Pythonreference RST
Pythonreference RST
_pythonreference:
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 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.
The VideoNode 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.
Note that frame numbers, like python arrays, start counting at 0.
Here are a few examples.
video = clip[5]
Make a clip containing frames 6 to 9 (unlike Trim, the end value of python slicing
is not inclusive)::
video = clip[6:10]
video = clip[::2]
video = clip[1::2]
video = clip[::-1]
It may all be combined at once to confuse people, just like normal Python slicing::
video = clip[-400:-800:-5]
clip = core.ffms2.Source("asdf.mov")
clip = clip.std.Trim(first=100, last=2000).std.FlipVertical()
clip = clip * 42
Note that multiplication by 0 is a special case that will repeat the clip up to the
maximum frame count.
::
args = { "lambda": 1 }
clip = core.plugin.Filter(clip, **args)
VapourSynth will also support the PEP8 convention of using a single trailing
underscore to prevent collisions with python keywords.
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.
Incorrect; Python will think "\\A" and "\\G" are supposed to mean
something special::
core.avs.LoadPlugin("B:\Avisynth plugins\GuavaComb.dll")
Correct; Python will think "\\\\" means something special, namely a
single backslash::
core.avs.LoadPlugin("B:\\Avisynth plugins\\GuavaComb.dll")
core.avs.LoadPlugin(r"B:\Avisynth plugins\GuavaComb.dll")
core.avs.LoadPlugin("B:/Avisynth plugins/GuavaComb.dll")
Output
######
The VideoFrame class simply contains one picture and all the metadata
associated with it. It is possible to access the raw data using ctypes and
some persistence. The three relevant functions are *get_read_ptr(plane)*,
*get_write_ptr(plane)*, and *get_stride(plane)*, all of which take the plane
to access as an argument. Accessing the data is a bit trickier as
*get_read_ptr()* and *get_write_ptr()* only return a pointer.
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::
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.
.. py:function:: set_message_handler(handler_func)
Sets a function to handle all debug output and fatal errors. The function should
have the form *handler(level, message)*,
where level corresponds to the vapoursynth.mt constants. Passing *None* restores
the default handler, which prints to stderr.
.. py:function:: get_outputs()
Get a previously set output node. Throws an error if the index hasn't been
set. Will return an AlphaOutputTuple when *alpha* was passed to
*VideoNode.set_output*.
.. py:function:: clear_outputs()
If *injected* is not None, the default of the first argument of the signature
will be replaced with the value supplied with injected.
.. py: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 *get_plugins()* to obtain a full list of all currently loaded plugins
you may call this way.
.. py:attribute:: 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.
.. py:attribute:: add_cache
Set the upper framebuffer cache size after which memory is aggressively
freed. The value is in megabytes.
.. py:method:: set_max_cache_size(mb)
.. py:method:: get_plugins()
.. py:method:: list_functions()
.. py:method:: get_format(id)
.. py:method:: version()
.. py:method:: version_number()
.. py: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.
.. py:attribute:: format
A Format object describing the frame data. If the format can change
between frames, this value is None.
.. py:attribute:: width
The width of the video. This value will be 0 if the width and height can
change between frames.
.. py:attribute:: height
The height of the video. This value will be 0 if the width and height can
change between frames.
.. py:attribute:: num_frames
.. py:attribute:: fps
.. py:attribute:: fps_num
The numerator of the framerate. If the clip has variable framerate, the
value will be 0.
.. py:attribute:: fps_den
The denominator of the framerate. If the clip has variable framerate, the
value will be 0.
.. py:attribute:: flags
Special flags set for this clip. This attribute should normally be
ignored.
.. py:method:: get_frame(n)
.. py:method:: get_frame_async(n)
First form of this method. It will call the callback from another thread as
soon as the frame is rendered.
*This method is intended for glue code. For normal use, use get_frame_async
instead.*
*This method is intended for glue code. For normal use, use get_frame_async
instead.*
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.
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.
.. py:method:: frames()
.. py:class:: AlphaOutputTuple
.. py:attribute:: clip
.. py:attribute:: alpha
.. py:class:: VideoFrame
This class represents a video frame and all metadata attached to it.
.. py:attribute:: format
.. py:attribute:: width
.. py:attribute:: height
.. py:attribute:: readonly
.. py:attribute:: props
This attribute holds all the frame's properties as a dict. They are also
mapped as sub-attributes for compatibility with older scripts.
.. py:method:: copy()
.. py:method:: get_read_ptr(plane)
Returns a pointer to the raw frame data. The data may not be modified.
.. py:method:: get_read_array(plane)
Returns a memoryview of the frame data that's only valid as long as the
VideoFrame object exists. The data may not be modified.
.. py:method:: get_write_ptr(plane)
Returns a pointer to the raw frame data. It may be modified using ctypes
or some other similar python package.
.. py:method:: get_write_array(plane)
Returns a memoryview of the frame data that's only valid as long as the
VideoFrame object exists.
.. py:method:: get_stride(plane)
.. py:class:: Format
.. py:attribute:: id
.. py:attribute:: color_family
.. py:attribute:: sample_type
.. py:attribute:: bits_per_sample
How many bits are used to store one sample in one plane.
.. py:attribute:: bytes_per_sample
.. py:attribute:: subsampling_w
The subsampling for the second and third plane in the horizontal
direction.
.. py:attribute:: subsampling_h
The subsampling for the second and third plane in the vertical direction.
.. py:attribute:: num_planes
.. py:class:: Plugin
.. py:attribute:: name
.. py:method:: get_functions()
Returns a dict containing all the functions in the plugin. You can access
it by calling *core.std.get_functions()*. Replace *std* with the namespace
of the plugin you want to query.
.. py:method:: list_functions()
Works similar to *get_functions()* but returns a human-readable string.
.. py:class:: Function
.. py:attribute:: name
The function name. Identical to the string used to register the function.
.. py:attribute:: plugin
.. py:attribute:: signature
Raw function signature string. Identical to the string used to register the
function.
.. py:class:: 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.
.. code::
env = get_current_environment()
# sometime later
with env.use():
# Do stuff inside this env.
.. warning::
.. code::
env = vpy_current_environment()
with env:
yield
.. py:function:: is_single()
.. py:attribute:: env_id
.. py:attribute:: single
See is_single()
.. py:attribute:: alive
.. py:method:: copy
Added: R50
.. py:method:: use
.. code::
env = vpy_current_environment()
with env.use():
with env.use():
pass
Added: R50
.. py:function:: vpy_current_environment()
.. py:function:: get_current_environment()
Added: R50
.. py:class:: EnvironmentPolicy
To use this class, first create a subclass and then use :func:`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!
Special considerations have been made to ensure the functions of class cannot be
abused. You cannot retrieve the current running policy youself.
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: R50
.. py:method:: 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.
.. py:method:: on_policy_cleared()
.. py:method:: get_current_environment()
.. py:method:: 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.
.. py:method:: is_alive(environment)
.. py:class:: EnvironmentPolicyAPI
Added: R50
.. py:method:: wrap_environment(environment)
.. warning::
.. py:method:: create_environment()
.. py:method:: unregister_policy()
.. py:function:: register_policy(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:
.. py:function:: has_policy()
Added: R50
.. py:attribute:: _using_vsscript
INTERNAL ATTRIBUTE. Deprecated (will be removed soon). This was the only way to
find out if VSScript.h was calling this script.
It now stores true if a custom policy is installed or VSScript.h is used.
Use :func:`has_policy` instead.
.. py: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.
Added: R50
.. py:class:: Func
.. py:exception:: Error
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::
RGB
YUV
GRAY
YCOCG
COMPAT
Format Constants
################
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::
GRAY8
GRAY16
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
RGB48
RGBH
RGBS
COMPATBGR32
COMPATYUY2
::
INTEGER
FLOAT