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