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