// file: stream-processor.js
class StreamProcessor extends AudioWorkletProcessor {
  constructor() {
    super();
    this.audioQueue = []; // Internal queue for storing audio data

    // Listen for incoming audio data from the main thread
    this.port.onmessage = (event) => {
      const { audioData } = event.data;
      if (audioData) {
        this.audioQueue.push(audioData); // Add received audio to the queue
      }
    };
  }

  process(inputs, outputs) {
    const output = outputs[0]; // Get output channels
    const channelCount = output.length;

    if (this.audioQueue.length > 0) {
      const audioData = this.audioQueue.shift(); // Get the next chunk of audio

      for (let channel = 0; channel < channelCount; channel++) {
        const outputChannel = output[channel];
        const inputChannel = audioData[channel] || new Float32Array(outputChannel.length);
        outputChannel.set(inputChannel.slice(0, outputChannel.length));
      }
    } else {
      // Fill output with silence if there's no audio data
      for (let channel = 0; channel < channelCount; channel++) {
        output[channel].fill(0);
      }
    }

    return true; // Keep the processor alive
  }
}

registerProcessor('stream-processor', StreamProcessor);
