Files
tracks/exit-progressive-emulation/master.py
T

128 lines
5.5 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
"""
Techno mastering chain for a stereo mix exported from Bitwig (stdlib + ffmpeg).
low cut 27 Hz -> mono bass below 120 Hz -> tonal EQ -> glue compression
-> soft saturation -> gain to target loudness -> 4x oversampled limiter
Usage: python3 master.py mix.wav [--tone neutral|dark|warm] [--lufs -8] [--ceiling -1.0]
[--ride START:END:DB] [--out mix_master.wav]
Export from Bitwig as 24-bit WAV, without a limiter on the master, peaks below 0 dBFS.
The input file is never modified.
"""
import argparse
import os
import re
import subprocess
import sys
import tempfile
def ffmpeg(*args):
p = subprocess.run(["ffmpeg", "-hide_banner", "-nostdin", "-y", *args], capture_output=True, text=True)
if p.returncode:
sys.exit("ffmpeg failed:\n" + p.stderr[-2000:])
return p.stderr
def measure(path):
"""Integrated loudness, loudness range and true peak (EBU R128)."""
log = ffmpeg("-i", path, "-af", "ebur128=peak=true", "-f", "null", "-")
summary = log[log.rindex("Summary:"):]
def grab(label):
return float(re.search(label + r":\s+(-?[\d.]+|-inf)", summary).group(1))
return {"lufs": grab("I"), "lra": grab("LRA"), "peak": grab("Peak")}
TONES = { # name -> (EQ chain, stereo width above 120 Hz)
"neutral": (",".join([
"equalizer=f=55:t=q:w=1.0:g=1.5", # kick weight
"equalizer=f=280:t=q:w=1.1:g=-2.0", # clear the mud between kick and bass
"equalizer=f=3200:t=q:w=1.4:g=-0.8", # tame harshness before pushing loudness
"highshelf=f=9000:g=1.5", # air on hats and percussion
]), 1.0),
"dark": (",".join([ # for sub-heavy, dull mixes
"equalizer=f=48:t=q:w=0.9:g=-4.0", # rein in the sub
"equalizer=f=160:t=q:w=1.0:g=1.5", # bass body, audible on small speakers
"equalizer=f=900:t=q:w=0.7:g=1.5", # forward mids
"equalizer=f=2800:t=q:w=0.8:g=2.0", # snare and percussion bite
"highshelf=f=6500:g=3.0", # open up the hats
]), 1.2),
"warm": (",".join([ # "dark" plus mid warmth borrowed from a reference record
"equalizer=f=48:t=q:w=0.9:g=-4.0", # rein in the sub
"equalizer=f=160:t=q:w=1.0:g=2.0", # bass body
"equalizer=f=380:t=q:w=0.8:g=3.0", # warmth
"equalizer=f=900:t=q:w=0.7:g=3.0", # forward mids
"equalizer=f=2600:t=q:w=0.8:g=1.5", # gentler bite
"highshelf=f=7000:g=2.0", # softer top than "dark"
]), 1.1),
}
def premaster(src, dst, trim_db, tone, rides=()):
eq, width = TONES[tone]
graph = (
"[0:a]aformat=sample_fmts=fltp:channel_layouts=stereo,aresample=48000,volume=%.2fdB," % trim_db
+ "".join("volume=%.2fdB:enable='between(t,%.3f,%.3f)'," % (db, start, end) for start, end, db in rides)
+ "highpass=f=27:p=2,acrossover=split=120:order=4th[lo][hi];"
+ "[lo]pan=stereo|c0=0.5*c0+0.5*c1|c1=0.5*c0+0.5*c1[mono];"
+ "[hi]extrastereo=m=%.2f:c=false[wide];" % width
+ "[mono][wide]amix=inputs=2:normalize=0," + eq + ","
+ "acompressor=threshold=-16dB:ratio=2:attack=30:release=120:knee=4,"
+ "asoftclip=type=tanh:oversample=4[out]"
)
ffmpeg("-i", src, "-filter_complex", graph, "-map", "[out]", "-c:a", "pcm_f32le", dst)
def limit(src, dst, gain_db, ceiling_db):
# limit 0.3 dB under the ceiling to leave room for inter-sample peaks
lim = 10 ** ((ceiling_db - 0.3) / 20)
chain = ("volume=%.2fdB,aresample=192000,alimiter=limit=%.5f:attack=3:release=60:level=false,"
"aresample=48000" % (gain_db, lim))
ffmpeg("-i", src, "-af", chain, "-c:a", "pcm_s24le", dst)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("mix")
ap.add_argument("--lufs", type=float, default=-8.0, help="target integrated loudness")
ap.add_argument("--ceiling", type=float, default=-1.0, help="true-peak ceiling in dBTP")
ap.add_argument("--tone", choices=sorted(TONES), default="neutral")
ap.add_argument("--ride", action="append", default=[], metavar="START:END:DB",
help="level change for a time span in seconds, before compression (repeatable)")
ap.add_argument("--out")
a = ap.parse_args()
out = a.out or os.path.splitext(a.mix)[0] + "_master.wav"
if os.path.abspath(out) == os.path.abspath(a.mix):
sys.exit("output must differ from input")
before = measure(a.mix)
if before["lufs"] < -60:
sys.exit("input is (nearly) silent")
if before["peak"] >= 0:
print("warning: the mix peaks at %.1f dBTP; if it clipped, re-export with more headroom" % before["peak"])
with tempfile.TemporaryDirectory() as d:
pre = os.path.join(d, "pre.wav")
premaster(a.mix, pre, -18.0 - before["lufs"], a.tone,
[tuple(float(v) for v in r.split(":")) for r in a.ride]) # gain-stage so the compressor behaves consistently
gain = a.lufs - measure(pre)["lufs"]
for _ in range(4): # the limiter eats loudness, so correct the drive a few times
limit(pre, out, gain, a.ceiling)
after = measure(out)
error = a.lufs - after["lufs"]
if abs(error) < 0.3:
break
gain += error
for name, m in (("mix", before), ("master", after)):
print("%-7s %6.1f LUFS LRA %4.1f LU true peak %5.1f dBTP" % (name, m["lufs"], m["lra"], m["peak"]))
if abs(after["lufs"] - a.lufs) >= 0.5:
print("note: target %.1f LUFS not reached" % a.lufs)
print("wrote", out)
if __name__ == "__main__":
main()