A WebRTC client
examples/webrtc_client.py is an application that makes calls. It publishes a video source
and plays the video of another client, so two of them make a call, each seeing the other. It
is built on webrtcsink and webrtcsrc from gst-plugins-rs and their built-in signalling: the
clients find each other through a signalling server, then send their video peer to peer.
Each client is a Player, so it gets what any player gets: mixtape run with a control page,
and live metrics. The call is a command, and who publishes, who is being played and how many
frames arrived are properties.
Install
webrtcsink and webrtcsrc are not part of GStreamer itself, they are in gst-plugins-rs.
webrtcbin, which they use, needs libnice for ICE:
$ brew install gstreamer libnice-gstreamer
Homebrew's gstreamer includes the Rust plugins.
$ sudo apt install gstreamer1.0-plugins-bad gstreamer1.0-nice \
libgstreamer-plugins-base1.0-dev libgstreamer-plugins-bad1.0-dev
Ubuntu does not package the Rust plugins. scripts/build-rs-plugins builds them from
gst-plugins-rs 0.15.4 with cargo (Rust 1.92 or newer), the same way CI does, and
GST_PLUGIN_PATH lets GStreamer find them:
$ scripts/build-rs-plugins ~/.cache/gst-rs-plugins
$ export GST_PLUGIN_PATH=~/.cache/gst-rs-plugins
Check that both elements are there. Without them, a pipeline fails with
no element "webrtcsink": see Troubleshooting.
$ gst-inspect-1.0 --exists webrtcsink && gst-inspect-1.0 --exists webrtcsrc && echo found
found
A call on one machine
Run the signalling server and one client in a terminal. --serve makes the client run the
server too, which webrtcsink can do itself:
$ python3 examples/webrtc_client.py --serve --name host
It publishes a test pattern, and waits. In another terminal, start a second client, which calls the first by its name as soon as it publishes, and exits when it has seen 60 frames of its video:
$ python3 examples/webrtc_client.py --name guest --call host
To try it without a second terminal, --demo runs two clients in one process, alice with
the server and bob, which call each other:
$ python3 examples/webrtc_client.py --demo
alice received 60 frames from bob
bob received 60 frames from alice
The test pattern is only the default. --camera publishes the camera instead, and
--sink autovideosink shows the remote video in a window instead of dropping it:
$ python3 examples/webrtc_client.py --camera --sink autovideosink --call
Without an argument --call calls the first client that publishes. On a network, every
client gets the server's address with --server ws://host:8443, and the two
stun-server=NULL in the code below must go, so that ICE can ask a STUN server for the
address to use.
How it works
What a client publishes
publisher makes the pipeline description: a source, scaled down to keep the encoding cheap,
into a webrtcsink. The sink offers the video to whoever calls it, and
encodes it once for each caller. The meta property is how a client says its name to the
others. stun-server=NULL is for a call on one machine: no STUN server is asked for the
address, so nothing goes out on the network. congestion-control=disabled leaves out the
bandwidth estimation, which needs a plugin of its own.
%%{init: {"flowchart": {"nodeSpacing": 20, "rankSpacing": 24, "subGraphTitleMargin": {"top": 4, "bottom": 12}}}}%%
flowchart LR
%% publish
p0n0["videotestsrc"]
p0n1["videoconvert"]
p0n2["videoscale"]
p0n3["<b>out</b><br>webrtcsink"]
p0n6["video/x-raw<br>width=320<br>height=240"]
p0n0 --> p0n1
p0n1 --> p0n2
p0n2 --> p0n6
p0n6 --> p0n3
import argparse
import asyncio
import logging
import os
import threading
from collections.abc import Callable, Sequence
from typing import Any
from urllib.parse import urlsplit
import gi
gi.require_version("Gst", "1.0")
from gi.repository import Gst
from mixtape import Player, command, prop
from mixtape.exceptions import CommandError, PlayerPipelineError
SERVER = "ws://127.0.0.1:8443"
def publisher(name: str, *, server: str = SERVER, serve: bool = False, camera: bool = False) -> str:
"""The pipeline description of a client: its source, sent by webrtcsink to whoever calls."""
source = "autovideosrc" if camera else "videotestsrc is-live=true"
sink = f'webrtcsink name=out meta="meta,name={name}" signaller::uri={server}'
sink += " stun-server=NULL congestion-control=disabled" # all on this machine
if serve: # this client also runs the signalling server
url = urlsplit(server)
sink += f" run-signalling-server=true signalling-server-host={url.hostname}"
sink += f" signalling-server-port={url.port}"
return f"{source} ! videoconvert ! videoscale ! video/x-raw,width=320,height=240 ! {sink}"
Source: examples/webrtc_client.py · tested by test_two_clients_in_one_process_each_receive_the_other
With serve the sink also runs the signalling server, in the same process. Every client
connects to a server over a WebSocket, the one its signaller::uri names. gst-plugins-rs also
has gst-webrtc-signalling-server, a program that does only that, which any of the clients can
use instead.
The client
A Client is a Player with that pipeline. webrtcsrc plays a given peer, but cannot list
who publishes, so the client asks the signalling server itself: it creates a second
signaller of the sink's kind, as a listener, and the server tells it who joins and who leaves.
GStreamer's signals come on threads of their own, so they are handed to the asyncio loop
before they touch the properties. The listener is stopped on a thread of its own, and the
client waits for it at most two seconds: in gst-plugins-rs 0.15 the signaller's stop can
deadlock when a peer's status arrives just as it stops, and it would take the loop with it.
class Client(Player):
"""Publishes its source and plays the video of the peer it calls."""
description = publisher("client")
sink = "fakesink sync=false" # what the remote video goes to: autovideosink shows it
def __init__(self, pipeline: Gst.Pipeline, **kwargs: Any) -> None:
super().__init__(pipeline, **kwargs)
self._signaller = pipeline.get_by_name("out").get_property("signaller")
self._signaller.connect("notify::client-id", self._on_joined)
self._offered: dict[str, str] = {} # everyone who publishes, us too: id to name
self._remote: str | None = None
self._call: Gst.Bin | None = None
self._webrtcbin: Gst.Element | None = None
self._frames = 0
self._listening = False
# a listener of the same signalling server: it is told who publishes
self._directory = type(self._signaller)(uri=self._signaller.props.uri)
self._directory.set_property("role", "listener")
self._directory.connect("producer-added", self._on_producer_added)
self._directory.connect("producer-removed", self._on_producer_removed)
self._directory.connect("error", lambda _, message: logger.warning(message))
async def set_state(self, state: Gst.State) -> Gst.StateChangeReturn:
if state == Gst.State.NULL: # the call ends before the pipeline, the listener after it
self.hangup()
result = await super().set_state(state)
if state == Gst.State.NULL and self._listening:
await self._stop_listening()
return result
async def _stop_listening(self) -> None:
"""Stop the listener on a thread of its own, and wait at most a few seconds: the
signaller's stop deadlocks when a peer's status arrives as it stops."""
self._listening = False
loop = asyncio.get_running_loop()
stopped = loop.create_future()
def stopped_now() -> None:
if not stopped.done(): # not timed out
stopped.set_result(None)
def stop() -> None:
self._directory.emit("stop")
if not loop.is_closed():
_ = loop.call_soon_threadsafe(stopped_now)
threading.Thread(target=stop, daemon=True).start()
try:
await asyncio.wait_for(stopped, STOP_TIMEOUT)
except TimeoutError:
logger.warning("the listener did not stop in %ss", STOP_TIMEOUT)
def _on_loop(self, callback: Any, *args: object) -> None:
"""Run `callback` on the asyncio loop: the signallers call from their own threads."""
if self.loop is not None:
self.loop.call_soon_threadsafe(callback, *args)
def _on_joined(self, *_: object) -> None:
self._on_loop(self._joined)
def _joined(self) -> None:
if not self._listening: # the server is up: ask it who publishes
self._listening = True
self._directory.emit("start")
self._offer_changed()
def _on_producer_added(self, _: object, peer: str, meta: Gst.Structure, __: bool) -> None:
self._on_loop(self._offer, peer, meta.get_string("name") or peer)
def _on_producer_removed(self, _: object, peer: str, meta: Gst.Structure) -> None:
self._on_loop(self._offer, peer, None)
def _offer(self, peer: str, name: str | None) -> None:
if name is None:
self._offered.pop(peer, None)
if peer == self._remote:
self.hangup() # the peer left
else:
self._offered[peer] = name
self._offer_changed()
def _offer_changed(self) -> None:
self.notify("peer_id")
self.notify("producers")
Source: examples/webrtc_client.py · tested by test_two_clients_in_one_process_each_receive_the_other
The properties
What the client knows is in read-only properties, which a control page shows. When one changes,
the client calls notify so that the page shows the new value.
@prop
def name(self) -> str:
"""The name this client publishes under"""
return self.pipeline.get_by_name("out").get_property("meta").get_string("name")
@prop
def peer_id(self) -> str | None:
"""This client's id on the signalling server, once it has joined"""
return self._signaller.props.client_id
@prop
def producers(self) -> dict[str, str]:
"""The other clients that publish: id to name"""
return {peer: name for peer, name in self._offered.items() if peer != self.peer_id}
@prop
def remote(self) -> str | None:
"""The id of the client whose video is playing"""
return self._remote
@prop
def connection(self) -> str:
"""The WebRTC connection state of the call: new, connecting, connected, ..."""
if self._webrtcbin is None:
return "none"
return self._webrtcbin.get_property("connection-state").value_nick
@prop
def frames(self) -> int:
"""The video frames received from the remote client so far"""
return self._frames
Source: examples/webrtc_client.py · tested by test_two_clients_in_one_process_each_receive_the_other
The call
call finds the peer in the list, by id or name, and plays it: it adds a webrtcsrc, a
converter and the sink to the running pipeline as a bin. Frames are counted with a probe on
the converter's sink pad. The probe and the signaller's webrtcbin-ready run on GStreamer's
threads, so they too go to the loop, with the bin they belong to: a frame or a late signal
of a call that has been hung up is ignored. hangup removes the bin again, and a client can call someone else
afterwards. Both are commands, so the control page has them as buttons, and a failed call is a
CommandError: the page shows its message.
%%{init: {"flowchart": {"nodeSpacing": 20, "rankSpacing": 24, "subGraphTitleMargin": {"top": 4, "bottom": 12}}}}%%
flowchart TB
%% call
subgraph p0["alice"]
p0n0["videotestsrc"]
p0n1["videoconvert"]
p0n2["videoscale"]
p0n3["<b>out</b><br>webrtcsink"]
subgraph p0n6["bin"]
p0n7["<b>in</b><br>webrtcsrc"]
p0n8["<b>convert</b><br>videoconvert"]
p0n9["<b>display</b><br>fakesink"]
end
p0n10["video/x-raw<br>width=320<br>height=240"]
end
subgraph p1["bob"]
p1n0["videotestsrc"]
p1n1["videoconvert"]
p1n2["videoscale"]
p1n3["<b>out</b><br>webrtcsink"]
subgraph p1n6["bin"]
p1n7["<b>in</b><br>webrtcsrc"]
p1n8["<b>convert</b><br>videoconvert"]
p1n9["<b>display</b><br>fakesink"]
end
p1n10["video/x-raw<br>width=320<br>height=240"]
end
p0n0 --> p0n1
p0n1 --> p0n2
p0n2 --> p0n10
p0n8 --> p0n9
p0n10 --> p0n3
p1n0 --> p1n1
p1n1 --> p1n2
p1n2 --> p1n10
p1n8 --> p1n9
p1n10 --> p1n3
p0n3 -. "WebRTC" .-> p1n7
p1n3 -. "WebRTC" .-> p0n7
p0n7 -. "on a call" .-> p0n8
p1n7 -. "on a call" .-> p1n8
@command
def call(self, peer: str | None = None) -> str:
"""Play a client's video: its id or name, or the first one that publishes."""
if peer is None and not self.producers:
raise CommandError("nobody else publishes")
found = [p for p, name in self.producers.items() if peer in (None, p, name)]
if not found:
raise CommandError(f"no client {peer!r} publishes: {list(self.producers.values())}")
self.hangup()
self._remote = found[0]
src = "webrtcsrc name=in stun-server=NULL"
src += f" signaller::uri={self._signaller.props.uri} signaller::producer-peer-id={found[0]}"
call = self._call = Gst.parse_bin_from_description(
f"{src} ! videoconvert name=convert ! {self.sink} name=display", False
)
# both come on GStreamer threads: hand them to the loop, with the call they belong to
call.get_by_name("in").get_property("signaller").connect(
"webrtcbin-ready", lambda _, __, webrtcbin: self._on_loop(self._ready, call, webrtcbin)
)
call.get_by_name("convert").get_static_pad("sink").add_probe(
Gst.PadProbeType.BUFFER, lambda *_: self._on_frame(call)
)
self.pipeline.add(call)
call.sync_state_with_parent()
self.notify("remote")
return found[0]
@command
def hangup(self) -> None:
"""Stop playing the remote video."""
if self._call is None:
return
self.pipeline.remove(self._call) # first: it may post an error while it stops
self._call.set_state(Gst.State.NULL)
self._call = self._remote = self._webrtcbin = None
self._frames = 0
for path in ("remote", "connection", "frames"):
self.notify(path)
def _ready(self, call: Gst.Bin, webrtcbin: Gst.Element) -> None:
if call is not self._call: # a call that ended meanwhile
return
self._webrtcbin = webrtcbin
webrtcbin.connect(
"notify::connection-state", lambda *_: self._on_loop(self.notify, "connection")
)
def _on_frame(self, call: Gst.Bin) -> Gst.PadProbeReturn:
self._on_loop(self._count, call)
return Gst.PadProbeReturn.OK
def _count(self, call: Gst.Bin) -> None:
if call is not self._call:
return
self._frames += 1
if self._frames % 30 == 1: # often enough for a control page
self.notify("frames")
Source: examples/webrtc_client.py · tested by test_two_clients_in_one_process_each_receive_the_other
The host
A Host is a client that also runs the signalling server. It exists so that
mixtape run examples/webrtc_client.py:Host starts one, and it keeps the server quiet: the
plugin logs a line for every peer that joins.
class Host(Client):
"""A client that also runs the signalling server, the way a call starts."""
description = publisher("host", serve=True)
def __init__(self, pipeline: Gst.Pipeline, **kwargs: Any) -> None:
os.environ.setdefault("WEBRTCSINK_SIGNALLING_SERVER_LOG", "error") # not a line per peer
super().__init__(pipeline, **kwargs)
Source: examples/webrtc_client.py · tested by test_two_clients_in_one_process_each_receive_the_other
The program
main wires the options to these: --serve picks Host, --call a call that ends the
program, and --demo runs both sides in one process. A call has 30 seconds to get going.
TIMEOUT = 30 # seconds for a call to get going and show its frames
async def until(client: Client, done: Callable[[], object]) -> None:
"""Wait for `done()`, and raise the error if the pipeline fails meanwhile."""
while not done():
if client.error is not None:
raise client.error
await asyncio.sleep(0.1)
async def talk(client: Client, peer: str | None, frames: int) -> str:
"""Call `peer` once it publishes; return who it was when its video has `frames` frames."""
def called() -> bool:
try:
client.call(peer)
except CommandError:
return False # not there yet
return True
await until(client, called)
remote = client.producers[client.remote or ""]
await until(client, lambda: client.frames >= frames)
return f"{client.name} received {frames} frames from {remote}"
async def demo(server: str, frames: int) -> None:
"""A call on one machine: alice runs the signalling server, and she and bob call each other."""
async with (
Host.from_description(publisher("alice", server=server, serve=True)) as alice,
Client.from_description(publisher("bob", server=server)) as bob,
):
await alice.play()
await until(alice, lambda: alice.peer_id) # the server is listening
await bob.play()
for line in await asyncio.gather(talk(alice, "bob", frames), talk(bob, "alice", frames)):
print(line)
alice.hangup() # both, before either one stops publishing
bob.hangup()
async def run(args: argparse.Namespace) -> None:
if args.demo:
async with asyncio.timeout(TIMEOUT):
await demo(args.server, args.frames)
return
description = publisher(args.name, server=args.server, serve=args.serve, camera=args.camera)
async with (Host if args.serve else Client).from_description(description) as client:
client.sink = args.sink
await client.play()
if args.call is None:
await asyncio.Event().wait() # publish until interrupted
async with asyncio.timeout(TIMEOUT):
print(await talk(client, args.call or None, args.frames))
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Publish a video source and call another client.")
parser.add_argument("--name", default="client", help="the name to publish under")
parser.add_argument(
"--server", default=SERVER, help="the signalling server (default: %(default)s)"
)
parser.add_argument("--serve", action="store_true", help="also run the signalling server")
parser.add_argument(
"--camera", action="store_true", help="publish the camera, not a test pattern"
)
parser.add_argument(
"--sink", default=Client.sink, help="where the remote video goes (default: %(default)s)"
)
parser.add_argument(
"--call",
nargs="?",
const="",
metavar="PEER",
help="call a client by id or name, or the first that publishes, and exit once its "
"video has --frames frames",
)
parser.add_argument(
"--frames", type=int, default=60, help="frames to wait for (default: %(default)s)"
)
parser.add_argument(
"--demo", action="store_true", help="run alice and bob in this process, calling each other"
)
args = parser.parse_args(argv)
try:
asyncio.run(run(args))
except TimeoutError:
print(f"error: no call within {TIMEOUT} s")
return 1
except PlayerPipelineError as exc:
print(f"error: {exc}")
return 1
except KeyboardInterrupt:
return 130
return 0
if __name__ == "__main__":
raise SystemExit(main())
Source: examples/webrtc_client.py · tested by test_two_clients_in_one_process_each_receive_the_other
The control page
Because a client is a Player, mixtape run starts it with a control page. A host and a client,
each with its page, make a call you can drive from the browser: open the client's page, and
call the host from its commands.
$ mixtape run examples/webrtc_client.py:Host --http 8047 > /dev/null &
$ mixtape run examples/webrtc_client.py:Client --http 8048
Serving on http://127.0.0.1:8048
The first command is in the background, with its output silenced; in a terminal of yours,
run each in a terminal of its own and the host says Serving on http://127.0.0.1:8047.
The page lists the properties of the last section, and the elements of the pipeline: out,
the sink with its signaller, and during a call in, the source with its webrtcbin, and the
converter and sink after it. connection goes from new to connected, and frames counts
up.
Performance
--feature perf measures a pipeline with GStreamer's tracers. The sending side exists from
the start, and is measured as any pipeline is:
$ mixtape run examples/webrtc_client.py:Host --http 8047 --feature perf
Serving on http://127.0.0.1:8047
The receiving side is different: call adds its elements after perf has started, so perf has no
record of their creation, and says so in a warning for each. What it measures of them is
incomplete. See Measuring performance for what the page shows.