// Isolated generated-media pipeline/lifecycle audit. No server, capture device or normal profile. // Test-only WeakRefs + explicit GC checkpoints measure retained wrappers, not production memory policy. import { launchApp } from './lib/electron-app.mjs'; import assert from 'node:assert/strict'; import { mkdirSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; const arg = (key) => { const index = process.argv.indexOf(`--${key}`); return index < 0 ? undefined : process.argv[index + 1]; }; const out = path.resolve(arg('out')); mkdirSync(out, { recursive: true }); const profile = mkdtempSync(path.join(tmpdir(), 'teamspeach-pipeline-')); const maintainResolution = process.argv.includes('--maintain-resolution'); const result = { startedAt: new Date().toISOString(), exe: arg('exe') ?? null, generatedMediaOnly: true, explicitTestGc: true, maintainResolution, maxBitrate: 6000000, cases: [], errors: [] }; let app; try { app = await launchApp({ profile, exe: arg('exe') }); const page = await app.firstWindow(); page.on('pageerror', (e) => result.errors.push(e.message)); await page.waitForSelector('#view-onboarding', { state: 'visible' }); await page.evaluate(() => { window.__captureRequests = 0; navigator.mediaDevices.getUserMedia = async () => { window.__captureRequests++; throw new Error('No capture in audit'); }; navigator.mediaDevices.getDisplayMedia = async () => { window.__captureRequests++; throw new Error('No capture in audit'); }; }); await page.fill('#onboarding-nick', 'GeneratedAudit'); await page.click('#onboarding-submit'); await page.waitForFunction(() => window.teamspeachDiagnostics?.snapshot().core === 'ready'); result.launch = await app.evaluate(({ app, BrowserWindow }) => ({ versions: process.versions, gpu: app.getGPUFeatureStatus(), backgroundThrottling: BrowserWindow.getAllWindows()[0].webContents.getBackgroundThrottling() })); await page.evaluate((value) => { window.__maintainResolution = value; }, maintainResolution); await page.evaluate(async () => { const watch = await import('./js/watch.js'); const { StreamViewerSession } = await import('./js/stream/session.js'); const { S } = await import('./js/state.js'); const NativePC = window.RTCPeerConnection; const pcs = [], sessions = []; // Test-only wrapper: remove public STUN so generated traffic stays on host candidates. window.RTCPeerConnection = function () { const pc = new NativePC(); pcs.push(new WeakRef(pc)); return pc; }; window.RTCPeerConnection.prototype = NativePC.prototype; const start = StreamViewerSession.prototype.start; StreamViewerSession.prototype.start = function () { sessions.push(new WeakRef(this)); return start.call(this); }; const A = window.__audit = { pcs, sessions, source: null, sequence: 0, presented: 0, draws: 0, videoCallback: null }; S.snap = { own_client_id: 1, own_channel_id: 10, clients: [{ id: 1, is_self: true, channel_id: 10, nickname: 'GeneratedAudit' }, { id: 2, channel_id: 10, nickname: 'GeneratedSender' }], channels: [{ id: 10, name: 'Generated', parent_id: 0 }] }; S.audio.output_muted = true; // Disposable profile only: generated tone is received but not played aloud. let video = null; const presented = (_now, metadata) => { A.presented++; A.compositorPresented = metadata.presentedFrames; A.videoCallback = video.requestVideoFrameCallback(presented); }; A.start = async (width, height, fps = 60, codec = null) => { if (video && A.videoCallback !== null) video.cancelVideoFrameCallback(A.videoCallback); watch.stopWatching(); // This audit intentionally closes the previous fixture before replacing it. const id = `generated-${++A.sequence}`; const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const g = canvas.getContext('2d'); const paint = () => { A.draws++; g.fillStyle = '#263447'; g.fillRect(0, 0, width, height); g.fillStyle = '#f7a76f'; g.fillRect((A.draws * 17) % width, height / 3, 160, 160); }; paint(); const timer = setInterval(paint, 1000 / fps); const audio = new AudioContext(); const osc = audio.createOscillator(); const dest = audio.createMediaStreamDestination(); osc.connect(dest); osc.start(); const ms = new MediaStream([canvas.captureStream(fps).getVideoTracks()[0], dest.stream.getAudioTracks()[0]]); const pc = new NativePC(); for (const track of ms.getTracks()) pc.addTrack(track, ms); if (codec) { const transceiver = pc.getTransceivers().find((t) => t.sender.track.kind === 'video'); const selected = RTCRtpSender.getCapabilities('video').codecs.filter((c) => c.mimeType === codec); if (!selected.length) throw new Error(`Requested test codec unavailable: ${codec}`); transceiver.setCodecPreferences(selected); // Test sender only, never product receiver policy. } const params = pc.getSenders().find((s) => s.track.kind === 'video').getParameters(); params.encodings = [{ ...params.encodings[0], maxBitrate: 6000000, maxFramerate: fps }]; if (window.__maintainResolution) params.degradationPreference = 'maintain-resolution'; await pc.getSenders().find((s) => s.track.kind === 'video').setParameters(params); let disposed = false; const dispose = async () => { if (disposed) return; disposed = true; clearInterval(timer); ms.getTracks().forEach((t) => t.stop()); pc.onicecandidate = null; pc.close(); osc.stop(); osc.disconnect(); await audio.close(); }; const emit = (name, item) => watch.onStreamEvent({ name, items: [{ id, clid: '2', ...item }] }); pc.onicecandidate = (e) => { if (e.candidate) emit('notifystreamsignaling', { json: JSON.stringify({ cmd: 'iceCandidate', args: { sdp: e.candidate.candidate, mid: e.candidate.sdpMid, mLine: e.candidate.sdpMLineIndex } }) }); }; const offer = async (first) => { await pc.setLocalDescription(await pc.createOffer()); emit(first ? 'notifyrespondjoinstreamrequest' : 'notifystreamsignaling', first ? { decision: '1', offer: pc.localDescription.sdp } : { json: JSON.stringify({ cmd: 'offer', args: { offer: pc.localDescription.sdp } }) }); }; watch.startWatching({ id, clientId: 2, name: 'Generated moving canvas', fields: { audio: '1' } }, { join: async () => offer(true), send: async (_id, _clid, json) => { if (disposed) return; if (json.cmd === 'answer') await pc.setRemoteDescription({ type: 'answer', sdp: json.args.answer }); else if (json.cmd === 'iceCandidate') await pc.addIceCandidate({ candidate: json.args.sdp, sdpMid: json.args.mid, sdpMLineIndex: json.args.mLine }); }, leave: dispose, }); video = document.querySelector(`[data-stream-id="${id}"] video`); A.videoCallback = video.requestVideoFrameCallback(presented); A.source = { pc, dispose, emit, offer }; }; const pcPolicy = (sdp = '') => sdp.split(/\r?\n/).filter((line) => /^(a=(framerate|fmtp):|b=)/.test(line)); A.sample = async () => { const receiver = sessions.at(-1)?.deref()?.pc; const sendReport = await A.source.pc.getStats(); const recvReport = await receiver.getStats(); const find = (r, type, kind) => [...r.values()].find((s) => s.type === type && (!kind || s.kind === kind)); const take = (s, keys) => Object.fromEntries(keys.filter((k) => s?.[k] !== undefined).map((k) => [k, s[k]])); const outbound = find(sendReport, 'outbound-rtp', 'video'); const inbound = find(recvReport, 'inbound-rtp', 'video'); const pair = [...recvReport.values()].find((s) => s.type === 'candidate-pair' && s.nominated && s.state === 'succeeded'); const local = recvReport.get(pair?.localCandidateId), remote = recvReport.get(pair?.remoteCandidateId); const sender = A.source.pc.getSenders().find((s) => s.track?.kind === 'video'); const parameters = sender.getParameters(); const rect = video.getBoundingClientRect(); return { now: performance.now(), draws: A.draws, presented: A.presented, compositorPresented: A.compositorPresented, videoQuality: { totalVideoFrames: video.getVideoPlaybackQuality().totalVideoFrames, droppedVideoFrames: video.getVideoPlaybackQuality().droppedVideoFrames }, outbound: take(outbound, ['timestamp','framesEncoded','framesSent','framesPerSecond','bytesSent','totalEncodeTime','qualityLimitationReason','qualityLimitationDurations','frameWidth','frameHeight','encoderImplementation']), inbound: take(inbound, ['timestamp','framesReceived','framesDecoded','framesDropped','framesPerSecond','bytesReceived','packetsReceived','packetsLost','jitter','totalDecodeTime','jitterBufferDelay','jitterBufferEmittedCount','freezeCount','decoderImplementation','powerEfficientDecoder','frameWidth','frameHeight']), source: take(find(sendReport, 'media-source', 'video'), ['timestamp','frames','framesPerSecond','width','height']), senderPolicy: { degradationPreference: parameters.degradationPreference, encodings: parameters.encodings.map((e) => take(e, ['maxBitrate','maxFramerate','scaleResolutionDownBy'])) }, captureTrackSettings: take(sender.track.getSettings(), ['width','height','frameRate']), sdpPolicy: { offer: pcPolicy(A.source.pc.localDescription?.sdp), answer: pcPolicy(receiver.localDescription?.sdp) }, audio: take(find(recvReport, 'inbound-rtp', 'audio'), ['packetsReceived','bytesReceived']), codec: recvReport.get(inbound?.codecId)?.mimeType, pair: { localType: local?.candidateType, remoteType: remote?.candidateType, protocol: local?.protocol, currentRoundTripTime: pair?.currentRoundTripTime }, video: { width: video.videoWidth, height: video.videoHeight, paused: video.paused, visible: video.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }), rect: rect.toJSON(), inViewport: rect.width > 0 && rect.height > 0 && rect.left >= 0 && rect.top >= 0 && rect.right <= innerWidth && rect.bottom <= innerHeight, sessionHidden: document.querySelector('#session-view').hidden, documentVisibility: document.visibilityState, focused: document.hasFocus() }, watch: watch.watchSnapshots()[0], }; }; A.end = async (kind) => { const source = A.source; const receiverTracks = video.srcObject?.getTracks() ?? []; if (kind === 'stop') watch.stopWatching(); else if (kind === 'disconnect') watch.onDisconnected(); else source.emit('notifystreamstopped', {}); await source.dispose(); A.source = null; const session = sessions.at(-1)?.deref(); return { kind, state: session?.state, closedPeerRetained: !!session?.pc, mediaAttached: video.srcObject !== null, playerHidden: !video.isConnected || video.closest('.stream-view').hidden, receiverTrackStates: receiverTracks.map((t) => t.readyState) }; }; A.retention = () => ({ liveSessions: sessions.filter((r) => r.deref()).length, liveReceiverWrappers: pcs.filter((r) => r.deref()).length, nonclosedReceivers: pcs.filter((r) => r.deref() && r.deref().connectionState !== 'closed').length, domNodes: document.querySelectorAll('*').length, captureRequests: window.__captureRequests, usedJsHeap: performance.memory?.usedJSHeapSize }); A.close = () => { watch.stopWatching(); if (video && A.videoCallback !== null) video.cancelVideoFrameCallback(A.videoCallback); video = null; }; }); // Use the normal snapshot/render lifecycle: setting S.snap alone leaves the session ancestor hidden. const fixture = await page.evaluate(async () => { const { S } = await import('./js/state.js'); return { ...S.snap, event: 'snapshot', rev: 1, server: { name: 'Generated fixture (no server)', version: null, welcome_message: '', hostbanner_gfx_url: null, hostbanner_url: null }, server_groups: [], channel_groups: [], channels: S.snap.channels.map((c) => ({ order: 0, topic: '', has_password: false, is_default: true, max_clients: null, needed_talk_power: 0, codec: 'opus_voice', codec_quality: 6, icon_id: null, banner_url: null, banner_mode: null, depth: 0, ...c })), clients: S.snap.clients.map((c) => ({ uid: null, client_type: 'normal', input_muted: true, output_muted: true, input_hardware: true, output_hardware: true, away: false, away_message: null, talk_power: 0, is_talker: false, is_channel_commander: false, is_priority_speaker: false, is_recording: false, is_streaming: false, description: null, country: null, server_groups: [], channel_group_id: null, channel_group_inherited_from: null, avatar_hash: null, has_myts: false, myts_avatars: [], myts_avatar_unparsed: null, icon_id: null, badges: null, ...c })), }; }); await app.evaluate(({ BrowserWindow }, snapshot) => BrowserWindow.getAllWindows()[0].webContents.send('core:event', { ...snapshot, connectionId: 'c1' }), fixture); await page.waitForSelector('#session-view', { state: 'visible' }); const cdp = await page.context().newCDPSession(page); const collect = async () => { await cdp.send('HeapProfiler.collectGarbage'); await page.waitForTimeout(100); return page.evaluate(() => window.__audit.retention()); }; result.baselineRetention = await collect(); const configs = process.argv.includes('--lifecycle-only') ? [] : [{ width: 1280, height: 720, codec: null }, { width: 2568, height: 1402, codec: 'video/AV1' }]; for (const config of configs) { await page.evaluate((c) => window.__audit.start(c.width, c.height, 60, c.codec), config); await page.waitForFunction(() => { const v = document.querySelector('[data-role="stream-video"]'); return v.videoWidth > 0 && !v.paused; }, null, { timeout: 20000 }); await page.waitForTimeout(2500); const first = await page.evaluate(() => window.__audit.sample()); await page.waitForTimeout(5000); const second = await page.evaluate(() => window.__audit.sample()); const seconds = (second.now - first.now) / 1000; const delta = (part, key) => (second[part][key] ?? 0) - (first[part][key] ?? 0); const rates = { intervalSeconds: seconds, generatedFps: (second.draws-first.draws)/seconds, senderEncodedFps: delta('outbound','framesEncoded')/seconds, senderSentFps: delta('outbound','framesSent')/seconds, receivedFps: delta('inbound','framesReceived')/seconds, decodedFps: delta('inbound','framesDecoded')/seconds, presentedCallbacksFps: (second.presented-first.presented)/seconds, droppedFrames: delta('inbound','framesDropped'), lostPackets: delta('inbound','packetsLost'), meanDecodeMs: delta('inbound','totalDecodeTime')*1000/Math.max(1,delta('inbound','framesDecoded')), receivedKbps: delta('inbound','bytesReceived')*8/seconds/1000 }; rates.capturedFps = first.source.frames === undefined || second.source.frames === undefined ? null : delta('source', 'frames') / seconds; rates.meanEncodeMs = delta('outbound', 'totalEncodeTime') * 1000 / Math.max(1, delta('outbound', 'framesEncoded')); await page.evaluate(() => window.__audit.source.offer(false)); await page.waitForTimeout(1000); const renegotiated = await page.evaluate(() => window.__audit.sample()); assert.ok(renegotiated.inbound.framesDecoded > second.inbound.framesDecoded, 'media survives renegotiation'); assert.ok(second.audio.packetsReceived > first.audio.packetsReceived, 'generated audio advances'); assert.equal(first.video.visible, true, 'video and every ancestor are visible'); assert.equal(second.video.inViewport, true, 'player fits the viewport'); rates.presentationTotalFrames = delta('videoQuality', 'totalVideoFrames'); rates.presentationDroppedFrames = delta('videoQuality', 'droppedVideoFrames'); rates.compositorSubmittedFps = (second.compositorPresented - first.compositorPresented) / seconds; await page.screenshot({ path: path.join(out, `visible-${config.width}.png`) }); const terminal = await page.evaluate(() => window.__audit.end('ended')); result.cases.push({ config, first, second, rates, renegotiated, terminal, retentionAfterTerminal: await collect() }); console.log(JSON.stringify({ config, rates, terminal })); } result.cycles = []; for (let i = 0; i < 12; i++) { await page.evaluate(() => window.__audit.start(640, 360, 30)); await page.waitForFunction(() => document.querySelector('[data-role="stream-video"]').videoWidth > 0, null, { timeout: 15000 }); await page.waitForTimeout(180); const kind = ['stop', 'ended', 'disconnect'][i % 3]; const terminal = await page.evaluate((k) => window.__audit.end(k), kind); assert.equal(terminal.mediaAttached, false); result.cycles.push({ index: i, ...terminal, retention: await collect() }); } result.switches = []; await page.evaluate(() => window.__audit.start(640, 360, 30)); for (let i = 0; i < 6; i++) { await page.waitForFunction(() => document.querySelector('[data-role="stream-video"]').videoWidth > 0, null, { timeout: 15000 }); const switched = await page.evaluate(async () => { const a = window.__audit; const priorSource = a.source; const priorSession = a.sessions.at(-1).deref(); const tracks = document.querySelector('[data-role="stream-video"]').srcObject.getTracks(); await a.start(640, 360, 30); return { oldSenderState: priorSource.pc.connectionState, oldSessionState: priorSession.state, closedPeerRetained: !!priorSession.pc, oldReceiverTrackStates: tracks.map((t) => t.readyState) }; }); assert.equal(switched.oldSenderState, 'closed'); assert.equal(switched.oldSessionState, 'stopped'); assert.ok(switched.oldReceiverTrackStates.every((s) => s === 'ended')); result.switches.push(switched); } await page.evaluate(() => window.__audit.end('stop')); // End notifications create short-lived toasts; wait for their real production expiry before final DOM count. await page.waitForTimeout(6500); result.processMetrics = await app.evaluate(({ app }) => app.getAppMetrics().map(({ type, cpu, memory }) => ({ type, cpu, memory }))); await page.evaluate(() => window.__audit.close()); result.finalRetention = await collect(); assert.equal(result.finalRetention.nonclosedReceivers, 0); assert.equal(result.finalRetention.captureRequests, 0); assert.deepEqual(result.errors, []); if (process.argv.includes('--expect-fixed')) { assert.equal(result.cycles.some((c) => c.closedPeerRetained), false); assert.equal(result.finalRetention.liveSessions, 0, 'stopped labels must not retain a session'); } } catch (error) { result.failure = error.stack; process.exitCode = 1; } finally { if (app) await app.close(); result.finishedAt = new Date().toISOString(); writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2)); rmSync(profile, { recursive: true, force: true }); }