View Single Post
Old 15th December 2014, 01:19   #7  |  Link
StainlessS
HeartlessS Usurer
 
StainlessS's Avatar
 
Join Date: Dec 2009
Location: Over the rainbow
Posts: 10,980
Post #2 of 2.

RoboLevels.avsi
Code:
Function RoboLevels(clip c,float "Strength",int "Samples",float "Ignore",Bool "ALQBC",Bool "QBC",Float "QBC_Thresh",int "X",int "Y",int "W",int "H", \
    int "Matrix",bool "PC",bool "DEBUG",bool "Laced", Int "WMod",Int "HMod",bool "Show") {
# Samples a number of frames from source clip and using minimum and maximum luma levels from those samples, auto levels clip.
# Default temporarily auto crop borders and samples the area remaining, or if both ALQBC and QBC == false then samples X,Y,W,H coords instead.
# Can optionally return border cropped clip when QBC==true.
#
# Args:
#  Strength, default 0.95 (0.0 -> 1.0). Auto levelling strength.
#  Samples, default 32. Number of frames sampled from source clip c.
#  Ignore, default 0.2 (0.0 -> 100%). Percentage of dark pixels to ignore when ascertaining YPlaneMin, YPlaneMax (noise).
#  ALQBC, default=true. Use temp auto cropped clip coords for auto levels sampling.
#  QBC, default false. If true then returns border cropped clip else non cropped.
#  QBC_Thresh, default -32.0. Threshold used for border detection. See RT_QueryBorderCrop.
#     NOTE, RT_QueryBorderCrop 'massages' DEFAULT THRESH (exactly -32.0) if low samples count or if short clip. Reason being to avoid
#     overcropping when insufficient data available for reliable cropping. It is considered better to not crop enough or at all, than
#     to overcrop. You can override by simply setting an explicit threshold (+ve) of eg 40.0, or setting a NON-DEFAULT auto thresh (-ve)
#     eg -16.0 or -32.1, where YPlaneMin is established for the sampled frames and then abs(thresh) is added to that value which is
#     then used as an explicit thresh.
#  X,Y,W,H. All default 0, ie full frame. Coords for luma sampling, only used if both ALQBC and QBC are both false.
#  Matrix default= 2(PC601) if clip width<720 else 3(PC709).
#     Conversion matrix for conversion of RGB to YUV-Y Luma.  0=REC601 : 1=REC709 : 2 = PC601 : 3 = PC709:  YUV not used
#     DO NOT USE Matrix of 0 or 1.
#  PC default = false. If YUV and PC == true then auto level PC Levels 0->255 instead of TV levels 16->235. RGB always 0->255
#  Debug default false. If true then send info the DebugView.
#    Recommended, DebugView: http://technet.microsoft.com/en-gb/sysinternals/bb545027
#  Laced, default = true. Alters Interlaced default for HMod, HMod doubled if true.
#  WMod, default = the natural cropping WMod for clip c colorspace (eg 2 for YV12 and YUY2, 1 for RGB).
#  HMod, default = the natural cropping HMod for clip c colorspace (eg 2 for YV12 and 1 for YUY2 and RGB), but doubled if Laced==true.
#    NOTE, WMod, HMod, If overridden must all be multiples of natural cropping WMod and HMod for clip c colorspace.
#    NOTE, VirtualDubMod and some players, may not like any colorspace WMOD less than 4 (Vdub latest, OK).
#    NOTE, If eg VDMod show blank frame, OR eg player halts saying eg "No combination of filters cound be found to render frame"
#    then set WMod to a multiple of 4. We do not do this by default as Current VDub and some player/encoders may work just fine.
#    If you dont care about possibility of losing a couple of pixels then always supply WMod=4 to avoid display problems.
#  Show, default false. If true, shows Levels() used on frame.
#
    myName="RoboLevels: "
    c
    Frames=FrameCount
    Strength=Float(Default(Strength,0.95))
    Samples=(!Defined(Samples)) ? 32 : (Samples > Frames) ? Frames : (Samples < 1) ? 1 : Samples
    Ignore=Float(Default(Ignore,0.2))
    ALQBC=Default(ALQBC,True)
    QBC=Default(QBC,False)
    QBC_Thresh=Float(Default(QBC_Thresh,-32.0))
    Default(Matrix,(width > 1100 || height > 600) ? 3 : 2) # Default to PC levels
    PC=Default(PC,False)
    DEBUG=Default(DEBUG,False)
    SHOW=Default(Show,false)
    QBCropXP = Default(X,0) QBCropYP = Default(Y,0) QBCropWP = Default(W,0) QBCropHP = Default(H,0) # prep
    Assert(Strength>=0.0 && Strength <=1.0, myName + "0.0 <= Strength <= 1.0")
    GScript("""
        if(ALQBC || QBC) {
            QBCS=RT_QueryBorderCrop(samples=Samples,thresh=QBC_Thresh,debug=DEBUG,ignore=Ignore,matrix=Matrix,laced=laced,wmod=WMod,hmod=HMod)
            Eval(QBCS)
        }
        QLMMS=RT_QueryLumaMinMax(c,samples=Samples,ignore=Ignore,x=QBCropXP,y=QBCropYP,W=QBCropWP,H=QBCropHP,debug=DEBUG,matrix=Matrix)
        Eval(QLMMS)
        if(IsRGB() || PC) {
            CSMin = 0
            CSMax = 255
        } else {
            CSMin = 16
            CSMax = 235
        }
        ALMin = Int(CSMin - ((CSMin - QLMMMin) * Strength) + 0.5)   # Round Up
        ALMax = Int(CSMax - ((CSMax - QLMMMax) * Strength))         # Round down
        if(QBC) {
            CropS="Crop("+String(QBCropXM)+","+String(QBCropYM)+","+String(QBCropWM)+","+String(QBCropHM)+")"
            (DEBUG)?RT_DebugF(CropS,name=myName):NOP
            Crop(QBCropXM,QBCropYM,QBCropWM,QBCropHM)
            (SHOW) ?RT_SubTitle(CropS,y=20):NOP                     # NOTE, After Cropping
        }
        LevelsS=RT_String("Levels(%d,%f,%d,%d,%d,coring=false)",ALMin,G_GAMMA,AlMax,CSMin,CSMax)
        (DEBUG)? RT_DebugF(LevelsS,name=myName):NOP
        (SHOW) ? RT_Subtitle(LevelsS,y=0):NOP
        Levels(ALMin,G_GAMMA,ALMax,CSMin,CSMax,Coring=False) # DO NOT use Coring
    """)
    return Last
}
RoboSplice.avsi
Code:
Function IsClose(Float a, Float b, Float threshold) {
    threshold=Abs(threshold)
    return ((abs(a-b)+threshold) <= threshold*2.0)
}

Function ConvRates(clip c,int "num",int "den",Bool "InterFrame",int "Channels",int "SampleRate",int "Bits",bool "Norm") {
    myName="ConvRates: "
    c
    GScript("""
        if((!Defined(num) || !Defined(den)) || (num==0 || den==0)) {num = 0 den = 0}
        InterFrame=Default(Interframe,false)
        Channels=Default(Channels,AudioChannels)
        SampleRate=Default(SampleRate,AudioRate)
        Bits=Default(bits,AudioBits)
        Norm=Default(Norm,True)     
        if(num == FrameRateNumerator && den == FrameRateDenominator) {
            RT_DebugF("Using Original FrameRate %.3f",FrameRate,name=myName)        
        } else {
            if(num==0 || den == 0) {
                FPS = FrameRate             
                if      (isClose(FPS,29.97,0.015))  {num=30000 den = 1001}
                else if (isClose(FPS,23.976,0.012)) {num=24000 den = 1001}
                else if (isClose(FPS,11.988,0.006)) {num=12000 den = 1001}
                else if (isClose(FPS,30.0,0.5))     {num=30 den = 1}
                else if (isClose(FPS,25.0,0.5))     {num=25 den = 1}
                else if (isClose(FPS,24.0,0.5))     {num=24 den = 1}
                else if (isClose(FPS,18.0,0.5))     {num=18 den = 1}
                else if (isClose(FPS,15.0,0.5))     {num=15 den = 1}
                else if (isClose(FPS,12.5,0.5))     {num=25 den = 2}
                else if (isClose(FPS,12.0,0.5))     {num=12 den = 1}
                else    {num=FrameRateNumerator den = FrameRateDenominator}
            }
            if(isClose(Float(num) / Float(den),FrameRate,1.0)) {
                AssumeFPS(num,den,sync_audio=true)
                RT_DebugF("Assuming FrameRate %.3f",FrameRate,name=myName)
            } else {
                if(Interframe) {
                    RT_DebugF("Interframe: Converting FrameRate to %.3f",Float(num) / Float(den),name=myName)
                    Interframe(NewNum=num,NewDen=den,cores=1)
                } Else {
                    RT_DebugF("MVTools: Converting FrameRate to %.3f",Float(num) / Float(den),name=myName)
                    if(False) {
                        super=MSuper(pel=1)
                        bvec=MAnalyse(super, isb=true, blksize=16)
                        fvec=MAnalyse(super, isb=false, blksize=16)
                        MBlockFps(super, bvec, fvec, num=num,den=den, mode=3)           
                    } else {
                        super=MSuper(pel=1, hpad=0, vpad=0)
                        backward_1=MAnalyse(super, chroma=false, isb=true,  blksize=16, blksizev=16, searchparam=3, plevel=0, search=3, badrange=(-24))
                        forward_1 =MAnalyse(super, chroma=false, isb=false, blksize=16, blksizev=16, searchparam=3, plevel=0, search=3, badrange=(-24))
                        backward_2 = MRecalculate(super, chroma=false, backward_1, blksize=8, blksizev=8, searchparam=0, search=3)
                        forward_2  = MRecalculate(super, chroma=false, forward_1,  blksize=8, blksizev=8, searchparam=0, search=3)
                        MBlockFps(super, backward_2, forward_2, num=num, den=den, mode=0)
                    }
                }
            }       
        }
        IsSilent=false
        if(!HasAudio) {
            RT_DebugF("Adding Silent Audio",name=myName)
            Aud=Last.Blankclip(audio_rate=SampleRate,channels=Channels)
            IsSilent=true
            Audiodub(Aud)
        }
        if(HasAudio) {
            if(Channels == 0 && AudioChannels > 0) {
                KillAudio()
                RT_DebugF("Killing Audio",name=myName)
            } else if(Channels == 1 && AudioChannels > 1) {
                ConvertToMono()     
                RT_DebugF("Converting To MONO",name=myName)
            } else if(Channels == 2 && AudioChannels ==1) {
                AudioDub(Last,MergeChannels(GetChannel(1),GetChannel(1)))
                RT_DebugF("Converting To DUEL Channel MONO",name=myName)
            }
            if(HasAudio() && Bits != AudioBits) {
                if(bits==8)       { ConvertAudioTo8bit() }
                else if(bits==16) { ConvertAudioTo16bit() }
                else if(bits==24) { ConvertAudioTo24bit() }
                else if(bits==32) { ConvertAudioTo32bit() }
            }
            if(HasAudio() && SampleRate != AudioRate) {ResampleAudio(SampleRate) }
            if(HasAudio() && Norm && !IsSilent) {
                Normalize(0.98)
                RT_DebugF("NORMALIZING AUDIO",name=myName)
            }
        }           
    """)
    Return Trim(0,0)
}

Function DoTrim(clip c) {
    myName="DoTrim: "
    c
    GScript("""
        W=Width % 8 H=Height % 8
        Addborders(0,0,W==0?0:8-W,H==0?0:8-h).ConvertToYV12()
        if(G_DEBLOCK!=0) {
            RT_DebugF("DEBLOCK(%d)",G_DEBLOCK,name=myName)
            Deblock(G_DEBLOCK)
        }
        if(G_RPOW2 ||((G_DISPWID>0 && G_DISPWID>Int(Width*Sqrt(2.0)))  ||  (G_DISPHIT>0 && G_DISPHIT>Int(Height*Sqrt(2.0))))) {
            RT_DebugF("RPOW2",name=myName)
            NNedi3_Rpow2(2)
        }
        if(G_QBC==true || G_SAMPLES!=0 || G_AL_STRENGTH>0.0 || G_AUTOGAIN) {
            RT_DebugF("Calling RoboLevels",name=myName)
            RoboLevels(Strength=G_AL_STRENGTH,samples=G_SAMPLES,qbc=G_QBC,QBC_Thresh=G_QBC_THRESH,DEBUG=G_DEBUG,Laced=G_INTERLACED,WMod=4,HMod=4)
            if(G_AUTOGAIN) {
                RT_DebugF("AutoGain",name=myName)
                TMPW=Int(Width /4)*4                                        # Mod 4 for AutoGain
                TMPH=Int(Height/4)*4                                        # Mod 4 for AutoGain
                TMP=Crop(0,0,TMPW,TMPH,align=True)
                AutoGain(Last,TMP)
            }
        }
        if(G_MCD==0) {
            if(G_SIGMA!=0.0 || G_SHARPEN!=0.0) {
                RT_DebugF("FFT3DFilter(Sigma=%f,Sharpen=%f)",G_SIGMA,G_SHARPEN,name=myName)
                FFT3DFilter(Sigma=G_SIGMA,Sharpen=G_SHARPEN)
            }
        } else {
            RT_DebugF("MCDeGrain(%d)",G_MCD,name=myName)
            MCDEGRAIN(G_MCD)
        }
        if(G_DISPWID!=Width || G_DISPHIT != Height) {
            if(G_DISPWID==0 || G_DISPHIT == 0) {
                WW=(Width  + (4-1)) / 4 * 4
                HH=(Height + (4-1)) / 4 * 4
                Global G_DISPWID = WW
                Global G_DISPHIT = HH
                if(WW==Width && HH==Height) {
                    RT_DebugF("Using Original SIZE %d %d",G_DISPWID,G_DISPHIT,name=myName)
                } else {
                    RT_DebugF("Resizing MOD 4, %dx%d",G_DISPWID,G_DISPHIT)
                    Spline36Resize(G_DISPWID,G_DISPHIT)
                }
            } else {
                RT_DebugF("Resizing to match previous clip %dx%d",G_DISPWID,G_DISPHIT)
                Spline36Resize(G_DISPWID,G_DISPHIT)
            }
        }
        ConvRates(num=G_FRNUM,den=G_FRDEN,Interframe=G_USE_INTERFRAME,Channels=G_CHANNELS,SampleRate=G_SAMPLERATE,Bits=G_BITS,norm=G_NORMALIZE)
        Global G_FRNUM = FrameRateNumerator
        Global G_FRDEN = FrameRateDenominator
        Global G_CHANNELS = AudioChannels
        Global G_SAMPLERATE = AudioRate
        Global G_BITS = AudioBits       
        if(G_MCD!=0) {
            if(G_SIGMA!=0.0 || G_SHARPEN!=0.0) {
                RT_DebugF("FFT3DFilter(Sigma=%f,Sharpen=%f)",G_SIGMA,G_SHARPEN,name=myName)
                FFT3DFilter(Sigma=G_SIGMA,Sharpen=G_SHARPEN)
            }
        }
        if(G_ASPECT_DARX>0 && G_ASPECT_DARY>0) {
            RT_DebugF("SignalDAR2(%d,%d)",G_ASPECT_DARX,G_ASPECT_DARY,name=myName)
            RT_SignalDar2(G_ASPECT_DARX,G_ASPECT_DARY)
        }
    """)
    ConvertToYV12()
}


Function GetTrim(string s) {
    Return GetFile(s).DoTrim()
}
Template given can be used on lone source or for concatenating multiple sources.
__________________
I sometimes post sober.
StainlessS@MediaFire ::: AND/OR ::: StainlessS@SendSpace

"Some infinities are bigger than other infinities", but how many of them are infinitely bigger ???

Last edited by StainlessS; 15th December 2014 at 02:07.
StainlessS is offline   Reply With Quote