-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathvisualmetrics.py
1908 lines (1724 loc) · 78.9 KB
/
visualmetrics.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
#!/usr/bin/env python
"""
Copyright 2019 WebPageTest LLC.
Copyright (c) 2014, Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the company nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."""
import gc
import glob
import gzip
import json
import logging
import math
import os
import platform
import re
import shutil
import subprocess
import sys
import tempfile
if (sys.version_info > (3, 0)):
GZIP_TEXT = 'wt'
GZIP_READ_TEXT = 'rt'
else:
GZIP_TEXT = 'w'
GZIP_READ_TEXT = 'r'
# Globals
options = None
client_viewport = None
image_magick = {'convert': 'convert', 'compare': 'compare', 'mogrify': 'mogrify'}
frame_cache = {}
# #################################################################################################
# Frame Extraction and de-duplication
# #################################################################################################
def video_to_frames(video, directory, force, orange_file, white_file, gray_file, multiple,
find_viewport, viewport_time, full_resolution, timeline_file, trim_end):
""" Extract the video frames"""
global client_viewport
first_frame = os.path.join(directory, 'ms_000000')
if (not os.path.isfile(first_frame + '.png')
and not os.path.isfile(first_frame + '.jpg')) or force:
if os.path.isfile(video):
video = os.path.realpath(video)
logging.info(
"Processing frames from video " +
video +
" to " +
directory)
if os.path.isdir(directory):
shutil.rmtree(directory, True)
if not os.path.isdir(directory):
os.mkdir(directory, 0o755)
if os.path.isdir(directory):
directory = os.path.realpath(directory)
viewport = find_video_viewport(
video, directory, find_viewport, viewport_time)
gc.collect()
if extract_frames(video, directory, full_resolution, viewport):
client_viewport = None
if find_viewport and options.notification:
client_viewport = find_image_viewport(
os.path.join(directory, 'video-000000.png'))
if multiple and orange_file is not None:
directories = split_videos(directory, orange_file)
else:
directories = [directory]
for dir in directories:
trim_video_end(dir, trim_end)
if orange_file is not None:
remove_frames_before_orange(dir, orange_file)
remove_orange_frames(dir, orange_file)
find_first_frame(dir, white_file)
blank_first_frame(dir)
find_render_start(dir, orange_file, gray_file)
find_last_frame(dir, white_file)
adjust_frame_times(dir)
if timeline_file is not None and not multiple:
synchronize_to_timeline(dir, timeline_file)
eliminate_duplicate_frames(dir)
eliminate_similar_frames(dir)
# See if we are limiting the number of frames to keep
# (before processing them to save processing time)
if options.maxframes > 0:
cap_frame_count(dir, options.maxframes)
crop_viewport(dir)
gc.collect()
else:
logging.critical("Error extracting the video frames from %s", video)
else:
logging.critical("Error creating output directory: %s", directory)
else:
logging.critical("Input video file %s does not exist", video)
else:
logging.info("Extracted video already exists in %s", directory)
def extract_frames(video, directory, full_resolution, viewport):
"""Extract and number the video frames"""
ret = False
logging.info("Extracting frames from " + video + " to " + directory)
decimate = get_decimate_filter()
if decimate is not None:
crop = ''
if viewport is not None:
crop = 'crop={0}:{1}:{2}:{3},'.format(
viewport['width'], viewport['height'], viewport['x'], viewport['y'])
scale = 'scale=iw*min({0:d}/iw\\,{0:d}/ih):ih*min({0:d}/iw\\,{0:d}/ih),'.format(
options.thumbsize)
if full_resolution:
scale = ''
# escape directory name
# see https://en.wikibooks.org/wiki/FFMPEG_An_Intermediate_Guide/image_sequence#Percent_in_filename
dir_escaped = directory.replace("%", "%%")
command = ['ffmpeg', '-v', 'debug', '-i', video, '-vsync', '0',
'-vf', crop + scale + decimate + '=0:64:640:0.001',
os.path.join(dir_escaped, 'img-%d.png')]
logging.debug(' '.join(command))
lines = []
proc = subprocess.Popen(command, stderr=subprocess.PIPE, universal_newlines=True)
while proc.poll() is None:
lines.append(proc.stderr.readline())
pattern = re.compile(r'keep pts:[0-9]+ pts_time:(?P<timecode>[0-9\.]+)')
frame_count = 0
for line in lines:
match = re.search(pattern, line)
if match:
frame_count += 1
frame_time = int(math.ceil(float( \
match.groupdict().get('timecode')) * 1000))
src = os.path.join(
directory, 'img-{0:d}.png'.format(frame_count))
dest = os.path.join(
directory, 'video-{0:06d}.png'.format(frame_time))
logging.debug('Renaming ' + src + ' to ' + dest)
os.rename(src, dest)
ret = True
return ret
def split_videos(directory, orange_file):
"""Split multiple videos on orange frame separators"""
logging.debug(
"Splitting video on orange frames (this may take a while)...")
directories = []
current = 0
found_orange = False
video_dir = None
frames = sorted(glob.glob(os.path.join(directory, 'video-*.png')))
if len(frames):
for frame in frames:
if is_color_frame(frame, orange_file):
if not found_orange:
found_orange = True
# Make a copy of the orange frame for the end of the
# current video
if video_dir is not None:
dest = os.path.join(video_dir, os.path.basename(frame))
shutil.copyfile(frame, dest)
current += 1
video_dir = os.path.join(directory, str(current))
logging.debug("Orange frame found: %s, starting video directory %s",
frame, video_dir)
if not os.path.isdir(video_dir):
os.mkdir(video_dir, 0o755)
if os.path.isdir(video_dir):
video_dir = os.path.realpath(video_dir)
clean_directory(video_dir)
directories.append(video_dir)
else:
video_dir = None
else:
found_orange = False
if video_dir is not None:
dest = os.path.join(video_dir, os.path.basename(frame))
os.rename(frame, dest)
else:
logging.debug("Removing spurious frame %s at the beginning", frame)
os.remove(frame)
return directories
def remove_frames_before_orange(directory, orange_file):
"""Remove stray frames from the start of the video"""
frames = sorted(glob.glob(os.path.join(directory, 'video-*.png')))
if len(frames):
# go through the first 20 frames and remove any that come before the first orange frame.
# iOS video capture starts with a blank white frame and then flips to
# orange before starting.
logging.debug("Scanning for non-orange frames...")
found_orange = False
remove_frames = []
frame_count = 0
for frame in frames:
frame_count += 1
if is_color_frame(frame, orange_file):
found_orange = True
break
if frame_count > 20:
break
remove_frames.append(frame)
if found_orange and len(remove_frames):
for frame in remove_frames:
logging.debug("Removing pre-orange frame %s", frame)
os.remove(frame)
def remove_orange_frames(directory, orange_file):
"""Remove orange frames from the beginning of the video"""
frames = sorted(glob.glob(os.path.join(directory, 'video-*.png')))
if len(frames):
logging.debug("Scanning for orange frames...")
for frame in frames:
if is_color_frame(frame, orange_file):
logging.debug("Removing Orange frame: %s", frame)
os.remove(frame)
else:
break
for frame in reversed(frames):
if is_color_frame(frame, orange_file):
logging.debug("Removing orange frame %s from the end", frame)
os.remove(frame)
else:
break
def find_image_viewport(file):
logging.debug("Finding the viewport for %s", file)
im = None
try:
from PIL import Image
im = Image.open(file)
width, height = im.size
x = int(math.floor(width / 2))
y = int(math.floor(height / 2))
pixels = im.load()
background = pixels[x, y]
# Find the left edge
left = None
while left is None and x >= 0:
if not colors_are_similar(background, pixels[x, y]):
left = x + 1
else:
x -= 1
if left is None:
left = 0
logging.debug('Viewport left edge is %d', left)
# Find the right edge
x = int(math.floor(width / 2))
right = None
while right is None and x < width:
if not colors_are_similar(background, pixels[x, y]):
right = x - 1
else:
x += 1
if right is None:
right = width
logging.debug('Viewport right edge is {0:d}'.format(right))
# Find the top edge
x = int(math.floor(width / 2))
top = None
while top is None and y >= 0:
if not colors_are_similar(background, pixels[x, y]):
top = y + 1
else:
y -= 1
if top is None:
top = 0
logging.debug('Viewport top edge is {0:d}'.format(top))
# Find the bottom edge
y = int(math.floor(height / 2))
bottom = None
while bottom is None and y < height:
if not colors_are_similar(background, pixels[x, y]):
bottom = y - 1
else:
y += 1
if bottom is None:
bottom = height
logging.debug('Viewport bottom edge is {0:d}'.format(bottom))
viewport = {
'x': left,
'y': top,
'width': (right - left),
'height': (bottom - top)}
except Exception:
logging.exception('Error calculating viewport')
viewport = None
if im is not None:
try:
im.close()
except Exception:
pass
return viewport
def find_video_viewport(video, directory, find_viewport, viewport_time):
logging.debug("Finding Video Viewport...")
viewport = None
try:
from PIL import Image
frame = os.path.join(directory, 'viewport.png')
if os.path.isfile(frame):
os.remove(frame)
command = ['ffmpeg', '-i', video]
if viewport_time:
command.extend(['-ss', viewport_time])
command.extend(['-frames:v', '1', frame])
subprocess.check_output(command)
if os.path.isfile(frame):
with Image.open(frame) as im:
width, height = im.size
logging.debug('%s is %dx%d', frame, width, height)
if options.notification:
im = None
try:
im = Image.open(frame)
pixels = im.load()
middle = int(math.floor(height / 2))
# Find the top edge (at ~40% in to deal with browsers that
# color the notification area)
x = int(width * 0.4)
y = 0
background = pixels[x, y]
top = None
while top is None and y < middle:
if not colors_are_similar(background, pixels[x, y]):
top = y
else:
y += 1
if top is None:
top = 0
logging.debug('Window top edge is {0:d}'.format(top))
# Find the bottom edge
x = 0
y = height - 1
bottom = None
while bottom is None and y > middle:
if not colors_are_similar(background, pixels[x, y]):
bottom = y
else:
y -= 1
if bottom is None:
bottom = height - 1
logging.debug('Window bottom edge is {0:d}'.format(bottom))
viewport = {
'x': 0,
'y': top,
'width': width,
'height': (
bottom -
top)}
except Exception:
logging.exception('Error finding vieport pixels')
if im is not None:
try:
im.close()
except Exception:
pass
elif find_viewport:
viewport = find_image_viewport(frame)
else:
viewport = {'x': 0, 'y': 0, 'width': width, 'height': height}
os.remove(frame)
except Exception:
logging.exception('Error finding viewport')
viewport = None
return viewport
def trim_video_end(directory, trim_time):
if trim_time > 0:
logging.debug(
"Trimming " +
str(trim_time) +
"ms from the end of the video in " +
directory)
frames = sorted(glob.glob(os.path.join(directory, 'video-*.png')))
if len(frames):
match = re.compile(r'video-(?P<ms>[0-9]+)\.png')
m = re.search(match, frames[-1])
if m is not None:
frame_time = int(m.groupdict().get('ms'))
end_time = frame_time - trim_time
logging.debug("Trimming frames before " + str(end_time) + "ms")
for frame in frames:
m = re.search(match, frame)
if m is not None:
frame_time = int(m.groupdict().get('ms'))
if frame_time > end_time:
logging.debug("Trimming frame " + frame)
os.remove(frame)
def adjust_frame_times(directory):
offset = None
frames = sorted(glob.glob(os.path.join(directory, 'video-*.png')))
if len(frames):
match = re.compile(r'video-(?P<ms>[0-9]+)\.png')
for frame in frames:
m = re.search(match, frame)
if m is not None:
frame_time = int(m.groupdict().get('ms'))
if offset is None:
offset = frame_time
new_time = frame_time - offset
dest = os.path.join(
directory, 'ms_{0:06d}.png'.format(new_time))
os.rename(frame, dest)
def find_first_frame(directory, white_file):
logging.debug("Finding First Frame...")
try:
if options.startwhite:
files = sorted(glob.glob(os.path.join(directory, 'video-*.png')))
count = len(files)
if count > 1:
from PIL import Image
for i in range(count):
if is_white_frame(files[i], white_file):
break
else:
logging.debug(
'Removing non-white frame {0} from the beginning'.format(files[i]))
os.remove(files[i])
elif options.findstart > 0 and options.findstart <= 100:
files = sorted(glob.glob(os.path.join(directory, 'video-*.png')))
count = len(files)
if count > 1:
from PIL import Image
blank = files[0]
with Image.open(blank) as im:
width, height = im.size
match_height = int(
math.ceil(
height *
options.findstart /
100.0))
crop = '{0:d}x{1:d}+{2:d}+{3:d}'.format(
width, match_height, 0, 0)
found_first_change = False
found_white_frame = False
found_non_white_frame = False
first_frame = None
if white_file is None:
found_white_frame = True
for i in range(count):
if not found_first_change:
different = not frames_match(
files[i], files[i + 1], 5, 100, crop, None)
logging.debug('Removing early frame %s from the beginning', files[i])
os.remove(files[i])
if different:
first_frame = files[i + 1]
found_first_change = True
elif not found_white_frame:
if files[i] != first_frame:
if found_non_white_frame:
found_white_frame = is_white_frame(
files[i], white_file)
if not found_white_frame:
logging.debug(
'Removing early non-white frame {0} from the beginning'.format(files[i]))
os.remove(files[i])
else:
found_non_white_frame = not is_white_frame(
files[i], white_file)
logging.debug(
'Removing early pre-non-white frame {0} from the beginning'.format(files[i]))
os.remove(files[i])
if found_first_change and found_white_frame:
break
except BaseException:
logging.exception('Error finding first frame')
def find_last_frame(directory, white_file):
logging.debug("Finding Last Frame...")
try:
if options.endwhite:
files = sorted(glob.glob(os.path.join(directory, 'video-*.png')))
count = len(files)
if count > 2:
found_end = False
from PIL import Image
for i in range(2, count):
if found_end:
logging.debug(
'Removing frame {0} from the end'.format(
files[i]))
os.remove(files[i])
if is_white_frame(files[i], white_file):
found_end = True
logging.debug(
'Removing ending white frame {0}'.format(
files[i]))
os.remove(files[i])
except BaseException:
logging.exception('Error finding last frame')
def find_render_start(directory, orange_file, gray_file):
logging.debug("Finding Render Start...")
try:
if client_viewport is not None or options.viewport is not None or (
options.renderignore > 0 and options.renderignore <= 100):
files = sorted(glob.glob(os.path.join(directory, 'video-*.png')))
count = len(files)
if count > 1:
from PIL import Image
first = files[0]
with Image.open(first) as im:
width, height = im.size
if options.renderignore > 0 and options.renderignore <= 100:
mask = {}
mask['width'] = int(
math.floor(
width *
options.renderignore /
100))
mask['height'] = int(
math.floor(
height *
options.renderignore /
100))
mask['x'] = int(math.floor(width / 2 - mask['width'] / 2))
mask['y'] = int(
math.floor(
height /
2 -
mask['height'] /
2))
else:
mask = None
top = 10
right_margin = 10
bottom_margin = 10
if height > 400 or width > 400:
right_margin = 25
bottom_margin = 25
top = int(math.ceil(float(height) * 0.03))
right_margin = max(right_margin, int(math.ceil(float(width) * 0.04)))
bottom_margin = max(bottom_margin, int(math.ceil(float(height) * 0.04)))
height = max(height - top - bottom_margin, 1)
left = 0
width = max(width - right_margin, 1)
if client_viewport is not None:
height = max(
client_viewport['height'] - top - bottom_margin, 1)
width = max(client_viewport['width'] - right_margin, 1)
left += client_viewport['x']
top += client_viewport['y']
crop = '{0:d}x{1:d}+{2:d}+{3:d}'.format(
width, height, left, top)
for i in range(1, count):
if frames_match(first, files[i], 10, 0, crop, mask):
logging.debug('Removing pre-render frame %s', files[i])
os.remove(files[i])
elif orange_file is not None and is_color_frame(files[i], orange_file):
logging.debug('Removing orange frame %s', files[i])
os.remove(files[i])
elif gray_file is not None and is_color_frame(files[i], gray_file):
logging.debug('Removing gray frame %s', files[i])
os.remove(files[i])
else:
break
except BaseException:
logging.exception('Error getting render start')
def eliminate_duplicate_frames(directory):
logging.debug("Eliminating Duplicate Frames...")
global client_viewport
try:
files = sorted(glob.glob(os.path.join(directory, 'ms_*.png')))
if len(files) > 1:
from PIL import Image
blank = files[0]
with Image.open(blank) as im:
width, height = im.size
if options.viewport and options.notification:
if client_viewport['width'] == width and client_viewport['height'] == height:
client_viewport = None
# Figure out the region of the image that we care about
top = 8
right_margin = 8
bottom_margin = 20
if height > 400 or width > 400:
top = int(math.ceil(float(height) * 0.04))
right_margin = int(math.ceil(float(width) * 0.04))
bottom_margin = int(math.ceil(float(width) * 0.04))
height = max(height - top - bottom_margin, 1)
left = 0
width = max(width - right_margin, 1)
if client_viewport is not None:
height = max(
client_viewport['height'] -
top -
bottom_margin,
1)
width = max(client_viewport['width'] - right_margin, 1)
left += client_viewport['x']
top += client_viewport['y']
crop = '{0:d}x{1:d}+{2:d}+{3:d}'.format(width, height, left, top)
logging.debug('Viewport cropping set to ' + crop)
# Do a pass looking for the first non-blank frame with an allowance
# for up to a 10% per-pixel difference for noise in the white
# field.
count = len(files)
for i in range(1, count):
if frames_match(blank, files[i], 10, 0, crop, None):
logging.debug(
'Removing duplicate frame {0} from the beginning'.format(
files[i]))
os.remove(files[i])
else:
break
# Do another pass looking for the last frame but with an allowance for up
# to a 10% difference in individual pixels to deal with noise
# around text.
files = sorted(glob.glob(os.path.join(directory, 'ms_*.png')))
count = len(files)
duplicates = []
if count > 2:
files.reverse()
baseline = files[0]
previous_frame = baseline
for i in range(1, count):
if frames_match(baseline, files[i], 10, 0, crop, None):
if previous_frame is baseline:
duplicates.append(previous_frame)
else:
logging.debug(
'Removing duplicate frame {0} from the end'.format(previous_frame))
os.remove(previous_frame)
previous_frame = files[i]
else:
break
for duplicate in duplicates:
logging.debug(
'Removing duplicate frame {0} from the end'.format(duplicate))
os.remove(duplicate)
except BaseException:
logging.exception('Error processing frames for duplicates')
def eliminate_similar_frames(directory):
logging.debug("Removing Similar Frames...")
try:
# only do this when decimate couldn't be used to eliminate similar
# frames
if options.notification:
files = sorted(glob.glob(os.path.join(directory, 'ms_*.png')))
count = len(files)
if count > 3:
crop = None
if client_viewport is not None:
crop = '{0:d}x{1:d}+{2:d}+{3:d}'.format(client_viewport['width'], client_viewport['height'],
client_viewport['x'], client_viewport['y'])
baseline = files[1]
for i in range(2, count - 1):
if frames_match(baseline, files[i], 1, 0, crop, None):
logging.debug(
'Removing similar frame {0}'.format(
files[i]))
os.remove(files[i])
else:
baseline = files[i]
except BaseException:
logging.exception('Error removing similar frames')
def blank_first_frame(directory):
try:
if options.forceblank:
files = sorted(glob.glob(os.path.join(directory, 'video-*.png')))
count = len(files)
if count > 1:
from PIL import Image
with Image.open(files[0]) as im:
width, height = im.size
command = '{0} -size {1}x{2} xc:white PNG24:"{3}"'.format(
image_magick['convert'], width, height, files[0])
subprocess.call(command, shell=True)
except BaseException:
logging.exception('Error blanking first frame')
def crop_viewport(directory):
if client_viewport is not None:
try:
files = sorted(glob.glob(os.path.join(directory, 'ms_*.png')))
count = len(files)
if count > 0:
crop = '{0:d}x{1:d}+{2:d}+{3:d}'.format(client_viewport['width'], client_viewport['height'],
client_viewport['x'], client_viewport['y'])
for i in range(count):
command = '{0} "{1}" -crop {2} "{1}"'.format(
image_magick['convert'], files[i], crop)
subprocess.call(command, shell=True)
except BaseException:
logging.exception('Error cropping to viewport')
def get_decimate_filter():
decimate = None
try:
if (sys.version_info > (3, 0)):
filters = subprocess.check_output(['ffmpeg', '-filters'], stderr=subprocess.STDOUT, encoding='UTF-8')
else:
filters = subprocess.check_output(['ffmpeg', '-filters'], stderr=subprocess.STDOUT)
lines = filters.split("\n")
match = re.compile(
r'(?P<filter>[\w]*decimate).*V->V.*Remove near-duplicate frames')
for line in lines:
m = re.search(match, line)
if m is not None:
decimate = m.groupdict().get('filter')
break
except BaseException:
logging.exception('Error checking ffmpeg filters for decimate')
decimate = None
return decimate
def clean_directory(directory):
files = glob.glob(os.path.join(directory, '*.png'))
for file in files:
os.remove(file)
files = glob.glob(os.path.join(directory, '*.jpg'))
for file in files:
os.remove(file)
files = glob.glob(os.path.join(directory, '*.json'))
for file in files:
os.remove(file)
def is_color_frame(file, color_file):
"""Check a section from the middle, top and bottom of the viewport to see if it matches"""
global frame_cache
if file in frame_cache and color_file in frame_cache[file]:
return bool(frame_cache[file][color_file])
match = False
if os.path.isfile(color_file):
try:
from PIL import Image
with Image.open(file) as img:
width, height = img.size
crops = []
# Middle
crops.append('{0:d}x{1:d}+{2:d}+{3:d}'.format(
int(width / 2), int(height / 3),
int(width / 4), int(height / 3)))
# Top
crops.append('{0:d}x{1:d}+{2:d}+{3:d}'.format(
int(width / 2), int(height / 5),
int(width / 4), 50))
# Bottom
crops.append('{0:d}x{1:d}+{2:d}+{3:d}'.format(
int(width / 2), int(height / 5),
int(width / 4), height - int(height / 5) - 50))
for crop in crops:
command = ('{0} "{1}" "(" "{2}" -crop {3} -resize 200x200! ")"'
' miff:- | {4} -metric AE - -fuzz 15% null:'
).format(image_magick['convert'], color_file, file, crop,
image_magick['compare'])
compare = subprocess.Popen(command, stderr=subprocess.PIPE, shell=True, universal_newlines=True)
_, err = compare.communicate()
if re.match('^[0-9]+$', err):
different_pixels = int(err)
if different_pixels < 100:
match = True
break
except Exception:
logging.exception('Error checking frame color')
if file not in frame_cache:
frame_cache[file] = {}
frame_cache[file][color_file] = bool(match)
return match
def is_white_frame(file, white_file):
white = False
if os.path.isfile(white_file):
if options.viewport:
command = ('{0} "{1}" "(" "{2}" -resize 200x200! ")" miff:- | '
'{3} -metric AE - -fuzz 10% null:').format(
image_magick['convert'], white_file, file, image_magick['compare'])
else:
command = ('{0} "{1}" "(" "{2}" -gravity Center -crop 50%x33%+0+0 -resize 200x200! ")" miff:- | '
'{3} -metric AE - -fuzz 10% null:').format(
image_magick['convert'], white_file, file, image_magick['compare'])
if client_viewport is not None:
crop = '{0:d}x{1:d}+{2:d}+{3:d}'.format(
client_viewport['width'],
client_viewport['height'],
client_viewport['x'],
client_viewport['y'])
command = ('{0} "{1}" "(" "{2}" -crop {3} -resize 200x200! ")" miff:- | '
'{4} -metric AE - -fuzz 10% null:').format(
image_magick['convert'], white_file, file, crop, image_magick['compare'])
compare = subprocess.Popen(command, stderr=subprocess.PIPE, shell=True)
out, err = compare.communicate()
if re.match('^[0-9]+$', err):
different_pixels = int(err)
if different_pixels < 500:
white = True
return white
def colors_are_similar(a, b, threshold=15):
similar = True
sum = 0
for x in range(3):
delta = abs(a[x] - b[x])
sum += delta
if delta > threshold:
similar = False
if sum > threshold:
similar = False
return similar
def frames_match(image1, image2, fuzz_percent,
max_differences, crop_region, mask_rect):
match = False
fuzz = ''
if fuzz_percent > 0:
fuzz = '-fuzz {0:d}% '.format(fuzz_percent)
crop = ''
if crop_region is not None:
crop = '-crop {0} '.format(crop_region)
if mask_rect is None:
img1 = '"{0}"'.format(image1)
img2 = '"{0}"'.format(image2)
else:
img1 = '( "{0}" -size {1}x{2} xc:white -geometry +{3}+{4} -compose over -composite )'.format(
image1, mask_rect['width'], mask_rect['height'], mask_rect['x'], mask_rect['y'])
img2 = '( "{0}" -size {1}x{2} xc:white -geometry +{3}+{4} -compose over -composite )'.format(
image2, mask_rect['width'], mask_rect['height'], mask_rect['x'], mask_rect['y'])
command = '{0} {1} {2} {3}miff:- | {4} -metric AE - {5}null:'.format(
image_magick['convert'], img1, img2, crop, image_magick['compare'], fuzz)
if platform.system() != 'Windows':
command = command.replace('(', '\\(').replace(')', '\\)')
compare = subprocess.Popen(command, stderr=subprocess.PIPE, shell=True)
out, err = compare.communicate()
if re.match('^[0-9]+$', err):
different_pixels = int(err)
if different_pixels <= max_differences:
match = True
else:
logging.debug(
'Unexpected compare result: out: "{0}", err: "{1}"'.format(
out, err))
return match
def generate_orange_png(orange_file):
try:
from PIL import Image, ImageDraw
im = Image.new('RGB', (200, 200))
draw = ImageDraw.Draw(im)
draw.rectangle([0, 0, 200, 200], fill=(222, 100, 13))
del draw
im.save(orange_file, 'PNG')
except BaseException:
logging.exception('Error generating orange png ' + orange_file)
def generate_gray_png(gray_file):
try:
from PIL import Image, ImageDraw
im = Image.new('RGB', (200, 200))
draw = ImageDraw.Draw(im)
draw.rectangle([0, 0, 200, 200], fill=(128, 128, 128))
del draw
im.save(gray_file, 'PNG')
except BaseException:
logging.exception('Error generating gray png ' + gray_file)
def generate_white_png(white_file):
try:
from PIL import Image, ImageDraw
im = Image.new('RGB', (200, 200))
draw = ImageDraw.Draw(im)
draw.rectangle([0, 0, 200, 200], fill=(255, 255, 255))
del draw
im.save(white_file, 'PNG')
except BaseException:
logging.exception('Error generating white png ' + white_file)
def synchronize_to_timeline(directory, timeline_file):
offset = get_timeline_offset(timeline_file)
if offset > 0:
frames = sorted(glob.glob(os.path.join(directory, 'ms_*.png')))
match = re.compile(r'ms_(?P<ms>[0-9]+)\.png')
for frame in frames:
m = re.search(match, frame)
if m is not None:
frame_time = int(m.groupdict().get('ms'))
new_time = max(frame_time - offset, 0)
dest = os.path.join(
directory, 'ms_{0:06d}.png'.format(new_time))
if frame != dest:
if os.path.isfile(dest):
os.remove(dest)
os.rename(frame, dest)
def get_timeline_offset(timeline_file):
offset = 0
try:
file_name, ext = os.path.splitext(timeline_file)
if ext.lower() == '.gz':
f = gzip.open(timeline_file, GZIP_READ_TEXT)
else:
f = open(timeline_file, 'r')
timeline = json.load(f)
f.close()
last_paint = None
first_navigate = None
# In the case of a trace instead of a timeline we want the list of
# events
if 'traceEvents' in timeline:
timeline = timeline['traceEvents']
for timeline_event in timeline:
paint_time = get_timeline_event_paint_time(timeline_event)
if paint_time is not None:
last_paint = paint_time
first_navigate = get_timeline_event_navigate_time(timeline_event)
if first_navigate is not None:
break
if last_paint is not None and first_navigate is not None and first_navigate > last_paint:
offset = int(round(first_navigate - last_paint))
logging.info(
"Trimming {0:d}ms from the start of the video based on timeline synchronization".format(offset))
except BaseException:
logging.exception("Error processing timeline file " + timeline_file)
return offset
def get_timeline_event_paint_time(timeline_event):