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.