#!/usr/bin/env bash
# normalize-two-pass.sh: measure a recording, then bring it to -16 LUFS (true peak limit -1.5 dBTP) and save an MP3.
# Usage: bash normalize-two-pass.sh input.wav output.mp3     (any audio file ffmpeg reads; mono or stereo is kept)
set -euo pipefail
in="${1:-}"; out="${2:-}"
[ -n "$in" ] && [ -n "$out" ] || { echo "usage: bash normalize-two-pass.sh input output.mp3" >&2; exit 2; }
[ -s "$in" ] || { echo "input missing or empty: $in" >&2; exit 2; }
dur=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$in" 2>/dev/null | head -1 || true)
case "$dur" in ""|N/A) ;; *) awk -v d="$dur" 'BEGIN{exit !(d<3)}' && { echo "clip shorter than 3 s ($dur s): loudnorm cannot measure it, not processed" >&2; exit 5; };; esac
j=$(ffmpeg -hide_banner -nostats -i "$in" -af loudnorm=I=-16:TP=-1.5:LRA=11:print_format=json -f null - 2>&1) || { echo "ffmpeg could not read $in" >&2; exit 3; }
field() { printf '%s\n' "$j" | sed -n "s/.*\"$1\" *: *\"\([^\"]*\)\".*/\1/p" | tail -1; }
mI=$(field input_i); mTP=$(field input_tp); mLRA=$(field input_lra); mT=$(field input_thresh); off=$(field target_offset)
case "$mI" in ""|-inf|inf) echo "no measurable speech in $in (silent or too short)" >&2; exit 4;; esac
echo "measured: I=$mI LUFS TP=$mTP dBTP LRA=$mLRA LU"
ffmpeg -hide_banner -loglevel error -y -i "$in" -af "loudnorm=I=-16:TP=-1.5:LRA=11:measured_I=$mI:measured_TP=$mTP:measured_LRA=$mLRA:measured_thresh=$mT:offset=$off:linear=true" -ar 48000 -c:a libmp3lame -q:a 2 "$out"
echo "wrote $out"
