-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathomxplayer-sync
394 lines (326 loc) · 12.4 KB
/
omxplayer-sync
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
#!/usr/bin/env python3
#
# omxplayer-sync
#
# Copyright 2016, Simon Josi
# Simon Josi me(at)yokto(dot)net
#
# This program is free software; you can redistribute
# it and/or modify it under the terms of the GNU
# General Public License version 3 as published by
# the Free Software Foundation.
#
import re
import os
import sys
import math
import socket
import signal
import dbus
import getpass
import itertools
import collections
from time import sleep, time
from optparse import OptionParser, BadOptionError, AmbiguousOptionError
from subprocess import Popen
try:
from subprocess import DEVNULL
except ImportError:
import os
DEVNULL = open(os.devnull, 'wb')
SYNC_TOLERANCE = .05
SYNC_GRACE_TIME = 5
SYNC_JUMP_AHEAD = 3
OMXPLAYER = 'omxplayer'
OMXPLAYER_DBUS_ADDR='/tmp/omxplayerdbus.%s' % getpass.getuser()
PORT = 1666
#
# Unknown option pass-through OptionParser
#
class PassThroughOptionParser(OptionParser):
"""
An unknown option pass-through implementation of OptionParser.
When unknown arguments are encountered, bundle with largs and try again,
until rargs is depleted.
sys.exit(status) will still be called if a known argument is passed
incorrectly (e.g. missing arguments or bad argument types, etc.)
"""
def _process_args(self, largs, rargs, values):
while rargs:
try:
OptionParser._process_args(self,largs,rargs,values)
except (BadOptionError,AmbiguousOptionError) as e:
largs.append(e.opt_str)
#
# D-Bus player interface
#
class PlayerInterface():
def _get_dbus_interface(self):
try:
bus = dbus.bus.BusConnection(
open(OMXPLAYER_DBUS_ADDR).readlines()[0].rstrip())
proxy = bus.get_object(
'org.mpris.MediaPlayer2.omxplayer',
'/org/mpris/MediaPlayer2',
introspect=False)
self.methods = dbus.Interface(
proxy, 'org.mpris.MediaPlayer2.Player')
self.properties = dbus.Interface(
proxy, 'org.freedesktop.DBus.Properties')
return True
except Exception as e:
print("WARNING: dbus connection could not be established")
print(e)
sleep(5)
return False
def initialize(self):
sleep(10) # wait for omxplayer to appear on dbus
return self._get_dbus_interface()
def playPause(self):
try:
self.methods.Action(16)
return True
except:
print(e)
return False
def setPosition(self, seconds):
try:
self.methods.SetPosition(
dbus.ObjectPath('/not/used'),
dbus.Int64(seconds * 1000000))
except Exception as e:
print(e)
return False
return True
def Position(self):
try:
return self.properties.Get(
'org.mpris.MediaPlayer2.Player',
'Position')
except Exception as e:
return False
#
# OMXPlayer-Sync main class
#
class OMXPlayerSync():
def __init__(self):
self.sock = self.init_socket()
self.controller = PlayerInterface()
self.options = None
self.omxplayer_options = []
self.playlist = []
self.playlist_index = 0
self.filename = ''
self.position_local = 0.0
self.position_local_oldage = 0.0
self.position_local_oldage_count = 0
self.position_master = 0.0
self.filename_master = ''
self.process = None
signal.signal(signal.SIGINT, self.kill_omxplayer_and_exit)
def run(self):
p = PassThroughOptionParser()
p.add_option('--master', '-m', action='store_true')
p.add_option('--slave', '-l', action='store_true')
p.add_option('--destination', '-x', default='255.255.255.255')
p.add_option('--loop', '-u', action='store_true')
p.add_option('--verbose', '-v', action='store_true')
p.add_option('--adev', '-o', default='both')
p.add_option('--aspect', '-a', default=None, help="Aspect Mode - fill, letterbox, stretch")
self.options, arguments = p.parse_args()
for argument in arguments:
if argument.startswith('-'):
self.omxplayer_options.append(argument)
else:
self.playlist.append(argument)
if not len(self.playlist):
sys.exit(0)
if self.options.loop and len(self.playlist) == 1:
self.omxplayer_options.append("--loop")
if self.options.aspect in ('fill', 'stretch', 'letterbox'):
self.omxplayer_options.append("--aspect-mode %s" % self.options.aspect)
if not filter(lambda x: os.path.isfile(x), self.playlist):
print("ERROR: none of the supplied filenames are found")
sys.exit(1)
self.omxplayer_options.append("-o %s" % self.options.adev)
self.omxplayer_options.append('--no-keys')
if not self.options.verbose:
self.omxplayer_options.append('--no-osd')
if self.options.master:
self.socket_enable_broadcast()
self.socket_connect(self.options.destination)
if self.options.slave:
self.read_position_master()
self.set_playlist_index()
while True:
self.play_file(self.playlist[self.playlist_index])
if not self.options.loop and self.playlist_index == 0:
break
def play_file(self, filename):
if not os.path.isfile(filename):
if self.options.verbose:
print("WARNING: %s file not found" % filename)
self.increment_playlist_index()
return
self.filename = filename
self.position_local = 0.0
self.position_local_oldage = 0.0
self.position_local_oldage_count = 0
if self.options.verbose:
last_frame_local, current_frame_local = 0, 0
if self.options.slave:
last_frame_master, current_frame_master = 0, 0
if self.options.master:
self.send_position_local()
self.process = Popen([OMXPLAYER] \
+ list(itertools.chain(*map(lambda x: x.split(' '), self.omxplayer_options))) \
+ [self.filename],
preexec_fn=os.setsid, stdout=DEVNULL, stderr=DEVNULL, stdin=DEVNULL)
self.controller.initialize()
if not self.read_position_local():
print("WARNING: omxplayer did not start. Try to test with `omxplayer -s OPTIONS`")
self.kill_omxplayer_and_exit()
if self.options.slave:
wait_for_sync = False
wait_after_sync = False
deviations = collections.deque(maxlen=10)
while True:
if self.options.slave:
self.read_position_master()
if wait_for_sync:
sync_timer = time()
if not self.read_position_local():
self.increment_playlist_index()
break
if self.hangup_detected():
break
if self.options.verbose:
current_frame_local = math.modf(self.position_local)[0]*100/4
if self.options.slave:
current_frame_master = math.modf(self.position_master)[0]*100/4
if self.options.master:
self.send_position_local()
if self.options.verbose:
sys.stdout.write("local: %.2f %.0f\n" %
(self.position_local, current_frame_local))
if self.options.slave:
if self.filename != self.filename_master:
self.set_playlist_index()
break
deviation = self.position_master - self.position_local
deviations.append(deviation)
median_deviation = self.median(list(deviations))
if self.options.verbose:
sys.stdout.write("local: %.2f %.0f master: %.2f %.0f deviation: %.2f median_deviation: %.2f filename: %s\n" % (
self.position_local,
current_frame_local,
self.position_master,
current_frame_master,
deviation,
median_deviation,
self.filename))
if wait_for_sync:
while True:
if abs(deviation) - (time() - sync_timer) < 0:
if self.options.verbose:
print("we are sync, play...")
if not self.controller.playPause():
break
wait_for_sync = False
wait_after_sync = time()
break
continue
if wait_after_sync:
if (time() - wait_after_sync) > SYNC_GRACE_TIME:
wait_after_sync = False
continue
if abs(median_deviation) > SYNC_TOLERANCE \
and self.position_local > SYNC_GRACE_TIME \
and self.position_master > SYNC_GRACE_TIME:
if self.options.verbose:
print("jump to %.2f" % (self.position_master + SYNC_JUMP_AHEAD))
print("enter pause...")
if not self.controller.playPause():
break
if not self.controller.setPosition(self.position_master + SYNC_JUMP_AHEAD):
break
wait_for_sync = True
wait_after_sync = time()
if self.options.master:
sleep(1)
self.kill_omxplayer()
def read_position_local(self):
position_local = self.controller.Position()
if position_local:
self.position_local = float(position_local)/1000000
else:
return False
return True
def set_playlist_index(self):
if self.filename_master == '':
print("WARNING: unable to get current filename from master")
sleep(5)
return
try:
self.playlist_index = self.playlist.index(self.filename_master)
except:
print("WARNING: current master file '%s' is unavailable" % self.filename_master)
def increment_playlist_index(self):
if len(self.playlist) == (self.playlist_index + 1):
self.playlist_index = 0
else:
self.playlist_index += 1
def hangup_detected(self):
self.position_local_oldage_count += 1
if self.position_local_oldage_count == 200:
if self.position_local_oldage == self.position_local:
return True
self.position_local_oldage = self.position_local
self.position_local_oldage_count = 0
return False
def init_socket(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
sock.bind(('0.0.0.0', PORT))
return sock
def kill_omxplayer(self):
try:
os.killpg(os.getpgid(self.process.pid), signal.SIGTERM)
except:
pass
try:
self.process.wait()
except:
pass
def kill_omxplayer_and_exit(self, *args):
self.kill_omxplayer()
sys.exit(0)
#
# master specific
#
def socket_enable_broadcast(self):
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
def socket_connect(self, destination):
try:
self.sock.connect((destination, PORT))
except:
print("connect: Network is unreachable")
pass
def send_position_local(self):
try:
self.sock.send(("%s%%%s" % (str(self.position_local), self.filename)).encode('utf-8'))
except socket.error:
pass
#
# slave specific
#
def read_position_master(self):
data = self.sock.recvfrom(1024)[0].decode('utf-8').split('%', 1)
self.position_master = float(data[0])
self.filename_master = data[1]
def median(self, lst):
quotient, remainder = divmod(len(lst), 2)
if remainder:
return sorted(lst)[quotient]
return float(sum(sorted(lst)[quotient - 1:quotient + 1]) / 2.0)
if __name__ == '__main__':
OMXPlayerSync().run()