class StreamProcessor extends AudioWorkletProcessor {
  constructor() {
    super();
    this.audioQueue = []; // Queue for incoming audio data
  }

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

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

      // Fill output channels with the audio data
      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
  }

  // Called from the main thread to enqueue audio data
  enqueueAudio(audioData) {
    this.audioQueue.push(audioData);
  }
}

registerProcessor('stream-processor', StreamProcessor);
