-
-
Notifications
You must be signed in to change notification settings - Fork 136
/
Copy pathvisualmetrics-portable.py
executable file
·2097 lines (1809 loc) · 70.8 KB
/
visualmetrics-portable.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 python3
"""
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."""
#
# The original script from Google was heavily modified for the Browsertime
# project.
#
import gc
import glob
import gzip
import json
import logging
import math
import os
import re
import sys
import shutil
import subprocess
import tempfile
GZIP_TEXT = "wt"
GZIP_READ_TEXT = "rt"
# Globals
options = None
client_viewport = None
frame_cache = {}
# #################################################################################################
# Replacement methods for ImageMagick to Python conversion
# #################################################################################################
def compare(img1, img2, fuzz=0.10):
"""Calculate the Absolute Error count between given images."""
try:
import numpy as np
img1_data = np.array(img1)
img2_data = np.array(img2)
inds = np.argwhere(
np.isclose(img1_data[:, :, 0], img2_data[:, :, 0], atol=fuzz * 255)
& np.isclose(img1_data[:, :, 1], img2_data[:, :, 1], atol=fuzz * 255)
& np.isclose(img1_data[:, :, 2], img2_data[:, :, 2], atol=fuzz * 255)
)
return (img1_data.shape[0] * img1_data.shape[1]) - len(inds)
except BaseException as e:
logging.exception(e)
return None
def crop_im(img, crop_x, crop_y, crop_x_offset, crop_y_offset, gravity=None):
"""Crop an image.
If gravity is equal to "center", the crop region will
first be centered before applying the crop.
"""
try:
import numpy as np
from PIL import Image
img = np.array(img)
base_x = 0
base_y = 0
height, width, _ = img.shape
if gravity == "center":
base_x = width // 2
base_y = height // 2
base_x -= crop_x // 2
base_y -= crop_y // 2
# Handle the boundaries of the crop using max to prevent
# negatives, and min to prevent going over the othersde of
# the image
start_x = min(width - 1, max(base_x + crop_x_offset, 0))
start_y = min(height - 1, max(base_y + crop_y_offset, 0))
end_x = min(width - 1, max(start_x + crop_x, 0))
end_y = min(height - 1, max(start_y + crop_y, 0))
if len(img[start_y:end_y, start_x:end_x, :]) == 0:
raise Exception(
f"Cropped image is empty. Image dimensions: {img.shape}, "
f"Crop Region: {crop_x}, {crop_y}, {crop_x_offset}, {crop_y_offset}"
)
return Image.fromarray(img[start_y:end_y, start_x:end_x, :])
except BaseException as e:
logging.exception(e)
return None
def resize(img, width, height):
"""Resize an image to the given width, and height."""
try:
from PIL import Image
try:
# If it's a numpy array, convert it first
img = Image.fromarray(img)
except:
pass
return img.resize((width, height), resample=Image.LANCZOS)
except BaseException as e:
logging.exception(e)
return None
def scale(img, maxsize):
"""Scale an image to the given max size."""
width, height = img.size
ratio = min(float(maxsize) / width, float(maxsize) / height)
return resize(img, int(width * ratio), int(height * ratio))
def mask(
img, x_mask, y_mask, x_offset, y_offset, color=(255, 255, 255), insert_img=None
):
"""Mask an image.
If insert_img is provided, the image given will mask the region
specified. Otherwise, by default, the region specified will be covered
in white - change color to change the mask color.
"""
try:
import numpy as np
from PIL import Image
img_data = np.array(img)
if insert_img is not None:
insert_img_data = np.array(insert_img)
img_data[
y_offset : y_offset + y_mask, x_offset : x_offset + x_mask, :
] = insert_img
else:
img_data[
y_offset : y_offset + y_mask, x_offset : x_offset + x_mask, :
] = color
return Image.fromarray(img_data)
except BaseException as e:
logging.exception(e)
return None
def blank_frame(file, color="white"):
"""Return a new blank frame that has the same dimensions as file."""
try:
from PIL import Image
with Image.open(file) as im:
width, height = im.size
return Image.new("RGB", (width, height), color=color)
except BaseException as e:
logging.exception(e)
return None
def edges_im(img):
"""Find the edges of the given image.
First, we apply a gaussian filter using a kernal of radius=13,
and sigma=1 to a grayscale version of the image. Then we apply
CED to find the edges.
We calculate the hysterisis thresholds for the CED using the min and max
vaues of the blurred image. We use 10% as the lower threshold,
and 30% as the upper threshold.
"""
try:
import cv2
import numpy as np
from PIL import Image, ImageOps
gs_img = np.array(ImageOps.grayscale(img))
blurred_img = cv2.GaussianBlur(gs_img, (13, 13), 1)
# Calculate the threshold values for double-thresholding
min_g = np.min(blurred_img[:])
max_g = np.max(blurred_img[:])
edge_img = cv2.Canny(
blurred_img, 0.10 * (max_g - min_g) + min_g, 0.30 * (max_g - min_g) + min_g
)
return Image.fromarray(edge_img)
except BaseException as e:
logging.exception(e)
return None
def contentful_value(img):
"""
Get the contentful value by counting the number of
defined pixels in the image of the edges.
"""
try:
import numpy as np
edge_img = np.array(edges_im(img))
white_pixels = np.where(edge_img != 0)
return len(white_pixels[0])
except BaseException as e:
logging.exception(e)
return None
def build_edge_video(video_path, viewport):
"""Compute, and highlight the edges of a given video.
Makes use of the same technique as the contentful value
calculation. However, it crops, and scales the image using
our own method rather than FFMPEG. This creates two videos
suffixed with `-edges` and `-edges-overlay` that contain
the raw edges, and a video with the edges overlaid. They will
be found in the same location as the original video.
These videos will only be produced when --contentful-video is
used.
"""
logging.debug("Creating edge video for {0}".format(video_path))
output_dir, video_name = os.path.split(video_path)
video_name, _ = os.path.splitext(video_name)
try:
import cv2
import numpy as np
from PIL import Image, ImageOps
# Get the edges of all frames
edge_video = []
resized_video = []
video = cv2.VideoCapture(video_path)
frame_count = video.get(cv2.CAP_PROP_FPS)
while video.isOpened():
ret, frame = video.read()
if ret:
cropped_im = frame
if viewport:
cropped_im = crop_im(
frame,
viewport["width"],
viewport["height"],
viewport["x"],
viewport["y"],
)
resized_video.append(scale(cropped_im, options.thumbsize))
edge_video.append(np.array(edges_im(resized_video[-1])))
else:
video.release()
break
out_size = edge_video[-1].shape
out_edges = cv2.VideoWriter(
os.path.join(output_dir, video_name + "-edges.mp4"),
cv2.VideoWriter_fourcc(*"MP4V"),
frame_count,
(out_size[1], out_size[0]),
1,
)
out_edges_overlay = cv2.VideoWriter(
os.path.join(output_dir, video_name + "-edges-overlay.mp4"),
cv2.VideoWriter_fourcc(*"MP4V"),
frame_count,
(out_size[1], out_size[0]),
1,
)
for i, frame in enumerate(edge_video):
cframe = np.zeros((out_size[0], out_size[1], 3))
overlayframe = np.array(resized_video[i])
for x in range(cframe.shape[0]):
for y in range(cframe.shape[1]):
if frame[x, y] != 0:
cframe[x, y, :] = (0, 0, 255)
overlayframe[x, y, :] = (0, 0, 255)
out_edges.write(np.uint8(cframe))
out_edges_overlay.write(np.uint8(overlayframe))
out_edges.release()
out_edges_overlay.release()
logging.debug("Finished creating edge videos for {0}".format(video_path))
except BaseException as e:
logging.exception(e)
return
def convert_to_srgb(img):
"""Convert PIL image to sRGB color space (if possible)"""
try:
import io
from PIL import Image, ImageCms
icc = img.info.get("icc_profile", "")
if icc:
return ImageCms.profileToProfile(
img,
ImageCms.ImageCmsProfile(io.BytesIO(icc)),
ImageCms.createProfile("sRGB"),
)
logging.debug(
"Unable to convert image to sRGB as there is no color "
"profile to transform from."
)
return img
except BaseException as e:
logging.exception(e)
return None
def convert_img_to_jpeg(src, dest, quality=30):
"""Convert an image to a JPEG with the given quality."""
try:
from PIL import Image
with Image.open(src) as img:
img = convert_to_srgb(img)
img.save(dest, quality=quality)
except BaseException as e:
logging.exception(e)
return
# #################################################################################################
# Frame Extraction and de-duplication
# #################################################################################################
def video_to_frames(
video,
directory,
force,
orange_file,
find_viewport,
viewport_retries,
viewport_min_height,
viewport_min_width,
full_resolution,
):
"""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)
is_mobile = find_recording_platform(video)
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, cropped = find_video_viewport(
video,
directory,
find_viewport,
viewport_retries,
viewport_min_height,
viewport_min_width,
is_mobile,
)
if options.contentful_video:
# Create some videos with the edges
build_edge_video(video, viewport)
gc.collect()
if extract_frames(video, directory, full_resolution, viewport):
client_viewport = None
directories = [directory]
for dir in directories:
if orange_file is not None:
remove_frames_before_orange(dir, orange_file)
remove_orange_frames(dir, orange_file)
find_render_start(dir, orange_file, cropped, is_mobile)
adjust_frame_times(dir)
eliminate_duplicate_frames(dir, cropped, is_mobile)
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, encoding="UTF-8")
while proc.poll() is None:
lines.extend(iter(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.floor(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 find_recording_platform(video):
"""Find the platform that this video was recorded on.
We can make use of a field called `com.android.version` to
determine if we've recorded on mobile or not.
"""
command = ["ffprobe", video]
logging.debug(command)
lines = []
proc = subprocess.Popen(command, stderr=subprocess.PIPE, encoding="UTF-8")
while proc.poll() is None:
lines.extend(iter(proc.stderr.readline, ""))
is_mobile = False
matcher = re.compile(".*com\.android\.version.*")
for line in lines:
if matcher.search(line):
is_mobile = True
return is_mobile
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, is_mobile):
logging.debug("Finding the viewport for %s", file)
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),
}
if is_mobile:
# On mobile we need to ignore the top ~10 pixels because
# there is a visible progress bar there on some browsers.
viewport["y"] += 10
viewport["height"] -= 14
except Exception:
viewport = None
return viewport
def find_video_viewport(
video,
directory,
find_viewport,
viewport_retries,
viewport_min_height,
viewport_min_width,
is_mobile,
):
logging.debug("Finding Video Viewport...")
viewport = None
# cropped will be True if the viewport setting changes
# the original frame
cropped = False
try:
from PIL import Image
retries = -1
while (
viewport is None
or viewport["height"] <= viewport_min_height
or viewport["width"] <= viewport_min_width
):
retries += 1
if retries >= 1:
# In some cases, the first frame is not an orange screen or a screen
# with a solid color. In this case, we need to try finding the viewport
# using the next frame. The `viewport_retries` dictates the maximum number
# of frames to check.
if retries >= viewport_retries:
logging.exception(
"Could not calculate a viewport after %s tries.",
viewport_retries,
)
break
logging.info("Failed to find a good viewport. Retrying...")
logging.debug("Using frame " + str(retries))
frame = os.path.join(directory, "viewport.png")
if os.path.isfile(frame):
os.remove(frame)
command = ["ffmpeg", "-i", video]
# Pull one frame from the video starting with the frame at
# the `retries` index
command.extend(["-vf", "select=gte(n\\,%s)" % retries])
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 find_viewport:
viewport = find_image_viewport(frame, is_mobile)
else:
viewport = {"x": 0, "y": 0, "width": width, "height": height}
os.remove(frame)
if viewport is not None and viewport != {
"x": 0,
"y": 0,
"width": width,
"height": height,
}:
cropped = True
except Exception as e:
viewport = None
return viewport, cropped
def adjust_frame_times(directory):
offset = None
frames = sorted(glob.glob(os.path.join(directory, "video-*.png")))
# Special hack to the the video start
# Let us tune this in the future to skip using a global
global videoRecordingStart
match = re.compile(r"video-(?P<ms>[0-9]+)\.png")
if len(frames):
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:
# This is the first frame.
videoRecordingStart = frame_time
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_render_start(directory, orange_file, cropped, is_mobile):
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
im_width = width
im_height = height
top = 10
right_margin = 10
bottom_margin = 24
if height > 400 or width > 400:
top = max(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(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"]
elif cropped:
# The image was already cropped, so only cutout the bottom
# to get rid of the network request/etc. information for
# desktop videos, and nothing extra on mobile.
top = 0
left = 0
width = im_width
if is_mobile:
height = im_height
else:
height = im_height - bottom_margin
crop = (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])
else:
break
except BaseException:
logging.exception("Error getting render start")
def eliminate_duplicate_frames(directory, cropped, is_mobile):
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
im_width = width
im_height = height
# Figure out the region of the image that we care about
top = 40
right_margin = 10
bottom_margin = 10
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.06))
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"]
elif cropped:
# The image was already cropped, so only cutout the bottom
# to get rid of the network request/etc. information for
# desktop videos, and nothing extra on mobile.
top = 0
left = 0
width = im_width
if is_mobile:
height = im_height
else:
height = im_height - bottom_margin
crop = (width, height, left, top)
logging.debug("Viewport cropping set to (W, H, L, T): " + str(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 15% 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], 15, 5, 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 crop_viewport(directory):
if client_viewport is not None:
try:
from PIL import Image
files = sorted(glob.glob(os.path.join(directory, "ms_*.png")))
count = len(files)
if count > 0:
for i in range(count):
with Image.open(files[i]) as im:
new_img = crop_im(
im,
client_viewport["width"],
client_viewport["height"],
client_viewport["x"],
client_viewport["y"],
)
new_img.save(files[i])
except BaseException:
logging.exception("Error cropping to viewport")
def get_decimate_filter():
decimate = None
try:
filters = subprocess.check_output(
["ffmpeg", "-filters"], stderr=subprocess.STDOUT, encoding="UTF-8"
)
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.critical("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(
(int(width / 2), int(height / 3), int(width / 4), int(height / 3))
)
# Top
crops.append((int(width / 2), int(height / 5), int(width / 4), 50))
# Bottom
crops.append(
(
int(width / 2),
int(height / 5),
int(width / 4),
height - int(height / 5),
)
)
for crop in crops:
with Image.open(file) as im:
crop_i = crop_im(im, crop[0], crop[1], crop[2], crop[3])
resized_im = resize(crop_i, 200, 200)
with Image.open(color_file) as color_im:
different_pixels = compare(resized_im, color_im, fuzz=0.15)