View difference between Paste ID: bY3UyrtJ and G4hHSAeC
SHOW: | | - or go back to the newest paste.
1
#-------------------------------------------------------------------#
2
#                                                                   #
3-
#           QTGMC 3.347, by Vit, 2012, 2016 mod by A.SONY           #
3+
#           QTGMC 3.348, by Vit, 2012, 2016 mod by A.SONY           #
4
#                                                                   #
5
#   A high quality deinterlacer using motion-compensated temporal   #
6
#  smoothing, with a range of features for quality and convenience  #
7
#          Originally based on TempGaussMC_beta2 by Didée           #
8
#                                                                   #
9
#-------------------------------------------------------------------#
10
#
11
# Full documentation is in the 'QTGMC' html file that comes with this script
12
#
13
# --- LATEST CHANGES ---
14
#
15
# v3.348s
16
# - added tr0=-1 to use the EdiExt clip (if there is no EdiExt clip then it will be like tr0=0)
17
#
18
# v3.347s
19
# - fix SourceMatch (bug after new YUY2 method, thanks to ndjamena for report it)
20
#
21
# v3.346s
22
# - EEDI3+NNEDI3 bug fix by ndjamena
23
# - Renamed DftThreads parameter to FftThreads, to set the ncpu argument of FFT3DFilter (from VS)
24
# - FFT3DFilter will work now in YUY2, use it with Denoiser="fft3df" (or use NoisePreset)
25
#
26
# v3.345s
27
# - work with SMDegrain_KNLMeansCL now to process chroma too
28
#
29
# v3.343s
30
# - edit in ChromaEdi
31
# - others
32
#
33
# v3.34s (mod) 2016 12 18 (ravewulf idea in another way)
34
# - Added yadifmod2 (if you need old one use it like this EdiMode="cYadif" or EdiMode="RepcYadif")
35
# - fast and clean up YUY2 (will work in x64 now, no need to SSETools)
36
#
37
# v3.33s (mod) 2016 12 06
38
# - Add TR2=4 and TR2=5
39
# - add TV_range bool and dither_luma_rebuild (from SMDegrain) Str and Amp
40
# - for avsplus now QTGMC_Bob is ready for any 420, not only yv12
41
#
42
# v3.33s (mod) 2016 04 11
43
# - Add KNLMeansCL as another Denoiser to NoiseProcess
44
# - others
45
#
46
# v3.33s (mod) 2016 01 19
47
# - make QTGMC_deflate/QTGMC_inflate work with YUY2 using masktool2 for avs 2.60
48
#
49
# v3.33s (mod) 2015 10 23
50
# - revert to QTGMC_deflate/QTGMC_inflate quoted from Dogway
51
#
52
# v3.33s (mod) 2015 9 10
53
# - fix Multiple QTGMC Calls
54
# - others fix
55
#
56
# v3.33s (mod) 2015 8 6
57
# - some changes in bob to speed up
58
#
59
# v3.33s (mod) 2015 8 4
60
# - fix bug in YUY2 with SourceMatch
61
# - add slice=false to ditherpost to avoid artefacts
62
#
63
# v3.33s (mod)
64
# - fix bob chroma
65
# - work with new masktool2 for avs 2.60 in YUY2
66
#
67
# v3.33d (mod)
68
# - Added 32 bit precision option through the lsbd (for dfttest and knlmeanscl) and lsb (mdegrain) options.
69
# - optimized some mask handling a bit as originally suggested by Vit
70
# - others
71
#
72
# v3.33
73
# - 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
74
# - Bug fix for the fact that Bob always outputs a BFF clip regardless of field order of input (thanks ajp_anton)
75
# - Improved generation of noise (NoiseDeint="Generate") for noise bypass / EZKeepGrain
76
# - Minor change to denoising
77
#
78
# v3.32
79
# - Bugfix with shutter blur and ChromaMotion (thanks Heaud)
80
# - Tweaked vector recalculation for shutter motion blur
81
# - Changed defaults for TR2 when using source-match
82
# - Minor bugfix with SLMode/SLRad on pass-through settings
83
#
84
# --- REQUIREMENTS ---
85
#
86
# Input colorspaces: YV12, YUY2, others as plugins supports
87
#
88
# Core plugins:
89
#	MVTools2 (2.7.5.22 or above from pinterf https://github.com/pinterf/mvtools/releases)
90
#	MaskTools v2 (2.0b1 or above)
91
#	NNEDI3 (0.9.4.6 or above)
92
#	RgTools
93
#
94
# Additional plugins:
95
#	NNEDI2, NNEDI, EEDI3, EEDI2, TDeInt - if selected directly or via a source-match preset
96
#	yadifmod2 - for Preset="Ultra Fast" or if selected directly
97
#	FFT3DFilter - if selected for noise processing
98
#	dfttest (1.9.4 or above) - if selected for noise processing
99
#		For FFT3DFilter & ddftest you also need the FFTW3 library (FFTW.org). On Windows the file needed for both is libfftw3f-3.dll. However, for FFT3DFilter
100
#		the file needs to be called FFTW3.dll, so you will need two copies and rename one. On Windows put the files in your System32 or SysWow64 folder
101
#   KNLMeansCL - if selected for noise processing
102
#	AddGrainC - if NoiseDeint="Generate" selected for noise bypass
103
104
105
# --- GETTING STARTED ---
106
#
107
# Install AviSynth and ensure you have at least the core plugins listed in the requirements section above. Put them in the plugins autoload folder.
108
# To use QTGMC write a script like this:
109
#	YourSource("yourfile")   # DGDecode_mpeg2source, FFVideoSource, AviSource, whatever your source requires
110
#	QTGMC( Preset="Slow" )
111
#	SelectEven()             # Add this line to keep original frame rate, leave it out for smoother doubled frame rate
112
#
113
# Save this script with an ".avs" extension. You can now use it as an AVI source for encoding.
114
#
115
# The "Preset" used selects sensible settings for a given encoding speed. Choose a preset from:
116
#	"Placebo", "Very Slow", "Slower", "Slow", "Medium", "Fast", "Faster", "Very Fast", "Super Fast", "Ultra Fast" & "Draft"
117
# The default preset is "Slower"
118
# 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)
119
# For much faster speeds read the full documentation, the section on 'Multi-threading'
120
#
121
# There are many settings for tweaking the script, full details in the main documentation. You can display settings currently being used with "ShowSettings":
122
#	QTGMC( Preset="Slow", ShowSettings=true )
123
124
125
function QTGMC( clip Input, string "Preset", int "TR0", int "TR1", int "TR2", int "Rep0", int "Rep1", int "Rep2", string "EdiMode", bool "RepChroma", \
126
                    int "NNSize", int "NNeurons", int "EdiQual", int "EdiMaxD", string "ChromaEdi", int "EdiThreads", clip "EdiExt", float "Sharpness", \
127
                    int "SMode", int "SLMode", int "SLRad", int "SOvs", float "SVThin", int "Sbb", int "SrchClipPP", int "SubPel", int "SubPelInterp", \
128
                    int "BlockSize", int "Overlap", int "Search", int "SearchParam", int "PelSearch", bool "ChromaMotion", bool "TrueMotion", int "Lambda", \
129
                    int "LSAD", int "PNew", int "PLevel", bool "GlobalMotion", int "DCT", int "ThSAD1", int "ThSAD2", int "ThSCD1", int "ThSCD2", \
130
                    int "SourceMatch", string "MatchPreset", string "MatchEdi", string "MatchPreset2", string "MatchEdi2", int "MatchTR2", \
131
                    float "MatchEnhance", int "Lossless", int "NoiseProcess", float "EZDenoise", float "EZKeepGrain", string "NoisePreset", string "Denoiser", \
132
                    int "FftThreads", bool "DenoiseMC", int "NoiseTR", float "Sigma", bool "ChromaNoise", val "ShowNoise", float "GrainRestore", \
133
                    float "NoiseRestore", string "NoiseDeint", bool "StabilizeNoise", int "InputType", float "ProgSADMask", int "FPSDivisor", \
134
                    int "ShutterBlur", float "ShutterAngleSrc", float "ShutterAngleOut", int "SBlurLimit", bool "Border", bool "Precise", string "Tuning", \
135
                    bool "ShowSettings", string "GlobalNames", string "PrevGlobals", int "ForceTR", \
136
                    val "BT", val "DetailRestore", val "MotionBlur", val "MBlurLimit", val "NoiseBypass", float "Str", float "Amp", bool "TV_range", bool "lsbd", bool "lsb" )
137
{
138
	# EdiMode="RepcYadif"/"cYadif" require the Yadif plugin, which doesn't autoload. Typically the calling script would load it.
139
140
	# Temporary Warnings
141
	Assert( !defined(BT),            "QTGMC: Setting BT has been replaced by setting NoiseTR" )
142
	Assert( !defined(DetailRestore), "QTGMC: Setting DetailRestore has been renamed to GrainRestore" )
143
	Assert( !defined(MotionBlur),    "QTGMC: Setting MotionBlur has been renamed to ShutterBlur" )
144
	Assert( !defined(MBlurLimit),    "QTGMC: Setting MBlurLimit has been renamed to SBlurLimit" )
145
	Assert( !defined(NoiseBypass),   "QTGMC: Setting NoiseBypass has been renamed to NoiseProcess" )
146
147
	#---------------------------------------
148
	# Presets
149
    lsbd         = default( lsbd,    false)
150
    lsb          = default( lsb,     false)
151
    Str          = default( Str,      1.0 )
152
    Amp          = default( Amp,   0.0625 )
153
    TV_range     = default( TV_range, true)
154
155
	# Select presets / tuning
156
	Preset = default( Preset, "Slower" )
157
	pNum = (Preset == "Placebo"   ) ? 0 : \
158
	       (Preset == "Very Slow" ) ? 1 : \
159
	       (Preset == "Slower"    ) ? 2 : \
160
	       (Preset == "Slow"      ) ? 3 : \
161
	       (Preset == "Medium"    ) ? 4 : \
162
	       (Preset == "Fast"      ) ? 5 : \
163
	       (Preset == "Faster"    ) ? 6 : \
164
	       (Preset == "Very Fast" ) ? 7 : \
165
	       (Preset == "Super Fast") ? 8 : \
166
	       (Preset == "Ultra Fast") ? 9 : \
167
	       (Preset == "Draft"     ) ? 10 : 11
168
	Assert( pNum  < 11, "'Preset' choice is invalid" )
169
170
	mpNum1 = (!defined(MatchPreset))       ? ((pNum + 3 <= 9) ? (pNum + 3) : 9) : \
171
	         (MatchPreset == "Placebo"   ) ? 0 : \
172
	         (MatchPreset == "Very Slow" ) ? 1 : \
173
	         (MatchPreset == "Slower"    ) ? 2 : \
174
	         (MatchPreset == "Slow"      ) ? 3 : \
175
	         (MatchPreset == "Medium"    ) ? 4 : \
176
	         (MatchPreset == "Fast"      ) ? 5 : \
177
	         (MatchPreset == "Faster"    ) ? 6 : \
178
	         (MatchPreset == "Very Fast" ) ? 7 : \
179
	         (MatchPreset == "Super Fast") ? 8 : \
180
	         (MatchPreset == "Ultra Fast") ? 9 : \
181
	         (MatchPreset == "Draft"     ) ? 10 : 11
182
	Assert( mpNum1 < 10, "'MatchPreset' choice is invalid/unsupported" )
183
	MatchPreset = Select( mpNum1, "Placebo", "Very Slow", "Slower", "Slow", "Medium", "Fast", "Faster", "Very Fast", "Super Fast", "Ultra Fast", "Draft" )
184
185
	mpNum2 = (!defined(MatchPreset2))       ? ((mpNum1 + 2 <= 9) ? (mpNum1 + 2) : 9) : \
186
	         (MatchPreset2 == "Placebo"   ) ? 0 : \
187
	         (MatchPreset2 == "Very Slow" ) ? 1 : \
188
	         (MatchPreset2 == "Slower"    ) ? 2 : \
189
	         (MatchPreset2 == "Slow"      ) ? 3 : \
190
	         (MatchPreset2 == "Medium"    ) ? 4 : \
191
	         (MatchPreset2 == "Fast"      ) ? 5 : \
192
	         (MatchPreset2 == "Faster"    ) ? 6 : \
193
	         (MatchPreset2 == "Very Fast" ) ? 7 : \
194
	         (MatchPreset2 == "Super Fast") ? 8 : \
195
	         (MatchPreset2 == "Ultra Fast") ? 9 : \
196
	         (MatchPreset2 == "Draft"     ) ? 10 : 11
197
	Assert( mpNum2 < 10, "'MatchPreset2' choice is invalid/unsupported" )
198
	MatchPreset2 = Select( mpNum2, "Placebo", "Very Slow", "Slower", "Slow", "Medium", "Fast", "Faster", "Very Fast", "Super Fast", "Ultra Fast", "Draft" )
199
200
	NoisePreset = default( NoisePreset, "Fast" )
201
	npNum = (NoisePreset == "Slower" ) ? 0 : \
202
	        (NoisePreset == "Slow"   ) ? 1 : \
203
	        (NoisePreset == "Medium" ) ? 2 : \
204
	        (NoisePreset == "Fast"   ) ? 3 : \
205
	        (NoisePreset == "Faster" ) ? 4 : 5
206
	Assert( npNum < 5, "'NoisePreset' choice is invalid" )
207
208
	Tuning = default( Tuning, "None" )
209
	tNum = (Tuning == "None"  ) ? 0 : \
210
	       (Tuning == "DV-SD" ) ? 1 : \
211
	       (Tuning == "DV-HD" ) ? 2 : 3
212
	Assert( tNum < 3, "'Tuning' choice is invalid" )
213
214
	# Tunings only affect blocksize in this version
215
	bs = Select( tNum,  16, 16, 32 )
216
	bs2 = (bs >= 16) ? 32 : bs * 2
217
218
	#                                                               Very                                                        Very      Super      Ultra
219
	# Preset groups:                                     Placebo    Slow      Slower    Slow      Medium    Fast      Faster    Fast      Fast       Fast       Draft
220
	TR0          = default( TR0,          Select( pNum,  2,         2,        2,        2,        2,        2,        1,        1,        1,         1,         0      ) )
221
	TR1          = default( TR1,          Select( pNum,  2,         2,        2,        1,        1,        1,        1,        1,        1,         1,         1      ) )
222
	TR2X         = default( TR2,          Select( pNum,  3,         2,        1,        1,        1,        0,        0,        0,        0,         0,         0      ) )
223
	Rep0         = default( Rep0,         Select( pNum,  4,         4,        4,        4,        3,        3,        0,        0,        0,         0,         0      ) )
224
	Rep1         = default( Rep1,         Select( pNum,  0,         0,        0,        0,        0,        0,        0,        0,        0,         0,         0      ) )
225
	Rep2         = default( Rep2,         Select( pNum,  4,         4,        4,        4,        4,        4,        4,        4,        3,         3,         0      ) )
226
	EdiMode      = default( EdiMode,      Select( pNum, "NNEDI3",  "NNEDI3", "NNEDI3", "NNEDI3", "NNEDI3", "NNEDI3", "NNEDI3", "NNEDI3", "NNEDI3",  "RepYadif","Bob"   ) )
227
	NNSize       = default( NNSize,       Select( pNum,  1,         1,        1,        1,        5,        5,        4,        4,        4,         4,         4      ) )
228
	NNeurons     = default( NNeurons,     Select( pNum,  2,         2,        1,        1,        1,        0,        0,        0,        0,         0,         0      ) )
229
	EdiQual      = default( EdiQual,      Select( pNum,  1,         1,        1,        1,        1,        1,        1,        1,        1,         1,         1      ) )
230
	EdiMaxD      = default( EdiMaxD,      Select( pNum,  12,        10,       8,        7,        7,        6,        6,        5,        4,         4,         4      ) )
231
	SMode        = default( SMode,        Select( pNum,  2,         2,        2,        2,        2,        2,        2,        2,        2,         2,         0      ) )
232
	SLModeX      = default( SLMode,       Select( pNum,  2,         2,        2,        2,        2,        2,        2,        2,        0,         0,         0      ) )
233
	SLRad        = default( SLRad,        Select( pNum,  3,         1,        1,        1,        1,        1,        1,        1,        1,         1,         1      ) )
234
	Sbb          = default( Sbb,          Select( pNum,  3,         1,        1,        0,        0,        0,        0,        0,        0,         0,         0      ) )
235
	SrchClipPP   = default( SrchClipPP,   Select( pNum,  3,         3,        3,        3,        3,        2,        2,        2,        1,         1,         0      ) )
236
	SubPel       = default( SubPel,       Select( pNum,  2,         2,        2,        2,        1,        1,        1,        1,        1,         1,         1      ) )
237
	Blocksize    = default( Blocksize,    Select( pNum,  bs,        bs,       bs,       bs,       bs,       bs,       bs2,      bs2,      bs2,       bs2,       bs2    ) )
238
	bs = Blocksize
239
	Overlap      = default( Overlap,      Select( pNum,  bs/2,      bs/2,     bs/2,     bs/2,     bs/2,     bs/2,     bs/2,     bs/4,     bs/4,      bs/4,      bs/4   ) )
240
	Search       = default( Search,       Select( pNum,  5,         4,        4,        4,        4,        4,        4,        4,        0,         0,         0      ) )
241
	SearchParam  = default( SearchParam,  Select( pNum,  2,         2,        2,        2,        2,        2,        2,        1,        1,         1,         1      ) )
242
	PelSearch    = default( PelSearch,    Select( pNum,  2,         2,        2,        2,        1,        1,        1,        1,        1,         1,         1      ) )
243
	ChromaMotion = default( ChromaMotion, Select( pNum,  true,      true,     true,     false,    false,    false,    false,    false,    false,     false,     false  ) )
244
	Precise      = default( Precise,      Select( pNum,  true,      true,     false,    false,    false,    false,    false,    false,    false,     false,     false  ) )
245
	ProgSADMask  = default( ProgSADMask,  Select( pNum,  10.0,      10.0,     10.0,     10.0,     10.0,     0.0,      0.0,      0.0,      0.0,       0.0,       0.0    ) )
246
247
	# Noise presets                                           Slower     Slow       Medium     Fast       Faster
248
	Denoiser       = default( Denoiser,       Select( npNum, "dfttest", "dfttest", "dfttest", "fft3df",  "fft3df" ) )
249
	DenoiseMC      = default( DenoiseMC,      Select( npNum,  true,      true,      false,     false,     false   ) )
250
	NoiseTR        = default( NoiseTR,        Select( npNum,  2,         1,         1,         1,         0       ) )
251
	NoiseDeint     = default( NoiseDeint,     Select( npNum, "Generate","Bob",      "",        "",        ""      ) )
252
	StabilizeNoise = default( StabilizeNoise, Select( npNum,  true,      true,      true,      false,     false   ) )
253
254
	# 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
255
	SourceMatch   = default( SourceMatch, 0 )
256
	MatchNNSize   = NNSize
257
	MatchNNeurons = NNeurons
258
	MatchEdiMaxD  = EdiMaxD
259
	MatchEdiQual  = EdiQual
260
261
	# However, can use a faster initial interpolation when using source-match allowing the basic source-match step to "correct" it with higher quality settings
262
	Assert( SourceMatch == 0 || mpNum1 >= pNum, "'MatchPreset' cannot use a slower setting than 'Preset'" )
263
	#                                                                    Very                                                        Very      Super     Ultra
264
	# Basic source-match presets                                Placebo  Slow      Slower    Slow      Medium    Fast      Faster    Fast      Fast      Fast
265
	NNSize   = (SourceMatch == 0) ? NNSize   : Select( mpNum1,  1,       1,        1,        1,        5,        5,        4,        4,        4,        4     )
266
	NNeurons = (SourceMatch == 0) ? NNeurons : Select( mpNum1,  2,       2,        1,        1,        1,        0,        0,        0,        0,        0     )
267
	EdiMaxD  = (SourceMatch == 0) ? EdiMaxD  : Select( mpNum1,  12,      10,       8,        7,        7,        6,        6,        5,        4,        4     )
268
	EdiQual  = (SourceMatch == 0) ? EdiQual  : Select( mpNum1,  1,       1,        1,        1,        1,        1,        1,        1,        1,        1     )
269
	TempEdi  = EdiMode # Main interpolation is actually done by basic-source match step when enabled, so a little swap and wriggle is needed
270
	EdiMode  = (SourceMatch == 0) ? EdiMode  : default( MatchEdi, ((mpNum1 < 9) ?  EdiMode : "Yadif") ) # Force Yadif for "Ultra Fast" basic source match
271
	MatchEdi = TempEdi
272
273
	#                                                          Very                                                        Very      Super     Ultra
274
	# Refined source-match presets                   Placebo   Slow      Slower    Slow      Medium    Fast      Faster    Fast      Fast      Fast
275
	MatchEdi2 = default( MatchEdi2, Select( mpNum2, "NNEDI3", "NNEDI3", "NNEDI3", "NNEDI3", "NNEDI3", "NNEDI3", "NNEDI3", "NNEDI3", "TDeint",  ""    ) )
276
	MatchNNSize2                  = Select( mpNum2,  1,        1,        1,        1,        5,        5,        4,        4,        4,        4     )
277
	MatchNNeurons2                = Select( mpNum2,  2,        2,        1,        1,        1,        0,        0,        0,        0,        0     )
278
	MatchEdiMaxD2                 = Select( mpNum2,  12,       10,       8,        7,        7,        6,        6,        5,        4,        4     )
279
	MatchEdiQual2                 = Select( mpNum2,  1,        1,        1,        1,        1,        1,        1,        1,        1,        1     )
280
281
282
	#---------------------------------------
283
	# Settings
284
285
	# Core and Interpolation defaults
286
	TR2        = (SourceMatch > 0) ? default(TR2, ((TR2X == 0) ? 1 : TR2X)) : TR2X  # ***TR2 defaults always at least 1 when using source-match***
287
	RepChroma  = default( RepChroma,  true )
288
	EdiThreads = default( EdiThreads, 0    )
289
	ChromaEdi  = default( ChromaEdi,  ""   )
290
	NNeurons   = (EdiMode == "NNEDI2" && NNeurons > 2) ? 2 : NNeurons # Smaller range for NNeurons in NNEDI2 (which calls it nsize)
291
	EdiQual    = (EdiMode == "EEDI3+NNEDI3" || EdiMode == "NNEDI3") && EdiQual > 2 ? 2 : EdiQual  # Smaller range for EdiQual in NNEDI3
292
293
	# Source-match / lossless defaults
294
	MatchTR1     = TR1
295
	MatchTR2     = default( MatchTR2,     1   )
296
	MatchEnhance = default( MatchEnhance, 0.5 )
297
	Lossless     = default( Lossless,     0   )
298
	Assert( Lossless <= 2, "Lossless setting only supports mode 1 ('true lossless') and mode 2 ('fake lossless') - see documentation in script and consider source-match settings" )
299
300
	# Sharpness defaults. Sharpness default is always 1.0 (0.2 with source-match), but adjusted to give roughly same sharpness for all settings
301
	SMode      = (defined(Sharpness) && Sharpness == 0.0) ? 0 : SMode
302
	SLMode     = (SourceMatch > 0) ? default(SLMode, 0) : SLModeX  # ***Sharpness limiting disabled by default for source-match***
303
	SLMode     = (SLRad <= 0)      ? 0 : SLMode
304
	spatialSL  = (SLMode == 1 || SLMode == 3)
305
	temporalSL = (SLMode == 2 || SLMode == 4)
306
	Sharpness  = default( Sharpness, (SMode == 0) ? 0.0 : ((SourceMatch > 0) ? 0.2 : 1.0) )      # Default sharpness is 1.0, or 0.2 if using source-match
307
	sharpMul   = (temporalSL) ? 2 : (spatialSL) ? 1.5 : 1                                        # Adjust sharpness based on other settings
308
	sharpAdj   = Sharpness * (sharpMul * (0.2 + TR1*0.15 + TR2*0.25) + ((SMode == 1) ? 0.1 : 0)) # [This needs a bit more refinement]
309
	Sbb        = (SMode == 0) ? 0 : Sbb
310
	SOvs       = default( SOvs,   0   )
311
	SVThin     = default( SVThin, 0.0 )
312
313
	# Noise processing settings
314
	Assert( !defined(EZDenoise) || EZDenoise <= 0.0 || !defined(EZKeepGrain) || EZKeepGrain <= 0.0, "QTGMC: EZDenoise and EZKeepGrain cannot be used together" )
315
	NoiseProcess = defined(NoiseProcess) ? NoiseProcess : \
316
	               (defined(EZDenoise)   && EZDenoise   > 0.0)    ? 1 : \
317
	               (defined(EZKeepGrain) && EZKeepGrain > 0.0)    ? 2 : \
318
				   (Preset == "Placebo" || Preset == "Very Slow") ? 2 : 0
319
	GrainRestore = defined(GrainRestore) ? GrainRestore : \
320
	               (defined(EZDenoise)   && EZDenoise   > 0.0) ? 0.0 : \
321
	               (defined(EZKeepGrain) && EZKeepGrain > 0.0) ? 0.3 * sqrt(EZKeepGrain) : \
322
				                                                Select( NoiseProcess, 0.0, 0.7, 0.3 )
323
	NoiseRestore = defined(NoiseRestore) ? NoiseRestore : \
324
	               (defined(EZDenoise)   && EZDenoise   > 0.0) ? 0.0 : \
325
	               (defined(EZKeepGrain) && EZKeepGrain > 0.0) ? 0.1 * sqrt(EZKeepGrain) : \
326
				                                                Select( NoiseProcess, 0.0, 0.3, 0.1 )
327
	Sigma        = defined(Sigma)       ? Sigma : \
328
	               (defined(EZDenoise)   && EZDenoise   > 0.0) ? EZDenoise : \
329
	               (defined(EZKeepGrain) && EZKeepGrain > 0.0) ? 4.0 * EZKeepGrain : 2.0
330
	FftThreads   = default( FftThreads, EdiThreads )
331
	ChromaNoise  = default( ChromaNoise, false )
332
	ShowNoise    = default( ShowNoise, 0.0 )
333
	ShowNoise    = IsBool( ShowNoise ) ? (ShowNoise ? 10.0 : 0.0) : ShowNoise
334
	NoiseProcess = (ShowNoise > 0.0)   ? 2   : NoiseProcess
335
	NoiseRestore = (ShowNoise > 0.0)   ? 1.0 : NoiseRestore
336
	NoiseTR      = (NoiseProcess == 0) ? 0   : NoiseTR
337
	GrainRestore = (NoiseProcess == 0) ? 0.0 : GrainRestore
338
	NoiseRestore = (NoiseProcess == 0) ? 0.0 : NoiseRestore
339
	totalRestore = GrainRestore + NoiseRestore
340
	StabilizeNoise = (totalRestore <= 0) ? false : StabilizeNoise
341
	noiseTD  = Select( NoiseTR, 1, 3, 5 )
342
	noiseCentre = (Denoiser == "dfttest") ? "128" : "128.5"
343
344
	# MVTools settings
345
	SubPelInterp = default( SubPelInterp, 2     )
346
	TrueMotion   = default( TrueMotion,   false )
347
	GlobalMotion = default( GlobalMotion, true  )
348
	Lambda       = default( Lambda, ((TrueMotion) ? 1000 : 100 ) * (BlockSize*BlockSize)/(8*8) )
349
	LSAD         = default( LSAD,    (TrueMotion) ? 1200 : 400 )
350
	PNew         = default( PNew,    (TrueMotion) ? 50   : 25  )
351
	PLevel       = default( PLevel,  (TrueMotion) ? 1    : 0   )
352
	DCT          = default( DCT,     0          )
353
	ThSAD1       = default( ThSAD1,  10 * 8*8   )
354
	ThSAD2       = default( ThSAD2,   4 * 8*8   )
355
	ThSCD1       = default( ThSCD1,  180        )
356
	ThSCD2       = default( ThSCD2,  98         )
357
358
	# Motion blur settings
359
	FPSDivisor  = default( FPSDivisor, 1 )
360
	ShutterBlur = default( ShutterBlur, 0 )
361
	ShutterAngleSrc = default( ShutterAngleSrc, 180 )
362
	ShutterAngleOut = default( ShutterAngleOut, 180 )
363
	SBlurLimit  = default( SBlurLimit, 4 )
364
	ShutterBlur = (ShutterAngleOut * FPSDivisor == ShutterAngleSrc) ? 0 : ShutterBlur  # If motion blur output is same as input
365
366
	# Miscellaneous
367
	InputType      = default( InputType,     0        )
368
	Border         = default( Border,        false    )
369
	ShowSettings   = default( ShowSettings,  false    )
370
	GlobalNames    = default( GlobalNames,  "QTGMC"   )
371
	PrevGlobals    = default( PrevGlobals,  "Replace" )
372
	ForceTR        = default( ForceTR,       0        )
373
	ReplaceGlobals = (PrevGlobals == "Replace" || PrevGlobals == "Reuse") # If reusing existing globals put them back afterwards - simplifies logic later
374
	ReuseGlobals   = (PrevGlobals == "Reuse")
375
	ProgSADMask    = (InputType != 2 && InputType != 3) ? 0.0 : ProgSADMask
376
	rgBlur         = (Precise) ? 11 : 12
377
378
	# Get maximum temporal radius needed
379
	maxTR = (temporalSL)       ? SLRad : 0
380
	maxTR = (MatchTR2 > maxTR) ? MatchTR2 : maxTR
381
	maxTR = (TR1 > maxTR)      ? TR1 : maxTR
382
   	maxTR = (TR2 > maxTR)      ? TR2 : maxTR
383
   	maxTR = (NoiseTR > maxTR)  ? NoiseTR : maxTR
384
	maxTR = (ProgSADMask > 0.0 || StabilizeNoise || ShutterBlur > 0) ? (maxTR > 1 ? maxTR : 1) : maxTR
385
	maxTR = (ForceTR > MaxTR)  ? ForceTR : maxTR
386
387
388
	#---------------------------------------
389
	# Pre-Processing
390
391
	w = Input.Width()
392
	h = Input.Height()
393
	yuy2 = Input.IsYUY2()
394
	epsilon = 0.0001
395
396
	# Reverse "field" dominance for progressive repair mode 3 (only difference from mode 2)
397
	compl = (InputType == 3) ? Input.ComplementParity() : Input
398
399
	# Pad vertically during processing (to prevent artefacts at top & bottom edges)
400
	clip = (Border) ? compl.PointResize( w,h+8, 0,-4,0,h+8+epsilon ) : compl
401
	h = (Border) ? h+8 : h
402
403
	# Calculate padding needed for MVTools super clips to avoid crashes [fixed in latest MVTools, but keeping this code for a while]
404
	hpad = w - (Int((w - Overlap) / (Blocksize - Overlap)) * (Blocksize - Overlap) + Overlap)
405
	vpad = h - (Int((h - Overlap) / (Blocksize - Overlap)) * (Blocksize - Overlap) + Overlap)
406
	hpad = (hpad > 8) ? hpad : 8 # But match default padding if possible
407
	vpad = (vpad > 8) ? vpad : 8
408
409
410
	#---------------------------------------
411
	# Motion Analysis
412
413
	# >>> Planar YUY2 for motion analysis, interleaved whilst blurring search clip
414
	planarClip = yuy2 ? clip.converttoyv16() : clip
415
416
	# Bob the input as a starting point for motion search clip
417
	bobbed = (InputType == 0) ? planarClip.QTGMC_Bob( 0,0.5 ) : \
418
	         (InputType == 1) ? planarClip : \
419
	                            planarClip.Blur( 0,1 )
420
421
	# If required, get any existing global clips with a matching "GlobalNames" setting. Unmatched values get NOP (= 0)
422
	srchClip  = QTGMC_GetUserGlobal( GlobalNames, "srchClip",  ReuseGlobals )
423
	srchSuper = QTGMC_GetUserGlobal( GlobalNames, "srchSuper", ReuseGlobals )
424
	bVec1     = QTGMC_GetUserGlobal( GlobalNames, "bVec1",     ReuseGlobals )
425
	fVec1     = QTGMC_GetUserGlobal( GlobalNames, "fVec1",     ReuseGlobals )
426
	bVec2     = QTGMC_GetUserGlobal( GlobalNames, "bVec2",     ReuseGlobals )
427
	fVec2     = QTGMC_GetUserGlobal( GlobalNames, "fVec2",     ReuseGlobals )
428
	bVec3     = QTGMC_GetUserGlobal( GlobalNames, "bVec3",     ReuseGlobals )
429
	fVec3     = QTGMC_GetUserGlobal( GlobalNames, "fVec3",     ReuseGlobals )
430
	bVec4     = QTGMC_GetUserGlobal( GlobalNames, "bVec4",     ReuseGlobals )
431
	fVec4     = QTGMC_GetUserGlobal( GlobalNames, "fVec4",     ReuseGlobals )
432
	bVec5     = QTGMC_GetUserGlobal( GlobalNames, "bVec5",     ReuseGlobals )
433
	fVec5     = QTGMC_GetUserGlobal( GlobalNames, "fVec5",     ReuseGlobals )
434
435
	CMmt = ChromaMotion ? 3   :  1
436
	CMts = ChromaMotion ? 255 :  0
437
	CMrg = ChromaMotion ? 12  : -1
438
439
	# The bobbed clip will shimmer due to being derived from alternating fields. Temporally smooth over the neighboring frames using a binomial kernel. Binomial
440
	# 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.
441
	# These kernels are approximately Gaussian kernels, which work well as a prefilter before motion analysis (hence the original name for this script)
442
	# Create linear weightings of neighbors first                                                 -2    -1     0    1     2
443
	ts1 = (!IsClip(srchClip) && TR0 > 0) ? bobbed.TemporalSoften( 1, 255,CMts, 28, 2 ) : NOP()  # 0.00  0.33  0.33  0.33  0.00
444
	ts2 = (!IsClip(srchClip) && TR0 > 1) ? bobbed.TemporalSoften( 2, 255,CMts, 28, 2 ) : NOP()  # 0.20  0.20  0.20  0.20  0.20
445
446
	# Combine linear weightings to give binomial weightings - TR0=0: (1), TR0=1: (1:2:1), TR0=2: (1:4:6:4:1)
447
	binomial0 = IsClip(srchClip) ? NOP() : \
448
	TR0 == -1 && defined(EdiExt) ? isyuy2(EdiExt) ? EdiExt.converttoyv16() : EdiExt : \
449
	            (TR0 == 0)       ? bobbed : \
450
	            (TR0 == 1)       ? (ChromaMotion ? ts1.Merge( bobbed, 0.25 ) : ts1.MergeLuma( bobbed, 0.25 )) : \
451
	                               (ChromaMotion ? ts1.Merge( ts2, 0.357 ).Merge( bobbed, 0.125 ) : ts1.MergeLuma( ts2, 0.357 ).MergeLuma( bobbed, 0.125 ))
452
453
	# Remove areas of difference between temporal blurred motion search clip and bob that are not due to bob-shimmer - removes general motion blur
454
	repair0 = (IsClip(srchClip) || Rep0 == 0) ? binomial0 : binomial0.QTGMC_KeepOnlyBobShimmerFixes( bobbed, Rep0, (RepChroma && ChromaMotion) )
455
456
	# 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
457
	# a slight change in an edge from frame to frame will give a high SAD due to the higher contrast of edges
458
	spatialBlur = (IsClip(srchClip) || SrchClipPP == 0) ? NOP() : \
459
	              (SrchClipPP == 1) ? repair0.BilinearResize( w/2, h/2 ).RemoveGrain( 12,CMrg).BilinearResize( w, h ) : \
460
	                                  repair0.RemoveGrain( 12,CMrg).GaussResize( w,h, 0,0, w+epsilon,h+epsilon, p=2 )
461
462
	spatialBlur = (IsClip(spatialBlur) && SrchClipPP > 1) ? (ChromaMotion ? spatialBlur.Merge( repair0, 0.1 ) : spatialBlur.MergeLuma( repair0, 0.1 )) : spatialBlur
463
	tweaked     = (!IsClip(srchClip) && SrchClipPP > 1) ? mt_lutxy( repair0, bobbed, "x 3 + y < x 3 + x 3 - y > x 3 - y ? ?", U=CMmt,V=CMmt ) : NOP()
464
	srchcheck   = IsClip(srchClip)
465
	srchClip    = srchcheck         ? srchClip : \
466
	              (SrchClipPP == 0) ? repair0 : \
467
	              (SrchClipPP < 3)  ? spatialBlur : \
468
	                                  spatialBlur.mt_lutxy( tweaked, "x 7 + y < x 2 + x 7 - y > x 2 - x 51 * y 49 * + 100 / ? ?", U=CMmt,V=CMmt )
469
	srchClip    = tv_range && !srchcheck ? srchClip.Dither_Luma_Rebuild(S0=Str,c=Amp,slice=false,lsb=lsb,uv=CMmt) : srchClip
470
	# Calculate forward and backward motion vectors from motion search clip
471
	srchSuper = IsClip(srchSuper) ? srchSuper : \
472
	            (maxTR > 0)       ? srchClip.MSuper( pel=SubPel, sharp=SubPelInterp, hpad=hpad, vpad=vpad, chroma=ChromaMotion ) : NOP()
473
	bVec5 = IsClip(bVec5) ? bVec5 : \
474
	        (maxTR > 4)   ? srchSuper.MAnalyse( isb=true,  delta=5, blksize=BlockSize, overlap=Overlap, search=Search, searchparam=SearchParam, \
475
	                                            pelsearch=PelSearch, truemotion=TrueMotion, lambda=Lambda, lsad=LSAD, pnew=PNew, plevel=PLevel, \
476
	                                            global=GlobalMotion, DCT=DCT, chroma=ChromaMotion ) : NOP()
477
	bVec4 = IsClip(bVec4) ? bVec4 : \
478
	        (maxTR > 3)   ? srchSuper.MAnalyse( isb=true,  delta=4, blksize=BlockSize, overlap=Overlap, search=Search, searchparam=SearchParam, \
479
	                                            pelsearch=PelSearch, truemotion=TrueMotion, lambda=Lambda, lsad=LSAD, pnew=PNew, plevel=PLevel, \
480
	                                            global=GlobalMotion, DCT=DCT, chroma=ChromaMotion ) : NOP()
481
	bVec3 = IsClip(bVec3) ? bVec3 : \
482
	        (maxTR > 2)   ? srchSuper.MAnalyse( isb=true,  delta=3, blksize=BlockSize, overlap=Overlap, search=Search, searchparam=SearchParam, \
483
	                                            pelsearch=PelSearch, truemotion=TrueMotion, lambda=Lambda, lsad=LSAD, pnew=PNew, plevel=PLevel, \
484
	                                            global=GlobalMotion, DCT=DCT, chroma=ChromaMotion ) : NOP()
485
	bVec2 = IsClip(bVec2) ? bVec2 : \
486
	        (maxTR > 1)   ? srchSuper.MAnalyse( isb=true,  delta=2, blksize=BlockSize, overlap=Overlap, search=Search, searchparam=SearchParam, \
487
	                                            pelsearch=PelSearch, truemotion=TrueMotion, lambda=Lambda, lsad=LSAD, pnew=PNew, plevel=PLevel, \
488
	                                            global=GlobalMotion, DCT=DCT, chroma=ChromaMotion ) : NOP()
489
	bVec1 = IsClip(bVec1) ? bVec1 : \
490
	        (maxTR > 0)   ? srchSuper.MAnalyse( isb=true,  delta=1, blksize=BlockSize, overlap=Overlap, search=Search, searchparam=SearchParam, \
491
	                                            pelsearch=PelSearch, truemotion=TrueMotion, lambda=Lambda, lsad=LSAD, pnew=PNew, plevel=PLevel, \
492
	                                            global=GlobalMotion, DCT=DCT, chroma=ChromaMotion ) : NOP()
493
	fVec1 = IsClip(fVec1) ? fVec1 : \
494
	        (maxTR > 0)   ? srchSuper.MAnalyse( isb=false, delta=1, blksize=BlockSize, overlap=Overlap, search=Search, searchparam=SearchParam, \
495
	                                            pelsearch=PelSearch, truemotion=TrueMotion, lambda=Lambda, lsad=LSAD, pnew=PNew, plevel=PLevel, \
496
	                                            global=GlobalMotion, DCT=DCT, chroma=ChromaMotion ) : NOP()
497
	fVec2 = IsClip(fVec2) ? fVec2 : \
498
	        (maxTR > 1)   ? srchSuper.MAnalyse( isb=false, delta=2, blksize=BlockSize, overlap=Overlap, search=Search, searchparam=SearchParam, \
499
	                                            pelsearch=PelSearch, truemotion=TrueMotion, lambda=Lambda, lsad=LSAD, pnew=PNew, plevel=PLevel, \
500
	                                            global=GlobalMotion, DCT=DCT, chroma=ChromaMotion ) : NOP()
501
	fVec3 = IsClip(fVec3) ? fVec3 : \
502
	        (maxTR > 2)   ? srchSuper.MAnalyse( isb=false, delta=3, blksize=BlockSize, overlap=Overlap, search=Search, searchparam=SearchParam, \
503
	                                            pelsearch=PelSearch, truemotion=TrueMotion, lambda=Lambda, lsad=LSAD, pnew=PNew, plevel=PLevel, \
504
	                                            global=GlobalMotion, DCT=DCT, chroma=ChromaMotion ) : NOP()
505
	fVec4 = IsClip(fVec4) ? fVec4 : \
506
	        (maxTR > 3)   ? srchSuper.MAnalyse( isb=false, delta=4, blksize=BlockSize, overlap=Overlap, search=Search, searchparam=SearchParam, \
507
	                                            pelsearch=PelSearch, truemotion=TrueMotion, lambda=Lambda, lsad=LSAD, pnew=PNew, plevel=PLevel, \
508
	                                            global=GlobalMotion, DCT=DCT, chroma=ChromaMotion ) : NOP()
509
	fVec5 = IsClip(fVec5) ? fVec5 : \
510
	        (maxTR > 4)   ? srchSuper.MAnalyse( isb=false, delta=5, blksize=BlockSize, overlap=Overlap, search=Search, searchparam=SearchParam, \
511
	                                            pelsearch=PelSearch, truemotion=TrueMotion, lambda=Lambda, lsad=LSAD, pnew=PNew, plevel=PLevel, \
512
	                                            global=GlobalMotion, DCT=DCT, chroma=ChromaMotion ) : NOP()
513
514
	# Expose search clip, motion search super clip and motion vectors to calling script through globals
515
	QTGMC_SetUserGlobal( GlobalNames, "srchClip",  srchClip,  ReplaceGlobals )
516
	QTGMC_SetUserGlobal( GlobalNames, "srchSuper", srchSuper, ReplaceGlobals )
517
	QTGMC_SetUserGlobal( GlobalNames, "bVec1",     bVec1,     ReplaceGlobals )
518
	QTGMC_SetUserGlobal( GlobalNames, "fVec1",     fVec1,     ReplaceGlobals )
519
	QTGMC_SetUserGlobal( GlobalNames, "bVec2",     bVec2,     ReplaceGlobals )
520
	QTGMC_SetUserGlobal( GlobalNames, "fVec2",     fVec2,     ReplaceGlobals )
521
	QTGMC_SetUserGlobal( GlobalNames, "bVec3",     bVec3,     ReplaceGlobals )
522
	QTGMC_SetUserGlobal( GlobalNames, "fVec3",     fVec3,     ReplaceGlobals )
523
	QTGMC_SetUserGlobal( GlobalNames, "bVec4",     bVec4,     ReplaceGlobals )
524
	QTGMC_SetUserGlobal( GlobalNames, "fVec4",     fVec4,     ReplaceGlobals )
525
	QTGMC_SetUserGlobal( GlobalNames, "bVec5",     bVec5,     ReplaceGlobals )
526
	QTGMC_SetUserGlobal( GlobalNames, "fVec5",     fVec5,     ReplaceGlobals )
527
528
529
	#---------------------------------------
530
	# Noise Processing
531
532
	# >>>> Interleaved YUY2 for denoising, planar whilst pre-motion compensating
533
534
	# Expand fields to full frame size before extracting noise (allows use of motion vectors which are frame-sized)
535
	fullClip  = (NoiseProcess == 0) ? NOP() : \
536
	            (InputType > 0)     ? clip : \
537
	                                  clip.QTGMC_Bob( 0,1.0 )
538
	fullClip  = (yuy2 && NoiseTR > 0) ? fullClip.converttoyv16() : fullClip
539
	fullSuper = (NoiseTR > 0)         ? fullClip.MSuper( pel=SubPel, levels=1, hpad=hpad, vpad=vpad, chroma=ChromaNoise ) : NOP() #TEST chroma OK?
540
541
	# Create a motion compensated temporal window around current frame and use to guide denoisers
542
	noiseWindow = (NoiseProcess == 0) ? NOP() : \
543
	              (!DenoiseMC)        ? fullClip : \
544
	              (NoiseTR == 0)      ? fullClip : \
545
	              (NoiseTR == 1)      ? Interleave( fullClip.MCompensate( fullSuper, fVec1, thSCD1=ThSCD1,thSCD2=ThSCD2 ), \
546
	                                                fullClip, \
547
	                                                fullClip.MCompensate( fullSuper, bVec1, thSCD1=ThSCD1,thSCD2=ThSCD2 ) ) : \
548
	                                    Interleave( fullClip.MCompensate( fullSuper, fVec2, thSCD1=ThSCD1,thSCD2=ThSCD2 ), \
549
	                                                fullClip.MCompensate( fullSuper, fVec1, thSCD1=ThSCD1,thSCD2=ThSCD2 ), \
550
	                                                fullClip, \
551
	                                                fullClip.MCompensate( fullSuper, bVec1, thSCD1=ThSCD1,thSCD2=ThSCD2 ), \
552
	                                                fullClip.MCompensate( fullSuper, bVec2, thSCD1=ThSCD1,thSCD2=ThSCD2 ) )
553
	noiseWindow = yuy2 && (Denoiser == "fft3df") && NoiseTR > 0 ? noiseWindow.ConvertToYUY2() : noiseWindow
554
	dnWindow = (NoiseProcess == 0)      ? NOP() : \
555
	           (Denoiser == "dfttest")  ? noiseWindow.dfttest( Y=true, U=ChromaNoise, V=ChromaNoise, sigma=Sigma*4, tbsize=noiseTD, threads=FftThreads, lsb=lsbd ) : \
556
	        (Denoiser == "KNLMeansCL")  ? noiseWindow.SMDegrain_KNLMeansCL(Chroma=ChromaNoise, lsb=lsbd, a=2, d=NoiseTR, h=Sigma, device_type="GPU" ) : \
557
	                                      noiseWindow.FFT3DFilter( plane=(ChromaNoise ? 4 : 0), sigma=Sigma, bt=noiseTD, ncpu=FftThreads )
558
	dnwindow = (Denoiser == "KNLMeansCL" || Denoiser == "dfttest") && (NoiseProcess != 0) && lsbd ? dnWindow.ditherpost(mode=6, U=ChromaNoise?3:2, V=ChromaNoise?3:2, slice=false) : dnWindow
559
	dnwindow = (Denoiser == "KNLMeansCL" || Denoiser == "dfttest") && (NoiseProcess != 0) && yuy2 ? dnWindow.ConvertToYUY2() : dnWindow
560
561
	# Rework denoised clip to match source format - various code paths here: discard the motion compensation window, discard doubled lines (from point resize)
562
	# 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)
563
	denoised = (NoiseProcess == 0) ? NOP() : \
564
	           (!DenoiseMC)        ? ((InputType > 0) ? dnWindow : dnWindow.SeparateFields().SelectEvery( 4, 0,3 ).Weave()) : \
565
	           (InputType > 0)     ? ((NoiseTR == 0)  ? dnWindow : dnWindow.SelectEvery( noiseTD, NoiseTR )) : \
566
	                                 dnWindow.SeparateFields().SelectEvery( noiseTD*4, NoiseTR*2,NoiseTR*6+3 ).Weave()
567
568
	# >>>> Switch to planar YUY2 for noise bypass
569
570
	CNmt1   = ChromaNoise ? 3 : 1
571
	CNmt2   = ChromaNoise ? 3 : 2
572
	CNmt128 = ChromaNoise ? 3 : -128
573
574
	# Get actual noise from difference. Then 'deinterlace' where we have weaved noise - create the missing lines of noise in various ways
575
	planarDenoised = (NoiseProcess == 0) ? NOP() : yuy2 ? denoised.converttoyv16() : denoised
576
	noise = (totalRestore > 0.0)  ? mt_makediff( planarClip, planarDenoised, U=CNmt1,V=CNmt1 ) : NOP()
577
	deintNoise = (NoiseProcess == 0 || totalRestore == 0.0) ? NOP() : \
578
	             (InputType != 0)                           ? noise : \
579
	             (NoiseDeint == "Bob")                      ? noise.QTGMC_Bob( 0,0.5 ) : \
580
	             (NoiseDeint == "Generate")                 ? noise.QTGMC_Generate2ndFieldNoise( denoised, ChromaNoise ) : \
581
	                                                          noise.DoubleWeave()
582
	# Motion-compensated stabilization of generated noise
583
	noiseSuper = (StabilizeNoise) ? deintNoise.MSuper( pel=SubPel, sharp=SubPelInterp, levels=1, hpad=hpad, vpad=vpad, chroma=ChromaNoise ) : NOP()
584
	mcNoise    = (StabilizeNoise) ? deintNoise.MCompensate( noiseSuper, bVec1, thSCD1=ThSCD1,thSCD2=ThSCD2 ) : NOP()
585
	finalNoise = (StabilizeNoise) ? mt_lutxy( deintNoise, mcNoise, "x 128 - abs y 128 - abs > x y ? 0.6 * x y + 0.2 * +", U=CNmt1,V=CNmt1 ) : deintNoise
586
587
	# 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
588
	innerClip = (NoiseProcess == 1) ? denoised : clip
589
590
591
	#---------------------------------------
592
	# Interpolation
593
594
	# >>>> Interleaved YUY2 for interpolation
595
596
	# Support badly deinterlaced progressive content - drop half the fields and reweave to get 1/2fps interlaced stream appropriate for QTGMC processing
597
	ediInput = (InputType == 2 || InputType == 3) ? innerClip.SeparateFields().SelectEvery(4,0,3).Weave() : innerClip
598
599
	# Create interpolated image as starting point for output
600
	edi1 = defined(EdiExt) ? EdiExt.PointResize( w,h, 0,(EdiExt.Height()-h)/2, -0,h+epsilon ) : \
601
	                         QTGMC_Interpolate( ediInput, InputType, EdiMode, NNSize, NNeurons, EdiQual, EdiMaxD, EdiThreads, bobbed, ChromaEdi )
602
603
	# >>>> Switch to planar YUY2 during next step - remains planar until very end of script except blurring for back blending & SVThin
604
605
	# 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
606
	inputTypeBlend = (ProgSADMask > 0.0) ? MMask( srchClip, bVec1, kind=1, ml=ProgSADMask ) : NOP()
607
	edi = (InputType != 2 && InputType != 3) ? (!yuy2 ? edi1 : edi1.ConvertToYV16()) :\
608
	      (ProgSADMask <= 0.0)               ? (!yuy2 ? edi1.MergeChroma( innerClip ) : edi1.MergeChroma( innerClip ).ConvertToYV16()) : \
609
	                                           (!yuy2 ? mt_merge( innerClip, edi1, inputTypeBlend, U=2,V=2 ) : \
610
											            mt_merge( innerClip.ConvertToYV16(), edi1.ConvertToYV16(), inputTypeBlend, U=2,V=2 ))
611
612
	# Get the max/min value for each pixel over neighboring motion-compensated frames - used for temporal sharpness limiting
613
	ediSuper = (TR1 > 0 || temporalSL)   ? edi.MSuper( pel=SubPel, sharp=SubPelInterp, levels=1, hpad=hpad, vpad=vpad ) : NOP()
614
	bComp1   = (temporalSL)              ? edi.MCompensate( ediSuper, bVec1, thSCD1=ThSCD1,thSCD2=ThSCD2              ) : NOP()
615
	fComp1   = (temporalSL)              ? edi.MCompensate( ediSuper, fVec1, thSCD1=ThSCD1,thSCD2=ThSCD2              ) : NOP()
616
	tMax     = (temporalSL)              ? edi.mt_logic( fComp1, "max", U=3,V=3 ).mt_logic( bComp1, "max", U=3,V=3 )    : NOP()
617
	tMin     = (temporalSL)              ? edi.mt_logic( fComp1, "min", U=3,V=3 ).mt_logic( bComp1, "min", U=3,V=3 )    : NOP()
618
	bComp3   = (SLRad > 1 && temporalSL) ? edi.MCompensate( ediSuper, bVec3, thSCD1=ThSCD1,thSCD2=ThSCD2              ) : NOP()
619
	fComp3   = (SLRad > 1 && temporalSL) ? edi.MCompensate( ediSuper, fVec3, thSCD1=ThSCD1,thSCD2=ThSCD2              ) : NOP()
620
	tMax     = (SLRad > 1 && temporalSL) ? tMax.mt_logic( fComp3, "max", U=3,V=3 ).mt_logic( bComp3, "max", U=3,V=3 )   : tMax
621
	tMin     = (SLRad > 1 && temporalSL) ? tMin.mt_logic( fComp3, "min", U=3,V=3 ).mt_logic( bComp3, "min", U=3,V=3 )   : tMin
622
623
624
	#---------------------------------------
625
	# Create basic output
626
627
	# Use motion vectors to blur interpolated image (edi) with motion-compensated previous and next frames. As above, this is done to remove shimmer from
628
	# alternate frames so the same binomial kernels are used. However, by using motion-compensated smoothing this time we avoid motion blur. The use of
629
	# MDegrain1 (motion compensated) rather than TemporalSmooth makes the weightings *look* different, but they evaluate to the same values
630
	# Create linear weightings of neighbors first                                                                                -2    -1     0    1     2
631
	degrain1 = (TR1 > 0) ? edi.MDegrain1( ediSuper, bVec1,fVec1, thSAD=ThSAD1, thSCD1=ThSCD1,thSCD2=ThSCD2, lsb=lsb) : NOP()  # 0.00  0.33  0.33  0.33  0.00
632
	degrain2 = (TR1 > 1) ? edi.MDegrain1( ediSuper, bVec2,fVec2, thSAD=ThSAD1, thSCD1=ThSCD1,thSCD2=ThSCD2, lsb=lsb) : NOP()  # 0.33  0.00  0.33  0.00  0.33
633
	degrain1 = (TR1 > 0) && lsb ? degrain1.ditherpost(mode=6, slice=false) : degrain1
634
	degrain2 = (TR1 > 1) && lsb ? degrain2.ditherpost(mode=6, slice=false) : degrain2
635
636
	# Combine linear weightings to give binomial weightings - TR1=0: (1), TR1=1: (1:2:1), TR1=2: (1:4:6:4:1)
637
	binomial1 = (TR1 == 0) ? edi : \
638
	            (TR1 == 1) ? degrain1.Merge( edi, 0.25 ) : \
639
	                         degrain1.Merge( degrain2, 0.2 ).Merge( edi, 0.0625 )
640
641
	# Remove areas of difference between smoothed image and interpolated image that are not bob-shimmer fixes: repairs residual motion blur from temporal smooth
642
	repair1 = (Rep1 == 0) ? binomial1 : binomial1.QTGMC_KeepOnlyBobShimmerFixes( edi, Rep1, RepChroma )
643
644
	# Apply source match - use difference between output and source to succesively refine output [extracted to function to clarify main code path]
645
	match = (SourceMatch == 0) ? repair1 : \
646
	                             repair1.QTGMC_ApplySourceMatch( InputType, ediInput, bVec1,fVec1, bVec2,fVec2, SubPel, SubPelInterp, hpad, vpad, \
647
	                                                             ThSAD1, ThSCD1, ThSCD2, SourceMatch, MatchTR1, MatchEdi, MatchNNSize, MatchNNeurons, \
648
	                                                             MatchEdiQual, MatchEdiMaxD, MatchTR2, MatchEdi2, MatchNNSize2, MatchNNeurons2, MatchEdiQual2, \
649
	                                                             MatchEdiMaxD2, MatchEnhance, EdiThreads, lsb )
650
651
	# Lossless=2 - after preparing an interpolated, de-shimmered clip, restore the original source fields into it and clean up any artefacts.
652
	# This mode will not give a true lossless result because the resharpening and final temporal smooth are still to come, but it will add further detail.
653
	# However, it can introduce minor combing. This setting is best used together with source-match (it's effectively the final source-match stage).
654
	lossed1 = (Lossless == 2) ? QTGMC_MakeLossless( match, innerClip, InputType ) : match
655
656
657
	#---------------------------------------
658
	# Resharpen / retouch output
659
660
	# Resharpen to counteract temporal blurs. Little sharpening needed for source-match mode since it has already recovered sharpness from source
661
	vresharp1 = (SMode == 2) ? Merge( lossed1.mt_expand( mode="vertical", U=3,V=3 ), lossed1.mt_inpand( mode="vertical", U=3,V=3 ) ) : NOP()
662
	vresharp  = (Precise && SMode == 2) ? vresharp1.mt_lutxy( lossed1, "x y < x 1 + x y > x 1 - x ? ?", U=3,V=3 ) : vresharp1 # Precise mode: reduce tiny overshoot
663
	resharp   = (SMode == 0) ? lossed1 : \
664
	            (SMode == 1) ? lossed1.mt_lutxy( lossed1.RemoveGrain( rgBlur ),  "x x y - "+ string(sharpAdj) + " * +", U=3,V=3 ) : \
665
	                           lossed1.mt_lutxy( vresharp.RemoveGrain( rgBlur ), "x x y - "+ string(sharpAdj) + " * +", U=3,V=3 )
666
667
	# Slightly thin down 1-pixel high horizontal edges that have been widened into neigboring field lines by the interpolator
668
	SVThinSc = SVThin * 6.0
669
	vertMedD = (SVthin > 0.0) ? mt_lutxy( lossed1, lossed1.VerticalCleaner( mode=1, modeU=-1, modeV=-1 ), "y x - " + string(SVThinSc) + " * 128 +", U=1,V=1 ) : NOP()
670
	vertMedD = (SVthin > 0.0) ? (vertMedD.Blur( 1,0 )) : NOP()
671
	neighborD = (SVthin > 0.0) ? mt_lutxy( vertMedD, vertMedD.RemoveGrain( rgBlur,-1 ), "y 128 - abs x 128 - abs > y 128 ?" ) : NOP()
672
	thin      = (SVthin > 0.0) ? resharp.mt_adddiff( neighborD, U=2,V=2 ) : resharp
673
674
	# Back blend the blurred difference between sharpened & unsharpened clip, before (1st) sharpness limiting (Sbb == 1,3). A small fidelity improvement
675
	backBlend1 = (Sbb != 1 && Sbb != 3) ? thin : \
676
		                 thin.mt_makediff( mt_makediff( thin, lossed1, U=1,V=1 ).RemoveGrain( 12, -1 ) \
677
	                         .GaussResize( w,h, 0,0, w+epsilon,h+epsilon, p=5 ), U=2,V=2 )
678
679
	# Limit over-sharpening by clamping to neighboring (spatial or temporal) min/max values in original
680
	# Occurs here (before final temporal smooth) if SLMode == 1,2. This location will restrict sharpness more, but any artefacts introduced will be smoothed
681
	sharpLimit1 = (SLMode == 1) ? backBlend1.Repair( ((SLrad <= 1) ? edi : backBlend1.Repair( edi, 12 )), 1 ) : \
682
	              (SLMode == 2) ? backBlend1.mt_clamp( tMax,tMin, Sovs,Sovs, U=3,V=3 ) : \
683
	                              backBlend1
684
685
	# Back blend the blurred difference between sharpened & unsharpened clip, after (1st) sharpness limiting (Sbb == 2,3). A small fidelity improvement
686
	backBlend2 = (Sbb < 2) ? sharpLimit1 : \
687
		                 sharpLimit1.mt_makediff( mt_makediff( sharpLimit1, lossed1, U=1,V=1 ).RemoveGrain( 12, -1 ) \
688
	                                    .GaussResize( w,h, 0,0, w+epsilon,h+epsilon, p=5 ), U=2,V=2 )
689
690
	# Add back any extracted noise, prior to final temporal smooth - this will restore detail that was removed as "noise" without restoring the noise itself
691
	# Average luma of FFT3DFilter extracted noise is 128.5, so deal with that too
692
	addNoise1 = (GrainRestore <= 0.0) ? backBlend2 : \
693
		                                backBlend2.mt_adddiff( finalNoise.mt_lut( "x " + noiseCentre + " - " + string(GrainRestore) + " * 128 +", U=CNmt1,V=CNmt1 ), U=CNmt2,V=CNmt2 )
694
695
	# Final light linear temporal smooth for denoising
696
	stableSuper = (TR2 > 0) ? addNoise1.MSuper( pel=SubPel, sharp=SubPelInterp, levels=1, hpad=hpad, vpad=vpad ) : NOP()
697
	stable  = (TR2 == 0) ? addNoise1 : \
698
	          (TR2 == 1) ? addNoise1.MDegrain1( stableSuper, bVec1,fVec1,                                                     thSAD=ThSAD2, thSCD1=ThSCD1,thSCD2=ThSCD2, lsb=lsb ) : \
699
	          (TR2 == 2) ? addNoise1.MDegrain2( stableSuper, bVec1,fVec1, bVec2,fVec2,                                        thSAD=ThSAD2, thSCD1=ThSCD1,thSCD2=ThSCD2, lsb=lsb ) : \
700
 	          (TR2 == 3) ? addNoise1.MDegrain3( stableSuper, bVec1,fVec1, bVec2,fVec2, bVec3,fVec3,                           thSAD=ThSAD2, thSCD1=ThSCD1,thSCD2=ThSCD2, lsb=lsb ) : \
701
 	          (TR2 == 4) ? addNoise1.MDegrain4( stableSuper, bVec1,fVec1, bVec2,fVec2, bVec3,fVec3, bVec4,fVec4,              thSAD=ThSAD2, thSCD1=ThSCD1,thSCD2=ThSCD2, lsb=lsb ) : \
702
 	                       addNoise1.MDegrain5( stableSuper, bVec1,fVec1, bVec2,fVec2, bVec3,fVec3, bVec4,fVec4, bVec5,fVec5, thSAD=ThSAD2, thSCD1=ThSCD1,thSCD2=ThSCD2, lsb=lsb )
703
	stable  = (TR2 > 0) && lsb ? stable.ditherpost(mode=6, slice=false) : stable
704
705
	# Remove areas of difference between final output & basic interpolated image that are not bob-shimmer fixes: repairs motion blur caused by temporal smooth
706
	repair2 = (Rep2 == 0) ? stable : stable.QTGMC_KeepOnlyBobShimmerFixes( edi, Rep2, RepChroma )
707
708
	# Limit over-sharpening by clamping to neighboring (spatial or temporal) min/max values in original
709
	# Occurs here (after final temporal smooth) if SLMode == 3,4. Allows more sharpening here, but more prone to introducing minor artefacts
710
	sharpLimit2 = (SLMode == 3) ? repair2.Repair( ((SLrad <= 1) ? edi : repair2.Repair( edi, 12 )), 1 ) : \
711
	              (SLMode == 4) ? repair2.mt_clamp( tMax,tMin, Sovs,Sovs, U=3,V=3 ) : \
712
	                              repair2
713
714
	# Lossless=1 - inject source fields into result and clean up inevitable artefacts. Provided NoiseRestore=0.0 or 1.0, this mode will make the script result 
715
	# properly lossless, but this will retain source artefacts and cause some combing (where the smoothed deinterlace doesn't quite match the source)
716
	lossed2 = (Lossless == 1) ? QTGMC_MakeLossless( sharpLimit2, innerClip, InputType ) : sharpLimit2
717
718
	# Add back any extracted noise, after final temporal smooth. This will appear as noise/grain in the output
719
	# Average luma of FFT3DFilter extracted noise is 128.5, so deal with that too
720
	addNoise2 = (NoiseRestore <= 0.0) ? lossed2 : \
721
		                                lossed2.mt_adddiff( finalNoise.mt_lut( "x " + noiseCentre + " - " + string(NoiseRestore) + " * 128 +", U=CNmt1,V=CNmt1 ), U=CNmt2,V=CNmt2 )
722
723
724
	#---------------------------------------
725
	# Post-Processing
726
727
	# Shutter motion blur - get level of blur depending on output framerate and blur already in source
728
	blurLevel = (ShutterAngleOut * FPSDivisor - ShutterAngleSrc) * 100.0 / 360.0
729
	Assert( blurLevel >= 0, "Cannot reduce motion blur already in source: increase ShutterAngleOut or FPSDivisor" )
730
	Assert( blurLevel <= 200, "Exceeded maximum motion blur level: decrease ShutterAngleOut or FPSDivisor" )
731
732
	# ShutterBlur mode 2,3 - get finer resolution motion vectors to reduce blur "bleeding" into static areas
733
	rBlockDivide = Select( ShutterBlur, 1, 1, 2, 4 )
734
	rBlockSize = BlockSize / rBlockDivide
735
	rOverlap   = Overlap   / rBlockDivide
736
	rBlockSize = (rBlockSize < 4) ? 4 : rBlockSize
737
	rOverlap   = (rOverlap   < 2) ? 2 : rOverlap
738
	rBlockDivide = BlockSize / rBlockSize
739
	rLambda = Lambda / (rBlockDivide * rBlockDivide)
740
	sbBVec1 = (ShutterBlur > 1) ? srchSuper.MRecalculate( bVec1, thSAD=ThSAD1, blksize=rBlockSize, overlap=rOverlap, search=Search, searchparam=SearchParam, \
741
	                                                      truemotion=TrueMotion, lambda=Lambda, pnew=PNew, DCT=DCT, chroma=ChromaMotion ) : bVec1
742
	sbFVec1 = (ShutterBlur > 1) ? srchSuper.MRecalculate( fVec1, thSAD=ThSAD1, blksize=rBlockSize, overlap=rOverlap, search=Search, searchparam=SearchParam, \
743
	                                                      truemotion=TrueMotion, lambda=Lambda, pnew=PNew, DCT=DCT, chroma=ChromaMotion ) : fVec1
744
745
	# Shutter motion blur - use MFlowBlur to blur along motion vectors
746
	sblurSuper = (ShutterBlur > 0) ? addNoise2.MSuper( pel=SubPel, sharp=SubPelInterp, levels=1, hpad=hpad, vpad=vpad ) : NOP()
747
	sblur =      (ShutterBlur > 0) ? addNoise2.MFlowBlur( sblurSuper, sbBVec1, sbFVec1, blur=blurLevel, thSCD1=ThSCD1,thSCD2=ThSCD2 ) : NOP()
748
749
	# Shutter motion blur - use motion mask to reduce blurring in areas of low motion - also helps reduce blur "bleeding" into static areas, then select blur type
750
	sbMotionMask = (ShutterBlur > 0 && SBlurLimit > 0) ? MMask( srchClip, bVec1, kind=0, ml=SBlurLimit ) : NOP()
751
	sblurred     = (ShutterBlur == 0) ? addNoise2 : \
752
	               (SBlurLimit == 0)  ? sblur : \
753
	                                    mt_merge( addNoise2, sblur, sbMotionMask, U=3,V=3 )
754
	# Reduce frame rate
755
	decimated = (FPSDivisor != 1) ? sblurred.SelectEvery( FPSDivisor, 0 ) : sblurred
756
757
	# Crop off temporary vertical padding
758
	cropped = Border ? decimated.Crop( 0, 4, -0, -4 ) : decimated
759
	h = Border ? h-8 : h
760
761
	# Show output of choice + settings
762
	# >>>> Restore YUY2 to interleaved
763
	output = (ShowNoise == 0.0) ? cropped : finalNoise.mt_lut( "x 128 - " + string(ShowNoise) + " * 128 +", U=CNmt128,V=CNmt128 )
764
	output = yuy2 ? output.ConvertToYUY2() : output
765
	return (ShowSettings == false) ? output : \
766
		output.Subtitle( "TR0=" + string(TR0) + " | TR1=" + string(TR1) + " | TR2=" + string(TR2) + " | Rep0=" + string(Rep0) + " | Rep1=" + string(Rep1) + \
767
		" | Rep2=" + string(Rep2) + " | RepChroma=" + string(RepChroma) + "\nEdiMode='" + EdiMode + "' | NNSize=" + string(NNSize) + " | NNeurons=" + \
768
		string(NNeurons) + " | EdiQual=" + string(EdiQual) + " | EdiMaxD=" + string(EdiMaxD) + " | ChromaEdi='" + ChromaEdi + "' | EdiThreads=" + \
769
		string(EdiThreads) + "\nSharpness=" + string(Sharpness, "%.2f") + " | SMode=" + string(SMode) + " | SLMode=" + string(SLMode) + " | SLRad=" + \
770
		string(SLRad) + " | SOvs=" + string(SOvs) + " | SVThin=" + string(SVThin, "%.2f") + " | Sbb=" + string(Sbb) + "\nSrchClipPP=" + string(SrchClipPP) + \
771
		" | SubPel=" + string(SubPel) + " | SubPelInterp=" + string(SubPelInterp) + " | BlockSize=" + string(BlockSize) + " | Overlap=" + string(Overlap) + \
772
		"\nSearch=" + string(Search) + " | SearchParam=" + string(SearchParam) + " | PelSearch=" + string(PelSearch) + " | ChromaMotion=" + \
773
		string(ChromaMotion) + " | TrueMotion=" + string(TrueMotion) + "\nLambda=" + string(Lambda) + " | LSAD=" + string(LSAD) + " | PNew=" + string(PNew) + \
774
		" | PLevel=" + string(PLevel) + " | GlobalMotion=" + string(GlobalMotion) + " | DCT=" + string(DCT) + "\nThSAD1=" + string(ThSAD1) + " | ThSAD2=" + \
775
		string(ThSAD2) + " | ThSCD1=" + string(ThSCD1) + " | ThSCD2=" + string(ThSCD2) + "\nSourceMatch=" + string(SourceMatch) + " | MatchPreset='" + \
776
		MatchPreset + "' | MatchEdi='" + MatchEdi + "'\nMatchPreset2='" + MatchPreset2 + "' | MatchEdi2='" + MatchEdi2 + "' | MatchTR2=" + string(MatchTR2) + \
777
		" | MatchEnhance=" + string(MatchEnhance, "%.2f") + " | Lossless=" + string(Lossless) + "\nNoiseProcess=" + string(NoiseProcess) + " | Denoiser='" + \
778
		Denoiser + "' | FftThreads=" + string(FftThreads) + " | DenoiseMC=" + string(DenoiseMC) + " | NoiseTR=" + string(NoiseTR) + " | Sigma=" + \
779
		string(Sigma, "%.2f") + "\nChromaNoise=" + string(ChromaNoise) + " | ShowNoise=" + string(ShowNoise, "%.2f") + " | GrainRestore=" + \
780
		string(GrainRestore, "%.2f") + " | NoiseRestore=" + string(NoiseRestore, "%.2f") + "\nNoiseDeint='" + NoiseDeint + "' | StabilizeNoise=" + \
781
		string(StabilizeNoise) + " | InputType=" + string(InputType) + " | ProgSADMask=" + string(ProgSADMask, "%.2f") + "\nFPSDivisor=" + \
782
		string(FPSDivisor) + " | ShutterBlur=" + string(ShutterBlur) + " | ShutterAngleSrc=" + string(ShutterAngleSrc, "%.2f") + " | ShutterAngleOut=" + \
783
		string(ShutterAngleOut, "%.2f") + " | SBlurLimit=" + string(SBlurLimit) + "\nBorder=" + string(Border) + " | Precise=" + string(Precise) + \
784
		"\nPreset='" + Preset + "' | Tuning='" + Tuning + "' | GlobalNames='" + GlobalNames + "' | PrevGlobals='" + PrevGlobals + "' | ForceTR=" + \
785
		string(ForceTR), font="Lucida Console", size=11, lsp=12 )
786
}
787
788
789
#---------------------------------------
790
# Helpers
791
792
# Same as Bob, but keeps the field order the same.
793
function QTGMC_Bob(clip cp, float "b", float "c", int "height" )
794
{
795
  ssispmt = Findstr(VersionString(), "AviSynth+") != 0 && Findstr(VersionString(), "r1576") == 0
796
  h = Default(height, cp.Height)
797
  w = cp.Width
798
  shift = GetParity(cp) ? 0.25 : -0.25
799
800
  c420 = ssispmt ? Is420(cp) : IsYV12(cp)
801
802
  c420 ? cp.SeparateFields() : nop()
803
804
  oeven=c420 ? SelectEven() : nop()
805
  oodd=c420 ? SelectOdd() : nop()
806
807
  even=c420 ? ssispmt ? oeven.ConvertToY().BicubicResize(w, h, b, c, 0, shift, w, Height()).AssumeFrameBased() : oeven.ConvertToY8().BicubicResize(w, h, b, c, 0, shift, w, Height()).AssumeFrameBased() : nop()
808
  odd=c420 ? ssispmt ? oodd.ConvertToY().BicubicResize(w, h, b, c, 0, -shift, w, Height()).AssumeFrameBased() : oodd.ConvertToY8().BicubicResize(w, h, b, c, 0, -shift, w, Height()).AssumeFrameBased() : nop()
809
810
  evenChr=c420 ? Interleave(ssispmt ? oeven.ExtractU() : oeven.UToY8(), ssispmt ? oeven.ExtractV() : oeven.VToY8()).BicubicResize(w/2, h/2, b, c, 0, shift, w/2, Height()/2).AssumeFrameBased() : nop()
811
  oddChr=c420 ? Interleave(ssispmt ? oodd.ExtractU() : oodd.UToY8(), ssispmt ? oodd.ExtractV() :oodd.VToY8()).BicubicResize(w/2, h/2, b, c, 0, -shift, w/2, Height()/2).AssumeFrameBased() : nop()
812
813
  c420 ? YToUV(Interleave(evenChr.SelectEven(), oddChr.SelectEven()),Interleave(evenChr.SelectOdd(), oddChr.SelectOdd()),Interleave(even, odd)) : cp.Bob( b,c, h )
814
  GetParity(cp) ? AssumeTFF() : AssumeBFF()
815
}
816
817
818
# Interpolate input clip using method given in EdiMode. Use Fallback or Bob as result if mode not in list. If ChromaEdi string if set then interpolate chroma
819
# separately with that method (only really useful for EEDIx). The function is used as main algorithm starting point and for first two source-match stages
820
function QTGMC_Interpolate( clip Input, int InputType, string EdiMode, int NNSize, int NNeurons, int EdiQual, int EdiMaxD, int EdiThreads, clip "Fallback", \
821
                            string "ChromaEdi" )
822
{
823
	# >>>> YUY2 is interleaved here
824
825
	ChromaEdi = default( ChromaEdi, "" )
826
	CEed = (ChromaEdi == "")
827
828
	interp = (InputType == 1)            ? Input : \
829
	         (EdiMode == "NNEDI3")       ? Input.NNEDI3( field=-2, nsize=NNSize, nns=NNeurons, qual=EdiQual, threads=EdiThreads, U=CEed,V=CEed ) : \
830
	         (EdiMode == "NNEDI2")       ? Input.NNEDI2( field=-2, nsize=NNeurons, qual=EdiQual, threads=EdiThreads, U=CEed,V=CEed ) : \
831
	         (EdiMode == "NNEDI")        ? Input.NNEDI( field=-2, U=CEed,V=CEed ) : \
832
	         (EdiMode == "EEDI3+NNEDI3") ? Input.EEDI3( field=-2, mdis=EdiMaxD, threads=EdiThreads, U=CEed,V=CEed, \
833
		                                                sclip=Input.NNEDI3( field=-2, nsize=NNSize, nns=NNeurons, qual=EdiQual, threads=EdiThreads, U=CEed,V=CEed ) ) : \
834
	         (EdiMode == "EEDI3")        ? Input.EEDI3( field=-2, mdis=EdiMaxD, threads=EdiThreads, U=CEed,V=CEed ) : \
835
	         (EdiMode == "EEDI2")        ? Input.SeparateFields().EEDI2( field=-2, maxd=EdiMaxD ) : \
836
	         (EdiMode == "Yadif")        ? isyuy2(Input) ? Input.ConvertToYv16().Yadifmod2( mode=3 ).ConvertToYUY2() : Input.Yadifmod2( mode=3 ) : \
837
	         (EdiMode == "cYadif")       ? Input.Yadif( mode=3 ) : \
838
	         (EdiMode == "TDeint")       ? Input.TDeInt( mode=1 ) : \
839
	         (EdiMode == "RepYadif")     ? isyuy2(Input) ? Repair( Input.ConvertToYv16().Yadifmod2( mode=3 ), default( Fallback, Input.QTGMC_Bob( 0,0.5 ) ).ConvertToYv16(), 2, 0 ).ConvertToYUY2() : \
840
                                                           Input.Yadifmod2( mode=3 ) : \	
841
	         (EdiMode == "RepcYadif")    ? isyuy2(Input) ? Repair( Input.Yadif( mode=3 ).ConvertToYv16(), default( Fallback, Input.QTGMC_Bob( 0,0.5 ) ).ConvertToYv16(), 2, 0 ).ConvertToYUY2() : \
842
	         	         	                       Repair( Input.Yadif( mode=3 ), default( Fallback, Input.QTGMC_Bob( 0,0.5 ) ), 2, 0 ) : \
843
	                                       default( Fallback, Input.QTGMC_Bob( 0,0.5 ) )
844
845
	interpuv = (InputType == 1)        ? NOP() : \
846
	           (ChromaEdi == "NNEDI3") ? Input.NNEDI3( field=-2, nsize=4, nns=0, qual=1, threads=EdiThreads, Y=false ) : \
847
	           (ChromaEdi == "Yadif")  ? isyuy2(Input) ? Input.ConvertToYv16().Yadifmod2( mode=3 ).ConvertToYUY2() : Input.Yadifmod2( mode=3 ) : \
848
	           (ChromaEdi == "cYadif") ? Input.Yadif( mode=3 ) : \
849
	           (ChromaEdi == "Bob")    ? Input.QTGMC_Bob( 0,0.5 ) : \
850
			                             NOP()
851
852
	return (!IsClip(interpuv)) ? interp : interp.MergeChroma( interpuv )
853
}
854
855
856
# Functions (from original TGMC) used instead of mt_xxflate with similar operation but a somewhat stronger result. Originally added for speed, they are
857
# no longer faster due to improvements in masktools. Difference (visual and speed) is small so may be reverted in a later version.
858
function QTGMC_inflate( clip c, int "Y", int "U", int "V" )
859
{
860
	# >>>> YUY2 is planar here
861
	mtY =default( Y, 3 )
862
	mtU =default( U, 1 )
863
	mtV =default( V, 1 )
864
	rgY = (mtY == 3) ? 20 : -1
865
	rgU = (mtU == 3) ? 20 : -1
866
	rgV = (mtV == 3) ? 20 : -1
867
	mt_logic( c, c.RemoveGrain( rgY, rgU, rgV ), "max", Y=mtY,U=mtU,V=mtV )
868
}
869
870
function QTGMC_deflate( clip c, int "Y", int "U", int "V" )
871
{
872
	# >>>> YUY2 is planar here
873
	mtY =default( Y, 3 )
874
	mtU =default( U, 1 )
875
	mtV =default( V, 1 )
876
	rgY = (mtY == 3) ? 20 : -1
877
	rgU = (mtU == 3) ? 20 : -1
878
	rgV = (mtV == 3) ? 20 : -1
879
	mt_logic( c, c.RemoveGrain( rgY, rgU, rgV ), "min", Y=mtY,U=mtU,V=mtV )
880
}
881
882
# Helper function: Compare processed clip with reference clip: only allow thin, horizontal areas of difference, i.e. bob shimmer fixes
883
# Rough algorithm: Get difference, deflate vertically by a couple of pixels or so, then inflate again. Thin regions will be removed
884
#                  by this process. Restore remaining areas of difference back to as they were in reference clip.
885
function QTGMC_KeepOnlyBobShimmerFixes( clip Input, clip Ref, int Rep, bool Chroma )
886
{
887
	# >>>> YUY2 is planar here
888
889
	# ed is the erosion distance - how much to deflate then reflate to remove thin areas of interest: 0 = minimum to 6 = maximum
890
	# od is over-dilation level  - extra inflation to ensure areas to restore back are fully caught:  0 = none to 3 = one full pixel
891
	# If Rep < 10, then ed = Rep and od = 0, otherwise ed = 10s digit and od = 1s digit (nasty method, but kept for compatibility with original TGMC)
892
	Rep    = default( Rep,    1    )
893
	Chroma = default( Chroma, true )
894
	ed = (Rep < 10) ? Rep : Rep / 10
895
	od = (Rep < 10) ? 0   : Rep % 10
896
	RCrg  = Chroma ? 3 : 1
897
	RCrgo = Chroma ? 3 : 2
898
899
	diff = mt_makediff(Ref, Input, U=3,V=3 )
900
901
	# Areas of positive difference                                                                # ed = 0 1 2 3 4 5 6 7
902
	choke1 =                        diff.  mt_inpand( mode="vertical", U=RCrg,V=RCrg )            #      x x x x x x x x    1 pixel   \
903
	choke1 = (ed > 2)             ? choke1.mt_inpand( mode="vertical", U=RCrg,V=RCrg ) : choke1   #      . . . x x x x x    1 pixel    |  Deflate to remove thin areas
904
	choke1 = (ed > 5)             ? choke1.mt_inpand( mode="vertical", U=RCrg,V=RCrg ) : choke1   #      . . . . . . x x    1 pixel   /
905
	choke1 = (ed % 3 != 0)        ? choke1.QTGMC_deflate( U=RCrg,V=RCrg )              : choke1   #      . x x . x x . x    A bit more deflate & some horizonal effect
906
	choke1 = (ed == 2 || ed == 5) ? choke1.RemoveGrain( 4              )               : choke1   #      . . x . . x . .    Local median
907
                                                                                                                      
908
	choke1 =                        choke1.mt_expand( mode="vertical", U=RCrg,V=RCrg )            #      x x x x x x x x    1 pixel  \
909
	choke1 = (ed > 1)             ? choke1.mt_expand( mode="vertical", U=RCrg,V=RCrg ) : choke1   #      . . x x x x x x    1 pixel   | Reflate again
910
	choke1 = (ed > 4)             ? choke1.mt_expand( mode="vertical", U=RCrg,V=RCrg ) : choke1   #      . . . . . x x x    1 pixel  /
911
912
	# Over-dilation - extra reflation up to about 1 pixel
913
	choke1 = (od == 0)            ? choke1 : \
914
	         (od == 1)            ? choke1.QTGMC_inflate( U=RCrg,V=RCrg ) : \
915
	         (od == 2)            ? choke1.QTGMC_inflate( U=RCrg,V=RCrg ).QTGMC_inflate( U=RCrg,V=RCrg ) : \
916
	                                choke1.mt_expand ( U=RCrg,V=RCrg )
917
918
	# Areas of negative difference (similar to above)
919
	choke2 =                        diff.  mt_expand( mode="vertical", U=RCrg,V=RCrg )         
920
	choke2 = (ed > 2)             ? choke2.mt_expand( mode="vertical", U=RCrg,V=RCrg ) : choke2
921
	choke2 = (ed > 5)             ? choke2.mt_expand( mode="vertical", U=RCrg,V=RCrg ) : choke2
922
	choke2 = (ed % 3 != 0)        ? choke2.QTGMC_inflate( U=RCrg,V=RCrg )              : choke2
923
	choke2 = (ed == 2 || ed == 5) ? choke2.RemoveGrain( 4              )               : choke2
924
	choke2 =                        choke2.mt_inpand( mode="vertical", U=RCrg,V=RCrg )
925
	choke2 = (ed > 1)             ? choke2.mt_inpand( mode="vertical", U=RCrg,V=RCrg ) : choke2
926
	choke2 = (ed > 4)             ? choke2.mt_inpand( mode="vertical", U=RCrg,V=RCrg ) : choke2
927
	choke2 = (od == 0)            ? choke2 : \
928
	         (od == 1)            ? choke2.QTGMC_deflate( U=RCrg,V=RCrg )  : \
929
	         (od == 2)            ? choke2.QTGMC_deflate( U=RCrg,V=RCrg ).QTGMC_deflate( U=RCrg,V=RCrg ) : \
930
	                                choke2.mt_inpand ( U=RCrg,V=RCrg )
931
932
	# Combine above areas to find those areas of difference to restore
933
	restore = diff.mt_lutxy( choke1, "x 129 < x y 128 < 128 y ? ?", U=RCrg,V=RCrg ).mt_lutxy( choke2, "x 127 > x y 128 > 128 y ? ?", U=RCrg,V=RCrg )
934
935
	return Input.mt_adddiff( restore, U=RCrgo,V=RCrgo )
936
}
937
938
939
# Given noise extracted from an interlaced source (i.e. the noise is interlaced), generate "progressive" noise with a new "field" of noise injected. The new
940
# noise is centered on a weighted local average and uses the difference between local min & max as an estimate of local variance
941
# YUY2 clip input is planar, but must pass interleaved version of clip to setup noise
942
function QTGMC_Generate2ndFieldNoise( clip Input, clip InterleavedClip, bool "ChromaNoise" )
943
{
944
	# >>>> YUY2 is planar here. Noise is generated (AddGrainC) interleaved, but immediately made planar
945
	ChromaNoise = default( ChromaNoise, false )
946
	CNmt1 = ChromaNoise ? 3 : 1
947
	origNoise = Input.SeparateFields()
948
	noiseMax  = origNoise.mt_expand( mode="square", U=CNmt1,V=CNmt1 ).mt_expand( mode="horizontal", U=CNmt1,V=CNmt1 )
949
	noiseMin  = origNoise.mt_inpand( mode="square", U=CNmt1,V=CNmt1 ).mt_inpand( mode="horizontal", U=CNmt1,V=CNmt1 )
950
	random    = BlankClip( InterleavedClip.SeparateFields(), color_yuv=$808080 ).AddGrainC( var=1800, uvar=ChromaNoise ? 1800 : 0 )
951
	random    = InterleavedClip.IsYUY2() ? random.converttoyv16() : random
952
	varRandom = mt_makediff( noiseMax, noiseMin, U=CNmt1,V=CNmt1 ).mt_lutxy( random, "x 128 - y * 256 / 128 +", U=CNmt1,V=CNmt1)
953
	newNoise  = noiseMin.mt_adddiff( varRandom, U=CNmt1,V=CNmt1 )
954
	return Interleave( origNoise, newNoise ).Weave()
955
}
956
957
958
# Insert the source lines into the result to create a true lossless output. However, the other lines in the result have had considerable processing and won't
959
# exactly match source lines. There will be some slight residual combing. Use vertical medians to clean a little of this away
960
function QTGMC_MakeLossless( clip Input, clip Source, int InputType )
961
{
962
	Assert( InputType != 1, "Lossless modes are incompatible with InputType=1" )
963
964
	# >>>> YUY2: 'Input' is planar, 'Source' is interleaved (changed to planar here for processing) - returns planar result
965
966
	# Weave the source fields and the "new" fields that have generated in the input
967
	srcFields1 = (InputType == 0) ? Source.SeparateFields() : Source.SeparateFields().SelectEvery( 4, 0,3 )
968
	srcFields  = Source.IsYUY2() ? srcFields1.converttoyv16() : srcFields1
969
	newFields  = Input.SeparateFields().SelectEvery( 4, 1,2 )
970
	processed  = Interleave( srcFields, newFields ).SelectEvery(4, 0,1,3,2 ).Weave()
971
972
	# Clean some of the artefacts caused by the above - creating a second version of the "new" fields
973
	vertMedian  = processed.VerticalCleaner( mode=1 )
974
	vertMedDiff = mt_makediff( processed, vertMedian, U=3,V=3 )
975
	vmNewDiff1  = vertMedDiff.SeparateFields().SelectEvery( 4, 1,2 )
976
	vmNewDiff2  = vmNewDiff1.VerticalCleaner( mode=1 ).mt_lutxy( vmNewDiff1, "x 128 - y 128 - * 0 < 128 x 128 - abs y 128 - abs < x y ? ?", U=3,V=3 )
977
	vmNewDiff3  = vmNewDiff2.Repair( vmNewDiff2.RemoveGrain( 2 ), 1 )
978
979
	# Reweave final result
980
	return Interleave( srcFields, newFields.mt_makediff( vmNewDiff3, U=3,V=3 )).SelectEvery( 4, 0,1,3,2 ).Weave()
981
}
982
983
984
# Source-match, a three stage process that takes the difference between deinterlaced input and the original interlaced source, to shift the input more towards
985
# the source without introducing shimmer. All other arguments defined in main script
986
function QTGMC_ApplySourceMatch( clip Deinterlace, int InputType, val Source, val bVec1, val fVec1, val bVec2, val fVec2, \
987
                                 int SubPel, int SubPelInterp, int hpad, int vpad, int ThSAD1, int ThSCD1, int ThSCD2, int SourceMatch, \
988
                                 int MatchTR1, string MatchEdi, int MatchNNSize, int MatchNNeurons, int MatchEdiQual, int MatchEdiMaxD,\
989
                                 int MatchTR2, string MatchEdi2, int MatchNNSize2, int MatchNNeurons2, int MatchEdiQual2, int MatchEdiMaxD2, \
990
                                 float MatchEnhance, int EdiThreads, bool lsb )
991
{
992
	# >>>> YUY2: 'Deinterlace' is planar, 'Source' is interleaved (changed to planar here for all processing except interpolation) - returns planar result
993
	yuy2 = Source.IsYUY2()
994
	Source = yuy2 ? Source.converttoyv16() : Source
995
996
	# Basic source-match. Find difference between source clip & equivalent fields in interpolated/smoothed clip (called the "error" in formula below). Ideally
997
	# there should be no difference, we want the fields in the output to be as close as possible to the source whilst remaining shimmer-free. So adjust the
998
	# *source* in such a way that smoothing it will give a result closer to the unadjusted source. Then rerun the interpolation (edi) and binomial smooth with
999
	# this new source. Result will still be shimmer-free and closer to the original source.
1000
	# Formula used for correction is P0' = P0 + (P0-P1)/(k+S(1-k)), where P0 is original image, P1 is the 1st attempt at interpolation/smoothing , P0' is the
1001
	# revised image to use as new source for interpolation/smoothing, k is the weighting given to the current frame in the smooth, and S is a factor indicating
1002
	# "temporal similarity" of the error from frame to frame, i.e. S = average over all pixels of [neighbor frame error / current frame error] . Decreasing
1003
	# S will make the result sharper, sensible range is about -0.25 to 1.0. Empirically, S=0.5 is effective [will do deeper analysis later]
1004
	errorTemporalSimilarity = 0.5  # S in formula described above
1005
	errorAdjust1   = Select( MatchTR1, 1.0, 2.0 / (1.0 + errorTemporalSimilarity), 8.0 / (3.0 + 5.0 * errorTemporalSimilarity) )
1006
	match1Clip     = (SourceMatch < 1 || InputType == 1) ? Deinterlace : Deinterlace.SeparateFields().SelectEvery( 4, 0,3 ).Weave()
1007
	match1Update   = (SourceMatch < 1 || MatchTR1 == 0) \
1008
						? Source : mt_lutxy( Source, match1Clip, "x " + string(errorAdjust1 + 1) + " * y " + string(errorAdjust1) + " * -", U=3,V=3 )
1009
	noyv16ma1Edi   = MatchEdi =="NNEDI2" || MatchEdi =="NNEDI" || MatchEdi =="EEDI3+NNEDI3" || MatchEdi =="EEDI3" || MatchEdi =="EEDI2" || MatchEdi =="TDeint" || MatchEdi =="cYadif" || MatchEdi =="RepcYadif"
1010
	noyv16ma2Edi   = MatchEdi2=="NNEDI2" || MatchEdi2=="NNEDI" || MatchEdi2=="EEDI3+NNEDI3" || MatchEdi2=="EEDI3" || MatchEdi2=="EEDI2" || MatchEdi2=="TDeint" || MatchEdi2=="cYadif" || MatchEdi2=="RepcYadif"
1011
	match1Edi      = (SourceMatch == 0) ? NOP() : \
1012
	!noyv16ma1Edi || !yuy2 ? match1Update.QTGMC_Interpolate( InputType, MatchEdi, MatchNNSize, MatchNNeurons, MatchEdiQual, MatchEdiMaxD, EdiThreads ) : \
1013
	                         match1Update.ConvertToYUY2() \
1014
	                                     .QTGMC_Interpolate( InputType, MatchEdi, MatchNNSize, MatchNNeurons, MatchEdiQual, MatchEdiMaxD, EdiThreads ) \
1015
	                                     .ConvertToYv16()
1016
	match1Super    = (SourceMatch > 0 && MatchTR1 > 0) ? match1Edi.MSuper( pel=SubPel, sharp=SubPelInterp, levels=1, hpad=hpad, vpad=vpad ) : NOP()
1017
	match1Degrain1 = (SourceMatch > 0 && MatchTR1 > 0) ? match1Edi.MDegrain1( match1Super, bVec1,fVec1, thSAD=ThSAD1, thSCD1=ThSCD1,thSCD2=ThSCD2, lsb=lsb ) : NOP()
1018
	match1Degrain2 = (SourceMatch > 0 && MatchTR1 > 1) ? match1Edi.MDegrain1( match1Super, bVec2,fVec2, thSAD=ThSAD1, thSCD1=ThSCD1,thSCD2=ThSCD2, lsb=lsb ) : NOP()
1019
	match1Degrain1 = (SourceMatch > 0 && MatchTR1 > 0) && lsb ? match1Degrain1.ditherpost(mode=6, slice=false) : match1Degrain1
1020
	match1Degrain2 = (SourceMatch > 0 && MatchTR1 > 1) && lsb ? match1Degrain2.ditherpost(mode=6, slice=false) : match1Degrain2
1021
	match1         = (SourceMatch < 1) ? Deinterlace : \
1022
	                 (MatchTR1 == 0)   ? match1Edi : \
1023
	                 (MatchTR1 == 1)   ? match1Degrain1.Merge( match1Edi, 0.25 ) : \
1024
	                                     match1Degrain1.Merge( match1Degrain2, 0.2 ).Merge( match1Edi, 0.0625 )
1025
1026
	# Enhance effect of source-match stages 2 & 3 by sharpening clip prior to refinement (source-match tends to underestimate so this will leave result sharper)
1027
	match1Shp = (SourceMatch > 1 && MatchEnhance > 0.0) ? match1.mt_lutxy( match1.RemoveGrain( 12 ), "x x y - "+ string(MatchEnhance) + " * +", U=3,V=3 ) : match1
1028
1029
	# Source-match refinement. Find difference between source clip & equivalent fields in (updated) interpolated/smoothed clip. Interpolate & binomially smooth
1030
	# this difference then add it back to output. Helps restore differences that the basic match missed. However, as this pass works on a difference rather than
1031
	# the source image it can be prone to occasional artefacts (difference images are not ideal for interpolation). In fact a lower quality interpolation such
1032
	# as a simple bob often performs nearly as well as advanced, slower methods (e.g. NNEDI3)
1033
	match2Clip     = (SourceMatch < 2 || InputType == 1) ? match1Shp : match1Shp.SeparateFields().SelectEvery( 4, 0,3 ).Weave()
1034
	match2Diff     = (SourceMatch > 1) ? mt_makediff( Source, match2Clip, U=3,V=3 ) : NOP()
1035
	match2Edi      = (SourceMatch <= 1) ? NOP() : \
1036
	!noyv16ma2Edi || !yuy2 ? match2Diff.QTGMC_Interpolate( InputType, MatchEdi2, MatchNNSize2, MatchNNeurons2, MatchEdiQual2, MatchEdiMaxD2, EdiThreads ) : \
1037
	                         match2Diff.ConvertToYUY2() \
1038
	                                   .QTGMC_Interpolate( InputType, MatchEdi2, MatchNNSize2, MatchNNeurons2, MatchEdiQual2, MatchEdiMaxD2, EdiThreads ) \
1039
	                                   .ConvertToYv16()
1040
	match2Super    = (SourceMatch > 1 && MatchTR2 > 0) ? match2Edi.MSuper( pel=SubPel, sharp=SubPelInterp, levels=1, hpad=hpad, vpad=vpad ) : NOP()
1041
	match2Degrain1 = (SourceMatch > 1 && MatchTR2 > 0) ? match2Edi.MDegrain1( match2Super, bVec1,fVec1, thSAD=ThSAD1, thSCD1=ThSCD1,thSCD2=ThSCD2, lsb=lsb ) : NOP()
1042
	match2Degrain2 = (SourceMatch > 1 && MatchTR2 > 1) ? match2Edi.MDegrain1( match2Super, bVec2,fVec2, thSAD=ThSAD1, thSCD1=ThSCD1,thSCD2=ThSCD2, lsb=lsb ) : NOP()
1043
	match2Degrain1 = (SourceMatch > 1 && MatchTR2 > 0) && lsb ? match2Degrain1.ditherpost(mode=6, slice=false) : match2Degrain1
1044
	match2Degrain2 = (SourceMatch > 1 && MatchTR2 > 1) && lsb ? match2Degrain2.ditherpost(mode=6, slice=false) : match2Degrain2
1045
	match2         = (SourceMatch < 2) ? match1 : \
1046
	                 (MatchTR2 == 0)   ? match2Edi : \
1047
	                 (MatchTR2 == 1)   ? match2Degrain1.Merge( match2Edi, 0.25 ) : \
1048
	                                     match2Degrain1.Merge( match2Degrain2, 0.2 ).Merge( match2Edi, 0.0625 )
1049
1050
	# Source-match second refinement - correct error introduced in the refined difference by temporal smoothing. Similar to error correction from basic step
1051
	errorAdjust2   = Select( MatchTR2, 1.0, 2.0 / (1.0 + errorTemporalSimilarity), 8.0 / (3.0 + 5.0 * errorTemporalSimilarity) )
1052
	match3Update   = (SourceMatch < 3 || MatchTR2 == 0) \
1053
	                     ? match2Edi : mt_lutxy( match2Edi, match2, "x " + string(errorAdjust2 + 1) + " * y " + string(errorAdjust2) + " * -", U=3,V=3 )
1054
	match3Super    = (SourceMatch > 2 && MatchTR2 > 0) ? match3Update.MSuper( pel=SubPel, sharp=SubPelInterp, levels=1, hpad=hpad, vpad=vpad ) : NOP()
1055
	match3Degrain1 = (SourceMatch > 2 && MatchTR2 > 0) ? match3Update.MDegrain1( match3Super, bVec1,fVec1, thSAD=ThSAD1, thSCD1=ThSCD1,thSCD2=ThSCD2, lsb=lsb ) : NOP()
1056
	match3Degrain2 = (SourceMatch > 2 && MatchTR2 > 1) ? match3Update.MDegrain1( match3Super, bVec2,fVec2, thSAD=ThSAD1, thSCD1=ThSCD1,thSCD2=ThSCD2, lsb=lsb ) : NOP()
1057
	match3Degrain1 = (SourceMatch > 2 && MatchTR2 > 0) && lsb ? match3Degrain1.ditherpost(mode=6, slice=false) : match3Degrain1
1058
	match3Degrain2 = (SourceMatch > 2 && MatchTR2 > 1) && lsb ? match3Degrain2.ditherpost(mode=6, slice=false) : match3Degrain2
1059
	match3         = (SourceMatch < 3) ? match2 : \
1060
	                 (MatchTR2 == 0)   ? match3Update : \
1061
	                 (MatchTR2 == 1)   ? match3Degrain1.Merge( match3Update, 0.25 ) : \
1062
	                                     match3Degrain1.Merge( match3Degrain2, 0.2 ).Merge( match3Update, 0.0625 )
1063
1064
	# Apply difference calculated in source-match refinement
1065
	return (SourceMatch < 2) ? match1 : match1Shp.mt_adddiff( match3, U=3,V=3 )
1066
}
1067
1068
1069
# Set global variable called "Prefix_Name" to "Value". Throws exception if global already exists unless Replace=true, in which case the global is overwritten
1070
function QTGMC_SetUserGlobal( string Prefix, string Name, val Value, bool "Replace" )
1071
{
1072
	Replace = default( Replace, false )
1073
	globalName = Prefix + "_" + Name
1074
1075
	# Tricky logic to check global: enter catch block if Replace=true *or* globalName doesn't exist (i.e. need to set the global), the exception is not rethrown
1076
	# Not entering catch block means that Replace=false and global exists - so it throws an exception back to AviSynth
1077
	try { Assert( !Replace && defined(Eval(globalName)) ) }
1078
	catch (e)
1079
	{
1080
		Eval( "global " + globalName + " = Value" )
1081
		Replace = true
1082
	}
1083
	Assert( Replace, """Multiple calls to QTGMC, set PrevGlobals="Replace" or read documentation on 'Multiple QTGMC Calls'""" )
1084
}
1085
1086
# Return value of global variable called "Prefix_Name". Returns NOP() if it doesn't exist or Reuse is false
1087
function QTGMC_GetUserGlobal( string Prefix, string Name, bool "Reuse" )
1088
{
1089
	Reuse = default( Reuse, false )
1090
	globalName = Prefix + "_" + Name
1091
1092
	try       { ret = Reuse ? Eval( globalName ) : NOP() }
1093
	catch (e) { ret = NOP() }
1094
	return ret
1095
}