show dvd burn jobs running in background in main menu and fix potential crash on...
[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):
14                 Task.run(self, callback)
15                 self.container.stdoutAvail.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):
30                 Task.run(self, callback)
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):
46                 Task.run(self, callback)
47                 self.container.stdoutAvail.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.args += [inputfile, "-demux", "-out", self.job.workspace ]
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.currentPID = None
95                 self.relevantAudioPIDs = [ ]
96                 self.getRelevantAudioPIDs(title)
97                 self.generated_files = [ ]
98                 self.mplex_streamfiles = [ ]
99                 if len(self.cutlist) > 1:
100                         self.args += [ "-cut", self.cutfile ]
101
102         def prepare(self):
103                 self.writeCutfile()
104
105         def getRelevantAudioPIDs(self, title):
106                 for audiotrack in title.properties.audiotracks:
107                         if audiotrack.active.getValue():
108                                 self.relevantAudioPIDs.append(audiotrack.pid.getValue())
109
110         def processOutputLine(self, line):
111                 line = line[:-1]
112                 MSG_NEW_FILE = "---> new File: "
113                 MSG_PROGRESS = "[PROGRESS] "
114                 MSG_NEW_MP2 = "--> MPEG Audio (0x"
115                 MSG_NEW_AC3 = "--> AC-3/DTS Audio on PID "
116
117                 if line.startswith(MSG_NEW_FILE):
118                         file = line[len(MSG_NEW_FILE):]
119                         if file[0] == "'":
120                                 file = file[1:-1]
121                         self.haveNewFile(file)
122                 elif line.startswith(MSG_PROGRESS):
123                         progress = line[len(MSG_PROGRESS):]
124                         self.haveProgress(progress)
125                 elif line.startswith(MSG_NEW_MP2) or line.startswith(MSG_NEW_AC3):
126                         self.currentPID = str(int(line.rstrip()[-6:].rsplit('0x',1)[-1],16))
127
128         def haveNewFile(self, file):
129                 print "[DemuxTask] produced file:", file, self.currentPID
130                 self.generated_files.append(file)
131                 if self.currentPID in self.relevantAudioPIDs or file.endswith("m2v"):
132                         self.mplex_streamfiles.append(file)
133
134         def haveProgress(self, progress):
135                 #print "PROGRESS [%s]" % progress
136                 MSG_CHECK = "check & synchronize audio file"
137                 MSG_DONE = "done..."
138                 if progress == "preparing collection(s)...":
139                         self.prog_state = 0
140                 elif progress[:len(MSG_CHECK)] == MSG_CHECK:
141                         self.prog_state += 1
142                 else:
143                         try:
144                                 p = int(progress)
145                                 p = p - 1 + self.prog_state * 100
146                                 if p > self.progress:
147                                         self.progress = p
148                         except ValueError:
149                                 pass
150
151         def writeCutfile(self):
152                 f = open(self.cutfile, "w")
153                 f.write("CollectionPanel.CutMode=4\n")
154                 for p in self.cutlist:
155                         s = p / 90000
156                         m = s / 60
157                         h = m / 60
158
159                         m %= 60
160                         s %= 60
161
162                         f.write("%02d:%02d:%02d\n" % (h, m, s))
163                 f.close()
164
165         def cleanup(self, failed):
166                 if failed:
167                         import os
168                         for file in self.generated_files.itervalues():
169                                 os.remove(file)
170
171 class MplexTaskPostcondition(Condition):
172         def check(self, task):
173                 if task.error == task.ERROR_UNDERRUN:
174                         return True
175                 return task.error is None
176
177         def getErrorMessage(self, task):
178                 return {
179                         task.ERROR_UNDERRUN: ("Can't multiplex source video!"),
180                         task.ERROR_UNKNOWN: ("An unknown error occured!")
181                 }[task.error]
182
183 class MplexTask(Task):
184         ERROR_UNDERRUN, ERROR_UNKNOWN = range(2)
185         def __init__(self, job, outputfile, inputfiles=None, demux_task=None, weighting = 500):
186                 Task.__init__(self, job, "Mux ES into PS")
187                 self.weighting = weighting
188                 self.demux_task = demux_task
189                 self.postconditions.append(MplexTaskPostcondition())
190                 self.setTool("/usr/bin/mplex")
191                 self.args += ["-f8", "-o", outputfile, "-v1"]
192                 if inputfiles:
193                         self.args += inputfiles
194
195         def setTool(self, tool):
196                 self.cmd = tool
197                 self.args = [tool]
198                 self.global_preconditions.append(ToolExistsPrecondition())
199                 # 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)
200
201         def prepare(self):
202                 self.error = None
203                 if self.demux_task:
204                         self.args += self.demux_task.mplex_streamfiles
205
206         def processOutputLine(self, line):
207                 print "[MplexTask] ", line[:-1]
208                 if line.startswith("**ERROR:"):
209                         if line.find("Frame data under-runs detected") != -1:
210                                 self.error = self.ERROR_UNDERRUN
211                         else:
212                                 self.error = self.ERROR_UNKNOWN
213
214 class RemoveESFiles(Task):
215         def __init__(self, job, demux_task):
216                 Task.__init__(self, job, "Remove temp. files")
217                 self.demux_task = demux_task
218                 self.setTool("/bin/rm")
219                 self.weighting = 10
220
221         def prepare(self):
222                 self.args += ["-f"]
223                 self.args += self.demux_task.generated_files.values()
224                 self.args += [self.demux_task.cutfile]
225
226 class DVDAuthorTask(Task):
227         def __init__(self, job):
228                 Task.__init__(self, job, "Authoring DVD")
229                 self.weighting = 20
230                 self.setTool("/usr/bin/dvdauthor")
231                 self.CWD = self.job.workspace
232                 self.args += ["-x", self.job.workspace+"/dvdauthor.xml"]
233                 self.menupreview = job.menupreview
234
235         def processOutputLine(self, line):
236                 print "[DVDAuthorTask] ", line[:-1]
237                 if not self.menupreview and line.startswith("STAT: Processing"):
238                         self.callback(self, [], stay_resident=True)
239                 elif line.startswith("STAT: VOBU"):
240                         try:
241                                 progress = int(line.split("MB")[0].split(" ")[-1])
242                                 if progress:
243                                         self.job.mplextask.progress = progress
244                                         print "[DVDAuthorTask] update mplextask progress:", self.job.mplextask.progress, "of", self.job.mplextask.end
245                         except:
246                                 print "couldn't set mux progress"
247
248 class DVDAuthorFinalTask(Task):
249         def __init__(self, job):
250                 Task.__init__(self, job, "dvdauthor finalize")
251                 self.setTool("/usr/bin/dvdauthor")
252                 self.args += ["-T", "-o", self.job.workspace + "/dvd"]
253
254 class WaitForResidentTasks(Task):
255         def __init__(self, job):
256                 Task.__init__(self, job, "waiting for dvdauthor to finalize")
257                 
258         def run(self, callback):
259                 print "waiting for %d resident task(s) %s to finish..." % (len(self.job.resident_tasks),str(self.job.resident_tasks))
260                 if self.job.resident_tasks == 0:
261                         callback(self, [])
262
263 class BurnTaskPostcondition(Condition):
264         RECOVERABLE = True
265         def check(self, task):
266                 if task.returncode == 0:
267                         return True
268                 elif task.error is None or task.error is task.ERROR_MINUSRWBUG:
269                         return True
270                 return False
271
272         def getErrorMessage(self, task):
273                 return {
274                         task.ERROR_NOTWRITEABLE: _("Medium is not a writeable DVD!"),
275                         task.ERROR_LOAD: _("Could not load Medium! No disc inserted?"),
276                         task.ERROR_SIZE: _("Content does not fit on DVD!"),
277                         task.ERROR_WRITE_FAILED: _("Write failed!"),
278                         task.ERROR_DVDROM: _("No (supported) DVDROM found!"),
279                         task.ERROR_ISOFS: _("Medium is not empty!"),
280                         task.ERROR_FILETOOLARGE: _("TS file is too large for ISO9660 level 1!"),
281                         task.ERROR_ISOTOOLARGE: _("ISO file is too large for this filesystem!"),
282                         task.ERROR_UNKNOWN: _("An unknown error occured!")
283                 }[task.error]
284
285 class BurnTask(Task):
286         ERROR_NOTWRITEABLE, ERROR_LOAD, ERROR_SIZE, ERROR_WRITE_FAILED, ERROR_DVDROM, ERROR_ISOFS, ERROR_FILETOOLARGE, ERROR_ISOTOOLARGE, ERROR_MINUSRWBUG, ERROR_UNKNOWN = range(10)
287         def __init__(self, job, extra_args=[], tool="/bin/growisofs"):
288                 Task.__init__(self, job, job.name)
289                 self.weighting = 500
290                 self.end = 120 # 100 for writing, 10 for buffer flush, 10 for closing disc
291                 self.postconditions.append(BurnTaskPostcondition())
292                 self.setTool(tool)
293                 self.args += extra_args
294         
295         def prepare(self):
296                 self.error = None
297
298         def processOutputLine(self, line):
299                 line = line[:-1]
300                 print "[GROWISOFS] %s" % line
301                 if line[8:14] == "done, ":
302                         self.progress = float(line[:6])
303                         print "progress:", self.progress
304                 elif line.find("flushing cache") != -1:
305                         self.progress = 100
306                 elif line.find("closing disc") != -1:
307                         self.progress = 110
308                 elif line.startswith(":-["):
309                         if line.find("ASC=30h") != -1:
310                                 self.error = self.ERROR_NOTWRITEABLE
311                         if line.find("ASC=24h") != -1:
312                                 self.error = self.ERROR_LOAD
313                         if line.find("SK=5h/ASC=A8h/ACQ=04h") != -1:
314                                 self.error = self.ERROR_MINUSRWBUG
315                         else:
316                                 self.error = self.ERROR_UNKNOWN
317                                 print "BurnTask: unknown error %s" % line
318                 elif line.startswith(":-("):
319                         if line.find("No space left on device") != -1:
320                                 self.error = self.ERROR_SIZE
321                         elif self.error == self.ERROR_MINUSRWBUG:
322                                 print "*sigh* this is a known bug. we're simply gonna assume everything is fine."
323                                 self.postconditions = []
324                         elif line.find("write failed") != -1:
325                                 self.error = self.ERROR_WRITE_FAILED
326                         elif line.find("unable to open64(") != -1 and line.find(",O_RDONLY): No such file or directory") != -1:
327                                 self.error = self.ERROR_DVDROM
328                         elif line.find("media is not recognized as recordable DVD") != -1:
329                                 self.error = self.ERROR_NOTWRITEABLE
330                         else:
331                                 self.error = self.ERROR_UNKNOWN
332                                 print "BurnTask: unknown error %s" % line
333                 elif line.startswith("FATAL:"):
334                         if line.find("already carries isofs!"):
335                                 self.error = self.ERROR_ISOFS
336                         else:
337                                 self.error = self.ERROR_UNKNOWN
338                                 print "BurnTask: unknown error %s" % line
339                 elif line.find("-allow-limited-size was not specified. There is no way do represent this file size. Aborting.") != -1:
340                         self.error = self.ERROR_FILETOOLARGE
341                 elif line.startswith("genisoimage: File too large."):
342                         self.error = self.ERROR_ISOTOOLARGE
343         
344         def setTool(self, tool):
345                 self.cmd = tool
346                 self.args = [tool]
347                 self.global_preconditions.append(ToolExistsPrecondition())
348
349 class RemoveDVDFolder(Task):
350         def __init__(self, job):
351                 Task.__init__(self, job, "Remove temp. files")
352                 self.setTool("/bin/rm")
353                 self.args += ["-rf", self.job.workspace]
354                 self.weighting = 10
355
356 class CheckDiskspaceTask(Task):
357         def __init__(self, job):
358                 Task.__init__(self, job, "Checking free space")
359                 totalsize = 0 # require an extra safety 50 MB
360                 maxsize = 0
361                 for title in job.project.titles:
362                         titlesize = title.estimatedDiskspace
363                         if titlesize > maxsize: maxsize = titlesize
364                         totalsize += titlesize
365                 diskSpaceNeeded = totalsize + maxsize
366                 job.estimateddvdsize = totalsize / 1024 / 1024
367                 totalsize += 50*1024*1024 # require an extra safety 50 MB
368                 self.global_preconditions.append(DiskspacePrecondition(diskSpaceNeeded))
369                 self.weighting = 5
370
371         def abort(self):
372                 self.finish(aborted = True)
373
374         def run(self, callback):
375                 failed_preconditions = self.checkPreconditions(True) + self.checkPreconditions(False)
376                 if len(failed_preconditions):
377                         callback(self, failed_preconditions)
378                         return
379                 self.callback = callback
380                 Task.processFinished(self, 0)
381
382 class PreviewTask(Task):
383         def __init__(self, job, path):
384                 Task.__init__(self, job, "Preview")
385                 self.postconditions.append(PreviewTaskPostcondition())
386                 self.job = job
387                 self.path = path
388                 self.weighting = 10
389
390         def run(self, callback):
391                 self.callback = callback
392                 if self.job.menupreview:
393                         self.previewProject()
394                 else:
395                         from Tools import Notifications
396                         Notifications.AddNotificationWithCallback(self.previewCB, MessageBox, _("Do you want to preview this DVD before burning?"), timeout = 60, default = False)
397
398         def abort(self):
399                 self.finish(aborted = True)
400         
401         def previewCB(self, answer):
402                 if answer == True:
403                         self.previewProject()
404                 else:
405                         self.closedCB(True)
406
407         def playerClosed(self):
408                 if self.job.menupreview:
409                         self.closedCB(True)
410                 else:
411                         from Tools import Notifications
412                         Notifications.AddNotificationWithCallback(self.closedCB, MessageBox, _("Do you want to burn this collection to DVD medium?") )
413
414         def closedCB(self, answer):
415                 if answer == True:
416                         Task.processFinished(self, 0)
417                 else:
418                         Task.processFinished(self, 1)
419
420         def previewProject(self):
421                 from Plugins.Extensions.DVDPlayer.plugin import DVDPlayer
422                 self.job.project.session.openWithCallback(self.playerClosed, DVDPlayer, dvd_filelist= [ self.path ])
423
424 class PreviewTaskPostcondition(Condition):
425         def check(self, task):
426                 return task.returncode == 0
427
428         def getErrorMessage(self, task):
429                 return "Cancel"
430
431 class ImagingPostcondition(Condition):
432         def check(self, task):
433                 return task.returncode == 0
434
435         def getErrorMessage(self, task):
436                 return _("Failed") + ": python-imaging"
437
438 class ImagePrepareTask(Task):
439         def __init__(self, job):
440                 Task.__init__(self, job, _("please wait, loading picture..."))
441                 self.postconditions.append(ImagingPostcondition())
442                 self.weighting = 20
443                 self.job = job
444                 self.Menus = job.Menus
445                 
446         def run(self, callback):
447                 self.callback = callback
448                 # we are doing it this weird way so that the TaskView Screen actually pops up before the spinner comes
449                 from enigma import eTimer
450                 self.delayTimer = eTimer()
451                 self.delayTimer.callback.append(self.conduct)
452                 self.delayTimer.start(10,1)
453
454         def conduct(self):
455                 try:
456                         from ImageFont import truetype
457                         from Image import open as Image_open
458                         s = self.job.project.settings
459                         self.Menus.im_bg_orig = Image_open(s.menubg.getValue())
460                         if self.Menus.im_bg_orig.size != (self.Menus.imgwidth, self.Menus.imgheight):
461                                 self.Menus.im_bg_orig = self.Menus.im_bg_orig.resize((720, 576))        
462                         self.Menus.fontsizes = s.font_size.getValue()
463                         fontface = s.font_face.getValue()
464                         self.Menus.fonts = [truetype(fontface, self.Menus.fontsizes[0]), truetype(fontface, self.Menus.fontsizes[1]), truetype(fontface, self.Menus.fontsizes[2])]
465                         Task.processFinished(self, 0)
466                 except:
467                         Task.processFinished(self, 1)
468
469 class MenuImageTask(Task):
470         def __init__(self, job, menu_count, spuxmlfilename, menubgpngfilename, highlightpngfilename):
471                 Task.__init__(self, job, "Create Menu %d Image" % menu_count)
472                 self.postconditions.append(ImagingPostcondition())
473                 self.weighting = 10
474                 self.job = job
475                 self.Menus = job.Menus
476                 self.menu_count = menu_count
477                 self.spuxmlfilename = spuxmlfilename
478                 self.menubgpngfilename = menubgpngfilename
479                 self.highlightpngfilename = highlightpngfilename
480
481         def run(self, callback):
482                 self.callback = callback
483                 try:
484                         import ImageDraw, Image, os
485                         s = self.job.project.settings
486                         fonts = self.Menus.fonts
487                         im_bg = self.Menus.im_bg_orig.copy()
488                         im_high = Image.new("P", (self.Menus.imgwidth, self.Menus.imgheight), 0)
489                         im_high.putpalette(self.Menus.spu_palette)
490                         draw_bg = ImageDraw.Draw(im_bg)
491                         draw_high = ImageDraw.Draw(im_high)
492                         if self.menu_count == 1:
493                                 headline = s.name.getValue().decode("utf-8")
494                                 textsize = draw_bg.textsize(headline, font=fonts[0])
495                                 if textsize[0] > self.Menus.imgwidth:
496                                         offset = (0 , 20)
497                                 else:
498                                         offset = (((self.Menus.imgwidth-textsize[0]) / 2) , 20)
499                                 draw_bg.text(offset, headline, fill=self.Menus.color_headline, font=fonts[0])
500                         spuxml = """<?xml version="1.0" encoding="utf-8"?>
501                 <subpictures>
502                 <stream>
503                 <spu 
504                 highlight="%s"
505                 transparent="%02x%02x%02x"
506                 start="00:00:00.00"
507                 force="yes" >""" % (self.highlightpngfilename, self.Menus.spu_palette[0], self.Menus.spu_palette[1], self.Menus.spu_palette[2])
508                         s_top, s_rows, s_left = s.space.getValue()
509                         rowheight = (self.Menus.fontsizes[1]+self.Menus.fontsizes[2]+s_rows)
510                         menu_start_title = (self.menu_count-1)*self.job.titles_per_menu + 1
511                         menu_end_title = (self.menu_count)*self.job.titles_per_menu + 1
512                         nr_titles = len(self.job.project.titles)
513                         if menu_end_title > nr_titles:
514                                 menu_end_title = nr_titles+1
515                         menu_i = 0
516                         for title_no in range( menu_start_title , menu_end_title ):
517                                 menu_i += 1
518                                 title = self.job.project.titles[title_no-1]
519                                 top = s_top + ( menu_i * rowheight )
520                                 titleText = title.formatDVDmenuText(s.titleformat.getValue(), title_no).decode("utf-8")
521                                 draw_bg.text((s_left,top), titleText, fill=self.Menus.color_button, font=fonts[1])
522                                 draw_high.text((s_left,top), titleText, fill=1, font=self.Menus.fonts[1])
523                                 subtitleText = title.formatDVDmenuText(s.subtitleformat.getValue(), title_no).decode("utf-8")
524                                 draw_bg.text((s_left,top+36), subtitleText, fill=self.Menus.color_button, font=fonts[2])
525                                 bottom = top+rowheight
526                                 if bottom > self.Menus.imgheight:
527                                         bottom = self.Menus.imgheight
528                                 spuxml += """
529                 <button name="button%s" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (str(title_no).zfill(2),s_left,self.Menus.imgwidth,top,bottom )
530                         if self.menu_count < self.job.nr_menus:
531                                 next_page_text = ">>>"
532                                 textsize = draw_bg.textsize(next_page_text, font=fonts[1])
533                                 offset = ( self.Menus.imgwidth-textsize[0]-2*s_left, s_top + ( self.job.titles_per_menu * rowheight ) )
534                                 draw_bg.text(offset, next_page_text, fill=self.Menus.color_button, font=fonts[1])
535                                 draw_high.text(offset, next_page_text, fill=1, font=fonts[1])
536                                 spuxml += """
537                 <button name="button_next" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (offset[0],offset[0]+textsize[0],offset[1],offset[1]+textsize[1])
538                         if self.menu_count > 1:
539                                 prev_page_text = "<<<"
540                                 textsize = draw_bg.textsize(prev_page_text, font=fonts[1])
541                                 offset = ( 2*s_left, s_top + ( self.job.titles_per_menu * rowheight ) )
542                                 draw_bg.text(offset, prev_page_text, fill=self.Menus.color_button, font=fonts[1])
543                                 draw_high.text(offset, prev_page_text, fill=1, font=fonts[1])
544                                 spuxml += """
545                 <button name="button_prev" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (offset[0],offset[0]+textsize[0],offset[1],offset[1]+textsize[1])
546                         del draw_bg
547                         del draw_high
548                         fd=open(self.menubgpngfilename,"w")
549                         im_bg.save(fd,"PNG")
550                         fd.close()
551                         fd=open(self.highlightpngfilename,"w")
552                         im_high.save(fd,"PNG")
553                         fd.close()
554                         spuxml += """
555                 </spu>
556                 </stream>
557                 </subpictures>"""
558         
559                         f = open(self.spuxmlfilename, "w")
560                         f.write(spuxml)
561                         f.close()
562                         Task.processFinished(self, 0)
563                 except:
564                         Task.processFinished(self, 1)
565
566 class Menus:
567         def __init__(self, job):
568                 self.job = job
569                 job.Menus = self
570                 
571                 s = self.job.project.settings
572
573                 self.imgwidth = 720
574                 self.imgheight = 576
575
576                 self.color_headline = tuple(s.color_headline.getValue())
577                 self.color_button = tuple(s.color_button.getValue())
578                 self.color_highlight = tuple(s.color_highlight.getValue())
579                 self.spu_palette = [ 0x60, 0x60, 0x60 ] + s.color_highlight.getValue()
580
581                 ImagePrepareTask(job)
582                 nr_titles = len(job.project.titles)
583                 if nr_titles < 6:
584                         job.titles_per_menu = 5
585                 else:
586                         job.titles_per_menu = 4
587                 job.nr_menus = ((nr_titles+job.titles_per_menu-1)/job.titles_per_menu)
588
589                 #a new menu_count every 4 titles (1,2,3,4->1 ; 5,6,7,8->2 etc.)
590                 for menu_count in range(1 , job.nr_menus+1):
591                         num = str(menu_count)
592                         spuxmlfilename = job.workspace+"/spumux"+num+".xml"
593                         menubgpngfilename = job.workspace+"/dvd_menubg"+num+".png"
594                         highlightpngfilename = job.workspace+"/dvd_highlight"+num+".png"
595                         MenuImageTask(job, menu_count, spuxmlfilename, menubgpngfilename, highlightpngfilename)
596                         png2yuvTask(job, menubgpngfilename, job.workspace+"/dvdmenubg"+num+".yuv")
597                         menubgm2vfilename = job.workspace+"/dvdmenubg"+num+".mv2"
598                         mpeg2encTask(job, job.workspace+"/dvdmenubg"+num+".yuv", menubgm2vfilename)
599                         menubgmpgfilename = job.workspace+"/dvdmenubg"+num+".mpg"
600                         menuaudiofilename = s.menuaudio.getValue()
601                         MplexTask(job, outputfile=menubgmpgfilename, inputfiles = [menubgm2vfilename, menuaudiofilename], weighting = 20)
602                         menuoutputfilename = job.workspace+"/dvdmenu"+num+".mpg"
603                         spumuxTask(job, spuxmlfilename, menubgmpgfilename, menuoutputfilename)
604                 
605 def CreateAuthoringXML_singleset(job):
606         nr_titles = len(job.project.titles)
607         mode = job.project.settings.authormode.getValue()
608         authorxml = []
609         authorxml.append('<?xml version="1.0" encoding="utf-8"?>\n')
610         authorxml.append(' <dvdauthor dest="' + (job.workspace+"/dvd") + '">\n')
611         authorxml.append('  <vmgm>\n')
612         authorxml.append('   <menus>\n')
613         authorxml.append('    <pgc>\n')
614         authorxml.append('     <vob file="' + job.project.settings.vmgm.getValue() + '" />\n', )
615         if mode.startswith("menu"):
616                 authorxml.append('     <post> jump titleset 1 menu; </post>\n')
617         else:
618                 authorxml.append('     <post> jump title 1; </post>\n')
619         authorxml.append('    </pgc>\n')
620         authorxml.append('   </menus>\n')
621         authorxml.append('  </vmgm>\n')
622         authorxml.append('  <titleset>\n')
623         if mode.startswith("menu"):
624                 authorxml.append('   <menus>\n')
625                 authorxml.append('    <video aspect="4:3"/>\n')
626                 for menu_count in range(1 , job.nr_menus+1):
627                         if menu_count == 1:
628                                 authorxml.append('    <pgc entry="root">\n')
629                         else:
630                                 authorxml.append('    <pgc>\n')
631                         menu_start_title = (menu_count-1)*job.titles_per_menu + 1
632                         menu_end_title = (menu_count)*job.titles_per_menu + 1
633                         if menu_end_title > nr_titles:
634                                 menu_end_title = nr_titles+1
635                         for i in range( menu_start_title , menu_end_title ):
636                                 authorxml.append('     <button name="button' + (str(i).zfill(2)) + '"> jump title ' + str(i) +'; </button>\n')
637                         if menu_count > 1:
638                                 authorxml.append('     <button name="button_prev"> jump menu ' + str(menu_count-1) + '; </button>\n')
639                         if menu_count < job.nr_menus:
640                                 authorxml.append('     <button name="button_next"> jump menu ' + str(menu_count+1) + '; </button>\n')
641                         menuoutputfilename = job.workspace+"/dvdmenu"+str(menu_count)+".mpg"
642                         authorxml.append('     <vob file="' + menuoutputfilename + '" pause="inf"/>\n')
643                         authorxml.append('    </pgc>\n')
644                 authorxml.append('   </menus>\n')
645         authorxml.append('   <titles>\n')
646         for i in range( nr_titles ):
647                 chapters = ','.join(job.project.titles[i].getChapterMarks())
648                 title_no = i+1
649                 title_filename = job.workspace + "/dvd_title_%d.mpg" % (title_no)
650                 if job.menupreview:
651                         LinkTS(job, job.project.settings.vmgm.getValue(), title_filename)
652                 else:
653                         MakeFifoNode(job, title_no)
654                 if mode.endswith("linked") and title_no < nr_titles:
655                         post_tag = "jump title %d;" % ( title_no+1 )
656                 elif mode.startswith("menu"):
657                         post_tag = "call vmgm menu 1;"
658                 else:   post_tag = ""
659
660                 authorxml.append('    <pgc>\n')
661                 authorxml.append('     <vob file="' + title_filename + '" chapters="' + chapters + '" />\n')
662                 authorxml.append('     <post> ' + post_tag + ' </post>\n')
663                 authorxml.append('    </pgc>\n')
664
665         authorxml.append('   </titles>\n')
666         authorxml.append('  </titleset>\n')
667         authorxml.append(' </dvdauthor>\n')
668         f = open(job.workspace+"/dvdauthor.xml", "w")
669         for x in authorxml:
670                 f.write(x)
671         f.close()
672
673 def CreateAuthoringXML_multiset(job):
674         nr_titles = len(job.project.titles)
675         mode = job.project.settings.authormode.getValue()
676         authorxml = []
677         authorxml.append('<?xml version="1.0" encoding="utf-8"?>\n')
678         authorxml.append(' <dvdauthor dest="' + (job.workspace+"/dvd") + '" jumppad="yes">\n')
679         authorxml.append('  <vmgm>\n')
680         authorxml.append('   <menus>\n')
681         authorxml.append('    <video aspect="4:3"/>\n')
682         if mode.startswith("menu"):
683                 for menu_count in range(1 , job.nr_menus+1):
684                         authorxml.append('    <pgc>\n')
685                         menu_start_title = (menu_count-1)*job.titles_per_menu + 1
686                         menu_end_title = (menu_count)*job.titles_per_menu + 1
687                         if menu_end_title > nr_titles:
688                                 menu_end_title = nr_titles+1
689                         for i in range( menu_start_title , menu_end_title ):
690                                 authorxml.append('     <button name="button' + (str(i).zfill(2)) + '"> jump titleset ' + str(i) +' title 1; </button>\n')
691                         if menu_count > 1:
692                                 authorxml.append('     <button name="button_prev"> jump menu ' + str(menu_count-1) + '; </button>\n')
693                         if menu_count < job.nr_menus:
694                                 authorxml.append('     <button name="button_next"> jump menu ' + str(menu_count+1) + '; </button>\n')
695                         menuoutputfilename = job.workspace+"/dvdmenu"+str(menu_count)+".mpg"
696                         authorxml.append('     <vob file="' + menuoutputfilename + '" pause="inf"/>\n')
697                         authorxml.append('    </pgc>\n')
698         else:
699                 authorxml.append('    <pgc>\n')
700                 authorxml.append('     <vob file="' + job.project.settings.vmgm.getValue() + '" />\n' )
701                 authorxml.append('     <post> jump titleset 1 title 1; </post>\n')
702                 authorxml.append('    </pgc>\n')
703         authorxml.append('   </menus>\n')
704         authorxml.append('  </vmgm>\n')
705
706         for i in range( nr_titles ):
707                 title = job.project.titles[i]
708                 authorxml.append('  <titleset>\n')
709                 authorxml.append('   <titles>\n')
710                 for audiotrack in title.properties.audiotracks:
711                         active = audiotrack.active.getValue()
712                         if active:
713                                 format = audiotrack.format.getValue()
714                                 language = audiotrack.language.getValue()
715                                 audio_tag = '    <audio format="%s"' % format
716                                 if language != "nolang":
717                                         audio_tag += ' lang="%s"' % language
718                                 audio_tag += ' />\n'
719                                 authorxml.append(audio_tag)
720                 aspect = title.properties.aspect.getValue()
721                 video_tag = '    <video aspect="'+aspect+'"'
722                 if title.properties.widescreen.getValue() == "4:3":
723                         video_tag += ' widescreen="'+title.properties.widescreen.getValue()+'"'
724                 video_tag += ' />\n'
725                 authorxml.append(video_tag)
726                 chapters = ','.join(title.getChapterMarks())
727                 title_no = i+1
728                 title_filename = job.workspace + "/dvd_title_%d.mpg" % (title_no)
729                 if job.menupreview:
730                         LinkTS(job, job.project.settings.vmgm.getValue(), title_filename)
731                 else:
732                         MakeFifoNode(job, title_no)
733                 if mode.endswith("linked") and title_no < nr_titles:
734                         post_tag = "jump titleset %d title 1;" % ( title_no+1 )
735                 elif mode.startswith("menu"):
736                         post_tag = "call vmgm menu 1;"
737                 else:   post_tag = ""
738
739                 authorxml.append('    <pgc>\n')
740                 authorxml.append('     <vob file="' + title_filename + '" chapters="' + chapters + '" />\n')
741                 authorxml.append('     <post> ' + post_tag + ' </post>\n')
742                 authorxml.append('    </pgc>\n')
743                 authorxml.append('   </titles>\n')
744                 authorxml.append('  </titleset>\n')
745         authorxml.append(' </dvdauthor>\n')
746         f = open(job.workspace+"/dvdauthor.xml", "w")
747         for x in authorxml:
748                 f.write(x)
749         f.close()
750
751 def getISOfilename(isopath, volName):
752         from Tools.Directories import fileExists
753         i = 0
754         filename = isopath+'/'+volName+".iso"
755         while fileExists(filename):
756                 i = i+1
757                 filename = isopath+'/'+volName + str(i).zfill(3) + ".iso"
758         return filename
759
760 class DVDJob(Job):
761         def __init__(self, project, menupreview=False):
762                 Job.__init__(self, "DVDBurn Job")
763                 self.project = project
764                 from time import strftime
765                 from Tools.Directories import SCOPE_HDD, resolveFilename, createDir
766                 new_workspace = resolveFilename(SCOPE_HDD) + "tmp/" + strftime("%Y%m%d%H%M%S")
767                 createDir(new_workspace, True)
768                 self.workspace = new_workspace
769                 self.project.workspace = self.workspace
770                 self.menupreview = menupreview
771                 self.conduct()
772
773         def conduct(self):
774                 CheckDiskspaceTask(self)
775                 if self.project.settings.authormode.getValue().startswith("menu") or self.menupreview:
776                         Menus(self)
777                 if self.project.settings.titlesetmode.getValue() == "multi":
778                         CreateAuthoringXML_multiset(self)
779                 else:
780                         CreateAuthoringXML_singleset(self)
781
782                 DVDAuthorTask(self)
783                 
784                 nr_titles = len(self.project.titles)
785
786                 if self.menupreview:
787                         PreviewTask(self, self.workspace + "/dvd/VIDEO_TS/")
788                 else:
789                         for self.i in range(nr_titles):
790                                 self.title = self.project.titles[self.i]
791                                 link_name =  self.workspace + "/source_title_%d.ts" % (self.i+1)
792                                 title_filename = self.workspace + "/dvd_title_%d.mpg" % (self.i+1)
793                                 LinkTS(self, self.title.inputfile, link_name)
794                                 demux = DemuxTask(self, link_name)
795                                 self.mplextask = MplexTask(self, outputfile=title_filename, demux_task=demux)
796                                 self.mplextask.end = self.estimateddvdsize
797                                 #RemoveESFiles(self, demux)
798                         WaitForResidentTasks(self)
799                         PreviewTask(self, self.workspace + "/dvd/VIDEO_TS/")
800                         output = self.project.settings.output.getValue()
801                         volName = self.project.settings.name.getValue()
802                         if output == "dvd":
803                                 self.name = _("Burn DVD")
804                                 tool = "/bin/growisofs"
805                                 burnargs = [ "-Z", "/dev/" + harddiskmanager.getCD(), "-dvd-compat" ]
806                         elif output == "iso":
807                                 self.name = _("Create DVD-ISO")
808                                 tool = "/usr/bin/mkisofs"
809                                 isopathfile = getISOfilename(self.project.settings.isopath.getValue(), volName)
810                                 burnargs = [ "-o", isopathfile ]
811                         burnargs += [ "-dvd-video", "-publisher", "Dreambox", "-V", volName, self.workspace + "/dvd" ]
812                         BurnTask(self, burnargs, tool)
813                 RemoveDVDFolder(self)
814
815 class DVDdataJob(Job):
816         def __init__(self, project):
817                 Job.__init__(self, "Data DVD Burn")
818                 self.project = project
819                 from time import strftime
820                 from Tools.Directories import SCOPE_HDD, resolveFilename, createDir
821                 new_workspace = resolveFilename(SCOPE_HDD) + "tmp/" + strftime("%Y%m%d%H%M%S") + "/dvd/"
822                 createDir(new_workspace, True)
823                 self.workspace = new_workspace
824                 self.project.workspace = self.workspace
825                 self.conduct()
826
827         def conduct(self):
828                 if self.project.settings.output.getValue() == "iso":
829                         CheckDiskspaceTask(self)
830                 nr_titles = len(self.project.titles)
831                 for self.i in range(nr_titles):
832                         title = self.project.titles[self.i]
833                         filename = title.inputfile.rstrip("/").rsplit("/",1)[1]
834                         link_name =  self.workspace + filename
835                         LinkTS(self, title.inputfile, link_name)
836                         CopyMeta(self, title.inputfile)
837
838                 output = self.project.settings.output.getValue()
839                 volName = self.project.settings.name.getValue()
840                 tool = "/bin/growisofs"
841                 if output == "dvd":
842                         self.name = _("Burn DVD")
843                         burnargs = [ "-Z", "/dev/" + harddiskmanager.getCD(), "-dvd-compat" ]
844                 elif output == "iso":
845                         tool = "/usr/bin/mkisofs"
846                         self.name = _("Create DVD-ISO")
847                         isopathfile = getISOfilename(self.project.settings.isopath.getValue(), volName)
848                         burnargs = [ "-o", isopathfile ]
849                 if self.project.settings.dataformat.getValue() == "iso9660_1":
850                         burnargs += ["-iso-level", "1" ]
851                 elif self.project.settings.dataformat.getValue() == "iso9660_4":
852                         burnargs += ["-iso-level", "4", "-allow-limited-size" ]
853                 elif self.project.settings.dataformat.getValue() == "udf":
854                         burnargs += ["-udf", "-allow-limited-size" ]
855                 burnargs += [ "-publisher", "Dreambox", "-V", volName, "-follow-links", self.workspace ]
856                 BurnTask(self, burnargs, tool)
857                 RemoveDVDFolder(self)
858
859 class DVDisoJob(Job):
860         def __init__(self, project, imagepath):
861                 Job.__init__(self, _("Burn DVD"))
862                 self.project = project
863                 self.menupreview = False
864                 if imagepath.endswith(".iso"):
865                         PreviewTask(self, imagepath)
866                         burnargs = [ "-Z", "/dev/" + harddiskmanager.getCD() + '='+imagepath, "-dvd-compat" ]
867                 else:
868                         PreviewTask(self, imagepath + "/VIDEO_TS/")
869                         volName = self.project.settings.name.getValue()
870                         burnargs = [ "-Z", "/dev/" + harddiskmanager.getCD(), "-dvd-compat" ]
871                         burnargs += [ "-dvd-video", "-publisher", "Dreambox", "-V", volName, imagepath ]
872                 tool = "/bin/growisofs"
873                 BurnTask(self, burnargs, tool)