Merge branch 'bug_539_add_multicontent_pixmap_progress'
[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("png2yuv")
9                 self.args += ["-n1", "-Ip", "-f25", "-j", inputfile]
10                 self.dumpFile = outputfile
11                 self.weighting = 15
12
13         def run(self, callback):
14                 Task.run(self, callback)
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("mpeg2enc")
25                 self.args += ["-f8", "-np", "-a2", "-o", outputfile]
26                 self.inputFile = inputfile
27                 self.weighting = 25
28                 
29         def run(self, callback):
30                 Task.run(self, callback)
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("spumux")
40                 self.args += [xmlfile]
41                 self.inputFile = inputfile
42                 self.dumpFile = outputfile
43                 self.weighting = 15
44
45         def run(self, callback):
46                 Task.run(self, callback)
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("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("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("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("projectx")
88                 self.args += [inputfile, "-demux", "-out", self.job.workspace ]
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.currentPID = None
95                 self.relevantAudioPIDs = [ ]
96                 self.getRelevantAudioPIDs(title)
97                 self.generated_files = [ ]
98                 self.mplex_audiofiles = { }
99                 self.mplex_videofile = ""
100                 self.mplex_streamfiles = [ ]
101                 if len(self.cutlist) > 1:
102                         self.args += [ "-cut", self.cutfile ]
103
104         def prepare(self):
105                 self.writeCutfile()
106
107         def getRelevantAudioPIDs(self, title):
108                 for audiotrack in title.properties.audiotracks:
109                         if audiotrack.active.getValue():
110                                 self.relevantAudioPIDs.append(audiotrack.pid.getValue())
111
112         def processOutputLine(self, line):
113                 line = line[:-1]
114                 #print "[DemuxTask]", line
115                 MSG_NEW_FILE = "---> new File: "
116                 MSG_PROGRESS = "[PROGRESS] "
117                 MSG_NEW_MP2 = "++> Mpg Audio: PID 0x"
118                 MSG_NEW_AC3 = "++> AC3/DTS Audio: PID 0x"
119
120                 if line.startswith(MSG_NEW_FILE):
121                         file = line[len(MSG_NEW_FILE):]
122                         if file[0] == "'":
123                                 file = file[1:-1]
124                         self.haveNewFile(file)
125                 elif line.startswith(MSG_PROGRESS):
126                         progress = line[len(MSG_PROGRESS):]
127                         self.haveProgress(progress)
128                 elif line.startswith(MSG_NEW_MP2) or line.startswith(MSG_NEW_AC3):
129                         try:
130                                 self.currentPID = str(int(line.split(': PID 0x',1)[1].split(' ',1)[0],16))
131                         except ValueError:
132                                 print "[DemuxTask] ERROR: couldn't detect Audio PID (projectx too old?)"
133
134         def haveNewFile(self, file):
135                 print "[DemuxTask] produced file:", file, self.currentPID
136                 self.generated_files.append(file)
137                 if self.currentPID in self.relevantAudioPIDs:
138                         self.mplex_audiofiles[self.currentPID] = file
139                 elif file.endswith("m2v"):
140                         self.mplex_videofile = file
141
142         def haveProgress(self, progress):
143                 #print "PROGRESS [%s]" % progress
144                 MSG_CHECK = "check & synchronize audio file"
145                 MSG_DONE = "done..."
146                 if progress == "preparing collection(s)...":
147                         self.prog_state = 0
148                 elif progress[:len(MSG_CHECK)] == MSG_CHECK:
149                         self.prog_state += 1
150                 else:
151                         try:
152                                 p = int(progress)
153                                 p = p - 1 + self.prog_state * 100
154                                 if p > self.progress:
155                                         self.progress = p
156                         except ValueError:
157                                 pass
158
159         def writeCutfile(self):
160                 f = open(self.cutfile, "w")
161                 f.write("CollectionPanel.CutMode=4\n")
162                 for p in self.cutlist:
163                         s = p / 90000
164                         m = s / 60
165                         h = m / 60
166
167                         m %= 60
168                         s %= 60
169
170                         f.write("%02d:%02d:%02d\n" % (h, m, s))
171                 f.close()
172
173         def cleanup(self, failed):
174                 print "[DemuxTask::cleanup]"
175                 self.mplex_streamfiles = [ self.mplex_videofile ]
176                 for pid in self.relevantAudioPIDs:
177                         self.mplex_streamfiles.append(self.mplex_audiofiles[pid])
178                 print self.mplex_streamfiles
179
180                 if failed:
181                         import os
182                         for file in self.generated_files:
183                                 try:
184                                         os.remove(file)
185                                 except OSError:
186                                         pass
187
188 class MplexTaskPostcondition(Condition):
189         def check(self, task):
190                 if task.error == task.ERROR_UNDERRUN:
191                         return True
192                 return task.error is None
193
194         def getErrorMessage(self, task):
195                 return {
196                         task.ERROR_UNDERRUN: ("Can't multiplex source video!"),
197                         task.ERROR_UNKNOWN: ("An unknown error occured!")
198                 }[task.error]
199
200 class MplexTask(Task):
201         ERROR_UNDERRUN, ERROR_UNKNOWN = range(2)
202         def __init__(self, job, outputfile, inputfiles=None, demux_task=None, weighting = 500):
203                 Task.__init__(self, job, "Mux ES into PS")
204                 self.weighting = weighting
205                 self.demux_task = demux_task
206                 self.postconditions.append(MplexTaskPostcondition())
207                 self.setTool("mplex")
208                 self.args += ["-f8", "-o", outputfile, "-v1"]
209                 if inputfiles:
210                         self.args += inputfiles
211
212         def setTool(self, tool):
213                 self.cmd = tool
214                 self.args = [tool]
215                 self.global_preconditions.append(ToolExistsPrecondition())
216                 # 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)
217
218         def prepare(self):
219                 self.error = None
220                 if self.demux_task:
221                         self.args += self.demux_task.mplex_streamfiles
222
223         def processOutputLine(self, line):
224                 print "[MplexTask] ", line[:-1]
225                 if line.startswith("**ERROR:"):
226                         if line.find("Frame data under-runs detected") != -1:
227                                 self.error = self.ERROR_UNDERRUN
228                         else:
229                                 self.error = self.ERROR_UNKNOWN
230
231 class RemoveESFiles(Task):
232         def __init__(self, job, demux_task):
233                 Task.__init__(self, job, "Remove temp. files")
234                 self.demux_task = demux_task
235                 self.setTool("rm")
236                 self.weighting = 10
237
238         def prepare(self):
239                 self.args += ["-f"]
240                 self.args += self.demux_task.generated_files
241                 self.args += [self.demux_task.cutfile]
242
243 class DVDAuthorTask(Task):
244         def __init__(self, job):
245                 Task.__init__(self, job, "Authoring DVD")
246                 self.weighting = 20
247                 self.setTool("dvdauthor")
248                 self.CWD = self.job.workspace
249                 self.args += ["-x", self.job.workspace+"/dvdauthor.xml"]
250                 self.menupreview = job.menupreview
251
252         def processOutputLine(self, line):
253                 print "[DVDAuthorTask] ", line[:-1]
254                 if not self.menupreview and line.startswith("STAT: Processing"):
255                         self.callback(self, [], stay_resident=True)
256                 elif line.startswith("STAT: VOBU"):
257                         try:
258                                 progress = int(line.split("MB")[0].split(" ")[-1])
259                                 if progress:
260                                         self.job.mplextask.progress = progress
261                                         print "[DVDAuthorTask] update mplextask progress:", self.job.mplextask.progress, "of", self.job.mplextask.end
262                         except:
263                                 print "couldn't set mux progress"
264
265 class DVDAuthorFinalTask(Task):
266         def __init__(self, job):
267                 Task.__init__(self, job, "dvdauthor finalize")
268                 self.setTool("dvdauthor")
269                 self.args += ["-T", "-o", self.job.workspace + "/dvd"]
270
271 class WaitForResidentTasks(Task):
272         def __init__(self, job):
273                 Task.__init__(self, job, "waiting for dvdauthor to finalize")
274                 
275         def run(self, callback):
276                 print "waiting for %d resident task(s) %s to finish..." % (len(self.job.resident_tasks),str(self.job.resident_tasks))
277                 self.callback = callback
278                 if self.job.resident_tasks == 0:
279                         callback(self, [])
280
281 class BurnTaskPostcondition(Condition):
282         RECOVERABLE = True
283         def check(self, task):
284                 if task.returncode == 0:
285                         return True
286                 elif task.error is None or task.error is task.ERROR_MINUSRWBUG:
287                         return True
288                 return False
289
290         def getErrorMessage(self, task):
291                 return {
292                         task.ERROR_NOTWRITEABLE: _("Medium is not a writeable DVD!"),
293                         task.ERROR_LOAD: _("Could not load Medium! No disc inserted?"),
294                         task.ERROR_SIZE: _("Content does not fit on DVD!"),
295                         task.ERROR_WRITE_FAILED: _("Write failed!"),
296                         task.ERROR_DVDROM: _("No (supported) DVDROM found!"),
297                         task.ERROR_ISOFS: _("Medium is not empty!"),
298                         task.ERROR_FILETOOLARGE: _("TS file is too large for ISO9660 level 1!"),
299                         task.ERROR_ISOTOOLARGE: _("ISO file is too large for this filesystem!"),
300                         task.ERROR_UNKNOWN: _("An unknown error occured!")
301                 }[task.error]
302
303 class BurnTask(Task):
304         ERROR_NOTWRITEABLE, ERROR_LOAD, ERROR_SIZE, ERROR_WRITE_FAILED, ERROR_DVDROM, ERROR_ISOFS, ERROR_FILETOOLARGE, ERROR_ISOTOOLARGE, ERROR_MINUSRWBUG, ERROR_UNKNOWN = range(10)
305         def __init__(self, job, extra_args=[], tool="growisofs"):
306                 Task.__init__(self, job, job.name)
307                 self.weighting = 500
308                 self.end = 120 # 100 for writing, 10 for buffer flush, 10 for closing disc
309                 self.postconditions.append(BurnTaskPostcondition())
310                 self.setTool(tool)
311                 self.args += extra_args
312         
313         def prepare(self):
314                 self.error = None
315
316         def processOutputLine(self, line):
317                 line = line[:-1]
318                 print "[GROWISOFS] %s" % line
319                 if line[8:14] == "done, ":
320                         self.progress = float(line[:6])
321                         print "progress:", self.progress
322                 elif line.find("flushing cache") != -1:
323                         self.progress = 100
324                 elif line.find("closing disc") != -1:
325                         self.progress = 110
326                 elif line.startswith(":-["):
327                         if line.find("ASC=30h") != -1:
328                                 self.error = self.ERROR_NOTWRITEABLE
329                         elif line.find("ASC=24h") != -1:
330                                 self.error = self.ERROR_LOAD
331                         elif line.find("SK=5h/ASC=A8h/ACQ=04h") != -1:
332                                 self.error = self.ERROR_MINUSRWBUG
333                         else:
334                                 self.error = self.ERROR_UNKNOWN
335                                 print "BurnTask: unknown error %s" % line
336                 elif line.startswith(":-("):
337                         if line.find("No space left on device") != -1:
338                                 self.error = self.ERROR_SIZE
339                         elif self.error == self.ERROR_MINUSRWBUG:
340                                 print "*sigh* this is a known bug. we're simply gonna assume everything is fine."
341                                 self.postconditions = []
342                         elif line.find("write failed") != -1:
343                                 self.error = self.ERROR_WRITE_FAILED
344                         elif line.find("unable to open64(") != -1 and line.find(",O_RDONLY): No such file or directory") != -1:
345                                 self.error = self.ERROR_DVDROM
346                         elif line.find("media is not recognized as recordable DVD") != -1:
347                                 self.error = self.ERROR_NOTWRITEABLE
348                         else:
349                                 self.error = self.ERROR_UNKNOWN
350                                 print "BurnTask: unknown error %s" % line
351                 elif line.startswith("FATAL:"):
352                         if line.find("already carries isofs!"):
353                                 self.error = self.ERROR_ISOFS
354                         else:
355                                 self.error = self.ERROR_UNKNOWN
356                                 print "BurnTask: unknown error %s" % line
357                 elif line.find("-allow-limited-size was not specified. There is no way do represent this file size. Aborting.") != -1:
358                         self.error = self.ERROR_FILETOOLARGE
359                 elif line.startswith("genisoimage: File too large."):
360                         self.error = self.ERROR_ISOTOOLARGE
361         
362         def setTool(self, tool):
363                 self.cmd = tool
364                 self.args = [tool]
365                 self.global_preconditions.append(ToolExistsPrecondition())
366
367 class RemoveDVDFolder(Task):
368         def __init__(self, job):
369                 Task.__init__(self, job, "Remove temp. files")
370                 self.setTool("rm")
371                 self.args += ["-rf", self.job.workspace]
372                 self.weighting = 10
373
374 class CheckDiskspaceTask(Task):
375         def __init__(self, job):
376                 Task.__init__(self, job, "Checking free space")
377                 totalsize = 0 # require an extra safety 50 MB
378                 maxsize = 0
379                 for title in job.project.titles:
380                         titlesize = title.estimatedDiskspace
381                         if titlesize > maxsize: maxsize = titlesize
382                         totalsize += titlesize
383                 diskSpaceNeeded = totalsize + maxsize
384                 job.estimateddvdsize = totalsize / 1024 / 1024
385                 totalsize += 50*1024*1024 # require an extra safety 50 MB
386                 self.global_preconditions.append(DiskspacePrecondition(diskSpaceNeeded))
387                 self.weighting = 5
388
389         def abort(self):
390                 self.finish(aborted = True)
391
392         def run(self, callback):
393                 self.callback = callback
394                 failed_preconditions = self.checkPreconditions(True) + self.checkPreconditions(False)
395                 if len(failed_preconditions):
396                         callback(self, failed_preconditions)
397                         return
398                 Task.processFinished(self, 0)
399
400 class PreviewTask(Task):
401         def __init__(self, job, path):
402                 Task.__init__(self, job, "Preview")
403                 self.postconditions.append(PreviewTaskPostcondition())
404                 self.job = job
405                 self.path = path
406                 self.weighting = 10
407
408         def run(self, callback):
409                 self.callback = callback
410                 if self.job.menupreview:
411                         self.previewProject()
412                 else:
413                         import Screens.Standby
414                         if Screens.Standby.inStandby:
415                                 self.previewCB(False)
416                         else:
417                                 from Tools import Notifications
418                                 Notifications.AddNotificationWithCallback(self.previewCB, MessageBox, _("Do you want to preview this DVD before burning?"), timeout = 60, default = False)
419
420         def abort(self):
421                 self.finish(aborted = True)
422         
423         def previewCB(self, answer):
424                 if answer == True:
425                         self.previewProject()
426                 else:
427                         self.closedCB(True)
428
429         def playerClosed(self):
430                 if self.job.menupreview:
431                         self.closedCB(True)
432                 else:
433                         from Tools import Notifications
434                         Notifications.AddNotificationWithCallback(self.closedCB, MessageBox, _("Do you want to burn this collection to DVD medium?") )
435
436         def closedCB(self, answer):
437                 if answer == True:
438                         Task.processFinished(self, 0)
439                 else:
440                         Task.processFinished(self, 1)
441
442         def previewProject(self):
443                 from Plugins.Extensions.DVDPlayer.plugin import DVDPlayer
444                 self.job.project.session.openWithCallback(self.playerClosed, DVDPlayer, dvd_filelist= [ self.path ])
445
446 class PreviewTaskPostcondition(Condition):
447         def check(self, task):
448                 return task.returncode == 0
449
450         def getErrorMessage(self, task):
451                 return "Cancel"
452
453 class ImagingPostcondition(Condition):
454         def check(self, task):
455                 return task.returncode == 0
456
457         def getErrorMessage(self, task):
458                 return _("Failed") + ": python-imaging"
459
460 class ImagePrepareTask(Task):
461         def __init__(self, job):
462                 Task.__init__(self, job, _("please wait, loading picture..."))
463                 self.postconditions.append(ImagingPostcondition())
464                 self.weighting = 20
465                 self.job = job
466                 self.Menus = job.Menus
467                 
468         def run(self, callback):
469                 self.callback = callback
470                 # we are doing it this weird way so that the TaskView Screen actually pops up before the spinner comes
471                 from enigma import eTimer
472                 self.delayTimer = eTimer()
473                 self.delayTimer.callback.append(self.conduct)
474                 self.delayTimer.start(10,1)
475
476         def conduct(self):
477                 try:
478                         from ImageFont import truetype
479                         from Image import open as Image_open
480                         s = self.job.project.menutemplate.settings
481                         (width, height) = s.dimensions.getValue()
482                         self.Menus.im_bg_orig = Image_open(s.menubg.getValue())
483                         if self.Menus.im_bg_orig.size != (width, height):
484                                 self.Menus.im_bg_orig = self.Menus.im_bg_orig.resize((width, height))
485                         self.Menus.fontsizes = [s.fontsize_headline.getValue(), s.fontsize_title.getValue(), s.fontsize_subtitle.getValue()]
486                         self.Menus.fonts = [(truetype(s.fontface_headline.getValue(), self.Menus.fontsizes[0])), (truetype(s.fontface_title.getValue(), self.Menus.fontsizes[1])),(truetype(s.fontface_subtitle.getValue(), self.Menus.fontsizes[2]))]
487                         Task.processFinished(self, 0)
488                 except:
489                         Task.processFinished(self, 1)
490
491 class MenuImageTask(Task):
492         def __init__(self, job, menu_count, spuxmlfilename, menubgpngfilename, highlightpngfilename):
493                 Task.__init__(self, job, "Create Menu %d Image" % menu_count)
494                 self.postconditions.append(ImagingPostcondition())
495                 self.weighting = 10
496                 self.job = job
497                 self.Menus = job.Menus
498                 self.menu_count = menu_count
499                 self.spuxmlfilename = spuxmlfilename
500                 self.menubgpngfilename = menubgpngfilename
501                 self.highlightpngfilename = highlightpngfilename
502
503         def run(self, callback):
504                 self.callback = callback
505                 #try:
506                 import ImageDraw, Image, os
507                 s = self.job.project.menutemplate.settings
508                 s_top = s.margin_top.getValue()
509                 s_bottom = s.margin_bottom.getValue()
510                 s_left = s.margin_left.getValue()
511                 s_right = s.margin_right.getValue()
512                 s_rows = s.space_rows.getValue()
513                 s_cols = s.space_cols.getValue()
514                 nr_cols = s.cols.getValue()
515                 nr_rows = s.rows.getValue()
516                 thumb_size = s.thumb_size.getValue()
517                 if thumb_size[0]:
518                         from Image import open as Image_open
519                 (s_width, s_height) = s.dimensions.getValue()
520                 fonts = self.Menus.fonts
521                 im_bg = self.Menus.im_bg_orig.copy()
522                 im_high = Image.new("P", (s_width, s_height), 0)
523                 im_high.putpalette(self.Menus.spu_palette)
524                 draw_bg = ImageDraw.Draw(im_bg)
525                 draw_high = ImageDraw.Draw(im_high)
526                 if self.menu_count == 1:
527                         headlineText = self.job.project.settings.name.getValue().decode("utf-8")
528                         headlinePos = self.getPosition(s.offset_headline.getValue(), 0, 0, s_width, s_top, draw_bg.textsize(headlineText, font=fonts[0]))
529                         draw_bg.text(headlinePos, headlineText, fill=self.Menus.color_headline, font=fonts[0])
530                 spuxml = """<?xml version="1.0" encoding="utf-8"?>
531         <subpictures>
532         <stream>
533         <spu 
534         highlight="%s"
535         transparent="%02x%02x%02x"
536         start="00:00:00.00"
537         force="yes" >""" % (self.highlightpngfilename, self.Menus.spu_palette[0], self.Menus.spu_palette[1], self.Menus.spu_palette[2])
538                 #rowheight = (self.Menus.fontsizes[1]+self.Menus.fontsizes[2]+thumb_size[1]+s_rows)
539                 menu_start_title = (self.menu_count-1)*self.job.titles_per_menu + 1
540                 menu_end_title = (self.menu_count)*self.job.titles_per_menu + 1
541                 nr_titles = len(self.job.project.titles)
542                 if menu_end_title > nr_titles:
543                         menu_end_title = nr_titles+1
544                 col = 1
545                 row = 1
546                 for title_no in range( menu_start_title , menu_end_title ):
547                         title = self.job.project.titles[title_no-1]
548                         col_width  = ( s_width  - s_left - s_right  ) / nr_cols
549                         row_height = ( s_height - s_top  - s_bottom ) / nr_rows
550                         left =   s_left + ( (col-1) * col_width ) + s_cols/2
551                         right =    left + col_width - s_cols
552                         top =     s_top + ( (row-1) * row_height) + s_rows/2
553                         bottom =    top + row_height - s_rows
554                         width = right - left
555                         height = bottom - top
556
557                         if bottom > s_height:
558                                 bottom = s_height
559                         #draw_bg.rectangle((left, top, right, bottom), outline=(255,0,0))
560                         im_cell_bg = Image.new("RGBA", (width, height),(0,0,0,0))
561                         draw_cell_bg = ImageDraw.Draw(im_cell_bg)
562                         im_cell_high = Image.new("P", (width, height), 0)
563                         im_cell_high.putpalette(self.Menus.spu_palette)
564                         draw_cell_high = ImageDraw.Draw(im_cell_high)
565
566                         if thumb_size[0]:
567                                 thumbPos = self.getPosition(s.offset_thumb.getValue(), 0, 0, width, height, thumb_size)
568                                 box = (thumbPos[0], thumbPos[1], thumbPos[0]+thumb_size[0], thumbPos[1]+thumb_size[1])
569                                 try:
570                                         thumbIm = Image_open(title.inputfile.rsplit('.',1)[0] + ".png")
571                                         im_cell_bg.paste(thumbIm,thumbPos)
572                                 except:
573                                         draw_cell_bg.rectangle(box, fill=(64,127,127,127))
574                                 border = s.thumb_border.getValue()
575                                 if border:
576                                         draw_cell_high.rectangle(box, fill=1)
577                                         draw_cell_high.rectangle((box[0]+border, box[1]+border, box[2]-border, box[3]-border), fill=0)
578
579                         titleText = title.formatDVDmenuText(s.titleformat.getValue(), title_no).decode("utf-8")
580                         titlePos = self.getPosition(s.offset_title.getValue(), 0, 0, width, height, draw_bg.textsize(titleText, font=fonts[1]))
581
582                         draw_cell_bg.text(titlePos, titleText, fill=self.Menus.color_button, font=fonts[1])
583                         draw_cell_high.text(titlePos, titleText, fill=1, font=self.Menus.fonts[1])
584                         
585                         subtitleText = title.formatDVDmenuText(s.subtitleformat.getValue(), title_no).decode("utf-8")
586                         subtitlePos = self.getPosition(s.offset_subtitle.getValue(), 0, 0, width, height, draw_cell_bg.textsize(subtitleText, font=fonts[2]))
587                         draw_cell_bg.text(subtitlePos, subtitleText, fill=self.Menus.color_button, font=fonts[2])
588
589                         del draw_cell_bg
590                         del draw_cell_high
591                         im_bg.paste(im_cell_bg,(left, top, right, bottom), mask=im_cell_bg)
592                         im_high.paste(im_cell_high,(left, top, right, bottom))
593
594                         spuxml += """
595         <button name="button%s" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (str(title_no).zfill(2),left,right,top,bottom )
596                         if col < nr_cols:
597                                 col += 1
598                         else:
599                                 col = 1
600                                 row += 1
601
602                 top = s_height - s_bottom - s_rows/2
603                 if self.menu_count < self.job.nr_menus:
604                         next_page_text = s.next_page_text.getValue().decode("utf-8")
605                         textsize = draw_bg.textsize(next_page_text, font=fonts[1])
606                         pos = ( s_width-textsize[0]-s_right, top )
607                         draw_bg.text(pos, next_page_text, fill=self.Menus.color_button, font=fonts[1])
608                         draw_high.text(pos, next_page_text, fill=1, font=fonts[1])
609                         spuxml += """
610         <button name="button_next" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (pos[0],pos[0]+textsize[0],pos[1],pos[1]+textsize[1])
611                 if self.menu_count > 1:
612                         prev_page_text = s.prev_page_text.getValue().decode("utf-8")
613                         textsize = draw_bg.textsize(prev_page_text, font=fonts[1])
614                         pos = ( (s_left+s_cols/2), top )
615                         draw_bg.text(pos, prev_page_text, fill=self.Menus.color_button, font=fonts[1])
616                         draw_high.text(pos, prev_page_text, fill=1, font=fonts[1])
617                         spuxml += """
618         <button name="button_prev" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (pos[0],pos[0]+textsize[0],pos[1],pos[1]+textsize[1])
619                 del draw_bg
620                 del draw_high
621                 fd=open(self.menubgpngfilename,"w")
622                 im_bg.save(fd,"PNG")
623                 fd.close()
624                 fd=open(self.highlightpngfilename,"w")
625                 im_high.save(fd,"PNG")
626                 fd.close()
627                 spuxml += """
628         </spu>
629         </stream>
630         </subpictures>"""
631
632                 f = open(self.spuxmlfilename, "w")
633                 f.write(spuxml)
634                 f.close()
635                 Task.processFinished(self, 0)
636                 #except:
637                         #Task.processFinished(self, 1)
638                         
639         def getPosition(self, offset, left, top, right, bottom, size):
640                 pos = [left, top]
641                 if offset[0] != -1:
642                         pos[0] += offset[0]
643                 else:
644                         pos[0] += ( (right-left) - size[0] ) / 2
645                 if offset[1] != -1:
646                         pos[1] += offset[1]
647                 else:
648                         pos[1] += ( (bottom-top) - size[1] ) / 2
649                 return tuple(pos)
650
651 class Menus:
652         def __init__(self, job):
653                 self.job = job
654                 job.Menus = self
655
656                 s = self.job.project.menutemplate.settings
657
658                 self.color_headline = tuple(s.color_headline.getValue())
659                 self.color_button = tuple(s.color_button.getValue())
660                 self.color_highlight = tuple(s.color_highlight.getValue())
661                 self.spu_palette = [ 0x60, 0x60, 0x60 ] + s.color_highlight.getValue()
662
663                 ImagePrepareTask(job)
664                 nr_titles = len(job.project.titles)
665                 
666                 job.titles_per_menu = s.cols.getValue()*s.rows.getValue()
667
668                 job.nr_menus = ((nr_titles+job.titles_per_menu-1)/job.titles_per_menu)
669
670                 #a new menu_count every 4 titles (1,2,3,4->1 ; 5,6,7,8->2 etc.)
671                 for menu_count in range(1 , job.nr_menus+1):
672                         num = str(menu_count)
673                         spuxmlfilename = job.workspace+"/spumux"+num+".xml"
674                         menubgpngfilename = job.workspace+"/dvd_menubg"+num+".png"
675                         highlightpngfilename = job.workspace+"/dvd_highlight"+num+".png"
676                         MenuImageTask(job, menu_count, spuxmlfilename, menubgpngfilename, highlightpngfilename)
677                         png2yuvTask(job, menubgpngfilename, job.workspace+"/dvdmenubg"+num+".yuv")
678                         menubgm2vfilename = job.workspace+"/dvdmenubg"+num+".mv2"
679                         mpeg2encTask(job, job.workspace+"/dvdmenubg"+num+".yuv", menubgm2vfilename)
680                         menubgmpgfilename = job.workspace+"/dvdmenubg"+num+".mpg"
681                         menuaudiofilename = s.menuaudio.getValue()
682                         MplexTask(job, outputfile=menubgmpgfilename, inputfiles = [menubgm2vfilename, menuaudiofilename], weighting = 20)
683                         menuoutputfilename = job.workspace+"/dvdmenu"+num+".mpg"
684                         spumuxTask(job, spuxmlfilename, menubgmpgfilename, menuoutputfilename)
685                 
686 def CreateAuthoringXML_singleset(job):
687         nr_titles = len(job.project.titles)
688         mode = job.project.settings.authormode.getValue()
689         authorxml = []
690         authorxml.append('<?xml version="1.0" encoding="utf-8"?>\n')
691         authorxml.append(' <dvdauthor dest="' + (job.workspace+"/dvd") + '">\n')
692         authorxml.append('  <vmgm>\n')
693         authorxml.append('   <menus lang="' + job.project.menutemplate.settings.menulang.getValue() + '">\n')
694         authorxml.append('    <pgc>\n')
695         authorxml.append('     <vob file="' + job.project.settings.vmgm.getValue() + '" />\n', )
696         if mode.startswith("menu"):
697                 authorxml.append('     <post> jump titleset 1 menu; </post>\n')
698         else:
699                 authorxml.append('     <post> jump title 1; </post>\n')
700         authorxml.append('    </pgc>\n')
701         authorxml.append('   </menus>\n')
702         authorxml.append('  </vmgm>\n')
703         authorxml.append('  <titleset>\n')
704         if mode.startswith("menu"):
705                 authorxml.append('   <menus lang="' + job.project.menutemplate.settings.menulang.getValue() + '">\n')
706                 authorxml.append('    <video aspect="4:3"/>\n')
707                 for menu_count in range(1 , job.nr_menus+1):
708                         if menu_count == 1:
709                                 authorxml.append('    <pgc entry="root">\n')
710                         else:
711                                 authorxml.append('    <pgc>\n')
712                         menu_start_title = (menu_count-1)*job.titles_per_menu + 1
713                         menu_end_title = (menu_count)*job.titles_per_menu + 1
714                         if menu_end_title > nr_titles:
715                                 menu_end_title = nr_titles+1
716                         for i in range( menu_start_title , menu_end_title ):
717                                 authorxml.append('     <button name="button' + (str(i).zfill(2)) + '"> jump title ' + str(i) +'; </button>\n')
718                         if menu_count > 1:
719                                 authorxml.append('     <button name="button_prev"> jump menu ' + str(menu_count-1) + '; </button>\n')
720                         if menu_count < job.nr_menus:
721                                 authorxml.append('     <button name="button_next"> jump menu ' + str(menu_count+1) + '; </button>\n')
722                         menuoutputfilename = job.workspace+"/dvdmenu"+str(menu_count)+".mpg"
723                         authorxml.append('     <vob file="' + menuoutputfilename + '" pause="inf"/>\n')
724                         authorxml.append('    </pgc>\n')
725                 authorxml.append('   </menus>\n')
726         authorxml.append('   <titles>\n')
727         for i in range( nr_titles ):
728                 chapters = ','.join(job.project.titles[i].getChapterMarks())
729                 title_no = i+1
730                 title_filename = job.workspace + "/dvd_title_%d.mpg" % (title_no)
731                 if job.menupreview:
732                         LinkTS(job, job.project.settings.vmgm.getValue(), title_filename)
733                 else:
734                         MakeFifoNode(job, title_no)
735                 if mode.endswith("linked") and title_no < nr_titles:
736                         post_tag = "jump title %d;" % ( title_no+1 )
737                 elif mode.startswith("menu"):
738                         post_tag = "call vmgm menu 1;"
739                 else:   post_tag = ""
740
741                 authorxml.append('    <pgc>\n')
742                 authorxml.append('     <vob file="' + title_filename + '" chapters="' + chapters + '" />\n')
743                 authorxml.append('     <post> ' + post_tag + ' </post>\n')
744                 authorxml.append('    </pgc>\n')
745
746         authorxml.append('   </titles>\n')
747         authorxml.append('  </titleset>\n')
748         authorxml.append(' </dvdauthor>\n')
749         f = open(job.workspace+"/dvdauthor.xml", "w")
750         for x in authorxml:
751                 f.write(x)
752         f.close()
753
754 def CreateAuthoringXML_multiset(job):
755         nr_titles = len(job.project.titles)
756         mode = job.project.settings.authormode.getValue()
757         authorxml = []
758         authorxml.append('<?xml version="1.0" encoding="utf-8"?>\n')
759         authorxml.append(' <dvdauthor dest="' + (job.workspace+"/dvd") + '" jumppad="yes">\n')
760         authorxml.append('  <vmgm>\n')
761         authorxml.append('   <menus lang="' + job.project.menutemplate.settings.menulang.getValue() + '">\n')
762         authorxml.append('    <video aspect="4:3"/>\n')
763         if mode.startswith("menu"):
764                 for menu_count in range(1 , job.nr_menus+1):
765                         if menu_count == 1:
766                                 authorxml.append('    <pgc>\n')
767                         else:
768                                 authorxml.append('    <pgc>\n')
769                         menu_start_title = (menu_count-1)*job.titles_per_menu + 1
770                         menu_end_title = (menu_count)*job.titles_per_menu + 1
771                         if menu_end_title > nr_titles:
772                                 menu_end_title = nr_titles+1
773                         for i in range( menu_start_title , menu_end_title ):
774                                 authorxml.append('     <button name="button' + (str(i).zfill(2)) + '"> jump titleset ' + str(i) +' title 1; </button>\n')
775                         if menu_count > 1:
776                                 authorxml.append('     <button name="button_prev"> jump menu ' + str(menu_count-1) + '; </button>\n')
777                         if menu_count < job.nr_menus:
778                                 authorxml.append('     <button name="button_next"> jump menu ' + str(menu_count+1) + '; </button>\n')
779                         menuoutputfilename = job.workspace+"/dvdmenu"+str(menu_count)+".mpg"
780                         authorxml.append('     <vob file="' + menuoutputfilename + '" pause="inf"/>\n')
781                         authorxml.append('    </pgc>\n')
782         else:
783                 authorxml.append('    <pgc>\n')
784                 authorxml.append('     <vob file="' + job.project.settings.vmgm.getValue() + '" />\n' )
785                 authorxml.append('     <post> jump titleset 1 title 1; </post>\n')
786                 authorxml.append('    </pgc>\n')
787         authorxml.append('   </menus>\n')
788         authorxml.append('  </vmgm>\n')
789
790         for i in range( nr_titles ):
791                 title = job.project.titles[i]
792                 authorxml.append('  <titleset>\n')
793                 authorxml.append('   <menus lang="' + job.project.menutemplate.settings.menulang.getValue() + '">\n')
794                 authorxml.append('    <pgc entry="root">\n')
795                 authorxml.append('     <pre>\n')
796                 authorxml.append('      jump vmgm menu entry title;\n')
797                 authorxml.append('     </pre>\n')
798                 authorxml.append('    </pgc>\n')
799                 authorxml.append('   </menus>\n')
800                 authorxml.append('   <titles>\n')
801                 for audiotrack in title.properties.audiotracks:
802                         active = audiotrack.active.getValue()
803                         if active:
804                                 format = audiotrack.format.getValue()
805                                 language = audiotrack.language.getValue()
806                                 audio_tag = '    <audio format="%s"' % format
807                                 if language != "nolang":
808                                         audio_tag += ' lang="%s"' % language
809                                 audio_tag += ' />\n'
810                                 authorxml.append(audio_tag)
811                 aspect = title.properties.aspect.getValue()
812                 video_tag = '    <video aspect="'+aspect+'"'
813                 if title.properties.widescreen.getValue() == "4:3":
814                         video_tag += ' widescreen="'+title.properties.widescreen.getValue()+'"'
815                 video_tag += ' />\n'
816                 authorxml.append(video_tag)
817                 chapters = ','.join(title.getChapterMarks())
818                 title_no = i+1
819                 title_filename = job.workspace + "/dvd_title_%d.mpg" % (title_no)
820                 if job.menupreview:
821                         LinkTS(job, job.project.settings.vmgm.getValue(), title_filename)
822                 else:
823                         MakeFifoNode(job, title_no)
824                 if mode.endswith("linked") and title_no < nr_titles:
825                         post_tag = "jump titleset %d title 1;" % ( title_no+1 )
826                 elif mode.startswith("menu"):
827                         post_tag = "call vmgm menu 1;"
828                 else:   post_tag = ""
829
830                 authorxml.append('    <pgc>\n')
831                 authorxml.append('     <vob file="' + title_filename + '" chapters="' + chapters + '" />\n')
832                 authorxml.append('     <post> ' + post_tag + ' </post>\n')
833                 authorxml.append('    </pgc>\n')
834                 authorxml.append('   </titles>\n')
835                 authorxml.append('  </titleset>\n')
836         authorxml.append(' </dvdauthor>\n')
837         f = open(job.workspace+"/dvdauthor.xml", "w")
838         for x in authorxml:
839                 f.write(x)
840         f.close()
841
842 def getISOfilename(isopath, volName):
843         from Tools.Directories import fileExists
844         i = 0
845         filename = isopath+'/'+volName+".iso"
846         while fileExists(filename):
847                 i = i+1
848                 filename = isopath+'/'+volName + str(i).zfill(3) + ".iso"
849         return filename
850
851 class DVDJob(Job):
852         def __init__(self, project, menupreview=False):
853                 Job.__init__(self, "DVDBurn Job")
854                 self.project = project
855                 from time import strftime
856                 from Tools.Directories import SCOPE_HDD, resolveFilename, createDir
857                 new_workspace = resolveFilename(SCOPE_HDD) + "tmp/" + strftime("%Y%m%d%H%M%S")
858                 createDir(new_workspace, True)
859                 self.workspace = new_workspace
860                 self.project.workspace = self.workspace
861                 self.menupreview = menupreview
862                 self.conduct()
863
864         def conduct(self):
865                 CheckDiskspaceTask(self)
866                 if self.project.settings.authormode.getValue().startswith("menu") or self.menupreview:
867                         Menus(self)
868                 if self.project.settings.titlesetmode.getValue() == "multi":
869                         CreateAuthoringXML_multiset(self)
870                 else:
871                         CreateAuthoringXML_singleset(self)
872
873                 DVDAuthorTask(self)
874                 
875                 nr_titles = len(self.project.titles)
876
877                 if self.menupreview:
878                         PreviewTask(self, self.workspace + "/dvd/VIDEO_TS/")
879                 else:
880                         for self.i in range(nr_titles):
881                                 self.title = self.project.titles[self.i]
882                                 link_name =  self.workspace + "/source_title_%d.ts" % (self.i+1)
883                                 title_filename = self.workspace + "/dvd_title_%d.mpg" % (self.i+1)
884                                 LinkTS(self, self.title.inputfile, link_name)
885                                 demux = DemuxTask(self, link_name)
886                                 self.mplextask = MplexTask(self, outputfile=title_filename, demux_task=demux)
887                                 self.mplextask.end = self.estimateddvdsize
888                                 RemoveESFiles(self, demux)
889                         WaitForResidentTasks(self)
890                         PreviewTask(self, self.workspace + "/dvd/VIDEO_TS/")
891                         output = self.project.settings.output.getValue()
892                         volName = self.project.settings.name.getValue()
893                         if output == "dvd":
894                                 self.name = _("Burn DVD")
895                                 tool = "growisofs"
896                                 burnargs = [ "-Z", "/dev/" + harddiskmanager.getCD(), "-dvd-compat" ]
897                                 if self.project.size/(1024*1024) > self.project.MAX_SL:
898                                         burnargs += [ "-use-the-force-luke=4gms", "-speed=1", "-R" ]
899                         elif output == "iso":
900                                 self.name = _("Create DVD-ISO")
901                                 tool = "genisoimage"
902                                 isopathfile = getISOfilename(self.project.settings.isopath.getValue(), volName)
903                                 burnargs = [ "-o", isopathfile ]
904                         burnargs += [ "-dvd-video", "-publisher", "Dreambox", "-V", volName, self.workspace + "/dvd" ]
905                         BurnTask(self, burnargs, tool)
906                 RemoveDVDFolder(self)
907
908 class DVDdataJob(Job):
909         def __init__(self, project):
910                 Job.__init__(self, "Data DVD Burn")
911                 self.project = project
912                 from time import strftime
913                 from Tools.Directories import SCOPE_HDD, resolveFilename, createDir
914                 new_workspace = resolveFilename(SCOPE_HDD) + "tmp/" + strftime("%Y%m%d%H%M%S") + "/dvd/"
915                 createDir(new_workspace, True)
916                 self.workspace = new_workspace
917                 self.project.workspace = self.workspace
918                 self.conduct()
919
920         def conduct(self):
921                 if self.project.settings.output.getValue() == "iso":
922                         CheckDiskspaceTask(self)
923                 nr_titles = len(self.project.titles)
924                 for self.i in range(nr_titles):
925                         title = self.project.titles[self.i]
926                         filename = title.inputfile.rstrip("/").rsplit("/",1)[1]
927                         link_name =  self.workspace + filename
928                         LinkTS(self, title.inputfile, link_name)
929                         CopyMeta(self, title.inputfile)
930
931                 output = self.project.settings.output.getValue()
932                 volName = self.project.settings.name.getValue()
933                 tool = "growisofs"
934                 if output == "dvd":
935                         self.name = _("Burn DVD")
936                         burnargs = [ "-Z", "/dev/" + harddiskmanager.getCD(), "-dvd-compat" ]
937                         if self.project.size/(1024*1024) > self.project.MAX_SL:
938                                 burnargs += [ "-use-the-force-luke=4gms", "-speed=1", "-R" ]
939                 elif output == "iso":
940                         tool = "genisoimage"
941                         self.name = _("Create DVD-ISO")
942                         isopathfile = getISOfilename(self.project.settings.isopath.getValue(), volName)
943                         burnargs = [ "-o", isopathfile ]
944                 if self.project.settings.dataformat.getValue() == "iso9660_1":
945                         burnargs += ["-iso-level", "1" ]
946                 elif self.project.settings.dataformat.getValue() == "iso9660_4":
947                         burnargs += ["-iso-level", "4", "-allow-limited-size" ]
948                 elif self.project.settings.dataformat.getValue() == "udf":
949                         burnargs += ["-udf", "-allow-limited-size" ]
950                 burnargs += [ "-publisher", "Dreambox", "-V", volName, "-follow-links", self.workspace ]
951                 BurnTask(self, burnargs, tool)
952                 RemoveDVDFolder(self)
953
954 class DVDisoJob(Job):
955         def __init__(self, project, imagepath):
956                 Job.__init__(self, _("Burn DVD"))
957                 self.project = project
958                 self.menupreview = False
959                 from Tools.Directories import getSize
960                 if imagepath.endswith(".iso"):
961                         PreviewTask(self, imagepath)
962                         burnargs = [ "-Z", "/dev/" + harddiskmanager.getCD() + '='+imagepath, "-dvd-compat" ]
963                         if getSize(imagepath)/(1024*1024) > self.project.MAX_SL:
964                                 burnargs += [ "-use-the-force-luke=4gms", "-speed=1", "-R" ]
965                 else:
966                         PreviewTask(self, imagepath + "/VIDEO_TS/")
967                         volName = self.project.settings.name.getValue()
968                         burnargs = [ "-Z", "/dev/" + harddiskmanager.getCD(), "-dvd-compat" ]
969                         if getSize(imagepath)/(1024*1024) > self.project.MAX_SL:
970                                 burnargs += [ "-use-the-force-luke=4gms", "-speed=1", "-R" ]
971                         burnargs += [ "-dvd-video", "-publisher", "Dreambox", "-V", volName, imagepath ]
972                 tool = "growisofs"
973                 BurnTask(self, burnargs, tool)