-
Notifications
You must be signed in to change notification settings - Fork 2
/
G41Fun.py
3851 lines (3255 loc) · 197 KB
/
G41Fun.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
from vapoursynth import core
from functools import partial
import vapoursynth as vs
import havsfunc as haf
import mvsfunc as mvf
import muvsfunc as muf
import nnedi3_resample as nnrs
import math, mvmulti
"""
Copyright 2019 Pao-Ming Lin
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
"""
Main functions:
FineSharp
psharpen
MCDegrainSharp
LSFmod
SeeSaw
QTGMC
SMDegrain
TemporalDegrain2
mClean
STPressoHD
MLDegrain
NonlinUSM
DetailSharpen
Hysteria
SuperToon
EdgeDetect
JohnFPS
SpotLess
HQDeringmod
MaskedDHA
daamod
LUSM
"""
def FineSharp(clip, mode=1, sstr=2.5, cstr=None, xstr=0, lstr=1.5, pstr=1.28, ldmp=None, hdmp=0.01, rep=12):
"""
Original author: Didée (https://forum.doom9.org/showthread.php?t=166082)
Small and relatively fast realtime-sharpening function, for 1080p,
or after scaling 720p → 1080p during playback.
(to make 720p look more like being 1080p)
It's a generic sharpener. Only for good quality sources!
(If the source is crap, FineSharp will happily sharpen the crap) :)
Noise/grain will be enhanced, too. The method is GENERIC.
Modus operandi: A basic nonlinear sharpening method is performed,
then the *blurred* sharp-difference gets subtracted again.
Args:
mode (int) - 1 to 3, weakest to strongest. When negative -1 to -3,
a broader kernel for equalisation is used.
sstr (float) - strength of sharpening.
cstr (float) - strength of equalisation (recommended 0.5 to 1.25)
xstr (float) - strength of XSharpen-style final sharpening, 0.0 to 1.0.
(but, better don't go beyond 0.25...)
lstr (float) - modifier for non-linear sharpening.
pstr (float) - exponent for non-linear sharpening.
ldmp (float) - "low damp", to not over-enhance very small differences.
(noise coming out of flat areas)
hdmp (float) - "high damp", this damping term has a larger effect than ldmp
when the sharp-difference is larger than 1, vice versa.
rep (int) - repair mode used in final sharpening, recommended modes are 1/12/13.
"""
color = clip.format.color_family
bd = clip.format.bits_per_sample
isFLOAT = clip.format.sample_type == vs.FLOAT
mid = 0 if isFLOAT else 1 << (bd - 1)
i = 0.00392 if isFLOAT else 1 << (bd - 8)
xy = 'x y - {} /'.format(i) if bd != 8 else 'x y -'
R = core.rgsf.Repair if isFLOAT else core.rgvs.Repair
mat1 = [1, 2, 1, 2, 4, 2, 1, 2, 1]
mat2 = [1, 1, 1, 1, 1, 1, 1, 1, 1]
if not isinstance(clip, vs.VideoNode):
raise TypeError("FineSharp: This is not a clip!")
if clip.format.color_family == vs.COMPAT:
raise TypeError("FineSharp: COMPAT color family is not supported!")
if cstr is None:
cstr = spline(sstr, {0: 0, 0.5: 0.1, 1: 0.6, 2: 0.9, 2.5: 1, 3: 1.1, 3.5: 1.15, 4: 1.2, 8: 1.25, 255: 1.5})
cstr **= 0.8 if mode > 0 else cstr
if ldmp is None:
ldmp = sstr
sstr = max(sstr, 0)
cstr = max(cstr, 0)
xstr = min(max(xstr, 0), 1)
ldmp = max(ldmp, 0)
hdmp = max(hdmp, 0)
if sstr < 0.01 and cstr < 0.01 and xstr < 0.01:
return clip
tmp = core.std.ShufflePlanes(clip, [0], vs.GRAY) if color in [vs.YUV, vs.YCOCG] else clip
if abs(mode) == 1:
c2 = core.std.Convolution(tmp, matrix=mat1).std.Median()
else:
c2 = core.std.Median(tmp).std.Convolution(matrix=mat1)
if abs(mode) == 3:
c2 = c2.std.Median()
if sstr >= 0.01:
expr = 'x y = x dup {} dup dup dup abs {} / {} pow swap3 abs {} + / swap dup * dup {} + / * * {} * + ?'
shrp = core.std.Expr([tmp, c2], [expr.format(xy, lstr, 1/pstr, hdmp, ldmp, sstr*i)])
if cstr >= 0.01:
diff = core.std.MakeDiff(shrp, tmp)
if cstr != 1:
expr = 'x {} *'.format(cstr) if isFLOAT else 'x {} - {} * {} +'.format(mid, cstr, mid)
diff = core.std.Expr([diff], [expr])
diff = core.std.Convolution(diff, matrix=mat1) if mode > 0 else core.std.Convolution(diff, matrix=mat2)
shrp = core.std.MakeDiff(shrp, diff)
if xstr >= 0.01:
xyshrp = core.std.Expr([shrp, core.std.Convolution(shrp, matrix=mat2)], ['x dup y - 9.69 * +'])
rpshrp = R(xyshrp, shrp, [rep])
shrp = core.std.Merge(shrp, rpshrp, [xstr])
return core.std.ShufflePlanes([shrp, clip], [0, 1, 2], color) if color in [vs.YUV, vs.YCOCG] else shrp
def psharpen(clip, strength=25, threshold=75, ssx=1, ssy=1, dw=None, dh=None):
"""
From https://forum.doom9.org/showthread.php?p=683344 by ilpippo80.
Sharpeing function similar to LimitedSharpenFaster,
performs two-point sharpening to avoid overshoot.
Args:
strength (float) - Strength of the sharpening, 0 to 100.
threshold (float) - Controls "how much" to be sharpened, 0 to 100.
ssx, ssy (float) - Supersampling factor (reduce aliasing on edges).
dw, dh (int) - Output resolution after sharpening.
"""
if not isinstance(clip, vs.VideoNode):
raise TypeError("psharpen: This is not a clip!")
if clip.format.sample_type != vs.INTEGER:
raise TypeError("psharpen: clip must be of integer sample type")
if clip.format.color_family == vs.COMPAT:
raise TypeError("psharpen: COMPAT color family is not supported!")
color = clip.format.color_family
ow = clip.width
oh = clip.height
ssx = max(ssx, 1.0)
ssy = max(ssy, 1.0)
strength = min(max(strength, 0), 100)
threshold = min(max(threshold, 0), 100)
xss = m4(ow * ssx)
yss = m4(oh * ssy)
if dw is None:
dw = ow
if dh is None:
dh = oh
# oversampling
if ssx > 1 or ssy > 1:
clip = core.resize.Spline36(clip, xss, yss)
tmp = core.std.ShufflePlanes(clip, [0], vs.GRAY) if color in [vs.YUV, vs.YCOCG] else clip
# calculating the max and min in every 3*3 square
maxi = core.std.Maximum(tmp)
mini = core.std.Minimum(tmp)
# normalizing max and val to values from 0 to (max-min)
nmax = core.std.Expr([maxi, mini], ['x y -'])
nval = core.std.Expr([tmp, mini], ['x y -'])
# initializing expression used to obtain the output luma value
s = strength / 100
t = threshold / 100
st = 1 - (s / (s + t - s * t))
expr = 'x y / 2 * 1 - abs {} < {} 1 = x y 2 / = 0 y 2 / ? x y / 2 * 1 - abs 1 {} - / ? x y / 2 * 1 - abs 1 {} - * {} + ? x y 2 / > 1 -1 ? * 1 + y * 2 /'
expr = expr.format(st, s, s, t, t)
# calculates the new luma value pushing it towards min or max
nval = core.std.Expr([nval, nmax], [expr])
# normalizing val to values from min to max
tmp = core.std.Expr([nval, mini], ['x y +'])
# resizing the image to the output resolution
# applying the new luma value to clip
if dw != ow or dh != oh:
if color in [vs.YUV, vs.YCOCG]:
tmp = core.std.ShufflePlanes([tmp, clip], [0, 1, 2], color)
return core.resize.Spline36(tmp, dw, dh)
elif ssx > 1 or ssy > 1:
if color in [vs.YUV, vs.YCOCG]:
tmp = core.std.ShufflePlanes([tmp, clip], [0, 1, 2], color)
return core.resize.Spline36(tmp, dw, dh)
elif color in [vs.YUV, vs.YCOCG]:
return core.std.ShufflePlanes([tmp, clip], [0, 1, 2], color)
else:
return tmp
def MCDegrainSharp(clip, tr=3, bblur=.69, csharp=.69, thSAD=400, rec=False, chroma=True, analyse_args=None, recalculate_args=None):
"""
Based on MCDegrain By Didée:
https://forum.doom9.org/showthread.php?t=161594
Also based on Didée observations in this thread:
https://forum.doom9.org/showthread.php?t=161580
Denoise with MDegrainX, do slight sharpening where motionmatch
is good, do slight blurring where motionmatch is bad.
In areas where MAnalyse cannot find good matches,
the Blur() will be dominant.
In areas where good matches are found,
the Sharpen()'ed pixels will overweight the Blur()'ed pixels
when the pixel averaging is performed.
Args:
bblur, csharp (int, float or function) The method to smooth/sharpen the image.
If it's an int or a float, it specifies the amount in Blur() and Sharpen().
If it's a function, it will use the specified function to smooth/sharpen the image.
tr (int) - Strength of the denoising (1-24).
thSAD (int) - Soft threshold of block sum absolute differences.
Low value can result in staggered denoising,
High value can result in ghosting and artifacts.
rec (bool) - Recalculate the motion vectors to obtain more precision.
chroma (bool) - Whether to process chroma.
"""
if not isinstance(clip, vs.VideoNode) or clip.format.color_family not in [vs.GRAY, vs.YUV]:
raise TypeError("MCDegrainSharp: This is not a GRAY or YUV clip!")
isFLOAT = clip.format.sample_type == vs.FLOAT
isGRAY = clip.format.color_family == vs.GRAY
chroma = False if isGRAY else chroma
planes = [0, 1, 2] if chroma else [0]
plane = 4 if chroma else 0
bs = 32 if clip.width > 2400 else 16 if clip.width > 960 else 8
pel = 1 if clip.width > 960 else 2
truemotion = False if clip.width > 960 else True
A = core.mvsf.Analyse if isFLOAT else core.mv.Analyse
S = core.mvsf.Super if isFLOAT else core.mv.Super
R = core.mvsf.Recalculate if isFLOAT else core.mv.Recalculate
D1 = core.mvsf.Degrain1 if isFLOAT else core.mv.Degrain1
D2 = core.mvsf.Degrain2 if isFLOAT else core.mv.Degrain2
D3 = core.mvsf.Degrain3 if isFLOAT else core.mv.Degrain3
if isinstance(bblur, (int, float)):
c2 = muf.Blur(clip, amountH=bblur, planes=planes)
elif callable(bblur):
c2 = bblur(clip)
else:
raise TypeError("MCDegrainSharp: bblur must be an int, a float or a function!")
if isinstance(csharp, (int, float)):
c4 = muf.Sharpen(clip, amountH=csharp, planes=planes)
elif callable(csharp):
c4 = csharp(clip)
else:
raise TypeError("MCDegrainSharp: csharp must be an int, a float or a function!")
if analyse_args is None:
analyse_args = dict(blksize=bs, overlap=bs//2, search=5, chroma=chroma, truemotion=truemotion)
if recalculate_args is None:
recalculate_args = dict(blksize=bs//2, overlap=bs//4, search=5, chroma=chroma, truemotion=truemotion)
if tr > 3 and not isFLOAT:
raise TypeError("MCDegrainSharp: DegrainN is only available in float")
super_b = S(DitherLumaRebuild(c2, 1), hpad=bs, vpad=bs, pel=pel, sharp=1, rfilter=4)
super_rend = S(c4, hpad=bs, vpad=bs, pel=pel, levels=1, rfilter=1)
if tr < 4:
bv1 = A(super_b, isb=True, delta=1, **analyse_args)
fv1 = A(super_b, isb=False, delta=1, **analyse_args)
if tr > 1:
bv2 = A(super_b, isb=True, delta=2, **analyse_args)
fv2 = A(super_b, isb=False, delta=2, **analyse_args)
if tr > 2:
bv3 = A(super_b, isb=True, delta=3, **analyse_args)
fv3 = A(super_b, isb=False, delta=3, **analyse_args)
else:
vec = mvmulti.Analyze(super_b, tr=tr, **analyse_args)
if rec:
if tr < 4:
bv1 = R(super_b, bv1, **recalculate_args)
fv1 = R(super_b, fv1, **recalculate_args)
if tr > 1:
bv2 = R(super_b, bv2, **recalculate_args)
fv2 = R(super_b, fv2, **recalculate_args)
if tr > 2:
bv3 = R(super_b, bv3, **recalculate_args)
fv3 = R(super_b, fv3, **recalculate_args)
else:
vec = mvmulti.Recalculate(super_b, vec, tr=tr, **recalculate_args)
if tr <= 1:
return D1(c2, super_rend, bv1, fv1, thSAD, plane=plane)
elif tr == 2:
return D2(c2, super_rend, bv1, fv1, bv2, fv2, thSAD, plane=plane)
elif tr == 3:
return D3(c2, super_rend, bv1, fv1, bv2, fv2, bv3, fv3, thSAD, plane=plane)
else:
return mvmulti.DegrainN(c2, super_rend, vec, tr=tr, thsad=thSAD, plane=plane)
def LSFmod(clip, strength=100, Smode=None, Smethod=None, kernel=11, preblur=False, secure=None, source=None,
Szrp=16, Spwr=None, SdmpLo=None, SdmpHi=None, Lmode=None, overshoot=None, undershoot=None, overshoot2=None, undershoot2=None,
soft=None, soothe=None, keep=None, edgemode=0, edgemaskHQ=None, ssx=None, ssy=None, dw=None, dh=None, defaults='slow'):
"""
LimitedSharpenFaster Modded Version by LaTo INV.
+--------------+
| DEPENDENCIES |
+--------------+
→ RGVS / RGSF
+---------+
| GENERAL |
+---------+
strength [int]
--------------
Strength of the sharpening
Smode [int]
----------------------
Sharpen mode:
= 1 : Range sharpening
= 2 : Nonlinear sharpening (corrected version)
= 3 : Nonlinear sharpening (original version)
Smethod [int]
--------------------
Sharpen method:
= 1 : 3x3 kernel
= 2 : Min/Max
= 3 : Min/Max + 3x3 kernel
kernel [int]
-------------------------
Kernel used in Smethod=1&3
In strength order: + 19 >> 20 > 11/12 -
Negative: absolute value specifies the MinBlur radius used.
+---------+
| SPECIAL |
+---------+
preblur [bool]
--------------------------------
Mode to avoid noise sharpening & ringing
secure [bool]
-------------
Mode to avoid banding & oil painting (or face wax) effect of sharpening
source [clip]
-------------
If source is defined, LSFmod doesn't sharp more a denoised clip than this source clip
In this mode, you can safely set Lmode = 0 & PP = OFF
+----------------------+
| NONLINEAR SHARPENING |
+----------------------+
Szrp [int]
----------
Zero Point:
- differences below Szrp are amplified (overdrive sharpening)
- differences above Szrp are reduced (reduced sharpening)
Spwr [int]
----------
Power: exponent for sharpener
SdmpLo [int]
------------
Damp Low: reduce sharpening for small changes [0:disable]
SdmpHi [int]
------------
Damp High: reduce sharpening for big changes [0:disable]
+----------+
| LIMITING |
+----------+
Lmode [int]
--------------------------
Limit mode:
< 0 : Limit with Repair (ex: Lmode = -1 → Repair(1), Lmode = -5 → Repair(5)...)
= 0 : No limit
= 1 : Limit to over/undershoot
= 2 : Limit to over/undershoot on edges and no limit on not-edges
= 3 : Limit to zero on edges and to over/undershoot on not-edges
= 4 : Limit to over/undershoot on edges and to over/undershoot2 on not-edges
overshoot [int]
---------------
Limit for pixels that get brighter during sharpening
undershoot [int]
----------------
Limit for pixels that get darker during sharpening
overshoot2 [int]
----------------
Same as overshoot, only for Lmode = 4
undershoot2 [int]
-----------------
Same as undershoot, only for Lmode = 4
+-----------------+
| POST-PROCESSING |
+-----------------+
soft [int]
-------------------------
Soft the sharpening effect (Negative: new autocalculate)
soothe [bool]
-------------
= True : Enable soothe temporal stabilization
= False : Disable soothe temporal stabilization
keep [int]
-------------------
Minimum percent of the original sharpening to keep (only with soothe=True)
+-------+
| EDGES |
+-------+
edgemode [int]
------------------------
=-1 : Show edgemask
= 0 : Sharpening all
= 1 : Sharpening only edges
= 2 : Sharpening only not-edges
edgemaskHQ [bool]
-----------------
= True : Original edgemask
= False : Faster edgemask
+------------+
| UPSAMPLING |
+------------+
ssx ssy [float]
-------------------
Supersampling factor (reduce aliasing on edges)
dw dh [int]
---------------------
Output resolution after sharpening (avoid a resizing step)
+----------+
| SETTINGS |
+----------+
defaults [string]
--------------------------------------------
= "old" : Reset settings to original version (output will be THE SAME AS LSF)
= "slow" : Enable SLOW modded version settings
= "fast" : Enable FAST modded version settings
defaults = "old" : - strength = 100
---------------- - Smode = 1
- Smethod = Smode == 1 ? 2 : 1
- kernel = 11
- preblur = False
- secure = False
- source = undefined
- Szrp = 16
- Spwr = 2
- SdmpLo = strength / 25
- SdmpHi = 0
- Lmode = 1
- overshoot = 1
- undershoot = overshoot
- overshoot2 = overshoot * 2
- undershoot2 = overshoot2
- soft = 0
- soothe = False
- keep = 25
- edgemode = 0
- edgemaskHQ = True
- ssx = Smode == 1 ? 1.50 : 1.25
- ssy = ssx
- dw = ow
- dh = oh
defaults = "slow" : - strength = 100
----------------- - Smode = 2
- Smethod = 3
- kernel = 11
- preblur = False
- secure = True
- source = undefined
- Szrp = 16
- Spwr = 4
- SdmpLo = 4
- SdmpHi = 48
- Lmode = 4
- overshoot = strength / 100
- undershoot = overshoot
- overshoot2 = overshoot * 2
- undershoot2 = overshoot2
- soft = -2
- soothe = True
- keep = 20
- edgemode = 0
- edgemaskHQ = True
- ssx = 1.50
- ssy = ssx
- dw = ow
- dh = oh
defaults = "fast" : - strength = 100
----------------- - Smode = 1
- Smethod = 2
- kernel = 11
- preblur = False
- secure = True
- source = undefined
- Szrp = 16
- Spwr = 4
- SdmpLo = 4
- SdmpHi = 48
- Lmode = 1
- overshoot = strength / 100
- undershoot = overshoot
- overshoot2 = overshoot * 2
- undershoot2 = overshoot2
- soft = 0
- soothe = True
- keep = 20
- edgemode = 0
- edgemaskHQ = False
- ssx = 1.25
- ssy = ssx
- dw = ow
- dh = oh
"""
# Modified from havsfunc: https://github.com/HomeOfVapourSynthEvolution/havsfunc/blob/r31/havsfunc.py#L4492
if not isinstance(clip, vs.VideoNode):
raise TypeError('LSFmod: This is not a clip!')
if source is not None and (not isinstance(source, vs.VideoNode) or source.format.id != clip.format.id):
raise TypeError("LSFmod: source must be the same format as clip")
if source is not None and (source.width != clip.width or source.height != clip.height):
raise TypeError("LSFmod: source must be the same size as clip")
if clip.format.color_family == vs.COMPAT:
raise TypeError("LSFmod: COMPAT color family is not supported!")
color = clip.format.color_family
bd = clip.format.bits_per_sample
isFLOAT = clip.format.sample_type == vs.FLOAT
mid = 0 if isFLOAT else 1 << (bd - 1)
i = 0.00392 if isFLOAT else 1 << (bd - 8)
R = core.rgsf.Repair if isFLOAT else core.rgvs.Repair
ow = clip.width
oh = clip.height
csrc = clip
### DEFAULTS
try:
num = ['old', 'slow', 'fast'].index(defaults.lower())
except:
raise ValueError('LSFmod: Defaults must be "old" or "slow" or "fast"')
if Smode is None:
Smode = [1, 2, 1][num]
if Smethod is None:
Smethod = [2 if Smode == 1 else 1, 3, 2][num]
if secure is None:
secure = [False, True, True][num]
if Spwr is None:
Spwr = [2, 4, 4][num]
if SdmpLo is None:
SdmpLo = [strength/25, 4, 4][num]
if SdmpHi is None:
SdmpHi = [0, 48, 48][num]
if Lmode is None:
Lmode = [1, 4, 1][num]
if overshoot is None:
overshoot = [1, strength/100, strength/100][num]
if undershoot is None:
undershoot = overshoot
if overshoot2 is None:
overshoot2 = overshoot * 2
if undershoot2 is None:
undershoot2 = overshoot2
if soft is None:
soft = [0, -2, 0][num]
if soothe is None:
soothe = [False, True, True][num]
if keep is None:
keep = [25, 20, 20][num]
if edgemaskHQ is None:
edgemaskHQ = [True, True, False][num]
if ssx is None:
ssx = [1.5 if Smode == 1 else 1.25, 1.5, 1.25][num]
if ssy is None:
ssy = ssx
if dw is None:
dw = ow
if dh is None:
dh = oh
if kernel <= 0:
Filter = partial(MinBlur, r=abs(kernel))
elif kernel == 4:
Filter = partial(core.std.Median)
elif kernel in [11, 12]:
Filter = partial(core.std.Convolution, matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1])
elif kernel == 19:
Filter = partial(core.std.Convolution, matrix=[1, 1, 1, 1, 0, 1, 1, 1, 1])
elif kernel == 20:
Filter = partial(core.std.Convolution, matrix=[1, 1, 1, 1, 1, 1, 1, 1, 1])
else:
if isFLOAT:
Filter = partial(core.rgsf.RemoveGrain, mode=[kernel])
else:
Filter = partial(core.rgvs.RemoveGrain, mode=[kernel])
if soft < 0:
soft = (1 + (2 / (ssx + ssy))) * math.sqrt(strength)
Spwr = max(Spwr, 1)
SdmpLo = max(SdmpLo, 0)
SdmpHi = max(SdmpHi, 0)
ssx = max(ssx, 1)
ssy = max(ssy, 1)
soft = max(min(soft/100, 1), 0)
keep = max(min(keep/100, 1), 0)
xss = m4(ow * ssx)
yss = m4(oh * ssy)
strength = max(strength, 0)
Str = strength / 100
### SHARP
if ssx > 1 or ssy > 1:
clip = core.resize.Spline36(clip, xss, yss)
tmp = core.std.ShufflePlanes(clip, [0], vs.GRAY) if color in [vs.YUV, vs.YCOCG] else clip
pre = MinBlur(tmp) if preblur else tmp
darklimit = core.std.Minimum(pre)
brightlimit = core.std.Maximum(pre)
if Smethod <= 1:
method = Filter(pre)
elif Smethod == 2:
method = core.std.Merge(darklimit, brightlimit)
else:
method = Filter(core.std.Merge(darklimit, brightlimit))
if secure:
method = core.std.Expr([method, pre], ['x y < x {} + x y > x {} - x ? ?'.format(i, i)])
if preblur:
method = core.std.Expr([method, tmp, pre], ['x y + z -'])
if Smode <= 1:
normsharp = core.std.Expr([tmp, method], ['x dup y - {} * +'.format(Str)])
elif Smode == 2:
xy = 'x y - abs {} /'.format(i) if bd != 8 else 'x y - abs'
Hi = 1 if SdmpHi == 0 else '1 {} {} / 4 pow + 1 {} {} / 4 pow + /'.format(Szrp, SdmpHi, xy, SdmpHi)
expr1 = 'x y = x dup {} dup {} / {} pow swap dup * dup {} {} + * swap {} + {} * / * {} * {} * x y > 1 -1 ? * + ?'
normsharp = core.std.Expr([tmp, method], [expr1.format(xy, Szrp, 1/Spwr, Szrp**2, SdmpLo, SdmpLo, Szrp**2, Hi, Szrp*Str*i)])
else:
xy = 'x y - abs {} /'.format(i) if bd != 8 else 'x y - abs'
Hi = 1 if SdmpHi == 0 else '1 {} {} / 4 pow +'.format(xy, SdmpHi)
expr1 = 'x y = x dup {} dup {} / {} pow swap dup * dup {} + / * {} / {} * x y > 1 -1 ? * + ?'
normsharp = core.std.Expr([tmp, method], [expr1.format(xy, Szrp, 1/Spwr, SdmpLo, Hi, Szrp*Str*i)])
### LIMIT
normal = haf.Clamp(normsharp, brightlimit, darklimit, max(overshoot, 0)*i, max(undershoot, 0)*i)
if edgemaskHQ:
edge = core.std.Expr([core.std.Sobel(tmp, scale=2)], 'x {} / 0.87 pow {} *'.format(128*i, 255*i))
else:
edge = core.std.Expr([core.std.Maximum(tmp), core.std.Minimum(tmp)], ['x y - {} / 0.87 pow {} *'.format(32*i, 255*i)])
inflate = core.std.Inflate(edge)
if Lmode == 0:
limit1 = normsharp
elif Lmode == 1:
limit1 = normal
elif Lmode == 2:
limit1 = core.std.MaskedMerge(normsharp, normal, inflate)
elif Lmode == 3:
zero = haf.Clamp(normsharp, brightlimit, darklimit, 0, 0)
limit1 = core.std.MaskedMerge(normal, zero, inflate)
elif Lmode == 4:
second = haf.Clamp(normsharp, brightlimit, darklimit, max(overshoot2, 0)*i, max(undershoot2, 0)*i)
limit1 = core.std.MaskedMerge(second, normal, inflate)
else:
limit1 = R(normsharp, tmp, abs(Lmode))
if edgemode < 0:
return core.resize.Spline36(edge, dw, dh)
if edgemode == 0:
limit2 = limit1
elif edgemode == 1:
limit2 = core.std.MaskedMerge(tmp, limit1, inflate.std.Inflate().std.Convolution(matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1]))
else:
limit2 = core.std.MaskedMerge(limit1, tmp, inflate.std.Inflate().std.Convolution(matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1]))
### SOFT
if soft == 0:
PP1 = limit2
else:
sharpdiff = core.std.MakeDiff(tmp, limit2)
if isFLOAT:
expr2 = 'x abs y abs > y {} * x {} * + x ?'.format(soft, 1-soft)
else:
expr2 = 'x {} - abs y {} - abs > y {} * x {} * + x ?'.format(mid, mid, soft, 1-soft)
sharpdiff = core.std.Expr([sharpdiff, core.std.Convolution(sharpdiff, matrix=[1]*9)],[expr2])
PP1 = core.std.MakeDiff(tmp, sharpdiff)
### SOOTHE
if soothe:
diff = core.std.MakeDiff(tmp, PP1)
if isFLOAT:
expr3 = 'x y * 0 < x {} * x abs y abs > x {} * y {} * + x ? ?'.format(keep, keep, 1-keep)
else:
expr3 = 'x {m} - y {m} - * 0 < x {m} - {k} * {m} + x {m} - abs y {m} - abs > x {k} * y {j} * + x ? ?'.format(m=mid, k=keep, j=1-keep)
diff = core.std.Expr([diff, haf.AverageFrames(diff, [1, 1, 1], 0.125)],[expr3])
PP2 = core.std.MakeDiff(tmp, diff)
else:
PP2 = PP1
### OUTPUT
if dw != ow or dh != oh:
if color in [vs.YUV, vs.YCOCG]:
PP2 = core.std.ShufflePlanes([PP2, clip], [0, 1, 2], color)
PPP = core.resize.Spline36(PP2, dw, dh)
elif ssx > 1 or ssy > 1:
if color in [vs.YUV, vs.YCOCG]:
PP2 = core.std.ShufflePlanes([PP2, clip], [0, 1, 2], color)
PPP = core.resize.Spline36(PP2, dw, dh)
elif color in [vs.YUV, vs.YCOCG]:
PPP = core.std.ShufflePlanes([PP2, clip], [0, 1, 2], color)
else:
PPP = PP2
if source is not None:
if dw != ow or dh != oh:
src = core.resize.Spline36(source, dw, dh)
In = core.resize.Spline36(csrc, dw, dh)
else:
src = source
In = csrc
shrpD = core.std.MakeDiff(In, PPP, [0]) if color in [vs.YUV, vs.YCOCG] else core.std.MakeDiff(In, PPP)
expr4 = 'x abs y abs < x y ?' if isFLOAT else 'x {} - abs y {} - abs < x y ?'.format(mid, mid)
if color in [vs.YUV, vs.YCOCG]:
shrpL = core.std.Expr([R(shrpD, core.std.MakeDiff(In, src, [0]), [1, 0]), shrpD], [expr4, ''])
else:
shrpL = core.std.Expr([R(shrpD, core.std.MakeDiff(In, src), [1]), shrpD], [expr4])
return core.std.MakeDiff(In, shrpL, [0]) if color in [vs.YUV, vs.YCOCG] else core.std.MakeDiff(In, shrpL)
else:
return PPP
def SeeSaw(clip, denoised=None, NRlimit=2, NRlimit2=None, sstr=2, Slimit=None, Spower=4, SdampLo=None, SdampHi=24, Szp=16, bias=50,
Smode=None, NSmode=1, sootheT=50, sootheS=0, ssx=1, ssy=None, diff=False):
"""
Author: Didée (https://avisynth.nl/images/SeeSaw.avs)
(Full Name: "Denoiser-and-Sharpener-are-riding-the-SeeSaw")
This function provides a (simple) implementation of the "crystality sharpen" principle.
In conjunction with a user-specified denoised clip, the aim is to enhance weak detail,
hopefully without oversharpening or creating jaggies on strong detail,
and produce a result that is temporally stable without detail shimmering,
while keeping everything within reasonable bitrate requirements.
This is done by intermixing source, denoised source and a modified sharpening process, in a seesaw-like manner.
You're very much encouraged to feed your own custom denoised clip into SeeSaw.
If the "denoised" clip parameter is omitted, a simple "spatial pressdown" filter is used.
Args:
NRlimit (int) - Absolute limit for pixel change by denoising.
NRlimit2 (int) - Limit for intermediate denoising.
sstr (float) - Sharpening strength (don't touch this too much).
Slimit (int) - Positive: absolute limit for pixel change by sharpening.
Negative: pixel's sharpening difference is reduced to pow(diff, 1/abs(Slimit)).
Spower (float) - Exponent for modified sharpener.
Szp (float) - Zero point, below: overdrive sharpening, above: reduced sharpening.
SdampLo (float) - Reduces overdrive sharpening for very small changes.
SdampHi (float) - Further reduces sharpening for big sharpening changes. Try 15~30. "0" disables.
bias (float) - Bias towards detail (> 50), or towards calm result (< 50).
Smode (int) - RemoveGrain mode used in the modified sharpening function (sharpen2).
Negative: absolute value specifies the MinBlur radius used.
NSmode (int) - 0 = corrected, 1 = original nonlinear sharpening.
sootheT (int) - 0 = minimum, 100 = maximum soothing of sharpener's temporal instability.
Negative: will chain 2 instances of temporal soothing.
sootheS (int) - 0 = minimum, 100 = maximum smoothing of sharpener's spatial effect.
ssx, ssy (int) - SeeSaw doesn't require supersampling urgently, if at all, small values ~1.25 seems to be enough.
diff (bool) - When True, limit the sharp-difference instead of the sharpened clip.
Relative limiting is more safe, less aliasing, but also less sharpening.
This parameter has no effect when Smode <= 0.
"""
# Modified from muvsfunc: https://github.com/WolframRhodium/muvsfunc/blob/v0.2.0/muvsfunc.py#L2007
if not isinstance(clip, vs.VideoNode):
raise TypeError("SeeSaw: This is not a clip!")
if clip.format.color_family == vs.COMPAT:
raise TypeError("SeeSaw: COMPAT color family is not supported!")
if NRlimit2 is None:
NRlimit2 = NRlimit + 1
if Slimit is None:
Slimit = NRlimit + 2
if SdampLo is None:
SdampLo = Spower + 1
if Smode is None:
if ssx <= 1.25:
Smode = 11
elif ssx <= 1.6:
Smode = 20
else:
Smode = 19
if ssy is None:
ssy = ssx
color = clip.format.color_family
Spower = max(Spower, 1)
SdampLo = max(SdampLo, 0)
SdampHi = max(SdampHi, 0)
ssx = max(ssx, 1)
ssy = max(ssy, 1)
ow = clip.width
oh = clip.height
xss = m4(ow * ssx)
yss = m4(oh * ssy)
isFLOAT = clip.format.sample_type == vs.FLOAT
bd = clip.format.bits_per_sample
i = 0.00392 if isFLOAT else 1 << (bd - 8)
mid = 0 if isFLOAT else 1 << (bd - 1)
peak = 1.0 if isFLOAT else (1 << bd) - 1
bias = max(min(bias/100, 1), 0)
NRL = scale(NRlimit, peak)
NRL2 = scale(NRlimit2, peak)
NRLL = scale(NRlimit2/bias - 1, peak)
SLIM = scale(Slimit, peak) if Slimit >= 0 else 1/abs(Slimit)
R = core.rgsf.Repair if isFLOAT else core.rgvs.Repair
if denoised is None:
dnexpr = 'x {N} + y < x {N} + x {N} - y > x {N} - y ? ?'.format(N=NRL)
denoised = core.std.Expr([clip, core.std.Median(clip, [0])], [dnexpr, '']) if color in [vs.YUV, vs.YCOCG] else core.std.Expr([clip, core.std.Median(clip)], [dnexpr])
else:
if not isinstance(denoised, vs.VideoNode) or denoised.format.id != clip.format.id:
raise TypeError("SeeSaw: denoised must be the same format as clip!")
if denoised.width != clip.width or denoised.height != clip.height:
raise TypeError("SeeSaw: denoised must be the same size as clip!")
if color in [vs.YUV, vs.YCOCG]:
tmp = core.std.ShufflePlanes(clip, [0], vs.GRAY)
tmp2 = core.std.ShufflePlanes(denoised, [0], vs.GRAY) if clip != denoised else tmp
else:
tmp = clip
tmp2 = denoised
tameexpr = 'x {N} + y < x {N2} + x {N} - y > x {N2} - x {B} * y {j} * + ? ?'.format(N=NRLL, N2=NRL2, B=bias, j=1-bias)
tame = core.std.Expr([tmp, tmp2], [tameexpr])
if Smode > 0:
head = Sharpen2(tame, sstr, Spower, Szp, SdampLo, SdampHi, 4, NSmode, diff)
head = core.std.MaskedMerge(head, tame, tame.std.Sobel().std.Maximum().std.Convolution(matrix=[1]*9))
if ssx == 1 and ssy == 1:
if Smode <= 0:
sharp = Sharpen2(tame, sstr, Spower, Szp, SdampLo, SdampHi, Smode, NSmode, diff)
else:
sharp = R(Sharpen2(tame, sstr, Spower, Szp, SdampLo, SdampHi, Smode, NSmode, diff), head, [1])
else:
if Smode <= 0:
sharp = Sharpen2(tame.resize.Spline36(xss, yss), sstr, Spower, Szp, SdampLo, SdampHi, Smode, NSmode, diff).resize.Spline36(ow, oh)
else:
sharp = R(Sharpen2(tame.resize.Spline36(xss, yss), sstr, Spower, Szp, SdampLo, SdampHi, Smode, NSmode, diff), head.resize.Spline36(xss, yss), [1]).resize.Spline36(ow, oh)
if diff and Smode > 0:
sharp = core.std.MergeDiff(tame, sharp)
soothed = SootheSS(sharp, tame, sootheT, sootheS)
sharpdiff = core.std.MakeDiff(tame, soothed)
if NRlimit == 0 or clip == denoised:
calm = tmp
else:
NRdiff = core.std.MakeDiff(tmp, tmp2)
if isFLOAT:
expr = 'y {N} > x {N} - y -{N} < x {N} + x y - ? ?'.format(N=NRL)
else:
expr = 'y {m} {N} + > x {N} - y {m} {N} - < x {N} + x y {m} - - ? ?'.format(m=mid, N=NRL)
calm = core.std.Expr([tmp, NRdiff], [expr])
if Slimit >= 0:
if isFLOAT:
limitexpr = 'y {S} > x {S} - y -{S} < x {S} + x y - ? ?'.format(S=SLIM)
else:
limitexpr = 'y {m} {S} + > x {S} - y {m} {S} - < x {S} + x y {m} - - ? ?'.format(m=mid, S=SLIM)
limited = core.std.Expr([calm, sharpdiff], [limitexpr])
else:
if isFLOAT:
limitexpr = 'y 0 = x dup y abs {i} / {S} pow {i} * y 0 > 1 -1 ? * - ?'.format(S=SLIM, i=i)
else:
limitexpr = 'y {m} = x dup y {m} - abs {i} / {S} pow {i} * y {m} > 1 -1 ? * - ?'.format(m=mid, S=SLIM, i=i)
limited = core.std.Expr([calm, sharpdiff], [limitexpr])
return core.std.ShufflePlanes([limited, clip], [0, 1, 2], color) if color in [vs.YUV, vs.YCOCG] else limited
def Sharpen2(clip, sstr, power, zp, ldmp, hdmp, rg, mode, diff):
"""Modified sharpening function from SeeSaw()"""
color = clip.format.color_family
isFLOAT = clip.format.sample_type == vs.FLOAT
bd = clip.format.bits_per_sample
i = 0.00392 if isFLOAT else 1 << (bd - 8)
R = core.rgsf.RemoveGrain if isFLOAT else core.rgvs.RemoveGrain
if not isinstance(clip, vs.VideoNode):
raise TypeError("Sharpen2: This is not a clip!")
if color == vs.COMPAT:
raise TypeError("Sharpen2: COMPAT color family is not supported!")
tmp = core.std.ShufflePlanes(clip, [0], vs.GRAY) if color in [vs.YUV, vs.YCOCG] else clip
if rg <= 0:
diff = False
method = MinBlur(tmp, abs(rg))
elif rg == 4:
method = tmp.std.Median()
elif rg in [11, 12]:
method = tmp.std.Convolution(matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1])
elif rg == 19:
method = tmp.std.Convolution(matrix=[1, 1, 1, 1, 0, 1, 1, 1, 1])
elif rg == 20:
method = tmp.std.Convolution(matrix=[1, 1, 1, 1, 1, 1, 1, 1, 1])
else:
method = R(tmp, mode=[rg])
if mode == 0:
xy = 'x y - abs {} /'.format(i) if bd != 8 else 'x y - abs'
Hi = 1 if hdmp == 0 else '1 {} {} / 4 pow + 1 {} {} / 4 pow + /'.format(zp, hdmp, xy, hdmp)
expr = 'x y = x dup {} dup {} / {} pow swap dup * dup {} {} + * swap {} + {} * / * {} * {} * x y > 1 -1 ? * + ?'
expr = expr.format(xy, zp, 1/power, zp**2, ldmp, ldmp, zp**2, Hi, zp*sstr*i)
normsharp = core.std.Expr([tmp, method], [expr])
else:
xy = 'x y - abs {} /'.format(i) if bd != 8 else 'x y - abs'
Hi = 1 if hdmp == 0 else '1 {} {} / 4 pow +'.format(xy, hdmp)
expr = 'x y = x dup {} dup {} / {} pow swap dup * dup {} + / * {} / {} * x y > 1 -1 ? * + ?'
normsharp = core.std.Expr([tmp, method], [expr.format(xy, zp, 1/power, ldmp, Hi, zp*sstr*i)])
if color in [vs.YUV, vs.YCOCG]:
normsharp = core.std.ShufflePlanes([normsharp, clip], [0, 1, 2], color)
return normsharp if not diff else core.std.MakeDiff(normsharp, clip)
def SootheSS(sharp, src, sootheT=50, sootheS=0):
"""Soothe() function to stabilze sharpening from SeeSaw()"""
if not isinstance(sharp, vs.VideoNode):
raise TypeError("SootheSS: sharp must be a clip!")
if sharp.format.color_family == vs.COMPAT:
raise TypeError("Sharpen2: COMPAT color family is not supported!")
if not isinstance(src, vs.VideoNode) or src.format.id != sharp.format.id:
raise TypeError("SootheSS: src must be of the same format as sharp!")
if src.width != sharp.width or src.height != sharp.height:
raise TypeError("SootheSS: src must be of the same size as sharp!")
ssrc = src