#!/usr/bin/env python3
"""Music-under-voice test material for add-music-in-capcut. Makes our own synthetic music bed with ffmpeg (chord pad, bass pulse, hi-hat-like noise, 120 bpm),
loudness-matches it and each FLEURS clip to -23 LUFS, then mixes the bed under the clip at 0, -6, -12 and -20 dB relative to the voice.
Usage: mix.py <clips_dir> <out_dir>   (clips_dir has c01.wav..c30.wav, 16 kHz mono)   Needs ffmpeg 6.x. Writes <out_dir>/mix-log.tsv"""
import subprocess, sys, os, re, glob

clips, out = sys.argv[1:3]
os.makedirs(out, exist_ok=True)
GAPS = [0, -6, -12, -20]
TARGET = -23.0


def run(cmd):
    return subprocess.run(cmd, capture_output=True, text=True).stderr


def lufs(path, extra=""):
    e = run(["ffmpeg", "-nostdin", "-hide_banner", "-i", path, "-af", "ebur128=peak=none", "-f", "null", "-"])
    m = re.findall(r"I:\s+(-?[\d.]+) LUFS", e)
    return float(m[-1])


bed = os.path.join(out, "bed.wav")
expr = ("0.30*sin(2*PI*220*t)+0.22*sin(2*PI*277.18*t)+0.22*sin(2*PI*329.63*t)+0.12*sin(2*PI*440*t)"
        "+0.45*sin(2*PI*110*t)*exp(-5*mod(t,0.5))+0.25*(2*random(0)-1)*exp(-30*mod(t+0.25,0.5))")
subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", f"aevalsrc='{expr}':s=16000:d=40", "-ac", "1", bed], check=True)
bed_i = lufs(bed)
log = open(os.path.join(out, "mix-log.tsv"), "w")
log.write("clip\tvoice_lufs_src\tbed_segment_lufs_src\tgap_db\tvoice_stem_lufs\tbed_stem_lufs\tmeasured_gap_db\tmax_volume_db\n")
files = sorted(glob.glob(os.path.join(clips, "c*.wav")))
for n, f in enumerate(files):
    b = os.path.basename(f)[:-4]
    vi = lufs(f)
    gv = TARGET - vi
    off = (n * 1.3) % 25  # a different part of the bed for each clip, the same part in every condition
    dur = float(subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", f], capture_output=True, text=True).stdout)
    seg = os.path.join(out, f"{b}_bed.wav")
    subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-y", "-ss", f"{off}", "-t", f"{dur}", "-i", bed, seg], check=True)
    si = lufs(seg)
    gb = TARGET - si
    ctrl = os.path.join(out, f"{b}_voice.wav")
    subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-y", "-i", f, "-af", f"volume={gv:.3f}dB", ctrl], check=True)
    for g in GAPS:
        stem = os.path.join(out, f"{b}_music{g}_stem.wav")
        subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-y", "-i", seg, "-af", f"volume={gb + g:.3f}dB", stem], check=True)
        mix = os.path.join(out, f"{b}_music{g}.wav")
        subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-y", "-i", ctrl, "-i", stem, "-filter_complex",
                        "[0:a][1:a]amix=inputs=2:duration=first:dropout_transition=0,volume=2", "-ac", "1", "-ar", "16000", mix], check=True)
        vs, bs = lufs(ctrl), lufs(stem)
        mv = re.findall(r"max_volume: (-?[\d.]+) dB", run(["ffmpeg", "-nostdin", "-hide_banner", "-i", mix, "-af", "volumedetect", "-f", "null", "-"]))[0]
        log.write(f"{b}\t{vi:.2f}\t{si:.2f}\t{g}\t{vs:.2f}\t{bs:.2f}\t{vs - bs:.2f}\t{mv}\n")
        log.flush()
        os.remove(stem)
    os.remove(seg)
print("done", len(files), "clips; bed loudness", bed_i)
