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