#!/usr/bin/env python3 """Mix the film's sound into video/assets/mix.m4a from video/assets/timeline.json. python3 tools/mix.py [music_file] Places every voice line, plays the drum clip's own sound in s18c, and, when a music file is given, loops it on whole bars under the voice. Output is -14 LUFS, true peak -1. """ import json, os, re, subprocess, sys ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") VIDEO = os.path.join(ROOT, "video") VO = os.path.join(ROOT, "assets", "vo", "film") WORK = os.path.join(ROOT, "assets", "mix") DRUM_CLIP = os.path.join(VIDEO, "assets", "clips", "drums.mp4") MUSIC_UNDER_VOICE_DB = -26.5 MUSIC_CLEAR_DB = -9.0 DRUM_CLIP_DB = -5.0 BPM = 104.54 BAR = 4 * 60 / BPM LOOP_START = 48.25 LOOP_PERIOD = 128.51 CROSSFADE_BARS = 4 def run(*args): return subprocess.run(args, check=True, capture_output=True, text=True) def voice_and_drums(timeline): beats = timeline["beats"] drum_start = next(s["start"] for s in timeline["scenes"] if s["id"] == "s18c") args, filters, labels = ["ffmpeg", "-y", "-v", "error"], [], [] for index, (beat, data) in enumerate(beats.items()): args += ["-i", os.path.join(VO, beat + ".mp3")] delay = round(data["start"] * 1000) filters.append(f"[{index}:a]aresample=48000,aformat=channel_layouts=stereo,adelay={delay}|{delay}[v{index}]") labels.append(f"[v{index}]") index = len(beats) args += ["-i", DRUM_CLIP] delay = round(drum_start * 1000) filters.append(f"[{index}:a]aresample=48000,aformat=channel_layouts=stereo,volume={DRUM_CLIP_DB}dB,adelay={delay}|{delay}[d]") labels.append("[d]") filters.append("".join(labels) + f"amix=inputs={len(labels)}:normalize=0:dropout_transition=0,apad,atrim=0:{timeline['total']:.3f}[out]") path = os.path.join(WORK, "voice.wav") run(*args, "-filter_complex", ";".join(filters), "-map", "[out]", "-c:a", "pcm_s24le", path) return path, drum_start def looped_music(music, total): """Repeat one stretch of whole bars, crossfaded, until it covers the film.""" crossfade = CROSSFADE_BARS * BAR start = LOOP_START loop_seconds = LOOP_PERIOD + crossfade count = int((total + crossfade) // LOOP_PERIOD) + 2 args, filters = ["ffmpeg", "-y", "-v", "error"], [] for index in range(count): args += ["-i", music] filters.append(f"[{index}:a]aresample=48000,aformat=channel_layouts=stereo,atrim={start:.4f}:{start + loop_seconds:.4f},asetpts=PTS-STARTPTS[m{index}]") last = "m0" for index in range(1, count): filters.append(f"[{last}][m{index}]acrossfade=d={crossfade:.4f}:c1=qsin:c2=qsin[x{index}]") last = f"x{index}" filters.append(f"[{last}]atrim=0:{total:.3f}[out]") path = os.path.join(WORK, "music.wav") run(*args, "-filter_complex", ";".join(filters), "-map", "[out]", "-c:a", "pcm_s24le", path) return path def music_level(timeline, drum_start): """Music sits under the voice, clears the drum clip and comes up at the ends.""" beats = timeline["beats"] total = timeline["total"] first_voice = beats["b01"]["start"] last_voice = beats["b23"]["start"] + beats["b23"]["length"] drum_end = beats["b19"]["start"] under = 10 ** (MUSIC_UNDER_VOICE_DB / 20) clear = 10 ** (MUSIC_CLEAR_DB / 20) ramp = lambda t, a, b, seconds: f"({a}+({b}-{a})*clip((t-{t})/{seconds},0,1))" gain = f"{ramp(0, 0, clear, 0.8)}" gain = f"if(lt(t,{first_voice - 0.2}),{gain},{ramp(first_voice - 0.2, clear, under, 0.8)})" gain = f"if(lt(t,{drum_start - 0.5}),{gain},if(lt(t,{drum_end - 0.2}),{ramp(drum_start - 0.5, under, 0.03, 0.4)},{ramp(drum_end - 0.2, 0.03, under, 0.5)}))" gain = f"if(lt(t,{last_voice + 0.2}),{gain},if(lt(t,{total - 3}),{ramp(last_voice + 0.2, under, clear, 1.2)},{ramp(total - 3, clear, 0, 2.9)}))" return gain def loudness(path): """Measure for a linear two-pass normalize.""" result = subprocess.run(["ffmpeg", "-hide_banner", "-i", path, "-af", "loudnorm=I=-14:TP=-1.3:LRA=11:print_format=json", "-f", "null", "-"], capture_output=True, text=True) return json.loads(result.stderr[result.stderr.rindex("{") : result.stderr.rindex("}") + 1]) def main(): os.makedirs(WORK, exist_ok=True) timeline = json.load(open(os.path.join(VIDEO, "assets", "timeline.json"))) voice, drum_start = voice_and_drums(timeline) bed = voice if len(sys.argv) > 1: music = looped_music(sys.argv[1], timeline["total"]) bed = os.path.join(WORK, "bed.wav") level = music_level(timeline, drum_start).replace(",", "\\,") run("ffmpeg", "-y", "-v", "error", "-i", voice, "-i", music, "-filter_complex", f"[1:a]volume='{level}':eval=frame[m];[0:a][m]amix=inputs=2:normalize=0:dropout_transition=0[out]", "-map", "[out]", "-c:a", "pcm_s24le", bed) measured = loudness(bed) final = os.path.join(WORK, "mix.wav") run("ffmpeg", "-y", "-v", "error", "-i", bed, "-af", f"loudnorm=I=-14:TP=-1.3:LRA=11:linear=true:measured_I={measured['input_i']}:measured_TP={measured['input_tp']}:measured_LRA={measured['input_lra']}:measured_thresh={measured['input_thresh']}:offset={measured['target_offset']},aresample=48000", "-c:a", "pcm_s24le", final) run("ffmpeg", "-y", "-v", "error", "-i", final, "-c:a", "aac", "-b:a", "256k", os.path.join(VIDEO, "assets", "mix.m4a")) check = loudness(final) print(f"integrated {check['input_i']} LUFS, true peak {check['input_tp']} dBTP, music {'yes' if len(sys.argv) > 1 else 'no'}") main()