-
Notifications
You must be signed in to change notification settings - Fork 156
/
qtgmc.py
2686 lines (2326 loc) · 133 KB
/
qtgmc.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
##################################################
### K7sfunc 的可选附属脚本
##################################################
__version__ = "0.1.1"
__all__ = ["QTGMC", "QTGMC_obs", "QTGMCv2"]
from distutils.version import LooseVersion
import functools
import math
import typing
import vapoursynth as vs
core = vs.core
vstools = None
QTGMC_globals = {}
dfttest2 = None
### MOD HAvsFunc (f11d79c98589c9dcb5b10beec35b631db68b495c)
def QTGMC(
Input: vs.VideoNode,
Preset: str = 'Slower',
TR0: typing.Optional[int] = None,
TR1: typing.Optional[int] = None,
TR2: typing.Optional[int] = None,
Rep0: typing.Optional[int] = None,
Rep1: int = 0,
Rep2: typing.Optional[int] = None,
EdiMode: typing.Optional[str] = None,
RepChroma: bool = True,
NNSize: typing.Optional[int] = None,
NNeurons: typing.Optional[int] = None,
EdiQual: int = 1,
EdiMaxD: typing.Optional[int] = None,
ChromaEdi: str = '',
EdiExt: typing.Optional[vs.VideoNode] = None,
Sharpness: typing.Optional[float] = None,
SMode: typing.Optional[int] = None,
SLMode: typing.Optional[int] = None,
SLRad: typing.Optional[int] = None,
SOvs: int = 0,
SVThin: float = 0.0,
Sbb: typing.Optional[int] = None,
SrchClipPP: typing.Optional[int] = None,
SubPel: typing.Optional[int] = None,
SubPelInterp: int = 2,
BlockSize: typing.Optional[int] = None,
Overlap: typing.Optional[int] = None,
Search: typing.Optional[int] = None,
SearchParam: typing.Optional[int] = None,
PelSearch: typing.Optional[int] = None,
ChromaMotion: typing.Optional[bool] = None,
TrueMotion: bool = False,
Lambda: typing.Optional[int] = None,
LSAD: typing.Optional[int] = None,
PNew: typing.Optional[int] = None,
PLevel: typing.Optional[int] = None,
GlobalMotion: bool = True,
DCT: int = 0,
ThSAD1: int = 640,
ThSAD2: int = 256,
ThSCD1: int = 180,
ThSCD2: int = 98,
SourceMatch: int = 0,
MatchPreset: typing.Optional[str] = None,
MatchEdi: typing.Optional[str] = None,
MatchPreset2: typing.Optional[str] = None,
MatchEdi2: typing.Optional[str] = None,
MatchTR2: int = 1,
MatchEnhance: float = 0.5,
Lossless: int = 0,
NoiseProcess: typing.Optional[int] = None,
EZDenoise: typing.Optional[float] = None,
EZKeepGrain: typing.Optional[float] = None,
NoisePreset: str = 'Fast',
Denoiser: typing.Optional[str] = None,
FftThreads: int = 1,
DenoiseMC: typing.Optional[bool] = None,
NoiseTR: typing.Optional[int] = None,
Sigma: typing.Optional[float] = None,
ChromaNoise: bool = False,
ShowNoise: typing.Union[bool, float] = 0.0,
GrainRestore: typing.Optional[float] = None,
NoiseRestore: typing.Optional[float] = None,
NoiseDeint: typing.Optional[str] = None,
StabilizeNoise: typing.Optional[bool] = None,
InputType: int = 0,
ProgSADMask: typing.Optional[float] = None,
FPSDivisor: int = 1,
ShutterBlur: int = 0,
ShutterAngleSrc: float = 180.0,
ShutterAngleOut: float = 180.0,
SBlurLimit: int = 4,
Border: bool = False,
Precise: typing.Optional[bool] = None,
Tuning: str = 'None',
ShowSettings: bool = False,
GlobalNames: str = 'QTGMC',
PrevGlobals: str = 'Replace',
ForceTR: int = 0,
Str: float = 2.0,
Amp: float = 0.0625,
FastMA: bool = False,
ESearchP: bool = False,
RefineMotion: bool = False,
TFF: typing.Optional[bool] = None,
nnedi3_args: typing.Mapping[str, typing.Any] = {},
eedi3_args: typing.Mapping[str, typing.Any] = {},
opencl: bool = False,
device: typing.Optional[int] = None,
) -> vs.VideoNode:
'''
QTGMC 3.33
A very high quality deinterlacer with a range of features for both quality and convenience. These include a simple presets system, extensive noise
processing capabilities, support for repair of progressive material, precision source matching, shutter speed simulation, etc. Originally based on
TempGaussMC_beta2 by Didée.
Parameters:
Input: Clip to process.
Preset: Sets a range of defaults for different encoding speeds.
Select from "Placebo", "Very Slow", "Slower", "Slow", "Medium", "Fast", "Faster", "Very Fast", "Super Fast", "Ultra Fast" & "Draft".
TR0: Temporal binomial smoothing radius used to create motion search clip. In general 2=quality, 1=speed, 0=don't use.
TR1: Temporal binomial smoothing radius used on interpolated clip for initial output. In general 2=quality, 1=speed, 0=don't use.
TR2: Temporal linear smoothing radius used for final stablization / denoising. Increase for smoother output.
Rep0: Repair motion search clip (0=off): repair unwanted blur after temporal smooth TR0 (see QTGMC_KeepOnlyBobShimmerFixes function for details).
Rep1: Repair initial output clip (0=off): repair unwanted blur after temporal smooth TR1.
Rep2: Repair final output clip (0=off): unwanted blur after temporal smooth TR2 (will also repair TR1 blur if Rep1 not used).
EdiMode: Interpolation method, from "NNEDI3", "EEDI3+NNEDI3" (EEDI3 with sclip from NNEDI3), "EEDI3" or "Bwdif", anything else uses "Bob".
RepChroma: Whether the repair modes affect chroma.
NNSize: Area around each pixel used as predictor for NNEDI3. A larger area is slower with better quality, read the NNEDI3 docs to see the area choices.
Note: area sizes are not in increasing order (i.e. increased value doesn't always mean increased quality).
NNeurons: Controls number of neurons in NNEDI3, larger = slower and better quality but improvements are small.
EdiQual: Quality setting for NNEDI3. Higher values for better quality - but improvements are marginal.
EdiMaxD: Spatial search distance for finding connecting edges in EEDI3.
ChromaEdi: Interpolation method used for chroma. Set to "" to use EdiMode above (default). Otherwise choose from "NNEDI3", "Bwdif" or "Bob" - all high
speed variants. This can give a minor speed-up if using a very slow EdiMode (i.e. one of the EEDIx modes).
EdiExt: Provide externally created interpolated clip rather than use one of the above modes.
Sharpness: How much to resharpen the temporally blurred clip (default is always 1.0 unlike original TGMC).
SMode: Resharpening mode.
0 = none
1 = difference from 3x3 blur kernel
2 = vertical max/min average + 3x3 kernel
SLMode: Sharpness limiting.
0 = off
[1 = spatial, 2 = temporal]: before final temporal smooth
[3 = spatial, 4 = temporal]: after final temporal smooth
SLRad: Temporal or spatial radius used with sharpness limiting (depends on SLMode). Temporal radius can only be 0, 1 or 3.
SOvs: Amount of overshoot allowed with temporal sharpness limiting (SLMode=2,4), i.e. allow some oversharpening.
SVThin: How much to thin down 1-pixel wide lines that have been widened due to interpolation into neighboring field lines.
Sbb: Back blend (blurred) difference between pre & post sharpened clip (minor fidelity improvement).
0 = off
1 = before (1st) sharpness limiting
2 = after (1st) sharpness limiting
3 = both
SrchClipPP: Pre-filtering for motion search clip.
0 = none
1 = simple blur
2 = Gauss blur
3 = Gauss blur + edge soften
SubPel: Sub-pixel accuracy for motion analysis.
1 = 1 pixel
2 = 1/2 pixel
4 = 1/4 pixel
SubPelInterp: Interpolation used for sub-pixel motion analysis.
0 = bilinear (soft)
1 = bicubic (sharper)
2 = Weiner (sharpest)
BlockSize: Size of blocks that are matched during motion analysis.
Overlap: How much to overlap motion analysis blocks (requires more blocks, but essential to smooth block edges in motion compenstion).
Search: Search method used for matching motion blocks - see MVTools2 documentation for available algorithms.
SearchParam: Parameter for search method chosen. For default search method (hexagon search) it is the search range.
PelSearch: Search parameter (as above) for the finest sub-pixel level (see SubPel).
ChromaMotion: Whether to consider chroma when analyzing motion. Setting to false gives good speed-up,
but may very occasionally make incorrect motion decision.
TrueMotion: Whether to use the 'truemotion' defaults from MAnalyse (see MVTools2 documentation).
Lambda: Motion vector field coherence - how much the motion analysis favors similar motion vectors for neighboring blocks.
Should be scaled by BlockSize*BlockSize/64.
LSAD: How much to reduce need for vector coherence (i.e. Lambda above) if prediction of motion vector from neighbors is poor,
typically in areas of complex motion. This value is scaled in MVTools (unlike Lambda).
PNew: Penalty for choosing a new motion vector for a block over an existing one - avoids choosing new vectors for minor gain.
PLevel: Mode for scaling lambda across different sub-pixel levels - see MVTools2 documentation for choices.
GlobalMotion: Whether to estimate camera motion to assist in selecting block motion vectors.
DCT: Modes to use DCT (frequency analysis) or SATD as part of the block matching process - see MVTools2 documentation for choices.
ThSAD1: SAD threshold for block match on shimmer-removing temporal smooth (TR1). Increase to reduce bob-shimmer more (may smear/blur).
ThSAD2: SAD threshold for block match on final denoising temporal smooth (TR2). Increase to strengthen final smooth (may smear/blur).
ThSCD1: Scene change detection parameter 1 - see MVTools documentation.
ThSCD2: Scene change detection parameter 2 - see MVTools documentation.
SourceMatch:
0 = source-matching off (standard algorithm)
1 = basic source-match
2 = refined match
3 = twice refined match
MatchPreset: Speed/quality for basic source-match processing, select from "Placebo", "Very Slow", "Slower", "Slow", "Medium", "Fast", "Faster",
"Very Fast", "Super Fast", "Ultra Fast" ("Draft" is not supported). Ideal choice is the same as main preset,
but can choose a faster setting (but not a slower setting). Default is 3 steps faster than main Preset.
MatchEdi: Override default interpolation method for basic source-match. Default method is same as main EdiMode setting (usually NNEDI3).
Only need to override if using slow method for main interpolation (e.g. EEDI3) and want a faster method for source-match.
MatchPreset2: Speed/quality for refined source-match processing, select from "Placebo", "Very Slow", "Slower", "Slow", "Medium", "Fast", "Faster",
"Very Fast", "Super Fast", "Ultra Fast" ("Draft" is not supported). Default is 2 steps faster than MatchPreset.
Faster settings are usually sufficient but can use slower settings if you get extra aliasing in this mode.
MatchEdi2: Override interpolation method for refined source-match. Can be a good idea to pick MatchEdi2="Bob" for speed.
MatchTR2: Temporal radius for refined source-matching. 2=smoothness, 1=speed/sharper, 0=not recommended. Differences are very marginal.
Basic source-match doesn't need this setting as its temporal radius must match TR1 core setting (i.e. there is no MatchTR1).
MatchEnhance: Enhance the detail found by source-match modes 2 & 3. A slight cheat - will enhance noise if set too strong. Best set < 1.0.
Lossless: Puts exact source fields into result & cleans any artefacts. 0=off, 1=after final temporal smooth, 2=before resharpening.
Adds some extra detail but: mode 1 gets shimmer / minor combing, mode 2 is more stable/tweakable but not exactly lossless.
NoiseProcess: Bypass mode.
0 = disable
1 = denoise source & optionally restore some noise back at end of script [use for stronger denoising]
2 = identify noise only & optionally restore some after QTGMC smoothing [for grain retention / light denoising]
EZDenoise: Automatic setting to denoise source. Set > 0.0 to enable. Higher values denoise more. Can use ShowNoise to help choose value.
EZKeepGrain: Automatic setting to retain source grain/detail. Set > 0.0 to enable. Higher values retain more grain. A good starting point = 1.0.
NoisePreset: Automatic setting for quality of noise processing. Choices: "Slower", "Slow", "Medium", "Fast", and "Faster".
Denoiser: Select denoiser to use for noise bypass / denoising. Select from "bm3d", "dfttest", "fft3dfilter" or "knlmeanscl".
Unknown value selects "fft3dfilter".
FftThreads: Number of threads to use if using "fft3dfilter" for Denoiser.
DenoiseMC: Whether to provide a motion-compensated clip to the denoiser for better noise vs detail detection (will be a little slower).
NoiseTR: Temporal radius used when analyzing clip for noise extraction. Higher values better identify noise vs detail but are slower.
Sigma: Amount of noise known to be in the source, sensible values vary by source and denoiser, so experiment. Use ShowNoise to help.
ChromaNoise: When processing noise (NoiseProcess > 0), whether to process chroma noise or not (luma noise is always processed).
ShowNoise: Display extracted and "deinterlaced" noise rather than normal output. Set to true or false, or set a value (around 4 to 16) to specify
contrast for displayed noise. Visualising noise helps to determine suitable value for Sigma or EZDenoise - want to see noise and noisy detail,
but not too much clean structure or edges - fairly subjective.
GrainRestore: How much removed noise/grain to restore before final temporal smooth. Retain "stable" grain and some detail (effect depends on TR2).
NoiseRestore: How much removed noise/grain to restore after final temporal smooth. Retains any kind of noise.
NoiseDeint: When noise is taken from interlaced source, how to 'deinterlace' it before restoring.
"Bob" & "DoubleWeave" are fast but with minor issues: "Bob" is coarse and "Doubleweave" lags by one frame.
"Generate" is a high quality mode that generates fresh noise lines, but it is slower. Unknown value selects "DoubleWeave".
StabilizeNoise: Use motion compensation to limit shimmering and strengthen detail within the restored noise. Recommended for "Generate" mode.
InputType: Default = 0 for interlaced input. Settings 1, 2 & 3 accept progressive input for deshimmer or repair. Frame rate of progressive source is not
doubled. Mode 1 is for general progressive material. Modes 2 & 3 are designed for badly deinterlaced material.
ProgSADMask: Only applies to InputType=2,3. If ProgSADMask > 0.0 then blend InputType modes 1 and 2/3 based on block motion SAD.
Higher values help recover more detail, but repair less artefacts. Reasonable range about 2.0 to 20.0, or 0.0 for no blending.
FPSDivisor: 1=Double-rate output, 2=Single-rate output. Higher values can be used too (e.g. 60fps & FPSDivisor=3 gives 20fps output).
ShutterBlur: 0=Off, 1=Enable, 2,3=Higher precisions (slower). Higher precisions reduce blur "bleeding" into static areas a little.
ShutterAngleSrc: Shutter angle used in source. If necessary, estimate from motion blur seen in a single frame.
0=pin-sharp, 360=fully blurred from frame to frame.
ShutterAngleOut: Shutter angle to simulate in output. Extreme values may be rejected (depends on other settings).
Cannot reduce motion blur already in the source.
SBlurLimit: Limit motion blur where motion lower than given value. Increase to reduce blur "bleeding". 0=Off. Sensible range around 2-12.
Border: Pad a little vertically while processing (doesn't affect output size) - set true you see flickering on the very top or bottom line of the
output. If you have wider edge effects than that, you should crop afterwards instead.
Precise: Set to false to use faster algorithms with *very* slight imprecision in places.
Tuning: Tweaks the defaults for different source types. Choose from "None", "DV-SD", "DV-HD".
ShowSettings: Display all the current parameter values - useful to find preset defaults.
GlobalNames: The name used to expose intermediate clips to calling script. QTGMC now exposes its motion vectors and other intermediate clips to the
calling script through global variables. These globals are uniquely named. By default they begin with the prefix "QTGMC_". The available clips are:
Backward motion vectors bVec1, bVec2, bVec3 (temporal radius 1 to 3)
Forward motion vectors fVec1, fVec2, fVec3
Filtered clip used for motion analysis srchClip
MVTools "super" clip for filtered clip srchSuper
Not all these clips are necessarily created - it depends on your QTGMC settings. To ensure motion vector creation to radius X, set ForceTR=X
Clips can be accessed from other scripts with havsfunc.QTGMC_globals['Prefix_Name']
PrevGlobals: What to do with global variables from earlier QTGMC call that match above name. Either "Replace", or "Reuse" (for a speed-up).
Set PrevGlobals="Reuse" to reuse existing similar named globals for this run & not recalculate motion vectors etc. This will improve performance.
Set PrevGlobals="Replace" to overwrite similar named globals from a previous run. This is the default and easiest option for most use cases.
ForceTR: Ensure globally exposed motion vectors are calculated to this radius even if not needed by QTGMC.
Str: With this parameter you control the strength of the brightening of the prefilter clip for motion analysis.
This is good when problems with dark areas arise.
Amp: Use this together with Str (active when Str is different from 1.0). This defines the amplitude of the brightening in the luma range,
for example by using 1.0 all the luma range will be used and the brightening will find its peak at luma value 128 in the original.
FastMA: Use 8-bit for faster motion analysis when using high bit depth input.
ESearchP: Use wider search range for hex and umh search method.
RefineMotion: Refines and recalculates motion data of previously estimated motion vectors with new parameters set (e.g. lesser block size).
The two-stage method may be also useful for more stable (robust) motion estimation.
TFF: Since VapourSynth only has a weak notion of field order internally, TFF may have to be set. Setting TFF to true means top field first and false
means bottom field first. Note that the _FieldBased frame property, if present, takes precedence over TFF.
nnedi3_args: Additional arguments to pass to NNEDI3.
eedi3_args: Additional arguments to pass to EEDI3.
opencl: Whether to use the OpenCL version of NNEDI3 and EEDI3.
device: Sets target OpenCL device.
'''
global vstools
if vstools is None :
import vstools
import vsdenoise
import vsexprtools
import vsrgtools
global dfttest2
if dfttest2 is None :
import dfttest2
if LooseVersion(dfttest2.__version__) < LooseVersion("0.3.3") :
raise EnvironmentError("依赖 dfttest2 的版本号过低,至少 0.3.3")
def _average_frames(
clip: vs.VideoNode, weights: float | typing.Sequence[float], scenechange: float | None = None, planes: vstools.PlanesT = None
) -> vs.VideoNode:
assert vstools.check_variable(clip, _average_frames)
planes = vstools.normalize_planes(clip, planes)
def _scdetect(clip: vs.VideoNode, threshold: float = 0.1) -> vs.VideoNode:
def _copy_property(n: int, f: list[vs.VideoFrame]) -> vs.VideoFrame:
fout = f[0].copy()
fout.props["_SceneChangePrev"] = f[1].props["_SceneChangePrev"]
fout.props["_SceneChangeNext"] = f[1].props["_SceneChangeNext"]
return fout
assert vstools.check_variable(clip, _scdetect)
sc = clip
if clip.format.color_family == vs.RGB:
sc = clip.resize.Point(format=vs.GRAY8, matrix_s="709")
sc = sc.misc.SCDetect(threshold)
if clip.format.color_family == vs.RGB:
sc = clip.std.ModifyFrame([clip, sc], _copy_property)
return sc
if scenechange:
clip = _scdetect(clip, scenechange)
return clip.std.AverageFrames(weights=weights, scenechange=scenechange, planes=planes)
def _mt_clamp(
clip: vs.VideoNode,
bright: vs.VideoNode,
dark: vs.VideoNode,
overshoot: int = 0,
undershoot: int = 0,
planes: vstools.PlanesT = None,
) -> vs.VideoNode:
## clamp the value of the clip between bright + overshoot and dark - undershoot
vstools.check_ref_clip(clip, bright, _mt_clamp)
vstools.check_ref_clip(clip, dark, _mt_clamp)
planes = vstools.normalize_planes(clip, planes)
if vsexprtools.complexpr_available:
expr = f"x z {undershoot} - y {overshoot} + clamp"
else:
expr = f"x z {undershoot} - max y {overshoot} + min"
return vsexprtools.norm_expr([clip, bright, dark], expr, planes)
if not isinstance(Input, vs.VideoNode):
raise vs.Error('QTGMC: this is not a clip')
if EdiExt is not None:
if not isinstance(EdiExt, vs.VideoNode):
raise vs.Error('QTGMC: EdiExt is not a clip')
if EdiExt.format.id != Input.format.id:
raise vs.Error('QTGMC: EdiExt must have the same format as input')
if InputType != 1 and TFF is None:
with Input.get_frame(0) as f:
if (field_based := f.props.get('_FieldBased')) not in [1, 2]:
raise vs.Error('QTGMC: TFF was not specified and field order could not be determined from frame properties')
TFF = field_based == 2
is_gray = Input.format.color_family == vs.GRAY
bits = vstools.get_depth(Input)
neutral = 1 << (bits - 1)
SOvs = vstools.scale_value(SOvs, 8, bits)
# ---------------------------------------
# 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 ValueError:
raise vs.Error("QTGMC: 'Preset' choice is invalid")
if MatchPreset is None:
mpNum1 = min(pNum + 3, 9)
MatchPreset = presets[mpNum1]
else:
try:
mpNum1 = presets[:10].index(MatchPreset.lower())
except ValueError:
raise vs.Error("QTGMC: 'MatchPreset' choice is invalid/unsupported")
if MatchPreset2 is None:
mpNum2 = min(mpNum1 + 2, 9)
MatchPreset2 = presets[mpNum2]
else:
try:
mpNum2 = presets[:10].index(MatchPreset2.lower())
except ValueError:
raise vs.Error("QTGMC: 'MatchPreset2' choice is invalid/unsupported")
try:
npNum = presets[2:7].index(NoisePreset.lower())
except ValueError:
raise vs.Error("QTGMC: 'NoisePreset' choice is invalid")
try:
tNum = ['none', 'dv-sd', 'dv-hd'].index(Tuning.lower())
except ValueError:
raise vs.Error("QTGMC: 'Tuning' choice is invalid")
# Tunings only affect blocksize in this version
bs = [16, 16, 32][tNum]
bs2 = 32
# fmt: off
# Very Very Super Ultra
# Preset groups: Placebo Slow Slower Slow Medium Fast Faster Fast Fast Fast Draft
TR0 = vstools.fallback(TR0, [ 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 0 ][pNum])
TR1 = vstools.fallback(TR1, [ 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1 ][pNum])
TR2X = vstools.fallback(TR2, [ 3, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0 ][pNum])
Rep0 = vstools.fallback(Rep0, [ 4, 4, 4, 4, 3, 3, 0, 0, 0, 0, 0 ][pNum])
Rep2 = vstools.fallback(Rep2, [ 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 0 ][pNum])
EdiMode = vstools.fallback(EdiMode, ['NNEDI3', 'NNEDI3', 'NNEDI3', 'NNEDI3', 'NNEDI3', 'NNEDI3', 'NNEDI3', 'NNEDI3', 'NNEDI3', 'Bwdif', 'Bob' ][pNum]).lower()
NNSize = vstools.fallback(NNSize, [ 1, 1, 1, 1, 5, 5, 4, 4, 4, 4, 4 ][pNum])
NNeurons = vstools.fallback(NNeurons, [ 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0 ][pNum])
EdiMaxD = vstools.fallback(EdiMaxD, [ 12, 10, 8, 7, 7, 6, 6, 5, 4, 4, 4 ][pNum])
SMode = vstools.fallback(SMode, [ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0 ][pNum])
SLModeX = vstools.fallback(SLMode, [ 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0 ][pNum])
SLRad = vstools.fallback(SLRad, [ 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ][pNum])
Sbb = vstools.fallback(Sbb, [ 3, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ][pNum])
SrchClipPP = vstools.fallback(SrchClipPP, [ 3, 3, 3, 3, 3, 2, 2, 2, 1, 1, 0 ][pNum])
SubPel = vstools.fallback(SubPel, [ 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1 ][pNum])
BlockSize = vstools.fallback(BlockSize, [ bs, bs, bs, bs, bs, bs, bs2, bs2, bs2, bs2, bs2 ][pNum])
bs = BlockSize
Overlap = vstools.fallback(Overlap, [ bs // 2, bs // 2, bs // 2, bs // 2, bs // 2, bs // 2, bs // 2, bs // 4, bs // 4, bs // 4, bs // 4][pNum])
Search = vstools.fallback(Search, [ 5, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0 ][pNum])
SearchParam = vstools.fallback(SearchParam, [ 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1 ][pNum])
PelSearch = vstools.fallback(PelSearch, [ 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1 ][pNum])
ChromaMotion = vstools.fallback(ChromaMotion, [ True, True, True, False, False, False, False, False, False, False, False ][pNum])
Precise = vstools.fallback(Precise, [ True, True, False, False, False, False, False, False, False, False, False ][pNum])
ProgSADMask = vstools.fallback(ProgSADMask, [ 10.0, 10.0, 10.0, 10.0, 10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ][pNum])
if ESearchP and Search in [4, 5]:
if pNum < 4:
SearchParam = 24
elif pNum < 8:
SearchParam = 16
# Noise presets Slower Slow Medium Fast Faster
Denoiser = vstools.fallback(Denoiser, ['dfttest', 'dfttest', 'dfttest', 'fft3df', 'fft3df'][npNum]).lower()
DenoiseMC = vstools.fallback(DenoiseMC, [ True, True, False, False, False ][npNum])
NoiseTR = vstools.fallback(NoiseTR, [ 2, 1, 1, 1, 0 ][npNum])
NoiseDeint = vstools.fallback(NoiseDeint, ['Generate', 'Bob', '', '', '' ][npNum]).lower()
StabilizeNoise = vstools.fallback(StabilizeNoise, [ True, True, True, False, False ][npNum])
# fmt: on
# The basic source-match step corrects and re-runs the interpolation of the input clip. So it initially uses same interpolation settings as the main preset
MatchNNSize = NNSize
MatchNNeurons = NNeurons
MatchEdiMaxD = EdiMaxD
MatchEdiQual = EdiQual
# 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:
# fmt: off
# 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]
EdiMaxD = [12, 10, 8, 7, 7, 6, 6, 5, 4, 4 ][mpNum1]
EdiQual = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ][mpNum1]
# fmt: on
TempEdi = EdiMode # Main interpolation is actually done by basic-source match step when enabled, so a little swap and wriggle is needed
if SourceMatch > 0:
EdiMode = vstools.fallback(MatchEdi, EdiMode if mpNum1 < 9 else 'Bwdif').lower() # Force Bwdif for "Ultra Fast" basic source match
MatchEdi = TempEdi
# fmt: off
# Very Very Super Ultra
# Refined source-match presets Placebo Slow Slower Slow Medium Fast Faster Fast Fast Fast
MatchEdi2 = vstools.fallback(MatchEdi2, ['NNEDI3', 'NNEDI3', 'NNEDI3', 'NNEDI3', 'NNEDI3', 'NNEDI3', 'NNEDI3', 'NNEDI3', 'NNEDI3', '' ][mpNum2]).lower()
MatchNNSize2 = [ 1, 1, 1, 1, 5, 5, 4, 4, 4, 4 ][mpNum2]
MatchNNeurons2 = [ 2, 2, 1, 1, 1, 0, 0, 0, 0, 0 ][mpNum2]
MatchEdiMaxD2 = [ 12, 10, 8, 7, 7, 6, 6, 5, 4, 4 ][mpNum2]
MatchEdiQual2 = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ][mpNum2]
# fmt: on
# ---------------------------------------
# Settings
# Core defaults
TR2 = vstools.fallback(TR2, max(TR2X, 1)) if SourceMatch > 0 else TR2X # ***TR2 defaults always at least 1 when using source-match***
# Source-match defaults
MatchTR1 = TR1
# Sharpness defaults. Sharpness default is always 1.0 (0.2 with source-match), but adjusted to give roughly same sharpness for all settings
if Sharpness is not None and Sharpness <= 0:
SMode = 0
SLMode = vstools.fallback(SLMode, 0) if SourceMatch > 0 else SLModeX # ***Sharpness limiting disabled by default for source-match***
if SLRad <= 0:
SLMode = 0
spatialSL = SLMode in [1, 3]
temporalSL = SLMode in [2, 4]
Sharpness = vstools.fallback(Sharpness, 0.0 if SMode <= 0 else 0.2 if SourceMatch > 0 else 1.0) # Default sharpness is 1.0, or 0.2 if using source-match
sharpMul = 2 if temporalSL else 1.5 if spatialSL else 1 # Adjust sharpness based on other settings
sharpAdj = Sharpness * (sharpMul * (0.2 + TR1 * 0.15 + TR2 * 0.25) + (0.1 if SMode == 1 else 0)) # [This needs a bit more refinement]
if SMode <= 0:
Sbb = 0
# Noise processing settings
if EZDenoise is not None and EZDenoise > 0 and EZKeepGrain is not None and EZKeepGrain > 0:
raise vs.Error("QTGMC: EZDenoise and EZKeepGrain cannot be used together")
if NoiseProcess is None:
if EZDenoise is not None and EZDenoise > 0:
NoiseProcess = 1
elif (EZKeepGrain is not None and EZKeepGrain > 0) or Preset in ['placebo', 'very slow']:
NoiseProcess = 2
else:
NoiseProcess = 0
if GrainRestore is None:
if EZDenoise is not None and EZDenoise > 0:
GrainRestore = 0.0
elif EZKeepGrain is not None and EZKeepGrain > 0:
GrainRestore = 0.3 * math.sqrt(EZKeepGrain)
else:
GrainRestore = [0.0, 0.7, 0.3][NoiseProcess]
if NoiseRestore is None:
if EZDenoise is not None and EZDenoise > 0:
NoiseRestore = 0.0
elif EZKeepGrain is not None and EZKeepGrain > 0:
NoiseRestore = 0.1 * math.sqrt(EZKeepGrain)
else:
NoiseRestore = [0.0, 0.3, 0.1][NoiseProcess]
if Sigma is None:
if EZDenoise is not None and EZDenoise > 0:
Sigma = EZDenoise
elif EZKeepGrain is not None and EZKeepGrain > 0:
Sigma = 4.0 * EZKeepGrain
else:
Sigma = 2.0
if isinstance(ShowNoise, bool):
ShowNoise = 10.0 if ShowNoise else 0.0
if ShowNoise > 0:
NoiseProcess = 2
NoiseRestore = 1.0
if NoiseProcess <= 0:
NoiseTR = 0
GrainRestore = 0.0
NoiseRestore = 0.0
totalRestore = GrainRestore + NoiseRestore
if totalRestore <= 0:
StabilizeNoise = False
noiseTD = [1, 3, 5][NoiseTR]
noiseCentre = vstools.scale_value(128.5, 8, bits) if Denoiser in ['fft3df', 'fft3dfilter'] else neutral
# MVTools settings
Lambda = vstools.fallback(Lambda, (1000 if TrueMotion else 100) * BlockSize * BlockSize // 64)
LSAD = vstools.fallback(LSAD, 1200 if TrueMotion else 400)
PNew = vstools.fallback(PNew, 50 if TrueMotion else 25)
PLevel = vstools.fallback(PLevel, 1 if TrueMotion else 0)
# Motion blur settings
if ShutterAngleOut * FPSDivisor == ShutterAngleSrc: # If motion blur output is same as input
ShutterBlur = 0
# Miscellaneous
PrevGlobals = PrevGlobals.lower()
ReplaceGlobals = PrevGlobals in ['replace', 'reuse'] # If reusing existing globals put them back afterwards - simplifies logic later
ReuseGlobals = PrevGlobals == 'reuse'
if InputType < 2:
ProgSADMask = 0.0
# Get maximum temporal radius needed
maxTR = max(SLRad if temporalSL else 0, MatchTR2, TR1, TR2, NoiseTR)
if (ProgSADMask > 0 or StabilizeNoise or ShutterBlur > 0) and maxTR < 1:
maxTR = 1
maxTR = max(ForceTR, maxTR)
# ---------------------------------------
# Pre-Processing
w = Input.width
h = Input.height
# Reverse "field" dominance for progressive repair mode 3 (only difference from mode 2)
if InputType >= 3:
TFF = not TFF
# Pad vertically during processing (to prevent artefacts at top & bottom edges)
if Border:
h += 8
clip = Input.resize.Point(w, h, src_top=-4, src_height=h)
else:
clip = Input
hpad = vpad = BlockSize
# ---------------------------------------
# Motion Analysis
# Bob the input as a starting point for motion search clip
if InputType <= 0:
bobbed = clip.resize.Bob(tff=TFF, filter_param_a=0, filter_param_b=0.5)
elif InputType == 1:
bobbed = clip
else:
bobbed = clip.std.Convolution(matrix=[1, 2, 1], mode='v')
# If required, get any existing global clips with a matching "GlobalNames" setting. Unmatched values get None
if ReuseGlobals:
srchClip = QTGMC_GetUserGlobal(GlobalNames, 'srchClip')
srchSuper = QTGMC_GetUserGlobal(GlobalNames, 'srchSuper')
bVec1 = QTGMC_GetUserGlobal(GlobalNames, 'bVec1')
fVec1 = QTGMC_GetUserGlobal(GlobalNames, 'fVec1')
bVec2 = QTGMC_GetUserGlobal(GlobalNames, 'bVec2')
fVec2 = QTGMC_GetUserGlobal(GlobalNames, 'fVec2')
bVec3 = QTGMC_GetUserGlobal(GlobalNames, 'bVec3')
fVec3 = QTGMC_GetUserGlobal(GlobalNames, 'fVec3')
else:
srchClip = srchSuper = bVec1 = fVec1 = bVec2 = fVec2 = bVec3 = fVec3 = None
CMplanes = [0, 1, 2] if ChromaMotion and not is_gray else [0]
# The bobbed clip will shimmer due to being derived from alternating fields. Temporally smooth over the neighboring frames using a binomial kernel. Binomial
# kernels give equal weight to even and odd frames and hence average away the shimmer. The two kernels used are [1 2 1] and [1 4 6 4 1] for radius 1 and 2.
# These kernels are approximately Gaussian kernels, which work well as a prefilter before motion analysis (hence the original name for this script)
# Create linear weightings of neighbors first -2 -1 0 1 2
if not isinstance(srchClip, vs.VideoNode):
if TR0 > 0:
ts1 = _average_frames(bobbed, weights=[1] * 3, scenechange=28 / 255, planes=CMplanes) # 0.00 0.33 0.33 0.33 0.00
if TR0 > 1:
ts2 = _average_frames(bobbed, weights=[1] * 5, scenechange=28 / 255, planes=CMplanes) # 0.20 0.20 0.20 0.20 0.20
# Combine linear weightings to give binomial weightings - TR0=0: (1), TR0=1: (1:2:1), TR0=2: (1:4:6:4:1)
if isinstance(srchClip, vs.VideoNode):
binomial0 = None
elif TR0 <= 0:
binomial0 = bobbed
elif TR0 == 1:
binomial0 = core.std.Merge(ts1, bobbed, weight=0.25 if ChromaMotion or is_gray else [0.25, 0])
else:
binomial0 = core.std.Merge(
core.std.Merge(ts1, ts2, weight=0.357 if ChromaMotion or is_gray else [0.357, 0]), bobbed, weight=0.125 if ChromaMotion or is_gray else [0.125, 0]
)
# Remove areas of difference between temporal blurred motion search clip and bob that are not due to bob-shimmer - removes general motion blur
if isinstance(srchClip, vs.VideoNode) or Rep0 <= 0:
repair0 = binomial0
else:
repair0 = QTGMC_KeepOnlyBobShimmerFixes(binomial0, bobbed, Rep0, RepChroma and ChromaMotion)
matrix = [1, 2, 1, 2, 4, 2, 1, 2, 1]
# Blur image and soften edges to assist in motion matching of edge blocks. Blocks are matched by SAD (sum of absolute differences between blocks), but even
# a slight change in an edge from frame to frame will give a high SAD due to the higher contrast of edges
if not isinstance(srchClip, vs.VideoNode):
if SrchClipPP == 1:
spatialBlur = repair0.resize.Bilinear(w // 2, h // 2).std.Convolution(matrix=matrix, planes=CMplanes).resize.Bilinear(w, h)
elif SrchClipPP >= 2:
spatialBlur = vsrgtools.gauss_blur(repair0.std.Convolution(matrix=matrix, planes=CMplanes), 1.75)
spatialBlur = core.std.Merge(spatialBlur, repair0, weight=0.1 if ChromaMotion or is_gray else [0.1, 0])
if SrchClipPP <= 0:
srchClip = repair0
elif SrchClipPP < 3:
srchClip = spatialBlur
else:
expr = 'x {i3} + y < x {i3} + x {i3} - y > x {i3} - y ? ?'.format(i3=vstools.scale_value(3, 8, bits))
tweaked = core.std.Expr([repair0, bobbed], expr=expr if ChromaMotion or is_gray else [expr, ''])
expr = 'x {i7} + y < x {i2} + x {i7} - y > x {i2} - x 51 * y 49 * + 100 / ? ?'.format(i7=vstools.scale_value(7, 8, bits), i2=vstools.scale_value(2, 8, bits))
srchClip = core.std.Expr([spatialBlur, tweaked], expr=expr if ChromaMotion or is_gray else [expr, ''])
srchClip = vsdenoise.prefilter_to_full_range(srchClip, Str, CMplanes)
if bits > 8 and FastMA:
srchClip = vstools.depth(srchClip, 8, dither_type=vstools.DitherType.NONE)
super_args = dict(pel=SubPel, hpad=hpad, vpad=vpad)
analyse_args = dict(
blksize=BlockSize,
overlap=Overlap,
search=Search,
searchparam=SearchParam,
pelsearch=PelSearch,
truemotion=TrueMotion,
lambda_=Lambda,
lsad=LSAD,
pnew=PNew,
plevel=PLevel,
global_=GlobalMotion,
dct=DCT,
chroma=ChromaMotion,
)
recalculate_args = dict(
thsad=ThSAD1 // 2,
blksize=max(BlockSize // 2, 4),
search=Search,
searchparam=SearchParam,
chroma=ChromaMotion,
truemotion=TrueMotion,
pnew=PNew,
overlap=max(Overlap // 2, 2),
dct=DCT,
)
# Calculate forward and backward motion vectors from motion search clip
if maxTR > 0:
if not isinstance(srchSuper, vs.VideoNode):
srchSuper = srchClip.mv.Super(sharp=SubPelInterp, chroma=ChromaMotion, **super_args)
if not isinstance(bVec1, vs.VideoNode):
bVec1 = srchSuper.mv.Analyse(isb=True, delta=1, **analyse_args)
if RefineMotion:
bVec1 = core.mv.Recalculate(srchSuper, bVec1, **recalculate_args)
if not isinstance(fVec1, vs.VideoNode):
fVec1 = srchSuper.mv.Analyse(isb=False, delta=1, **analyse_args)
if RefineMotion:
fVec1 = core.mv.Recalculate(srchSuper, fVec1, **recalculate_args)
if maxTR > 1:
if not isinstance(bVec2, vs.VideoNode):
bVec2 = srchSuper.mv.Analyse(isb=True, delta=2, **analyse_args)
if RefineMotion:
bVec2 = core.mv.Recalculate(srchSuper, bVec2, **recalculate_args)
if not isinstance(fVec2, vs.VideoNode):
fVec2 = srchSuper.mv.Analyse(isb=False, delta=2, **analyse_args)
if RefineMotion:
fVec2 = core.mv.Recalculate(srchSuper, fVec2, **recalculate_args)
if maxTR > 2:
if not isinstance(bVec3, vs.VideoNode):
bVec3 = srchSuper.mv.Analyse(isb=True, delta=3, **analyse_args)
if RefineMotion:
bVec3 = core.mv.Recalculate(srchSuper, bVec3, **recalculate_args)
if not isinstance(fVec3, vs.VideoNode):
fVec3 = srchSuper.mv.Analyse(isb=False, delta=3, **analyse_args)
if RefineMotion:
fVec3 = core.mv.Recalculate(srchSuper, fVec3, **recalculate_args)
# Expose search clip, motion search super clip and motion vectors to calling script through globals
if ReplaceGlobals:
QTGMC_SetUserGlobal(GlobalNames, 'srchClip', srchClip)
QTGMC_SetUserGlobal(GlobalNames, 'srchSuper', srchSuper)
QTGMC_SetUserGlobal(GlobalNames, 'bVec1', bVec1)
QTGMC_SetUserGlobal(GlobalNames, 'fVec1', fVec1)
QTGMC_SetUserGlobal(GlobalNames, 'bVec2', bVec2)
QTGMC_SetUserGlobal(GlobalNames, 'fVec2', fVec2)
QTGMC_SetUserGlobal(GlobalNames, 'bVec3', bVec3)
QTGMC_SetUserGlobal(GlobalNames, 'fVec3', fVec3)
# ---------------------------------------
# Noise Processing
# Expand fields to full frame size before extracting noise (allows use of motion vectors which are frame-sized)
if NoiseProcess > 0:
if InputType > 0:
fullClip = clip
else:
fullClip = clip.resize.Bob(tff=TFF, filter_param_a=0, filter_param_b=1)
if NoiseTR > 0:
fullSuper = fullClip.mv.Super(levels=1, chroma=ChromaNoise, **super_args) # TEST chroma OK?
CNplanes = [0, 1, 2] if ChromaNoise and not is_gray else [0]
if NoiseProcess > 0:
# Create a motion compensated temporal window around current frame and use to guide denoisers
if not DenoiseMC or NoiseTR <= 0:
noiseWindow = fullClip
elif NoiseTR == 1:
noiseWindow = core.std.Interleave(
[
core.mv.Compensate(fullClip, fullSuper, fVec1, thscd1=ThSCD1, thscd2=ThSCD2),
fullClip,
core.mv.Compensate(fullClip, fullSuper, bVec1, thscd1=ThSCD1, thscd2=ThSCD2),
]
)
else:
noiseWindow = core.std.Interleave(
[
core.mv.Compensate(fullClip, fullSuper, fVec2, thscd1=ThSCD1, thscd2=ThSCD2),
core.mv.Compensate(fullClip, fullSuper, fVec1, thscd1=ThSCD1, thscd2=ThSCD2),
fullClip,
core.mv.Compensate(fullClip, fullSuper, bVec1, thscd1=ThSCD1, thscd2=ThSCD2),
core.mv.Compensate(fullClip, fullSuper, bVec2, thscd1=ThSCD1, thscd2=ThSCD2),
]
)
if Denoiser == 'bm3d':
dnWindow = vsdenoise.BM3D.denoise(noiseWindow, Sigma, NoiseTR, planes=CNplanes)
elif Denoiser == 'dfttest':
dnWindow = dfttest2.DFTTest(clip=noiseWindow, sigma=Sigma * 4, tbsize=noiseTD, planes=CNplanes) #TODO:GPU
elif Denoiser in ['knlm', 'knlmeanscl']:
dnWindow = vsdenoise.nl_means(noiseWindow, strength=Sigma, tr=NoiseTR, planes=CNplanes)
else:
dnWindow = noiseWindow.fft3dfilter.FFT3DFilter(sigma=Sigma, planes=CNplanes, bt=noiseTD, ncpu=FftThreads)
# Rework denoised clip to match source format - various code paths here: discard the motion compensation window, discard doubled lines (from point resize)
# Also reweave to get interlaced noise if source was interlaced (could keep the full frame of noise, but it will be poor quality from the point resize)
if not DenoiseMC:
if InputType > 0:
denoised = dnWindow
else:
denoised = dnWindow.std.SeparateFields(tff=TFF).std.SelectEvery(cycle=4, offsets=[0, 3]).std.DoubleWeave(TFF)[::2]
elif InputType > 0:
if NoiseTR <= 0:
denoised = dnWindow
else:
denoised = dnWindow.std.SelectEvery(cycle=noiseTD, offsets=NoiseTR)
else:
denoised = dnWindow.std.SeparateFields(tff=TFF).std.SelectEvery(cycle=noiseTD * 4, offsets=[NoiseTR * 2, NoiseTR * 6 + 3]).std.DoubleWeave(TFF)[::2]
if totalRestore > 0:
# Get actual noise from difference. Then 'deinterlace' where we have weaved noise - create the missing lines of noise in various ways
noise = core.std.MakeDiff(clip, denoised, planes=CNplanes)
if InputType > 0:
deintNoise = noise
elif NoiseDeint == 'bob':
deintNoise = noise.resize.Bob(tff=TFF, filter_param_a=0, filter_param_b=0.5)
elif NoiseDeint == 'generate':
deintNoise = QTGMC_Generate2ndFieldNoise(noise, denoised, ChromaNoise, TFF)
else:
deintNoise = noise.std.SeparateFields(tff=TFF).std.DoubleWeave(tff=TFF)
# Motion-compensated stabilization of generated noise
if StabilizeNoise:
noiseSuper = deintNoise.mv.Super(sharp=SubPelInterp, levels=1, chroma=ChromaNoise, **super_args)
mcNoise = core.mv.Compensate(deintNoise, noiseSuper, bVec1, thscd1=ThSCD1, thscd2=ThSCD2)
expr = f'x {neutral} - abs y {neutral} - abs > x y ? 0.6 * x y + 0.2 * +'
finalNoise = core.std.Expr([deintNoise, mcNoise], expr=expr if ChromaNoise or is_gray else [expr, ''])
else:
finalNoise = deintNoise
# If NoiseProcess=1 denoise input clip. If NoiseProcess=2 leave noise in the clip and let the temporal blurs "denoise" it for a stronger effect
innerClip = denoised if NoiseProcess == 1 else clip
# ---------------------------------------
# Interpolation
# Support badly deinterlaced progressive content - drop half the fields and reweave to get 1/2fps interlaced stream appropriate for QTGMC processing
if InputType > 1:
ediInput = innerClip.std.SeparateFields(tff=TFF).std.SelectEvery(cycle=4, offsets=[0, 3]).std.DoubleWeave(TFF)[::2]
else:
ediInput = innerClip
# Create interpolated image as starting point for output
if EdiExt is not None:
edi1 = EdiExt.resize.Point(w, h, src_top=(EdiExt.height - h) // 2, src_height=h)
else:
edi1 = QTGMC_Interpolate(
ediInput, InputType, EdiMode, NNSize, NNeurons, EdiQual, EdiMaxD, bobbed, ChromaEdi.lower(), TFF, nnedi3_args, eedi3_args, opencl, device
)
# InputType=2,3: use motion mask to blend luma between original clip & reweaved clip based on ProgSADMask setting. Use chroma from original clip in any case
if InputType < 2:
edi = edi1
elif ProgSADMask <= 0:
if not is_gray:
edi = core.std.ShufflePlanes([edi1, innerClip], planes=[0, 1, 2], colorfamily=Input.format.color_family)
else:
edi = edi1
else:
inputTypeBlend = core.mv.Mask(srchClip, bVec1, kind=1, ml=ProgSADMask)
edi = core.std.MaskedMerge(innerClip, edi1, inputTypeBlend, planes=0)
# Get the max/min value for each pixel over neighboring motion-compensated frames - used for temporal sharpness limiting
if TR1 > 0 or temporalSL:
ediSuper = edi.mv.Super(sharp=SubPelInterp, levels=1, **super_args)
if temporalSL:
bComp1 = core.mv.Compensate(edi, ediSuper, bVec1, thscd1=ThSCD1, thscd2=ThSCD2)
fComp1 = core.mv.Compensate(edi, ediSuper, fVec1, thscd1=ThSCD1, thscd2=ThSCD2)
tMax = core.std.Expr([core.std.Expr([edi, fComp1], expr='x y max'), bComp1], expr='x y max')
tMin = core.std.Expr([core.std.Expr([edi, fComp1], expr='x y min'), bComp1], expr='x y min')
if SLRad > 1:
bComp3 = core.mv.Compensate(edi, ediSuper, bVec3, thscd1=ThSCD1, thscd2=ThSCD2)
fComp3 = core.mv.Compensate(edi, ediSuper, fVec3, thscd1=ThSCD1, thscd2=ThSCD2)
tMax = core.std.Expr([core.std.Expr([tMax, fComp3], expr='x y max'), bComp3], expr='x y max')
tMin = core.std.Expr([core.std.Expr([tMin, fComp3], expr='x y min'), bComp3], expr='x y min')
# ---------------------------------------
# Create basic output
# Use motion vectors to blur interpolated image (edi) with motion-compensated previous and next frames. As above, this is done to remove shimmer from
# alternate frames so the same binomial kernels are used. However, by using motion-compensated smoothing this time we avoid motion blur. The use of
# MDegrain1 (motion compensated) rather than TemporalSmooth makes the weightings *look* different, but they evaluate to the same values
# Create linear weightings of neighbors first -2 -1 0 1 2
if TR1 > 0:
degrain1 = core.mv.Degrain1(edi, ediSuper, bVec1, fVec1, thsad=ThSAD1, thscd1=ThSCD1, thscd2=ThSCD2) # 0.00 0.33 0.33 0.33 0.00
if TR1 > 1:
degrain2 = core.mv.Degrain1(edi, ediSuper, bVec2, fVec2, thsad=ThSAD1, thscd1=ThSCD1, thscd2=ThSCD2) # 0.33 0.00 0.33 0.00 0.33
# Combine linear weightings to give binomial weightings - TR1=0: (1), TR1=1: (1:2:1), TR1=2: (1:4:6:4:1)
if TR1 <= 0:
binomial1 = edi
elif TR1 == 1:
binomial1 = core.std.Merge(degrain1, edi, weight=0.25)
else:
binomial1 = core.std.Merge(core.std.Merge(degrain1, degrain2, weight=0.2), edi, weight=0.0625)
# Remove areas of difference between smoothed image and interpolated image that are not bob-shimmer fixes: repairs residual motion blur from temporal smooth
if Rep1 <= 0:
repair1 = binomial1
else:
repair1 = QTGMC_KeepOnlyBobShimmerFixes(binomial1, edi, Rep1, RepChroma)
# Apply source match - use difference between output and source to succesively refine output [extracted to function to clarify main code path]
if SourceMatch <= 0:
match = repair1
else:
match = QTGMC_ApplySourceMatch(
repair1,
InputType,
ediInput,
bVec1 if maxTR > 0 else None,
fVec1 if maxTR > 0 else None,
bVec2 if maxTR > 1 else None,
fVec2 if maxTR > 1 else None,
SubPel,
SubPelInterp,
hpad,
vpad,
ThSAD1,
ThSCD1,
ThSCD2,
SourceMatch,
MatchTR1,
MatchEdi,
MatchNNSize,
MatchNNeurons,
MatchEdiQual,