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