#!/usr/bin/env bash
# measure.sh <file>: one line with integrated loudness, loudness range, true peak, peak-to-loudness (PLR), channels, duration.
set -euo pipefail
f="${1:-}"
[ -s "$f" ] || { echo "input missing or empty: $f" >&2; exit 2; }
out=$(ffmpeg -hide_banner -nostats -i "$f" -af ebur128=peak=true -f null - 2>&1) || { echo "ffmpeg could not read $f" >&2; exit 3; }
I=$(echo "$out" | awk '/I:/ && /LUFS/ {v=$2} END{print v}')
L=$(echo "$out" | awk '/LRA:/ && /LU/ {v=$2} END{print v}')
P=$(echo "$out" | awk '/Peak:/ {v=$2} END{print v}')
ch=$(ffprobe -v error -select_streams a:0 -show_entries stream=channels -of csv=p=0 "$f")
d=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$f")
awk -v d="$d" 'BEGIN{exit !(d<3)}' && echo "warning: clip shorter than 3 s, the reading is not reliable" >&2
awk -v n="$(basename "$f")" -v I="$I" -v L="$L" -v P="$P" -v ch="$ch" -v d="$d" 'BEGIN{printf "%s\tI=%s LUFS\tLRA=%s LU\tTP=%s dBTP\tPLR=%.1f dB\tch=%s\tdur=%.1f s\n", n, I, L, P, P-I, ch, d}'
