-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlasfunc.py
2133 lines (1757 loc) · 98 KB
/
lasfunc.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
import vapoursynth as vs
import math
import os
import subprocess
import functools
from typing import Optional, Union, List, NamedTuple, Literal
# https://peps.python.org/pep-0483/#fundamental-building-blocks
# Requriements: imwri, mvtools, fmtc, rgvs, rgsf, flux,
# ctmf, vs-noise, adaptivegrain, znedi3,
# tcanny, neo_f3kdb
# Docs
# https://github.com/vapoursynth/vs-imwri/blob/master/docs/imwri.rst
# http://avisynth.org.ru/mvtools/mvtools2.html
# https://github.com/dubhater/vapoursynth-mvtools
# https://amusementclub.github.io/fmtconv/doc/fmtconv.html
# https://github.com/dubhater/vapoursynth-fluxsmooth
# https://github.com/IFeelBloated/RGSF
# https://github.com/HomeOfVapourSynthEvolution/VapourSynth-CTMF
# https://github.com/wwww-wwww/vs-noise
# https://git.kageru.moe/kageru/adaptivegrain
# https://github.com/sekrit-twc/znedi3
# https://github.com/HomeOfVapourSynthEvolution/VapourSynth-TCanny
# https://github.com/HomeOfAviSynthPlusEvolution/neo_f3kdb
# https://f3kdb.readthedocs.io/en/stable/usage.html
class check:
#-----------------------------------------------------------------------
# check functions
# check_deps(["fmtc", "mv", "mvsf"])
# check_fmt(clip, ["yuv", "-444"]) # yuv and not 444
# check_fmt(clip, ["32"]) # RGB 32 float
# check_fmt(clip, ["-RGB"]) # anything but RGB
# check_fmt_clips([clipa, clipb]) # clips must be of same formats
# #-----------
# import inspect
# def first():
# return second()
# def second():
# return inspect.getouterframes( inspect.currentframe() )[1]
# first()[3] # 'first'
# #-----------
#-----------------------------------------------------------------------
def deps(deps:List[str]):
pass
def fmt(clips:Union[List[vs.VideoNode],vs.VideoNode], fmts:List[str]):
pass
def fmt_multi(clips:List[vs.VideoNode], fmts:Optional[List[str]]):
pass
class helper:
def round_to_closest(x:Union[int, float]) -> int:
# I'm amazed that's not a thing.
if x - math.floor(x) < 0.5:
return math.floor(x)
return math.ceil(x)
def scale_depth(i:int, depth_out:int=16, depth_in:int=8) -> int:
# converting the values in one depth to another
return i*2**(depth_out-depth_in)
def scale255(value:int, peak:int) -> int:
return helper.round_to_closest(peak * value/255)
def mod_m(x:Union[int, float], m:Union[int, float]=4.0) -> Union[int, float]:
return 16 if x < 16 else math.floor(x / m) * m
def clamp(minimum:Union[int, float], x:Union[int, float], maximum:Union[int, float]) -> int:
return helper.round_to_closest(max(minimum, min(x, maximum)))
class util:
def fmtc_kernel_kwargs(kernel:str, taps:Optional[int]=None, strength:Optional[int]=None):
kernel = kernel.lower()
if kernel in ["point", "nearest", "neighbour"]:
kernel_kwargs = {"kernel": "point"}
# most of those are from lvsfunc
elif kernel in ["rect", "box", "linear", "bilinear", "blackman",
"blackmanminlobe", "spline", "sinc", "spline16",
"spline36", "spline64"]:
kernel_kwargs = {"kernel": kernel}
elif kernel == "lanczos":
taps = 3 if taps is None else taps
kernel_kwargs = {"kernel": "lanczos", "taps": taps}
elif kernel == "spline144":
kernel_kwargs = {"kernel": "spline", "taps": 6}
# Bicubic
elif kernel in ["didée", "didee"]:
kernel_kwargs = {"kernel": "bicubic", "a1": -1/2, "a2": 1/4}
elif kernel in ["mitchell", "mitchell-netravali", "neutral"]:
kernel_kwargs = {"kernel": "bicubic", "a1": 1/3, "a2": 1/3}
elif kernel in ["catrom", "catmullrom", "catmull-rom"]:
kernel_kwargs = {"kernel": "bicubic", "a1": 0, "a2": 1/2}
elif kernel in ["bicubicsharp", "sharp"]:
kernel_kwargs = {"kernel": "bicubic", "a1": 0, "a2": 1}
elif kernel in ["bicubiczoptineutral", "zoptineutral"]:
kernel_kwargs = {"kernel": "bicubic", "a1": -0.6, "a2": 0.3}
elif kernel == "robidouxsoft":
x = (9 - 3 * math.sqrt(2)) / 7
kernel_kwargs = {"kernel": "bicubic",
"a1": x,
"a2": (1 - x) / 2}
elif kernel == "robidoux":
kernel_kwargs = {"kernel": "bicubic",
"a1": 12 / (19 + 9 * math.sqrt(2)),
"a2": 113 / (58 + 216 * math.sqrt(2))}
elif kernel == "robidouxsharp":
kernel_kwargs = {"kernel": "bicubic",
"a1": 6 / (13 + 7 * math.sqrt(2)),
"a2": 7 / (2 + 12 * math.sqrt(2))}
elif kernel == "bspline":
kernel_kwargs = {"kernel": "bicubic", "a1": 1, "a2": 0}
elif kernel in ["setsuCcbic", "setsu"]:
strength = 100 if strength is None else strength
kernel_kwargs = {"kernel": "bicubic",
"a1": math.asinh(.5) * math.acos(.5) * -abs(math.cos(strength*4)),
"a2": abs(math.asinh(.5) * math.acos(-.5) * math.cos((strength*4) + strength/2))}
# Impulse
elif kernel in ["parzen–rosenblatt", "parzen", "kde"]:
impulse = [0.666667, 0.648727, 0.596804, 0.51624, 0.415088, 0.303095,
0.190509, 0.086876, 0, -0.064824, -0.105205, -0.121655, -0.117225,
-0.096848, -0.0665116, -0.032382, 0, 0.026335, 0.0439404, 0.051856,
0.0506892, 0.042271, 0.0291773, 0.014224, 0, -0.011489, -0.0190243,
-0.022227, -0.0214634, -0.017647, -0.0119891, -0.005745, 0, 0.004475,
0.00727292, 0.008338, 0.00789788, 0.006366, 0.00423604, 0.001986, 0,
-0.001471, -0.00232189, -0.002577, -0.00235492, -0.001824, -0.00116114,
-0.000518, 0, 0.000341, 0.000502619, 0.000515, 0.000430408, 0.000301,
0.000169602, 0.000066, 0, -0.00003, -0.0000341078, -0.000025,
-0.0000138158, -0.000005, -0.00000118185, 0]
kernel_kwargs = {"kernel": "impulse",
"impulse": [*impulse[:-1], *impulse[::-1]]}
elif kernel in ["kaiser–bessel ", "kaiser"]:
impulse = [1, 0.973784, 0.897692, 0.779078, 0.629225, 0.462012,
0.29231, 0.134312, 0, -0.102037, -0.167326, -0.195688, -0.190881,
-0.159791, -0.111303, -0.055016, 0, 0.046264, 0.0786285, 0.094631,
0.0944555, 0.080540, 0.0569238, 0.028458, 0, -0.024290, -0.0414535,
-0.050006, -0.0499464, -0.042553, -0.0300094, -0.014951, 0, 0.012629,
0.0214054, 0.025619, 0.0253622, 0.021395, 0.0149254, 0.007348, 0,
-0.006043, -0.0100898, -0.011883, -0.0115622, -0.009575, -0.00654779,
-0.003156, 0, 0.002475, 0.00402406, 0.004606, 0.00434445, 0.003478,
0.00229289, 0.001061, 0, -0.000757, -0.0011651, -0.001252, -0.00109846,
-0.000808, -0.000481802, -0.000197]
kernel_kwargs = {"kernel": "impulse",
"impulse": [*impulse[:-1], *impulse[::-1]]}
else:
raise vs.Error("fmtc_kernel_kwargs: unkown kernel")
return kernel_kwargs
# stolen from vsutil btw.
def plane(clip:vs.VideoNode, plane:int) -> vs.VideoNode:
if clip.format.num_planes == 1 and plane == 0:
return clip
return vs.core.std.ShufflePlanes(clip, plane, vs.GRAY)
def join(planes:List[vs.VideoNode], family:vs.ColorFamily=vs.YUV) -> vs.VideoNode:
if family not in [vs.RGB, vs.YUV]:
raise vs.Error('Color family must have 3 planes.')
return vs.core.std.ShufflePlanes(clips=planes, planes=[0, 0, 0], colorfamily=family)
def split(clip:vs.VideoNode) -> List[vs.VideoNode]:
return [util.plane(clip, x) for x in range(clip.format.num_planes)]
def edge_detection(clip:vs.VideoNode, planes:Optional[Union[int,List[int]]]=None,
method:str="kirsch", thr:Optional[int]=None, scale:bool=False) -> vs.VideoNode:
if planes is None:
planes = list(range(clip.format.num_planes))
elif isinstance(planes, int):
planes = [planes]
max_value = 1 if clip.format.sample_type == vs.FLOAT else (1 << clip.format.bits_per_sample) - 1
if method in ["t", "tcanny"]:
# Fastest
if thr is None: thr = 5
edge = vs.core.tcanny.TCanny(clip, mode=1, sigma=1)
# edge = vs.core.tcanny.TCanny(clip, sigma=1.25, t_h=4.0, t_l=1.0, op=1, mode=1) # Blue
elif method in ["p", "prewitt"]:
# Best??
if thr is None: thr = 15
edge = vs.core.std.Expr([
clip.std.Convolution(matrix=[1, 1, 0, 1, 0, -1, 0, -1, -1], planes=planes, saturate=False),
clip.std.Convolution(matrix=[1, 1, 1, 0, 0, 0, -1, -1, -1], planes=planes, saturate=False),
clip.std.Convolution(matrix=[1, 0, -1, 1, 0, -1, 1, 0, -1], planes=planes, saturate=False),
clip.std.Convolution(matrix=[0, -1, -1, 1, 0, -1, 1, 1, 0], planes=planes, saturate=False)],
expr=['x y max z max a max' if i in planes else '' for i in range(clip.format.num_planes)])
elif method in ["k", "kirsch"]:
# Slowest and maybe most chaotic
if thr is None: thr = 40
edge = vs.core.std.Expr([
clip.std.Convolution(matrix=[ 5, 5, 5, -3, 0, -3, -3, -3, -3], planes=planes, saturate=False),
clip.std.Convolution(matrix=[-3, 5, 5, -3, 0, 5, -3, -3, -3], planes=planes, saturate=False),
clip.std.Convolution(matrix=[-3, -3, 5, -3, 0, 5, -3, -3, 5], planes=planes, saturate=False),
clip.std.Convolution(matrix=[-3, -3, -3, -3, 0, 5, -3, 5, 5], planes=planes, saturate=False)],
expr=['x y max z max a max' if i in planes else '' for i in range(clip.format.num_planes)])
else:
raise ValueError("edge_detection: invalid method.")
if scale:
edge = vs.core.std.Expr([edge], expr=f'x {helper.scale255(thr, max_value)} < 0 x ?')
return edge
def retinex_edge(clip:vs.VideoNode, method="prewitt", sigma:int=1,
thr:Optional[int]=None, plane:int=0) -> vs.VideoNode:
# from kageunc
plane_clip = util.plane(clip, plane=plane)
max_value = 1 if clip.format.sample_type == vs.FLOAT else (1 << clip.format.bits_per_sample) - 1
ret = vs.core.retinex.MSRCP(plane_clip, sigma=[50, 200, 350], upper_thr=0.005)
tcanny = ret.tcanny.TCanny(mode=1, sigma=sigma).std.Minimum(coordinates=[1, 0, 1, 0, 0, 1, 0, 1])
return vs.core.std.Expr([util.edge_detection(plane_clip, method=method, thr=thr), tcanny], f'x y + {max_value} min')
def mt_expand_multi(clip:vs.VideoNode, mode:str='rectangle',
planes:Optional[Union[int, List[int]]]=None, sw:int=1, sh:int=1) -> vs.VideoNode:
if isinstance(planes, int):
planes = [planes]
if sw > 0 and sh > 0:
mode_m = [0, 1, 0, 1, 1, 0, 1, 0] if mode == 'losange' or (mode == 'ellipse' and (sw % 3) != 1) else [1, 1, 1, 1, 1, 1, 1, 1]
elif sw > 0:
mode_m = [0, 0, 0, 1, 1, 0, 0, 0]
elif sh > 0:
mode_m = [0, 1, 0, 0, 0, 0, 1, 0]
else:
mode_m = None
if mode_m is not None:
clip = util.mt_expand_multi(clip.std.Maximum(planes=planes, coordinates=mode_m), mode=mode, planes=planes, sw=sw - 1, sh=sh - 1)
return clip
def mt_inpand_multi(clip:vs.VideoNode, mode:str='rectangle',
planes:Optional[Union[int, List[int]]]=None, sw:int=1, sh:int=1) -> vs.VideoNode:
if isinstance(planes, int):
planes = [planes]
if sw > 0 and sh > 0:
mode_m = [0, 1, 0, 1, 1, 0, 1, 0] if mode == 'losange' or (mode == 'ellipse' and (sw % 3) != 1) else [1, 1, 1, 1, 1, 1, 1, 1]
elif sw > 0:
mode_m = [0, 0, 0, 1, 1, 0, 0, 0]
elif sh > 0:
mode_m = [0, 1, 0, 0, 0, 0, 1, 0]
else:
mode_m = None
if mode_m is not None:
clip = util.mt_inpand_multi(clip.std.Minimum(planes=planes, coordinates=mode_m), mode=mode, planes=planes, sw=sw - 1, sh=sh - 1)
return clip
def mt_inflate_multi(clip:vs.VideoNode, planes:Optional[Union[int, List[int]]]=None, radius:int=1) -> vs.VideoNode:
if isinstance(planes, int):
planes = [planes]
for i in range(radius):
clip = vs.core.std.Inflate(clip, planes=planes)
return clip
def mt_deflate_multi(clip:vs.VideoNode, planes:Optional[Union[int, List[int]]]=None, radius:int=1) -> vs.VideoNode:
if isinstance(planes, int):
planes = [planes]
for i in range(radius):
clip = vs.core.std.Deflate(clip, planes=planes)
return clip
def check_color_family(color_family:str, valid_list:List[str]=None, invalid_list:Optional[List[str]]=None) -> vs.VideoNode:
if valid_list is None:
valid_list = ('RGB', 'YUV', 'GRAY')
if invalid_list is None:
invalid_list = ('COMPAT', 'UNDEFINED')
# check invalid list
for cf in invalid_list:
if color_family == getattr(vs, cf, None):
raise value_error(f'color family *{cf}* is not supported!')
# check valid list
if valid_list:
if color_family not in [getattr(vs, cf, None) for cf in valid_list]:
raise value_error(f'color family not supported, only {valid_list} are accepted')
def min_blur(clip:vs.VideoNode, r:int=1, planes:Optional[Union[int, List[int]]]=None) -> vs.VideoNode:
# by Didée (http://avisynth.nl/index.php/MinBlur)
# Nifty Gauss/Median combination
if planes is None:
planes = list(range(clip.format.num_planes))
elif isinstance(planes, int):
planes = [planes]
matrix1 = [1, 2, 1, 2, 4, 2, 1, 2, 1]
matrix2 = [1, 1, 1, 1, 1, 1, 1, 1, 1]
if r <= 0:
RG11 = sbr(clip, planes=planes)
RG4 = clip.std.Median(planes=planes)
elif r == 1:
RG11 = clip.std.Convolution(matrix=matrix1, planes=planes)
RG4 = clip.std.Median(planes=planes)
elif r == 2:
RG11 = clip.std.Convolution(matrix=matrix1, planes=planes).std.Convolution(matrix=matrix2, planes=planes)
RG4 = clip.ctmf.CTMF(radius=2, planes=planes)
else:
RG11 = clip.std.Convolution(matrix=matrix1, planes=planes).std.Convolution(matrix=matrix2, planes=planes).std.Convolution(matrix=matrix2, planes=planes)
if clip.format.bits_per_sample == 16:
s16 = clip
RG4 = clip.fmtc.bitdepth(bits=12, planes=planes, dmode=1).ctmf.CTMF(radius=3, planes=planes).fmtc.bitdepth(bits=16, planes=planes)
RG4 = util.limit_filter(s16, RG4, thr=0.0625, elast=2, planes=planes)
else:
RG4 = clip.ctmf.CTMF(radius=3, planes=planes)
expr = 'x y - x z - * 0 < x x y - abs x z - abs < y z ? ?'
return vs.core.std.Expr([clip, RG11, RG4], expr=[expr if i in planes else '' for i in range(clip.format.num_planes)])
def limit_filter(flt:vs.VideoNode, src:vs.VideoNode, ref:Optional[vs.VideoNode]=None,
thr:Optional[float]=None, elast:Optional[float]=None, planes:Optional[Union[int, List[int]]]=None,
brighten_thr:Optional[float]=None, thrc:Optional[float]=None, force_expr:bool=True) -> vs.VideoNode:
# from mvsfunc
# It acts as a post-processor, and is very useful to limit the difference of filtering while avoiding artifacts.
# Commonly used cases:
# de-banding
# de-ringing
# de-noising
# sharpening
# combining high precision source with low precision filtering: util.limit_filter(src, flt, thr=1.0, elast=2.0)
# There are 2 implementations, default one with std.Expr, the other with std.Lut.
# The Expr version supports all mode, while the Lut version doesn't support float input and ref clip.
# Also the Lut version will truncate the filtering diff if it exceeds half the value range(128 for 8-bit, 32768 for 16-bit).
# The Lut version might be faster than Expr version in some cases, for example 8-bit input and brighten_thr != thr.
# Basic parameters
# flt {clip}: filtered clip, to compute the filtering diff
# can be of YUV/RGB/Gray color family, can be of 8-16 bit integer or 16/32 bit float
# src {clip}: source clip, to apply the filtering diff
# must be of the same format and dimension as "flt"
# ref {clip} (optional): reference clip, to compute the weight to be applied on filtering diff
# must be of the same format and dimension as "flt"
# default: None (use "src")
# thr {float}: threshold (8-bit scale) to limit filtering diff
# default: 1.0
# elast {float}: elasticity of the soft threshold
# default: 2.0
# planes {int, int[]}: specify which planes to process
# unprocessed planes will be copied from "flt"
# default: all planes will be processed, [0,1,2] for YUV/RGB input, [0] for Gray input
# Advanced parameters
# brighten_thr {float}: threshold (8-bit scale) for filtering diff that brightening the image (Y/R/G/B plane)
# set a value different from "thr" is useful to limit the overshoot/undershoot/blurring introduced in sharpening/de-ringing
# default is the same as "thr"
# thrc {float}: threshold (8-bit scale) for chroma (U/V/Co/Cg plane)
# default is the same as "thr"
# force_expr {bool}
# - True: force to use the std.Expr implementation
# - False: use the std.Lut implementation if available
# default: True
def _limit_filter_expr(defref, thr, elast, largen_thr, value_range) -> str:
flt = " x "
src = " y "
ref = " z " if defref else src
dif = f" {flt} {src} - "
dif_ref = f" {flt} {ref} - "
dif_abs = dif_ref + " abs "
thr = thr * value_range / 255
largen_thr = largen_thr * value_range / 255
if thr <= 0 and largen_thr <= 0:
limitExpr = f" {src} "
elif thr >= value_range and largen_thr >= value_range:
limitExpr = ""
else:
if thr <= 0:
limitExpr = f" {src} "
elif thr >= value_range:
limitExpr = f" {flt} "
elif elast <= 1:
limitExpr = f" {dif_abs} {thr} <= {flt} {src} ? "
else:
thr_1 = thr
thr_2 = thr * elast
thr_slope = 1 / (thr_2 - thr_1)
# final = src + dif * (thr_2 - dif_abs) / (thr_2 - thr_1)
limitExpr = f" {src} {dif} {thr_2} {dif_abs} - * {thr_slope} * + "
limitExpr = f" {dif_abs} {thr_1} <= {flt} {dif_abs} {thr_2} >= {src} " + limitExpr + " ? ? "
if largen_thr != thr:
if largen_thr <= 0:
limitExprLargen = f" {src} "
elif largen_thr >= value_range:
limitExprLargen = f" {flt} "
elif elast <= 1:
limitExprLargen = f" {dif_abs} {largen_thr} <= {flt} {src} ? "
else:
thr_1 = largen_thr
thr_2 = largen_thr * elast
thr_slope = 1 / (thr_2 - thr_1)
# final = src + dif * (thr_2 - dif_abs) / (thr_2 - thr_1)
limitExprLargen = f" {src} {dif} {thr_2} {dif_abs} - * {thr_slope} * + "
limitExprLargen = f" {dif_abs} {thr_1} <= {flt} {dif_abs} {thr_2} >= {src} " + limitExprLargen + " ? ? "
limitExpr = f" {flt} {ref} > " + limitExprLargen + " " + limitExpr + " ? "
return limitExpr
def _limit_diff_lut(diff:vs.VideoNode, thr:float, elast:float,
largen_thr:Union[int, float], planes:List[vs.VideoNode]):
# Get properties of input clip
sFormat = diff.format
sSType = sFormat.sample_type
sbitPS = sFormat.bits_per_sample
if sSType == vs.INTEGER:
neutral = 1 << (sbitPS - 1)
value_range = (1 << sbitPS) - 1
else:
neutral = 0
value_range = 1
# Process
thr = thr * value_range / 255
largen_thr = largen_thr * value_range / 255
if thr <= 0 and largen_thr <= 0:
return diff
elif thr >= value_range / 2 and largen_thr >= value_range / 2:
def limitLut(x):
return neutral
return vs.core.std.Lut(diff, planes=planes, function=limitLut)
elif elast <= 1:
def limitLut(x):
dif = x - neutral
dif_abs = abs(dif)
thr_1 = largen_thr if dif > 0 else thr
return neutral if dif_abs <= thr_1 else x
return vs.core.std.Lut(diff, planes=planes, function=limitLut)
else:
def limitLut(x):
dif = x - neutral
dif_abs = abs(dif)
thr_1 = largen_thr if dif > 0 else thr
thr_2 = thr_1 * elast
if dif_abs <= thr_1:
return neutral
elif dif_abs >= thr_2:
return x
else:
# final = flt - dif * (dif_abs - thr_1) / (thr_2 - thr_1)
thr_slope = 1 / (thr_2 - thr_1)
return round(dif * (dif_abs - thr_1) * thr_slope + neutral)
return vs.core.std.Lut(diff, planes=planes, function=limitLut)
# Get properties of input clip
sFormat = flt.format
if sFormat.id != src.format.id:
raise value_error('"flt" and "src" must be of the same format!')
if flt.width != src.width or flt.height != src.height:
raise value_error('"flt" and "src" must be of the same width and height!')
if ref is not None:
if sFormat.id != ref.format.id:
raise value_error('"flt" and "ref" must be of the same format!')
if flt.width != ref.width or flt.height != ref.height:
raise value_error('"flt" and "ref" must be of the same width and height!')
sColorFamily = sFormat.color_family
util.check_color_family(sColorFamily)
sIsYUV = sColorFamily == vs.YUV
sSType = sFormat.sample_type
sbitPS = sFormat.bits_per_sample
sNumPlanes = sFormat.num_planes
# Parameters
if thr is None:
thr = 1.0
elif isinstance(thr, int) or isinstance(thr, float):
if thr < 0:
raise value_error('valid range of "thr" is [0, +inf)')
else:
raise type_error('"thr" must be an int or a float!')
if elast is None:
elast = 2.0
elif isinstance(elast, int) or isinstance(elast, float):
if elast < 1:
raise value_error('valid range of "elast" is [1, +inf)')
else:
raise type_error('"elast" must be an int or a float!')
if brighten_thr is None:
brighten_thr = thr
elif isinstance(brighten_thr, int) or isinstance(brighten_thr, float):
if brighten_thr < 0:
raise value_error('valid range of "brighten_thr" is [0, +inf)')
else:
raise type_error('"brighten_thr" must be an int or a float!')
if thrc is None:
thrc = thr
elif isinstance(thrc, int) or isinstance(thrc, float):
if thrc < 0:
raise value_error('valid range of "thrc" is [0, +inf)')
else:
raise type_error('"thrc" must be an int or a float!')
if ref is not None or sSType != vs.INTEGER:
force_expr = True
# planes
process = [0 for i in range(3)]
if planes is None:
process = [1 for i in range(3)]
elif isinstance(planes, int):
if planes < 0 or planes >= 3:
raise vs.Error(f'valid range of planes is 0 to 3')
process[planes] = 1
elif isinstance(planes, list):
for p in planes:
if p < 0 or p >= 3:
raise vs.Error(f'valid range of planes is [0, 3]!')
process[p] = 1
# Process
if thr <= 0 and brighten_thr <= 0:
if sIsYUV:
if thrc <= 0:
return src
else:
return src
if thr >= 255 and brighten_thr >= 255:
if sIsYUV:
if thrc >= 255:
return flt
else:
return flt
if thr >= 128 or brighten_thr >= 128:
force_expr = True
if force_expr: # implementation with std.Expr
valueRange = (1 << sbitPS) - 1 if sSType == vs.INTEGER else 1
limitExprY = _limit_filter_expr(ref is not None, thr, elast, brighten_thr, valueRange)
limitExprC = _limit_filter_expr(ref is not None, thrc, elast, thrc, valueRange)
expr = []
for i in range(sNumPlanes):
if process[i]:
if i > 0 and (sIsYUV):
expr.append(limitExprC)
else:
expr.append(limitExprY)
else:
expr.append("")
if ref is None:
clip = vs.core.std.Expr([flt, src], expr)
else:
clip = vs.core.std.Expr([flt, src, ref], expr)
else: # implementation with std.MakeDiff, std.Lut and std.MergeDiff
diff = vs.core.std.MakeDiff(flt, src, planes=planes)
if sIsYUV:
if process[0]:
diff = _limit_diff_lut(diff, thr, elast, brighten_thr, [0])
if process[1] or process[2]:
_planes = []
if process[1]:
_planes.append(1)
if process[2]:
_planes.append(2)
diff = _limit_diff_lut(diff, thrc, elast, thrc, _planes)
else:
diff = _limit_diff_lut(diff, thr, elast, brighten_thr, planes)
clip = vs.core.std.MakeDiff(flt, diff, planes=planes)
# Output
return clip
class output:
def rav1e(clip:vs.VideoNode, file_str:str, speed:int=6, scd_speed:int=1,
quantizer:int=100, gop:Optional[int]=None,
tiles_row:Optional[int]=None, tiles_col:Optional[int]=None,
color_range:Optional[str]=None, primaties:Optional[str]=None,
transfer:Optional[str]=None, matrix:Optional[str]=None,
mastering_display:Optional[str]=None, content_light:Optional[str]=None,
executable:str="rav1e"):
if clip.format.name not in ['YUV420P8', 'YUV422P8', 'YUV444P8', 'YUV420P10', 'YUV422P10', 'YUV444P10', 'YUV420P12', 'YUV422P12', 'YUV444P12']:
raise vs.Error(f"Pixel format must be one of `YUV420P8, YUV422P8, YUV444P8, YUV420P10, YUV422P10, YUV444P10, YUV420P12, YUV422P12, YUV444P12` currently {clip.format.name}")
if gop is None: gop = min(300, helper.round_to_closest(clip.fps)*10)
args = [
executable,
"-",
"-o", "-",
"--quantizer", f"{quantizer}",
"--speed", f"{speed}",
"--scd_speed", f"{scd_speed}",
"--keyint", f"{gop}"
]
if color_range is not None: args += ["--range", f"{color_range}"]
if primaties is not None: args += ["--primaries", f"{primaties}"]
if transfer is not None: args += ["--transfer", f"{transfer}"]
if matrix is not None: args += ["--matrix", f"{matrix}"]
if mastering_display is not None: args += ["--mastering-display", f"{mastering_display}"]
if content_light is not None: args += ["--content-light", f"{content_light}"]
if tiles_row is not None: args += ["--tile-rows", f"{tiles_row}"]
if tiles_col is not None: args += ["--tile-cols", f"{tiles_col}"]
args += ["-"]
file = open(file_str, 'wb')
with subprocess.Popen(args, stdin=subprocess.PIPE, stdout=file) as process:
clip.output(process.stdin, y4m=True)
process.stdin.close()
file.close()
# def svtav1(clip:vs.VideoNode, file_str:str,
# stat_file:Optional[str]=None):
# if clip.format.name not in ['YUV420P8', 'YUV420P10']:
# raise vs.Error(f"Pixel format must be one of `YUV420P8, YUV420P10` currently {clip.format.name}")
# args = [
# executable,
# "-i", "-",
# "-b", "stdout",
# "--fps-num", f"{clip.fps.numerator}",
# "--fps-denom", f"{clip.fps.denominator}",
# "--width", f"{clip.width}",
# "--height", f"{clip.height}",
# "--input-depth", f"{clip.format.bits_per_sample}"
# ]
# if stat_file is not None: args += [
# "--stat-file", f"{stat_file}",
# "--enable-stat-report", "1"
# ]
# print(" ".join(args))
# file = open(file_str, 'wb')
# with subprocess.Popen(args, stdin=subprocess.PIPE, stdout=file) as process:
# clip.output(process.stdin)
# process.stdin.close()
# file.close()
def aomenc_fp(clip:vs.VideoNode, fpf=str, speed:int=6, executable:str="aomenc"):
if clip.format.name not in ['YUV420P8', 'YUV422P8', 'YUV444P8', 'YUV420P10', 'YUV422P10', 'YUV444P10', 'YUV420P12', 'YUV422P12', 'YUV444P12']:
raise vs.Error(f"Pixel format must be one of `YUV420P8, YUV422P8, YUV444P8, YUV420P10, YUV422P10, YUV444P10, YUV420P12, YUV422P12, YUV444P12` currently {clip.format.name}")
if (clip.format.name in ["YUV420P8", "YUV420P10"]):
profile=0
elif (clip.format.name in ["YUV444P8", "YUV444P10"]) and monochrome:
profile=1
elif (clip.format.name in ["YUV422P8", "YUV422P10", "YUV422P12", "YUV420P12", "YUV444P12"]):
profile=2
args = [
executable,
"-",
"--passes=2",
"--pass=1",
f"--cpu-used={speed}",
f"--fps={clip.fps.numerator}/{clip.fps.denominator}",
f"--profile={profile}",
f"--width={clip.width}",
f"--height={clip.height}",
f"--input-chroma-subsampling-x={clip.format.subsampling_w}",
f"--input-chroma-subsampling-y={clip.format.subsampling_h}",
f"--input-bit-depth={clip.format.bits_per_sample}",
f"--bit-depth={clip.format.bits_per_sample}",
f"--fpf={fpf}",
"--output=-"
]
print(" ".join(args))
with subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) as process:
clip.output(process.stdin)
process.stdin.close()
def aomenc(clip:vs.VideoNode, file_str:str, mux:str="webm", speed:int=4,
usage:str="q", quantizer:int=32, bitrate_min:int=1500,
bitrate_mid:int=2000, bitrate_max:int=2500, gop:Optional[int]=None,
lif:Optional[int]=None, tiles_row:Optional[int]=None,
tiles_col:Optional[int]=None, enable_cdef:bool=True,
enable_restoration:Optional[bool]=None, enable_chroma_deltaq:bool=True,
arnr_strength:int=2, arnr_max_frames:int=5, resize_mode:Optional[int]=None,
superres_mode:Optional[int]=None, tune:Optional[str]=None, tune_content:Optional[str]=None,
fpf:Optional[str]=None, monochrome:bool=False, executable:str="aomenc"):
# Only Q or VBR
if clip.format.name not in ['YUV420P8', 'YUV422P8', 'YUV444P8', 'YUV420P10', 'YUV422P10', 'YUV444P10', 'YUV420P12', 'YUV422P12', 'YUV444P12']:
raise vs.Error(f"Pixel format must be one of `YUV420P8, YUV422P8, YUV444P8, YUV420P10, YUV422P10, YUV444P10, YUV420P12, YUV422P12, YUV444P12` currently {clip.format.name}")
if (clip.format.name in ["YUV420P8", "YUV420P10"]):
profile=0 # Main
elif (clip.format.name in ["YUV444P8", "YUV444P10"]) and not monochrome:
profile=1 # High
# No monochrome support here or some reason.
else:
# elif (clip.format.name in ["YUV422P8", "YUV422P10", "YUV422P12", "YUV420P12", "YUV444P12"]):
profile=2 # Professional
if (mux not in ["ivf", "webm", "obu"]):
raise vs.Error('Muxing container format must be one of `ivf webm obu`')
if gop is None: gop = min(300, helper.round_to_closest(clip.fps)*10)
if lif is None: lif = min(35, gop)
if tiles_row is None: tiles_row = math.floor(clip.height/1080) if clip.height<clip.width else math.floor(clip.height/1920)
if tiles_col is None: tiles_col = math.floor(clip.width/1920) if clip.height<clip.width else math.floor(clip.width/1080)
enable_cdef = "1" if enable_cdef else "0"
enable_chroma_deltaq = "1" if enable_chroma_deltaq else "0"
if enable_restoration is None:
if (clip.height*clip.width >= 3200*2000) or not enable_restoration: # if smaller than 2160p
enable_restoration = 0
else: enable_restoration = 1
args = [
executable,
"-",
# "--rate-hist=1",
f"--{mux}" ,
f"--cpu-used={speed}"
]
if fpf is not None:
args += [
"--passes=2",
"--pass=2",
f"--fpf={fpf}"
]
else:
args += ["--passes=1"]
if usage == "q":
args += ["--end-usage=q", f"--cq-level={quantizer}"]
elif usage == "vbr":
args += [
"--end-usage=vbr", "--bias-pct=75",
f"--target-bitrate={bitrate_mid}",
f"--undershoot-pct={helper.round_to_closest(((bitrate_mid - bitrate_min) / bitrate_min)*100)}",
f"--overshoot-pct={helper.round_to_closest(((bitrate_max - bitrate_mid) / bitrate_mid)*100)}"
]
else:
raise vs.Error('Only q and vbr end usages are supported.')
# if clip.format.color_family == vs.GRAY:
# args+="--monochrome"
if monochrome:
args += ["--monochrome"]
args += [
f"--fps={clip.fps.numerator}/{clip.fps.denominator}",
f"--profile={profile}",
f"--width={clip.width}",
f"--height={clip.height}",
f"--input-chroma-subsampling-x={clip.format.subsampling_w}",
f"--input-chroma-subsampling-y={clip.format.subsampling_h}",
f"--input-bit-depth={clip.format.bits_per_sample}",
f"--bit-depth={clip.format.bits_per_sample}",
f"--kf-max-dist={gop}",
f"--lag-in-frames={lif}",
"--row-mt=1",
f"--tile-columns={tiles_row}",
f"--tile-rows={tiles_row}",
f"--enable-chroma-deltaq={enable_chroma_deltaq}",
f"--enable-cdef={enable_cdef}",
f"--enable-restoration={enable_restoration}",
f"--arnr-strength={arnr_strength}",
f"--arnr-maxframes={arnr_max_frames}",
]
# if (clip.height*clip.width < 1280*720):
# args += ["--max-partition-size=64", "--sb-size=64"] # sb-size used to be 32 but now it can't work? `dynamic, 64, 128`
if (clip.height*clip.width < 1920*1080):
args += ["--max-partition-size=64", "--sb-size=64"]
if resize_mode is not None: args += [f"--resize-mode={resize_mode}"]
if superres_mode is not None: args += [f"--superres-mode={superres_mode}"]
if tune is not None: args += [f"--tune={tune}"]
if tune_content is not None: args += [f"--tune-content={tune_content}"]
args += [
"--min-q=1",
f"--enable-fwd-kf=1",
"--quant-b-adapt=1",
"--enable-dual-filter=0",
f"--enable-qm=1",
"--qm-min=5",
"--output=-"
]
print(" ".join(args))
file = open(file_str, 'wb')
with subprocess.Popen(args, stdin=subprocess.PIPE, stdout=file) as process:
clip.output(process.stdin)
process.stdin.close()
file.close()
def __get_progress__(a:int, b:int):
print(f"Progress: {str(math.floor((a/b)*100)).rjust(3,' ')}% {str(a).rjust(str(b).__len__())}/{b}", end="\r")
def __ff_fmt_conv__(vs_format_name:str) -> str:
if vs_format_name not in ["YUV411P8","YUV410P8","YUV420P8","YUV422P8","YUV440P8","YUV444P8","YUV420P9","YUV422P9","YUV444P9","YUV420P10","YUV422P10","YUV444P10","YUV420P12","YUV422P12","YUV444P12","YUV420P14","YUV422P14","YUV444P14","YUV420P16","YUV422P16","YUV444P16","Gray8","Gray9","Gray10","Gray12","Gray16","RGB24","RGB27","RGB30","RGB36","RGB42","RGB48"]:
raise vs.Error(f"Pixel format must be one of `YUV411P8, YUV410P8, YUV420P8, YUV422P8, YUV440P8, YUV444P8, YUV420P9, YUV422P9, YUV444P9, YUV420P10, YUV422P10, YUV444P10, YUV420P12, YUV422P12, YUV444P12, YUV420P14, YUV422P14, YUV444P14, YUV420P16, YUV422P16, YUV444P16, Gray8, Gray9, Gray10, Gray12, Gray16, RGB24, RGB27, RGB30, RGB36, RGB42, RGB48` currently {clip.format.name}")
return {
"YUV411P8": "yuv411p",
"YUV410P8": "yuv410p",
"YUV420P8": "yuv420p",
"YUV422P8": "yuv422p",
"YUV440P8": "yuv440p",
"YUV444P8": "yuv444p",
"YUV420P9": "yuv420p9le",
"YUV422P9": "yuv422p9le",
"YUV444P9": "yuv444p9le",
"YUV420P10": "yuv420p10le",
"YUV422P10": "yuv422p10le",
"YUV444P10": "yuv444p10le",
"YUV420P12": "yuv420p12le",
"YUV422P12": "yuv422p12le",
"YUV444P12": "yuv444p12le",
"YUV420P14": "yuv420p14le",
"YUV422P14": "yuv422p14le",
"YUV444P14": "yuv444p14le",
"YUV420P16": "yuv420p16le",
"YUV422P16": "yuv422p16le",
"YUV444P16": "yuv444p16le",
"Gray8": "gray",
"Gray9": "gray9le",
"Gray10": "gray10le",
"Gray12": "gray12le",
"Gray16": "gray16le",
"RGB24": "gbrp",
"RGB27": "gbrp9le",
"RGB30": "gbrp10le",
"RGB36": "gbrp12le",
"RGB42": "gbrp14le",
"RGB48": "gbrp16le"
}.get(vs_format_name)
def libx264(clip:vs.VideoNode, file_str:str, preset:str='veryslow', crf:int=7,
crf_max:Optional[int]=None, gop:Optional[int]=None, threads:int=3,
rc_lookahead:Optional[int]=None, mux:str='nut', executable:str='ffmpeg'):
if clip.format.name not in ['YUV420P8', 'YUV422P8', 'YUV444P8', 'YUV420P10', 'YUV422P10', 'YUV444P10']:
raise vs.Error(f"Pixel format must be one of `YUV420P8, YUV420P10` currently {clip.format.name}")
args = [
executable,
"-y",
"-hide_banner",
"-v", "8",
"-i", "-",
"-c", "libx264",
"-preset", f"{preset}",
"-crf", f"{crf}"
]
if gop is not None: args += ["-g", f"{gop}"]
if crf_max is not None: ffmpeg_str += ["-crf_max", f"{crf_max}"]
args += [
"-threads", f"{threads}",
"-f", f"{mux}",
"-"
]
file = open(file_str, 'wb')
with subprocess.Popen(args, stdin=subprocess.PIPE, stdout=file) as process:
clip.output(process.stdin, y4m=True, progress_update=output.__get_progress__)
process.stdin.close()
file.close()
def llx264(clip:vs.VideoNode, file_str:str, preset:str='veryslow', mux:str='nut', executable:str='ffmpeg'):
if clip.format.name not in ['YUV420P8', 'YUV422P8', 'YUV444P8', 'YUV420P10', 'YUV422P10', 'YUV444P10']:
raise vs.Error(f"Pixel format must be one of `YUV420P8, YUV420P10` currently {clip.format.name}")
args = [
executable,
"-y",
"-hide_banner",
"-v", "8",
"-i", "-",
"-c", "libx264",
"-preset", f"{preset}",
"-qp", "0",
"-f", f"{mux}",
"-"
]
file = open(file_str, 'wb')
with subprocess.Popen(args, stdin=subprocess.PIPE, stdout=file) as process:
clip.output(process.stdin, y4m=True, progress_update=output.__get_progress__)
process.stdin.close()
file.close()
def ffv1(clip:vs.VideoNode, file_str:str, mux:str='nut', executable:str='ffmpeg'):
if clip.format.name not in ["YUV411P8", "YUV410P8", "YUV420P8", "YUV422P8", "YUV440P8", "YUV444P8", "YUV420P9", "YUV422P9", "YUV444P9", "YUV420P10", "YUV422P10", "YUV444P10", "YUV420P12", "YUV422P12", "YUV444P12", "YUV420P14", "YUV422P14", "YUV444P14", "YUV420P16", "YUV422P16", "YUV444P16", "Gray8", "Gray9", "Gray10", "Gray12", "Gray16", "RGB27", "RGB30", "RGB36", "RGB42", "RGB48"]:
raise vs.Error(f"Pixel format must be one of `YUV411P8, YUV410P8, YUV420P8, YUV422P8, YUV440P8, YUV444P8, YUV420P9, YUV422P9, YUV444P9, YUV420P10, YUV422P10, YUV444P10, YUV420P12, YUV422P12, YUV444P12, YUV420P14, YUV422P14, YUV444P14, YUV420P16, YUV422P16, YUV444P16, Gray8, Gray9, Gray10, Gray12, Gray16, RGB27, RGB30, RGB36, RGB42, RGB48` currently {clip.format.name}")
if clip.format.color_family is vs.RGB:
# rgb to gbr
clip = util.join([
util.plane(clip, 1), # g
util.plane(clip, 2), # b
util.plane(clip, 0) # r
], vs.RGB)
args = [
executable,
"-y",
"-hide_banner",
"-v", "8",
"-f", "rawvideo",
"-pixel_format", f"{output.__ff_fmt_conv__(clip.format.name)}",
"-video_size", f"{clip.width}x{clip.height}",
"-framerate", f"{clip.fps}",
"-i", "-",
"-c", "ffv1",
"-f", f"{mux}",
"-"
]
file = open(file_str, 'wb')
with subprocess.Popen(args, stdin=subprocess.PIPE, stdout=file) as process:
clip.output(process.stdin, progress_update=output.__get_progress__)
process.stdin.close()
file.close()
def libaom(clip:vs.VideoNode, file_str:str, speed:int=4, quantizer:int=32,
gop:Optional[int]=None, lif:Optional[int]=None,
tiles_row:Optional[int]=None, tiles_col:Optional[int]=None,
enable_cdef:bool=True, enable_restoration:Optional[bool]=None,
enable_chroma_deltaq:bool=True, arnr_strength:int=2,
arnr_max_frames:int=5, threads:int=4, mux:str='nut', executable='ffmpeg'):
if clip.format.name not in ["YUV420P8", "YUV422P8", "YUV444P8", "YUV420P10", "YUV422P10", "YUV444P10", "YUV420P12", "YUV422P12", "YUV444P12", "Gray8", "Gray10", "Gray12", "RGB24", "RGB30", "RGB36"]:
raise vs.Error(f"Pixel format must be one of `YUV420P8, YUV422P8, YUV444P8, YUV420P10, YUV422P10, YUV444P10, YUV420P12, YUV422P12, YUV444P12, Gray8, Gray10, Gray12, RGB24, RGB30, RGB36` currently {clip.format.name}")
if clip.format.color_family is vs.RGB:
# rgb to gbr
clip = util.join([
util.plane(clip, 1), # g
util.plane(clip, 2), # b
util.plane(clip, 0) # r
], vs.RGB)
if gop is None: gop = min(300, helper.round_to_closest(clip.fps)*10)
if lif is None: lif = min(35, gop)
tiles_row = math.floor(clip.height/1080) if clip.height<clip.width else math.floor(clip.height/1920)
tiles_col = math.floor(clip.width/1920) if clip.height<clip.width else math.floor(clip.width/1080)
if enable_restoration is None:
if (clip.height*clip.width >= 3200*2000): # if smaller than 2160p
enable_restoration = True