365 lines
16 KiB
JavaScript
365 lines
16 KiB
JavaScript
// Noise reduction: the real bundled denoise.wasm inside the real capture worklet (synthetic VM, no devices),
|
|
// the AudioEngine capture lifecycle around it with stubbed Web Audio / getUserMedia, and the preference
|
|
// schema/migration of the official denoiserLevel.
|
|
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { readFileSync } from 'node:fs';
|
|
import { createRequire } from 'node:module';
|
|
import vm from 'node:vm';
|
|
import { AudioEngine, DENOISE_DELAY } from '../app/renderer/js/audio/engine.js';
|
|
import { captureDenoiseLevel } from '../app/renderer/js/audio/profiles.js';
|
|
|
|
const require = createRequire(import.meta.url);
|
|
const { VOICE_SCHEMA, migrateVoicePrefs } = require('../app/main/voice-prefs.js');
|
|
|
|
const WASM_URL = new URL('../app/renderer/assets/audio/denoise.wasm', import.meta.url);
|
|
const module = new WebAssembly.Module(readFileSync(WASM_URL));
|
|
const workletSource = readFileSync(new URL('../app/renderer/js/audio/capture-worklet.js', import.meta.url), 'utf8');
|
|
|
|
function capture(options, rate = 48000) {
|
|
let Processor;
|
|
const messages = [];
|
|
const context = vm.createContext({
|
|
sampleRate: rate,
|
|
currentFrame: 0,
|
|
ArrayBuffer,
|
|
Int16Array,
|
|
Float32Array,
|
|
WebAssembly,
|
|
AudioWorkletProcessor: class {
|
|
constructor() { this.port = { postMessage(message) { messages.push(message); }, close() { this.closed = true; } }; }
|
|
},
|
|
registerProcessor(_id, implementation) { Processor = implementation; },
|
|
});
|
|
vm.runInContext(workletSource, context, { filename: 'capture-worklet.js' });
|
|
const processor = options === undefined ? new Processor() : new Processor(options);
|
|
return {
|
|
processor,
|
|
messages,
|
|
frames: () => messages.filter((m) => m.type === 'frame'),
|
|
send(data) { processor.port.onmessage({ data }); },
|
|
/** Feeds `input` in render quanta of `quantum` samples; returns whether the processor stays alive. */
|
|
render(input, quantum = 128) {
|
|
for (let offset = 0; offset < input.length; offset += quantum) {
|
|
const chunk = input.subarray(offset, Math.min(input.length, offset + quantum));
|
|
const output = new Float32Array(chunk.length);
|
|
if (!processor.process([[chunk]], [[output]])) return false;
|
|
assert.ok(output.every((v) => v === 0), 'the capture node output stays silent');
|
|
context.currentFrame += chunk.length;
|
|
}
|
|
return true;
|
|
},
|
|
};
|
|
}
|
|
const denoised = (level) => capture({ processorOptions: { denoise: { module, level } } });
|
|
|
|
/** Deterministic uniform noise in [-amplitude, amplitude). */
|
|
function noise(length, amplitude = 0.1, seed = 1) {
|
|
const out = new Float32Array(length);
|
|
let state = seed >>> 0;
|
|
for (let i = 0; i < length; i += 1) {
|
|
state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
|
|
out[i] = (state / 2 ** 32 * 2 - 1) * amplitude;
|
|
}
|
|
return out;
|
|
}
|
|
const pcmOf = (frames) => {
|
|
const all = new Int16Array(frames.length * 960);
|
|
frames.forEach((frame, i) => all.set(new Int16Array(frame.pcm), i * 960));
|
|
return all;
|
|
};
|
|
const rms = (samples) => Math.sqrt(samples.reduce((sum, v) => sum + v * v, 0) / samples.length);
|
|
const near = (actual, expected, epsilon = 1e-9) => assert.ok(Math.abs(actual - expected) <= epsilon, `${actual} != ${expected}`);
|
|
|
|
test('the bundled module has the renderer ABI and no imports', () => {
|
|
assert.deepEqual(WebAssembly.Module.imports(module), []);
|
|
const exports = new Map(WebAssembly.Module.exports(module).map(({ name, kind }) => [name, kind]));
|
|
for (const name of ['dsp_new', 'dsp_input', 'dsp_process', 'dsp_reset', 'dsp_free']) assert.equal(exports.get(name), 'function', name);
|
|
assert.equal(exports.get('memory'), 'memory');
|
|
});
|
|
|
|
test('noise reduction off is the bit-preserving bypass and never reports a handshake', () => {
|
|
const input = noise(48000, 1.6, 7); // includes clipping
|
|
const plain = capture();
|
|
const off = capture({ processorOptions: {} });
|
|
plain.render(input);
|
|
off.render(input);
|
|
assert.deepEqual(pcmOf(off.frames()), pcmOf(plain.frames()));
|
|
assert.equal(off.messages.some((m) => m.type === 'ready' || m.type === 'error'), false);
|
|
});
|
|
|
|
test('every level starts, keeps 20 ms framing and capture timestamps, and is independent of the quantum size', () => {
|
|
const input = noise(48000 * 2 + 300, 0.1, 3);
|
|
for (const level of [0, 1, 2, 3]) {
|
|
const runs = [128, 960, 37].map((quantum) => {
|
|
const run = denoised(level);
|
|
assert.deepEqual(run.messages.map((m) => m.type), ['ready']); // VM-realm objects: compare fields
|
|
assert.equal(run.render(input, quantum), true);
|
|
return run.frames();
|
|
});
|
|
const frames = runs[0];
|
|
assert.equal(frames.length, Math.floor(input.length / 960));
|
|
frames.forEach((frame, k) => {
|
|
assert.equal(frame.pcm.byteLength, 1920);
|
|
near(frame.capturedAt, (k + 1) * 0.02);
|
|
});
|
|
for (const other of runs.slice(1)) {
|
|
assert.deepEqual(pcmOf(other), pcmOf(frames), `level ${level}: no sample dropped, duplicated or reordered`);
|
|
assert.deepEqual(other.map((f) => f.capturedAt), frames.map((f) => f.capturedAt));
|
|
}
|
|
}
|
|
});
|
|
|
|
test('stationary noise is reduced, more at Very High than at Low', () => {
|
|
const input = noise(48000 * 3, 0.1, 11);
|
|
const tail = (frames) => Array.from(pcmOf(frames).subarray(-48000), (v) => v / 32768);
|
|
const inputRms = rms(input.subarray(-48000));
|
|
const levels = [0, 1, 2, 3].map((level) => {
|
|
const run = denoised(level);
|
|
run.render(input);
|
|
assert.equal(run.messages.some((m) => m.type === 'error'), false);
|
|
return rms(tail(run.frames()));
|
|
});
|
|
for (const level of levels) assert.ok(level < inputRms * 0.9, `${level} vs input ${inputRms}`);
|
|
assert.ok(levels[3] < levels[0] * 0.8, `Very High ${levels[3]} vs Low ${levels[0]}`);
|
|
});
|
|
|
|
test('a level change resets the suppressor to a fresh state at that level without losing samples', () => {
|
|
const before = noise(9600, 0.1, 5);
|
|
const after = noise(9600 * 2, 0.1, 6);
|
|
const changed = denoised(1);
|
|
changed.render(before);
|
|
changed.send({ type: 'denoise-level', level: 3 });
|
|
changed.render(after);
|
|
const fresh = denoised(3);
|
|
fresh.render(after);
|
|
assert.deepEqual(pcmOf(changed.frames().slice(10)), pcmOf(fresh.frames()));
|
|
assert.equal(changed.processor.denoise.level, 3);
|
|
|
|
const midBlock = denoised(2);
|
|
midBlock.render(noise(1000, 0.1, 8), 1000);
|
|
midBlock.send({ type: 'denoise-level', level: 0 });
|
|
midBlock.render(noise(8600, 0.1, 9));
|
|
const frames = midBlock.frames();
|
|
assert.equal(frames.length, 10);
|
|
frames.forEach((frame, k) => near(frame.capturedAt, (k + 1) * 0.02));
|
|
assert.equal(midBlock.messages.some((m) => m.type === 'error'), false);
|
|
});
|
|
|
|
test('NaN input is quantized as silence, not reported as a denoiser failure', () => {
|
|
const run = denoised(1);
|
|
const input = noise(1920, 0.1, 4);
|
|
input[5] = NaN;
|
|
run.render(input);
|
|
assert.equal(run.frames().length, 2);
|
|
assert.equal(run.messages.some((m) => m.type === 'error'), false);
|
|
});
|
|
|
|
test('denoiser failures are fatal: no frames follow, and the stop handshake still completes', () => {
|
|
for (const [options, rate] of [[{ module, level: 4 }, 48000], [{ module, level: 1 }, 44100], [{ module: {}, level: 1 }, 48000]]) {
|
|
const run = capture({ processorOptions: { denoise: options } }, rate);
|
|
assert.equal(run.messages.length, 1);
|
|
assert.equal(run.messages[0].type, 'error');
|
|
assert.equal(run.messages[0].fatal, true);
|
|
run.render(noise(4800));
|
|
assert.equal(run.frames().length, 0);
|
|
run.send({ type: 'stop' });
|
|
assert.equal(run.render(new Float32Array(128)), false);
|
|
assert.equal(run.messages.at(-1).type, 'stopped');
|
|
}
|
|
const run = denoised(1);
|
|
run.render(noise(960));
|
|
run.send({ type: 'denoise-level', level: 9 });
|
|
assert.equal(run.messages.at(-1).fatal, true);
|
|
run.render(noise(4800));
|
|
assert.equal(run.frames().length, 1);
|
|
assert.equal(run.processor.denoise, null);
|
|
});
|
|
|
|
test('stop releases the denoiser handle', () => {
|
|
const run = denoised(2);
|
|
run.render(noise(960));
|
|
const { exports, handle } = run.processor.denoise;
|
|
run.send({ type: 'stop' });
|
|
assert.equal(run.render(new Float32Array(128)), false);
|
|
assert.equal(run.processor.denoise, null);
|
|
assert.equal(exports.dsp_input(handle), 0, 'the freed handle is invalid');
|
|
});
|
|
|
|
// ---------- AudioEngine capture lifecycle ----------
|
|
|
|
function fakeStream(name) {
|
|
const track = {
|
|
label: name,
|
|
muted: false,
|
|
stopped: false,
|
|
stop() { this.stopped = true; },
|
|
addEventListener() {},
|
|
removeEventListener() {},
|
|
getSettings: () => ({}),
|
|
};
|
|
return { track, getTracks: () => [track], getAudioTracks: () => [track] };
|
|
}
|
|
const mockNode = () => ({
|
|
handlers: new Map(),
|
|
addEventListener(type, handler) { this.handlers.set(type, handler); },
|
|
removeEventListener(type, handler) { if (this.handlers.get(type) === handler) this.handlers.delete(type); },
|
|
connect(next) { return next ?? this; },
|
|
disconnect() {},
|
|
port: { messages: [], postMessage(data) { this.messages.push(data); if (data.type === 'stop') this.onmessage?.({ data: { type: 'stopped' } }); }, close() { this.closed = true; } },
|
|
gain: { value: 1 },
|
|
});
|
|
let wasmAvailable = true;
|
|
globalThis.fetch = async (url) => (wasmAvailable && String(url) === WASM_URL.href ? new Response(readFileSync(WASM_URL)) : new Response(null, { status: 404 }));
|
|
const answerReady = (node) => { if (node.options.processorOptions.denoise) queueMicrotask(() => node.port.onmessage?.({ data: { type: 'ready' } })); };
|
|
|
|
function engineSetup(worklet = answerReady) {
|
|
const pending = [];
|
|
const nodes = [];
|
|
Object.defineProperty(globalThis, 'navigator', {
|
|
configurable: true,
|
|
value: { mediaDevices: { getUserMedia: (constraints) => new Promise((resolve, reject) => pending.push({ constraints, resolve, reject })) } },
|
|
});
|
|
globalThis.AudioWorkletNode = class {
|
|
constructor(_ctx, _name, options) { Object.assign(this, mockNode(), { options }); nodes.push(this); worklet(this); }
|
|
};
|
|
globalThis.AudioContext = class {
|
|
constructor() { this.state = 'running'; this.currentTime = 0; this.audioWorklet = { addModule: async () => {} }; }
|
|
createMediaStreamSource() { return mockNode(); }
|
|
createGain() { return mockNode(); }
|
|
async close() { this.state = 'closed'; }
|
|
};
|
|
const errors = [];
|
|
const engine = new AudioEngine({ onFrame() {}, onError: (e) => errors.push(e), log() {} });
|
|
engine.init = async () => {};
|
|
return { engine, pending, nodes, errors };
|
|
}
|
|
async function until(condition) {
|
|
for (let i = 0; i < 2000 && !condition(); i += 1) await new Promise((resolve) => setTimeout(resolve, 1));
|
|
assert.ok(condition());
|
|
}
|
|
|
|
// First: the module cache must not have loaded the asset yet.
|
|
test('a missing noise-reduction module fails the capture before any microphone is requested', async () => {
|
|
wasmAvailable = false;
|
|
const { engine, pending } = engineSetup();
|
|
await assert.rejects(engine.startCapture({ denoiseLevel: 1 }), { code: 'denoise_unavailable' });
|
|
assert.equal(pending.length, 0);
|
|
assert.equal(engine.capturing, false);
|
|
wasmAvailable = true;
|
|
});
|
|
|
|
test('noise reduction capture: browser suppression off, module and level to the processor, live level reset', async () => {
|
|
const { engine, pending, nodes } = engineSetup();
|
|
const started = engine.startCapture({ denoiseLevel: 1, echoCancellation: true, autoGainControl: true });
|
|
await until(() => pending.length === 1);
|
|
assert.equal(pending[0].constraints.audio.noiseSuppression, false);
|
|
const stream = fakeStream('mic');
|
|
pending[0].resolve(stream);
|
|
assert.equal(await started, 'mic');
|
|
const { denoise } = nodes[0].options.processorOptions;
|
|
assert.ok(denoise.module instanceof WebAssembly.Module);
|
|
assert.equal(denoise.level, 1);
|
|
assert.equal(engine.captureDenoising, true);
|
|
engine.setDenoiseLevel(3);
|
|
engine.setDenoiseLevel(3);
|
|
assert.deepEqual(nodes[0].port.messages.filter((m) => m.type === 'denoise-level'), [{ type: 'denoise-level', level: 3 }]);
|
|
engine.capture.ctx.currentTime = 5;
|
|
engine.discardCapturedFrames();
|
|
near(engine.captureBoundary, 5 + 0.02 + DENOISE_DELAY);
|
|
engine.stopCapture();
|
|
await engine.captureClosing;
|
|
assert.equal(stream.track.stopped, true);
|
|
});
|
|
|
|
test('capture without noise reduction also disables browser suppression and builds the bypass processor', async () => {
|
|
const { engine, pending, nodes } = engineSetup();
|
|
const started = engine.startCapture({ denoiseLevel: null });
|
|
await until(() => pending.length === 1);
|
|
assert.equal(pending[0].constraints.audio.noiseSuppression, false);
|
|
pending[0].resolve(fakeStream('mic'));
|
|
await started;
|
|
assert.equal(nodes[0].options.processorOptions.denoise, undefined);
|
|
assert.equal(engine.captureDenoising, false);
|
|
engine.setDenoiseLevel(2);
|
|
assert.equal(nodes[0].port.messages.some((m) => m.type === 'denoise-level'), false);
|
|
engine.capture.ctx.currentTime = 5;
|
|
engine.discardCapturedFrames();
|
|
near(engine.captureBoundary, 5.02);
|
|
engine.stopCapture();
|
|
await engine.captureClosing;
|
|
});
|
|
|
|
test('a processor that cannot start noise reduction fails the capture and releases the microphone', async () => {
|
|
const { engine, pending } = engineSetup((node) => queueMicrotask(() => node.port.onmessage?.({ data: { type: 'error', fatal: true, message: 'Noise reduction could not start: x' } })));
|
|
const started = engine.startCapture({ denoiseLevel: 2 });
|
|
await until(() => pending.length === 1);
|
|
const stream = fakeStream('mic');
|
|
pending[0].resolve(stream);
|
|
await assert.rejects(started, /Noise reduction could not start: x/);
|
|
assert.equal(stream.track.stopped, true);
|
|
assert.equal(engine.capturing, false);
|
|
});
|
|
|
|
test('a running noise reduction failure stops capture and reports it', async () => {
|
|
const { engine, pending, nodes, errors } = engineSetup();
|
|
const started = engine.startCapture({ denoiseLevel: 0 });
|
|
await until(() => pending.length === 1);
|
|
const stream = fakeStream('mic');
|
|
pending[0].resolve(stream);
|
|
await started;
|
|
nodes[0].port.onmessage({ data: { type: 'error', fatal: true, message: 'Noise reduction failed: boom' } });
|
|
assert.equal(engine.capturing, false);
|
|
assert.equal(stream.track.stopped, true);
|
|
assert.deepEqual(errors, [{ code: 'capture', message: 'Noise reduction failed: boom' }]);
|
|
await engine.captureClosing;
|
|
});
|
|
|
|
test('a stop while the processor starts noise reduction supersedes the start at once', async () => {
|
|
const { engine, pending, nodes } = engineSetup(() => {});
|
|
const started = engine.startCapture({ denoiseLevel: 1 });
|
|
await until(() => pending.length === 1);
|
|
const stream = fakeStream('mic');
|
|
pending[0].resolve(stream);
|
|
await until(() => nodes.length === 1);
|
|
engine.stopCapture();
|
|
assert.equal(await started, null);
|
|
assert.equal(stream.track.stopped, true);
|
|
assert.equal(nodes[0].port.closed, true);
|
|
assert.equal(engine.capturing, false);
|
|
await engine.captureClosing;
|
|
});
|
|
|
|
// ---------- preferences ----------
|
|
|
|
function load(raw) {
|
|
const values = {};
|
|
for (const [key, spec] of Object.entries(VOICE_SCHEMA)) {
|
|
values[key] = Object.hasOwn(raw, key) && spec.check(raw[key]) ? raw[key] : structuredClone(spec.default);
|
|
}
|
|
return migrateVoicePrefs(raw, values);
|
|
}
|
|
|
|
test('denoiserLevel defaults to Moderate, validates 0..3, and is added to profiles stored before it existed', () => {
|
|
assert.equal(VOICE_SCHEMA.inputDsp.default.template.denoiseLevel, 1);
|
|
const old = { agc: true, denoise: false, typing: true, vad: true, vadMode: 'hybrid', vadLevel: -12, vadSensitivity: 'low' };
|
|
const migrated = load({ inputDsp: { template: { ...old, denoise: true }, devices: { mic: old } } });
|
|
assert.deepEqual(migrated.inputDsp, { template: { ...old, denoise: true, denoiseLevel: 1 }, devices: { mic: { ...old, denoiseLevel: 1 } } });
|
|
const stored = { template: { ...old, denoiseLevel: 3 }, devices: {} };
|
|
assert.deepEqual(load({ inputDsp: stored }).inputDsp, stored);
|
|
for (const bad of [4, -1, 1.5, '2']) assert.equal(VOICE_SCHEMA.inputDsp.check({ template: { ...old, denoiseLevel: bad }, devices: {} }), false);
|
|
assert.equal(load({ inputDsp: { template: { ...old, denoiseLevel: 9 }, devices: {} } }).inputDsp.template.denoiseLevel, 1);
|
|
const legacy = load({ noiseSuppression: false });
|
|
assert.equal(legacy.inputDsp.template.denoise, false);
|
|
assert.equal(legacy.inputDsp.template.denoiseLevel, 1);
|
|
});
|
|
|
|
test('the capture level is the device profile level only while noise reduction is on', () => {
|
|
const prefs = { inputDeviceId: 'a', inputDsp: { template: { denoise: true, denoiseLevel: 1 }, devices: { a: { denoise: true, denoiseLevel: 3 }, b: { denoise: false, denoiseLevel: 2 } } } };
|
|
assert.equal(captureDenoiseLevel(prefs), 3);
|
|
prefs.inputDeviceId = 'b';
|
|
assert.equal(captureDenoiseLevel(prefs), null);
|
|
prefs.inputDeviceId = 'other';
|
|
assert.equal(captureDenoiseLevel(prefs), 1);
|
|
});
|