-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslideshow_ENCODER_legacy.vpy
3498 lines (3352 loc) · 229 KB
/
slideshow_ENCODER_legacy.vpy
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
# Copyright (C) <2023> <ongoing> <hydra3333>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import sys
import os
print(f"",flush=True,file=sys.stderr)
print(f"<This Script: '{os.path.abspath(__file__)}'>",flush=True,file=sys.stderr)
print(f"<QN_Auto_Slideshow_Creator_for_Windows> Copyright (C) <2023> <congoing> <hydra3333>",flush=True,file=sys.stderr)
print(f"This program comes with ABSOLUTELY NO WARRANTY; for details refer to the license on",flush=True,file=sys.stderr)
print(f"github at https://github.com/hydra3333/QN_Auto_Slideshow_Creator_for_Windows/blob/main/LICENSE.",flush=True,file=sys.stderr)
print(f"This is free software, and you are welcome to redistribute it",flush=True,file=sys.stderr)
print(f"under certain conditions; for details refer to the license on",flush=True,file=sys.stderr)
print(f"github at https://github.com/hydra3333/QN_Auto_Slideshow_Creator_for_Windows/blob/main/LICENSE.",flush=True,file=sys.stderr)
print(f"",flush=True,file=sys.stderr)
### LEGACY CODE
# 1. Modifying the sys.path list in a module DOES NOT not affect the sys.path of other modules or the main program.
# 2. Modifying the sys.path list in the MAIN PROGRAM WILL affect the search path for all modules imported by that program.
# Ensure we can import modules from ".\" by adding the current default folder to the python path.
# (tried using just PYTHONPATH environment variable but it was unreliable)
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import slideshow_GLOBAL_UTILITIES_AND_VARIABLES as UTIL # define utilities and make global variables available to everyone
import vapoursynth as vs
from vapoursynth import core
core = vs.core
#core.num_threads = 1
import importlib
import re
import argparse
from functools import partial
import pathlib
from pathlib import Path, PureWindowsPath
import shutil
import subprocess
import datetime
#from datetime import datetime, date, time, timezone
from fractions import Fraction
from ctypes import * # for mediainfo ... load via ctypes.CDLL(r'.\MediaInfo.dll')
from typing import Union # for mediainfo
from typing import NamedTuple
from collections import defaultdict, OrderedDict
from enum import Enum
from enum import auto
#from strenum import StrEnum
#from strenum import LowercaseStrEnum
#from strenum import UppercaseStrEnum
import itertools
import math
import random
import glob
import configparser # or in v3: configparser
import yaml
import json
import pprint
import ast
import uuid
import logging
# for subprocess control eg using Popen
import time
from queue import Queue, Empty
from threading import Thread
import gc # for inbuilt garbage collection
# THE NEXT STATEMENT IS ONLY FOR DEBUGGING AND WILL CAUSE EXTRANEOUS OUTPUT TO STDERR
#gc.set_debug(gc.DEBUG_LEAK | gc.DEBUG_STATS) # for debugging, additional garbage collection settings, writes to stderr https://docs.python.org/3/library/gc.html to help detect leaky memory issues
num_unreachable_objects = gc.collect() # collect straight away
from PIL import Image, ExifTags, UnidentifiedImageError
from PIL.ExifTags import TAGS
import pydub
from pydub import AudioSegment
CDLL(r'MediaInfo.dll') # note the hard-coded folder # per https://forum.videohelp.com/threads/408230-ffmpeg-avc-from-jpgs-of-arbitrary-dimensions-maintaining-aspect-ratio#post2678372
from MediaInfoDLL3 import MediaInfo, Stream, Info, InfoOption # per https://forum.videohelp.com/threads/408230-ffmpeg-avc-from-jpgs-of-arbitrary-dimensions-maintaining-aspect-ratio#post2678372
#from MediaInfoDLL3 import * # per https://github.com/MediaArea/MediaInfoLib/blob/master/Source/Example/HowToUse_Dll3.py
#core.std.LoadPlugin(r'DGDecodeNV.dll')
#core.avs.LoadPlugin(r'DGDecodeNV.dll')
global TERMINAL_WIDTH # for use by PrettyPrinter
TERMINAL_WIDTH = 250
global objPrettyPrint
objPrettyPrint = pprint.PrettyPrinter(width=TERMINAL_WIDTH, compact=False, sort_dicts=False) # facilitates formatting and printing of text and dicts etc
#def UTIL.normalize_path(path):
# #if DEBUG: print(f"DEBUG: UTIL.normalize_path: incoming path='{path}'",flush=True,file=sys.stderr)
# # Replace single backslashes with double backslashes
# path = path.rstrip(os.linesep).strip('\r').strip('\n').strip()
# r1 = r'\\'
# r2 = r1 + r1
# r4 = r2 + r2
# path = path.replace(r1, r4)
# # Add double backslashes before any single backslashes
# for i in range(0,20):
# path = path.replace(r2, r1)
# #if DEBUG: print(f"DEBUG: UTIL.normalize_path: outgoing path='{path}'",flush=True,file=sys.stderr)
# return path
# A Special function needed at the top DEFAULT_INI_FILE_SPECIFYING_PARAMETERS and DEFAULT_DIRECTORY_LIST
#def UTIL.fully_qualified_directory_no_trailing_backslash(directory_name):
# # make into a fully qualified directory string stripped and without a trailing backslash
# # also remove extraneous backslashes which get added by things like abspath
# new_directory_name = os.path.abspath(directory_name).rstrip(os.linesep).strip('\r').strip('\n').strip()
# if directory_name[-1:] == (r'\ '.strip()): # r prefix means the string is treated as a raw string so all escape codes will be ignored. EXCEPT IF THE \ IS THE LAST CHARACTER IN THE STRING !
# new_directory_name = directory_name[:-1] # remove any trailing backslash
# new_directory_name = UTIL.normalize_path(new_directory_name)
# return new_directory_name
#def UTIL.fully_qualified_filename(file_name):
# # Make into a fully qualified filename string using double backslashes
# # to later print/write with double backslashes use eg
# # converted_string = UTIL.fully_qualified_filename('D:\\a\\b\\\\c\\\\\\d\\e\\f\\filename.txt')
# # print(repr(converted_string),flush=True,file=sys.stderr)
# # yields 'D:\\a\\b\\c\\d\\e\\f\\filename.txt'
# new_file_name = os.path.abspath(file_name).rstrip(os.linesep).strip('\r').strip('\n').strip()
# if new_file_name.endswith('\\'):
# new_file_name = new_file_name[:-1] # Remove trailing backslash
# new_file_name = UTIL.normalize_path(new_file_name)
# return new_file_name
###
# Define GLOBALS and initialize them
#
global FFMPEG_PATH
FFMPEG_PATH = 'this_is_set_in_class_settings'
global IS_DEBUG
IS_DEBUG = False # default DEBUG to False
global IS_DEBUG_SYSTEM_OVERRIDE
IS_DEBUG_SYSTEM_OVERRIDE = False # for major debugging ONLY: this is always FALSE otherwide ...
global A_DEBUG_IS_ON
A_DEBUG_IS_ON = IS_DEBUG or IS_DEBUG_SYSTEM_OVERRIDE
#
# 2022.03.19, see what happens with multi [ "MI = MediaInfo()" and matching "del MI" ] instead of one global declaration
#global MI
#MI = MediaInfo() # initialize a global for mediainfo per https://forum.videohelp.com/threads/408230-ffmpeg-avc-from-jpgs-of-arbitrary-dimensions-maintaining-aspect-ratio#post2678372
#
##########
global objSettings # a global object for the class which deals with settings.
objSettings = None
##########
# some "working" globals
global last_file_opened_with_ffms2
global last_file_opened_with_imwri
global last_file_opened_with_LWLibavSource
global last_file_opened_with_LibavSMASHSource
global Count_of_files
#
# https://github.com/vapoursynth/vapoursynth/issues/940#issuecomment-1465041338
# When calling rezisers etc, ONLY use these values:
# ZIMG_RANGE_LIMITED = 0, /**< Studio (TV) legal range, 16-235 in 8 bits. */
# ZIMG_RANGE_FULL = 1 /**< Full (PC) dynamic range, 0-255 in 8 bits. */
# but when obtaining from frame properties and comparing etc, use the vs values from
# frame properties even though the vapoursynth values are incorrect (opposite to the spec)
global ZIMG_RANGE_LIMITED
ZIMG_RANGE_LIMITED = 0 # /**< Studio (TV) legal range, 16-235 in 8 bits. */
global ZIMG_RANGE_FULL
ZIMG_RANGE_FULL = 1 # /**< Full (PC) dynamic range, 0-255 in 8 bits. */
# https://www.vapoursynth.com/doc/apireference.html?highlight=_FieldBased
global vs_interlaced
vs_interlaced = { 'Progressive' : 0, 'BFF' : 1, 'TFF' : 2 } # vs documnetation says frame property _FieldBased is one of 0=frame based (progressive), 1=bottom field first, 2=top field first.
###
# Public Domain software: vs_transitions
# https://github.com/OrangeChannel/vs-transitions
# vs-transitions SOURCE CODE:
# https://raw.githubusercontent.com/OrangeChannel/vs-transitions/master/vs_transitions/__init__.py
# vs-transitions DOCUMENTATION:
# https://vapoursynth-transitions.readthedocs.io/en/latest/api.html
# modified and saved as vs_transitions.py from
# https://raw.githubusercontent.com/OrangeChannel/vs-transitions/master/vs_transitions/__init__.py
import vs_transitions
###
global crossfade_type_list
crossfade_type_list = list(map(str.lower,[ 'none',
'random',
'fade',
'fade_to_black',
'fade_from_black',
'wipe',
'push',
'slide_expand',
'squeeze_slide',
'squeeze_expand',
'cover',
'reveal',
'curtain_cover',
'curtain_reveal',
'peel',
'pixellate',
'cube_rotate',
#'linear_boundary',
]))
global crossfade_type_list_no_black_fades
crossfade_type_list_no_black_fades = list(map(str.lower,[
'none',
#'random',
'fade',
#'fade_to_black',
#'fade_from_black',
'wipe',
'push',
'slide_expand',
'squeeze_slide',
'squeeze_expand',
'cover',
'reveal',
'curtain_cover',
'curtain_reveal',
'peel',
'pixellate',
'cube_rotate',
#'linear_boundary',
]))
global crossfade_direction_list
crossfade_direction_list = []
for v in vs_transitions.Direction:
crossfade_direction_list.append(v.value)
###
def print_DEBUG(*args, **kwargs): # PRINT TO stderr
# per https://stackoverflow.com/questions/5574702/how-do-i-print-to-stderr-in-python
if A_DEBUG_IS_ON:
right_now = datetime.datetime.now().strftime('%Y-%m-%d.%H:%M:%S.%f')
print(f'{right_now} DEBUG:', *args, **kwargs, file=sys.stderr, flush=True)
###
def print_NORMAL(*args, **kwargs): # PRINT TO stderr
# per https://stackoverflow.com/questions/5574702/how-do-i-print-to-stderr-in-python
right_now = datetime.datetime.now().strftime('%Y-%m-%d.%H:%M:%S.%f')
print(f'{right_now}', *args, **kwargs, file=sys.stderr, flush=True)
###
class settings:
# class global variables shared across instances
_ini_section_name = 'slideshow'
SETTINGS_DICT = {}
USER_SPECIFIED_SETTINGS_DICT = {}
_ini_values = { _ini_section_name : {} }
calc_ini = {}
def __init__(self):
global IS_DEBUG
global A_DEBUG_IS_ON
global FFMPEG_PATH
import slideshow_LOAD_SETTINGS # from same folder .\
self.SETTINGS_DICT, self._ini_values, self.calc_ini, self.USER_SPECIFIED_SETTINGS_DICT = slideshow_LOAD_SETTINGS.load_settings()
# slideshow_LOAD_SETTINGS.load_settings() returns 4 things:
# SETTINGS_DICT contains user settings with defaults appled plus "closed" settings added
# INI_DICT an old dict compatible with the "chunk encoder" which has an older code base (with changes to understand modern chunk and snippet)
# CALC_INI_DICT per "INI_DICT" but with extra fields calculated and added per the legacy CALC_INI
# USER_SPECIFIED_SETTINGS_DICT the settings which were specified by the user
if self.SETTINGS_DICT['DEBUG']:
IS_DEBUG = True
#IS_DEBUG = False
else:
IS_DEBUG = False
A_DEBUG_IS_ON = IS_DEBUG or IS_DEBUG_SYSTEM_OVERRIDE
FFMPEG_PATH = self.SETTINGS_DICT['FFMPEG_PATH']
# make class variables from the self.calc_ini dictionary # https://www.geeksforgeeks.org/how-to-change-a-dictionary-into-a-class/
# Having made class variables from the self.SETTINGS_DICT dictionary
# we can read them as normal class variables like thing.variable_name
# or as dictionary variables like thing.calc_ini["key_name"]
# *** Remembering the dict and the class-global variables are SEPARATE VARIABLES and
# that overwriting one does NOT overwrite the other and mismatches WILL then occur ...
# OR ...
# self.__dict__.update(self.calc_ini) # per https://www.sobyte.net/post/2022-04/python-dict-2-member-variables/ # this updates existing variables with new values per https://www.geeksforgeeks.org/python-dictionary-update-method/
for key in self.SETTINGS_DICT:
if not key.startswith(';'):
setattr(self, key, self.SETTINGS_DICT[key]) # this updates existing variables with new values
# THIS NEXT BIT IS REQUIRED AND RELIED ON THROUGHOUT THIS LEGACY CODE
# make class variables from the self.calc_ini dictionary # https://www.geeksforgeeks.org/how-to-change-a-dictionary-into-a-class/
for key in self.calc_ini:
if not key.startswith(';'):
setattr(self, key, self.calc_ini[key]) # this updates existing variables with new values
#
def class_variables_and_values(self):
# yield class variables and values as a dict
return self.__dict__
def debug_print_class_vars(self):
#members = [attr for attr in dir(obj) if not callable(getattr(obj, attr)) and not attr.startswith("__")]
#print(members, file=sys.stderr, flush=True)
# we need to convert vars(self).items() to a LIST, since dict does not allow duplicate keys
#objPrettyPrint.pprint(vars(self), file=sys.stderr, flush=True)
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: CLASS VARIABLES IN ALPHABETIC NAME ORDER')
c = sorted(vars(self).items(), key=lambda yvar: str(yvar[0]).lower() )
choppy = 48
for d,e in c:
sd = str(d)
L = min(choppy,len(sd))
sd = sd[0:L]
s = ' ' * (choppy-len(sd)+1)
if A_DEBUG_IS_ON: print_DEBUG(f'"{sd}"{s} = "{e}"')
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: {len(c)} VARIABLES IN ALPHABETIC NAME ORDER')
del c
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: CLASS VARIABLES IN ALPHABETIC VALUE ORDER')
f = sorted(vars(self).items(), key=lambda yvar: str(yvar[1]).lower() )
choppy = 64
for g,h in f:
sh = str(h)
m = max(0,choppy-len(sh)+1)
s = ' '*m
if A_DEBUG_IS_ON: print_DEBUG(f'"{sh}"{s} = "{g}"')
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: {len(f)} VARIABLES IN ALPHABETIC VALUE ORDER')
del f
###
class OBOLETE_legacy_settings:
# class global variables shared across instances
_default_ini_file = r'.\SLIDESHOW_PARAMETERS.ini'
_pre_default_directories_list = [ r'.' ]
_default_temp_directory = r'.\\temp'
_default_snippets_filename_path = r'.\\snippets_data.txt'
_default_output_mkv_filename_path = r'.\\slideshow.txt'
_ini_section_name = 'slideshow'
_default_ini_values = { _ini_section_name : {} }
_ini_values = { _ini_section_name : {} }
DEFAULT_INI_FILE_SPECIFYING_PARAMETERS = ''
DEFAULT_DIRECTORY_LIST = []
DEFAULT_TEMP_DIRECTORY_LIST = []
DEFAULT_SNIPPETS_FILENAME_PATH_LIST = []
DEFAULT_OUTPUT_MKV_FILENAME_PATH_LIST = []
#
ini_file_specifying_parameters = ''
calc_ini = {}
def __repr__(self):
# override the __repr__ method of our class and make it print out something a more useful, like class variables
# https://www.blog.pythonlibrary.org/2014/02/14/python-101-how-to-change-a-dict-into-a-class/
attrs = str([x for x in self.__dict__])
#attrs = str([x for x in dir(self) if not x.startswith('__')]) # also could have done this:
#return "<settings: %s="">" % attrs
return "<settings: %s"">" % attrs
def class_variables_and_values(self):
return self.__dict__
def debug_print_class_vars(self):
#members = [attr for attr in dir(obj) if not callable(getattr(obj, attr)) and not attr.startswith("__")]
#print(members, file=sys.stderr, flush=True)
# we need to convert vars(self).items() to a LIST, since dict does not allow duplicate keys
#objPrettyPrint.pprint(vars(self), file=sys.stderr, flush=True)
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: CLASS VARIABLES IN ALPHABETIC NAME ORDER')
c = sorted(vars(self).items(), key=lambda yvar: str(yvar[0]).lower() )
choppy = 48
for d,e in c:
sd = str(d)
L = min(choppy,len(sd))
sd = sd[0:L]
s = ' ' * (choppy-len(sd)+1)
if A_DEBUG_IS_ON: print_DEBUG(f'"{sd}"{s} = "{e}"')
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: {len(c)} VARIABLES IN ALPHABETIC NAME ORDER')
del c
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: CLASS VARIABLES IN ALPHABETIC VALUE ORDER')
f = sorted(vars(self).items(), key=lambda yvar: str(yvar[1]).lower() )
choppy = 64
for g,h in f:
sh = str(h)
m = max(0,choppy-len(sh)+1)
s = ' '*m
if A_DEBUG_IS_ON: print_DEBUG(f'"{sh}"{s} = "{g}"')
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: {len(f)} VARIABLES IN ALPHABETIC VALUE ORDER')
del f
return
def __init__(self):
global IS_DEBUG
global A_DEBUG_IS_ON
self.DEFAULT_INI_FILE_SPECIFYING_PARAMETERS = UTIL.fully_qualified_directory_no_trailing_backslash(self._default_ini_file) # r prefix means the string is treated as a raw string so all escape codes will be ignored. EXCEPT IF THE \ is the last character in the string ! So don't put one there.
self.ini_file_specifying_parameters = UTIL.fully_qualified_directory_no_trailing_backslash(self.DEFAULT_INI_FILE_SPECIFYING_PARAMETERS)
for ddl in self._pre_default_directories_list:
self.DEFAULT_DIRECTORY_LIST.append(UTIL.fully_qualified_directory_no_trailing_backslash(ddl))
self.DEFAULT_TEMP_DIRECTORY_LIST = [ UTIL.fully_qualified_directory_no_trailing_backslash(self._default_temp_directory) ]
self.DEFAULT_SNIPPETS_FILENAME_PATH_LIST = [ UTIL.fully_qualified_filename(self._default_snippets_filename_path) ]
self.DEFAULT_OUTPUT_MKV_FILENAME_PATH_LIST = [ UTIL.fully_qualified_filename(self._default_output_mkv_filename_path) ]
self._default_ini_values = {
self._ini_section_name : {
'; CRITICAL NOTES re "directory_list" and "temp_directory"' : '.',
'; 1. paths MUST ALWAYS contain DOUBLE backslashes in every instance - a single backslash causes problems and the result, if any, will be extremely uncertain' : '.',
'; 2. paths must NEVER end with a backslash; backslashes are "escaping" notifiers - if a path ends in a backslash, always put a space character after it at the end of string' : '.',
'; remember : always use double-backslashes in all paths' : '.',
'; remember : never end a path with a backslash as the last character (you would rue it)' : '.',
';' : '.',
'; "DIRECTORY_LIST" is defined as a list of paths (double-backslashed); beware: .\\\\ by itself means current default path' : '.',
'DIRECTORY_LIST' : str(self.DEFAULT_DIRECTORY_LIST), # must convert LIST to a STR or it all fails
'; "TEMP_DIRECTORY_LIST" is defined as a list of paths (for coding convenience) however only the first path in the list will be used' : '.',
'TEMP_DIRECTORY_LIST' : str(self.DEFAULT_TEMP_DIRECTORY_LIST),
'; "SNIPPETS_FILENAME_PATH_LIST" is defined as a list of paths (for coding convenience) however only the first path in the list will be used' : '.',
'SNIPPETS_FILENAME_PATH_LIST' : str(self.DEFAULT_SNIPPETS_FILENAME_PATH_LIST),
'; "OUTPUT_MKV_FILENAME_PATH_LIST" is defined as a list of paths (for coding convenience) however only the first path in the list will be used' : '.',
'OUTPUT_MKV_FILENAME_PATH_LIST' : str(self.DEFAULT_OUTPUT_MKV_FILENAME_PATH_LIST),
'; "RECURSIVE" is True or False; if True, it also walks the sub-directory tree(s) looking for images/videos' : '.',
'RECURSIVE' : True,
'; "SUBTITLE_DEPTH" an integer; it subtitles with the path/filename of the image/video from the right up to the nominated depth; 0 turns it off' : '.',
'SUBTITLE_DEPTH' : 3, # adds a subtitle in the bottom right corner containing the last specified number of parts of the path to the image/video
'; "SUBTITLE_FONTSIZE" an integer; the fontsize used for subtitling (18 is good)' : '.',
'SUBTITLE_FONTSIZE' : 18,
'; "SUBTITLE_FONTSCALE" a real number; scale applied to the fontsize (1.0 to 3.0 is good)' : '.',
'SUBTITLE_FONTSCALE' : 1.0,
'; "DURATION_PIC_SEC" a real number; the number of seconds a pic is displayed in trhe slideshow' : '.',
'DURATION_PIC_SEC' : 4.0, ### MAXIMUM duration of display of an image, in seconds
'; "DURATION_CROSSFADE_SECS" a real number; the number of seconds for a crossfade between each image/video' : '.',
'DURATION_CROSSFADE_SECS': 0.5, # 0.5 sec is best. # could be 0.2
'; "CROSSFADE_TYPE" a string; the type of crossfade if DURATION_CROSSFADE_SECS > 0' : '.',
f'; "CROSSFADE_TYPE" must be one of {crossfade_type_list}' : '.',
'CROSSFADE_TYPE': 'random',
'; "CROSSFADE_DIRECTION" a string; the direction of crossfade type if DURATION_CROSSFADE_SECS > 0' : '.',
f'; "CROSSFADE_DIRECTION" must be one of {crossfade_direction_list}' : '.',
f'; CROSSFADE_DIRECTION" could be be one of "{vs_transitions.Direction.LEFT.value}" "{vs_transitions.Direction.RIGHT.value}" "{vs_transitions.Direction.UP.value}" "{vs_transitions.Direction.DOWN.value}" if crossfade type not "curtain_cover" or "curtain_reveal"' : '.',
f'; CROSSFADE_DIRECTION" could be be "{vs_transitions.Direction.HORIZONTAL.value}" or "{vs_transitions.Direction.VERTICAL.value}" if crossfade type is "curtain_cover" or "curtain_reveal"' : '.',
'CROSSFADE_DIRECTION': vs_transitions.Direction.LEFT.value,
'; "DURATION_MAX_VIDEO_SEC" a real number; the maximum number of seconds a video runs before it is clipped off' : '.',
'DURATION_MAX_VIDEO_SEC' : 15.0, # Maximum duration of a video clip in seconds (incoming video will get clipped at this point)
'; "DENOISE_SMALL_SIZE_VIDEOS" is True or False; if True, smaller framesize videos (which tend to be older and noisier) will be slightly denoised using mv.Degrain1' : '.',
'DENOISE_SMALL_SIZE_VIDEOS' : True,
'; "DEBUG_MODE" is True or False; if True, you will rue the day - an unbelievable volume of debug messages as used during development/debugging' : '.',
'DEBUG_MODE' : False,
'; Does not matter what you specify for TARGET_COLOR* stuff here, we always used fixed values ahs shown below' : '',
'; "TARGET_COLORSPACE" a string; set for HD; required to render subtitles, it is fixed at this value; this item MUST MATCH TARGET_COLORSPACE_MATRIX_I etc' : '.',
'TARGET_COLORSPACE' : r'BT.709', # for subtitling. # colorspace Rec2020, BT.2020 Rec709, BT.709, Rec601, BT.601, PC.709, PC.601, TV.fcc, PC.fcc, TV.240m, PC.240m; When no hint found in ASS script and colorspace parameter is empty then the default is BT.601
# ALSO ... A note about fixed output colour characteristics (the y4m YUV4MPEG2 container doesn't mention them.
# https://forum.videohelp.com/newreply.php?do=postreply&t=408230#post2684387
# So we always output BT.709 and related characteristics per what we specify here in _default_ini_values
'; "TARGET_COLORSPACE_MATRIX_I" an integer; set for HD; this is the value that counts; it is fixed at this value; turn on DEBUG_MODE to see lists of these values' : '.',
'TARGET_COLORSPACE_MATRIX_I' : int(vs.MatrixCoefficients.MATRIX_BT709.value),
'; "TARGET_COLOR_TRANSFER_I" an integer; set for HD; this is the value that counts; it is fixed at this value; used by Vapoursynth; turn on DEBUG_MODE to see lists of these values' : '.',
'TARGET_COLOR_TRANSFER_I' : int(vs.TransferCharacteristics.TRANSFER_BT709.value),
'; "TARGET_COLOR_PRIMARIES_I" an integer; set for HD; this is the value that counts; it is fixed at this value; turn on DEBUG_MODE to see lists of these values' : '.',
'TARGET_COLOR_PRIMARIES_I' : int(vs.ColorPrimaries.PRIMARIES_BT709.value),
# NOTE THESE IN REGARD TO VS "bug" in RANGE values not agreeing with the spec:
# https://github.com/vapoursynth/vapoursynth/issues/940
# https://github.com/vapoursynth/vapoursynth/issues/857
# https://github.com/vapoursynth/vapoursynth/issues/940#issuecomment-1465041338
# When calling rezisers etc, ONLY use these values:
# ZIMG_RANGE_LIMITED = 0, /**< Studio (TV) legal range, 16-235 in 8 bits. */
# ZIMG_RANGE_FULL = 1 /**< Full (PC) dynamic range, 0-255 in 8 bits. */
# but when obtaining from frame properties and comparing etc, use the vs values from
# frame properties even though the vapoursynth values are incorrect (opposite to the spec)
# BUT BUT BUT here we are working solely with vapoursynth settings, not resizers, so stick with using vapoursynth constants and not zimg ones
'; "TARGET_COLOR_RANGE_I" an integer; set for full-range, not limited-range; this is the (Vapoursynth) value that counts; it is fixed at this value; used by Vapoursynth; turn on DEBUG_MODE to see lists of these values' : '.',
'; "TARGET_COLOR_RANGE_I note: this Vapoursynth value is opposite to that needed by ZIMG and by resizers which require the ZIMG (the propeer) value; internal transations vs->zimg are done' : '.',
'TARGET_COLOR_RANGE_I' : int(vs.ColorRange.RANGE_FULL.value),
'; "TARGET_WIDTH" an integer; set for HD; do not change unless a dire emergency' : '.',
'TARGET_WIDTH' : 1920,
'; "TARGET_HEIGHT" an integer; set for HD; do not change unless a dire emergency' : '.',
'TARGET_HEIGHT' : 1080,
'; "TARGET_FPSNUM" an integer; set for PAL' : '.',
'TARGET_FPSNUM' : 25, # for fps numerator ... PAL world bias
'; "TARGET_FPSDEN" an integer; set for PAL' : '.',
'TARGET_FPSDEN' : 1, # for fps denominator ... PAL world bias
'; "UPSIZE_KERNEL" a string; do not change unless a dire emergency; you need the EXACT string name of the resizer' : '.',
'UPSIZE_KERNEL' : r'Lanczos',
'; "DOWNSIZE_KERNEL" a string; do not change unless a dire emergency; you need the EXACT string name of the resizer' : '.',
'DOWNSIZE_KERNEL' : r'Spline36',
'; "BOX" is True or False; if True, images and videos are resized vertically/horizontally to maintain aspect ratio and padded; False streches and squeezes ' : '.',
'BOX' : True, # True would initiate letterboxing or pillarboxing. False fills to TARGET_WIDTH,TARGET_HEIGHT
}
}
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: __init__: _default_ini_values=\n{objPrettyPrint.pformat(self._default_ini_values)}')
#for k, v in _default_ini_values[self._ini_section_name].items():
# if A_DEBUG_IS_ON: print_DEBUG(f'USING A FOR LOOP, _default_ini_values {objPrettyPrint.pformat(k)}"] = "{objPrettyPrint.pformat(v)}"')
self.read_ini_and_calculate_settings()
return
def read_ini_and_calculate_settings(self):
global IS_DEBUG
global A_DEBUG_IS_ON
self._ini_values = self._default_ini_values # default to the defaults funnily enough
config = None
config = configparser.ConfigParser(self._default_ini_values[self._ini_section_name], allow_no_value=True) # create a configparser objeft which also uses the default values we set above
reset_to_ini_defaults = False
if os.path.isfile(self.ini_file_specifying_parameters):
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: .ini file "{self.ini_file_specifying_parameters}" exists ... about to try reading that .ini file ...')
input_file = open(self.ini_file_specifying_parameters,'r')
config.read_file(input_file)
input_file.close()
if config.has_section(self._ini_section_name):
if config.has_option(self._ini_section_name, "DEBUG_MODE"):
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: config.has_option(self._ini_section_name, "DEBUG_MODE") detected in .ini, value={config.getboolean(self._ini_section_name, "DEBUG_MODE")}')
IS_DEBUG = config.getboolean(self._ini_section_name, "DEBUG_MODE") # if enabled, turn on DEBUG immediately
A_DEBUG_IS_ON = IS_DEBUG or IS_DEBUG_SYSTEM_OVERRIDE
###if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: "{self._ini_section_name}" detected in config, config={objPrettyPrint.pformat(config[self._ini_section_name].items())}')
#for k,v in config[self._ini_section_name].items():
# if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: \tRAW, READ FROM .ini WITH DEFAULTS: config["{self._ini_section_name}"]["{objPrettyPrint.pformat(k)}"] = {objPrettyPrint.pformat(v)}')
reset_to_ini_defaults = False
else:
print_NORMAL(f'ENCODER (legacy): class settings: read_ini_and_calculate_settings: WARNING: Missing section "{self._ini_section_name}" in .ini file "{self.ini_file_specifying_parameters}". Using defaults.')
reset_to_ini_defaults = True
else:
print_NORMAL(f'ENCODER (legacy): class settings: read_ini_and_calculate_settings: WARNING: Missing .ini file "{self.ini_file_specifying_parameters}". Using defaults.')
reset_to_ini_defaults = True
if reset_to_ini_defaults:
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: Reverting to default ini settngs')
config = configparser.ConfigParser(allow_no_value=True) # don't apply defaults here, do't want them written to the .ini file
# ... the ini is not yet fleshed out with extra values but re-save it anyway
config.read_dict(self._default_ini_values)
# re-write the .ini file with newly defaulted values
o_f = open(self.ini_file_specifying_parameters,'w')
config.write(o_f)
o_f.close()
# re-read the parameters from the newly re-created .ini file, applying defaults to the read operation
config = configparser.ConfigParser(self._default_ini_values[self._ini_section_name], allow_no_value=False)
i_f = open(self.ini_file_specifying_parameters,'r')
config.read_file(i_f)
i_f.close()
if config.has_option(self._ini_section_name, "DEBUG_MODE"):
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: .ini re-read: config.getboolean(self._ini_section_name, "DEBUG_MODE") detected value={config.getboolean(self._ini_section_name, "DEBUG_MODE")}')
IS_DEBUG = config.getboolean(self._ini_section_name, "DEBUG_MODE") # if enabled, turn on/off DEBUG_MODE immediately
A_DEBUG_IS_ON = IS_DEBUG or IS_DEBUG_SYSTEM_OVERRIDE
else:
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: Using settings from .ini file "{self.ini_file_specifying_parameters}"')
pass
if A_DEBUG_IS_ON: print_DEBUG(f'Final setting of DEBUG_MODE={config.getboolean(self._ini_section_name, "DEBUG_MODE")} ... global DEBUG_MODE={IS_DEBUG} A_DEBUG_IS_ON={A_DEBUG_IS_ON}')
#
# grab the .ini settings that the user has specified, or the defaults we have set, or combined both
if config.has_section(self._ini_section_name):
###if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: RAW config .ini read as config.get(self._ini_section_name, "DIRECTORY_LIST")={config.get(self._ini_section_name, "DIRECTORY_LIST")}')
self._ini_values[self._ini_section_name]["DIRECTORY_LIST"] = ast.literal_eval(config.get(self._ini_section_name, 'DIRECTORY_LIST')) # convert str back into a list with ast
###if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: RAW config .ini read as self._ini_values[self._ini_section_name]["DIRECTORY_LIST"]={self._ini_values[self._ini_section_name]["DIRECTORY_LIST"]}')
ddl_fully_qualified = [] # make DIRECTORY_LIST entries all fully qualified and escaped where required
for ddl in self._ini_values[self._ini_section_name]["DIRECTORY_LIST"]:
ddl_fully_qualified.append(UTIL.fully_qualified_directory_no_trailing_backslash(ddl))
self._ini_values[self._ini_section_name]["DIRECTORY_LIST"] = ddl_fully_qualified
###if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: RAW config .ini read as config.get(self._ini_section_name, "TEMP_DIRECTORY_LIST")={config.get(self._ini_section_name, "TEMP_DIRECTORY_LIST")}')
self._ini_values[self._ini_section_name]["TEMP_DIRECTORY_LIST"] = ast.literal_eval(config.get(self._ini_section_name, 'TEMP_DIRECTORY_LIST')) # convert str back into a list
###if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: RAW config .ini read as self._ini_values[self._ini_section_name]["TEMP_DIRECTORY_LIST"]={self._ini_values[self._ini_section_name]["TEMP_DIRECTORY_LIST"]}')
td_fully_qualified = []
for td in self._ini_values[self._ini_section_name]["TEMP_DIRECTORY_LIST"]: # should only be 1 in the list. if more then we convert them all but only use the first
td_fully_qualified.append(UTIL.fully_qualified_directory_no_trailing_backslash(td))
self._ini_values[self._ini_section_name]["TEMP_DIRECTORY_LIST"] = td_fully_qualified
###if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: RAW config .ini read as config.get(self._ini_section_name, "SNIPPETS_FILENAME_PATH_LIST")={config.get(self._ini_section_name, "SNIPPETS_FILENAME_PATH_LIST")}')
self._ini_values[self._ini_section_name]["SNIPPETS_FILENAME_PATH_LIST"] = ast.literal_eval(config.get(self._ini_section_name, 'SNIPPETS_FILENAME_PATH_LIST')) # convert str back into a list
###if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: RAW config .ini read as self._ini_values[self._ini_section_name]["SNIPPETS_FILENAME_PATH_LIST"]={self._ini_values[self._ini_section_name]["SNIPPETS_FILENAME_PATH_LIST"]}')
sfp_fully_qualified = []
for sfp in self._ini_values[self._ini_section_name]["SNIPPETS_FILENAME_PATH_LIST"]: # should only be 1 in the list. if more then we convert them all but only use the first
sfp_fully_qualified.append(UTIL.fully_qualified_filename(sfp))
self._ini_values[self._ini_section_name]["SNIPPETS_FILENAME_PATH_LIST"] = sfp_fully_qualified
###if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: RAW config .ini read as config.get(self._ini_section_name, "OUTPUT_MKV_FILENAME_PATH_LIST")={config.get(self._ini_section_name, "OUTPUT_MKV_FILENAME_PATH_LIST")}')
self._ini_values[self._ini_section_name]["OUTPUT_MKV_FILENAME_PATH_LIST"] = ast.literal_eval(config.get(self._ini_section_name, 'OUTPUT_MKV_FILENAME_PATH_LIST')) # convert str back into a list
###if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: RAW config .ini read as self._ini_values[self._ini_section_name]["OUTPUT_MKV_FILENAME_PATH_LIST"]={self._ini_values[self._ini_section_name]["OUTPUT_MKV_FILENAME_PATH_LIST"]}')
amf_fully_qualified = []
for amf in self._ini_values[self._ini_section_name]["OUTPUT_MKV_FILENAME_PATH_LIST"]: # should only be 1 in the list. if more then we convert them all but only use the first
amf_fully_qualified.append(UTIL.fully_qualified_filename(amf))
self._ini_values[self._ini_section_name]["OUTPUT_MKV_FILENAME_PATH_LIST"] = amf_fully_qualified
self._ini_values[self._ini_section_name]["RECURSIVE"] = config.getboolean(self._ini_section_name, 'RECURSIVE')
self._ini_values[self._ini_section_name]["SUBTITLE_DEPTH"] = int(config.getint(self._ini_section_name, 'SUBTITLE_DEPTH'))
self._ini_values[self._ini_section_name]["SUBTITLE_FONTSIZE"] = int(config.getint(self._ini_section_name, 'SUBTITLE_FONTSIZE'))
self._ini_values[self._ini_section_name]["SUBTITLE_FONTSCALE"] = float(config.getfloat(self._ini_section_name, 'SUBTITLE_FONTSCALE'))
self._ini_values[self._ini_section_name]["DURATION_PIC_SEC"] = float(config.getfloat(self._ini_section_name, 'DURATION_PIC_SEC'))
self._ini_values[self._ini_section_name]["DURATION_CROSSFADE_SECS"] = float(config.getfloat(self._ini_section_name, 'DURATION_CROSSFADE_SECS'))
self._ini_values[self._ini_section_name]["CROSSFADE_TYPE"] = config.get(self._ini_section_name, 'CROSSFADE_TYPE')
self._ini_values[self._ini_section_name]["CROSSFADE_DIRECTION"] = config.get(self._ini_section_name, 'CROSSFADE_DIRECTION')
self._ini_values[self._ini_section_name]["DURATION_MAX_VIDEO_SEC"] = float(config.getfloat(self._ini_section_name, 'DURATION_MAX_VIDEO_SEC'))
self._ini_values[self._ini_section_name]["DENOISE_SMALL_SIZE_VIDEOS"] = config.getboolean(self._ini_section_name, 'DENOISE_SMALL_SIZE_VIDEOS')
self._ini_values[self._ini_section_name]["DEBUG_MODE"] = config.getboolean(self._ini_section_name, 'DEBUG_MODE')
# A note about fixed output colour characteristics (the y4m YUV4MPEG2 container doesn't mention them.
# https://forum.videohelp.com/newreply.php?do=postreply&t=408230#post2684387
# So we always output BT.709 and related characteristics per what we specify in self._default_ini_values
# Hence we comment out TARGET_COLOR* ini-read stuff so as to only use our DEFAULT settings and take the defaults from self._default_ini_values we poked in earlier
#self._ini_values[self._ini_section_name]["TARGET_COLORSPACE"] = config.get(self._ini_section_name, 'TARGET_COLORSPACE') # for subtitliing
#self._ini_values[self._ini_section_name]["TARGET_COLORSPACE_MATRIX_I"] = int(config.getint(self._ini_section_name, 'TARGET_COLORSPACE_MATRIX_I'))
#self._ini_values[self._ini_section_name]["TARGET_COLOR_TRANSFER_I"] = int(config.getint(self._ini_section_name, 'TARGET_COLOR_TRANSFER_I'))
#self._ini_values[self._ini_section_name]["TARGET_COLOR_PRIMARIES_I"] = int(config.getint(self._ini_section_name, 'TARGET_COLOR_PRIMARIES_I'))
#self._ini_values[self._ini_section_name]["TARGET_COLOR_RANGE_I"] = int(config.get(self._ini_section_name, 'TARGET_COLOR_RANGE_I'))
self._ini_values[self._ini_section_name]["TARGET_WIDTH"] = int(config.getint(self._ini_section_name, 'TARGET_WIDTH'))
self._ini_values[self._ini_section_name]["TARGET_HEIGHT"] = int(config.getint(self._ini_section_name, 'TARGET_HEIGHT'))
self._ini_values[self._ini_section_name]["TARGET_FPSNUM"] = int(config.getint(self._ini_section_name, 'TARGET_FPSNUM'))
self._ini_values[self._ini_section_name]["TARGET_FPSDEN"] = int(config.getint(self._ini_section_name, 'TARGET_FPSDEN'))
self._ini_values[self._ini_section_name]["UPSIZE_KERNEL"] = config.get(self._ini_section_name, 'UPSIZE_KERNEL')
self._ini_values[self._ini_section_name]["DOWNSIZE_KERNEL"] = config.get(self._ini_section_name, 'DOWNSIZE_KERNEL')
self._ini_values[self._ini_section_name]["BOX"] = config.getboolean(self._ini_section_name, 'BOX')
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: values read in from the .ini values (defaults applied from the .ini file)')
else:
raise ValueError(f'class settings: read_ini_and_calculate_settings: ERROR: .ini file unable to be read or recreated properly')
# add EXTRA clarifying information to and re-save the updated set of .ini values over the top of the existing .ini file
with open(self.ini_file_specifying_parameters, 'w') as configfile:
# add the new set of .ini value to be saved
update_config = configparser.ConfigParser(allow_no_value=True)
##update_config[self._ini_section_name] = self._default_ini_values[self._ini_section_name]
update_config[self._ini_section_name] = self._ini_values[self._ini_section_name]
# add example values to make it easier for a human reader of the .ini file
tmp_name = 'Enum_vs.MatrixCoefficients'
tmp_dict = { tmp_name : {}}
for v in vs.MatrixCoefficients:
tmp_dict[tmp_name][str(v)] = v.value
pass
update_config[tmp_name] = tmp_dict[tmp_name]
tmp_name = 'Enum_vs.TransferCharacteristics'
tmp_dict = { tmp_name : {}}
for v in vs.TransferCharacteristics:
tmp_dict[tmp_name][str(v)] = v.value
pass
update_config[tmp_name] = tmp_dict[tmp_name]
tmp_name = 'Enum_vs.ColorPrimaries'
tmp_dict = { tmp_name : {}}
for v in vs.ColorPrimaries:
tmp_dict[tmp_name][str(v)] = v.value
pass
update_config[tmp_name] = tmp_dict[tmp_name]
tmp_name = 'Enum_vs.ColorRange'
tmp_dict = { tmp_name : {}}
for v in vs.ColorRange:
tmp_dict[tmp_name][str(v)] = v.value
pass
update_config[tmp_name] = tmp_dict[tmp_name]
tmp_name = 'Enum_ZIMG.ColorRange'
tmp_dict = { tmp_name : {"ZIMG.RANGE_LIMITED" : ZIMG_RANGE_LIMITED, "ZIMG.RANGE_FULL" : ZIMG_RANGE_FULL}}
update_config[tmp_name] = tmp_dict[tmp_name]
tmp_name = 'Enum_vs.PresetFormat'
tmp_dict = { tmp_name : {}}
for v in vs.PresetFormat:
tmp_dict[tmp_name][str(v)] = v.value
pass
update_config[tmp_name] = tmp_dict[tmp_name]
tmp_name = 'Enum_vs.ColorFamily'
tmp_dict = { tmp_name : {}}
for v in vs.ColorFamily:
tmp_dict[tmp_name][str(v)] = v.value
pass
update_config[tmp_name] = tmp_dict[tmp_name]
tmp_name = 'Enum_vs.ChromaLocation'
tmp_dict = { tmp_name : {}}
for v in vs.ChromaLocation:
tmp_dict[tmp_name][str(v)] = v.value
pass
update_config[tmp_name] = tmp_dict[tmp_name]
tmp_name = 'Enum_vs.FieldBased'
tmp_dict = { tmp_name : {}}
for v in vs.FieldBased:
tmp_dict[tmp_name][str(v)] = v.value
pass
update_config[tmp_name] = tmp_dict[tmp_name]
# update the .ini file
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: Saving updated .ini file: ini_values=\n{objPrettyPrint.pformat(self._ini_values)}')
update_config.write(configfile)
print_NORMAL(f'ENCODER (legacy): class settings: read_ini_and_calculate_settings: Saved updated .ini "{self.ini_file_specifying_parameters}"')
# calculate required values and create a new updated calculated values dict
self.calc_ini = self._ini_values[self._ini_section_name]
self.calc_ini["PIC_EXTENSIONS"] = [".png", ".jpg", ".jpeg", ".gif"] # always lower case
self.calc_ini["VID_EXTENSIONS"] = [".mp4", ".mpeg4", ".mpg", ".mpeg", ".avi", ".mjpeg", ".3gp", ".mov"] # always lower case
self.calc_ini["EEK_EXTENSIONS"] = [".m2ts"] # always lower case
self.calc_ini["VID_EEK_EXTENSIONS"] = self.calc_ini["VID_EXTENSIONS"] + self.calc_ini["EEK_EXTENSIONS"]
self.calc_ini["EXTENSIONS"] = self.calc_ini["PIC_EXTENSIONS"] + self.calc_ini["VID_EXTENSIONS"] + self.calc_ini["EEK_EXTENSIONS"]
self.calc_ini["WORKING_PIXEL_FORMAT"] = vs.YUV444P8 # int(vs.YUV444P8.value) # pixel format of the working clips (mainly required by vs_transitions)
self.calc_ini["TARGET_PIXEL_FORMAT"] = vs.YUV420P8 # int(vs.YUV420P8.value) # pixel format of the target video
self.calc_ini["DG_PIXEL_FORMAT"] = vs.YUV420P16 # int(vs.YUV420P16.value) # pixel format of the video for use by DG tools
self.calc_ini["TARGET_FPS"] = round(self.calc_ini["TARGET_FPSNUM"] / self.calc_ini["TARGET_FPSDEN"], 3)
self.calc_ini["DURATION_PIC_FRAMES"] = int(math.ceil(self.calc_ini["DURATION_PIC_SEC"] * self.calc_ini["TARGET_FPS"]))
self.calc_ini["DURATION_CROSSFADE_FRAMES"] = int(math.ceil(self.calc_ini["DURATION_CROSSFADE_SECS"] * self.calc_ini["TARGET_FPS"]))
self.calc_ini["DURATION_BLANK_CLIP_FRAMES"] = self.calc_ini["DURATION_CROSSFADE_FRAMES"] + 1 # make equal to the display time for an image; DURATION_CROSSFADE_FRAMES will be less than this
self.calc_ini["DURATION_MAX_VIDEO_FRAMES"] = int(math.ceil(self.calc_ini["DURATION_MAX_VIDEO_SEC"] * self.calc_ini["TARGET_FPS"]))
self.calc_ini["DOT_FFINDEX"] = ".ffindex".lower() # for removing temporary *.ffindex files at the end
self.calc_ini["MODX"] = int(2) # mods for letterboxing calculations, example, for 411 YUV as an extreme
self.calc_ini["MODY"] = int(2) # mods would have to be MODX=4, MODY=1 as minimum
self.calc_ini["SUBTITLE_MAX_DEPTH"] = int(10)
self.calc_ini["Rotation_anti_clockwise"] = "anti-clockwise".lower()
self.calc_ini["Rotation_clockwise"] = "clockwise".lower()
self.calc_ini["TARGET_VFR_FPSNUM"] = self.calc_ini["TARGET_FPSNUM"] * 2
self.calc_ini["TARGET_VFR_FPSDEN"] = self.calc_ini["TARGET_FPSDEN"]
self.calc_ini["TARGET_VFR_FPS"] = self.calc_ini["TARGET_VFR_FPSNUM"] / self.calc_ini["TARGET_VFR_FPSDEN"]
self.calc_ini["precision_tolerance"] = 0.0002 # used in float comarisons eg fps calculations and comparisons so do not have to use "==" which would almost never work
# https://github.com/vapoursynth/vapoursynth/issues/940#issuecomment-1465041338
# When calling rezisers etc, ONLY use these values:
# ZIMG_RANGE_LIMITED = 0, /**< Studio (TV) legal range, 16-235 in 8 bits. */
# ZIMG_RANGE_FULL = 1 /**< Full (PC) dynamic range, 0-255 in 8 bits. */
# but when obtaining from frame properties and comparing etc, use the vs values from
# frame properties even though the vapoursynth values are incorrect (opposite to the spec)
# https://www.vapoursynth.com/doc/api/vapoursynth.h.html#enum-vspresetformat
if self.calc_ini["TARGET_COLOR_RANGE_I"] == int(vs.ColorRange.RANGE_LIMITED.value):
self.calc_ini["TARGET_COLOR_RANGE_I_ZIMG"] = ZIMG_RANGE_LIMITED # use the ZIMG RANGE constants as they are correct and vapoursynth ones are not (opposite to the spec)
elif self.calc_ini["TARGET_COLOR_RANGE_I"] == int(vs.ColorRange.RANGE_FULL.value):
self.calc_ini["TARGET_COLOR_RANGE_I_ZIMG"] = ZIMG_RANGE_FULL # use the ZIMG RANGE constants as they are correct and vapoursynth ones are not (opposite to the spec)
else:
raise ValueError(f'class settings: read_ini_and_calculate_settings: ERROR: self.calc_ini["TARGET_COLOR_RANGE_I"]={self.calc_ini["TARGET_COLOR_RANGE_I"]} is an invalid value')
#++++++++++++++++++++
# Consistency checks
min_actual_display_time = 0.5 # seconds
if (2 * self._ini_values[self._ini_section_name]["DURATION_CROSSFADE_SECS"]) + min_actual_display_time > self._ini_values[self._ini_section_name]["DURATION_PIC_SEC"]:
raise ValueError(f'class settings: read_ini_and_calculate_settings: ERROR: DURATION_PIC_SEC must be >= (2 * DURATION_CROSSFADE_SECS) + min_actual_display_time \n\ DURATION_CROSSFADE_SECS={self._ini_values[self._ini_section_name]["DURATION_CROSSFADE_SECS"]} DURATION_PIC_SEC={self._ini_values[self._ini_section_name]["DURATION_PIC_SEC"]} min_actual_display_time={min_actual_display_time}')
if (2 * self._ini_values[self._ini_section_name]["DURATION_CROSSFADE_SECS"]) + min_actual_display_time > self._ini_values[self._ini_section_name]["DURATION_MAX_VIDEO_SEC"]:
raise ValueError(f'class settings: read_ini_and_calculate_settings: ERROR: DURATION_MAX_VIDEO_SEC must be >= (2 * DURATION_CROSSFADE_SECS) + min_actual_display_time \n\ DURATION_CROSSFADE_SECS={self._ini_values[self._ini_section_name]["DURATION_CROSSFADE_SECS"]} DURATION_MAX_VIDEO_SEC={self._ini_values[self._ini_section_name]["DURATION_MAX_VIDEO_SEC"]} min_actual_display_time={min_actual_display_time}')
#++++++++++++++++++++
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: ----------------------------------------------------------------------------------------------------------------------------')
for v in vs.PresetFormat: # eg vs.YUV420P8
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: vs.PresetFormat ENUM: {str(v)} = {v.value}')
pass
for v in vs.MatrixCoefficients:
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: vs.MatrixCoefficients ENUM: {str(v)} = {v.value}')
pass
for v in vs.TransferCharacteristics:
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: vs.TransferCharacteristics ENUM: {str(v)} = {v.value}')
pass
for v in vs.ColorPrimaries:
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: vs.ColorPrimaries ENUM: {str(v)} = {v.value}')
pass
for v in vs.ColorRange:
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: vs.ColorRange ENUM: {str(v)} = {v.value}')
pass
for v in vs.ColorFamily:
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: vs.ColorFamily ENUM: {str(v)} = {v.value}')
pass
for v in vs.ChromaLocation:
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: vs.ChromaLocation ENUM: {str(v)} = {v.value}')
pass
for v in vs.FieldBased:
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: vs.FieldBased ENUM: {str(v)} = {v.value}')
pass
###if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: ----------------------------------------------------------------------------------------------------------------------------')
###if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: \nself._default_ini_values=\n{objPrettyPrint.pformat(self._default_ini_values)}')
###if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: ----------------------------------------------------------------------------------------------------------------------------')
###if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: \nself._ini_values=\n{objPrettyPrint.pformat(self._ini_values)}')
###if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: ----------------------------------------------------------------------------------------------------------------------------')
###if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: \nself.calc_ini=\n{objPrettyPrint.pformat(self.calc_ini)}')
###if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: ----------------------------------------------------------------------------------------------------------------------------')
#
# make class variables from the self.calc_ini dictionary # https://www.geeksforgeeks.org/how-to-change-a-dictionary-into-a-class/
for key in self.calc_ini:
if not key.startswith(';'):
setattr(self, key, self.calc_ini[key]) # this updates existing variables with new values
# Having made class variables from the self.calc_ini dictionary
# we can read them as normal class variables like thing.variable_name
# or as dictionary variables like thing.calc_ini["key_name"]
# *** Remembering they are separate variabkes and overwriting one does NOT overwrite the other and mismatches will then occur ...
# OR ...
# self.__dict__.update(self.calc_ini) # per https://www.sobyte.net/post/2022-04/python-dict-2-member-variables/ # this updates existing variables with new values per https://www.geeksforgeeks.org/python-dictionary-update-method/
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: ----------------------------------------------------------------------------------------------------------------------------------')
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: ----------------------------------------------------------------------------------------------------------------------------------')
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: CLASS VARIABLES AND VALUES:\n{objPrettyPrint.pformat(self.class_variables_and_values())}')
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: ----------------------------------------------------------------------------------------------------------------------------------')
if A_DEBUG_IS_ON: print_DEBUG(f'class settings: read_ini_and_calculate_settings: ----------------------------------------------------------------------------------------------------------------------------------')
return
###
def get_mediainfo_specs(path: Union[Path,str]):
# THIS IS A CUSTOM FUNCTION
# WHICH DOES ADDITIONAL THINGS WITH RETURNED VALUES BESIDE RETRIEVING THEM
mi_video_params = [
'Format', # : Format used
'Format/String', # : Format used + additional features
'Format_Profile', # : Profile of the Format (old XML Profile@Level@Tier format
'Format_Level', # : Level of the Format (only MIXML)
'Format_Tier', # : Tier of the Format (only MIXML)
'HDR_Format', # : Format used
'HDR_Format_Version', # : Version of this format
'HDR_Format_Profile', # : Profile of the Format
'HDR_Format_Level', # : Level of the Format
'HDR_Format_Settings', # : Settings of the Format
'HDR_Format_Compatibility', # : Compatibility with some commercial namings
'MaxCLL', # : Maximum content light level
'MaxFALL', # : Maximum frame average light level
'Duration', # : Play time of the stream in ms
'Width', # : Width (aperture size if present) in pixel
'Height', # : Height in pixel
'PixelAspectRatio', # : Pixel Aspect ratio
'DisplayAspectRatio', # : Display Aspect ratio
'Rotation', # : Rotation as a real number eg 180.00 # CLOCKWISE in mediainfo
'FrameRate', # : Frames per second
'FrameRate_Num', # : Frames per second, numerator
'FrameRate_Den', # : Frames per second, denominator
'FrameCount', # : Number of frames
#
'Recorded_Date', # : Time/date/year that the recording began ... this can be None so use Encoded_Date instead. date_recorded = datetime.strptime(mi_dict["Recorded_Date"], "%Y-%m-%d %H:%M:%S UTC")
'Encoded_Date', # : Time/date/year that the encoding of this content was completed. date_encoded = datetime.strptime(mi_dict["Encoded_Date"], "%Y-%m-%d %H:%M:%S UTC")
#
'FrameRate_Mode', # : Frame rate mode (CFR, VFR)
'FrameRate_Minimum', # : Minimum Frames per second
'FrameRate_Nominal', # : Nominal Frames per second
'FrameRate_Maximum', # : Maximum Frames per second
'FrameRate_Real', # : Real (capture) frames per second
'ScanType', # : ??? progressive interlaced
'ScanOrder', # : ??? TFF BFF
'ScanOrder_Stored',
'ScanOrder_StoredDisplayedInverted',
#
'Standard', # : NTSC or PAL
'ColorSpace', # :
'ChromaSubsampling', # :
'BitDepth', # : 16/24/32
'ScanType', # :
'colour_description_present', # : Presence of colour description "Yes" or not "Yes" if not None
'colour_range', # : Colour range for YUV colour space
'colour_primaries', # : Chromaticity coordinates of the source primaries
'transfer_characteristics', # : Opto-electronic transfer characteristic of the source picture
'matrix_coefficients', # : Matrix coefficients used in deriving luma and chroma signals from the green, blue, and red primaries
]
###if A_DEBUG_IS_ON: print_DEBUG(f'get_mediainfo_specs: path={path} type(path)={type(path)} mi_video_params=\n{objPrettyPrint.pformat(mi_video_params)}')
mi_video_dict = {'path' : path } | mediainfo_value_dict(Stream.Video, 0, mi_video_params, path) # returns a filled-in dict, with keys and possibly None values
if mi_video_dict["FrameCount"] is None or mi_video_dict["FrameCount"] <= 0: mi_video_dict["FrameCount"] = 0
if mi_video_dict["FrameRate"] is None or mi_video_dict["FrameRate"] <=0 :
mi_video_dict["FrameRate"] = 0
mi_video_dict["FrameRate_Num"] = 0
mi_video_dict["FrameRate_Den"] = 0
mi_video_dict["FrameRate_Minimum"] = 0
mi_video_dict["FrameRate_Nominal"] = 0
mi_video_dict["FrameRate_Maximum"] = 0
mi_video_dict["FrameRate_Real"] = 0
if mi_video_dict["FrameRate_Mode"] is None: mi_video_dict["FrameRate_Mode"] = "CFR"
if mi_video_dict["ScanType"] is None: mi_video_dict["ScanType"] = "Progressive"
if mi_video_dict["ScanOrder"] is None: mi_video_dict["ScanOrder"] = "TFF" # IF SCAN ORDER IS BFF then yadif/zeedi settngs will be different for deinterlacing
if mi_video_dict["FrameRate_Nominal"] is None: mi_video_dict["FrameRate_Nominal"] = mi_video_dict["FrameRate"]
# sometimes, who knows why, mediainfo returns NO FrameRate_Num/FrameRate_Den although FrameRate is returned
if mi_video_dict["FrameRate_Num"] is None:
mi_video_dict["FrameRate_Num"] = int(mi_video_dict["FrameRate"] * 1000.0)
mi_video_dict["FrameRate_Den"] = 1000
## REMINDER: if FPS was zero from mediainfo here, we set it to clip.fps values when in get_clip_from_path
###if A_DEBUG_IS_ON: print_DEBUG(f'get_mediainfo_specs: mediainfo specs=\n{objPrettyPrint.pformat(mi_video_dict)}')
return mi_video_dict
###
def mediainfo_value_dict(stream:int, track:int, param:list, path: Union[Path,str]) -> Union[int,float,str]:
# A wrapper for mediainfo_value_worker
# Given a LIST of parameter names, return a dict of names/values of properties
# eg
# param:
# [ 'ColorSpace', # :
# 'ChromaSubsampling', # :
# 'BitDepth', # : 16/24/32
# 'ScanType', # :
# 'colour_description_present', # : Presence of colour description "Yes" or not "Yes" if not None
# 'colour_range', # : Colour range for YUV colour space
# 'colour_primaries', # : Chromaticity coordinates of the source primaries
# 'transfer_characteristics', # : Opto-electronic transfer characteristic of the source picture
# 'matrix_coefficients', # : Matrix coefficients used in deriving luma and chroma signals from the green, blue, and red primaries
# ]
# returns something like this (some values can be None):
# {'ColorSpace': 'YUV', 'ChromaSubsampling': '4:2:0', 'BitDepth': 8, 'ScanType': 'Progressive',
# 'colour_description_present': 'Yes', 'colour_range': 'Limited', 'colour_primaries': 'BT.709',
# 'transfer_characteristics': 'BT.709', 'matrix_coefficients': 'BT.709'}
#global MI
if not stream in range(0,8):
raise ValueError(f'ERROR: mediainfo_value_dict: stream must be a Stream attribute: General, Video, Audio, Text, Other, Image, Menu, Max')
if not isinstance(track, int) or track<0:
raise ValueError(f'ERROR: mediainfo_value_dict: track must be a positive integer')
if not isinstance(param, list):
raise ValueError(f'ERROR: mediainfo_value_dict: param must be a list of str parameters for a particular stream, in_Static("Info_Parameters")') # https://github.com/MediaArea/MediaInfoLib/blob/master/Source/Example/HowToUse_Dll3.py
if not isinstance(path, (Path, str)):
raise ValueError(f'ERROR: mediainfo_value_dict: path must be Path or str class')
MI = MediaInfo()
MI.Open(str(path))
local_dict = {}
for p in param:
value = mediainfo_value_worker(MI, stream, track, p, path)
local_dict[p] = value # any of str, int, float, or None
###if A_DEBUG_IS_ON: print_DEBUG(f'"{p}" = \t\t\t\t"{value}"\t\t\ttype={type(value)}\t\t\tisinstance(value,str)={isinstance(value,str)}\t\tisinstance(value,int)={isinstance(value,int)}\t\tisinstance(value,bool)={isinstance(value,bool)}\t\tisinstance(value,float)={isinstance(value,float)}')
MI.Close()
del MI # free the object
return local_dict
###
def mediainfo_value(stream:int, track:int, param:str, path: Union[Path,str]) -> Union[int,float,str]:
# A wrapper for mediainfo_value_worker, which gets and returns a single parameter
# This function permits mediainfo_value_worker to be recycled elsewhere to be called mutiple times per a single MI.open
#global MI
if not stream in range(0,8):
raise ValueError(f'ERROR: mediainfo_value: stream must be a Stream attribute: General, Video, Audio, Text, Other, Image, Menu, Max')
if not isinstance(track, int) or track<0:
raise ValueError(f'ERROR: mediainfo_value: track must be a positive integer')
if not isinstance(param, str):
raise ValueError(f'ERROR: mediainfo_value: param must be a string for particular stream, in_Static("Info_Parameters")') # https://github.com/MediaArea/MediaInfoLib/blob/master/Source/Example/HowToUse_Dll3.py
if not isinstance(path, (Path, str)):
raise ValueError(f'ERROR: mediainfo_value: path must be Path or str class')
MI = MediaInfo()
MI.Open(str(path))
val = mediainfo_value_worker(MI, stream, track, param, path)
MI.Close()
del MI # free the object
return val
###
def mediainfo_value_worker(MI, stream:int, track:int, param:str, path: Union[Path,str]) -> Union[int,float,str]:
# gets and returns a single parameter
#global MI
if not stream in range(0,8):
raise ValueError(f'ERROR: mediainfo_value_worker: stream must be a Stream attribute: General, Video, Audio, Text, Other, Image, Menu, Max')
if not isinstance(track, int) or track<0:
raise ValueError(f'ERROR: mediainfo_value_worker: track must be a positive integer')
if not isinstance(param, str):
raise ValueError(f'ERROR: mediainfo_value_worker: param must be a string for particular stream, in_Static("Info_Parameters")') # https://github.com/MediaArea/MediaInfoLib/blob/master/Source/Example/HowToUse_Dll3.py
if not isinstance(path, (Path, str)):
raise ValueError(f'ERROR: mediainfo_value_worker: path must be Path or str class')
#MI = MediaInfo()
#MI.Open(str(path)) # CHANGED: open/close in calling routine, allowing this to be called mutiple times
str_value = MI.Get(stream, track, param)
info_option = MI.Get(stream, track, param, InfoKind=Info.Options)
#MI.Close() # CHANGED: open/close in calling routine, allowing this to be called mutiple times
#del MI # free the object
if not str_value:
del str_value
del info_option
return None
if info_option:
#returning a proper value type, int, float or str for particular parameter
type_ = info_option[InfoOption.TypeOfValue] #type_=info_option[3] #_type will be 'I', 'F', 'T', 'D' or 'B'
try: # sometimes mediainfo flags an INT or a FLOAT which cannou be ocnverted, so catch those
val = {'I':int, 'F':float, 'T':str, 'D':str, 'B':str}[type_](str_value)
except Exception as e:
if A_DEBUG_IS_ON: print_DEBUG(f'CONVERSION EXCEPTION ON val =["I":int, "F":float, "T":str, "D":str, "B":str][type_](str_value) ... type_="{type_}" param="{param}" str_value="{str_value}" path={path}')
if A_DEBUG_IS_ON: print_DEBUG(f"Unexpected Error {e=}, {type(e)=} {str(e)=}")
val = None
#raise
pass
else:
raise ValueError(f'ERROR: mediainfo_value_worker: wrong parameter: "{param}" for given stream: {stream}')
del str_value
del info_option
return val
###
def boxing(clip, W, H):
# ensure aspect ratio of an original image/video is preserved by adding black bars where necessary
source_width, source_height = clip.width, clip.height
if W/H > source_width/source_height:
w = source_width*H/source_height
x = int((W-w)/2)
x = x - x%objSettings.MODX
x = max(0, min(x,W))
clip = resize_clip(clip, W-2*x, H)
if x:
return clip.std.AddBorders(left=x, right=x, color=(16,128,128)) #RGB is out then (16,16,16)
else:
return clip
else:
h = source_height*W/source_width
y = int((H-h)/2)
y = y - y%objSettings.MODY
y = max(0, min(y,H))
clip = resize_clip(clip, W, H-2*y)
if y:
return clip.std.AddBorders(top=y, bottom=y, color=(16,128,128))
else:
return clip
###
def write_props(clip, **kwargs):
# function borrowed from _AI_ and modified to be API4 only and R62+ only add use json.dumps(value) on type 'list' as well, added _ColorRange
'''
kwargs are: prop1=value1, prop2=value2, ... this will work for API4 ONLY
Keys are strings only, values can be: int, str, lists or dictionaries.
As for dictionaries, whatever json allows. Not wanting to go into annotations nightmare for it,
if it is a dictionary passed as a value, it can be whatever json module can decode to bytes.
As for lists and tuples, values can be int, float, str, same type for a particular list.
Note: If complicated values, use a dictionary! json module is used to write to bytes, and that is stored to a prop.
Then it is read from bytes back to a dictionary by json again in read_prop(), so structure can be really complicated one.
Example:
clip = write_props(
clip,
_FieldBased = 1,
any_string = 'dogs',
data = {'clip_name':'Kittens', 'litter_of':3, 'names': {'fluffy':'Anna','ginger':'Bob','mottled':'Jen'}},
filters = {'denoise':['core','fft3dfilter','FFT3DFilter',{'sigma':1.5}]},
integer_list = [2, 6],
string_list = ['apples','oranges']
)
'''
TRANSFER = {
## 0:'reserved',
1:'709',
2:'unspec',
## 3:'reserved',
4:'470m',
5:'470bg',
6:'601',
7:'240m',
8:'linear',
9:'log100',
10:'log316',