1 from Components.Task import Task, Job, job_manager, DiskspacePrecondition, Condition
2 from Screens.MessageBox import MessageBox
4 class png2yuvTask(Task):
5 def __init__(self, job, inputfile, outputfile):
6 Task.__init__(self, job, "Creating menu video")
7 self.setTool("/usr/bin/png2yuv")
8 self.args += ["-n1", "-Ip", "-f25", "-j", inputfile]
9 self.dumpFile = outputfile
12 def run(self, callback, task_progress_changed):
13 Task.run(self, callback, task_progress_changed)
14 self.container.dumpToFile(self.dumpFile)
16 def processStderr(self, data):
17 print "[png2yuvTask]", data
19 def processStdout(self, data):
22 class mpeg2encTask(Task):
23 def __init__(self, job, inputfile, outputfile):
24 Task.__init__(self, job, "Encoding menu video")
25 self.setTool("/usr/bin/mpeg2enc")
26 self.args += ["-f8", "-np", "-a2", "-o", outputfile]
27 self.inputFile = inputfile
30 def run(self, callback, task_progress_changed):
31 Task.run(self, callback, task_progress_changed)
32 self.container.readFromFile(self.inputFile)
34 def processOutputLine(self, line):
35 print "[mpeg2encTask]", line[:-1]
37 class spumuxTask(Task):
38 def __init__(self, job, xmlfile, inputfile, outputfile):
39 Task.__init__(self, job, "Muxing buttons into menu")
40 self.setTool("/usr/bin/spumux")
41 self.args += [xmlfile]
42 self.inputFile = inputfile
43 self.dumpFile = outputfile
46 def run(self, callback, task_progress_changed):
47 Task.run(self, callback, task_progress_changed)
48 self.container.dumpToFile(self.dumpFile)
49 self.container.readFromFile(self.inputFile)
51 def processStderr(self, data):
52 print "[spumuxTask]", data[:-1]
54 def processStdout(self, data):
57 class MakeFifoNode(Task):
58 def __init__(self, job, number):
59 Task.__init__(self, job, "Make FIFO nodes")
60 self.setTool("/bin/mknod")
61 nodename = self.job.workspace + "/dvd_title_%d" % number + ".mpg"
62 self.args += [nodename, "p"]
66 def __init__(self, job, sourcefile, link_name):
67 Task.__init__(self, job, "Creating symlink for source titles")
68 self.setTool("/bin/ln")
69 self.args += ["-s", sourcefile, link_name]
72 class DemuxTask(Task):
73 def __init__(self, job, inputfile):
74 Task.__init__(self, job, "Demux video into ES")
75 title = job.project.titles[job.i]
76 self.global_preconditions.append(DiskspacePrecondition(title.estimatedDiskspace))
77 self.setTool("/usr/bin/projectx")
78 self.generated_files = [ ]
82 self.cutfile = self.job.workspace + "/cut_%d.Xcl" % (job.i+1)
83 self.cutlist = title.cutlist
84 self.args += [inputfile, "-demux", "-out", self.job.workspace ]
85 if len(self.cutlist) > 1:
86 self.args += [ "-cut", self.cutfile ]
91 def processOutputLine(self, line):
93 MSG_NEW_FILE = "---> new File: "
94 MSG_PROGRESS = "[PROGRESS] "
96 if line.startswith(MSG_NEW_FILE):
97 file = line[len(MSG_NEW_FILE):]
100 self.haveNewFile(file)
101 elif line.startswith(MSG_PROGRESS):
102 progress = line[len(MSG_PROGRESS):]
103 self.haveProgress(progress)
105 def haveNewFile(self, file):
106 print "PRODUCED FILE [%s]" % file
107 self.generated_files.append(file)
109 def haveProgress(self, progress):
110 #print "PROGRESS [%s]" % progress
111 MSG_CHECK = "check & synchronize audio file"
113 if progress == "preparing collection(s)...":
115 elif progress[:len(MSG_CHECK)] == MSG_CHECK:
120 p = p - 1 + self.prog_state * 100
121 if p > self.progress:
127 def writeCutfile(self):
128 f = open(self.cutfile, "w")
129 f.write("CollectionPanel.CutMode=4\n")
130 for p in self.cutlist:
138 f.write("%02d:%02d:%02d\n" % (h, m, s))
141 def cleanup(self, failed):
144 for f in self.generated_files:
147 class MplexTaskPostcondition(Condition):
148 def check(self, task):
149 return task.error is None
151 def getErrorMessage(self, task):
152 print "[MplexTaskPostcondition] getErrorMessage", task
154 task.ERROR_UNDERRUN: ("Can't multiplex source video!"),
155 task.ERROR_UNKNOWN: ("An unknown error occured!")
158 class MplexTask(Task):
159 ERROR_UNDERRUN, ERROR_UNKNOWN = range(2)
160 def __init__(self, job, outputfile, inputfiles=None, demux_task=None):
161 Task.__init__(self, job, "Mux ES into PS")
163 self.demux_task = demux_task
164 self.postconditions.append(MplexTaskPostcondition())
165 self.setTool("/usr/bin/mplex")
166 self.args += ["-f8", "-o", outputfile, "-v1"]
168 self.args += inputfiles
173 self.args += self.demux_task.generated_files
175 def processOutputLine(self, line):
176 print "[MplexTask] processOutputLine=", line[:-1]
177 if line.startswith("**ERROR:"):
178 if line.find("Frame data under-runs detected") != -1:
179 self.error = self.ERROR_UNDERRUN
180 print "BUFFER UNDERRUN ERROR !!!"
182 self.error = self.ERROR_UNKNOWN
184 class RemoveESFiles(Task):
185 def __init__(self, job, demux_task):
186 Task.__init__(self, job, "Remove temp. files")
187 self.demux_task = demux_task
188 self.setTool("/bin/rm")
192 self.args += self.demux_task.generated_files
193 self.args += [self.demux_task.cutfile]
195 class DVDAuthorTask(Task):
196 def __init__(self, job, diskspaceNeeded):
197 Task.__init__(self, job, "Authoring DVD")
199 self.global_preconditions.append(DiskspacePrecondition(diskspaceNeeded))
201 self.setTool("/usr/bin/dvdauthor")
202 self.CWD = self.job.workspace
203 self.args += ["-x", self.job.workspace+"/dvdauthor.xml"]
204 self.menupreview = job.menupreview
206 def processOutputLine(self, line):
207 print "[DVDAuthorTask] processOutputLine=", line[:-1]
208 if not self.menupreview and line.startswith("STAT: Processing"):
209 self.callback(self, [], stay_resident=True)
211 class DVDAuthorFinalTask(Task):
212 def __init__(self, job):
213 Task.__init__(self, job, "dvdauthor finalize")
214 self.setTool("/usr/bin/dvdauthor")
215 self.args += ["-T", "-o", self.job.workspace + "/dvd"]
217 class WaitForResidentTasks(Task):
218 def __init__(self, job):
219 Task.__init__(self, job, "waiting for dvdauthor to finalize")
221 def run(self, callback, task_progress_changed):
222 print "waiting for %d resident task(s) %s to finish..." % (len(self.job.resident_tasks),str(self.job.resident_tasks))
223 if self.job.resident_tasks == 0:
226 class BurnTaskPostcondition(Condition):
228 def check(self, task):
229 return task.error is None
231 def getErrorMessage(self, task):
233 task.ERROR_MEDIA: _("Medium is not a writeable DVD!"),
234 task.ERROR_SIZE: _("Content does not fit on DVD!"),
235 task.ERROR_WRITE_FAILED: _("Write failed!"),
236 task.ERROR_DVDROM: _("No (supported) DVDROM found!"),
237 task.ERROR_ISOFS: _("Medium is not empty!"),
238 task.ERROR_UNKNOWN: _("An unknown error occured!")
241 class BurnTask(Task):
242 ERROR_MEDIA, ERROR_SIZE, ERROR_WRITE_FAILED, ERROR_DVDROM, ERROR_ISOFS, ERROR_UNKNOWN = range(6)
243 def __init__(self, job):
244 Task.__init__(self, job, "burn")
247 self.end = 120 # 100 for writing, 10 for buffer flush, 10 for closing disc
248 self.postconditions.append(BurnTaskPostcondition())
249 self.setTool("/bin/growisofs")
250 volName = self.getASCIIname(job.project.settings.name.getValue())
251 self.args += ["-dvd-video", "-dvd-compat", "-Z", "/dev/cdroms/cdrom0", "-V", volName, "-P", "Dreambox", "-use-the-force-luke=dummy", self.job.workspace + "/dvd"]
253 def getASCIIname(self, name):
255 for char in name.decode("utf-8").encode("ascii","replace"):
256 if ord(char) <= 0x20 or ( ord(char) >= 0x3a and ord(char) <= 0x40 ):
265 def processOutputLine(self, line):
267 print "[GROWISOFS] %s" % line
268 if line[8:14] == "done, ":
269 self.progress = float(line[:6])
270 print "progress:", self.progress
271 elif line.find("flushing cache") != -1:
273 elif line.find("closing disc") != -1:
275 elif line.startswith(":-["):
276 if line.find("ASC=30h") != -1:
277 self.error = self.ERROR_MEDIA
279 self.error = self.ERROR_UNKNOWN
280 print "BurnTask: unknown error %s" % line
281 elif line.startswith(":-("):
282 if line.find("No space left on device") != -1:
283 self.error = self.ERROR_SIZE
284 elif line.find("write failed") != -1:
285 self.error = self.ERROR_WRITE_FAILED
286 elif line.find("unable to open64(\"/dev/cdroms/cdrom0\",O_RDONLY): No such file or directory") != -1: # fixme
287 self.error = self.ERROR_DVDROM
288 elif line.find("media is not recognized as recordable DVD") != -1:
289 self.error = self.ERROR_MEDIA
291 self.error = self.ERROR_UNKNOWN
292 print "BurnTask: unknown error %s" % line
293 elif line.startswith("FATAL:"):
294 if line.find("already carries isofs!"):
295 self.error = self.ERROR_ISOFS
297 self.error = self.ERROR_UNKNOWN
298 print "BurnTask: unknown error %s" % line
300 class RemoveDVDFolder(Task):
301 def __init__(self, job):
302 Task.__init__(self, job, "Remove temp. files")
303 self.setTool("/bin/rm")
304 self.args += ["-rf", self.job.workspace]
306 class PreviewTask(Task):
307 def __init__(self, job):
308 Task.__init__(self, job, "Preview")
309 self.postconditions.append(PreviewTaskPostcondition())
312 def run(self, callback, task_progress_changed):
313 self.callback = callback
314 self.task_progress_changed = task_progress_changed
315 if self.job.project.waitboxref:
316 self.job.project.waitboxref.close()
317 if self.job.menupreview:
318 self.waitAndOpenPlayer()
320 self.job.project.session.openWithCallback(self.previewCB, MessageBox, _("Do you want to preview this DVD before burning?"), timeout = 60, default = False)
322 def previewCB(self, answer):
324 self.waitAndOpenPlayer()
328 def playerClosed(self):
329 if self.job.menupreview:
332 self.job.project.session.openWithCallback(self.closedCB, MessageBox, _("Do you want to burn this collection to DVD medium?") )
334 def closedCB(self, answer):
336 Task.processFinished(self, 0)
338 Task.processFinished(self, 1)
340 def waitAndOpenPlayer(self):
341 from enigma import eTimer
342 self.delayTimer = eTimer()
343 self.delayTimer.callback.append(self.previewProject)
344 self.delayTimer.start(10,1)
346 def previewProject(self):
347 from Plugins.Extensions.DVDPlayer.plugin import DVDPlayer
348 self.job.project.session.openWithCallback(self.playerClosed, DVDPlayer, dvd_filelist= [ self.job.project.workspace + "/dvd/VIDEO_TS/" ])
350 class PreviewTaskPostcondition(Condition):
351 def check(self, task):
352 return task.returncode == 0
354 def getErrorMessage(self, task):
357 def getTitlesPerMenu(nr_titles):
362 return titles_per_menu
364 def formatTitle(template, title, track):
365 template = template.replace("$i", str(track))
366 template = template.replace("$t", title.name)
367 template = template.replace("$d", title.descr)
368 template = template.replace("$c", str(len(title.chaptermarks)+1))
369 template = template.replace("$A", str(title.audiotracks))
370 template = template.replace("$f", title.inputfile)
371 template = template.replace("$C", title.channel)
373 lengthstring = "%d:%02d:%02d" % (l/3600, l%3600/60, l%60)
374 template = template.replace("$l", lengthstring)
376 template = template.replace("$Y", str(title.timeCreate[0]))
377 template = template.replace("$M", str(title.timeCreate[1]))
378 template = template.replace("$D", str(title.timeCreate[2]))
379 timestring = "%d:%02d" % (title.timeCreate[3], title.timeCreate[4])
380 template = template.replace("$T", timestring)
382 template = template.replace("$Y", "").replace("$M", "").replace("$D", "").replace("$T", "")
383 return template.decode("utf-8")
385 def CreateMenus(job):
386 import os, Image, ImageDraw, ImageFont
389 s = job.project.settings
390 im_bg_orig = Image.open(s.menubg.getValue())
391 if im_bg_orig.size != (imgwidth, imgheight):
392 im_bg_orig = im_bg_orig.resize((720, 576))
394 fontsizes = s.font_size.getValue()
395 fontface = s.font_face.getValue()
397 font0 = ImageFont.truetype(fontface, fontsizes[0])
398 font1 = ImageFont.truetype(fontface, fontsizes[1])
399 font2 = ImageFont.truetype(fontface, fontsizes[2])
401 color_headline = tuple(s.color_headline.getValue())
402 color_button = tuple(s.color_button.getValue())
403 color_highlight = tuple(s.color_highlight.getValue())
404 spu_palette = [ 0x60, 0x60, 0x60 ] + s.color_highlight.getValue()
406 nr_titles = len(job.project.titles)
407 titles_per_menu = getTitlesPerMenu(nr_titles)
408 job.nr_menus = ((nr_titles+titles_per_menu-1)/titles_per_menu)
410 #a new menu_count every 5 titles (1,2,3,4,5->1 ; 6,7,8,9,10->2 etc.)
411 for menu_count in range(1 , job.nr_menus+1):
412 im_bg = im_bg_orig.copy()
413 im_high = Image.new("P", (imgwidth, imgheight), 0)
414 im_high.putpalette(spu_palette)
415 draw_bg = ImageDraw.Draw(im_bg)
416 draw_high = ImageDraw.Draw(im_high)
419 headline = s.name.getValue().decode("utf-8")
420 textsize = draw_bg.textsize(headline, font=font0)
421 if textsize[0] > imgwidth:
424 offset = (((imgwidth-textsize[0]) / 2) , 20)
425 draw_bg.text(offset, headline, fill=color_headline, font=font0)
427 menubgpngfilename = job.workspace+"/dvd_menubg"+str(menu_count)+".png"
428 highlightpngfilename = job.workspace+"/dvd_highlight"+str(menu_count)+".png"
429 spuxml = """<?xml version="1.0" encoding="utf-8"?>
434 transparent="%02x%02x%02x"
436 force="yes" >""" % (highlightpngfilename, spu_palette[0], spu_palette[1], spu_palette[2])
437 s_top, s_rows, s_left = s.space.getValue()
438 rowheight = (fontsizes[1]+fontsizes[2]+s_rows)
439 menu_start_title = (menu_count-1)*titles_per_menu + 1
440 menu_end_title = (menu_count)*titles_per_menu + 1
441 if menu_end_title > nr_titles:
442 menu_end_title = nr_titles+1
444 for title_no in range( menu_start_title , menu_end_title ):
446 top = s_top + ( menu_i * rowheight )
448 title = job.project.titles[i]
449 titleText = formatTitle(s.titleformat.getValue(), title, title_no)
450 draw_bg.text((s_left,top), titleText, fill=color_button, font=font1)
451 draw_high.text((s_left,top), titleText, fill=1, font=font1)
452 subtitleText = formatTitle(s.subtitleformat.getValue(), title, title_no)
453 draw_bg.text((s_left,top+36), subtitleText, fill=color_button, font=font2)
454 bottom = top+rowheight
455 if bottom > imgheight:
458 <button name="button%s" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (str(title_no).zfill(2),s_left,imgwidth,top,bottom )
460 prev_page_text = "<<<"
461 textsize = draw_bg.textsize(prev_page_text, font=font1)
462 offset = ( 2*s_left, s_top + ( titles_per_menu * rowheight ) )
463 draw_bg.text(offset, prev_page_text, fill=color_button, font=font1)
464 draw_high.text(offset, prev_page_text, fill=1, font=font1)
466 <button name="button_prev" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (offset[0],offset[0]+textsize[0],offset[1],offset[1]+textsize[1])
468 if menu_count < job.nr_menus:
469 next_page_text = ">>>"
470 textsize = draw_bg.textsize(next_page_text, font=font1)
471 offset = ( imgwidth-textsize[0]-2*s_left, s_top + ( titles_per_menu * rowheight ) )
472 draw_bg.text(offset, next_page_text, fill=color_button, font=font1)
473 draw_high.text(offset, next_page_text, fill=1, font=font1)
475 <button name="button_next" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (offset[0],offset[0]+textsize[0],offset[1],offset[1]+textsize[1])
479 fd=open(menubgpngfilename,"w")
482 fd=open(highlightpngfilename,"w")
483 im_high.save(fd,"PNG")
486 png2yuvTask(job, menubgpngfilename, job.workspace+"/dvdmenubg"+str(menu_count)+".yuv")
487 menubgm2vfilename = job.workspace+"/dvdmenubg"+str(menu_count)+".mv2"
488 mpeg2encTask(job, job.workspace+"/dvdmenubg"+str(menu_count)+".yuv", menubgm2vfilename)
489 menubgmpgfilename = job.workspace+"/dvdmenubg"+str(menu_count)+".mpg"
490 menuaudiofilename = s.menuaudio.getValue()
491 MplexTask(job, outputfile=menubgmpgfilename, inputfiles = [menubgm2vfilename, menuaudiofilename])
497 spuxmlfilename = job.workspace+"/spumux"+str(menu_count)+".xml"
498 f = open(spuxmlfilename, "w")
502 menuoutputfilename = job.workspace+"/dvdmenu"+str(menu_count)+".mpg"
503 spumuxTask(job, spuxmlfilename, menubgmpgfilename, menuoutputfilename)
505 def CreateAuthoringXML(job):
506 nr_titles = len(job.project.titles)
507 titles_per_menu = getTitlesPerMenu(nr_titles)
508 mode = job.project.settings.authormode.getValue()
510 authorxml.append('<?xml version="1.0" encoding="utf-8"?>\n')
511 authorxml.append(' <dvdauthor dest="' + (job.workspace+"/dvd") + '">\n')
512 authorxml.append(' <vmgm>\n')
513 authorxml.append(' <menus>\n')
514 authorxml.append(' <pgc>\n')
515 authorxml.append(' <vob file="' + job.project.settings.vmgm.getValue() + '" />\n', )
516 if mode.startswith("menu"):
517 authorxml.append(' <post> jump titleset 1 menu; </post>\n')
519 authorxml.append(' <post> jump title 1; </post>\n')
520 authorxml.append(' </pgc>\n')
521 authorxml.append(' </menus>\n')
522 authorxml.append(' </vmgm>\n')
523 authorxml.append(' <titleset>\n')
524 if mode.startswith("menu"):
525 authorxml.append(' <menus>\n')
526 authorxml.append(' <video aspect="4:3"/>\n')
527 for menu_count in range(1 , job.nr_menus+1):
529 authorxml.append(' <pgc entry="root">\n')
531 authorxml.append(' <pgc>\n')
532 menu_start_title = (menu_count-1)*titles_per_menu + 1
533 menu_end_title = (menu_count)*titles_per_menu + 1
534 if menu_end_title > nr_titles:
535 menu_end_title = nr_titles+1
536 for i in range( menu_start_title , menu_end_title ):
537 authorxml.append(' <button name="button' + (str(i).zfill(2)) + '"> jump title ' + str(i) +'; </button>\n')
539 authorxml.append(' <button name="button_prev"> jump menu ' + str(menu_count-1) + '; </button>\n')
540 if menu_count < job.nr_menus:
541 authorxml.append(' <button name="button_next"> jump menu ' + str(menu_count+1) + '; </button>\n')
542 menuoutputfilename = job.workspace+"/dvdmenu"+str(menu_count)+".mpg"
543 authorxml.append(' <vob file="' + menuoutputfilename + '" pause="inf"/>\n')
544 authorxml.append(' </pgc>\n')
545 authorxml.append(' </menus>\n')
546 authorxml.append(' <titles>\n')
547 for i in range( nr_titles ):
548 for audiotrack in job.project.titles[i].audiotracks:
549 authorxml.append(' <audio lang="'+audiotrack[0][:2]+'" format="'+audiotrack[1]+'" />\n')
550 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])
552 title_filename = job.workspace + "/dvd_title_%d.mpg" % (title_no)
554 LinkTS(job, job.project.settings.vmgm.getValue(), title_filename)
556 MakeFifoNode(job, title_no)
557 if mode.endswith("linked") and title_no < nr_titles:
558 post_tag = "jump title %d;" % ( title_no+1 )
559 elif mode.startswith("menu"):
560 post_tag = "call vmgm menu 1;"
563 authorxml.append(' <pgc>\n')
564 authorxml.append(' <vob file="' + title_filename + '" chapters="' + chapters + '" />\n')
565 authorxml.append(' <post> ' + post_tag + ' </post>\n')
566 authorxml.append(' </pgc>\n')
568 authorxml.append(' </titles>\n')
569 authorxml.append(' </titleset>\n')
570 authorxml.append(' </dvdauthor>\n')
571 f = open(job.workspace+"/dvdauthor.xml", "w")
577 def __init__(self, project, menupreview=False):
578 Job.__init__(self, "DVD Burn")
579 self.project = project
580 from time import strftime
581 from Tools.Directories import SCOPE_HDD, resolveFilename, createDir
582 new_workspace = resolveFilename(SCOPE_HDD) + "tmp/" + strftime("%Y%m%d%H%M%S")
583 createDir(new_workspace, True)
584 self.workspace = new_workspace
585 self.project.workspace = self.workspace
586 self.menupreview = menupreview
590 if self.project.settings.authormode.getValue().startswith("menu") or self.menupreview:
592 CreateAuthoringXML(self)
594 totalsize = 50*1024*1024 # require an extra safety 50 MB
596 for title in self.project.titles:
597 titlesize = title.estimatedDiskspace
598 if titlesize > maxsize: maxsize = titlesize
599 totalsize += titlesize
600 diskSpaceNeeded = totalsize + maxsize
602 DVDAuthorTask(self, diskSpaceNeeded)
604 nr_titles = len(self.project.titles)
609 for self.i in range(nr_titles):
610 title = self.project.titles[self.i]
611 link_name = self.workspace + "/source_title_%d.ts" % (self.i+1)
612 title_filename = self.workspace + "/dvd_title_%d.mpg" % (self.i+1)
613 LinkTS(self, title.inputfile, link_name)
614 demux = DemuxTask(self, link_name)
615 MplexTask(self, outputfile=title_filename, demux_task=demux)
616 RemoveESFiles(self, demux)
617 WaitForResidentTasks(self)
620 RemoveDVDFolder(self)
622 def Burn(session, project):
624 job_manager.AddJob(j)
627 def PreviewMenu(session, project):
628 j = DVDJob(project, menupreview=True)
629 job_manager.AddJob(j)