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