3 # subconv v0.2.2 -- divx subtitles converter
4 # (w)by Pawel Stolowski
7 # Released under terms of GNU GPL
9 # mpl2 (w) by Grzegorz Zyla
11 import re, sys, getopt, string
15 subconv v0.2.2 -- DivX subtitles converter
16 (w)by Pawel Stolowski <yogin@linux.bydg.org>
17 Julien Lerouge <julien.lerouge@free.fr>
19 Usage: subconv [-i fmt|-o fmt|-a sec|-s sec|-S h:m:s[,h:m:s,...]] input [output1, output2, ...]
21 -i fmt input format (one of: srt, tmp, mdvd, sub2, mpl2, auto; auto by default)
22 -o fmt output format (one of: tmp, srt; srt by default)
23 -f fps adjust fps rate for microdvd input subtitles (auto by default)
24 -a sec adjust subtitle delay in seconds (add)
25 -s sec adjust subtitle delay in seconds (sub)
26 -S h:m:s,... split subtitles in selected position(s); additional output file names must be specified
35 Detect the FPS for a given input file
36 input: contents of a file as list
39 sys.stderr.write("FPS guessing, here are approximate length of file for several FPS :\n")
40 most_current=[23.976,25.0,29.97]
42 re_mdvd = re.compile("^[\{\[](\d+)[\}\]][\{\[](\d*)[\}\]]\s*(.*)")
44 m = re_mdvd.match(list[count])
47 m = re_mdvd.match(list[count])
48 last = int(m.group(2))
50 for i in range(0,len(most_current)):
51 sys.stderr.write(str(i)+" "+str(most_current[i])+" Fps -> ")
52 tot_sec = int(last / most_current[i])
55 sys.stderr.write(str(min)+" min "+str(sec)+"sec\n")
56 sys.stderr.write("Choice : ")
57 choice=int(sys.stdin.readline().strip())
58 if choice>=0 and choice<len(most_current):
59 return most_current[choice]
61 sys.stderr.write("Bad choice\n")
65 def detect_format(list):
67 Detect the format of input subtitles file.
68 input: contents of a file as list
69 returns: format (srt, tmp, mdvd) or "" if unknown
71 sys.stderr.write("Guessing subs format .")
72 re_mdvd = re.compile("^[\{\[](\d+)[\}\]][\{\[](\d*)[\}\]]\s*(.*)")
73 re_srt = re.compile("^(\d+):(\d+):(\d+),\d+\s*-->.*")
74 re_tmp = re.compile("^(\d+):(\d+):(\d+):(.*)")
75 re_sub2 = re.compile("^(\d+):(\d+):(\d+)\.\d+\s*\,.*")
76 re_mpl2 = re.compile("^\[(\d+)\]\[(\d+)\]\s*(.*)")
80 if re_mdvd.match(line):
81 sys.stderr.write(" mdvd\n")
83 elif re_srt.match(line):
84 sys.stderr.write(" srt\n")
86 elif re_tmp.match(line):
87 sys.stderr.write(" tmp\n")
89 elif re_sub2.match(line):
90 sys.stderr.write(" subviewer 2 format\n")
92 elif re_mpl2.match(line):
93 sys.stderr.write(" mpl2\n")
98 def read_mdvd(list, fps):
100 Read micro-dvd subtitles.
101 input: contents of a file as list
102 returns: list of subtitles in form: [[time_start in secs, time_end in secs, line1, ...],....]
104 re1 = re.compile("^[\{\[](\d+)[\}\]][\{\[](\d*)[\}\]]\s*(.*)")
111 time1 = int(m.group(1))
112 subt = [int(time1) / float(fps)]
115 time2 = int(time1) + 20
116 subt.append(int(time2) / float(fps))
117 texts = m.group(3).strip().split("|")
118 for i in range(len(texts)):
120 if text.lower().startswith('{c:') or text.lower().startswith('{y:'):
121 end_marker = text.index('}')
123 text = text[end_marker + 1:]
126 subtitles.append(subt)
132 input: contents of a file as list
133 returns: list of subtitles in form: [[time_start in secs, time_end is secs, line1, ...],.....]
135 re1 = re.compile("^\[(\d+)\]\[(\d+)\]\s*(.*)")
138 m = re1.match(list.pop(0),0);
140 subt = [int(m.group(1))*0.1]
141 subt.append(int(m.group(2))*0.1)
142 subt.extend(m.group(3).strip().split("|"))
143 subtitles.append(subt)
148 Reads subviewer 2.0 format subtitles, e.g. :
149 00:01:54.75,00:01:58.54
151 input: contents of a file as list
152 returns: list of subtitles in form: [[time_dep, time_end, line1, ...],[time_dep, time_end, line1, ...],....]
154 re1 = re.compile("^(\d+):(\d+):(\d+)\.(\d+)\s*\,\s*(\d+):(\d+):(\d+)\.(\d+).*$")
158 m = re1.match(list.pop(0), 0)
160 subt = [int(m.group(1))*3600 + int(m.group(2))*60 + int(m.group(3)) + int(m.group(4))/100.0]
161 subt.append(int(m.group(5))*3600 + int(m.group(6))*60 + int(m.group(7)) + int(m.group(8))/100.0)
162 l = list.pop(0).strip()
163 lines = l.split("[br]")
164 for i in range(0,len(lines)):
165 subt.append(lines[i])
166 subtitles.append(subt)
168 sys.stderr.write("Warning: it seems like input file is damaged or too short.\n")
174 input: contents of a file as list
175 returns: list of subtitles in form: [[time_dep, time_end, line1, ...],[time_dep, time_end, line1, ...],....]
177 re1 = re.compile("^(\d+)\s*$")
178 re2 = re.compile("^(\d+):(\d+):(\d+),(\d+)\s*-->\s*(\d+):(\d+):(\d+),(\d+).*$")
179 re3 = re.compile("^\s*$")
183 if re1.match(list.pop(0), 0):
184 m = re2.match(list.pop(0), 0)
186 subt = [int(m.group(1))*3600 + int(m.group(2))*60 + int(m.group(3)) + int(m.group(4))/1000.0]
187 subt.append(int(m.group(5))*3600 + int(m.group(6))*60 + int(m.group(7)) + int(m.group(8))/1000.0)
189 while not re3.match(l, 0):
190 #subt.append(string.replace(l[:-1], "\r", ""))
191 subt.append(l.strip())
193 subtitles.append(subt)
195 sys.stderr.write("Warning: it seems like input file is damaged or too short.\n")
200 Reads tmplayer (tmp) subtitles.
201 input: contents of a file as list
202 returns: list of subtitles in form: [[time_dep, time_end, line1, ...],[time_dep, time_end, line1, ...],....]
204 re1 = re.compile("^(\d+):(\d+):(\d+):(.*)")
208 m = re1.match(list.pop(0), 0)
210 time = int(m.group(1))*3600 + int(m.group(2))*60 + int(m.group(3))
211 if subs.has_key(time) :
212 subs[time].extend(m.group(4).strip().split("|"))
214 subs[time] = m.group(4).strip().split("|")
218 for i in range(0,len(times)):
220 while not subs.has_key(times[i]+next_time) and next_time < 4 :
221 next_time = next_time + 1
222 subt = [ times[i] , times[i] + next_time]
223 subt.extend(subs[times[i]])
224 subtitles.append(subt)
229 Converts list of subtitles (internal format) to tmp format
235 m = int(int(secs%3600)/60)
237 outl.append("%.2d:%.2d:%.2d:%s\n" % (h,m,s,"|".join(l[2:])))
243 Converts list of subtitles (internal format) to srt format
250 m1 = int(int(secs1%3600)/60)
252 f1 = (secs1 - int(secs1))*1000
255 m2 = int(int(secs2%3600)/60)
257 f2 = (secs2 - int(secs2))*1000
258 outl.append("%d\n%.2d:%.2d:%.2d,%.3d --> %.2d:%.2d:%.2d,%.3d\n%s\n\n" % (count,h1,m1,s1,f1,h2,m2,s2,f2,"\n".join(l[2:])))
263 def sub_add_offset(list, off):
265 Adds an offset (in seconds, may be negative) to all subtitles in the list
266 input: subtitles (internal format)
267 returns: new subtitles (internal format)
274 sys.stderr.write("Warning, negative offset too high, subs beginning at 00:00:00\n")
277 sys.stderr.write("Warning, negative offset too high, subs beginning at 00:00:00\n")
282 def sub_split(sub, times):
285 input: subtitles (internal format) and split positions (in seconds)
286 returns: a list of lists with new subtitles
291 while pos<num and sub[pos][0]<times[0]:
294 lists = [ sub[:pos] ] # [subtitles1, subtitles2, ...]
296 times.append(99999999)
297 minussec = times.pop(0)
301 while pos<num and sub[pos][0]<second:
302 subline = [sub[pos][0]-minussec] + [sub[pos][1]-minussec] + sub[pos][2:]
313 def get_split_times(str):
315 Converts comma-separated string of "xx:yy:zz,xx:yy:zz,..." times to list of times (in seconds)
316 input: string of comma-separated xx:yy:zz time positions
317 returns: list of times
319 tlist = str.split(",")
320 re1 = re.compile("^(\d+):(\d+):(\d+)")
325 sys.stderr.write("Unknown time format\n")
327 times.append(int(m.group(1))*3600 + int(m.group(2))*60 + int(m.group(3)))
331 def read_subs(file,fmt,fps):
333 Reads subtitles fomr file, using format fmt
334 input : file name, format (srt,mdvd,tmp,auto)
335 returns: list of subtitles in form: [[time in secs, line1, ...],[time in secs, line1, ...],....]
338 subs = src.readlines()
341 return read_tmp(subs)
343 return read_srt(subs)
346 fps = detect_fps(subs)
347 return read_mdvd(subs, fps)
349 return read_subs(file,detect_format(subs),fps)
351 return read_sub2(subs)
353 return read_mpl2(subs)
355 sys.stderr.write("Input format not specified/recognized\n")
360 #-----------------------------------------------------------------------------------------
371 #out_to_file == 1 => output to a file, 0 => output stdout, -1 => Split, output to stdout not allowed
375 opts, args = getopt.getopt(sys.argv[1:], 'i:o:a:s:S:f:h')
376 except getopt.GetoptError:
382 for opt, arg in opts:
384 if outfunc.has_key(arg):
387 sys.stderr.write("Unknown output format.\n")
392 subdelay = float(arg)
394 subdelay = -float(arg)
397 splittimes = get_split_times(arg)
405 # number of file names must be 2 + number of split-points
406 if len(args) == len(splittimes)+2:
408 elif len(args) == len(splittimes)+1 and out_to_file != -1:
411 sys.stderr.write("Too few file names given!\n")
417 sub = read_subs(args.pop(0),infmt,fps)
422 sub = sub_add_offset(sub, subdelay)
426 if len(splittimes) == 0:
429 sub_list = sub_split(sub, splittimes)
433 for nsub in sub_list:
434 s = outfunc[outfmt](nsub)
436 dst = open(args.pop(0), 'w')
440 sys.stdout.writelines(s)