RTC calls

Audio, video and data between two devices — a video call, a voice chat, a game's peer-to-peer messages — over one fixed profile: Opus, H.264 through the phone's hardware codec, data channels. RtcConnection is one peer, RtcMedia the microphone and the camera, UIRTCVideoNode and RTCVideoView the picture. An app has no browser RTCPeerConnection or navigator.mediaDevices (its types have no DOM): a call is this API, on every platform.

  • make a video call between two phones, or a phone and a browser
  • make a voice-only call
  • show my camera in a corner and the other person on the rest of the screen
  • turn my camera or microphone off during a call, and show that the other side turned theirs off
  • switch between the front and the back camera
  • send chat messages or game state peer to peer, without a server in between
  • a group call of a few people
  • play the call on the loudspeaker or the earpiece
  • show the call's quality: round trip, bitrate, loss
  • a call between two networks that cannot reach each other directly
  • run my own media server for the relay and the rooms

Platforms: iOS, Android, the web (a secure page: https or localhost) and the web player, the le.codes viewer app (not its iOS App Clip); not on desktop or in headless tests — check RtcConnection.supported and RtcMedia.supported. The picture inside a screen (UIRTCVideoNode) draws on iOS, Android and the web; in the web player it is an empty box.

A plugin of the app: list it in app.json — "plugins": { "rtc": "*" }. On iOS and Android it is tinyrtc (a call stack of about 2 MB); on the web, the browser's own WebRTC held to the same profile, so a browser tab calls a phone.

At a glance

A 1:1 video call. Signaling is the app's: the offer, the answer and the candidates are text the app carries to the other side — here over a WebSocket of its backend that forwards each message to the other participant (sendToPeer, onPeerMessage: yours to write).

TypeScript
// app.json: "plugins": { "rtc": "*" }
const signal = new WebSocket("wss://example.com/calls/42")
const sendToPeer = (message: object) => signal.send(JSON.stringify(message))
const onPeerMessage = (handle: (message: any) => Promise<void>) => {
  let chain = Promise.resolve()   // one message after the other: a candidate waits for its description
  signal.addEventListener("message", (text: string) => { chain = chain.then(() => handle(JSON.parse(text))) })
}

const theirs = UIRTCVideoNode().style({ flex: 1 })                                // the other side
const mine = UIRTCVideoNode({ mirror: true })                                    // my camera, a tile
  .style({ position: "absolute", right: 16, bottom: 16, width: 120, height: 160 })
const status = UIText("Calling…").style({ position: "absolute", left: 16, top: 48, color: "#fff" })

const call = async (offering: boolean) => {
  const [microphone, camera] = await RtcMedia.getUserMedia({ audio: true, video: true })
  const connection = new RtcConnection({ iceServers: [{ urls: "stun:stun.l.google.com:19302" }] })
  await connection.setTrack("audio", microphone)
  await connection.setTrack("video", camera)
  await connection.ready                          // the received tracks are known
  mine.track = camera
  theirs.track = connection.remoteVideo           // its sound plays by itself

  connection.onicecandidate = (e) => sendToPeer({ candidate: e.candidate })
  connection.onstatechange = (e) => { status.text = e.state === "connected" ? "" : e.state }
  connection.onremotemedia = (e) => { if (e.kind === "video") status.text = e.active ? "" : "Their camera is off" }
  onPeerMessage(async (message) => {
    if (message.offer) sendToPeer({ answer: await connection.acceptOffer(message.offer) })
    if (message.answer) await connection.acceptAnswer(message.answer)
    if (message.candidate) await connection.addIceCandidate(message.candidate)
  })
  if (offering) sendToPeer({ offer: await connection.createOffer() })

  const hangUp = UIButton(UIText("Hang up")).style({ position: "absolute", left: 16, bottom: 16 })
    .onClick(() => { connection.close(); microphone.stop(); camera.stop(); status.text = "Ended" })
  screen.append(hangUp)
}

const screen = UIScreen(theirs, mine, status).style({ bgColor: "#000" })
screen.open()
if (RtcConnection.supported) call(true)          // the side that calls; the other one runs call(false)
else status.text = "No calls on this device"
Note

send the offer (or the answer) as soon as its promise resolves: the candidates the connection finds meanwhile are held and come after it, in the next task. On the receiving side keep the messages in order, as the example's chain does: a candidate is added after the description it came with.

The profile and its limits

Every connection speaks the same thing, never negotiated: Opus for audio; H.264 Constrained Baseline, packetization-mode 1, for video (encoded and decoded by the phone's hardware); SCTP data channels. Both kinds of media and the data line are in the first offer, so nothing a call does later — a camera turned on, a track swapped, a channel opened — is a new offer; the only second offer is an ICE restart.

  • One peer per connection. There is no SFU client (mediasoup, LiveKit) and no simulcast: a group is a connection per other participant (below).
  • STUN, no TURN. iceServers takes STUN servers; a call with no direct path crosses a relay (below).
  • A browser must have H.264. Chrome, Edge and Safari do; a browser that cannot encode and decode H.264 Constrained Baseline (or has no Opus) fails the first createOffer / acceptOffer with "failed".

The connection: RtcConnection

TypeScript
RtcConnection.supported: boolean
new RtcConnection({ iceServers?: { urls: string | string[] }[], relayOnly?: boolean })   // throws where unsupported
connection.createOffer(iceRestart?): Promise<string>     // the offering side: the offer's SDP text
connection.acceptOffer(offer): Promise<string>           // the answering side: resolves with the answer
connection.acceptAnswer(answer): Promise<void>           // the offering side
connection.addIceCandidate(line): Promise<void>          // the other side's `candidate:` line, or a relay's — no mid needed
connection.setTrack("audio" | "video", track | null): Promise<void>   // send a local track; null = stop sending that kind
connection.ready: Promise<void>                          // remoteAudio / remoteVideo are set
connection.remoteAudio, connection.remoteVideo: RtcTrack | null       // what it receives; null until ready
connection.setRemoteAudioMuted(muted): Promise<void>     // leave this peer's sound out
connection.getStats(): Promise<RtcConnectionStats>
connection.createDataChannel(label, { ordered?, maxRetransmits?, maxPacketLifeTime? }?): RtcDataChannel
connection.state       // "new" | "connecting" | "connected" | "disconnected" | "failed" | "closed"
connection.close()
// events — on<type> or addEventListener(type, …); each event has `type` and `target`
statechange { state } · icecandidate { candidate } · icerestartneeded · remotemedia { kind, active, track } · datachannel { channel }
  • The connection opens its session with the host when it is made, and asks for the two tracks it receives: remoteAudio / remoteVideo exist before any media flows (muted until the other side sends) and are set when ready resolves — and always by the time createOffer / acceptOffer resolve. The received audio plays by itself; draw the video with a node or a view.
  • statechange is the one state of the call: "disconnected" while the path is lost (it heals by itself, or after an ICE restart), "failed" when it is gone. icerestartneeded fires when the network changed under the call: the side that made the offer calls createOffer(true) and sends that offer as before.
  • close() ends it: its channels close (close), the received tracks end (ended), no statechange follows, and every method after rejects "closed". A closed connection is not reopened — make a new one.
Note

the rejections are codes: "failed", "closed", "notFound" (a track or a channel the host does not know), and on RtcMedia.getUserMedia "denied" / "notFound" / "failed".

Camera and microphone: RtcMedia, RtcTrack

TypeScript
RtcMedia.supported: boolean
RtcMedia.getUserMedia({ audio?: boolean | RtcAudioConstraints, video?: boolean | RtcVideoConstraints }?): Promise<RtcTrack[]>   // the microphone first
  // RtcAudioConstraints: { echoCancellation?, noiseSuppression?, autoGainControl? }   all default true
  // RtcVideoConstraints: { deviceId?, facingMode?: "user" | "environment", width?, height?, frameRate? }   default front, 1280×720, 30
RtcMedia.enumerateDevices(): Promise<RtcDeviceInfo[]>         // { deviceId, kind, label, facing? }
RtcMedia.setAudioOutput("earpiece" | "speaker"): Promise<void>   // the phone's route; a no-op on the web
RtcMedia.ondevicechange                                        // a headset or a camera came or went

track.id, track.kind ("audio" | "video"), track.label, track.remote, track.readyState ("live" | "ended")
track.enabled = false        // a local track: not sent — the other side gets remotemedia inactive; the device stays open
track.muted                  // a received track whose sender is not sending
track.stop()                 // a local track: the device is released, every connection stops sending it
track.applyConstraints({ facingMode: "environment" })   // a local video track: the other camera; the track and its id stay
track.getSettings(): Promise<RtcTrackSettings>           // { deviceId?, facingMode?, width?, height?, frameRate? }
track.setMaxBitrate(bps): Promise<void>                  // a local video track's ceiling, bits per second (default 1 500 000)
track.onended / onmute / onunmute

Turning the camera off and showing that the other side did — the sender says it, the receiver hears remotemedia (and its track's mute / unmute). Inside call() of the example above:

TypeScript
const mutedBadge = UIText("").style({ position: "absolute", right: 16, top: 48, color: "#fff" })
const cameraButton = UIButton(UIText("Camera")).style({ position: "absolute", right: 16, bottom: 190 })
  .onClick(() => { camera.enabled = !camera.enabled })       // off: not sent; the camera stays open
const flip = UIButton(UIText("Flip")).style({ position: "absolute", right: 16, bottom: 240 })
  .onClick(async () => {
    const { facingMode } = await camera.getSettings()
    await camera.applyConstraints({ facingMode: facingMode === "environment" ? "user" : "environment" })
    mine.mirror = facingMode === "environment"               // mirror the front camera only
  })
screen.append(mutedBadge, cameraButton, flip)
connection.onremotemedia = (e) => {
  if (e.kind === "video") theirs.style({ opacity: e.active ? 1 : 0 })   // black where their picture was
  if (e.kind === "audio") mutedBadge.text = e.active ? "" : "Muted"
}

track.enabled = false and setTrack("video", null) both stop sending; the first keeps the camera open and the track in every connection, for a quick way back. A track is one object per device track: the one a node draws is the one a connection sends.

A picture keeps its last frame. A sender whose camera is off sends nothing, so the receiving node goes on showing the last frame it drew. Cover or hide the node while remotemedia says the video is inactive, as the example does. The same before any picture came: connection.remoteVideo exists from the start and is muted until the other side sends, so read it once the connection is ready to know whether there is a picture to wait for.

The camera can come later. Both kinds are in every connection from the start, so a call can begin with the microphone alone — no camera prompt — and get the camera when the person asks for it, with no new offer. A smaller picture and a ceiling on its bitrate keep a phone call light:

TypeScript
const [microphone] = await RtcMedia.getUserMedia({ audio: true })
await connection.setTrack("audio", microphone)
// … later, on the camera button's first tap:
const [camera] = await RtcMedia.getUserMedia({ video: { width: 640, height: 360, frameRate: 30 } })
await camera.setMaxBitrate(700_000)
await connection.setTrack("video", camera)      // every connection that should send it
mine.track = camera

The picture: UIRTCVideoNode, RTCVideoView

TypeScript
UIRTCVideoNode.supported: boolean
UIRTCVideoNode({ track?, objectFit?: "cover" | "contain", mirror? }): UIRTCVideoNode   // a box of the layout
node.track = track | null           // live: switches the picture; null = black
node.objectFit = "contain"; node.mirror = true
node.onResize(({ width, height }) => …)   // the first frame, and every change of the picture's size

RTCVideoView.supported: boolean
RTCVideoView({ track?, objectFit?, mirror? }): RTCVideoView   // full screen: Router.push(view) / view.open(), widgets over it
view.track = track | null; view.objectFit; view.mirror; view.on("resize", ({ width, height }) => …)

A picture that is a part of a screen — the other side filling it, your camera in a corner — is a UIRTCVideoNode: sized by its styles like any element (a height, or flex: 1), black where there is no picture, the picture clipped to the box (overflow: "hidden" is its default). One participant full screen with your controls over it is an RTCVideoView pushed as a destination.

TypeScript
// a tile in the picture's own shape; full screen when tapped
const tile = UIRTCVideoNode({ track: connection.remoteVideo, objectFit: "contain" })
  .style({ width: "100%", aspectRatio: 16 / 9 })
  .onResize(({ width, height }) => { tile.style({ aspectRatio: width / height }) })
const big = RTCVideoView({ track: connection.remoteVideo })
const open = UIButton(tile).onClick(() => Router.push(big))

Data channels: messages peer to peer

TypeScript
const channel = connection.createDataChannel("chat")      // at once, "connecting"; no new offer
channel.label, channel.readyState         // "connecting" | "open" | "closing" | "closed"
channel.send(text | Uint8Array | ArrayBuffer): Promise<void>
channel.getBufferedAmount(): Promise<number>
channel.bufferedAmountLowThreshold = 64 * 1024
channel.close()
channel.onopen / onmessage (e.data: string | Uint8Array) / onbufferedamountlow / onclose
connection.ondatachannel = (e) => { e.channel.onmessage = … }    // a channel the other side opened, open already

What is sent before the channel opened is queued (a copy) and goes, in order, when it opens — before open fires. A channel closed before it opened rejects what was queued. send resolves when the host took the message and rejects "closed" on a closing or closed channel; leaving it unawaited is fine.

TypeScript
// a chat beside the call: one side makes the channel, the other hears it in ondatachannel
const log = UIText("")
const listen = (channel: RtcDataChannel) => {
  channel.onmessage = (e) => { if (typeof e.data === "string") log.text += JSON.parse(e.data).text + "\n" }
}
if (offering) {
  const chat = connection.createDataChannel("chat")
  chat.send(JSON.stringify({ text: "hello" }))                    // queued until it opens
  listen(chat)
}
connection.ondatachannel = (e) => { if (e.channel.label === "chat") listen(e.channel) }

Options: { ordered: false, maxRetransmits: 0 } for game state where only the newest matters (at most one of maxRetransmits / maxPacketLifeTime; neither = reliable).

A group call: a connection per participant

The wire is one peer; a group of a few people (up to four or so) is a connection to each other participant, each sending the same local tracks. With sendTo(who, message) the app's signaling to one participant:

TypeScript
const grid = UIRow().style({ flexWrap: "wrap" })
const peers = new Map<string, RtcConnection>()
const join = async (who: string, offering: boolean, microphone: RtcTrack, camera: RtcTrack) => {
  const connection = new RtcConnection({ iceServers: [{ urls: "stun:stun.l.google.com:19302" }] })
  peers.set(who, connection)
  await connection.setTrack("audio", microphone)
  await connection.setTrack("video", camera)
  await connection.ready
  grid.append(UIRTCVideoNode({ track: connection.remoteVideo }).style({ width: "50%", aspectRatio: 3 / 4 }))
  connection.onicecandidate = (e) => sendTo(who, { candidate: e.candidate })
  if (offering) sendTo(who, { offer: await connection.createOffer() })
}

On a phone the camera is encoded once for every connection that sends it (setMaxBitrate is the track's ceiling for all of them); on the web each connection encodes its own.

No direct path: the relay

Most calls connect directly (a STUN server finds the address outside the network). When none is found — two networks that block each other — the call crosses a relay that forwards bytes it cannot read, on a tinyrtc media server (your own): the app's backend reserves it for the two sides (the server's POST /calls, with each side's ICE username fragment — the a=ice-ufrag: of its description) and sends both sides the relay's candidate: line, which each passes to addIceCandidate. The line is a relay one of the lowest priority (candidate:1 1 udp 255 <server> <port> typ relay raddr 0.0.0.0 rport 0): every direct path outranks it, so a call that can go direct still does, and the relay then carries only its checks. Keep the candidates flowing both ways as in any call.

relayOnly: true makes the relay the only path and keeps this device's address from the other side, whatever the app passes the connection:

  • no candidate of its own goes into a description (an ICE restart's included) or out as icecandidate;
  • of the other side's candidates, only typ relay ones are taken — from addIceCandidate and from a=candidate lines inside the other side's description alike; a host, srflx, prflx or mDNS one is ignored, so this device never checks the other side's addresses, and the other side never hears from its own (it learns no peer-reflexive candidate of it either);
  • without a relay candidate the connection never connects.

One side asking is enough: the other may be an ordinary connection, which keeps trickling its candidates (the relay-only side ignores them) and reaches it only through the relay — but its own address does reach the relay-only side's app in those lines; it asks for relayOnly too if it should not. What still sees a relay-only device's address: the relay itself (it forwards from it) and the STUN servers in iceServers (they are asked; what they answer is never shown) — leave iceServers out of a relay-only connection to keep it from them.

An ICE restart (icerestartneeded, then createOffer(true)) makes new ICE credentials, and the relay was reserved for the old ones: the backend reserves it again with the new ufrags (the old one can be released) and both sides add its candidate again.

relayOnly is for a call through a relay, not for a room: there the media server is the other side, its candidate is its own (typ host), and a relay-only connection would never connect. In a room no other participant learns a device's address anyway.

Rooms through a tinyrtc media server

A group larger than a few people goes through a tinyrtc media server (your own), which receives each participant once and forwards to the others. Each device publishes its microphone and camera on ONE connection and receives each other participant on one connection per publisher; the app's backend carries every offer to the server's API and the answer back (POST /rooms/{id}/publish/{me}, POST /rooms/{id}/subscribe/{me}/{other}) — devices never call the media server themselves.

TypeScript
const publisher = new RtcConnection()                       // not relayOnly: the server is the peer
await publisher.setTrack("audio", microphone)
await publisher.setTrack("video", camera)
await publisher.acceptAnswer(await publish(room, await publisher.createOffer()))   // publish: yours, on the backend
// for each other participant who publishes:
const theirs = new RtcConnection()
await theirs.acceptAnswer(await subscribe(room, other, await theirs.createOffer()))
grid.append(UIRTCVideoNode({ track: theirs.remoteVideo }))
  • No trickle with the server. It answers with its own address as the only candidate, inside the answer, and learns the device's from its checks: nothing needs to follow the offer, and the connection's icecandidates can be dropped.
  • Data channels are not forwarded. A channel of a room connection opens and goes nowhere: a room's chat goes through the app's backend (a channel of the backend's, say).
  • remotemedia is slower in a room. The server does not pass on the words a sender says when its camera or microphone stops, so a received track's state is read from what arrives: a camera turned off shows after a second or two, where a 1:1 call shows it at once.
  • An ICE restart is not a relay's matter here (there is none); a 1:1 call through the relay needs a new reservation for it (above).

Your own media server

The relay and the rooms need a tinyrtc media server, and there is no shared one: an app runs its own. A direct 1:1 call needs none. The server is open source — github.com/letary/tinyrtc, the mediaserver/ folder — and published as a Docker image, ghcr.io/letary/tinyrtc-mediaserver. On a Linux machine with a public address, a docker-compose.yml:

yaml
services:
  mediaserver:
    image: ghcr.io/letary/tinyrtc-mediaserver:latest   # or a version: :X.Y.Z
    restart: unless-stopped
    network_mode: host        # media is UDP: no port publishing in between
    env_file: .env

and beside it the .env, the server's whole configuration; then docker compose up -d:

bash
TINYRTC_SECRET=<a long random string: openssl rand -hex 32>
TINYRTC_PUBLIC_IP=<the address the devices send to>
# TINYRTC_UDP=0.0.0.0:3478      the defaults
# TINYRTC_HTTP=127.0.0.1:8080
  • One UDP port is public (3478): the media of every room and call. Open it in the firewall.
  • The HTTP API is private (127.0.0.1:8080): only the app's backend calls it, with Authorization: Bearer <secret>. Never open it to the internet or call it from the app — the secret would ship inside the bundle. A backend on another machine reaches it through a reverse proxy with TLS that lets only that backend in.
  • Raise the socket buffers on the host, or a loaded server drops packets: sysctl -w net.core.rmem_max=8388608 net.core.wmem_max=8388608.

What the backend does with it — reserving the relay of a call:

bash
curl -X POST http://127.0.0.1:8080/calls \
  -H "Authorization: Bearer $TINYRTC_SECRET" -H "Content-Type: application/json" \
  -d '{"ufrags": ["<the offer'\''s ice-ufrag>", "<the answer'\''s>"]}'
# 201 {"id": "…", "candidate": "candidate:1 1 udp 255 <ip> 3478 typ relay raddr 0.0.0.0 rport 0"}

and for a room POST /rooms, then each device's offer to /rooms/{id}/publish/{user} or /rooms/{id}/subscribe/{user}/{other}, the answer in the response. The whole API, the options and the limits (one thread: a few hundred forwarded streams per process) are in the server's README.

A relay forwards bytes it cannot read; a room's server decrypts what it forwards — one more reason it is the app's own.

Call quality: getStats

TypeScript
const stats = await connection.getStats()
// { state, rttMs, sendEstimate, audioSendBitrate, audioRecvBitrate, videoSendBitrate, videoRecvBitrate,
//   audioLoss, videoLoss (0..1), audioJitterBufferMs, videoRecvFps, bytesSent, bytesReceived }
const quality = UIText("")
const poll = setInterval(async () => {
  if (connection.state === "closed") return clearInterval(poll)
  const s = await connection.getStats()
  quality.text = `${s.rttMs} ms · ${Math.round(s.videoRecvBitrate / 1000)} kbit/s · ${Math.round(s.videoLoss * 100)}% lost`
}, 2000)

Bitrates are in bits per second, times in milliseconds. On the web the rates and the loss are over the time since the previous call (the first call after connecting counts from the moment it connected).

Permissions

RtcMedia.getUserMedia asks for what it captures — the microphone, the camera — the first time, and rejects "denied" when the person refused. The plugin brings what the app declares for it: on iOS the usage strings of Info.plist (NSCameraUsageDescription, NSMicrophoneUsageDescription), on Android the CAMERA and RECORD_AUDIO permissions; on the web the browser asks itself, on a secure page only.

Platform notes

  • The web: the browser's WebRTC with tinyrtc's conventions (the lines, the codecs, a hidden channel on which each side says what it sends), so a tab calls a phone and a phone calls a tab. The received sound plays through an audio element of its own; a page the person has not tapped yet may refuse to play it until the first tap or key. setAudioOutput does nothing. A peer that never says what it sends (an older page) is read from what arrives: remotemedia inactive within about 2 s after its media stops.
  • The web player: calls and RTCVideoView work; UIRTCVideoNode is an empty box (UIRTCVideoNode.supported is false).
  • The le.codes viewer app carries the plugin; its iOS App Clip does not (supported is false there).
  • Desktop and headless tests: no calls — RtcConnection.supported is false.

See also

  • NativeView — what RTCVideoView is: a destination.
  • Service — the channel the typed wrappers stand on.