fix progress scaling and remove unneeded project paramter from dvd media toolbox
[enigma2.git] / lib / python / Plugins / Extensions / DVDBurn / Process.py
1 from Components.Task import Task, Job, DiskspacePrecondition, Condition, ToolExistsPrecondition
2 from Components.Harddisk import harddiskmanager
3 from Screens.MessageBox import MessageBox
4
5 class png2yuvTask(Task):
6         def __init__(self, job, inputfile, outputfile):
7                 Task.__init__(self, job, "Creating menu video")
8                 self.setTool("/usr/bin/png2yuv")
9                 self.args += ["-n1", "-Ip", "-f25", "-j", inputfile]
10                 self.dumpFile = outputfile
11                 self.weighting = 15
12
13         def run(self, callback, task_progress_changed):
14                 Task.run(self, callback, task_progress_changed)
15                 self.container.stdoutAvail.get().remove(self.processStdout)
16                 self.container.dumpToFile(self.dumpFile)
17
18         def processStderr(self, data):
19                 print "[png2yuvTask]", data[:-1]
20
21 class mpeg2encTask(Task):
22         def __init__(self, job, inputfile, outputfile):
23                 Task.__init__(self, job, "Encoding menu video")
24                 self.setTool("/usr/bin/mpeg2enc")
25                 self.args += ["-f8", "-np", "-a2", "-o", outputfile]
26                 self.inputFile = inputfile
27                 self.weighting = 25
28                 
29         def run(self, callback, task_progress_changed):
30                 Task.run(self, callback, task_progress_changed)
31                 self.container.readFromFile(self.inputFile)
32
33         def processOutputLine(self, line):
34                 print "[mpeg2encTask]", line[:-1]
35
36 class spumuxTask(Task):
37         def __init__(self, job, xmlfile, inputfile, outputfile):
38                 Task.__init__(self, job, "Muxing buttons into menu")
39                 self.setTool("/usr/bin/spumux")
40                 self.args += [xmlfile]
41                 self.inputFile = inputfile
42                 self.dumpFile = outputfile
43                 self.weighting = 15
44
45         def run(self, callback, task_progress_changed):
46                 Task.run(self, callback, task_progress_changed)
47                 self.container.stdoutAvail.get().remove(self.processStdout)
48                 self.container.dumpToFile(self.dumpFile)
49                 self.container.readFromFile(self.inputFile)
50
51         def processStderr(self, data):
52                 print "[spumuxTask]", data[:-1]
53
54 class MakeFifoNode(Task):
55         def __init__(self, job, number):
56                 Task.__init__(self, job, "Make FIFO nodes")
57                 self.setTool("/bin/mknod")
58                 nodename = self.job.workspace + "/dvd_title_%d" % number + ".mpg"
59                 self.args += [nodename, "p"]
60                 self.weighting = 10
61
62 class LinkTS(Task):
63         def __init__(self, job, sourcefile, link_name):
64                 Task.__init__(self, job, "Creating symlink for source titles")
65                 self.setTool("/bin/ln")
66                 self.args += ["-s", sourcefile, link_name]
67                 self.weighting = 10
68
69 class CopyMeta(Task):
70         def __init__(self, job, sourcefile):
71                 Task.__init__(self, job, "Copy title meta files")
72                 self.setTool("/bin/cp")
73                 from os import listdir
74                 path, filename = sourcefile.rstrip("/").rsplit("/",1)
75                 tsfiles = listdir(path)
76                 for file in tsfiles:
77                         if file.startswith(filename+"."):
78                                 self.args += [path+'/'+file]
79                 self.args += [self.job.workspace]
80                 self.weighting = 15
81
82 class DemuxTask(Task):
83         def __init__(self, job, inputfile):
84                 Task.__init__(self, job, "Demux video into ES")
85                 title = job.project.titles[job.i]
86                 self.global_preconditions.append(DiskspacePrecondition(title.estimatedDiskspace))
87                 self.setTool("/usr/bin/projectx")
88                 self.generated_files = [ ]
89                 self.end = 300
90                 self.prog_state = 0
91                 self.weighting = 1000
92                 self.cutfile = self.job.workspace + "/cut_%d.Xcl" % (job.i+1)
93                 self.cutlist = title.cutlist
94                 self.args += [inputfile, "-demux", "-out", self.job.workspace ]
95                 if len(self.cutlist) > 1:
96                         self.args += [ "-cut", self.cutfile ]
97
98         def prepare(self):
99                 self.writeCutfile()
100
101         def processOutputLine(self, line):
102                 line = line[:-1]
103                 MSG_NEW_FILE = "---> new File: "
104                 MSG_PROGRESS = "[PROGRESS] "
105
106                 if line.startswith(MSG_NEW_FILE):
107                         file = line[len(MSG_NEW_FILE):]
108                         if file[0] == "'":
109                                 file = file[1:-1]
110                         self.haveNewFile(file)
111                 elif line.startswith(MSG_PROGRESS):
112                         progress = line[len(MSG_PROGRESS):]
113                         self.haveProgress(progress)
114
115         def haveNewFile(self, file):
116                 print "PRODUCED FILE [%s]" % file
117                 self.generated_files.append(file)
118
119         def haveProgress(self, progress):
120                 #print "PROGRESS [%s]" % progress
121                 MSG_CHECK = "check & synchronize audio file"
122                 MSG_DONE = "done..."
123                 if progress == "preparing collection(s)...":
124                         self.prog_state = 0
125                 elif progress[:len(MSG_CHECK)] == MSG_CHECK:
126                         self.prog_state += 1
127                 else:
128                         try:
129                                 p = int(progress)
130                                 p = p - 1 + self.prog_state * 100
131                                 if p > self.progress:
132                                         self.progress = p
133                         except ValueError:
134                                 print "val error"
135                                 pass
136
137         def writeCutfile(self):
138                 f = open(self.cutfile, "w")
139                 f.write("CollectionPanel.CutMode=4\n")
140                 for p in self.cutlist:
141                         s = p / 90000
142                         m = s / 60
143                         h = m / 60
144
145                         m %= 60
146                         s %= 60
147
148                         f.write("%02d:%02d:%02d\n" % (h, m, s))
149                 f.close()
150
151         def cleanup(self, failed):
152                 if failed:
153                         import os
154                         for f in self.generated_files:
155                                 os.remove(f)
156
157 class MplexTaskPostcondition(Condition):
158         def check(self, task):
159                 if task.error == task.ERROR_UNDERRUN:
160                         return True
161                 return task.error is None
162
163         def getErrorMessage(self, 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, weighting = 500):
172                 Task.__init__(self, job, "Mux ES into PS")
173                 self.weighting = weighting
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] ", 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                 self.weighting = 10
206
207         def prepare(self):
208                 self.args += ["-f"]
209                 self.args += self.demux_task.generated_files
210                 self.args += [self.demux_task.cutfile]
211
212 class DVDAuthorTask(Task):
213         def __init__(self, job, diskspaceNeeded):
214                 Task.__init__(self, job, "Authoring DVD")
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] ", 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 to DVD..."))
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/" + harddiskmanager.getCD(), "-V", volName, "-publisher", "Dreambox", "-use-the-force-luke=dummy" ]
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(") != -1 and line.find(",O_RDONLY): No such file or directory") != -1:
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                 self.weighting = 10
326
327 class PreviewTask(Task):
328         def __init__(self, job):
329                 Task.__init__(self, job, "Preview")
330                 self.postconditions.append(PreviewTaskPostcondition())
331                 self.job = job
332                 self.weighting = 10
333
334         def run(self, callback, task_progress_changed):
335                 self.callback = callback
336                 self.task_progress_changed = task_progress_changed
337                 if self.job.menupreview:
338                         self.previewProject()
339                 else:
340                         self.job.project.session.openWithCallback(self.previewCB, MessageBox, _("Do you want to preview this DVD before burning?"), timeout = 60, default = False)
341
342         def abort(self):
343                 self.finish(aborted = True)
344         
345         def previewCB(self, answer):
346                 if answer == True:
347                         self.previewProject()
348                 else:
349                         self.closedCB(True)
350
351         def playerClosed(self):
352                 if self.job.menupreview:
353                         self.closedCB(True)
354                 else:
355                         self.job.project.session.openWithCallback(self.closedCB, MessageBox, _("Do you want to burn this collection to DVD medium?") )
356
357         def closedCB(self, answer):
358                 if answer == True:
359                         Task.processFinished(self, 0)
360                 else:
361                         Task.processFinished(self, 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 formatTitle(template, title, track):
375         template = template.replace("$i", str(track))
376         template = template.replace("$t", title.name)
377         template = template.replace("$d", title.descr)
378         template = template.replace("$c", str(len(title.chaptermarks)+1))
379         template = template.replace("$A", str(title.audiotracks))
380         template = template.replace("$f", title.inputfile)
381         template = template.replace("$C", title.channel)
382         l = title.length
383         lengthstring = "%d:%02d:%02d" % (l/3600, l%3600/60, l%60)
384         template = template.replace("$l", lengthstring)
385         if title.timeCreate:
386                 template = template.replace("$Y", str(title.timeCreate[0]))
387                 template = template.replace("$M", str(title.timeCreate[1]))
388                 template = template.replace("$D", str(title.timeCreate[2]))
389                 timestring = "%d:%02d" % (title.timeCreate[3], title.timeCreate[4])
390                 template = template.replace("$T", timestring)
391         else:
392                 template = template.replace("$Y", "").replace("$M", "").replace("$D", "").replace("$T", "")
393         return template.decode("utf-8")
394
395 class ImagingPostcondition(Condition):
396         def check(self, task):
397                 return task.returncode == 0
398
399         def getErrorMessage(self, task):
400                 return _("Failed") + ": python-imaging"
401
402 class ImagePrepareTask(Task):
403         def __init__(self, job):
404                 Task.__init__(self, job, _("please wait, loading picture..."))
405                 self.postconditions.append(ImagingPostcondition())
406                 self.weighting = 20
407                 self.job = job
408                 self.Menus = job.Menus
409                 
410         def run(self, callback, task_progress_changed):                 
411                 self.callback = callback
412                 self.task_progress_changed = task_progress_changed
413                 # we are doing it this weird way so that the TaskView Screen actually pops up before the spinner comes
414                 from enigma import eTimer
415                 self.delayTimer = eTimer()
416                 self.delayTimer.callback.append(self.conduct)
417                 self.delayTimer.start(10,1)
418
419         def conduct(self):
420                 try:
421                         from ImageFont import truetype
422                         from Image import open as Image_open            
423                         s = self.job.project.settings
424                         self.Menus.im_bg_orig = Image_open(s.menubg.getValue())
425                         if self.Menus.im_bg_orig.size != (self.Menus.imgwidth, self.Menus.imgheight):
426                                 self.Menus.im_bg_orig = self.Menus.im_bg_orig.resize((720, 576))        
427                         self.Menus.fontsizes = s.font_size.getValue()
428                         fontface = s.font_face.getValue()
429                         self.Menus.fonts = [truetype(fontface, self.Menus.fontsizes[0]), truetype(fontface, self.Menus.fontsizes[1]), truetype(fontface, self.Menus.fontsizes[2])]
430                         Task.processFinished(self, 0)
431                 except:
432                         Task.processFinished(self, 1)
433
434 class MenuImageTask(Task):
435         def __init__(self, job, menu_count, spuxmlfilename, menubgpngfilename, highlightpngfilename):
436                 Task.__init__(self, job, "Create Menu %d Image" % menu_count)
437                 self.postconditions.append(ImagingPostcondition())
438                 self.weighting = 10
439                 self.job = job
440                 self.Menus = job.Menus
441                 self.menu_count = menu_count
442                 self.spuxmlfilename = spuxmlfilename
443                 self.menubgpngfilename = menubgpngfilename
444                 self.highlightpngfilename = highlightpngfilename
445
446         def run(self, callback, task_progress_changed):
447                 self.callback = callback
448                 self.task_progress_changed = task_progress_changed
449                 try:
450                         import ImageDraw, Image, os
451                         s = self.job.project.settings
452                         fonts = self.Menus.fonts
453                         im_bg = self.Menus.im_bg_orig.copy()
454                         im_high = Image.new("P", (self.Menus.imgwidth, self.Menus.imgheight), 0)
455                         im_high.putpalette(self.Menus.spu_palette)
456                         draw_bg = ImageDraw.Draw(im_bg)
457                         draw_high = ImageDraw.Draw(im_high)
458                         if self.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                         spuxml = """<?xml version="1.0" encoding="utf-8"?>
467                 <subpictures>
468                 <stream>
469                 <spu 
470                 highlight="%s"
471                 transparent="%02x%02x%02x"
472                 start="00:00:00.00"
473                 force="yes" >""" % (self.highlightpngfilename, self.Menus.spu_palette[0], self.Menus.spu_palette[1], self.Menus.spu_palette[2])
474                         s_top, s_rows, s_left = s.space.getValue()
475                         rowheight = (self.Menus.fontsizes[1]+self.Menus.fontsizes[2]+s_rows)
476                         menu_start_title = (self.menu_count-1)*self.job.titles_per_menu + 1
477                         menu_end_title = (self.menu_count)*self.job.titles_per_menu + 1
478                         nr_titles = len(self.job.project.titles)
479                         if menu_end_title > nr_titles:
480                                 menu_end_title = nr_titles+1
481                         menu_i = 0
482                         for title_no in range( menu_start_title , menu_end_title ):
483                                 i = title_no-1
484                                 top = s_top + ( menu_i * rowheight )
485                                 menu_i += 1
486                                 title = self.job.project.titles[i]
487                                 titleText = formatTitle(s.titleformat.getValue(), title, title_no)
488                                 draw_bg.text((s_left,top), titleText, fill=self.Menus.color_button, font=fonts[1])
489                                 draw_high.text((s_left,top), titleText, fill=1, font=self.Menus.fonts[1])
490                                 subtitleText = formatTitle(s.subtitleformat.getValue(), title, title_no)
491                                 draw_bg.text((s_left,top+36), subtitleText, fill=self.Menus.color_button, font=fonts[2])
492                                 bottom = top+rowheight
493                                 if bottom > self.Menus.imgheight:
494                                         bottom = self.Menus.imgheight
495                                 spuxml += """
496                 <button name="button%s" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (str(title_no).zfill(2),s_left,self.Menus.imgwidth,top,bottom )
497                         if self.menu_count < self.job.nr_menus:
498                                 next_page_text = ">>>"
499                                 textsize = draw_bg.textsize(next_page_text, font=fonts[1])
500                                 offset = ( self.Menus.imgwidth-textsize[0]-2*s_left, s_top + ( self.job.titles_per_menu * rowheight ) )
501                                 draw_bg.text(offset, next_page_text, fill=self.Menus.color_button, font=fonts[1])
502                                 draw_high.text(offset, next_page_text, fill=1, font=fonts[1])
503                                 spuxml += """
504                 <button name="button_next" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (offset[0],offset[0]+textsize[0],offset[1],offset[1]+textsize[1])
505                         if self.menu_count > 1:
506                                 prev_page_text = "<<<"
507                                 textsize = draw_bg.textsize(prev_page_text, font=fonts[1])
508                                 offset = ( 2*s_left, s_top + ( self.job.titles_per_menu * rowheight ) )
509                                 draw_bg.text(offset, prev_page_text, fill=self.Menus.color_button, font=fonts[1])
510                                 draw_high.text(offset, prev_page_text, fill=1, font=fonts[1])
511                                 spuxml += """
512                 <button name="button_prev" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (offset[0],offset[0]+textsize[0],offset[1],offset[1]+textsize[1])
513                         del draw_bg
514                         del draw_high
515                         fd=open(self.menubgpngfilename,"w")
516                         im_bg.save(fd,"PNG")
517                         fd.close()
518                         fd=open(self.highlightpngfilename,"w")
519                         im_high.save(fd,"PNG")
520                         fd.close()
521                         spuxml += """
522                 </spu>
523                 </stream>
524                 </subpictures>"""
525         
526                         f = open(self.spuxmlfilename, "w")
527                         f.write(spuxml)
528                         f.close()
529                         Task.processFinished(self, 0)
530                 except:
531                         Task.processFinished(self, 1)
532
533 class Menus:
534         def __init__(self, job):
535                 self.job = job
536                 job.Menus = self
537                 
538                 s = self.job.project.settings
539
540                 self.imgwidth = 720
541                 self.imgheight = 576
542
543                 self.color_headline = tuple(s.color_headline.getValue())
544                 self.color_button = tuple(s.color_button.getValue())
545                 self.color_highlight = tuple(s.color_highlight.getValue())
546                 self.spu_palette = [ 0x60, 0x60, 0x60 ] + s.color_highlight.getValue()
547
548                 ImagePrepareTask(job)
549                 nr_titles = len(job.project.titles)
550                 if nr_titles < 6:
551                         job.titles_per_menu = 5
552                 else:
553                         job.titles_per_menu = 4
554                 job.nr_menus = ((nr_titles+job.titles_per_menu-1)/job.titles_per_menu)
555
556                 #a new menu_count every 4 titles (1,2,3,4->1 ; 5,6,7,8->2 etc.)
557                 for menu_count in range(1 , job.nr_menus+1):
558                         num = str(menu_count)
559                         spuxmlfilename = job.workspace+"/spumux"+num+".xml"
560                         menubgpngfilename = job.workspace+"/dvd_menubg"+num+".png"
561                         highlightpngfilename = job.workspace+"/dvd_highlight"+num+".png"
562                         MenuImageTask(job, menu_count, spuxmlfilename, menubgpngfilename, highlightpngfilename)
563                         png2yuvTask(job, menubgpngfilename, job.workspace+"/dvdmenubg"+num+".yuv")
564                         menubgm2vfilename = job.workspace+"/dvdmenubg"+num+".mv2"
565                         mpeg2encTask(job, job.workspace+"/dvdmenubg"+num+".yuv", menubgm2vfilename)
566                         menubgmpgfilename = job.workspace+"/dvdmenubg"+num+".mpg"
567                         menuaudiofilename = s.menuaudio.getValue()
568                         MplexTask(job, outputfile=menubgmpgfilename, inputfiles = [menubgm2vfilename, menuaudiofilename], weighting = 20)
569                         menuoutputfilename = job.workspace+"/dvdmenu"+num+".mpg"
570                         spumuxTask(job, spuxmlfilename, menubgmpgfilename, menuoutputfilename)
571                 
572 def CreateAuthoringXML(job):
573         nr_titles = len(job.project.titles)
574         mode = job.project.settings.authormode.getValue()
575         authorxml = []
576         authorxml.append('<?xml version="1.0" encoding="utf-8"?>\n')
577         authorxml.append(' <dvdauthor dest="' + (job.workspace+"/dvd") + '">\n')
578         authorxml.append('  <vmgm>\n')
579         authorxml.append('   <menus>\n')
580         authorxml.append('    <pgc>\n')
581         authorxml.append('     <vob file="' + job.project.settings.vmgm.getValue() + '" />\n', )
582         if mode.startswith("menu"):
583                 authorxml.append('     <post> jump titleset 1 menu; </post>\n')
584         else:
585                 authorxml.append('     <post> jump title 1; </post>\n')
586         authorxml.append('    </pgc>\n')
587         authorxml.append('   </menus>\n')
588         authorxml.append('  </vmgm>\n')
589         authorxml.append('  <titleset>\n')
590         if mode.startswith("menu"):
591                 authorxml.append('   <menus>\n')
592                 authorxml.append('    <video aspect="4:3"/>\n')
593                 for menu_count in range(1 , job.nr_menus+1):
594                         if menu_count == 1:
595                                 authorxml.append('    <pgc entry="root">\n')
596                         else:
597                                 authorxml.append('    <pgc>\n')
598                         menu_start_title = (menu_count-1)*job.titles_per_menu + 1
599                         menu_end_title = (menu_count)*job.titles_per_menu + 1
600                         if menu_end_title > nr_titles:
601                                 menu_end_title = nr_titles+1
602                         for i in range( menu_start_title , menu_end_title ):
603                                 authorxml.append('     <button name="button' + (str(i).zfill(2)) + '"> jump title ' + str(i) +'; </button>\n')
604                         if menu_count > 1:
605                                 authorxml.append('     <button name="button_prev"> jump menu ' + str(menu_count-1) + '; </button>\n')
606                         if menu_count < job.nr_menus:
607                                 authorxml.append('     <button name="button_next"> jump menu ' + str(menu_count+1) + '; </button>\n')
608                         menuoutputfilename = job.workspace+"/dvdmenu"+str(menu_count)+".mpg"
609                         authorxml.append('     <vob file="' + menuoutputfilename + '" pause="inf"/>\n')
610                         authorxml.append('    </pgc>\n')
611                 authorxml.append('   </menus>\n')
612         authorxml.append('   <titles>\n')
613         for i in range( nr_titles ):
614                 #for audiotrack in job.project.titles[i].audiotracks:
615                         #authorxml.append('    <audio lang="'+audiotrack[0][:2]+'" format="'+audiotrack[1]+'" />\n')
616                 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])
617                 title_no = i+1
618                 title_filename = job.workspace + "/dvd_title_%d.mpg" % (title_no)
619                 if job.menupreview:
620                         LinkTS(job, job.project.settings.vmgm.getValue(), title_filename)
621                 else:
622                         MakeFifoNode(job, title_no)
623                 if mode.endswith("linked") and title_no < nr_titles:
624                         post_tag = "jump title %d;" % ( title_no+1 )
625                 elif mode.startswith("menu"):
626                         post_tag = "call vmgm menu 1;"
627                 else:   post_tag = ""
628
629                 authorxml.append('    <pgc>\n')
630                 authorxml.append('     <vob file="' + title_filename + '" chapters="' + chapters + '" />\n')
631                 authorxml.append('     <post> ' + post_tag + ' </post>\n')
632                 authorxml.append('    </pgc>\n')
633
634         authorxml.append('   </titles>\n')
635         authorxml.append('  </titleset>\n')
636         authorxml.append(' </dvdauthor>\n')
637         f = open(job.workspace+"/dvdauthor.xml", "w")
638         for x in authorxml:
639                 f.write(x)
640         f.close()
641
642 class DVDJob(Job):
643         def __init__(self, project, menupreview=False):
644                 Job.__init__(self, _("Burn DVD"))
645                 self.project = project
646                 from time import strftime
647                 from Tools.Directories import SCOPE_HDD, resolveFilename, createDir
648                 new_workspace = resolveFilename(SCOPE_HDD) + "tmp/" + strftime("%Y%m%d%H%M%S")
649                 createDir(new_workspace, True)
650                 self.workspace = new_workspace
651                 self.project.workspace = self.workspace
652                 self.menupreview = menupreview
653                 self.conduct()
654
655         def conduct(self):
656                 if self.project.settings.authormode.getValue().startswith("menu") or self.menupreview:
657                         Menus(self)
658                 CreateAuthoringXML(self)
659
660                 totalsize = 50*1024*1024 # require an extra safety 50 MB
661                 maxsize = 0
662                 for title in self.project.titles:
663                         titlesize = title.estimatedDiskspace
664                         if titlesize > maxsize: maxsize = titlesize
665                         totalsize += titlesize
666                 diskSpaceNeeded = totalsize + maxsize
667
668                 DVDAuthorTask(self, diskSpaceNeeded)
669                 
670                 nr_titles = len(self.project.titles)
671
672                 if self.menupreview:
673                         PreviewTask(self)
674                 else:
675                         for self.i in range(nr_titles):
676                                 title = self.project.titles[self.i]
677                                 link_name =  self.workspace + "/source_title_%d.ts" % (self.i+1)
678                                 title_filename = self.workspace + "/dvd_title_%d.mpg" % (self.i+1)
679                                 LinkTS(self, title.inputfile, link_name)
680                                 demux = DemuxTask(self, link_name)
681                                 MplexTask(self, outputfile=title_filename, demux_task=demux)
682                                 RemoveESFiles(self, demux)
683                         WaitForResidentTasks(self)
684                         PreviewTask(self)
685                         BurnTask(self, ["-dvd-video", self.workspace + "/dvd"])
686                 RemoveDVDFolder(self)
687
688 class DVDdataJob(Job):
689         def __init__(self, project):
690                 Job.__init__(self, "Data DVD Burn")
691                 self.project = project
692                 from time import strftime
693                 from Tools.Directories import SCOPE_HDD, resolveFilename, createDir
694                 new_workspace = resolveFilename(SCOPE_HDD) + "tmp/" + strftime("%Y%m%d%H%M%S") + "/dvd/"
695                 createDir(new_workspace, True)
696                 self.workspace = new_workspace
697                 self.project.workspace = self.workspace
698                 self.conduct()
699
700         def conduct(self):
701                 diskSpaceNeeded = 50*1024*1024 # require an extra safety 50 MB
702                 for title in self.project.titles:
703                         diskSpaceNeeded += title.filesize
704                 nr_titles = len(self.project.titles)
705
706                 for self.i in range(nr_titles):
707                         title = self.project.titles[self.i]
708                         filename = title.inputfile.rstrip("/").rsplit("/",1)[1]
709                         link_name =  self.workspace + filename
710                         LinkTS(self, title.inputfile, link_name)
711                         CopyMeta(self, title.inputfile)
712                 BurnTask(self, ["-follow-links", self.workspace])
713                 RemoveDVDFolder(self)