/
havsfunc.py
5913 lines (5115 loc) · 273 KB
/
havsfunc.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 math
from functools import partial
import mvsfunc as mvf
import vapoursynth as vs
core = vs.core
"""
Holy's ported AviSynth functions for VapourSynth.
Main functions:
daa
daa3mod
mcdaa3
santiag
FixChromaBleedingMod
Deblock_QED
DeHalo_alpha
EdgeCleaner
FineDehalo, FineDehalo2
YAHR
HQDeringmod
QTGMC
smartfademod
srestore
dec_txt60mc
ivtc_txt30mc
ivtc_txt60mc
logoNR
Vinverse
Vinverse2
LUTDeCrawl
LUTDeRainbow
Stab
GrainStabilizeMC
MCTemporalDenoise
SMDegrain
STPresso
bbmod
SigmoidInverse, SigmoidDirect
GrainFactory3
InterFrame
FixColumnBrightness, FixRowBrightness
FixColumnBrightnessProtect, FixRowBrightnessProtect
FixColumnBrightnessProtect2, FixRowBrightnessProtect2
SmoothLevels
FastLineDarkenMOD
Toon
LSFmod
TemporalDegrain
aaf
Utility functions:
AverageFrames
AvsPrewitt
Bob
ChangeFPS
Clamp
KNLMeansCL
Overlay
Padding
Resize
SCDetect
Weave
ContraSharpening
MinBlur
sbr, sbrV
DitherLumaRebuild
mt_expand_multi, mt_inpand_multi
mt_inflate_multi, mt_deflate_multi
"""
##################
# #
# Main functions #
# #
##################
# Anti-aliasing with contra-sharpening by Didée
def daa(c, nsize=None, nns=None, qual=None, pscrn=None, int16_prescreener=None, int16_predictor=None, exp=None, opencl=False, device=None):
if not isinstance(c, vs.VideoNode):
raise vs.Error('daa: This is not a clip')
if opencl:
nnedi3 = partial(core.nnedi3cl.NNEDI3CL, nsize=nsize, nns=nns, qual=qual, pscrn=pscrn, device=device)
else:
nnedi3 = partial(core.znedi3.nnedi3, nsize=nsize, nns=nns, qual=qual, pscrn=pscrn, int16_prescreener=int16_prescreener, int16_predictor=int16_predictor, exp=exp)
nn = nnedi3(c, field=3)
dbl = core.std.Merge(nn[::2], nn[1::2])
dblD = core.std.MakeDiff(c, dbl)
shrpD = core.std.MakeDiff(dbl, dbl.std.Convolution(matrix=[1, 1, 1, 1, 1, 1, 1, 1, 1] if c.width > 1100 else [1, 2, 1, 2, 4, 2, 1, 2, 1]))
DD = core.rgvs.Repair(shrpD, dblD, mode=[13])
return core.std.MergeDiff(dbl, DD)
def daa3mod(c1, nsize=None, nns=None, qual=None, pscrn=None, int16_prescreener=None, int16_predictor=None, exp=None, opencl=False, device=None):
if not isinstance(c1, vs.VideoNode):
raise vs.Error('daa3mod: This is not a clip')
c = c1.resize.Spline36(c1.width, c1.height * 3 // 2)
return daa(c, nsize, nns, qual, pscrn, int16_prescreener, int16_predictor, exp, opencl, device).resize.Spline36(c1.width, c1.height)
def mcdaa3(input, nsize=None, nns=None, qual=None, pscrn=None, int16_prescreener=None, int16_predictor=None, exp=None, opencl=False, device=None):
if not isinstance(input, vs.VideoNode):
raise vs.Error('mcdaa3: This is not a clip')
sup = input.hqdn3d.Hqdn3d().fft3dfilter.FFT3DFilter().mv.Super(sharp=1)
fv1 = sup.mv.Analyse(isb=False, delta=1, truemotion=False, dct=2)
fv2 = sup.mv.Analyse(isb=True, delta=1, truemotion=True, dct=2)
csaa = daa3mod(input, nsize, nns, qual, pscrn, int16_prescreener, int16_predictor, exp, opencl, device)
momask1 = input.mv.Mask(fv1, ml=2, kind=1)
momask2 = input.mv.Mask(fv2, ml=3, kind=1)
momask = core.std.Merge(momask1, momask2)
return core.std.MaskedMerge(input, csaa, momask)
# santiag v1.6
# Simple antialiasing
#
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See
# http://sam.zoy.org/wtfpl/COPYING for more details.
#
# type = "nnedi3", "eedi2", "eedi3" or "sangnom"
def santiag(c, strh=1, strv=1, type='nnedi3', nsize=None, nns=None, qual=None, pscrn=None, int16_prescreener=None, int16_predictor=None, exp=None, aa=None,
alpha=None, beta=None, gamma=None, nrad=None, mdis=None, vcheck=None, fw=None, fh=None, halfres=False, typeh=None, typev=None, opencl=False, device=None):
def santiag_dir(c, strength, type, fw=None, fh=None):
if fw is None:
fw = c.width
if fh is None:
fh = c.height
c = santiag_stronger(c, strength, type)
cshift = 0.0 if halfres else 0.5
if c.format.color_family != vs.GRAY:
cshift = [cshift, cshift * (1 << c.format.subsampling_h)]
return Resize(c, fw, fh, sy=cshift, dmode=1)
def santiag_stronger(c, strength, type):
if opencl:
nnedi3 = partial(core.nnedi3cl.NNEDI3CL, nsize=nsize, nns=nns, qual=qual, pscrn=pscrn, device=device)
eedi3 = partial(core.eedi3m.EEDI3CL, alpha=alpha, beta=beta, gamma=gamma, nrad=nrad, mdis=mdis, vcheck=vcheck, device=device)
else:
nnedi3 = partial(core.znedi3.nnedi3, nsize=nsize, nns=nns, qual=qual, pscrn=pscrn, int16_prescreener=int16_prescreener, int16_predictor=int16_predictor, exp=exp)
eedi3 = partial(core.eedi3m.EEDI3, alpha=alpha, beta=beta, gamma=gamma, nrad=nrad, mdis=mdis, vcheck=vcheck)
strength = max(strength, 0)
field = strength % 2
dh = (strength <= 0 and not halfres)
if strength > 0:
c = santiag_stronger(c, strength - 1, type)
w = c.width
h = c.height
if type == 'nnedi3':
return nnedi3(c, field=field, dh=dh)
elif type == 'eedi2':
if not dh:
cshift = 1 - field
if c.format.color_family != vs.GRAY:
cshift = [cshift, cshift * (1 << c.format.subsampling_h)]
c = Resize(c, w, h // 2, sy=cshift, kernel='point', dmode=1)
return c.eedi2.EEDI2(field=field)
elif type == 'eedi3':
sclip = nnedi3(c, field=field, dh=dh)
return eedi3(c, field=field, dh=dh, sclip=sclip)
elif type == 'sangnom':
if dh:
cshift = -0.25
if c.format.color_family != vs.GRAY:
cshift = [cshift, cshift * (1 << c.format.subsampling_h)]
c = Resize(c, w, h * 2, sy=cshift, dmode=1)
return c.sangnom.SangNom(order=field + 1, aa=aa)
else:
raise vs.Error('santiag: unexpected value for type')
if not isinstance(c, vs.VideoNode):
raise vs.Error('santiag: This is not a clip')
type = type.lower()
typeh = type if typeh is None else typeh.lower()
typev = type if typev is None else typev.lower()
w = c.width
h = c.height
fwh = fw if strv < 0 else w
fhh = fh if strv < 0 else h
if strh >= 0:
c = santiag_dir(c, strh, typeh, fwh, fhh)
if strv >= 0:
c = santiag_dir(c.std.Transpose(), strv, typev, fh, fw).std.Transpose()
if fw is None:
fw = w
if fh is None:
fh = h
if strh < 0 and strv < 0:
c = c.resize.Spline36(fw, fh)
return c
# FixChromaBleedingMod v1.35
#
# Parameters:
# cx (int) - Horizontal chroma shift. Positive value shifts chroma to left, negative value shifts chroma to right. Default is 4
# cy (int) - Vertical chroma shift. Positive value shifts chroma upwards, negative value shifts chroma downwards. Default is 4
# thr (float) - Masking threshold, higher value treats more areas as color bleed. Default is 4.0
# strength (float) - Saturation strength in clip to be merged with the original chroma. Value below 1.0 reduces the saturation, a value of 1.0 leaves the saturation intact. Default is 0.8
# blur (bool) - Set to true to blur the mask clip. Default is false
def FixChromaBleedingMod(input, cx=4, cy=4, thr=4.0, strength=0.8, blur=False):
import adjust
if not isinstance(input, vs.VideoNode):
raise vs.Error('FixChromaBleedingMod: This is not a clip')
if input.format.color_family in [vs.GRAY, vs.RGB]:
raise vs.Error('FixChromaBleedingMod: Gray and RGB formats are not supported')
neutral = 1 << (input.format.bits_per_sample - 1)
peak = (1 << input.format.bits_per_sample) - 1
def Levels(clip, input_low, gamma, input_high, output_low, output_high, coring=True):
gamma = 1 / gamma
divisor = input_high - input_low + (input_high == input_low)
tvLow = scale(16, peak)
tvHigh = [scale(235, peak), scale(240, peak)]
scaleUp = peak / scale(219, peak)
scaleDown = scale(219, peak) / peak
def get_lut1(x):
p = ((x - tvLow) * scaleUp - input_low) / divisor if coring else (x - input_low) / divisor
p = min(max(p, 0), 1) ** gamma * (output_high - output_low) + output_low
return min(max(cround(p * scaleDown + tvLow), tvLow), tvHigh[0]) if coring else min(max(cround(p), 0), peak)
def get_lut2(x):
q = cround((x - neutral) * (output_high - output_low) / divisor + neutral)
return min(max(q, tvLow), tvHigh[1]) if coring else min(max(q, 0), peak)
last = clip.std.Lut(planes=[0], function=get_lut1)
if clip.format.color_family != vs.GRAY:
last = last.std.Lut(planes=[1, 2], function=get_lut2)
return last
# prepare to work on the V channel and filter noise
vch = mvf.GetPlane(adjust.Tweak(input, sat=thr), 2)
if blur:
area = vch.std.Convolution(matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1])
else:
area = vch
# select and normalize both extremes of the scale
red = Levels(area, scale(255, peak), 1.0, scale(255, peak), scale(255, peak), 0)
blue = Levels(area, 0, 1.0, 0, 0, scale(255, peak))
# merge both masks
mask = core.std.Merge(red, blue)
if not blur:
mask = mask.std.Convolution(matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1])
mask = Levels(mask, scale(250, peak), 1.0, scale(250, peak), scale(255, peak), 0)
# expand to cover beyond the bleeding areas and shift to compensate the resizing
mask = mask.std.Convolution(matrix=[0, 0, 0, 1, 0, 0, 0, 0, 0], divisor=1, saturate=False).std.Convolution(matrix=[1, 1, 1, 1, 1, 1, 0, 0, 0], divisor=8, saturate=False)
# binarize (also a trick to expand)
mask = Levels(mask, scale(10, peak), 1.0, scale(10, peak), 0, scale(255, peak)).std.Inflate()
# prepare a version of the image that has its chroma shifted and less saturated
input_c = adjust.Tweak(input.resize.Spline36(src_left=cx, src_top=cy), sat=strength)
# combine both images using the mask
fu = core.std.MaskedMerge(mvf.GetPlane(input, 1), mvf.GetPlane(input_c, 1), mask)
fv = core.std.MaskedMerge(mvf.GetPlane(input, 2), mvf.GetPlane(input_c, 2), mask)
return core.std.ShufflePlanes([input, fu, fv], planes=[0, 0, 0], colorfamily=input.format.color_family)
# Parameters:
# quant1 (int) - Strength of block edge deblocking. Default is 24
# quant2 (int) - Strength of block internal deblocking. Default is 26
# aOff1 (int) - Halfway "sensitivity" and halfway a strength modifier for borders. Default is 1
# aOff2 (int) - Halfway "sensitivity" and halfway a strength modifier for block interiors. Default is 1
# bOff1 (int) - "sensitivity to detect blocking" for borders. Default is 2
# bOff2 (int) - "sensitivity to detect blocking" for block interiors. Default is 2
# uv (int) - 3: use proposed method for chroma deblocking, 2: no chroma deblocking at all (fastest method), 1|-1: directly use chroma debl. from the normal|strong Deblock(). Default is 3
def Deblock_QED(clp, quant1=24, quant2=26, aOff1=1, bOff1=2, aOff2=1, bOff2=2, uv=3):
if not isinstance(clp, vs.VideoNode):
raise vs.Error('Deblock_QED: This is not a clip')
isGray = (clp.format.color_family == vs.GRAY)
planes = [0, 1, 2] if uv >= 3 and not isGray else [0]
if clp.format.sample_type == vs.INTEGER:
neutral = 1 << (clp.format.bits_per_sample - 1)
peak = (1 << clp.format.bits_per_sample) - 1
else:
neutral = 0.0
peak = 1.0
# add borders if clp is not mod 8
w = clp.width
h = clp.height
padX = 8 - w % 8 if w & 7 else 0
padY = 8 - h % 8 if h & 7 else 0
if padX or padY:
clp = clp.resize.Point(w + padX, h + padY, src_width=w + padX, src_height=h + padY)
# block
block = clp.std.BlankClip(width=6, height=6, format=clp.format.replace(color_family=vs.GRAY, subsampling_w=0, subsampling_h=0), length=1, color=[0])
block = block.std.AddBorders(1, 1, 1, 1, color=[peak])
block = core.std.StackHorizontal([block for i in range(clp.width // 8)])
block = core.std.StackVertical([block for i in range(clp.height // 8)])
if not isGray:
blockc = block.std.CropAbs(width=clp.width >> clp.format.subsampling_w, height=clp.height >> clp.format.subsampling_h)
block = core.std.ShufflePlanes([block, blockc], planes=[0, 0, 0], colorfamily=clp.format.color_family)
block = block.std.Loop(times=clp.num_frames)
# create normal deblocking (for block borders) and strong deblocking (for block interiour)
normal = clp.deblock.Deblock(quant=quant1, aoffset=aOff1, boffset=bOff1, planes=[0, 1, 2] if uv != 2 and not isGray else [0])
strong = clp.deblock.Deblock(quant=quant2, aoffset=aOff2, boffset=bOff2, planes=[0, 1, 2] if uv != 2 and not isGray else [0])
# build difference maps of both
normalD = core.std.MakeDiff(clp, normal, planes=planes)
strongD = core.std.MakeDiff(clp, strong, planes=planes)
# separate border values of the difference maps, and set the interiours to '128'
expr = f'y {peak} = x {neutral} ?'
normalD2 = core.std.Expr([normalD, block], expr=[expr] if uv >= 3 or isGray else [expr, ''])
strongD2 = core.std.Expr([strongD, block], expr=[expr] if uv >= 3 or isGray else [expr, ''])
# interpolate the border values over the whole block: DCTFilter can do it. (Kiss to Tom Barry!)
# (Note: this is not fully accurate, but a reasonable approximation.)
# add borders if clp is not mod 16
sw = strongD2.width
sh = strongD2.height
remX = 16 - sw % 16 if sw & 15 else 0
remY = 16 - sh % 16 if sh & 15 else 0
if remX or remY:
strongD2 = strongD2.resize.Point(sw + remX, sh + remY, src_width=sw + remX, src_height=sh + remY)
expr = f'x {neutral} - 1.01 * {neutral} +'
strongD3 = strongD2.std.Expr(expr=[expr] if uv >= 3 or isGray else [expr, '']).dctf.DCTFilter(factors=[1, 1, 0, 0, 0, 0, 0, 0], planes=planes).std.Crop(right=remX, bottom=remY)
# apply compensation from "normal" deblocking to the borders of the full-block-compensations calculated from "strong" deblocking ...
expr = f'y {neutral} = x y ?'
strongD4 = core.std.Expr([strongD3, normalD2], expr=[expr] if uv >= 3 or isGray else [expr, ''])
# ... and apply it.
deblocked = core.std.MakeDiff(clp, strongD4, planes=planes)
# simple decisions how to treat chroma
if not isGray:
if uv <= -1:
deblocked = core.std.ShufflePlanes([deblocked, strong], planes=[0, 1, 2], colorfamily=clp.format.color_family)
elif uv <= 1:
deblocked = core.std.ShufflePlanes([deblocked, normal], planes=[0, 1, 2], colorfamily=clp.format.color_family)
# remove mod 8 borders
return deblocked.std.Crop(right=padX, bottom=padY)
# rx, ry [float, 1.0 ... 2.0 ... ~3.0]
# As usual, the radii for halo removal.
# Note: this function is rather sensitive to the radius settings. Set it as low as possible! If radius is set too high, it will start missing small spots.
#
# darkkstr, brightstr [float, 0.0 ... 1.0] [<0.0 and >1.0 possible]
# The strength factors for processing dark and bright halos. Default 1.0 both for symmetrical processing.
# On Comic/Anime, darkstr=0.4~0.8 sometimes might be better ... sometimes. In General, the function seems to preserve dark lines rather good.
#
# lowsens, highsens [int, 0 ... 50 ... 100]
# Sensitivity settings, not that easy to describe them exactly ...
# In a sense, they define a window between how weak an achieved effect has to be to get fully accepted, and how strong an achieved effect has to be to get fully discarded.
# Defaults are 50 and 50 ... try and see for yourself.
#
# ss [float, 1.0 ... 1.5 ...]
# Supersampling factor, to avoid creation of aliasing.
def DeHalo_alpha(clp, rx=2.0, ry=2.0, darkstr=1.0, brightstr=1.0, lowsens=50, highsens=50, ss=1.5):
if not isinstance(clp, vs.VideoNode):
raise vs.Error('DeHalo_alpha: This is not a clip')
if clp.format.color_family == vs.RGB:
raise vs.Error('DeHalo_alpha: RGB format is not supported')
isInteger = (clp.format.sample_type == vs.INTEGER)
peak = (1 << clp.format.bits_per_sample) - 1 if isInteger else 1.0
if clp.format.color_family != vs.GRAY:
clp_orig = clp
clp = mvf.GetPlane(clp, 0)
else:
clp_orig = None
ox = clp.width
oy = clp.height
halos = clp.resize.Bicubic(m4(ox / rx), m4(oy / ry), filter_param_a=1/3, filter_param_b=1/3).resize.Bicubic(ox, oy, filter_param_a=1, filter_param_b=0)
are = core.std.Expr([clp.std.Maximum(), clp.std.Minimum()], expr=['x y -'])
ugly = core.std.Expr([halos.std.Maximum(), halos.std.Minimum()], expr=['x y -'])
expr = f'y x - y y 0 = + / {peak} * {scale(lowsens, peak)} - y {scale(256, peak)} + {scale(512, peak)} / {highsens / 100} + * {"0 max 1 min" if not isInteger else ""}'
so = core.std.Expr([ugly, are], expr=[expr])
lets = core.std.MaskedMerge(halos, clp, so)
if ss <= 1:
remove = core.rgvs.Repair(clp, lets, mode=[1])
else:
remove = core.std.Expr([core.std.Expr([clp.resize.Lanczos(m4(ox * ss), m4(oy * ss)),
lets.std.Maximum().resize.Bicubic(m4(ox * ss), m4(oy * ss), filter_param_a=1/3, filter_param_b=1/3)],
expr=['x y min']),
lets.std.Minimum().resize.Bicubic(m4(ox * ss), m4(oy * ss), filter_param_a=1/3, filter_param_b=1/3)],
expr=['x y max']).resize.Lanczos(ox, oy)
them = core.std.Expr([clp, remove], expr=[f'x y < x x y - {darkstr} * - x x y - {brightstr} * - ?'])
if clp_orig is not None:
them = core.std.ShufflePlanes([them, clp_orig], planes=[0, 1, 2], colorfamily=clp_orig.format.color_family)
return them
# EdgeCleaner() v1.04 (03/04/2012)
# - a simple edge cleaning and weak dehaloing function
#
# Requirements:
# AWarpSharp2, RGVS (optional)
#
# Parameters:
# strength (float) - specifies edge denoising strength (10)
# rep (boolean) - actives Repair for the aWarpSharped clip (true)
# rmode (integer) - specifies the Repair mode;
# 1 is very mild and good for halos,
# 16 and 18 are good for edge structure preserval on strong settings but keep more halos and edge noise,
# 17 is similar to 16 but keeps much less haloing, other modes are not recommended (17)
# smode (integer) - specifies what method will be used for finding small particles, ie stars;
# 0 is disabled, 1 uses RemoveGrain (0)
# hot (boolean) - specifies whether removal of hot pixels should take place (false)
def EdgeCleaner(c, strength=10, rep=True, rmode=17, smode=0, hot=False):
if not isinstance(c, vs.VideoNode):
raise vs.Error('EdgeCleaner: This is not a clip')
if c.format.color_family == vs.RGB:
raise vs.Error('EdgeCleaner: RGB format is not supported')
peak = (1 << c.format.bits_per_sample) - 1
if c.format.color_family != vs.GRAY:
c_orig = c
c = mvf.GetPlane(c, 0)
else:
c_orig = None
if smode > 0:
strength += 4
main = Padding(c, 6, 6, 6, 6).warp.AWarpSharp2(blur=1, depth=cround(strength / 2)).std.Crop(6, 6, 6, 6)
if rep:
main = core.rgvs.Repair(main, c, mode=[rmode])
mask = AvsPrewitt(c).std.Expr(expr=[f'x {scale(4, peak)} < 0 x {scale(32, peak)} > {peak} x ? ?']).std.Invert().std.Convolution(matrix=[1, 1, 1, 1, 1, 1, 1, 1, 1])
final = core.std.MaskedMerge(c, main, mask)
if hot:
final = core.rgvs.Repair(final, c, mode=[2])
if smode > 0:
clean = c.rgvs.RemoveGrain(mode=[17])
diff = core.std.MakeDiff(c, clean)
expr = f'x {scale(4, peak)} < 0 x {scale(16, peak)} > {peak} x ? ?'
mask = AvsPrewitt(diff.std.Levels(min_in=scale(40, peak), max_in=scale(168, peak), gamma=0.35).rgvs.RemoveGrain(mode=[7])).std.Expr(expr=[expr])
final = core.std.MaskedMerge(final, c, mask)
if c_orig is not None:
final = core.std.ShufflePlanes([final, c_orig], planes=[0, 1, 2], colorfamily=c_orig.format.color_family)
return final
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See
# http://sam.zoy.org/wtfpl/COPYING for more details.
def FineDehalo(src, rx=2.0, ry=None, thmi=80, thma=128, thlimi=50, thlima=100, darkstr=1.0, brightstr=1.0, showmask=0, contra=0.0, excl=True, edgeproc=0.0):
if not isinstance(src, vs.VideoNode):
raise vs.Error('FineDehalo: This is not a clip')
if src.format.color_family == vs.RGB:
raise vs.Error('FineDehalo: RGB format is not supported')
isInteger = (src.format.sample_type == vs.INTEGER)
peak = (1 << src.format.bits_per_sample) - 1 if isInteger else 1.0
if src.format.color_family != vs.GRAY:
src_orig = src
src = mvf.GetPlane(src, 0)
else:
src_orig = None
if ry is None:
ry = rx
rx_i = cround(rx)
ry_i = cround(ry)
### Dehaloing ###
dehaloed = DeHalo_alpha(src, rx=rx, ry=ry, darkstr=darkstr, brightstr=brightstr)
# Contrasharpening
if contra > 0:
dehaloed = FineDehalo_contrasharp(dehaloed, src, contra)
### Main edges ###
# Basic edge detection, thresholding will be applied later
edges = AvsPrewitt(src)
# Keeps only the sharpest edges (line edges)
strong = edges.std.Expr(expr=[f'x {scale(thmi, peak)} - {thma - thmi} / 255 *' if isInteger else f'x {scale(thmi, peak)} - {thma - thmi} / 255 * 0 max 1 min'])
# Extends them to include the potential halos
large = mt_expand_multi(strong, sw=rx_i, sh=ry_i)
### Exclusion zones ###
# When two edges are close from each other (both edges of a single line or multiple parallel color bands), the halo removal oversmoothes them or makes seriously bleed the bands,
# producing annoying artifacts. Therefore we have to produce a mask to exclude these zones from the halo removal
# Includes more edges than previously, but ignores simple details
light = edges.std.Expr(expr=[f'x {scale(thlimi, peak)} - {thlima - thlimi} / 255 *' if isInteger else f'x {scale(thlimi, peak)} - {thlima - thlimi} / 255 * 0 max 1 min'])
# To build the exclusion zone, we make grow the edge mask, then shrink it to its original shape
# During the growing stage, close adjacent edge masks will join and merge, forming a solid area, which will remain solid even after the shrinking stage
# Mask growing
shrink = mt_expand_multi(light, mode='ellipse', sw=rx_i, sh=ry_i)
# At this point, because the mask was made of a shades of grey, we may end up with large areas of dark grey after shrinking
# To avoid this, we amplify and saturate the mask here (actually we could even binarize it)
shrink = shrink.std.Expr(expr=['x 4 *' if isInteger else 'x 4 * 1 min'])
# Mask shrinking
shrink = mt_inpand_multi(shrink, mode='ellipse', sw=rx_i, sh=ry_i)
# This mask is almost binary, which will produce distinct discontinuities once applied. Then we have to smooth it
shrink = shrink.std.Convolution(matrix=[1, 1, 1, 1, 1, 1, 1, 1, 1]).std.Convolution(matrix=[1, 1, 1, 1, 1, 1, 1, 1, 1])
### Final mask building ###
# Previous mask may be a bit weak on the pure edge side, so we ensure that the main edges are really excluded. We do not want them to be smoothed by the halo removal
if excl:
shr_med = core.std.Expr([strong, shrink], expr=['x y max'])
else:
shr_med = strong
# Substracts masks and amplifies the difference to be sure we get 255 on the areas to be processed
outside = core.std.Expr([large, shr_med], expr=['x y - 2 *' if isInteger else 'x y - 2 * 0 max 1 min'])
# If edge processing is required, adds the edgemask
if edgeproc > 0:
outside = core.std.Expr([outside, strong], expr=[f'x y {edgeproc * 0.66} * +' if isInteger else f'x y {edgeproc * 0.66} * + 1 min'])
# Smooth again and amplify to grow the mask a bit, otherwise the halo parts sticking to the edges could be missed
outside = outside.std.Convolution(matrix=[1, 1, 1, 1, 1, 1, 1, 1, 1]).std.Expr(expr=['x 2 *' if isInteger else 'x 2 * 1 min'])
### Masking ###
if showmask <= 0:
last = core.std.MaskedMerge(src, dehaloed, outside)
if src_orig is not None:
if showmask <= 0:
return core.std.ShufflePlanes([last, src_orig], planes=[0, 1, 2], colorfamily=src_orig.format.color_family)
elif showmask == 1:
return core.resize.Bicubic(outside, format=src_orig.format.id)
elif showmask == 2:
return core.resize.Bicubic(shrink, format=src_orig.format.id)
elif showmask == 3:
return core.resize.Bicubic(edges, format=src_orig.format.id)
else:
return core.resize.Bicubic(strong, format=src_orig.format.id)
else:
if showmask <= 0:
return last
elif showmask == 1:
return outside
elif showmask == 2:
return shrink
elif showmask == 3:
return edges
else:
return strong
# level == 1.0 : normal contrasharp
def FineDehalo_contrasharp(dehaloed, src, level):
if not (isinstance(dehaloed, vs.VideoNode) and isinstance(src, vs.VideoNode)):
raise vs.Error('FineDehalo_contrasharp: This is not a clip')
if dehaloed.format.color_family == vs.RGB:
raise vs.Error('FineDehalo_contrasharp: RGB format is not supported')
if dehaloed.format.id != src.format.id:
raise vs.Error('FineDehalo_contrasharp: Clips must be the same format')
neutral = 1 << (dehaloed.format.bits_per_sample - 1) if dehaloed.format.sample_type == vs.INTEGER else 0.0
if dehaloed.format.color_family != vs.GRAY:
dehaloed_orig = dehaloed
dehaloed = mvf.GetPlane(dehaloed, 0)
src = mvf.GetPlane(src, 0)
else:
dehaloed_orig = None
bb = dehaloed.std.Convolution(matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1])
bb2 = core.rgvs.Repair(bb, core.rgvs.Repair(bb, bb.ctmf.CTMF(radius=2), mode=[1]), mode=[1])
xd = core.std.MakeDiff(bb, bb2)
xd = xd.std.Expr(expr=[f'x {neutral} - 2.49 * {level} * {neutral} +'])
xdd = core.std.Expr([xd, core.std.MakeDiff(src, dehaloed)], expr=[f'x {neutral} - y {neutral} - * 0 < {neutral} x {neutral} - abs y {neutral} - abs < x y ? ?'])
last = core.std.MergeDiff(dehaloed, xdd)
if dehaloed_orig is not None:
last = core.std.ShufflePlanes([last, dehaloed_orig], planes=[0, 1, 2], colorfamily=dehaloed_orig.format.color_family)
return last
# Try to remove 2nd order halos
def FineDehalo2(src, hconv=[-1, -2, 0, 0, 40, 0, 0, -2, -1], vconv=[-2, -1, 0, 0, 40, 0, 0, -1, -2], showmask=0):
def grow_mask(mask, coordinates):
mask = mask.std.Maximum(coordinates=coordinates).std.Minimum(coordinates=coordinates)
mask_1 = mask.std.Maximum(coordinates=coordinates)
mask_2 = mask_1.std.Maximum(coordinates=coordinates).std.Maximum(coordinates=coordinates)
mask = core.std.Expr([mask_2, mask_1], expr=['x y -'])
return mask.std.Convolution(matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1]).std.Expr(expr=['x 1.8 *'])
if not isinstance(src, vs.VideoNode):
raise vs.Error('FineDehalo2: This is not a clip')
if src.format.color_family == vs.RGB:
raise vs.Error('FineDehalo2: RGB format is not supported')
if src.format.color_family != vs.GRAY:
src_orig = src
src = mvf.GetPlane(src, 0)
else:
src_orig = None
fix_h = src.std.Convolution(matrix=vconv, mode='v')
fix_v = src.std.Convolution(matrix=hconv, mode='h')
mask_h = src.std.Convolution(matrix=[1, 2, 1, 0, 0, 0, -1, -2, -1], divisor=4, saturate=False)
mask_v = src.std.Convolution(matrix=[1, 0, -1, 2, 0, -2, 1, 0, -1], divisor=4, saturate=False)
temp_h = core.std.Expr([mask_h, mask_v], expr=['x 3 * y -'])
temp_v = core.std.Expr([mask_v, mask_h], expr=['x 3 * y -'])
mask_h = grow_mask(temp_h, [0, 1, 0, 0, 0, 0, 1, 0])
mask_v = grow_mask(temp_v, [0, 0, 0, 1, 1, 0, 0, 0])
if showmask <= 0:
last = core.std.MaskedMerge(src, fix_h, mask_h)
last = core.std.MaskedMerge(last, fix_v, mask_v)
else:
last = core.std.Expr([mask_h, mask_v], expr=['x y max'])
if src_orig is not None:
if showmask <= 0:
last = core.std.ShufflePlanes([last, src_orig], planes=[0, 1, 2], colorfamily=src_orig.format.color_family)
else:
last = last.resize.Bicubic(format=src_orig.format.id)
return last
# Y'et A'nother H'alo R'educing script
#
# Parameters:
# blur (int) - "blur" parameter of AWarpSharp2. Default is 2
# depth (int) - "depth" parameter of AWarpSharp2. Default is 32
def YAHR(clp, blur=2, depth=32):
if not isinstance(clp, vs.VideoNode):
raise vs.Error('YAHR: This is not a clip')
if clp.format.color_family == vs.RGB:
raise vs.Error('YAHR: RGB format is not supported')
if clp.format.color_family != vs.GRAY:
clp_orig = clp
clp = mvf.GetPlane(clp, 0)
else:
clp_orig = None
b1 = MinBlur(clp, r=2).std.Convolution(matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1])
b1D = core.std.MakeDiff(clp, b1)
w1 = Padding(clp, 6, 6, 6, 6).warp.AWarpSharp2(blur=blur, depth=depth).std.Crop(6, 6, 6, 6)
w1b1 = MinBlur(w1, r=2).std.Convolution(matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1])
w1b1D = core.std.MakeDiff(w1, w1b1)
DD = core.rgvs.Repair(b1D, w1b1D, mode=[13])
DD2 = core.std.MakeDiff(b1D, DD)
last = core.std.MakeDiff(clp, DD2)
if clp_orig is not None:
last = core.std.ShufflePlanes([last, clp_orig], planes=[0, 1, 2], colorfamily=clp_orig.format.color_family)
return last
######
###
### HQDering mod v1.8 by mawen1250 2014.03.22
###
### Requirements: Miscellaneous Filters, RGVS, CTMF
###
### Applies deringing by using a smart smoother near edges (where ringing occurs) only
###
### Parameters:
### mrad (int) - Expanding of edge mask, higher value means more aggressive processing. Default is 1
### msmooth (int) - Inflate of edge mask, smooth boundaries of mask. Default is 1
### incedge (bool) - Whether to include edge in ring mask, by default ring mask only include area near edges. Default is false
### mthr (int) - Threshold of sobel edge mask, lower value means more aggressive processing. Or define your own mask clip "ringmask". Default is 60
### But for strong ringing, lower value will treat some ringing as edge, which protects this ringing from being processed.
### minp (int) - Inpanding of sobel edge mask, higher value means more aggressive processing. Default is 1
### nrmode (int) - Kernel of dering - 1: MinBlur(radius=1), 2: MinBlur(radius=2), 3: MinBlur(radius=3). Or define your own smoothed clip "p". Default is 2 for HD / 1 for SD
### sharp (int) - Whether to use contra-sharpening to resharp deringed clip, 1-3 represents radius, 0 means no sharpening. Default is 1
### drrep (int) - Use repair for details retention, recommended values are 24/23/13/12/1. Default is 24
### thr (float) - The same meaning with "thr" in Dither_limit_dif16, valid value range is [0.0, 128.0]. Default is 12.0
### elast (float) - The same meaning with "elast" in Dither_limit_dif16, valid value range is [1.0, inf). Default is 2.0
### Larger "thr" will result in more pixels being taken from processed clip
### Larger "thr" will result in less pixels being taken from input clip
### Larger "elast" will result in more pixels being blended from processed&input clip, for smoother merging
### darkthr (float) - Threshold for darker area near edges, set it lower if you think deringing destroys too much lines, etc. Default is thr/4
### When "darkthr" is not equal to "thr", "thr" limits darkening while "darkthr" limits brightening
### planes (int[]) - Whether to process the corresponding plane. The other planes will be passed through unchanged. Default is [0]
### show (bool) - Whether to output mask clip instead of filtered clip. Default is false
###
######
def HQDeringmod(input, p=None, ringmask=None, mrad=1, msmooth=1, incedge=False, mthr=60, minp=1, nrmode=None, sharp=1, drrep=24, thr=12.0, elast=2.0, darkthr=None, planes=[0], show=False):
if not isinstance(input, vs.VideoNode):
raise vs.Error('HQDeringmod: This is not a clip')
if input.format.color_family == vs.RGB:
raise vs.Error('HQDeringmod: RGB format is not supported')
if p is not None and (not isinstance(p, vs.VideoNode) or p.format.id != input.format.id):
raise vs.Error("HQDeringmod: 'p' must be the same format as input")
if ringmask is not None and not isinstance(ringmask, vs.VideoNode):
raise vs.Error("HQDeringmod: 'ringmask' is not a clip")
isGray = (input.format.color_family == vs.GRAY)
neutral = 1 << (input.format.bits_per_sample - 1)
peak = (1 << input.format.bits_per_sample) - 1
if isinstance(planes, int):
planes = [planes]
if nrmode is None:
nrmode = 2 if input.width > 1024 or input.height > 576 else 1
if darkthr is None:
darkthr = thr / 4
# Kernel: Smoothing
if p is None:
p = MinBlur(input, r=nrmode, planes=planes)
# Post-Process: Contra-Sharpening
matrix1 = [1, 2, 1, 2, 4, 2, 1, 2, 1]
matrix2 = [1, 1, 1, 1, 1, 1, 1, 1, 1]
if sharp <= 0:
sclp = p
else:
pre = p.std.Median(planes=planes)
if sharp == 1:
method = pre.std.Convolution(matrix=matrix1, planes=planes)
elif sharp == 2:
method = pre.std.Convolution(matrix=matrix1, planes=planes).std.Convolution(matrix=matrix2, planes=planes)
else:
method = pre.std.Convolution(matrix=matrix1, planes=planes).std.Convolution(matrix=matrix2, planes=planes).std.Convolution(matrix=matrix2, planes=planes)
sharpdiff = core.std.MakeDiff(pre, method, planes=planes)
allD = core.std.MakeDiff(input, p, planes=planes)
ssDD = core.rgvs.Repair(sharpdiff, allD, mode=[1 if i in planes else 0 for i in range(input.format.num_planes)])
expr = f'x {neutral} - abs y {neutral} - abs <= x y ?'
ssDD = core.std.Expr([ssDD, sharpdiff], expr=[expr if i in planes else '' for i in range(input.format.num_planes)])
sclp = core.std.MergeDiff(p, ssDD, planes=planes)
# Post-Process: Repairing
if drrep <= 0:
repclp = sclp
else:
repclp = core.rgvs.Repair(input, sclp, mode=[drrep if i in planes else 0 for i in range(input.format.num_planes)])
# Post-Process: Limiting
if (thr <= 0 and darkthr <= 0) or (thr >= 128 and darkthr >= 128):
limitclp = repclp
else:
limitclp = mvf.LimitFilter(repclp, input, thr=thr, elast=elast, brighten_thr=darkthr, planes=planes)
# Post-Process: Ringing Mask Generating
if ringmask is None:
expr = f'x {scale(mthr, peak)} < 0 x ?'
prewittm = AvsPrewitt(input, planes=[0]).std.Expr(expr=[expr] if isGray else [expr, ''])
fmask = core.misc.Hysteresis(prewittm.std.Median(planes=[0]), prewittm, planes=[0])
if mrad > 0:
omask = mt_expand_multi(fmask, planes=[0], sw=mrad, sh=mrad)
else:
omask = fmask
if msmooth > 0:
omask = mt_inflate_multi(omask, planes=[0], radius=msmooth)
if incedge:
ringmask = omask
else:
if minp > 3:
imask = fmask.std.Minimum(planes=[0]).std.Minimum(planes=[0])
elif minp > 2:
imask = fmask.std.Inflate(planes=[0]).std.Minimum(planes=[0]).std.Minimum(planes=[0])
elif minp > 1:
imask = fmask.std.Minimum(planes=[0])
elif minp > 0:
imask = fmask.std.Inflate(planes=[0]).std.Minimum(planes=[0])
else:
imask = fmask
expr = f'x {peak} y - * {peak} /'
ringmask = core.std.Expr([omask, imask], expr=[expr] if isGray else [expr, ''])
# Mask Merging & Output
if show:
if isGray:
return ringmask
else:
return ringmask.std.Expr(expr=['', repr(neutral)])
else:
return core.std.MaskedMerge(input, limitclp, ringmask, planes=planes, first_plane=True)
#-------------------------------------------------------------------#
# #
# QTGMC 3.33, by Vit, 2012 #
# #
# A high quality deinterlacer using motion-compensated temporal #
# smoothing, with a range of features for quality and convenience #
# Originally based on TempGaussMC_beta2 by Didée #
# #
#-------------------------------------------------------------------#
#
# Full documentation is in the 'QTGMC' html file that comes with this script
#
# --- LATEST CHANGES ---
#
# v3.33
# - Increased maximum value for Rep0, Rep1 and Rep2 to 7 (from 5). Higher values help with flicker on static detail, potential for minor motion blur
# - Bug fix for the fact that Bob always outputs a BFF clip regardless of field order of input (thanks ajp_anton)
# - Improved generation of noise (NoiseDeint="Generate") for noise bypass / EZKeepGrain
# - Minor change to denoising
#
# --- REQUIREMENTS ---
#
# Core plugins:
# MVTools
# Miscellaneous Filters
# znedi3
# RGVS
# fmtconv
#
# Additional plugins:
# eedi3m - if selected directly or via a source-match preset
# FFT3DFilter - if selected for noise processing
# DFTTest - if selected for noise processing
# For FFT3DFilter & DFTTest you also need the FFTW3 library (FFTW.org). On Windows the file needed for both is libfftw3f-3.dll.
# Put the file in your System32 or SysWow64 folder
# KNLMeansCL - if selected for noise processing
# AddGrain - if NoiseDeint="Generate" selected for noise bypass
#
# --- GETTING STARTED ---
#
# The "Preset" used selects sensible settings for a given encoding speed. Choose a preset from:
# "Placebo", "Very Slow", "Slower", "Slow", "Medium", "Fast", "Faster", "Very Fast", "Super Fast", "Ultra Fast" & "Draft"
# The default preset is "Slower"
# Don't be obsessed with using slower settings as the differences can be small. HD material benefits little from extreme settings (and will be very slow)
# For much faster speeds read the full documentation, the section on 'Multi-threading'
#
# There are many settings for tweaking the script, full details in the main documentation. You can display settings currently being used with "ShowSettings":
# QTGMC( Preset="Slow", ShowSettings=True )
def QTGMC(Input, Preset='Slower', TR0=None, TR1=None, TR2=None, Rep0=None, Rep1=0, Rep2=None, EdiMode=None, RepChroma=True, NNSize=None, NNeurons=None, EdiQual=1, EdiMaxD=None, ChromaEdi='',
EdiExt=None, Sharpness=None, SMode=None, SLMode=None, SLRad=None, SOvs=0, SVThin=0.0, Sbb=None, SrchClipPP=None, SubPel=None, SubPelInterp=2, BlockSize=None, Overlap=None, Search=None,
SearchParam=None, PelSearch=None, ChromaMotion=None, TrueMotion=False, Lambda=None, LSAD=None, PNew=None, PLevel=None, GlobalMotion=True, DCT=0, ThSAD1=640, ThSAD2=256, ThSCD1=180, ThSCD2=98,
SourceMatch=0, MatchPreset=None, MatchEdi=None, MatchPreset2=None, MatchEdi2=None, MatchTR2=1, MatchEnhance=0.5, Lossless=0, NoiseProcess=None, EZDenoise=None, EZKeepGrain=None,
NoisePreset='Fast', Denoiser=None, FftThreads=1, DenoiseMC=None, NoiseTR=None, Sigma=None, ChromaNoise=False, ShowNoise=0.0, GrainRestore=None, NoiseRestore=None, NoiseDeint=None,
StabilizeNoise=None, InputType=0, ProgSADMask=None, FPSDivisor=1, ShutterBlur=0, ShutterAngleSrc=180, ShutterAngleOut=180, SBlurLimit=4, Border=False, Precise=None, Tuning='None',
ShowSettings=False, ForceTR=0, TFF=None, pscrn=None, int16_prescreener=None, int16_predictor=None, exp=None, alpha=None, beta=None, gamma=None, nrad=None, vcheck=None, opencl=False, device=None):
#---------------------------------------
# Presets
# Select presets / tuning
Preset = Preset.lower()
presets = ['placebo', 'very slow', 'slower', 'slow', 'medium', 'fast', 'faster', 'very fast', 'super fast', 'ultra fast', 'draft']
try:
pNum = presets.index(Preset)
except:
raise vs.Error("QTGMC: 'Preset' choice is invalid")
if MatchPreset is None:
mpNum1 = pNum + 3 if pNum + 3 <= 9 else 9
MatchPreset = presets[mpNum1]
else:
try:
mpNum1 = presets[:10].index(MatchPreset.lower())
except:
raise vs.Error("QTGMC: 'MatchPreset' choice is invalid/unsupported")
if MatchPreset2 is None:
mpNum2 = mpNum1 + 2 if mpNum1 + 2 <= 9 else 9
MatchPreset2 = presets[mpNum2]
else:
try:
mpNum2 = presets[:10].index(MatchPreset2.lower())
except:
raise vs.Error("QTGMC: 'MatchPreset2' choice is invalid/unsupported")
try:
npNum = presets[2:7].index(NoisePreset.lower())
except:
raise vs.Error("QTGMC: 'NoisePreset' choice is invalid")
try:
tNum = ['none', 'dv-sd', 'dv-hd'].index(Tuning.lower())
except:
raise vs.Error("QTGMC: 'Tuning' choice is invalid")
# Tunings only affect blocksize in this version
bs = [16, 16, 32][tNum]
bs2 = 32 if bs >= 16 else bs * 2
# Very Very Super Ultra
# Preset groups: Placebo Slow Slower Slow Medium Fast Faster Fast Fast Fast Draft
if TR0 is None: TR0 = [ 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 0 ][pNum]
if TR1 is None: TR1 = [ 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1 ][pNum]
if TR2 is not None:
TR2X = TR2
else:
TR2X = [ 3, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0 ][pNum]
if Rep0 is None: Rep0 = [ 4, 4, 4, 4, 3, 3, 0, 0, 0, 0, 0 ][pNum]
if Rep2 is None: Rep2 = [ 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 0 ][pNum]
if EdiMode is not None:
EdiMode = EdiMode.lower()
else:
EdiMode = ['nnedi3', 'nnedi3', 'nnedi3', 'nnedi3', 'nnedi3', 'nnedi3', 'nnedi3', 'nnedi3', 'nnedi3', 'nnedi3', 'bob' ][pNum]
if NNSize is None: NNSize = [ 1, 1, 1, 1, 5, 5, 4, 4, 4, 4, 4 ][pNum]
if NNeurons is None: NNeurons = [ 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0 ][pNum]
if EdiMaxD is None: EdiMaxD = [ 12, 10, 8, 7, 7, 6, 6, 5, 4, 4, 4 ][pNum]
ChromaEdi = ChromaEdi.lower()
if SMode is None: SMode = [ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0 ][pNum]
if SLMode is not None:
SLModeX = SLMode
else:
SLModeX = [ 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0 ][pNum]
if SLRad is None: SLRad = [ 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ][pNum]
if Sbb is None: Sbb = [ 3, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ][pNum]
if SrchClipPP is None: SrchClipPP = [ 3, 3, 3, 3, 3, 2, 2, 2, 1, 1, 0 ][pNum]
if SubPel is None: SubPel = [ 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1 ][pNum]
if BlockSize is None: BlockSize = [ bs, bs, bs, bs, bs, bs, bs2, bs2, bs2, bs2, bs2 ][pNum]
bs = BlockSize
if Overlap is None: Overlap = [ bs // 2, bs // 2, bs // 2, bs // 2, bs // 2, bs // 2, bs // 2, bs // 4, bs // 4, bs // 4, bs // 4][pNum]
if Search is None: Search = [ 5, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0 ][pNum]
if SearchParam is None: SearchParam = [ 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1 ][pNum]
if PelSearch is None: PelSearch = [ 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1 ][pNum]
if ChromaMotion is None: ChromaMotion = [ True, True, True, False, False, False, False, False, False, False, False ][pNum]
if Precise is None: Precise = [ True, True, False, False, False, False, False, False, False, False, False ][pNum]
if ProgSADMask is None: ProgSADMask = [ 10.0, 10.0, 10.0, 10.0, 10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ][pNum]
# Noise presets Slower Slow Medium Fast Faster
if Denoiser is not None:
Denoiser = Denoiser.lower()
else:
Denoiser = ['dfttest', 'dfttest', 'dfttest', 'fft3df', 'fft3df'][npNum]
if DenoiseMC is None: DenoiseMC = [ True, True, False, False, False ][npNum]
if NoiseTR is None: NoiseTR = [ 2, 1, 1, 1, 0 ][npNum]
if NoiseDeint is not None:
NoiseDeint = NoiseDeint.lower()
else:
NoiseDeint = ['generate', 'bob', '', '', '' ][npNum]
if StabilizeNoise is None: StabilizeNoise = [ True, True, True, False, False ][npNum]
# The basic source-match step corrects and re-runs the interpolation of the input clip. So it initialy uses same interpolation settings as the main preset
MatchNNSize = NNSize
MatchNNeurons = NNeurons
MatchEdiQual = EdiQual
MatchEdiMaxD = EdiMaxD
# However, can use a faster initial interpolation when using source-match allowing the basic source-match step to "correct" it with higher quality settings
if SourceMatch > 0 and mpNum1 < pNum:
raise vs.Error("QTGMC: 'MatchPreset' cannot use a slower setting than 'Preset'")
# Basic source-match presets
if SourceMatch > 0:
# Very Very Super Ultra
# Placebo Slow Slower Slow Medium Fast Faster Fast Fast Fast
NNSize = [1, 1, 1, 1, 5, 5, 4, 4, 4, 4][mpNum1]
NNeurons = [2, 2, 1, 1, 1, 0, 0, 0, 0, 0][mpNum1]