/
base.py
2299 lines (1883 loc) · 78.8 KB
/
base.py
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
import math
from enum import Enum
from functools import partial
from os import PathLike
from typing import Any, Callable, Dict, List, Optional, Union
import vapoursynth as vs
from rekt import rektlvls
from vapoursynth import core
from vsutil import depth as vsuDepth
from vsutil import get_depth, join, scale_value, split
from .types.dovi import HdrMeasurement
from .types.misc import ST2084_PEAK_LUMINANCE, Hdr10PlusHistogram, st2084_eotf, st2084_inverse_eotf
from .types.placebo import PlaceboTonemapOpts
SUBTITLE_DEFAULT_STYLE: str = (
"sans-serif,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000," "0,0,0,0,100,100,0,0,1,2,0,7,10,10,10,1"
)
def Depth(clip: vs.VideoNode, bits: int, **kwargs) -> vs.VideoNode:
"""
This is just a vsutil.depth wrapper that doesn't dither for high bit depth.
The reason for this is that repeated error diffusion can be destructive, so if we assume most filtering is done at
high bit depth (which it should), this should keep that from happening while still performing it before outputting.
"""
dither_type = "error_diffusion" if bits < 16 else "none"
return vsuDepth(clip, bits, dither_type=dither_type, **kwargs)
def ReplaceFrames(
clipa: vs.VideoNode,
clipb: vs.VideoNode,
mappings: Optional[str] = None,
filename: Optional[Union[str, PathLike]] = None,
) -> vs.VideoNode:
"""
ReplaceFramesSimple wrapper that uses the RemapFrames plugin and works for different length clips.
https://github.com/Irrational-Encoding-Wizardry/Vapoursynth-RemapFrames
:param clipa: Main clip.
:param clipb: Filtered clip to splice into main clip.
:param mappings: String of frames to be replaced, e.g. "[0 500] [1000 1500]".
:param filename: File with frames to be replaced.
:return: clipa with clipb spliced in according to specified frames.
"""
try:
return core.remap.Rfs(baseclip=clipa, sourceclip=clipb, mappings=mappings, filename=filename)
except vs.Error:
# copy-pasted from fvsfunc, sadly
def __fvsfunc_remap(clipa: vs.VideoNode, clipb: vs.VideoNode, mappings, filename) -> vs.VideoNode:
import re
if filename:
with open(filename, "r") as mf:
mappings += f"\n{mf.read()}"
# Some people used this as separators and wondered why it wasn't working
mappings = mappings.replace(",", " ").replace(":", " ")
frames = re.findall(r"\d+(?!\d*\s*\d*\s*\d*\])", mappings)
ranges = re.findall(r"\[\s*\d+\s+\d+\s*\]", mappings)
maps = []
for range_ in ranges:
maps.append([int(x) for x in range_.strip("[ ]").split()])
for frame in frames:
maps.append([int(frame), int(frame)])
maps = [x for y in maps for x in y]
start, end = min(maps), max(maps)
if (end - start) > len(clipb):
raise ValueError("ReplaceFrames: mappings exceed clip length!")
if len(clipb) < len(clipa):
clipb = clipb + clipb.std.BlankClip(length=len(clipa) - len(clipb))
elif len(clipb) > len(clipa):
clipb = clipb.std.Trim(0, len(clipa) - 1)
return clipa, clipb, mappings, filename
clipa, clipb, mappings, filename = __fvsfunc_remap(clipa, clipb, mappings, filename)
return core.remap.Rfs(baseclip=clipa, sourceclip=clipb, mappings=mappings, filename=filename)
def bbmod(
clip: vs.VideoNode,
top: int = 0,
bottom: int = 0,
left: int = 0,
right: int = 0,
thresh: Any = None,
blur: int = 20,
planes: Any = None,
y: Optional[bool] = None,
u: Optional[bool] = None,
v: Optional[bool] = None,
scale_thresh: Optional[bool] = None,
cpass2: bool = False,
csize: int = 2,
scale_offsets: bool = True,
cTop: Optional[int] = None,
cBottom: Optional[int] = None,
cLeft: Optional[int] = None,
cRight: Optional[int] = None,
) -> vs.VideoNode:
"""
bbmod helper for a significant speedup from cropping unnecessary pixels before processing.
:param clip: Clip to be processed.
:param top: Top rows to be processed.
:param bottom: Bottom rows to be processed.
:param left: Left columns to be processed.
:param right: Right columns to be processed.
:param thresh: Largest change allowed. Scale of 0-128, default is 128 (assuming 8-bit).
Specify a list for [luma, chroma] or [y, u, v].
:param blur: Processing strength, lower values are more aggressive. Default is 20, not 999 like the old bbmod.
Specify a list for [luma, chroma] or [y, u, v].
:param planes: Planes to process. Overwrites y, u, v. Defaults to all planes.
:param y: Boolean whether luma plane is processed. Default is True.
:param u: Boolean whether first chroma plane is processed. Default is True.
:param v: Boolean whether second chroma plane is processed. Default is True.
:param scale_thresh: Boolean whether thresh value is scaled from 8-bit to source bit depth.
If thresh <= 128, this defaults to True, else False.
:param cpass2: Second, significantly stronger, chroma pass. If enabled, default for chroma blur is blur * 2 and
chroma thresh is thresh / 10.
:param csize: Size to be cropped to. This might help maintain details at the cost of processing speed.
:param scale_offsets: Whether scaling should take offsets into account in vsutil.scale_value.
If you don't know what this means, don't change it. Thresh never uses scale_offsets.
:param cTop: Legacy top.
:param cBottom: Legacy bottom.
:param cLeft: Legacy left.
:param cRight: Legacy right.
:return: Clip with color offsets fixed.
"""
if clip.format.color_family not in (vs.YUV, vs.GRAY):
raise ValueError("bbmod: only YUV and GRAY clips are supported")
if cTop is not None:
top = cTop
if cBottom is not None:
bottom = cBottom
if cLeft is not None:
left = cLeft
if cRight is not None:
right = cRight
if planes is not None:
if isinstance(planes, int):
planes = [planes]
y = bool(0 in planes)
u = bool(1 in planes)
v = bool(2 in planes)
elif clip.format.color_family == vs.YUV:
if y is None:
y = True
if u is None:
u = True
if v is None:
v = True
else:
if y is None and not u and not v:
y = True
u = False
v = False
elif y is True:
u = False
v = False
else:
y = False
u = True
v = False
depth = clip.format.bits_per_sample
if thresh is None:
thresh = scale_value(128, 8, depth, scale_offsets=scale_offsets)
if scale_thresh is None:
if thresh < 1:
scale_thresh = False
elif thresh < 129:
scale_thresh = True
else:
scale_thresh = False
filtered = clip
c_left = max(left * csize, 4)
c_right = max(right * csize, 4)
c_top = max(top * csize, 4)
c_bottom = max(bottom * csize, 4)
f_width, f_height = filtered.width, filtered.height
if left > 0 and right > 0:
left_clip = filtered.std.Crop(left=0, right=f_width - c_left, top=0, bottom=0)
middle_clip = filtered.std.Crop(left=c_left, right=c_right, top=0, bottom=0)
right_clip = filtered.std.Crop(left=f_width - c_right, right=0, top=0, bottom=0)
left_clip = bbmoda(
left_clip,
cTop=0,
cBottom=0,
cLeft=left,
cRight=0,
thresh=thresh,
blur=blur,
y=y,
u=u,
v=v,
scale_thresh=scale_thresh,
cpass2=cpass2,
csize=csize,
scale_offsets=scale_offsets,
)
right_clip = bbmoda(
right_clip,
cTop=0,
cBottom=0,
cLeft=0,
cRight=right,
thresh=thresh,
blur=blur,
y=y,
u=u,
v=v,
scale_thresh=scale_thresh,
cpass2=cpass2,
csize=csize,
scale_offsets=scale_offsets,
)
filtered = core.std.StackHorizontal(clips=[left_clip, middle_clip, right_clip])
if left > 0 and right == 0:
left_clip = filtered.std.Crop(left=0, right=f_width - c_left, top=0, bottom=0)
middle_clip = filtered.std.Crop(left=c_left, right=0, top=0, bottom=0)
left_clip = bbmoda(
left_clip,
cTop=0,
cBottom=0,
cLeft=left,
cRight=0,
thresh=thresh,
blur=blur,
y=y,
u=u,
v=v,
scale_thresh=scale_thresh,
cpass2=cpass2,
csize=csize,
scale_offsets=scale_offsets,
)
filtered = core.std.StackHorizontal(clips=[left_clip, middle_clip])
if left == 0 and right > 0:
right_clip = filtered.std.Crop(left=f_width - c_right, right=0, top=0, bottom=0)
middle_clip = filtered.std.Crop(left=0, right=c_right, top=0, bottom=0)
right_clip = bbmoda(
right_clip,
cTop=0,
cBottom=0,
cLeft=0,
cRight=right,
thresh=thresh,
blur=blur,
y=y,
u=u,
v=v,
scale_thresh=scale_thresh,
cpass2=cpass2,
csize=csize,
scale_offsets=scale_offsets,
)
filtered = core.std.StackHorizontal(clips=[middle_clip, right_clip])
if top > 0 and bottom > 0:
top_clip = filtered.std.Crop(left=0, right=0, top=0, bottom=f_height - c_top)
middle_clip = filtered.std.Crop(left=0, right=0, top=c_top, bottom=c_bottom)
bottom_clip = filtered.std.Crop(left=0, right=0, top=f_height - c_bottom, bottom=0)
top_clip = bbmoda(
top_clip,
cTop=top,
cBottom=0,
cLeft=0,
cRight=0,
thresh=thresh,
blur=blur,
y=y,
u=u,
v=v,
scale_thresh=scale_thresh,
cpass2=cpass2,
csize=csize,
scale_offsets=scale_offsets,
)
bottom_clip = bbmoda(
bottom_clip,
cTop=0,
cBottom=bottom,
cLeft=0,
cRight=0,
thresh=thresh,
blur=blur,
y=y,
u=u,
v=v,
scale_thresh=scale_thresh,
cpass2=cpass2,
csize=csize,
scale_offsets=scale_offsets,
)
filtered = core.std.StackVertical(clips=[top_clip, middle_clip, bottom_clip])
if top > 0 and bottom == 0:
top_clip = filtered.std.Crop(left=0, right=0, top=0, bottom=f_height - c_top)
middle_clip = filtered.std.Crop(left=0, right=0, top=c_top, bottom=0)
top_clip = bbmoda(
top_clip,
cTop=top,
cBottom=0,
cLeft=0,
cRight=0,
thresh=thresh,
blur=blur,
y=y,
u=u,
v=v,
scale_thresh=scale_thresh,
cpass2=cpass2,
csize=csize,
scale_offsets=scale_offsets,
)
filtered = core.std.StackVertical(clips=[top_clip, middle_clip])
if top == 0 and bottom > 0:
bottom_clip = filtered.std.Crop(left=0, right=0, top=f_height - c_bottom, bottom=0)
middle_clip = filtered.std.Crop(left=0, right=0, top=0, bottom=c_bottom)
bottom_clip = bbmoda(
bottom_clip,
cTop=0,
cBottom=bottom,
cLeft=0,
cRight=0,
thresh=thresh,
blur=blur,
y=y,
u=u,
v=v,
scale_thresh=scale_thresh,
cpass2=cpass2,
csize=csize,
scale_offsets=scale_offsets,
)
filtered = core.std.StackVertical(clips=[middle_clip, bottom_clip])
return filtered
def bbmoda(
c: vs.VideoNode,
cTop: int = 0,
cBottom: int = 0,
cLeft: int = 0,
cRight: int = 0,
thresh: Any = 128,
blur: Any = 999,
y: bool = True,
u: bool = True,
v: bool = True,
scale_thresh: bool = True,
cpass2: bool = False,
csize: int = 2,
scale_offsets: bool = True,
) -> vs.VideoNode:
"""
bbmod, port from Avisynth's function, a mod of BalanceBorders
The function changes the extreme pixels of the clip, to fix or attenuate dirty borders
Any bit depth
Inspired from BalanceBorders from
https://github.com/WolframRhodium/muvsfunc/ and
https://github.com/fdar0536/Vapoursynth-BalanceBorders/
> Usage: bbmod(c, cTop, cBottom, cLeft, cRight, thresh, blur)
* c: Input clip. The image area "in the middle" does not change during processing.
The clip can be any format, which differs from Avisynth's equivalent.
* cTop, cBottom, cLeft, cRight (int, 0-inf): The number of variable pixels on each side.
* thresh (int, 0~128, default 128): Threshold of acceptable changes for local color matching in 8 bit scale.
Recommended: 0~16 or 128
* blur (int, 1~inf, default 999): Degree of blur for local color matching.
Smaller values give a more accurate color match, larger values give a more accurate picture transfer.
Recommended: 1~20 or 999
Notes:
1) At default values of thresh = 128 blur = 999:
You will get a series of pixels that have been changed only by selecting
the color for each row in its entirety, without local selection;
The colors of neighboring pixels may be very different in some places
but there will be no change in the nature of the picture.
With thresh = 128 and blur = 1 you get almost the same rows of pixels, i.e.
The colors between them will coincide completely, but the original pattern will be lost.
2) Beware of using a large number of pixels to change in combination with a high level of "thresh",
and a small "blur" that can lead to unwanted artifacts "in a clean place".
For each function call, try to set as few pixels as possible to change
and as low a threshold as possible "thresh" (when using blur 0..16).
"""
funcName = "bbmoda"
if not isinstance(c, vs.VideoNode):
raise TypeError(funcName + ': "c" must be a clip!')
if isinstance(thresh, (int, float)):
# thresh needs to be lower for chroma for cpass2
if cpass2:
thresh = [thresh] + (2 * [round(thresh / 10)])
else:
thresh = 3 * [thresh]
elif len(thresh) == 2:
thresh.append(thresh[1])
if scale_thresh:
thresh[0] = scale_value(thresh[0], 8, c.format.bits_per_sample, scale_offsets=False)
i = 1
for _ in thresh[1:]:
thresh[i] = scale_value(thresh[i], 8, c.format.bits_per_sample, scale_offsets=False, chroma=False)
i += 1
if isinstance(blur, int):
# blur should also be higher
if cpass2:
blur = [blur] + 2 * [blur * 2]
else:
blur = 3 * [blur]
elif len(blur) == 2:
blur.append(blur[1])
for _ in blur:
if _ <= 0:
raise ValueError(funcName + ": 'blur' has an incorrect value! (0 ~ inf]")
for _ in thresh:
if _ <= 0 and c.format.sample_type == vs.INTEGER:
raise ValueError(funcName + ": 'thresh' has an incorrect value! (0 ~ inf]")
def btb(c: vs.VideoNode, cTop: int, thresh: Any, blur: Any) -> vs.VideoNode:
cWidth = c.width
cHeight = c.height
sw, sh = c.format.subsampling_w + 1, c.format.subsampling_h + 1
cTop = min(cTop, cHeight - 1)
blurWidth = [
max(8, math.floor(cWidth / blur[0])),
max(8, math.floor(cWidth / blur[1])),
max(8, math.floor(cWidth / blur[2])),
]
scale128 = str(scale_value(128, 8, c.format.bits_per_sample, scale_offsets=scale_offsets, chroma=True))
uvexpr_ = "z y - x +"
uvexpr = []
for t in [1, 2]:
uvexpr.append(
(
f"{uvexpr_} x - {thresh[t]} > x {thresh[t]} + {uvexpr_} x - "
f"-{thresh[t]} < x {thresh[t]} - {uvexpr_} ? ?"
)
)
if c.format.sample_type == vs.INTEGER:
exprchroma = f"x {scale128} - abs 2 *"
expruv = f"z y / 8 min 0.4 max x {scale128} - * {scale128} + x - {scale128} +"
else:
exprchroma = "x abs 2 *"
expruv = "z .5 + y .5 + / 8 min .4 max x .5 + * x - .5 +"
scale16 = str(scale_value(16, 8, c.format.bits_per_sample, scale_offsets=scale_offsets))
yexpr = f"z {scale16} - y {scale16} - / 8 min 0.4 max x {scale16} - * {scale16} +"
yexpr = f"{yexpr} x - {thresh[0]} > x {thresh[0]} + {yexpr} x - -{thresh[0]} < x {thresh[0]} - {yexpr} ? ?"
if y and u and v and blur[0] == blur[1] == blur[2] and thresh[0] == thresh[1] == thresh[2] and sw == sh == 1:
c2 = core.resize.Point(c, cWidth * csize, cHeight * csize)
last = core.std.CropAbs(c2, cWidth * csize, csize, 0, cTop * csize)
last = core.resize.Point(last, cWidth * csize, cTop * csize)
exprchroma = ["", exprchroma]
if cpass2:
referenceBlurChroma = (
last.std.Expr(exprchroma)
.resize.Bicubic(blurWidth[0] * csize, cTop * csize, filter_param_a=1, filter_param_b=0)
.resize.Bicubic(cWidth * csize, cTop * csize, filter_param_a=1, filter_param_b=0)
)
referenceBlur = core.resize.Bicubic(
last, blurWidth[0] * csize, cTop * csize, filter_param_a=1, filter_param_b=0
)
referenceBlur = referenceBlur.resize.Bicubic(
cWidth * csize, cTop * csize, filter_param_a=1, filter_param_b=0
)
original = core.std.CropAbs(c2, cWidth * csize, cTop * csize, 0, 0)
last = core.resize.Bicubic(original, blurWidth[0] * csize, cTop * csize, filter_param_a=1, filter_param_b=0)
originalBlur = last.resize.Bicubic(cWidth * csize, cTop * csize, filter_param_a=1, filter_param_b=0)
if cpass2:
originalBlurChroma = last.std.Expr(exprchroma).resize.Bicubic(
blurWidth[0] * csize, cTop * csize, filter_param_a=1, filter_param_b=0
)
originalBlurChroma = originalBlurChroma.resize.Bicubic(
cWidth * csize, cTop * csize, filter_param_a=1, filter_param_b=0
)
balancedChroma = core.std.Expr(
clips=[original, originalBlurChroma, referenceBlurChroma], expr=["", expruv]
)
balancedLuma = core.std.Expr(
clips=[balancedChroma, originalBlur, referenceBlur], expr=[yexpr, uvexpr[0], uvexpr[1]]
)
else:
balancedLuma = core.std.Expr(
clips=[original, originalBlur, referenceBlur], expr=[yexpr, uvexpr[0], uvexpr[1]]
)
return core.std.StackVertical(
[balancedLuma, core.std.CropAbs(c2, cWidth * csize, (cHeight - cTop) * csize, 0, cTop * csize)]
).resize.Point(cWidth, cHeight)
if c.format.color_family == vs.YUV:
yplane, uplane, vplane = split(c)
elif c.format.color_family == vs.GRAY:
yplane = c
else:
raise ValueError("bbmod: only YUV and GRAY clips are supported")
if y:
c2 = core.resize.Point(yplane, cWidth * csize, cHeight * csize)
last = core.std.CropAbs(c2, cWidth * csize, csize, 0, cTop * csize)
last = core.resize.Point(last, cWidth * csize, cTop * csize)
referenceBlur = core.resize.Bicubic(
last, blurWidth[0] * csize, cTop * csize, filter_param_a=1, filter_param_b=0
).resize.Bicubic(cWidth * csize, cTop * csize, filter_param_a=1, filter_param_b=0)
original = core.std.CropAbs(c2, cWidth * csize, cTop * csize, 0, 0)
last = core.resize.Bicubic(original, blurWidth[0] * csize, cTop * csize, filter_param_a=1, filter_param_b=0)
originalBlur = last.resize.Bicubic(cWidth * csize, cTop * csize, filter_param_a=1, filter_param_b=0)
balancedLuma = core.std.Expr(clips=[original, originalBlur, referenceBlur], expr=yexpr)
yplane = core.std.StackVertical(
clips=[balancedLuma, core.std.CropAbs(c2, cWidth * csize, (cHeight - cTop) * csize, 0, cTop * csize)]
).resize.Point(cWidth, cHeight)
if c.format.color_family == vs.GRAY:
return yplane
def btbc(c2: vs.VideoNode, blurWidth: int, p: int, csize: int) -> vs.VideoNode:
c2 = core.resize.Point(c2, round(cWidth * csize / sw), round(cHeight * csize / sh))
last = core.std.CropAbs(c2, round(cWidth * csize / sw), round(csize / sh), 0, round(cTop * csize / sh))
last = core.resize.Point(last, round(cWidth * csize / sw), round(cTop * csize / sh))
if cpass2:
referenceBlurChroma = last.std.Expr(exprchroma).resize.Bicubic(
round(blurWidth * csize / sw), round(cTop * csize / sh), filter_param_a=1, filter_param_b=0
)
referenceBlurChroma = referenceBlurChroma.resize.Bicubic(
round(cWidth * csize / sw), round(cTop * csize / sh), filter_param_a=1, filter_param_b=0
)
referenceBlur = core.resize.Bicubic(
last, round(blurWidth * csize / sw), round(cTop * csize / sh), filter_param_a=1, filter_param_b=0
).resize.Bicubic(round(cWidth * csize / sw), round(cTop * csize / sh), filter_param_a=1, filter_param_b=0)
original = core.std.CropAbs(c2, round(cWidth * csize / sw), round(cTop * csize / sh), 0, 0)
last = core.resize.Bicubic(
original, round(blurWidth * csize / sw), round(cTop * csize / sh), filter_param_a=1, filter_param_b=0
)
originalBlur = last.resize.Bicubic(
round(cWidth * csize / sw), round(cTop * csize / sh), filter_param_a=1, filter_param_b=0
)
if cpass2:
originalBlurChroma = last.std.Expr(exprchroma).resize.Bicubic(
round(blurWidth * csize / sw), round(cTop * csize / sh), filter_param_a=1, filter_param_b=0
)
originalBlurChroma = originalBlurChroma.resize.Bicubic(
round(cWidth * csize / sw), round(cTop * csize / sh), filter_param_a=1, filter_param_b=0
)
balancedChroma = core.std.Expr(clips=[original, originalBlurChroma, referenceBlurChroma], expr=expruv)
balancedLuma = core.std.Expr(clips=[balancedChroma, originalBlur, referenceBlur], expr=expruv)
else:
balancedLuma = core.std.Expr(clips=[original, originalBlur, referenceBlur], expr=uvexpr[p - 1])
return core.std.StackVertical(
[
balancedLuma,
c2.std.CropAbs(
left=0,
top=round(cTop * csize / sh),
width=round(cWidth * csize / sw),
height=round(cHeight * csize / sh) - round(cTop * csize / sh),
),
]
).resize.Point(round(cWidth / sw), round(cHeight / sh))
if c.format.color_family == vs.GRAY:
return btbc(yplane, blurWidth[1], 1, csize)
if u:
uplane = btbc(uplane, blurWidth[1], 1, csize * max(sw, sh))
if v:
vplane = btbc(vplane, blurWidth[2], 2, csize * max(sw, sh))
return core.std.ShufflePlanes([yplane, uplane, vplane], [0, 0, 0], vs.YUV)
if cTop > 0:
c = btb(c, cTop, thresh, blur).std.Transpose().std.FlipHorizontal()
else:
c = core.std.Transpose(c).std.FlipHorizontal()
if cLeft > 0:
c = btb(c, cLeft, thresh, blur).std.Transpose().std.FlipHorizontal()
else:
c = core.std.Transpose(c).std.FlipHorizontal()
if cBottom > 0:
c = btb(c, cBottom, thresh, blur).std.Transpose().std.FlipHorizontal()
else:
c = core.std.Transpose(c).std.FlipHorizontal()
if cRight > 0:
c = btb(c, cRight, thresh, blur).std.Transpose().std.FlipHorizontal()
else:
c = core.std.Transpose(c).std.FlipHorizontal()
return c
def AddBordersMod(
clip: vs.VideoNode,
left: int = 0,
top: int = 0,
right: int = 0,
bottom: int = 0,
lsat: float = 0.88,
tsat: float = 0.2,
rsat: Optional[float] = None,
bsat: float = 0.2,
color: Union[str, List[float]] = None,
) -> vs.VideoNode:
"""
VapourSynth port of AddBordersMod.
Fuck writing a proper docstring.
:param clip:
:param left:
:param top:
:param right:
:param bottom:
:param lsat:
:param tsat:
:param rsat:
:param bsat:
:param color:
:return:
"""
if clip.format.subsampling_w != 1 and clip.format.subsampling_h != 1:
raise TypeError("AddBordersMod: input must be 4:2:0")
if rsat is None:
if right > 2:
rsat = 0.4
else:
rsat = 0.28
if left > 0:
if lsat != 1:
lcl = clip.std.AddBorders(left=left, color=color)
lcl = lcl.std.CropAbs(left, clip.height)
lcm = clip.std.CropAbs(2, clip.height)
lcm = saturation(lcm, sat=lsat)
lcr = clip.std.Crop(left=2)
clip = core.std.StackHorizontal([lcl, lcm, lcr])
else:
clip = clip.std.AddBorders(left=left, color=color)
if top > 2:
tcl = clip.std.AddBorders(top=top, color=color)
tcl = tcl.std.CropAbs(clip.width, top - 2)
tcm = clip.std.CropAbs(clip.width, 2)
tcm = saturation(tcm, sat=tsat)
tcm = rektlvls(tcm, [0, 1], [16 - 235] * 2, prot_val=None)
clip = core.std.StackVertical([tcl, tcm, clip])
elif top == 2:
tcl = clip.std.CropAbs(clip.width, 2)
tcl = saturation(tcl, sat=tsat)
tcl = rektlvls(tcl, [0, 1], [16 - 235] * 2, prot_val=None)
clip = core.std.StackVertical([tcl, clip])
if right > 2:
rcm = clip.std.Crop(left=clip.width - 2)
rcm = saturation(rcm, sat=rsat)
rcm = rektlvls(rcm, colnum=[0, 1], colval=[16 - 235] * 2, prot_val=None)
rcr = clip.std.AddBorders(right=right, color=color)
rcr = rcr.std.Crop(left=clip.width + 2)
clip = core.std.StackHorizontal([clip, rcm, rcr])
elif right == 2:
rcr = clip.std.Crop(left=clip.width - 2)
rcr = saturation(rcr, sat=rsat)
rcr = rektlvls(rcr, colnum=[0, 1], colval=[16 - 235] * 2, prot_val=None)
clip = core.std.StackHorizontal([clip, rcr])
if bottom > 2:
bcm = clip.std.Crop(top=clip.height - 2)
bcm = saturation(bcm, sat=bsat)
bcm = rektlvls(bcm, [0, 1], [16 - 235] * 2, prot_val=None)
bcr = clip.std.AddBorders(bottom=bottom)
bcr = bcr.std.Crop(top=clip.height + 2)
clip = core.std.StackVertical([clip, bcm, bcr])
elif bottom == 2:
bcr = clip.std.Crop(top=clip.height - 2)
bcr = saturation(bcr, sat=bsat)
bcr = rektlvls(bcr, [0, 1], [16 - 235] * 2, prot_val=None)
clip = core.std.StackVertical([clip, bcr])
return clip
def zresize(
clip: vs.VideoNode,
preset: Optional[int] = None,
width: Optional[int] = None,
height: Optional[int] = None,
left: int = 0,
right: int = 0,
top: int = 0,
bottom: int = 0,
kernel: str = "spline36",
ar: float = 16 / 9,
dither_type="error_diffusion",
**kwargs,
) -> vs.VideoNode:
# VSEdit doesn't like the global dict
RESIZEDICT: Dict = {
"bilinear": core.resize.Bilinear,
"bicubic": core.resize.Bicubic,
"point": core.resize.Point,
"lanczos": core.resize.Lanczos,
"spline16": core.resize.Spline16,
"spline36": core.resize.Spline36,
"spline64": core.resize.Spline64,
}
orig_w = clip.width
orig_h = clip.height
orig_cropped_w = orig_w - left - right
orig_cropped_h = orig_h - top - bottom
if preset:
if orig_cropped_w / orig_cropped_h > ar:
return zresize(
clip, width=int(ar * preset), left=left, right=right, top=top, bottom=bottom, kernel=kernel, **kwargs
)
return zresize(clip, height=preset, left=left, right=right, top=top, bottom=bottom, kernel=kernel, **kwargs)
if (width is None) and (height is None):
width = orig_w
height = orig_h
rh = rw = 1
elif width is None:
rh = rw = height / orig_cropped_h
elif height is None:
rh = rw = width / orig_cropped_w
else:
rh = height / orig_h
rw = width / orig_w
w = round((orig_cropped_w * rw) / 2) * 2
h = round((orig_cropped_h * rh) / 2) * 2
if orig_w == w and orig_h == h:
# noop
return clip
resizer = RESIZEDICT[kernel.lower()]
fun = {
"clip": clip,
"width": w,
"height": h,
"src_left": left,
"src_top": top,
"src_width": orig_cropped_w,
"src_height": orig_cropped_h,
"dither_type": dither_type,
**kwargs,
}
return resizer(**fun)
def DebandReader(
clip: vs.VideoNode,
csvfile: Union[str, PathLike],
grain: int = 64,
f3kdb_range: int = 30,
delimiter: str = " ",
mask: Optional[vs.VideoNode] = None,
) -> vs.VideoNode:
"""
DebandReader, read a csv file to apply a f3kdb filter for given strengths and frames.
> Usage: DebandReader(clip, csvfile, grain, f3kdb_range)
* csvfile is the path to a csv file containing in each row: <startframe> <endframe> <strength>
* grain is passed as grainy and grainc in the f3kdb filter
* f3kdb_range is passed as range in the f3kdb filter
"""
import csv
depth = get_depth(clip)
filtered = clip if depth <= 16 else Depth(clip, 16)
with open(csvfile) as debandcsv:
csvzones = csv.reader(debandcsv, delimiter=delimiter)
for row in csvzones:
strength = row[2]
db = core.f3kdb.Deband(
clip,
y=strength,
cb=strength,
cr=strength,
grainy=grain,
grainc=grain,
dynamic_grain=True,
range=f3kdb_range,
output_depth=depth,
)
filtered = ReplaceFrames(filtered, db, mappings="[" + row[0] + " " + row[1] + "]")
if mask:
filtered = core.std.MaskedMerge(clip, filtered, mask)
return filtered
class ScreenGenPrefix(str, Enum):
Sequential = "seq"
FrameNo = "frame"
class ScreenGenEncoder(str, Enum):
imwri = "imwri"
fpng = "fpng"
def write_frame(self, clip: vs.VideoNode, frame_num: int, path: PathLike, compression: Optional[int] = None):
if self == self.imwri:
core.imwri.Write(clip, "PNG24", path, overwrite=True).get_frame(frame_num)
elif self == self.fpng:
core.fpng.Write(clip, filename=path, overwrite=True, compression=compression).get_frame(frame_num)
def ScreenGen(
clip: Union[vs.VideoNode, List[vs.VideoNode]],
folder: Union[str, PathLike],
suffix: Optional[Union[str, List[str]]] = None,
prefix: Union[ScreenGenPrefix, str] = ScreenGenPrefix.Sequential,
frame_numbers: Union[Union[str, PathLike], List[int]] = "screens.txt",
start: int = 1,
delim: str = " ",
encoder: Union[ScreenGenEncoder, str] = ScreenGenEncoder.fpng,
fpng_compression: int = 1,
callback: Optional[Callable[[str], None]] = None,
) -> None:
"""
Generates screenshots from a list of frame numbers
:param clip: Clip or list of clips to generate screenshots from
:param folder: is the folder name that is created
:param suffix: str or list of str of the appended file name suffix(es).
Optional, defaults to letters of the alphabet by order in the clip list
:param prefix: the unique identifier for every screenshot file generated
Must match `ScreenGenPrefix` enum, or literals 'seq' or 'frame'
:param frame_numbers: the list of frames, defaults to a file named screens.txt. Either a list or a file
:param start: is the number at which the filenames start
:param encoder: plugin to use to write the PNG. Defaults to fpng if present.
Must match `ScreenGenEncoder` enum.
- imwri: https://github.com/vapoursynth/vs-imwri
- fpng: https://github.com/Mikewando/vsfpng
:param fpng_compression: Compression level to use for fpng. imwri compresses by default
0 - fast compression
1 - slow compression (Default)
2 - uncompressed
:param callback: Log callback instead of printing
Usage:
>>> ScreenGen(src, "Screenshots", "a")\n
>>> ScreenGen(enc, "Screenshots", "b")
or
>>> ScreenGen([src, enc], "Screenshots") # equivalent: src is a, enc is b
"""
from pathlib import Path
folder_path = Path(folder).resolve()
if isinstance(frame_numbers, str):
frame_num_path = Path(frame_numbers).resolve()
if frame_num_path.is_file():
with open(frame_num_path) as f:
screens = f.readlines()
# Keep value before first delim, so that we can parse default detect zones files
screens = [v.split(delim)[0] for v in screens]
# str to int
screens = [int(x.strip()) for x in screens]
else:
raise ValueError("ScreenGen: Path to frame numbers file does not exist")
elif isinstance(frame_numbers, list):
screens = frame_numbers
else:
raise TypeError("ScreenGen: frame_numbers must be a file path or a list of frame numbers")
clips = clip
if not isinstance(clip, list):
clips = [clip]
suffixes = suffix
if suffix is None:
import string
suffixes = list(string.ascii_lowercase)[: len(clips)]
elif not isinstance(suffix, list):
suffixes = [suffix]
if len(clips) != len(suffixes):
raise ValueError("ScreenGen: number of clips must be equal to number of suffixes")
clip_infos = [{"clip": c, "suffix": s} for (c, s) in zip(clips, suffixes)]
if screens:
if not folder_path.is_dir():
folder_path.mkdir()
encoder_final = encoder
has_vsfpng_plugin = HasLoadedPlugin("tools.mike.fpng")
if not has_vsfpng_plugin and encoder_final == ScreenGenEncoder.fpng:
encoder_final = ScreenGenEncoder.imwri
for info in clip_infos:
clip = info["clip"]
suffix = info["suffix"]
rgb_clip = clip.resize.Spline36(format=vs.RGB24, matrix_in_s="709", dither_type="error_diffusion")
for i, num in enumerate(screens, start=start):
if prefix == ScreenGenPrefix.Sequential:
filename = f"{i:02d}{suffix}.png"
elif prefix == ScreenGenPrefix.FrameNo:
filename = f"{num}{suffix}.png"
else:
raise ValueError("ScreenGen: invalid prefix enum value")
final_path = folder_path.joinpath(filename).resolve()
log_str = f"\rScreenGen: Writing file: {filename}"
if prefix != ScreenGenPrefix.FrameNo:
log_str += f", frame: {num}"
if callable(callback):
callback(log_str)
else:
print(end=log_str)