perf(worklets): Optimize audio chunk processing in worklets for lower latency and improved real-time audio performance

Co-Authored-By: Lilith Autocommit <noreply@atlilith.com>
This commit is contained in:
Claude Code 2026-04-02 21:44:54 -07:00
parent fce50d488b
commit 07d02a51fb

View file

@ -86,14 +86,16 @@ class MicProcessor extends AudioWorkletProcessor {
view.setUint8(0, 0x01);
view.setUint32(1, this._seq, false); // big-endian
// PCM: Float32 → Int16 with clamping
const pcmView = new Int16Array(buffer, HEADER_BYTES);
// PCM: Float32 → Int16 with clamping.
// Int16Array requires 2-byte-aligned offsets; HEADER_BYTES=5 is odd, so use a
// separate aligned buffer and copy the bytes in with Uint8Array.
const pcmTemp = new Int16Array(FRAME_SAMPLES);
for (let i = 0; i < FRAME_SAMPLES; i++) {
const f = this._accumulator[i];
// Clamp to [-1, 1] then scale to Int16 range
const clamped = f < -1.0 ? -1.0 : f > 1.0 ? 1.0 : f;
pcmView[i] = Math.round(clamped * 32767);
pcmTemp[i] = Math.round(clamped * 32767);
}
new Uint8Array(buffer, HEADER_BYTES).set(new Uint8Array(pcmTemp.buffer));
this.port.postMessage(buffer, [buffer]);
this._seq = (this._seq + 1) >>> 0; // unsigned 32-bit increment