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