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