Branchwell

AI Resource Pro / full-access-films · airesourcepro.com / tools / mix.py

1#!/usr/bin/env python3
2"""Mix the film's sound into video/assets/mix.m4a from video/assets/timeline.json.
3
4 python3 tools/mix.py [music_file]
5
6Places every voice line, plays the drum clip's own sound in s18c, and, when a music
7file is given, loops it on whole bars under the voice. Output is -14 LUFS, true peak -1.
8"""
9import json, os, re, subprocess, sys
10
11ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
12VIDEO = os.path.join(ROOT, "video")
13VO = os.path.join(ROOT, "assets", "vo", "film")
14WORK = os.path.join(ROOT, "assets", "mix")
15DRUM_CLIP = os.path.join(VIDEO, "assets", "clips", "drums.mp4")
16MUSIC_UNDER_VOICE_DB = -26.5
17MUSIC_CLEAR_DB = -9.0
18DRUM_CLIP_DB = -5.0
19BPM = 104.54
20BAR = 4 * 60 / BPM
21LOOP_START = 48.25
22LOOP_PERIOD = 128.51
23CROSSFADE_BARS = 4
24
25
26def run(*args):
27 return subprocess.run(args, check=True, capture_output=True, text=True)
28
29
30def voice_and_drums(timeline):
31 beats = timeline["beats"]
32 drum_start = next(s["start"] for s in timeline["scenes"] if s["id"] == "s18c")
33 args, filters, labels = ["ffmpeg", "-y", "-v", "error"], [], []
34 for index, (beat, data) in enumerate(beats.items()):
35 args += ["-i", os.path.join(VO, beat + ".mp3")]
36 delay = round(data["start"] * 1000)
37 filters.append(f"[{index}:a]aresample=48000,aformat=channel_layouts=stereo,adelay={delay}|{delay}[v{index}]")
38 labels.append(f"[v{index}]")
39 index = len(beats)
40 args += ["-i", DRUM_CLIP]
41 delay = round(drum_start * 1000)
42 filters.append(f"[{index}:a]aresample=48000,aformat=channel_layouts=stereo,volume={DRUM_CLIP_DB}dB,adelay={delay}|{delay}[d]")
43 labels.append("[d]")
44 filters.append("".join(labels) + f"amix=inputs={len(labels)}:normalize=0:dropout_transition=0,apad,atrim=0:{timeline['total']:.3f}[out]")
45 path = os.path.join(WORK, "voice.wav")
46 run(*args, "-filter_complex", ";".join(filters), "-map", "[out]", "-c:a", "pcm_s24le", path)
47 return path, drum_start
48
49
50def looped_music(music, total):
51 """Repeat one stretch of whole bars, crossfaded, until it covers the film."""
52 crossfade = CROSSFADE_BARS * BAR
53 start = LOOP_START
54 loop_seconds = LOOP_PERIOD + crossfade
55 count = int((total + crossfade) // LOOP_PERIOD) + 2
56 args, filters = ["ffmpeg", "-y", "-v", "error"], []
57 for index in range(count):
58 args += ["-i", music]
59 filters.append(f"[{index}:a]aresample=48000,aformat=channel_layouts=stereo,atrim={start:.4f}:{start + loop_seconds:.4f},asetpts=PTS-STARTPTS[m{index}]")
60 last = "m0"
61 for index in range(1, count):
62 filters.append(f"[{last}][m{index}]acrossfade=d={crossfade:.4f}:c1=qsin:c2=qsin[x{index}]")
63 last = f"x{index}"
64 filters.append(f"[{last}]atrim=0:{total:.3f}[out]")
65 path = os.path.join(WORK, "music.wav")
66 run(*args, "-filter_complex", ";".join(filters), "-map", "[out]", "-c:a", "pcm_s24le", path)
67 return path
68
69
70def music_level(timeline, drum_start):
71 """Music sits under the voice, clears the drum clip and comes up at the ends."""
72 beats = timeline["beats"]
73 total = timeline["total"]
74 first_voice = beats["b01"]["start"]
75 last_voice = beats["b23"]["start"] + beats["b23"]["length"]
76 drum_end = beats["b19"]["start"]
77 under = 10 ** (MUSIC_UNDER_VOICE_DB / 20)
78 clear = 10 ** (MUSIC_CLEAR_DB / 20)
79 ramp = lambda t, a, b, seconds: f"({a}+({b}-{a})*clip((t-{t})/{seconds},0,1))"
80 gain = f"{ramp(0, 0, clear, 0.8)}"
81 gain = f"if(lt(t,{first_voice - 0.2}),{gain},{ramp(first_voice - 0.2, clear, under, 0.8)})"
82 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)}))"
83 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)}))"
84 return gain
85
86
87def loudness(path):
88 """Measure for a linear two-pass normalize."""
89 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)
90 return json.loads(result.stderr[result.stderr.rindex("{") : result.stderr.rindex("}") + 1])
91
92
93def main():
94 os.makedirs(WORK, exist_ok=True)
95 timeline = json.load(open(os.path.join(VIDEO, "assets", "timeline.json")))
96 voice, drum_start = voice_and_drums(timeline)
97 bed = voice
98 if len(sys.argv) > 1:
99 music = looped_music(sys.argv[1], timeline["total"])
100 bed = os.path.join(WORK, "bed.wav")
101 level = music_level(timeline, drum_start).replace(",", "\\,")
102 run("ffmpeg", "-y", "-v", "error", "-i", voice, "-i", music, "-filter_complex",
103 f"[1:a]volume='{level}':eval=frame[m];[0:a][m]amix=inputs=2:normalize=0:dropout_transition=0[out]",
104 "-map", "[out]", "-c:a", "pcm_s24le", bed)
105 measured = loudness(bed)
106 final = os.path.join(WORK, "mix.wav")
107 run("ffmpeg", "-y", "-v", "error", "-i", bed, "-af",
108 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",
109 "-c:a", "pcm_s24le", final)
110 run("ffmpeg", "-y", "-v", "error", "-i", final, "-c:a", "aac", "-b:a", "256k", os.path.join(VIDEO, "assets", "mix.m4a"))
111 check = loudness(final)
112 print(f"integrated {check['input_i']} LUFS, true peak {check['input_tp']} dBTP, music {'yes' if len(sys.argv) > 1 else 'no'}")
113
114
115main()