#!/usr/bin/env python3
"""Measure several music tracks against one loudness target, or a music bed under a voice.

  python3 levels.py track1.mp3 track2.wav ...      loudness table and spread
  python3 levels.py --list tracks.txt              same, file names one per line
  python3 levels.py --bed voice.mp3 music.mp3 -18  voice vs bed after a gain in dB

Needs ffmpeg (EBU R128 meter, BS.1770). Target -16 LUFS, change with --target -14.
Our tolerance is 1 LU (our choice, not a standard): outside it, run the track through the tool again.
"""
import math, os, re, subprocess, sys

TARGET = -16.0
TOLERANCE = 1.0  # LU, our choice; outside this, run the track through the tool again
SILENT = -70.0  # ebur128 reads -70.0 LUFS for silence and for files shorter than one 400 ms block


def die(msg):
    print(msg, file=sys.stderr)
    sys.exit(1)


def check(path):
    if not os.path.isfile(path) or os.path.getsize(path) == 0:
        die(f"missing or empty file: {path}")


def ebur(inputs, graph, name):
    cmd = ["ffmpeg", "-hide_banner", "-nostats"]
    for p in inputs:
        cmd += ["-i", p]
    cmd += ["-filter_complex", graph, "-f", "null", "-"]
    try:
        r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace")
    except FileNotFoundError:
        die("ffmpeg not found: install ffmpeg and make sure it is on your PATH")
    tail = r.stderr[r.stderr.rfind("Summary:"):] if "Summary:" in r.stderr else ""
    if r.returncode != 0 or not tail:
        die(f"not an audio file or ffmpeg failed: {name}")
    get = lambda k: re.search(rf"{k}:\s+(-?[\d.]+|-inf)", tail)
    vals = {k: get(k) for k in ("I", "LRA", "Peak")}
    if vals["I"] is None:
        die(f"no loudness reading: {name}")
    return {k: (float(v.group(1)) if v else None) for k, v in vals.items()}


def measure(path, graph="[0:a]ebur128=peak=true"):
    check(path)
    m = ebur([path], graph, path)
    if m["I"] <= SILENT:
        die(f"silent or too short to measure (under 0.4 s of sound): {path}")
    return m


def table(paths, target):
    bases = [os.path.basename(p) for p in paths]
    rows = []
    for p, b in zip(paths, bases):
        m = measure(p)
        off = target - m["I"]
        note = "ok" if abs(off) <= TOLERANCE else "more than 1 LU off target"
        rows.append(m["I"])
        label = p if bases.count(b) > 1 else b  # same file name in two folders: show the path as given
        print(f"{label}\tI={m['I']:.1f} LUFS\tTP={m['Peak']:.1f} dBTP\tLRA={m['LRA']:.1f} LU\tto target={off:+.1f} dB\t{note}")
    if len(rows) > 1:
        print(f"spread (loudest - quietest) = {max(rows) - min(rows):.1f} LU over {len(rows)} files")


def bed(voice, music, gain):
    v = measure(voice, "[0:a]ebur128")["I"]
    measure(music, "[0:a]ebur128")  # names the music file if it is the bad one
    both = f"{voice}, {music}"
    # the music is looped and cut to the voice length, then lowered by the gain
    mus = f"[1:a]aloop=loop=-1:size=2e9,volume={gain}dB[m0];[m0][0:a]amix=inputs=2:duration=shortest:weights=1 0:normalize=0"
    b = ebur([voice, music], mus + ",ebur128", both)["I"]
    mix = ebur([voice, music], f"[1:a]aloop=loop=-1:size=2e9,volume={gain}dB[m];[0:a][m]amix=inputs=2:duration=first:normalize=0,ebur128=peak=true", both)
    if b <= SILENT:
        die(f"bed too quiet to measure at {gain:+g} dB: {music}")
    print(f"bed gain {gain:+g} dB\tvoice={v:.1f} LUFS\tbed={b:.1f} LUFS\tvoice minus bed={v - b:.1f} LU\tmix I={mix['I']:.1f} LUFS\tmix TP={mix['Peak']:.1f} dBTP")


def number(text, msg):
    try:
        x = float(text)
    except ValueError:
        die(msg)
    if not math.isfinite(x):
        die(msg)
    return x


def main(argv):
    global TARGET
    if "--target" in argv:
        i = argv.index("--target")
        if i + 1 >= len(argv):
            die("--target needs a number, for example --target -14")
        TARGET = number(argv[i + 1], "--target needs a number, for example --target -14")
        del argv[i:i + 2]
    if not argv:
        die(__doc__.strip())
    if argv[0] == "--bed":
        if len(argv) != 4:
            die("usage: levels.py --bed voice.mp3 music.mp3 -18")
        gain = number(argv[3], f"gain must be a number in dB, got: {argv[3]}")
        return bed(argv[1], argv[2], gain)
    if argv[0] == "--list":
        if len(argv) != 2:
            die("usage: levels.py --list tracks.txt")
        check(argv[1])
        with open(argv[1], encoding="utf-8-sig", errors="replace", newline="") as f:
            names = [ln.strip().strip('"') for ln in f.read().splitlines()]
        base = os.path.dirname(os.path.abspath(argv[1]))
        listfile = argv[1]
        argv = [n if os.path.isabs(n) else os.path.join(base, n) for n in names if n and not n.startswith("#")]
        if not argv:
            die(f"no file names in list: {listfile}")
    table(argv, TARGET)


if __name__ == "__main__":
    main(sys.argv[1:])
