Advertisement
Guest User

QTGMC 3.33s for avs 2.60

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