oficina / meet Public

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

Plain git — no account needed to clone.

Download

Download this file

1// native-screen.mjs — the app shares its (synthetic) screen to a browser
2// for a long stretch while the call is disturbed underneath it, and the
3// browser watches the received screen for freezes.
4//
5// Written for Paul's report of 2026-09-28 (Mac 0.4.1): "after a while, my
6// screen froze on her end and she was no longer able to see my screen. I
7// had to stop and re-share again." Every scenario here asserts the same
8// thing: the receiver's screen keeps decoding, or comes back within a
9// bound, without anyone sharing again.
10//
11// Scenarios, one per run (argv[4]):
12// renewals the relay on, the stream renewed every ten seconds (which
13// is when the app used to restart ICE on every connection) and
14// relay credentials that need renewing every twenty seconds,
15// so real renewals — ICE restarts — happen mid-share
16// resume the streams renewed every ten seconds with no relay, so
17// every resume is a resume and nothing else
18// capture the synthetic screen stops producing frames (a capture that
19// has stalled): the app's watchdog must restart it
20// encoder the app's encoder stops putting frames out (the screen
21// sender deactivated under it): the watchdog must recover it
22// loss the browser stops painting and asks for a keyframe
23// (screenStalled): the app must answer with one
24// wedge the browser's screen receiver stops passing anything to its
25// decoder (an encoded transform that drops every frame), which
26// no keyframe mends: the app must escalate to a rebuild and
27// the browser decode again within 30 s, the app's notice going
28// "recovering", "Restarting your share for …", then nothing
29// (spec §15.22)
30// wedge-sticky every screen receiver the browser gets is wedged, new
31// ones too: the app must end at "Couldn’t restore …", and
32// clear once the wedge is lifted
33// soak renewals and resumes as `renewals`, for SCREEN_SOAK_SECONDS,
34// with the mode cycled (balanced, motion, detail) and the
35// app's uplink capped and lifted every SCREEN_SOAK_STEP_MS:
36// every freeze is logged with what the ladder did about it
37// web-soak the same with the browser sharing and the app watching, the
38// browser's mode cycled
39// web-wedge, web-wedge-sticky the same the other way round: the
40// browser shares, the app's screen decoder wedges, and the
41// browser's ladder has to restore it (or say it cannot)
42//
43// Run by TestNativeMacScreenRecovery (make native-browser).
44import { syntheticMedia } from './synthetic-media.mjs';
45import { chromium } from 'playwright';
46import { spawn } from 'node:child_process';
47import { createInterface } from 'node:readline';
48import assert from 'node:assert/strict';
49
50const [origin, room, binary, scenario] = process.argv.slice(2);
51const SOAK = Number(process.env.SCREEN_SOAK_SECONDS || 60);
52// The longest the browser's screen may go without a new frame and still
53// count as healthy. A freeze is anything longer.
54const FREEZE_MS = Number(process.env.SCREEN_FREEZE_MS || 3000);
55// How long recovery may take, from the fault to frames again.
56const RECOVER_S = Number(process.env.SCREEN_RECOVER_SECONDS || 15);
57const asserting = process.env.SCREEN_ASSERT !== '0';
58
59const browser = await chromium.launch({ headless: true, args: [
60 '--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream',
61 '--autoplay-policy=no-user-gesture-required', '--disable-features=WebRtcHideLocalIpsWithMdns',
62 '--mute-audio',
63 // getDisplayMedia answered with a fake 1280x720 monitor and no picker,
64 // for the web-* scenarios (see call.mjs).
65 '--auto-accept-this-tab-capture',
66] });
67// bypassCSP: the wedge's encoded transform runs in a worker made from a
68// blob, which the page's own policy (default-src 'self') would refuse.
69// The gate's, never the page's.
70const context = await browser.newContext({ permissions: ['camera', 'microphone'], bypassCSP: true });
71if (process.env.CALLS_SYNTHETIC_MEDIA) await context.addInitScript(syntheticMedia);
72await context.addCookies([{ name: process.env.CALLS_COOKIE_NAME, value: process.env.CALLS_COOKIE_A, url: origin }]);
73const page = await context.newPage();
74await page.addInitScript(() => {
75 const Native = window.RTCPeerConnection;
76 window.__nativeInteropPCs = new Set();
77 // §15.22's wedge: a receiver whose frames never reach its decoder.
78 // Chromium takes an encoded transform only on a receiver that has not
79 // started, so in the wedge scenarios every screen receiver gets one as
80 // it arrives — passing everything through — and __wedgeScreens tells
81 // the ones there now to swallow every frame instead. `sticky` has each
82 // one that arrives after start out swallowing.
83 let worker = null;
84 let serial = 0;
85 const wedgeWorker = () => {
86 if (!worker) {
87 const code = [
88 'const drops = new Map();',
89 'onmessage = (m) => { for (const id of m.data.ids) drops.set(id, m.data.drop); };',
90 'onrtctransform = (e) => {',
91 ' const id = e.transformer.options.id;',
92 ' if (!drops.has(id)) drops.set(id, !!e.transformer.options.drop);',
93 ' e.transformer.readable.pipeThrough(new TransformStream({ transform(f, c) { if (!drops.get(id)) c.enqueue(f); } }))',
94 ' .pipeTo(e.transformer.writable);',
95 '};',
96 ].join('\n');
97 worker = new Worker(URL.createObjectURL(new Blob([code], { type: 'text/javascript' })));
98 }
99 return worker;
100 };
101 window.__wedge = { sticky: false, wedged: 0, ids: new Map() };
102 const screenReceiver = (tx) => tx && tx.receiver && tx.receiver.track && tx.receiver.track.kind === 'video' &&
103 tx.direction === 'recvonly' && tx.currentDirection !== 'stopped';
104 const watchReceiver = (tx) => {
105 if (!window.__wedgeReady || !screenReceiver(tx) || window.__wedge.ids.has(tx.receiver)) return;
106 const id = ++serial;
107 window.__wedge.ids.set(tx.receiver, id);
108 tx.receiver.transform = new RTCRtpScriptTransform(wedgeWorker(), { id, drop: window.__wedge.sticky });
109 if (window.__wedge.sticky) window.__wedge.wedged += 1;
110 };
111 window.__wedgeScreens = (sticky) => {
112 window.__wedge.sticky = !!sticky;
113 const ids = [];
114 for (const pc of window.__nativeInteropPCs) {
115 for (const tx of pc.getTransceivers()) {
116 const id = screenReceiver(tx) && window.__wedge.ids.get(tx.receiver);
117 if (id) ids.push(id);
118 }
119 }
120 wedgeWorker().postMessage({ ids, drop: true });
121 window.__wedge.wedged += ids.length;
122 return ids.length;
123 };
124 window.__releaseWedge = () => {
125 window.__wedge.sticky = false;
126 wedgeWorker().postMessage({ ids: [...window.__wedge.ids.values()], drop: false });
127 };
128 window.RTCPeerConnection = class extends Native {
129 // The web-* scenarios' screen goes out as H.264: the app can only
130 // wedge a VideoToolbox decoder (DecoderWedge.swift), and the browser
131 // left to itself sends VP8. What is under test, the ladder, does not
132 // turn on the codec.
133 addTransceiver(track, init) {
134 const tx = super.addTransceiver(track, init);
135 if (window.__h264Screen && init && init.direction === 'sendonly' && track && track.kind === 'video') {
136 const codecs = RTCRtpSender.getCapabilities('video').codecs;
137 const h264 = codecs.filter((c) => /h264/i.test(c.mimeType));
138 try {
139 tx.setCodecPreferences([...h264, ...codecs.filter((c) => !/h264/i.test(c.mimeType))]);
140 } catch {}
141 }
142 return tx;
143 }
144 constructor(...args) {
145 super(...args);
146 window.__nativeInteropPCs.add(this);
147 this.addEventListener('track', (e) => watchReceiver(e.transceiver));
148 }
149 };
150});
151// Receivers made ready to wedge only in the scenarios that wedge them, so
152// every other scenario's browser decodes exactly as a person's would.
153await page.addInitScript((ready) => { window.__wedgeReady = ready; }, scenario === 'wedge' || scenario === 'wedge-sticky');
154let native;
155let failed = false;
156try {
157 await page.goto(`${origin}/m/${room}`);
158 await page.waitForFunction(() => !!window.meet);
159 // The app's decoders can be wedged in the web-* scenarios only.
160 const env = scenario.startsWith('web-') ? Object.assign({}, process.env, { CALLS_DECODER_WEDGE: '1' }) : process.env;
161 native = spawn(binary, [], { stdio: ['pipe', 'pipe', 'pipe'], env });
162 native.stdin.write(process.env.CALLS_NATIVE_INPUT + '\n');
163 let sample = null;
164 let exited = false;
165 const replies = [];
166 native.on('exit', () => { exited = true; });
167 createInterface({ input: native.stdout }).on('line', (line) => {
168 try {
169 const value = JSON.parse(line);
170 if (value.stats) sample = value;
171 else replies.push(value);
172 } catch {}
173 });
174 native.stderr.resume();
175 const wait = async (predicate, label, seconds = 35) => {
176 const until = Date.now() + seconds * 1000;
177 while (Date.now() < until) {
178 if (exited) throw new Error('native executable exited');
179 if (await predicate()) return;
180 await new Promise((r) => setTimeout(r, 250));
181 }
182 throw new Error(label + ': ' + JSON.stringify(sample));
183 };
184 await wait(() => sample?.stats.framesDecoded > 15, 'native receives the browser');
185 const nativePeer = sample.peer;
186 if (scenario === 'web-soak') {
187 await webSoak(page, native, () => sample, wait);
188 console.log(`PASS ${scenario}`);
189 throw new Done();
190 }
191 if (scenario.startsWith('web-')) {
192 await webShares(page, native, () => sample, replies, wait, scenario.endsWith('sticky'));
193 console.log(`PASS ${scenario}`);
194 process.exitCode = 0;
195 throw new Done();
196 }
197 const key = nativePeer + '#share';
198 // What the browser is receiving on the app's screen, from the
199 // connection's own statistics: the screen is the inbound video that is
200 // not the camera's mid.
201 const received = () => page.evaluate(async (peer) => {
202 const s = window.meet.state();
203 const frames = Object.fromEntries(s.frames);
204 const out = { frames: frames[peer + '#share'] || 0, camera: frames[peer] || 0, shares: s.shares, ufrags: [], screen: null };
205 for (const pc of window.__nativeInteropPCs) {
206 if (pc.connectionState === 'closed') continue;
207 const remote = pc.remoteDescription?.sdp || '';
208 const m = remote.match(/a=ice-ufrag:(\S+)/);
209 if (m) out.ufrags.push(m[1]);
210 const tx = pc.getTransceivers().filter((t) => t.receiver.track?.kind === 'video' && t.direction === 'recvonly');
211 const mids = new Set(tx.map((t) => t.mid));
212 for (const r of (await pc.getStats()).values()) {
213 if (r.type === 'inbound-rtp' && r.kind === 'video' && mids.has(r.mid)) {
214 out.screen = { decoded: r.framesDecoded, received: r.framesReceived, pli: r.pliCount, fir: r.firCount,
215 freezes: r.freezeCount, keyframes: r.keyFramesDecoded, lost: r.packetsLost, mid: r.mid };
216 }
217 }
218 }
219 return out;
220 }, nativePeer);
221
222 // The mode first: it is remembered across runs of the interop binary,
223 // and the screen's source is made for the mode the share starts in.
224 native.stdin.write(`screen-mode ${process.env.SCREEN_MODE || 'balanced'}\n`);
225 // SCREEN_SOURCE=motion shares the 1920-wide scrolling page (its height
226 // CALLS_SYNTHETIC_SCREEN_HEIGHT) rather than the small still screen:
227 // what meets H.264 level 3.1's limit (§15.22).
228 if (scenario === 'display') native.stdin.write(`screen-display ${process.env.SCREEN_DEPTH || 6}\n`);
229 else if (process.env.SCREEN_SOURCE === 'motion') native.stdin.write('screen-motion\n');
230 else if (process.env.SCREEN_SOURCE === 'display') native.stdin.write(`screen-display ${process.env.SCREEN_DEPTH || 6}\n`);
231 else native.stdin.write('screen-on\n');
232 await wait(() => sample?.sharingScreen === true, 'native says it is sharing');
233 await wait(async () => (await received()).frames > 15, 'the browser decodes the app’s screen');
234 console.log('PASS the browser decodes the app’s screen');
235
236 // The watch: once a second, how long since the screen's frame count
237 // last moved. Every freeze longer than FREEZE_MS is recorded with what
238 // was going on around it.
239 const freezes = [];
240 let last = await received();
241 let lastMoved = Date.now();
242 let restarts = 0;
243 const seenUfrags = new Set(last.ufrags);
244 const watchFor = async (seconds, label) => {
245 const until = Date.now() + seconds * 1000;
246 let frozen = null;
247 while (Date.now() < until) {
248 if (exited) throw new Error('native executable exited');
249 await new Promise((r) => setTimeout(r, 1000));
250 const now = await received();
251 for (const u of now.ufrags) if (!seenUfrags.has(u)) { seenUfrags.add(u); restarts += 1; }
252 if (now.frames > last.frames) {
253 if (frozen) {
254 frozen.ms = Date.now() - frozen.since;
255 freezes.push(frozen);
256 console.log(`FREEZE ${label}: ${frozen.ms} ms, then frames again (${JSON.stringify(now.screen)})`);
257 frozen = null;
258 }
259 lastMoved = Date.now();
260 } else if (!frozen && Date.now() - lastMoved > FREEZE_MS) {
261 frozen = { since: lastMoved, label, at: now.screen, native: sample?.stats };
262 console.log(`FROZEN ${label}: no screen frame for ${Date.now() - lastMoved} ms ${JSON.stringify(now.screen)} native=${JSON.stringify(pick(sample?.stats))}`);
263 }
264 last = now;
265 }
266 if (frozen) {
267 frozen.ms = Date.now() - frozen.since;
268 frozen.open = true;
269 freezes.push(frozen);
270 }
271 };
272 const pick = (s) => s && Object.fromEntries(Object.entries(s).filter(([k]) => /^screen|Watchdog|peerConnections/.test(k)));
273 const recovered = async (label) => {
274 const base = (await received()).frames;
275 await wait(async () => (await received()).frames > base + 10, label, RECOVER_S);
276 };
277
278 if (scenario === 'display') {
279 if (process.env.SCREEN_UPLINK) native.stdin.write(`uplink ${process.env.SCREEN_UPLINK}\n`);
280 if (process.env.SCREEN_MODE_LATER) native.stdin.write(`screen-mode ${process.env.SCREEN_MODE_LATER}\n`);
281 let prev = null;
282 const until = Date.now() + SOAK * 1000;
283 const tick = setInterval(() => {
284 const s = sample?.stats || {};
285 const now = { beats: s.screenCaptureHeartbeats, delivered: s.screenCaptureDelivered, encoded: s.screenFramesEncoded, sent: s.screenFramesSent };
286 if (prev) console.log(`display: +${now.beats - prev.beats} reports, +${now.delivered - prev.delivered} delivered, +${now.encoded - prev.encoded} encoded, +${now.sent - prev.sent} sent, ${s.screenSendWidth}x${s.screenSendHeight}, limit ${s.screenLimitation} target ${s.screenTargetBitrate} kf ${s.screenKeyframes} enc ${s.screenEncodeMsTenths / 10} ms, watchdog r${s.screenWatchdogCaptureRestarts} k${s.screenWatchdogKeyframes} e${s.screenWatchdogEncoderRecoveries} a${s.screenWatchdogReAdds}`);
287 prev = now;
288 }, Number(process.env.SCREEN_TICK_MS || 5000));
289 await watchFor(SOAK, 'display');
290 clearInterval(tick);
291 } else if (scenario === 'renewals' || scenario === 'resume') {
292 // §15.23: a renewal or a resume is never said as "Reconnecting…", by
293 // the app or the browser, while the core's phase does go through it.
294 const said = [];
295 let phases = 0;
296 const saidTick = setInterval(async () => {
297 if (sample?.phase === 'reconnecting') phases += 1;
298 if (sample?.reconnecting || sample?.reconnectingPeers) said.push('app');
299 try {
300 const r = (await page.evaluate(() => window.meet.state())).reconnect;
301 if (r.call || r.peers.length) said.push('browser');
302 } catch {}
303 }, 250);
304 await watchFor(SOAK, scenario);
305 clearInterval(saidTick);
306 console.log(`reconnecting: the app's core was mid-resume at ${phases} samples; said by ${JSON.stringify([...new Set(said)])}`);
307 if (asserting) assert.equal(said.length, 0, 'a renewal or resume was said as Reconnecting: ' + said.join(','));
308 console.log(`ICE restarts seen by the browser: ${restarts}`);
309 const ours = sample?.stats.iceRestarts || 0;
310 console.log(`ICE restarts the app started: ${ours}`);
311 if (asserting && scenario === 'renewals') {
312 // Credentials renewed every ~17 s: restarts mid-share, from both
313 // sides, and the app's own nowhere near one per stream renewal
314 // (every 10 s), which is what 0.4.1 did.
315 assert.ok(restarts >= 2, 'relay credentials were renewed by ICE restarts mid-share: ' + restarts);
316 assert.ok(ours >= 1 && ours <= Math.ceil(SOAK / 16) + 1, 'the app restarts ICE only when a renewal is due: ' + ours);
317 }
318 if (asserting && scenario === 'resume') assert.equal(restarts, 0, 'a resume alone restarts nothing');
319 } else if (scenario === 'capture') {
320 await watchFor(5, 'before capture stall');
321 native.stdin.write('screen-stall\n');
322 await wait(() => replies.some((r) => r.screenStalled === true), 'the synthetic screen stops');
323 await recovered('the app restarts a stalled capture and the browser decodes again');
324 await wait(() => (sample?.stats.screenWatchdogCaptureRestarts || 0) > 0, 'the watchdog says it restarted the capture', 5);
325 console.log('PASS a stalled capture was restarted without a re-share');
326 } else if (scenario === 'encoder') {
327 await watchFor(5, 'before encoder stall');
328 native.stdin.write('screen-encoder-stall\n');
329 await wait(() => replies.some((r) => r.encoderStalled === true), 'the encoder stops');
330 await recovered('the app recovers a stalled encoder and the browser decodes again');
331 await wait(() => (sample?.stats.screenWatchdogKeyframes || 0) + (sample?.stats.screenWatchdogEncoderRecoveries || 0) > 0,
332 'the watchdog says it recovered the encoder', 5);
333 console.log('PASS a stalled encoder was recovered without a re-share');
334 } else if (scenario === 'soak') {
335 // §15.22's search for the cause: a long share with everything that
336 // moves under it moving. What matters is not whether a freeze
337 // happened but what it took to end it — the ladder's counts at each
338 // freeze say whether keyframes were enough.
339 const modes = ['balanced', 'motion', 'detail'];
340 const uplinks = [0, 1500000, 600000, 0, 3000000, 900000];
341 const started = Date.now();
342 const notices = new Set();
343 let step = 0;
344 const tick = setInterval(() => {
345 step += 1;
346 const mode = modes[step % modes.length];
347 const up = uplinks[step % uplinks.length];
348 native.stdin.write(`screen-mode ${mode}\n`);
349 native.stdin.write(`uplink ${up}\n`);
350 const st = sample?.stats || {};
351 console.log(`soak ${Math.round((Date.now() - started) / 1000)} s: mode ${mode}, uplink ${up || 'open'} (was sending ${st.screenSendWidth}x${st.screenSendHeight} at ${(st.screenSendFpsTenths || 0) / 10} fps, limitation ${st.screenLimitation})`);
352 }, Number(process.env.SCREEN_SOAK_STEP_MS || 45000));
353 const noticeTick = setInterval(() => { if (sample?.screenRecovery) notices.add(sample.screenRecovery); }, 500);
354 await watchFor(SOAK, 'soak');
355 clearInterval(tick);
356 clearInterval(noticeTick);
357 native.stdin.write('uplink 0\n');
358 const st = sample?.stats || {};
359 console.log(`SOAK app: ICE restarts ${st.iceRestarts}, stall reports ${st.screenStallReports}, keyframes ${st.screenWatchdogKeyframes}, fresh encoders ${st.screenWatchdogEncoderRecoveries}, re-adds ${st.screenWatchdogReAdds}, rebuilds ${st.screenWatchdogRebuilds}, shares again ${st.screenWatchdogReshares}, given up ${st.screenWatchdogFailures}, capture restarts ${st.screenWatchdogCaptureRestarts}`);
360 console.log(`SOAK browser ICE restarts ${restarts}; notices at the app: ${JSON.stringify([...notices])}`);
361 console.log('the browser\u2019s screen log:\n' + (await page.evaluate(() => window.meet.diagnostics())).split('## Screen')[1]);
362 if (asserting) {
363 assert.equal(st.screenWatchdogFailures || 0, 0, 'the app gave up on the browser\u2019s view');
364 assert.equal(freezes.filter((f) => f.open).length, 0, 'the screen froze and never came back');
365 }
366 } else if (scenario === 'wedge' || scenario === 'wedge-sticky') {
367 await watchFor(5, 'before the wedge');
368 const sticky = scenario === 'wedge-sticky';
369 const keyframes = sample?.stats.screenWatchdogKeyframes || 0;
370 const notices = new Set();
371 const note = () => { if (sample?.screenRecovery) notices.add(sample.screenRecovery); };
372 const wedgedAt = Date.now();
373 const n = await page.evaluate((s) => window.__wedgeScreens(s), sticky);
374 assert.ok(n >= 1, 'the browser\u2019s screen receiver was wedged');
375 await wait(async () => (await page.evaluate(() => window.meet.state().screenStalled)).length === 1,
376 'the browser reports the app\u2019s screen stalled', 15);
377 if (!sticky) {
378 // Painted frames on the share tile, counted across a new tile.
379 const progress = await progressOf(() => received().then((r) => r.frames));
380 await wait(async () => { note(); return (await progress()) > 15; },
381 'the browser decodes the app\u2019s screen again, without a share again', 30);
382 console.log(`the browser decoding again ${Date.now() - wedgedAt} ms after the wedge: rebuilds ${sample?.stats.screenWatchdogRebuilds}, shares again ${sample?.stats.screenWatchdogReshares}, keyframes ${(sample?.stats.screenWatchdogKeyframes || 0) - keyframes}`);
383 assert.ok((sample?.stats.screenWatchdogKeyframes || 0) > keyframes, 'keyframes were tried first');
384 assert.ok((sample?.stats.screenWatchdogRebuilds || 0) > 0, 'the rebuild is what mended it');
385 await wait(async () => (await page.evaluate(() => window.meet.state().screenStalled)).length === 0,
386 'the browser clears its report', 20);
387 await wait(() => { note(); return sample?.screenRecovery === ''; }, 'the app\u2019s notice clears', 20);
388 console.log('notices seen at the app: ' + JSON.stringify([...notices]));
389 assert.ok([...notices].some((x) => x.includes('recovering')), 'the notice said recovering');
390 assert.ok([...notices].some((x) => x.includes('Restarting your share for')), 'the notice said restarting');
391 console.log('PASS a wedged browser receiver was restored by the app\u2019s rebuild');
392 } else {
393 await wait(() => { note(); return (sample?.screenRecovery || '').includes('Couldn\u2019t restore'); },
394 'the app says it could not restore the browser\u2019s view', 60);
395 console.log('notices seen at the app: ' + JSON.stringify([...notices]));
396 assert.ok((sample?.stats.screenWatchdogRebuilds || 0) > 0 && (sample?.stats.screenWatchdogReshares || 0) > 0,
397 'a rebuild and a share again were tried first');
398 assert.ok([...notices].some((x) => x.includes('Restarting your share for')), 'the notice said restarting');
399 await page.evaluate(() => window.__releaseWedge());
400 await recovered('the browser decodes again once the wedge is lifted');
401 await wait(() => sample?.screenRecovery === '', 'the app\u2019s notice clears once the view is back', 30);
402 console.log('PASS the app said it could not restore a view nothing could, and cleared when it came back');
403 }
404 } else if (scenario === 'loss') {
405 await watchFor(5, 'before loss');
406 // The browser's watch treats the app's screen as frozen, as it would
407 // a picture stuck after lost packets, and reports it (screenStalled);
408 // the app must hear it and answer with a keyframe, which the
409 // browser's decoder counts.
410 const before = sample?.stats.screenWatchdogKeyframes || 0;
411 const keyframes = (await received()).screen?.keyframes || 0;
412 await page.evaluate(() => window.meet.stallScreenForTest(8000));
413 await wait(async () => (await page.evaluate(() => window.meet.state().screenStalled)).length === 1,
414 'the browser reports the app\u2019s screen stalled', 10);
415 await wait(() => (sample?.stats.screenStallReports || 0) > 0, 'the app hears the browser\u2019s stall report', 10);
416 await wait(() => (sample?.stats.screenWatchdogKeyframes || 0) > before, 'the app forces a keyframe for it', 10);
417 await wait(async () => ((await received()).screen?.keyframes || 0) > keyframes, 'the browser decodes the keyframe', 10);
418 await wait(async () => (await page.evaluate(() => window.meet.state().screenStalled)).length === 0,
419 'the browser clears its report once frames move', 20);
420 await recovered('the browser decodes again');
421 console.log('PASS a receiver\u2019s stall report was answered with a keyframe and cleared');
422 } else {
423 throw new Error('unknown scenario ' + scenario);
424 }
425
426 // Whatever the scenario, the screen has to be decoding at the end.
427 await recovered('the app’s screen is still decoding at the end');
428 const open = freezes.filter((f) => f.open);
429 console.log(`SUMMARY ${scenario}: ${freezes.length} freezes, longest ${Math.max(0, ...freezes.map((f) => f.ms))} ms, restarts ${restarts}`);
430 if (asserting && (scenario === 'renewals' || scenario === 'resume')) {
431 assert.equal(open.length, 0, 'the screen froze and never came back');
432 assert.equal(freezes.length, 0, 'the screen froze during ' + scenario + ': ' + JSON.stringify(freezes.map((f) => f.ms)));
433 }
434 console.log(`PASS ${scenario}: the app’s screen kept arriving`);
435} catch (err) {
436 if (!(err instanceof Done)) {
437 failed = true;
438 console.log('FAIL', err.message);
439 }
440} finally {
441 if (native) {
442 native.stdin.write('leave\n');
443 await new Promise((r) => setTimeout(r, 1000));
444 native.kill('SIGTERM');
445 }
446 await browser.close();
447 if (failed) process.exit(1);
448}
449
450// Done ends a scenario that has passed before the app-shares path below
451// it: thrown, and caught as not a failure.
452function Done() {}
453
454// progressOf counts how far a counter has moved since now, across a
455// restart from zero (a new tile, a new receiver): a fall is taken as a
456// new count starting.
457async function progressOf(read) {
458 let last = await read();
459 let total = 0;
460 return async () => {
461 const now = await read();
462 total += now >= last ? now - last : now;
463 last = now;
464 return total;
465 };
466}
467
468// webShares is the web-* scenarios: the browser shares its screen (a fake
469// monitor), the app watches, the app's screen decoder is wedged, and the
470// browser's own ladder (§15.22) has to put it right — or, sticky, say it
471// cannot, and clear once the wedge is lifted.
472async function webShares(page, native, current, replies, wait, sticky) {
473 const stat = (k) => current()?.stats[k] || 0;
474 await page.evaluate(() => { window.__h264Screen = true; });
475 await page.hover('#share');
476 await page.click('#share');
477 await wait(() => stat('remoteScreens') === 1 && stat('screenFramesDecoded') > 15, 'the app decodes the browser\u2019s screen', 30);
478 console.log('PASS the app decodes the browser\u2019s screen');
479 await new Promise((r) => setTimeout(r, 5000));
480 const s0 = () => page.evaluate(() => window.meet.state());
481 const keyframes = (await s0()).shareRecoveries.keyframes;
482 const wedgedAt = Date.now();
483 native.stdin.write(sticky ? 'screen-decoder-wedge sticky\n' : 'screen-decoder-wedge\n');
484 await wait(() => replies.some((r) => (r.decoderWedged || 0) >= 1), 'the app\u2019s screen decoder is wedged', 10);
485 await wait(() => stat('screenStalledHere') === 1, 'the app reports the browser\u2019s screen stalled (the wedge hit the screen)', 15);
486 const notices = new Set();
487 const note = async () => {
488 const s = await s0();
489 if (s.shareRecovery) notices.add(s.shareRecovery);
490 return s;
491 };
492 if (!sticky) {
493 const base = stat('screenFramesDecodedTotal');
494 await wait(async () => { await note(); return stat('screenFramesDecodedTotal') > base + 15; },
495 'the app decodes the browser\u2019s screen again, without a share again', 30);
496 const s = await note();
497 console.log(`the app decoding again ${Date.now() - wedgedAt} ms after the wedge: ${JSON.stringify(s.shareRecoveries)}`);
498 assert.ok(s.shareRecoveries.keyframes > keyframes, 'keyframes were tried first');
499 assert.ok(s.shareRecoveries.rebuilds > 0, 'the rebuild is what mended it');
500 await wait(() => stat('screenStalledHere') === 0, 'the app clears its report', 20);
501 await wait(async () => (await note()).shareRecovery === '', 'the browser\u2019s notice clears', 20);
502 console.log('notices seen at the browser: ' + JSON.stringify([...notices]));
503 assert.ok([...notices].some((x) => x.includes('recovering')), 'the notice said recovering');
504 assert.ok([...notices].some((x) => x.includes('Restarting your share for')), 'the notice said restarting');
505 } else {
506 await wait(async () => (await note()).shareRecovery.includes('Couldn\u2019t restore'),
507 'the browser says it could not restore the app\u2019s view', 60);
508 const s = await note();
509 console.log('notices seen at the browser: ' + JSON.stringify([...notices]) + ' ' + JSON.stringify(s.shareRecoveries));
510 assert.ok(s.shareRecoveries.rebuilds > 0 && s.shareRecoveries.reshares > 0, 'a rebuild and a share again were tried first');
511 assert.ok([...notices].some((x) => x.includes('Restarting your share for')), 'the notice said restarting');
512 native.stdin.write('screen-decoder-release\n');
513 const base = stat('screenFramesDecodedTotal');
514 await wait(() => stat('screenFramesDecodedTotal') > base + 10, 'the app decodes again once the wedge is lifted', 30);
515 await wait(async () => (await note()).shareRecovery === '', 'the browser\u2019s notice clears once the view is back', 30);
516 }
517 console.log('the browser\u2019s diagnostics:\n' + (await page.evaluate(() => window.meet.diagnostics())).split('## Screen')[1]);
518}
519
520// webSoak is `soak` with the browser sharing and the app watching: the
521// app's received screen, counted across rebuilds, watched for freezes
522// while the renewals run and the browser's mode is cycled.
523async function webSoak(page, native, current, wait) {
524 const stat = (k) => current()?.stats[k] || 0;
525 await page.hover('#share');
526 await page.click('#share');
527 await wait(() => stat('remoteScreens') === 1 && stat('screenFramesDecoded') > 15, 'the app decodes the browser\u2019s screen', 30);
528 const modes = ['balanced', 'motion', 'detail'];
529 const started = Date.now();
530 let step = 0;
531 const notices = new Set();
532 const freezes = [];
533 let last = stat('screenFramesDecodedTotal');
534 let moved = Date.now();
535 let frozen = null;
536 let nextStep = Date.now() + Number(process.env.SCREEN_SOAK_STEP_MS || 45000);
537 while (Date.now() - started < SOAK * 1000) {
538 await new Promise((r) => setTimeout(r, 1000));
539 const s = await page.evaluate(() => window.meet.state());
540 if (s.shareRecovery) notices.add(s.shareRecovery);
541 if (Date.now() >= nextStep) {
542 step += 1;
543 const mode = modes[step % modes.length];
544 await page.evaluate((m) => {
545 const el = document.getElementById('pick-share-mode');
546 if (el) { el.value = m; el.dispatchEvent(new Event('change', { bubbles: true })); }
547 }, mode);
548 console.log(`web-soak ${Math.round((Date.now() - started) / 1000)} s: the browser\u2019s mode ${mode}`);
549 nextStep = Date.now() + Number(process.env.SCREEN_SOAK_STEP_MS || 45000);
550 }
551 const now = stat('screenFramesDecodedTotal');
552 if (now > last) {
553 if (frozen) {
554 frozen.ms = Date.now() - frozen.since;
555 freezes.push(frozen);
556 console.log(`FREEZE web-soak: ${frozen.ms} ms, then frames again; browser ladder ${JSON.stringify(s.shareRecoveries)}`);
557 frozen = null;
558 }
559 moved = Date.now();
560 } else if (!frozen && Date.now() - moved > FREEZE_MS) {
561 frozen = { since: moved };
562 console.log(`FROZEN web-soak: no screen frame at the app for ${Date.now() - moved} ms; app stalled-here ${stat('screenStalledHere')}; browser ladder ${JSON.stringify(s.shareRecoveries)}`);
563 }
564 last = now;
565 }
566 const s = await page.evaluate(() => window.meet.state());
567 console.log(`SUMMARY web-soak: ${freezes.length} freezes, longest ${Math.max(0, ...freezes.map((f) => f.ms))} ms, open ${!!frozen}; app ICE restarts ${stat('iceRestarts')}, pictures attached again ${stat('screenReattaches')}; browser ladder ${JSON.stringify(s.shareRecoveries)}; notices ${JSON.stringify([...notices])}`);
568 console.log('the browser\u2019s screen log:\n' + (await page.evaluate(() => window.meet.diagnostics())).split('## Screen')[1]);
569 if (asserting) {
570 assert.equal(s.shareRecoveries.failures, 0, 'the browser gave up on the app\u2019s view');
571 assert.ok(!frozen, 'the app\u2019s screen froze and never came back');
572 }
573}
574