CreateMenu is now a task of its own
[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_NOTWRITEABLE: _("Medium is not a writeable DVD!"),
250                         task.ERROR_LOAD: _("Could not load Medium! No disc inserted?"),
251                         task.ERROR_SIZE: _("Content does not fit on DVD!"),
252                         task.ERROR_WRITE_FAILED: _("Write failed!"),
253                         task.ERROR_DVDROM: _("No (supported) DVDROM found!"),
254                         task.ERROR_ISOFS: _("Medium is not empty!"),
255                         task.ERROR_UNKNOWN: _("An unknown error occured!")
256                 }[task.error]
257
258 class BurnTask(Task):
259         ERROR_NOTWRITEABLE, ERROR_LOAD, ERROR_SIZE, ERROR_WRITE_FAILED, ERROR_DVDROM, ERROR_ISOFS, ERROR_UNKNOWN = range(7)
260         def __init__(self, job, extra_args=[]):
261                 Task.__init__(self, job, "burn")
262
263                 self.weighting = 500
264                 self.end = 120 # 100 for writing, 10 for buffer flush, 10 for closing disc
265                 self.postconditions.append(BurnTaskPostcondition())
266                 self.setTool("/bin/growisofs")
267                 volName = self.getASCIIname(job.project.settings.name.getValue())
268                 self.args += ["-dvd-compat", "-Z", "/dev/cdroms/cdrom0", "-V", volName, "-P", "Dreambox", "-use-the-force-luke=dummy", self.job.workspace + "/dvd"]
269                 self.args += extra_args
270
271         def getASCIIname(self, name):
272                 ASCIIname = ""
273                 for char in name.decode("utf-8").encode("ascii","replace"):
274                         if ord(char) <= 0x20 or ( ord(char) >= 0x3a and ord(char) <= 0x40 ):
275                                 ASCIIname += '_'
276                         else:
277                                 ASCIIname += char
278                 return ASCIIname
279                 
280         def prepare(self):
281                 self.error = None
282
283         def processOutputLine(self, line):
284                 line = line[:-1]
285                 print "[GROWISOFS] %s" % line
286                 if line[8:14] == "done, ":
287                         self.progress = float(line[:6])
288                         print "progress:", self.progress
289                 elif line.find("flushing cache") != -1:
290                         self.progress = 100
291                 elif line.find("closing disc") != -1:
292                         self.progress = 110
293                 elif line.startswith(":-["):
294                         if line.find("ASC=30h") != -1:
295                                 self.error = self.ERROR_NOTWRITEABLE
296                         if line.find("ASC=24h") != -1:
297                                 self.error = self.ERROR_LOAD
298                         else:
299                                 self.error = self.ERROR_UNKNOWN
300                                 print "BurnTask: unknown error %s" % line
301                 elif line.startswith(":-("):
302                         if line.find("No space left on device") != -1:
303                                 self.error = self.ERROR_SIZE
304                         elif line.find("write failed") != -1:
305                                 self.error = self.ERROR_WRITE_FAILED
306                         elif line.find("unable to open64(\"/dev/cdroms/cdrom0\",O_RDONLY): No such file or directory") != -1: # fixme
307                                 self.error = self.ERROR_DVDROM
308                         elif line.find("media is not recognized as recordable DVD") != -1:
309                                 self.error = self.ERROR_NOTWRITEABLE
310                         else:
311                                 self.error = self.ERROR_UNKNOWN
312                                 print "BurnTask: unknown error %s" % line
313                 elif line.startswith("FATAL:"):
314                         if line.find("already carries isofs!"):
315                                 self.error = self.ERROR_ISOFS
316                         else:
317                                 self.error = self.ERROR_UNKNOWN
318                                 print "BurnTask: unknown error %s" % line
319
320 class RemoveDVDFolder(Task):
321         def __init__(self, job):
322                 Task.__init__(self, job, "Remove temp. files")
323                 self.setTool("/bin/rm")
324                 self.args += ["-rf", self.job.workspace]
325
326 class PreviewTask(Task):
327         def __init__(self, job):
328                 Task.__init__(self, job, "Preview")
329                 self.postconditions.append(PreviewTaskPostcondition())
330                 self.job = job
331
332         def run(self, callback, task_progress_changed):
333                 self.callback = callback
334                 self.task_progress_changed = task_progress_changed
335                 if self.job.menupreview:
336                         self.waitAndOpenPlayer()
337                 else:
338                         self.job.project.session.openWithCallback(self.previewCB, MessageBox, _("Do you want to preview this DVD before burning?"), timeout = 60, default = False)
339         
340         def previewCB(self, answer):
341                 if answer == True:
342                         self.waitAndOpenPlayer()
343                 else:
344                         self.closedCB(True)
345
346         def playerClosed(self):
347                 if self.job.menupreview:
348                         self.closedCB(True)
349                 else:
350                         self.job.project.session.openWithCallback(self.closedCB, MessageBox, _("Do you want to burn this collection to DVD medium?") )
351
352         def closedCB(self, answer):
353                 if answer == True:
354                         Task.processFinished(self, 0)
355                 else:
356                         Task.processFinished(self, 1)
357
358         def waitAndOpenPlayer(self):
359                 from enigma import eTimer
360                 self.delayTimer = eTimer()
361                 self.delayTimer.callback.append(self.previewProject)
362                 self.delayTimer.start(10,1)
363                 
364         def previewProject(self):
365                 from Plugins.Extensions.DVDPlayer.plugin import DVDPlayer
366                 self.job.project.session.openWithCallback(self.playerClosed, DVDPlayer, dvd_filelist= [ self.job.project.workspace + "/dvd/VIDEO_TS/" ])
367
368 class PreviewTaskPostcondition(Condition):
369         def check(self, task):
370                 return task.returncode == 0
371
372         def getErrorMessage(self, task):
373                 return "Cancel"
374
375 def formatTitle(template, title, track):
376         template = template.replace("$i", str(track))
377         template = template.replace("$t", title.name)
378         template = template.replace("$d", title.descr)
379         template = template.replace("$c", str(len(title.chaptermarks)+1))
380         template = template.replace("$A", str(title.audiotracks))
381         template = template.replace("$f", title.inputfile)
382         template = template.replace("$C", title.channel)
383         l = title.length
384         lengthstring = "%d:%02d:%02d" % (l/3600, l%3600/60, l%60)
385         template = template.replace("$l", lengthstring)
386         if title.timeCreate:
387                 template = template.replace("$Y", str(title.timeCreate[0]))
388                 template = template.replace("$M", str(title.timeCreate[1]))
389                 template = template.replace("$D", str(title.timeCreate[2]))
390                 timestring = "%d:%02d" % (title.timeCreate[3], title.timeCreate[4])
391                 template = template.replace("$T", timestring)
392         else:
393                 template = template.replace("$Y", "").replace("$M", "").replace("$D", "").replace("$T", "")
394         return template.decode("utf-8")
395
396 class ImagingPostcondition(Condition):
397         def check(self, task):
398                 return task.returncode == 0
399
400         def getErrorMessage(self, task):
401                 return "python-imaging " + _("failed")
402
403 class ImagePrepareTask(Task):
404         def __init__(self, job):
405                 Task.__init__(self, job, _("please wait, loading picture..."))
406                 self.postconditions.append(ImagingPostcondition())
407                 self.weighting = 20
408                 self.job = job
409                 self.Menus = job.Menus
410                 
411         def run(self, callback, task_progress_changed):                 
412                 self.callback = callback
413                 self.task_progress_changed = task_progress_changed
414                 # we are doing it this weird way so that the TaskView Screen actually pops up before the spinner comes
415                 from enigma import eTimer
416                 self.delayTimer = eTimer()
417                 self.delayTimer.callback.append(self.conduct)
418                 self.delayTimer.start(10,1)
419
420         def conduct(self):
421                 try:
422                         from ImageFont import truetype
423                         from Image import open as Image_open            
424                         s = self.job.project.settings
425                         self.Menus.im_bg_orig = Image_open(s.menubg.getValue())
426                         if self.Menus.im_bg_orig.size != (self.Menus.imgwidth, self.Menus.imgheight):
427                                 self.Menus.im_bg_orig = self.Menus.im_bg_orig.resize((720, 576))        
428                         self.Menus.fontsizes = s.font_size.getValue()
429                         fontface = s.font_face.getValue()
430                         self.Menus.fonts = [truetype(fontface, self.Menus.fontsizes[0]), truetype(fontface, self.Menus.fontsizes[1]), truetype(fontface, self.Menus.fontsizes[2])]
431                         Task.processFinished(self, 0)
432                 except:
433                         Task.processFinished(self, 1)
434
435 class MenuImageTask(Task):
436         def __init__(self, job):
437                 Task.__init__(self, job, "Create Menu %d Image" % job.Menus.menu_count)
438                 self.postconditions.append(ImagingPostcondition())
439                 self.weighting = 20 
440                 self.job = job
441                 self.Menus = job.Menus
442
443         def run(self, callback, task_progress_changed):
444                 self.callback = callback
445                 self.task_progress_changed = task_progress_changed
446                 try:
447                         import ImageDraw, Image, os
448                 
449                         s = self.job.project.settings
450                         fonts = self.Menus.fonts
451         
452                         im_bg = self.Menus.im_bg_orig.copy()
453                         im_high = Image.new("P", (self.Menus.imgwidth, self.Menus.imgheight), 0)
454                         im_high.putpalette(self.Menus.spu_palette)
455                         draw_bg = ImageDraw.Draw(im_bg)
456                         draw_high = ImageDraw.Draw(im_high)
457         
458                         if self.Menus.menu_count == 1:
459                                 headline = s.name.getValue().decode("utf-8")
460                                 textsize = draw_bg.textsize(headline, font=fonts[0])
461                                 if textsize[0] > self.Menus.imgwidth:
462                                         offset = (0 , 20)
463                                 else:
464                                         offset = (((self.Menus.imgwidth-textsize[0]) / 2) , 20)
465                                 draw_bg.text(offset, headline, fill=self.Menus.color_headline, font=fonts[0])
466         
467                         spuxml = """<?xml version="1.0" encoding="utf-8"?>
468                 <subpictures>
469                 <stream>
470                 <spu 
471                 highlight="%s"
472                 transparent="%02x%02x%02x"
473                 start="00:00:00.00"
474                 force="yes" >""" % (self.Menus.highlightpngfilename, self.Menus.spu_palette[0], self.Menus.spu_palette[1], self.Menus.spu_palette[2])
475                         s_top, s_rows, s_left = s.space.getValue()
476                         rowheight = (self.Menus.fontsizes[1]+self.Menus.fontsizes[2]+s_rows)
477                         menu_start_title = (self.Menus.menu_count-1)*self.job.titles_per_menu + 1
478                         menu_end_title = (self.Menus.menu_count)*self.job.titles_per_menu + 1
479                         nr_titles = len(self.job.project.titles)
480                         if menu_end_title > nr_titles:
481                                 menu_end_title = nr_titles+1
482                         menu_i = 0
483                         for title_no in range( menu_start_title , menu_end_title ):
484                                 i = title_no-1
485                                 top = s_top + ( menu_i * rowheight )
486                                 menu_i += 1
487                                 title = self.job.project.titles[i]
488                                 titleText = formatTitle(s.titleformat.getValue(), title, title_no)
489                                 draw_bg.text((s_left,top), titleText, fill=self.Menus.color_button, font=fonts[1])
490                                 draw_high.text((s_left,top), titleText, fill=1, font=self.Menus.fonts[1])
491                                 subtitleText = formatTitle(s.subtitleformat.getValue(), title, title_no)
492                                 draw_bg.text((s_left,top+36), subtitleText, fill=self.Menus.color_button, font=fonts[2])
493                                 bottom = top+rowheight
494                                 if bottom > self.Menus.imgheight:
495                                         bottom = self.Menus.imgheight
496                                 spuxml += """
497                 <button name="button%s" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (str(title_no).zfill(2),s_left,self.Menus.imgwidth,top,bottom )
498                         if self.Menus.menu_count > 1:
499                                 prev_page_text = "<<<"
500                                 textsize = draw_bg.textsize(prev_page_text, font=fonts[1])
501                                 offset = ( 2*s_left, s_top + ( self.job.titles_per_menu * rowheight ) )
502                                 draw_bg.text(offset, prev_page_text, fill=self.Menus.color_button, font=fonts[1])
503                                 draw_high.text(offset, prev_page_text, fill=1, font=fonts[1])
504                                 spuxml += """
505                 <button name="button_prev" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (offset[0],offset[0]+textsize[0],offset[1],offset[1]+textsize[1])
506         
507                         if self.Menus.menu_count < self.job.nr_menus:
508                                 next_page_text = ">>>"
509                                 textsize = draw_bg.textsize(next_page_text, font=fonts[1])
510                                 offset = ( self.Menus.imgwidth-textsize[0]-2*s_left, s_top + ( self.job.titles_per_menu * rowheight ) )
511                                 draw_bg.text(offset, next_page_text, fill=self.Menus.color_button, font=fonts[1])
512                                 draw_high.text(offset, next_page_text, fill=1, font=fonts[1])
513                                 spuxml += """
514                 <button name="button_next" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (offset[0],offset[0]+textsize[0],offset[1],offset[1]+textsize[1])
515                                         
516                         del draw_bg
517                         del draw_high
518                         fd=open(self.Menus.menubgpngfilename,"w")
519                         im_bg.save(fd,"PNG")
520                         fd.close()
521                         fd=open(self.Menus.highlightpngfilename,"w")
522                         im_high.save(fd,"PNG")
523                         fd.close()
524                         spuxml += """
525                 </spu>
526                 </stream>
527                 </subpictures>"""
528         
529                         f = open(self.Menus.spuxmlfilename, "w")
530                         f.write(spuxml)
531                         f.close()
532                         Task.processFinished(self, 0)
533                 except:
534                         Task.processFinished(self, 1)
535
536 class Menus:
537         def __init__(self, job):
538                 self.job = job
539                 job.Menus = self
540                 
541                 s = self.job.project.settings
542
543                 self.imgwidth = 720
544                 self.imgheight = 576
545
546                 self.color_headline = tuple(s.color_headline.getValue())
547                 self.color_button = tuple(s.color_button.getValue())
548                 self.color_highlight = tuple(s.color_highlight.getValue())
549                 self.spu_palette = [ 0x60, 0x60, 0x60 ] + s.color_highlight.getValue()
550
551                 ImagePrepareTask(job)
552                 print "[nach ImagePrepareTask]"
553                 nr_titles = len(job.project.titles)
554                 if nr_titles < 6:
555                         job.titles_per_menu = 5
556                 else:
557                         job.titles_per_menu = 4
558                 job.nr_menus = ((nr_titles+job.titles_per_menu-1)/job.titles_per_menu)
559
560                 #a new menu_count every 4 titles (1,2,3,4->1 ; 5,6,7,8->2 etc.)
561                 for self.menu_count in range(1 , job.nr_menus+1):
562                         num = str(self.menu_count)
563                         self.spuxmlfilename = job.workspace+"/spumux"+num+".xml"
564                         self.menubgpngfilename = job.workspace+"/dvd_menubg"+num+".png"
565                         self.highlightpngfilename = job.workspace+"/dvd_highlight"+num+".png"
566
567                         MenuImageTask(job)
568                         png2yuvTask(job, self.menubgpngfilename, job.workspace+"/dvdmenubg"+num+".yuv")
569                         menubgm2vfilename = job.workspace+"/dvdmenubg"+num+".mv2"
570                         mpeg2encTask(job, job.workspace+"/dvdmenubg"+num+".yuv", menubgm2vfilename)
571                         menubgmpgfilename = job.workspace+"/dvdmenubg"+num+".mpg"
572                         menuaudiofilename = s.menuaudio.getValue()
573                         MplexTask(job, outputfile=menubgmpgfilename, inputfiles = [menubgm2vfilename, menuaudiofilename])
574                         menuoutputfilename = job.workspace+"/dvdmenu"+num+".mpg"
575                         spumuxTask(job, self.spuxmlfilename, menubgmpgfilename, menuoutputfilename)
576                 
577 def CreateAuthoringXML(job):
578         nr_titles = len(job.project.titles)
579         mode = job.project.settings.authormode.getValue()
580         authorxml = []
581         authorxml.append('<?xml version="1.0" encoding="utf-8"?>\n')
582         authorxml.append(' <dvdauthor dest="' + (job.workspace+"/dvd") + '">\n')
583         authorxml.append('  <vmgm>\n')
584         authorxml.append('   <menus>\n')
585         authorxml.append('    <pgc>\n')
586         authorxml.append('     <vob file="' + job.project.settings.vmgm.getValue() + '" />\n', )
587         if mode.startswith("menu"):
588                 authorxml.append('     <post> jump titleset 1 menu; </post>\n')
589         else:
590                 authorxml.append('     <post> jump title 1; </post>\n')
591         authorxml.append('    </pgc>\n')
592         authorxml.append('   </menus>\n')
593         authorxml.append('  </vmgm>\n')
594         authorxml.append('  <titleset>\n')
595         if mode.startswith("menu"):
596                 authorxml.append('   <menus>\n')
597                 authorxml.append('    <video aspect="4:3"/>\n')
598                 for menu_count in range(1 , job.nr_menus+1):
599                         if menu_count == 1:
600                                 authorxml.append('    <pgc entry="root">\n')
601                         else:
602                                 authorxml.append('    <pgc>\n')
603                         menu_start_title = (menu_count-1)*job.titles_per_menu + 1
604                         menu_end_title = (menu_count)*job.titles_per_menu + 1
605                         if menu_end_title > nr_titles:
606                                 menu_end_title = nr_titles+1
607                         for i in range( menu_start_title , menu_end_title ):
608                                 authorxml.append('     <button name="button' + (str(i).zfill(2)) + '"> jump title ' + str(i) +'; </button>\n')
609                         if menu_count > 1:
610                                 authorxml.append('     <button name="button_prev"> jump menu ' + str(menu_count-1) + '; </button>\n')
611                         if menu_count < job.nr_menus:
612                                 authorxml.append('     <button name="button_next"> jump menu ' + str(menu_count+1) + '; </button>\n')
613                         menuoutputfilename = job.workspace+"/dvdmenu"+str(menu_count)+".mpg"
614                         authorxml.append('     <vob file="' + menuoutputfilename + '" pause="inf"/>\n')
615                         authorxml.append('    </pgc>\n')
616                 authorxml.append('   </menus>\n')
617         authorxml.append('   <titles>\n')
618         for i in range( nr_titles ):
619                 for audiotrack in job.project.titles[i].audiotracks:
620                         authorxml.append('    <audio lang="'+audiotrack[0][:2]+'" format="'+audiotrack[1]+'" />\n')
621                 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])
622                 title_no = i+1
623                 title_filename = job.workspace + "/dvd_title_%d.mpg" % (title_no)
624                 if job.menupreview:
625                         LinkTS(job, job.project.settings.vmgm.getValue(), title_filename)
626                 else:
627                         MakeFifoNode(job, title_no)
628                 if mode.endswith("linked") and title_no < nr_titles:
629                         post_tag = "jump title %d;" % ( title_no+1 )
630                 elif mode.startswith("menu"):
631                         post_tag = "call vmgm menu 1;"
632                 else:   post_tag = ""
633
634                 authorxml.append('    <pgc>\n')
635                 authorxml.append('     <vob file="' + title_filename + '" chapters="' + chapters + '" />\n')
636                 authorxml.append('     <post> ' + post_tag + ' </post>\n')
637                 authorxml.append('    </pgc>\n')
638
639         authorxml.append('   </titles>\n')
640         authorxml.append('  </titleset>\n')
641         authorxml.append(' </dvdauthor>\n')
642         f = open(job.workspace+"/dvdauthor.xml", "w")
643         for x in authorxml:
644                 f.write(x)
645         f.close()
646
647 class DVDJob(Job):
648         def __init__(self, project, menupreview=False):
649                 Job.__init__(self, "DVD Burn")
650                 self.project = project
651                 from time import strftime
652                 from Tools.Directories import SCOPE_HDD, resolveFilename, createDir
653                 new_workspace = resolveFilename(SCOPE_HDD) + "tmp/" + strftime("%Y%m%d%H%M%S")
654                 createDir(new_workspace, True)
655                 self.workspace = new_workspace
656                 self.project.workspace = self.workspace
657                 self.menupreview = menupreview
658                 self.conduct()
659
660         def conduct(self):
661                 if self.project.settings.authormode.getValue().startswith("menu") or self.menupreview:
662                         Menus(self)
663                 CreateAuthoringXML(self)
664
665                 totalsize = 50*1024*1024 # require an extra safety 50 MB
666                 maxsize = 0
667                 for title in self.project.titles:
668                         titlesize = title.estimatedDiskspace
669                         if titlesize > maxsize: maxsize = titlesize
670                         totalsize += titlesize
671                 diskSpaceNeeded = totalsize + maxsize
672
673                 DVDAuthorTask(self, diskSpaceNeeded)
674                 
675                 nr_titles = len(self.project.titles)
676                 
677                 if self.menupreview:
678                         PreviewTask(self)
679                 else:
680                         for self.i in range(nr_titles):
681                                 title = self.project.titles[self.i]
682                                 link_name =  self.workspace + "/source_title_%d.ts" % (self.i+1)
683                                 title_filename = self.workspace + "/dvd_title_%d.mpg" % (self.i+1)
684                                 LinkTS(self, title.inputfile, link_name)
685                                 demux = DemuxTask(self, link_name)
686                                 MplexTask(self, outputfile=title_filename, demux_task=demux)
687                                 RemoveESFiles(self, demux)
688                         WaitForResidentTasks(self)
689                         PreviewTask(self)
690                         BurnTask(self,["-dvd-video"])
691                 RemoveDVDFolder(self)
692
693 class DVDdataJob(Job):
694         def __init__(self, project):
695                 Job.__init__(self, "Data DVD Burn")
696                 self.project = project
697                 from time import strftime
698                 from Tools.Directories import SCOPE_HDD, resolveFilename, createDir
699                 new_workspace = resolveFilename(SCOPE_HDD) + "tmp/" + strftime("%Y%m%d%H%M%S") + "/dvd/"
700                 createDir(new_workspace, True)
701                 self.workspace = new_workspace
702                 self.project.workspace = self.workspace
703                 self.conduct()
704
705         def conduct(self):
706                 diskSpaceNeeded = 50*1024*1024 # require an extra safety 50 MB
707                 for title in self.project.titles:
708                         diskSpaceNeeded += title.filesize
709                 nr_titles = len(self.project.titles)
710
711                 for self.i in range(nr_titles):
712                         title = self.project.titles[self.i]
713                         filename = title.inputfile.rstrip("/").rsplit("/",1)[1]
714                         link_name =  self.workspace + filename
715                         LinkTS(self, title.inputfile, link_name)
716                         CopyMeta(self, title.inputfile)
717                 BurnTask(self)
718                 RemoveDVDFolder(self)
719
720 def Burn(session, project):
721         j = DVDJob(project)
722         job_manager.AddJob(j)
723         return j
724
725 def PreviewMenu(session, project):
726         j = DVDJob(project, menupreview=True)
727         job_manager.AddJob(j)
728         return j
729
730 def BurnDataTS(session, project):
731         j = DVDdataJob(project)
732         job_manager.AddJob(j)
733         return j