VAPOURSYNTH(3)

NAME
vapoursynth - VapourSynth Documentation

Contents:

INTRODUCTION

VapourSynth is an application for video manipulation. Or a plugin. Or a library. It's hard to tell because it has a core library written in C++ and a Python module to allow video scripts to be created. It came to be when I started thinking about alternative designs for Avisynth and most of it was written over a 3 month period.

The software has been heavily inspired by Avisynth and aims to be a 21st century rewrite, taking advantage of the advancements computers have made since the late 90s. The main features compared to Avisynth are:

•   Multithreaded - Frame level multithreading that scales well

•   Generalized Colorspaces - New colorspaces can be specified at runtime

•   Per Frame Properties - Additional metadata can be attached to frames

•   Python Based - The scripting part is implemented as a Python module so you don't have to learn a special language

•   Support for video with format changes - Some video just can't stick to one format or frame size. VapourSynth can handle any kind of change

•   Compatible with a large number of already existing Avisynth plugins

  About the author

Fredrik Mellbin majored in electrical engineering with a focus on image analysis and processing with medical applications. He has previously worked with digital electronics and likes to plan his own software projects in his spare time. When he one day found himself out of work he needed something to do between sending out job applications and waiting for a reply. The natural choice for the author was to try to improve Avisynth, the software that once made him interested in video editing. VapourSynth is the result of all that time waiting.

Feel free to contact me at fredrik.mellbin that round thingy with an a gmail.com if you need help to port a filter or want to sponsor the development.

INSTALLATION

  Basic Program

The installation contains two main steps:

1.  Install VapourSynth core library.

2.  Install the Python wrapper of VapourSynth.

    After you completed the second step, you can test it by opening a Python command line and type this:

        from vapoursynth import core
        print(str(core))

    After pressing return at the final line, you should see the version printed along with a few other lines describing the options used when instantiating the Core object. In fact, these lines should be the same as the output result of vspipe --version.

  Windows Installation

  Prerequisites

First download and install the prerequisites:

•   Python 3.12.x or Python 3.8.x -- 64 bit version

    Note that VapourSynth and Python have to be matched so both are either installed for all users or for only for the current user.

    Also note that per user installs will not install the required Visual Studio 2019 runtimes.

  Installation

Simply run the VapourSynth installer. It should automatically detect and install everything, including the Python wrapper.

If the tests mentioned at the beginning fails, there may be a bug in the installer or there are old copies of vapoursynth.pyd and vapoursynth.dll lying around.

  Windows Installation (Portable)

First download and decompress the prerequisites:

•   Python 3.12.x or Python 3.8.x -- 64 bit embeddable version

    Simply decompress the portable VapourSynth archive into the Python dir and overwrite all existing files.Run vs-detect-python.bat to configure it for the current Python version. Done.

    You can also use the VapourSynth Editor by decompressing it into the same directory.

  OS X Installation

First download and install the prerequisites:

•   Xcode -- Available from the AppStore

•   Homebrew -- A package manager

    Simply run these commands in a terminal and wait for them to complete:

        brew install vapoursynth

  Linux installation

Several distributions have VapourSynth packages. Note that those packages are usually OUT OF DATE.

  Debian

The VapourSynth packages are provided by deb-multimedia repository. You need to add the repository first following the guide on the official website.

  Fedora, CentOS and RHEL

For Fedora, the VapourSynth packages can be downloaded from official repository directly. For CentOS and RHEL, you should install EPEL (Extra Packages for Enterprise Linux) repository first.

  Gentoo

There is an unofficial Portage tree with all VapourSynth related ebuilds. Check the Github link for more information and instructions.

  Arch Linux

VapourSynth-related packages are provided by the Community repository.

  Nix and NixOS

vapoursynth is available on nixpkgs, either via nixpkgs#vapoursynth or via nixpkgs#python3Packages.vapoursynth (currently on unstable only). Be aware that the derivation is broken on MacOS.

VapourSynth releases are not backported to the current stable branch. To get the newest version use the unstable branch.

  Windows Compilation

  Preparing the Build Environment on Windows

Default install paths are assumed in all projects and scripts, be prepared to adjust many things if you changed them

Required languages and applications:

•   Needs Visual Studio 2019

•   It also needs both 32bit and 64bit Python 3.8.x and 3.12.x (the msvc project assumes that you installed python for all users.)

•   InnoSetup is needed to create the installer (default installation path assumed)

•   7-zip is needed to compress the portable version (default installation path assumed)

  Preparing the C++ Project

•   Clone VapourSynth

•   Clone VSRepo into the VapourSynth dir (git clone https://github.com/vapoursynth/vsrepo)

•   Clone zimg into the VapourSynth dir (git clone https://github.com/sekrit-twc/zimg.git --recurse-submodules)

•   Clone avs+ into the VapourSynth dir (git clone https://github.com/AviSynth/AviSynthPlus.git)

•   Clone libp2p into the VapourSynth dir (git clone https://github.com/sekrit-twc/libp2p.git)

•   Compile 32 and 64 bit releases using the VapourSynth solution

  Preparing the Python Project

•   Run py -3.12 -m pip install -r python-requirements.txt for 64bit.

•   Run py -3.8 -m pip install -r python-requirements.txt for 64bit.

•   Run cython_build.bat to compile the Python modules

•   Run docs_build.bat to compile the documentation

  Distribution

All the above steps are necessary to create the installer

You also need 7z.exe and 7z.dll from 7-zip Both need to be placed in the "installer" dir.

You'll also have to grab the file pfm-192-vapoursynth-win.exe which is only available from installations/portable releases.

Run make_portable.bat and make_installers.bat to package things.

NOTE: Note that the Avisynth side of AVFS won't work properly in debug builds (memory allocation and exceptions across module boundaries trolololol)

  Linux and OS X Compilation

These are the requirements:

•   Autoconf, Automake, and Libtool, probably recent versions

•   pkg-config

•   GCC 4.8 or newer, or Clang

•   zimg

•   Python 3.8 or later (may work on earlier versions but these are never fully tested)

•   Cython 3.x or later installed in your Python 3 environment

•   Sphinx for the documentation (optional)

    Note: any version of Python 3 will do. A specific version is only required when using the official Windows binaries.

  Required packages (OS X)

First download and install the prerequisites:

•   Xcode -- Available from the AppStore

•   Homebrew -- A package manager

    Installation of the required packages is very easy. Simply run these commands in a terminal and wait for them to complete:

        brew install python3 ffmpeg libass zimg imagemagick
        pip3 install cython

    If you've already installed all the required packages and instead want to update them, simply run:

        brew update && brew upgrade
        pip3 install --upgrade cython

  Compilation

If you haven't checked out the source code before, use git to do so:

    git clone https://github.com/vapoursynth/vapoursynth.git

Or if you already have a copy of the source, update it with:

    git pull

Enter the VapourSynth directory and run these commands to compile and install:

    ./autogen.sh
    ./configure
    make
    make install

Depending on your operating system's configuration, VapourSynth may not work out of the box with the default prefix of /usr/local. Two errors may pop up when running vspipe --version:

•   "vspipe: error while loading shared libraries: libvapoursynth-script.so.0: cannot open shared object file: No such file or directory"

    This is caused by the non-standard location of libvapoursynth-script.so.0. Your dynamic loader is not configured to look in /usr/local/lib. One way to work around this error is to use the LD_LIBRARY_PATH environment variable:

        $ LD_LIBRARY_PATH=/usr/local/lib vspipe --version

•   "Failed to initialize VapourSynth environment"

    This is caused by the non-standard location of the Python module, vapoursynth.so. Your Python is not configured to look in /usr/local/lib/python3.x/site-packages. One way to work around this error is to use the PYTHONPATH environment variable:

        $ PYTHONPATH=/usr/local/lib/python3.x/site-packages vspipe --version

    Replace "x" with the correct number.

    The documentation can be built using its own Makefile:

        $ make -C doc/ html

    The documentation can be installed using the standard program cp.

  Plugins and Scripts

If you're looking for plugins and scripts then one of the most complete lists available can be found at vsdb.top.

  Installing with VSRepo

On windows you can use the included vsrepo.py to install and upgrade plugins and scripts.

Simply run vsrepo.py install <namespace or identifier> to install them.

If you need a list of known plugins and scripts you can run vsrepo.py available or visit vsdb.top.

For more reference, visit vsrepo's repository

  Installing Manually

You can put your plugin (.dll) and script (.py) to where you think it is convenient.

For plugins, you can use std.LoadPlugin function to load it. there is also a plugin autoloading mechanism to save your time, see blow.

For scripts, you should add a relative path to python<your_python_version>._pth, then you can import it in your script.

  Plugin Autoloading

VapourSynth automatically loads all the native plugins located in certain folders. Autoloading works just like manual loading, with the exception that any errors encountered while loading a plugin are silently ignored.

NOTE: Avoid autoloading from folders that other applications might also use, such as /usr/lib or /usr/local/lib in a Linux system. Several users reported crashes when VapourSynth attempted to load some random libraries (*cough*wxgtk*cough*).

  Windows

Windows has in total 3 different autoloading directories: user plugins, core plugins and global plugins. They are searched in that order. User plugins are always loaded first so that the current user can always decide which exact version of a plugin is used. Core plugins follow. Global plugins are placed last to prevent them from overriding any of the included plugins by accident.

The searched paths are:

1.  <AppData>\VapourSynth\plugins32 or <AppData>\VapourSynth\plugins64

2.  <VapourSynth path>\core\plugins

3.  <VapourSynth path>\plugins

    Note that the per user path is not created by default. On modern Windows versions the AppData directory is located in <user>\AppData\Roaming by default.

    Shortcuts to the global autoload directory are located in the start menu.

    Avisynth plugins are never autoloaded. Support for this may be added in the future.

    User plugins should never be put into the core\plugins directory.

  Windows Portable

The searched paths are:

1.  <VapourSynth.dll path>\vapoursynth32\coreplugins or <VapourSynth.dll path>\vapoursynth64\coreplugins

2.  <VapourSynth.dll path>\vapoursynth32\plugins or <VapourSynth.dll path>\vapoursynth64\plugins

    User plugins should never be put into the coreplugins directory.

  Linux

Autoloading can be configured using the file $XDG_CONFIG_HOME/vapoursynth/vapoursynth.conf, or $HOME/.config/vapoursynth/vapoursynth.conf if XDG_CONFIG_HOME is not defined.

To provide your own path to the config file, you can use $VAPOURSYNTH_CONF_PATH.

Two configuration options may be used: UserPluginDir, empty by default, and SystemPluginDir, whose default value is set at compile time to $libdir/vapoursynth, or to the location passed to the --with-plugindir argument to configure.

UserPluginDir is tried first, then SystemPluginDir.

Example vapoursynth.conf:

    UserPluginDir=/home/asdf/vapoursynth/plugins
    SystemPluginDir=/special/non/default/location

  OS X

Autoloading can be configured using the file $HOME/Library/Application Support/VapourSynth/vapoursynth.conf. Everything else is the same as in Linux.

Like on linux, you can use $VAPOURSYNTH_CONF_PATH to provide your own configuration.

GETTING STARTED

So you managed to install VapourSynth. Now what?

If you don't know the basics of Python, you may want to check out a tutorial.

You can "play around" in the python interpreter if you want, but that's not how most scripts are created.

  Example Script

It all starts with a .vpy script. Here's a sample script to be inspired by, it assumes that BestSource is installed and auto-loaded.

    from vapoursynth import core                     # Get an instance of the core
    clip = core.bs.VideoSource(source='filename.mkv')  # Load a video track in mkv file
    clip = core.std.FlipHorizontal(clip)             # Flip the video clip in the horizontal direction
    clip.set_output()                                # Set the video clip to be accessible for output

Audio is also supported, use BestSource to load your audio file.

    from vapoursynth import core                     # Get an instance of the core
    clip = core.bs.AudioSource(source='filename.mkv')    # Load an audio track in mkv file
    clip = core.std.AudioGain(clip,gain=2.0)         # Gain all channels 2x
    clip.set_output()                                # Set the audio clip to be accessible for output

You can combine 2 operations in one script.

    from vapoursynth import core
    video = core.bs.VideoSource(source='filename.mkv')
    audio = core.bs.AudioSource(source='filename.mkv')
    video = core.std.FlipHorizontal(video)
    audio = core.std.AudioGain(audio,gain=2.0)
    video.set_output(index=0)
    audio.set_output(index=1)

Remember that most VapourSynth objects have a quite nice string representation in Python, so if you want to know more about an instance just call print().

  Preview

It's possible to directly open the script in VapourSynth Editor or VirtualDub FilterMod for previewing.

  Output with VSPipe

VSPipe is very useful to pipe the output to various applications, for example x264 and flac for encoding.

Here are some examples of command lines that automatically pass on most video and audio attributes.

For x264:

    vspipe -c y4m script.vpy - | x264 --demuxer y4m - --output encoded.264

For flac:

    vspipe -c wav script.vpy - | flac - -o encoded.flac

For FFmpeg:

    vspipe -c y4m script.vpy - | ffmpeg -i - encoded.mkv

For mpv:

    vspipe -c y4m script.vpy - | mpv -
    vspipe -c wav script.vpy - | mpv -

PYTHON REFERENCE

VapourSynth is separated into a core library and a Python module. This section explains how the core library is exposed through Python and some of the special things unique to Python scripting, such as slicing and output.

NOTE: Any script executed through the vsscript api (that means vspipe, avfs, vsvfw or other API users) will have __name__ set to "__vapoursynth__" unlike normal Python scripts where it usually is "__main__".

  VapourSynth Structure

Most operations in the VapourSynth library are performed through the singleton core object. This core may load plugins, which all end up in their own unit, or namespace, so to say, to avoid naming conflicts in the contained functions. For this reason you call a plugin function with core.unit.Function().

All arguments to functions have names that are lowercase and all function names are CamelCase. Unit names are also lowercase and usually short. This is good to remember as a general rule.

  Grammar

  Slicing and Other Syntactic Sugar

The VideoNode and AudioNode class (always called "clip" in practice) supports the full range of indexing and slicing operations in Python. If you do perform a slicing operation on a clip, you will get a new clip back with the desired frames. Here are a few examples.
Operation | Description | Equivalent
clip = clip[5] | Make a single frame clip containing frame number 5 | clip = core.std.Trim(clip, first=5, last=5)
clip = clip[5:11] | Make a clip containing frames 5 to 10 [1] | clip = core.std.Trim(clip, first=5, last=10) clip = core.std.AudioTrim(clip, first=5, last=10)
clip = clip[::2] | Select even numbered frames | clip = core.std.SelectEvery(clip, cycle=2, offsets=0)
clip = clip[1::2] | Select odd numbered frames | clip = core.std.SelectEvery(clip, cycle=2, offsets=1)
clip = clip[::-1] | Reverses a clip | clip = core.std.Reverse(clip) clip = core.std.AudioReverse(clip)
clip = clip1 + clip2 | The addition operator can be used to splice clips together | clip = core.std.Splice([clip1, clip2], mismatch=False) clip = core.std.AudioSplice([clip1, clip2])
clip = clip * 10 | The multiplication operator can be used to loop a clip [2] | clip = core.std.Loop(clip, times=10) clip = core.std.AudioLoop(clip, times=10)

[1] Note that frame numbers, like python arrays, start counting at 0 and the end value of slicing is not inclusive

[2] Note that multiplication by 0 is a special case that will repeat the clip up to the maximum frame count

    Filters can be chained with a dot:

        clip = clip.std.Trim(first=100, last=2000).std.FlipVertical()

    Which is quivalent to:

        clip = core.std.FlipVertical(core.std.Trim(clip, first=100, last=2000))

  Function Arguments, Return Types and Property Type Deduction in Python

VapourSynth internally uses a very simple map of key-value pairs to pass values to and from functions. As a result of this every key is actually a one dimensional array of values of a single type. The Python bindings try to hide this as best as possible to make things less annoying. For example a function returning only a single key will have the only the array itself returned and an array with a single value will in turn only have the single value returned.

Similarly function arguments are first converted to the appropriate type specified by the function's argument string or fails if this isn't possible. There is however one quirk where the data type's type hint (utf-8/non-printable raw data) is set based on whether a str or a bytes/bytearray object is passed. Likewise a str object will be returned for all utf-8 hinted data and a bytes object for all other types.

Frame properties and "anything goes" function arguments have much stricter type requirements since the underlying type has to be possible to deduce from them. When using this type of functions, such as SetFrameProps, or property assignment it may be necessary to convert to int, float, str or bytes explicitly to make things works.

  Python Keywords as Filter Arguments

If a filter's argument happens to be a Python keyword, you may append an underscore to the argument's name when invoking the filter. The Python module will strip one trailing underscore (if present) from all filter arguments before passing them to the filters.

    clip = core.plugin.Filter(clip, lambda_=1)

Another way to deal with such arguments is to place them in a dictionary:

    kwargs = { "lambda": 1 }
    clip = core.plugin.Filter(clip, **kwargs)

VapourSynth will also support the PEP8 convention of using a single trailing underscore to prevent collisions with python keywords.

  Windows File Paths

If you have a string containing backslashes, you must either prefix the string with "r", or duplicate every single backslash. The reason is that the backslash is an escape character in Python.

Use os.path.normcase(path) to fix Incorrect path string.

Correct example:

    "B:/VapourSynth/VapourSynth.dll"
    "B:\\VapourSynth\\VapourSynth.dll"
    r"B:\VapourSynth\VapourSynth.dll"

  Output

The normal way of specifying the clip(s) to output is to call clip.set_output(). All standard VapourSynth components only use output index 0, except for vspipe where it's configurable but defaults to 0. There are also other variables that can be set to control how a format is output. For example, setting alt_output=1 changes the packing of the YUV422P10 format to one that is common in professional software (like Adobe products). Note that currently alt_output modes only has an effect with YUV420P8 (I420, IYUV), YUV422P8 (YUY2, UYVY) and YUV422P10 (v210).

An example on how to get v210 output:

    some_clip = core.resize.Bicubic(clip, format=vs.YUV422P10)
    some_clip.set_output(alt_output=1)

An example on how to get UYVY output:

    some_clip = core.resize.Bicubic(clip, format=vs.YUV422P8)
    some_clip.set_output(alt_output=2)

  Raw Access to Frame Data

The VideoFrame and AudioFrame classes contains one picture/audio chunk and all the metadata associated with it. It is possible to access the raw data using either get_read_ptr(plane) or get_write_ptr(plane) and get_stride(plane) with ctypes.

A more Python friendly wrapping is also available where each plane/channel can be accessed as a Python array using frame[plane/channel].

To get a frame simply call get_frame(n) on a clip. Should you desire to get all frames in a clip, use this code:

    for frame in clip.frames():
        # Do stuff with your frame
        pass

  Classes and Functions

core
    Gets the singleton Core object. If it is the first time the function is called, the Core will be instantiated with the default options. This is the preferred way to reference the core.

get_outputs()
    Return a read-only mapping of all outputs registered on the current node.

    The mapping will automatically update when a new output is registered.

get_output([index = 0])
    Get a previously set output node. Throws an error if the index hasn't been set. Will return a VideoOutputTuple containing alpha and the alt_output setting for video output and an AudioNode for audio.

clear_output([index = 0])
    Clears a clip previously set for output.

clear_outputs()
    Clears all clips set for output in the current environment.

construct_signature(signature[, injected=None])
    Creates a inspect.Signature object for the given registration signature.

    If injected is not None, the default of the first argument of the signature will be replaced with the value supplied with injected.

register_on_destroy(callback)
    Registers a callback that is called when the script is being finalized. This allows you to release resources at the end of a script.

    A callback must be registered with every script that is run, even if the code is being reused in multiple script runs.

    No new callbacks can be registered when the script is already being finalized.

unregister_on_destroy(callback)
    Unregisters a previously added callback.

class Core
    The Core class uses a singleton pattern. Use the core attribute to obtain an instance. All loaded plugins are exposed as attributes of the core object. These attributes in turn hold the functions contained in the plugin. Use plugins() to obtain a full list of all currently loaded plugins you may call this way.

num_threads
    The number of concurrent threads used by the core. Can be set to change the number. Setting to a value less than one makes it default to the number of hardware threads.

max_cache_size
    Set the upper framebuffer cache size after which memory is aggressively freed. The value is in megabytes.

used_cache_size
    The size of the core's current cache. The value is in bytes.

core_version
    Returns the core version as VapourSynthVersion tuple.

    NOTE: If you are writing a library, and are not retrieving this from the proxy, you should consider using vapoursynth.__version__ instead not to have to unnecessarily fetch the core and lock inside an environment.

api_version
    Returns the api version as VapourSynthAPIVersion tuple.

    NOTE: If you are writing a library, and are not retrieving this from the proxy, you should consider using vapoursynth.__api_version__ instead not to have to unnecessarily fetch the core and lock inside an environment.

plugins()
    Containing all loaded plugins.

get_video_format(id)
    Retrieve a Format object corresponding to the specified id. Returns None if the id is invalid.

query_video_format(color_family, sample_type, bits_per_sample, subsampling_w, subsampling_h)
    Retrieve a Format object corresponding to the format information, Invalid formats throw an exception.

create_video_frame(format, width, height)
    Creates a new frame with uninitialized planes with the given dimensions and format. This function is safe to call within a frame callback.

add_log_handler(handler_func)
    Installs a custom handler for the various error messages VapourSynth emits. The message handler is currently global, i.e. per process, not per VSCore instance. Returns a LogHandle object. handler_func is a callback function of the form func(MessageType, message).

remove_log_handler(handle)
    Removes a custom handler.

log_message(message_type, message)
    Send a message through VapourSynth’s logging framework.

rule6()
    Illegal behavior detection.

class Local
    Internally, there can be more than one core. This is usually the case in previewer-applications. Use this class to store variables that depend on the currently active core.

        l = Local()
        l.test = 1

class VideoNode
    Represents a video clip. The class itself supports indexing and slicing to perform trim, reverse and selectevery operations. Several operators are also defined for the VideoNode class: addition appends clips and multiplication repeats them. Note that slicing and indexing always return a new VideoNode object and not a VideoFrame.

format
    A Format object describing the frame data. If the format can change between frames, this value is None.

width
    The width of the video. This value will be 0 if the width and height can change between frames.

height
    The height of the video. This value will be 0 if the width and height can change between frames.

num_frames
    The number of frames in the clip.

fps The framerate represented as a Fraction. It is 0/1 when the clip has a variable framerate.

numerator
    The numerator of the framerate. If the clip has variable framerate, the value will be 0.

denominator
    The denominator of the framerate. If the clip has variable framerate, the value will be 0.

fps_num
    Deprecated, use fps.numerator instead

fps_den
    Deprecated, use fps.denominator instead

flags
    Special flags set for this clip. This attribute should normally be ignored.

get_frame(n)
    Returns a VideoFrame from position n.

get_frame_async(n)
    Returns a concurrent.futures.Future-object which result will be a VideoFrame instance or sets the exception thrown when rendering the frame.

    The future will always be in the running or completed state

get_frame_async(n, cb: callable)
    Renders a frame in another thread. When the frame is rendered, it will either call cb(Frame, None) on success or cb(None, Exception) if something fails.

    Added: R58

set_output(index=0, alpha=None, alt_output=0)
    Set the clip to be accessible for output. This is the standard way to specify which clip(s) to output. All VapourSynth tools (vsvfw, vsfs, vspipe) use the clip in index 0. It's possible to specify an additional containing the alpha to output at the same time. Currently only vspipe takes alpha into consideration when outputting. The alt_output argument is for optional alternate output modes. Currently it controls the FOURCCs used for VFW-style output with certain formats.

output(fileobj[, y4m = False, prefetch = 0, progress_update = None, backlog=-1])
    Write the whole clip to the specified file handle. It is possible to pipe to stdout by specifying sys.stdout as the file. YUV4MPEG2 headers will be added when y4m is true. The current progress can be reported by passing a callback function of the form func(current_frame, total_frames) to progress_update. The prefetch argument is only for debugging purposes and should never need to be changed. The backlog argument is only for debugging purposes and should never need to be changed.

frames([prefetch=None, backlog=None, close=False])
    Returns a generator iterator of all VideoFrames in the clip. It will render multiple frames concurrently.

    The prefetch argument defines how many frames are rendered concurrently. Is only there for debugging purposes and should never need to be changed. The backlog argument defines how many unconsumed frames (including those that did not finish rendering yet) vapoursynth buffers at most before it stops rendering additional frames. This argument is there to limit the memory this function uses storing frames. The close argument determines if the frame should be closed after each iteration step. It defaults to false to remain backward compatible.

is_inspectable(version=None)
    Returns a truthy value if you can use the node inspection API with a given version. The python inspection-api is versioned, as the underlying API is unstable at the time of writing. The version number will be incremented every time the python API changes. There will be no attempt to maintain backwards compatibility as long as the API is marked as unstable.

    This method may never return a truthy value.

    This is the only stable function in the current inspection api-implementation.

    NOTE: Be aware that introspection features must be enabled manually by the backing environment. Standalone Python-Scripts, not running inside vspipe or other editors, have introspection enabled automatically.

    WARNING: The graph-inspection-api is unstable. Omitting the version-argument will therefore always return None.

    The current version of the unstable python graph-inspection API is 0.

    Added: R58

Parameters
    version -- If None, it will use the version number of the last stable API.

class VideoOutputTuple
    This class is returned by get_output if the output is video.

clip
    A VideoNode-instance containing the color planes.

alpha
    A VideoNode-instance containing the alpha planes.

alt_output
    An integer with the alternate output mode to be used. May be ignored if no meaningful mapping exists.

class VideoFrame
    This class represents a video frame and all metadata attached to it.

format
    A Format object describing the frame data.

width
    The width of the frame.

height
    The height of the frame.

readonly
    If readonly is True, the frame data and properties cannot be modified.

props
    This attribute holds all the frame's properties as a dict. They are also mapped as sub-attributes for compatibility with older scripts. For more information, see: API Reference Note: This includes the data for matrix, transfer and primaries. (_Matrix, _Transfer, _Primaries) See Resize for more information.

copy()
    Returns a writable copy of the frame.

close()
    Forcefully releases the frame. Once freed, the you cannot call any function on the frame, nor use the associated FrameProps.

    To make sure you don't forget to close the frame, the frame is now a context-manager that automatically calls this method for you:

        with core.std.BlankClip().get_frame(0) as f:
            print(f.props)

closed
    Tells you if the frame has been closed. It will be False if the close()-method has not been called yet.

get_read_ptr(plane)
    Returns a pointer to the raw frame data. The data may not be modified. Note that this is a thin wrapper for the underlying C-api and as such calls to get_write_ptr, including the ones made internally by other functions in the Python bindings, may invalidate any pointers previously gotten to the frame with get_read_ptr when called.

get_write_ptr(plane)
    Returns a pointer to the raw frame data. It may be modified using ctypes or some other similar python package. Note that this is a thin wrapper for the underlying C-api and as such calls to get_write_ptr, including the ones made internally by other functions in the Python bindings, may invalidate any pointers previously gotten to the frame with get_read_ptr when called.

get_stride(plane)
    Returns the stride between lines in a plane.

readchunks()
    This method is usually used to dump the contents of a VideoFrame to disk. The returned generator yields contiguous chunks of the VideoFrame memory.

        with open('output.raw', 'wb') as file:
           with vs.core.std.BlankClip(color=[25, 50, 60]).get_frame(0) as f:
              for chunk in f.readchunks():
                 file.write(chunk)

    NOTE: Usually, the frame contents will be held in a contiguous array, and this method will yield n_planes of data chunks each holding the entire plane. Don't, however, take this for granted, as it can't be the case, and you will iterate over lines of plane data instead, which are assured to be contiguous.

    If you want to safely read the whole plane, use frame[plane_idx] to get the plane memoryview.

class VideoFormat
    This class represents all information needed to describe a frame format. It holds the general color type, subsampling, number of planes and so on. The names map directly to the C API so consult it for more detailed information.

id  A unique id identifying the format.

name
    A human readable name of the format.

color_family
    Which group of colorspaces the format describes.

sample_type
    If the format is integer or floating point based.

bits_per_sample
    How many bits are used to store one sample in one plane.

bytes_per_sample
    The actual storage is padded up to 2^n bytes for efficiency.

subsampling_w
    The subsampling for the second and third plane in the horizontal direction.

subsampling_h
    The subsampling for the second and third plane in the vertical direction.

num_planes
    The number of planes the format has.

replace(core=None, **kwargs)
    Returns a new format with the given modifications.

    The only supported attributes that can be replaced are color_family, sample_type, bits_per_sample, subsampling_w, subsampling_h.

    The optional core-parameter defines on which core the new format should be registered. This is usually not needed and defaults to the core of the current environment.

class AudioNode
    Represents an audio clip. The class itself supports indexing and slicing to perform trim, reverse and selectevery operations. Several operators are also defined for the AudioNode class: addition appends clips and multiplication repeats them. Note that slicing and indexing always return a new AudioNode object and not a AudioFrame.

sample_type
    If the format is integer or floating point based.

bits_per_sample
    How many bits are used to store one sample in one plane.

bytes_per_sample
    The actual storage is padded up to 2^n bytes for efficiency.

channel_layout
    A mask of used channels.

num_channels
    The number of channels the format has.

sample_rate
    Playback sample rate.

get_frame(n)
    Returns an AudioFrame from position n.

get_frame_async(n)
    Returns a concurrent.futures.Future-object which result will be an AudioFrame instance or sets the exception thrown when rendering the frame.

    The future will always be in the running or completed state

set_output(index=0)
    Set the clip to be accessible for output.

frames([prefetch=None, backlog=None])
    Returns a generator iterator of all AudioFrames in the clip. It will render multiple frames concurrently.

    The prefetch argument defines how many frames are rendered concurrently. Is only there for debugging purposes and should never need to be changed. The backlog argument defines how many unconsumed frames (including those that did not finish rendering yet) vapoursynth buffers at most before it stops rendering additional frames. This argument is there to limit the memory this function uses storing frames.

is_inspectable(version=None)
    Returns a truthy value if you can use the node inspection API with a given version. The python inspection-api is versioned, as the underlying API is unstable at the time of writing. The version number will be incremented every time the python API changes. There will be no attempt to maintain backwards compatibility as long as the API is marked as unstable.

    This method may never return a truthy value.

    This is the only stable function in the current inspection api-implementation.

    NOTE: Be aware that introspection features must be enabled manually by the backing environment. Standalone Python-Scripts, not running inside vspipe or other editors, have introspection enabled automatically.

    WARNING: The graph-inspection-api is unstable. Omitting the version-argument will therefore always return None.

    The current version of the unstable python graph-inspection API is 0.

    Added: R58

Parameters
    version -- If None, it will use the version number of the last stable API.

class AudioFrame
    This class represents an audio frame and all metadata attached to it.

sample_type
    If the format is integer or floating point based.

bits_per_sample
    How many bits are used to store one sample in one plane.

bytes_per_sample
    The actual storage is padded up to 2^n bytes for efficiency.

channel_layout
    A mask of used channels.

num_channels
    The number of channels the format has.

readonly
    If readonly is True, the frame data and properties cannot be modified.

props
    This attribute holds all the frame's properties as a dict. Note that audio frame properties are fairly non-sensical as a concept for audio due to an arbitrary number of samples being lumped together and rarely used.

copy()
    Returns a writable copy of the frame.

get_read_ptr(plane)
    Returns a pointer to the raw frame data. The data may not be modified.

get_write_ptr(plane)
    Returns a pointer to the raw frame data. It may be modified using ctypes or some other similar python package.

get_stride(plane)
    Returns the stride between lines in a plane.

class Plugin
    Plugin is a class that represents a loaded plugin and its namespace.

namespace
    The namespace of the plugin.

name
    The name string of the plugin.

version
    The version of the plugin returned as a PluginVersion tuple.

plugin_path
    The main library location of the plugin. Note that internal functions don't have a plugin path and instead return None.

identifier

functions()
    Containing all the functions in the plugin, You can access it by calling core.<namespace>.functions().

class Function
    Function is a simple wrapper class for a function provided by a VapourSynth plugin. Its main purpose is to be called and nothing else.

name
    The function name. Identical to the string used to register the function.

plugin
    The Plugin object the function belongs to.

signature
    Raw function signature string. Identical to the string used to register the function.

return_signature
    Raw function signature string. Identical to the return type string used register the function.

class Environment
    This class represents an environment.

    Some editors allow multiple vapoursynth-scripts to run in the same process, each of them comes with a different Core-instance and their own set of outputs. Each core-instance with their associated outputs represent their own environment.

    At any given time, only one environment can be active (in the same context). This class allows introspection about environments and allows to switch to them at will.

        env = get_current_environment()
        # sometime later
        with env.use():
          # Do stuff inside this env.

is_single()
    Returns True if the script is _not_ running inside a vsscript-Environment. If it is running inside a vsscript-Environment, it returns False.

env_id
    Return -1 if the script is not running inside a vsscript-Environment. Otherwise, it will return the current environment-id.

single
    See is_single()

alive
    Has the environment been destroyed by the underlying application?

copy()
    Creates a copy of the environment-object.

    Added: R51

use()
    Returns a context-manager that enables the given environment in the block enclosed in the with-statement and restores the environment to the one defined before the with-block has been encountered.

        env = get_current_environment()
        with env.use():
            with env.use():
                pass

    Added: R51

get_current_environment()
    Returns an Environment-object representing the environment the script is currently running in. It will raise an error if we are currently not inside any script-environment while vsscript is being used.

    This function is intended for Python-based editors using vsscript.

    Added: R51

class EnvironmentPolicy
    This class is intended for subclassing by custom Script-Runners and Editors. Normal users don't need this class. Most methods implemented here have corresponding APIs in other parts of this module.

    An instance of this class controls which environment is activated in the current context. The exact meaning of "context" is defined by the concrete EnvironmentPolicy. A environment is represented by a EnvironmentData-object.

    To use this class, first create a subclass and then use register_policy() to get VapourSynth to use your policy. This must happen before vapoursynth is first used. VapourSynth will automatically register an internal policy if it needs one. The subclass must be weak-referenciable!

    Once the method on_policy_registered() has been called, the policy is responsible for creating and managing environments.

    Special considerations have been made to ensure the functions of class cannot be abused. You cannot retrieve the current running policy yourself. The additional API exposed by "on_policy_registered" is only valid if the policy has been registered. Once the policy is unregistered, all calls to the additional API will fail with a RuntimeError.

    Added: R51

on_policy_registered(special_api)
    This method is called when the policy has successfully been registered. It proivdes additional internal methods that are hidden as they are useless and or harmful unless you implement your own policy.

Parameters
    special_api -- This is a EnvironmentPolicyAPI-object that exposes additional API

on_policy_cleared()
    This method is called once the python-process exits or when unregister_policy is called by the environment-policy. This allows the policy to free the resources used by the policy.

get_current_environment()
    This method is called by the module to detect which environment is currently running in the current context. If None is returned, it means that no environment is currently active.

Returns
    An EnvironmentData-object representing the currently active environment in the current context.

set_environment(environment)
    This method is called by the module to change the currently active environment. If None is passed to this function the policy may switch to another environment of its choosing.

    Note: The function is responsible to check whether or not the environment is alive. If a dead environment is passed, it should act like None has been passed instead of the dead environment but must never error.

Parameters
    environment -- The EnvironmentData to enable in the current context.

Returns
    The environment that was enabled previously.

is_alive(environment)
    Is the current environment still active and managed by the policy.

    The default implementation checks if EnvironmentPolicyAPI.destroy_environment has been called on the environment.

class EnvironmentPolicyAPI
    This class is intended to be used by custom Script-Runners and Editors. An instance of this class exposes an additional API. The methods are bound to a specific EnvironmentPolicy-instance and will only work if the policy is currently registered.

    Added: R51

wrap_environment(environment)
    Creates a new Environment-object bound to the passed environment-id.

    WARNING: This function does not check if the id corresponds to a live environment as the caller is expected to know which environments are active.

create_environment(flags=0)
    Returns a Environment that is used by the wrapper for context sensitive data used by VapourSynth. For example it holds the currently active core object as well as the currently registered outputs.

set_logger(environment, callback)
    This function sets the logger for the given environment.

    This logger is a callback function that accepts two parameters: Level, which is an instance of vs.MessageType and a string containing the log message.

destroy_environment(environment)
    Marks an environment as destroyed. Older environment-policy implementations that don't use this function still work.

    Either EnvironmentPolicy.is_alive must be overridden or this method be used to mark the environment as destroyed.

    Added: R52

unregister_policy()
    Unregisters the policy it is bound to and allows another policy to be registered.

get_vapoursynth_api(version)
    Exposes getVapoursynthAPI to python. Returns a ctypes.c_void_p.

    Access to this function is provisional and might be removed if it is abused too much.

    Added: R62

get_core_ptr(environment)
    Returns a ctypes.c_void_p pointing to the Core*-object that powers the environment.

    Access to this function is provisional and might be removed if it is abused too much.

    Added: R62

register_policy(policy)
    This function is intended for use by custom Script-Runners and Editors. It installs your custom EnvironmentPolicy. This function only works if no other policy has been installed.

    If no policy is installed, the first environment-sensitive call will automatically register an internal policy.

    Added: R50

    NOTE: This must be done before VapourSynth is used in any way. Here is a non-exhaustive list that automatically register a policy:

•   Using "vsscript_init" in "VSScript.h"

•   Using get_outputs()

•   Using get_output()

•   Using clear_output()

•   Using clear_outputs()

•   Using get_current_environment()

•   Accessing any attribute of core

_try_enable_introspection(version=None)
    Tries to enable introspection. Returns true if it succeeds.

Parameters
    version -- If not passed it will use the newest stable introspection-api.

    Added: R58

has_policy()
    This function is intended for subclassing by custom Script-Runners and Editors. This function checks if a EnvironmentPolicy has been installed.

    Added: R50

class EnvironmentData
    Internal class that stores the context sensitive data that VapourSynth needs. It is an opaque object whose attributes you cannot access directly.

    A normal user has no way of getting an instance of this object. You can only encounter EnvironmentData-objects if you work with EnvironmentPolicies.

    This object is weak-referenciable meaning you can get a callback if the environment-data object is actually being freed (i.e. no other object holds an instance to the environment data.)

    Added: R50

class Func
    Func is a simple wrapper class for VapourSynth VSFunc objects. Its main purpose is to be called and manage reference counting.

exception Error
    The standard exception class. This exception is thrown on most errors encountered in VapourSynth.

  Constants

  Video

  Color Family

The color family constants describe groups of formats and the basic way their color information is stored. You should be familiar with all of them apart from maybe YCOCG and COMPAT. The latter is a special junk category for non-planar formats. These are the declared constants in the module:

    UNDEFINED
    RGB
    YUV
    GRAY

  Format

Format constants exactly describe a format. All common and even more uncommon formats have handy constants predefined so in practice no one should really need to register one of their own. These values are mostly used by the resizers to specify which format to convert to. The naming system is quite simple. First the color family, then the subsampling (only YUV has it) and after that how many bits per sample in one plane. The exception to this rule is RGB, which has the bits for all 3 planes added together. The long list of values:

    NONE
    GRAY8
    GRAY9
    GRAY10
    GRAY12
    GRAY14
    GRAY16
    GRAY32
    GRAYH
    GRAYS
    YUV420P8
    YUV422P8
    YUV444P8
    YUV410P8
    YUV411P8
    YUV440P8
    YUV420P9
    YUV422P9
    YUV444P9
    YUV420P10
    YUV422P10
    YUV444P10
    YUV420P12
    YUV422P12
    YUV444P12
    YUV420P14
    YUV422P14
    YUV444P14
    YUV420P16
    YUV422P16
    YUV444P16
    YUV444PH
    YUV444PS
    RGB24
    RGB27
    RGB30
    RGB36
    RGB42
    RGB48
    RGBH
    RGBS

  Chroma Location

    CHROMA_LEFT
    CHROMA_CENTER
    CHROMA_TOP_LEFT
    CHROMA_TOP
    CHROMA_BOTTOM_LEFT
    CHROMA_BOTTOM

  Field Based

    FIELD_PROGRESSIVE
    FIELD_TOP
    FIELD_BOTTOM

  Color Range

    RANGE_FULL
    RANGE_LIMITED

  Matrix Coefficients

    MATRIX_RGB
    MATRIX_BT709
    MATRIX_UNSPECIFIED
    MATRIX_FCC
    MATRIX_BT470_BG
    MATRIX_ST170_M
    MATRIX_ST240_M
    MATRIX_YCGCO
    MATRIX_BT2020_NCL
    MATRIX_BT2020_CL
    MATRIX_CHROMATICITY_DERIVED_NCL
    MATRIX_CHROMATICITY_DERIVED_CL
    MATRIX_ICTCP

  TransferCharacteristics

    TRANSFER_BT709
    TRANSFER_UNSPECIFIED
    TRANSFER_BT470_M
    TRANSFER_BT470_BG
    TRANSFER_BT601
    TRANSFER_ST240_M
    TRANSFER_LINEAR
    TRANSFER_LOG_100
    TRANSFER_LOG_316
    TRANSFER_IEC_61966_2_4
    TRANSFER_IEC_61966_2_1
    TRANSFER_BT2020_10
    TRANSFER_BT2020_12
    TRANSFER_ST2084
    TRANSFER_ARIB_B67

  Color Primaries

    PRIMARIES_BT709
    PRIMARIES_UNSPECIFIED
    PRIMARIES_BT470_M
    PRIMARIES_BT470_BG
    PRIMARIES_ST170_M
    PRIMARIES_ST240_M
    PRIMARIES_FILM
    PRIMARIES_BT2020
    PRIMARIES_ST428
    PRIMARIES_ST431_2
    PRIMARIES_ST432_1
    PRIMARIES_EBU3213_E

  Audio

  Channels

    FRONT_LEFT
    FRONT_RIGHT
    FRONT_CENTER
    LOW_FREQUENCY
    BACK_LEFT
    BACK_RIGHT
    FRONT_LEFT_OF_CENTER
    FRONT_RIGHT_OF_CENTER
    BACK_CENTER
    SIDE_LEFT
    SIDE_RIGHT
    TOP_CENTER
    TOP_FRONT_LEFT
    TOP_FRONT_CENTER
    TOP_FRONT_RIGHT
    TOP_BACK_LEFT
    TOP_BACK_CENTER
    TOP_BACK_RIGHT
    STEREO_LEFT
    STEREO_RIGHT
    WIDE_LEFT
    WIDE_RIGHT
    SURROUND_DIRECT_LEFT
    SURROUND_DIRECT_RIGHT
    LOW_FREQUENCY2

  Sample Type

    INTEGER
    FLOAT

FUNCTION REFERENCE

  General Functions

  LoadAllPlugins

std.LoadAllPlugins(string path)
    Loads all native VapourSynth plugins found in the specified path. Plugins that fail to load are silently skipped.

    Beware of Python's escape character, this will fail:

        LoadPlugin(path='c:\plugins')

    Correct ways:

        LoadPlugin(path='c:/plugins')
        LoadPlugin(path=r'c:\plugins')
        LoadPlugin(path='c:\\plugins\\')

  LoadPlugin

std.LoadPlugin(string path, bint altsearchpath = False)
    Load a native VapourSynth plugin. If successful, the loaded plugin's functions will end up in their own namespace.

    Returns an error if a plugin with the same identifier or namespace already has been loaded. This is to prevent naming collisions or multiple versions of the same plugin being loaded at once.

    Plugins are normally loaded with a very specific search order for dependencies. Setting altsearchpath modifies this behavior to also include dlls in the PATH.

    Beware of Python's escape character, this will fail:

        LoadPlugin(path='c:\plugins\filter.dll')

    Correct ways:

        LoadPlugin(path='c:/plugins/filter.dll')
        LoadPlugin(path=r'c:\plugins\filter.dll')
        LoadPlugin(path='c:\\plugins\\filter.dll')

  LoadPlugin (Avisynth Compatibility)

avs.LoadPlugin(string path)
    Load an Avisynth 2.5 (32 bit only), 2.6 (32 and 64 bit) or Avisynth+ (32 and 64 bit) plugin. If successful, the loaded plugin's functions will end up in the avs namespace. Note that in the case of Avisynth+ there's no way to use the formats combined with alpha or higher bitdepth packed RGB. Coincidentally there are no plugins that use this in a meaningful way yet.

    The compatibility module can work with a large number of Avisynth's plugins. However, the wrapping is not complete, so the following things will cause problems:

•   The plugin expects YUY2 or RGB32 input. In this case provide input in either YUV422P8 or RGB24 format pass compatpack=True as an argument to the Avisynth function.

•   The plugin tries to call env->invoke(). These calls are ignored when it is safe to do so, but otherwise they will most likely trigger a fatal error.

•   Plugins trying to read global variables. There are no global variables.

    If there are function name collisions functions will have a number appended to them to make them distinct. For example if three functions are named func then they will be named func, func_2 and func_3. This means that Avisynth functions that have multiple overloads (rare) will give each overload a different name.

    Note that if you are really insane you can load Avisynth's VirtualDub plugin loader and use VirtualDub plugins as well. Function overloads are very common when dealing with VirtualDub.

    Beware of Python's escape character, this will fail:

        LoadPlugin(path='c:\plugins\filter.dll')

    Correct ways:

        LoadPlugin(path='c:/plugins/filter.dll')
        LoadPlugin(path=r'c:\plugins\filter.dll')
        LoadPlugin(path='c:\\plugins\\filter.dll')

  SetMaxCPU

std.SetMaxCPU(string cpu)
    This function is only intended for testing and debugging purposes and sets the maximum used instruction set for optimized functions.

    Possible values for x86: "avx2", "sse2", "none"

    Other platforms: "none"

    By default all supported cpu features are used.

  Video Functions

  AddBorders

std.AddBorders(vnode clip[, int left=0, int right=0, int top=0, int bottom=0, float[] color=<black>])
    Adds borders to frames. The arguments specify the number of pixels to add on each side. They must obey the subsampling restrictions. The newly added borders will be set to color.

  AssumeFPS

std.AssumeFPS(vnode clip[, vnode src, int fpsnum, int fpsden=1])
    Returns a clip with the framerate changed. This does not in any way modify the frames, only their metadata.

    The framerate to assign can either be read from another clip, src, or given as a rational number with fpsnum and fpsden.

    It is an error to specify both src and fpsnum.

    AssumeFPS overwrites the frame properties _DurationNum and _DurationDen with the frame duration computed from the new frame rate.

  AverageFrames

std.AverageFrames(vnode[] clips, float[] weights[, float scale, bint scenechange, int[] planes])
    AverageFrames has two main modes depending on whether one or multiple clips are supplied. The filter is named AverageFrames since using ones for weights is an easy way to average many frames together but it can also be seen as a temporal or multiple frame convolution.

    If multiple clips are supplied then the frames from each of the clips are multiplied by the respective weights, summed together and divided by scale before being output. Note that only integer weights and scale are allowed for integer input formats.

    If a single clip is supplied then an odd number of weights are needed and they will instead be temporally centered on the current frame of the clip. The rest works as multiple clip mode with the only difference being that scenechange can be set to avoid averaging frames over scene changes. If this happens then all the weights beyond a scene change are instead applied to the frame right before it.

    At most 31 weights can be supplied.

  Binarize/BinarizeMask

std.Binarize(vnode clip[, float[] threshold, float[] v0, float[] v1, int[] planes=[0, 1, 2]])

std.BinarizeMask(vnode clip[, float[] threshold, float[] v0, float[] v1, int[] planes=[0, 1, 2]])
    Turns every pixel in the image into either v0, if it's below threshold, or v1, otherwise. The BinarizeMask version is intended for use on mask clips where all planes have the same value range and only differs in the default values of v0 and v1.

clip
    Clip to process. It must have integer sample type and bit depth between 8 and 16, or float sample type and bit depth of 32. If there are any frames with other formats, an error will be returned.

threshold
    Defaults to the middle point of range allowed by the format. Can be specified for each plane individually.

v0  Value given to pixels that are below threshold. Can be specified for each plane individually. Defaults to the lower bound of the format.

v1  Value given to pixels that are greater than or equal to threshold. Defaults to the maximum value allowed by the format. Can be specified for each plane individually. Defaults to the upper bound of the format.

planes
    Specifies which planes will be processed. Any unprocessed planes will be simply copied.

  BlankClip

std.BlankClip([vnode clip, int width=640, int height=480, int format=vs.RGB24, int length=(10*fpsnum)/fpsden, int fpsnum=24, int fpsden=1, float[] color=<black>, bint keep=0, bint varsize=0, bint varformat=0])
    Generates a new empty clip. This can be useful to have when editing video or for testing. The default is a 640x480 RGB24 24fps 10 second long black clip. Instead of specifying every property individually, BlankClip can also copy the properties from clip. If both an argument such as width, and clip are set, then width will take precedence.

    If keep is set, a reference to the same frame is returned on every request. Otherwise a new frame is generated every time. There should usually be no reason to change this setting.

    If varsize is set, a clip with variable size will be returned. The frames themselves will still have the size given by the width and height arguments.

    If varformat is set, a clip with variable format will be returned. The frames themselves will have the format given by the format argument.

    It is never an error to use BlankClip.

  BoxBlur

std.BoxBlur(vnode clip[, int[] planes, int hradius = 1, int hpasses = 1, int vradius = 1, int vpasses = 1])
    Performs a box blur which is fast even for large radius values. Using multiple passes can be used to fairly cheaply approximate a gaussian blur. A radius of 0 means no processing is performed.

  ClipToProp

std.ClipToProp(vnode clip, vnode mclip[, string prop='_Alpha'])
    Stores each frame of mclip as a frame property named prop in clip. This is primarily intended to attach mask/alpha clips to another clip so that editing operations will apply to both. Unlike most other filters the output length is derived from the second argument named mclip.

    If the attached mclip does not represent the alpha channel, you should set prop to something else.

    It is the inverse of PropToClip().

  Convolution

std.Convolution(vnode clip, float[] matrix[, float bias=0.0, float divisor=0.0, int[] planes=[0, 1, 2], bint saturate=True, string mode="s"])
    Performs a spatial convolution.

    Here is how a 3x3 convolution is done. Each pixel in the 3x3 neighbourhood is multiplied by the corresponding coefficient in matrix. The results of the nine multiplications are added together, then this sum is divided by divisor. Next, bias is added, and the result is rounded to the nearest larger integer. If this integer result is negative and the saturate parameter is False, it is multiplied by -1. Finally, the result is clamped to the format's range of valid values.

clip
    Clip to process. It must have integer sample type and bit depth between 8 and 16, or float sample type and bit depth of 32. If there are any frames with other formats, an error will be returned.

matrix
    Coefficients for the convolution.

    When mode is "s", this must be an array of 9 or 25 numbers, for a 3x3 or 5x5 convolution, respectively.

    When mode is not "s", this must be an array of 3 to 25 numbers, with an odd number of elements.

    The values of the coefficients must be between -1023 and 1023 (inclusive). The coefficients are rounded to integers when the input is an integer format.

    This is how the elements of matrix correspond to the pixels in a 3x3 neighbourhood:

        1 2 3
        4 5 6
        7 8 9

    It's the same principle for the other types of convolutions. The middle element of matrix always corresponds to the center pixel.

bias
    Value to add to the final result of the convolution (before clamping the result to the format's range of valid values).

divisor
    Divide the output of the convolution by this value (before adding bias).

    If this parameter is 0.0 (the default), the output of the convolution will be divided by the sum of the elements of matrix, or by 1.0, if the sum is 0.

planes
    Specifies which planes will be processed. Any unprocessed planes will be simply copied.

saturate
    The final result is clamped to the format's range of valid values (0 .. (2**bitdepth)-1). Therefore, if this parameter is True, negative values become 0. If this parameter is False, it's instead the absolute value that is clamped and returned.

mode
    Selects the type of convolution. Possible values are "s", for square, "h" for horizontal, "v" for vertical, and "hv" or "vh" for both horizontal and vertical.

    How to apply a simple blur equivalent to Avisynth's Blur(1):

        Convolution(matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1])

    How to apply a stronger blur equivalent to Avisynth's Blur(1.58):

        Convolution(matrix=[1, 1, 1, 1, 1, 1, 1, 1, 1])

  CopyFrameProps

std.CopyFrameProps(vnode clip, vnode prop_src[, string[] props])
    Returns clip but with all the frame properties replaced with the ones from the clip in prop_src. Note that if clip is longer than prop_src then the last source frame's properties will be used instead.

    If props is set only the specified properties will be copied. If the prop_src doesn't have the property it is deleted. In this mode all other properties in clip remain unchanged.

  Crop/CropAbs

std.Crop(vnode clip[, int left=0, int right=0, int top=0, int bottom=0])

std.CropAbs(vnode clip, int width, int height[, int left=0, int top=0])
    Crops the frames in a clip.

    Crop is the simplest to use of the two. The arguments specify how many pixels to crop from each side. This function used to be called CropRel which is still an alias for it.

    CropAbs, on the other hand, is special, because it can accept clips with variable frame sizes and crop out a fixed size area, thus making it a fixed size clip.

    Both functions return an error if the whole picture is cropped away, if the cropped area extends beyond the input or if the subsampling restrictions aren't met.

  Deflate/Inflate

std.Deflate(vnode clip[, int[] planes=[0, 1, 2], float threshold])
    Replaces each pixel with the average of the eight pixels in its 3x3 neighbourhood, but only if that average is less than the center pixel.

clip
    Clip to process. It must have integer sample type and bit depth between 8 and 16, or float sample type and bit depth of 32. If there are any frames with other formats, an error will be returned.

planes
    Specifies which planes will be processed. Any unprocessed planes will be simply copied.

threshold
    Allows to limit how much pixels are changed. Output pixels will not become less than input - threshold. The default is no limit.

std.Inflate(vnode clip[, int[] planes=[0, 1, 2], int threshold=65535])
    Replaces each pixel with the average of the eight pixels in its 3x3 neighbourhood, but only if that average is greater than the center pixel.

clip
    Clip to process. It must have integer sample type and bit depth between 8 and 16, or float sample type and bit depth of 32. If there are any frames with other formats, an error will be returned.

planes
    Specifies which planes will be processed. Any unprocessed planes will be simply copied.

threshold
    Allows to limit how much pixels are changed. Output pixels will not become greater than input + threshold. The default is no limit.

  DeleteFrames

std.DeleteFrames(vnode clip, int[] frames)
    Deletes the specified frames.

    All frame numbers apply to the input clip.

    Returns an error if the same frame is deleted twice or if all frames in a clip are deleted.

  DoubleWeave

std.DoubleWeave(vnode clip[, bint tff])
    Weaves the fields back together from a clip with interleaved fields.

    Since VapourSynth only has a weak notion of field order internally, tff may have to be set. Setting tff to true means top fields first and false means bottom fields first. Note that the _Field frame property, if present and in a valid combination, takes precedence over tff.

    DoubleWeave's output has the same number of frames as the input. One must use DoubleWeave together with SelectEvery to undo the effect of SeparateFields:

        sep = core.std.SeparateFields(source)
        ...
        woven = core.std.DoubleWeave(sep)
        woven = core.std.SelectEvery(woven, 2, 0)

    The _Field frame property is deleted and _FieldBased is set accordingly.

  DuplicateFrames

std.DuplicateFrames(vnode clip, int[] frames)
    Duplicates the specified frames.

    A frame may be duplicated several times.

    All frame numbers apply to the input clip.

  Expr

std.Expr(vnode[] clips, string[] expr[, int format])
    Expr evaluates an expression per pixel for up to 26 input clips. The expression, expr, is written using reverse polish notation and can be specified for each plane individually. The expression given for the previous plane is used if the expr array contains fewer expressions than the input clip has planes. In practice this means that a single expression will be applied to all planes by default.

    Specifying an empty string as the expression enables a fast plane copy from the first specified clip, when possible. If it is not possible due to the output format being incompatible, the plane contents will be undefined.

    Since the expression is evaluated at runtime, there are a few pitfalls. In order to keep speed up, the input ranges are not normalized to the usual floating point ranges. Instead they are left as is, meaning that an 8 bit clip will have values in the 0-255 range and a 10 bit clip will have values in the 0-1023 range. Note that floating point clips are even more difficult, as most channels are stored in the 0-1 range with the exception of U, V, Co and Cg planes, which are in the -0.5-0.5 range. If you mix clips with different input formats this must be taken into consideration.

    When the output format uses integer samples, the result of the expression is clamped to the [0, 2**bits_per_sample-1] range. When the output format uses float samples, the result of the expression is stored without any clamping.

    By default the output format is the same as the first input clip's format. You can override it by setting format. The only restriction is that the output format must have the same subsampling as the input clips and be 8..16 bit integer or 32 bit float. 16 bit float is also supported on cpus with the f16c instructions.

    Logical operators are also a bit special, since everything is done in floating point arithmetic. All values greater than 0 are considered true for the purpose of comparisons. Logical operators return 0.0 for false and 1.0 for true in their operations.

    Since the expression is being evaluated at runtime, there are also the stack manipulation operators, swap and dup. The former swaps the topmost and second topmost values, and the latter duplicates the topmost stack value.

    These operators also have swapN and dupN forms that allow a value N steps up in the stack to be swapped or duplicated. The top value of the stack has index zero meaning that dup is equivalent to dup0 and swap is equivalent to swap1. This is because swapN always swaps with the topmost value at index 0.

    Expressions are converted to byte-code or machine-code by an optimizing compiler and are not guaranteed to evaluate in the order originally written. The compiler assumes that all input values are finite (i.e neither NaN nor INF) and that no operator will produce a non-finite value. Such expressions are invalid. This is especially important for the transcendental operators:

•   exp - expression must not overflow (i.e. x <= 88)

•   log - input must be finite and non-negative (i.e. x >= 0 && x <= 3e+38)

•   pow - base must be finite and non-negative. Result must not overflow (i.e. x >= 0 && x <= 3e+38; 1e-38 <= result <= 3e+38)

    Clip load operators:

        x-z, a-w

    The operators taking one argument are:

        exp log sqrt sin cos abs not dup dupN

    The operators taking two arguments are:

        + - * / max min pow > < = >= <= and or xor swap swapN

    The operators taking three arguments are:

        ?

    For example these operations:

        a b c ?
        d e <
        f abs

    Are equivalent to these operations in C:

        a ? b : c
        d < e
        abs(f)

    The sin/cos operators are approximated to within 2e-6 absolute error for inputs with magnitude up to 1e5, and there is no accuracy guarantees for inputs whose magnitude is larger than 2e5.

    How to average the Y planes of 3 YUV clips and pass through the UV planes unchanged (assuming same format):

        std.Expr(clips=[clipa, clipb, clipc], expr=["x y + z + 3 /", "", ""])

    How to average the Y planes of 3 YUV clips and pass through the UV planes unchanged (different formats):

        std.Expr(clips=[clipa16bit, clipb10bit, clipa8bit],
           expr=["x y 64 * + z 256 * + 3 /", ""])

    Setting the output format because the resulting values are illegal in a 10 bit clip (note that the U and V planes will contain junk since direct copy isn't possible):

        std.Expr(clips=[clipa10bit, clipb16bit, clipa8bit],
           expr=["x 64 * y + z 256 * + 3 /", ""], format=vs.YUV420P16)

  FlipVertical/FlipHorizontal

std.FlipVertical(vnode clip)

std.FlipHorizontal(vnode clip)
    Flips the clip in the vertical or horizontal direction.

  FrameEval

std.FrameEval(vnode clip, func eval[, vnode[] prop_src, vnode[] clip_src])
    Allows an arbitrary function to be evaluated every frame. The function gets the frame number, n, as input and should return a clip the output frame can be requested from.

    The clip argument is only used to get the output format from since there is no reliable automatic way to deduce it.

    When using the argument prop_src the function will also have an argument, f, containing the current frames. This is mainly so frame properties can be accessed and used to make decisions. Note that f will only be a list if more than one prop_src clip is provided.

    The clip_src argument only exists as a way to hint which clips are referenced in the eval function which can improve caching and graph generation. Its use is encouraged but not required.

    This function can be used to accomplish the same things as Animate, ScriptClip and all the other conditional filters in Avisynth. Note that to modify per frame properties you should use ModifyFrame.

    How to animate a BlankClip to fade from white to black. This is the simplest use case without using the prop_src argument:

        import vapoursynth as vs
        import functools
        base_clip = vs.core.std.BlankClip(format=vs.YUV420P8, length=1000, color=[255, 128, 128])
        def animator(n, clip):
           if n > 255:
              return clip
           else:
              return vs.core.std.BlankClip(format=vs.YUV420P8, length=1000, color=[n, 128, 128])
        animated_clip = vs.core.std.FrameEval(base_clip, functools.partial(animator, clip=base_clip))
        animated_clip.set_output()

    How to perform a simple per frame auto white balance. It shows how to access calculated frame properties and use them for conditional filtering:

        import vapoursynth as vs
        import functools
        import math
        def GrayWorld1Adjust(n, f, clip, core):
           small_number = 0.000000001
           red   = f[0].props['PlaneStatsAverage']
           green = f[1].props['PlaneStatsAverage']
           blue  = f[2].props['PlaneStatsAverage']
           max_rgb = max(red, green, blue)
           red_corr   = max_rgb/max(red, small_number)
           green_corr = max_rgb/max(green, small_number)
           blue_corr  = max_rgb/max(blue, small_number)
           norm = max(blue, math.sqrt(red_corr*red_corr + green_corr*green_corr + blue_corr*blue_corr) / math.sqrt(3), small_number)
           r_gain = red_corr/norm
           g_gain = green_corr/norm
           b_gain = blue_corr/norm
           return core.std.Expr(clip, expr=['x ' + repr(r_gain) + ' *', 'x ' + repr(g_gain) + ' *', 'x ' + repr(b_gain) + ' *'])
        def GrayWorld1(clip, matrix_s=None):
           rgb_clip = vs.core.resize.Bilinear(clip, format=vs.RGB24)
           r_avg = vs.core.std.PlaneStats(rgb_clip, plane=0)
           g_avg = vs.core.std.PlaneStats(rgb_clip, plane=1)
           b_avg = vs.core.std.PlaneStats(rgb_clip, plane=2)
           adjusted_clip = vs.core.std.FrameEval(rgb_clip, functools.partial(GrayWorld1Adjust, clip=rgb_clip, core=vs.core), prop_src=[r_avg, g_avg, b_avg])
           return vs.core.resize.Bilinear(adjusted_clip, format=clip.format.id, matrix_s=matrix_s)
        vs.core.std.LoadPlugin(path='BestSource.dll')
        main = vs.core.bs.VideoSource(source='...')
        main = GrayWorld1(main)
        main.set_output()

  FreezeFrames

std.FreezeFrames(vnode clip, int[] first, int[] last, int[] replacement)
    FreezeFrames replaces all the frames in the [first,last] range (inclusive) with replacement.

    A single call to FreezeFrames can freeze any number of ranges:

        core.std.FreezeFrames(input, first=[0, 100, 231], last=[15, 112, 300], replacement=[8, 50, 2])

    This replaces [0,15] with 8, [100,112] with 50, and [231,300] with 2 (the original frame number 2, not frame number 2 after it was replaced with number 8 by the first range).

    The frame ranges must not overlap.

  Interleave

std.Interleave(vnode[] clips[, bint extend=0, bint mismatch=0, bint modify_duration=True])
    Returns a clip with the frames from all clips interleaved. For example, Interleave(clips=[A, B]) will return A.Frame 0, B.Frame 0, A.Frame 1, B.Frame...

    The extend argument controls whether or not all input clips will be treated as if they have the same length as the longest clip.

    Interleaving clips with different formats or dimensions is considered an error unless mismatch is true.

    If modify_duration is set then the output clip's frame rate is the first input clip's frame rate multiplied by the number of input clips. The frame durations are divided by the number of input clips. Otherwise the first input clip's frame rate is used.

  Invert/InvertMask

std.Invert(vnode clip[, int[] planes=[0, 1, 2]])

std.InvertMask(vnode clip[, int[] planes=[0, 1, 2]])
    Inverts the pixel values. Specifically, it subtracts the value of the input pixel from the format's maximum allowed value. The InvertMask version is intended for use on mask clips where all planes have the same maximum value regardless of the colorspace.

clip
    Clip to process. It must have integer sample type and bit depth between 8 and 16, or float sample type and bit depth of 32. If there are any frames with other formats, an error will be returned.

planes
    Specifies which planes will be processed. Any unprocessed planes will be simply copied.

  Levels

std.Levels(vnode clip[, float min_in, float max_in, float gamma=1.0, float min_out, float max_out, int[] planes=[0, 1, 2]])
    Adjusts brightness, contrast, and gamma.

    The range [min_in, max_in] is remapped into [min_out, max_out]. Note that the range behavior is unintuitive for YUV float formats since the assumed range will be 0-1 even for the UV-planes.

    For example, to convert from limited range YUV to full range (8 bit):

        clip = std.Levels(clip, min_in=16, max_in=235, min_out=0, max_out=255, planes=0)
        clip = std.Levels(clip, min_in=16, max_in=240, min_out=0, max_out=255, planes=[1,2])

    The default value of max_in and max_out is the format's minimum and maximum allowed values respectively. Note that all input is clamped to the input range to prevent out of range output.

    WARNING:

The default ranges are 0-1 for floating point formats. This may have an undesired
    effect on YUV formats.

clip
    Clip to process. It must have integer sample type and bit depth between 8 and 16, or float sample type and bit depth of 32. If there are any frames with other formats, an error will be returned.

gamma
    Controls the degree of non-linearity of the conversion. Values greater than 1.0 brighten the output, while values less than 1.0 darken it.

planes
    Specifies which planes will be processed. Any unprocessed planes will be simply copied.

  Limiter

std.Limiter(vnode clip[, float[] min, float[] max, int[] planes=[0, 1, 2]])
    Limits the pixel values to the range [min, max].

clip
    Clip to process. It must have integer sample type and bit depth between 8 and 16, or float sample type and bit depth of 32. If there are any frames with other formats, an error will be returned.

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

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

planes
    Specifies which planes will be processed. Any unprocessed planes will be simply copied.

  Loop

std.Loop(vnode clip[, int times=0])
    Returns a clip with the frames or samples repeated over and over again. If times is less than 1 the clip will be repeated until the maximum clip length is reached, otherwise it will be repeated times times.

    In Python, std.Loop can also be invoked using the multiplication operator.

  Lut

std.Lut(vnode clip[, int[] planes, int[] lut, float[] lutf, func function, int bits, bint floatout])
    Applies a look-up table to the given clip. The lut can be specified as either an array of 2^bits_per_sample values or given as a function having an argument named x to be evaluated. Either lut, lutf or function must be used. The lut will be applied to the planes listed in planes and the other planes will simply be passed through unchanged. By default all planes are processed.

    If floatout is set then the output will be floating point instead, and either lutf needs to be set or function always needs to return floating point values.

    How to limit YUV range (by passing an array):

        luty = []
        for x in range(2**clip.format.bits_per_sample):
           luty.append(max(min(x, 235), 16))
        lutuv = []
        for x in range(2**clip.format.bits_per_sample):
           lutuv.append(max(min(x, 240), 16))
        ret = Lut(clip=clip, planes=0, lut=luty)
        limited_clip = Lut(clip=ret, planes=[1, 2], lut=lutuv)

    How to limit YUV range (using a function):

        def limity(x):
           return max(min(x, 235), 16)
        def limituv(x):
           return max(min(x, 240), 16)
        ret = Lut(clip=clip, planes=0, function=limity)
        limited_clip = Lut(clip=ret, planes=[1, 2], function=limituv)

  Lut2

std.Lut2(vnode clipa, vnode clipb[, int[] planes, int[] lut, float[] lutf, func function, int bits, bint floatout])
    Applies a look-up table that takes into account the pixel values of two clips. The lut needs to contain 2^(clip1.bits_per_sample + clip2.bits_per_sample) entries and will be applied to the planes listed in planes. Alternatively a function taking x and y as arguments can be used to make the lut. The other planes will be passed through unchanged. By default all planes are processed.

    Lut2 also takes an optional bit depth parameter, bits, which defaults to the bit depth of the first input clip, and specifies the bit depth of the output clip. The user is responsible for understanding the effects of bit depth conversion, specifically from higher bit depths to lower bit depths, as no scaling or clamping is applied.

    If floatout is set then the output will be floating point instead, and either lutf needs to be set or function always needs to return floating point values.

    How to average 2 clips:

        lut = []
        for y in range(2 ** clipy.format.bits_per_sample):
           for x in range(2 ** clipx.format.bits_per_sample):
              lut.append((x + y)//2)
        Lut2(clipa=clipa, clipb=clipb, lut=lut)

    How to average 2 clips with a 10-bit output:

        def f(x, y):
           return (x*4 + y)//2
        Lut2(clipa=clipa8bit, clipb=clipb10bit, function=f, bits=10)

  MakeDiff

std.MakeDiff(vnode clipa, vnode clipb[, int[] planes])
    Calculates the difference between clipa and clipb and clamps the result. By default all planes are processed. This function is usually used together with MergeDiff, which can be used to add back the difference.

    Unsharp masking of luma:

        blur_clip = core.std.Convolution(clip, matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1], planes=[0])
        diff_clip = core.std.MakeDiff(clip, blur_clip, planes=[0])
        sharpened_clip = core.std.MergeDiff(clip, diff_clip, planes=[0])

  MakeFullDiff

std.MakeFullDiff(vnode clipa, vnode clipb)
    Calculates the difference between clipa and clipb and outputs a clip with a one higher bitdepth to avoid the clamping or wraparound issues that would otherwise happen with filters like MakeDiff when forming a difference. This function is usually used together with MergeFullDiff, which can be used to add back the difference.

    Unsharp mask:

        blur_clip = core.std.Convolution(clip, matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1])
        diff_clip = core.std.MakeFullDiff(clip, blur_clip)
        sharpened_clip = core.std.MergeFullDiff(clip, diff_clip)

  MaskedMerge

std.MaskedMerge(vnode clipa, vnode clipb, vnode mask[, int[] planes, bint first_plane=0, bint premultiplied=0])
    MaskedMerge merges clipa with clipb using the per pixel weights in the mask, where 0 means that clipa is returned unchanged. The mask clip is assumed to be full range for all planes and in the 0-1 interval for float formats regardless of the colorspace. If mask is a grayscale clip or if first_plane is true, the mask's first plane will be used as the mask for merging all planes. The mask will be bilinearly resized if necessary.

    If premultiplied is set the blending is performed as if clipb has been pre-multiplied with alpha. In pre-multiplied mode it is an error to try to merge two frames with mismatched full and limited range since it will most likely cause horrible unintended color shifts. In the other mode it's just a very, very bad idea.

    By default all planes will be processed, but it is also possible to specify a list of the planes to merge in the output. The unprocessed planes will be copied from the first clip.

    clipa and clipb must have the same dimensions and format, and the mask must be the same format as the clips or the grayscale equivalent.

    How to apply a mask to the first plane:

        MaskedMerge(clipa=A, clipb=B, mask=Mask, planes=0)

    How to apply the first plane of a mask to the second and third plane:

        MaskedMerge(clipa=A, clipb=B, mask=Mask, planes=[1, 2], first_plane=True)

    The frame properties are copied from clipa.

  Median

std.Median(vnode clip[, int[] planes=[0, 1, 2]])
    Replaces each pixel with the median of the nine pixels in its 3x3 neighbourhood. In other words, the nine pixels are sorted from lowest to highest, and the middle value is picked.

clip
    Clip to process. It must have integer sample type and bit depth between 8 and 16, or float sample type and bit depth of 32. If there are any frames with other formats, an error will be returned.

planes
    Specifies which planes will be processed. Any unprocessed planes will be simply copied.

  Merge

std.Merge(vnode clipa, vnode clipb[, float[] weight = 0.5])
    Merges clipa and clipb using the specified weight for each plane. The default is to use a 0.5 weight for all planes. A zero weight means that clipa is returned unchanged and 1 means that clipb is returned unchanged. If a single weight is specified, it will be used for all planes. If two weights are given then the second value will be used for the third plane as well.

    Values outside the 0-1 range are considered to be an error. Specifying more weights than planes in the clips is also an error. The clips must have the same dimensions and format.

    How to merge luma:

        Merge(clipa=A, clipb=B, weight=[1, 0])

    How to merge chroma:

        Merge(clipa=A, clipb=B, weight=[0, 1])

    The average of two clips:

        Merge(clipa=A, clipb=B)

    The frame properties are copied from clipa.

  MergeDiff

std.MergeDiff(vnode clipa, vnode clipb[, int[] planes])
    Merges back the difference in clipb to clipa and clamps the result. By default all planes are processed. This function is usually used together with MakeDiff, which is normally used to calculate the difference.

    Unsharp masking of luma:

        blur_clip = core.std.Convolution(clip, matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1], planes=[0])
        diff_clip = core.std.MakeDiff(clip, blur_clip, planes=[0])
        sharpened_clip = core.std.MergeDiff(clip, diff_clip, planes=[0])

  MergeFullDiff

std.MergeFullDiff(vnode clipa, vnode clipb)
    Merges back the difference in clipb to clipa. Note that the bitdepth of clipb has to be one higher than that of clip. This function is usually used together with MakeFullDiff, which is normally used to calculate the difference.

    Unsharp mask:

        blur_clip = core.std.Convolution(clip, matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1])
        diff_clip = core.std.MakeFullDiff(clip, blur_clip)
        sharpened_clip = core.std.MergeFullDiff(clip, diff_clip)

  Minimum/Maximum

std.Minimum(vnode clip[, int[] planes=[0, 1, 2], float threshold, bint[] coordinates=[1, 1, 1, 1, 1, 1, 1, 1]])
    Replaces each pixel with the smallest value in its 3x3 neighbourhood. This operation is also known as erosion.

clip
    Clip to process. It must have integer sample type and bit depth between 8 and 16, or float sample type and bit depth of 32. If there are any frames with other formats, an error will be returned.

planes
    Specifies which planes will be processed. Any unprocessed planes will be simply copied.

threshold
    Allows to limit how much pixels are changed. Output pixels will not become less than input - threshold. The default is no limit.

coordinates
    Specifies which pixels from the 3x3 neighbourhood are considered. If an element of this array is 0, the corresponding pixel is not considered when finding the minimum value. This must contain exactly 8 numbers.

    Here is how each number corresponds to a pixel in the 3x3 neighbourhood:

        1 2 3
        4   5
        6 7 8

std.Maximum(vnode clip[, int[] planes=[0, 1, 2], float threshold, bint[] coordinates=[1, 1, 1, 1, 1, 1, 1, 1]])
    Replaces each pixel with the largest value in its 3x3 neighbourhood. This operation is also known as dilation.

clip
    Clip to process. It must have integer sample type and bit depth between 8 and 16, or float sample type and bit depth of 32. If there are any frames with other formats, an error will be returned.

planes
    Specifies which planes will be processed. Any unprocessed planes will be simply copied.

threshold
    Allows to limit how much pixels are changed. Output pixels will not become less than input - threshold. The default is no limit.

coordinates
    Specifies which pixels from the 3x3 neighbourhood are considered. If an element of this array is 0, the corresponding pixel is not considered when finding the maximum value. This must contain exactly 8 numbers.

    Here is how each number corresponds to a pixel in the 3x3 neighbourhood:

        1 2 3
        4   5
        6 7 8

  ModifyFrame

std.ModifyFrame(vnode clip, clip[] clips, func selector)
    The selector function is called for every single frame and can modify the properties of one of the frames gotten from clips. The additional clips' properties should only be read and not modified because only one modified frame can be returned.

    You must first copy the input frame to make it modifiable. Any frame may be returned as long as it has the same format as the clip. Failure to do so will produce an error. If for conditional reasons you do not need to modify the current frame's properties, you can simply pass it through. The selector function is passed n, the current frame number, and f, which is a frame or a list of frames if there is more than one clip specified.

    If you do not need to modify frame properties but only read them, you should probably be using FrameEval instead.

    How to set the property FrameNumber to the current frame number:

        def set_frame_number(n, f):
           fout = f.copy()
           fout.props['FrameNumber'] = n
           return fout
        ...
        ModifyFrame(clip=clip, clips=clip, selector=set_frame_number)

    How to remove a property:

        def remove_property(n, f):
           fout = f.copy()
           del fout.props['FrameNumber']
           return fout
        ...
        ModifyFrame(clip=clip, clips=clip, selector=remove_property)

    An example of how to copy certain properties from one clip to another (clip1 and clip2 have the same format):

        def transfer_property(n, f):
           fout = f[1].copy()
           fout.props['FrameNumber'] = f[0].props['FrameNumber']
           fout.props['_Combed'] = f[0].props['_Combed']
           return fout
        ...
        ModifyFrame(clip=clip1, clips=[clip1, clip2], selector=transfer_property)

  PEMVerifier

std.PEMVerifier(vnode clip[, float[] upper, float[] lower])
    The PEMVerifier is used to check for out-of-bounds pixel values during filter development. It is a public function so badly coded filters won't go unnoticed.

    If no values are set, then upper and lower default to the max and min values allowed in the current format. If an out of bounds value is encountered a frame error is set and the coordinates of the first bad pixel are included in the error message.

  PlaneStats

std.PlaneStats(vnode clipa[, vnode clipb, int plane=0, string prop='PlaneStats'])
    This function calculates the min, max and average normalized value of all the pixels in the specified plane and stores the values in the frame properties named propMin, propMax and propAverage.

    If clipb is supplied, the absolute normalized difference between the two clips will be stored in propDiff as well.

    The normalization means that the average and the diff will always be floats between 0 and 1, no matter what the input format is.

  PreMultiply

std.PreMultiply(vnode clip, vnode alpha)
    PreMultiply simply multiplies clip and alpha in order to make it more suitable for later operations. This will yield much better results when resizing and a clip with an alpha channel and MaskedMerge can use it as input. The alpha clip must be the grayscale format equivalent of clip.

    Note that limited range pre-multiplied contents excludes the offset. For example with 8 bit input 60 luma and 128 alpha would be calculated as ((60 - 16) * 128)/255 + 16 and not (60 * 128)/255.

  Prewitt/Sobel

std.Prewitt(vnode clip[, int[] planes=[0, 1, 2], float scale=1])
    Creates an edge mask using the Prewitt operator.

std.Sobel(vnode clip[, int[] planes=[0, 1, 2], float scale=1])
    Creates an edge mask using the Sobel operator.

clip
    Clip to process. It must have integer sample type and bit depth between 8 and 16, or float sample type and bit depth of 32. If there are any frames with other formats, an error will be returned.

planes
    Specifies which planes will be processed. Any unprocessed planes will be simply copied.

scale
    Multiply all pixels by scale before outputting. This can be used to increase or decrease the intensity of edges in the output.

  PropToClip

std.PropToClip(vnode clip[, string prop='_Alpha'])
    Extracts a clip from the frames attached to the frame property prop in clip. This function is mainly used to extract a mask/alpha clip that was stored in another one.

    It is the inverse of ClipToProp().

  RemoveFrameProps

std.RemoveFrameProps(vnode clip[, string props[]])
    Returns clip but with all the frame properties named in props removed. If props is unset them all frame properties are removed.

    Note that props accepts wildcards (* and ?) which can be very useful if you for example only want to clear properties set by a single filter since they're usually prefixed such as VFM* or _* can be used as a shorthand to conveniently clear only the internally reserved properties (colorimetry, time, field structure).

  Resize

resize.Bilinear(vnode clip[, int width, int height, int format, enum matrix, enum transfer, enum primaries, enum range, enum chromaloc, enum matrix_in, enum transfer_in, enum primaries_in, enum range_in, enum chromaloc_in, float filter_param_a, float filter_param_b, string resample_filter_uv, float filter_param_a_uv, float filter_param_b_uv, string dither_type="none", string cpu_type, float src_left, float src_top, float src_width, float src_height, float nominal_luminance, bint approximate_gamma=True])

resize.Bicubic(vnode clip[, ...])

resize.Point(vnode clip[, ...])

resize.Lanczos(vnode clip[, ...])

resize.Spline16(vnode clip[, ...])

resize.Spline36(vnode clip[, ...])

resize.Spline64(vnode clip[, ...])

resize.Bob(vnode clip, string filter="bicubic", bint tff[, ...])
    In VapourSynth the resizers have several functions. In addition to scaling, they also do colorspace conversions and conversions to and from the compat formats. Resize converts a clip of known or unknown format to another clip of known or unknown format, changing only the parameters specified by the user. The resize filters can handle varying size and format input clips and turn them into constant format clips.

    If you do not know which resizer to choose, then try Bicubic. It usually makes a good neutral default.

    Bob can be used as a rudimentary deinterlacer.

    Arguments denoted as type enum may be specified by numerical index (see ITU-T H.265 Annex E.3) or by name. Enums specified by name have their argument name suffixed with "_s". For example, a destination matrix of BT 709 can be specified either with matrix=1 or with matrix_s="709".

    Note that matrix is not an optional argument when converting to YUV. Also note that if no matrix is specified in an input YUV frame's properties then matrix_in also needs to be set.

    The function will return an error if the subsampling restrictions aren't followed.

    If you get an error like:

        Resize error 3074: no path between colorspaces (2/2/2 => 1/1/1).
        May need to specify additional colorspace parameters.

    It usually means the matrix/transfer/primaries are unknown and you have to specify the input colorspace parameters yourself. Note: 2 means "unspecified" according to the ITU-T recommendation.

    Resizing is performed per-field for interlaced images, as indicated by the _FieldBased frame property. Source filters may sometimes mark progressive video as interlaced, which can result in sub-optimal resampling quality unless _FieldBased is cleared.

    clip: Accepts all kinds of input.

    width, height: Output image dimensions.

    filter: Scaling method for deinterlacing. See resample_filter_uv for accepted values.

    tff: Field order for deinterlacing. Used when the _FieldBased property is not set.

    format: Output format id.

    matrix, transfer, primaries: Output colorspace specification. If not provided, the corresponding attributes from the input clip will be selected, except for YCoCg and RGB color families, where the corresponding matrix is set by default.

    range: Output pixel range. For integer formats, this allows selection of the legal code values. Even when set, out of range values (BTB/WTW) may be generated. If the input format is of a different color family, the default range is studio/limited for YUV and full-range for RGB.

    chromaloc: Output chroma location. For subsampled formats, specifies the chroma location. If the input format is 4:4:4 or RGB and the output is subsampled, the default location is left-aligned, as per MPEG. Possible chroma locations (ITU-T H.265 Figure E.1): left, center, top_left, top, bottom_left, bottom

    matrix_in, transfer_in, primaries_in, range_in, chromaloc_in: Input colorspace/format specification. If the corresponding frame property is set to a value other than unspecified, the frame property is used instead of this parameter. Default values are set for certain color families. See the equivalent output arguments for more information.

    filter_param_a, filter_param_b: Parameters for the scaler used for RGB and Y-channel. For the bicubic filter, filter_param_a/b represent the "b" and "c" parameters. For the lanczos filter, filter_param_a represents the number of taps.

    resample_filter_uv: Scaling method for UV channels. It defaults to the same as for the Y-channel. The following values can be used with resample_filter_uv: point, bilinear, bicubic, spline16, spline36, lanczos.

    filter_param_a_uv, filter_param_b_uv: Parameters for the scaler used for UV channels.

    dither_type: Dithering method. Dithering is used only for conversions resulting in an integer format. The following dithering methods are available: none, ordered, random, error_diffusion.

    cpu_type: Only used for testing.

    src_left, src_top, src_width, src_height: Used to select the source region of the input to use. Can also be used to shift the image. Defaults to the whole image.

    nominal_luminance: Determines the physical brightness of the value 1.0. The unit is in cd/m^2.

    approximate_gamma: Use LUT to evaluate transfer functions. Defaults to True.

    To convert to YV12:

        Bicubic(clip=clip, format=vs.YUV420P8, matrix_s="709")

    To resize and convert YUV with color information frame properties to planar RGB:

        Bicubic(clip=clip, width=1920, height=1080, format=vs.RGB24)

    To resize and convert YUV without color information frame properties to planar RGB:

        Bicubic(clip=clip, width=1920, height=1080, format=vs.RGB24, matrix_in_s="709")

    The following tables list values of selected colorspace enumerations and their abbreviated names. (Numerical value in parentheses.) For all possible values, see ITU-T H.265. Matrix coefficients (ITU-T H.265 Table E.5):

        rgb (0)        Identity
                       The identity matrix.
                       Typically used for GBR (often referred to as RGB);
                       however, may also be used for YZX (often referred to as
                       XYZ);
        709 (1)        KR = 0.2126; KB = 0.0722
                       ITU-R Rec. BT.709-5
        unspec (2)     Unspecified
                       Image characteristics are unknown or are determined by the
                       application.
        fcc (4)
        470bg (5)      KR = 0.299; KB = 0.114
                       ITU-R Rec. BT.470-6 System B, G (historical)
                       (functionally the same as the value 6 (170m))
        170m (6)       KR = 0.299; KB = 0.114
                       SMPTE 170M (2004)
                       (functionally the same as the value 5 (470bg))
        240m (7)       SMPTE 240M
        ycgco (8)      YCgCo
        2020ncl (9)    KR = 0.2627; KB = 0.0593
                       Rec. ITU-R BT.2020 non-constant luminance system
        2020cl (10)    KR = 0.2627; KB = 0.0593
                       Rec. ITU-R BT.2020 constant luminance system
        chromancl (12) Chromaticity derived non-constant luminance system
        chromacl (13)  Chromaticity derived constant luminance system
        ictcp (14)     ICtCp

    Transfer characteristics (ITU-T H.265 Table E.4):

        709 (1)        V = a * Lc0.45 - ( a - 1 ) for 1 >= Lc >= b
                       V = 4.500 * Lc for b > Lc >= 0
                       Rec. ITU-R BT.709-5
                       (functionally the same as the values 6 (601),
                       14 (2020_10) and 15 (2020_12))
        unspec (2)     Unspecified
                       Image characteristics are unknown or are determined by the
                       application.
        470m (4)       ITU-R Rec. BT.470-6 System M
        470bg (5)      ITU-R Rec. BT.470-6 System B, G (historical)
        601 (6)        V = a * Lc0.45 - ( a - 1 ) for 1 >= Lc >= b
                       V = 4.500 * Lc for b > Lc >= 0
                       Rec. ITU-R BT.601-6 525 or 625
                       (functionally the same as the values 1 (709),
                       14 (2020_10) and 15 (2020_12))
        240m (7)       SMPTE 240M
        linear (8)     V = Lc for all values of Lc
                       Linear transfer characteristics
        log100 (9)     Log 1:100 contrast
        log316 (10)    Log 1:316 contrast
        xvycc (11)     IEC 61966-2-4
        srgb (13)      IEC 61966-2-1
        2020_10 (14)   V = a * Lc0.45 - ( a - 1 ) for 1 >= Lc >= b
                       V = 4.500 * Lc for b > Lc >= 0
                       Rec. ITU-R BT.2020
                       (functionally the same as the values 1 (709),
                       6 (601) and 15 (2020_12))
        2020_12 (15)   V = a * Lc0.45 - ( a - 1 ) for 1 >= Lc >= b
                       V = 4.500 * Lc for b > Lc >= 0
                       Rec. ITU-R BT.2020
                       (functionally the same as the values 1 (709),
                       6 (601) and 14 (2020_10))
        st2084 (16)    SMPTE ST 2084
        std-b67 (18)   ARIB std-b67

    Color primaries (ITU-T H.265 Table E.3):

        709 (1)        primary x y
                       green 0.300 0.600
                       blue 0.150 0.060
                       red 0.640 0.330
                       white D65 0.3127 0.3290
                       Rec. ITU-R BT.709-5
        unspec (2)     Unspecified
                       Image characteristics are unknown or are determined by the
                       application.
        470m (4)       ITU-R Rec. BT.470-6 System M
        470bg (5)      ITU-R Rec. BT.470-6 System B, G (historical)
        170m (6)       primary x y
                       green 0.310 0.595
                       blue 0.155 0.070
                       red 0.630 0.340
                       white D65 0.3127 0.3290
                       SMPTE 170M (2004)
                       (functionally the same as the value 7 (240m))
        240m (7)       primary x y
                       green 0.310 0.595
                       blue 0.155 0.070
                       red 0.630 0.340
                       white D65 0.3127 0.3290
                       SMPTE 240M (1999)
                       (functionally the same as the value 6 (170m))
        film (8)
        2020 (9)       primary x y
                       green 0.170 0.797
                       blue 0.131 0.046
                       red 0.708 0.292
                       white D65 0.3127 0.3290
                       Rec. ITU-R BT.2020
        st428 (10)     Commonly known as xyz
        xyz (10)       Alias for st428
        st431-2 (11)   DCI-P3 with traditional white point
        st432-1 (12)   DCI-P3
        jedec-p22 (22) E.B.U. STANDARD FOR CHROMATICITY TOLERANCES FOR STUDIO MONITORS (3213-E)
                       Also known as JEDEC P22

    Pixel range (ITU-T H.265 Eq E-4 to E-15):

        limited (0) Studio (TV) legal range, 16-235 in 8 bits.
                    Y = Clip1Y( Round( ( 1 << ( BitDepthY - 8 ) ) *
                                              ( 219 * E'Y + 16 ) ) )
                    Cb = Clip1C( Round( ( 1 << ( BitDepthC - 8 ) ) *
                                               ( 224 * E'PB + 128 ) ) )
                    Cr = Clip1C( Round( ( 1 << ( BitDepthC - 8 ) ) *
                                               ( 224 * E'PR + 128 ) ) )
                    R = Clip1Y( ( 1 << ( BitDepthY - 8 ) ) *
                                       ( 219 * E'R + 16 ) )
                    G = Clip1Y( ( 1 << ( BitDepthY - 8 ) ) *
                                       ( 219 * E'G + 16 ) )
                    B = Clip1Y( ( 1 << ( BitDepthY - 8 ) ) *
                                       ( 219 * E'B + 16 ) )
        full (1)    Full (PC) dynamic range, 0-255 in 8 bits.
                    Y = Clip1Y( Round( ( ( 1 << BitDepthY ) - 1 ) * E'Y ) )
                    Cb = Clip1C( Round( ( ( 1 << BitDepthC ) - 1 ) * E'PB +
                                          ( 1 << ( BitDepthC - 1 ) ) ) )
                    Cr = Clip1C( Round( ( ( 1 << BitDepthC ) - 1 ) * E'PR +
                                          ( 1 << ( BitDepthC - 1 ) ) ) )
                    R = Clip1Y( ( ( 1 << BitDepthY ) - 1 ) * E'R )
                    G = Clip1Y( ( ( 1 << BitDepthY ) - 1 ) * E'G )
                    B = Clip1Y( ( ( 1 << BitDepthY ) - 1 ) * E'B )

  Reverse

std.Reverse(vnode clip)
    Returns a clip with the frame or sample order reversed. For example, a clip with 3 frames would have the frame order 2, 1, 0.

    In Python, std.Reverse can also be invoked by slicing a clip.

  SelectEvery

std.SelectEvery(vnode clip, int cycle, int[] offsets[, bint modify_duration=True])
    Returns a clip with only some of the frames in every cycle selected. The offsets given must be between 0 and cycle - 1.

    Below are some examples of useful operations.

    Return even numbered frames, starting with 0:

        SelectEvery(clip=clip, cycle=2, offsets=0)

    Return odd numbered frames, starting with 1:

        SelectEvery(clip=clip, cycle=2, offsets=1)

    Fixed pattern 1 in 5 decimation, first frame in every cycle removed:

        SelectEvery(clip=clip, cycle=5, offsets=[1, 2, 3, 4])

    Duplicate every fourth frame:

        SelectEvery(clip=clip, cycle=4, offsets=[0, 1, 2, 3, 3])

    In Python, std.SelectEvery can also be invoked by slicing a clip.

    If modify_duration is set the clip's frame rate is multiplied by the number of offsets and divided by cycle. The frame durations are adjusted in the same manner.

  SeparateFields

std.SeparateFields(vnode clip[, bint tff, bint modify_duration=True])
    Returns a clip with the fields separated and interleaved.

    The tff argument only has an effect when the field order isn't set for a frame. Setting tff to true means top field first and false means bottom field first.

    If modify_duration is set then the output clip's frame rate is double that of the input clip. The frame durations will also be halved.

    The _FieldBased frame property is deleted. The _Field frame property is added.

    If no field order is specified in _FieldBased or tff an error will be returned.

  SetFieldBased

std.SetFieldBased(vnode clip, int value)
    This is a convenience function. See SetFrameProps if you want to set other properties.

    SetFieldBased sets _FieldBased to value and deletes the _Field frame property. The possible values are: 0 = Frame Based

    1 = Bottom Field First

    2 = Top Field First

    For example, if you have source material that's progressive but has been encoded as interlaced you can set it to be treated as frame based (not interlaced) to improve resizing quality:

        clip = core.bs.VideoSource("rule6.mkv")
        clip = core.std.SetFieldBased(clip, 0)
        clip = clip.resize.Bilinear(clip, width=320, height=240)

  SetFrameProp

std.SetFrameProp(vnode clip, string prop[, int[] intval, float[] floatval, string[] data])
    Adds a frame property to every frame in clip.

    If there is already a property with the name prop in the frames, it will be overwritten.

    The type of the property added depends on which of the intval, floatval, or data parameters is used.

    For example, to set the field order to top field first:

        clip = c.std.SetFrameProp(clip, prop="_FieldBased", intval=2)

  SetFrameProps

std.SetFrameProps(vnode clip, ...)
    Adds the specified values as a frame property of every frame in clip. If a frame property with the same key already exists it will be replaced.

    For example, to set the field order to top field first:

        clip = c.std.SetFrameProps(clip, _FieldBased=2)

  SetVideoCache

std.SetVideoCache(vnode clip[, int mode, int fixedsize, int maxsize, int historysize])
    Every filter node has a cache associated with it that may or may not be enabled depending on the dependencies and request patterns. This function allows all automatic behavior to be overridden.

    The mode option has 3 possible options where 0 always disables caching, 1 always enables the cache and -1 uses the automatically calculated settings. Note that setting mode to -1 will reset the other values to their defaults as well.

    The other options are fairly self-explanatory where setting fixedsize prevents the cache from over time altering its maxsize based on request history. The final historysize argument controls how many previous and no longer cached requests should be considered when adjusting maxsize, generally this value should not be touched at all.

    Note that setting mode will reset all other options to their defaults.

  ShufflePlanes

std.ShufflePlanes(vnode[] clips, int[] planes, int colorfamily[ vnode prop_src=clips[0]])
    ShufflePlanes can extract and combine planes from different clips in the most general way possible. This is both good and bad, as there are almost no error checks.

    Most of the returned clip's properties are implicitly determined from the first clip given to clips but can also be changed by using prop_src.

    The clips parameter takes between one and three clips for color families with three planes. In this case clips=[A] is equivalent to clips=[A, A, A] and clips=[A, B] is equivalent to clips=[A, B, B]. For the GRAY color family, which has one plane, it takes exactly one clip.

    The argument planes controls which of the input clips' planes to use. Zero indexed. The first number refers to the first input clip, the second number to the second clip, the third number to the third clip.

    The only thing that needs to be specified is colorfamily, which controls which color family (YUV, RGB, GRAY) the output clip will be. Properties such as subsampling are determined from the relative size of the given planes to combine.

    ShufflePlanes accepts clips with variable format and dimensions only when extracting a single plane.

    Below are some examples of useful operations.

    Extract plane with index X. X=0 will mean luma in a YUV clip and R in an RGB clip. Likewise 1 will return the U and G channels, respectively:

        ShufflePlanes(clips=clip, planes=X, colorfamily=vs.GRAY)

    Swap U and V in a YUV clip:

        ShufflePlanes(clips=clip, planes=[0, 2, 1], colorfamily=vs.YUV)

    Merge 3 grayscale clips into a YUV clip:

        ShufflePlanes(clips=[Yclip, Uclip, Vclip], planes=[0, 0, 0], colorfamily=vs.YUV)

    Cast a YUV clip to RGB:

        ShufflePlanes(clips=[YUVclip], planes=[0, 1, 2], colorfamily=vs.RGB)

  Splice

std.Splice(vnode[] clips[, bint mismatch=0])
    Returns a clip with all clips appended in the given order.

    Splicing clips with different formats or dimensions is considered an error unless mismatch is true.

    In Python, std.Splice can also be invoked using the addition operator.

  SplitPlanes

std.SplitPlanes(vnode clip)
    SplitPlanes returns each plane of the input as separate clips.

  StackVertical/StackHorizontal

std.StackVertical(vnode[] clips)

std.StackHorizontal(vnode[] clips)
    Stacks all given clips together. The same format is a requirement. For StackVertical all clips also need to be the same width and for StackHorizontal all clips need to be the same height.

    The frame properties are copied from the first clip.

  Transpose

std.Transpose(vnode clip)
    Flips the contents of the frames in the same way as a matrix transpose would do. Combine it with FlipVertical or FlipHorizontal to synthesize a left or right rotation. Calling Transpose twice in a row is the same as doing nothing (but slower).

    Here is a picture to illustrate what Transpose does:

                                  0   5  55
         0   1   1   2   3        1   8  89
         5   8  13  21  34   =>   1  13 144
        55  89 144 233 377        2  21 233
                                  3  34 377

  Trim

std.Trim(vnode clip[, int first=0, int last, int length])
    Trim returns a clip with only the frames between the arguments first and last, or a clip of length frames, starting at first. Trim is inclusive so Trim(clip, first=3, last=3) will return one frame. If neither last nor length is specified, no frames are removed from the end of the clip.

    Specifying both last and length is considered to be an error. Likewise is calling Trim in a way that returns no frames, as 0 frame clips are not allowed in VapourSynth.

    In Python, std.Trim can also be invoked by slicing a clip.

  Turn180

std.Turn180(vnode clip)
    Turns the frames in a clip 180 degrees (to the left, not to the right).

  Text

  ClipInfo

text.ClipInfo(vnode clip[, int alignment=7, int scale=1]])
    Prints information about the clip, such as the format and framerate.

    This is a convenience function for Text.

  CoreInfo

text.CoreInfo([vnode clip=std.BlankClip(), int alignment=7, int scale=1])
    Prints information about the VapourSynth core, such as version and memory use. If no clip is supplied, a default blank one is used.

    This is a convenience function for Text.

  FrameNum

text.FrameNum(vnode clip[, int alignment=7, int scale=1])
    Prints the current frame number.

    This is a convenience function for Text.

  FrameProps

text.FrameProps(vnode clip[, string props=[], int alignment=7, int scale=1])
    Prints all properties attached to the frames, or if the props array is given only those properties.

    This is a convenience function for Text.

  Text

text.Text(vnode clip, string text[, int alignment=7, int scale=1])
    Text is a simple text printing filter. It doesn't use any external libraries for drawing the text. It uses a built-in bitmap font: the not-bold, 8×16 version of Terminus. The font was not modified, only converted from PCF to an array of bytes.

    The font covers Windows-1252, which is a superset of ISO-8859-1 (aka latin1). Unprintable characters get turned into underscores. Long lines get wrapped in a dumb way. Lines that end up too low to fit in the frame are silently dropped.

    The alignment parameter takes a number from 1 to 9, corresponding to the positions of the keys on a numpad.

    The scale parameter sets an integer scaling factor for the bitmap font.

    ClipInfo, CoreInfo, FrameNum, and FrameProps are convenience functions based on Text.

  Audio Functions

  AssumeSampleRate

std.AssumeSampleRate(anode clip[, anode src, int samplerate])

  AudioGain

std.AudioGain(anode clip, float[] gain, bint overflow_error = False)
    AudioGain can either change the volume of individual channels if a separate gain for each channel is given or if only a single gain value is supplied it's applied to all channels.

    Negative gain values are allowed. Applying a too large gain will lead to clipping in integer formats.

    Will stop processing with an error if clipping is detected if overflow_error is set. If it's false a warning will be printed for the first audio block with clipping.

  AudioLoop

std.AudioLoop(anode clip[, int times=0])
    Returns a clip with the frames or samples repeated over and over again. If times is less than 1 the clip will be repeated until the maximum clip length is reached, otherwise it will be repeated times times.

    In Python, std.AudioLoop can also be invoked using the multiplication operator.

  AudioMix

std.AudioMix(anode[] clips, float[] matrix, int[] channels_out, bint overflow_error = False)
    AudioMix can mix and combine channels from different clips in the most general way possible.

    Most of the returned clip's properties are implicitly determined from the first clip given to clips.

    The clips parameter takes one or more clips with the same format. If the clips are different lengths they'll be zero extended to that of the longest.

    The argument matrix applies the coefficients to each channel of each input clip where the channels are in the numerical order of their channel constants. For example a stereo clip will have its channels presented in the order FRONT_LEFT and then FRONT_RIGHT.

    Output channels and order is determined by the channels_out array between input index and output channel happens on the order of lowest output channel identifier to the highest.

    Will stop processing with an error if clipping is detected if overflow_error is set. If it's false a warning will be printed for the first audio block with clipping.

    Below are some examples of useful operations.

    Downmix stereo audio to mono:

        AudioMix(clips=clip, matrix=[0.5, 0.5], channels_out=[vs.FRONT_CENTER])

    Downmix 5.1 audio:

        AudioMix(clips=clip, matrix=[1, 0, 0.7071, 0, 0.7071, 0, 0, 1, 0.7071, 0, 0, 0.7071], channels_out=[vs.FRONT_LEFT, vs.FRONT_RIGHT])

    Copy stereo audio to 5.1 and zero the other channels:

        AudioMix(clips=c, matrix=[1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], channels_out=[vs.FRONT_LEFT, vs.FRONT_RIGHT, vs.FRONT_CENTER, vs.LOW_FREQUENCY, vs.BACK_LEFT, vs.BACK_RIGHT])

  AudioReverse

std.AudioReverse(anode clip)
    Returns a clip with the frame or sample order reversed. For example, a clip with 3 frames would have the frame order 2, 1, 0.

    In Python, std.AudioReverse can also be invoked by slicing a clip.

  AudioSplice

std.AudioSplice(anode[] clips)
    Returns a clip with all clips appended in the given order.

    Splicing clips with different formats or dimensions is considered an error unless mismatch is true.

    In Python, std.AudioSplice can also be invoked using the addition operator.

  AudioTrim

std.AudioTrim(anode clip[, int first=0, int last, int length])
    AudioTrim performs exactly the same operation on audio clips but the unit is obviously samples instead of frames.

    In Python, std.AudioTrim can also be invoked by slicing a clip.

  BlankAudio

std.BlankAudio([anode clip, int[] channels=[FRONT_LEFT, FRONT_RIGHT], int bits=16, int sampletype=INTEGER, int samplerate=44100, int length=(10*samplerate), bint keep=0])
    Generates a new empty clip. This can be useful to have when editing audio or for testing. The default is a 10 second long 44.1kHz 16 bit stereo clip. Instead of specifying every property individually, BlankAudio can also copy the properties from clip. If both an argument such as sampletype, and clip are set, then sampletype will take precedence.

    The channels argument is a list of channel constants. Specifying the same channel twice is not allowed.

    The possible sampletype values are currently INTEGER (0) and FLOAT (1).

    If keep is set, a reference to the same frame is returned on every request. Otherwise a new frame is generated every time. There should usually be no reason to change this setting.

  SetAudioCache

std.SetAudioCache(anode clip[, int mode, int fixedsize, int maxsize, int historysize])
    see SetVideoCache

  ShuffleChannels

std.ShuffleChannels(anode[] clips, int[] channels_in, int[] channels_out)
    ShuffleChannels can extract and combine channels from different clips in the most general way possible.

    Most of the returned clip's properties are implicitly determined from the first clip given to clips.

    The clips parameter takes one or more clips with the same format. If the clips are different lengths they'll be zero extended to that of the longest.

    The argument channels_in controls which of the input clips' channels to use and takes a channel constants as its argument. Specifying a non-existent channel is an error. If more channels_in than clips values are specified then the last clip in the clips list is reused as a source. In addition to the channel constant it's also possible to specify the nth channel by using negative numbers.

    The output channel mapping is determined by channels_out and corresponds to the input channel order. The number of channels_out entries must be the same as the number of channels_in entries. Specifying the same output channel twice is an error.

    Below are some examples of useful operations.

    Extract the left channel (assuming it exists):

        ShuffleChannels(clips=clip, channels_in=vs.FRONT_LEFT, channels_out=vs.FRONT_LEFT)

    Swap left and right audio channels in a stereo clip:

        ShuffleChannels(clips=clip, channels_in=[vs.FRONT_RIGHT, vs.FRONT_LEFT], channels_out=[vs.FRONT_LEFT, vs.FRONT_RIGHT])

    Swap left and right audio channels in a stereo clip (alternate ordering of arguments):

        ShuffleChannels(clips=clip, channels_in=[vs.FRONT_LEFT, vs.FRONT_RIGHT], channels_out=[vs.FRONT_RIGHT, vs.FRONT_LEFT])

    Swap left and right audio channels in a stereo clip (alternate indexing):

        ShuffleChannels(clips=clip, channels_in=[-2, -1], channels_out=[vs.FRONT_LEFT, vs.FRONT_RIGHT])

    Merge 2 mono audio clips into a single stereo clip:

        ShuffleChannels(clips=[clipa, clipb], channels_in=[vs.FRONT_LEFT, vs.FRONT_LEFT], channels_out=[vs.FRONT_LEFT, vs.FRONT_RIGHT])

  SplitChannels

std.SplitChannels(anode clip)
    SplitChannels returns each audio channel of the input as a separate clip.

OUTPUT

  VSPipe

  Synopsis

vspipe <script> <outfile> [options]

vspipe's main purpose is to evaluate VapourSynth scripts and output the frames to a file.

If outfile is a hyphen (-), vspipe will write to the standard output.

If outfile is a dot (.), vspipe will do everything as usual, except it will not write the video frames anywhere.

  Options

-a, --arg key=value
    Argument to pass to the script environment, it a key with this name and value (str typed) will be set in the globals dict

-s, --start N
    Set output frame range (first frame)

-e, --end N
    Set output frame range (last frame)

-o, --outputindex N
    Select output index

-r, --requests N
    Set number of concurrent frame requests

-c, --container <y4m/wav/w64>
    Add headers for the specified format to the output

-t, --timecodes FILE
    Write timecodes v2 file

-p, --progress
    Print progress to stderr

--filter-time
    Records the time spent in each filter and prints it out at the end of processing.

-i, --info
    Show video info and exit

-g, --graph <simple/full>
    Print output node filter graph in dot format to outfile and exit

-v, --version
    Show version info and exit

  Examples

Show script info:
    vspipe --info script.vpy -

Write to stdout:
    vspipe [options] script.vpy -

Request all frames but don't output them:
    vspipe [options] script.vpy .

Write frames 5-100 to file:
    vspipe --start 5 --end 100 script.vpy output.raw

Pipe to x264 and write timecodes file:
    vspipe script.vpy - --y4m --timecodes timecodes.txt | x264 --demuxer y4m -o script.mkv -

Pass values to a script:
    vspipe --arg deinterlace=yes --arg "message=fluffy kittens" script.vpy output.raw

  AVFS

AV FileSystem is based on AVFS and shares most of its source code and functionality. This package has several uses. It can easily make a script file openable by any application, as it appears like a real, uncompressed avi file. It can also be used to bridge the 32/64 bit gap, since a plain file can always be read.

To use it simply run avfs in the core32 or core64 directories with the script name as argument. This will create a virtual file in C:\\Volumes.

The alt_output argument of set_output is respected and can be used to get additional compatibility with professional applications.

  Avisynth Support

Note that this AVFS version is also compatible with Avisynth 2.6 and Avisynth+. When using Avisynth+ higher bitdepth output is also supported. The easiest way to obtain a recent version is to extract avfs.exe from the portable VapourSynth archives.

  VFW

On windows, you can output video to VFW based programs.

If you install VapourSynth by installer, the VSVFW.dll is registered already

Else, you could register it manually, use register file below or use theChaosCoder's batch.

    Windows Registry Editor Version 5.00
    [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{58F74CA0-BD0E-4664-A49B-8D10E6F0C131}]
    @="VapourSynth"
    [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{58F74CA0-BD0E-4664-A49B-8D10E6F0C131}\InProcServer32]
    @="<your VSVFW.dll directory>\\VSVFW.dll"
    "ThreadingModel"="Apartment"
    [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\AVIFile\Extensions\VPY]
    @="{58F74CA0-BD0E-4664-A49B-8D10E6F0C131}"

APPLICATIONS AND LIBRARIES

  Applications

•   D2V Witch -- creates indexes that can be opened by d2vsource

•   Hybrid (Doom9) -- encoding GUI with VapourSynth support

•   mpv.net -- a media player with VapourSynth built-in

•   SmoothVideo Project -- a plugin/video player component for realtime frame interpolation

•   StaxRip -- encoding GUI with extended VapourSynth scripting support

•   VapourSynth Editor (Doom9) -- an editor with syntax completion and fast preview support

•   VapourSynth Editor 2 (Doom9) -- a spiritual successor to VapourSynth Editor

•   VirtualDub2 (Doom9) -- VirtualDub with added support for high bitdepth colorspaces, useful for previewing

•   vsmkv -- a FUSE-based virtual filesystem for exporting VapourSynth scripts as uncompressed videos in the Matroska (MKV) file format

•   vspreview -- an advanced standalone previewer written in python with too many features to list

•   vspreview-rs (Doom9) -- minimal VapourSynth script previewer

•   Wobbly (Doom9) -- IVTC assistant similar to YATTA

•   Yuuno -- incorporates VapourSynth into Jupyter

  Libraries

•   VapourSynth.nim -- Bindings for the Nim programming language

•   vapoursynth-rs -- VapourSynth Rust wrapper

•   vsxx -- VapourSynth C++ API wrapper

  Tools

•   GitHub Action install-vapoursynth -- Installs vapoursynth in your GitHub Action.

VAPOURSYNTH C API REFERENCE

See the example filters in the sdk dir. Reading simplefilters.c, which contains several built-in functions, can also be very helpful.

  Public Headers

  VapourSynth4.h

  Table of contents

Introduction

Macros
    VS_CC

    VS_EXTERNAL_API

    VAPOURSYNTH_API_MAJOR

    VAPOURSYNTH_API_MINOR

    VAPOURSYNTH_API_VERSION

    VS_AUDIO_FRAME_SAMPLES

    VS_MAKE_VERSION

Enums
    VSColorFamily

    VSSampleType

    VSPresetVideoFormat

    VSFilterMode

    VSMediaType

    VSAudioChannels

    VSPropertyType

    VSMapPropertyError

    VSMapAppendMode

    VSActivationReason

    VSMessageType

    VSCoreCreationFlags

    VSPluginConfigFlags

    VSDataTypeHint

    VSRequestPattern

    VSCacheMode

Structs
    VSFrame

    VSNode

    VSCore

    VSPlugin

    VSPluginFunction

    VSFunction

    VSMap

    VSLogHandle

    VSFrameContext

    VSVideoFormat

    VSVideoInfo

    VSAudioFormat

    VSAudioInfo

    VSCoreInfo

    VSFilterDependency

    VSPLUGINAPI

    VSAPI

•   Functions that deal with the core:

•   createCore

•   freeCore

•   setMaxCacheSize

•   setThreadCount

•   getCoreInfo

•   getAPIVersion

•   Functions that deal with logging

•   addLogHandler

•   removeLogHandler

•   logMessage

•   Functions that deal with frames:

•   newVideoFrame

•   newVideoFrame2

•   newAudioFrame

•   newAudioFrame2

•   freeFrame

•   addFrameRef

•   copyFrame

•   getFramePropertiesRO

•   getFramePropertiesRW

•   getStride

•   getReadPtr

•   getWritePtr

•   getVideoFrameFormat

•   getAudioFrameFormat

•   getFrameType

•   getFrameWidth

•   getFrameHeight

•   getFrameLength

•   Functions that deal with filters and nodes:

•   createVideoFilter

•   createVideoFilter2

•   createAudioFilter

•   createAudioFilter2

•   setLinearFilter

•   setCacheMode

•   setCacheOptions

•   freeNode

•   addNodeRef

•   getNodeType

•   getVideoInfo

•   getAudioInfo

•   Functions that deal with formats:

•   getVideoFormatName

•   getAudioFormatName

•   queryVideoFormat

•   queryAudioFormat

•   queryVideoFormatID

•   getVideoFormatByID

•   Functions that deal with maps:

•   createMap

•   freeMap

•   clearMap

•   mapGetError

•   mapSetError

•   mapNumKeys

•   mapGetKey

•   mapDeleteKey

•   mapNumElements

•   mapGetType

•   mapSetEmpty

•   mapGetInt

•   mapGetIntSaturated

•   mapGetIntArray

•   mapSetInt

•   mapSetIntArray

•   mapGetFloat

•   mapGetFloatSaturated

•   mapGetFloatArray

•   mapSetFloat

•   mapSetFloatArray

•   mapGetData

•   mapGetDataSize

•   mapGetDataTypeHint

•   mapSetData

•   mapGetNode

•   mapSetNode

•   mapConsumeNode

•   mapGetFrame

•   mapSetFrame

•   mapConsumeFrame

•   mapGetFunction

•   mapSetFunction

•   mapConsumeFunction

•   Functions that deal with plugins and plugin functions:

•   registerFunction

•   getPluginByID

•   getPluginByNamespace

•   getNextPlugin

•   getPluginName

•   getPluginID

•   getPluginNamespace

•   getNextPluginFunction

•   getPluginFunctionByName

•   getPluginFunctionName

•   getPluginFunctionArguments

•   getPluginFunctionReturnType

•   getPluginPath

•   getPluginVersion

•   invoke

•   Functions that deal with wrapped external functions:

•   createFunction

•   freeFunction

•   addFunctionRef

•   callFunction

•   Functions that are used to fetch frames and inside filters:

•   getFrame

•   getFrameAsync

•   getFrameFilter

•   requestFrameFilter

•   releaseFrameEarly

•   cacheFrame

•   setFilterError

Functions
    getVapourSynthAPI

Writing plugins
    VSInitPlugin

    VSFilterGetFrame

    VSFilterFree

  Introduction

This is VapourSynth's main header file. Plugins and applications that use the library must include it.

VapourSynth's public API is all C.

  Macros

VapourSynth4.h defines some preprocessor macros that make the programmer's life easier. The relevant ones are described below.

  VS_CC

The VS_CC macro expands to the calling convention used by VapourSynth. All functions meant to be called by VapourSynth must use this macro (a filter's "init", "getframe", "free" functions, etc).

Example:

    static void VS_CC fooInit(...) { ... }

  VS_EXTERNAL_API

The VS_EXTERNAL_API macro expands to the platform-specific magic required for functions exported by shared libraries. It also takes care of adding extern "C" when needed, and VS_CC.

This macro must be used for a plugin's entry point, like so:

    VS_EXTERNAL_API(void) VapourSynthPluginInit2(...) { ... }

  VAPOURSYNTH_API_MAJOR

Major API version.

  VAPOURSYNTH_API_MINOR

Minor API version. It is bumped when new functions are added to VSAPI or core behavior is noticeably changed.

  VAPOURSYNTH_API_VERSION

API version. The high 16 bits are VAPOURSYNTH_API_MAJOR, the low 16 bits are VAPOURSYNTH_API_MINOR.

  VS_AUDIO_FRAME_SAMPLES

The number of audio samples in an audio frame. It is a static number to make it possible to calculate which audio frames are needed to retrieve specific samples.

  VS_MAKE_VERSION

Used to create version numbers. The first argument is the major version and second is the minor.

  Enums

  enum VSColorFamily

•   cfUndefined

•   cfGray

•   cfRGB

•   cfYUV

  enum VSSampleType

•   stInteger

•   stFloat

  enum VSPresetVideoFormat
The presets suffixed with H and S have floating point sample type. The H and S suffixes stand for half precision and single precision, respectively. All formats are planar. See the header for all currently defined video format presets.

•   pf*

  enum VSFilterMode
Controls how a filter will be multithreaded, if at all.

•   fmParallel

    Completely parallel execution. Multiple threads will call a filter's "getframe" function, to fetch several frames in parallel.

•   fmParallelRequests

    For filters that are serial in nature but can request in advance one or more frames they need. A filter's "getframe" function will be called from multiple threads at a time with activation reason arInitial, but only one thread will call it with activation reason arAllFramesReady at a time.

•   fmUnordered

    Only one thread can call the filter's "getframe" function at a time. Useful for filters that modify or examine their internal state to determine which frames to request.

    While the "getframe" function will only run in one thread at a time, the calls can happen in any order. For example, it can be called with reason arInitial for frame 0, then again with reason arInitial for frame 1, then with reason arAllFramesReady for frame 0.

•   fmFrameState

    For compatibility with other filtering architectures. DO NOT USE IN NEW FILTERS. The filter's "getframe" function only ever gets called from one thread at a time. Unlike fmUnordered, only one frame is processed at a time.

  enum VSMediaType
Used to indicate the type of a VSFrame or VSNode object.

•   mtVideo

•   mtAudio

  enum VSAudioChannels
Audio channel positions as an enum. Mirrors the FFmpeg audio channel constants in older api versions. See the header for all available values.

•   ac*

  enum VSPropertyType
Types of properties that can be stored in a VSMap.

•   ptUnset

•   ptInt

•   ptFloat

•   ptData

•   ptFunction

•   ptVideoNode

•   ptAudioNode

•   ptVideoFrame

•   ptAudioFrame

  enum VSMapPropertyError
When a mapGet* function fails, it returns one of these in the err parameter.

All errors are non-zero.

•   peSuccess

•   peUnset

    The requested key was not found in the map.

•   peType

    The wrong function was used to retrieve the property. E.g. mapGetInt() was used on a property of type ptFloat.

•   peIndex

    The requested index was out of bounds.

•   peError

    The map has the error state set.

  enum VSMapAppendMode
Controls the behaviour of mapSetInt() and friends.

•   maReplace

    All existing values associated with the key will be replaced with the new value.

•   maAppend

    The new value will be appended to the list of existing values associated with the key.

  enum VSActivationReason
See VSFilterGetFrame.

•   arInitial

•   arAllFramesReady

•   arError

  enum VSMessageType
See addLogHandler().

•   mtDebug

•   mtInformation

•   mtWarning

•   mtCritical

•   mtFatal

  enum VSCoreCreationFlags
Options when creating a core.

•   ccfEnableGraphInspection Required to use the graph inspection api functions. Increases memory usage due to the extra information stored.

•   ccfDisableAutoLoading Don't autoload any user plugins. Core plugins are always loaded.

•   ccfDisableLibraryUnloading Don't unload plugin libraries when the core is destroyed. Due to a small amount of memory leaking every load and unload (windows feature, not my fault) of a library this may help in applications with extreme amount of script reloading.

  enum VSPluginConfigFlags
Options when loading a plugin.

•   pcModifiable Allow functions to be added to the plugin object after the plugin loading phase. Mostly useful for Avisynth compatibility and other foreign plugin loaders.

  enum VSDataTypeHint
Since the data type can contain both pure binary data and printable strings the type also contains a hint for whether or not it is human readable. Generally the unknown type should be very rare and is almost only created as an artifact of API3 compatibility.

•   dtUnknown

•   dtBinary

•   dtUtf8

  enum VSRequestPattern
Describes the upstream frame request pattern of a filter.

•   rpGeneral Anything goes. Note that filters that may be requesting beyond the end of a VSNode length in frames (repeating the last frame) should use rpGeneral and not any of the other modes.

•   rpNoFrameReuse

    Will only request an input frame at most once if all output frames are requested exactly one time. This includes filters such as Trim, Reverse, SelectEvery.

•   rpStrictSpatial

    Only requests frame N to output frame N. The main difference to rpNoFrameReuse is that the requested frame is always fixed and known ahead of time. Filter examples Lut, Expr (conditionally, see rpGeneral note) and similar.

•   rpFrameReuseLastOnly

    Similar to rpNoFrameReuse but the last frame is cached in case it's requested multiple times.

  enum VSCacheMode
Describes how the output of a node is cached.

•   cmAuto Cache is enabled or disabled based on the reported request patterns and number of consumers.

•   cmForceDisable Never cache anything.

•   cmForceEnable

•   Always use the cache.

  Structs

Most structs are opaque and their contents can only be accessed using functions in the API.

  struct VSFrame
A frame that can hold audio or video data.

Each row of pixels in a frame is guaranteed to have an alignment of at least 32 bytes. Two frames with the same width and bytes per sample are guaranteed to have the same stride.

Audio data is also guaranteed to be at least 32 byte aligned.

Any data can be attached to a frame, using a VSMap.

  struct VSNode
A reference to a node in the constructed filter graph. Its primary use is as an argument to other filter or to request frames from.

  struct VSCore
The core represents one instance of VapourSynth. Every core individually loads plugins and keeps track of memory.

  struct VSPlugin
A VapourSynth plugin. There are a few of these built into the core, and therefore available at all times: the basic filters (identifier com.vapoursynth.std, namespace std), the resizers (identifier com.vapoursynth.resize, namespace resize), and the Avisynth compatibility module, if running in Windows (identifier com.vapoursynth.avisynth, namespace avs).

The Function Reference describes how to load VapourSynth and Avisynth plugins.

A VSPlugin instance is constructed by the core when loading a plugin (.so / .dylib / .dll), and the pointer is passed to the plugin's VapourSynthPluginInit2() function.

A VapourSynth plugin can export any number of filters.

Plugins have a few attributes:

•   An identifier, which must be unique among all VapourSynth plugins in existence, because this is what the core uses to make sure a plugin only gets loaded once.

•   A namespace, also unique. The filters exported by a plugin end up in the plugin's namespace.

•   A full name, which is used by the core in a few error messages.

•   The version of the plugin.

•   The VapourSynth API version the plugin requires.

•   A file name.

    Things you can do with a VSPlugin:

•   Enumerate all the filters it exports, using getNextPluginFunction().

•   Invoke one of its filters, using invoke().

•   Get its location in the file system, using getPluginPath().

    All loaded plugins (including built-in) can be enumerated with getNextPlugin().

    Once loaded, a plugin only gets unloaded when the VapourSynth core is freed.

  struct VSPluginFunction
A function belonging to a Vapoursynth plugin. This object primarily exists so a plugin's name, argument list and return type can be queried by editors.

One peculiarity is that plugin functions cannot be invoked using a VSPluginFunction pointer but is instead done using invoke() which takes a VSPlugin and the function name as a string.

  struct VSFunction
Holds a reference to a function that may be called. This type primarily exists so functions can be shared between the scripting layer and plugins in the core.

  struct VSMap
VSMap is a container that stores (key,value) pairs. The keys are strings and the values can be (arrays of) integers, floating point numbers, arrays of bytes, VSNode, VSFrame, or VSFunction.

The pairs in a VSMap are sorted by key.

In VapourSynth, VSMaps have several uses:

•   storing filters' arguments and return values

•   storing user-defined functions' arguments and return values

•   storing the properties attached to frames

    Only alphanumeric characters and the underscore may be used in keys.

    Creating and destroying a map can be done with createMap() and freeMap(), respectively.

    A map's contents can be retrieved and modified using a number of functions, all prefixed with "map".

    A map's contents can be erased with clearMap().

  struct VSLogHandle
Opaque type representing a registered logger.

  struct VSFrameContext
Opaque type representing the current frame request in a filter.

  struct VSVideoFormat
Describes the format of a clip.

Use queryVideoFormat() to fill it in with proper error checking. Manually filling out the struct is allowed but discouraged since illegal combinations of values will cause undefined behavior.

int colorFamily
    See VSColorFamily.

int sampleType
    See VSSampleType.

int bitsPerSample
    Number of significant bits.

int bytesPerSample
    Number of bytes needed for a sample. This is always a power of 2 and the smallest possible that can fit the number of bits used per sample.

int subSamplingW

int subSamplingH
    log2 subsampling factor, applied to second and third plane. Convenient numbers that can be used like so:

        uv_width = y_width >> subSamplingW;

int numPlanes
    Number of planes.

  struct VSVideoInfo
Contains information about a clip.

VSVideoFormat format
    Format of the clip. Will have colorFamily set to cfUndefined if the format can vary.

int64_t fpsNum
    Numerator part of the clip's frame rate. It will be 0 if the frame rate can vary. Should always be a reduced fraction.

int64_t fpsDen
    Denominator part of the clip's frame rate. It will be 0 if the frame rate can vary. Should always be a reduced fraction.

int width
    Width of the clip. Both width and height will be 0 if the clip's dimensions can vary.

int height
    Height of the clip. Both width and height will be 0 if the clip's dimensions can vary.

int numFrames
    Length of the clip.

  struct VSAudioFormat
Describes the format of a clip.

Use queryAudioFormat() to fill it in with proper error checking. Manually filling out the struct is allowed but discouraged since illegal combinations of values will cause undefined behavior.

int sampleType
    See VSSampleType.

int bitsPerSample
    Number of significant bits.

int bytesPerSample
    Number of bytes needed for a sample. This is always a power of 2 and the smallest possible that can fit the number of bits used per sample.

int numChannels
    Number of audio channels.

uint64_t channelLayout
    A bitmask representing the channels present using the constants in 1 left shifted by the constants in VSAudioChannels.

  struct VSAudioInfo
Contains information about a clip.

VSAudioFormat format
    Format of the clip. Unlike video the audio format can never change.

int sampleRate
    Sample rate.

int64_t numSamples
    Length of the clip in audio samples.

int numFrames
    Length of the clip in audio frames.

  struct VSCoreInfo
Contains information about a VSCore instance.

const char *versionString
    Printable string containing the name of the library, copyright notice, core and API versions.

int core
    Version of the core.

int api
    Version of the API.

int numThreads
    Number of worker threads.

int64_t maxFramebufferSize
    The framebuffer cache will be allowed to grow up to this size (bytes) before memory is aggressively reclaimed.

int64_t usedFramebufferSize
    Current size of the framebuffer cache, in bytes.

  struct VSFilterDependency
Contains information about a VSCore instance.

VSNode *source
    The node frames are requested from.

int requestPattern
    A value from VSRequestPattern.

  struct VSPLUGINAPI
This struct is used to access VapourSynth's API when a plugin is initially loaded.

----

int getAPIVersion() See getAPIVersion() in the struct VSAPI.

----

int configPlugin(const char *identifier, const char *pluginNamespace, const char *name, int pluginVersion, int apiVersion, int flags, VSPlugin *plugin) Used to provide information about a plugin when loaded. Must be called exactly once from the VapourSynthPluginInit2 entry point. It is recommended to use the VS_MAKE_VERSION macro when providing the pluginVersion. If you don't know the specific apiVersion you actually require simply pass VAPOURSYNTH_API_VERSION to match the header version you're compiling against. The flags consist of values from VSPluginConfigFlags ORed together but should for most plugins typically be 0.

Returns non-zero on success.

----

int registerFunction(const char *name, const char *args, const char *returnType, VSPublicFunction argsFunc, void *functionData, VSPlugin *plugin) See registerFunction() in the struct VSAPI.

  struct VSAPI
This giant struct is the way to access VapourSynth's public API.

----

VSCore *createCore(int flags) Creates the VapourSynth processing core and returns a pointer to it. It is possible to create multiple cores but in most cases it shouldn't be needed.

flags
    VSCoreCreationFlags ORed together if desired. Pass 0 for sane defaults that should suit most uses.

    ----

    void freeCore(VSCore *core) Frees a core. Should only be done after all frame requests have completed and all objects belonging to the core have been released.

    ----

    int64_t setMaxCacheSize(int64_t bytes, VSCore *core) Sets the maximum size of the framebuffer cache. Returns the new maximum size.

    ----

    int setThreadCount(int threads, VSCore *core) Sets the number of threads used for processing. Pass 0 to automatically detect. Returns the number of threads that will be used for processing.

    ----

    void getCoreInfo(VSCore *core, VSCoreInfo *info) Returns information about the VapourSynth core.

    ----

    int getAPIVersion() Returns the highest VAPOURSYNTH_API_VERSION the library support.

    ----

    void logMessage(int msgType, const char *msg, VSCore *core) Send a message through VapourSynth's logging framework. See addLogHandler.

msgType
    The type of message. One of VSMessageType.

    If msgType is mtFatal, VapourSynth will call abort() after delivering the message.

msg The message.

    ----

    VSLogHandle *addLogHandler(VSLogHandler handler, VSLogHandlerFree free, void *userData, VSCore *core) Installs a custom handler for the various error messages VapourSynth emits. The message handler is per VSCore instance. Returns a unique handle.

    If no log handler is installed up to a few hundred messages are cached and will be delivered as soon as a log handler is attached. This behavior exists mostly so that warnings when auto-loading plugins (default behavior) won't disappear-

handler
    typedef void (VS_CC *VSLogHandler)(int msgType, const char *msg, void *userdata)

    Custom message handler. If this is NULL, the default message handler will be restored.

msgType
    The type of message. One of VSMessageType.

    If msgType is mtFatal, VapourSynth will call abort() after the message handler returns.

msg The message.

free
    typedef void (VS_CC *VSLogHandlerFree)(void *userData)

    Called when a handler is removed.

userData
    Pointer that gets passed to the message handler.

    ----

    int removeLogHandler(VSLogHandle *handle, VSCore *core) Removes a custom handler. Return non-zero on success and zero if the handle is invalid.

handle
    Handle obtained from addLogHandler().

    ----

    VSFrame *newVideoFrame(const VSVideoFormat *format, int width, int height, const VSFrame *propSrc, VSCore *core) Creates a new video frame, optionally copying the properties attached to another frame. It is a fatal error to pass invalid arguments to this function.

    The new frame contains uninitialised memory.

format
    The desired colorspace format. Must not be NULL.

    width

height
    The desired dimensions of the frame, in pixels. Must be greater than 0 and have a suitable multiple for the subsampling in format.

propSrc
    A frame from which properties will be copied. Can be NULL.

    Returns a pointer to the created frame. Ownership of the new frame is transferred to the caller.

    See also newVideoFrame2().

    ----

    VSFrame *newVideoFrame2(const VSVideoFormat *format, int width, int height, const VSFrame **planeSrc, const int *planes, const VSFrame *propSrc, VSCore *core) Creates a new video frame from the planes of existing frames, optionally copying the properties attached to another frame. It is a fatal error to pass invalid arguments to this function.

format
    The desired colorspace format. Must not be NULL.

    width

height
    The desired dimensions of the frame, in pixels. Must be greater than 0 and have a suitable multiple for the subsampling in format.

planeSrc
    Array of frames from which planes will be copied. If any elements of the array are NULL, the corresponding planes in the new frame will contain uninitialised memory.

planes
    Array of plane numbers indicating which plane to copy from the corresponding source frame.

propSrc
    A frame from which properties will be copied. Can be NULL.

    Returns a pointer to the created frame. Ownership of the new frame is transferred to the caller.

    Example (assume frameA, frameB, frameC are existing frames):

        const VSFrame * frames[3] = { frameA, frameB, frameC };
        const int planes[3] = { 1, 0, 2 };
        VSFrame * newFrame = vsapi->newVideoFrame2(f, w, h, frames, planes, frameB, core);

    The newFrame's first plane is now a copy of frameA's second plane, the second plane is a copy of frameB's first plane, the third plane is a copy of frameC's third plane and the properties have been copied from frameB.

    ----

    VSFrame *newAudioFrame(const VSAudioFormat *format, int numSamples, const VSFrame *propSrc, VSCore *core) Creates a new audio frame, optionally copying the properties attached to another frame. It is a fatal error to pass invalid arguments to this function.

    The new frame contains uninitialised memory.

format
    The desired audio format. Must not be NULL.

numSamples
    The number of samples in the frame. All audio frames apart from the last one returned by a filter must have VS_AUDIO_FRAME_SAMPLES.

propSrc
    A frame from which properties will be copied. Can be NULL.

    Returns a pointer to the created frame. Ownership of the new frame is transferred to the caller.

    See also newAudioFrame2().

    ----

    VSFrame *newAudioFrame2(const VSAudioFormat *format, int numSamples, const VSFrame **channelSrc, const int *channels, const VSFrame *propSrc, VSCore *core) Creates a new audio frame, optionally copying the properties attached to another frame. It is a fatal error to pass invalid arguments to this function.

    The new frame contains uninitialised memory.

format
    The desired audio format. Must not be NULL.

numSamples
    The number of samples in the frame. All audio frames apart from the last one returned by a filter must have VS_AUDIO_FRAME_SAMPLES.

channelSrc
    Array of frames from which channels will be copied. If any elements of the array are NULL, the corresponding planes in the new frame will contain uninitialised memory.

channels
    Array of channel numbers indicating which channel to copy from the corresponding source frame. Note that the number refers to the nth channel and not a channel name constant.

propSrc
    A frame from which properties will be copied. Can be NULL.

    Returns a pointer to the created frame. Ownership of the new frame is transferred to the caller.

    See also newVideoFrame2().

    ----

    void freeFrame(const VSFrame *f) Decrements the reference count of a frame and deletes it when it reaches 0.

    It is safe to pass NULL.

    ----

    const VSFrame *addFrameRef(const VSFrame *f) Increments the reference count of a frame. Returns f as a convenience.

    ----

    VSFrame *copyFrame(const VSFrame *f, VSCore *core) Duplicates the frame (not just the reference). As the frame buffer is shared in a copy-on-write fashion, the frame content is not really duplicated until a write operation occurs. This is transparent for the user.

    Returns a pointer to the new frame. Ownership is transferred to the caller.

    ----

    const VSMap *getFramePropertiesRO(const VSFrame *f) Returns a read-only pointer to a frame's properties. The pointer is valid as long as the frame lives.

    ----

    VSMap *getFramePropertiesRW(VSFrame *f) Returns a read/write pointer to a frame's properties. The pointer is valid as long as the frame lives.

    ----

    ptrdiff_t getStride(const VSFrame *f, int plane) Returns the distance in bytes between two consecutive lines of a plane of a video frame. The stride is always positive. Returns 0 if the requested plane doesn't exist or if it isn't a video frame.

    ----

    const uint8_t *getReadPtr(const VSFrame *f, int plane) Returns a read-only pointer to a plane or channel of a frame. Returns NULL if an invalid plane or channel number is passed.

    NOTE: Don't assume all three planes of a frame are allocated in one contiguous chunk (they're not).

    ----

    uint8_t *getWritePtr(VSFrame *f, int plane) Returns a read-write pointer to a plane or channel of a frame. Returns NULL if an invalid plane or channel number is passed.

    NOTE: Don't assume all three planes of a frame are allocated in one contiguous chunk (they're not).

    ----

    const VSVideoFormat *getVideoFrameFormat(const VSFrame *f) Retrieves the format of a video frame.

    ----

    const VSAudioFormat *getAudioFrameFormat(const VSFrame *f) Retrieves the format of an audio frame.

    ----

    int getFrameType(const VSFrame *f) Returns a value from VSMediaType to distinguish audio and video frames.

    ----

    int getFrameWidth(const VSFrame *f, int plane) Returns the width of a plane of a given video frame, in pixels. The width depends on the plane number because of the possible chroma subsampling. Returns 0 for audio frames.

    ----

    int getFrameHeight(const VSFrame *f, int plane) Returns the height of a plane of a given video frame, in pixels. The height depends on the plane number because of the possible chroma subsampling. Returns 0 for audio frames.

    ----

    int getFrameLength(const VSFrame *f) Returns the number of audio samples in a frame. Always returns 1 for video frames.

    ----

    void createVideoFilter(VSMap *out, const char *name, const VSVideoInfo *vi, VSFilterGetFrame getFrame, VSFilterFree free, int filterMode, const VSFilterDependency *dependencies, int numDeps, void *instanceData, VSCore *core) Creates a new video filter node.

out Output map for the filter node.

name
    Instance name. Please make it the same as the filter's name for easy identification.

vi  The output format of the filter.

getFrame
    The filter's "getframe" function. Must not be NULL.

free
    The filter's "free" function. Can be NULL.

filterMode
    One of VSFilterMode. Indicates the level of parallelism supported by the filter.

dependencies
    An array of nodes the filter requests frames from and the access pattern. Used to more efficiently configure caches.

numDeps
    Length of the dependencies array.

instanceData
    A pointer to the private filter data. This pointer will be passed to the getFrame and free functions. It should be freed by the free function.

    After this function returns, out will contain the new node appended to the "clip" property, or an error, if something went wrong.

    ----

    VSNode *createVideoFilter2(const char *name, const VSVideoInfo *vi, VSFilterGetFrame getFrame, VSFilterFree free, int filterMode, const VSFilterDependency *dependencies, int numDeps, void *instanceData, VSCore *core) Identical to createVideoFilter except that the new node is returned instead of appended to the out map. Returns NULL on error.

    ----

    void createAudioFilter(VSMap *out, const char *name, const VSAudioInfo *ai, VSFilterGetFrame getFrame, VSFilterFree free, int filterMode, const VSFilterDependency *dependencies, int numDeps, void *instanceData, VSCore *core) Creates a new video filter node.

out Output map for the filter node.

name
    Instance name. Please make it the same as the filter's name for easy identification.

ai  The output format of the filter.

getFrame
    The filter's "getframe" function. Must not be NULL.

free
    The filter's "free" function. Can be NULL.

filterMode
    One of VSFilterMode. Indicates the level of parallelism supported by the filter.

dependencies
    An array of nodes the filter requests frames from and the access pattern. Used to more efficiently configure caches.

numDeps
    Length of the dependencies array.

instanceData
    A pointer to the private filter data. This pointer will be passed to the getFrame and free functions. It should be freed by the free function.

    After this function returns, out will contain the new node appended to the "clip" property, or an error, if something went wrong.

    ----

    VSNode *createAudioFilter2(const char *name, const VSAudioInfo *ai, VSFilterGetFrame getFrame, VSFilterFree free, int filterMode, const VSFilterDependency *dependencies, int numDeps, void *instanceData, VSCore *core) Identical to createAudioFilter except that the new node is returned instead of appended to the out map. Returns NULL on error.

    ----

    int setLinearFilter(VSNode *node) Must be called immediately after audio or video filter creation. Returns the upper bound of how many additional frames it is reasonable to pass to cacheFrame when trying to make a request more linear.

    ----

    void setCacheMode(VSNode *node, int mode) Determines the strategy for frame caching. Pass a VSCacheMode constant. Mostly useful for cache debugging since the auto mode should work well in just about all cases. Calls to this function may also be silently ignored.

    Resets the cache to default options when called, discarding setCacheOptions changes.

    ----

    void setCacheOptions(VSNode *node, int fixedSize, int maxSize, int maxHistorySize) Call after setCacheMode or the changes will be discarded. Sets internal details of a node's associated cache. Calls to this function may also be silently ignored.

fixedSize
    Set to non-zero to make the cache always hold maxSize frames.

maxSize
    The maximum number of frames to cache. Note that this value is automatically adjusted using an internal algorithm unless fixedSize is set.

maxHistorySize
    How many frames that have been recently evicted from the cache to keep track off. Used to determine if growing or shrinking the cache is beneficial. Has no effect when fixedSize is set.

    ----

    void freeNode(VSNode *node) Decreases the reference count of a node and destroys it once it reaches 0.

    It is safe to pass NULL.

    ----

    VSNode *addNodeRef(VSNode *node) Increment the reference count of a node. Returns the same node for convenience.

    ----

    int getNodeType(VSNode *node) Returns VSMediaType. Used to determine if a node is of audio or video type.

    ----

    const VSVideoInfo *getVideoInfo(VSNode *node) Returns a pointer to the video info associated with a node. The pointer is valid as long as the node lives. It is undefined behavior to pass a non-video node.

    ----

    const VSAudioInfo *getAudioInfo(VSNode *node) Returns a pointer to the audio info associated with a node. The pointer is valid as long as the node lives. It is undefined behavior to pass a non-audio node.

    ----

    int getVideoFormatName(const VSVideoFormat *format, char *buffer) Tries to output a fairly human-readable name of a video format.

format
    The input video format.

buffer
    Destination buffer. At most 32 bytes including terminating NULL will be written.

    Returns non-zero on success.

    ----

    int getAudioFormatName(const VSAudioFormat *format, char *buffer) Tries to output a fairly human-readable name of an audio format.

format
    The input audio format.

buffer
    Destination buffer. At most 32 bytes including terminating NULL will be written.

    Returns non-zero on success.

    ----

    int queryVideoFormat(VSVideoFormat *format, int colorFamily, int sampleType, int bitsPerSample, int subSamplingW, int subSamplingH, VSCore *core) Fills out a VSVideoInfo struct based on the provided arguments. Validates the arguments before filling out format.

format
    The struct to fill out.

colorFamily
    One of VSColorFamily.

sampleType
    One of VSSampleType.

bitsPerSample
    Number of meaningful bits for a single component. The valid range is 8-32.

    For floating point formats only 16 or 32 bits are allowed.

subSamplingW
    log2 of the horizontal chroma subsampling. 0 == no subsampling. The valid range is 0-4.

subSamplingH
    log2 of the vertical chroma subsampling. 0 == no subsampling. The valid range is 0-4.

    NOTE: RGB formats are not allowed to be subsampled in VapourSynth.

    Returns non-zero on success.

    ----

    int queryAudioFormat(VSAudioFormat *format, int sampleType, int bitsPerSample, uint64_t channelLayout, VSCore *core) Fills out a VSAudioFormat struct based on the provided arguments. Validates the arguments before filling out format.

format
    The struct to fill out.

sampleType
    One of VSSampleType.

bitsPerSample
    Number of meaningful bits for a single component. The valid range is 8-32.

    For floating point formats only 32 bits are allowed.

channelLayout
    A bitmask constructed from bitshifted constants in VSAudioChannels. For example stereo is expressed as (1 << acFrontLeft) | (1 << acFrontRight).

    Returns non-zero on success.

    ----

    uint32_t queryVideoFormatID(int colorFamily, int sampleType, int bitsPerSample, int subSamplingW, int subSamplingH, VSCore *core) Get the id associated with a video format. Similar to queryVideoFormat() except that it returns a format id instead of filling out a VSVideoInfo struct.

colorFamily
    One of VSColorFamily.

sampleType
    One of VSSampleType.

bitsPerSample
    Number of meaningful bits for a single component. The valid range is 8-32.

    For floating point formats, only 16 or 32 bits are allowed.

subSamplingW
    log2 of the horizontal chroma subsampling. 0 == no subsampling. The valid range is 0-4.

subSamplingH
    log2 of the vertical chroma subsampling. 0 == no subsampling. The valid range is 0-4.

    NOTE: RGB formats are not allowed to be subsampled in VapourSynth.

    Returns a valid format id if the provided arguments are valid, on error 0 is returned.

    ----

    int getVideoFormatByID(VSVideoFormat *format, uint32_t id, VSCore *core) Fills out the VSVideoFormat struct passed to format based

format
    The struct to fill out.

id  The format identifier: one of VSPresetVideoFormat or a value gotten from queryVideoFormatID.

    Returns 0 on failure and non-zero on success.

    ----

    VSMap *createMap(void) Creates a new property map. It must be deallocated later with freeMap().

    ----

    void freeMap(VSMap *map) Frees a map and all the objects it contains.

    ----

    void clearMap(VSMap *map) Deletes all the keys and their associated values from the map, leaving it empty.

    ----

    const char *mapGetError(const VSMap *map) Returns a pointer to the error message contained in the map, or NULL if there is no error set. The pointer is valid until the next modifying operation on the map.

    ----

    void mapSetError(VSMap *map, const char *errorMessage) Adds an error message to a map. The map is cleared first. The error message is copied. In this state the map may only be freed, cleared or queried for the error message.

    For errors encountered in a filter's "getframe" function, use setFilterError.

    ----

    int mapNumKeys(const VSMap *map) Returns the number of keys contained in a property map.

    ----

    const char *mapGetKey(const VSMap *map, int index) Returns the nth key from a property map.

    Passing an invalid index will cause a fatal error.

    The pointer is valid as long as the key exists in the map.

    ----

    int mapDeleteKey(VSMap *map, const char *key) Removes the property with the given key. All values associated with the key are lost.

    Returns 0 if the key isn't in the map. Otherwise it returns 1.

    ----

    int mapNumElements(const VSMap *map, const char *key) Returns the number of elements associated with a key in a property map. Returns -1 if there is no such key in the map.

    ----

    int mapGetType(const VSMap *map, const char *key) Returns a value from VSPropertyType representing type of elements in the given key. If there is no such key in the map, the returned value is ptUnset. Note that also empty arrays created with mapSetEmpty are typed.

    ----

    int mapSetEmpty(const VSMap *map, const char *key, int type) Creates an empty array of type in key. Returns non-zero value on failure due to key already existing or having an invalid name.

    ----

    int64_t mapGetInt(const VSMap *map, const char *key, int index, int *error) Retrieves an integer from a specified key in a map.

    Returns the number on success, or 0 in case of error.

    If the map has an error set (i.e. if mapGetError() returns non-NULL), VapourSynth will die with a fatal error.

index
    Zero-based index of the element.

    Use mapNumElements() to know the total number of elements associated with a key.

error
    One of VSMapPropertyError, peSuccess on success.

    You may pass NULL here, but then any problems encountered while retrieving the property will cause VapourSynth to die with a fatal error.

    ----

    int mapGetIntSaturated(const VSMap *map, const char *key, int index, int *error) Works just like mapGetInt() except that the value returned is also converted to an integer using saturation.

    ----

    const int64_t *mapGetIntArray(const VSMap *map, const char *key, int *error) Retrieves an array of integers from a map. Use this function if there are a lot of numbers associated with a key, because it is faster than calling mapGetInt() in a loop.

    Returns a pointer to the first element of the array on success, or NULL in case of error. Use mapNumElements() to know the total number of elements associated with a key.

    See mapGetInt() for a complete description of the arguments and general behavior.

    ----

    int mapSetInt(VSMap *map, const char *key, int64_t i, int append) Sets an integer to the specified key in a map.

    Multiple values can be associated with one key, but they must all be the same type.

key Name of the property. Alphanumeric characters and underscore may be used.

i   Value to store.

append
    One of VSMapAppendMode.

    Returns 0 on success, or 1 if trying to append to a property with the wrong type to an existing key.

    ----

    int mapSetIntArray(VSMap *map, const char *key, const int64_t *i, int size) Adds an array of integers to a map. Use this function if there are a lot of numbers to add, because it is faster than calling mapSetInt() in a loop.

    If map already contains a property with this key, that property will be overwritten and all old values will be lost.

key Name of the property. Alphanumeric characters and underscore may be used.

i   Pointer to the first element of the array to store.

size
    Number of integers to read from the array. It can be 0, in which case no integers are read from the array, and the property will be created empty.

    Returns 0 on success, or 1 if size is negative.

    ----

    double mapGetFloat(const VSMap *map, const char *key, int index, int *error) Retrieves a floating point number from a map.

    Returns the number on success, or 0 in case of error.

    See mapGetInt() for a complete description of the arguments and general behavior.

    ----

    float mapGetFloatSaturated(const VSMap *map, const char *key, int index, int *error) Works just like mapGetFloat() except that the value returned is also converted to a float.

    ----

    const double *mapGetFloatArray(const VSMap *map, const char *key, int *error) Retrieves an array of floating point numbers from a map. Use this function if there are a lot of numbers associated with a key, because it is faster than calling mapGetFloat() in a loop.

    Returns a pointer to the first element of the array on success, or NULL in case of error. Use mapNumElements() to know the total number of elements associated with a key.

    See mapGetInt() for a complete description of the arguments and general behavior.

    ----

    int mapSetFloat(VSMap *map, const char *key, double d, int append) Sets a float to the specified key in a map.

    See mapSetInt() for a complete description of the arguments and general behavior.

    ----

    int mapSetFloatArray(VSMap *map, const char *key, const double *d, int size) Adds an array of floating point numbers to a map. Use this function if there are a lot of numbers to add, because it is faster than calling mapSetFloat() in a loop.

    If map already contains a property with this key, that property will be overwritten and all old values will be lost.

key Name of the property. Alphanumeric characters and underscore may be used.

d   Pointer to the first element of the array to store.

size
    Number of floating point numbers to read from the array. It can be 0, in which case no numbers are read from the array, and the property will be created empty.

    Returns 0 on success, or 1 if size is negative.

    ----

    const char *mapGetData(const VSMap *map, const char *key, int index, int *error) Retrieves arbitrary binary data from a map. Checking mapGetDataTypeHint() may provide a hint about whether or not the data is human readable.

    Returns a pointer to the data on success, or NULL in case of error.

    The array returned is guaranteed to be NULL-terminated. The NULL byte is not considered to be part of the array (mapGetDataSize doesn't count it).

    The pointer is valid until the map is destroyed, or until the corresponding key is removed from the map or altered.

    See mapGetInt() for a complete description of the arguments and general behavior.

    ----

    int mapGetDataSize(const VSMap *map, const char *key, int index, int *error) Returns the size in bytes of a property of type ptData (see VSPropertyType), or 0 in case of error. The terminating NULL byte added by mapSetData() is not counted.

    See mapGetInt() for a complete description of the arguments and general behavior.

    ----

    int mapGetDataTypeHint(const VSMap *map, const char *key, int index, int *error) Returns the size in bytes of a property of type ptData (see VSPropertyType), or 0 in case of error. The terminating NULL byte added by mapSetData() is not counted.

    See mapGetInt() for a complete description of the arguments and general behavior.

    ----

    int mapSetData(VSMap *map, const char *key, const char *data, int size, int type, int append) Sets binary data to the specified key in a map.

    Multiple values can be associated with one key, but they must all be the same type.

key Name of the property. Alphanumeric characters and the underscore may be used.

data
    Value to store.

    This function copies the data, so the pointer should be freed when no longer needed. A terminating NULL is always added to the copied data but not included in the total size to make string handling easier.

size
    The number of bytes to copy. If this is negative, everything up to the first NULL byte will be copied.

type
    One of VSDataTypeHint to hint whether or not it is human readable data.

append
    One of VSMapAppendMode.

    Returns 0 on success, or 1 if trying to append to a property with the wrong type.

    ----

    VSNode *mapGetNode(const VSMap *map, const char *key, int index, int *error) Retrieves a node from a map.

    Returns a pointer to the node on success, or NULL in case of error.

    This function increases the node's reference count, so freeNode() must be used when the node is no longer needed.

    See mapGetInt() for a complete description of the arguments and general behavior.

    ----

    int mapSetNode(VSMap *map, const char *key, VSNode *node, int append) Sets a node to the specified key in a map.

    See mapSetInt() for a complete description of the arguments and general behavior.

    ----

    int mapConsumeNode(VSMap *map, const char *key, VSNode *node, int append) Sets a node to the specified key in a map and decreases the reference count.

    See mapSetInt() for a complete description of the arguments and general behavior.

    ----

    const VSFrame *mapGetFrame(const VSMap *map, const char *key, int index, int *error) Retrieves a frame from a map.

    Returns a pointer to the frame on success, or NULL in case of error.

    This function increases the frame's reference count, so freeFrame() must be used when the frame is no longer needed.

    See mapGetInt() for a complete description of the arguments and general behavior.

    ----

    int mapSetFrame(VSMap *map, const char *key, const VSFrame *f, int append) Sets a frame to the specified key in a map.

    See mapSetInt() for a complete description of the arguments and general behavior.

    ----

    int mapConsumeFrame(VSMap *map, const char *key, const VSFrame *f, int append) Sets a frame to the specified key in a map and decreases the reference count.

    See mapSetInt() for a complete description of the arguments and general behavior.

    ----

    VSFunctionRef *mapGetFunction(const VSMap *map, const char *key, int index, int *error) Retrieves a function from a map.

    Returns a pointer to the function on success, or NULL in case of error.

    This function increases the function's reference count, so freeFunction() must be used when the function is no longer needed.

    See mapGetInt() for a complete description of the arguments and general behavior.

    ----

    int mapSetFunction(VSMap *map, const char *key, VSFunction *func, int append) Sets a function object to the specified key in a map.

    See mapSetInt() for a complete description of the arguments and general behavior.

    ----

    int mapConsumeFunction(VSMap *map, const char *key, VSFunction *func, int append) Sets a function object to the specified key in a map and decreases the reference count.

    See mapSetInt() for a complete description of the arguments and general behavior.

    ----

    VSPlugin *getPluginByID(const char *identifier, VSCore *core) Returns a pointer to the plugin with the given identifier, or NULL if not found.

identifier
    Reverse URL that uniquely identifies the plugin.

    ----

    VSPlugin *getPluginByNamespace(const char *ns, VSCore *core) Returns a pointer to the plugin with the given namespace, or NULL if not found.

    getPluginByID is generally a better option.

ns  Namespace.

    ----

    VSPlugin *getNextPlugin(VSPlugin *plugin, VSCore *core) Used to enumerate over all currently loaded plugins. The order is fixed but provides no other guarantees.

plugin
    Current plugin. Pass NULL to get the first plugin.

    Returns a pointer to the next plugin in order or NULL if the final plugin has been reached.

    ----

    const char *getPluginName(VSPlugin *plugin) Returns the name of the plugin that was passed to configPlugin.

    ----

    const char *getPluginID(VSPlugin *plugin) Returns the identifier of the plugin that was passed to configPlugin.

    ----

    const char *getPluginNamespace(VSPlugin *plugin) Returns the namespace the plugin currently is loaded in.

    ----

    VSPluginFunction *getNextPluginFunction(VSPluginFunction *func, VSPlugin *plugin) Used to enumerate over all functions in a plugin. The order is fixed but provides no other guarantees.

func
    Current function. Pass NULL to get the first function.

plugin
    The plugin to enumerate functions in.

    Returns a pointer to the next function in order or NULL if the final function has been reached.

    ----

    VSPluginFunction *getPluginFunctionByName(const char *name, VSPlugin *plugin) Get a function belonging to a plugin by its name.

    ----

    const char *getPluginFunctionName(VSPluginFunction *func) Returns the name of the function that was passed to registerFunction.

    ----

    const char *getPluginFunctionArguments(VSPluginFunction *func) Returns the argument string of the function that was passed to registerFunction.

    ----

    const char *getPluginFunctionReturnType(VSPluginFunction *func) Returns the return type string of the function that was passed to registerFunction.

    ----

    const char *getPluginPath(const VSPlugin *plugin) Returns the absolute path to the plugin, including the plugin's file name. This is the real location of the plugin, i.e. there are no symbolic links in the path.

    Path elements are always delimited with forward slashes.

    VapourSynth retains ownership of the returned pointer.

    ----

    int getPluginVersion(const VSPlugin *plugin) Returns the version of the plugin. This is the same as the version number passed to configPlugin.

    ----

    VSMap *invoke(VSPlugin *plugin, const char *name, const VSMap *args) Invokes a filter.

    invoke() checks that the args passed to the filter are consistent with the argument list registered by the plugin that contains the filter, calls the filter's "create" function, and checks that the filter returns the declared types. If everything goes smoothly, the filter will be ready to generate frames after invoke() returns.

plugin
    A pointer to the plugin where the filter is located. Must not be NULL.

    See getPluginByID().

name
    Name of the filter to invoke.

args
    Arguments for the filter.

    Returns a map containing the filter's return value(s). The caller takes ownership of the map. Use mapGetError() to check if the filter was invoked successfully.

    Most filters will either set an error, or one or more clips with the key "clip". The exception to this are functions, for example LoadPlugin, which doesn't return any clips for obvious reasons.

    ----

    VSFunction *createFunction(VSPublicFunction func, void *userData, VSFreeFunctionData free, VSCore *core)

func
    typedef void (VS_CC *VSPublicFunction)(const VSMap *in, VSMap *out, void *userData, VSCore *core, const VSAPI *vsapi)

    User-defined function that may be called in any context.

userData
    Pointer passed to func.

free
    typedef void (VS_CC *VSFreeFunctionData)(void *userData)

    Callback tasked with freeing userData. Can be NULL.

    ----

    void freeFunction(VSFunction *f) Decrements the reference count of a function and deletes it when it reaches 0.

    It is safe to pass NULL.

    ----

    VSFunction *addFunctionRef(VSFunction *f) Increments the reference count of a function. Returns f as a convenience.

    ----

    void callFunction(VSFunction *func, const VSMap *in, VSMap *out) Calls a function. If the call fails out will have an error set.

func
    Function to be called.

in  Arguments passed to func.

out Returned values from func.

    ----

    const VSFrame *getFrame(int n, VSNode *node, char *errorMsg, int bufSize) Fetches a frame synchronously. The frame is available when the function returns.

    This function is meant for external applications using the core as a library, or if frame requests are necessary during a filter's initialization.

    Thread-safe.

n   The frame number. Negative values will cause an error.

node
    The node from which the frame is requested.

errorMsg
    Pointer to a buffer of bufSize bytes to store a possible error message. Can be NULL if no error message is wanted.

bufSize
    Maximum length for the error message, in bytes (including the trailing '0'). Can be 0 if no error message is wanted.

    Returns a reference to the generated frame, or NULL in case of failure. The ownership of the frame is transferred to the caller.

    WARNING: Never use inside a filter's "getframe" function.

    ----

    void getFrameAsync(int n, VSNode *node, VSFrameDoneCallback callback, void *userData) Requests the generation of a frame. When the frame is ready, a user-provided function is called. Note that the completion callback will only be called from a single thread at a time.

    This function is meant for applications using VapourSynth as a library.

    Thread-safe.

n   Frame number. Negative values will cause an error.

node
    The node from which the frame is requested.

callback
    typedef void (VS_CC *VSFrameDoneCallback)(void *userData, const VSFrame *f, int n, VSNode *node, const char *errorMsg)

    Function of the client application called by the core when a requested frame is ready, after a call to getFrameAsync().

    If multiple frames were requested, they can be returned in any order. Client applications must take care of reordering them.

    This function is only ever called from one thread at a time.

    getFrameAsync() may be called from this function to request more frames.

userData
    Pointer to private data from the client application, as passed previously to getFrameAsync().

f   Contains a reference to the generated frame, or NULL in case of failure. The ownership of the frame is transferred to the caller.

n   The frame number.

node
    Node the frame belongs to.

errorMsg
    String that usually contains an error message if the frame generation failed. NULL if there is no error.

userData
    Pointer passed to the callback.

    WARNING: Never use inside a filter's "getframe" function.

    ----

    const VSFrame *getFrameFilter(int n, VSNode *node, VSFrameContext *frameCtx) Retrieves a frame that was previously requested with requestFrameFilter().

    Only use inside a filter's "getframe" function.

    A filter usually calls this function when its activation reason is arAllFramesReady or arFrameReady. See VSActivationReason.

    It is safe to retrieve a frame more than once, but each reference needs to be freed.

n   The frame number.

node
    The node from which the frame is retrieved.

frameCtx
    The context passed to the filter's "getframe" function.

    Returns a pointer to the requested frame, or NULL if the requested frame is not available for any reason. The ownership of the frame is transferred to the caller.

    ----

    void requestFrameFilter(int n, VSNode *node, VSFrameContext *frameCtx) Requests a frame from a node and returns immediately.

    Only use inside a filter's "getframe" function.

    A filter usually calls this function when its activation reason is arInitial. The requested frame can then be retrieved using getFrameFilter(), when the filter's activation reason is arAllFramesReady. See VSActivationReason.

    It is best to request frames in ascending order, i.e. n, n+1, n+2, etc.

n   The frame number. Negative values will cause an error.

node
    The node from which the frame is requested.

frameCtx
    The context passed to the filter's "getframe" function.

    ----

    void releaseFrameEarly(VSNode *node, int n, VSFrameContext *frameCtx) By default all requested frames are referenced until a filter's frame request is done. In extreme cases where a filter needs to reduce 20+ frames into a single output frame it may be beneficial to request these in batches and incrementally process the data instead.

    Should rarely be needed.

    Only use inside a filter's "getframe" function.

node
    The node from which the frame was requested.

n   The frame number. Invalid frame numbers (not cached or negative) will simply be ignored.

frameCtx
    The context passed to the filter's "getframe" function.

    ----

    int registerFunction(const char *name, const char *args, const char *returnType, VSPublicFunction argsFunc, void *functionData, VSPlugin *plugin) Function that registers a filter exported by the plugin. A plugin can export any number of filters. This function may only be called during the plugin loading phase unless the pcModifiable flag was set by configPlugin.

name
    Filter name. The characters allowed are letters, numbers, and the underscore. The first character must be a letter. In other words: ^[a-zA-Z][a-zA-Z0-9_]*$

    Filter names should be PascalCase.

args
    String containing the filter's list of arguments.

    Arguments are separated by a semicolon. Each argument is made of several fields separated by a colon. Don't insert additional whitespace characters, or VapourSynth will die.

Fields:

The argument name.
    The same characters are allowed as for the filter's name. Argument names should be all lowercase and use only letters and the underscore.

The type.
    "int": int64_t

    "float": double

    "data": const char*

    "anode": const VSNode* (audio type)

    "vnode": const VSNode* (video type)

    "aframe": const VSFrame* (audio type)

    "vframe": const VSFrame* (video type)

    "func": const VSFunctionRef*

    It is possible to declare an array by appending "[]" to the type.

"opt"
    If the parameter is optional.

"empty"
    For arrays that are allowed to be empty.

"any"
    Can only be placed last without a semicolon after. Indicates that all remaining arguments that don't match should also be passed through.

    The following example declares the arguments "blah", "moo", and "asdf":

        blah:vnode;moo:int[]:opt;asdf:float:opt;

    The following example declares the arguments "blah" and accepts all other arguments no matter the type:

        blah:vnode;any

returnType
    Specifies works similarly to args but instead specifies which keys and what type will be returned. Typically this will be:

        clip:vnode;

    for video filters. It is important to not simply specify "any" for all filters since this information is used for better auto-completion in many editors.

argsFunc
    typedef void (VS_CC *VSPublicFunction)(const VSMap *in, VSMap *out, void *userData, VSCore *core, const VSAPI *vsapi)

    User-defined function called by the core to create an instance of the filter. This function is often named fooCreate.

    In this function, the filter's input parameters should be retrieved and validated, the filter's private instance data should be initialised, and createAudioFilter() or createVideoFilter() should be called. This is where the filter should perform any other initialisation it requires.

    If for some reason you cannot create the filter, you have to free any created node references using freeNode(), call mapSetError() on out, and return.

in  Input parameter list.

    Use mapGetInt() and friends to retrieve a parameter value.

    The map is guaranteed to exist only until the filter's "init" function returns. In other words, pointers returned by mapGetData() will not be usable in the filter's "getframe" and "free" functions.

out Output parameter list. createAudioFilter() or createVideoFilter() will add the output node(s) with the key named "clip", or an error, if something went wrong.

userData
    Pointer that was passed to registerFunction().

functionData
    Pointer to user data that gets passed to argsFunc when creating a filter. Useful to register multiple filters using a single argsFunc function.

plugin
    Pointer to the plugin object in the core, as passed to VapourSynthPluginInit2().

    ----

    void cacheFrame(const VSFrame *frame, int n, VSFrameContext *frameCtx) Pushes a not requested frame into the cache. This is useful for (source) filters that greatly benefit from completely linear access and producing all output in linear order.

    This function may only be used in filters that were created with setLinearFilter.

    Only use inside a filter's "getframe" function.

    ----

    void setFilterError(const char *errorMessage, VSFrameContext *frameCtx) Adds an error message to a frame context, replacing the existing message, if any.

    This is the way to report errors in a filter's "getframe" function. Such errors are not necessarily fatal, i.e. the caller can try to request the same frame again.

  Functions

const VSAPI* getVapourSynthAPI(int version) Returns a pointer to the global VSAPI instance.

Returns NULL if the requested API version is not supported or if the system does not meet the minimum requirements to run VapourSynth. It is recommended to pass VAPOURSYNTH_API_VERSION.

  Writing plugins

A simple VapourSynth plugin which exports one filter will contain five functions: an entry point (called VapourSynthPluginInit2), a function tasked with creating a filter instance (often called fooCreate), an "init" function (often called fooInit), a "getframe" function (often called fooGetframe), and a "free" function (often called fooFree). These functions are described below.

Another thing a filter requires is an object for storing a filter instance's private data. This object will usually contain the filter's input nodes (if it has any) and a VSVideoInfo struct describing the video the filter wants to return.

The sdk folder in the VapourSynth source contains some examples.

----

typedef void (VS_CC *VSInitPlugin)(VSPlugin *plugin, const VSPLUGINAPI *vspapi) A plugin's entry point. It must be called VapourSynthPluginInit2. This function is called after the core loads the shared library. Its purpose is to configure the plugin and to register the filters the plugin wants to export.

plugin
    A pointer to the plugin object to be initialized.

vspapi
    A pointer to a VSPLUGINAPI struct with a subset of the VapourSynth API used for initializing plugins. The proper way to do things is to call configPlugin and then registerFunction for each function to export.

    ----

    typedef const VSFrame *(VS_CC *VSFilterGetFrame)(int n, int activationReason, void *instanceData, void **frameData, VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi) A filter's "getframe" function. It is called by the core when it needs the filter to generate a frame.

    It is possible to allocate local data, persistent during the multiple calls requesting the output frame.

    In case of error, call setFilterError(), free *frameData if required, and return NULL.

    Depending on the VSFilterMode set for the filter, multiple output frames could be requested concurrently.

    It is never called concurrently for the same frame number.

n   Requested frame number.

activationReason
    One of VSActivationReason.

    This function is first called with activationReason arInitial. At this point the function should request the input frames it needs and return NULL. When one or all of the requested frames are ready, this function is called again with arAllFramesReady. The function should only return a frame when called with activationReason arAllFramesReady.

    If a the function is called with arError all processing has to be aborted and any.

instanceData
    The filter's private instance data.

frameData
    Optional private data associated with output frame number n. It must be deallocated before the last call for the given frame (arAllFramesReady or error).

    It points to a void *[4] array of memory that may be used freely. See filters like Splice and Trim for examples.

    Return a reference to the output frame number n when it is ready, or NULL. The ownership of the frame is transferred to the caller.

    ----

    typedef void (VS_CC *VSFilterFree)(void *instanceData, VSCore *core, const VSAPI *vsapi) A filter's "free" function.

    This is where the filter should free everything it allocated, including its instance data.

instanceData
    The filter's private instance data.

  VSHelper4.h

  Table of contents

Introduction

Macros
    VSH_STD_PLUGIN_ID

    VSH_RESIZE_PLUGIN_ID

    VSH_TEXT_PLUGIN_ID

    VS_RESTRICT

    VSH_ALIGNED_MALLOC

    VSH_ALIGNED_FREE

    VSMIN

    VSMAX

Functions
    vsh_aligned_malloc

    vsh_aligned_free

    isConstantFormat

    isSameVideoFormat

    isSameVideoPresetFormat

    isSameVideoInfo

    isSameAudioFormat

    isSameAudioInfo

    muldivRational

    addRational

    reduceRational

    int64ToIntS

    doubleToFloatS

    bitblt

    areValidDimensions

  Introduction

This is a collection of helpful macros and functions. Note that all functions (not macros) are either prefixed with vsh_ in C mode or placed in the vsh namespace for C++. This documentation will use the C++ names for these function.

  Macros

  VSH_STD_PLUGIN_ID

Macro defined to the internal std plugin id provided for convenience.

  VSH_RESIZE_PLUGIN_ID

Macro defined to the internal resizer plugin id provided for convenience.

  VSH_TEXT_PLUGIN_ID

Macro defined to the internal std plugin id provided for convenience.

  VS_RESTRICT

Attempts to provide a portable definition of the C99 restrict keyword, or its C++ counterpart.

  VSH_ALIGNED_MALLOC

VSH_ALIGNED_MALLOC(pptr, size, alignment)

Expands to _aligned_malloc() in Windows, and posix_memalign() elsewhere. Note that the arguments are in the style of posix_memalign().

pptr is a pointer to a pointer.

  VSH_ALIGNED_FREE

VSH_ALIGNED_FREE(ptr)

Expands to _aligned_free() in Windows, and free() elsewhere.

ptr is a pointer.

  VSMIN

VSMIN(a, b)

Returns the minimum of the two numbers.

  VSMAX

VSMAX(a, b)

Returns the maximum of the two numbers.

  Functions

  vsh_aligned_malloc

T *vsh::vsh_aligned_malloc(size_t size, size_t alignment)
    A templated aligned malloc for C++. It uses the same functions as the VSH_ALIGNED_MALLOC macro but is easier to use.

  vsh_aligned_free

void vsh::vsh_aligned_free(void *ptr)
    This simply uses the VSH_ALIGNED_FREE macro.

  isConstantFormat

static inline bool vsh::isConstantFormat(const VSVideoInfo *vi)
    Checks if a clip's format and dimensions are known (and therefore constant).

  isSameVideoFormat

static inline bool vsh::isSameVideoFormat(const VSVideoInfo *v1, const VSVideoInfo *v2)
    Checks if two clips have the same video format. If the format is unknown in both, it will be considered the same.

  isSameVideoPresetFormat

static inline bool vsh::isSameVideoPresetFormat(unsigned presetFormat, const VSVideoFormat *v, VSCore *core, const VSAPI *vsapi)
    Checks if a clip has the same video format as the preset.

  isSameVideoInfo

static inline bool vsh::isSameVideoInfo(const VSVideoInfo *v1, const VSVideoInfo *v2)
    Checks if two clips have the same video format and dimensions. If the format is unknown in both, it will be considered the same. This is also true for the dimensions. Framerate is not taken into consideration when comparing.

  isSameAudioFormat

static inline bool vsh::isSameAudioFormat(const VSAudioInfo *v1, const VSAudioInfo *v2)
    Checks if two clips have the same audio format.

  isSameAudioInfo

static inline bool vsh::isSameAudioInfo(const VSAudioInfo *v1, const VSAudioInfo *v2)
    Checks if two clips have the same audio format and samplerate.

  muldivRational

static inline void vsh::muldivRational(int64_t *num, int64_t *den, int64_t mul, int64_t div)
    Multiplies two rational numbers and reduces the result, i.e. num/den * mul/div. The result is stored in num and den.

    The caller must ensure that div is not 0.

  reduceRational

static inline void vsh::reduceRational(int64_t *num, int64_t *den)
    Reduces a rational number.

  addRational

static inline void vsh::addRational(int64_t *num, int64_t *den, int64_t addnum, int64_t addden)
    Adds two rational numbers and reduces the result, i.e. num/den + addnum/addden. The result is stored in num and den.

  int64ToIntS

static inline int vsh::int64ToIntS(int64_t i)
    Converts an int64_t to int with signed saturation. It's useful to silence warnings when reading integer properties from a VSMap and to avoid unexpected behavior on int overflow.

  doubleToFloatS

static inline int vsh::doubleToFloatS(double d)
    Converts a double to float. It's useful to silence warnings when reading double properties from a VSMap and mostly exists to mirror int64ToIntS.

  bitblt

static inline void vsh::bitblt(void *dstp, int dst_stride, const void *srcp, int src_stride, size_t row_size, size_t height)
    Copies bytes from one plane to another. Basically, it is memcpy in a loop.

    row_size is in bytes.

  areValidDimensions

static inline bool vsh::areValidDimensions(const VSFormat *fi, int width, int height)
    Checks if the given dimensions are valid for a particular format, with regards to chroma subsampling.

  VSScript4.h

  Table of contents

Introduction

Structs
    VSScript

    VSScriptAPI

Functions
    getVSScriptAPI

    getApiVersion

    getVSAPI

    createScript

    getCore

    evaluateBuffer

    evaluateFile

    getError

    getExitCode

    getVariable

    setVariables

    getOutputNode

    getOutputAlphaNode

    getAltOutputMode

    freeScript

    evalSetWorkingDir

  Introduction

VSScript provides a convenient wrapper for VapourSynth's scripting interface(s), allowing the evaluation of VapourSynth scripts and retrieval of output clips.

For reasons unknown, the VSScript library is called VSScript in Windows and vapoursynth-script everywhere else.

At this time, VapourSynth scripts can be written only in Python (version 3).

Here are a few users of the VSScript library:

•   vspipe

•   vsvfw

•   an example program

•   the video player mpv

    NOTE: If libvapoursynth-script is loaded with dlopen(), the RTLD_GLOBAL flag must be used. If not, Python won't be able to import binary modules. This is due to Python's design.

  Structs

  VSScript

A script environment. All evaluation and communication with evaluated scripts happens through a VSScript object.

  VSScriptAPI

This struct is the way to access VSScript's public API.

  Functions

  getVSScriptAPI

const VSSCRIPTAPI *getVSScriptAPI(int version)
    Returns a struct containing function pointer for the api. Will return NULL is the specified version isn't supported.

    It is recommended to always pass VSSCRIPT_API_VERSION.

  getApiVersion

int getApiVersion()
    Returns the api version provided by vsscript.

  getVSAPI

const VSAPI *getVSAPI(int version)
    Retrieves the VSAPI struct. Exists mostly as a convenience so the vapoursynth module doesn't have to be explicitly loaded.

    This could return NULL if the VapourSynth library doesn't provide the requested version.

  createScript

VSScript *createScript(VSCore *core)
    Creates an empty script environment that can be used to evaluate scripts. Passing a pre-created core can be usful to have custom core creation flags, log callbacks or plugins pre-loaded. Passing NULL will automatically create a new core with default settings.

    Takes over ownership of the core regardless of success or failure. Returns NULL on error.

  getCore

VSCore *getCore(VSScript *handle)
    Retrieves the VapourSynth core that was created in the script environment. If a VapourSynth core has not been created yet, it will be created now, with the default options (see the Python Reference).

    VSScript retains ownership of the returned core object.

    Returns NULL on error.

  evaluateBuffer

int evaluateBuffer(VSScript *handle, const char *buffer, const char *scriptFilename)
    Evaluates a script contained in a C string. Can be called multiple times on the same script environment to successively add more processing.

handle
    Pointer to a script environment.

buffer
    The entire script to evaluate, as a C string.

scriptFilename
    A name for the script, which will be displayed in error messages. If this is NULL, the name "<string>" will be used.

    The special __file__ variable will be set to scriptFilename's absolute path if this is not NULL.

    Returns non-zero in case of errors. The error message can be retrieved with getError(). If the script calls sys.exit(code) the exit code can be retrieved with getExitCode(). The working directory behavior can be changed by calling evalSetWorkingDir() before this function.

  evaluateFile

int evaluateFile(VSScript **handle, const char *scriptFilename)
    Evaluates a script contained in a file. This is a convenience function which reads the script from a file for you. It will only read the first 16 MiB which should be enough for everyone.

    Behaves the same as evaluateBuffer().

  getError

const char *getError(VSScript *handle)
    Returns the error message from a script environment, or NULL, if there is no error.

    It is okay to pass NULL.

    VSScript retains ownership of the pointer and it is only guaranteed to be valid until the next vsscript operation on the handle.

  getExitCode

int getExitCode(VSScript *handle)
    Returns the exit code if the script calls sys.exit(code), or 0, if the script fails for other reasons or calls sys.exit(0).

    It is okay to pass NULL.

  getVariable

int getVariable(VSScript *handle, const char *name, VSMap *dst)
    Retrieves a variable from the script environment.

    If a VapourSynth core has not been created yet in the script environment, one will be created now, with the default options (see the Python Reference).

name
    Name of the variable to retrieve.

dst Map where the variable's value will be placed, with the key name.

    Returns non-zero on error.

  setVariables

int vsscript_setVariable(VSScript *handle, const VSMap *vars)
    Sets variables in the script environment.

    The variables are now available to the script.

    If a VapourSynth core has not been created yet in the script environment, one will be created now, with the default options (see the Python Reference).

vars
    Map containing the variables to set.

    Returns non-zero on error.

  getOutputNode

VSNode *getOutputNode(VSScript *handle, int index)
    Retrieves a node from the script environment. A node in the script must have been marked for output with the requested index.

    The returned node has its reference count incremented by one.

    Returns NULL if there is no node at the requested index.

  getOutputAlphaNode

VSNode *getOutputAlphaNode(VSScript *handle, int index)
    Retrieves an alpha node from the script environment. A node with associated alpha in the script must have been marked for output with the requested index.

    The returned node has its reference count incremented by one.

    Returns NULL if there is no alpha node at the requested index.

  getAltOutputMode

int getAltOutputMode(VSScript *handle, int index)
    Retrieves the alternative output mode settings from the script. This value has no fixed meaning but in vspipe and vsvfw it indicates that alternate output formats should be used when multiple ones are available. It is up to the client application to define the exact meaning or simply disregard it completely.

    Returns 0 if there is no alt output mode set.

  freeScript

void freeScript(VSScript *handle)
    Frees a script environment. handle is no longer usable.

•   Cancels any clips set for output in the script environment.

•   Clears any variables set in the script environment.

•   Clears the error message from the script environment, if there is one.

•   Frees the VapourSynth core used in the script environment, if there is one.

    Since this function frees the VapourSynth core, it must be called only after all frame requests are finished and all objects obtained from the script have been freed (frames, nodes, etc).

    It is safe to pass NULL.

  evalSetWorkingDir

void evalSetWorkingDir(VSScript *handle, int setCWD)
    Set whether or not the working directory is temporarily changed to the same location as the script file when evaluateFile is called. Off by default.

  Common Pitfalls

There are several minor pitfalls related to the threading and design that have to be taken into consideration. Most of them usually aren't a problem but here's a small checklist of things you have to watch out for sometimes.

  General API

You may not pass objects (clips, functions and so on) owned by one core as arguments to filters in another core. A manual full deep copy of the data you want to pass on is required. This is generally not a problem since you should never need more than one core per filter graph.

  Plugins

Plugin code may run more multithreaded than it initially appears. VapourSynthPluginInit is the only function always guaranteed to not run in parallel. This means that the constructor and destructor of a filter may be run in parallel for several instances. Use proper synchronization if you need to initialize shared data.

The GetFrame function is a bit more complicated so see the reference of the constants. Do however note that the parallelism is per instance. Even if a filter is fmUnordered or fmSerial other instances may enter GetFrame simultaneously.

There are two common misconseptions about which mode should be used. A simple rule is that fmSerial should never be used. And source filters (those returning a frame on arInitial) that need locking should use fmUnordered.

  Reserved Frame Properties

All frames contain a map of key--value pairs. It is recommended that these properties are named using only a-z, A-Z, 0-9 using CamelCase. There is a special category of keys starting with _ which have strictly defined meanings specified below. It is acceptable to not set any of these keys if they are unknown. It is also a fatal error to set them to a value not specified below.

int _ChromaLocation Chroma sample position in YUV formats.

0=left, 1=center, 2=topleft, 3=top, 4=bottomleft, 5=bottom.

int _ColorRange Full or limited range (PC/TV range). Primarily used with YUV formats.

0=full range, 1=limited range.

int _Primaries Color primaries as specified in ITU-T H.265 Table E.3.

int _Matrix Matrix coefficients as specified in ITU-T H.265 Table E.5.

int _Transfer Transfer characteristics as specified in ITU-T H.265 Table E.4.

int _FieldBased If the frame is composed of two independent fields (interlaced).

0=frame based (progressive), 1=bottom field first, 2=top field first.

float _AbsoluteTime The frame's absolute timestamp in seconds if reported by the source filter. Should only be set by the source filter and not be modified. Use durations for all operations that depend on frame length.

int _DurationNum, int _DurationDen The frame's duration in seconds as a rational number. Filters that modify the framerate should also change these values.

This fraction should always be normalized.

bint _Combed Whether or not the frame needs postprocessing, usually hinted from field matching filters.

int _Field If the frame was produced by something like core.std.SeparateFields, this property signals which field was used to generate this frame.

0=from bottom field, 1=from top field.

string _PictType A single character describing the frame type. It uses the common IPB letters but other letters may also be used for formats with additional frame types.

int _SARNum, int _SARDen Pixel (sample) aspect ratio as a rational number.

bint _SceneChangeNext If 1, this frame is the last frame of the current scene. The next frame starts a new scene.

bint _SceneChangePrev If 1, this frame starts a new scene.

frame _Alpha A clip's alpha channel can be attached to the clip one frame at a time using this property.

•   Index

•   Search Page

AUTHOR
Fredrik Mellbin

COPYRIGHT
2012-2024, Fredrik Mellbin