-
Notifications
You must be signed in to change notification settings - Fork 4
/
video_remixer_processor.py
3126 lines (2665 loc) · 144 KB
/
video_remixer_processor.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
"""Video Remixer Content Processing"""
import os
import math
from random import randint
import shutil
from typing import Callable, TYPE_CHECKING
import cv2
import numpy as np
from webui_utils.file_utils import split_filepath, create_directory, get_directories, get_files,\
remove_directories, copy_files, simple_sanitize_filename, move_files
from webui_utils.video_utils import details_from_group_name, PNGtoMP4, combine_video_audio,\
combine_videos, PNGtoCustom, image_size
from webui_utils.simple_utils import dummy_args
from webui_utils.mtqdm import Mtqdm
from slice_video import SliceVideo
from resize_frames import ResizeFrames
from interpolate import Interpolate
from deep_interpolate import DeepInterpolate
from interpolate_series import InterpolateSeries
from resequence_files import ResequenceFiles
from upscale_series import UpscaleSeries
if TYPE_CHECKING:
from video_remixer import VideoRemixerState
class VideoRemixerProcessor():
def __init__(self, state : "VideoRemixerState", engine : any, engine_settings : dict,
realesrgan_settings : dict, global_options : dict, log_fn : Callable):
self.state = state
self.engine = engine
self.engine_settings = engine_settings
self.realesrgan_settings = realesrgan_settings
self.global_options = global_options
self.log_fn = log_fn
self.saved_view = self.DEFAULT_VIEW
self.processing_messages = []
self.processing_messages_context = {}
self.saved_lens_hint = self.DEFAULT_LENS_HINT
self.noise_dampening = None
self.sticky_block_hints = []
self.block_animation_contexts = {}
def log(self, message):
if self.log_fn:
self.log_fn(message)
QUADRANT_ZOOM_HINT = "/"
QUADRANT_GRID_CHAR = "X"
PERCENT_ZOOM_HINT = "%"
COMBINED_ZOOM_HINT = "@"
ANIMATED_ZOOM_HINT = "-"
ANIMATION_TIME_HINT = "#"
ANIMATION_TIME_SEP = "~"
ANIMATION_SCHEDULE_HINT = "$"
QUADRATIC_SCHEDULE = "Q"
BEZIER_SCHEDULE = "B"
PARAMETRIC_SCHEDULE = "P"
LINEAR_SCHEDULE = "L"
LENS_SCHEDULE = "Z"
QUADRANT_ZOOM_MIN_LEN = 3 # 1/3
PERCENT_ZOOM_MIN_LEN = 4 # 123%
COMBINED_ZOOM_MIN_LEN = 8 # 1/1@100%
ANIMATED_ZOOM_MIN_LEN = 1 # -
ANIMATED_FADE_MIN_LEN = 1 # I
ANIMATED_BLOCK_MIN_LEN = 5 # 1X-8X
ANIMATED_LENS_MIN_LEN = 1 # -
MAX_SELF_FIT_ZOOM = 1000
FIXED_UPSCALE_FACTOR = 4.0
TEMP_UPSCALE_PATH = "upscaled_frames"
DEFAULT_DOWNSCALE_TYPE = "area"
DEFAULT_VIEW = "100%"
DEFAULT_ANIMATION_SCHEDULE = "L" # linear
DEFAULT_ANIMATION_TIME = 0 # whole scene
FADE_TYPE_IN = "I"
FADE_TYPE_OUT = "O"
STICKY_HINT = "!"
BLOCK_TYPE_BLACK = "K"
BLOCK_TYPE_WHITE = "W"
BLOCK_TYPE_NOISE = "N"
BLOCK_TYPE_STATIC = "S"
BLOCK_TYPE_PIXELATED = "X"
# BLOCK_TYPE_SCRAMBLE = "R"
# DEFAULT_BLOCK_TYPE = BLOCK_TYPE_PIXELATED
# DEFAULT_BLOCK_PARAM = "1/1"
BLOCK_TYPES = [BLOCK_TYPE_BLACK, BLOCK_TYPE_WHITE, BLOCK_TYPE_NOISE, BLOCK_TYPE_STATIC, BLOCK_TYPE_PIXELATED, STICKY_HINT]
DEFAULT_BLOCK_FACTOR = 32
BLOCK_VALUE_BLACK = 0 #16 # NTSC standard
BLOCK_VALUE_WHITE = 255 #235
LENS_TYPE_UNDISTORT = "U"
LENS_TYPE_DISTORT = "D"
LENS_TYPES = [LENS_TYPE_UNDISTORT, LENS_TYPE_DISTORT]
LENS_MIN_UNDISTORT = -1000.0
LENS_MAX_UNDISTORT = 1000.0
DEFAULT_LENS_HINT = "0D"
NO_ACTION_HINT = "N"
DEFAULT_BLOCK_VIEW = "100%"
### Exports --------------------
def prepare_process_remix(self, redo_resynth, redo_inflate, redo_upscale):
self.state.setup_processing_paths()
self.state.recompile_scenes()
if self.state.processed_content_invalid:
self.state.purge_processed_content(purge_from=self.state.RESIZE_STEP)
self.state.processed_content_invalid = False
else:
self.purge_stale_processed_content(redo_resynth, redo_inflate, redo_upscale)
self.purge_incomplete_processed_content()
self.reset_processing_messages()
self.state.save()
def process_remix(self, kept_scenes):
if self.resize_needed():
self.resize_scenes(kept_scenes)
if self.resynthesize_needed():
self.resynthesize_scenes(kept_scenes)
if self.inflate_needed():
self.inflate_scenes(kept_scenes)
if self.effects_needed():
self.effect_scenes(kept_scenes)
if self.upscale_needed():
self.upscale_scenes(kept_scenes)
def processed_content_complete(self, processing_step):
expected_items = len(self.state.kept_scenes())
if processing_step == self.state.RESIZE_STEP:
return self._processed_content_complete(self.state.resize_path, expected_dirs=expected_items)
elif processing_step == self.state.RESYNTH_STEP:
return self._processed_content_complete(self.state.resynthesis_path, expected_dirs=expected_items)
elif processing_step == self.state.INFLATE_STEP:
return self._processed_content_complete(self.state.inflation_path, expected_dirs=expected_items)
elif processing_step == self.state.EFFECTS_STEP:
return self._processed_content_complete(self.state.effects_path, expected_dirs=expected_items)
elif processing_step == self.state.UPSCALE_STEP:
return self._processed_content_complete(self.state.upscale_path, expected_dirs=expected_items)
elif processing_step == self.state.AUDIO_STEP:
return self._processed_content_complete(self.state.audio_clips_path, expected_files=expected_items)
elif processing_step == self.state.VIDEO_STEP:
return self._processed_content_complete(self.state.video_clips_path, expected_files=expected_items)
else:
raise RuntimeError(f"'processing_step' {processing_step} is unrecognized")
def prepare_save_remix(self, output_filepath : str, invalidate_video_clips=True):
if not output_filepath:
raise ValueError("Enter a path for the remixed video to proceed")
self.state.recompile_scenes()
kept_scenes = self.state.kept_scenes()
if not kept_scenes:
raise ValueError("No kept scenes were found")
self.drop_empty_processed_scenes(kept_scenes)
self.state.save()
# get this again in case scenes have been auto-dropped
kept_scenes = self.state.kept_scenes()
if not kept_scenes:
raise ValueError("No kept scenes after removing empties")
# create audio clips only if they do not already exist
# this depends on the audio clips being purged at the time the scene selection are compiled
if self.state.video_details["has_audio"] and not self.processed_content_complete(
self.state.AUDIO_STEP):
self.create_audio_clips()
self.state.save()
# leave video clips if they are complete since we may be only making audio changes
if invalidate_video_clips or not self.processed_content_complete(self.state.VIDEO_STEP):
self.state.clean_remix_content(purge_from="video_clips")
else:
# always recreate remix clips
self.state.clean_remix_content(purge_from="remix_clips")
return kept_scenes
def save_remix(self, kept_scenes):
# leave video clips if they are complete since we may be only making audio changes
if not self.processed_content_complete(self.state.VIDEO_STEP):
self.create_video_clips(kept_scenes)
self.state.save()
self.create_scene_clips(kept_scenes)
self.state.save()
if not self.state.clips:
raise ValueError("No processed video clips were found")
ffcmd = self.create_remix_video(self.state.output_filepath)
self.log(f"FFmpeg command: {ffcmd}")
self.state.save()
def save_custom_remix(self,
output_filepath,
kept_scenes,
custom_video_options,
custom_audio_options,
draw_text_options=None,
use_scene_sorting=True,
volume=0.0):
_, _, output_ext = split_filepath(output_filepath)
output_ext = output_ext[1:]
# leave video clips if they are complete since we may be only making audio changes
if not self.processed_content_complete(self.state.VIDEO_STEP):
self.create_custom_video_clips(kept_scenes, custom_video_options=custom_video_options,
custom_ext=output_ext,
draw_text_options=draw_text_options)
self.state.save()
self.create_custom_scene_clips(kept_scenes,
custom_audio_options=custom_audio_options,
custom_ext=output_ext,
volume=volume)
self.state.save()
if not self.state.clips:
raise ValueError("No processed video clips were found")
ffcmd = self.create_remix_video(output_filepath,
use_scene_sorting=use_scene_sorting)
self.log(f"FFmpeg command: {ffcmd}")
self.state.save()
def sort_marked_scenes(self) -> dict:
"""Returns dict mapping scene sort mark to scene name."""
result = {}
for scene_name in self.state.scene_names:
scene_label = self.state.scene_labels.get(scene_name)
sort, _, _ = self.state.split_label(scene_label)
if sort:
result[sort] = scene_name
return result
def get_processing_messages(self, raw=False):
return self.processing_messages if raw else "\r\n".join(self.processing_messages)
### Internal --------------------
# Handling processing feedback to user
def add_processing_message(self, message):
operation = self.processing_messages_context.get("operation", "unknown")
scene_name = self.processing_messages_context.get("scene_name", "unknown")
message = f"Operation: {operation} Scene: {scene_name} Message: {message}"
if message not in self.processing_messages:
self.processing_messages.append(message)
def reset_processing_messages(self):
self.processing_messages = []
self.processing_messages_context = {}
# Preprocessing
def _processed_content_complete(self, path, expected_dirs = 0, expected_files = 0):
if not path or not os.path.exists(path):
return False
if expected_dirs:
return len(get_directories(path)) == expected_dirs
if expected_files:
return len(get_files(path)) == expected_files
return True
# processed content is stale if it is not selected and exists
def processed_content_stale(self, selected : bool, path : str):
if selected:
return False
if not os.path.exists(path):
return False
contents = get_directories(path)
content_present = len(contents) > 0
return content_present
# content is stale if it is present on disk but not currently selected
# stale content and its derivative content should be purged
def purge_stale_processed_content(self, purge_resynth, purge_inflation, purge_upscale):
if self.processed_content_stale(self.state.resize_chosen(), self.state.resize_path):
self.state.purge_processed_content(purge_from=self.state.RESIZE_STEP)
if self.processed_content_stale(self.state.resynthesize_chosen(),
self.state.resynthesis_path) or purge_resynth:
self.state.purge_processed_content(purge_from=self.state.RESYNTH_STEP)
if self.processed_content_stale(self.state.inflate_chosen(),
self.state.inflation_path) or purge_inflation:
self.state.purge_processed_content(purge_from=self.state.INFLATE_STEP)
if self.processed_content_stale(self.state.effects_chosen(), self.state.effects_path):
self.state.purge_processed_content(purge_from=self.state.EFFECTS_STEP)
if self.processed_content_stale(self.state.upscale_chosen(),
self.state.upscale_path) or purge_upscale:
self.state.purge_processed_content(purge_from=self.state.UPSCALE_STEP)
def purge_incomplete_processed_content(self):
# content is incomplete if the wrong number of scene directories are present
# if it is currently selected and incomplete, it should be purged
if self.state.resize_chosen() and not self.processed_content_complete(
self.state.RESIZE_STEP):
self.state.purge_processed_content(purge_from=self.state.RESIZE_STEP)
if self.state.resynthesize_chosen() and not self.processed_content_complete(
self.state.RESYNTH_STEP):
self.state.purge_processed_content(purge_from=self.state.RESYNTH_STEP)
if self.state.inflate_chosen() and not self.processed_content_complete(
self.state.INFLATE_STEP):
self.state.purge_processed_content(purge_from=self.state.INFLATE_STEP)
if self.state.effects_chosen() and not self.processed_content_complete(
self.state.EFFECTS_STEP):
self.state.purge_processed_content(purge_from=self.state.EFFECTS_STEP)
if self.state.upscale_chosen() and not self.processed_content_complete(
self.state.UPSCALE_STEP):
self.state.purge_processed_content(purge_from=self.state.UPSCALE_STEP)
# General Processing
def resize_needed(self):
return self.state.resize_chosen() \
and not self.processed_content_complete(self.state.RESIZE_STEP)
def resynthesize_needed(self):
return self.state.resynthesize_chosen() \
and not self.processed_content_complete(self.state.RESYNTH_STEP)
def inflate_needed(self):
return self.state.inflate_chosen() \
and not self.processed_content_complete(self.state.INFLATE_STEP)
def effects_needed(self):
return self.state.effects_chosen() \
and not self.processed_content_complete(self.state.EFFECTS_STEP)
def upscale_needed(self):
return self.state.upscale_chosen() \
and not self.processed_content_complete(self.state.UPSCALE_STEP)
def scenes_source_path(self, processing_step):
processing_path = self.state.scenes_path
if processing_step == self.state.RESIZE_STEP:
# resize is the first processing step and always draws from the scenes path
pass
elif processing_step == self.state.RESYNTH_STEP:
# resynthesis is the second processing step
if self.state.resize_chosen():
# if resize is enabled, draw from the resized scenes path
processing_path = self.state.resize_path
elif processing_step == self.state.INFLATE_STEP:
# inflation is the third processing step
if self.state.resynthesize_chosen():
# if resynthesis is enabled, draw from the resyntheized scenes path
processing_path = self.state.resynthesis_path
elif self.state.resize_chosen():
# if resize is enabled, draw from the resized scenes path
processing_path = self.state.resize_path
elif processing_step == self.state.EFFECTS_STEP:
# effects is the fourth processing step
if self.state.inflate_chosen():
# if inflation is enabled, draw from the inflation path
processing_path = self.state.inflation_path
elif self.state.resynthesize_chosen():
# if resynthesis is enabled, draw from the resyntheized scenes path
processing_path = self.state.resynthesis_path
elif self.state.resize_chosen():
# if resize is enabled, draw from the resized scenes path
processing_path = self.state.resize_path
elif processing_step == self.state.UPSCALE_STEP:
# upscaling is the fifth processing step
if self.state.effects_chosen():
# if effects hints are in use, draw from the effects path
processing_path = self.state.effects_path
elif self.state.inflate_chosen():
# if inflation is enabled, draw from the inflation path
processing_path = self.state.inflation_path
elif self.state.resynthesize_chosen():
# if resynthesis is enabled, draw from the resyntheized scenes path
processing_path = self.state.resynthesis_path
elif self.state.resize_chosen():
# if resize is enabled, draw from the resized scenes path
processing_path = self.state.resize_path
return processing_path
# get path to the furthest processed content
def furthest_processed_path(self):
if self.state.upscale_chosen():
path = self.state.upscale_path
elif self.state.effects_chosen():
path = self.state.effects_path
elif self.state.inflate_chosen():
path = self.state.inflation_path
elif self.state.resynthesize_chosen():
path = self.state.resynthesis_path
elif self.state.resize_chosen():
path = self.state.resize_path
else:
path = self.state.scenes_path
return path
# Resize Processing
def resize_scenes(self, kept_scenes):
self.processing_messages_context["operation"] = "Resize"
scenes_base_path = self.scenes_source_path(self.state.RESIZE_STEP)
output_base_path = self.state.resize_path
create_directory(output_base_path)
desc = "Resize"
hint_type = self.state.RESIZE_HINT
self.process_resizing(scenes_base_path, output_base_path, hint_type, kept_scenes, desc,
adjust_for_inflation=False)
def effect_scenes(self, kept_scenes):
output_base_path = self.state.effects_path
create_directory(output_base_path)
working_input_path = self.scenes_source_path(self.state.EFFECTS_STEP)
working_paths = []
if self.state.effects_hint_chosen(self.state.EFFECTS_BLOCK_HINT):
operation = "Block FX"
self.processing_messages_context["operation"] = operation
working_output_path = os.path.join(output_base_path, "block_fx")
working_paths.append(working_output_path)
create_directory(working_output_path)
self.process_block_effects(working_input_path, working_output_path, kept_scenes, operation, adjust_for_inflation=True)
working_input_path = working_output_path
if self.state.effects_hint_chosen(self.state.EFFECTS_LENS_HINT):
operation = "Lens FX"
self.processing_messages_context["operation"] = operation
working_output_path = os.path.join(output_base_path, "lens_fx")
working_paths.append(working_output_path)
create_directory(working_output_path)
self.process_lens_effects(working_input_path, working_output_path, kept_scenes, operation, adjust_for_inflation=True)
working_input_path = working_output_path
# view is processed after all other effects (except fade) to take into account all effects
if self.state.effects_hint_chosen(self.state.EFFECTS_VIEW_HINT):
operation = "View FX"
self.processing_messages_context["operation"] = operation
working_output_path = os.path.join(output_base_path, "view_fx")
working_paths.append(working_output_path)
create_directory(working_output_path)
self.process_resizing(working_input_path, working_output_path,
self.state.EFFECTS_VIEW_HINT, kept_scenes, operation,
adjust_for_inflation=True)
working_input_path = working_output_path
# Fade is processed last so the fade effect doesn't interfere with other effect processing
if self.state.effects_hint_chosen(self.state.EFFECTS_FADE_HINT):
operation = "Fade FX"
self.processing_messages_context["operation"] = operation
working_output_path = os.path.join(output_base_path, "fade_fx")
working_paths.append(working_output_path)
create_directory(working_output_path)
self.process_fade(working_input_path, working_output_path, kept_scenes, operation, adjust_for_inflation=True)
working_input_path = working_output_path
# copy from last working input path to effects path
shutil.copytree(working_input_path, output_base_path, dirs_exist_ok=True)
remove_directories(working_paths)
def process_lens_effects(self, scenes_base_path, output_base_path, kept_scenes, desc,
adjust_for_inflation):
self.saved_lens_hint = self.DEFAULT_LENS_HINT
with Mtqdm().open_bar(total=len(kept_scenes), desc=desc) as bar:
for scene_name in kept_scenes:
self.processing_messages_context["scene_name"] = scene_name
scene_input_path = os.path.join(scenes_base_path, scene_name)
scene_output_path = os.path.join(output_base_path, scene_name)
create_directory(scene_output_path)
handled = self.process_lens_hint(scene_input_path, scene_output_path,
scene_name, adjust_for_inflation)
if not handled:
copy_files(scene_input_path, scene_output_path)
Mtqdm().update_bar(bar)
def process_lens_hint(self, scene_input_path, scene_output_path, scene_name,
adjust_for_inflation):
message = None
scene_label = self.state.scene_labels.get(scene_name)
lens_hint = self.state.get_hint(scene_label, self.state.EFFECTS_LENS_HINT)
# if there's no lens correction hint, and the saved correction differs
# from the default, presume the saved correction is what's wanted for
# an unhinted scene
if not lens_hint and self.saved_lens_hint != self.DEFAULT_LENS_HINT:
lens_hint = self.saved_lens_hint
handled = False
if lens_hint:
try:
handled = handled or \
self.process_animated_lens_hint(lens_hint, scene_input_path, scene_output_path,
scene_name, adjust_for_inflation)
handled = handled or \
self.process_static_lens_hint(lens_hint, scene_input_path, scene_output_path)
except Exception as error:
message = f"Skipping processing of hint {lens_hint} due to error: {error}"
handled = False
if self.state.remixer_settings.get("raise_on_error"):
raise
if message:
self.add_processing_message(message)
self.log(message)
return handled
def process_animated_lens_hint(self, lens_hint, scene_input_path, scene_output_path, scene_name, adjust_for_inflation):
if self.ANIMATED_ZOOM_HINT in lens_hint:
lens_hint = self.get_implied_lens_hint(lens_hint)
self.log(f"get_implied_lens_hint() filtered lens hint: {lens_hint}")
type_from, param_from, type_to, param_to, frame_from, frame_to, schedule = \
self.get_animated_lens_hints(lens_hint)
if type_from and type_to:
first_frame, last_frame, _ = details_from_group_name(scene_name)
num_frames = (last_frame - first_frame) + 1
param_from = float(param_from)
param_to = float(param_to)
context = self.compute_animated_lens_hints(scene_name, num_frames, type_from, param_from,
type_to, param_to, frame_from, frame_to, schedule,
adjust_for_inflation)
self.animate_undistort_scene(scene_input_path,
scene_output_path,
context=context)
return True
return False
def process_static_lens_hint(self, lens_hint, scene_input_path, scene_output_path):
type, param = self.get_lens_hint(lens_hint)
param = float(param)
if type == self.LENS_TYPE_UNDISTORT:
self.static_undistort_scene(scene_input_path, scene_output_path, param * -1.)
self.saved_lens_hint = lens_hint
return True
elif type == self.LENS_TYPE_DISTORT:
self.static_undistort_scene(scene_input_path, scene_output_path, param)
self.saved_lens_hint = lens_hint
return True
return False
def _get_lens_hint(self, hint, check_type):
lens_type = None
param = None
remainder = hint
if check_type in hint:
split_pos = hint.index(check_type)
lens_type = hint[:split_pos+1]
# if the lens type was found in a position other than first,
# the preceding value is stripped and passed into lens function
if len(lens_type) > 1:
param = lens_type[:-1]
lens_type = lens_type[-1]
return lens_type, param
def get_lens_hint(self, hint):
if hint:
for lens_type in self.LENS_TYPES:
type, param = self._get_lens_hint(hint, lens_type)
if type:
return type, param
return None, None
# https://stackoverflow.com/questions/26602981/correct-barrel-distortion-in-opencv-manually-without-chessboard-image
def undistort_frame(self, frame, param):
if param == 0.0:
return frame
height, width = frame.shape[:2]
distCoeff = np.zeros((4, 1), np.float64)
distCoeff[0,0] = param; # negative to remove barrel distortion
distCoeff[1,0] = 0.
distCoeff[2,0] = 0.
distCoeff[3,0] = 0.
# assume unit matrix for camera
cam = np.eye(3, dtype=np.float32)
# this will quickly lead to a nice circular "pipe" effect at the image edge
# - if this needs to lead to it slower, change to use max() instead
# - if this instead should perform a barrel (oval) distortion,
# set these to the width and height or some scaled variation
focal_length = float(min(width, height))
cam[0, 2] = width / 2. # define center x
cam[1, 2] = height / 2. # define center y
cam[0, 0] = focal_length # define focal length x
cam[1, 1] = focal_length # define focal length y
# here the undistortion will be computed
return cv2.undistort(frame, cam, distCoeff)
def static_undistort_scene(self, scene_input_path, scene_output_path, param):
files = sorted(get_files(scene_input_path))
with Mtqdm().open_bar(total=len(files), desc="Distort FX") as bar:
for file in files:
_, filename, ext = split_filepath(file)
output_path = os.path.join(scene_output_path, filename + ext)
frame = cv2.imread(file)
frame = self.undistort_frame(frame, param)
cv2.imwrite(output_path, frame.astype(np.uint8))
Mtqdm().update_bar(bar)
def get_implied_lens_hint(self, hint):
if self.ANIMATED_ZOOM_HINT in hint:
if len(hint) >= self.ANIMATED_LENS_MIN_LEN:
split_pos = hint.index(self.ANIMATED_ZOOM_HINT)
hint_from = hint[:split_pos]
hint_to = hint[split_pos+1:]
# if the hint_to part includes time or schedule info, remove it to get only the view
lens_to = hint_to
remainder = ""
if self.ANIMATION_TIME_HINT in lens_to:
split_pos = lens_to.index(self.ANIMATION_TIME_HINT)
remainder = lens_to[split_pos:]
lens_to = lens_to[:split_pos]
# may include schedule part, which can come after time part
elif self.ANIMATION_SCHEDULE_HINT in lens_to:
split_pos = lens_to.index(self.ANIMATION_SCHEDULE_HINT)
remainder = lens_to[split_pos:]
lens_to = lens_to[:split_pos]
if not hint_from or not lens_to:
if not hint_from and not lens_to:
# single dash (both missing) means return to default lens hint
hint_from = self.saved_lens_hint
hint_to = self.DEFAULT_LENS_HINT
lens_to = self.DEFAULT_LENS_HINT
self.log(f"get_implied_lens_hint(): using saved hint for from: {hint_from} and default hint for to: {hint_to}")
elif hint_from and not lens_to:
# missing 'to' means go to saved lens hint
hint_to = self.saved_lens_hint
self.log(f"get_implied_lens_hint(): using passed hint for from: {hint_from} and saved hint for to: {hint_to}")
elif not hint_from and lens_to:
# missing 'from' means go from saved lens hint
hint_from = self.saved_lens_hint
self.log(f"get_implied_lens_hint(): using saved hint for from: {hint_from} and passed hint for to: {hint_to}")
else:
self.log(f"get_implied_lens_hint(): using passed hint for from: {hint_from} and passed hint for to: {hint_to}")
if lens_to:
self.saved_lens_hint = lens_to
return f"{hint_from}-{lens_to}{remainder}"
return hint
# TODO DRY
def get_animated_lens_hints(self, lens_hint):
hint = lens_hint
if self.ANIMATED_ZOOM_HINT in hint:
if len(hint) >= self.ANIMATED_LENS_MIN_LEN:
schedule = self.DEFAULT_ANIMATION_SCHEDULE
time = self.DEFAULT_ANIMATION_TIME
if self.ANIMATION_SCHEDULE_HINT in hint:
split_pos = hint.index(self.ANIMATION_SCHEDULE_HINT)
remainder = hint[:split_pos]
schedule = hint[split_pos+1:]
hint = remainder
if self.ANIMATION_TIME_HINT in hint:
split_pos = hint.index(self.ANIMATION_TIME_HINT)
remainder = hint[:split_pos]
time = hint[split_pos+1:]
hint = remainder
if self.ANIMATION_TIME_SEP in time:
# a specific frame range is specified
split_pos = time.index(self.ANIMATION_TIME_SEP)
# one or both values may be empty strings
frame_from = time[:split_pos]
frame_to = time[split_pos+1:]
else:
# a frame count is specified with an implied range starting at zero
frame_from = 0
frame_to = int(time)
else:
frame_from = ""
frame_to = ""
split_pos = lens_hint.index(self.ANIMATED_ZOOM_HINT)
hint_from = lens_hint[:split_pos]
hint_to = lens_hint[split_pos+1:]
from_type, from_param = self.get_lens_hint(hint_from)
to_type, to_param = self.get_lens_hint(hint_to)
return from_type, from_param, to_type, to_param, frame_from, frame_to, schedule
return None, None, None, None, None, None, None
# TODO DRY
def compute_animated_lens_hints(self, scene_name, num_frames, type_from, param_from, type_to, param_to,
frame_from, frame_to, schedule, adjust_for_inflation):
# animation time override
if frame_from == "" and frame_to == "":
# unspecified range, ignore
frame_from = 0
frame_to = num_frames
elif frame_to == "":
# frame_to is the last frame
frame_to = num_frames
elif frame_from == "":
# frame_from is offset from the end
frame_from = num_frames - int(frame_to)
frame_to = num_frames
frame_from = int(frame_from)
frame_to = int(frame_to)
if frame_from >= 0 and frame_to <= num_frames and frame_from < frame_to:
num_frames = frame_to - frame_from
else:
# safety catch
frame_from = 0
frame_to = num_frames
# account for inflation if being used for view handling
if adjust_for_inflation:
_video_clip_fps, fps_factor = self.compute_scene_fps(scene_name)
num_frames = self.compute_inflated_frame_count(num_frames, fps_factor)
frame_from = self.compute_inflated_frame_count(frame_from, fps_factor)
frame_to = self.compute_inflated_frame_count(frame_to, fps_factor)
if type_from == self.LENS_TYPE_UNDISTORT:
param_from *= -1.
if type_to == self.LENS_TYPE_UNDISTORT:
param_to *= -1.
lens_from = param_from
lens_to = param_to
diff_lens = lens_to - lens_from
# TODO why is this needed? without it, the last transition doesn't happen
# - maybe it needs to be the number of transitions between frames not number of frames
# Ensure the final transition occurs
num_frames -= 1
step_lens = diff_lens / num_frames
context = {}
context["lens_from"] = lens_from
context["step_lens"] = step_lens
context["num_frames"] = num_frames
context["schedule"] = schedule
context["start_frame"] = frame_from
context["end_frame"] = frame_to
return context
def animate_undistort_scene(self,
scene_input_path,
scene_output_path,
context : any=None):
lens_from = context["lens_from"]
step_lens = context["step_lens"]
num_frames = context["num_frames"]
schedule = context["schedule"]
start_frame = context["start_frame"]
end_frame = context["end_frame"]
files = sorted(get_files(scene_input_path))
with Mtqdm().open_bar(total=len(files), desc="Distort FX") as bar:
for index, file in enumerate(files):
_, filename, ext = split_filepath(file)
output_path = os.path.join(scene_output_path, filename + ext)
if index < start_frame:
index = 0
elif index > end_frame:
index = end_frame - start_frame
else:
index -= start_frame
accelerate = True
index, float_carry = self._apply_animation_schedule(schedule, num_frames, index,
accelerate)
if float_carry >= 0.5:
index += 1
if index > num_frames:
index = num_frames
param = lens_from + (step_lens * index)
if param < self.LENS_MIN_UNDISTORT:
param = self.LENS_MIN_UNDISTORT
elif param > self.LENS_MAX_UNDISTORT:
param = self.LENS_MAX_UNDISTORT
frame = cv2.imread(file)
frame = self.undistort_frame(frame, param)
cv2.imwrite(output_path, frame)
Mtqdm().update_bar(bar)
def process_block_effects(self, scenes_base_path, output_base_path, kept_scenes, desc,
adjust_for_inflation):
self.sticky_block_hints = []
self.block_animation_contexts = {}
with Mtqdm().open_bar(total=len(kept_scenes), desc=desc) as bar:
for scene_name in kept_scenes:
self.processing_messages_context["scene_name"] = scene_name
scene_input_path = os.path.join(scenes_base_path, scene_name)
scene_output_path = os.path.join(output_base_path, scene_name)
create_directory(scene_output_path)
handled = self.process_block_hints(scene_input_path, scene_output_path,
scene_name, adjust_for_inflation)
if not handled:
copy_files(scene_input_path, scene_output_path)
Mtqdm().update_bar(bar)
# have default arguments so this is more easily reused for showing a preview
def process_block_hint(self, hint, frame, main_resize_w, main_resize_h, main_offset_x,
main_offset_y, main_crop_w, main_crop_h, index=None, scene_name=None,
adjust_for_inflation=False):
self.noise_dampening = None
hint_handled = False
if not hint_handled and (index != None and scene_name != None):
hint_handled, frame = self.process_animated_block_hint(hint, frame, main_resize_w, main_resize_h, main_offset_x, main_offset_y, main_crop_w, main_crop_h, index, scene_name, adjust_for_inflation)
if not hint_handled:
hint_handled, frame = self.process_combined_block_hint(hint, frame, main_resize_w, main_resize_h, main_offset_x, main_offset_y, main_crop_w, main_crop_h)
if not hint_handled:
hint_handled, frame = self.process_quadrant_block_hint(hint, frame, main_resize_w, main_resize_h, main_offset_x, main_offset_y, main_crop_w, main_crop_h)
if not hint_handled:
hint_handled, frame = self.process_percent_block_hint(hint, frame, main_resize_w, main_resize_h, main_offset_x, main_offset_y, main_crop_w, main_crop_h)
return hint_handled, frame
def process_block_hints(self, scene_input_path, scene_output_path, scene_name,
adjust_for_inflation):
message = None
scene_handled = False
hints = self.state.get_hint(self.state.scene_labels.get(scene_name),
self.state.EFFECTS_BLOCK_HINT, allow_multiple=True)
hints = self.sticky_block_hints + hints if hints else self.sticky_block_hints
if hints:
content_width = self.state.video_details["content_width"]
content_height = self.state.video_details["content_height"]
main_resize_w, main_resize_h, main_crop_w, main_crop_h, main_offset_x, main_offset_y = \
self.setup_resize_hint(content_width, content_height, False)
files = sorted(get_files(scene_input_path))
with Mtqdm().open_bar(total=len(files), desc="Block FX") as bar:
for index, file in enumerate(files):
_, filename, ext = split_filepath(file)
output_path = os.path.join(scene_output_path, filename + ext)
frame = cv2.imread(file)
for hint in hints:
try:
hint_handled, frame = self.process_block_hint(hint, frame, main_resize_w, main_resize_h, main_offset_x, main_offset_y, main_crop_w, main_crop_h, index, scene_name, adjust_for_inflation)
scene_handled = scene_handled or hint_handled
except Exception as error:
message = f"Skipping processing of hint {hint} due to error: {error}"
hint_handled = False
if self.state.remixer_settings.get("raise_on_error"):
raise
cv2.imwrite(output_path, frame.astype(np.uint8))
Mtqdm().update_bar(bar)
if message:
self.add_processing_message(message)
self.log(message)
return scene_handled
def get_animated_block_hints(self, hint):
if self.ANIMATED_ZOOM_HINT in hint:
if len(hint) >= self.ANIMATED_BLOCK_MIN_LEN:
split_pos = hint.index(self.ANIMATED_ZOOM_HINT)
hint_from = hint[:split_pos]
hint_to = hint[split_pos+1:]
from_block_type, from_block_param, remaining_hint_from = self.get_block_type(hint_from)
to_block_type, to_block_param, remaining_hint_to = self.get_block_type(hint_to)
# remove the block hint specific parts of the hint and process like a zoom hint
# 'type' may include a block fx parameter
block_hint = f"{remaining_hint_from}-{remaining_hint_to}"
from_type, from_param1, from_param2, from_param3, to_type, to_param1, \
to_param2, to_param3, frame_from, frame_to, schedule \
= self.get_animated_zoom_hints(block_hint)
return from_block_type, from_block_param, to_block_type, to_block_param, \
from_type, from_param1, from_param2, from_param3, \
to_type, to_param1, to_param2, to_param3, \
frame_from, frame_to, schedule
return dummy_args(15)
def process_animated_block_hint(self, block_hint, frame,
main_resize_w, main_resize_h, main_offset_x, main_offset_y,
main_crop_w, main_crop_h,
index, scene_name, adjust_for_inflation):
from_block_type, from_block_param, to_block_type, to_block_param, \
from_type, from_param1, from_param2, from_param3, \
to_type, to_param1, to_param2, to_param3, \
frame_from, frame_to, schedule = \
self.get_animated_block_hints(block_hint)
context = self.block_animation_contexts.get(block_hint)
if not context:
if from_type and to_type:
first_frame, last_frame, _ = details_from_group_name(scene_name)
num_frames = (last_frame - first_frame) + 1
context = self.compute_animated_zoom(scene_name, num_frames,
from_type, from_param1, from_param2, from_param3,
to_type, to_param1, to_param2, to_param3, frame_from,
frame_to, schedule, main_resize_w, main_resize_h,
main_offset_x, main_offset_y, main_crop_w, main_crop_h,
adjust_for_inflation)
if context:
context["block_type"] = from_block_type
if from_block_param or to_block_param:
if not from_block_param:
from_block_param = self.default_block_param(from_type)
if not to_block_param:
to_block_param = self.default_block_param(to_type)
num_frames = context["num_frames"]
diff_block_param = float(to_block_param) - float(from_block_param)
step_block_param = diff_block_param / num_frames
context["from_block_param"] = float(from_block_param)
context["step_block_param"] = step_block_param
self.block_animation_contexts[block_hint] = context
if context:
start_frame = context["start_frame"]
end_frame = context["end_frame"]
schedule = context["schedule"]
num_frames = context["num_frames"]
if index < start_frame:
index = 0
elif index > end_frame:
index = end_frame - start_frame
else:
index -= start_frame
accelerate = True
index, float_carry = self._apply_animation_schedule(schedule, num_frames, index,
accelerate)
if float_carry >= 0.5:
index += 1
if index > num_frames:
index = num_frames
resize_w, resize_h, crop_offset_x, crop_offset_y = \
self._resize_frame_param(index, context)
block_type = context["block_type"]