"""The recording's own sounds, cut out and sorted, for a build to play. uv run python -m scripts.sounds BUILD BUILD holds ``recording.mp4`` and ``input.jsonl`` (and ``controller.json`` when the camera is known). Writes ``BUILD/sounds/NAME.wav`` and ``BUILD/sounds.json``: every sudden sound the judge will look for (the same onsets as bench_builder.audio_track), cut from where it rises out of the steady sound to where it has sunk back, sorted into kinds by spectrum and length, with one clean take of each kind, the moments it was heard, where the camera stood, and what it goes with: a key it follows, or keys it repeats under while one is held. What goes with nothing is something in the world (a pickup, a door); the moments and places are there for a builder to find out what. The steady sound between them is ``bed.wav``. A sound under a louder one is not found. """ from __future__ import annotations import json import subprocess import sys import wave from pathlib import Path import numpy as np from bench_builder import audio_track RATE, FRAME = 48000, 240 # 5 ms frames for the fine loudness curve def cut(samples, start, end): """The samples from start to end (seconds) as 16-bit PCM bytes with 5 ms fades.""" clip = samples[int(start * RATE):int(end * RATE)].copy(); ramp = min(FRAME, len(clip) // 2) clip[:ramp] *= np.linspace(0, 1, ramp); clip[len(clip) - ramp:] *= np.linspace(1, 0, ramp) return (np.clip(clip, -1, 1) * 32767).astype("= a) & (hz < b)].sum() for a, b in zip(audio_track.BAND_EDGES_HZ, audio_track.BAND_EDGES_HZ[1:])]) return 10 * np.log10(np.maximum(bands / max(bands.sum(), 1e-20), 1e-6)) def main(argv: list[str] | None = None) -> int: build = Path((argv or sys.argv[1:])[0]); video = build / "recording.mp4" if not audio_track.has_audio(video): print("the recording has no sound"); return 0 samples = np.frombuffer(subprocess.run(["ffmpeg", "-loglevel", "error", "-i", str(video), "-vn", "-ac", "1", "-ar", str(RATE), "-f", "f32le", "-"], capture_output=True, check=True).stdout, np.float32).astype(np.float64) seconds = len(samples) / RATE level = 10 * np.log10(np.maximum((samples[:len(samples) // FRAME * FRAME].reshape(-1, FRAME) ** 2).mean(1), 1e-9)) steady = float(np.median(level)); quiet = level < steady + 3 takes = [] for moment in audio_track.onsets(audio_track.measure_audio(video)["rows"]): # known to a tenth of a second a, b = max(0, int((moment - 0.1) * RATE / FRAME)), min(len(level), int((moment + 0.2) * RATE / FRAME)) if b <= a: continue peak = a + int(np.argmax(level[a:b])); start = peak while start > 0 and peak - start < 60 and not quiet[start - 1]: start -= 1 end = peak while end < len(level) - 1 and end - peak < 400 and not quiet[end:end + 10].all(): # sunk back for 50 ms, or 2 s end += 1 if takes and start * FRAME / RATE < takes[-1]["end"]: # still inside the one before if start * FRAME / RATE - takes[-1]["start"] < 0.05: continue takes[-1]["end"] = start * FRAME / RATE takes.append({"start": start * FRAME / RATE, "end": (end + 1) * FRAME / RATE, "peak": float(level[peak])}) takes = [t for t in takes if t["end"] - t["start"] >= 0.02] kinds = [] for take in takes: # the same kind: its first 80 ms within 6 dB band for band, a third to three times as long take["seconds"] = take["end"] - take["start"] # (where a take ends depends on how loud the steady sound is) take["tone"] = tone(samples[int(take["start"] * RATE):int(min(take["end"], take["start"] + 0.08) * RATE)]) home = next((k for k in kinds if np.abs(k[0]["tone"] - take["tone"]).mean() < 6 and 1 / 3 < take["seconds"] / k[0]["seconds"] < 3), None) home.append(take) if home else kinds.append([take]) events = sorted((json.loads(line) for line in (build / "input.jsonl").read_text().splitlines() if line.strip()), key=lambda e: e["time_ns"]) pressed, held, down = {}, {}, {} for e in events: code, t = e.get("code"), e["time_ns"] / 1e9 if e["event"] == "key_press" and code not in down: down[code] = t; pressed.setdefault(code, []).append(t) elif e["event"] == "key_release" and code in down: held.setdefault(code, []).append((down.pop(code), t)) for code, t in down.items(): held.setdefault(code, []).append((t, seconds)) where, moving = None, list(held) if (build / "controller.json").is_file(): from scripts import probe c, rows = probe.poses(build, seconds); where = lambda t: [round(v, 2) for v in probe.at(rows, t)[1:4]] moving = [code for part, code in c.get("keys", {}).items() if part in ("forward", "back", "left", "right") and code in held] folder = build / "sounds"; folder.mkdir(exist_ok=True) for old in folder.glob("*.wav"): old.unlink() listed = [] for n, kind in enumerate(sorted(kinds, key=lambda k: -len(k)), 1): heard = np.array([t["start"] for t in kind]) best = sorted(kind, key=lambda t: t["seconds"])[len(kind) // 2] # a take of the usual length row = {"name": f"sound-{n}", "file": f"sounds/sound-{n}.wav", "seconds": round(best["seconds"], 3), "peak_db": round(max(t["peak"] for t in kind), 1), "heard": [round(float(t), 2) for t in heard]} save(folder / f"sound-{n}.wav", cut(samples, best["start"], best["end"])) if where: row["where"] = [where(float(t)) for t in heard] follows = None for code, times in pressed.items(): # a key it follows: most of the sounds after a press, most presses before one times = np.array(times); after = heard[:, None] - times[None, :]; near = (after > -0.05) & (after < 0.4) of_sounds, of_presses = near.any(1).mean(), near.any(0).mean() if min(of_sounds, of_presses) >= 0.6 and (not follows or of_sounds * of_presses > follows["of_sounds"] * follows["of_presses"]): follows = {"key": code, "delay": round(float(np.median(after[near])), 2), "of_sounds": round(float(of_sounds), 2), "of_presses": round(float(of_presses), 2)} if follows: row["follows"] = follows elif len(kind) >= 4: # or keys it repeats under: nearly all of them while one is held, share = lambda codes: np.mean([any(a <= t <= b + 0.2 for code in codes for a, b in held.get(code, [])) for t in heard]) gaps = np.diff(heard); usual = float(np.median(gaps)) # at a steady beat (the usual gap; a pause is not one) under = max([[code] for code in held] + [moving], key=lambda codes: (round(share(codes), 2), -len(codes))) if share(under) >= 0.8 and np.median(np.abs(gaps - usual)) < 0.25 * usual: row["while"] = {"keys": under, "every": round(usual, 3)} listed.append(row) bed, edges = None, [0.0, *(v for t in takes for v in (t["start"], t["end"])), seconds] a, b = max(zip(edges[::2], edges[1::2]), key=lambda span: span[1] - span[0]) if b - a >= 1.0 and steady > audio_track.SILENCE_DB: b = min(b, a + 6.0); save(folder / "bed.wav", cut(samples, a + 0.05, b - 0.05)) bed = {"file": "sounds/bed.wav", "seconds": round(b - a - 0.1, 2), "level_db": round(steady, 1), "from": round(a, 2)} (build / "sounds.json").write_text(json.dumps({"bed": bed, "sounds": listed}, indent=1) + "\n") print(f"{len(takes)} sudden sounds of {len(listed)} kinds; steady sound at {steady:.0f} dB" + ("" if bed else " (none kept)")) for row in listed: goes = (f"follows {row['follows']['key']} by {row['follows']['delay']} s" if "follows" in row else f"repeats every {row['while']['every']} s while {' or '.join(row['while']['keys'])} is held" if "while" in row else "goes with no key") print(f" {row['name']}: {len(row['heard'])} times, {row['seconds']} s, {goes}; first at {row['heard'][0]} s") return 0 if __name__ == "__main__": sys.exit(main())