Skip to content

User API

The user-facing API is used primarily within VapourSynth scripts to register nodes for preview.

Functions:

set_output

set_output(
    node: VideoNode,
    index: int = ...,
    /,
    *,
    alpha: VideoNode | Literal[True] | None = ...,
    framedurs: Sequence[SupportsFloat] | None = None,
    hdr: bool | None = None,
    **kwargs: Any,
) -> None
set_output(
    node: VideoNode,
    name: str | bool | None = ...,
    /,
    *,
    alpha: VideoNode | Literal[True] | None = ...,
    framedurs: Sequence[SupportsFloat] | None = None,
    hdr: bool | None = None,
    **kwargs: Any,
) -> None
set_output(
    node: VideoNode,
    index: int = ...,
    name: str | bool | None = ...,
    /,
    alpha: VideoNode | Literal[True] | None = ...,
    *,
    framedurs: Sequence[SupportsFloat] | None = None,
    hdr: bool | None = None,
    **kwargs: Any,
) -> None
set_output(
    node: AudioNode, index: int = ..., /, *, downmix: bool | None = None, **kwargs: Any
) -> None
set_output(
    node: AudioNode,
    name: str | bool | None = ...,
    /,
    *,
    downmix: bool | None = None,
    **kwargs: Any,
) -> None
set_output(
    node: AudioNode,
    index: int = ...,
    name: str | bool | None = ...,
    /,
    *,
    downmix: bool | None = None,
    **kwargs: Any,
) -> None
set_output(node: RawNode, index: int | Sequence[int] = ..., /, **kwargs: Any) -> None
set_output(node: RawNode, name: str | bool | None = ..., /, **kwargs: Any) -> None
set_output(
    node: VideoNodeIterable | AudioNodeIterable | RawNodeIterable,
    index: int | Sequence[int] = ...,
    /,
    **kwargs: Any,
) -> None
set_output(
    node: VideoNodeIterable | AudioNodeIterable | RawNodeIterable,
    name: str | bool | None = ...,
    /,
    **kwargs: Any,
) -> None
set_output(
    node: VideoNodeIterable | AudioNodeIterable,
    index: int | Sequence[int] = ...,
    name: str | bool | None = ...,
    /,
    **kwargs: Any,
) -> None

Register one or more VapourSynth nodes as outputs for preview.

This function sets the output(s) and registers metadata for tab naming in vsview. If no index is provided, outputs are assigned to the next available indices.

Examples:

set_output(clip)  # Auto-index, auto-name ("clip")
set_output(clip, 0)  # Index 0, auto-name
set_output(clip, 0, "My Clip")  # Index 0, explicit name
set_output(clip, "Source")  # Auto-index, explicit name
set_output([clip1, clip2])  # Multiple outputs

Parameters:

Name Type Description Default
node OutputNode

A VideoNode, AudioNode, or iterable of nodes to output.

required
index_or_name int | Sequence[int] | str | bool | None

Either:

  • An int or sequence of ints specifying output indices
  • A str to use as the output name
  • True/None to auto-detect the variable name
  • False to disable name detection
None
name str | bool | None

Explicit name override. If provided when index_or_name is an int, this sets the display name for the output.

None
alpha VideoNode | Literal[True] | None

Optional alpha channel VideoNode or if True, fetch the _Alpha prop (only for VideoNode outputs).

None
framedurs Sequence[SupportsFloat] | None

Optional sequence of frame durations in seconds for VFR clips (only for VideoNode outputs).

None
hdr bool | None

Optional boolean override for the HDR detection for VideoNode outputs. If passing --hdr, this flag can be used to disable HDR conversion for this output.

None
downmix bool | None

if None (default), follows the global settings downmix of vsview if previewed through vsview. Otherwise True or False forces the behavior.

None
**kwargs Any

Additional metadata for custom configuration of this output.

{}
Source code in src/vsview/api/output.py
def set_output(
    node: OutputNode,
    index_or_name: int | Sequence[int] | str | bool | None = None,
    name: str | bool | None = None,
    /,
    alpha: vs.VideoNode | Literal[True] | None = None,
    *,
    framedurs: Sequence[SupportsFloat] | None = None,
    hdr: bool | None = None,
    downmix: bool | None = None,
    **kwargs: Any,
) -> None:
    """
    Register one or more VapourSynth nodes as outputs for preview.

    This function sets the output(s) and registers metadata for tab naming in vsview.
    If no index is provided, outputs are assigned to the next available indices.

    Examples:
        ```python
        set_output(clip)  # Auto-index, auto-name ("clip")
        set_output(clip, 0)  # Index 0, auto-name
        set_output(clip, 0, "My Clip")  # Index 0, explicit name
        set_output(clip, "Source")  # Auto-index, explicit name
        set_output([clip1, clip2])  # Multiple outputs
        ```

    Args:
        node: A VideoNode, AudioNode, or iterable of nodes to output.
        index_or_name: Either:

               - An int or sequence of ints specifying output indices
               - A str to use as the output name
               - True/None to auto-detect the variable name
               - False to disable name detection

        name: Explicit name override. If provided when index_or_name is an int,
            this sets the display name for the output.
        alpha: Optional alpha channel VideoNode or if True, fetch the `_Alpha` prop (only for VideoNode outputs).
        framedurs: Optional sequence of frame durations in seconds for VFR clips (only for VideoNode outputs).
        hdr: Optional boolean override for the HDR detection for VideoNode outputs.
            If passing `--hdr`, this flag can be used to disable HDR conversion for this output.
        downmix: if None (default), follows the global settings downmix of vsview if previewed
            through vsview. Otherwise True or False forces the behavior.
        **kwargs: Additional metadata for custom configuration of this output.
    """
    if isinstance(index_or_name, (str, bool)):
        index = None
        name = index_or_name
    else:
        index = index_or_name

    func = kwargs.pop("func", set_output)
    frame_depth = kwargs.pop("frame_depth", 1) + 1

    outputs = vs.get_outputs()
    nodes = list[vs.VideoNode | vs.AudioNode](flatten([node]))

    indices = to_arr(index) if index is not None else [max(outputs, default=-1) + 1]

    if not indices:
        raise CustomValueError("The index sequence must not be empty", func)

    while len(indices) < len(nodes):
        indices.append(indices[-1] + 1)

    script_module = sys.modules.get("__vsview__")
    file = getattr(script_module, "__file__", None) if script_module else None

    if file and framedurs:
        for n in nodes:
            if isinstance(n, vs.VideoNode) and len(framedurs) != n.num_frames:
                raise CustomValueError("framedurs length must match number of frames", func)

    for i, n in zip(indices[: len(nodes)], nodes):
        if i in outputs:
            _logger.warning("Output index %d already in use; overwriting.", i)

        match n:
            case vs.VideoNode():
                n.set_output(i, alpha if alpha is not True else None)
                title = "Clip"
            case vs.AudioNode():
                n.set_output(i)
                title = "Audio"
            case _:
                assert_never(n)

        if not script_module:
            continue

        effective_name: str | None

        match name:
            case True | None:
                effective_name = _resolve_var_name(n, frame_depth=frame_depth)
            case False:
                effective_name = None
            case str():
                effective_name = name

        if file:
            if isinstance(n, vs.VideoNode):
                _output_metadata[file][i] = VideoMetadata(
                    effective_name or f"{title} {i}",
                    tuple(float(f) for f in (framedurs or [])),
                    alpha is True or None,
                    hdr,
                    kwargs.copy(),
                )
            elif isinstance(n, vs.AudioNode):
                _output_metadata[file][i] = AudioMetadata(effective_name or f"{title} {i}", downmix, kwargs.copy())

catch_output

catch_output[**P, N: OutputNode](func: Callable[P, N]) -> Callable[P, N]
catch_output[**P, N: OutputNode](
    *,
    index: int | Sequence[int] = ...,
    name: str | bool | None = ...,
    alpha: VideoNode | Literal[True] | None = ...,
    framedurs: Sequence[SupportsFloat] | None = ...,
    hdr: bool | None = ...,
    downmix: bool | None = ...,
    **kwargs: Any,
) -> Callable[[Callable[P, N]], Callable[P, N]]

Decorator variant of set_output().

Calls the decorated function and registers its return value as an output.

Examples:

@catch_output
def source() -> vs.VideNode:
    return vs.core.bs.BestSource("video.mkv")


@catch_output(name="Filtered", alpha=True)
def filtered() -> vs.VideNode:
    src = vs.core.bs.BestSource("image.png")
    return src.std.BoxBlur()

Parameters:

Name Type Description Default
func Callable[P, N] | None

The function to decorate (populated automatically when used as a bare decorator).

None
index int | Sequence[int] | None

An int or sequence of ints specifying output indices

None
name str | bool | None

Explicit name override. If not provided, the function name is used.

None
alpha VideoNode | Literal[True] | None

Optional alpha channel VideoNode or if True, fetch the _Alpha prop (only for VideoNode outputs).

None
framedurs Sequence[SupportsFloat] | None

Optional sequence of frame durations in seconds for VFR clips (only for VideoNode outputs).

None
hdr bool | None

Optional boolean override for the HDR detection for VideoNode outputs.

None
downmix bool | None

If None (default), follows the global settings downmix of vsview if previewed through vsview. Otherwise True or False forces the behavior.

None
**kwargs Any

Additional metadata passed to VSView plugins for custom configuration of this output.

{}

Returns:

Type Description
Callable[P, N] | Callable[[Callable[P, N]], Callable[P, N]]

The decorated function (its original return type is preserved).

Source code in src/vsview/api/output.py
def catch_output[**P, N: OutputNode](
    func: Callable[P, N] | None = None,
    /,
    index: int | Sequence[int] | None = None,
    name: str | bool | None = None,
    alpha: vs.VideoNode | Literal[True] | None = None,
    *,
    framedurs: Sequence[SupportsFloat] | None = None,
    hdr: bool | None = None,
    downmix: bool | None = None,
    **kwargs: Any,
) -> Callable[P, N] | Callable[[Callable[P, N]], Callable[P, N]]:
    """
    Decorator variant of `set_output()`.

    Calls the decorated function and registers its return value as an output.

    Examples:
        ```python
        @catch_output
        def source() -> vs.VideNode:
            return vs.core.bs.BestSource("video.mkv")


        @catch_output(name="Filtered", alpha=True)
        def filtered() -> vs.VideNode:
            src = vs.core.bs.BestSource("image.png")
            return src.std.BoxBlur()
        ```

    Args:
        func: The function to decorate (populated automatically when used as a bare decorator).
        index: An int or sequence of ints specifying output indices
        name: Explicit name override. If not provided, the function name is used.
        alpha: Optional alpha channel VideoNode or if True, fetch the `_Alpha` prop (only for VideoNode outputs).
        framedurs: Optional sequence of frame durations in seconds for VFR clips (only for VideoNode outputs).
        hdr: Optional boolean override for the HDR detection for VideoNode outputs.
        downmix: If None (default), follows the global settings downmix of vsview if previewed through vsview.
            Otherwise True or False forces the behavior.
        **kwargs: Additional metadata passed to VSView plugins for custom configuration of this output.

    Returns:
        The decorated function (its original return type is preserved).
    """

    def decorator(fn: Callable[P, N]) -> Callable[P, N]:
        @wraps(fn)
        def wrapper(*fn_args: P.args, **fn_kwargs: P.kwargs) -> N:
            result = fn(*fn_args, **fn_kwargs)

            effective_name = fn.__name__ if (name is True or name is None) else name

            set_output(  # type: ignore[misc]
                result,  # type: ignore[arg-type]
                index,  # type: ignore[arg-type]
                effective_name,
                alpha=alpha,
                framedurs=framedurs,
                hdr=hdr,
                downmix=downmix,
                **kwargs,
            )

            return result

        return wrapper

    if func is not None:
        return decorator(func)

    return decorator

is_preview

is_preview() -> bool

Check if the current script is running in a preview environment (VSView only).

Source code in src/vsview/api/info.py
def is_preview() -> bool:
    """Check if the current script is running in a preview environment (VSView only)."""
    return bool(sys.modules.get("__vsview__"))

is_reload

is_reload() -> bool | None

Check if the current script run is a reload inside VSView.

Source code in src/vsview/api/info.py
def is_reload() -> bool | None:
    """
    Check if the current script run is a reload inside VSView.
    """
    return ctx.is_reload if (ctx := Context.get()) is not None else None

get_reload_count

get_reload_count() -> int | None

Return how many times the current script has been reloaded in VSView (0 if initial load or None outside preview).

Source code in src/vsview/api/info.py
def get_reload_count() -> int | None:
    """
    Return how many times the current script has been reloaded in VSView
    (0 if initial load or None outside preview).
    """
    return ctx.reload_count if (ctx := Context.get()) is not None else None

get_state

get_state() -> MutableMapping[Any, Any] | None

Return the persistent state dictionary shared across script reloads, or None if outside VSView.

Note

Objects stored in this dictionary survive script reloads within the same workspace.

  • DO NOT store VapourSynth clips, frames, or script closures capturing 'globals()'.
  • DO store heavy external resources (e.g. PyTorch models, ONNX sessions, lookup tables).
Source code in src/vsview/api/info.py
def get_state() -> MutableMapping[Any, Any] | None:
    """
    Return the persistent state dictionary shared across script reloads, or None if outside VSView.

    Note:
        Objects stored in this dictionary survive script reloads within the same workspace.

        - DO NOT store VapourSynth clips, frames, or script closures capturing 'globals()'.
        - DO store heavy external resources (e.g. PyTorch models, ONNX sessions, lookup tables).
    """
    return ctx.persistent_state if (ctx := Context.get()) is not None else None

get_cached

get_cached[**P, R](
    key: str, loader: Callable[P, R], *args: P.args, **kwargs: P.kwargs
) -> R

Get a cached value from the persistent state, or compute and cache it if not present.

If running outside VSView, the loader is called directly without caching.

Parameters:

Name Type Description Default
key str

The key to look up or store in the persistent state.

required
loader Callable[P, R]

A callable to produce the value if key is not found.

required
*args P.args

Positional arguments forwarded to loader.

()
**kwargs P.kwargs

Keyword arguments forwarded to loader.

{}

Returns:

Type Description
R

The cached or newly computed value.

Source code in src/vsview/api/info.py
def get_cached[**P, R](key: str, loader: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R:
    """
    Get a cached value from the persistent state, or compute and cache it if not present.

    If running outside VSView, the loader is called directly without caching.

    Args:
        key: The key to look up or store in the persistent state.
        loader: A callable to produce the value if key is not found.
        *args: Positional arguments forwarded to loader.
        **kwargs: Keyword arguments forwarded to loader.

    Returns:
        The cached or newly computed value.
    """
    if (state := get_state()) is None:
        return loader(*args, **kwargs)
    if key not in state:
        state[key] = loader(*args, **kwargs)
    return state[key]

register_on_workspace_destroy

register_on_workspace_destroy[**P, R](
    cb: Callable[P, R], *args: P.args, **kwargs: P.kwargs
) -> Callable[P, R]

Register a callback to run once when the workspace closes (ignored on reload).

Use for resources persisting across reloads (e.g., via get_cached). Duplicate registrations with identical arguments are ignored, when all arguments can be hashed.

Note

Functions defined inside the script create new objects on each reload and will execute with cleared globals at close. Use register_on_unload for per-run resources instead.

Parameters:

Name Type Description Default
cb Callable[P, R]

Callable to invoke on workspace close.

required
*args P.args

Positional arguments forwarded to cb.

()
**kwargs P.kwargs

Keyword arguments forwarded to cb.

{}

Returns:

Type Description
Callable[P, R]

The registered callback (allows use as a decorator).

Source code in src/vsview/api/info.py
def register_on_workspace_destroy[**P, R](cb: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> Callable[P, R]:
    """
    Register a callback to run once when the workspace closes (ignored on reload).

    Use for resources persisting across reloads (e.g., via `get_cached`).
    Duplicate registrations with identical arguments are ignored, when all arguments can be hashed.

    Note:
        Functions defined inside the script create new objects on each reload
        and will execute with cleared globals at close.
        Use `register_on_unload` for per-run resources instead.

    Args:
        cb: Callable to invoke on workspace close.
        *args: Positional arguments forwarded to `cb`.
        **kwargs: Keyword arguments forwarded to `cb`.

    Returns:
        The registered callback (allows use as a decorator).
    """
    if (ctx := Context.get()) is not None:
        ctx.on_workspace_destroy(cb, *args, **kwargs)
    return cb

register_on_unload

register_on_unload[**P, R](
    cb: Callable[P, R], *args: P.args, **kwargs: P.kwargs
) -> Callable[P, R]

Register a one-time callback to run when the current script run is released (before the next reload or on workspace close).

Use for resources created fresh on each run. The callback is removed after execution.

Parameters:

Name Type Description Default
cb Callable[P, R]

Callable to invoke on release.

required
*args P.args

Positional arguments forwarded to cb.

()
**kwargs P.kwargs

Keyword arguments forwarded to cb.

{}

Returns:

Type Description
Callable[P, R]

The registered callback (allows use as a decorator).

Source code in src/vsview/api/info.py
def register_on_unload[**P, R](cb: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> Callable[P, R]:
    """
    Register a one-time callback to run when the current script run is released
    (before the next reload or on workspace close).

    Use for resources created fresh on each run. The callback is removed after execution.

    Args:
        cb: Callable to invoke on release.
        *args: Positional arguments forwarded to `cb`.
        **kwargs: Keyword arguments forwarded to `cb`.

    Returns:
        The registered callback (allows use as a decorator).
    """
    if (ctx := Context.get()) is not None:
        ctx.on_unload(cb, *args, **kwargs)
    return cb