forked from stb-tester/stb-tester
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstbt.py
2000 lines (1619 loc) · 70.9 KB
/
stbt.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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Main stb-tester python module. Intended to be used with `stbt run`.
See `man stbt` and http://stb-tester.com for documentation.
Copyright 2012-2013 YouView TV Ltd and contributors.
License: LGPL v2.1 or (at your option) any later version (see
https://github.com/drothlis/stb-tester/blob/master/LICENSE for details).
"""
import argparse
from collections import namedtuple, deque
import ConfigParser
import contextlib
import errno
import functools
import glob
import inspect
import os
import Queue
import re
import socket
import sys
import threading
import time
import warnings
import cv2
import numpy
import irnetbox
@contextlib.contextmanager
def hide_argv():
""" For use with 'with' statement: Provides a context with an empty
argument list.
This is used because otherwise gst-python will exit if '-h', '--help', '-v'
or '--version' command line arguments are given.
"""
old_argv = sys.argv[:]
sys.argv = [sys.argv[0]]
try:
yield
finally:
sys.argv = old_argv
@contextlib.contextmanager
def hide_stderr():
"""For use with 'with' statement: Hide stderr output.
This is used because otherwise gst-python will print
'pygobject_register_sinkfunc is deprecated'.
"""
fd = sys.__stderr__.fileno()
saved_fd = os.dup(fd)
sys.__stderr__.flush()
null_stream = open(os.devnull, 'w', 0)
os.dup2(null_stream.fileno(), fd)
try:
yield
finally:
sys.__stderr__.flush()
os.dup2(saved_fd, sys.__stderr__.fileno())
null_stream.close()
import pygst # gstreamer
pygst.require("0.10")
with hide_argv(), hide_stderr():
import gst
import gobject
import glib
warnings.filterwarnings(
action="always", category=DeprecationWarning, message='^noise_threshold')
_config = None
# Functions available to stbt scripts
#===========================================================================
def get_config(section, key, default=None, type_=str):
"""Read the value of `key` from `section` of the stbt config file.
See 'CONFIGURATION' in the stbt(1) man page for the config file search
path.
Raises `ConfigurationError` if the specified `section` or `key` is not
found, unless `default` is specified (in which case `default` is returned).
"""
global _config
if not _config:
_config = ConfigParser.SafeConfigParser()
_config.readfp(
open(os.path.join(os.path.dirname(__file__), 'stbt.conf')))
try:
# Host-wide config, e.g. /etc/stbt/stbt.conf (see `Makefile`).
system_config = _config.get('global', '__system_config')
except ConfigParser.NoOptionError:
# Running `stbt` from source (not installed) location.
system_config = ''
_config.read([
system_config,
# User config: ~/.config/stbt/stbt.conf, as per freedesktop's base
# directory specification:
'%s/stbt/stbt.conf' % os.environ.get(
'XDG_CONFIG_HOME', '%s/.config' % os.environ['HOME']),
# Config files specific to the test suite / test run:
os.environ.get('STBT_CONFIG_FILE', ''),
])
try:
return type_(_config.get(section, key))
except ConfigParser.Error as e:
if default is None:
raise ConfigurationError(e.message)
else:
return default
except ValueError:
raise ConfigurationError("'%s.%s' invalid type (must be %s)" % (
section, key, type_.__name__))
def press(key):
"""Send the specified key-press to the system under test.
The mechanism used to send the key-press depends on what you've configured
with `--control`.
`key` is a string. The allowed values depend on the control you're using:
If that's lirc, then `key` is a key name from your lirc config file.
"""
_control.press(key)
draw_text(key, duration_secs=3)
def draw_text(text, duration_secs=3):
"""Write the specified `text` to the video output.
`duration_secs` is the number of seconds that the text should be displayed.
"""
_display.draw_text(text, duration_secs)
class MatchParameters(object):
"""Parameters to customise the image processing algorithm used by
`wait_for_match`, `detect_match`, and `press_until_match`.
You can change the default values for these parameters by setting
a key (with the same name as the corresponding python parameter)
in the `[match]` section of your stbt.conf configuration file.
`match_method` (str) default: From stbt.conf
The method that is used by the OpenCV `cvMatchTemplate` algorithm to find
likely locations of the "template" image within the larger source image.
Allowed values are ``"sqdiff-normed"``, ``"ccorr-normed"``, and
``"ccoeff-normed"``. For the meaning of these parameters, see the OpenCV
`cvMatchTemplate` reference documentation and tutorial:
* http://docs.opencv.org/modules/imgproc/doc/object_detection.html
* http://docs.opencv.org/doc/tutorials/imgproc/histograms/
template_matching/template_matching.html
`match_threshold` (float) default: From stbt.conf
How strong a result from `cvMatchTemplate` must be, to be considered a
match. A value of 0 will mean that anything is considered to match,
whilst a value of 1 means that the match has to be pixel perfect. (In
practice, a value of 1 is useless because of the way `cvMatchTemplate`
works, and due to limitations in the storage of floating point numbers in
binary.)
`confirm_method` (str) default: From stbt.conf
The result of the previous `cvMatchTemplate` algorithm often gives false
positives (it reports a "match" for an image that shouldn't match).
`confirm_method` specifies an algorithm to be run just on the region of
the source image that `cvMatchTemplate` identified as a match, to confirm
or deny the match.
The allowed values are:
"``none``"
Do not confirm the match. Assume that the potential match found is
correct.
"``absdiff``" (absolute difference)
The absolute difference between template and source Region of
Interest (ROI) is calculated; thresholded and eroded to account for
potential noise; and if any white pixels remain then the match is
deemed false.
"``normed-absdiff``" (normalized absolute difference)
As with ``absdiff`` but both template and ROI are normalized before
the absolute difference is calculated. This has the effect of
exaggerating small differences between images with similar, small
ranges of pixel brightnesses (luminance).
This method is more accurate than ``absdiff`` at reporting true and
false matches when there is noise involved, particularly aliased
text. However it will, in general, require a greater
confirm_threshold than the equivalent match with absdiff.
When matching solid regions of colour, particularly where there are
regions of either black or white, ``absdiff`` is better than
``normed-absdiff`` because it does not alter the luminance range,
which can lead to false matches. For example, an image which is half
white and half grey, once normalised, will match a similar image
which is half white and half black because the grey becomes
normalised to black so that the maximum luminance range of [0..255]
is occupied. However, if the images are dissimilar enough in
luminance, they will have failed to match the `cvMatchTemplate`
algorithm and won't have reached the "confirm" stage.
`confirm_threshold` (float) default: From stbt.conf
Increase this value to avoid false negatives, at the risk of increasing
false positives (a value of 1.0 will report a match every time).
`erode_passes` (int) default: From stbt.conf
The number of erode steps in the `absdiff` and `normed-absdiff` confirm
algorithms. Increasing the number of erode steps makes your test less
sensitive to noise and small variances, at the cost of being more likely
to report a false positive.
Please let us know if you are having trouble with image matches so that we
can further improve the matching algorithm.
"""
def __init__(
self,
match_method=get_config('match', 'match_method'),
match_threshold=get_config(
'match', 'match_threshold', type_=float),
confirm_method=get_config('match', 'confirm_method'),
confirm_threshold=get_config(
'match', 'confirm_threshold', type_=float),
erode_passes=get_config('match', 'erode_passes', type_=int)):
if match_method not in (
"sqdiff-normed", "ccorr-normed", "ccoeff-normed"):
raise ValueError("Invalid match_method '%s'" % match_method)
if confirm_method not in ("none", "absdiff", "normed-absdiff"):
raise ValueError("Invalid confirm_method '%s'" % confirm_method)
self.match_method = match_method
self.match_threshold = match_threshold
self.confirm_method = confirm_method
self.confirm_threshold = confirm_threshold
self.erode_passes = erode_passes
class Position(namedtuple('Position', 'x y')):
"""
* `x` and `y`: Integer coordinates from the top left corner of the video
frame.
"""
pass
class MatchResult(namedtuple(
'MatchResult', 'timestamp match position first_pass_result')):
"""
* `timestamp`: Video stream timestamp.
* `match`: Boolean result.
* `position`: `Position` of the match.
* `first_pass_result`: Value between 0 (poor) and 1.0 (excellent match)
from the first pass of the two-pass templatematch algorithm.
"""
pass
def detect_match(image, timeout_secs=10, noise_threshold=None,
match_parameters=None):
"""Generator that yields a sequence of one `MatchResult` for each frame
processed from the source video stream.
Returns after `timeout_secs` seconds. (Note that the caller can also choose
to stop iterating over this function's results at any time.)
The templatematch parameter `noise_threshold` is marked for deprecation
but appears in the args for backward compatibility with positional
argument syntax. It will be removed in a future release; please use
`match_parameters.confirm_threshold` intead.
Specify `match_parameters` to customise the image matching algorithm. See
the documentation for `MatchParameters` for details.
"""
if match_parameters is None:
match_parameters = MatchParameters()
if noise_threshold is not None:
warnings.warn(
"noise_threshold is marked for deprecation. Please use "
"match_parameters.confirm_threshold instead.",
DeprecationWarning, stacklevel=2)
match_parameters.confirm_threshold = noise_threshold
template_name = _find_path(image)
if not os.path.isfile(template_name):
raise UITestError("No such template file: %s" % image)
template = cv2.imread(template_name, cv2.CV_LOAD_IMAGE_COLOR)
if template is None:
raise UITestError("Failed to load template file: %s" % template_name)
debug("Searching for " + template_name)
for frame, timestamp in frames(timeout_secs):
matched, position, first_pass_certainty = _match(
frame, template, match_parameters, template_name)
result = MatchResult(
timestamp=timestamp,
match=matched,
position=position,
first_pass_result=first_pass_certainty)
debug("%s found: %s" % (
"Match" if matched else "Weak match", str(result)))
yield result
class MotionResult(namedtuple('MotionResult', 'timestamp motion')):
"""
* `timestamp`: Video stream timestamp.
* `motion`: Boolean result.
"""
pass
def detect_motion(timeout_secs=10, noise_threshold=None, mask=None):
"""Generator that yields a sequence of one `MotionResult` for each frame
processed from the source video stream.
Returns after `timeout_secs` seconds. (Note that the caller can also choose
to stop iterating over this function's results at any time.)
`noise_threshold` (float) default: From stbt.conf
`noise_threshold` is a parameter used by the motiondetect algorithm.
Increase `noise_threshold` to avoid false negatives, at the risk of
increasing false positives (a value of 0.0 will never report motion).
This is particularly useful with noisy analogue video sources.
The default value is read from `motion.noise_threshold` in your
configuration file.
`mask` (str) default: None
A mask is a black and white image that specifies which part of the image
to search for motion. White pixels select the area to search; black
pixels the area to ignore.
"""
if noise_threshold is None:
noise_threshold = get_config('motion', 'noise_threshold', type_=float)
debug("Searching for motion")
mask_image = None
if mask:
mask_ = _find_path(mask)
debug("Using mask %s" % mask_)
if not os.path.isfile(mask_):
raise UITestError("No such mask file: %s" % mask)
mask_image = cv2.imread(mask_, cv2.CV_LOAD_IMAGE_GRAYSCALE)
if mask_image is None:
raise UITestError("Failed to load mask file: %s" % mask_)
previous_frame_gray = None
log = functools.partial(_log_image, directory="stbt-debug/detect_motion")
for frame, timestamp in frames(timeout_secs):
frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
log(frame_gray, "source")
if previous_frame_gray is None:
if (mask_image is not None and
mask_image.shape[:2] != frame.shape[:2]):
raise UITestError(
"The dimensions of the mask '%s' %s don't match the video "
"frame %s" % (mask_, mask_image.shape, frame.shape))
previous_frame_gray = frame_gray
continue
absdiff = cv2.absdiff(frame_gray, previous_frame_gray)
previous_frame_gray = frame_gray
log(absdiff, "absdiff")
if mask_image is not None:
absdiff = cv2.bitwise_and(absdiff, mask_image)
log(mask_image, "mask")
log(absdiff, "absdiff_masked")
_, thresholded = cv2.threshold(
absdiff, int((1 - noise_threshold) * 255), 255, cv2.THRESH_BINARY)
eroded = cv2.erode(
thresholded,
cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))
log(thresholded, "absdiff_threshold")
log(eroded, "absdiff_threshold_erode")
motion = (cv2.countNonZero(eroded) > 0)
# Visualisation: Highlight in red the areas where we detected motion
if motion:
cv2.add(
frame,
numpy.multiply(
numpy.ones(frame.shape, dtype=numpy.uint8),
(0, 0, 255), # bgr
dtype=numpy.uint8),
mask=cv2.dilate(
thresholded,
cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)),
iterations=1),
dst=frame)
result = MotionResult(timestamp, motion)
debug("%s found: %s" % (
"Motion" if motion else "No motion", str(result)))
yield result
def wait_for_match(image, timeout_secs=10, consecutive_matches=1,
noise_threshold=None, match_parameters=None):
"""Search for `image` in the source video stream.
Returns `MatchResult` when `image` is found.
Raises `MatchTimeout` if no match is found after `timeout_secs` seconds.
`consecutive_matches` forces this function to wait for several consecutive
frames with a match found at the same x,y position. Increase
`consecutive_matches` to avoid false positives due to noise.
The templatematch parameter `noise_threshold` is marked for deprecation
but appears in the args for backward compatibility with positional
argument syntax. It will be removed in a future release; please use
`match_parameters.confirm_threshold` instead.
Specify `match_parameters` to customise the image matching algorithm. See
the documentation for `MatchParameters` for details.
"""
if match_parameters is None:
match_parameters = MatchParameters()
if noise_threshold is not None:
warnings.warn(
"noise_threshold is marked for deprecation. Please use "
"match_parameters.confirm_threshold instead.",
DeprecationWarning, stacklevel=2)
match_parameters.confirm_threshold = noise_threshold
match_count = 0
last_pos = Position(0, 0)
for res in detect_match(
image, timeout_secs, match_parameters=match_parameters):
if res.match and (match_count == 0 or res.position == last_pos):
match_count += 1
else:
match_count = 0
last_pos = res.position
if match_count == consecutive_matches:
debug("Matched " + image)
return res
screenshot = get_frame()
raise MatchTimeout(screenshot, image, timeout_secs)
def press_until_match(
key,
image,
interval_secs=get_config(
"press_until_match", "interval_secs", type_=int),
noise_threshold=None,
max_presses=get_config("press_until_match", "max_presses", type_=int),
match_parameters=None):
"""Calls `press` as many times as necessary to find the specified `image`.
Returns `MatchResult` when `image` is found.
Raises `MatchTimeout` if no match is found after `max_presses` times.
`interval_secs` is the number of seconds to wait for a match before
pressing again.
The global defaults for `interval_secs` and `max_presses` can be set
in the configuration file, in section `press_until_match`.
The templatematch parameter `noise_threshold` is marked for deprecation
but appears in the args for backward compatibility with positional
argument syntax. It will be removed in a future release; please use
`match_parameters.confirm_threshold` instead.
Specify `match_parameters` to customise the image matching algorithm. See
the documentation for `MatchParameters` for details.
"""
if match_parameters is None:
match_parameters = MatchParameters()
if noise_threshold is not None:
warnings.warn(
"noise_threshold is marked for deprecation. Please use "
"match_parameters.confirm_threshold instead.",
DeprecationWarning, stacklevel=2)
match_parameters.confirm_threshold = noise_threshold
i = 0
while True:
try:
return wait_for_match(image, timeout_secs=interval_secs,
match_parameters=match_parameters)
except MatchTimeout:
if i < max_presses:
press(key)
i += 1
else:
raise
def wait_for_motion(
timeout_secs=10, consecutive_frames=None,
noise_threshold=None, mask=None):
"""Search for motion in the source video stream.
Returns `MotionResult` when motion is detected.
Raises `MotionTimeout` if no motion is detected after `timeout_secs`
seconds.
`consecutive_frames` (str) default: From stbt.conf
Considers the video stream to have motion if there were differences
between the specified number of `consecutive_frames`, which can be:
* a positive integer value, or
* a string in the form "x/y", where `x` is the number of frames with
motion detected out of a sliding window of `y` frames.
The default value is read from `motion.consecutive_frames` in your
configuration file.
`noise_threshold` (float) default: From stbt.conf
Increase `noise_threshold` to avoid false negatives, at the risk of
increasing false positives (a value of 0.0 will never report motion).
This is particularly useful with noisy analogue video sources.
The default value is read from `motion.noise_threshold` in your
configuration file.
`mask` (str) default: None
A mask is a black and white image that specifies which part of the image
to search for motion. White pixels select the area to search; black
pixels the area to ignore.
"""
if consecutive_frames is None:
consecutive_frames = get_config('motion', 'consecutive_frames')
consecutive_frames = str(consecutive_frames)
if '/' in consecutive_frames:
motion_frames = int(consecutive_frames.split('/')[0])
considered_frames = int(consecutive_frames.split('/')[1])
else:
motion_frames = int(consecutive_frames)
considered_frames = int(consecutive_frames)
if motion_frames > considered_frames:
raise ConfigurationError(
"`motion_frames` exceeds `considered_frames`")
debug("Waiting for %d out of %d frames with motion" % (
motion_frames, considered_frames))
matches = deque(maxlen=considered_frames)
for res in detect_motion(timeout_secs, noise_threshold, mask):
matches.append(res.motion)
if matches.count(True) >= motion_frames:
debug("Motion detected.")
return res
screenshot = get_frame()
raise MotionTimeout(screenshot, mask, timeout_secs)
def frames(timeout_secs=None):
"""Generator that yields frames captured from the GStreamer pipeline.
"timeout_secs" is in seconds elapsed, from the method call. Note that
you can also simply stop iterating over the sequence yielded by this
method.
Returns an (image, timestamp) tuple for every frame captured, where
"image" is in OpenCV format.
"""
return _display.frames(timeout_secs)
def save_frame(image, filename):
"""Saves an OpenCV image to the specified file.
Takes an image obtained from `get_frame` or from the `screenshot`
property of `MatchTimeout` or `MotionTimeout`.
"""
cv2.imwrite(filename, image)
def get_frame():
"""Returns an OpenCV image of the current video frame."""
return gst_to_opencv(_display.get_frame())
def debug(msg):
"""Print the given string to stderr if stbt run `--verbose` was given."""
if _debug_level > 0:
sys.stderr.write(
"%s: %s\n" % (os.path.basename(sys.argv[0]), str(msg)))
class UITestError(Exception):
"""The test script had an unrecoverable error."""
pass
class UITestFailure(Exception):
"""The test failed because the system under test didn't behave as expected.
"""
pass
class NoVideo(UITestFailure):
"""No video available from the source pipeline."""
pass
class MatchTimeout(UITestFailure):
"""
* `screenshot`: An OpenCV image from the source video when the search
for the expected image timed out.
* `expected`: Filename of the image that was being searched for.
* `timeout_secs`: Number of seconds that the image was searched for.
"""
def __init__(self, screenshot, expected, timeout_secs):
super(MatchTimeout, self).__init__()
self.screenshot = screenshot
self.expected = expected
self.timeout_secs = timeout_secs
def __str__(self):
return "Didn't find match for '%s' within %d seconds." % (
self.expected, self.timeout_secs)
class MotionTimeout(UITestFailure):
"""
* `screenshot`: An OpenCV image from the source video when the search
for motion timed out.
* `mask`: Filename of the mask that was used (see `wait_for_motion`).
* `timeout_secs`: Number of seconds that motion was searched for.
"""
def __init__(self, screenshot, mask, timeout_secs):
super(MotionTimeout, self).__init__()
self.screenshot = screenshot
self.mask = mask
self.timeout_secs = timeout_secs
def __str__(self):
return "Didn't find motion%s within %d seconds." % (
" (with mask '%s')" % self.mask if self.mask else "",
self.timeout_secs)
class ConfigurationError(UITestError):
pass
# stbt-run initialisation and convenience functions
# (you will need these if writing your own version of stbt-run)
#===========================================================================
def argparser():
parser = argparse.ArgumentParser()
parser.add_argument(
'--control',
default=get_config('global', 'control'),
help='The remote control to control the stb (default: %(default)s)')
parser.add_argument(
'--source-pipeline',
default=get_config('global', 'source_pipeline'),
help='A gstreamer pipeline to use for A/V input (default: '
'%(default)s)')
parser.add_argument(
'--sink-pipeline',
default=get_config('global', 'sink_pipeline'),
help='A gstreamer pipeline to use for video output '
'(default: %(default)s)')
parser.add_argument(
'--restart-source', action='store_true',
default=(get_config('global', 'restart_source').lower() in
("1", "yes", "true", "on")),
help='Restart the GStreamer source pipeline when video loss is '
'detected')
class IncreaseDebugLevel(argparse.Action):
num_calls = 0
def __call__(self, parser, namespace, values, option_string=None):
self.num_calls += 1
global _debug_level
_debug_level = self.num_calls
setattr(namespace, self.dest, _debug_level)
global _debug_level
_debug_level = get_config('global', 'verbose', type_=int)
parser.add_argument(
'-v', '--verbose', action=IncreaseDebugLevel, nargs=0,
default=get_config('global', 'verbose'), # for stbt-run arguments dump
help='Enable debug output (specify twice to enable GStreamer element '
'dumps to ./stbt-debug directory)')
return parser
def init_run(
gst_source_pipeline, gst_sink_pipeline, control_uri, save_video=False,
restart_source=False):
global _display, _control
_display = Display(
gst_source_pipeline, gst_sink_pipeline, save_video, restart_source)
_control = uri_to_remote(control_uri, _display)
def teardown_run():
if _display:
_display.teardown()
# Internal
#===========================================================================
_debug_level = 0
_mainloop = glib.MainLoop()
_display = None
_control = None
class Display:
def __init__(self, user_source_pipeline, user_sink_pipeline, save_video,
restart_source=False):
gobject.threads_init()
self.novideo = False
self.lock = threading.RLock() # Held by whoever is consuming frames
self.last_buffer = Queue.Queue(maxsize=1)
self.source_pipeline = None
self.start_timestamp = None
self.underrun_timeout = None
self.video_debug = []
self.restart_source_enabled = restart_source
appsink = (
"appsink name=appsink max-buffers=1 drop=true sync=false "
"emit-signals=true "
"caps=video/x-raw-rgb,bpp=24,depth=24,endianness=4321,"
"red_mask=0xFF,green_mask=0xFF00,blue_mask=0xFF0000")
self.source_pipeline_description = " ! ".join([
user_source_pipeline,
"queue leaky=downstream name=q",
"ffmpegcolorspace",
appsink])
self.create_source_pipeline()
if save_video:
if not save_video.endswith(".webm"):
save_video += ".webm"
debug("Saving video to '%s'" % save_video)
video_pipeline = (
"t. ! queue leaky=downstream ! ffmpegcolorspace ! "
"vp8enc speed=7 ! webmmux ! filesink location=%s" % save_video)
else:
video_pipeline = ""
sink_pipeline_description = " ".join([
"appsrc name=appsrc !",
"tee name=t",
video_pipeline,
"t. ! queue leaky=downstream ! ffmpegcolorspace !",
user_sink_pipeline
])
self.sink_pipeline = gst.parse_launch(sink_pipeline_description)
sink_bus = self.sink_pipeline.get_bus()
sink_bus.connect("message::error", self.on_error)
sink_bus.connect("message::warning", self.on_warning)
sink_bus.connect("message::eos", self.on_eos_from_sink_pipeline)
sink_bus.add_signal_watch()
self.appsrc = self.sink_pipeline.get_by_name("appsrc")
debug("source pipeline: %s" % self.source_pipeline_description)
debug("sink pipeline: %s" % sink_pipeline_description)
self.source_pipeline.set_state(gst.STATE_PLAYING)
self.sink_pipeline.set_state(gst.STATE_PLAYING)
self.mainloop_thread = threading.Thread(target=_mainloop.run)
self.mainloop_thread.daemon = True
self.mainloop_thread.start()
def create_source_pipeline(self):
self.source_pipeline = gst.parse_launch(
self.source_pipeline_description)
source_bus = self.source_pipeline.get_bus()
source_bus.connect("message::error", self.on_error)
source_bus.connect("message::warning", self.on_warning)
source_bus.connect("message::eos", self.on_eos_from_source_pipeline)
source_bus.add_signal_watch()
appsink = self.source_pipeline.get_by_name("appsink")
appsink.connect("new-buffer", self.on_new_buffer)
if self.restart_source_enabled:
# Handle loss of video (but without end-of-stream event) from the
# Hauppauge HDPVR capture device.
source_queue = self.source_pipeline.get_by_name("q")
self.start_timestamp = None
source_queue.connect("underrun", self.on_underrun)
source_queue.connect("running", self.on_running)
def get_frame(self, timeout_secs=10):
try:
# Timeout in case no frames are received. This happens when the
# Hauppauge HDPVR video-capture device loses video.
gst_buffer = self.last_buffer.get(timeout=timeout_secs)
self.novideo = False
except Queue.Empty:
self.novideo = True
raise NoVideo("No video")
if isinstance(gst_buffer, Exception):
raise UITestError(str(gst_buffer))
return gst_buffer
def frames(self, timeout_secs):
self.start_timestamp = None
with self.lock:
while True:
ddebug("user thread: Getting buffer at %s" % time.time())
buf = self.get_frame(max(10, timeout_secs))
ddebug("user thread: Got buffer at %s" % time.time())
timestamp = buf.timestamp
if timeout_secs is not None:
if not self.start_timestamp:
self.start_timestamp = timestamp
if (timestamp - self.start_timestamp > timeout_secs * 1e9):
debug("timed out: %d - %d > %d" % (
timestamp, self.start_timestamp,
timeout_secs * 1e9))
return
image = gst_to_opencv(buf)
try:
yield (image, timestamp)
finally:
self.push_buffer(buf, image)
def on_new_buffer(self, appsink):
buf = appsink.emit("pull-buffer")
self.tell_user_thread(buf)
if self.lock.acquire(False): # non-blocking
try:
self.push_buffer(buf)
finally:
self.lock.release()
def tell_user_thread(self, buffer_or_exception):
# `self.last_buffer` (a synchronised Queue) is how we communicate from
# this thread (the GLib main loop) to the main application thread
# running the user's script. Note that only this thread writes to the
# Queue.
if isinstance(buffer_or_exception, Exception):
ddebug("glib thread: reporting exception to user thread: %s" %
buffer_or_exception)
else:
ddebug("glib thread: new buffer (timestamp=%s). Queue.qsize: %d" %
(buffer_or_exception.timestamp, self.last_buffer.qsize()))
# Drop old frame
try:
self.last_buffer.get_nowait()
except Queue.Empty:
pass
self.last_buffer.put_nowait(buffer_or_exception)
def draw_text(self, text, duration_secs):
"""Draw the specified text on the output video."""
self.video_debug.append((text, duration_secs, None))
def push_buffer(self, gst_buffer, opencv_image=None):
for text, duration, timeout in list(self.video_debug):
if timeout is None:
timeout = gst_buffer.timestamp + (duration * 1e9)
self.video_debug.remove((text, duration, None))
self.video_debug.append((text, duration, timeout))
if (gst_buffer.timestamp > timeout):
self.video_debug.remove((text, duration, timeout))
if opencv_image is None and len(self.video_debug) == 0:
self.appsrc.emit("push-buffer", gst_buffer)
else:
if opencv_image is None:
opencv_image = gst_to_opencv(gst_buffer)
for i in range(len(self.video_debug)):
text, _, _ = self.video_debug[len(self.video_debug) - i - 1]
cv2.putText(
opencv_image, text, (10, (i + 1) * 30),
cv2.FONT_HERSHEY_TRIPLEX, fontScale=1.0,
color=(255, 255, 255))
newbuf = gst.Buffer(opencv_image.data)
newbuf.set_caps(gst_buffer.get_caps())
newbuf.timestamp = gst_buffer.timestamp
self.appsrc.emit("push-buffer", newbuf)
def on_error(self, _bus, message):
assert message.type == gst.MESSAGE_ERROR
err, dbg = message.parse_error()
self.tell_user_thread(
UITestError("%s: %s\n%s\n" % (err, err.message, dbg)))
_mainloop.quit()
@staticmethod
def on_warning(_bus, message):
assert message.type == gst.MESSAGE_WARNING
err, dbg = message.parse_warning()
sys.stderr.write("Warning: %s: %s\n%s\n" % (err, err.message, dbg))
def on_eos_from_source_pipeline(self, _bus, _message):
warn("Got EOS from source pipeline")
self.restart_source()
def on_eos_from_sink_pipeline(self, _bus, _message):
debug("Got EOS")
_mainloop.quit()
def on_underrun(self, _element):
if self.underrun_timeout:
ddebug("underrun: I already saw a recent underrun; ignoring")
else:
ddebug("underrun: scheduling 'restart_source' in 2s")
self.underrun_timeout = GObjectTimeout(2, self.restart_source)
self.underrun_timeout.start()
def on_running(self, _element):
if self.underrun_timeout:
ddebug("running: cancelling underrun timer")
self.underrun_timeout.cancel()
self.underrun_timeout = None
else:
ddebug("running: no outstanding underrun timers; ignoring")
def restart_source(self, *_args):
warn("Attempting to recover from video loss: "
"Stopping source pipeline and waiting 5s...")
self.source_pipeline.set_state(gst.STATE_NULL)
self.source_pipeline = None
GObjectTimeout(5, self.start_source).start()
return False # stop the timeout from running again
def start_source(self):
warn("Restarting source pipeline...")
self.create_source_pipeline()
self.source_pipeline.set_state(gst.STATE_PLAYING)
warn("Restarted source pipeline")
if self.restart_source_enabled:
self.underrun_timeout.start()
return False # stop the timeout from running again
def teardown(self):
if self.source_pipeline:
self.source_pipeline.set_state(gst.STATE_NULL)
if not self.novideo:
debug("teardown: Sending eos")
self.appsrc.emit("end-of-stream")
self.mainloop_thread.join(10)
debug("teardown: Exiting (GLib mainloop %s)" % (
"is still alive!" if self.mainloop_thread.isAlive() else "ok"))
class GObjectTimeout:
"""Responsible for setting a timeout in the GTK main loop."""
def __init__(self, timeout_secs, handler, *args):
self.timeout_secs = timeout_secs
self.handler = handler
self.args = args
self.timeout_id = None