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