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