Skip to content

noise

Classes:

  • AddNoise

    Built-in noise.Add plugin. https://github.com/wwww-wwww/vs-noise

  • ChickenDream
  • FilmGrain

    fgrain_cuda.Add plugin. https://github.com/AmusementClub/vs-fgrain-cuda

  • GrainPP
  • Grainer

    Abstract graining interface

  • LinearLightGrainer

    Base grainer depending on linear RGB clip, input dependent.

  • PlaceboGrain

    placebo.Deband plugin. https://github.com/Lypheo/vs-placebo

Functions:

  • multi_graining

    Interface for applying multiple grainers to a clip.

Attributes:

FadeLimits module-attribute

FadeLimits = tuple[int | Iterable[int] | None, int | Iterable[int] | None]

GrainPostProcessT module-attribute

GrainPostProcessesT module-attribute

GrainPostProcessesT = GrainPostProcessT | list[GrainPostProcessT]

MultiGrainerT module-attribute

MultiGrainerT = (
    Grainer
    | type[Grainer]
    | tuple[Grainer | type[Grainer] | None, float]
    | tuple[Grainer | type[Grainer] | None, float, float]
)

AddNoise

AddNoise(
    strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0),
    sharp: float | ScalerT = Lanczos,
    dynamic: bool = True,
    temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None,
    protect_chroma: bool = True,
    luma_scaling: float | None = None,
    fade_limits: bool | FadeLimits = True,
    *,
    matrix: MatrixT | None = None,
    kernel: KernelT = Catrom,
    neutral_out: bool = False,
    **kwargs: Any
)

Bases: AddNoiseBase

Built-in noise.Add plugin. https://github.com/wwww-wwww/vs-noise

Classes:

Methods:

Attributes:

Source code
 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
def __init__(
    self, strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0), sharp: float | ScalerT = Lanczos,
    dynamic: bool = True, temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None, protect_chroma: bool = True,
    luma_scaling: float | None = None, fade_limits: bool | FadeLimits = True, *,
    matrix: MatrixT | None = None, kernel: KernelT = Catrom, neutral_out: bool = False,
    **kwargs: Any
) -> None:
    super().__init__()

    self.strength = strength
    self.size = size if isinstance(size, tuple) else (size, size)
    self.neutral_out = neutral_out
    self.dynamic = dynamic
    self.postprocess = postprocess
    self.protect_chroma = protect_chroma
    self.luma_scaling = luma_scaling
    self.fade_limits = fade_limits
    self.kwargs = kwargs

    if isinstance(sharp, (float, int)):
        self.scaler: Scaler = BicubicAuto(sharp)
    else:
        self.scaler = Scaler.ensure_obj(sharp, self.__class__)

    if isinstance(temporal_average, tuple):
        self.temporal_average, self.temporal_radius = temporal_average
    else:
        self.temporal_average, self.temporal_radius = temporal_average, 1

    self.matrix = Matrix.from_param(matrix, self.__class__)
    self.kernel = Kernel.ensure_obj(kernel, self.__class__)

dynamic instance-attribute

dynamic = dynamic

fade_limits instance-attribute

fade_limits = fade_limits

kernel instance-attribute

kernel = ensure_obj(kernel, __class__)

kwargs instance-attribute

kwargs = kwargs

luma_scaling instance-attribute

luma_scaling = luma_scaling

matrix instance-attribute

matrix = from_param(matrix, __class__)

neutral_out instance-attribute

neutral_out = neutral_out

postprocess instance-attribute

postprocess = postprocess

protect_chroma instance-attribute

protect_chroma = protect_chroma

scaler instance-attribute

scaler: Scaler = BicubicAuto(sharp)

size instance-attribute

size = size if isinstance(size, tuple) else (size, size)

strength instance-attribute

strength = strength

FBM_SIMPLEX

FBM_SIMPLEX(
    strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0),
    sharp: float | ScalerT = Lanczos,
    dynamic: bool = True,
    temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None,
    protect_chroma: bool = True,
    luma_scaling: float | None = None,
    fade_limits: bool | FadeLimits = True,
    *,
    matrix: MatrixT | None = None,
    kernel: KernelT = Catrom,
    neutral_out: bool = False,
    **kwargs: Any
)

Bases: AddNoiseBase

Methods:

Attributes:

Source code
 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
def __init__(
    self, strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0), sharp: float | ScalerT = Lanczos,
    dynamic: bool = True, temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None, protect_chroma: bool = True,
    luma_scaling: float | None = None, fade_limits: bool | FadeLimits = True, *,
    matrix: MatrixT | None = None, kernel: KernelT = Catrom, neutral_out: bool = False,
    **kwargs: Any
) -> None:
    super().__init__()

    self.strength = strength
    self.size = size if isinstance(size, tuple) else (size, size)
    self.neutral_out = neutral_out
    self.dynamic = dynamic
    self.postprocess = postprocess
    self.protect_chroma = protect_chroma
    self.luma_scaling = luma_scaling
    self.fade_limits = fade_limits
    self.kwargs = kwargs

    if isinstance(sharp, (float, int)):
        self.scaler: Scaler = BicubicAuto(sharp)
    else:
        self.scaler = Scaler.ensure_obj(sharp, self.__class__)

    if isinstance(temporal_average, tuple):
        self.temporal_average, self.temporal_radius = temporal_average
    else:
        self.temporal_average, self.temporal_radius = temporal_average, 1

    self.matrix = Matrix.from_param(matrix, self.__class__)
    self.kernel = Kernel.ensure_obj(kernel, self.__class__)

dynamic instance-attribute

dynamic = dynamic

fade_limits instance-attribute

fade_limits = fade_limits

kernel instance-attribute

kernel = ensure_obj(kernel, __class__)

kwargs instance-attribute

kwargs = kwargs

luma_scaling instance-attribute

luma_scaling = luma_scaling

matrix instance-attribute

matrix = from_param(matrix, __class__)

neutral_out instance-attribute

neutral_out = neutral_out

postprocess instance-attribute

postprocess = postprocess

protect_chroma instance-attribute

protect_chroma = protect_chroma

scaler instance-attribute

scaler: Scaler = BicubicAuto(sharp)

size instance-attribute

size = size if isinstance(size, tuple) else (size, size)

strength instance-attribute

strength = strength

grain

grain(
    clip: VideoNode,
    strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None,
    **kwargs: Any
) -> VideoNode
Source code
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
@inject_self.init_kwargs.clean
def grain(
    self, clip: vs.VideoNode, strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None, **kwargs: Any
) -> vs.VideoNode:
    assert clip.format

    kwargs = self._get_kw(kwargs)

    if strength is None:
        strength = self.strength

    dynamic = fallback(dynamic, self.dynamic)
    strength = strength if isinstance(strength, tuple) else (
        strength, strength if clip.format.num_planes > 1 else 0.0
    )

    if max(strength) <= 0.0:
        return clip

    if strength[0] <= 0.0 and strength[1] > 0.0:
        planes: PlanesT = [1, 2]
    elif strength[0] > 0.0 and strength[1] <= 0.0:
        planes = 0
    else:
        planes = None

    do_taverage = (
        dynamic
        and self.temporal_average > 0 and self.temporal_radius > 0
        and (clip.num_frames > self.temporal_radius * 2)
    )
    do_protect_chroma = self.protect_chroma and strength[1] > 0.0 and clip.format.color_family is vs.YUV
    input_dep = self._is_input_dependent(clip, **kwargs)

    def _wrap_implementation(clip: vs.VideoNode, neutral_out: bool) -> vs.VideoNode:
        if input_dep and do_taverage and not kwargs.get('unsafe_graining', False):
            raise CustomValueError(
                'You can\'t have temporal averaging with input dependent graining as it will create ghosting!'
            )

        if neutral_out and not input_dep:
            length = clip.num_frames + ((self.temporal_radius * 2) if do_taverage else 0)
            base_clip = clip.std.BlankClip(length=length, color=get_neutral_values(clip))
        elif do_taverage:
            base_clip = (clip[0] * self.temporal_radius) + clip + (clip[-1] * self.temporal_radius)
        else:
            base_clip = clip

        def _try_grain(src: vs.VideoNode, stre: tuple[float, float] = strength, **args: Any) -> vs.VideoNode:
            args = kwargs | dict(strength=stre, dynamic=dynamic) | args
            try:
                self._check_input(src, **args)
                grained = self._perform_graining(src, **args)
            except NotImplementedError as e:
                reason, *_ = map(str, e.args)

                if reason == 'dynamic-only':
                    grained = _try_grain(src[src.num_frames // 2], dynamic=True)
                elif reason.startswith('bad-depth'):
                    good_depth = int(reason.split('-')[-1])
                    grained = _try_grain(depth(src, good_depth))
                    grained = depth(grained, src)
                elif reason == 'single-plane':
                    str_luma, str_chroma = strength

                    if str_luma > 0 and str_chroma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )
                    elif str_luma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            src
                        )
                    elif str_chroma > 0:
                        return join(
                            src,
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )

                    return src
                else:
                    raise e

            return grained

        grained = _try_grain(base_clip)

        if input_dep and neutral_out:
            grained = clip.std.MakeDiff(grained)

        return grained

    if (
        self.size == (1.0, 1.0) and not do_taverage and not self.postprocess
        and not do_protect_chroma and self.luma_scaling is None and not self.fade_limits
    ):
        return _wrap_implementation(clip, self.neutral_out)

    (sizex, sizey), mod = self.size, max(clip.format.subsampling_w, clip.format.subsampling_h) << 1
    sx, sy = mod_x(clip.width / sizex, mod), mod_x(clip.height / sizey, mod)

    if (sx, sy) != (clip.width, clip.height):
        sxa, sya = mod_x((clip.width + sx) / 2, mod), mod_x((clip.height + sy) / 2, mod)

        grained = _wrap_implementation(self.scaler.scale(clip, sx, sy), True)

        # If the scale is too big, we need to scale it in two passes, else the window
        # will be too big and the grain will be dampened down too much
        if max(self.size) > 1.5:
            grained = self.scaler.scale(grained, sxa, sya)

        grained = self.scaler.scale(grained, clip.width, clip.height)
    else:
        grained = _wrap_implementation(clip, True)

    if do_taverage:
        average = BlurMatrix.MEAN(taps=self.temporal_radius, mode=ConvMode.TEMPORAL)(grained)
        grained = grained.std.Merge(average, self.temporal_average)
        grained = grained[self.temporal_radius:-self.temporal_radius]

    if self.fade_limits:
        low, high = (None, None) if self.fade_limits is True else self.fade_limits

        low = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(low, 16)))
        ]

        high = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(high, [235, 240])))
        ]

        if complexpr_available:
            limit_expr = 'y neutral - abs A! x A@ - {low} < x A@ + {high} > or neutral y ?'
        else:
            limit_expr = 'x y neutral - abs - {low} < x y neutral - abs + {high} > or neutral y ?'

        grained = norm_expr([clip, grained], limit_expr, planes, low=low, high=high, func=self.__class__.grain)

    if self.postprocess:
        for postprocess in cast(list[GrainPostProcessT], to_arr(self.postprocess)):
            if callable(postprocess):
                try:
                    postprocess = postprocess(grained, clip)
                except TypeError:
                    postprocess = postprocess(grained)

            if isinstance(postprocess, vs.VideoNode):
                grained = postprocess
            else:
                if isinstance(postprocess, GrainPP):
                    postprocess, ppkwargs = postprocess.value, postprocess.kwargs
                else:
                    ppkwargs = KwargsT()

                # fuck importing re
                uses_y = ' y ' in postprocess or postprocess.startswith('y ') or postprocess.endswith(' y')  #type: ignore
                grained = norm_expr(
                    [grained, clip] if uses_y else grained, postprocess, **ppkwargs, func=self.__class__.grain
                )

    neutral = get_neutral_value(clip)

    if self.neutral_out:
        merge_clip = grained.std.MakeDiff(grained)[0].std.Loop(grained.num_frames)
    else:
        merge_clip, grained = clip, clip.std.MergeDiff(grained, planes)

    if do_protect_chroma:
        neutral_mask = Lanczos.resample(clip, clip.format.replace(subsampling_h=0, subsampling_w=0))

        neutral_mask = norm_expr(
            split(neutral_mask), f'y {neutral} = z {neutral} = and {get_peak_value(clip, range_in=ColorRange.FULL)} 0 ?',
            func=self.__class__.grain
        )

        grained = grained.std.MaskedMerge(merge_clip, neutral_mask, [1, 2])

    if self.luma_scaling is not None:
        mask = adg_mask(clip, self.luma_scaling, func=self.grain)

        grained = merge_clip.std.MaskedMerge(grained, mask)

    return grained

GAUSS

GAUSS(
    strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0),
    sharp: float | ScalerT = Lanczos,
    dynamic: bool = True,
    temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None,
    protect_chroma: bool = True,
    luma_scaling: float | None = None,
    fade_limits: bool | FadeLimits = True,
    *,
    matrix: MatrixT | None = None,
    kernel: KernelT = Catrom,
    neutral_out: bool = False,
    **kwargs: Any
)

Bases: AddNoiseBase

Methods:

Attributes:

Source code
 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
def __init__(
    self, strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0), sharp: float | ScalerT = Lanczos,
    dynamic: bool = True, temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None, protect_chroma: bool = True,
    luma_scaling: float | None = None, fade_limits: bool | FadeLimits = True, *,
    matrix: MatrixT | None = None, kernel: KernelT = Catrom, neutral_out: bool = False,
    **kwargs: Any
) -> None:
    super().__init__()

    self.strength = strength
    self.size = size if isinstance(size, tuple) else (size, size)
    self.neutral_out = neutral_out
    self.dynamic = dynamic
    self.postprocess = postprocess
    self.protect_chroma = protect_chroma
    self.luma_scaling = luma_scaling
    self.fade_limits = fade_limits
    self.kwargs = kwargs

    if isinstance(sharp, (float, int)):
        self.scaler: Scaler = BicubicAuto(sharp)
    else:
        self.scaler = Scaler.ensure_obj(sharp, self.__class__)

    if isinstance(temporal_average, tuple):
        self.temporal_average, self.temporal_radius = temporal_average
    else:
        self.temporal_average, self.temporal_radius = temporal_average, 1

    self.matrix = Matrix.from_param(matrix, self.__class__)
    self.kernel = Kernel.ensure_obj(kernel, self.__class__)

dynamic instance-attribute

dynamic = dynamic

fade_limits instance-attribute

fade_limits = fade_limits

kernel instance-attribute

kernel = ensure_obj(kernel, __class__)

kwargs instance-attribute

kwargs = kwargs

luma_scaling instance-attribute

luma_scaling = luma_scaling

matrix instance-attribute

matrix = from_param(matrix, __class__)

neutral_out instance-attribute

neutral_out = neutral_out

postprocess instance-attribute

postprocess = postprocess

protect_chroma instance-attribute

protect_chroma = protect_chroma

scaler instance-attribute

scaler: Scaler = BicubicAuto(sharp)

size instance-attribute

size = size if isinstance(size, tuple) else (size, size)

strength instance-attribute

strength = strength

grain

grain(
    clip: VideoNode,
    strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None,
    **kwargs: Any
) -> VideoNode
Source code
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
@inject_self.init_kwargs.clean
def grain(
    self, clip: vs.VideoNode, strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None, **kwargs: Any
) -> vs.VideoNode:
    assert clip.format

    kwargs = self._get_kw(kwargs)

    if strength is None:
        strength = self.strength

    dynamic = fallback(dynamic, self.dynamic)
    strength = strength if isinstance(strength, tuple) else (
        strength, strength if clip.format.num_planes > 1 else 0.0
    )

    if max(strength) <= 0.0:
        return clip

    if strength[0] <= 0.0 and strength[1] > 0.0:
        planes: PlanesT = [1, 2]
    elif strength[0] > 0.0 and strength[1] <= 0.0:
        planes = 0
    else:
        planes = None

    do_taverage = (
        dynamic
        and self.temporal_average > 0 and self.temporal_radius > 0
        and (clip.num_frames > self.temporal_radius * 2)
    )
    do_protect_chroma = self.protect_chroma and strength[1] > 0.0 and clip.format.color_family is vs.YUV
    input_dep = self._is_input_dependent(clip, **kwargs)

    def _wrap_implementation(clip: vs.VideoNode, neutral_out: bool) -> vs.VideoNode:
        if input_dep and do_taverage and not kwargs.get('unsafe_graining', False):
            raise CustomValueError(
                'You can\'t have temporal averaging with input dependent graining as it will create ghosting!'
            )

        if neutral_out and not input_dep:
            length = clip.num_frames + ((self.temporal_radius * 2) if do_taverage else 0)
            base_clip = clip.std.BlankClip(length=length, color=get_neutral_values(clip))
        elif do_taverage:
            base_clip = (clip[0] * self.temporal_radius) + clip + (clip[-1] * self.temporal_radius)
        else:
            base_clip = clip

        def _try_grain(src: vs.VideoNode, stre: tuple[float, float] = strength, **args: Any) -> vs.VideoNode:
            args = kwargs | dict(strength=stre, dynamic=dynamic) | args
            try:
                self._check_input(src, **args)
                grained = self._perform_graining(src, **args)
            except NotImplementedError as e:
                reason, *_ = map(str, e.args)

                if reason == 'dynamic-only':
                    grained = _try_grain(src[src.num_frames // 2], dynamic=True)
                elif reason.startswith('bad-depth'):
                    good_depth = int(reason.split('-')[-1])
                    grained = _try_grain(depth(src, good_depth))
                    grained = depth(grained, src)
                elif reason == 'single-plane':
                    str_luma, str_chroma = strength

                    if str_luma > 0 and str_chroma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )
                    elif str_luma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            src
                        )
                    elif str_chroma > 0:
                        return join(
                            src,
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )

                    return src
                else:
                    raise e

            return grained

        grained = _try_grain(base_clip)

        if input_dep and neutral_out:
            grained = clip.std.MakeDiff(grained)

        return grained

    if (
        self.size == (1.0, 1.0) and not do_taverage and not self.postprocess
        and not do_protect_chroma and self.luma_scaling is None and not self.fade_limits
    ):
        return _wrap_implementation(clip, self.neutral_out)

    (sizex, sizey), mod = self.size, max(clip.format.subsampling_w, clip.format.subsampling_h) << 1
    sx, sy = mod_x(clip.width / sizex, mod), mod_x(clip.height / sizey, mod)

    if (sx, sy) != (clip.width, clip.height):
        sxa, sya = mod_x((clip.width + sx) / 2, mod), mod_x((clip.height + sy) / 2, mod)

        grained = _wrap_implementation(self.scaler.scale(clip, sx, sy), True)

        # If the scale is too big, we need to scale it in two passes, else the window
        # will be too big and the grain will be dampened down too much
        if max(self.size) > 1.5:
            grained = self.scaler.scale(grained, sxa, sya)

        grained = self.scaler.scale(grained, clip.width, clip.height)
    else:
        grained = _wrap_implementation(clip, True)

    if do_taverage:
        average = BlurMatrix.MEAN(taps=self.temporal_radius, mode=ConvMode.TEMPORAL)(grained)
        grained = grained.std.Merge(average, self.temporal_average)
        grained = grained[self.temporal_radius:-self.temporal_radius]

    if self.fade_limits:
        low, high = (None, None) if self.fade_limits is True else self.fade_limits

        low = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(low, 16)))
        ]

        high = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(high, [235, 240])))
        ]

        if complexpr_available:
            limit_expr = 'y neutral - abs A! x A@ - {low} < x A@ + {high} > or neutral y ?'
        else:
            limit_expr = 'x y neutral - abs - {low} < x y neutral - abs + {high} > or neutral y ?'

        grained = norm_expr([clip, grained], limit_expr, planes, low=low, high=high, func=self.__class__.grain)

    if self.postprocess:
        for postprocess in cast(list[GrainPostProcessT], to_arr(self.postprocess)):
            if callable(postprocess):
                try:
                    postprocess = postprocess(grained, clip)
                except TypeError:
                    postprocess = postprocess(grained)

            if isinstance(postprocess, vs.VideoNode):
                grained = postprocess
            else:
                if isinstance(postprocess, GrainPP):
                    postprocess, ppkwargs = postprocess.value, postprocess.kwargs
                else:
                    ppkwargs = KwargsT()

                # fuck importing re
                uses_y = ' y ' in postprocess or postprocess.startswith('y ') or postprocess.endswith(' y')  #type: ignore
                grained = norm_expr(
                    [grained, clip] if uses_y else grained, postprocess, **ppkwargs, func=self.__class__.grain
                )

    neutral = get_neutral_value(clip)

    if self.neutral_out:
        merge_clip = grained.std.MakeDiff(grained)[0].std.Loop(grained.num_frames)
    else:
        merge_clip, grained = clip, clip.std.MergeDiff(grained, planes)

    if do_protect_chroma:
        neutral_mask = Lanczos.resample(clip, clip.format.replace(subsampling_h=0, subsampling_w=0))

        neutral_mask = norm_expr(
            split(neutral_mask), f'y {neutral} = z {neutral} = and {get_peak_value(clip, range_in=ColorRange.FULL)} 0 ?',
            func=self.__class__.grain
        )

        grained = grained.std.MaskedMerge(merge_clip, neutral_mask, [1, 2])

    if self.luma_scaling is not None:
        mask = adg_mask(clip, self.luma_scaling, func=self.grain)

        grained = merge_clip.std.MaskedMerge(grained, mask)

    return grained

PERLIN

PERLIN(
    strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0),
    sharp: float | ScalerT = Lanczos,
    dynamic: bool = True,
    temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None,
    protect_chroma: bool = True,
    luma_scaling: float | None = None,
    fade_limits: bool | FadeLimits = True,
    *,
    matrix: MatrixT | None = None,
    kernel: KernelT = Catrom,
    neutral_out: bool = False,
    **kwargs: Any
)

Bases: AddNoiseBase

Methods:

Attributes:

Source code
 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
def __init__(
    self, strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0), sharp: float | ScalerT = Lanczos,
    dynamic: bool = True, temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None, protect_chroma: bool = True,
    luma_scaling: float | None = None, fade_limits: bool | FadeLimits = True, *,
    matrix: MatrixT | None = None, kernel: KernelT = Catrom, neutral_out: bool = False,
    **kwargs: Any
) -> None:
    super().__init__()

    self.strength = strength
    self.size = size if isinstance(size, tuple) else (size, size)
    self.neutral_out = neutral_out
    self.dynamic = dynamic
    self.postprocess = postprocess
    self.protect_chroma = protect_chroma
    self.luma_scaling = luma_scaling
    self.fade_limits = fade_limits
    self.kwargs = kwargs

    if isinstance(sharp, (float, int)):
        self.scaler: Scaler = BicubicAuto(sharp)
    else:
        self.scaler = Scaler.ensure_obj(sharp, self.__class__)

    if isinstance(temporal_average, tuple):
        self.temporal_average, self.temporal_radius = temporal_average
    else:
        self.temporal_average, self.temporal_radius = temporal_average, 1

    self.matrix = Matrix.from_param(matrix, self.__class__)
    self.kernel = Kernel.ensure_obj(kernel, self.__class__)

dynamic instance-attribute

dynamic = dynamic

fade_limits instance-attribute

fade_limits = fade_limits

kernel instance-attribute

kernel = ensure_obj(kernel, __class__)

kwargs instance-attribute

kwargs = kwargs

luma_scaling instance-attribute

luma_scaling = luma_scaling

matrix instance-attribute

matrix = from_param(matrix, __class__)

neutral_out instance-attribute

neutral_out = neutral_out

postprocess instance-attribute

postprocess = postprocess

protect_chroma instance-attribute

protect_chroma = protect_chroma

scaler instance-attribute

scaler: Scaler = BicubicAuto(sharp)

size instance-attribute

size = size if isinstance(size, tuple) else (size, size)

strength instance-attribute

strength = strength

grain

grain(
    clip: VideoNode,
    strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None,
    **kwargs: Any
) -> VideoNode
Source code
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
@inject_self.init_kwargs.clean
def grain(
    self, clip: vs.VideoNode, strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None, **kwargs: Any
) -> vs.VideoNode:
    assert clip.format

    kwargs = self._get_kw(kwargs)

    if strength is None:
        strength = self.strength

    dynamic = fallback(dynamic, self.dynamic)
    strength = strength if isinstance(strength, tuple) else (
        strength, strength if clip.format.num_planes > 1 else 0.0
    )

    if max(strength) <= 0.0:
        return clip

    if strength[0] <= 0.0 and strength[1] > 0.0:
        planes: PlanesT = [1, 2]
    elif strength[0] > 0.0 and strength[1] <= 0.0:
        planes = 0
    else:
        planes = None

    do_taverage = (
        dynamic
        and self.temporal_average > 0 and self.temporal_radius > 0
        and (clip.num_frames > self.temporal_radius * 2)
    )
    do_protect_chroma = self.protect_chroma and strength[1] > 0.0 and clip.format.color_family is vs.YUV
    input_dep = self._is_input_dependent(clip, **kwargs)

    def _wrap_implementation(clip: vs.VideoNode, neutral_out: bool) -> vs.VideoNode:
        if input_dep and do_taverage and not kwargs.get('unsafe_graining', False):
            raise CustomValueError(
                'You can\'t have temporal averaging with input dependent graining as it will create ghosting!'
            )

        if neutral_out and not input_dep:
            length = clip.num_frames + ((self.temporal_radius * 2) if do_taverage else 0)
            base_clip = clip.std.BlankClip(length=length, color=get_neutral_values(clip))
        elif do_taverage:
            base_clip = (clip[0] * self.temporal_radius) + clip + (clip[-1] * self.temporal_radius)
        else:
            base_clip = clip

        def _try_grain(src: vs.VideoNode, stre: tuple[float, float] = strength, **args: Any) -> vs.VideoNode:
            args = kwargs | dict(strength=stre, dynamic=dynamic) | args
            try:
                self._check_input(src, **args)
                grained = self._perform_graining(src, **args)
            except NotImplementedError as e:
                reason, *_ = map(str, e.args)

                if reason == 'dynamic-only':
                    grained = _try_grain(src[src.num_frames // 2], dynamic=True)
                elif reason.startswith('bad-depth'):
                    good_depth = int(reason.split('-')[-1])
                    grained = _try_grain(depth(src, good_depth))
                    grained = depth(grained, src)
                elif reason == 'single-plane':
                    str_luma, str_chroma = strength

                    if str_luma > 0 and str_chroma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )
                    elif str_luma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            src
                        )
                    elif str_chroma > 0:
                        return join(
                            src,
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )

                    return src
                else:
                    raise e

            return grained

        grained = _try_grain(base_clip)

        if input_dep and neutral_out:
            grained = clip.std.MakeDiff(grained)

        return grained

    if (
        self.size == (1.0, 1.0) and not do_taverage and not self.postprocess
        and not do_protect_chroma and self.luma_scaling is None and not self.fade_limits
    ):
        return _wrap_implementation(clip, self.neutral_out)

    (sizex, sizey), mod = self.size, max(clip.format.subsampling_w, clip.format.subsampling_h) << 1
    sx, sy = mod_x(clip.width / sizex, mod), mod_x(clip.height / sizey, mod)

    if (sx, sy) != (clip.width, clip.height):
        sxa, sya = mod_x((clip.width + sx) / 2, mod), mod_x((clip.height + sy) / 2, mod)

        grained = _wrap_implementation(self.scaler.scale(clip, sx, sy), True)

        # If the scale is too big, we need to scale it in two passes, else the window
        # will be too big and the grain will be dampened down too much
        if max(self.size) > 1.5:
            grained = self.scaler.scale(grained, sxa, sya)

        grained = self.scaler.scale(grained, clip.width, clip.height)
    else:
        grained = _wrap_implementation(clip, True)

    if do_taverage:
        average = BlurMatrix.MEAN(taps=self.temporal_radius, mode=ConvMode.TEMPORAL)(grained)
        grained = grained.std.Merge(average, self.temporal_average)
        grained = grained[self.temporal_radius:-self.temporal_radius]

    if self.fade_limits:
        low, high = (None, None) if self.fade_limits is True else self.fade_limits

        low = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(low, 16)))
        ]

        high = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(high, [235, 240])))
        ]

        if complexpr_available:
            limit_expr = 'y neutral - abs A! x A@ - {low} < x A@ + {high} > or neutral y ?'
        else:
            limit_expr = 'x y neutral - abs - {low} < x y neutral - abs + {high} > or neutral y ?'

        grained = norm_expr([clip, grained], limit_expr, planes, low=low, high=high, func=self.__class__.grain)

    if self.postprocess:
        for postprocess in cast(list[GrainPostProcessT], to_arr(self.postprocess)):
            if callable(postprocess):
                try:
                    postprocess = postprocess(grained, clip)
                except TypeError:
                    postprocess = postprocess(grained)

            if isinstance(postprocess, vs.VideoNode):
                grained = postprocess
            else:
                if isinstance(postprocess, GrainPP):
                    postprocess, ppkwargs = postprocess.value, postprocess.kwargs
                else:
                    ppkwargs = KwargsT()

                # fuck importing re
                uses_y = ' y ' in postprocess or postprocess.startswith('y ') or postprocess.endswith(' y')  #type: ignore
                grained = norm_expr(
                    [grained, clip] if uses_y else grained, postprocess, **ppkwargs, func=self.__class__.grain
                )

    neutral = get_neutral_value(clip)

    if self.neutral_out:
        merge_clip = grained.std.MakeDiff(grained)[0].std.Loop(grained.num_frames)
    else:
        merge_clip, grained = clip, clip.std.MergeDiff(grained, planes)

    if do_protect_chroma:
        neutral_mask = Lanczos.resample(clip, clip.format.replace(subsampling_h=0, subsampling_w=0))

        neutral_mask = norm_expr(
            split(neutral_mask), f'y {neutral} = z {neutral} = and {get_peak_value(clip, range_in=ColorRange.FULL)} 0 ?',
            func=self.__class__.grain
        )

        grained = grained.std.MaskedMerge(merge_clip, neutral_mask, [1, 2])

    if self.luma_scaling is not None:
        mask = adg_mask(clip, self.luma_scaling, func=self.grain)

        grained = merge_clip.std.MaskedMerge(grained, mask)

    return grained

POISSON

POISSON(
    strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0),
    sharp: float | ScalerT = Lanczos,
    dynamic: bool = True,
    temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None,
    protect_chroma: bool = True,
    luma_scaling: float | None = None,
    fade_limits: bool | FadeLimits = True,
    *,
    matrix: MatrixT | None = None,
    kernel: KernelT = Catrom,
    neutral_out: bool = False,
    **kwargs: Any
)

Bases: AddNoiseBase

Methods:

Attributes:

Source code
 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
def __init__(
    self, strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0), sharp: float | ScalerT = Lanczos,
    dynamic: bool = True, temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None, protect_chroma: bool = True,
    luma_scaling: float | None = None, fade_limits: bool | FadeLimits = True, *,
    matrix: MatrixT | None = None, kernel: KernelT = Catrom, neutral_out: bool = False,
    **kwargs: Any
) -> None:
    super().__init__()

    self.strength = strength
    self.size = size if isinstance(size, tuple) else (size, size)
    self.neutral_out = neutral_out
    self.dynamic = dynamic
    self.postprocess = postprocess
    self.protect_chroma = protect_chroma
    self.luma_scaling = luma_scaling
    self.fade_limits = fade_limits
    self.kwargs = kwargs

    if isinstance(sharp, (float, int)):
        self.scaler: Scaler = BicubicAuto(sharp)
    else:
        self.scaler = Scaler.ensure_obj(sharp, self.__class__)

    if isinstance(temporal_average, tuple):
        self.temporal_average, self.temporal_radius = temporal_average
    else:
        self.temporal_average, self.temporal_radius = temporal_average, 1

    self.matrix = Matrix.from_param(matrix, self.__class__)
    self.kernel = Kernel.ensure_obj(kernel, self.__class__)

dynamic instance-attribute

dynamic = dynamic

fade_limits instance-attribute

fade_limits = fade_limits

kernel instance-attribute

kernel = ensure_obj(kernel, __class__)

kwargs instance-attribute

kwargs = kwargs

luma_scaling instance-attribute

luma_scaling = luma_scaling

matrix instance-attribute

matrix = from_param(matrix, __class__)

neutral_out instance-attribute

neutral_out = neutral_out

postprocess instance-attribute

postprocess = postprocess

protect_chroma instance-attribute

protect_chroma = protect_chroma

scaler instance-attribute

scaler: Scaler = BicubicAuto(sharp)

size instance-attribute

size = size if isinstance(size, tuple) else (size, size)

strength instance-attribute

strength = strength

grain

grain(
    clip: VideoNode,
    strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None,
    **kwargs: Any
) -> VideoNode
Source code
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
@inject_self.init_kwargs.clean
def grain(
    self, clip: vs.VideoNode, strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None, **kwargs: Any
) -> vs.VideoNode:
    assert clip.format

    kwargs = self._get_kw(kwargs)

    if strength is None:
        strength = self.strength

    dynamic = fallback(dynamic, self.dynamic)
    strength = strength if isinstance(strength, tuple) else (
        strength, strength if clip.format.num_planes > 1 else 0.0
    )

    if max(strength) <= 0.0:
        return clip

    if strength[0] <= 0.0 and strength[1] > 0.0:
        planes: PlanesT = [1, 2]
    elif strength[0] > 0.0 and strength[1] <= 0.0:
        planes = 0
    else:
        planes = None

    do_taverage = (
        dynamic
        and self.temporal_average > 0 and self.temporal_radius > 0
        and (clip.num_frames > self.temporal_radius * 2)
    )
    do_protect_chroma = self.protect_chroma and strength[1] > 0.0 and clip.format.color_family is vs.YUV
    input_dep = self._is_input_dependent(clip, **kwargs)

    def _wrap_implementation(clip: vs.VideoNode, neutral_out: bool) -> vs.VideoNode:
        if input_dep and do_taverage and not kwargs.get('unsafe_graining', False):
            raise CustomValueError(
                'You can\'t have temporal averaging with input dependent graining as it will create ghosting!'
            )

        if neutral_out and not input_dep:
            length = clip.num_frames + ((self.temporal_radius * 2) if do_taverage else 0)
            base_clip = clip.std.BlankClip(length=length, color=get_neutral_values(clip))
        elif do_taverage:
            base_clip = (clip[0] * self.temporal_radius) + clip + (clip[-1] * self.temporal_radius)
        else:
            base_clip = clip

        def _try_grain(src: vs.VideoNode, stre: tuple[float, float] = strength, **args: Any) -> vs.VideoNode:
            args = kwargs | dict(strength=stre, dynamic=dynamic) | args
            try:
                self._check_input(src, **args)
                grained = self._perform_graining(src, **args)
            except NotImplementedError as e:
                reason, *_ = map(str, e.args)

                if reason == 'dynamic-only':
                    grained = _try_grain(src[src.num_frames // 2], dynamic=True)
                elif reason.startswith('bad-depth'):
                    good_depth = int(reason.split('-')[-1])
                    grained = _try_grain(depth(src, good_depth))
                    grained = depth(grained, src)
                elif reason == 'single-plane':
                    str_luma, str_chroma = strength

                    if str_luma > 0 and str_chroma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )
                    elif str_luma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            src
                        )
                    elif str_chroma > 0:
                        return join(
                            src,
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )

                    return src
                else:
                    raise e

            return grained

        grained = _try_grain(base_clip)

        if input_dep and neutral_out:
            grained = clip.std.MakeDiff(grained)

        return grained

    if (
        self.size == (1.0, 1.0) and not do_taverage and not self.postprocess
        and not do_protect_chroma and self.luma_scaling is None and not self.fade_limits
    ):
        return _wrap_implementation(clip, self.neutral_out)

    (sizex, sizey), mod = self.size, max(clip.format.subsampling_w, clip.format.subsampling_h) << 1
    sx, sy = mod_x(clip.width / sizex, mod), mod_x(clip.height / sizey, mod)

    if (sx, sy) != (clip.width, clip.height):
        sxa, sya = mod_x((clip.width + sx) / 2, mod), mod_x((clip.height + sy) / 2, mod)

        grained = _wrap_implementation(self.scaler.scale(clip, sx, sy), True)

        # If the scale is too big, we need to scale it in two passes, else the window
        # will be too big and the grain will be dampened down too much
        if max(self.size) > 1.5:
            grained = self.scaler.scale(grained, sxa, sya)

        grained = self.scaler.scale(grained, clip.width, clip.height)
    else:
        grained = _wrap_implementation(clip, True)

    if do_taverage:
        average = BlurMatrix.MEAN(taps=self.temporal_radius, mode=ConvMode.TEMPORAL)(grained)
        grained = grained.std.Merge(average, self.temporal_average)
        grained = grained[self.temporal_radius:-self.temporal_radius]

    if self.fade_limits:
        low, high = (None, None) if self.fade_limits is True else self.fade_limits

        low = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(low, 16)))
        ]

        high = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(high, [235, 240])))
        ]

        if complexpr_available:
            limit_expr = 'y neutral - abs A! x A@ - {low} < x A@ + {high} > or neutral y ?'
        else:
            limit_expr = 'x y neutral - abs - {low} < x y neutral - abs + {high} > or neutral y ?'

        grained = norm_expr([clip, grained], limit_expr, planes, low=low, high=high, func=self.__class__.grain)

    if self.postprocess:
        for postprocess in cast(list[GrainPostProcessT], to_arr(self.postprocess)):
            if callable(postprocess):
                try:
                    postprocess = postprocess(grained, clip)
                except TypeError:
                    postprocess = postprocess(grained)

            if isinstance(postprocess, vs.VideoNode):
                grained = postprocess
            else:
                if isinstance(postprocess, GrainPP):
                    postprocess, ppkwargs = postprocess.value, postprocess.kwargs
                else:
                    ppkwargs = KwargsT()

                # fuck importing re
                uses_y = ' y ' in postprocess or postprocess.startswith('y ') or postprocess.endswith(' y')  #type: ignore
                grained = norm_expr(
                    [grained, clip] if uses_y else grained, postprocess, **ppkwargs, func=self.__class__.grain
                )

    neutral = get_neutral_value(clip)

    if self.neutral_out:
        merge_clip = grained.std.MakeDiff(grained)[0].std.Loop(grained.num_frames)
    else:
        merge_clip, grained = clip, clip.std.MergeDiff(grained, planes)

    if do_protect_chroma:
        neutral_mask = Lanczos.resample(clip, clip.format.replace(subsampling_h=0, subsampling_w=0))

        neutral_mask = norm_expr(
            split(neutral_mask), f'y {neutral} = z {neutral} = and {get_peak_value(clip, range_in=ColorRange.FULL)} 0 ?',
            func=self.__class__.grain
        )

        grained = grained.std.MaskedMerge(merge_clip, neutral_mask, [1, 2])

    if self.luma_scaling is not None:
        mask = adg_mask(clip, self.luma_scaling, func=self.grain)

        grained = merge_clip.std.MaskedMerge(grained, mask)

    return grained

SIMPLEX

SIMPLEX(
    strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0),
    sharp: float | ScalerT = Lanczos,
    dynamic: bool = True,
    temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None,
    protect_chroma: bool = True,
    luma_scaling: float | None = None,
    fade_limits: bool | FadeLimits = True,
    *,
    matrix: MatrixT | None = None,
    kernel: KernelT = Catrom,
    neutral_out: bool = False,
    **kwargs: Any
)

Bases: AddNoiseBase

Methods:

Attributes:

Source code
 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
def __init__(
    self, strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0), sharp: float | ScalerT = Lanczos,
    dynamic: bool = True, temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None, protect_chroma: bool = True,
    luma_scaling: float | None = None, fade_limits: bool | FadeLimits = True, *,
    matrix: MatrixT | None = None, kernel: KernelT = Catrom, neutral_out: bool = False,
    **kwargs: Any
) -> None:
    super().__init__()

    self.strength = strength
    self.size = size if isinstance(size, tuple) else (size, size)
    self.neutral_out = neutral_out
    self.dynamic = dynamic
    self.postprocess = postprocess
    self.protect_chroma = protect_chroma
    self.luma_scaling = luma_scaling
    self.fade_limits = fade_limits
    self.kwargs = kwargs

    if isinstance(sharp, (float, int)):
        self.scaler: Scaler = BicubicAuto(sharp)
    else:
        self.scaler = Scaler.ensure_obj(sharp, self.__class__)

    if isinstance(temporal_average, tuple):
        self.temporal_average, self.temporal_radius = temporal_average
    else:
        self.temporal_average, self.temporal_radius = temporal_average, 1

    self.matrix = Matrix.from_param(matrix, self.__class__)
    self.kernel = Kernel.ensure_obj(kernel, self.__class__)

dynamic instance-attribute

dynamic = dynamic

fade_limits instance-attribute

fade_limits = fade_limits

kernel instance-attribute

kernel = ensure_obj(kernel, __class__)

kwargs instance-attribute

kwargs = kwargs

luma_scaling instance-attribute

luma_scaling = luma_scaling

matrix instance-attribute

matrix = from_param(matrix, __class__)

neutral_out instance-attribute

neutral_out = neutral_out

postprocess instance-attribute

postprocess = postprocess

protect_chroma instance-attribute

protect_chroma = protect_chroma

scaler instance-attribute

scaler: Scaler = BicubicAuto(sharp)

size instance-attribute

size = size if isinstance(size, tuple) else (size, size)

strength instance-attribute

strength = strength

grain

grain(
    clip: VideoNode,
    strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None,
    **kwargs: Any
) -> VideoNode
Source code
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
@inject_self.init_kwargs.clean
def grain(
    self, clip: vs.VideoNode, strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None, **kwargs: Any
) -> vs.VideoNode:
    assert clip.format

    kwargs = self._get_kw(kwargs)

    if strength is None:
        strength = self.strength

    dynamic = fallback(dynamic, self.dynamic)
    strength = strength if isinstance(strength, tuple) else (
        strength, strength if clip.format.num_planes > 1 else 0.0
    )

    if max(strength) <= 0.0:
        return clip

    if strength[0] <= 0.0 and strength[1] > 0.0:
        planes: PlanesT = [1, 2]
    elif strength[0] > 0.0 and strength[1] <= 0.0:
        planes = 0
    else:
        planes = None

    do_taverage = (
        dynamic
        and self.temporal_average > 0 and self.temporal_radius > 0
        and (clip.num_frames > self.temporal_radius * 2)
    )
    do_protect_chroma = self.protect_chroma and strength[1] > 0.0 and clip.format.color_family is vs.YUV
    input_dep = self._is_input_dependent(clip, **kwargs)

    def _wrap_implementation(clip: vs.VideoNode, neutral_out: bool) -> vs.VideoNode:
        if input_dep and do_taverage and not kwargs.get('unsafe_graining', False):
            raise CustomValueError(
                'You can\'t have temporal averaging with input dependent graining as it will create ghosting!'
            )

        if neutral_out and not input_dep:
            length = clip.num_frames + ((self.temporal_radius * 2) if do_taverage else 0)
            base_clip = clip.std.BlankClip(length=length, color=get_neutral_values(clip))
        elif do_taverage:
            base_clip = (clip[0] * self.temporal_radius) + clip + (clip[-1] * self.temporal_radius)
        else:
            base_clip = clip

        def _try_grain(src: vs.VideoNode, stre: tuple[float, float] = strength, **args: Any) -> vs.VideoNode:
            args = kwargs | dict(strength=stre, dynamic=dynamic) | args
            try:
                self._check_input(src, **args)
                grained = self._perform_graining(src, **args)
            except NotImplementedError as e:
                reason, *_ = map(str, e.args)

                if reason == 'dynamic-only':
                    grained = _try_grain(src[src.num_frames // 2], dynamic=True)
                elif reason.startswith('bad-depth'):
                    good_depth = int(reason.split('-')[-1])
                    grained = _try_grain(depth(src, good_depth))
                    grained = depth(grained, src)
                elif reason == 'single-plane':
                    str_luma, str_chroma = strength

                    if str_luma > 0 and str_chroma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )
                    elif str_luma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            src
                        )
                    elif str_chroma > 0:
                        return join(
                            src,
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )

                    return src
                else:
                    raise e

            return grained

        grained = _try_grain(base_clip)

        if input_dep and neutral_out:
            grained = clip.std.MakeDiff(grained)

        return grained

    if (
        self.size == (1.0, 1.0) and not do_taverage and not self.postprocess
        and not do_protect_chroma and self.luma_scaling is None and not self.fade_limits
    ):
        return _wrap_implementation(clip, self.neutral_out)

    (sizex, sizey), mod = self.size, max(clip.format.subsampling_w, clip.format.subsampling_h) << 1
    sx, sy = mod_x(clip.width / sizex, mod), mod_x(clip.height / sizey, mod)

    if (sx, sy) != (clip.width, clip.height):
        sxa, sya = mod_x((clip.width + sx) / 2, mod), mod_x((clip.height + sy) / 2, mod)

        grained = _wrap_implementation(self.scaler.scale(clip, sx, sy), True)

        # If the scale is too big, we need to scale it in two passes, else the window
        # will be too big and the grain will be dampened down too much
        if max(self.size) > 1.5:
            grained = self.scaler.scale(grained, sxa, sya)

        grained = self.scaler.scale(grained, clip.width, clip.height)
    else:
        grained = _wrap_implementation(clip, True)

    if do_taverage:
        average = BlurMatrix.MEAN(taps=self.temporal_radius, mode=ConvMode.TEMPORAL)(grained)
        grained = grained.std.Merge(average, self.temporal_average)
        grained = grained[self.temporal_radius:-self.temporal_radius]

    if self.fade_limits:
        low, high = (None, None) if self.fade_limits is True else self.fade_limits

        low = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(low, 16)))
        ]

        high = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(high, [235, 240])))
        ]

        if complexpr_available:
            limit_expr = 'y neutral - abs A! x A@ - {low} < x A@ + {high} > or neutral y ?'
        else:
            limit_expr = 'x y neutral - abs - {low} < x y neutral - abs + {high} > or neutral y ?'

        grained = norm_expr([clip, grained], limit_expr, planes, low=low, high=high, func=self.__class__.grain)

    if self.postprocess:
        for postprocess in cast(list[GrainPostProcessT], to_arr(self.postprocess)):
            if callable(postprocess):
                try:
                    postprocess = postprocess(grained, clip)
                except TypeError:
                    postprocess = postprocess(grained)

            if isinstance(postprocess, vs.VideoNode):
                grained = postprocess
            else:
                if isinstance(postprocess, GrainPP):
                    postprocess, ppkwargs = postprocess.value, postprocess.kwargs
                else:
                    ppkwargs = KwargsT()

                # fuck importing re
                uses_y = ' y ' in postprocess or postprocess.startswith('y ') or postprocess.endswith(' y')  #type: ignore
                grained = norm_expr(
                    [grained, clip] if uses_y else grained, postprocess, **ppkwargs, func=self.__class__.grain
                )

    neutral = get_neutral_value(clip)

    if self.neutral_out:
        merge_clip = grained.std.MakeDiff(grained)[0].std.Loop(grained.num_frames)
    else:
        merge_clip, grained = clip, clip.std.MergeDiff(grained, planes)

    if do_protect_chroma:
        neutral_mask = Lanczos.resample(clip, clip.format.replace(subsampling_h=0, subsampling_w=0))

        neutral_mask = norm_expr(
            split(neutral_mask), f'y {neutral} = z {neutral} = and {get_peak_value(clip, range_in=ColorRange.FULL)} 0 ?',
            func=self.__class__.grain
        )

        grained = grained.std.MaskedMerge(merge_clip, neutral_mask, [1, 2])

    if self.luma_scaling is not None:
        mask = adg_mask(clip, self.luma_scaling, func=self.grain)

        grained = merge_clip.std.MaskedMerge(grained, mask)

    return grained

grain

grain(
    clip: VideoNode,
    strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None,
    **kwargs: Any
) -> VideoNode
Source code
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
@inject_self.init_kwargs.clean
def grain(
    self, clip: vs.VideoNode, strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None, **kwargs: Any
) -> vs.VideoNode:
    assert clip.format

    kwargs = self._get_kw(kwargs)

    if strength is None:
        strength = self.strength

    dynamic = fallback(dynamic, self.dynamic)
    strength = strength if isinstance(strength, tuple) else (
        strength, strength if clip.format.num_planes > 1 else 0.0
    )

    if max(strength) <= 0.0:
        return clip

    if strength[0] <= 0.0 and strength[1] > 0.0:
        planes: PlanesT = [1, 2]
    elif strength[0] > 0.0 and strength[1] <= 0.0:
        planes = 0
    else:
        planes = None

    do_taverage = (
        dynamic
        and self.temporal_average > 0 and self.temporal_radius > 0
        and (clip.num_frames > self.temporal_radius * 2)
    )
    do_protect_chroma = self.protect_chroma and strength[1] > 0.0 and clip.format.color_family is vs.YUV
    input_dep = self._is_input_dependent(clip, **kwargs)

    def _wrap_implementation(clip: vs.VideoNode, neutral_out: bool) -> vs.VideoNode:
        if input_dep and do_taverage and not kwargs.get('unsafe_graining', False):
            raise CustomValueError(
                'You can\'t have temporal averaging with input dependent graining as it will create ghosting!'
            )

        if neutral_out and not input_dep:
            length = clip.num_frames + ((self.temporal_radius * 2) if do_taverage else 0)
            base_clip = clip.std.BlankClip(length=length, color=get_neutral_values(clip))
        elif do_taverage:
            base_clip = (clip[0] * self.temporal_radius) + clip + (clip[-1] * self.temporal_radius)
        else:
            base_clip = clip

        def _try_grain(src: vs.VideoNode, stre: tuple[float, float] = strength, **args: Any) -> vs.VideoNode:
            args = kwargs | dict(strength=stre, dynamic=dynamic) | args
            try:
                self._check_input(src, **args)
                grained = self._perform_graining(src, **args)
            except NotImplementedError as e:
                reason, *_ = map(str, e.args)

                if reason == 'dynamic-only':
                    grained = _try_grain(src[src.num_frames // 2], dynamic=True)
                elif reason.startswith('bad-depth'):
                    good_depth = int(reason.split('-')[-1])
                    grained = _try_grain(depth(src, good_depth))
                    grained = depth(grained, src)
                elif reason == 'single-plane':
                    str_luma, str_chroma = strength

                    if str_luma > 0 and str_chroma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )
                    elif str_luma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            src
                        )
                    elif str_chroma > 0:
                        return join(
                            src,
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )

                    return src
                else:
                    raise e

            return grained

        grained = _try_grain(base_clip)

        if input_dep and neutral_out:
            grained = clip.std.MakeDiff(grained)

        return grained

    if (
        self.size == (1.0, 1.0) and not do_taverage and not self.postprocess
        and not do_protect_chroma and self.luma_scaling is None and not self.fade_limits
    ):
        return _wrap_implementation(clip, self.neutral_out)

    (sizex, sizey), mod = self.size, max(clip.format.subsampling_w, clip.format.subsampling_h) << 1
    sx, sy = mod_x(clip.width / sizex, mod), mod_x(clip.height / sizey, mod)

    if (sx, sy) != (clip.width, clip.height):
        sxa, sya = mod_x((clip.width + sx) / 2, mod), mod_x((clip.height + sy) / 2, mod)

        grained = _wrap_implementation(self.scaler.scale(clip, sx, sy), True)

        # If the scale is too big, we need to scale it in two passes, else the window
        # will be too big and the grain will be dampened down too much
        if max(self.size) > 1.5:
            grained = self.scaler.scale(grained, sxa, sya)

        grained = self.scaler.scale(grained, clip.width, clip.height)
    else:
        grained = _wrap_implementation(clip, True)

    if do_taverage:
        average = BlurMatrix.MEAN(taps=self.temporal_radius, mode=ConvMode.TEMPORAL)(grained)
        grained = grained.std.Merge(average, self.temporal_average)
        grained = grained[self.temporal_radius:-self.temporal_radius]

    if self.fade_limits:
        low, high = (None, None) if self.fade_limits is True else self.fade_limits

        low = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(low, 16)))
        ]

        high = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(high, [235, 240])))
        ]

        if complexpr_available:
            limit_expr = 'y neutral - abs A! x A@ - {low} < x A@ + {high} > or neutral y ?'
        else:
            limit_expr = 'x y neutral - abs - {low} < x y neutral - abs + {high} > or neutral y ?'

        grained = norm_expr([clip, grained], limit_expr, planes, low=low, high=high, func=self.__class__.grain)

    if self.postprocess:
        for postprocess in cast(list[GrainPostProcessT], to_arr(self.postprocess)):
            if callable(postprocess):
                try:
                    postprocess = postprocess(grained, clip)
                except TypeError:
                    postprocess = postprocess(grained)

            if isinstance(postprocess, vs.VideoNode):
                grained = postprocess
            else:
                if isinstance(postprocess, GrainPP):
                    postprocess, ppkwargs = postprocess.value, postprocess.kwargs
                else:
                    ppkwargs = KwargsT()

                # fuck importing re
                uses_y = ' y ' in postprocess or postprocess.startswith('y ') or postprocess.endswith(' y')  #type: ignore
                grained = norm_expr(
                    [grained, clip] if uses_y else grained, postprocess, **ppkwargs, func=self.__class__.grain
                )

    neutral = get_neutral_value(clip)

    if self.neutral_out:
        merge_clip = grained.std.MakeDiff(grained)[0].std.Loop(grained.num_frames)
    else:
        merge_clip, grained = clip, clip.std.MergeDiff(grained, planes)

    if do_protect_chroma:
        neutral_mask = Lanczos.resample(clip, clip.format.replace(subsampling_h=0, subsampling_w=0))

        neutral_mask = norm_expr(
            split(neutral_mask), f'y {neutral} = z {neutral} = and {get_peak_value(clip, range_in=ColorRange.FULL)} 0 ?',
            func=self.__class__.grain
        )

        grained = grained.std.MaskedMerge(merge_clip, neutral_mask, [1, 2])

    if self.luma_scaling is not None:
        mask = adg_mask(clip, self.luma_scaling, func=self.grain)

        grained = merge_clip.std.MaskedMerge(grained, mask)

    return grained

AddNoiseBase

AddNoiseBase(
    strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0),
    sharp: float | ScalerT = Lanczos,
    dynamic: bool = True,
    temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None,
    protect_chroma: bool = True,
    luma_scaling: float | None = None,
    fade_limits: bool | FadeLimits = True,
    *,
    matrix: MatrixT | None = None,
    kernel: KernelT = Catrom,
    neutral_out: bool = False,
    **kwargs: Any
)

Bases: Grainer

Methods:

Attributes:

Source code
 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
def __init__(
    self, strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0), sharp: float | ScalerT = Lanczos,
    dynamic: bool = True, temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None, protect_chroma: bool = True,
    luma_scaling: float | None = None, fade_limits: bool | FadeLimits = True, *,
    matrix: MatrixT | None = None, kernel: KernelT = Catrom, neutral_out: bool = False,
    **kwargs: Any
) -> None:
    super().__init__()

    self.strength = strength
    self.size = size if isinstance(size, tuple) else (size, size)
    self.neutral_out = neutral_out
    self.dynamic = dynamic
    self.postprocess = postprocess
    self.protect_chroma = protect_chroma
    self.luma_scaling = luma_scaling
    self.fade_limits = fade_limits
    self.kwargs = kwargs

    if isinstance(sharp, (float, int)):
        self.scaler: Scaler = BicubicAuto(sharp)
    else:
        self.scaler = Scaler.ensure_obj(sharp, self.__class__)

    if isinstance(temporal_average, tuple):
        self.temporal_average, self.temporal_radius = temporal_average
    else:
        self.temporal_average, self.temporal_radius = temporal_average, 1

    self.matrix = Matrix.from_param(matrix, self.__class__)
    self.kernel = Kernel.ensure_obj(kernel, self.__class__)

dynamic instance-attribute

dynamic = dynamic

fade_limits instance-attribute

fade_limits = fade_limits

kernel instance-attribute

kernel = ensure_obj(kernel, __class__)

kwargs instance-attribute

kwargs = kwargs

luma_scaling instance-attribute

luma_scaling = luma_scaling

matrix instance-attribute

matrix = from_param(matrix, __class__)

neutral_out instance-attribute

neutral_out = neutral_out

postprocess instance-attribute

postprocess = postprocess

protect_chroma instance-attribute

protect_chroma = protect_chroma

scaler instance-attribute

scaler: Scaler = BicubicAuto(sharp)

size instance-attribute

size = size if isinstance(size, tuple) else (size, size)

strength instance-attribute

strength = strength

grain

grain(
    clip: VideoNode,
    strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None,
    **kwargs: Any
) -> VideoNode
Source code
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
@inject_self.init_kwargs.clean
def grain(
    self, clip: vs.VideoNode, strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None, **kwargs: Any
) -> vs.VideoNode:
    assert clip.format

    kwargs = self._get_kw(kwargs)

    if strength is None:
        strength = self.strength

    dynamic = fallback(dynamic, self.dynamic)
    strength = strength if isinstance(strength, tuple) else (
        strength, strength if clip.format.num_planes > 1 else 0.0
    )

    if max(strength) <= 0.0:
        return clip

    if strength[0] <= 0.0 and strength[1] > 0.0:
        planes: PlanesT = [1, 2]
    elif strength[0] > 0.0 and strength[1] <= 0.0:
        planes = 0
    else:
        planes = None

    do_taverage = (
        dynamic
        and self.temporal_average > 0 and self.temporal_radius > 0
        and (clip.num_frames > self.temporal_radius * 2)
    )
    do_protect_chroma = self.protect_chroma and strength[1] > 0.0 and clip.format.color_family is vs.YUV
    input_dep = self._is_input_dependent(clip, **kwargs)

    def _wrap_implementation(clip: vs.VideoNode, neutral_out: bool) -> vs.VideoNode:
        if input_dep and do_taverage and not kwargs.get('unsafe_graining', False):
            raise CustomValueError(
                'You can\'t have temporal averaging with input dependent graining as it will create ghosting!'
            )

        if neutral_out and not input_dep:
            length = clip.num_frames + ((self.temporal_radius * 2) if do_taverage else 0)
            base_clip = clip.std.BlankClip(length=length, color=get_neutral_values(clip))
        elif do_taverage:
            base_clip = (clip[0] * self.temporal_radius) + clip + (clip[-1] * self.temporal_radius)
        else:
            base_clip = clip

        def _try_grain(src: vs.VideoNode, stre: tuple[float, float] = strength, **args: Any) -> vs.VideoNode:
            args = kwargs | dict(strength=stre, dynamic=dynamic) | args
            try:
                self._check_input(src, **args)
                grained = self._perform_graining(src, **args)
            except NotImplementedError as e:
                reason, *_ = map(str, e.args)

                if reason == 'dynamic-only':
                    grained = _try_grain(src[src.num_frames // 2], dynamic=True)
                elif reason.startswith('bad-depth'):
                    good_depth = int(reason.split('-')[-1])
                    grained = _try_grain(depth(src, good_depth))
                    grained = depth(grained, src)
                elif reason == 'single-plane':
                    str_luma, str_chroma = strength

                    if str_luma > 0 and str_chroma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )
                    elif str_luma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            src
                        )
                    elif str_chroma > 0:
                        return join(
                            src,
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )

                    return src
                else:
                    raise e

            return grained

        grained = _try_grain(base_clip)

        if input_dep and neutral_out:
            grained = clip.std.MakeDiff(grained)

        return grained

    if (
        self.size == (1.0, 1.0) and not do_taverage and not self.postprocess
        and not do_protect_chroma and self.luma_scaling is None and not self.fade_limits
    ):
        return _wrap_implementation(clip, self.neutral_out)

    (sizex, sizey), mod = self.size, max(clip.format.subsampling_w, clip.format.subsampling_h) << 1
    sx, sy = mod_x(clip.width / sizex, mod), mod_x(clip.height / sizey, mod)

    if (sx, sy) != (clip.width, clip.height):
        sxa, sya = mod_x((clip.width + sx) / 2, mod), mod_x((clip.height + sy) / 2, mod)

        grained = _wrap_implementation(self.scaler.scale(clip, sx, sy), True)

        # If the scale is too big, we need to scale it in two passes, else the window
        # will be too big and the grain will be dampened down too much
        if max(self.size) > 1.5:
            grained = self.scaler.scale(grained, sxa, sya)

        grained = self.scaler.scale(grained, clip.width, clip.height)
    else:
        grained = _wrap_implementation(clip, True)

    if do_taverage:
        average = BlurMatrix.MEAN(taps=self.temporal_radius, mode=ConvMode.TEMPORAL)(grained)
        grained = grained.std.Merge(average, self.temporal_average)
        grained = grained[self.temporal_radius:-self.temporal_radius]

    if self.fade_limits:
        low, high = (None, None) if self.fade_limits is True else self.fade_limits

        low = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(low, 16)))
        ]

        high = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(high, [235, 240])))
        ]

        if complexpr_available:
            limit_expr = 'y neutral - abs A! x A@ - {low} < x A@ + {high} > or neutral y ?'
        else:
            limit_expr = 'x y neutral - abs - {low} < x y neutral - abs + {high} > or neutral y ?'

        grained = norm_expr([clip, grained], limit_expr, planes, low=low, high=high, func=self.__class__.grain)

    if self.postprocess:
        for postprocess in cast(list[GrainPostProcessT], to_arr(self.postprocess)):
            if callable(postprocess):
                try:
                    postprocess = postprocess(grained, clip)
                except TypeError:
                    postprocess = postprocess(grained)

            if isinstance(postprocess, vs.VideoNode):
                grained = postprocess
            else:
                if isinstance(postprocess, GrainPP):
                    postprocess, ppkwargs = postprocess.value, postprocess.kwargs
                else:
                    ppkwargs = KwargsT()

                # fuck importing re
                uses_y = ' y ' in postprocess or postprocess.startswith('y ') or postprocess.endswith(' y')  #type: ignore
                grained = norm_expr(
                    [grained, clip] if uses_y else grained, postprocess, **ppkwargs, func=self.__class__.grain
                )

    neutral = get_neutral_value(clip)

    if self.neutral_out:
        merge_clip = grained.std.MakeDiff(grained)[0].std.Loop(grained.num_frames)
    else:
        merge_clip, grained = clip, clip.std.MergeDiff(grained, planes)

    if do_protect_chroma:
        neutral_mask = Lanczos.resample(clip, clip.format.replace(subsampling_h=0, subsampling_w=0))

        neutral_mask = norm_expr(
            split(neutral_mask), f'y {neutral} = z {neutral} = and {get_peak_value(clip, range_in=ColorRange.FULL)} 0 ?',
            func=self.__class__.grain
        )

        grained = grained.std.MaskedMerge(merge_clip, neutral_mask, [1, 2])

    if self.luma_scaling is not None:
        mask = adg_mask(clip, self.luma_scaling, func=self.grain)

        grained = merge_clip.std.MaskedMerge(grained, mask)

    return grained

ChickenDream

ChickenDream(
    strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0),
    sharp: float | ScalerT = Lanczos,
    dynamic: bool = True,
    temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None,
    protect_chroma: bool = True,
    luma_scaling: float | None = None,
    fade_limits: bool | FadeLimits = True,
    *,
    res: int = 1024,
    dev: float = 0.0,
    gamma: float = 1.0,
    matrix: MatrixT | None = None,
    kernel: KernelT = Catrom,
    neutral_out: bool = False,
    **kwargs: Any
)

Bases: ChickenDreamBox

Classes:

Methods:

Attributes:

Source code
509
510
511
512
513
514
515
516
517
518
519
520
521
def __init__(
    self, strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0), sharp: float | ScalerT = Lanczos,
    dynamic: bool = True, temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None, protect_chroma: bool = True,
    luma_scaling: float | None = None, fade_limits: bool | FadeLimits = True,
    *, res: int = 1024, dev: float = 0.0, gamma: float = 1.0,
    matrix: MatrixT | None = None, kernel: KernelT = Catrom, neutral_out: bool = False, **kwargs: Any
) -> None:
    super().__init__(
        strength, True, size, sharp, dynamic, temporal_average, postprocess, protect_chroma, luma_scaling,
        fade_limits, matrix=matrix, kernel=kernel, neutral_out=neutral_out, res=res, dev=dev, gamma=gamma, **kwargs
    )

draft instance-attribute

draft = draft

dynamic instance-attribute

dynamic = dynamic

fade_limits instance-attribute

fade_limits = fade_limits

gamma instance-attribute

gamma = gamma

kernel instance-attribute

kernel = ensure_obj(kernel, __class__)

kwargs instance-attribute

kwargs = kwargs

luma_scaling instance-attribute

luma_scaling = luma_scaling

matrix instance-attribute

matrix = from_param(matrix, __class__)

neutral_out instance-attribute

neutral_out = neutral_out

postprocess instance-attribute

postprocess = postprocess

protect_chroma instance-attribute

protect_chroma = protect_chroma

scaler instance-attribute

scaler: Scaler = BicubicAuto(sharp)

size instance-attribute

size = size if isinstance(size, tuple) else (size, size)

strength instance-attribute

strength = strength

BOX

BOX(
    strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0),
    sharp: float | ScalerT = Lanczos,
    dynamic: bool = True,
    temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None,
    protect_chroma: bool = True,
    luma_scaling: float | None = None,
    fade_limits: bool | FadeLimits = True,
    *,
    res: int = 1024,
    dev: float = 0.0,
    gamma: float = 1.0,
    matrix: MatrixT | None = None,
    kernel: KernelT = Catrom,
    neutral_out: bool = False,
    **kwargs: Any
)

Bases: ChickenDreamBox

Methods:

Attributes:

Source code
509
510
511
512
513
514
515
516
517
518
519
520
521
def __init__(
    self, strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0), sharp: float | ScalerT = Lanczos,
    dynamic: bool = True, temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None, protect_chroma: bool = True,
    luma_scaling: float | None = None, fade_limits: bool | FadeLimits = True,
    *, res: int = 1024, dev: float = 0.0, gamma: float = 1.0,
    matrix: MatrixT | None = None, kernel: KernelT = Catrom, neutral_out: bool = False, **kwargs: Any
) -> None:
    super().__init__(
        strength, True, size, sharp, dynamic, temporal_average, postprocess, protect_chroma, luma_scaling,
        fade_limits, matrix=matrix, kernel=kernel, neutral_out=neutral_out, res=res, dev=dev, gamma=gamma, **kwargs
    )

draft instance-attribute

draft = draft

dynamic instance-attribute

dynamic = dynamic

fade_limits instance-attribute

fade_limits = fade_limits

gamma instance-attribute

gamma = gamma

kernel instance-attribute

kernel = ensure_obj(kernel, __class__)

kwargs instance-attribute

kwargs = kwargs

luma_scaling instance-attribute

luma_scaling = luma_scaling

matrix instance-attribute

matrix = from_param(matrix, __class__)

neutral_out instance-attribute

neutral_out = neutral_out

postprocess instance-attribute

postprocess = postprocess

protect_chroma instance-attribute

protect_chroma = protect_chroma

scaler instance-attribute

scaler: Scaler = BicubicAuto(sharp)

size instance-attribute

size = size if isinstance(size, tuple) else (size, size)

strength instance-attribute

strength = strength

grain

grain(
    clip: VideoNode,
    strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None,
    **kwargs: Any
) -> VideoNode
Source code
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
@inject_self.init_kwargs.clean
def grain(
    self, clip: vs.VideoNode, strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None, **kwargs: Any
) -> vs.VideoNode:
    assert clip.format

    kwargs = self._get_kw(kwargs)

    if strength is None:
        strength = self.strength

    dynamic = fallback(dynamic, self.dynamic)
    strength = strength if isinstance(strength, tuple) else (
        strength, strength if clip.format.num_planes > 1 else 0.0
    )

    if max(strength) <= 0.0:
        return clip

    if strength[0] <= 0.0 and strength[1] > 0.0:
        planes: PlanesT = [1, 2]
    elif strength[0] > 0.0 and strength[1] <= 0.0:
        planes = 0
    else:
        planes = None

    do_taverage = (
        dynamic
        and self.temporal_average > 0 and self.temporal_radius > 0
        and (clip.num_frames > self.temporal_radius * 2)
    )
    do_protect_chroma = self.protect_chroma and strength[1] > 0.0 and clip.format.color_family is vs.YUV
    input_dep = self._is_input_dependent(clip, **kwargs)

    def _wrap_implementation(clip: vs.VideoNode, neutral_out: bool) -> vs.VideoNode:
        if input_dep and do_taverage and not kwargs.get('unsafe_graining', False):
            raise CustomValueError(
                'You can\'t have temporal averaging with input dependent graining as it will create ghosting!'
            )

        if neutral_out and not input_dep:
            length = clip.num_frames + ((self.temporal_radius * 2) if do_taverage else 0)
            base_clip = clip.std.BlankClip(length=length, color=get_neutral_values(clip))
        elif do_taverage:
            base_clip = (clip[0] * self.temporal_radius) + clip + (clip[-1] * self.temporal_radius)
        else:
            base_clip = clip

        def _try_grain(src: vs.VideoNode, stre: tuple[float, float] = strength, **args: Any) -> vs.VideoNode:
            args = kwargs | dict(strength=stre, dynamic=dynamic) | args
            try:
                self._check_input(src, **args)
                grained = self._perform_graining(src, **args)
            except NotImplementedError as e:
                reason, *_ = map(str, e.args)

                if reason == 'dynamic-only':
                    grained = _try_grain(src[src.num_frames // 2], dynamic=True)
                elif reason.startswith('bad-depth'):
                    good_depth = int(reason.split('-')[-1])
                    grained = _try_grain(depth(src, good_depth))
                    grained = depth(grained, src)
                elif reason == 'single-plane':
                    str_luma, str_chroma = strength

                    if str_luma > 0 and str_chroma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )
                    elif str_luma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            src
                        )
                    elif str_chroma > 0:
                        return join(
                            src,
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )

                    return src
                else:
                    raise e

            return grained

        grained = _try_grain(base_clip)

        if input_dep and neutral_out:
            grained = clip.std.MakeDiff(grained)

        return grained

    if (
        self.size == (1.0, 1.0) and not do_taverage and not self.postprocess
        and not do_protect_chroma and self.luma_scaling is None and not self.fade_limits
    ):
        return _wrap_implementation(clip, self.neutral_out)

    (sizex, sizey), mod = self.size, max(clip.format.subsampling_w, clip.format.subsampling_h) << 1
    sx, sy = mod_x(clip.width / sizex, mod), mod_x(clip.height / sizey, mod)

    if (sx, sy) != (clip.width, clip.height):
        sxa, sya = mod_x((clip.width + sx) / 2, mod), mod_x((clip.height + sy) / 2, mod)

        grained = _wrap_implementation(self.scaler.scale(clip, sx, sy), True)

        # If the scale is too big, we need to scale it in two passes, else the window
        # will be too big and the grain will be dampened down too much
        if max(self.size) > 1.5:
            grained = self.scaler.scale(grained, sxa, sya)

        grained = self.scaler.scale(grained, clip.width, clip.height)
    else:
        grained = _wrap_implementation(clip, True)

    if do_taverage:
        average = BlurMatrix.MEAN(taps=self.temporal_radius, mode=ConvMode.TEMPORAL)(grained)
        grained = grained.std.Merge(average, self.temporal_average)
        grained = grained[self.temporal_radius:-self.temporal_radius]

    if self.fade_limits:
        low, high = (None, None) if self.fade_limits is True else self.fade_limits

        low = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(low, 16)))
        ]

        high = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(high, [235, 240])))
        ]

        if complexpr_available:
            limit_expr = 'y neutral - abs A! x A@ - {low} < x A@ + {high} > or neutral y ?'
        else:
            limit_expr = 'x y neutral - abs - {low} < x y neutral - abs + {high} > or neutral y ?'

        grained = norm_expr([clip, grained], limit_expr, planes, low=low, high=high, func=self.__class__.grain)

    if self.postprocess:
        for postprocess in cast(list[GrainPostProcessT], to_arr(self.postprocess)):
            if callable(postprocess):
                try:
                    postprocess = postprocess(grained, clip)
                except TypeError:
                    postprocess = postprocess(grained)

            if isinstance(postprocess, vs.VideoNode):
                grained = postprocess
            else:
                if isinstance(postprocess, GrainPP):
                    postprocess, ppkwargs = postprocess.value, postprocess.kwargs
                else:
                    ppkwargs = KwargsT()

                # fuck importing re
                uses_y = ' y ' in postprocess or postprocess.startswith('y ') or postprocess.endswith(' y')  #type: ignore
                grained = norm_expr(
                    [grained, clip] if uses_y else grained, postprocess, **ppkwargs, func=self.__class__.grain
                )

    neutral = get_neutral_value(clip)

    if self.neutral_out:
        merge_clip = grained.std.MakeDiff(grained)[0].std.Loop(grained.num_frames)
    else:
        merge_clip, grained = clip, clip.std.MergeDiff(grained, planes)

    if do_protect_chroma:
        neutral_mask = Lanczos.resample(clip, clip.format.replace(subsampling_h=0, subsampling_w=0))

        neutral_mask = norm_expr(
            split(neutral_mask), f'y {neutral} = z {neutral} = and {get_peak_value(clip, range_in=ColorRange.FULL)} 0 ?',
            func=self.__class__.grain
        )

        grained = grained.std.MaskedMerge(merge_clip, neutral_mask, [1, 2])

    if self.luma_scaling is not None:
        mask = adg_mask(clip, self.luma_scaling, func=self.grain)

        grained = merge_clip.std.MaskedMerge(grained, mask)

    return grained

GAUSS

GAUSS(
    strength: float | tuple[float, float] = 0.35,
    size: float | tuple[float, float] = (1.0, 1.0),
    sharp: float | ScalerT = Lanczos,
    dynamic: bool = True,
    temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None,
    protect_chroma: bool = True,
    luma_scaling: float | None = None,
    fade_limits: bool | FadeLimits = True,
    *,
    rad: float = 0.25,
    res: int = 1024,
    dev: float = 0.0,
    gamma: float = 1.0,
    matrix: MatrixT | None = None,
    kernel: KernelT = Catrom,
    neutral_out: bool = False,
    **kwargs: Any
)

Bases: ChickenDreamGauss

Methods:

Attributes:

Source code
528
529
530
531
532
533
534
535
536
537
538
539
540
541
def __init__(
    self, strength: float | tuple[float, float] = 0.35,
    size: float | tuple[float, float] = (1.0, 1.0), sharp: float | ScalerT = Lanczos,
    dynamic: bool = True, temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None, protect_chroma: bool = True,
    luma_scaling: float | None = None, fade_limits: bool | FadeLimits = True,
    *, rad: float = 0.25, res: int = 1024, dev: float = 0.0, gamma: float = 1.0,
    matrix: MatrixT | None = None, kernel: KernelT = Catrom, neutral_out: bool = False, **kwargs: Any
) -> None:
    super().__init__(
        strength, False, size, sharp, dynamic, temporal_average, postprocess, protect_chroma, luma_scaling,
        fade_limits, matrix=matrix, kernel=kernel, neutral_out=neutral_out, rad=rad, res=res, dev=dev,
        gamma=gamma, **kwargs
    )

draft instance-attribute

draft = draft

dynamic instance-attribute

dynamic = dynamic

fade_limits instance-attribute

fade_limits = fade_limits

gamma instance-attribute

gamma = gamma

kernel instance-attribute

kernel = ensure_obj(kernel, __class__)

kwargs instance-attribute

kwargs = kwargs

luma_scaling instance-attribute

luma_scaling = luma_scaling

matrix instance-attribute

matrix = from_param(matrix, __class__)

neutral_out instance-attribute

neutral_out = neutral_out

postprocess instance-attribute

postprocess = postprocess

protect_chroma instance-attribute

protect_chroma = protect_chroma

scaler instance-attribute

scaler: Scaler = BicubicAuto(sharp)

size instance-attribute

size = size if isinstance(size, tuple) else (size, size)

strength instance-attribute

strength = strength

grain

grain(
    clip: VideoNode,
    strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None,
    **kwargs: Any
) -> VideoNode
Source code
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
@inject_self.init_kwargs.clean
def grain(
    self, clip: vs.VideoNode, strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None, **kwargs: Any
) -> vs.VideoNode:
    assert clip.format

    kwargs = self._get_kw(kwargs)

    if strength is None:
        strength = self.strength

    dynamic = fallback(dynamic, self.dynamic)
    strength = strength if isinstance(strength, tuple) else (
        strength, strength if clip.format.num_planes > 1 else 0.0
    )

    if max(strength) <= 0.0:
        return clip

    if strength[0] <= 0.0 and strength[1] > 0.0:
        planes: PlanesT = [1, 2]
    elif strength[0] > 0.0 and strength[1] <= 0.0:
        planes = 0
    else:
        planes = None

    do_taverage = (
        dynamic
        and self.temporal_average > 0 and self.temporal_radius > 0
        and (clip.num_frames > self.temporal_radius * 2)
    )
    do_protect_chroma = self.protect_chroma and strength[1] > 0.0 and clip.format.color_family is vs.YUV
    input_dep = self._is_input_dependent(clip, **kwargs)

    def _wrap_implementation(clip: vs.VideoNode, neutral_out: bool) -> vs.VideoNode:
        if input_dep and do_taverage and not kwargs.get('unsafe_graining', False):
            raise CustomValueError(
                'You can\'t have temporal averaging with input dependent graining as it will create ghosting!'
            )

        if neutral_out and not input_dep:
            length = clip.num_frames + ((self.temporal_radius * 2) if do_taverage else 0)
            base_clip = clip.std.BlankClip(length=length, color=get_neutral_values(clip))
        elif do_taverage:
            base_clip = (clip[0] * self.temporal_radius) + clip + (clip[-1] * self.temporal_radius)
        else:
            base_clip = clip

        def _try_grain(src: vs.VideoNode, stre: tuple[float, float] = strength, **args: Any) -> vs.VideoNode:
            args = kwargs | dict(strength=stre, dynamic=dynamic) | args
            try:
                self._check_input(src, **args)
                grained = self._perform_graining(src, **args)
            except NotImplementedError as e:
                reason, *_ = map(str, e.args)

                if reason == 'dynamic-only':
                    grained = _try_grain(src[src.num_frames // 2], dynamic=True)
                elif reason.startswith('bad-depth'):
                    good_depth = int(reason.split('-')[-1])
                    grained = _try_grain(depth(src, good_depth))
                    grained = depth(grained, src)
                elif reason == 'single-plane':
                    str_luma, str_chroma = strength

                    if str_luma > 0 and str_chroma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )
                    elif str_luma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            src
                        )
                    elif str_chroma > 0:
                        return join(
                            src,
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )

                    return src
                else:
                    raise e

            return grained

        grained = _try_grain(base_clip)

        if input_dep and neutral_out:
            grained = clip.std.MakeDiff(grained)

        return grained

    if (
        self.size == (1.0, 1.0) and not do_taverage and not self.postprocess
        and not do_protect_chroma and self.luma_scaling is None and not self.fade_limits
    ):
        return _wrap_implementation(clip, self.neutral_out)

    (sizex, sizey), mod = self.size, max(clip.format.subsampling_w, clip.format.subsampling_h) << 1
    sx, sy = mod_x(clip.width / sizex, mod), mod_x(clip.height / sizey, mod)

    if (sx, sy) != (clip.width, clip.height):
        sxa, sya = mod_x((clip.width + sx) / 2, mod), mod_x((clip.height + sy) / 2, mod)

        grained = _wrap_implementation(self.scaler.scale(clip, sx, sy), True)

        # If the scale is too big, we need to scale it in two passes, else the window
        # will be too big and the grain will be dampened down too much
        if max(self.size) > 1.5:
            grained = self.scaler.scale(grained, sxa, sya)

        grained = self.scaler.scale(grained, clip.width, clip.height)
    else:
        grained = _wrap_implementation(clip, True)

    if do_taverage:
        average = BlurMatrix.MEAN(taps=self.temporal_radius, mode=ConvMode.TEMPORAL)(grained)
        grained = grained.std.Merge(average, self.temporal_average)
        grained = grained[self.temporal_radius:-self.temporal_radius]

    if self.fade_limits:
        low, high = (None, None) if self.fade_limits is True else self.fade_limits

        low = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(low, 16)))
        ]

        high = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(high, [235, 240])))
        ]

        if complexpr_available:
            limit_expr = 'y neutral - abs A! x A@ - {low} < x A@ + {high} > or neutral y ?'
        else:
            limit_expr = 'x y neutral - abs - {low} < x y neutral - abs + {high} > or neutral y ?'

        grained = norm_expr([clip, grained], limit_expr, planes, low=low, high=high, func=self.__class__.grain)

    if self.postprocess:
        for postprocess in cast(list[GrainPostProcessT], to_arr(self.postprocess)):
            if callable(postprocess):
                try:
                    postprocess = postprocess(grained, clip)
                except TypeError:
                    postprocess = postprocess(grained)

            if isinstance(postprocess, vs.VideoNode):
                grained = postprocess
            else:
                if isinstance(postprocess, GrainPP):
                    postprocess, ppkwargs = postprocess.value, postprocess.kwargs
                else:
                    ppkwargs = KwargsT()

                # fuck importing re
                uses_y = ' y ' in postprocess or postprocess.startswith('y ') or postprocess.endswith(' y')  #type: ignore
                grained = norm_expr(
                    [grained, clip] if uses_y else grained, postprocess, **ppkwargs, func=self.__class__.grain
                )

    neutral = get_neutral_value(clip)

    if self.neutral_out:
        merge_clip = grained.std.MakeDiff(grained)[0].std.Loop(grained.num_frames)
    else:
        merge_clip, grained = clip, clip.std.MergeDiff(grained, planes)

    if do_protect_chroma:
        neutral_mask = Lanczos.resample(clip, clip.format.replace(subsampling_h=0, subsampling_w=0))

        neutral_mask = norm_expr(
            split(neutral_mask), f'y {neutral} = z {neutral} = and {get_peak_value(clip, range_in=ColorRange.FULL)} 0 ?',
            func=self.__class__.grain
        )

        grained = grained.std.MaskedMerge(merge_clip, neutral_mask, [1, 2])

    if self.luma_scaling is not None:
        mask = adg_mask(clip, self.luma_scaling, func=self.grain)

        grained = merge_clip.std.MaskedMerge(grained, mask)

    return grained

grain

grain(
    clip: VideoNode,
    strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None,
    **kwargs: Any
) -> VideoNode
Source code
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
@inject_self.init_kwargs.clean
def grain(
    self, clip: vs.VideoNode, strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None, **kwargs: Any
) -> vs.VideoNode:
    assert clip.format

    kwargs = self._get_kw(kwargs)

    if strength is None:
        strength = self.strength

    dynamic = fallback(dynamic, self.dynamic)
    strength = strength if isinstance(strength, tuple) else (
        strength, strength if clip.format.num_planes > 1 else 0.0
    )

    if max(strength) <= 0.0:
        return clip

    if strength[0] <= 0.0 and strength[1] > 0.0:
        planes: PlanesT = [1, 2]
    elif strength[0] > 0.0 and strength[1] <= 0.0:
        planes = 0
    else:
        planes = None

    do_taverage = (
        dynamic
        and self.temporal_average > 0 and self.temporal_radius > 0
        and (clip.num_frames > self.temporal_radius * 2)
    )
    do_protect_chroma = self.protect_chroma and strength[1] > 0.0 and clip.format.color_family is vs.YUV
    input_dep = self._is_input_dependent(clip, **kwargs)

    def _wrap_implementation(clip: vs.VideoNode, neutral_out: bool) -> vs.VideoNode:
        if input_dep and do_taverage and not kwargs.get('unsafe_graining', False):
            raise CustomValueError(
                'You can\'t have temporal averaging with input dependent graining as it will create ghosting!'
            )

        if neutral_out and not input_dep:
            length = clip.num_frames + ((self.temporal_radius * 2) if do_taverage else 0)
            base_clip = clip.std.BlankClip(length=length, color=get_neutral_values(clip))
        elif do_taverage:
            base_clip = (clip[0] * self.temporal_radius) + clip + (clip[-1] * self.temporal_radius)
        else:
            base_clip = clip

        def _try_grain(src: vs.VideoNode, stre: tuple[float, float] = strength, **args: Any) -> vs.VideoNode:
            args = kwargs | dict(strength=stre, dynamic=dynamic) | args
            try:
                self._check_input(src, **args)
                grained = self._perform_graining(src, **args)
            except NotImplementedError as e:
                reason, *_ = map(str, e.args)

                if reason == 'dynamic-only':
                    grained = _try_grain(src[src.num_frames // 2], dynamic=True)
                elif reason.startswith('bad-depth'):
                    good_depth = int(reason.split('-')[-1])
                    grained = _try_grain(depth(src, good_depth))
                    grained = depth(grained, src)
                elif reason == 'single-plane':
                    str_luma, str_chroma = strength

                    if str_luma > 0 and str_chroma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )
                    elif str_luma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            src
                        )
                    elif str_chroma > 0:
                        return join(
                            src,
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )

                    return src
                else:
                    raise e

            return grained

        grained = _try_grain(base_clip)

        if input_dep and neutral_out:
            grained = clip.std.MakeDiff(grained)

        return grained

    if (
        self.size == (1.0, 1.0) and not do_taverage and not self.postprocess
        and not do_protect_chroma and self.luma_scaling is None and not self.fade_limits
    ):
        return _wrap_implementation(clip, self.neutral_out)

    (sizex, sizey), mod = self.size, max(clip.format.subsampling_w, clip.format.subsampling_h) << 1
    sx, sy = mod_x(clip.width / sizex, mod), mod_x(clip.height / sizey, mod)

    if (sx, sy) != (clip.width, clip.height):
        sxa, sya = mod_x((clip.width + sx) / 2, mod), mod_x((clip.height + sy) / 2, mod)

        grained = _wrap_implementation(self.scaler.scale(clip, sx, sy), True)

        # If the scale is too big, we need to scale it in two passes, else the window
        # will be too big and the grain will be dampened down too much
        if max(self.size) > 1.5:
            grained = self.scaler.scale(grained, sxa, sya)

        grained = self.scaler.scale(grained, clip.width, clip.height)
    else:
        grained = _wrap_implementation(clip, True)

    if do_taverage:
        average = BlurMatrix.MEAN(taps=self.temporal_radius, mode=ConvMode.TEMPORAL)(grained)
        grained = grained.std.Merge(average, self.temporal_average)
        grained = grained[self.temporal_radius:-self.temporal_radius]

    if self.fade_limits:
        low, high = (None, None) if self.fade_limits is True else self.fade_limits

        low = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(low, 16)))
        ]

        high = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(high, [235, 240])))
        ]

        if complexpr_available:
            limit_expr = 'y neutral - abs A! x A@ - {low} < x A@ + {high} > or neutral y ?'
        else:
            limit_expr = 'x y neutral - abs - {low} < x y neutral - abs + {high} > or neutral y ?'

        grained = norm_expr([clip, grained], limit_expr, planes, low=low, high=high, func=self.__class__.grain)

    if self.postprocess:
        for postprocess in cast(list[GrainPostProcessT], to_arr(self.postprocess)):
            if callable(postprocess):
                try:
                    postprocess = postprocess(grained, clip)
                except TypeError:
                    postprocess = postprocess(grained)

            if isinstance(postprocess, vs.VideoNode):
                grained = postprocess
            else:
                if isinstance(postprocess, GrainPP):
                    postprocess, ppkwargs = postprocess.value, postprocess.kwargs
                else:
                    ppkwargs = KwargsT()

                # fuck importing re
                uses_y = ' y ' in postprocess or postprocess.startswith('y ') or postprocess.endswith(' y')  #type: ignore
                grained = norm_expr(
                    [grained, clip] if uses_y else grained, postprocess, **ppkwargs, func=self.__class__.grain
                )

    neutral = get_neutral_value(clip)

    if self.neutral_out:
        merge_clip = grained.std.MakeDiff(grained)[0].std.Loop(grained.num_frames)
    else:
        merge_clip, grained = clip, clip.std.MergeDiff(grained, planes)

    if do_protect_chroma:
        neutral_mask = Lanczos.resample(clip, clip.format.replace(subsampling_h=0, subsampling_w=0))

        neutral_mask = norm_expr(
            split(neutral_mask), f'y {neutral} = z {neutral} = and {get_peak_value(clip, range_in=ColorRange.FULL)} 0 ?',
            func=self.__class__.grain
        )

        grained = grained.std.MaskedMerge(merge_clip, neutral_mask, [1, 2])

    if self.luma_scaling is not None:
        mask = adg_mask(clip, self.luma_scaling, func=self.grain)

        grained = merge_clip.std.MaskedMerge(grained, mask)

    return grained

ChickenDreamBase

ChickenDreamBase(
    strength: float | tuple[float, float],
    draft: bool,
    size: float | tuple[float, float] = (1.0, 1.0),
    sharp: float | ScalerT = Lanczos,
    dynamic: bool = True,
    temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None,
    protect_chroma: bool = True,
    luma_scaling: float | None = None,
    fade_limits: bool | FadeLimits = True,
    *,
    rad: float = 0.25,
    res: int = 1024,
    dev: float = 0.0,
    gamma: float = 1.0,
    matrix: MatrixT | None = None,
    kernel: KernelT = Catrom,
    neutral_out: bool = False,
    **kwargs: Any
)

Bases: LinearLightGrainer

chkdr.grain plugin. https://github.com/EleonoreMizo/chickendream

Methods:

Attributes:

Source code
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
def __init__(
    self, strength: float | tuple[float, float], draft: bool,
    size: float | tuple[float, float] = (1.0, 1.0), sharp: float | ScalerT = Lanczos,
    dynamic: bool = True, temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None, protect_chroma: bool = True,
    luma_scaling: float | None = None, fade_limits: bool | FadeLimits = True, *,
    rad: float = 0.25, res: int = 1024, dev: float = 0.0, gamma: float = 1.0,
    matrix: MatrixT | None = None, kernel: KernelT = Catrom, neutral_out: bool = False, **kwargs: Any
) -> None:
    super().__init__(
        strength, size, sharp, dynamic, temporal_average, postprocess, protect_chroma, luma_scaling, fade_limits,
        matrix=matrix, kernel=kernel, neutral_out=neutral_out, rad=rad, res=res, dev=dev, gamma=gamma, **kwargs
    )

    self.draft = draft

draft instance-attribute

draft = draft

dynamic instance-attribute

dynamic = dynamic

fade_limits instance-attribute

fade_limits = fade_limits

gamma instance-attribute

gamma = gamma

kernel instance-attribute

kernel = ensure_obj(kernel, __class__)

kwargs instance-attribute

kwargs = kwargs

luma_scaling instance-attribute

luma_scaling = luma_scaling

matrix instance-attribute

matrix = from_param(matrix, __class__)

neutral_out instance-attribute

neutral_out = neutral_out

postprocess instance-attribute

postprocess = postprocess

protect_chroma instance-attribute

protect_chroma = protect_chroma

scaler instance-attribute

scaler: Scaler = BicubicAuto(sharp)

size instance-attribute

size = size if isinstance(size, tuple) else (size, size)

strength instance-attribute

strength = strength

grain

grain(
    clip: VideoNode,
    strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None,
    **kwargs: Any
) -> VideoNode
Source code
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
@inject_self.init_kwargs.clean
def grain(
    self, clip: vs.VideoNode, strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None, **kwargs: Any
) -> vs.VideoNode:
    assert clip.format

    kwargs = self._get_kw(kwargs)

    if strength is None:
        strength = self.strength

    dynamic = fallback(dynamic, self.dynamic)
    strength = strength if isinstance(strength, tuple) else (
        strength, strength if clip.format.num_planes > 1 else 0.0
    )

    if max(strength) <= 0.0:
        return clip

    if strength[0] <= 0.0 and strength[1] > 0.0:
        planes: PlanesT = [1, 2]
    elif strength[0] > 0.0 and strength[1] <= 0.0:
        planes = 0
    else:
        planes = None

    do_taverage = (
        dynamic
        and self.temporal_average > 0 and self.temporal_radius > 0
        and (clip.num_frames > self.temporal_radius * 2)
    )
    do_protect_chroma = self.protect_chroma and strength[1] > 0.0 and clip.format.color_family is vs.YUV
    input_dep = self._is_input_dependent(clip, **kwargs)

    def _wrap_implementation(clip: vs.VideoNode, neutral_out: bool) -> vs.VideoNode:
        if input_dep and do_taverage and not kwargs.get('unsafe_graining', False):
            raise CustomValueError(
                'You can\'t have temporal averaging with input dependent graining as it will create ghosting!'
            )

        if neutral_out and not input_dep:
            length = clip.num_frames + ((self.temporal_radius * 2) if do_taverage else 0)
            base_clip = clip.std.BlankClip(length=length, color=get_neutral_values(clip))
        elif do_taverage:
            base_clip = (clip[0] * self.temporal_radius) + clip + (clip[-1] * self.temporal_radius)
        else:
            base_clip = clip

        def _try_grain(src: vs.VideoNode, stre: tuple[float, float] = strength, **args: Any) -> vs.VideoNode:
            args = kwargs | dict(strength=stre, dynamic=dynamic) | args
            try:
                self._check_input(src, **args)
                grained = self._perform_graining(src, **args)
            except NotImplementedError as e:
                reason, *_ = map(str, e.args)

                if reason == 'dynamic-only':
                    grained = _try_grain(src[src.num_frames // 2], dynamic=True)
                elif reason.startswith('bad-depth'):
                    good_depth = int(reason.split('-')[-1])
                    grained = _try_grain(depth(src, good_depth))
                    grained = depth(grained, src)
                elif reason == 'single-plane':
                    str_luma, str_chroma = strength

                    if str_luma > 0 and str_chroma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )
                    elif str_luma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            src
                        )
                    elif str_chroma > 0:
                        return join(
                            src,
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )

                    return src
                else:
                    raise e

            return grained

        grained = _try_grain(base_clip)

        if input_dep and neutral_out:
            grained = clip.std.MakeDiff(grained)

        return grained

    if (
        self.size == (1.0, 1.0) and not do_taverage and not self.postprocess
        and not do_protect_chroma and self.luma_scaling is None and not self.fade_limits
    ):
        return _wrap_implementation(clip, self.neutral_out)

    (sizex, sizey), mod = self.size, max(clip.format.subsampling_w, clip.format.subsampling_h) << 1
    sx, sy = mod_x(clip.width / sizex, mod), mod_x(clip.height / sizey, mod)

    if (sx, sy) != (clip.width, clip.height):
        sxa, sya = mod_x((clip.width + sx) / 2, mod), mod_x((clip.height + sy) / 2, mod)

        grained = _wrap_implementation(self.scaler.scale(clip, sx, sy), True)

        # If the scale is too big, we need to scale it in two passes, else the window
        # will be too big and the grain will be dampened down too much
        if max(self.size) > 1.5:
            grained = self.scaler.scale(grained, sxa, sya)

        grained = self.scaler.scale(grained, clip.width, clip.height)
    else:
        grained = _wrap_implementation(clip, True)

    if do_taverage:
        average = BlurMatrix.MEAN(taps=self.temporal_radius, mode=ConvMode.TEMPORAL)(grained)
        grained = grained.std.Merge(average, self.temporal_average)
        grained = grained[self.temporal_radius:-self.temporal_radius]

    if self.fade_limits:
        low, high = (None, None) if self.fade_limits is True else self.fade_limits

        low = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(low, 16)))
        ]

        high = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(high, [235, 240])))
        ]

        if complexpr_available:
            limit_expr = 'y neutral - abs A! x A@ - {low} < x A@ + {high} > or neutral y ?'
        else:
            limit_expr = 'x y neutral - abs - {low} < x y neutral - abs + {high} > or neutral y ?'

        grained = norm_expr([clip, grained], limit_expr, planes, low=low, high=high, func=self.__class__.grain)

    if self.postprocess:
        for postprocess in cast(list[GrainPostProcessT], to_arr(self.postprocess)):
            if callable(postprocess):
                try:
                    postprocess = postprocess(grained, clip)
                except TypeError:
                    postprocess = postprocess(grained)

            if isinstance(postprocess, vs.VideoNode):
                grained = postprocess
            else:
                if isinstance(postprocess, GrainPP):
                    postprocess, ppkwargs = postprocess.value, postprocess.kwargs
                else:
                    ppkwargs = KwargsT()

                # fuck importing re
                uses_y = ' y ' in postprocess or postprocess.startswith('y ') or postprocess.endswith(' y')  #type: ignore
                grained = norm_expr(
                    [grained, clip] if uses_y else grained, postprocess, **ppkwargs, func=self.__class__.grain
                )

    neutral = get_neutral_value(clip)

    if self.neutral_out:
        merge_clip = grained.std.MakeDiff(grained)[0].std.Loop(grained.num_frames)
    else:
        merge_clip, grained = clip, clip.std.MergeDiff(grained, planes)

    if do_protect_chroma:
        neutral_mask = Lanczos.resample(clip, clip.format.replace(subsampling_h=0, subsampling_w=0))

        neutral_mask = norm_expr(
            split(neutral_mask), f'y {neutral} = z {neutral} = and {get_peak_value(clip, range_in=ColorRange.FULL)} 0 ?',
            func=self.__class__.grain
        )

        grained = grained.std.MaskedMerge(merge_clip, neutral_mask, [1, 2])

    if self.luma_scaling is not None:
        mask = adg_mask(clip, self.luma_scaling, func=self.grain)

        grained = merge_clip.std.MaskedMerge(grained, mask)

    return grained

ChickenDreamBox

ChickenDreamBox(
    strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0),
    sharp: float | ScalerT = Lanczos,
    dynamic: bool = True,
    temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None,
    protect_chroma: bool = True,
    luma_scaling: float | None = None,
    fade_limits: bool | FadeLimits = True,
    *,
    res: int = 1024,
    dev: float = 0.0,
    gamma: float = 1.0,
    matrix: MatrixT | None = None,
    kernel: KernelT = Catrom,
    neutral_out: bool = False,
    **kwargs: Any
)

Bases: ChickenDreamBase

Methods:

Attributes:

Source code
509
510
511
512
513
514
515
516
517
518
519
520
521
def __init__(
    self, strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0), sharp: float | ScalerT = Lanczos,
    dynamic: bool = True, temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None, protect_chroma: bool = True,
    luma_scaling: float | None = None, fade_limits: bool | FadeLimits = True,
    *, res: int = 1024, dev: float = 0.0, gamma: float = 1.0,
    matrix: MatrixT | None = None, kernel: KernelT = Catrom, neutral_out: bool = False, **kwargs: Any
) -> None:
    super().__init__(
        strength, True, size, sharp, dynamic, temporal_average, postprocess, protect_chroma, luma_scaling,
        fade_limits, matrix=matrix, kernel=kernel, neutral_out=neutral_out, res=res, dev=dev, gamma=gamma, **kwargs
    )

draft instance-attribute

draft = draft

dynamic instance-attribute

dynamic = dynamic

fade_limits instance-attribute

fade_limits = fade_limits

gamma instance-attribute

gamma = gamma

kernel instance-attribute

kernel = ensure_obj(kernel, __class__)

kwargs instance-attribute

kwargs = kwargs

luma_scaling instance-attribute

luma_scaling = luma_scaling

matrix instance-attribute

matrix = from_param(matrix, __class__)

neutral_out instance-attribute

neutral_out = neutral_out

postprocess instance-attribute

postprocess = postprocess

protect_chroma instance-attribute

protect_chroma = protect_chroma

scaler instance-attribute

scaler: Scaler = BicubicAuto(sharp)

size instance-attribute

size = size if isinstance(size, tuple) else (size, size)

strength instance-attribute

strength = strength

grain

grain(
    clip: VideoNode,
    strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None,
    **kwargs: Any
) -> VideoNode
Source code
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
@inject_self.init_kwargs.clean
def grain(
    self, clip: vs.VideoNode, strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None, **kwargs: Any
) -> vs.VideoNode:
    assert clip.format

    kwargs = self._get_kw(kwargs)

    if strength is None:
        strength = self.strength

    dynamic = fallback(dynamic, self.dynamic)
    strength = strength if isinstance(strength, tuple) else (
        strength, strength if clip.format.num_planes > 1 else 0.0
    )

    if max(strength) <= 0.0:
        return clip

    if strength[0] <= 0.0 and strength[1] > 0.0:
        planes: PlanesT = [1, 2]
    elif strength[0] > 0.0 and strength[1] <= 0.0:
        planes = 0
    else:
        planes = None

    do_taverage = (
        dynamic
        and self.temporal_average > 0 and self.temporal_radius > 0
        and (clip.num_frames > self.temporal_radius * 2)
    )
    do_protect_chroma = self.protect_chroma and strength[1] > 0.0 and clip.format.color_family is vs.YUV
    input_dep = self._is_input_dependent(clip, **kwargs)

    def _wrap_implementation(clip: vs.VideoNode, neutral_out: bool) -> vs.VideoNode:
        if input_dep and do_taverage and not kwargs.get('unsafe_graining', False):
            raise CustomValueError(
                'You can\'t have temporal averaging with input dependent graining as it will create ghosting!'
            )

        if neutral_out and not input_dep:
            length = clip.num_frames + ((self.temporal_radius * 2) if do_taverage else 0)
            base_clip = clip.std.BlankClip(length=length, color=get_neutral_values(clip))
        elif do_taverage:
            base_clip = (clip[0] * self.temporal_radius) + clip + (clip[-1] * self.temporal_radius)
        else:
            base_clip = clip

        def _try_grain(src: vs.VideoNode, stre: tuple[float, float] = strength, **args: Any) -> vs.VideoNode:
            args = kwargs | dict(strength=stre, dynamic=dynamic) | args
            try:
                self._check_input(src, **args)
                grained = self._perform_graining(src, **args)
            except NotImplementedError as e:
                reason, *_ = map(str, e.args)

                if reason == 'dynamic-only':
                    grained = _try_grain(src[src.num_frames // 2], dynamic=True)
                elif reason.startswith('bad-depth'):
                    good_depth = int(reason.split('-')[-1])
                    grained = _try_grain(depth(src, good_depth))
                    grained = depth(grained, src)
                elif reason == 'single-plane':
                    str_luma, str_chroma = strength

                    if str_luma > 0 and str_chroma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )
                    elif str_luma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            src
                        )
                    elif str_chroma > 0:
                        return join(
                            src,
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )

                    return src
                else:
                    raise e

            return grained

        grained = _try_grain(base_clip)

        if input_dep and neutral_out:
            grained = clip.std.MakeDiff(grained)

        return grained

    if (
        self.size == (1.0, 1.0) and not do_taverage and not self.postprocess
        and not do_protect_chroma and self.luma_scaling is None and not self.fade_limits
    ):
        return _wrap_implementation(clip, self.neutral_out)

    (sizex, sizey), mod = self.size, max(clip.format.subsampling_w, clip.format.subsampling_h) << 1
    sx, sy = mod_x(clip.width / sizex, mod), mod_x(clip.height / sizey, mod)

    if (sx, sy) != (clip.width, clip.height):
        sxa, sya = mod_x((clip.width + sx) / 2, mod), mod_x((clip.height + sy) / 2, mod)

        grained = _wrap_implementation(self.scaler.scale(clip, sx, sy), True)

        # If the scale is too big, we need to scale it in two passes, else the window
        # will be too big and the grain will be dampened down too much
        if max(self.size) > 1.5:
            grained = self.scaler.scale(grained, sxa, sya)

        grained = self.scaler.scale(grained, clip.width, clip.height)
    else:
        grained = _wrap_implementation(clip, True)

    if do_taverage:
        average = BlurMatrix.MEAN(taps=self.temporal_radius, mode=ConvMode.TEMPORAL)(grained)
        grained = grained.std.Merge(average, self.temporal_average)
        grained = grained[self.temporal_radius:-self.temporal_radius]

    if self.fade_limits:
        low, high = (None, None) if self.fade_limits is True else self.fade_limits

        low = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(low, 16)))
        ]

        high = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(high, [235, 240])))
        ]

        if complexpr_available:
            limit_expr = 'y neutral - abs A! x A@ - {low} < x A@ + {high} > or neutral y ?'
        else:
            limit_expr = 'x y neutral - abs - {low} < x y neutral - abs + {high} > or neutral y ?'

        grained = norm_expr([clip, grained], limit_expr, planes, low=low, high=high, func=self.__class__.grain)

    if self.postprocess:
        for postprocess in cast(list[GrainPostProcessT], to_arr(self.postprocess)):
            if callable(postprocess):
                try:
                    postprocess = postprocess(grained, clip)
                except TypeError:
                    postprocess = postprocess(grained)

            if isinstance(postprocess, vs.VideoNode):
                grained = postprocess
            else:
                if isinstance(postprocess, GrainPP):
                    postprocess, ppkwargs = postprocess.value, postprocess.kwargs
                else:
                    ppkwargs = KwargsT()

                # fuck importing re
                uses_y = ' y ' in postprocess or postprocess.startswith('y ') or postprocess.endswith(' y')  #type: ignore
                grained = norm_expr(
                    [grained, clip] if uses_y else grained, postprocess, **ppkwargs, func=self.__class__.grain
                )

    neutral = get_neutral_value(clip)

    if self.neutral_out:
        merge_clip = grained.std.MakeDiff(grained)[0].std.Loop(grained.num_frames)
    else:
        merge_clip, grained = clip, clip.std.MergeDiff(grained, planes)

    if do_protect_chroma:
        neutral_mask = Lanczos.resample(clip, clip.format.replace(subsampling_h=0, subsampling_w=0))

        neutral_mask = norm_expr(
            split(neutral_mask), f'y {neutral} = z {neutral} = and {get_peak_value(clip, range_in=ColorRange.FULL)} 0 ?',
            func=self.__class__.grain
        )

        grained = grained.std.MaskedMerge(merge_clip, neutral_mask, [1, 2])

    if self.luma_scaling is not None:
        mask = adg_mask(clip, self.luma_scaling, func=self.grain)

        grained = merge_clip.std.MaskedMerge(grained, mask)

    return grained

ChickenDreamGauss

ChickenDreamGauss(
    strength: float | tuple[float, float] = 0.35,
    size: float | tuple[float, float] = (1.0, 1.0),
    sharp: float | ScalerT = Lanczos,
    dynamic: bool = True,
    temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None,
    protect_chroma: bool = True,
    luma_scaling: float | None = None,
    fade_limits: bool | FadeLimits = True,
    *,
    rad: float = 0.25,
    res: int = 1024,
    dev: float = 0.0,
    gamma: float = 1.0,
    matrix: MatrixT | None = None,
    kernel: KernelT = Catrom,
    neutral_out: bool = False,
    **kwargs: Any
)

Bases: ChickenDreamBase

Methods:

Attributes:

Source code
528
529
530
531
532
533
534
535
536
537
538
539
540
541
def __init__(
    self, strength: float | tuple[float, float] = 0.35,
    size: float | tuple[float, float] = (1.0, 1.0), sharp: float | ScalerT = Lanczos,
    dynamic: bool = True, temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None, protect_chroma: bool = True,
    luma_scaling: float | None = None, fade_limits: bool | FadeLimits = True,
    *, rad: float = 0.25, res: int = 1024, dev: float = 0.0, gamma: float = 1.0,
    matrix: MatrixT | None = None, kernel: KernelT = Catrom, neutral_out: bool = False, **kwargs: Any
) -> None:
    super().__init__(
        strength, False, size, sharp, dynamic, temporal_average, postprocess, protect_chroma, luma_scaling,
        fade_limits, matrix=matrix, kernel=kernel, neutral_out=neutral_out, rad=rad, res=res, dev=dev,
        gamma=gamma, **kwargs
    )

draft instance-attribute

draft = draft

dynamic instance-attribute

dynamic = dynamic

fade_limits instance-attribute

fade_limits = fade_limits

gamma instance-attribute

gamma = gamma

kernel instance-attribute

kernel = ensure_obj(kernel, __class__)

kwargs instance-attribute

kwargs = kwargs

luma_scaling instance-attribute

luma_scaling = luma_scaling

matrix instance-attribute

matrix = from_param(matrix, __class__)

neutral_out instance-attribute

neutral_out = neutral_out

postprocess instance-attribute

postprocess = postprocess

protect_chroma instance-attribute

protect_chroma = protect_chroma

scaler instance-attribute

scaler: Scaler = BicubicAuto(sharp)

size instance-attribute

size = size if isinstance(size, tuple) else (size, size)

strength instance-attribute

strength = strength

grain

grain(
    clip: VideoNode,
    strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None,
    **kwargs: Any
) -> VideoNode
Source code
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
@inject_self.init_kwargs.clean
def grain(
    self, clip: vs.VideoNode, strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None, **kwargs: Any
) -> vs.VideoNode:
    assert clip.format

    kwargs = self._get_kw(kwargs)

    if strength is None:
        strength = self.strength

    dynamic = fallback(dynamic, self.dynamic)
    strength = strength if isinstance(strength, tuple) else (
        strength, strength if clip.format.num_planes > 1 else 0.0
    )

    if max(strength) <= 0.0:
        return clip

    if strength[0] <= 0.0 and strength[1] > 0.0:
        planes: PlanesT = [1, 2]
    elif strength[0] > 0.0 and strength[1] <= 0.0:
        planes = 0
    else:
        planes = None

    do_taverage = (
        dynamic
        and self.temporal_average > 0 and self.temporal_radius > 0
        and (clip.num_frames > self.temporal_radius * 2)
    )
    do_protect_chroma = self.protect_chroma and strength[1] > 0.0 and clip.format.color_family is vs.YUV
    input_dep = self._is_input_dependent(clip, **kwargs)

    def _wrap_implementation(clip: vs.VideoNode, neutral_out: bool) -> vs.VideoNode:
        if input_dep and do_taverage and not kwargs.get('unsafe_graining', False):
            raise CustomValueError(
                'You can\'t have temporal averaging with input dependent graining as it will create ghosting!'
            )

        if neutral_out and not input_dep:
            length = clip.num_frames + ((self.temporal_radius * 2) if do_taverage else 0)
            base_clip = clip.std.BlankClip(length=length, color=get_neutral_values(clip))
        elif do_taverage:
            base_clip = (clip[0] * self.temporal_radius) + clip + (clip[-1] * self.temporal_radius)
        else:
            base_clip = clip

        def _try_grain(src: vs.VideoNode, stre: tuple[float, float] = strength, **args: Any) -> vs.VideoNode:
            args = kwargs | dict(strength=stre, dynamic=dynamic) | args
            try:
                self._check_input(src, **args)
                grained = self._perform_graining(src, **args)
            except NotImplementedError as e:
                reason, *_ = map(str, e.args)

                if reason == 'dynamic-only':
                    grained = _try_grain(src[src.num_frames // 2], dynamic=True)
                elif reason.startswith('bad-depth'):
                    good_depth = int(reason.split('-')[-1])
                    grained = _try_grain(depth(src, good_depth))
                    grained = depth(grained, src)
                elif reason == 'single-plane':
                    str_luma, str_chroma = strength

                    if str_luma > 0 and str_chroma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )
                    elif str_luma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            src
                        )
                    elif str_chroma > 0:
                        return join(
                            src,
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )

                    return src
                else:
                    raise e

            return grained

        grained = _try_grain(base_clip)

        if input_dep and neutral_out:
            grained = clip.std.MakeDiff(grained)

        return grained

    if (
        self.size == (1.0, 1.0) and not do_taverage and not self.postprocess
        and not do_protect_chroma and self.luma_scaling is None and not self.fade_limits
    ):
        return _wrap_implementation(clip, self.neutral_out)

    (sizex, sizey), mod = self.size, max(clip.format.subsampling_w, clip.format.subsampling_h) << 1
    sx, sy = mod_x(clip.width / sizex, mod), mod_x(clip.height / sizey, mod)

    if (sx, sy) != (clip.width, clip.height):
        sxa, sya = mod_x((clip.width + sx) / 2, mod), mod_x((clip.height + sy) / 2, mod)

        grained = _wrap_implementation(self.scaler.scale(clip, sx, sy), True)

        # If the scale is too big, we need to scale it in two passes, else the window
        # will be too big and the grain will be dampened down too much
        if max(self.size) > 1.5:
            grained = self.scaler.scale(grained, sxa, sya)

        grained = self.scaler.scale(grained, clip.width, clip.height)
    else:
        grained = _wrap_implementation(clip, True)

    if do_taverage:
        average = BlurMatrix.MEAN(taps=self.temporal_radius, mode=ConvMode.TEMPORAL)(grained)
        grained = grained.std.Merge(average, self.temporal_average)
        grained = grained[self.temporal_radius:-self.temporal_radius]

    if self.fade_limits:
        low, high = (None, None) if self.fade_limits is True else self.fade_limits

        low = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(low, 16)))
        ]

        high = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(high, [235, 240])))
        ]

        if complexpr_available:
            limit_expr = 'y neutral - abs A! x A@ - {low} < x A@ + {high} > or neutral y ?'
        else:
            limit_expr = 'x y neutral - abs - {low} < x y neutral - abs + {high} > or neutral y ?'

        grained = norm_expr([clip, grained], limit_expr, planes, low=low, high=high, func=self.__class__.grain)

    if self.postprocess:
        for postprocess in cast(list[GrainPostProcessT], to_arr(self.postprocess)):
            if callable(postprocess):
                try:
                    postprocess = postprocess(grained, clip)
                except TypeError:
                    postprocess = postprocess(grained)

            if isinstance(postprocess, vs.VideoNode):
                grained = postprocess
            else:
                if isinstance(postprocess, GrainPP):
                    postprocess, ppkwargs = postprocess.value, postprocess.kwargs
                else:
                    ppkwargs = KwargsT()

                # fuck importing re
                uses_y = ' y ' in postprocess or postprocess.startswith('y ') or postprocess.endswith(' y')  #type: ignore
                grained = norm_expr(
                    [grained, clip] if uses_y else grained, postprocess, **ppkwargs, func=self.__class__.grain
                )

    neutral = get_neutral_value(clip)

    if self.neutral_out:
        merge_clip = grained.std.MakeDiff(grained)[0].std.Loop(grained.num_frames)
    else:
        merge_clip, grained = clip, clip.std.MergeDiff(grained, planes)

    if do_protect_chroma:
        neutral_mask = Lanczos.resample(clip, clip.format.replace(subsampling_h=0, subsampling_w=0))

        neutral_mask = norm_expr(
            split(neutral_mask), f'y {neutral} = z {neutral} = and {get_peak_value(clip, range_in=ColorRange.FULL)} 0 ?',
            func=self.__class__.grain
        )

        grained = grained.std.MaskedMerge(merge_clip, neutral_mask, [1, 2])

    if self.luma_scaling is not None:
        mask = adg_mask(clip, self.luma_scaling, func=self.grain)

        grained = merge_clip.std.MaskedMerge(grained, mask)

    return grained

FilmGrain

FilmGrain(
    strength: float | tuple[float, float] = 0.8,
    size: float | tuple[float, float] = (1.0, 1.0),
    sharp: float | ScalerT = Lanczos,
    dynamic: bool = True,
    temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None,
    protect_chroma: bool = True,
    luma_scaling: float | None = None,
    fade_limits: bool | FadeLimits = True,
    *,
    rad: float = 0.1,
    iterations: int = 800,
    dev: float = 0.0,
    gamma: float = 1.0,
    matrix: MatrixT | None = None,
    kernel: KernelT = Catrom,
    neutral_out: bool = False,
    **kwargs: Any
)

Bases: LinearLightGrainer

fgrain_cuda.Add plugin. https://github.com/AmusementClub/vs-fgrain-cuda

Methods:

Attributes:

Source code
547
548
549
550
551
552
553
554
555
556
557
558
559
560
def __init__(
    self, strength: float | tuple[float, float] = 0.8,
    size: float | tuple[float, float] = (1.0, 1.0), sharp: float | ScalerT = Lanczos,
    dynamic: bool = True, temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None, protect_chroma: bool = True,
    luma_scaling: float | None = None, fade_limits: bool | FadeLimits = True,
    *, rad: float = 0.1, iterations: int = 800, dev: float = 0.0, gamma: float = 1.0,
    matrix: MatrixT | None = None, kernel: KernelT = Catrom, neutral_out: bool = False, **kwargs: Any
) -> None:
    super().__init__(
        strength, size, sharp, dynamic, temporal_average, postprocess, protect_chroma, luma_scaling, fade_limits,
        matrix=matrix, kernel=kernel, neutral_out=neutral_out, gamma=gamma,
        grain_radius_mean=rad, num_iterations=iterations, grain_radius_std=dev, **kwargs
    )

dynamic instance-attribute

dynamic = dynamic

fade_limits instance-attribute

fade_limits = fade_limits

gamma instance-attribute

gamma = gamma

kernel instance-attribute

kernel = ensure_obj(kernel, __class__)

kwargs instance-attribute

kwargs = kwargs

luma_scaling instance-attribute

luma_scaling = luma_scaling

matrix instance-attribute

matrix = from_param(matrix, __class__)

neutral_out instance-attribute

neutral_out = neutral_out

postprocess instance-attribute

postprocess = postprocess

protect_chroma instance-attribute

protect_chroma = protect_chroma

scaler instance-attribute

scaler: Scaler = BicubicAuto(sharp)

size instance-attribute

size = size if isinstance(size, tuple) else (size, size)

strength instance-attribute

strength = strength

grain

grain(
    clip: VideoNode,
    strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None,
    **kwargs: Any
) -> VideoNode
Source code
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
@inject_self.init_kwargs.clean
def grain(
    self, clip: vs.VideoNode, strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None, **kwargs: Any
) -> vs.VideoNode:
    assert clip.format

    kwargs = self._get_kw(kwargs)

    if strength is None:
        strength = self.strength

    dynamic = fallback(dynamic, self.dynamic)
    strength = strength if isinstance(strength, tuple) else (
        strength, strength if clip.format.num_planes > 1 else 0.0
    )

    if max(strength) <= 0.0:
        return clip

    if strength[0] <= 0.0 and strength[1] > 0.0:
        planes: PlanesT = [1, 2]
    elif strength[0] > 0.0 and strength[1] <= 0.0:
        planes = 0
    else:
        planes = None

    do_taverage = (
        dynamic
        and self.temporal_average > 0 and self.temporal_radius > 0
        and (clip.num_frames > self.temporal_radius * 2)
    )
    do_protect_chroma = self.protect_chroma and strength[1] > 0.0 and clip.format.color_family is vs.YUV
    input_dep = self._is_input_dependent(clip, **kwargs)

    def _wrap_implementation(clip: vs.VideoNode, neutral_out: bool) -> vs.VideoNode:
        if input_dep and do_taverage and not kwargs.get('unsafe_graining', False):
            raise CustomValueError(
                'You can\'t have temporal averaging with input dependent graining as it will create ghosting!'
            )

        if neutral_out and not input_dep:
            length = clip.num_frames + ((self.temporal_radius * 2) if do_taverage else 0)
            base_clip = clip.std.BlankClip(length=length, color=get_neutral_values(clip))
        elif do_taverage:
            base_clip = (clip[0] * self.temporal_radius) + clip + (clip[-1] * self.temporal_radius)
        else:
            base_clip = clip

        def _try_grain(src: vs.VideoNode, stre: tuple[float, float] = strength, **args: Any) -> vs.VideoNode:
            args = kwargs | dict(strength=stre, dynamic=dynamic) | args
            try:
                self._check_input(src, **args)
                grained = self._perform_graining(src, **args)
            except NotImplementedError as e:
                reason, *_ = map(str, e.args)

                if reason == 'dynamic-only':
                    grained = _try_grain(src[src.num_frames // 2], dynamic=True)
                elif reason.startswith('bad-depth'):
                    good_depth = int(reason.split('-')[-1])
                    grained = _try_grain(depth(src, good_depth))
                    grained = depth(grained, src)
                elif reason == 'single-plane':
                    str_luma, str_chroma = strength

                    if str_luma > 0 and str_chroma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )
                    elif str_luma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            src
                        )
                    elif str_chroma > 0:
                        return join(
                            src,
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )

                    return src
                else:
                    raise e

            return grained

        grained = _try_grain(base_clip)

        if input_dep and neutral_out:
            grained = clip.std.MakeDiff(grained)

        return grained

    if (
        self.size == (1.0, 1.0) and not do_taverage and not self.postprocess
        and not do_protect_chroma and self.luma_scaling is None and not self.fade_limits
    ):
        return _wrap_implementation(clip, self.neutral_out)

    (sizex, sizey), mod = self.size, max(clip.format.subsampling_w, clip.format.subsampling_h) << 1
    sx, sy = mod_x(clip.width / sizex, mod), mod_x(clip.height / sizey, mod)

    if (sx, sy) != (clip.width, clip.height):
        sxa, sya = mod_x((clip.width + sx) / 2, mod), mod_x((clip.height + sy) / 2, mod)

        grained = _wrap_implementation(self.scaler.scale(clip, sx, sy), True)

        # If the scale is too big, we need to scale it in two passes, else the window
        # will be too big and the grain will be dampened down too much
        if max(self.size) > 1.5:
            grained = self.scaler.scale(grained, sxa, sya)

        grained = self.scaler.scale(grained, clip.width, clip.height)
    else:
        grained = _wrap_implementation(clip, True)

    if do_taverage:
        average = BlurMatrix.MEAN(taps=self.temporal_radius, mode=ConvMode.TEMPORAL)(grained)
        grained = grained.std.Merge(average, self.temporal_average)
        grained = grained[self.temporal_radius:-self.temporal_radius]

    if self.fade_limits:
        low, high = (None, None) if self.fade_limits is True else self.fade_limits

        low = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(low, 16)))
        ]

        high = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(high, [235, 240])))
        ]

        if complexpr_available:
            limit_expr = 'y neutral - abs A! x A@ - {low} < x A@ + {high} > or neutral y ?'
        else:
            limit_expr = 'x y neutral - abs - {low} < x y neutral - abs + {high} > or neutral y ?'

        grained = norm_expr([clip, grained], limit_expr, planes, low=low, high=high, func=self.__class__.grain)

    if self.postprocess:
        for postprocess in cast(list[GrainPostProcessT], to_arr(self.postprocess)):
            if callable(postprocess):
                try:
                    postprocess = postprocess(grained, clip)
                except TypeError:
                    postprocess = postprocess(grained)

            if isinstance(postprocess, vs.VideoNode):
                grained = postprocess
            else:
                if isinstance(postprocess, GrainPP):
                    postprocess, ppkwargs = postprocess.value, postprocess.kwargs
                else:
                    ppkwargs = KwargsT()

                # fuck importing re
                uses_y = ' y ' in postprocess or postprocess.startswith('y ') or postprocess.endswith(' y')  #type: ignore
                grained = norm_expr(
                    [grained, clip] if uses_y else grained, postprocess, **ppkwargs, func=self.__class__.grain
                )

    neutral = get_neutral_value(clip)

    if self.neutral_out:
        merge_clip = grained.std.MakeDiff(grained)[0].std.Loop(grained.num_frames)
    else:
        merge_clip, grained = clip, clip.std.MergeDiff(grained, planes)

    if do_protect_chroma:
        neutral_mask = Lanczos.resample(clip, clip.format.replace(subsampling_h=0, subsampling_w=0))

        neutral_mask = norm_expr(
            split(neutral_mask), f'y {neutral} = z {neutral} = and {get_peak_value(clip, range_in=ColorRange.FULL)} 0 ?',
            func=self.__class__.grain
        )

        grained = grained.std.MaskedMerge(merge_clip, neutral_mask, [1, 2])

    if self.luma_scaling is not None:
        mask = adg_mask(clip, self.luma_scaling, func=self.grain)

        grained = merge_clip.std.MaskedMerge(grained, mask)

    return grained

GrainPP dataclass

GrainPP(value: str, kwargs: KwargsT = lambda: KwargsT()())

Methods:

Attributes:

Resolver class-attribute instance-attribute

Resolver = Callable[[VideoNode], 'GrainPP']

kwargs class-attribute instance-attribute

kwargs: KwargsT = field(default_factory=lambda: KwargsT())

value instance-attribute

value: str

Bump classmethod

Bump(strength: float = 0.1) -> GrainPP
Source code
52
53
54
@classmethod
def Bump(cls, strength: float = 0.1) -> GrainPP:
    return cls('x[-1,1] x - {strength} * x +', KwargsT(strength=strength + 1.0))

NormBrightness classmethod

NormBrightness() -> ResolverOneClipArgs
Source code
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
@classmethod
def NormBrightness(cls) -> ResolverOneClipArgs:
    def _resolve(grained: vs.VideoNode) -> vs.VideoNode:
        assert grained.format

        for i in range(grained.format.num_planes):
            grained = grained.std.PlaneStats(plane=i, prop=f'PS{i}')

        if get_sample_type(grained) is vs.FLOAT:
            return norm_expr(grained, 'x x.PS{plane_idx}Average -', func=cls.NormBrightness)

        return norm_expr(
            grained, 'x neutral range_size / x.PS{plane_idx}Average - range_size * +', func=cls.NormBrightness
        )

    return _resolve

Grainer

Grainer(
    strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0),
    sharp: float | ScalerT = Lanczos,
    dynamic: bool = True,
    temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None,
    protect_chroma: bool = True,
    luma_scaling: float | None = None,
    fade_limits: bool | FadeLimits = True,
    *,
    matrix: MatrixT | None = None,
    kernel: KernelT = Catrom,
    neutral_out: bool = False,
    **kwargs: Any
)

Bases: ABC

Abstract graining interface

Methods:

Attributes:

Source code
 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
def __init__(
    self, strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0), sharp: float | ScalerT = Lanczos,
    dynamic: bool = True, temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None, protect_chroma: bool = True,
    luma_scaling: float | None = None, fade_limits: bool | FadeLimits = True, *,
    matrix: MatrixT | None = None, kernel: KernelT = Catrom, neutral_out: bool = False,
    **kwargs: Any
) -> None:
    super().__init__()

    self.strength = strength
    self.size = size if isinstance(size, tuple) else (size, size)
    self.neutral_out = neutral_out
    self.dynamic = dynamic
    self.postprocess = postprocess
    self.protect_chroma = protect_chroma
    self.luma_scaling = luma_scaling
    self.fade_limits = fade_limits
    self.kwargs = kwargs

    if isinstance(sharp, (float, int)):
        self.scaler: Scaler = BicubicAuto(sharp)
    else:
        self.scaler = Scaler.ensure_obj(sharp, self.__class__)

    if isinstance(temporal_average, tuple):
        self.temporal_average, self.temporal_radius = temporal_average
    else:
        self.temporal_average, self.temporal_radius = temporal_average, 1

    self.matrix = Matrix.from_param(matrix, self.__class__)
    self.kernel = Kernel.ensure_obj(kernel, self.__class__)

dynamic instance-attribute

dynamic = dynamic

fade_limits instance-attribute

fade_limits = fade_limits

kernel instance-attribute

kernel = ensure_obj(kernel, __class__)

kwargs instance-attribute

kwargs = kwargs

luma_scaling instance-attribute

luma_scaling = luma_scaling

matrix instance-attribute

matrix = from_param(matrix, __class__)

neutral_out instance-attribute

neutral_out = neutral_out

postprocess instance-attribute

postprocess = postprocess

protect_chroma instance-attribute

protect_chroma = protect_chroma

scaler instance-attribute

scaler: Scaler = BicubicAuto(sharp)

size instance-attribute

size = size if isinstance(size, tuple) else (size, size)

strength instance-attribute

strength = strength

grain

grain(
    clip: VideoNode,
    strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None,
    **kwargs: Any
) -> VideoNode
Source code
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
@inject_self.init_kwargs.clean
def grain(
    self, clip: vs.VideoNode, strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None, **kwargs: Any
) -> vs.VideoNode:
    assert clip.format

    kwargs = self._get_kw(kwargs)

    if strength is None:
        strength = self.strength

    dynamic = fallback(dynamic, self.dynamic)
    strength = strength if isinstance(strength, tuple) else (
        strength, strength if clip.format.num_planes > 1 else 0.0
    )

    if max(strength) <= 0.0:
        return clip

    if strength[0] <= 0.0 and strength[1] > 0.0:
        planes: PlanesT = [1, 2]
    elif strength[0] > 0.0 and strength[1] <= 0.0:
        planes = 0
    else:
        planes = None

    do_taverage = (
        dynamic
        and self.temporal_average > 0 and self.temporal_radius > 0
        and (clip.num_frames > self.temporal_radius * 2)
    )
    do_protect_chroma = self.protect_chroma and strength[1] > 0.0 and clip.format.color_family is vs.YUV
    input_dep = self._is_input_dependent(clip, **kwargs)

    def _wrap_implementation(clip: vs.VideoNode, neutral_out: bool) -> vs.VideoNode:
        if input_dep and do_taverage and not kwargs.get('unsafe_graining', False):
            raise CustomValueError(
                'You can\'t have temporal averaging with input dependent graining as it will create ghosting!'
            )

        if neutral_out and not input_dep:
            length = clip.num_frames + ((self.temporal_radius * 2) if do_taverage else 0)
            base_clip = clip.std.BlankClip(length=length, color=get_neutral_values(clip))
        elif do_taverage:
            base_clip = (clip[0] * self.temporal_radius) + clip + (clip[-1] * self.temporal_radius)
        else:
            base_clip = clip

        def _try_grain(src: vs.VideoNode, stre: tuple[float, float] = strength, **args: Any) -> vs.VideoNode:
            args = kwargs | dict(strength=stre, dynamic=dynamic) | args
            try:
                self._check_input(src, **args)
                grained = self._perform_graining(src, **args)
            except NotImplementedError as e:
                reason, *_ = map(str, e.args)

                if reason == 'dynamic-only':
                    grained = _try_grain(src[src.num_frames // 2], dynamic=True)
                elif reason.startswith('bad-depth'):
                    good_depth = int(reason.split('-')[-1])
                    grained = _try_grain(depth(src, good_depth))
                    grained = depth(grained, src)
                elif reason == 'single-plane':
                    str_luma, str_chroma = strength

                    if str_luma > 0 and str_chroma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )
                    elif str_luma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            src
                        )
                    elif str_chroma > 0:
                        return join(
                            src,
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )

                    return src
                else:
                    raise e

            return grained

        grained = _try_grain(base_clip)

        if input_dep and neutral_out:
            grained = clip.std.MakeDiff(grained)

        return grained

    if (
        self.size == (1.0, 1.0) and not do_taverage and not self.postprocess
        and not do_protect_chroma and self.luma_scaling is None and not self.fade_limits
    ):
        return _wrap_implementation(clip, self.neutral_out)

    (sizex, sizey), mod = self.size, max(clip.format.subsampling_w, clip.format.subsampling_h) << 1
    sx, sy = mod_x(clip.width / sizex, mod), mod_x(clip.height / sizey, mod)

    if (sx, sy) != (clip.width, clip.height):
        sxa, sya = mod_x((clip.width + sx) / 2, mod), mod_x((clip.height + sy) / 2, mod)

        grained = _wrap_implementation(self.scaler.scale(clip, sx, sy), True)

        # If the scale is too big, we need to scale it in two passes, else the window
        # will be too big and the grain will be dampened down too much
        if max(self.size) > 1.5:
            grained = self.scaler.scale(grained, sxa, sya)

        grained = self.scaler.scale(grained, clip.width, clip.height)
    else:
        grained = _wrap_implementation(clip, True)

    if do_taverage:
        average = BlurMatrix.MEAN(taps=self.temporal_radius, mode=ConvMode.TEMPORAL)(grained)
        grained = grained.std.Merge(average, self.temporal_average)
        grained = grained[self.temporal_radius:-self.temporal_radius]

    if self.fade_limits:
        low, high = (None, None) if self.fade_limits is True else self.fade_limits

        low = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(low, 16)))
        ]

        high = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(high, [235, 240])))
        ]

        if complexpr_available:
            limit_expr = 'y neutral - abs A! x A@ - {low} < x A@ + {high} > or neutral y ?'
        else:
            limit_expr = 'x y neutral - abs - {low} < x y neutral - abs + {high} > or neutral y ?'

        grained = norm_expr([clip, grained], limit_expr, planes, low=low, high=high, func=self.__class__.grain)

    if self.postprocess:
        for postprocess in cast(list[GrainPostProcessT], to_arr(self.postprocess)):
            if callable(postprocess):
                try:
                    postprocess = postprocess(grained, clip)
                except TypeError:
                    postprocess = postprocess(grained)

            if isinstance(postprocess, vs.VideoNode):
                grained = postprocess
            else:
                if isinstance(postprocess, GrainPP):
                    postprocess, ppkwargs = postprocess.value, postprocess.kwargs
                else:
                    ppkwargs = KwargsT()

                # fuck importing re
                uses_y = ' y ' in postprocess or postprocess.startswith('y ') or postprocess.endswith(' y')  #type: ignore
                grained = norm_expr(
                    [grained, clip] if uses_y else grained, postprocess, **ppkwargs, func=self.__class__.grain
                )

    neutral = get_neutral_value(clip)

    if self.neutral_out:
        merge_clip = grained.std.MakeDiff(grained)[0].std.Loop(grained.num_frames)
    else:
        merge_clip, grained = clip, clip.std.MergeDiff(grained, planes)

    if do_protect_chroma:
        neutral_mask = Lanczos.resample(clip, clip.format.replace(subsampling_h=0, subsampling_w=0))

        neutral_mask = norm_expr(
            split(neutral_mask), f'y {neutral} = z {neutral} = and {get_peak_value(clip, range_in=ColorRange.FULL)} 0 ?',
            func=self.__class__.grain
        )

        grained = grained.std.MaskedMerge(merge_clip, neutral_mask, [1, 2])

    if self.luma_scaling is not None:
        mask = adg_mask(clip, self.luma_scaling, func=self.grain)

        grained = merge_clip.std.MaskedMerge(grained, mask)

    return grained

LinearLightGrainer

LinearLightGrainer(
    strength: float | tuple[float, float],
    size: float | tuple[float, float] = (1.0, 1.0),
    sharp: float | ScalerT = Lanczos,
    dynamic: bool = True,
    temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None,
    protect_chroma: bool = True,
    luma_scaling: float | None = None,
    fade_limits: bool | FadeLimits = True,
    *,
    gamma: float = 1.0,
    matrix: MatrixT | None = None,
    kernel: KernelT = Catrom,
    neutral_out: bool = False,
    **kwargs: Any
)

Bases: Grainer

Base grainer depending on linear RGB clip, input dependent.

Methods:

Attributes:

Source code
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
def __init__(
    self, strength: float | tuple[float, float],
    size: float | tuple[float, float] = (1.0, 1.0), sharp: float | ScalerT = Lanczos,
    dynamic: bool = True, temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None, protect_chroma: bool = True,
    luma_scaling: float | None = None, fade_limits: bool | FadeLimits = True,
    *, gamma: float = 1.0, matrix: MatrixT | None = None, kernel: KernelT = Catrom, neutral_out: bool = False,
    **kwargs: Any
) -> None:
    super().__init__(
        strength, size, sharp, dynamic, temporal_average, postprocess, protect_chroma, luma_scaling, fade_limits,
        matrix=matrix, kernel=kernel, neutral_out=neutral_out, **kwargs
    )

    if not 0.0 <= gamma <= 1.0:
        raise CustomOverflowError('Gamma must be between 0.0 and 1.0 (inclusive)!', self.__class__, gamma)
    self.gamma = gamma

dynamic instance-attribute

dynamic = dynamic

fade_limits instance-attribute

fade_limits = fade_limits

gamma instance-attribute

gamma = gamma

kernel instance-attribute

kernel = ensure_obj(kernel, __class__)

kwargs instance-attribute

kwargs = kwargs

luma_scaling instance-attribute

luma_scaling = luma_scaling

matrix instance-attribute

matrix = from_param(matrix, __class__)

neutral_out instance-attribute

neutral_out = neutral_out

postprocess instance-attribute

postprocess = postprocess

protect_chroma instance-attribute

protect_chroma = protect_chroma

scaler instance-attribute

scaler: Scaler = BicubicAuto(sharp)

size instance-attribute

size = size if isinstance(size, tuple) else (size, size)

strength instance-attribute

strength = strength

grain

grain(
    clip: VideoNode,
    strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None,
    **kwargs: Any
) -> VideoNode
Source code
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
@inject_self.init_kwargs.clean
def grain(
    self, clip: vs.VideoNode, strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None, **kwargs: Any
) -> vs.VideoNode:
    assert clip.format

    kwargs = self._get_kw(kwargs)

    if strength is None:
        strength = self.strength

    dynamic = fallback(dynamic, self.dynamic)
    strength = strength if isinstance(strength, tuple) else (
        strength, strength if clip.format.num_planes > 1 else 0.0
    )

    if max(strength) <= 0.0:
        return clip

    if strength[0] <= 0.0 and strength[1] > 0.0:
        planes: PlanesT = [1, 2]
    elif strength[0] > 0.0 and strength[1] <= 0.0:
        planes = 0
    else:
        planes = None

    do_taverage = (
        dynamic
        and self.temporal_average > 0 and self.temporal_radius > 0
        and (clip.num_frames > self.temporal_radius * 2)
    )
    do_protect_chroma = self.protect_chroma and strength[1] > 0.0 and clip.format.color_family is vs.YUV
    input_dep = self._is_input_dependent(clip, **kwargs)

    def _wrap_implementation(clip: vs.VideoNode, neutral_out: bool) -> vs.VideoNode:
        if input_dep and do_taverage and not kwargs.get('unsafe_graining', False):
            raise CustomValueError(
                'You can\'t have temporal averaging with input dependent graining as it will create ghosting!'
            )

        if neutral_out and not input_dep:
            length = clip.num_frames + ((self.temporal_radius * 2) if do_taverage else 0)
            base_clip = clip.std.BlankClip(length=length, color=get_neutral_values(clip))
        elif do_taverage:
            base_clip = (clip[0] * self.temporal_radius) + clip + (clip[-1] * self.temporal_radius)
        else:
            base_clip = clip

        def _try_grain(src: vs.VideoNode, stre: tuple[float, float] = strength, **args: Any) -> vs.VideoNode:
            args = kwargs | dict(strength=stre, dynamic=dynamic) | args
            try:
                self._check_input(src, **args)
                grained = self._perform_graining(src, **args)
            except NotImplementedError as e:
                reason, *_ = map(str, e.args)

                if reason == 'dynamic-only':
                    grained = _try_grain(src[src.num_frames // 2], dynamic=True)
                elif reason.startswith('bad-depth'):
                    good_depth = int(reason.split('-')[-1])
                    grained = _try_grain(depth(src, good_depth))
                    grained = depth(grained, src)
                elif reason == 'single-plane':
                    str_luma, str_chroma = strength

                    if str_luma > 0 and str_chroma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )
                    elif str_luma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            src
                        )
                    elif str_chroma > 0:
                        return join(
                            src,
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )

                    return src
                else:
                    raise e

            return grained

        grained = _try_grain(base_clip)

        if input_dep and neutral_out:
            grained = clip.std.MakeDiff(grained)

        return grained

    if (
        self.size == (1.0, 1.0) and not do_taverage and not self.postprocess
        and not do_protect_chroma and self.luma_scaling is None and not self.fade_limits
    ):
        return _wrap_implementation(clip, self.neutral_out)

    (sizex, sizey), mod = self.size, max(clip.format.subsampling_w, clip.format.subsampling_h) << 1
    sx, sy = mod_x(clip.width / sizex, mod), mod_x(clip.height / sizey, mod)

    if (sx, sy) != (clip.width, clip.height):
        sxa, sya = mod_x((clip.width + sx) / 2, mod), mod_x((clip.height + sy) / 2, mod)

        grained = _wrap_implementation(self.scaler.scale(clip, sx, sy), True)

        # If the scale is too big, we need to scale it in two passes, else the window
        # will be too big and the grain will be dampened down too much
        if max(self.size) > 1.5:
            grained = self.scaler.scale(grained, sxa, sya)

        grained = self.scaler.scale(grained, clip.width, clip.height)
    else:
        grained = _wrap_implementation(clip, True)

    if do_taverage:
        average = BlurMatrix.MEAN(taps=self.temporal_radius, mode=ConvMode.TEMPORAL)(grained)
        grained = grained.std.Merge(average, self.temporal_average)
        grained = grained[self.temporal_radius:-self.temporal_radius]

    if self.fade_limits:
        low, high = (None, None) if self.fade_limits is True else self.fade_limits

        low = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(low, 16)))
        ]

        high = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(high, [235, 240])))
        ]

        if complexpr_available:
            limit_expr = 'y neutral - abs A! x A@ - {low} < x A@ + {high} > or neutral y ?'
        else:
            limit_expr = 'x y neutral - abs - {low} < x y neutral - abs + {high} > or neutral y ?'

        grained = norm_expr([clip, grained], limit_expr, planes, low=low, high=high, func=self.__class__.grain)

    if self.postprocess:
        for postprocess in cast(list[GrainPostProcessT], to_arr(self.postprocess)):
            if callable(postprocess):
                try:
                    postprocess = postprocess(grained, clip)
                except TypeError:
                    postprocess = postprocess(grained)

            if isinstance(postprocess, vs.VideoNode):
                grained = postprocess
            else:
                if isinstance(postprocess, GrainPP):
                    postprocess, ppkwargs = postprocess.value, postprocess.kwargs
                else:
                    ppkwargs = KwargsT()

                # fuck importing re
                uses_y = ' y ' in postprocess or postprocess.startswith('y ') or postprocess.endswith(' y')  #type: ignore
                grained = norm_expr(
                    [grained, clip] if uses_y else grained, postprocess, **ppkwargs, func=self.__class__.grain
                )

    neutral = get_neutral_value(clip)

    if self.neutral_out:
        merge_clip = grained.std.MakeDiff(grained)[0].std.Loop(grained.num_frames)
    else:
        merge_clip, grained = clip, clip.std.MergeDiff(grained, planes)

    if do_protect_chroma:
        neutral_mask = Lanczos.resample(clip, clip.format.replace(subsampling_h=0, subsampling_w=0))

        neutral_mask = norm_expr(
            split(neutral_mask), f'y {neutral} = z {neutral} = and {get_peak_value(clip, range_in=ColorRange.FULL)} 0 ?',
            func=self.__class__.grain
        )

        grained = grained.std.MaskedMerge(merge_clip, neutral_mask, [1, 2])

    if self.luma_scaling is not None:
        mask = adg_mask(clip, self.luma_scaling, func=self.grain)

        grained = merge_clip.std.MaskedMerge(grained, mask)

    return grained

PlaceboGrain

PlaceboGrain(
    strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0),
    sharp: float | ScalerT = Lanczos,
    dynamic: bool = True,
    temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None,
    protect_chroma: bool = True,
    luma_scaling: float | None = None,
    fade_limits: bool | FadeLimits = True,
    *,
    matrix: MatrixT | None = None,
    kernel: KernelT = Catrom,
    neutral_out: bool = False,
    **kwargs: Any
)

Bases: Grainer

placebo.Deband plugin. https://github.com/Lypheo/vs-placebo

Methods:

Attributes:

Source code
 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
def __init__(
    self, strength: float | tuple[float, float] = 0.25,
    size: float | tuple[float, float] = (1.0, 1.0), sharp: float | ScalerT = Lanczos,
    dynamic: bool = True, temporal_average: int | tuple[float, int] = (0.0, 1),
    postprocess: GrainPostProcessesT | None = None, protect_chroma: bool = True,
    luma_scaling: float | None = None, fade_limits: bool | FadeLimits = True, *,
    matrix: MatrixT | None = None, kernel: KernelT = Catrom, neutral_out: bool = False,
    **kwargs: Any
) -> None:
    super().__init__()

    self.strength = strength
    self.size = size if isinstance(size, tuple) else (size, size)
    self.neutral_out = neutral_out
    self.dynamic = dynamic
    self.postprocess = postprocess
    self.protect_chroma = protect_chroma
    self.luma_scaling = luma_scaling
    self.fade_limits = fade_limits
    self.kwargs = kwargs

    if isinstance(sharp, (float, int)):
        self.scaler: Scaler = BicubicAuto(sharp)
    else:
        self.scaler = Scaler.ensure_obj(sharp, self.__class__)

    if isinstance(temporal_average, tuple):
        self.temporal_average, self.temporal_radius = temporal_average
    else:
        self.temporal_average, self.temporal_radius = temporal_average, 1

    self.matrix = Matrix.from_param(matrix, self.__class__)
    self.kernel = Kernel.ensure_obj(kernel, self.__class__)

dynamic instance-attribute

dynamic = dynamic

fade_limits instance-attribute

fade_limits = fade_limits

kernel instance-attribute

kernel = ensure_obj(kernel, __class__)

kwargs instance-attribute

kwargs = kwargs

luma_scaling instance-attribute

luma_scaling = luma_scaling

matrix instance-attribute

matrix = from_param(matrix, __class__)

neutral_out instance-attribute

neutral_out = neutral_out

postprocess instance-attribute

postprocess = postprocess

protect_chroma instance-attribute

protect_chroma = protect_chroma

scaler instance-attribute

scaler: Scaler = BicubicAuto(sharp)

size instance-attribute

size = size if isinstance(size, tuple) else (size, size)

strength instance-attribute

strength = strength

grain

grain(
    clip: VideoNode,
    strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None,
    **kwargs: Any
) -> VideoNode
Source code
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
@inject_self.init_kwargs.clean
def grain(
    self, clip: vs.VideoNode, strength: float | tuple[float, float] | None = None,
    dynamic: bool | None = None, **kwargs: Any
) -> vs.VideoNode:
    assert clip.format

    kwargs = self._get_kw(kwargs)

    if strength is None:
        strength = self.strength

    dynamic = fallback(dynamic, self.dynamic)
    strength = strength if isinstance(strength, tuple) else (
        strength, strength if clip.format.num_planes > 1 else 0.0
    )

    if max(strength) <= 0.0:
        return clip

    if strength[0] <= 0.0 and strength[1] > 0.0:
        planes: PlanesT = [1, 2]
    elif strength[0] > 0.0 and strength[1] <= 0.0:
        planes = 0
    else:
        planes = None

    do_taverage = (
        dynamic
        and self.temporal_average > 0 and self.temporal_radius > 0
        and (clip.num_frames > self.temporal_radius * 2)
    )
    do_protect_chroma = self.protect_chroma and strength[1] > 0.0 and clip.format.color_family is vs.YUV
    input_dep = self._is_input_dependent(clip, **kwargs)

    def _wrap_implementation(clip: vs.VideoNode, neutral_out: bool) -> vs.VideoNode:
        if input_dep and do_taverage and not kwargs.get('unsafe_graining', False):
            raise CustomValueError(
                'You can\'t have temporal averaging with input dependent graining as it will create ghosting!'
            )

        if neutral_out and not input_dep:
            length = clip.num_frames + ((self.temporal_radius * 2) if do_taverage else 0)
            base_clip = clip.std.BlankClip(length=length, color=get_neutral_values(clip))
        elif do_taverage:
            base_clip = (clip[0] * self.temporal_radius) + clip + (clip[-1] * self.temporal_radius)
        else:
            base_clip = clip

        def _try_grain(src: vs.VideoNode, stre: tuple[float, float] = strength, **args: Any) -> vs.VideoNode:
            args = kwargs | dict(strength=stre, dynamic=dynamic) | args
            try:
                self._check_input(src, **args)
                grained = self._perform_graining(src, **args)
            except NotImplementedError as e:
                reason, *_ = map(str, e.args)

                if reason == 'dynamic-only':
                    grained = _try_grain(src[src.num_frames // 2], dynamic=True)
                elif reason.startswith('bad-depth'):
                    good_depth = int(reason.split('-')[-1])
                    grained = _try_grain(depth(src, good_depth))
                    grained = depth(grained, src)
                elif reason == 'single-plane':
                    str_luma, str_chroma = strength

                    if str_luma > 0 and str_chroma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )
                    elif str_luma > 0:
                        return join(
                            _try_grain(plane(src, 0), str_luma),
                            src
                        )
                    elif str_chroma > 0:
                        return join(
                            src,
                            _try_grain(plane(src, 1), str_chroma),
                            _try_grain(plane(src, 2), str_chroma)
                        )

                    return src
                else:
                    raise e

            return grained

        grained = _try_grain(base_clip)

        if input_dep and neutral_out:
            grained = clip.std.MakeDiff(grained)

        return grained

    if (
        self.size == (1.0, 1.0) and not do_taverage and not self.postprocess
        and not do_protect_chroma and self.luma_scaling is None and not self.fade_limits
    ):
        return _wrap_implementation(clip, self.neutral_out)

    (sizex, sizey), mod = self.size, max(clip.format.subsampling_w, clip.format.subsampling_h) << 1
    sx, sy = mod_x(clip.width / sizex, mod), mod_x(clip.height / sizey, mod)

    if (sx, sy) != (clip.width, clip.height):
        sxa, sya = mod_x((clip.width + sx) / 2, mod), mod_x((clip.height + sy) / 2, mod)

        grained = _wrap_implementation(self.scaler.scale(clip, sx, sy), True)

        # If the scale is too big, we need to scale it in two passes, else the window
        # will be too big and the grain will be dampened down too much
        if max(self.size) > 1.5:
            grained = self.scaler.scale(grained, sxa, sya)

        grained = self.scaler.scale(grained, clip.width, clip.height)
    else:
        grained = _wrap_implementation(clip, True)

    if do_taverage:
        average = BlurMatrix.MEAN(taps=self.temporal_radius, mode=ConvMode.TEMPORAL)(grained)
        grained = grained.std.Merge(average, self.temporal_average)
        grained = grained[self.temporal_radius:-self.temporal_radius]

    if self.fade_limits:
        low, high = (None, None) if self.fade_limits is True else self.fade_limits

        low = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(low, 16)))
        ]

        high = [
            scale_value(
                threshold, 8, clip.format.bits_per_sample,
                chroma=not not plane_index
            )
            for plane_index, threshold in enumerate(normalize_seq(fallback(high, [235, 240])))
        ]

        if complexpr_available:
            limit_expr = 'y neutral - abs A! x A@ - {low} < x A@ + {high} > or neutral y ?'
        else:
            limit_expr = 'x y neutral - abs - {low} < x y neutral - abs + {high} > or neutral y ?'

        grained = norm_expr([clip, grained], limit_expr, planes, low=low, high=high, func=self.__class__.grain)

    if self.postprocess:
        for postprocess in cast(list[GrainPostProcessT], to_arr(self.postprocess)):
            if callable(postprocess):
                try:
                    postprocess = postprocess(grained, clip)
                except TypeError:
                    postprocess = postprocess(grained)

            if isinstance(postprocess, vs.VideoNode):
                grained = postprocess
            else:
                if isinstance(postprocess, GrainPP):
                    postprocess, ppkwargs = postprocess.value, postprocess.kwargs
                else:
                    ppkwargs = KwargsT()

                # fuck importing re
                uses_y = ' y ' in postprocess or postprocess.startswith('y ') or postprocess.endswith(' y')  #type: ignore
                grained = norm_expr(
                    [grained, clip] if uses_y else grained, postprocess, **ppkwargs, func=self.__class__.grain
                )

    neutral = get_neutral_value(clip)

    if self.neutral_out:
        merge_clip = grained.std.MakeDiff(grained)[0].std.Loop(grained.num_frames)
    else:
        merge_clip, grained = clip, clip.std.MergeDiff(grained, planes)

    if do_protect_chroma:
        neutral_mask = Lanczos.resample(clip, clip.format.replace(subsampling_h=0, subsampling_w=0))

        neutral_mask = norm_expr(
            split(neutral_mask), f'y {neutral} = z {neutral} = and {get_peak_value(clip, range_in=ColorRange.FULL)} 0 ?',
            func=self.__class__.grain
        )

        grained = grained.std.MaskedMerge(merge_clip, neutral_mask, [1, 2])

    if self.luma_scaling is not None:
        mask = adg_mask(clip, self.luma_scaling, func=self.grain)

        grained = merge_clip.std.MaskedMerge(grained, mask)

    return grained

ResolverOneClipArgs

Bases: Protocol

Methods:

__call__

__call__(grained: VideoNode) -> VideoNode
Source code
36
37
def __call__(self, grained: vs.VideoNode) -> vs.VideoNode:
    ...

ResolverTwoClipsArgs

Bases: Protocol

Methods:

__call__

__call__(grained: VideoNode, clip: VideoNode) -> VideoNode
Source code
41
42
def __call__(self, grained: vs.VideoNode, clip: vs.VideoNode) -> vs.VideoNode:
    ...

multi_graining

multi_graining(
    clip: VideoNode,
    *grainers: MultiGrainerT,
    prefilter: VideoNode | Prefilter | None = None
) -> VideoNode

Interface for applying multiple grainers to a clip.

Parameters:

  • clip

    (VideoNode) –

    Input clip.

  • grainers

    (MultiGrainerT, default: () ) –

    Grainers to apply. Can be a grainer, or a tuple of a grainer/None and threshold, overflow. The threshold is the upper threshold of where the grainer will be applied. The overflow is the range of the hard threshold. If a grainer is None, the original clip will be applied in that range. For example: MultiGrainer((None, 0.1), (AddNoise, 0.5)) Will apply no grain for values <= 0.1 & > 0.5, AddNoise for values <= 0.5.

  • prefilter

    (VideoNode | Prefilter | None, default: None ) –

    Clip or prefilter for making theh clip used for the threshold masks.

Source code
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
def multi_graining(
    clip: vs.VideoNode, *grainers: MultiGrainerT, prefilter: vs.VideoNode | Prefilter | None = None
) -> vs.VideoNode:
    """
    Interface for applying multiple grainers to a clip.

    :param clip:        Input clip.
    :param grainers:    Grainers to apply. Can be a grainer, or a tuple of a grainer/None and threshold, overflow.
                        The threshold is the upper threshold of where the grainer will be applied.
                        The overflow is the range of the hard threshold.
                        If a grainer is None, the original clip will be applied in that range.
                        For example:
                            MultiGrainer((None, 0.1), (AddNoise, 0.5))

                        Will apply no grain for values <= 0.1 & > 0.5, AddNoise for values <= 0.5.
    :param prefilter:   Clip or prefilter for making theh clip used for the threshold masks.
    """

    assert check_variable(clip, multi_graining)

    InvalidColorFamilyError.check(clip, (vs.GRAY, vs.YUV))

    length = len(grainers)

    if length < 2:
        raise CustomIndexError('You need to give at least two grainers!')

    norm_grainers = sorted([
        (
            grainer if len(grainer) == 3 else (
                (*grainer, 1 / length) if len(grainer) == 2 else (None, 1.0, 1 / length)
            )
        ) if isinstance(grainer, tuple) else (grainer, 1.0, 1 / length)
        for grainer in grainers
    ], key=lambda x: x[1])

    if all(grainer is None for grainer, *_ in norm_grainers):
        raise CustomValueError('No valid grainers given!')
    elif any(grainer.neutral_out for grainer, *_ in norm_grainers if isinstance(grainer, Grainer)):
        raise CustomValueError('You can\'t set neutral_out in any grainer!')

    if prefilter is None:
        prefilter = get_y(clip)
    elif isinstance(prefilter, Prefilter):
        prefilter = prefilter(get_y(clip))

    prefilter = depth(get_y(prefilter), clip)

    peak = get_peak_value(clip)
    masks = [prefilter.std.BlankClip(color=0)] + [
        norm_expr(
            prefilter,
            'x {min_thr} >= x {max_thr} <= and x {min_thr} - {max_thr} {min_thr} '
            '- / {peak} * {peak} - abs x {min_thr} < {peak} x {max_thr} > 0 x ? ? ?',
            min_thr=f'{thr} {weight} {peak} * 2 / -', max_thr=f'{thr} {weight} {peak} * 2 / +',
            peak=peak, func=multi_graining
        ) for _, thr, weight in norm_grainers
    ]

    masks = [norm_expr(diffs, 'y x -', func=multi_graining) for diffs in zip(masks[:-1], masks[1:])]

    if clip.format.num_planes == 3:
        masks = [Bilinear.resample(join(mask, mask, mask), clip) for mask in masks]

    graineds = [grainer.grain(clip) if grainer else clip for grainer, *_ in norm_grainers]

    clips_merge = [
        clip.std.MaskedMerge(grained, mask) for grained, mask in zip(graineds, masks)
    ]

    return reduce(lambda x, y: y.std.MergeDiff(clip.std.MakeDiff(x)), clips_merge, clip)  # type: ignore