-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmedia_player.py
More file actions
537 lines (432 loc) · 16.2 KB
/
media_player.py
File metadata and controls
537 lines (432 loc) · 16.2 KB
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
#!/usr/bin/env python
"""
Usage
media_player.py [options] <filename> [<filename> ...]
Plays the audio / video files listed as arguments, optionally
collecting debug info
Options
--debug : saves sequence of internal state as a binary *.dbg
--outfile : filename to store the debug info, defaults to filename.dbg
The raw data captured in the .dbg can be rendered as human readable
using the script report.py
"""
__docformat__ = "restructuredtext"
__version__ = "$Id: $"
import os
import sys
import weakref
from pyglet.gl import (
glEnable,
glBlendFunc,
GL_BLEND,
GL_LINE_LOOP,
GL_ONE_MINUS_SRC_ALPHA,
GL_SRC_ALPHA,
)
import pyglet
from pyglet.window import key
pyglet.options.debug_media = False
# pyglet.options['audio'] = ('openal', 'pulse', 'silent')
from pyglet.media import buffered_logger as bl
### Draw Rectangle Function ###
def draw_rect(x, y, width, height, color=(0, 0, 1, 1)):
pyglet.graphics.draw(
4,
GL_LINE_LOOP,
position=(
"f",
(
x,
y,
0,
x + width,
y,
0,
x + width,
y + height,
0,
x,
y + height,
0,
),
),
colors=("f", color * 4),
)
### GUI CONTROLS ###
class Control(pyglet.event.EventDispatcher):
x = y = 0
width = height = 10
"""
Initialize a Control instance.
Args:
*args: Variable length argument list.
**kwargs: Arbitrary keyword arguments.
"""
def __init__(self, parent):
super(Control, self).__init__()
self.parent = weakref.proxy(parent)
def hit_test(self, x, y):
return self.x < x < self.x + self.width and self.y < y < self.y + self.height
def capture_events(self):
self.parent.push_handlers(self)
def release_events(self):
self.parent.remove_handlers(self)
### Button Control ###
class Button(Control):
charged = False
def draw(self):
if self.charged:
draw_rect(self.x, self.y, self.width, self.height)
else:
draw_rect(self.x, self.y, self.width, self.height, color=(1, 1, 0, 1))
self.draw_label()
def draw_label(self):
pass
def on_mouse_press(self, x, y, button, modifiers):
self.capture_events()
self.charged = True
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
self.charged = self.hit_test(x, y)
def on_mouse_release(self, x, y, button, modifiers):
self.release_events()
if self.hit_test(x, y):
self.dispatch_event("on_press")
self.charged = False
### Register Button Event ###
Button.register_event_type("on_press")
### Text Button Class ###
class TextButton(Button):
"""
Initialize a TextButton instance.
Args:
*args: Variable length argument list.
**kwargs: Arbitrary keyword arguments.
"""
def __init__(self, *args, **kwargs):
super(TextButton, self).__init__(*args, **kwargs)
self._text = pyglet.text.Label("", anchor_x="center", anchor_y="center")
def draw_label(self):
self._text.x = self.x + self.width / 2
self._text.y = self.y + self.height / 2
self._text.draw()
def set_text(self, text):
self._text.text = text
text = property(lambda self: self._text.text, set_text)
### Slider Control Class ###
class Slider(Control):
### Slider Constants Thumb and Groove dimensions ###
THUMB_WIDTH = 10
THUMB_HEIGHT = 20
GROOVE_HEIGHT = 6
RESPONSIVNESS = 0.3
def __init__(self, *args, **kwargs):
super(Slider, self).__init__(*args, **kwargs)
### Slider Attributes ###
self.seek_value = None
self.value = 0.0
self.min = 0.0
self.max = 1.0
def draw(self):
center_y = self.y + self.height / 2
draw_rect(
self.x, center_y - self.GROOVE_HEIGHT / 2, self.width, self.GROOVE_HEIGHT
)
pos = self.x + self.value * self.width / (self.max - self.min)
draw_rect(
pos - self.THUMB_WIDTH / 2,
center_y - self.THUMB_HEIGHT / 2,
self.THUMB_WIDTH,
self.THUMB_HEIGHT,
)
def coordinate_to_value(self, x):
value = float(x - self.x) / self.width * (self.max - self.min) + self.min
return value
def on_mouse_press(self, x, y, button, modifiers):
value = self.coordinate_to_value(x)
self.capture_events()
self.dispatch_event("on_begin_scroll")
self.dispatch_event("on_change", value)
pyglet.clock.schedule_once(self.seek_request, self.RESPONSIVNESS)
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
# On some platforms, on_mouse_drag is triggered with a high frequency.
# Seeking takes some time (~200ms). Asking for a seek at every
# on_mouse_drag event would starve the event loop.
# Instead we only record the last mouse position and we
# schedule seek_request to dispatch the on_change event in the future.
# This will allow subsequent on_mouse_drag to change the seek_value
# without triggering yet the on_change event.
value = min(max(self.coordinate_to_value(x), self.min), self.max)
if self.seek_value is None:
# We have processed the last recorded mouse position.
# We re-schedule seek_request
pyglet.clock.schedule_once(self.seek_request, self.RESPONSIVNESS)
self.seek_value = value
def on_mouse_release(self, x, y, button, modifiers):
self.release_events()
self.dispatch_event("on_end_scroll")
self.seek_value = None
def seek_request(self, dt):
if self.seek_value is not None:
self.dispatch_event("on_change", self.seek_value)
self.seek_value = None
### Register Slider Events ###
Slider.register_event_type("on_begin_scroll")
Slider.register_event_type("on_end_scroll")
Slider.register_event_type("on_change")
### Player Window Class ###
class PlayerWindow(pyglet.window.Window):
GUI_WIDTH = 400
GUI_HEIGHT = 80
GUI_PADDING = 20
GUI_BUTTON_HEIGHT = 40
def __init__(self, player):
super(PlayerWindow, self).__init__(
caption="Media Player", visible=False, resizable=True
)
# We only keep a weakref to player as we are about to push ourself
# as a handler which would then create a circular reference between
# player and window.
self.player = weakref.proxy(player)
self._player_playing = False
self.player.push_handlers(self)
### Slider Setup ###
self.slider = Slider(self)
self.slider.push_handlers(self)
self.slider.x = self.GUI_PADDING
self.slider.y = self.GUI_PADDING + self.GUI_BUTTON_HEIGHT
### Play Pause Button Setup ###
self.play_pause_button = TextButton(self)
self.play_pause_button.x = self.GUI_PADDING
self.play_pause_button.y = self.GUI_PADDING // 2
self.play_pause_button.height = self.GUI_BUTTON_HEIGHT
self.play_pause_button.width = 65
self.play_pause_button.push_handlers(on_press=self.on_play_pause)
### Window Button Setup ###
self.window_button = TextButton(self)
self.window_button.x = (
self.play_pause_button.x + self.play_pause_button.width + self.GUI_PADDING
)
self.window_button.y = self.GUI_PADDING // 2
self.window_button.height = self.GUI_BUTTON_HEIGHT
self.window_button.width = 90
self.window_button.text = "Windowed"
self.window_button.push_handlers(on_press=lambda: self.set_fullscreen(False))
### Control Buttons Setup ###
self.controls = [
self.slider,
self.play_pause_button,
self.window_button,
]
### Screen Buttons Setup ###
x = self.window_button.x + self.window_button.width + self.GUI_PADDING
i = 0
for screen in self.display.get_screens():
screen_button = TextButton(self)
screen_button.x = x
screen_button.y = self.GUI_PADDING // 2
screen_button.height = self.GUI_BUTTON_HEIGHT
screen_button.width = 80
screen_button.text = f"Screen {i + 1}"
screen_button.push_handlers(
on_press=lambda screen=screen: self.set_fullscreen(True, screen)
)
self.controls.append(screen_button)
i += 1
x += screen_button.width + self.GUI_PADDING
### Set Default Video Size ###
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
def on_player_next_source(self):
self.gui_update_state()
self.gui_update_source()
self.set_default_video_size()
return True
def on_player_eos(self):
self.gui_update_state()
pyglet.clock.schedule_once(self.auto_close, 0.1)
return True
def gui_update_source(self):
if self.player.source:
source = self.player.source
self.slider.min = 0.0
self.slider.max = source.duration
self.gui_update_state()
def gui_update_state(self):
if self.player.playing:
self.play_pause_button.text = "Pause"
else:
self.play_pause_button.text = "Play"
def get_video_size(self):
if not self.player.source or not self.player.source.video_format:
return 0, 0
video_format = self.player.source.video_format
width = video_format.width
height = video_format.height
if video_format.sample_aspect > 1:
width *= video_format.sample_aspect
elif video_format.sample_aspect < 1:
height /= video_format.sample_aspect
return width, height
def set_default_video_size(self):
"""Make the window size just big enough to show the current
video and the GUI."""
width = self.GUI_WIDTH
height = self.GUI_HEIGHT
video_width, video_height = self.get_video_size()
width = max(width, video_width)
height += video_height
self.set_size(int(width), int(height))
def on_resize(self, width, height):
"""Position and size video image."""
super(PlayerWindow, self).on_resize(width, height)
self.slider.width = width - self.GUI_PADDING * 2
height -= self.GUI_HEIGHT
if height <= 0:
return
video_width, video_height = self.get_video_size()
if video_width == 0 or video_height == 0:
return
display_aspect = width / float(height)
video_aspect = video_width / float(video_height)
if video_aspect > display_aspect:
self.video_width = width
self.video_height = width / video_aspect
else:
self.video_height = height
self.video_width = height * video_aspect
self.video_x = (width - self.video_width) / 2
self.video_y = (height - self.video_height) / 2 + self.GUI_HEIGHT
def on_mouse_press(self, x, y, button, modifiers):
for control in self.controls:
if control.hit_test(x, y):
control.on_mouse_press(x, y, button, modifiers)
def on_key_press(self, symbol, modifiers):
if symbol == key.SPACE:
self.on_play_pause()
elif symbol == key.ESCAPE:
self.dispatch_event("on_close")
elif symbol == key.LEFT:
self.player.seek(0)
elif symbol == key.RIGHT:
self.player.next_source()
def on_close(self):
self.player.pause()
self.close()
def auto_close(self, dt):
self.close()
def on_play_pause(self):
if self.player.playing:
self.player.pause()
else:
if self.player.time >= self.player.source.duration:
self.player.seek(0)
self.player.play()
self.gui_update_state()
def on_draw(self):
self.clear()
# Video Image
"""
This may be where it can be determined if the video needs to be played horizontally or vertically.
"""
### Determine the aspect ratio of the video, and rotate the video vertically if the video aspect is in portrait mode. ###
if self.player.source and self.player.source.video_format:
video_format = self.player.source.video_format
video_texture = self.player.texture
if video_format.width < video_format.height:
video_texture.blit(
self.video_x,
self.video_y,
width=self.video_width,
height=self.video_height,
rotation=90,
)
else:
video_texture.blit(
self.video_x,
self.video_y,
width=self.video_width,
height=self.video_height,
)
# Slider and Controls
self.slider.value = self.player.time
for control in self.controls:
control.draw()
def on_begin_scroll(self):
self._player_playing = self.player.playing
self.player.pause()
def on_change(self, value):
self.player.seek(value)
def on_end_scroll(self):
if self._player_playing:
self.player.play()
### Main Function ###
def main(target, dbg_file, debug):
set_logging_parameters(target, dbg_file, debug)
player = pyglet.media.Player()
window = PlayerWindow(player)
player.queue(pyglet.media.load(filename) for filename in sys.argv[1:])
window.gui_update_source()
window.set_visible(True)
window.set_default_video_size()
# this is an async call
player.play()
window.gui_update_state()
pyglet.app.run()
### Set Logging Parameters ###
def set_logging_parameters(target_file, dbg_file, debug):
if not debug:
bl.logger = None
return
if dbg_file is None:
dbg_file = target_file + ".dbg"
else:
dbg_dir = os.path.dirname(dbg_file)
if dbg_dir and not os.path.isdir(dbg_dir):
os.mkdir(dbg_dir)
bl.logger = bl.BufferedLogger(dbg_file)
from pyglet.media.instrumentation import mp_events
# allow to detect crashes by prewriting a crash file, if no crash
# it will be overwrited by the captured data
sample = os.path.basename(target_file)
bl.logger.log("version", mp_events["version"])
bl.logger.log("crash", sample)
bl.logger.save_log_entries_as_pickle()
bl.logger.clear()
# start the real capture data
bl.logger.log("version", mp_events["version"])
bl.logger.log("mp.im", sample)
### Usage Function ###
def usage():
print(__doc__)
sys.exit(1)
### System Arguments to Main Arguments ###
def sysargs_to_mainargs():
"""builds main args from sys.argv"""
if len(sys.argv) < 2:
usage()
debug = False
dbg_file = None
for i in range(2):
if sys.argv[1].startswith("--"):
a = sys.argv.pop(1)
if a.startswith("--debug"):
debug = True
elif a.startswith("--outfile="):
dbg_file = a[len("--outfile=") :]
else:
print("Error unknown option:", a)
usage()
target_file = sys.argv[1]
return target_file, dbg_file, debug
### Main Function Call ###
"""
__name__ is a built-in variable which evaluates to the name of the current module.
However, if a module is being run directly (as in media_player.py), then __name__ instead is set to the string "__main__".
Thus, you can test whether your script is being run directly or being imported by something else by testing if __name__ == '__main__':.
If the script is being imported into another module, the various function and class definitions it contains will be imported and the script will not be executed.
If the script is being run directly, on the other hand, the script will run.
This is a common idiom used in Python modules, allowing one to have a module that can double as a standalone script.
"""
if __name__ == "__main__":
target_file, dbg_file, debug = sysargs_to_mainargs()
main(target_file, dbg_file, debug)