#!/usr/bin/env bash
#
# pcm-play — low-latency PCM audio player from base64-encoded stream
#
# Reads base64-encoded f32le PCM lines on stdin, decodes them,
# and plays through the default audio output with minimal buffering.
#
# Usage:
#   some-stream-source | pcm-play [sample_rate] [channels]
#
# Defaults: 48000 Hz, 2 channels (stereo)

set -euo pipefail

RATE="${1:-48000}"
CHANNELS="${2:-2}"

case "$CHANNELS" in
  1) LAYOUT="mono" ;;
  2) LAYOUT="stereo" ;;
  *) LAYOUT="$CHANNELS channels" ;;
esac

exec grep -v '^$' \
  | python3 -u -c "
import sys, base64
for line in sys.stdin.buffer:
    line = line.strip()
    if line:
        sys.stdout.buffer.write(base64.b64decode(line))
        sys.stdout.buffer.flush()
" \
  | ffplay -nodisp \
      -fflags nobuffer \
      -flags low_delay \
      -probesize 32 \
      -analyzeduration 0 \
      -f f32le \
      -ar "$RATE" \
      -ch_layout "$LAYOUT" \
      -i pipe:0
