aboutsummaryrefslogtreecommitdiff
path: root/lib/python/Plugins/Extensions/DVDBurn/Process.py
blob: 217c724cc26b2789c3ca2671ba71672a29c79dca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
from Components.Task import Task, Job, job_manager, DiskspacePrecondition, Condition

class MakeFifoNode(Task):
	def __init__(self, job, number):
		Task.__init__(self, job, "Make FIFO Nodes")
		self.setTool("/bin/mknod")
		nodename = self.job.workspace + "/dvd_title_%d" % number + ".mpg"
		self.args += [nodename, "p"]

class LinkTS(Task):
	def __init__(self, job, sourcefile, link_name):
		Task.__init__(self, job, "Creating Symlink for source titles")
		self.setTool("/bin/ln")
		self.args += ["-s", sourcefile, link_name]

class DemuxTask(Task):
	def __init__(self, job, inputfile, cutlist):
		Task.__init__(self, job, "Demux video into ES")

		self.global_preconditions.append(DiskspacePrecondition(4*1024*1024))
		self.setTool("/usr/bin/projectx")
		self.cutfile = self.job.workspace + "/cut.Xcl"
		self.generated_files = [ ]
		self.cutlist = cutlist

		self.end = 300
		self.prog_state = 0
		self.weighting = 1000

		self.args += [inputfile, "-demux", "-out", self.job.workspace, "-cut", self.job.workspace + "/" + self.cutfile ]

	def prepare(self):
		self.writeCutfile()

	def processOutputLine(self, line):
		line = line[:-1]
		MSG_NEW_FILE = "---> new File: "
		MSG_PROGRESS = "[PROGRESS] "

		if line.startswith(MSG_NEW_FILE):
			file = line[len(MSG_NEW_FILE):]
			if file[0] == "'":
				file = file[1:-1]
			self.haveNewFile(file)
		elif line.startswith(MSG_PROGRESS):
			progress = line[len(MSG_PROGRESS):]
			self.haveProgress(progress)

	def haveNewFile(self, file):
		print "PRODUCED FILE [%s]" % file
		self.generated_files.append(file)

	def haveProgress(self, progress):
		print "PROGRESS [%s]" % progress
		MSG_CHECK = "check & synchronize audio file"
		MSG_DONE = "done..."
		if progress == "preparing collection(s)...":
			self.prog_state = 0
		elif progress[:len(MSG_CHECK)] == MSG_CHECK:
			self.prog_state += 1
		else:
			try:
				p = int(progress)
				p = p - 1 + self.prog_state * 100
				if p > self.progress:
					self.progress = p
			except ValueError:
				print "val error"
				pass

	def writeCutfile(self):
		f = open(self.cutfile, "w")
		f.write("CollectionPanel.CutMode=4\n")
		for p in self.cutlist:
			s = p / 90000
			m = s / 60
			h = m / 60

			m %= 60
			s %= 60

			f.write("%02d:%02d:%02d\n" % (h, m, s))
		f.close()

	def cleanup(self, failed):
		if failed:
			import os
			for f in self.generated_files:
				os.remove(f)

class MplexTask(Task):
	def __init__(self, job, outputfile, demux_task):
		Task.__init__(self, job, "Mux ES into PS")

		self.weighting = 500
		self.demux_task = demux_task
		self.setTool("/usr/bin/mplex")
		self.args += ["-f8", "-o", outputfile, "-v1"]

	def prepare(self):
		self.args += self.demux_task.generated_files

	def processOutputLine(self, line):
		print "[MplexTask] processOutputLine=", line

class RemoveESFiles(Task):
	def __init__(self, job, demux_task):
		Task.__init__(self, job, "Remove temp. files")
		self.demux_task = demux_task
		self.setTool("/bin/rm")

	def prepare(self):
		self.args += ["-f"]
		self.args += self.demux_task.generated_files
		self.args += [self.demux_task.cutfile]

class DVDAuthorTask(Task):
	def __init__(self, job):
		Task.__init__(self, job, "Authoring DVD")

		self.weighting = 300
		self.setTool("/usr/bin/dvdauthor")
		self.CWD = self.job.workspace
		self.args += ["-x", self.job.workspace+"/dvdauthor.xml"]

	def processOutputLine(self, line):
		print "[DVDAuthorTask] processOutputLine=", line
		if line.startswith("STAT: Processing"):
			self.callback(self, [], stay_resident=True)

class DVDAuthorFinalTask(Task):
	def __init__(self, job):
		Task.__init__(self, job, "dvdauthor finalize")
		self.setTool("/usr/bin/dvdauthor")
		self.args += ["-T", "-o", self.job.workspace + "/dvd"]

class WaitForResidentTasks(Task):
	def __init__(self, job):
		Task.__init__(self, job, "waiting for dvdauthor to finalize")
		
	def run(self, callback, task_progress_changed):
		print "waiting for %d resident task(s) %s to finish..." % (len(self.job.resident_tasks),str(self.job.resident_tasks))
		if self.job.resident_tasks == 0:
			callback(self, [])

class BurnTaskPostcondition(Condition):
	def check(self, task):
		return task.error is None

	def getErrorMessage(self, task):
		return {
			task.ERROR_MEDIA: ("Medium is not a writeable DVD!"),
			task.ERROR_SIZE: ("Content does not fit on DVD!"),
			task.ERROR_WRITE_FAILED: ("Write failed!"),
			task.ERROR_DVDROM: ("No (supported) DVDROM found!"),
			task.ERROR_UNKNOWN: ("An unknown error occured!")
		}[task.error]

class BurnTask(Task):
	ERROR_MEDIA, ERROR_SIZE, ERROR_WRITE_FAILED, ERROR_DVDROM, ERROR_UNKNOWN = range(5)
	def __init__(self, job):
		Task.__init__(self, job, "burn")

		self.weighting = 500
		self.end = 120 # 100 for writing, 10 for buffer flush, 10 for closing disc
		self.postconditions.append(BurnTaskPostcondition())
		self.setTool("/bin/growisofs")
		self.args += ["-dvd-video", "-dvd-compat", "-Z", "/dev/cdroms/cdrom0", "-V", "Dreambox_DVD", "-use-the-force-luke=dummy", self.job.workspace + "/dvd"]

	def prepare(self):
		self.error = None

	def processOutputLine(self, line):
		line = line[:-1]
		print "[GROWISOFS] %s" % line
		if line[8:14] == "done, ":
			self.progress = float(line[:6])
			print "progress:", self.progress
		elif line.find("flushing cache") != -1:
			self.progress = 100
		elif line.find("closing disc") != -1:
			self.progress = 110
		elif line.startswith(":-["):
			if line.find("ASC=30h") != -1:
				self.error = self.ERROR_MEDIA
			else:
				self.error = self.ERROR_UNKNOWN
				print "BurnTask: unknown error %s" % line
		elif line.startswith(":-("):
			if line.find("No space left on device") != -1:
				self.error = self.ERROR_SIZE
			elif line.find("write failed") != -1:
				self.error = self.ERROR_WRITE_FAILED
			elif line.find("unable to open64(\"/dev/cdroms/cdrom0\",O_RDONLY): No such file or directory") != -1: # fixme
				self.error = self.ERROR_DVDROM
			elif line.find("media is not recognized as recordable DVD") != -1:
				self.error = self.ERROR_MEDIA
			else:
				self.error = self.ERROR_UNKNOWN
				print "BurnTask: unknown error %s" % line

class RemoveDVDFolder(Task):
	def __init__(self, job):
		Task.__init__(self, job, "Remove temp. files")
		self.setTool("/bin/rm")
		self.args += ["-rf", self.job.workspace]

class DVDJob(Job):
	def __init__(self, cue):
		Job.__init__(self, "DVD Burn")
		self.cue = cue
		from time import strftime
		from Tools.Directories import SCOPE_HDD, resolveFilename, createDir
		new_workspace = resolveFilename(SCOPE_HDD) + "tmp/" + strftime("%Y%m%d%H%M%S")
		createDir(new_workspace)
		self.workspace = new_workspace
		self.fromDescription(self.createDescription())

	def fromDescription(self, description):
		nr_titles = int(description["nr_titles"])
		authorxml = """
<dvdauthor dest="%s">
   <vmgm>
      <menus>
         <pgc>
            <post> jump title 1; </post>
         </pgc>
      </menus>
   </vmgm>
   <titleset>
      <titles>""" % (self.workspace+"/dvd")
		for i in range(nr_titles):
			chapterlist_entries = description["chapterlist%d_entries" % i]
			chapterlist = [ ]
			print str(chapterlist_entries)
			for j in range(chapterlist_entries):
				chapterlist.append(int(description["chapterlist%d_%d" % (i, j)]))
			print str(chapterlist)
			chapters = ','.join(["%d:%02d:%02d.%03d," % (p / (90000 * 3600), p % (90000 * 3600) / (90000 * 60), p % (90000 * 60) / 90000, (p % 90000) / 90) for p in chapterlist])

			title_no = i+1
			MakeFifoNode(self, title_no)
			vob_tag = """file="%s/dvd_title_%d.mpg" chapters="%s" />""" % (self.workspace, title_no, chapters)
						
			if title_no < nr_titles:
				post_tag = "> jump title %d;</post>" % ( title_no+1 )
			else:
				post_tag = " />"
			authorxml += """
         <pgc>
            <vob %s
            <post%s
         </pgc>""" % (vob_tag, post_tag)
	 	authorxml += """
      </titles>
   </titleset>
</dvdauthor>
"""
		f = open(self.workspace+"/dvdauthor.xml", "w")
		f.write(authorxml)
		f.close()

		DVDAuthorTask(self)

		for i in range(nr_titles):
			inputfile = description["inputfile%d" % i]
			cutlist_entries = description["cutlist%d_entries" % i]
			cutlist = [ ]
			for j in range(cutlist_entries):
				cutlist.append(int(description["cutlist%d_%d" % (i, j)]))

			link_name =  self.workspace + "/source_title_%d.ts" % (i+1)
			LinkTS(self, inputfile, link_name)
			demux = DemuxTask(self, inputfile = link_name, cutlist = cutlist)
			title_filename =  self.workspace + "/dvd_title_%d.mpg" % (i+1)
			MplexTask(self, title_filename, demux)
			RemoveESFiles(self, demux)
			
			#RemovePSFile(self, title_filename)
		#DVDAuthorFinalTask(self)
		WaitForResidentTasks(self)
		BurnTask(self)
		#RemoveDVDFolder(self)

	def createDescription(self):
		# self.cue is a list of titles, with 
		#   each title being a tuple of 
		#     inputfile,
		#     a list of cutpoints (in,out)
		#     a list of chaptermarks
		# we turn this into a flat dict with
		# nr_titles = the number of titles,
		# cutlist%d_entries = the number of cutlist entries for title i,
		# cutlist%d_%d = cutlist entry j for title i,
		# chapterlist%d_entries = the number of chapters for title i,
		# chapterlist%d_%d = chapter j for title i
		res = { "nr_titles": len(self.cue) }
		for i in range(len(self.cue)):
			c = self.cue[i]
			res["inputfile%d" % i] = c[0]
			res["cutlist%d_entries" % i] = len(c[1])
			for j in range(len(c[1])):
				res["cutlist%d_%d" % (i,j)] = c[1][j]

			res["chapterlist%d_entries" % i] = len(c[2])
			for j in range(len(c[2])):
				res["chapterlist%d_%d" % (i,j)] = c[2][j]
		return res

def Burn(session, cue):
	print "burning cuesheet!"
	j = DVDJob(cue)
	job_manager.AddJob(j)
	return j