Advertisement
Guest User

QTGMC for avs 2.60

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