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