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