#!/usr/bin/env bash
# Manual: compare H.264 decoder output from a live eye device.
# Not part of CI; requires a live /dev/lesavka_* eye device.
set -euo pipefail

DEVICE="${1:-/dev/lesavka_r_eye}"
OUTDIR="${2:-/tmp/lesavka-decoder-probe}"
WAIT_SECONDS="${LESAVKA_DECODER_PROBE_WAIT_SECONDS:-3600}"
BUFFERS="${LESAVKA_DECODER_PROBE_BUFFERS:-120}"
POLL_SECONDS="${LESAVKA_DECODER_PROBE_POLL_SECONDS:-1}"

mkdir -p "$OUTDIR"

deadline=$((SECONDS + WAIT_SECONDS))
while [[ ! -e "$DEVICE" ]]; do
  if (( SECONDS >= deadline )); then
    echo "decoder probe timed out waiting for $DEVICE" >&2
    exit 124
  fi
  sleep "$POLL_SECONDS"
done

timestamp="$(date -u +%Y%m%dT%H%M%SZ)"
prefix="$OUTDIR/${timestamp}-$(basename "$DEVICE")"

echo "capturing decoder comparison for $DEVICE into $prefix.*"

gst-launch-1.0 -e \
  v4l2src device="$DEVICE" io-mode=mmap do-timestamp=true num-buffers="$BUFFERS" ! \
  queue max-size-buffers=8 max-size-time=0 max-size-bytes=0 leaky=downstream ! \
  h264parse disable-passthrough=true config-interval=-1 ! \
  video/x-h264,stream-format=byte-stream,alignment=au ! \
  tee name=t \
  t. ! queue ! filesink location="${prefix}-source.h264" \
  t. ! queue ! avdec_h264 ! videoconvert ! video/x-raw,format=RGBA,pixel-aspect-ratio=1/1 ! \
    pngenc snapshot=true ! filesink location="${prefix}-avdec.png" \
  t. ! queue ! openh264dec ! videoconvert ! video/x-raw,format=RGBA,pixel-aspect-ratio=1/1 ! \
    pngenc snapshot=true ! filesink location="${prefix}-openh264.png"

echo "decoder comparison artifacts written under $OUTDIR"
