Internal functions

From Avisynth wiki
(Redirected from Import)
Jump to: navigation, search

In addition to internal filters AviSynth has a fairly large number of other (non-clip) internal functions.

The input or/and output of these functions are not clips, but some other variables which can be used in a script.

 

Contents

Boolean functions

These return true or false, if the condition that they test holds or not, respectively.
IsBool
IsBool(var)  
Tests if var is of the bool type. var can be any expression allowed by the AviSynth Syntax.

Examples:

b = false
IsBool(b) = true
IsBool(1 < 2 && 0 == 1) = true
IsBool(123) = false
IsClip
IsClip(var)  
Tests if var is of the clip type. var can be any expression allowed by the AviSynth Syntax.

Examples:

c = AviSource(...)
IsClip(c) = true
IsClip("c") = false
IsFloat
IsFloat(var)  
Tests if var is of the float type. var can be any expression allowed by the AviSynth Syntax.

Examples:

f = Sqrt(2)
IsFloat(f) = true
IsFloat(true) = false
IsFloat("42.") = false
IsFloat(2) = true   # ints are considered to be floats by this function
IsReallyFloat(2) = false # see below
As a workaround for the issue noted above, you may use the following user function:
## return true for floats only
function IsReallyFloat(val v)
{
    return (IsInt(v)==false) && IsFloat(v)
}
IsInt
IsInt(var)  
Tests if var is of the int type. var can be any expression allowed by the AviSynth Syntax.

Examples:

IsInt(2) = true
IsInt(2.1) = false
IsInt(true) = false
IsString
IsString(var)  
Tests if var is of the string type. var can be any expression allowed by the AviSynth Syntax.

Examples:

IsString("test") = true
IsString(2.3) = false
IsString(String(2.3)) = true
Exist
Exist(filename)  
Tests if the file specified by filename exists.

Examples:

filename = ...
clp = Exist(filename) 
\ ? AviSource(filename) 
\ : Assert(false, "file: " + filename + " does not exist")
Defined
Defined(var)  
Tests if var is defined. Can be used inside Script_functions to test if an optional argument has been given an explicit value.
More formally, the function returns false if its argument (normally a function argument or variable) has the void ('undefined') type, otherwise it returns true.

Examples:

b_arg_supplied = Defined(arg)
myvar = b_arg_supplied ? ... : ...
FunctionExists
FunctionExists(name)   AVS+
Tests if the function or filter name is defined in the script.
name can be any string – it does not need to be a legal name.
Example – see Apply below
InternalFunctionExists
InternalFunctionExists(name)   AVS+
Tests if the function, filter or property name is defined natively within AviSynth+.
VarExist
VarExist(name)   AVS+
Tests if the variable exists or not. Note: if variable exists, it returns true regardless of the "defined" state of the variable

Control functions

These facilitate flow of control (loading of scripts, arguments checks, global settings adjustment, etc.).
Apply
Apply(string func_string [, arg1 [, arg2 [, ... [, argn]]]] )  
Calls the function or filter func_string with arguments arg1, arg2, ..., argn (as many as supplied).
  • This provides a way to call a function or filter by name, with arguments.
  • Apply("f", x) is equivalent to f(x)
  • Apply("f", x) is equivalent to Eval("f(" + String(x) + ")")
  • Note that the clip argument must be supplied explicitly - the special variable Last is not used.

Examples:

## Building an expression dynamically  
new_width = 352
new_height = 288

Apply("BicubicResize", Last, new_width, new_height)
# Note that the clip argument must be supplied - 'Last' is not implicitly assumed

## the same action, using Eval
Eval( "BicubicResize(" + String(new_width) + "," + String(new_height) + ")" )
## using a filter only if it exists (AviSynth 2.6)
function MyFilter(clip C, string s) { 
    return C.Subtitle("MyFilter: "+s, align=5)
}
ColorBars 
try {
    Apply("MyFilter", Last, "TEST")
} catch (err_msg) {
    # (ignore)
}
return Last
## using a filter only if it exists (AVS+ only)
ColorBars  
return FunctionExists("MyFilter") 
\ ? Apply("MyFilter", Last, "TEST") 
\ : Last 
Eval
Eval(expression [, string name])  
Evaluates an arbitrary expression and returns the result of that evaluation. It works exactly like Import below, except
  • The expression to be evaluated comes from a string instead of a file;
  • The values of ScriptName, ScriptFile and ScriptDir are not changed;
  • The current working directory (CWD) is not changed.
Argument name will be shown in the error message beside the script name. Both will be followed with the line number in expression where the error occurred.
Variables in your calling script are available within expression; global variables are not required.
Note Eval can return the result of any valid expression; usually a clip, but also a string, boolean etc.
You can use Eval to construct and evaluate expressions dynamically inside your scripts, based on variable input data.
Eval is useful as a control structure for creating multi-line block statements without requiring AviSynth+.
Eval can be used to put aside the need to install external plugins if they are not actually used.

Examples:

## Building an expression dynamically 
## calls BicubicResize(last, 352, 288)
settings = "352, 288"
Eval( "BicubicResize(" + settings + ")" )
## if...else control structure
option = true
option  
\ ? Eval("""
    Levels(0, 1.2, 255, 20, 235)
    Spline36Resize(720, 400)
    Sharpen(0.2)
""") 
\ : Eval("""
    BicubicResize(720, 400)
    Sharpen(0.3)
""")
## using a filter only if it is needed; 
## in this example, SMDegrain only needs to be installed if the option is true.
option = false
option 
\ ? Eval("""
    SMDegrain(tr=2, thSAD=250, contrasharp=true, refinemotion=true, lsb=true)
""")
\ : Last 
## accessing script variables
ColorBars
A=Subtitle("A", align=5)
Eval("A")
return Last ## returns clip 'A'
## setting script variables
ColorBars
A=Subtitle("A", align=5)
Eval("B = A.Invert")
return B ## returns clip 'A' with colors inverted
## Increment a global variable, based on a local variable
Eval("global my_counter = my_counter + " + String(increment)) 
## multi-line example with comment and line continuation
Eval("""
ColorBars
BicubicResize(352, 288)
#FlipVertical
Subtitle(
\   "Width  = "  + String(Width) + "\n"
\ + "Height = " + String(Height)
\ , align=7, lsp=0)
""")
## Empty expression 
## results in error: 'Defined(u) == false'
u = Eval("#")   
## Error reporting
ColorBars
A=Subtitle("A", size=Height, align=2)
Eval("""
A
foo("bar") ## ERROR!
""", "eval_test_1") ## name for error reporting purposes
return Last

results in the error message:
Script error: there is no function named "foo"
(eval_test_1, line 3)
(E:\_test.avs, line 6)
Import
Import(filename)  
Import(filename [, ...] [, bool utf8])   AVS+
Evaluates the contents of another script and returns the result of that evaluation. It works exactly like Eval above, except
  • The expression to be evaluated comes from a file instead of a string;
  • The values of ScriptName, ScriptFile and ScriptDir are set to the current (imported) script;
  • The current working directory (CWD) is set to the current (imported) script.
  • utf8 AVS+ if true, assumes filename(s) are UTF8, else (default), assume ANSI.
Functions, variables and loaded plugins declared inside the imported script are made available to the parent script. Import's return value can be assigned to a variable of the parent script; this is most useful when the imported script ends with a clip.
Typically Import is used to make library functions available to the parent script, and the return value is not used. However this is simply a convention; it is not enforced by the AviSynth Syntax. Some indicative uses of Import include:
  • Storing multiple script-functions, variables and global variables for reuse by scripts (creation of script libraries).
  • Retrieving pre-built streams.
  • Retrieving dynamically configured pre-built streams (the core idea is that the importing script declares some global variables which the imported script uses to configure the stream that will return).
Note 1: Since the contents of the imported script are evaluated at the point of invocation, it is possible by enclosing the Import call in a nested scope (for example inside a function) to make available to the importing script the functions and globals of the imported script without its script-level variables.
Note 2: Any script with the AVSI extension in the AviSynth Plugins folder is automatically imported. This is useful for making script functions available to any new script you create without having to copy and paste.

Examples:

# B.avsi
A.Invert
ColorBars
A=Subtitle("A", align=5) ## create clip 'A'
Import("B.avsi")
return Last ## returns clip 'A' with colors inverted
## here we do not care about the return value (mylib.avsi contains only functions)
Import("mylib.avsi")  
...
## mysources.avsi loads predetermined file names from a folder into globals
okflag = Import("mysources.avsi")  
source = okflag ? global1 + global2 + global3 : BlankClip()
Select
Select(index, item0 [, item1 [, ...[, itemn]]])  
Returns the item selected by the index argument, which must be of int type (0 returns item0, 1 returns item1, ..., etc). Items can be any script variable or expression of any type and can even be mixed.
If index is out of range, an error is raised.

Examples:

# select a clip-brush from a set of presets
idx = 2
brush = Select(idx, AviSource("round.avi"), 
\        rectangle, diagonal, diagonal.FlipHorizontal)

Note - all branches are evaluated:

index=1
Select(index, "zero", "one", "two", 
\        Assert(false, "Select evaluates all branches")) 
## NOTE this code does not run - it throws Assert error
## because Select evaluates all branches

If this is not desired, use the conditional execution operator:

index=1
x = (index==0) ? "zero"
\ : (index==1) ? "one"
\ : (index==2) ? "two"
\ : Assert(false, "index out of range")
Default
Default(x, d)  
Returns x if Defined(x) is true, d otherwise. x must either be a function's argument or an already declared script variable (ie a variable which has been assigned a value) else an error will occur.

Examples:

function myfunc(clip c, ..., int "strength") {
    ...
    strength = Default(strength, 4) # if not supplied make it 4
    ...
}
Assert
Assert(condition [, err_msg])  
Does nothing if condition is true; throws an error, immediately terminating script execution, if condition is false. In the later case err_msg, if supplied, is presented to the user through a dialog box; else the standard message "Assert: assertion failed" shows up.

Examples:

function myfunc(clip c, ..., int "strength") {
    ...
    strength = Default(strength, 4) # if not supplied make it 4
    Assert(strength > 0, "'strength' must be positive")
    ...
}
NOP
NOP()  
This is a no-operation function provided mainly for conditional execution with non-return value items such as Import, when no "else" condition is desired. That is, use it whenever the AviSynth Syntax requires an operation (such as with the ?: operator) but your script does not need one.
Return value: 0 (int type).

Examples:

preset = want_presets ? AviSource("c:\presets\any.avi") : NOP
... 
loadlib ? Import("my_useful_functions.avs") : NOP
Undefined
Undefined()   v2.60
Returns the undefined state.
It's the state for which Defined() returns false.

Examples:

x = Undefined()
Defined(x) # == false


Global Options

SetMemoryMax
SetMemoryMax(amount)  
Sets the maximum memory that AviSynth uses (in MB) to the value of amount. Setting to zero just returns the current Memory Max value. In the 2.5 series the default Memory Max value is 25% of the free physical memory, with a minimum of 16MB.
The default Memory Max is also limited to 512MB.
AVS+In Avisynth+ this limit for default Memory Max is 1024MB for 32 bits and 4096MB on the x64 version
DefaultMemoryMax = minimum(physical_memory / 4, secondary_memory_max_limit)
for classic Avisynth see the table below
Free memory <64 128 256 512 1024 2048 3072
Default Max 16 32 64 192 448 512 512
In some versions there is a default setting of 5MB, which is quite low. If you encounter problems (e.g. low speed) try to set this values to at least 32MB. Too high values can result in crashes because of 2GB address space limit.
Return value: Actual MemoryMax value set.

Examples:

SetMemoryMax(128)
AVS+SetMemoryMax(int, int “type”, int “index”)
With additional arguments for devices such as GPUs. Memory usage is managed individually for devices such as GPUs.


int   =
Device (including CPU) memory limit (MB)
int  type =
Device type. The following values ​​are available:
DEV_TYPE_CPU: CPU (default)
DEV_TYPE_CUDA: GPU
int  index =
Device number. Same as onCUDA device_index. Only 0 for DEV_TYPE_CPU.
Default value: 0


SetCacheMode
SetCacheMode(mode)  
AVS+Fine tunes the internal frame caching strategy in AviSynth+.
Available values:
  • 0 or CACHE_FAST_START start up time and size balanced mode (default)
  • 1 or CACHE_OPTIMAL_SIZE slow start up but optimal speed and cache size
  • since Avisynth+ 3.6.1
SetMaxCPU
SetMaxCPU([string feature1, string feature2, ...])  
AVS+Limits the CPU capabilities which AviSynth reports to its core and external plugins through GetCPUFlags.
Available values:
  • "" or "none" for zero SIMD support, no processor flags are reported
  • "mmx", "sse", "sse2", "sse3", "ssse3", "sse4" or "sse4.1", "sse4.2", "avx, "avx2"
Parameters are case insensitive.
Note: "avx2" triggers FMA3 flag as well.
  • Processor options w/o any modifier will limit the CPU flag report to at most the processor level.
  • When "feature" is ended by '+', relevant processor feature flag will be switched on
  • When "feature" is ended by '-', relevant processor feature flag will be removed.
Multiple options can be put in a comma separated list. They will evaluate in that order.

Examples:

SetMaxCPU("SSE2") #reports at most SSE2 processor (even if AVX2 is available)
SetMaxCPU("avx,sse4.1-") #limits to avx2 but explicitely removes reporting sse4.1 support
SetMaxCPU("none,avx2+") #limits to plain C, then switches on AVX2-only support
  • since Avisynth+ 3.6
SetWorkingDir
SetWorkingDir(path)  
Sets the default directory for AviSynth to the path argument.
This is primarily for easy loading of source clips, importing scripts, etc. It does not affect plugins' autoloading.
Return value is 0 if successful, -1 otherwise.

Examples:

SetWorkingDir("c:\my_presets")
AviSource("border_mask.avi")  # this loads c:\my_presets\border_mask.avi
SetPlanarLegacyAlignment
SetPlanarLegacyAlignment(mode)  
Set alignment mode for planar frames. mode can either be true or false.
Some older plugins illegally assume the layout of video frames in memory. This special filter forces the memory layout of planar frames to be compatible with prior versions of AviSynth. The filter works on the GetFrame() call stack, so it effects filters before it in the script.

Examples:

Example : Using an older version of Mpeg2Source() (1.10 or older):

LoadPlugin("...\Mpeg2Decode.dll")
Mpeg2Source("test.d2v")         # A plugin that illegally assumes the layout of memory
SetPlanarLegacyAlignment(true)  # Set legacy memory alignment for prior statements
ConvertToYUY2()     # Statements through to the end of the script have
...                             # advanced memory alignment.
OPT_AllowFloatAudio
global OPT_AllowFloatAudio = true ## default false  
Float audio is converted to 16 bit when frameserving through ACM, unless OPT_AllowFloatAudio is set to true (this option enables WAVE_FORMAT_IEEE_FLOAT audio output[1]). In that case the audio is kept as it is. When accessing AviSynth directly (like MeGUI, BeHappy or ffmpeg do for example), there is no automatic conversion.
The automatic conversion is done for clients that cannot handle Float audio (in the old days most of them couldn't). Note conversion takes place after the script processing is finished. Float audio is always allowed within the script.
OPT_UseWaveExtensible
global OPT_UseWaveExtensible = true ## default false  
This option enables WAVE_FORMAT_EXTENSIBLE audio output. The default is WAVE_FORMAT_EX.
Note: The default DirectShow component for .AVS files, "AVI/WAV File Source", does not correctly implement WAVE_FORMAT_EXTENSIBLE processing, so many application may not be able to detect the audio track. There are third party DirectShow readers that do work correctly. Intermediate work files written using the AVIFile interface for later DirectShow processing will work correctly if they use the DirectShow "File Source (async)" component or equivalent.
OPT_dwChannelMask
global OPT_dwChannelMask(int v)   v2.60
This option enables you to set ChannelMask. It overrides WAVEFORMATEXTENSIBLE.dwChannelMask[[2] which is set according to this table
0x00004, // 1   -- -- Cf
0x00003, // 2   Lf Rf
0x00007, // 3   Lf Rf Cf
0x00033, // 4   Lf Rf -- -- Lr Rr
0x00037, // 5   Lf Rf Cf -- Lr Rr
0x0003F, // 5.1 Lf Rf Cf Sw Lr Rr
0x0013F, // 6.1 Lf Rf Cf Sw Lr Rr -- -- Cr
0x0063F, // 7.1 Lf Rf Cf Sw Lr Rr -- -- -- Ls Rs
OPT_AVIPadScanlines
global OPT_AVIPadScanlines = true ## default false   v2.60
This option enables DWORD aligned planar padding. Default is packed aligned planar padding. See memory alignment used in the AVIFile output emulation.
OPT_VDubPlanarHack
global OPT_VDubPlanarHack = true ## default false   v2.60
This option enables flipped YV24 and YV16 chroma planes. This is an hack for early versions of Virtualdub with YV24/YV16 support.
OPT_Enable_V210
global OPT_Enable_V210 = true ## default false   AVS+
For 10bit YUV422, Frameserve interleaved V210 instead of planar P210. (VfW)

§ VfW here means Video For Windows clients such as VirtualDub are affected, but not other clients such as ffmpeg.

OPT_Enable_Y3_10_10
global OPT_Enable_Y3_10_10 = true ## default false   AVS+
For 10bit YUV422, set the FourCC to Y3[10][10] ('Y', '3', 10, 10) instead of P210 ('P', '2', '1', '0'). (VfW)
OPT_Enable_Y3_10_16
global OPT_Enable_Y3_10_16 = true ## default false   AVS+
For 16bit YUV422, use Y3[10][16] instead of P216 (VfW)
OPT_Enable_b64a
global OPT_Enable_b64a = true ## default false   AVS+
Use b64a instead of BRA[64] (VfW)
works for avs+ version above r2636
OPT_Enable_PlanarToPackedRGB
global OPT_Enable_PlanarToPackedRGB = true ## default false   AVS+
Convert Planar RGB to packed RGB (VfW)
Planar RGB 8, 10, 12, 14 and 16 bits are reported as G3[0][8], G3[0][10], G3[0][12], G3[0][14] and G3[0][16]
Planar RGBA 8, 10, 12, 14 and 16 bits are reported as G4[0][8], G4[0][10], G4[0][12], G4[0][14] and G4[0][16]
When these FourCC codes are not handled through VfW, use OPT_Enable_PlanarToPackedRGB=true.
Avisynth+ will convert the clip from planar to RGB64 (packed 16bit RGB) and will negotiate this format instead

Conversion functions

These convert between different types.
Value
Value(string)  
Converts a decimal string to its associated numeric value.

Examples:

Value ("-2.7") = -2.7
HexValue
HexValue(string)  
HexValue(string [, int pos])   AVS+
Converts a hexadecimal string to its associated numeric value.
  • pos sets the starting point of the numeric parser. All characters to the left of pos are ignored. Default is 1 (start of string).

Examples:

HexValue ("FF00") = 65280
Hex
Hex(int)   v2.60
Hex(int [, int width])   AVS+
Converts a numerical value to its hexadecimal value. See Colors for more information on specifying colors.
  • width sets the minimum width of the returned string.
Resulting string will be left-padded with zeroes as needed. Allowed range is 0..8; default is 0.

Examples:

Hex (10824234) = "A52A2A"
Hex (15 width=2) = "0F"
String
String(var [, string format_string])  
Converts a variable to a string. String arguments are passed along unchanged; bools are converted to "true" or "false"; numbers are formatted as described below; other variable types (clip, val) are converted to the empty string.
The syntax of format_string is as follows:
%[flags][width][.precision]f    the leading '%' and trailing 'f' are required.
The parts of format_string are:
flags
- left align (right align by default)
+ always print the +/- sign (show only '+' by default)
0 pad (see width) with leading zeroes (pad with spaces by default) 
 ' print a blank instead of a '+'
# always print the decimal point (dropped by default if there are no decimal digits) 
width
the minimum width (the string is never truncated if it is wider than width)
precision
the number of decimal digits
You can also put arbitrary text around format_string, similar to the C-language sprintf function.

Examples:

Subtitle( String(1.23) )                    # '1.230000' (six decimals by default for floats)
Subtitle( String(123) )                     # '123'      (no decimals by default for ints)

Subtitle( String(1.23, "%0.2f" ))           # '1.23'
Subtitle( String(1.23, "%0.1f" ))           # '1.2'
Subtitle( String(1.23, "%5.1f") )           # '  1.2'    (padded to 5 characters wide)
Subtitle( String(1.23, "%1.3f") )           # '1.230'    (3 decimals; add trailing zeroes)

Subtitle( String(123, "%0.0f") )            # '123'      (no decimals for precision=0)
Subtitle( String(123, "%#0.0f") )           # '123.'     ('#' flag: always show decimal point)
Subtitle( String(123, "%0.2f") )            # '123.00'   (2 decimals: add trailing zeroes)
Subtitle( String(123, "%5.0f") )            # '  123'    (padded to 5 characters wide using ' ')
Subtitle( String(123, "%05.0f") )           # '00123'    (padded to 5 characters wide using '0')

Subtitle( String(PI, "PI=%0.0f") )          # 'PI=3'     (text around format_string)
Subtitle( String(PI, "PI=%#0.0f") )         # 'PI=3.'    ('#' flag: always show decimal point)
Subtitle( String(PI, "PI=%2.0f") )          # 'PI= 3'
Subtitle( String(PI, "PI=%3.2f") )          # 'PI=3.14'
Subtitle( String(PI, "PI=%0.5f") )          # 'PI=3.14159'
Subtitle( String(PI, "PI=%6.3f") )          # 'PI= 3.142'

Subtitle( String(32, "%0.0f") )             # '32'
Subtitle( String(32, "%3.0f") )             # ' 32'
Subtitle( String(32, "%8.0f") )             # '      32'

## arbitrary text around format_string:
Subtitle( String(Last.Height, "Clip height is %0.0f") ) # 'Clip height is 480'
## same output as above but using string concatenation:
Subtitle( "Clip height is " + String(Last.Height) )


Numeric functions

These provide common mathematical operations on numeric variables.
Max
Max(float, float [, ...])  
Returns the maximum value of a set of numbers.
If all the values are of type Int, the result is an Int. If any of the values are of type Float, the result is a Float.
This may cause an unexpected result when an Int value greater than 16777216 is mixed with Float values.

Examples:

Max (1, 2) = 2
Max (5, 3.0, 2) = 5.0
Min
Min(float, float [, ...])  
Returns the minimum value of a set of numbers.

Examples:

Min (1, 2) = 1
Min (5, 3.0, 2) = 2.0
MulDiv
MulDiv(int, int, int)  
Multiplies two ints (m, n) and divides the product by a third (d) in a single operation, with 64 bit intermediate result. The actual equation used is (m * n + d / 2) / d .

Examples:

MulDiv (1, 1, 2) = 1
MulDiv (2, 3, 2) = 3
Floor
Floor(float)  
Converts from single-precision, floating-point value to int (round down on any fractional amount).

Examples:

Floor(1.2) = 1
Floor(1.6) = 1
Floor(-1.2) = -2
Floor(-1.6) = -2
Ceil
Ceil(float)  
Converts from single-precision, floating-point value to int (round up on any fractional amount).

Examples:

Ceil(1.2) = 2
Ceil(1.6) = 2
Ceil(-1.2) = -1
Ceil(-1.6) = -1
Round
Round(float)  
Converts from single-precision, floating-point value to int (round off to nearest integer).

Examples:

Round(1.2) = 1
Round(1.6) = 2
Round(-1.2) = -1
Round(-1.6) = -2
Int
Int(float)  
Converts from single-precision, floating-point value to int (round towards zero).

Examples:

Int(1.2) = 1
Int(1.6) = 1
Int(-1.2) = -1
Int(-1.6) = -1
Float
Float(int)  
Converts int to single-precision, floating-point value. Integer values that require more than 24-bits to be represented will have their lower 8-bits truncated yielding unexpected values.

Examples:

Float(4) = 4.0
Float(4) / 3 = 1.333 (while 4 / 3 = 1 , due to integer division)
Float(123456789) = 123456792.0 (error = -3, 0.000002%)
Float(1234567890) = 1234567936.0 (error = -46, 0.000004%)
Fmod
Fmod(float, float)   v2.60
Returns the modulo of the argument. Output is float.

Examples:

Fmod(3.5, 0.5) = 0 (since 3.5 - 7*0.5 = 0)
Fmod(3.5, 1.0) = 0.5 (since 3.5 - 3*1.0 = 0.5)
Pi
Pi()  
Returns the value of the π constant (the ratio of a circle's circumference to its diameter).

Examples:

d = Pi()    # d == 3.141592653
Exp
Exp(float)  
Returns the natural (base-e) exponent of the argument.

Examples:

Exp(1) = 2.7182818
Exp(0) = 1.0
Log
Log(float)  
Returns the natural (base-e) logarithm of the argument.

Examples:

Log(1) = 0.0
Log(10) = 2.30259
Log(Exp(1)) = 1.0
Log10
Log10(float)   v2.60
Returns the common logarithm of the argument.

Examples:

Log10(1.0) = 0
Log10(10.0) = 1.0
Log10(2.0) = 0.3010299957
Pow
Pow(float base, float power)  
Returns base raised to a power.

Examples:

Pow(2, 3) = 8
Pow(3, 2) = 9
Pow(3.45, 1.75) = 8.7334
Sqrt
Sqrt(float)  
Returns the square root of the argument.

Examples:

Sqrt(1) = 1.0
Sqrt(2) = 1.4142
Abs
Abs(float or int)  
Returns the absolute value of its argument (returns float for float, integer for integer).

Examples:

Abs(-3.8) = 3.8
Abs(-4) = 4
Sign
Sign(float)  
Returns the sign of the value passed as argument (1, 0 or -1).

Examples:

Sign(-3.5) = -1
Sign(3.5) = 1
Sign(0) = 0
Frac
Frac(float)  
Returns the fractional portion of the value provided.

Examples:

Frac(3.7) = 0.7
Frac(-1.8) = -0.8
Rand
Rand([int max] [, bool scale] [, bool seed])  
Returns a random integer value. All parameters are optional.
max
sets the maximum value+1 (default 32768) and can be set negative for negative results. It operates either in scaled or modulus mode (default scale=true only if Abs(max) > 32768, false otherwise).
scale
When true, scales the internal random number generator value to the maximum value, while modulus mode (scale=false) uses the remainder from an integer divide of the random generator value by the maximum. Modulus mode is recommended for smaller maximums.
seed
When true, seeds the random number generator with the current time. seed defaults to false and probably isn't necessary, although it's there just in case.
Typically, this function would be used with the Select function for random clips.

Examples:

Select(Rand(5), clip1, clip2, clip3, clip4, clip5)
Spline
Spline(float X, x1, y1, x2, y2, .... [, bool cubic])  
Interpolates the Y value at point X using the control points x1/y1, ... There have to be at least 2 x/y-pairs. The interpolation can be cubic (the result is a spline) or linear (the result is a polygon). Default is cubic.

Examples:

Spline(5, 0, 0, 10, 10, 20, 0, false) = 5
Spline(5, 0, 0, 10, 10, 20, 0, true) = 7
Continued Numerator, Denominator
ContinuedNumerator(float, int limit)   v2.60
ContinuedNumerator(int, int, int limit)   v2.60
ContinuedDenominator(float, int limit)   v2.60
ContinuedDenominator(int, int, int limit)   v2.60
The rational pair (ContinuedNumerator, ContinuedDenominator) returned has the smallest possible denominator such that the absolute error is less than 1/limit. More information can be found on wikipedia.
If limit is not specified in the Float case the rational pair returned is to the limit of the single precision floating point value. Thus (float)((double)Num/(double)Den) == V.
In the Int case if limit is not specified then the normalized original values will be returned, i.e. reduced by the GCD (greatest common divisor).

Examples:

ContinuedNumerator(PI(), limit=5000]) = 355
ContinuedDenominator(PI(), limit=5000) = 113

ContinuedNumerator(PI(), limit=50]) = 22
ContinuedDenominator(PI(), limit=50) = 7

ContinuedNumerator(355, 113, limit=50]) = 22
ContinuedDenominator(355, 113, limit=50) = 7


Trigonometry functions

relationships involving lengths and angles of triangles.
Sin
Sin(float)  
Returns the sine of the argument (assumes it is radians).

Examples:

Sin(Pi()/4) = 0.707
Sin(Pi()/2) = 1.0
Cos
Cos(float)  
Returns the cosine of the argument (assumes it is radians).

Examples:

Cos(Pi()/4) = 0.707
Cos(Pi()/2) = 0.0
Tan
Tan(float)   v2.60
Returns the tangent of the argument (assumes it is radians).

Examples:

Tan(Pi/4) = 1.0
Tan(Pi/2) = not defined
32 bit IEEE floats do not have sufficient resolution to exactly represent
pi/2 so AviSynth returns a large positive number for the value slightly less
than pi/2 and a large negative value for the next possible value which is
slightly greater than pi/2.
Asin
Asin(float)   v2.60
Returns the inverse of the sine of the argument (output is radians).

Examples:

Asin(0.707) = 0.7852471634 (~ Pi/4)
Asin(1.0) = 1.570796327 (~ Pi/2)
Acos
Acos(float)   v2.60
Returns the inverse of the cosine of the argument (output is in radians).

Examples:

Acos(0.707) = 0.7852471634 (~ Pi/4)
Acos(0.0) = 1.570796327 (~ Pi/2)
Atan
Atan(float)   v2.60
Returns the inverse of the tangent of the argument (output is in radians).

Examples:

Atan(0.707) = 0.6154085176
Atan(1.0) = 0.7853981634 (~ Pi/4)
Atan2
Atan2(float, float)   v2.60
Returns the angle between the positive x-axis of a plane and the point given by the coordinates (x, y) on it. Output is in radians. See wikipedia for more information.
y is the first argument and x is the second argument.

Examples:

Atan2(1.0, 0) = 1.570796327 (~ Pi/2)
Atan2(1.0, 1.0) = 0.7852471634 (~ Pi/4)
Atan2(-1.0, -1.0) = -2.356194490 (~ -3Pi/4)
Sinh
Sinh(float)   v2.60
Returns the hyperbolic sine of the argument. See wikipedia for more information.

Examples:

Sinh(2.0) = 3.626860408
Cosh
Cosh(float)   v2.60
Returns the hyperbolic cosine of the argument.

Examples:

Cosh(2.0) = 3.762195691
Tanh
Tanh(float)   v2.60
Returns the hyperbolic tangent of the argument.

Examples:

Tanh(2.0) = 0.9640275801


Bit functions

The functions are bitwise operators. They manipulate individual bits within integer variables. This means that their arguments (being integers) are converted to binary numbers, the operation is performed on their bits, and the resulting binary number is converted back again.
BitAnd
BitAnd(int, int)   v2.60
Returns the bitwise AND (sets bit to 1 if both bits are 1 and sets bit to 0 otherwise).

Examples:

BitAnd(5, 6) = 4 # since 5 = 101, 6 = 110, and 101&110 = 100
BitNot
BitNot(int)   v2.60
Returns the bit-inversion (sets bit to 1 if bit is 0 and vice-versa).

Examples:

BitNOT(5) = -6 
# since  5 = 101,  
# and ~101 = 1111 1111 1111 1111 1111 1111 1111 1010 = -6
Note: 1111 1111 1111 1111 1111 1111 1111 1010
= (2^32-1)-2^0-2^2 = 2^32-(1+2^0+2^2)
= (signed) -(1+2^0+2^2) = -6
BitOr
BitOr(int, int)   v2.60
Returns the bitwise inclusive OR (sets bit to 1 if one of the bits (or both) is 1 and sets bit to 0 otherwise).

Examples:

BitOr(5, 6) = 7 # since 5 = 101, 6 = 110, and 101|110 = 111
BitOr(4, 2) = 6 # since 4 = 100, 2 = 010, and 100|010 = 110
BitXor
BitXor(int, int)   v2.60
Returns the bitwise exclusive OR (sets bit to 1 if exactly one of the bits is 1 and sets bit to 0 otherwise).

Examples:

BitXor(5, 6) = 3 # since 5 = 101, 6 = 110, and 101^110 = 011
BitXor(4, 2) = 6 # since 4 = 100, 2 = 010, and 100^010 = 110
Bit shift left
BitLShift(int, int)   v2.60
BitShl(int, int)   v2.60
BitSal(int, int)   v2.60
Shift the bits of a number to the left.

Examples:

Shifts the bits of the number 5 two bits to the left:
BitLShift(5, 2) = 20 (since 101 << 2 = 10100)
Bit shift right
BitRShiftA(int, int)   v2.60
BitRShiftS(int, int)   v2.60
BitSar(int, int)   v2.60
Shift the bits of an integer to the right. (Arithmetic, Sign bit fill, Right Shift)

Examples:

Shifts the bits of the number -42 one bit to the right, treating it as signed:
BitRShiftA(-42, 1) = -21 
# (since 1111 1111 1111 1111 1111 1111 1101 0110 >> 1  
#      = 1111 1111 1111 1111 1111 1111 1110 1011)
Bit shift right, unsigned
BitRShiftL(int, int)   v2.60
BitRShiftU(int, int)   v2.60
BitShr(int, int)   v2.60
Shift the bits of an unsigned integer to the right. (Logical, zero fill, Right Shift)

Examples:

Shifts the bits of the number -42 one bit to the right, treating it as unsigned:
BitRShiftL(-42, 1) = 2147483627 
# (since 1111 1111 1111 1111 1111 1111 1101 0110 >> 1 
#      = 0111 1111 1111 1111 1111 1111 1110 1011)
Note: -42 = -(1+2^0+2^3+2^5) = (unsigned) (2^32-1)-(2^0+2^3+2^5) =
1111 1111 1111 1111 1111 1111 1101 0110
Bit rotate left
BitLRotate(int, int)   v2.60
BitRol(int, int)   v2.60
Rotates the bits of an integer to the left by the number of bits specified in the second operand. For each rotation specified, the high order bit that exits from the left of the operand returns at the right to become the new low order bit.

Examples:

Rotates the bits of the number -2147483642 one bit to the left:
BitLRotate(-2147483642, 1) = 13 
# (since 10000000000000000000000000000110 ROL 1
#      = 00000000000000000000000000001101)
Bit rotate right
BitRRotateL(int, int)   v2.60
BitRor(int, int)   v2.60
Rotates the bits of an integer to the right by the number of bits specified in the second operand. For each rotation specified, the low order bit that exits from the right of the operand returns at the left to become the new high order bit.

Examples:

Rotates the bits of the number 13 one bit to the right:
BitRRotate(13, 1) = -2147483642 
# (since 00000000000000000000000000001101 ROR 1 
#      = 10000000000000000000000000000110)
Bit test
BitTest(int, int)   v2.60
BitTst(int, int)   v2.60
Tests a single bit (that is, it returns true if its state is one, else it returns false). The second operand denotes the location of the bit which is specified as an offset from the low order end of the operand (starting at zero).

Examples:

Check the state of the fourth bit:
BitTest(3, 4) = False
BitTest(19, 4) = True

Check the state of the sign bit:
BitTest(-1, 31) = True
BitTest(2147483647, 31) = False
BitSet
BitSet(int, int)   v2.60
Sets a single bit to one (so it sets its state to one). The second operand denotes the location of the bit which is specified as an offset from the low order end of the operand (starting at zero).

Examples:

Set the state of the fourth bit to one:
BitSet(3, 4) = 19
BitSet(19, 4) = 19

Set the state of the sign bit to one:
BitSet(-1, 31) = -1
BitSet(2147483647, 31) = -1
BitSetCount
BitSetCount(int [, int...])   AVS+
Returns the total number of set bits in all supplied integer arguments.
Bit clear
BitClear(int, int)   v2.60
BitClr(int, int)   v2.60
Sets a single bit to zero (so it sets its state to zero). The second operand denotes the location of the bit which is specified as an offset from the low order end of the operand (starting at zero).

Examples:

Clear the bits of the number 5
BitClear(5, 0) = 4 (first bit is set to zero)
BitClear(5, 1) = 5 (second bit is already zero)
BitClear(5, 2) = 1 (third bit is set to zero)
BitClear(5, 3) = 5 (fourth bit is already zero)

Clear the state of the sign bit:
BitClear(-1, 31) = 2147483647
Bit change
BitChange(int, int)   v2.60
BitChg(int, int)   v2.60
Sets a single bit to its complement (so it changes the state of a single bit; 1 becomes 0 and vice versa). The second operand denotes the location of the bit which is specified as an offset from the low order end of the operand (starting at zero). The sign bit is bit 31.

Examples:

Change the state of the a bit of the number 5:
BitChange(5, 0) = 4 (first bit is set to zero)
BitChange(5, 1) = 7 (second bit is set to one)
BitChange(5, 2) = 1 (third bit is set to zero)
BitChange(5, 3) = 13 (fourth bit is set to one)

Change the state of the sign bit:
BitChange(-1, 31) = 2147483647


Runtime functions

These are internal functions which are evaluated at every frame. They can be used inside the scripts passed to runtime filters (ConditionalFilter, ScriptClip, FrameEvaluate) to return information for a frame.
Average
AverageLuma(clip [, int offset = 0])  
AverageChromaU(clip [, int offset = 0])  
AverageChromaV(clip [, int offset = 0])  
AverageB(clip [, int offset = 0])   AVS+
AverageG(clip [, int offset = 0])   AVS+
AverageR(clip [, int offset = 0])   AVS+
This group of functions return a float value with the average pixel value of a plane (Luma, U-chroma and V-chroma, respectively). They require an ISSE capable cpu. In v2.61 an offset argument is added which enables you to access other frames than the current one.

Examples:

ScriptClip(Last, """
    threshold = 55
    luma = AverageLuma ## gives the average luma of the current frame
    #luma = AverageLuma(1) ## gives the average luma of the next frame
    luma < threshold 
    \ ? Levels(0, 1.0+0.5*(threshold-luma)/threshold, 255, 0, 255) 
    \ : last
    Subtitle("luma=" + String(luma), align=2)
""")
Difference
LumaDifference(clip1, clip2)  
ChromaUDifference(clip1, clip2)  
ChromaVDifference(clip1, clip2)  
RGBDifference(clip1, clip2)  
BDifference(clip1, clip2)   AVS+
GDifference(clip1, clip2)   AVS+
RDifference(clip1, clip2)   AVS+
This group of functions return a float value between 0 and 255 of the absolute difference between two planes from two different clips – either the combined RGB difference or the Luma, U-chroma or V-chroma differences, respectively. They require an ISSE capable cpu.

Examples:

ovl = Overlay(last, mov_star, x=some_xvalue, y=some_yvalue, mask=mov_mask)
ldif = LumaDifference(ovl) # implicit last for clip1
udif = ChromaUDifference(Tweak(hue=24), ovl)
...
Difference from previous
YDifferenceFromPrevious(clip)  
UDifferenceFromPrevious(clip)  
VDifferenceFromPrevious(clip)  
RGBDifferenceFromPrevious(clip)  
BDifferenceFromPrevious(clip)   AVS+
GDifferenceFromPrevious(clip)   AVS+
RDifferenceFromPrevious(clip)   AVS+
This group of functions return the absolute difference of pixel value between the current and previous frame of clip – either the combined RGB difference or the Luma, U-chroma or V-chroma differences, respectively.

Examples:

scene_change = (YDifferenceFromPrevious) > threshold)
scene_change ? some_filter(...) : another_filter(...)
Difference to next
YDifferenceToNext(clip [, int offset = 1])  
UDifferenceToNext(clip [, int offset = 1])  
VDifferenceToNext(clip [, int offset = 1])  
RGBDifferenceToNext(clip [, int offset = 1])  
BDifferenceToNext(clip [, int offset = 1])   AVS+
GDifferenceToNext(clip [, int offset = 1])   AVS+
RDifferenceToNext(clip [, int offset = 1])   AVS+
This group of functions return the absolute difference of pixel value between the current and next frame of clip – either the combined RGB difference or the Luma, U-chroma or V-chroma differences, respectively. In v2.61 an offset argument is added, which enables you to access the difference between the RGB, luma or chroma plane of the current frame and of any other frame. Note that for example clip.RGBDifferenceToNext(-1) = clip.RGBDifferenceToPrevious, and clip.RGBDifferenceToNext(0) = 0.

Examples:

# both th1, th2 are positive thresholds; th1 is larger enough than th2
scene_change = (YDifferenceFromPrevious > th1) && (YDifferenceToNext < th2)
scene_change ? some_filter(...) : another_filter(...)
Color plane median, min, max, range
YPlaneMedian(clip [, int offset = 0])  
UPlaneMedian(clip [, int offset = 0])  
VPlaneMedian(clip [, int offset = 0])  
BPlaneMedian(clip [, int offset = 0])   AVS+
GPlaneMedian(clip [, int offset = 0])   AVS+
RPlaneMedian(clip [, int offset = 0])   AVS+
YPlaneMin(clip [, float threshold = 0, int offset = 0])  
UPlaneMin(clip [, float threshold = 0, int offset = 0])  
VPlaneMin(clip [, float threshold = 0, int offset = 0])  
BPlaneMin(clip [, float threshold = 0, int offset = 0])   AVS+
GPlaneMin(clip [, float threshold = 0, int offset = 0])   AVS+
RPlaneMin(clip [, float threshold = 0, int offset = 0])   AVS+
YPlaneMax(clip [, float threshold = 0, int offset = 0])  
UPlaneMax(clip [, float threshold = 0, int offset = 0])  
VPlaneMax(clip [, float threshold = 0, int offset = 0])  
BPlaneMax(clip [, float threshold = 0, int offset = 0])   AVS+
GPlaneMax(clip [, float threshold = 0, int offset = 0])   AVS+
RPlaneMax(clip [, float threshold = 0, int offset = 0])   AVS+
YPlaneMinMaxDifference(clip [, float threshold, int offset = 0])  
UPlaneMinMaxDifference(clip [, float threshold, int offset = 0])  
VPlaneMinMaxDifference(clip [, float threshold, int offset = 0])  
BPlaneMinMaxDifference(clip [, float threshold, int offset = 0])   AVS+
GPlaneMinMaxDifference(clip [, float threshold, int offset = 0])   AVS+
RPlaneMinMaxDifference(clip [, float threshold, int offset = 0])   AVS+
This group of functions return statistics about the distribution of pixel values on a plane (Luma, U-chroma and V-chroma, respectively). The statistics are, in order of presentation: maximum, minimum, median and range (maximum - minimum difference).
threshold is a percentage, stating how many percent of the pixels are allowed above or below minimum. The threshold is optional and defaults to 0. In v2.61 an offset argument is added, which enables you to access the statistics of other frames than the current one.

Examples:

# median and average are close only on even distributions; 
# this can be a useful diagnostic
have_intense_brights = YPlaneMedian() - AverageLuma() < threshold
...
# a simple per-frame normalizer to [16..235], CCIR, range
Levels(YPlaneMin(), 1.0, YPlaneMax(), 16, 235)

Functions for frame properties

Core and concept ported from VapourSynth.
Frame properties are per-frame data. Source or other filters can store useful data into frame properties such as information on colorimetry.
Imagine them as an array of zero or more elements of PropertyName=Value
Reading them is possible only by runtime functions.

Note:
At the moment (v3.6.2test7) Avisynth+ provides only the necessary framework for handling (set, read, clear, pass) such properties. None of its internal functions (such as color space converters) set or work upon frame property values.
There are already filters (like avsresize) and source plugins that are already using frame properties. Avisynth+ core will rely on frame in the future as well.

Developer info:
On filter level the set of frame properties should be copied from a previous (or specific) input frame. When filter is using env->MakeWritable in its GetFrame method this happens automatically.
But a simple env->NewVideoFrame means a dead-end for frame property passing mechanism. So filter must either use env->NewVideoFrameP which has an additional parameter: a source frame of the frame properties.
Or frame properties have to be copied later, programatically by the copyFrameProps ScriptEnvironment function.
For compatibility reasons NewVideoFrameP should be called adaptively instead of the traditional NewVideoFrame: usable after detecting Avisynth interface version 8 (NewVideoFrameP was introduced in v8).
What happens if this copy is not done properly? Then the filter is a dead-end for frame properties since NewVideoFrame constructs new frame with no frame properties. All old filters will behave like this.

Frame property getter functions are evaluated at every frame. They can be used inside the scripts passed to runtime filters (ScriptClip).
Frame property setters can be called both at script level and in runtime. When a property is set on script level it will be constant along the lifetime of the whole clip, unless it is changed in runtime, inside ScriptClip.
Though using property setter functions are allowed in FrameEvaluate but since it does not return an altered frame, writing a frame property there has zero effect.

  • frame properties are stored as key-value pairs
    • Key is an alphanumeric identifier.
    • Values can be of single value or array of type
      • 64 bit integer (32 bit integer when converted to AVSValue inside Avisynth+, AVSValue limitation)
      • 64 bit double (32 bit float when converted to AVSValue inside Avisynth+, AVSValue limitation)
      • string (or byte data) with given length. Strings are null terminated.
      • frame reference (PVideoFrame)
      • clip reference (PClip)
  • property setting has 3 modes: 0-replace 1-append 2-touch (see AVSPropAppendMode in avisynth.h)::
    • 0 - single value for that key is replaced
    • 1 - property is appended (make arrays by calling with mode=1 consecutively)
    • 2 - touch

Reserved frame property names

There are quasi-standard frame property names which are used widespread.
As frame properties came from VapourSynth (see "Reserved Frame Properties" at http://www.vapoursynth.com/doc/apireference.html), it is convenient that Avisynth plugins use the same properties and values.
Keys starting with _ 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.
_ChromaLocation
int _ChromaLocation  
Chroma sample position in YUV formats.
0=left, 1=center, 2=topleft, 3=top, 4=bottomleft, 5=bottom.
_ColorRange
int _ColorRange  
Full or limited range (PC/TV range). Primarily used with YUV formats.
0=full range, 1=limited range.
_Primaries
int _Primaries  
Color primaries as specified in ITU-T H.265 Table E.3.
_Matrix
int _Matrix  
Matrix coefficients as specified in ITU-T H.265 Table E.5.
_Transfer
int _Transfer  
Transfer characteristics as specified in ITU-T H.265 Table E.4.
_FieldBased
int _FieldBased  
If the frame is composed of two independent fields (interlaced).
0=frame based (progressive), 1=bottom field first, 2=top field first
_AbsoluteTime
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.
_DurationNum
int _DurationNum  
_DurationDen
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.
_Combed
int _Combed (boolean)  
Whether or not the frame needs postprocessing, usually hinted from field matching filters.
_Field
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.
_PictType
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.
_SARNum
int _SARNum  
_SARDen
int _SARDen  
Pixel (sample) aspect ratio as a rational number.
_SceneChangeNext
int _SceneChangeNext (boolean)  
If 1, this frame is the last frame of the current scene. The next frame starts a new scene.
_SceneChangePrev
int _SceneChangePrev (boolean)  
If 1, this frame starts a new scene.

Property set

Input value of setter functions are to be come either
  • from the return value of "function objects"
  • direct value
Property setter function names begin with propSet
Common parameters:
  • clip c,
  • string key_name,
  • direct value of supported types (integer, float, string, array, clip) or a "function object"
  • int "mode": 0=replace (default), 1=append, 2=touch. There is no append mode for inserting a full array into the property.
propSet
propSet(clip, string key_name, function func_obj [, integer "mode"])   AVS+
generic property setter, automatic type recognition by the return value of the function object
propSet
propSet(clip, string key_name, integer value [, integer "mode"])   AVS+
propSet
propSet(clip, string key_name, float value [, integer "mode"])   AVS+
propSet
propSet(clip, string key_name, string value [, integer "mode"])   AVS+
propSet
propSet(clip, string key_name, array value)   AVS+
propSet
propSet(clip, string key_name, clip value [, integer "mode"])   AVS+
The above four functions are setting a property by a directly passed values
note: array must contain only the similarly typed values, e.g. cannot mix strings with integers.
propSetInt
propSetInt(clip, string key_name, function func_obj [, integer "mode"])   AVS+
propSetFloat
propSetFloat(clip, string key_name, function func_obj [, integer "mode"])   AVS+
propSetString
propSetString(clip, string key_name, function func_obj [, integer "mode"])   AVS+
propSetArray
propSetArray(clip, string key_name, function func_obj [, integer "mode"])   AVS+
propSetClip
propSetClip(clip, string key_name, function func_obj [, integer "mode"])   AVS+
these setters accept only the specific type

Property get

Get properties by name or as a whole
Common parameters:
clip c,
string key_name,
integer "index", (default 0): for zero based indexing array access
integer "offset" (default 0), similar to the other runtime functions: frame offset (e.g. -1: previous, 2: next next)
propGetAny
propGetAny(clip, string key_name[, integer "index", integer "offset"])   AVS+
returns the automatically detected type
propGetInt
propGetInt(clip, string key_name[, integer "index", integer "offset"])   AVS+
returns only if value is integer, throws an error otherwise (note: unlike Avisynth integer frame properties internally use 64 bit integers)
propGetFloat
propGetFloat(clip, string key_name[, integer "index", integer "offset"])   AVS+
returns only if value is float, throws an error otherwise (note: unlike Avisynth float frame properties internally use 64 bit doubles)
propGetString
propGetString(clip, string key_name[, integer "index", integer "offset"])   AVS+
returns only if value is string, throws an error otherwise
propGetAsArray
propGetAsArray(clip, string key_name[, integer "index", integer "offset"])   AVS+
A frame property can hold multiple values of the same type: it can be an array
propGetAsArray returns an array. For a single property array size will be 1. (only in array-aware AviSynth+ versions)
propGetClip
propGetClip(clip, string key_name[, integer "index", integer "offset"])   AVS+
returns only if value is clip, throws an error otherwise (since 3.7.1)
propGetAll
propGetAll(clip [, integer "offset"])   AVS+
Returns all frame properties in an array of [key-value] pairs. Array size will be 'numProps'
Each key-value pair is contained in a two dimensional subarray.
If the property value for a given key is an array again then "value" will be an array as well.
Once you have the array with all properties you can access them with the "associative" feature of AviSynth array access

Example:

 ScriptClip("""last.propSet("cica","hello"+String(current_frame)).\
   propSetInt("test_i1",function[](clip c) { return current_frame*3 }).\
   propSet("test_i2", current_frame * 2) """)
 ScriptClip("""p = propGetAll() \
   SubTitle("size:" + String(p.ArraySize()) + " " + \
                      String(p["test_i1"]) + " " + \
                      String(p["cica"]) + " " + \
                      String(p["test_i2"]))""")
 ScriptClip("""p = propGetAll() \
   SubTitle("size:" + String(p.ArraySize()) + " " + \
       String(p[0,1]) + " " + \
       String(p[1,1]) + " " + \
       String(p[2,1]), x=0, y=20)""")

Example (read-write basic)

 ColorBars()
  
 # just practicing with function objects
 ScriptClip(function[](clip c) { c.Subtitle(String(current_frame)) })
 
 # write frame properties with function object
 ScriptClip("""propSetInt("frameprop_from_str",func(YPlaneMax))""")
 # write frame properties with traditional script string
 ScriptClip(function[](clip c) { propSetInt("frameluma_sc_func",func(AverageLuma)) })
 
 # read frame properties (function object, string)
 ScriptClip(function[](clip c) { SubTitle(string(propGetInt("frameprop_from_str")), y=20) })
 ScriptClip("""SubTitle(string(propGetInt("frameluma_sc_func")), y=40)""")

 return last

Example (nearly everything)

 ColorBars(width=640, height=480, pixel_type="yv12", staticframes=true)

 ScriptClip(function[](clip c) { propSetString("s",function[](clip c) { return "Hello " + string(current_frame) }) })
 ScriptClip(function[](clip c) { propSetString("s",function[](clip c) { return "Hello array element #2 " }, mode=1) })
 ScriptClip(function[](clip c) { propSetString("s",function[](clip c) { return "Hello array element #3 "}, mode=1 ) })

 ScriptClip(function[](clip c) { propSetString("s2",function[](clip c) { return "Another property "} ) })

 ScriptClip(function[](clip c) { propSetInt("s_int",function[](clip c) { return current_frame*1 }) })
 ScriptClip(function[](clip c) { propSetInt("s_int",function[](clip c) { return current_frame*2 }, mode=1) })
 ScriptClip(function[](clip c) { propSetInt("s_int",function[](clip c) { return current_frame*4 }, mode=1 ) })

 ScriptClip(function[](clip c) { propSetFloat("s_float",function[](clip c) { return current_frame*1*3.14 }) })
 ScriptClip(function[](clip c) { propSetFloat("s_float",function[](clip c) { return current_frame*2*3.14 }, mode=1) })
 ScriptClip(function[](clip c) { propSetFloat("s_float",function[](clip c) { return current_frame*3*3.14 }, mode=1 ) })

 ScriptClip(function[](clip c) { propSetArray("s_float_arr",function[](clip c) { return [1.1, 2.2] } ) })
 ScriptClip(function[](clip c) { propSetArray("s_int_arr",function[](clip c) { return [-1,-2,-5] } ) })
 ScriptClip(function[](clip c) { propSetArray("s_string",function[](clip c) { return ["ArrayElementS_1", "ArrayElementS_2"] } ) })
 #ScriptClip("""propDelete("s")""")
 ScriptClip(function[](clip c) {
   y = 0
   SubTitle("Prop Key count =" + String(propNumKeys), y=y)
   y = y + 15
   numKeys = propNumKeys() - 1
   for ( i = 0 , numKeys) {
     propName = propGetKeyByIndex(index = i)
     propType = propGetType(propName)
     SubTitle("#"+String(i) + " property: '" + propName + "', Type = " + String(propType) , y=y)
     y = y + 15

     for(j=0, propNumElements(propName) - 1) {
       SubTitle("element #" + String(j) + ", size = " + String(propType == 3 ? propGetDataSize(propName, index=j) : 0) + ", Value = " + String(propGetAny(propName, index=j)), y = y)
       #SubTitle("element #" + String(j) + " size = " + String(propType == 3 ? propGetDataSize(propName, index=j) : 0) + ", Value = " + String(propGetAny(propName, index=j)), y = y)
       y = y + 15
     }
   }
   return last
 })

 ScriptClip(function[](clip c) {
   a = propGetAsArray("s")
   y = 100
   x = 400
   SubTitle(string(a.ArraySize()), x=x, y=y)
   for(i=0, a.ArraySize()-1) {
     SubTitle("["+String(i)+"]="+ String(a[i]),x=x,y=y)
     y = y + 15
   }
   return last
 })

 # get int array one pass
 ScriptClip(function[](clip c) {
   a = propGetAsArray("s_int")
   y = 440
   x = 400
   SubTitle("Array size=" + string(a.ArraySize()), x=x, y=y)
   y = y + 15
   for(i=0, a.ArraySize()-1) {
     SubTitle("["+String(i)+"]="+ String(a[i]),x=x,y=y)
     y = y + 15
   }
   return last
 })

 # get float array one pass
 ScriptClip(function[](clip c) {
   a = propGetAsArray("s_float")
   y = 440
   x = 200
   SubTitle("Array size=" + string(a.ArraySize()), x=x, y=y)
   y = y + 15
   for(i=0, a.ArraySize()-1) {
     SubTitle("["+String(i)+"]="+ String(a[i]),x=x,y=y)
     y = y + 15
   }
   return last
 })

 # get string array
 ScriptClip(function[](clip c) {
   a = propGetAsArray("s_string")
   y = 440
   x = 000
   SubTitle("Array size=" + string(a.ArraySize()), x=x, y=y)
   y = y + 15
   for(i=0, a.ArraySize()-1) {
     SubTitle("["+String(i)+"]="+ String(a[i]),x=x,y=y)
     y = y + 15
   }
   return last
 })

AviSynth 3.7.1: allow propGetXXX property getter functions called as normal functions, outside runtime.
By default frame property values are read from frame#0 which index can be overridden by the offset parameter.

Example:

   Colorbars()
   PropSet(last, "hello", 1) # Set to 1 for all frames
   # Override to 2 with runtime function except for frameNo=1
   ScriptClip("""if(current_frame!=1) {propSet("hello",2)}""")
   n0 = propGetInt("hello") # same as propGetInt("hello",offset=0)
   # or get the frame property from the Nth frame
   n1 = propGetInt("hello",offset=1)
   n2 = propGetInt("hello",offset=2)
   # n0 and n2 is 2 (overridden in runtime)
   # n1 will be 1 (keeps global setting)
   SubTitle("n0/n1/n2=" + "{n0}/{n1}/{n2}".Format)

Deleting properties

Delete one specific property or all property entries
propDelete
propDelete(clip, string)   AVS+
Deletes a property by name. If property does not exist, do nothing.
  • clip (required) specifies clip.
  • string (required) key_name (case sensitive) specifies the name of the parameter to delete

Example:

 ScriptClip("""propDelete("my_spec_prop")""")
propClearAll
propClearAll(clip)   AVS+
Clears all properties for a given video frame
  • clip (required) specifies clip.

Other property functions

propShow
propShow(clip, integer "size", bool "showtype")   AVS+
This debug filter lists all frame properties on screen.
Listing appears as a name = value list. Arrays values are displayed between [ and ]
Top line contains the number of properties. If no properties found, nothing is displayed.
  • clip (required) specifies clip.
  • integer "size" default(16), font size to use (the "Text" filter is used for display, sizes are of limited set)
  • bool "showtype" default(false), if true, the data type in parenthesis appears next to the property key name
propGetDataSize
propGetDataSize(clip, string key_name [, integer "index", integer "offset"])   AVS+
returns the size of the string or underlying data array
propNumElements
propNumElements(clip, string key_name [, integer "offset"])   AVS+
returns the array size of a given property. 1=single value
propNumKeys
propNumKeys(clip, [, integer "offset"])   AVS+
returns number of entries (keys) for a frame
propGetKeyByIndex
propGetKeyByIndex(clip, integer "index" [, integer "offset")   AVS+
returns the key name for the Nth property (zero based, 0<=index<propNumKeys)
propGetType
propGetType(clip, string key_name [, integer "offset"])   AVS+(v3.7.0)
returns the type of the given key
  • unset: 0
  • integer: 1
  • float: 2
  • string: 3
  • clip: 4
  • frame: 5
propCopy
propCopy(clip, clip [,bool "merge"])   AVS+(v3.7.1)
Copies the frame properties of the second clip to the first.
  • Parameter 'merge' (default false):
  • when false: exact copy (original target properties will be lost)
  • when true: keeps original properties, appends all parameters from source but overwrite if a parameter with the same name already exists.

Script functions

These provide AviSynth script information.
ScriptName
ScriptName()   v2.60
Returns the path and filename of the loaded script as a string.

Examples:

name = ScriptName() # name = "F:\ProjectXYZ\video.avs"
ScriptNameUtf8
ScriptNameUtf8()   AVS+
Returns the path and filename of the loaded script as a Unicode string, encoded in UTF8.
ScriptFile
ScriptFile()   v2.60
Returns the filename of the loaded script as a string.

Examples:

file = ScriptFile() # file = "video.avs"
ScriptFileUtf8
ScriptFileUtf8()   AVS+
Returns the filename of the loaded script as a Unicode string, encoded in UTF8.
ScriptDir
ScriptDir()   v2.60
Returns the path of the loaded script as a string.

Examples:

folder = ScriptDir() # folder = "F:\ProjectXYZ"
ScriptDirUtf8
ScriptDirUtf8()   AVS+
Returns the path of the loaded script as a Unicode string, encoded in UTF8.
SetLogParams
SetLogParams([string target, int level])   AVS+
Sets a file path for a log file, used by LogMsg and internal error reporting.
  • target names a file which will be created when the script loads. If attempting to create or write to target fails, the script will raise an error immediately. If the file exists, new log entries will be appended to the end. If omitted, target defaults to stderr.
  • level sets the log verbosity; it can be one of the following:
LOG_ERROR (1) creates the fewest log entries
LOG_WARNING  (2) 
LOG_INFO (3) creates the most log entries
If omitted, level defaults to LOG_INFO.
Examples see LogMsg below.
LogMsg
LogMsg(string, int)   AVS+
Creates a new log entry.
  • string (required) specifies the log message.
  • int (required) specifies the log entry level: see SetLogParams above.

Examples:

## creating file and set path for future log entries:
SetLogParams("<path>\_test1.log", LOG_INFO)

...log contents:
(empty)
## logging an INFO message:
SetLogParams("<path>\_test2.log", LOG_INFO)
LogMsg("this is a test", LOG_INFO)

log contents:
---------------------------------------------------------------------
INFO: this is a test
## logging a script error:
SetLogParams("<path>\_test3.log", LOG_INFO)
foo("bar") ## ERROR!

...log contents (redundant entries are common):
ERROR: Script error: There is no function named 'foo'.
---------------------------------------------------------------------
ERROR: Script error: There is no function named 'foo'.
(<path>\_test.avs, line 35)
## logging INFO context for script error:
SetLogParams("<path>\_test4.log", LOG_INFO)
function MyFunction(clip C)
{
    C
    try {
        foo("bar") ## ERROR!
    } catch (err_msg) {
        msg2 = "Error in MyFunction: "
        LogMsg(Time("%Y-%m-%d %I:%M:%S %p, %z") + ": " + msg2, LOG_INFO)
        #Assert(false, msg2 + err_msg) ## optional: stop script, else continue
    }
    return Last
}

log contents (redundant entries omitted):
---------------------------------------------------------------------
ERROR: Script error: There is no function named 'foo'.
(<path>\_test.avs, line 54)
---------------------------------------------------------------------
INFO: 2017-11-12 11:03:41 AM, -0500: Error in MyFunction:
(<path>\_test.avs, line 54)
GetProcessInfo
GetProcessInfo(int)   AVS+
Returns information about the process the script is running in.
The int argument has two legal values:
  • if 0 (default), returns 64 for a 64-bit process or 32 for a 32-bit process.
  • else if 1,
    • returns 0 for 32-bit process on 32-bit OS;
    • returns 1 for 32-bit process on 64-bit OS;
    • returns 2 for 64-bit process on 64-bit OS;
    • else returns -1 (unknown)
/// TODO this is preliminary info

String functions

These provide common operations on string variables.
LCase
LCase(string)  
Returns lower case of string.

Examples:

LCase("AviSynth") = "avisynth"
UCase
UCase(string)  
Returns upper case of string.

Examples:

UCase("AviSynth") = "AVISYNTH"
StrToUtf8
StrToUtf8(string)   AVS+
Converts string from ANSI to UTF8.
StrFromUtf8
StrFromUtf8(string)   AVS+
Converts string from UTF8 to ANSI.
StrLen
StrLen(string)  
Returns length of string.

Examples:

StrLen("AviSynth") = 8
RevStr
RevStr(string)  
Returns string backwards.

Examples:

RevStr("AviSynth") = "htnySivA"
LeftStr
LeftStr(string, int)  
Returns first int count of characters.

Examples:

LeftStr("AviSynth", 3) = "Avi"
RightStr
RightStr(string, int)  
Returns last int count of characters.

Examples:

RightStr("AviSynth", 5) = "Synth"
MidStr
MidStr(string, int pos [, int length])  
Returns substring starting at pos for optional length or to end. pos=1 specifies start.

Examples:

MidStr("AviSynth", 3, 2) = "iS"
FindStr
FindStr(string, substring)  
Returns (1-based) position of substring within string
  • Note this function is case-sensitive.
  • Returns 0 if substring is not found.

Examples:

Findstr("AviSynth", "Syn") ## returns 4
Findstr("AviSynth", "SYN") ## returns 0
ReplaceStr
ReplaceStr(string, substring, replacement_string [, bool sig])   AVS+
Replaces occurrences of substring with replacement_string and returns the result.
  • sig if false (the default), search is case-sensitive; if true, search is not case-sensitive.
  • Avisynth 2.6.x users have other options, such as the user function below, adapted from StrReplace, found here.
function ReplaceStr(string base, string sought, string repstr) {
    pos = FindStr(base, sought)
    return (sought=="" || pos==0) ? base : ReplaceStr(
    \       LeftStr(base, pos-1) + repstr +
    \       MidStr(base, pos+StrLen(sought)),
    \       sought, repstr)
}

Examples:

ReplaceStr("FlipHorizontal", "Horizontal", "Vertical")
ReplaceStr("$a x *", "$a", String(1.5)) ## (a MaskTools expression with argument)
Format
Format(formatstring [, value1, value2, ...])   AVS+
Mixes the string containing inline placeholders with parameters each converted to strings and returns the result.
  • formatstring unnamed parameter, string literal with parameter insertion points marked with {}.
  • value1, value2,etc. zero or more values which are inserted into the format string one after another
Description:
The format string consists of
  • ordinary characters (except { and }), which are copied unchanged to the output,
  • escape sequences double "{" ("{{") and double "}" ("}}"), which are replaced with "{" and "}" respectively in the output, and
  • replacement fields.
Each replacement field has the following format:
introductory { character;
(optional)
arg-id, a non-negative number;
or:
identifier which is used for lookup named parameters. (["name", value] construction)
or:
valid AviSynth variable name
final } character.
If arg-id is a number it specifies the index of the argument in args whose value is to be used for formatting;
Index is zero based.
If arg-id is string then it serves as a lookup key from the parameters list given as an array ["name",value] pair.
If not found, then arg-id is searched among Avisynth variables.
If arg-id is omitted, the arguments are used in order.
Mixing manual and automatic indexing is not an error.
Notes
It is not an error to provide more arguments than the format string requires:
Format("{} {}!", "Hello", "world", "something") # OK, produces "Hello world!"

Example: By Avisynth variable

max_pixel_value = 255
SubTitle(Format("max={max_pixel_value}!")) # no format value given, inserts directly from variable

Example: By index:

SubTitle(Format("{0} {1} {0}", "Home", "sweet"))

Example: by order:

SubTitle(Format("{} {} {}", "AviSynth", "+", 2020))

Example: by Array name-value pairs:

SubTitle(Format("maximum={max} minimum={min} max again {max}!", ["max",255], ["min",0]))
  • since Avisynth+ 3.6
FillStr
FillStr(int [, string])   v2.60
Fills a string. When int>1 it concatenates the string int times. string is " " (space) by default.

Examples:

FillStr(1, "AviSynth") = "AviSynth"
FillStr(2, "AviSynth") = "AviSynthAviSynth"
StrCmp
StrCmp(string, string)   v2.60
Compares two character strings. The comparison is case-sensitive. If the first string is less than the second string, the return value is negative. If it's greater, the return value is positive. If they are equal, the return value is zero. (The actual value seems to be language dependent so it can't be relied upon.)

Examples:

StrCmp("AviSynth", "AviSynth") = 0 # strings are equal.
StrCmp("AviSynth", "Avisynth") != 0 # strings are not equal.
StrCmpi
StrCmpi(string, string)   v2.60
Compares two character strings. The comparison is not case-sensitive. If the first string is less than the second string, the return value is negative. If it's greater, the return value is positive. If they are equal, the return value is zero. (The actual value seems to be language dependent so it can't be relied upon.)

Examples:

StrCmpi("AviSynth", "AviSynth") = 0 # strings are equal.
StrCmpi("AviSynth", "Avisynth") = 0 # strings are equal.
StrCmpi("abcz", "abcdefg") != 0 
# returns the difference betweeen "z" and "d" (which is positive).
TrimLeft, TrimRight, TrimAll
TrimLeft(string)  
TrimRight(string)  
TrimAll(string)  
AVS+ Removes whitespace characters (space, tab, nonbreaking space) from the left, right, or both ends of a string.
Chr
Chr(int)  
Returns the ASCII character.
Note that characters above the ASCII character set (ie above 127) are code page dependent and may render different (visual) results in different systems. This has an importance only for user-supplied localised text messages.

Examples:

Chr(34) returns the quote character
Chr(9)  returns the tab   character
Ord
Ord(string)   v2.60
Gives the ordinal number (character code) of the first character of string (works like php ord or Basic Asc)

Examples:

Ord("a") = 97
Ord("AviSynth") = Ord("A") = 65
Ord("§") = 167
Time
Time(string)  
Returns a string with the current system time formatted as defined by string.
The string may contain any of the codes for output formatting presented below:
Code Description
%a

%A

Abbreviated weekday name

Full weekday name

%b

%B

Abbreviated month name

Full month name

%c Date and time representation appropriate for locale
%d Day of month as decimal number (01 - 31)
%H

%I

Hour in 24-hour format (00 - 23)

Hour in 12-hour format (01 - 12)

%j Day of year as decimal number (001 - 366)
%m Month as decimal number (01 - 12)
%M Minute as decimal number (00 - 59)
%p Current locale's A.M./P.M. indicator for 12-hour clock
%S Second as decimal number (00 - 59)
%U Week of year as decimal number, with Sunday as first day of week (00 - 53)
%w Weekday as decimal number (0 - 6; Sunday is 0)
%W Week of year as decimal number, with Monday as first day of week (00 - 53)
%x Date representation for current locale
%X Time representation for current locale
%y

%Y

Year without century, as decimal number (00 - 99)

Year with century, as decimal number

%z, %Z Time-zone name or abbreviation; no characters if time zone is unknown
%% Percent sign
The '#' flag may prefix any formatting code. In that case, the meaning of the format code is changed as follows:
Code with '#' flag Change in meaning
%#a, %#A, %#b,

%#B, %#p, %#X, %#z, %#Z, %#%

No change; flag is ignored.
%#c Long date and time representation, appropriate for current locale.

For example, "Tuesday, March 14, 1995, 12:41:29"

%#x Long date representation, appropriate to current locale.

For example, "Tuesday, March 14, 1995"

%#d, %#H, %#I,

%#j, %#m, %#M, %#S, %#U, %#w, %#W, %#y, %#Y

Remove leading zeroes (if any).

Examples:

v = Time("%Y-%m-%d")        # "2010-03-01"
v = Time("%d-%b-%Y")        # "01-Mar-2010"
v = Time("%#d/%#m/%y")      # "1/3/10"
v = Time("%I:%M:%S %p, %z") # "08:04:42 PM, GMT Standard Time"
v = Time("%H:%M:%S %z")     # "20:04:42 GMT Standard Time"

Version functions

These provide AviSynth version information.
VersionNumber
VersionNumber()  
Returns AviSynth version number as a float.

Examples:

VersionNumber ## returns 2.60 (release version as of 11/2017)
VersionNumber ## returns 2.61 (beta)
VersionNumber ## returns 2.60 (AVS+ release 2508)
VersionString
VersionString()  
Returns AviSynth version info as a string (first line used in Version() command).

Examples:

VersionString ## returns "AviSynth 2.60, build:Mar 31 2015 [16:38:54]"
VersionString ## returns "AviSynth 2.61, build:May 17 2016 [16:06:18] VC2008Exp"
VersionString ## returns "AviSynth+ 0.1, (r2508, MT, x86_64)"
function IsAvsPlus()
{
    sVer = LCase(VersionString) 
    return (FindStr(sVer, "avisynth+")    > 0)
    \   || (FindStr(sVer, "avisynthplus") > 0)
}
IsVersionOrGreater
bool IsVersionOrGreater(int majorVersion, int minorVersion [,int bugfixVersion]) AVS+  
Returns true if Avisynth+ version is is equal or greater than the required one in the parameters.
Since Avisynth+ 3.5

Examples:

isAtLeast3_10 = IsVersionOrGreater(3,10)
isAtLeast3_5_1 = IsVersionOrGreater(3,5,1)

Array functions

AVS+
Array manipulator functions for AviSynth+.
ArrayAdd
ArrayAdd(array_to_mod, value_to_append [, index1, index2, index3...])  
Appends value to the end of an array or its subarray
Returns a new array with value_to_append appended to array_to_mod (1D array) or array_to_mod[index1 (, index2, index3...)] (multi-dimensional array).
Original array (as with the other functions) remains untouched.
ArrayDel
ArrayDel(array_to_mod, index1 (, index2, index3...])  
Returns a new array in which the requested position was deleted.
Original array (as with the other functions) remains untouched.
ArrayIns
ArrayIns (array_to_mod, value_to_insert, index1 [, index2, index3...])  
Insert a value into an array or into its subarray.
Returns a new array with value_to_insert inserted into array_to_mod (1D array) or array_to_mod[index1 (, index2, index3...)] (multi-dimensional array)
The indexes point to the insertion point. Index 0 will insert at the beginning of the array.
Index (ArraySize) will insert after the last element (same as ArrayAdd - append)
Original array (as with the other functions) remains untouched.
ArraySet
ArraySet(array_to_mod, replacement_value, index1 [, index2, index3...])  
Returns a new array with array_to_mod[index1 (, index2, index3...)] = replacement_value
Original array (as with the other functions) remains untouched.


Examples:

ColorbarsHD()
# array indexes are zero based
a = []
a=ArrayAdd(a,[1,2]) # [[1,2]]
a=ArrayIns(a,3,0) # [3,[1,2]]
a=ArrayAdd(a,"s1") # [3,[1,2],"s1"]
a=ArrayAdd(a,"s2") # [3,[1,2],"s1","s2"]
a=ArrayDel(a,2) # [3,[1,2],"s2"]
a=ArraySet(a,"g",1,0) # [3,["g",2],"s2"]
a=ArrayAdd(a,"h",1) # [3,["g",2,"h"],"s2"]
a=ArrayAdd(a,[10,11,12],1) # append to (1) -> [3,["g",2,"h",[10,11,12]],"s2"]
a=ArrayDel(a,1,3,0) # del from (1,3,0) -> [3,["g",2,"h",[11,12]],"s2"]
a=ArrayAdd(a,"added") # [3,["g",2,"h",[11,12]],"s2","added"]
a=ArrayAdd(a,["yet","another","sub"]) # [3,["g",2,"h",[11,12]],"s2","added",["yet","another","sub"]]
x=a[0] #3
x=a[1,0] #g
x=a[1,2] #h
x=a[1,3,1] #12
x=a[3] #"added"
x=a[4,1] #"another"
SubTitle("x = " + String(x) + " Size=" + String(a.ArraySize()))
For more examples see the Facts about user defined script functions section.

Other helper functions

Non-categorized functions
BuildPixelType
string BuildPixelType(string family, int bits, int chroma, bool compat, bool oldnames, clip sample_clip)   AVS+
Creates a video format (pixel_type) string by giving a colorspace family, bit depth, optional chroma subsampling and/or a
template clip, from which the undefined format elements are inherited.
  • string family
defines color family: "Y", "YUV", "YUVA", "RGB", "RGBA"
use "RGB" for both planar RGB and classic packed RGB24 and RGB48 - compat switches to classic formats
  • int bits
intended bit depth: 8, 10, 12, 14, 16, 32. In Avisynth+ 8-16 bits are integer formats, 32 bit is float
  • int chroma
chroma subsampling: 411, 420, 422, 444. Applies for YUV(A) formats. Ignored for RGB(A) and Y
  • bool compat default false
When set to true, function returns packed RGB(A) formats instead of planar RGB(A) (e.g. "RGB48" instead of "RGBP16"), when applicable
  • bool oldnames default false
when true, function returns "YV12", "YV16", "YV24" instead of "YUV420P8", "YUV422P8" and "YUV444P8" respectively
  • clip sample_clip when given, the clip serves as the base format, all optional parameters (bits, subsampling) will modify only its respective properties

Examples:

define "YUV444P10"
family = "YUV"
bits = 10
chroma = 444
compat = false
oldformat = false
s = BuildPixelType(family, bits, chroma, compat, oldformat)
BlankClip(width=320,height=200,length=len,pixel_type=s,color=$008080).Info()
Change only bit depth to 16, sample format is of an existing clip
newbits = 16
c = last
s = BuildPixelType(bits=newbits, sample_clip=c)
BlankClip(width=320,height=200,length=len,pixel_type=s,color=$008080).Info()
ColorSpaceNameToPixelType
int ColorSpaceNameToPixelType(string)   AVS+
Creates a video format (pixel_type) by providing a colorspace name
  • some formats have multiple valid names: "YV12" is identical to "YUV420P8", "YV16" = "YUV422P8", "YV24" = "YUV444P8"

Back to AviSynth Syntax.

Personal tools