491 lines
21 KiB
JavaScript
491 lines
21 KiB
JavaScript
// Web Audio voice: persistent 48 kHz playback mixing one bounded ring per server connection on the
|
|
// audio clock, and a capture-owned 48 kHz context. Chromium retains MediaStream source nodes until
|
|
// their context is closed.
|
|
import { dbToGain } from './fader.js';
|
|
|
|
const DENOISE_URL = new URL('../../assets/audio/denoise.wasm', import.meta.url);
|
|
const DENOISE_EXPORTS = { memory: 'memory', dsp_new: 'function', dsp_input: 'function', dsp_process: 'function', dsp_reset: 'function', dsp_free: 'function' };
|
|
/** Fixed algorithmic delay of the noise suppressor (312 samples at 48 kHz, see capture-worklet.js). */
|
|
export const DENOISE_DELAY = 312 / 48000;
|
|
const PROCESSOR_READY_TIMEOUT_MS = 5000;
|
|
let denoiseModule = null;
|
|
|
|
/**
|
|
* Compiles the bundled denoise.wasm once, on the renderer thread: an AudioWorklet cannot fetch, so the
|
|
* compiled module is handed to the capture processor. A failure is not cached; the next capture retries.
|
|
*/
|
|
export function loadDenoiseModule() {
|
|
denoiseModule ??= (async () => {
|
|
const response = await fetch(DENOISE_URL);
|
|
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
const module = await WebAssembly.compile(await response.arrayBuffer());
|
|
const exports = new Map(WebAssembly.Module.exports(module).map(({ name, kind }) => [name, kind]));
|
|
const missing = Object.entries(DENOISE_EXPORTS).filter(([name, kind]) => exports.get(name) !== kind).map(([name]) => name);
|
|
if (missing.length) throw new Error(`missing exports ${missing.join(', ')}`);
|
|
if (WebAssembly.Module.imports(module).length) throw new Error('the module must not import anything');
|
|
return module;
|
|
})().catch((err) => {
|
|
denoiseModule = null;
|
|
throw Object.assign(new Error(`Noise reduction is unavailable: ${err.message}`), { code: 'denoise_unavailable' });
|
|
});
|
|
return denoiseModule;
|
|
}
|
|
|
|
export class AudioEngine {
|
|
constructor({ onFrame, onError, log }) {
|
|
this.onFrame = onFrame;
|
|
this.onError = onError ?? (() => {});
|
|
this.log = log ?? (() => {});
|
|
this.ctx = null;
|
|
this.playback = null;
|
|
this.voiceGain = null;
|
|
this.outputLevelDb = 0;
|
|
this.playbackDsp = { comfortNoise: false, comfortNoiseLevel: -60, echoReduction: 0 };
|
|
this.playbackEnabled = false;
|
|
this.transmitting = false;
|
|
this.typingEnabled = false;
|
|
this.denoiseLevel = null; // official denoiser level 0..3 of the current capture request, null = off
|
|
this.captureBoundary = 0;
|
|
this.outputDeviceId = '';
|
|
this.capture = null;
|
|
this.openingCapture = null;
|
|
this.captureClosing = Promise.resolve();
|
|
this.failedCaptureContext = null;
|
|
this.captureCloseError = null;
|
|
this.captureGen = 0; // bumped by every start/stop; a pending start only completes if still current
|
|
this.startingGen = null;
|
|
this.ready = null;
|
|
this.playbackFailed = false;
|
|
this.initializing = false;
|
|
this.stats = { framesOut: 0, staleCaptureFrames: 0 };
|
|
this.statsWaiters = [];
|
|
this.testSource = null;
|
|
}
|
|
|
|
init() {
|
|
if (!this.ready || (!this.initializing && (this.playbackFailed || this.ctx?.state === 'closed'))) {
|
|
this.initializing = true;
|
|
const released = this.ctx ? this.releasePlayback() : Promise.resolve();
|
|
this.playbackFailed = false;
|
|
this.ready = released.then(() => this._init().catch(async (err) => {
|
|
await this.releasePlayback();
|
|
throw err;
|
|
})).catch((err) => {
|
|
this.ready = null;
|
|
throw err;
|
|
}).finally(() => { this.initializing = false; });
|
|
}
|
|
if (!this.initializing && this.ctx && this.ctx.state !== 'running') return this.ctx.resume();
|
|
return this.ready;
|
|
}
|
|
|
|
async releasePlayback() {
|
|
this.stopDeviceTestPlayback();
|
|
const ctx = this.ctx;
|
|
if (ctx) ctx.onstatechange = null;
|
|
if (this.playback) {
|
|
this.playback.removeEventListener('processorerror', this.playbackErrorHandler);
|
|
this.playback.port.onmessage = null;
|
|
this.playback.port.close();
|
|
this.playback.disconnect();
|
|
}
|
|
this.voiceGain?.disconnect();
|
|
this.playback = null;
|
|
this.voiceGain = null;
|
|
for (const resolve of this.statsWaiters.splice(0)) resolve(null);
|
|
// A rejected close retains the context, so an explicit retry cannot create an overlapping one.
|
|
if (ctx && ctx.state !== 'closed') await ctx.close();
|
|
this.ctx = null;
|
|
}
|
|
|
|
async _init() {
|
|
const ctx = new AudioContext({ sampleRate: 48000, latencyHint: 'interactive' });
|
|
this.ctx = ctx;
|
|
await ctx.audioWorklet.addModule(new URL('./playback-worklet.js', import.meta.url));
|
|
this.playback = new AudioWorkletNode(ctx, 'tp-playback', {
|
|
numberOfInputs: 0,
|
|
numberOfOutputs: 1,
|
|
outputChannelCount: [1],
|
|
});
|
|
this.playbackErrorHandler = () => {
|
|
this.playbackFailed = true;
|
|
for (const resolve of this.statsWaiters.splice(0)) resolve(null);
|
|
this.onError({ code: 'playback', message: 'Audio playback processor failed; reconnect to retry' });
|
|
};
|
|
this.playback.addEventListener('processorerror', this.playbackErrorHandler, { once: true });
|
|
ctx.onstatechange = () => {
|
|
if (ctx.state === 'closed') {
|
|
for (const resolve of this.statsWaiters.splice(0)) resolve(null);
|
|
}
|
|
};
|
|
this.playback.port.onmessage = (event) => {
|
|
if (event.data && event.data.type === 'stats') {
|
|
const waiters = this.statsWaiters.splice(0);
|
|
for (const resolve of waiters) resolve(event.data);
|
|
}
|
|
};
|
|
this.voiceGain = ctx.createGain();
|
|
this.voiceGain.gain.value = dbToGain(this.outputLevelDb);
|
|
this.playback.port.postMessage({ type: 'dsp', ...this.playbackDsp });
|
|
this.playback.port.postMessage({ type: 'enabled', enabled: this.playbackEnabled });
|
|
this.playback.port.postMessage({ type: 'transmitting', active: this.transmitting });
|
|
if (this.outputDeviceId) await ctx.setSinkId(this.outputDeviceId);
|
|
this.playback.connect(this.voiceGain).connect(ctx.destination);
|
|
if (ctx.state !== 'running') await ctx.resume();
|
|
this.log('info', `audio: context ${ctx.sampleRate} Hz, baseLatency ${Math.round((ctx.baseLatency || 0) * 1000)} ms`);
|
|
}
|
|
|
|
setOutputLevelDb(db) {
|
|
this.outputLevelDb = db;
|
|
if (this.voiceGain) this.voiceGain.gain.setTargetAtTime(dbToGain(db), this.ctx.currentTime, 0.02);
|
|
}
|
|
|
|
setPlaybackDsp(config) {
|
|
this.playbackDsp = { comfortNoise: config.comfortNoise, comfortNoiseLevel: config.comfortNoiseLevel, echoReduction: config.echoReduction };
|
|
this.playback?.port.postMessage({ type: 'dsp', ...this.playbackDsp });
|
|
}
|
|
|
|
setPlaybackEnabled(enabled) {
|
|
this.playbackEnabled = enabled;
|
|
this.playback?.port.postMessage({ type: 'enabled', enabled });
|
|
}
|
|
|
|
setTransmitting(active) {
|
|
if (active === this.transmitting) return;
|
|
this.transmitting = active;
|
|
this.playback?.port.postMessage({ type: 'transmitting', active });
|
|
}
|
|
|
|
setTypingEnabled(enabled) {
|
|
this.typingEnabled = enabled;
|
|
this.capture?.node.port.postMessage({ type: 'typing', enabled });
|
|
}
|
|
|
|
typingHit() { if (this.typingEnabled) this.capture?.node.port.postMessage({ type: 'typing-hit' }); }
|
|
|
|
/**
|
|
* Live level change of the running noise reduction; the processor resets its suppressor state.
|
|
* Switching noise reduction on or off needs a capture restart (the processor is built for one mode).
|
|
*/
|
|
setDenoiseLevel(level) {
|
|
this.denoiseLevel = level;
|
|
const c = this.capture;
|
|
if (!c || c.denoiseLevel === null || level === null || level === c.denoiseLevel) return;
|
|
c.denoiseLevel = level;
|
|
c.node.port.postMessage({ type: 'denoise-level', level });
|
|
}
|
|
|
|
// A capture-clock boundary rejects PCM already queued before a route/PTT/privacy transition: one frame,
|
|
// plus the noise suppressor's delay, during which its output still carries pre-boundary input.
|
|
discardCapturedFrames() {
|
|
const c = this.capture;
|
|
this.captureBoundary = c ? c.ctx.currentTime + 0.02 + (c.denoiseLevel === null ? 0 : DENOISE_DELAY) : 0;
|
|
}
|
|
|
|
async setOutputDevice(deviceId) {
|
|
this.stopDeviceTestPlayback();
|
|
await this.init();
|
|
if (typeof this.ctx.setSinkId !== 'function') throw new Error('Output device selection is not supported');
|
|
await this.ctx.setSinkId(deviceId || '');
|
|
this.outputDeviceId = deviceId || '';
|
|
}
|
|
|
|
stopDeviceTestPlayback() {
|
|
const source = this.testSource;
|
|
this.testSource = null;
|
|
if (source) { try { source.stop(); } catch { /* already ended */ } source.disconnect(); }
|
|
}
|
|
|
|
async playDeviceTest(samples, ended, isCurrent, deviceId) {
|
|
await this.setOutputDevice(deviceId);
|
|
if (!isCurrent()) return () => {};
|
|
const buffer = this.ctx.createBuffer(1, samples.length, 48000);
|
|
buffer.copyToChannel(samples, 0);
|
|
const source = this.ctx.createBufferSource();
|
|
source.buffer = buffer;
|
|
source.connect(this.voiceGain);
|
|
this.testSource = source;
|
|
source.onended = () => { if (this.testSource === source) this.testSource = null; source.disconnect(); ended(); };
|
|
source.start();
|
|
return () => { if (this.testSource === source) this.stopDeviceTestPlayback(); };
|
|
}
|
|
|
|
/** Copies the 1920-byte frame of connection `stream` into the worklet (transfer); rings are mixed there. */
|
|
pushPlayback(bytes, stream) {
|
|
if (!this.playback || this.playbackFailed || this.ctx?.state === 'closed' || typeof stream !== 'string') return;
|
|
const pcm = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
this.playback.port.postMessage({ stream, pcm }, [pcm]);
|
|
this.stats.framesOut += 1;
|
|
}
|
|
|
|
/** Drops buffered voice of one connection, or of all connections without `stream`. */
|
|
flushPlayback(stream) {
|
|
if (this.playback) this.playback.port.postMessage(typeof stream === 'string' ? { type: 'flush', stream } : { type: 'flush' });
|
|
}
|
|
|
|
/** The connection is gone: free its ring. */
|
|
removePlaybackStream(stream) {
|
|
if (this.playback && typeof stream === 'string') this.playback.port.postMessage({ type: 'remove', stream });
|
|
}
|
|
|
|
playbackStats() {
|
|
if (!this.playback || this.playbackFailed || this.ctx?.state === 'closed') return Promise.resolve(null);
|
|
return new Promise((resolve) => {
|
|
this.statsWaiters.push(resolve);
|
|
this.playback.port.postMessage({ type: 'stats' });
|
|
});
|
|
}
|
|
|
|
get capturing() {
|
|
return this.capture !== null;
|
|
}
|
|
|
|
/** True while a startCapture() call is still waiting for the engine or the microphone. */
|
|
get captureStarting() {
|
|
return this.startingGen !== null;
|
|
}
|
|
|
|
/** Whether the running capture was built with noise reduction (switching it needs a restart). */
|
|
get captureDenoising() {
|
|
return this.capture !== null && this.capture.denoiseLevel !== null;
|
|
}
|
|
|
|
/**
|
|
* Opens the microphone. Every later startCapture() or stopCapture() supersedes a pending call: when
|
|
* getUserMedia resolves for a superseded call its tracks are stopped at once and null is returned, so a
|
|
* disconnect or a closed mic test during the permission/device wait never leaves a microphone open.
|
|
* `denoiseLevel` (0..3, null = off) selects TeamsPeach's noise reduction; Chromium's own noise
|
|
* suppression is always off, so the voice is never suppressed twice nor by a different algorithm.
|
|
* A noise reduction that cannot load or start fails the capture: the microphone is never sent unprocessed.
|
|
*/
|
|
async startCapture({ deviceId, echoCancellation, autoGainControl, denoiseLevel = null }) {
|
|
const gen = ++this.captureGen;
|
|
this.startingGen = gen;
|
|
this.denoiseLevel = denoiseLevel;
|
|
this.releaseCapture();
|
|
try {
|
|
return await this.openCapture(gen, { deviceId, echoCancellation, autoGainControl, denoiseLevel });
|
|
} catch (err) {
|
|
if (gen !== this.captureGen) return null; // superseded: the failure no longer matters
|
|
throw err;
|
|
} finally {
|
|
if (this.startingGen === gen) this.startingGen = null;
|
|
}
|
|
}
|
|
|
|
async openCapture(gen, { deviceId, echoCancellation, autoGainControl, denoiseLevel }) {
|
|
await this.init();
|
|
await this.captureClosing;
|
|
if (gen !== this.captureGen) return null;
|
|
if (this.failedCaptureContext) {
|
|
this.captureClosing = this.closeCaptureContext(this.failedCaptureContext);
|
|
await this.captureClosing;
|
|
if (gen !== this.captureGen) return null;
|
|
if (this.failedCaptureContext) throw this.captureCloseError;
|
|
}
|
|
// Before the microphone opens: a missing or invalid module never leaves it open.
|
|
const denoiseModule = denoiseLevel === null ? null : await loadDenoiseModule();
|
|
if (gen !== this.captureGen) return null;
|
|
const audio = {
|
|
channelCount: 1,
|
|
echoCancellation,
|
|
noiseSuppression: false,
|
|
autoGainControl,
|
|
};
|
|
if (deviceId) audio.deviceId = { exact: deviceId };
|
|
let stream;
|
|
try {
|
|
stream = await navigator.mediaDevices.getUserMedia({ audio, video: false });
|
|
} catch (err) {
|
|
// A saved microphone that is gone is an error: never open a different microphone in its place.
|
|
if (deviceId && err && err.name === 'OverconstrainedError') {
|
|
throw Object.assign(new Error('Selected microphone is not available'), { name: 'OverconstrainedError', code: 'device_unavailable' });
|
|
}
|
|
throw err;
|
|
}
|
|
if (gen !== this.captureGen) {
|
|
for (const t of stream.getTracks()) t.stop();
|
|
return null;
|
|
}
|
|
let source = null;
|
|
let node = null;
|
|
let sink = null;
|
|
let ctx = null;
|
|
let processorErrorHandler = null;
|
|
let ready = null; // pending noise-reduction start: the processor answers 'ready' or a fatal error
|
|
let level = null;
|
|
try {
|
|
ctx = new AudioContext({ sampleRate: 48000, latencyHint: 'interactive' });
|
|
const opening = { stream, ctx, cancel: null };
|
|
this.openingCapture = opening;
|
|
await ctx.audioWorklet.addModule(new URL('./capture-worklet.js', import.meta.url));
|
|
if (gen !== this.captureGen) return null;
|
|
if (ctx.state !== 'running') await ctx.resume();
|
|
if (gen !== this.captureGen) return null;
|
|
level = denoiseModule ? (this.denoiseLevel ?? denoiseLevel) : null;
|
|
source = ctx.createMediaStreamSource(stream);
|
|
node = new AudioWorkletNode(ctx, 'tp-capture', {
|
|
numberOfInputs: 1,
|
|
numberOfOutputs: 1,
|
|
outputChannelCount: [1],
|
|
channelCount: 1,
|
|
channelCountMode: 'explicit',
|
|
channelInterpretation: 'speakers',
|
|
processorOptions: denoiseModule ? { denoise: { module: denoiseModule, level } } : {},
|
|
});
|
|
sink = ctx.createGain();
|
|
sink.gain.value = 0;
|
|
node.port.postMessage({ type: 'typing', enabled: this.typingEnabled });
|
|
this.captureBoundary = ctx.currentTime;
|
|
node.port.onmessage = (event) => {
|
|
const data = event.data;
|
|
if (data.type === 'frame') {
|
|
// MessagePort can accumulate speech while the renderer is busy. The core's bounded
|
|
// queue cannot age those messages before IPC. Match its 200 ms live-audio budget;
|
|
// compare only clocks belonging to this capture context (never performance.now()).
|
|
if (ctx.currentTime - data.capturedAt > 0.2 || data.capturedAt <= this.captureBoundary) {
|
|
this.stats.staleCaptureFrames += 1;
|
|
return;
|
|
}
|
|
this.onFrame(data.pcm, data.rms, data.peak);
|
|
} else if (data.type === 'ready') {
|
|
ready?.resolve();
|
|
} else if (data.type === 'error') {
|
|
if (!data.fatal) this.onError({ code: 'capture', message: data.message });
|
|
else if (ready) ready.reject(new Error(data.message));
|
|
else if (this.capture?.node === node) {
|
|
// The processor stopped emitting frames; release the microphone and report it.
|
|
this.stopCapture();
|
|
this.onError({ code: 'capture', message: data.message });
|
|
}
|
|
}
|
|
};
|
|
processorErrorHandler = () => {
|
|
if (ready) {
|
|
ready.reject(new Error('Microphone audio processor failed'));
|
|
return;
|
|
}
|
|
if (this.capture?.node !== node) return;
|
|
this.stopCapture();
|
|
this.onError({ code: 'capture', message: 'Microphone audio processor failed' });
|
|
};
|
|
node.addEventListener('processorerror', processorErrorHandler, { once: true });
|
|
if (denoiseModule) {
|
|
await new Promise((resolve, reject) => {
|
|
let timer = 0;
|
|
const settle = (done, value) => { clearTimeout(timer); ready = null; opening.cancel = null; done(value); };
|
|
ready = { resolve: () => settle(resolve), reject: (err) => settle(reject, err) };
|
|
opening.cancel = ready.resolve; // superseded: stop waiting, the context is being closed
|
|
timer = setTimeout(() => ready?.reject(new Error('Noise reduction did not start')), PROCESSOR_READY_TIMEOUT_MS);
|
|
});
|
|
if (gen !== this.captureGen) {
|
|
node.removeEventListener('processorerror', processorErrorHandler);
|
|
node.port.onmessage = null;
|
|
node.port.close();
|
|
return null;
|
|
}
|
|
}
|
|
source.connect(node).connect(sink).connect(ctx.destination);
|
|
} catch (err) {
|
|
// The microphone is already open: release it and whatever was built before rethrowing.
|
|
for (const t of stream.getTracks()) t.stop();
|
|
if (node) node.removeEventListener('processorerror', processorErrorHandler);
|
|
if (node) {
|
|
await this.closeCaptureNode(node, ctx);
|
|
}
|
|
for (const part of [source, node, sink]) {
|
|
try {
|
|
part?.disconnect();
|
|
} catch {
|
|
// never connected
|
|
}
|
|
}
|
|
if (ctx && !node) await this.closeCaptureContext(ctx);
|
|
throw err;
|
|
} finally {
|
|
if (this.openingCapture?.ctx === ctx) this.openingCapture = null;
|
|
}
|
|
const track = stream.getAudioTracks()[0];
|
|
const onEnded = () => {
|
|
if (this.capture && this.capture.stream === stream) {
|
|
this.stopCapture();
|
|
this.onError({ code: 'device_lost', message: 'Microphone disconnected' });
|
|
}
|
|
};
|
|
const onMute = () => this.log('warn', 'audio: capture track muted by the system');
|
|
const onUnmute = () => this.log('info', 'audio: capture track unmuted');
|
|
const trackHandlers = { ended: onEnded, mute: onMute, unmute: onUnmute };
|
|
for (const [event, handler] of Object.entries(trackHandlers)) track.addEventListener(event, handler);
|
|
this.capture = { ctx, stream, source, node, sink, track, trackHandlers, processorErrorHandler, denoiseLevel: level, label: track ? track.label : '' };
|
|
const settings = track ? track.getSettings() : {};
|
|
this.log('info', `audio: capture started "${track ? track.label : '?'}" ${settings.sampleRate ?? '?'} Hz, ${settings.channelCount ?? '?'} ch, muted=${track ? track.muted : '?'}, ec=${settings.echoCancellation} ns=${settings.noiseSuppression} agc=${settings.autoGainControl} denoise=${level ?? 'off'}`);
|
|
// A level chosen while this capture was starting.
|
|
this.setDenoiseLevel(this.denoiseLevel);
|
|
return this.capture.label;
|
|
}
|
|
|
|
/** Stops the microphone and cancels a pending startCapture(). */
|
|
stopCapture() {
|
|
this.captureGen += 1;
|
|
this.startingGen = null;
|
|
this.releaseCapture();
|
|
}
|
|
|
|
releaseCapture() {
|
|
const opening = this.openingCapture;
|
|
this.openingCapture = null;
|
|
if (opening) {
|
|
opening.cancel?.();
|
|
for (const track of opening.stream.getTracks()) track.stop();
|
|
this.captureClosing = this.closeCaptureContext(opening.ctx);
|
|
}
|
|
const c = this.capture;
|
|
if (!c) return;
|
|
this.capture = null;
|
|
c.node.removeEventListener('processorerror', c.processorErrorHandler);
|
|
this.captureClosing = this.closeCaptureNode(c.node, c.ctx);
|
|
for (const [event, handler] of Object.entries(c.trackHandlers)) c.track.removeEventListener(event, handler);
|
|
try {
|
|
c.source.disconnect();
|
|
c.node.disconnect();
|
|
c.sink.disconnect();
|
|
} catch {
|
|
// already disconnected
|
|
}
|
|
for (const t of c.stream.getTracks()) t.stop();
|
|
}
|
|
|
|
async closeCaptureNode(node, ctx) {
|
|
// Let the processor return false before closing its context. The deadline releases even a
|
|
// failed worklet; microphone tracks are stopped synchronously by releaseCapture regardless.
|
|
await new Promise((resolve) => {
|
|
const timer = setTimeout(resolve, 1000);
|
|
node.port.onmessage = ({ data }) => {
|
|
if (data?.type === 'stopped') {
|
|
clearTimeout(timer);
|
|
resolve();
|
|
}
|
|
};
|
|
node.port.postMessage({ type: 'stop' });
|
|
});
|
|
node.port.onmessage = null;
|
|
node.port.close();
|
|
await this.closeCaptureContext(ctx);
|
|
}
|
|
|
|
async closeCaptureContext(ctx) {
|
|
try {
|
|
if (ctx.state !== 'closed') await ctx.close();
|
|
if (this.failedCaptureContext === ctx) {
|
|
this.failedCaptureContext = null;
|
|
this.captureCloseError = null;
|
|
}
|
|
} catch (err) {
|
|
// Retain failed ownership; only a later explicit start retries, before acquiring a microphone.
|
|
this.failedCaptureContext = ctx;
|
|
this.captureCloseError = err;
|
|
this.onError({ code: 'capture', message: `Could not close microphone audio context: ${err.message}` });
|
|
}
|
|
}
|
|
}
|