Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down Expand Up @@ -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).

Expand Down
38 changes: 38 additions & 0 deletions docs/agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.<role>.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
Expand Down
67 changes: 67 additions & 0 deletions examples/06_tuned_bell.py
Original file line number Diff line number Diff line change
@@ -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()
2 changes: 2 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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

Expand Down
10 changes: 7 additions & 3 deletions src/orb/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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
],
Expand All @@ -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))):
Expand All @@ -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", [])
]
Expand Down
59 changes: 58 additions & 1 deletion src/orb/grammar.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions src/orb/model/spec_tokenizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
35 changes: 30 additions & 5 deletions src/orb/render/natural.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
}

Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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]


Expand Down
Loading