| 1 | // native-screen-receivers.mjs — the Mac app shares a screen to a browser, |
| 2 | // WebKit or Chromium, and the browser's own screen watch is held to what |
| 3 | // it actually shows. |
| 4 | // |
| 5 | // Written for 2026-10-21: Paul (Mac 0.4.10) shared to Farshad in Safari, |
| 6 | // who said "screen sharing keeps getting interrupted". Paul's screen log |
| 7 | // had Safari reporting the screen stalled every 40 s or so, keyframes, |
| 8 | // rebuilds and shares again answering it, and the report back 25 s later. |
| 9 | // |
| 10 | // Scenarios, one per run (argv[4]): |
| 11 | // still a still page repeated once a second, as the Mac's capture |
| 12 | // repeats one (CallsInterop `screen-still 0`) |
| 13 | // slow the same page, changed every five seconds (`screen-still 5`) |
| 14 | // motion the 30 fps scrolling page (`screen-motion`) |
| 15 | // encoder the moving page, and then the app's screen encoding switched |
| 16 | // off behind its back (`screen-encoder-stall`): a stall that is |
| 17 | // real and the sender's, as 2026-10-21's was, which the browser |
| 18 | // must report and the app's own watch must mend |
| 19 | // wedge (Chromium only: WebKit's encoded transform does not take hold |
| 20 | // of a receiver already started) the still page, and then every |
| 21 | // frame of the browser's screen receiver swallowed before its |
| 22 | // decoder: a stall that is real and the receiver's |
| 23 | // |
| 24 | // SCREEN_ENGINE is webkit (the default) or chromium; SCREEN_MODE the |
| 25 | // share's "Optimise for" (balanced by default); SCREEN_SECONDS how long |
| 26 | // the share is watched (60). Every second it logs the browser's screen |
| 27 | // statistics and what its tile is painting (requestVideoFrameCallback |
| 28 | // and the element's clock), so a stall can be told apart from a screen |
| 29 | // with nothing new on it. SCREEN_ASSERT=0 only logs. |
| 30 | // |
| 31 | // Run by TestNativeMacScreenReceivers (make native-webkit). |
| 32 | import { webkit, chromium } from 'playwright'; |
| 33 | import { spawn } from 'node:child_process'; |
| 34 | import { createInterface } from 'node:readline'; |
| 35 | import assert from 'node:assert/strict'; |
| 36 | |
| 37 | const [origin, room, binary, scenario] = process.argv.slice(2); |
| 38 | const engine = process.env.SCREEN_ENGINE || 'webkit'; |
| 39 | const SECONDS = Number(process.env.SCREEN_SECONDS || 60); |
| 40 | const asserting = process.env.SCREEN_ASSERT !== '0'; |
| 41 | const verbose = process.env.SCREEN_VERBOSE === '1'; |
| 42 | |
| 43 | const browser = engine === 'chromium' |
| 44 | ? await chromium.launch({ headless: true, args: [ |
| 45 | '--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', |
| 46 | '--autoplay-policy=no-user-gesture-required', '--disable-features=WebRtcHideLocalIpsWithMdns', '--mute-audio'] }) |
| 47 | : await webkit.launch({ headless: true }); |
| 48 | // bypassCSP: the wedge's encoded transform runs in a worker made from a |
| 49 | // blob, which the page's own policy would refuse. The gate's, never the |
| 50 | // page's. |
| 51 | const context = await browser.newContext({ permissions: ['camera', 'microphone'], bypassCSP: true }); |
| 52 | await context.addCookies([{ name: process.env.CALLS_COOKIE_NAME, value: process.env.CALLS_COOKIE_A, url: origin }]); |
| 53 | const page = await context.newPage(); |
| 54 | await page.addInitScript((wedging) => { |
| 55 | const Native = window.RTCPeerConnection; |
| 56 | window.__pcs = new Set(); |
| 57 | // The wedge: every screen receiver gets a pass-through transform as it |
| 58 | // arrives (WebKit and Chromium both take one only before it starts), |
| 59 | // and __wedge(true) has them all swallow every frame. |
| 60 | let worker = null; |
| 61 | const transforms = []; |
| 62 | const work = () => { |
| 63 | if (!worker) { |
| 64 | const code = [ |
| 65 | 'let drop = false;', |
| 66 | 'onmessage = (m) => { drop = !!m.data; };', |
| 67 | 'onrtctransform = (e) => {', |
| 68 | ' e.transformer.readable.pipeThrough(new TransformStream({ transform(f, c) { if (!drop) c.enqueue(f); } }))', |
| 69 | ' .pipeTo(e.transformer.writable);', |
| 70 | '};', |
| 71 | ].join('\n'); |
| 72 | worker = new Worker(URL.createObjectURL(new Blob([code], { type: 'text/javascript' }))); |
| 73 | } |
| 74 | return worker; |
| 75 | }; |
| 76 | window.__wedge = (on) => { work().postMessage(!!on); return transforms.length; }; |
| 77 | window.RTCPeerConnection = class extends Native { |
| 78 | constructor(...args) { |
| 79 | super(...args); |
| 80 | window.__pcs.add(this); |
| 81 | this.addEventListener('track', (e) => { |
| 82 | const tx = e.transceiver; |
| 83 | if (!wedging || !tx || tx.receiver.track.kind !== 'video' || tx.direction !== 'recvonly') return; |
| 84 | try { |
| 85 | tx.receiver.transform = new RTCRtpScriptTransform(work(), {}); |
| 86 | transforms.push(tx); |
| 87 | } catch {} |
| 88 | }); |
| 89 | } |
| 90 | }; |
| 91 | // What the screen's tile paints: frames presented |
| 92 | // (requestVideoFrameCallback) and the element's own clock, read off the |
| 93 | // element that is showing the screen whatever the room does to it. |
| 94 | window.__painted = { frames: 0, el: null }; |
| 95 | const arm = (el) => { |
| 96 | if (window.__painted.el === el || !el.requestVideoFrameCallback) return; |
| 97 | window.__painted.el = el; |
| 98 | const step = () => { |
| 99 | if (window.__painted.el !== el) return; |
| 100 | window.__painted.frames += 1; |
| 101 | el.requestVideoFrameCallback(step); |
| 102 | }; |
| 103 | el.requestVideoFrameCallback(step); |
| 104 | }; |
| 105 | setInterval(() => { |
| 106 | for (const el of document.querySelectorAll('video')) { |
| 107 | const tile = el.closest('[data-tile]'); |
| 108 | if (tile && /#share$/.test(tile.dataset.tile || '')) arm(el); |
| 109 | } |
| 110 | }, 250); |
| 111 | }, scenario === 'wedge'); |
| 112 | |
| 113 | let native; |
| 114 | let sample = null; |
| 115 | let exited = false; |
| 116 | const wait = async (predicate, label, seconds = 40) => { |
| 117 | const until = Date.now() + seconds * 1000; |
| 118 | while (Date.now() < until) { |
| 119 | if (exited) throw new Error('native executable exited'); |
| 120 | if (await predicate()) return; |
| 121 | await new Promise((r) => setTimeout(r, 250)); |
| 122 | } |
| 123 | throw new Error(label + ': ' + JSON.stringify(sample && sample.stats)); |
| 124 | }; |
| 125 | |
| 126 | // The browser's screen, from its own connection: the inbound video whose |
| 127 | // mid is a recvonly transceiver's (the camera's is sendrecv). |
| 128 | const screen = () => page.evaluate(async () => { |
| 129 | const out = { stats: null, painted: window.__painted.frames, time: 0, stalled: [], tile: false }; |
| 130 | const el = window.__painted.el; |
| 131 | if (el && el.isConnected) { |
| 132 | out.time = el.currentTime; |
| 133 | out.tile = true; |
| 134 | out.paused = el.paused; |
| 135 | out.size = el.videoWidth + 'x' + el.videoHeight; |
| 136 | } |
| 137 | for (const pc of window.__pcs) { |
| 138 | if (pc.connectionState === 'closed') continue; |
| 139 | const mids = new Set(pc.getTransceivers() |
| 140 | .filter((t) => t.receiver.track && t.receiver.track.kind === 'video' && t.direction === 'recvonly' && t.currentDirection !== 'stopped') |
| 141 | .map((t) => t.mid)); |
| 142 | const all = await pc.getStats(); |
| 143 | for (const r of all.values()) { |
| 144 | if (r.type === 'inbound-rtp' && r.kind === 'video' && !mids.has(r.mid)) out.camera = r.framesDecoded || 0; |
| 145 | if (r.type === 'candidate-pair' && r.nominated && r.state === 'succeeded') out.inKbps = Math.round((r.availableIncomingBitrate || 0) / 1000); |
| 146 | if (r.type !== 'inbound-rtp' || r.kind !== 'video' || !mids.has(r.mid)) continue; |
| 147 | const c = r.codecId && all.get(r.codecId); |
| 148 | out.codec = c ? c.mimeType + ' ' + (c.sdpFmtpLine || '') : ''; |
| 149 | out.stats = { mid: r.mid, packets: r.packetsReceived || 0, received: r.framesReceived || 0, decoded: r.framesDecoded || 0, |
| 150 | dropped: r.framesDropped || 0, keyframes: r.keyFramesDecoded || 0, freezes: r.freezeCount || 0, |
| 151 | width: r.frameWidth || 0, height: r.frameHeight || 0, decoder: r.decoderImplementation || '', |
| 152 | pli: r.pliCount || 0, fps: r.framesPerSecond || 0, assembled: r.framesAssembledFromMultiplePackets }; |
| 153 | } |
| 154 | } |
| 155 | const s = window.meet.state(); |
| 156 | out.screenWatch = s.screenWatch || null; |
| 157 | return out; |
| 158 | }); |
| 159 | |
| 160 | class Skip extends Error {} |
| 161 | let nudge = null; |
| 162 | const stallLines = []; |
| 163 | try { |
| 164 | page.on('pageerror', (e) => console.log('page error', String(e))); |
| 165 | page.on('console', (m) => { |
| 166 | const text = m.text(); |
| 167 | if (!/^calls: /.test(text)) return; |
| 168 | if (/screen/.test(text)) { |
| 169 | console.log(`[${engine}] ${text}`); |
| 170 | if (/stalled here: reporting it/.test(text)) stallLines.push(text); |
| 171 | } |
| 172 | }); |
| 173 | await page.goto(`${origin}/m/${room}`); |
| 174 | await page.waitForFunction(() => !!window.meet); |
| 175 | native = spawn(binary, [], { stdio: ['pipe', 'pipe', 'pipe'] }); |
| 176 | native.on('exit', () => { exited = true; }); |
| 177 | native.stdin.write(process.env.CALLS_NATIVE_INPUT + '\n'); |
| 178 | createInterface({ input: native.stdout }).on('line', (text) => { |
| 179 | try { |
| 180 | const value = JSON.parse(text); |
| 181 | if (value.stats) sample = value; |
| 182 | } catch {} |
| 183 | }); |
| 184 | native.stderr.resume(); |
| 185 | nudge = setInterval(() => { page.mouse.click(5, 300).catch(() => {}); }, 2000); |
| 186 | await wait(() => sample && sample.stats.framesDecoded > 15, 'the app decodes the browser'); |
| 187 | native.stdin.write(`screen-mode ${process.env.SCREEN_MODE || 'balanced'}\n`); |
| 188 | if (scenario === 'wedge' && engine !== 'chromium') { |
| 189 | console.log(`SKIP wedge on ${engine}: its encoded transform does not take hold of a started receiver`); |
| 190 | throw new Skip(); |
| 191 | } |
| 192 | const moving = scenario === 'motion' || scenario === 'encoder'; |
| 193 | native.stdin.write(moving ? 'screen-motion\n' : scenario === 'slow' ? 'screen-still 5\n' : 'screen-still 0\n'); |
| 194 | await wait(() => sample && sample.sharingScreen === true, 'the app says it is sharing'); |
| 195 | await wait(async () => { |
| 196 | const s = await screen(); |
| 197 | return s.stats && s.stats.decoded > 2; |
| 198 | }, `${engine} decodes the app’s screen`); |
| 199 | console.log('screen codec ' + (await screen()).codec); |
| 200 | console.log(`PASS ${engine} decodes the app’s screen (${scenario}, ${process.env.SCREEN_MODE || 'balanced'})`); |
| 201 | |
| 202 | const w = (sample && sample.stats) || {}; |
| 203 | const ladder = () => { |
| 204 | const s = (sample && sample.stats) || {}; |
| 205 | return { reports: s.screenStallReports || 0, keyframes: s.screenWatchdogKeyframes || 0, |
| 206 | rebuilds: s.screenWatchdogRebuilds || 0, reshares: s.screenWatchdogReshares || 0, failures: s.screenWatchdogFailures || 0 }; |
| 207 | }; |
| 208 | const start = ladder(); |
| 209 | let prev = await screen(); |
| 210 | let paintedQuiet = 0; |
| 211 | let longestPaintedQuiet = 0; |
| 212 | const watch = async (seconds, label) => { |
| 213 | for (let i = 0; i < seconds; i += 1) { |
| 214 | await new Promise((r) => setTimeout(r, 1000)); |
| 215 | const now = await screen(); |
| 216 | const a = now.stats || {}; |
| 217 | const b = prev.stats || {}; |
| 218 | const same = a.mid === b.mid; |
| 219 | const d = (k) => (same ? (a[k] || 0) - (b[k] || 0) : 'new ' + (a[k] || 0)); |
| 220 | const painted = now.painted - prev.painted; |
| 221 | paintedQuiet = painted > 0 ? 0 : paintedQuiet + 1; |
| 222 | longestPaintedQuiet = Math.max(longestPaintedQuiet, paintedQuiet); |
| 223 | const s = (sample && sample.stats) || {}; |
| 224 | if (verbose || i % 5 === 4 || painted === 0) { |
| 225 | console.log(`${label} t=${i + 1}s mid ${a.mid} ${a.width}x${a.height} ${a.decoder} | packets +${d('packets')} received +${d('received')} ` + |
| 226 | `decoded +${d('decoded')} dropped +${d('dropped')} keyframes +${d('keyframes')} freezes ${a.freezes} pli ${a.pli} | ` + |
| 227 | `painted +${painted} clock +${(now.time - prev.time).toFixed(2)} ${now.size || ''} | app sent ${s.screenSendWidth}x${s.screenSendHeight} ` + |
| 228 | `fps ${(s.screenSendFpsTenths || 0) / 10} limit ${s.screenLimitation} target ${Math.round((s.screenTargetBitrate || 0) / 1000)}k ` + |
| 229 | `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())}`); |
| 230 | } |
| 231 | prev = now; |
| 232 | } |
| 233 | }; |
| 234 | |
| 235 | if (scenario === 'encoder') { |
| 236 | await watch(10, 'before'); |
| 237 | native.stdin.write('screen-encoder-stall\n'); |
| 238 | await watch(12, 'stopped'); |
| 239 | const reported = ladder().reports - start.reports; |
| 240 | const mended = (sample && sample.stats.screenWatchdogKeyframes) || 0; |
| 241 | console.log(`the app's own watch: ${JSON.stringify(ladder())}, keyframes asked ${mended}`); |
| 242 | const base = (await screen()).painted; |
| 243 | await wait(async () => (await screen()).painted > base + 10, `${engine} paints the screen again with nobody sharing again`, 30); |
| 244 | if (asserting) assert.equal(ladder().reshares - start.reshares, 0, 'mended without a share again'); |
| 245 | console.log(`PASS ${engine}: a screen that stopped leaving was mended (reports ${reported})`); |
| 246 | } else if (scenario === 'wedge') { |
| 247 | await watch(8, 'before'); |
| 248 | const n = await page.evaluate(() => window.__wedge(true)); |
| 249 | console.log(`wedged ${n} screen receiver(s)`); |
| 250 | await watch(14, 'wedged'); |
| 251 | const reported = ladder().reports - start.reports; |
| 252 | if (asserting) assert.ok(reported >= 1, `the wedged screen is reported (${reported})`); |
| 253 | console.log(`PASS ${engine}: a genuine stall is still reported (${reported})`); |
| 254 | await page.evaluate(() => window.__wedge(false)); |
| 255 | const base = (await screen()).painted; |
| 256 | await wait(async () => (await screen()).painted > base + 2, `${engine} paints the screen again once the wedge lifts`, 30); |
| 257 | const cleared = async () => !stallLines.length || (await page.evaluate(() => !(window.meet.state().screenStalled || []).length)); |
| 258 | await wait(cleared, 'the report clears', 20); |
| 259 | console.log(`PASS ${engine}: the wedged screen recovered`); |
| 260 | } else { |
| 261 | await watch(SECONDS, scenario); |
| 262 | const end = ladder(); |
| 263 | const reports = end.reports - start.reports; |
| 264 | console.log(`${engine} ${scenario}: ${reports} stall report(s) at the app, ladder ${JSON.stringify(end)}; ` + |
| 265 | `longest stretch with nothing painted ${longestPaintedQuiet} s; reported here ${stallLines.length}`); |
| 266 | if (asserting) { |
| 267 | assert.equal(reports, 0, `a ${scenario} screen that is being painted is never reported stalled (${reports})`); |
| 268 | assert.equal(end.rebuilds - start.rebuilds + end.reshares - start.reshares, 0, 'nothing was rebuilt or shared again'); |
| 269 | } |
| 270 | console.log(`PASS ${engine} ${scenario}: no stall reported, nothing rebuilt`); |
| 271 | } |
| 272 | void w; |
| 273 | clearInterval(nudge); |
| 274 | native.stdin.write('leave\n'); |
| 275 | await new Promise((r) => setTimeout(r, 1000)); |
| 276 | } catch (err) { |
| 277 | if (!(err instanceof Skip)) { |
| 278 | console.log('FAIL ' + (err && err.message ? err.message : String(err))); |
| 279 | process.exitCode = 1; |
| 280 | } |
| 281 | } finally { |
| 282 | if (nudge) clearInterval(nudge); |
| 283 | if (native && !exited) native.kill(); |
| 284 | await browser.close(); |
| 285 | } |
| 286 | |