Writing an application
mixtape is a library first: mixtape run is a small program built on it. This page builds
applications on the same pieces: a Player that drives a
pipeline from an asyncio loop, the events it publishes, a model of its properties and commands
that the command line and the HTTP API read, and features that add to that
model.
It starts with the smallest programs, then builds one application of its own, a test card: a
Player subclass with a pattern to choose, a frame counter and a command. Errors, events and
features follow as topics.
The names are in mixtape (Feature,
prop, command),
mixtape.events and
mixtape.exceptions; the API reference lists
them all.
Play a pipeline
Player.from_description builds a player from a
gst-launch-1.0 description. It needs no
running loop: the first await on the player attaches it to the loop that is running, and
async with tears it down, setting the pipeline to NULL, when the block ends.
%%{init: {"flowchart": {"nodeSpacing": 20, "rankSpacing": 24, "subGraphTitleMargin": {"top": 4, "bottom": 12}}}}%%
flowchart LR
%% lifecycle
p0n0["videotestsrc"]
p0n1["fakesink"]
p0n0 --> p0n1
import asyncio
from mixtape import Player
async def main() -> None:
async with Player.from_description("videotestsrc is-live=true ! fakesink") as player:
await player.play()
print(player.state.value_nick)
# > playing
await player.pause()
print(player.state.value_nick)
# > paused
print(player.state.value_nick)
# > null
asyncio.run(main())
Source: examples/lib_lifecycle.py · tested by test_play_pause_and_teardown
The # > comments under the prints are what the program prints; the tests check them.
play(), pause(),
ready() and stop() return when the pipeline has reached
the state, not before. stop() sets it to NULL, after an EOS with stop(eos=True). A player that
is torn down can be used again. Without async with, call
player.setup() on the loop to attach it and
player.teardown() to detach it.
Until the end of the stream
await player.play_until_eos() plays and returns
on the next EOS. The pipeline is still playing
then; calling it again plays the stream again, from READY:
import asyncio
from mixtape import Player
async def main() -> None:
async with Player.from_description("videotestsrc num-buffers=100 ! fakesink") as player:
for run in (1, 2):
await player.play_until_eos()
print(f"run {run}: {player.state.value_nick} at the end of the stream")
# > run 1: playing at the end of the stream
# > run 2: playing at the end of the stream
asyncio.run(main())
Source: examples/lib_until_eos.py · tested by test_play_until_eos_plays_again_from_the_end
Player.run is the shortcut for a script: it plays a
description (or a Gst.Pipeline) until EOS, tears the player down and returns. It starts the
loop itself, so it cannot be called from a coroutine. It raises TimeoutError when timeout
seconds pass first, and PlayerPipelineError
when the pipeline fails (see When it goes wrong).
from mixtape import Player
Player.run("videotestsrc num-buffers=100 ! fakesink", timeout=30)
print("done")
# > done
Source: examples/lib_run.py · tested by test_run_plays_until_eos
From a pipeline you built
A pipeline made in code, with Gst.ElementFactory and link, goes to Player(pipeline).
GStreamer has to be initialised before the elements are made, so call Gst.init(None) first.
from_description does it for you, and wraps a description that is a single element in a
pipeline.
%%{init: {"flowchart": {"nodeSpacing": 20, "rankSpacing": 24, "subGraphTitleMargin": {"top": 4, "bottom": 12}}}}%%
flowchart LR
%% dynamic
p0n0["<b>src</b><br>videotestsrc"]
p0n1["<b>sink</b><br>fakesink"]
p0n0 --> p0n1
import asyncio
import gi
gi.require_version("Gst", "1.0")
from gi.repository import Gst
from mixtape import Player
def build() -> Gst.Pipeline:
Gst.init(None)
pipeline = Gst.Pipeline.new("dynamic")
src = Gst.ElementFactory.make("videotestsrc", "src")
src.set_property("num-buffers", 30)
sink = Gst.ElementFactory.make("fakesink", "sink")
pipeline.add(src)
pipeline.add(sink)
src.link(sink)
return pipeline
async def main() -> None:
async with Player(build()) as player:
print("elements:", ", ".join(player.describe().elements))
# > elements: dynamic, src, sink
print("links:", [(link.source, link.sink) for link in player.graph().links])
# > links: [('src', 'sink')]
await player.play_until_eos()
print("played")
# > played
asyncio.run(main())
Source: examples/lib_dynamic.py · tested by test_a_player_for_a_pipeline_built_in_code
Only elements with a name of your own are in the model:
describe().elements lists the
pipeline, src and sink here, and not videotestsrc0. Give a name to what you want to
read and set, or pass expose_all=True to expose every element.
Subclass Player
Subclass Player for an application of your own: its pipeline, its properties, its commands. The
test card has a videotestsrc and a fakesink, a pattern to choose, a count of the frames
that reached the sink and a command to show a pattern.
%%{init: {"flowchart": {"nodeSpacing": 20, "rankSpacing": 24, "subGraphTitleMargin": {"top": 4, "bottom": 12}}}}%%
flowchart LR
%% testcard
p0n0["<b>src</b><br>videotestsrc"]
p0n1["<b>sink</b><br>fakesink"]
p0n2["video/x-raw<br>width=320<br>height=240"]
p0n0 --> p0n2
p0n2 --> p0n1
from typing import Any, Literal
import gi
gi.require_version("Gst", "1.0")
from gi.repository import Gst
from mixtape import Player, command, prop
Pattern = Literal["smpte", "ball", "snow"]
class Testcard(Player):
description = (
"videotestsrc name=src is-live=true ! video/x-raw,width=320,height=240 ! fakesink name=sink"
)
pattern = prop("src.pattern", description="The test pattern")
def __init__(self, pipeline: Gst.Pipeline, **kwargs: Any) -> None:
super().__init__(pipeline, **kwargs)
self._frames = 0
pad = self.pipeline.get_by_name("sink").get_static_pad("sink")
pad.add_probe(Gst.PadProbeType.BUFFER, self._on_buffer)
async def play(self) -> Gst.StateChangeReturn:
self._frames = 0
return await super().play()
@prop
def frames(self) -> int:
"""Frames shown since play() was called"""
return self._frames
@command
async def show(self, pattern: Pattern = "smpte") -> str:
"""Show a test pattern."""
await self.set("pattern", pattern)
return pattern
def _on_buffer(self, pad: Gst.Pad, info: Gst.PadProbeInfo) -> Gst.PadProbeReturn:
# a streaming thread: count on the loop, which publishes
self.call_soon_threadsafe(self._count)
return Gst.PadProbeReturn.OK
def _count(self) -> None:
self._frames += 1
if self._frames % 10 == 0:
self.notify("frames")
Source: examples/testcard.py · tested by test_the_test_card_player
What each part does:
descriptionis the pipeline of the class.Testcard.from_description(Testcard.description)builds it, and so domixtape run examples/testcard.py:Testcardandmixtape inspect examples/testcard.py:Testcard. A subclass with its own__init__takes the pipeline and passes the keyword arguments on (expose_all,features) tosuper().__init__.prop("src.pattern")declares an alias of an element property:patternin the model, with the type, the range and the value ofsrc.pattern, and a description of your own (and alabelfor the page). Readingcard.patterniscard.get("pattern"). A property is set withawait card.set("pattern", "ball"), which validates the value and changes nothing when it is rejected. A typo in the target fails when the player is built.@propon a method declares a read-only property that the method computes. Its return type hint is the type in the model, and a missing one fails when the class is defined. The first line of its docstring is the description.self.notify("frames")publishes its current value as aPropertyChangedevent.@commandon a method, sync or async, declares a command. The type hints of its parameters are the types of its arguments, and a default makes an argument optional.Literalis an enumeration. The arguments are validated before the method runs, and the return hint is the type of the result. It takes no*argsor**kwargs. The built-inplay,pause,stop,eosandseekare commands of every player, and a command calls your override of a method such asplay.- A pad probe, a signal handler or a callback of an element runs on a GStreamer thread, where
the loop's objects are off limits.
player.call_soon_threadsafe(callback, *args)runs a function on the loop, andplayer.run_coroutine_threadsafe(coroutine)runs a coroutine there and returns aconcurrent.futures.Futurewith its result. The probe uses the first: it counts each frame on the loop, which also publishes the count, asnotifyis for the loop thread only.
describe() returns the player's model as a pydantic model (describe().model_dump_json() is
JSON with JSON Schema for every type), get(path) reads a
property, set(path, value) sets one and
invoke(name, **arguments) runs a command: the calls that
the command line and the HTTP API make. A name that does not exist is an
UnknownNameError, a rejected value or
argument an InvalidValueError, and a
property that cannot be written a
NotWritableError.
import asyncio
from mixtape.events import PropertyChanged
from mixtape.exceptions import InvalidValueError
async def main() -> None:
async with Testcard.from_description(Testcard.description) as card:
spec = card.describe()
print("commands:", ", ".join(sorted(spec.commands)))
# > commands: eos, pause, play, seek, show, stop
print("properties:", ", ".join(sorted(spec.properties)))
# > properties: duration, frames, pattern, position, state
print("pattern:", card.get("pattern"))
# > pattern: smpte
events = card.events()
await card.play()
await card.set("pattern", "ball")
print("show:", await card.invoke("show", pattern="snow"))
# > show: snow
# from a thread of your own, run a coroutine on the player's loop
def from_a_thread() -> str:
return card.run_coroutine_threadsafe(card.invoke("show", pattern="smpte")).result()
print("from a thread:", await asyncio.to_thread(from_a_thread))
# > from a thread: smpte
try:
await card.invoke("show", pattern="plaid")
except InvalidValueError as exc:
print("rejected:", exc)
# > rejected: Invalid arguments for 'show': pattern: Input should be 'smpte', 'ball' or 'snow'
async for event in events:
if isinstance(event, PropertyChanged) and event.path == "frames":
print("frames:", event.value)
# > frames: 10
break
if __name__ == "__main__":
asyncio.run(main())
Source: examples/testcard.py · tested by test_the_test_card_player
The command line reads the same model without playing, from the file and the class. Here is the command of the test card:
$ mixtape inspect examples/testcard.py:Testcard | grep 'show('
show(pattern: smpte|ball|snow = smpte) Show a test pattern.
See Command line for what else mixtape run and mixtape inspect do with a class,
and HTTP API for the control page it gets.
When it goes wrong
Everything that can fail has an exception, all of them subclasses of
mixtape.exceptions.MixTapeError:
| Exception | Raised when |
|---|---|
PlayerDescriptionError |
from_description cannot parse the description |
PlayerPipelineError |
the pipeline posts an error: source, message, debug and the gerror |
PlayerSetStateError |
a state change fails, or the pipeline is stuck changing state |
PlayerNotConfigured |
a method needs the running loop of the player and there is none |
A typo in the description fails at once, with the parser's message:
import asyncio
import logging
from mixtape import Player
from mixtape.exceptions import PlayerDescriptionError, PlayerPipelineError
logging.getLogger("mixtape").setLevel(logging.CRITICAL) # the player logs errors too
def typo() -> None:
try:
Player.from_description("videotestsrc ! nosuchelement ! fakesink")
except PlayerDescriptionError as exc:
print(exc)
# > Invalid pipeline 'videotestsrc ! nosuchelement ! fakesink': no element "nosuchelement"
Source: examples/lib_errors.py · tested by test_errors_of_the_description_the_start_and_the_stream
An element error reaches the code that awaits. await player.play() raises
PlayerPipelineError with the element's own message when the pipeline fails to start, and the
player has already set the pipeline to NULL:
async def cannot_start() -> None:
async with Player.from_description("videotestsrc ! filesink location=/nonexistent/x") as player:
try:
await player.play()
except PlayerPipelineError as exc:
print(f"{exc.source}: {exc.message}")
# > filesink0: Could not open file "/nonexistent/x" for writing.
print("state:", player.state.value_nick)
# > state: null
Source: examples/lib_errors.py · tested by test_errors_of_the_description_the_start_and_the_stream
When the pipeline fails after it started, the await player.play_until_eos() that waits for it
raises. The first error is the cause, because an element downstream often follows it with errors
of its own. player.error keeps it until the pipeline
starts again:
%%{init: {"flowchart": {"nodeSpacing": 20, "rankSpacing": 24, "subGraphTitleMargin": {"top": 4, "bottom": 12}}}}%%
flowchart LR
%% errors
p0n0["videotestsrc"]
p0n1["<b>flaky</b><br>identity"]
p0n2["fakesink"]
p0n0 --> p0n1
p0n1 --> p0n2
async def fails_while_playing() -> None:
description = "videotestsrc ! identity name=flaky error-after=5 ! fakesink"
async with Player.from_description(description) as player:
try:
await player.play_until_eos()
except PlayerPipelineError as exc:
print(f"{exc.source}: {exc.message}")
# > flaky: Failed after iterations as requested.
print("player.error is the exception:", player.error is exc)
# > player.error is the exception: True
await player.set("flaky.error-after", -1) # no more failures
await player.play()
print("error after playing again:", player.error)
# > error after playing again: None
Source: examples/lib_errors.py · tested by test_errors_of_the_description_the_start_and_the_stream
The player also logs an error and a warning through the mixtape.player logger. The program
turns that off to keep its output to what it prints, the # > lines.
An error that happens while nothing awaits, a pipeline that plays while the program sleeps, does
not raise anywhere: it is an Error event and
player.error.
Events
Every message on the pipeline's bus is also an event.
player.events() subscribes to the events published from
now on, so call it before the change that you want to see. It returns an async iterator that
ends when the player is torn down, or when you call its close().
| Event | Fields | Published when |
|---|---|---|
StateChanged |
old, new, pending |
the pipeline itself changed state |
Eos |
the stream ended | |
Error |
error |
the pipeline failed; the player set it to NULL already |
Warning |
source, message, debug |
an element posted a warning |
PropertyChanged |
path, element, property, value |
an exposed element's property changed, on any thread, or a computed property was notified |
Position |
position, duration |
either changed, in seconds; only for events(position=True) |
GraphChanged |
graph |
the pipeline's elements, pads, links or caps changed |
ModelChanged |
model |
the exposed elements or their keys changed |
Message |
message |
any bus message, after the specific event for it |
They are frozen dataclasses, so they work with match. This program reads a short stream,
with its position, and sets a property while it waits:
%%{init: {"flowchart": {"nodeSpacing": 20, "rankSpacing": 24, "subGraphTitleMargin": {"top": 4, "bottom": 12}}}}%%
flowchart LR
%% events
p0n0["<b>src</b><br>videotestsrc"]
p0n1["fakesink"]
p0n0 --> p0n1
import asyncio
from mixtape import Player
from mixtape.events import Eos, Error, Position, PropertyChanged, StateChanged, Warning
async def main() -> None:
description = "videotestsrc name=src num-buffers=45 ! fakesink sync=true" # 1.5 s
async with Player.from_description(description) as player:
events = player.events(position=True)
await player.set("src.pattern", "ball")
await player.play()
moving = False
async for event in events:
match event:
case PropertyChanged(path=path, value=value):
print(f"{path} = {value}")
# > src.pattern = ball
case StateChanged(new=state) if state.value_nick == "playing":
print("playing")
# > playing
case Position(position=position) if position and not moving:
print("the position moves")
# > the position moves
moving = True
case Warning(message=message):
print("warning:", message)
case Error(error=error):
print("error:", error.message)
break
case Eos():
print("end of stream")
# > end of stream
break
asyncio.run(main())
Source: examples/lib_events.py · tested by test_the_events_of_a_short_stream
Position is read every Player.position_interval seconds (0.25) while some stream asks for it,
and published when the value changed. A stream that asks for them gets the current one at once.
Handling one kind of message
add_handler calls a function on the loop for the bus messages of a type, after the
built-in handling of them. It returns the function that removes it. A handler that raises is
logged and does not stop the others.
import asyncio
import gi
gi.require_version("Gst", "1.0")
from gi.repository import Gst
from mixtape import Player
async def main() -> None:
async with Player.from_description("videotestsrc num-buffers=10 ! fakesink") as player:
remove = player.add_handler(
Gst.MessageType.STREAM_START, lambda message: print("a stream started")
)
await player.play_until_eos()
# > a stream started
remove() # a handler stays until it is removed
await player.play_until_eos() # no second line: it was removed
print("done")
# > done
asyncio.run(main())
Source: examples/lib_handler.py · tested by test_a_handler_runs_until_it_is_removed
Use add_handler to react to one kind of message with a function, and events() to read
everything in order, in a loop of your own.
When the pipeline changes shape
describe() and graph() are snapshots. A pipeline changes while it runs: a decodebin adds
elements, pads come and go, links are made and caps are negotiated. The player watches for it
and publishes what changed as GraphChanged with the new graph(). The changes of
Player.shape_interval (0.1 s) come together as one event, and only when the graph differs from
the last one published.
When the elements the model exposes change, or their keys do (a second q in another bin makes
the first one a.q), ModelChanged follows with the new describe(). It has the action signals
of the elements that came as commands, and none of those that went. A decodebin's elements are
never named by you, so what it adds is a GraphChanged and no ModelChanged, unless the player
exposes all elements.
This program adds a named branch to a tee while the pipeline plays. The graph is the pipeline once the branch, in a bin of its own, is added:
%%{init: {"flowchart": {"nodeSpacing": 20, "rankSpacing": 24, "subGraphTitleMargin": {"top": 4, "bottom": 12}}}}%%
flowchart LR
%% shape
p0n0["videotestsrc"]
p0n1["<b>t</b><br>tee"]
p0n2["queue"]
p0n3["<b>main</b><br>fakesink"]
subgraph p0n4["bin"]
p0n5["queue"]
p0n6["<b>extra</b><br>fakesink"]
end
p0n0 --> p0n1
p0n1 --> p0n2
p0n1 --> p0n5
p0n2 --> p0n3
p0n5 --> p0n6
import asyncio
import gi
gi.require_version("Gst", "1.0")
from gi.repository import Gst
from mixtape import Player
from mixtape.events import GraphChanged, ModelChanged
DESCRIPTION = "videotestsrc is-live=true ! tee name=t ! queue ! fakesink name=main"
async def main() -> None:
async with Player.from_description(DESCRIPTION) as player:
events = player.events()
await player.play()
print("exposed:", ", ".join(player.describe().elements))
# > exposed: t, main
# a second branch: this changes the graph, and the model with it, as `extra` is named
branch = Gst.parse_bin_from_description("queue ! fakesink name=extra", True)
player.pipeline.add(branch)
player.pipeline.get_by_name("t").link(branch)
branch.sync_state_with_parent()
async for event in events:
if isinstance(event, GraphChanged) and "extra" in event.graph.nodes:
print("links:", len(event.graph.links))
# > links: 5
elif isinstance(event, ModelChanged):
print("exposed:", ", ".join(event.model.elements))
# > exposed: t, main, extra
break
asyncio.run(main())
Source: examples/lib_shape.py · tested by test_a_branch_added_while_playing_changes_the_graph_and_the_model
The web page of the HTTP API follows the same events: its graph and its element sections change without a reload.
Write a feature
A feature is a plugin of a player: it adds commands and live properties to the model, next to
the elements', as feature.name. They show up in describe(), mixtape inspect, the HTTP API
and the control page like any other. Measuring performance uses the built-in
perf; this one counts beats.
A feature is a Feature subclass with a name, its options as
the keyword parameters of __init__, and @command methods and @prop getters like a player's.
Its hooks run in this order:
prepareruns once, before GStreamer is initialised, when the player is built from a description: the place to set environment variables.initialisedruns once GStreamer is initialised and before the pipeline is built from a description: what has to be in place before an element is made.checkruns when the player is built, oncerequires(GStreamer elements or tracers) is met. It raisesFeatureErrorif the feature cannot work with this pipeline.attachruns when the player is set up, on its loop: start what runs beside the pipeline.detachruns when the player is torn down, with the pipeline in NULL: stop it.
import asyncio
import os
from typing import Annotated
from pydantic import Field
from mixtape import Feature, Player, command, prop
from mixtape.exceptions import FeatureError
class Heartbeat(Feature):
name = "heartbeat"
requires = ("identity",) # GStreamer elements or tracers it needs
def __init__(self, interval: Annotated[float, Field(gt=0)] = 1.0) -> None:
self.interval = interval
self._beats = 0
self._task: asyncio.Task[None] | None = None
def prepare(self) -> None:
# before GStreamer is initialised: the place for environment variables
os.environ.setdefault("GST_DEBUG_NO_COLOR", "1")
def check(self, player: Player) -> None:
# when the player is built: refuse a pipeline the feature cannot work with
if not player.sinks:
raise FeatureError("heartbeat needs a pipeline with a sink")
def attach(self, player: Player) -> None:
# when the player is set up, on its loop
self._beats = 0
self._task = asyncio.get_running_loop().create_task(self._beat())
def detach(self, player: Player) -> None:
# when it is torn down
if self._task:
self._task.cancel()
async def _beat(self) -> None:
while True:
await asyncio.sleep(self.interval)
self._beats += 1
self.notify("beats")
@prop
def beats(self) -> int:
"""Beats since the player was set up"""
return self._beats
@command
def reset(self) -> None:
"""Start counting again"""
self._beats = 0
self.notify("beats")
Source: examples/heartbeat_plugin/heartbeat.py · tested by test_the_heartbeat_feature
- The options are validated.
heartbeat,interval=0.5on the command line gives a float, and a value that does not fit is aFeatureErrorbefore anything starts. notify("beats")publishes the current value of the propertybeatsas aPropertyChangedofheartbeat.beats, and does nothing while the feature is detached. Like the player's, it is for the loop thread only.- Getters and commands must also work when the player is not set up, because
mixtape inspectreads every property: answer from what you have.self.playeris the player while attached. - A feature declares computed properties only. Its name cannot be that of an element of the pipeline.
Enable it with the features argument of a player, as an instance, a class or a
"name,key=value" string. A player class can enable features for every instance with its own
features attribute, such as features = ("heartbeat,interval=2",): names and classes, not
instances.
%%{init: {"flowchart": {"nodeSpacing": 20, "rankSpacing": 24, "subGraphTitleMargin": {"top": 4, "bottom": 12}}}}%%
flowchart LR
%% heartbeat
p0n0["videotestsrc"]
p0n1["identity"]
p0n2["fakesink"]
p0n0 --> p0n1
p0n1 --> p0n2
import asyncio
from heartbeat import Heartbeat
from mixtape import Player
from mixtape.events import PropertyChanged
from mixtape.exceptions import FeatureError
async def main() -> None:
description = "videotestsrc is-live=true ! identity ! fakesink"
async with Player.from_description(description, features=[Heartbeat(interval=0.05)]) as player:
model = player.describe()
print("in the model:", *[n for n in (*model.commands, *model.properties) if "." in n])
# > in the model: heartbeat.reset heartbeat.beats
events = player.events()
await player.play()
async for event in events:
if isinstance(event, PropertyChanged) and event.value == 3:
print(f"{event.path} = {event.value}")
# > heartbeat.beats = 3
break
print("reset:", await player.invoke("heartbeat.reset"), player.get("heartbeat.beats"))
# > reset: None 0
print("detached:", player.enabled_features["heartbeat"].player is None)
# > detached: True
try:
Heartbeat.from_options(interval="0")
except FeatureError as exc:
print(exc)
# > Invalid options for feature 'heartbeat': interval: Input should be greater than 0
try:
Player.from_description("fakesrc", features=[Heartbeat()])
except FeatureError as exc:
print(exc)
# > heartbeat needs a pipeline with a sink
asyncio.run(main())
Source: examples/heartbeat_plugin/heartbeat_demo.py · tested by test_the_heartbeat_feature
Make it available by name
Register the class in the mixtape.features entry points of your package, and --feature
heartbeat, features=["heartbeat"] and mixtape inspect --help know it. This is the whole
pyproject.toml of the package, next to its heartbeat.py:
[project]
name = "mixtape-heartbeat"
version = "0.1"
requires-python = ">=3.12"
dependencies = ["mixtape"]
[project.entry-points."mixtape.features"]
heartbeat = "heartbeat:Heartbeat"
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
only-include = ["heartbeat.py"]
Install it into the environment that has mixtape:
$ pip install ./examples/heartbeat_plugin
$ mixtape inspect --feature heartbeat,interval=0.5 "videotestsrc ! fakesink" | grep heartbeat
Features: heartbeat
heartbeat.reset() Start counting again
heartbeat.beats r- integer = 0 Beats since the player was set up
The same package gives the feature to mixtape run, with --http for the control page: beats
is a property that updates live, and reset has a form.