-
Notifications
You must be signed in to change notification settings - Fork 0
/
mvsfunc.py
3261 lines (2881 loc) · 151 KB
/
mvsfunc.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
################################################################################################################################
## mvsfunc - mawen1250's VapourSynth functions
################################################################################################################################
## Requirments:
## fmtconv
## BM3D
################################################################################################################################
## Main functions:
## Depth
## ToRGB
## ToYUV
## BM3D
## VFRSplice
################################################################################################################################
## Runtime functions:
## PlaneStatistics
## PlaneCompare
## ShowAverage
## FilterIf
## FilterCombed
################################################################################################################################
## Utility functions:
## Min
## Max
## Avg
## MinFilter
## MaxFilter
## LimitFilter
## PointPower
## CheckMatrix
## postfix2infix
################################################################################################################################
## Frame property functions:
## SetColorSpace
## AssumeFrame
## AssumeTFF
## AssumeBFF
## AssumeField
## AssumeCombed
################################################################################################################################
## Helper functions:
## CheckVersion
## GetMatrix
## zDepth
## PlaneAverage
## GetPlane
## GrayScale
## Preview
## CheckColorFamily
## RemoveFrameProp
## RegisterFormat
################################################################################################################################
import vapoursynth as vs
import functools
import math
from collections.abc import Sequence
from ._metadata import __version__
if not hasattr(vs, 'core'):
core = vs.get_core()
else:
core = vs.core
################################################################################################################################
VSMaxPlaneNum = 3
################################################################################################################################
################################################################################################################################
################################################################################################################################
################################################################################################################################
## Main functions below
################################################################################################################################
################################################################################################################################
################################################################################################################################
################################################################################################################################
## Main function: Depth()
################################################################################################################################
## Bit depth conversion with dithering (if needed).
## It's a wrapper for fmtc.bitdepth and zDepth (core.resize/zimg).
## Only constant format is supported, frame properties of the input clip is mostly ignored (only available with zDepth).
################################################################################################################################
## Basic parameters
## input {clip}: clip to be converted
## can be of YUV/RGB/Gray color family, can be of 8~16 bit integer or 16/32 bit float
## depth {int}: output bit depth, can be 1~16 bit integer or 16/32 bit float
## note that 1~7 bit content is still stored as 8 bit integer format
## default is the same as that of the input clip
## sample {int}: output sample type, can be 0 (vs.INTEGER) or 1 (vs.FLOAT)
## default is the same as that of the input clip
## fulls {bool}: define if input clip is of full range
## default: None, assume True for RGB/YCgCo input, assume False for Gray/YUV input
## fulld {bool}: define if output clip is of full range
## default is the same as "fulls"
################################################################################################################################
## Advanced parameters
## dither {int|str}: dithering algorithm applied for depth conversion
## - {int}: same as "dmode" in fmtc.bitdepth, will be automatically converted if using zDepth
## - {str}: same as "dither_type" in zDepth, will be automatically converted if using fmtc.bitdepth
## - default:
## - output depth is 32, and conversions without quantization error: 1 | "none"
## - otherwise: 3 | "error_diffusion"
## useZ {bool}: prefer zDepth or fmtc.bitdepth for depth conversion
## When 11,13~15 bit integer or 16 bit float is involved, zDepth is always used.
## - False: prefer fmtc.bitdepth
## - True: prefer zDepth
## default: False
################################################################################################################################
## Parameters of fmtc.bitdepth
## ampo, ampn, dyn, staticnoise, cpuopt, patsize, tpdfo, tpdfn, corplane:
## same as those in fmtc.bitdepth, ignored when useZ=True
## *NOTE* no positional arguments, only keyword arguments are accepted
################################################################################################################################
def Depth(input, depth=None, sample=None, fulls=None, fulld=None,
dither=None, useZ=None, **kwargs):
# input clip
clip = input
if not isinstance(input, vs.VideoNode):
raise type_error('"input" must be a clip!')
## Default values for kwargs
if 'ampn' not in kwargs:
kwargs['ampn'] = None
if 'ampo' not in kwargs:
kwargs['ampo'] = None
# Get properties of input clip
sFormat = input.format
sColorFamily = sFormat.color_family
CheckColorFamily(sColorFamily)
sIsYUV = sColorFamily == vs.YUV
sIsGRAY = sColorFamily == vs.GRAY
sbitPS = sFormat.bits_per_sample
sSType = sFormat.sample_type
if fulls is None:
# If not set, assume limited range for YUV and Gray input
fulls = False if sIsYUV or sIsGRAY else True
elif not isinstance(fulls, int):
raise type_error('"fulls" must be a bool!')
# Get properties of output clip
lowDepth = False
if depth is None:
dbitPS = sbitPS
elif not isinstance(depth, int):
raise type_error('"depth" must be an int!')
else:
if depth < 8:
dbitPS = 8
lowDepth = True
else:
dbitPS = depth
if sample is None:
if depth is None:
dSType = sSType
depth = dbitPS
else:
dSType = vs.FLOAT if dbitPS >= 32 else vs.INTEGER
elif not isinstance(sample, int):
raise type_error('"sample" must be an int!')
elif sample != vs.INTEGER and sample != vs.FLOAT:
raise value_error('"sample" must be either 0 (vs.INTEGER) or 1 (vs.FLOAT)!')
else:
dSType = sample
if depth is None and sSType != vs.FLOAT and sample == vs.FLOAT:
dbitPS = 32
elif depth is None and sSType != vs.INTEGER and sample == vs.INTEGER:
dbitPS = 16
if dSType == vs.INTEGER and (dbitPS < 1 or dbitPS > 16):
raise value_error(f'{dbitPS}-bit integer output is not supported!')
if dSType == vs.FLOAT and (dbitPS != 16 and dbitPS != 32):
raise value_error(f'{dbitPS}-bit float output is not supported!')
if fulld is None:
fulld = fulls
elif not isinstance(fulld, int):
raise type_error('"fulld" must be a bool!')
# Low-depth support
if lowDepth:
if dither == "none" or dither == 1:
clip = _quantization_conversion(clip, sbitPS, depth, vs.INTEGER, fulls, fulld, False, False, 8, 0)
clip = _quantization_conversion(clip, depth, 8, vs.INTEGER, fulld, fulld, False, False, 8, 0)
return clip
else:
full = fulld
clip = _quantization_conversion(clip, sbitPS, depth, vs.INTEGER, fulls, full, False, False, 16, 1)
sSType = vs.INTEGER
sbitPS = 16
fulls = False
fulld = False
# Whether to use zDepth or fmtc.bitdepth for conversion
# When 11,13~15 bit integer or 16 bit float is involved, force using zDepth
if useZ is None:
useZ = False
elif not isinstance(useZ, int):
raise type_error('"useZ" must be a bool!')
if sSType == vs.INTEGER and (sbitPS == 13 or sbitPS == 15):
useZ = True
if dSType == vs.INTEGER and (dbitPS == 11 or 13 <= dbitPS <= 15):
useZ = True
if (sSType == vs.FLOAT and sbitPS < 32) or (dSType == vs.FLOAT and dbitPS < 32):
useZ = True
# Dithering type
if kwargs['ampn'] is not None and not isinstance(kwargs['ampn'], (int, float)):
raise type_error('"ampn" must be an int or a float!')
if dither is None:
if dbitPS == 32 or (dbitPS >= sbitPS and fulld == fulls and fulld == False):
dither = "none" if useZ else 1
else:
dither = "error_diffusion" if useZ else 3
elif not isinstance(dither, (int, str)):
raise type_error('"dither" must be an int or a str!')
else:
if isinstance(dither, str):
dither = dither.lower()
if dither != "none" and dither != "ordered" and dither != "random" and dither != "error_diffusion":
raise value_error('Unsupported "dither" specified!')
else:
if dither < 0 or dither > 9:
raise value_error('Unsupported "dither" specified!')
if useZ and isinstance(dither, int):
if dither == 0:
dither = "ordered"
elif dither == 1 or dither == 2:
if kwargs['ampn'] is not None and kwargs['ampn'] > 0:
dither = "random"
else:
dither = "none"
else:
dither = "error_diffusion"
elif not useZ and isinstance(dither, str):
if dither == "none":
dither = 1
elif dither == "ordered":
dither = 0
elif dither == "random":
if kwargs['ampn'] is None:
dither = 1
kwargs['ampn'] = 1
elif kwargs['ampn'] > 0:
dither = 1
else:
dither = 3
else:
dither = 3
if not useZ:
if kwargs['ampo'] is None:
kwargs['ampo'] = 1.5 if dither == 0 else 1
elif not isinstance(kwargs['ampo'], (int, float)):
raise type_error('"ampo" must be an int or a float!')
# Skip processing if not needed
if dSType == sSType and dbitPS == sbitPS and (sSType == vs.FLOAT or fulld == fulls) and not lowDepth:
return clip
# Apply conversion
if useZ:
clip = zDepth(clip, sample=dSType, depth=dbitPS, range=fulld, range_in=fulls, dither_type=dither)
else:
clip = core.fmtc.bitdepth(clip, bits=dbitPS, flt=dSType, fulls=fulls, fulld=fulld, dmode=dither, **kwargs)
clip = SetColorSpace(clip, ColorRange=0 if fulld else 1)
# Low-depth support
if lowDepth:
clip = _quantization_conversion(clip, depth, 8, vs.INTEGER, full, full, False, False, 8, 0)
# Output
return clip
################################################################################################################################
################################################################################################################################
## Main function: ToRGB()
################################################################################################################################
## A wrapper of fmtconv to convert any color space to full range RGB.
## Thus, if input is limited range RGB, it will be converted to full range.
## If matrix is 10, "2020cl" or "bt2020c", the output is linear RGB.
## Only constant format is supported, frame properties of the input clip is mostly ignored.
## Note that you may get faster speed with core.resize, or not (for now, dither_type='error_diffusion' is slow).
## It's recommended to use Preview() for previewing now.
################################################################################################################################
## Basic parameters
## input {clip}: clip to be converted
## can be of YUV/RGB/Gray color family, can be of 8-16 bit integer or 16/32 bit float
## matrix {int|str}: color matrix of input clip, only makes sense for YUV input
## decides the conversion coefficients from YUV to RGB
## check GetMatrix() for available values
## default: None, guessed according to the color family and size of input clip
## depth {int}: output bit depth, can be 1-16 bit integer or 16/32 bit float
## note that 1-7 bit content is still stored as 8 bit integer format
## default is the same as that of the input clip
## sample {int}: output sample type, can be 0 (vs.INTEGER) or 1 (vs.FLOAT)
## default is the same as that of the input clip
## full {bool}: define if input clip is of full range
## default: guessed according to the color family of input clip and "matrix"
################################################################################################################################
## Parameters of resampling
## kernel, taps, a1, a2, cplace:
## used for chroma re-sampling, same as those in fmtc.resample
## default: kernel="bicubic", a1=0, a2=0.5, also known as "Catmull-Rom".
################################################################################################################################
## Parameters of depth conversion
## dither, useZ, ampo, ampn, dyn, staticnoise, cpuopt, patsize, tpdfo, tpdfn, corplane:
## same as those in Depth()
## *NOTE* no positional arguments, only keyword arguments are accepted
################################################################################################################################
def ToRGB(input, matrix=None, depth=None, sample=None, full=None,
kernel=None, taps=None, a1=None, a2=None, cplace=None, **kwargs):
# input clip
clip = input
if not isinstance(input, vs.VideoNode):
raise type_error('"input" must be a clip!')
# Get string format parameter "matrix"
matrix = GetMatrix(input, matrix, True)
# Get properties of input clip
sFormat = input.format
sColorFamily = sFormat.color_family
CheckColorFamily(sColorFamily)
sIsRGB = sColorFamily == vs.RGB
sIsYUV = sColorFamily == vs.YUV
sIsGRAY = sColorFamily == vs.GRAY
sbitPS = sFormat.bits_per_sample
sSType = sFormat.sample_type
sHSubS = 1 << sFormat.subsampling_w
sVSubS = 1 << sFormat.subsampling_h
if full is None:
# If not set, assume limited range for YUV and Gray input
# Assume full range for YCgCo and OPP input
if (sIsGRAY or sIsYUV) and (matrix == "RGB" or matrix == "YCgCo" or matrix == "OPP"):
fulls = True
else:
fulls = False if sIsYUV or sIsGRAY else True
elif not isinstance(full, int):
raise type_error('"full" must be a bool!')
else:
fulls = full
# Get properties of output clip
if depth is None:
dbitPS = sbitPS
elif not isinstance(depth, int):
raise type_error('"depth" must be an int!')
else:
dbitPS = depth
if sample is None:
if depth is None:
dSType = sSType
else:
dSType = vs.FLOAT if dbitPS >= 32 else vs.INTEGER
elif not isinstance(sample, int):
raise type_error('"sample" must be an int!')
elif sample != vs.INTEGER and sample != vs.FLOAT:
raise value_error('"sample" must be either 0 (vs.INTEGER) or 1 (vs.FLOAT)!')
else:
dSType = sample
if depth is None and sSType != vs.FLOAT and sample == vs.FLOAT:
dbitPS = 32
elif depth is None and sSType != vs.INTEGER and sample == vs.INTEGER:
dbitPS = 16
if dSType == vs.INTEGER and (dbitPS < 1 or dbitPS > 16):
raise value_error(f'{dbitPS}-bit integer output is not supported!')
if dSType == vs.FLOAT and (dbitPS != 16 and dbitPS != 32):
raise value_error(f'{dbitPS}-bit float output is not supported!')
fulld = True
# Get properties of internal processed clip
pSType = max(sSType, dSType) # If float sample type is involved, then use float for conversion
if pSType == vs.FLOAT:
# For float sample type, only 32-bit is supported by fmtconv
pbitPS = 32
else:
# Apply conversion in the higher one of input and output bit depth
pbitPS = max(sbitPS, dbitPS)
# For integer sample type, only 8-, 9-, 10-, 12-, 16-bit is supported by fmtc.matrix
if sHSubS != 1 or sVSubS != 1:
# When chroma re-sampling is needed, always process in 16-bit for integer sample type
pbitPS = 16
elif pbitPS == 11:
pbitPS = 12
elif pbitPS > 12 and pbitPS < 16:
pbitPS = 16
# fmtc.resample parameters
if kernel is None:
kernel = "bicubic"
if a1 is None and a2 is None:
a1 = 0
a2 = 0.5
elif not isinstance(kernel, str):
raise type_error('"kernel" must be a str!')
# Conversion
if sIsRGB:
# Skip matrix conversion for RGB input
# Apply depth conversion for output clip
clip = Depth(clip, dbitPS, dSType, fulls, fulld, **kwargs)
elif sIsGRAY:
# Apply depth conversion for output clip
clip = Depth(clip, dbitPS, dSType, fulls, fulld, **kwargs)
# Shuffle planes for Gray input
clip = core.std.ShufflePlanes([clip,clip,clip], [0,0,0], vs.RGB)
# Set output frame properties
clip = SetColorSpace(clip, Matrix=0)
else:
# Apply chroma up-sampling if needed
if sHSubS != 1 or sVSubS != 1:
clip = core.fmtc.resample(clip, kernel=kernel, taps=taps, a1=a1, a2=a2, css="444", planes=[2,3,3], fulls=fulls, fulld=fulls, cplace=cplace, flt=pSType==vs.FLOAT)
# Apply depth conversion for processed clip
else:
clip = Depth(clip, pbitPS, pSType, fulls, fulls, **kwargs)
# Apply matrix conversion for YUV input
if matrix == "OPP":
clip = core.fmtc.matrix(clip, fulls=fulls, fulld=fulld, coef=[1,1,2/3,0, 1,0,-4/3,0, 1,-1,2/3,0], col_fam=vs.RGB)
clip = SetColorSpace(clip, Matrix=0)
elif matrix == "2020cl":
clip = core.fmtc.matrix2020cl(clip, full=fulls)
else:
clip = core.fmtc.matrix(clip, mat=matrix, fulls=fulls, fulld=fulld, col_fam=vs.RGB)
# Apply depth conversion for output clip
clip = Depth(clip, dbitPS, dSType, fulld, fulld, **kwargs)
# Output
return clip
################################################################################################################################
################################################################################################################################
## Main function: ToYUV()
################################################################################################################################
## A wrapper of fmtconv to convert any color space to YUV with/without sub-sampling.
## If input is RGB, it's assumed to be of full range.
## Thus, limited range RGB clip should first be manually converted to full range before calling this function.
## If matrix is 10, "2020cl" or "bt2020c", the input should be linear RGB.
## Only constant format is supported, frame properties of the input clip is mostly ignored.
## Note that you may get faster speed with core.resize, or not (for now, dither_type='error_diffusion' is slow).
################################################################################################################################
## Basic parameters
## input {clip}: clip to be converted
## can be of YUV/RGB/Gray color family, can be of 8-16 bit integer or 16/32 bit float
## matrix {int|str}: color matrix of output clip
## decides the conversion coefficients from RGB to YUV
## check GetMatrix() for available values
## default: None, guessed according to the color family and size of input clip
## css {str}: chroma sub-sampling of output clip, similar to the one in fmtc.resample
## If two number is defined, then the first is horizontal sub-sampling and the second is vertical sub-sampling.
## For example, "11" is 4:4:4, "21" is 4:2:2, "22" is 4:2:0.
## preset values:
## - "444" | "4:4:4" | "11"
## - "440" | "4:4:0" | "12"
## - "422" | "4:2:2" | "21"
## - "420" | "4:2:0" | "22"
## - "411" | "4:1:1" | "41"
## - "410" | "4:1:0" | "42"
## default: 4:4:4 for RGB/Gray input, same as input is for YUV input
## depth {int}: output bit depth, can be 1-16 bit integer or 16/32 bit float
## note that 1-7 bit content is still stored as 8 bit integer format
## default is the same as that of the input clip
## sample {int}: output sample type, can be 0 (vs.INTEGER) or 1 (vs.FLOAT)
## default is the same as that of the input clip
## full {bool}: define if input/output Gray/YUV clip is of full range
## default: guessed according to the color family of input clip and "matrix"
################################################################################################################################
## Parameters of resampling
## kernel, taps, a1, a2, cplace:
## used for chroma re-sampling, same as those in fmtc.resample
## default: kernel="bicubic", a1=0, a2=0.5, also known as "Catmull-Rom"
################################################################################################################################
## Parameters of depth conversion
## dither, useZ, ampo, ampn, dyn, staticnoise, cpuopt, patsize, tpdfo, tpdfn, corplane:
## same as those in Depth()
## *NOTE* no positional arguments, only keyword arguments are accepted
################################################################################################################################
def ToYUV(input, matrix=None, css=None, depth=None, sample=None, full=None,
kernel=None, taps=None, a1=None, a2=None, cplace=None, **kwargs):
# input clip
clip = input
if not isinstance(input, vs.VideoNode):
raise type_error('"input" must be a clip!')
# Get string format parameter "matrix"
matrix = GetMatrix(input, matrix, False)
# Get properties of input clip
sFormat = input.format
sColorFamily = sFormat.color_family
CheckColorFamily(sColorFamily)
sIsRGB = sColorFamily == vs.RGB
sIsYUV = sColorFamily == vs.YUV
sIsGRAY = sColorFamily == vs.GRAY
sbitPS = sFormat.bits_per_sample
sSType = sFormat.sample_type
sHSubS = 1 << sFormat.subsampling_w
sVSubS = 1 << sFormat.subsampling_h
if sIsRGB:
# Always assume full range for RGB input
fulls = True
elif full is None:
# If not set, assume limited range for YUV and Gray input
# Assume full range for YCgCo and OPP input
if (sIsGRAY or sIsYUV) and (matrix == "RGB" or matrix == "YCgCo" or matrix == "OPP"):
fulls = True
else:
fulls = False if sIsYUV or sIsGRAY else True
elif not isinstance(full, int):
raise type_error('"full" must be a bool!')
else:
fulls = full
# Get properties of output clip
if depth is None:
dbitPS = sbitPS
elif not isinstance(depth, int):
raise type_error('"depth" must be an int!')
else:
dbitPS = depth
if sample is None:
if depth is None:
dSType = sSType
else:
dSType = vs.FLOAT if dbitPS >= 32 else vs.INTEGER
elif not isinstance(sample, int):
raise type_error('"sample" must be an int!')
elif sample != vs.INTEGER and sample != vs.FLOAT:
raise value_error('"sample" must be either 0 (vs.INTEGER) or 1 (vs.FLOAT)!')
else:
dSType = sample
if depth is None and sSType != vs.FLOAT and sample == vs.FLOAT:
dbitPS = 32
elif depth is None and sSType != vs.INTEGER and sample == vs.INTEGER:
dbitPS = 16
if dSType == vs.INTEGER and (dbitPS < 1 or dbitPS > 16):
raise value_error(f'{dbitPS}-bit integer output is not supported!')
if dSType == vs.FLOAT and (dbitPS != 16 and dbitPS != 32):
raise value_error(f'{dbitPS}-bit float output is not supported!')
if full is None:
# If not set, assume limited range for YUV and Gray output
# Assume full range for YCgCo and OPP output
if matrix == "RGB" or matrix == "YCgCo" or matrix == "OPP":
fulld = True
else:
fulld = False
elif not isinstance(full, int):
raise type_error('"full" must be a bool!')
else:
fulld = full
# Chroma sub-sampling parameters
if css is None:
dHSubS = sHSubS
dVSubS = sVSubS
css = f'{dHSubS}{dVSubS}'
elif not isinstance(css, str):
raise type_error('"css" must be a str!')
else:
if css == "444" or css == "4:4:4":
css = "11"
elif css == "440" or css == "4:4:0":
css = "12"
elif css == "422" or css == "4:2:2":
css = "21"
elif css == "420" or css == "4:2:0":
css = "22"
elif css == "411" or css == "4:1:1":
css = "41"
elif css == "410" or css == "4:1:0":
css = "42"
dHSubS = int(css[0])
dVSubS = int(css[1])
# Get properties of internal processed clip
pSType = max(sSType, dSType) # If float sample type is involved, then use float for conversion
if pSType == vs.FLOAT:
# For float sample type, only 32-bit is supported by fmtconv
pbitPS = 32
else:
# Apply conversion in the higher one of input and output bit depth
pbitPS = max(sbitPS, dbitPS)
# For integer sample type, only 8-, 9-, 10-, 12-, 16-bit is supported by fmtc.matrix
if pbitPS == 11:
pbitPS = 12
elif pbitPS > 12 and pbitPS < 16:
pbitPS = 16
if dHSubS != sHSubS or dVSubS != sVSubS:
# When chroma re-sampling is needed, always process in 16-bit for integer sample type
pbitPS = 16
# fmtc.resample parameters
if kernel is None:
kernel = "bicubic"
if a1 is None and a2 is None:
a1 = 0
a2 = 0.5
elif not isinstance(kernel, str):
raise type_error('"kernel" must be a str!')
# Conversion
if sIsYUV:
# Skip matrix conversion for YUV input
# Change chroma sub-sampling if needed
if dHSubS != sHSubS or dVSubS != sVSubS:
# Apply depth conversion for processed clip
clip = Depth(clip, pbitPS, pSType, fulls, fulls, **kwargs)
clip = core.fmtc.resample(clip, kernel=kernel, taps=taps, a1=a1, a2=a2, css=css, planes=[2,3,3], fulls=fulls, fulld=fulls, cplace=cplace)
# Apply depth conversion for output clip
clip = Depth(clip, dbitPS, dSType, fulls, fulld, **kwargs)
elif sIsGRAY:
# Apply depth conversion for output clip
clip = Depth(clip, dbitPS, dSType, fulls, fulld, **kwargs)
# Shuffle planes for Gray input
widthc = input.width // dHSubS
heightc = input.height // dVSubS
UV = core.std.BlankClip(clip, width=widthc, height=heightc,
color=1 << (dbitPS - 1) if dSType == vs.INTEGER else 0)
clip = core.std.ShufflePlanes([clip,UV,UV], [0,0,0], vs.YUV)
else:
# Apply depth conversion for processed clip
clip = Depth(clip, pbitPS, pSType, fulls, fulls, **kwargs)
# Apply matrix conversion for RGB input
if matrix == "OPP":
clip = core.fmtc.matrix(clip, fulls=fulls, fulld=fulld, coef=[1/3,1/3,1/3,0, 1/2,0,-1/2,0, 1/4,-1/2,1/4,0], col_fam=vs.YUV)
clip = SetColorSpace(clip, Matrix=2)
elif matrix == "2020cl":
clip = core.fmtc.matrix2020cl(clip, full=fulld)
else:
clip = core.fmtc.matrix(clip, mat=matrix, fulls=fulls, fulld=fulld, col_fam=vs.YUV)
# Change chroma sub-sampling if needed
if dHSubS != sHSubS or dVSubS != sVSubS:
clip = core.fmtc.resample(clip, kernel=kernel, taps=taps, a1=a1, a2=a2, css=css, planes=[2,3,3], fulls=fulld, fulld=fulld, cplace=cplace)
# Apply depth conversion for output clip
clip = Depth(clip, dbitPS, dSType, fulld, fulld, **kwargs)
# Output
return clip
################################################################################################################################
################################################################################################################################
## Main function: BM3D()
################################################################################################################################
## A wrap function for easy using of BM3D/V-BM3D denoising filter.
## The BM3D filtering is always done in 16-bit int or 32-bit float opponent (OPP) color space internally.
## It can automatically convert any input color space to OPP and convert it back after filtering.
## Alternatively, you can specify "output" to force outputting RGB or OPP, and "css" to change chroma subsampling.
## For Gray input, no color space conversion is involved, thus "output" and "css" won't take effect.
## You can specify "refine" for any number of final estimate refinements.
################################################################################################################################
## Basic parameters
## input {clip}: clip to be filtered
## can be of YUV/RGB/Gray color family, can be of 8-16 bit integer or 16/32 bit float
## sigma {float[]}: same as "sigma" in BM3D, used for both basic estimate and final estimate
## the strength of filtering, should be carefully adjusted according to the noise
## set 0 to disable the filtering of corresponding plane
## default: [5.0,5.0,5.0]
## radius1 {int}: temporal radius of basic estimate
## - 0: BM3D (spatial denoising)
## - 1~16: temporal radius of V-BM3D (spatial-temporal denoising)
## default: 0
## radius2 {int}: temporal radius of final estimate
## default is the same as "radius1"
## profile1 {str}: same as "profile" in BM3D basic estimate
## default: "fast"
## profile2 {str}: same as "profile" in BM3D final estimate
## default is the same as "profile1"
################################################################################################################################
## Advanced parameters
## refine {int}: refinement times
## - 0: basic estimate only
## - 1: basic estimate + refined with final estimate, the original behavior of BM3D
## - n: basic estimate + refined with final estimate for n times
## each final estimate takes the filtered clip in previous estimate as reference clip to filter the input clip
## default: 1
## pre {clip} (optional): pre-filtered clip for basic estimate
## must be of the same format and dimension as the input clip
## should be a clip better suited for block-matching than the input clip
## ref {clip} (optional): basic estimate clip
## must be of the same format and dimension as the input clip
## replace the basic estimate of BM3D and serve as the reference clip for final estimate
## psample {int}: internal processed precision
## - 0: 16-bit integer, less accuracy, less memory consumption
## - 1: 32-bit float, more accuracy, more memory consumption
## default: 1
################################################################################################################################
## Parameters of input properties
## matrix {int|str}: color matrix of input clip, only makes sense for YUV input
## check GetMatrix() for available values
## default: guessed according to the color family and size of input clip
## full {bool}: define if input clip is of full range
## default: guessed according to the color family of input clip and "matrix"
################################################################################################################################
## Parameters of output properties
## output {int}: type of output clip, doesn't make sense for Gray input
## - 0: same format as input clip
## - 1: full range RGB (converted from input clip)
## - 2: full range OPP (converted from full range RGB, the color space where the filtering takes place)
## default: 0
## css {str}: chroma subsampling of output clip, only valid when output=0 and input clip is YUV
## check ToYUV() for available values
## default is the same as that of the input clip
## depth {int}: bit depth of output clip, can be 1-16 for integer or 16/32 for float
## note that 1-7 bit content is still stored as 8 bit integer format
## default is the same as that of the input clip
## sample {int}: sample type of output clip, can be 0 (vs.INTEGER) or 1 (vs.FLOAT)
## default is the same as that of the input clip
################################################################################################################################
## Parameters of resampling
## cu_kernel, cu_taps, cu_a1, cu_a2, cu_cplace:
## used for chroma up-sampling, same as those in fmtc.resample
## default: kernel="bicubic", a1=0, a2=0.5, also known as "Catmull-Rom"
## cd_kernel, cd_taps, cd_a1, cd_a2, cd_cplace:
## used for chroma down-sampling, same as those in fmtc.resample
## default: kernel="bicubic", a1=0, a2=0.5, also known as "Catmull-Rom"
################################################################################################################################
## Parameters of BM3D basic estimate
## block_size1, block_step1, group_size1, bm_range1, bm_step1, ps_num1, ps_range1, ps_step1, th_mse1, hard_thr:
## same as those in bm3d.Basic/bm3d.VBasic
################################################################################################################################
## Parameters of BM3D final estimate
## block_size2, block_step2, group_size2, bm_range2, bm_step2, ps_num2, ps_range2, ps_step2, th_mse2:
## same as those in bm3d.Final/bm3d.VFinal
################################################################################################################################
## Parameters of depth conversion
## dither, useZ, ampo, ampn, dyn, staticnoise, cpuopt, patsize, tpdfo, tpdfn, corplane:
## same as those in Depth()
## *NOTE* no positional arguments, only keyword arguments are accepted
################################################################################################################################
def BM3D(input, sigma=None, radius1=None, radius2=None, profile1=None, profile2=None,
refine=None, pre=None, ref=None, psample=None,
matrix=None, full=None,
output=None, css=None, depth=None, sample=None,
cu_kernel=None, cu_taps=None, cu_a1=None, cu_a2=None, cu_cplace=None,
cd_kernel=None, cd_taps=None, cd_a1=None, cd_a2=None, cd_cplace=None,
block_size1=None, block_step1=None, group_size1=None, bm_range1=None, bm_step1=None, ps_num1=None, ps_range1=None, ps_step1=None, th_mse1=None, hard_thr=None,
block_size2=None, block_step2=None, group_size2=None, bm_range2=None, bm_step2=None, ps_num2=None, ps_range2=None, ps_step2=None, th_mse2=None,
**kwargs):
# input clip
clip = input
if not isinstance(input, vs.VideoNode):
raise type_error('"input" must be a clip!')
# Get string format parameter "matrix"
matrix = GetMatrix(input, matrix, True)
# Get properties of input clip
sFormat = input.format
sColorFamily = sFormat.color_family
CheckColorFamily(sColorFamily)
sIsRGB = sColorFamily == vs.RGB
sIsYUV = sColorFamily == vs.YUV
sIsGRAY = sColorFamily == vs.GRAY
sbitPS = sFormat.bits_per_sample
sSType = sFormat.sample_type
sHSubS = 1 << sFormat.subsampling_w
sVSubS = 1 << sFormat.subsampling_h
if full is None:
# If not set, assume limited range for YUV and Gray input
# Assume full range for YCgCo and OPP input
if (sIsGRAY or sIsYUV) and (matrix == "RGB" or matrix == "YCgCo" or matrix == "OPP"):
fulls = True
else:
fulls = False if sIsYUV or sIsGRAY else True
elif not isinstance(full, int):
raise type_error('"full" must be a bool!')
else:
fulls = full
# Get properties of internal processed clip
if psample is None:
psample = vs.FLOAT
elif not isinstance(psample, int):
raise type_error('"psample" must be an int!')
elif psample != vs.INTEGER and psample != vs.FLOAT:
raise value_error('"psample" must be either 0 (vs.INTEGER) or 1 (vs.FLOAT)!')
pbitPS = 16 if psample == vs.INTEGER else 32
pSType = psample
# Chroma sub-sampling parameters
if css is None:
dHSubS = sHSubS
dVSubS = sVSubS
css = f'{dHSubS}{dVSubS}'
elif not isinstance(css, str):
raise type_error('"css" must be a str!')
else:
if css == "444" or css == "4:4:4":
css = "11"
elif css == "440" or css == "4:4:0":
css = "12"
elif css == "422" or css == "4:2:2":
css = "21"
elif css == "420" or css == "4:2:0":
css = "22"
elif css == "411" or css == "4:1:1":
css = "41"
elif css == "410" or css == "4:1:0":
css = "42"
dHSubS = int(css[0])
dVSubS = int(css[1])
if cu_cplace is not None and cd_cplace is None:
cd_cplace = cu_cplace
# Parameters processing
if sigma is None:
sigma = [5.0,5.0,5.0]
else:
if isinstance(sigma, int):
sigma = float(sigma)
sigma = [sigma,sigma,sigma]
elif isinstance(sigma, float):
sigma = [sigma,sigma,sigma]
elif isinstance(sigma, list):
while len(sigma) < 3:
sigma.append(sigma[len(sigma) - 1])
else:
raise type_error('sigma must be a float[] or an int[]!')
if sIsGRAY:
sigma = [sigma[0],0,0]
skip = sigma[0] <= 0 and sigma[1] <= 0 and sigma[2] <= 0
if radius1 is None:
radius1 = 0
elif not isinstance(radius1, int):
raise type_error('"radius1" must be an int!')
elif radius1 < 0:
raise value_error('valid range of "radius1" is [0, +inf)!')
if radius2 is None:
radius2 = radius1
elif not isinstance(radius2, int):
raise type_error('"radius2" must be an int!')
elif radius2 < 0:
raise value_error('valid range of "radius2" is [0, +inf)!')
if profile1 is None:
profile1 = "fast"
elif not isinstance(profile1, str):
raise type_error('"profile1" must be a str!')
if profile2 is None:
profile2 = profile1
elif not isinstance(profile2, str):
raise type_error('"profile2" must be a str!')
if refine is None:
refine = 1
elif not isinstance(refine, int):
raise type_error('"refine" must be an int!')
elif refine < 0:
raise value_error('valid range of "refine" is [0, +inf)!')
if output is None:
output = 0
elif not isinstance(output, int):
raise type_error('"output" must be an int!')
elif output < 0 or output > 2:
raise value_error('valid values of "output" are 0, 1 and 2!')
if pre is not None:
if not isinstance(pre, vs.VideoNode):
raise type_error('"pre" must be a clip!')
if pre.format.id != sFormat.id:
raise value_error('clip "pre" must be of the same format as the input clip!')
if pre.width != input.width or pre.height != input.height:
raise value_error('clip "pre" must be of the same size as the input clip!')
if ref is not None:
if not isinstance(ref, vs.VideoNode):
raise type_error('"ref" must be a clip!')
if ref.format.id != sFormat.id:
raise value_error('clip "ref" must be of the same format as the input clip!')
if ref.width != input.width or ref.height != input.height:
raise value_error('clip "ref" must be of the same size as the input clip!')
# Get properties of output clip
if depth is None:
if output == 0:
dbitPS = sbitPS
else:
dbitPS = pbitPS
elif not isinstance(depth, int):
raise type_error('"depth" must be an int!')
else:
dbitPS = depth
if sample is None:
if depth is None:
if output == 0:
dSType = sSType
else:
dSType = pSType
else:
dSType = vs.FLOAT if dbitPS >= 32 else vs.INTEGER
elif not isinstance(sample, int):
raise type_error('"sample" must be an int!')
elif sample != vs.INTEGER and sample != vs.FLOAT:
raise value_error('"sample" must be either 0 (vs.INTEGER) or 1 (vs.FLOAT)!')
else:
dSType = sample
if depth is None and sSType != vs.FLOAT and sample == vs.FLOAT:
dbitPS = 32
elif depth is None and sSType != vs.INTEGER and sample == vs.INTEGER:
dbitPS = 16
if dSType == vs.INTEGER and (dbitPS < 1 or dbitPS > 16):
raise value_error(f'{dbitPS}-bit integer output is not supported!')
if dSType == vs.FLOAT and (dbitPS != 16 and dbitPS != 32):
raise value_error(f'{dbitPS}-bit float output is not supported!')
if output == 0:
fulld = fulls
else:
# Always full range output when output=1|output=2 (full range RGB or full range OPP)
fulld = True
# Convert to processed format
# YUV/RGB input is converted to opponent color space as full range YUV
# Gray input is converted to full range Gray
onlyY = False
if sIsGRAY:
onlyY = True
# Convert Gray input to full range Gray in processed format
clip = Depth(clip, pbitPS, pSType, fulls, True, **kwargs)
if pre is not None:
pre = Depth(pre, pbitPS, pSType, fulls, True, **kwargs)
if ref is not None:
ref = Depth(ref, pbitPS, pSType, fulls, True, **kwargs)
else:
# Convert input to full range RGB
clip = ToRGB(clip, matrix, pbitPS, pSType, fulls,
cu_kernel, cu_taps, cu_a1, cu_a2, cu_cplace, **kwargs)
if pre is not None:
pre = ToRGB(pre, matrix, pbitPS, pSType, fulls,
cu_kernel, cu_taps, cu_a1, cu_a2, cu_cplace, **kwargs)
if ref is not None:
ref = ToRGB(ref, matrix, pbitPS, pSType, fulls,
cu_kernel, cu_taps, cu_a1, cu_a2, cu_cplace, **kwargs)
# Convert full range RGB to full range OPP
clip = ToYUV(clip, "OPP", "444", pbitPS, pSType, True,
cu_kernel, cu_taps, cu_a1, cu_a2, cu_cplace, **kwargs)
if pre is not None:
pre = ToYUV(pre, "OPP", "444", pbitPS, pSType, True,
cu_kernel, cu_taps, cu_a1, cu_a2, cu_cplace, **kwargs)
if ref is not None:
ref = ToYUV(ref, "OPP", "444", pbitPS, pSType, True,
cu_kernel, cu_taps, cu_a1, cu_a2, cu_cplace, **kwargs)
# Convert OPP to Gray if only Y is processed
srcOPP = clip
if sigma[1] <= 0 and sigma[2] <= 0:
onlyY = True
clip = core.std.ShufflePlanes([clip], [0], vs.GRAY)
if pre is not None:
pre = core.std.ShufflePlanes([pre], [0], vs.GRAY)
if ref is not None:
ref = core.std.ShufflePlanes([ref], [0], vs.GRAY)
# Basic estimate
if ref is not None:
# Use custom basic estimate specified by clip "ref"
flt = ref
elif skip:
flt = clip
elif radius1 < 1:
# Apply BM3D basic estimate
# Optional pre-filtered clip for block-matching can be specified by "pre"