Files
client/scripts/lib/appaudio-smoke-renderer.mjs
T
omar e6464bc4ed feat: checkpoint account-free client workflows and source-matched UI
Preserve accumulated client implementation since v0.1.4, including local identities, multi-server state, chat, administration, audio and streaming controls. Refine official-source layout, original artwork, responsive composer overflow, settings navigation and chat scroll anchoring.

Current verification: Node suite passes; isolated packaged chat and responsive control smokes pass without device capture. Native core is reused, not rebuilt in this pass. Strict whole-screen visual parity remains incomplete; no 1:1 or cross-platform acceptance claim. Local checkpoint only; no release or push.
2026-11-01 19:43:18 +03:00

151 lines
9.6 KiB
JavaScript

import { attachApplicationAudio } from '../../app/renderer/js/stream/appaudio-renderer.js';
const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
const assert = (condition, message) => { if (!condition) throw new Error(message); };
const evidence = { ok: false, startedAt: new Date().toISOString(), source: 'Two owned generated waveOut tones, 440 and 997 Hz; no desktop or private application capture.', path: 'real native helper -> Electron bounded IPC -> production AudioWorklet mixer -> local WebRTC -> remote receiver analyser', measurements: [] };
let attachment;
let video;
let viewer;
const audioErrors = [];
const mixerContexts = [];
const mixerWorklets = [];
const rendererCounters = { received: 0, posted: 0, consumed: 0, stopAcks: 0 };
class DiagnosticContext extends AudioContext { constructor(options) { super({ ...options, sinkId: { type: 'none' } }); mixerContexts.push(this); } }
class DiagnosticWorklet extends AudioWorkletNode {
constructor(...args) {
super(...args); mixerWorklets.push(this);
const post = this.port.postMessage.bind(this.port);
this.port.postMessage = (packet, transfer) => { if (packet.type === 'pcm') rendererCounters.posted++; post(packet, transfer); };
this.port.addEventListener('message', ({ data }) => { if (data.type === 'ack') rendererCounters.consumed++; if (data.type === 'stopped') rendererCounters.stopAcks++; });
}
}
const diagnosticBridge = { ...window.teamspeach, onAppAudio: callback => window.teamspeach.onAppAudio(packet => { if (packet.event === 'pcm') rendererCounters.received++; callback(packet); }) };
async function receiver(track) {
const sender = new RTCPeerConnection({ iceServers: [] });
const remote = new RTCPeerConnection({ iceServers: [] });
sender.onicecandidate = event => { if (event.candidate) remote.addIceCandidate(event.candidate).catch(() => {}); };
remote.onicecandidate = event => { if (event.candidate) sender.addIceCandidate(event.candidate).catch(() => {}); };
const received = new Promise((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error('WebRTC receiver track timed out.')), 10000);
remote.ontrack = event => { clearTimeout(timeout); resolve(event.track); };
});
sender.addTrack(track, new MediaStream([track]));
await sender.setLocalDescription(await sender.createOffer());
await remote.setRemoteDescription(sender.localDescription);
await remote.setLocalDescription(await remote.createAnswer());
await sender.setRemoteDescription(remote.localDescription);
const receivedTrack = await received;
const element = document.createElement('audio');
element.muted = true;
element.srcObject = new MediaStream([receivedTrack]);
document.body.append(element);
await element.play();
const context = new AudioContext({ sampleRate: 48000, sinkId: { type: 'none' } });
await context.resume();
const input = context.createMediaStreamSource(new MediaStream([receivedTrack]));
const analyser = context.createAnalyser();
analyser.fftSize = 8192;
analyser.smoothingTimeConstant = 0;
const mute = context.createGain();
mute.gain.value = 0;
input.connect(analyser).connect(mute).connect(context.destination);
const bins = new Float32Array(analyser.frequencyBinCount);
const samples = new Float32Array(analyser.fftSize);
return {
async measure(name) {
await pause(600);
const values = [];
for (let n = 0; n < 6; n++) {
analyser.getFloatFrequencyData(bins);
analyser.getFloatTimeDomainData(samples);
const peak = frequency => {
const bin = Math.round(frequency / context.sampleRate * analyser.fftSize);
return Math.max(...bins.slice(bin - 2, bin + 3));
};
values.push({ hz440: peak(440), hz997: peak(997), rms: Math.sqrt(samples.reduce((total, sample) => total + sample * sample, 0) / samples.length) });
await pause(50);
}
const mean = key => values.reduce((sum, row) => sum + row[key], 0) / values.length;
const stats = [...(await remote.getStats()).values()].filter(item => item.type === 'inbound-rtp').map(item => ({ packetsReceived: item.packetsReceived, bytesReceived: item.bytesReceived, totalSamplesReceived: item.totalSamplesReceived }));
const value = { name, hz440: mean('hz440'), hz997: mean('hz997'), rms: mean('rms'), receiverContext: context.state, receiverConnection: remote.connectionState, stats, main: await window.smoke.state(), renderer: { ...rendererCounters }, mixerContexts: mixerContexts.map(ctx => ({ state: ctx.state, time: ctx.currentTime })) };
evidence.measurements.push(value);
return value;
},
async close() { element.pause(); element.srcObject = null; element.remove(); sender.close(); remote.close(); input.disconnect(); analyser.disconnect(); mute.disconnect(); receivedTrack.stop(); await context.close(); },
};
}
async function setup(ids) {
const selected = await window.smoke.prepare();
evidence.scope = selected.scope;
evidence.ownedApplications = selected.applications;
const canvas = document.createElement('canvas');
canvas.width = 16; canvas.height = 16;
canvas.getContext('2d').fillRect(0, 0, 16, 16);
video = canvas.captureStream(1);
attachment = await attachApplicationAudio(video, { sessionId: selected.sessionId, applications: ids.map(index => selected.applications[index].id), onError: cause => audioErrors.push(cause.message) }, { bridge: diagnosticBridge, AudioContext: DiagnosticContext, AudioWorkletNode: DiagnosticWorklet });
viewer = await receiver(video.getAudioTracks()[0]);
return selected.applications;
}
async function cleanup() {
await attachment?.release(); attachment = null;
await viewer?.close(); viewer = null;
video?.getTracks().forEach(track => track.stop()); video = null;
}
try {
const initial = await window.smoke.state();
if (initial.diagnostic) { evidence.source = 'Synthetic exact-contract PCM child-process fixture. NO native WASAPI/PulseAudio capture and NO native isolation proof.'; evidence.path = 'synthetic PCM child -> production Electron transport -> production renderer/worklet -> local WebRTC decoded analyser'; }
assert(initial.offscreen && !initial.visible, 'Smoke must remain invisible and offscreen.');
const apps = await setup([0]);
const selectedOnly = await viewer.measure('selected440-only');
assert(selectedOnly.hz440 > -80 && selectedOnly.hz440 - selectedOnly.hz997 > 20, 'Selected tone missing or unselected application leaked.');
attachment.setMasterGain(0.5);
const half = await viewer.measure('master-half');
assert(half.hz440 < selectedOnly.hz440 - 4 && half.hz440 > selectedOnly.hz440 - 8, 'Master half gain did not yield approximately -6 dB.');
attachment.setMasterGain(1);
attachment.setAppGain(apps[0].id, 0);
const muted = await viewer.measure('selected-app-muted');
assert(muted.rms < selectedOnly.rms * 0.03, 'Per-application mute leaked audio.');
await cleanup();
await pause(500);
assert(!(await window.smoke.state()).active, 'Release left a capture session active.');
const bothApps = await setup([0, 1]);
const both = await viewer.measure('both-selected');
assert(both.hz440 > -80 && both.hz997 > -80, 'Both selected applications did not reach WebRTC.');
attachment.setAppGain(bothApps[0].id, 0);
const isolated = await viewer.measure('only-app440-muted');
assert(isolated.hz440 < both.hz440 - 20, 'Per-app gain failed to mute selected application.');
assert(Math.abs(isolated.hz997 - both.hz997) < 3, 'Per-app gain changed another application.');
attachment.setAppGain(bothApps[0].id, 1);
const reset = await viewer.measure('application-gain-reset');
assert(Math.abs(reset.hz440 - both.hz440) < 3, 'Per-app reset failed.');
attachment.setMasterGain(0);
const masterMuted = await viewer.measure('master-muted');
assert(masterMuted.rms < both.rms * 0.03, 'Master gain failed to mute all selected apps.');
await cleanup();
await pause(500);
evidence.finalState = await window.smoke.state();
assert(!evidence.finalState.active && evidence.finalState.captureChildren === 0 && !evidence.finalState.visible && evidence.finalState.offscreen, 'Final capture/window state is not clean.');
assert(audioErrors.length === 0, `Unexpected capture errors: ${audioErrors.join('; ')}`);
evidence.failureCycles = [];
for (let cycle = 0; cycle < 3; cycle++) {
await setup([0]);
const before = audioErrors.length;
mixerWorklets.at(-1).dispatchEvent(new Event('processorerror'));
await attachment.release();
await cleanup();
const deadline = performance.now() + 2000;
let state = await window.smoke.state();
while (state.captureChildren && performance.now() < deadline) { await pause(20); state = await window.smoke.state(); }
assert(audioErrors.length === before + 1 && audioErrors.at(-1) === 'The application audio mixer stopped.', 'Actual worklet EventTarget processorerror did not stop the mixer.');
assert(mixerContexts.every(ctx => ctx.state === 'closed') && !state.active && state.captureChildren === 0 && state.inFlight === 0, 'Processor error retained a context, native helper or pending frame.');
evidence.failureCycles.push({ cycle, state, closedContexts: mixerContexts.length, stopAcks: rendererCounters.stopAcks });
}
assert(rendererCounters.stopAcks === mixerWorklets.length, 'A worklet was closed without its stop acknowledgement.');
evidence.ok = true;
} catch (cause) { evidence.error = cause.stack || String(cause); }
finally {
await cleanup().catch(cause => { evidence.cleanupError = String(cause); evidence.ok = false; });
evidence.lifecycle = { contexts: mixerContexts.map(ctx => ctx.state), ...rendererCounters, main: await window.smoke.state() };
evidence.finishedAt = new Date().toISOString();
await window.smoke.result(evidence);
}