// Browser-pipeline check of the viewer's media lifecycle inside the real Electron renderer. // A throwaway RTCPeerConnection in the same page plays the streamer: it sends a canvas video and a // generated 440 Hz tone, trickles ICE before its offer is delivered, and sends a realign offer. // The real viewer code (watch.js + StreamViewerSession) receives it through an injected transport. // // This proves Chromium-side behaviour (track attach, playback, output-device routing, stop/switch // while callbacks are pending). It is NOT TeamSpeak interoperability: see scripts/probe-stream.mjs. // // node scripts/loopback-stream.mjs --out docs/evidence/runtime/ import { launchApp } from './lib/electron-app.mjs'; import { mkdirSync, writeFileSync, mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const argv = process.argv.slice(2); const out = path.resolve(root, argv[argv.indexOf('--out') + 1] ?? 'loopback-out'); mkdirSync(out, { recursive: true }); const profile = mkdtempSync(path.join(tmpdir(), 'teamspeach-loopback-')); const result = { startedAt: new Date().toISOString(), steps: [], console: [] }; const step = (name, data = {}) => { result.steps.push({ name, ...data }); console.log(`[loopback] ${name}`, JSON.stringify(data)); }; // Runs in the page: builds a fake streamer bound to stream id `id`. const installStreamer = () => { window.__loop = { async make(id) { const watch = await import('/js/watch.js'); const ctx = new AudioContext(); const osc = ctx.createOscillator(); osc.frequency.value = 440; const gain = ctx.createGain(); gain.gain.value = 0.2; const dest = ctx.createMediaStreamDestination(); osc.connect(gain).connect(dest); osc.start(); const canvas = document.createElement('canvas'); canvas.width = 640; canvas.height = 360; const g = canvas.getContext('2d'); let n = 0; const timer = setInterval(() => { g.fillStyle = `hsl(${(n += 7) % 360} 60% 50%)`; g.fillRect(0, 0, 640, 360); }, 33); const ms = new MediaStream([canvas.captureStream(30).getVideoTracks()[0], dest.stream.getAudioTracks()[0]]); const pc = new RTCPeerConnection(); for (const t of ms.getTracks()) pc.addTrack(t, ms); const emit = (name, item) => watch.onStreamEvent({ event: 'stream', name, items: [{ id, clid: '999', ...item }] }); pc.onicecandidate = (e) => { if (e.candidate) emit('notifystreamsignaling', { json: JSON.stringify({ cmd: 'iceCandidate', args: { mLine: e.candidate.sdpMLineIndex, mid: e.candidate.sdpMid, sdp: e.candidate.candidate } }) }); }; let answers = 0; const transport = { join: async () => { await pc.setLocalDescription(await pc.createOffer()); // Deliver the offer a little later so trickled candidates arrive first (buffering path). setTimeout(() => emit('notifyrespondjoinstreamrequest', { decision: '1', offer: pc.localDescription.sdp, msg: '' }), 150); }, send: async (_id, _clid, json) => { if (json.cmd === 'answer') { await pc.setRemoteDescription({ type: 'answer', sdp: json.args.answer }); answers += 1; if (answers === 1) { // Realign offer, as a TS6 streamer does after the first answer. setTimeout(async () => { await pc.setLocalDescription(await pc.createOffer()); emit('notifystreamsignaling', { json: JSON.stringify({ cmd: 'offer', args: { offer: pc.localDescription.sdp } }) }); }, 200); } } else if (json.cmd === 'iceCandidate') { await pc.addIceCandidate({ candidate: json.args.sdp, sdpMid: json.args.mid, sdpMLineIndex: json.args.mLine }); } }, leave: async () => { clearInterval(timer); pc.close(); ctx.close(); }, }; return { transport, pc }; }, async start(id) { const watch = await import('/js/watch.js'); const { transport } = await this.make(id); watch.startWatching({ id, clientId: 999, name: `loop ${id}`, nickname: 'loopback', fields: { audio: '1' } }, transport); }, async stop() { const watch = await import('/js/watch.js'); watch.stopWatching(); }, }; }; let app; let page; let failed = null; try { // Synthetic capture device only: getUserMedia permission unlocks real output-device enumeration. app = await launchApp({ profile, args: ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream'] }); page = await app.firstWindow(); page.on('console', (m) => result.console.push(`${m.type()}: ${m.text()}`)); page.on('pageerror', (e) => result.console.push(`pageerror: ${e.message}`)); await page.waitForSelector('#view-onboarding', { state: 'visible', timeout: 20000 }); await page.fill('#onboarding-nick', 'LoopbackTest'); await page.click('#onboarding-submit'); await page.waitForSelector('#view-app', { state: 'visible', timeout: 20000 }); // Not connected to any server: show the session area so the viewer panel is laid out. await page.evaluate(() => { document.querySelector('#connect-view').hidden = true; document.querySelector('#session-view').hidden = false; }); await page.evaluate(installStreamer); await page.$eval('#stream-volume', (el) => { el.value = '5'; el.dispatchEvent(new Event('input', { bubbles: true })); }); const stats = () => page.evaluate(() => window.teamspeachDiagnostics.snapshot().watch); const errorToasts = () => page.$$eval('.toast[data-kind="error"]', (els) => els.map((e) => e.textContent)); // 1. Switch while the first session's track-attach callback is pending, then stop/start rapidly. await page.evaluate(async () => { await window.__loop.start('A'); await window.__loop.stop(); await window.__loop.start('B'); }); await page.waitForFunction(() => window.teamspeachDiagnostics.snapshot().watch.framesDecoded > 30, null, { timeout: 20000 }); await page.waitForTimeout(2000); let s = await stats(); const srcIsCurrent = await page.evaluate(() => document.querySelector('#stream-video').srcObject?.getTracks().length ?? 0); step('switch while pending', { state: s.state, framesDecoded: s.framesDecoded, offersApplied: s.offersApplied, answersSent: s.answersSent, inboundAudioPackets: s.inboundAudioPackets, tracksOnElement: srcIsCurrent, errors: await errorToasts() }); if (s.offersApplied < 2) throw new Error('realign offer was not answered'); if (!(s.inboundAudioPackets > 0)) throw new Error('no inbound audio packets'); // 2. Default output: no setSinkId call is needed and no error may appear. step('default sink', { sinkId: s.sinkId, sinkError: s.sinkError, errors: await errorToasts() }); // 3. Select a concrete output device through the real settings UI while the stream plays. await page.click('#btn-settings'); await page.waitForSelector('#settings-view', { state: 'visible' }); await page.click('#mic-test'); await page.waitForTimeout(1200); await page.click('#mic-test'); await page.waitForTimeout(300); const options = await page.$$eval('#output-device option', (os) => os.map((o) => ({ value: o.value, label: o.textContent }))); const device = options.find((o) => o.value); if (device) { await page.selectOption('#output-device', device.value); await page.waitForTimeout(1500); s = await stats(); const elementSink = await page.evaluate(() => document.querySelector('#stream-video').sinkId); step('selected sink', { device: device.label, elementSinkMatches: elementSink === device.value, sinkError: s.sinkError, errors: await errorToasts() }); if (elementSink !== device.value) throw new Error('stream element not routed to selected device'); // Restart viewing with the device already selected: applied on `playing`. await page.click('#settings-back'); await page.evaluate(() => { document.querySelector('#connect-view').hidden = true; document.querySelector('#session-view').hidden = false; }); await page.evaluate(async () => { await window.__loop.stop(); await window.__loop.start('C'); }); await page.waitForFunction(() => window.teamspeachDiagnostics.snapshot().watch.inboundAudioPackets > 50, null, { timeout: 20000 }); s = await stats(); step('restart with selected sink', { sinkId: s.sinkId === device.value, sinkError: s.sinkError, framesDecoded: s.framesDecoded, inboundAudioPackets: s.inboundAudioPackets, errors: await errorToasts() }); await page.selectOption('#output-device', '').catch(() => {}); } else { step('selected sink skipped', { reason: 'no non-default output device enumerated' }); } await page.evaluate(() => { document.querySelector('#stream-video').style.visibility = 'hidden'; }); await page.screenshot({ path: path.join(out, '30-loopback-viewer-redacted.png') }); await page.evaluate(() => window.__loop.stop()); const errs = await errorToasts(); step('final', { errors: errs }); if (errs.length) throw new Error(`error toasts: ${errs.join(' | ')}`); } catch (err) { failed = err; step('FAILED', { error: String(err.stack || err) }); } finally { if (app) await app.close().catch(() => {}); rmSync(profile, { recursive: true, force: true }); } result.ok = !failed; result.note = 'Loopback inside Chromium: validates the browser media pipeline only, not TS6 interoperability.'; writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2)); console.log(`[loopback] ${result.ok ? 'OK' : 'FAILED'} → ${out}`); process.exit(result.ok ? 0 : 1);