-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmisc.py
More file actions
1360 lines (1172 loc) · 58.3 KB
/
Copy pathmisc.py
File metadata and controls
1360 lines (1172 loc) · 58.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from vapoursynth import core
import vapoursynth as vs
from typing import Optional, Union, Sequence, List
def Overlay(
base: vs.VideoNode,
overlay: vs.VideoNode,
x: int = 0,
y: int = 0,
mask: Optional[vs.VideoNode] = None,
opacity: float = 1.0,
mode: str = 'normal',
planes: Optional[Union[int, Sequence[int]]] = None,
mask_first_plane: bool = True,
) -> vs.VideoNode:
'''
Puts clip overlay on top of clip base using different blend modes, and with optional x,y positioning, masking and opacity.
Parameters:
base: This clip will be the base, determining the size and all other video properties of the result.
overlay: This is the image that will be placed on top of the base clip.
x, y: Define the placement of the overlay image on the base clip, in pixels. Can be positive or negative.
mask: Optional transparency mask. Must be the same size as overlay. Where mask is darker, overlay will be more transparent.
opacity: Set overlay transparency. The value is from 0.0 to 1.0, where 0.0 is transparent and 1.0 is fully opaque.
This value is multiplied by mask luminance to form the final opacity.
mode: Defines how your overlay should be blended with your base image. Available blend modes are:
addition, average, burn, darken, difference, divide, dodge, exclusion, extremity, freeze, glow, grainextract, grainmerge, hardlight, hardmix, heat,
lighten, linearlight, multiply, negation, normal, overlay, phoenix, pinlight, reflect, screen, softlight, subtract, vividlight
planes: Specifies which planes will be processed. Any unprocessed planes will be simply copied.
mask_first_plane: If true, only the mask's first plane will be used for transparency.
'''
if not (isinstance(base, vs.VideoNode) and isinstance(overlay, vs.VideoNode)):
raise vs.Error('Overlay: this is not a clip')
if mask is not None:
if not isinstance(mask, vs.VideoNode):
raise vs.Error('Overlay: mask is not a clip')
if mask.width != overlay.width or mask.height != overlay.height or mask.format.bits_per_sample != overlay.format.bits_per_sample :
raise vs.Error('Overlay: mask must have the same dimensions and bit depth as overlay')
if base.format.sample_type == vs.INTEGER:
bits = base.format.bits_per_sample
neutral = 1 << (bits - 1)
peak = (1 << bits) - 1
factor = 1 << bits
else:
neutral = 0.5
peak = factor = 1.0
plane_range = range(base.format.num_planes)
if planes is None:
planes = list(plane_range)
elif isinstance(planes, int):
planes = [planes]
if base.format.subsampling_w > 0 or base.format.subsampling_h > 0:
base_orig = base
base = base.resize.Point(format=base.format.replace(subsampling_w=0, subsampling_h=0))
else:
base_orig = None
if overlay.format.id != base.format.id:
overlay = overlay.resize.Point(format=base.format)
if mask is None:
mask = overlay.std.BlankClip(format=overlay.format.replace(color_family=vs.GRAY, subsampling_w=0, subsampling_h=0), color=peak)
elif mask.format.id != overlay.format.id and mask.format.color_family != vs.GRAY:
mask = mask.resize.Point(format=overlay.format, range_s='full')
opacity = min(max(opacity, 0.0), 1.0)
mode = mode.lower()
# Calculate padding sizes
l, r = x, base.width - overlay.width - x
t, b = y, base.height - overlay.height - y
# Split into crop and padding values
cl, pl = min(l, 0) * -1, max(l, 0)
cr, pr = min(r, 0) * -1, max(r, 0)
ct, pt = min(t, 0) * -1, max(t, 0)
cb, pb = min(b, 0) * -1, max(b, 0)
# Crop and padding
overlay = overlay.std.Crop(left=cl, right=cr, top=ct, bottom=cb)
overlay = overlay.std.AddBorders(left=pl, right=pr, top=pt, bottom=pb)
mask = mask.std.Crop(left=cl, right=cr, top=ct, bottom=cb)
mask = mask.std.AddBorders(left=pl, right=pr, top=pt, bottom=pb, color=[0] * mask.format.num_planes)
EXPR = core.akarin.Expr if hasattr(core, 'akarin') else core.cranexpr.Expr if hasattr(core, 'cranexpr') else core.std.Expr
if opacity < 1:
mask = EXPR(mask, expr=f'x {opacity} *')
if mode == 'normal':
pass
elif mode == 'addition':
expr = f'x y +'
elif mode == "linearadd":
expr = f'x 2 pow y 2 pow + sqrt' # same as Gimp's 2.10 subtract blending mode
elif mode == 'average':
expr = f'x y + 2 /'
elif mode == 'burn':
expr = f'x 0 <= x {peak} {peak} y - {factor} * x / - ?'
elif mode == 'darken':
expr = f'x y min'
elif mode == 'difference':
expr = f'x y - abs'
elif mode == 'divide':
expr = f'y 0 <= {peak} {peak} x * y / ?'
elif mode == 'dodge':
expr = f'x {peak} >= x y {factor} * {peak} x - / ?'
elif mode == 'exclusion':
expr = f'x y + 2 x * y * {peak} / -'
elif mode == 'extremity':
expr = f'{peak} x - y - abs'
elif mode == 'freeze':
expr = f'y 0 <= 0 {peak} {peak} x - dup * y / {peak} min - ?'
elif mode == 'glow':
expr = f'x {peak} >= x y y * {peak} x - / ?'
elif mode == 'grainextract':
expr = f'x y - {neutral} +'
elif mode == 'grainmerge':
expr = f'x y + {neutral} -'
elif mode == 'hardlight':
expr = f'y {neutral} < 2 y x * {peak} / * {peak} 2 {peak} y - {peak} x - * {peak} / * - ?'
elif mode == 'hardmix':
expr = f'x {peak} y - < 0 {peak} ?'
elif mode == 'heat':
expr = f'x 0 <= 0 {peak} {peak} y - dup * x / {peak} min - ?'
elif mode == 'lighten':
expr = f'x y max'
elif mode == 'linearlight':
expr = f'y {neutral} < y 2 x * + {peak} - y 2 x {neutral} - * + ?'
elif mode == 'multiply':
expr = f'x y * {peak} /'
elif mode == 'negation':
expr = f'{peak} {peak} x - y - abs -'
elif mode == 'overlay':
expr = f'x {neutral} < 2 x y * {peak} / * {peak} 2 {peak} x - {peak} y - * {peak} / * - ?'
elif mode == 'phoenix':
expr = f'x y min x y max - {peak} +'
elif mode == 'pinlight':
expr = f'y {neutral} < x 2 y * min x 2 y {neutral} - * max ?'
elif mode == 'reflect':
expr = f'y {peak} >= y x x * {peak} y - / ?'
elif mode == 'screen':
expr = f'{peak} {peak} x - {peak} y - * {peak} / -'
elif mode == 'softlight':
expr = f'x {neutral} > y {peak} y - x {neutral} - * {neutral} / 0.5 y {neutral} - abs {peak} / - * + y y {neutral} x - {neutral} / * 0.5 y {neutral} - abs {peak} / - * - ?'
elif mode == 'subtract':
expr = f'x y -'
elif mode == "linearsubtract":
expr = f'x 2 pow y 2 pow - sqrt' # same as Gimp's 2.10 subtract blending mode
elif mode == 'vividlight':
expr = f'x {neutral} < x 0 <= 2 x * {peak} {peak} y - {factor} * 2 x * / - ? 2 x {neutral} - * {peak} >= 2 x {neutral} - * y {factor} * {peak} 2 x {neutral} - * - / ? ?'
else:
raise vs.Error('Overlay: invalid mode specified')
if mode != 'normal':
overlay = EXPR([overlay, base], expr=[expr if i in planes else '' for i in plane_range])
# Return padded clip
last = core.std.MaskedMerge(base, overlay, mask, planes=planes, first_plane=mask_first_plane)
if base_orig is not None:
last = last.resize.Point(format=base_orig.format)
return last
def ShiftLinesHorizontally(clip: vs.VideoNode, shift: int, ymin: int, ymax: int) -> vs.VideoNode:
# Validate clip format and subsampling
if clip.format.color_family != vs.YUV or clip.format.subsampling_w != 0 or clip.format.subsampling_h != 0:
raise ValueError("ShiftLinesHorizontalRange: only YUV444 input is supported.")
# Ensure ymin and ymax are within valid range
if ymin < 0 or ymin >= clip.height:
raise ValueError(f"ShiftLinesHorizontalRange: ymin ({ymin}) is out of range.")
if ymax < ymin or ymax >= clip.height:
raise ValueError(f"ShiftLinesHorizontalRange: ymax ({ymax}) is out of range.")
# If no shift is needed, return original clip
if shift == 0:
return clip
width = clip.width
height = clip.height
# Create shifted version of just the target lines
mid = clip.std.CropAbs(width=width, height=ymax-ymin+1, left=0, top=ymin)
black = core.std.BlankClip(mid, width=abs(shift), height=mid.height, color=[0, 128, 128])
if shift > 0:
shifted_mid = core.std.StackHorizontal([black, mid.std.CropRel(right=shift)])
else:
shifted_mid = core.std.StackHorizontal([mid.std.CropRel(left=-shift), black])
shifted_mid = shifted_mid.resize.Point(width=width, height=mid.height)
# Build the output clip by stacking:
# 1. Lines above ymin (unchanged)
# 2. Shifted lines (ymin to ymax)
# 3. Lines below ymax (unchanged)
parts = []
if ymin > 0:
parts.append(clip.std.CropAbs(width=width, height=ymin, left=0, top=0))
parts.append(shifted_mid)
if ymax < height - 1:
parts.append(clip.std.CropAbs(width=width, height=height-ymax-1, left=0, top=ymax+1))
return core.std.StackVertical(parts)
def SCDetect(clip: vs.VideoNode, threshold: float = 0.1, plane: int = 0) -> vs.VideoNode:
"""
Scene change detection with _SceneChangePrev/_SceneChangeNext frame properties.
Uses core.misc.SCDetect or core.scd.Detect if available (plane=0 only), otherwise falls back to
a std.PlaneStats-based reimplementation.
Args:
clip : Input clip
threshold : Scene change threshold (default: 0.1, must be 0.0–1.0)
plane : Plane to analyze; only honoured in fallback path —
misc.SCDetect always uses plane 0
Returns:
Clip with _SceneChangePrev and _SceneChangeNext frame properties set.
"""
if not isinstance(clip, vs.VideoNode):
raise vs.Error('SCDetect: this is not a clip')
if not (0.0 <= threshold <= 1.0):
raise vs.Error('SCDetect: threshold must be between 0.0 and 1.0')
if clip.num_frames < 2:
raise vs.Error('SCDetect: clip must have more than one frame')
if hasattr(core,'scd'):
if clip.format.color_family == vs.RGB:
sc = clip.resize.Point(format=vs.GRAY8, matrix_s='709')
sc = core.misc.SCDetect(sc, threshold=threshold)
def _copy_props(n: int, f: list[vs.VideoFrame]) -> vs.VideoFrame:
fout = f[0].copy()
fout.props['_SceneChangePrev'] = f[1].props['_SceneChangePrev']
fout.props['_SceneChangeNext'] = f[1].props['_SceneChangeNext']
return fout
return clip.std.ModifyFrame(clips=[clip, sc], selector=_copy_props)
return core.scd.Detect(clip, thresh=threshold)
elif hasattr(core, 'misc') and plane == 0:
if clip.format.color_family == vs.RGB:
sc = clip.resize.Point(format=vs.GRAY8, matrix_s='709')
sc = core.misc.SCDetect(sc, threshold=threshold)
def _copy_props(n: int, f: list[vs.VideoFrame]) -> vs.VideoFrame:
fout = f[0].copy()
fout.props['_SceneChangePrev'] = f[1].props['_SceneChangePrev']
fout.props['_SceneChangeNext'] = f[1].props['_SceneChangeNext']
return fout
return clip.std.ModifyFrame(clips=[clip, sc], selector=_copy_props)
return core.misc.SCDetect(clip, threshold=threshold)
# prev_stats[n] = diff(frame_{n-1}, frame_n) → SceneChangePrev
# next_stats[n] = diff(frame_n, frame_{n+1}) → SceneChangeNext
prev_shifted = clip.std.DuplicateFrames(0).std.Trim(last=clip.num_frames - 1)
prev_stats = core.std.PlaneStats(prev_shifted, clip, plane=plane)
next_stats = core.std.PlaneStats(clip, clip.std.Trim(first=1), plane=plane)
def _set_sc_props(n: int, f: list[vs.VideoFrame]) -> vs.VideoFrame:
fout = f[0].copy()
fout.props['_SceneChangePrev'] = int(float(f[1].props.get('PlaneStatsDiff', 0.0)) > threshold)
fout.props['_SceneChangeNext'] = int(float(f[2].props.get('PlaneStatsDiff', 0.0)) > threshold)
return fout
return clip.std.ModifyFrame(
clips=[clip, prev_stats, next_stats],
selector=_set_sc_props
)
def scene_aware(
clip: vs.VideoNode,
filter_func,
sc_threshold: float = 0.1,
min_scene_len: int = 5,
color_matrix: str = "709",
**filter_kwargs
) -> vs.VideoNode:
"""
Automatically split a clip by scene changes and apply a filter separately per scene.
"""
if not isinstance(clip, vs.VideoNode):
raise TypeError("scene_aware: 'clip' must be a VideoNode")
# --- SCDetect: clip must be constant format and of integer 8-16 bit type or 32 bit float
sc_src = clip
if clip.format.color_family == vs.RGB:
sc_src = core.resize.Bicubic(clip, format=vs.YUV420P8, matrix_s=color_matrix) # convert to YUV8 for SCDetect
elif clip.format.sample_type == vs.FLOAT and clip.format.bits_per_sample != 32:
sc_src = core.resize.Bicubic(clip, format=vs.YUV420P8)
if hasattr(core,'scd'):
sc = core.scd.Detect(sc_src, thresh=sc_threshold)
elif hasattr(core,'misc'):
sc = core.misc.SCDetect(sc_src, threshold=sc_threshold)
else:
sc = SCDetect(sc_src, threshold=sc_threshold)
sc_frames = [i for i in range(clip.num_frames) if sc.get_frame(i).props._SceneChangePrev == 1]
# --- Remove very short segments
clean_frames = []
prev = 0
for f in sc_frames:
if f - prev >= min_scene_len:
clean_frames.append(f)
prev = f
sc_frames = clean_frames
# --- Build scene ranges
start = 0
ranges = []
for f in sc_frames:
ranges.append((start, f - 1))
start = f
ranges.append((start, clip.num_frames - 1))
# --- Apply filter per scene
processed_segments = []
for i, (s, e) in enumerate(ranges):
sub = clip[s:e+1]
out = filter_func(sub, **filter_kwargs)
processed_segments.append(out)
# --- Join them back
result = core.std.Splice(processed_segments)
return result
# define ShowFramesAround here (correct FrameEval usage)
def ShowFramesAround(src_clip: vs.VideoNode, count: int = 3) -> vs.VideoNode:
"""
Return a clip that shows `count` consecutive frames horizontally,
centered around each frame of the source. `count` must be odd.
This implementation builds a stacked TEMPLATE clip and uses FrameEval
on that template so returned frames match expected dimensions.
"""
if count < 1 or (count % 2) == 0:
raise ValueError("ShowFramesAround: count must be an odd integer >= 1")
radius = count // 2
last = src_clip.num_frames - 1
# Build a template whose frames already have the stacked (wider) dimensions:
# stack `count` copies of the source clip horizontally. The template has the same
# number of frames as src_clip and the desired output dimensions.
template = core.std.StackHorizontal([src_clip] * count)
# callback for FrameEval: given frame index n, gather frames around n from src_clip
def _select(n: int) -> vs.VideoNode:
frames = []
for offset in range(-radius, radius + 1):
i = n + offset
# clamp to first/last frame
if i < 0:
i = 0
elif i > last:
i = last
# index into the original source clip to get the requested frame
frames.append(src_clip[i])
# stack the selected frames horizontally; dimensions match the template
return core.std.StackHorizontal(frames)
# Evaluate on the template so FrameEval sees matching dimensions
return core.std.FrameEval(template, _select)
def AddVerticalLines(clip: vs.VideoNode, interval_ms: int = 10, color: float = 1.0) -> vs.VideoNode:
"""
Draw vertical lines every `interval_ms` milliseconds.
"""
width, height = clip.width, clip.height
fps = clip.fps_num / clip.fps_den
pixels_per_interval = max(1, int(width * interval_ms / (1000 / fps)))
# start with a blank clip of the same size as clip
lines_clip = core.std.BlankClip(
clip=clip,
color=0.0,
width=width,
height=height
)
for x in range(0, width, pixels_per_interval):
# create a single-pixel-wide vertical line
line = core.std.BlankClip(clip=clip, color=color, width=1, height=height)
# shift it into position
left = x
right = width - x - 1
line = core.std.AddBorders(line, left=left, right=right, top=0, bottom=0)
# overlay this line on lines_clip
lines_clip = core.std.MergeDiff(lines_clip, line)
# overlay the vertical lines on the original clip
return core.std.MergeDiff(clip, lines_clip)
def DelayAudio(audio_clip: vs.AudioNode, delay_ms: float) -> vs.AudioNode:
"""
Delay an AudioNode by delay_ms milliseconds.
Positive delay_ms prepends silence (audio plays later),
Negative delay_ms trims the start (audio plays earlier).
"""
if delay_ms == 0:
return audio_clip
sr = audio_clip.sample_rate # sample rate of the audio
delay_samples = abs(int(sr * (delay_ms / 1000)))
if delay_ms > 0: # prepend silence
silence = core.std.BlankAudio(clip=audio_clip, length=delay_samples)
return core.std.AudioSplice([silence, audio_clip])
else: # negative delay → trim start
return core.std.AudioTrim(audio_clip, first=delay_samples)
def AverageFrames(
clip: vs.VideoNode, weights: Union[float, Sequence[float]], scenechange: Optional[float] = None, planes: Optional[Union[int, Sequence[int]]] = None
) -> vs.VideoNode:
if not isinstance(clip, vs.VideoNode):
raise vs.Error('AverageFrames: this is not a clip')
if scenechange:
clip = SCDetect(clip, threshold=scenechange)
return clip.std.AverageFrames(weights=weights, scenechange=scenechange, planes=planes)
# convert i.e. 1080p50 to 1080i25
def Interlace(clip: vs.VideoNode, tff: bool=True) -> vs.VideoNode:
if hasattr(core,'interlace'):
return core.interlace.Interlace(clip=clip,tff=tff)
clip = core.std.SeparateFields(clip=clip, tff=tff)
clip = core.std.SelectEvery(clip=clip, cycle=2, offsets=[0])
clip = core.std.DoubleWeave(clip=clip, tff=tff)
return core.std.SelectEvery(clip=clip, cycle=2, offsets=[0])
def median_blur(
clip: vs.VideoNode,
radius: Union[int, Sequence[int]] = 2,
planes: Optional[Union[int, Sequence[int]]] = None,
**kwargs
) -> vs.VideoNode:
"""
Standalone median-blur replacement for the deprecated CTMF filter.
Falls back to zsmooth.Median if CTMF is not installed.
Parameters
----------
clip : vs.VideoNode
Input clip. Any bit-depth and subsampling are accepted.
radius : int | Sequence[int], optional
Spatial radius of the median kernel.
1 = 3×3, 2 = 5×5, 3 = 7×7.
Defaults to 2 to match CTMF's historical default.
If a sequence is passed, one value per plane may be given.
planes : int | Sequence[int] | None, optional
Planes to process. None (default) processes all planes.
**kwargs
Extra arguments forwarded to CTMF only (e.g. memsize).
Silently ignored when the zsmooth fallback is used.
Returns
-------
vs.VideoNode
Median-blurred clip.
Raises
------
RuntimeError
If neither vapoursynth-ctmf nor vapoursynth-zsmooth is available.
"""
# Normalize planes to a list so we can iterate uniformly later
if planes is None:
planes = list(range(clip.format.num_planes))
elif isinstance(planes, int):
planes = [planes]
# ------------------------------------------------------------------
# 1. Prefer vapoursynth-ctmf (the original, now deprecated plugin)
# ------------------------------------------------------------------
if hasattr(core, 'ctmf'):
# CTMF accepts radius as int or list[int] natively
return core.ctmf.CTMF(clip, radius=radius, planes=planes, **kwargs)
# ------------------------------------------------------------------
# 2. Fallback: zsmooth.Median
# - Supports radius 0–3 only.
# - Does NOT accept the extra kwargs that CTMF understands.
# ------------------------------------------------------------------
if hasattr(core, 'zsmooth'):
# zsmooth.Median signature:
# Median(clip clip[, int[] radius, int[] planes])
return core.zsmooth.Median(clip, radius=radius, planes=planes)
# ------------------------------------------------------------------
# 3. Nothing available – bail out with a helpful message
# ------------------------------------------------------------------
raise RuntimeError(
"median_blur: Neither 'ctmf' nor 'zsmooth' is installed. "
"Please install vapoursynth-ctmf or vapoursynth-zsmooth."
)
def MinBlur(clp: vs.VideoNode, r: int = 1, planes: Optional[Union[int, Sequence[int]]] = None) -> vs.VideoNode:
'''Nifty Gauss/Median combination – CTMF-free variant'''
if not isinstance(clp, vs.VideoNode):
raise vs.Error('MinBlur: this is not a clip')
plane_range = range(clp.format.num_planes)
if planes is None:
planes = list(plane_range)
elif isinstance(planes, int):
planes = [planes]
matrix1 = [1, 2, 1, 2, 4, 2, 1, 2, 1]
matrix2 = [1, 1, 1, 1, 1, 1, 1, 1, 1]
# --- Helper: median with a fallback instead of a hard ctmf call ---
def _median(clip, radius, planes):
if hasattr(core, 'ctmf'):
return core.ctmf.CTMF(clip, radius=radius, planes=planes)
if hasattr(core, 'zsmooth'):
return core.zsmooth.Median(clip, radius=radius, planes=planes)
raise RuntimeError("MinBlur: neither ctmf nor zsmooth available")
if r <= 0:
RG11 = sbr(clp, planes=planes)
RG4 = clp.std.Median(planes=planes)
elif r == 1:
RG11 = clp.std.Convolution(matrix=matrix1, planes=planes)
RG4 = clp.std.Median(planes=planes)
elif r == 2:
RG11 = clp.std.Convolution(matrix=matrix1, planes=planes).std.Convolution(matrix=matrix2, planes=planes)
RG4 = _median(clp, radius=2, planes=planes)
else:
RG11 = clp.std.Convolution(matrix=matrix1, planes=planes).std.Convolution(matrix=matrix2, planes=planes).std.Convolution(matrix=matrix2, planes=planes)
# Note: zsmooth.Median supports radius=3 at most
if clp.format.bits_per_sample == 16 and hasattr(core, 'ctmf'):
# Keep the original LimitFilter logic only when CTMF is available
from mvsfunc import LimitFilter
s16 = clp
RG4 = depth(clp, 12, dither_type=Dither.NONE).ctmf.CTMF(radius=3, planes=planes)
RG4 = LimitFilter(s16, depth(RG4, 16), thr=0.0625, elast=2, planes=planes)
else:
RG4 = _median(clp, radius=3, planes=planes)
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]
)
def sbr(c: vs.VideoNode, r: int = 1, planes: Optional[Union[int, Sequence[int]]] = None) -> vs.VideoNode:
'''make a highpass on a blur's difference (well, kind of that)'''
if not isinstance(c, vs.VideoNode):
raise vs.Error('sbr: this is not a clip')
neutral = 1 << (c.format.bits_per_sample - 1) if c.format.sample_type == vs.INTEGER else 0.0
plane_range = range(c.format.num_planes)
if planes is None:
planes = list(plane_range)
elif isinstance(planes, int):
planes = [planes]
matrix1 = [1, 2, 1, 2, 4, 2, 1, 2, 1]
matrix2 = [1, 1, 1, 1, 1, 1, 1, 1, 1]
RG11 = c.std.Convolution(matrix=matrix1, planes=planes)
if r >= 2:
RG11 = RG11.std.Convolution(matrix=matrix2, planes=planes)
if r >= 3:
RG11 = RG11.std.Convolution(matrix=matrix2, planes=planes)
RG11D = core.std.MakeDiff(c, RG11, planes=planes)
RG11DS = RG11D.std.Convolution(matrix=matrix1, planes=planes)
if r >= 2:
RG11DS = RG11DS.std.Convolution(matrix=matrix2, planes=planes)
if r >= 3:
RG11DS = RG11DS.std.Convolution(matrix=matrix2, planes=planes)
EXPR = core.akarin.Expr if hasattr(core, 'akarin') else core.cranexpr.Expr if hasattr(core, 'cranexpr') else core.std.Expr
RG11DD = EXPR(
[RG11D, RG11DS],
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],
)
return core.std.MakeDiff(c, RG11DD, planes=planes)
def mt_clamp(
clip: vs.VideoNode,
bright_limit: vs.VideoNode,
dark_limit: vs.VideoNode,
overshoot: int = 0,
undershoot: int = 0,
planes: Optional[Union[int, Sequence[int]]] = None,
) -> vs.VideoNode:
if not (isinstance(clip, vs.VideoNode) and isinstance(bright_limit, vs.VideoNode) and isinstance(dark_limit, vs.VideoNode)):
raise vs.Error('mt_clamp: this is not a clip')
if bright_limit.format.id != clip.format.id or dark_limit.format.id != clip.format.id:
raise vs.Error('mt_clamp: clips must have the same format')
plane_range = range(clip.format.num_planes)
if planes is None:
planes = list(plane_range)
elif isinstance(planes, int):
planes = [planes]
EXPR = core.akarin.Expr if hasattr(core, 'akarin') else core.cranexpr.Expr if hasattr(core, 'cranexpr') else core.std.Expr
return EXPR([clip, bright_limit, dark_limit], expr=[f'x y {overshoot} + min z {undershoot} - max' if i in planes else '' for i in plane_range])
def mt_expand_multi(src: vs.VideoNode, mode: str = 'rectangle', planes: Optional[Union[int, Sequence[int]]] = None, sw: int = 1, sh: int = 1) -> vs.VideoNode:
'''
Calls std.Maximum multiple times in order to grow the mask from the desired width and height.
Parameters:
src: Clip to process.
mode: "rectangle", "ellipse" or "losange". Ellipses are actually combinations of rectangles and losanges and look more like octogons.
Losanges are truncated (not scaled) when sw and sh are not equal.
planes: Specifies which planes will be processed. Any unprocessed planes will be simply copied.
sw: Growing shape width. 0 is allowed.
sh: Growing shape height. 0 is allowed.
'''
if not isinstance(src, vs.VideoNode):
raise vs.Error('mt_expand_multi: this is not a clip')
if sw > 0 and sh > 0:
mode_m = [0, 1, 0, 1, 1, 0, 1, 0] if mode == 'losange' or (mode == 'ellipse' and (sw % 3) != 1) else [1, 1, 1, 1, 1, 1, 1, 1]
elif sw > 0:
mode_m = [0, 0, 0, 1, 1, 0, 0, 0]
elif sh > 0:
mode_m = [0, 1, 0, 0, 0, 0, 1, 0]
else:
mode_m = None
if mode_m is not None:
src = mt_expand_multi(src.std.Maximum(planes=planes, coordinates=mode_m), mode=mode, planes=planes, sw=sw - 1, sh=sh - 1)
return src
def mt_inflate_multi(src: vs.VideoNode, planes: Optional[Union[int, Sequence[int]]] = None, radius: int = 1) -> vs.VideoNode:
if not isinstance(src, vs.VideoNode):
raise vs.Error('mt_inflate_multi: this is not a clip')
for _ in range(radius):
src = src.std.Inflate(planes=planes)
return src
def mt_inpand_multi(src: vs.VideoNode, mode: str = 'rectangle', planes: Optional[Union[int, Sequence[int]]] = None, sw: int = 1, sh: int = 1) -> vs.VideoNode:
'''
Calls std.Minimum multiple times in order to shrink the mask from the desired width and height.
Parameters:
src: Clip to process.
mode: "rectangle", "ellipse" or "losange". Ellipses are actually combinations of rectangles and losanges and look more like octogons.
Losanges are truncated (not scaled) when sw and sh are not equal.
planes: Specifies which planes will be processed. Any unprocessed planes will be simply copied.
sw: Shrinking shape width. 0 is allowed.
sh: Shrinking shape height. 0 is allowed.
'''
if not isinstance(src, vs.VideoNode):
raise vs.Error('mt_inpand_multi: this is not a clip')
if sw > 0 and sh > 0:
mode_m = [0, 1, 0, 1, 1, 0, 1, 0] if mode == 'losange' or (mode == 'ellipse' and (sw % 3) != 1) else [1, 1, 1, 1, 1, 1, 1, 1]
elif sw > 0:
mode_m = [0, 0, 0, 1, 1, 0, 0, 0]
elif sh > 0:
mode_m = [0, 1, 0, 0, 0, 0, 1, 0]
else:
mode_m = None
if mode_m is not None:
src = mt_inpand_multi(src.std.Minimum(planes=planes, coordinates=mode_m), mode=mode, planes=planes, sw=sw - 1, sh=sh - 1)
return src
# =============================================================================
# Motion-vector plugin wrapper (mvtools / mvsf / mvutensils)
# =============================================================================
#
# Every other script in this repository that needs motion estimation/compensation
# calls into this wrapper instead of `core.mv.*` / `core.mvsf.*` directly. That gives
# us one place to optionally route calls to mvutensils (https://github.com/myrsloik/mvutensils,
# namespace `core.mvu`) while keeping every call site written in the familiar
# mvtools/mvsf argument style (isb=, delta=, hpad=, lambda_=, dct=, thsadc=, ...).
#
# Behaviour:
# - If core.mvu is NOT loaded: calls are forwarded to core.mv / core.mvsf unchanged
# (core.mvsf is used for float clips when available, exactly like the old code did).
# - If core.mvu IS loaded (and not explicitly disabled): arguments are translated
# to mvutensils' conventions per https://github.com/myrsloik/mvutensils#porting-from-mvtools
# and the call is forwarded to core.mvu.
#
# Known lossy/approximate translations (documented inline at each call site below):
# - Analyse/Recalculate: `dct` (0-10) only maps cleanly to mvu's boolean `satd`
# for dct in {0, 5}; other dct modes have no mvutensils equivalent and are
# approximated as satd=True for dct>=5, satd=False otherwise.
# - Analyse: mvu removed the `truemotion` preset. When `lambda_`/`lsad`/`pnew` are
# not explicitly given we fall back to mvu's own defaults (mvlambda=1000, lsad=400,
# pnew=25), which match old truemotion=True except lsad (was 1200 under
# truemotion=True, mvu always uses 400).
# - Degrain family: `limit`/`limitc` (0-255 int, 255 == "off") are converted to
# mvu's float `limit` (per-plane, inf == "off"), scaled to the clip's peak value.
# - Mask: mvu splits `Mask(kind=0/1/2)` into three separate functions and drops the
# `clip`/`ysc` arguments, returning a single grayscale plane instead of a
# clip-shaped/UV-colored mask. Code relying on the old multi-plane mask shape
# needs to be checked when switching a given call site over.
# - thscd2: rescaled from the old 0-256 integer to mvu's 0-100 float percentage.
#
# Usage in other files:
# from misc import MV
# sup = MV.Super(clip, hpad=16, vpad=16, pel=2, blksize=8, overlap=2)
# bvec = MV.Analyse(sup, blksize=8, overlap=2, isb=True, delta=1)
# fvec = MV.Analyse(sup, blksize=8, overlap=2, isb=False, delta=1)
# den = MV.Degrain1(clip, sup, bvec, fvec, thsad=400)
#
# `blksize`/`overlap` are new, *optional* keyword-only additions to `Super()` (mvtools'
# Super never took them). They are required only when mvutensils is actually in use
# (mvutensils pads the super clip itself and needs to know the block geometry up
# front) and should be passed the same values used in the matching Analyse() call.
def has_mvutensils() -> bool:
'''Returns True if the mvutensils plugin (core.mvu) is loaded.'''
return hasattr(core, 'mvu')
def _mvu_scale_thscd2(thscd2: float) -> float:
'''mvtools/mvsf thscd2 is a 0-256 int; mvutensils thscd2 is a 0-100 float percentage.'''
return max(0.0, min(100.0, thscd2 * 100.0 / 256.0))
def _mvu_search_mode(search: int) -> int:
'''mvtools search modes 0-7 -> mvutensils 0-5 (old modes 0/1 dropped, rest shifted by -2).'''
if search in (0, 1):
# No 1:1 equivalent (old logarithmic/one-time-search modes were dropped).
# Fall back to mvutensils' closest remaining option (0 = logarithmic/diamond).
return 0
return max(0, min(5, search - 2))
def _mvu_rfilter(rfilter: int) -> int:
'''mvtools rfilter 0-4 -> mvutensils rfilter 0-2 (old modes 1 and 3 dropped).'''
return {0: 0, 1: 0, 2: 1, 3: 1, 4: 2}.get(rfilter, 1)
def _mvu_dct_to_satd(dct: int) -> bool:
'''mvtools dct (0-10) -> mvutensils boolean satd. Only dct in {0, 5} map cleanly.'''
return dct >= 5
def _mvu_plane_to_planes(plane: int, clip: vs.VideoNode) -> List[int]:
'''mvtools DegrainN `plane` (0=Y,1=U,2=V,3=UV,4=YUV) -> mvutensils `planes` list.'''
if plane == 4:
return list(range(clip.format.num_planes))
if plane == 3:
return [1, 2]
if plane in (0, 1, 2):
return [plane]
raise vs.Error(f'MV: unsupported plane value {plane!r}')
def _mvu_limit_to_float(limit: Optional[float], clip: vs.VideoNode) -> float:
'''mvtools DegrainN `limit`/`limitc` (0-255 int, 255 = off) -> mvutensils float limit (inf = off).'''
if limit is None or limit >= 255:
return float('inf')
if clip.format.sample_type == vs.FLOAT:
return limit / 255.0
peak = (1 << clip.format.bits_per_sample) - 1
return limit * peak / 255.0
class MotionVectors:
'''
mvtools/mvsf-style wrapper that optionally routes to mvutensils (core.mvu).
See the module-level comment above `has_mvutensils()` for the full rationale and
list of approximate/lossy argument translations. Instantiate once per preference
(the default `MV` singleton below auto-detects mvutensils) and call the familiar
mvtools method names/argument names on it; the correct backend is picked
automatically per call based on clip format and availability.
'''
def __init__(self, prefer_mvutensils: Optional[bool] = None):
'''
prefer_mvutensils:
None -> use mvutensils automatically whenever core.mvu is available (default).
True -> require mvutensils; raises if core.mvu isn't loaded.
False -> always use legacy core.mv / core.mvsf, even if core.mvu is available.
NOTE: availability is checked live on every call
'''
self._prefer_mvutensils = prefer_mvutensils
@property
def use_mvu(self) -> bool:
if self._prefer_mvutensils is True:
if not has_mvutensils():
raise vs.Error('MotionVectors: mvutensils (core.mvu) was requested but is not loaded')
return True
if self._prefer_mvutensils is False:
return False
return has_mvutensils()
# -- internal helpers ----------------------------------------------------
def _legacy_ns(self, clip: vs.VideoNode):
'''Picks core.mvsf for float clips (if available) or core.mv, exactly like the old code did.'''
if clip.format.sample_type == vs.FLOAT and hasattr(core, 'mvsf'):
return core.mvsf
return core.mv
def _legacy_analyse_func(self, ns):
# Some mvsf builds expose "Analyze", others "Analyse"; mv always uses "Analyse".
return getattr(ns, 'Analyse', None) or getattr(ns, 'Analyze')
# -- Super -----------------------------------------------------------
def Super(
self,
clip: vs.VideoNode,
hpad: int = 8,
vpad: int = 8,
pel: int = 2,
levels: int = 0,
chroma: bool = True,
sharp: int = 2,
rfilter: int = 2,
pelclip: Optional[vs.VideoNode] = None,
*,
blksize: Optional[int] = None,
blksizev: Optional[int] = None,
overlap: Optional[int] = None,
overlapv: Optional[int] = None,
) -> vs.VideoNode:
'''
blksize/overlap are only required when mvutensils is in use (it pads the super
clip itself and needs the block geometry up front); pass the same values you
use in the matching Analyse() call. They are ignored by the legacy backend.
'''
if self.use_mvu:
if blksize is None or overlap is None:
raise vs.Error(
'MV.Super: mvutensils requires blksize and overlap to be passed '
'(use the same values as the matching Analyse() call)'
)
return core.mvu.Super(
clip,
blksize=[blksize, blksizev or blksize],
overlap=[overlap, overlapv or overlap],
pad=[max(1, hpad), max(1, vpad)], # pad must be positive
pel=pel,
sharp=sharp,
rfilter=_mvu_rfilter(rfilter),
onelevel=(levels == 1),
pelclip=pelclip,
)
ns = self._legacy_ns(clip)
return ns.Super(clip, hpad=hpad, vpad=vpad, pel=pel, levels=levels, chroma=chroma, sharp=sharp, rfilter=rfilter, pelclip=pelclip)
# -- Analyse / Analyze -------------------------------------------------
def _mvu_analyse_kwargs(
self, blksize, blksizev, levels, search, searchparam, pelsearch, lambda_, chroma,
truemotion, lsad, plevel, global_, pnew, pzero, pglobal, overlap, overlapv,
badsad, badrange, meander, trymany, fields, tff, dct,
) -> dict:
'''Shared mvutensils Analyse/AnalyseMany kwarg translation (everything except delta/isb/radius).'''
kwargs = dict(
blksize=[blksize, blksizev or blksize],
overlap=[overlap, overlapv or overlap],
levels=levels,
search=_mvu_search_mode(search),
searchparam=searchparam,
mvlambda=(lambda_ if lambda_ is not None else (1000 if truemotion else 0)),
chroma=chroma,
lsad=(lsad if lsad is not None else 400),
plevel=(plevel if plevel is not None else 1),
globalmv=(global_ if global_ is not None else True),
pnew=(pnew if pnew is not None else 25),
pglobal=pglobal,
badsad=badsad,
badrange=badrange,
meander=meander,
trymany=(2 if trymany else 0),
fields=fields,
tff=bool(tff),
satd=_mvu_dct_to_satd(dct),
)
kwargs['pzero'] = pzero if pzero is not None else kwargs['pnew']
if pelsearch:
kwargs['pelsearch'] = pelsearch
return kwargs
def _analyse(
self,
super: vs.VideoNode,
blksize: int = 8,
blksizev: Optional[int] = None,
levels: int = 0,
search: int = 4,
searchparam: int = 2,
pelsearch: int = 0,
isb: bool = False,
lambda_: Optional[int] = None,
chroma: bool = True,
delta: int = 1,
truemotion: bool = True,
lsad: Optional[int] = None,
plevel: Optional[int] = None,
global_: Optional[bool] = None,
pnew: Optional[int] = None,
pzero: Optional[int] = None,
pglobal: int = 0,
overlap: int = 0,
overlapv: Optional[int] = None,
divide: int = 0,
badsad: int = 10000,
badrange: int = 24,
meander: bool = True,
trymany: bool = False,
fields: bool = False,
tff: Optional[bool] = None,
search_coarse: int = 3,
dct: int = 0,
) -> vs.VideoNode:
if self.use_mvu:
kwargs = self._mvu_analyse_kwargs(
blksize, blksizev, levels, search, searchparam, pelsearch, lambda_, chroma,
truemotion, lsad, plevel, global_, pnew, pzero, pglobal, overlap, overlapv,
badsad, badrange, meander, trymany, fields, tff, dct,
)
# isb=True (old "is backward") -> positive delta; isb=False (forward) -> negative delta.
kwargs['delta'] = delta if isb else -delta
return core.mvu.Analyse(super, **kwargs)
ns = self._legacy_ns(super)
func = self._legacy_analyse_func(ns)
return func(
super, blksize=blksize, blksizev=blksizev, levels=levels, search=search, searchparam=searchparam,
pelsearch=pelsearch, isb=isb, lambda_=lambda_, chroma=chroma, delta=delta, truemotion=truemotion,
lsad=lsad, plevel=plevel, global_=global_, pnew=pnew, pzero=pzero, pglobal=pglobal, overlap=overlap,
overlapv=overlapv, divide=divide, badsad=badsad, badrange=badrange, meander=meander, trymany=trymany,
fields=fields, tff=tff, search_coarse=search_coarse, dct=dct,
)
def Analyse(self, *args, **kwargs) -> vs.VideoNode:
return self._analyse(*args, **kwargs)
def Analyze(self, *args, **kwargs) -> vs.VideoNode:
return self._analyse(*args, **kwargs)
# -- AnalyseMany ---------------------------------------------------------
def AnalyseMany(
self,
super: vs.VideoNode,
radius: int = 1,
delta: int = 1,
blksize: int = 8,
blksizev: Optional[int] = None,
levels: int = 0,
search: int = 4,
searchparam: int = 2,
pelsearch: int = 0,
lambda_: Optional[int] = None,
chroma: bool = True,
truemotion: bool = True,
lsad: Optional[int] = None,
plevel: Optional[int] = None,
global_: Optional[bool] = None,
pnew: Optional[int] = None,
pzero: Optional[int] = None,
pglobal: int = 0,
overlap: int = 0,
overlapv: Optional[int] = None,
badsad: int = 10000,
badrange: int = 24,