Reference

pyffstream.ffmpeg

Helper functions for interacting with ffmpeg.

Functions include mimicking number/duration processing, probing files with ffprobe, and a utility class to deal with filters.

pyffstream.ffmpeg.ff_bin

A tuple that is the recommended way to specify the path to ffmpeg utilities. Can be overridden.

Type:

FFBin

class pyffstream.ffmpeg.FFBanner(ffversion, ffconfig, versions)
ffconfig: list[str]

Alias for field number 1

ffversion: str

Alias for field number 0

versions: dict[str, pyffstream.ffmpeg.FFVersion]

Alias for field number 2

class pyffstream.ffmpeg.FFBin(ffmpeg='ffmpeg', ffprobe='ffprobe', env=None)

An instance of a path to an ffmpeg binary.

Provides various helper properties to get information about the capabilities of the ffmpeg binary. Note that just because something was compiled into the binary it doesn’t mean it’s usable at runtime. This is the case for hardware support (e.g. nvidia) in particular.

ffmpeg

Path to ffmpeg binary.

Type:

str

ffprobe

Path to ffprobe binary.

Type:

str

env

Environmental variables to use with ffmpeg.

Type:

dict[str,str]

Parameters:
property aencoders: set[str]

Set of compiled-in audio encoders.

Return type:

set[str]

property build_config: list[str]

List of build config options.

Return type:

list[str]

property ffversion: str

String representing ffmpeg release version.

Note this might not always be sensible to use for simple comparison, for example in the case of versions compiled from git.

Return type:

str

property filters: set[str]

Set of filters compiled into ffmpeg instance.

property hwaccels: set[str]

Set of hwaccels compiled into ffmpeg version.

make_playlist(pathlist, directory, idxs=(0, 0), deep_probe=False, name='streamplaylist.txt')

Construct ffconcat playlist from path list.

Paths created are absolute, and the files are probed in parallel if needed to determine the duration.

Parameters:
  • pathlist (Iterable[Path]) – Ordered pathlist to construct ffconcat with.

  • directory (Path) – Directory to put the constructed playlist in.

  • idxs (Sequence[int]) – Tuple of (video, audio) stream index.

  • deep_probe (bool) – Whether to probe file deeply.

  • name (str) – Optional; name of playlist file.

Return type:

Path

Returns:

Path to created ffconcat playlist.

probe_json(entries, fileargs, streamtype=None, deep_probe=False, extraargs=None)

Probes a media file with ffprobe and returns results.

Generic function for probing a media file for information using ffmpeg’s ffprobe utility and returning its JSON.

Parameters:
  • entries (str) – Argument passed to the -show_entries flag in ffprobe.

  • fileargs (str | Iterable[str] | None) – String of the file you want to analyze. If additional args are needed to specify the input, accepts a list of args to pass on.

  • streamtype (str | None) – Optional; Argument to pass on to the -select_streams flag in ffprobe. Argument not passed if None.

  • deep_probe (bool) – Optional; Pass extra arguments to ffprobe in order to probe the file more deeply. This is useful for containers that can’t be lightly inspected.

  • extraargs (str | Iterable[str] | None) – Optional; A list of additional arguments to past to ffprobe during runtime. Can be used for example to request -sexagesimal formatting of duration fields.

Returns:

The query failed or returned “unknown” or “N/A”.

deserialized JSON: For raw probetype, the JSON returned after deserialization.

Return type:

None

probe_val(entry, fileargs, streamtype=None, probetype=ProbeType.STREAM, deep_probe=False, extraargs=None)

Wrapper for probe_vals to probe a single val.

Parameters:
  • entry (str) –

  • fileargs (str | Iterable[str] | None) –

  • streamtype (str | None) –

  • probetype (ProbeType) –

  • deep_probe (bool) –

  • extraargs (str | Iterable[str] | None) –

Return type:

str | None

probe_vals(entries, fileargs, streamtype=None, probetype=ProbeType.STREAM, deep_probe=False, extraargs=None)

Probes a media file with ffprobe and returns results.

Generic function for probing a media file for information using ffmpeg’s ffprobe utility. Returns individual values.

Parameters:
  • entries (Iterable[str]) – List of arguments passed to the -show_entries flag in ffprobe. If a non-raw streamtype is specified, then the argument may be the type field you want to query, for example the duration.

  • fileargs (str | Iterable[str] | None) – String of the file you want to analyze. If additional args are needed to specify the input, accepts a list of args to pass on.

  • streamtype (str | None) – Optional; Argument to pass on to the -select_streams flag in ffprobe. Argument not passed if None.

  • probetype (ProbeType) – Optional; One of STREAM, TAGS, DISPOSITION, FORMAT; query file for metadata of selected probetype and streamtype and return the requested entries of the first matching stream.

  • deep_probe (bool) – Optional; Pass extra arguments to ffprobe in order to probe the file more deeply. This is useful for containers that can’t be lightly inspected.

  • extraargs (str | Iterable[str] | None) – Optional; A list of additional arguments to past to ffprobe during runtime. Can be used for example to request -sexagesimal formatting of duration fields.

Returns:

None: The query failed or returned “unknown” or “N/A”.

str: The value of the requested query.

Return type:

list of values in order of entries iterable containing

Raises:

ValueError – Invalid probetype was passed.

property protocols: FFProtocols

A FFProtocols of compiled in input/output protocols.

property sencoders: set[str]

Set of compiled-in subtitle encoders.

Return type:

set[str]

property vencoders: set[str]

Set of compiled-in video encoders.

Return type:

set[str]

property version: dict[str, pyffstream.ffmpeg.FFVersion]

Dict of FFVersions indexed by component name.

Return type:

dict[str, FFVersion]

class pyffstream.ffmpeg.FFEncoders(vencoders, aencoders, sencoders)
aencoders: set[str]

Alias for field number 1

sencoders: set[str]

Alias for field number 2

vencoders: set[str]

Alias for field number 0

class pyffstream.ffmpeg.FFProbeJSON
class pyffstream.ffmpeg.FFProtocols(inputs, outputs)
inputs: set[str]

Alias for field number 0

outputs: set[str]

Alias for field number 1

class pyffstream.ffmpeg.FFVersion(*args)

Holds a ffmpeg component version.

Parameters:

args (str | int | FFVersion) –

class pyffstream.ffmpeg.Filter(filt, *filtopts, src=None, dst=None)

A single ffmpeg filter.

Collects helper methods for constructing and rendering out ffmpeg filter strings for use with the CLI.

Parameters:
  • filt (str | Filter) –

  • filtopts (str) –

  • src (Sequence[str | int | None] | None) –

  • dst (Sequence[str | int | None] | None) –

classmethod complex_join(filterlist, startkey='v', endkey='b', basekey='c')

Combine filters in a way compatible with -filter_complex.

Parameters:
  • filterlist (Sequence[Filter | str]) –

  • startkey (str) –

  • endkey (str) –

  • basekey (str) –

Return type:

str

classmethod full_escape(val)

Do full escaping needed for complex filter graph in ffmpeg.

https://ffmpeg.org/ffmpeg-filters.html#Notes-on-filtergraph-escaping

Parameters:

val (str) –

Return type:

str

static vf_join(filterlist)

Combine filters in a way compatible with -af/-vf.

Parameters:

filterlist (Sequence[str | Filter]) –

Return type:

str

class pyffstream.ffmpeg.ProbeType(value)

An enumeration.

class pyffstream.ffmpeg.Progress

Assists in monitoring the progress output of an ffmpeg encode.

pyffstream.ffmpeg.duration(timestamp)

Processes ffmpeg duration string into time in seconds.

https://ffmpeg.org/ffmpeg-utils.html#Time-duration

Parameters:

timestamp (str | float | int) –

Return type:

float

pyffstream.ffmpeg.format_q_tuple(init_tuple, is_stream)

Format the entries arg for raw JSON queries to the probefile.

This corresponds to the -show_entries flag in ffprobe and can be used generically to format arguments to it.

Parameters:
  • init_tuple (InitTuple | None) – If querying a stream, a 3-tuple of the stream values, stream tags, and stream dispositions to query ffprobe for. If querying a format, a list of the format values to query. Can be None.

  • is_stream (bool) – A boolean indicating whether or not init_tuple is a 3-tuple for a stream or a list for a format.

Return type:

str

Returns:

A formatted query for -show_entries in ffprobe. An empty string if init_tuple is None.

pyffstream.ffmpeg.num(val)

Process input into float in a way that mimics ffmpeg.

Method follows ffmpeg’s numerical options. All whitespace is stripped, then valid input is a number followed optionally with an SI prefix that may be appended with an i modifier that indicates the SI prefix is in powers of 1024 instead of 1000. Finally, the number may end in a B indicating it is to be multiplied by 8. The optional ffmpeg utility ffeval may be used to validate the output of this function.

Parameters:

val (str) –

Return type:

float

pyffstream.ffmpeg.single_quote(unescaped)

Return a single-quote escaped string from input.

Parameters:

unescaped (object) –

Return type:

str

pyffstream.encode

Classes and functions for ffmpeg encoding.

class pyffstream.encode.EncType(value)

An enumeration.

class pyffstream.encode.FileOpts(main, subtitle, fpath, sfpath, allpaths)
allpaths: Sequence[Path]

Alias for field number 4

fpath: Path

Alias for field number 2

main: MutableSequence[str]

Alias for field number 0

sfpath: Path

Alias for field number 3

subtitle: MutableSequence[str]

Alias for field number 1

class pyffstream.encode.FilterList

Thread-safe class for storing and getting ffmpeg filters.

get(k, default=None)

An implementation of the get method as in dicts.

Parameters:
Return type:

str | None

if_exists(key)

Return 1-tuple of filter at key if it exists, else 0-tuple.

The intent is to use this function starred in-line like *if_exists(key) when defining a list to simplify creation of filter lists.

Parameters:

key (str) –

Return type:

tuple[str] | tuple[()]

class pyffstream.encode.StaticEncodeVars(tempdir, verbosity=0, api_url='', api_key='', samplerate='48000', endpoint='127.0.0.1:9998', target_w='1920', target_h='1080', framerate='24/1', framerate_multiplier=Fraction(1, 1), scale_w='1920', scale_h='1080', bound_w='1920', bound_h='1080', kf_target_sec=5.0, clip_length=None, vencoder=VEncoder(name='libx264', codec='h264', flag_function=<function get_libx264_flags>, presets=['placebo', 'veryslow', 'slower', 'slow', 'medium', 'fast', 'faster', 'veryfast', 'superfast', 'ultrafast'], default_preset='medium', tenbit=False, type=<EncType.SOFTWARE: 1>, multipass=True), aencoder='aac', encode_preset=None, encode_tune=None, realtime=False, vstandard='h264', astandard='aac', include_audio=True, protocol='srt', vbitrate='6M', max_vbitrate='0', rc_mode='cbr', abitrate='256k', chlayout='stereo', start_delay='30', end_pad=True, end_delay='600', timestamp=None, suboffset=None, cleanborders=None, crop_ts='600', crop_len='60', target_i='-19', target_lra='11.0', target_tp='-1.0', pix_fmt='yuv420p', subfile_provided=False, text_subs=True, subfilter_list=<factory>, kf_int='0', min_kf_int='0', bufsize='0', kf_sec='0', latency_target='0', afilters='', filter_complex='', input_flags=<factory>, encode_flags=<factory>, filter_flags=<factory>, output_flags=<factory>, shader_list=<factory>, ff_flags=<factory>, srt_passphrase='', srt_latency=5.0, ff_verbosity_flags=<factory>, ff_deepprobe_flags=<factory>, placebo_opts=<factory>, sw_filters=<factory>, vencoder_params=<factory>, copy_audio=False, copy_video=False, use_timeline=False, hwaccel=True, subs=False, deep_probe=False, vindex=0, aindex=0, sindex=None, outfile=None, npass=None, passfile=None, wait=False, overwrite=False, fifo=False, soxr=False, zscale=False, slowseek=False, live=False, obs=False, vulkan=False, vgop=False, trust_vulkan=False, vulkan_device=-1, decimate_target='24/1', is_playlist=False, eightbit=False, cropsecond=False, subcropfirst=False, picsubscale='bicubic', delay_start=False, deinterlace=False, crop=False, upscale=False, anormalize=False, normfile=None, dynamicnorm=False, fix_start_time=True, pyffserver=False, ffprogress=<factory>)

Class holding general encoding parameters.

Needs to be passed to an encode session to initialize it.

Parameters:
  • tempdir (pathlib.Path) –

  • verbosity (int) –

  • api_url (str) –

  • api_key (str) –

  • samplerate (str) –

  • endpoint (str) –

  • target_w (str) –

  • target_h (str) –

  • framerate (str) –

  • framerate_multiplier (fractions.Fraction) –

  • scale_w (str) –

  • scale_h (str) –

  • bound_w (str) –

  • bound_h (str) –

  • kf_target_sec (float) –

  • clip_length (str | None) –

  • vencoder (VEncoder) –

  • aencoder (str) –

  • encode_preset (str | None) –

  • encode_tune (str | None) –

  • realtime (bool) –

  • vstandard (str) –

  • astandard (str) –

  • include_audio (bool) –

  • protocol (str) –

  • vbitrate (str) –

  • max_vbitrate (str) –

  • rc_mode (str) –

  • abitrate (str) –

  • chlayout (str) –

  • start_delay (str) –

  • end_pad (bool) –

  • end_delay (str) –

  • timestamp (str | None) –

  • suboffset (str | None) –

  • cleanborders (list[int] | None) –

  • crop_ts (str) –

  • crop_len (str) –

  • target_i (str) –

  • target_lra (str) –

  • target_tp (str) –

  • pix_fmt (str) –

  • subfile_provided (bool) –

  • text_subs (bool) –

  • subfilter_list (Sequence[ffmpeg.Filter]) –

  • kf_int (str) –

  • min_kf_int (str) –

  • bufsize (str) –

  • kf_sec (str) –

  • latency_target (str) –

  • afilters (str) –

  • filter_complex (str) –

  • input_flags (MutableSequence[str]) –

  • encode_flags (MutableSequence[str]) –

  • filter_flags (MutableSequence[str]) –

  • output_flags (MutableSequence[str]) –

  • shader_list (MutableSequence[str]) –

  • ff_flags (MutableSequence[str]) –

  • srt_passphrase (str) –

  • srt_latency (float) –

  • ff_verbosity_flags (Sequence[str]) –

  • ff_deepprobe_flags (Sequence[str]) –

  • placebo_opts (Sequence[str]) –

  • sw_filters (Sequence[str]) –

  • vencoder_params (Sequence[str]) –

  • copy_audio (bool) –

  • copy_video (bool) –

  • use_timeline (bool) –

  • hwaccel (bool) –

  • subs (bool) –

  • deep_probe (bool) –

  • vindex (int) –

  • aindex (int) –

  • sindex (int | None) –

  • outfile (pathlib.Path | None) –

  • npass (int | None) –

  • passfile (pathlib.Path | None) –

  • wait (bool) –

  • overwrite (bool) –

  • fifo (bool) –

  • soxr (bool) –

  • zscale (bool) –

  • slowseek (bool) –

  • live (bool) –

  • obs (bool) –

  • vulkan (bool) –

  • vgop (bool) –

  • trust_vulkan (bool) –

  • vulkan_device (int) –

  • decimate_target (str) –

  • is_playlist (bool) –

  • eightbit (bool) –

  • cropsecond (bool) –

  • subcropfirst (bool) –

  • picsubscale (str) –

  • delay_start (bool) –

  • deinterlace (bool) –

  • crop (bool) –

  • upscale (bool) –

  • anormalize (bool) –

  • normfile (pathlib.Path | None) –

  • dynamicnorm (bool) –

  • fix_start_time (bool) –

  • pyffserver (bool) –

  • ffprogress (ffmpeg.Progress[str]) –

classmethod from_args(args)

Constructor to make StaticEncodeVars from passed args.

Parameters:

args (Namespace) –

Return type:

StaticEncodeVars

class pyffstream.encode.StatusCode(value)

An enumeration.

class pyffstream.encode.StyleFile(names, lines, insert_index)
insert_index: int

Alias for field number 2

lines: MutableSequence[str]

Alias for field number 1

names: MutableSequence[str]

Alias for field number 0

class pyffstream.encode.VEncoder(name, codec, flag_function, presets=<factory>, default_preset=None, tenbit=False, type=EncType.SOFTWARE, multipass=False)
Parameters:
  • name (str) –

  • codec (str) –

  • flag_function (Callable[[EncodeSession], list[str]]) –

  • presets (Iterable[object]) –

  • default_preset (str | None) –

  • tenbit (bool) –

  • type (EncType) –

  • multipass (bool) –

pyffstream.encode.close_futures(futures)

Wait on futures in list, then raise any exceptions in them.

Parameters:

futures (Iterable[Future[Any]]) –

Return type:

None

pyffstream.cli

CLI frontend for encoding and streaming.

class pyffstream.cli.ConfName(file_name, arg_name)
arg_name: str

Alias for field number 1

file_name: str

Alias for field number 0

class pyffstream.cli.DefaultConfig(pyffserver=False, protocol='srt', vbitrate='6M', max_vbitrate='0', abitrate='256k', aencoder='aac', vencoder='libx264', endpoint='127.0.0.1:9998', api_url='', api_key='', soxr=False, preset=<factory>, zscale=False, vulkan=False, trust_vulkan=False, vgop=False, vulkan_device=-1, hwaccel=True, height=1080, shader_list=<factory>, kf_target_sec=5.0, srt_latency=5.0, ffmpeg_bin='ffmpeg', ffprobe_bin='ffprobe', env=<factory>)

Holds config file values.

Used to determine the default CLI parameters after processing config from files.

Parameters:
  • pyffserver (bool) –

  • protocol (str) –

  • vbitrate (str) –

  • max_vbitrate (str) –

  • abitrate (str) –

  • aencoder (str) –

  • vencoder (str) –

  • endpoint (str) –

  • api_url (str) –

  • api_key (str) –

  • soxr (bool) –

  • preset (dict[str, str | None]) –

  • zscale (bool) –

  • vulkan (bool) –

  • trust_vulkan (bool) –

  • vgop (bool) –

  • vulkan_device (int) –

  • hwaccel (bool) –

  • height (int) –

  • shader_list (list[str]) –

  • kf_target_sec (float) –

  • srt_latency (float) –

  • ffmpeg_bin (str) –

  • ffprobe_bin (str) –

  • env (dict[str, str]) –

pyffstream.cli.download_win_ffmpeg(dltype='git')

Download and install ffmpeg for windows in user_data_path.

The current ffmpeg in the location is replaced if already there. User data path is determined from platformdirs.

Parameters:

dltype (str) –

Return type:

bool

pyffstream.cli.get_parserconfig(reproducible=True)

Return parser and config used.

Parameters:

reproducible (bool) –

Return type:

tuple[ArgumentParser, DefaultConfig]

pyffstream.cli.get_stream_list(streamtype, q_tuple, myfileargs, deep_probe=False)

Make and return tuples of (key,val) pairs for each stream.

Parameters:
Return type:

list[list[tuple[str, str]]]

pyffstream.cli.main()

Process config and CLI arguments then send off for processing.

Return type:

None

pyffstream.cli.parse_files(args, parser)

Process input arguments and send them off processing.

Parameters:
Return type:

None

pyffstream.cli.print_info(fopts, *, verbosity=0, deep_probe=False)

Prints to console formatted information about the input file.

Output is nicely formatted for console usage using rich tables.

Parameters:
  • fopts (FileOpts) – The file to print information about.

  • verbosity (int) – Print extra fields based on size.

  • deep_probe (bool) – Whether or not to probe the file deeply.

Return type:

None

pyffstream.cli.process_file(fpath, args, stream_flist)

Format input arguments needed for a file and send to output.

Parameters:
Return type:

None

pyffstream.cli.set_console_logger(verbosity, logfile)

Set loglevel.

Parameters:
Return type:

None

pyffstream.cli.setup_pyffserver_stream(fv)

Communicate with a pyffserver API to set up encode session.

Parameters:

fv (EncodeSession) –

Return type:

None

pyffstream.cli.start_stream(fv)

Start and track the actual encode.

Parameters:

fv (EncodeSession) –

Return type:

None

pyffstream.cli.status_wait(fv, futures)

Wait on remaining background processes while showing status.

Parameters:
  • fv (EncodeSession) –

  • futures (Iterable[Future[Any]]) –

Return type:

None

pyffstream.cli.stream_file(fopts, args)

Manage calculating of all stream parameters.

Parameters:
Return type:

None

pyffstream.cli.win_set_local_ffmpeg(dltype, env)

Set the ffmpeg instance to the app-local Windows copy.

If ffmpeg is not already available in user_data_path, offer to download it from a public repository.

Parameters:
Return type:

None