]>
code.delx.au - bluplayer/blob - bluplayer.py
11 from lxml
import etree
12 from PyQt4
.QtCore
import *
13 from PyQt4
.QtGui
import *
16 XHTML
= "http://www.w3.org/1999/xhtml"
20 DEFAULT_PATH
= "/usr/local/bin:/usr/bin:/bin"
23 def set_env_config(name
, value
):
24 value
= os
.environ
.get(name
, value
)
25 globals()[name
] = value
27 def find_path(binary
):
29 paths
= os
.environ
.get("PATH", DEFAULT_PATH
).split(":")
31 path
= os
.path
.join(path
, binary
)
32 if os
.path
.isfile(path
):
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)
44 f
= urllib
.urlopen(url
)
51 tds
= doc
.xpath("//xhtml:td", namespaces
=NS
)
57 if v
.tag
== "{%s}a" % XHTML
:
68 logging
.info("Determing number of CPUs")
70 return subprocess
.check_output("nproc").strip()
72 logging
.warn("Unable to run nproc: %s", fmt_exc(e
))
81 return "%s: %s" % (e
.__class
__.__name
__, str(e
))
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"]
91 return "Title%s: %s %s" % (self
.id, self
.duration
, self
.video_url
)
94 class MakeMkvCon(object):
95 def __init__(self
, params
):
96 cmd
= [MAKEMKVCON_PATH
, "--robot"]
98 logging
.info("Running makemkvcon: %s", params
)
99 self
.p
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
)
100 self
.fd
= self
.p
.stdout
.fileno()
102 self
.finished
= False
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)
117 raise StopIteration()
119 pos
= self
.buf
.find("\n")
121 result
= self
.buf
[:pos
]
122 self
.buf
= self
.buf
[pos
+1:]
123 return self
.decode_line(result
)
126 data
= os
.read(self
.p
.stdout
.fileno(), 4096)
128 if e
.errno
== errno
.EINTR
:
131 self
.status
= self
.p
.wait()
132 logging
.info("makemkvcon exited with status %s", self
.status
)
134 raise StopIteration()
139 class Player(QObject
):
140 play_finished
= pyqtSignal()
141 fatal_error
= pyqtSignal(str, str)
144 logging
.info("player thread started")
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."
156 self
.opts
= PLAYER_OPTS
.split()
162 def play(self
, video_url
):
163 video_url
= str(video_url
)
164 logging
.info("Running player: %s", video_url
)
166 subprocess
.check_call([PLAYER_PATH
] + self
.opts
+ [video_url
])
168 self
.fatal_error
.emit("Failed to play the video.", fmt_exc(e
))
170 self
.play_finished
.emit()
173 class MakeMkv(QObject
):
174 title_loaded
= pyqtSignal(Title
)
175 title_load_complete
= pyqtSignal()
176 status
= pyqtSignal(str)
177 fatal_error
= pyqtSignal(str, str)
180 makemkvcon
= MakeMkvCon(["info", "disc:9999"])
182 for key
, line
in makemkvcon
:
183 if key
== "MSG" and line
[0] != "5010":
184 self
.status
.emit(line
[3])
186 if disc_number
is None and key
== "DRV" and line
[5]:
187 disc_number
= line
[0]
189 self
.status
.emit("Found disc %s" % disc_name
)
191 if makemkvcon
.status
== 0:
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
)
203 self
.status
.emit(line
[3])
205 if makemkvcon
.status
!= 0:
206 self
.fatal_error
.emit(
207 "MakeMKV quit unexpectedly.",
208 "makemkvcon exited with code %s" % makemkvcon
.status
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()
222 logging
.info("makemkv thread started")
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."
234 disc_number
= self
.find_disc()
236 self
.fatal_error
.emit("Error searching for disc.", fmt_exc(e
))
240 self
.fatal_error
.emit(
242 "Please insert a BluRay disc and try again."
247 self
.run_stream(disc_number
)
249 self
.fatal_error
.emit("Failed to start MakeMKV.", fmt_exc(e
))
252 logging
.info("makemkv thread finished")
255 class PlayerWindow(QWidget
):
256 fatal_error
= pyqtSignal(str, str)
257 video_selected
= pyqtSignal(str)
260 QWidget
.__init
__(self
)
263 self
.is_playing
= False
265 self
.list_widget
= QListWidget(self
)
266 self
.list_widget
.itemActivated
.connect(self
.handle_activated
)
267 self
.list_widget
.setEnabled(False)
269 self
.log
= QTextEdit(self
)
270 self
.log
.setReadOnly(True)
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])
277 self
.layout
= QVBoxLayout(self
)
278 self
.layout
.addWidget(self
.splitter
)
279 self
.setWindowTitle("BluPlayer")
280 self
.resize(1200, 700)
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
287 def select_longest_title(self
):
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
297 self
.list_widget
.setCurrentItem(longest_item
)
298 self
.list_widget
.setEnabled(True)
299 self
.list_widget
.setFocus()
301 def add_log_entry(self
, text
):
302 self
.log
.append(text
)
304 def handle_activated(self
, item
):
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
)
313 def set_play_finished(self
):
314 self
.is_playing
= False
315 self
.list_widget
.setEnabled(True)
316 self
.list_widget
.setFocus()
318 def keyPressEvent(self
, e
):
319 if e
.key() in (Qt
.Key_Escape
, Qt
.Key_Backspace
):
322 QWidget
.keyPressEvent(self
, e
)
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")
334 class ErrorDialog(QMessageBox
):
335 fatal_error
= pyqtSignal(str, str)
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")
345 def configure_popup(self
, text
, detail
):
350 self
.setInformativeText(detail
)
351 QTimer
.singleShot(0, self
.show_and_exit
)
353 def show_and_exit(self
):
354 logging
.info("showing and exiting")
358 def killall_makemkvcon():
359 logging
.info("Stopping any makemkvcon processes")
360 subprocess
.Popen(["killall", "--quiet", "makemkvcon"]).wait()
363 logging
.basicConfig(format
="%(levelname)s: %(message)s")
364 logging
.getLogger().setLevel(logging
.DEBUG
)
365 logging
.info("Configuring application")
367 app
= QApplication(sys
.argv
)
368 app
.setQuitOnLastWindowClosed(True)
370 default_font
= app
.font()
371 default_font
.setPointSize(16)
372 app
.setFont(default_font
)
374 player_window
= PlayerWindow()
377 loading_dialog
= LoadingDialog(player_window
)
378 loading_dialog
.show()
380 error_dialog
= ErrorDialog(player_window
)
383 makemkv_thread
= QThread()
384 makemkv
.moveToThread(makemkv_thread
)
385 makemkv_thread
.started
.connect(makemkv
.run
)
388 player_thread
= QThread()
389 player
.moveToThread(player_thread
)
390 player_thread
.started
.connect(player
.run
)
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
)
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
)
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
)
406 logging
.info("Starting application")
407 makemkv_thread
.start()
408 player_thread
.start()
411 logging
.info("Shutting down")
412 makemkv_thread
.quit()
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...")
422 if __name__
== "__main__":