don't crash when removing of temp. files failes
[vuplus_dvbapp] / 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                         from Tools import Notifications
399                         Notifications.AddNotificationWithCallback(self.previewCB, MessageBox, _("Do you want to preview this DVD before burning?"), timeout = 60, default = False)
400
401         def abort(self):
402                 self.finish(aborted = True)
403         
404         def previewCB(self, answer):
405                 if answer == True:
406                         self.previewProject()
407                 else:
408                         self.closedCB(True)
409
410         def playerClosed(self):
411                 if self.job.menupreview:
412                         self.closedCB(True)
413                 else:
414                         from Tools import Notifications
415                         Notifications.AddNotificationWithCallback(self.closedCB, MessageBox, _("Do you want to burn this collection to DVD medium?") )
416
417         def closedCB(self, answer):
418                 if answer == True:
419                         Task.processFinished(self, 0)
420                 else:
421                         Task.processFinished(self, 1)
422
423         def previewProject(self):
424                 from Plugins.Extensions.DVDPlayer.plugin import DVDPlayer
425                 self.job.project.session.openWithCallback(self.playerClosed, DVDPlayer, dvd_filelist= [ self.path ])
426
427 class PreviewTaskPostcondition(Condition):
428         def check(self, task):
429                 return task.returncode == 0
430
431         def getErrorMessage(self, task):
432                 return "Cancel"
433
434 class ImagingPostcondition(Condition):
435         def check(self, task):
436                 return task.returncode == 0
437
438         def getErrorMessage(self, task):
439                 return _("Failed") + ": python-imaging"
440
441 class ImagePrepareTask(Task):
442         def __init__(self, job):
443                 Task.__init__(self, job, _("please wait, loading picture..."))
444                 self.postconditions.append(ImagingPostcondition())
445                 self.weighting = 20
446                 self.job = job
447                 self.Menus = job.Menus
448                 
449         def run(self, callback):
450                 self.callback = callback
451                 # we are doing it this weird way so that the TaskView Screen actually pops up before the spinner comes
452                 from enigma import eTimer
453                 self.delayTimer = eTimer()
454                 self.delayTimer.callback.append(self.conduct)
455                 self.delayTimer.start(10,1)
456
457         def conduct(self):
458                 try:
459                         from ImageFont import truetype
460                         from Image import open as Image_open
461                         s = self.job.project.menutemplate.settings
462                         (width, height) = s.dimensions.getValue()
463                         self.Menus.im_bg_orig = Image_open(s.menubg.getValue())
464                         if self.Menus.im_bg_orig.size != (width, height):
465                                 self.Menus.im_bg_orig = self.Menus.im_bg_orig.resize((width, height))
466                         self.Menus.fontsizes = [s.fontsize_headline.getValue(), s.fontsize_title.getValue(), s.fontsize_subtitle.getValue()]
467                         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]))]
468                         Task.processFinished(self, 0)
469                 except:
470                         Task.processFinished(self, 1)
471
472 class MenuImageTask(Task):
473         def __init__(self, job, menu_count, spuxmlfilename, menubgpngfilename, highlightpngfilename):
474                 Task.__init__(self, job, "Create Menu %d Image" % menu_count)
475                 self.postconditions.append(ImagingPostcondition())
476                 self.weighting = 10
477                 self.job = job
478                 self.Menus = job.Menus
479                 self.menu_count = menu_count
480                 self.spuxmlfilename = spuxmlfilename
481                 self.menubgpngfilename = menubgpngfilename
482                 self.highlightpngfilename = highlightpngfilename
483
484         def run(self, callback):
485                 self.callback = callback
486                 #try:
487                 import ImageDraw, Image, os
488                 s = self.job.project.menutemplate.settings
489                 s_top = s.margin_top.getValue()
490                 s_bottom = s.margin_bottom.getValue()
491                 s_left = s.margin_left.getValue()
492                 s_right = s.margin_right.getValue()
493                 s_rows = s.space_rows.getValue()
494                 s_cols = s.space_cols.getValue()
495                 nr_cols = s.cols.getValue()
496                 nr_rows = s.rows.getValue()
497                 thumb_size = s.thumb_size.getValue()
498                 if thumb_size[0]:
499                         from Image import open as Image_open
500                 (s_width, s_height) = s.dimensions.getValue()
501                 fonts = self.Menus.fonts
502                 im_bg = self.Menus.im_bg_orig.copy()
503                 im_high = Image.new("P", (s_width, s_height), 0)
504                 im_high.putpalette(self.Menus.spu_palette)
505                 draw_bg = ImageDraw.Draw(im_bg)
506                 draw_high = ImageDraw.Draw(im_high)
507                 if self.menu_count == 1:
508                         headlineText = self.job.project.settings.name.getValue().decode("utf-8")
509                         headlinePos = self.getPosition(s.offset_headline.getValue(), 0, 0, s_width, s_top, draw_bg.textsize(headlineText, font=fonts[0]))
510                         draw_bg.text(headlinePos, headlineText, fill=self.Menus.color_headline, font=fonts[0])
511                 spuxml = """<?xml version="1.0" encoding="utf-8"?>
512         <subpictures>
513         <stream>
514         <spu 
515         highlight="%s"
516         transparent="%02x%02x%02x"
517         start="00:00:00.00"
518         force="yes" >""" % (self.highlightpngfilename, self.Menus.spu_palette[0], self.Menus.spu_palette[1], self.Menus.spu_palette[2])
519                 #rowheight = (self.Menus.fontsizes[1]+self.Menus.fontsizes[2]+thumb_size[1]+s_rows)
520                 menu_start_title = (self.menu_count-1)*self.job.titles_per_menu + 1
521                 menu_end_title = (self.menu_count)*self.job.titles_per_menu + 1
522                 nr_titles = len(self.job.project.titles)
523                 if menu_end_title > nr_titles:
524                         menu_end_title = nr_titles+1
525                 col = 1
526                 row = 1
527                 for title_no in range( menu_start_title , menu_end_title ):
528                         title = self.job.project.titles[title_no-1]
529                         col_width  = ( s_width  - s_left - s_right  ) / nr_cols
530                         row_height = ( s_height - s_top  - s_bottom ) / nr_rows
531                         left =   s_left + ( (col-1) * col_width ) + s_cols/2
532                         right =    left + col_width - s_cols
533                         top =     s_top + ( (row-1) * row_height) + s_rows/2
534                         bottom =    top + row_height - s_rows
535                         width = right - left
536                         height = bottom - top
537
538                         if bottom > s_height:
539                                 bottom = s_height
540                         #draw_bg.rectangle((left, top, right, bottom), outline=(255,0,0))
541                         im_cell_bg = Image.new("RGBA", (width, height),(0,0,0,0))
542                         draw_cell_bg = ImageDraw.Draw(im_cell_bg)
543                         im_cell_high = Image.new("P", (width, height), 0)
544                         im_cell_high.putpalette(self.Menus.spu_palette)
545                         draw_cell_high = ImageDraw.Draw(im_cell_high)
546
547                         if thumb_size[0]:
548                                 thumbPos = self.getPosition(s.offset_thumb.getValue(), 0, 0, width, height, thumb_size)
549                                 box = (thumbPos[0], thumbPos[1], thumbPos[0]+thumb_size[0], thumbPos[1]+thumb_size[1])
550                                 try:
551                                         thumbIm = Image_open(title.inputfile.rsplit('.',1)[0] + ".png")
552                                         im_cell_bg.paste(thumbIm,thumbPos)
553                                 except:
554                                         draw_cell_bg.rectangle(box, fill=(64,127,127,127))
555                                 border = s.thumb_border.getValue()
556                                 if border:
557                                         draw_cell_high.rectangle(box, fill=1)
558                                         draw_cell_high.rectangle((box[0]+border, box[1]+border, box[2]-border, box[3]-border), fill=0)
559
560                         titleText = title.formatDVDmenuText(s.titleformat.getValue(), title_no).decode("utf-8")
561                         titlePos = self.getPosition(s.offset_title.getValue(), 0, 0, width, height, draw_bg.textsize(titleText, font=fonts[1]))
562
563                         draw_cell_bg.text(titlePos, titleText, fill=self.Menus.color_button, font=fonts[1])
564                         draw_cell_high.text(titlePos, titleText, fill=1, font=self.Menus.fonts[1])
565                         
566                         subtitleText = title.formatDVDmenuText(s.subtitleformat.getValue(), title_no).decode("utf-8")
567                         subtitlePos = self.getPosition(s.offset_subtitle.getValue(), 0, 0, width, height, draw_cell_bg.textsize(subtitleText, font=fonts[2]))
568                         draw_cell_bg.text(subtitlePos, subtitleText, fill=self.Menus.color_button, font=fonts[2])
569
570                         del draw_cell_bg
571                         del draw_cell_high
572                         im_bg.paste(im_cell_bg,(left, top, right, bottom), mask=im_cell_bg)
573                         im_high.paste(im_cell_high,(left, top, right, bottom))
574
575                         spuxml += """
576         <button name="button%s" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (str(title_no).zfill(2),left,right,top,bottom )
577                         if col < nr_cols:
578                                 col += 1
579                         else:
580                                 col = 1
581                                 row += 1
582
583                 top = s_height - s_bottom - s_rows/2
584                 if self.menu_count < self.job.nr_menus:
585                         next_page_text = s.next_page_text.getValue().decode("utf-8")
586                         textsize = draw_bg.textsize(next_page_text, font=fonts[1])
587                         pos = ( s_width-textsize[0]-s_right, top )
588                         draw_bg.text(pos, next_page_text, fill=self.Menus.color_button, font=fonts[1])
589                         draw_high.text(pos, next_page_text, fill=1, font=fonts[1])
590                         spuxml += """
591         <button name="button_next" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (pos[0],pos[0]+textsize[0],pos[1],pos[1]+textsize[1])
592                 if self.menu_count > 1:
593                         prev_page_text = s.prev_page_text.getValue().decode("utf-8")
594                         textsize = draw_bg.textsize(prev_page_text, font=fonts[1])
595                         pos = ( (s_left+s_cols/2), top )
596                         draw_bg.text(pos, prev_page_text, fill=self.Menus.color_button, font=fonts[1])
597                         draw_high.text(pos, prev_page_text, fill=1, font=fonts[1])
598                         spuxml += """
599         <button name="button_prev" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (pos[0],pos[0]+textsize[0],pos[1],pos[1]+textsize[1])
600                 del draw_bg
601                 del draw_high
602                 fd=open(self.menubgpngfilename,"w")
603                 im_bg.save(fd,"PNG")
604                 fd.close()
605                 fd=open(self.highlightpngfilename,"w")
606                 im_high.save(fd,"PNG")
607                 fd.close()
608                 spuxml += """
609         </spu>
610         </stream>
611         </subpictures>"""
612
613                 f = open(self.spuxmlfilename, "w")
614                 f.write(spuxml)
615                 f.close()
616                 Task.processFinished(self, 0)
617                 #except:
618                         #Task.processFinished(self, 1)
619                         
620         def getPosition(self, offset, left, top, right, bottom, size):
621                 pos = [left, top]
622                 if offset[0] != -1:
623                         pos[0] += offset[0]
624                 else:
625                         pos[0] += ( (right-left) - size[0] ) / 2
626                 if offset[1] != -1:
627                         pos[1] += offset[1]
628                 else:
629                         pos[1] += ( (bottom-top) - size[1] ) / 2
630                 return tuple(pos)
631
632 class Menus:
633         def __init__(self, job):
634                 self.job = job
635                 job.Menus = self
636
637                 s = self.job.project.menutemplate.settings
638
639                 self.color_headline = tuple(s.color_headline.getValue())
640                 self.color_button = tuple(s.color_button.getValue())
641                 self.color_highlight = tuple(s.color_highlight.getValue())
642                 self.spu_palette = [ 0x60, 0x60, 0x60 ] + s.color_highlight.getValue()
643
644                 ImagePrepareTask(job)
645                 nr_titles = len(job.project.titles)
646                 
647                 job.titles_per_menu = s.cols.getValue()*s.rows.getValue()
648
649                 job.nr_menus = ((nr_titles+job.titles_per_menu-1)/job.titles_per_menu)
650
651                 #a new menu_count every 4 titles (1,2,3,4->1 ; 5,6,7,8->2 etc.)
652                 for menu_count in range(1 , job.nr_menus+1):
653                         num = str(menu_count)
654                         spuxmlfilename = job.workspace+"/spumux"+num+".xml"
655                         menubgpngfilename = job.workspace+"/dvd_menubg"+num+".png"
656                         highlightpngfilename = job.workspace+"/dvd_highlight"+num+".png"
657                         MenuImageTask(job, menu_count, spuxmlfilename, menubgpngfilename, highlightpngfilename)
658                         png2yuvTask(job, menubgpngfilename, job.workspace+"/dvdmenubg"+num+".yuv")
659                         menubgm2vfilename = job.workspace+"/dvdmenubg"+num+".mv2"
660                         mpeg2encTask(job, job.workspace+"/dvdmenubg"+num+".yuv", menubgm2vfilename)
661                         menubgmpgfilename = job.workspace+"/dvdmenubg"+num+".mpg"
662                         menuaudiofilename = s.menuaudio.getValue()
663                         MplexTask(job, outputfile=menubgmpgfilename, inputfiles = [menubgm2vfilename, menuaudiofilename], weighting = 20)
664                         menuoutputfilename = job.workspace+"/dvdmenu"+num+".mpg"
665                         spumuxTask(job, spuxmlfilename, menubgmpgfilename, menuoutputfilename)
666                 
667 def CreateAuthoringXML_singleset(job):
668         nr_titles = len(job.project.titles)
669         mode = job.project.settings.authormode.getValue()
670         authorxml = []
671         authorxml.append('<?xml version="1.0" encoding="utf-8"?>\n')
672         authorxml.append(' <dvdauthor dest="' + (job.workspace+"/dvd") + '">\n')
673         authorxml.append('  <vmgm>\n')
674         authorxml.append('   <menus>\n')
675         authorxml.append('    <pgc>\n')
676         authorxml.append('     <vob file="' + job.project.settings.vmgm.getValue() + '" />\n', )
677         if mode.startswith("menu"):
678                 authorxml.append('     <post> jump titleset 1 menu; </post>\n')
679         else:
680                 authorxml.append('     <post> jump title 1; </post>\n')
681         authorxml.append('    </pgc>\n')
682         authorxml.append('   </menus>\n')
683         authorxml.append('  </vmgm>\n')
684         authorxml.append('  <titleset>\n')
685         if mode.startswith("menu"):
686                 authorxml.append('   <menus>\n')
687                 authorxml.append('    <video aspect="4:3"/>\n')
688                 for menu_count in range(1 , job.nr_menus+1):
689                         if menu_count == 1:
690                                 authorxml.append('    <pgc entry="root">\n')
691                         else:
692                                 authorxml.append('    <pgc>\n')
693                         menu_start_title = (menu_count-1)*job.titles_per_menu + 1
694                         menu_end_title = (menu_count)*job.titles_per_menu + 1
695                         if menu_end_title > nr_titles:
696                                 menu_end_title = nr_titles+1
697                         for i in range( menu_start_title , menu_end_title ):
698                                 authorxml.append('     <button name="button' + (str(i).zfill(2)) + '"> jump title ' + str(i) +'; </button>\n')
699                         if menu_count > 1:
700                                 authorxml.append('     <button name="button_prev"> jump menu ' + str(menu_count-1) + '; </button>\n')
701                         if menu_count < job.nr_menus:
702                                 authorxml.append('     <button name="button_next"> jump menu ' + str(menu_count+1) + '; </button>\n')
703                         menuoutputfilename = job.workspace+"/dvdmenu"+str(menu_count)+".mpg"
704                         authorxml.append('     <vob file="' + menuoutputfilename + '" pause="inf"/>\n')
705                         authorxml.append('    </pgc>\n')
706                 authorxml.append('   </menus>\n')
707         authorxml.append('   <titles>\n')
708         for i in range( nr_titles ):
709                 chapters = ','.join(job.project.titles[i].getChapterMarks())
710                 title_no = i+1
711                 title_filename = job.workspace + "/dvd_title_%d.mpg" % (title_no)
712                 if job.menupreview:
713                         LinkTS(job, job.project.settings.vmgm.getValue(), title_filename)
714                 else:
715                         MakeFifoNode(job, title_no)
716                 if mode.endswith("linked") and title_no < nr_titles:
717                         post_tag = "jump title %d;" % ( title_no+1 )
718                 elif mode.startswith("menu"):
719                         post_tag = "call vmgm menu 1;"
720                 else:   post_tag = ""
721
722                 authorxml.append('    <pgc>\n')
723                 authorxml.append('     <vob file="' + title_filename + '" chapters="' + chapters + '" />\n')
724                 authorxml.append('     <post> ' + post_tag + ' </post>\n')
725                 authorxml.append('    </pgc>\n')
726
727         authorxml.append('   </titles>\n')
728         authorxml.append('  </titleset>\n')
729         authorxml.append(' </dvdauthor>\n')
730         f = open(job.workspace+"/dvdauthor.xml", "w")
731         for x in authorxml:
732                 f.write(x)
733         f.close()
734
735 def CreateAuthoringXML_multiset(job):
736         nr_titles = len(job.project.titles)
737         mode = job.project.settings.authormode.getValue()
738         authorxml = []
739         authorxml.append('<?xml version="1.0" encoding="utf-8"?>\n')
740         authorxml.append(' <dvdauthor dest="' + (job.workspace+"/dvd") + '" jumppad="yes">\n')
741         authorxml.append('  <vmgm>\n')
742         authorxml.append('   <menus>\n')
743         authorxml.append('    <video aspect="4:3"/>\n')
744         if mode.startswith("menu"):
745                 for menu_count in range(1 , job.nr_menus+1):
746                         authorxml.append('    <pgc>\n')
747                         menu_start_title = (menu_count-1)*job.titles_per_menu + 1
748                         menu_end_title = (menu_count)*job.titles_per_menu + 1
749                         if menu_end_title > nr_titles:
750                                 menu_end_title = nr_titles+1
751                         for i in range( menu_start_title , menu_end_title ):
752                                 authorxml.append('     <button name="button' + (str(i).zfill(2)) + '"> jump titleset ' + str(i) +' title 1; </button>\n')
753                         if menu_count > 1:
754                                 authorxml.append('     <button name="button_prev"> jump menu ' + str(menu_count-1) + '; </button>\n')
755                         if menu_count < job.nr_menus:
756                                 authorxml.append('     <button name="button_next"> jump menu ' + str(menu_count+1) + '; </button>\n')
757                         menuoutputfilename = job.workspace+"/dvdmenu"+str(menu_count)+".mpg"
758                         authorxml.append('     <vob file="' + menuoutputfilename + '" pause="inf"/>\n')
759                         authorxml.append('    </pgc>\n')
760         else:
761                 authorxml.append('    <pgc>\n')
762                 authorxml.append('     <vob file="' + job.project.settings.vmgm.getValue() + '" />\n' )
763                 authorxml.append('     <post> jump titleset 1 title 1; </post>\n')
764                 authorxml.append('    </pgc>\n')
765         authorxml.append('   </menus>\n')
766         authorxml.append('  </vmgm>\n')
767
768         for i in range( nr_titles ):
769                 title = job.project.titles[i]
770                 authorxml.append('  <titleset>\n')
771                 authorxml.append('   <titles>\n')
772                 for audiotrack in title.properties.audiotracks:
773                         active = audiotrack.active.getValue()
774                         if active:
775                                 format = audiotrack.format.getValue()
776                                 language = audiotrack.language.getValue()
777                                 audio_tag = '    <audio format="%s"' % format
778                                 if language != "nolang":
779                                         audio_tag += ' lang="%s"' % language
780                                 audio_tag += ' />\n'
781                                 authorxml.append(audio_tag)
782                 aspect = title.properties.aspect.getValue()
783                 video_tag = '    <video aspect="'+aspect+'"'
784                 if title.properties.widescreen.getValue() == "4:3":
785                         video_tag += ' widescreen="'+title.properties.widescreen.getValue()+'"'
786                 video_tag += ' />\n'
787                 authorxml.append(video_tag)
788                 chapters = ','.join(title.getChapterMarks())
789                 title_no = i+1
790                 title_filename = job.workspace + "/dvd_title_%d.mpg" % (title_no)
791                 if job.menupreview:
792                         LinkTS(job, job.project.settings.vmgm.getValue(), title_filename)
793                 else:
794                         MakeFifoNode(job, title_no)
795                 if mode.endswith("linked") and title_no < nr_titles:
796                         post_tag = "jump titleset %d title 1;" % ( title_no+1 )
797                 elif mode.startswith("menu"):
798                         post_tag = "call vmgm menu 1;"
799                 else:   post_tag = ""
800
801                 authorxml.append('    <pgc>\n')
802                 authorxml.append('     <vob file="' + title_filename + '" chapters="' + chapters + '" />\n')
803                 authorxml.append('     <post> ' + post_tag + ' </post>\n')
804                 authorxml.append('    </pgc>\n')
805                 authorxml.append('   </titles>\n')
806                 authorxml.append('  </titleset>\n')
807         authorxml.append(' </dvdauthor>\n')
808         f = open(job.workspace+"/dvdauthor.xml", "w")
809         for x in authorxml:
810                 f.write(x)
811         f.close()
812
813 def getISOfilename(isopath, volName):
814         from Tools.Directories import fileExists
815         i = 0
816         filename = isopath+'/'+volName+".iso"
817         while fileExists(filename):
818                 i = i+1
819                 filename = isopath+'/'+volName + str(i).zfill(3) + ".iso"
820         return filename
821
822 class DVDJob(Job):
823         def __init__(self, project, menupreview=False):
824                 Job.__init__(self, "DVDBurn Job")
825                 self.project = project
826                 from time import strftime
827                 from Tools.Directories import SCOPE_HDD, resolveFilename, createDir
828                 new_workspace = resolveFilename(SCOPE_HDD) + "tmp/" + strftime("%Y%m%d%H%M%S")
829                 createDir(new_workspace, True)
830                 self.workspace = new_workspace
831                 self.project.workspace = self.workspace
832                 self.menupreview = menupreview
833                 self.conduct()
834
835         def conduct(self):
836                 CheckDiskspaceTask(self)
837                 if self.project.settings.authormode.getValue().startswith("menu") or self.menupreview:
838                         Menus(self)
839                 if self.project.settings.titlesetmode.getValue() == "multi":
840                         CreateAuthoringXML_multiset(self)
841                 else:
842                         CreateAuthoringXML_singleset(self)
843
844                 DVDAuthorTask(self)
845                 
846                 nr_titles = len(self.project.titles)
847
848                 if self.menupreview:
849                         PreviewTask(self, self.workspace + "/dvd/VIDEO_TS/")
850                 else:
851                         for self.i in range(nr_titles):
852                                 self.title = self.project.titles[self.i]
853                                 link_name =  self.workspace + "/source_title_%d.ts" % (self.i+1)
854                                 title_filename = self.workspace + "/dvd_title_%d.mpg" % (self.i+1)
855                                 LinkTS(self, self.title.inputfile, link_name)
856                                 demux = DemuxTask(self, link_name)
857                                 self.mplextask = MplexTask(self, outputfile=title_filename, demux_task=demux)
858                                 self.mplextask.end = self.estimateddvdsize
859                                 RemoveESFiles(self, demux)
860                         WaitForResidentTasks(self)
861                         PreviewTask(self, self.workspace + "/dvd/VIDEO_TS/")
862                         output = self.project.settings.output.getValue()
863                         volName = self.project.settings.name.getValue()
864                         if output == "dvd":
865                                 self.name = _("Burn DVD")
866                                 tool = "/bin/growisofs"
867                                 burnargs = [ "-Z", "/dev/" + harddiskmanager.getCD(), "-dvd-compat" ]
868                         elif output == "iso":
869                                 self.name = _("Create DVD-ISO")
870                                 tool = "/usr/bin/mkisofs"
871                                 isopathfile = getISOfilename(self.project.settings.isopath.getValue(), volName)
872                                 burnargs = [ "-o", isopathfile ]
873                         burnargs += [ "-dvd-video", "-publisher", "Dreambox", "-V", volName, self.workspace + "/dvd" ]
874                         BurnTask(self, burnargs, tool)
875                 RemoveDVDFolder(self)
876
877 class DVDdataJob(Job):
878         def __init__(self, project):
879                 Job.__init__(self, "Data DVD Burn")
880                 self.project = project
881                 from time import strftime
882                 from Tools.Directories import SCOPE_HDD, resolveFilename, createDir
883                 new_workspace = resolveFilename(SCOPE_HDD) + "tmp/" + strftime("%Y%m%d%H%M%S") + "/dvd/"
884                 createDir(new_workspace, True)
885                 self.workspace = new_workspace
886                 self.project.workspace = self.workspace
887                 self.conduct()
888
889         def conduct(self):
890                 if self.project.settings.output.getValue() == "iso":
891                         CheckDiskspaceTask(self)
892                 nr_titles = len(self.project.titles)
893                 for self.i in range(nr_titles):
894                         title = self.project.titles[self.i]
895                         filename = title.inputfile.rstrip("/").rsplit("/",1)[1]
896                         link_name =  self.workspace + filename
897                         LinkTS(self, title.inputfile, link_name)
898                         CopyMeta(self, title.inputfile)
899
900                 output = self.project.settings.output.getValue()
901                 volName = self.project.settings.name.getValue()
902                 tool = "/bin/growisofs"
903                 if output == "dvd":
904                         self.name = _("Burn DVD")
905                         burnargs = [ "-Z", "/dev/" + harddiskmanager.getCD(), "-dvd-compat" ]
906                 elif output == "iso":
907                         tool = "/usr/bin/mkisofs"
908                         self.name = _("Create DVD-ISO")
909                         isopathfile = getISOfilename(self.project.settings.isopath.getValue(), volName)
910                         burnargs = [ "-o", isopathfile ]
911                 if self.project.settings.dataformat.getValue() == "iso9660_1":
912                         burnargs += ["-iso-level", "1" ]
913                 elif self.project.settings.dataformat.getValue() == "iso9660_4":
914                         burnargs += ["-iso-level", "4", "-allow-limited-size" ]
915                 elif self.project.settings.dataformat.getValue() == "udf":
916                         burnargs += ["-udf", "-allow-limited-size" ]
917                 burnargs += [ "-publisher", "Dreambox", "-V", volName, "-follow-links", self.workspace ]
918                 BurnTask(self, burnargs, tool)
919                 RemoveDVDFolder(self)
920
921 class DVDisoJob(Job):
922         def __init__(self, project, imagepath):
923                 Job.__init__(self, _("Burn DVD"))
924                 self.project = project
925                 self.menupreview = False
926                 if imagepath.endswith(".iso"):
927                         PreviewTask(self, imagepath)
928                         burnargs = [ "-Z", "/dev/" + harddiskmanager.getCD() + '='+imagepath, "-dvd-compat" ]
929                 else:
930                         PreviewTask(self, imagepath + "/VIDEO_TS/")
931                         volName = self.project.settings.name.getValue()
932                         burnargs = [ "-Z", "/dev/" + harddiskmanager.getCD(), "-dvd-compat" ]
933                         burnargs += [ "-dvd-video", "-publisher", "Dreambox", "-V", volName, imagepath ]
934                 tool = "/bin/growisofs"
935                 BurnTask(self, burnargs, tool)