Skip to content

API reference

The public API, generated from its docstrings. For how to use it, see Writing an application.

Player

mixtape.Player

Drive a Gst.Pipeline from an asyncio loop.

The player reads the pipeline's bus on the loop it is attached to, which happens lazily on the first await of any of its methods. Subclass it and override the state methods, or react to bus messages with add_handler and events().

Its controls and state are described by describe(): the properties of the named elements (all of them with expose_all), the aliases declared with prop(), the computed properties declared with @prop, the commands declared with @command, and the built-ins. The features it enables add their own, as feature.name.

features class-attribute

features: Sequence[str | type[Feature]] = ()

The features every instance enables, as "name,key=value" strings or classes: never instances, which would be shared. The features argument adds to them and wins by name.

description class-attribute

description: str | None = None

The pipeline description of a subclass that carries its own, for mixtape run

position_interval class-attribute

position_interval: float = 0.25

Seconds between the reads that publish Position to events(position=True) streams

state_timeout class-attribute

state_timeout: float = 5.0

Seconds a change down to READY or NULL may take: a streaming thread that hangs blocks it, and the player then calls the pipeline stuck until the change finishes after all

shape_interval class-attribute

shape_interval: float = 0.1

Seconds the player gathers changes to the pipeline's shape (elements, pads, links, caps) before it publishes them as one GraphChanged, and ModelChanged when they change it

bus property

bus: Bus

The pipeline's bus

state property

state: State

The current pipeline state, asked from the pipeline

pending property

pending: State

The pending pipeline state, VOID_PENDING when not changing

loop property

loop: AbstractEventLoop | None

The asyncio loop the player is attached to

error property

error: PlayerPipelineError | None

The first error since the last change to another state than NULL, which stopped the pipeline, until the next such change

enabled_features property

enabled_features: Mapping[str, Feature]

The features of this player by name, in the order they were enabled

sinks property

sinks: list[Element]

Returns all sink elements

sources property

sources: list[Element]

Return all source elements

elements property

elements: list[Element]

Return all pipeline elements

from_description classmethod

from_description(description: str, *, expose_all: bool = False, features: Iterable[FeatureSpec] = ()) -> Self

Build a player from a gst-launch style pipeline description.

The features are prepared first: before GStreamer is initialised, so they can set its environment.

run classmethod

run(description_or_pipeline: str | Pipeline, timeout: float | None = None) -> None

Play a pipeline until EOS and tear it down, for scripts.

Raises PlayerPipelineError on a pipeline error and TimeoutError when timeout seconds pass first.

get_elements_by_gtype

get_elements_by_gtype(gtype: Any) -> list[Gst.Element]

Return all elements in pipeline that match gtype

setup

setup() -> None

Attach to the running loop. Idempotent; every async method calls it.

teardown

teardown() -> None

Set the pipeline to NULL and detach from the loop. Idempotent, re-usable after.

A pipeline that fails to stop, or does not within state_timeout, is left as it is with a warning, and kept on purpose for the life of the process: GStreamer cannot free an element outside NULL. The features detach once it is in NULL, so they see what it left.

call_soon_threadsafe

call_soon_threadsafe(callback: Callable[..., object], *args: object) -> None

Run callback(*args) on the player's loop, from any thread.

run_coroutine_threadsafe

run_coroutine_threadsafe(coro: Coroutine[Any, Any, T]) -> concurrent.futures.Future[T]

Run coro on the player's loop, from any thread.

set_state async

set_state(state: State) -> Gst.StateChangeReturn

Set the pipeline state, returning once the change is complete.

pause async

pause() -> Gst.StateChangeReturn

Pause the pipeline.

play async

play() -> Gst.StateChangeReturn

Play the pipeline.

stop async

stop(eos: bool = False, timeout: float | None = 5.0) -> None

Set the pipeline to NULL, after an EOS when eos and it is playing.

A paused pipeline cannot carry the EOS to its sinks (waiting for it blocks), and one at its EOS already sends no second one: both stop at once.

eos async

eos(timeout: float | None = 5.0) -> None

Send an EOS event and wait for the EOS message it causes, while playing, for up to timeout seconds: a streaming thread that hangs never carries it to the sinks.

seek

seek(position: NonNegativeFloat) -> None

Seek to a position in seconds, flushing.

send_eos async

send_eos(timeout: float | None = None) -> None

Send an EOS event and wait for the EOS message it causes.

play_until_eos async

play_until_eos() -> None

Play and return on the next EOS; raise PlayerPipelineError on an error.

A pipeline still at the EOS of an earlier run restarts from READY.

describe

describe() -> PlayerSpec

A snapshot of the player's commands, properties and exposed elements.

graph

graph() -> GraphSpec

A snapshot of the pipeline's elements and the links between them.

get

get(path: str) -> Any

Read a property by path: a built-in, a computed property (feature.name), an alias or element.property, as JSON-friendly.

set async

set(path: str, value: Any) -> None

Validate value and set the property. Nothing changes when it is rejected.

invoke async

invoke(name: str, /, **args: Any) -> Any

Call the command name with validated args and return its result.

Built-in commands return None, as their specs say.

notify

notify(path: str) -> None

Publish the current value of the computed property path (feature.name) as a PropertyChanged with no element. On the loop thread only: the events are not thread safe, call_soon_threadsafe brings a call from another thread there.

exposed_elements

exposed_elements() -> dict[str, Gst.Element]

The elements the model exposes by key: the named ones, or all with expose_all. The pipeline itself counts too: playbin name=pb is the pipeline.

events

events(position: bool = False) -> events.EventStream

Subscribe to the events published from now on.

With position, the stream also gets Position events: the current one at once, then one whenever the position or duration changes, read every position_interval.

add_handler

add_handler(message_type: MessageType, callback: MessageCallback) -> Callable[[], None]

Call callback(message) on the loop for bus messages of message_type, after the built-in handling. Returns a function that removes it again.

Feature

mixtape.Feature

A plugin of a Player. Subclass it with a name, the options as __init__ keyword parameters, and @command methods and @prop getters for its model.

Getters and commands must work when the player is not set up (mixtape inspect reads every property), so a feature that needs the loop answers from what it has.

name instance-attribute

name: str

Its name in the model (name.command) and the entry point; [a-z][a-z0-9_]*

requires class-attribute

requires: tuple[str, ...] = ()

GStreamer plugin features (elements or tracers) the player needs to enable it

own_tracers class-attribute

own_tracers: tuple[str, ...] = ()

GStreamer tracers it reads itself: gst:NAME of one is refused beside it, as both would use the one tracer of the process

player class-attribute instance-attribute

player: Player | None = None

The player it is attached to: set just before attach, None again after detach

from_options classmethod

from_options(**raw: Any) -> Self

The feature with its options validated, strings from a command line included ("0.5" is a float). Raises FeatureError for a rejected one.

prepare

prepare() -> None

Called before GStreamer is initialised, when the player builds the pipeline from a description: the place to set environment variables such as GST_TRACERS.

initialised

initialised() -> None

Called once GStreamer is initialised (by the player or before), and before the player builds its pipeline from a description: the place for what has to be in place before an element is made, such as a logger. Raise FeatureError if the feature cannot work.

check

check(player: Player) -> None

Called when the player is built, after GStreamer is initialised and requires is met, before it is set up: raise FeatureError if the feature cannot work here, so the player is not built rather than failing later in attach.

attach

attach(player: Player) -> None

Called by Player.setup, on the running loop. One that raises gets no detach: it cleans up after itself, and the features attached before it are detached.

detach

detach(player: Player) -> None

Called by Player.teardown, once the pipeline is in NULL. An exception is logged and teardown goes on.

notify

notify(prop: str) -> None

Publish the current value of its computed property prop to the player's event streams. Does nothing while detached. On the loop thread only.

prop and command

mixtape.prop

prop(target: Callable[[Any], T]) -> Computed[T]
prop(target: str, *, label: str | None = None, description: str | None = None) -> Any
prop(target: str | Callable[[Any], Any], *, label: str | None = None, description: str | None = None) -> Any

Declare an alias of the element property target ("enc.bitrate") on a Player.

As a decorator of a method (@prop) it declares a read-only computed property instead, typed by the method's return hint and described by its docstring.

mixtape.command

command(method: F) -> F

Mark a sync or async method of a Player as a command.

Events

mixtape.events

Events a Player publishes, and the stream subscribers read them from.

Event dataclass

Base class of every event published by a Player.

StateChanged dataclass

Bases: Event

The pipeline itself changed state.

Eos dataclass

Bases: Event

End of stream.

Error dataclass

Bases: Event

A pipeline error. The player has already set the pipeline to NULL.

Warning dataclass

Bases: Event

A pipeline warning.

PropertyChanged dataclass

Bases: Event

A property changed: an exposed element's, on whatever thread changed it, or a computed one, published on the loop by Player.notify.

path is the element path (enc.bitrate, or a.enc.bitrate when the element name is not unique); aliases map to it via PropSpec.target. The element's key is fixed when the player starts watching it. A computed property (feature.name) has no element: element and property are None.

value instance-attribute
value: Any

The JSON-friendly value, as Player.get returns it

Position dataclass

Bases: Event

The playback position or duration changed, in seconds as Player.get returns them.

Only streams made with Player.events(position=True) receive it.

GraphChanged dataclass

Bases: Event

The pipeline's shape changed: elements came or went (decodebin's), pads came or went, links or caps changed. The changes of Player.shape_interval come as one event, published only when the graph differs from the one before.

graph instance-attribute
graph: GraphSpec

The graph as of now, as Player.graph returns it

ModelChanged dataclass

Bases: Event

The elements the model exposes changed, or their keys did (a namesake in another bin makes q a.q). Published with the GraphChanged of the same change.

model instance-attribute
model: PlayerSpec

The model as of now, as Player.describe returns it

Message dataclass

Bases: Event

Any bus message, published after the specific event (if any) for it.

EventStream

Async iterator over the events published after it was created.

It ends when the player is torn down or close() is called, after the events already queued have been read.

positions instance-attribute
positions: bool = positions

Whether it also receives Position events

close
close() -> None

Stop receiving events; the iteration ends once the queued ones are read.

Broadcast

Fan out events to any number of EventStream subscribers.

wants_positions property
wants_positions: bool

Whether an open stream receives Position events

close
close() -> None

End every subscriber's iteration.

Exceptions

mixtape.exceptions

MixTapeError

Bases: Exception

Mixtape exception base clase

PlayerNotConfigured

Bases: MixTapeError

The player is not attached to the running asyncio loop

PlayerDescriptionError

Bases: MixTapeError

A pipeline description could not be parsed

PlayerSetStateError

Bases: MixTapeError

Setting the pipeline state has failed

PlayerPipelineError

Bases: MixTapeError

Error originating from Gst Pipeline

source instance-attribute
source = source

Name of the element that posted the error

gerror instance-attribute
gerror = gerror

The GLib.Error of the bus message

ModelError

Bases: MixTapeError

Base of the errors of the declarative model: properties and commands

UnknownNameError

Bases: ModelError

A property path or command name does not exist, or is not exposed

InvalidValueError

Bases: ModelError

A value or an argument was rejected, and nothing was changed

errors instance-attribute
errors: list[Any] = errors or []

Pydantic's error list when validation failed, else empty

NotReadableError

Bases: ModelError

The property cannot be read

NotWritableError

Bases: ModelError

The property cannot be written: it is read-only or construct-only

FeatureError

Bases: ModelError

A feature could not be resolved, configured or enabled

CommandError

Bases: ModelError

A built-in command could not do what was asked

HTTP interface

mixtape.interfaces.http.serve async

serve(player: Player, host: str, port: int, *, log_level: int | str = 'warning') -> AsyncIterator[Listening]

Serve player over HTTP in the running loop until the block ends.

It returns once the server listens, with where it does (port may be 0). It raises OSError when the address cannot be bound. log_level is uvicorn's own; its loggers use the logging configuration of the process.

mixtape.interfaces.http.create_app

create_app(player: Player, *, host: str = '127.0.0.1') -> FastAPI

The app of player. host is the address the server binds to: on a loopback one, requests must also name this machine in their Host header (see security).