The SDK covers the call control plane and the protocol rules of the media path. It does not include WebRTC, capture, codecs or playback: those are your platform's. What it gives you:

  • CallsApi (server.calls): one method per call endpoint of document 15, including the relay's {relayUrl}/connect.
  • Pure state machines that perform no I/O: CallContinuity for auto-rejoin and transmit state, LeaseTracker for lease ticks and coverage, RelayLiveness for relay keepalives and failure detection. You feed them events with times from your monotonic clock and carry out what they return.
  • Codecs with strict validation for voice-dc/1 (document 16) and video-dc/1 (document 17) frames, in the @sloppyvoice/sdk/media entry point.
  • SFrame for secure calls (document 18): KIDs, key derivation from the MLS exporter, AES-128-GCM through WebCrypto, and per-transport helpers.

Read Calls and Media first for how the protocol works. This page shows how the SDK maps onto it.

What your app provides

Part Why the SDK can't do it
One RTCPeerConnection to the relay per participation, with the three data channels of 15 §6.4 WebRTC is a platform API; Node has none built in.
A second RTCPeerConnection for the SFU session while videoRoute is sfu (15 §8.1) Same.
Microphone and screen capture, the Opus encoder and decoder, video encoders and decoders Codecs and devices are platform APIs.
The audio engine: transmit gate evaluation on the audio thread, jitter buffer, mixing It runs on the audio clock (16 §11.1), which the SDK can't own.
The event WebSocket subscription to the call's context, kept at full for the whole participation (15 §3.1) The SDK provides it (EventSocket); you keep it open. Call setCall(ctx) when you join and setCall(null) when the participation ends: while it is set, the socket keeps the context at full, refuses to unsubscribe it, and sends session.ping whenever no call.tick has arrived for 3 s.
Secure calls only: an MlsProvider whose group handle exports secrets The MLS state machine is pluggable (MLS and sealed messages).

Two WebRTC rules apply to the relay connection: it uses no TURN, and you configure no STUN servers for it, because the relay's public candidates are enough (15 §6.3); and every data channel is created with negotiated: true and a fixed id (15 §6.4). Every source travels through the hosting server's relay or its SFU, in every context and security mode, so the server enforces leases on every path and no participant learns another's IP address from a call (15 §7.1 item 2).

Joining

Calls live on the context's hosting server (15 §3.1), so use the ServerClient for that server. Before you join, run the security check of 15 §2.1 item 4 with checkCallSecurity: the call's mode comes from the context's mode as your client established it, never from the Call object.

import { LeaseTracker, SloppyVoiceClient, botToken, checkCallSecurity } from '@sloppyvoice/sdk'

const sv = new SloppyVoiceClient({ client: 'radio-bot/1.0', home: 'sloppyvoice.com', auth: botToken(process.env.SV_BOT_TOKEN!) })
const server = await sv.serverFor('publiclobby@sloppyvoice.com')
const ctx = 'ch:01938a11-2b3c-7d4e-8f90-112233445566'

const { call } = await server.calls.get(ctx)
if (call !== null && checkCallSecurity('insecure', call.security) !== 'ok') {
  throw new Error('The call is not in the mode this client holds for the channel')
}

const leases = new LeaseTracker()
let sentAt = 0
const joined = await server.calls.join(
  ctx,
  { features: ['voice-dc/1', 'video-dc/1', 'sfu-rtp/1'], selfMuted: false },
  // The join response's tick counts as received when the request was first sent (15 §3.3.3).
  { onSend: () => { sentAt = performance.now() } },
)
leases.acceptJoinTick(joined.tick, sentAt)
console.log(`pid ${joined.pid}, relay ${joined.relay.url}`)

CallsApi.join checks the body before sending it: features must include voice-dc/1, planned needs rejoinToken, and a rejoin token must match the ABNF of 15 §10.2. It always sends an Idempotency-Key, a fresh one unless you pass idempotencyKey, because every new join needs a fresh key and only a resend of the same request after a lost response reuses one (15 §3.3.1). The key also makes the request idempotent, so the HTTP client retries it with the same key after a network error, a timeout or a retryable problem; onSend runs only before the first send. Pass timeoutMs or signal to bound an attempt, as an auto-rejoin driver must. Use relay.url from the response, never ServerMetadata endpoints.relayUrl (15 §3.3.3).

Keep the rejoinToken in memory and delete it when the participation ends (15 §10.2 item 5). CallContinuity does this for you.

Connecting to the relay

Connect at once after the join response (15 §3.3.4). CallsApi.connectRelay sends POST {relayUrl}/connect with the RelayTicket as the bearer token, never your session token, gives up after 10 s and never retries: the ticket is single use, so every failure means a rejoin for a fresh ticket (15 §6.2 item 3). relayConnectFailureAction classifies the failure by that table.

import {
  RelayLiveness,
  encodeControlMessage,
  isKnownControlMessage,
  parseControlMessage,
  relayConnectFailureAction,
  type JoinResponse,
  type LeaseTracker,
  type ServerClient,
} from '@sloppyvoice/sdk'

declare const server: ServerClient
declare const joined: JoinResponse
declare const leases: LeaseTracker

// 15 §6.4: fixed ids, negotiated channels. No STUN or TURN servers (15 §6.3).
const pc = new RTCPeerConnection({ iceServers: [] })
const control = pc.createDataChannel('sv-control', { negotiated: true, id: 0, protocol: 'sv-control/1', ordered: true })
const audio = pc.createDataChannel('sv-audio', { negotiated: true, id: 1, protocol: 'voice-dc/1', ordered: false, maxRetransmits: 0 })
const video = pc.createDataChannel('sv-video', { negotiated: true, id: 2, protocol: 'video-dc/1', ordered: false, maxPacketLifeTime: 120 })
audio.binaryType = 'arraybuffer'
video.binaryType = 'arraybuffer'

// The offer goes out without waiting for ICE gathering (15 §6.2 item 1).
await pc.setLocalDescription(await pc.createOffer())
try {
  const { answer } = await server.calls.connectRelay(joined.relay.url, joined.relay.ticket, { offer: pc.localDescription!.sdp })
  await pc.setRemoteDescription({ type: 'answer', sdp: answer })
} catch (err) {
  const action = relayConnectFailureAction(err)
  console.log(`connect failed (${action.code}): ${action.class}`) // rejoin_now, wait_then_rejoin or rejoin_once
  throw err // never retry with the same ticket: rejoin for a fresh one
}

// Start watching when sv-control opens; until then there is nothing to time out.
let liveness: RelayLiveness | null = null
control.onopen = () => { liveness = new RelayLiveness(performance.now()) }
control.onmessage = (ev) => {
  const now = performance.now()
  if (liveness === null || liveness.check(now) !== null) return // a failed connection ignores later messages (15 §6.7)
  liveness.messageReceived(now)
  const msg = parseControlMessage(String(ev.data))
  if (msg === null || !isKnownControlMessage(msg)) return // unknown types are ignored (15 §6.5)
  switch (msg.t) {
    case 'relay.welcome':
      console.log(`session ${msg.d.relaySessionId} up`)
      break
    case 'call.tick':
      leases.receive(msg.d, 'relay', now)
      break
    case 'relay.closing':
      console.log(`relay closing: ${msg.d.reason}`)
      break
  }
}
pc.oniceconnectionstatechange = () => liveness?.iceStateChanged(pc.iceConnectionState, performance.now())
control.onclose = () => liveness?.transportClosed()

setInterval(() => {
  const now = performance.now()
  if (liveness === null) return
  const ping = liveness.pingDue(now) // every 5 s (15 §6.7 item 1)
  if (ping !== null) control.send(encodeControlMessage('relay.ping', ping))
  const failed = liveness.check(now)
  if (failed !== null) console.log(`relay connection failed: ${failed}`) // rejoin (15 §6.7 item 4)
}, 100)

RelayLiveness declares the connection failed at the first of: 5,000 ms without any control message, ICE failed, ICE disconnected for 5,000 ms, or the transport closing (15 §6.7 item 2). An ICE recovery cancels only the disconnected condition. Once failed it stays failed.

encodeControlMessage refuses messages over 16 KiB (15 §6.3). Subscribe to the video and shared sound you show with relay.subscribe; each message replaces the previous list, and microphone audio is never subscribed (15 §6.6).

Relay tickets

A client treats the ticket as opaque. parseRelayTicket reads its claims without verifying anything, for diagnostics and for showing when it expires; never act on the result, and never trust its sec claim (15 §2.1 item 4). Relays and test servers use verifyRelayTicket, which runs items 1 to 6 of 15 §5.2 and records the jti in a JtiStore, and signRelayTicket.

Lease ticks and coverage

Ticks arrive over the relay (call.tick on sv-control) and over the event WebSocket (the call.tick event), and you process both as one stream per call (15 §4.4). LeaseTracker applies the three rules: keep the highest seq, ignore other calls, and accept the next WebSocket tick whatever its seq once the newest one is 3,000 ms old. Feed it the join response's tick with acceptJoinTick, and every other tick with receive(tick, source, now), with source relay for sv-control and websocket for events.on('call.tick', …). Clients accept ticks from no other source (16 §12.1 item 2). receive also checks the tick's shape (15 §4.2) and returns why a tick wasn't accepted.

Method Answers
covered(pid, list, now) Whether a sender is covered for audio, video or listeners (15 §4.6). Drop a remote frame before decoding unless its sender is covered for the source's list.
coveredForSource(pid, sourceId, now) The same, by source ID: 0 and 2 use audio, 1 and 3 use video.
leaseState(ownPid, now) Your own leaseState for the transmit gate: covered, excluded or stale (16 §12.3).
mayListen(ownPid, now) Whether you may render call audio at all (16 §12.3).
expiresAt() When the newest tick stops being fresh, for scheduling a timer.

Pass times from the audio engine's monotonic clock, because coverage is enforced on that clock (15 §4.6). The VoiceLease in the join response and in call.lease_changed says why you are blocked (audioBlockedBy, videoBlockedBy); ticks decide whether you may send.

The roster

Call events are ephemeral and never replayed. Whenever a socket gains a full subscription to the context, the server sends call.state with the whole call (15 §3.1). applyCallEvent folds each call event into the Call you hold: call.state and call.started replace it, events for another callId are ignored, and events that don't change the Call (ticks, leases, SFU events) leave it as it is.

import { applyCallEvent, showReconnectingBadge, type Call, type CtxRef, type ServerClient } from '@sloppyvoice/sdk'

declare const server: ServerClient
declare const ctx: CtxRef

let call: Call | null = null
const reconnectingSince = new Map<number, number>()

const events = server.events({ subscribe: [ctx] })
events.on('call.state', (e) => { call = applyCallEvent(call, 'call.state', e.d) })
events.on('call.started', (e) => { call = applyCallEvent(call, 'call.started', e.d) })
events.on('call.route_changed', (e) => { call = applyCallEvent(call, 'call.route_changed', e.d) })
events.on('call.ring_updated', (e) => { call = applyCallEvent(call, 'call.ring_updated', e.d) })
events.on('call.epoch_switch', (e) => { call = applyCallEvent(call, 'call.epoch_switch', e.d) })
events.on('call.participant_joined', (e) => { call = applyCallEvent(call, 'call.participant_joined', e.d) })
events.on('call.participant_left', (e) => { call = applyCallEvent(call, 'call.participant_left', e.d) })
events.on('call.ended', (e) => { call = applyCallEvent(call, 'call.ended', e.d) })
events.on('call.participant_updated', (e) => {
  call = applyCallEvent(call, 'call.participant_updated', e.d)
  const p = e.d.participant
  if (p.state === 'reconnecting') {
    if (!reconnectingSince.has(p.pid)) reconnectingSince.set(p.pid, performance.now())
  } else {
    reconnectingSince.delete(p.pid)
  }
})
await events.connect()

// The badge shows only after 2 s in `reconnecting` (15 §10.3 item 2).
function badge(pid: number, now: number): boolean {
  const p = call?.participants.find((x) => x.pid === pid)
  return p !== undefined && showReconnectingBadge(p.state, reconnectingSince.get(pid) ?? null, now)
}
console.log(badge(3, performance.now()))

Unknown enum values from the server are tolerated. The normalize… helpers map them as the spec says, for example normalizeCallSecurity treats an unknown security as secure (15 §2.5.1).

Leaving

CallsApi.leave sends POST …/call/leave with the callId. It is idempotent. After sending it, close the relay connection and the SFU session and stop auto-rejoin (15 §3.4). Never call it because of network trouble: closing the relay connection without leave is an outage, and the seat is held for 30 s.

Mutes and your own state

Method Endpoint Notes
updateParticipant(ctx, pid, patch) PATCH …/call/participants/{pid} Your own selfMuted, selfDeafened and sources, for display only (15 §3.5). screen and webcam need video in your lease, screenAudio needs audio.
listMutes(ctx), getMute(ctx, addr) GET …/call/mutes[/{addr}] Any member who may read the call. listMutes pages for you.
putMute(ctx, addr, body) PUT …/call/mutes/{addr} Mute for everyone in a voice channel; needs mute_members (15 §3.6). reason is at most 512 Unicode scalar values.
deleteMute(ctx, addr) DELETE …/call/mutes/{addr} Removes it.

putMute and deleteMute always send an Idempotency-Key, as 10 §8.2 rule 6 requires. addr must be a canonical address. A muted person keeps video and listening; only the audio list changes (15 §3.6 rule 4), and the muted client learns it from call.lease_changed.

Ringing

In DM calls, a join with ring: true (the default in DMs) starts the ring (15 §13). The target's devices get call.ringing and call.ring_ended on the me stream.

Check a caller's display name against addr before you show it (Addresses).

SFU signalling

While the call's videoRoute is sfu, video and the shared sound that goes with a screen share travel through the SFU; microphone audio stays on the relay (15 §7.1). You exchange SDP with call control, never with the SFU itself (15 §8.1).

import { SloppyVoiceError, type CtxRef, type ServerClient } from '@sloppyvoice/sdk'

declare const server: ServerClient
declare const ctx: CtxRef
declare const callId: string

const sfu = new RTCPeerConnection()
const webcam = sfu.addTransceiver('video', { direction: 'sendonly' })
await sfu.setLocalDescription(await sfu.createOffer())

const session = await server.calls.createSfuSession(ctx, {
  callId,
  offer: sfu.localDescription!.sdp,
  publish: [{ mid: webcam.mid!, sourceId: 3 }],
})
await sfu.setRemoteDescription({ type: 'answer', sdp: session.answer })

// Server offers must be answered within 10 s (15 §8.3 item 3).
const events = server.events({ subscribe: [ctx] })
events.on('sfu.offer', async (e) => {
  if (e.d.sfuSessionId !== session.sfuSessionId) return
  await sfu.setRemoteDescription({ type: 'offer', sdp: e.d.offer })
  await sfu.setLocalDescription(await sfu.createAnswer())
  await server.calls.sfuAnswer(ctx, session.sfuSessionId, { negotiationId: e.d.negotiationId, answer: sfu.localDescription!.sdp })
})
await events.connect()

// Choose what to receive; each request replaces the previous set.
await server.calls.setSfuSubscriptions(ctx, session.sfuSessionId, { want: [{ pid: 3, sourceId: 1, maxSpatialLayer: 1 }] })

// Renegotiate from the client side, for example after starting a screen share.
const screen = sfu.addTransceiver('video', { direction: 'sendonly' })
await sfu.setLocalDescription(await sfu.createOffer())
try {
  const res = await server.calls.sfuOffer(ctx, session.sfuSessionId, {
    offer: sfu.localDescription!.sdp,
    publish: [{ mid: webcam.mid!, sourceId: 3 }, { mid: screen.mid!, sourceId: 1 }],
  })
  await sfu.setRemoteDescription({ type: 'answer', sdp: res.answer })
} catch (err) {
  // A server offer is outstanding: answer it first, then retry (15 §8.3 item 1).
  if (err instanceof SloppyVoiceError && err.code === 'sfu.negotiation_conflict') console.log('retry after answering')
}

Every offer and answer is at most 16 KiB; the SDK refuses a longer one before sending. Close the session with deleteSfuSession. When the SFU connection fails, delete the session if you can and create a new one, retrying after 1, 2, 4 and 8 s and then every 30 s while videoRoute is sfu; this is not an outage (15 §8.3 item 4).

A 1:1 DM call never uses the SFU (15 §7.2 item 1). In a secure call, call control negotiates only Opus for screen sound and VP8 and VP9 for video on the SFU path (15 §8.3 item 7), and every published frame is SFrame-encrypted through WebRTC encoded transforms (18 §8.4). Each SFU session gets its own SFrameEncryptor with a fresh joinNonce, never the media process's main one (18 §4.4 item 3). protectSfuFrame, splitSfuFrame and openSfuFrame do the per-frame work inside your transform; dropping frames of a source your lease doesn't cover is yours.

Continuity and push-to-talk

CallContinuity is the client state machine of 15 §10.4 for one participation, plus the transmit state it keeps across drops (15 §10.6). It is pure: you report what happens, and it returns a list of ContinuityEffects to carry out in order. Call advance() when wakeAt() passes.

It encodes these rules:

  • Push-to-talk follows the physical control. Nothing about PTT changes across a drop, and when the route, coverage and keys come back the gate opens with whatever the control says at that moment (15 §10.6 rule 3).
  • Voice activation and open mic come back muted after an unexpected drop, with mute reason rejoin, and are muted when a moderator's block on their audio starts (15 §10.6 rules 4 and 6).
  • After an unexpected drop the webcam is off, and a held screen share resumes only if a join response with seatRestored: true arrived within 30 s of the drop (15 §10.6 rule 7).
  • Planned migrations (call.migrate, relay.closing drain, call_restarted) change none of this (15 §10.8).
  • Attempts start at 0, 1, 2, 4, 8 and 15 s after the drop, then every 30 s with no limit, each with a fresh Idempotency-Key and ring: false (15 §10.5). Failed attempts are classified by the outcomes table of 15 §10.5 (classifyRejoinFailure).

Driving it

import { CallContinuity, LeaseTracker, type ContinuityEffect, type ServerClient } from '@sloppyvoice/sdk'

declare const server: ServerClient
declare const ctx: string
declare function openRelay(url: string, ticket: string, keepExisting: boolean): void
declare function closeRelay(): void
declare function closeSfu(): void
declare function stopWebcam(): void
declare function setScreenShare(state: 'hold' | 'resume' | 'stop'): void
declare function renewSession(): Promise<'ok' | 'transient' | 'terminal'>
declare function closeCallScreen(reason: string): void

const leases = new LeaseTracker()
const continuity = new CallContinuity({ ctx, mode: 'ptt' })
let timer: ReturnType<typeof setTimeout> | undefined

function run(effects: ContinuityEffect[]): void {
  for (const fx of effects) {
    switch (fx.type) {
      case 'send_join': {
        let sentAt = 0
        server.calls
          .join(ctx, fx.request, { idempotencyKey: fx.idempotencyKey, onSend: () => { sentAt = performance.now() } })
          .then(
            (res) => {
              leases.acceptJoinTick(res.tick, sentAt)
              run(continuity.joinSucceeded(res))
            },
            (err) => run(continuity.joinFailed(err)),
          )
        break
      }
      case 'connect_relay':
        openRelay(fx.url, fx.ticket, fx.keepExisting)
        break
      case 'close_relay':
        closeRelay()
        break
      case 'close_sfu':
        closeSfu()
        break
      case 'self_mute_changed':
        if (fx.report && continuity.pid !== null) void server.calls.updateParticipant(ctx, continuity.pid, { selfMuted: fx.selfMuted })
        break
      case 'report_sources':
        if (continuity.pid !== null) void server.calls.updateParticipant(ctx, continuity.pid, { sources: fx.sources })
        break
      case 'stop_webcam':
        stopWebcam()
        break
      case 'hold_screen_share':
        setScreenShare('hold')
        break
      case 'resume_screen_share':
        setScreenShare('resume')
        break
      case 'stop_screen_share':
        setScreenShare('stop')
        break
      case 'renew_session':
        void renewSession().then((result) => run(continuity.sessionRenewed(result)))
        break
      case 'send_leave':
        void server.calls.leave(fx.ctx, { callId: fx.callId })
        break
      case 'ended':
        closeCallScreen(fx.reason)
        leases.reset()
        break
      default:
        break // complete_mls_join, rejoin_complete and report_failure: see below
    }
  }
  clearTimeout(timer)
  const at = continuity.wakeAt()
  if (at !== null) timer = setTimeout(() => run(continuity.advance()), Math.max(0, at - performance.now()))
}

run(continuity.join())

A connect_relay effect with keepExisting: true comes only from a relay migration: connect to the new relay without closing the old one, and once the new relay's first tick arrives, send every frame to both relays and accept frames from both, discarding duplicates (15 §6.9 item 3). The old relay closes the call's sessions 10 s after the migration started.

Report these inputs as they happen; each returns effects for run:

Input When
relayUp() relay.welcome arrived on the new session.
relayTick() A lease tick arrived on the new relay connection. With send keys installed, the first one completes the (re)join.
setSendKeysReady(ready) Secure calls: send keys for the sending epoch are or aren't installed (15 §3.3.4).
relayConnectFailed(err) connectRelay threw.
relayFailed() RelayLiveness declared the connection failed.
relayClosing(reason) relay.closing arrived.
migrate(), moved(), participantLeft(ev), callEnded(ev), leaseChanged(lease) The events call.migrate, call.moved, call.participant_left, call.ended, call.lease_changed.
networkUp() The operating system reports that the network came back: the next attempt starts now.
dmSecurityChanged() dm.security_changed arrived after dm.upgrade_in_progress.
leave() The user pressed Leave or closed the call screen.
setSelfMuted(muted), setSelfDeafened(on), setMode(mode), setWebcam(on), setScreenShare(on, { audio }) The user changed them. The machine needs the webcam and screen-share state to stop or hold them after a drop.
setPtt(down), setPttObservable(observable), osInterruptionEnded(ms) The push-to-talk control changed, or an operating-system audio interruption ended (16 §7.9).

Before every automatic send_join (fx.automatic is true), run checkCallSecurity against your own view of the context and call abort('security_check_failed') if it fails (15 §10.5). With fx.prepareSecureContext, first run steps 2 to 5 of 15 §12.1. A complete_mls_join effect asks you to get a current leaf in the context's MLS group at once through your MlsProvider; the next attempt follows the schedule. rejoin_complete means the gate can open again: evaluate it at once. A report_failure effect asks for a call_failure report if the user's setting allows it (see Diagnostics).

After the app's own process restarted within 60 s, the user hadn't pressed Leave and the call screen is still present, pass restoreAfterProcessRestart to start in the rejoin path (15 §10.9). It needs the previous process's rejoin token, callId and pid, so keep them in protected storage during the call and delete them when the participation ends (15 §10.2 item 5).

The transmit gate

The gate decides whether captured microphone audio is sent (16 §7.3). evaluateTransmitGate is the gate function (evaluateGate in @sloppyvoice/sdk/media); it also returns the TalkState for the talk indicator, evaluated in the same step so the indicator never says transmitting while the gate is closed (16 §7.10). gateInputs() supplies the inputs the state machine owns; the audio engine supplies the rest.

import { evaluateTransmitGate, type CallContinuity, type LeaseTracker, type TalkState } from '@sloppyvoice/sdk'

declare const continuity: CallContinuity
declare const leases: LeaseTracker
declare const ownPid: number
declare function showTalkState(s: TalkState): void

// Only transitions count, except that an auto-repeat while the control counts as released is a press (16 §7.7).
addEventListener('keydown', (e) => { if (e.code === 'Space' && (!e.repeat || !continuity.pttDown)) continuity.setPtt(true) })
addEventListener('keyup', (e) => { if (e.code === 'Space') continuity.setPtt(false) })
// Without a global hotkey, losing focus makes the control unobservable: it counts as released (16 §7.7).
addEventListener('blur', () => continuity.setPttObservable(false))

// Run on the audio thread on every input change and at least every 10 ms of audio (16 §7.3).
function gate(now: number, audio: { vadActive: boolean; routeUp: boolean; captureOk: boolean }): boolean {
  const result = evaluateTransmitGate({
    ...continuity.gateInputs(),
    vadActive: audio.vadActive,
    routeUp: audio.routeUp,
    leaseState: leases.leaseState(ownPid, now),
    keysOk: true, // always true in an insecure call
    captureOk: audio.captureOk,
  })
  showTalkState(result.talkState)
  return result.transmit
}
console.log(gate(performance.now(), { vadActive: false, routeUp: true, captureOk: true }))

routeUp is stricter than the relay failure detector: the sv-audio channel is open, ICE is neither disconnected nor failed, some message arrived from the relay within the last 1,500 ms, and the channel's bufferedAmount hasn't stayed above 6,000 octets for 200 ms (16 §7.2). Audio captured while the gate is closed is discarded, never sent later (15 §10.6 rule 2).

voice-dc/1 frames

Audio frames go on sv-audio, one Opus packet per message behind a 12-octet route header (16 §4.3). The codecs live in @sloppyvoice/sdk/media.

import { checkVoiceFrameForReceiver, drawJoinNonce, encodeVoiceFrame, genOfJoinNonce, parseVoiceFrame } from '@sloppyvoice/sdk/media'
import type { LeaseTracker } from '@sloppyvoice/sdk'

declare const audio: RTCDataChannel
declare const ownPid: number
declare const leases: LeaseTracker
declare const recentGens: Set<number> // gens of your last media process in this call and of those started in the last 60 s
declare function isKnownPid(pid: number): boolean
declare function decodeOpus(pid: number, packet: Uint8Array): void

// One gen per media process, from a fresh joinNonce, in insecure calls too (16 §4.5.1).
const gen = genOfJoinNonce(drawJoinNonce({ avoidGens: recentGens }))
let sequence = 0

function sendOpus(packet: Uint8Array, timestamp: number, start: boolean, end: boolean): void {
  const message = encodeVoiceFrame({ pid: ownPid, sourceId: 0, gen, sequence, timestamp, start, end }, packet)
  audio.send(Uint8Array.from(message))
  sequence = (sequence + 1) % 65536
}

audio.onmessage = (ev) => {
  const parsed = parseVoiceFrame(new Uint8Array(ev.data as ArrayBuffer))
  if (!parsed.ok) return // count in invalidDrops (16 §4.9.1)
  const drop = checkVoiceFrameForReceiver(parsed.frame, { secure: false, ownPid, isKnownPid })
  if (drop !== null) return
  // Coverage at arrival (SHOULD); check it again at render, which is a MUST (16 §12.2).
  if (!leases.coveredForSource(parsed.frame.pid, parsed.frame.sourceId, performance.now())) return
  decodeOpus(parsed.frame.pid, parsed.frame.payload)
}
console.log(sendOpus)

The encoder enforces the sender rules: source 0 or 2 only, D never with S or E and never on source 2, an Opus packet of at most 1,000 octets and a message of at most 1,100 (16 §4.4, §4.8). parseVoiceFrame applies item 1 of 16 §4.9.1 and checkVoiceFrameForReceiver items 2 to 5; item 6, the KID check of a secure frame, is inspectSecureVoiceFrame and checkKidLeaf. The first two return a reason instead of throwing, because invalid frames are dropped silently and counted. Relays use checkVoiceMessageForRelay.

timestamp counts 48 kHz sample periods from the media process's reference instant, and keeps advancing while nothing is sent (16 §4.5.3). Receivers extend sequence and timestamp with serial-number arithmetic: SerialExtender and extendSerial do that. The jitter buffer, concealment and mixing are yours; jitterTarget and playoutDecision compute the values of 16 §9.3, and VoiceActivityDetector implements the voice-activation timing of 16 §7.6.

video-dc/1 fragments

A video frame is protected first (in a secure call), then split into fragments, each a message on sv-video with the 16-octet frame header, fragIndex and fragCount (17 §6.2, §6.5).

import {
  VideoStreamReassembler,
  checkVideoFragmentForReceiver,
  encodeVideoFrameHeader,
  fragmentVideoFrame,
  parseVideoFragment,
} from '@sloppyvoice/sdk/media'
import type { LeaseTracker } from '@sloppyvoice/sdk'

declare const video: RTCDataChannel
declare const ownPid: number
declare const gen: number
declare const leases: LeaseTracker
declare function isKnownPid(pid: number): boolean
declare function decodeVp8(pid: number, frame: Uint8Array, keyframe: boolean): void

function sendFrame(encoded: Uint8Array, frameNumber: number, refSeq: number, timestamp: number, keyframe: boolean): void {
  const header = encodeVideoFrameHeader({ pid: ownPid, sourceId: 3, gen, frameNumber, refSeq, timestamp, codec: 'vp8', keyframe })
  for (const fragment of fragmentVideoFrame(header, encoded)) video.send(Uint8Array.from(fragment))
}

// One reassembler per stream (pid, sourceId, gen).
const streams = new Map<string, VideoStreamReassembler>()
video.onmessage = (ev) => {
  const now = performance.now()
  const parsed = parseVideoFragment(new Uint8Array(ev.data as ArrayBuffer))
  if (!parsed.ok) return
  const f = parsed.fragment
  if (checkVideoFragmentForReceiver(f, { secure: false, ownPid, isKnownPid }) !== null) return
  if (!leases.coveredForSource(f.pid, f.sourceId, now)) return // the video list (17 §10.3)
  const key = `${f.pid}/${f.sourceId}/${f.gen}`
  let stream = streams.get(key)
  if (stream === undefined) streams.set(key, (stream = new VideoStreamReassembler()))
  for (const event of stream.add(f, now)) {
    if (event.type === 'complete') decodeVp8(f.pid, event.protectedFrame, event.header.keyframe)
  }
}
console.log(sendFrame)

fragmentVideoFrame uses the recommended chunk of 1,130 octets and refuses a protected frame over 2 MiB or one needing more than 2,048 fragments; send a lower-quality keyframe instead (17 §6.6 item 5). VideoStreamReassembler applies the slot rules of 17 §6.9: duplicates, abandonment after 500 ms, a newer keyframe superseding older slots, and the 32-slot and 8 MiB limits per stream. The call-wide 64 MiB limit and the current, candidate and retired gen rules of 17 §6.9 are yours. Call markDecoded after decoding so late fragments are recognised, and expire regularly. VideoDecodeOrder applies the decodability rules of 17 §6.10.

Codec choice follows 17 §5.3: selectVideoCodec picks from your preference list what every viewer can decode. RungController and ViewerForwarder implement sender adaptation and the relay's per-viewer forwarding state (17 §9, §8.2).

SFrame in secure calls

In a secure call every frame is an SFrame ciphertext under suite AES_128_GCM_SHA256_128, with keys derived from the context's MLS group (18 §3). The SDK does the encryption with WebCrypto; your MlsProvider supplies the exporter secret.

import {
  SFrameEncryptor,
  SFrameEpochKeys,
  checkKidLeaf,
  decomposeKid,
  drawJoinNonce,
  inspectSecureVoiceFrame,
  openVoiceFrame,
  parseVoiceFrame,
  protectVoiceFrame,
  sframeEpochSecret,
  type MlsExporter,
  type RosterLeaf,
} from '@sloppyvoice/sdk/media'
import type { ServerClient } from '@sloppyvoice/sdk'

declare const server: ServerClient
declare const ctx: string
declare const callId: string
declare const group: MlsExporter // the MLS group handle, in epoch `epoch`
declare const epoch: number
declare const ownLeafIndex: number
declare const ownPid: number
declare const audio: RTCDataChannel
declare function rosterLeaf(epoch: number, leafIndex: number): RosterLeaf | null
declare function participant(pid: number): { did: string; addr: string }
declare const usedJoinNonces: Set<number> // this group's joinNonce set for `epoch`, persisted with the MLS state
declare function persistJoinNonces(epoch: number, used: Set<number>): Promise<void>

// Install the epoch: its media secret stays in memory only (18 §3.3 item 3).
const keys = new SFrameEpochKeys(epoch, await sframeEpochSecret(group))

// One encryptor per media process, with a joinNonce never used in this epoch, written to
// persistent storage before the first frame is encrypted (18 §4.3 items 3 and 4, §4.4).
const encryptor = new SFrameEncryptor({ joinNonce: drawJoinNonce({ usedInEpoch: usedJoinNonces }) })
usedJoinNonces.add(encryptor.joinNonce)
await persistJoinNonces(epoch, usedJoinNonces)
encryptor.setSendingEpoch(keys, ownLeafIndex)
await server.calls.epochReady(ctx, { callId, epoch })

let sequence = 0
async function sendOpus(packet: Uint8Array, timestamp: number): Promise<void> {
  const protectedFrame = await protectVoiceFrame(encryptor, { pid: ownPid, sourceId: 0, sequence, timestamp }, packet)
  audio.send(Uint8Array.from(protectedFrame.message))
  sequence = (sequence + 1) % 65536
}

// A frame that fails any check or decryption is dropped (18 §6.7); none of these throws past here.
async function receive(bytes: Uint8Array): Promise<Uint8Array | null> {
  const parsed = parseVoiceFrame(bytes)
  if (!parsed.ok) return null
  try {
    const sframe = inspectSecureVoiceFrame(parsed.frame) // KID checks 1 to 3 against the route header (18 §4.5)
    const { leafIndex } = decomposeKid(sframe.kid)
    if (checkKidLeaf(rosterLeaf(epoch, leafIndex), participant(parsed.frame.pid)) !== null) return null // check 4
    // Epoch resolution (ReceiverEpochs) and the counter check (ReplayWindow) come here in a real client.
    return await openVoiceFrame(parsed.frame, await keys.keyFor(sframe.kid))
  } catch {
    return null // media.malformed_frame, media.kid_mismatch: invalid; media.decrypt_failed: lost
  }
}
console.log(sendOpus, receive)

SFrameEncryptor owns one counter per KID, starting at 0 and never reused (18 §5), and enforces the usage limits of 18 §3.6: selfUpdateNeeded turns true at half a limit, and encrypt throws media.key_exhausted at the limit. Before the first frame in an epoch, add the joinNonce to the group's persisted set for that epoch, also when a running encryptor moves to a new sending epoch (18 §4.3 item 4); that storage is yours, and drawJoinNonce takes the set as usedInEpoch. protectVideoFrame and openVideoFrame do the same for video-dc/1, encrypting the whole frame before fragmenting it (18 §8.3).

The rest of the receive path is in the same entry point:

Helper Rule
ReceiverEpochs Resolve a frame's epoch from its KID residue, hold frames of an unknown newer epoch for up to 200 ms, and retain or erase old epochs (18 §6.4–§6.6).
SendingEpochState Choose the sending epoch and the keysOk input of the gate (18 §6.3).
ReplayWindow, FreshnessCheck The counter check before decryption, and the freshness check after it; record a counter only once both passed (18 §7).
AttestationBatcher, createMediaAttestation, verifyMediaAttestation, StreamPlayback MediaAttestation batches, signatures, verification and the stream playback state (18 §9).

Post epochReady once you have installed the SFrame receive and send keys for an epoch (15 §3.7, §9.2). In an insecure call the C flag is 0 and none of this applies (18 §8.6).

Diagnostics

Record a sample every 10 s and once when the call closes, keep the last 30 (15 §14.1), and upload only what the user's setting allows (15 §14.2).

import {
  SampleRing,
  callFailureReport,
  diagnosticsAllowed,
  fitDiagnosticReport,
  type CallSample,
  type DiagnosticsSetting,
  type ServerClient,
} from '@sloppyvoice/sdk'

declare const server: ServerClient
declare const ctx: string
declare const callId: string
declare const setting: DiagnosticsSetting // 'failures' unless the user changed it
declare function collectSample(): CallSample

const samples = new SampleRing()
setInterval(() => samples.push(collectSample()), 10_000)

async function reportRelayFailure(code: string | null, rejoinAttempts: number): Promise<void> {
  if (!diagnosticsAllowed(setting, 'call_failure')) return
  const report = callFailureReport(
    { client: 'radio-bot/1.0', platform: 'bot', ctx, callId },
    { phase: 'relay_connect', code, security: 'insecure', outageMs: 0, rejoinAttempts, iceState: 'failed', dtlsState: 'new', samples: samples.list() },
  )
  const fitted = fitDiagnosticReport(report)
  await server.calls.sendDiagnostics({ ...fitted, data: { ...fitted.data } })
}
console.log(reportRelayFailure)

Never put media, keys, KIDs, SDP, ICE candidate addresses or other participants' names or addresses in a report (15 §14.2). Apply the upload bounds of 16 §13 and 17 §14 to the audio and video members of your samples first; then fitDiagnosticReport drops the oldest samples until the report fits in 64 KiB, and throws if it can't fit even without them, and CallsApi.sendDiagnostics refuses a larger body locally (15 §14.3).