193 lines
7.4 KiB
JavaScript
193 lines
7.4 KiB
JavaScript
// Microphone → 20 ms frames of 960 signed 16-bit mono samples at 48 kHz (bridge §4.9).
|
|
//
|
|
// Noise reduction: processorOptions.denoise = { module, level } carries the WebAssembly.Module the
|
|
// renderer compiled from the local denoise.wasm (WebRTC-derived sonora noise suppressor, fullband 48 kHz
|
|
// through its three-band split/merge) and the official denoiser level 0..3. It runs on 10 ms blocks of
|
|
// 480 samples; two blocks make one frame, so a frame still completes at the same input sample — and
|
|
// carries the same capture timestamp — as without it. The suppressor itself delays the audio by a fixed
|
|
// ≈6.5 ms (312 samples), in order, one sample out per sample in. Without the option the clamped input is
|
|
// quantized unchanged. Any denoiser failure posts a fatal error and no further frames: the microphone is
|
|
// never sent unprocessed while noise reduction is selected.
|
|
//
|
|
// WASM ABI (dsp/src/lib.rs): dsp_new(level) → handle, 0 on failure; dsp_input(handle) → byte offset of the
|
|
// handle's 480 f32 in/out block (stable for the handle's life); dsp_process(handle) → 0 when the block was
|
|
// processed in place; dsp_reset(handle, level) → 0 when all state was cleared (block zeroed); dsp_free(handle).
|
|
// Samples are normalized [-1, 1] both ways. Memory grows only in dsp_new/dsp_reset, so the block view is
|
|
// re-created after both; dsp_process never allocates.
|
|
const FRAME = 960;
|
|
const BLOCK = 480;
|
|
const TYPING_GAIN = 10 ** (-18 / 20);
|
|
|
|
class CaptureProcessor extends AudioWorkletProcessor {
|
|
constructor(options) {
|
|
super();
|
|
this.frame = new Int16Array(FRAME);
|
|
this.pos = 0;
|
|
this.sumSq = 0;
|
|
this.peak = 0;
|
|
this.stopped = false;
|
|
this.failed = false;
|
|
this.denoise = null;
|
|
// Hints come only from application key events; this processor never observes global keys.
|
|
this.typingEnabled = false;
|
|
this.typingGain = 1;
|
|
this.typingRemaining = 0;
|
|
this.typingAttackSamples = Math.max(1, Math.round(sampleRate * 0.002));
|
|
this.typingHoldSamples = Math.round(sampleRate * 0.06);
|
|
this.typingAttackStep = (1 - TYPING_GAIN) / this.typingAttackSamples;
|
|
this.typingReleaseStep = (1 - TYPING_GAIN) / Math.max(1, Math.round(sampleRate * 0.04));
|
|
this.port.onmessage = ({ data }) => {
|
|
if (data?.type === 'stop') {
|
|
this.stopped = true;
|
|
} else if (data?.type === 'typing' && typeof data.enabled === 'boolean') {
|
|
this.typingEnabled = data.enabled;
|
|
if (!this.typingEnabled) {
|
|
this.typingGain = 1;
|
|
this.typingRemaining = 0;
|
|
}
|
|
} else if (data?.type === 'typing-hit' && this.typingEnabled) {
|
|
this.typingRemaining = this.typingAttackSamples + this.typingHoldSamples;
|
|
} else if (data?.type === 'denoise-level') {
|
|
this.setDenoiseLevel(data.level);
|
|
}
|
|
};
|
|
const denoise = options?.processorOptions?.denoise;
|
|
if (denoise) {
|
|
this.startDenoise(denoise);
|
|
if (!this.failed) this.port.postMessage({ type: 'ready' });
|
|
} else if (sampleRate !== 48000) {
|
|
this.port.postMessage({ type: 'error', message: `sample rate ${sampleRate}` });
|
|
}
|
|
}
|
|
|
|
startDenoise({ module, level }) {
|
|
try {
|
|
if (sampleRate !== 48000) throw new Error(`sample rate ${sampleRate}`);
|
|
if (!Number.isInteger(level) || level < 0 || level > 3) throw new Error(`invalid level ${level}`);
|
|
const exports = new WebAssembly.Instance(module, {}).exports;
|
|
const handle = exports.dsp_new(level);
|
|
if (!handle) throw new Error('dsp_new failed');
|
|
this.denoise = { exports, handle, level, block: null, pos: 0, hold: new Float32Array(BLOCK) };
|
|
this.viewDenoiseBlock();
|
|
} catch (err) {
|
|
this.fail(`Noise reduction could not start: ${err.message}`);
|
|
}
|
|
}
|
|
|
|
viewDenoiseBlock() {
|
|
const d = this.denoise;
|
|
const offset = d.exports.dsp_input(d.handle);
|
|
if (!offset) throw new Error('dsp_input failed');
|
|
d.block = new Float32Array(d.exports.memory.buffer, offset, BLOCK);
|
|
}
|
|
|
|
/** A level change clears the suppressor state; samples already gathered for the next block are kept. */
|
|
setDenoiseLevel(level) {
|
|
const d = this.denoise;
|
|
if (!d || this.failed || level === d.level) return;
|
|
try {
|
|
if (!Number.isInteger(level) || level < 0 || level > 3) throw new Error(`invalid level ${level}`);
|
|
d.hold.set(d.block.subarray(0, d.pos));
|
|
const status = d.exports.dsp_reset(d.handle, level);
|
|
if (status !== 0) throw new Error(`dsp_reset status ${status}`);
|
|
d.level = level;
|
|
this.viewDenoiseBlock();
|
|
d.block.set(d.hold.subarray(0, d.pos));
|
|
} catch (err) {
|
|
this.fail(`Noise reduction failed: ${err.message}`);
|
|
}
|
|
}
|
|
|
|
releaseDenoise() {
|
|
const d = this.denoise;
|
|
this.denoise = null;
|
|
try {
|
|
d?.exports.dsp_free(d.handle);
|
|
} catch {
|
|
// the instance is discarded with this processor either way
|
|
}
|
|
}
|
|
|
|
fail(message) {
|
|
this.failed = true;
|
|
this.releaseDenoise();
|
|
this.port.postMessage({ type: 'error', fatal: true, message });
|
|
}
|
|
|
|
process(inputs, outputs) {
|
|
if (this.stopped) {
|
|
this.releaseDenoise();
|
|
this.port.postMessage({ type: 'stopped' });
|
|
this.port.close();
|
|
return false;
|
|
}
|
|
const input = inputs[0];
|
|
const out = outputs[0] && outputs[0][0];
|
|
if (out) out.fill(0);
|
|
if (this.failed || !input || input.length === 0) return true;
|
|
const ch = input[0];
|
|
const d = this.denoise;
|
|
for (let i = 0; i < ch.length; i += 1) {
|
|
let s = ch[i];
|
|
if (s > 1) s = 1;
|
|
else if (s < -1) s = -1;
|
|
if (this.typingEnabled) {
|
|
if (this.typingRemaining > 0) {
|
|
this.typingGain = Math.max(TYPING_GAIN, this.typingGain - this.typingAttackStep);
|
|
this.typingRemaining -= 1;
|
|
} else {
|
|
this.typingGain = Math.min(1, this.typingGain + this.typingReleaseStep);
|
|
}
|
|
s *= this.typingGain;
|
|
}
|
|
if (d === null) {
|
|
this.emit(s, i);
|
|
continue;
|
|
}
|
|
d.block[d.pos] = s === s ? s : 0; // NaN quantizes to 0 without the denoiser too
|
|
d.pos += 1;
|
|
if (d.pos === BLOCK) {
|
|
d.pos = 0;
|
|
let status;
|
|
try {
|
|
status = d.exports.dsp_process(d.handle);
|
|
} catch (err) {
|
|
this.fail(`Noise reduction failed: ${err.message}`);
|
|
return true;
|
|
}
|
|
if (status !== 0) {
|
|
this.fail(`Noise reduction failed: dsp_process status ${status}`);
|
|
return true;
|
|
}
|
|
const block = d.block;
|
|
for (let k = 0; k < BLOCK; k += 1) this.emit(block[k], i);
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/** Quantizes one sample into the frame; `i` is the input sample index of this render quantum. */
|
|
emit(sample, i) {
|
|
let s = sample;
|
|
if (s > 1) s = 1;
|
|
else if (s < -1) s = -1;
|
|
this.frame[this.pos] = s < 0 ? Math.round(s * 0x8000) : Math.round(s * 0x7fff);
|
|
this.pos += 1;
|
|
this.sumSq += s * s;
|
|
const a = s < 0 ? -s : s;
|
|
if (a > this.peak) this.peak = a;
|
|
if (this.pos === FRAME) {
|
|
const pcm = this.frame.buffer;
|
|
// Timestamp in this capture context's sample clock, not wall time or the playback clock.
|
|
const capturedAt = (currentFrame + i + 1) / sampleRate;
|
|
this.port.postMessage({ type: 'frame', pcm, rms: Math.sqrt(this.sumSq / FRAME), peak: this.peak, capturedAt }, [pcm]);
|
|
this.frame = new Int16Array(FRAME);
|
|
this.pos = 0;
|
|
this.sumSq = 0;
|
|
this.peak = 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
registerProcessor('tp-capture', CaptureProcessor);
|