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