rtpflux documentation
rtpflux is a media relay for SIP calls. Start with the page that matches what you want to do.
I want to run it
- Getting started: build, configure, run, and follow a call through the relay.
- Configuration: every setting, with examples.
- Control protocol: connect Kamailio or OpenSIPS, and the commands and options they can send.
- Integration: tested Kamailio, OpenSIPS, ferrosip and FreeSWITCH configurations.
- Operations: metrics, logs, restarts and the systemd service.
- Web UI: a read-only website with live traffic, calls, statistics and logs.
I want to know what it can do
- Media handling: NAT traversal, SRTP, WebRTC (ICE, DTLS, BUNDLE), re-INVITEs and hold.
- Call features: DTMF detection, blocking, recording, announcements, transcoding and call-quality statistics.
- XDP fast path: forwarding calls inside the network driver.
- Benchmarks: how fast it is, and how that is measured.
I want to work on the code
- Architecture: threads, the path of a packet and the crates.
- Testing: the test suites, browser tests and kernel tests.
- Conformance: checking rtpflux against an independent reference model.
- AGENTS.md: the rules every change follows.
Terms
The Glossary explains SIP, SDP, RTP, SRTP, ICE, BUNDLE and the other terms used throughout, in plain English.
Getting started
This guide takes you from source code to a running relay. It also walks through what happens during a call.
1. Requirements
- Linux (the relay uses
epollandrecvmmsg/sendmmsg). - Rust. The exact version is pinned in
rust-toolchain.toml;rustupinstalls it automatically the first time you build.
rtpflux is written entirely in Rust, including its cryptography (SRTP,
DTLS, Opus), so it needs no C libraries or C compiler. Two optional
features need a C compiler: mp3 (MP3 recordings, through LAME) and
s3 (recordings uploaded to S3, over rustls and ring):
cargo build --release --features mp3,s3. The amr feature (pure Rust)
adds AMR and AMR-WB transcoding; it is off by default because of AMR’s
patents.
The optional XDP fast path has extra requirements; see XDP fast path.
2. Build
git clone https://github.com/RustedBytes/rtpflux.git
cd rtpflux
cargo build --release
The binary is target/release/rtpflux. To make sure everything works on
your machine, run the tests:
cargo test --workspace
3. Configure
The configuration is a TOML file. Print the fully commented example and edit it:
./target/release/rtpflux --print-example-config > rtpflux.toml
Only [[interface]] is required. A relay with one public address can be
as short as this:
[control]
listen = ["127.0.0.1:2223"]
[[interface]]
name = "default"
address = "203.0.113.10"
[control] listenis where the SIP proxy sends its commands. Keep it on a private address: the ng protocol has no authentication.[[interface]] addressis the local address media uses. If the server is behind a 1:1 NAT (common in clouds), also setadvertiseto the public address. That is the address written into the SDP.
Check the file before starting:
./target/release/rtpflux --check -c rtpflux.toml
rtpflux.toml: configuration is valid
If something is wrong, --check lists every problem at once, for example
a port range too small for the number of sessions. See
Configuration for all options.
4. Run
./target/release/rtpflux -c rtpflux.toml
INFO rtpflux: rtpflux 0.2.0 starting: 1 interface(s), ports 30000-60000, up to 5000 sessions, xdp off
INFO rtpflux::relay: relay: 8 worker(s), 1875 port pairs each
INFO rtpflux: ng control on udp 127.0.0.1:2223
Use -l debug (or RUST_LOG=debug) for more detail. Stop the relay with
Ctrl-C or SIGTERM.
5. Install as a service
sudo install -m 755 target/release/rtpflux /usr/bin/rtpflux
sudo mkdir -p /etc/rtpflux
sudo cp rtpflux.toml /etc/rtpflux/rtpflux.toml
sudo cp contrib/rtpflux.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now rtpflux
The unit checks the configuration before each start, runs the relay as an
unprivileged dynamic user and keeps state in /var/lib/rtpflux. See
Operations.
5b. Or run it in a container
The repository has a Dockerfile and a compose.yaml. The container uses
the host network: a relay opens ports from [ports] for every call
and writes the host’s own address into the SDP, which port mapping cannot
do.
-
Edit
config/docker.toml. Set[[interface]] addressto an address of the host that phones can reach (it ships as127.0.0.1, for a local try-out). -
Build and start:
docker compose up -d --build # or: docker-compose up -d --build docker compose logs -f rtpflux
The image is about 90 MB: the relay on Debian slim, running as an unprivileged user. Two volumes keep data across restarts:
| Volume | Mounted at | Holds |
|---|---|---|
rtpflux-state | /var/lib/rtpflux | The state file: calls survive docker compose restart |
rtpflux-recordings | /var/spool/rtpflux | pcap recordings |
Without compose:
docker build -t rtpflux .
docker run -d --name rtpflux --network host --ulimit nofile=1048576:1048576 \
-v "$PWD/config/docker.toml:/etc/rtpflux/rtpflux.toml:ro" \
-v rtpflux-state:/var/lib/rtpflux rtpflux
Docker’s default seccomp profile refuses io_uring, so in a container
the media workers receive with recvmmsg, logging io_uring: Operation not permitted; using recvmmsg at start. Calls work either way; to use
io_uring (the default runtime.receive, a little less CPU per packet),
run the container with --security-opt seccomp=unconfined, or with a
seccomp profile that also allows io_uring_setup, io_uring_enter and
io_uring_register. The commented security_opt line in compose.yaml
shows where.
To use the XDP fast path in a container, grant CAP_BPF,
CAP_NET_ADMIN and CAP_PERFMON, run the container as root (added
capabilities do not reach the image’s unprivileged user), and mount the
compiled program. The commented lines in compose.yaml show how.
6. Connect your SIP proxy
Point the proxy’s rtpengine module at [control] listen. For Kamailio:
loadmodule "rtpengine.so"
modparam("rtpengine", "rtpengine_sock", "udp:127.0.0.1:2223")
and call rtpengine_manage() for messages that carry SDP. The OpenSIPS
setup is almost the same; see
Control protocol.
What happens during a call
Here is a real exchange with the relay, shown in readable form. On the wire, each command is one bencoded UDP datagram.
Alice calls Bob. Alice’s phone offers audio on 192.0.2.10:40000.
The proxy sends this offer to rtpflux:
command: offer
call-id: call-1@example.com
from-tag: alice-tag
sdp:
v=0
o=alice 1 1 IN IP4 192.0.2.10
s=-
c=IN IP4 192.0.2.10
t=0 0
m=audio 40000 RTP/AVP 0 101
a=rtpmap:0 PCMU/8000
a=rtpmap:101 telephone-event/8000
a=sendrecv
rtpflux reserves ports and replies with a rewritten SDP. The address and
port now point at the relay (here 127.0.0.1:30002):
result: ok
sdp:
v=0
o=alice 1 1 IN IP4 192.0.2.10
s=-
c=IN IP4 127.0.0.1
t=0 0
m=audio 30002 RTP/AVP 0 101
a=rtpmap:0 PCMU/8000
a=rtpmap:101 telephone-event/8000
a=sendrecv
The proxy sends this SDP to Bob instead of Alice’s original. Bob will send his audio to the relay.
Bob answers. The proxy passes Bob’s answer (audio on
198.51.100.20:50000) to rtpflux with command: answer and both tags.
rtpflux rewrites it to point at another relay port, 30000, and the
proxy sends that to Alice. Now:
Alice 192.0.2.10:40000 ⇄ relay :30000 │ relay :30002 ⇄ Bob 198.51.100.20:50000
During the call the proxy can ask how the call is doing with
command: query. The reply lists each party’s streams with the
relay’s port, the peer’s address, packet counters, detected DTMF and RTCP
statistics. See Control protocol.
Bob hangs up. The proxy sends command: delete with the Call-ID. The
relay frees the ports.
If a party is behind NAT, the address in its SDP may be wrong. The relay then latches onto the address its packets really come from; see Media handling.
Next steps
- Configuration: multiple interfaces, timeouts, metrics, recording and restarts.
- Media handling: WebRTC, SRTP and NAT.
- Call features: DTMF, recording, announcements and transcoding.
Configuration
rtpflux reads one TOML file, by default /etc/rtpflux/rtpflux.toml. Pass
another path with -c:
rtpflux -c /path/to/rtpflux.toml # run
rtpflux --check -c /path/to/rtpflux.toml # validate and exit
rtpflux --print-example-config # print the commented example
The commented example is also in the repository as
config/rtpflux.toml.
Rules
- Every section is optional except
[[interface]]. A missing key takes its default value (shown below). - Unknown keys are an error. That catches typos such as
adress. --checkreports every problem at once, not just the first:
rtpflux: bad.toml: invalid configuration:
- interface 'a': address must be a concrete address
- ports.min: must be even and non-zero (RTP on even, RTCP on odd ports)
- ports: 5 RTP/RTCP pairs cannot serve sessions.max = 100 (two pairs per call)
- Besides the per-key ranges below, the check rejects listeners that
clash (two sockets of one transport on the same port, with the same
address or a wildcard), a
control.listenport inside the media port range of an interface on the same address,xdp.devicesentries that are not device names, and interface names with whitespace. - Settings that are valid but probably not what was meant are
warnings: they never stop the relay.
--checkprints them on stderr and still reports the file as valid; at start-up they are logged atwarn. They covernglisteners reachable beyond loopback and private networks, a web UI not on loopback, Redis without a password or on another host, settings that have no effect (for examplexdp.deviceswithenabled = false,bitratefor a lossless format,[recording.s3]with local storage), moreworkersthan the port range can use, ports below 1024, and relative paths.
rtpflux: rtpflux.toml: warning: webui.listen: 0.0.0.0:8090 is not loopback; the login travels without TLS unless a reverse proxy adds it
rtpflux.toml: configuration is valid
[control]: the SIP proxy’s connection
[control]
listen = ["127.0.0.1:2223"] # default
listen_tcp = [] # ng over TCP (none by default)
listen_http = [] # ng over HTTP and WebSocket (none by default)
max_message = 65535 # largest command, in bytes (512 to 65535)
# native_socket = "/run/rtpflux/native.sock" # the native API (off by default)
native_uids = [] # user ids allowed on native_socket, besides the relay's and root
native_max_endpoints = 0 # endpoints per tenant on the native API (0: up to sessions.max)
# pcm_dir = "/run/rtpflux/pcm" # where external audio services listen (PCM streams)
native_listen = [] # the native API over TCP too (needs native_tokens)
native_tokens = {} # tenant = "token" (16 characters or more), for native_listen
native_event_journal = 65536 # native API events kept for replay from a cursor
listen takes one or more address:port pairs. The ng protocol has no
authentication, so listen only on loopback or a private network that only
your SIP proxies can reach. listen_tcp and listen_http serve the same
commands over TCP, and over HTTP (POST /ng, /ng-plain) and WebSocket
(ng.rtpengine.com); see
Over TCP, HTTP and WebSocket.
native_socket serves the native control API, for a
B2BUA or softswitch that manages media endpoints itself. It is a Unix
socket: only the relay’s own user, root and the user ids in native_uids
may connect (checked with the peer’s credentials). The file is mode 0600,
0666 when native_uids lists other users, or 0660 with
native_socket_group.
native_listen serves the same API over TCP, for a softswitch on another
host. Each connection authenticates with one of native_tokens first, or
with one of native_tokens_file (re-read when it changes, for rotation),
and is then that tenant’s. There is no TLS. A non-loopback native_listen
is refused unless native_allow_remote = true: listen on loopback behind
an authenticated TLS proxy.
native_rate_limit caps the requests per second of each tenant.
ng_protect_native keeps ng from changing calls that hold native
endpoints. See Connecting. pcm_dir is the directory where external audio services listen
for PCM streams; a stream names its socket by
its file name there.
[[interface]]: where media flows
Each [[interface]] block is a named local address. You need at least
one.
[[interface]]
name = "external"
address = "203.0.113.10"
| Key | Meaning |
|---|---|
name | Name used by the proxy to pick the interface (direction). Must be unique. |
address | Local IPv4 or IPv6 address the media sockets bind to. Must be a real address, not 0.0.0.0. |
advertise | Address written into the SDP. Defaults to address. |
Example: behind a 1:1 NAT. Many cloud servers have a private address on the network card and a public address mapped onto it. Bind to the private one and advertise the public one:
[[interface]]
name = "public"
address = "10.0.0.5" # on the network card
advertise = "198.51.100.20" # what phones must send to
Example: bridging two networks. A relay with one leg on the internet and one on an internal network:
[[interface]]
name = "external"
address = "203.0.113.10"
[[interface]]
name = "internal"
address = "10.0.0.5"
The proxy then chooses per call with the direction option, for example
direction=external direction=internal in Kamailio. The first name is
the offerer’s side and the second the answerer’s. Without direction,
both sides use the first interface. See
Control protocol.
[ports]: the media port range
[ports]
min = 30000 # default; must be even
max = 60000 # default
RTP uses even ports and RTCP the next odd port. Each call needs two
pairs, one for each side, so the range must hold at least
2 × sessions.max pairs. The defaults give 15,000 pairs, enough for the
default 5,000 sessions. Open this range in your firewall.
[sessions]: limits and timeouts
[sessions]
max = 5000 # most calls at once
timeout = 60 # seconds without media before a call ends
silent_timeout = 3600 # the media timeout of calls on hold
final_timeout = 0 # the longest a call may last (0: no limit)
offer_timeout = 3600 # seconds an offer waits for its answer
strict_source = false # every call as if flagged strict-source
# state_file = "/var/lib/rtpflux/state.json"
# redis = "redis://:password@127.0.0.1:6379/0"
# redis_key = "rtpflux:state"
# ledger = "/var/lib/rtpflux/ledger.jsonl" # the native API's durable operation ledger
ledger_retention = 86400 # seconds an operation's outcome is kept
ledger_quota = 100000 # operation keys kept per tenant
timeoutends an answered call whose media stopped in both directions. That protects against proxies that never senddelete, for example after a crash. It counts from the answer, so a call that rang for a long time is not ended the moment it is answered.offer_timeoutends an offer that is never answered, this long after the offer, whether or not early media flows. While a call rings, the media timeout does not apply. The default (an hour) is rtpengine’s.- When a call ends on its own like this, its dialog is removed too: later commands for it get “unknown call”, and its ports can serve new calls.
silent_timeoutreplacestimeoutfor a call on hold: a media section that either party offered or answeredsendonly,recvonlyorinactive, or with the address0.0.0.0. A held call without music on hold sends nothing, so it would otherwise end aftertimeout. When the call is resumed (sendrecvagain),timeoutapplies again. It must not be shorter thantimeout.- Native API endpoints and parties made by
createfollow the same rules: an endpoint whose side sends nothing fortimeoutends (endpoint.timeout, thenendpoint.destroyedwith reasontimeout), bridged or not, a video room’s too. It is held only when its own SDP says so. Media sent to an endpoint counts as well, so a listener bridged to a talker stays. final_timeoutends a call this many seconds after its first offer, whatever its media (0, the default: no limit).strict_source = truetreats every call as if the proxy sent thestrict-sourceflag: once the relay has learned a side’s address from its media, media from any other source is dropped, so a third party cannot inject audio into a call. The cost: a phone whose NAT mapping changes mid-call is not followed. See NAT and latching.maxis the most calls (dialogs) at once: an offer for a new call beyond it is refused withsession limit reached; re-offers of existing calls always pass.state_filekeeps calls across restarts. See Operations.rediskeeps the same state in Redis, as well as or instead of the file:redis://[[user]:password@]host[:port][/db](port 6379 and database 0 by default;rediss://with TLS is not supported).redis_keyis the key (defaultrtpflux:state); give each relay its own. See Operations.ledgermakes the native API’s operation keys durable. It needsstate_file. A keyed mutation’s state and its outcome reach the disk, in one journal record, before it is acknowledged. A retry after a crash gets the first outcome or runs it, never twice. A relay that cannot open its ledger does not start. See Operation keys and the ledger.
The state journal
With state_file, changes are appended to a journal beside it
(<state>.journal.<generation>) instead of rewriting the whole file:
- Records. Each one holds what changed: the sessions, endpoints and recordings touched, new tombstones, the other state when it changed, and a keyed operation’s outcome. It is not the whole state, so its cost does not grow with the number of calls.
- Syncs. They run on a thread of their own, many records at once (group commit). A durable reply waits for its record; nothing else waits for the disk.
- Compaction. When the journal holds more than 4 MiB, and four times the last snapshot, the whole state is written as a new snapshot (the state file), and a new journal file begins. The old one is removed once the snapshot is on the disk. At a start and at a stop the state is written whole too.
- Restart. The snapshot, then the journal files of its generation and after, in order. A record cut short by a crash is skipped.
Measured (tests/durable.rs, 16 connections making and destroying
endpoints with keys, durable, on an i9-9900K):
| Live endpoints | Before the journal | With it |
|---|---|---|
| 10 | 63 operations/s, p50 222 ms | 2943 operations/s, p50 4.7 ms |
| 1000 | 17 operations/s, p50 783 ms | 1677 operations/s, p50 8.0 ms (p99 101 ms: compactions) |
A slow disk no longer stops the control thread either. Before, a request
could time out (the relay is busy) behind a state file sync.
[ha]: exclusive controller ownership
[ha]
enabled = false
state = "/var/lib/rtpflux/ownership.json" # accepted claims, synced
authority_keys = { k1 = "…" } # key id → HMAC-SHA256 secret
enabled: fencing of the native API. Every mutation must prove three things for the groups of the resources it touches: the current ownership epoch, a running lease, and the owner’s token. Grants come from an ownership authority that signs them with one ofauthority_keys.ngcannot change a call holding native endpoints; it can still read it.state: the highest epoch accepted per group, synced before a claim is acknowledged. A relay that cannot read it does not start.authority_keys: each at least 32 characters. Several keys allow rotation: a claim names itskey_id.
See Exclusive ownership.
[runtime]: threads and buffers
Everything here is allocated once at start-up; nothing grows while calls run.
[runtime]
workers = 0 # media threads; 0 = one per CPU
batch = 32 # packets per receive/send system call (1 to 64)
ring_capacity = 4096 # packet slots per worker (a power of two)
packet_buffer = 2048 # bytes per packet buffer (1500 to 65535)
receive = "io_uring" # or "recvmmsg"
pcm_shards = 0 # threads serving every PCM stream; 0 = one per CPU, at most 4
The defaults suit most systems. A smaller workers value leaves CPUs for
other services on the same host.
receive chooses how the media workers read their sockets:
io_uring(the default; Linux 6.0 or later): one multishot receive per socket keeps receiving into a ring ofring_capacitybuffers per worker (eachpacket_bufferplus 144 octets), and the datagrams of every socket are read from one completion queue, with no system call per socket or packet. A worker whose kernel lacks it, or where it is not allowed, logs a warning and usesrecvmmsg. Docker’s default seccomp profile does not allow it: in a container, see Getting started. It costs the buffers’ memory (9 MB per worker with the defaults).pcm_shards: the threads that serve PCM streams (stream.start). Each serves many streams, and a stream stays on one, so there are no threads per stream. See PCM streams.recvmmsg: epoll says which sockets have datagrams, and each is read in batches of up tobatch, one system call per socket per batch. With many calls, each socket has a packet or two at a time, so that is about one system call per packet.
On an Intel Xeon E5-1620 v3 (4 cores, 8 threads; Linux 7.0, loopback,
172-octet datagrams),
cargo bench -p rtpflux-uring measured the receiving thread’s CPU time
per datagram:
| Load | recvmmsg | io_uring |
|---|---|---|
| 1 socket, flooded | 2.6 µs | 2.2 µs (1.2×) |
| 16 sockets, 100 000 packets/s | 3.1 µs | 2.2 µs (1.4×) |
| 256 sockets, 100 000 packets/s | 3.7 µs | 2.3 µs (1.6×) |
| 1024 sockets, 100 000 packets/s | 3.7 µs | 2.3 µs (1.6×) |
| 4096 sockets, 200 000 packets/s | 3.7 µs | 2.7 µs (1.4×) |
Measure on your own hardware: the gain depends on the
kernel, the NIC and how many calls each worker carries. Sending is
sendmmsg either way, and calls in the XDP fast path do not
reach the workers at all.
[xdp]: the kernel fast path
[xdp]
enabled = false # default
devices = ["eth0"] # required when enabled
mode = "native" # or "generic"
object = "/usr/lib/rtpflux/rtpflux-xdp" # the compiled XDP program
af_xdp = false # AF_XDP receive path (af-xdp builds)
af_xdp_frames = 2048 # AF_XDP memory per queue, 4 KiB frames
af_xdp receives the traffic the kernel does not relay (SRTP, WebRTC,
BUNDLE, calls not settled yet) through AF_XDP sockets on the first device
in devices, instead of the kernel’s UDP stack. It needs enabled = true
and a build with the af-xdp cargo feature. af_xdp_frames (64 to
65,536) is the memory of each receive queue’s socket, in 4 KiB frames:
the default 2,048 frames is 8 MiB per queue.
With XDP enabled, sessions.max can be at most 16,384, because the
kernel’s flow table holds 65,536 entries and each call uses 4. See
XDP fast path.
[log]: logging
[log]
level = "info" # error, warn, info, debug or trace
format = "full" # or "compact"
The -l/--log-level option overrides level, and so does the
RUST_LOG environment variable. See Operations.
[metrics]: Prometheus metrics
[metrics]
listen = ["127.0.0.1:9101"] # default: [] (off)
Serves GET /metrics. See Operations.
[webui]: the web UI
[webui]
listen = "127.0.0.1:8090" # default: none (off)
user = "admin" # required with listen
password_hash = "sha256:…" # required with listen: rtpflux --webui-hash
realm = "rtpflux" # the login prompt's realm
max_connections = 64 # concurrent HTTP connections (1 to 4096)
refresh_ms = 2000 # how often the pages refresh (500 to 60000)
log_buffer = 2000 # log lines kept for the Logs page (0: off)
A read-only website showing traffic, calls, statistics and logs. Keep it
on 127.0.0.1 or behind a TLS reverse proxy: the login is sent with
every request. See Web UI.
[recording]: call recordings
[recording]
dir = "/var/spool/rtpflux"
format = "pcap" # pcap, wav, flac, opus or mp3
channels = "stereo" # or mono
sample_rate = 8000 # 8000, 16000, 24000 or 48000
bitrate = 32 # kbit/s, for opus and mp3
keep_pcap = false # keep the pcap once converted
storage = "local" # or "s3"
file_name = "{call_id}-{from_tag}-{section}" # the default
max_mixer_recordings = 64 # conference mixers recorded at once
[recording.metadata] # tags in every recording (optional)
company = "Example Ltd"
[recording.s3] # with storage = "s3"
bucket = "call-recordings"
region = "eu-west-1"
# endpoint = "https://minio.example.com" # S3-compatible servers
prefix = "rtpflux/"
path_style = false
keep_local = false
[recording.s3.webhook] # optional: notify after each upload
url = "https://hooks.example.com/recordings"
timeout_ms = 5000 # each attempt, DNS to response
connect_timeout_ms = 2000
attempts = 5
backoff_ms = 1000 # doubled per retry, jittered
backoff_max_ms = 30000
queue = 1000
dir is where start recording writes. It is created at start; without
it, recording requests are refused. The other keys choose what a
recording becomes when it ends; start recording can override each of
them per call. mp3 needs a build with the mp3 feature.
file_name names the files (without the extension). It is text made of
letters, digits and . - _ @, and the placeholders {call_id},
{from_tag}, {to_tag}, {section}, {date} (2026-11-25), {time}
(142530, both UTC, when the recording starts) and {timestamp} (Unix
seconds); for a conference mixer’s recording (native API), {mixer_id},
{recording_id} and {track} too (-, - and empty for a call’s).
With the default file_name, a mixer recording is called
mixer-{mixer_id}-{recording_id}-{section}{track}. Values are made file-name safe as before. A name that a file
already has is never reused: the next recording of it gets -2, -3,
…, so even a template without the call-id never mixes two recordings
(--check warns about one without {call_id} and {section}). For
example, "{date}_{time}-{call_id}-{section}" sorts by time.
max_mixer_recordings limits the conference mixers recorded at once
through the native API (recording.start with a mixer_id; see
Recording a mixer).
[recording.metadata] holds tags every recording carries, in its JSON
and embedded in its audio file; see
Recording metadata.
storage = "s3" uploads finished recordings to a bucket and removes the
local copies; it needs a build with the s3 feature, and credentials in
the environment (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY). See
Storing recordings in S3.
[recording.s3.webhook] posts a notification after each upload; see
Upload notifications.
[ice]: ICE towards endpoints that use it
| Key | Default | Meaning |
|---|---|---|
mode | "full" | "full": the relay is a full ICE agent (it checks the endpoint’s candidates, nominates or accepts a nomination, keeps checking consent); "lite": it only answers checks. The ICE-lite option overrides it per call. See ICE. |
pacing_ms | 50 | Ta: how often the relay’s agents send a new check (5–1000 ms) |
stun_server | none | A STUN server (host:port) the relay asks for its public address on each interface without advertise, at start and every 5 minutes; it is offered as a server-reflexive candidate |
[ice]
mode = "full"
pacing_ms = 50
# stun_server = "stun.example.net:3478"
The server-reflexive candidate uses the media port itself, so it is right
behind a NAT that keeps ports (a 1:1 NAT, or an endpoint-independent one
that preserves them). Elsewhere it does no harm: the endpoint’s checks to
the host candidate still find their way, and the relay learns the address
they come from. With a known public address, set advertise on the
interface instead.
A complete example
A relay on a cloud server behind NAT, with an internal leg, metrics, restarts and recording:
[control]
listen = ["10.0.0.5:2223"]
[[interface]]
name = "external"
address = "10.0.0.5"
advertise = "198.51.100.20"
[[interface]]
name = "internal"
address = "10.1.0.5"
[ports]
min = 20000
max = 40000
[sessions]
max = 4000
state_file = "/var/lib/rtpflux/state.json"
[metrics]
listen = ["10.0.0.5:9101"]
[recording]
dir = "/var/spool/rtpflux"
Control protocol
A SIP proxy controls rtpflux with the ng protocol, the protocol of
rtpengine. If your proxy already uses its rtpengine module, it can use
rtpflux without changes. This page describes the commands rtpflux
understands and the options it reads.
How messages look
Each command is one UDP datagram sent to [control] listen. It has two
parts:
<cookie> <bencoded dictionary>
- The cookie is a random string chosen by the proxy. The reply starts with the same cookie, so the proxy can match replies to requests.
- The dictionary holds the command and its options, in bencode.
For example, a ping:
5323_1 d7:command4:pinge
and its reply:
5323_1 d6:result4:ponge
Every reply has result. It is ok (or pong) on success, or error
with an error-reason:
result: error
error-reason: missing sdp
A successful reply may also carry a warning (as rtpengine’s do) when
part of the request was ignored: an option, flag, replace or SDES
value rtpflux does not implement (option frobnicate: not supported, ignored), a codec name the relay does not know in codec: transcode, or
a codec: mask with no codec to transcode to. rtpflux also logs each
warning at debug.
If the proxy resends a request because the reply was lost, rtpflux recognises the cookie and sends the same reply again, without running the command twice. Only the same request counts: a cookie reused for a different request (a proxy whose counter restarted, say) runs that request. Replies are kept for 30 seconds, per sender: two proxies that send the same cookie (Kamailio’s are made of its server id, process id and a counter, so identical containers send identical ones) each get the reply to their own request.
Over TCP, HTTP and WebSocket
Besides UDP, rtpflux takes the same messages on streams, as rtpengine
does ([control] listen_tcp, listen_http):
- TCP: messages back to back on a connection,
<cookie> <bencoded dictionary>each, with no length prefix (a message ends where its dictionary does); replies the same way. A connection that sends something else is closed: no space within the first 256 bytes, an empty cookie, a dictionary that is not strict bencode (integers without leading zeros or-0and within 64 bits, no repeated key, at most 256 keys, nesting below 32), or a message over 65 535 bytes. - HTTP (
POST /ng,Content-Type: application/x-rtpengine-ng): the body is one message and so is the reply.POST /ng-plaintakes the dictionary without a cookie, asapplication/x-rtpengine-ng(bencode) orapplication/json.GET /pinganswerspong. - WebSocket (on the HTTP endpoints): subprotocol
ng.rtpengine.com, one message per WebSocket message (<cookie> <dictionary>), orng-plain.rtpengine.com(no cookie); replies come in binary frames. As RFC 6455 requires of a server with no extension, the connection is failed on a frame that is not masked, has a reserved bit or opcode, is a fragmented or long control frame, has a length not in its shortest form, or (rtpflux’s limit) carries over 65 535 bytes; a continuation frame needs a fragmented message in progress, and a new message must wait for the end of one. A failed connection gets a Close frame first (RFC 6455 §7.1.7): 1002 (protocol error), or 1009 for a message that grows over the limit across fragments. Kamailio’s rtpengine module connects this way withrtpengine_sock "ws://host:port"(andwss://through a TLS proxy).
On HTTP and WebSocket the dictionary may be JSON instead of bencode (it
starts with {); the reply is then JSON too:
POST /ng-plain {"command":"ping"}
→ 200 application/json {"result":"pong"}
rtpflux does not speak TLS itself: for HTTPS and WSS, put a TLS proxy in front.
Commands
| Command | What it does |
|---|---|
ping | Checks that the relay is alive |
offer | Sets up (or changes) a call from an SDP offer |
answer | Completes a call from the SDP answer |
delete | Ends a call |
rollback | Takes back a re-offer that was not answered |
list | Lists active calls |
query | Reports one call’s streams and statistics |
block media, unblock media | Stops or resumes relaying a participant’s audio |
block DTMF, unblock DTMF | Stops or resumes relaying a participant’s key presses |
start recording, stop recording, pause recording | Records a call to pcap files |
play media, stop media | Plays an announcement to a participant |
play DTMF | Sends key presses as if a participant had pressed them |
silence media, unsilence media | Replaces a participant’s audio with silence, keeping the stream |
statistics | Reports the relay’s counters |
subscribe request, subscribe answer, unsubscribe | Sends copies of parties’ media to a third party (a SIPREC recorder) |
publish | Takes media from a party that only sends, for others to subscribe to |
create, create answer | Makes an offer for a party of the relay’s own, answered by an endpoint such as a media server |
create from offer | Answers an endpoint’s offer for a party of the relay’s own, with no other party (rtpflux’s own) |
inject start, inject stop | Sends one party’s media to another party as well, one way |
mesh | Sends parties’ media to other parties, of one call or several, in one request |
connect | Joins a party of one call with a party of another, or copies parties’ media to another |
A call is identified by its SIP Call-ID and the tags of its two parties (see the glossary).
ping
No options. Replies result: pong.
offer
Sends an SDP offer through the relay. rtpflux allocates ports for each media section and replies with the SDP rewritten to point at the relay. The proxy forwards that SDP instead of the original.
| Option | Required | Meaning |
|---|---|---|
call-id | yes | The SIP Call-ID |
from-tag | yes | The tag of the party sending the offer |
sdp | yes | The offer |
to-tag | no | Present in a re-INVITE: the dialog with that party (see Calls with more than two parties) |
label (or set-label) | no | A label for the offerer, which later commands can name it by |
via-branch | no | The branch of a forked INVITE: another branch’s offer (an initial one, while the dialog is unanswered) gets media of its own, and the branch whose answer names it becomes the dialog |
| other options | no | See Options |
The reply has sdp, the rewritten offer.
A second offer in the same dialog is a re-INVITE: hold, resume,
new codecs, a new address, an added or removed stream. The relay keeps
the call’s ports and keys, so the other party sees no change it does not
need to see. A re-INVITE can come from either party. If the
from-tag is the original answerer’s, the relay swaps the roles for
the new exchange. See Media handling.
answer
Passes the SDP answer through the relay and completes the call.
| Option | Required | Meaning |
|---|---|---|
call-id | yes | The SIP Call-ID |
from-tag | yes | The offerer’s tag (as in the offer) |
to-tag | yes | The answerer’s tag |
sdp | yes | The answer |
label (or set-label) | no | A label for the answerer |
The reply has sdp, the rewritten answer for the offerer. An answer
section whose formats are all static payload types (0–95) that were not
offered, neither by the offerer nor by the relay’s transcoding, is refused
(RFC 3264 §6.1); dynamic payload types pass, since an answer may renumber
them.
delete
Ends a call and frees its ports.
| Option | Required | Meaning |
|---|---|---|
call-id | yes | The SIP Call-ID |
from-tag | no | Only the dialog with this tag (either party’s) |
to-tag | no | Only if the dialog was answered with this tag (or it is the offerer’s): a forked call’s losing branch deletes nothing |
via-branch | no | Only that branch of a forked INVITE (a losing branch’s media), or a dialog whose offer carried it (or none) |
delete-delay | no | Seconds the call goes on before it ends (default 0: at once), for media still in flight |
flags: fatal | no | Deleting nothing is an error |
When nothing matches (an unknown call, another fork’s tag, another
branch), the reply is ok with the warning Call-ID not found or tags didn't match, as rtpengine’s; with fatal, it is the error unknown call.
rollback
Takes back a re-offer that has not been answered (the answerer rejected
the re-INVITE): the dialog returns to its last agreed media (addresses,
ports, codecs, profile, SRTP keys, ICE credentials, DTLS roles), as
rtpengine’s rollback does. Only a re-offer of an answered dialog that
carried flags: track-state can be taken back: it keeps the dialog as
last agreed until its answer (offers before the answer share it), and
the relay calls of sections it removed go on meanwhile. The answer commits
it; a section it removed ends then.
| Option | Required | Meaning |
|---|---|---|
call-id | yes | The SIP Call-ID |
from-tag | yes | Either party’s tag |
to-tag | yes (or via-branch) | The other party’s tag |
via-branch | no | Names the dialog by the branch of its latest offer instead |
The reply’s rolled-back is 1 when a re-offer was taken back, 0 when
there was none to take back (so a repeated rollback is harmless).
Sections the re-offer added end. A rollback names the dialog with the
tags either way round, also after a re-offer by the answerer. A pending
re-offer is kept across a restart of the relay (with the calls of the
sections it removed), so it can be rolled back after one.
list
Lists the Call-IDs of active calls, sorted. limit (an integer) returns at
most that many.
result: ok
calls: [ "call-1@example.com" ]
subscriptions:
- { call-id: "call-1@example.com", to-tag: rec-1, from-tags: [ alice-tag, bob-tag ] }
subscriptions lists the subscriptions
of every call (limit applies to calls only).
query
Reports a call’s streams. Options: call-id, and optionally a party
(to-tag or to-label, else from-tag or label): only the dialogs
that party is in. A shortened real reply:
result: ok
created: 1795509703 # Unix time of the offer
totals:
RTP: { packets: 1500, bytes: 258000, errors: 0 }
RTCP: { packets: 12, bytes: 1056, errors: 0 }
tags:
alice-tag:
tag: alice-tag
label: caller # if it has one
created: 1795509703
in dialogue with: bob-tag
subscriptions: [ { tag: bob-tag, type: offer/answer } ] # what it receives
subscribers: [ { tag: rec-1, type: pub/sub } ] # who gets copies of it
medias:
- index: 1
protocol: RTP/AVP
streams:
- local port: 30000 # the relay's RTP port
endpoint: { family: IPv4, address: 192.0.2.10, port: 40000 }
stats: { packets: 750, bytes: 129000, errors: 0 }
DTMF: [ { event: "5", timestamp: 3200, duration: 160 } ]
RTCP: { reports: 6, SSRC: 1234, fraction lost: 0,
packets lost: 0, jitter: 12, RTT: 41, ... }
- local port: 30001 # the relay's RTCP port
...
bob-tag:
...
rec-1: # a subscription
tag: rec-1
created: 1795509710
answered: 1
subscriptions: [ { tag: alice-tag, type: pub/sub }, { tag: bob-tag, type: pub/sub } ]
medias:
- index: 1
type: audio
protocol: RTP/AVP
streams:
- local port: 30010
endpoint: { family: IPv4, address: 192.0.2.50, port: 50000 }
stats: { packets: 750, bytes: 129000, errors: 0 } # copies sent
- ...
- Each party is there once. A party in several dialogs (see Calls with
more than two parties) has the
media of all of them, numbered on;
in dialogue withnames the first party it is in a dialog with,subscriptionsall of them. statscounts what the relay received on that port;errorscounts packets it dropped. On a subscription’s streams it counts the copies sent to the subscriber.subscriptionsandsubscriberslink the tags (rtpengine’s form): the two parties of a dialog receive from each other (offer/answer), a subscription from its sources (pub/sub). Withfrom-tag, a subscription is reported when it is that tag’s or one of its sources’.DTMFlists detected key presses; see Call features.RTCPappears once the endpoint has sent RTCP reports; see Call features.
Packets forwarded by the XDP fast path are included, as of the relay’s last poll of the kernel counters.
Block and unblock
block media, unblock media, block DTMF and unblock DTMF stop or
resume relaying what one participant sends. Options: call-id, and
from-tag (or label, from-label) naming the participant. Without
it, every participant of the call is affected. With to-tag (or
to-label) too, only what it sends to that party (in a call with more
than two parties: its side of their dialog, not of its others). See
Call features.
all chooses which of a participant’s flows block media, unblock media, silence media and unsilence media act on, as in rtpengine:
all | Flows |
|---|---|
none, offer-answer (the default) | What it sends to its dialog’s other party (or to the party it is connected to) |
except-offer-answer | Only the copies of what it sends: subscriptions, directional connect, injections (silenced copies: G.711 silence; other audio is not copied while silenced) |
flows | Both |
all (or the flag all) | Every participant of the call, whatever the tags |
block DTMF and unblock DTMF take all: all and none.
block DTMF also takes rtpengine’s DTMF security: DTMF-security
(drop, silence, tone, random, zero, DTMF, off) with
digit, frequency and volume; the triggers trigger, trigger-end,
trigger-end-time, trigger-end-digits, DTMF-security-trigger and
DTMF-security-trigger-end; and DTMF-delay. unblock DTMF ends it. See
DTMF security.
start recording and stop recording
Records every stream of a call in [recording] dir, and converts each
recording to an audio file when it ends.
| Option | Meaning |
|---|---|
call-id | The SIP Call-ID |
from-tag | Only the dialog with this tag (either party’s) |
format | pcap, wav, flac, opus or mp3 |
channels | stereo or mono |
sample-rate | 8000, 16000, 24000 or 48000 |
bitrate | kbit/s, for opus and mp3 |
keep-pcap | yes to keep the packets once converted |
metadata | Tags for this recording: a dictionary of strings (keys of letters, digits, _ - ., up to 64; values up to 1024 octets; 32 at most, with the configured ones), or one string, which becomes comment. Added to [recording.metadata], in the JSON and the audio file |
recording-path, recording-file, output-destination, recording-pattern | Where this call’s files go and what they are called, inside [recording] dir; see Recording |
Options left out take the [recording] defaults. See
Call features.
pause recording (call-id, optionally from-tag) stops writing
packets but keeps the files open; start recording then goes on in the
same files. start recording on a call already being recorded changes
nothing. A recording started again after stop recording goes to a new
file (<call>-<tag>-<section>-2.pcap, then -3, …), so the first one’s
pcap and audio file are never overwritten. An offer or answer with record-call: yes starts recording
the dialog (when [recording] dir is set; the recording options above
apply), and record-call: no stops it, as rtpengine’s record-call.
play media and stop media
Plays an audio file (MP3, FLAC or WAV) to one participant.
| Option | Required | Meaning |
|---|---|---|
call-id | yes | The SIP Call-ID |
from-tag | for play media (or label, from-label, flags: all) | The participant who hears it (either party’s tag); all (the flag, or all: all): every participant |
file | for play media, or blob | Path of an MP3, FLAC or WAV file on the relay host |
blob | for play media, or file | The file itself, in the request |
start-pos | no | Start this many milliseconds into the media |
duration | no | Play only this many milliseconds of it |
repeat-times | no | How many times to play it (default 1) |
repeat-duration | no | Repeat it for this many milliseconds in all (cut there), instead of repeat-times |
The reply’s duration is the media’s length in milliseconds (after
start-pos and duration). An announcement from a file goes on after a
restart of the relay; one from a blob does not. stop media without
from-tag stops every announcement in the call. See
Call features.
play DTMF
Sends key presses to the other party, as if the participant from-tag
names had pressed them (rtpengine’s meaning of from-tag here).
| Option | Required | Meaning |
|---|---|---|
call-id | yes | The SIP Call-ID |
from-tag | yes (or label, from-label, flags: all) | The participant “pressing” the keys (either party’s tag); all: every participant |
code | yes | The keys: a string of 0-9, *, #, A-D (several are played in turn), or one event number 0–15 |
duration | no | Milliseconds per key (default 250; clamped to 40–5000, as rtpengine does) |
pause | no | Milliseconds between keys (default 100; clamped to 0–5000) |
volume | no | The level, in dB below 0 dBm0 (default 8, i.e. −8 dBm0; clamped to 0–63) |
Values of duration, pause and volume that are not numbers are refused.
If the listener negotiated telephone-event, the keys are sent as RFC
4733 events; otherwise as in-band tones in the audio it receives: G.711,
or G.722, G.729, Opus (and AMR with the amr build), encoded by the
relay (an error if it receives neither events nor such audio). See
Call features.
silence media and unsilence media
Like block media, but the participant’s audio is replaced by silence
instead of being dropped, so the other party keeps receiving a stream.
Same options as block and unblock.
statistics
No options. The reply’s statistics dictionary has:
currentstatistics:sessionsown,sessionsforeign(always 0),sessionstotal,transcodedmedia(media sections being transcoded),calls(relayed media sections), and the traffic per second over the latest second (sampled every second):packetrate,byterateanderrorratein all, and the same with_user(userspace) and_kernel(the XDP fast path, as of the relay’s last poll of its counters; it counts no errors, soerrorrate_kernelis 0). Errors are packets dropped and packets the kernel refused to send. Octets are the UDP payloads (RTP and RTCP datagrams);totalstatistics:uptime(seconds),relayedpacketsandrelayedbytes,droppedpacketsandrelayedpacketerrors(the userspace path),relayedpackets_kernelandrelayedbytes_kernel(the XDP fast path),timeoutsessions,srtprejectedandzrtppackets;controlstatistics:requests(per command),errorsandretransmissions.
The names follow rtpengine’s where the meaning is the same.
subscribe request, subscribe answer and unsubscribe
A subscription sends a third party (the subscriber: a SIPREC recording server, a monitoring tool) copies of what parties of a call send, as rtpengine’s commands of the same names do. The subscriber only receives.
subscribe request takes the call’s call-id and the sources:
| Key | Meaning |
|---|---|
from-tag | One party, by its tag |
label, from-label | One party, by its label |
from-tags | Several parties (a list of tags) |
flags: all | Every party of the call |
to-tag | The subscription’s tag (one is made up without it) |
set-label, to-label | A label for the subscriber |
flags: siprec | Label the sections for SIPREC metadata (below) |
flags: inactive | Offer the sections inactive: nothing is sent |
transport-protocol | RTP/AVP (the default), RTP/AVPF; with SRTP (SDES: the offer carries the relay’s key, and the answer must take SRTP) RTP/SAVP, RTP/SAVPF; or for a WebRTC subscriber UDP/TLS/RTP/SAVP, UDP/TLS/RTP/SAVPF (DTLS-SRTP: the offer carries the relay’s fingerprint with a=setup:actpass, ICE-lite credentials and host candidates, a=rtcp-mux and a=mid; the answer must take DTLS-SRTP, and nothing is sent before the handshake) |
direction | list of two interface names |
address-family | IP4, IP6 |
media-address | an IP address |
The reply’s sdp is the offer to send the subscriber: one a=sendonly
media section per section of each source party (in the order of the
tags, then of the call’s sections), with the formats that party offered
or answered with and their a=rtpmap/a=fmtp lines. It also has
to-tag (the subscription’s), from-tags (the sources) and, with a
single source, from-tag. With siprec, each section has an
a=label:<n> (1, 2, …) and the reply has tag-medias (a list, per
source tag, of {tag, medias}, where each media is {index, type, label, mode}: its position in the offer counting from 1, audio or
another media type, its label, and the source party’s direction) and
media-labels (a dictionary from each label to the same, with tag).
subscribe answer takes call-id, the subscription’s to-tag and the
subscriber’s sdp (and flags: trust-address, received-from and
endpoint-learning as an answer does). Copies start then. The
subscriber receives the media as the sources send it, without
transcoding: a section it accepts must keep at least one offered format,
or the answer is refused; a section it rejects (port 0) gets nothing.
unsubscribe takes call-id and the subscription’s to-tag (or
to-label). Deleting the call (or its timing out) ends its subscriptions
too. Naming the destination of a directional connect instead stops its
copies (see connect).
connect
Joins a party of one call with a party of another (or the other party of the same call), as after a transfer: what each sends goes to the other, from the relay port it already knows, so neither needs a re-INVITE. The parties they leave are detached: their media is dropped.
| Option | Required | Meaning |
|---|---|---|
call-id | yes | The first party’s call |
from-tag | yes (or label, from-label) | The first party (either tag of the dialog) |
to-tag | yes (or to-label) | The second party (a label of the to-call-id’s) |
to-call-id | no | The second party’s call (default: the same) |
flags: directional | no | Copies instead of a transfer (below) |
flags: bidirectional | no | With directional: copies both ways |
from-tags, flags: all | no | With directional: several sources (a list of tags), or every party of the call but the destination |
Media sections are joined by type, in order: the first audio section of
each, then the second; the first video of each; and so on. A section with
no partner of its type is left out, and the reply has a warning.
Parties with no media type in common are refused (unsupported), and so
are connected to nothing; sections of the same type that are rejected
(port 0) connect nothing, with a warning. A state saved by an older
version, which does not know the parties’ SDP, is joined in order. The two calls may be on different media workers: each passes
its party’s packets to the other through a preallocated queue, which
then encrypts them (SRTP, DTLS) for its own party. When their audio
codecs differ and the relay converts both (G.711, G.722, G.729, Opus,
AMR), each one’s audio is converted for the other. When either call
ends, the other party is left alone. Connecting a party that is already
connected (a second transfer) moves it: the party it was connected to is
detached, both ways. Connections are kept in the state
file and made again after a restart. Connected calls enter the XDP fast
path once settled (on one worker or across two: each publishes its
party’s settled address for the other); the parties left behind are
dropped in the kernel.
With flags: directional, nobody is detached: what each source sends is
also copied to the destination, which keeps its own media (so it hears
its own dialog’s other party and the sources: a supervisor listening in,
or whispering with bidirectional, which copies what the destination
sends back to each source as well). Several sources (from-tags, all)
are taken only with directional, as in rtpengine. Each copy is a stream
of its own (the source’s SSRC), sent from the destination’s relay port,
encrypted for it if it uses SRTP. Copies are taken as packets arrive
(decrypted, before blocking or the source’s own transcoding) and
converted to the destination’s audio codec when it differs (G.711, G.722,
G.729, Opus, AMR: as a connection’s are); with a codec the relay does not
convert, they go as sent, and the reply’s warning says so.
Across media workers, copies pass through a preallocated queue, as a
connection’s packets do. A source with copies stays in userspace (off the
XDP fast path). Copies end when either party’s dialog does, are kept in
the state file, and stop with unsubscribe naming the destination
(call-id and to-tag or to-label).
Calls with more than two parties
One call-id may hold more than two parties (tags), each in dialogs with
one or more of the others: a B2BUA that joins its legs within one call,
a consultation before a transfer, a three-way call. Every dialog has
media of its own (its own ports), so a party in two dialogs sends to,
and receives from, two pairs of relay ports.
- An
offerwithoutto-tagfrom a new tag starts a dialog, as always. - An
offerwith ato-tagis for the dialog between those two parties: the one either of them offered, if there is one (a re-INVITE from either side). If the offerer is in a dialog with someone else and theto-tagis another party already in the call, it starts a new dialog between the two; itsanswer(same tags) finds it. Ato-tagthat is no party of the call is the answerer’s tag of the offerer’s dialog, as in a two-party call. - Each dialog ends on its own: a
deletenaming one party’s tag (and optionally the other’s into-tag) leaves its other dialogs alone.
Labels. label (or set-label) on an offer labels the offerer, on
an answer the answerer; on subscribe request (set-label or
to-label) the subscriber; on publish the publisher. A label belongs
to one party of the call (labelling another party with it moves it). The
commands that select parties take a label where they take a tag:
label or from-label for from-tag, to-label for to-tag:
block/unblock media and DTMF, silence media, play media,
stop media, play DTMF, subscribe request, connect, query. A
label no party has is an error (no party with label …). query
reports each party’s label. Labels are kept in the state file.
create and create answer
create makes an SDP offer of the relay’s own, for a new party of a call
whose media is at the endpoint that answers it (a media server, a
conference leg), as rtpengine’s create does. The proxy sends the offer
there and hands the answer back with create answer. The party then
exists like any other: join it with connect, a
subscription, or play media to it. Until then its media goes nowhere.
| Option | Meaning |
|---|---|
call-id | The call (made up, 32 hex digits, when missing) |
from-tag | The new party’s tag (made up, 16 hex digits, when missing) |
codec: offer | The formats offered: PCMU, PCMA, G722, G729, CN, opus, AMR, AMR-WB, telephone-event (default PCMA, PCMU) |
medias | Several sections: a list of dictionaries with type (audio) and codecs (a list of names, else codec: offer’s) |
label (or set-label) | A label for the party |
| other options | As for an offer: transport-protocol (SRTP with SDES, DTLS-SRTP), SDES, DTLS, ICE, direction, address-family, media-address, … |
The reply has call-id, from-tag and sdp (the offer). create
again with the same tags offers the same ports again.
create answer takes call-id, from-tag (the created party’s) and
sdp (its endpoint’s answer), with the options of an
answer (flags: trust-address, endpoint-learning, …).
query lists the created party like any other. Deleting it (delete
with its tag) ends its media. A created party, answered or not, is kept
across a restart of the relay.
create from offer
rtpflux’s own command (rtpengine has none like it): the other direction of
create. An endpoint offers (an inbound call to an IVR, or a call that is
parked before it is joined to anyone) and the relay answers it, with no
second party. The party then exists like a created one: join it with
connect, play media to it, subscribe to it, delete it.
Until then its media goes nowhere and nothing is sent to it.
| Option | Meaning |
|---|---|
sdp | The endpoint’s offer (required) |
call-id | The call (made up, 32 hex digits, when missing) |
from-tag | The party’s tag (made up, 16 hex digits, when missing) |
label (or set-label) | A label for the party |
| other options | As for an offer towards the party: flags: trust-address, received-from, endpoint-learning, SDES, DTLS, ICE, rtcp-mux, direction, codec: strip, … |
The reply has call-id, from-tag and sdp, the answer for the
endpoint. It accepts every format of each section that the relay offered
on (strip formats with codec options to narrow it), and mirrors each
section’s direction (RFC 3264 §6.1): sendonly is answered recvonly,
recvonly sendonly. A rejected section (port 0) stays rejected. The
answer takes the profile of the offer, so SRTP (SDES), DTLS-SRTP and ICE
are answered as for an ordinary offer.
create from offer again with the same call-id and from-tag is the
party’s re-offer (a re-INVITE: hold, resume, new codecs): the same ports
and keys, answered the same way. A from-tag that already offered in the
call in an ordinary dialog is refused. The party is kept across a restart
of the relay, as a created one is.
inject start and inject stop
inject start sends what one party sends to another party as well, one
way (rtpengine’s injection): the destination keeps its own media and also
gets the source’s. It is a directional connect of one
source, with rtpengine’s keys:
| Option | Required | Meaning |
|---|---|---|
call-id | yes | The destination’s call |
to-tag | yes | The destination party |
source-tag | yes | The source party |
source-call-id | no | The source’s call (default: the same) |
inject stop (the same keys) ends it; so does unsubscribe naming the
destination, or the end of either party’s dialog. Other injections and
announcements to the destination go on. rtpengine mixes the injected
audio into the destination’s stream; the relay has no mixer, so the
destination gets it as a stream of its own (the source’s SSRC, from the
destination’s relay port, converted to its codec), which an endpoint may
play instead of the other stream rather than with it.
mesh
Sends what parties send to other parties, of one call or several, in one
request (rtpengine’s mesh): for a conference without a mixer, each
participant gets the others’ streams.
| Option | Meaning |
|---|---|
calls | The call-ids (at least one, all known) |
tags | A list of {from: <tag>, to: [<tag>, …]}: each to party gets what the from party sends |
flags: bidirectional | Each pair both ways |
flags: unsubscribe | First, each from party stops hearing anyone: its dialogs’ other parties’ media to it is blocked (as block media of theirs), and copies to it end; with bidirectional, nobody hears it either |
Tags are looked up in the listed calls; a tag that is a party of two of
them is refused. Everything is checked before anything changes. The
copies are those of a directional connect: streams of their
own, converted to the receiver’s codec, kept across a restart; unblock media undoes unsubscribe’s blocking. rtpengine also merges the listed
calls into one, and mesh without tags only does that; rtpflux names
parties by call and tag, so it does nothing then.
publish
As rtpengine’s: a party that only sends (a WebRTC client publishing its
camera and microphone, say) offers its media with publish (call-id,
from-tag, sdp, and the options of an offer); the reply’s sdp is
the relay’s answer, receive-only. Others then receive it with
subscribe request
naming its tag, each in its own profile (an SRTP or DTLS publisher’s
media reaches plain RTP subscribers decrypted). delete ends the
publication and its subscriptions.
Each subscribed section takes relay ports of its own; what the subscriber sends to them (RTCP reports, say) is not relayed. A call with a subscription leaves the XDP fast path. Subscriptions use RTP, SRTP with SDES or DTLS-SRTP. They are kept across a restart of the relay (with the state file or Redis): their ports and keys come back, and an answered one goes on copying. Which legs receive copies follows a rule checked against reference vectors: only a subscription’s legs are ever copied to, so a port that served one and now serves another call never gets them.
Options
These options are read by offer (and answer where it makes sense).
Flags go in the flags list.
| Option | Values | Meaning |
|---|---|---|
direction | list of two interface names | The interface for the offerer’s side and for the answerer’s side. One name: that interface for both. Default: the first interface for both. |
flags: trust-address | flag | Use the address in the SDP as is. Without it, the relay uses received-from (where the SIP message came from) when the proxy sends it. |
received-from | ["IP4", "192.0.2.10"] | The address the SIP message came from (sent by proxy modules automatically) |
endpoint-learning | heuristic (default), delayed, immediate, off | How the relay learns where media really comes from. See NAT and latching. |
flags: strict-source | flag | Drop media from any address other than the learned one |
flags: asymmetric | flag | The side does not send from where it receives: nothing is learned from its packets (as endpoint-learning: off) |
flags: port latching | flag | Keep the relay’s ports across a re-offer whatever the endpoint’s port: what rtpflux always does |
flags: loop protect | flag | Mark the SDP the relay writes with a=rtpflux:<instance>; an SDP carrying this relay’s mark is returned as it is, nothing set up (an SDP loop through the same relay) |
flags: track-state | flag | A re-offer of an answered dialog can be taken back with rollback until its answer |
flags: unidirectional | flag | Media flowing one way may enter the XDP fast path (both sides’ addresses still settled); otherwise both directions must have carried traffic |
media echo (or media-echo) | forward, backwards, both, blackhole (sinkhole), off | For testing: forward: the receiver of this message (the answerer for an offer, the offerer for an answer) hears its own media, the other’s is dropped; backwards: the sender hears itself; both: each hears itself; blackhole: all media dropped; off: relayed again. Echoed media goes back as it came (the sender’s codec, not transcoded); echoed RTCP is dropped. Kept across a restart. |
DTMF-delay | milliseconds | The keys of the party that sent this SDP reach the other party that much later (at most 10 000). See DTMF security. |
OSRTP | list of offer, accept (also offer-RFC, accept-RFC) | Opportunistic SRTP (RFC 8643): an offer in a plain profile (RTP/AVP) with a=crypto is passed on as one, with the relay’s key, and SRTP is used on both sides when the answerer takes it (plain RTP when it does not). offer: a plain offer becomes an opportunistic one to the answerer. accept: the offerer’s opportunistic SRTP is taken even when the answer is plain (the relay converts). offer-legacy: the same in the older form, each stream offered twice (in RTP/SAVP with the relay’s key, then in RTP/AVP), the answerer’s choice of the two read back. accept-legacy: such a doubled offer is taken as one opportunistic stream (its SRTP accepted), and answered doubled again. |
flags: media-handover | flag | Follow a side whose source changes mid-call (a NAT rebinding): a new source takes the learned address over after 3 packets in a row. See NAT and latching. |
replace | list of origin, username, session-name, sdp-version, force-increment-sdp-version, session-connection, zero-address (or flags replace-<value>) | origin: also rewrite the o= line to the relay’s address (a call across two interfaces, two different direction names, gets it without asking, so neither network sees the other’s addresses). username, session-name: - in o= and s=. sdp-version: the relay sets the o= version of what each party gets: the sender’s at first, raised by one only when what that party gets changes (a re-INVITE that changes nothing keeps it). force-increment-sdp-version (also a flag): raised every time. origin-full: the whole o= line is the relay’s, o=- <id> <version> IN <family> <relay address>, its session id the same in every SDP that party gets and its version as with sdp-version. session-connection and zero-address are always done: every c= is the relay’s. |
sdp-attr | {<level>: {add: [...], remove: [...], substitute: [[from, to], ...]}} | Attribute edits, without a=: <level> is global (or none) for the session, or a media kind (audio, video, …) for its sections. remove names an attribute (tool removes a=tool:…) or a whole value; substitute replaces a whole value; add appends. Edits apply to the input’s attributes before the relay’s own; the relay’s (keys, ICE, a=rtcp) are not touched. In offer and answer. |
flags: strip-extmap | flag | Remove a=extmap (RTP header extensions) everywhere |
flags: generate-mid | flag | In an offer: give each section without a=mid one (its index) |
flags: no-rtcp-attribute, full-rtcp-attribute | flag | a=rtcp: never written, or always written in full (port, network, address) for a section without rtcp-mux. By default the relay rewrites the input’s. |
transport-protocol | RTP/AVP, RTP/SAVP, RTP/AVPF, RTP/SAVPF, UDP/TLS/RTP/SAVP, UDP/TLS/RTP/SAVPF | The profile offered to the answerer, for example plain RTP towards a desk phone when the caller is a browser. See Bridging. |
ICE | default, remove, force, reject, force-relay, optional | default: be an ICE agent towards both sides when the offerer uses ICE (but not towards a phone a WebRTC offer is bridged to with a SIP transport-protocol); remove: no ICE on either side (browsers need ICE, so do not use it for them); force: ICE towards both sides; reject: the offer’s ICE is ignored, so none is answered (as remove). force-relay: an offer whose sections all use ICE passes as it is (its m= and c= lines, ICE, keys and DTLS untouched, its own relay candidates dropped) with the relay added as a relay candidate of each section; what reaches the relay’s ports is relayed as it is, nothing terminated, so media goes through the relay only when the endpoints’ ICE picks it. optional: the same, keeping all the endpoints’ candidates. Without ICE in the offer, both are force. |
ICE-lite | off, forward, backward, both | Where the relay is an ICE-lite agent rather than a full one (default: [ice] mode): forward towards the answerer, backward towards the offerer, both, or off (full on both sides). See ICE. |
flags: fragment | flag | With offer: the sdp is a trickle ICE fragment, not an offer; see Trickle ICE |
codec: transcode | ["PCMA"], ["PCMU"], ["G722"], ["G729"], ["opus"], and with the amr build feature ["AMR"] or ["AMR-WB"]; a name may carry rtpengine’s parameters, opus/48000/2/32000 | Offer this codec too and convert when the answerer picks it. For Opus the fourth field is the bitrate (bit/s, 6000 to 510000) of the relay’s Opus encoder. |
codec: consume | list of codec names | As mask, and the codec is withheld from the answerer even when there is nothing to transcode to |
codec: ignore | list of codec names | The offerer’s codecs treated as never offered: not offered to the answerer, never transcoded from |
codec: accept | a codec name | The offerer’s codec the relay transcodes from (by default its first convertible one), so the offerer is answered with it when the answerer takes the transcoded codec |
codec: set | list of codec specifications, opus/48000/2/24000, AMR/8000/1/7950 | Set a codec’s parameters where the relay encodes it: Opus’s bitrate; AMR’s and AMR-WB’s mode, by its bitrate (AMR 4750 to 12200, AMR-WB 6600 to 23850), used towards a side whose mode-set takes it (else the relay’s default mode, 12.2 or 12.65 kbit/s). Other parameters are warned about. |
codec: mask | list of codec names | Withhold the offerer’s codec from the answerer |
codec: strip | list of codec names, or all | Remove these of the offerer’s formats from the offer to the answerer (with their a=rtpmap, a=fmtp and a=rtcp-fb lines). A codec named in transcode that the offerer has is kept. An offer that would leave a section without a codec (only telephone events or comfort noise, and nothing to transcode to) is refused. |
codec: except | list of codec names | Keep these whatever strip says (strip: all with except offers only those) |
codec: offer | list of codec names | As except, and put them first, in this order |
flags: codec-transcode-<name>, codec-mask-<name>, codec-strip-<name>, codec-except-<name>, codec-offer-<name>, codec-set-<spec>, codec-accept-, codec-consume-, codec-ignore-<name> | flag | The same as codec, as flags |
codec: transcode: ["telephone-event"] | When the offerer has no telephone events, offer them to the answerer and convert (DTMF transcoding); see DTMF transcoding | |
flags: always transcode | flag | Keep the offerer’s telephone events and convert should the answerer refuse them (DTMF transcoding) |
SDES | list of off, no-<suite>, only-<suite> (or flags SDES-<value>) | The suites used: the answerer is offered every allowed suite, the offerer’s first (else the first allowed of AES_CM_128_HMAC_SHA1_80, AES_CM_128_HMAC_SHA1_32, AEAD_AES_128_GCM, AEAD_AES_256_GCM, AES_256_CM_HMAC_SHA1_80, AES_256_CM_HMAC_SHA1_32), and of the offerer’s own lines the first allowed one is used. off: no SDES; an answerer offered RTP/SAVP(F) needs it, so that is refused. Options that leave no suite, on either side, are refused. unencrypted_srtp, unencrypted_srtcp, unauthenticated_srtp: the answerer is offered AES-CM suites declaring them, and lines declaring them are accepted (see SDES keys). lifetime: each key with ` |
DTLS | off, passive, active | passive / active: the relay’s a=setup in the SDP it writes: in an offer, instead of actpass (the answer must fit it, RFC 4145); in an answer, towards an offerer that offered actpass. off: no DTLS-SRTP; refused when the answerer is offered a DTLS profile. |
DTLS-reverse | passive, active | The relay’s role towards DTLS offered to it with actpass: passive (the default; it waits for the handshake) or active (it starts it) |
DTLS-fingerprint | SHA-1, SHA-224, SHA-256, SHA-384, SHA-512 | The hash of the relay’s a=fingerprint (default: SHA-256 in an offer, the offerer’s own hash in an answer) |
ptime | milliseconds (integer or string), a multiple of 10 from 10 to 200 | The packet time of the answerer’s leg: its offer gets a=ptime with this value, and the relay regroups the offerer’s audio into packets of it. The offerer keeps its own packet time (its a=ptime, else 20 ms): what the answerer sends is regrouped back. G.711, G.722 and G.729 are repacketised (after any transcoding), and Opus is decoded and encoded again in packets of one frame (the longest of 10, 20, 40 or 60 ms not over the packet time); other codecs pass as they are, with a warning. |
ptime-reverse | as ptime | The same for the offerer’s leg: its answer gets a=ptime with this value. |
rtcp-mux | list of offer, require, demux, accept, reject (or flags rtcp-mux-<value>) | Where RTCP is multiplexed on the RTP port; see rtcp-mux. Read from the offer. |
Using rtpflux with a SIP proxy
Kamailio
A complete, tested configuration is in
contrib/kamailio/kamailio.cfg; see
Integration. The essentials:
loadmodule "rtpengine.so"
modparam("rtpengine", "rtpengine_sock", "udp:127.0.0.1:2223")
request_route {
...
if (is_method("INVITE|ACK|BYE|CANCEL|UPDATE") || has_body("application/sdp")) {
rtpengine_manage("trust-address replace-origin");
}
...
}
rtpengine_manage() sends offer, answer or delete depending on the
message. You can also call rtpengine_offer(), rtpengine_answer() and
rtpengine_delete() yourself. Flags in the string become ng options:
| Kamailio flag | ng option |
|---|---|
trust-address | flags: [trust-address] |
replace-origin | replace: [origin] |
direction=external direction=internal | direction: [external, internal] |
RTP/AVP, RTP/SAVPF, … | transport-protocol |
ICE=remove | ICE: remove |
codec-transcode-PCMA | the transcode option |
Example: a browser calling a desk phone. Offer plain RTP to the phone:
rtpengine_offer("trust-address replace-origin RTP/AVP");
The phone gets an ordinary RTP offer with a port per stream. The browser gets its answer with DTLS-SRTP, ICE and BUNDLE, as it expects. See Media handling.
OpenSIPS
A complete, tested configuration is in
contrib/opensips/opensips.cfg; see
Integration. The essentials:
loadmodule "rtpengine.so"
modparam("rtpengine", "rtpengine_sock", "udp:127.0.0.1:2223")
route {
...
if (has_body("application/sdp")) {
if (is_method("INVITE")) rtpengine_offer("trust-address replace-origin");
}
...
}
onreply_route {
if (has_body("application/sdp")) rtpengine_answer("trust-address replace-origin");
}
and rtpengine_delete() on BYE and CANCEL.
OpenSIPS’s siprec module records a call through
subscriptions: it
sends subscribe request with flags: [all, siprec], gives the
recording server the offer with the tag-medias labels in its metadata,
and passes the server’s answer back with subscribe answer.
Trickle ICE
An endpoint that trickles ICE (RFC 8838) sends candidates it finds later in
SIP INFO requests whose body is application/trickle-ice-sdpfrag (RFC 8840):
a=ice-ufrag:8hhY
a=ice-pwd:asd88fgpdd777uzjYhagZg
m=audio 9 RTP/AVP 0
a=mid:0
a=candidate:2 1 UDP 1694498815 192.0.2.3 5010 typ srflx raddr 192.0.2.1 rport 8998
a=end-of-candidates
The proxy hands such a body to the relay as an offer with
flags: [fragment], the dialog’s call-id and the sender’s tag as
from-tag (the caller’s or the callee’s). The relay gives the new
candidates to its agent towards that endpoint, by a=mid, if the body’s
ice-ufrag and ice-pwd are the current ones (a body of another ICE
generation is ignored, as RFC 8840 §4.4 says); candidates it already has
are skipped. The reply’s sdp is the fragment to forward to the other
endpoint: the relay’s credentials towards it and a=end-of-candidates
for each section (the relay has nothing to trickle).
What rtpflux does not support (yet)
Commands other than those listed above are answered with an error (among
rtpengine’s: start forwarding and stop forwarding, which feed its own
recording daemon), so the proxy sees a
clear failure rather than a silent no-op. Options, flags and values
rtpflux does not implement are ignored, and named in the reply’s
warning (see How messages look). Among them:
T.38gateway options: T.38 is relayed between T.38 endpoints only.- Mixing the audio of several parties into one stream (a conference
bridge).
connectjoins two parties, and a subscription to several parties delivers each one’s media in a section of its own, as rtpengine does without its mixer. - Codec parameters other than Opus’s bitrate and AMR’s mode.
delay-buffer(all media held back by a time, so that DTMF security can take a key’s first milliseconds out too): keys are found as they arrive, so an in-band key’s first frame or two pass.
Native control API
The native API is for a B2BUA or softswitch that manages media itself.
It creates endpoints, negotiates them in either direction, bridges
them, renegotiates them, and destroys them. It can also stream an
endpoint’s audio to an external service, or mix endpoints in a
conference. It is served beside the ng protocol,
which stays exactly as it is. Both run on the same handlers, so an
endpoint is also a party that ng commands such as query can see. The
design is in ADR 0001.
Two Rust clients are in the workspace:
rtpflux-client-async, on Tokio, is for a softswitch’s call control. It has typed requests and replies, a pool of connections, bounded queues, deadlines, cancellation, reconnect, and events on a connection of their own.rtpflux-clientis blocking, for tools and prototypes. Itsfixtures/directory holds example sessions, request by request.
Connecting
[control]
native_socket = "/run/rtpflux/native.sock"
native_uids = [1001] # users allowed besides the relay's own and root
native_max_endpoints = 0 # per tenant; 0: up to sessions.max
pcm_dir = "/run/rtpflux/pcm" # where audio services listen (PCM streams)
native_listen = ["127.0.0.1:2224"] # also over TCP, behind a TLS proxy
native_tokens = { switch-a = "a long random token", switch-b = "another one" }
native_tokens_file = "/etc/rtpflux/tokens" # more tokens, re-read when it changes
native_rate_limit = 0 # requests per second per tenant; 0: no limit
ng_protect_native = false # keep ng off calls holding native endpoints
The Unix socket. Only the relay’s own user, root and the users in
native_uids may connect: the peer’s credentials (SO_PEERCRED) are
checked on each connection. The socket file’s mode follows:
- 0600 (the relay’s user only) when
native_uidsis empty; - 0666 when other users are listed, so they can reach the socket and the credentials check decides;
- 0660 with
native_socket_group(a gid), the file’s group.
At most 64 connections are served at once.
Over TCP (native_listen), a connection’s first request must
authenticate, with a tenant’s token:
{"v": 1, "op": "auth", "token": "…"} → {"result": {"tenant": "switch-a"}}.
Tokens are compared in constant time, and must be 16 characters or more.
- Until it authenticates, a connection gets
unauthorizedfor anything else. - Three bad tokens close the connection.
- An authenticated connection is that tenant’s. A request naming another
tenant is refused (
unauthorized).
Rotating tokens. native_tokens_file holds more tokens, one
tenant token per line (# comments). A tenant may have several. The
file is re-read, at most once a second, when it changes. To rotate:
- add the new token next to the old one;
- move the clients to the new token;
- remove the old one.
A connection that authenticated with a removed token is refused at its
next request (unauthorized) and closed. Write the file whole and
rename it into place: while it cannot be read, the tokens it last gave
stay.
Rate limits. native_rate_limit is the number of requests one tenant
may make each second, with a burst of the same size. Beyond it, requests
are refused with exhausted and nothing is done. Each tenant has its
own budget.
Protected transport. The relay has no TLS of its own. A
native_listen on an address other than loopback is refused at start
unless native_allow_remote = true. Listen on loopback and put an
authenticated TLS proxy in front, for example stunnel or HAProxy with
client certificates, that forwards to it.
Audit. Every request that changes something, each ownership.claim,
each authentication (success or failure) and each refused connection is
logged on the rtpflux::audit target at info or warn. A line has:
- the tenant, the peer (uid and pid, or TCP address) and the connection;
- the operation, its
operation_idandidempotency_key; - the resources named and made;
- the outcome.
It never has a request’s body: no SDP (it can hold SRTP keys), no token,
no digit. Send the target to its own sink with RUST_LOG, for example
RUST_LOG=info,rtpflux::audit=info.
ng isolation. ng has no authentication of its own: keep its
port on a trusted network. With ng_protect_native (always under
[ha]), an ng command cannot change a call that holds native
endpoints. ping, list, query and statistics still work.
Each message, in either direction, is a 4-octet big-endian length followed by that many octets of JSON, at most 1 MiB. A connection’s requests are answered in order.
Requests and replies
{"v": 1, "op": "endpoint.create", "operation_id": "op-7", "remote_sdp": "v=0\r\n…"}
| Field | Meaning |
|---|---|
v | The protocol version: 1 |
op | The operation |
operation_id | Chosen by the client. Echoed in the reply and in the events the operation causes |
idempotency_key | Optional: the operation’s stable key, per tenant. See Operation keys and the ledger |
first_attempt_unix_ms | Optional, with idempotency_key: when the operation was first attempted. A key older than the ledger keeps is refused (expired), not run again |
tenant | Optional (default default). Endpoints, sessions and mixers belong to a tenant; another tenant gets unauthorized |
endpoint_id | The endpoint the operation is about |
expected_generation, expected_revision | Optional. The request fails with conflict when the endpoint’s are different |
deadline_unix_ms | Optional. A request that arrives after this time fails with timeout and is not run |
A reply is {"v": 1, "operation_id": …, "ok": true, "result": {…}}, or
"ok": false with "error": {"code": …, "message": …}. The error codes
are:
| Code | Meaning |
|---|---|
not_found | No such endpoint, mixer or stream; or it was destroyed (the message says which, with its generation) |
conflict | The wrong generation or revision, a renegotiation already pending, an answer to an endpoint already answered, … |
unsupported | An operation, option, codec or capability the relay does not have |
exhausted | No free ports, the session or endpoint limit is reached, or the relay is busy (its queue of requests is full). Nothing was run |
timeout | The deadline has passed; or the relay took the request but did not reply within 5 s (a durable reply waits for the disk). The operation may have been applied: check (operation.query with its key, or the resources) before acting again |
unauthorized | Another tenant’s resource |
invalid | A malformed request or SDP |
internal | Anything else |
unavailable | Durable storage failed. Nothing was done, unless the message says the operation was applied and only its record failed (detail names the resources) |
expired | The operation key’s first attempt is older than the ledger keeps; it was not run again |
unknown_outcome | The operation began before a restart and its outcome was never recorded: it may or may not have taken effect. Reconcile before acting again |
An error may carry detail, typed: the live or destroyed endpoint an
external_id conflict is about, the resources of an unknown outcome.
A reply means the change is applied in the control thread and queued to
the media workers, which apply their commands in order. Operations that
change where media goes wait until the workers concerned have applied the
change before they reply: bridge.attach, bridge.detach,
stream.start, mixer.add. Each worker confirms with a barrier queued
after the change. If a worker does not confirm within a second, the reply
is timeout; the change may still take effect, and endpoint.query
tells.
Operations that finish later report their end with an event: an
announcement that played out, a recording, a stream.
Operation keys and the ledger
A request that changes something and carries idempotency_key is
recorded in the ledger:
- A retry with the same key and the same intent gets the first reply,
marked
replayed: true. Nothing runs again, whether the first attempt succeeded or failed. - The same key with another intent is a
conflict.
The intent is the request’s canonical JSON (keys sorted at every
level) without the fields of a single attempt: v, operation_id,
idempotency_key, tenant, deadline_unix_ms, first_attempt_unix_ms
and correlation_id. Its SHA-256 is the fingerprint that is compared.
What is not recorded. A request refused for its envelope (protocol version, tenant, a deadline already past) is definitely not executed. It is not recorded, so a retry runs normally.
In memory (the default), the ledger keeps outcomes for 5 minutes, for the relay process’s lifetime.
Durable ([sessions] ledger, with a state_file):
- A keyed mutation runs.
- What it changed (its endpoints, sessions, recordings, tombstones) and its outcome are appended to the state journal as one record.
- A sync thread syncs the records written meanwhile together (group commit).
- Only then is the reply sent.
The control thread never waits for the disk: other requests, reads among them, go on meanwhile. The cost of a mutation no longer depends on the number of live endpoints: only what it touched is written. See The state journal.
After a crash, an operation is either wholly on the disk (its record
written: a retry gets its outcome) or not at all (a retry runs it, once).
unknown_outcome is left only for an operation whose media workers did
not confirm the change in time (timeout), or for one begun before a
restart of an older version. Then:
- Reconcile:
endpoint.lookupbyexternal_id, orendpoint.list. - Make what is missing with a new key.
The ledger keeps outcomes for ledger_retention (a day by default), and
holds at most ledger_quota keys per tenant. A new key beyond the quota
is refused (exhausted); nothing is evicted early. The file is created
readable by the relay’s user only: replies hold SDP, which may carry SRTP
keys.
What the guarantee is not. Without a ledger, state reaches the disk
at most once a second, and Redis writes are best effort. hello says
which applies (guarantees: idempotency, state_commit). A crash
loses up to a second of unkeyed changes.
| Operation | Fields | Result |
|---|---|---|
operation.query | idempotency_key, first_attempt_unix_ms (optional) | status: pending, applied, failed, unknown, expired (older than kept), or not_found; and op, resources, reply, at_unix_ms, durable |
Endpoints
An endpoint is media the relay terminates. It is identified by
endpoint_id (ep- and 32 hex digits) and belongs to a media session
session_id (the ng call: ms- and 32 hex digits, or a name the client
gives).
- Generation: given when the endpoint is created. It is never reused, even after a restart.
- Revision: counts the endpoint’s committed negotiations, from 1.
- State:
offereduntil it is answered, thenready. Anofferedendpoint has no media yet:bridge.attach,recording.start,playback.startandendpoint.prepareon it are refused withconflict(“not answered yet”);recording.stopsays it is not recording. - Before it is bridged: its media goes nowhere and nothing is sent to it. It is parked, but it can play announcements and stream audio.
| Operation | Fields | Result |
|---|---|---|
hello | versions, operations, events, capabilities (codecs, transports, PCM streaming and its rates, mixer), limits | |
endpoint.create | remote_sdp (the remote side’s offer, which the relay answers), or codecs (the relay offers one audio section of these: PCMU, PCMA, G722, G729, opus, AMR, AMR-WB, telephone-event, CN), or medias (typed sections, video among them: see The relay’s own offers); direction (of the relay’s offer); session_id, label, lease_ms, options, external_id, replaces_generation, video (sfu: an endpoint of a video room) | endpoint_id, session_id, generation, revision, state, sdp_type (answer or offer), sdp, warnings |
endpoint.apply_answer | endpoint_id, sdp, options | revision, state |
endpoint.prepare | endpoint_id; remote_sdp (the remote side’s re-offer), or the relay’s re-offer: medias or codecs (new sections), or neither (the sections it has, again), with direction and options; whichever side offered first | pending_revision, sdp_type, sdp |
endpoint.commit | endpoint_id, revision; after the relay’s re-offer, sdp (the answer) | revision |
endpoint.abort | endpoint_id, revision | revision (the committed one) |
endpoint.destroy | endpoint_id | destroyed, or already: true. Its playback and queue stop first (playback.stopped, reason: "endpoint_destroyed"); its recording is stopped and finished, its outcome reported after endpoint.destroyed |
endpoint.query | endpoint_id, include_local_sdp | The endpoint’s snapshot, and media (its streams, statistics, RTCP, DTMF, as ng query reports them); with include_local_sdp: true, local_sdp and local_sdp_type (the SDP the relay last returned for it, committed: offer or answer) |
endpoint.list | endpoints (snapshots), destroyed (recent tombstones), global_seq | |
endpoint.lookup | external_id | The live endpoint’s snapshot (state_of_id: "live"), or the destroyed one’s id, generation and reason (state_of_id: "destroyed") while its tombstone is kept |
endpoint.renew | endpoint_id, lease_ms (optional) | lease_ms |
endpoint.echo | endpoint_id, echo (true/false) | echo, changed (see Echo) |
ownership.claim | group, epoch, owner, lease_expires_unix_ms, key_id, signature (see Exclusive ownership) | group, epoch, owner, lease_expires_unix_ms, previous_epoch, drained |
options are ng options for the operation (see
Options), as JSON:
{"flags": ["trust-address"], "ICE": "remove", "transport-protocol": "RTP/SAVP", "SDES": ["no-AES_CM_128_HMAC_SHA1_32"]}.
Strings, integers, lists and objects map to their bencode forms, and
true/false become yes/no. Keys the operation sets itself are
refused: call-id, from-tag, to-tag, sdp, label.
Renegotiation goes in either direction, whichever side made the
endpoint’s first offer. With remote_sdp, the remote side re-offers (a
re-INVITE or UPDATE). Without it, the relay re-offers (a delayed offer, a
codec change).
- Both keep the committed media (ports, keys, ICE, roles, bridge) as a
checkpoint until
endpoint.commit. The answer to a remote re-offer is given at prepare, and its media apply then, but the checkpoint stays. endpoint.abortputs the checkpoint back exactly (rollback), and the endpoint is bridged again as it was. An abort that cannot take it back fails (internal) and says so; it does not report success.- A renegotiation that does not change the media keeps the ports, the keys and the bridge.
Inventory and recovery.
| Operation | Fields | Result |
|---|---|---|
inventory.list | kind (endpoints, bridges, streams, mixers, playbacks, recordings), limit (1–500, default 100), cursor | items, next_cursor, total, watermark (boot_id, global_seq, topology_epoch) |
recovery.report | boot_id, previous_boot_id, restored_endpoints, lost, unknown_operations |
Inventory pages list one kind in id order. A cursor is valid only while
nothing changes. If any resource or link changes between two pages, the
next page is a conflict, and the client starts again without a cursor.
It never gets pages of two different states. Endpoint items also carry
their stream and mixer.
hello gives this run’s boot_id; a restart makes a new one. After a
restart, recovery.report says what came back and what did not:
- the endpoints restored, with their media, bridges and recordings, which continue in the same files;
- what was lost: PCM streams and mixers are never restored, and neither
is an announcement from a
blob. Announcements from a file are; - the operations whose outcome is unknown.
Nothing is reported as restored that is not. The client reconstructs the rest: it starts streams again, and creates mixers and adds their participants.
External ids. external_id is the client’s stable key for an
endpoint, such as a call’s UUID and leg. It is unique per tenant:
- Creating a second endpoint under a live endpoint’s external id is a
conflict, whosedetailnames the live endpoint. - Under a destroyed endpoint’s external id, a new endpoint needs
replaces_generation: the destroyed one’s generation. A retry of the destroyed one’s creation is therefore never taken for a new logical endpoint. - External ids, tombstones and the counters ids are made from (endpoint generations, stream and mixer ids) are saved with the state, so no id is given twice across restarts.
Lifecycle.
- Destroying an endpoint frees everything it holds: ports, keys, its bridge, its announcement, stream and mixer membership, and its kernel flows.
- A destroyed endpoint leaves a tombstone for 5 minutes. A late command
for it fails with
not_found(“destroyed”) and never brings it back. - An endpoint also ends when its media times out
(
sessions.timeout), withendpoint.timeoutthenendpoint.destroyed. It ends when its lease is not renewed in time (reasonlease), and when ng deletes its session (reasonended). - A client that disconnects destroys nothing. Leases are how a client limits what outlives it.
Restarts. With a state file or Redis, endpoints come back with their
media: the same ids, generations, revisions and bridges, on the same
ports. A pending renegotiation also comes back. Leases start again at
the restart. A client that reconnects calls endpoint.list to
resynchronise. What does not come back:
- PCM streams and mixers, which the client starts again;
- DTLS associations: browser endpoints need a new handshake, as in Operations.
Exclusive ownership ([ha])
With several controllers, only one may change a call at a time, and one
that lost a call (a partition, a pause) must not change it afterwards.
Under [ha], the relay enforces that with fencing epochs. The
epochs are issued by the controllers’ ownership authority, never by a
controller.
Groups and grants. The authority grants an ownership group (a call, say) to one controller at a time, each grant at a higher epoch. It signs the grant with a key it shares with the relay:
signature = hex(HMAC-SHA256(key, "rtpflux-ownership-v1\n<tenant>\n<group>\n<epoch>\n<owner>\n<lease_expires_unix_ms>"))
token = hex(HMAC-SHA256(key, "rtpflux-ownership-token-v1\n<tenant>\n<group>\n<epoch>\n<owner>"))
The controller sends the grant as ownership.claim. The relay accepts it
only when:
- the signature verifies with the named key (constant-time comparison);
- the lease is still running;
- the epoch is not below the group’s highest so far. The same epoch is accepted only for the same owner, as a renewal that never shortens the lease.
The relay syncs the claim to disk ([ha] state) before acknowledging it.
With a state_file, the write happens on the state journal’s sync thread,
in order: it is on the disk before the claim’s reply and before the reply
to anything sent after it. Meanwhile the control thread goes on (the
previous owner is fenced at once). If the write fails, the reply is
unavailable; the claim still counts in memory, and the next claim or
renewal writes it.
When the epoch rises, the reply says whether the media workers confirmed
the previous owner’s commands applied (drained). In any case nothing
the previous owner sent can land after the new owner’s commands: both go
through the one control thread, and each worker applies its commands in
order.
Every mutation carries "ownership": {"group", "epoch", "token"}.
The token is only the owner’s, so an old controller cannot guess its way
in by sending a higher epoch. A mutation is refused with fenced, and
nothing is done, unless:
- the epoch is the group’s current one;
- the lease is running;
- the token is the current owner’s;
- every resource it touches (
endpoint_id,peer_endpoint_id,mixer_id,stream_id) belongs to a group it proves.
A resource belongs to the group its creation proved (endpoint.create,
mixer.create, stream.start). A bridge across groups (calls) also needs
"peer_ownership" for the peer’s group. Resources made before [ha] was
enabled belong to no group, and no one can change them.
Reads, events.* and ownership.claim itself need no proof. A refusal
for ownership happens before the ledger, so it is never recorded and a
retry with a fresh claim runs normally.
Fail closed. With no claim, a lease that has run out, or a claims file
that cannot be written, mutations are refused (fenced, or unavailable
for the claim). Media already established keeps flowing.
After a restart the relay remembers the epochs and which group owns each restored endpoint, so a stale controller is still refused.
Pruning. A group whose lease is over and that owns nothing is forgotten. The highest epoch forgotten becomes the tenant’s floor: a grant at or below it, for a group the relay does not know, is refused, whatever its lease. The authority must therefore issue epochs from one rising sequence per tenant, across all groups.
ng. In this mode, an ng command cannot change a call that holds
native endpoints (call-id or to-call-id). ping, list, query and
statistics still answer. ng calls without native endpoints are not
affected: isolate the ng port from controllers that must be fenced.
Tenants. Grants are signed for a tenant, and a connection authenticated as another tenant cannot use them.
The relay’s own offers
endpoint.create without remote_sdp, and endpoint.prepare for a
re-offer by the relay, build the offer from sections:
codecs: one audio section of the relay’s codecs.medias: an ordered list of typed sections:{"type": "audio", "codecs": [...]}: audio of the relay’s codecs;{"type": "video" | "audio", "formats": [{"pt", "rtpmap", "fmtp", "rtcp_fb": [...]}]}: written exactly as given. The relay converts no video, so the caller picks the formats: the other leg’s, by payload type.- Either may have its own
direction.
- Limits. At most 4 sections, and 16 formats in each. A payload type
is static (0 to 34) or 96 to 127.
rtpmapis<name>/<clock>[/<channels>], and a dynamic payload type must have one.fmtpandrtcp_fbare single printable lines. Anything else isinvalid, and nothing is made. direction(sendrecv, the default,sendonly,recvonly,inactive): of every section without its own.- A re-offer without
mediasorcodecsoffers again the sections the endpoint has, read from the SDP the relay last returned for it: in order, with their formats and ports. A hold ({"direction": "sendonly"}) of a video endpoint keeps its video. - Sections are relayed as they are and joined in order by
bridge.attach. Video RTP keeps its payload types.
SDP origin
Every SDP the relay returns for an endpoint carries the relay’s own origin (RFC 3264 §8):
o=- <session> <version> IN IP4 <the relay's address>;- the session id is chosen when the endpoint is made, and kept for its life;
- the version starts at 1, and grows by one with every SDP returned (offers and answers);
- an answer never carries the offerer’s
o=line; - a keyed retry returns the recorded SDP, at the same version;
- the origin is saved with the state, so after a restart the next version follows the last.
Bridges
| Operation | Fields | Result |
|---|---|---|
bridge.attach | endpoint_id, peer_endpoint_id; optionally peer_expected_generation, peer_expected_revision, peer_expected_topology_revision (with expected_* for endpoint_id) | bridged_to, replaced (the former peers, now alone) |
bridge.detach | endpoint_id | detached, was_bridged_to |
What is joined. Sections are joined by media type, in order (audio
with audio, video with video), as ng’s connect; the others get a
warning. Endpoints with no media type in common (audio and video only)
are refused (unsupported) before anything changes: the bridges they had
stay.
Topology revisions.
- Every endpoint has a
topology_revision, which changes whenever what it is bridged to changes. Negotiation revisions do not. - A bridge request may expect both endpoints’ topology revisions
(
expected_topology_revisionandpeer_expected_topology_revision). A stale one is aconflict, so a late request never undoes a newer bridge. - The control thread runs every mutation in turn, so concurrent requests are ordered, and nothing deadlocks.
Confirmation.
- A bridge change replies only once both endpoints’ media workers have applied it.
- If they do not confirm within a second, the reply is
timeout, and the endpoints’ snapshots saytopology_state: "unconfirmed"until a later change is confirmed.
A failed attach may have been half applied: one worker took its end,
and its endpoint’s former peer was detached. Every endpoint involved is
then detached, on the media workers and in the records, each with
bridge.changed (reason: "attach_failed"). The error’s detail says
so (compensated). No bridge is ever reported that the media do not
have.
Attaching joins two endpoints with ng’s connect.
- The two may be in different sessions, and on different media workers.
- Neither side needs a re-INVITE: each keeps the relay port it knows.
- When their codecs differ and the relay converts both, each one’s audio is converted for the other.
- Attaching an endpoint that is already bridged moves it. Its former peer
is detached, and told so with
bridge.changed, reasonreplaced. - Bridged endpoints enter the XDP fast path once settled, as connected calls do.
Echo
endpoint.echo with echo: true sends an endpoint its own media back:
an echo test, or an RTP loopback for checking a media path.
- Each RTP packet the endpoint sends comes back to it from the relay’s port, unchanged: its own codec, packet time, SSRC and sequence. Its RTCP is dropped, and nothing reaches anyone else.
- It needs an answered endpoint, and is refused (
conflict) for one that is bridged or in a mixer.bridge.attachandmixer.addare refused while it echoes:echo: falsefirst. - It is kept through a renegotiation and, with a state file, a restart.
endpoint.querysaysecho. - Combining echo with announcements, tones or PCM streams on the same endpoint is not specified (not tested).
echo: falseparks the endpoint again: its media goes nowhere.nghas the same per leg:media echo(forward,backwards,both,blackhole,off) in an offer or answer.
Announcements and recordings
| Operation | Fields | Result |
|---|---|---|
playback.start | endpoint_id, file or blob_base64, repeat_times, start_pos, duration, repeat_duration, queue (wait behind the current one), stop_on (["dtmf", "speech"]) | playback_id, duration_ms; queued: queued, position |
playback.stop | endpoint_id | stopped, playback_id (the queue goes too) |
playback.query | playback_id | Its state: playing, queued (with position), completed or stopped (with reason, queued, ended_unix_ms); endpoint_id, generation, operation_id. not_found once the relay no longer knows it |
recording.start, recording.stop | endpoint_id, options (format, channels, …) | recording, recording_id (starting again while it records gives the same id) |
recording.pause, recording.resume | endpoint_id | recording_id, state, changed, pauses |
recording.query | recording_id (the latest 4096 finished recordings are kept, and every one not finished) | Its state (active, paused, pausing, stopped, completed, failed), pauses, file, finalized, uploaded, upload (pending, none, uploaded, failed), detail, start and end times |
- An announcement that plays to its end gives
playback.completed, with theoperation_idof itsplayback.start. One that is stopped, or replaced by another, givesplayback.stoppedwith the reason. - Queues. With
queue: true, a playback waits behind the current one, 16 at most, and starts when it completes. It gets itsplayback_idat once. - Interruption. With
stop_on, a key the endpoint presses (dtmf) or speech it starts (speech, which needs a VAD detector: see Detectors) stops the playback at once (playback.stopped,reason: "dtmf"or"speech"). What was queued behind it goes too (reason: "interrupted",queued: true). Aplayback.startwithoutqueuereplaces the current playback and drops the queue (reason: "replaced"). The relay does the stopping, without a round trip to the controller. Digit collection and timeouts stay with the controller. - Missed ends. A controller that missed a playback’s end (it was
reconnecting) asks
playback.query. The relay keeps how the latest 8192 playbacks ended, in memory: after a restart they are gone, as the endpoint’sendpoint.events_lostsays.
IVR: keys, tones, detectors and sensitive digits
| Operation | Fields | Result |
|---|---|---|
dtmf.send | endpoint_id, digits (1–64 of 0-9*#A-D), duration_ms (40–5000, default 100), pause_ms (default 50), volume (0–63 dBm0 below, default 8), mode (auto, rfc4733, inband) | keys, mode, duration_ms (the digits are not echoed) |
tone.start | endpoint_id, frequency_hz (50–4000), on_ms (default 1000), off_ms (default 0), repeat (1–1000), volume | duration_ms |
tone.stop | endpoint_id | stopped |
dtmf.policy | endpoint_id, policy (dedup, both, rfc4733, inband) | policy |
endpoint.sensitive | endpoint_id, sensitive (true/false) | sensitive, recording_paused |
-
Sending keys.
dtmf.sendplays them as telephone events when the endpoint negotiated them (auto,rfc4733), else as tones in its audio (inband). Tones and keys are refused while an announcement plays to the endpoint. -
Detectors need no service:
stream.startwithoutsocketruns the endpoint’s audio through the detectors only (vad,dtmf, both on by default), on the PCM shards, and sends it nowhere.stream.detectswitches them at run time. -
Detection. RFC 4733 keys are reported for an endpoint even when it is not bridged to anyone (an IVR leg).
-
DTMF sources. With both an in-band detector and telephone events, a press can be reported twice.
dtmf.policydecides what reachesdtmf.detected:dedup(the default): a key reported by one source within a second of the same key from the other is dropped;both: every report;rfc4733orinband: one source only.
-
Sensitive digits (a PIN, a card number). While
endpoint.sensitiveis on:- the endpoint’s
dtmf.detectedevents carrysensitive: true. Only subscribers that asked for them (events.subscribewithsensitive: true) get the digit; the others getdigitandcodeasnullandredacted: true, live and on replay; - its recordings are paused, and resumed when it is turned off. One the controller paused itself stays paused.
Digits are never logged, sensitive or not (
logat any level).Not covered:
- a PCM stream’s external service hears in-band tones as audio;
- a bridged peer still hears in-band tones and gets the events (use
ng’sblock DTMFif it must not); - the in-memory event journal holds the digit, for the subscribers entitled to it.
- the endpoint’s
-
Pause and resume take effect when the media workers confirm them (a barrier over the endpoint’s calls). Only then is the recording
paused, with the time inpauses([paused_at, resumed_at], in ms since the epoch). The recording holds nothing inside a pause. If the workers do not confirm within a second, the request fails (timeout,detail.state: "pausing") and the recording stayspausing: the relay never sayspausedwhile capture may go on. A pause survives a restart of the relay.endpoint.sensitivepauses through the same path. -
Outcomes are kept apart in
recording.query:finalized(the file is written),upload(nonewithout uploads,uploaded,failed,pendingbefore the end), andfailedwith itsdetailwhen no file could be made.recording.startwith anidempotency_keyrecords therecording_idamong the operation’s resources (operation.query). -
Only relayed media is recorded: an endpoint bridged to no one records nothing.
-
Destroying the endpoint stops its recording (active or paused), and the media workers finish its file. The outcome (
recording.completedorrecording.failed) arrives afterendpoint.destroyed, as the destroyed endpoint’s event (withoutseq), andrecording.querykeeps answering. An endpoint that ends otherwise (timeout,ended) has its recording finished with its call, reported the same way. -
A finished recording gives
recording.completedonce its audio file is written (file), withuploadedsaying whether the S3 upload worked (nullwithout uploads). A recording whose conversion failed givesrecording.failed; its pcap is kept.
PCM streams
A stream sends an endpoint’s audio, decoded, to an external service
(speech recognition, a voice bot), and plays the service’s audio back to
the endpoint. The service listens on a Unix socket in [control] pcm_dir, and the relay connects to it.
| Operation | Fields | Result |
|---|---|---|
stream.start | endpoint_id, socket (a file name in pcm_dir; none: detectors only), rate (8000, 16000, 24000 or 48000; default 16000), inject (default true), protocol (1 or 2, default 1), vad, dtmf (detectors, default on) | stream_id, rate, inject, protocol, service, detect |
stream.flush | stream_id | flushed: the audio queued for the endpoint is dropped (barge-in), and a new generation begins |
stream.detect | stream_id, vad, dtmf (true/false) | detect |
stream.stop | stream_id | stopped |
Frames. Each frame on the socket is a 32-octet header followed by its payload. Integers and samples are little-endian.
| Octets | Field |
|---|---|
| 0–3 | RFPC |
| 4 | version: 1, or 2 with protocol: 2 |
| 5 | kind: 1 hello, 2 audio, 3 mark, 4 flush, 5 gap |
| 6–7 | flags: bit 0, a discontinuity (after a gap or a flush); version 2: bits 8–15, the flush generation (mod 256) |
| 8–11 | the stream id |
| 12–15 | sequence number, per direction (for a mark: its id; for a gap: frames missed) |
| 16–23 | media timestamp, in milliseconds of audio since the stream began |
| 24–27 | sample rate |
| 28 | channels: 1 |
| 29 | encoding: 1 (signed 16-bit PCM) |
| 30–31 | samples in the payload: 10 or 20 ms at the rate |
What the relay sends begins with a hello frame, then 20 ms audio frames of what the endpoint sends, at the stream’s rate. On the way the audio goes through:
- a jitter buffer (40 ms target delay, reordering and duplicates handled);
- the endpoint’s decoder (any codec the relay converts);
- loss concealment, then resampling to the stream’s rate.
A voice activity detector on the same audio gives speech.started and
speech.ended. Key presses in the audio give dtmf.detected with
source: "inband". The relay never waits for a service. One that reads
too slowly misses frames: up to 240 ms waits in the relay’s write
buffer, beyond that frames are dropped. A gap frame gives the count as
soon as there is room, and the next audio frame is marked as a
discontinuity.
What the service sends is audio frames of 10 or 20 ms at any of the four rates. The relay resamples them to the rate of the endpoint’s codec, encodes them in that codec, and plays them in 20 ms packets. That codec is G.711, G.722, G.729, Opus (16 kHz) or AMR. While they come, the endpoint’s bridged peer is held back, as during an announcement. Further rules:
- Backpressure: when more than 100 ms of audio is queued, the relay stops reading the socket, so the service’s writes wait. Memory stays bounded.
- Flush: a flush frame, or
stream.flush, drops what is queued. This is barge-in. Frames already on their way to the media worker are dropped too: each frame carries the flush count it was made under. Marks still waiting are answered as flushed.stream.flushedreports the newgenerationandplayed_ms, the service’s audio sent as RTP before it. - Marks: a mark (kind 3, its id in the sequence field) is answered
with
stream.markonce the audio sent before it has been sent to the endpoint as RTP (boundary: "rtp_sent"). The event hasgenerationandplayed_ms, andflushed: truewhen the audio never will be sent. The relay knows what it sent, not what the remote side has played out: the endpoint’s own jitter buffer adds its delay. - Protocol 2 (flush generations): start the stream with
protocol: 2and the relay’s hello says version 2. The service tags every frame with the current generation (flags bits 8–15). Each flush is acknowledged with a flush frame to the service: its sequence field is the new generation, its media timestamp isplayed_ms. Audio and marks of an older generation are late audio of what was flushed (TTS still arriving after a barge-in, say). They are dropped and never played, and a late mark is answered as flushed. Version 1 services are unaffected. - End: the stream ends with
stream.endedwhen the service closes the socket, or withstream.stop.
The relay’s media workers only copy packets for a stream and play the
frames it sends back. The signal processing and the socket I/O run on a
few shared PCM shard threads ([runtime] pcm_shards). There are no
threads per stream. A stream stays on one shard, and every 20 ms the
shard runs each of its streams once: at most a few frames are read from
one service, so a busy one does not starve the others. With 100 streams
both ways (load in tests/pcm.rs), 4 shard threads used 9.2–10.8% of
a core, where two threads per stream (200 threads) used 11.6–12.6%.
Conference mixers
| Operation | Fields | Result |
|---|---|---|
mixer.create | mixer_id, max_participants (64) | |
mixer.add | mixer_id, endpoint_id, role (optional) | participants |
mixer.remove | mixer_id, endpoint_id | removed |
mixer.set | mixer_id, endpoint_id, muted, deafened, input_gain_db (or gain_db, −60 to +24), output_gain_db (−60 to +24), role, whisper_to | set |
mixer.destroy | mixer_id | destroyed; mixer.destroyed follows (its recording, if any, is stopped first) |
A mixer gives each participant the sum of everyone else (N − 1 mixing), on a thread of its own. Every 20 ms it does the following:
- Each participant’s audio goes through its own jitter buffer, decoder and loss concealment, resampled to 16 kHz. A participant with nothing due contributes silence.
- The mixer sums the participants in 32 bits, each at its gain. A muted participant adds nothing.
- Each participant gets the sum minus its own contribution, through its own limiter. Nothing clips before its own voice is taken out.
- Each mix is encoded in the participant’s own codec and played to it. Wideband codecs (G.722, Opus, AMR-WB) get it at 16 kHz, narrowband ones at 8 kHz.
Roles. A participant’s role decides who hears it:
participant(the default): everyone hears it. A supervisor barging in is one.listen: it hears everyone, and no one hears it. A supervisor listening in.whisperwithwhisper_to(another participant’s endpoint id): only that participant hears it. Its audio is added to that participant’s mix alone, never to the sum. A supervisor coaching an agent.
Every role hears the whole conference.
Active speaker. The loudest participant whose voice is detected is
reported with mixer.speaker. A speaker stays the active one for at
least 500 ms.
Per participant.
muted: no one hears it.deafened: it hears silence, while it is still heard and its RTP still flows.input_gain_db: on what it says.output_gain_db: on what it hears.
Participants may use any codec the relay converts, and may differ
from each other. An endpoint in a mixer is not bridged. In-band key
presses of participants give dtmf.detected.
Taps. stream.start on a participant makes a tap: a PCM stream
(speech recognition, say) gets a copy of what the participant says, from
the mixer, decoded at the stream’s rate, while the mix goes on.
- A tap cannot inject (
inject: trueis refused): the mixer plays to the participant. - A participant has 4 taps at most.
- A tap whose queue is full loses copies, never the mix.
- A tap ends (
stream.ended) when its participant leaves the mixer.
Recovery. Each mixer’s desired topology is its plan: its id, tenant,
and seats (role, whisper_to, muted, deafened, both gains). Every
successful mixer.* operation updates it, and it is saved with the
state. After a restart, before any request is answered, every planned
mixer is created again with the same id, and each participant whose
endpoint was restored is seated again with its settings.
recovery.report lists them in restored_mixers. A participant whose
endpoint did not come back is reported in lost
(kind: "mixer_participant"). The mixing state itself starts afresh
(jitter buffers, the active speaker), and taps are not restored, as no
PCM stream is.
Recording a mixer
The recording operations take a mixer_id instead of an endpoint_id.
A request naming both is refused (invalid).
| Operation | Fields | Result |
|---|---|---|
recording.start | mixer_id, options (format, sample_rate, channels, bitrate, include_whispers, tracks, metadata) | recording, recording_id, mixer_id |
recording.stop | mixer_id | recording, recording_id, mixer_id, state (stopped until the files are made) |
recording.pause, recording.resume | mixer_id | recording_id, mixer_id, state, changed, pauses |
recording.query | recording_id | As an endpoint recording’s, with mixer_id instead of endpoint_id, and participants, duration_ms, lost_ms, section, files, tracks, options |
- What is recorded is what a
listenparticipant hears: every participant heard by everyone, at its input gain, through a limiter. Muted,listenandwhisperparticipants are not in it, unlessinclude_whispers: trueadds the whisperers (for compliance). A deafened participant is in it: deafening changes what it hears, not what it says. Output gains do not apply. - The timeline is continuous from start to stop, one 20 ms period at
a time at the mixer’s 16 kHz, resampled to
sample_rate: silence when no one speaks, participants joining and leaving change the sum, not the timeline. The mix is taken in the same period the participants hear it, and recording adds no latency to the conference. - Options.
formatandsample_ratedefault to[recording]’s; a[recording] formatofpcapgives WAV (a mixer has no packets, andformat: "pcap"is refused).channelsismono(the default) orstereo(the same mix on both).metadataadds tags to[recording.metadata]’s. Any other option isinvalid. - Tracks. With
tracks: true, each participant’s own input (after its input gain, whatever its role or mute) is also written to a file of its own, on the mix’s timeline: silence before it joined and after it left, so every track lines up with the mix. For transcription with speakers apart. Its name is the mix’s with{track}the endpoint id (-{track}added to afile_namewithout it), its tags carryTRACK.recording.completedandrecording.querylist them intracks:[{endpoint_id, file, uploaded}]. - One at a time. Starting again while a mixer records gives the same
recording_id. At most[recording] max_mixer_recordings(64) mixers record at once; beyond,exhausted. With anidempotency_keythe operation is in the ledger, andoperation.querylists itsrecording_id. - Pauses count once the mixer has taken them, as an endpoint
recording’s once its media workers have:
pausedthen, with the time inpauses; if the mixer does not confirm within a second,timeoutand the recording stayspausing. A pause holds nothing: the file is shorter by it. While any participant’s endpoint is sensitive (endpoint.sensitive), the recording is paused, and resumed when none is, unless the controller paused it itself. - Participants: each endpoint that was in the mixer while it
recorded, with its
external_idand its[joined_at, left_at]intervals (ms since the epoch). The list is also in the files’ tags (PARTICIPANTS), withMIXER_IDandRECORDING_ID. - The end.
recording.stop(ormixer.destroy) ends it; its writer writes what is queued, and the audio is converted like an endpoint recording’s: the file in[recording] dirwith its JSON report, stored locally or on S3, with the upload webhook. Thenrecording.completed(orrecording.failed), a mixer event (see Events):recording_id,mixer_id,file(the first section’s),files(every section’s),tracks,uploaded,section,duration_ms,lost_ms. Aftermixer.destroyit comes aftermixer.destroyed, andrecording.querykeeps answering. - File names:
[recording] file_namewith{mixer_id},{recording_id}and{track}(empty for the mix); with the defaultfile_name, a mixer recording is calledmixer-{mixer_id}-{recording_id}-{section}{track}. - Backpressure. The mixer hands each period to a queue of 5 s and
never waits for it. A period the queue has no room for is lost:
silence at its place in the file, counted in
lost_ms, and logged once per recording. - Write failures (a full disk) never leave half a period in the
spool, so the audio after them stays in place. The periods not written
count in
lost_msand become silence once writing works again. A track that cannot be written is given up (its file removed, logged), never left out of step with the mix. A file name already taken is never written into. - A starved mixer. A mixer thread that falls more than 100 ms behind
its schedule (a loaded machine) skips the periods it missed rather than
running them back to back, which would burst them at the participants.
Its recording keeps the wall-clock timeline: the skipped periods are
silence there, counted in
lost_ms. - Conversion failures. A section or track that cannot be converted
keeps its spool, and
recording.completed(when the rest could be) says what indetail. With nothing converted,recording.failed. Converting again after a restart (one that came before the outcome was saved) counts the sections already made. - A restart. A recording whose mixer is rebuilt goes on in a new
section (a new file,
sectionone more): the downtime is between the files, not silence inside one. A paused one stays paused.recovery.reportlists them inrestored_mixer_recordings. One whose mixer did not come back is finished with what it holds, and reported inlost(kind: "mixer_recording"). - Tenancy and
[ha]: the mixer must be the requester’s (unauthorized), and under[ha]the request must prove the mixer’s group, as every operation naming amixer_id.
Video rooms
Browsers in a conference room see each other: the relay forwards their
VP8 video selectively (an SFU), without transcoding and without mixing.
Audio stays with the room’s mixer. Design and status:
docs/video-sfu.md.
| Operation | Fields | Result |
|---|---|---|
video.router.create | mixer_id (optional: the room’s mixer, one router each) | router_id, max_cameras (16), max_screens (1) |
video.router.destroy | router_id | destroyed (its tracks reported removed) |
video.router.query | router_id | tracks, subscriptions, running, dropped, stats (per track: packets, octets, keyframes, PLIs sent, paused, quiet; per subscription: packets, NACKs, retransmitted, PLIs, dropped, waiting for a keyframe) |
video.publish | router_id, endpoint_id, mid (the section the browser sends on), kind (camera or screen) | track_id (publishing it again gives the same, already: true) |
video.unpublish | track_id | removed; the slots showing it show nothing |
video.track.set | track_id, paused (the moderator) | paused, changed |
video.subscribe | router_id, endpoint_id, slot_mid (a section the browser receives on), track_id (optional: empty until video.set), paused, max_height | subscription_id, ssrc (the slot’s, as its answer declared) |
video.set | subscription_id, track_id (another source; null: none), paused, max_height | subscription_id, track_id, paused |
video.unsubscribe | subscription_id | removed |
Endpoints. A browser’s endpoint for a video room is made with
video: "sfu" from its offer (audio and video sections in one BUNDLE).
The relay’s answer, then and at every renegotiation:
- keeps each video section to VP8 and its RTX, so no transcoding is ever needed;
- declares, in every section the relay sends on (the browser’s
recvonlyorsendrecv), the slot’s SSRCs:a=ssrc,a=ssrc-group:FIDanda=msid.
The SSRCs come from the endpoint and the section’s mid, so they never
change. A slot can therefore switch sources with video.set, without
new SDP. Both ways of offering slots work: a fixed number in the first
offer (say 9 cameras and a screen), or sections added by re-INVITE. A
renegotiated endpoint’s tracks and slots carry on with the same ids.
Forwarding.
- A slot’s packets go out under its SSRC, with continuous sequence numbers and timestamps across source switches.
- A new source, and every subscription, starts on a keyframe. The
relay asks the publisher for one (PLI), at most once per track every
300 ms, and asks again after a second without one. After 3 s it
reports
video.keyframe.timeout. - A subscriber’s NACK is answered from the relay’s own cache of each track’s recent packets (512, about a second at 720p), as RTX when the slot negotiated it. A NACK never reaches the publisher.
- A subscriber’s PLI or FIR asks the publisher for a keyframe.
- Only the publisher’s VP8 payload type is forwarded. Its own RTX and padding probes are not.
Pauses. A track paused by the moderator (video.track.set) is not
forwarded: video.track.paused, then video.track.resumed, with
reason: "moderator". A publisher silent for 2 s (a camera turned off)
gives the same events with reason: "quiet". A paused subscription
(video.set with paused) gets nothing. Either way it starts again on
a keyframe.
Events are the router’s own (with router_id and, for a room’s
router, mixer_id; no endpoint_id):
video.track.added:track_id,endpoint_id,mid,kind;video.track.removed:track_id,endpoint_id,kind,reason(request,endpoint_destroyed,section_gone);video.track.paused,video.track.resumed:track_id,endpoint_id,reason;video.keyframe.timeout:subscription_id,track_id,endpoint_id.
A subscription gets them unless it names only endpoint_ids or
session_ids.
Limits.
- A router takes 16 cameras and 1 screen.
- An endpoint has 10 slots, and a router 500.
- An endpoint takes part in one router.
- A session has at most 16 media sections.
- Queues are bounded: a full one drops and counts, never blocks a media worker.
Tenancy and [ha]. A router, its tracks and its subscriptions are
its tenant’s. Another tenant’s are unauthorized, and so are its
endpoints. A track of one router cannot be shown in another’s slot.
Under [ha] a router belongs to the group whose proof created it, and
every operation on it, its tracks or its subscriptions must prove that
group.
A restart. The routers’ plans are saved with the state. After a
restart, before any request is answered, each comes back with the same
ids, its tracks and subscriptions started again on their restored
endpoints. recovery.report lists them in restored_routers. What
could not come back is in lost (video_router, video_track,
video_subscription). Browsers keep their SSRCs, so video resumes once
their ICE and DTLS are back.
Not in phase 1: simulcast and layer choice (max_height is stored,
not yet used), bandwidth estimation (TWCC, REMB), H.264, VP9, AV1, and
video recording. Header extensions are not forwarded, so no MID,
orientation or transport-wide sequence on the slots.
Media composition
What processes an endpoint’s audio is a small graph, built only when asked for. An endpoint with none of it stays on the ordinary relay, transcoding and XDP paths, untouched.
| Node | Made by | Runs on |
|---|---|---|
| Decode, jitter buffer, concealment | a stream, a detector, a mixer seat | the PCM shards, or the mixer’s thread |
| VAD, in-band DTMF | stream.start (vad, dtmf), a mixer seat (DTMF) | the same |
| Speech-recognition feed (PCM out) | stream.start with a socket | the PCM shards |
| Tap on a participant | stream.start on a participant | the mixer (copy), the PCM shards (the rest) |
| Mixing (N − 1, roles, gains) | mixer.add | the mixer’s thread |
| Injection (PCM in), encode | stream.start with inject, a mixer seat | the PCM shards or the mixer, then the media worker |
| Recording | recording.start | the media worker (relayed media only); a mixer’s: the mixer (copy), a writer thread, then the conversion thread |
Rules.
- Ownership. Each node belongs to the endpoint’s tenant, and under
[ha]to the ownership group its creation proved. A tap or a seat is removed with its endpoint. - No cycles. A mixer’s participants are endpoints, never other mixers. An endpoint has one audio sink at a time: a bridge, a mixer, or its own stream. Taps only read. So no graph can loop.
- Atomic changes. Each change is one operation on the control thread, confirmed by the media workers before its reply. A failed one leaves the graph as it was.
- Budgets:
- 64 participants per mixer;
- 4 taps per participant;
- bounded queues everywhere: 64 packets in, 100 ms out, 240 ms towards a service. A full queue drops and counts, and never blocks a media worker.
- Latency:
- a mixed or tapped stream adds the jitter buffer (40 ms target) and one 20 ms frame;
- the output to a participant adds its encoder’s frame;
- injected audio waits in a queue of at most 100 ms.
Events
{"v": 1, "op": "events.subscribe", "types": ["dtmf.detected", "endpoint.destroyed"], "endpoint_ids": ["ep-…"]}
events.subscribe takes these filters, all optional:
types;endpoint_ids,session_ids;all_parties: also events about ng parties, which are not endpoints; these carrycall_idandtaginstead ofendpoint_id;sensitive: sensitive digits as they are, not redacted (see IVR);mixer_ids: the mixers whose own events are wanted.
A mixer’s own events (mixer.destroyed, a mixer recording’s
recording.completed and recording.failed) carry mixer_id and no
endpoint_id. A subscription gets them unless it names only
endpoint_ids or session_ids; with mixer_ids, only those mixers’.
The reply has subscription_id and the current global_seq. Events then
arrive on the same connection, between replies, until the connection
closes or the client calls events.unsubscribe (subscription_id). A
subscriber sees only its own tenant’s events.
{"event": "dtmf.detected", "endpoint_id": "ep-…", "session_id": "ms-…", "tenant": "default",
"generation": 1, "revision": 1, "seq": 3, "global_seq": 41, "time_unix_ms": 1795509710000,
"data": {"digit": "5", "code": 5, "duration_ms": 150, "rtp_timestamp": 320, "source": "rfc4733",
"start_unix_ms": 1795509709850, "end_unix_ms": 1795509710000}}
| Event | data |
|---|---|
endpoint.ready | |
endpoint.failed | reason (dtls, or media with a detail: a media worker could not take the endpoint’s socket) |
endpoint.timeout | |
endpoint.destroyed | reason: request, lease, timeout, ended (ng deleted it) |
endpoint.events_lost | Some of its media events were lost before the journal: what it awaited is indeterminate |
bridge.changed | bridged_to (or null), reason: attached, detached, replaced, peer_destroyed |
ice.connected, dtls.ready | |
dtmf.detected | digit, code, duration_ms, rtp_timestamp, source, start_unix_ms, end_unix_ms; sensitive, or redacted with digit and code null |
playback.completed | playback_id |
playback.stopped | playback_id, reason (request, replaced, dtmf, speech, interrupted, failed, endpoint_destroyed), queued |
recording.completed, recording.failed | file, uploaded, section; a recording whose file the worker cannot open fails at once, with reason: "recording" and a detail |
speech.started, speech.ended | (an endpoint with a PCM stream) |
stream.mark | stream_id, mark, generation, played_ms, flushed, boundary (rtp_sent) |
stream.flushed | stream_id, generation, played_ms |
stream.ended | stream_id |
mixer.speaker | mixer_id |
mixer.destroyed | mixer_id, reason (a mixer event) |
gap | missed (and source: "media" when the relay’s own queue overflowed) |
DTMF.
- An RFC 4733 key press is reported once, when it ends. Its repeated end packets are deduplicated.
- An event that never gets its end packet is reported up to about a second late.
- In-band keys (tones in the audio) are found in the audio a PCM stream
or a mixer decodes. They are reported with
source: "inband", about 40 ms after the key is released (plus the 40 ms jitter buffer). Keys shorter than 40 ms are not seen.
Delivery. Events can be replayed from a cursor, at least once, in order, with every loss said:
- Identity. Each event carries
event_id(<boot_id>:<global_seq>),boot_id,seq(counts up per endpoint) andglobal_seq(counts up across all events). A jump in theglobal_seqof a filtered subscription is not a loss: other events are filtered out. - The journal. The relay keeps the last
[control] native_event_journalevents (65,536 by default), in memory: they outlive the client’s connection, not a restart of the relay. - Resuming.
events.subscribewithcursor(anevent_id, the previous subscription’scursor, or a page’s watermark) first replays what came after it, then goes on live. Its reply saysresumed: true. - What cannot be resumed is said: a cursor older than the journal
gets a
gapwithreason: "retention_expired", and one of another run of the relay getsreason: "boot_changed"(resumed: false). The client then reconciles withinventory.listandrecovery.report. Terminal results (recordings, playbacks) are also in the inventory andrecording.query. - A subscriber that falls behind (its queue holds 1024 events) misses
events. As soon as it has room, it gets a
gapwithreason: "overflow",missed, andresume_cursor. Subscribing again fromresume_cursorgets the missed events back, possibly some twice: deduplicate byevent_id. - A snapshot without a race: take
inventory.list, then subscribe from its watermark (<boot_id>:<global_seq>). Nothing between the two is missed. - Lost before the journal. When the relay’s own queue of media events
overflows, the events are lost before they reach the journal:
- the endpoints known to be affected get
endpoint.events_lost, and their snapshots sayevents_indeterminate: true, since a digit collection or an announcement’s end may be missing; - a
gapwithreason: "media_overflow"lists them; - the count is in
rtpflux_media_events_dropped_total.
- the endpoints known to be affected get
- No one waits. A slow subscriber never holds up the relay: neither its media workers nor its control thread wait for it.
Example: two legs
A softswitch answers an inbound call and bridges it to a leg it places itself:
endpoint.createwith the caller’s offer (remote_sdp). The reply’ssdpis the answer for the 200 OK. The caller is parked.endpoint.createwithcodecs. The reply’ssdpis the offer for the outbound INVITE.endpoint.apply_answerwith the callee’s answer.bridge.attach. The two talk.- A re-INVITE from the caller:
endpoint.preparewith its offer, the answer back in the 200 OK, thenendpoint.commit(orendpoint.abortif the transaction fails). - BYE:
endpoint.destroyfor both.
The tests run this, and the rest of the API, against a running relay.
Integration with SIP servers
rtpflux speaks rtpengine’s ng protocol, so a SIP proxy that drives rtpengine drives rtpflux the same way. This page has complete, tested configurations for Kamailio, OpenSIPS and ferrosip, the FreeSWITCH side of a proxy + rtpflux + FreeSWITCH setup, and the test bench that checks them with real calls. For the ng options themselves, see Control protocol.
Kamailio
contrib/kamailio/kamailio.cfg is a
complete configuration: Kamailio as the edge proxy in front of a PBX, with
rtpflux relaying every call’s media through Kamailio’s rtpengine module.
phones ──SIP──▶ Kamailio ──SIP──▶ PBX (FreeSWITCH, Asterisk, …)
│ │ ng (UDP 2223) │
└────RTP────▶ rtpflux ◀───────RTP──────────┘
What it does:
- Every INVITE goes to the PBX. Kamailio adds a
Record-Route, so re-INVITEs and BYE come back through it. rtpengine_manage()rewrites each SDP with rtpflux’s address and ports: the offer in the INVITE (or a late offer’s answer in the ACK), the answer in the provisional or final reply.- BYE, CANCEL and failed calls delete the call in rtpflux, which frees its ports at once.
- The
rtpenginemodule pings rtpflux at start (“rtpengine instance … found, support for it enabled” in Kamailio’s log) and retries an unanswered command three times; rtpflux answers a retransmitted command from its reply cache, so a retry never creates a second call.
It is set up from the environment (Kamailio 5.6 or later):
| Variable | Default | Meaning |
|---|---|---|
KAMAILIO_LISTEN | udp:0.0.0.0:5060 | Where Kamailio listens |
KAMAILIO_ADVERTISE | none | The address to put in Via and Record-Route when listening on 0.0.0.0 or behind NAT |
PBX_URI | sip:127.0.0.1:5080 | Where calls go |
RTPFLUX_NG | udp:127.0.0.1:2223 | rtpflux’s [control] listen |
RTPFLUX_FLAGS | trust-address replace-origin | The flags of every offer and answer |
For example, rtpflux on the same host and FreeSWITCH’s external profile on another:
PBX_URI=sip:10.0.0.20:5080 RTPFLUX_NG=udp:127.0.0.1:2223 \
kamailio -DD -E -f contrib/kamailio/kamailio.cfg
On the rtpflux side, [control] listen must be reachable from Kamailio,
and [[interface]] address (or advertise) must be an address both the
phones and the PBX can send RTP to.
Flags. trust-address uses the addresses in the SDP as they are;
leave it out when phones are behind NAT and their SDP addresses are
private, and rtpflux uses the address the SIP message came from (Kamailio
sends it) and learns the real one from the media. Other useful flags:
ICE=remove towards SIP phones, RTP/AVP to offer plain RTP to the PBX
when callers are browsers, direction=external direction=internal with
two interfaces. See Control protocol.
OpenSIPS
contrib/opensips/opensips.cfg is the
same edge proxy for OpenSIPS 3.4 or later, with its rtpengine module:
every INVITE goes to the PBX through a Record-Route,
rtpengine_manage() rewrites each SDP with rtpflux’s address and
ports, and BYE, CANCEL and failed calls delete the call in rtpflux.
Set where it listens (socket) and rtpflux’s ng address
(rtpengine_sock) in the file. At run time it reads PBX_URI (default
sip:127.0.0.1:5080) and RTPFLUX_FLAGS (default trust-address replace-origin) from the environment. mpath is the module directory of
Debian and Ubuntu packages and of the official opensips/opensips
images; adjust it elsewhere.
PBX_URI=sip:10.0.0.20:5080 opensips -F -f contrib/opensips/opensips.cfg
The flags are the same as Kamailio’s. For SIPREC recording, OpenSIPS’s
siprec module drives rtpflux’s subscriptions; see
Control protocol.
ferrosip
ferrosip’s media module is
Kamailio’s rtpengine module: the same ng commands and flag syntax.
contrib/ferrosip/ is the same setup as the
Kamailio one, in ferrosip’s own configuration (ferrosip.toml and the
routing in routes/main.fsr):
- Every INVITE goes to the PBX, record-routed; its offer goes through
media.offer(), the answer in a 180–299 reply throughmedia.answer(). - BYE and CANCEL, and a call that fails or times out,
media.delete()it in rtpflux. A re-INVITE’s offer (or a late answer in the ACK) goes throughmedia.manage().
It is set up from the environment, with the same names as the Kamailio configuration:
| Variable | Default | Meaning |
|---|---|---|
SIP_ADDR | 127.0.0.1 | Where ferrosip listens (UDP 5060) |
PBX_URI | sip:127.0.0.1:5080 | Where calls go |
RTPFLUX_NG | udp:127.0.0.1:2223 | rtpflux’s [control] listen |
RTPFLUX_FLAGS | trust-address replace-origin | The flags of every offer and answer |
SIP_ADDR=10.0.0.10 PBX_URI=sip:10.0.0.20:5080 \
ferrosip --config contrib/ferrosip/ferrosip.toml
ferrosip check --config contrib/ferrosip/ferrosip.toml # validate it
FreeSWITCH
FreeSWITCH does not drive a media relay itself: it sits behind Kamailio as the PBX, and Kamailio has rtpflux relay the media between the phones and FreeSWITCH (the diagram above). FreeSWITCH then only ever sees rtpflux’s address and ports in the SDP, and sends its RTP there.
contrib/freeswitch/ has two drop-in files for
a standard FreeSWITCH configuration:
-
sip_profiles/rtpflux.xml: a SIP profile on port 5080 for calls from the proxy. Calls from the addresses in the ACL listrtpflux_proxiesare taken without digest authentication (Kamailio authenticates its users); anything else is challenged. Add the list toautoload_configs/acl.conf.xml:<list name="rtpflux_proxies" default="deny"> <node type="allow" cidr="10.0.0.10/32"/> <!-- Kamailio --> </list>No NAT settings are needed on this profile: rtpflux already learns where each phone’s media really comes from.
-
dialplan/rtpflux.xml: thefrom-proxycontext, with two test numbers (echosends back what it hears,toneplays 440 Hz) and a commented transfer to yourdefaultcontext.
The profile prefers G.722, then PCMA, PCMU and Opus; G.722 needs
mod_spandsp loaded (it is in a standard FreeSWITCH build).
Point Kamailio at the profile with PBX_URI=sip:<freeswitch>:5080.
The test bench
integration/ runs real calls through these
configurations in Docker:
uac .13 ──SIP──▶ kamailio .11 ──SIP──▶ uas (SIPp) .12
uac .13 ──SIP──▶ kamailio-fs .15 ──SIP──▶ freeswitch:5080 .14
uac .13 ──SIP──▶ ferrosip .17 ──SIP──▶ uas (SIPp) .12
uac .13 ──SIP──▶ kamailio-g722 .18 ──SIP──▶ freeswitch:5080 .14
uac .13 ──SIP──▶ opensips .19 ──SIP──▶ uas (SIPp) .12
zrtp-a .21 ──SIP──▶ kamailio-zrtp .16 ──SIP──▶ zrtp-b (linphone) .22
│ │ ng │
└──────RTP──▶ rtpflux 172.30.89.10 ◀──RTP─────┘
- rtpflux is built from the repository’s
Dockerfile. - Kamailio and SIPp come from Debian’s packages. Both Kamailio
instances run
contrib/kamailio/kamailio.cfgunchanged; they differ only inPBX_URI. - OpenSIPS (3.6) is the official image
opensips/opensips, pinned by digest. It runscontrib/opensips/opensips.cfgwith only its listen socket and rtpflux’s ng address set to the bench’s (sedat start), andPBX_URIpointing at the SIPp callee. The caller calls through it as through Kamailio. - FreeSWITCH (1.11) is the community image
safarov/freeswitch, pinned by digest. It runs a minimalfreeswitch.xmlthat includescontrib/freeswitch/’s profile and dialplan unchanged. - The caller (SIPp) offers G.711 A-law and plays 7 seconds of audio (236
RTP packets). It calls twice: through the first Kamailio to a SIPp
callee that echoes every packet, then through the second to
FreeSWITCH’s
echo. - ferrosip is built from its repository at the commit in
integration/ferrosip.ref, and runscontrib/ferrosip/unchanged. The repository is private:run.shclones it over SSH (or uses a checkout inintegration/ferrosip-src; CI makes one with theFERROSIP_TOKENsecret, a read-only token). Without access, the ferrosip call is skipped (REQUIRE_FERROSIP=1makes that a failure). The caller calls through it to the SIPp callee. - Transcoding: a fourth Kamailio adds
codec-transcode-G722 codec-mask-PCMAto its flags, so FreeSWITCH is offered G.722 only while the caller speaks PCMA. The call connects only if FreeSWITCH takes rtpflux’s G.722, and the echo comes back only if each side decodes the other’s (FreeSWITCH’s G.722 is SpanDSP’s); the caller is answered with its own PCMA. - ZRTP: two
linphonec(Debian’slinphone-cli, with bzrtp) with ZRTP mandatory call each other through the third Kamailio. Their keys are agreed end to end, through rtpflux (see Media handling).
integration/run.sh # build, run one call, check, tear down
KEEP=1 integration/run.sh # leave the bench running
RUST_LOG=debug integration/run.sh # rtpflux logs at debug (ng warnings included)
It passes when, for each call:
- the call completes (INVITE, 200, ACK, BYE, 200 through the proxy);
- the parties got rtpflux’s address in the SDP, not each other’s (the caller’s and the SIPp callee’s SDP are checked; a FreeSWITCH that got the caller’s address would send its echo around rtpflux, which the next check catches);
- rtpflux forwarded the audio both ways (472 packets, 236 each way; 95% is required, as FreeSWITCH’s echo starts a few frames late);
- rtpflux answered every ng command without an error;
- the call is gone from rtpflux after the BYE;
and when, for the ZRTP call, both phones reach ZRTP’s secure state with the same short authentication string (they could not if the relay had interfered with the key agreement) and rtpflux relayed their ZRTP packets.
The bench found one real bug on its first run: the two Kamailio
instances, identical containers, sent the same ng cookies, and rtpflux
answered the second one’s offer from its reply cache. Replies are now
cached per sender.
The SIP messages each party saw, and every container’s log, are left in
integration/out/. It needs Docker with Compose (v2, or v1’s
docker-compose). CI runs it on every push.
Operations
Running rtpflux in production: monitoring, logs, restarts and the systemd service.
Command line
rtpflux [OPTIONS]
-c, --config <PATH> Configuration file [default: /etc/rtpflux/rtpflux.toml]
-l, --log-level <LEVEL> error, warn, info, debug or trace
--check Validate the configuration and exit
--print-example-config Print the documented example configuration and exit
--webui-hash Read a password on standard input and print its
[webui] password_hash value
-h, --help Print help
-V, --version Print version
SIGTERM or SIGINT (Ctrl-C) stops the relay cleanly; with a state file
or Redis, calls are saved first.
Metrics
Enable the Prometheus endpoint:
[metrics]
listen = ["127.0.0.1:9101"]
and scrape http://127.0.0.1:9101/metrics:
# HELP rtpflux_packets_forwarded_total Packets relayed by the userspace workers.
# TYPE rtpflux_packets_forwarded_total counter
rtpflux_packets_forwarded_total 0
...
rtpflux_ng_requests_total{command="offer"} 2
rtpflux_ng_requests_total{command="answer"} 1
| Metric | Type | Meaning |
|---|---|---|
rtpflux_packets_forwarded_total | counter | Packets relayed by userspace (the XDP fast path’s are in query, not here) |
rtpflux_packets_dropped_total | counter | Packets dropped: no call on the port, wrong source, no destination yet, or malformed |
rtpflux_send_errors_total | counter | Packets the kernel refused to send |
rtpflux_srtp_rejected_total | counter | SRTP/SRTCP packets that failed authentication or replay checks, or arrived before keys existed |
rtpflux_zrtp_forwarded_total | counter | ZRTP packets relayed untouched between endpoints (also counted as forwarded) |
rtpflux_calls_timed_out_total | counter | Calls ended because media stopped |
rtpflux_ice_checks_total | counter | ICE connectivity checks and consent requests the relay sent |
rtpflux_ice_nominations_total | counter | Candidate pairs the relay nominated, or accepted as nominated |
rtpflux_ice_role_conflicts_total | counter | ICE role conflicts resolved (both sides claimed the same role) |
rtpflux_ice_consent_lost_total | counter | Pairs whose consent expired (RFC 7675): the relay stopped sending to them |
rtpflux_ice_restarts_total | counter | ICE restarts |
rtpflux_bytes_forwarded_total | counter | Octets (UDP payloads) relayed by userspace |
rtpflux_kernel_packets_total, rtpflux_kernel_bytes_total | counter | Packets and octets the XDP fast path relayed in the kernel, as of the relay’s last poll (once a second) |
rtpflux_dtls_handshakes_total | counter | DTLS-SRTP handshakes that keyed SRTP |
rtpflux_dtls_failures_total | counter | DTLS-SRTP associations that failed (a wrong certificate, a broken handshake) |
rtpflux_offloaded_calls | gauge | Relay calls the XDP fast path relays now |
rtpflux_connections | gauge | Parties joined with connect (transfers) |
rtpflux_copies | gauge | Copies of a party’s media to another (directional connect, inject, mesh) |
rtpflux_subscriptions | gauge | Media subscriptions (SIPREC and others) |
rtpflux_delayed_deletes | gauge | Deletes waiting for their delete-delay |
rtpflux_state_writes_total, rtpflux_state_write_failures_total | counter | State file writes, and the ones that failed |
rtpflux_redis_writes_total, rtpflux_redis_failures_total | counter | Snapshots written to Redis, and failed attempts |
rtpflux_redis_failing | gauge | 1 while writing to Redis fails |
rtpflux_sessions | gauge | Dialogs with relayed media |
rtpflux_calls | gauge | Relayed media sections (a dialog with audio and video counts 2) |
rtpflux_workers | gauge | Media worker threads |
rtpflux_ng_requests_total{command=…} | counter | ng requests by command (other for unknown commands) |
rtpflux_native_endpoints, rtpflux_native_bridged_endpoints | gauge | Endpoints of the native API, and those bridged |
rtpflux_native_mixers, rtpflux_native_streams | gauge | Conference mixers, and PCM streams to external services |
rtpflux_media_events_dropped_total | counter | Media events (key presses, announcements’ ends, …) dropped because the queue to the control thread was full |
rtpflux_ng_errors_total | counter | ng requests answered with an error |
rtpflux_ng_retransmissions_total | counter | Repeated ng requests answered from the reply cache |
rtpflux_recordings_converted_total | counter | Recordings converted when they ended (or kept as pcap) |
rtpflux_recording_conversions_failed_total | counter | Recording conversions that failed (the pcap is kept) |
rtpflux_recording_uploads_total | counter | Recording files uploaded to S3 |
rtpflux_recording_upload_failures_total | counter | Recording files not uploaded after every attempt (kept locally) |
rtpflux_recording_webhooks_delivered_total | counter | Upload notifications the webhook answered with 2xx |
rtpflux_recording_webhooks_failed_total | counter | Upload notifications given up on, or refused with a final status |
rtpflux_recording_webhooks_dropped_total | counter | Upload notifications dropped unsent (queue full, or the relay stopping) |
Worth alerting on:
- A rising
rtpflux_srtp_rejected_total: key mismatches, or someone sending forged packets. - A rising
rtpflux_send_errors_total: network or socket buffer problems. rtpflux_redis_failingat 1, or a risingrtpflux_state_write_failures_total: calls would not survive a restart.- A rising
rtpflux_dtls_failures_total: browsers whose certificates do not match their SDP, or networks breaking the handshake. - A rising
rtpflux_recording_upload_failures_totalorrtpflux_recording_webhooks_failed_total: recordings piling up locally, or a receiver not hearing about them. rtpflux_ng_errors_totalgrowing faster than usual: the proxy is sending requests the relay rejects.
The endpoint has no authentication; keep it on a private address.
Logs
Logs go to standard error (and so to the journal under systemd). The
level comes from, in order of precedence: --log-level, the RUST_LOG
environment variable, then [log] level (default info).
At info you see start-up, every offer, answer and delete with its
Call-ID, detected DTMF, and calls ending on timeout:
INFO rtpflux: ng control on udp 127.0.0.1:2223
INFO rtpflux::control: call call-1@example.com: offer, 1 relayed media section(s)
INFO rtpflux::control: call call-1@example.com: answer, 1 relayed media section(s)
INFO rtpflux::control: ng offer x: missing sdp
INFO rtpflux::relay: call 7 ended: no media for the configured timeout
debug adds ICE and DTLS progress per call. RUST_LOG also accepts
per-module filters, such as RUST_LOG=info,rtpflux::dtls=debug: a level,
then module=level pairs, comma-separated. A value that is not of that
form is reported at start, and [log] level is used instead.
SRTP keys, DTLS secrets and a=crypto lines are never logged.
Restarts
If an internal thread of the relay (a media worker, the ng control thread or the XDP controller) ever fails, rtpflux logs the error and exits at once instead of running on with some calls dead, so that systemd (or your supervisor) restarts it. A failure while converting a recording only loses that recording’s audio file; its pcap is kept.
Set a state file to keep calls through a restart or an upgrade:
[sessions]
state_file = "/var/lib/rtpflux/state.json"
The relay writes all dialogs to this file within a second of a command
that changes a call (at most once a second), and when it stops. Each
write replaces the file atomically and reaches the disk first. If the
relay crashes, up to the last second’s changes can be missing. A file
that cannot be used at start (not valid, or of another version) is renamed
to state.json.bad, so that the relay’s next write does not replace it. The file
holds SRTP keys and ICE passwords, so it is created readable by the
relay’s user only (mode 0600). At start it recreates each call on the
same ports, with:
- both sides’ addresses, including addresses learned by latching;
- SDES keys, ICE credentials,
rtcp-muxand BUNDLE; - blocking, transcoding and recording (which continues in the same file);
- announcements, which resume where they would have been, or are dropped
if they would have finished (an announcement from a
blobis not kept); - media subscriptions, on their ports and with the relay’s SRTP keys towards the subscribers, copying again once their calls are back;
media echo,connections and the parties’ labels;- for an offer not answered yet, what the offer decided for its answer:
the relay’s keys offered to the answerer (each SDES suite), opportunistic
and legacy OSRTP, the
rtcp-muxand DTLS roles,ptime, transcoding and telephone-event plans, and ICE passed through. An answer that comes after the restart is handled as it would have been before it; - a re-offer made with
track-stateand not answered, which can still be rolled back, and parties made bycreate.
Phones keep sending to the same ports during the restart and carry on when the relay is back. Packets that arrive while it is down are lost.
Limitation: DTLS keys are not saved. A WebRTC side has to make a new DTLS handshake, which browsers do only when renegotiating. In practice, browser calls do not survive a restart.
State in Redis
The same state can also go to Redis, so that another host (or this one after its disk was replaced) can take the calls over:
[sessions]
state_file = "/var/lib/rtpflux/state.json" # optional with Redis
redis = "redis://:password@10.0.0.5:6379/0"
redis_key = "rtpflux:state:relay-a"
- Every save writes the file (if set) and the key, with the same snapshot. Redis is written by a background thread that only keeps the newest snapshot, so a slow or unreachable server never delays ng commands. While Redis is down, the relay logs it once, retries every second, and logs again when writes succeed.
- On shutdown the relay waits up to 3 seconds for the last snapshot to reach Redis.
- At start, with both a file and Redis, the newer snapshot is restored (each records when it was taken). With Redis only, it is read from Redis. An unreachable Redis is logged, and the file is used.
- A host taking over another’s calls needs the same interfaces and port range, and the calls’ addresses must reach it (a floating IP, for example). Point it at the other relay’s key.
- The value holds SRTP keys and ICE passwords. Use a password (
AUTH, with a user for Redis ACLs) and keep Redis on the host or a private network: the connection is not encrypted.
systemd
contrib/rtpflux.service is a ready-made unit:
sudo install -m 755 target/release/rtpflux /usr/bin/rtpflux
sudo install -D -m 644 config/rtpflux.toml /etc/rtpflux/rtpflux.toml # then edit
sudo cp contrib/rtpflux.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now rtpflux
What it sets up:
- Runs
rtpflux --checkbefore every start, so a broken configuration never replaces a running relay’s settings unnoticed. - Runs as an unprivileged dynamic user, with a read-only system, private
/tmpand no access to home directories. - Keeps state in
/var/lib/rtpflux(use that forstate_file). - Raises the open-file limit. Every call holds four sockets, and the usual default of 1,024 would cap the relay at about 250 calls.
- Grants only the capabilities the XDP fast path needs (
CAP_BPF,CAP_NET_ADMIN,CAP_PERFMON). Remove them if you do not use XDP. - Restarts the relay if it fails.
If you use recording, give the service write access to the recording
directory, for example with ReadWritePaths=/var/spool/rtpflux in a
drop-in (systemctl edit rtpflux).
Capacity planning
- Ports: two RTP/RTCP pairs per media section. An audio-and-video call uses four pairs.
- File descriptors: four sockets per media section.
- CPU: in the benchmark, four worker threads relayed 200,000 plain RTP packets per second (2,000 G.711 calls) using about three CPUs. See Benchmarks. SRTP adds a little; Opus transcoding costs much more per packet.
- Memory: buffers are allocated at start from
[runtime]and[sessions] max, so memory use does not grow with traffic.
Web UI
rtpflux can serve a small website for operators. It shows what the relay is doing right now: traffic, calls, statistics and recent log lines. It is read-only: nothing you do in it can change a call or the relay.
Turning it on
-
Choose a password and make its hash. The command reads the password from standard input (
read -skeeps it off the screen and out of the shell history):read -s -p "Password: " pw && echo "$pw" | rtpflux --webui-hash; unset pwIt prints a line like
sha256:3f1c…:9a07…. -
Add a
[webui]section to the configuration:[webui] listen = "127.0.0.1:8090" user = "admin" password_hash = "sha256:3f1c…:9a07…" -
Restart rtpflux and open
http://127.0.0.1:8090/. The browser asks for the user and password.
See Configuration for every option.
Pages
| Page | What it shows |
|---|---|
| Overview | Live tiles with five-minute sparklines: packets relayed and dropped per second, sessions, relay calls, ng requests per second, SRTP rejections, send errors, calls ended by the media timeout, DTLS handshakes (and failures), joins, copies and subscriptions, and with XDP the packets relayed in the kernel and the calls there. ng requests per second by command. The process (version, uptime, memory, threads, workers, and how each worker receives: io_uring, or recvmmsg and why io_uring was refused, flagged when it is not as configured) and the configuration (ports, sessions and strict_source, every timeout, interfaces and their learned server-reflexive addresses, ICE mode and STUN server, ng over UDP, TCP and HTTP/WebSocket, metrics, state file and Redis, XDP, recording, and S3 with its webhook). Configuration warnings from start-up (what --check prints) are shown at the top. A Media workers table shows each worker’s calls, calls in XDP, packets per second, totals relayed and dropped, send errors, SRTP rejections and how it receives, so an overloaded or idle worker stands out. |
| Calls | Every dialog: state (offered or answered), age, call-id, tags, interfaces, security (plain, SDES-SRTP or DTLS-SRTP), number of media sections, and whether it is recorded, blocked or playing an announcement. Badges show what links a call to more parties or to other calls: multi-party (more than one dialog: a B2BUA’s legs, a three-way call, a conference), joined (connect: a transfer), copies (monitoring, whisper, inject, mesh) and subscribed (SIPREC and other subscriptions); search for them by name. Search, sort and pages. Click a call to see what will end it (an unanswered offer, final_timeout, a delete-delay under way, with the time left) and its fork branch, then each media section: profiles, security, rtcp-mux, BUNDLE, ICE passed through, and whether the XDP program relays it in the kernel; for each side the codec it receives, the conversion of what it sends, its ptime, the direction its SDP asks for (sendrecv, sendonly, recvonly, inactive, or held with c=0.0.0.0), latching (strict-source, handover), DTLS role and ICE, non-RTP media (T.38) and DTMF security; and for each side’s RTP and RTCP legs the peer address, relay port, packets, octets, drops, loss, jitter, round-trip time, the DTMF keys received, whether the latch has settled, the DTLS state (handshaking or keyed) and the relay’s ICE agent (role, state, selected pair, consent). A call with more than two parties, links or subscriptions also shows Parties and links: each party with its label, codec and the parties it is in dialogs with; each join or copy with its direction, the other call when it is in one, and the codec conversion; and each subscription with its sources, profile and state. |
| Statistics | Every counter and gauge (the same as /metrics), with its rate per second and a five-minute history; filter by group. |
| Recordings | With [recording] dir: the pcaps there (each recording’s, while it is written and, with keep_pcap, after it is converted), with call-id, tags, length, size and whether an audio file was made. Click one to see its streams (per sender, receiver and SSRC: packets, octets, packets lost, length, payload types; caller and callee once converted) and its packets (time, addresses, kind — RTP, RTCP, STUN, DTLS, ZRTP —, length, and the RTP or RTCP header fields; filter by kind, search, sort), or download the pcap for Wireshark. Payloads are never shown. With storage = "s3" it has two more tabs, since uploaded files leave the directory: Uploads to S3 (the bucket, endpoint, prefix and webhook settings, then the last 200 uploads: when, call, each file’s object key, size, and why a file was kept locally) and Webhook deliveries (the last 200 notifications: outcome — delivered, rejected, failed or dropped —, HTTP status, attempts, error and delivery id). Error texts never include URL queries or credentials. |
| XDP | With [xdp] enabled: the calls the XDP program relays in the kernel, with their dialog, media section and worker, and for each direction the peer, where it is sent, the device, packets and octets (as of the relay’s last poll, once a second), and what the kernel does besides relaying (drops a blocked side, sends DTMF up to userspace, copies to the recording ring). |
| Logs | A live tail of the last log lines (log_buffer), with a level filter and search. Only lines that pass the log level are kept. A call’s Log lines of this call button opens it searching for the call-id. |
The views refresh every refresh_ms (two seconds by default) while they
are open. The Pause button in the header stops all refreshing. Light
and dark mode follow the system, and the layout works on a phone.
Packets the XDP fast path relays in the kernel are added to a call’s counters once a second.
Security
- Read-only. The server answers
GETandHEADonly; anything else gets405. Each API path reads one fixed piece of state. - Login on every request, with HTTP Basic authentication. The password
is stored only as a salted PBKDF2-HMAC-SHA256 hash (100,000 rounds, so
slow to guess should the configuration leak), and compared in constant
time. Hashes made by older versions (
sha256:…) still work; make a new one with--webui-hashto get the stronger form. - Lockout. Five failed logins from one address (for IPv6, one /64
network) within a minute lock it out for a minute (
429). Behind a reverse proxy every client has the proxy’s address, so anyone’s failed logins lock out everyone: there, let the proxy authenticate too, or rate limit at the proxy. - Slow clients. A request head must arrive within 10 seconds of its first byte, so slow-sending clients cannot hold the connections.
- No encryption of its own. Basic authentication sends the password
with every request. Keep
listenon127.0.0.1and use an SSH tunnel (ssh -L 8090:127.0.0.1:8090 relay-host), or put a TLS reverse proxy such as nginx or Caddy in front of it. - Strict headers: a Content-Security-Policy that allows only the UI’s
own files,
X-Frame-Options: DENY,nosniffandno-referrer. API answers are never cached. - Limits: request heads up to 8 KiB, no request bodies, idle
connections closed after 15 seconds, at most
max_connectionsat once. - What it shows: call-ids, tags, and the IP addresses and ports of
the parties. With
[recording] dir, it also hands out the recordings’ pcaps, which hold the calls’ audio (recorded after SRTP decryption). It never shows SRTP keys or DTLS secrets. Treat access to the UI as access to that data and to the recordings. - Recordings, safely: a recording is named by its path in the
recording directory, which must end in
.pcapand name a regular file in it or in arecording-pathsubdirectory: plain names, none starting with.(so no..), at most 4 levels, never through a link. At most 300,000 packets of a file are read per request (a longer one says so), and pcaps over 256 MiB are not downloaded through the UI.
The API
The UI’s JSON API can be used on its own, for example with curl:
curl -u admin 'http://127.0.0.1:8090/api/v1/calls?q=alice&sort=-age'
| Path | Answer |
|---|---|
/api/v1/meta | Version, refresh interval and the available pages |
/api/v1/info | Process and configuration facts |
/api/v1/stats | Every counter and gauge, with kind, help and a timestamp |
/api/v1/calls | The dialogs |
/api/v1/calls/detail?call_id=…&from_tag=… | One dialog with its legs (from_tag: the row’s key) |
/api/v1/calls/parties?call_id=… | A call’s parties, dialogs, links (joins and copies, to other calls too) and subscriptions |
/api/v1/logs?after=<seq> | Log lines after a sequence number |
/api/v1/recordings | The pcaps in [recording] dir, newest first |
/api/v1/recordings/streams?file=… | One recording’s streams, and the converter’s JSON when there is one |
/api/v1/recordings/packets?file=…&kind=… | Its packets (kind: RTP, RTCP, STUN, DTLS, ZRTP, other) |
/api/v1/recordings/download?file=… | The pcap itself (application/vnd.tcpdump.pcap) |
/api/v1/xdp | With [xdp] enabled: the calls in the kernel, each with both directions |
/api/v1/uploads | With storage = "s3": the last 200 uploads, newest first |
/api/v1/uploads/webhooks | With a webhook: the last 200 upload notifications, newest first |
calls, recordings, recordings/packets, uploads, uploads/webhooks and xdp accept q (search), sort
(field, or -field for descending), offset and limit (up to 500),
and answer
{total, offset, limit, rows}. The list is cached for a second, so many
open browsers cost the relay one answer per second.
Changing the UI
The app is written in TypeScript with Preact,
in crates/rtpflux/webui/ui/. The built files (webui/assets/, about
16 KB gzipped) are committed and embedded in the binary, so building
rtpflux needs no Node.js. After changing the sources, rebuild them with
Node.js 22 or later:
cd crates/rtpflux/webui/ui
npm ci
npm run check # type-check, then build into ../assets
cargo build --release
The build is reproducible: the same sources give the same files.
The UI started as a copy of the web UI of ferrosip, adapted to rtpflux.
Media handling
This page explains what rtpflux does with the media of a call: where it sends packets, how it handles encryption and browsers, and what happens when a call changes.
Ports
For each media section of the offer (each m= line), the relay opens
two port pairs: one facing the offerer and one facing the answerer. Each
pair is an even RTP port and the odd RTCP port above it. When a section
uses rtcp-mux, RTCP shares the RTP port.
A rejected section (port 0) gets no ports and stays rejected in the
rewritten SDP.
NAT and latching
A phone behind NAT often writes its private address, such as
192.168.1.20, into its SDP. Packets sent there would never arrive. The
relay solves this by latching: it watches where the phone’s packets
actually come from and sends media back to that address. This works
because phones send and receive on the same port (symmetric RTP).
Choose how the relay learns with the endpoint-learning option:
| Mode | Behaviour |
|---|---|
heuristic (default; delayed is a synonym) | For the first 3 seconds of media, prefer the source that best matches the SDP: the same address and port, then the same address, then any. After that, the choice is fixed. |
immediate | Latch onto the source of the very first packet. |
off | Always use the address from the SDP. |
By default the relay trusts the SDP address only if the proxy says so:
without the trust-address flag, it uses the address the SIP message came
from (received-from, which proxy modules send automatically).
With the strict-source flag (or [sessions] strict_source = true for
every call), once the relay knows a side’s address it drops packets from
any other source. That stops a third party from
injecting media, at the cost of not following a phone that changes its
address mid-call.
With the media-handover flag, a learned address is not fixed: a new
source takes it over once it has sent 3 packets in a row with none from
the current address in between, as when a NAT rebinds or a phone moves
from Wi-Fi to mobile data. A stray packet does not move it; under SRTP
only authentic packets count. With strict-source as well, the
newcomer’s packets are dropped until it takes over. An address an ICE
check confirmed moves only by ICE. Such calls stay off the XDP fast path,
which does not learn.
Example. Alice’s SDP says 192.168.1.20:4000, but her router
rewrites her packets to come from 203.0.113.7:61234. In heuristic
mode, the relay sees those packets, latches onto 203.0.113.7:61234
within the first seconds of the call, and Bob’s audio reaches Alice.
Timeouts
A call whose media has stopped in both directions for
[sessions] timeout seconds (default 60) after its answer is ended and
its ports freed; an offer never answered ends after offer_timeout
(default an hour). This cleans up calls whose delete never arrived.
A call on hold (either side sendonly, recvonly, inactive or
c=0.0.0.0) uses silent_timeout (default an hour) instead, since a hold
without music on hold sends nothing either way; resuming it brings
timeout back. final_timeout, when set, ends any call that long after
its first offer.
SRTP (encrypted media)
rtpflux handles encryption separately on each side of a call. It decrypts what one side sends and encrypts it again with the other side’s keys. So one side can use SRTP while the other uses plain RTP, or the two sides can use different keys or suites.
SDES keys (a=crypto)
Many SIP phones put their SRTP key into the SDP as an a=crypto line
(SDES). rtpflux reads the offerer’s key and generates its own key for each
side.
Supported suites:
| Suite | Notes |
|---|---|
AES_CM_128_HMAC_SHA1_80 | The most common |
AES_CM_128_HMAC_SHA1_32 | Shorter authentication tag |
AES_256_CM_HMAC_SHA1_80, AES_256_CM_HMAC_SHA1_32 | 256-bit keys (RFC 6188) |
AEAD_AES_128_GCM, AEAD_AES_256_GCM | AES-GCM (RFC 7714) |
The relay uses the first usable a=crypto line: a supported suite with
one key and no MKI. Towards an answerer it offers SDES to, it offers
every suite, the offerer’s first (AES_CM_128_HMAC_SHA1_80 for a plain
offerer), each with its own key and tag, so that the answerer can take
one it supports; the relay then uses its key of the suite answered (a
re-offer after that offers that suite only, with the same key). The
SDES option (no-<suite>, only-<suite>; see
Options) narrows both what is offered and
which of the offerer’s lines is used. By default, lines with session
parameters (UNENCRYPTED_SRTP, UNAUTHENTICATED_SRTP, …) are not used,
as the reference model the relay is checked against specifies. When the
proxy asks for them (SDES values unencrypted_srtp,
unencrypted_srtcp, unauthenticated_srtp), the relay offers the
answerer AES-CM suites declaring them (AEAD suites cannot leave anything
out), accepts lines declaring them from either side, and protects
accordingly: payloads in clear but still authenticated, SRTCP with E = 0,
or RTP without a tag (no integrity at all: only for testing or trusted
networks). Packets that fail authentication, or replay an earlier
packet, are dropped and counted (rtpflux_srtp_rejected_total).
Opportunistic SRTP
An offer in a plain profile (RTP/AVP) may still carry a=crypto lines
(RFC 8643): SRTP if the answerer can, plain RTP otherwise. The relay
passes such an offer on with its own key; when the answerer answers with
a key, both sides use SRTP (each under its own keys), and the offerer is
answered with the relay’s key; otherwise both stay plain. Nothing is
encrypted before the answer agrees it. The OSRTP option makes a plain
offer opportunistic towards the answerer (offer), or takes the
offerer’s SRTP even when the answerer stays plain (accept).
DTLS-SRTP (WebRTC)
Browsers agree their SRTP keys with a DTLS handshake on the media port instead. rtpflux takes part in that handshake on each side that uses it:
- It has its own self-signed certificate (ECDSA P-256, generated at start, valid for 400 days from a day before). Its SHA-256 fingerprint goes into the SDP.
- It speaks DTLS 1.2 (the version WebRTC browsers use with each other), with the ECDHE-ECDSA AES-GCM and ChaCha20-Poly1305 cipher suites.
- It checks the peer’s certificate against the peer’s
a=fingerprint. There is no certificate-authority check; the fingerprint is what matters, as in WebRTC. - It takes the DTLS role the
a=setupexchange gives it. It answers anactpassoffer as the server (passive), and offersactpassitself. TheDTLSoption changes that:passiveoractivein what it offers (an answer that does not fit is refused, RFC 4145), and in its answer to anactpassofferer. - For SRTP it prefers
AEAD_AES_256_GCM, thenAEAD_AES_128_GCM, thenAES_CM_128_HMAC_SHA1_80. (AES_CM_128_HMAC_SHA1_32is available with SDES keys only.)
Bridging WebRTC and SIP phones
Because each side is handled separately, a browser can call a desk phone.
Ask for plain RTP towards the phone with
transport-protocol: RTP/AVP (in Kamailio, the RTP/AVP flag):
Browser ── DTLS-SRTP, ICE, rtcp-mux, BUNDLE ──► rtpflux ── plain RTP ──► desk phone
The other profiles work too: RTP/SAVP gives the phone SDES-SRTP, and
UDP/TLS/RTP/SAVPF offers DTLS-SRTP to a phone that only spoke SDES. If
the two sides also use different codecs, see
Transcoding.
ZRTP (end-to-end keys)
Some softphones (Linphone, Jitsi, Zoiper, Acrobits and others) agree on their SRTP keys with ZRTP (RFC 6189): a Diffie-Hellman exchange inside the media stream, verified by a short string the users can read to each other. The keys never appear in the SIP messages, so neither the proxies nor the relay can read the call.
ZRTP packets share the RTP port and start with a byte from 16 to 19 (RFC 7983). rtpflux treats them by call:
- Plain relaying (no SRTP terminated by the relay, no transcoding, no
BUNDLE): ZRTP packets are forwarded as they are, on the same path as the
RTP, and the SDP’s
a=zrtp-hashlines are kept. The phones encrypt end to end through the relay, which only sees ciphertext. - The relay changes the media (it holds SDES or DTLS-SRTP keys on
either side, transcodes, or sorts a BUNDLE group): end-to-end keys cannot
cover media the relay decrypts or rewrites, so ZRTP packets are dropped
and
a=zrtp-hashis removed from the SDP. The phones see that ZRTP is not available rather than failing half-way.
Forwarded ZRTP packets are counted in rtpflux_zrtp_forwarded_total.
Recording a ZRTP call stores the encrypted audio, which cannot be
converted.
Fax (T.38)
A T.38 fax call usually starts as audio and is re-INVITEd to an image
stream: m=image <port> udptl t38. rtpflux relays it like any other
section: the SDP gets the relay’s address and ports (the a=T38…
attributes are kept), and every UDPTL datagram is forwarded as it is,
after latching. A section in any transport rtpflux does not read as RTP
is handled the same way. It does not convert between T.38 and G.711 fax
(no fax gateway): both ends must speak T.38.
ICE
Browsers will not send media until ICE connectivity checks succeed, and many SIP phones use ICE too. Towards an endpoint that uses ICE, rtpflux is a full ICE agent (RFC 8445) by default:
- It puts its own credentials and candidates (its interface address,
typ host, and with[ice] stun_serverits public address,typ srflx) in the SDP, witha=ice-options:ice2anda=end-of-candidates; the endpoint’s candidates are removed (they would steer media around the relay). - It reads the endpoint’s candidates and checks them itself, paced every
pacing_ms(Ta), with retransmissions; it answers the endpoint’s checks, and learns addresses it did not announce from them (peer-reflexive candidates). - Towards the offerer it is the controlled agent (the offerer nominates the pair), unless the offerer is ICE-lite; towards the answerer it offered to, it is the controlling one: it nominates the best pair that works. Role conflicts are resolved as RFC 8445 §7.3.1.1 says.
- Media goes only to a pair whose check succeeded: the nominated one, or, until there is one, the best that works. Before any pair works, media towards that endpoint is held back, and so is a DTLS handshake the relay starts.
- Consent freshness (RFC 7675): the relay checks the pair it sends to
every 4–6 seconds; with no answer for 30 seconds it stops sending to it
for good (counted in
rtpflux_ice_consent_lost_total), until an ICE restart. - ICE restarts: an endpoint that re-offers with a new
ice-ufragandice-pwdrestarts ICE (RFC 8839 §4.4.1.1.1); the relay answers with new credentials too and checks again, while media keeps going to the old pair until a new one works. - Trickle ICE (RFC 8838, RFC 8840): candidates an endpoint sends later,
in an
application/trickle-ice-sdpfragbody (a SIP INFO), reach the relay throughofferwith thefragmentflag; see Trickle ICE. When the endpoint trickles, the relay’s SDP saysa=ice-options:trickle ice2. The relay itself never trickles: all its candidates are in its SDP.
As an ICE-lite agent instead ([ice] mode = "lite", or ICE-lite per
call), the relay only answers checks and sends media to the address they
come from, as servers with a public address traditionally do. The SDP then
says a=ice-lite.
By default the relay uses ICE towards both sides when the offerer does,
except when a WebRTC offer (DTLS-SRTP) is bridged to a SIP profile with
transport-protocol (RTP/AVP, RTP/SAVP, …): the phone then gets
plain SIP media without ICE attributes, while the browser keeps ICE.
The ICE option changes that (remove or force); see
Options.
Packet time (ptime)
With the ptime option (and ptime-reverse) the relay repacketises: it
regroups the audio of G.711, G.722 and G.729 into packets of another
duration, joining several into one or cutting one into several. Opus
cannot be cut: it is decoded and encoded again, in packets of one Opus
frame (the longest of 10, 20, 40 or 60 ms not over the packet time). A
packet made from several goes out when the last arrives; the parts of a
cut packet go out one packet time apart. Sequence numbers are the
relay’s own, timestamps follow the audio, and telephone events and
comfort noise pass in order. A gap in the stream (a lost packet, a new
talkspurt) sends what is held as a shorter packet. Calls that are
repacketised stay off the XDP fast path. See
Options.
rtcp-mux
With rtcp-mux, RTCP travels on the RTP port. The relay uses it on a
stream when the offerer offers it and the answerer accepts it. Otherwise
RTCP keeps its own port on both sides. A bundled side (see below) always
uses rtcp-mux, whatever the other side does.
Each side can differ: the relay joins and splits RTCP between the two
forms. The rtcp-mux option (rtpengine’s values) chooses:
| Value | Towards the offerer | Offered to the answerer |
|---|---|---|
| (none) | if offered and the answerer accepts | if the offerer offered it |
offer | if offered and the answerer accepts | always |
require | if offered | always, without an RTCP port, and the answerer is taken to accept |
demux | if offered | never |
accept | if offered | if the offerer offered it |
reject | never | never |
The answerer uses it when it was offered it and accepts. With require
(meant for WebRTC clients, against RFC 5761) the answerer is offered no
separate RTCP port, and the relay multiplexes towards it from the start,
whatever its answer says.
BUNDLE
Browsers usually send audio and video on one port (BUNDLE). The relay accepts this from the offerer:
- All bundled sections share one relay port, one ICE session and one DTLS handshake.
- Arriving packets are sorted back into their streams: RTP by payload type, RTCP by the sender’s SSRC.
- The answerer (typically a SIP phone) is offered an ordinary port per stream, without BUNDLE.
bundle-onlysections (the browser’smax-bundlepolicy) are supported.
With SDES-SRTP, each bundled section keeps its own key. With DTLS, they share the keys of the one handshake.
Re-INVITEs and hold
A call can change after it starts. Each new offer in the same dialog (a
re-INVITE) goes through offer and answer again. rtpflux keeps
everything that does not need to change:
- Same ports and keys. The relay’s ports and its SRTP keys towards each side stay. A party that did not move sees no change.
- Either party may re-INVITE. When the callee re-offers (its tag in
from-tag), the relay swaps the roles for that exchange.queryanddeleteaccept either party’s tag. - Streams on their own. Without BUNDLE, a re-offer can disable one
stream (port
0), add a new one, or bring a disabled one back. The other streams are not touched. - Hold and resume.
a=sendonly,a=recvonly,a=inactiveand the olderc=0.0.0.0hold all pass through. The relay never sends media to0.0.0.0. - BUNDLE and re-INVITEs. When a SIP phone re-INVITEs a bundled browser, the browser is offered its BUNDLE group again on the same shared port, and the phone keeps a port per stream. A bundled re-offer from the party that did not bundle at first is refused with an error (the relay can bundle only one side of a call), and the call continues unchanged.
IPv6
Interfaces can have IPv6 addresses, and the XDP fast path handles IPv6 as well as IPv4.
Without direction, an offer is handled on the first interface of the
offerer’s address family, so with one IPv4 and one IPv6 interface both
kinds of caller work. To bridge the two families (an IPv4 phone and an
IPv6 one, a carrier’s IPv6 core), the address-family option (IP4 or
IP6) puts the answerer’s side on the first interface of that family:
each side gets SDP of its own family (c= and o=), and the relay
carries the media between them. Naming the two interfaces in
direction does the same. media-address writes another address into
the SDP than the interface’s (of the same family), as advertise does
per interface.
Call features
Besides relaying media, rtpflux can detect key presses, mute participants, record calls, play announcements, convert codecs and report call quality. The SIP proxy triggers each feature with an ng command; see Control protocol for the message format.
Calls with DTMF detection, blocking, an announcement or recording can stay in the XDP fast path: the kernel drops what is blocked, sends telephone events up to the relay, and copies recorded packets to it. Transcoding is done in userspace, so a call that uses it leaves the fast path.
DTMF detection
When a side offers telephone events (a=rtpmap:101 telephone-event/8000
in its SDP), rtpflux watches its key presses (RFC 4733 DTMF events).
Each key press is reported once, when it ends. The end is signalled by
the event’s end flag, the next key press, ordinary audio, or silence for
three packet intervals. Retransmitted and duplicate event packets are
recognised and not counted again.
Each key press is logged:
INFO rtpflux::relay::worker: dtmf: slot 0: '5' (160 ms)
and listed by query under the stream that sent it:
DTMF:
- { event: "5", timestamp: 3200, duration: 160 } # duration in ms
- { event: "#", timestamp: 8000, duration: 120 }
Events are passed on to the other side unchanged (unless blocked, below).
Blocking media and DTMF
Mute a participant without ending the call:
| Command | Effect |
|---|---|
block media | Stop relaying everything this participant sends (audio, video and its DTMF) |
unblock media | Relay it again |
block DTMF | Stop relaying only its key presses; audio still flows |
unblock DTMF | Relay its key presses again |
Name the participant with from-tag (either party’s tag). Without
from-tag, the whole call is affected.
Example: a PIN prompt. An IVR asks the caller for a PIN. To keep the
PIN away from the agent’s phone, block the caller’s DTMF towards the
agent. Blocked key presses are still detected and listed by query.
command: block DTMF
call-id: call-1@example.com
from-tag: alice-tag
Blocked media is still received, counted in the statistics and checked for DTMF; it is just not forwarded. RTCP is never blocked, so quality reports keep flowing.
DTMF security
block DTMF can do more than drop key presses (rtpengine’s
DTMF-security). The keys a participant presses, as telephone events or
as in-band tones in its audio, can be:
DTMF-security | What the other party gets for each key |
|---|---|
drop (the default) | Nothing: telephone events are dropped (in-band tones pass) |
silence | Silence in its audio while the key is held |
tone | A sine tone (frequency, Hz, default 400) while the key is held |
zero | Key 0 instead |
DTMF | The key digit (or code) names instead (0-9 * # A-D) |
random | Another key, a random one (never the key itself, so it tells nothing of it) |
off | The key itself |
A telephone event’s key is rewritten in place (zero, DTMF,
random), or the event is dropped and the replacement played in the
listener’s audio. An in-band key is found in the audio (G.711 as it is;
G.722, G.729, Opus and AMR decoded) and, while it is held, the
replacement is played instead of the participant’s audio. Finding a tone
takes a frame or two, so its first tens of milliseconds pass. Replacements
are at volume (dB below 0 dBm0, default 10). Detected keys are still
listed by query as they were pressed.
Triggers. With trigger (a key sequence such as *1), nothing is
blocked until the participant presses it; then DTMF-security-trigger
applies (default drop). It ends with the key sequence trigger-end, or
after trigger-end-time milliseconds or trigger-end-digits more keys,
switching to DTMF-security-trigger-end (default off); then the trigger
is watched for again. Keys more than 2.5 s apart start a sequence afresh.
command: block DTMF
call-id: call-1@example.com
from-tag: alice-tag
trigger: "*1"
DTMF-security-trigger: random
trigger-end-digits: 16
Delay. DTMF-delay (milliseconds, at most 10 000), on block DTMF
or on the offer or answer of the participant, makes its keys reach the
other party that much later: telephone events are held back and sent
again later (as events if the other party takes them, else as tones in
its audio). An in-band key is replaced by silence while it is held and
played after the delay (or as soon as it is over, if it lasts longer than
the delay). Keys waiting for their delay are kept in a small fixed queue
(eight keys); more are dropped and counted.
unblock DTMF ends DTMF security as well. Calls with DTMF security stay
in userspace (off the XDP fast path). The settings are kept across a
restart.
Silencing (silence media, unsilence media) is the gentler form:
the participant’s packets keep flowing with their sequence numbers and
timestamps, but G.711 audio is replaced by silence, so the other phone
does not see the stream stop. Audio in other codecs is held back (there is
no silent payload to put in without encoding it), and telephone events
still pass. A silenced call stays out of the XDP fast path while silenced.
DTMF transcoding
When one side sends DTMF as telephone events (RFC 4733) and the other only as tones in its audio, rtpflux converts between them, as rtpengine does:
- The offerer has no telephone events: with
codec: {transcode: ["telephone-event"]}(or the flagcodec-transcode-telephone-event), rtpflux offers them to the answerer. If it accepts them, its key presses reach the offerer as tones, and tones in the offerer’s audio reach the answerer as events. The offerer never sees the events in the SDP. An answer that takes the events under another payload type than the one offered gets no conversion (and the offerer’s own formats are never touched). - The answerer refuses the offerer’s telephone events: with the flag
always transcode, rtpflux keeps them towards the offerer anyway; its events reach the answerer as tones, and the answerer’s tones reach it as events.
Tones are played and detected in the parties’ audio: G.711 (μ-law or
A-law) as it is, or G.722, G.729, Opus (and AMR with the amr build),
which the relay decodes to look for tones and encodes to play them. A key
lasts as long as the sender holds it: the tones while the events go on,
the events while the tones do (detected 20 ms frame by 20 ms frame, a key
needing two frames to start and two to end). While a key is converted the
sender’s own audio towards the other side is held back. Detected keys are
reported by query as usual.
Sending DTMF
play DTMF sends key presses to a party, for example to drive an IVR or a
voicemail system on behalf of the other side:
command: play DTMF
call-id: call-1@example.com
from-tag: alice-tag # Alice "presses"; Bob hears it
code: 1234#
duration: 200
- If Bob negotiated
telephone-event, he gets RFC 4733 events: one per key, the marker bit on its first packet, a packet every 20 ms with the duration so far, and three end packets. - Otherwise Bob’s phone gets the keys as tones (the two ITU-T Q.23 frequencies) in
the audio it receives: G.711 as it is, or G.722, G.729, Opus (and AMR
with the
amrbuild) encoded by the relay. - While the keys play, Alice’s own audio to Bob is held back, as for an announcement; the keys go out on the relay’s own RTP stream towards Bob (encrypted if Bob uses SRTP).
- An announcement playing to Bob must end first (the request is refused otherwise).
Recording
start recording records every packet of a call. When the recording
ends, rtpflux can turn it into an audio file in the format you choose,
stereo or mono.
What you get
For each media section of the call, in [recording] dir:
<call-id>-<from-tag>-<section>.pcap the packets, as recorded
<call-id>-<from-tag>-<section>.wav the audio (or .flac, .opus, .mp3)
<call-id>-<from-tag>-<section>.json what was recorded
In the Call-ID and tag, characters other than letters, digits and
. - _ @ become _, and each is cut to 128 characters. The name is the
default of [recording] file_name, which can put the date, time or
to-tag in it instead (see Configuration).
The proxy can choose per call (in start recording, or in an offer or
answer with record-call), as with rtpengine:
| Option | What |
|---|---|
recording-path | A subdirectory of [recording] dir, made if missing: acme/agents. Up to 4 levels of plain names (letters, digits, . - _ @, none starting with .); never outside the directory, never through a link. |
recording-file, output-destination | A fixed name for this call’s files: call-42 (an extension such as .wav is dropped; a leading dir/ is a subdirectory, as above). Another section or a later recording gets -2, -3. |
recording-pattern | A file-name template for this call, as [recording] file_name. |
Anything else is refused with the reason. Recordings in subdirectories
are listed in the web UI by their path, and uploaded to S3 under it
(prefix + acme/agents/call-42.wav).
Recording metadata
Each audio file carries tags: TITLE (the call-id and section),
CALL_ID, FROM_TAG, TO_TAG, SECTION, DATE (when the recording
started, UTC) and the encoder, plus your own:
[recording.metadata] # in every recording
company = "Example Ltd"
command: start recording
call-id: call-1@example.com
metadata: { agent: "Jane Doe", queue: "support", ticket: "4711" }
The tags go where players and tools read them: Vorbis comments in FLAC
and Ogg Opus (AGENT=Jane Doe), an ID3v2.4 tag in MP3 (TXXX frames,
with TIT2, TDRC, TSSE), and in WAV the LIST/INFO chunk: title
(INAM), date (ICRD), software (ISFT), and every tag as
NAME=value lines in the comment (ICMT), as INFO has no free names.
ffprobe, metaflac, exiftool and most players show them. The JSON
file has them under metadata. They are kept across restarts.
Keys are letters, digits, _, - and . (up to 64), upper-cased in
the audio tags; values are up to 1024 octets; a recording has at most
32. A request’s own keys override the configured ones. Invalid metadata
is refused with the reason, and the recording does not start.
| Format | What it is | Good for |
|---|---|---|
pcap (default) | The packets themselves; no audio file | Troubleshooting with Wireshark |
wav | 16-bit PCM | Anything; largest files |
flac | Lossless, about half the size of WAV | Archiving |
opus | Ogg Opus at the bitrate you choose | Small files for speech |
mp3 | MP3 at the bitrate you choose | Players everywhere; needs a build with the mp3 feature |
- Stereo puts the caller (the party that sent the first offer) on the left and the callee on the right. Mono mixes both.
- Sample rate: 8000, 16000, 24000 or 48000 Hz. G.711 calls carry 8 kHz audio, so 8000 loses nothing; choose 16000 or more for Opus calls from browsers.
- Bitrate (Opus and MP3), in kbit/s: Opus takes 6 to 510, MP3 one of 8, 16, 24, 32, 40, 48, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320.
The .json file describes the recording:
{
"call_id": "call-1@example.com",
"from_tag": "alice-tag",
"to_tag": "bob-tag",
"section": 1,
"left_port": 30000,
"opus_pts": [],
"file": "call-1@example.com-alice-tag-1.wav",
"format": "wav",
"channels": "stereo",
"sample_rate": 16000,
"started_ms": 1795509703000,
"duration_ms": 62340,
"caller": { "packets": 3117, "lost": 0, "streams": 1 },
"callee": { "packets": 3115, "lost": 2, "streams": 1 }
}
Choosing the format
Set the default in the configuration:
[recording]
dir = "/var/spool/rtpflux"
format = "flac" # pcap, wav, flac, opus or mp3
channels = "stereo" # or mono
sample_rate = 16000
bitrate = 32 # kbit/s, for opus and mp3
keep_pcap = false # keep the packets once converted
and override any of it per call in start recording:
command: start recording
call-id: call-1@example.com
format: opus
channels: mono
sample-rate: 16000
bitrate: 24
keep-pcap: yes
Wrong values are refused with a clear error, such as
sample_rate 44100: one of [8000, 16000, 24000, 48000] is needed.
How the audio is made
The conversion runs on a background thread when the recording ends:
stop recording, the call deleted, or the call timing out. It never runs
on the threads that relay media.
- Each party’s packets are placed by their RTP timestamps, starting from when their first packet arrived. Jitter does not stretch the audio, reordered and duplicated packets are handled, and lost packets leave silence.
- Each packet is recorded as its sender sent it: after SRTP decryption, before transcoding or blocking. G.711 (PCMU, PCMA) and Opus are decoded; telephone events, comfort noise and other codecs are left out of the audio.
- The audio file appears when it is complete (it is written under a temporary name first), usually a moment after the call ends.
- The pcap is removed after a successful conversion, unless
keep_pcapis set. If a conversion fails, the pcap always stays, and the reason is logged. A section without audio rtpflux decodes (G.711, G.722, G.729, Opus, and AMR with theamrfeature; not a video stream, for example) is not converted; its pcap is kept. Wideband audio (G.722, AMR-WB) keeps its band at 16 and 48 kHz outputs; at 8 and 24 kHz it goes through 8 kHz. - If rtpflux stops while a call is being recorded, its pcap is kept. With a state file or Redis, the recording continues after the restart and is converted once, from the whole recording, when it ends (so stopping is not held up by conversions). Without one the call does not come back, so the recording is converted as rtpflux stops.
- A call encrypted end to end with ZRTP (the phones’ own keys, which the relay never has) is not converted: its pcap, with the ZRTP handshake in it, is kept, and the log says why.
- Audio files left half written (
*.part) by a crash are removed when rtpflux starts.
Storing recordings in S3
By default recordings stay on the local filesystem, in [recording] dir.
With storage = "s3", each finished recording’s files (the audio file,
its .json, and the pcap when it is kept) are uploaded to an S3 bucket,
then removed from the local directory:
[recording]
dir = "/var/spool/rtpflux" # still needed: files are made here first
format = "opus"
storage = "s3"
[recording.s3]
bucket = "call-recordings"
region = "eu-west-1"
prefix = "rtpflux/" # object keys: rtpflux/<call-id>-<tag>-<n>.opus
export AWS_ACCESS_KEY_ID=...
export AWS_SECRET_ACCESS_KEY=...
rtpflux -c rtpflux.toml
- Credentials come from the environment:
AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY, andAWS_SESSION_TOKENfor temporary credentials. They are never read from the configuration file. Without them the relay does not start, and says why. - S3-compatible servers (MinIO, Ceph, Cloudflare R2, versitygw, …):
set
endpointto the server’s URL and usuallypath_style = true. - Failures: each file is tried three times. A file that still cannot be uploaded stays in the local directory, and the error is logged.
keep_local = trueuploads and also keeps the local copies.- A recording interrupted because rtpflux stopped is uploaded when it finally ends, after the restart.
- S3 storage needs a build with the
s3feature (cargo build --release --features s3); the Docker image has it.
Upload notifications (webhook)
With a [recording.s3.webhook] section, the relay sends an HTTP POST
after each finished recording is uploaded, so another system (a CRM, a
transcription pipeline) can fetch it without listing the bucket:
[recording.s3.webhook]
url = "https://hooks.example.com/recordings"
timeout_ms = 5000 # each attempt's deadline, DNS to response (100–60000)
connect_timeout_ms = 2000 # connecting (100–timeout_ms)
attempts = 5 # 1–20
backoff_ms = 1000 # before the first retry, doubled after it
backoff_max_ms = 30000 # the longest wait, Retry-After included
queue = 1000 # notifications waiting to be sent
The body is JSON:
{
"event": "recording.uploaded",
"delivery": "5f0c…",
"uploaded_ms": 1795509703120,
"call_id": "a84b4c76e66710@pc33",
"from_tag": "1928301774",
"to_tag": "a6c85cf",
"section": 1,
"metadata": { "company": "Example Ltd" },
"bucket": "call-recordings",
"files": [
{ "key": "rtpflux/a84b4c76e66710@pc33-1928301774-1.opus",
"url": "https://call-recordings.s3.eu-west-1.amazonaws.com/rtpflux/…opus",
"content_type": "audio/ogg", "size": 412733 },
{ "key": "rtpflux/…-1.json", "url": "…", "content_type": "application/json", "size": 911 }
],
"complete": true
}
complete is false when a file could not be uploaded; not_uploaded
then names it (it stays in the local directory). No notification is sent
when nothing was uploaded. The urls are not presigned: the receiver
needs its own access to the bucket.
-
Delivery runs on a thread of its own, from a queue of
queuenotifications, so a slow or unreachable receiver never holds up the next recording. When the queue is full, a notification is dropped and logged. -
Retries: timeouts, connection errors,
5xx,408and429are retried up toattemptstimes in all. The waits double frombackoff_msup tobackoff_max_ms, each jittered (half of it plus up to half at random), and are at least what aRetry-Afterheader asks for (in seconds), but never more thanbackoff_max_ms. Any other status (2xxis success;3xxand other4xx) is final: redirects are not followed. -
Timeouts: every attempt ends by
timeout_ms, everything from resolving the host to the response’s headers included, andconnect_timeout_mslimits connecting. The response body is not read, and response headers over 16 KiB end the attempt. -
Stopping: when rtpflux stops, queued notifications get one attempt each, for at most twice
timeout_msin all. What is left is dropped, and how many is logged. -
Headers:
Content-Type: application/json,X-Rtpflux-Event: recording.uploaded,X-Rtpflux-Delivery(thedeliveryid: drop repeats of it, since a retry after a lost response arrives twice) andX-Rtpflux-Timestamp(Unix seconds). -
Signing: with
RTPFLUX_WEBHOOK_SECRETset in the environment (never in the configuration file), each request also carriesX-Rtpflux-Signature: sha256=<hex>, the HMAC-SHA256 of<X-Rtpflux-Timestamp>.<raw body>keyed with the secret. Check it in constant time, and refuse old timestamps, so a captured request cannot be replayed:import hashlib, hmac, time def valid(secret: bytes, headers, body: bytes) -> bool: ts = headers["X-Rtpflux-Timestamp"] want = "sha256=" + hmac.new(secret, f"{ts}.".encode() + body, hashlib.sha256).hexdigest() return hmac.compare_digest(want, headers["X-Rtpflux-Signature"]) and abs(time.time() - int(ts)) < 300 -
Logs name the receiver by scheme, host and path only: a token in the URL’s query or credentials stays out of them.
-
Watching it: the web UI’s Recordings page lists the last 200 uploads and webhook deliveries, and
/metricscounts them (rtpflux_recording_uploads_total,…_upload_failures_total,…_webhooks_delivered_total,…_webhooks_failed_total,…_webhooks_dropped_total); see Operations.
open it in Wireshark and use Telephony → RTP → RTP Streams.
Announcements
play media plays an audio file to one participant, for example “please
hold” or “this call is recorded”:
command: play media
call-id: call-1@example.com
from-tag: bob-tag # who hears it
file: /usr/share/rtpflux/hold.wav
repeat-times: 3
- File format: MP3, FLAC or WAV. WAV at 8 kHz mono (16-bit PCM,
A-law or μ-law) is played as it is; anything else is decoded, mixed down
to mono and resampled to 8 kHz (filtered to the telephone band, so
nothing above it folds back). Converting ahead, for example with
sox in.mp3 -r 8000 -c 1 -b 16 out.wav, saves that work per play. - The file must be a regular file (not a device or a pipe) of at most 64 MiB, about 35 minutes of 16-bit audio.
- The relay converts the audio to the G.711 law the listener receives and sends it in 20 ms packets with its own SSRC. Later announcements to the same participant continue that stream (same SSRC, sequence numbers going on), as SRTP requires. It encrypts them when the listener uses SRTP.
- While the announcement plays, the other party’s audio to the listener is held back, so the two do not mix.
stop mediaends it early. Withoutfrom-tag, every announcement in the call stops.- The listener must receive PCMU or PCMA. A participant who receives only Opus cannot be played to yet.
- After a restart, an announcement resumes where it would have been. It is not restarted if it would already have finished.
Transcoding
When the two parties have no codec in common, the relay can convert between them. Any of these converts to any other:
| Codec | Payload type | Audio | Implementation |
|---|---|---|---|
| PCMU, PCMA (G.711) | 0, 8 | 8 kHz | Built in. Between the two laws, a table lookup per sample |
| G.722 | 9 | 16 kHz (RTP clock 8000 Hz) | Built in (the public-domain reference algorithm, 64 kbit/s) |
| G.729, with Annex B | 18 | 8 kHz, 10 ms frames | g729-sys, a Rust port of bcg729 (GPL-3.0) |
| Opus | dynamic (111) | 8 or 16 kHz, matching the other side; 24 or 32 kbit/s | opus-rs |
| AMR, AMR-WB | dynamic | 8 / 16 kHz, 20 ms frames, 12.2 / 12.65 kbit/s | amr-nb / amr-wb, ports of opencore-amr; only in a build with the amr feature |
Between codecs of different audio rates (G.711 and G.722, for example), the audio is resampled between 8 and 16 kHz. Opus takes the other side’s rate, so G.722 to Opus stays wideband.
Ask for transcoding in the offer with the codec option (or flags):
codec: { transcode: ["PCMU"] } # or flags: ["codec-transcode-PCMU"]
rtpflux adds that codec to the offer it sends to the answerer, keeping the offerer’s codecs too. Then:
- If the answerer picks a codec the offerer also has, nothing is converted.
- If the answerer picks the codec only the relay offered, the relay converts both ways. The offerer is answered with its own codec and never knows.
To force conversion, also withhold the offerer’s codec from the
answerer with mask:
codec: { transcode: ["PCMA"], mask: ["PCMU"] }
Example: a browser calling an old PBX. The browser offers only Opus;
the PBX speaks only PCMU. The proxy sends the offer with
transport-protocol: RTP/AVP and codec-transcode-PCMU:
browser offer: m=audio 9 UDP/TLS/RTP/SAVPF 111
a=rtpmap:111 opus/48000/2
relay's offer to PBX: m=audio 30002 RTP/AVP 111 0
a=rtpmap:111 opus/48000/2
a=rtpmap:0 PCMU/8000
PBX answer: m=audio 50000 RTP/AVP 0
relay's answer to the browser: Opus (payload type 111)
The browser sends Opus and the PBX receives PCMU, and the other way round.
Details:
- When the relay adds Opus or AMR, it uses payload type 111, or the first free dynamic number if the offer already uses 111. G.722 and G.729 keep their static numbers.
- Every codec is converted packet by packet, with the same packet length (a 20 ms packet stays 20 ms): G.729 needs a multiple of 10 ms, AMR of 20 ms, and other lengths are dropped.
- G.729 is sent without voice activity detection (every frame is voice), which suits a peer with or without Annex B; its SID frames are decoded into comfort noise.
- AMR is transcoded only in the octet-aligned packing: the relay offers
a=fmtp:<pt> octet-align=1, and an offerer’s AMR counts only withoctet-align=1and amode-setthat includes 12.2 kbit/s (AMR-WB: 12.65 kbit/s), the modes the relay sends. AMR packets take one small allocation each to pack; the other codecs none. Check AMR’s patent situation where you use it: that is why it is off by default. - Opus is converted packet by packet. A G.711 packet of an Opus frame length (2.5, 5, 10, 20, 40 or 60 ms; 20 ms is the usual one) becomes one Opus frame; other lengths that split into equal frames, such as 30 ms, become one Opus packet of several frames (three of 10 ms). Up to 120 ms per packet; anything else is dropped.
- Timestamps are scaled between the RTP clocks (Opus 48 kHz, AMR-WB 16 kHz, the others 8 kHz, G.722 included). Sequence numbers and SSRCs are kept.
- Telephone events (DTMF) and RTCP are passed through unconverted.
RTCP statistics
Endpoints send RTCP reports about the media they receive. rtpflux reads
the reports it relays (after SRTCP decryption) and shows the latest one
per stream in query:
RTCP:
reports: 14 # reports seen
SSRC: 3735928559 # who sent them
sender packets: 1480 # from the last sender report, if any
sender octets: 236800
reported SSRC: 1234567 # the stream the report is about
fraction lost: 3 # out of 256, since the previous report
packets lost: 21 # in total (can be negative: duplicates)
highest sequence: 71480
jitter: 9 # in RTP timestamp units
RTT: 38 # round-trip time, ms
Round-trip time. When a sender report from one side is answered by a
receiver report from the other, the relay works out how long the round
trip took (RFC 3550, section 6.4.1). It is the time between the relay
forwarding the sender report and receiving the reply, minus the delay the
other side reported. RTT is shown once such a pair has been seen.
XDP fast path
Normally every media packet travels from the network card up to the rtpflux process and back down again. For simple calls, rtpflux can instead load a small program into the network driver with XDP (eXpress Data Path). That program rewrites and forwards the call’s packets itself, so they never reach userspace. This saves most of the CPU time a relay spends per packet.
In a benchmark with 4,000 calls (400,000 packets per second), the relay process used 7% of one CPU with the fast path and 400% without it. See Benchmarks.
Which calls use it
A call moves into the kernel once both directions are settled: the relay knows where each side’s media comes from and where to send it. Until then, and for any call the fast path cannot handle, packets go through userspace as usual.
The fast path handles plain RTP only. A call stays in userspace if it:
- uses SRTP or DTLS-SRTP (encryption is not done in the kernel);
- uses BUNDLE;
- has transcoding active;
- mixes IPv4 and IPv6 between its two sides.
If a call starts one of these features later (for example a re-INVITE that needs transcoding), it is taken out of the kernel again. The relay can still receive such calls through AF_XDP, skipping most of the kernel’s network stack.
Other features keep the call in the kernel and change what the program does with one side’s packets:
- DTMF detection. Telephone events (RFC 4733: packets with the side’s telephone-event payload type) go up to the relay, which detects the digits and forwards the events itself. The audio stays in the kernel.
- Blocking media (
block media). The kernel drops the side’s packets. They are still counted, so the media timeout does not end the call. - Blocking DTMF (
block DTMF). The events go up to the relay, which drops them; the audio stays in the kernel. - Announcements (
play media). While an announcement plays to one side, the kernel drops the other side’s media towards it. The relay sends the announcement. When it ends, forwarding resumes. - Recording (
start recording). The kernel copies each datagram’s payload (up to 1,504 octets) into a ring buffer shared with the relay, then relays it as usual. The relay reads the ring every 10 ms while a recorded call is in the kernel and writes the packets into the call’s recording, with the time the kernel received them. The ring holds about 2,700 packets; if it fills up, the kernel skips the copies (the packets are still relayed) and the recording has gaps.
These changes take effect while the call stays in the kernel: the relay updates the call’s flows, it does not remove them.
What the program does with each packet:
- Same network device: the packet is rewritten (addresses, ports,
checksums) and sent straight back out of the card it arrived on
(
XDP_TX). - Another device: when the two sides of a call use different
interfaces, the packet is sent out of the other device
(
XDP_REDIRECT). Both devices must be listed in[xdp] devices. - Anything else (unknown flows, STUN, DTLS, RTCP of other calls, malformed packets) is passed up to the kernel’s network stack and the relay as if XDP were not there.
The kernel counts each forwarded flow’s packets. The relay reads these
counters, so query shows correct statistics and the media timeout does
not end calls that are busy in the kernel.
Supported traffic
- IPv4 and IPv6 UDP.
- For IPv6, only packets with UDP directly after the fixed header (no extension headers) and a non-zero UDP checksum. IPv4-mapped addresses are not offloaded.
- The next hop’s MAC address comes from the kernel’s tables: the routing
table and ARP cache for IPv4, and the routing table and a netlink
neighbour dump for IPv6. Among equally specific routes, the one with
the lowest metric is used, as the kernel does. Policy routing
(
ip rule, routing tables other thanmain) is not followed: if you use it, check that offloaded calls leave through the right gateway. - Every 30 seconds the relay looks the next hops up again and updates the calls whose next hop’s MAC address changed (a gateway failover, a moved address), since offloaded packets never pass through the kernel’s stack to notice.
Status. IPv4 and IPv6, on one device (
XDP_TX) and across two (XDP_REDIRECT), pass the end-to-end kernel tests: real calls through virtual Ethernet pairs in generic XDP mode. The IPv4 path on one device has also been benchmarked. The per-flow flags (DTMF, blocking, announcements) and the recording ring are checked in the kernel byxdp-selfteston generated frames, not yet by end-to-end calls. Native (driver) mode on a real network card has not been tested; run the kernel tests on your hardware before relying on it.
AF_XDP for the other calls
The kernel cannot relay encrypted, WebRTC or BUNDLE calls: their keys,
DTLS handshakes and ICE checks live in the relay. With af_xdp = true
(and a build with the af-xdp cargo feature), their packets still skip
most of the kernel’s network stack on the way in:
- The relay opens one AF_XDP socket for each receive queue of the
first device in
devices. - The XDP program sends every datagram addressed to the relay’s port range on that device, which no kernel flow relays, straight to the socket of the queue it arrived on. Kernel flows (plain calls) come first and are not affected.
- A receive thread per queue checks each datagram as the kernel would (IP and UDP checksums, lengths) and hands it to the worker that owns the port. The worker handles it exactly as if its UDP socket had received it: STUN, DTLS, SRTP, BUNDLE and recording all work the same.
- Replies and relayed packets leave through the workers’ UDP sockets as before. Only the receive side changes.
If a queue has no socket, or a datagram arrives on another device, the program passes it to the kernel’s stack as usual, so nothing is lost when AF_XDP is not available.
Each queue’s socket has its own memory (8 MiB by default, see
af_xdp_frames), allocated when the relay starts and kept until it exits.
AF_XDP sockets need CAP_NET_RAW besides the XDP capabilities, and the
memory counts against the locked-memory limit: under systemd, add
CAP_NET_RAW to the unit’s capabilities, AF_XDP to
RestrictAddressFamilies, and raise LimitMEMLOCK= (the shipped unit
explains this in a comment).
When a worker falls behind, its queue of received datagrams (1,024
datagrams) fills up and the newest are dropped and counted in the
dropped statistic.
Licence. The AF_XDP sockets use the xdpilone crate, which is under the EUPL-1.2. The EUPL lists the GPL-3.0 as a compatible licence, so it can be combined with rtpflux (GPL-3.0-only). The feature is off by default and not in the Docker image because it is new and untested on real network cards.
Status. In the kernel,
xdp-selftest(built with--features af-xdp) checks the steering, including the redirect to a real AF_XDP socket on the loopback device. In userspace, tests check that frames given to the receive threads are relayed like socket traffic. The whole path has not yet carried real calls, on virtual or physical network cards, and has not been benchmarked.
Building the program
The XDP program is a separate crate, crates/rtpflux-xdp-ebpf, built
for the BPF target. It needs a nightly Rust toolchain (pinned in that
directory’s rust-toolchain.toml) and bpf-linker:
cargo binstall bpf-linker # its release binary (needs cargo-binstall)
cd crates/rtpflux-xdp-ebpf
cargo build --release
cargo install bpf-linker works too, but builds against your system’s
LLVM, which must be the version bpf-linker expects (with its development
files); the release binary carries its own. CI uses bpf-linker 0.13.0.
The result is crates/rtpflux-xdp-ebpf/target/bpfel-unknown-none/release/rtpflux-xdp.
Install it where the configuration expects it:
sudo install -D -m 644 target/bpfel-unknown-none/release/rtpflux-xdp \
/usr/lib/rtpflux/rtpflux-xdp
Enabling it
[xdp]
enabled = true
devices = ["eth0"] # every device media can arrive on or leave by
mode = "native" # "generic" works with any driver, but slower
object = "/usr/lib/rtpflux/rtpflux-xdp"
nativeruns in the network driver and is the fast option. Your driver must support XDP; most modern server NICs do.genericruns a little later in the kernel and works with any device, including virtual ones. It is useful for testing.- The kernel’s flow table holds 65,536 entries and each call needs 4, so
sessions.maxcan be at most 16,384 with XDP enabled.
Loading and attaching the program needs the capabilities CAP_BPF,
CAP_NET_ADMIN and CAP_PERFMON. The systemd unit
grants exactly these.
Testing it
Both tests need root.
xdp-selftest loads the program into the kernel without attaching it
to any device. It runs it on generated frames and compares every result
with the reference implementation in rtpflux-xdp-common: rewrites,
passes, the per-flow flags (events going up, dropping) and the copies
in the recording ring:
cargo build
sudo target/debug/xdp-selftest
scripts/xdp-e2e.sh runs real calls through the fast path in
network namespaces. It uses two virtual Ethernet pairs and covers IPv4
and IPv6, on one device and across two. It checks that calls are
offloaded once settled, keep flowing intact, stay alive on kernel-only
traffic and time out cleanly:
./scripts/xdp-e2e.sh # generic XDP
XDP_MODE=native ./scripts/xdp-e2e.sh # driver mode
The script builds as your user and calls sudo itself for the
namespaces.
Benchmarks
How fast is rtpflux, and how do we measure it?
Method
The load generator, rtpflux-bench, behaves like many phones at once.
It sets up calls over the ng protocol and sends G.711 audio: one
172-byte RTP packet every 20 ms, in both directions, so 100 packets per
second per call. It then reports:
- delivery: how many packets arrived, and the loss percentage;
- latency: one-way delay through the relay (median, 99th and 99.9th percentile);
- relay CPU: CPU time used by the relay process, in percent of one CPU;
- with the XDP fast path, also softirq and host CPU, because packets forwarded in the kernel do not show up as relay process time.
Each step runs a warm-up, then three 10-second windows, and reports the median window. The relay and the load generator are pinned to separate physical cores.
Results
Reference machine: Intel Xeon E5-1620 v3 (4 cores, 8 threads, 3.5 GHz), Linux 7.0, four relay worker threads on two physical cores, 4 load-generator threads on the other two. rtpengine 13.5.1.16 was run with the same worker count and flags.
Userspace, loopback (bench/compare.sh)
Measured on 26 November 2026 with all current features: rtpflux with each
runtime.receive (io_uring, the default, and recvmmsg), then
rtpengine. Latency is one way through the relay; CPU is the relay
process, in percent of one CPU.
| Calls | Packets/s | io_uring: p99 latency, CPU | recvmmsg: p99 latency, CPU | rtpengine: delivered, p99 latency, CPU |
|---|---|---|---|---|
| 250 | 25,000 | 0.32 ms, 101% | 0.31 ms, 110% | 100%, 0.53 ms, 144% |
| 500 | 50,000 | 0.41 ms, 171% | 0.44 ms, 186% | 100%, 0.69 ms, 259% |
| 1,000 | 100,000 | 0.36 ms, 300% | 0.50 ms, 308% | 100%, 0.84 ms, 306% |
| 2,000 | 200,000 | 0.14 ms, 294% | 0.17 ms, 302% | 100%, 0.24 ms, 374% |
| 3,000 | 300,000 | 0.12 ms, 378% | 0.11 ms, 382% | 100%, 47 ms (queueing), 400% |
| 4,000 | 400,000 | 53 ms (queueing), 400% | 50 ms (queueing), 400% | 2.6%, 2.9 ms, 55% |
rtpflux delivered every packet at every step, with either way of
receiving. At 4,000 calls it uses all four worker threads and packets
queue (a median of 35 ms with io_uring, 23 ms with recvmmsg).
rtpengine queued at 3,000 calls and dropped most packets at 4,000, from
full receive queues. io_uring used 3–8% less relay CPU than recvmmsg
up to 2,000 calls.
The SRTP and kernel fast path results below were measured earlier, at
the commits in their result files, before the newer call features and
io_uring receive.
SRTP (bench/srtp.sh)
At 2,000 calls (200,000 packets/s), with AES_CM_128_HMAC_SHA1_80:
| Mode | Delivered | Relay CPU |
|---|---|---|
| Plain RTP | 100% | 303% |
| SRTP on one side (the relay encrypts or decrypts every packet) | 100% | 287% |
| SRTP on both sides (decrypt and re-encrypt every packet) | 100% | 320% |
At this load SRTP added little relay CPU; the differences are close to the variation between runs.
Kernel fast paths (bench/fastpath.sh)
Over a virtual Ethernet pair between two network namespaces, with generic-mode XDP:
| Calls | rtpflux userspace: relay CPU | rtpflux XDP: relay CPU | rtpflux XDP: host CPU | rtpengine kernel module: host CPU |
|---|---|---|---|---|
| 1,000 | 300% | 1.9% | 242% | 425% |
| 2,000 | 304% | 3.6% | 306% | 520% |
| 4,000 | 400% | 7.3% | 365% | 723% |
All variants delivered every packet. The result file also records that rtpengine’s kernel table held 0 streams during the first step, so its kernel forwarding may not have been active in that run; treat the last column with caution. “Host CPU” counts all CPU time on the machine, including the kernel’s packet processing and the load generator. Generic XDP runs late in the kernel; native XDP on a physical NIC should do better.
Against the integration baseline
bench/baseline.sh compares HEAD with a pinned commit (BASELINE,
default cac9411, before the Ferroswitch integration work). It runs on
the same machine and configuration, alternating the two binaries over
two rounds.
The figures below are from an i9-9900K (8 cores, 16 threads) on Linux 7.0, over loopback:
- relay: 2 workers on CPUs 0,1,8,9 (two physical cores);
- load generator on 2,3,10,11;
native-benchon 4,12.
Ordinary relaying (rtpflux-bench, G.711 both ways, 10 s windows,
no loss in any run). Each cell is round 1 / round 2:
| Load | Baseline: p50 / p99 µs | Baseline: relay CPU % | HEAD: p50 / p99 µs | HEAD: relay CPU % |
|---|---|---|---|---|
| 500 calls, plain | 93 / 184, 87 / 220 | 38.5, 37.1 | 97 / 189, 94 / 188 | 38.8, 38.5 |
| 1000 calls, plain | 146 / 344, 216 / 354 | 63.1, 71.9 | 157 / 348, 134 / 342 | 66.4, 60.4 |
| 500 calls, SRTP both sides | 110 / 262, 104 / 253 | 46.0, 46.7 | 88 / 254, 76 / 203 | 42.8, 37.8 |
| 1000 calls, SRTP both sides | 213 / 477, 157 / 448 | 90.1, 77.6 | 147 / 451, 134 / 359 | 77.8, 71.9 |
No regression beyond the run-to-run spread, which is itself larger than
the proposed gates (5 % median throughput, 10 % p99). A short window
misleads: a 2 s smoke run at 100 calls showed HEAD at 3.5× the
baseline’s CPU, and 6 s windows at 500 calls, in both orders, showed
them equal. Transcoding (no load mode in rtpflux-bench) and XDP (root:
bench/fastpath.sh) were not compared.
Native control (native-bench, 2000 create+destroy pairs,
unkeyed). Each cell is round 1 / round 2:
| Pairs/s | Create p50 / p95 / p99 ms | Destroy p50 / p99 ms | Events/s | RSS growth | |
|---|---|---|---|---|---|
| Baseline | 5873 / 6819 | 0.085 / 0.114 / 0.133 | 0.079 / 0.133 | 5884 / 6836 | +8.9 MB |
| HEAD | 8930 / 7779 | 0.069 / 0.075 / 0.102 | 0.041 / 0.075 | 8953 / 7798 | +0.8 MB |
The baseline’s memory growth was a leak, fixed during the integration work (“two leaks fixed”).
Durable operations (HEAD only, [sessions] ledger, keyed, 2000
pairs): 72 pairs/s, create p50 2.6 ms and p99 29.7 ms, destroy p50
3.1 ms and p99 34.0 ms. This is bound by the disk’s sync latency (three
to four syncs per operation), and runs of the same build vary from about
35 to 70 pairs/s. The ledger keeps each outcome, its reply included, for
its retention: about 4.6 KB of memory per keyed operation, bounded by
ledger_quota per tenant. Lower the quota or the retention where
memory matters.
Recovery (500 endpoints; time from the relay’s launch until it lists them all):
| After SIGINT (graceful) | After SIGKILL | |
|---|---|---|
| Baseline | 180, 184 ms | 107, 101 ms |
| HEAD | 136, 133 ms | 120, 106 ms |
Recording conference mixers
mixrec::load (an ignored test: cargo test --release -p rtpflux --test mixrec load -- --ignored --nocapture) runs 50 mixers of 5 participants,
each participant sending a tone, for 5 s without recording, then for 5 s
with all 50 mixers recorded (WAV, 8 kHz, mono). Measured on an
i9-9900K (16 threads), loopback, release build, two runs:
| Mixer threads | Writer threads | Mix packets/s per participant | |
|---|---|---|---|
| Not recorded | 23.0–26.6% of a CPU | 50.2–50.3 | |
| Recorded | 31.8–35.4% of a CPU | under the clock-tick resolution (0.2%) | 50.1–50.2 |
- Recording costs the mixers 5–12 points of one CPU for 50 mixers (about 0.1–0.25% each): one more sum through a limiter and a copy into the queue per 20 ms. The participants’ mixes keep their rate: the conference is not slowed.
- No period was lost (
lost_ms0 for all 50). - The 50 WAV files were made 0.16–0.17 s after the stop.
- Not measured: latency to the participants as such (the rate is the proxy), tracks under load, and lossy formats (Opus, MP3), whose encoding runs on the conversion thread after the stop.
Running the benchmarks
# rtpflux against rtpengine, userspace, loopback (needs podman and an
# rtpengine container image, set with RTPENGINE_IMAGE)
CALLS=250,500,1000,2000 bench/compare.sh
# rtpflux with plain RTP, SRTP on one side and on both sides
bench/srtp.sh
# kernel fast paths: rtpflux XDP against rtpengine's kernel module (root)
bench/fastpath.sh
# HEAD against a pinned baseline: relaying, native control, durable
# operations, recovery (builds the baseline in a worktree)
BASELINE=cac9411 bench/baseline.sh
# the native API's load alone (native-bench), against a running relay
target/release/native-bench --socket /run/rtpflux/native.sock --pid <pid> --ops 2000
The scripts are configured with environment variables, listed at the top
of each script: CALLS, WARMUP, DURATION, REPEAT, WORKERS,
RELAY_CPUS, CLIENT_CPUS and others. Results are printed and saved to
bench/results/ (not committed: the tables here keep the numbers). Pin the relay and the load generator to different
physical cores (see lscpu -e), or the numbers mostly measure the
competition between them.
The cost of one DTLS handshake is measured separately:
cargo test --release -p rtpflux --lib handshake_cost -- --ignored --nocapture
Architecture
How rtpflux is organised, and the design choices that make it fast.
Goals
rtpflux is built to be as fast as possible. Every change is judged first on correctness, then on how much it costs per packet. In practice this means:
- No allocation while relaying. Buffers, tables and codec state are created at start-up or when a call is set up, never per packet.
- No copying. Packets are parsed in place and sent from the same buffer they were received into.
- No locks between media threads. Each worker owns its calls completely.
- Batched system calls. One
recvmmsgreads up to 32 packets, onesendmmsgsends them. - Optional kernel fast path. Simple calls skip userspace entirely (XDP).
Threads
┌────────────────────────┐
SIP proxy ──ng──► │ control thread │ parses commands, rewrites SDP,
│ (ng server) │ allocates ports, saves state
└──────────┬─────────────┘
bounded queue│+ eventfd wake-up
┌───────────────────┼────────────────────┐
▼ ▼ ▼
┌────────────┐ ┌────────────┐ ┌────────────┐
│ worker 1 │ │ worker 2 │ ... │ worker N │ relay media
│ ports │ │ ports │ │ ports │ (epoll loop)
│ 30000-… │ │ … │ │ …-60000 │
└─────┬──────┘ └────────────┘ └────────────┘
│ offload requests ┌────────────┐
└─────────────────────────────────►│ XDP thread │ installs kernel
└────────────┘ flows, polls counters
┌────────────┐
│ metrics │ serves /metrics
└────────────┘
- The control thread answers ng commands. It reads and rewrites SDP, picks ports, creates SRTP keys and ICE credentials, and sends each new call to its worker.
- Workers each own one contiguous slice (“shard”) of the port range.
A call’s sockets all come from one shard, so a call belongs to exactly
one worker and no state is shared. A worker sleeps in
epolluntil packets or commands arrive. It also runs DTLS handshakes, DTMF detection, recordings and announcements for its calls. - The XDP thread (only with
[xdp] enabled) installs settled calls into the kernel program. Every second it reads the kernel’s per-flow counters, so those calls do not time out. - The native API (only with
[control] native_socket) has a listener thread and a thread per connection. They hand each request to the control thread and write its reply, and the events the connection subscribed to. See Native control API. - PCM streams and mixers each have threads of their own. A worker copies an endpoint’s packets into a bounded queue for them, and plays the 20 ms frames they send back. Decoding, jitter buffering, concealment, resampling, voice detection and mixing happen there, never on a media worker.
- Media events (key presses, announcements played out, DTLS and ICE progress, recordings finished) go from the workers to the control thread through one bounded queue, which never blocks a worker.
- The metrics thread serves Prometheus metrics from counters the workers update atomically. Reading them takes no locks.
The path of a packet
For each datagram a worker receives:
- Demultiplex by its first byte (RFC 5764, RFC 7983): STUN (ICE checks and their answers) goes to the side’s ICE agent (or the ICE-lite responder), DTLS to the handshake, RTP and RTCP onward, ZRTP straight to the other side (when the call’s media is passed through).
- Decrypt SRTP or SRTCP in place, if this side uses it. A packet that fails authentication is dropped here, before it can influence anything else.
- Decide: is there a call on this port, is the source acceptable, and where does the packet go? This step also does the latching.
- Inspect: record it, read RTCP reports, apply blocking, and transcode.
- Encrypt for the destination side, if it uses SRTP.
- Send, batched with the other packets for the same socket.
Crates
The code is split so that protocol logic can be tested without sockets, threads or clocks:
| Crate | Role | Constraints |
|---|---|---|
rtpflux-core | Protocol logic: RTP and RTCP parsing, SDP reading and rewriting, latching, the relay decision, ICE and STUN, DTMF detection, G.711 and G.722 | no_std, no allocation, no I/O |
rtpflux-srtp | SRTP and SRTCP encryption and decryption, in place, all six suites | no_std, no allocation, constant-time tag checks |
rtpflux-ng | The ng protocol: bencode and commands | no_std, no allocation, no I/O |
rtpflux-xdp-common | The XDP program’s data layout and per-packet arithmetic, with safe reference versions of its logic | no_std |
rtpflux-xdp | Loading the XDP program, managing its flow table, AF_XDP sockets, the xdp-selftest tool | std |
rtpflux-xdp-ebpf | The XDP program itself, built for the BPF target | no_std, outside the workspace |
rtpflux-uring | io_uring multishot UDP receive for the media workers, with its benchmark | std |
rtpflux | The daemon: configuration, sockets, threads, DTLS, recordings, state file and Redis, metrics, web UI | std |
rtpflux-client | A client of the native control API, for a softswitch | std, only serde_json |
rtpflux-client-async | The async (Tokio) client of the native API, for production call control: typed requests, a connection pool, deadlines, reconnect, events on their own connection | std, tokio |
rtpflux-bench | The load generator used by the benchmarks | std |
Each crate’s README explains why it is separate and what is in it.
unsafe code is forbidden everywhere except the XDP program and three
small, documented modules: pod and xsk in rtpflux-xdp, and ring
in rtpflux-uring.
External code
- dimpl, a pure-Rust DTLS implementation on the RustCrypto
libraries, runs the DTLS handshakes only. The relay’s self-signed
certificate is made with the RustCrypto
p256andx509-certcrates. Media encryption uses the RustCrypto AES and SHA-1 implementations inrtpflux-srtp. - flacenc and ogg (pure Rust) write FLAC and Ogg Opus recordings; Opus audio is encoded and decoded by opus-rs.
- LAME writes MP3 recordings, only in builds with the
mp3feature. It is a C library under the LGPL. - rusty-s3 (request signing) and ureq (HTTPS over rustls) upload
recordings to S3, only in builds with the
s3feature, which builds ring’s C and assembly code. The default build links no C code. - opus-rs, a pure-Rust port of libopus, does Opus transcoding.
- aya loads the XDP program.
See AGENTS.md for the full rules contributors follow.
Testing
rtpflux is checked in five ways, from fast unit tests to real browsers,
SIP servers and the kernel. CI (.github/workflows/ci.yml) runs all of
them on every push: formatting and Clippy, the test suite with and without
the optional features, the web UI bundle, the XDP program with
xdp-selftest and xdp-e2e (GitHub’s runners allow sudo), and the
Kamailio, OpenSIPS and FreeSWITCH bench.
1. The test suite
cargo test --workspace
This runs, without root:
- Unit tests in every crate: SDP parsing and rewriting, SRTP against the RFC test vectors, latching, DTMF detection, RTCP, G.711, G.722 (bit for bit against another translation of the reference code), G.729, Opus and AMR, the PCM kernels (jitter buffer, concealment, resampler, VAD, N − 1 mixer, tones; against reference implementations), the XDP program’s reference logic, and more.
- Integration tests in
crates/rtpflux/tests/. They start a real relay on loopback and drive it over the ng protocol with real UDP media:
| File | What it covers |
|---|---|
ng/ | The ng commands over UDP: calls, re-INVITEs and rollback, hold, BUNDLE, SRTP bridging, blocking and DTMF security, RTCP statistics, transcoding, announcements, subscriptions, calls with more than two parties (labels, connect, mesh, inject), create and create from offer, delayed deletes, and the options of offers and answers |
native.rs | The native control API over its Unix socket, with rtpflux-client: two independent endpoints negotiated both ways, bridged across workers, renegotiated (commit and abort), destroyed (tombstones, idempotent destroy); DTMF, playback, bridge and speech events; idempotency keys, generations, tenants, deadlines, leases and the endpoint limit; endpoints surviving a restart; a PCM stream to a service (decoded audio, speech detection, audio back, marks, flush); mixers (N − 1, mute, active speaker; G.722 and PCMU together; a supervisor listening, whispering and barging in); in-band DTMF; the API over TCP with tokens; a worker’s failure reported; churn without leaks |
rtpflux-client-async/tests/client.rs | The async client against a running relay: two legs with typed requests and events on their own connection; many concurrent requests; deadlines; cancellation; reconnecting requests and events across a restart; TCP tokens; a slow event consumer (bounded, gap reported) |
relay.rs | The media relay itself: forwarding both ways, RTCP, latching, strict source, batching, port reuse, timeouts |
recording.rs | pcap recordings |
restart.rs | Calls, blocking, DTMF security, recordings, announcements, connections, copies, labels and media echo surviving a restart; offers answered, re-offers rolled back and created parties answered after one; parties created from their offer |
conformance.rs | The conformance vectors (below) |
ng/uring.rs | Calls received with io_uring and with recvmmsg (runtime.receive); the rest of ng/ uses the default (io_uring), or recvmmsg with RTPFLUX_TEST_RECEIVE=recvmmsg |
robustness.rs | No untrusted input panics: RTP, RTCP, STUN, telephone events, SDP, bencode, SRTP and the XDP frame checks get random bytes and mutated valid inputs; the ng control layer gets every command with mutated options and SDP; a live call’s ports get mutated media from its parties and a stranger, and still relay afterwards; native API requests of every operation, with fields of every type, and PCM stream frames. Seeded, so reproducible; RTPFLUX_FUZZ_SCALE=<n> runs n times as many cases (run it in a debug build, where overflow panics) |
control.rs | Error replies to bad requests, state files that cannot be restored, and calls restored from Redis (the newer of file and Redis) |
daemon.rs | The command line, the daemon started, used and stopped, and the rtpflux binary itself (SIGTERM) |
webui.rs | The web UI over HTTP: login, the app’s files and headers, read-only rules, and the API with a real call |
xdp_e2e.rs | The XDP fast path; run by scripts/xdp-e2e.sh, skipped otherwise |
Before sending a change, also run the formatter and the linter (the project uses Clippy’s pedantic set):
cargo fmt --check
cargo clippy --workspace --all-targets
2. Conformance vectors
conformance/media-vectors.txt holds over 5,000 expected results
computed by an independent, executable reference model of the
protocols. They cover SRTP and SRTCP for all six suites, SDES key
selection, ICE (answers, checks, priorities, role conflicts, check
lists, trickled pairs, consent freshness, trickle fragments), DTLS roles
and keying, DTMF detection, RTCP
reports, G.711, BUNDLE answers and the XDP frame rewrite.
cargo test -p rtpflux --test conformance
The test reports every disagreement at once. See Conformance for what each kind of vector checks.
3. Real browsers
scripts/webrtc-firefox.py makes a real WebRTC call through the relay.
Headless Firefox (with a fake microphone) calls a plain RTP “phone”
played by the script. The script checks that ICE and DTLS complete (with
the relay as a full ICE agent, the browser controlling; --lite makes
it ICE-lite), that the relay’s SDP says which, and that audio flows both
ways.
cargo build --release -p rtpflux
python3 scripts/webrtc-firefox.py # audio
python3 scripts/webrtc-firefox.py --video # audio and video, BUNDLE
python3 scripts/webrtc-firefox.py --video --max-bundle # bundle-only sections
python3 scripts/webrtc-firefox.py --lite # the relay ICE-lite
python3 scripts/webrtc-firefox.py --chrome /usr/bin/chromium # Chrome or Chromium
It prints PASS or exits with an error. Firefox only offers a
non-loopback address, so the script binds the relay to your machine’s
LAN address for the run.
S3
Two tests run against a real S3-compatible server when you point them at one. For example, with versitygw:
docker run -d --rm --name s3 -p 127.0.0.1:7070:7070 \
-e ROOT_ACCESS_KEY=test -e ROOT_SECRET_KEY=testsecret \
versity/versitygw --port :7070 posix /tmp
RTPFLUX_S3_TEST_ENDPOINT=http://127.0.0.1:7070 RTPFLUX_S3_TEST_BUCKET=recordings \
AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=testsecret \
cargo test -p rtpflux --features s3 -- --ignored s3
Coverage
Line coverage of the whole workspace is measured with cargo-llvm-cov:
rustup component add llvm-tools
cargo install cargo-llvm-cov
cargo llvm-cov --workspace --summary-only # the table
cargo llvm-cov --workspace --html # browsable, in target/llvm-cov/html
It is above 90% of lines. Most of what is not covered is code that needs
root to run: xdp-selftest and the XDP program loader (about 400 lines,
exercised by the kernel tests below). Without them, coverage is about 94%.
The tests install a logger that formats every record, so the code that
builds log messages is covered too.
The XDP offload controller does not need a kernel to be tested: the relay’s flow table and the host’s network tables sit behind two small traits, and the tests use in-memory versions of both.
4. SIP servers
integration/run.sh places real calls through Kamailio (its rtpengine
module driving rtpflux) in Docker, to a SIPp callee and to FreeSWITCH,
and through ferrosip’s media module, and checks the SDP, the media both
ways and each call’s cleanup; then a ZRTP call between two linphones,
checked secure end to end. See Integration.
integration/run.sh
integration/ferroswitch/run.sh tests a softswitch’s view of the native
API. ferrosip’s sip-ua engines (caller, B2BUA, callee, transfer target)
run on a deterministic simulated SIP network. The B2BUA anchors each leg
in an in-process rtpflux through rtpflux-client-async, and real RTP
crosses the relay. Scenarios:
- an early and a delayed offer;
- hold and resume (answered by the relay on the same port);
- a renegotiation the remote side refuses (rolled back with
endpoint.abort, media unchanged); - a blind transfer;
- after every BYE: an empty inventory, an
endpoint.destroyedevent for each endpoint, and no unknown operations.
sip-ua is a git dependency pinned by rev (ferrosip is private: SSH,
or FERROSIP_REPO for a mirror or a local clone). Without access the test
is skipped, unless REQUIRE_FERROSIP=1.
integration/ferroswitch/run.sh
FERROSIP_REPO=../ferrosip integration/ferroswitch/run.sh
5. The kernel fast path
These need root; see XDP fast path.
sudo target/debug/xdp-selftest # the program on generated frames
./scripts/xdp-e2e.sh # real calls in network namespaces
To check the redirect to an AF_XDP socket as well, build the self-test with the feature:
cargo build -p rtpflux-xdp --features af-xdp
sudo target/debug/xdp-selftest
6. Benchmarks
cargo bench -p rtpflux-uring compares the two ways the media workers can
receive (runtime.receive): epoll + recvmmsg and io_uring multishot
receive. A sender spreads RTP-sized datagrams over 1 to 4096 sockets at a
steady rate (and floods one socket); the benchmark reports each receiver
thread’s CPU time per datagram and how many it received. The results on one
machine are in Configuration.
Run it on an idle machine; numbers vary between runs by a few percent.
Conformance
Protocol code is easy to get almost right. To catch the cases that ordinary tests miss, rtpflux is checked against an independent, executable reference model of the protocols it implements. The model was written separately from rtpflux, directly from the RFCs. It computes the expected result for thousands of inputs. If rtpflux and the model disagree on any of them, one of the two has a bug.
How it works
- The reference model writes its expected results, called vectors,
into
conformance/media-vectors.txt. There are over 5,000 of them. - The test
crates/rtpflux/tests/conformance.rsfeeds each vector’s input to rtpflux and compares the output. - It reports every disagreement at once, not just the first.
cargo test -p rtpflux --test conformance
A vector looks like one line of a test table. For example, an srtp-send
vector gives a key, a plain RTP packet and the exact bytes the encrypted
packet must have.
What is checked
| Kind | What is checked | Against |
|---|---|---|
srtp-send / pkt | Protect::rtp output, byte for byte: CSRCs, header extensions, padding, marker, empty payloads, a sequence-number wrap; all six suites | RFC 3711 §3.1–§3.3, §4.1, §4.3; RFC 6188; RFC 7714 §8, §11–§12 |
srtp-recv / in | Unprotect::rtp accept/drop and plaintext over arrivals with loss, reordering across the wrap, replays, tampering, a large jump right after start, the 64-packet replay window, a forged first packet, and three interleaved SSRCs each wrapping on its own with replays across them | RFC 3711 §3.2.3, §3.3, §3.3.1, §3.3.2, Appendix A; RFC 4568 §6.4 |
srtcp-send, srtcp-recv | Protect::rtcp / Unprotect::rtcp, including E = 0 packets and 80-bit SRTCP tags for the _32 suites, GCM’s tag-then-index trailer | RFC 3711 §3.4, RFC 5764 §4.1.2, RFC 7714 §9 |
crypto, crypto-select | which a=crypto line is usable and its tag, suite and key | RFC 4568 §6.1, §9.1 with the relay profile below |
rtcp | the RTCP port read from a=rtcp | RFC 3605 |
csum2, csum4 | incremental checksum updates of the XDP path | RFC 1624 Eqn. 3 |
rtcp-report, rtt | rtcp::compound, rtcp::Report (SR/RR, report blocks, signed cumulative loss, short and malformed packets) and rtcp::rtt | RFC 3550 §6.1, §6.4, §6.4.1 |
g711-code, g711-linear | g711 decoding of every μ-law and A-law code, the transcoding tables, and encoding of linear samples | RFC 3551 §4.5.14 (ITU-T G.711) |
xdp | classify and rewrite of the XDP path on IPv4 and IPv6 frames: the lookup key, or pass, and the rewritten frame byte for byte, against checksums recomputed in full (including a computed zero sent as all ones and IPv4 without a UDP checksum) | RFC 791, RFC 8200 §8.1, RFC 768, RFC 1071 |
demux | what the first octet of a datagram on a media port is (STUN, ZRTP, DTLS, RTP/RTCP, drop), all 256 values | RFC 5764 §5.1.2, RFC 7983 §7 |
ice | the ICE-lite answer to a datagram, byte for byte: success with XOR-MAPPED-ADDRESS, 400/401/420, and no answer | RFC 8445 §2.5, §7.3; RFC 8489 §6.3, §9.1.3, §14 |
priority | host candidate priorities | RFC 8445 §5.1.2 |
ice-cand-priority, ice-pair-priority | candidate priorities of every type, pair priorities seen from either role | RFC 8445 §5.1.2, §6.1.2.3 |
ice-check | a connectivity check byte for byte: USERNAME, PRIORITY, ICE-CONTROLLING/ICE-CONTROLLED with the tie-breaker, USE-CANDIDATE, MESSAGE-INTEGRITY, FINGERPRINT | RFC 8445 §7.2.2, §16.1; RFC 8489 §14.5, §14.7 |
ice-role, ice-role-reply | role conflicts: the role after a check claiming a role and whether it is answered 487, and the role after a 487 | RFC 8445 §7.2.5.1, §7.3.1.1 |
ice-init, ice-next, ice-rto | initial pair states, the next check (triggered queue, then the best Waiting pair), the check RTO | RFC 8445 §6.1.2.6, §6.1.4.2, §14.3 |
ice-trickle-state, ice-trickle-insert, ice-list-state | the state of a pair formed after checks started, inserting it (redundancy, the pair limit), the checklist state with end-of-candidates | RFC 8838 §8, §11, §12 |
consent | consent freshness over runs of time, pair success, requests and responses, restarts: what is sent, whether data may flow, whether consent is lost | RFC 7675 §5.1 |
sdpfrag | which trickled candidates an application/trickle-ice-sdpfrag body delivers to which stream, and end-of-candidates | RFC 8840 §4.4, §8, §9.2; RFC 8839 §5.1 |
ice-agent-start, ice-agent | whole runs of the ICE agent (ice::Agent): for each input — a remote candidate, end-of-candidates, a check or a response received, time passing, a restart — what it sends (component, destination, transaction id, USE-CANDIDATE, role, credential generation) and then its state (role, media target and nominated pair per component, checklist state, lost consent, next deadline) | RFC 8445 §6–§9, §12; RFC 7675 §5.1; RFC 8838 §11–§14 |
setup | which a=setup answers an offer allows, and who is the DTLS client | RFC 4145 §4.1, RFC 5763 §5 |
fingerprint | whether a certificate matches the signalled a=fingerprint values of the strongest hash among them (real hashes) | RFC 4572 §5, RFC 8122 §5 |
keying | which half of the exported keying material protects which direction | RFC 5764 §4.2 |
exporter | the 60 octets exported with “EXTRACTOR-dtls_srtp” (TLS 1.2 PRF, SHA-256) | RFC 5705, RFC 5764 §4.2 |
group | which a=group lines the relay passes on in an offer (all but BUNDLE) | RFC 5888 §5, §9.4 |
dtmf | which telephone events are detected, with timestamp, duration and timeout extension, from sender streams with loss, duplicates, reordering, media and silence | RFC 4733 §2.3, §2.5.2.2 |
bundle-answer | the BUNDLE group of the relay’s answer: the offered tags without the refused sections | RFC 5888 §9, RFC 8843 §7.3 |
Details
The DTLS handshake itself is outside the reference model (it does not
model the ServerKeyExchange signature or CertificateVerify, so its
handshake does not interoperate with real TLS stacks). In rtpflux it is
run by the dimpl library, and scripts/webrtc-firefox.py checks it
against a real browser. The exporter vectors check rtpflux’s own RFC 5705
exporter against the reference; the keys dimpl exports are checked by
the two sides of a handshake agreeing and by the browser calls.
Receiver driver: no state until a packet authenticates; the first one is estimated against ROC 0 and its own sequence number (RFC 3711 §3.3.1).
ICE-lite responder: a datagram without a valid FINGERPRINT is not STUN; only Binding requests are answered; missing MESSAGE-INTEGRITY or USERNAME gives 400, a foreign username fragment or a wrong MESSAGE-INTEGRITY 401 (both unauthenticated); an unknown comprehension-required attribute 420; otherwise success. Understood attributes: USERNAME, MESSAGE-INTEGRITY, PRIORITY, USE-CANDIDATE.
Whole agent runs: the reference plays the peer — it answers the agent’s
checks (sometimes with 400 or 487, unauthenticated, from another address,
late or never), checks the agent from known and unknown addresses with
either role, trickles candidates, restarts ICE, sends end-of-candidates, or
goes silent (consent is lost) or never answers (the checklist fails). The
test drives ice::Agent with real STUN messages built from each input
(credentials L000/R000, the next generation after each restart) and a
random source whose k-th draw is k, and reads what the agent sends back.
Full ICE agent: checks carry the peer-reflexive priority (type preference 110, local preference 65535); a pair’s priority is computed from the controlling agent’s candidate as G (RFC 8445 §6.1.2.3). Of Waiting pairs with equal priority the lowest component goes first, then the first in the checklist. A trickled pair redundant with an In-Progress, Succeeded or Failed pair is not added, and making room never evicts In-Progress or Succeeded pairs (RFC 8838 §11 leaves both open). Consent requests use a 5 s basic period; a response after consent expired is discarded.
Relay profile for DTLS-SRTP fingerprints: SHA-1, SHA-224, SHA-256, SHA-384 and SHA-512, upper-case hex; MD2 and MD5 never match (RFC 8122 §5).
Relay profile for SDES keys: AES_CM_128_HMAC_SHA1_80/_32 (30
octets), AES_256_CM_HMAC_SHA1_80/_32 (46), AEAD_AES_128_GCM (28) or
AEAD_AES_256_GCM (44); exactly one key of the suite’s length in
canonical base64, an optional lifetime of at most 2^48, no MKI, no session parameters. Other offers are valid RFC 4568 but
not used by rtpflux.
For the GCM suites the reference model derives the session key and salt with the 96-bit master salt zero-padded on the right to 112 bits (the layout libsrtp and the browsers use; RFC 3711 §4.3.1 read literally would right-align it).
Where the model and rtpflux meet
The file is regenerated by the reference model’s media-vectors program
and committed as is; do not edit it by hand. A disagreement is a bug on
one side: find out which, and never edit the vectors to make rtpflux
pass.
Media engine: audit and gaps
rtpflux is growing from an RTP relay driven by a SIP proxy into a media engine driven by a B2BUA or softswitch (ferrosip, and a softswitch to come). The proposal behind this work is the programmable media engine specification (P0: independent endpoints, bridges, lifecycle, a native control API and events; P1: PCM processing; P2: a conference mixer).
This page started as that specification’s first milestone (P0a): an
audit of what the code did, against each requirement. It now also records
what was built on it, and what is left. Each line cites the code (paths
under crates/rtpflux/src/ unless written otherwise). The design of the
native API is in ADR 0001, and its
reference is Native control API.
Ordinary relaying must not get slower: every step below is judged first on correctness, then on what it costs the relay path. Features that need userspace stay off the XDP fast path, as today.
What existed before (the audit)
Endpoints and negotiation
| Requirement | Today | Where |
|---|---|---|
| Local offer, remote answer, with no other party | create, create answer: a hidden offerer (rtpflux-create:<tag>) whose answerer is the party | control/create.rs |
| Remote offer, local answer, with no other party | create from offer (added in P0a): the party is the offerer, the hidden side answers with every offered format, directions mirrored | control/create.rs, publish.rs (mirror_answer) |
| Receive-only answer | publish | control/subscribe.rs (publish) |
| Unbridged endpoint | A created party’s media is dropped (Echo::Discard on both legs) until connect | control/create.rs |
| Re-offer, hold, resume, new codecs | offer again in the dialog; create/create from offer again with the same tags | control/offer.rs (reoffer, replace_media) |
| Rejected sections, direction attributes | Port 0 kept; directions passed or mirrored | rtpflux-core/src/sdp/ |
| Pending vs committed revision | Only with flags: track-state: a full clone of the dialog (Session::checkpoint), taken back by rollback, committed by the answer | control/offer.rs, control/rollback.rs |
| SRTP (SDES), DTLS-SRTP, ICE, BUNDLE per endpoint | Per media section (MediaState) | control/media.rs |
Bridging
connect joins two parties of one call or two, on one worker
(ConnectLocal) or across two (two bounded queues of 256 packets, one
per direction, dropped and counted when full). It detaches the parties
they leave, and moving a connected party detaches its former peer both
ways (relay/worker/connect.rs). Codecs are converted when they differ
(G.711, G.722, G.729, Opus, AMR). Directional copies (connect with
directional, inject, mesh) are separate streams, not mixed audio.
Lifecycle, recovery
- A call belongs to one worker (round-robin over port shards); its ports
are freed when the worker reports
Event::Closed(relay/mod.rs). - Teardown releases sockets, SRTP and DTLS state, ICE agents, taps,
recordings (finished and converted), announcements, tones, BUNDLE,
connections and the call’s XDP flows (
relay/worker/commands.rs,close_call). - Timeouts:
sessions.timeout(60 s of no media),silent_timeout(held),offer_timeout(unanswered),final_timeout(off by default). - The state file and Redis hold every dialog with its ports, addresses,
keys, ICE credentials, pending offers,
track-statecheckpoints, subscriptions, connections, copies, labels and per-call features (state.rs,control/persist.rs). DTLS associations, announcements from ablob,play DTMFin progress and counters are not kept. Redis being down never blocks the control thread.
Events and observation
- The only push to a controller is the recording upload webhook
(
recording/webhook.rs): bounded queue (default 1000, dropped and counted when full), up to 5 attempts with backoff, a delivery id stable across retries, HMAC signature. It fires after S3 uploads only. - DTMF: RFC 4733 events are deduplicated (a ring of the last 32 finished
events,
rtpflux-core/src/dtmf.rs) and listed inquery(at most 256 per leg). In-band detection (Goertzel, 40 ms to start and to end,rtpflux-core/src/dtmf_inband.rs) feeds DTMF transcoding and DTMF security only, notquery. play mediareplies with the duration; nothing reports its end.- Prometheus metrics have no per-call labels (
metrics.rs).
Media processing primitives
| Primitive | Today | Live, allocation-free |
|---|---|---|
| Decoders/encoders: G.711, G.722, G.729 (+B), Opus, AMR, AMR-WB | codec.rs | yes (AMR encode packs into a Vec) |
| Resampling 8↔16 kHz | codec::Resampler, half-band FIR | yes |
| Resampling by integer factors | recording/resample.rs | no (offline) |
Repacketisation (ptime) | relay/repack.rs, preallocated | yes |
| Tone generation (DTMF, in-band) | relay/worker/tones.rs | yes |
| Two-party mix | recording/mix.rs | no (offline, after the call) |
| Fixed-capacity FIFO | rtpflux-core/src/ring.rs | yes (unused by the daemon) |
| Jitter buffer, reordering, PLC, VAD, gain, N-party mixer | none | — |
Announcements are G.711 frames of 20 ms, paced by the worker
(relay/play.rs, relay/worker/features.rs).
Defects found, and fixed
The audit found these. Each is fixed, with a regression test where a test can show it.
- Resurrection. A
delete-delaywas a bare selector: when it fired, it deleted a dialog made again under the same Call-ID and tags meanwhile. Every dialog now has a generation (Session::generation, kept by re-offers, new for a new dialog), and a delayed delete ends only the generations it selected (control/mod.rs,delete; testa_delayed_delete_spares_a_dialog_made_again). Native endpoints add their own generations and tombstones (below). - Partial
connect. Across workers, the second end of a connection could be refused after the first had detached its party’s former peer. The second end is now offered again for up to 20 ms before the connection fails (relay/calls.rs,connect). A re-offer of a connected created party no longer parks it: it is joined again (control/create.rs,park_or_rejoin). - Port leak. A delete whose worker was gone left the call
endingforever. Its ports are now freed (relay/calls.rs,forget_call). - Offer stored after a failed render. A new dialog whose offer cannot
be written is no longer kept: its calls end (
control/offer.rs). rollbackreported success after a failure. Media updates that fail are now named in the reply’swarning(control/rollback.rs);rolled-backstays as rtpengine’s.- XDP flow after a port is reused. Not changed. The worker sends the
flow’s
Removebefore it reports the call closed. Both reach their threads through FIFO channels, and a new call on the same port is on the same worker, so itsInstallcomes after theRemove. The remaining window is the old peer sending to a port reused within the XDP thread’s latency. - The DTMF list allocated on the packet path. It is now allocated
with the leg (
relay/worker/dtmf.rs).
What was built
P0: endpoints, lifecycle, the native API, events
- Negotiation both ways.
create(the relay offers) andcreate from offer(the relay answers an endpoint’s offer, with no second party), both reachable through ng and through the native API’sendpoint.create. - The native API (reference;
control/native.rs,native.rs):- a Unix socket with peer-credential checks;
- endpoint ids, generations and revisions, tombstones, idempotency keys, deadlines, tenants and leases;
- prepare/commit/abort renegotiation;
- bridges (attach, detach, replace) with
bridge.changed; - typed errors, and
endpoint.listfor reconciliation.
- One command model. Native operations build the requests of the ng commands they correspond to and run them on the same handlers. The ng wire format, warnings and behaviour are unchanged; the ng test suite is the check.
- Events.
- Media workers and the recording thread report through one bounded
queue (
relay/media_events.rs): key presses, announcements played out, DTLS keyed or failed, ICE connected, recordings finished. Nothing is sent per packet, and a full queue drops and counts. - The control thread delivers events to subscribers through bounded
queues, with per-endpoint and global sequence numbers and
gapevents.
- Media workers and the recording thread report through one bounded
queue (
- Detach. A new worker command (
Command::Detach) takes a leg out of whatever it is joined to. - Restarts. Endpoints are saved with the dialogs (
state.rs,SavedEndpoint) and come back with their media. - Client.
crates/rtpflux-client(a synchronous Rust client) and protocol fixtures.
P1: PCM processing
-
DSP kernels (
rtpflux-core/src/dsp/;no_std, no allocation, no unchecked arithmetic):- a jitter buffer;
- loss concealment;
- gain and a limiter;
- voice activity detection;
- a polyphase resampler between 8, 16, 24 and 48 kHz;
- the N − 1 mix;
- a tone generator.
Their tests check them against reference implementations.
-
PCM streams (
pcm/). An endpoint’s audio goes to an external service’s Unix socket and the service’s audio comes back, framed as in PCM streams. They have backpressure, flush (barge-in), playout marks, and speech events. The media worker only copies packets, by value into a bounded queue, and plays 20 ms frames. The signal processing runs on the stream’s threads. -
Modes. The packet fast path (XDP) and the transcoding path are unchanged. A leg with a stream or in a mixer leaves the XDP fast path (
offload_dirs) before its packets are needed. The ordinary relay path’s only addition is a check that a worker has no stream.
P2: conference mixing
- Mixers (
pcm/mixer.rs) do N − 1 mixing on their own threads, for up to 64 participants:- per-participant jitter buffer, decoder and loss concealment;
- a 32-bit sum, with each participant’s own contribution subtracted exactly;
- a limiter per listener;
- mute and gain;
- active-speaker events;
- participants in any codec the relay converts, mixed at 16 kHz and each encoded in its own codec;
- supervisor roles: listen, whisper to one participant, barge in.
- Worker failures as events. A recording that cannot be opened gives
recording.failed, and a socket a worker cannot watch givesendpoint.failed. Routing changes are confirmed by the workers (a barrier after them) before the reply. - In-band DTMF. Key presses in audio a stream or mixer decodes are
reported with
source: "inband". - TCP for the native API. It authenticates each connection with a tenant’s token, and binds the connection to that tenant.
What is left
- Typed requests. The ng handlers still read bencode. Native operations reach them through requests they encode, which is a cost on the control path only.
- AEC/AGC, a general media graph, a T.38 gateway. None of these is
done. Video is selective forwarding in conference rooms only (phase 1:
VP8, no simulcast; see
docs/video-sfu.md). - Integration and load.
- What exists: a churn test (100 rounds of create, bridge, detach and
destroy across workers, with retried creates and repeated destroys)
that checks the relay’s full capacity is available afterwards; and
the relay benchmark of
mainagainst this work on one machine, with no measurable difference in CPU per packet, delivery or p99 latency. - What is left: a two-leg scenario against ferrosip’s UA engine,
tc netemsoak tests, and benchmarks on production hardware (Benchmarks).
- What exists: a churn test (100 rounds of create, bridge, detach and
destroy across workers, with retried creates and repeated destroys)
that checks the relay’s full capacity is available afterwards; and
the relay benchmark of
ADR 0001: a native control API beside ng
- Status: accepted, implemented (see the notes at the end)
- Date: 2026-11-27
- Context: Media engine: audit and gaps
Context
A B2BUA or softswitch (ferrosip, and the softswitch that will use it) drives media differently from a SIP proxy. It names endpoints, not Call-IDs and tags. It must know whether a change was applied, not just queued. It needs events (DTMF, the end of an announcement, a recording finished) and has to reconcile its state with the relay’s after it reconnects. The ng protocol has none of this. Its requests are fire-and-forget per UDP datagram, identified by SIP identity, and idempotent only through a 30-second reply cache keyed by cookie.
ng must keep working unchanged: Kamailio, OpenSIPS and ferrosip’s media
module rely on its wire format, warnings and behaviour.
The audit found that the control thread has no transport-independent
command layer. Handlers read bencode dictionaries directly, and composite
commands re-encode bencode to call offer and answer.
Decision
-
One command model, two adapters. Each command becomes a typed request parsed once, with semantics in handlers that take the typed request. The ng adapter maps dictionaries to these requests, and must reproduce today’s replies and warnings exactly (the ng test suite is the check). The native adapter maps native messages to the same requests where the semantics match. Native-only semantics (generations, revisions, prepare/commit) live in the command layer, not in the adapter.
-
Transport.
- Version 1 runs over a Unix stream socket
(
[control] native_socket, mode 0600, owned by the relay’s user). Peer credentials (SO_PEERCRED) decide who may connect. - A network listener (
[control] native_listen) comes later. It will require an authentication token per tenant and is meant to sit behind TLS, as the ng HTTP endpoint already does. - No gRPC: it would add a large dependency tree, and an async runtime, to a daemon that has neither.
- The control thread owns the socket. Media workers never see it.
- Version 1 runs over a Unix stream socket
(
-
Framing and encoding.
- Each message is a 4-byte big-endian length followed by a JSON object, at most 1 MiB.
serde_jsonis already a dependency. The control path is not the packet path, and JSON keeps fixtures readable for the softswitch’s tests.- A message carries
"v": 1. A connection starts withhello, which returns the protocol versions and the capabilities the relay offers (codecs, SRTP, DTLS, ICE,pcm,mixer, and so on).
-
Requests. Each request has:
op, for exampleendpoint.createorbridge.attach;operation_id, chosen by the client and echoed in the reply and in every event the operation causes;- optionally
idempotency_key,endpoint_id,expected_generation,deadline_msandtenant.
A request whose
idempotency_keywas seen within the retention period (5 minutes by default, bounded in number) gets the stored outcome and runs nothing. A request past its deadline is refused withtimeout, and is not run. -
Replies. A reply carries
okwith the result, orerrorwith:- a
code, one ofnot_found,conflict,unsupported,exhausted,timeout,unauthorized,invalidorinternal; - a human-readable
message.
“Accepted” and “completed” are distinct. A reply comes once the change is applied in the control state and acknowledged by the workers it touches. Long operations (playback, recording) reply when started and finish with an event.
- a
-
Identity.
MediaSessionIdandMediaEndpointIdare opaque strings the relay makes up: 128 random bits, base32. They are not SIP identifiers, and the relay never infers SIP identity from them.- Each endpoint has a
generationthat a re-creation under the same client-supplied key raises. A deleted endpoint leaves a tombstone for the retention period, so a delayed command fails withconflictornot_foundrather than resurrecting it. - An endpoint made through the native API is also a party of an
internal call, so ng commands such as
querykeep working on it.
-
Events.
events.subscribesets a filter by endpoint, session or event type. Events then arrive on the same connection as{"event": …}messages.- Each event carries the endpoint id, generation, operation id where there is one, a sequence number per endpoint and a timestamp.
- Workers write events to a bounded ring per worker. When a ring is
full, the next event delivered carries
gap: true. A subscriber that falls behind is cut off with a finalgapevent, never waited on. - After a gap or a reconnect, the client calls
endpoint.listorendpoint.queryto resynchronise. Delivery is at most once, with gaps that can be detected.
-
Disconnect policy. A client disconnecting destroys nothing by default.
endpoint.createmay set a lease (lease_ms): an endpoint whose lease is not renewed is destroyed, with anendpoint.destroyedevent whose reason islease.
Operations in version 1
| Operation | Built on |
|---|---|
endpoint.create (offer) | create |
endpoint.create (answer to remote_sdp) | create from offer |
endpoint.apply_answer | create answer |
endpoint.prepare / commit / abort | re-offer with a checkpoint (track-state), rollback |
endpoint.destroy | delete of the party, idempotent |
endpoint.query / list | query, list |
bridge.attach / detach / replace | connect, made transactional |
playback.start / stop | play media, stop media, plus a completion event |
recording.start / stop | start recording, stop recording, plus file and upload events |
stream.start / flush / stop | new: PCM streams to external services |
mixer.create / add / remove / set / destroy | new: N − 1 conference mixing |
events.subscribe / unsubscribe | new |
Consequences
- The command-layer refactor comes first. It changes no behaviour, and the ng tests show that.
- A Rust client crate (
rtpflux-client) and JSON fixtures are published for the softswitch. They depend on no daemon internals. - Contract changes are agreed with ferrosip’s maintainers before they are implemented.
- The packet path is unaffected: commands reach workers through the existing bounded queues. Events leave through bounded rings and are counted when dropped.
Implementation notes
The reference is Native control API. The implementation departs from the decisions above in these ways:
- Command model (decision 1).
- What exists: native operations build the requests of the ng commands they correspond to, and run them on the same handlers. One model, with no second copy of any semantics.
- What is left: the typed-request refactor of the handlers, which would let both adapters skip bencode on the control path. It is a cost there, never on the packet path.
- Completion (decision 5).
- What exists: a reply comes once the change is applied in the control thread and queued to the media workers. Each worker applies its queue in order.
- Operations that change routing (bridges, streams, mixer membership)
then wait for a barrier from each worker concerned, so they reply
once the change is in effect, or with
timeout. - What is left: failures inside a worker are logged, as before, but not reported back.
- Identity (decision 6). Endpoint ids are the parties’ ng tags, and
session ids the ng call-ids, so ng commands such as
querystill see the endpoints. Generations are global and increase across restarts. - Events (decision 7). Workers write to one bounded queue shared by
all workers (
relay/media_events.rs), not one ring per worker. Overflow is counted, and reported as agap. - Network listener. Built as
native_listen: a connection’s first request authenticates with a tenant’s token (auth), and the connection is then that tenant’s. TLS is left to a proxy, as for ng’s HTTP endpoint.
Ferroswitch integration: tracking
Work on the Ferroswitch integration and reliability specification (a delta on the media engine): what the checkout had, what each step adds, the evidence, and what is left. Updated with every step.
Baseline
- rtpflux:
cac94112d993ae1e61614b0c4bbb8e416d45059c(0.2.0, native API v1 andrtpflux-client-async). It matches the specification’s baseline. - ferrosip:
60b20fc2ee38eba830705ee2e257f6da7b9eaf4a(0.2.0, withsip-ua). Cross-repository tests pin this revision.
What the baseline had
| Area | State at the baseline |
|---|---|
| Endpoints | Created both ways, parked, bridged across workers, renegotiated with prepare/commit/abort, destroyed with 5-minute in-memory tombstones; leases; tenants; generations and revisions |
| Idempotency | An in-memory reply cache keyed by (tenant, idempotency_key), 5 minutes. A reused key with a different request got the cached reply: no conflict |
| Recovery | Endpoints and their media saved with the dialogs (state file, at most once a second, or Redis): a crash loses up to a second. Streams, mixers, playback and recordings of endpoints are not tracked across a restart, and nothing reports what was lost |
| Events | Bounded, non-blocking, at most once, with gaps; no replay, no cursor, no boot id |
| Worker confirmation | Barrier after bridge, stream and mixer changes; no topology revision |
| Async SDK | Typed create/apply/attach/detach/destroy/prepare/commit/abort/query/list, pool, deadlines, cancellation, reconnect, events with gaps |
| HA | None |
| PCM | Two OS threads per stream; one thread per mixer |
Test evidence at the baseline
cargo test --workspace: 581 passed, 0 failed.- ferrosip at
60b20fcagainst the baseline’s release binary:cargo test -p sip-ua --test b2bua_rtpfluxpassed (ng protocol);tests/e2e_rtpflux.py35/35;tests/e2e_scenarios.py --only m15-media-relay36/36.
Deviations from the specification’s picture
sip-uadrives rtpflux over ng only; there was no native-API adapter.- The specification’s “five-minute in-memory response cache” is exact; it also did not detect a reused key with a different request.
Plan and status
| Step | Priority | Status |
|---|---|---|
1. Durable operation ledger, fingerprints, operation.query, external_id | P0 | done |
| 2. Inventory, boot id, recovery report | P0 | done |
| 3. Topology revisions, bridge CAS, half-bridge compensation, renegotiation both ways | P0 | done |
| 4. Replayable critical events with cursors | P0 | done |
| 5. Async SDK: capabilities, inventory, operations, cursors, recovery | P0 | done |
6. Cross-repository test: ferrosip sip-ua + async SDK + rtpflux | P0 | done |
| 7. Fencing epochs issued by an ownership authority | P0-HA | done |
| 8. PCM on shared I/O and DSP shards; flush generations | P1 | done |
| 9. Detectors without a stream, DTMF send, tones, sensitive digits | P1 | done |
| 10. Recording pause/resume with identity and state; ACLs, quotas, token rotation, audit | P1 | done |
| 11. Media graph, conference recovery | P2 | done |
| 12. Benchmarks against the baseline | all | done |
Step 1: operation ledger and external ids
control/ledger.rs: fingerprints (SHA-256 of the canonical intent), the ledger in memory or durable (append-only, synced; torn last line skipped;pendingwithout an outcome becomesunknownat start; compaction by rewrite; mode 0600), retention, per-tenant quota without early eviction.- Native requests: envelope checks first (never recorded); a keyed
mutation runs pending → apply → synced state (
save_durable) → synced outcome → reply; same key and another intent isconflict; an old first attempt isexpired;unknown_outcomeafter a crash.operation.query. New error codesunavailable,expired,unknown_outcome, anddetailon errors.hellostates the guarantees. external_idonendpoint.create, unique per tenant, kept with the tombstones (never evicted early);replaces_generationfor a new endpoint under a destroyed one’s id;endpoint.lookup. Tombstones and id counters are saved with the state.- Feature
fault-injection(tests only):RTPFLUX_FAULTkills the relay (SIGKILL) at a boundary.
Evidence: cargo test -p rtpflux --features fault-injection --test crash
(CI runs it in the all-features test job); cargo test --workspace: 584
passed.
- A SIGKILL at
after_pending,after_apply,after_stateandafter_outcome, then a retry and reconciliation, leaves one endpoint per external id; the outcome is either replayed or reportedunknown_outcome. - Durable keys and external ids work across a clean restart.
Unit tests in ledger.rs cover fingerprints, a torn last line,
pending turning unknown on restart, expiry and the quota.
Residual: mixers, streams, playback and recordings are deduplicated by
operation keys, but have no external id of their own (step 2 reports
those that a restart loses). A ledger costs two fsyncs and a state-file
write per keyed mutation; this is measured in step 12.
Step 2: inventory and recovery report
control/inventory.rs:inventory.list(six kinds, id order, pages of at most 500, a cursor bound to the run andtopology_epoch, a conflict when anything changed between pages, a watermark on every page);recovery.report;recording.query.- A boot id per run (in
hello), and the previous one after a restart. topology_epochchanges with every mutation, endpoint end, recording end.- Recordings have ids and a state (
active,stopped,completed,failed), updated from the media events, saved with the state. - Saved with the state: the streams, mixers, recordings and each endpoint’s playback and recording. After a restart, streams and mixers are reported lost, and so is a playback the relay did not restore (one from a blob).
Evidence: tests/native.rs inventory_and_recovery_report. It pages
through five endpoints, refuses a stale cursor, lists the bridges, the
recordings and the mixers, then restarts. Afterwards previous_boot_id
matches, six endpoints are restored, the mixer is reported lost, the
recording is still active, and the bridge is intact.
Residual: leases start again at a restart (documented). The epoch is coarse: any mutation invalidates a paged walk.
Step 3: topology and renegotiation
- Created parties in either orientation.
create,create answerandcreate from offerfind a created party’s dialog whoever offered last (created_dialog), so the relay can re-offer to an endpoint that offered first, and an endpoint the relay offered to can re-offer. - Prepare in both directions, by what it is given.
remote_sdpis answered at once, and its checkpoint is kept by an internal flag until the commit.- The relay’s re-offer is committed by its answer.
- Abort is an exact
rollback(it fails visibly if nothing was taken back), and the endpoint is bridged again as it was.
topology_revisionper endpoint. CAS on both endpoints of an attach (topology revision, and the peer’s generation and revision), andexpected_topology_revisionon any request that names an endpoint.- A failed attach is compensated: every endpoint involved, the former
peers included, is detached on the workers and in the records. A worker
that does not confirm leaves
topology_state: "unconfirmed". - Fault injection:
connect_halfrefuses a cross-worker bridge’s second end after the first was taken.
Evidence:
tests/native.rsrenegotiation_both_ways_and_topology_cas. The IVR leg’s own hold re-offer is aborted, then committed; the caller’s leg gets the relay’s re-offer, aborted, then committed. Media flows after each step, and a stale topology revision is a conflict.tests/crash.rsa_half_made_bridge_is_compensated. It fails when the compensation is removed (mutation check): the former peer is then still reported bridged while its media is not.
Residual: worker acknowledgements are synchronous barriers on the control thread (at most a second), so a late acknowledgement cannot overwrite a newer intent. Early media and delayed SDP are the existing endpoint flows, exercised end to end in step 6.
Step 4: replayable events
- Every event has
event_id(<boot_id>:<global_seq>) andboot_id, and goes into a bounded in-memory journal ([control] native_event_journal). events.subscribetakes acursor. It replays what came after, then goes live (resumed: true). A cursor of another run (boot_changed) or older than the journal (retention_expired) gets an explicit gap. The reply’scursorand the inventory’s watermark are cursors (a snapshot and a subscription without a race).- An overflowing subscriber gets a gap with
resume_cursoras soon as it has room, even when no event follows. Pending gaps are flushed on every pass of the control thread. - Events dropped before the journal (the workers’ queue was full) are
attributed where possible: the endpoints get
endpoint.events_lostandevents_indeterminate: true, and the gap ismedia_overflow.
Two bugs were found and fixed while testing:
- Destroying an endpoint whose relay offer was never answered deleted nothing, leaking its session and ports. Its dialog had no to-tag yet.
- A subscriber’s overflow gap was only sent with its next event, so a burst followed by quiet left the subscriber unaware.
Evidence (tests/native.rs):
events_resume_from_a_cursor: replay in order after a disconnect;boot_changed; subscribing from a watermark.an_overflowing_subscriber_resumes_without_loss: 3000 events to a subscriber that does not read, resumed from the gaps’ cursors, every event seen once after deduplication; a cursor older than the journal isretention_expired.
Residual: the journal is in memory. Events of a run do not survive a
relay restart, which is reported as boot_changed, and the terminal
results are reconciled from the saved state. Events are not persisted
across power loss by design.
Step 5: the async SDK
- Typed
hello(Capabilities,Guarantees, keeping unknown fields),inventoryandinventory_all(restarting a walk that raced a change),operation(OperationState),lookup,renew,recovery_report;MediaEventwithevent_idandboot_id;EventFilter::cursor; error codesunavailable,expired,unknown_outcome. - Event streams keep a position and resubscribe from it after a broken connection, a relay overflow, or the consumer falling behind (they stop reading, so memory stays bounded). Repeats are dropped by event number. Only unrecoverable losses reach the consumer as gaps.
- Bug found and fixed: events the relay writes while a subscription is
being made (a replay, a
boot_changedgap) could come before the subscription’s reply and were dropped. They are now delivered first. - Documented: ordering across pooled connections, correlation ids unique across reconnects, no automatic retries.
Evidence:
rtpflux-client-async/tests/client.rs: a slow consumer gets every event once and in order; after a relay restart,boot_changed.tests/typed.rs: capabilities, operations by key, an external id, a lease, the whole inventory and a subscription from its watermark, the recovery report.tests/cancel.rs, against a fake relay:- a request cancelled while queued is never written;
- a cancelled request’s late reply is not taken for the next request’s;
- fragmented replies are read;
- a request in flight when the connection drops is
Disconnected { sent: true }, and the client reconnects with new ids; - an unanswered request is
Timeout { sent: true }, and carries its deadline.
rtpflux/tests/native.rsfragmented_and_oversized_frames: a request written one octet at a time, and a frame over 1 MiB.
Step 6: cross-repository test
integration/ferroswitch is a crate outside the workspace, so the
workspace builds without the private repository. Its pieces:
sip-uafrom ferrosip, pinned byrev60b20fc in its Cargo.toml and Cargo.lock;- a B2BUA on simulated SIP engines;
- an in-process rtpflux with a durable ledger, driven through
rtpflux-client-async; - real RTP between UDP sockets.
The B2BUA creates one endpoint per leg. The relay answers each side’s re-offers itself, and the B2BUA bridges the legs.
The CI job ferroswitch checks ferrosip out at the pinned rev using the
FERROSIP_TOKEN secret. It runs with REQUIRE_FERROSIP=1, and is skipped
without the token.
Evidence (tests/b2bua.rs, 4 tests):
| Test | What it covers |
|---|---|
early_offer_hold_resume_and_bye | media both ways; the callee’s sendonly/sendrecv re-offers are answered recvonly/sendrecv on the same relay port; media both ways after the resume |
delayed_offer_and_bye_from_the_caller | the relay offers in the 2xx, and the caller’s answer arrives in the ACK |
a_refused_renegotiation_is_rolled_back | a PCMA re-offer to the caller is refused; endpoint.abort leaves the revision unchanged; media flows |
blind_transfer_to_a_third_party | REFER; the target is bridged to the callee, the referrer’s leg is released |
Every test ends with the checks after BYE: each endpoint is destroyed and reported by event, the inventory is empty, and the recovery report lists no unknown operations.
Deviation found: the relay does not refuse a re-offer with an unknown codec, or with no media. It passes them through, as rtpengine does. A softswitch that must refuse those has to check the SDP itself. Recorded here; not changed.
Not covered yet: attended transfer (Replaces), early media (183), and
UPDATE. These are left for step 11’s media graph work, or later.
Step 7: P0-HA fencing
Design: grants are HMAC-SHA256 signatures from an ownership authority. The relay keeps the highest epoch per tenant/group, synced to disk. Every mutation must prove three things: the epoch, a running lease, and the owner’s token, a second signature issued to the owner alone. Each touched resource must belong to a proven group. See docs/native-api.md “Exclusive ownership”.
Requirement placed on Ferroswitch: one rising epoch sequence per tenant, across groups. That lets the relay prune old groups safely, through a per-tenant floor.
Bug found while testing: proofs carried only {group, epoch}. A stale
controller could have guessed the next epoch. Proofs now carry the owner
token.
Evidence:
control/ownership.rsunit tests:- epochs only rise;
- same epoch for another owner: conflict;
- a renewal never shortens the lease;
- forged signature, unknown key, or another tenant’s signature: refused;
- an expired lease is refused;
- a guessed epoch without the token is refused;
- claims survive a restart;
- pruning raises the floor, and an old grant with a running lease cannot come back;
- a corrupt file is an error, and the relay does not start.
tests/ha.rsfencing_by_authority_epochs, end to end:- with no claim, mutations are refused;
- a forged grant is refused;
- another group’s proof does not cover an endpoint;
- after a handoff the stale controller is refused, even with a matching generation;
- a guessed epoch is refused;
- self-promotion is refused (an old grant, or the same epoch);
- a bridge across calls needs
peer_ownershipat the current epoch; - another tenant cannot use a grant;
- an
ngdelete on a native call is refused, whilequeryworks; - after a restart the stale controller is still refused and the current owner continues;
- an expired lease fails closed until it is renewed;
- a replayed expired grant is refused.
Residual gaps:
- The async SDK knows
fenced, but its typed requests have noownershipfield yet; useMediaClient::callin HA mode. - Mixer and stream membership check only the ids named in a request.
mixer.addnames the endpoint, so it is covered; pending worker operations are covered by the control-thread ordering argument above. - Partition is modelled as a stale controller (an old epoch, or no token). There is no network-level partition test.
Step 8: PCM on shared shards; flush generations
-
PCM streams no longer have two OS threads each. A few shard threads (
[runtime] pcm_shards; default one per CPU, at most 4) serve every stream. A stream stays on one shard, and every 20 ms the shard runs each stream once: the DSP towards the service, the service’s audio towards the worker, marks, and non-blocking writes. -
Buffers are bounded:
- a 240 ms write buffer per stream (overflow is dropped and counted, reported by a gap frame);
- the worker’s 100 ms inject queue (when it is full, the shard stops reading that service);
- at most 8 frames read per stream per tick (fairness).
-
The relay workers are untouched apart from flush handling.
-
The I/O design was chosen by measurement.
tests/pcm.rsload(100 streams, both ways, 5 s, release build), share of one core:Engine Threads CPU Baseline: threads per stream 200 12.6%, 11.6% Shards with an epoll loop on readability 4 18.4% Shards driven by the 20 ms tick (kept) 4 10.8%, 9.4%, 9.2% The epoll variant lost: its interest changed twice per tick for every stream whose service wrote ahead. The baseline also took about 250 s to shut down after the load run; the shards stop at once.
-
Flush generations, an opt-in protocol version 2 (
stream.start protocol: 2; version 1 services keep working):- a flush starts a new generation and is acknowledged with a flush
frame (the generation, and
played_ms) and astream.flushedevent; - stale audio and marks are dropped and counted, and a late mark is answered as flushed;
- every injected frame carries the flush count it was made under, and the worker drops it if a flush came since. This closes a race in which a frame encoded just before a flush was queued just after it.
- marks carry
generation,played_msandboundary: "rtp_sent". RTP sent is stated explicitly not to be audible playout.
- a flush starts a new generation and is acknowledged with a flush
frame (the generation, and
-
Bugs fixed on the way:
- marks pending at a flush could wait forever: the worker drained its queue without counting, while mark positions counted every frame. The worker now counts frames consumed (played or dropped).
- a gap frame was written only ahead of the next audio frame, so a service that fell behind at the end of speech was never told.
Evidence:
tests/pcm.rsflush_generations:- the hello says version 2;
- a flush during a long answer: the old generation stops at once, the
ack and
stream.flushedagree onplayed_ms; - a mark that waited behind the answer is answered as flushed;
- late generation-0 TTS plays nothing, and its mark is answered as flushed;
- generation 1 plays, and its mark has
rtp_sentand its generation; - a service flush racing a mark: the mark is flushed and the ack has generation 2.
tests/pcm.rsmany_streams_share_two_threads, 8 streams on 2 threads:- while one service floods the relay, another’s mark is answered in under a second;
- the services that read get their audio;
- a service that does not read gets a gap frame;
- a service that disconnects ends its stream, and a new stream on the same endpoint works;
- there are still 2 threads.
- The existing
audio_streams_to_and_from_a_servicepasses unchanged. frame.rsunit tests: version 2 round trips, and version 1 never carries a generation.
Residual gaps:
- A shard serves its streams in turn within the tick; a stream’s DSP is not split further.
- Mixers keep their own thread per mixer (not per participant).
- A hung service cannot block a shard: every read and write is
non-blocking. Only the hello is written blocking, at
stream.start, with a 100 ms timeout.
Step 9: detectors, DTMF send, tones, playback queues, sensitive digits
-
control/ivr.rscomposes what the relay already had:- the worker’s tone engine (RFC 4733 events or in-band tones; a sine code for cadenced tones);
- file and blob playback;
- recording pause;
- the PCM shards’ VAD and in-band DTMF.
-
New operations:
dtmf.send,tone.start,tone.stop;dtmf.policy(dedupby default,both,rfc4733,inband);endpoint.sensitive;stream.detect, withstream.starttaking nosocketfor detectors only (nopcm_dirneeded).
-
playback.startgainsqueueandstop_on(dtmf,speech). Interruption happens in the relay; digit collection and timeouts stay with the controller. -
Sensitive digits. Every output path, and what covers it:
Path Coverage Logs The worker logged every key at info; it now logs that a key was pressed, atdebug, without the digit, sensitive or notEvents Subscribers without sensitive: truegetdigit/codenullandredacted: true, live and on cursor replayRecordings Paused while sensitive, resumed after (only those it paused) Bridged peer Not covered (documented; ngblock DTMFexists)PCM service Not covered: it hears the tones as audio (documented) Event journal In memory only; holds the digit for entitled subscribers -
Bug fixed: RFC 4733 keys from an endpoint not bridged to anyone (an IVR leg) were never reported, because the worker skipped every dropped packet. It now observes authentic packets dropped only for lack of a destination, and still ignores unknown legs and wrong sources.
Evidence (tests/ivr.rs):
keys_and_tones_to_an_endpoint:- events with telephone-event, tones with
inband; - digits are not echoed;
- bad digits are refused;
- a cadenced tone plays and
tone.stopsilences it.
- events with telephone-event, tones with
detectors_policies_and_sensitive_digits:- a detector with no service or
pcm_dir, VAD off: no speech events; - one press, sent both in-band and as events, is reported once under
dedup, twice underboth, once (rfc4733) underrfc4733; - sensitive mode with a recording running: the recording pauses, the trusted subscriber sees the digit, the plain one sees it redacted, a cursor replay is redacted, and turning it off resumes;
stream.detectturns VAD on and speech is detected.
- a detector with no service or
playback_queues_and_barge_in:- a queued playback starts after the first completes;
- a key stops a
stop_on: ["dtmf"]playback and drops the queue behind it.
Residual gaps:
- The test checks a recording’s pause through the operation’s reply and the relay’s recording state, not by inspecting the pcap. A worker-confirmed pause boundary is step 10.
- Tones and
dtmf.sendhave no completion event; their reply gives the duration.
Step 10a: recording pause/resume with a confirmed boundary
recording.pauseandrecording.resume(control/rec.rs). The recording ispausedonly after a barrier confirms the media workers took the pause; the boundary time is recorded inpauses. Unconfirmed, the recording ispausingand the request fails (timeout). It is never reported paused while capture may go on.endpoint.sensitivenow pauses through the same confirmed path.recording.queryreports outcomes apart:finalized(the file is written),upload(pending,none,uploaded,failed), andfailedwith its detail.- Identity: a recording keeps its
recording_idacross pause, resume and a restart. A keyedrecording.startlists it in the operation’s resources.
Evidence: tests/recpause.rs pauses_are_confirmed_and_hold_nothing:
- pausing with no recording is refused;
- a pause is confirmed with its boundary; pausing again changes nothing;
- resume;
- a second pause spans a restart of the relay, and the recording is still
pausedafter it; - resume, then stop:
completed,finalized,upload: none, two pauses; - the finished pcap is parsed: no packet inside either pause window, and audio before, between and after them.
The existing a_worker_failure_is_reported covers a recording whose file
cannot be written (recording.failed).
Deviations and gaps found:
- Only relayed media is recorded. An endpoint bridged to no one (an IVR leg talking to prompts) records nothing; the test had to bridge it. Recording an IVR leg needs the recorder to also take dropped authentic packets and injected audio. Recorded, not changed.
- A failed upload is mapped (
upload: failed) and covered by the store’s own tests, but there is no end-to-end test: S3 needs thes3feature and credentials. - Disk full mid-recording is not simulated; an unwritable directory is.
Step 10b: access controls, rotation, rate limits, audit, ng isolation
- Unix socket ACL. Bug fixed: the socket was always mode 0600, so the
users configured in
native_uidscould not reach it, and theSO_PEERCREDcheck never ran for them. The mode is now 0600, 0666 when other users are listed (the credentials decide), or 0660 withnative_socket_group. - Token rotation.
native_tokens_file(several tokens per tenant) is re-read when it changes. A connection whose token was removed is refused at its next request and closed. An unreadable file keeps the last tokens. - Quotas.
native_rate_limit: a per-tenant token bucket, refused withexhaustedbefore anything runs. The existing per-tenant endpoint quota stays. - Protected transport. A non-loopback
native_listenis refused unlessnative_allow_remote, and the TLS proxy setup is documented. This changes behaviour: it used to be a warning. - Audit. The
rtpflux::auditlog target gets one line per mutation, claim, authentication and refused connection: who, what and outcome, never a body. - No secrets in logs:
- the audit line’s unit test feeds an SDP with
a=cryptoand checks no key reaches the line; - the logs were checked with grep: no log statement prints SDP or a request body;
- digits stopped being logged in step 9.
- the audit line’s unit test feeds an SDP with
- ng isolation.
ng_protect_nativegives the[ha]guard without HA.
Evidence:
native.rsunit tests:- socket modes 0600, 0666 and 0660 (with the group set);
- token rotation with overlap, revocation, and a short token left out;
- an unreadable file keeps the tokens.
audit.rsunit tests: the audit line never holds SDP keys; per-tenant buckets.tests/security.rs:- TCP rotation end to end: the old and new tokens overlap, then the revoked connection is refused and closed, and the old token can no longer connect;
- the rate limit refuses a burst, another tenant is unaffected, and it recovers;
ngdelete of a native call is refused whilequeryanswers;- a non-loopback
native_listenis refused unless allowed.
Not covered:
- A second Unix user connecting (the test runs as one user): the
SO_PEERCREDpath is the existing one, and the file modes are tested. - Native TLS: none; a TLS proxy is required.
Also in this step: two async SDK tests that failed only under a fully loaded test run were made tolerant of it. The slow-consumer test now waits for each event instead of stopping after 500 ms of quiet; the durable-mode test has a 30 s deadline. Neither showed a logic fault: both pass alone, and the events arrived complete and in order.
Step 11: composition and conference recovery
-
Mixer, per participant:
- deafen (hears silence, still heard);
- output gain, on what it hears, with
input_gain_dbas an alias ofgain_db; - taps: PCM streams fed a copy of its packets by the mixer, at most 4. “Conference participants can also stream PCM”: speech recognition on a conference leg. A tap cannot inject, and it ends when its participant leaves.
-
A PCM stream now ends when nothing can send it packets any more (its call ended, or its participant left), instead of ticking silently.
-
Conference recovery (
control/conference.rs):- each mixer’s plan (id, tenant, seats with role,
whisper_to, mute, deafen, both gains) is kept by everymixer.*operation and saved; - after a restart, mixers are rebuilt with the same ids before any request is answered;
recovery.reportgainsrestored_mixers, and participants whose endpoint did not return are listed as lost;- the mixing state starts afresh, and is documented as resumed, not transparently continued.
- each mixer’s plan (id, tenant, seats with role,
-
The media graph is documented (
docs/native-api.md, “Media composition”):- nodes and where they run;
- ownership, no cycles (one audio sink per endpoint, taps read-only);
- atomic, worker-confirmed changes;
- budgets and latency.
No new graph engine was built: the graph is composed from the existing nodes, and endpoints without any keep the relay, transcode and XDP paths.
Evidence (tests/conference.rs):
composition_and_controls:- mixed codecs (PCMU, PCMA, G.722): B and C hear A, A does not hear itself (N − 1);
- B’s output gain −20 dB is markedly quieter;
- A deafened hears nothing of B;
- A muted is heard by no one;
- an injecting stream on a participant is refused;
- a tap on A gets A’s voice while B still hears A;
- removing A ends the tap.
attach_detach_and_a_restart:- three clients add and remove at once (15 rounds each), leaving three participants;
- B deafened, C muted with +6 dB;
- after a restart:
restored_mixersholds the same id, nothing is lost, three participants; B still deafened and C still muted, by audio levels; - a new mixer gets a higher id.
tests/native.rsinventory_and_recovery_reportnow expects the mixer restored (it expected it lost).
Not covered (spec items left as gaps):
- A conference recording: since done (see “Recording a conference mixer” below).
- Mixer-to-mixer links (cascading) are not supported, by design (no cycles).
- AEC, AGC, video and T.38 are optional later milestones, per the spec.
Step 12 finding: durable operations cost grew with history (fixed)
Found by the step 12 benchmark. With [sessions] ledger, every keyed
operation rewrote and synced the whole state file, and the state file
held every tombstone (up to 65 536). The cost of each operation grew
with the number of endpoints ever destroyed. The rate fell from 122
pairs/s after 500 keyed pairs to 53 after 1500 and 37 after 2000, and
over 1500 pairs the relay wrote 509 MB to a 330 KB state file.
Tombstones now have their own append-only file next to the state file
(<state>.tombs.jsonl, control/tomblog.rs):
- a destruction appends a line, synced before a durable reply;
- the file is compacted at start-up and whenever it holds more than twice the tombstones kept;
- a torn last line is skipped;
- a state file of an older version still restores its tombstones, and they move to the new file.
Over 1500 keyed pairs: 8.7 MB written (58× less), a 354-octet state file, and a rate that no longer falls as history grows. The durable rate itself is bound by the disk’s sync latency (three to four syncs per operation), which on this machine varies from about 35 to 70 pairs a second from run to run.
Evidence:
tomblog.rsunit test: append, a later line replacing an earlier one, a torn line skipped, compaction;- the crash tests (SIGKILL at each boundary, keys and external ids durable) and the restart tests pass unchanged.
Step 12: benchmarks against the baseline
- New tools:
bench/baseline.sh: HEAD against a pinned commit (defaultcac9411), built from a worktree, run alternately on identical configuration;native-bench, a binary ofrtpflux-bench: native create+destroy rate, per-operation p50/p95/p99, event throughput, RSS growth, and the recovery time after a restart.
- Results (
docs/benchmarks.md, “Against the integration baseline”):- ordinary relaying: no regression beyond the run-to-run spread, plain and SRTP;
- native control: HEAD 7.8–8.9 k pairs/s against 5.9–6.8 k, lower p99, and no memory growth (the baseline grew 8.9 MB per 2000 pairs, a leak fixed earlier);
- recovery of 500 endpoints: about 105–135 ms either way;
- durable operations: 72 pairs/s, p50 2.6–3.1 ms, p99 about 30 ms, sync-bound. Their cost growing with history is fixed (see above).
- Not measured: transcoding (no load mode), XDP (needs root;
bench/fastpath.sh), the soak runs andtc netem(P1 acceptance table), and 500/1000 simultaneous PCM streams (the load test measured 100). - Memory note: the ledger keeps about 4.6 KB per keyed operation for its
retention, bounded by
ledger_quota.
Follow-up: gaps Ferroswitch found while integrating
Ferroswitch reported three gaps and worked around each on its side. Each is now fixed in the relay:
- A recording never finished when its endpoint was destroyed. The
call ended, but the outcome looked its endpoint up and found nothing,
so
recording.completednever came and the record stayedactive.endpoint.destroynow stops the recording first (stop recording), and an outcome that arrives after the endpoint is gone goes to its tenant as the destroyed endpoint’s event (found by its tombstone, withoutseq).recording.queryfinds the record by the endpoint it was of. Test:recpause::destroying_the_endpoint_finishes_its_recording. Ferroswitch’s own stop before teardown is no longer needed, but does no harm. - Finished playbacks were not kept, so a controller that missed
playback.completedwhile reconnecting could not tell completed from stopped. The relay now keeps how the latest 8192 playbacks ended (in memory) and answersplayback.query(playing,queued,completed,stoppedwith itsreason). A destroyed endpoint’s playback and queue now end withplayback.stopped(reason: "endpoint_destroyed") beforeendpoint.destroyed. The async SDK hasMediaClient::playback. Test:ivr::playback_ends_are_kept. - The SDK’s event filter could not ask for unredacted digits. The
relay already honoured
events.subscribewithsensitive: true, butEventFilterhad no field for it. It now hassensitive. - No echo or loopback primitive. The media workers already had
media echoforng, but the native API had no way to use it.endpoint.echo(echo: true/false) now sends an endpoint its own RTP back, unchanged. The echo is kept through a renegotiation and a restart,endpoint.queryreports it, and it is refused together with a bridge or a mixer, in either order. Async SDK:MediaClient::echo. Test:echo::an_endpoint_hears_itself.
Recording a conference mixer
Spec: “recording a conference mixer (rtpflux)”, proposed 2026-11-28
(Ferroswitch upstream issue rtpflux 9). recording.* take a mixer_id
(see native-api.md, “Recording a mixer”).
How it runs:
- The mixer thread computes what a
listenparticipant hears and hands each 20 ms period to a 5 s queue (pcm::mixer::MixTap). It never waits: a full queue loses the period and counts it. - A writer thread spools the periods (raw 16 kHz PCM, one file per section). Lost periods are written as silence at their place.
- At the end, the existing conversion thread turns each section into the
chosen format and rate. The encoders now take any PCM source
(
recording::encode::Pcm). - Storage (local, S3, webhook) and the outcome events are the endpoint
recordings’. The outcome is routed by
Subject::Recording(id).
Covered by the spec’s acceptance list:
| # | Status | Evidence |
|---|---|---|
| 1 | done | mixrec::the_mix_a_listener_hears: tones per party (Goertzel), duration within 40 ms of start→stop |
| 2 | done | same test: muted, listener and whisperer absent; include_whispers adds the whisperer (mutation-checked) |
| 3 | done | same test: a participant leaving, silence in the middle, participants intervals |
| 4 | done; the timeout branch is not tested | mixrec::pauses_sensitivity_restart_and_keys: confirmed pause, the section shorter by the pauses (mutation-checked). A pause the mixer does not confirm in time is not provoked by any test |
| 5 | done | same test: a sensitive participant pauses it; the controller’s pause survives sensitivity going away |
| 6 | done | first test: mixer.destroyed then recording.completed; recording.query answers |
| 7 | done | same test: a restart goes on in section 2, listed in restored_mixer_recordings, a file per section; mixrec::a_mixer_not_restored_finishes_its_recording: its mixer’s plan removed from the state, it is finished with what it holds and reported lost |
| 8 | unit level | pcm::mixer test: a full queue loses and counts, numbering goes on; recording::mixrec test: the writer fills lost periods with silence. No end-to-end run with a deliberately slow writer |
| 9 | done | ha::mixer_recordings_are_fenced: no proof, another group’s, and a stale epoch after a handoff are fenced; the new owner stops it |
| 10 | done | same test: one recording for one key; operation.query lists its recording_id |
| 11 | not tested | same storage code path as endpoint recordings |
| 12 | done | mixrec::a_track_per_participant: a file per participant, as long as the mix, its own tone only, silence before a latecomer joined, a muted one’s input kept |
| 13 | done | mixrec::load (ignored; by hand): see docs/benchmarks.md, “Recording conference mixers” |
Also added:
mixer.destroyedevent;- mixer events (with
mixer_id, noendpoint_id) reach subscriptions that name no endpoints or sessions, filtered bymixer_ids; - the
{mixer_id},{recording_id}and{track}file-name placeholders; [recording] max_mixer_recordings(64);- the async SDK has
EventKind::MixerDestroyed,MediaEvent::mixer_idandEventFilter::mixer_ids.
Found while testing the restart path, and fixed: with no event
subscriber connected, the control thread dropped media events (only an
announcement’s end was kept). A recording’s outcome then never reached
recording.query, endpoint and mixer recordings alike. A playback queue
did not advance, playback.query missed the end, and nothing went to the
journal for a later subscriber to replay. Media events are now always
handled. Test: recpause::the_outcome_is_kept_without_subscribers
(fails without the fix).
Ferroswitch’s requests R1–R5 (29 Nov 2026)
| # | Request | Status | Evidence |
|---|---|---|---|
| R1 | Video sections in the relay’s own offers | done (6a04ece) | offers::video_offers_origins_and_local_sdp: an offer of audio and video (a port each), video both ways across a bridge with its payload types, a hold re-offering both sections (same ports, sendonly), limits refused |
| R2 | The relay’s own SDP origin | done (6a04ece) | same test: one session id, versions 1, 2, 3, 4 across a restart; an answer without the offerer’s o=; a keyed retry at the same version |
| R3 | Durable throughput | done | the state journal (docs/configuration.md, “The state journal”); tests/durable.rs: 63 → 2943 keyed operations/s with 10 live endpoints, 17 → 1677 with 1000 (p50 4.7 ms and 8.0 ms); crash tests at each boundary |
| R4 | endpoint.query with the local SDP | done (6a04ece) | same test: the create reply’s SDP, then the committed one, absent without the flag |
| R5 | Typed external_id, replaces_generation | done (6a04ece) | typed test: a typed create found by lookup |
R3’s crash semantics changed for the better. An operation’s state and outcome are one record, so a crash leaves it wholly done or not done. There is no “pending, outcome unknown” left, except for a worker timeout. The crash tests were updated to that.
R3’s p99 at 1000 endpoints (about 100 ms) comes from compactions: the whole state is encoded on the control thread when the journal is full. That happens every few thousand operations; encoding it elsewhere is possible if the tail matters.
Bugs found by the tests after R3 (29 Nov 2026)
- The journal lost restored mixers and video routers. At a start,
the journal writes a full snapshot and removes the old files. Mixers
and routers are rebuilt just after that, and the snapshot held only
running ones. A second crash before the next snapshot lost the room.
Snapshots now hold the plans still waiting to be rebuilt. Test:
journal::a_kill_after_compactions_loses_nothing_acknowledged(thousands of keyed operations, compactions, SIGKILL twice). - A renegotiated video subscriber froze. See
video-sfu.md. - An unanswered endpoint said “unknown call or tag”. Recording,
bridging or playing to an endpoint the relay offered, before its answer,
gave
not_found, as if the endpoint were gone. It is nowconflict, “not answered yet”. Test:offers::an_unanswered_offer_says_so.
Checked and found right: changes without a key (native and ng) survive a
SIGKILL a second later (journal::a_kill_keeps_what_was_changed_a_second_before);
an aborted re-offer keeps the committed SDP, and the next offer’s origin
version goes above the rejected one’s, across a restart
(offers::an_aborted_reoffer_keeps_the_sdp_and_moves_the_version_on).
- A slow disk said “the relay is busy” for an operation that ran.
Durable replies wait for the disk. When one took longer than the
front’s 5 s, the client got
exhausted(“busy”, documented as not run) without itsoperation_id, so the client could not match it. A late reply is nowtimeout, saying the outcome is unknown, with theoperation_id.exhaustedis kept for a full request queue, which really runs nothing. Test:crash::a_slow_disk_times_out_durable_replies_only(a fault that makes each sync take 6 s; a read meanwhile answers at once). [ha]claims synced on the control thread. Under disk load, every client waited behind a claim’s twofsyncs. With a state file, claims are now written on the journal’s sync thread, before their reply. Test:ha::an_acknowledged_claim_is_on_the_disk.
Bugs found by coverage-guided tests (29 Nov 2026)
A coverage run (cargo llvm-cov, 81% of lines) pointed at what no test
reached; tests there found:
connect/bridge.attachjoined sections by position, not type. An audio endpoint bridged to a video-only one was accepted, its audio sent into the video section. An endpoint offering video then audio got the audio in its video. Sections are now joined by type; no type in common is refused. The refusal happens before anything changes, where before a refused attach had also dropped the bridge the endpoint had. Rejected sections now say they connect nothing. Test:bridges::sections_are_bridged_by_media_type.- A crafted WAVE header crashed the decoder. 32769 channels
overflowed symphonia’s WAVE reader (a panic with overflow checks on).
play mediacan carry the file in the request, and decodes on the control thread. Headers with no channels, or more than 8, are refused; a panic in the decoder now refuses the file instead of ending the thread. Test:robustness::media_files_never_panic(a new fuzz target, 900 000 cases clean). - A flaky relay test read counters before the worker had counted the packet it had just sent. It now waits for the counters, and for the worker to install each call.
Checked and found right: operation keys (expiry, quota, conflicts, failed
outcomes replayed, across a restart; keys.rs), external_id lifecycle
(keys.rs), video routers’ refusals and a router destroyed in use
(video.rs).
Found by Ferroswitch’s soak (30 Nov 2026)
-
The ledger rewrote itself on every append past 50,000 live keys. After a compaction its line count was the live entries, already over the threshold, so each keyed operation rewrote and synced the whole file. Past about 28 minutes at 30 operations a second, operations took about 0.5 s and clients timed out. It now compacts only when the file also holds twice the live entries: each rewrite is followed by at least as many appends (amortised O(1)), and the file stays within twice what it holds. Test:
ledger::tests::many_live_keys_do_not_rewrite_the_file_on_every_append(1990 rewrites for 2000 appends before, at most 10 now). Release binary: keyed operations hold their rate from 8,000 to 64,000 live keys. -
Memory, measured: a live ledger key costs about 2.5 KB (its reply is kept as a parsed JSON tree; about 450 bytes on disk), so the default quota of 100,000 keys per tenant is about 250 MB. The event journal (65,536 events) adds about 66 MB, bounded. Keeping replies as text would cut the ledger’s share about fourfold; not done yet.
-
Native endpoints never timed out in practice. A created party’s hidden offerer is at
0.0.0.0(“not advertised”); the hold check took that for RFC 3264 hold, so every native endpoint (and everycreated party) hadsilent_timeout(an hour by default) instead oftimeout. A browser gone without a BYE stayed in its room for up to an hour. The hold check now reads only the real party’s SDP. And since a bridged endpoint is a call of its own, media sent to an endpoint now marks it active too: a listener bridged to a talker does not time out. Test:timeouts::one_sided_endpoints_time_out_and_live_ones_stay(not bridged and a room’s end with reasontimeout; one that sends, a talker and its silent listener stay). Not counted yet: RTCP and STUN consent alone (an endpoint that sends no RTP at all, such as a browser with its microphone track removed).
Glossary
Plain-English explanations of the terms used in the rtpflux documents. Terms in italics inside an entry have their own entry.
A-law, μ-law — The two variants of G.711. A-law (PCMA) is used in Europe and most of the world, μ-law (PCMU) in North America and Japan. Converting between them is a simple table lookup.
Announcement — A recorded audio file the relay plays to a participant, for example “please hold”. See Call features.
Answer, answerer — In SDP offer/answer, the reply to an offer. The answerer is the party that replies, usually the person being called.
AES-CM, AES-GCM — The encryption methods (“suites”) SRTP uses. AES-CM encrypts and adds a separate HMAC-SHA1 tag to detect tampering. AES-GCM does both in one step. Browsers now prefer AES-GCM.
AF_XDP — A Linux socket type that receives packets straight from an XDP program, skipping most of the kernel’s network stack. rtpflux can use it for the calls the kernel cannot relay itself. See XDP fast path.
BUNDLE — A WebRTC feature that sends audio and video over one port instead of one port each. The relay sorts the mixed packets back into streams. Defined in RFC 8843.
bencode — The simple text-and-numbers encoding the ng protocol uses for its messages. It was originally invented for BitTorrent.
Call-ID, from-tag, to-tag — Identifiers from the SIP messages. Together they name a dialog. The from-tag belongs to the party that sent the request, the to-tag to the other party.
Codec — The method used to compress audio or video. rtpflux can convert (transcode) between PCMU, PCMA and Opus.
Dialog — A SIP call between two parties, identified by its Call-ID and the two tags.
DTLS, DTLS-SRTP — DTLS is TLS (the encryption behind HTTPS) adapted for UDP. WebRTC uses a DTLS handshake to agree the keys for SRTP; this combination is called DTLS-SRTP.
DTMF, telephone events — The tones sent when someone presses keys on a phone keypad (“press 1 for sales”). Over RTP they travel as separate “telephone event” packets (RFC 4733), which rtpflux detects and reports.
Endpoint — A phone, softphone, browser or gateway that sends and receives media.
Fast path — See XDP.
G.711 — The classic telephone audio codec: 8,000 samples per second, one byte each, 64 kbit/s. Comes in two variants, A-law and μ-law.
HMAC-SHA1 — A cryptographic checksum that proves a packet was not changed in transit. Used by the AES-CM suites of SRTP.
Hold — Pausing a call. The phone sends a re-INVITE that marks its
media as send-only or inactive, or (older phones) sets the address to
0.0.0.0.
ICE, ICE-lite — ICE is how WebRTC endpoints find a network path to each other, by sending connectivity checks (STUN messages) to candidate addresses. A full agent, like rtpflux by default, checks the other side’s candidates and answers its checks; an ICE-lite agent has a public address and only answers. Consent freshness keeps checking the chosen pair, so a relay stops sending to an endpoint that went away; trickle ICE sends candidates as they are found instead of all at once.
Interface — In rtpflux’s configuration, a named local address that
media is sent and received on, such as external or internal.
Jitter — How much the arrival time of packets varies. High jitter makes audio choppy.
Latching — Learning where a phone’s media really comes from by looking at the source address of its packets, rather than trusting the address in the SDP. This is how the relay reaches phones behind NAT. Also called “endpoint learning”.
Leg — One direction or one side of a relayed call. Each relayed stream has a leg towards each party.
Media section — One m= line in an SDP, describing one stream (for
example audio or video) and everything that follows it until the next
m= line.
NAT — Network address translation. A home router, for example, hides many devices behind one public address. The address a phone writes into its SDP is then often unreachable, which latching solves.
ng protocol — The control protocol between a SIP proxy and the relay:
bencoded commands such as offer, answer and delete, sent over UDP.
It comes from rtpengine and is used by the rtpengine modules of
Kamailio and OpenSIPS.
Offer, offerer — In SDP offer/answer, the first description of the media a party wants. The offerer is usually the caller, but in a re-INVITE it can be either party.
Opus — A modern, high-quality audio codec used by WebRTC. Its RTP clock always runs at 48,000 ticks per second.
pcap — A standard file format for captured network packets. Tools like Wireshark can open it and play back the audio.
PCMU, PCMA — The names of the two G.711 variants in SDP: PCMU is μ-law (payload type 0), PCMA is A-law (payload type 8).
Payload type — A number in every RTP packet that says which codec
it carries. The SDP maps numbers to codecs, for example a=rtpmap:111 opus/48000/2.
Re-INVITE — A new offer in an existing call, for example to put it on hold, add video or move to a new network. Either party can send one.
Relay — A server that receives media from one party and forwards it to the other. rtpflux is a relay.
Round-trip time (RTT) — How long a packet takes to reach the other side and come back. rtpflux calculates it from RTCP reports.
RTCP — The companion protocol of RTP. Endpoints use it to report reception quality: packets lost, jitter, timing.
rtcp-mux — Sending RTCP on the same port as RTP instead of the next port up. Required by WebRTC.
RTP — Real-time Transport Protocol. Carries audio and video as a sequence of UDP packets, each with a sequence number, timestamp and SSRC.
rtpengine — A widely used open-source media relay by Sipwise. rtpflux speaks its control protocol (ng) so it can be used in its place.
SDES — A way to exchange SRTP keys inside the SDP itself
(a=crypto lines), as many SIP phones do. The keys are only as secret as
the signalling.
SDP — Session Description Protocol. The text that describes a call’s media: addresses, ports, codecs, encryption. Carried inside SIP messages.
SDP offer/answer — The exchange in which one party offers the media it wants and the other answers with what it accepts (RFC 3264).
SIP — Session Initiation Protocol. Sets up, changes and ends calls. SIP carries the SDP; the media itself travels separately over RTP.
SIP proxy — A server that routes SIP messages, such as Kamailio or OpenSIPS. It controls the relay over the ng protocol.
SRTP, SRTCP — Secure RTP and RTCP: encrypted and tamper-protected versions. The keys come from SDES or DTLS.
SSRC — A random number that identifies one media source in RTP packets.
State file — A file where rtpflux saves its calls, so that it can restore them after a restart. The same state can also be kept in Redis.
STUN — A small protocol used by ICE for connectivity checks.
Symmetric RTP — The common practice of sending media from the same port it is received on (RFC 4961). It is what makes latching work.
Transcoding — Converting media from one codec to another, for example Opus from a browser to PCMU for a desk phone.
WebRTC — Real-time audio and video in web browsers. It always encrypts with DTLS-SRTP, uses ICE, and usually BUNDLE and rtcp-mux.
XDP — eXpress Data Path, a Linux feature that runs a small program in the network driver for each arriving packet. rtpflux uses it as a “fast path” that forwards settled calls without waking the relay process. See XDP fast path.