-
Notifications
You must be signed in to change notification settings - Fork 2
/
gstvideo.py
executable file
·560 lines (462 loc) · 16.1 KB
/
gstvideo.py
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
#!/usr/bin/env python
# -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
# sinkelement.py
# (c) 2005 Edward Hervey <edward@fluendo.com>
# Licensed under LGPL
#
# Small test application to show how to write a sink element
# in 20 lines in python
#
# Run this script with GST_DEBUG=python:5 to see the debug
# messages
from ledwall import LedMatrix
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('file', metavar='FILE', type=str, nargs='+',
help='filename to play')
parser.add_argument('--server', dest="server", type=str,
default='127.0.0.1',
help='server ip address')
parser.add_argument('--vis', dest='visualize', #action='store_const',
default="libvisual_bumpscope",
help='use gstreamer visualize plugin')
parser
args = parser.parse_args()
if not args:
print parser.usage()
import time
import pygst
pygst.require('0.10')
import gst
import gobject
import sys
gobject.threads_init ()
#
# Simple Sink element created entirely in python
#
def log(*args):
print "\n".join(args)
def terminal_size():
def ioctl_GWINSZ(fd):
try:
import fcntl, termios, struct, os
cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
'1234'))
except:
return None
return cr
cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
if not cr:
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
cr = ioctl_GWINSZ(fd)
os.close(fd)
except:
pass
if not cr:
try:
cr = (os.environment['LINES'], os.environment['COLUMNS'])
except:
cr = (25, 80)
return int(cr[1]), int(cr[0])
class LedVideoSink(gst.BaseSink):
__gsttemplates__ = (
gst.PadTemplate ("sink",
gst.PAD_SINK,
gst.PAD_ALWAYS,
gst.caps_from_string("video/x-raw-rgb,width=16,height=15,bpp=24,framerate=40/1")
),
)
sinkpad = property(lambda self: self.get_pad("sink"))
def __init__(self, matrix):
gst.BaseSink.__init__(self)
self.matrix = matrix
self.set_sync(True)
gst.info('setting chain/event functions')
# will break seeking
#self.sinkpad.set_event_function(self.eventfunc)
def do_render(self, buffer):
self.matrix.send_raw_image(buffer)
return gst.FLOW_OK
def eventfunc(self, pad, event):
self.info("%s event:%r" % (pad, event.type))
return True
gobject.type_register(LedVideoSink)
class LedPipe:
def __init__(self, location, matrix, visualize=None, mainloop=None):
# The pipeline
self.visualize = visualize
self.seek_to = None
self.start_pipeline = False
self.pipeline = gst.Pipeline()
self.pipeline.auto_clock()
# Create bus and connect several handlers
self.bus = self.pipeline.get_bus()
self.bus.add_signal_watch()
self.bus.connect('message::eos', self.on_eos)
self.bus.connect('message::tag', self.on_tag)
self.bus.connect('message::error', self.on_error)
# Create elements
self.src = gst.element_factory_make('filesrc')
self.player = player = gst.element_factory_make('playbin2')
self.player.set_property("volume", 2)
self.player.set_property("flags", 0x00000001 | 0x00000002 | 0x00000008 | 0x00000010 | 0x00000200)
self.sink = gst.Bin() #gst.element_factory_make('alsasink')
self.led = LedVideoSink(matrix) #gst.element_factory_make('alsasink')
self.color = gst.element_factory_make('ffmpegcolorspace')
self.rate = gst.element_factory_make('videorate')
self.scale = gst.element_factory_make('ffvideoscale')
self.scale.set_property("method", 5)
self.sink.add(self.color, self.rate, self.scale, self.led)
ghostpad = gst.GhostPad("sink", self.color.get_pad("sink"))
self.sink.add_pad(ghostpad)
gst.element_link_many(self.color, self.rate, self.scale, self.led)
if self.visualize:
self.vis = gst.element_factory_make(self.visualize)
player.set_property("vis-plugin", self.vis)
player.set_property("video-sink", self.sink)
player.connect("about-to-finish", self.on_finish)
#player.connect("state-change", self.on_state_change)
bus = self.pipeline.get_bus()
bus.add_signal_watch()
bus.enable_sync_message_emission()
#bus.connect("message", self.on_message)
bus.connect("sync-message::element", self.on_sync_message)
bus.connect("message", self.on_message)
# Set 'location' property on filesrc
player.set_property('uri', gst.uri_is_valid(location) and location or "file://" + location)
# Connect handler for 'new-decoded-pad' signal
#self.dec.connect('new-decoded-pad', self.on_new_decoded_pad)
# Add elements to pipeline
self.pipeline.add(player)
# The MainLoop
self.mainloop = mainloop or gobject.MainLoop()
# And off we go!
self.pipeline.set_state(gst.STATE_PLAYING)
def seek(self, to):
#self.player.seek_simple(gst.FORMAT_TIME, gst.SEEK_FLAG_FLUSH, long(to))
if not self.player.seek_simple(gst.FORMAT_TIME,
gst.SEEK_FLAG_FLUSH | gst.SEEK_FLAG_KEY_UNIT,
max(to, 0)):
log("seek failed")
#self.pipeline.set_state(gst.STATE_PLAYING)
self.player.get_state(-1)
def play(self):
self.pipeline.set_state(gst.STATE_PLAYING)
def pause(self):
self.pipeline.set_state(gst.STATE_PAUSED)
@property
def paused(self):
state = self.pipeline.get_state(-1)
if not state:
return False
return state[1] != gst.STATE_PLAYING
def on_state_change(self, bus, msg):
#print "state_change", msg, msg.__dict__
pass
def quit(self):
self.pipeline.set_state(gst.STATE_NULL)
def on_finish(self, unused):
self.mainloop.quit()
def on_eos(self, bus, msg):
log('on_eos')
self.mainloop.quit()
def on_tag(self, bus, msg):
taglist = msg.parse_tag()
log('on_tag:')
for key in taglist.keys():
log('\t%s = %s' % (key, taglist[key]))
def on_error(self, bus, msg):
error = msg.parse_error()
log('on_error: %s' %error[1])
self.mainloop.quit()
def on_message(self, bus, message):
t = message.type
#print "msg",bus,message
if t == gst.MESSAGE_STATE_CHANGED:
self.on_state_change(bus, message)
elif t == gst.MESSAGE_EOS:
self.player.set_state(gst.STATE_NULL)
elif t == gst.MESSAGE_ERROR:
self.player.set_state(gst.STATE_NULL)
err, debug = message.parse_error()
print "Error: %s" % err, debug
def on_sync_message(self, bus, message):
print (bus, message)
if message.structure is None:
return
#message_name = message.structure.get_name()
#if message_name == "prepare-xwindow-id":
# imagesink = message.src
# imagesink.set_property("force-aspect-ratio", True)
# imagesink.set_xwindow_id(self.movie_window.window.xid)
#
# Code to test the MySink class
#
matrix = LedMatrix(server=args.server)
#matrix = LedMatrix(server="127.0.0.1")
pipe = LedPipe(args.file[0], matrix, visualize=args.visualize)
import glib, sys, os, fcntl
def GetInHMS(seconds):
hours = seconds / 3600
seconds -= 3600*hours
minutes = seconds / 60
seconds -= 60*minutes
if hours == 0:
return "%02d:%02d" % (minutes, seconds)
return "%02d:%02d:%02d" % (hours, minutes, seconds)
class ProgressBar:
def __init__(self, min_value = 0, max_value = 100, width=77,**kwargs):
self.char = kwargs.get('char', '#')
self.mode = kwargs.get('mode', 'dynamic') # fixed or dynamic
if not self.mode in ['fixed', 'dynamic']:
self.mode = 'fixed'
self.bar = ''
self.min = min_value
self.max = max_value
self.span = max_value - min_value
self.width = width
self.amount = 0 # When amount == max, we are 100% done
self.update_amount(0)
def increment_amount(self, add_amount = 1):
"""
Increment self.amount by 'add_ammount' or default to incrementing
by 1, and then rebuild the bar string.
"""
new_amount = self.amount + add_amount
if new_amount < self.min: new_amount = self.min
if new_amount > self.max: new_amount = self.max
self.amount = new_amount
self.build_bar()
def update_amount(self, new_amount = None):
"""
Update self.amount with 'new_amount', and then rebuild the bar
string.
"""
if not new_amount: new_amount = self.amount
if new_amount < self.min: new_amount = self.min
if new_amount > self.max: new_amount = self.max
self.amount = new_amount
self.build_bar()
def build_bar(self):
"""
Figure new percent complete, and rebuild the bar string base on
self.amount.
"""
diff = float(self.amount - self.min)
percent_done = int(round((diff / float(self.span)) * 100.0))
# figure the proper number of 'character' make up the bar
suff = " [%s/%s]" %(GetInHMS(self.amount),GetInHMS(self.max))
all_full = self.width - len(suff) - 9
num_hashes = int(round((percent_done * all_full) / 100))
if self.mode == 'dynamic':
# build a progress bar with self.char (to create a dynamic bar
# where the percent string moves along with the bar progress.
self.bar = self.char * num_hashes
else:
# build a progress bar with self.char and spaces (to create a
# fixe bar (the percent string doesn't move)
self.bar = self.char * num_hashes + ' ' * (all_full-num_hashes)
percent_str = str(percent_done) + "%"
self.bar = '[ ' + self.bar + ' ] ' + percent_str + suff
def __str__(self):
return str(self.bar)
prog = ProgressBar(0, 100, mode='fixed', width=terminal_size()[0])
def update_scrollbar():
prog = globals().get("prog", None)
try:
dur = pipe.player.query_duration(gst.FORMAT_TIME)[0]/gst.SECOND
cur = pipe.player.query_position(gst.FORMAT_TIME)[0]/gst.SECOND
if prog and prog.max != dur:
prog = ProgressBar(0, dur, mode='fixed', width=terminal_size()[0])
prog.max = dur
prog.update_amount(cur)
except gst.QueryError, e:
prog.max = 100
prog.update_amount(0)
sys.stdout.write("\r" + str(prog)),
sys.stdout.flush()
return True
import sys, tty, termios
class IODriver(object):
def __init__(self, line_callback=None, key_callback=None):
self.buffer = ''
self.line_callback = line_callback
self.key_callback = key_callback
flags = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
flags |= os.O_NONBLOCK # | os.O_NDELAY
fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, flags)
fd = sys.stdin.fileno()
#tty.setraw(sys.stdin.fileno())
#old_settings = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3] = new[3] & ~termios.ECHO & ~termios.ICANON
#new[6][termios.VMIN] = 1
#new[6][termios.VTIME] = 0
#termios.tcsetattr(fd, termios.TCSADRAIN, new)
termios.tcsetattr(fd, termios.TCSANOW, new)
glib.io_add_watch(sys.stdin, glib.IO_IN, self.io_callback)
def io_callback(self, fd, condition):
chunk = fd.read()
#log( "got %s" %repr(chunk))
if self.key_callback:
self.key_callback(chunk)
for char in chunk:
self.buffer += char
if char == '\n':
if self.line_callback:
self.line_callback(self.buffer)
self.buffer = ''
return True
def usage():
log("############## Shortcuts ##############")
log("< > seek")
log("q quit")
log("R S record/stop")
log("v switch visualization")
log("#######################################")
SEEKS = {
'\x1b[D': -15,
'\x1b[C': 15,
# shift key
'\x1b[1;2C': 30,
'\x1b[1;2D': -30,
# ctrl key
'\x1b[1;5C': 300,
'\x1b[1;5D': -300,
}
def key_entered(key):
if key == " ":
if pipe.paused:
log("playing")
pipe.play()
else:
log("pause")
pipe.pause()
k = key.strip()
if k == "q":
pipe.mainloop.quit()
elif k in SEEKS:
# seek backwards
if not pipe.player.get_state():
return
try:
cur = pipe.player.query_position(gst.FORMAT_TIME)[0]
to = max(cur + (SEEKS[k] * gst.SECOND), 0)
#print(cur, to)
pipe.seek(to)
except gst.QueryError, e:
log(e)
update_scrollbar()
elif k == "R":
log("!!!! START RECORDING !!!!")
matrix.record_start()
elif k == "S":
log("!!!! RECORDING STOPPED !!!!")
matrix.record_stop()
elif k == "v":
#FIXME
pass
else:
log("You have typed: %s" %k)
d = IODriver(key_callback=key_entered)
glib.timeout_add(500, update_scrollbar)
usage()
pipe.mainloop.run()
#
#
# class IODriver(object):
# def __init__(self, line_callback=None, key_callback=None):
# self.buffer = ''
# self.line_callback = line_callback
# self.key_callback = key_callback
# flags = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
# flags |= os.O_NONBLOCK | os.O_NDELAY
# fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, flags)
# glib.io_add_watch(sys.stdin, glib.IO_IN, self.io_callback)
#
# def io_callback(self, fd, condition):
# chunk = fd.read()
# if self.key_callback:
# self.key_callback(chunk)
# for char in chunk:
# self.buffer += char
# if char == '\n':
# if self.line_callback:
# self.line_callback(self.buffer)
# self.buffer = ''
#
# return True
#
# def line_entered(line):
# print "You have typed:", line.strip()
#
# d = IODriver(key_callback=line_entered)
# def update_scrollbar():
# try:
# log(str(pipe.player.query_position()))
# prog_bar.current = pipe.player.query_position()
# prog_bar.done = pipe.player.query_duration()
# except gst.QueryError, e:
# prog_bar.current = 0
# prog_bar.done = 1
#
# log("jo")
#
# return True
if False:
import urwid
import urwid.raw_display
ufile = urwid.Text("test", align='left')
screen = urwid.raw_display.Screen()
header = urwid.AttrWrap(urwid.Text("pentavideo"), 'header')
blank = urwid.Divider()
prog_bar = urwid.ProgressBar('pg normal', 'pg complete', 0, 1, 'pg smooth')
log_text = urwid.Text("BLA")
def log(*args):
log_text.set_text(log_text.text + "\n".join([str(x) for x in args]))
listbox_content = [
blank,
log_text,
urwid.Padding(urwid.Text("hi there"), ('fixed left',2),
('fixed right',2), 20),
blank,
prog_bar,
]
listbox = urwid.ListBox(urwid.SimpleListWalker(listbox_content))
frame = urwid.Frame(urwid.AttrWrap(listbox, 'body'), header=header)
palette = [
('body','black','light gray', 'standout'),
('reverse','light gray','black'),
('header','white','dark red', 'bold'),
('important','dark blue','light gray',('standout','underline')),
('editfc','white', 'dark blue', 'bold'),
('editbx','light gray', 'dark blue'),
('editcp','black','light gray', 'standout'),
('bright','dark gray','light gray', ('bold','standout')),
('buttn','black','dark cyan'),
('buttnf','white','dark blue','bold'),
]
def unhandled(key):
if key == 'f8':
raise urwid.ExitMainLoop()
loop = urwid.MainLoop(frame, palette, screen,
unhandled_input=unhandled, event_loop=urwid.GLibEventLoop())
loop.run()
#urwid.GLibEventLoop().run()
# if True:
#
# import curses
# stdscr = curses.initscr()
# curses.noecho()
# curses.cbreak()
# stdscr.keypad(1)
# pipe.mainloop.run()
# begin_x = 20 ; begin_y = 7
# height = 5 ; width = 40
# win = curses.newwin(height, width, begin_y, begin_x)
# curses.endwin()
#
# else:
# pipe.mainloop.run()