├── .env.zvs.global ├── vsenv.py ├── README.md ├── joke01.py ├── XcQ └── scene_detect.py ├── LICENSE └── zvs.py /.env.zvs.global: -------------------------------------------------------------------------------- 1 | nnrs_mode_default=nnedi3cl 2 | #The default mode to use for Nnedi3_Resample 3 | 4 | bm3d_mode_default=cuda 5 | #The default mode to use for BM3D 6 | 7 | bm3d_extractor_exp_default=0 8 | 9 | -------------------------------------------------------------------------------- /vsenv.py: -------------------------------------------------------------------------------- 1 | import vapoursynth as vs 2 | core=vs.core 3 | core.num_threads/=2 4 | import xvs,zvs #love 5 | from zvs import nnrs #so i can use my default 6 | import mvsfunc as mvf 7 | import havsfunc as haf 8 | import muvsfunc as muf 9 | import vsTAAmbk as taa 10 | import joke01 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # z-vsPyScripts 2 | 3 | Z's weird vapoursynth python script(s) 4 | 5 | ## Usage 6 | 7 | ### zvs 8 | 9 | `import zvs` 10 | 11 | ### .env.zvs(.global) 12 | 13 | NOT necessary. Will fall back to default values if it can't be found. 14 | The global one resides alongside the main script file zvs.py, and a local one can override global values, you should place it somewhere can be found by python-dotenv, like your project root folder.(that means follow the python-dotenv documents there, yes I'm lazy) 15 | 16 | ### vsenv 17 | 18 | ``` 19 | from vsenv import * 20 | core.num_threads=nn 21 | core.max_cache_size=xxx #change these values can work inside vsenv.py but like if you preview in vsedit it only works for first time so not very well... but other than that i think it's viable 22 | ``` 23 | 24 | ### scene_detect 25 | 26 | 27 | it's recommended to uninstall any other variant/flavor/EP of onnxruntime before you install your desired ort version/package 28 | `pip uninstall onnxruntime[-xxx]` 29 | `pip install onnxruntime-directml` or what ever but i recommend dml for windows 30 | 31 | ``` 32 | import scene_detect as scd 33 | clip=scd.scene_detect(clip[,onnx_path=,thresh=0.92,ort_provider='Dml' et cetera et cetera ]) 34 | ``` 35 | 36 | ## Requirements (for zvs) 37 | 38 | ### python packages 39 | 40 | - [mvsfunc](https://github.com/HomeOfVapourSynthEvolution/mvsfunc) 41 | - [numpy](https://pypi.org/project/numpy/)(optional) 42 | - [opencv-python](https://pypi.org/project/opencv-python/)(optional) 43 | - [PyWavelets](https://pypi.org/project/PyWavelets/)(optional) 44 | - [scipy](https://pypi.org/project/scipy/)(optional) 45 | - [python-dotenv](https://pypi.org/project/python-dotenv/)(optional) 46 | 47 | ### python scripts 48 | 49 | - [nnedi3_resample](https://github.com/HomeOfVapourSynthEvolution/nnedi3_resample) 50 | - [xvs](https://github.com/xyx98/my-vapoursynth-script) 51 | - [finesharp](https://gist.github.com/4re/8676fd350d4b5b223ab9)(optional) 52 | - [muvsfunc](https://github.com/WolframRhodium/muvsfunc)(optional but required by xvs) 53 | 54 | ### plugins (most of which should be optional when not using related function and this list is probably incomplete) 55 | 56 | - [BM3DCUDA](https://github.com/WolframRhodium/VapourSynth-BM3DCUDA)/CPU 57 | - [BM3D](https://github.com/HomeOfVapourSynthEvolution/VapourSynth-BM3D) (only VAggregate is used for not-v2 bm3dcuda/cpu) 58 | - *[FFTW3](http://www.fftw.org/install/windows.html)* (dependency of some plugins such as the one above) 59 | - [mvtools](https://github.com/dubhater/vapoursynth-mvtools) ([my build](https://github.com/Mr-Z-2697/vapoursynth-mvtools/releases) is also available, clang produces faster binary in this case) 60 | - [descale](https://github.com/Jaded-Encoding-Thaumaturgy/vapoursynth-descale) 61 | - [nnedi3cl](https://github.com/HomeOfVapourSynthEvolution/VapourSynth-NNEDI3CL)/[znedi3](https://github.com/sekrit-twc/znedi3)/[nnedi3](https://github.com/dubhater/vapoursynth-nnedi3) 62 | - [fmtconv](https://gitlab.com/EleonoreMizo/fmtconv) 63 | - [neo_f3kdb](https://github.com/HomeOfAviSynthPlusEvolution/neo_f3kdb)/[f3kdb](https://github.com/SAPikachu/flash3kyuu_deband) 64 | - [tcanny](https://github.com/HomeOfVapourSynthEvolution/VapourSynth-TCanny) 65 | - [akarin](https://github.com/AkarinVS/vapoursynth-plugin) 66 | - [edgefixer](https://github.com/sekrit-twc/EdgeFixer) 67 | - [KNLMeansCL](https://github.com/pinterf/KNLMeansCL) 68 | - [nlm-cuda](https://github.com/AmusementClub/vs-nlm-cuda) 69 | - [bilateral](https://github.com/HomeOfVapourSynthEvolution/VapourSynth-Bilateral) 70 | - [cas](https://github.com/HomeOfVapourSynthEvolution/VapourSynth-CAS) 71 | - [vs-removegrain](https://github.com/vapoursynth/vs-removegrain) 72 | - [ctmf](https://github.com/HomeOfVapourSynthEvolution/VapourSynth-CTMF) 73 | - [DualSynth-madVR](https://github.com/Jaded-Encoding-Thaumaturgy/DualSynth-madVR) (and madVR itself of course) 74 | -------------------------------------------------------------------------------- /joke01.py: -------------------------------------------------------------------------------- 1 | import vapoursynth as vs 2 | core=vs.core 3 | import zvs 4 | __all__=['lrnoise','debit','naive32k','naive32i'] 5 | 6 | def lrnoise(src,lr=(1280,720),gy=50,gc=0,hc=0,vc=0,con=0,seed=1,opt=0,a1=20,adg=False,mdg=False,azmdg={},cdif=False,fnoise=None,avg=[]): 7 | src=zvs.simplebitdepth(src,16) 8 | za={'thsad':1000,'truemotion':True} 9 | za.update(azmdg) 10 | last=src 11 | lr=last.fmtc.resample(lr[0],lr[1]) 12 | if callable(fnoise): 13 | lrn=fnoise(lr) 14 | else: 15 | lrn=core.grain.Add(lr,var=gy,uvar=gc,hcorr=hc,vcorr=vc,constant=con,seed=seed,opt=opt) 16 | if adg: 17 | lr=lr.std.PlaneStats() 18 | lrm=lr.adg.Mask(adg) 19 | lrn=core.std.MaskedMerge(lr,lrn,lrm) 20 | if mdg: mvd=zvs.zmdg(lr,mvout=True,**za) 21 | if cdif: 22 | nd=zvs.cdif(lrn,lr) 23 | else: 24 | nd=core.std.MakeDiff(lrn,lr) 25 | if mdg: nd=zvs.zmdg(nd,mvin=mvd,**za) 26 | if avg: nd=nd.std.AverageFrames(avg) 27 | ndhr=nd.fmtc.resample(last.width,last.height,kernel='gaussian',a1=a1) 28 | if cdif: 29 | last=zvs.cdif(last,ndhr,1) 30 | else: 31 | last=core.std.MergeDiff(last,ndhr) 32 | return last 33 | 34 | # i know mvf.Depth can do just want a simpler approach 35 | # is it still the depth we want if chroma sign is considered? what about the range of values? 36 | # brain cells are dying 37 | # cs: consider chroma sign 38 | # cs2: is a free upgrade to CS:GO 39 | # cs2: half the scaling for +-0.5 range 40 | def debit(src,depth=1,dither=0,fulls=None,fulld=None,cs=None,cs2=None,count=None): 41 | if depth>=8 or (count!=None and count>=256): 42 | raise ValueError("use normal dither for >8bit bro") 43 | isrgb=src.format.color_family==vs.RGB 44 | isgray=src.format.color_family==vs.GRAY 45 | if fulls==None: fulls=True if isrgb else False 46 | if fulld==None: fulld=True if isrgb else False 47 | if cs==None: cs=False if isrgb or isgray else True 48 | if cs2==None: cs2=False 49 | if src.format.sample_type==vs.FLOAT: 50 | src=core.resize.Point(src,format=src.format.replace(sample_type=vs.INTEGER,bits_per_sample=16),range_s='full') 51 | fulls=True 52 | if src.format.bits_per_sample < 16: 53 | src=zvs.simplebitdepth(src,16) 54 | if isinstance(dither,int): 55 | rehtid=lambda x:x.fmtc.bitdepth(bits=8,dmode=dither) 56 | elif isinstance(dither,str): 57 | rehtid=lambda x:zvs.simplebitdepth(x,8,dither) 58 | elif callable(dither): 59 | rehtid=dither 60 | if count==None: 61 | count=2**depth 62 | scaling=255/(count-1) 63 | scalingc=scaling if not cs2 else scaling/2 64 | cs=(cs or cs2) and not isgray 65 | last=src 66 | if not fulls: 67 | last=zvs.setrange(last,'rm') 68 | last=last.resize.Point(range_in_s='limited',range_s='full') 69 | if cs: 70 | last=last.std.Expr([f'x {scaling} /',f'x 32768 - {scalingc} / 32768 +']) 71 | else: 72 | last=last.std.Expr(f'x {scaling} /') 73 | last=rehtid(last) 74 | if cs: 75 | last=last.std.Expr([f'x {scaling} *',f'x 128 - {scalingc} * 128 +']) 76 | else: 77 | last=last.std.Expr(f'x {scaling} *') 78 | if not fulld: 79 | last=zvs.setrange(last,'rm') 80 | last=last.resize.Point(range_in_s='full',range_s='limited') 81 | return last 82 | 83 | def naive32k(src,shift=0): 84 | clip=core.std.SeparateFields(src,tff=1) 85 | _tf=clip[::2] 86 | _bf=clip[1::2] 87 | match shift: 88 | case 0: 89 | selector_tf=[0,1,1,2,3] #1 90 | selector_bf=[0,1,2,3,3] #3 91 | case 1: 92 | selector_tf=[0,1,2,2,3] #2 93 | selector_bf=[0,0,1,2,3] #0 94 | case 2: 95 | selector_tf=[0,1,2,3,3] #3 96 | selector_bf=[0,1,1,2,3] #1 97 | case 3: 98 | selector_tf=[0,0,1,2,3] #0 99 | selector_bf=[0,1,2,2,3] #2 100 | _tf=_tf.std.SelectEvery(4,selector_tf) 101 | _bf=_bf.std.SelectEvery(4,selector_bf) 102 | clip=core.std.Interleave([_tf,_bf]) 103 | clip=core.std.DoubleWeave(clip)[::2] 104 | clip=clip.std.SetFieldBased(2) 105 | return clip 106 | 107 | def naive32i(src,shift=0): 108 | clip=core.std.SeparateFields(src,tff=1) 109 | _tf=clip[::2] 110 | _bf=clip[1::2] 111 | match shift: 112 | case 0: 113 | selector_tf=[0,1,3,4] #2 114 | selector_bf=[0,1,2,3] #4 115 | case 1: 116 | selector_tf=[0,1,2,4] #3 117 | selector_bf=[1,2,3,4] #0 118 | case 2: 119 | selector_tf=[0,1,2,3] #4 120 | selector_bf=[0,2,3,4] #1 121 | case 3: 122 | selector_tf=[1,2,3,4] #0 123 | selector_bf=[0,1,3,4] #2 124 | case 4: 125 | selector_tf=[0,2,3,4] #1 126 | selector_bf=[0,1,2,4] #3 127 | _tf=_tf.std.SelectEvery(5,selector_tf) 128 | _bf=_bf.std.SelectEvery(5,selector_bf) 129 | clip=core.std.Interleave([_tf,_bf]) 130 | clip=core.std.DoubleWeave(clip)[::2] 131 | clip=clip.std.SetFieldBased(0) 132 | return clip 133 | 134 | # the grey from black and white 135 | # prepare your frame props btw, im relying on auto selection of core.resize 136 | def grey(src,fp32=1,matrix='601',linearize=1): 137 | if src.format.color_family==vs.GRAY: 138 | return src 139 | elif src.format.color_family==vs.YUV: 140 | clip=core.resize.Spline64(src,format=vs.RGBS if fp32 else vs.RGB48) 141 | else: 142 | clip=zvs.sb(src,32 if fp32 else 16) 143 | if isinstance(matrix,int) and matrix>=0 and matrix<256: 144 | matrixval=matrix 145 | else: 146 | matrixvaldict={'rgb':0,'709':1,'fcc':4,'470bg':5,'170m':6,'240m':7,'ycgco':8,'2020ncl':9,'2020cl':10,'ydzdx':11,'601':5,709:1,601:5} 147 | matrixval=matrixvaldict.get(matrix) 148 | if matrixval==None: raise ValueError 149 | if linearize: clip=core.resize.Point(clip,transfer_s='linear') 150 | if matrixval==11: 151 | clip=core.fmtc.matrix(clip,mats='rgb',matd='ydzdx') 152 | clip=core.std.ShufflePlanes(clip,0,vs.GRAY) 153 | clip=zvs.setmatrix(clip,1) 154 | else: 155 | clip=core.resize.Point(clip,format=vs.GRAYS if fp32 else vs.GRAY16,matrix=matrixval) 156 | if linearize: clip=core.resize.Point(clip,transfer=src.get_frame(0).props._Transfer) 157 | return clip 158 | 159 | # "lens blur" 160 | def lamb(clip,radius=10,shape=None,ss=True,partial=False,y5g=0): 161 | import math 162 | if shape: 163 | import shapely 164 | p=shapely.Polygon(shape) 165 | n=33 #acts like an upper limit 166 | o=int(n/2) 167 | def meow(sx=1,sy=1): #this is what lambs sound like 168 | w=0 169 | c=0 170 | e='' 171 | for i in range(n): 172 | for j in range(n): 173 | x=j-o 174 | y=i-o 175 | xs=x*sx 176 | ys=y*sy 177 | if shape: 178 | pt=shapely.Point(xs,ys) 179 | if pt.within(p) or pt.touches(p): 180 | e+=f" x[{x},{y}]" 181 | w+=1 182 | c+=1 183 | else: 184 | if (xs*xs)+(ys*ys) <= radius**2: 185 | e+=f" x[{x},{y}]" 186 | w+=1 187 | c+=1 188 | elif partial: 189 | xm=math.copysign(abs(xs)-sx,xs) 190 | ym=math.copysign(abs(ys)-sy,ys) 191 | if (xm*xm)+(ym*ym) <= radius**2: 192 | d=radius-(xm*xm+ym*ym)**.5 193 | r=d/(sx*sx+sy*sy)**.5 #approximation 194 | r=r*r 195 | if r>0.01: 196 | e+=f" x[{x},{y}] {r} *" 197 | w+=r 198 | c+=1 199 | e+=" +" * (c-1) 200 | e+=f" {w} /" 201 | return e 202 | if clip.format.color_family==vs.YUV and ss: 203 | if y5g: 204 | return core.llvmexpr.Expr(clip,[meow(),meow(2**clip.format.subsampling_w,2**clip.format.subsampling_h)],opt_level=1) 205 | else: 206 | return core.akarin.Expr(clip,[meow(),meow(2**clip.format.subsampling_w,2**clip.format.subsampling_h)]) 207 | else: 208 | if y5g: 209 | return core.llvmexpr.Expr(clip,meow(),opt_level=1) 210 | else: 211 | return core.akarin.Expr(clip,meow()) 212 | -------------------------------------------------------------------------------- /XcQ/scene_detect.py: -------------------------------------------------------------------------------- 1 | '''https://github.com/styler00dollar/VSGAN-tensorrt-docker/blob/main/src/scene_detect.py 2 | Model Download: https://github.com/styler00dollar/VSGAN-tensorrt-docker/releases/tag/models 3 | (look for onnx models start with "sc_") 4 | 5 | USAGE: 6 | import scene_detect as scd 7 | clip=scd.scene_detect(clip,[model path, [other parameters]]) 8 | 9 | BSD 3-Clause License 10 | 11 | Copyright (c) 2022, styler00dollar aka sudo rm -rf / --no-preserve-root 12 | All rights reserved. 13 | 14 | Redistribution and use in source and binary forms, with or without 15 | modification, are permitted provided that the following conditions are met: 16 | 17 | 1. Redistributions of source code must retain the above copyright notice, this 18 | list of conditions and the following disclaimer. 19 | 20 | 2. Redistributions in binary form must reproduce the above copyright notice, 21 | this list of conditions and the following disclaimer in the documentation 22 | and/or other materials provided with the distribution. 23 | 24 | 3. Neither the name of the copyright holder nor the names of its 25 | contributors may be used to endorse or promote products derived from 26 | this software without specific prior written permission. 27 | 28 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 29 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 30 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 31 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 32 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 33 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 34 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 35 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 36 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 37 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.''' 38 | 39 | import os 40 | import numpy as np 41 | import vapoursynth as vs 42 | import functools 43 | import onnxruntime as ort 44 | from threading import Lock 45 | core = vs.core 46 | 47 | def scene_detect( 48 | clip: vs.VideoNode, 49 | onnx_path: str = r"D:\Misc\scd-models\maxxvitv2_nano_rw_256.sw_in1k_256px_b100_30k_coloraug0.4_6ch_clamp_softmax_fp16_op17_onnxslim.onnx", 50 | thresh: float = 0.92, 51 | fp16=None, 52 | onnx_res=None, 53 | onnx_type=None, 54 | ort_provider='Dml', 55 | resizer=None, 56 | model_rev=None, 57 | output_type=None, 58 | ssim_clip=None, 59 | ssim_thresh=0.98, 60 | num_sessions=1, 61 | ort_log_level=3, 62 | return_clip=None, 63 | ) -> vs.VideoNode: 64 | 65 | if not isinstance(return_clip,vs.VideoNode): 66 | return_clip=clip 67 | 68 | ort.set_default_logger_severity(ort_log_level) 69 | 70 | onnx_name=os.path.split(onnx_path)[-1] 71 | onnx_name=os.path.splitext(onnx_name)[0] 72 | onnx_name_split=onnx_name.split('_') 73 | 74 | if fp16 is None: 75 | if 'fp16' in onnx_name_split: 76 | fp16=True 77 | else: 78 | fp16=False 79 | 80 | if onnx_res is None: 81 | if '256' in onnx_name_split or '256px' in onnx_name_split: 82 | onnx_res=[256,256] 83 | elif '224' in onnx_name_split or '224px' in onnx_name_split: 84 | onnx_res=[224,224] 85 | elif 'autoshot' in onnx_name_split or '48x27' in onnx_name_split: 86 | onnx_res=[48,27] 87 | elif isinstance(onnx_res,int): 88 | onnx_res=[onnx_res,onnx_res] 89 | 90 | if onnx_type is None: 91 | if 'autoshot' in onnx_name_split or '5img' in onnx_name_split: 92 | onnx_type='5img' 93 | else: 94 | onnx_type='2img' 95 | 96 | if model_rev is None: 97 | if 'softmaxOut' in onnx_name_split: 98 | model_rev=1 99 | else: 100 | model_rev=2 101 | 102 | if output_type is None: 103 | if 'dists' in onnx_name_split: 104 | output_type=2 105 | else: 106 | output_type=1 107 | 108 | options = {} 109 | ''' 110 | I can't test these options because I can't get TRT provider to work in my Windows system. 111 | The "trt_engine_cache_path" looks definitely gonna cause some trouble (in Windows, perhaps Linux as well, as the upstream is intended for docker). 112 | ''' 113 | if ort_provider=='Tensorrt': 114 | # https://onnxruntime.ai/docs/execution-providers/TensorRT-ExecutionProvider.html 115 | options["device_id"] = 0 116 | options["trt_engine_cache_enable"] = True 117 | options["trt_timing_cache_enable"] = ( 118 | True # Using TensorRT timing cache to accelerate engine build time on a device with the same compute capability 119 | ) 120 | options["trt_engine_cache_path"] = ( 121 | "/workspace/tensorrt/" 122 | ) 123 | options["trt_fp16_enable"] = fp16 124 | options["trt_max_workspace_size"] = 7000000000 # ~7gb 125 | options["trt_builder_optimization_level"] = 5 126 | 127 | sessions = [ 128 | ort.InferenceSession( 129 | onnx_path, 130 | providers=[(f"{ort_provider}ExecutionProvider",options)], 131 | ) 132 | for _ in range(num_sessions) 133 | ] 134 | sessions_lock = [Lock() for _ in range(num_sessions)] 135 | 136 | index=-1 137 | index_lock=Lock() 138 | 139 | def execute(n,f): 140 | nonlocal index 141 | with index_lock: 142 | index = (index + 1) % num_sessions 143 | local_index = index 144 | nonlocal ssim_clip 145 | nonlocal ssim_thresh 146 | if ssim_clip: 147 | ssim_eval = f[3].props.get("float_ssim") 148 | if ssim_clip and ssim_eval > ssim_thresh: 149 | return f[0].copy() 150 | fout=f[0].copy() 151 | I0 = frame_to_tensor(f[1]) 152 | I1 = frame_to_tensor(f[2]) 153 | ort_session = sessions[local_index] 154 | if model_rev==1: 155 | I0 = np.expand_dims(I0, 0) 156 | I1 = np.expand_dims(I1, 0) 157 | in_sess = np.concatenate([I0, I1], axis=1) 158 | result = ort_session.run(None, {"input": in_sess})[0] 159 | elif model_rev==2: 160 | if onnx_type=='2img': 161 | in_sess = np.concatenate([I0, I1], axis=0) 162 | elif onnx_type=='5img': 163 | I2 = frame_to_tensor(f[3]) 164 | I3 = frame_to_tensor(f[4]) 165 | I4 = frame_to_tensor(f[5]) 166 | in_sess = np.stack([I0, I1, I2, I3, I4], axis=1) 167 | if output_type==2: 168 | result=ort_session.run(None, {"input": in_sess})[0] 169 | else: 170 | result = ort_session.run(None, {"input": in_sess})[0][0] 171 | if onnx_type=='2img': 172 | result=result[0] 173 | elif onnx_type=='5img': 174 | result=result[2] 175 | 176 | if result > thresh: 177 | fout.props._SceneChangeNext=1 178 | else: 179 | fout.props._SceneChangeNext=0 180 | fout.props._SceneChangeMetrics=float(result) 181 | return fout 182 | 183 | clip_down=prepare_clip(clip,onnx_res=onnx_res,fp16=fp16,resizer=resizer) 184 | if onnx_type == "5img": 185 | shift_up2 = clip_down.std.DeleteFrames(frames=[0, 1]) + core.std.BlankClip( 186 | clip_down, length=2 187 | ) 188 | shift_up1 = clip_down.std.DeleteFrames(frames=[0]) + core.std.BlankClip( 189 | clip_down, length=1 190 | ) 191 | 192 | shift_down1 = core.std.BlankClip(clip_down, length=1) + core.std.BlankClip( 193 | clip_down, length=1 194 | ) 195 | shift_down2 = core.std.BlankClip(clip_down, length=2) + core.std.BlankClip( 196 | clip_down, length=2 197 | ) 198 | 199 | return core.std.ModifyFrame( 200 | return_clip, 201 | (return_clip, shift_down2, shift_down1, clip_down, shift_up1, shift_up2), 202 | execute, 203 | ) 204 | 205 | if ssim_clip: 206 | return core.std.ModifyFrame(return_clip,(return_clip,clip_down,clip_down[1:],ssim_clip),execute) 207 | return core.std.ModifyFrame(return_clip,(return_clip,clip_down,clip_down[1:]),execute) 208 | 209 | 210 | def frame_to_tensor(frame: vs.VideoFrame): 211 | return np.stack( 212 | [np.asarray(frame[plane]) for plane in range(frame.format.num_planes)] 213 | ) 214 | def tensor_to_frame(f: vs.VideoFrame, array) -> vs.VideoFrame: 215 | for plane in range(f.format.num_planes): 216 | d = np.asarray(f[plane]) 217 | np.copyto(d, array[plane, :, :]) 218 | return f 219 | def tensor_to_clip(clip: vs.VideoNode, image) -> vs.VideoNode: 220 | clip = core.std.BlankClip( 221 | clip=clip, width=image.shape[-1], height=image.shape[-2] 222 | ) 223 | return core.std.ModifyFrame( 224 | clip=clip, 225 | clips=clip, 226 | selector=lambda n, f: tensor_to_frame(f.copy(), image), 227 | ) 228 | def box_resizer(clip,w,h,*args,**kwargs): 229 | clip=core.fmtc.resample(clip,w,h,kernel='box',css='444') 230 | clip=core.resize.Point(clip,*args,**kwargs) 231 | return clip 232 | def prepare_clip(clip,onnx_res,fp16,resizer): 233 | col_fam=clip.format.color_family 234 | target_fmt=[vs.RGBS,vs.RGBH][fp16] 235 | if not callable(resizer): 236 | if not hasattr(core,'fmtc'): 237 | resizer=functools.partial(core.resize.Bicubic,filter_param_a=-0.3,filter_param_b=0.15) 238 | else: 239 | resizer=box_resizer 240 | resizer=functools.partial(resizer,format=target_fmt) 241 | if clip.format.id==target_fmt and clip.width==onnx_res[0] and clip.height==onnx_res[1]: 242 | return clip 243 | if col_fam==vs.RGB: 244 | return resizer(clip,onnx_res[0],onnx_res[1]) 245 | else: 246 | matrix=clip.get_frame(0).props.get("_Matrix") 247 | if matrix is None or matrix==2: 248 | if clip.width>=1280 or clip.height>=720: 249 | matrix=1 250 | else: 251 | matrix=5 252 | return resizer(clip,onnx_res[0],onnx_res[1],matrix_in=matrix) 253 | 254 | def sc_copy(clip,propclip): # in case you need it, e.g. you want to preprocess the detection clip but not the result clip 255 | def execute(n,f): 256 | fout=f[0].copy() 257 | fout.props._SceneChangeNext=f[1].props._SceneChangeNext 258 | fout.props._SceneChangeMetrics=f[1].props._SceneChangeMetrics 259 | return fout 260 | return core.std.ModifyFrame(clip,[clip,propclip],execute) 261 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /zvs.py: -------------------------------------------------------------------------------- 1 | __version__=str(1763916847/2**31) 2 | import os,sys 3 | import vapoursynth as vs 4 | from vapoursynth import core 5 | import xvs 6 | import mvsfunc as mvf 7 | from functools import partial 8 | from pathlib import Path 9 | from typing import Any, Mapping, Optional, Sequence, Union 10 | import nnedi3_resample as nnrs 11 | 12 | ''' 13 | functions: 14 | - pqdenoise 15 | - zmdg (zmde) 16 | - xdbcas 17 | - arop 18 | - pfinesharp (rpfilter (rpclip)) 19 | - w2xaa 20 | - knl4a (nlm) 21 | - wtfmask 22 | - bordermask 23 | - bm3d (copy-paste!) 24 | - n3pv 25 | - rescale, rescalef, multirescale (copy-paste!) 26 | - quack 27 | - bilateraluv 28 | - dft, idft, dct, idct 29 | - badlyscaledborderdetect (bsbd for short) 30 | - rescaleandtrytounfuckborders (rattub for short) 31 | - isvse, isvspipe 32 | - fmvfps 33 | - hrife 34 | - go444keepuv 35 | - setrange, setmatrix, settransfer, setprimaries, setchromaloc, setparams 36 | - gaussianblurfmtc (gbf for short) 37 | - cdif 38 | - alpha2clip 39 | - addsc 40 | - simplebitdepth (sb for short) 41 | - framehash 42 | - outputs 43 | ''' 44 | 45 | try: 46 | from dotenv import load_dotenv 47 | 48 | if (env := Path(__file__).parent / ".env.zvs.global").exists(): 49 | load_dotenv(env) 50 | load_dotenv('.env.zvs',override=True) 51 | except ModuleNotFoundError: 52 | pass 53 | 54 | # Override these values if they're found in .env. 55 | nnrs_mode_default = os.environ.get("nnrs_mode_default", "nnedi3") 56 | bm3d_mode_default = os.environ.get("bm3d_mode_default", "cpu") 57 | bm3d_extractor_exp_default = os.environ.get("bm3d_extractor_exp_default", 0) 58 | 59 | nnrs.nnedi3_resample=partial(nnrs.nnedi3_resample,mode=nnrs_mode_default,nns=3,nsize=1,qual=2,pscrn=1) 60 | Nnrs=nnrs 61 | 62 | 63 | #denoise pq hdr content by partially convert it to bt709, do denoise in bt709 then take the difference back to pq, may yeeld a better result 64 | def pqdenoise(src,sigma=[1,1,1],lumaonly=False,block_step=7,radius=1,finalest=False,bm3dtyp=bm3d_mode_default,vt=0,mdegrain=True,tr=2,pel=1,blksize=16,overlap=None,chromamv=True,thsad=100,thsadc=None,thscd1=400,thscd2=130,truemotion=False,nl=100,contrasharp=1,to709=1,show='output',limit=None,limitc=None,sigma2=None,radius2=None,lf=None,refinemotion=False,rmblksize=None,rmoverlap=None,rmpel=None,rmchromamv=None,rmtruemotion=None,rmthsad=None,pref=None): 65 | if lumaonly: 66 | chromamv=False 67 | chromaclip=src 68 | src=xvs.getY(src) 69 | 70 | src=simplebitdepth(src,16) 71 | denoised=sdr=core.resize.Point(src,transfer_in=16,transfer=1,nominal_luminance=nl) if to709 else src 72 | pref=core.resize.Point(pref,transfer_in=16,transfer=1,nominal_luminance=nl) if pref!=None else pref if to709 else pref 73 | if mdegrain: 74 | limitc=limitc if limitc else limit 75 | denoised=zmde(denoised,tr=tr,thsad=thsad,thsadc=thsadc,blksize=blksize,overlap=overlap,pel=pel,thscd1=thscd1,thscd2=thscd2,truemotion=truemotion,chromamv=chromamv,limit=limit,limitc=limitc,lf=lf,refinemotion=refinemotion,rmblksize=rmblksize,rmoverlap=rmoverlap,rmpel=rmpel,rmchromamv=rmchromamv,rmtruemotion=rmtruemotion,rmthsad=rmthsad,pref=pref) 76 | if show=='mde': 77 | return denoised 78 | 79 | if contrasharp>=2 or (contrasharp==1 and bm3dtyp=='no'): 80 | denoised=ContraSharpening(denoised,sdr) 81 | if show=='mdecs': 82 | return denoised 83 | 84 | if not bm3dtyp=='no': 85 | if vt==0: 86 | if bm3dtyp=='cpu': 87 | BM3D=core.bm3dcpu.BM3D 88 | elif bm3dtyp=='cuda': 89 | BM3D=core.bm3dcuda.BM3D 90 | elif bm3dtyp=='cuda_rtc': 91 | BM3D=core.bm3dcuda_rtc.BM3D 92 | elif vt==1: 93 | if bm3dtyp=='cpu': 94 | BM3D=core.bm3dcpu.BM3Dv2 95 | elif bm3dtyp=='cuda': 96 | BM3D=core.bm3dcuda.BM3Dv2 97 | elif bm3dtyp=='cuda_rtc': 98 | BM3D=core.bm3dcuda_rtc.BM3Dv2 99 | 100 | bdenoised=BM3D(denoised.fmtc.bitdepth(bits=32),sigma=sigma,radius=radius,block_step=block_step) 101 | if radius>0 and vt==0: 102 | bdenoised=core.bm3d.VAggregate(bdenoised,radius,1) 103 | 104 | if finalest: 105 | sigma2=sigma2 if sigma2 else sigma 106 | radius2=radius2 if radius2 else radius 107 | bdenoised=BM3D(denoised.fmtc.bitdepth(bits=32),ref=bdenoised,sigma=sigma2,radius=radius2,block_step=max(block_step-1,1)) 108 | if radius2>0 and vt==0: 109 | bdenoised=core.bm3d.VAggregate(bdenoised,radius2,1) 110 | 111 | denoised=bdenoised.fmtc.bitdepth(bits=16) 112 | if show=='bm3d': 113 | return denoised 114 | 115 | if contrasharp>=1: 116 | denoised=ContraSharpening(denoised,sdr) 117 | if show=='bm3dcs': 118 | return denoised 119 | 120 | if to709: 121 | denoised,sdr=[core.resize.Point(i,transfer_in=1,transfer=16,nominal_luminance=nl) for i in (denoised,sdr)] 122 | 123 | output=core.std.Expr([src,sdr,denoised],'x y - z +') if to709 else denoised 124 | if lumaonly: 125 | output=core.std.ShufflePlanes([output,chromaclip],[0,1,2],vs.YUV) 126 | 127 | return output 128 | 129 | #a simple mdegrain wrapper function that's enough for my own use 130 | ''' 131 | cs: go 132 | no I'm joking 133 | cs: call ContraSharpening after degrain 134 | mvout: output a dict of mvs ready for "mvin" 135 | mvout_sup: output super clips as well, benefit is small and may cause unintended behavior, not recommended 136 | mvin: take a dict of mvs, use them to degrain, if super clips present, they will be used too 137 | mvinrm: apply recalculate on mvs from "mvin" 138 | mvupd: only with "mvinrm", decide whether to update the input dict 139 | limit: passed to mdegrain as before (it was included in **args ;P) if None or in range [0, (1<mvin['tr']:raise ValueError 212 | if mvinrm: 213 | for i in range(tr): 214 | _fw=core.mv.Recalculate(sup3,_mvfw[i],rmthsad,blksize=rmblksize,overlap=rmoverlap,truemotion=rmtruemotion,chroma=rmchromamv,dct=rmdct,**rargs) 215 | _bw=core.mv.Recalculate(sup3,_mvbw[i],rmthsad,blksize=rmblksize,overlap=rmoverlap,truemotion=rmtruemotion,chroma=rmchromamv,dct=rmdct,**rargs) 216 | mvfw.append(_fw) 217 | mvbw.append(_bw) 218 | if mvupd: 219 | _mvfw[i]=_fw 220 | _mvbw[i]=_bw 221 | else: 222 | mvfw=_mvfw 223 | mvbw=_mvbw 224 | else: 225 | for i in range(1,tr+1): 226 | _fw=core.mv.Analyse(sup,isb=False,delta=i,blksize=blksize,overlap=overlap,truemotion=truemotion,chroma=chromamv,dct=dct,**aargs) 227 | _bw=core.mv.Analyse(sup,isb=True,delta=i,blksize=blksize,overlap=overlap,truemotion=truemotion,chroma=chromamv,dct=dct,**aargs) 228 | if refinemotion: 229 | _fw=core.mv.Recalculate(sup3,_fw,rmthsad,blksize=rmblksize,overlap=rmoverlap,truemotion=rmtruemotion,chroma=rmchromamv,dct=rmdct,**rargs) 230 | _bw=core.mv.Recalculate(sup3,_bw,rmthsad,blksize=rmblksize,overlap=rmoverlap,truemotion=rmtruemotion,chroma=rmchromamv,dct=rmdct,**rargs) 231 | mvfw.append(_fw) 232 | mvbw.append(_bw) 233 | 234 | mv_list_string=','.join([f'mvbw[{j}],mvfw[{j}]' for j in range(tr)]) 235 | if mvout: 236 | mvd={'mvfw':mvfw,'mvbw':mvbw,'tr':tr,'mvlist':mv_list_string} 237 | if mvout_sup: 238 | mvd['sup']=[sup,sup2,sup3] if refinemotion else [sup,sup2] 239 | return mvd 240 | 241 | last=eval(f'core.mv.Degrain{tr}(last,sup2,{mv_list_string},thsad=thsad,thsadc=thsadc,thscd1=thscd1,thscd2=thscd2,limit=limit,**args)') 242 | if alim: 243 | neutral=1 << (src.format.bits_per_sample-1) 244 | pdiff=core.std.MakeDiff(src,alim_ref) if not alim_cdif else cdif(src,alim_ref) 245 | mdiff=core.std.MakeDiff(src,last) if not alim_cdif else cdif(src,last) 246 | expr=f'x {neutral} - abs y {neutral} - abs < x y ?' 247 | ddiff=core.std.Expr([pdiff,mdiff],expr=[expr]) 248 | last=core.std.MakeDiff(src,ddiff) if not alim_cdif else cdif(src,ddiff,merge=-1) 249 | if callable(lf): 250 | last=lf(last,src) 251 | elif isinstance(lf,(int,float)): 252 | last=mvf.LimitFilter(last,src,thr=lf,elast=elast) 253 | if cs: 254 | last=rpfilter(last,src,filter=lambda x,y: ContraSharpening(x,y,radius=csrad,rep=csrep,planes=cspl),psize=4) 255 | if resize_pad: 256 | if isinstance(resize_pad,bool): 257 | last=last.std.Crop(*[blksize]*4) 258 | elif isinstance(resize_pad,int): 259 | last=last.std.Crop(*[resize_pad]*4) 260 | return last 261 | #for backward compatibility 262 | def zmde(src,thsad=100,thsadc=None,resize_pad=None,truemotion=False,**args): 263 | if thsadc==None:thsadc=thsad 264 | return zmdg(src,thsad=thsad,thsadc=thsadc,resize_pad=resize_pad,truemotion=truemotion,**args) 265 | 266 | #multi-pass f3kdb with optional contra-sharpening, masking and limit filter 267 | #idea stolen from xyx98 268 | def xdbcas(src,r=[8,15],y=[32,24],cb=[16,10],cr=[16,10],gy=[0,0],gc=[0,0],sm=[2,2],rs=[0,0],bf=[True,True],dg=[False,False],opt=[-1,-1],mt=[True,True],da=[3,3],ktv=[False,False],od=[16,16],rar=[1,1],rag=[1,1],rpr=[1,1],rpg=[1,1],passes=2,neo=True,casstr=0,mask=True,limit=True,s16=False): 269 | last=db=src.fmtc.bitdepth(bits=16) if s16 else src 270 | r,y,cb,cr,gy,gc,sm,rs,bf,dg,opt,mt,da,ktv,od,rar,rag,rpr,rpg=[[i]*passes if isinstance(i,int) else i+[i[-1]]*passes for i in (r,y,cb,cr,gy,gc,sm,rs,bf,dg,opt,mt,da,ktv,od,rar,rag,rpr,rpg)] 271 | 272 | # l1,l2,l3,l4,l5,l6=[len(i) for i in (r,y,cb,cr,gy,gc)] 273 | # if l1==l2==l3==l4==l5==l6: 274 | # passes=l6 275 | # else: 276 | # passes=min(l1,l2,l3,l4,l5,l6) 277 | 278 | for i in range(passes): 279 | if neo: 280 | db=core.neo_f3kdb.Deband(db,r[i],y[i],cb[i],cr[i],gy[i],gc[i],sm[i],rs[i],bf[i],dg[i],opt[i],mt[i],da[i],ktv[i],od[i],rar[i],rag[i],rpr[i],rpg[i]) 281 | else: 282 | db=core.f3kdb.Deband(db,r[i],y[i],cb[i],cr[i],gy[i],gc[i],sm[i],rs[i],bf[i],dg[i],opt[i],da[i],ktv[i],od[i],rar[i],rag[i],rpr[i],rpg[i]) 283 | 284 | if isinstance(limit,bool) and limit: 285 | db=mvf.LimitFilter(db,last,thr=0.1,thrc=0.05,elast=20,planes=[0,1,2]) 286 | elif isinstance(limit,(list,tuple)): 287 | limit=[i for i in limit if isinstance(i,(int,float))] 288 | if len(limit)==3: 289 | db=mvf.LimitFilter(db,last,thr=limit[0],thrc=limit[1],elast=limit[2],planes=[0,1,2]) 290 | else: 291 | raise ValueError 292 | elif callable(limit): 293 | db=limit(db,last) 294 | else: 295 | pass 296 | 297 | if mask: 298 | if isinstance(mask,vs.VideoNode): 299 | dbmask=mask 300 | else: 301 | dbmask=xvs.mwdbmask(last) 302 | db=core.std.MaskedMerge(db,last,dbmask) 303 | 304 | if casstr<=0: 305 | return db 306 | 307 | cas=core.cas.CAS(last,casstr,planes=[0,1,2]) 308 | cas=mvf.LimitFilter(cas,last,thr=0.3,thrc=0.15,brighten_thr=0.15,elast=4,planes=[0,1,2]) 309 | last=core.std.Expr([cas,last,db],'x y - z +') 310 | 311 | return last 312 | 313 | #arbitrary crop, result resolution must be compatible with src clip subsampling tho 314 | def arop(src,left=0,right=0,top=0,bottom=0): #mostly useless experimental function 315 | subsw,subsh=[2**src.format.subsampling_w,2**src.format.subsampling_h] 316 | if not (top%subsh or bottom%subsh or left%subsw or right%subsw): 317 | return core.std.Crop(src,left=left,right=right,top=top,bottom=bottom) 318 | else: 319 | l,r=[i if not i%subsw else 0 for i in (left,right)] 320 | t,b=[i if not i%subsh else 0 for i in (top,bottom)] 321 | 322 | last=core.std.Crop(src,left=l,right=r,top=t,bottom=b) if not(l==r==t==b==0) else src 323 | y,u,v=xvs.extractPlanes(last) 324 | 325 | l,r=[i if i%subsw else 0 for i in (left,right)] 326 | t,b=[i if i%subsh else 0 for i in (top,bottom)] 327 | 328 | y=core.std.Crop(y,left=l,right=r,top=t,bottom=b) 329 | w=(src.width-left-right)//subsw 330 | h=(src.height-top-bottom)//subsh 331 | src_left=l/subsw 332 | src_top=t/subsh 333 | src_width=(last.width-l-r)/subsw 334 | src_height=(last.height-t-b)/subsh 335 | u,v=[core.resize.Bicubic(i,w,h,src_left=src_left,src_top=src_top,src_width=src_width,src_height=src_height) for i in (u,v)] 336 | 337 | last=core.std.ShufflePlanes([y,u,v],[0,0,0],vs.YUV) 338 | return last 339 | 340 | #padded finesharp, because finesharp like to mess up frames' edges 341 | def pfinesharp(src,crop=True,psize=4,**args): 342 | import finesharp 343 | sharpen=lambda x: finesharp.sharpen(x,**args) 344 | return rpfilter(src,filter=sharpen,psize=psize,crop=crop) 345 | 346 | #nnrs and ssim is for chroma upscaling and downscaling only 347 | #deprecated, 無駄無駄 348 | def w2xaa(src,model=0,noise=-1,fp32=False,tile_size=0,format=None,full=None,matrix='709',nnrs=False,ssim=False,ssim_smooth=False,ssim_sigmoid=True,nnrs_down=None,ort=False,model_f=None,model_p=None,overlap=None): 349 | import muvsfunc as muf 350 | if full==None: 351 | try: 352 | full=not src.get_frame(0).props._ColorRange 353 | except: 354 | full=False 355 | src_range_s='full' if full else 'limited' 356 | src_format=src.format if format==None else format 357 | width,height=src.width,src.height 358 | precision=32 if fp32 else 16 359 | nnrs_down=nnrs if nnrs_down==None else nnrs_down 360 | if nnrs: 361 | last=Nnrs.nnedi3_resample(src,csp=vs.RGBS,fulls=full,mats=matrix) 362 | else: 363 | last=core.resize.Bicubic(src,format=vs.RGBS,range_in_s=src_range_s,matrix_in_s=matrix) 364 | 365 | if not ort: 366 | if tile_size==0: 367 | tile_size=[src.width,src.height] 368 | elif isinstance(tile_size,int): 369 | tile_size=[tile_size]*2 370 | last=core.w2xncnnvk.Waifu2x(last,model=model,scale=2,noise=noise,precision=precision,tile_w=tile_size[0],tile_h=tile_size[1]) 371 | else: 372 | tile_size=[src.width,src.height] if tile_size==0 else tile_size 373 | overlap=4 if model==2 else 8 if overlap==None else overlap 374 | builtin=True if model_f==model_p==None else False 375 | model_f='waifu2x' if model_f==None else model_f 376 | model_g=['upconv_7_anime_style_art_rgb','upconv_7_photo','cunet'][model] if isinstance(model,int) else model 377 | model_n=f'noise{noise}_scale2.0x_model.onnx' if not noise==-1 else 'scale2.0x_model.onnx' 378 | model_p=os.path.join(model_f,model_g,model_n) if model_p==None else model_p 379 | last=core.ort.Model(last,model_p,provider='CUDA',builtin=builtin,fp16=not fp32,tilesize=tile_size,overlap=overlap) 380 | 381 | if ssim: 382 | last=muf.SSIM_downsample(last,width,height,format=src_format,range_s=src_range_s,matrix_s=matrix,smooth=ssim_smooth,sigmoid=ssim_sigmoid) 383 | elif nnrs_down: 384 | last=Nnrs.nnedi3_resample(last,width,height,csp=src_format,fulld=full,matd=matrix) 385 | else: 386 | last=core.resize.Bicubic(last,width,height,format=src_format,range_s=src_range_s,matrix_s=matrix) 387 | return last 388 | 389 | #a workaround for amd rdna graphic cards to use knlmeanscl 390 | def knl4a(src,*args,**kwargs): 391 | return nlm(src,*args,**kwargs,amd=True,mode='ocl') 392 | def nlm(src,planes=[0,1,2],rclip=None,h=1.2,amd=False,mode='ocl',**args): 393 | NLM={'ocl':core.knlm.KNLMeansCL,'cuda':core.nlm_cuda.NLMeans}[mode] if not amd else core.knlm.KNLMeansCL 394 | if isinstance(h,list): 395 | if len(h)>=3: 396 | pass 397 | elif len(h)==2: 398 | h=[h[0],h[1],h[1]] 399 | else: 400 | h=[h[0],h[0],h[0]] 401 | else: 402 | h=[h,h,h] 403 | 404 | p0,p1,p2=[i in planes for i in (0,1,2)] 405 | if not amd and p0 and p1 and p2 and h[1]==h[2]: 406 | return NLM(NLM(src,rclip=rclip,h=h[0],channels='Y',**args),rclip=rclip,h=h[1],channels='UV',**args) 407 | 408 | y,u,v=core.std.SplitPlanes(src) 409 | if amd: 410 | y,u,v=[core.std.ShufflePlanes([i,i,i],[0,0,0],vs.RGB) for i in (y,u,v)] 411 | if isinstance(rclip,vs.VideoNode): 412 | ry,ru,rv=core.std.SplitPlanes(rclip) 413 | if amd: 414 | ry,ru,rv=[core.std.ShufflePlanes([i,i,i],[0,0,0],vs.RGB) for i in (ry,ru,rv)] 415 | else: 416 | ry=ru=rv=None 417 | if p0: 418 | y=NLM(y,rclip=ry,h=h[0],**args) 419 | if p1 and p2 and h[1]==h[2]: 420 | uv=NLM(src,rclip=rclip,h=h[1],channels='UV',**args) 421 | u=xvs.getU(uv) 422 | v=xvs.getV(uv) 423 | else: 424 | if p1: 425 | u=NLM(u,rclip=ru,h=h[1],**args) 426 | if p2: 427 | v=NLM(v,rclip=rv,h=h[2],**args) 428 | y,u,v=[core.std.ShufflePlanes(i,[0],vs.GRAY) for i in (y,u,v)] 429 | return core.std.ShufflePlanes([y,u,v],[0,0,0],vs.YUV) 430 | 431 | #line mask? 432 | def wtfmask(src,nnrs=True,t_l=16,t_h=26,range='full',op=[1],optc=1,bin=True,bthr=1,**args): 433 | if nnrs: 434 | last=Nnrs.nnedi3_resample(src,csp=vs.RGBS) 435 | else: 436 | last=core.resize.Bicubic(src,format=vs.RGBS,matrix_in=1) 437 | last=core.tcanny.TCanny(last,t_l=t_l,t_h=t_h,op=optc,**args) 438 | if range in ['full','pc']: 439 | last=last.resize.Bicubic(format=vs.GRAY16,matrix=1,range_s='full') 440 | if bin: last=last.std.Binarize(256*bthr,0,65535) 441 | else: 442 | last=last.resize.Bicubic(format=vs.GRAY16,matrix=1,range_s='limited') 443 | if bin: last=last.std.Binarize(256*(16+(235-16)/256*bthr),16*256,235*256) 444 | f=[core.std.Minimum,core.std.Maximum,core.std.Deflate,core.std.Inflate] 445 | for i in op: 446 | last=f[i](last) 447 | return last 448 | 449 | 450 | def bordermask(src,l=0,r=0,t=0,b=0,d=16): 451 | return core.std.BlankClip(src,format=core.std.BlankClip(format=vs.GRAY16).fmtc.bitdepth(bits=d).format,color=0).std.Crop(left=l,right=r,top=t,bottom=b).std.AddBorders(left=l,right=r,top=t,bottom=b,color=2**d-1 if d<32 else 1) 452 | 453 | #resize padded filter 454 | def rpfilter(input,ref=None,other=None,filter=lambda x: x,psize=2,crop=True): 455 | input=rpclip(input,psize) 456 | if isinstance(other,dict): 457 | for key in other: 458 | if isinstance(other[key],vs.VideoNode): 459 | other[key]=rpclip(other[key],psize) 460 | if isinstance(ref,vs.VideoNode): 461 | ref=rpclip(ref,psize) 462 | if isinstance(other,dict): 463 | last=filter(input,ref,**other) 464 | else: 465 | last=filter(input,ref) 466 | else: 467 | if isinstance(other,dict): 468 | last=filter(input,**other) 469 | else: 470 | last=filter(input) 471 | if crop: 472 | last=core.std.Crop(last,*[psize]*4) 473 | return last 474 | 475 | #resize pad clip 476 | def rpclip(input,psize=2,left=None,right=None,top=None,bottom=None): 477 | if left==None:left=psize 478 | if right==None:right=psize 479 | if top==None:top=psize 480 | if bottom==None:bottom=psize 481 | w=input.width+left+right 482 | h=input.height+top+bottom 483 | return core.resize.Point(input,w,h,src_top=-top,src_left=-left,src_width=w,src_height=h) 484 | 485 | #nnedi3 preview 486 | def n3pv(*args,**kwargs): 487 | scale=kwargs.get('scale',2) 488 | nns=kwargs.get('nns',1) 489 | nsize=kwargs.get('nsize',0) 490 | qual=kwargs.get('qual',1) 491 | mode=kwargs.get('mode',nnrs_mode_default) 492 | int_=kwargs.get('int',False) 493 | depth=kwargs.get('depth',8) 494 | mats=kwargs.get('mats') 495 | fulls=kwargs.get('fulls') 496 | bypass=mode=='bypass' 497 | madvr=mode=='madvr' 498 | madvr_algo=kwargs.get('madvr_algo','nguSharpLow') 499 | csp=eval(f'vs.RGB{depth*3}') 500 | last=list() 501 | if len(args)==1: 502 | if isinstance(args[0],list): 503 | clipnum=len(args[0]) 504 | scale=[scale]*clipnum if not isinstance(scale,(list,tuple)) else scale 505 | mats=[mats]*clipnum if not isinstance(mats,(list,tuple)) else mats 506 | fulls=[fulls]*clipnum if not isinstance(fulls,(list,tuple)) else fulls 507 | scale,mats,fulls=[i+[i[-1]]*clipnum for i in (scale,mats,fulls)] 508 | for i,clip in enumerate(args[0]): 509 | _w,_h=clip.width*scale[i],clip.height*scale[i] 510 | if bypass: 511 | _tmpclp=core.resize.Bicubic(clip,_w,_h) 512 | _tmpclp=mvf.ToRGB(_tmpclp,depth=depth,matrix=mats[i],full=fulls[i]) 513 | elif madvr: 514 | _tmpclp=core.madvr.Process(clip,[f'upscale({_w},{_h},{madvr_algo})',f'setOutputFormat(rgbPC,{depth})']) 515 | else: 516 | _tmpclp=Nnrs.nnedi3_resample(clip,_w,_h,csp=csp,nns=nns,nsize=nsize,qual=qual,mode=mode,mats=mats[i],fulls=fulls[i]) 517 | last.append(_tmpclp) 518 | elif isinstance(args[0],vs.VideoNode): 519 | scale=scale[0] if isinstance(scale,(list,tuple)) else scale 520 | mats=mats[0] if isinstance(mats,(list,tuple)) else mats 521 | fulls=fulls[0] if isinstance(fulls,(list,tuple)) else fulls 522 | _w,_h=args[0].width*scale,args[0].height*scale 523 | if bypass: 524 | _tmpclp=core.resize.Bicubic(args[0],_w,_h) 525 | _tmpclp=mvf.ToRGB(_tmpclp,depth=depth,matrix=mats,full=fulls) 526 | elif madvr: 527 | _tmpclp=core.madvr.Process(args[0],[f'upscale({_w},{_h},{madvr_algo})',f'setOutputFormat(rgbPC,{depth})']) 528 | else: 529 | _tmpclp=Nnrs.nnedi3_resample(args[0],_w,_h,csp=csp,nns=nns,nsize=nsize,qual=qual,mode=mode,mats=mats,fulls=fulls) 530 | last.append(_tmpclp) 531 | else: 532 | raise TypeError('input for preview should be list or clip') 533 | elif len(args)>1: 534 | clipnum=len(args) 535 | scale=[scale]*clipnum if not isinstance(scale,(list,tuple)) else scale 536 | mats=[mats]*clipnum if not isinstance(mats,(list,tuple)) else mats 537 | fulls=[fulls]*clipnum if not isinstance(fulls,(list,tuple)) else fulls 538 | scale,mats,fulls=[i+[i[-1]]*clipnum for i in (scale,mats,fulls)] 539 | for i,clip in enumerate(args): 540 | _w,_h=clip.width*scale[i],clip.height*scale[i] 541 | if bypass: 542 | _tmpclp=core.resize.Bicubic(clip,_w,_h) 543 | _tmpclp=mvf.ToRGB(_tmpclp,depth=depth,matrix=mats[i],full=fulls[i]).sub.Subtitle(f'clip{i}') 544 | elif madvr: 545 | _tmpclp=core.madvr.Process(clip,[f'upscale({_w},{_h},{madvr_algo})',f'setOutputFormat(rgbPC,{depth})']).sub.Subtitle(f'clip{i}') 546 | else: 547 | _tmpclp=Nnrs.nnedi3_resample(clip,_w,_h,csp=csp,nns=nns,nsize=nsize,qual=qual,mode=mode,mats=mats[i],fulls=fulls[i]).sub.Subtitle(f'clip{i}') 548 | last.append(_tmpclp) 549 | else: 550 | raise ValueError('Panik') 551 | return last[0] if len(last)==1 else core.std.Interleave(last) if int_ else last 552 | 553 | #quack quack, I'll take your grains 554 | #a dumb-ass func may be suitable for old movies with heavy dynamic grains 555 | def quack(src,bilateral=False,median=None,knl={},md1={},bm1={},md2={},bm2={}): 556 | _knl={'amd':False,'a':1,'s':2,'d':3,'h':2} 557 | _md1={'thsad':250,'thscd1':250,'limit':768,'tr':3} 558 | _bm1={'sigma':[2,2,2],'radius':1} 559 | _md2={'thsad':250,'thscd1':250,'limit':768,'tr':3} 560 | _bm2={'sigma':[1,1,1],'radius':1} 561 | if median is None: 562 | median=knl!=False 563 | if bilateral is None: 564 | if knl!=False:bilateral='cpu' 565 | if not knl==False: 566 | _knl.update(knl) 567 | _md1.update(md1) 568 | _bm1.update(bm1) 569 | _md2.update(md2) 570 | _bm2.update(bm2) 571 | if src.format.bits_per_sample!=16: 572 | src=src.fmtc.bitdepth(bits=16) 573 | last=src 574 | if bilateral: 575 | m=last.bilateralgpu.Bilateral() if bilateral=='gpu' else last.bilateral.Bilateral(planes=[0,1,2]) 576 | elif median: 577 | m=last.std.Median() 578 | else: 579 | m=src 580 | if knl==False: 581 | n=m 582 | else: 583 | n=nlm(last,rclip=m,**_knl) 584 | last=zmdg(last,pref=n,**_md1) 585 | last=bm3d(last,iref=src,**_bm1) 586 | last=zmdg(src,pref=last,**_md2) 587 | last=bm3d(last,iref=src,**_bm2) 588 | return last 589 | 590 | #use y channel or opponent chroma channel as reference to repair uv channels with bilateral 591 | #tbilateral is much trickier to use, the "ref" doesn't even mean the same thing, just add it for testing 592 | #parameters you should really care about are ones in first line 593 | #using KrigBilateral with vs-placebo may be better? 594 | def bilateraluv(src,ch='uv',mode='down',method='spline36',oldbehavior=False,clc=True,left=True,top=False,S=1,R=0.02,lumaref=True,crossref=False,\ 595 | algo=0,P=None,T=False,diameter=3,sdev=0.5,idev=0.01,cs=1,d2=True,kerns=1,kerni=1,restype=0,**kwargs): 596 | if mode.lower()=='up': 597 | targetw=src.width 598 | targeth=src.height 599 | elif mode.lower()=='down': 600 | targetw=src.width>>src.format.subsampling_w 601 | targeth=src.height>>src.format.subsampling_h 602 | else: 603 | raise ValueError('mode not supported') 604 | 605 | if lumaref: 606 | if method.lower()=='nnrs': 607 | resizer=lambda x,w,h,l,t,**args:Nnrs.nnedi3_resample(x,w,h,src_left=l,src_top=t,csp=args.pop('format') if oldbehavior else None,**args) 608 | elif method.lower() in ['point','bilinear','bicubic','lanczos','spline16','spline36','spline64']: 609 | resizer=eval(f'lambda x,w,h,l,t,**args:core.resize.{method.capitalize()}(x,w,h,src_left=l,src_top=t,**args)') 610 | else: 611 | raise ValueError('resize method not supported') 612 | last=go444keepuv(src,dir=mode,clc=clc,left=left,top=top,resampler=partial(resizer,**kwargs)) if not oldbehavior else resizer(src,targetw,targeth,0,0,format=vs.YUV444P16,**kwargs) 613 | else: 614 | last=src 615 | 616 | y,u,v=xvs.extractPlanes(last) 617 | if 'u' in ch.lower(): 618 | if lumaref: 619 | ub=core.bilateral.Bilateral(u,y,sigmaS=S,sigmaR=R,algorithm=algo,PBFICnum=P) if not T else\ 620 | core.tbilateral.TBilateral(u,y,diameter,sdev,idev,cs,d2,kerns,kerni,restype) 621 | else: 622 | ub=u 623 | if crossref: 624 | ub=core.bilateral.Bilateral(ub,v,sigmaS=S,sigmaR=R,algorithm=algo,PBFICnum=P) if not T else\ 625 | core.tbilateral.TBilateral(ub,v,diameter,sdev,idev,cs,d2,kerns,kerni,restype) 626 | if 'v' in ch.lower(): 627 | if lumaref: 628 | vb=core.bilateral.Bilateral(v,y,sigmaS=S,sigmaR=R,algorithm=algo,PBFICnum=P) if not T else\ 629 | core.tbilateral.TBilateral(v,y,diameter,sdev,idev,cs,d2,kerns,kerni,restype) 630 | else: 631 | vb=v 632 | if crossref: 633 | vb=core.bilateral.Bilateral(vb,u,sigmaS=S,sigmaR=R,algorithm=algo,PBFICnum=P) if not T else\ 634 | core.tbilateral.TBilateral(vb,u,diameter,sdev,idev,cs,d2,kerns,kerni,restype) 635 | return core.std.ShufflePlanes([src,ub,vb],[0,0,0],vs.YUV) 636 | 637 | #this is cool but I don't really know why I wrote this 638 | #some reference: 639 | #https://stackoverflow.com/questions/59975604/how-to-inverse-a-dft-with-magnitude-with-opencv-python 640 | def dft(src,d=10,spectrum=False,split=True,linear='1886',shift=True): 641 | if src.format.id != vs.GRAYS: 642 | raise ValueError('I thought only GRAYS input was supported.') 643 | import numpy as np 644 | import cv2 645 | if linear is not False: 646 | src=src.fmtc.transfer(transs=linear,transd='linear') 647 | src=src.std.PlaneStats() 648 | def dft(n,f,h): 649 | fout=f.copy() 650 | Dft=np.asarray(fout[0])[:h,:] 651 | Dft=cv2.dft(Dft,flags=cv2.DFT_COMPLEX_OUTPUT) 652 | if shift: Dft=np.fft.fftshift(Dft) 653 | mag,phase=cv2.cartToPolar(Dft[:,:,0],Dft[:,:,1]) 654 | if spectrum: 655 | spec=np.log(mag)/d 656 | Stack=np.concatenate([mag,phase,spec]) 657 | else: 658 | Stack=np.concatenate([mag,phase]) 659 | np.copyto(np.asarray(fout[0]),Stack) 660 | return fout 661 | stack=core.std.StackVertical([src]*(2+spectrum)) 662 | stack=core.std.FrameEval(stack,lambda n:core.std.ModifyFrame(stack,stack,partial(dft,h=src.height))) 663 | if not split: 664 | return stack 665 | mag=stack.std.Crop(bottom=src.height*(1+spectrum)) 666 | phase=stack.std.Crop(top=src.height,bottom=src.height*(0+spectrum)) 667 | if spectrum: 668 | spec=stack.std.Crop(top=src.height*2) 669 | return mag,phase,spec 670 | return mag,phase 671 | 672 | 673 | def idft(mag,phase,linear='1886',ishift=True): 674 | if not (mag.format.id==phase.format.id==vs.GRAYS): 675 | raise ValueError('I thought only GRAYS inputs were supported.') 676 | import numpy as np 677 | import cv2 678 | def idft(n,f): 679 | fout=f[0].copy() 680 | mag=np.asarray(f[0].copy()[0]) 681 | phase=np.asarray(f[1].copy()[0]) 682 | real,imag=cv2.polarToCart(mag,phase) 683 | fr=cv2.merge([real,imag]) 684 | if ishift: fr=np.fft.ifftshift(fr) 685 | fr=cv2.idft(fr) 686 | fr=cv2.magnitude(fr[:,:,0],fr[:,:,1]) 687 | fr=cv2.normalize(fr,None,f[0].props.PlaneStatsMin,f[0].props.PlaneStatsMax,cv2.NORM_MINMAX,dtype=cv2.CV_32F) 688 | np.copyto(np.asarray(fout[0]),fr) 689 | return fout 690 | last=core.std.FrameEval(mag,lambda n:core.std.ModifyFrame(mag,[mag,phase],idft)) 691 | if linear is not False: 692 | last=last.fmtc.transfer(transs='linear',transd=linear) 693 | return last 694 | 695 | 696 | def dct(src): 697 | if not src.format.id==vs.GRAYS: 698 | raise ValueError('I thought only GRAYS input was supported.') 699 | import numpy as np 700 | import cv2 701 | def dct(n,f): 702 | fout=f.copy() 703 | tr=np.asarray(fout[0]) 704 | tr=cv2.dct(tr) 705 | np.copyto(np.asarray(fout[0]),tr) 706 | return fout 707 | return core.std.FrameEval(src,lambda n:core.std.ModifyFrame(src,src,dct)) 708 | 709 | 710 | def idct(src): 711 | if not src.format.id==vs.GRAYS: 712 | raise ValueError('I thought only GRAYS input was supported.') 713 | import numpy as np 714 | import cv2 715 | def idct(n,f): 716 | fout=f.copy() 717 | tr=np.asarray(fout[0]) 718 | tr=cv2.idct(tr) 719 | np.copyto(np.asarray(fout[0]),tr) 720 | return fout 721 | return core.std.FrameEval(src,lambda n:core.std.ModifyFrame(src,src,idct)) 722 | 723 | #I don't even know what this do, will likely be abandoned 724 | def dwt(src,w='Haar'): 725 | if not src.format.id==vs.GRAYS: 726 | raise ValueError('I thought only GRAYS input was supported.') 727 | import numpy as np 728 | import pywt 729 | def dwt(n,f,w): 730 | fout=f.copy() 731 | tr=np.asarray(fout[0]) 732 | a,(h,v,d)=pywt.dwt2(tr,w) 733 | tr=np.concatenate([np.concatenate([a,v]),np.concatenate([h,d])],axis=1) 734 | np.copyto(np.asarray(fout[0]),np.float32(tr)) 735 | return fout 736 | return core.std.FrameEval(src,lambda n:core.std.ModifyFrame(src,src,partial(dwt,w=w))) 737 | 738 | 739 | def idwt(src,w='Haar'): 740 | if not src.format.id==vs.GRAYS: 741 | raise ValueError('I thought only GRAYS input was supported.') 742 | import numpy as np 743 | import pywt 744 | def dwt(n,f,w): 745 | fout=f.copy() 746 | tr=np.asarray(fout[0]) 747 | a1,a2=np.hsplit(tr,2) 748 | (a,v),(h,d)=np.vsplit(a1,2),np.vsplit(a2,2) 749 | tr=pywt.idwt2([a,(h,v,d)],w) 750 | np.copyto(np.asarray(fout[0]),np.float32(tr)) 751 | return fout 752 | return core.std.FrameEval(src,lambda n:core.std.ModifyFrame(src,src,partial(dwt,w=w))) 753 | 754 | #badly scaled border detect 755 | def badlyscaledborderdetect(src,left=True,right=True,top=True,bottom=True,conditionmode='or',valuemode='avg',showfrac=False,thr=0.9,thrmode='<',leftline1pos=0,leftline2pos=1,rightline1pos=0,rightline2pos=1,topline1pos=0,topline2pos=1,bottomline1pos=0,bottomline2pos=1): 756 | cliplist=[src] 757 | luma=xvs.getY(src) 758 | def sel1(n,f): 759 | fout=f[0].copy() 760 | try: 761 | if valuemode=='avg': 762 | fout.props.frac=f[0].props.PlaneStatsAverage/f[1].props.PlaneStatsAverage 763 | elif valuemode=='max': 764 | fout.props.frac=f[0].props.PlaneStatsMax/f[1].props.PlaneStatsMax 765 | elif valuemode=='min': 766 | fout.props.frac=f[0].props.PlaneStatsMin/f[1].props.PlaneStatsMin 767 | except ZeroDivisionError: 768 | fout.props.frac=1 769 | return fout 770 | letters=' ' 771 | if left: 772 | ll1=core.std.Crop(luma,left=leftline1pos,right=luma.width-1-leftline1pos).std.PlaneStats() 773 | ll2=core.std.Crop(luma,left=leftline2pos,right=luma.width-1-leftline2pos).std.PlaneStats() 774 | lf=core.std.ModifyFrame(ll1,[ll1,ll2],sel1) 775 | cliplist.append(lf) 776 | letters+='L' 777 | if right: 778 | rl1=core.std.Crop(luma,right=rightline1pos,left=luma.width-1-rightline1pos).std.PlaneStats() 779 | rl2=core.std.Crop(luma,right=rightline2pos,left=luma.width-1-rightline2pos).std.PlaneStats() 780 | rf=core.std.ModifyFrame(rl1,[rl1,rl2],sel1) 781 | cliplist.append(rf) 782 | letters+='R' 783 | if top: 784 | tl1=core.std.Crop(luma,top=topline1pos,bottom=luma.height-1-topline1pos).std.PlaneStats() 785 | tl2=core.std.Crop(luma,top=topline2pos,bottom=luma.height-1-topline2pos).std.PlaneStats() 786 | tf=core.std.ModifyFrame(tl1,[tl1,tl2],sel1) 787 | cliplist.append(tf) 788 | letters+='T' 789 | if bottom: 790 | bl1=core.std.Crop(luma,bottom=bottomline1pos,top=luma.height-1-bottomline1pos).std.PlaneStats() 791 | bl2=core.std.Crop(luma,bottom=bottomline2pos,top=luma.height-1-bottomline2pos).std.PlaneStats() 792 | bf=core.std.ModifyFrame(bl1,[bl1,bl2],sel1) 793 | cliplist.append(bf) 794 | letters+='B' 795 | def sel2(n,f,thr=thr): 796 | fout=f[0].copy() 797 | ftot=len(f) 798 | if showfrac: fracs=[];fracs_in_thr=[] 799 | if conditionmode=='or': 800 | isbad=False 801 | for i in range(1,ftot): 802 | isbad=isbad or eval(f'f[i].props.frac{thrmode}thr') 803 | if showfrac: 804 | fracs.append(f'{letters[i]}?:{f[i].props.frac}') 805 | if eval(f'f[i].props.frac{thrmode}thr'): 806 | fracs_in_thr.append(f'{letters[i]}?:{f[i].props.frac}') 807 | elif conditionmode=='and': 808 | isbad=True 809 | for i in range(1,ftot): 810 | isbad=isbad and eval(f'f[i].props.frac{thrmode}thr') 811 | if showfrac: 812 | fracs.append(f'{letters[i]}?:{f[i].props.frac}') 813 | if eval(f'f[i].props.frac{thrmode}thr'): 814 | fracs_in_thr.append(f'{letters[i]}?:{f[i].props.frac}') 815 | elif isinstance(conditionmode,int): 816 | countbad=0 817 | for i in range(1,ftot): 818 | countbad+=eval(f'f[i].props.frac{thrmode}thr') 819 | if showfrac: 820 | fracs.append(f'{letters[i]}?:{f[i].props.frac}') 821 | if eval(f'f[i].props.frac{thrmode}thr'): 822 | fracs_in_thr.append(f'{letters[i]}?:{f[i].props.frac}') 823 | isbad=countbad>=conditionmode 824 | fout.props.badborder=isbad 825 | if showfrac: 826 | fout.props.borderfracs=', '.join(fracs) 827 | fout.props.borderfracs_in_thr=', '.join(fracs_in_thr) 828 | return fout 829 | return core.std.ModifyFrame(src,cliplist,sel2) 830 | #why, past me, why? 831 | bsbd=badlyscaledborderdetect 832 | 833 | #rescale and try to unfuck border, target on highly specific situation 834 | #ALWAYS DO TESTS BEFORE USE! 835 | def rescaleandtrytounfuckborders(src,w=None,h=None,mask=True,mopf=None,mask_gen_clip=None,mask_dif_pix=2.5,kernel='bilinear',b=0,c=0.5,border_handling=0,ignore_mask=None,taps=3,nns=3,nsize=1,qual=2,pscrn=1,show='result',offst1=1,offsl1=1,offst2=1/3,offsl2=1/3,cuth=1,cutv=1,down_kernel=None,post_kernel='bicubic',nns2=None,nsize2=None,qual2=None,pscrn2=None,rim=64,border=4,bc=1,rc=3,linear=False,sigmoid=False,custom_nnedi3down=False,**args): 836 | if src.format.bits_per_sample!=16:src=src.fmtc.bitdepth(bits=16) 837 | last=src 838 | srcw,srch=src.width,src.height 839 | isgray=last.format.color_family==vs.GRAY 840 | if w==None and h==None:raise ValueError 841 | if w==None and isinstance(h,int):w=int(h*(srcw/srch)) 842 | if isinstance(w,int) and h==None:h=int(w*(srch/srcw)) 843 | if nns2==None:nns2=nns 844 | if nsize2==None:nsize2=nsize 845 | if qual2==None:qual2=qual 846 | if pscrn2==None:pscrn2=pscrn 847 | if mopf==None:mopf=lambda x:xvs.inpand(xvs.expand(x,cycle=2),cycle=2) 848 | post_kernel=eval(f'core.resize.{post_kernel.capitalize()}') if not callable(post_kernel) else post_kernel 849 | down_kernel=(post_kernel if not callable(custom_nnedi3down) else custom_nnedi3down) if down_kernel==None else down_kernel 850 | down_kernel=eval(f'core.resize.{down_kernel.capitalize()}') if not callable(down_kernel) else down_kernel 851 | tin='1886' if args.get("tin") is None else args.get("tin") 852 | fulls=False if args.get("fulls") is None else args.get("fulls") 853 | fulld=True if args.get("fulld") is None else args.get("fulld") 854 | 855 | luma=xvs.getY(last) if not isgray else last 856 | if isinstance(mask_gen_clip,vs.VideoNode): 857 | luma=core.std.Interleave([luma,xvs.getY(mask_gen_clip)]) 858 | if sigmoid: 859 | luma=core.fmtc.transfer(luma,transs=tin,transd='sigmoid',fulls=fulls,fulld=fulld) 860 | elif linear: 861 | luma=core.fmtc.transfer(luma,transs=tin,transd='linear',fulls=fulls,fulld=fulld) 862 | luma32=luma.fmtc.bitdepth(bits=32) 863 | 864 | bct='b=b,c=c' if kernel.lower()=='bicubic' else 'taps=taps' if kernel.lower()=='lanczos' else '' 865 | luma_de=eval(f'core.descale.De{kernel.lower()}(luma32,{w},{h},src_top=-offst1,src_left=-offsl1,border_handling=border_handling,ignore_mask=ignore_mask,{bct})') 866 | luma_de2=eval(f'core.descale.De{kernel.lower()}(luma32,{w},{h},src_top=offst1,src_left=offsl1,border_handling=border_handling,ignore_mask=ignore_mask,{bct})') 867 | # luma_de=core.descale.Descale(luma32,w,h,kernel=kernel,b=b,c=c,taps=taps,src_top=-offst1,src_left=-offsl1) 868 | # luma_de2=core.descale.Descale(luma32,w,h,kernel=kernel,b=b,c=c,taps=taps,src_top=offst1,src_left=offsl1) 869 | resize_params=f'filter_param_a={b},filter_param_b={c},'if kernel=='bicubic'else f'filter_param_a={taps},'if kernel=='lanczos'else'' 870 | luma_up=eval(f'core.resize.{kernel.capitalize()}(luma_de,{srcw},{srch},{resize_params}src_top=-offst1,src_left=-offsl1).fmtc.bitdepth(bits=16,dmode=1)') 871 | 872 | if isinstance(mask_gen_clip,vs.VideoNode): 873 | mclip=xvs.getY(mask_gen_clip) 874 | mclip_up=luma_up[1::2] 875 | luma=luma[::2] 876 | luma_de=luma_de[::2] 877 | luma_de2=luma_de2[::2] 878 | luma_up=luma_up[::2] 879 | ### 880 | blk=core.std.BlankClip(luma_de,color=0) 881 | bmask=bordermask(blk,*[rim]*4,32) 882 | luma_de1=luma_de.std.Crop(right=cuth,bottom=cutv).std.AddBorders(left=cuth,top=cutv,color=0) 883 | luma_de2=luma_de2.std.Crop(left=cuth,top=cutv).std.AddBorders(right=cuth,bottom=cutv,color=0) 884 | luma_de1=core.std.MaskedMerge(blk,luma_de1,bmask) 885 | luma_de2=core.std.MaskedMerge(blk,luma_de2,bmask) 886 | 887 | if sigmoid: 888 | luma_de=core.fmtc.transfer(luma_de.fmtc.bitdepth(bits=16),transs='sigmoid',transd=tin,fulls=fulld,fulld=fulls) 889 | luma_de1=core.fmtc.transfer(luma_de1.fmtc.bitdepth(bits=16),transs='sigmoid',transd=tin,fulls=fulld,fulld=fulls) 890 | luma_de2=core.fmtc.transfer(luma_de2.fmtc.bitdepth(bits=16),transs='sigmoid',transd=tin,fulls=fulld,fulld=fulls) 891 | elif linear: 892 | luma_de=core.fmtc.transfer(luma_de.fmtc.bitdepth(bits=16),transs='linear',transd=tin,fulls=fulld,fulld=fulls) 893 | luma_de1=core.fmtc.transfer(luma_de1.fmtc.bitdepth(bits=16),transs='linear',transd=tin,fulls=fulld,fulld=fulls) 894 | luma_de2=core.fmtc.transfer(luma_de2.fmtc.bitdepth(bits=16),transs='linear',transd=tin,fulls=fulld,fulld=fulls) 895 | 896 | luma_rescale1=Nnrs.nnedi3_dh(luma_de1,mode=nnrs_mode_default,nns=nns2,nsize=nsize2,qual=qual2,pscrn=pscrn2,field=0).std.Transpose() 897 | luma_rescale1=Nnrs.nnedi3_dh(luma_rescale1,mode=nnrs_mode_default,nns=nns2,nsize=nsize2,qual=qual2,pscrn=pscrn2,field=0).std.Transpose() 898 | luma_rescale1=down_kernel(luma_rescale1,srcw,srch) 899 | luma_rescale2=Nnrs.nnedi3_dh(luma_de2,mode=nnrs_mode_default,nns=nns2,nsize=nsize2,qual=qual2,pscrn=pscrn2,field=1).std.Transpose() 900 | luma_rescale2=Nnrs.nnedi3_dh(luma_rescale2,mode=nnrs_mode_default,nns=nns2,nsize=nsize2,qual=qual2,pscrn=pscrn2,field=1).std.Transpose() 901 | luma_rescale2=down_kernel(luma_rescale2,srcw,srch) 902 | luma_rescale1=post_kernel(luma_rescale1,src_left=offsl2,src_top=offst2,src_width=srcw,src_height=srch) 903 | luma_rescale2=post_kernel(luma_rescale2,src_left=-offsl2,src_top=-offst2,src_width=srcw,src_height=srch) 904 | luma_edge=core.std.MaskedMerge(luma_rescale1,luma_rescale2,bordermask(luma,t=border,l=border,d=32)).fmtc.bitdepth(bits=16) 905 | 906 | miss_mask=core.akarin.Expr(luma,f"X {srcw-border-1} > Y {border} < and X {border} < Y {srch-border-1} > and or 65535 0 ?") 907 | ### 908 | if show=='border': 909 | luma_rescale=luma 910 | elif callable(custom_nnedi3down): 911 | luma_rescale=Nnrs.nnedi3_resample(luma_de,luma_de.width*2,luma_de.height*2,qual=qual,nsize=nsize,nns=nns,pscrn=pscrn,src_top=-offst1,src_left=-offsl1) 912 | luma_rescale=custom_nnedi3down(luma_rescale,srcw,srch).fmtc.bitdepth(bits=16) 913 | else: 914 | luma_rescale=Nnrs.nnedi3_resample(luma_de,srcw,srch,qual=qual,nsize=nsize,nns=nns,pscrn=pscrn,src_top=-offst1,src_left=-offsl1).fmtc.bitdepth(bits=16) 915 | luma_rescale=core.std.MaskedMerge(luma_rescale,luma_edge,bordermask(luma,*[border]*4)) 916 | 917 | luma_fixedge=core.edgefixer.Continuity(luma,left=bc,right=bc,top=bc,bottom=bc,radius=rc) 918 | luma_rescale=core.std.MaskedMerge(luma_rescale,luma_fixedge,miss_mask) 919 | 920 | if mask: 921 | if not isinstance(mask_gen_clip,vs.VideoNode): 922 | mclip,mclip_up=luma,luma_up 923 | mask=core.std.Expr([mclip,mclip_up],"x y - abs").std.Binarize(mask_dif_pix*256) 924 | mask=core.std.Crop(mask,*[border]*4).std.AddBorders(*[border]*4,color=0) 925 | mask=mopf(mask) 926 | if show=='mask': return mask 927 | if show=='miss_mask': return miss_mask 928 | if show=='descale': return luma_de 929 | if show=='descale1': return luma_de1 930 | if show=='descale2': return luma_de2 931 | 932 | luma_rescale=core.std.MaskedMerge(luma_rescale,luma,mask) 933 | last=core.std.ShufflePlanes([luma_rescale,last],[0,1,2],vs.YUV) if not isgray else luma_rescale 934 | return last 935 | #sorry 936 | rattub=rescaleandtrytounfuckborders 937 | 938 | #for no reason 939 | def isvse(): 940 | return sys.executable.find('vsedit')!=-1 941 | def isvspipe(): 942 | return sys.executable.find('vspipe')!=-1 943 | 944 | #fake mvtools fps 945 | def fmvfps(src,num=60,den=1,blend=True): 946 | _fn=src.num_frames 947 | _d=core.std.BlankClip(src,length=1) 948 | sup=core.mv.Super(_d,pel=1,levels=1)*_fn 949 | mv=core.mv.Analyse(sup,isb=True,truemotion=False,levels=1)[0]*_fn 950 | mv2=core.mv.Analyse(sup,truemotion=False,levels=1)[0]*_fn 951 | return core.mv.BlockFPS(src,sup,mv,mv2,num,den,mode=0,blend=blend) 952 | 953 | #it's a helper 954 | def hrife(src,ref=None,mode=None,m='709',format=None,rgbh=True,base=64,pad=1,color=None,resizer=None): 955 | from math import ceil 956 | if ref is None:ref=src 957 | if format is None:format=ref.format 958 | if resizer is None:resizer=core.resize.Spline64 959 | s_w,s_h=ref.width,ref.height 960 | p_w,p_h=ceil(s_w/base)*base,ceil(s_h/base)*base 961 | if pad: 962 | if mode=='i' or src.format.color_family==vs.YUV: 963 | ret=setmatrix(src,'rm') 964 | ret=ret.std.AddBorders(0,p_w-s_w,0,p_h-s_h,color=color) 965 | ret=resizer(ret,format=[vs.RGBS,vs.RGBH][rgbh],matrix_in_s=m) 966 | elif mode=='o' or src.format.color_family==vs.RGB: 967 | ret=resizer(src,format=format,matrix_s=m) 968 | ret=ret.std.Crop(0,p_w-s_w,0,p_h-s_h) 969 | else: 970 | if mode=='i' or src.format.color_family==vs.YUV: 971 | ret=setmatrix(src,'rm') 972 | ret=resizer(ret,p_w,p_h,src_width=p_w,src_height=p_h,format=[vs.RGBS,vs.RGBH][rgbh],matrix_in_s=m) 973 | elif mode=='o' or src.format.color_family==vs.RGB: 974 | ret=resizer(src,s_w,s_h,src_width=s_w,src_height=s_h,format=format,matrix_s=m) 975 | return ret 976 | 977 | def go444keepuv(src,dir='down',clc=True,left=True,top=False,resampler=None): 978 | sw,sh=src.width,src.height 979 | ssw,ssh=src.format.subsampling_w,src.format.subsampling_h 980 | tw,th=sw>>ssw,sh>>ssh 981 | if resampler is None:resampler=lambda x,w,h,l,t:core.resize.Spline36(x,w,h,src_left=l,src_top=t) 982 | if dir.lower()=='down': 983 | luma=xvs.getY(src) 984 | luma=resampler(luma,tw,th,0,0) if not clc else resampler(luma,tw,th,-ssw/2 if left else 0,-ssh/2 if top else 0) 985 | return core.std.ShufflePlanes([luma,src],[0,1,2],vs.YUV) 986 | elif dir.lower()=='up': 987 | luma,u,v=xvs.extractPlanes(src) 988 | u=resampler(u,sw,sh,0,0) 989 | v=resampler(v,sw,sh,0,0) 990 | if clc:luma=resampler(luma,sw,sh,-ssw/2 if left else 0,-ssh/2 if top else 0) 991 | return core.std.ShufflePlanes([luma,u,v],[0,0,0],vs.YUV) 992 | 993 | 994 | def setrange(src,range): 995 | if range in ('remove','rm','del'): 996 | return src.std.RemoveFrameProps('_ColorRange') 997 | if range in ('full','pc','jpeg'): 998 | rangeval=0 999 | elif range in ('limited','tv','mpeg'): 1000 | rangeval=1 1001 | else: 1002 | raise ValueError 1003 | return src.std.SetFrameProps(_ColorRange=rangeval) 1004 | 1005 | 1006 | def setmatrix(src,matrix): 1007 | if matrix in ('remove','rm','del'): 1008 | return src.std.RemoveFrameProps('_Matrix') 1009 | if isinstance(matrix,int) and matrix>=0 and matrix<256: 1010 | return src.std.SetFrameProps(_Matrix=matrix) 1011 | matrixvaldict={'rgb':0,'709':1,'unspec':2,'fcc':4,'470bg':5,'170m':6,'240m':7,'ycgco':8,'2020ncl':9,'2020cl':10,'ydzdx':11,'chromancl':12,'chromacl':13,'ictcp':14,'601':5,709:1,601:5} 1012 | matrixval=matrixvaldict.get(matrix) 1013 | if matrixval==None: 1014 | raise ValueError 1015 | return src.std.SetFrameProps(_Matrix=matrixval) 1016 | 1017 | 1018 | def settransfer(src,transfer): 1019 | if transfer in ('remove','rm','del'): 1020 | return src.std.RemoveFrameProps('_Transfer') 1021 | if isinstance(transfer,int) and transfer>=0 and transfer<256: 1022 | return src.std.SetFrameProps(_Transfer=transfer) 1023 | transfervaldict={'709':1,'unspec':2,'470m':4,'470bg':5,'601':6,'240m':7,'linear':8,'log100':9,'log316':10,'xvycc':11,'srgb':13,'2020_10':14,'2020_12':15,'st2084':16,'st428':17,'std-b67':18,'2084':16,'pq':16,'hlg':18,709:1,601:6,2084:16} 1024 | transferval=transfervaldict.get(transfer) 1025 | if transferval==None: 1026 | raise ValueError 1027 | return src.std.SetFrameProps(_Transfer=transferval) 1028 | 1029 | 1030 | def setprimaries(src,primaries): 1031 | if primaries in ('remove','rm','del'): 1032 | return src.std.RemoveFrameProps('_Primaries') 1033 | if isinstance(primaries,int) and primaries>=0 and primaries<256: 1034 | return src.std.SetFrameProps(_Primaries=primaries) 1035 | primariesvaldict={'709':1,'unspec':2,'470m':4,'470bg':5,'170m':6,'240m':7,'film':8,'2020':9,'st428':10,'xyz':10,'st431-2':11,'st432-1':12,'jedec-p22':22,'p3dci':11,'p3d65':12,709:1,2020:9} 1036 | primariesval=primariesvaldict.get(primaries) 1037 | if primariesval==None: 1038 | raise ValueError 1039 | return src.std.SetFrameProps(_Primaries=primariesval) 1040 | 1041 | 1042 | def setchromaloc(src,chromaloc): 1043 | if chromaloc in ('remove','rm','del'): 1044 | return src.std.RemoveFrameProps('_ChromaLocation') 1045 | if isinstance(chromaloc,int) and chromaloc>=0 and chromaloc<6: 1046 | return src.std.SetFrameProps(_ChromaLocation=chromaloc) 1047 | chromalocvaldict={'left':0,'center':1,'centre':1,'topleft':2,'top left':2,'top':3,'bottomleft':4,'bottom left':4,'bottom':5} 1048 | chromalocval=chromalocvaldict.get(chromaloc) 1049 | if chromalocval==None: 1050 | return ValueError 1051 | return src.std.SetFrameProps(_ChromaLocation=chromalocval) 1052 | 1053 | 1054 | def setparams(src,range=None,matrix=None,transfer=None,primaries=None,chromaloc=None): 1055 | if range is not None: 1056 | src=setrange(src,range) 1057 | if matrix is not None: 1058 | src=setmatrix(src,matrix) 1059 | if transfer is not None: 1060 | src=settransfer(src,transfer) 1061 | if primaries is not None: 1062 | src=setprimaries(src,primaries) 1063 | if chromaloc is not None: 1064 | src=setchromaloc(src,chromaloc) 1065 | return src 1066 | 1067 | #just for fun 1068 | #but impulse mode is more accurate than gaussian blur functions provided by tcanny and bilateral in my book, most likely the border handling stuff, i dunno (but much slower at very large stdev (but faster at small stdev (< 9 on my machine))) 1069 | #impdr: impulse mode pre-downscale ratio, to tradeoff for some speed perhaps 1070 | def gaussianblurfmtc(src,sigma=1,stdev=None,mode='impulse',planes=[0,1,2],r=None,impext=3,impdr=1,kd='bilinear',rsa1=9,sci=False,dir='hv',is444=None): 1071 | import warnings 1072 | if stdev==None: stdev=sigma #lame alias approach 1073 | sw,sh=src.width,src.height 1074 | p0,p1,p2=[i in planes for i in (0,1,2)] 1075 | hb,vb='h' in dir,'v' in dir 1076 | sep='+' in dir and hb and vb 1077 | isgray=src.format.color_family==vs.GRAY 1078 | if not (p0 and p1 and p2) and not isgray: 1079 | original=src 1080 | if p0 and not p1 and not p2: 1081 | src=xvs.getY(src) 1082 | if mode=='resample': #by dnjulek at https://github.com/sekrit-twc/zimg/issues/186#issue-1462626153 1083 | if stdev<1: 1084 | warnings.warn('gaussianblurfmtc: resample mode will not behave normal with stdev < 1.') 1085 | dw,dh=round(sw/stdev) if hb else sw,round(sh/stdev) if vb else sh 1086 | last=core.fmtc.resample(src,dw,dh,kernel=kd,css='444') if stdev>1 else src 1087 | last=core.fmtc.resample(last,sw,sh,kernel='gauss',a1=rsa1,csp=src.format.replace(bits_per_sample=16),fv=-1,fh=-1) 1088 | elif mode=='impulse': 1089 | import math 1090 | if impdr<1: raise ValueError('impdr<1, don\'t do it bruh.') 1091 | dw,dh=round(sw/impdr) if hb else sw,round(sh/impdr) if vb else sh 1092 | stdev/=impdr 1093 | if is444==None: 1094 | is444=src.format.subsampling_w==src.format.subsampling_h==0 1095 | if not is444: dw,dh=round(dw/2)*2,round(dh/2)*2 1096 | r=math.ceil(max(1,stdev)*impext) if r==None else r 1097 | if sci: 1098 | import numpy as np 1099 | import scipy 1100 | gauss_imp=scipy.stats.norm.pdf(np.linspace(-r,r,1+2*r,dtype=np.int_),0,stdev) 1101 | else: 1102 | _gd=lambda x:math.exp(-.5*(x/stdev)**2)/(math.sqrt(math.pi*2)*stdev) 1103 | gauss_imp=[_gd(i) for i in range(r+1)] 1104 | gauss_imp=gauss_imp[::-1]+gauss_imp[1:] 1105 | last=core.fmtc.resample(src,dw,dh,kernel=kd) if impdr>1 else src 1106 | if sep: 1107 | last=core.fmtc.resample(last,sw,sh,kernel='impulse',fv=(-1)**vb,fh=1,impulse=gauss_imp,css=['420','444'][is444],kovrspl=[(1,2,2),1][is444]) 1108 | last=core.fmtc.resample(last,sw,sh,kernel='impulse',fv=1,fh=(-1)**hb,impulse=gauss_imp,css=['420','444'][is444],kovrspl=[(1,2,2),1][is444]) 1109 | else: 1110 | last=core.fmtc.resample(last,sw,sh,kernel='impulse',fv=(-1)**vb,fh=(-1)**hb,impulse=gauss_imp,css=['420','444'][is444],kovrspl=[(1,2,2),1][is444]) 1111 | else: 1112 | raise ValueError(f'what do you mean "{mode}"?') 1113 | if not (p0 and p1 and p2) and not isgray: 1114 | cage=(original,last) 1115 | last=core.std.ShufflePlanes([cage[p0],cage[p1],cage[p2]],[0,1,2],vs.YUV) 1116 | return last 1117 | #i haven't played this game, but... 1118 | #https://granbluefantasy.jp/ 1119 | gbf=gaussianblurfmtc 1120 | 1121 | #curved/cursed diff 1122 | def cdif(clipa,clipb,merge=False,p=16384,mode='sine',lb=10): 1123 | import math 1124 | import numpy as np 1125 | if not clipa.format.bits_per_sample==16: clipa=clipa.fmtc.bitdepth(bits=16) 1126 | if not clipb.format.bits_per_sample==16: clipb=clipb.fmtc.bitdepth(bits=16) 1127 | if not merge: 1128 | sign=core.std.Expr([clipa,clipb],'x y < 65535 0 ?') 1129 | difabs=core.std.Expr([clipa,clipb],'x y - abs') 1130 | if mode=='sine': 1131 | lut=[round(math.sin(math.pi/2*(i-p)/(65535-p))*(32767-p)+p) if i>p else i for i in range(65536)] 1132 | elif mode=='linear': 1133 | lut=[round((i-p)/(65535-p)*(32767-p)+p) if i>p else i for i in range(65536)] 1134 | elif mode=='log': 1135 | lut=[round(math.log((i-p)/(65535-p)*(lb-1)+1,lb)*(32767-p)+p) if i>p else i for i in range(65536)] 1136 | lut=np.clip(lut,0,65535) 1137 | difabs=core.std.Lut(difabs,lut=lut) 1138 | dif=core.std.Expr([difabs,sign],'y 0 > 32768 x - 32768 x + ?') 1139 | return dif 1140 | else: 1141 | difabs=core.std.Expr(clipb,'x 32768 - abs') 1142 | if mode=='sine': 1143 | lut=[round(math.asin((i-p)/(32767-p))/(math.pi/2)*(65535-p))+p if i>p else i for i in range(32768)]+[0]*32768 1144 | elif mode=='linear': 1145 | lut=[round((i-p)/(32767-p)*(65535-p)+p) if i>p else i for i in range(32768)]+[0]*32768 1146 | elif mode=='log': 1147 | lut=[round((math.pow(lb,(i-p)/(32767-p))-1)/(lb-1)*(65535-p))+p if i>p else i for i in range(32768)]+[0]*32768 1148 | lut=np.clip(lut,0,65535) 1149 | difabs=core.std.Lut(difabs,lut=lut) 1150 | asdf='-+' if merge>0 else '+-' 1151 | merged=core.std.Expr([clipa,difabs,clipb],f'z 32768 < x y {asdf[0]} x y {asdf[1]} ?') 1152 | return merged 1153 | Corps_Diplomatique_of_Interstellar_Ferrets=cdif 1154 | #what? 1155 | 1156 | def plotcdif(merge=False,p=16384,mode='sine',lb=10): 1157 | import math 1158 | import matplotlib.pyplot as plt 1159 | if not merge: 1160 | if mode=='sine': 1161 | lut=[round(math.sin(math.pi/2*(i-p)/(65535-p))*(32767-p)+p) if i>p else i for i in range(65536)] 1162 | elif mode=='linear': 1163 | lut=[round((i-p)/(65535-p)*(32767-p)+p) if i>p else i for i in range(65536)] 1164 | elif mode=='log': 1165 | lut=[round(math.log((i-p)/(65535-p)*(lb-1)+1,lb)*(32767-p)+p) if i>p else i for i in range(65536)] 1166 | else: 1167 | if mode=='sine': 1168 | lut=[round(math.asin((i-p)/(32767-p))/(math.pi/2)*(65535-p))+p if i>p else i for i in range(32768)] 1169 | elif mode=='linear': 1170 | lut=[round((i-p)/(32767-p)*(65535-p)+p) if i>p else i for i in range(32768)] 1171 | elif mode=='log': 1172 | lut=[round((math.pow(lb,(i-p)/(32767-p))-1)/(lb-1)*(65535-p))+p if i>p else i for i in range(32768)] 1173 | plt.plot(lut) 1174 | plt.show() 1175 | 1176 | 1177 | def alpha2clip(src): 1178 | return core.std.PropToClip(src,'_Alpha') 1179 | 1180 | 1181 | def addsc(src,framelist=[],listfile=None,dir='next'): 1182 | if isinstance(listfile,(str,os.PathLike)): 1183 | with open(listfile,'r') as lf: 1184 | framelist=lf.read().split() 1185 | framelist=[int(i) for i in framelist] 1186 | if dir=='next': 1187 | def mod(n,f): 1188 | fout=f.copy() 1189 | if n in framelist: 1190 | fout.props._SceneChangeNext=1 1191 | return fout 1192 | elif dir=='prev': 1193 | def mod(n,f): 1194 | fout=f.copy() 1195 | if n in framelist: 1196 | fout.props._SceneChangePrev=1 1197 | return fout 1198 | return core.std.ModifyFrame(src,src,mod) 1199 | 1200 | #difference of gaussians, basic stuff 1201 | def DoG(src,s1=1,s2=2,grayscale=True,abs=True): 1202 | if grayscale: 1203 | src=src.std.ShufflePlanes(0,vs.GRAY) 1204 | g1=gbf(src,s1) 1205 | g2=gbf(src,s2) 1206 | expr='x y -' + (' abs' if abs else '') 1207 | if abs: 1208 | return core.std.Expr([g1,g2],expr) 1209 | else: 1210 | return core.std.Expr([g1,g2],expr,g1.format.replace(sample_type=vs.FLOAT,bits_per_sample=32)) 1211 | #alias 1212 | dog=DoG 1213 | 1214 | # random is a predefined static blue noise pattern, not really random. which is good <3 1215 | def simplebitdepth(src,bits,dither=None,float=None): 1216 | if float is None: 1217 | if bits==32: 1218 | float=True 1219 | else: 1220 | float=False 1221 | if isinstance(dither,int): 1222 | dither={0:'none',1:'ordered',2:'random',3:'error_diffusion'}[dither] 1223 | sb=src.format.bits_per_sample 1224 | sst=src.format.sample_type 1225 | dst=(vs.INTEGER,vs.FLOAT)[float] #gocha 1226 | if dither is None: 1227 | dither='none' 1228 | if bits0 1316 | 1317 | if sigma2 is None: 1318 | sigma2=sigma 1319 | 1320 | if preset2 is None: 1321 | preset2=preset 1322 | 1323 | if preset not in ["fast","fastm","lc","lcm","np","npm","high","highm"] or preset2 not in ["fast","fastm","lc","lcm","np","npm","high","highm"]: 1324 | raise ValueError("preset and preset2 must be 'fast','fastm','lc','lcm','np','npm','highm',or'high'") 1325 | 1326 | parmas1={ 1327 | #block_step,bm_range, ps_num, ps_range 1328 | "fast":[8,9,2,4], 1329 | "fastm":[7,9,2,4], 1330 | "lc" :[6,9,2,4], 1331 | "lcm" :[5,9,2,4], 1332 | "np" :[4,16,2,5], 1333 | "npm" :[3,16,2,5], 1334 | "high":[3,16,2,7], 1335 | "highm":[2,16,2,7], 1336 | } 1337 | 1338 | vparmas1={ 1339 | #block_step,bm_range, ps_num, ps_range 1340 | "fast":[8,7,2,4], 1341 | "fastm":[7,7,2,4], 1342 | "lc" :[6,9,2,4], 1343 | "lcm" :[5,9,2,4], 1344 | "np" :[4,12,2,5], 1345 | "npm" :[3,12,2,5], 1346 | "high":[3,16,2,7], 1347 | "highm":[2,16,2,7], 1348 | } 1349 | 1350 | parmas2={ 1351 | #block_step,bm_range, ps_num, ps_range 1352 | "fast":[7,9,2,5], 1353 | "fastm":[8,9,2,5], 1354 | "lc" :[5,9,2,5], 1355 | "lcm" :[6,9,2,5], 1356 | "np" :[3,16,2,6], 1357 | "npm" :[4,16,2,6], 1358 | "high":[2,16,2,8], 1359 | "highm":[3,16,2,8], 1360 | } 1361 | 1362 | vparmas2={ 1363 | #block_step,bm_range, ps_num, ps_range 1364 | "fast":[7,7,2,5], 1365 | "fastm":[8,7,2,5], 1366 | "lc" :[5,9,2,5], 1367 | "lcm" :[6,9,2,5], 1368 | "np" :[3,12,2,6], 1369 | "npm" :[4,12,2,6], 1370 | "high":[2,16,2,8], 1371 | "highm":[3,16,2,8], 1372 | } 1373 | 1374 | 1375 | if isvbm3d: 1376 | p1,p2=vparmas1,vparmas2 1377 | else: 1378 | p1,p2=parmas1,parmas2 1379 | 1380 | 1381 | block_step1=p1[preset][0] if block_step1 is None else block_step1 1382 | bm_range1=p1[preset][1] if bm_range1 is None else bm_range1 1383 | ps_num1=p1[preset][2] if ps_num1 is None else ps_num1 1384 | ps_range1=p1[preset][3] if ps_range1 is None else ps_range1 1385 | 1386 | block_step2=p2[preset2][0] if block_step2 is None else block_step2 1387 | bm_range2=p2[preset2][1] if bm_range2 is None else bm_range2 1388 | ps_num2=p2[preset2][2] if ps_num2 is None else ps_num2 1389 | ps_range2=p2[preset2][3] if ps_range2 is None else ps_range2 1390 | 1391 | if iterates: 1392 | outputs=list() 1393 | if isvbm3d: 1394 | flt=bm3d_core(clip,ref=iref,mode=mode,sigma=sigma,radius=radius,block_step=block_step1,bm_range=bm_range1,ps_num=ps_num1,ps_range=ps_range1,chroma=chroma,fast=fast,extractor_exp=extractor_exp,device_id=device_id,bm_error_s=bm_error_s,transform_2d_s=transform_2d_s,transform_1d_s=transform_1d_s,vt=vt) 1395 | if radius>0 and vt==0: 1396 | flt=core.bm3d.VAggregate(flt,radius=radius,sample=1) 1397 | if iterates: 1398 | outputs.append(core.fmtc.bitdepth(flt,bits=bits,dmode=dmode) if not keepfloat else flt) 1399 | 1400 | for i in range(refine): 1401 | flt=bm3d_core(clip,ref=flt,mode=mode,sigma=sigma2,radius=radius2,block_step=block_step2,bm_range=bm_range2,ps_num=ps_num2,ps_range=ps_range2,chroma=chroma,fast=fast,extractor_exp=extractor_exp,device_id=device_id,bm_error_s=bm_error_s,transform_2d_s=transform_2d_s,transform_1d_s=transform_1d_s,vt=vt) 1402 | if radius2>0 and vt==0: 1403 | flt=core.bm3d.VAggregate(flt,radius=radius2,sample=1) 1404 | if iterates: 1405 | outputs.append(core.fmtc.bitdepth(flt,bits=bits,dmode=dmode) if not keepfloat else flt) 1406 | 1407 | else: 1408 | flt=bm3d_core(clip,ref=iref,mode=mode,sigma=sigma,radius=radius,block_step=block_step1,bm_range=bm_range1,ps_num=ps_num1,ps_range=ps_range1,chroma=chroma,fast=fast,extractor_exp=extractor_exp,device_id=device_id,bm_error_s=bm_error_s,transform_2d_s=transform_2d_s,transform_1d_s=transform_1d_s,vt=vt) 1409 | if iterates: 1410 | outputs.append(core.fmtc.bitdepth(flt,bits=bits,dmode=dmode) if not keepfloat else flt) 1411 | 1412 | for i in range(refine): 1413 | flt=bm3d_core(clip,ref=flt,mode=mode,sigma=sigma2,radius=radius2,block_step=block_step2,bm_range=bm_range2,ps_num=ps_num2,ps_range=ps_range2,chroma=chroma,fast=fast,extractor_exp=extractor_exp,device_id=device_id,bm_error_s=bm_error_s,transform_2d_s=transform_2d_s,transform_1d_s=transform_1d_s,vt=vt) 1414 | if iterates: 1415 | outputs.append(core.fmtc.bitdepth(flt,bits=bits,dmode=dmode) if not keepfloat else flt) 1416 | 1417 | if iterates: 1418 | return outputs 1419 | elif keepfloat: 1420 | return flt 1421 | else: 1422 | return core.fmtc.bitdepth(flt,bits=bits,dmode=dmode) 1423 | 1424 | #copy-paste from xyx98's xvs 1425 | def bm3d_core(clip,ref=None,mode="cpu",sigma=3.0,block_step=8,bm_range=9,radius=0,ps_num=2,ps_range=4,chroma=False,fast=True,extractor_exp=bm3d_extractor_exp_default,device_id=0,bm_error_s="SSD",transform_2d_s="DCT",transform_1d_s="DCT",vt=0): 1426 | if chroma and clip.format.id !=vs.YUV444PS: 1427 | if clip.format.color_family!=vs.YUV: 1428 | raise ValueError("YUV should be used with 'chroma'") 1429 | clip_down=go444keepuv(clip) 1430 | ref_down=go444keepuv(ref) if ref!=None else None 1431 | chroma_fullres=False 1432 | else: 1433 | chroma_fullres=chroma 1434 | 1435 | if mode not in ["cpu","cuda","cuda_rtc"]: 1436 | raise ValueError("mode must be cpu,or cuda,or cuda_rtc") 1437 | elif mode=="cpu": 1438 | if vt==1: 1439 | fullres=core.bm3dcpu.BM3Dv2(clip,ref=ref,sigma=sigma,block_step=block_step,bm_range=bm_range,radius=radius,ps_num=ps_num,ps_range=ps_range,chroma=chroma_fullres) 1440 | else: 1441 | fullres=core.bm3dcpu.BM3D(clip,ref=ref,sigma=sigma,block_step=block_step,bm_range=bm_range,radius=radius,ps_num=ps_num,ps_range=ps_range,chroma=chroma_fullres) 1442 | elif mode=="cuda": 1443 | if vt==1: 1444 | fullres=core.bm3dcuda.BM3Dv2(clip,ref=ref,sigma=sigma,block_step=block_step,bm_range=bm_range,radius=radius,ps_num=ps_num,ps_range=ps_range,chroma=chroma_fullres,fast=fast,extractor_exp=extractor_exp,device_id=device_id) 1445 | else: 1446 | fullres=core.bm3dcuda.BM3D(clip,ref=ref,sigma=sigma,block_step=block_step,bm_range=bm_range,radius=radius,ps_num=ps_num,ps_range=ps_range,chroma=chroma_fullres,fast=fast,extractor_exp=extractor_exp,device_id=device_id) 1447 | else: 1448 | if vt==1: 1449 | fullres=core.bm3dcuda_rtc.BM3Dv2(clip,ref=ref,sigma=sigma,block_step=block_step,bm_range=bm_range,radius=radius,ps_num=ps_num,ps_range=ps_range,chroma=chroma_fullres,fast=fast,extractor_exp=extractor_exp,device_id=device_id,bm_error_s=bm_error_s,transform_2d_s=transform_2d_s,transform_1d_s=transform_1d_s) 1450 | else: 1451 | fullres=core.bm3dcuda_rtc.BM3D(clip,ref=ref,sigma=sigma,block_step=block_step,bm_range=bm_range,radius=radius,ps_num=ps_num,ps_range=ps_range,chroma=chroma_fullres,fast=fast,extractor_exp=extractor_exp,device_id=device_id,bm_error_s=bm_error_s,transform_2d_s=transform_2d_s,transform_1d_s=transform_1d_s) 1452 | 1453 | if chroma and clip.format.id !=vs.YUV444PS: 1454 | if clip.format.color_family!=vs.YUV: 1455 | raise ValueError("YUV should be used with 'chroma'") 1456 | chroma_clip=bm3d_core(clip_down,ref_down,mode,sigma,block_step,bm_range,radius,ps_num,ps_range,chroma,fast,extractor_exp,device_id,bm_error_s,transform_2d_s,transform_1d_s,vt) 1457 | ret=core.std.ShufflePlanes([fullres,chroma_clip],[0,1,2],vs.YUV) 1458 | else: 1459 | ret=fullres 1460 | 1461 | return ret 1462 | 1463 | #copy-paste from xyx98's xvs with some modification 1464 | #new feature 1465 | #mask_gen_clip: an alternative clip can be provided for diff mask generation 1466 | #mask_operate_func: a function can be specified for mask operations after generation (e.g. expand, inpand and more) 1467 | #linear, sigmoid: do descale in linear or sigmoid light 1468 | def rescale(src:vs.VideoNode,kernel:str,w=None,h=None,mask=True,mask_dif_pix=2,show="result",postfilter_descaled=None,mthr:list[int]=[2,2],mask_gen_clip=None,mask_operate_func=None,linear=False,sigmoid=False,custom_nnedi3down=False,**args): 1469 | if src.format.color_family not in [vs.YUV,vs.GRAY]: 1470 | raise ValueError("input clip should be YUV or GRAY!") 1471 | 1472 | src_h,src_w=src.height,src.width 1473 | if w is None and h is None: 1474 | w,h=1280,720 1475 | elif w is None: 1476 | w=int(h*src_w/src_h) 1477 | else: 1478 | h=int(w*src_h/src_w) 1479 | 1480 | if w>=src_w or h>=src_h: 1481 | raise ValueError("w,h should less than input resolution") 1482 | 1483 | kernel=kernel.strip().capitalize() 1484 | if kernel not in ["Debilinear","Debicubic","Delanczos","Despline16","Despline36","Despline64"]: 1485 | raise ValueError("unsupport kernel") 1486 | 1487 | src=core.fmtc.bitdepth(src,bits=16) 1488 | luma=xvs.getY(src) 1489 | tin='1886' if args.get("tin") is None else args.get("tin") 1490 | fulls=False if args.get("fulls") is None else args.get("fulls") 1491 | fulld=True if args.get("fulld") is None else args.get("fulld") 1492 | border_handling=args.get("border_handling",0) 1493 | ignore_mask=args.get("ignore_mask") 1494 | if isinstance(mask_gen_clip,vs.VideoNode): 1495 | luma=core.std.Interleave([luma,xvs.getY(mask_gen_clip)]) 1496 | if sigmoid: 1497 | luma=core.fmtc.transfer(luma,transs=tin,transd='sigmoid',fulls=fulls,fulld=fulld) 1498 | elif linear: 1499 | luma=core.fmtc.transfer(luma,transs=tin,transd='linear',fulls=fulls,fulld=fulld) 1500 | #### 1501 | if kernel in ["Debilinear","Despline16","Despline36","Despline64"]: 1502 | luma_de=eval("core.descale.{k}(luma.fmtc.bitdepth(bits=32),w,h,border_handling=border_handling,ignore_mask=ignore_mask)".format(k=kernel)) 1503 | luma_up=eval("core.resize.{k}(luma_de,src_w,src_h)".format(k=kernel[2:].capitalize())).fmtc.bitdepth(bits=16,dmode=1) 1504 | elif kernel=="Debicubic": 1505 | luma_de=core.descale.Debicubic(luma.fmtc.bitdepth(bits=32),w,h,border_handling=border_handling,ignore_mask=ignore_mask,b=args.get("b"),c=args.get("c")) 1506 | luma_up=core.resize.Bicubic(luma_de,src_w,src_h,filter_param_a=args.get("b"),filter_param_b=args.get("c")).fmtc.bitdepth(bits=16,dmode=1) 1507 | else: 1508 | luma_de=core.descale.Delanczos(luma.fmtc.bitdepth(bits=32),w,h,border_handling=border_handling,ignore_mask=ignore_mask,taps=args.get("taps")) 1509 | luma_up=core.resize.Lanczos(luma_de,src_w,src_h,filter_param_a=args.get("taps")).fmtc.bitdepth(bits=16,dmode=1) 1510 | 1511 | if isinstance(mask_gen_clip,vs.VideoNode): 1512 | mclip=xvs.getY(mask_gen_clip) 1513 | mclip_up=luma_up[1::2] 1514 | luma=luma[::2] 1515 | luma_de=luma_de[::2] 1516 | luma_up=luma_up[::2] 1517 | 1518 | if postfilter_descaled is None: 1519 | pass 1520 | elif callable(postfilter_descaled): 1521 | luma_de=postfilter_descaled(luma_de) 1522 | else: 1523 | raise ValueError("postfilter_descaled must be a function") 1524 | 1525 | nsize=1 if args.get("nsize") is None else args.get("nsize")#keep behavior before 1526 | nns=args.get("nns") 1527 | qual=2 if args.get("qual") is None else args.get("qual")#keep behavior before 1528 | etype=args.get("etype") 1529 | pscrn=1 if args.get("pscrn") is None else args.get("pscrn") 1530 | exp=args.get("exp") 1531 | mode=nnrs_mode_default if args.get("mode") is None else args.get("mode") 1532 | 1533 | if sigmoid: 1534 | luma_de=core.fmtc.transfer(luma_de.fmtc.bitdepth(bits=16),transs='sigmoid',transd=tin,fulls=fulld,fulld=fulls) 1535 | elif linear: 1536 | luma_de=core.fmtc.transfer(luma_de.fmtc.bitdepth(bits=16),transs='linear',transd=tin,fulls=fulld,fulld=fulls) 1537 | if callable(custom_nnedi3down): 1538 | luma_rescale=nnrs.nnedi3_resample(luma_de,luma_de.width*2,luma_de.height*2,nsize=nsize,nns=nns,qual=qual,etype=etype,pscrn=pscrn,exp=exp,mode=mode) 1539 | luma_rescale=custom_nnedi3down(luma_rescale,src_w,src_h).fmtc.bitdepth(bits=16) 1540 | else: 1541 | luma_rescale=nnrs.nnedi3_resample(luma_de,src_w,src_h,nsize=nsize,nns=nns,qual=qual,etype=etype,pscrn=pscrn,exp=exp,mode=mode).fmtc.bitdepth(bits=16) 1542 | 1543 | if mask: 1544 | if not isinstance(mask_gen_clip,vs.VideoNode): 1545 | mclip,mclip_up=luma,luma_up 1546 | mask=core.std.Expr([mclip,mclip_up],"x y - abs").std.Binarize(mask_dif_pix*256) 1547 | if callable(mask_operate_func): 1548 | mask=mask_operate_func(mask) 1549 | else: 1550 | mask=xvs.expand(mask,cycle=mthr[0]) 1551 | mask=xvs.inpand(mask,cycle=mthr[1]) 1552 | 1553 | luma_rescale=core.std.MaskedMerge(luma_rescale,xvs.getY(src),mask) 1554 | 1555 | if show=="descale": 1556 | return luma_de 1557 | elif show=="upscale": 1558 | return luma_up 1559 | elif show=="mask": 1560 | return mask 1561 | elif show=="both": 1562 | return luma_de,mask 1563 | 1564 | if src.format.color_family==vs.GRAY: 1565 | return luma_rescale 1566 | else: 1567 | return core.std.ShufflePlanes([luma_rescale,src],[0,1,2],vs.YUV) 1568 | 1569 | #copy-paste from xyx98's xvs with some modification 1570 | def rescalef(src: vs.VideoNode,kernel: str,w=None,h=None,bh=None,bw=None,mask=True,mask_dif_pix=2,show="result",postfilter_descaled=None,selective=False,upper=0.0001,lower=0.00001,mthr:list[int]=[2,2],mask_gen_clip=None,mask_operate_func=None,linear=False,sigmoid=False,custom_nnedi3down=False,**args): 1571 | #for decimal resolution descale,refer to GetFnative 1572 | if src.format.color_family not in [vs.YUV,vs.GRAY]: 1573 | raise ValueError("input clip should be YUV or GRAY!") 1574 | 1575 | src_h,src_w=src.height,src.width 1576 | if w is None and h is None: 1577 | w,h=1280,720 1578 | elif w is None: 1579 | w=int(h*src_w/src_h) 1580 | else: 1581 | h=int(w*src_h/src_w) 1582 | 1583 | if bh is None: 1584 | bh=1080 1585 | 1586 | if w>=src_w or h>=src_h: 1587 | raise ValueError("w,h should less than input resolution") 1588 | 1589 | kernel=kernel.strip().capitalize() 1590 | if kernel not in ["Debilinear","Debicubic","Delanczos","Despline16","Despline36","Despline64"]: 1591 | raise ValueError("unsupport kernel") 1592 | 1593 | src=core.fmtc.bitdepth(src,bits=16) 1594 | luma=xvs.getY(src) 1595 | tin='1886' if args.get("tin") is None else args.get("tin") 1596 | fulls=False if args.get("fulls") is None else args.get("fulls") 1597 | fulld=True if args.get("fulld") is None else args.get("fulld") 1598 | border_handling=args.get("border_handling",0) 1599 | ignore_mask=args.get("ignore_mask") 1600 | if isinstance(mask_gen_clip,vs.VideoNode): 1601 | luma=core.std.Interleave([luma,xvs.getY(mask_gen_clip)]) 1602 | if sigmoid: 1603 | luma=core.fmtc.transfer(luma,transs=tin,transd='sigmoid',fulls=fulls,fulld=fulld) 1604 | elif linear: 1605 | luma=core.fmtc.transfer(luma,transs=tin,transd='linear',fulls=fulls,fulld=fulld) 1606 | cargs=xvs.cropping_args(src.width,src.height,h,bh,bw) 1607 | #### 1608 | if kernel in ["Debilinear","Despline16","Despline36","Despline64"]: 1609 | luma_de=eval("core.descale.{k}(luma.fmtc.bitdepth(bits=32),border_handling=border_handling,ignore_mask=ignore_mask,**cargs.descale_gen())".format(k=kernel)) 1610 | luma_up=eval("core.resize.{k}(luma_de,**cargs.resize_gen())".format(k=kernel[2:].capitalize())) 1611 | elif kernel=="Debicubic": 1612 | luma_de=core.descale.Debicubic(luma.fmtc.bitdepth(bits=32),border_handling=border_handling,ignore_mask=ignore_mask,b=args.get("b"),c=args.get("c"),**cargs.descale_gen()) 1613 | luma_up=core.resize.Bicubic(luma_de,filter_param_a=args.get("b"),filter_param_b=args.get("c"),**cargs.resize_gen()) 1614 | else: 1615 | luma_de=core.descale.Delanczos(luma.fmtc.bitdepth(bits=32),border_handling=border_handling,ignore_mask=ignore_mask,taps=args.get("taps"),**cargs.descale_gen()) 1616 | luma_up=core.resize.Lanczos(luma_de,filter_param_a=args.get("taps"),**cargs.resize_gen())# 1617 | 1618 | if isinstance(mask_gen_clip,vs.VideoNode): 1619 | mclip=xvs.getY(mask_gen_clip) 1620 | mclip_up=luma_up[1::2] 1621 | luma=luma[::2] 1622 | luma_de=luma_de[::2] 1623 | luma_up=luma_up[::2] 1624 | 1625 | diff = core.std.Expr([luma.fmtc.bitdepth(bits=32), luma_up], f'x y - abs dup 0.015 > swap 0 ?').std.Crop(10, 10, 10, 10).std.PlaneStats() 1626 | 1627 | if postfilter_descaled is None: 1628 | pass 1629 | elif callable(postfilter_descaled): 1630 | luma_de=postfilter_descaled(luma_de) 1631 | else: 1632 | raise ValueError("postfilter_descaled must be a function") 1633 | 1634 | nsize=1 if args.get("nsize") is None else args.get("nsize")#keep behavior before 1635 | nns=args.get("nns") 1636 | qual=2 if args.get("qual") is None else args.get("qual")#keep behavior before 1637 | etype=args.get("etype") 1638 | pscrn=1 if args.get("pscrn") is None else args.get("pscrn") 1639 | exp=args.get("exp") 1640 | mode=nnrs_mode_default if args.get("mode") is None else args.get("mode") 1641 | 1642 | if sigmoid: 1643 | luma_de=core.fmtc.transfer(luma_de.fmtc.bitdepth(bits=16),transs='sigmoid',transd=tin,fulls=fulld,fulld=fulls) 1644 | elif linear: 1645 | luma_de=core.fmtc.transfer(luma_de.fmtc.bitdepth(bits=16),transs='linear',transd=tin,fulls=fulld,fulld=fulls) 1646 | if callable(custom_nnedi3down): 1647 | _cargs=cargs.nnrs_gen() 1648 | del _cargs['target_width'],_cargs['target_height'] 1649 | luma_rescale=nnrs.nnedi3_resample(luma_de,luma_de.width*2,luma_de.height*2,nsize=nsize,nns=nns,qual=qual,etype=etype,pscrn=pscrn,exp=exp,mode=mode,**_cargs) 1650 | luma_rescale=custom_nnedi3down(luma_rescale,src_w,src_h).fmtc.bitdepth(bits=16) 1651 | else: 1652 | luma_rescale=nnrs.nnedi3_resample(luma_de,nsize=nsize,nns=nns,qual=qual,etype=etype,pscrn=pscrn,exp=exp,mode=mode,**cargs.nnrs_gen()).fmtc.bitdepth(bits=16) 1653 | 1654 | def calc(n,f): 1655 | fout=f[1].copy() 1656 | fout.props["diff"]=f[0].props["PlaneStatsAverage"] 1657 | return fout 1658 | 1659 | luma_rescale=core.std.ModifyFrame(luma_rescale,[diff,luma_rescale],calc) 1660 | 1661 | if mask: 1662 | if not isinstance(mask_gen_clip,vs.VideoNode): 1663 | mclip,mclip_up=luma,luma_up 1664 | mask=core.std.Expr([mclip,mclip_up.fmtc.bitdepth(bits=16,dmode=1)],"x y - abs").std.Binarize(mask_dif_pix*256) 1665 | if callable(mask_operate_func): 1666 | mask=mask_operate_func(mask) 1667 | else: 1668 | mask=xvs.expand(mask,cycle=mthr[0]) 1669 | mask=xvs.inpand(mask,cycle=mthr[1]) 1670 | 1671 | luma_rescale=core.std.MaskedMerge(luma_rescale,xvs.getY(src),mask) 1672 | 1673 | if selective: 1674 | base=upper-lower 1675 | #x:rescale y:src 1676 | expr=f"x.diff {upper} > y x.diff {lower} < x {upper} x.diff - {base} / y * x.diff {lower} - {base} / x * + ? ?" 1677 | luma_rescale=core.akarin.Expr([luma_rescale,luma], expr) 1678 | 1679 | if show=="descale": 1680 | return luma_de 1681 | if show=="upscale": 1682 | return luma_up 1683 | elif show=="mask": 1684 | return mask 1685 | elif show=="both": 1686 | return luma_de,mask 1687 | elif show=="diff": 1688 | return core.text.FrameProps(luma_rescale,"diff", scale=2) 1689 | 1690 | if src.format.color_family==vs.GRAY: 1691 | return luma_rescale 1692 | else: 1693 | return core.std.ShufflePlanes([luma_rescale,src],[0,1,2],vs.YUV) 1694 | 1695 | #copy-paste from xyx98's xvs with some modification 1696 | def multirescale(clip:vs.VideoNode,kernels:list[dict],w:Optional[int]=None,h:Optional[int]=None,mask:bool=True,mask_dif_pix:float=2.5,postfilter_descaled=None,selective_disable:bool=False,disable_thr:float=0.00001,showinfo=False,mthr:list[int]=[2,2],mask_gen_clip=None,mask_operate_func=None,linear=False,sigmoid=False,tin='1886',fulls=False,fulld=True,border_handling=0,ignore_mask=None,**args): 1697 | clip=core.fmtc.bitdepth(clip,bits=16) 1698 | luma=xvs.getY(clip) 1699 | src_h,src_w=clip.height,clip.width 1700 | def getwh(w,h): 1701 | if w is None and h is None: 1702 | w,h=1280,720 1703 | elif w is None: 1704 | w=int(h*src_w/src_h) 1705 | elif h is None: 1706 | h=int(w*src_h/src_w) 1707 | 1708 | if w>=src_w or h>=src_h: 1709 | raise ValueError("w,h should less than input resolution") 1710 | return w,h 1711 | 1712 | w,h=getwh(w,h) 1713 | 1714 | info_gobal=f"gobal:\nresolution:{w}x{h}\tmask:{mask}\tmask_dif_pix:{mask_dif_pix}\tpostfilter_descaled:{'yes' if postfilter_descaled else 'no'}\nselective_disable:{selective_disable}\tdisable_thr:{disable_thr:f}\nextra:{str(args)}" 1715 | rescales=[] 1716 | total=len(kernels) 1717 | for i in kernels: 1718 | kfmode=False if i.get("fmode") is None else i.get("fmode") 1719 | k=i["k"][2:] 1720 | kb,kc,ktaps=i.get("b"),i.get("c"),i.get("taps") 1721 | kw,kh=i.get("w"),i.get("h") 1722 | if kw is not None or kh is not None: 1723 | kw,kh=getwh(kw,kh) 1724 | else: 1725 | kw,kh=w,h 1726 | kmask=mask if i.get("mask") is None else i.get("mask") 1727 | kmdp=mask_dif_pix if i.get("mask_dif_pix") is None else i.get("mask_dif_pix") 1728 | kpp=postfilter_descaled if i.get("postfilter_descaled") is None else i.get("postfilter_descaled") 1729 | kmultiple=1 if i.get("multiple") is None else i.get("multiple") 1730 | kmthr=mthr if i.get("mthr") is None else i.get("mthr") 1731 | kmgc=mask_gen_clip if i.get("mask_gen_clip") is None else i.get("mask_gen_clip") 1732 | kmof=mask_operate_func if i.get("mask_operate_func") is None else i.get("mask_operate_func") 1733 | klin=linear if i.get("linear") is None else i.get("linear") 1734 | ksig=sigmoid if i.get("sigmoid") is None else i.get("sigmoid") 1735 | ktin=tin if i.get("tin") is None else i.get("tin") 1736 | kfulls=fulls if i.get("fulls") is None else i.get("fulls") 1737 | kfulld=fulld if i.get("fulld") is None else i.get("fulld") 1738 | kborder_handling=i.get("border_handling",border_handling) 1739 | kignore_mask=i.get("ignore_mask",ignore_mask) 1740 | 1741 | if not kfmode: 1742 | rescales.append(MRcore(luma,kernel=k,w=kw,h=kh,mask=kmask,mask_dif_pix=kmdp,postfilter_descaled=kpp,taps=ktaps,b=kb,c=kc,multiple=kmultiple,mthr=kmthr,mask_gen_clip=kmgc,mask_operate_func=kmof,linear=klin,sigmoid=ksig,tin=ktin,fulls=kfulls,fulld=kfulld,border_handling=kborder_handling,ignore_mask=kignore_mask,**args)) 1743 | 1744 | else: 1745 | kbh=src_h if i.get("bh") is None else i.get("bh") 1746 | kbw=i.get("bw") 1747 | rescales.append(MRcoref(luma,kernel=k,w=kw,h=kh,bh=kbh,bw=kbw,mask=kmask,mask_dif_pix=kmdp,postfilter_descaled=kpp,mthr=kmthr,taps=ktaps,b=kb,c=kc,multiple=kmultiple,maskpp=kmof,mask_gen_clip=kmgc,linear=klin,sigmoid=ksig,tin=ktin,fulls=kfulls,fulld=kfulld,border_handling=kborder_handling,ignore_mask=kignore_mask,**args)) 1748 | 1749 | 1750 | def selector(n,f,src,clips): 1751 | kernels_info=[] 1752 | index,mindiff=0,f[0].props["diff"] 1753 | for i in range(total): 1754 | tmpdiff=f[i].props["diff"] 1755 | kernels_info.append(f"kernel {i}:\t{kernels[i]}\n{tmpdiff:.10f}") 1756 | if tmpdiffdisable_thr: 1761 | last=src 1762 | info+="source" 1763 | else: 1764 | last=clips[index] 1765 | info+=kernels_info[index] 1766 | if showinfo: 1767 | last=core.text.Text(last,info.replace("\t"," ")) 1768 | return last.std.SetFrameProp('kindex',intval=index) 1769 | 1770 | last=core.std.FrameEval(luma,partial(selector,src=luma,clips=rescales),prop_src=rescales) 1771 | if clip.format.color_family==vs.GRAY: 1772 | return last 1773 | else: 1774 | return core.std.ShufflePlanes([last,clip],[0,1,2],vs.YUV) 1775 | 1776 | #copy-paste from xyx98's xvs with some modification 1777 | def MRcore(clip:vs.VideoNode,kernel:str,w:int,h:int,mask: Union[bool,vs.VideoNode]=True,mask_dif_pix:float=2,postfilter_descaled=None,taps:int=3,b:float=0,c:float=0.5,multiple:float=1,mthr:list[int]=[2,2],mask_gen_clip=None,mask_operate_func=None,linear=False,sigmoid=False,tin='1886',fulls=False,fulld=True,custom_nnedi3down=False,show:str='result',border_handling=0,ignore_mask=None,**args): 1778 | src_w,src_h=clip.width,clip.height 1779 | clipo=clip 1780 | if isinstance(mask_gen_clip,vs.VideoNode): 1781 | clip32=core.std.Interleave([clip32,xvs.getY(mask_gen_clip)]) 1782 | if sigmoid: 1783 | clip=core.fmtc.transfer(clip,transs=tin,transd='sigmoid',fulls=fulls,fulld=fulld) 1784 | elif linear: 1785 | clip=core.fmtc.transfer(clip,transs=tin,transd='linear',fulls=fulls,fulld=fulld) 1786 | clip32=core.fmtc.bitdepth(clip,bits=32) 1787 | bct='b=b,c=c' if kernel.lower()=='bicubic' else 'taps=taps' if kernel.lower()=='lanczos' else '' 1788 | descaled=eval(f'core.descale.De{kernel.lower()}(clip32,width={w},height={h},border_handling=border_handling,ignore_mask=ignore_mask,{bct})') 1789 | # descaled=core.descale.Descale(clip32,width=w,height=h,kernel=kernel.lower(),taps=taps,b=b,c=c) 1790 | upscaled=xvs.resize_core(kernel.capitalize(),taps,b,c)(descaled,src_w,src_h) 1791 | if isinstance(mask_gen_clip,vs.VideoNode): 1792 | mclip=xvs.getY(mask_gen_clip) 1793 | mclip_up=upscaled[1::2] 1794 | clip32=clip32[::2] 1795 | descaled=descaled[::2] 1796 | upscaled=upscaled[::2] 1797 | diff=core.std.Expr([clip32,upscaled],"x y - abs dup 0.015 > swap 0 ?").std.PlaneStats() 1798 | 1799 | def calc(n,f): 1800 | fout=f[1].copy() 1801 | fout.props["diff"]=f[0].props["PlaneStatsAverage"]*multiple 1802 | return fout 1803 | 1804 | if postfilter_descaled is None: 1805 | pass 1806 | elif callable(postfilter_descaled): 1807 | descaled=postfilter_descaled(descaled) 1808 | else: 1809 | raise ValueError("postfilter_descaled must be a function") 1810 | 1811 | nsize=1 if args.get("nsize") is None else args.get("nsize") 1812 | nns=args.get("nns") 1813 | qual=2 if args.get("qual") is None else args.get("qual") 1814 | etype=args.get("etype") 1815 | pscrn=1 if args.get("pscrn") is None else args.get("pscrn") 1816 | exp=args.get("exp") 1817 | mode=nnrs_mode_default if args.get("mode") is None else args.get("mode") 1818 | if mode=='eval': 1819 | return core.std.ModifyFrame(clipo,[diff,clipo],calc) 1820 | if sigmoid: 1821 | descaled=core.fmtc.transfer(descaled.fmtc.bitdepth(bits=16),transs='sigmoid',transd=tin,fulls=fulld,fulld=fulls) 1822 | elif linear: 1823 | descaled=core.fmtc.transfer(descaled.fmtc.bitdepth(bits=16),transs='linear',transd=tin,fulls=fulld,fulld=fulls) 1824 | if callable(custom_nnedi3down): 1825 | rescale=nnrs.nnedi3_resample(descaled,descaled.width*2,descaled.height*2,nsize=nsize,nns=nns,qual=qual,etype=etype,pscrn=pscrn,exp=exp,mode=mode) 1826 | rescale=custom_nnedi3down(rescale,src_w,src_h).fmtc.bitdepth(bits=16) 1827 | else: 1828 | rescale=nnrs.nnedi3_resample(descaled,src_w,src_h,nsize=nsize,nns=nns,qual=qual,etype=etype,pscrn=pscrn,exp=exp,mode=mode).fmtc.bitdepth(bits=16) 1829 | 1830 | if mask is True: 1831 | if not isinstance(mask_gen_clip,vs.VideoNode): 1832 | mclip=clip 1833 | mclip_up=upscaled 1834 | mask=core.std.Expr([mclip,mclip_up.fmtc.bitdepth(bits=16,dmode=1)],"x y - abs").std.Binarize(mask_dif_pix*256) 1835 | if callable(mask_operate_func): 1836 | mask=mask_operate_func(mask) 1837 | else: 1838 | mask=xvs.expand(mask,cycle=mthr[0]) 1839 | mask=xvs.inpand(mask,cycle=mthr[1]) 1840 | rescale=core.std.MaskedMerge(rescale,clipo,mask) 1841 | elif isinstance(mask,vs.VideoNode): 1842 | if mask.width!=src_w or mask.height!=src_h or mask.format.color_family!=vs.GRAY: 1843 | raise ValueError("mask should have same resolution as source,and should be GRAY") 1844 | mask=core.fmtc.bitdepth(mask,bits=16,dmode=1) 1845 | rescale=core.std.MaskedMerge(rescale,clip,mask) 1846 | else: 1847 | mask=core.std.BlankClip(rescale) 1848 | 1849 | if show.lower()=="result": 1850 | return core.std.ModifyFrame(rescale,[diff,rescale],calc) 1851 | elif show.lower()=="mask" and mask: 1852 | return core.std.ModifyFrame(mask,[diff,mask],calc) 1853 | elif show.lower()=="descale": 1854 | return descaled #after postfilter_descaled 1855 | elif show.lower()=="upscale": 1856 | return upscaled 1857 | elif show.lower()=="both": #result,mask,descaled 1858 | return core.std.ModifyFrame(rescale,[diff,rescale],calc),core.std.ModifyFrame(mask,[diff,mask],calc),descaled 1859 | 1860 | #copy-paste from xyx98's xvs with some modification 1861 | def MRcoref(clip:vs.VideoNode,kernel:str,w:float,h:float,bh:int,bw:int=None,mask: Union[bool,vs.VideoNode]=True,mask_dif_pix:float=2,postfilter_descaled=None,mthr:list[int]=[2,2],taps:int=3,b:float=0,c:float=0.5,multiple:float=1,maskpp=None,show:str="result",mask_gen_clip=None,linear=False,sigmoid=False,tin='1886',fulls=False,fulld=True,custom_nnedi3down=False,border_handling=0,ignore_mask=None,**args): 1862 | 1863 | src_w,src_h=clip.width,clip.height 1864 | clipo=clip 1865 | if isinstance(mask_gen_clip,vs.VideoNode): 1866 | clip32=core.std.Interleave([clip32,xvs.getY(mask_gen_clip)]) 1867 | if sigmoid: 1868 | clip=core.fmtc.transfer(clip,transs=tin,transd='sigmoid',fulls=fulls,fulld=fulld) 1869 | elif linear: 1870 | clip=core.fmtc.transfer(clip,transs=tin,transd='linear',fulls=fulls,fulld=fulld) 1871 | cargs=xvs.cropping_args(src_w,src_h,h,bh,bw) 1872 | clip32=core.fmtc.bitdepth(clip,bits=32) 1873 | bct='b=b,c=c' if kernel.lower()=='bicubic' else 'taps=taps' if kernel.lower()=='lanczos' else '' 1874 | descaled=eval(f'core.descale.De{kernel.lower()}(clip32,**cargs.descale_gen(),border_handling=border_handling,ignore_mask=ignore_mask,{bct})') 1875 | # descaled=core.descale.Descale(clip32,kernel=kernel.lower(),taps=taps,b=b,c=c,**cargs.descale_gen()) 1876 | upscaled=xvs.resize_core(kernel.capitalize(),taps,b,c)(descaled,**cargs.resize_gen()) 1877 | if isinstance(mask_gen_clip,vs.VideoNode): 1878 | mclip=xvs.getY(mask_gen_clip) 1879 | mclip_up=upscaled[1::2] 1880 | clip32=clip32[::2] 1881 | descaled=descaled[::2] 1882 | upscaled=upscaled[::2] 1883 | diff=core.std.Expr([clip32,upscaled],"x y - abs dup 0.015 > swap 0 ?").std.Crop(10, 10, 10, 10).std.PlaneStats() 1884 | def calc(n,f): 1885 | fout=f[1].copy() 1886 | fout.props["diff"]=f[0].props["PlaneStatsAverage"]*multiple 1887 | return fout 1888 | 1889 | if postfilter_descaled is None: 1890 | pass 1891 | elif callable(postfilter_descaled): 1892 | descaled=postfilter_descaled(descaled) 1893 | else: 1894 | raise ValueError("postfilter_descaled must be a function") 1895 | 1896 | nsize=1 if args.get("nsize") is None else args.get("nsize") 1897 | nns=args.get("nns") 1898 | qual=2 if args.get("qual") is None else args.get("qual") 1899 | etype=args.get("etype") 1900 | pscrn=1 if args.get("pscrn") is None else args.get("pscrn") 1901 | exp=args.get("exp") 1902 | mode=nnrs_mode_default if args.get("mode") is None else args.get("mode") 1903 | if mode=='eval': 1904 | return core.std.ModifyFrame(clipo,[diff,clipo],calc) 1905 | if sigmoid: 1906 | descaled=core.fmtc.transfer(descaled.fmtc.bitdepth(bits=16),transs='sigmoid',transd=tin,fulls=fulld,fulld=fulls) 1907 | elif linear: 1908 | descaled=core.fmtc.transfer(descaled.fmtc.bitdepth(bits=16),transs='linear',transd=tin,fulls=fulld,fulld=fulls) 1909 | 1910 | if callable(custom_nnedi3down): 1911 | _cargs=cargs.nnrs_gen() 1912 | del _cargs['target_width'],_cargs['target_height'] 1913 | rescale=nnrs.nnedi3_resample(descaled,descaled.width*2,descaled.height*2,nsize=nsize,nns=nns,qual=qual,etype=etype,pscrn=pscrn,exp=exp,mode=mode,**_cargs) 1914 | rescale=custom_nnedi3down(rescale,src_w,src_h).fmtc.bitdepth(bits=16) 1915 | else: 1916 | rescale=nnrs.nnedi3_resample(descaled,nsize=nsize,nns=nns,qual=qual,etype=etype,pscrn=pscrn,exp=exp,mode=mode,**cargs.nnrs_gen()).fmtc.bitdepth(bits=16) 1917 | 1918 | if mask is True: 1919 | if not isinstance(mask_gen_clip,vs.VideoNode): 1920 | mclip=clip 1921 | mclip_up=upscaled 1922 | mask=core.std.Expr([mclip,mclip_up.fmtc.bitdepth(bits=16,dmode=1)],"x y - abs").std.Binarize(mask_dif_pix*256) 1923 | if callable(maskpp): 1924 | mask=maskpp(mask) 1925 | else: 1926 | mask=xvs.expand(mask,cycle=mthr[0]) 1927 | mask=xvs.inpand(mask,cycle=mthr[1]) 1928 | rescale=core.std.MaskedMerge(rescale,clip,mask) 1929 | elif isinstance(mask,vs.VideoNode): 1930 | if mask.width!=src_w or mask.height!=src_h or mask.format.color_family!=vs.GRAY: 1931 | raise ValueError("mask should have same resolution as source,and should be GRAY") 1932 | mask=core.fmtc.bitdepth(mask,bits=16,dmode=1) 1933 | rescale=core.std.MaskedMerge(rescale,clip,mask) 1934 | else: 1935 | mask=core.std.BlankClip(rescale) 1936 | 1937 | if show.lower()=="result": 1938 | return core.std.ModifyFrame(rescale,[diff,rescale],calc) 1939 | elif show.lower()=="mask" and mask: 1940 | return core.std.ModifyFrame(mask,[diff,mask],calc) 1941 | elif show.lower()=="descale": 1942 | return descaled #after postfilter_descaled 1943 | elif show.lower()=="upscale": 1944 | return upscaled 1945 | elif show.lower()=="both": #result,mask,descaled 1946 | return core.std.ModifyFrame(rescale,[diff,rescale],calc),core.std.ModifyFrame(mask,[diff,mask],calc),descaled 1947 | 1948 | 1949 | #copy-paste from HolyWu's havsfunc 1950 | def ContraSharpening( 1951 | denoised: vs.VideoNode, original: vs.VideoNode, radius: int = 1, rep: int = 1, planes: Optional[Union[int, Sequence[int]]] = None 1952 | ) -> vs.VideoNode: 1953 | ''' 1954 | contra-sharpening: sharpen the denoised clip, but don't add more to any pixel than what was removed previously. 1955 | 1956 | Parameters: 1957 | denoised: Denoised clip to sharpen. 1958 | 1959 | original: Original clip before denoising. 1960 | 1961 | radius: Spatial radius for contra-sharpening. 1962 | 1963 | rep: Mode of repair to limit the difference. 1964 | 1965 | planes: Specifies which planes will be processed. Any unprocessed planes will be simply copied. 1966 | By default only luma plane will be processed for non-RGB formats. 1967 | ''' 1968 | if not (isinstance(denoised, vs.VideoNode) and isinstance(original, vs.VideoNode)): 1969 | raise vs.Error('ContraSharpening: this is not a clip') 1970 | 1971 | if denoised.format.id != original.format.id: 1972 | raise vs.Error('ContraSharpening: clips must have the same format') 1973 | 1974 | neutral = 1 << (denoised.format.bits_per_sample - 1) 1975 | 1976 | plane_range = range(denoised.format.num_planes) 1977 | 1978 | if planes is None: 1979 | planes = [0] if denoised.format.color_family != vs.RGB else [0, 1, 2] 1980 | elif isinstance(planes, int): 1981 | planes = [planes] 1982 | 1983 | pad = 2 if radius < 3 else 4 1984 | denoised = rpclip(denoised, pad) 1985 | original = rpclip(original, pad) 1986 | 1987 | matrix1 = [1, 2, 1, 2, 4, 2, 1, 2, 1] 1988 | matrix2 = [1, 1, 1, 1, 1, 1, 1, 1, 1] 1989 | 1990 | # damp down remaining spots of the denoised clip 1991 | s = MinBlur(denoised, radius, planes) 1992 | # the difference achieved by the denoising 1993 | allD = core.std.MakeDiff(original, denoised, planes=planes) 1994 | 1995 | RG11 = s.std.Convolution(matrix=matrix1, planes=planes) 1996 | if radius >= 2: 1997 | RG11 = RG11.std.Convolution(matrix=matrix2, planes=planes) 1998 | if radius >= 3: 1999 | RG11 = RG11.std.Convolution(matrix=matrix2, planes=planes) 2000 | 2001 | # the difference of a simple kernel blur 2002 | ssD = core.std.MakeDiff(s, RG11, planes=planes) 2003 | # limit the difference to the max of what the denoising removed locally 2004 | ssDD = core.rgvs.Repair(ssD, allD, mode=[rep if i in planes else 0 for i in plane_range]) 2005 | # abs(diff) after limiting may not be bigger than before 2006 | ssDD = core.std.Expr([ssDD, ssD], expr=[f'x {neutral} - abs y {neutral} - abs < x y ?' if i in planes else '' for i in plane_range]) 2007 | # apply the limited difference (sharpening is just inverse blurring) 2008 | last = core.std.MergeDiff(denoised, ssDD, planes=planes) 2009 | return last.std.Crop(pad, pad, pad, pad) 2010 | 2011 | #copy-paste from HolyWu's havsfunc 2012 | def MinBlur(clp: vs.VideoNode, r: int = 1, planes: Optional[Union[int, Sequence[int]]] = None) -> vs.VideoNode: 2013 | '''Nifty Gauss/Median combination''' 2014 | from mvsfunc import LimitFilter 2015 | 2016 | if not isinstance(clp, vs.VideoNode): 2017 | raise vs.Error('MinBlur: this is not a clip') 2018 | 2019 | plane_range = range(clp.format.num_planes) 2020 | 2021 | if planes is None: 2022 | planes = list(plane_range) 2023 | elif isinstance(planes, int): 2024 | planes = [planes] 2025 | 2026 | matrix1 = [1, 2, 1, 2, 4, 2, 1, 2, 1] 2027 | matrix2 = [1, 1, 1, 1, 1, 1, 1, 1, 1] 2028 | 2029 | if r <= 0: 2030 | RG11 = sbr(clp, planes=planes) 2031 | RG4 = clp.std.Median(planes=planes) 2032 | elif r == 1: 2033 | RG11 = clp.std.Convolution(matrix=matrix1, planes=planes) 2034 | RG4 = clp.std.Median(planes=planes) 2035 | elif r == 2: 2036 | RG11 = clp.std.Convolution(matrix=matrix1, planes=planes).std.Convolution(matrix=matrix2, planes=planes) 2037 | RG4 = clp.ctmf.CTMF(radius=2, planes=planes) 2038 | else: 2039 | RG11 = clp.std.Convolution(matrix=matrix1, planes=planes).std.Convolution(matrix=matrix2, planes=planes).std.Convolution(matrix=matrix2, planes=planes) 2040 | if clp.format.bits_per_sample == 16: 2041 | s16 = clp 2042 | RG4 = core.fmtc.bitdepth(clp, bits=12, dmode=1).ctmf.CTMF(radius=3, planes=planes) 2043 | RG4 = LimitFilter(s16, core.fmtc.bitdepth(RG4, bits=16), thr=0.0625, elast=2, planes=planes) 2044 | else: 2045 | RG4 = clp.ctmf.CTMF(radius=3, planes=planes) 2046 | 2047 | return core.std.Expr([clp, RG11, RG4], expr=['x y - x z - * 0 < x x y - abs x z - abs < y z ? ?' if i in planes else '' for i in plane_range]) 2048 | 2049 | #copy-paste from HolyWu's havsfunc 2050 | def sbr(c: vs.VideoNode, r: int = 1, planes: Optional[Union[int, Sequence[int]]] = None) -> vs.VideoNode: 2051 | '''make a highpass on a blur's difference (well, kind of that)''' 2052 | if not isinstance(c, vs.VideoNode): 2053 | raise vs.Error('sbr: this is not a clip') 2054 | 2055 | neutral = 1 << (c.format.bits_per_sample - 1) if c.format.sample_type == vs.INTEGER else 0.0 2056 | 2057 | plane_range = range(c.format.num_planes) 2058 | 2059 | if planes is None: 2060 | planes = list(plane_range) 2061 | elif isinstance(planes, int): 2062 | planes = [planes] 2063 | 2064 | matrix1 = [1, 2, 1, 2, 4, 2, 1, 2, 1] 2065 | matrix2 = [1, 1, 1, 1, 1, 1, 1, 1, 1] 2066 | 2067 | RG11 = c.std.Convolution(matrix=matrix1, planes=planes) 2068 | if r >= 2: 2069 | RG11 = RG11.std.Convolution(matrix=matrix2, planes=planes) 2070 | if r >= 3: 2071 | RG11 = RG11.std.Convolution(matrix=matrix2, planes=planes) 2072 | 2073 | RG11D = core.std.MakeDiff(c, RG11, planes=planes) 2074 | 2075 | RG11DS = RG11D.std.Convolution(matrix=matrix1, planes=planes) 2076 | if r >= 2: 2077 | RG11DS = RG11DS.std.Convolution(matrix=matrix2, planes=planes) 2078 | if r >= 3: 2079 | RG11DS = RG11DS.std.Convolution(matrix=matrix2, planes=planes) 2080 | 2081 | RG11DD = core.std.Expr( 2082 | [RG11D, RG11DS], 2083 | expr=[f'x y - x {neutral} - * 0 < {neutral} x y - abs x {neutral} - abs < x y - {neutral} + x ? ?' if i in planes else '' for i in plane_range], 2084 | ) 2085 | return core.std.MakeDiff(c, RG11DD, planes=planes) 2086 | 2087 | #copy-paste from xyx98's xvs with some modification 2088 | def SCSharpen(clip:vs.VideoNode,ref:vs.VideoNode,max_sharpen_weight=3/7,min_sharpen_weight=0,casstr=0.7,planes=[0]): 2089 | """ 2090 | Sharpness Considered Sharpen: 2091 | It mainly design for sharpen a bad source after blurry filtered such as strong AA, and source unsuited to be reference when you want sharpen filtered clip to match the sharpness of source. 2092 | It use cas as sharpen core,and calculate sharpness of source(reference clip),filtered clip (the clip you want sharpen),and sharpen clip(by cas).Use these sharpness information adjust merge weight of filtered clip and sharpen clip. 2093 | ############################ 2094 | arg "clean" was removed because of the deprecation of havsfunc in this script(zvs). 2095 | Don't use high max_sharpen_weight or you might need addition filter to resolve artifacts cause by cas(1). 2096 | only luma processed,output is always 16bit. 2097 | """ 2098 | # trust the user( ͡° ͜ʖ ͡°) 爱来自中国 2099 | # if max_sharpen_weight >1 or max_sharpen_weight <=0 : 2100 | # raise ValueError("max_sharpen_weight should in (0,1]") 2101 | 2102 | # if min_sharpen_weight >1 or min_sharpen_weight <0 or max_sharpen_weight {L1} z * {L2} y * + {k1} {L3} < {L3} z * {L4} y * + {k1} z * {k2} y * + ? ? ?" 2144 | last=core.akarin.Expr([ref,last,sharp],expr) 2145 | 2146 | if isYUV and Yonly: 2147 | last=core.std.ShufflePlanes([last,clip],[0,1,2],vs.YUV) 2148 | 2149 | return last 2150 | #alias 2151 | #i hate uppercase func/arg name somehow 2152 | scsharpen=SCSharpen 2153 | 2154 | #copy-paste from xyx98's xvs 2155 | def getsharpness(clip,show=False): 2156 | 2157 | def calc(n,f): 2158 | fout=f[1].copy() 2159 | fout.props["sharpness"]=f[0].props["PlaneStatsAverage"]*65535 2160 | return fout 2161 | 2162 | luma=xvs.getY(clip).resize.Point(format=vs.GRAY16) 2163 | blur=core.rgvs.RemoveGrain(luma, 20) 2164 | dif=core.akarin.Expr([luma,blur],[f"x y - 65535 / 2 pow 65535 *"]) 2165 | dif=core.std.PlaneStats(dif) 2166 | last=core.std.ModifyFrame(clip,[dif,clip],calc) 2167 | return core.text.FrameProps(last,"sharpness",scale=2) if show else last 2168 | --------------------------------------------------------------------------------