// pcm-processor.js
class PCMProcessor extends AudioWorkletProcessor {
    constructor() {
        super();
        this.buffer = new Int16Array(1024); // 64ms at 16kHz
        this.bufferIndex = 0;
    }

    process(inputs) {
        const input = inputs[0];
        if (input.length > 0) {
            const float32Data = input[0];
            for (let i = 0; i < float32Data.length; i++) {
                this.buffer[this.bufferIndex++] = Math.max(-1, Math.min(1, float32Data[i])) * 0x7FFF;
                if (this.bufferIndex >= this.buffer.length) {
                    // Packet: 2 bytes header + 2048 bytes payload = 2049 bytes (Even!)
                    const packet = new Uint8Array(1 + this.buffer.byteLength);
                    packet[0] = 0; // Type: Audio
                    packet.set(new Uint8Array(this.buffer.buffer), 1);
                    
                    this.port.postMessage(packet.buffer, [packet.buffer]);
                    this.buffer = new Int16Array(1024);
                    this.bufferIndex = 0;
                }
            }
        }
        return true;
    }
}
registerProcessor('pcm-processor', PCMProcessor);