Index
ffmpeg
This module provides methods to build and run FFmpeg with fine control commands.
Example
For simple usecase use export
function it allows to export in one line, see example below
from ffmpeg import export, InputFile
clip = InputFile("input.mp4")
export(clip, path="output.mkv").run()
FFmpeg
__init__
This class provides methods to construct and execute FFmpeg commands. either Run or Compile the command to get the command list and run it manually.
Initialize the FFmpeg command builder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
str
|
Path to the ffmpeg executable.". |
'ffmpeg'
|
use_filter_file
|
bool
|
Whether to use a filter script file,useful for very long filter graphs. |
False
|
filter_script_file
|
str
|
Path to the filter script file if use_filter_file is True. |
'filters.txt'
|
compile
Generate the full FFmpeg command as a list of arguments.
This method collects and combines all the necessary parts of the FFmpeg command, including global flags, input definitions, filter graphs, mapping, output flags, and output file paths. It ensures that the command is constructed in the correct order and with all required options for execution.
Returns:
Type | Description |
---|---|
list[str]
|
The complete FFmpeg command as a list of arguments. |
output
Create output for the with streams mapped to it.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*maps
|
Map | BaseInput | StreamSpecifier
|
One or more |
()
|
path
|
str
|
The file path for the output media file. |
required |
metadata
|
Optional[dict[str, str]]
|
Metadata to be added to the output file. |
None
|
**kwargs
|
dict[str, Any]
|
Additional keyword arguments representing output-specific |
{}
|
run
Run the FFmpeg command.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
progress_callback
|
Optional[Callable[[dict], None]]
|
Function that can be used to track progress of the process running data can be mix of None and actual values |
None
|
progress_period
|
float
|
Set period at which progress_callback is called |
0.5
|
overwrite
|
bool
|
overwrite the output if already exists |
True
|
run_async
async
Asynchronously run the FFmpeg command.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
progress_callback
|
Optional[Callable[[dict], Coroutine[Any, Any, None]]]
|
Function that can be used to track progress of the process running data can be mix of None and actual values |
None
|
progress_period
|
float
|
Set period at which progress_callback is called |
0.5
|
overwrite
|
bool
|
overwrite the output if already exists |
True
|
export
Exports a clip by processing the given input nodes and saving the output to the specified path.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
nodes
|
BaseInput | StreamSpecifier
|
One or more input nodes representing media sources. |
()
|
path
|
The output file path where the exported clip will be saved. |
required | |
kwargs
|
dict[str, Any]
|
flags for Output |
{}
|
Returns:
Type | Description |
---|---|
FFmpeg
|
FFmpeg instance configured with the given inputs and output path. |
filters
This module contains various FFmpeg filters as Python classes. The filters Always Inherit from BaseFilter class and Optionally TimelineEditingMixin if they support timeline editing.
AudioDelay
AudioFormat
Bases: BaseFilter
__init__
Represents an audio format filter that sets audio parameters. At least one of sample_rates, sample_fmts, or channel_layouts must be provided.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sample_rates
|
Optional[list[str | float]]
|
Optional list of sample rates (e.g., ["44100", "48000"]). |
None
|
sample_fmts
|
Optional[list[str | float]]
|
Optional list of sample formats (e.g., ["fltp", "s16"]). |
None
|
channel_layouts
|
Optional[list[str | float]]
|
Optional list of channel layouts (e.g., ["stereo", "5.1"]). |
None
|
AudioMix
BaseFilter
Concat
Bases: BaseFilter
Represents a concat filter that joins multiple segments. See: https://ffmpeg.org/ffmpeg-filters.html#concat
Format
Bases: BaseFilter
Represents a format filter that sets the pixel format of a video stream.
__init__
Convert the input video to one of the specified pixel formats. Libavfilter will try to pick one that is suitable as input to the next filter.
It accepts the following parameters:
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pixel_format
|
str
|
A |
required |
color_space
|
Optional[str]
|
A |
None
|
color_range
|
Optional[str]
|
A |
None
|
alpha_mode
|
Optional[str]
|
A |
None
|
HorizontalStack
Overlay
Bases: BaseFilter
, TimelineEditingMixin
Represents an overlay filter that combines two video streams.
Scale
Bases: BaseFilter
Represents the FFmpeg scale filter.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
width
|
float
|
The width of the output video. |
required |
height
|
float
|
The height of the output video. |
required |
reset_sar
Reset the sample aspect ratio.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
enable
|
bool
|
Whether to enable resetting SAR. |
True
|
Returns:
Name | Type | Description |
---|---|---|
Self |
Self
|
The current Scale instance. |
set_aspect_ratio_mode
Set the aspect ratio mode.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mode
|
AspectRatioMode
|
The aspect ratio mode. |
required |
Returns:
Name | Type | Description |
---|---|---|
Self |
Self
|
The current Scale instance. |
set_eval
Set the evaluation mode. Useful for dynamic scaling.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mode
|
EvalMode
|
The evaluation mode. |
required |
Returns:
Name | Type | Description |
---|---|---|
Self |
Self
|
The current Scale instance. |
set_force_divisible_by
Set the force divisible by value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n
|
int
|
The value to force divisibility by. |
required |
Returns:
Name | Type | Description |
---|---|---|
Self |
Self
|
The current Scale instance. |
set_in_chroma_location
Set the input chroma location.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
loc
|
IOChromaLocation
|
The input chroma location. |
required |
Returns:
Name | Type | Description |
---|---|---|
Self |
Self
|
The current Scale instance. |
set_in_color_matrix
Set the input color matrix.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
matrix
|
ColorMatrix
|
The input color matrix. |
required |
Returns:
Name | Type | Description |
---|---|---|
Self |
Self
|
The current Scale instance. |
set_in_primaries
Set the input color primaries.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
primaries
|
IOPrimaries
|
The input color primaries. |
required |
Returns:
Name | Type | Description |
---|---|---|
Self |
Self
|
The current Scale instance. |
set_in_range
Set the input range.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
rng
|
IORange
|
The input range. |
required |
Returns:
Name | Type | Description |
---|---|---|
Self |
Self
|
The current Scale instance. |
set_intent
Set the color intent.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
intent
|
Intent
|
The color intent. |
required |
Returns:
Name | Type | Description |
---|---|---|
Self |
Self
|
The current Scale instance. |
set_interlacing
Set the interlacing mode.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mode
|
InterlacingMode
|
The interlacing mode. |
required |
Returns:
Name | Type | Description |
---|---|---|
Self |
Self
|
The current Scale instance. |
set_out_chroma_location
Set the output chroma location.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
loc
|
IOChromaLocation
|
The output chroma location. |
required |
Returns:
Name | Type | Description |
---|---|---|
Self |
Self
|
The current Scale instance. |
set_out_color_matrix
Set the output color matrix.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
matrix
|
ColorMatrix
|
The output color matrix. |
required |
Returns:
Name | Type | Description |
---|---|---|
Self |
Self
|
The current Scale instance. |
set_out_primaries
Set the output color primaries.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
primaries
|
IOPrimaries
|
The output color primaries. |
required |
Returns:
Name | Type | Description |
---|---|---|
Self |
Self
|
The current Scale instance. |
SetSampleAspectRatio
Bases: BaseFilter
Subtitles
Text
Bases: BaseFilter
, TimelineEditingMixin
Draw a text string or text from a specified file on top of a video, using the libfreetype library.
f_expression
staticmethod
Returns an FFmpeg drawtext expansion string that evaluate expression.
f_frame_num
staticmethod
Returns an FFmpeg drawtext expansion string that expands to the local time with given strftime format.
f_gmtime
staticmethod
Returns an FFmpeg drawtext expansion string that expands to the local time with given strftime format.
f_localtime
staticmethod
Returns an FFmpeg drawtext expansion string that expands to the local time with given strftime format.
f_pts
staticmethod
Returns an FFmpeg drawtext expansion string that expands to the PTS (presentation timestamp).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fmt
|
Literal['flt', 'hms', 'gmtime', 'localtime']
|
Format of the timestamp. - "flt" -> seconds with microsecond precision (default) - "hms" -> [-]HH:MM:SS.mmm - "gmtime" -> UTC timestamp (strftime supported if extra is given) - "localtime" -> local timestamp (strftime supported if extra is given) |
'flt'
|
offset
|
Optional[str]
|
Offset to add to timestamp (e.g., "10" for +10s). |
None
|
extra
|
Optional[str]
|
Optional third argument: - for "hms" format: "24HH" - for gmtime/localtime: strftime format string. |
None
|
Examples:
f_pts() -> "%{pts}" f_pts("hms") -> "%{pts:hms}" f_pts("hms", "5") -> "%{pts:hms:5}" f_pts("localtime", "0", "%H\:%M\:%S") -> "%{pts:localtime:0:%H\:%M\:%S}"
TimelineEditingMixin
Mixin providing timeline-based activation control for FFmpeg filter graphs.
This mixin allows enabling filters conditionally based on the video timestamp,
using FFmpeg's enable
expression mechanism with between
, gte
, and lte
.
Attributes:
Name | Type | Description |
---|---|---|
flags |
dict
|
Dictionary storing FFmpeg filter options, such as enable expressions. |
enable_after
Enable the filter only after the given timestamp.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
t
|
float
|
Time (in seconds) after which the filter is enabled. |
required |
Returns:
Name | Type | Description |
---|---|---|
TimelineEditingMixin |
Self
|
The current instance with the updated |
enable_before
Enable the filter only before the given timestamp.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
t
|
float
|
Time (in seconds) before which the filter is enabled. |
required |
Returns:
Name | Type | Description |
---|---|---|
TimelineEditingMixin |
Self
|
The current instance with the updated |
enable_between
Enable the filter only between the given start and end times.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
start
|
float
|
Start time (in seconds). |
required |
end
|
float
|
End time (in seconds). |
required |
Returns:
Name | Type | Description |
---|---|---|
TimelineEditingMixin |
Self
|
The current instance with the updated |
VerticalStack
Volume
XFade
Bases: BaseFilter
apply
Apply a filter input streams.
This function connects the given input nodes (either BaseInput or StreamSpecifier) to a filter node and returns a single output stream from the filter.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filter_obj
|
BaseFilter
|
The filter node to apply. |
required |
*parent
|
BaseInput | StreamSpecifier
|
Input nodes to connect to the filter. |
()
|
Returns:
Type | Description |
---|---|
StreamSpecifier
|
The resulting single output stream from the filter. |
apply2
Apply a filter input streams.
This function connects the given input nodes (either BaseInput or StreamSpecifier) to a filter node and returns a list of all output streams from the filter.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filter_obj
|
BaseFilter
|
The filter node to apply. |
required |
*parent
|
BaseInput | StreamSpecifier
|
Input nodes to connect to the filter. |
()
|
Returns:
Type | Description |
---|---|
list[StreamSpecifier]
|
A list of output streams from the filter. |
utils
build_flags
Generate flags for FFmpeg command from key-value pairs. if value is bool, convert to int (True=1, False=0) if value is None, skip the flag value part (y=None, ["-y"]).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
kwflags
|
dict
|
Dictionary of key-value pairs representing flags. |
required |
Returns:
Name | Type | Description |
---|---|---|
list |
list[str]
|
List of command-line flags for FFmpeg. |
build_name_kvargs_format
Build a formatted string for FFmpeg filter options. Automatically skips None values and converts bool int. Args: name (str): The name of the filter. flags (dict): A dictionary of key-value pairs representing filter options.
exception
FFmpegException
Bases: Exception
Exception raised when an FFmpeg command fails.
Attributes:
Name | Type | Description |
---|---|---|
msg |
The error message returned by FFmpeg. |
|
return_code |
The process return code from FFmpeg. |
FFprobeException
Bases: FFmpegException
Exception raised when an FFprobe command fails.
Inherits from FFmpegException and is specific to FFprobe failures.
Attributes:
Name | Type | Description |
---|---|---|
msg |
str
|
The error message returned by FFprobe. |
return_code |
int
|
The process return code from FFprobe. |
ffplay
Use FFplay through easy to use function
ffplay
ffplay
ffplay(file_path, width=None, height=None, fullscreen=False, disable_audio=False, disable_video=False, disable_subtitles=False, seek_position=None, duration=None, seek_by_bytes=False, seek_interval=None, nodisp=False, noborder=False, alwaysontop=False, volume=None, force_format=None, window_title=None, left=None, top=None, loop=None, showmode=None, video_filter=None, audio_filter=None, autoexit=False, fbuf=False, sync=None, fast=False, stats=False, drp=False, fflags=None, vf=None, af=None, framedrop=False)
Run ffplay to play the specified media file with customizable options.
ffprobe
Use FFprobe through easy to use function or use flags to get specific data
ffprobe
ffprobe
Run ffprobe with the given options on the specified file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
file_path
|
str
|
Path to the media file. |
required |
options
|
Optional[Iterable[str]]
|
set ffprobe options (default extracts streams and format). |
None
|
Returns:
Type | Description |
---|---|
Any
|
Parsed JSON dictionary output. |
math
Variety of math and logic fuctions for ffmpeg evaluation during runtime.
f_between
Return 1 if x is greater than or equal to min and lesser than or equal to max, 0 otherwise.
f_bitor
The results of the evaluation of x and y are converted to integers before executing the bitwise operation. Note that both the conversion to integer and the conversion back to floating point can lose precision. Beware of unexpected results for large numbers (usually 2^53 and larger).
f_ceil
Round the value of expression expr upwards to the nearest integer. For example, "ceil(1.5)" is "2.0".
f_floor
Round the value of expression expr downwards to the nearest integer. For example, "floor(-1.5)" is "-2.0".
f_gcd
Return f_the greatest common divisor of x and y. If both x and y are 0 or either or both are less than zero then behavior is undefined.
f_hypot
This function is similar to the C function with the same name; it returns "sqrt(xx + yy)", the length of the hypotenuse of a right triangle with sides of length x and y, or the distance of the point (x, y) from the origin.:
f_if
Evaluate x, and if the result is non-zero return the evaluation result of y, otherwise the evaluation result of z.
f_ifnot
Evaluate x, and if the result is zero return the evaluation result of y, otherwise the evaluation result of z.
f_ld
Load the value of the internal variable with index idx, which was previously stored with st(idx, expr). The function returns the loaded value.
f_print
Pf_rint the value of expression t with loglevel l. If l is not specified then a default log level is used. Return the value of the expression printed.:
f_random
Return a pseudo random value between 0.0 and 1.0. idx is the index of the internal variable used to save the seed/state, which can be previously stored with st(idx). To initialize the seed, you need to store the seed value as a 64-bit unsigned integer in the internal variable with index idx. For example, to store the seed with value 42 in the internal variable with index 0 and print a few random values:
f_randomi
Return a pseudo random value in the interval between min and max. idx is the index of the internal variable which will be used to save the seed/state, which can be previously stored with st(idx). To initialize the seed, you need to store the seed value as a 64-bit unsigned integer in the internal variable with index idx.
f_root
Find an input value for which the function represented by expr with argument ld(0) is 0 in the interval 0..max.
The expression in expr must denote a continuous function or the result is undefif_ned. ld(0) is used to represent the function input value, which means that the given expression will be evaluated multiple times with various input values that the expression can access through ld(0). When the expression evaluates to 0 then the corresponding input value will be returned.
f_round
Round the value of expression expr to the nearest integer. For example, "round(1.5)" is "2.0".
f_st
Store the value of the expression expr in an internal variable. idx specifies the index of the variable where to store the value, and it is a value ranging from 0 to 9. The function returns the value stored in the internal variable.
The stored value can be retrieved with ld(var).
Note: variables are currently not shared between expressions.
f_taylor
Evaluate a Taylor series at x, given an expression representing the ld(idx)-th derivative of a function at 0.
When the series does not converge the result is undefined.
ld(idx) is used to represent the derivative order in expr, which means that the given expression will be evaluated multiple times with various input values that the expression can access through ld(idx). If idx is not specified then 0 is assumed.
Note, when you have the derivatives at y instead of 0, taylor(expr, x-y) can be used.
f_trunc
Round the value of expression expr towards zero to the nearest integer. For example, trunc(-1.5)
is -1.0