Skip to content

utils

EXPR_VARS module-attribute

EXPR_VARS = (alph := list(ascii_lowercase))[(idx := index('x')):] + alph[:idx]

Variables to access clips in core.std.Expr.

depth_func module-attribute

depth_func = depth

DitherType

Bases: CustomStrEnum

Enum for zimg_dither_type_e and fmtc dmode.

ATKINSON class-attribute instance-attribute

ATKINSON = 'atkinson'

Another error diffusion kernel. Generates distinct patterns but keeps clean the flat areas (noise modulation).

AUTO class-attribute instance-attribute

AUTO = 'auto'

Choose automatically.

ERROR_DIFFUSION class-attribute instance-attribute

ERROR_DIFFUSION = 'error_diffusion'

Floyd-Steinberg error diffusion.

ERROR_DIFFUSION_FMTC class-attribute instance-attribute

ERROR_DIFFUSION_FMTC = 'error_diffusion_fmtc'

Floyd-Steinberg error diffusion. Modified for serpentine scan (avoids worm artefacts).

NONE class-attribute instance-attribute

NONE = 'none'

Round to nearest.

ORDERED class-attribute instance-attribute

ORDERED = 'ordered'

Bayer patterned dither.

OSTROMOUKHOV class-attribute instance-attribute

OSTROMOUKHOV = 'ostromoukhov'

Another error diffusion kernel. Slow, available only for integer input at the moment. Avoids usual F-S artefacts.

QUASIRANDOM class-attribute instance-attribute

QUASIRANDOM = 'quasirandom'

Dither using quasirandom sequences. Good intermediary between void, cluster, and error diffusion algorithms.

RANDOM class-attribute instance-attribute

RANDOM = 'random'

Pseudo-random noise of magnitude 0.5.

SIERRA_2_4A class-attribute instance-attribute

SIERRA_2_4A = 'sierra_2_4a'

Another type of error diffusion. Quick and excellent quality, similar to Floyd-Steinberg.

STUCKI class-attribute instance-attribute

STUCKI = 'stucki'

Another error diffusion kernel. Preserves delicate edges better but distorts gradients.

VOID class-attribute instance-attribute

VOID = 'void'

A way to generate blue-noise dither and has a much better visual aspect than ordered dithering.

is_fmtc property

is_fmtc: bool

Whether the DitherType is applied through fmtc.

apply

apply(
    clip: VideoNode,
    fmt_out: VideoFormat,
    range_in: ColorRange,
    range_out: ColorRange,
) -> VideoNode

Apply the given DitherType to a clip.

Source code
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
def apply(
    self, clip: vs.VideoNode, fmt_out: vs.VideoFormat, range_in: ColorRange, range_out: ColorRange
) -> vs.VideoNode:
    """Apply the given DitherType to a clip."""

    from ..utils import get_video_format

    assert self != DitherType.AUTO, CustomValueError("Cannot apply AUTO.", self.__class__)

    fmt = get_video_format(clip)
    clip = ColorRange.ensure_presence(clip, range_in)

    if not self.is_fmtc:
        return clip.resize.Point(
            format=fmt_out.id, dither_type=self.value.lower(),
            range_in=range_in.value_zimg, range=range_out.value_zimg
        )

    if fmt.sample_type is vs.FLOAT:
        if self == DitherType.OSTROMOUKHOV:
            raise CustomValueError("Ostromoukhov can't be used for float input.", self.__class__)

        # Workaround because fmtc doesn't support FLOAT 16 input
        if fmt.bits_per_sample < 32:
            clip = DitherType.NONE.apply(clip, fmt.replace(bits_per_sample=32), range_in, range_out)

    return clip.fmtc.bitdepth(
        dmode=_dither_fmtc_types.get(self), bits=fmt_out.bits_per_sample,
        fulls=range_in is ColorRange.FULL, fulld=range_out is ColorRange.FULL
    )

should_dither staticmethod

should_dither(
    in_fmt: VideoFormatT | HoldsVideoFormatT,
    out_fmt: VideoFormatT | HoldsVideoFormatT,
    /,
    in_range: ColorRangeT | None = None,
    out_range: ColorRangeT | None = None,
) -> bool
should_dither(
    in_bits: int,
    out_bits: int,
    /,
    in_sample_type: SampleType | None = None,
    out_sample_type: SampleType | None = None,
    in_range: ColorRangeT | None = None,
    out_range: ColorRangeT | None = None,
) -> bool
should_dither(
    in_bits_or_fmt: int | VideoFormatT | HoldsVideoFormatT,
    out_bits_or_fmt: int | VideoFormatT | HoldsVideoFormatT,
    /,
    in_sample_type_or_range: SampleType | ColorRangeT | None = None,
    out_sample_type_or_range: SampleType | ColorRangeT | None = None,
    in_range: ColorRangeT | None = None,
    out_range: ColorRangeT | None = None,
) -> bool
Source code
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
@staticmethod  # type: ignore
def should_dither(
    in_bits_or_fmt: int | VideoFormatT | HoldsVideoFormatT,
    out_bits_or_fmt: int | VideoFormatT | HoldsVideoFormatT, /,
    in_sample_type_or_range: vs.SampleType | ColorRangeT | None = None,
    out_sample_type_or_range: vs.SampleType | ColorRangeT | None = None,
    in_range: ColorRangeT | None = None, out_range: ColorRangeT | None = None,
) -> bool:
    from ..utils import get_video_format

    in_fmt = get_video_format(in_bits_or_fmt, sample_type=in_sample_type_or_range)
    out_fmt = get_video_format(out_bits_or_fmt, sample_type=out_sample_type_or_range)

    in_range = ColorRange.from_param(in_range, (DitherType.should_dither, 'in_range'))
    out_range = ColorRange.from_param(out_range, (DitherType.should_dither, 'out_range'))

    if out_fmt.sample_type is vs.FLOAT:
        return False

    if in_fmt.sample_type is vs.FLOAT:
        return True

    if in_range != out_range:
        return True

    in_bits = in_fmt.bits_per_sample
    out_bits = out_fmt.bits_per_sample

    if in_bits == out_bits:
        return False

    if in_bits > out_bits:
        return True

    return in_range == ColorRange.FULL and (in_bits, out_bits) != (8, 16)

depth

depth(
    clip: VideoNode,
    bitdepth: VideoFormatT | HoldsVideoFormatT | int | None = None,
    /,
    sample_type: int | SampleType | None = None,
    *,
    range_in: ColorRangeT | None = None,
    range_out: ColorRangeT | None = None,
    dither_type: str | DitherType = AUTO,
) -> VideoNode

A convenience bitdepth conversion function using only internal plugins if possible.

This uses exclusively internal plugins except for specific dither_types. To check whether your DitherType uses fmtc, use DitherType.is_fmtc.

.. code-block:: python

>>> src_8 = vs.core.std.BlankClip(format=vs.YUV420P8)
>>> src_10 = depth(src_8, 10)
>>> src_10.format.name
'YUV420P10'

.. code-block:: python

>>> src2_10 = vs.core.std.BlankClip(format=vs.RGB30)
>>> src2_8 = depth(src2_10, 8, dither_type=Dither.RANDOM)  # override default dither behavior
>>> src2_8.format.name
'RGB24'

Parameters:

  • clip

    (VideoNode) –

    Input clip.

  • bitdepth

    (VideoFormatT | HoldsVideoFormatT | int | None, default: None ) –

    Desired bitdepth of the output clip.

  • sample_type

    (int | SampleType | None, default: None ) –

    Desired sample type of output clip. Allows overriding default float/integer behavior. Accepts vapoursynth.SampleType enums vapoursynth.INTEGER and vapoursynth.FLOAT or their values, 0 and 1 respectively.

  • range_in

    (ColorRangeT | None, default: None ) –

    Input pixel range (defaults to input clip's range).

  • range_out

    (ColorRangeT | None, default: None ) –

    Output pixel range (defaults to input clip's range).

  • dither_type

    (str | DitherType, default: AUTO ) –

    Dithering algorithm. Allows overriding default dithering behavior. See :py:class:Dither. Defaults to :attr:Dither.ERROR_DIFFUSION, or Floyd-Steinberg error diffusion, when downsampling, converting between ranges, or upsampling full range input. Defaults to :attr:Dither.NONE, or round to nearest, otherwise. See :py:func:Dither.should_dither for more information.

Returns:

  • VideoNode

    Converted clip with desired bit depth and sample type. ColorFamily will be same as input.

Source code
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
@disallow_variable_format
def depth(
    clip: vs.VideoNode, bitdepth: VideoFormatT | HoldsVideoFormatT | int | None = None, /,
    sample_type: int | vs.SampleType | None = None, *,
    range_in: ColorRangeT | None = None, range_out: ColorRangeT | None = None,
    dither_type: str | DitherType = DitherType.AUTO,
) -> vs.VideoNode:
    """
    A convenience bitdepth conversion function using only internal plugins if possible.

    This uses exclusively internal plugins except for specific dither_types.
    To check whether your DitherType uses fmtc, use `DitherType.is_fmtc`.

    .. code-block:: python

        >>> src_8 = vs.core.std.BlankClip(format=vs.YUV420P8)
        >>> src_10 = depth(src_8, 10)
        >>> src_10.format.name
        'YUV420P10'

    .. code-block:: python

        >>> src2_10 = vs.core.std.BlankClip(format=vs.RGB30)
        >>> src2_8 = depth(src2_10, 8, dither_type=Dither.RANDOM)  # override default dither behavior
        >>> src2_8.format.name
        'RGB24'

    :param clip:            Input clip.
    :param bitdepth:        Desired bitdepth of the output clip.
    :param sample_type:     Desired sample type of output clip. Allows overriding default float/integer behavior.
                            Accepts ``vapoursynth.SampleType`` enums ``vapoursynth.INTEGER`` and ``vapoursynth.FLOAT``
                            or their values, ``0`` and ``1`` respectively.
    :param range_in:        Input pixel range (defaults to input `clip`'s range).
    :param range_out:       Output pixel range (defaults to input `clip`'s range).
    :param dither_type:     Dithering algorithm. Allows overriding default dithering behavior. See :py:class:`Dither`.

                            Defaults to :attr:`Dither.ERROR_DIFFUSION`, or Floyd-Steinberg error diffusion,
                            when downsampling, converting between ranges, or upsampling full range input.
                            Defaults to :attr:`Dither.NONE`, or round to nearest, otherwise.
                            See :py:func:`Dither.should_dither` for more information.

    :return:                Converted clip with desired bit depth and sample type.
                            ``ColorFamily`` will be same as input.
    """

    from ..utils import get_video_format
    from .funcs import fallback

    in_fmt = get_video_format(clip)
    out_fmt = get_video_format(fallback(bitdepth, clip), sample_type=sample_type)

    range_out = ColorRange.from_param_or_video(range_out, clip)
    range_in = ColorRange.from_param_or_video(range_in, clip)

    if (
        in_fmt.bits_per_sample, in_fmt.sample_type, range_in
    ) == (
        out_fmt.bits_per_sample, out_fmt.sample_type, range_out
    ):
        return clip

    dither_type = DitherType(dither_type)

    if dither_type is DitherType.AUTO:
        should_dither = DitherType.should_dither(in_fmt, out_fmt, range_in, range_out)

        if hasattr(clip, "fmtc"):
            dither_type = DitherType.VOID
        else:
            dither_type = DitherType.ERROR_DIFFUSION if out_fmt.bits_per_sample == 8 else DitherType.ORDERED
        dither_type = dither_type if should_dither else DitherType.NONE

    new_format = in_fmt.replace(
        bits_per_sample=out_fmt.bits_per_sample, sample_type=out_fmt.sample_type
    )

    return dither_type.apply(clip, new_format, range_in, range_out)

frame2clip

frame2clip(frame: VideoFrame) -> VideoNode

Convert a VideoFrame to a VideoNode.

Parameters:

  • frame

    (VideoFrame) –

    Input frame.

Returns:

  • VideoNode

    1-frame long VideoNode of the input frame.

Source code
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
def frame2clip(frame: vs.VideoFrame) -> vs.VideoNode:
    """
    Convert a VideoFrame to a VideoNode.

    :param frame:       Input frame.

    :return:            1-frame long VideoNode of the input frame.
    """

    key = hash((frame.width, frame.height, frame.format.id))

    if _f2c_cache.get(key, None) is None:
        _f2c_cache[key] = blank_clip = vs.core.std.BlankClip(
            None, frame.width, frame.height,
            frame.format.id, 1, 1, 1,
            [0] * frame.format.num_planes,
            True
        )
    else:
        blank_clip = _f2c_cache[key]

    frame_cp = frame.copy()

    return blank_clip.std.ModifyFrame(blank_clip, lambda n, f: frame_cp)

get_b

get_b(clip: VideoNode) -> VideoNode

Extract the blue plane of the given clip.

Parameters:

  • clip

    (VideoNode) –

    Input clip.

Returns:

  • VideoNode

    B plane of the input clip.

Raises:

  • CustomValueError

    Clip is not RGB.

Source code
438
439
440
441
442
443
444
445
446
447
448
449
450
451
def get_b(clip: vs.VideoNode, /) -> vs.VideoNode:
    """
    Extract the blue plane of the given clip.

    :param clip:                Input clip.

    :return:                    B plane of the input clip.

    :raises CustomValueError:   Clip is not RGB.
    """

    InvalidColorFamilyError.check(clip, vs.RGB, get_b)

    return plane(clip, 2)

get_g

get_g(clip: VideoNode) -> VideoNode

Extract the green plane of the given clip.

Parameters:

  • clip

    (VideoNode) –

    Input clip.

Returns:

  • VideoNode

    G plane of the input clip.

Raises:

  • CustomValueError

    Clip is not RGB.

Source code
422
423
424
425
426
427
428
429
430
431
432
433
434
435
def get_g(clip: vs.VideoNode, /) -> vs.VideoNode:
    """
    Extract the green plane of the given clip.

    :param clip:                Input clip.

    :return:                    G plane of the input clip.

    :raises CustomValueError:   Clip is not RGB.
    """

    InvalidColorFamilyError.check(clip, vs.RGB, get_g)

    return plane(clip, 1)

get_r

get_r(clip: VideoNode) -> VideoNode

Extract the red plane of the given clip.

Parameters:

  • clip

    (VideoNode) –

    Input clip.

Returns:

  • VideoNode

    R plane of the input clip.

Raises:

  • CustomValueError

    Clip is not RGB.

Source code
406
407
408
409
410
411
412
413
414
415
416
417
418
419
def get_r(clip: vs.VideoNode, /) -> vs.VideoNode:
    """
    Extract the red plane of the given clip.

    :param clip:                Input clip.

    :return:                    R plane of the input clip.

    :raises CustomValueError:   Clip is not RGB.
    """

    InvalidColorFamilyError.check(clip, vs.RGB, get_r)

    return plane(clip, 0)

get_u

get_u(clip: VideoNode) -> VideoNode

Extract the first chroma (U) plane of the given clip.

Parameters:

  • clip

    (VideoNode) –

    Input clip.

Returns:

  • VideoNode

    Y plane of the input clip.

Raises:

  • CustomValueError

    Clip is not YUV.

Source code
374
375
376
377
378
379
380
381
382
383
384
385
386
387
def get_u(clip: vs.VideoNode, /) -> vs.VideoNode:
    """
    Extract the first chroma (U) plane of the given clip.

    :param clip:                Input clip.

    :return:                    Y plane of the input clip.

    :raises CustomValueError:   Clip is not YUV.
    """

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

    return plane(clip, 1)

get_v

get_v(clip: VideoNode) -> VideoNode

Extract the second chroma (V) plane of the given clip.

Parameters:

  • clip

    (VideoNode) –

    Input clip.

Returns:

  • VideoNode

    V plane of the input clip.

Raises:

  • CustomValueError

    Clip is not YUV.

Source code
390
391
392
393
394
395
396
397
398
399
400
401
402
403
def get_v(clip: vs.VideoNode, /) -> vs.VideoNode:
    """
    Extract the second chroma (V) plane of the given clip.

    :param clip:                Input clip.

    :return:                    V plane of the input clip.

    :raises CustomValueError:   Clip is not YUV.
    """

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

    return plane(clip, 2)

get_y

get_y(clip: VideoNode) -> VideoNode

Extract the luma (Y) plane of the given clip.

Parameters:

  • clip

    (VideoNode) –

    Input clip.

Returns:

  • VideoNode

    Y plane of the input clip.

Raises:

  • CustomValueError

    Clip is not GRAY or YUV.

Source code
358
359
360
361
362
363
364
365
366
367
368
369
370
371
def get_y(clip: vs.VideoNode, /) -> vs.VideoNode:
    """
    Extract the luma (Y) plane of the given clip.

    :param clip:                Input clip.

    :return:                    Y plane of the input clip.

    :raises CustomValueError:   Clip is not GRAY or YUV.
    """

    InvalidColorFamilyError.check(clip, [vs.YUV, vs.GRAY], get_y)

    return plane(clip, 0)

insert_clip

insert_clip(
    clip: VideoNode, /, insert: VideoNode, start_frame: int, strict: bool = True
) -> VideoNode

Replace frames of a longer clip with those of a shorter one.

The insert clip may NOT exceed the final frame of the input clip. This limitation can be circumvented by setting strict=False.

Parameters:

  • clip

    (VideoNode) –

    Input clip.

  • insert

    (VideoNode) –

    Clip to insert into the input clip.

  • start_frame

    (int) –

    Frame to start inserting from.

  • strict

    (bool, default: True ) –

    Throw an error if the inserted clip exceeds the final frame of the input clip. If False, truncate the inserted clip instead. Default: True.

Returns:

  • VideoNode

    Clip with frames replaced by the insert clip.

Raises:

  • CustomValueError

    Insert clip is too long, strict=False, and exceeds the final frame of the input clip.

Source code
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
def insert_clip(clip: vs.VideoNode, /, insert: vs.VideoNode, start_frame: int, strict: bool = True) -> vs.VideoNode:
    """
    Replace frames of a longer clip with those of a shorter one.

    The insert clip may NOT exceed the final frame of the input clip.
    This limitation can be circumvented by setting `strict=False`.

    :param clip:                Input clip.
    :param insert:              Clip to insert into the input clip.
    :param start_frame:         Frame to start inserting from.
    :param strict:              Throw an error if the inserted clip exceeds the final frame of the input clip.
                                If False, truncate the inserted clip instead.
                                Default: True.

    :return:                    Clip with frames replaced by the insert clip.

    :raises CustomValueError:   Insert clip is too long, ``strict=False``,
                                and exceeds the final frame of the input clip.
    """

    if start_frame == 0:
        return insert + clip[insert.num_frames:]

    pre = clip[:start_frame]
    insert_diff = (start_frame + insert.num_frames) - clip.num_frames

    if insert_diff == 0:
        return pre + insert

    if insert_diff < 0:
        return pre + insert + clip[insert_diff:]

    if strict:
        raise ClipLengthError(
            'Inserted clip is too long and exceeds the final frame of the input clip.',
            insert_clip, {'clip': clip.num_frames, 'diff': insert_diff}
        )

    return pre + insert[:-insert_diff]

join

join(
    luma: VideoNode, chroma: VideoNode, family: ColorFamily | None = None
) -> VideoNode
join(
    y: VideoNode, u: VideoNode, v: VideoNode, family: Literal[YUV]
) -> VideoNode
join(
    y: VideoNode,
    u: VideoNode,
    v: VideoNode,
    alpha: VideoNode,
    family: Literal[YUV],
) -> VideoNode
join(
    r: VideoNode, g: VideoNode, b: VideoNode, family: Literal[RGB]
) -> VideoNode
join(
    r: VideoNode,
    g: VideoNode,
    b: VideoNode,
    alpha: VideoNode,
    family: Literal[RGB],
) -> VideoNode
join(*planes: VideoNode, family: ColorFamily | None = None) -> VideoNode
join(
    planes: Iterable[VideoNode], family: ColorFamily | None = None
) -> VideoNode
join(
    planes: Mapping[PlanesT, VideoNode | None],
    family: ColorFamily | None = None,
) -> VideoNode
join(*_planes: Any, **kwargs: Any) -> VideoNode
Source code
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
def join(*_planes: Any, **kwargs: Any) -> vs.VideoNode:
    from ..functions import flatten_vnodes, to_arr
    from ..utils import get_color_family, get_video_format

    family: vs.ColorFamily | None = kwargs.get('family', None)

    if isinstance(_planes[-1], vs.ColorFamily):
        family = _planes[-1]
        _planes = _planes[:-1]

    if isinstance(_planes[0], Mapping):
        planes_map = dict[int, vs.VideoNode]()

        for p_key, node in _planes[0].items():
            if node is None:
                continue

            if p_key is None:
                planes_map |= {i: n for i, n in enumerate(flatten_vnodes(node, split_planes=True))}
            else:
                planes_map |= {i: plane(node, min(i, node.format.num_planes - 1)) for i in to_arr(p_key)}

        return join(*(planes_map[i] for i in sorted(planes_map.keys())))

    planes = list[vs.VideoNode](_planes[0] if (
        isinstance(_planes[0], Iterable) and not isinstance(_planes[0], vs.VideoNode)
    ) else _planes)

    n_clips = len(planes)

    if not n_clips:
        raise CustomIndexError('Not enough clips/planes passed!', join)

    if n_clips == 1 and (family is None or family is (planes[0].format and planes[0].format.color_family)):
        return planes[0]

    if family is None:
        family = get_color_family(planes[0])

    if n_clips == 2:
        other_family = get_color_family(planes[1])

        if family in {vs.GRAY, vs.YUV}:
            InvalidColorFamilyError.check(
                other_family, vs.YUV, join, '"chroma" clip must be {correct} color family, not {wrong}!'
            )

            if family is vs.GRAY:
                planes[0] = get_y(planes[0])

            return vs.core.std.ShufflePlanes(planes, [0, 1, 2], other_family)

    if n_clips in {3, 4}:
        if family is vs.GRAY:
            for pplane in planes[:3]:
                if (fmt := get_video_format(pplane)).num_planes > 1:
                    family = fmt.color_family
                    break
            else:
                matrix = Matrix.from_video(planes[0])
                family = vs.RGB if matrix is Matrix.RGB else vs.YUV

        clip = vs.core.std.ShufflePlanes(planes[:3], [0, 0, 0], family)

        if n_clips == 4:
            clip = clip.std.ClipToProp(planes[-1], '_Alpha')

        return clip
    elif n_clips > 4:
        raise CustomValueError('Too many clips or planes passed!', join)

    raise CustomValueError('Not enough clips or planes passed!', join)

limiter

limiter(
    clip: VideoNode,
    /,
    min_val: float | Sequence[float] | None = None,
    max_val: float | Sequence[float] | None = None,
    *,
    tv_range: bool = False,
    func: FuncExceptT | None = None,
) -> VideoNode
limiter(
    _func: F_VD,
    /,
    min_val: float | Sequence[float] | None = None,
    max_val: float | Sequence[float] | None = None,
    *,
    tv_range: bool = False,
    func: FuncExceptT | None = None,
) -> F_VD
limiter(
    *,
    min_val: float | Sequence[float] | None = None,
    max_val: float | Sequence[float] | None = None,
    tv_range: bool = False,
    func: FuncExceptT | None = None
) -> Callable[[F_VD], F_VD]
limiter(
    clip: VideoNode | F_VD | None = None,
    /,
    min_val: float | Sequence[float] | None = None,
    max_val: float | Sequence[float] | None = None,
    *,
    tv_range: bool = False,
    func: FuncExceptT | None = None,
) -> VideoNode | F_VD | Callable[[F_VD], F_VD]

Wraps vs-zip <https://github.com/dnjulek/vapoursynth-zip>.Limiter but only processes if clip format is not integer, a min/max val is specified or tv_range is True.

Parameters:

  • clip

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

    Clip to process.

  • min_val

    (float | Sequence[float] | None, default: None ) –

    Lower bound. Defaults to the lowest allowed value for the input. Can be specified for each plane individually.

  • max_val

    (float | Sequence[float] | None, default: None ) –

    Upper bound. Defaults to the highest allowed value for the input. Can be specified for each plane individually.

  • tv_range

    (bool, default: False ) –

    Changes min/max defaults values to LIMITED.

  • func

    (FuncExceptT | None, default: None ) –

    Function returned for custom error handling. This should only be set by VS package developers.

Returns:

Source code
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
def limiter(
    clip: vs.VideoNode | F_VD | None = None,
    /,
    min_val: float | Sequence[float] | None = None,
    max_val: float | Sequence[float] | None = None,
    *,
    tv_range: bool = False,
    func: FuncExceptT | None = None
) -> vs.VideoNode | F_VD | Callable[[F_VD], F_VD]:
    """
    Wraps `vs-zip <https://github.com/dnjulek/vapoursynth-zip>`.Limiter but only processes
    if clip format is not integer, a min/max val is specified or tv_range is True.

    :param clip:        Clip to process.
    :param min_val:     Lower bound. Defaults to the lowest allowed value for the input.
                        Can be specified for each plane individually.
    :param max_val:     Upper bound. Defaults to the highest allowed value for the input.
                        Can be specified for each plane individually.
    :param tv_range:    Changes min/max defaults values to LIMITED.
    :param func:        Function returned for custom error handling.
                        This should only be set by VS package developers.
    :return:            Clamped clip.
    """
    if callable(clip):
        @wraps(clip)
        def _wrapper(*args: Any, **kwargs: Any) -> vs.VideoNode:
            return limiter(clip(*args, **kwargs), min_val, max_val, tv_range=tv_range, func=func or clip)

        return cast(F_VD, _wrapper)

    func = func or limiter

    if clip is None:
        return cast(
            Callable[[F_VD], F_VD],
            partial(limiter, min_val=min_val, max_val=max_val, tv_range=tv_range, func=func)
        )

    assert check_variable(clip, func)

    if all([
        clip.format.sample_type == vs.INTEGER,
        min_val is None,
        max_val is None,
        tv_range is False
    ]):
        return clip

    if not (min_val == max_val is None):
        from ..utils import get_lowest_values, get_peak_values

        min_val = normalize_seq(min_val or get_lowest_values(clip, clip), clip.format.num_planes)
        max_val = normalize_seq(max_val or get_peak_values(clip, clip), clip.format.num_planes)

    return clip.vszip.Limiter(min_val, max_val, tv_range)

plane

plane(clip: VideoNode, index: int, /, strict: bool = True) -> VideoNode

Extract a plane from the given clip.

Parameters:

  • clip

    (VideoNode) –

    Input clip.

  • index

    (int) –

    Index of the plane to extract.

Returns:

  • VideoNode

    Grayscale clip of the clip's plane.

Source code
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
def plane(clip: vs.VideoNode, index: int, /, strict: bool = True) -> vs.VideoNode:
    """
    Extract a plane from the given clip.

    :param clip:        Input clip.
    :param index:       Index of the plane to extract.

    :return:            Grayscale clip of the clip's plane.
    """

    assert check_variable_format(clip, plane)

    if clip.format.num_planes == 1 and index == 0:
        return clip

    if not strict:
        if clip.format.color_family is vs.RGB:
            clip = clip.std.RemoveFrameProps('_Matrix')

    return vs.core.std.ShufflePlanes(clip, index, vs.GRAY)

split

split(clip: VideoNode) -> list[VideoNode]

Split a clip into a list of individual planes.

Parameters:

  • clip

    (VideoNode) –

    Input clip.

Returns:

  • list[VideoNode]

    List of individual planes.

Source code
702
703
704
705
706
707
708
709
710
711
712
713
714
715
def split(clip: vs.VideoNode, /) -> list[vs.VideoNode]:
    """
    Split a clip into a list of individual planes.

    :param clip:    Input clip.

    :return:        List of individual planes.
    """

    assert check_variable_format(clip, split)

    return [clip] if clip.format.num_planes == 1 else [
        plane(clip, i, False) for i in range(clip.format.num_planes)
    ]

stack_clips

stack_clips(
    clips: Sequence[
        VideoNode
        | Sequence[
            VideoNode
            | Sequence[
                VideoNode
                | Sequence[
                    VideoNode | Sequence[VideoNode | Sequence[VideoNode]]
                ]
            ]
        ]
    ],
) -> VideoNode

Stack clips in the following repeating order: hor->ver->hor->ver->...

Parameters:

Returns:

  • VideoNode

    Stacked clips.

Source code
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
def stack_clips(
    clips: Sequence[vs.VideoNode | Sequence[vs.VideoNode | Sequence[
        vs.VideoNode | Sequence[vs.VideoNode | Sequence[vs.VideoNode | Sequence[vs.VideoNode]]]
    ]]]
) -> vs.VideoNode:
    """
    Stack clips in the following repeating order: hor->ver->hor->ver->...

    :param clips:   Sequence of clips to stack recursively.

    :return:        Stacked clips.
    """

    return vs.core.std.StackHorizontal([
        inner_clips if isinstance(inner_clips, vs.VideoNode) else (
            vs.core.std.StackVertical([
                clipa if isinstance(clipa, vs.VideoNode) else stack_clips(clipa)
                for clipa in inner_clips
            ])
        )
        for inner_clips in clips
    ])