-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdering.py
More file actions
711 lines (605 loc) · 28.3 KB
/
Copy pathdering.py
File metadata and controls
711 lines (605 loc) · 28.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
import vapoursynth as vs
from vapoursynth import core
import math
from typing import Optional, Union, Sequence, TypeVar
from misc import MinBlur, median_blur, mt_expand_multi, mt_inflate_multi
from helpers import scale, DFTTest
from color import LimitFilter
def _hysteresis_fn():
"""Pick the best available Hysteresis."""
if hasattr(core, 'hysteresis'): return core.hysteresis.Hysteresis
return core.misc.Hysteresis
def HQDeringmod(
input: vs.VideoNode,
smoothed: Optional[vs.VideoNode] = None,
ringmask: Optional[vs.VideoNode] = None,
mrad: int = 1,
msmooth: int = 1,
incedge: bool = False,
mthr: int = 60,
minp: int = 1,
nrmode: Optional[int] = None,
sigma: float = 128.0,
sigma2: Optional[float] = None,
sbsize: Optional[int] = None,
sosize: Optional[int] = None,
sharp: int = 1,
drrep: Optional[int] = None,
thr: float = 12.0,
elast: float = 2.0,
darkthr: Optional[float] = None,
planes: Union[int, Sequence[int]] = 0,
show: bool = False,
cuda: bool = False,
) -> vs.VideoNode:
'''
HQDering mod v1.8
Applies deringing by using a smart smoother near edges (where ringing occurs) only.
Parameters:
input: Clip to process.
mrad: Expanding of edge mask, higher value means more aggressive processing.
msmooth: Inflate of edge mask, smooth boundaries of mask.
incedge: Whether to include edge in ring mask, by default ring mask only include area near edges.
mthr: Threshold of prewitt edge mask, lower value means more aggressive processing.
But for strong ringing, lower value will treat some ringing as edge, which protects this ringing from being processed.
minp: Inpanding of prewitt edge mask, higher value means more aggressive processing.
nrmode: Kernel of deringing.
0 = DFTTest
1 = MinBlur(r=1)
2 = MinBlur(r=2)
3 = MinBlur(r=3)
sigma: Sigma for medium frequecies in DFTTest.
sigma2: Sigma for low & high frequecies in DFTTest.
sbsize: Length of the sides of the spatial window in DFTTest.
sosize: Spatial overlap amount in DFTTest.
sharp: Whether to use contra-sharpening to resharp deringed clip, 1-3 represents radius, 0 means no sharpening.
drrep: Use repair for details retention, recommended values are 24/23/13/12/1.
thr: The same meaning with "thr" in LimitFilter.
elast: The same meaning with "elast" in LimitFilter.
darkthr: Threshold for darker area near edges, by default equals to thr/4. Set it lower if you think de-ringing destroys too much lines, etc.
When "darkthr" is not equal to "thr", "thr" limits darkening while "darkthr" limits brightening.
planes: Specifies which planes will be processed. Any unprocessed planes will be simply copied.
show: Whether to output mask clip instead of filtered clip.
cuda: Whether to enable CUDA functionality (for dfttest2).
'''
if not isinstance(input, vs.VideoNode):
raise vs.Error('HQDeringmod: this is not a clip')
if input.format.color_family == vs.RGB:
raise vs.Error('HQDeringmod: RGB format is not supported')
if smoothed is not None:
if not isinstance(smoothed, vs.VideoNode):
raise vs.Error('HQDeringmod: smoothed is not a clip')
if smoothed.format.id != input.format.id:
raise vs.Error("HQDeringmod: smoothed must have the same format as input")
if ringmask is not None and not isinstance(ringmask, vs.VideoNode):
raise vs.Error("HQDeringmod: ringmask is not a clip")
is_gray = input.format.color_family == vs.GRAY
bits = input.format.bits_per_sample
neutral = 1 << (bits - 1)
peak = (1 << bits) - 1
plane_range = range(input.format.num_planes)
if isinstance(planes, int):
planes = [planes]
HD = input.width > 1024 or input.height > 576
nrmode = (2 if HD else 1) if nrmode is None else nrmode
sigma2 = sigma / 16 if sigma2 is None else sigma2
sbsize = (8 if HD else 6) if sbsize is None else sbsize
sosize = (6 if HD else 4) if sosize is None else sosize
drrep = (24 if nrmode > 0 else 0) if drrep is None else drrep
darkthr = thr / 4 if darkthr is None else darkthr
# Kernel: Smoothing
if smoothed is None:
if nrmode <= 0:
# The GPU implementations only cover sbsize == 16; DFTTest() falls back on its own.
smoothed = DFTTest(input, cuda=cuda, sbsize=sbsize, sosize=sosize, tbsize=1,
slocation=[0.0, sigma2, 0.05, sigma, 0.5, sigma, 0.75, sigma2, 1.0, 0.0], planes=planes)
else:
smoothed = MinBlur(input, nrmode, planes)
# Post-Process: Contra-Sharpening
matrix1 = [1, 2, 1, 2, 4, 2, 1, 2, 1]
matrix2 = [1, 1, 1, 1, 1, 1, 1, 1, 1]
has_zsmooth = hasattr(core,'zsmooth')
EXPR = core.akarin.Expr if hasattr(core, 'akarin') else core.cranexpr.Expr if hasattr(core, 'cranexpr') else core.std.Expr
if sharp <= 0:
sclp = smoothed
else:
pre = smoothed.zsmooth.Median(planes=planes) if has_zsmooth else smoothed.std.Median(planes=planes)
if sharp == 1:
method = pre.std.Convolution(matrix=matrix1, planes=planes)
elif sharp == 2:
method = pre.std.Convolution(matrix=matrix1, planes=planes).std.Convolution(matrix=matrix2, planes=planes)
else:
method = (
pre.std.Convolution(matrix=matrix1, planes=planes).std.Convolution(matrix=matrix2, planes=planes).std.Convolution(matrix=matrix2, planes=planes)
)
sharpdiff = core.std.MakeDiff(pre, method, planes=planes)
allD = core.std.MakeDiff(input, smoothed, planes=planes)
if hasattr(core,'zsmooth'):
ssDD = core.zsmooth.Repair(sharpdiff, allD, mode=[1 if i in planes else 0 for i in plane_range])
else:
ssDD = core.rgvs.Repair(sharpdiff, allD, mode=[1 if i in planes else 0 for i in plane_range])
ssDD = EXPR(
[ssDD, sharpdiff], expr=[f'x {neutral} - abs y {neutral} - abs <= x y ?' if i in planes else '' for i in plane_range]
)
sclp = core.std.MergeDiff(smoothed, ssDD, planes=planes)
# Post-Process: Repairing
if drrep <= 0:
repclp = sclp
else:
if has_zsmooth:
repclp = core.zsmooth.Repair(input, sclp, mode=[drrep if i in planes else 0 for i in plane_range])
else:
repclp = core.rgvs.Repair(input, sclp, mode=[drrep if i in planes else 0 for i in plane_range])
# Post-Process: Limiting
if (thr <= 0 and darkthr <= 0) or (thr >= 255 and darkthr >= 255):
limitclp = repclp
else:
limitclp = LimitFilter(repclp, input, thr=thr, elast=elast, brighten_thr=darkthr, planes=planes)
EXPR = core.akarin.Expr if hasattr(core, 'akarin') else core.cranexpr.Expr if hasattr(core, 'cranexpr') else core.std.Expr
# Post-Process: Ringing Mask Generating
if ringmask is None:
expr = f'x {scale(mthr, bits)} < 0 x ?'
PREWITT = core.edgemasks.ExPrewitt if hasattr(core,"edgemasks") else core.std.Prewitt
prewittm = EXPR(PREWITT(input, planes=0), expr=expr if is_gray else [expr, ''])
fmask = _hysteresis_fn()(prewittm.zsmooth.Median(planes=0), prewittm, planes=0) if has_zsmooth else _hysteresis_fn()(prewittm.std.Median(planes=0), prewittm, planes=0)
if mrad > 0:
omask = mt_expand_multi(fmask, planes=0, sw=mrad, sh=mrad)
else:
omask = fmask
if msmooth > 0:
omask = mt_inflate_multi(omask, planes=0, radius=msmooth)
if incedge:
ringmask = omask
else:
if minp > 3:
imask = fmask.std.Minimum(planes=0).std.Minimum(planes=0)
elif minp > 2:
imask = fmask.std.Inflate(planes=0).std.Minimum(planes=0).std.Minimum(planes=0)
elif minp > 1:
imask = fmask.std.Minimum(planes=0)
elif minp > 0:
imask = fmask.std.Inflate(planes=0).std.Minimum(planes=0)
else:
imask = fmask
expr = f'x {peak} y - * {peak} /'
ringmask = EXPR([omask, imask], expr=expr if is_gray else [expr, ''])
# Mask Merging & Output
if show:
if is_gray:
return ringmask
else:
return EXPR(ringmask, expr=['', repr(neutral)])
else:
return core.std.MaskedMerge(input, limitclp, ringmask, planes=planes, first_plane=True)
# Taken from mvsfunc
def mdering(clip: vs.VideoNode, thr: float = 2) -> vs.VideoNode:
"""A simple light and bright DCT ringing remover
It is a special instance of TMinBlur (r=1 and only filter the bright part) for higher performance.
Post-processing is needed to reduce degradation of flat and texture areas.
Args:
clip: Input clip.
thr: (float) Threshold in 8 bits scale.
Default is 2.
"""
if clip.format.sample_type != vs.INTEGER:
raise TypeError(funcName + ': \"clip\" must be an integer clip!')
bits = clip.format.bits_per_sample
thr = scale(thr, bits)
rg11_1 = core.std.Convolution(clip, matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1])
rg11_2 = core.std.Convolution(rg11_1, [1]*9)
rg4_1 = core.std.Median(clip)
if bits <= 12:
rg4_2 = median_blur(clip, radius=2)
else:
rg4_2 = core.fmtc.bitdepth(clip, bits=12, dmode=1)
rg4_2 = median_blur(rg4_2, radius=2).fmtc.bitdepth(bits=bits)
rg4_2 = LimitFilter(clip, rg4_2, thr=0.0625, elast=2)
EXPR = core.akarin.Expr if hasattr(core, 'akarin') else core.cranexpr.Expr if hasattr(core, 'cranexpr') else core.std.Expr
minblur_1 = EXPR([clip, rg11_1, rg4_1], ['x y - x z - xor x x y - abs x z - abs < y z ? ?'])
minblur_2 = EXPR([clip, rg11_2, rg4_2], ['x y - x z - xor x x y - abs x z - abs < y z ? ?'])
dering = EXPR([clip, minblur_1, minblur_2], ['y z - abs {thr} <= y x <= and y x ?'.format(thr=thr)])
return dering
################################################################################################################################
## Helper function: CheckColorFamily()
################################################################################################################################
def CheckColorFamily(color_family, valid_list=None, invalid_list=None):
if valid_list is None:
valid_list = ('RGB', 'YUV', 'GRAY')
if invalid_list is None:
invalid_list = ('COMPAT', 'UNDEFINED')
# check invalid list
for cf in invalid_list:
if color_family == getattr(vs, cf, None):
raise value_error(f'color family *{cf}* is not supported!')
# check valid list
if valid_list:
if color_family not in [getattr(vs, cf, None) for cf in valid_list]:
raise value_error(f'color family not supported, only {valid_list} are accepted')
################################################################################################################################
################################################################################################################################
## Internal used functions for LimitFilter()
################################################################################################################################
def _limit_filter_expr(defref, thr, elast, largen_thr, value_range):
flt = " x "
src = " y "
ref = " z " if defref else src
dif = f" {flt} {src} - "
dif_ref = f" {flt} {ref} - "
dif_abs = dif_ref + " abs "
thr = thr * value_range / 255
largen_thr = largen_thr * value_range / 255
if thr <= 0 and largen_thr <= 0:
limitExpr = f" {src} "
elif thr >= value_range and largen_thr >= value_range:
limitExpr = ""
else:
if thr <= 0:
limitExpr = f" {src} "
elif thr >= value_range:
limitExpr = f" {flt} "
elif elast <= 1:
limitExpr = f" {dif_abs} {thr} <= {flt} {src} ? "
else:
thr_1 = thr
thr_2 = thr * elast
thr_slope = 1 / (thr_2 - thr_1)
# final = src + dif * (thr_2 - dif_abs) / (thr_2 - thr_1)
limitExpr = f" {src} {dif} {thr_2} {dif_abs} - * {thr_slope} * + "
limitExpr = f" {dif_abs} {thr_1} <= {flt} {dif_abs} {thr_2} >= {src} " + limitExpr + " ? ? "
if largen_thr != thr:
if largen_thr <= 0:
limitExprLargen = f" {src} "
elif largen_thr >= value_range:
limitExprLargen = f" {flt} "
elif elast <= 1:
limitExprLargen = f" {dif_abs} {largen_thr} <= {flt} {src} ? "
else:
thr_1 = largen_thr
thr_2 = largen_thr * elast
thr_slope = 1 / (thr_2 - thr_1)
# final = src + dif * (thr_2 - dif_abs) / (thr_2 - thr_1)
limitExprLargen = f" {src} {dif} {thr_2} {dif_abs} - * {thr_slope} * + "
limitExprLargen = f" {dif_abs} {thr_1} <= {flt} {dif_abs} {thr_2} >= {src} " + limitExprLargen + " ? ? "
limitExpr = f" {flt} {ref} > " + limitExprLargen + " " + limitExpr + " ? "
return limitExpr
def _expr2(clips: vs.VideoNode | list[vs.VideoNode], expr: str | list[str]) -> vs.VideoNode:
"""Expr — prefers akarin → cranexpr → std."""
if hasattr(core, "akarin"):
return core.akarin.Expr(clips, expr)
if hasattr(core, "cranexpr"):
return core.cranexpr.Expr(clips, expr)
raise RuntimeError(
"AntiRingLR requires akarin or cranexpr — "
"none found. Install akarin or cranexpr into your VS plugins folder."
)
# --- Hans' Ringing Remover ----------------------------------------------------
#
# Ports of the AviSynth+ functions AntiRingLR, AntiRingLR2, AntiRingL2R2 and
# AntiRing22LR. Each of them is a single Expr made of two to four blocks. A
# block measures the local edge strength, subtracts the radius-2 and radius-3
# protection terms from it, turns what is left into a sigmoid gate and
# multiplies that gate with a pixel delta taken at offsetL/offsetR. The block
# results are combined and finally added to the source pixel.
#
# The AviSynth originals call Expr with scale_inputs="allf", which evaluates the
# expression in the 0..255 range and scales the result back afterwards. Here the
# working clip is float 0..1, so every absolute constant of the original has to
# be divided by 255 -- including the two constants of the sigmoid gate, which is
# what gate_scale does. The "256.0 /" the original applies to the pixel delta is
# folded into the weight as 255/256.
#
# Tap notation: (a, b, coeff) stands for x[a,0] x[b,0] - dup * coeff *
_AR_S128 = 128.0 / 255.0
_AR_S64 = 64.0 / 255.0
_AR_S127 = 127.0 / 255.0
# edge measure windows
_AR_W0 = ((2, 1, 0.75), (1, 0, 1.0), (0, -1, 1.0), (-1, -2, 0.75))
_AR_WL2 = ((3, 2, 0.75), (2, 1, 1.0), (1, 0, 1.0), (0, -1, 0.75))
_AR_WR2 = ((1, 0, 0.75), (0, -1, 1.0), (-1, -2, 1.0), (-2, -3, 0.75))
# One entry per block: (edge window, pr2 taps, pr3 taps, (near, far) of the
# corrected pixel delta, side the weight and offset come from, weight factor,
# operator that combines this block with the ones before it).
# The tap tables are transcribed one by one and are deliberately not symmetric:
# AntiRing22LR reuses the radius-3 taps of AntiRingLR under the edge window of
# AntiRingLR2, and the last block of AntiRingL2R2/AntiRing22LR uses 0.55 where
# AntiRingLR2 uses 0.6.
_AR_MODES = {
"LR": (
(_AR_W0,
((3, 1, 0.66), (2, 0, 1.0), (1, -1, 1.0), (0, -2, 0.66)),
((3, 0, 0.5), (2, -1, 1.0), (1, -2, 1.0), (0, -3, 0.66)),
(0, 2), "L", 1.0, ""),
(_AR_W0,
((-3, -1, 0.66), (-2, 0, 1.0), (-1, 1, 1.0), (0, 2, 0.66)),
((-3, 0, 0.5), (-2, 1, 1.0), (-1, 2, 1.0), (0, 3, 0.66)),
(0, 2), "R", 1.0, "+"),
),
"LR2": (
(_AR_W0,
((3, 1, 0.66), (2, 0, 1.0), (1, -1, 1.0), (0, -2, 0.66)),
((3, 0, 0.5), (2, -1, 1.0), (1, -2, 1.0), (0, -3, 0.66)),
(0, 2), "L", 1.0, ""),
(_AR_W0,
((-3, -1, 0.66), (-2, 0, 1.0), (-1, 1, 1.0), (0, 2, 0.66)),
((-3, 0, 0.5), (-2, 1, 1.0), (-1, 2, 1.0), (0, 3, 0.66)),
(0, 2), "R", 1.0, "+"),
(_AR_WR2,
((-4, -2, 0.66), (-3, -1, 1.0), (-2, 0, 1.0), (-1, 1, 0.66)),
((-4, -1, 0.5), (-3, 0, 1.0), (-2, 1, 1.0), (-1, 2, 0.66)),
(1, 3), "R", 0.6, "-"),
),
"L2R2": (
(_AR_W0,
((3, 1, 0.45), (2, 0, 0.77), (1, -1, 1.0), (0, -2, 0.77), (-1, -3, 0.45)),
((3, 0, 0.5), (2, -1, 1.0), (1, -2, 1.0), (0, -3, 0.5)),
(0, 2), "L", 1.0, ""),
(_AR_WL2,
((4, 2, 0.66), (3, 1, 1.0), (2, 0, 1.0), (1, -1, 0.66)),
((4, 1, 0.66), (3, 0, 1.0), (2, -1, 1.0), (1, -2, 0.5)),
(1, 3), "L", 0.6, "+"),
(_AR_W0,
((-3, -1, 0.45), (-2, 0, 0.77), (-1, 1, 1.0), (0, 2, 0.77), (1, 3, 0.45)),
((-3, 0, 0.5), (-2, 1, 1.0), (-1, 2, 1.0), (0, 3, 0.5)),
(0, 2), "R", 1.0, "+"),
(_AR_WR2,
((-4, -2, 0.66), (-3, -1, 1.0), (-2, 0, 1.0), (-1, 1, 0.66)),
((-4, -1, 0.5), (-3, 0, 1.0), (-2, 1, 1.0), (-1, 2, 0.66)),
(1, 3), "R", 0.55, "-"),
),
"22LR": (
(_AR_W0,
((2, 0, 0.45), (1, -1, 0.77), (0, -2, 1.0), (-1, -3, 0.77), (-2, -4, 0.45)),
((2, -1, 0.5), (1, -2, 1.0), (0, -3, 1.0), (-1, -4, 0.5)),
(0, 2), "L", 1.0, ""),
(_AR_WL2,
((3, 1, 0.66), (2, 0, 1.0), (1, -1, 1.0), (0, -2, 0.66)),
((3, 0, 0.66), (2, -1, 1.0), (1, -2, 1.0), (0, -3, 0.5)),
(1, 3), "L", 0.6, "+"),
(_AR_W0,
((-2, 0, 0.45), (-1, 1, 0.77), (0, 2, 1.0), (1, 3, 0.77), (2, 4, 0.45)),
((-2, 1, 0.5), (-1, 2, 1.0), (0, 3, 1.0), (1, 4, 0.5)),
(0, 2), "R", 1.0, "+"),
(_AR_WR2,
((-3, -1, 0.66), (-2, 0, 1.0), (-1, 1, 1.0), (0, 2, 0.66)),
((-3, 0, 0.5), (-2, 1, 1.0), (-1, 2, 1.0), (0, 3, 0.66)),
(1, 3), "R", 0.55, "-"),
),
}
def _ar_terms(taps) -> str:
"""RPN for sqrt(sum of weighted squared neighbour differences)."""
parts = []
for index, (a, b, coeff) in enumerate(taps):
term = f"x[{a},0] x[{b},0] - dup * "
if coeff != 1.0:
term += f"{coeff} * "
parts.append(term if index == 0 else term + "+ ")
return "".join(parts) + "sqrt "
def _ar_block(spec, weightL: float, offsetL: int, weightR: float, offsetR: int,
pr2_coeff: float, pr3_coeff: float, gate_scale: float, gate_bias: float) -> str:
window, pr2_taps, pr3_taps, (near, far), side, factor, combine = spec
if side == "L":
weight, p, q = weightL * factor, offsetL + near, offsetL + far
else:
weight, p, q = weightR * factor, -(offsetR + near), -(offsetR + far)
weight *= 255.0 / 256.0 # the original divides the delta by 256, the float clip carries 255
return (
_ar_terms(window)
+ _ar_terms(pr2_taps) + f"{pr2_coeff} * - "
+ _ar_terms(pr3_taps) + f"{pr3_coeff} * - "
+ f"{gate_scale} / {gate_bias} - 0.0 max "
+ f"dup 1.0 - swap 1.0 + / 1.0 + {_AR_S128} * 1.0 min "
+ f"x[{p},0] x[{q},0] - * {weight} * -{_AR_S64} max {_AR_S127} min "
+ (f"{combine} " if combine else "")
)
def _ar_expr(mode: str, weightL: float, offsetL: int, weightR: float, offsetR: int,
knee: float, pr2: float, pr3: float) -> str:
pr2_coeff = pr2 * 0.36
pr3_coeff = pr3 * 0.3
# 10.0/knee and 0.5*knee are 8 bit constants; the working clip is float
# 0..1, so the edge measure is lifted into the 0..255 range first
gate_scale = 10.0 / (knee * 255.0)
gate_bias = 0.5 * knee
blocks = (_ar_block(spec, weightL, offsetL, weightR, offsetR, pr2_coeff, pr3_coeff, gate_scale, gate_bias)
for spec in _AR_MODES[mode])
return "".join(blocks) + "x + "
def _ar_apply(cl: vs.VideoNode, planes: str, expr: str) -> vs.VideoNode:
"""Run expr on the requested planes; the output format matches the input."""
fmt_in = cl.format
is_gray = fmt_in.color_family == vs.GRAY
work_fmt = vs.GRAYS if is_gray else vs.YUV444PS
# Full scale in both directions, like the scale_inputs="allf" of the
# original: an integer step of one is 1/255 in the working clip, for luma
# and chroma alike, whatever the range of the source. With the default
# (limited) handling the factor would be 1/219 for luma and 1/224 for
# chroma, and the gate constants below would fit neither.
#
# range_in_s alone does not do it: a _Range/_ColorRange frame property
# takes precedence over the argument (measured), and a clip coming out of
# a player or a script generator carries one. Without dropping it first the
# clip is read as limited and written as full, which stretches the levels.
# CopyFrameProps puts the original properties back at the end.
tagless = core.std.RemoveFrameProps(cl, props=["_Range", "_ColorRange"])
cl_f = core.resize.Bicubic(tagless, format=work_fmt, range_in_s="full", range_s="full")
expr_y = expr if planes in ("luma", "all") else "x"
expr_c = expr if planes in ("chroma", "all") else "x"
expr_list = [expr_y] if is_gray else [expr_y, expr_c, expr_c]
result = core.resize.Bicubic(_expr2(cl_f, expr_list), format=fmt_in, range_in_s="full", range_s="full")
return core.std.CopyFrameProps(result, cl)
def AntiRingLR(
cl: vs.VideoNode,
planes: str = "luma",
weightL: float = 0.25,
offsetL: int = 1,
weightR: float = 0.25,
offsetR: int = 1,
knee: float = 0.7,
pr2: float = 0.5,
pr3: float = 0.5,
) -> vs.VideoNode:
"""
Hans' Ringing Remover — VapourSynth port.
One correction lobe per side. Output format always matches input format.
Parameters
----------
cl : Input clip.
planes : "luma", "chroma", or "all".
weightL : Left-side correction intensity (0.15 – 0.7; 0.0 = inactive,
negative reverses the polarity of the correction).
offsetL : Left-side distance from edge (1 – 3).
weightR : Right-side correction intensity.
offsetR : Right-side distance from edge (1 – 3).
knee : Softness of the on/off curve (0.2 – 1.5).
pr2 : Protection for radius-2 signal components (0.0 – 1.5).
pr3 : Protection for radius-3 signal components (0.0 – 1.5).
"""
return _ar_apply(cl, planes, _ar_expr("LR", weightL, offsetL, weightR, offsetR, knee, pr2, pr3))
def AntiRingLRUD(
cl: vs.VideoNode,
planes: str = "all",
weightL: float = 0.25,
offsetL: int = 1,
weightR: float = 0.25,
offsetR: int = 1,
knee: float = 0.7,
pr2: float = 0.5,
pr3: float = 0.5
) -> vs.VideoNode:
"""
Hans' Ringing Remover — horizontal + vertical pass.
Applies AntiRingLR twice: once normally (fixes left/right ringing),
and once on a 90°-rotated clip (fixes up/down ringing).
"""
# Pass 1 — horizontal ringing
result = AntiRingLR(cl, planes=planes,
weightL=weightL, offsetL=offsetL,
weightR=weightR, offsetR=offsetR,
knee=knee, pr2=pr2, pr3=pr3)
# Pass 2 — vertical ringing via 90° rotation
rotated = core.std.Transpose(result)
rotated = AntiRingLR(rotated, planes=planes,
weightL=weightL, offsetL=offsetL,
weightR=weightR, offsetR=offsetR,
knee=knee, pr2=pr2, pr3=pr3)
result = core.std.Transpose(rotated)
return result
def AntiRingLR2(
cl: vs.VideoNode,
planes: str = "luma",
weightL: float = 0.25,
offsetL: int = 1,
weightR: float = 0.25,
offsetR: int = 1,
knee: float = 0.7,
pr2: float = 0.5,
pr3: float = 0.5,
) -> vs.VideoNode:
"""
Hans' Ringing Remover v2
Extends AntiRingLR with a secondary right-side correction pass
(weightR * 0.6, offset+1) that suppresses a second artifact lobe.
Parameters
----------
cl : Input clip.
planes : "luma", "chroma", or "all".
weightL : Left-side correction intensity (0.15 – 0.7; 0.0 = inactive,
negative reverses the polarity of the correction).
offsetL : Left-side distance from edge (1 – 3).
weightR : Right-side correction intensity.
offsetR : Right-side distance from edge (1 – 3).
knee : Softness of the on/off curve (0.2 – 1.5).
pr2 : Protection for radius-2 signal components (0.0 – 1.5).
pr3 : Protection for radius-3 signal components (0.0 – 1.5).
"""
return _ar_apply(cl, planes, _ar_expr("LR2", weightL, offsetL, weightR, offsetR, knee, pr2, pr3))
def AntiRingL2R2(
cl: vs.VideoNode,
planes: str = "luma",
weightL: float = 0.25,
offsetL: int = 1,
weightR: float = 0.25,
offsetR: int = 1,
knee: float = 0.7,
pr2: float = 0.5,
pr3: float = 0.5,
) -> vs.VideoNode:
"""
Hans' Ringing Remover — two correction lobes on each side.
The secondary lobes sit one pixel further out and are weaker
(weightL * 0.6 on the left, weightR * 0.55 on the right); the primary
protection terms cover five taps instead of four.
Parameters
----------
cl : Input clip.
planes : "luma", "chroma", or "all".
weightL : Left-side correction intensity (0.15 – 0.7; 0.0 = inactive,
negative reverses the polarity of the correction).
offsetL : Left-side distance from edge (1 – 6; higher values suit
upsampled material).
weightR : Right-side correction intensity.
offsetR : Right-side distance from edge (1 – 6).
knee : Softness of the on/off curve (0.2 – 1.5).
pr2 : Protection for radius-2 signal components (0.0 – 1.5).
pr3 : Protection for radius-3 signal components (0.0 – 1.5).
"""
return _ar_apply(cl, planes, _ar_expr("L2R2", weightL, offsetL, weightR, offsetR, knee, pr2, pr3))
def AntiRing22LR(
cl: vs.VideoNode,
planes: str = "luma",
weightL: float = 0.25,
offsetL: int = 1,
weightR: float = 0.25,
offsetR: int = 1,
knee: float = 0.7,
pr2: float = 0.5,
pr3: float = 0.5,
) -> vs.VideoNode:
"""
Hans' Ringing Remover — two correction lobes on each side, with the
protection windows of the primary lobes shifted outwards. Tuned for NTSC
DVD signal structure; the correction fades once the target moves out of
the sampling window, which limits how far the source can be upsampled.
Parameters
----------
cl : Input clip.
planes : "luma", "chroma", or "all".
weightL : Left-side correction intensity (0.15 – 1.5; 0.0 = inactive,
negative reverses the polarity of the correction; higher offsets
usually need higher weights).
offsetL : Left-side distance from edge (1 – 7).
weightR : Right-side correction intensity.
offsetR : Right-side distance from edge (1 – 7).
knee : Softness of the on/off curve (0.2 – 1.5).
pr2 : Protection for radius-2 signal components (0.0 – 1.5).
pr3 : Protection for radius-3 signal components (0.0 – 1.5).
"""
return _ar_apply(cl, planes, _ar_expr("22LR", weightL, offsetL, weightR, offsetR, knee, pr2, pr3))
def AntiRingLR2UD(
cl: vs.VideoNode,
planes: list[int] | None = None,
weightL: float = 0.25,
offsetL: int = 1,
weightR: float = 0.25,
offsetR: int = 1,
knee: float = 0.7,
pr2: float = 0.5,
pr3: float = 0.5,
) -> vs.VideoNode:
"""
Hans' Ringing Remover v2 — horizontal + vertical pass.
Applies AntiRingLR2 twice: once normally (fixes left/right ringing),
and once on a 90°-rotated clip (fixes up/down ringing).
planes : List of plane indices to process. Default [0] = luma only.
"""
if planes is None:
planes = [0]
result = AntiRingLR2(cl, planes=planes,
weightL=weightL, offsetL=offsetL,
weightR=weightR, offsetR=offsetR,
knee=knee, pr2=pr2, pr3=pr3)
rotated = core.std.Transpose(result)
rotated = AntiRingLR2(rotated, planes=planes,
weightL=weightL, offsetL=offsetL,
weightR=weightR, offsetR=offsetR,
knee=knee, pr2=pr2, pr3=pr3)
return core.std.Transpose(rotated)
################################################################################################################################