class RecorderProcessor extends AudioWorkletProcessor {
  process(inputs) {
    const input = inputs[0]
    if (!input || !input[0]) {
      return true
    }

    const samples = input[0]
    const pcm = new Int16Array(samples.length)
    for (let i = 0; i < samples.length; i += 1) {
      const sample = Math.max(-1, Math.min(1, samples[i]))
      pcm[i] = sample < 0 ? sample * 0x8000 : sample * 0x7fff
    }

    this.port.postMessage({ type: "pcm", data: pcm.buffer }, [pcm.buffer])
    return true
  }
}

registerProcessor("pmate-mic-recorder-processor", RecorderProcessor)
