Skip to content

Two pipelines

A Player drives one pipeline. When one pipeline has to feed another, mixtape has nothing of its own for it: you build two players and link them with GStreamer elements, in one process or across two. This page lists the elements that can do it, says which to pick, runs one example of each kind, and ends with what mixtape does for two players, and what it does not.

The ways to connect two pipelines

Elements Where What passes Notes
intervideosink / intervideosrc, interaudiosink / interaudiosrc (gst-plugins-bad) same process raw video or raw audio only linked by channel name; the receiver keeps its own rate and repeats frames
proxysink / proxysrc (gst-plugins-bad) same process any caps; events and queries pass too linked by object in code: proxysrc's proxysink property; both pipelines need one clock and one base time
intersink / intersrc (gst-plugins-rs) same process any caps linked by producer-name; Homebrew installs it, Ubuntu does not package it
appsink / appsrc same process anything you pass along your Python runs on the streaming thread
shmsink / shmsrc (gst-plugins-bad) two processes raw bytes the receiver is told the caps; no zero copy
unixfdsink / unixfdsrc (gst-plugins-bad) two processes any caps, which travel with the buffers zero copy; GStreamer 1.24 and later
UDP and RTP, WebRTC two machines encoded media see A WebRTC client

RidgeRun's interpipe links pipelines by name too, but neither Homebrew nor Ubuntu packages it.

Which one to use

  • A lossless link between two players of one process, which share a clock: proxysink and proxysrc. Every buffer arrives, and so do the EOS and the queries.
  • Two players that must not depend on each other, one of which comes and goes: intervideo or interaudio. The consumer keeps its own rate, and carries on when the producer stops.
  • Two processes: unixfdsink and unixfdsrc.

The other elements are for what these do not cover: intersink for any caps, linked by name, where gst-plugins-rs is installed; appsink and appsrc when your code has to touch the data; shmsink between processes below GStreamer 1.24.

Decoupled: intervideo

The producer plays a camera at 10 frames per second into the channel cam. The consumer reads the channel at 30:

%%{init: {"flowchart": {"nodeSpacing": 20, "rankSpacing": 24, "subGraphTitleMargin": {"top": 4, "bottom": 12}}}}%%
flowchart LR
  %% inter
  subgraph p0["producer"]
    p0n0["videotestsrc"]
    p0n1["intervideosink"]
    p0n2["video/x-raw<br>width=320<br>height=240<br>framerate=10/1"]
  end
  subgraph p1["consumer"]
    p1n0["intervideosrc"]
    p1n1["queue"]
    p1n2["<b>sink</b><br>fakesink"]
    p1n3["video/x-raw<br>framerate=30/1"]
  end
  p0n0 --> p0n2
  p0n2 --> p0n1
  p1n0 --> p1n3
  p1n1 --> p1n2
  p1n3 --> p1n1
  p0n1 -. "channel cam" .-> p1n0
import asyncio

from mixtape import Player

# a camera at 10 fps, and a consumer that asks for 30
PRODUCER = (
    "videotestsrc is-live=true ! video/x-raw,width=320,height=240,framerate=10/1"
    " ! intervideosink channel=cam"
)
CONSUMER = "intervideosrc channel=cam ! video/x-raw,framerate=30/1 ! queue ! fakesink name=sink"

Source: examples/inter_restart.py · tested by test_the_consumer_renders_while_the_producer_stops_and_restarts

Both players run in one asyncio loop. The consumer is started first, then the producer is stopped, and played again, while the program counts the frames the consumer's sink renders in a second:

def rendered(player: Player) -> int:
    """The frames the consumer's sink has rendered so far."""
    sink = player.pipeline.get_by_name("sink")
    return int(sink.get_property("stats").get_value("rendered"))


async def frames_in_a_second(player: Player) -> int:
    before = rendered(player)
    await asyncio.sleep(1)
    return rendered(player) - before

Source: examples/inter_restart.py · tested by test_the_consumer_renders_while_the_producer_stops_and_restarts

async def report(step: str, consumer: Player) -> None:
    frames = await frames_in_a_second(consumer)
    print(f"producer {step}: the consumer rendered more than 10 frames: {frames > 10}")
    # > producer playing: the consumer rendered more than 10 frames: True
    # > producer stopped: the consumer rendered more than 10 frames: True
    # > producer restarted: the consumer rendered more than 10 frames: True


async def main() -> None:
    producer = Player.from_description(PRODUCER)
    consumer = Player.from_description(CONSUMER)
    async with producer, consumer:
        await consumer.play()
        await producer.play()
        await report("playing", consumer)
        await producer.stop()
        await report("stopped", consumer)
        await producer.play()
        await report("restarted", consumer)


asyncio.run(main())

Source: examples/inter_restart.py · tested by test_the_consumer_renders_while_the_producer_stops_and_restarts

The consumer did not stop with the producer: intervideosrc makes a frame at the consumer's rate, and repeats the last one it got when no new one has come. When the producer stops it makes black frames, straight away, and so it does when the producer is paused for longer than its timeout property (one second). The two pipelines have their own state: stopping one does not touch the other.

Lossless: proxysink and proxysrc

proxysrc takes buffers, events and queries from a proxysink, and it is linked to it in code. The two pipelines then have to agree on time: they use one clock, and one base time, the clock time that is their running time 0. A buffer is stamped with the running time of the pipeline that made it, and a consumer with another base time sees it earlier or later than it was meant:

%%{init: {"flowchart": {"nodeSpacing": 20, "rankSpacing": 24, "subGraphTitleMargin": {"top": 4, "bottom": 12}}}}%%
flowchart LR
  %% proxy
  subgraph p0["producer"]
    p0n0["videotestsrc"]
    p0n1["<b>out</b><br>proxysink"]
    p0n2["video/x-raw<br>framerate=10/1"]
  end
  subgraph p1["consumer"]
    p1n0["<b>in</b><br>proxysrc"]
    p1n2["queue"]
    p1n3["<b>sink</b><br>fakesink"]
  end
  p0n0 --> p0n2
  p0n2 --> p0n1
  p1n0 --> p1n2
  p1n2 --> p1n3
  p0n1 -. "proxysink property" .-> p1n0
import asyncio
import time

import gi

gi.require_version("Gst", "1.0")
from gi.repository import Gst

from mixtape import Player

HEAD_START = 1.5  # seconds the producer plays before the consumer starts, in `first_frame`
PRODUCER = "videotestsrc is-live=true ! video/x-raw,framerate=10/1 ! proxysink name=out"
CONSUMER = "proxysrc name=in ! queue ! fakesink name=sink sync=true"


def link(producer: Player, consumer: Player, *, share_base_time: bool = True) -> None:
    """Tell proxysrc which proxysink it takes from, and put both pipelines on one timeline."""
    psrc = consumer.pipeline.get_by_name("in")
    psrc.set_property("proxysink", producer.pipeline.get_by_name("out"))
    clock = Gst.SystemClock.obtain()
    base_time = clock.get_time()
    for player in (producer, consumer):
        player.pipeline.use_clock(clock)
        if share_base_time:
            # NONE: do not reset the base time when the pipeline goes to PLAYING
            player.pipeline.set_start_time(Gst.CLOCK_TIME_NONE)
            player.pipeline.set_base_time(base_time)

Source: examples/proxy_link.py · tested by test_proxy_link_shares_the_base_time_and_starts_in_order

Both pipelines pick the system clock unless one of their elements provides another one, so use_clock only makes sure. set_start_time with CLOCK_TIME_NONE is not optional: without it a pipeline sets its base time again when it goes to PLAYING, and the one you set is gone.

The order the pipelines start in matters. proxysrc has nothing to show until the producer pushes a buffer, so the consumer's play() does not return before the producer plays: start the producer first, or start both at once.

async def start_order() -> bool:
    """Is the consumer's play() still waiting before the producer plays?"""
    producer = Player.from_description(PRODUCER)
    consumer = Player.from_description(CONSUMER)
    link(producer, consumer)
    async with producer, consumer:
        consumer_playing = asyncio.create_task(consumer.play())
        await asyncio.wait([consumer_playing], timeout=1)
        waiting = not consumer_playing.done()
        await producer.play()
        await consumer_playing
    return waiting

Source: examples/proxy_link.py · tested by test_proxy_link_shares_the_base_time_and_starts_in_order

A producer that ends sends its EOS through the link, and the buffers before it are all there. This producer is not live, so it waits for the consumer; a live one does not, and a buffer it pushes before the consumer is playing can be lost (the first one went missing in 4 of 30 runs on one machine):

async def lossless() -> bool:
    """Did the consumer render all 50 buffers of the producer, and get its EOS?"""
    producer = Player.from_description(
        "videotestsrc num-buffers=50 ! video/x-raw,framerate=50/1 ! proxysink name=out"
    )
    consumer = Player.from_description(CONSUMER)
    link(producer, consumer)
    sink = consumer.pipeline.get_by_name("sink")
    async with producer, consumer:
        await asyncio.gather(producer.play(), consumer.play())
        await asyncio.wait_for(consumer.play_until_eos(), 10)
        return bool(sink.get_property("stats").get_value("rendered") == 50)

Source: examples/proxy_link.py · tested by test_proxy_link_shares_the_base_time_and_starts_in_order

The base time is what keeps the two on one timeline. Here the producer plays for 1.5 seconds before the consumer starts. With a shared base time, the consumer's first frame comes in well under that.

With a base time of its own, the consumer's sink waits for the clock and holds the frame back until the consumer has been running as long as the producer had:

async def first_frame(*, share_base_time: bool) -> float:
    """Seconds from the consumer's play() until its sink has rendered a frame, when the
    producer has been playing for HEAD_START seconds before it."""
    producer = Player.from_description(PRODUCER)
    consumer = Player.from_description(CONSUMER)
    link(producer, consumer, share_base_time=share_base_time)
    sink = consumer.pipeline.get_by_name("sink")
    async with producer, consumer:
        await producer.play()
        await asyncio.sleep(HEAD_START)
        started = time.monotonic()
        await consumer.play()
        while sink.get_property("stats").get_value("rendered") == 0:
            await asyncio.sleep(0.05)
        return time.monotonic() - started

Source: examples/proxy_link.py · tested by test_proxy_link_shares_the_base_time_and_starts_in_order

async def main() -> None:
    print(f"the consumer waits for the producer to play: {await start_order()}")
    # > the consumer waits for the producer to play: True
    print(f"all 50 buffers and the EOS arrive: {await lossless()}")
    # > all 50 buffers and the EOS arrive: True
    shared = await first_frame(share_base_time=True)
    print(f"shared base time: first frame before the producer's age: {shared < HEAD_START}")
    # > shared base time: first frame before the producer's age: True
    own = await first_frame(share_base_time=False)
    print(f"own base time: first frame after the producer's age: {own >= HEAD_START}")
    # > own base time: first frame after the producer's age: True


asyncio.run(main())

Source: examples/proxy_link.py · tested by test_proxy_link_shares_the_base_time_and_starts_in_order

Two processes: unixfd

unixfdsink listens on a socket, and passes the buffers to the unixfdsrc that connects to it, as file descriptors: the frames are not copied. The caps travel with them, so the consumer's description has none. The producer has to be listening before the consumer starts, as unixfdsrc fails to start without a socket to connect to.

Each process is a mixtape run --http, with its own control page and its own perf. Run the two commands in two terminals; the block below runs both in one shell, asks each process for the pads its perf measured, and stops them in its last command. Their own output, the address each one serves, goes to /dev/null:

%%{init: {"flowchart": {"nodeSpacing": 20, "rankSpacing": 24, "subGraphTitleMargin": {"top": 4, "bottom": 12}}}}%%
flowchart LR
  %% unixfd
  subgraph p0["producer, :8101"]
    p0n0["<b>cam</b><br>videotestsrc"]
    p0n1["unixfdsink"]
  end
  subgraph p1["consumer, :8102"]
    p1n0["<b>feed</b><br>unixfdsrc"]
    p1n1["<b>conv</b><br>videoconvert"]
    p1n2["fakesink"]
  end
  p0n0 --> p0n1
  p1n0 --> p1n1
  p1n1 --> p1n2
  p0n1 -. "cam.sock" .-> p1n0
$ dir=$(mktemp -d)
$ mixtape run --http 8101 --feature perf \
    "videotestsrc is-live=true name=cam ! unixfdsink socket-path=$dir/cam.sock" > /dev/null 2>&1 &
$ producer=$!
$ until [ -S $dir/cam.sock ]; do sleep 0.1; done
$ mixtape run --http 8102 --feature perf \
    "unixfdsrc name=feed socket-path=$dir/cam.sock ! videoconvert name=conv ! fakesink" \
    > /dev/null 2>&1 &
$ consumer=$!
$ sleep 3
$ for port in 8101 8102; do echo "port $port:"; \
    curl -s 127.0.0.1:$port/api/properties | grep -o '"[a-z]*:src"' | sort -u; done; \
    kill $producer $consumer; wait; rm -r $dir
port 8101:
"cam:src"
port 8102:
"conv:src"
"feed:src"

Open the two addresses and each page has the graph and the charts of its own pipeline. Each process measures only what runs in it.

What mixtape does across two players

Each Player is a complete one, with its own bus watch, its own model of the pipeline (its properties, commands and graph) and its own events. Nothing in one sees the other. You can serve each on a port of its own: serve takes the player and the address, and with port 0 it picks one.

The tracers are another matter. GStreamer creates them once per process, when it initialises, and mixtape's perf, leaks and tracers features read them: they are one per process, not one per player. For perf that means one collector per process, and every recorder gets every sample the process makes. So with perf on two players in one process:

  • each player records both pipelines, and shows both on its page;
  • elements of the same name in the two pipelines share one subject: two queues named q are one q.
%%{init: {"flowchart": {"nodeSpacing": 20, "rankSpacing": 24, "subGraphTitleMargin": {"top": 4, "bottom": 12}}}}%%
flowchart LR
  %% two-players
  subgraph p0["cam"]
    p0n0["<b>cam</b><br>videotestsrc"]
    p0n1["<b>q</b><br>queue"]
    p0n2["fakesink"]
  end
  subgraph p1["mic"]
    p1n0["<b>mic</b><br>audiotestsrc"]
    p1n1["<b>q</b><br>queue"]
    p1n2["fakesink"]
  end
  p0n0 --> p0n1
  p0n1 --> p0n2
  p1n0 --> p1n1
  p1n1 --> p1n2
import asyncio
import json
import urllib.request

from mixtape import Player
from mixtape.interfaces.http import serve

CAM = "videotestsrc is-live=true name=cam ! queue name=q ! fakesink"
MIC = "audiotestsrc is-live=true name=mic ! queue name=q ! fakesink"


def get_json(url: str) -> dict[str, dict[str, object]]:
    with urllib.request.urlopen(url) as response:
        return json.load(response)


async def page_elements(url: str) -> list[str]:
    """The elements a control page of a player lists."""
    model = await asyncio.to_thread(get_json, f"{url}/api/model")
    return sorted(model["elements"])

Source: examples/two_players.py · tested by test_two_players_in_one_process_share_the_tracers

def pad_subjects(player: Player) -> list[str]:
    """The pads `perf` of a player has counted buffers of."""
    summary = player.get("perf.summary")
    return sorted(summary["metrics"]["pad.buffers"]) if summary else []


async def both_measured(*players: Player) -> None:
    while not all(len(pad_subjects(player)) >= 3 for player in players):
        await asyncio.sleep(0.1)

Source: examples/two_players.py · tested by test_two_players_in_one_process_share_the_tracers

async def main() -> None:
    cam = Player.from_description(CAM, features=["perf"])
    mic = Player.from_description(MIC, features=["perf"])
    async with (
        cam,
        mic,
        serve(cam, "127.0.0.1", 0) as cam_page,
        serve(mic, "127.0.0.1", 0) as mic_page,
    ):
        await asyncio.gather(cam.play(), mic.play())
        print("two ports:", cam_page.port != mic_page.port)
        # > two ports: True
        print("cam's page lists:", await page_elements(cam_page.url))
        # > cam's page lists: ['cam', 'q']
        print("mic's page lists:", await page_elements(mic_page.url))
        # > mic's page lists: ['mic', 'q']
        await asyncio.wait_for(both_measured(cam, mic), 15)
        print("cam's perf counted buffers of:", pad_subjects(cam))
        # > cam's perf counted buffers of: ['cam:src', 'mic:src', 'q:src']
        print("mic's perf counted buffers of:", pad_subjects(mic))
        # > mic's perf counted buffers of: ['cam:src', 'mic:src', 'q:src']


asyncio.run(main())

Source: examples/two_players.py · tested by test_two_players_in_one_process_share_the_tracers

Each page lists its own pipeline's elements, and each player's perf has counted buffers of the pads of both: cam:src and mic:src. The leaks feature documents the same limit: one player at a time can track.

To measure two pipelines apart, run them in two processes, as in the unixfd example above: each has its own tracers, its own perf and its own control page. Names are free to repeat there.

One option under consideration is a way to group the players of a process or of several, with one control page and one perf for the session as a whole (a "Session"). It is not planned, and nothing of it exists today.