ignore mplex buffer underruns since they apperently only occur at the very end of...
[vuplus_dvbapp] / lib / python / Plugins / Extensions / DVDBurn / Process.py
1 from Components.Task import Task, Job, job_manager, DiskspacePrecondition, Condition, ToolExistsPrecondition
2 from Screens.MessageBox import MessageBox
3
4 class png2yuvTask(Task):
5         def __init__(self, job, inputfile, outputfile):
6                 Task.__init__(self, job, "Creating menu video")
7                 self.setTool("/usr/bin/png2yuv")
8                 self.args += ["-n1", "-Ip", "-f25", "-j", inputfile]
9                 self.dumpFile = outputfile
10                 self.weighting = 10
11
12         def run(self, callback, task_progress_changed):
13                 Task.run(self, callback, task_progress_changed)
14                 self.container.stdoutAvail.get().remove(self.processStdout)
15                 self.container.dumpToFile(self.dumpFile)
16
17         def processStderr(self, data):
18                 print "[png2yuvTask]", data[:-1]
19
20 class mpeg2encTask(Task):
21         def __init__(self, job, inputfile, outputfile):
22                 Task.__init__(self, job, "Encoding menu video")
23                 self.setTool("/usr/bin/mpeg2enc")
24                 self.args += ["-f8", "-np", "-a2", "-o", outputfile]
25                 self.inputFile = inputfile
26                 self.weighting = 10
27                 
28         def run(self, callback, task_progress_changed):
29                 Task.run(self, callback, task_progress_changed)
30                 self.container.readFromFile(self.inputFile)
31
32         def processOutputLine(self, line):
33                 print "[mpeg2encTask]", line[:-1]
34
35 class spumuxTask(Task):
36         def __init__(self, job, xmlfile, inputfile, outputfile):
37                 Task.__init__(self, job, "Muxing buttons into menu")
38                 self.setTool("/usr/bin/spumux")
39                 self.args += [xmlfile]
40                 self.inputFile = inputfile
41                 self.dumpFile = outputfile
42                 self.weighting = 10
43
44         def run(self, callback, task_progress_changed):
45                 Task.run(self, callback, task_progress_changed)
46                 self.container.stdoutAvail.get().remove(self.processStdout)
47                 self.container.dumpToFile(self.dumpFile)
48                 self.container.readFromFile(self.inputFile)
49
50         def processStderr(self, data):
51                 print "[spumuxTask]", data[:-1]
52
53 class MakeFifoNode(Task):
54         def __init__(self, job, number):
55                 Task.__init__(self, job, "Make FIFO nodes")
56                 self.setTool("/bin/mknod")
57                 nodename = self.job.workspace + "/dvd_title_%d" % number + ".mpg"
58                 self.args += [nodename, "p"]
59                 self.weighting = 10
60
61 class LinkTS(Task):
62         def __init__(self, job, sourcefile, link_name):
63                 Task.__init__(self, job, "Creating symlink for source titles")
64                 self.setTool("/bin/ln")
65                 self.args += ["-s", sourcefile, link_name]
66                 self.weighting = 10
67
68 class DemuxTask(Task):
69         def __init__(self, job, inputfile):
70                 Task.__init__(self, job, "Demux video into ES")
71                 title = job.project.titles[job.i]
72                 self.global_preconditions.append(DiskspacePrecondition(title.estimatedDiskspace))
73                 self.setTool("/usr/bin/projectx")
74                 self.generated_files = [ ]
75                 self.end = 300
76                 self.prog_state = 0
77                 self.weighting = 1000
78                 self.cutfile = self.job.workspace + "/cut_%d.Xcl" % (job.i+1)
79                 self.cutlist = title.cutlist
80                 self.args += [inputfile, "-demux", "-out", self.job.workspace ]
81                 if len(self.cutlist) > 1:
82                         self.args += [ "-cut", self.cutfile ]
83
84         def prepare(self):
85                 self.writeCutfile()
86
87         def processOutputLine(self, line):
88                 line = line[:-1]
89                 MSG_NEW_FILE = "---> new File: "
90                 MSG_PROGRESS = "[PROGRESS] "
91
92                 if line.startswith(MSG_NEW_FILE):
93                         file = line[len(MSG_NEW_FILE):]
94                         if file[0] == "'":
95                                 file = file[1:-1]
96                         self.haveNewFile(file)
97                 elif line.startswith(MSG_PROGRESS):
98                         progress = line[len(MSG_PROGRESS):]
99                         self.haveProgress(progress)
100
101         def haveNewFile(self, file):
102                 print "PRODUCED FILE [%s]" % file
103                 self.generated_files.append(file)
104
105         def haveProgress(self, progress):
106                 #print "PROGRESS [%s]" % progress
107                 MSG_CHECK = "check & synchronize audio file"
108                 MSG_DONE = "done..."
109                 if progress == "preparing collection(s)...":
110                         self.prog_state = 0
111                 elif progress[:len(MSG_CHECK)] == MSG_CHECK:
112                         self.prog_state += 1
113                 else:
114                         try:
115                                 p = int(progress)
116                                 p = p - 1 + self.prog_state * 100
117                                 if p > self.progress:
118                                         self.progress = p
119                         except ValueError:
120                                 print "val error"
121                                 pass
122
123         def writeCutfile(self):
124                 f = open(self.cutfile, "w")
125                 f.write("CollectionPanel.CutMode=4\n")
126                 for p in self.cutlist:
127                         s = p / 90000
128                         m = s / 60
129                         h = m / 60
130
131                         m %= 60
132                         s %= 60
133
134                         f.write("%02d:%02d:%02d\n" % (h, m, s))
135                 f.close()
136
137         def cleanup(self, failed):
138                 if failed:
139                         import os
140                         for f in self.generated_files:
141                                 os.remove(f)
142
143 class MplexTaskPostcondition(Condition):
144         def check(self, task):
145                 if task.error == task.ERROR_UNDERRUN:
146                         return True
147                 return task.error is None
148
149         def getErrorMessage(self, task):
150                 print "[MplexTaskPostcondition] getErrorMessage", task
151                 return {
152                         task.ERROR_UNDERRUN: ("Can't multiplex source video!"),
153                         task.ERROR_UNKNOWN: ("An unknown error occured!")
154                 }[task.error]
155
156 class MplexTask(Task):
157         ERROR_UNDERRUN, ERROR_UNKNOWN = range(2)
158         def __init__(self, job, outputfile, inputfiles=None, demux_task=None):
159                 Task.__init__(self, job, "Mux ES into PS")
160                 self.weighting = 500
161                 self.demux_task = demux_task
162                 self.postconditions.append(MplexTaskPostcondition())
163                 self.setTool("/usr/bin/mplex")
164                 self.args += ["-f8", "-o", outputfile, "-v1"]
165                 if inputfiles:
166                         self.args += inputfiles
167
168         def setTool(self, tool):
169                 self.cmd = tool
170                 self.args = [tool]
171                 self.global_preconditions.append(ToolExistsPrecondition())
172                 # we don't want the ReturncodePostcondition in this case because for right now we're just gonna ignore the fact that mplex fails with a buffer underrun error on some streams (this always at the very end)
173
174         def prepare(self):
175                 self.error = None                       
176                 if self.demux_task:
177                         self.args += self.demux_task.generated_files
178
179         def processOutputLine(self, line):
180                 print "[MplexTask] processOutputLine=", line[:-1]
181                 if line.startswith("**ERROR:"):
182                         if line.find("Frame data under-runs detected") != -1:
183                                 self.error = self.ERROR_UNDERRUN
184                         else:
185                                 self.error = self.ERROR_UNKNOWN
186
187 class RemoveESFiles(Task):
188         def __init__(self, job, demux_task):
189                 Task.__init__(self, job, "Remove temp. files")
190                 self.demux_task = demux_task
191                 self.setTool("/bin/rm")
192
193         def prepare(self):
194                 self.args += ["-f"]
195                 self.args += self.demux_task.generated_files
196                 self.args += [self.demux_task.cutfile]
197
198 class DVDAuthorTask(Task):
199         def __init__(self, job, diskspaceNeeded):
200                 Task.__init__(self, job, "Authoring DVD")
201
202                 self.global_preconditions.append(DiskspacePrecondition(diskspaceNeeded))
203                 self.weighting = 300
204                 self.setTool("/usr/bin/dvdauthor")
205                 self.CWD = self.job.workspace
206                 self.args += ["-x", self.job.workspace+"/dvdauthor.xml"]
207                 self.menupreview = job.menupreview
208
209         def processOutputLine(self, line):
210                 print "[DVDAuthorTask] processOutputLine=", line[:-1]
211                 if not self.menupreview and line.startswith("STAT: Processing"):
212                         self.callback(self, [], stay_resident=True)
213
214 class DVDAuthorFinalTask(Task):
215         def __init__(self, job):
216                 Task.__init__(self, job, "dvdauthor finalize")
217                 self.setTool("/usr/bin/dvdauthor")
218                 self.args += ["-T", "-o", self.job.workspace + "/dvd"]
219
220 class WaitForResidentTasks(Task):
221         def __init__(self, job):
222                 Task.__init__(self, job, "waiting for dvdauthor to finalize")
223                 
224         def run(self, callback, task_progress_changed):
225                 print "waiting for %d resident task(s) %s to finish..." % (len(self.job.resident_tasks),str(self.job.resident_tasks))
226                 if self.job.resident_tasks == 0:
227                         callback(self, [])
228
229 class BurnTaskPostcondition(Condition):
230         RECOVERABLE = True
231         def check(self, task):
232                 return task.error is None
233
234         def getErrorMessage(self, task):
235                 return {
236                         task.ERROR_MEDIA: _("Medium is not a writeable DVD!"),
237                         task.ERROR_SIZE: _("Content does not fit on DVD!"),
238                         task.ERROR_WRITE_FAILED: _("Write failed!"),
239                         task.ERROR_DVDROM: _("No (supported) DVDROM found!"),
240                         task.ERROR_ISOFS: _("Medium is not empty!"),
241                         task.ERROR_UNKNOWN: _("An unknown error occured!")
242                 }[task.error]
243
244 class BurnTask(Task):
245         ERROR_MEDIA, ERROR_SIZE, ERROR_WRITE_FAILED, ERROR_DVDROM, ERROR_ISOFS, ERROR_UNKNOWN = range(6)
246         def __init__(self, job):
247                 Task.__init__(self, job, "burn")
248
249                 self.weighting = 500
250                 self.end = 120 # 100 for writing, 10 for buffer flush, 10 for closing disc
251                 self.postconditions.append(BurnTaskPostcondition())
252                 self.setTool("/bin/growisofs")
253                 volName = self.getASCIIname(job.project.settings.name.getValue())
254                 self.args += ["-dvd-video", "-dvd-compat", "-Z", "/dev/cdroms/cdrom0", "-V", volName, "-P", "Dreambox", "-use-the-force-luke=dummy", self.job.workspace + "/dvd"]
255
256         def getASCIIname(self, name):
257                 ASCIIname = ""
258                 for char in name.decode("utf-8").encode("ascii","replace"):
259                         if ord(char) <= 0x20 or ( ord(char) >= 0x3a and ord(char) <= 0x40 ):
260                                 ASCIIname += '_'
261                         else:
262                                 ASCIIname += char
263                 return ASCIIname
264                 
265         def prepare(self):
266                 self.error = None
267
268         def processOutputLine(self, line):
269                 line = line[:-1]
270                 print "[GROWISOFS] %s" % line
271                 if line[8:14] == "done, ":
272                         self.progress = float(line[:6])
273                         print "progress:", self.progress
274                 elif line.find("flushing cache") != -1:
275                         self.progress = 100
276                 elif line.find("closing disc") != -1:
277                         self.progress = 110
278                 elif line.startswith(":-["):
279                         if line.find("ASC=30h") != -1:
280                                 self.error = self.ERROR_MEDIA
281                         else:
282                                 self.error = self.ERROR_UNKNOWN
283                                 print "BurnTask: unknown error %s" % line
284                 elif line.startswith(":-("):
285                         if line.find("No space left on device") != -1:
286                                 self.error = self.ERROR_SIZE
287                         elif line.find("write failed") != -1:
288                                 self.error = self.ERROR_WRITE_FAILED
289                         elif line.find("unable to open64(\"/dev/cdroms/cdrom0\",O_RDONLY): No such file or directory") != -1: # fixme
290                                 self.error = self.ERROR_DVDROM
291                         elif line.find("media is not recognized as recordable DVD") != -1:
292                                 self.error = self.ERROR_MEDIA
293                         else:
294                                 self.error = self.ERROR_UNKNOWN
295                                 print "BurnTask: unknown error %s" % line
296                 elif line.startswith("FATAL:"):
297                         if line.find("already carries isofs!"):
298                                 self.error = self.ERROR_ISOFS
299                         else:
300                                 self.error = self.ERROR_UNKNOWN
301                                 print "BurnTask: unknown error %s" % line
302
303 class RemoveDVDFolder(Task):
304         def __init__(self, job):
305                 Task.__init__(self, job, "Remove temp. files")
306                 self.setTool("/bin/rm")
307                 self.args += ["-rf", self.job.workspace]
308
309 class PreviewTask(Task):
310         def __init__(self, job):
311                 Task.__init__(self, job, "Preview")
312                 self.postconditions.append(PreviewTaskPostcondition())
313                 self.job = job
314
315         def run(self, callback, task_progress_changed):
316                 self.callback = callback
317                 self.task_progress_changed = task_progress_changed
318                 if self.job.project.waitboxref:
319                         self.job.project.waitboxref.close()
320                 if self.job.menupreview:
321                         self.waitAndOpenPlayer()
322                 else:
323                         self.job.project.session.openWithCallback(self.previewCB, MessageBox, _("Do you want to preview this DVD before burning?"), timeout = 60, default = False)
324         
325         def previewCB(self, answer):
326                 if answer == True:
327                         self.waitAndOpenPlayer()
328                 else:
329                         self.closedCB(True)
330
331         def playerClosed(self):
332                 if self.job.menupreview:
333                         self.closedCB(True)
334                 else:
335                         self.job.project.session.openWithCallback(self.closedCB, MessageBox, _("Do you want to burn this collection to DVD medium?") )
336
337         def closedCB(self, answer):
338                 if answer == True:
339                         Task.processFinished(self, 0)
340                 else:
341                         Task.processFinished(self, 1)
342
343         def waitAndOpenPlayer(self):
344                 from enigma import eTimer
345                 self.delayTimer = eTimer()
346                 self.delayTimer.callback.append(self.previewProject)
347                 self.delayTimer.start(10,1)
348                 
349         def previewProject(self):
350                 from Plugins.Extensions.DVDPlayer.plugin import DVDPlayer
351                 self.job.project.session.openWithCallback(self.playerClosed, DVDPlayer, dvd_filelist= [ self.job.project.workspace + "/dvd/VIDEO_TS/" ])
352
353 class PreviewTaskPostcondition(Condition):
354         def check(self, task):
355                 return task.returncode == 0
356
357         def getErrorMessage(self, task):
358                 return "Cancel"
359
360 def getTitlesPerMenu(nr_titles):
361         if nr_titles < 6:
362                 titles_per_menu = 5
363         else:
364                 titles_per_menu = 4
365         return titles_per_menu
366
367 def formatTitle(template, title, track):
368         template = template.replace("$i", str(track))
369         template = template.replace("$t", title.name)
370         template = template.replace("$d", title.descr)
371         template = template.replace("$c", str(len(title.chaptermarks)+1))
372         template = template.replace("$A", str(title.audiotracks))
373         template = template.replace("$f", title.inputfile)
374         template = template.replace("$C", title.channel)
375         l = title.length
376         lengthstring = "%d:%02d:%02d" % (l/3600, l%3600/60, l%60)
377         template = template.replace("$l", lengthstring)
378         if title.timeCreate:
379                 template = template.replace("$Y", str(title.timeCreate[0]))
380                 template = template.replace("$M", str(title.timeCreate[1]))
381                 template = template.replace("$D", str(title.timeCreate[2]))
382                 timestring = "%d:%02d" % (title.timeCreate[3], title.timeCreate[4])
383                 template = template.replace("$T", timestring)
384         else:
385                 template = template.replace("$Y", "").replace("$M", "").replace("$D", "").replace("$T", "")
386         return template.decode("utf-8")
387
388 def CreateMenus(job):
389         import os, Image, ImageDraw, ImageFont
390         imgwidth = 720
391         imgheight = 576
392         s = job.project.settings
393         im_bg_orig = Image.open(s.menubg.getValue())
394         if im_bg_orig.size != (imgwidth, imgheight):
395                 im_bg_orig = im_bg_orig.resize((720, 576))
396         
397         fontsizes = s.font_size.getValue()
398         fontface = s.font_face.getValue()
399         
400         font0 = ImageFont.truetype(fontface, fontsizes[0])
401         font1 = ImageFont.truetype(fontface, fontsizes[1])
402         font2 = ImageFont.truetype(fontface, fontsizes[2])
403
404         color_headline = tuple(s.color_headline.getValue())
405         color_button = tuple(s.color_button.getValue())
406         color_highlight = tuple(s.color_highlight.getValue())
407         spu_palette = [ 0x60, 0x60, 0x60 ] + s.color_highlight.getValue()
408
409         nr_titles = len(job.project.titles)
410         titles_per_menu = getTitlesPerMenu(nr_titles)
411         job.nr_menus = ((nr_titles+titles_per_menu-1)/titles_per_menu)
412
413         #a new menu_count every 5 titles (1,2,3,4,5->1 ; 6,7,8,9,10->2 etc.)
414         for menu_count in range(1 , job.nr_menus+1):
415                 im_bg = im_bg_orig.copy()
416                 im_high = Image.new("P", (imgwidth, imgheight), 0)
417                 im_high.putpalette(spu_palette)
418                 draw_bg = ImageDraw.Draw(im_bg)
419                 draw_high = ImageDraw.Draw(im_high)
420
421                 if menu_count == 1:
422                         headline = s.name.getValue().decode("utf-8")
423                         textsize = draw_bg.textsize(headline, font=font0)
424                         if textsize[0] > imgwidth:
425                                 offset = (0 , 20)
426                         else:
427                                 offset = (((imgwidth-textsize[0]) / 2) , 20)
428                         draw_bg.text(offset, headline, fill=color_headline, font=font0)
429                 
430                 menubgpngfilename = job.workspace+"/dvd_menubg"+str(menu_count)+".png"
431                 highlightpngfilename = job.workspace+"/dvd_highlight"+str(menu_count)+".png"
432                 spuxml = """<?xml version="1.0" encoding="utf-8"?>
433         <subpictures>
434         <stream>
435         <spu 
436         highlight="%s"
437         transparent="%02x%02x%02x"
438         start="00:00:00.00"
439         force="yes" >""" % (highlightpngfilename, spu_palette[0], spu_palette[1], spu_palette[2])
440                 s_top, s_rows, s_left = s.space.getValue()
441                 rowheight = (fontsizes[1]+fontsizes[2]+s_rows)
442                 menu_start_title = (menu_count-1)*titles_per_menu + 1
443                 menu_end_title = (menu_count)*titles_per_menu + 1
444                 if menu_end_title > nr_titles:
445                         menu_end_title = nr_titles+1
446                 menu_i = 0
447                 for title_no in range( menu_start_title , menu_end_title ):
448                         i = title_no-1
449                         top = s_top + ( menu_i * rowheight )
450                         menu_i += 1
451                         title = job.project.titles[i]
452                         titleText = formatTitle(s.titleformat.getValue(), title, title_no)
453                         draw_bg.text((s_left,top), titleText, fill=color_button, font=font1)
454                         draw_high.text((s_left,top), titleText, fill=1, font=font1)
455                         subtitleText = formatTitle(s.subtitleformat.getValue(), title, title_no)
456                         draw_bg.text((s_left,top+36), subtitleText, fill=color_button, font=font2)
457                         bottom = top+rowheight
458                         if bottom > imgheight:
459                                 bottom = imgheight
460                         spuxml += """
461         <button name="button%s" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (str(title_no).zfill(2),s_left,imgwidth,top,bottom )
462                 if menu_count > 1:
463                         prev_page_text = "<<<"
464                         textsize = draw_bg.textsize(prev_page_text, font=font1)
465                         offset = ( 2*s_left, s_top + ( titles_per_menu * rowheight ) )
466                         draw_bg.text(offset, prev_page_text, fill=color_button, font=font1)
467                         draw_high.text(offset, prev_page_text, fill=1, font=font1)
468                         spuxml += """
469         <button name="button_prev" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (offset[0],offset[0]+textsize[0],offset[1],offset[1]+textsize[1])
470
471                 if menu_count < job.nr_menus:
472                         next_page_text = ">>>"
473                         textsize = draw_bg.textsize(next_page_text, font=font1)
474                         offset = ( imgwidth-textsize[0]-2*s_left, s_top + ( titles_per_menu * rowheight ) )
475                         draw_bg.text(offset, next_page_text, fill=color_button, font=font1)
476                         draw_high.text(offset, next_page_text, fill=1, font=font1)
477                         spuxml += """
478         <button name="button_next" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (offset[0],offset[0]+textsize[0],offset[1],offset[1]+textsize[1])
479                                 
480                 del draw_bg
481                 del draw_high
482                 fd=open(menubgpngfilename,"w")
483                 im_bg.save(fd,"PNG")
484                 fd.close()
485                 fd=open(highlightpngfilename,"w")
486                 im_high.save(fd,"PNG")
487                 fd.close()
488         
489                 png2yuvTask(job, menubgpngfilename, job.workspace+"/dvdmenubg"+str(menu_count)+".yuv")
490                 menubgm2vfilename = job.workspace+"/dvdmenubg"+str(menu_count)+".mv2"
491                 mpeg2encTask(job, job.workspace+"/dvdmenubg"+str(menu_count)+".yuv", menubgm2vfilename)
492                 menubgmpgfilename = job.workspace+"/dvdmenubg"+str(menu_count)+".mpg"
493                 menuaudiofilename = s.menuaudio.getValue()
494                 MplexTask(job, outputfile=menubgmpgfilename, inputfiles = [menubgm2vfilename, menuaudiofilename])
495         
496                 spuxml += """
497         </spu>
498         </stream>
499         </subpictures>"""
500                 spuxmlfilename = job.workspace+"/spumux"+str(menu_count)+".xml"
501                 f = open(spuxmlfilename, "w")
502                 f.write(spuxml)
503                 f.close()
504                 
505                 menuoutputfilename = job.workspace+"/dvdmenu"+str(menu_count)+".mpg"
506                 spumuxTask(job, spuxmlfilename, menubgmpgfilename, menuoutputfilename)
507                 
508 def CreateAuthoringXML(job):
509         nr_titles = len(job.project.titles)
510         titles_per_menu = getTitlesPerMenu(nr_titles)
511         mode = job.project.settings.authormode.getValue()
512         authorxml = []
513         authorxml.append('<?xml version="1.0" encoding="utf-8"?>\n')
514         authorxml.append(' <dvdauthor dest="' + (job.workspace+"/dvd") + '">\n')
515         authorxml.append('  <vmgm>\n')
516         authorxml.append('   <menus>\n')
517         authorxml.append('    <pgc>\n')
518         authorxml.append('     <vob file="' + job.project.settings.vmgm.getValue() + '" />\n', )
519         if mode.startswith("menu"):
520                 authorxml.append('     <post> jump titleset 1 menu; </post>\n')
521         else:
522                 authorxml.append('     <post> jump title 1; </post>\n')
523         authorxml.append('    </pgc>\n')
524         authorxml.append('   </menus>\n')
525         authorxml.append('  </vmgm>\n')
526         authorxml.append('  <titleset>\n')
527         if mode.startswith("menu"):
528                 authorxml.append('   <menus>\n')
529                 authorxml.append('    <video aspect="4:3"/>\n')
530                 for menu_count in range(1 , job.nr_menus+1):
531                         if menu_count == 1:
532                                 authorxml.append('    <pgc entry="root">\n')
533                         else:
534                                 authorxml.append('    <pgc>\n')
535                         menu_start_title = (menu_count-1)*titles_per_menu + 1
536                         menu_end_title = (menu_count)*titles_per_menu + 1
537                         if menu_end_title > nr_titles:
538                                 menu_end_title = nr_titles+1
539                         for i in range( menu_start_title , menu_end_title ):
540                                 authorxml.append('     <button name="button' + (str(i).zfill(2)) + '"> jump title ' + str(i) +'; </button>\n')
541                         if menu_count > 1:
542                                 authorxml.append('     <button name="button_prev"> jump menu ' + str(menu_count-1) + '; </button>\n')
543                         if menu_count < job.nr_menus:
544                                 authorxml.append('     <button name="button_next"> jump menu ' + str(menu_count+1) + '; </button>\n')
545                         menuoutputfilename = job.workspace+"/dvdmenu"+str(menu_count)+".mpg"
546                         authorxml.append('     <vob file="' + menuoutputfilename + '" pause="inf"/>\n')
547                         authorxml.append('    </pgc>\n')
548                 authorxml.append('   </menus>\n')
549         authorxml.append('   <titles>\n')
550         for i in range( nr_titles ):
551                 for audiotrack in job.project.titles[i].audiotracks:
552                         authorxml.append('    <audio lang="'+audiotrack[0][:2]+'" format="'+audiotrack[1]+'" />\n')
553                 chapters = ','.join(["%d:%02d:%02d.%03d" % (p / (90000 * 3600), p % (90000 * 3600) / (90000 * 60), p % (90000 * 60) / 90000, (p % 90000) / 90) for p in job.project.titles[i].chaptermarks])
554                 title_no = i+1
555                 title_filename = job.workspace + "/dvd_title_%d.mpg" % (title_no)
556                 if job.menupreview:
557                         LinkTS(job, job.project.settings.vmgm.getValue(), title_filename)
558                 else:
559                         MakeFifoNode(job, title_no)
560                 if mode.endswith("linked") and title_no < nr_titles:
561                         post_tag = "jump title %d;" % ( title_no+1 )
562                 elif mode.startswith("menu"):
563                         post_tag = "call vmgm menu 1;"
564                 else:   post_tag = ""
565
566                 authorxml.append('    <pgc>\n')
567                 authorxml.append('     <vob file="' + title_filename + '" chapters="' + chapters + '" />\n')
568                 authorxml.append('     <post> ' + post_tag + ' </post>\n')
569                 authorxml.append('    </pgc>\n')
570
571         authorxml.append('   </titles>\n')
572         authorxml.append('  </titleset>\n')
573         authorxml.append(' </dvdauthor>\n')
574         f = open(job.workspace+"/dvdauthor.xml", "w")
575         for x in authorxml:
576                 f.write(x)
577         f.close()
578
579 class DVDJob(Job):
580         def __init__(self, project, menupreview=False):
581                 Job.__init__(self, "DVD Burn")
582                 self.project = project
583                 from time import strftime
584                 from Tools.Directories import SCOPE_HDD, resolveFilename, createDir
585                 new_workspace = resolveFilename(SCOPE_HDD) + "tmp/" + strftime("%Y%m%d%H%M%S")
586                 createDir(new_workspace, True)
587                 self.workspace = new_workspace
588                 self.project.workspace = self.workspace
589                 self.menupreview = menupreview
590                 self.conduct()
591
592         def conduct(self):
593                 if self.project.settings.authormode.getValue().startswith("menu") or self.menupreview:
594                         CreateMenus(self)
595                 CreateAuthoringXML(self)
596
597                 totalsize = 50*1024*1024 # require an extra safety 50 MB
598                 maxsize = 0
599                 for title in self.project.titles:
600                         titlesize = title.estimatedDiskspace
601                         if titlesize > maxsize: maxsize = titlesize
602                         totalsize += titlesize
603                 diskSpaceNeeded = totalsize + maxsize
604
605                 DVDAuthorTask(self, diskSpaceNeeded)
606                 
607                 nr_titles = len(self.project.titles)
608                 
609                 if self.menupreview:
610                         PreviewTask(self)
611                 else:
612                         for self.i in range(nr_titles):
613                                 title = self.project.titles[self.i]
614                                 link_name =  self.workspace + "/source_title_%d.ts" % (self.i+1)
615                                 title_filename = self.workspace + "/dvd_title_%d.mpg" % (self.i+1)
616                                 LinkTS(self, title.inputfile, link_name)
617                                 demux = DemuxTask(self, link_name)
618                                 MplexTask(self, outputfile=title_filename, demux_task=demux)
619                                 RemoveESFiles(self, demux)
620                         WaitForResidentTasks(self)
621                         PreviewTask(self)
622                         BurnTask(self)
623                 RemoveDVDFolder(self)
624
625 def Burn(session, project):
626         j = DVDJob(project)
627         job_manager.AddJob(j)
628         return j
629
630 def PreviewMenu(session, project):
631         j = DVDJob(project, menupreview=True)
632         job_manager.AddJob(j)
633         return j