RustToDust/tools/audio/curate_haven_audio.py

217 lines
8 KiB
Python

#!/usr/bin/env python3
"""Curate 25 original Haven Kendrick MWO WAVs into mono 44.1 kHz 16-bit PCM WAVs.
Strictly read-only on D:\\Google Drive\\Gamecult\\Aetheria\\Audio\\WIP & Ideas\\Haven\\MWO Soundpack.
Explicitly excludes SW01_*, MW4*, Utilities-*, and desktop.ini.
"""
from __future__ import annotations
import array
import math
import os
import subprocess
import sys
import wave
from dataclasses import dataclass
from pathlib import Path
SOURCE_DIR = Path(r"D:\Google Drive\Gamecult\Aetheria\Audio\WIP & Ideas\Haven\MWO Soundpack")
REPO_ROOT = Path(__file__).resolve().parents[2]
DEST_DIR = REPO_ROOT / "assets" / "audio" / "haven"
TARGET_SAMPLE_RATE = 44100
TARGET_PEAK = 0.89
FORBIDDEN_PREFIXES = ("SW01_", "MW4", "Utilities-")
FORBIDDEN_EXACT = {"desktop.ini"}
@dataclass(frozen=True)
class ClipSpec:
dest_name: str
src_name: str
lead_trim_s: float
max_dur_s: float
fade_out_s: float
auto_trim_lead: bool = True
CLIPS: tuple[ClipSpec, ...] = (
# Machine guns (mg_762)
ClipSpec("mg_shot_01.wav", "ClanMG3_fixed.wav", 0.0, 0.24, 0.035),
ClipSpec("mg_shot_02.wav", "New_MG 2.wav", 0.0, 0.24, 0.035),
ClipSpec("mg_tail.wav", "mgtail.wav", 0.0, 0.66, 0.030),
# Autocannons (autocannon)
ClipSpec("ac_light_01.wav", "AC5.wav", 0.0, 0.85, 0.040),
ClipSpec("ac_light_02.wav", "AC5_2.wav", 0.065, 0.80, 0.040, auto_trim_lead=False),
ClipSpec("ac_med_01.wav", "AC10.wav", 0.0, 0.95, 0.040),
ClipSpec("ac_rotary.wav", "RAC5.wav", 0.0, 1.01, 0.040),
# Flak & heavy recoilless (flak, recoilless)
ClipSpec("flak_blast_01.wav", "ClanLBX7_2019.wav", 0.0, 1.15, 0.045),
ClipSpec("flak_blast_02.wav", "IS_LBX20_2.wav", 0.0, 1.35, 0.045),
ClipSpec("cannon_heavy_01.wav", "BigCannon1.wav", 0.070, 1.80, 0.050, auto_trim_lead=False),
ClipSpec("cannon_heavy_02.wav", "AC20.wav", 0.0, 1.50, 0.050),
# Point defense (pd_flak, aegis_pd)
ClipSpec("pd_bark_01.wav", "AMS3.wav", 0.0, 0.28, 0.030),
ClipSpec("pd_bark_02.wav", "amsTP.wav", 0.0, 0.28, 0.030),
ClipSpec("pd_laser.wav", "laserams.wav", 0.0, 0.32, 0.030),
# Missiles / Rockets (Cut 7)
ClipSpec("rocket_salvo_01.wav", "MRM1.wav", 0.0, 1.20, 0.045),
ClipSpec("rocket_salvo_02.wav", "NEWSRM1.wav", 0.0, 1.35, 0.045),
# Energy / Plasma / Thermal Lance / Gauss (touring_plasma, gilded_lance, Cut 7)
ClipSpec("plasma_ppc_01.wav", "Snub_PPC2.wav", 0.0, 1.25, 0.045),
ClipSpec("plasma_ppc_02.wav", "PPcSWEET.wav", 0.045, 0.78, 0.040, auto_trim_lead=False),
ClipSpec("lance_beam_01.wav", "CPPC_DEC2018_2.wav", 0.0, 1.55, 0.050),
ClipSpec("laser_heavy_01.wav", "CLL3.wav", 0.0, 1.20, 0.045),
ClipSpec("gauss_rail_01.wav", "Gauss Sweet 1.wav", 0.015, 1.15, 0.045, auto_trim_lead=False),
# Mechanical / Bolt-clank / Chassis swap
ClipSpec("mech_reload_bolt.wav", "CannonReload2.wav", 0.0, 1.25, 0.045),
ClipSpec("mech_quick_bolt.wav", "reload.wav", 0.0, 0.94, 0.040),
ClipSpec("mech_eject.wav", "eject.wav", 0.0, 0.74, 0.035),
ClipSpec("mech_turret_servo.wav", "turret9.wav", 0.0, 1.10, 0.040),
)
def validate_source_name(name: str) -> None:
if name in FORBIDDEN_EXACT or any(name.startswith(p) for p in FORBIDDEN_PREFIXES):
raise ValueError(f"Refusing forbidden third-party/system file: {name}")
def decode_mono_f32(src_path: Path) -> list[float]:
cmd = [
"ffmpeg",
"-v",
"error",
"-i",
str(src_path),
"-ac",
"1",
"-ar",
str(TARGET_SAMPLE_RATE),
"-f",
"f32le",
"-",
]
proc = subprocess.run(cmd, capture_output=True, check=False)
if proc.returncode != 0:
err = proc.stderr.decode("utf-8", errors="replace").strip()
raise RuntimeError(f"ffmpeg failed on '{src_path}': {err}")
arr = array.array("f")
arr.frombytes(proc.stdout)
if sys.byteorder != "little":
arr.byteswap()
return list(arr)
def process_clip(spec: ClipSpec, src_path: Path, dst_path: Path) -> tuple[float, float, int]:
samples = decode_mono_f32(src_path)
if not samples:
raise RuntimeError(f"Decoded zero samples from '{src_path}'")
lead_idx = int(round(spec.lead_trim_s * TARGET_SAMPLE_RATE))
if lead_idx > 0 and lead_idx < len(samples):
samples = samples[lead_idx:]
if spec.auto_trim_lead:
# Trim only genuinely silent leading padding (>10 ms below -54 dBFS)
silence_thresh = 0.002
first_active = 0
for idx, s in enumerate(samples):
if abs(s) >= silence_thresh:
first_active = idx
break
if first_active > int(0.010 * TARGET_SAMPLE_RATE):
samples = samples[first_active:]
max_samples = int(round(spec.max_dur_s * TARGET_SAMPLE_RATE))
if len(samples) > max_samples:
samples = samples[:max_samples]
# Trim trailing near-silence beyond 15ms if tail is quieter than -60 dBFS, keeping at least 150ms
min_keep = min(len(samples), int(0.15 * TARGET_SAMPLE_RATE))
last_active = len(samples) - 1
while last_active > min_keep and abs(samples[last_active]) < 0.001:
last_active -= 1
samples = samples[: min(len(samples), last_active + int(0.015 * TARGET_SAMPLE_RATE))]
n = len(samples)
if n < 256:
raise RuntimeError(f"Clip '{spec.dest_name}' became too short ({n} samples)")
# Short 4ms fade-in only if attack begins non-zero, avoiding click
fade_in = min(n // 8, int(0.004 * TARGET_SAMPLE_RATE))
if fade_in > 0 and abs(samples[0]) > 0.005:
for i in range(fade_in):
gain = 0.5 * (1.0 - math.cos(math.pi * (i + 0.5) / fade_in))
samples[i] *= gain
# Smooth cosine fade-out on tail
fade_out = min(n // 2, int(round(spec.fade_out_s * TARGET_SAMPLE_RATE)))
if fade_out > 0:
start = n - fade_out
for i in range(fade_out):
gain = 0.5 * (1.0 + math.cos(math.pi * (i + 1) / fade_out))
samples[start + i] *= gain
peak = max(abs(x) for x in samples)
if peak < 1e-4:
raise RuntimeError(f"Clip '{spec.dest_name}' is silent (peak={peak})")
scale = TARGET_PEAK / peak
pcm = array.array("h")
final_peak = 0.0
for s in samples:
v = max(-1.0, min(1.0, s * scale))
final_peak = max(final_peak, abs(v))
pcm.append(int(round(v * 32767.0)))
if sys.byteorder != "little":
pcm.byteswap()
with wave.open(str(dst_path), "wb") as wf:
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(TARGET_SAMPLE_RATE)
wf.writeframes(pcm.tobytes())
size_bytes = dst_path.stat().st_size
dur_s = n / TARGET_SAMPLE_RATE
return dur_s, final_peak, size_bytes
def main() -> int:
if len(CLIPS) != 25:
raise AssertionError(f"Expected exactly 25 clips, got {len(CLIPS)}")
if not SOURCE_DIR.is_dir():
raise FileNotFoundError(f"Source directory not found: {SOURCE_DIR}")
DEST_DIR.mkdir(parents=True, exist_ok=True)
expected_names = {c.dest_name for c in CLIPS}
for existing in DEST_DIR.glob("*"):
if existing.is_file() and existing.name not in expected_names:
existing.unlink()
total_bytes = 0
for spec in CLIPS:
validate_source_name(spec.src_name)
src_path = SOURCE_DIR / spec.src_name
if not src_path.is_file():
raise FileNotFoundError(f"Missing Haven source WAV: {src_path}")
dst_path = DEST_DIR / spec.dest_name
dur_s, peak, size_bytes = process_clip(spec, src_path, dst_path)
total_bytes += size_bytes
print(f" {spec.dest_name:<22} <- {spec.src_name:<22} {dur_s:5.2f}s peak={peak:.3f} {size_bytes/1024:6.1f} KiB")
produced = sorted(p.name for p in DEST_DIR.glob("*.wav"))
if len(produced) != 25:
raise RuntimeError(f"Expected 25 WAVs in {DEST_DIR}, found {len(produced)}")
total_mib = total_bytes / (1024.0 * 1024.0)
print(f"Curated {len(produced)} WAVs into {DEST_DIR} (total {total_mib:.2f} MiB)")
if total_mib >= 4.0:
raise RuntimeError(f"Total audio size {total_mib:.2f} MiB exceeds 4.0 MiB budget")
return 0
if __name__ == "__main__":
raise SystemExit(main())