// native-screen-receivers.mjs — the Mac app shares a screen to a browser, // WebKit or Chromium, and the browser's own screen watch is held to what // it actually shows. // // Written for 2026-10-21: Paul (Mac 0.4.10) shared to Farshad in Safari, // who said "screen sharing keeps getting interrupted". Paul's screen log // had Safari reporting the screen stalled every 40 s or so, keyframes, // rebuilds and shares again answering it, and the report back 25 s later. // // Scenarios, one per run (argv[4]): // still a still page repeated once a second, as the Mac's capture // repeats one (CallsInterop `screen-still 0`) // slow the same page, changed every five seconds (`screen-still 5`) // motion the 30 fps scrolling page (`screen-motion`) // encoder the moving page, and then the app's screen encoding switched // off behind its back (`screen-encoder-stall`): a stall that is // real and the sender's, as 2026-10-21's was, which the browser // must report and the app's own watch must mend // wedge (Chromium only: WebKit's encoded transform does not take hold // of a receiver already started) the still page, and then every // frame of the browser's screen receiver swallowed before its // decoder: a stall that is real and the receiver's // // SCREEN_ENGINE is webkit (the default) or chromium; SCREEN_MODE the // share's "Optimise for" (balanced by default); SCREEN_SECONDS how long // the share is watched (60). Every second it logs the browser's screen // statistics and what its tile is painting (requestVideoFrameCallback // and the element's clock), so a stall can be told apart from a screen // with nothing new on it. SCREEN_ASSERT=0 only logs. // // Run by TestNativeMacScreenReceivers (make native-webkit). import { webkit, chromium } from 'playwright'; import { spawn } from 'node:child_process'; import { createInterface } from 'node:readline'; import assert from 'node:assert/strict'; const [origin, room, binary, scenario] = process.argv.slice(2); const engine = process.env.SCREEN_ENGINE || 'webkit'; const SECONDS = Number(process.env.SCREEN_SECONDS || 60); const asserting = process.env.SCREEN_ASSERT !== '0'; const verbose = process.env.SCREEN_VERBOSE === '1'; const browser = engine === 'chromium' ? await chromium.launch({ headless: true, args: [ '--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', '--autoplay-policy=no-user-gesture-required', '--disable-features=WebRtcHideLocalIpsWithMdns', '--mute-audio'] }) : await webkit.launch({ headless: true }); // bypassCSP: the wedge's encoded transform runs in a worker made from a // blob, which the page's own policy would refuse. The gate's, never the // page's. const context = await browser.newContext({ permissions: ['camera', 'microphone'], bypassCSP: true }); await context.addCookies([{ name: process.env.CALLS_COOKIE_NAME, value: process.env.CALLS_COOKIE_A, url: origin }]); const page = await context.newPage(); await page.addInitScript((wedging) => { const Native = window.RTCPeerConnection; window.__pcs = new Set(); // The wedge: every screen receiver gets a pass-through transform as it // arrives (WebKit and Chromium both take one only before it starts), // and __wedge(true) has them all swallow every frame. let worker = null; const transforms = []; const work = () => { if (!worker) { const code = [ 'let drop = false;', 'onmessage = (m) => { drop = !!m.data; };', 'onrtctransform = (e) => {', ' e.transformer.readable.pipeThrough(new TransformStream({ transform(f, c) { if (!drop) c.enqueue(f); } }))', ' .pipeTo(e.transformer.writable);', '};', ].join('\n'); worker = new Worker(URL.createObjectURL(new Blob([code], { type: 'text/javascript' }))); } return worker; }; window.__wedge = (on) => { work().postMessage(!!on); return transforms.length; }; window.RTCPeerConnection = class extends Native { constructor(...args) { super(...args); window.__pcs.add(this); this.addEventListener('track', (e) => { const tx = e.transceiver; if (!wedging || !tx || tx.receiver.track.kind !== 'video' || tx.direction !== 'recvonly') return; try { tx.receiver.transform = new RTCRtpScriptTransform(work(), {}); transforms.push(tx); } catch {} }); } }; // What the screen's tile paints: frames presented // (requestVideoFrameCallback) and the element's own clock, read off the // element that is showing the screen whatever the room does to it. window.__painted = { frames: 0, el: null }; const arm = (el) => { if (window.__painted.el === el || !el.requestVideoFrameCallback) return; window.__painted.el = el; const step = () => { if (window.__painted.el !== el) return; window.__painted.frames += 1; el.requestVideoFrameCallback(step); }; el.requestVideoFrameCallback(step); }; setInterval(() => { for (const el of document.querySelectorAll('video')) { const tile = el.closest('[data-tile]'); if (tile && /#share$/.test(tile.dataset.tile || '')) arm(el); } }, 250); }, scenario === 'wedge'); let native; let sample = null; let exited = false; const wait = async (predicate, label, seconds = 40) => { const until = Date.now() + seconds * 1000; while (Date.now() < until) { if (exited) throw new Error('native executable exited'); if (await predicate()) return; await new Promise((r) => setTimeout(r, 250)); } throw new Error(label + ': ' + JSON.stringify(sample && sample.stats)); }; // The browser's screen, from its own connection: the inbound video whose // mid is a recvonly transceiver's (the camera's is sendrecv). const screen = () => page.evaluate(async () => { const out = { stats: null, painted: window.__painted.frames, time: 0, stalled: [], tile: false }; const el = window.__painted.el; if (el && el.isConnected) { out.time = el.currentTime; out.tile = true; out.paused = el.paused; out.size = el.videoWidth + 'x' + el.videoHeight; } for (const pc of window.__pcs) { if (pc.connectionState === 'closed') continue; const mids = new Set(pc.getTransceivers() .filter((t) => t.receiver.track && t.receiver.track.kind === 'video' && t.direction === 'recvonly' && t.currentDirection !== 'stopped') .map((t) => t.mid)); const all = await pc.getStats(); for (const r of all.values()) { if (r.type === 'inbound-rtp' && r.kind === 'video' && !mids.has(r.mid)) out.camera = r.framesDecoded || 0; if (r.type === 'candidate-pair' && r.nominated && r.state === 'succeeded') out.inKbps = Math.round((r.availableIncomingBitrate || 0) / 1000); if (r.type !== 'inbound-rtp' || r.kind !== 'video' || !mids.has(r.mid)) continue; const c = r.codecId && all.get(r.codecId); out.codec = c ? c.mimeType + ' ' + (c.sdpFmtpLine || '') : ''; out.stats = { mid: r.mid, packets: r.packetsReceived || 0, received: r.framesReceived || 0, decoded: r.framesDecoded || 0, dropped: r.framesDropped || 0, keyframes: r.keyFramesDecoded || 0, freezes: r.freezeCount || 0, width: r.frameWidth || 0, height: r.frameHeight || 0, decoder: r.decoderImplementation || '', pli: r.pliCount || 0, fps: r.framesPerSecond || 0, assembled: r.framesAssembledFromMultiplePackets }; } } const s = window.meet.state(); out.screenWatch = s.screenWatch || null; return out; }); class Skip extends Error {} let nudge = null; const stallLines = []; try { page.on('pageerror', (e) => console.log('page error', String(e))); page.on('console', (m) => { const text = m.text(); if (!/^calls: /.test(text)) return; if (/screen/.test(text)) { console.log(`[${engine}] ${text}`); if (/stalled here: reporting it/.test(text)) stallLines.push(text); } }); await page.goto(`${origin}/m/${room}`); await page.waitForFunction(() => !!window.meet); native = spawn(binary, [], { stdio: ['pipe', 'pipe', 'pipe'] }); native.on('exit', () => { exited = true; }); native.stdin.write(process.env.CALLS_NATIVE_INPUT + '\n'); createInterface({ input: native.stdout }).on('line', (text) => { try { const value = JSON.parse(text); if (value.stats) sample = value; } catch {} }); native.stderr.resume(); nudge = setInterval(() => { page.mouse.click(5, 300).catch(() => {}); }, 2000); await wait(() => sample && sample.stats.framesDecoded > 15, 'the app decodes the browser'); native.stdin.write(`screen-mode ${process.env.SCREEN_MODE || 'balanced'}\n`); if (scenario === 'wedge' && engine !== 'chromium') { console.log(`SKIP wedge on ${engine}: its encoded transform does not take hold of a started receiver`); throw new Skip(); } const moving = scenario === 'motion' || scenario === 'encoder'; native.stdin.write(moving ? 'screen-motion\n' : scenario === 'slow' ? 'screen-still 5\n' : 'screen-still 0\n'); await wait(() => sample && sample.sharingScreen === true, 'the app says it is sharing'); await wait(async () => { const s = await screen(); return s.stats && s.stats.decoded > 2; }, `${engine} decodes the app’s screen`); console.log('screen codec ' + (await screen()).codec); console.log(`PASS ${engine} decodes the app’s screen (${scenario}, ${process.env.SCREEN_MODE || 'balanced'})`); const w = (sample && sample.stats) || {}; const ladder = () => { const s = (sample && sample.stats) || {}; return { reports: s.screenStallReports || 0, keyframes: s.screenWatchdogKeyframes || 0, rebuilds: s.screenWatchdogRebuilds || 0, reshares: s.screenWatchdogReshares || 0, failures: s.screenWatchdogFailures || 0 }; }; const start = ladder(); let prev = await screen(); let paintedQuiet = 0; let longestPaintedQuiet = 0; const watch = async (seconds, label) => { for (let i = 0; i < seconds; i += 1) { await new Promise((r) => setTimeout(r, 1000)); const now = await screen(); const a = now.stats || {}; const b = prev.stats || {}; const same = a.mid === b.mid; const d = (k) => (same ? (a[k] || 0) - (b[k] || 0) : 'new ' + (a[k] || 0)); const painted = now.painted - prev.painted; paintedQuiet = painted > 0 ? 0 : paintedQuiet + 1; longestPaintedQuiet = Math.max(longestPaintedQuiet, paintedQuiet); const s = (sample && sample.stats) || {}; if (verbose || i % 5 === 4 || painted === 0) { console.log(`${label} t=${i + 1}s mid ${a.mid} ${a.width}x${a.height} ${a.decoder} | packets +${d('packets')} received +${d('received')} ` + `decoded +${d('decoded')} dropped +${d('dropped')} keyframes +${d('keyframes')} freezes ${a.freezes} pli ${a.pli} | ` + `painted +${painted} clock +${(now.time - prev.time).toFixed(2)} ${now.size || ''} | app sent ${s.screenSendWidth}x${s.screenSendHeight} ` + `fps ${(s.screenSendFpsTenths || 0) / 10} limit ${s.screenLimitation} target ${Math.round((s.screenTargetBitrate || 0) / 1000)}k ` + `sent ${Math.round((s.screenSentBitrate || 0) / 1000)}k captured ${s.screenFramesCaptured} encoded ${s.screenFramesEncoded} sentFrames ${s.screenFramesSent} | camera +${(now.camera || 0) - (prev.camera || 0)} | ladder ${JSON.stringify(ladder())}`); } prev = now; } }; if (scenario === 'encoder') { await watch(10, 'before'); native.stdin.write('screen-encoder-stall\n'); await watch(12, 'stopped'); const reported = ladder().reports - start.reports; const mended = (sample && sample.stats.screenWatchdogKeyframes) || 0; console.log(`the app's own watch: ${JSON.stringify(ladder())}, keyframes asked ${mended}`); const base = (await screen()).painted; await wait(async () => (await screen()).painted > base + 10, `${engine} paints the screen again with nobody sharing again`, 30); if (asserting) assert.equal(ladder().reshares - start.reshares, 0, 'mended without a share again'); console.log(`PASS ${engine}: a screen that stopped leaving was mended (reports ${reported})`); } else if (scenario === 'wedge') { await watch(8, 'before'); const n = await page.evaluate(() => window.__wedge(true)); console.log(`wedged ${n} screen receiver(s)`); await watch(14, 'wedged'); const reported = ladder().reports - start.reports; if (asserting) assert.ok(reported >= 1, `the wedged screen is reported (${reported})`); console.log(`PASS ${engine}: a genuine stall is still reported (${reported})`); await page.evaluate(() => window.__wedge(false)); const base = (await screen()).painted; await wait(async () => (await screen()).painted > base + 2, `${engine} paints the screen again once the wedge lifts`, 30); const cleared = async () => !stallLines.length || (await page.evaluate(() => !(window.meet.state().screenStalled || []).length)); await wait(cleared, 'the report clears', 20); console.log(`PASS ${engine}: the wedged screen recovered`); } else { await watch(SECONDS, scenario); const end = ladder(); const reports = end.reports - start.reports; console.log(`${engine} ${scenario}: ${reports} stall report(s) at the app, ladder ${JSON.stringify(end)}; ` + `longest stretch with nothing painted ${longestPaintedQuiet} s; reported here ${stallLines.length}`); if (asserting) { assert.equal(reports, 0, `a ${scenario} screen that is being painted is never reported stalled (${reports})`); assert.equal(end.rebuilds - start.rebuilds + end.reshares - start.reshares, 0, 'nothing was rebuilt or shared again'); } console.log(`PASS ${engine} ${scenario}: no stall reported, nothing rebuilt`); } void w; clearInterval(nudge); native.stdin.write('leave\n'); await new Promise((r) => setTimeout(r, 1000)); } catch (err) { if (!(err instanceof Skip)) { console.log('FAIL ' + (err && err.message ? err.message : String(err))); process.exitCode = 1; } } finally { if (nudge) clearInterval(nudge); if (native && !exited) native.kill(); await browser.close(); }