Skip to content

utils

Classes:

  • DitherType

    Enum for zimg_dither_type_e and fmtc dmode.

Functions:

  • depth

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

  • frame2clip

    Convert a VideoFrame to a VideoNode.

  • get_b

    Extract the blue plane of the given clip.

  • get_g

    Extract the green plane of the given clip.

  • get_r

    Extract the red plane of the given clip.

  • get_u

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

  • get_v

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

  • get_y

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

  • insert_clip

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

  • join

    General interface to combine clips or planes into a single clip.

  • limiter

    Wraps vs-zip <https://github.com/dnjulek/vapoursynth-zip>.Limiter but only processes

  • plane

    Extract a plane from the given clip.

  • sc_detect
  • split

    Split a clip into a list of individual planes.

  • stack_clips

    Recursively stack clips in alternating directions: horizontal → vertical → horizontal → ...

Attributes:

EXPR_VARS module-attribute

EXPR_VARS = [
    "x",
    "y",
    "z",
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
]

Variables to access clips in Expr.

depth_func module-attribute

depth_func = depth

DitherType

Bases: CustomStrEnum

Enum for zimg_dither_type_e and fmtc dmode.

Methods:

Attributes:

  • ATKINSON

    Another error diffusion kernel.

  • AUTO

    Choose automatically.

  • ERROR_DIFFUSION

    Floyd-Steinberg error diffusion.

  • ERROR_DIFFUSION_FMTC

    Floyd-Steinberg error diffusion.

  • NONE

    Round to nearest.

  • ORDERED

    Bayer patterned dither.

  • OSTROMOUKHOV

    Another error diffusion kernel.

  • QUASIRANDOM

    Dither using quasirandom sequences.

  • RANDOM

    Pseudo-random noise of magnitude 0.5.

  • SIERRA_2_4A

    Another type of error diffusion.

  • STUCKI

    Another error diffusion kernel.

  • VOID

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

  • is_fmtc (bool) –

    Whether the DitherType is applied through fmtc.

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,
) -> ConstantFormatVideoNode

Apply the given DitherType to a clip.

Source code in vstools/functions/utils.py
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
def apply(
    self, clip: vs.VideoNode, fmt_out: vs.VideoFormat, range_in: ColorRange, range_out: ColorRange
) -> ConstantFormatVideoNode:
    """
    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: VideoFormatLike | HoldsVideoFormat,
    out_fmt: VideoFormatLike | HoldsVideoFormat,
    /,
    in_range: ColorRangeLike | None = None,
    out_range: ColorRangeLike | None = None,
) -> bool
should_dither(
    in_bits: int,
    out_bits: int,
    /,
    in_range: ColorRangeLike | None = None,
    out_range: ColorRangeLike | None = None,
    in_sample_type: SampleType | None = None,
    out_sample_type: SampleType | None = None,
) -> bool
should_dither(
    in_bits_or_fmt: int | VideoFormatLike | HoldsVideoFormat,
    out_bits_or_fmt: int | VideoFormatLike | HoldsVideoFormat,
    /,
    in_range: ColorRangeLike | None = None,
    out_range: ColorRangeLike | None = None,
    in_sample_type: SampleType | None = None,
    out_sample_type: SampleType | None = None,
) -> bool
Source code in vstools/functions/utils.py
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
@staticmethod
def should_dither(
    in_bits_or_fmt: int | VideoFormatLike | HoldsVideoFormat,
    out_bits_or_fmt: int | VideoFormatLike | HoldsVideoFormat,
    /,
    in_range: ColorRangeLike | None = None,
    out_range: ColorRangeLike | None = None,
    in_sample_type: vs.SampleType | None = None,
    out_sample_type: vs.SampleType | None = None,
) -> bool:
    from ..utils import get_video_format

    in_fmt = get_video_format(in_bits_or_fmt, sample_type=in_sample_type)
    out_fmt = get_video_format(out_bits_or_fmt, sample_type=out_sample_type)

    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 bool(out_bits % in_bits)

depth

depth(
    clip: VideoNode,
    bitdepth: VideoFormatLike | HoldsVideoFormat | int | None = None,
    /,
    sample_type: int | SampleType | None = None,
    *,
    range_in: ColorRangeLike | None = None,
    range_out: ColorRangeLike | None = None,
    dither_type: str | DitherType = AUTO,
) -> ConstantFormatVideoNode

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.

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

>>> 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

    (VideoFormatLike | HoldsVideoFormat | 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

    (ColorRangeLike | None, default: None ) –

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

  • range_out

    (ColorRangeLike | 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 Dither.

    When integer output is desired but the conversion may produce fractional values, defaults to DitherType.VOID if it is available via the fmtc VapourSynth plugin, or to Floyd-Steinberg DitherType.ERROR_DIFFUSION for 8-bit output or DitherType.ORDERED for higher bit depths. In other cases, defaults to DitherType.NONE, or round to nearest. See DitherType.should_dither for more information.

Returns:

  • ConstantFormatVideoNode

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

Source code in vstools/functions/utils.py
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
def depth(
    clip: vs.VideoNode,
    bitdepth: VideoFormatLike | HoldsVideoFormat | int | None = None,
    /,
    sample_type: int | vs.SampleType | None = None,
    *,
    range_in: ColorRangeLike | None = None,
    range_out: ColorRangeLike | None = None,
    dither_type: str | DitherType = DitherType.AUTO,
) -> ConstantFormatVideoNode:
    """
    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`.

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

        >>> 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'

    Args:
        clip: Input clip.
        bitdepth: Desired bitdepth of the output clip.
        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.
        range_in: Input pixel range (defaults to input `clip`'s range).
        range_out: Output pixel range (defaults to input `clip`'s range).
        dither_type: Dithering algorithm. Allows overriding default dithering behavior.
            See [Dither][vstools.DitherType].

            When integer output is desired but the conversion may produce fractional values,
            defaults to DitherType.VOID if it is available via the fmtc VapourSynth plugin,
            or to Floyd-Steinberg DitherType.ERROR_DIFFUSION for 8-bit output
            or DitherType.ORDERED for higher bit depths.
            In other cases, defaults to DitherType.NONE, or round to nearest.
            See [DitherType.should_dither][vstools.DitherType.should_dither] for more information.

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

    from ..utils import get_video_format

    assert check_variable_format(clip, depth)

    in_fmt = get_video_format(clip)
    out_fmt = get_video_format(bitdepth or 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) -> ConstantFormatVideoNode

Convert a VideoFrame to a VideoNode.

Parameters:

  • frame

    (VideoFrame) –

    Input frame.

Returns:

  • ConstantFormatVideoNode

    1-frame long VideoNode of the input frame.

Source code in vstools/functions/utils.py
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
def frame2clip(frame: vs.VideoFrame) -> ConstantFormatVideoNode:
    """
    Convert a VideoFrame to a VideoNode.

    Args:
        frame: Input frame.

    Returns:
        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 vs.core.std.ModifyFrame(blank_clip, blank_clip, lambda n, f: frame_cp)

get_b

get_b(clip: VideoNode) -> ConstantFormatVideoNode

Extract the blue plane of the given clip.

Parameters:

  • clip

    (VideoNode) –

    Input clip.

Returns:

  • ConstantFormatVideoNode

    B plane of the input clip.

Raises:

  • CustomValueError

    Clip is not RGB.

Source code in vstools/functions/utils.py
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
def get_b(clip: vs.VideoNode, /) -> ConstantFormatVideoNode:
    """
    Extract the blue plane of the given clip.

    Args:
        clip: Input clip.

    Returns:
        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) -> ConstantFormatVideoNode

Extract the green plane of the given clip.

Parameters:

  • clip

    (VideoNode) –

    Input clip.

Returns:

  • ConstantFormatVideoNode

    G plane of the input clip.

Raises:

  • CustomValueError

    Clip is not RGB.

Source code in vstools/functions/utils.py
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
def get_g(clip: vs.VideoNode, /) -> ConstantFormatVideoNode:
    """
    Extract the green plane of the given clip.

    Args:
        clip: Input clip.

    Returns:
        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) -> ConstantFormatVideoNode

Extract the red plane of the given clip.

Parameters:

  • clip

    (VideoNode) –

    Input clip.

Returns:

  • ConstantFormatVideoNode

    R plane of the input clip.

Raises:

  • CustomValueError

    Clip is not RGB.

Source code in vstools/functions/utils.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
def get_r(clip: vs.VideoNode, /) -> ConstantFormatVideoNode:
    """
    Extract the red plane of the given clip.

    Args:
        clip: Input clip.

    Returns:
        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) -> ConstantFormatVideoNode

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

Parameters:

  • clip

    (VideoNode) –

    Input clip.

Returns:

  • ConstantFormatVideoNode

    Y plane of the input clip.

Raises:

  • CustomValueError

    Clip is not YUV.

Source code in vstools/functions/utils.py
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
def get_u(clip: vs.VideoNode, /) -> ConstantFormatVideoNode:
    """
    Extract the first chroma (U) plane of the given clip.

    Args:
        clip: Input clip.

    Returns:
        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) -> ConstantFormatVideoNode

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

Parameters:

  • clip

    (VideoNode) –

    Input clip.

Returns:

  • ConstantFormatVideoNode

    V plane of the input clip.

Raises:

  • CustomValueError

    Clip is not YUV.

Source code in vstools/functions/utils.py
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
def get_v(clip: vs.VideoNode, /) -> ConstantFormatVideoNode:
    """
    Extract the second chroma (V) plane of the given clip.

    Args:
        clip: Input clip.

    Returns:
        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) -> ConstantFormatVideoNode

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

Parameters:

  • clip

    (VideoNode) –

    Input clip.

Returns:

  • ConstantFormatVideoNode

    Y plane of the input clip.

Raises:

  • CustomValueError

    Clip is not GRAY or YUV.

Source code in vstools/functions/utils.py
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
def get_y(clip: vs.VideoNode, /) -> ConstantFormatVideoNode:
    """
    Extract the luma (Y) plane of the given clip.

    Args:
        clip: Input clip.

    Returns:
        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
) -> ConstantFormatVideoNode

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:

  • ConstantFormatVideoNode

    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 in vstools/functions/utils.py
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
def insert_clip(
    clip: vs.VideoNode, /, insert: vs.VideoNode, start_frame: int, strict: bool = True
) -> ConstantFormatVideoNode:
    """
    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`.

    Args:
        clip: Input clip.
        insert: Clip to insert into the input clip.
        start_frame: Frame to start inserting from.
        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.

    Returns:
        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 vs.core.std.Splice([insert, clip[insert.num_frames :]])

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

    if insert_diff == 0:
        return vs.core.std.Splice([pre, insert])

    if insert_diff < 0:
        return vs.core.std.Splice([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 vs.core.std.Splice([pre, insert[:-insert_diff]])

join

join(
    luma: VideoNode,
    chroma: VideoNode,
    /,
    *,
    prop_src: VideoNode | SupportsIndex | None = ...,
) -> ConstantFormatVideoNode
join(
    plane0: VideoNode,
    plane1: VideoNode,
    plane2: VideoNode,
    alpha: VideoNode | None = None,
    /,
    *,
    family: ColorFamily = YUV,
    prop_src: VideoNode | SupportsIndex | None = ...,
) -> ConstantFormatVideoNode
join(
    planes: Sequence[VideoNode],
    family: ColorFamily = YUV,
    /,
    *,
    prop_src: VideoNode | SupportsIndex | None = ...,
) -> ConstantFormatVideoNode
join(
    clips: Mapping[Planes, VideoNode | None],
    family: ColorFamily = YUV,
    /,
    *,
    prop_src: VideoNode | SupportsIndex | None = ...,
) -> ConstantFormatVideoNode
join(
    clips: VideoNode | Sequence[VideoNode] | Mapping[Planes, VideoNode | None],
    plane1_or_family: VideoNode | ColorFamily | None = None,
    plane2: VideoNode | None = None,
    alpha: VideoNode | None = None,
    /,
    *,
    family: ColorFamily = YUV,
    prop_src: VideoNode | SupportsIndex | None = None,
) -> VideoNode

General interface to combine clips or planes into a single clip.

Parameters:

  • clips

    (VideoNode | Sequence[VideoNode] | Mapping[Planes, VideoNode | None]) –

    First plane, sequence of single-plane clips or mapping of planes to clips:

  • plane1_or_family

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

    Chroma clip, second plane or color family, depending on usage.

  • plane2

    (VideoNode | None, default: None ) –

    Third plane when combining three planes.

  • alpha

    (VideoNode | None, default: None ) –

    Optional alpha clip.

  • family

    (ColorFamily, default: YUV ) –

    Output color family. Defaults to YUV.

  • prop_src

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

    Optional clip or index to copy frame properties from.

Raises:

  • CustomIndexError

    Invalid plane index.

  • CustomTypeError

    Invalid input type.

Returns:

  • VideoNode

    Clip with combined planes.

Source code in vstools/functions/utils.py
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
def join(
    clips: vs.VideoNode | Sequence[vs.VideoNode] | Mapping[Planes, vs.VideoNode | None],
    plane1_or_family: vs.VideoNode | vs.ColorFamily | None = None,
    plane2: vs.VideoNode | None = None,
    alpha: vs.VideoNode | None = None,
    /,
    *,
    family: vs.ColorFamily = vs.ColorFamily.YUV,
    prop_src: vs.VideoNode | SupportsIndex | None = None,
) -> vs.VideoNode:
    """
    General interface to combine clips or planes into a single clip.

    Args:
        clips: First plane, sequence of single-plane clips or mapping of planes to clips:
        plane1_or_family: Chroma clip, second plane or color family, depending on usage.
        plane2: Third plane when combining three planes.
        alpha: Optional alpha clip.
        family: Output color family. Defaults to YUV.
        prop_src: Optional clip or index to copy frame properties from.

    Raises:
        CustomIndexError: Invalid plane index.
        CustomTypeError: Invalid input type.

    Returns:
        Clip with combined planes.
    """
    if isinstance(clips, Mapping):
        from ..functions import flatten_vnodes

        clips_map = dict[int, vs.VideoNode]()

        for p_key, node in clips.items():
            if node is None:
                continue

            if p_key is None:
                clips_map.update(enumerate(flatten_vnodes(node, split_planes=True)))
            else:
                clips_map.update((i, plane(node, i)) for i in to_arr(p_key))

        return join([clips_map[i] for i in sorted(clips_map)], family, prop_src=prop_src)

    if not isinstance(clips, vs.VideoNode):
        if isinstance(plane1_or_family, vs.ColorFamily):
            family = plane1_or_family

        if (n_clips := len(clips)) == 1:
            return clips[0]
        if n_clips in (2, 3, 4):
            return join(*clips, family=family, prop_src=prop_src)
        else:
            raise CustomIndexError("Too many or not enough clips/planes passed!", join, n_clips)

    if not isinstance(plane1_or_family, vs.VideoNode):
        raise CustomTypeError(func=join)

    if not plane2:
        InvalidColorFamilyError.check(
            (family, plane1_or_family),
            vs.YUV,
            join,
            "When combining two clips, color family and chroma clip must be {correct}, not {wrong}.",
        )

        clips = [clips, plane1_or_family]
        planes = [0, 1, 2]

    else:
        clips = [clips, plane1_or_family, plane2]
        planes = [0, 0, 0]

    if not isinstance(prop_src, (vs.VideoNode, NoneType)):
        prop_src = clips[prop_src.__index__()]

    joined = vs.core.std.ShufflePlanes(clips, planes, family, prop_src)

    if alpha:
        joined = joined.std.ClipToProp(alpha, "_Alpha")

    return joined

limiter

limiter(
    clip: VideoNode,
    /,
    min_val: float | Sequence[float] | None = None,
    max_val: float | Sequence[float] | None = None,
    *,
    tv_range: bool = False,
    mask: bool = False,
    planes: Planes = None,
    func: FuncExcept | None = None,
) -> ConstantFormatVideoNode
limiter(
    _func: Callable[P, ConstantFormatVideoNode],
    /,
    min_val: float | Sequence[float] | None = None,
    max_val: float | Sequence[float] | None = None,
    *,
    tv_range: bool = False,
    mask: bool = False,
    planes: Planes = None,
    func: FuncExcept | None = None,
) -> Callable[P, ConstantFormatVideoNode]
limiter(
    *,
    min_val: float | Sequence[float] | None = None,
    max_val: float | Sequence[float] | None = None,
    tv_range: bool = False,
    mask: bool = False,
    planes: Planes = None,
    func: FuncExcept | None = None
) -> Callable[
    [Callable[P, ConstantFormatVideoNode]],
    Callable[P, ConstantFormatVideoNode],
]
limiter(
    clip_or_func: (
        VideoNode | Callable[P, ConstantFormatVideoNode] | None
    ) = None,
    /,
    min_val: float | Sequence[float] | None = None,
    max_val: float | Sequence[float] | None = None,
    *,
    tv_range: bool = False,
    mask: bool = False,
    planes: Planes = None,
    func: FuncExcept | None = None,
) -> Union[
    ConstantFormatVideoNode,
    Callable[P, ConstantFormatVideoNode],
    Callable[
        [Callable[P, ConstantFormatVideoNode]],
        Callable[P, ConstantFormatVideoNode],
    ],
]

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_or_func

    (VideoNode | Callable[P, ConstantFormatVideoNode] | None, default: None ) –

    Clip to process or function that returns a VideoNode to be processed.

  • 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.

  • mask

    (bool, default: False ) –

    Float chroma range from -0.5/0.5 to 0.0/1.0.

  • planes

    (Planes, default: None ) –

    Planes to process.

  • func

    (FuncExcept | None, default: None ) –

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

Returns:

Source code in vstools/functions/utils.py
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
def limiter(
    clip_or_func: vs.VideoNode | Callable[P, ConstantFormatVideoNode] | None = None,
    /,
    min_val: float | Sequence[float] | None = None,
    max_val: float | Sequence[float] | None = None,
    *,
    tv_range: bool = False,
    mask: bool = False,
    planes: Planes = None,
    func: FuncExcept | None = None,
) -> Union[
    ConstantFormatVideoNode,
    Callable[P, ConstantFormatVideoNode],
    Callable[[Callable[P, ConstantFormatVideoNode]], Callable[P, ConstantFormatVideoNode]],
]:
    """
    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.

    Args:
        clip_or_func: Clip to process or function that returns a VideoNode to be processed.
        min_val: Lower bound. Defaults to the lowest allowed value for the input. Can be specified for each plane
            individually.
        max_val: Upper bound. Defaults to the highest allowed value for the input. Can be specified for each plane
            individually.
        tv_range: Changes min/max defaults values to LIMITED.
        mask: Float chroma range from -0.5/0.5 to 0.0/1.0.
        planes: Planes to process.
        func: Function returned for custom error handling. This should only be set by VS package developers.

    Returns:
        Clamped clip.
    """
    if callable(clip_or_func):
        _func = clip_or_func

        @wraps(_func)
        def _wrapper(*args: P.args, **kwargs: P.kwargs) -> ConstantFormatVideoNode:
            return limiter(
                _func(*args, **kwargs),
                min_val,
                max_val,
                tv_range=tv_range,
                mask=mask,
                planes=planes,
                func=func or _func,
            )

        return _wrapper

    func = func or limiter
    clip = clip_or_func

    if clip is None:
        return partial(limiter, min_val=min_val, max_val=max_val, tv_range=tv_range, planes=planes, func=func)

    assert check_variable_format(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, mask, planes)

plane

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

Extract a plane from the given clip.

Parameters:

  • clip

    (VideoNode) –

    Input clip.

  • index

    (SupportsIndex) –

    Index of the plane to extract.

  • strict

    (bool, default: True ) –

    If False, removes _Matrix property when the input clip is RGB.

Returns:

  • ConstantFormatVideoNode

    Grayscale clip of the clip's plane.

Source code in vstools/functions/utils.py
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
def plane(clip: vs.VideoNode, index: SupportsIndex, /, strict: bool = True) -> ConstantFormatVideoNode:
    """
    Extract a plane from the given clip.

    Args:
        clip: Input clip.
        index: Index of the plane to extract.
        strict: If False, removes `_Matrix` property when the input clip is RGB.

    Returns:
        Grayscale clip of the clip's plane.
    """
    assert check_variable_format(clip, plane)

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

    if not strict and clip.format.color_family is vs.RGB:
        clip = vs.core.std.RemoveFrameProps(clip, "_Matrix")

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

sc_detect

sc_detect(clip: VideoNode, threshold: float = 0.1) -> ConstantFormatVideoNode
Source code in vstools/functions/utils.py
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
def sc_detect(clip: vs.VideoNode, threshold: float = 0.1) -> ConstantFormatVideoNode:
    assert check_variable_format(clip, sc_detect)

    stats = vs.core.std.PlaneStats(shift_clip(clip, -1), clip)

    return vs.core.akarin.PropExpr(
        [clip, stats, stats[1:]],
        lambda: {
            "_SceneChangePrev": f"y.PlaneStatsDiff {threshold} > 1 0 ?",
            "_SceneChangeNext": f"z.PlaneStatsDiff {threshold} > 1 0 ?",
        },
    )

split

split(clip: VideoNode, /, strict: bool = True) -> list[ConstantFormatVideoNode]

Split a clip into a list of individual planes.

Parameters:

  • clip

    (VideoNode) –

    Input clip.

  • strict

    (bool, default: True ) –

    If False, removes _Matrix property when the input clip is RGB.

Returns:

  • list[ConstantFormatVideoNode]

    List of individual planes.

Source code in vstools/functions/utils.py
782
783
784
785
786
787
788
789
790
791
792
793
794
795
def split(clip: vs.VideoNode, /, strict: bool = True) -> list[ConstantFormatVideoNode]:
    """
    Split a clip into a list of individual planes.

    Args:
        clip: Input clip.
        strict: If False, removes `_Matrix` property when the input clip is RGB.

    Returns:
        List of individual planes.
    """
    assert check_variable_format(clip, split)

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

stack_clips

stack_clips(clips: Iterable[VideoNodeIterableT[VideoNode]]) -> VideoNode

Recursively stack clips in alternating directions: horizontal → vertical → horizontal → ...

This function takes a nested sequence of clips (or lists of clips) and stacks them alternately along the horizontal and vertical axes at each nesting level.

Examples:

  • Stack a list of clips horizontally:

    from vstools import core, split, vs
    
    clip = core.std.BlankClip(format=vs.RGB24)
    clips = split(clip)
    
    stacked = stack_clips(clips)
    

  • Stack a list of clips vertically (wrap in another list):

    from vstools import core, split, vs
    
    clip = core.std.BlankClip(format=vs.RGB24)
    clips = split(clip)
    
    stacked = stack_clips([clips])
    

  • Stack the Y plane horizontally with the U and V planes stacked vertically:

    from vstools import core, split, vs
    
    clip = core.std.BlankClip(format=vs.YUV420P8)
    y, u, v = split(clip)
    
    stacked = stack_clips([y, [u, v]])
    

  • Stack multiple YUV clips, with Y planes horizontally and UV planes vertically:

    from vstools import core, split, vs
    
    yuv_clips = [...]  # all must share format and height
    
    clips = []
    for yuv_clip in yuv_clips:
        y, *uv = split(yuv_clip)
        clips.extend([y, uv])
    
    stacked = stack_clips(clips)
    

  • Using append instead of extend (and wrapping the sequence, e.g. stack_clips([clips])) changes the stacking layout, since it alters the nesting depth.

Parameters:

Returns:

  • VideoNode

    Stacked clips.

Source code in vstools/functions/utils.py
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
def stack_clips(clips: Iterable[VideoNodeIterableT[vs.VideoNode]]) -> vs.VideoNode:
    """
    Recursively stack clips in alternating directions: horizontal → vertical → horizontal → ...

    This function takes a nested sequence of clips (or lists of clips) and stacks them
    alternately along the horizontal and vertical axes at each nesting level.

    Examples:
        - Stack a list of clips horizontally:
          ```py
          from vstools import core, split, vs

          clip = core.std.BlankClip(format=vs.RGB24)
          clips = split(clip)

          stacked = stack_clips(clips)
          ```

        - Stack a list of clips vertically (wrap in another list):
          ```py
          from vstools import core, split, vs

          clip = core.std.BlankClip(format=vs.RGB24)
          clips = split(clip)

          stacked = stack_clips([clips])
          ```

        - Stack the Y plane horizontally with the U and V planes stacked vertically:
          ```py
          from vstools import core, split, vs

          clip = core.std.BlankClip(format=vs.YUV420P8)
          y, u, v = split(clip)

          stacked = stack_clips([y, [u, v]])
          ```

        - Stack multiple YUV clips, with Y planes horizontally and UV planes vertically:
          ```py
          from vstools import core, split, vs

          yuv_clips = [...]  # all must share format and height

          clips = []
          for yuv_clip in yuv_clips:
              y, *uv = split(yuv_clip)
              clips.extend([y, uv])

          stacked = stack_clips(clips)
          ```

        - Using ``append`` instead of ``extend`` (and wrapping the sequence, e.g. ``stack_clips([clips])``)
          changes the stacking layout, since it alters the nesting depth.

    Args:
        clips: A (possibly nested) sequence of clips to be stacked.

    Returns:
        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
        ]
    )