oficina / meet Public

Calls: the browser asks each sender for less video when what arrives from them suffers, and sends less when asked (spec 15.30)

Per sender, on the receiving side: down a level after ten seconds of
freezes, loss, a deep jitter buffer or dropped frames, two for severe
trouble; up one after 45 s clean, as a probe whose failure doubles the
wait to five minutes. The sender sets that one connection's camera and
screen parameters; a screen keeps its size, loses frame rate first and is
never paused, and the camera gives way to it. Devices gains Video quality:
Auto, Low bandwidth, Audio only. Tiles say Low bandwidth and Video paused
to keep audio clear; the sender says who it is sending less to.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 97be4289be3ee4502d3803ce3e165288cc875114 parent 7d78cb8
6 files changed, +916 −9
  • Makefile +1 −0
  • internal/calls/static/calls.css +18 −0
  • internal/calls/static/room.js +594 −9
  • internal/calls/templates/room.html +11 −0
  • test/browser/room-adapt.test.mjs +286 −0
  • test/browser/room-mute.test.mjs +6 −0
diff --git a/Makefile b/Makefile
index 09e2561..f9579cf 100644
--- a/Makefile
+++ b/Makefile
@@ -153,6 +153,7 @@ browser:
node --test test/browser/room-screen.test.mjs
node --test test/browser/room-reconnect.test.mjs
node --test test/browser/room-recovery.test.mjs
+ node --test test/browser/room-adapt.test.mjs
node --test test/browser/room-connecting.test.mjs
node --test test/browser/room-glow.test.mjs
node --test test/browser/room-layout.test.mjs
diff --git a/internal/calls/static/calls.css b/internal/calls/static/calls.css
index f378f2e..0987246 100644
--- a/internal/calls/static/calls.css
+++ b/internal/calls/static/calls.css
@@ -920,6 +920,16 @@ body:has(> .calls-window) { background: var(--rst-bg); }
.calls-tile-off .icon { inline-size: 2rem; block-size: 2rem; }
.calls-tile-camera-off .calls-tile-name { z-index: 1; }
+/* Spec §15.30: "Low bandwidth" beside the name while this browser asks
+ that person for less video — the vendored badge's word, quiet like
+ Muted — and, at Audio only, the camera-off cover's shape with its own
+ words, and a smaller line for an app too old to send less. */
+.calls-tile-low { display: inline-flex; align-items: center; flex: none; }
+.calls-tile-low[hidden] { display: none; }
+.calls-tile-video-paused .calls-tile-name { z-index: 1; }
+.calls-tile-paused-old { max-inline-size: 18rem; text-align: center; font-size: var(--rst-fs-xs); opacity: 0.8; }
+.calls-tile-paused-old[hidden] { display: none; }
+
/* Our own preview, when the browser will not play it (room.js's
self-view watch, 2026-10-21): never a black box with nothing said.
The whole tile is the button, because the floating self view on a
@@ -1025,6 +1035,14 @@ body:has(> .calls-window) { background: var(--rst-bg); }
.calls-tile-name > span:first-child { flex: 0 1 auto; min-inline-size: 0; }
.calls-tile-off { --calls-caption-clear: 2rem; }
.calls-tile-name > :not(:first-child) { flex: none; }
+ .calls-tile-low:not([hidden]) {
+ position: absolute;
+ inline-size: 1px;
+ block-size: 1px;
+ overflow: hidden;
+ clip-path: inset(50%);
+ white-space: nowrap;
+ }
.calls-tile-muted > :not(svg) {
position: absolute;
inline-size: 1px;
diff --git a/internal/calls/static/room.js b/internal/calls/static/room.js
index 82a46ac..1c58cbe 100644
--- a/internal/calls/static/room.js
+++ b/internal/calls/static/room.js
@@ -111,6 +111,9 @@
const rawInput = rawRow ? rawRow.querySelector('input[type="checkbox"]') : null;
const shareModeRow = $('share-mode-row');
const pickShareMode = $('pick-share-mode');
+ // §15.30's own choice: Auto, Low bandwidth, Audio only.
+ const videoQualityRow = $('video-quality-row');
+ const pickVideoQuality = $('pick-video-quality');
const DEVICE_KEY = 'meet.devices';
const BACKOFF_MIN = 500;
@@ -395,6 +398,50 @@
// counted as time a notice was showing: a suspended tab's timers stop,
// and the gap when they start again is not a notice someone saw.
const QUALITY_LOOK_MAX = 1000;
+ // §15.30 (2026-10-28): adaptive video. Every receiver watches what
+ // arrives from each sender and asks that sender, through its own media
+ // report, for one of four levels; the sender applies it to that one
+ // connection's sender parameters. Down quickly, up slowly, and a probe up
+ // that fails doubles the wait before the next. The apps' VideoAdapt has
+ // the same numbers; test/browser/room-adapt.test.mjs and
+ // VideoAdaptTests hold both.
+ const ADAPT_LEVELS = ['normal', 'reduced', 'minimal', 'audio'];
+ const ADAPT_WINDOW = 10000; // the trouble window, and the time at a level before a step down
+ const ADAPT_SEVERE_AFTER = 5000; // severe trouble steps two levels after this long
+ const ADAPT_DOWN_FREEZES = 2; // camera freezes in the window
+ const ADAPT_DOWN_LOSS = 0.05; // packets lost in the window, of all inbound
+ const ADAPT_DOWN_RTT = 600; // ms, counted with at least one freeze
+ const ADAPT_DOWN_JITTER_BUFFER = 500; // ms, the audio jitter buffer's mean delay
+ const ADAPT_DOWN_DROPPED = 0.25; // frames dropped, of decoded and dropped, at least ADAPT_DOWN_DROPPED_MIN
+ const ADAPT_DOWN_DROPPED_MIN = 10;
+ const ADAPT_SEVERE_FREEZES = 5;
+ const ADAPT_SEVERE_FREEZE_SECONDS = 4; // seconds frozen in the window
+ const ADAPT_SEVERE_LOSS = 0.15;
+ const ADAPT_CLEAN_LOSS = 0.02; // a clean second: no freeze, loss at most this,
+ const ADAPT_CLEAN_RTT = 400; // a round trip under this (ms),
+ const ADAPT_CLEAN_JITTER_BUFFER = 300; // and the jitter buffer under this (ms)
+ const ADAPT_UP_AFTER = 45000; // clean this long at a level, then probe one up
+ const ADAPT_PROBE_WATCH = 20000; // trouble this soon after a probe steps back
+ const ADAPT_PROBE_JUDGE = 5000; // and is judged on at least this much of it
+ const ADAPT_UP_MAX = 300000; // the probe's wait doubles to at most this
+ // What each level sends (the sender's half). The camera: its bitrate,
+ // frame rate, and the box its picture is fitted into (long side, short
+ // side). The screen keeps its size and gives up frame rate first, and
+ // only at minimal is it made smaller; it is never paused.
+ const ADAPT_CAMERA = [null,
+ { maxBitrate: 350000, maxFramerate: 15, long: 640, short: 360 },
+ { maxBitrate: 120000, maxFramerate: 8, long: 320, short: 180 }];
+ const ADAPT_SCREEN = [null,
+ { maxBitrate: 1200000, maxFramerate: 10 },
+ { maxBitrate: 500000, maxFramerate: 5, long: 1280 }];
+ // An app older than this ignores a request; its video can only be hidden
+ // here, which saves this device's work and not the connection.
+ const ADAPT_MIN_NATIVE_VERSION = '0.4.14';
+ // How long the sender's "Sending reduced video to …" stays up.
+ const ADAPT_NOTICE_FOR = 8000;
+ // The person's own choice, in the Devices panel: Auto, Low bandwidth
+ // (minimal from everyone), Audio only (no video either way).
+ const VIDEO_SETTINGS = [['auto', 'Auto'], ['low', 'Low bandwidth'], ['audio', 'Audio only']];
// §5.4, sending: "Optimise shared screen for". What a screen gives up
// first when the uplink or the encoder cannot carry all of it. The
// first is the default; sharePlan says what each one means.
@@ -468,6 +515,18 @@
const screenSeen = new Map();
let screenStalled = [];
const screenAsks = new Map();
+ // §15.30: peer id -> the adaptive watch's record of what arrives from
+ // them; the asks this tab last put in its report (peer id -> level);
+ // what each connection is sending at, as asked (on the entry); the
+ // sender's notice and its timer; seconds at each level for the report;
+ // and, for the gate, the watch's up wait.
+ const adapt = new Map();
+ let videoAsks = {};
+ let adaptNoticeTimer = 0;
+ let adaptNoticeShown = '';
+ const videoTime = new Map();
+ let adaptUpAfter = ADAPT_UP_AFTER;
+ let adaptPolledAt = 0;
let shareRecovery = '';
let screenStallTestUntil = 0;
// §15.22: each arriving screen's statistics at the last poll and when
@@ -821,19 +880,28 @@
// tuneShare puts one connection's screen and camera where the mode
// wants them: the screen at its plan, the camera capped beside it —
// or, with nothing shared, the camera back at its defaults.
+ //
+ // §15.30: at the level this connection's peer asks of us
+ // (entry.sentLevel), and with no camera at all to anyone while the
+ // person's own Video quality is Audio only.
function tuneShare(entry) {
if (!entry) return;
const sharing = !!(share && entry.shareTx);
+ const level = entry.sentLevel || 0;
if (sharing) {
const s = share.track.getSettings ? share.track.getSettings() : {};
- const plan = sharePlan(shareMode(), s.width, s.height);
+ const plan = screenAtLevel(sharePlan(shareMode(), s.width, s.height), level, s.width, s.height);
tuneSender(entry.shareTx.sender, plan.encoding, plan.degradationPreference);
}
const camera = senderFor(entry, 'video');
const track = camera && camera.sender && camera.sender.track;
if (!track) return;
const settings = track.getSettings ? track.getSettings() : {};
- tuneSender(camera.sender, cameraCap(sharing, settings.height || 0));
+ const encoding = cameraAtLevel(videoSetting() === 'audio' ? 3 : level, sharing, settings.width || 0, settings.height || 0);
+ // The camera watch's to know: a camera paused on purpose encodes
+ // nothing, and that is not a stalled encoder.
+ entry.cameraPaused = encoding.active === false;
+ tuneSender(camera.sender, encoding);
}
// startLocal walks down a ladder: the remembered devices, then the
@@ -2044,6 +2112,10 @@
addShareTo(entry);
upgradeWhenQuiet(entry);
adoptWhenQuiet(id, entry);
+ // §15.30: a connection that settles is given what its peer asks of
+ // us, and the person's own Audio only — a new connection's senders
+ // have no parameters to set until it has.
+ if (pc.signalingState === 'stable' && (entry.sentLevel || videoSetting() === 'audio')) tuneShare(entry);
// And it is when an ask the negotiation rounds ran out on gets
// its turn (Codex S4-8): a connection that was mid-negotiation is
// the usual reason they ran out, and this is it settling.
@@ -4389,6 +4461,19 @@
}
out.hearing = ids;
}
+ // §15.30: what they ask each sender for, the wire's levels only.
+ if (value.video && typeof value.video === 'object' && !Array.isArray(value.video)) {
+ const asks = {};
+ let n = 0;
+ for (const [id, level] of Object.entries(value.video)) {
+ if (n >= 15) break;
+ if (/^[0-9a-f]{32}$/.test(id) && ['reduced', 'minimal', 'audio'].includes(level)) {
+ asks[id] = level;
+ n += 1;
+ }
+ }
+ if (n) out.video = asks;
+ }
return out;
}
@@ -4406,6 +4491,9 @@
if (m.noSoundFrom && m.noSoundFrom.length) key += ':' + m.noSoundFrom.slice().sort().join(',');
if (m.screenStalled && m.screenStalled.length) key += '/' + m.screenStalled.slice().sort().join(',');
if (Array.isArray(m.hearing)) key += '|' + m.hearing.slice().sort().join(',');
+ if (m.video && Object.keys(m.video).length) {
+ key += '>' + Object.keys(m.video).sort().map((id) => id + '=' + m.video[id]).join(',');
+ }
return key;
}
@@ -4415,7 +4503,9 @@
function localMedia() {
const hasAudio = !!(local && local.getAudioTracks().length);
const hasVideo = !!(local && local.getVideoTracks().length);
- return { muted: !!prefs.muted || !hasAudio, cameraOff: !!prefs.cameraOff || !hasVideo };
+ // §15.30: Audio only stops the camera going to anyone, so it is off as
+ // far as anyone watching can tell.
+ return { muted: !!prefs.muted || !hasAudio, cameraOff: !!prefs.cameraOff || !hasVideo || videoSetting() === 'audio' };
}
// mediaPayload is the report itself: §15.19's two booleans, and
@@ -4424,7 +4514,7 @@
// is good news, and its presence tells the others this tab says who it
// hears. `plain` is a server that has refused the extras once. Pure,
// and lifted by name in the node test.
- function mediaPayload(mine, blocked, silentFrom, plain, stalled, heard) {
+ function mediaPayload(mine, blocked, silentFrom, plain, stalled, heard, asks) {
const out = { muted: !!mine.muted, cameraOff: !!mine.cameraOff };
if (plain) return out;
if (blocked) out.audioBlocked = true;
@@ -4432,6 +4522,8 @@
// §15.21: whose screens have stalled here, bad news only, like the rest.
if (stalled && stalled.length) out.screenStalled = stalled.slice(0, 15);
if (Array.isArray(heard)) out.hearing = heard.slice(0, 15);
+ // §15.30: what this tab asks each sender for, only those below normal.
+ if (asks && Object.keys(asks).length) out.video = Object.assign({}, asks);
return out;
}
@@ -4447,7 +4539,7 @@
// as muted or not matters more than being heard as unable to hear.
function reportMedia() {
if (!state.admitted || state.stopped || !state.peer) return;
- const now = mediaPayload(localMedia(), audioBlocked, noSoundList(), !mediaExtras, screenStalled, hearingList());
+ const now = mediaPayload(localMedia(), audioBlocked, noSoundList(), !mediaExtras, screenStalled, hearingList(), videoAsks);
const key = mediaKey(now);
if (key === mediaSent) return;
mediaSent = key;
@@ -4477,10 +4569,13 @@
learnMedia(rp.peer, rp.media);
continue;
}
- const now = mediaPayload(localMedia(), audioBlocked, noSoundList(), !mediaExtras, screenStalled, hearingList());
+ const now = mediaPayload(localMedia(), audioBlocked, noSoundList(), !mediaExtras, screenStalled, hearingList(), videoAsks);
mediaSent = sameMedia(mediaFrom(rp.media), now) ? mediaKey(now) : '';
}
reportMedia();
+ // §15.30: and what each of them asks of us now.
+ answerVideoAsks();
+ for (const id of pcs.keys()) markAdapt(id);
}
// learnMedia records a roster's or a peer event's word on one peer.
@@ -4503,6 +4598,398 @@
announceMedia(mediaChange(msg.name || names.get(id) || 'Someone', before, next));
markTile(id, next);
answerScreenStalls();
+ answerVideoAsks();
+ markAdapt(id);
+ }
+
+ // ---------------------------------------------------------------
+ // Adaptive video (§15.30, 2026-10-28)
+ // ---------------------------------------------------------------
+ //
+ // Paul, after a Dublin–London call whose guest was on café Wi-Fi in
+ // Safari, relayed, at 840–1300 ms round trips, seeing up to seven
+ // freezes every thirty seconds in his video: "Low-bandwidth with
+ // auto-switching up and down." Audio mattered most.
+ //
+ // It is a mesh, so every pair has its own sender, and the one who can
+ // see the trouble is the receiver. So each receiver watches what arrives
+ // from each sender — camera freezes, packet loss, the jitter buffer, the
+ // round trip, frames dropped — and asks that sender for a level in its
+ // own media report (`video`, peer id -> level, only the ones below
+ // normal). The sender reads its own id in each report and sets that one
+ // connection's sender parameters: no renegotiation, and audio is never
+ // touched. A shared screen keeps its size and gives up frame rate first,
+ // and is never paused; while one is going, the camera gives way first.
+
+ // adaptRecord is one sender's watch, on the receiving side. `upAfter` is
+ // the clean time before the first probe up (ADAPT_UP_AFTER, shortened
+ // only by the gate's hook). Pure, as is everything down to adaptAsks;
+ // test/browser/room-adapt.test.mjs lifts them by name.
+ function adaptRecord(upAfter) {
+ const base = upAfter || ADAPT_UP_AFTER;
+ return { level: 0, since: null, samples: [], cleanSince: null, upBase: base, upWait: base,
+ probeAt: null, probeFrom: 0, downs: 0, ups: 0 };
+ }
+
+ // adaptSample is one second of what arrived from a sender, from
+ // qualityPeer's deltas: camera freezes (only while the camera is to be
+ // watched — on, and the tab visible — because a still screen's gaps and
+ // a hidden tab's unpainted frames are not freezes), packets and loss
+ // across audio, camera and screen, the round trip, the audio jitter
+ // buffer, and frames decoded and dropped. Null when nothing at all
+ // arrived and nothing was measured: a connection that is down is
+ // §15.28's to mend, and says nothing about the link's width.
+ function adaptSample(q, cameraWatched) {
+ const inb = (q && q.in) || {};
+ const a = inb.audio || {};
+ const v = inb.video || {};
+ const s = inb.screen || {};
+ const packets = (a.packets || 0) + (v.packets || 0) + (s.packets || 0);
+ const lost = (a.lost || 0) + (v.lost || 0) + (s.lost || 0);
+ const rtt = q && typeof q.rtt === 'number' ? q.rtt : null;
+ if (packets + lost === 0 && rtt === null) return null;
+ return {
+ freezes: cameraWatched ? v.freezes || 0 : 0,
+ freezeSeconds: cameraWatched ? v.freezeSeconds || 0 : 0,
+ packets,
+ lost,
+ rtt,
+ jitterBufferMs: typeof a.jitterBufferMs === 'number' ? a.jitterBufferMs : null,
+ decoded: (v.decoded || 0) + (s.decoded || 0),
+ dropped: (v.dropped || 0) + (s.dropped || 0),
+ };
+ }
+
+ // adaptWindow sums the samples in the window: counts added up, the
+ // round trip as their median (one spike is not a slow link), the jitter
+ // buffer as their mean.
+ function adaptWindow(samples) {
+ const w = { freezes: 0, freezeSeconds: 0, packets: 0, lost: 0, decoded: 0, dropped: 0, rtt: null, jitterBuffer: null };
+ const rtts = [];
+ const jbs = [];
+ for (const x of samples) {
+ w.freezes += x.freezes;
+ w.freezeSeconds += x.freezeSeconds;
+ w.packets += x.packets;
+ w.lost += x.lost;
+ w.decoded += x.decoded;
+ w.dropped += x.dropped;
+ if (x.rtt !== null) rtts.push(x.rtt);
+ if (x.jitterBufferMs !== null) jbs.push(x.jitterBufferMs);
+ }
+ if (rtts.length) {
+ rtts.sort((p, q) => p - q);
+ w.rtt = rtts[Math.floor(rtts.length / 2)];
+ }
+ if (jbs.length) w.jitterBuffer = jbs.reduce((p, q) => p + q, 0) / jbs.length;
+ w.loss = w.packets + w.lost > 0 ? w.lost / (w.packets + w.lost) : 0;
+ return w;
+ }
+
+ // adaptTrouble is a window's verdict: 'severe', 'trouble' or ''.
+ function adaptTrouble(w) {
+ if (w.freezes >= ADAPT_SEVERE_FREEZES || w.freezeSeconds >= ADAPT_SEVERE_FREEZE_SECONDS ||
+ w.loss > ADAPT_SEVERE_LOSS) {
+ return 'severe';
+ }
+ if (w.freezes >= ADAPT_DOWN_FREEZES || w.loss > ADAPT_DOWN_LOSS ||
+ (w.rtt !== null && w.rtt >= ADAPT_DOWN_RTT && w.freezes >= 1) ||
+ (w.jitterBuffer !== null && w.jitterBuffer >= ADAPT_DOWN_JITTER_BUFFER) ||
+ (w.dropped >= ADAPT_DOWN_DROPPED_MIN && w.dropped >= ADAPT_DOWN_DROPPED * (w.decoded + w.dropped))) {
+ return 'trouble';
+ }
+ return '';
+ }
+
+ // adaptClean is whether one second was clean, for the slow way up.
+ function adaptClean(x) {
+ const n = x.packets + x.lost;
+ return x.freezes === 0 && x.freezeSeconds === 0 && (n === 0 || x.lost / n <= ADAPT_CLEAN_LOSS) &&
+ (x.rtt === null || x.rtt < ADAPT_CLEAN_RTT) &&
+ (x.jitterBufferMs === null || x.jitterBufferMs < ADAPT_CLEAN_JITTER_BUFFER);
+ }
+
+ // adaptMove changes the level, and starts the watch again from nothing:
+ // the new level is judged on what it does, not on what the old one did.
+ function adaptMove(rec, now, level, up) {
+ if (up) rec.ups += 1;
+ else rec.downs += 1;
+ rec.level = level;
+ rec.since = now;
+ rec.samples = [];
+ rec.cleanSince = null;
+ if (!up) rec.probeAt = null;
+ return level;
+ }
+
+ // adaptStep is one look, about once a second, with that second's sample
+ // (or null for none). Returns the level, 0 normal to 3 audio only.
+ //
+ // down one level once the window at this level has been trouble for
+ // ADAPT_WINDOW; two at once for severe trouble, after
+ // ADAPT_SEVERE_AFTER
+ // up one level after `upWait` of clean seconds in a row, as a
+ // probe: trouble within ADAPT_PROBE_WATCH of it (judged on at
+ // least ADAPT_PROBE_JUDGE) steps straight back and doubles the
+ // wait, to at most ADAPT_UP_MAX; a probe that holds puts the
+ // wait back to its base
+ function adaptStep(rec, now, sample) {
+ if (rec.since === null) rec.since = now;
+ if (!sample) return rec.level;
+ rec.samples.push(Object.assign({ at: now }, sample));
+ while (rec.samples.length && rec.samples[0].at <= now - ADAPT_WINDOW) rec.samples.shift();
+ const observed = now - rec.since;
+ const verdict = adaptTrouble(adaptWindow(rec.samples));
+ if (adaptClean(sample)) {
+ if (rec.cleanSince === null) rec.cleanSince = now;
+ } else {
+ rec.cleanSince = null;
+ }
+ const top = ADAPT_LEVELS.length - 1;
+ if (rec.probeAt !== null) {
+ if (now - rec.probeAt < ADAPT_PROBE_WATCH) {
+ if (verdict && observed >= ADAPT_PROBE_JUDGE) {
+ rec.upWait = Math.min(rec.upWait * 2, ADAPT_UP_MAX);
+ return adaptMove(rec, now, rec.probeFrom, false);
+ }
+ } else {
+ rec.probeAt = null;
+ rec.upWait = rec.upBase;
+ }
+ }
+ if (verdict === 'severe' && observed >= ADAPT_SEVERE_AFTER && rec.level < top) {
+ return adaptMove(rec, now, Math.min(top, rec.level + 2), false);
+ }
+ if (verdict && observed >= ADAPT_WINDOW && rec.level < top) {
+ return adaptMove(rec, now, rec.level + 1, false);
+ }
+ if (rec.level > 0 && rec.cleanSince !== null && now - rec.cleanSince >= rec.upWait) {
+ const from = rec.level;
+ adaptMove(rec, now, from - 1, true);
+ rec.probeAt = now;
+ rec.probeFrom = from;
+ }
+ return rec.level;
+ }
+
+ // videoFloor is the person's own setting as a level: Low bandwidth asks
+ // everyone for minimal, Audio only for no video; Auto leaves it to the
+ // watch.
+ function videoFloor(setting) {
+ if (setting === 'audio') return 3;
+ if (setting === 'low') return 2;
+ return 0;
+ }
+
+ // adaptAsks is the `video` object for the report: every peer whose level
+ // — the watch's or the setting's, whichever is lower — is below normal.
+ // `levels` is peer id -> the watch's level.
+ function adaptAsks(levels, setting) {
+ const out = {};
+ const floor = videoFloor(setting);
+ for (const [id, level] of levels) {
+ const at = Math.max(level || 0, floor);
+ if (at > 0 && Object.keys(out).length < 15) out[id] = ADAPT_LEVELS[at];
+ }
+ return out;
+ }
+
+ // askedOf is what one peer's report asks of us, as a level index.
+ function askedOf(media, me) {
+ const at = media && media.video && me ? ADAPT_LEVELS.indexOf(media.video[me]) : -1;
+ return at > 0 ? at : 0;
+ }
+
+ // cameraAtLevel is the camera's encoding for one receiver at a level.
+ // While a screen is going out the camera gives way first: normal is
+ // §5.4's cap beside the screen, and every level below is one lower for
+ // the camera, so a receiver at minimal gets the screen and no camera.
+ // `width` and `height` are the camera's own, fitted by their long and
+ // short sides so a portrait camera is boxed the right way round.
+ function cameraAtLevel(level, sharing, width, height) {
+ const at = sharing && level > 0 ? Math.min(3, level + 1) : level;
+ if (at <= 0) return Object.assign({ maxFramerate: undefined, active: true }, cameraCap(sharing, height || 0));
+ const c = ADAPT_CAMERA[Math.min(at, 2)];
+ const long = Math.max(width || 0, height || 0);
+ const short = Math.min(width || 0, height || 0);
+ return {
+ maxBitrate: c.maxBitrate,
+ maxFramerate: c.maxFramerate,
+ scaleResolutionDownBy: Math.max(1, long / c.long, short / c.short),
+ active: at < 3,
+ };
+ }
+
+ // screenAtLevel is sharePlan's answer for one receiver at a level: the
+ // frame rate and bitrate lowered first, the size kept, and only at
+ // minimal and below the long side brought to ADAPT_SCREEN's. Resolution
+ // is held under pressure from then on (maintain-resolution), because a
+ // screen is for reading. Never paused.
+ function screenAtLevel(plan, level, width, height) {
+ if (level <= 0) return plan;
+ const c = ADAPT_SCREEN[Math.min(level, 2)];
+ const encoding = Object.assign({}, plan.encoding, {
+ maxFramerate: c.maxFramerate,
+ maxBitrate: Math.min(plan.encoding.maxBitrate || c.maxBitrate, c.maxBitrate),
+ });
+ if (c.long) {
+ const longest = Math.max(width || 0, height || 0);
+ encoding.scaleResolutionDownBy = Math.max(plan.encoding.scaleResolutionDownBy || 1, longest > c.long ? longest / c.long : 1);
+ }
+ return { contentHint: plan.contentHint, degradationPreference: 'maintain-resolution', encoding };
+ }
+
+ // honoursAsks is whether a peer's client acts on a request: every
+ // browser (its page is this server's), and an app from
+ // ADAPT_MIN_NATIVE_VERSION on.
+ function honoursAsks(client) {
+ const c = parseClient(client || '');
+ if (!c) return !client;
+ return compareVersions(c.version, ADAPT_MIN_NATIVE_VERSION) >= 0;
+ }
+
+ // adaptNoticeWords is the sender's quiet notice for the people it is
+ // sending less to, by name: '' for nobody.
+ function adaptNoticeWords(people) {
+ if (!people.length) return '';
+ const names = people.map((p) => p.name);
+ const list = names.length === 1 ? names[0]
+ : names.slice(0, -1).join(', ') + ' and ' + names[names.length - 1];
+ const weak = names.length === 1 ? '(their connection is weak)' : '(their connections are weak)';
+ if (people.every((p) => p.level >= 3)) return 'Sending only audio to ' + list + ' ' + weak;
+ return 'Sending reduced video to ' + list + ' ' + weak;
+ }
+
+ // videoSetting is the person's choice, Auto unless they made one.
+ function videoSetting() {
+ return VIDEO_SETTINGS.some(([v]) => v === prefs.videoQuality) ? prefs.videoQuality : 'auto';
+ }
+
+ // adaptLook is one connection's second, from the stats walk pollFrames
+ // already makes: qualityReading's parse of it, the delta from the last
+ // one, and a step of that sender's watch.
+ function adaptLook(id, entry, stats, now) {
+ const reading = qualityReading(stats, (r) => qualityKind(id, entry, r));
+ const prev = entry.adaptReading;
+ entry.adaptReading = { pc: entry.pc, reading, at: now };
+ if (!prev || prev.pc !== entry.pc || now <= prev.at) return;
+ const q = qualityPeer(prev.reading, reading, (now - prev.at) / 1000);
+ const media = remoteMedia.get(id) || null;
+ const watched = !(media && media.cameraOff) && !(typeof document !== 'undefined' && document.hidden);
+ let rec = adapt.get(id);
+ if (!rec) {
+ rec = adaptRecord(adaptUpAfter);
+ adapt.set(id, rec);
+ }
+ const before = rec.level;
+ adaptStep(rec, now, adaptSample(q, watched));
+ if (rec.level !== before) {
+ console.info('calls: video from ' + id.slice(0, 6) + ' ' + ADAPT_LEVELS[before] + ' -> ' +
+ ADAPT_LEVELS[rec.level] + (rec.level < before ? ' (probe)' : ''));
+ }
+ }
+
+ // answerAdapt runs after each stats walk: the asks this tab makes, sent
+ // when they change; the tiles' badges; and the seconds at each level,
+ // asked and sent, for the next quality report.
+ function answerAdapt(now, dt) {
+ for (const id of Array.from(adapt.keys())) if (!pcs.has(id)) adapt.delete(id);
+ const levels = new Map();
+ for (const id of pcs.keys()) levels.set(id, adapt.has(id) ? adapt.get(id).level : 0);
+ const asks = adaptAsks(levels, videoSetting());
+ const changed = JSON.stringify(Object.entries(asks).sort()) !== JSON.stringify(Object.entries(videoAsks).sort());
+ videoAsks = asks;
+ if (changed) {
+ reportMedia();
+ for (const id of pcs.keys()) markAdapt(id);
+ }
+ const step = Math.min(Math.max(0, dt || 0), 2000) / 1000;
+ for (const [id, entry] of pcs) {
+ const asked = ADAPT_LEVELS.indexOf(asks[id] || 'normal');
+ const sent = entry.sentLevel || 0;
+ if (!step || (asked <= 0 && sent <= 0)) continue;
+ let t = videoTime.get(id);
+ if (!t) {
+ t = { asked: [0, 0, 0], sent: [0, 0, 0] };
+ videoTime.set(id, t);
+ }
+ if (asked > 0) t.asked[asked - 1] += step;
+ if (sent > 0) t.sent[sent - 1] += step;
+ }
+ }
+
+ // answerVideoAsks is the sender's half: each connection's senders set
+ // to what that peer last asked of us, and the notice when it changes.
+ function answerVideoAsks() {
+ let moved = false;
+ for (const [id, entry] of pcs) {
+ const level = askedOf(remoteMedia.get(id), state.peer);
+ if ((entry.sentLevel || 0) === level) continue;
+ console.info('calls: ' + id.slice(0, 6) + ' asks for ' + ADAPT_LEVELS[level] + ' video');
+ if (level > (entry.sentLevel || 0)) moved = true;
+ entry.sentLevel = level;
+ tuneShare(entry);
+ }
+ const people = [];
+ for (const [id, entry] of pcs) {
+ if (entry.sentLevel > 0) people.push({ name: names.get(id) || 'Someone', level: entry.sentLevel });
+ }
+ const words = adaptNoticeWords(people);
+ if (!words) {
+ showAdaptNotice('');
+ } else if (moved && words !== adaptNoticeShown) {
+ showAdaptNotice(words);
+ }
+ }
+
+ // applyVideoSetting is the person's choice taking effect: what this tab
+ // asks of everyone, its own camera to everyone, and its report.
+ function applyVideoSetting() {
+ console.info('calls: video quality ' + videoSetting());
+ answerAdapt(Date.now(), 0);
+ for (const entry of pcs.values()) tuneShare(entry);
+ applyToggles();
+ for (const id of pcs.keys()) markAdapt(id);
+ }
+
+ // showAdaptNotice puts the sender's notice up for ADAPT_NOTICE_FOR, once
+ // per change, and says it to a screen reader politely.
+ function showAdaptNotice(words) {
+ adaptNoticeShown = words;
+ const el = $('video-notice');
+ if (adaptNoticeTimer) clearTimeout(adaptNoticeTimer);
+ adaptNoticeTimer = 0;
+ if (!el) return;
+ el.textContent = words;
+ el.hidden = !words;
+ if (!words) return;
+ announceMedia(words);
+ adaptNoticeTimer = setTimeout(() => {
+ el.hidden = true;
+ el.textContent = '';
+ }, ADAPT_NOTICE_FOR);
+ }
+
+ // markAdapt draws one tile's level: the badge in its caption while this
+ // tab asks that person for less than normal, and, at audio only, the
+ // cover over their picture — which also hides it here for an app too
+ // old to send less.
+ function markAdapt(id) {
+ const t = tiles.get(id);
+ if (!t || !t.lowBadge) return;
+ const level = ADAPT_LEVELS.indexOf(videoAsks[id] || 'normal');
+ const who = names.get(id) || 'them';
+ const own = videoSetting() !== 'auto';
+ t.lowBadge.hidden = level <= 0;
+ t.lowBadge.title = level <= 0 ? '' : (own
+ ? 'Asking ' + who + ' for less video, as your Video quality setting says'
+ : 'Asking ' + who + ' for less video while your connection is weak');
+ t.lowBadge.setAttribute('aria-label', level <= 0 ? '' : 'Low bandwidth: ' + t.lowBadge.title);
+ const media = remoteMedia.get(id) || null;
+ const paused = level >= 3 && !(media && media.cameraOff);
+ t.videoPaused.hidden = !paused;
+ if (t.videoPausedOld) t.videoPausedOld.hidden = !paused || honoursAsks(clients.get(id) || '');
+ t.figure.classList.toggle('calls-tile-video-paused', paused);
}
// ---------------------------------------------------------------
@@ -5175,6 +5662,19 @@
return { call, peers };
}
+ // withVideoTime adds §15.30's seconds at each level, asked and sent, to
+ // one peer's events, only where there were any. Pure, and lifted by name
+ // in the node test.
+ function withVideoTime(events, t) {
+ if (!t) return events;
+ const out = Object.assign({}, events || {});
+ for (const k of ['asked', 'sent']) {
+ if (!t[k].some((x) => x > 0)) continue;
+ out[k + 'Seconds'] = t[k].map((x) => Math.round(Math.min(x, QUALITY_MAX_SECONDS) * 10) / 10);
+ }
+ return Object.keys(out).length ? out : events;
+ }
+
// qualityReport is the body POSTed to /m/{sqid}/quality
// (protocol.QualityReport). `o.peers` is [{id, prev, now, ladder,
// reattaches, events}]: the two readings, the §15.22 ladder's steps
@@ -5319,9 +5819,11 @@
ladder: shareCountsBy.get(id) || null,
reattaches: reattachesBy.get(id) || 0,
stalls: stallsBy.get(id) || null,
- events: events.peers.get(id) || null,
+ events: withVideoTime(events.peers.get(id) || null, videoTime.get(id)),
});
}
+ videoTime.clear();
+ if (videoSetting() !== 'auto') events.call.videoSetting = videoSetting();
for (const id of Array.from(qualityPrev.keys())) if (!pcs.has(id)) qualityPrev.delete(id);
shareCountsBy.clear();
reattachesBy.clear();
@@ -6338,6 +6840,31 @@
return { muted, off };
}
+ // adaptMarks are §15.30's: the "Low bandwidth" badge, the vendored
+ // badge from the page's template so the state is a word and not a
+ // colour, and the cover for a person whose video is paused to keep their
+ // audio clear, with the line for an app too old to send less.
+ function adaptMarks() {
+ const badge = document.createElement('span');
+ badge.className = 'calls-tile-low';
+ badge.hidden = true;
+ const badgeMark = $('tile-low-bandwidth');
+ if (badgeMark) badge.append(badgeMark.content.cloneNode(true));
+ else badge.textContent = 'Low bandwidth';
+ const cover = document.createElement('div');
+ cover.className = 'calls-tile-off calls-tile-video-paused-cover';
+ cover.hidden = true;
+ const coverMark = $('tile-video-paused');
+ if (coverMark) cover.append(coverMark.content.cloneNode(true));
+ else cover.textContent = 'Video paused to keep audio clear';
+ const old = document.createElement('span');
+ old.className = 'calls-tile-paused-old';
+ old.textContent = 'Their app can’t send less video, so it’s only hidden here';
+ old.hidden = true;
+ cover.append(old);
+ return { badge, cover, old };
+ }
+
// markTile shows or hides one tile's marks. `media` null is unknown.
function markTile(key, media) {
const t = tiles.get(key);
@@ -6345,6 +6872,7 @@
t.muted.hidden = !(media && media.muted);
t.off.hidden = !(media && media.cameraOff);
t.figure.classList.toggle('calls-tile-camera-off', !!(media && media.cameraOff));
+ if (t.lowBadge) markAdapt(key);
drawHearing(key);
}
@@ -7130,7 +7658,7 @@
// live-looking select that silently does nothing is the worse half
// of that, so they are disabled and say so.
if (devicesToggle) devicesToggle.disabled = !on;
- for (const el of [pickCamera, pickMic, pickSpeaker, rawInput, pickShareMode]) {
+ for (const el of [pickCamera, pickMic, pickSpeaker, rawInput, pickShareMode, pickVideoQuality]) {
if (el) el.disabled = !on;
}
}
@@ -7332,9 +7860,16 @@
paused.append(said, show);
paused.addEventListener('click', () => playSelf(t));
}
+ // §15.30's two, on another person's tile: the badge while this tab
+ // asks them for less video, and the cover at audio only.
+ const low = marks && !isSelf ? adaptMarks() : null;
if (marks) {
nameEl.after(marks.muted);
figure.append(marks.off);
+ if (low) {
+ marks.muted.after(low.badge);
+ figure.append(low.cover);
+ }
if (paused) figure.append(paused);
// After Play, so the caption's buttons keep their order.
label.append(hear.box, hear.notice);
@@ -7346,6 +7881,7 @@
t = {
figure, video, label, nameEl, note, retry, play,
muted: marks && marks.muted, off: marks && marks.off,
+ lowBadge: low && low.badge, videoPaused: low && low.cover, videoPausedOld: low && low.old,
hear, hearShown: '',
remove: null, stream: null, track: null, self: isSelf,
// What judgeRender remembers between polls: the element's own
@@ -7774,6 +8310,25 @@
});
}
+ // §15.30's "Video quality". Applied at once: the asks this tab makes of
+ // everyone, and — for Audio only — no camera to anyone, reported as off.
+ // Remembered with the devices, so the next call starts the same way.
+ if (pickVideoQuality && videoQualityRow) {
+ for (const [value, label] of VIDEO_SETTINGS) {
+ const option = document.createElement('option');
+ option.value = value;
+ option.textContent = label;
+ pickVideoQuality.append(option);
+ }
+ pickVideoQuality.value = videoSetting();
+ videoQualityRow.hidden = false;
+ pickVideoQuality.addEventListener('change', () => {
+ prefs.videoQuality = pickVideoQuality.value;
+ savePrefs();
+ applyVideoSetting();
+ });
+ }
+
// §5.4's gesture. The handler is not async: a rejection escaping one
// goes where neither a person nor a gate could see it, so the work is
// a named function with a catch of its own — the same shape as the
@@ -8165,7 +8720,7 @@
// an iPhone's camera paused. Disabled (camera off) is the person's
// own doing, and no more a stall.
if (!tx || !sends || !track || track.readyState === 'ended' || track.muted ||
- track.enabled === false ||
+ track.enabled === false || entry.cameraPaused ||
!report || typeof report.framesEncoded !== 'number') {
entry.cameraFrames = -1;
entry.cameraStalls = 0;
@@ -8430,6 +8985,8 @@
// §15.26: the quality report reads this walk rather than making
// one of its own.
entry.statsReport = stats;
+ // §15.30: and so does the adaptive watch.
+ adaptLook(id, entry, stats, Date.now());
const outbound = [];
// What the decoder is delivering, per tile: the fallback frame
// count where there is no requestVideoFrameCallback, and — in
@@ -8481,6 +9038,10 @@
}
watchScreens(screens, screenReports);
answerScreenStalls();
+ const at = Date.now();
+ answerAdapt(at, adaptPolledAt ? at - adaptPolledAt : 0);
+ adaptPolledAt = at;
+ answerVideoAsks();
qualityTick();
}
@@ -8638,6 +9199,17 @@
recoveryForTest(on) {
recoveryOn = !!on;
},
+ // §15.30, for the gate: the clean time before the watch's first probe
+ // up, shortened so a scenario can see a whole climb back; at least a
+ // second, at most the real one, and only for watches made after it.
+ adaptForTest(o) {
+ const up = Number(o && o.upAfter) || ADAPT_UP_AFTER;
+ adaptUpAfter = Math.max(1000, Math.min(up, ADAPT_UP_AFTER));
+ for (const r of adapt.values()) {
+ r.upBase = adaptUpAfter;
+ r.upWait = Math.min(r.upWait, adaptUpAfter);
+ }
+ },
stallScreenForTest(ms) {
screenStallTestUntil = Date.now() + Math.max(0, Math.min(Number(ms) || 0, 60000));
},
@@ -8742,6 +9314,19 @@
shareMode: shareMode(),
shareSend: Object.fromEntries(
Array.from(pcs, ([id, entry]) => [id, entry.shareSend || null])),
+ // §15.30: per peer, the watch's level and what this tab asks of
+ // them; what each asks of us and what we send them at; the
+ // person's setting; and the sender's notice as it stands.
+ adapt: Object.fromEntries(Array.from(pcs.keys(), (id) => {
+ const r = adapt.get(id);
+ const e = pcs.get(id);
+ return [id, { level: r ? ADAPT_LEVELS[r.level] : 'normal', asked: videoAsks[id] || 'normal',
+ sent: ADAPT_LEVELS[(e && e.sentLevel) || 0], downs: r ? r.downs : 0, ups: r ? r.ups : 0,
+ upWait: r ? r.upWait : adaptUpAfter, cameraPaused: !!(e && e.cameraPaused) }];
+ })),
+ videoAsks: Object.assign({}, videoAsks),
+ videoSetting: videoSetting(),
+ videoNotice: adaptNoticeShown,
// §15.19: what this tab reports, and what it has been told, by
// peer id. Peers that never reported are absent.
media: localMedia(),
diff --git a/internal/calls/templates/room.html b/internal/calls/templates/room.html
index 0665fdf..7b5536a 100644
--- a/internal/calls/templates/room.html
+++ b/internal/calls/templates/room.html
@@ -71,6 +71,9 @@
<p id="share-recovery" class="calls-share-recovery" role="status" hidden></p>
</div>
<p id="status" class="calls-status" role="status"></p>
+ {{/* Spec §15.30: the sender's quiet notice, for a few seconds after
+ someone asks for less of its video. */}}
+ <p id="video-notice" class="calls-status calls-video-notice" role="status" data-quiet hidden></p>
{{/* §5.5's relay notice, once a session: call-window.js shows it on
the first visit of a tab's session and it stays until it is put
away. */}}
@@ -164,6 +167,10 @@
{{/* §5.4: what a shared screen gives up first when the connection
cannot carry all of it. room.js fills the options, remembers the
choice and reveals the row in a browser that can share. */}}
+ {{/* Spec §15.30: Auto lowers and raises the video each person sends
+ here as the connection allows; the other two are the person's
+ own floor. room.js fills the options and remembers the choice. */}}
+ <div id="video-quality-row" hidden>{{template "field-select" dict "ID" "pick-video-quality" "Name" "video-quality" "Label" "Video quality" "Help" "Auto lowers video when a connection is weak and raises it again when it recovers. Low bandwidth asks everyone for small video. Audio only pauses video both ways, to keep sound clear."}}</div>
<div id="share-mode-row" hidden>{{template "field-select" dict "ID" "pick-share-mode" "Name" "share-mode" "Label" "Optimise shared screen for" "Help" "Balanced keeps text readable and keeps up with scrolling. Text and detail keeps small print sharp; movement may look jerky. Motion and video keeps movement smooth; text may look softer."}}</div>
{{/* Device messages get a live region of their own, like the relay
warning: renderStatus owns #status and rewrites it on every
@@ -235,6 +242,10 @@
plain one; the icon is on top of it, never instead. */}}
<template id="tile-muted">{{icon "mic-off"}}{{template "badge" dict "Label" "Muted"}}</template>
<template id="tile-camera-off">{{icon "video-off"}}<span>Camera off</span></template>
+ {{/* Spec §15.30: while this browser asks someone for less video, the
+ badge by their name; at Audio only, the cover over their picture. */}}
+ <template id="tile-low-bandwidth">{{template "badge" dict "Label" "Low bandwidth"}}</template>
+ <template id="tile-video-paused">{{icon "video-off"}}<span>Video paused to keep audio clear</span></template>
{{/* Each tile's arrangement buttons, which call-layout.js clones and
names: a Pinned badge while the tile is pinned, and ⋯, which opens
#tile-menu for that tile. */}}
diff --git a/test/browser/room-adapt.test.mjs b/test/browser/room-adapt.test.mjs
new file mode 100644
index 0000000..5f8860e
--- /dev/null
+++ b/test/browser/room-adapt.test.mjs
@@ -0,0 +1,286 @@
+// room-adapt.test.mjs — adaptive video (spec §15.30, 2026-10-28), gated
+// without a browser.
+//
+// node --test test/browser/room-adapt.test.mjs
+//
+// The receiver's watch (adaptStep and its helpers: down fast, up slow, a
+// probe up that fails doubling the wait), what a sender sends at each level
+// (the camera giving way before a shared screen, a screen never paused),
+// and the report's `video` member, lifted out of the shipped room.js by
+// name with the constants they read, on a fake clock. The apps'
+// VideoAdaptTests are the twin of these, number for number.
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+const src = readFileSync(fileURLToPath(new URL('../../internal/calls/static/room.js', import.meta.url)), 'utf8');
+
+function lift(name) {
+ const start = src.indexOf('function ' + name + '(');
+ assert.notEqual(start, -1, name + ' is not in room.js any more — this test is stale, not passing');
+ let depth = 0;
+ for (let i = src.indexOf('{', start); i < src.length; i++) {
+ if (src[i] === '{') depth += 1;
+ else if (src[i] === '}') {
+ depth -= 1;
+ if (depth === 0) return src.slice(start, i + 1);
+ }
+ }
+ assert.fail('unbalanced braces reading ' + name);
+}
+function liftConst(name) {
+ const m = src.match(new RegExp('const ' + name + ' = ([^;]+);'));
+ assert.ok(m, name + ' is not a const in room.js any more');
+ return 'const ' + name + ' = ' + m[1] + ';';
+}
+const CONSTS = ['ADAPT_LEVELS', 'ADAPT_WINDOW', 'ADAPT_SEVERE_AFTER', 'ADAPT_DOWN_FREEZES', 'ADAPT_DOWN_LOSS',
+ 'ADAPT_DOWN_RTT', 'ADAPT_DOWN_JITTER_BUFFER', 'ADAPT_DOWN_DROPPED', 'ADAPT_DOWN_DROPPED_MIN', 'ADAPT_SEVERE_FREEZES',
+ 'ADAPT_SEVERE_FREEZE_SECONDS', 'ADAPT_SEVERE_LOSS', 'ADAPT_CLEAN_LOSS', 'ADAPT_CLEAN_RTT', 'ADAPT_CLEAN_JITTER_BUFFER',
+ 'ADAPT_UP_AFTER', 'ADAPT_PROBE_WATCH', 'ADAPT_PROBE_JUDGE', 'ADAPT_UP_MAX', 'ADAPT_CAMERA', 'ADAPT_SCREEN',
+ 'ADAPT_MIN_NATIVE_VERSION', 'QUALITY_MAX_SECONDS'].map(liftConst).join('\n');
+const NAMES = ['adaptRecord', 'adaptSample', 'adaptWindow', 'adaptTrouble', 'adaptClean', 'adaptMove', 'adaptStep',
+ 'videoFloor', 'adaptAsks', 'askedOf', 'cameraCap', 'cameraAtLevel', 'sharePlan', 'screenAtLevel', 'parseClient',
+ 'compareVersions', 'honoursAsks', 'adaptNoticeWords', 'withVideoTime', 'mediaFrom', 'mediaKey', 'mediaPayload'];
+// eslint-disable-next-line no-new-func
+const r = new Function(CONSTS + '\n' + NAMES.map(lift).join('\n') + '; return { ' + NAMES.join(', ') +
+ ', ADAPT_UP_AFTER, ADAPT_UP_MAX };')();
+
+const P1 = 'a'.repeat(32);
+const P2 = 'b'.repeat(32);
+
+// Trouble that is not severe: a freeze every four seconds, two or three in
+// any ten.
+const freezing = (t) => clean({ freezes: t % 4 === 0 ? 1 : 0 });
+
+// One second's sample: clean unless told otherwise.
+const clean = (o = {}) => Object.assign({ freezes: 0, freezeSeconds: 0, packets: 100, lost: 0, rtt: 80,
+ jitterBufferMs: 60, decoded: 30, dropped: 0 }, o);
+
+// Once a second from `from` to `to` seconds (inclusive), each second's
+// sample from `at(t)`; the level after every look, and the seconds it
+// changed at.
+function run(rec, from, to, at) {
+ const changes = [];
+ for (let t = from; t <= to; t++) {
+ const before = rec.level;
+ r.adaptStep(rec, t * 1000, at(t));
+ if (rec.level !== before) changes.push([t, rec.level]);
+ }
+ return changes;
+}
+
+test('the numbers are the approved ones', () => {
+ assert.equal(r.ADAPT_UP_AFTER, 45000);
+ assert.equal(r.ADAPT_UP_MAX, 300000);
+});
+
+test('trouble that lasts steps down one level every ten seconds, to audio only, and no further', () => {
+ const rec = r.adaptRecord();
+ const seen = run(rec, 0, 60, freezing);
+ assert.deepEqual(seen, [[10, 1], [20, 2], [30, 3]]);
+ assert.equal(rec.level, 3);
+ assert.equal(rec.downs, 3);
+});
+
+test('severe trouble steps two levels at once, five seconds in', () => {
+ const rec = r.adaptRecord();
+ assert.deepEqual(run(rec, 0, 12, () => clean({ freezes: 2 })), [[5, 2], [10, 3]]);
+ const lossy = r.adaptRecord();
+ assert.deepEqual(run(lossy, 0, 6, () => clean({ packets: 80, lost: 20 })), [[5, 2]]);
+});
+
+test('a freeze now and then, a little loss, or a slow link alone is not trouble', () => {
+ const rare = r.adaptRecord();
+ assert.deepEqual(run(rare, 0, 60, (t) => clean({ freezes: t % 11 === 0 ? 1 : 0 })), []);
+ const lossy = r.adaptRecord();
+ assert.deepEqual(run(lossy, 0, 60, () => clean({ packets: 97, lost: 3 })), []);
+ const slow = r.adaptRecord();
+ assert.deepEqual(run(slow, 0, 60, () => clean({ rtt: 900 })), []);
+});
+
+test('loss over five percent, a slow link with freezes, a deep jitter buffer and dropped frames each step down', () => {
+ for (const [what, sample] of [
+ ['loss', () => clean({ packets: 94, lost: 6 })],
+ ['one freeze on a 700 ms round trip', (t) => clean({ rtt: 700, freezes: t === 5 ? 1 : 0 })],
+ ['the jitter buffer', () => clean({ jitterBufferMs: 650 })],
+ ['frames dropped', () => clean({ decoded: 20, dropped: 10 })],
+ ]) {
+ const rec = r.adaptRecord();
+ assert.deepEqual(run(rec, 0, 10, sample), [[10, 1]], what);
+ }
+});
+
+test('the round trip is the window median: one spike is not a slow link', () => {
+ const rec = r.adaptRecord();
+ assert.deepEqual(run(rec, 0, 30, (t) => clean({ rtt: t % 10 === 3 ? 2000 : 100, freezes: t % 10 === 3 ? 1 : 0 })), []);
+});
+
+test('a second with nothing measured is no news either way', () => {
+ const rec = r.adaptRecord();
+ run(rec, 0, 9, freezing);
+ assert.deepEqual(run(rec, 10, 40, () => null), []);
+ assert.equal(rec.level, 0, 'a connection that is down says nothing about the link');
+ assert.equal(r.adaptSample({}, true), null);
+ assert.equal(r.adaptSample({ in: { audio: { packets: 0 } } }, true), null);
+});
+
+test('freezes count only while the camera is watched', () => {
+ const q = { rtt: 50, in: { audio: { packets: 50, lost: 1, jitterBufferMs: 70 }, video: { packets: 90, freezes: 2, freezeSeconds: 1.5, decoded: 30, dropped: 1 },
+ screen: { packets: 10, lost: 1, decoded: 1 } } };
+ assert.deepEqual(r.adaptSample(q, true), { freezes: 2, freezeSeconds: 1.5, packets: 150, lost: 2, rtt: 50, jitterBufferMs: 70, decoded: 31, dropped: 1 });
+ const off = r.adaptSample(q, false);
+ assert.equal(off.freezes, 0);
+ assert.equal(off.freezeSeconds, 0);
+ assert.equal(off.packets, 150);
+});
+
+test('clean seconds step up one level after forty-five, and again after another forty-five', () => {
+ const rec = r.adaptRecord();
+ run(rec, 0, 20, freezing);
+ assert.equal(rec.level, 2);
+ // Clean from 21 s: up at 21 + 45; the probe holds, and the next clean run
+ // starts the second after the step, so up again at 67 + 45.
+ const seen = run(rec, 21, 200, () => clean());
+ assert.deepEqual(seen, [[66, 1], [112, 0]]);
+ assert.equal(rec.upWait, r.ADAPT_UP_AFTER, 'a probe that holds puts the wait back');
+});
+
+test('one bad second resets the clean run', () => {
+ const rec = r.adaptRecord();
+ run(rec, 0, 10, freezing);
+ assert.equal(rec.level, 1);
+ const seen = run(rec, 11, 120, (t) => clean({ lost: t === 40 ? 10 : 0, packets: 100 }));
+ assert.deepEqual(seen, [[86, 0]], 'clean from 41 s, so up at 86 s');
+});
+
+test('a probe that fails within twenty seconds steps straight back and doubles the wait, to five minutes at most', () => {
+ const rec = r.adaptRecord();
+ run(rec, 0, 10, freezing);
+ assert.equal(rec.level, 1);
+ // The link carries Reduced and not Normal: clean at 1, freezing at 0.
+ const at = () => (rec.level === 0 ? clean({ freezes: 1 }) : clean());
+ const seen = run(rec, 11, 1200, at);
+ const ups = seen.filter(([, l]) => l === 0).map(([t]) => t);
+ const backs = seen.filter(([, l]) => l === 1).map(([t]) => t);
+ // Up after 45 s clean, back 5 s later; then 90, 180, 300, 300 … of
+ // clean seconds counted from the second after each step back.
+ assert.deepEqual(ups, [56, 152, 338, 644, 950]);
+ assert.deepEqual(backs, [61, 157, 343, 649, 955]);
+ assert.equal(rec.upWait, r.ADAPT_UP_MAX);
+});
+
+test('trouble after the probe watch is an ordinary step down, and the wait is back to its base', () => {
+ const rec = r.adaptRecord();
+ run(rec, 0, 10, freezing);
+ run(rec, 11, 56, () => clean());
+ assert.equal(rec.level, 0);
+ const seen = run(rec, 57, 100, (t) => (t >= 80 ? freezing(t) : clean()));
+ assert.deepEqual(seen, [[84, 1], [94, 2]], 'freezes at 80 and 84 s: the window is trouble at 84, and ten seconds on');
+ assert.equal(rec.upWait, r.ADAPT_UP_AFTER);
+});
+
+test('the person’s own setting is a floor under the watch, and only levels below normal are asked', () => {
+ const levels = new Map([[P1, 0], [P2, 1]]);
+ assert.deepEqual(r.adaptAsks(levels, 'auto'), { [P2]: 'reduced' });
+ assert.deepEqual(r.adaptAsks(levels, 'low'), { [P1]: 'minimal', [P2]: 'minimal' });
+ assert.deepEqual(r.adaptAsks(new Map([[P1, 3]]), 'low'), { [P1]: 'audio' });
+ assert.deepEqual(r.adaptAsks(levels, 'audio'), { [P1]: 'audio', [P2]: 'audio' });
+ assert.deepEqual(r.adaptAsks(new Map([[P1, 0]]), 'auto'), {});
+ const many = new Map(Array.from({ length: 20 }, (_, i) => [i.toString(16).padStart(32, '0'), 2]));
+ assert.equal(Object.keys(r.adaptAsks(many, 'auto')).length, 15);
+});
+
+test('a sender reads only its own id, and only the wire’s levels', () => {
+ assert.equal(r.askedOf({ video: { [P1]: 'minimal' } }, P1), 2);
+ assert.equal(r.askedOf({ video: { [P1]: 'minimal' } }, P2), 0);
+ assert.equal(r.askedOf({ video: { [P1]: 'tiny' } }, P1), 0);
+ assert.equal(r.askedOf(null, P1), 0);
+ assert.equal(r.askedOf({ muted: false }, P1), 0);
+});
+
+test('the camera at each level, fitted by its long and short sides', () => {
+ assert.deepEqual(r.cameraAtLevel(0, false, 640, 480), { maxFramerate: undefined, active: true, maxBitrate: undefined, scaleResolutionDownBy: 1 });
+ assert.deepEqual(r.cameraAtLevel(1, false, 640, 480), { maxBitrate: 350000, maxFramerate: 15, scaleResolutionDownBy: 480 / 360, active: true });
+ assert.deepEqual(r.cameraAtLevel(1, false, 1280, 720), { maxBitrate: 350000, maxFramerate: 15, scaleResolutionDownBy: 2, active: true });
+ // A portrait camera is boxed the right way round: 360 × 640 at most.
+ assert.equal(r.cameraAtLevel(1, false, 720, 1280).scaleResolutionDownBy, 2);
+ assert.deepEqual(r.cameraAtLevel(2, false, 640, 480), { maxBitrate: 120000, maxFramerate: 8, scaleResolutionDownBy: 480 / 180, active: true });
+ assert.equal(r.cameraAtLevel(3, false, 640, 480).active, false);
+ // Unknown size: no scaling, the rest as the level says.
+ assert.equal(r.cameraAtLevel(2, false, 0, 0).scaleResolutionDownBy, 1);
+});
+
+test('while a screen is shared the camera gives way first', () => {
+ // Normal: §5.4's cap beside the screen.
+ assert.deepEqual(r.cameraAtLevel(0, true, 640, 720), Object.assign({ maxFramerate: undefined, active: true }, r.cameraCap(true, 720)));
+ // Reduced asks the camera for minimal, and minimal for none.
+ assert.equal(r.cameraAtLevel(1, true, 640, 480).maxBitrate, 120000);
+ assert.equal(r.cameraAtLevel(1, true, 640, 480).active, true);
+ assert.equal(r.cameraAtLevel(2, true, 640, 480).active, false);
+ assert.equal(r.cameraAtLevel(3, true, 640, 480).active, false);
+});
+
+test('a screen keeps its size and gives up frame rate first, is made smaller only at minimal, and is never paused', () => {
+ const plan = r.sharePlan('balanced', 1920, 1080);
+ assert.deepEqual(r.screenAtLevel(plan, 0, 1920, 1080), plan);
+ const reduced = r.screenAtLevel(plan, 1, 1920, 1080);
+ assert.equal(reduced.encoding.maxFramerate, 10);
+ assert.equal(reduced.encoding.maxBitrate, 1200000);
+ assert.equal(reduced.encoding.scaleResolutionDownBy, plan.encoding.scaleResolutionDownBy, 'the size is kept');
+ assert.equal(reduced.degradationPreference, 'maintain-resolution');
+ const minimal = r.screenAtLevel(plan, 2, 1920, 1080);
+ assert.equal(minimal.encoding.maxFramerate, 5);
+ assert.equal(minimal.encoding.maxBitrate, 500000);
+ assert.equal(minimal.encoding.scaleResolutionDownBy, 1.5);
+ const audio = r.screenAtLevel(plan, 3, 1920, 1080);
+ assert.deepEqual(audio, minimal, 'audio only sends the screen as minimal does');
+ assert.notEqual(audio.encoding.active, false);
+ // Motion's own smaller cap is kept where it is smaller still.
+ const motion = r.sharePlan('motion', 3840, 2160);
+ assert.equal(r.screenAtLevel(motion, 2, 3840, 2160).encoding.scaleResolutionDownBy, 3840 / 1280);
+ // The plan it was given is not changed under it.
+ assert.equal(plan.encoding.maxFramerate, 30);
+});
+
+test('browsers and new apps act on an ask; an app that does not say, or an old one, does not', () => {
+ assert.equal(r.honoursAsks(''), true);
+ assert.equal(r.honoursAsks('mac 0.4.14'), true);
+ assert.equal(r.honoursAsks('iphone 0.5'), true);
+ assert.equal(r.honoursAsks('mac 0.4.13'), false);
+ assert.equal(r.honoursAsks('native'), false);
+ assert.equal(r.honoursAsks('something else'), false);
+});
+
+test('the sender’s notice names the people, and says audio only only when that is all it is', () => {
+ assert.equal(r.adaptNoticeWords([]), '');
+ assert.equal(r.adaptNoticeWords([{ name: 'David', level: 2 }]), 'Sending reduced video to David (their connection is weak)');
+ assert.equal(r.adaptNoticeWords([{ name: 'David', level: 3 }]), 'Sending only audio to David (their connection is weak)');
+ assert.equal(r.adaptNoticeWords([{ name: 'David', level: 1 }, { name: 'Ana', level: 3 }, { name: 'Cy', level: 2 }]),
+ 'Sending reduced video to David, Ana and Cy (their connections are weak)');
+});
+
+test('the report carries the seconds at each level, asked and sent, only when there were any', () => {
+ assert.equal(r.withVideoTime(null, undefined), null);
+ assert.deepEqual(r.withVideoTime(null, { asked: [0, 24.04, 0], sent: [0, 0, 0] }), { askedSeconds: [0, 24, 0] });
+ assert.deepEqual(r.withVideoTime({ noSound: true }, { asked: [0, 0, 0], sent: [5, 0, 1] }), { noSound: true, sentSeconds: [5, 0, 1] });
+ assert.equal(r.withVideoTime(null, { asked: [0, 0, 0], sent: [0, 0, 0] }), null);
+});
+
+test('the media report carries the asks, and reads them back leniently', () => {
+ const mine = { muted: false, cameraOff: false };
+ assert.deepEqual(r.mediaPayload(mine, false, [], false, [], [], { [P1]: 'minimal' }),
+ { muted: false, cameraOff: false, hearing: [], video: { [P1]: 'minimal' } });
+ assert.deepEqual(r.mediaPayload(mine, false, [], false, [], [], {}), { muted: false, cameraOff: false, hearing: [] });
+ assert.deepEqual(r.mediaPayload(mine, false, [], true, [], [], { [P1]: 'minimal' }), mine, 'an old server gets the two keys');
+ const back = r.mediaFrom({ muted: false, cameraOff: false, video: { [P1]: 'audio', [P2]: 'tiny', short: 'minimal' } });
+ assert.deepEqual(back.video, { [P1]: 'audio' });
+ assert.equal(r.mediaFrom({ muted: false, cameraOff: false, video: [P1] }).video, undefined);
+ // The same asks in another order are the same report; a level changed is not.
+ const a = r.mediaKey({ muted: false, cameraOff: false, video: { [P1]: 'audio', [P2]: 'reduced' } });
+ const b = r.mediaKey({ muted: false, cameraOff: false, video: { [P2]: 'reduced', [P1]: 'audio' } });
+ const c = r.mediaKey({ muted: false, cameraOff: false, video: { [P2]: 'minimal', [P1]: 'audio' } });
+ assert.equal(a, b);
+ assert.notEqual(a, c);
+ assert.notEqual(r.mediaKey({ muted: false, cameraOff: false }), a);
+});
diff --git a/test/browser/room-mute.test.mjs b/test/browser/room-mute.test.mjs
index 9cf47d6..f54405e 100644
--- a/test/browser/room-mute.test.mjs
+++ b/test/browser/room-mute.test.mjs
@@ -171,6 +171,12 @@ function reporter({ admitted = true, local = { muted: false, cameraOff: false },
'\nlet mediaExtras = true;' +
'\nlet audioBlocked = false;' +
'\nlet screenStalled = [];' +
+ // §15.30: the asks this tab makes, and the sender's half, which a
+ // roster also runs; neither is under test here.
+ '\nlet videoAsks = env.asks = {};' +
+ '\nconst pcs = new Map();' +
+ '\nconst answerVideoAsks = () => {};' +
+ '\nconst markAdapt = () => {};' +
// §15.28: rosterMedia also records each peer's client.
'\nconst clients = env.clients = new Map();' +
'\nconst noSoundList = () => env.noSound;' +