]> code.delx.au - bluplayer/blob - bluplayer.py
README
[bluplayer] / bluplayer.py
1 #!/usr/bin/python2
2
3 import csv
4 import errno
5 import logging
6 import os
7 import subprocess
8 import sys
9 import urllib
10
11 from lxml import etree
12 from PyQt4.QtCore import *
13 from PyQt4.QtGui import *
14
15
16 XHTML = "http://www.w3.org/1999/xhtml"
17 NS = {
18 "xhtml": XHTML,
19 }
20 DEFAULT_PATH = "/usr/local/bin:/usr/bin:/bin"
21
22
23 def set_env_config(name, value):
24 value = os.environ.get(name, value)
25 globals()[name] = value
26
27 def find_path(binary):
28 value = ""
29 paths = os.environ.get("PATH", DEFAULT_PATH).split(":")
30 for path in paths:
31 path = os.path.join(path, binary)
32 if os.path.isfile(path):
33 value = path
34 break
35 return value
36
37 set_env_config("MAKEMKVCON_PATH", find_path("makemkvcon"))
38 set_env_config("PLAYER_NAME", "vlc")
39 set_env_config("PLAYER_PATH", find_path(PLAYER_NAME))
40 set_env_config("PLAYER_OPTS", None)
41
42
43 def grab_xml(url):
44 f = urllib.urlopen(url)
45 doc = etree.parse(f)
46 f.close()
47 return doc
48
49 def parse_doc(doc):
50 d = {}
51 tds = doc.xpath("//xhtml:td", namespaces=NS)
52 i = 0
53 while i < len(tds)-1:
54 key = tds[i].text
55 value = tds[i+1]
56 for v in value:
57 if v.tag == "{%s}a" % XHTML:
58 value = v.get("href")
59 break
60 else:
61 value = value.text
62
63 d[key] = value
64 i += 2
65 return d
66
67 def get_num_cpus():
68 logging.info("Determing number of CPUs")
69 try:
70 return subprocess.check_output("nproc").strip()
71 except Exception, e:
72 logging.warn("Unable to run nproc: %s", fmt_exc(e))
73 return 1
74
75 def grab_dict(url):
76 doc = grab_xml(url)
77 d = parse_doc(doc)
78 return d
79
80 def fmt_exc(e):
81 return "%s: %s" % (e.__class__.__name__, str(e))
82
83
84 class Title(object):
85 def __init__(self, title_page):
86 self.id = title_page["id"]
87 self.duration = title_page["duration"]
88 self.video_url = title_page["file0"]
89
90 def __str__(self):
91 return "Title%s: %s %s" % (self.id, self.duration, self.video_url)
92
93
94 class MakeMkvCon(object):
95 def __init__(self, params):
96 cmd = [MAKEMKVCON_PATH, "--robot"]
97 cmd.extend(params)
98 logging.info("Running makemkvcon: %s", params)
99 self.p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
100 self.fd = self.p.stdout.fileno()
101 self.buf = ""
102 self.finished = False
103 self.status = None
104
105 def decode_line(self, line):
106 logging.debug("makemkvcon output: %s", line)
107 data = csv.reader([line]).next()
108 key, x0 = data[0].split(":", 1)
109 data[0] = x0
110 return key, data
111
112 def __iter__(self):
113 return self
114
115 def next(self):
116 if self.finished:
117 raise StopIteration()
118 while True:
119 pos = self.buf.find("\n")
120 if pos >= 0:
121 result = self.buf[:pos]
122 self.buf = self.buf[pos+1:]
123 return self.decode_line(result)
124
125 try:
126 data = os.read(self.p.stdout.fileno(), 4096)
127 except OSError, e:
128 if e.errno == errno.EINTR:
129 continue
130 if not data:
131 self.status = self.p.wait()
132 logging.info("makemkvcon exited with status %s", self.status)
133 self.finished = True
134 raise StopIteration()
135
136 self.buf += data
137
138
139 class Player(QObject):
140 play_finished = pyqtSignal()
141 fatal_error = pyqtSignal(str, str)
142
143 def run(self):
144 logging.info("player thread started")
145
146 if not os.path.isfile(PLAYER_PATH):
147 self.fatal_error.emit(
148 PLAYER_NAME + " was not found.",
149 "Please install it. If you already have done so you " +
150 "may set the PLAYER_PATH environment variable to the " +
151 "absolute path to the player executable."
152 )
153 return
154
155 if PLAYER_OPTS:
156 self.opts = PLAYER_OPTS.split()
157 else:
158 self.opts = [
159 "--fullscreen",
160 ]
161
162 def play(self, video_url):
163 video_url = str(video_url)
164 logging.info("Running player: %s", video_url)
165 try:
166 subprocess.check_call([PLAYER_PATH] + self.opts + [video_url])
167 except Exception, e:
168 self.fatal_error.emit("Failed to play the video.", fmt_exc(e))
169 finally:
170 self.play_finished.emit()
171
172
173 class MakeMkv(QObject):
174 title_loaded = pyqtSignal(Title)
175 title_load_complete = pyqtSignal()
176 status = pyqtSignal(str)
177 fatal_error = pyqtSignal(str, str)
178
179 def find_disc(self):
180 makemkvcon = MakeMkvCon(["info", "disc:9999"])
181 disc_number = None
182 for key, line in makemkvcon:
183 if key == "MSG" and line[0] != "5010":
184 self.status.emit(line[3])
185
186 if disc_number is None and key == "DRV" and line[5]:
187 disc_number = line[0]
188 disc_name = line[5]
189 self.status.emit("Found disc %s" % disc_name)
190
191 if makemkvcon.status == 0:
192 return disc_number
193
194 def run_stream(self, disc_number):
195 makemkvcon = MakeMkvCon(["stream", "disc:%s" % disc_number])
196 for key, line in makemkvcon:
197 if key == "MSG" and line[0] == "4500":
198 # Sometimes the port in field 6 is wrong
199 port = line[5].split(":")[1]
200 url = "http://localhost:%s/" % port
201 self.load_titles(url)
202 elif key == "MSG":
203 self.status.emit(line[3])
204
205 if makemkvcon.status != 0:
206 self.fatal_error.emit(
207 "MakeMKV quit unexpectedly.",
208 "makemkvcon exited with code %s" % makemkvcon.status
209 )
210
211 def load_titles(self, url):
212 home_page = grab_dict(url)
213 title_list_page = grab_dict(home_page["titles"])
214 title_count = int(title_list_page["titlecount"])
215 for i in xrange(title_count):
216 title_page = grab_dict(title_list_page["title%d" % i])
217 title = Title(title_page)
218 self.title_loaded.emit(title)
219 self.title_load_complete.emit()
220
221 def run(self):
222 logging.info("makemkv thread started")
223
224 if not os.path.isfile(MAKEMKVCON_PATH):
225 self.fatal_error.emit(
226 "MakeMKV was not found.",
227 "Please install MakeMKV. If you already have done so you " +
228 "may set the MAKEMKVCON_PATH environment variable to the " +
229 "absolute path to the makemkvcon executable."
230 )
231 return
232
233 try:
234 disc_number = self.find_disc()
235 except Exception, e:
236 self.fatal_error.emit("Error searching for disc.", fmt_exc(e))
237 raise
238
239 if not disc_number:
240 self.fatal_error.emit(
241 "No disc found.",
242 "Please insert a BluRay disc and try again."
243 )
244 return
245
246 try:
247 self.run_stream(disc_number)
248 except Exception, e:
249 self.fatal_error.emit("Failed to start MakeMKV.", fmt_exc(e))
250 raise
251
252 logging.info("makemkv thread finished")
253
254
255 class PlayerWindow(QWidget):
256 fatal_error = pyqtSignal(str, str)
257 video_selected = pyqtSignal(str)
258
259 def __init__(self):
260 QWidget.__init__(self)
261
262 self.title_map = {}
263 self.is_playing = False
264
265 self.list_widget = QListWidget(self)
266 self.list_widget.itemActivated.connect(self.handle_activated)
267 self.list_widget.setEnabled(False)
268
269 self.log = QTextEdit(self)
270 self.log.setReadOnly(True)
271
272 self.splitter = QSplitter(Qt.Vertical, self)
273 self.splitter.addWidget(self.list_widget)
274 self.splitter.addWidget(self.log)
275 self.splitter.setSizes([900, 200])
276
277 self.layout = QVBoxLayout(self)
278 self.layout.addWidget(self.splitter)
279 self.setWindowTitle("BluPlayer")
280 self.resize(1200, 700)
281
282 def add_title(self, title):
283 name = "Title %s (%s)" % (int(title.id)+1, title.duration)
284 self.list_widget.addItem(name)
285 self.title_map[name] = title
286
287 def select_longest_title(self):
288 longest_title = None
289 longest_item = None
290 for i in xrange(self.list_widget.count()):
291 item = self.list_widget.item(i)
292 name = str(item.text())
293 title = self.title_map[name]
294 if longest_title is None or title.duration > longest_title.duration:
295 longest_title = title
296 longest_item = item
297 self.list_widget.setCurrentItem(longest_item)
298 self.list_widget.setEnabled(True)
299 self.list_widget.setFocus()
300
301 def add_log_entry(self, text):
302 self.log.append(text)
303
304 def handle_activated(self, item):
305 if self.is_playing:
306 return
307 name = str(item.text())
308 title = self.title_map[name]
309 self.is_playing = True
310 self.list_widget.setEnabled(False)
311 self.video_selected.emit(title.video_url)
312
313 def set_play_finished(self):
314 self.is_playing = False
315 self.list_widget.setEnabled(True)
316 self.list_widget.setFocus()
317
318 def keyPressEvent(self, e):
319 if e.key() in (Qt.Key_Escape, Qt.Key_Backspace):
320 self.close()
321 return
322 QWidget.keyPressEvent(self, e)
323
324 class LoadingDialog(QProgressDialog):
325 def __init__(self, parent):
326 QProgressDialog.__init__(self, parent)
327 self.setWindowModality(Qt.WindowModal);
328 self.setWindowTitle("Loading disc")
329 self.setLabelText("Loading BluRay disc. Please wait...")
330 self.setCancelButtonText("Exit")
331 self.setMinimum(0)
332 self.setMaximum(0)
333
334 class ErrorDialog(QMessageBox):
335 fatal_error = pyqtSignal(str, str)
336
337 def __init__(self, parent):
338 QMessageBox.__init__(self, parent)
339 self.setStandardButtons(QMessageBox.Ok)
340 self.setDefaultButton(QMessageBox.Ok)
341 self.fatal_error.connect(self.configure_popup)
342 self.setWindowTitle("Fatal error")
343 self.has_run = False
344
345 def configure_popup(self, text, detail):
346 if self.has_run:
347 return
348 self.has_run = True
349 self.setText(text)
350 self.setInformativeText(detail)
351 QTimer.singleShot(0, self.show_and_exit)
352
353 def show_and_exit(self):
354 logging.info("showing and exiting")
355 self.exec_()
356 qApp.quit()
357
358 def killall_makemkvcon():
359 logging.info("Stopping any makemkvcon processes")
360 subprocess.Popen(["killall", "--quiet", "makemkvcon"]).wait()
361
362 def main():
363 logging.basicConfig(format="%(levelname)s: %(message)s")
364 logging.getLogger().setLevel(logging.DEBUG)
365 logging.info("Configuring application")
366
367 app = QApplication(sys.argv)
368 app.setQuitOnLastWindowClosed(True)
369
370 default_font = app.font()
371 default_font.setPointSize(16)
372 app.setFont(default_font)
373
374 player_window = PlayerWindow()
375 player_window.show()
376
377 loading_dialog = LoadingDialog(player_window)
378 loading_dialog.show()
379
380 error_dialog = ErrorDialog(player_window)
381
382 makemkv = MakeMkv()
383 makemkv_thread = QThread()
384 makemkv.moveToThread(makemkv_thread)
385 makemkv_thread.started.connect(makemkv.run)
386
387 player = Player()
388 player_thread = QThread()
389 player.moveToThread(player_thread)
390 player_thread.started.connect(player.run)
391
392 makemkv.title_loaded.connect(player_window.add_title)
393 makemkv.title_load_complete.connect(player_window.select_longest_title)
394 makemkv.status.connect(player_window.add_log_entry)
395 makemkv.fatal_error.connect(error_dialog.fatal_error)
396 makemkv.title_load_complete.connect(loading_dialog.reset)
397
398 player_window.video_selected.connect(player.play)
399 player.play_finished.connect(player_window.set_play_finished)
400 player.fatal_error.connect(error_dialog.fatal_error)
401
402 player_window.fatal_error.connect(error_dialog.fatal_error)
403 error_dialog.fatal_error.connect(loading_dialog.reset)
404 loading_dialog.canceled.connect(qApp.quit)
405
406 logging.info("Starting application")
407 makemkv_thread.start()
408 player_thread.start()
409 result = app.exec_()
410
411 logging.info("Shutting down")
412 makemkv_thread.quit()
413 player_thread.quit()
414 killall_makemkvcon()
415 logging.info("Waiting for makemkv thread")
416 makemkv_thread.wait(2000)
417 logging.info("Waiting for player thread")
418 player_thread.wait(2000)
419 logging.info("Exiting...")
420 sys.exit(result)
421
422 if __name__ == "__main__":
423 main()
424