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