#!/usr/bin/env bash
# check-level.sh <audio-or-video-file>: one line with loudness, true peak, speech level, noise floor and the gap between them.
# Needs ffmpeg 5 or newer and awk. Speech level = 90th percentile and noise floor = 10th percentile of the RMS of every 100 ms block, in dBFS.
set -euo pipefail
f="${1:-}"
[ -n "$f" ] || { echo "usage: bash check-level.sh <file>" >&2; exit 2; }
[ -s "$f" ] || { echo "input missing or empty: $f" >&2; exit 2; }
ffprobe -v error -select_streams a:0 -show_entries stream=codec_type -of csv=p=0 "$f" 2>/dev/null | grep -q audio || { echo "no audio stream in $f" >&2; exit 3; }
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 readings are not reliable" >&2
ebu=$(ffmpeg -hide_banner -nostats -i "$f" -vn -af ebur128=peak=true -f null - 2>&1) || { echo "ffmpeg could not read $f" >&2; exit 3; }
I=$(echo "$ebu" | awk '/I:/ && /LUFS/ {v=$2} END{print v}')
TP=$(echo "$ebu" | awk '/Peak:/ {v=$2} END{print v}')
blocks=$(ffmpeg -hide_banner -nostats -i "$f" -vn -af "aformat=channel_layouts=mono,aresample=48000,asetnsamples=n=4800:p=0,astats=metadata=1:reset=1,ametadata=print:key=lavfi.astats.Overall.RMS_level:file=-" -f null - 2>/dev/null | sed -n 's/.*RMS_level=//p' | grep -v -i inf || true)
if [ -z "$blocks" ]; then echo "$(basename "$f")	I=$I LUFS	TP=$TP dBTP	digital silence: nothing to measure" ; exit 0; fi
echo "$blocks" | sort -g | awk -v n="$(basename "$f")" -v I="$I" -v TP="$TP" '{a[NR]=$1} END{lo=a[int((NR-1)*0.10)+1]; hi=a[int((NR-1)*0.90)+1]; printf "%s\tI=%s LUFS\tTP=%s dBTP\tspeech=%.1f dBFS\tfloor=%.1f dBFS\tgap=%.1f dB\tblocks=%d\n", n, I, TP, hi, lo, hi-lo, NR}'
