diff tools/cut_sounds.py @ 4:2d46729a022e

sound processing and in-game sounds
author ark
date 2026-10-18 20:58 +0200
parents
children 85d23328a215
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/cut_sounds.py	Sun Oct 18 20:58:33 2026 +0200
@@ -0,0 +1,180 @@
+"""
+cut the voice recordings in art/sound_sources/ into game sounds in art/sounds/.
+
+    python3 tools/cut_sounds.py [NAME ...]
+
+without names, every recording is processed. a recording is named after its
+game event (doc/sound.md). one with several variants, listed in VARIANTS, is
+split into that many sounds, written as NAME_1.mp3, NAME_2.mp3 and so on; any
+other recording becomes one sound, NAME.mp3.
+
+each sound is filtered against low rumble, trimmed to the voice with a short
+margin, faded in and out, brought to the same peak level and written as mono
+mp3. a recording is split at its longest pauses: as many as it takes to give
+the listed number of variants. pauses inside one sound are left alone.
+
+requires ffmpeg with libmp3lame, which the build does not need: the build
+reads art/sounds/ only. run this script by hand after a recording changes.
+"""
+
+import math
+import subprocess
+import sys
+from array import array
+from pathlib import Path
+
+ART = Path(__file__).resolve().parent.parent / "art"
+SOURCES = ART / "sound_sources"
+SOUNDS = ART / "sounds"
+
+# number of variants in a recording (doc/art.md)
+VARIANTS = {
+    "t0_attack": 4,
+    "t1_shot": 6,
+    "t2_shot": 4,
+    "t3_shot": 7,
+    "monster_enter": 3,
+    "monster_die": 4,
+}
+
+RATE = 44100
+BITRATE = "64k"
+# remove rumble below this frequency, Hz
+HIGHPASS = 80
+# level analysis in frames of this length, s
+FRAME = 0.01
+# a frame is voice when its level is within this many dB of the loudest frame
+THRESHOLD_DB = 35
+# shorter bits of voice are clicks and dropped, s
+MIN_SOUND = 0.03
+# margin kept before and after the voice, s
+MARGIN_IN = 0.02
+MARGIN_OUT = 0.05
+# fade lengths at the cut ends, s
+FADE_IN = 0.005
+FADE_OUT = 0.03
+# peak level of every sound, dB below full scale
+PEAK_DB = -1.0
+# warn when the shortest split pause is less than this times the longest
+# pause kept inside a sound
+SPLIT_MARGIN = 1.5
+
+
+def decode(path):
+    """decode a recording to mono 16 bit samples at RATE, rumble filtered."""
+    out = subprocess.run(
+        ["ffmpeg", "-v", "error", "-i", str(path), "-af", f"highpass=f={HIGHPASS}",
+         "-ac", "1", "-ar", str(RATE), "-f", "s16le", "-"],
+        check=True, capture_output=True).stdout
+    samples = array("h")
+    samples.frombytes(out)
+    if sys.byteorder == "big":
+        samples.byteswap()
+    return samples
+
+
+def encode(samples, path):
+    data = array("h", samples)
+    if sys.byteorder == "big":
+        data.byteswap()
+    # bitexact keeps the encoder version out of the file, so the output
+    # changes only when the sound does
+    subprocess.run(
+        ["ffmpeg", "-v", "error", "-y", "-f", "s16le", "-ar", str(RATE), "-ac", "1",
+         "-i", "-", "-c:a", "libmp3lame", "-b:a", BITRATE, "-map_metadata", "-1",
+         "-flags", "+bitexact", "-fflags", "+bitexact", str(path)],
+        input=data.tobytes(), check=True)
+
+
+def voice(samples):
+    """
+    return the stretches of voice as (start, end) in samples, in order.
+    clicks shorter than MIN_SOUND are dropped.
+    """
+    n = int(FRAME * RATE)
+    levels = []
+    for i in range(0, len(samples) - n + 1, n):
+        frame = samples[i:i + n]
+        rms = math.sqrt(sum(v * v for v in frame) / n)
+        levels.append(20 * math.log10(rms) if rms > 0 else -200.0)
+    limit = max(levels) - THRESHOLD_DB
+    runs, start = [], None
+    for i, lv in enumerate(levels + [-200.0]):
+        if lv >= limit and start is None:
+            start = i
+        elif lv < limit and start is not None:
+            runs.append((start * n, i * n))
+            start = None
+    return [r for r in runs if r[1] - r[0] >= MIN_SOUND * RATE]
+
+
+def split(runs, count, name):
+    """group the voice stretches into count sounds at the longest pauses."""
+    gaps = sorted(range(len(runs) - 1), key=lambda i: runs[i + 1][0] - runs[i][1], reverse=True)
+    if len(gaps) < count - 1:
+        sys.exit(f"{name}: found {len(runs)} stretch(es) of voice, need {count} variants")
+    cuts = sorted(gaps[:count - 1])
+    length = [(runs[i + 1][0] - runs[i][1]) / RATE for i in gaps]
+    if count > 1 and len(length) >= count and length[count - 2] < SPLIT_MARGIN * length[count - 1]:
+        print(f"  warning: {name}: split pause {length[count - 2]:.2f} s is close to"
+              f" a pause kept inside a sound, {length[count - 1]:.2f} s")
+    out, first = [], 0
+    for c in cuts + [len(runs) - 1]:
+        out.append((runs[first][0], runs[c][1]))
+        first = c + 1
+    return out
+
+
+def shape(samples, start, end):
+    """cut one sound with margins, fade its ends and set its peak level."""
+    a = max(0, start - int(MARGIN_IN * RATE))
+    b = min(len(samples), end + int(MARGIN_OUT * RATE))
+    part = samples[a:b]
+    peak = max(abs(v) for v in part)
+    gain = 32767 * 10 ** (PEAK_DB / 20) / peak
+    fin, fout = int(FADE_IN * RATE), int(FADE_OUT * RATE)
+    n = len(part)
+    out = array("h", bytes(2 * n))
+    for i, v in enumerate(part):
+        g = gain
+        if i < fin:
+            g *= i / fin
+        if n - i <= fout:
+            g *= (n - 1 - i) / fout
+        out[i] = max(-32768, min(32767, round(v * g)))
+    return out
+
+
+def process(path):
+    name = path.stem
+    count = VARIANTS.get(name, 1)
+    samples = decode(path)
+    runs = voice(samples)
+    if not runs:
+        sys.exit(f"{name}: no voice found")
+    sounds = split(runs, count, name) if count > 1 else [(runs[0][0], runs[-1][1])]
+    for old in list(SOUNDS.glob(f"{name}.mp3")) + list(SOUNDS.glob(f"{name}_[0-9]*.mp3")):
+        old.unlink()
+    for i, (start, end) in enumerate(sounds, start=1):
+        dst = SOUNDS / (f"{name}_{i}.mp3" if count > 1 else f"{name}.mp3")
+        encode(shape(samples, start, end), dst)
+        print(f"  {dst.name}: {start / RATE:.2f}-{end / RATE:.2f} s of the recording,"
+              f" {(end - start) / RATE:.2f} s")
+
+
+def main(names):
+    # any format ffmpeg reads
+    paths = sorted(p for p in SOURCES.iterdir() if p.is_file() and not p.name.startswith("."))
+    if names:
+        paths = [p for p in paths if p.stem in names]
+        missing = set(names) - {p.stem for p in paths}
+        if missing:
+            sys.exit("no recording for: " + ", ".join(sorted(missing)))
+    SOUNDS.mkdir(exist_ok=True)
+    for p in paths:
+        print(p.name)
+        process(p)
+
+
+if __name__ == "__main__":
+    main(sys.argv[1:])