1 from Components.Task import Task, Job, job_manager, DiskspacePrecondition, Condition, ToolExistsPrecondition
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.stdoutAvail.get().remove(self.processStdout)
15 self.container.dumpToFile(self.dumpFile)
17 def processStderr(self, data):
18 print "[png2yuvTask]", data[:-1]
20 class mpeg2encTask(Task):
21 def __init__(self, job, inputfile, outputfile):
22 Task.__init__(self, job, "Encoding menu video")
23 self.setTool("/usr/bin/mpeg2enc")
24 self.args += ["-f8", "-np", "-a2", "-o", outputfile]
25 self.inputFile = inputfile
28 def run(self, callback, task_progress_changed):
29 Task.run(self, callback, task_progress_changed)
30 self.container.readFromFile(self.inputFile)
32 def processOutputLine(self, line):
33 print "[mpeg2encTask]", line[:-1]
35 class spumuxTask(Task):
36 def __init__(self, job, xmlfile, inputfile, outputfile):
37 Task.__init__(self, job, "Muxing buttons into menu")
38 self.setTool("/usr/bin/spumux")
39 self.args += [xmlfile]
40 self.inputFile = inputfile
41 self.dumpFile = outputfile
44 def run(self, callback, task_progress_changed):
45 Task.run(self, callback, task_progress_changed)
46 self.container.stdoutAvail.get().remove(self.processStdout)
47 self.container.dumpToFile(self.dumpFile)
48 self.container.readFromFile(self.inputFile)
50 def processStderr(self, data):
51 print "[spumuxTask]", data[:-1]
53 class MakeFifoNode(Task):
54 def __init__(self, job, number):
55 Task.__init__(self, job, "Make FIFO nodes")
56 self.setTool("/bin/mknod")
57 nodename = self.job.workspace + "/dvd_title_%d" % number + ".mpg"
58 self.args += [nodename, "p"]
62 def __init__(self, job, sourcefile, link_name):
63 Task.__init__(self, job, "Creating symlink for source titles")
64 self.setTool("/bin/ln")
65 self.args += ["-s", sourcefile, link_name]
68 class DemuxTask(Task):
69 def __init__(self, job, inputfile):
70 Task.__init__(self, job, "Demux video into ES")
71 title = job.project.titles[job.i]
72 self.global_preconditions.append(DiskspacePrecondition(title.estimatedDiskspace))
73 self.setTool("/usr/bin/projectx")
74 self.generated_files = [ ]
78 self.cutfile = self.job.workspace + "/cut_%d.Xcl" % (job.i+1)
79 self.cutlist = title.cutlist
80 self.args += [inputfile, "-demux", "-out", self.job.workspace ]
81 if len(self.cutlist) > 1:
82 self.args += [ "-cut", self.cutfile ]
87 def processOutputLine(self, line):
89 MSG_NEW_FILE = "---> new File: "
90 MSG_PROGRESS = "[PROGRESS] "
92 if line.startswith(MSG_NEW_FILE):
93 file = line[len(MSG_NEW_FILE):]
96 self.haveNewFile(file)
97 elif line.startswith(MSG_PROGRESS):
98 progress = line[len(MSG_PROGRESS):]
99 self.haveProgress(progress)
101 def haveNewFile(self, file):
102 print "PRODUCED FILE [%s]" % file
103 self.generated_files.append(file)
105 def haveProgress(self, progress):
106 #print "PROGRESS [%s]" % progress
107 MSG_CHECK = "check & synchronize audio file"
109 if progress == "preparing collection(s)...":
111 elif progress[:len(MSG_CHECK)] == MSG_CHECK:
116 p = p - 1 + self.prog_state * 100
117 if p > self.progress:
123 def writeCutfile(self):
124 f = open(self.cutfile, "w")
125 f.write("CollectionPanel.CutMode=4\n")
126 for p in self.cutlist:
134 f.write("%02d:%02d:%02d\n" % (h, m, s))
137 def cleanup(self, failed):
140 for f in self.generated_files:
143 class MplexTaskPostcondition(Condition):
144 def check(self, task):
145 if task.error == task.ERROR_UNDERRUN:
147 return task.error is None
149 def getErrorMessage(self, task):
150 print "[MplexTaskPostcondition] getErrorMessage", task
152 task.ERROR_UNDERRUN: ("Can't multiplex source video!"),
153 task.ERROR_UNKNOWN: ("An unknown error occured!")
156 class MplexTask(Task):
157 ERROR_UNDERRUN, ERROR_UNKNOWN = range(2)
158 def __init__(self, job, outputfile, inputfiles=None, demux_task=None):
159 Task.__init__(self, job, "Mux ES into PS")
161 self.demux_task = demux_task
162 self.postconditions.append(MplexTaskPostcondition())
163 self.setTool("/usr/bin/mplex")
164 self.args += ["-f8", "-o", outputfile, "-v1"]
166 self.args += inputfiles
168 def setTool(self, tool):
171 self.global_preconditions.append(ToolExistsPrecondition())
172 # 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)
177 self.args += self.demux_task.generated_files
179 def processOutputLine(self, line):
180 print "[MplexTask] processOutputLine=", line[:-1]
181 if line.startswith("**ERROR:"):
182 if line.find("Frame data under-runs detected") != -1:
183 self.error = self.ERROR_UNDERRUN
185 self.error = self.ERROR_UNKNOWN
187 class RemoveESFiles(Task):
188 def __init__(self, job, demux_task):
189 Task.__init__(self, job, "Remove temp. files")
190 self.demux_task = demux_task
191 self.setTool("/bin/rm")
195 self.args += self.demux_task.generated_files
196 self.args += [self.demux_task.cutfile]
198 class DVDAuthorTask(Task):
199 def __init__(self, job, diskspaceNeeded):
200 Task.__init__(self, job, "Authoring DVD")
202 self.global_preconditions.append(DiskspacePrecondition(diskspaceNeeded))
204 self.setTool("/usr/bin/dvdauthor")
205 self.CWD = self.job.workspace
206 self.args += ["-x", self.job.workspace+"/dvdauthor.xml"]
207 self.menupreview = job.menupreview
209 def processOutputLine(self, line):
210 print "[DVDAuthorTask] processOutputLine=", line[:-1]
211 if not self.menupreview and line.startswith("STAT: Processing"):
212 self.callback(self, [], stay_resident=True)
214 class DVDAuthorFinalTask(Task):
215 def __init__(self, job):
216 Task.__init__(self, job, "dvdauthor finalize")
217 self.setTool("/usr/bin/dvdauthor")
218 self.args += ["-T", "-o", self.job.workspace + "/dvd"]
220 class WaitForResidentTasks(Task):
221 def __init__(self, job):
222 Task.__init__(self, job, "waiting for dvdauthor to finalize")
224 def run(self, callback, task_progress_changed):
225 print "waiting for %d resident task(s) %s to finish..." % (len(self.job.resident_tasks),str(self.job.resident_tasks))
226 if self.job.resident_tasks == 0:
229 class BurnTaskPostcondition(Condition):
231 def check(self, task):
232 return task.error is None
234 def getErrorMessage(self, task):
236 task.ERROR_MEDIA: _("Medium is not a writeable DVD!"),
237 task.ERROR_SIZE: _("Content does not fit on DVD!"),
238 task.ERROR_WRITE_FAILED: _("Write failed!"),
239 task.ERROR_DVDROM: _("No (supported) DVDROM found!"),
240 task.ERROR_ISOFS: _("Medium is not empty!"),
241 task.ERROR_UNKNOWN: _("An unknown error occured!")
244 class BurnTask(Task):
245 ERROR_MEDIA, ERROR_SIZE, ERROR_WRITE_FAILED, ERROR_DVDROM, ERROR_ISOFS, ERROR_UNKNOWN = range(6)
246 def __init__(self, job):
247 Task.__init__(self, job, "burn")
250 self.end = 120 # 100 for writing, 10 for buffer flush, 10 for closing disc
251 self.postconditions.append(BurnTaskPostcondition())
252 self.setTool("/bin/growisofs")
253 volName = self.getASCIIname(job.project.settings.name.getValue())
254 self.args += ["-dvd-video", "-dvd-compat", "-Z", "/dev/cdroms/cdrom0", "-V", volName, "-P", "Dreambox", "-use-the-force-luke=dummy", self.job.workspace + "/dvd"]
256 def getASCIIname(self, name):
258 for char in name.decode("utf-8").encode("ascii","replace"):
259 if ord(char) <= 0x20 or ( ord(char) >= 0x3a and ord(char) <= 0x40 ):
268 def processOutputLine(self, line):
270 print "[GROWISOFS] %s" % line
271 if line[8:14] == "done, ":
272 self.progress = float(line[:6])
273 print "progress:", self.progress
274 elif line.find("flushing cache") != -1:
276 elif line.find("closing disc") != -1:
278 elif line.startswith(":-["):
279 if line.find("ASC=30h") != -1:
280 self.error = self.ERROR_MEDIA
282 self.error = self.ERROR_UNKNOWN
283 print "BurnTask: unknown error %s" % line
284 elif line.startswith(":-("):
285 if line.find("No space left on device") != -1:
286 self.error = self.ERROR_SIZE
287 elif line.find("write failed") != -1:
288 self.error = self.ERROR_WRITE_FAILED
289 elif line.find("unable to open64(\"/dev/cdroms/cdrom0\",O_RDONLY): No such file or directory") != -1: # fixme
290 self.error = self.ERROR_DVDROM
291 elif line.find("media is not recognized as recordable DVD") != -1:
292 self.error = self.ERROR_MEDIA
294 self.error = self.ERROR_UNKNOWN
295 print "BurnTask: unknown error %s" % line
296 elif line.startswith("FATAL:"):
297 if line.find("already carries isofs!"):
298 self.error = self.ERROR_ISOFS
300 self.error = self.ERROR_UNKNOWN
301 print "BurnTask: unknown error %s" % line
303 class RemoveDVDFolder(Task):
304 def __init__(self, job):
305 Task.__init__(self, job, "Remove temp. files")
306 self.setTool("/bin/rm")
307 self.args += ["-rf", self.job.workspace]
309 class PreviewTask(Task):
310 def __init__(self, job):
311 Task.__init__(self, job, "Preview")
312 self.postconditions.append(PreviewTaskPostcondition())
315 def run(self, callback, task_progress_changed):
316 self.callback = callback
317 self.task_progress_changed = task_progress_changed
318 if self.job.project.waitboxref:
319 self.job.project.waitboxref.close()
320 if self.job.menupreview:
321 self.waitAndOpenPlayer()
323 self.job.project.session.openWithCallback(self.previewCB, MessageBox, _("Do you want to preview this DVD before burning?"), timeout = 60, default = False)
325 def previewCB(self, answer):
327 self.waitAndOpenPlayer()
331 def playerClosed(self):
332 if self.job.menupreview:
335 self.job.project.session.openWithCallback(self.closedCB, MessageBox, _("Do you want to burn this collection to DVD medium?") )
337 def closedCB(self, answer):
339 Task.processFinished(self, 0)
341 Task.processFinished(self, 1)
343 def waitAndOpenPlayer(self):
344 from enigma import eTimer
345 self.delayTimer = eTimer()
346 self.delayTimer.callback.append(self.previewProject)
347 self.delayTimer.start(10,1)
349 def previewProject(self):
350 from Plugins.Extensions.DVDPlayer.plugin import DVDPlayer
351 self.job.project.session.openWithCallback(self.playerClosed, DVDPlayer, dvd_filelist= [ self.job.project.workspace + "/dvd/VIDEO_TS/" ])
353 class PreviewTaskPostcondition(Condition):
354 def check(self, task):
355 return task.returncode == 0
357 def getErrorMessage(self, task):
360 def getTitlesPerMenu(nr_titles):
365 return titles_per_menu
367 def formatTitle(template, title, track):
368 template = template.replace("$i", str(track))
369 template = template.replace("$t", title.name)
370 template = template.replace("$d", title.descr)
371 template = template.replace("$c", str(len(title.chaptermarks)+1))
372 template = template.replace("$A", str(title.audiotracks))
373 template = template.replace("$f", title.inputfile)
374 template = template.replace("$C", title.channel)
376 lengthstring = "%d:%02d:%02d" % (l/3600, l%3600/60, l%60)
377 template = template.replace("$l", lengthstring)
379 template = template.replace("$Y", str(title.timeCreate[0]))
380 template = template.replace("$M", str(title.timeCreate[1]))
381 template = template.replace("$D", str(title.timeCreate[2]))
382 timestring = "%d:%02d" % (title.timeCreate[3], title.timeCreate[4])
383 template = template.replace("$T", timestring)
385 template = template.replace("$Y", "").replace("$M", "").replace("$D", "").replace("$T", "")
386 return template.decode("utf-8")
388 def CreateMenus(job):
389 import os, Image, ImageDraw, ImageFont
392 s = job.project.settings
393 im_bg_orig = Image.open(s.menubg.getValue())
394 if im_bg_orig.size != (imgwidth, imgheight):
395 im_bg_orig = im_bg_orig.resize((720, 576))
397 fontsizes = s.font_size.getValue()
398 fontface = s.font_face.getValue()
400 font0 = ImageFont.truetype(fontface, fontsizes[0])
401 font1 = ImageFont.truetype(fontface, fontsizes[1])
402 font2 = ImageFont.truetype(fontface, fontsizes[2])
404 color_headline = tuple(s.color_headline.getValue())
405 color_button = tuple(s.color_button.getValue())
406 color_highlight = tuple(s.color_highlight.getValue())
407 spu_palette = [ 0x60, 0x60, 0x60 ] + s.color_highlight.getValue()
409 nr_titles = len(job.project.titles)
410 titles_per_menu = getTitlesPerMenu(nr_titles)
411 job.nr_menus = ((nr_titles+titles_per_menu-1)/titles_per_menu)
413 #a new menu_count every 5 titles (1,2,3,4,5->1 ; 6,7,8,9,10->2 etc.)
414 for menu_count in range(1 , job.nr_menus+1):
415 im_bg = im_bg_orig.copy()
416 im_high = Image.new("P", (imgwidth, imgheight), 0)
417 im_high.putpalette(spu_palette)
418 draw_bg = ImageDraw.Draw(im_bg)
419 draw_high = ImageDraw.Draw(im_high)
422 headline = s.name.getValue().decode("utf-8")
423 textsize = draw_bg.textsize(headline, font=font0)
424 if textsize[0] > imgwidth:
427 offset = (((imgwidth-textsize[0]) / 2) , 20)
428 draw_bg.text(offset, headline, fill=color_headline, font=font0)
430 menubgpngfilename = job.workspace+"/dvd_menubg"+str(menu_count)+".png"
431 highlightpngfilename = job.workspace+"/dvd_highlight"+str(menu_count)+".png"
432 spuxml = """<?xml version="1.0" encoding="utf-8"?>
437 transparent="%02x%02x%02x"
439 force="yes" >""" % (highlightpngfilename, spu_palette[0], spu_palette[1], spu_palette[2])
440 s_top, s_rows, s_left = s.space.getValue()
441 rowheight = (fontsizes[1]+fontsizes[2]+s_rows)
442 menu_start_title = (menu_count-1)*titles_per_menu + 1
443 menu_end_title = (menu_count)*titles_per_menu + 1
444 if menu_end_title > nr_titles:
445 menu_end_title = nr_titles+1
447 for title_no in range( menu_start_title , menu_end_title ):
449 top = s_top + ( menu_i * rowheight )
451 title = job.project.titles[i]
452 titleText = formatTitle(s.titleformat.getValue(), title, title_no)
453 draw_bg.text((s_left,top), titleText, fill=color_button, font=font1)
454 draw_high.text((s_left,top), titleText, fill=1, font=font1)
455 subtitleText = formatTitle(s.subtitleformat.getValue(), title, title_no)
456 draw_bg.text((s_left,top+36), subtitleText, fill=color_button, font=font2)
457 bottom = top+rowheight
458 if bottom > imgheight:
461 <button name="button%s" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (str(title_no).zfill(2),s_left,imgwidth,top,bottom )
463 prev_page_text = "<<<"
464 textsize = draw_bg.textsize(prev_page_text, font=font1)
465 offset = ( 2*s_left, s_top + ( titles_per_menu * rowheight ) )
466 draw_bg.text(offset, prev_page_text, fill=color_button, font=font1)
467 draw_high.text(offset, prev_page_text, fill=1, font=font1)
469 <button name="button_prev" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (offset[0],offset[0]+textsize[0],offset[1],offset[1]+textsize[1])
471 if menu_count < job.nr_menus:
472 next_page_text = ">>>"
473 textsize = draw_bg.textsize(next_page_text, font=font1)
474 offset = ( imgwidth-textsize[0]-2*s_left, s_top + ( titles_per_menu * rowheight ) )
475 draw_bg.text(offset, next_page_text, fill=color_button, font=font1)
476 draw_high.text(offset, next_page_text, fill=1, font=font1)
478 <button name="button_next" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (offset[0],offset[0]+textsize[0],offset[1],offset[1]+textsize[1])
482 fd=open(menubgpngfilename,"w")
485 fd=open(highlightpngfilename,"w")
486 im_high.save(fd,"PNG")
489 png2yuvTask(job, menubgpngfilename, job.workspace+"/dvdmenubg"+str(menu_count)+".yuv")
490 menubgm2vfilename = job.workspace+"/dvdmenubg"+str(menu_count)+".mv2"
491 mpeg2encTask(job, job.workspace+"/dvdmenubg"+str(menu_count)+".yuv", menubgm2vfilename)
492 menubgmpgfilename = job.workspace+"/dvdmenubg"+str(menu_count)+".mpg"
493 menuaudiofilename = s.menuaudio.getValue()
494 MplexTask(job, outputfile=menubgmpgfilename, inputfiles = [menubgm2vfilename, menuaudiofilename])
500 spuxmlfilename = job.workspace+"/spumux"+str(menu_count)+".xml"
501 f = open(spuxmlfilename, "w")
505 menuoutputfilename = job.workspace+"/dvdmenu"+str(menu_count)+".mpg"
506 spumuxTask(job, spuxmlfilename, menubgmpgfilename, menuoutputfilename)
508 def CreateAuthoringXML(job):
509 nr_titles = len(job.project.titles)
510 titles_per_menu = getTitlesPerMenu(nr_titles)
511 mode = job.project.settings.authormode.getValue()
513 authorxml.append('<?xml version="1.0" encoding="utf-8"?>\n')
514 authorxml.append(' <dvdauthor dest="' + (job.workspace+"/dvd") + '">\n')
515 authorxml.append(' <vmgm>\n')
516 authorxml.append(' <menus>\n')
517 authorxml.append(' <pgc>\n')
518 authorxml.append(' <vob file="' + job.project.settings.vmgm.getValue() + '" />\n', )
519 if mode.startswith("menu"):
520 authorxml.append(' <post> jump titleset 1 menu; </post>\n')
522 authorxml.append(' <post> jump title 1; </post>\n')
523 authorxml.append(' </pgc>\n')
524 authorxml.append(' </menus>\n')
525 authorxml.append(' </vmgm>\n')
526 authorxml.append(' <titleset>\n')
527 if mode.startswith("menu"):
528 authorxml.append(' <menus>\n')
529 authorxml.append(' <video aspect="4:3"/>\n')
530 for menu_count in range(1 , job.nr_menus+1):
532 authorxml.append(' <pgc entry="root">\n')
534 authorxml.append(' <pgc>\n')
535 menu_start_title = (menu_count-1)*titles_per_menu + 1
536 menu_end_title = (menu_count)*titles_per_menu + 1
537 if menu_end_title > nr_titles:
538 menu_end_title = nr_titles+1
539 for i in range( menu_start_title , menu_end_title ):
540 authorxml.append(' <button name="button' + (str(i).zfill(2)) + '"> jump title ' + str(i) +'; </button>\n')
542 authorxml.append(' <button name="button_prev"> jump menu ' + str(menu_count-1) + '; </button>\n')
543 if menu_count < job.nr_menus:
544 authorxml.append(' <button name="button_next"> jump menu ' + str(menu_count+1) + '; </button>\n')
545 menuoutputfilename = job.workspace+"/dvdmenu"+str(menu_count)+".mpg"
546 authorxml.append(' <vob file="' + menuoutputfilename + '" pause="inf"/>\n')
547 authorxml.append(' </pgc>\n')
548 authorxml.append(' </menus>\n')
549 authorxml.append(' <titles>\n')
550 for i in range( nr_titles ):
551 for audiotrack in job.project.titles[i].audiotracks:
552 authorxml.append(' <audio lang="'+audiotrack[0][:2]+'" format="'+audiotrack[1]+'" />\n')
553 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])
555 title_filename = job.workspace + "/dvd_title_%d.mpg" % (title_no)
557 LinkTS(job, job.project.settings.vmgm.getValue(), title_filename)
559 MakeFifoNode(job, title_no)
560 if mode.endswith("linked") and title_no < nr_titles:
561 post_tag = "jump title %d;" % ( title_no+1 )
562 elif mode.startswith("menu"):
563 post_tag = "call vmgm menu 1;"
566 authorxml.append(' <pgc>\n')
567 authorxml.append(' <vob file="' + title_filename + '" chapters="' + chapters + '" />\n')
568 authorxml.append(' <post> ' + post_tag + ' </post>\n')
569 authorxml.append(' </pgc>\n')
571 authorxml.append(' </titles>\n')
572 authorxml.append(' </titleset>\n')
573 authorxml.append(' </dvdauthor>\n')
574 f = open(job.workspace+"/dvdauthor.xml", "w")
580 def __init__(self, project, menupreview=False):
581 Job.__init__(self, "DVD Burn")
582 self.project = project
583 from time import strftime
584 from Tools.Directories import SCOPE_HDD, resolveFilename, createDir
585 new_workspace = resolveFilename(SCOPE_HDD) + "tmp/" + strftime("%Y%m%d%H%M%S")
586 createDir(new_workspace, True)
587 self.workspace = new_workspace
588 self.project.workspace = self.workspace
589 self.menupreview = menupreview
593 if self.project.settings.authormode.getValue().startswith("menu") or self.menupreview:
595 CreateAuthoringXML(self)
597 totalsize = 50*1024*1024 # require an extra safety 50 MB
599 for title in self.project.titles:
600 titlesize = title.estimatedDiskspace
601 if titlesize > maxsize: maxsize = titlesize
602 totalsize += titlesize
603 diskSpaceNeeded = totalsize + maxsize
605 DVDAuthorTask(self, diskSpaceNeeded)
607 nr_titles = len(self.project.titles)
612 for self.i in range(nr_titles):
613 title = self.project.titles[self.i]
614 link_name = self.workspace + "/source_title_%d.ts" % (self.i+1)
615 title_filename = self.workspace + "/dvd_title_%d.mpg" % (self.i+1)
616 LinkTS(self, title.inputfile, link_name)
617 demux = DemuxTask(self, link_name)
618 MplexTask(self, outputfile=title_filename, demux_task=demux)
619 RemoveESFiles(self, demux)
620 WaitForResidentTasks(self)
623 RemoveDVDFolder(self)
625 def Burn(session, project):
627 job_manager.AddJob(j)
630 def PreviewMenu(session, project):
631 j = DVDJob(project, menupreview=True)
632 job_manager.AddJob(j)