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