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