From 48b7fc4fe5f9871c738aff72a6a2a4275bf53a01 Mon Sep 17 00:00:00 2001 From: Parker Brown Date: Thu, 19 Nov 2026 10:14:58 -0700 Subject: [PATCH] Spec: per-event params, so a bell can sit on a note - A Spec event may carry `params`, renderer parameters for that one event: {"role": "church_bell", "t": 1.0, "dur": 6.0, "params": {"f0": 293.66}} puts the strike note on D4 - `orb.grammar.EVENT_PARAMS` is the registry (role -> name -> range and meaning): `f0` and `t60` for bell, ui_pop, click and impact; `f0` and `f_end` for sub_drop; `f0`, `ring`, `hardness`, `tierce` and `beat` for church_bell - The synth roles already read these from `ROLE_PARAMS` and `Event.params`; this opens that path at the Spec layer. The church bell gains the five dials, with every random draw made either way, so a param changes only what it names - Render-only, like `bed_db`: the caption and the planner cannot express params, the tokenizer refuses them, validation warns, and a planner Spec serialises exactly as before - No existing sound moves: all 47 roles x 4 seeds hash the same before and after, and a param at its default is the same audio as leaving it out - orb_validate_spec rejects unknown or out-of-range params by path; orb_describe_grammar lists each role's params with ranges and defaults (null where the seed picks the value) - examples/06_tuned_bell.py, tests/test_params.py, README, docs/agents.md, CHANGELOG --- CHANGELOG.md | 4 + README.md | 8 + docs/agents.md | 38 +++++ examples/06_tuned_bell.py | 67 +++++++++ examples/README.md | 2 + src/orb/api.py | 10 +- src/orb/grammar.py | 59 +++++++- src/orb/model/spec_tokenizer.py | 2 + src/orb/render/natural.py | 35 ++++- src/orb/tools.py | 50 ++++++- tests/test_params.py | 254 ++++++++++++++++++++++++++++++++ 11 files changed, 516 insertions(+), 13 deletions(-) create mode 100644 examples/06_tuned_bell.py create mode 100644 tests/test_params.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f8af54e..9386301 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Added + +- Per-event `params` in a hand-written Spec, so a pitched sound can follow the key of the music it sits over: `{"role": "church_bell", "t": 1.0, "dur": 6.0, "params": {"f0": 293.66}}` puts the bell's strike note on D4. `bell`, `ui_pop`, `click`, `impact` and `sub_drop` take `f0` (and `t60` or `f_end`); `church_bell` takes `f0`, `ring`, `hardness`, `tierce` and `beat`. `orb.grammar.EVENT_PARAMS` is the registry, `orb_describe_grammar` lists each role's params with ranges and defaults, and `orb_validate_spec` rejects unknown or out-of-range ones by path. Like `bed_db`, params are render-only: the caption grammar and the planner do not express them, and the tokenizer refuses a Spec that carries any. A Spec without params renders bit-identically to before, and a param at its default is the same audio as leaving it out. `examples/06_tuned_bell.py`, `tests/test_params.py`. + ### Changed - Realism pass on the natural, foley and everyday sounds: 30 roles rebuilt from the physics of the real sound and checked against ESC-50 recordings and two audio judges (RESULTS.md). Thunder is a crack, then rumble arriving from the rest of the bolt and a long low tail, instead of a whoosh. Big gains for church bell, heartbeat, siren, owl, birds, applause, fireworks, gunshot and the desk sounds. Variant contract unchanged, no planner retrain. The site's pre-rendered library is re-rendered with the new sounds. diff --git a/README.md b/README.md index 66fa81d..8f1915a 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,7 @@ Why this matters for agents and motion design: | [`examples/03_variants.py`](examples/03_variants.py) | no | N non-repeating takes from one Spec | | [`examples/04_no_torch.py`](examples/04_no_torch.py) | no | the shippable DSP engine | | [`examples/05_agent_tool.py`](examples/05_agent_tool.py) | no | the agent tool layer, called directly | +| [`examples/06_tuned_bell.py`](examples/06_tuned_bell.py) | no | per-event `params`: church bells on a D minor triad | A 12-second trailer cue: @@ -210,6 +211,13 @@ The planner emits a small typed object, and the renderer is a pure function of i `"bed_db"` to move it, or `"texture": "none"` for no bed at all (clean UI sounds). In a caption, write `no bed` in place of the bed clause; such a caption is rendered exactly, without the planner. +- a few roles take per-event **`params`** in a Spec dict, so a sound can sit on a note: + `{"role": "church_bell", "t": 1.0, "dur": 6.0, "params": {"f0": 293.66}}` puts the bell's + strike note on D4. `bell`, `ui_pop`, `click`, `impact` and `sub_drop` take `f0` as well; + the church bell also takes `ring` (how long it rings), `hardness` (the clapper), `tierce` + (its minor or major third) and `beat`. Left out, every sound is exactly what it was. Like + `bed_db`, params are Spec-only: a caption cannot express them. `orb_describe_grammar` + lists each role's params with their ranges and defaults. The caption grammar is documented in [`examples/README.md`](examples/README.md). diff --git a/docs/agents.md b/docs/agents.md index 0fb0f92..da43c33 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -289,6 +289,44 @@ events = [{"role": ROLE_FOR[k["kind"]], "t": k["t"], "dur": k["dur"], "pan": k[" If you move a keyframe and re-run, the sound moves with it. +### A bell in the key of the music + +A cue that sits over music has to follow its key, and a role's pitch is otherwise fixed +(the synth `bell` rings at 880 Hz) or left to the seed (each `church_bell` is cast +somewhere between C4 and B4). An event's `params` puts it on a note: + +```python +D4, F4, A4 = 293.66, 349.23, 440.00 +spec = {"duration": 10.0, "texture": "none", "mood": "calm", "events": [ + {"role": "church_bell", "t": 0.5, "dur": 9.0, "seed": 0, "params": {"f0": D4}}, + {"role": "church_bell", "t": 2.5, "dur": 7.0, "seed": 2, "params": {"f0": F4}}, + {"role": "church_bell", "t": 4.5, "dur": 5.0, "seed": 4, + "params": {"f0": A4, "hardness": 0.9, "ring": 1.5}}, +]} +run_tool("orb_render_spec", {"spec": spec, "name": "d_minor_bells"}) +``` + +| Role | Params | +|---|---| +| `bell`, `ui_pop`, `click`, `impact` | `f0` (Hz), `t60` (ring time, s) | +| `sub_drop` | `f0`, `f_end` (Hz: where the drop starts and lands) | +| `church_bell` | `f0` (strike note, Hz), `ring` (x decay), `hardness` (0 felt .. 1 hard), `tierce` (0.6 minor, 0.63 major), `beat` (doublet width) | + +`orb_describe_grammar` returns the same table under `roles..params`, with each +param's range and default. A default of `null` means there is none: unset, the seed picks +the value (a church bell's note). `orb_validate_spec` rejects a param the role does not +take, or one outside its range, with the event's path. + +- **`f0` on a church bell is its strike note**, the pitch a listener hears: half the bell's + nominal. The seed still casts the bell (how far its hum and prime are from true, the + weight of each partial), so two seeds on one note are two different bells on that note. +- **A param left out changes nothing.** A Spec without params renders what it always + rendered, and a param set to its default is the same audio as leaving it out. +- **Spec only.** Like `bed_db`, params have no place in the caption grammar, so the planner + never emits them and a caption will not carry them. Validation says so in a warning. + +[`examples/06_tuned_bell.py`](../examples/06_tuned_bell.py) tolls a D minor triad this way. + ## Limits - Up to 8 events per Spec, 47 roles and 13 textures (`orb_describe_grammar` lists them, with each role's variants). A cue lasts 0.1–60 s when rendered diff --git a/examples/06_tuned_bell.py b/examples/06_tuned_bell.py new file mode 100644 index 0000000..122824b --- /dev/null +++ b/examples/06_tuned_bell.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""Put a sound on a note. + +A role's pitch is normally fixed (the synth `bell` rings at 880 Hz) or left to +the seed (each `church_bell` is cast somewhere between C4 and B4). A cue that +sits over music has to follow its key, so a Spec event can carry `params`: +`f0` is the note, and the church bell also takes `ring` (how long it rings), +`hardness` (the clapper), `tierce` (its minor or major third) and `beat`. + +Three bells toll a D minor triad one at a time, then together, harder and +longer. No model and no torch: params are Spec-only, like `bed_db`. + + python examples/06_tuned_bell.py +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "src")) + +from orb.api import render_spec, save_wav # noqa: E402 +from orb.tools import validate_spec # noqa: E402 + +NOTES = {"D4": 293.66, "F4": 349.23, "A4": 440.00} + + +def bell(t: float, note: str, seed: int, **params: float) -> dict: + # An even seed is a single strike; the seed also casts the bell (its + # detuned hum and prime, the weight of each partial). + return {"role": "church_bell", "t": t, "dur": 12.0 - t, "gain_db": -6.0, "pan": 0.0, "seed": seed, + "params": {"f0": NOTES[note], **params}} + + +SPEC = { + "duration": 12.0, + "texture": "none", + "mood": "calm", + "events": [ + bell(0.5, "D4", 0), + bell(2.5, "F4", 2), + bell(4.5, "A4", 4), + bell(7.0, "D4", 0, hardness=0.9, ring=1.5), + bell(7.0, "F4", 2, hardness=0.9, ring=1.5), + bell(7.0, "A4", 4, hardness=0.9, ring=1.5), + ], +} + + +def main() -> None: + report = validate_spec(SPEC) + assert report["valid"], report["errors"] + audio = render_spec(report["spec"]) + save_wav(audio, ROOT / "out/example_06_tuned_bells.wav") + + for ev in report["spec"]["events"][:3]: + print(f"church_bell @ {ev['t']:.1f} s strike note {ev['params']['f0']:.2f} Hz") + print(f"then all three at 7.0 s, hardness 0.9, ring x1.5 {audio.shape} {audio.dtype}") + for w in report["warnings"]: + print(f"note {w}") + print("wrote out/example_06_tuned_bells.wav") + + +if __name__ == "__main__": + main() diff --git a/examples/README.md b/examples/README.md index 0a62745..5a2f0ed 100644 --- a/examples/README.md +++ b/examples/README.md @@ -8,6 +8,7 @@ python examples/02_edit_spec.py # change one number, re-render python examples/03_variants.py # N non-repeating takes from one Spec python examples/04_no_torch.py # pure DSP, numpy only, no weights python examples/05_agent_tool.py # an agent scores a UI animation via orb.tools +python examples/06_tuned_bell.py # three church bells on a D minor triad (event params) ``` | Example | Needs torch? | Needs weights? | Shows | @@ -17,6 +18,7 @@ python examples/05_agent_tool.py # an agent scores a UI animation via orb.too | `03_variants.py` | no | no | infinite non-repeating takes | | `04_no_torch.py` | no | no | the shippable DSP engine | | `05_agent_tool.py` | no | no | the agent tool layer (`orb.tools`, as used by `orb-mcp`) | +| `06_tuned_bell.py` | no | no | per-event `params`: a sound on a note | ## The caption grammar diff --git a/src/orb/api.py b/src/orb/api.py index fa8fdbc..0d00861 100644 --- a/src/orb/api.py +++ b/src/orb/api.py @@ -46,8 +46,8 @@ def spec_to_dict(spec: Spec) -> dict[str, Any]: """A JSON-serialisable view of a Spec. - ``bed_db`` is included only when it is set, so a planner Spec (which never - sets it) serialises exactly as before. + ``bed_db`` and an event's ``params`` are included only when they are set, + so a planner Spec (which never sets either) serialises exactly as before. """ out = { "duration": float(spec.duration), @@ -61,6 +61,7 @@ def spec_to_dict(spec: Spec) -> dict[str, Any]: "gain_db": float(e.gain_db), "pan": float(e.pan), "seed": int(e.seed), + **({"params": dict(e.params)} if e.params else {}), } for e in spec.events ], @@ -75,7 +76,9 @@ def dict_to_spec(data: dict[str, Any]) -> Spec: Besides the planner's fields, a hand-written Spec may set ``texture`` to ``"none"`` (no bed: digital silence between events) and ``bed_db``, the - bed level relative to the foreground in [-60, -6] dB (default -40). + bed level relative to the foreground in [-60, -6] dB (default -40). An + event may carry ``params``, renderer parameters for that one event (see + ``orb.grammar.EVENT_PARAMS``): ``{"f0": 440.0}`` puts a bell on a note. """ bed_db = data.get("bed_db") if bed_db is not None and (isinstance(bed_db, bool) or not isinstance(bed_db, (int, float))): @@ -88,6 +91,7 @@ def dict_to_spec(data: dict[str, Any]) -> Spec: gain_db=float(e.get("gain_db", -12.0)), pan=float(e.get("pan", 0.0)), seed=int(e.get("seed", 0)), + params=e.get("params"), ) for e in data.get("events", []) ] diff --git a/src/orb/grammar.py b/src/orb/grammar.py index a0ccd5b..6ef13b8 100644 --- a/src/orb/grammar.py +++ b/src/orb/grammar.py @@ -128,6 +128,53 @@ AMBIENCE_BED_DB = -14.0 +# Per-event renderer parameters a hand-written Spec may set in `params`. +# Like `bed_db` they are render-only: the caption grammar and the planner +# cannot express them, so a planner Spec never carries any. role -> name -> +# (min, max, what it does). A role that is not listed takes no params. +_PITCH = "pitch of the fundamental, Hz" +_RING = "ring time (T60) of the fundamental, s" +EVENT_PARAMS: dict[str, dict[str, tuple[float, float, str]]] = { + "bell": {"f0": (110.0, 2400.0, _PITCH), "t60": (0.05, 8.0, _RING)}, + "ui_pop": {"f0": (200.0, 4000.0, _PITCH), "t60": (0.01, 1.0, _RING)}, + "click": {"f0": (500.0, 8000.0, _PITCH), "t60": (0.005, 0.5, _RING)}, + "impact": {"f0": (30.0, 400.0, _PITCH), "t60": (0.05, 3.0, _RING)}, + "sub_drop": { + "f0": (40.0, 400.0, "pitch the drop starts on, Hz"), + "f_end": (20.0, 200.0, "pitch the drop lands on, Hz"), + }, + "church_bell": { + "f0": (100.0, 1000.0, "strike note, Hz: half the bell's nominal. Unset, the seed picks the bell."), + "ring": (0.2, 4.0, "scales every partial's ring time (1 = as cast)"), + "hardness": (0.0, 1.0, "clapper hardness: 0 felt, 0.5 the shipped iron clapper, 1 a hard, bright blow"), + "tierce": (0.55, 0.67, "the third above the prime, as a ratio to the nominal: 0.6 minor (a church bell), 0.63 major"), + "beat": (0.0, 0.01, "how far apart each partial's doublet sits, as a fraction of its frequency (0.0012 as cast)"), + }, +} + + +def event_param_errors(role: str, params: object) -> list[str]: + """Why `params` is not valid for `role`; empty when it is (or is None).""" + if params is None: + return [] + if not isinstance(params, dict): + return ["params: must be an object of name -> number"] + allowed = EVENT_PARAMS.get(role, {}) + errors = [] + for name in sorted(params, key=str): + value = params[name] + if name not in allowed: + takes = f"takes {', '.join(sorted(allowed))}" if allowed else "takes no params" + errors.append(f"params.{name}: unknown for role {role!r} (it {takes})") + continue + lo, hi, _ = allowed[name] + if isinstance(value, bool) or not isinstance(value, (int, float)) or not np.isfinite(value): + errors.append(f"params.{name}: must be a finite number") + elif not lo <= value <= hi: + errors.append(f"params.{name}: {value:g} is outside [{lo:g}, {hi:g}]") + return errors + + def default_bed_db(texture: str) -> float: return AMBIENCE_BED_DB if texture in AMBIENCE_TEXTURES else DEFAULT_BED_DB @@ -172,12 +219,20 @@ class SpecEvent: gain_db: float pan: float seed: int + # Renderer parameters for this one event (see `EVENT_PARAMS`), e.g. + # {"f0": 440.0} to put a bell on a note. None = the role's defaults. + params: dict[str, float] | None = None def __post_init__(self) -> None: if self.role not in EVENT_ROLES: raise ValueError(f"unknown event role {self.role!r}") if self.seed < 0 or self.seed > 255: raise ValueError("event seed must be in [0, 255]") + errors = event_param_errors(self.role, self.params) + if errors: + raise ValueError("; ".join(errors)) + if self.params is not None: + self.params = {str(k): float(v) for k, v in self.params.items()} or None @dataclass @@ -187,7 +242,8 @@ class Spec: `texture` is one of `TEXTURES`, or `"none"` for no bed at all. `bed_db` is the bed level relative to the foreground (None = `DEFAULT_BED_DB`). The planner only ever produces a texture from `TEXTURES` with - `bed_db=None`; the other two options exist for hand-written Specs. + `bed_db=None` and events without `params`; those options exist for + hand-written Specs. """ duration: float @@ -419,6 +475,7 @@ def score_from_spec(spec: Spec, with_music: bool = False) -> Score: dur, character, apex=apex, + params=dict(se.params or {}), gain_db=se.gain_db, pan=se.pan, seed=se.seed, diff --git a/src/orb/model/spec_tokenizer.py b/src/orb/model/spec_tokenizer.py index bc363f1..d191d91 100644 --- a/src/orb/model/spec_tokenizer.py +++ b/src/orb/model/spec_tokenizer.py @@ -134,6 +134,8 @@ def encode_spec(self, spec: Spec, add_special: bool = True) -> list[int]: raise ValueError(f"texture {spec.texture!r} cannot be tokenized") if spec.bed_db is not None: raise ValueError("bed_db cannot be tokenized: the planner always emits the default bed level") + if any(ev.params for ev in spec.events): + raise ValueError("event params cannot be tokenized: the planner always emits the role defaults") out += [SPEC, DUR] + _digits(round(spec.duration * 100), 5) tex = NOBED if spec.texture == NO_BED else tex_token(TEX_TO_ID[spec.texture]) out += [TEX, tex, MOOD, MOODVAL + MOOD_TO_ID[spec.mood], EVENTS] diff --git a/src/orb/render/natural.py b/src/orb/render/natural.py index b539ddc..021eabc 100644 --- a/src/orb/render/natural.py +++ b/src/orb/render/natural.py @@ -121,7 +121,9 @@ "car_horn": dict(width=0.2, reverb=0.18, reverb_decay=0.9), "siren": dict(width=0.3, reverb=0.22, reverb_decay=1.2), "engine": dict(width=0.3, reverb=0.08, reverb_decay=0.6), - "church_bell": dict(width=0.4, reverb=0.4, reverb_decay=2.0), + # ring / hardness / tierce / beat are the bell as cast; a Spec's params may move them + # (`orb.grammar.EVENT_PARAMS`). `f0` has no default: unset, the seed picks the bell. + "church_bell": dict(width=0.4, reverb=0.4, reverb_decay=2.0, ring=1.0, hardness=0.5, tierce=0.6, beat=0.0012), "fireworks": dict(width=0.7, reverb=0.25, reverb_decay=1.6), } @@ -2559,20 +2561,38 @@ def _church_bell(ev, sr, rng, crng, p, seed): 4-5x. The iron clapper's blow excites the upper partials strongly, and they die within a second or two while the hum rings on for tens of seconds. Every partial is a doublet (the bell is not perfectly round), - so they beat slowly, and the two ears hear different mixes of each pair.""" + so they beat slowly, and the two ears hear different mixes of each pair. + + `p` may carry a Spec's params (`orb.grammar.EVENT_PARAMS`): `f0` puts the + strike note on a pitch, `ring` scales the decay, `hardness` is the + clapper, `tierce` the bell's third and `beat` the width of the doublets. + Each one unset leaves the bell exactly as the seed casts it, and every + random draw is made either way, so a param changes only what it names.""" n = _n(ev, sr) dur = n / sr fN = crng.uniform(520, 980) - ratios = np.array((0.25, 0.5, 0.6, 0.75, 1.0, 1.25, 1.335, 1.5, 2.0, 2.5, 2.67, 3.0, 3.36, 4.0, 4.5, 5.0)) + if "f0" in p: + # The strike note is heard an octave under the nominal, where a tuned + # bell's prime sits (the nominal, superquint and octave nominal are + # the 2nd, 3rd and 4th harmonics of it). + fN = 2.0 * float(p["f0"]) + tierce = float(p.get("tierce", 0.6)) + ratios = np.array((0.25, 0.5, tierce, 0.75, 1.0, 1.25, 1.335, 1.5, 2.0, 2.5, 2.67, 3.0, 3.36, 4.0, 4.5, 5.0)) ratios = ratios * crng.uniform(0.993, 1.007, len(ratios)) ratios[0] *= crng.uniform(0.97, 1.03) # old bells: hum and prime are rarely true ratios[1] *= crng.uniform(0.98, 1.02) ratios[4] = 1.0 size = (700.0 / fN) ** 0.8 t60 = np.array((24, 12, 9, 6, 6, 3, 3, 3.5, 2.6, 1.8, 1.6, 1.4, 1.1, 0.9, 0.7, 0.55)) * size + t60 = t60 * float(p.get("ring", 1.0)) g = np.array((0.35, 0.5, 0.75, 0.25, 1.0, 0.2, 0.3, 0.55, 0.5, 0.4, 0.35, 0.3, 0.25, 0.2, 0.12, 0.08)) g = g * crng.uniform(0.75, 1.25, len(g)) - fa, fb, ta, tb = _bells_doublets(fN * ratios, t60, crng, 0.0012) + hard = float(p.get("hardness", 0.5)) + if hard != 0.5: + # A harder clapper is in contact for less time, so more of the blow + # goes into the partials above the nominal; felt leaves them out. + g = g * np.where(ratios > 1.0, (0.15 + 1.7 * hard) ** np.log2(np.maximum(ratios, 1.0)), 1.0) + fa, fb, ta, tb = _bells_doublets(fN * ratios, t60, crng, float(p.get("beat", 0.0012))) # each ear hears its own blend of the two halves of every doublet u_l = crng.uniform(0.25, 0.75, len(g)) u_r = np.clip(u_l + crng.uniform(-0.2, 0.2, len(g)), 0.1, 0.9) @@ -2584,6 +2604,11 @@ def _church_bell(ev, sr, rng, crng, p, seed): m = g[i] * _bells_mode(f, d, sr, k) ir_l[:k] += ul * m ir_r[:k] += ur * m + if hard < 0.5: + # ...and a soft clapper lands slower: up to 12 ms for felt. + k = min(n, max(2, int(0.024 * (0.5 - hard) * sr))) + ir_l[:k] *= np.linspace(0.0, 1.0, k) + ir_r[:k] *= np.linspace(0.0, 1.0, k) strikes = [0.005] if seed % 2 == 0 else list(np.arange(0.005, max(0.01, dur - 0.5), 2.5)) amps = crng.uniform(0.85, 1.0, len(strikes)) # the clapper's clank: iron on bronze, a few ms @@ -2597,7 +2622,7 @@ def _church_bell(ev, sr, rng, crng, p, seed): y = np.zeros(n) for st, a in zip(strikes, amps): _bells_place(y, int(st * sr), ir, a) - out.append((_norm(y) + 0.05 * _norm(clank)) * fo) + out.append((_norm(y) + 0.05 * (2.0 * hard) ** 2 * _norm(clank)) * fo) return out[0], out[1] diff --git a/src/orb/tools.py b/src/orb/tools.py index 6efad03..b3b0770 100644 --- a/src/orb/tools.py +++ b/src/orb/tools.py @@ -42,6 +42,7 @@ BED_CHOICES, BED_DB_RANGE, DEFAULT_BED_DB, + EVENT_PARAMS, EVENT_STYLE, MAX_EVENTS, MOODS, @@ -49,7 +50,9 @@ PAN_LABELS, Spec, SpecEvent, + event_param_errors, ) +from .render.events import ROLE_PARAMS as _ROLE_PARAMS from .render.foley import VARIANTS as _FOLEY_VARIANTS from .render.natural import VARIANTS as _NATURAL_VARIANTS from .score import AMBIENCE_TEXTURES, EVENT_ROLES, TEXTURES @@ -69,7 +72,7 @@ MAX_VARIANTS = 32 _SPEC_KEYS = {"duration", "texture", "mood", "events", "bed_db"} -_EVENT_KEYS = {"role", "t", "dur", "gain_db", "pan", "seed"} +_EVENT_KEYS = {"role", "t", "dur", "gain_db", "pan", "seed", "params"} class OrbToolError(ValueError): @@ -109,6 +112,16 @@ class OrbToolError(ValueError): "footsteps surface and pace, water drop drip or plop, door weight, explosion distance." ), }, + "params": { + "type": "object", + "additionalProperties": {"type": "number"}, + "description": ( + "Renderer parameters for this one event, for the roles that take them (see " + "roles..params in orb_describe_grammar): for example {\"f0\": 440} puts a bell or a " + "church bell on A4, so a cue can follow the key of the music under it. Spec only: a " + "caption cannot express params." + ), + }, }, "required": ["role", "t"], "additionalProperties": False, @@ -349,6 +362,7 @@ def validate_spec(data: Any) -> dict[str, Any]: errors.append(f"events: {len(raw_events)} events, at most {MAX_EVENTS} allowed") events: list[dict[str, Any]] = [] + has_params = False for i, ev in enumerate(raw_events): p = f"events[{i}]" if not isinstance(ev, dict): @@ -397,9 +411,16 @@ def validate_spec(data: Any) -> dict[str, Any]: if not isinstance(seed, int) or isinstance(seed, bool) or not (0 <= seed <= 255): errors.append(f"{p}.seed: must be an integer in [0, 255]") continue - events.append( - {"role": role, "t": float(t), "dur": float(dur), "gain_db": float(gain), "pan": float(pan), "seed": seed} - ) + params = ev.get("params") + param_errors = event_param_errors(role, params) + if param_errors: + errors.extend(f"{p}.{e}" for e in param_errors) + continue + event = {"role": role, "t": float(t), "dur": float(dur), "gain_db": float(gain), "pan": float(pan), "seed": seed} + if params: + event["params"] = {k: float(v) for k, v in params.items()} + has_params = True + events.append(event) if texture == NO_BED and not raw_events: errors.append('texture: "none" needs at least one event (the cue would be silent)') @@ -412,6 +433,11 @@ def validate_spec(data: Any) -> dict[str, Any]: "bed_db is render-only: the caption cannot express it, so it will not round-trip " "through the planner" ) + if has_params: + warnings.append( + "event params are render-only: the caption cannot express them, so they will not " + "round-trip through the planner" + ) events.sort(key=lambda e: e["t"]) spec = {"duration": float(duration), "texture": texture, "mood": mood, "events": events} if bed_db is not None: @@ -667,6 +693,18 @@ def _tool_variants(args: dict[str, Any]) -> dict[str, Any]: } +def _describe_params(role: str) -> dict[str, Any]: + """The params a role takes: range, what each does, and the default. + + A default of None means the role has no single default for it: the seed + picks the value (a church bell's note), which is not the same as zero. + """ + return { + name: {"range": [lo, hi], "default": _ROLE_PARAMS[role].get(name), "description": doc} + for name, (lo, hi, doc) in EVENT_PARAMS[role].items() + } + + def describe_grammar() -> dict[str, Any]: """Everything an agent needs to author a Spec without the planner.""" return { @@ -679,6 +717,7 @@ def describe_grammar() -> dict[str, Any]: "default_gain_db": EVENT_STYLE[role][2], "default_dur": EVENT_STYLE[role][3], **({"seed_variants": FOLEY_VARIANTS[role]} if role in FOLEY_VARIANTS else {}), + **({"params": _describe_params(role)} if role in EVENT_PARAMS else {}), } for role in EVENT_ROLES }, @@ -708,6 +747,9 @@ def describe_grammar() -> dict[str, Any]: f"The texture bed runs for the whole cue, bed_db (default {DEFAULT_BED_DB:g}) below the events. Set " 'texture to "none" for no bed (silence between events), or lower bed_db for a quieter one.', "Same Spec + same seed = bit-identical audio.", + "A few roles take per-event params (roles..params): set params.f0 to put a bell, church bell, " + "pop, click, impact or sub drop on a pitch, so a cue can follow the key of the music it sits over. " + "Params are Spec-only: a caption cannot express them.", ], "caption_grammar": ( "{duration:.2f}-second {mood} cue, {texture} bed[, with {role} @{t:.2f} {dur:.2f}s " diff --git a/tests/test_params.py b/tests/test_params.py new file mode 100644 index 0000000..7533e85 --- /dev/null +++ b/tests/test_params.py @@ -0,0 +1,254 @@ +"""Per-event params: a hand-written Spec can put a pitched sound on a note. + +The planner and the caption grammar know nothing about params (like `bed_db` +they are render-only), so the default path must not move: a Spec without +params renders exactly what it rendered before, and a param set to its +default is the same audio as leaving it out. +""" + +from __future__ import annotations + +import math + +import numpy as np +import pytest + +from orb.api import dict_to_spec, render_spec, spec_to_dict +from orb.grammar import EVENT_PARAMS, Spec, SpecEvent, event_param_errors, score_from_spec +from orb.render.events import ROLE_PARAMS, render_event +from orb.score import EVENT_ROLES +from orb.tools import describe_grammar, dispatch, validate_spec + +SR = 48000 + + +def _one(role: str, params: dict | None = None, seed: int = 0, dur: float = 3.0) -> np.ndarray: + ev = {"role": role, "t": 0.0, "dur": dur, "gain_db": -6.0, "pan": 0.0, "seed": seed} + if params is not None: + ev["params"] = params + spec = dict_to_spec({"duration": dur, "texture": "none", "mood": "neutral", "events": [ev]}) + (event,) = score_from_spec(spec).events + return render_event(event, SR, seed=0) + + +def _peak_hz(audio: np.ndarray, near: float, span: float = 0.04, start: float = 0.3, length: float = 1.5) -> float: + """The strongest spectral peak within `span` of `near`.""" + x = audio.mean(axis=1)[int(start * SR) : int((start + length) * SR)] + x = x * np.hanning(len(x)) + spec = np.abs(np.fft.rfft(x, 1 << 20)) + freqs = np.fft.rfftfreq(1 << 20, 1.0 / SR) + band = (freqs > near * (1 - span)) & (freqs < near * (1 + span)) + return float(freqs[band][np.argmax(spec[band])]) + + +def _cents(f: float, ref: float) -> float: + return 1200.0 * math.log2(f / ref) + + +def _centroid(audio: np.ndarray, seconds: float) -> float: + x = audio.mean(axis=1)[: int(seconds * SR)] + spec = np.abs(np.fft.rfft(x * np.hanning(len(x)))) + freqs = np.fft.rfftfreq(len(x), 1.0 / SR) + return float((freqs * spec).sum() / spec.sum()) + + +def _seconds_to_fall(audio: np.ndarray, db: float = 40.0) -> float: + env = np.abs(audio).max(axis=1) + hop = SR // 20 + blocks = env[: len(env) // hop * hop].reshape(-1, hop).max(axis=1) + below = np.where(blocks < blocks.max() * 10 ** (-db / 20))[0] + return float(below[0] * hop / SR) if len(below) else float("inf") + + +# -- the registry ------------------------------------------------------------ + + +def test_registry_names_real_roles_and_sane_ranges(): + for role, params in EVENT_PARAMS.items(): + assert role in EVENT_ROLES + for name, (lo, hi, doc) in params.items(): + assert lo < hi and doc + default = ROLE_PARAMS[role].get(name) + # A param either has a default inside its range, or none at all + # (the seed picks it): never a default the validator would reject. + assert default is None or lo <= default <= hi, (role, name, default) + + +def test_describe_grammar_lists_params_with_defaults(): + roles = describe_grammar()["roles"] + assert roles["bell"]["params"]["f0"] == { + "range": [110.0, 2400.0], + "default": 880, + "description": EVENT_PARAMS["bell"]["f0"][2], + } + # The church bell's note has no default: unset, the seed picks the bell. + assert roles["church_bell"]["params"]["f0"]["default"] is None + assert roles["church_bell"]["params"]["ring"]["default"] == 1.0 + assert "params" not in roles["whoosh"] + + +# -- the default path does not move ------------------------------------------ + + +@pytest.mark.parametrize("role", sorted(EVENT_PARAMS)) +def test_empty_params_is_no_params(role): + assert np.array_equal(_one(role), _one(role, {})) + + +@pytest.mark.parametrize("role", sorted(EVENT_PARAMS)) +def test_a_param_at_its_default_is_the_same_audio(role): + defaults = {k: ROLE_PARAMS[role][k] for k in EVENT_PARAMS[role] if k in ROLE_PARAMS[role]} + assert defaults + for seed in (0, 1, 7): + assert np.array_equal(_one(role, seed=seed), _one(role, defaults, seed=seed)), (role, seed) + + +def test_planner_spec_serialises_as_before(): + spec = Spec(4.0, "wind", "bright", [SpecEvent("bell", 1.0, 1.4, -14.0, 0.25, 99)]) + assert "params" not in spec_to_dict(spec)["events"][0] + + +def test_params_roundtrip_through_the_dict(): + data = { + "duration": 4.0, + "texture": "none", + "mood": "calm", + "events": [{"role": "church_bell", "t": 0.0, "dur": 3.0, "gain_db": -6.0, "pan": 0.0, "seed": 4, + "params": {"f0": 440, "ring": 2.0}}], + } + back = spec_to_dict(dict_to_spec(data)) + assert back["events"][0]["params"] == {"f0": 440.0, "ring": 2.0} + assert spec_to_dict(dict_to_spec(back)) == back + + +# -- pitch ------------------------------------------------------------------- + + +@pytest.mark.parametrize("hz", [220.0, 293.66, 440.0, 659.26]) +def test_bell_lands_on_the_asked_pitch(hz): + audio = _one("bell", {"f0": hz, "t60": 3.0}, dur=2.5) + assert abs(_cents(_peak_hz(audio, hz), hz)) < 1.0 + + +@pytest.mark.parametrize("hz", [261.63, 293.66, 369.99, 440.0]) +@pytest.mark.parametrize("seed", [0, 2, 6]) +def test_church_bell_strike_note_is_half_its_nominal(hz, seed): + """`f0` is the strike note; the nominal partial sits an octave up, whatever bell the seed casts.""" + # With the doublets closed the nominal is a single line, exactly on 2 * f0. + pure = _one("church_bell", {"f0": hz, "beat": 0.0}, seed=seed, dur=4.0) + assert abs(_cents(_peak_hz(pure, 2 * hz), 2 * hz)) < 0.5 + # As cast, each partial is a pair straddling its frequency by at most + # 0.06 % (about a cent), and the louder half is the peak a tuner reads. + cast = _one("church_bell", {"f0": hz}, seed=seed, dur=4.0) + assert abs(_cents(_peak_hz(cast, 2 * hz), 2 * hz)) < 2.0 + + +def test_church_bell_f0_changes_the_note_and_nothing_random(): + """Asking for the note the seed would have picked gives the seed's own bell back.""" + # Recover the seed's own nominal from the as-cast render, then ask for it. + as_cast = _one("church_bell", seed=2, dur=4.0) + spec = np.abs(np.fft.rfft(as_cast.mean(axis=1)[int(0.3 * SR) : int(1.8 * SR)] * np.hanning(int(1.5 * SR)), 1 << 20)) + freqs = np.fft.rfftfreq(1 << 20, 1.0 / SR) + band = (freqs > 520) & (freqs < 980) + nominal = float(freqs[band][np.argmax(spec[band])]) + asked = _one("church_bell", {"f0": nominal / 2}, seed=2, dur=4.0) + # Same bell to within the FFT's resolution of the recovered nominal. + assert abs(_cents(_peak_hz(asked, nominal), nominal)) < 1.0 + a, b = as_cast.mean(axis=1), asked.mean(axis=1) + assert np.corrcoef(np.abs(a[:SR]), np.abs(b[:SR]))[0, 1] > 0.9 + + +def test_sub_drop_and_impact_follow_f0(): + low, high = _one("impact", {"f0": 50.0}, dur=1.0), _one("impact", {"f0": 200.0}, dur=1.0) + assert _centroid(low, 0.5) < _centroid(high, 0.5) + drop = _one("sub_drop", {"f0": 220.0, "f_end": 55.0}, dur=1.5) + assert drop.shape == (int(1.5 * SR), 2) and np.isfinite(drop).all() + + +# -- the church bell's other dials ------------------------------------------ + + +def test_ring_scales_the_decay(): + short, cast, long = (_seconds_to_fall(_one("church_bell", {"f0": 440.0, "ring": r}, dur=20.0)) for r in (0.35, 1.0, 2.5)) + assert short < cast < long + assert long > 2 * short + + +def test_hardness_brightens_the_blow_and_felt_lands_slower(): + felt, cast, hard = (_one("church_bell", {"f0": 440.0, "hardness": h}, dur=4.0) for h in (0.05, 0.5, 1.0)) + assert _centroid(felt, 0.15) < _centroid(cast, 0.15) < _centroid(hard, 0.15) + rise = lambda a: int(np.argmax(np.abs(a).max(axis=1) >= 0.9 * np.abs(a).max())) # noqa: E731 + assert rise(felt) > rise(hard) + + +def test_tierce_moves_only_the_third(): + minor = _one("church_bell", {"f0": 440.0, "tierce": 0.6, "beat": 0.0}, dur=4.0) + major = _one("church_bell", {"f0": 440.0, "tierce": 0.63, "beat": 0.0}, dur=4.0) + assert not np.array_equal(minor, major) + # the nominal is where it was + assert abs(_cents(_peak_hz(major, 880.0), 880.0)) < 1.0 + + +def test_tuned_render_is_deterministic(): + spec = {"duration": 4.0, "texture": "none", "mood": "calm", + "events": [{"role": "church_bell", "t": 0.2, "dur": 3.5, "seed": 3, "gain_db": -6.0, "pan": 0.0, + "params": {"f0": 293.66, "ring": 1.5, "hardness": 0.8}}]} + assert np.array_equal(render_spec(spec), render_spec(spec)) + + +# -- validation -------------------------------------------------------------- + + +def test_event_param_errors(): + assert event_param_errors("bell", None) == [] + assert event_param_errors("bell", {"f0": 440}) == [] + assert "unknown" in event_param_errors("bell", {"ring": 2.0})[0] + assert "takes no params" in event_param_errors("whoosh", {"f0": 440})[0] + assert "outside" in event_param_errors("bell", {"f0": 20000})[0] + assert "finite" in event_param_errors("bell", {"f0": float("nan")})[0] + assert "finite" in event_param_errors("bell", {"f0": True})[0] + assert "finite" in event_param_errors("bell", {"f0": "440"})[0] + assert "object" in event_param_errors("bell", [440])[0] + + +def test_spec_event_rejects_bad_params(): + with pytest.raises(ValueError, match="unknown for role"): + SpecEvent("whoosh", 0.0, 1.0, -6.0, 0.0, 0, {"f0": 440.0}) + with pytest.raises(ValueError, match="outside"): + dict_to_spec({"duration": 2.0, "texture": "none", "mood": "calm", + "events": [{"role": "church_bell", "t": 0.0, "dur": 1.0, "params": {"tierce": 0.9}}]}) + assert SpecEvent("bell", 0.0, 1.0, -6.0, 0.0, 0, {}).params is None + + +def test_validate_spec_reports_params_by_path_and_warns(): + base = {"duration": 3.0, "texture": "none", "mood": "calm"} + bad = validate_spec({**base, "events": [{"role": "bell", "t": 0.0, "dur": 1.0, "params": {"f0": 5, "nope": 1}}]}) + assert not bad["valid"] + assert any(e.startswith("events[0].params.f0:") for e in bad["errors"]) + assert any(e.startswith("events[0].params.nope:") for e in bad["errors"]) + + good = validate_spec({**base, "events": [{"role": "bell", "t": 0.0, "dur": 1.0, "params": {"f0": 440}}]}) + assert good["valid"] and good["spec"]["events"][0]["params"] == {"f0": 440.0} + assert any("render-only" in w and "params" in w for w in good["warnings"]) + + plain = validate_spec({**base, "events": [{"role": "bell", "t": 0.0, "dur": 1.0}]}) + assert "params" not in plain["spec"]["events"][0] + assert not any("params" in w for w in plain["warnings"]) + + +def test_tokenizer_refuses_params(): + pytest.importorskip("torch") # orb.model imports torch; everything above runs on numpy alone + from orb.model.spec_tokenizer import SpecTokenizer + + spec = Spec(4.0, "wind", "calm", [SpecEvent("bell", 1.0, 1.4, -14.0, 0.0, 9, {"f0": 440.0})]) + with pytest.raises(ValueError, match="params cannot be tokenized"): + SpecTokenizer().encode_spec(spec) + + +def test_render_tool_takes_params_and_names_differ(tmp_path, monkeypatch): + monkeypatch.setenv("ORB_OUTPUT_DIR", str(tmp_path)) + base = {"duration": 3.0, "texture": "none", "mood": "calm"} + a = dispatch("orb_render_spec", {"spec": {**base, "events": [{"role": "church_bell", "t": 0.0, "dur": 2.5, "seed": 0, "params": {"f0": 293.66}}]}}) + b = dispatch("orb_render_spec", {"spec": {**base, "events": [{"role": "church_bell", "t": 0.0, "dur": 2.5, "seed": 0, "params": {"f0": 440.0}}]}}) + assert a["path"] != b["path"] # the content hash covers params + assert a["spec"]["events"][0]["params"] == {"f0": 293.66}