WebRTC
Real-time audio, video and data between peers: the browser's WebRTC API — RTCPeerConnection,
MediaStream, MediaStreamTrack, RTCDataChannel, mediaDevices.getUserMedia() — plus the
picture of a track: UIRTCVideoNode, a box of a screen's layout (a call's tiles), and
RTCVideoView, a track full screen with your controls over it. Code written against the browser
reads the same here. Host-optional — guard with RTCPeerConnection.supported /
mediaDevices.supported before offering calls, and UIRTCVideoNode.supported before drawing a
track in a screen (iOS, Android and Web Lite).
A plugin of the app: list it in app.json — "plugins": { "webrtc": "*" }. On iOS and Android
it runs over libwebrtc (Google's library, in the shell: ~8 MB), on the web (Web Lite and the web
player) over the browser's own stack, in a secure context (https or localhost). Not on the desktop
or headless (lecodes render) — supported is false there.
Signaling is the app's. The plugin carries no room, no call and no server: the app sends the
descriptions and the candidates to the other side over its own channel (a WebSocket to its
backend) and feeds what comes back in. A STUN server gets most peers through; a TURN server
(coturn) is needed for the rest — pass both as iceServers.
At a glance
A 1:1 call, the "perfect negotiation" pattern of the browser, over a signaling channel of the app's:
const signal = new WebSocket("wss://signal.example.com/ws")
const send = (msg: object) => signal.send(JSON.stringify(msg))
const pc = new RTCPeerConnection({ iceServers: [{ urls: "stun:stun.l.google.com:19302" }] })
const local = await mediaDevices.getUserMedia({ audio: true, video: { facingMode: "user" } })
for (const track of local.getTracks()) await pc.addTrack(track, local)
const mine = UIRTCVideoNode({ track: local.getVideoTracks()[0], mirror: true }) // your camera, a tile
.style({ position: "absolute", right: 16, bottom: 16, width: 120, height: 160, borderRadius: 12 })
const theirs = UIRTCVideoNode().style({ flex: 1 }) // the other side, the rest
pc.ontrack = (e) => { if (e.track.kind === "video") theirs.track = e.track }
pc.onnegotiationneeded = async () => {
await pc.setLocalDescription() // an offer
send({ type: "description", description: pc.localDescription })
}
pc.onicecandidate = (e) => send({ type: "candidate", candidate: e.candidate })
// one message after the other: a candidate must not be added while a description is still being set
let chain = Promise.resolve()
signal.addEventListener("message", (text) => { chain = chain.then(() => handle(JSON.parse(text))) })
const handle = async (msg) => {
if (msg.type === "description") {
await pc.setRemoteDescription(msg.description)
if (msg.description.type === "offer") {
await pc.setLocalDescription() // the answer
send({ type: "description", description: pc.localDescription })
}
} else if (msg.type === "candidate") {
await pc.addIceCandidate(msg.candidate)
}
}
UIScreen(theirs, mine).open()
// … later
pc.close()
for (const track of local.getTracks()) track.stop()API
What the browser has, with the differences a host-side object brings (below).
// the devices — navigator.mediaDevices of the browser
mediaDevices.supported: boolean
mediaDevices.getUserMedia(constraints?: MediaStreamConstraints): Promise<MediaStream>
// { audio?: boolean | AudioConstraints, video?: boolean | VideoConstraints }
// VideoConstraints: { deviceId?, facingMode?: "user" | "environment", width?, height?, frameRate? }
// rejects "denied" / "notFound" / "failed"
mediaDevices.enumerateDevices(): Promise<DeviceInfo[]> // { deviceId, kind, label, facing? }
mediaDevices.setAudioOutput("earpiece" | "speaker"): Promise<void> // the phone's route; a no-op on the web
mediaDevices.ondevicechange / addEventListener("devicechange", …)
// a track
track.id, track.kind, track.label, track.readyState ("live" | "ended"), track.muted
track.enabled = false // silence / black frames; stays in every connection
track.stop() // releases the device
track.applyConstraints({ facingMode: "environment" }) // the other camera; the track and its senders stay
track.getSettings(): Promise<TrackSettings> // a promise: the host knows
track.onended / onmute / onunmute
// a stream: a group of tracks
new MediaStream(tracks?)
stream.id, stream.active, getTracks(), getAudioTracks(), getVideoTracks(), getTrackById(), addTrack(), removeTrack()
// the connection
RTCPeerConnection.supported: boolean
new RTCPeerConnection(configuration?) // { iceServers, iceTransportPolicy, bundlePolicy, iceCandidatePoolSize }
pc.createOffer(options?) / createAnswer(): Promise<RTCSessionDescription>
pc.setLocalDescription(description?) // none = the implicit form: an answer to a pending offer, an offer otherwise
pc.setRemoteDescription(description)
pc.addIceCandidate(candidate | null) // null / empty = the end of the remote candidates
pc.localDescription, remoteDescription, signalingState, iceGatheringState, iceConnectionState, connectionState
pc.restartIce(), getConfiguration(), setConfiguration(c)
pc.addTrack(track, ...streams): Promise<RTCRtpSender> // a promise: the host makes the sender
pc.removeTrack(sender): Promise<void>
pc.addTransceiver(trackOrKind, { direction?, streams?, sendEncodings? }): Promise<RTCRtpTransceiver>
pc.getTransceivers() / getSenders() / getReceivers() // the SDK's copy, synced after every description and on every track
pc.getStats(track?): Promise<Map<string, any>> // the RTCStatsReport: id → { type, timestamp, … }
pc.createDataChannel(label, init?): RTCDataChannel
pc.close()
pc.onnegotiationneeded / onicecandidate / ontrack / ondatachannel / on…statechange
sender.track, sender.replaceTrack(track | null), sender.getParameters() (a promise), sender.setParameters({ encodings })
transceiver.mid, direction (settable), currentDirection, sender, receiver, stop()
// a data channel
channel.label, ordered, protocol, negotiated, id, readyState, binaryType ("arraybuffer")
channel.send(string | ArrayBuffer | ArrayBufferView) // before the host made it: queued
channel.getBufferedAmount(): Promise<number> // a promise — there is no bufferedAmount property
channel.bufferedAmountLowThreshold
channel.close()
channel.onopen / onmessage (e.data: string | ArrayBuffer) / onclose / onerror / onbufferedamountlow
// the picture in a screen — a node of the layout, sized by its styles (iOS, Android, Web Lite)
UIRTCVideoNode.supported: boolean
UIRTCVideoNode({ track?, objectFit?: "cover" | "contain", mirror? }): UIRTCVideoNode
node.track = track | null // live: switches the picture; null = black
node.objectFit = "contain"; node.mirror = true // live
node.onResize(({ width, height }) => …) // the first frame, and every change of the picture's size
// the picture full screen — a destination (NativeView): Router.push(view) / view.open(), widgets over it
RTCVideoView.supported: boolean
RTCVideoView({ track?, objectFit?: "cover" | "contain", mirror? }): RTCVideoView
view.track = track | null // changes at any time
view.objectFit, view.mirror
view.on("resize", ({ width, height }) => …)The picture: UIRTCVideoNode, RTCVideoView
A track drawn as a part of a screen — the other side filling it, your own camera in a corner tile —
is a UIRTCVideoNode: a node of the screen's layout, a box among its children like a UIImage,
with the picture in it. A track that fills the screen with controls over it — a full-screen view of
one participant — is an RTCVideoView pushed as a destination; the node has no open, onBack or
widgets.
// app.json: "plugins": { "webrtc": "*" }
const local = await mediaDevices.getUserMedia({ video: { facingMode: "user" } })
const size = UIText("")
const me = UIRTCVideoNode({ track: local.getVideoTracks()[0], mirror: true }) // the front camera, mirrored
.style({ width: 200, height: 200, borderRadius: 16 })
.onResize(({ width, height }) => { size.text = `${width} × ${height}` }) // the picture's size, as shown
UIScreen(UIRTCVideoNode.supported ? me : UIText("No video here"), size)
.style({ pt: "safe-top", p: 16, gap: 12 }).open()- It is placed like any element: give it a size, or
flex: 1in a column; it is black where there is no picture, andborderRadiusrounds it (the node clips:overflow: "hidden"is its default). It measures nothing itself: for a box of the picture's shape, setaspectRatiofromonResize. track,objectFitandmirrorare live; a getter answers what was written last.
on the web (Web Lite) the node is a <video> of the track in its box, the same picture
as the fullscreen RTCVideoView's: objectFit is CSS object-fit, mirror a CSS flip,
onResize the video's own size events. In the web player, on desktop and in headless tests the
node is an empty box of its size and UIRTCVideoNode.supported is false (building one there
warns once). An RTCVideoView is never a part of a screen: handed to one as a child it is
reported and skipped — a picture in a screen is a UIRTCVideoNode.
What differs from the browser
The objects live in the host and a call crosses to it, so what the browser answers from its own
memory is a promise here when the host must be asked: addTrack, addTransceiver,
track.getSettings(), sender.getParameters(), channel.getBufferedAmount(). getTransceivers()
answers at once from the SDK's copy, refreshed after every description set and on every track
event — the moments the mids and the directions change. A data channel is returned at once, in
the "connecting" state; what is sent before the host made it is queued. Events come as plain
objects with type and target, on on<type> handlers and addEventListener alike.
A MediaStream is a grouping and its id a label on the wire: on the web the browser gives the
stream it sends its own id, so compare tracks, not stream ids, across peers.
Groups, an SFU
The wire is the peer connection, not a call: a mesh of 1:1 connections serves a small group (up to
four or so); past that an SFU is the answer, and a client of one (mediasoup-client, LiveKit's) runs
in the app's bundle over these objects — addTransceiver with sendEncodings is the simulcast an
SFU asks for, getStats what it measures with.
See also
- Service — the raw channel the typed wrappers stand on.
- NativeView — what
RTCVideoViewis: a destination.