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
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
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 MplexTask(Task):
148 def __init__(self, job, outputfile, inputfiles=None, demux_task=None):
149 Task.__init__(self, job, "Mux ES into PS")
151 self.demux_task = demux_task
152 self.setTool("/usr/bin/mplex")
153 self.args += ["-f8", "-o", outputfile, "-v1"]
155 self.args += inputfiles
159 self.args += self.demux_task.generated_files
161 def processOutputLine(self, line):
162 print "[MplexTask] processOutputLine=", line
164 class RemoveESFiles(Task):
165 def __init__(self, job, demux_task):
166 Task.__init__(self, job, "Remove temp. files")
167 self.demux_task = demux_task
168 self.setTool("/bin/rm")
172 self.args += self.demux_task.generated_files
173 self.args += [self.demux_task.cutfile]
175 class DVDAuthorTask(Task):
176 def __init__(self, job, diskspaceNeeded):
177 Task.__init__(self, job, "Authoring DVD")
179 self.global_preconditions.append(DiskspacePrecondition(diskspaceNeeded))
181 self.setTool("/usr/bin/dvdauthor")
182 self.CWD = self.job.workspace
183 self.args += ["-x", self.job.workspace+"/dvdauthor.xml"]
184 self.menupreview = job.menupreview
186 def processOutputLine(self, line):
187 print "[DVDAuthorTask] processOutputLine=", line
188 if not self.menupreview and line.startswith("STAT: Processing"):
189 self.callback(self, [], stay_resident=True)
191 class DVDAuthorFinalTask(Task):
192 def __init__(self, job):
193 Task.__init__(self, job, "dvdauthor finalize")
194 self.setTool("/usr/bin/dvdauthor")
195 self.args += ["-T", "-o", self.job.workspace + "/dvd"]
197 class WaitForResidentTasks(Task):
198 def __init__(self, job):
199 Task.__init__(self, job, "waiting for dvdauthor to finalize")
201 def run(self, callback, task_progress_changed):
202 print "waiting for %d resident task(s) %s to finish..." % (len(self.job.resident_tasks),str(self.job.resident_tasks))
203 if self.job.resident_tasks == 0:
206 class BurnTaskPostcondition(Condition):
207 def check(self, task):
208 return task.error is None
210 def getErrorMessage(self, task):
212 task.ERROR_MEDIA: ("Medium is not a writeable DVD!"),
213 task.ERROR_SIZE: ("Content does not fit on DVD!"),
214 task.ERROR_WRITE_FAILED: ("Write failed!"),
215 task.ERROR_DVDROM: ("No (supported) DVDROM found!"),
216 task.ERROR_ISOFS: ("Medium is not empty!"),
217 task.ERROR_UNKNOWN: ("An unknown error occured!")
220 class BurnTask(Task):
221 ERROR_MEDIA, ERROR_SIZE, ERROR_WRITE_FAILED, ERROR_DVDROM, ERROR_ISOFS, ERROR_UNKNOWN = range(6)
222 def __init__(self, job):
223 Task.__init__(self, job, "burn")
226 self.end = 120 # 100 for writing, 10 for buffer flush, 10 for closing disc
227 self.postconditions.append(BurnTaskPostcondition())
228 self.setTool("/bin/growisofs")
230 self.args += ["-dvd-video", "-dvd-compat", "-Z", "/dev/cdroms/cdrom0", "-V", self.getASCIIname(job.project.name), "-P", "Dreambox", "-use-the-force-luke=dummy", self.job.workspace + "/dvd"]
232 def getASCIIname(self, name):
234 for char in name.decode("utf-8").encode("ascii","replace"):
235 if ord(char) <= 0x20 or ( ord(char) >= 0x3a and ord(char) <= 0x40 ):
244 def processOutputLine(self, line):
246 print "[GROWISOFS] %s" % line
247 if line[8:14] == "done, ":
248 self.progress = float(line[:6])
249 print "progress:", self.progress
250 elif line.find("flushing cache") != -1:
252 elif line.find("closing disc") != -1:
254 elif line.startswith(":-["):
255 if line.find("ASC=30h") != -1:
256 self.error = self.ERROR_MEDIA
258 self.error = self.ERROR_UNKNOWN
259 print "BurnTask: unknown error %s" % line
260 elif line.startswith(":-("):
261 if line.find("No space left on device") != -1:
262 self.error = self.ERROR_SIZE
263 elif line.find("write failed") != -1:
264 self.error = self.ERROR_WRITE_FAILED
265 elif line.find("unable to open64(\"/dev/cdroms/cdrom0\",O_RDONLY): No such file or directory") != -1: # fixme
266 self.error = self.ERROR_DVDROM
267 elif line.find("media is not recognized as recordable DVD") != -1:
268 self.error = self.ERROR_MEDIA
270 self.error = self.ERROR_UNKNOWN
271 print "BurnTask: unknown error %s" % line
272 elif line.startswith("FATAL:"):
273 if line.find("already carries isofs!"):
274 self.error = self.ERROR_ISOFS
276 self.error = self.ERROR_UNKNOWN
277 print "BurnTask: unknown error %s" % line
279 class RemoveDVDFolder(Task):
280 def __init__(self, job):
281 Task.__init__(self, job, "Remove temp. files")
282 self.setTool("/bin/rm")
283 self.args += ["-rf", self.job.workspace]
285 class PreviewTask(Task):
286 def __init__(self, job):
287 Task.__init__(self, job, "Preview")
290 def run(self, callback, task_progress_changed):
291 self.callback = callback
292 self.task_progress_changed = task_progress_changed
293 if self.job.project.waitboxref:
294 self.job.project.waitboxref.close()
295 if self.job.menupreview:
296 self.waitAndOpenPlayer()
298 self.job.project.session.openWithCallback(self.previewCB, MessageBox, _("Do you want to preview this project before burning?"), timeout = 60, default = False)
300 def previewCB(self, answer):
302 self.waitAndOpenPlayer()
306 def playerClosed(self):
307 if self.job.menupreview:
310 self.job.project.session.openWithCallback(self.closedCB, MessageBox, _("Do you want to burn this project to DVD medium?") )
312 def closedCB(self, answer):
314 Task.processFinished(self, 0)
316 Task.processFinished(self, 1)
318 def waitAndOpenPlayer(self):
319 from enigma import eTimer
320 self.delayTimer = eTimer()
321 self.delayTimer.callback.append(self.previewProject)
322 self.delayTimer.start(10,1)
324 def previewProject(self):
325 from Plugins.Extensions.DVDPlayer.plugin import DVDPlayer
326 self.job.project.session.openWithCallback(self.playerClosed, DVDPlayer, dvd_filelist= [ self.job.project.workspace + "/dvd/VIDEO_TS/" ])
328 def getTitlesPerMenu(nr_titles):
333 return titles_per_menu
335 def CreateMenus(job):
336 import os, Image, ImageDraw, ImageFont, re
340 im_bg_orig = Image.open(job.project.menubg)
341 if im_bg_orig.size != (imgwidth, imgheight):
342 im_bg_orig = im_bg_orig.resize((720, 576))
344 font0 = ImageFont.truetype(job.project.font_face, job.project.font_size[0])
345 font1 = ImageFont.truetype(job.project.font_face, job.project.font_size[1])
346 font2 = ImageFont.truetype(job.project.font_face, job.project.font_size[2])
347 spu_palette = [ 0x60, 0x60, 0x60 ] + list(job.project.color_highlight)
349 nr_titles = len(job.project.titles)
350 titles_per_menu = getTitlesPerMenu(nr_titles)
351 job.nr_menus = ((nr_titles+titles_per_menu-1)/titles_per_menu)
353 #a new menu_count every 5 titles (1,2,3,4,5->1 ; 6,7,8,9,10->2 etc.)
354 for menu_count in range(1 , job.nr_menus+1):
355 im_bg = im_bg_orig.copy()
356 im_high = Image.new("P", (imgwidth, imgheight), 0)
357 im_high.putpalette(spu_palette)
358 draw_bg = ImageDraw.Draw(im_bg)
359 draw_high = ImageDraw.Draw(im_high)
362 headline = job.project.name.decode("utf-8")
363 textsize = draw_bg.textsize(headline, font=font0)
364 if textsize[0] > imgwidth:
367 offset = (((imgwidth-textsize[0]) / 2) , 20)
368 draw_bg.text(offset, headline, fill=job.project.color_headline, font=font0)
370 menubgpngfilename = job.workspace+"/dvd_menubg"+str(menu_count)+".png"
371 highlightpngfilename = job.workspace+"/dvd_highlight"+str(menu_count)+".png"
372 spuxml = """<?xml version="1.0" encoding="utf-8"?>
377 transparent="%02x%02x%02x"
379 force="yes" >""" % (highlightpngfilename, spu_palette[0], spu_palette[1], spu_palette[2])
381 rowheight = (job.project.font_size[1]+job.project.font_size[2]+job.project.space_rows)
382 menu_start_title = (menu_count-1)*titles_per_menu + 1
383 menu_end_title = (menu_count)*titles_per_menu + 1
384 if menu_end_title > nr_titles:
385 menu_end_title = nr_titles+1
387 for title_no in range( menu_start_title , menu_end_title ):
389 top = job.project.space_top + ( menu_i * rowheight )
391 title = job.project.titles[i]
392 titlename = title.name.decode("utf-8")
393 menuitem = "%d. %s" % (title_no, titlename)
394 draw_bg.text((job.project.space_left,top), menuitem, fill=job.project.color_button, font=font1)
395 draw_high.text((job.project.space_left,top), menuitem, fill=1, font=font1)
396 res = re.search("(?:/.*?).*/(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2}).(?P<hour>\d{2})(?P<minute>\d{2}).-.*.?.ts", title.inputfile)
399 subtitle = "%s-%s-%s, %s:%s. " % (res.group("year"),res.group("month"),res.group("day"),res.group("hour"),res.group("minute"))
400 if len(title.descr) > 1:
401 subtitle += title.descr.decode("utf-8") + ". "
402 if len(title.chaptermarks) > 1:
403 subtitle += (" (%d %s)" % (len(title.chaptermarks)+1, _("chapters")))
404 draw_bg.text((job.project.space_left,top+36), subtitle, fill=job.project.color_button, font=font2)
406 bottom = top+rowheight
407 if bottom > imgheight:
410 <button name="button%s" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (str(title_no).zfill(2),job.project.space_left,imgwidth,top,bottom )
412 prev_page_text = "<<<"
413 textsize = draw_bg.textsize(prev_page_text, font=font1)
414 offset = ( 2*job.project.space_left, job.project.space_top + ( titles_per_menu * rowheight ) )
415 draw_bg.text(offset, prev_page_text, fill=job.project.color_button, font=font1)
416 draw_high.text(offset, prev_page_text, fill=1, font=font1)
418 <button name="button_prev" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (offset[0],offset[0]+textsize[0],offset[1],offset[1]+textsize[1])
420 if menu_count < job.nr_menus:
421 next_page_text = ">>>"
422 textsize = draw_bg.textsize(next_page_text, font=font1)
423 offset = ( imgwidth-textsize[0]-2*job.project.space_left, job.project.space_top + ( titles_per_menu * rowheight ) )
424 draw_bg.text(offset, next_page_text, fill=job.project.color_button, font=font1)
425 draw_high.text(offset, next_page_text, fill=1, font=font1)
427 <button name="button_next" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (offset[0],offset[0]+textsize[0],offset[1],offset[1]+textsize[1])
431 fd=open(menubgpngfilename,"w")
434 fd=open(highlightpngfilename,"w")
435 im_high.save(fd,"PNG")
438 png2yuvTask(job, menubgpngfilename, job.workspace+"/dvdmenubg"+str(menu_count)+".yuv")
439 menubgm2vfilename = job.workspace+"/dvdmenubg"+str(menu_count)+".mv2"
440 mpeg2encTask(job, job.workspace+"/dvdmenubg"+str(menu_count)+".yuv", menubgm2vfilename)
441 menubgmpgfilename = job.workspace+"/dvdmenubg"+str(menu_count)+".mpg"
442 MplexTask(job, outputfile=menubgmpgfilename, inputfiles = [menubgm2vfilename, job.project.menuaudio])
448 spuxmlfilename = job.workspace+"/spumux"+str(menu_count)+".xml"
449 f = open(spuxmlfilename, "w")
453 menuoutputfilename = job.workspace+"/dvdmenu"+str(menu_count)+".mpg"
454 spumuxTask(job, spuxmlfilename, menubgmpgfilename, menuoutputfilename)
456 def CreateAuthoringXML(job):
457 nr_titles = len(job.project.titles)
458 titles_per_menu = getTitlesPerMenu(nr_titles)
460 authorxml.append('<?xml version="1.0" encoding="utf-8"?>\n')
461 authorxml.append(' <dvdauthor dest="' + (job.workspace+"/dvd") + '">\n')
462 authorxml.append(' <vmgm>\n')
463 authorxml.append(' <menus>\n')
464 authorxml.append(' <pgc>\n')
465 authorxml.append(' <vob file="' + job.project.vmgm + '" />\n', )
467 authorxml.append(' <post> jump titleset 1 menu; </post>\n')
469 authorxml.append(' <post> jump title 1; </post>\n')
470 authorxml.append(' </pgc>\n')
471 authorxml.append(' </menus>\n')
472 authorxml.append(' </vmgm>\n')
473 authorxml.append(' <titleset>\n')
475 authorxml.append(' <menus>\n')
476 authorxml.append(' <video aspect="4:3"/>\n')
477 for menu_count in range(1 , job.nr_menus+1):
479 authorxml.append(' <pgc entry="root">\n')
481 authorxml.append(' <pgc>\n')
482 menu_start_title = (menu_count-1)*titles_per_menu + 1
483 menu_end_title = (menu_count)*titles_per_menu + 1
484 if menu_end_title > nr_titles:
485 menu_end_title = nr_titles+1
486 for i in range( menu_start_title , menu_end_title ):
487 authorxml.append(' <button name="button' + (str(i).zfill(2)) + '"> jump title ' + str(i) +'; </button>\n')
489 authorxml.append(' <button name="button_prev"> jump menu ' + str(menu_count-1) + '; </button>\n')
490 if menu_count < job.nr_menus:
491 authorxml.append(' <button name="button_next"> jump menu ' + str(menu_count+1) + '; </button>\n')
492 menuoutputfilename = job.workspace+"/dvdmenu"+str(menu_count)+".mpg"
493 authorxml.append(' <vob file="' + menuoutputfilename + '" pause="inf"/>\n')
494 authorxml.append(' </pgc>\n')
495 authorxml.append(' </menus>\n')
496 authorxml.append(' <titles>\n')
497 for i in range( nr_titles ):
498 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])
500 title_filename = job.workspace + "/dvd_title_%d.mpg" % (title_no)
502 LinkTS(job, job.project.vmgm, title_filename)
504 MakeFifoNode(job, title_no)
506 if job.project.linktitles and title_no < nr_titles:
507 post_tag = "jump title %d;" % ( title_no+1 )
508 elif job.project.menu:
509 post_tag = "call vmgm menu 1;"
512 authorxml.append(' <pgc>\n')
513 authorxml.append(' <vob file="' + title_filename + '" chapters="' + chapters + '" />\n')
514 authorxml.append(' <post> ' + post_tag + ' </post>\n')
515 authorxml.append(' </pgc>\n')
517 authorxml.append(' </titles>\n')
518 authorxml.append(' </titleset>\n')
519 authorxml.append(' </dvdauthor>\n')
520 f = open(job.workspace+"/dvdauthor.xml", "w")
526 def __init__(self, project, menupreview=False):
527 Job.__init__(self, "DVD Burn")
528 self.project = project
529 from time import strftime
530 from Tools.Directories import SCOPE_HDD, resolveFilename, createDir
531 new_workspace = resolveFilename(SCOPE_HDD) + "tmp/" + strftime("%Y%m%d%H%M%S")
532 createDir(new_workspace, True)
533 self.workspace = new_workspace
534 self.project.workspace = self.workspace
535 self.menupreview = menupreview
539 if self.project.menu or self.menupreview:
541 CreateAuthoringXML(self)
543 totalsize = 50*1024*1024 # require an extra safety 50 MB
545 for title in self.project.titles:
546 titlesize = title.estimatedDiskspace
547 if titlesize > maxsize: maxsize = titlesize
548 totalsize += titlesize
549 diskSpaceNeeded = totalsize + maxsize
550 print "diskSpaceNeeded:", diskSpaceNeeded
552 DVDAuthorTask(self, diskSpaceNeeded)
554 nr_titles = len(self.project.titles)
559 for self.i in range(nr_titles):
560 title = self.project.titles[self.i]
561 link_name = self.workspace + "/source_title_%d.ts" % (self.i+1)
562 title_filename = self.workspace + "/dvd_title_%d.mpg" % (self.i+1)
563 LinkTS(self, title.inputfile, link_name)
564 demux = DemuxTask(self, link_name)
565 MplexTask(self, outputfile=title_filename, demux_task=demux)
566 RemoveESFiles(self, demux)
567 WaitForResidentTasks(self)
570 #RemoveDVDFolder(self)
572 def Burn(session, project):
573 print "burning cuesheet!"
575 job_manager.AddJob(j)
578 def PreviewMenu(session, project):
579 print "preview DVD menu!"
580 j = DVDJob(project, menupreview=True)
581 job_manager.AddJob(j)