oficina / meet Public

Clone
git clone https://amadan.net/oficina/meet

Plain git — no account needed to clone.

Download

Download this file

File too large to show in full — download it above (showing a truncated preview below).

1// room.js: the browser half of a call.
2//
3// Spec sections this implements, and the order they appear below:
4//
5// §4.1 transport one SSE stream down, POST /signal up
6// §4.2 peer identity the server issues `peer`; one peer per session
7// per room, and nothing here ever displaces
8// another tab automatically
9// §4.3 messages the event table, including the roster as the
10// authority and the admission queue
11// §4.5 resume the probe, the replay, the four refusals and
12// the terminal reasons
13// §4.6 delivery per-target outbound queue with `seq`, pair
14// generations, inbound dedupe, candidate buffer
15// §5.1 negotiation the W3C perfect-negotiation pattern
16// §5.2 ICE servers GET /m/{sqid}/ice before the first connection
17// §5.3 renewal per connection, at the server's `renewAt`, and
18// complete only when a new ICE username fragment
19// is on the selected candidate pair
20// §5.4 screen share getDisplayMedia as one sendonly transceiver
21// per connection, a `share` message so peers can
22// label the tile, and a stop that ends the
23// receiver's track rather than muting it
24// §5.5 the floor an empty list is the floor: host candidates
25// only, and the failed tile says whether a relay
26// was there to fail
27// §6 chat the broadcast lane and the panel: chat.js owns
28// the words and the log, this file owns the wire
29// and when the panel is usable
30// §15.19 media state who is muted and whose camera is off: our own
31// reported on the broadcast lane, everyone else's
32// read from the roster and `media`
33// §15.26 reports the anonymous quality report every thirty
34// seconds and at leave, and "Report a problem"
35// (report.js's sheet) with the diagnostics
36//
37// House rules this file is written under: no library, no inline script
38// (the page's CSP is `default-src 'self'`), nothing built with
39// innerHTML, and every string a peer or the server sends is written
40// with textContent. `data-is-member` on #room is a rendering hint only
41// — the server re-derives authority on every request, and the roster
42// it sends is what this file actually believes.
43(() => {
44 'use strict';
45
46 const root = document.getElementById('room');
47 if (!root) return;
48 // Revealing the room is the first job: the server renders it hidden
49 // so a scriptless browser sees the fallback paragraph instead.
50 root.hidden = false;
51
52 const sqid = root.dataset.sqid || '';
53 const selfName = root.dataset.selfName || '';
54 const memberHint = root.dataset.isMember === '1';
55 // §5.5: whether this instance has a relay at all. It changes one
56 // sentence — the one a failed tile shows — and nothing else. Like
57 // data-is-member it is a rendering hint: the ICE list the server
58 // actually mints is what decides whether a call has a relay to use.
59 const relayConfigured = root.dataset.relay === '1';
60
61 const $ = (id) => document.getElementById(id);
62 const tilesEl = $('tiles');
63 const queueEl = $('queue');
64 const knocksEl = $('knocks');
65 const statusEl = $('status');
66 const muteButton = $('mute');
67 const cameraButton = $('camera');
68 const leaveButton = $('leave');
69 const shareButton = $('share');
70 const muteState = $('mute-state');
71 const cameraState = $('camera-state');
72 const shareState = $('share-state');
73 // The sharing notice and its own Stop sharing button (2026-09-28).
74 const shareNotice = $('share-notice');
75 const shareStop = $('share-stop');
76 const shareRecoveryEl = $('share-recovery');
77 const copyDiagnostics = $('copy-diagnostics');
78 // §15.26: "Report a problem", in the Devices panel beside Copy call
79 // diagnostics and in the More menu, and the person's own switch for
80 // the automatic reports.
81 const reportProblem = $('report-problem');
82 const reportProblemMenu = $('report-problem-menu');
83 const moreToggle = $('call-more-toggle');
84 const morePanel = $('call-more');
85 const qualityRow = $('quality-row');
86 const qualityInput = qualityRow ? qualityRow.querySelector('input[type="checkbox"]') : null;
87 // §15.19: the tile marks, rendered by the server so they are the
88 // vendored badge and the app's own icons rather than a copy of either,
89 // and the polite region that says a change out loud. #status is no
90 // use for that: renderStatus rewrites it on every render.
91 const mutedMark = $('tile-muted');
92 const cameraOffMark = $('tile-camera-off');
93 const mediaLive = $('media-live');
94 // The chat panel's root (§6). chat.js owns everything inside it; this
95 // file owns the wire under it and the moment it becomes usable.
96 const chatEl = $('chat');
97 // The device panel and its controls. Every one of these is optional
98 // as far as this file is concerned — the room renders without them in
99 // a browser that cannot enumerate devices, and switchDevice and
100 // fillDevices both check before they reach for one.
101 const devicesToggle = $('devices-toggle');
102 const devicesPanel = $('room-devices');
103 const deviceNote = $('device-note');
104 const pickCamera = $('pick-camera');
105 const pickMic = $('pick-mic');
106 const pickSpeaker = $('pick-speaker');
107 const cameraRow = $('camera-row');
108 const micRow = $('mic-row');
109 const speakerRow = $('speaker-row');
110 const rawRow = $('raw-row');
111 const rawInput = rawRow ? rawRow.querySelector('input[type="checkbox"]') : null;
112 const shareModeRow = $('share-mode-row');
113 const pickShareMode = $('pick-share-mode');
114 // §15.30's own choice: Auto, Low bandwidth, Audio only.
115 const videoQualityRow = $('video-quality-row');
116 const pickVideoQuality = $('pick-video-quality');
117
118 const DEVICE_KEY = 'meet.devices';
119 const BACKOFF_MIN = 500;
120 const BACKOFF_MAX = 30000;
121 // The stream's own ceiling is deliberately well under the hub's
122 // thirty-second resume window: a client that waited the full thirty
123 // would lose the participation to its own patience, and come back to
124 // a fresh peer id and a renegotiated mesh for no reason.
125 const STREAM_BACKOFF_MAX = 10000;
126 // §4.6: a target whose POSTs have failed for this long is treated as
127 // unreachable — the pair is reset and the connection rebuilt.
128 const SEND_DEADLINE = 30000;
129 const MAX_BUFFERED_CANDIDATES = 256;
130 // §4.3: `full` is not a refusal, it is "not yet" — a member waits and
131 // retries the join on this interval.
132 const FULL_RETRY = 5000;
133 // A stream refusal the probe cannot name — a full room behind a 204,
134 // a 500, a `last` the server would not parse — would otherwise retry
135 // for ever behind "Connecting to the call." After this many rounds
136 // that produced no `hello`, and this long since the last one, the
137 // client stops and says so. Both conditions, because either alone
138 // gives up on something worth waiting for: a count alone would quit on
139 // a handful of fast failures at the start of the backoff ladder, and a
140 // clock alone would quit on one slow round that was still going to
141 // succeed.
142 const MAX_STALLS = 8;
143 const STALL_WINDOW = 60000;
144 // A stream that lived at least this long was a working stream, not a
145 // refusal: only that resets the backoff. A stream dying moments after
146 // its `hello` would otherwise reconnect in a tight loop.
147 const HEALTHY_STREAM = 5000;
148 // §5.3: a fetch of /ice that fails is retried every minute, and the
149 // warning stands from the first failure until one succeeds. The gate
150 // shortens the *schedule* through X-Calls-Test-Ice-TTL's effect on
151 // `renewAt`, never this: there is no client knob for it.
152 const ICE_RETRY = 60000;
153 // §5.3 step 2: each ICE restart gets thirty seconds to prove itself,
154 // and a connection gets three of them.
155 const RENEW_ATTEMPTS = 3;
156 const RENEW_WINDOW = 30000;
157 const RENEW_POLL = 500;
158 // The floor under a renewal delay. Nothing the server can send should
159 // schedule a renewal sooner than this: a list with no margin left in
160 // it would otherwise fetch, schedule for now, and fetch again.
161 const MIN_RENEW_DELAY = 1000;
162 // And the floor under the margin itself. A list whose renew time and
163 // expiry are less than a second apart cannot be renewed on any
164 // sensible schedule: the delay floor above would turn it into a fetch
165 // roughly once a second for as long as the tab stayed open. The
166 // server clamps what it will mint, so this can only arrive through
167 // the development-only TTL header — but a client that answers a
168 // nonsense schedule with a 1 Hz loop is a client that can be made to
169 // hammer its own server, so it declines instead, and says so in
170 // state().ice rather than looking idle for no reason (W3-12).
171 const MIN_MARGIN = 1000;
172 const PEER_ID = /^[0-9a-f]{32}$/;
173 // §4.3's two untargeted messages ride one queue of their own, and this
174 // is its key: not a peer id, and it cannot collide with one, because
175 // every peer id is thirty-two hex characters.
176 const BROADCAST = '*';
177 // A 404 on the broadcast lane is diagnosed inside the message's own
178 // deadline — but a POST that spent all thirty seconds getting that 404
179 // leaves nothing to diagnose with, and a recovery with no budget
180 // decides nothing at all. This is the floor it gets instead: enough
181 // for one probe and one retry, and short enough that a tab which has
182 // really lost its participation is not left looking live.
183 const MIN_RECOVERY = 5000;
184 // §5.1: how long the polite peer waits before offering. Perfect
185 // negotiation's answer to glare is a rollback on the polite side, and
186 // in Chromium rolling back an offer that added an m-line rebuilds the
187 // whole connection's send streams: the camera's comes back on the same
188 // SSRC having encoded nothing, on an m-line that goes on reading
189 // sendrecv with a live track, and it never encodes again. Two peers
190 // sharing a screen in the same moment is how a call finds that, and
191 // the gate's mutualshare scenario is where it was measured.
192 //
193 // So the peer that would roll back yields instead. A remote offer that
194 // was already on its way arrives while this side is still stable and
195 // is answered rather than collided with, and no rollback happens at
196 // all. The cost is this much delay before the polite side offers, and
197 // only when the other side has nothing to offer. The wait itself is
198 // unconditional — the check that reads the connection happens after
199 // it, not during — so what a remote offer arriving buys is not a
200 // shorter wait but a negotiation this side no longer has to make.
201 const POLITE_YIELD = 300;
202 // How many times in a row the polite side may give way without an
203 // offer of its own going out. A boolean could not answer both "give
204 // the allowance back when the exchange that took our turn completes"
205 // and "never let giving way become a habit"; a small counter answers
206 // both (Codex S4-4, and the Task 4 re-review's item 1).
207 const POLITE_YIELDS = 2;
208 // Polls in a row that must report no new encoded frames before a
209 // camera counts as stopped, and repairs on one connection before the
210 // pair is reset instead. At one poll a second that is two seconds of
211 // a live track on a sending m-line encoding nothing, then a
212 // replaceTrack cycle, then two more seconds, then a reset (Codex
213 // S4-5, and the Task 4 re-review's item 2).
214 const CAMERA_STALL_POLLS = 2;
215 const CAMERA_REPAIRS = 1;
216 // And the same shape for the last link in the chain: how many polls a
217 // tile may hold a live, unmuted track that its connection is decoding
218 // frames for and paint none of them, before the element is handed its
219 // media again — and how many of those before the pair is rebuilt
220 // instead (Codex round 2, the branch after S4-9).
221 const RENDER_STALL_POLLS = 3;
222 const RENDER_REPLAYS = 2;
223 // How far an element's own clock must advance in a poll to count as
224 // playing rather than twitching. A second of video is a second of
225 // clock; a single frame is thirty milliseconds, and a tile painting
226 // one frame every three seconds is a stall with a tic, not a picture.
227 // Reading any advance at all as health let such a tile reset the
228 // budget below for ever and never earn its reset.
229 const RENDER_MOVED = 0.25;
230 // The self view's own watch (2026-10-21: an iPhone in Safari showed
231 // its own picture black for a whole call while sending it perfectly).
232 // How long a live, enabled camera may sit in the self view without
233 // its element's clock moving before the element is handed the stream
234 // again and asked to play, and — that once — before the tile says so.
235 const SELF_STUCK_MS = 2000;
236 const SELF_PAUSED = 'Your camera preview is paused.';
237 const SELF_SHOW = 'Show it';
238 // The ceiling studio audio asks for, in bits per second. Opus is
239 // transparent for speech well below it; the number is picked so a
240 // microphone someone turned the processing off for is not then
241 // squeezed down a pipe built for speech. It is a ceiling and not a
242 // floor — the encoder still spends only what the link will carry.
243 const RAW_AUDIO_BITRATE = 128000;
244 // §15.20: the hearing watch. How often the levels are read — five
245 // times a second, which is as fast as a bar is worth moving and slow
246 // enough that one small getStats per connection costs nothing a
247 // person could notice.
248 const LEVEL_EVERY = 200;
249 // An audioLevel below this is silence: -80 dBFS, well under any room's
250 // own noise floor, so a microphone reading it is not hearing the room
251 // at all. Anything at or above it counts as sound.
252 const FLAT_LEVEL = 0.0001;
253 // How long a stream that is arriving must stay that flat before it is
254 // called silent — long enough to cover somebody simply not talking in
255 // a quiet room, short enough to catch "can you hear me?" early.
256 const NO_SOUND_AFTER = 5000;
257 // Packets count as arriving if one came this recently. Wider than a
258 // poll, because a sender using DTX sends a packet every 400 ms or so
259 // through silence, and silence with packets is exactly the case the
260 // watch is for.
261 const ARRIVING_WINDOW = 1500;
262 // The speaking highlight, with hysteresis: on at SPEAK_ON, and off only
263 // after SPEAK_HOLD polls below SPEAK_OFF, so a tile does not flicker
264 // between syllables.
265 const SPEAK_ON = 0.04;
266 const SPEAK_OFF = 0.015;
267 const SPEAK_HOLD = 4;
268 // The speaking light on a tile's name, which replaced the ring round
269 // the tile and the meter beside the name (0.3.7), and since 0.4.3 is
270 // the warm rim, as the native apps have it (SpeakingGlow.swift,
271 // WarmRim.swift): a level by decibels between GLOW_QUIET_DB and
272 // GLOW_LOUD_DB; lit only once sound at SPEAK_ON has kept up for
273 // GLOW_ONSET ms, so a click never lights it; the level rising over
274 // GLOW_ATTACK ms and falling over GLOW_RELEASE ms, which is a CSS
275 // transition on --lvl, with --on going out once it has fallen; and one
276 // steady GLOW_STEADY for anyone who has asked for reduced motion.
277 const GLOW_QUIET_DB = -42;
278 const GLOW_LOUD_DB = -12;
279 const GLOW_ONSET = 150;
280 const GLOW_ATTACK = 50;
281 const GLOW_RELEASE = 300;
282 const GLOW_STEADY = 0.6;
283 // Speaker view's stage (0.4.0), as the native apps have it
284 // (ActiveSpeaker in SpeakerView.swift): someone takes the stage only
285 // after SPEAKER_DOMINANCE ms as the loudest speaker, and whoever is on it
286 // keeps it at least SPEAKER_HOLD ms, so an interjection, a laugh or two
287 // people talking over each other never make it flap. Never yourself.
288 const SPEAKER_DOMINANCE = 1300;
289 const SPEAKER_HOLD = 3000;
290 // §4.3's limit on the list the hub will take.
291 const MAX_NO_SOUND = 15;
292 // §5.4: the tile key a peer's screen gets, built by shareKey.
293 const SHARE_SUFFIX = '#share';
294 // §15.21, the screen watchdogs (2026-09-28). A screen that has decoded
295 // nothing new for SCREEN_STALL_AFTER while its sender says it is
296 // sharing is stalled here, and reported as `screenStalled`; every
297 // sender repeats a still screen at least once a second, so this long
298 // without a frame is not a still screen. Held for at most
299 // SCREEN_STALL_GIVE_UP, so a screen nobody can recover is not a report
300 // that never ends. A sharer named in someone's report asks its encoder
301 // for a keyframe, at most once every SCREEN_KEYFRAME_EVERY, and rests
302 // SCREEN_KEYFRAME_REST after SCREEN_KEYFRAME_TRIES of them.
303 const SCREEN_STALL_AFTER = 4000;
304 const SCREEN_STALL_GIVE_UP = 180000;
305 const SCREEN_KEYFRAME_EVERY = 4000;
306 const SCREEN_KEYFRAME_TRIES = 3;
307 const SCREEN_KEYFRAME_REST = 30000;
308 // §15.22 (2026-09-30), when keyframes do not answer. The receiver
309 // hands a stalled screen's picture to its element again once,
310 // SCREEN_REATTACH_AFTER into the stall. The sharer, still named
311 // SCREEN_REBUILD_AFTER after its first keyframe, rebuilds that
312 // connection's screen (a new transceiver: a new encoder here, a new
313 // receiver and decoder there); still named SCREEN_RESHARE_AFTER after
314 // that, shares again for everyone from the same capture; and
315 // SCREEN_GIVE_UP_AFTER after that, says it could not. A rebuild at most
316 // once every SCREEN_REBUILD_EVERY per person, a share again at most
317 // once every SCREEN_RESHARE_EVERY, and neither unless at least
318 // SCREEN_ESCALATE_SENT frames left for that person since the last step:
319 // a receiver cannot be failing to decode frames that were never sent.
320 const SCREEN_REATTACH_AFTER = 4000;
321 const SCREEN_REBUILD_AFTER = 6000;
322 const SCREEN_RESHARE_AFTER = 10000;
323 const SCREEN_GIVE_UP_AFTER = 10000;
324 const SCREEN_REBUILD_EVERY = 60000;
325 const SCREEN_RESHARE_EVERY = 300000;
326 const SCREEN_ESCALATE_SENT = 3;
327 // 2026-10-21, a loop: Paul's screen to Farshad in Safari was rebuilt,
328 // restored within a second and reported stalled again 25 s later, for
329 // eight minutes, every rebuild an interruption that mended nothing for
330 // long. A report back within SCREEN_LOOP_WITHIN of a rebuild or a share
331 // again restoring that person's view is that step mending it only
332 // briefly; SCREEN_LOOP_LIMIT of them in a row and neither is taken for
333 // them for SCREEN_LOOP_REST: the notice says it could not be restored,
334 // and keyframes go on.
335 const SCREEN_LOOP_WITHIN = 120000;
336 const SCREEN_LOOP_LIMIT = 2;
337 const SCREEN_LOOP_REST = 600000;
338 // The screen's timeline, for "Copy call diagnostics": its last lines.
339 const SCREEN_LOG_LINES = 200;
340 // §15.23 (2026-09-30), "Reconnecting…" only for a problem that lasts:
341 // the stream down RECONNECT_STREAM_AFTER (the whole call); a connection
342 // disconnected or failed RECONNECT_CONNECTION_AFTER, or no audio packets
343 // from someone unmuted RECONNECT_AUDIO_AFTER (that person's tile, or the
344 // whole call when it is everyone). Said for RECONNECT_HOLD past the
345 // recovery, so it does not flicker. A stream renewal — ended on purpose
346 // and resumed in half a second — is never said at all.
347 const RECONNECT_STREAM_AFTER = 4000;
348 const RECONNECT_CONNECTION_AFTER = 3000;
349 const RECONNECT_AUDIO_AFTER = 2000;
350 const RECONNECT_HOLD = 1000;
351 const RECONNECT_EVERY = 200;
352 // §15.28 (2026-10-21): a connection that stops working is mended without
353 // anyone asking. ICE failed, disconnected RECOVER_DISCONNECTED_AFTER, or
354 // never connected RECOVER_CONNECT_AFTER after the connection was made is
355 // trouble; attempts follow RECOVER_BACKOFF and then RECOVER_EVERY: an ICE
356 // restart, another, then the pair rebuilt (a reset), and round again. The
357 // impolite side leads; the polite side follows RECOVER_FOLLOW behind,
358 // only if the leader has not acted. The failure is said after
359 // RECOVER_NOTICE_AFTER. Trouble again within RECOVER_FLAP of a recovery
360 // carries on where the schedule was. The apps' ConnectionRecovery is the
361 // twin.
362 const RECOVER_DISCONNECTED_AFTER = 5000;
363 const RECOVER_CONNECT_AFTER = 15000;
364 const RECOVER_BACKOFF = [0, 2000, 5000, 10000, 20000];
365 const RECOVER_EVERY = 30000;
366 const RECOVER_FOLLOW = 3000;
367 const RECOVER_NOTICE_AFTER = 60000;
368 const RECOVER_FLAP = 60000;
369 // §15.28: the oldest app that does not break a call for the people in
370 // it with it (protocol.MinNativeVersion carries the reason).
371 const MIN_NATIVE_VERSION = '0.4.2';
372 // §15.24 (2026-10-01), "<name> is connecting and can't hear you yet":
373 // said on a person's tile from the moment they appear until their own
374 // report says they hear us — but only once CONNECTING_GRACE has passed
375 // without that, so an ordinary join says nothing, and never past
376 // CONNECTING_CAP, after which §15.20's and §15.23's words take over.
377 const CONNECTING_GRACE = 1000;
378 const CONNECTING_CAP = 20000;
379 // §15.26 (2026-10-03), the automatic quality report: one every
380 // QUALITY_EVERY while admitted, and one more at leave. The gate
381 // shortens the cadence through window.meet.qualityEveryForTest, never
382 // below QUALITY_EVERY_MIN. QUALITY_KEY is the person's own switch
383 // ("Send anonymous quality reports"), stored as "off" when off.
384 // The bounds are protocol/quality.go's, so a report is clamped here to
385 // what the server would accept rather than refused there.
386 const QUALITY_EVERY = 30000;
387 const QUALITY_EVERY_MIN = 1000;
388 const QUALITY_KEY = 'calls.qualityReports';
389 const QUALITY_MAX_PEERS = 4;
390 const QUALITY_MAX_SECONDS = 600;
391 const QUALITY_MAX_MILLIS = 600000;
392 const QUALITY_MAX_COUNT = 1e9;
393 const QUALITY_MAX_KBPS = 1e6;
394 const QUALITY_MAX_PIXELS = 16384;
395 const QUALITY_MAX_FPS = 240;
396 const QUALITY_MAX_BODY = 16384;
397 // The longest stretch between two looks of the event watch that is
398 // counted as time a notice was showing: a suspended tab's timers stop,
399 // and the gap when they start again is not a notice someone saw.
400 const QUALITY_LOOK_MAX = 1000;
401 // §15.29 (2026-10-28), the automatic "Report a problem": what counts as
402 // a call struggling, and how often this tab may say so. The rules are
403 // protocol/quality.go's, which the server enforces on its own: inbound
404 // freezes at least AUTO_FREEZES in this window and the one before it;
405 // the window's highest round trip above AUTO_RTT_MS in both; a
406 // "Reconnecting…" showing longer than AUTO_RECONNECTING_SECONDS in one
407 // window; or the screen's ladder past its keyframes. At most
408 // AUTO_REPORTS_PER_CALL in one participation, at least AUTO_REPORT_EVERY
409 // apart. AUTO_BODY_MAX is report.js's BODY_MAX: the server's 64 KB, less
410 // a margin.
411 const AUTO_FREEZES = 3;
412 const AUTO_RTT_MS = 800;
413 const AUTO_RECONNECTING_SECONDS = 5;
414 const AUTO_REPORTS_PER_CALL = 3;
415 const AUTO_REPORT_EVERY = 600000;
416 const AUTO_BODY_MAX = 65024;
417 // §15.30 (2026-10-28): adaptive video. Every receiver watches what
418 // arrives from each sender and asks that sender, through its own media
419 // report, for one of four levels; the sender applies it to that one
420 // connection's sender parameters. Down quickly, up slowly, and a probe up
421 // that fails doubles the wait before the next. The apps' VideoAdapt has
422 // the same numbers; test/browser/room-adapt.test.mjs and
423 // VideoAdaptTests hold both.
424 const ADAPT_LEVELS = ['normal', 'reduced', 'minimal', 'audio'];
425 const ADAPT_WINDOW = 10000; // the trouble window, and the time at a level before a step down
426 const ADAPT_SEVERE_AFTER = 5000; // severe trouble steps two levels after this long
427 const ADAPT_DOWN_FREEZES = 2; // camera freezes in the window
428 const ADAPT_DOWN_LOSS = 0.05; // packets lost in the window, of all inbound
429 const ADAPT_DOWN_RTT = 600; // ms, counted with at least one freeze
430 const ADAPT_DOWN_JITTER_BUFFER = 500; // ms, the audio jitter buffer's mean delay
431 const ADAPT_DOWN_DROPPED = 0.25; // frames dropped, of decoded and dropped, at least ADAPT_DOWN_DROPPED_MIN
432 const ADAPT_DOWN_DROPPED_MIN = 10;
433 const ADAPT_DOWN_FREEZE_SECONDS = 2; // seconds frozen in the window: a picture stuck a fifth of the time
434 const ADAPT_DOWN_KEYFRAME_ASKS = 3; // keyframes this side asked the camera for (PLI, FIR) in the window
435 const ADAPT_SEVERE_FREEZES = 5;
436 const ADAPT_SEVERE_FREEZE_SECONDS = 4; // seconds frozen in the window
437 const ADAPT_SEVERE_LOSS = 0.15;
438 const ADAPT_CLEAN_LOSS = 0.02; // a clean second: no freeze, loss at most this,
439 const ADAPT_CLEAN_RTT = 400; // a round trip under this (ms),
440 const ADAPT_CLEAN_JITTER_BUFFER = 300; // and the jitter buffer under this (ms)
441 const ADAPT_UP_AFTER = 45000; // clean this long at a level, then probe one up
442 const ADAPT_PROBE_WATCH = 20000; // trouble this soon after a probe steps back
443 const ADAPT_PROBE_JUDGE = 5000; // and is judged on at least this much of it
444 const ADAPT_UP_MAX = 300000; // the probe's wait doubles to at most this
445 const ADAPT_SETTLE = 5000; // after a renegotiation (a screen added or taken away), no news this long
446 // The sender's own half (2026-10-29): this device struggling — the
447 // Compute Pressure API at serious or critical in the browser; the apps
448 // add their own process's CPU — for this many of the window's seconds is
449 // trouble for its own camera, judged by the same watch at the same
450 // levels. The screen and audio are not touched.
451 const ADAPT_DOWN_LOAD_SECONDS = 8;
452 const PRESSURE_STATES = ['nominal', 'fair', 'serious', 'critical'];
453 // What each level sends (the sender's half). The camera: its bitrate,
454 // frame rate, and the box its picture is fitted into (long side, short
455 // side). The screen keeps its size and gives up frame rate first, and
456 // only at minimal is it made smaller; it is never paused.
457 const ADAPT_CAMERA = [null,
458 { maxBitrate: 350000, maxFramerate: 15, long: 640, short: 360 },
459 { maxBitrate: 120000, maxFramerate: 8, long: 320, short: 180 }];
460 const ADAPT_SCREEN = [null,
461 { maxBitrate: 1200000, maxFramerate: 10 },
462 { maxBitrate: 500000, maxFramerate: 5, long: 1280 }];
463 // An app older than this ignores a request; its video can only be hidden
464 // here, which saves this device's work and not the connection.
465 const ADAPT_MIN_NATIVE_VERSION = '0.4.15';
466 // How long the sender's "Sending reduced video to …" stays up.
467 const ADAPT_NOTICE_FOR = 8000;
468 // The person's own choice, in the Devices panel: Auto, Low bandwidth
469 // (minimal from everyone), Audio only (no video either way).
470 const VIDEO_SETTINGS = [['auto', 'Auto'], ['low', 'Low bandwidth'], ['audio', 'Audio only']];
471 // §5.4, sending: "Optimise shared screen for". What a screen gives up
472 // first when the uplink or the encoder cannot carry all of it. The
473 // first is the default; sharePlan says what each one means.
474 const SHARE_MODES = [
475 ['balanced', 'Balanced'],
476 ['detail', 'Text and detail'],
477 ['motion', 'Motion and video'],
478 ];
479 const HAS_DISPLAY_MEDIA = typeof navigator !== 'undefined' &&
480 !!navigator.mediaDevices &&
481 typeof navigator.mediaDevices.getDisplayMedia === 'function';
482 const HAS_SINK_ID = typeof HTMLMediaElement !== 'undefined' &&
483 typeof HTMLMediaElement.prototype.setSinkId === 'function';
484
485 // ---------------------------------------------------------------
486 // State (§4.2, §4.6)
487 // ---------------------------------------------------------------
488
489 const state = {
490 peer: null, // this stream's server-issued peer id
491 boot: root.dataset.boot || '',
492 admitted: false, // a roster has arrived, so we are in the mesh
493 joined: false, // `join` has been accepted at least once
494 full: false, // the last `full` event, cleared by a roster
495 stopped: false, // terminal, or waiting on a takeover: no reconnect
496 terminal: null, // the reason this call ended, once it has
497 leaveSent: false, // §4.3: `leave` is not idempotent
498 kind: memberHint ? 'member' : 'guest',
499 };
500
501 const pcs = new Map(); // peer id -> connection record
502 const gen = new Map(); // peer id -> pair generation (§4.6)
503 const seqOut = new Map(); // peer id -> last seq we sent (never reset)
504 const lastIn = new Map(); // peer id -> highest seq received (resume cursor)
505 const queue = new Map(); // peer id -> [{seq, body}] outbound, in order
506 const inflight = new Set();// peer ids with a POST in flight
507 // Targets the hub has answered 404 for while our own participation is
508 // alive: they have left, and our roster has not caught up yet. Nothing
509 // is sent to them and no reset is asked for until a roster settles it —
510 // otherwise every message to a departed peer starts its own 404 →
511 // probe → reset → 404 cycle, each with a fresh budget (Codex S2-11).
512 const stale = new Set();
513 const resetting = new Set(); // targets with a reset already in flight
514 const names = new Map(); // peer id -> display name, from the server only
515 const frames = new Map(); // peer id -> frames rendered, for the test hook
516 const tiles = new Map(); // tile key -> {figure, video}
517 // §15.19: peer id -> {muted, cameraOff}, for the peers that have
518 // reported. A peer absent here is unknown and is drawn as neither.
519 const remoteMedia = new Map();
520 // §15.28: peer id -> what their participation was opened from, as the
521 // roster says ("mac 0.4.12", "native", or '' for a browser); peer id ->
522 // the recovery record of their connections; and, for the gate only,
523 // until when every ICE candidate either way is pointed at nothing.
524 const clients = new Map();
525 const recovery = new Map();
526 let iceBlockUntil = 0;
527 let iceBlockMangled = 0;
528 let autoRestartsTotal = 0;
529 let recoveryOn = true;
530 let autoRebuildsTotal = 0;
531 // The state this tab last put on the broadcast lane, as mediaKey
532 // writes it, so a toggle that changes nothing sends nothing.
533 let mediaSent = '';
534 // §15.20: whether the report may carry the two optional keys. A server
535 // from before them answers 400 to anything but the two booleans, and
536 // the first such answer turns them off for the life of the page.
537 let mediaExtras = true;
538 // §15.21: share key -> {decoded, movedAt}, the receiver's watch; the
539 // peers last reported stalled; peer -> {at, tries, restUntil}, the
540 // sharer's keyframe answers; and the sharer's quiet notice.
541 const screenSeen = new Map();
542 let screenStalled = [];
543 const screenAsks = new Map();
544 // §15.30: peer id -> the adaptive watch's record of what arrives from
545 // them; the asks this tab last put in its report (peer id -> level);
546 // what each connection is sending at, as asked (on the entry); the
547 // sender's notice and its timer; seconds at each level for the report;
548 // and, for the gate, the watch's up wait.
549 const adapt = new Map();
550 let videoAsks = {};
551 let adaptNoticeTimer = 0;
552 let adaptNoticeShown = '';
553 const videoTime = new Map();
554 let adaptUpAfter = ADAPT_UP_AFTER;
555 // The sender's own watch of this device, and the Compute Pressure API's
556 // state now and at its worst since the last quality report.
557 let localAdapt = adaptRecord();
558 const pressure = { state: '', worst: '', observer: null, forced: '' };
559 let adaptPolledAt = 0;
560 let shareRecovery = '';
561 let screenStallTestUntil = 0;
562 // §15.22: each arriving screen's statistics at the last poll and when
563 // it last moved (share key -> screenReading); pictures handed back;
564 // when each peer's screen was last rebuilt, and everyone's last shared
565 // again; and the timeline itself.
566 const screenReadings = new Map();
567 const screenMoving = new Map();
568 let screenReattaches = 0;
569 const shareRebuiltAt = new Map();
570 // peer -> {restoredAt, loops, dampedUntil}: escalateShare's loop record,
571 // kept across reports.
572 const shareLoops = new Map();
573 let shareResharedAt = 0;
574 const shareCounts = { keyframes: 0, rebuilds: 0, reshares: 0, failures: 0, damped: 0 };
575 const screenLines = [];
576 // §15.26: the same ladder and mending, per peer, taken by each quality
577 // report (peer id -> counts). shareCounts above is the whole call's,
578 // for the diagnostics.
579 const shareCountsBy = new Map();
580 const reattachesBy = new Map();
581 // And the stalls this tab judged, per peer, by what the statistics said
582 // (peer id -> {stalls, noPackets, undecoded}).
583 const stallsBy = new Map();
584 // §15.23: when the stream went down (0 while it is up), and the watch.
585 let streamDownSince = 0;
586 const reconnect = reconnectRecord();
587 // §15.24: who can hear us yet (connectingStep's record), and the
588 // `hearing` list as last reported, joined, so a change is seen.
589 const connecting = connectingRecord();
590 let hearingKey = '';
591 // §15.20: peer id -> what this tab is hearing from that peer, as
592 // pollLevels reads it (hearingRecord). selfHearing is the same record
593 // for our own microphone, read off the sender.
594 const hearing = new Map();
595 const selfHearing = hearingRecord();
596 // Who has the floor, for Speaker view's stage (speakerStep).
597 const stageSpeaker = speakerRecord();
598 // Tile keys whose element the browser refused to play. Non-empty is
599 // `audioBlocked`: the page banner shows, and the report says so.
600 const refusedTiles = new Set();
601 let audioBlocked = false;
602 // The autoplay policy as the browser states it in advance, where it
603 // will (Firefox). A hint that puts the banner up early; the refusal
604 // is still the authority, and a play that succeeds takes it down.
605 let autoplayDoubted = autoplayPolicyDoubtful();
606 let soundBanner = null; // {box, text, button} once built
607 let levelTimer = 0;
608 let levelsBusy = false;
609 // The noSoundFrom list as last computed, joined, so a change is seen.
610 let noSoundKey = '';
611
612 // §5.2's list and §5.3's clocks. `expiresAt`, `renewAt`, `fetchedAt`
613 // and `lastFetchAt` are all milliseconds since the epoch: the server
614 // sends unix seconds and fetchIce is the one place they are converted,
615 // so everything below — and everything the test hook exposes —
616 // compares them with Date.now() and with nothing else.
617 const ice = {
618 servers: [], // the RTCIceServer list, [] on the floor (§5.5)
619 expiresAt: 0, // the credential's hard deadline on the relay
620 renewAt: 0, // when the server asks us to come back
621 margin: 0, // expiresAt - renewAt: a duration both clocks agree on
622 fetchedAt: 0, // when the list we hold arrived
623 failedSince: 0, // the first failure of the current run, or 0
624 lastTryAt: 0, // the most recent failed attempt, for the catch-up
625 fetches: 0, // *successful* fetches, for the gate
626 lastFetchAt: 0,
627 };
628 // peer id -> §5.3's record for one connection's renewal.
629 const renewals = new Map();
630
631 let waiting = []; // the admission queue, members only (§4.3)
632 let lastRoster = null;
633 // The newest roster this browser has been sent and has not applied
634 // yet. Only §5.2's fetch can leave anything in it for longer than a
635 // microtask.
636 let pendingRoster = null;
637 let pendingRosterAt = 0; // the tick that roster arrived on
638 let tick = 0;
639 let local = null; // the local MediaStream, or null
640 // §5.4: the display capture while this tab is sharing, and nothing
641 // when it is not. One capture, whatever the mesh's size — every
642 // connection carries the same track on a transceiver of its own.
643 let share = null; // {stream, track} while sharing
644 // True from the moment getDisplayMedia is asked until it answers. The
645 // picker takes as long as a person takes, and without this a second
646 // click during it takes a second capture that nothing ever stops.
647 let sharePending = false;
648 // §6: the mounted panel, once there is one. `chatSent` counts lines
649 // the hub accepted, not lines typed, and `chatReceived` counts lines
650 // put in the log — the two facts a gate cannot read off the DOM
651 // without knowing the panel's own markup.
652 let chat = null;
653 let chatSent = 0;
654 let chatReceived = 0;
655 let prefs = loadPrefs();
656 let es = null; // the live EventSource
657 let backoff = BACKOFF_MIN;
658 let stalls = 0; // consecutive stream rounds that produced no hello
659 // When this browser last reached the room. It starts at load rather
660 // than at zero: a page that has never once got a `hello` has been
661 // trying since it opened, and that is the stretch STALL_WINDOW means.
662 let lastHelloAt = Date.now();
663 let reconnectTimer = 0;
664 let reconnectWatchTimer = 0;
665 let statsTimer = 0;
666 let backdropTimer = 0;
667 let fullTimer = 0;
668 let renewTimer = 0; // §5.3: the scheduled renewal, at `renewAt`
669 let iceRetryTimer = 0; // §5.3 step 1: the one-minute retry
670 let expiryTimer = 0; // §5.3 step 3: the must-succeed-by verdict
671 let icePrimed = false; // a first fetch has been made (success or not)
672 let firstIce = null; // that fetch, shared by concurrent callers
673 let renewing = false; // a renewal fetch is in flight
674 let renewDue = false; // the current run is a renewal, not a first fetch
675 let iceWarningEl = null;
676 // §15.26: the report token the latest `hello` carried — the authority
677 // for both report endpoints, kept after leaving because it goes on
678 // working for ten minutes after — and the quality report's own state:
679 // when the current window began (0 until admitted), each connection's
680 // reading at the last report (peer id -> {pc, reading}), the event
681 // watch, the output device's kind as last enumerated, and what has
682 // been sent. A 204 is the server's kill switch, and stops the reports
683 // for the rest of this page.
684 let reportToken = '';
685 let qualityEvery = QUALITY_EVERY;
686 let qualityFrom = 0;
687 const qualityPrev = new Map();
688 const qualityEvents = qualityWatchRecord();
689 let qualityOutput = 'unknown';
690 let qualityServerOff = false;
691 let qualityLocalOff = false; // the switch, where there is no storage to keep it in
692 let qualityFinalSent = false;
693 const quality = { sent: 0, accepted: 0, status: 0, auto: { sent: 0, status: 0, refs: [], reported: 0 } };
694 // §15.29: the window's once-a-second readings of each connection's
695 // round trip and inbound jitter (peer id -> qualitySample's record),
696 // emptied by every report; the facts the last window's report held,
697 // for the rules that need two windows in a row; the automatic report's
698 // gate for this participation ({token, count, last}); and the gate's
699 // forced trigger (window.meet.autoReportForTest), spent by the next
700 // window.
701 const qualitySamples = new Map();
702 let autoPrevFacts = null;
703 let autoGate = autoReportGate(null, '');
704 let autoForce = '';
705 // How many rosters this tab has applied. Nothing in the page reads
706 // it: it is the one fact a gate cannot infer from the DOM or from
707 // `peers`, because a connection can be closed locally without any
708 // roster having arrived, and "recovered" has to mean the server said
709 // so (Codex S2-16).
710 let rosters = 0;
711
712 // ---------------------------------------------------------------
713 // Preferences, stored by the holding screen (devices.js)
714 // ---------------------------------------------------------------
715
716 function loadPrefs() {
717 try {
718 return JSON.parse(localStorage.getItem(DEVICE_KEY) || '{}') || {};
719 } catch {
720 return {};
721 }
722 }
723
724 function savePrefs() {
725 try {
726 localStorage.setItem(DEVICE_KEY, JSON.stringify(prefs));
727 } catch {
728 // Private browsing or a full quota: the toggle still works for
729 // this call, it just will not be remembered for the next one.
730 }
731 }
732
733 // ---------------------------------------------------------------
734 // Local media (§3.3's stored choices, §5.1's tracks)
735 // ---------------------------------------------------------------
736
737 // audioConstraints builds the microphone half of a getUserMedia
738 // request out of the stored preferences. It is a pure function of
739 // `prefs` so the gate can lift it out of both files and check the two
740 // copies still agree (test/browser/audio.test.mjs). room.js carries
741 // it verbatim, because the room asks for a stream of its own at join
742 // — the holding screen's is stopped by then — and a choice that held
743 // on one page and not the other would be worse than no choice.
744 //
745 // The three flags are the browser's voice pipeline: echo
746 // cancellation, noise suppression and automatic gain. Every browser
747 // turns all three on for a microphone unless told otherwise, which is
748 // right for a laptop on a kitchen table and wrong for an interface in
749 // a room someone has treated — gain riding a held note, noise
750 // suppression taking a cello for a fan. `rawAudio` is the person
751 // saying which of those two rooms they are in.
752 //
753 // They are asked for as ideals and never as `exact`. A browser that
754 // cannot turn its processing off should hand over a processed
755 // microphone, not refuse getUserMedia and cost the person their
756 // voice — the same rule the device ladder is built on. It is also why
757 // the holding screen checks afterwards what it was actually given
758 // (rawHonoured) instead of trusting that it got what it asked for.
759 //
760 // voiceIsolation is the newer, heavier filter in Safari and Chrome —
761 // on a Mac it is Apple's own system Voice Isolation, reached through
762 // the browser. It is only ever asked for *off*, and never on. Asked
763 // on, it runs on top of the noise suppression above rather than
764 // instead of it, and two suppressors chewing one voice is not twice
765 // as clean: it is a growl with the keystrokes still coming through,
766 // which is what a call on 2026-09-17 came back as. The pipeline above
767 // is every browser's own default and is the one this app asks for.
768 //
769 // Off it still belongs here, because someone may have turned Voice
770 // Isolation on for the whole machine and studio audio has to be able
771 // to say no to it. An unknown constraint name in this basic,
772 // non-exact form is dropped rather than refused, so naming it costs
773 // nothing in a browser that has never heard of it.
774 function audioConstraints(prefs) {
775 const processed = !prefs.rawAudio;
776 const constraints = {
777 echoCancellation: processed,
778 noiseSuppression: processed,
779 autoGainControl: processed,
780 };
781 if (!processed) constraints.voiceIsolation = false;
782 if (prefs.mic) constraints.deviceId = { exact: prefs.mic };
783 return constraints;
784 }
785
786 // tuneAudioSender raises the audio ceiling on one connection, and is
787 // the other half of what studio audio promises: turning the filters
788 // off buys nothing if the result then goes out through Opus at its
789 // default of roughly 32 kbit/s mono, which is a codec a good
790 // microphone is heard *through* rather than heard.
791 //
792 // It is a sender-side change, so it needs no SDP of our own and no
793 // renegotiation, and §5.1's perfect negotiation above never learns it
794 // happened. Stereo is deliberately not attempted: it lives in the
795 // fmtp line, and reaching it would mean building offers by hand
796 // instead of the argumentless setLocalDescription §5.1 is written on
797 // — a large risk to the one part of this file that must not wobble,
798 // bought for a microphone that is almost always mono anyway.
799 //
800 // Every step is optional in some browser that is otherwise fine, so
801 // the whole thing is best effort: a browser that will not take the
802 // parameters carries the call at its own bitrate rather than losing
803 // the connection over it. The encodings array is read right after
804 // addTrack, which is where Chromium has already built it; a browser
805 // that fills it in later simply keeps its default here, and that is a
806 // quieter microphone and not a broken one.
807 function tuneAudioSender(pc) {
808 let sender;
809 try {
810 sender = pc.getSenders().find((s) => s.track && s.track.kind === 'audio');
811 } catch {
812 return;
813 }
814 if (!sender || typeof sender.getParameters !== 'function') return;
815 let params;
816 try {
817 params = sender.getParameters();
818 } catch {
819 return;
820 }
821 // A sender the browser has not built encodings for yet is not one to
822 // invent an encodings array for: that is a different request, and
823 // not the one this function is making.
824 if (!params.encodings || !params.encodings.length) return;
825 // Both directions. Studio audio turned off mid-call has to give the
826 // ceiling back, and `undefined` — not zero, which is a request to
827 // send nothing — is how the API spells "the encoder's own default".
828 if (prefs.rawAudio) params.encodings[0].maxBitrate = RAW_AUDIO_BITRATE;
829 else delete params.encodings[0].maxBitrate;
830 Promise.resolve().then(() => sender.setParameters(params)).catch(() => {
831 // Chromium refuses parameters that did not come from the most
832 // recent getParameters, which a renegotiation in flight can cause.
833 // The call is unharmed, and the next connection gets its own try.
834 });
835 }
836
837 // sharePlan is what a shared screen is sent as, for one "Optimise
838 // for" mode and the capture's size. Pure, and lifted by name in the
839 // node test; the native app's ScreenSendPolicy is its twin, and the two
840 // are meant to agree number for number.
841 //
842 // Why it exists (2026-09-24, "the screenshare isn't keeping up"): a
843 // screen capture left to the browser's defaults keeps every pixel and
844 // drops frames, at the encoder's default ceiling of about 2.5 Mbit/s
845 // for 1080p. On anything but a fast uplink that is a few frames a
846 // second of someone scrolling.
847 //
848 // detail full resolution, frames give way — slides, code, text
849 // balanced frame rate held, full size while the link carries it
850 // and smaller rather than a slideshow when it cannot
851 // motion frame rate held, at most 1280 on the long side
852 //
853 // Measured in the native gate (ScreenSendPolicy has the numbers): on a
854 // 1.5 Mbit/s uplink a scrolling 1080p page arrived at 2 fps as before,
855 // 13 in detail, 19 in balanced and 30 in motion.
856 //
857 // contentHint is the browser's own name for the same choice, and
858 // degradationPreference the sender's; both are set because browsers
859 // honour one or the other.
860 function sharePlan(mode, width, height) {
861 const longest = Math.max(width || 0, height || 0);
862 const fit = (side) => (longest > side ? longest / side : 1);
863 const high = { priority: 'high', networkPriority: 'high', maxFramerate: 30 };
864 if (mode === 'detail') {
865 return {
866 contentHint: 'detail', degradationPreference: 'maintain-resolution',
867 encoding: Object.assign({ maxBitrate: 3500000, scaleResolutionDownBy: fit(1920) }, high),
868 };
869 }
870 if (mode === 'motion') {
871 return {
872 contentHint: 'motion', degradationPreference: 'maintain-framerate',
873 encoding: Object.assign({ maxBitrate: 2500000, scaleResolutionDownBy: fit(1280) }, high),
874 };
875 }
876 return {
877 contentHint: 'detail', degradationPreference: 'maintain-framerate',
878 encoding: Object.assign({ maxBitrate: 3000000, scaleResolutionDownBy: fit(1920) }, high),
879 };
880 }
881
882 // cameraCap is the camera's encoding while this tab shares a screen,
883 // and its defaults again when it stops: the screen is what everyone is
884 // looking at, and it should have the uplink. `undefined` rather than a
885 // number is how the API spells "the encoder's own choice". Pure, and
886 // lifted by name in the node test.
887 function cameraCap(sharing, height) {
888 if (!sharing) return { maxBitrate: undefined, scaleResolutionDownBy: 1 };
889 return { maxBitrate: 500000, scaleResolutionDownBy: height > 360 ? height / 360 : 1 };
890 }
891
892 function shareMode() {
893 return SHARE_MODES.some(([m]) => m === prefs.shareMode) ? prefs.shareMode : SHARE_MODES[0][0];
894 }
895
896 // tuneSender sets one sender's first encoding (and, where given, its
897 // degradation preference). Best effort for the same reasons as
898 // tuneAudioSender: a sender parameter needs no SDP and no
899 // renegotiation, so §5.1 never learns it happened, and a browser that
900 // refuses carries the call at its own defaults.
901 function tuneSender(sender, encoding, degradationPreference) {
902 if (!sender || typeof sender.getParameters !== 'function') return;
903 let params;
904 try {
905 params = sender.getParameters();
906 } catch {
907 return;
908 }
909 if (!params.encodings || !params.encodings.length) return;
910 for (const [key, value] of Object.entries(encoding)) {
911 if (value === undefined) delete params.encodings[0][key];
912 else params.encodings[0][key] = value;
913 }
914 if (degradationPreference) params.degradationPreference = degradationPreference;
915 Promise.resolve().then(() => sender.setParameters(params)).catch(() => {
916 // Refused, or raced a renegotiation: the next call to this for the
917 // same sender (a mode change, the next connection) tries again.
918 });
919 }
920
921 // tuneShare puts one connection's screen and camera where the mode
922 // wants them: the screen at its plan, the camera capped beside it —
923 // or, with nothing shared, the camera back at its defaults.
924 //
925 // §15.30: at the level this connection's peer asks of us
926 // (entry.sentLevel), and with no camera at all to anyone while the
927 // person's own Video quality is Audio only.
928 function tuneShare(entry) {
929 if (!entry) return;
930 const sharing = !!(share && entry.shareTx);
931 const level = entry.sentLevel || 0;
932 if (sharing) {
933 const s = share.track.getSettings ? share.track.getSettings() : {};
934 const plan = screenAtLevel(sharePlan(shareMode(), s.width, s.height), level, s.width, s.height);
935 tuneSender(entry.shareTx.sender, plan.encoding, plan.degradationPreference);
936 }
937 const camera = senderFor(entry, 'video');
938 const track = camera && camera.sender && camera.sender.track;
939 if (!track) return;
940 const settings = track.getSettings ? track.getSettings() : {};
941 // This device's own trouble lowers its camera to everyone, never its
942 // screen or its audio.
943 const cameraLevel = videoSetting() === 'audio' ? 3 : Math.max(level, localAdapt.level);
944 const encoding = cameraAtLevel(cameraLevel, sharing, settings.width || 0, settings.height || 0);
945 // The camera watch's to know: a camera paused on purpose encodes
946 // nothing, and that is not a stalled encoder.
947 entry.cameraPaused = encoding.active === false;
948 tuneSender(camera.sender, encoding);
949 }
950
951 // startLocal walks down a ladder: the remembered devices, then the
952 // browser's defaults, then audio alone. A camera that is missing or
953 // in use should not cost the call its microphone as well, and a
954 // person who reaches the bottom rung joins with nothing, which the
955 // room is built to allow.
956 async function startLocal() {
957 if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
958 applyToggles();
959 return;
960 }
961 const exact = (id) => ({ deviceId: { exact: id } });
962 const remembered = !!(prefs.mic || prefs.camera);
963 // The processing choice rides every rung. Falling back to the
964 // browser's default *device* is not a reason to put the voice
965 // pipeline back on someone who asked for it off, so only the
966 // remembered device id is dropped on the way down — by
967 // forgetDevices, which touches mic and camera and never rawAudio.
968 const raw = { rawAudio: prefs.rawAudio };
969 const attempts = [
970 { audio: audioConstraints(prefs), video: prefs.camera ? exact(prefs.camera) : true },
971 { audio: audioConstraints(raw), video: true },
972 { audio: audioConstraints(raw), video: false },
973 ];
974 for (let i = 0; i < attempts.length; i++) {
975 try {
976 local = await navigator.mediaDevices.getUserMedia(attempts[i]);
977 if (i > 0 && remembered) forgetDevices();
978 break;
979 } catch {
980 // Try the next rung. Nothing is said on the way down: the only
981 // thing worth telling a person is where they ended up.
982 }
983 }
984 applyToggles();
985 }
986
987 // forgetDevices drops remembered ids the browser would not honour, so
988 // the next visit does not repeat the same failed attempt. devices.js
989 // does the same on the holding screen; this is the room's copy for
990 // the case where the device went between the two pages.
991 function forgetDevices() {
992 delete prefs.mic;
993 delete prefs.camera;
994 savePrefs();
995 }
996
997 function applyToggles() {
998 if (local) {
999 for (const track of local.getAudioTracks()) track.enabled = !prefs.muted;
1000 for (const track of local.getVideoTracks()) track.enabled = !prefs.cameraOff;
1001 }
1002 // The accessible name is fixed, in aria-label on the server's own
1003 // markup; a toggle whose name changes under the reader is announced
1004 // as a different control every time it is used. The state moves
1005 // three ways and never by colour: aria-pressed, the word in the
1006 // button, and calls.css's inset outline.
1007 muteButton.setAttribute('aria-pressed', String(!!prefs.muted));
1008 cameraButton.setAttribute('aria-pressed', String(!!prefs.cameraOff));
1009 if (muteState) muteState.textContent = prefs.muted ? 'Muted' : 'On';
1010 if (cameraState) cameraState.textContent = prefs.cameraOff ? 'Off' : 'On';
1011 // With no stream there is no track to enable, so the two toggles
1012 // are controls that would do nothing. Leave is still live.
1013 const hasAudio = !!(local && local.getAudioTracks().length);
1014 const hasVideo = !!(local && local.getVideoTracks().length);
1015 if (!state.stopped) {
1016 muteButton.disabled = !hasAudio;
1017 cameraButton.disabled = !hasVideo;
1018 }
1019 // §15.19: every path that can change what we send ends here — the
1020 // two toggles, a device switch, a stream that lost a track — so the
1021 // report is made here too, and the tile marks follow.
1022 reportMedia();
1023 if (tiles.has('self')) markTile('self', localMedia());
1024 }
1025
1026 function stopLocal() {
1027 if (!local) return;
1028 for (const track of local.getTracks()) track.stop();
1029 local = null;
1030 }
1031
1032 // ---------------------------------------------------------------
1033 // Changing a device mid-call (§3.3's stored choice, made movable)
1034 // ---------------------------------------------------------------
1035 //
1036 // The holding screen picks the devices; until now that was the only
1037 // place they could be picked, and a microphone chosen wrongly — or
1038 // unplugged, or wanted for a headset halfway through — cost the
1039 // person the call to change. Everything below is that choice, applied
1040 // to a call already running.
1041 //
1042 // The whole thing rests on replaceTrack, which swaps the media a
1043 // sender is sending without touching the m-line it sends on. That is
1044 // the part §5.1 never has to hear about: no offer, no answer, no
1045 // rollback, and no chance of the glare the negotiation above spends
1046 // 300 ms avoiding. The one case that does renegotiate is named at
1047 // sendTrack, and it is a direction change on an m-line that already
1048 // exists rather than a new one.
1049
1050 // Two clicks on a picker are two switches, and they must not run at
1051 // once. devices.js can settle that with a generation counter alone
1052 // because the only thing it is racing for is one <video>; here the
1053 // loser would be racing for what every sender in the mesh is holding,
1054 // and interleaved replaceTracks leave that decided by whichever
1055 // getUserMedia happened to settle last.
1056 //
1057 // So they are serialised, and the counter only decides which queued
1058 // run is still wanted: three clicks queue three runs, the first two
1059 // find themselves superseded before their turn and return without
1060 // opening anything, and the third does the work. One switch is in
1061 // flight at a time and the last click wins, which is what clicking
1062 // means.
1063 // One counter per kind, not one between them: a camera and a
1064 // microphone are two independent choices, and a shared counter made
1065 // changing the camera silently cancel a microphone change whose
1066 // getUserMedia had not settled — the select snapping back with
1067 // nothing said about why.
1068 const switching = { audio: 0, video: 0 };
1069 let switchQueue = Promise.resolve();
1070
1071 // senderFor finds the transceiver carrying one kind for this call —
1072 // the camera or the microphone, never the screen. entry.shareTx is
1073 // video too, and replacing *its* track with a camera would put the
1074 // camera on the m-line the far side has already labelled a screen
1075 // (§5.4), which is the one mistake here that would look like a bug in
1076 // someone else's browser.
1077 function senderFor(entry, kind) {
1078 let transceivers;
1079 try {
1080 transceivers = entry.pc.getTransceivers();
1081 } catch {
1082 return null;
1083 }
1084 for (const tx of transceivers) {
1085 if (tx === entry.shareTx || tx.stopped) continue;
1086 // receiver.track is present on every transceiver and carries the
1087 // kind even when nothing is being sent yet, which is exactly the
1088 // recvonly case this has to find.
1089 const known = (tx.sender && tx.sender.track) || (tx.receiver && tx.receiver.track);
1090 if (known && known.kind === kind) return tx;
1091 }
1092 return null;
1093 }
1094
1095 // sendTrack puts one track on one connection.
1096 //
1097 // The replaceTrack is the whole job when this browser was already
1098 // sending that kind. When it was not — it came down startLocal's
1099 // ladder with no camera, or joined with nothing at all — createPC
1100 // left a `recvonly` transceiver for the kind, and that m-line is
1101 // already in the right place in the order. Turning it round is a
1102 // direction change on an existing m-line, so no m-line is added and
1103 // none moves: the hazard addShareTo carries (an unassociated
1104 // transceiver claiming the m-line a remote offer meant for something
1105 // else) is not in this path at all. It still waits for `stable`,
1106 // because a direction changed mid-negotiation is a change the offer
1107 // in flight does not carry, and the deferred ones are picked up by
1108 // the connection's own signalingstatechange.
1109 async function sendTrack(entry, kind, track) {
1110 const tx = senderFor(entry, kind);
1111 if (!tx || !tx.sender || typeof tx.sender.replaceTrack !== 'function') return;
1112 try {
1113 await tx.sender.replaceTrack(track);
1114 } catch {
1115 // A connection closing under us, or a browser refusing the track.
1116 // Every other peer still gets it, and this one is the reset path's
1117 // problem rather than this function's.
1118 return;
1119 }
1120 // classifyTrack reads entry.sentVideo to tell an arriving camera
1121 // from an arriving screen, and a browser that starts sending video
1122 // for the first time here has just changed that answer.
1123 if (kind === 'video') entry.sentVideo = true;
1124 if (tx.direction === 'sendrecv' || tx.direction === 'sendonly') return;
1125 if (entry.pc.signalingState !== 'stable') {
1126 entry.upgrades.add(kind);
1127 return;
1128 }
1129 try {
1130 tx.direction = 'sendrecv';
1131 } catch {
1132 // Older browsers make direction read-only. The track is on the
1133 // sender either way; it simply is not sent until the next full
1134 // renegotiation builds the m-line sending.
1135 }
1136 }
1137
1138 // upgradeWhenQuiet runs the direction changes sendTrack could not make
1139 // because the connection was mid-negotiation. Called from the same
1140 // signalingstatechange that adds a deferred share transceiver.
1141 function upgradeWhenQuiet(entry) {
1142 if (!entry.upgrades.size || entry.pc.signalingState !== 'stable') return;
1143 for (const kind of Array.from(entry.upgrades)) {
1144 entry.upgrades.delete(kind);
1145 const tx = senderFor(entry, kind);
1146 if (!tx || !tx.sender || !tx.sender.track) continue;
1147 if (tx.direction === 'sendrecv' || tx.direction === 'sendonly') continue;
1148 try {
1149 tx.direction = 'sendrecv';
1150 } catch {
1151 // As above: nothing to do about it, and nothing broken by it.
1152 }
1153 }
1154 }
1155
1156 // switchDevice is the gesture: one kind, one device id, applied to
1157 // every connection and then to the local stream.
1158 //
1159 // Order matters twice here. The new track is disabled before it is
1160 // anywhere near a sender, because a track that goes live for even one
1161 // frame while the person is muted has broken the only promise the
1162 // mute button makes. And the old track is stopped only once the new
1163 // one is on every sender: stopping it first would take the camera
1164 // light off a beat early and send black frames in the gap.
1165 function switchDevice(kind, deviceId) {
1166 const myGen = ++switching[kind];
1167 const run = switchQueue.then(() => applySwitch(kind, deviceId, myGen));
1168 // The queue must not break on a failure, or one rejected switch
1169 // would swallow every switch after it. The caller still sees the
1170 // rejection through `run`.
1171 switchQueue = run.catch(() => {});
1172 return run;
1173 }
1174
1175 // Returns true when the call is actually on the new device, so a
1176 // caller that changed a preference to ask for the switch can put it
1177 // back when the switch did not happen.
1178 async function applySwitch(kind, deviceId, myGen) {
1179 // Superseded before this run's turn came round, or the call ended
1180 // while it waited. Nothing has been opened yet, so there is nothing
1181 // to put back.
1182 if (myGen !== switching[kind] || state.stopped) return false;
1183 const wanted = kind === 'audio'
1184 ? { audio: audioConstraints(Object.assign({}, prefs, { mic: deviceId })) }
1185 : { video: deviceId ? { deviceId: { exact: deviceId } } : true };
1186 let fresh;
1187 try {
1188 fresh = await navigator.mediaDevices.getUserMedia(wanted);
1189 } catch (err) {
1190 if (myGen !== switching[kind]) return false;
1191 note(deviceError(kind, err));
1192 // The choice is not saved: the pickers are put back to the device
1193 // actually in use, so the select never claims a device the call is
1194 // not on.
1195 fillDevices().catch(() => {});
1196 return false;
1197 }
1198 const track = fresh.getTracks()[0];
1199 if (myGen !== switching[kind] || !track || state.stopped) {
1200 for (const t of fresh.getTracks()) t.stop();
1201 return false;
1202 }
1203 track.enabled = kind === 'audio' ? !prefs.muted : !prefs.cameraOff;
1204 for (const entry of pcs.values()) {
1205 // Sequential and not Promise.all: replaceTrack is cheap, the mesh
1206 // is four, and a failure on one connection should not abandon the
1207 // rest through a rejected race.
1208 await sendTrack(entry, kind, track);
1209 }
1210 // No *generation* check here, and that is deliberate. From the loop
1211 // above onwards this run owns what every sender is holding, so
1212 // stopping the track to defer to a newer choice would stop the
1213 // media the call is sending — until that newer choice arrives, which
1214 // it may never do if its own getUserMedia fails, leaving every peer
1215 // watching a track that ended. The queued run replaces the senders
1216 // and `local` together when its turn comes; until then this is the
1217 // truth and is recorded as such.
1218 //
1219 // The call *ending* is the other thing entirely, and does need
1220 // checking: terminal() leaves the page alive, so without this the
1221 // line below would build a fresh MediaStream around a camera that
1222 // was opened for a call that is already over, and nothing would
1223 // ever stop it. A light left on after the meeting ended is the one
1224 // way this file can be rude.
1225 if (state.stopped) {
1226 track.stop();
1227 return false;
1228 }
1229 if (!local) local = new MediaStream();
1230 for (const old of kind === 'audio' ? local.getAudioTracks() : local.getVideoTracks()) {
1231 local.removeTrack(old);
1232 old.stop();
1233 }
1234 local.addTrack(track);
1235 // A track that ends on its own — the device unplugged mid-call —
1236 // should leave the pickers telling the truth about what is left.
1237 track.addEventListener('ended', () => {
1238 fillDevices().catch(() => {});
1239 });
1240 // An id that names nothing is the browser's default, and the
1241 // absence of a remembered device is how the rest of this file and
1242 // devices.js both spell that.
1243 const key = kind === 'audio' ? 'mic' : 'camera';
1244 if (deviceId) prefs[key] = deviceId;
1245 else delete prefs[key];
1246 savePrefs();
1247 note('');
1248 applyToggles();
1249 renderTiles();
1250 // The audio ceiling follows the choice and not the connection: a
1251 // studio switch flipped mid-call has to reach the connections that
1252 // already exist, and flipped back has to let them go again.
1253 // tuneAudioSender reads the preference itself, so this is the same
1254 // call in both directions.
1255 if (kind === 'audio') {
1256 for (const entry of pcs.values()) tuneAudioSender(entry.pc);
1257 }
1258 await fillDevices().catch(() => {});
1259 return true;
1260 }
1261
1262 // deviceError is the sentence for a device that would not open. The
1263 // names are getUserMedia's own; the wording says what the person can
1264 // do about it, and never that the call is over, because it is not —
1265 // the old device is still on every sender.
1266 function deviceError(kind, err) {
1267 const thing = kind === 'audio' ? 'microphone' : 'camera';
1268 if (err && err.name === 'NotAllowedError') {
1269 return 'Calls needs permission to use that ' + thing + '. The call is still on the previous one.';
1270 }
1271 if (err && err.name === 'NotReadableError') {
1272 return 'That ' + thing + ' is in use by another app. The call is still on the previous one.';
1273 }
1274 return 'That ' + thing + ' could not be opened. The call is still on the previous one.';
1275 }
1276
1277 // note writes the device panel's own live region. It is not `say`:
1278 // renderStatus owns #status and rewrites it on every render, so a
1279 // sentence put there would be gone by the next roster.
1280 function note(text) {
1281 if (!deviceNote) return;
1282 deviceNote.textContent = text;
1283 deviceNote.hidden = !text;
1284 }
1285
1286 // fillDevices is devices.js's fillPickers, for the room. The two are
1287 // deliberate mirrors — same ids, same rules, same reason for each —
1288 // and test/browser/devices.test.mjs holds them to it. Labels only
1289 // exist once permission has been granted, which in the room it always
1290 // has by the time this runs.
1291 async function fillDevices() {
1292 if (!pickCamera || !navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) return;
1293 let devices;
1294 try {
1295 devices = await navigator.mediaDevices.enumerateDevices();
1296 } catch {
1297 devices = [];
1298 }
1299 const fillOne = (select, kind, chosen) => {
1300 select.replaceChildren();
1301 let count = 0;
1302 for (const device of devices) {
1303 if (device.kind !== kind) continue;
1304 count++;
1305 const option = document.createElement('option');
1306 option.value = device.deviceId;
1307 option.textContent = device.label || labelFor(kind, count);
1308 if (device.deviceId === chosen) option.selected = true;
1309 select.append(option);
1310 }
1311 return count;
1312 };
1313 const cameraCount = fillOne(pickCamera, 'videoinput', liveDeviceId('video') || prefs.camera);
1314 const micCount = fillOne(pickMic, 'audioinput', liveDeviceId('audio') || prefs.mic);
1315 const speakerCount = HAS_SINK_ID ? fillOne(pickSpeaker, 'audiooutput', prefs.speaker) : 0;
1316 // A field with nothing to choose from is clutter, not help. Unlike
1317 // the holding screen, the camera and microphone rows can be empty
1318 // here too — a call joined with neither is a call this file is
1319 // built to allow.
1320 if (cameraRow) cameraRow.hidden = cameraCount === 0;
1321 if (micRow) micRow.hidden = micCount === 0;
1322 if (speakerRow) speakerRow.hidden = !HAS_SINK_ID || speakerCount === 0;
1323 if (rawRow) rawRow.hidden = micCount === 0;
1324 }
1325
1326 function labelFor(kind, count) {
1327 return (kind === 'videoinput' ? 'Camera ' : 'Microphone ') + count;
1328 }
1329
1330 // liveDeviceId is what the call is *actually* on, which is the honest
1331 // thing for a select to be showing: prefs can name a device that
1332 // startLocal's ladder never managed to open.
1333 function liveDeviceId(kind) {
1334 const track = local && local.getTracks().find((t) => t.kind === kind && t.readyState === 'live');
1335 if (!track || typeof track.getSettings !== 'function') return '';
1336 return track.getSettings().deviceId || '';
1337 }
1338
1339 // applySinkAll re-routes every remote tile after a speaker change.
1340 // applySink does one element and is what a new tile gets; this is the
1341 // same thing for the tiles that already exist.
1342 function applySinkAll() {
1343 for (const [key, t] of tiles) {
1344 if (t.self || key === 'self') continue;
1345 applySink(t.video);
1346 }
1347 }
1348
1349 // ---------------------------------------------------------------
1350 // The stream (§4.1, §4.5)
1351 // ---------------------------------------------------------------
1352
1353 const DOWNSTREAM = ['hello', 'roster', 'peer', 'gone', 'knock', 'knock-gone',
1354 'full', 'lost', 'pair', 'gap', 'state', 'offer', 'answer', 'candidate',
1355 // §4.3's fan-out pair. They carry no `to`, no `seq` and no `gen`, so
1356 // nothing about them goes through §4.6's inbound rules: the hub
1357 // rebuilt the envelope and there is nothing to dedupe against.
1358 'chat', 'share',
1359 // §15.19: one peer's media state changed. State, not an event —
1360 // the roster carries it too — so a missed one costs nothing.
1361 'media'];
1362
1363 function streamPath(peer) {
1364 let path = '/m/' + encodeURIComponent(sqid) + '/stream';
1365 if (!peer) return path;
1366 const last = {};
1367 for (const [id, seq] of lastIn) last[id] = seq;
1368 return path + '?peer=' + encodeURIComponent(peer) +
1369 '&last=' + encodeURIComponent(JSON.stringify(last));
1370 }
1371
1372 function closeStream() {
1373 if (!es) return;
1374 // Always close by hand. EventSource reconnects on its own, and its
1375 // own retry of a fresh (peerless) URL would ask for a second
1376 // participation and be refused 409 — reconnection is this file's
1377 // job, not the browser's.
1378 es.onerror = null;
1379 es.close();
1380 es = null;
1381 }
1382
1383 // connectStream opens a fresh stream: no `peer`, so the hub issues a
1384 // new participation and this browser posts `join` on its `hello`.
1385 function connectStream() {
1386 if (state.stopped) return;
1387 closeStream();
1388 state.peer = null;
1389 state.joined = false;
1390 state.admitted = false;
1391 // `full` belongs to the participation that heard it, not to the tab.
1392 state.full = false;
1393 clearTimeout(fullTimer);
1394 renderStatus();
1395 attach(streamPath(null), diagnoseFresh);
1396 }
1397
1398 // resume reattaches to the participation we already hold. EventSource
1399 // hides the status of a refused stream, so the refusal is read first
1400 // with a plain fetch against ?probe=1 — which attaches nothing and,
1401 // per the wire contract, must NOT carry Accept: text/event-stream.
1402 async function resume() {
1403 if (state.stopped) return;
1404 closeStream();
1405 const peer = state.peer;
1406 if (!peer) {
1407 connectStream();
1408 return;
1409 }
1410 let res;
1411 try {
1412 // Bounded like every other probe: a request that never settles
1413 // would otherwise be the end of this browser's reconnecting.
1414 res = await probe('/m/' + encodeURIComponent(sqid) + '/stream?probe=1&peer=' + encodeURIComponent(peer),
1415 Date.now() + SEND_DEADLINE);
1416 } catch {
1417 later(resume);
1418 return;
1419 }
1420 if (state.stopped) return;
1421 if (refused(res)) return;
1422 if (res.status === 204) {
1423 // "A resume would attach" — not "a resume is free". If this
1424 // round produces no hello either, the stall count is what stops
1425 // the loop.
1426 if (stall()) return;
1427 attach(streamPath(peer), resume);
1428 return;
1429 }
1430 if (res.status === 410) {
1431 terminal(res.data.reason || 'ended');
1432 return;
1433 }
1434 if (res.status === 404) {
1435 // Either the process restarted (a different boot) or the window
1436 // lapsed (the same one). Both answers are the same: drop every
1437 // connection and enter afresh — but only after the local
1438 // connections are closed, so no media survives a restart.
1439 closeAllPCs();
1440 state.boot = res.data.boot || state.boot;
1441 connectStream();
1442 return;
1443 }
1444 if (res.status === 409) {
1445 terminal('replaced');
1446 return;
1447 }
1448 // A status the contract does not name (500, or anything a proxy
1449 // invented): retry, but not for ever.
1450 if (stall()) return;
1451 later(resume);
1452 }
1453
1454 // diagnoseFresh runs when a fresh stream failed to open. The peerless
1455 // probe says whether this session already holds a peer here (409) or
1456 // whether the room is gone (404); a 204 means the refusal was
1457 // something the probe cannot see — a full room, or the network.
1458 async function diagnoseFresh() {
1459 if (state.stopped) return;
1460 let res;
1461 try {
1462 res = await probe('/m/' + encodeURIComponent(sqid) + '/stream?probe=1', Date.now() + SEND_DEADLINE);
1463 } catch {
1464 later(connectStream);
1465 return;
1466 }
1467 if (state.stopped) return;
1468 if (refused(res)) return;
1469 if (res.status === 409) {
1470 terminal('replaced');
1471 return;
1472 }
1473 if (res.status === 404) {
1474 terminal('gone');
1475 return;
1476 }
1477 // 204 here means only "this session holds no peer in this room".
1478 // The stream that follows can still be refused 503 for a full
1479 // room, which the probe cannot see, so this round is counted.
1480 if (stall()) return;
1481 later(connectStream);
1482 }
1483
1484 // refused is the two answers that mean "stop, and say why", wherever
1485 // they turn up: a session that has ended, and a request the stream
1486 // endpoint will not accept in the shape this client sends it.
1487 //
1488 // There is no arm for 400 (review W-8). Both callers pass a probe
1489 // response, the stream's only 400 is a `last` it could not parse, and
1490 // neither probe form sends `last` — so the arm that used to be here
1491 // could not fire. The attaching stream's 400 is invisible to
1492 // EventSource anyway: it arrives as an error with no status, and the
1493 // stall ladder is what ends it.
1494 function refused(res) {
1495 if (res.signedOut) {
1496 terminal('signedout');
1497 return true;
1498 }
1499 if (res.status === 406) {
1500 terminal('accept');
1501 return true;
1502 }
1503 return false;
1504 }
1505
1506 // stall counts consecutive rounds that ended without a `hello`. A
1507 // network failure is not one of them: an unreachable server is worth
1508 // waiting for, and the browser says nothing new by giving up on it.
1509 function stall() {
1510 stalls += 1;
1511 if (stalls < MAX_STALLS) return false;
1512 if (Date.now() - lastHelloAt < STALL_WINDOW) return false;
1513 terminal('unreachable');
1514 return true;
1515 }
1516
1517 function attach(path, onFail) {
1518 const source = new EventSource(path);
1519 const openedAt = Date.now();
1520 es = source;
1521 for (const type of DOWNSTREAM) {
1522 source.addEventListener(type, (ev) => {
1523 if (source !== es) return;
1524 let msg;
1525 try {
1526 msg = JSON.parse(ev.data);
1527 } catch {
1528 return;
1529 }
1530 handle(type, msg);
1531 });
1532 }
1533 source.onerror = () => {
1534 if (source !== es) return;
1535 closeStream();
1536 if (state.stopped) return;
1537 if (!streamDownSince) streamDownSince = Date.now();
1538 // Only a stream that actually lived clears the backoff. One that
1539 // died moments after its hello has not proved anything, and
1540 // resetting on the hello alone is how a tight reconnect loop
1541 // starts.
1542 if (Date.now() - openedAt > HEALTHY_STREAM) backoff = BACKOFF_MIN;
1543 if (state.peer) {
1544 later(resume);
1545 return;
1546 }
1547 // No participation to come back to, so this goes to the fresh
1548 // ladder's own diagnosis — which waits before it retries. Waiting
1549 // here as well would put two backoffs in every round, and double
1550 // the ladder's own doubling.
1551 onFail();
1552 };
1553 }
1554
1555 // `deadline` is an absolute instant, and it bounds the whole exchange
1556 // — the request and the reading of its body — because both are the
1557 // same fetch and an AbortController ends both. Without it a probe that
1558 // never settles never returns, and every caller here awaits it: the
1559 // recovery's deadline was checked only between attempts, so a hanging
1560 // probe held its target's pump or reset marked in flight for as long
1561 // as the request stayed open (Codex S2-15).
1562 async function probe(path, deadline) {
1563 let stop = 0;
1564 let controller = null;
1565 if (deadline && typeof AbortController === 'function') {
1566 controller = new AbortController();
1567 stop = setTimeout(() => controller.abort(), Math.max(0, deadline - Date.now()));
1568 }
1569 try {
1570 // No Accept header: the probe forms are exempt from the stream's
1571 // text/event-stream gate and must not claim to be one.
1572 const res = await fetch(path, {
1573 credentials: 'same-origin',
1574 cache: 'no-store',
1575 signal: controller ? controller.signal : undefined,
1576 });
1577 return await readRefusal(res, 204, path);
1578 } finally {
1579 if (stop) clearTimeout(stop);
1580 }
1581 }
1582
1583 // readRefusal turns one response into the shape every caller here
1584 // branches on. `emptyOK` is the one status that legitimately carries
1585 // no body — 204 from the stream probe, 200 from the signal endpoint.
1586 //
1587 // The signed-out case needs saying: an expired session answers 303 to
1588 // /signin, fetch follows it, and what comes back is a 200 carrying a
1589 // sign-in page, which read as a status alone is indistinguishable
1590 // from success.
1591 //
1592 // A redirect on its own is not that, though, which is why `asked` is
1593 // passed in: a redirect that lands back on the path it was sent to —
1594 // a proxy normalising a URL, a trailing slash, anything a deployment
1595 // might do in front of this app — is not a sign-out, and treating it
1596 // as one would end a working call with a sentence about signing in.
1597 // Only a redirect that came out somewhere else counts.
1598 async function readRefusal(res, emptyOK, asked) {
1599 let data = null;
1600 if (res.status !== emptyOK) {
1601 try {
1602 data = await res.json();
1603 } catch {
1604 data = null;
1605 }
1606 }
1607 const signedOut = wentElsewhere(res, asked) || res.status === 401 || res.status === 403 ||
1608 (res.status === 200 && res.status !== emptyOK && data === null);
1609 return { status: res.status, data: data || {}, signedOut, retryAfter: res.headers.get('Retry-After') };
1610 }
1611
1612 // Origin as well as pathname: a redirect off this origin is somewhere
1613 // else however familiar the path looks, and a sign-in page served from
1614 // an identity host would otherwise read as success.
1615 function wentElsewhere(res, asked) {
1616 if (!res.redirected) return false;
1617 try {
1618 const got = new URL(res.url);
1619 const want = new URL(asked, location.origin);
1620 return got.origin !== want.origin || got.pathname !== want.pathname;
1621 } catch {
1622 // A URL neither of them can parse is not one this browser asked
1623 // for: treat it the way the old check did.
1624 return true;
1625 }
1626 }
1627
1628 function later(fn) {
1629 if (state.stopped) return;
1630 clearTimeout(reconnectTimer);
1631 renderStatus();
1632 reconnectTimer = setTimeout(fn, backoff);
1633 backoff = Math.min(backoff * 2, STREAM_BACKOFF_MAX);
1634 }
1635
1636 // ---------------------------------------------------------------
1637 // Events (§4.3)
1638 // ---------------------------------------------------------------
1639
1640 function handle(type, msg) {
1641 // Every downstream event moves this on. It is not a clock and not a
1642 // sequence number the server would recognise — it is only this
1643 // browser's own count of what it has been told, and it exists so
1644 // that a roster can be compared with the connections built since it
1645 // arrived (see reconcile).
1646 tick += 1;
1647 switch (type) {
1648 case 'hello': return onHello(msg);
1649 case 'roster': return onRoster(msg);
1650 case 'peer': return onPeer(msg);
1651 case 'gone': return onGone(msg);
1652 case 'knock': return onKnock(msg);
1653 case 'knock-gone': return onKnockGone(msg);
1654 case 'full': return onFull();
1655 case 'state': return onState(msg);
1656 case 'pair': return onPair(msg);
1657 case 'gap': return onGap(msg);
1658 case 'lost': return onLost(msg);
1659 case 'offer': return onOffer(testBlockedMessage(msg));
1660 case 'answer': return onAnswer(testBlockedMessage(msg));
1661 case 'candidate': return onCandidate(testBlockedMessage(msg));
1662 case 'chat': return onChat(msg);
1663 case 'share': return onShare(msg);
1664 case 'media': return onMedia(msg);
1665 default: return undefined;
1666 }
1667 }
1668
1669 function onHello(msg) {
1670 // A hello is the proof that this round reached the room; the
1671 // backoff itself is cleared by attach, and only for a stream that
1672 // then stayed open.
1673 stalls = 0;
1674 lastHelloAt = Date.now();
1675 streamDownSince = 0;
1676 const fresh = !state.peer;
1677 state.peer = msg.peer || null;
1678 state.boot = msg.boot || state.boot;
1679 // §15.26: a resumed stream's hello carries the same token, and a new
1680 // participation's a new one; either way the latest is the one that
1681 // works. A server from before reports sends none, and nothing is sent.
1682 if (typeof msg.report === 'string' && /^[0-9a-f]{32}$/.test(msg.report)) reportToken = msg.report;
1683 root.dataset.peer = state.peer || '';
1684 if (fresh) join();
1685 renderStatus();
1686 }
1687
1688 async function join(attempt) {
1689 const round = attempt || 0;
1690 const peer = state.peer;
1691 const res = await postSignal({ peer, type: 'join' });
1692 if (state.stopped || state.peer !== peer) return;
1693 // signedOut before the status, because it can be true *of* a 200: a
1694 // session that has expired answers 303 to /signin, fetch follows
1695 // it, and the sign-in page comes back 200 — which read as a status
1696 // alone marked the join a success (Codex S2-8).
1697 if (res.signedOut) {
1698 terminal('signedout');
1699 return;
1700 }
1701 if (res.status === 200) {
1702 state.joined = true;
1703 // A guest gets nothing back from its own join: no roster, no
1704 // state. The waiting sentence is this browser's own conclusion,
1705 // not an event it waits for.
1706 renderStatus();
1707 return;
1708 }
1709 if (res.status === 404) {
1710 await recoverFromNotFound(res.data.boot);
1711 // The probe kept this participation, so the 404 raced something
1712 // rather than naming the end of it. `join` is idempotent: one
1713 // more go, and then it is the stream's ladder's problem.
1714 if (round === 0 && !state.stopped && state.peer === peer && !state.joined) {
1715 await sleep(BACKOFF_MIN);
1716 if (!state.stopped && state.peer === peer && !state.joined) join(1);
1717 }
1718 return;
1719 }
1720 // 429 and the transient failures are retried on the same peer, with
1721 // its own wait so a pending stream reconnect is never cancelled;
1722 // anything else leaves the sentence alone and the next roster or
1723 // knock speaks for itself.
1724 if (res.status === 429 || res.status >= 500 || res.status === 0) {
1725 await sleep(res.status === 429 ? retryAfter(res.retryAfter) : BACKOFF_MIN);
1726 if (!state.stopped && state.peer === peer && !state.joined) join(round);
1727 }
1728 }
1729
1730 function onPeer(msg) {
1731 const id = msg.peer;
1732 if (!id || id === state.peer) return;
1733 if (msg.name) names.set(id, msg.name);
1734 const rp = (msg.roster && msg.roster.peers && msg.roster.peers[0]) || {};
1735 const g = rp.gen || 1;
1736 if (rp.name) names.set(id, rp.name);
1737 clients.set(id, rp.client || '');
1738 learnMedia(id, rp.media);
1739 ensurePC(id, g);
1740 renderTiles();
1741 }
1742
1743 function onGone(msg) {
1744 if (!msg.from) return;
1745 remoteMedia.delete(msg.from);
1746 clients.delete(msg.from);
1747 recovery.delete(msg.from);
1748 closePC(msg.from, true);
1749 dropWaiting(msg.from);
1750 renderTiles();
1751 renderQueue();
1752 }
1753
1754 function onKnock(msg) {
1755 if (!msg.from) return;
1756 names.set(msg.from, msg.name || '');
1757 if (!waiting.some((w) => w.peer === msg.from)) {
1758 waiting = waiting.concat([{ peer: msg.from, name: msg.name || '' }]);
1759 }
1760 renderQueue();
1761 }
1762
1763 function onKnockGone(msg) {
1764 if (!msg.from) return;
1765 dropWaiting(msg.from);
1766 renderQueue();
1767 }
1768
1769 function dropWaiting(id) {
1770 waiting = waiting.filter((w) => w.peer !== id);
1771 }
1772
1773 // §4.3: a member who sees `full` may wait and retry, so this does —
1774 // once every five seconds, until a roster says we are in or the
1775 // stream ends. Nothing else in the room polls.
1776 function onFull() {
1777 state.full = true;
1778 renderStatus();
1779 clearTimeout(fullTimer);
1780 fullTimer = setTimeout(() => {
1781 if (state.stopped || state.admitted || !state.peer) return;
1782 join();
1783 }, FULL_RETRY);
1784 }
1785
1786 function onState(msg) {
1787 // The only `state` the server sends is waiting:true, on a resume of
1788 // a participation that has not been admitted. `waiting` uses
1789 // omitempty, so an absent field is false.
1790 if (!msg.waiting) return;
1791 // Not joined: this only ever confirms that the participation this
1792 // stream reattached to has not been admitted. `joined` is the
1793 // join's own answer and is not re-derived from an event.
1794 state.admitted = false;
1795 renderStatus();
1796 }
1797
1798 function onPair(msg) {
1799 const id = msg.peer;
1800 if (!id || !msg.gen) return;
1801 // A generation at or below the local one is a no-op, so duplicates
1802 // and reordering are harmless (§4.6).
1803 if (msg.gen <= (gen.get(id) || 0)) return;
1804 rebuildPC(id, msg.gen);
1805 }
1806
1807 function onGap(msg) {
1808 // The replay could not fill this sender's gap, so the pair is
1809 // reset: the hub bumps the generation and tells both sides (§4.6).
1810 if (msg.from) requestReset(msg.from);
1811 }
1812
1813 function onLost(msg) {
1814 const reason = msg.reason || 'ended';
1815 if (reason === 'buffer') {
1816 // The one reason that is followed by a resume, not a screen.
1817 closeStream();
1818 resume();
1819 return;
1820 }
1821 terminal(reason);
1822 }
1823
1824 // ---------------------------------------------------------------
1825 // Reconciliation (§4.5: the roster is the authority)
1826 // ---------------------------------------------------------------
1827
1828 // onRoster is the roster's door, and it keeps `handle` synchronous:
1829 // §5.2 puts one await in front of the first connection this browser
1830 // builds, and a rejection escaping an event listener goes where
1831 // neither a person nor a gate could see it. Same shape as the
1832 // pageshow handler's.
1833 function onRoster(msg) {
1834 // The newest roster wins, and the slot is what makes that true
1835 // across §5.2's await: a roster that arrives while the first /ice
1836 // fetch is out overwrites the one waiting to be applied, rather
1837 // than queueing behind it. Reconciling a superseded roster closes
1838 // connections the hub has since named — which is exactly how the
1839 // gate's three ICE scenarios died (Task 5's report): a `peer` event
1840 // ten milliseconds after the roster built a connection the captured
1841 // roster did not carry.
1842 pendingRoster = msg.roster || { peers: [] };
1843 pendingRosterAt = tick;
1844 applyRoster().catch((err) => {
1845 console.error('meet: roster', err);
1846 });
1847 }
1848
1849 // applyRoster is §5.2's ordering: the ICE list is fetched before the
1850 // first connection is built, and only before the first — every later
1851 // roster reconciles straight away. A fetch that fails does not hold
1852 // the room up: it leaves the floor's empty list in place, shows the
1853 // warning and arms the minute retry, and the roster is applied.
1854 //
1855 // Whatever it applies is read *after* the await, never before. Two
1856 // rosters that arrive during one fetch resume in order: the first
1857 // takes the newest of them and empties the slot, and the second finds
1858 // it empty and has nothing left to do.
1859 async function applyRoster() {
1860 if (!icePrimed) await iceReady();
1861 if (state.stopped) return;
1862 const roster = pendingRoster;
1863 const at = pendingRosterAt;
1864 pendingRoster = null;
1865 if (!roster) return;
1866 reconcile(roster, at);
1867 }
1868
1869 function reconcile(roster, at) {
1870 rosters += 1;
1871 lastRoster = roster;
1872 state.admitted = true;
1873 state.joined = true;
1874 state.full = false;
1875 // The roster is the authority on who is here (§4.5), so it settles
1876 // every target a 404 marked stale: the ones it lists get their
1877 // connection back through ensurePC below, and the ones it does not
1878 // are closed a few lines further down.
1879 stale.clear();
1880 const present = new Set();
1881 for (const rp of roster.peers || []) {
1882 if (!rp || !rp.peer) continue;
1883 names.set(rp.peer, rp.name || '');
1884 if (rp.peer === state.peer) {
1885 // Our own kind, re-derived by the server on every tick: this,
1886 // not data-is-member, is what decides whether the member-only
1887 // controls are drawn.
1888 state.kind = rp.kind || state.kind;
1889 continue;
1890 }
1891 present.add(rp.peer);
1892 ensurePC(rp.peer, rp.gen || 1);
1893 }
1894 for (const [id, entry] of pcs) {
1895 if (present.has(id)) continue;
1896 // A roster can only speak for the room as it was when the hub
1897 // sent it. A connection built *since* — from a `peer` event that
1898 // arrived while §5.2's fetch was still out, which is the case
1899 // that cost the gate three scenarios (Task 5's report) — is not
1900 // something this roster ever knew about, and closing it leaves a
1901 // call with a peer it will never hear from again: no further
1902 // roster is coming, because nothing has changed as far as the hub
1903 // is concerned.
1904 if (at && entry.bornAt > at) continue;
1905 // Otherwise: a connection to an id the roster does not carry is
1906 // closed, which is how a browser that missed a `gone` still lets
1907 // go. The counters are *not* dropped with it, though — §4.6 gives
1908 // `seq` a sender's whole participation, and a roster's silence is
1909 // not the hub telling us that participation ended. `gone`, `lost`
1910 // and a departure of our own are; they forget. Dropping them here
1911 // meant a connection closed and rebuilt started numbering at 1
1912 // into a peer whose cursor was already at 3, and every message of
1913 // the new one was discarded as a replay.
1914 closePC(id, false);
1915 }
1916 waiting = (roster.waiting || []).map((w) => {
1917 names.set(w.peer, w.name || '');
1918 return { peer: w.peer, name: w.name || '' };
1919 });
1920 // §6: a roster is admission, and admission is when the chat panel
1921 // appears and becomes usable. Mounting is idempotent, so every later
1922 // roster costs one `setEnabled(true)` and nothing else.
1923 mountChat();
1924 chatEnabled(true);
1925 // §15.19: before the tiles are drawn, so they are drawn right.
1926 rosterMedia(roster);
1927 renderTiles();
1928 renderQueue();
1929 renderStatus();
1930 }
1931
1932 // ---------------------------------------------------------------
1933 // Peer connections and perfect negotiation (§5.1)
1934 // ---------------------------------------------------------------
1935
1936 // ensurePC is the one door into the mesh: a peer with no connection
1937 // gets one, and a peer whose generation has moved on is rebuilt under
1938 // the new one. Both `roster` and `peer` come through here, so the two
1939 // paths cannot drift.
1940 function ensurePC(id, g) {
1941 if (state.stopped) return null;
1942 if (pcs.has(id)) {
1943 if (g > (gen.get(id) || 0)) rebuildPC(id, g);
1944 return pcs.get(id);
1945 }
1946 gen.set(id, g);
1947 return createPC(id, g);
1948 }
1949
1950 function rebuildPC(id, g) {
1951 // A new generation: close the connection, discard the outbound
1952 // queue and the candidate buffer, keep the seq counters (§4.6).
1953 closePC(id, false);
1954 if (state.stopped) return;
1955 gen.set(id, g);
1956 createPC(id, g);
1957 renderTiles();
1958 }
1959
1960 function createPC(id, g) {
1961 // §5.2: the list `fetchIce` took from GET /m/{sqid}/ice, which the
1962 // first roster waits for. An empty one is §5.5's floor — browsers
1963 // gather host candidates only, which connects on a permissive local
1964 // network and usually not across the internet — and it is what a
1965 // connection built during the very first fetch gets, until
1966 // `adoptServers` hands it the real list.
1967 let pc;
1968 try {
1969 pc = new RTCPeerConnection({ iceServers: ice.servers });
1970 } catch {
1971 // No WebRTC at all: an old browser, or one where it is switched
1972 // off. Nothing here can recover, so the room says so once.
1973 terminal('nowebrtc');
1974 return null;
1975 }
1976 // Building a connection to a peer means the server has just named it
1977 // — a roster, a `peer`, or a `pair` — so whatever a 404 marked stale
1978 // about it is out of date. Without this, a pair the hub reset while
1979 // this tab was giving up on it would be rebuilt and then never
1980 // spoken to, because `send` drops for a stale target.
1981 stale.delete(id);
1982 const entry = {
1983 pc,
1984 // §5.1: the peer with the lower id is polite and rolls back on a
1985 // collision; the higher is impolite and ignores the offer.
1986 polite: String(state.peer) < String(id),
1987 makingOffer: false,
1988 ignoreOffer: false,
1989 // §5.1's third negotiation flag, and the one this file was
1990 // missing (Codex S2-7). It is true only while an answer is being
1991 // applied, which is a state that looks exactly like glare from
1992 // the outside — signalingState is still have-local-offer — and is
1993 // not.
1994 isSettingRemoteAnswerPending: false,
1995 // §5.1's polite yield, in three parts (Codex S4-4).
1996 //
1997 // `yields` is how many times in a row this side has given way
1998 // without an offer of its own going out, capped at POLITE_YIELDS
1999 // and handed back one at a time by an exchange this side did not
2000 // offer. `negotiation` is the generation: it moves whenever this
2001 // connection's negotiation moves on, so a yield that captured it
2002 // and then slept can tell "nothing happened" from "an exchange
2003 // came and went while I was asleep". `negotiating` is the
2004 // serializer: one local offer attempt at a time, because two
2005 // `negotiationneeded` events while one of them sleeps used to
2006 // produce two offers, the second of them skipping the yield
2007 // entirely because the first had already spent it.
2008 yields: 0,
2009 negotiation: 0,
2010 negotiating: false,
2011 // A retry scheduled for an ask the rounds ran out on, so a second
2012 // one is never stacked on top of it, and how many times that
2013 // retry has found the connection busy and put itself off.
2014 negotiateTimer: 0,
2015 negotiateDefers: 0,
2016 // A `negotiationneeded` that arrived while an attempt was in
2017 // flight, kept rather than dropped: an attempt that abandons its
2018 // offer would otherwise take that change to the grave with it.
2019 renegotiate: false,
2020 // §5.1's camera watch (Codex S4-5): the last framesEncoded read
2021 // off this connection's own camera m-line, how many polls in a
2022 // row have reported that same number, and how many times the
2023 // encoder has been rebuilt before giving up and resetting.
2024 cameraFrames: -1,
2025 cameraStalls: 0,
2026 cameraRepairs: 0,
2027 pending: [],
2028 descSeq: 0,
2029 gen: g,
2030 // §15.28, what the recovery reads: when this connection was made,
2031 // when the far side last restarted ICE on it (an offer with a new
2032 // username fragment), the fragment it is on, and whether a
2033 // description refused to apply.
2034 builtAt: Date.now(),
2035 remoteRestartAt: 0,
2036 remoteUfrag: '',
2037 errored: false,
2038 stream: null,
2039 failed: false,
2040 // §5.2: true while this connection is running on the empty list,
2041 // so `adoptServers` can find the ones built during the first
2042 // fetch and give them the servers when they arrive.
2043 floor: !ice.servers.length,
2044 // Which list this connection was built on. A connection built
2045 // after a fetch is already on that credential and has nothing to
2046 // renew, which is what keeps §5.3 step 3's deadline off a peer
2047 // who joined the call two minutes ago.
2048 listAt: ice.fetchedAt,
2049 // Remote descriptions applied, which is how §5.3 step 2's "the
2050 // restart's offer/answer exchange has completed" is read without
2051 // guessing from signalingState alone.
2052 desc: 0,
2053 // What this browser had been told when the connection was built.
2054 // reconcile reads it: a roster older than this cannot be talking
2055 // about this connection.
2056 bornAt: tick,
2057 // The four numbers that say where ICE stopped, and the one place
2058 // they exist: a connection whose negotiation completed and whose
2059 // transport never left `new` (the residual gate flake) is either
2060 // gathering nothing, delivering nothing, receiving nothing, or
2061 // adding nothing, and only these tell those four apart.
2062 // `delivered` is counted where the hub accepts a candidate, not
2063 // where one is handed to the queue. Counts, never candidates: an
2064 // address is not something this file publishes.
2065 gathered: 0,
2066 delivered: 0,
2067 received: 0,
2068 added: 0,
2069 // §5.4, sending: the transceiver this connection carries our
2070 // display track on, while we are sharing.
2071 shareTx: null,
2072 // §5.4, receiving: what this peer's camera came in on, and the
2073 // screen once it arrives. `cameraMid` and `cameraStream` are
2074 // recorded from the *first* video track — the camera, by
2075 // definition — and `classifyTrack` reads them to tell the second
2076 // video track apart from it. `sharing` is the `share {on:true}`
2077 // message, which usually beats the track here by a renegotiation,
2078 // and is what lets the tile carry the label before there is
2079 // anything to show in it.
2080 cameraMid: '',
2081 cameraStream: '',
2082 // The stream everything else from this peer has been arriving in,
2083 // recorded from the first track of any kind. A sender puts its
2084 // camera and its microphone in one MediaStream and its screen in
2085 // another, so this places a video track even before there is a
2086 // camera to compare it with — which is the audio-only sharer, whose
2087 // screen is the first video track its peers ever see.
2088 peerStream: '',
2089 // Whether this connection carries a camera of ours. Not the same
2090 // question as `local` having a video track: addTrack can throw,
2091 // and then this tab has a camera and this connection has a video
2092 // m-line it built for nobody. classifyTrack's direction rule turns
2093 // on which of the two is true.
2094 sentVideo: false,
2095 // Kinds whose transceiver switchDevice turned round while the
2096 // connection was mid-negotiation, waiting for it to settle.
2097 upgrades: new Set(),
2098 sharing: false,
2099 share: null,
2100 // The mid the peer's screen arrives on, so the getStats fallback
2101 // can tell two inbound video streams apart.
2102 shareMid: '',
2103 };
2104 pcs.set(id, entry);
2105
2106 // The listeners go on before any media does. `addTrack` fires
2107 // `negotiationneeded`, and a connection registered in `pcs` with
2108 // nothing listening for that is a connection that will never offer:
2109 // the event is one-shot, and by the time a listener arrives it has
2110 // been and gone. The same order also means a throw from the media
2111 // below leaves a connection that can still be reset and rebuilt,
2112 // rather than a live entry nobody is watching.
2113
2114 // The listener is not async, for the reason the pageshow handler is
2115 // not: a rejection escaping an event listener goes where neither a
2116 // person nor a gate could see it. The work is a named function, so
2117 // it is also the one §5.1 path a node test can drive.
2118 pc.addEventListener('negotiationneeded', () => {
2119 negotiate(id, entry).catch((err) => {
2120 console.error('meet: negotiate', err);
2121 });
2122 });
2123
2124 pc.addEventListener('icecandidate', ({ candidate }) => {
2125 if (pcs.get(id) !== entry || !candidate) return;
2126 entry.gathered += 1;
2127 send(id, 'candidate', { candidate: candidate.toJSON() });
2128 });
2129
2130 pc.addEventListener('track', (ev) => {
2131 if (pcs.get(id) !== entry) return;
2132 onRemoteTrack(id, entry, ev);
2133 });
2134
2135 pc.addEventListener('connectionstatechange', () => {
2136 if (pcs.get(id) !== entry) return;
2137 // Whether it has failed for long enough to say so is the
2138 // recovery's verdict (§15.28), not this event's.
2139 renderTiles();
2140 });
2141
2142 // §5.2's deferred half. A connection built during the first /ice
2143 // fetch is on the floor's empty list, and `adoptServers` will not
2144 // restart it while a negotiation is in flight — doing that cost a
2145 // gate run its media. So it waits here for the connection's own
2146 // next quiet moment instead of waiting 150 minutes for the first
2147 // renewal.
2148 pc.addEventListener('signalingstatechange', () => {
2149 if (pcs.get(id) !== entry) return;
2150 // §15.30: the adaptive watch takes no news while this settles.
2151 entry.adaptSettleUntil = Date.now() + ADAPT_SETTLE;
2152 // §5.4: the same quiet moment is when a deferred share transceiver
2153 // is added. addShareTo will not add one to a connection that is
2154 // mid-negotiation, because an unassociated sendonly transceiver is
2155 // exactly what a remote offer's m-line matching will claim on a
2156 // rollback — and then the screen is being sent on the m-line the
2157 // far side means for something else.
2158 addShareTo(entry);
2159 upgradeWhenQuiet(entry);
2160 adoptWhenQuiet(id, entry);
2161 // §15.30: a connection that settles is given what its peer asks of
2162 // us, and the person's own Audio only — a new connection's senders
2163 // have no parameters to set until it has.
2164 if (pc.signalingState === 'stable' && (entry.sentLevel || videoSetting() === 'audio')) tuneShare(entry);
2165 // And it is when an ask the negotiation rounds ran out on gets
2166 // its turn (Codex S4-8): a connection that was mid-negotiation is
2167 // the usual reason they ran out, and this is it settling.
2168 if (entry.renegotiate && !entry.negotiating && pc.signalingState === 'stable') {
2169 negotiate(id, entry).catch((err) => {
2170 console.error('meet: negotiate', err);
2171 });
2172 }
2173 });
2174
2175 // And now the media. Our own tracks, and a transceiver for every
2176 // kind we do not have one of — the two used to be all-or-nothing,
2177 // and that was a hole: a browser that came down `startLocal`'s
2178 // ladder to audio alone (a camera in use, or gone) has a local
2179 // stream, so nothing asked to receive video, so it offered no video
2180 // m-line at all and the person on the other side sat looking at a
2181 // tile that was never going to get a frame. Per kind, and a track
2182 // that has ended counts as absent, because it is.
2183 try {
2184 if (local) {
2185 for (const track of local.getTracks()) {
2186 pc.addTrack(track, local);
2187 if (track.kind === 'video' && track.readyState !== 'ended') entry.sentVideo = true;
2188 }
2189 }
2190 } catch {
2191 // A track the browser will not add — ended between the ladder and
2192 // here, or a device that went away — is not worth the connection.
2193 // The recvonly transceivers below cover what it would have been.
2194 }
2195 tuneAudioSender(pc);
2196 for (const kind of ['video', 'audio']) {
2197 if (hasLiveTrack(kind)) continue;
2198 try {
2199 pc.addTransceiver(kind, { direction: 'recvonly' });
2200 } catch {
2201 // An old browser without addTransceiver simply waits to be
2202 // offered to, which the other side will do if it has media.
2203 }
2204 }
2205 // §5.4: a connection built while this tab is already sharing gets
2206 // the screen with everything else, rather than waiting for the next
2207 // time the button is pressed. Someone joining a call mid-share sees
2208 // the screen.
2209 //
2210 // Last, and that is load-bearing: the m-lines of the first offer
2211 // come out in the order the transceivers were created, so the camera
2212 // and the microphone take the places the far side's own createPC
2213 // built for them and the screen takes a place of its own after them.
2214 // Added before them, the screen would sit in the m-line a peer built
2215 // for a camera.
2216 addShareTo(entry);
2217
2218 return entry;
2219 }
2220
2221 // politeYield waits POLITE_YIELD and then answers whether the
2222 // negotiation it gave way for is still this side's to make.
2223 //
2224 // Three things can have happened while it slept. The connection can
2225 // have gone, or the call ended: nothing to offer to. A remote offer
2226 // can have arrived and still be being answered: signalingState says
2227 // so. Or — the case a state check alone cannot see, and Codex S4-4's
2228 // first half — a whole exchange can have arrived, been answered and
2229 // completed, leaving the connection back at `stable` looking exactly
2230 // as it did when this yield began. The generation is what tells those
2231 // two apart: it moves on every exchange, so a yield whose generation
2232 // has changed is a yield whose negotiation somebody else already
2233 // made. Offering anyway is the extra offer that produced.
2234 //
2235 // It answers with the reason rather than a bare no, because the three
2236 // are not the same afterwards (Codex S4-12). A connection that has
2237 // gone owes nothing. A negotiation somebody else made is finished
2238 // with. But an exchange still *in flight* has settled nothing: this
2239 // side's own reason for offering is as outstanding as it was, and an
2240 // attempt that walks away from it without saying so is where the ask
2241 // went missing.
2242 async function politeYield(id, entry, generation) {
2243 await sleep(POLITE_YIELD);
2244 if (pcs.get(id) !== entry || state.stopped) return 'gone';
2245 if (entry.negotiation !== generation) return 'superseded';
2246 if (entry.pc.signalingState !== 'stable') return 'busy';
2247 return '';
2248 }
2249
2250 // answeredExchange records one offer/answer exchange this side did
2251 // not offer: a return to `stable` through somebody else's turn.
2252 //
2253 // It moves the generation, which invalidates any yield sleeping
2254 // through it, and it hands back one spent yield — one, never more
2255 // than was spent, so a pair renegotiating in turn cannot talk this
2256 // side into giving way for ever. Without the hand-back, a yield lost
2257 // to an exchange that happened to satisfy this side's own change left
2258 // `yields` spent and the *next* independent negotiation unprotected,
2259 // which is the reset defect the Task 4 re-review carried (item 1).
2260 function answeredExchange(entry) {
2261 entry.negotiation += 1;
2262 if (entry.yields > 0) entry.yields -= 1;
2263 }
2264
2265 // negotiate is §5.1's offering half: one offer per negotiation, with
2266 // the polite side's yield in front of it.
2267 //
2268 // The yield is fix round 2's finding, and it is the whole reason this
2269 // function is not two lines. Perfect negotiation's answer to glare is
2270 // a rollback on the polite side, and in Chromium rolling back an offer
2271 // that added an m-line rebuilds every send stream on the connection:
2272 // the camera's comes back having encoded nothing and never encodes
2273 // again, on an m-line that goes on reading sendrecv with a live track
2274 // the whole time. So the side that would roll back gives way *before*
2275 // it offers instead, and the offer that was already on its way is
2276 // answered from a stable state with no rollback anywhere.
2277 //
2278 // Bounded, which is what `yields` is for: a side that gave way and
2279 // came back to find another offer waiting would give way again, and
2280 // two peers renegotiating in turn would keep one of them permanently a
2281 // beat behind. Past POLITE_YIELDS in a row it offers and takes the
2282 // ordinary collision path, which is what the pattern is for. The count
2283 // goes back to zero on this side's own offer, and back by one on an
2284 // exchange this side answered instead.
2285 //
2286 // One attempt at a time, too (Codex S4-4). `negotiationneeded` can
2287 // fire again while the first attempt is asleep in its yield — a
2288 // remote exchange completing is exactly the thing that fires it — and
2289 // the second attempt used to skip the yield, because the first had
2290 // already spent it, and then both of them offered.
2291 // An attempt abandoned by its yield is not the end of the story, and
2292 // this is where the first draft of the serializer was wrong — the
2293 // browser gate's mutualshare caught it. `negotiationneeded` fires for
2294 // the polite side's own screen while its attempt is asleep; the
2295 // attempt then wakes, finds the generation moved by the exchange it
2296 // slept through, and abandons its offer. If that event was simply
2297 // dropped because an attempt was in flight, the screen it was about
2298 // is never offered at all — the transceiver sits unassociated for the
2299 // rest of the call and the far side sees a caption with nothing in
2300 // it. So an event that arrives mid-attempt is remembered, and an
2301 // attempt that abandons its offer runs again for it.
2302 //
2303 // Bounded, because "go round again" and "give way" are the same two
2304 // steps: each round can spend a yield, and the allowance runs out.
2305 const NEGOTIATE_ROUNDS = 4;
2306
2307 // How many times a kept ask's retry may find the connection busy and
2308 // put itself off again. After that it stops asking and waits: the
2309 // connection's own `signalingstatechange` is what picks the ask up,
2310 // and a timer that keeps waking every 300 ms adds nothing to it.
2311 const NEGOTIATE_DEFERS = 10;
2312
2313 async function negotiate(id, entry) {
2314 if (pcs.get(id) !== entry) return;
2315 if (entry.negotiating) {
2316 entry.renegotiate = true;
2317 return;
2318 }
2319 entry.negotiating = true;
2320 try {
2321 for (let round = 0; round < NEGOTIATE_ROUNDS; round++) {
2322 entry.renegotiate = false;
2323 const generation = entry.negotiation;
2324 if (entry.polite && entry.yields < POLITE_YIELDS) {
2325 entry.yields += 1;
2326 const why = await politeYield(id, entry, generation);
2327 if (why === 'gone') return;
2328 if (why === 'busy') {
2329 // An exchange is in flight and has settled nothing of ours.
2330 // The ask goes back on the connection for the return to
2331 // `stable` to collect (Codex S4-12): walking away from it
2332 // here is how a preserved request went missing, and this
2333 // attempt may be the only thing that was holding it.
2334 entry.renegotiate = true;
2335 return;
2336 }
2337 if (why === 'superseded') {
2338 // Somebody else made this negotiation. Only an ask that
2339 // arrived *while* we slept is still outstanding.
2340 if (!entry.renegotiate || pcs.get(id) !== entry || state.stopped) return;
2341 continue;
2342 }
2343 }
2344 let offered = false;
2345 try {
2346 entry.makingOffer = true;
2347 await entry.pc.setLocalDescription();
2348 // This side's own offer: the negotiation is ours, the
2349 // generation moves with it, and the next one starts with the
2350 // whole allowance again.
2351 entry.negotiation += 1;
2352 entry.yields = 0;
2353 send(id, 'offer', { description: describe(entry.pc.localDescription) });
2354 offered = true;
2355 } catch {
2356 // A failed local description is not fatal: the pair recovers
2357 // through a reset if it never connects.
2358 } finally {
2359 entry.makingOffer = false;
2360 }
2361 // An offer that went out was made from the connection as it
2362 // stands, so it carries every local change asked for up to this
2363 // moment. One that did not — an impolite side finding the
2364 // connection mid-exchange, say — has settled nothing, and the
2365 // ask goes back for the quiet moment to collect.
2366 if (!offered) entry.renegotiate = true;
2367 return;
2368 }
2369 } finally {
2370 entry.negotiating = false;
2371 // The bound limits how long one attempt may go round; it does not
2372 // decide that outstanding work stops mattering (Codex S4-8). If
2373 // something asked for a negotiation that this attempt never got
2374 // to, the ask stays on the connection and is picked up at its
2375 // next quiet moment.
2376 keepNegotiation(id, entry);
2377 }
2378 }
2379
2380 // keepNegotiation is what happens to an ask the rounds ran out on.
2381 // The request stays true and a retry is scheduled: on the next return
2382 // to `stable` if the connection is mid-negotiation (which is the
2383 // usual reason the rounds ran out), and on a timer otherwise, because
2384 // a connection that is already stable and quiet will not announce
2385 // anything for the retry to hang off.
2386 //
2387 // A retry is scheduled once at a time: `negotiate` clears the flag at
2388 // the top of every round, so a scheduled one that finds nothing
2389 // outstanding does nothing at all.
2390 function keepNegotiation(id, entry) {
2391 if (!entry.renegotiate) return;
2392 if (pcs.get(id) !== entry || state.stopped) {
2393 entry.renegotiate = false;
2394 return;
2395 }
2396 if (entry.negotiateTimer) return;
2397 entry.negotiateTimer = setTimeout(() => {
2398 entry.negotiateTimer = 0;
2399 if (!entry.renegotiate || pcs.get(id) !== entry || state.stopped) return;
2400 // A retry that lands mid-exchange must not spend the ask on an
2401 // attempt that cannot offer (Codex S4-12): it defers instead, and
2402 // the connection's own return to `stable` is what collects it.
2403 // The timer comes back a bounded number of times for the case
2404 // where nothing announces that return; after that the ask simply
2405 // waits, because the stable handler is not going anywhere.
2406 if (entry.negotiating || entry.pc.signalingState !== 'stable') {
2407 if (entry.negotiateDefers >= NEGOTIATE_DEFERS) return;
2408 entry.negotiateDefers += 1;
2409 keepNegotiation(id, entry);
2410 return;
2411 }
2412 entry.negotiateDefers = 0;
2413 negotiate(id, entry).catch((err) => {
2414 console.error('meet: negotiate', err);
2415 });
2416 }, POLITE_YIELD);
2417 }
2418
2419 // hasLiveTrack answers whether the local stream has a track of this
2420 // kind that could actually carry media. An ended track is not one:
2421 // the browser keeps it in the stream, and `addTrack` will take it,
2422 // but nothing ever comes out of it.
2423 function hasLiveTrack(kind) {
2424 if (!local) return false;
2425 const tracks = kind === 'video' ? local.getVideoTracks() : local.getAudioTracks();
2426 return tracks.some((track) => track && track.readyState !== 'ended');
2427 }
2428
2429 function describe(desc) {
2430 return desc ? { type: desc.type, sdp: desc.sdp } : null;
2431 }
2432
2433 function closePC(id, forget) {
2434 const entry = pcs.get(id);
2435 if (entry) {
2436 try {
2437 entry.pc.close();
2438 } catch {
2439 // Already closed.
2440 }
2441 // A retry scheduled for a connection that is going away has
2442 // nothing left to negotiate; the timer's own guard would refuse
2443 // it anyway, and clearing it here keeps nothing pending.
2444 if (entry.negotiateTimer) {
2445 clearTimeout(entry.negotiateTimer);
2446 entry.negotiateTimer = 0;
2447 }
2448 entry.renegotiate = false;
2449 pcs.delete(id);
2450 }
2451 queue.delete(id);
2452 // §5.3's record belongs to a connection, not to a peer id: a pair
2453 // rebuilt under a new generation has renewed nothing yet, and a
2454 // record left behind would say it had.
2455 renewals.delete(id);
2456 // §15.20: what was heard belongs to a connection too. A rebuilt one
2457 // starts its counters again, and a silence timed on the old one is
2458 // not a silence on the new.
2459 hearing.delete(id);
2460 if (forget) {
2461 stale.delete(id);
2462 gen.delete(id);
2463 seqOut.delete(id);
2464 lastIn.delete(id);
2465 names.delete(id);
2466 frames.delete(id);
2467 frames.delete(shareKey(id));
2468 }
2469 }
2470
2471 function closeAllPCs() {
2472 for (const id of Array.from(pcs.keys())) closePC(id, true);
2473 waiting = [];
2474 lastRoster = null;
2475 renderTiles();
2476 renderQueue();
2477 }
2478
2479 // accept applies §4.6's inbound rules to a targeted message: drop
2480 // anything at or below the seq already seen from this sender, then
2481 // drop anything below the current pair generation. A generation
2482 // *above* the local one means a `pair` was missed, so the connection
2483 // is rebuilt before the message is used.
2484 function accept(msg) {
2485 const from = msg.from;
2486 if (!from) return null;
2487 const seq = msg.seq || 0;
2488 const g = msg.gen || 0;
2489 const mine = gen.get(from) || 0;
2490 // The generation is read before the cursor, and that order is
2491 // load-bearing. A message from a generation *older* than ours
2492 // belongs to a pair that has been reset out from under it and is
2493 // gone whatever its seq. One from a *newer* generation is the other
2494 // side of a reset we have not seen yet — and the cursor it would be
2495 // measured against was built by the connection that reset, so it
2496 // cannot honestly call that message a replay. Reading the cursor
2497 // first meant the first message of a rebuilt pair could be
2498 // discarded for ever, which is the line Task 5's report found under
2499 // the stale-roster defect.
2500 if (g && g < mine) return null;
2501 if (g && g > mine) {
2502 rebuildPC(from, g);
2503 if (seq) lastIn.set(from, seq);
2504 return pcs.get(from) || null;
2505 }
2506 if (seq && seq <= (lastIn.get(from) || 0)) return null;
2507 if (seq) lastIn.set(from, seq);
2508 return pcs.get(from) || null;
2509 }
2510
2511 // offerCollision is the W3C perfect-negotiation decision, written out
2512 // as its own function because it is the one piece of §5.1 that can be
2513 // reasoned about — and gated — without a browser (see
2514 // test/browser/negotiation.test.mjs, which reads it out of this file).
2515 //
2516 // readyForOffer = !makingOffer &&
2517 // (signalingState === "stable" || isSettingRemoteAnswerPending)
2518 // offerCollision = !readyForOffer
2519 //
2520 // The second half of that disjunction is the whole point: while an
2521 // answer is being applied, signalingState is still have-local-offer,
2522 // and without this an offer arriving in that window read as glare and
2523 // was discarded by the impolite side (Codex S2-7).
2524 function offerCollision(entry, signalingState) {
2525 const readyForOffer = !entry.makingOffer &&
2526 (signalingState === 'stable' || entry.isSettingRemoteAnswerPending);
2527 return !readyForOffer;
2528 }
2529
2530 async function onOffer(msg) {
2531 const entry = accept(msg);
2532 if (!entry) return;
2533 const desc = msg.payload && msg.payload.description;
2534 if (!desc || desc.type !== 'offer') return;
2535 if (offerCollision(entry, entry.pc.signalingState)) {
2536 entry.ignoreOffer = !entry.polite;
2537 if (entry.ignoreOffer) return;
2538 } else {
2539 entry.ignoreOffer = false;
2540 }
2541 try {
2542 // The polite peer's implicit rollback lives inside this call.
2543 entry.isSettingRemoteAnswerPending = false; // this one is an offer
2544 await entry.pc.setRemoteDescription(desc);
2545 entry.ignoreOffer = false;
2546 entry.descSeq = msg.seq || entry.descSeq;
2547 // §15.28: a new username fragment is the far side restarting ICE.
2548 const m = /(?:^|\r\n)a=ice-ufrag:([^\r\n]+)/.exec(desc.sdp || '');
2549 const ufrag = m ? m[1] : '';
2550 if (ufrag && entry.remoteUfrag && ufrag !== entry.remoteUfrag) entry.remoteRestartAt = Date.now();
2551 if (ufrag) entry.remoteUfrag = ufrag;
2552 await drainCandidates(entry);
2553 await entry.pc.setLocalDescription();
2554 // One exchange completed, on the answering side (§5.3 step 2) —
2555 // and an exchange this side did not offer, which is what moves
2556 // the negotiation generation and hands a spent yield back.
2557 entry.desc += 1;
2558 answeredExchange(entry);
2559 send(msg.from, 'answer', { description: describe(entry.pc.localDescription) });
2560 } catch {
2561 // A description that will not apply leaves the pair to its
2562 // recovery (§15.28) rather than throwing into the event handler.
2563 entry.errored = true;
2564 }
2565 }
2566
2567 async function onAnswer(msg) {
2568 const entry = accept(msg);
2569 if (!entry) return;
2570 const desc = msg.payload && msg.payload.description;
2571 if (!desc || desc.type !== 'answer') return;
2572 if (entry.pc.signalingState !== 'have-local-offer') return;
2573 try {
2574 // The W3C flag, set exactly where the reference sets it: around
2575 // setRemoteDescription, true because this description is an
2576 // answer. An offer that arrives while this is in flight is a
2577 // legitimate offer, not glare, and offerCollision reads this to
2578 // tell the two apart.
2579 entry.isSettingRemoteAnswerPending = true;
2580 try {
2581 await entry.pc.setRemoteDescription(desc);
2582 } finally {
2583 entry.isSettingRemoteAnswerPending = false;
2584 }
2585 // The reference sets ignoreOffer on every description it applies,
2586 // and an answer that lands means the collision it was set for is
2587 // over: candidate failures after this point are real again.
2588 entry.ignoreOffer = false;
2589 entry.descSeq = msg.seq || entry.descSeq;
2590 // One exchange completed, on the offering side (§5.3 step 2).
2591 entry.desc += 1;
2592 await drainCandidates(entry);
2593 } catch {
2594 // Same as above: an answer that will not apply is the recovery's.
2595 entry.errored = true;
2596 }
2597 }
2598
2599 async function onCandidate(msg) {
2600 const entry = accept(msg);
2601 if (!entry) return;
2602 const candidate = msg.payload && msg.payload.candidate;
2603 if (!candidate) return;
2604 entry.received += 1;
2605 // §4.6: a candidate whose seq precedes the current description's
2606 // belongs to a description that has been replaced.
2607 if (msg.seq && entry.descSeq && msg.seq < entry.descSeq) return;
2608 if (!entry.pc.remoteDescription) {
2609 entry.pending.push(candidate);
2610 if (entry.pending.length > MAX_BUFFERED_CANDIDATES) entry.pending.shift();
2611 return;
2612 }
2613 await addCandidate(entry, candidate);
2614 }
2615
2616 async function drainCandidates(entry) {
2617 const held = entry.pending;
2618 entry.pending = [];
2619 for (const candidate of held) await addCandidate(entry, candidate);
2620 }
2621
2622 async function addCandidate(entry, candidate) {
2623 try {
2624 await entry.pc.addIceCandidate(candidate);
2625 entry.added += 1;
2626 } catch (err) {
2627 // The W3C reference swallows exactly this: an ignored offer's
2628 // candidates cannot apply, and that is expected, not an error.
2629 if (!entry.ignoreOffer) console.warn('meet: candidate', err && err.name);
2630 }
2631 }
2632
2633 // ---------------------------------------------------------------
2634 // ICE servers and renewal (§5.2, §5.3, §5.5)
2635 // ---------------------------------------------------------------
2636 //
2637 // The shape of it: the first roster waits for `fetchIce`, every
2638 // connection is built with the list it took, and each connection is
2639 // renewed on its own at the time the server named — with new servers,
2640 // an ICE restart, and proof that the restart landed. Nothing about the
2641 // servers is logged: the list carries a credential, and the three
2642 // diagnostics below print an error object and never a response.
2643
2644 const ICE_WARNING = 'Calls could not reach the relay. Calls may not connect until it can.';
2645 const ICE_EXPIRED = 'The relay credential expired for this connection.';
2646 const ICE_STUCK = 'Could not renew this connection through the relay.';
2647 const FAILED_RELAY = 'Could not connect, even through the relay.';
2648 const FAILED_PLAIN = 'Could not connect.';
2649
2650 // iceReady is the one await §5.2 puts in front of the first connection
2651 // this browser builds. One shared promise, so two rosters in the same
2652 // breath cannot start two fetches, and a failure primes exactly as a
2653 // success does: the room carries on with the floor's empty list while
2654 // the minute retry runs behind it.
2655 function iceReady() {
2656 if (icePrimed) return Promise.resolve(false);
2657 if (!firstIce) {
2658 firstIce = fetchIce().finally(() => {
2659 firstIce = null;
2660 });
2661 }
2662 return firstIce;
2663 }
2664
2665 // fetchIce is §5.2's client half: GET /m/{sqid}/ice for this
2666 // participation, answering {iceServers, expiresAt, renewAt}. It never
2667 // throws and never rejects — every caller carries on either way — and
2668 // answers whether a new list is in hand.
2669 //
2670 // The stream's `probe` is borrowed whole: same-origin credentials, no
2671 // store, no Accept the endpoint did not ask for, and an absolute
2672 // deadline, so a request that never settles cannot be the end of this
2673 // browser's renewing.
2674 async function fetchIce() {
2675 const peer = state.peer;
2676 if (state.stopped || !peer) return false;
2677 const path = '/m/' + encodeURIComponent(sqid) + '/ice?peer=' + encodeURIComponent(peer);
2678 // One budget for the whole exchange, however many requests it takes
2679 // — the shape §4.6 already gives one outbound message, and the same
2680 // reason applies: /ice spends /signal's own per-session, per-room
2681 // bucket, so a renewal that lands inside a burst of signalling gets
2682 // a 429 and a Retry-After rather than an answer.
2683 const deadline = Date.now() + SEND_DEADLINE;
2684 for (;;) {
2685 let res;
2686 try {
2687 res = await probe(path, deadline);
2688 } catch {
2689 icePrimed = true;
2690 iceFailed();
2691 return false;
2692 }
2693 if (state.stopped || state.peer !== peer) return false;
2694 if (res.signedOut) {
2695 terminal('signedout');
2696 return false;
2697 }
2698 if (res.status === 429) {
2699 // Not a failure: the server said "not now, come back in n". Honour
2700 // it inside this budget and say nothing — a warning about the
2701 // relay would be untrue, and the person's own call is what filled
2702 // that bucket. Only a wait that runs out of budget is a failure.
2703 if (!(await waitWithin(retryAfter(res.retryAfter), deadline))) {
2704 icePrimed = true;
2705 iceFailed();
2706 return false;
2707 }
2708 continue;
2709 }
2710 if (res.status === 404) {
2711 // Not a relay failure: a 404 here says this participation is
2712 // gone — a resume window that has lapsed included, now that
2713 // /ice gates on the same liveness /signal does — and /signal's
2714 // own 404 says no more than that either. So it goes through
2715 // the same probe-first recovery — this browser's own
2716 // participation is the authority on what the 404 meant — and the
2717 // next roster fetches again, because whatever comes back from that
2718 // ladder is a call that has not got a list yet.
2719 icePrimed = false;
2720 firstIce = null;
2721 await recoverFromNotFound(res.data.boot);
2722 // The ladder is allowed to decide nothing at all: a probe that
2723 // cannot answer inside its budget leaves this participation alone
2724 // (§4.5), and a call left with no list and no retry pending would
2725 // simply sit there. So unless it ended the call or entered afresh
2726 // — both of which change what is checked here — the minute retry
2727 // covers it.
2728 if (!state.stopped && state.peer === peer) iceFailed();
2729 return false;
2730 }
2731 if (res.status !== 200 || !Array.isArray(res.data.iceServers)) {
2732 icePrimed = true;
2733 iceFailed();
2734 return false;
2735 }
2736 icePrimed = true;
2737 ice.servers = res.data.iceServers;
2738 ice.expiresAt = millis(res.data.expiresAt);
2739 ice.renewAt = millis(res.data.renewAt);
2740 // The margin the server left itself: expiry minus renew time, on
2741 // its clock, where the two subtract to a duration both machines
2742 // agree on. Everything below is scheduled from it and from
2743 // `fetchedAt`, which is this browser's own clock — see renewDelay.
2744 ice.margin = Math.max(0, ice.expiresAt - ice.renewAt);
2745 ice.fetchedAt = Date.now();
2746 ice.lastFetchAt = ice.fetchedAt;
2747 ice.fetches += 1;
2748 ice.failedSince = 0;
2749 ice.lastTryAt = 0;
2750 clearTimeout(iceRetryTimer);
2751 iceWarning(false);
2752 scheduleRenewal();
2753 adoptServers();
2754 return true;
2755 }
2756 }
2757
2758 // The wire carries unix seconds; everything in this file works in
2759 // milliseconds since the epoch, and this is the one place the two
2760 // meet. A field that is missing, zero or not a number means "no
2761 // clock", which is exactly what the server sends when there is no
2762 // relay to renew.
2763 function millis(v) {
2764 const n = Number(v);
2765 return Number.isFinite(n) && n > 0 ? n * 1000 : 0;
2766 }
2767
2768 // iceFailed is §5.3 step 1: keep the list we have — or the floor's
2769 // empty one, on the very first fetch — say so from the first failure,
2770 // and come back in a minute. `ice.expiresAt` is deliberately left
2771 // alone: the old credential's deadline is the must-succeed-by for
2772 // every connection that has not renewed (§5.3 step 3), and a failed
2773 // fetch is the case that makes it matter.
2774 function iceFailed() {
2775 if (state.stopped) return;
2776 // Every failure, not just the first: the catch-up on a tab coming
2777 // back has to know when this browser last actually tried, and
2778 // `failedSince` is the start of the run and answers a different
2779 // question (whether the sentence is up).
2780 ice.lastTryAt = Date.now();
2781 if (!ice.failedSince) ice.failedSince = Date.now();
2782 iceWarning(true);
2783 clearTimeout(iceRetryTimer);
2784 iceRetryTimer = setTimeout(() => {
2785 if (state.stopped) return;
2786 const run = renewDue ? renewAll() : fetchIce();
2787 run.catch((err) => {
2788 console.error('meet: ice', err);
2789 });
2790 }, ICE_RETRY);
2791 }
2792
2793 // iceWarning is §5.3 step 1's sentence, in a live region of its own
2794 // created once beside #status. Its own, because the status paragraph
2795 // is busy with the call's state and a warning coming and going from
2796 // there would take whatever a person was reading with it. Never colour
2797 // alone: the sentence is the whole signal.
2798 function iceWarning(show) {
2799 const el = warningEl();
2800 if (!el) return;
2801 // On the floor the sentence would be untrue: there is no relay this
2802 // instance could reach, /ice answers an empty list, and a fetch that
2803 // fails there costs the call nothing a person could act on (§5.5).
2804 if (show && !relayConfigured) return;
2805 if (show) {
2806 // Unhidden first, then written: a live region announces the change
2807 // it can see, and text set into a hidden element is not one.
2808 el.hidden = false;
2809 el.textContent = ICE_WARNING;
2810 return;
2811 }
2812 el.textContent = '';
2813 el.hidden = true;
2814 }
2815
2816 function warningEl() {
2817 if (iceWarningEl) return iceWarningEl;
2818 if (!statusEl) return null;
2819 const el = document.createElement('p');
2820 el.id = 'ice-warning';
2821 el.className = 'calls-ice-warning';
2822 el.setAttribute('role', 'status');
2823 el.hidden = true;
2824 statusEl.after(el);
2825 iceWarningEl = el;
2826 return el;
2827 }
2828
2829 // adoptServers closes the one window §5.2's ordering leaves open: a
2830 // `peer` event can arrive while the very first fetch is still out, and
2831 // that connection was built on the floor's empty list. Nothing about
2832 // it is broken — it is gathering host candidates — so it is handed the
2833 // servers and restarted rather than torn down and rebuilt.
2834 function adoptServers() {
2835 if (!ice.servers.length) return;
2836 for (const [id, entry] of pcs) {
2837 if (!entry.floor) continue;
2838 try {
2839 entry.pc.setConfiguration({ iceServers: ice.servers });
2840 } catch {
2841 // An older browser without setConfiguration: nothing to adopt
2842 // into, and the connection keeps what it was built with.
2843 continue;
2844 }
2845 // And the restart, if this connection is quiet enough to take
2846 // one now. If it is not — which is the common case for a peer
2847 // built during the fetch, because it is mid-offer — it is
2848 // deferred, not dropped: `createPC`'s signalingstatechange
2849 // listener runs the same decision at every quiet moment, so the
2850 // connection takes the list as soon as its negotiation settles
2851 // rather than waiting 150 minutes for the first renewal.
2852 adoptWhenQuiet(id, entry);
2853 }
2854 }
2855
2856 // adoptWhenQuiet is that decision and the act. It is safe to call as
2857 // often as anything likes: `floor` is what makes it happen at most
2858 // once per list, and clearing it first means the restart's own
2859 // signalingstatechange cannot come back round here.
2860 function adoptWhenQuiet(id, entry) {
2861 if (!readyToAdopt(entry, ice.servers.length)) return;
2862 entry.floor = false;
2863 entry.listAt = ice.fetchedAt;
2864 try {
2865 entry.pc.restartIce();
2866 } catch {
2867 // No restartIce on this browser: a fresh generation is the only
2868 // way to put the servers under this pair, and the `pair` that
2869 // answers rebuilds the connection with them from nothing.
2870 requestReset(id);
2871 }
2872 }
2873
2874 // readyToAdopt is §5.2's deferral rule, pure so it can be gated
2875 // without a browser: still on the floor, a list to move to, and a
2876 // connection quiet enough that a restart will not cut across a
2877 // negotiation already in flight.
2878 function readyToAdopt(entry, servers) {
2879 return !!(entry.floor && servers && !entry.makingOffer &&
2880 entry.pc.signalingState === 'stable');
2881 }
2882
2883 // scheduleRenewal is §5.3 step 4: the next renewal is the `renewAt`
2884 // the server named, counted from the fetch that succeeded. Nothing is
2885 // scheduled on the floor — there is no credential to renew — and a
2886 // `renewAt` already behind us runs at once.
2887 function scheduleRenewal() {
2888 clearTimeout(renewTimer);
2889 if (state.stopped || !schedulable()) return;
2890 renewTimer = setTimeout(renew, Math.max(0, renewDelay() - (Date.now() - ice.fetchedAt)));
2891 }
2892
2893 // renewDelay and mustSucceedBy are §5.3's two instants, measured as
2894 // durations from the moment this browser took the list rather than as
2895 // points on the server's clock. A browser whose clock is minutes off
2896 // the server's would otherwise renew at the wrong time, and one far
2897 // enough ahead would decide the credential had expired before it ever
2898 // used it.
2899 //
2900 // There are two ways to read the duration and neither is right on its
2901 // own, so both are taken and the earlier wins.
2902 //
2903 // The *ratio* reading uses the margin the server left itself —
2904 // expiresAt minus renewAt, a subtraction of two instants on one clock,
2905 // so it survives any skew at all. The contract's shape (renew at five
2906 // sixths of the life) makes the rest arithmetic: the margin is a sixth
2907 // of the life, the delay five of them, the life six. But the server
2908 // sends whole seconds, and truncation eats the margin at short lives:
2909 // a twelve-second life gives 10 and 12 — margin 2, and 2 x 5 = 10, the
2910 // truth — while a ten-second life gives 8 and 10, where the same
2911 // arithmetic says 10 and would renew at the very moment the credential
2912 // died.
2913 //
2914 // The *clock* reading subtracts this browser's fetch stamp from the
2915 // server's instants. It is exact when the clocks agree and wrong by
2916 // the skew when they do not — but wrong in a direction that only
2917 // matters one way: a browser running ahead of the server gets a
2918 // shorter answer and renews early, which costs nothing, and one
2919 // running behind gets a longer one, which the ratio reading then caps.
2920 //
2921 // So: the earlier of the two, and a floor under the delay so that a
2922 // server answering with no margin at all cannot turn the schedule into
2923 // a spin.
2924 function renewDelay() {
2925 return Math.max(MIN_RENEW_DELAY,
2926 Math.min(ice.margin * 5, ice.renewAt - ice.fetchedAt));
2927 }
2928
2929 function mustSucceedBy() {
2930 return ice.fetchedAt + Math.min(ice.margin * 6, ice.expiresAt - ice.fetchedAt);
2931 }
2932
2933 // §5.3's last paragraph: a suspended tab stops its timers, so a tab
2934 // coming back to visible compares the clock with `renewAt` rather than
2935 // trusting one, and runs the sequence at once if it is overdue.
2936 function catchUpRenewal() {
2937 if (state.stopped || !schedulable()) return;
2938 // A fetch that is already failing has a retry of its own running on
2939 // its own minute, and a tab coming back to visible is not a reason
2940 // to jump that queue. The comparison is with the clock rather than
2941 // with the timer because that timer is exactly what a suspended tab
2942 // stops: a failure older than the retry interval means the minute
2943 // has passed with nothing to run it, and this is what runs it.
2944 if (ice.failedSince && Date.now() - ice.lastTryAt < ICE_RETRY) return;
2945 if (Date.now() - ice.fetchedAt >= renewDelay()) renew();
2946 }
2947
2948 function renew() {
2949 renewAll().catch((err) => {
2950 console.error('meet: renew', err);
2951 });
2952 }
2953
2954 // renewAll is §5.3's sequence for the whole mesh: fetch, then hand
2955 // what came back to every connection still on the old list. Both the
2956 // deadline it arms the watchdog with — step 3's must-succeed-by, the
2957 // one honest signal, because the browser cannot see which credential
2958 // an allocation is using — and the stamp naming the credential that
2959 // deadline belongs to are read *before* the fetch. A failed fetch
2960 // leaves neither where the watchdog could confuse them: `fetchedAt`
2961 // only ever advances on a success, which is exactly why reading it
2962 // afterwards made the watchdog unreachable (round-1 review, item 1).
2963 async function renewAll() {
2964 if (state.stopped || renewing) return;
2965 renewing = true;
2966 renewDue = true;
2967 const expiring = ice.fetchedAt;
2968 armMustSucceedBy(mustSucceedBy(), expiring);
2969 try {
2970 // A failed fetch has already armed the warning and the minute
2971 // retry, and that retry comes back here.
2972 if (!(await fetchIce())) return;
2973 renewDue = false;
2974 renewOutdated(expiring);
2975 } finally {
2976 renewing = false;
2977 }
2978 }
2979
2980 // renewOutdated hands a list that has just arrived to every
2981 // connection still on an older one. Every path that produces a list
2982 // comes through here — the scheduled renewal and a tile's Retry
2983 // alike — because a fetch is a fetch: one credential is minted for
2984 // the call, and renewing only the connection whose Retry happened to
2985 // make the request left every other connection on a credential about
2986 // to die, with the shared timers already reset out from under them
2987 // (Codex S3-2).
2988 function renewOutdated(expiring) {
2989 for (const id of Array.from(pcs.keys())) {
2990 const entry = pcs.get(id);
2991 if (!entry || entry.listAt > expiring) continue;
2992 renewOne(id).catch((err) => {
2993 console.error('meet: renew', err);
2994 });
2995 }
2996 }
2997
2998 // armMustSucceedBy sets §5.3 step 3's verdict for the connections that
2999 // have nothing running: with the fetch still failing a minute at a
3000 // time, the old credential's deadline passes and their allocation dies
3001 // with it, and the person is owed the sentence. A connection whose own
3002 // restart is still in flight is left alone — it is the thing that
3003 // would clear this, and interrupting it would show the sentence to
3004 // someone whose call is about to come back.
3005 function armMustSucceedBy(at, expiring) {
3006 clearTimeout(expiryTimer);
3007 if (!at) return;
3008 expiryTimer = setTimeout(() => expireUnrenewed(expiring), Math.max(0, at - Date.now()));
3009 }
3010
3011 // expireUnrenewed is the verdict itself. `expiring` is the stamp of
3012 // the credential that has just run out, so "newer than that" means
3013 // "built on a list this deadline was never about" — a peer who joined
3014 // after the fetch, whose connection has the current credential and
3015 // nothing to renew. It has to be the *expiring* stamp and not
3016 // `ice.fetchedAt`: on the path this exists for, the fetch is still
3017 // failing and `ice.fetchedAt` has not moved, so comparing against it
3018 // exempted every connection in the call and nothing was ever marked.
3019 function expireUnrenewed(expiring) {
3020 if (state.stopped) return;
3021 for (const [id, entry] of pcs) {
3022 // The one exemption that means anything: this connection is on a
3023 // list *newer* than the one that just expired, because it was
3024 // built on it or was proven onto it. `listAt` is that list's
3025 // stamp and it moves only on proof, so it answers "which
3026 // credential is this connection actually using" — which is the
3027 // question. A `renewed` flag answered "did this connection ever
3028 // renew, once, at any time", and stayed true through every later
3029 // failure: one successful renewal exempted a connection from
3030 // every deadline for the rest of the call, and nobody was ever
3031 // told the second credential had died (Codex S3-1).
3032 if (entry.listAt > expiring) continue;
3033 const record = renewals.get(id);
3034 // A restart still in flight is the thing that would clear this,
3035 // and interrupting it would show the sentence to someone whose
3036 // call is about to come back.
3037 if (record && record.running) continue;
3038 markRelayExpired(id, expiring);
3039 }
3040 }
3041
3042 // The two verdicts a renewal can end on, and they are not
3043 // interchangeable. `expired` is the must-succeed-by: the credential
3044 // this connection is using ran out before a new one landed, which is
3045 // §5.3 step 3's honest signal. `stuck` is the other ending — three
3046 // ICE restarts with a good new credential in hand, none of them
3047 // proven — where the credential is fine and the path is not. Saying
3048 // "expired" there would be a sentence about the wrong thing.
3049 function markRelayExpired(id, expiring) {
3050 markTrouble(id, 'expired', expiring);
3051 }
3052
3053 // markTrouble is where a verdict becomes a sentence, and `upTo` is
3054 // the list the verdict is about: the credential that expired, or the
3055 // one a restart could not install. A connection proven onto something
3056 // newer has nothing to answer for and is left alone; anything else is
3057 // told.
3058 //
3059 // It used to read `record.renewed` instead — "did this connection
3060 // ever renew, once, at any time" — which was true for the rest of the
3061 // call after a single success and swallowed every later verdict
3062 // silently, watchdog included (Codex S3-8). The boolean is gone from
3063 // the decision entirely; `listAt` is the only thing that answers
3064 // which credential a connection is actually on.
3065 function markTrouble(id, kind, upTo) {
3066 const entry = pcs.get(id);
3067 if (!entry || (upTo && entry.listAt > upTo)) return;
3068 renewalRecord(id).trouble = kind;
3069 renderTiles();
3070 }
3071
3072 function renewalRecord(id) {
3073 let record = renewals.get(id);
3074 if (!record) {
3075 record = {
3076 attempts: 0, renewed: false, ufrag: '', at: 0, running: false, trouble: '',
3077 // The last run's own budget and how it ended, for a reader who
3078 // needs to know a verdict followed three restarts and not one —
3079 // which `attempts`, counting a whole life, cannot answer.
3080 lastRun: null,
3081 };
3082 renewals.set(id, record);
3083 }
3084 return record;
3085 }
3086
3087 // renewOne is §5.3 step 2 for one connection: the new servers under
3088 // the existing transport, an ICE restart, perfect negotiation carrying
3089 // the offer, and then proof. Three attempts, thirty seconds each, and
3090 // the must-succeed-by is read *between* attempts rather than during
3091 // one — cutting a restart that is about to land would show a person
3092 // the expired sentence for a call that was coming back.
3093 // renewOne is reached only with a fresh credential in hand — every
3094 // caller has just fetched one — so the deadline plays no part in it.
3095 // Its whole budget is three restarts, and its verdict on failure is
3096 // always `stuck`: the credential is fine and the path is not. Cutting
3097 // the budget short at the old deadline and calling the result
3098 // "expired" was a sentence about the wrong thing, told after one
3099 // attempt of the three (Codex S3-4). `expired` belongs to the
3100 // watchdog, which is the only place that knows the other case: no
3101 // fresh credential arrived at all.
3102 async function renewOne(id) {
3103 const entry = pcs.get(id);
3104 if (!entry || state.stopped) return false;
3105 const record = renewalRecord(id);
3106 if (record.running) return false;
3107 record.running = true;
3108 record.renewed = false;
3109 // The stamp of the last list this run actually installed, for the
3110 // verdict at the bottom: it is the list the restarts failed on, and
3111 // not necessarily the newest one the call holds.
3112 let lastInstalled = ice.fetchedAt;
3113 // What *this* run spends, as against `record.attempts`, which is
3114 // the connection's whole life. A verdict has to be readable
3115 // alongside the budget it followed, and a lifetime counter cannot
3116 // say that: a later run raises it while the first verdict is still
3117 // on the screen (Codex S3-14).
3118 let spent = 0;
3119 try {
3120 for (let attempt = 1; attempt <= RENEW_ATTEMPTS; attempt++) {
3121 if (state.stopped || pcs.get(id) !== entry) return false;
3122 // Restarts spent on this connection, and never reset: a
3123 // connection that is handed one list after another and cannot
3124 // land on any of them has spent all of them, and a count that
3125 // started again with each run read as 1 the instant a
3126 // follow-up began — which is a number that says nothing and
3127 // that a gate cannot wait on.
3128 record.attempts += 1;
3129 spent += 1;
3130 // The generation this connection is on now, and the count of
3131 // exchanges it has completed: the two things the proof is
3132 // measured against.
3133 const oldUfrag = await selectedUfrag(entry.pc);
3134 const from = entry.desc;
3135 // The list this attempt installs, and the stamp that names it.
3136 // Read here and used on proof, because `ice.fetchedAt` is the
3137 // *newest* list the call has fetched and another tile's Retry
3138 // can replace it while this attempt is still running: stamping
3139 // the global one claimed the connection was on a credential it
3140 // had never been given, and handed it that credential's
3141 // schedule (Codex S3-9).
3142 const installed = ice.servers;
3143 const installedAt = ice.fetchedAt;
3144 try {
3145 entry.pc.setConfiguration({ iceServers: installed });
3146 entry.floor = !installed.length;
3147 } catch {
3148 // The connection is still on the list it had, and a restart
3149 // from here would re-gather on *those* servers — and could
3150 // prove, on a new fragment, and be stamped onto a list it
3151 // never took (Codex S3-13). Nothing is stamped, nothing is
3152 // restarted, and a fresh generation is asked for instead: a
3153 // rebuilt connection takes `ice.servers` at construction,
3154 // which is the only way left to put these servers under this
3155 // pair, and it keeps §4.6's counters.
3156 requestReset(id);
3157 await sleep(RENEW_WINDOW);
3158 if (state.stopped || pcs.get(id) !== entry) return false;
3159 verdict(id, record, spent, 'stuck', lastInstalled);
3160 return false;
3161 }
3162 // Installed, and only now is this the list the run is working
3163 // on. The stamp moves after the call returns, never before it.
3164 lastInstalled = installedAt;
3165 try {
3166 entry.pc.restartIce();
3167 } catch {
3168 // No restartIce at all: a fresh generation is the only way to
3169 // put a new credential under this pair, and the `pair` that
3170 // answers rebuilds the connection from nothing — a rebuild
3171 // this record does not survive, which is what "the connection
3172 // is gone from under us" means below. If nothing has rebuilt
3173 // it by the end of the window, nothing is going to, and the
3174 // person is owed a sentence rather than a tile that looks
3175 // fine and carries no media.
3176 requestReset(id);
3177 await sleep(RENEW_WINDOW);
3178 if (state.stopped || pcs.get(id) !== entry) return false;
3179 verdict(id, record, spent, 'stuck', installedAt);
3180 return false;
3181 }
3182 const proven = await proveRenewed(id, entry, oldUfrag, from, Date.now() + RENEW_WINDOW);
3183 if (state.stopped || pcs.get(id) !== entry) return false;
3184 if (proven !== null) {
3185 record.renewed = true;
3186 record.ufrag = proven;
3187 record.at = Date.now();
3188 entry.listAt = installedAt;
3189 record.trouble = '';
3190 record.lastRun = { attempts: spent, verdict: 'renewed' };
3191 renderTiles();
3192 return true;
3193 }
3194 }
3195 verdict(id, record, spent, 'stuck', lastInstalled);
3196 return false;
3197 } finally {
3198 record.running = false;
3199 // And if a newer list arrived while this attempt was running,
3200 // this connection owes a renewal onto it: `renewOutdated` skipped
3201 // it because a restart was in flight, and nothing else is coming
3202 // for it until the next scheduled renewal (Codex S3-9).
3203 followUp(id, lastInstalled);
3204 }
3205 }
3206
3207 // verdict records how a run ended and what it spent getting there,
3208 // and then says it on the tile. `spent` is this run's own budget;
3209 // `record.attempts` keeps counting across runs for whoever wants the
3210 // whole story.
3211 function verdict(id, record, spent, kind, upTo) {
3212 record.lastRun = { attempts: spent, verdict: kind };
3213 markTrouble(id, kind, upTo);
3214 }
3215
3216 // followUp is that debt, paid once the attempt that incurred it has
3217 // let go of the record. `attempted` is the newest list that run had
3218 // to work with: only a list newer than *that* is a debt, which is
3219 // what keeps a connection that simply cannot be renewed from
3220 // restarting itself for ever. A timeout of zero rather than a direct
3221 // call, because `renewOne` refuses to start while `running` is set
3222 // and this runs from the `finally` that clears it.
3223 function followUp(id, attempted) {
3224 if (state.stopped || ice.fetchedAt <= attempted) return;
3225 const entry = pcs.get(id);
3226 if (!entry || entry.listAt >= ice.fetchedAt) return;
3227 setTimeout(() => {
3228 const now = pcs.get(id);
3229 if (state.stopped || !now || now.listAt >= ice.fetchedAt) return;
3230 renewOne(id).catch((err) => {
3231 console.error('meet: renew', err);
3232 });
3233 }, 0);
3234 }
3235
3236 // retryRenewal is the control §5.3 step 3 puts on a tile in trouble:
3237 // a fresh fetch, then step 2 again — for this connection and for
3238 // every other one the fetch just re-credentialed.
3239 //
3240 // A fetch that fails is the case worth writing out. `restartIce` has
3241 // already cleared the sentence off the tile, so returning here left a
3242 // person looking at a tile that said nothing was wrong while nothing
3243 // had been done about it. The sentence goes back up — it is still
3244 // true — and the connection still gets the plain restart the ordinary
3245 // Retry would have given it, which is the one thing left that might
3246 // help.
3247 async function retryRenewal(id, wasTrouble) {
3248 const expiring = ice.fetchedAt;
3249 if (await fetchIce()) {
3250 // Not just this one. The fetch this Retry made replaced the
3251 // credential every connection was using, and reset the shared
3252 // schedule with it, so every connection still on the old list is
3253 // renewed here (Codex S3-2).
3254 renewOutdated(expiring);
3255 return;
3256 }
3257 if (wasTrouble) {
3258 renewalRecord(id).trouble = wasTrouble;
3259 renderTiles();
3260 }
3261 const entry = pcs.get(id);
3262 if (entry) bareRestart(id, entry);
3263 }
3264
3265 // proveRenewed polls getStats until the decision below says the
3266 // restart landed, or until the window runs out. Half a second between
3267 // polls: an ICE restart is a round trip and a handful of candidate
3268 // exchanges, and asking faster only costs the call CPU.
3269 async function proveRenewed(id, entry, oldUfrag, from, deadline) {
3270 // The generation this connection was on before the restart, when it
3271 // could be read. When it could not, the first fragment readable
3272 // afterwards stands in for it, and the proof is then the ordinary
3273 // one: a *different* fragment after that. It is a weaker starting
3274 // point and it can honestly fail to prove a restart that did land —
3275 // but failing to prove costs a sentence and a Retry, where wrongly
3276 // proving is a call running on a credential nobody ever checked.
3277 let baseline = oldUfrag || '';
3278 for (;;) {
3279 // A connection replaced under us — a `pair`, a roster, an
3280 // unreachable target — is not the connection this proof is about,
3281 // and polling its stats for another thirty seconds proves nothing
3282 // about either of them.
3283 if (state.stopped || pcs.get(id) !== entry) return null;
3284 const reports = await statsList(entry.pc);
3285 const proven = renewedUfrag(reports, baseline,
3286 entry.pc.signalingState, entry.desc > from);
3287 if (proven !== null) return proven;
3288 if (!baseline) baseline = selectedPairUfrag(reports) || '';
3289 const left = deadline - Date.now();
3290 if (left <= 0) return null;
3291 await sleep(Math.min(RENEW_POLL, left));
3292 }
3293 }
3294
3295 // renewedUfrag is §5.3 step 2's decision, written as a pure function
3296 // of one getStats report so it can be reasoned about — and gated —
3297 // without a browser (test/browser/negotiation.test.mjs lifts it out of
3298 // this file by name).
3299 //
3300 // A connection is renewed when the restart's offer/answer exchange has
3301 // completed, `signalingState` is stable with that answer applied, and
3302 // the selected succeeded pair's local candidate carries a *different*
3303 // ICE username fragment from the one the connection was on. An
3304 // `iceConnectionState` change proves nothing on its own: a `completed`
3305 // transport moves to `connected` merely by starting a restart.
3306 //
3307 // It answers the new fragment, '' when the restart is proven but the
3308 // browser does not name fragments, and null when it is not proven —
3309 // so callers test `!== null`, never truthiness.
3310 function renewedUfrag(reports, oldUfrag, signalingState, negotiated) {
3311 if (!negotiated || signalingState !== 'stable') return null;
3312 // No baseline, no proof. Without knowing which generation this
3313 // connection was on, a selected pair that has not moved at all
3314 // looks exactly like one that has — and the old reading took that
3315 // as proof, cleared the warning, and stamped the connection as
3316 // renewed onto a credential it had never gathered on (Codex S3-3).
3317 // A getStats that rejected before the restart arrived here the same
3318 // way. The caller establishes a baseline from the first reading it
3319 // can take *after* the restart and comes back; if none can be read,
3320 // the restart stays unproven, which is the honest answer.
3321 if (!oldUfrag) return null;
3322 const ufrag = selectedPairUfrag(reports);
3323 // And a pair the browser will not name is not evidence either: ''
3324 // says "there is a pair", not "there is a new one".
3325 if (!ufrag) return null;
3326 return ufrag !== oldUfrag ? ufrag : null;
3327 }
3328
3329 // selectedPairUfrag reads one getStats report and answers the ICE
3330 // username fragment on the local candidate of the selected, succeeded
3331 // candidate pair: the fragment when the browser names it, '' when the
3332 // pair is there and the fragment is not, and null when there is no
3333 // such pair at all. Pure, like the decision above.
3334 //
3335 // Where a browser names the selected pair itself — Chromium's
3336 // transport.selectedCandidatePairId — that answer wins outright, and a
3337 // pair it does not name is not consulted however succeeded and
3338 // nominated it looks. Chromium keeps the *previous* generation's pair
3339 // in the report for a while after a restart, still succeeded and still
3340 // nominated, and scanning for one of those was how a restart could
3341 // read as proven by the connection it had just replaced (round-1
3342 // review, item 2). `nominated`/`selected` are the fallback for a
3343 // report with no transport in it, which is what Firefox sends.
3344 function selectedPairUfrag(reports) {
3345 const locals = new Map();
3346 const pairs = [];
3347 const selected = new Set();
3348 let transports = 0;
3349 for (const r of reports || []) {
3350 if (!r || !r.type) continue;
3351 if (r.type === 'local-candidate') locals.set(r.id, r);
3352 else if (r.type === 'candidate-pair') pairs.push(r);
3353 else if (r.type === 'transport') {
3354 transports += 1;
3355 if (r.selectedCandidatePairId) selected.add(r.selectedCandidatePairId);
3356 }
3357 }
3358 // A transport that has not named a pair yet has not selected one:
3359 // `selected` is empty, nothing matches, and the answer is null.
3360 const chosen = transports
3361 ? pairs.filter((p) => selected.has(p.id))
3362 : pairs.filter((p) => p.nominated || p.selected);
3363 let found = null;
3364 for (const p of chosen) {
3365 if (p.state !== 'succeeded') continue;
3366 const local = locals.get(p.localCandidateId);
3367 const ufrag = (local && local.usernameFragment) || '';
3368 // A pair that names the fragment is worth more than one that does
3369 // not, so keep looking rather than settling for the first.
3370 if (ufrag) return ufrag;
3371 found = '';
3372 }
3373 return found;
3374 }
3375
3376 // selectedUfrag is the generation a connection is on right now. null
3377 // means the browser will not say — no selected pair yet, or no
3378 // fragment reported — which is the case renewedUfrag falls back for.
3379 async function selectedUfrag(pc) {
3380 return selectedPairUfrag(await statsList(pc)) || null;
3381 }
3382
3383 // statsList flattens one RTCStatsReport into an array, and answers an
3384 // empty one for a connection that is closing — getStats can reject,
3385 // and on some browsers throw outright, and neither is worth an
3386 // exception in the middle of a renewal.
3387 function statsList(pc) {
3388 try {
3389 return pc.getStats().then((stats) => {
3390 const list = [];
3391 stats.forEach((report) => list.push(report));
3392 return list;
3393 }, () => []);
3394 } catch {
3395 return Promise.resolve([]);
3396 }
3397 }
3398
3399 function stopIceTimers() {
3400 clearTimeout(renewTimer);
3401 clearTimeout(iceRetryTimer);
3402 clearTimeout(expiryTimer);
3403 }
3404
3405 // ---------------------------------------------------------------
3406 // Outbound queue (§4.6)
3407 // ---------------------------------------------------------------
3408
3409 function send(to, type, payload) {
3410 if (!state.peer) return;
3411 payload = testBlockedPayload(payload);
3412 // A target the hub has already said it does not have. Queueing for
3413 // it would buy one more 404 and one more recovery round each time,
3414 // and ICE alone produces a dozen candidates a renegotiation; the
3415 // roster is what settles this, and it clears the mark.
3416 if (stale.has(to)) return;
3417 const seq = (seqOut.get(to) || 0) + 1;
3418 seqOut.set(to, seq);
3419 const q = queue.get(to) || [];
3420 q.push({ seq, body: { peer: state.peer, type, to, seq, gen: gen.get(to) || 1, payload } });
3421 queue.set(to, q);
3422 pump(to);
3423 }
3424
3425 // pump owns one POST at a time per target, in order, and does not
3426 // start the next message until this one is accepted. Every status the
3427 // wire contract names has its own arm here.
3428 //
3429 // §4.6's thirty seconds is an absolute deadline per message, stamped
3430 // when the message reaches the head of the queue and covering
3431 // everything that follows: the requests, the backoff between them,
3432 // and the 429s. Each of those used to be able to slip it (Codex
3433 // S2-6) — a 429 skipped the check entirely, a sleep could overshoot
3434 // it, and a fetch that never settled meant the check was never
3435 // reached at all — so a pair could sit "unreachable" for ever with
3436 // nothing rebuilding it. The fetch is aborted at the deadline for
3437 // that last one.
3438 async function pump(to) {
3439 if (inflight.has(to)) return;
3440 inflight.add(to);
3441 let wait = BACKOFF_MIN;
3442 try {
3443 for (;;) {
3444 const q = queue.get(to);
3445 if (!q || !q.length || state.stopped) return;
3446 const head = q[0];
3447 if (!head.deadline) head.deadline = Date.now() + SEND_DEADLINE;
3448 if (Date.now() >= head.deadline) {
3449 unreachable(to);
3450 return;
3451 }
3452 const res = await postSignal(head.body, { deadline: head.deadline });
3453 if (queue.get(to) !== q) return; // the queue was dropped underneath us
3454 // signedOut is read before the status, because it can be true
3455 // *of* a 200: an expired session answers 303 to /signin, fetch
3456 // follows it, and the sign-in page comes back 200 (Codex S2-8).
3457 if (res.signedOut) {
3458 terminal('signedout');
3459 return;
3460 }
3461 if (res.status === 200) {
3462 // Accepted by the hub, which is the only count worth having:
3463 // one taken at `send` counted candidates that a stale target
3464 // dropped on the spot and ones still sitting in a queue
3465 // nobody was pumping (Codex S3-12).
3466 if (head.body.type === 'candidate') {
3467 const entry = pcs.get(to);
3468 if (entry) entry.delivered += 1;
3469 }
3470 q.shift();
3471 wait = BACKOFF_MIN;
3472 continue;
3473 }
3474 if (res.status === 429) {
3475 // Retry-After is whole seconds, and the same message is
3476 // retried with the same seq — but never past this message's
3477 // own deadline.
3478 if (!(await waitWithin(retryAfter(res.retryAfter), head.deadline))) {
3479 unreachable(to);
3480 return;
3481 }
3482 continue;
3483 }
3484 if (res.status === 409) {
3485 if (res.data.error === 'stale') {
3486 // The pair moved on. Drop everything queued for this
3487 // target; a `pair` or the next roster rebuilds it, and if
3488 // the roster already knows a higher generation, use it now.
3489 queue.set(to, []);
3490 const known = rosterGen(to);
3491 if (known > (gen.get(to) || 0)) rebuildPC(to, known);
3492 else requestReset(to);
3493 return;
3494 }
3495 return; // `conflict` belongs to admit, which is not queued here
3496 }
3497 if (res.status === 404) {
3498 // The message's own deadline, not a fresh one: the diagnosis
3499 // and any reset it leads to are part of getting this message
3500 // delivered, and §4.6 gives that thirty seconds in total
3501 // (Codex S2-15).
3502 await recoverFromNotFound(res.data.boot, to, { deadline: head.deadline });
3503 return;
3504 }
3505 if (res.status === 400 || res.status === 413) {
3506 // Malformed, or over 64 KB: never retried. Drop that one
3507 // message and carry on with the rest of the queue — the next
3508 // one gets a deadline of its own, because this one was
3509 // answered.
3510 q.shift();
3511 wait = BACKOFF_MIN;
3512 continue;
3513 }
3514 if (!(await waitWithin(wait, head.deadline))) {
3515 unreachable(to);
3516 return;
3517 }
3518 wait = Math.min(wait * 2, BACKOFF_MAX);
3519 }
3520 } finally {
3521 inflight.delete(to);
3522 // A send() that arrived while this POST was in flight found the
3523 // pump busy and returned; and if the queue was replaced under
3524 // this loop, the loop returned rather than touching the new one.
3525 // Either way what is here now has no pump, so it gets this one.
3526 const rest = queue.get(to);
3527 if (!state.stopped && rest && rest.length) pump(to);
3528 }
3529 }
3530
3531 // unreachable is §4.6's verdict on one target: the message at the head
3532 // of its queue never got through inside its deadline. Close the
3533 // connection, drop what was queued for it, and ask the hub for a fresh
3534 // generation — `pair` or the next roster builds it again.
3535 function unreachable(to) {
3536 queue.set(to, []);
3537 closePC(to, false);
3538 renderTiles();
3539 requestReset(to);
3540 }
3541
3542 // ---------------------------------------------------------------
3543 // The broadcast lane (§4.3's chat and share)
3544 // ---------------------------------------------------------------
3545 //
3546 // `send` above is §4.6: per target, with a seq, a generation and a
3547 // pair to reset when it stops working. Chat and screen share are
3548 // neither targeted nor paired — the hub fans them out to every other
3549 // admitted peer and rebuilds the envelope itself — so they ride a
3550 // queue of their own under the sentinel key '*', with the same pump
3551 // discipline and none of §4.6's bookkeeping: no `to`, no `seq`, no
3552 // `gen` on the wire, and `stale`/`gen` mean nothing here.
3553 //
3554 // The one thing this lane has that the other does not is an answer:
3555 // the chat panel echoes a line into the log only when the hub took
3556 // it, so every message resolves exactly once, and only a 200 resolves
3557 // true.
3558
3559 // broadcastBody is the whole wire shape of an untargeted message. It
3560 // is its own function because what is *not* in it is the contract:
3561 // any `to`, `seq` or `gen` here is a 400 from /signal.
3562 function broadcastBody(peer, type, payload) {
3563 return { peer, type, payload };
3564 }
3565
3566 // broadcastVerdict reads one POST answer, in the wire contract's own
3567 // terms. Pure, so the node test can lift it by name.
3568 function broadcastVerdict(res) {
3569 // signedOut before the status, for the reason pump gives: an
3570 // expired session answers 303 to /signin and fetch follows it, so
3571 // the sign-in page comes back 200.
3572 if (res.signedOut) return 'signedout';
3573 if (res.status === 200) return 'sent';
3574 if (res.status === 429) return 'wait';
3575 if (res.status === 404) return 'recover';
3576 // 400 is a bug in this file, 413 is a message the server will never
3577 // take however often it is offered, and 409 belongs to the targeted
3578 // lane and cannot mean anything here. None of the three is retried.
3579 if (res.status === 400 || res.status === 413 || res.status === 409) return 'drop';
3580 // A 5xx, a network failure, or a status the contract does not name:
3581 // worth trying again inside the deadline.
3582 return 'retry';
3583 }
3584
3585 // accepted is the answer the sender gets, and the only true in it is
3586 // a 200. chat.js echoes a line into the log on exactly `true` and on
3587 // nothing else, so anything looser here would put a message on the
3588 // screen that nobody received.
3589 function accepted(verdict) {
3590 return verdict === 'sent';
3591 }
3592
3593 // recoveryDeadline is the budget a 404's diagnosis actually gets. The
3594 // message's own deadline, unless the POST that produced the 404 spent
3595 // it — a recovery with nothing left decides nothing, leaves the
3596 // participation unexamined, and the tab goes on looking live. Pure, so
3597 // the node test can lift it by name.
3598 function recoveryDeadline(deadline, now) {
3599 return Math.max(deadline, now + MIN_RECOVERY);
3600 }
3601
3602 // broadcast queues one untargeted message and resolves when the hub
3603 // has answered for it: true if it was accepted, false for every other
3604 // ending, including a deadline that ran out with nothing decided.
3605 // `onStatus`, if given, hears the status of the answer that settled it
3606 // — the one thing the boolean cannot say, and what §15.20's report
3607 // needs to tell an old server's 400 from a network that failed.
3608 function broadcast(type, payload, onStatus) {
3609 if (!state.peer || state.stopped) return Promise.resolve(false);
3610 return new Promise((resolve) => {
3611 const q = queue.get(BROADCAST) || [];
3612 q.push({ body: broadcastBody(state.peer, type, payload), resolve, onStatus });
3613 queue.set(BROADCAST, q);
3614 runBroadcast();
3615 });
3616 }
3617
3618 // runBroadcast is the fire-and-forget face of pumpBroadcast: nothing
3619 // awaits the pump, and a rejection escaping an async function nobody
3620 // awaits goes where neither a person nor a gate could see it. Same
3621 // shape as requestReset's, and as the share button's.
3622 function runBroadcast() {
3623 pumpBroadcast().catch((err) => {
3624 console.error('meet: chat', err);
3625 });
3626 }
3627
3628 // pumpBroadcast is pump's discipline for the lane with no target: one
3629 // POST in flight, in order, each message with its own absolute thirty
3630 // seconds covering the requests, the backoff and the 429s.
3631 async function pumpBroadcast() {
3632 if (inflight.has(BROADCAST)) return;
3633 inflight.add(BROADCAST);
3634 let wait = BACKOFF_MIN;
3635 try {
3636 for (;;) {
3637 const q = queue.get(BROADCAST);
3638 if (!q || !q.length) return;
3639 if (state.stopped) {
3640 // Nothing more will be sent, and a sender waiting on a
3641 // promise that never settles is a chat box that never comes
3642 // back. Answer every one of them.
3643 drainBroadcast(q);
3644 return;
3645 }
3646 const head = q[0];
3647 if (!head.deadline) head.deadline = Date.now() + SEND_DEADLINE;
3648 if (Date.now() >= head.deadline) {
3649 // Out of time with nothing decided: the sender is told so, and
3650 // the next message in the lane starts on a budget of its own.
3651 settleBroadcast(q, false);
3652 wait = BACKOFF_MIN;
3653 continue;
3654 }
3655 const res = await postSignal(head.body, { deadline: head.deadline });
3656 if (queue.get(BROADCAST) !== q) return; // the queue was dropped underneath us
3657 const verdict = broadcastVerdict(res);
3658 if (verdict === 'signedout') {
3659 drainBroadcast(q);
3660 terminal('signedout');
3661 return;
3662 }
3663 if (verdict === 'sent' || verdict === 'drop') {
3664 if (typeof head.onStatus === 'function') head.onStatus(res.status);
3665 settleBroadcast(q, accepted(verdict));
3666 wait = BACKOFF_MIN;
3667 continue;
3668 }
3669 if (verdict === 'recover') {
3670 // The participation is gone, or was never admitted. Nothing
3671 // queued here can be delivered by anyone, so every sender is
3672 // answered before the probe-first diagnosis decides what this
3673 // tab does next — with no target to pass it, because a
3674 // fan-out message never had one.
3675 queue.set(BROADCAST, []);
3676 drainBroadcast(q);
3677 await recoverFromNotFound(res.data.boot, null, {
3678 deadline: recoveryDeadline(head.deadline, Date.now()),
3679 });
3680 return;
3681 }
3682 const ms = verdict === 'wait' ? retryAfter(res.retryAfter) : wait;
3683 if (!(await waitWithin(ms, head.deadline))) {
3684 settleBroadcast(q, false);
3685 wait = BACKOFF_MIN;
3686 continue;
3687 }
3688 if (verdict !== 'wait') wait = Math.min(wait * 2, BACKOFF_MAX);
3689 }
3690 } finally {
3691 inflight.delete(BROADCAST);
3692 const rest = queue.get(BROADCAST);
3693 if (rest && rest.length) {
3694 // Something was queued while this pump was busy — during the
3695 // 404's diagnosis, most of the time, which is the one arm that
3696 // returns while the tab may still be alive. If that diagnosis
3697 // ended the session there is nobody left to send it, and a
3698 // sender left holding a promise that never settles is a composer
3699 // that never comes back; otherwise it gets this pump.
3700 if (state.stopped) drainBroadcast(rest);
3701 else runBroadcast();
3702 }
3703 }
3704 }
3705
3706 // settleBroadcast answers the message at the head of the lane and
3707 // drops it.
3708 function settleBroadcast(q, ok) {
3709 const head = q.shift();
3710 if (head && head.resolve) head.resolve(ok);
3711 }
3712
3713 // drainBroadcast answers everything still queued with false: the lane
3714 // is finished, and nothing in it was delivered.
3715 function drainBroadcast(q) {
3716 while (q.length) settleBroadcast(q, false);
3717 }
3718
3719 function rosterGen(id) {
3720 if (!lastRoster) return 0;
3721 for (const rp of lastRoster.peers || []) if (rp.peer === id) return rp.gen || 0;
3722 return 0;
3723 }
3724
3725 function retryAfter(header) {
3726 const n = parseInt(header || '', 10);
3727 return Number.isFinite(n) && n > 0 ? Math.min(n, 30) * 1000 : 1000;
3728 }
3729
3730 function sleep(ms) {
3731 return new Promise((resolve) => setTimeout(resolve, ms));
3732 }
3733
3734 // waitWithin sleeps for ms, or until the deadline, whichever comes
3735 // first, and answers whether there is any budget left afterwards. A
3736 // backoff is not allowed to be the reason a deadline is missed.
3737 async function waitWithin(ms, deadline) {
3738 const left = deadline - Date.now();
3739 if (left <= 0) return false;
3740 await sleep(Math.min(ms, left));
3741 return Date.now() < deadline;
3742 }
3743
3744 // postSignal is the one place this file talks upstream. csrf.Protect
3745 // is origin-based, so a same-origin fetch needs no token.
3746 //
3747 // `deadline` is an absolute instant, not a duration: a request that
3748 // has not settled by then is aborted, so a hanging fetch cannot hold
3749 // a queue open past the moment its caller had promised to give up
3750 // (Codex S2-6). An aborted fetch throws, and lands on the same
3751 // status 0 as any other network failure — which the caller then reads
3752 // as "out of budget" on its next pass.
3753 async function postSignal(body, opts) {
3754 const o = opts || {};
3755 const path = '/m/' + encodeURIComponent(sqid) + '/signal';
3756 let stop = 0;
3757 let controller = null;
3758 if (o.deadline && typeof AbortController === 'function') {
3759 controller = new AbortController();
3760 stop = setTimeout(() => controller.abort(), Math.max(0, o.deadline - Date.now()));
3761 }
3762 try {
3763 const res = await fetch(path, {
3764 method: 'POST',
3765 credentials: 'same-origin',
3766 headers: { 'Content-Type': 'application/json' },
3767 body: JSON.stringify(body),
3768 keepalive: !!o.keepalive,
3769 signal: controller ? controller.signal : undefined,
3770 });
3771 return await readRefusal(res, 200, path);
3772 } catch {
3773 return { status: 0, data: {}, signedOut: false, retryAfter: null };
3774 } finally {
3775 if (stop) clearTimeout(stop);
3776 }
3777 }
3778
3779 // requestReset is the fire-and-forget face of resetPair: every caller
3780 // asks for a reset and carries on, and a rejection escaping an async
3781 // function nobody awaits would go where neither a person nor a gate
3782 // could see it. Same shape as the pageshow handler's.
3783 function requestReset(to, budget) {
3784 resetPair(to, budget).catch((err) => {
3785 console.error('meet: reset', err);
3786 });
3787 }
3788
3789 // resetPair asks the hub for a fresh generation with this target.
3790 // The answer used to be discarded (Codex S2-5), so a 429 or a 5xx
3791 // lost the reset silently — and the reset that follows an outbound
3792 // deadline is the only thing that rebuilds a connection this browser
3793 // has just closed, which left the pair down with nothing coming to
3794 // fix it. Bounded by the same thirty seconds one queued message gets,
3795 // and by the same rules: Retry-After on a 429, doubling backoff on
3796 // the transient failures, terminal on a session that has been signed
3797 // out, and the 404 ladder.
3798 async function resetPair(to, budget) {
3799 const peer = state.peer;
3800 if (!peer) return;
3801 // One reset per target at a time. Two in flight can only ask the hub
3802 // for two generations, and the second is stale before it is sent.
3803 if (resetting.has(to)) return;
3804 resetting.add(to);
3805 try {
3806 await resetLoop(to, peer, budget || Date.now() + SEND_DEADLINE);
3807 } finally {
3808 resetting.delete(to);
3809 }
3810 }
3811
3812 async function resetLoop(to, peer, deadline) {
3813 let wait = BACKOFF_MIN;
3814 for (;;) {
3815 if (state.stopped || state.peer !== peer) return;
3816 if (Date.now() >= deadline) {
3817 // The budget this reset inherited is spent. One more POST would
3818 // be a request made outside the deadline that was supposed to
3819 // cover it, and the target has to be released either way
3820 // (Codex S2-17): the roster is what settles it now.
3821 staleTarget(to, true, deadline);
3822 return;
3823 }
3824 const res = await postSignal({ peer, type: 'reset', to }, { deadline });
3825 if (res.signedOut) {
3826 terminal('signedout');
3827 return;
3828 }
3829 if (res.status === 200) return;
3830 if (res.status === 404) {
3831 // Whatever this 404 turns out to be, it is not worth another
3832 // reset: `fromReset` is what stops the cycle, and the budget is
3833 // the same one, not a fresh thirty seconds (Codex S2-11).
3834 await recoverFromNotFound(res.data.boot, to, { deadline, fromReset: true });
3835 return;
3836 }
3837 if (res.status !== 429 && res.status !== 0 && res.status < 500) {
3838 // 400, 409 and anything else the contract names: a reset that
3839 // is refused on its merits is not retried. The roster is the
3840 // other way this pair converges (§4.6).
3841 return;
3842 }
3843 const ms = res.status === 429 ? retryAfter(res.retryAfter) : wait;
3844 wait = Math.min(wait * 2, BACKOFF_MAX);
3845 // As in the diagnosis: round the loop, and let the check at the
3846 // top be the one place a spent budget is answered.
3847 await waitWithin(ms, deadline);
3848 }
3849 }
3850
3851 // recoverFromNotFound is a 404 from either endpoint. It used to read
3852 // as "this participation no longer exists" and close everything, but
3853 // a 404 from `/signal` says no such thing (Codex S2-3): the *target*
3854 // may simply have left, which is the ordinary case while this
3855 // browser's own stream is down and the `gone` event cannot reach it.
3856 // Acting on that as if it were our own ending closed a live call and
3857 // then met a 409 from our own still-live participation, and showed a
3858 // takeover screen for a tab that does not exist.
3859 //
3860 // So the sender's own participation is probed, and that is the
3861 // authority: 204 keeps the call and lets the next roster reconcile
3862 // the target; 410 is terminal with the reason the tombstone carries;
3863 // 404 — and only 404 — is the fresh-entry ladder, which is what this
3864 // function always was.
3865 //
3866 // A 429 or a 5xx from the probe proves nothing either way, and used
3867 // to fall through to the fresh-entry ladder and re-create exactly the
3868 // failure above (Codex S2-12). It is retried instead, on the stream's
3869 // own backoff, inside one budget shared with whatever asked for the
3870 // diagnosis — a recovery that cannot get an answer inside thirty
3871 // seconds leaves the participation alone and lets the stream ladder,
3872 // which is running anyway, be the thing that decides.
3873 async function recoverFromNotFound(boot, to, opts) {
3874 const o = opts || {};
3875 const deadline = o.deadline || Date.now() + SEND_DEADLINE;
3876 if (state.stopped) return;
3877 if (boot) state.boot = boot;
3878 const peer = state.peer;
3879 if (!peer) {
3880 enterAfresh();
3881 return;
3882 }
3883 const path = '/m/' + encodeURIComponent(sqid) + '/stream?probe=1&peer=' + encodeURIComponent(peer);
3884 let wait = BACKOFF_MIN;
3885 for (;;) {
3886 if (Date.now() >= deadline) {
3887 // Out of budget with nothing decided. The participation is left
3888 // alone — nothing here proved anything about it — but the target
3889 // this recovery was for is treated as stale, so the queue is
3890 // dropped and the in-flight mark released rather than held by a
3891 // diagnosis that is never going to answer (Codex S2-15). The
3892 // next roster settles it.
3893 staleTarget(to, true, deadline);
3894 return;
3895 }
3896 let res;
3897 try {
3898 res = await probe(path, deadline);
3899 } catch {
3900 // The probe could not be made at all: the same "nothing is
3901 // proved" as a 5xx, and treated the same way.
3902 res = { status: 0, data: {}, signedOut: false, retryAfter: null };
3903 }
3904 if (state.stopped || state.peer !== peer) return;
3905 if (refused(res)) return;
3906 if (res.status === 410) {
3907 terminal(res.data.reason || 'ended');
3908 return;
3909 }
3910 if (res.status === 204) {
3911 staleTarget(to, !!o.fromReset, deadline);
3912 return;
3913 }
3914 if (res.status === 404) {
3915 enterAfresh();
3916 return;
3917 }
3918 // 429, 5xx, a network failure, or a status the contract does not
3919 // name: try the diagnosis again rather than acting on it.
3920 const ms = res.status === 429 ? retryAfter(res.retryAfter) : wait;
3921 wait = Math.min(wait * 2, STREAM_BACKOFF_MAX);
3922 // Deliberately not a `return` when the budget runs out here: the
3923 // loop goes round and the check at the top is the one exit for an
3924 // exhausted diagnosis, so it cannot be reached without releasing
3925 // the target (Codex S2-17). Returning straight from this line left
3926 // the queue intact, the pump's `finally` restarted it, its expired
3927 // head called `unreachable`, and that opened a reset with a fresh
3928 // thirty seconds — the bounded recovery this whole path exists to
3929 // be. `waitWithin` does not sleep when there is nothing left, so
3930 // this is not a spin.
3931 await waitWithin(ms, deadline);
3932 }
3933 }
3934
3935 // staleTarget is what a 404 means once the probe has said this
3936 // browser's own participation is fine: the peer we were writing to has
3937 // gone, and our roster has not caught up. Nothing queued for it can be
3938 // delivered, and nothing new may be queued until a roster settles it.
3939 //
3940 // The single reset is worth asking for once, while the roster still
3941 // lists the target, because a `pair` is how a live peer that merely
3942 // lost its own participation comes back. Asking again after that reset
3943 // has itself been answered 404 is the cycle S2-11 found — twelve
3944 // rounds and counting — so `fromReset` skips straight to closing the
3945 // connection and waiting for the roster, which recreates it through
3946 // `reconcile` if the peer is still there.
3947 function staleTarget(to, fromReset, deadline) {
3948 if (!to) return;
3949 queue.set(to, []);
3950 const first = !stale.has(to);
3951 stale.add(to);
3952 if (first && !fromReset && rosterGen(to)) {
3953 // The same budget again: one message, one thirty seconds, however
3954 // many requests it takes to settle (Codex S2-15).
3955 requestReset(to, deadline);
3956 return;
3957 }
3958 closePC(to, false);
3959 renderTiles();
3960 }
3961
3962 // enterAfresh is the fresh-entry ladder: drop every connection, forget
3963 // the peer, and open a new stream. `boot` has already been recorded by
3964 // the caller, so the fresh stream starts from the right one.
3965 function enterAfresh() {
3966 if (state.stopped) return;
3967 closeStream();
3968 closeAllPCs();
3969 state.peer = null;
3970 connectStream();
3971 }
3972
3973 // ---------------------------------------------------------------
3974 // Chat (§6) and screen share (§5.4)
3975 // ---------------------------------------------------------------
3976 //
3977 // The panel is chat.js's: it owns the log, the composer, the two
3978 // sentences it can say and every word on a line. This file owns four
3979 // things about it — the wire underneath it, the name on the local
3980 // echo, when it appears, and when it is usable — and nothing else.
3981 // Nothing below reads inside `#chat`.
3982 //
3983 // Screen share is §5.4 in full: one display capture, carried to every
3984 // connection on a `sendonly` transceiver of its own so the camera
3985 // m-line is untouched, announced with a `share` message so the far
3986 // side can label the tile before the track lands, and stopped by
3987 // stopping the transceiver — which ends the receiver's track rather
3988 // than leaving a frozen last frame on the screen.
3989
3990 const SHARE_REFUSED = 'Screen sharing was not allowed.';
3991
3992 // mountChat hands chat.js the panel and the one thing it cannot know:
3993 // how to put a line on the wire. It is called on admission and on the
3994 // first arriving message, whichever comes first — a `chat` can be
3995 // fanned out to us while §5.2's fetch still has our own roster
3996 // waiting behind it, and a message that reached this tab is a message
3997 // a person should see.
3998 //
3999 // Un-hiding is this file's job and not the panel's: `mount` never
4000 // touches `hidden`, because when a panel is usable is the host's
4001 // fact. And it is only un-hidden if chat.js is actually here — a
4002 // visible composer with no script behind it would submit its form and
4003 // navigate away from the call.
4004 function mountChat() {
4005 if (chat) return chat;
4006 if (!chatEl || !window.Chat || typeof window.Chat.mount !== 'function') return null;
4007 // chat.js answers a root it cannot use with a working no-op rather
4008 // than a throw, which is right for it and wrong to trust here: an
4009 // un-hidden panel backed by a no-op is a composer that swallows
4010 // everything typed into it in silence. These are the three elements
4011 // its own mount requires, so this is the same question asked before
4012 // the answer stops being distinguishable.
4013 if (!chatEl.querySelector('[data-chat-log]') ||
4014 !chatEl.querySelector('[data-chat-form]') ||
4015 !chatEl.querySelector('[data-chat-text]')) {
4016 return null;
4017 }
4018 const panel = window.Chat.mount(chatEl, { name: selfName, send: sendChat });
4019 if (!panel) return null;
4020 chat = panel;
4021 chatEl.hidden = false;
4022 chat.setEnabled(!!state.admitted && !state.stopped);
4023 return chat;
4024 }
4025
4026 // chatEnabled is the panel's gate, and it moves with admission: the
4027 // roster turns it on, terminal and leave turn it off. It is not the
4028 // same thing as `hidden` — a panel that has been usable stays
4029 // readable after the call ends.
4030 function chatEnabled(on) {
4031 if (!chat) return;
4032 chat.setEnabled(!!on);
4033 }
4034
4035 // sendChat is the panel's `send`: chat.js hands it text it has
4036 // already trimmed and measured, and reads back a strict boolean. True
4037 // is the only answer that echoes the line into the log, so anything
4038 // this file is unsure about has to be false.
4039 async function sendChat(text) {
4040 const ok = await broadcast('chat', { text });
4041 if (ok === true) chatSent += 1;
4042 return ok === true;
4043 }
4044
4045 // onChat renders one arrived message (§6). The name comes from the
4046 // envelope and from nowhere else: the hub put the sender's own name
4047 // on it, and a peer that is not in this tab's roster — one admitted
4048 // while our own roster was in flight — is still someone the hub says
4049 // is in the room. The text is re-validated as a string here, because
4050 // what reaches `append` reaches the DOM.
4051 function onChat(msg) {
4052 // Validated before anything is built: a malformed message is not a
4053 // reason to put a panel on the screen.
4054 const text = msg.payload && msg.payload.text;
4055 if (typeof text !== 'string' || !text) return;
4056 const panel = mountChat();
4057 if (!panel) return;
4058 chatReceived += 1;
4059 panel.append({
4060 from: msg.from || '',
4061 name: msg.name || '',
4062 text,
4063 at: Date.now(),
4064 self: false,
4065 });
4066 }
4067
4068 // onShare is the label arriving ahead of the media, or the removal
4069 // arriving ahead of the track's own `ended` — §5.4 says whichever
4070 // comes first wins, and both endings meet in dropShare.
4071 function onShare(msg) {
4072 const from = msg.from;
4073 const entry = from ? pcs.get(from) : null;
4074 if (!entry) return;
4075 const on = !!(msg.payload && msg.payload.on === true);
4076 if (!on) {
4077 dropShare(entry);
4078 return;
4079 }
4080 entry.sharing = true;
4081 renderTiles();
4082 }
4083
4084 // shareKey is the tile key a peer's screen gets: the peer's own key
4085 // with a suffix that no peer id can carry, so one peer holds two
4086 // tiles and every map keyed by tile key — `tiles`, `frames` — keeps
4087 // them apart without a second structure.
4088 function shareKey(id) {
4089 return id + SHARE_SUFFIX;
4090 }
4091
4092 // classifyTrack tells a peer's screen from its camera, which is the
4093 // one judgement §5.4's receiving half turns on. Pure, and lifted by
4094 // name in the node test.
4095 //
4096 // known what this connection has recorded: cameraMid, cameraStream,
4097 // peerStream, sharing
4098 // info the arriving track: {kind, streamId, mid, direction},
4099 // direction being the transceiver's currentDirection
4100 // self this tab: {hasVideo}, a live local video track
4101 //
4102 // "The first video track is the camera" is the rule this started as,
4103 // and it is wrong for one sender that really exists: the audio-only
4104 // rung of startLocal. A peer whose camera was in use or absent has no
4105 // camera m-line at all, so its *screen* is the first video track its
4106 // peers ever see, and the rule would caption it as a face.
4107 //
4108 // So four signals, strongest first.
4109 //
4110 // 1. The transceiver's direction. This connection builds a video
4111 // m-line of its own — sendrecv when it is sending a camera,
4112 // recvonly when it has none to send — so a video track arriving
4113 // `recvonly` on a connection that *is* sending a camera is a track
4114 // on an m-line the far side added, and the only m-line it adds is
4115 // the screen.
4116 // 2. The camera's own mid, once one is known. Assigned once, and it
4117 // survives every renegotiation and ICE restart.
4118 // 3. The camera's stream id, for a browser that reports no mid.
4119 // 4. The stream everything else from this peer has arrived in. A
4120 // sender puts its camera and its microphone in one MediaStream and
4121 // its screen in another, so a video track in a *different* stream
4122 // from the peer's audio is the screen even when no camera has ever
4123 // arrived — which is the audio-only sharer above.
4124 //
4125 // And, when none of the four can speak — a peer that has sent nothing
4126 // else at all — `sharing`, the `share {on:true}` message, breaks the
4127 // tie. It is last on purpose: it says this peer is showing a screen
4128 // somewhere, not that *this* track is it.
4129 //
4130 // One hole is left, and it is left knowingly. A peer that joined with
4131 // no camera *and* no microphone — startLocal's bottom rung, where
4132 // getUserMedia gave nothing at all — has sent this connection nothing
4133 // before its screen, so there is no camera mid, no camera stream and
4134 // no peer stream, and if this tab has no camera either the direction
4135 // says nothing. Everything then rests on the `share` message, which is
4136 // sent before the track and is what the tiebreaker reads. If that
4137 // message were ever lost, that peer's screen would be captioned as its
4138 // face. Nothing in §4.3 loses it — a fan-out message is delivered to
4139 // an admitted peer or the sender is told it failed — so the hole is a
4140 // consequence of the wire, not of this judgement.
4141 function classifyTrack(known, info, self) {
4142 if (info.kind !== 'video') return 'audio';
4143 if (info.direction === 'recvonly' && self.hasVideo) return 'share';
4144 if (known.cameraMid && info.mid) return info.mid === known.cameraMid ? 'camera' : 'share';
4145 if (known.cameraStream && info.streamId) {
4146 return info.streamId === known.cameraStream ? 'camera' : 'share';
4147 }
4148 if (known.peerStream && info.streamId) {
4149 return info.streamId === known.peerStream ? 'camera' : 'share';
4150 }
4151 if (!known.cameraMid && !known.cameraStream) return known.sharing ? 'share' : 'camera';
4152 // A camera is known but there is nothing on this track to compare
4153 // with it: a second video track is the screen.
4154 return 'share';
4155 }
4156
4157 // onRemoteTrack is the `track` handler's whole body. A camera track
4158 // goes on the peer's own tile, exactly as it always did; a screen
4159 // goes on a tile of its own and leaves the camera alone.
4160 function onRemoteTrack(id, entry, ev) {
4161 const track = ev.track;
4162 const stream = (ev.streams && ev.streams.length && ev.streams[0]) || null;
4163 const mid = (ev.transceiver && ev.transceiver.mid) || '';
4164 const tx = ev.transceiver;
4165 const what = classifyTrack(entry, {
4166 kind: track.kind,
4167 streamId: (stream && stream.id) || '',
4168 mid,
4169 // currentDirection is the negotiated one and the one to believe —
4170 // but it is null until an *answer* has been applied, so on the
4171 // side that answers an offer it says nothing at all, which is
4172 // exactly the side a screen arrives at. `direction` is what the
4173 // browser set when it built the transceiver, and a transceiver
4174 // built by setRemoteDescription for an m-line the far side added
4175 // is recvonly. Falling back to it is what makes the rule work in
4176 // both roles.
4177 direction: (tx && (tx.currentDirection || tx.direction)) || '',
4178 }, { hasVideo: !!entry.sentVideo });
4179 if (what === 'share') {
4180 entry.sharing = true;
4181 entry.shareMid = mid || entry.shareMid;
4182 // The stream a tile shows is this file's own, kept for the life
4183 // of the entry, and what goes in it is decided here (Codex S4-9).
4184 // A remote stream is a thing the far side composes: it can carry
4185 // the old track and the new one at once, in whatever order, and
4186 // binding a tile to "its first video track" then shows whichever
4187 // happens to be first. So the role owns a stream, the role's
4188 // authoritative track goes in it, and nothing else of that kind
4189 // stays behind.
4190 const held = (entry.share && entry.share.stream) || new MediaStream();
4191 entry.share = { stream: held, track };
4192 entry.shareTrack = track;
4193 adoptTrack(held, track);
4194 // §5.4's first ending: the sender stopped the transceiver, so
4195 // this track ends rather than freezing. The listener is dropped
4196 // with the connection, and dropShare is idempotent, so the `share
4197 // {on:false}` that usually arrives alongside it costs nothing.
4198 //
4199 // Only for the screen that is still showing, though (Codex
4200 // S4-15). A screen can be *replaced* on its own mid — the far
4201 // side rebuilding it, or a rollback doing it for them — and the
4202 // predecessor ends afterwards, as a superseded track does. Its
4203 // listener is still on the connection, and without this it took
4204 // the live replacement's tile away with it.
4205 track.addEventListener('ended', () => {
4206 if (pcs.get(id) !== entry) return;
4207 if (!entry.share || entry.share.track !== track) return;
4208 dropShare(entry);
4209 });
4210 renderTiles();
4211 return;
4212 }
4213 if (what === 'camera') {
4214 // Recorded from the first video track and never revised: this is
4215 // what every later video track is judged against.
4216 if (mid) entry.cameraMid = mid;
4217 if (stream) entry.cameraStream = stream.id;
4218 // The authoritative camera track, which is what the tile binds
4219 // to. A replacement arriving on the same mid supersedes its
4220 // predecessor whether or not the predecessor has ended.
4221 entry.cameraTrack = track;
4222 }
4223 // Recorded from the first track of any kind, camera or microphone:
4224 // it is what places a video track for a peer that has no camera.
4225 if (stream && !entry.peerStream) entry.peerStream = stream.id;
4226 // This tile's own stream, again: the remote one is only ever read
4227 // for its id. Audio and video are kept apart by `adoptTrack`, so a
4228 // camera replacing a camera leaves the microphone alone.
4229 entry.stream = entry.stream || new MediaStream();
4230 adoptTrack(entry.stream, track);
4231 renderTiles();
4232 }
4233
4234 // adoptTrack makes one arriving track *the* track of its kind in the
4235 // stream a tile shows: every other track of that kind comes out,
4236 // whatever its readyState, and this one goes in. Pure enough to lift
4237 // by name, and gated in the node test.
4238 //
4239 // This is the receiving half of the rollback damage, and its first
4240 // draft got the rule wrong (Codex S4-9). Chromium rebuilds every
4241 // stream on a connection when it rolls back an offer that added an
4242 // m-line — receive streams included — so the far side's camera
4243 // arrives again as a *new* track, sometimes with no stream of its own
4244 // and sometimes inside the very stream that still holds the old one.
4245 // The old one is not necessarily `ended`: a receiver can be
4246 // superseded while its track is still live and simply never carries
4247 // another frame. Pruning only ended tracks therefore left the stream
4248 // holding [old, new], and a media element renders the first track of
4249 // its kind — a face that never moves again on a connection that is
4250 // otherwise perfect: connected, stable, sendrecv, and decoding
4251 // hundreds of frames nobody can see.
4252 //
4253 // Which track is authoritative is `onRemoteTrack`'s judgement, not
4254 // this function's: classifyTrack has already said whether this is the
4255 // camera or the screen, and each role owns a stream of its own. So
4256 // there is no ordering question left here, and none of "is the old
4257 // one finished with" either. Audio is a kind of its own and is
4258 // untouched by a video track arriving.
4259 function adoptTrack(stream, track) {
4260 if (!stream || !track) return stream;
4261 for (const old of stream.getTracks()) {
4262 if (old !== track && old.kind === track.kind) stream.removeTrack(old);
4263 }
4264 if (!stream.getTracks().includes(track)) stream.addTrack(track);
4265 return stream;
4266 }
4267
4268 // shownTrack is the video track a tile is actually rendering: the
4269 // first one in the stream. The tile follows it, not just the stream
4270 // object, because the two can change independently.
4271 function shownTrack(stream) {
4272 if (!stream || !stream.getVideoTracks) return null;
4273 return stream.getVideoTracks()[0] || null;
4274 }
4275
4276 // dropShare removes one peer's screen, from either ending. The frame
4277 // count is deliberately left behind: it says the screen was really
4278 // arriving before it went away, which is exactly what a gate watching
4279 // a stop needs to be able to see afterwards.
4280 function dropShare(entry) {
4281 if (!entry.sharing && !entry.share) return;
4282 entry.sharing = false;
4283 entry.share = null;
4284 entry.shareMid = '';
4285 renderTiles();
4286 }
4287
4288 // hasShare: this peer holds a share tile. The message alone is enough
4289 // — it beats the media by a renegotiation — so the tile can carry the
4290 // label before there is anything to show in it.
4291 function hasShare(entry) {
4292 return !!(entry.sharing || entry.share);
4293 }
4294
4295 function shareCaption(name) {
4296 return name + '’s screen';
4297 }
4298
4299 // startSharing is the button's on half. The capture is asked for
4300 // first: a person who changes their mind at the browser's own picker
4301 // has shared nothing, and nothing should have been announced.
4302 async function startSharing() {
4303 if (share || sharePending || state.stopped || !HAS_DISPLAY_MEDIA) return;
4304 // The picker is open for as long as a person takes to answer it, and
4305 // the button is live the whole time. Without this a second click
4306 // starts a second capture: the peers would be watching the first,
4307 // `share` would point at the second, and Off would stop only the one
4308 // nobody could see — leaving a screen being sent that this tab no
4309 // longer believes in.
4310 sharePending = true;
4311 let stream;
4312 try {
4313 stream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: false });
4314 } catch {
4315 // Refused at the picker, or not permitted by policy. One
4316 // sentence, and no diagnosis of which.
4317 say(SHARE_REFUSED);
4318 return;
4319 } finally {
4320 sharePending = false;
4321 }
4322 const track = stream.getVideoTracks()[0];
4323 // Read again on this side of the await: a capture that arrives after
4324 // the call ended, or after some other path started one, is a capture
4325 // nothing will ever stop unless it is stopped here.
4326 if (!track || share || state.stopped) {
4327 stopStream(stream);
4328 return;
4329 }
4330 share = { stream, track };
4331 try {
4332 track.contentHint = sharePlan(shareMode()).contentHint;
4333 } catch {
4334 // A browser without contentHint: the sender's degradation
4335 // preference below says the same thing.
4336 }
4337 // The browser's own "Stop sharing" bar ends the track without
4338 // telling this file anything else. §5.4 gives it the same ending as
4339 // the button.
4340 track.addEventListener('ended', () => stopSharing());
4341 for (const entry of pcs.values()) addShareTo(entry);
4342 renderShare();
4343 // The label, not the media: peers use it to draw the tile before
4344 // the renegotiation lands, and the track carries no name of its own.
4345 broadcast('share', { on: true });
4346 }
4347
4348 // addShareTo gives one connection the display track on a transceiver
4349 // of its own. `sendonly` and a stream of its own is what keeps it
4350 // clear of the camera at the far end, and adding it fires
4351 // `negotiationneeded`, so §5.1's perfect negotiation carries the
4352 // offer with no help from here.
4353 function addShareTo(entry) {
4354 if (!share || !entry || entry.shareTx) return;
4355 // Only on a stable connection. A transceiver added mid-negotiation
4356 // is unassociated when the far side's offer arrives, and m-line
4357 // matching will hand it that offer's m-line — so two peers sharing
4358 // at the same moment end up with each one's screen in the place the
4359 // other built for its own. The connection's own signalingstatechange
4360 // brings this back the moment it settles, which is where every
4361 // deferred one is added.
4362 if (entry.pc.signalingState !== 'stable') return;
4363 try {
4364 entry.shareTx = entry.pc.addTransceiver(share.track, {
4365 direction: 'sendonly',
4366 streams: [share.stream],
4367 });
4368 tuneShare(entry);
4369 } catch {
4370 // A browser without addTransceiver, or a connection already
4371 // closing: that peer simply never sees this screen, and the call
4372 // carries on.
4373 }
4374 }
4375
4376 // stopSharing is the off half, and every way out uses it: the button,
4377 // the browser's own stop bar, and the end of the call.
4378 function stopSharing() {
4379 if (!share) return;
4380 const held = share;
4381 share = null;
4382 for (const entry of pcs.values()) removeShareFrom(entry);
4383 renderShare();
4384 broadcast('share', { on: false });
4385 // Last, so the transceivers are stopped and the message is queued
4386 // before the capture goes: stopping the track first would fire its
4387 // own `ended` into a path that has already run.
4388 stopStream(held.stream);
4389 }
4390
4391 // stopStream ends a capture, whether it was ever used or not.
4392 function stopStream(stream) {
4393 if (!stream) return;
4394 for (const t of stream.getTracks()) {
4395 try {
4396 t.stop();
4397 } catch {
4398 // Already stopped.
4399 }
4400 }
4401 }
4402
4403 // removeShareFrom ends one connection's share m-line. `stop()` is
4404 // §5.4's own instruction and the only one that makes the receiver's
4405 // track *end*; the fallback is for a browser whose transceivers
4406 // cannot be stopped, where nulling the sender and removing it at
4407 // least stops the media and renegotiates.
4408 //
4409 // Only ever this connection's own share transceiver, which fix round 2
4410 // pins with a test: a camera that stopped encoding was that round's
4411 // whole hunt, and `removeTrack` on the wrong sender is one of the two
4412 // ways this file could have done that to itself.
4413 function removeShareFrom(entry) {
4414 const tx = entry.shareTx;
4415 if (!tx) return;
4416 entry.shareTx = null;
4417 tuneShare(entry);
4418 try {
4419 if (typeof tx.stop === 'function') {
4420 tx.stop();
4421 return;
4422 }
4423 } catch {
4424 // Fall through to the older way.
4425 }
4426 try {
4427 const sender = tx.sender;
4428 if (!sender) return;
4429 if (typeof sender.replaceTrack === 'function') {
4430 const replaced = sender.replaceTrack(null);
4431 if (replaced && typeof replaced.catch === 'function') replaced.catch(() => {});
4432 }
4433 entry.pc.removeTrack(sender);
4434 } catch {
4435 // A connection that is closing: there is nothing left to remove.
4436 }
4437 }
4438
4439 // renderShare moves the button's state three ways and never by
4440 // colour, exactly as the other two toggles do: aria-pressed, the word
4441 // in the button, and calls.css's inset outline.
4442 function renderShare() {
4443 if (!shareButton) return;
4444 shareButton.setAttribute('aria-pressed', String(!!share));
4445 if (shareState) shareState.textContent = share ? 'On' : 'Off';
4446 if (shareNotice) shareNotice.hidden = !share;
4447 if (shareRecoveryEl) {
4448 const text = share ? shareRecovery : '';
4449 shareRecoveryEl.textContent = text;
4450 shareRecoveryEl.hidden = !text;
4451 }
4452 }
4453
4454 // sharingPeers: the peers holding a share tile, for the gate.
4455 function sharingPeers() {
4456 const out = [];
4457 for (const [id, entry] of pcs) if (hasShare(entry)) out.push(id);
4458 return out;
4459 }
4460
4461 // ---------------------------------------------------------------
4462 // Media state (§15.19): who is muted, whose camera is off
4463 // ---------------------------------------------------------------
4464 //
4465 // State, not an event. The hub keeps each peer's last report and puts
4466 // it in every roster, so what a tile shows is always the roster's word
4467 // or a `media` since; nothing here is replayed or reconstructed. A
4468 // peer that never reports — a client from before this — is unknown,
4469 // and unknown is drawn as neither muted nor camera-off.
4470
4471 // mediaFrom accepts the two booleans and nothing looser, for a roster
4472 // entry or a `media` payload alike: either is missing or not a
4473 // boolean, and the whole report is unknown. §15.20's two optional keys
4474 // are read more forgivingly, because they are news about hearing and
4475 // not about who is muted: an `audioBlocked` that is not exactly true,
4476 // or a `noSoundFrom` entry that is not a peer id, is dropped on its
4477 // own and the rest of the report stands. Pure, and lifted by name in
4478 // the node test.
4479 function mediaFrom(value) {
4480 if (!value || typeof value !== 'object') return null;
4481 if (typeof value.muted !== 'boolean' || typeof value.cameraOff !== 'boolean') return null;
4482 const out = { muted: value.muted, cameraOff: value.cameraOff };
4483 if (value.audioBlocked === true) out.audioBlocked = true;
4484 if (Array.isArray(value.noSoundFrom)) {
4485 const ids = [];
4486 for (const id of value.noSoundFrom) {
4487 if (ids.length >= 15) break;
4488 if (typeof id === 'string' && /^[0-9a-f]{32}$/.test(id) && !ids.includes(id)) ids.push(id);
4489 }
4490 if (ids.length) out.noSoundFrom = ids;
4491 }
4492 if (Array.isArray(value.screenStalled)) {
4493 const ids = [];
4494 for (const id of value.screenStalled) {
4495 if (ids.length >= 15) break;
4496 if (typeof id === 'string' && /^[0-9a-f]{32}$/.test(id) && !ids.includes(id)) ids.push(id);
4497 }
4498 if (ids.length) out.screenStalled = ids;
4499 }
4500 // §15.24: kept even when empty — [] is "I hear nobody yet", where an
4501 // absent list is a client that does not say.
4502 if (Array.isArray(value.hearing)) {
4503 const ids = [];
4504 for (const id of value.hearing) {
4505 if (ids.length >= 15) break;
4506 if (typeof id === 'string' && /^[0-9a-f]{32}$/.test(id) && !ids.includes(id)) ids.push(id);
4507 }
4508 out.hearing = ids;
4509 }
4510 // §15.30: what they ask each sender for, the wire's levels only.
4511 if (value.video && typeof value.video === 'object' && !Array.isArray(value.video)) {
4512 const asks = {};
4513 let n = 0;
4514 for (const [id, level] of Object.entries(value.video)) {
4515 if (n >= 15) break;
4516 if (/^[0-9a-f]{32}$/.test(id) && ['reduced', 'minimal', 'audio'].includes(level)) {
4517 asks[id] = level;
4518 n += 1;
4519 }
4520 }
4521 if (n) out.video = asks;
4522 }
4523 return out;
4524 }
4525
4526 function sameMedia(a, b) {
4527 return !!a && !!b && mediaKey(a) === mediaKey(b);
4528 }
4529
4530 // mediaKey is one string per distinct report, the optional keys
4531 // included, so a change in what this tab can hear is a change that is
4532 // sent. The list is sorted here: the same peers in another order are
4533 // the same report.
4534 function mediaKey(m) {
4535 let key = (m.muted ? 'm' : '-') + (m.cameraOff ? 'c' : '-');
4536 if (m.audioBlocked) key += 'b';
4537 if (m.noSoundFrom && m.noSoundFrom.length) key += ':' + m.noSoundFrom.slice().sort().join(',');
4538 if (m.screenStalled && m.screenStalled.length) key += '/' + m.screenStalled.slice().sort().join(',');
4539 if (Array.isArray(m.hearing)) key += '|' + m.hearing.slice().sort().join(',');
4540 if (m.video && Object.keys(m.video).length) {
4541 key += '>' + Object.keys(m.video).sort().map((id) => id + '=' + m.video[id]).join(',');
4542 }
4543 return key;
4544 }
4545
4546 // localMedia is what this tab is actually sending. No microphone at
4547 // all is muted as far as anyone listening can tell, and no camera is
4548 // off; the preference alone would claim a microphone that is not there.
4549 function localMedia() {
4550 const hasAudio = !!(local && local.getAudioTracks().length);
4551 const hasVideo = !!(local && local.getVideoTracks().length);
4552 // §15.30: Audio only stops the camera going to anyone, so it is off as
4553 // far as anyone watching can tell.
4554 return { muted: !!prefs.muted || !hasAudio, cameraOff: !!prefs.cameraOff || !hasVideo || videoSetting() === 'audio' };
4555 }
4556
4557 // mediaPayload is the report itself: §15.19's two booleans, and
4558 // §15.20's two keys only when they carry bad news. §15.24's `hearing`
4559 // is the exception, and travels whenever it is given, [] included: it
4560 // is good news, and its presence tells the others this tab says who it
4561 // hears. `plain` is a server that has refused the extras once. Pure,
4562 // and lifted by name in the node test.
4563 function mediaPayload(mine, blocked, silentFrom, plain, stalled, heard, asks) {
4564 const out = { muted: !!mine.muted, cameraOff: !!mine.cameraOff };
4565 if (plain) return out;
4566 if (blocked) out.audioBlocked = true;
4567 if (silentFrom && silentFrom.length) out.noSoundFrom = silentFrom.slice(0, 15);
4568 // §15.21: whose screens have stalled here, bad news only, like the rest.
4569 if (stalled && stalled.length) out.screenStalled = stalled.slice(0, 15);
4570 if (Array.isArray(heard)) out.hearing = heard.slice(0, 15);
4571 // §15.30: what this tab asks each sender for, only those below normal.
4572 if (asks && Object.keys(asks).length) out.video = Object.assign({}, asks);
4573 return out;
4574 }
4575
4576 // reportMedia puts our state on the broadcast lane, once per change,
4577 // and only once admitted: before that the hub refuses it, and the
4578 // roster that admits us is where it is sent from. A refusal forgets
4579 // what was sent, so the next toggle or roster tries again — which
4580 // against a server from before §15.19 is a quiet 400 each time.
4581 //
4582 // A 400 for a report that carried §15.20's keys is a server from
4583 // between the two, and the answer is to stop sending them and say the
4584 // two booleans at once, for the rest of this page's life: being heard
4585 // as muted or not matters more than being heard as unable to hear.
4586 function reportMedia() {
4587 if (!state.admitted || state.stopped || !state.peer) return;
4588 const now = mediaPayload(localMedia(), audioBlocked, noSoundList(), !mediaExtras, screenStalled, hearingList(), videoAsks);
4589 const key = mediaKey(now);
4590 if (key === mediaSent) return;
4591 mediaSent = key;
4592 const extras = key !== mediaKey(mediaPayload(now, false, null, true));
4593 let fallBack = false;
4594 broadcast('media', now, (status) => {
4595 if (status === 400 && extras && mediaExtras) {
4596 mediaExtras = false;
4597 fallBack = true;
4598 }
4599 }).then((ok) => {
4600 if (!ok && mediaSent === key) mediaSent = '';
4601 if (fallBack) reportMedia();
4602 });
4603 }
4604
4605 // rosterMedia takes a roster's word on everybody's media. On ours as
4606 // well: missing is a participation the hub has never heard from — a
4607 // fresh join, or a restart — and different is a report lost while the
4608 // stream was down, and either way it is told again.
4609 function rosterMedia(roster) {
4610 for (const rp of roster.peers || []) {
4611 if (!rp || !rp.peer) continue;
4612 if (rp.peer !== state.peer) {
4613 // §15.28: and what their participation was opened from.
4614 clients.set(rp.peer, rp.client || '');
4615 learnMedia(rp.peer, rp.media);
4616 continue;
4617 }
4618 const now = mediaPayload(localMedia(), audioBlocked, noSoundList(), !mediaExtras, screenStalled, hearingList(), videoAsks);
4619 mediaSent = sameMedia(mediaFrom(rp.media), now) ? mediaKey(now) : '';
4620 }
4621 reportMedia();
4622 // §15.30: and what each of them asks of us now.
4623 answerVideoAsks();
4624 for (const id of pcs.keys()) markAdapt(id);
4625 }
4626
4627 // learnMedia records a roster's or a peer event's word on one peer.
4628 // Absent is unknown, and forgets anything older: the roster is the
4629 // authority, and a participation that has not reported has not.
4630 function learnMedia(id, value) {
4631 const m = mediaFrom(value);
4632 if (m) remoteMedia.set(id, m);
4633 else remoteMedia.delete(id);
4634 }
4635
4636 // onMedia is one peer's change. Only a peer we hold a connection to
4637 // is drawn; the roster will carry the rest.
4638 function onMedia(msg) {
4639 const id = msg.from;
4640 const next = mediaFrom(msg.payload);
4641 if (!id || id === state.peer || !next) return;
4642 const before = remoteMedia.get(id) || null;
4643 remoteMedia.set(id, next);
4644 announceMedia(mediaChange(msg.name || names.get(id) || 'Someone', before, next));
4645 markTile(id, next);
4646 answerScreenStalls();
4647 answerVideoAsks();
4648 markAdapt(id);
4649 }
4650
4651 // ---------------------------------------------------------------
4652 // Adaptive video (§15.30, 2026-10-28)
4653 // ---------------------------------------------------------------
4654 //
4655 // Paul, after a Dublin–London call whose guest was on café Wi-Fi in
4656 // Safari, relayed, at 840–1300 ms round trips, seeing up to seven
4657 // freezes every thirty seconds in his video: "Low-bandwidth with
4658 // auto-switching up and down." Audio mattered most.
4659 //
4660 // It is a mesh, so every pair has its own sender, and the one who can
4661 // see the trouble is the receiver. So each receiver watches what arrives
4662 // from each sender — camera freezes, packet loss, the jitter buffer, the
4663 // round trip, frames dropped — and asks that sender for a level in its
4664 // own media report (`video`, peer id -> level, only the ones below
4665 // normal). The sender reads its own id in each report and sets that one
4666 // connection's sender parameters: no renegotiation, and audio is never
4667 // touched. A shared screen keeps its size and gives up frame rate first,
4668 // and is never paused; while one is going, the camera gives way first.
4669
4670 // adaptRecord is one sender's watch, on the receiving side. `upAfter` is
4671 // the clean time before the first probe up (ADAPT_UP_AFTER, shortened
4672 // only by the gate's hook). Pure, as is everything down to adaptAsks;
4673 // test/browser/room-adapt.test.mjs lifts them by name.
4674 function adaptRecord(upAfter) {
4675 const base = upAfter || ADAPT_UP_AFTER;
4676 return { level: 0, since: null, samples: [], cleanSince: null, upBase: base, upWait: base,
4677 probeAt: null, probeFrom: 0, downs: 0, ups: 0 };
4678 }
4679
4680 // adaptSample is one second of what arrived from a sender, from
4681 // qualityPeer's deltas: camera freezes (only while the camera is to be
4682 // watched — on, and the tab visible — because a still screen's gaps and
4683 // a hidden tab's unpainted frames are not freezes), packets and loss
4684 // across audio, camera and screen, the round trip, the audio jitter
4685 // buffer, and frames decoded and dropped. Null when nothing at all
4686 // arrived and nothing was measured: a connection that is down is
4687 // §15.28's to mend, and says nothing about the link's width.
4688 //
4689 // `keyframeAsks` is the PLIs and FIRs this side sent for their camera in
4690 // the second: a decoder that keeps losing its picture asks for a new one,
4691 // and on a thin link that, not a freeze, can be all there is to see — a
4692 // picture at five frames a second, every one a keyframe.
4693 function adaptSample(q, cameraWatched, keyframeAsks) {
4694 const inb = (q && q.in) || {};
4695 const a = inb.audio || {};
4696 const v = inb.video || {};
4697 const s = inb.screen || {};
4698 const packets = (a.packets || 0) + (v.packets || 0) + (s.packets || 0);
4699 const lost = (a.lost || 0) + (v.lost || 0) + (s.lost || 0);
4700 const rtt = q && typeof q.rtt === 'number' ? q.rtt : null;
4701 if (packets + lost === 0 && rtt === null) return null;
4702 return {
4703 freezes: cameraWatched ? v.freezes || 0 : 0,
4704 freezeSeconds: cameraWatched ? v.freezeSeconds || 0 : 0,
4705 keyframeAsks: cameraWatched ? keyframeAsks || 0 : 0,
4706 packets,
4707 lost,
4708 rtt,
4709 jitterBufferMs: typeof a.jitterBufferMs === 'number' ? a.jitterBufferMs : null,
4710 decoded: (v.decoded || 0) + (s.decoded || 0),
4711 dropped: (v.dropped || 0) + (s.dropped || 0),
4712 };
4713 }
4714
4715 // adaptWindow sums the samples in the window: counts added up, the
4716 // round trip as their median (one spike is not a slow link), the jitter
4717 // buffer as their mean.
4718 function adaptWindow(samples) {
4719 const w = { freezes: 0, freezeSeconds: 0, keyframeAsks: 0, loadSeconds: 0, packets: 0, lost: 0, decoded: 0, dropped: 0, rtt: null, jitterBuffer: null };
4720 const rtts = [];
4721 const jbs = [];
4722 for (const x of samples) {
4723 w.freezes += x.freezes;
4724 w.freezeSeconds += x.freezeSeconds;
4725 w.keyframeAsks += x.keyframeAsks || 0;
4726 if (x.load) w.loadSeconds += 1;
4727 w.packets += x.packets;
4728 w.lost += x.lost;
4729 w.decoded += x.decoded;
4730 w.dropped += x.dropped;
4731 if (x.rtt !== null) rtts.push(x.rtt);
4732 if (x.jitterBufferMs !== null) jbs.push(x.jitterBufferMs);
4733 }
4734 if (rtts.length) {
4735 rtts.sort((p, q) => p - q);
4736 w.rtt = rtts[Math.floor(rtts.length / 2)];
4737 }
4738 if (jbs.length) w.jitterBuffer = jbs.reduce((p, q) => p + q, 0) / jbs.length;
4739 w.loss = w.packets + w.lost > 0 ? w.lost / (w.packets + w.lost) : 0;
4740 return w;
4741 }
4742
4743 // adaptTrouble is a window's verdict: 'severe', 'trouble' or ''.
4744 function adaptTrouble(w) {
4745 if (w.freezes >= ADAPT_SEVERE_FREEZES || w.freezeSeconds >= ADAPT_SEVERE_FREEZE_SECONDS ||
4746 w.loss > ADAPT_SEVERE_LOSS) {
4747 return 'severe';
4748 }
4749 if (w.freezes >= ADAPT_DOWN_FREEZES || w.freezeSeconds >= ADAPT_DOWN_FREEZE_SECONDS || w.loss > ADAPT_DOWN_LOSS ||
4750 w.keyframeAsks >= ADAPT_DOWN_KEYFRAME_ASKS || w.loadSeconds >= ADAPT_DOWN_LOAD_SECONDS ||
4751 (w.rtt !== null && w.rtt >= ADAPT_DOWN_RTT && w.freezes >= 1) ||
4752 (w.jitterBuffer !== null && w.jitterBuffer >= ADAPT_DOWN_JITTER_BUFFER) ||
4753 (w.dropped >= ADAPT_DOWN_DROPPED_MIN && w.dropped >= ADAPT_DOWN_DROPPED * (w.decoded + w.dropped))) {
4754 return 'trouble';
4755 }
4756 return '';
4757 }
4758
4759 // adaptWhy names what made a window trouble, for the console and the
4760 // diagnostics: the first rule it broke.
4761 function adaptWhy(w) {
4762 if (w.freezes >= ADAPT_DOWN_FREEZES) return w.freezes + ' freezes';
4763 if (w.freezeSeconds >= ADAPT_DOWN_FREEZE_SECONDS) return w.freezeSeconds + ' s frozen';
4764 if (w.loss > ADAPT_DOWN_LOSS) return Math.round(w.loss * 100) + '% loss';
4765 if (w.keyframeAsks >= ADAPT_DOWN_KEYFRAME_ASKS) return w.keyframeAsks + ' keyframe asks';
4766 if (w.loadSeconds >= ADAPT_DOWN_LOAD_SECONDS) return 'this device struggling ' + w.loadSeconds + ' s';
4767 if (w.rtt !== null && w.rtt >= ADAPT_DOWN_RTT && w.freezes >= 1) return w.rtt + ' ms round trip with a freeze';
4768 if (w.jitterBuffer !== null && w.jitterBuffer >= ADAPT_DOWN_JITTER_BUFFER) return Math.round(w.jitterBuffer) + ' ms jitter buffer';
4769 return w.dropped + ' of ' + (w.decoded + w.dropped) + ' frames dropped';
4770 }
4771
4772 // loadSample is one second of this device's own load, for the sender's
4773 // watch of itself: nothing about a link, only whether it struggled.
4774 function loadSample(struggling) {
4775 return { freezes: 0, freezeSeconds: 0, keyframeAsks: 0, load: !!struggling, packets: 0, lost: 0, rtt: null,
4776 jitterBufferMs: null, decoded: 0, dropped: 0 };
4777 }
4778
4779 // adaptClean is whether one second was clean, for the slow way up.
4780 function adaptClean(x) {
4781 const n = x.packets + x.lost;
4782 return x.freezes === 0 && x.freezeSeconds === 0 && !x.keyframeAsks && !x.load && (n === 0 || x.lost / n <= ADAPT_CLEAN_LOSS) &&
4783 (x.rtt === null || x.rtt < ADAPT_CLEAN_RTT) &&
4784 (x.jitterBufferMs === null || x.jitterBufferMs < ADAPT_CLEAN_JITTER_BUFFER);
4785 }
4786
4787 // adaptMove changes the level, and starts the watch again from nothing:
4788 // the new level is judged on what it does, not on what the old one did.
4789 function adaptMove(rec, now, level, up) {
4790 if (up) rec.ups += 1;
4791 else rec.downs += 1;
4792 rec.level = level;
4793 rec.since = now;
4794 rec.samples = [];
4795 rec.cleanSince = null;
4796 if (!up) rec.probeAt = null;
4797 return level;
4798 }
4799
4800 // adaptStep is one look, about once a second, with that second's sample
4801 // (or null for none). Returns the level, 0 normal to 3 audio only.
4802 //
4803 // down one level once the window at this level has been trouble for
4804 // ADAPT_WINDOW; two at once for severe trouble, after
4805 // ADAPT_SEVERE_AFTER
4806 // up one level after `upWait` of clean seconds in a row, as a
4807 // probe: trouble within ADAPT_PROBE_WATCH of it (judged on at
4808 // least ADAPT_PROBE_JUDGE) steps straight back and doubles the
4809 // wait, to at most ADAPT_UP_MAX; a probe that holds puts the
4810 // wait back to its base
4811 function adaptStep(rec, now, sample) {
4812 if (rec.since === null) rec.since = now;
4813 if (!sample) return rec.level;
4814 rec.samples.push(Object.assign({ at: now }, sample));
4815 while (rec.samples.length && rec.samples[0].at <= now - ADAPT_WINDOW) rec.samples.shift();
4816 const observed = now - rec.since;
4817 const win = adaptWindow(rec.samples);
4818 const verdict = adaptTrouble(win);
4819 if (verdict) rec.why = adaptWhy(win);
4820 if (adaptClean(sample)) {
4821 if (rec.cleanSince === null) rec.cleanSince = now;
4822 } else {
4823 rec.cleanSince = null;
4824 }
4825 const top = ADAPT_LEVELS.length - 1;
4826 if (rec.probeAt !== null) {
4827 if (now - rec.probeAt < ADAPT_PROBE_WATCH) {
4828 if (verdict && observed >= ADAPT_PROBE_JUDGE) {
4829 rec.upWait = Math.min(rec.upWait * 2, ADAPT_UP_MAX);
4830 return adaptMove(rec, now, rec.probeFrom, false);
4831 }
4832 } else {
4833 rec.probeAt = null;
4834 rec.upWait = rec.upBase;
4835 }
4836 }
4837 if (verdict === 'severe' && observed >= ADAPT_SEVERE_AFTER && rec.level < top) {
4838 return adaptMove(rec, now, Math.min(top, rec.level + 2), false);
4839 }
4840 if (verdict && observed >= ADAPT_WINDOW && rec.level < top) {
4841 return adaptMove(rec, now, rec.level + 1, false);
4842 }
4843 if (rec.level > 0 && rec.cleanSince !== null && now - rec.cleanSince >= rec.upWait) {
4844 const from = rec.level;
4845 adaptMove(rec, now, from - 1, true);
4846 rec.probeAt = now;
4847 rec.probeFrom = from;
4848 }
4849 return rec.level;
4850 }
4851
4852 // videoFloor is the person's own setting as a level: Low bandwidth asks
4853 // everyone for minimal, Audio only for no video; Auto leaves it to the
4854 // watch.
4855 function videoFloor(setting) {
4856 if (setting === 'audio') return 3;
4857 if (setting === 'low') return 2;
4858 return 0;
4859 }
4860
4861 // adaptAsks is the `video` object for the report: every peer whose level
4862 // — the watch's or the setting's, whichever is lower — is below normal.
4863 // `levels` is peer id -> the watch's level.
4864 function adaptAsks(levels, setting) {
4865 const out = {};
4866 const floor = videoFloor(setting);
4867 for (const [id, level] of levels) {
4868 const at = Math.max(level || 0, floor);
4869 if (at > 0 && Object.keys(out).length < 15) out[id] = ADAPT_LEVELS[at];
4870 }
4871 return out;
4872 }
4873
4874 // askedOf is what one peer's report asks of us, as a level index.
4875 function askedOf(media, me) {
4876 const at = media && media.video && me ? ADAPT_LEVELS.indexOf(media.video[me]) : -1;
4877 return at > 0 ? at : 0;
4878 }
4879
4880 // cameraAtLevel is the camera's encoding for one receiver at a level.
4881 // While a screen is going out the camera gives way first: normal is
4882 // §5.4's cap beside the screen, and every level below is one lower for
4883 // the camera, so a receiver at minimal gets the screen and no camera.
4884 // `width` and `height` are the camera's own, fitted by their long and
4885 // short sides so a portrait camera is boxed the right way round.
4886 function cameraAtLevel(level, sharing, width, height) {
4887 const at = sharing && level > 0 ? Math.min(3, level + 1) : level;
4888 if (at <= 0) return Object.assign({ maxFramerate: undefined, active: true }, cameraCap(sharing, height || 0));
4889 const c = ADAPT_CAMERA[Math.min(at, 2)];
4890 const long = Math.max(width || 0, height || 0);
4891 const short = Math.min(width || 0, height || 0);
4892 return {
4893 maxBitrate: c.maxBitrate,
4894 maxFramerate: c.maxFramerate,
4895 scaleResolutionDownBy: Math.max(1, long / c.long, short / c.short),
4896 active: at < 3,
4897 };
4898 }
4899
4900 // screenAtLevel is sharePlan's answer for one receiver at a level: the
4901 // frame rate and bitrate lowered first, the size kept, and only at
4902 // minimal and below the long side brought to ADAPT_SCREEN's. Resolution
4903 // is held under pressure from then on (maintain-resolution), because a
4904 // screen is for reading. Never paused.
4905 function screenAtLevel(plan, level, width, height) {
4906 if (level <= 0) return plan;
4907 const c = ADAPT_SCREEN[Math.min(level, 2)];
4908 const encoding = Object.assign({}, plan.encoding, {
4909 maxFramerate: c.maxFramerate,
4910 maxBitrate: Math.min(plan.encoding.maxBitrate || c.maxBitrate, c.maxBitrate),
4911 });
4912 if (c.long) {
4913 const longest = Math.max(width || 0, height || 0);
4914 encoding.scaleResolutionDownBy = Math.max(plan.encoding.scaleResolutionDownBy || 1, longest > c.long ? longest / c.long : 1);
4915 }
4916 return { contentHint: plan.contentHint, degradationPreference: 'maintain-resolution', encoding };
4917 }
4918
4919 // honoursAsks is whether a peer's client acts on a request: every
4920 // browser (its page is this server's), and an app from
4921 // ADAPT_MIN_NATIVE_VERSION on.
4922 function honoursAsks(client) {
4923 const c = parseClient(client || '');
4924 if (!c) return !client;
4925 return compareVersions(c.version, ADAPT_MIN_NATIVE_VERSION) >= 0;
4926 }
4927
4928 // adaptNoticeWords is the sender's quiet notice for the people it is
4929 // sending less to, by name: '' for nobody.
4930 function adaptNoticeWords(people) {
4931 if (!people.length) return '';
4932 const names = people.map((p) => p.name);
4933 const list = names.length === 1 ? names[0]
4934 : names.slice(0, -1).join(', ') + ' and ' + names[names.length - 1];
4935 const weak = names.length === 1 ? '(their connection is weak)' : '(their connections are weak)';
4936 if (people.every((p) => p.level >= 3)) return 'Sending only audio to ' + list + ' ' + weak;
4937 return 'Sending reduced video to ' + list + ' ' + weak;
4938 }
4939
4940 // videoSetting is the person's choice, Auto unless they made one.
4941 function videoSetting() {
4942 return VIDEO_SETTINGS.some(([v]) => v === prefs.videoQuality) ? prefs.videoQuality : 'auto';
4943 }
4944
4945 // adaptLook is one connection's second, from the stats walk pollFrames
4946 // already makes and the reading §15.29's sampler takes of it
4947 // (entry.statsReading): the delta from the last one, by qualityPeer, and
4948 // a step of that sender's watch.
4949 function adaptLook(id, entry, stats, now) {
4950 const reading = entry.statsReading || qualityReading(stats, (r) => qualityKind(id, entry, r));
4951 const prev = entry.adaptReading;
4952 entry.adaptReading = { pc: entry.pc, reading, at: now, stats };
4953 if (!prev || prev.pc !== entry.pc || now <= prev.at) return;
4954 const q = qualityPeer(prev.reading, reading, (now - prev.at) / 1000);
4955 const asks = keyframeAsksFor(id, entry, prev.stats, stats);
4956 const media = remoteMedia.get(id) || null;
4957 const watched = !(media && media.cameraOff) && !(typeof document !== 'undefined' && document.hidden);
4958 // A renegotiation — a screen added or taken away, either side — costs
4959 // the camera a freeze or two that are not the link's: no news then.
4960 const settling = now < (entry.adaptSettleUntil || 0);
4961 let rec = adapt.get(id);
4962 if (!rec) {
4963 rec = adaptRecord(adaptUpAfter);
4964 adapt.set(id, rec);
4965 }
4966 const before = rec.level;
4967 adaptStep(rec, now, settling ? null : adaptSample(q, watched, asks));
4968 if (rec.level !== before) {
4969 console.info('calls: video from ' + id.slice(0, 6) + ' ' + ADAPT_LEVELS[before] + ' -> ' +
4970 ADAPT_LEVELS[rec.level] + (rec.level < before ? ' (probe)' : ' (' + (rec.why || '') + ')'));
4971 }
4972 }
4973
4974 // keyframeAsksFor is the PLIs and FIRs this side sent for one peer's
4975 // camera between two stats walks, by report id (a new stream counts from
4976 // nothing); the screen is not counted.
4977 function keyframeAsksFor(id, entry, before, after) {
4978 const count = (stats) => {
4979 const out = new Map();
4980 if (!stats || typeof stats.forEach !== 'function') return out;
4981 stats.forEach((r) => {
4982 if (r.type === 'inbound-rtp' && r.kind === 'video' && frameKey(id, entry, r.mid || '') === id) {
4983 out.set(r.id, (r.pliCount || 0) + (r.firCount || 0));
4984 }
4985 });
4986 return out;
4987 };
4988 const was = count(before);
4989 let n = 0;
4990 for (const [key, x] of count(after)) n += Math.max(0, x - (was.get(key) || 0));
4991 return n;
4992 }
4993
4994 // answerAdapt runs after each stats walk: the asks this tab makes, sent
4995 // when they change; the tiles' badges; and the seconds at each level,
4996 // asked and sent, for the next quality report.
4997 function answerAdapt(now, dt) {
4998 if (dt > 0) {
4999 const was = localAdapt.level;
5000 adaptStep(localAdapt, now, loadSample(PRESSURE_STATES.indexOf(pressure.forced || pressure.state) >= 2));
5001 if (localAdapt.level !== was) {
5002 console.info('calls: own camera ' + ADAPT_LEVELS[was] + ' -> ' + ADAPT_LEVELS[localAdapt.level] +
5003 ' (compute pressure ' + (pressure.forced || pressure.state || 'unknown') + ')');
5004 for (const entry of pcs.values()) tuneShare(entry);
5005 }
5006 }
5007 for (const id of Array.from(adapt.keys())) if (!pcs.has(id)) adapt.delete(id);
5008 const levels = new Map();
5009 for (const id of pcs.keys()) levels.set(id, adapt.has(id) ? adapt.get(id).level : 0);
5010 const asks = adaptAsks(levels, videoSetting());
5011 const changed = JSON.stringify(Object.entries(asks).sort()) !== JSON.stringify(Object.entries(videoAsks).sort());
5012 videoAsks = asks;
5013 if (changed) {
5014 reportMedia();
5015 for (const id of pcs.keys()) markAdapt(id);
5016 }
5017 const step = Math.min(Math.max(0, dt || 0), 2000) / 1000;
5018 for (const [id, entry] of pcs) {
5019 const asked = ADAPT_LEVELS.indexOf(asks[id] || 'normal');
5020 const sent = entry.sentLevel || 0;
5021 if (!step || (asked <= 0 && sent <= 0)) continue;
5022 let t = videoTime.get(id);
5023 if (!t) {
5024 t = { asked: [0, 0, 0], sent: [0, 0, 0] };
5025 videoTime.set(id, t);
5026 }
5027 if (asked > 0) t.asked[asked - 1] += step;
5028 if (sent > 0) t.sent[sent - 1] += step;
5029 }
5030 }
5031
5032 // answerVideoAsks is the sender's half: each connection's senders set
5033 // to what that peer last asked of us, and the notice when it changes.
5034 function answerVideoAsks() {
5035 let moved = false;
5036 for (const [id, entry] of pcs) {
5037 const level = askedOf(remoteMedia.get(id), state.peer);
5038 if ((entry.sentLevel || 0) === level) continue;
5039 console.info('calls: ' + id.slice(0, 6) + ' asks for ' + ADAPT_LEVELS[level] + ' video');
5040 if (level > (entry.sentLevel || 0)) moved = true;
5041 entry.sentLevel = level;
5042 tuneShare(entry);
5043 }
5044 const people = [];
5045 for (const [id, entry] of pcs) {
5046 if (entry.sentLevel > 0) people.push({ name: names.get(id) || 'Someone', level: entry.sentLevel });
5047 }
5048 const words = adaptNoticeWords(people);
5049 if (!words) {
5050 showAdaptNotice('');
5051 } else if (moved && words !== adaptNoticeShown) {
5052 showAdaptNotice(words);
5053 }
5054 }
5055
5056 // applyVideoSetting is the person's choice taking effect: what this tab
5057 // asks of everyone, its own camera to everyone, and its report.
5058 function applyVideoSetting() {
5059 console.info('calls: video quality ' + videoSetting());
5060 answerAdapt(Date.now(), 0);
5061 for (const entry of pcs.values()) tuneShare(entry);
5062 applyToggles();
5063 for (const id of pcs.keys()) markAdapt(id);
5064 }
5065
5066 // adaptWire is, for the gate, what one connection's last stats walk says
5067 // is on the wire: our camera going out to them (its size, rate, bytes and
5068 // whether the encoding is active) and their audio arriving here.
5069 function adaptWire(id, entry) {
5070 const out = { cameraHeight: 0, cameraFps: 0, cameraBytes: 0, audioPackets: 0, videoFreezes: 0 };
5071 const stats = entry.statsReport;
5072 if (!stats || typeof stats.forEach !== 'function') return out;
5073 stats.forEach((r) => {
5074 if (r.type === 'outbound-rtp' && r.kind === 'video' && !(entry.shareTx && entry.shareTx.mid && r.mid === entry.shareTx.mid)) {
5075 out.cameraHeight = r.frameHeight || 0;
5076 out.cameraFps = r.framesPerSecond || 0;
5077 out.cameraBytes += r.bytesSent || 0;
5078 if (typeof r.active === 'boolean') out.cameraActive = r.active;
5079 } else if (r.type === 'inbound-rtp' && r.kind === 'audio') {
5080 out.audioPackets += r.packetsReceived || 0;
5081 } else if (r.type === 'inbound-rtp' && r.kind === 'video' && qualityKind(id, entry, r) === 'video') {
5082 out.videoFreezes += r.freezeCount || 0;
5083 }
5084 });
5085 return out;
5086 }
5087
5088 // showAdaptNotice puts the sender's notice up for ADAPT_NOTICE_FOR, once
5089 // per change, and says it to a screen reader politely.
5090 function showAdaptNotice(words) {
5091 adaptNoticeShown = words;
5092 const el = $('video-notice');
5093 if (adaptNoticeTimer) clearTimeout(adaptNoticeTimer);
5094 adaptNoticeTimer = 0;
5095 if (!el) return;
5096 el.textContent = words;
5097 el.hidden = !words;
5098 if (!words) return;
5099 announceMedia(words);
5100 adaptNoticeTimer = setTimeout(() => {
5101 el.hidden = true;
5102 el.textContent = '';
5103 }, ADAPT_NOTICE_FOR);
5104 }
5105
5106 // markAdapt draws one tile's level: the badge in its caption while this
5107 // tab asks that person for less than normal, and, at audio only, the
5108 // cover over their picture — which also hides it here for an app too
5109 // old to send less.
5110 function markAdapt(id) {
5111 const t = tiles.get(id);
5112 if (!t || !t.lowBadge) return;
5113 const level = ADAPT_LEVELS.indexOf(videoAsks[id] || 'normal');
5114 const who = names.get(id) || 'them';
5115 const own = videoSetting() !== 'auto';
5116 t.lowBadge.hidden = level <= 0;
5117 t.lowBadge.title = level <= 0 ? '' : (own
5118 ? 'Asking ' + who + ' for less video, as your Video quality setting says'
5119 : 'Asking ' + who + ' for less video while your connection is weak');
5120 t.lowBadge.setAttribute('aria-label', level <= 0 ? '' : 'Low bandwidth: ' + t.lowBadge.title);
5121 const media = remoteMedia.get(id) || null;
5122 const paused = level >= 3 && !(media && media.cameraOff);
5123 t.videoPaused.hidden = !paused;
5124 if (t.videoPausedOld) t.videoPausedOld.hidden = !paused || honoursAsks(clients.get(id) || '');
5125 t.figure.classList.toggle('calls-tile-video-paused', paused);
5126 }
5127
5128 // ---------------------------------------------------------------
5129 // The screen watchdogs (§15.21, 2026-09-28)
5130 // ---------------------------------------------------------------
5131 //
5132 // Paul, on the Mac app: "after a while, my screen froze on her end and
5133 // she was no longer able to see my screen. I had to stop and re-share
5134 // again." The receiver can see that happening and the sharer cannot, so
5135 // the receiver says so and the sharer answers with a keyframe — the
5136 // part of a stop and a share again that a frozen picture is missing.
5137
5138 // judgeScreen is the receiver's verdict on one screen, from its decoded
5139 // count this poll: stalled, or not. `seen` is its record, updated here.
5140 // Pure over its arguments, and lifted by name in the node test.
5141 //
5142 // Any change in the count is movement, a smaller one included: a
5143 // screen the sharer has rebuilt arrives on a new receiver whose count
5144 // starts again, and up to 2026-09-30 only a larger count moved, so a
5145 // rebuilt screen that was playing again stayed "stalled" here — and the
5146 // sharer's notice with it — until the new count passed the old.
5147 function judgeScreen(seen, decoded, now, frozen) {
5148 if (!seen.movedAt || (decoded !== seen.decoded && !frozen)) {
5149 seen.decoded = decoded;
5150 seen.movedAt = now;
5151 seen.reattached = false;
5152 return false;
5153 }
5154 const quiet = now - seen.movedAt;
5155 return quiet >= SCREEN_STALL_AFTER && quiet < SCREEN_STALL_GIVE_UP;
5156 }
5157
5158 // reattachDue says, once per stall, when a stalled screen's picture
5159 // should be handed to its element again (§15.22): SCREEN_REATTACH_AFTER
5160 // into the stall. A picture stopped on this side — an element or a
5161 // track Chromium has left muted — is this side's to mend. Pure over
5162 // `seen`, and lifted by name in the node test.
5163 function reattachDue(seen, now) {
5164 const quiet = now - seen.movedAt;
5165 if (seen.reattached || quiet < SCREEN_STALL_AFTER + SCREEN_REATTACH_AFTER || quiet >= SCREEN_STALL_GIVE_UP) {
5166 return false;
5167 }
5168 seen.reattached = true;
5169 return true;
5170 }
5171
5172 // screenLog is one line of the screen's timeline: the console, and the
5173 // last SCREEN_LOG_LINES kept for "Copy call diagnostics".
5174 function screenLog(line) {
5175 const d = new Date();
5176 const pad = (n, w) => String(n).padStart(w || 2, '0');
5177 const stamp = pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()) + '.' + pad(d.getMilliseconds(), 3);
5178 screenLines.push(stamp + ' ' + line);
5179 if (screenLines.length > SCREEN_LOG_LINES) screenLines.splice(0, screenLines.length - SCREEN_LOG_LINES);
5180 console.info('calls: ' + line);
5181 }
5182
5183 // screenReading is what one inbound screen report says, and
5184 // readingSummary and readingMoved put it in words. Pure, and lifted by
5185 // name in the node test: packets arriving and frames assembled but none
5186 // decoded is a decoder; nothing arriving is the sender or the path.
5187 function screenReading(r, trackMuted) {
5188 return {
5189 mid: r.mid || '',
5190 packets: r.packetsReceived || 0,
5191 lost: r.packetsLost || 0,
5192 received: r.framesReceived || 0,
5193 decoded: r.framesDecoded || 0,
5194 dropped: r.framesDropped || 0,
5195 keyframes: r.keyFramesDecoded || 0,
5196 pli: r.pliCount || 0,
5197 fir: r.firCount || 0,
5198 nack: r.nackCount || 0,
5199 freezes: r.freezeCount || 0,
5200 width: r.frameWidth || 0,
5201 height: r.frameHeight || 0,
5202 decoder: r.decoderImplementation || '',
5203 muted: !!trackMuted,
5204 };
5205 }
5206
5207 function readingSummary(r) {
5208 return 'mid ' + (r.mid || '-') + ', ' + r.width + 'x' + r.height + ', decoder ' + (r.decoder || 'unknown') +
5209 (r.muted ? ', track muted' : '') + '; packets ' + r.packets + ' (lost ' + r.lost + '), frames received ' +
5210 r.received + ', decoded ' + r.decoded + ', dropped ' + r.dropped + ', keyframes ' + r.keyframes +
5211 ', PLI ' + r.pli + ', FIR ' + r.fir + ', NACK ' + r.nack + ', freezes ' + r.freezes;
5212 }
5213
5214 function readingMoved(r, b) {
5215 if (!b || b.mid !== r.mid) return readingSummary(r) + ' — no earlier reading';
5216 const d = (a, z) => (a >= z ? '+' + (a - z) : 'new ' + a);
5217 let verdict = 'decoding';
5218 if (r.packets === b.packets) verdict = 'no packets arriving (the sender or the path)';
5219 else if (r.received === b.received) verdict = 'packets arriving, no frames assembled (loss, or waiting on a keyframe)';
5220 else if (r.decoded === b.decoded) verdict = 'frames arriving, none decoded (the decoder)';
5221 return 'packets ' + d(r.packets, b.packets) + ', frames received ' + d(r.received, b.received) + ', decoded ' +
5222 d(r.decoded, b.decoded) + ', dropped ' + d(r.dropped, b.dropped) + ', keyframes ' + d(r.keyframes, b.keyframes) +
5223 ', PLI ' + d(r.pli, b.pli) + ', NACK ' + d(r.nack, b.nack) + (r.muted ? ', track muted' : '') + ' — ' + verdict;
5224 }
5225
5226 // watchScreens takes one poll's decoded counts, by share key, and
5227 // reports the list when it changes.
5228 //
5229 // `readings` is the same poll's screenReading per share key: kept for
5230 // the diagnostics, and set against the reading from when the screen last
5231 // moved, so a stall is logged with what is and is not still arriving.
5232 function watchScreens(decodedByKey, readings) {
5233 const now = Date.now();
5234 const frozen = now < screenStallTestUntil;
5235 const stalled = [];
5236 for (const key of Array.from(screenSeen.keys())) {
5237 if (!decodedByKey.has(key)) screenSeen.delete(key);
5238 }
5239 for (const key of Array.from(screenReadings.keys())) {
5240 if (!decodedByKey.has(key)) {
5241 screenReadings.delete(key);
5242 screenMoving.delete(key);
5243 }
5244 }
5245 for (const [key, decoded] of decodedByKey) {
5246 const id = key.slice(0, -SHARE_SUFFIX.length);
5247 const entry = pcs.get(id);
5248 if (!entry || !hasShare(entry)) {
5249 screenSeen.delete(key);
5250 continue;
5251 }
5252 let seen = screenSeen.get(key);
5253 if (!seen) {
5254 seen = { decoded: 0, movedAt: 0, reattached: false };
5255 screenSeen.set(key, seen);
5256 }
5257 const reading = readings && readings.get(key);
5258 if (reading) screenReadings.set(key, reading);
5259 if (judgeScreen(seen, decoded, now, frozen)) {
5260 stalled.push(id);
5261 if (reattachDue(seen, now)) {
5262 screenLog('screen from ' + id.slice(0, 6) + ' still stalled: handing its picture to the tile again; ' +
5263 (reading ? readingMoved(reading, screenMoving.get(key)) : 'no reading'));
5264 const t = tiles.get(key);
5265 if (t && t.video) {
5266 screenReattaches += 1;
5267 reattachesBy.set(id, (reattachesBy.get(id) || 0) + 1);
5268 replayTile(key, t, entry, true);
5269 }
5270 }
5271 } else if (reading) {
5272 screenMoving.set(key, reading);
5273 }
5274 }
5275 stalled.sort();
5276 if (stalled.join() === screenStalled.join()) return;
5277 for (const id of stalled) {
5278 if (screenStalled.includes(id)) continue;
5279 const key = shareKey(id);
5280 const reading = screenReadings.get(key);
5281 screenLog('screen from ' + id.slice(0, 6) + ' stalled here: reporting it; since it last moved ' +
5282 (reading ? readingMoved(reading, screenMoving.get(key)) : 'no reading'));
5283 // §15.26: counted with what the statistics said.
5284 const c = stallsBy.get(id) || { stalls: 0, noPackets: 0, undecoded: 0 };
5285 c.stalls += 1;
5286 const was = screenMoving.get(key);
5287 if (reading && was && was.mid === reading.mid) {
5288 if (reading.packets === was.packets) c.noPackets += 1;
5289 else if (reading.decoded === was.decoded) c.undecoded += 1;
5290 }
5291 stallsBy.set(id, c);
5292 }
5293 for (const id of screenStalled) {
5294 if (stalled.includes(id)) continue;
5295 const reading = screenReadings.get(shareKey(id));
5296 screenLog('screen from ' + id.slice(0, 6) + ' moving here again' + (reading ? ': ' + readingSummary(reading) : ''));
5297 }
5298 screenStalled = stalled;
5299 reportMedia();
5300 }
5301
5302 // answerScreenStalls is the sharer's half: every peer whose report
5303 // names us gets a keyframe from our screen's encoder, and — when
5304 // keyframes do not answer (§15.22) — that connection's screen rebuilt,
5305 // then everyone's shared again from the same capture, and then words
5306 // saying it could not be restored. The quiet notice says which.
5307 function answerScreenStalls() {
5308 const me = state.peer;
5309 const now = Date.now();
5310 let reshare = false;
5311 for (const [id, m] of remoteMedia) {
5312 const asking = !!(share && me && m && m.screenStalled && m.screenStalled.includes(me));
5313 if (!asking) {
5314 const gone = screenAsks.get(id);
5315 if (gone && gone.stage && share) {
5316 screenLog(id.slice(0, 6) + '\u2019s view restored after ' + stageWords(gone.stage));
5317 const loop = shareLoops.get(id) || {};
5318 shareRestored(Object.assign(loop, { stage: gone.stage }), now);
5319 shareLoops.set(id, loop);
5320 }
5321 screenAsks.delete(id);
5322 continue;
5323 }
5324 const entry = pcs.get(id);
5325 let ask = screenAsks.get(id);
5326 if (!ask) {
5327 ask = { at: 0, tries: 0, restUntil: 0, stage: '', stageAt: 0 };
5328 screenAsks.set(id, ask);
5329 if (entry) entry.shareSentSince = 0;
5330 }
5331 if (entry && now >= ask.restUntil && now - ask.at >= SCREEN_KEYFRAME_EVERY) {
5332 ask.at = now;
5333 ask.tries += 1;
5334 if (ask.tries >= SCREEN_KEYFRAME_TRIES) {
5335 ask.tries = 0;
5336 ask.restUntil = now + SCREEN_KEYFRAME_REST;
5337 }
5338 shareCounts.keyframes += 1;
5339 countShareStep(id, 'keyframes');
5340 screenLog('keyframe for ' + id.slice(0, 6) + ', whose view of the screen stalled');
5341 shareKeyframe(entry).catch(() => {});
5342 }
5343 // Frames left for this person since the last step, or no screen
5344 // negotiated with them at all (a rebuild that never came back).
5345 const negotiated = !!(entry && entry.shareTx && entry.shareSend);
5346 const owed = !negotiated || (entry.shareSentSince || 0) >= SCREEN_ESCALATE_SENT;
5347 const loop = shareLoops.get(id) || {};
5348 const rec = { stage: ask.stage, at: ask.stageAt, lastRebuild: shareRebuiltAt.get(id) || 0,
5349 restoredAt: loop.restoredAt || 0, loops: loop.loops || 0, dampedUntil: loop.dampedUntil || 0 };
5350 const before = rec.stage;
5351 const reshareFree = reshare || !shareResharedAt || now - shareResharedAt >= SCREEN_RESHARE_EVERY;
5352 const action = escalateShare(rec, now, owed, reshareFree);
5353 ask.stage = rec.stage;
5354 ask.stageAt = rec.at;
5355 shareLoops.set(id, { restoredAt: rec.restoredAt, loops: rec.loops, dampedUntil: rec.dampedUntil });
5356 if (rec.stage !== before && entry) entry.shareSentSince = 0;
5357 if (action === 'rebuild') {
5358 shareRebuiltAt.set(id, now);
5359 shareCounts.rebuilds += 1;
5360 countShareStep(id, 'rebuilds');
5361 screenLog(id.slice(0, 6) + ' still reports a stall after keyframes: rebuilding its screen (new transceiver, same size and mode)');
5362 if (entry) rebuildShareFor(entry);
5363 } else if (action === 'reshare') {
5364 reshare = true;
5365 countShareStep(id, 'reshares');
5366 screenLog(id.slice(0, 6) + ' still reports a stall' + (before === 'rebuilt' ? ' after the rebuild' : ', rebuilt under a minute ago') + ': sharing again');
5367 } else if (action === 'damped') {
5368 shareCounts.failures += 1;
5369 shareCounts.damped += 1;
5370 countShareStep(id, 'failures');
5371 countShareStep(id, 'damped');
5372 screenLog(id.slice(0, 6) + ' still reports a stall, and rebuilding has only mended it briefly: not rebuilding or sharing again for ' +
5373 Math.round((rec.dampedUntil - now) / 1000) + ' s');
5374 } else if (action === 'failed') {
5375 shareCounts.failures += 1;
5376 countShareStep(id, 'failures');
5377 screenLog(id.slice(0, 6) + ' still reports a stall and there is nothing left to try: giving up');
5378 }
5379 }
5380 if (reshare) {
5381 shareResharedAt = now;
5382 shareCounts.reshares += 1;
5383 // One share again answers every report in flight. For §15.26 it is
5384 // counted against each of the people it answers: it was done for
5385 // them, though it reached everyone.
5386 for (const [askId, ask] of screenAsks) {
5387 if (ask.stage === 'keyframes' || ask.stage === 'rebuilt') {
5388 countShareStep(askId, 'reshares');
5389 ask.stage = 'reshared';
5390 ask.stageAt = now;
5391 }
5392 }
5393 for (const entry of pcs.values()) entry.shareSentSince = 0;
5394 reshareAll();
5395 }
5396 const recovering = [];
5397 const restarting = [];
5398 const failed = [];
5399 for (const [id, ask] of screenAsks) {
5400 const who = names.get(id) || 'Someone';
5401 if (ask.stage === 'failed') failed.push(who);
5402 else if (ask.stage === 'rebuilt' || ask.stage === 'reshared') restarting.push(who);
5403 else recovering.push(who);
5404 }
5405 const text = noticeWords(recovering.sort(), restarting.sort(), failed.sort());
5406 if (text !== shareRecovery) {
5407 shareRecovery = text;
5408 renderShare();
5409 }
5410 }
5411
5412 // callDiagnostics is "Copy call diagnostics" for the browser: the
5413 // connections, and the screen — how ours is leaving and what the ladder
5414 // has done, every screen arriving here as its statistics have it, and
5415 // the timeline. Names, states and counts only: no media, no addresses,
5416 // no credentials.
5417 //
5418 // §15.26: "Report a problem" sends the same text with `anonymous`, in
5419 // which every person is "peer " and the first six characters of their
5420 // peer id rather than their name — the server turns those into the
5421 // call's random tags before anything is logged. "Copy call
5422 // diagnostics" keeps the names: that text goes only where its owner
5423 // pastes it.
5424 function callDiagnostics(opts) {
5425 const anonymous = !!(opts && opts.anonymous);
5426 const who = (id) => (anonymous ? 'peer ' + id.slice(0, 6) : names.get(id) || 'Someone');
5427 const lines = ['Calls web diagnostics, ' + new Date().toISOString()];
5428 lines.push('Browser: ' + (navigator.userAgent || 'unknown'));
5429 lines.push('');
5430 lines.push('## Call');
5431 lines.push('admitted ' + state.admitted + ', people here ' + (pcs.size + 1) + ', stopped ' + state.stopped);
5432 for (const [id, entry] of pcs) {
5433 lines.push((anonymous ? who(id) : who(id) + ' (' + id.slice(0, 6) + ')') + ': connection ' + entry.pc.connectionState +
5434 ', signalling ' + entry.pc.signalingState + ', ICE ' + entry.pc.iceConnectionState);
5435 }
5436 lines.push('');
5437 lines.push('## Screen');
5438 if (share) {
5439 lines.push('Sharing (' + shareMode() + ')');
5440 for (const [id, entry] of pcs) {
5441 const r = entry.shareSend;
5442 if (!r) {
5443 lines.push('to ' + who(id) + ': ' + (entry.shareTx ? 'negotiating' : 'no screen transceiver'));
5444 continue;
5445 }
5446 lines.push('to ' + who(id) + ': ' + r.width + 'x' + r.height + ' at ' + Math.round(r.fps) + ' fps, encoder ' +
5447 (r.encoder || 'unknown') + ', encoded ' + r.framesEncoded + ', sent ' + r.framesSent + ', keyframes ' +
5448 r.keyFramesEncoded + ', limitation ' + (r.limitation || 'none'));
5449 }
5450 for (const [id, ask] of screenAsks) {
5451 if (ask.stage) lines.push('recovering ' + who(id) + '\u2019s view: ' + ask.stage);
5452 }
5453 } else {
5454 lines.push('Not sharing');
5455 }
5456 lines.push('recoveries: ' + shareCounts.keyframes + ' keyframes, ' + shareCounts.rebuilds + ' rebuilds, ' +
5457 shareCounts.reshares + ' shares again, ' + shareCounts.failures + ' given up');
5458 for (const [key, reading] of screenReadings) {
5459 const id = key.slice(0, -SHARE_SUFFIX.length);
5460 lines.push('from ' + who(id) + ': ' + readingSummary(reading));
5461 }
5462 if (screenStalled.length) lines.push('stalled here: ' + screenStalled.map(who).join(', '));
5463 if (screenReattaches) lines.push('pictures handed to their tiles again here: ' + screenReattaches);
5464 lines.push('');
5465 lines.push('## Screen log (last ' + SCREEN_LOG_LINES + ' lines)');
5466 if (screenLines.length) lines.push(...screenLines);
5467 else lines.push('(nothing logged)');
5468 return lines.join('\n');
5469 }
5470
5471 // ---------------------------------------------------------------
5472 // Quality reports and "Report a problem" (§15.26, 2026-10-03)
5473 // ---------------------------------------------------------------
5474 //
5475 // Paul's ruling: every thirty seconds while admitted, and once more at
5476 // leave, this tab tells the server how its connections went over the
5477 // window — numbers and enums only, per remote peer, read off the stats
5478 // walk pollFrames already makes once a second rather than a walk of its
5479 // own. No name, no email, no title, no meeting, no device label, no
5480 // address and nothing anyone typed: the report names a remote peer only
5481 // by the peer id the server already knows, which it logs as the call's
5482 // random tag in its place. The person can switch the reports off in the
5483 // Devices panel; the server can switch them off for everyone (a 204).
5484 //
5485 // "Report a problem" is report.js's sheet; this file hands it the
5486 // token, the diagnostics with the people named by short peer id, and
5487 // what kind of client this is.
5488
5489 // qualityCeiling is a number's bound in protocol/quality.go, by its JSON
5490 // name, as the server's numberCeiling has it.
5491 function qualityCeiling(name) {
5492 switch (name) {
5493 case 'seconds': case 'reconnectingSeconds': case 'cantHearSeconds': case 'freezeSeconds':
5494 case 'limitedBandwidthSeconds': case 'limitedCpuSeconds':
5495 return QUALITY_MAX_SECONDS;
5496 case 'rtt': case 'jitter': case 'jitterBufferMs':
5497 case 'rttAvg': case 'rttMax': case 'jitterAvg': case 'jitterMax':
5498 return QUALITY_MAX_MILLIS;
5499 case 'kbps':
5500 return QUALITY_MAX_KBPS;
5501 case 'width': case 'height':
5502 return QUALITY_MAX_PIXELS;
5503 case 'fps':
5504 return QUALITY_MAX_FPS;
5505 default:
5506 return QUALITY_MAX_COUNT;
5507 }
5508 }
5509
5510 // qualitySet writes one number into a report part: finite and not
5511 // negative or it is left out (absent is "could not measure"), clamped
5512 // to its ceiling, and to a tenth, which is all the server keeps.
5513 function qualitySet(obj, name, v) {
5514 if (typeof v !== 'number' || !Number.isFinite(v) || v < 0) return;
5515 obj[name] = Math.round(Math.min(v, qualityCeiling(name)) * 10) / 10;
5516 }
5517
5518 // qualityReading is one connection's getStats walk, kept as the next
5519 // window's starting point: each RTP stream by its report id (a new SSRC
5520 // is a new stream, whose counters start again from nothing) with its
5521 // running counters and what it reads now, and the selected candidate
5522 // pair's kinds, transport and round trip. `classify(r)` names an RTP
5523 // report's stream — 'audio', 'video' or 'screen', or '' to leave it out
5524 // — and a remote-inbound-rtp report (the far side's account of what we
5525 // send) takes the name of the outbound stream it is about. Fields are
5526 // copied by name from the lists below and nothing else is: a
5527 // candidate's address and port never leave this function. Pure, and
5528 // lifted by name in test/browser/room-quality.test.mjs.
5529 //
5530 // §15.29 (2026-10-28) reads more of the same walk, by name as before.
5531 // An outbound stream's encoder and an inbound one's decoder, as the
5532 // implementation's name and the browser's own hardware-or-not, kept
5533 // here only for coderKind to turn into an enum: "VideoToolbox" or
5534 // "libvpx" is read and never reported. The codec by its MIME type,
5535 // through the stream's codecId. The encoder's qualityLimitationDurations
5536 // — seconds held back by each reason since the stream began — as four
5537 // counters (limitNone, limitCpu, limitBandwidth, limitOther), so a
5538 // window can say which reason held it back longest rather than which
5539 // one happened to hold at the moment it ended. The selected pair's
5540 // totalRoundTripTime and responsesReceived, for the window's mean round
5541 // trip, and the pair's id, so the next window knows the counters are the
5542 // same pair's (an id of the stats walk's own: never an address, and it
5543 // never leaves qualityPeer). And `candidates`: what this side gathered
5544 // and what it was offered, by type, and which kinds of pair succeeded —
5545 // whether any had neither end a relay (directOk), any had this side's
5546 // end not a relay (localDirectOk), and any went over UDP the whole way
5547 // to the peer or the relay (udpOk). Types and counts only.
5548 function qualityReading(reports, classify) {
5549 const COUNTERS = {
5550 out: ['bytesSent', 'packetsSent'],
5551 remote: ['packetsLost'],
5552 in: ['bytesReceived', 'packetsReceived', 'packetsLost', 'totalSamplesReceived', 'concealedSamples',
5553 'insertedSamplesForDeceleration', 'removedSamplesForAcceleration', 'jitterBufferDelay',
5554 'jitterBufferEmittedCount', 'freezeCount', 'totalFreezesDuration', 'framesDecoded', 'framesDropped'],
5555 };
5556 const GAUGES = {
5557 out: ['frameWidth', 'frameHeight', 'framesPerSecond', 'qualityLimitationReason', 'encoderImplementation',
5558 'powerEfficientEncoder'],
5559 remote: ['roundTripTime', 'jitter'],
5560 in: ['jitter', 'frameWidth', 'frameHeight', 'framesPerSecond', 'decoderImplementation', 'powerEfficientDecoder'],
5561 };
5562 const LIMITS = [['none', 'limitNone'], ['cpu', 'limitCpu'], ['bandwidth', 'limitBandwidth'], ['other', 'limitOther']];
5563 const all = [];
5564 const byId = new Map();
5565 if (reports && typeof reports.forEach === 'function') {
5566 reports.forEach((r) => {
5567 if (!r || typeof r !== 'object') return;
5568 all.push(r);
5569 if (r.id) byId.set(r.id, r);
5570 });
5571 }
5572 const streams = new Map();
5573 const keep = (key, dir, kind, r) => {
5574 const counters = {};
5575 const gauges = {};
5576 for (const n of COUNTERS[dir]) if (typeof r[n] === 'number') counters[n] = r[n];
5577 for (const n of GAUGES[dir]) {
5578 if (typeof r[n] === 'number' || typeof r[n] === 'string' || typeof r[n] === 'boolean') gauges[n] = r[n];
5579 }
5580 if (dir === 'out' && r.qualityLimitationDurations && typeof r.qualityLimitationDurations === 'object') {
5581 for (const [reason, name] of LIMITS) {
5582 const v = r.qualityLimitationDurations[reason];
5583 if (typeof v === 'number') counters[name] = v;
5584 }
5585 }
5586 const codec = dir !== 'remote' && r.codecId ? byId.get(r.codecId) : null;
5587 if (codec && codec.type === 'codec' && typeof codec.mimeType === 'string') gauges.mimeType = codec.mimeType;
5588 streams.set(key, { dir, kind, counters, gauges });
5589 };
5590 for (const r of all) {
5591 const key = r.type + ':' + (r.id || r.ssrc || '');
5592 if (r.type === 'outbound-rtp' || r.type === 'inbound-rtp') {
5593 const kind = classify(r);
5594 if (kind) keep(key, r.type === 'outbound-rtp' ? 'out' : 'in', kind, r);
5595 } else if (r.type === 'remote-inbound-rtp') {
5596 const sent = r.localId ? byId.get(r.localId) : null;
5597 const kind = sent && sent.type === 'outbound-rtp' ? classify(sent) : '';
5598 if (kind) keep(key, 'remote', kind, r);
5599 }
5600 }
5601 let pair = null;
5602 for (const r of all) {
5603 if (r.type === 'transport' && r.selectedCandidatePairId && byId.has(r.selectedCandidatePairId)) {
5604 pair = byId.get(r.selectedCandidatePairId);
5605 break;
5606 }
5607 }
5608 // Firefox has no transport report; it marks the pair itself.
5609 if (!pair) pair = all.find((r) => r.type === 'candidate-pair' && r.selected === true) || null;
5610 if (!pair) pair = all.find((r) => r.type === 'candidate-pair' && r.nominated && r.state === 'succeeded') || null;
5611 let path = null;
5612 if (pair) {
5613 const kinds = ['host', 'srflx', 'prflx', 'relay'];
5614 const local = byId.get(pair.localCandidateId) || {};
5615 const remote = byId.get(pair.remoteCandidateId) || {};
5616 // A relay candidate's own protocol is the relay's leg to the peer;
5617 // how this browser reaches the relay is relayProtocol, and that is
5618 // the one that says "TURN over TLS".
5619 const transport = local.candidateType === 'relay' && ['udp', 'tcp', 'tls'].includes(local.relayProtocol)
5620 ? local.relayProtocol
5621 : ['udp', 'tcp'].includes(local.protocol) ? local.protocol : 'unknown';
5622 path = {
5623 local: kinds.includes(local.candidateType) ? local.candidateType : 'unknown',
5624 remote: kinds.includes(remote.candidateType) ? remote.candidateType : 'unknown',
5625 protocol: transport,
5626 rtt: typeof pair.currentRoundTripTime === 'number' ? pair.currentRoundTripTime * 1000 : undefined,
5627 pair: typeof pair.id === 'string' ? pair.id : '',
5628 totalRoundTripTime: typeof pair.totalRoundTripTime === 'number' ? pair.totalRoundTripTime : undefined,
5629 responsesReceived: typeof pair.responsesReceived === 'number' ? pair.responsesReceived : undefined,
5630 };
5631 }
5632 // §15.29: the candidates, by type, and the pairs that worked.
5633 let candidates = null;
5634 const types = ['host', 'srflx', 'prflx', 'relay'];
5635 for (const r of all) {
5636 if (r.type !== 'local-candidate' && r.type !== 'remote-candidate') continue;
5637 if (!candidates) {
5638 candidates = { local: { host: 0, srflx: 0, prflx: 0, relay: 0 }, remote: { host: 0, srflx: 0, prflx: 0, relay: 0 },
5639 directOk: false, localDirectOk: false, udpOk: false };
5640 }
5641 const side = r.type === 'local-candidate' ? candidates.local : candidates.remote;
5642 if (types.includes(r.candidateType)) side[r.candidateType] += 1;
5643 }
5644 if (candidates) {
5645 for (const r of all) {
5646 if (r.type !== 'candidate-pair' || r.state !== 'succeeded') continue;
5647 const local = byId.get(r.localCandidateId);
5648 const remote = byId.get(r.remoteCandidateId);
5649 if (!local || !types.includes(local.candidateType)) continue;
5650 const localRelay = local.candidateType === 'relay';
5651 if (!localRelay) candidates.localDirectOk = true;
5652 if (!localRelay && remote && types.includes(remote.candidateType) && remote.candidateType !== 'relay') {
5653 candidates.directOk = true;
5654 }
5655 if (local.protocol === 'udp' && (!localRelay || local.relayProtocol === 'udp')) candidates.udpOk = true;
5656 }
5657 }
5658 return { streams, path, candidates };
5659 }
5660
5661 // coderKind is a video encoder's or decoder's kind (§15.29): 'hardware'
5662 // or 'software', or 'unknown' for an implementation it cannot place, and
5663 // '' — left out of the report — when the browser said nothing at all.
5664 // The browser's own powerEfficientEncoder/Decoder is the better word
5665 // where it gives one; otherwise the implementation's name, which never
5666 // leaves this function ("ExternalEncoder", "VideoToolbox", "libvpx",
5667 // "OpenH264", "FallbackEncoder (…)"). Pure, and lifted by name in the
5668 // node test.
5669 function coderKind(impl, powerEfficient) {
5670 if (typeof powerEfficient === 'boolean') return powerEfficient ? 'hardware' : 'software';
5671 const name = typeof impl === 'string' ? impl : '';
5672 if (!name) return '';
5673 if (/videotoolbox|external|mediacodec|vaapi|v4l2|d3d11|dxva|nvenc|nvdec|mediafoundation|qsv|amf/i.test(name)) {
5674 return 'hardware';
5675 }
5676 if (/libvpx|openh264|libaom|dav1d|ffmpeg|libav|fallback|software/i.test(name)) return 'software';
5677 return 'unknown';
5678 }
5679
5680 // codecKind is a stream's codec family (protocol.C