Skip to content

Ears for coding agents: let AI hear, review and make sound. CPU-only, open source.

recipes: the 0.4 sound families and their knobs

Leonxlnxff396323bf28
diff --git a/earshot/forge/knobs.py b/earshot/forge/knobs.py
index facb43a..a4778b8 100644
--- a/earshot/forge/knobs.py
+++ b/earshot/forge/knobs.py
@@ -10,7 +10,8 @@ dur (s, the length of the file):
shape the whoosh family (whoosh_fast, whoosh_big, pro_whoosh_big, swish, swipe): rise, hold and fall scale
together, so the pass keeps its shape; with apex as well, rise comes from apex and hold / fall from the rest
param the recipe's own length key (riser, downlifter, sub drops, shimmer, zip: `length`; glitch and typing runs:
- `dur`; pro_logo_sting: `g_length`; the UI sounds' end gate: `length`; a spectral fit: its `length` knob):
+ `dur`; pro_logo_sting: `g_length`; the UI sounds' end gate: `length`; a spectral or gesture fit: its `length`
+ knob; a sines fit: `stretch`):
scaled, rendered, measured, then corrected along the secant through the renders so far, at most MAX_FIX
times (a key that turns out not to move the length falls back to trim)
trim no length key (impact, toggle, typing_key, logo_sting, pluck: its file always holds 3 s of ring and room,
@@ -39,6 +40,23 @@ pitch ('C5', 'Eb6', 'F#4' or 'Fs4', 440, '440hz'): the note goes into the recipe
partial you hear (click/soft: 2454 Hz, heard 2903 Hz). Their note is the measured partial (meta pitch_hz, measured
when the bank was built; null = no clear partial, so no pitch knob); a target is landed by measurement: the
parameter is scaled by target / heard, rendered, measured and corrected (at most MAX_FIX times), keeping the closest.
+decay / onset / bright / width (earshot 0.4, the tonal knobs; TONAL): aim a tonal or UI sound at a film's measured
+ character through one recipe parameter, landed by measurement with the catalog's own definitions
+ (recipes/_tonal.measure, the ones the films were measured with):
+ decay t20 in ms (the peak to 20 dB down): the ring itself gets shorter (notify / pro_notify: `ring`, which scales
+ every decay constant of the style; a pluck's tau1; a pop's tau ...), never a fade over a long ring (dur
+ does that, and the audit calls such takes truncated)
+ onset attack in ms (the first ms within 20 dB of the peak, to the peak): a felt mallet / a soft rise (notify:
+ `soft`; ui_pop / drip / mallet: `onset`); the films' pops and dings start in 20-60 ms, the bank's in 5
+ bright spectral centroid in Hz (a mallet's hardness, a pop's or a drip's 2nd partial, a shutter's box)
+ width L / R correlation (1 = mono, 0 = decorrelated: the films' bell notes sit at 0.33-0.67, their ticks at 0)
+ The parameter moves along a secant through the renders (log-log for decay / onset / bright, linear for the
+ parameters that may sit at 0, width ** 2 against (1 - corr) / (1 + corr) for width), kept inside the tightest
+ bracket once two renders straddle the target, at most TONAL_FIX corrections after a first render at the sound's own
+ value; the closest render's value is kept. edits[knob] = {target,
+ param, value, measured (on the file that ships), renders, ok (within TONAL_TOL)}. A sound without the parameter
+ (whooshes, keys, fits) is refused with the reason. bank.render / kit edits pass these through apply(..., decay=,
+ onset=, bright=, width=) once they name them.
Level (peak_db, weight) is bank.render's, after the knobs.
"""
import re
@@ -63,7 +81,10 @@ LENGTH = {'riser': 'length', 'pro_riser': 'length', 'downlifter': 'length', 'sub
'glitch': 'dur', 'pro_glitch': 'dur', 'pro_typing_run': 'dur', 'pro_logo_sting': 'g_length',
'click': 'length', 'pro_click': 'length', 'hover_tick': 'length', 'pro_hover_tick': 'length',
'tap': 'length', 'pro_tap': 'length', 'pro_pop_in': 'length', 'pop': 'length', 'pro_pop': 'length',
- 'notify': 'length', 'pro_notify': 'length', 'pro_typing_key': 'length'}
+ 'notify': 'length', 'pro_notify': 'length', 'pro_typing_key': 'length',
+ 'reverse_swell': 'length'}
+# (earshot 0.4: reverse_swell = recipes/revcymbal.py; cut_hit stays trim: its `length` is a ceiling, the render ends
+# 30 ms after it is 60 dB down)
# category -> pitch spec: param (the note), co (scaled with it), range (Hz), needs (param, minimum: the tonal layer
# must be on), measure ('start': the first 0.6 s, 'end': the last half, None: not measured), mode 'pc' = a pitch class,
@@ -95,6 +116,15 @@ PITCH = {
'pro_whoosh_big': {'param': 'sub_f', 'range': (25.0, 120.0), 'needs': ('sub_db', -30.0), 'measure': 'end'},
'shimmer': {'param': 'key', 'mode': 'pc'},
'pro_shimmer': {'param': 'key', 'mode': 'pc'},
+ # earshot 0.4 tonal / UI recipes (ui_pop: the landing pitch; knock: the lowest mode; drip: the pitch at pinch-off,
+ # not measured: the heard pitch is where it has risen to)
+ 'ui_pop': {'param': 'f0', 'range': (250.0, 1200.0)},
+ 'mallet': {'param': 'f0', 'range': (150.0, 3200.0)},
+ 'knock': {'param': 'f1', 'range': (250.0, 2600.0)},
+ 'drip': {'param': 'f0', 'range': (250.0, 1600.0), 'measure': None},
+ # earshot 0.4 cut hit (recipes/cuthit.py): the sub lands on the track's root, its start keeps the glide ratio; not
+ # measured (the kick's click and the short glide hide the landing pitch in a 0.3 s file)
+ 'cut_hit': {'param': 'sub_f1', 'co': ('sub_f0',), 'range': (36.0, 130.0), 'measure': None},
}
UNTUNED = {
'whoosh_fast': 'a noise pass-by: its band moves with the motion, it has no note',
@@ -108,9 +138,38 @@ UNTUNED = {
'pro_typing_run': 'a typed run is not tuned',
}
FIT_PITCH = {'hybrid': 'pitch', 'sines': 'transpose', 'modal': 'size'} # fit kind -> knob (semitones; size ratio)
-FIT_LENGTH = {'spectral': 'length', 'sines': 'stretch'}
+FIT_LENGTH = {'spectral': 'length', 'sines': 'stretch', 'gesture': 'length'} # (0.4: the gesture's time-stretch)
FIT_PITCH_ST = 12.0 # a fit moves at most an octave from its own note
+# earshot 0.4, the tonal knobs (module doc): knob -> category -> {param, range (the parameter's own limits), co (scaled
+# by the same ratio), lin (search the parameter linearly: it may sit at 0), inverse (a larger value lowers the measure),
+# styles (only these values of the recipe's `style`: notify's hardness is the bell's; a mallet pluck has none)}
+TONAL = {
+ 'decay': {'notify': {'param': 'ring', 'range': (0.05, 4.0)}, 'pro_notify': {'param': 'ring', 'range': (0.05, 4.0)},
+ 'pluck': {'param': 'tau1', 'range': (0.03, 2.4)}, 'ui_pop': {'param': 'tau', 'range': (0.006, 0.2)},
+ 'drip': {'param': 'tau', 'range': (0.008, 0.25)}, 'knock': {'param': 'decay', 'range': (0.002, 0.2)},
+ 'mallet': {'param': 'decay', 'co': ('gate',), 'range': (0.02, 2.0)},
+ 'shutter': {'param': 'b_decay', 'co': ('body_ms',), 'range': (0.002, 0.15)}},
+ 'onset': {'notify': {'param': 'soft', 'range': (0.0, 0.12), 'lin': True},
+ 'pro_notify': {'param': 'soft', 'range': (0.0, 0.12), 'lin': True},
+ 'ui_pop': {'param': 'onset', 'range': (0.002, 0.12)}, 'drip': {'param': 'onset', 'range': (0.0005, 0.12)},
+ 'mallet': {'param': 'onset', 'range': (0.0003, 0.12)}},
+ 'bright': {'notify': {'param': 'hard', 'range': (0.0, 1.0), 'lin': True, 'styles': ('bell',)},
+ 'mallet': {'param': 'hard', 'range': (0.0, 1.0), 'lin': True, 'styles': ('note',)},
+ 'ui_pop': {'param': 'h2', 'range': (0.0, 1.2), 'lin': True},
+ 'drip': {'param': 'h2', 'range': (0.0, 1.0), 'lin': True},
+ 'shutter': {'param': 'b_hz', 'range': (300.0, 3000.0)}}, # the box under the curtain
+ # (no knock: its centroid follows the contact's spectral nulls and the noise, not one parameter; pick a member or
+ # use the pitch knob)
+ 'width': {c: {'param': 'width', 'range': (0.0, 3.0 if c in ('notify', 'pro_notify') else 1.5), 'lin': True,
+ 'inverse': True} # fx.decorrelate reaches corr ~0 at 1.43 (notify halves its width: 2.9)
+ for c in ('notify', 'pro_notify', 'ui_pop', 'drip', 'knock', 'mallet', 'shutter', 'pluck')},
+}
+TONAL_LIMITS = {'decay': (2.0, 3000.0), 'onset': (0.5, 300.0), 'bright': (50.0, 16000.0), 'width': (-1.0, 1.0)}
+TONAL_TOL = {'decay': (0.1, 3.0), 'onset': (0.15, 3.0), 'bright': (0.08, 30.0), 'width': (0.0, 0.05)} # (rel, abs)
+TONAL_ORDER = ('decay', 'onset', 'bright', 'width')
+TONAL_FIX = 4 # tonal knobs: corrections after the first render (_aim_tonal)
+
class KnobError(ValueError):
"""a knob this sound cannot take, or a target outside its range"""
@@ -180,6 +239,12 @@ def describe(entry):
out['pitch'] = _pitch_spec(entry)
except KnobError as e:
out['why'] = str(e).split(': ', 1)[-1]
+ out['tonal'] = {}
+ for knob in TONAL_ORDER: # earshot 0.4: which tonal knobs it takes, through which parameter
+ try:
+ out['tonal'][knob] = _tonal_spec(entry, knob)['param']
+ except KnobError:
+ out['tonal'][knob] = None
return out
@@ -275,10 +340,17 @@ def _number(v, name):
return float(v)
-def validate(entry, dur=None, apex=None, pitch=None):
+def validate(entry, dur=None, apex=None, pitch=None, decay=None, onset=None, bright=None, width=None):
"""the knobs an entry can take, checked without rendering (KnobError says why): what apply() refuses, so a kit
check refuses the same (earshot.forge.kit.problems)"""
sid = entry.get('id') or _cat(entry)
+ for knob, v in (('decay', decay), ('onset', onset), ('bright', bright), ('width', width)):
+ if v is not None:
+ v = _number(v, knob)
+ lo, hi = TONAL_LIMITS[knob]
+ if not lo <= v <= hi:
+ raise KnobError(f'{knob} must be {lo:g}-{hi:g} ({TONAL_UNITS[knob]}), got {v:g}')
+ _tonal_spec(entry, knob)
if dur is not None:
dur = _number(dur, 'dur')
if not 0.01 <= dur <= 60:
@@ -296,10 +368,10 @@ def validate(entry, dur=None, apex=None, pitch=None):
_pitch(entry, pitch)
-def apply(entry, run, dur=None, apex=None, pitch=None):
+def apply(entry, run, dur=None, apex=None, pitch=None, decay=None, onset=None, bright=None, width=None):
"""(raw render, edits) of an entry with its knobs set: run(params_edit, fit_knobs) renders (bank.renderer)"""
from . import bank
- validate(entry, dur, apex, pitch)
+ validate(entry, dur, apex, pitch, decay, onset, bright, width)
edits, pe, fk = {}, {}, {}
if pitch is not None:
p_upd, f_upd, info = _pitch(entry, pitch)
@@ -309,6 +381,11 @@ def apply(entry, run, dur=None, apex=None, pitch=None):
meta = entry.get('meta') or {}
if pitch is not None and edits['pitch'].get('mode') == 'partial':
pe.update(_land_partial(entry, run, pe, fk, edits['pitch']))
+ tonal = {'decay': decay, 'onset': onset, 'bright': bright, 'width': width}
+ for knob in TONAL_ORDER: # earshot 0.4: the tonal knobs, each landed by measurement
+ if tonal[knob] is not None:
+ upd, edits[knob] = _aim_tonal(entry, run, pe, fk, knob, float(tonal[knob]))
+ pe.update(upd)
if apex is not None or (dur is not None and _cat(entry) in WHOOSH):
x, info = _whoosh(entry, run, pe, dur, apex, meta)
edits.update(info)
@@ -331,9 +408,140 @@ def apply(entry, run, dur=None, apex=None, pitch=None):
edits['pitch']['cents_off'] = int(round(1200 * np.log2(got / edits['pitch']['target_hz'])))
ok = bool(got) and abs(edits['pitch'].get('cents_off', 0)) <= PITCH_TOL_CENTS
edits['pitch']['ok'] = ok if where else None # None: a sound whose pitch is not measured (riser, impact)
+ if any(tonal[k] is not None for k in TONAL_ORDER): # measure the file that ships (dur may have changed it)
+ got = _tonal_measures(x)
+ for knob in TONAL_ORDER:
+ if tonal[knob] is not None:
+ edits[knob]['measured'] = got[knob]
+ edits[knob]['ok'] = _tonal_ok(knob, got[knob], tonal[knob])
return x, edits
+# ------------------------------------------------------------------------------------------- earshot 0.4: tonal knobs
+TONAL_UNITS = {'decay': 't20 ms', 'onset': 'attack ms', 'bright': 'centroid Hz', 'width': 'L/R correlation'}
+
+
+def _recipe_defaults(entry):
+ """the DEFAULTS of an entry's recipe module ({} when it has none): a parameter added after the entry was built
+ (notify's ring / soft) takes its recipe default, which renders the entry unchanged"""
+ import importlib
+ try:
+ return dict(getattr(importlib.import_module(f"earshot.forge.recipes.{entry.get('recipe')}"), 'DEFAULTS', {}))
+ except (ImportError, TypeError, ValueError):
+ return {}
+
+
+def _tonal_spec(entry, knob):
+ """{param, range, co, lin, inverse} of a tonal knob on an entry, or KnobError with the reason"""
+ sid = entry.get('id') or _cat(entry)
+ if entry.get('type') == 'fit':
+ raise KnobError(f'{sid}: a fitted recording has no {knob} parameter (its fit knobs are pitch and length)')
+ s = TONAL[knob].get(_cat(entry))
+ if s is None:
+ raise KnobError(f'{sid}: {_cat(entry)} has no {knob} knob (it applies to '
+ f'{", ".join(sorted(TONAL[knob]))})')
+ if s['param'] not in entry.get('params', {}) and s['param'] not in _recipe_defaults(entry):
+ raise KnobError(f"{sid}: its recipe has no {s['param']} parameter (the {knob} knob)")
+ if s.get('styles'):
+ style = {**_recipe_defaults(entry), **entry.get('params', {})}.get('style')
+ if style not in s['styles']:
+ raise KnobError(f"{sid}: its {style} style has no {knob} parameter (only {', '.join(s['styles'])})")
+ return s
+
+
+def _tonal_measures(x):
+ from .recipes._tonal import measure
+ m = measure(x)
+ return {'decay': m['t20_ms'], 'onset': m['attack_ms'], 'bright': m['centroid_hz'], 'width': m['corr']}
+
+
+def _tonal_ok(knob, got, target):
+ if got is None:
+ return False
+ rel, ab = TONAL_TOL[knob]
+ return bool(abs(got - target) <= max(ab, rel * abs(target)))
+
+
+def _aim_tonal(entry, run, pe, fk, knob, target):
+ """({param: value, co...}, info) landing one tonal knob (module doc): a first render at the current value, then at
+ most TONAL_FIX corrections along a safeguarded secant in the knob's own coordinates (_tonal_axes): extrapolated
+ from the last two renders (a first step from the knob's sense) until two renders bracket the target, then kept
+ inside the tightest bracket (the catalog's measures step where an envelope's peak moves along a plateau, so a free
+ secant can wander); the closest render is kept"""
+ s = _tonal_spec(entry, knob)
+ k, (lo, hi) = s['param'], s['range']
+ base = {**_recipe_defaults(entry), **entry.get('params', {}), **pe}
+ v0 = float(base[k])
+ co = {c: float(base[c]) for c in s.get('co', ()) if c in base}
+ lin = s.get('lin', False)
+ X, Xi, Y = _tonal_axes(knob, lin)
+ yt = Y(target)
+
+ def upd(v):
+ return {k: v, **{c: c0 * (v / v0) for c, c0 in co.items()}} if v0 > 0 else {k: v}
+
+ def meas(v):
+ got = _tonal_measures(run({**pe, **upd(v)}, fk))[knob]
+ return None if got is None else float(got)
+
+ def first_step(v1, m1):
+ if knob == 'width': # decorrelation: (1 - corr) / (1 + corr) grows as width ** 2
+ return 0.5 if v1 <= 1e-6 or m1 is None else float(np.sqrt(yt / max(Y(m1) / v1 ** 2, 1e-9)))
+ if lin and knob == 'onset' and m1 is not None: # a soft rise of T s lengthens the attack by ~0.9 T
+ return v1 + 0.9 * (target - m1) / 1000.0
+ if lin: # guess the direction from the knob's sense
+ sgn = -1.0 if s.get('inverse') else 1.0
+ return v1 + (0.25 * (hi - lo) * (1.0 if m1 is None else np.sign(target - m1) * sgn))
+ ratio = target / max(m1, 1e-9) if m1 else 2.0
+ return v1 * (ratio ** (-1.0 if s.get('inverse') else 1.0))
+
+ def step():
+ ok = [(X(v), Y(m)) for v, m in pts if m is not None]
+ below, above = [p for p in ok if p[1] < yt], [p for p in ok if p[1] > yt]
+ if below and above: # bracketed: interpolate, kept off the ends of the tightest bracket
+ a, b = min(((p, q) for p in below for q in above), key=lambda pq: abs(pq[0][0] - pq[1][0]))
+ x = a[0] + (yt - a[1]) * (b[0] - a[0]) / (b[1] - a[1])
+ x0, x1 = sorted((a[0], b[0]))
+ return Xi(float(np.clip(x, x0 + 0.15 * (x1 - x0), x1 - 0.15 * (x1 - x0))))
+ (va, ma), (vb, mb) = (pts[-2] if len(pts) > 1 else (None, None)), pts[-1]
+ if knob != 'width' and va is not None and ma is not None and mb is not None and Y(ma) != Y(mb) and va != vb:
+ xa, xb = X(va), X(vb)
+ slope = (Y(mb) - Y(ma)) / (xb - xa)
+ if slope * (-1.0 if s.get('inverse') else 1.0) > 0: # a secant against the knob's sense is noise: skip it
+ x = xb + (yt - Y(mb)) / slope
+ lim = (hi - lo) * 0.5 if lin else np.log(4.0) # an extrapolation moves at most this far
+ return Xi(float(np.clip(x, xb - lim, xb + lim)))
+ return first_step(vb, mb)
+
+ pts = [(v0, meas(v0))]
+ best = pts[0]
+ for _ in range(TONAL_FIX):
+ if best[1] is not None and _tonal_ok(knob, best[1], target):
+ break
+ v = float(np.clip(step(), lo, hi))
+ if any(abs(v - p[0]) <= 1e-9 * max(1.0, abs(v)) for p in pts):
+ break
+ pts.append((v, meas(v)))
+ if pts[-1][1] is not None and (best[1] is None or abs(pts[-1][1] - target) < abs(best[1] - target)):
+ best = pts[-1]
+ info = {'target': target, 'param': k, 'value': round(best[0], 6), 'renders': len(pts),
+ 'search_measured': None if best[1] is None else round(best[1], 3)}
+ if co:
+ info['co'] = {c: round(v, 6) for c, v in upd(best[0]).items() if c != k}
+ return upd(best[0]), info
+
+
+def _tonal_axes(knob, lin):
+ """(X, X inverse, Y): the coordinates a tonal knob's secant runs in, where the measure is near linear in the
+ parameter: width = (width ** 2, (1 - corr) / (1 + corr)); lin specs = (value, measure); the rest log-log"""
+ if knob == 'width':
+ return (lambda v: v * v, lambda x: float(np.sqrt(max(x, 0.0))),
+ lambda c: (1 - min(max(c, -0.99), 0.999)) / (1 + min(max(c, -0.99), 0.999)))
+ if lin:
+ return (lambda v: v, lambda x: x, lambda m: m)
+ return (lambda v: float(np.log(max(v, 1e-9))), lambda x: float(np.exp(x)), lambda m: float(np.log(max(m, 1e-9))))
+
+
def _land_partial(entry, run, pe, fk, info):
"""a click / toggle aimed at a heard note: the parameter scaled by target / heard (heard: meta pitch_hz, else
measured on a first render), then rendered, measured and corrected along the ratio at most MAX_FIX times; the
diff --git a/earshot/forge/recipes/_tonal.py b/earshot/forge/recipes/_tonal.py
new file mode 100644
index 0000000..09e1393
--- /dev/null
+++ b/earshot/forge/recipes/_tonal.py
@@ -0,0 +1,234 @@
+"""Shared building blocks of the earshot 0.4 tonal / UI recipes (ui_pop, knock, mallet, drip, shutter): a soft onset
+with a real decay, a gliding tone with soft partials, noise that follows a pitch, short contact bursts, struck modes,
+and the finish (band limits, a small room, width, a clean start and end). Every sample is computed.
+
+ from earshot.forge import dsp
+ from earshot.forge.recipes import _tonal as T
+ t = dsp.t_of(dsp.n_of(0.3))
+ e = T.env(t, onset=0.03, tau=0.035) # 30 ms soft rise, then 20 dB down in ~80 ms
+ y = T.tone(T.glide(t, 560.0, 3.0, 0.02), dsp.rng(1), [(2, 0.3, 1.5)], e)
+ x = T.finish(y, dsp.rng(1), hp=120.0, lp=5000.0, room=0.08, width=0.1)
+
+Why a shared module: the films' UI sounds differ in body (a tone, a struck bar, a wooden block, a bubble, a shutter's
+two contacts) but share the parts that the 0.3 bank got wrong in all of them (the earshot 0.4 film study): the onset
+(20-60 ms in the films' pops and dings, 5 ms in the bank), the decay (a real ring-down to 0.2-0.4 s, not a fade at the
+end of a 2 s ring) and the width (corr 0.3-0.7 on mallet notes, ~1.0 in the bank).
+"""
+import numpy as np
+
+from .. import dsp, fx
+
+SR = dsp.SR
+
+
+def env(t, onset, tau, hold=0.0, curve=1.0, dcurve=1.0):
+ """a soft rise from 0 to 1 over `onset` s (a raised cosine; curve > 1 starts slower, < 1 faster), `hold` s at the
+ top, then a decay exp(-(t' / tau) ** dcurve): dcurve 1 = exponential (20 dB down in 2.3 tau), > 1 = a body that is
+ damped as it rings (slower at first, then faster: t40 / t20 = 2 ** (1 / dcurve))"""
+ u = np.clip(t / max(onset, 1e-4), 0, 1) ** curve
+ rise = 0.5 - 0.5 * np.cos(np.pi * u)
+ x = np.maximum(t - onset - hold, 0) / max(tau, 1e-4)
+ return rise * np.exp(-(x if dcurve == 1.0 else x ** dcurve))
+
+
+def two_rate(t, onset, fast, tf, ts, curve=1.0):
+ """a struck body's decay: a soft rise over `onset`, then `fast` of the level dying with tf, the rest with ts (most
+ of a strike dies in tens of ms, a quiet ring carries on)"""
+ u = np.clip(t / max(onset, 1e-4), 0, 1) ** curve
+ rise = 0.5 - 0.5 * np.cos(np.pi * u)
+ tm = np.maximum(t - onset, 0)
+ return rise * (fast * np.exp(-tm / max(tf, 1e-4)) + (1 - fast) * np.exp(-tm / max(ts, 1e-4)))
+
+
+def glide(t, f0, bend_st=0.0, ptau=0.02):
+ """a pitch track (Hz per sample) that starts bend_st semitones off f0 (> 0: above, so it falls) and settles on f0
+ exponentially with time constant ptau s"""
+ return f0 * 2 ** (bend_st / 12 * np.exp(-t / max(ptau, 1e-4)))
+
+
+def rise_track(t, f0, rise_st, rtau):
+ """a pitch that RISES from f0 by rise_st semitones, most of it within ~3 rtau s (a bubble's cavity shrinking)"""
+ return f0 * 2 ** (rise_st / 12 * (1 - np.exp(-t / max(rtau, 1e-4))))
+
+
+def _alias(f, q):
+ """a partial's gain as it nears Nyquist (faded out over the last 2.4 kHz below 0.45 SR)"""
+ return np.clip((0.45 * SR - q * f) / 2400.0, 0, 1)
+
+
+def tone(f, r, parts=(), e=None):
+ """a sine on the pitch track f (Hz per sample) plus partials [(ratio, amp, decay)], each following the envelope
+ e ** decay (decay > 1: dies faster than the body, a natural rounded tone); ratio may be inharmonic"""
+ n = len(f)
+ e = np.ones(n) if e is None else e
+ ph = 2 * np.pi * np.cumsum(f) / SR + r.uniform(0, 2 * np.pi)
+ y = np.sin(ph) * e
+ for q, a, d in parts:
+ if a <= 0:
+ continue
+ y = y + a * _alias(f, q) * e ** d * np.sin(q * ph + r.uniform(0, 2 * np.pi))
+ return y
+
+
+def follow_noise(n, r, fc, q, e):
+ """turbulence through a band-pass that follows fc (Hz per sample or a number): a breath or cavity hiss, scaled to
+ the RMS of a unit sine over the envelope's live part (so 0 dB = as strong as the tone), times e"""
+ fc = np.minimum(np.broadcast_to(np.asarray(fc, float), (n,)), 16000.0)
+ b = dsp.svf(r.standard_normal(n), fc, q, 'band')
+ live = e > 0.1 * (e.max() + 1e-12)
+ b = b / (np.sqrt(np.mean(b[live] ** 2)) + 1e-12) * np.sqrt(0.5)
+ return b * e
+
+
+def burst(n, r, lo, hi, tau, rise=0.0003, order=2):
+ """a short contact noise of length n samples: white noise band-passed lo-hi Hz, a `rise` s rise and an exponential
+ decay (tau s); peak 1"""
+ k = min(n, dsp.n_of(max(6 * tau + rise, 0.002)))
+ tk = dsp.t_of(k)
+ w = dsp.butter(r.standard_normal(k), 'band', (max(lo, 20.0), min(hi, 0.45 * SR)), order=order)
+ w *= (1 - np.exp(-tk / max(rise, 1e-5))) * np.exp(-tk / max(tau, 1e-5))
+ y = np.zeros(n)
+ y[:k] = w / (np.abs(w).max() + 1e-12)
+ return y
+
+
+def thump(n, f, tau, rise=0.002):
+ """a soft low thump of length n: a damped sine at f Hz with a `rise` s onset; peak ~1"""
+ t = dsp.t_of(n)
+ y = np.sin(2 * np.pi * f * t) * (1 - np.exp(-t / max(rise, 1e-4))) * np.exp(-t / max(tau, 1e-4))
+ return y / (np.abs(y).max() + 1e-12)
+
+
+def modes(n, r, freqs, amps, taus, jitter=0.0, bend=0.0, bend_tau=0.004):
+ """struck modes: damped sines (Hz, linear amplitudes, time constants s); `bend` = a fraction the pitch starts above
+ (a hard strike stiffens the body for a few ms), settling with bend_tau"""
+ t = dsp.t_of(n)
+ y = np.zeros(n)
+ b = 1 + bend * np.exp(-t / max(bend_tau, 1e-4))
+ for f, a, tau in zip(freqs, amps, taus):
+ if a <= 0 or f >= 0.45 * SR:
+ continue
+ f = f * (1 + jitter * r.standard_normal())
+ ph = 2 * np.pi * np.cumsum(f * b) / SR + r.uniform(0, 2 * np.pi)
+ y += a * np.exp(-t / max(tau, 1e-5)) * np.sin(ph)
+ return y
+
+
+def strike(y, r, contact_s, bright=0.5):
+ """a resonator's response driven by a contact (dsp.contact: a raised-cosine force pulse of contact_s s plus a little
+ grit); a longer contact (a soft mallet, a fingertip) excites the high modes less"""
+ return dsp.excite(y, dsp.contact(contact_s, r, bright))
+
+
+def room(y, r, wet, rt60, size=0.15, width=0.3):
+ """a small room on a stereo (n, 2) signal (fx.reverb, stereo); wet 0 = none (no rng draw)"""
+ if wet <= 0.005:
+ return y
+ return fx.reverb(y, r, rt60=rt60, size=size, predelay=0.004, damp=0.6, wet=wet, stereo=True, width=width)
+
+
+def finish(y, r, hp=80.0, lp=12000.0, room_wet=0.0, rt60=0.15, width=0.0, cut=500.0, end_db=-60.0, fade=0.006,
+ pan=0.0, size=0.15):
+ """mono -> stereo: band limits (4th-order high-pass at hp, 2nd-order low-pass at lp; lp >= 17.5 kHz = none), width
+ (fx.decorrelate: a decorrelated side above `cut` Hz), a constant-power pan, a small room, the tail trimmed where it
+ stays end_db under the peak, a clean start (0.3 ms) and a convex end fade. The dry signal's own end is faded first
+ (20 ms, at most 15 % of it): it is ~60 dB down there, but the room rings on past it, and a low body cut within
+ one of its cycles (a 95 Hz desk thump: 10.5 ms) leaves a step in the quiet tail that the audit hears as a click"""
+ y = np.array(y, np.float64)
+ kd = min(len(y), dsp.n_of(0.02), int(0.15 * len(y)))
+ y[len(y) - kd:] *= np.cos(np.linspace(0, np.pi / 2, kd)) ** 2
+ y = dsp.butter(y, 'high', hp, order=4)
+ if lp < 17500:
+ y = dsp.butter(y, 'low', lp, order=2)
+ st = fx.decorrelate(y, width, cut=cut) if width > 0.005 else np.stack([y, y], 1)
+ if abs(pan) > 0.005:
+ th = (np.clip(pan, -1, 1) + 1) * np.pi / 4
+ st = st * np.array([np.cos(th), np.sin(th)]) * np.sqrt(2)
+ st = room(st, r, room_wet, rt60, size=size, width=0.3 + width)
+ st = dsp.trim_tail(st, end_db, 0.01)
+ k = min(len(st), dsp.n_of(fade))
+ w = np.cos(np.linspace(0, np.pi / 2, k)) ** 2
+ st[-k:] *= w[:, None]
+ a = min(len(st), dsp.n_of(0.0003))
+ st[:a] *= (0.5 - 0.5 * np.cos(np.linspace(0, np.pi, a)))[:, None]
+ return st
+
+
+def measure(x):
+ """the catalog's model-free measurements of one render on silence (the same definitions the films were measured
+ with: the earshot 0.4 film catalog, stage A): dur_s (onset at -30 dB to the last frame within 45 dB), attack_ms
+ (first ms within 20 dB of the peak to the peak, 5 ms RMS smoothed 10 ms), t20_ms / t40_ms, centroid_hz, lo150 / hi4k
+ (energy shares under 150 Hz / over 4 kHz), tonal (mean share within a quarter octave of the strongest bin), glide_st
+ and corr (L / R correlation)"""
+ y = np.asarray(x, np.float64)
+ if y.ndim == 1:
+ y = np.stack([y, y], 1)
+ m = y.mean(1)
+ n = len(m)
+ c = np.concatenate([[0.0], np.cumsum(m * m)])
+ w, hop = int(0.005 * SR), int(0.001 * SR)
+ cen = np.arange(0, n, hop)
+ a, b = np.clip(cen - w // 2, 0, n), np.clip(cen + w // 2, 0, n)
+ sm = np.convolve((c[b] - c[a]) / np.maximum(b - a, 1), np.ones(10) / 10, mode='same')
+ ip = int(np.argmax(sm))
+ pk = sm[ip]
+ above = np.nonzero(sm[:ip + 1] >= pk * 1e-2)[0]
+ on = np.nonzero(sm >= pk * 1e-3)[0]
+ after = sm[ip:]
+ w20, w40 = np.nonzero(after < pk * 1e-2)[0], np.nonzero(after < pk * 1e-4)[0]
+ a45 = np.nonzero(sm >= pk * 10 ** -4.5)[0]
+ out = {'dur_s': round((a45[-1] if len(a45) else n / hop) * 0.001 - (on[0] * 0.001 if len(on) else 0.0), 3),
+ 'attack_ms': float(ip - above[0]) if len(above) else None,
+ 't20_ms': float(w20[0]) if len(w20) else None, 't40_ms': float(w40[0]) if len(w40) else None}
+ nf, hp_ = 2048, 240
+ seg = np.pad(m, (0, max(0, nf - n)))
+ k = 1 + (len(seg) - nf) // hp_
+ idx = np.arange(nf)[None, :] + hp_ * np.arange(k)[:, None]
+ P = (np.abs(np.fft.rfft(seg[idx] * np.hanning(nf), axis=1)) ** 2).T
+ F = np.fft.rfftfreq(nf, 1 / SR)
+ fe = P.sum(0)
+ act = fe >= fe.max() * 1e-2
+ spec = P[:, act].mean(1)
+ tot = spec.sum() + 1e-20
+ out['centroid_hz'] = round(float((spec * F).sum() / tot))
+ out['lo150'] = round(float(spec[F < 150].sum() / tot), 3)
+ out['hi4k'] = round(float(spec[F >= 4000].sum() / tot), 3)
+ band = (F >= 80) & (F <= 12000)
+ rid, ton = [], []
+ for j in np.nonzero(act)[0]:
+ col = P[band, j]
+ if col.max() <= 0:
+ continue
+ fr = F[band][int(np.argmax(col))]
+ rid.append(fr)
+ ton.append(col[(F[band] >= fr / 2 ** 0.25) & (F[band] <= fr * 2 ** 0.25)].sum() / (col.sum() + 1e-20))
+ out['tonal'] = round(float(np.mean(ton)), 2) if len(ton) >= 2 else None
+ if len(rid) >= 2:
+ k3 = max(1, min(3, len(rid) // 3))
+ out['glide_st'] = round(float(12 * np.log2(np.median(rid[-k3:]) / np.median(rid[:k3]))), 1)
+ else:
+ out['glide_st'] = None
+ L, R = y[:, 0], y[:, 1]
+ out['corr'] = round(float((L * R).sum() / (np.sqrt((L * L).sum() * (R * R).sum()) + 1e-20)), 2)
+ return out
+
+
+def outside(m, targets):
+ """how far measurements fall outside target ranges {key: (lo, hi, scale)}: the sum of (distance / scale), each
+ capped at 2 (0 = every target met)"""
+ pen = 0.0
+ for k, (lo, hi, sc) in targets.items():
+ v = m.get(k)
+ if v is None:
+ pen += 1.0
+ elif v < lo:
+ pen += min(2.0, (lo - v) / sc)
+ elif v > hi:
+ pen += min(2.0, (v - hi) / sc)
+ return pen
+
+
+def family_space(space, params, fine):
+ """a member's search space: its `fine` keys free (the SPACE ranges), every other key pinned to its value (a
+ one-element choice list: the forge's way of fixing a parameter)"""
+ return {k: (spec if k in fine else [params.get(k)]) for k, spec in space.items() if k in params}
diff --git a/earshot/forge/recipes/brightswish.py b/earshot/forge/recipes/brightswish.py
new file mode 100644
index 0000000..57a589e
--- /dev/null
+++ b/earshot/forge/recipes/brightswish.py
@@ -0,0 +1,130 @@
+"""Bright swishes and the designed bright whip: high, wide air flicks for text and pane moves (forge categories
+'swish' and 'whoosh_fast', members on the pass engine of recipes/whoosh.py).
+
+What the reference clips do (a private licensed set and its category notes; the clips
+are local study material and are not shipped):
+ * swish (6 events in 5 films): short and BRIGHT, 0.25 s (0.21-0.29), centroid 2.1 kHz (0.8-3.6), its loudest point
+ 134 ms (115-150) after the first moment within 20 dB of it (it rises, then stops), fairly wide (L/R correlation
+ 0.76, 0.43-0.94; one of the clean ones -0.04 at 4.4 kHz). earshot 0.3's swishes sat at ~600 Hz, 2-5x darker;
+ * the effects-led film's whip: 0.74 s, 2.7 kHz, decorrelated (correlation 0.07), hits in ~15 ms and falls ~45
+ semitones while it rings out (-20 dB 0.45 s after the peak), a comb-like fan of falling partials and a granular
+ flutter through it. It FALLS: the rising synth whip is the cheap version this recipe never makes (the audit's
+ rising-glide check stays silent on every member).
+How it is built: the pass engine (`whoosh.render`) with the air band high (f_peak 2-5 kHz), no low weight or sub, the
+hiss as loud as the air body, a decorrelated hiss side (hiss_width) and air side (width); the whip adds a fast rise,
+a band that sinks down_oct after the peak (track > 1: it falls with the level) and a deep fast flutter. One optional
+layer of its own: `comb_mix` runs the pass through a feedback comb whose fundamental falls comb_f0 -> comb_f1 over the
+file (a fan of falling partials, after impact._vcomb_core), per channel. The whoosh knobs (dur 'shape', apex) apply.
+Every sample is computed; no recorded audio is used.
+"""
+import types
+
+import numpy as np
+
+from .. import dsp
+from . import whoosh as _w
+from .impact import _vcomb_core
+
+SR = dsp.SR
+TARGET = 'a bright quick swish'
+ALTS = ['a short burst of steam', 'a page being flipped', 'a sword being sharpened', 'rain']
+REFSET = 'swish'
+
+COMB_SPACE = {
+ 'comb_mix': (0.0, 1.0),
+ 'comb_f0': (150.0, 4000.0, 'log'), # the comb's fundamental at the first sample (Hz)
+ 'comb_f1': (40.0, 1500.0, 'log'), # and at the last
+ 'comb_fb': (0.0, 0.92),
+}
+COMB_KEYS = tuple(COMB_SPACE)
+COMB_OFF = {'comb_mix': 0.0, 'comb_f0': 1000.0, 'comb_f1': 200.0, 'comb_fb': 0.5}
+SPACE = {**_w.SPACE, **COMB_SPACE}
+
+SWISH = {**_w.FAST, **_w.OPTIONAL, **COMB_OFF,
+ 'rise': 0.13, 'rise_k': 0.8, 'hold': 0.0, 'fall': 0.07, 'fall_k': 1.1, 'start_db': -32.0, 'track': 0.7,
+ 'f_peak': 2300.0, 'up_oct': 1.0, 'down_oct': 1.3, 'dop_st': 3.0, 'dop_w': 0.03, 'q_air': 1.4,
+ 'lp_ratio': 2.6, 'flut_depth': 0.2, 'flut_f': 30.0, 'low_db': -40.0, 'sub_db': -50.0, 'hiss_db': -6.0,
+ 'hiss_hp': 3000.0, 'hiss_open': 1.2, 'hiss_pow': 1.3, 'hiss_tail': None, 'hiss_pre': None,
+ 'hiss_mfloor': 0.0, 'tail_sweep': 0.0, 'hiss_q': 0.8, 'tone_db': -50.0, 'grain_db': -50.0,
+ 'room_wet': 0.08, 'rt60': 0.35, 'room_damp': 0.3, 'pan': 0.15, 'width': 0.35, 'hiss_width': 0.5,
+ 'drive_db': 1.0, 'end_db': -62.0, 'end_fade': 0.03, 'eq_lo_db': -12.0, 'eq_lo_f': 300.0,
+ 'eq_hi_db': 0.0, 'eq_hi_f': 6000.0}
+WHIP = {**SWISH,
+ 'rise': 0.02, 'rise_k': 1.0, 'hold': 0.0, 'fall': 0.5, 'fall_k': 0.75, 'start_db': -30.0, 'track': 1.2,
+ 'f_peak': 4200.0, 'up_oct': 0.5, 'down_oct': 3.5, 'dop_st': 6.0, 'dop_w': 0.05, 'q_air': 2.5,
+ 'lp_ratio': 2.2, 'flut_depth': 0.6, 'flut_f': 32.0, 'hiss_db': -12.0, 'hiss_hp': 2500.0, 'hiss_tail': 1.0,
+ 'room_wet': 0.15, 'rt60': 0.6, 'width': 0.6, 'hiss_width': 1.0, 'pan': 0.1, 'end_db': -60.0,
+ 'end_fade': 0.06, 'comb_mix': 0.5, 'comb_f0': 2200.0, 'comb_f1': 160.0, 'comb_fb': 0.7}
+BASES = {'swish': SWISH, 'whoosh_fast': WHIP}
+FAMILIES = {
+ # earshot 0.4 phase B: hand-designed corners of SWISH / WHIP, then tuned toward each style on the measured
+ # features (the music films' swish profile for bright; the study's dev-split clips of the flick and the designed
+ # whip) and, for flick and whip, on CLAP only up to the grade bar
+ 'swish': [
+ # the music films' bright swish: ~2.4 kHz, a 100 ms rise, a quick fall, fairly wide
+ ('bright', {'rise_k': 0.9287, 'hold': 0.05657, 'fall_k': 1.127, 'track': 0.6361, 'up_oct': 1.004,
+ 'down_oct': 2.161, 'q_air': 2.813, 'flut_depth': 0.3016, 'flut_f': 33.74, 'hiss_db': -3.588,
+ 'hiss_hp': 2054.0, 'hiss_open': 1.037, 'hiss_pow': 1.567, 'grain_rate': 2789.0,
+ 'grain_f': 2753.0, 'room_wet': 0.0, 'rt60': 0.4884, 'pan': 0.1457, 'width': 0.4008,
+ 'eq_lo_db': -10.06, 'eq_hi_db': -12.75, 'hiss_width': 0.7457, 'comb_f0': 327.0,
+ 'comb_f1': 66.57, 'comb_fb': 0.5578}),
+ # a flick that rises and stops dead: higher (~4 kHz), fluttering, decorrelated, a touch of falling comb
+ ('flick', {'rise': 0.09435, 'rise_k': 0.45, 'fall': 0.03, 'fall_k': 1.335, 'track': 0.7737, 'f_peak': 800.3,
+ 'up_oct': 1.338, 'down_oct': 3.046, 'dop_st': 2.201, 'q_air': 0.6, 'lp_ratio': 2.779,
+ 'flut_depth': 0.524, 'flut_f': 44.69, 'hiss_db': -2.058, 'hiss_hp': 3720.0, 'hiss_open': 0.7442,
+ 'hiss_pow': 1.669, 'grain_rate': 381.1, 'grain_f': 3588.0, 'room_wet': 0.06281, 'rt60': 0.307,
+ 'pan': 0.05213, 'width': 0.5124, 'end_fade': 0.02, 'eq_lo_db': -12.61, 'eq_hi_db': 0.8779,
+ 'hiss_width': 1.0, 'comb_mix': 0.3188, 'comb_f0': 4000.0, 'comb_f1': 99.3, 'comb_fb': 0.4513}),
+ ],
+ 'whoosh_fast': [
+ # the designed bright whip: a 20 ms hit, a band and a ringing comb falling ~45 semitones, wide
+ ('whip', {'rise': 0.02, 'rise_k': 0.7391, 'hold': 0.05657, 'fall_k': 1.127, 'track': 1.071, 'f_peak': 4000.0,
+ 'up_oct': 0.2647, 'dop_st': 10.95, 'q_air': 3.505, 'lp_ratio': 1.2, 'flut_f': 25.21, 'hiss_db': 0.0,
+ 'hiss_hp': 1807.0, 'hiss_open': 0.0, 'hiss_pow': 1.51, 'grain_db': -46.8, 'grain_rate': 50.0,
+ 'grain_f': 5843.0, 'room_wet': 0.03593, 'rt60': 0.6411, 'pan': 0.2634, 'eq_lo_db': -15.23,
+ 'eq_hi_db': 1.169, 'comb_mix': 1.0, 'comb_f0': 1464.0, 'comb_f1': 40.0, 'comb_fb': 0.7323}),
+ ],
+}
+DEFAULTS = dict(SWISH)
+TARGETS = {'swish': TARGET, 'whoosh_fast': 'a bright whip whoosh'}
+
+
+def preset(cat, name):
+ return {**BASES[cat], **dict(FAMILIES[cat])[name]}
+
+
+def preset_full(cat, params):
+ return {**BASES[cat], **params}
+
+
+def _comb(y, p):
+ """a feedback comb whose fundamental falls comb_f0 -> comb_f1 over the file, mixed in parallel, per channel"""
+ if p['comb_mix'] < 0.01:
+ return y
+ n = len(y)
+ u = np.arange(n) / max(1, n - 1)
+ d = SR / (p['comb_f0'] * (p['comb_f1'] / p['comb_f0']) ** u)
+ out = np.empty_like(y)
+ for c in range(y.shape[1]):
+ x = np.ascontiguousarray(y[:, c])
+ z = _vcomb_core(x, np.ascontiguousarray(d), p['comb_fb']) * (1 - p['comb_fb'])
+ out[:, c] = x + p['comb_mix'] * (z - x)
+ return out
+
+
+def render(p, r):
+ """the pass engine on SWISH + p (whoosh.OPTIONAL keys absent from p are off), then the falling comb"""
+ q = {**SWISH, **p}
+ y = _w.render({k: v for k, v in q.items() if k not in COMB_KEYS}, r)
+ y = _comb(y, q)
+ y = dsp.fade(y, 0.0, min(q['end_fade'], 0.3 * len(y) / SR))
+ return y / (np.abs(y).max() + 1e-12) * 0.89
+
+
+def recipe(cat='swish', name=None):
+ ns = types.SimpleNamespace(TARGET=TARGETS[cat], ALTS=ALTS, REFSET=cat)
+ ns.__name__ = __name__
+ ns.SPACE = SPACE
+ ns.DEFAULTS = preset(cat, name or FAMILIES[cat][0][0])
+ ns.render = render
+ return ns
diff --git a/earshot/forge/recipes/burstglitch.py b/earshot/forge/recipes/burstglitch.py
new file mode 100644
index 0000000..ac7f689
--- /dev/null
+++ b/earshot/forge/recipes/burstglitch.py
@@ -0,0 +1,211 @@
+"""A burst glitch: a digital glitch that HITS (its loudest burst first, within ~20 ms), then bursts that speed up into
+the cut; every sample is computed.
+
+What the reference clips do (a private licensed set, 'glitch', 10 events in 10 films;
+the clips are local study material and are not shipped): onset 18 ms (16-22) from the first moment within 20 dB of
+the loudest point to it, 0.23 s (0.1-0.45) long, falling 20 dB in 76 ms (71-118); in the music films a mid glitch
+(centroid 902 Hz, 802-1281) laid near mono (correlation 0.98), in the effects-led film crackle, then 11 bright bursts
+(~10 kHz) speeding up into the final cut, fully decorrelated. earshot 0.3's glitches swell for 300-450 ms into their
+loudest burst (pro_glitch, glitch: onset 12-18x too slow on the profile).
+Layers:
+ crackle the first `crackle` share of the length: sparse 1.5-6 ms grains high-passed at crackle_hp, density rising
+ to crackle_rate / s, crackle_db under the bursts (kept under -20 dB so the first burst is the onset)
+ bursts from crackle x dur to dur on a grid accelerating grid0 -> grid1 (power accel), each gated to `gate` of its
+ slot with 0.4 ms edges; the FIRST burst is the loudest (accent_db over the others), the rest fall
+ `fall_db` across the train with lvl_jit dB of spread; a burst is a crushed buffer (bits, srate) of noise
+ mixed with a square chirp stepping down around tone_f (`tonal`), replayed from the previous burst with
+ probability `repeat` (the buffer-repeat identity of a stutter)
+ colour a band-pass lo_f .. hi_f on the bursts (10 kHz glitches: lo_f 4-6 kHz; mid glitches: ~0.4-2.5 kHz)
+ low an optional low pulse under each burst (low_db, around low_f): the effects-led film's bursts thud at
+ 100-400 Hz under their 10 kHz crack
+ stereo `width` = share of bursts whose right channel reads its own buffer with a 0-2 ms offset; crackle grains are
+ independent per channel
+ end the last burst ends on `dur`, then only its own decay end_tail
+"""
+import types
+
+import numpy as np
+
+from .. import dsp
+from .. import fx
+
+SR = dsp.SR
+TARGET = 'a short digital glitch burst'
+ALTS = ['radio static', 'a woodpecker', 'rain on a tin roof', 'a camera shutter']
+REFSET = 'glitch'
+
+SPACE = {
+ 'dur': (0.1, 0.8),
+ 'crackle': (0.0, 0.6), # share of the length before the first burst
+ 'crackle_db': (-45.0, -20.0),
+ 'crackle_rate': (40.0, 600.0, 'log'),
+ 'crackle_hp': (1500.0, 9000.0, 'log'),
+ 'grid0': (0.018, 0.07, 'log'), # first burst interval (s)
+ 'grid1': (0.008, 0.04, 'log'), # last
+ 'accel': (0.5, 2.5, 'log'),
+ 'gate': (0.25, 0.9),
+ 'decay': (0.15, 2.0, 'log'), # each burst's own decay, in slots
+ 'accent_db': (0.0, 12.0), # the first burst over the others
+ 'fall_db': (-12.0, 6.0), # level change across the rest of the train
+ 'lvl_jit': (0.0, 8.0),
+ 'bits': (3.0, 10.0),
+ 'srate': (1500.0, 20000.0, 'log'),
+ 'tonal': (0.0, 1.0),
+ 'tone_f': (300.0, 6000.0, 'log'),
+ 'repeat': (0.0, 0.9),
+ 'lo_f': (150.0, 7000.0, 'log'),
+ 'hi_f': (1500.0, 18000.0, 'log'),
+ 'width': (0.0, 1.0),
+ 'low_db': (-50.0, 0.0), # a low pulse under each burst, re the bursts' peak (-50 = none)
+ 'low_f': (60.0, 500.0, 'log'),
+ 'end_tail': (0.004, 0.06, 'log'),
+ 'pattern': (0, 999, 'int'),
+}
+FAMILIES = {
+ # earshot 0.4 phase B: hand-designed corners, then tuned toward each style on the measured features (the study's
+ # dev-split clip of the effects-led film for burst, CLAP only up to the grade bar; the music films' glitch profile
+ # for mid and chirp), every take audited (no rising chirp survives: the audit's rising-glide check is in the loss)
+ 'glitch': [
+ # the effects-led film's: quiet crackle, then a bright 5-17 kHz burst train that speeds up into the cut, wide,
+ # a faint low thud under each burst
+ ('burst', {'dur': 0.726, 'crackle': 0.4906, 'crackle_db': -35.95, 'crackle_rate': 579.1,
+ 'crackle_hp': 7237.0, 'grid0': 0.0229, 'grid1': 0.02146, 'accel': 1.588, 'gate': 0.6991,
+ 'decay': 0.4964, 'accent_db': 3.442, 'fall_db': -12.0, 'lvl_jit': 7.164, 'bits': 7.138,
+ 'srate': 5507.0, 'tonal': 0.02252, 'tone_f': 3311.0, 'repeat': 0.5548, 'lo_f': 5000.0,
+ 'hi_f': 16990.0, 'width': 1.0, 'low_db': -40.98, 'low_f': 156.6, 'end_tail': 0.02849,
+ 'pattern': 17}),
+ # the music films' mid glitch: a 0.22 s crushed stutter around 1 kHz that hits first, near mono
+ ('mid', {'dur': 0.2159, 'crackle': 0.1444, 'crackle_db': -32.74, 'crackle_rate': 40.0, 'crackle_hp': 3000.0,
+ 'grid0': 0.03, 'grid1': 0.01798, 'accel': 0.8936, 'gate': 0.6, 'decay': 0.7133, 'accent_db': 3.068,
+ 'fall_db': -4.756, 'lvl_jit': 2.992, 'bits': 6.225, 'srate': 8000.0, 'tonal': 0.2935,
+ 'tone_f': 636.8, 'repeat': 0.371, 'lo_f': 150.0, 'hi_f': 2764.0, 'width': 0.1, 'low_db': -50.0,
+ 'low_f': 150.0, 'end_tail': 0.005826, 'pattern': 5}),
+ # data chirps: a pitched, crushed stutter (square tones stepping down) that hits first and rolls faster
+ ('chirp', {'dur': 0.2788, 'crackle': 0.2608, 'crackle_db': -45.0, 'crackle_rate': 94.3, 'crackle_hp': 1734.0,
+ 'grid0': 0.03896, 'grid1': 0.009084, 'accel': 0.7294, 'gate': 0.7683, 'decay': 1.285,
+ 'accent_db': 6.973, 'fall_db': -9.256, 'lvl_jit': 2.413, 'bits': 4.329, 'srate': 6357.0,
+ 'tonal': 0.85, 'tone_f': 446.1, 'repeat': 0.2995, 'lo_f': 459.1, 'hi_f': 6342.0,
+ 'width': 0.7961, 'low_db': -50.0, 'low_f': 150.0, 'end_tail': 0.02571, 'pattern': 29}),
+ ],
+}
+DEFAULTS = dict(FAMILIES['glitch'][0][1])
+TARGETS = {'glitch': TARGET}
+
+
+def _box(n, edge=0.0004):
+ e = np.ones(n)
+ k = min(n // 2, max(2, dsp.n_of(edge)))
+ ramp = 0.5 - 0.5 * np.cos(np.linspace(0, np.pi, k))
+ e[:k] = ramp
+ e[-k:] = ramp[::-1]
+ return e
+
+
+def _buffer(p, pr, n, r):
+ """one burst buffer: crushed noise + a stepped square chirp (pr = the pattern rng: pitches; r = the noise)"""
+ out = r.standard_normal(n)
+ if p['tonal'] > 0.02:
+ f = p['tone_f'] * 2 ** pr.uniform(-0.5, 0.5)
+ steps = int(pr.integers(1, 4)) # the chirp steps DOWN inside a burst (never a rising whine)
+ fr = np.repeat(f * 2 ** (np.sort(pr.integers(-4, 5, steps))[::-1] / 6), int(np.ceil(n / steps)))[:n]
+ out = (1 - 0.7 * p['tonal']) * out / 3.0 + p['tonal'] * dsp.osc(fr, 'square')
+ return fx.crush(out / (np.abs(out).max() + 1e-9), bits=int(round(p['bits'])), rate=p['srate'])
+
+
+def _grid(p, t0, t1):
+ """burst start times from t0, intervals accelerating grid0 -> grid1, the last slot ending at t1"""
+ out, t = [], t0
+ span = max(1e-3, t1 - t0)
+ while True:
+ u = min(1.0, (t - t0) / span) ** p['accel']
+ d = p['grid0'] + (p['grid1'] - p['grid0']) * u
+ if t + d > t1 + 0.25 * d:
+ break
+ out.append((t, d))
+ t += d
+ return out or [(t0, span)]
+
+
+def render(p, r):
+ p = {**DEFAULTS, **p}
+ pr = dsp.rng(int(p['pattern']) * 7919 + 101)
+ dur = p['dur']
+ n_end = dsp.n_of(dur)
+ tail = dsp.n_of(p['end_tail'] * 5)
+ n = n_end + tail
+ y = np.zeros((n, 2))
+ t_st = dur * p['crackle']
+ bursts = _grid(p, t_st, dur)
+ L = dsp.n_of(max(d for _, d in bursts) + 0.004)
+ bufs = [[_buffer(p, pr, L, r) for _ in range(3)] for _ in range(2)] # a buffer set per channel
+ nb = len(bursts)
+ prev = [0, 0]
+ pick_l = (0, 0)
+ for k, (tb, d) in enumerate(bursts):
+ last = k == nb - 1
+ g = max(16, dsp.n_of(d * p['gate']))
+ if last:
+ g = max(16, n_end - dsp.n_of(tb))
+ db = 0.0 if k == 0 else -p['accent_db'] + p['fall_db'] * (k - 1) / max(1, nb - 2) \
+ - abs(p['lvl_jit'] * pr.standard_normal())
+ for c in range(2):
+ own = c == 0 or pr.uniform() <= p['width'] # the right channel reads its own set, or the left's take
+ if not own:
+ j, off = pick_l
+ else:
+ j = prev[c] if pr.uniform() < p['repeat'] else int(pr.integers(0, 3))
+ off = dsp.n_of(pr.uniform(0, 0.002)) if c == 1 and not last and k else 0
+ if c == 0:
+ pick_l = (j, off)
+ prev[c] = j
+ b = bufs[c if own else 0][j]
+ m = min(g, L) if not last else g
+ seg = np.resize(b, m) if m > L else b[:m].copy()
+ env = _box(m) * np.exp(-np.arange(m) / SR / (p['decay'] * d))
+ if last: # the final burst holds to the cut, then its own decay
+ seg = np.concatenate([seg, np.resize(b, tail)])
+ env = np.concatenate([env, env[-1] * np.exp(-np.arange(tail) / SR / (p['end_tail'] / 1.3))])
+ i = dsp.n_of(tb) + off
+ mm = min(len(seg), n - i)
+ if mm > 0:
+ y[i:i + mm, c] += (seg * env)[:mm] * 10 ** (db / 20) * float(np.exp(0.1 * r.standard_normal()))
+ y = dsp.butter(y, 'band', (p['lo_f'], max(p['hi_f'], p['lo_f'] * 1.5)), 2)
+ pk = np.abs(y).max() + 1e-12
+ if p.get('low_db', -50.0) > -49.5: # drawn only when used: members without it render as before
+ low = np.zeros(n)
+ for k, (tb, d) in enumerate(bursts):
+ i = dsp.n_of(tb)
+ m = min(dsp.n_of(d * p['gate']) + dsp.n_of(0.01), n - i)
+ if m < 16:
+ continue
+ tt = np.arange(m) / SR
+ f0 = p['low_f'] * 2 ** pr.uniform(-0.4, 0.4)
+ lo = np.sin(2 * np.pi * f0 * tt + r.uniform(0, 2 * np.pi)) * np.exp(-tt / max(0.004, 0.5 * d))
+ low[i:i + m] += lo * _box(m, 0.001) * (1.0 if k == 0 else 10 ** (-p['accent_db'] / 20))
+ y += (pk * 10 ** (p['low_db'] / 20) * low / (np.abs(low).max() + 1e-12))[:, None]
+ if p['crackle'] > 0.02 and t_st > 0.01:
+ cr = np.zeros((n, 2))
+ for c in range(2):
+ t = 0.0
+ while True:
+ u = t / t_st
+ t += float(r.exponential(1.0 / (p['crackle_rate'] * (0.25 + 0.75 * u ** 1.5))))
+ if t >= t_st:
+ break
+ m = dsp.n_of(r.uniform(0.0015, 0.006))
+ gr = r.standard_normal(m) * np.hanning(m)
+ i = dsp.n_of(t)
+ mm = min(m, n - i)
+ cr[i:i + mm, c] += gr[:mm] * 10 ** ((18 * np.log10(r.uniform(0.05, 1.0)) + 6 * u) / 20)
+ cr = dsp.butter(cr, 'high', p['crackle_hp'], 2)
+ y += cr / (np.abs(cr).max() + 1e-12) * pk * 10 ** (p['crackle_db'] / 20)
+ y = dsp.butter(y, 'low', 18500.0, 6)
+ y[:2] = 0.0
+ return dsp.fade(y, 0.0005, 0.003) / (np.abs(y).max() + 1e-12) * 0.89
+
+
+def recipe_for(cat='glitch', preset=0):
+ fam = FAMILIES[cat]
+ i = preset if isinstance(preset, int) else [nm for nm, _ in fam].index(preset)
+ return types.SimpleNamespace(__name__=__name__, SPACE=dict(SPACE), DEFAULTS=dict(fam[i][1]), render=render,
+ TARGET=TARGETS[cat], ALTS=ALTS, REFSET=REFSET, PRESET=fam[i][0])
diff --git a/earshot/forge/recipes/cuthit.py b/earshot/forge/recipes/cuthit.py
new file mode 100644
index 0000000..d1125d5
--- /dev/null
+++ b/earshot/forge/recipes/cuthit.py
@@ -0,0 +1,289 @@
+"""A short cut hit: the sub hit with a kick that music-led films put on a cut, and its punchy mid sibling; every sample
+is computed.
+
+What the reference clips do (a private licensed set, 'sub_drop' / 'impact', medians
+with the interquartile range; the film clips are local study material and are not shipped):
+ * the sub drop of the voice-over and music films is SHORT: 0.26 s (0.11-0.59) long, its loudest point 61 ms (37-137)
+ after the onset, -20 dB 116 ms (67-145) after that, the sub itself at 57-155 Hz, mono (L/R correlation 0.96). It is
+ usually laid with a kick ('sub-bass drop + kick', 12 pairs within 60 ms of each other): the beater lifts the
+ centroid to 435 Hz (149-598) and only 45 % (25-86 %) of the energy stays under 150 Hz. earshot 0.3's sub drops
+ were 1-1.5 s blooms at 54-83 Hz: faded to 0.3 s they stayed 5-7x darker than the films';
+ * the music films' impact is a short punchy hit: 0.28 s, centroid 306 Hz, 64 % under 150 Hz, peak 52 ms in;
+ * the effects-led film's designed hits are longer and wide: a kick on a sub drop that ends in a granular rumble
+ (L/R correlation about 0), or a fast sub hit under a sustained 5-10 kHz air band.
+Layers (each normalised to its own peak, then mixed at its level re the sub):
+ sub a sine falling sub_f0 -> sub_f1 (time constant sub_glide), a raised-cosine bloom of sub_attack to its peak,
+ then straight in dB to -20 dB in sub_t20 s; tanh saturation (sub_drive) adds the 2nd / 3rd harmonics small
+ speakers need; sub_phase turns the right channel up to 90 degrees (a designed wide sub: correlation
+ cos(phase))
+ kick a sine sweeping kick_f0 -> kick_f1 in kick_tau with its own decay kick_decay (the drum under the sub)
+ click the beater: click_ms of band noise around click_f with a (1 - t / len)^3 envelope, plus a 3 ms ping
+ punch a low-mid noise band at punch_f decaying in punch_decay: the smack that puts a punchy hit at ~300 Hz
+ rumble Hann grains (25-60 ms) of low brown noise, grain_rate per second slowing to half, falling to -20 dB over
+ rumble_t20; each grain ticks softly through 0.8-5 kHz (grain_tick) and can carry a broadband click
+ (crackle: the effects-led film's crackling hit tails); a faint low bed fills the gaps; independent per
+ channel
+ air high-passed noise from air_f, a 5 ms rise and a decay of air_len, independent per channel
+ space width decorrelates everything above 150 Hz (the sub keeps its own phase), a short dark room on click + punch
+The file ends at `length` with a raised-cosine fade of `fade` s: a sub must never stop audibly.
+
+Character parameters (each family member is one corner): weight (sub_f0 / sub_f1, sub_t20, length), punch (kick,
+click, punch, punch_f), bloom (sub_attack), texture (rumble, air) and width (sub_phase, width).
+"""
+import types
+
+import numpy as np
+
+from .. import dsp
+
+SR = dsp.SR
+TARGET = 'a short deep sub bass hit with a kick drum'
+ALTS = ['an explosion', 'a door slam', 'thunder', 'a low hum']
+REFSET = 'cut_hit'
+
+SPACE = {
+ 'length': (0.12, 1.8), # s, the file (it fades over its last `fade` s)
+ 'fade': (0.004, 0.25, 'log'),
+ 'sub_f0': (50.0, 260.0, 'log'), # sub start pitch (Hz)
+ 'sub_f1': (36.0, 130.0, 'log'), # sub landing pitch (Hz)
+ 'sub_glide': (0.008, 0.4, 'log'), # time constant of the fall (s)
+ 'sub_attack': (0.002, 0.35, 'log'), # bloom to the sub's peak (s)
+ 'sub_t20': (0.03, 0.8, 'log'), # s from the sub's peak to -20 dB (straight in dB)
+ 'sub_drive': (0.0, 3.0), # tanh harmonics
+ 'sub_phase': (0.0, 1.0), # right channel phase, x 90 degrees
+ 'kick': (0.0, 1.5), # kick level re the sub
+ 'kick_f0': (120.0, 700.0, 'log'),
+ 'kick_f1': (40.0, 130.0, 'log'),
+ 'kick_tau': (0.003, 0.06, 'log'),
+ 'kick_decay': (0.015, 0.25, 'log'),
+ 'click': (0.0, 1.0), # beater level re the sub
+ 'click_f': (1200.0, 9000.0, 'log'),
+ 'click_ms': (1.0, 15.0, 'log'),
+ 'punch': (0.0, 1.2), # low-mid smack level re the sub
+ 'punch_f': (140.0, 1000.0, 'log'),
+ 'punch_decay': (0.008, 0.15, 'log'),
+ 'rumble': (0.0, 1.2), # granular low rumble level re the sub
+ 'rumble_t20': (0.1, 1.5, 'log'),
+ 'grain_rate': (12.0, 70.0, 'log'),
+ 'grain_tick': (0.0, 1.0),
+ 'crackle': (0.0, 1.5), # a broadband click (0.5-20 kHz, 1-3 ms) on each rumble grain
+ 'air': (0.0, 1.0), # high air band level re the sub
+ 'air_f': (3000.0, 12000.0, 'log'),
+ 'air_len': (0.03, 0.8, 'log'),
+ 'width': (0.0, 1.0), # decorrelation above 150 Hz (0 = mono)
+ 'room': (0.0, 0.4),
+}
+
+FAMILIES = {
+ # earshot 0.4 phase B: hand-designed corners, then tuned toward each style on the measured features (the films'
+ # category profile and the study's dev-split clips: band balance, envelope, onset, decay, low share, width) and on
+ # CLAP only up to the grade bar (cosine 0.70: no pull past it); every member stays an original (max CLAP cosine to
+ # any study clip 0.79 or less). A slow-blooming member ('bloom', 0.25 s swell) was dropped: it read as a held
+ # tone, not a hit, and it needed a rising sub to fit its one music-bed clip.
+ 'cut_hit': [
+ # the music films' short sub hit: an 808-like sub falling 225 -> 46 Hz under a low punch, -20 dB in ~0.15 s
+ ('sub', {'length': 0.2858, 'fade': 0.1949, 'sub_f0': 224.8, 'sub_f1': 45.69, 'sub_glide': 0.04827,
+ 'sub_attack': 0.01613, 'sub_t20': 0.04364, 'sub_drive': 0.6188, 'sub_phase': 0.0, 'kick': 0.6151,
+ 'kick_f0': 174.9, 'kick_f1': 92.57, 'kick_tau': 0.008307, 'kick_decay': 0.2089, 'click': 0.1667,
+ 'click_f': 1226.0, 'click_ms': 2.506, 'punch': 1.069, 'punch_f': 374.4, 'punch_decay': 0.1464,
+ 'rumble': 0.0, 'rumble_t20': 0.1565, 'grain_rate': 12.92, 'grain_tick': 0.002876, 'crackle': 0.0,
+ 'air': 0.0, 'air_f': 9115.0, 'air_len': 0.03, 'width': 0.3875, 'room': 0.05584}),
+ # the same gesture led by the kick: the beater and a 440 Hz smack lift the centroid (the films' median drop)
+ ('kick', {'length': 1.022, 'fade': 0.0589, 'sub_f0': 176.6, 'sub_f1': 37.04, 'sub_glide': 0.1106,
+ 'sub_attack': 0.007655, 'sub_t20': 0.05602, 'sub_drive': 0.3078, 'sub_phase': 0.0, 'kick': 1.025,
+ 'kick_f0': 363.2, 'kick_f1': 108.2, 'kick_tau': 0.009914, 'kick_decay': 0.03626, 'click': 0.1688,
+ 'click_f': 2440.0, 'click_ms': 5.914, 'punch': 1.077, 'punch_f': 437.1, 'punch_decay': 0.04711,
+ 'rumble': 0.0, 'rumble_t20': 0.1437, 'grain_rate': 29.02, 'grain_tick': 0.0, 'crackle': 0.0,
+ 'air': 0.0, 'air_f': 6018.0, 'air_len': 0.07952, 'width': 0.0, 'room': 0.01595}),
+ # the music films' punchy impact: ~0.3 s, a driven sub and a bright smack, two thirds under 150 Hz
+ ('punch', {'length': 0.2823, 'fade': 0.01307, 'sub_f0': 144.2, 'sub_f1': 47.8, 'sub_glide': 0.06248,
+ 'sub_attack': 0.06125, 'sub_t20': 0.03285, 'sub_drive': 2.878, 'sub_phase': 0.09153,
+ 'kick': 0.6973, 'kick_f0': 284.4, 'kick_f1': 84.94, 'kick_tau': 0.0141, 'kick_decay': 0.04286,
+ 'click': 0.4873, 'click_f': 9000.0, 'click_ms': 5.467, 'punch': 0.9001, 'punch_f': 1000.0,
+ 'punch_decay': 0.07649, 'rumble': 0.0, 'rumble_t20': 0.1443, 'grain_rate': 15.95,
+ 'grain_tick': 0.04938, 'crackle': 0.0, 'air': 0.0, 'air_f': 5858.0, 'air_len': 0.1071,
+ 'width': 0.346, 'room': 0.1467}),
+ # the effects-led film's designed hit: a kick on a slow sub drop that ends in a wide granular rumble
+ ('rumble', {'length': 1.4, 'fade': 0.04147, 'sub_f0': 125.0, 'sub_f1': 40.27, 'sub_glide': 0.15,
+ 'sub_attack': 0.07542, 'sub_t20': 0.09859, 'sub_drive': 0.863, 'sub_phase': 1.0, 'kick': 0.3807,
+ 'kick_f0': 197.6, 'kick_f1': 69.6, 'kick_tau': 0.004458, 'kick_decay': 0.0623, 'click': 0.0,
+ 'click_f': 2568.0, 'click_ms': 2.467, 'punch': 0.03031, 'punch_f': 140.0,
+ 'punch_decay': 0.01199, 'rumble': 1.2, 'rumble_t20': 1.5, 'grain_rate': 21.45,
+ 'grain_tick': 0.6988, 'crackle': 0.0, 'air': 0.3205, 'air_f': 3809.0, 'air_len': 0.166,
+ 'width': 0.6293, 'room': 0.3665}),
+ # a fast sub hit under a crackling granular tail and a sustained bright air band (the effects-led film's
+ # erase hit), wide
+ ('air', {'length': 0.5493, 'fade': 0.2087, 'sub_f0': 203.3, 'sub_f1': 50.96, 'sub_glide': 0.02,
+ 'sub_attack': 0.05396, 'sub_t20': 0.03, 'sub_drive': 3.0, 'sub_phase': 1.0, 'kick': 1.084,
+ 'kick_f0': 193.6, 'kick_f1': 50.09, 'kick_tau': 0.006564, 'kick_decay': 0.03479, 'click': 0.4183,
+ 'click_f': 3710.0, 'click_ms': 1.241, 'punch': 0.1212, 'punch_f': 190.7, 'punch_decay': 0.1313,
+ 'rumble': 0.9522, 'rumble_t20': 0.4372, 'grain_rate': 14.47, 'grain_tick': 0.4375,
+ 'crackle': 0.7462, 'air': 0.824, 'air_f': 10810.0, 'air_len': 0.6526, 'width': 1.0,
+ 'room': 0.4}),
+ ],
+}
+DEFAULTS = dict(FAMILIES['cut_hit'][0][1])
+TARGETS = {'cut_hit': TARGET}
+
+
+def _bloom(t, attack, t20):
+ """raised-cosine rise to 1 over `attack`, then straight in dB: -20 dB every t20 s"""
+ e = np.empty_like(t)
+ s = t < attack
+ e[s] = 0.5 - 0.5 * np.cos(np.pi * t[s] / attack)
+ e[~s] = 10 ** (-(t[~s] - attack) / t20)
+ return e
+
+
+def _peak1(x):
+ return x / (np.abs(x).max() + 1e-12)
+
+
+def _sub(p, t, r):
+ """(left, right) of the falling sub, saturated; the right channel turned by sub_phase x 90 degrees"""
+ f = p['sub_f1'] + (p['sub_f0'] - p['sub_f1']) * np.exp(-t / p['sub_glide'])
+ ph = 2 * np.pi * np.cumsum(f) / SR + r.uniform(0, 2 * np.pi)
+ env = _bloom(t, p['sub_attack'], p['sub_t20'])
+ g = 1.0 + 2.0 * p['sub_drive']
+ out = []
+ for off in (0.0, 0.5 * np.pi * p['sub_phase']):
+ s = np.tanh(g * np.sin(ph + off)) / np.tanh(g)
+ out.append(dsp.butter(s, 'low', 900.0, 2) * env)
+ return out
+
+
+def _kick(p, t, r):
+ f = p['kick_f1'] + (p['kick_f0'] - p['kick_f1']) * np.exp(-t / p['kick_tau'])
+ ph = 2 * np.pi * np.cumsum(f) / SR + r.uniform(-0.2, 0.2)
+ return np.sin(ph) * np.exp(-t / p['kick_decay']) * (1 - np.exp(-t / 0.0004))
+
+
+def _click(p, n, r):
+ L = min(n, max(16, dsp.n_of(p['click_ms'] / 1000)))
+ u = np.arange(L) / L
+ w = dsp.butter(r.standard_normal(L) * (1 - u) ** 3, 'band', (p['click_f'] * 0.5, min(p['click_f'] * 2.2, 19000)),
+ 2)
+ k = min(n, dsp.n_of(0.012))
+ tk = np.arange(k) / SR
+ ping = np.sin(2 * np.pi * p['click_f'] * tk) * np.exp(-tk / 0.003) * (1 - np.exp(-tk / 0.0002))
+ y = np.zeros(n)
+ y[:L] += _peak1(w)
+ y[:k] += 0.5 * ping
+ return _peak1(y)
+
+
+def _punch(p, t, r):
+ f = p['punch_f']
+ w = dsp.butter(r.standard_normal(len(t)), 'band', (f / 1.7, min(f * 1.7, 19000)), 2)
+ return _peak1(w * np.exp(-t / p['punch_decay']) * (1 - np.exp(-t / 0.0008)))
+
+
+def _air(p, t, r):
+ out = []
+ for _ in range(2):
+ w = dsp.butter(r.standard_normal(len(t)), 'high', p['air_f'], 4)
+ w = dsp.butter(w, 'low', min(p['air_f'] * 2.5, 19000), 2)
+ out.append(w * (1 - np.exp(-t / 0.005)) * np.exp(-t / p['air_len']))
+ return out
+
+
+def _rumble(p, n, r):
+ """(left, right): Hann grains of low brown noise, independent per channel, slowing, falling to -20 dB per
+ rumble_t20; each grain carries a soft 0.8-5 kHz tick (grain_tick), a broadband click (crackle), and a faint low bed
+ fills the gaps"""
+ out = []
+ span = n / SR
+ for _ in range(2):
+ y = np.zeros(n)
+ tg = 0.01
+ while tg < span:
+ u = tg / span
+ m = dsp.n_of(r.uniform(0.025, 0.06))
+ g = np.cumsum(r.standard_normal(m))
+ g = dsp.butter(g - g.mean(), 'band', (35.0, 220.0), 2) * np.hanning(m)
+ # level: falling with rumble_t20, a log-normal spread capped at +2.6 dB (a grain standing over the hit reads
+ # as a second attack: the audit's stacked hit)
+ a = 10 ** (-tg / p['rumble_t20']) * np.exp(min(0.35 * r.standard_normal(), 0.3))
+ i = dsp.n_of(tg)
+ mm = min(m, n - i)
+ y[i:i + mm] += a * _peak1(g)[:mm]
+ if p['grain_tick'] > 0.01: # a 2.5 ms rise, a 3 ms decay, 0.8-5 kHz: a grain's tick, not a
+ k = min(dsp.n_of(0.014), n - i) # click (shorter, brighter ticks trip the audit's click detector in
+ if k > 8: # the quiet tail)
+ tk = np.arange(k) / SR
+ tick = dsp.butter(r.standard_normal(k), 'band', (800.0, 5000.0), 2)
+ tick *= np.sin(0.5 * np.pi * np.minimum(tk / 0.0025, 1.0)) ** 2 * np.exp(-tk / 0.003)
+ y[i:i + k] += 0.25 * p['grain_tick'] * a * _peak1(tick)
+ if p.get('crackle', 0.0) > 0.01: # drawn only when used: members without it render as before
+ k = min(dsp.n_of(r.uniform(0.001, 0.003)), n - i)
+ if k > 8:
+ ck = dsp.butter(r.standard_normal(k), 'high', 500.0, 2) * np.hanning(k)
+ y[i:i + k] += p['crackle'] * a * np.exp(0.5 * r.standard_normal()) * _peak1(ck)
+ tg += float(r.exponential(1.0 / (p['grain_rate'] * (1.0 - 0.5 * u))))
+ if p['rumble'] > 0.01: # a faint low bed under the grains: no digital silence in the gaps
+ b = np.cumsum(r.standard_normal(n))
+ b = dsp.butter(b - b.mean(), 'band', (35.0, 220.0), 2)
+ y += 0.06 * _peak1(b) * 10 ** (-np.arange(n) / SR / p['rumble_t20'])
+ out.append(y)
+ return out
+
+
+def render(p, r):
+ p = {**DEFAULTS, **p}
+ n = dsp.n_of(p['length'])
+ t = np.arange(n) / SR
+ # the layers draw their noise in this order whatever their level (crackle and the rumble bed only when they are on),
+ # so a seed is one take
+ subL, subR = _sub(p, t, r)
+ kick = _kick(p, t, r)
+ click = _click(p, n, r)
+ punch = _punch(p, t, r)
+ airL, airR = _air(p, t, r)
+ rumL, rumR = _rumble(p, n, r)
+ top = 0.6 * p['kick'] * kick + 0.5 * p['click'] * click + 0.6 * p['punch'] * punch
+ if p['room'] > 0.01:
+ top = dsp.room(top, r, rt60=0.3, size=0.35, damp=0.7, wet=p['room'])[:n]
+ else:
+ dsp.room_ir(r, 0.3, 0.35, 0.7) # keep the draw order
+ w = p['width']
+ rk = np.sqrt(max(0.0, 1 - w * w)) # right = rk x left + w x independent: correlation ~ rk
+ # width: a delayed copy above 150 Hz on the right (the low end of the top layers stays centred)
+ hiL = dsp.butter(top, 'high', 150.0, 2)
+ lo = top - hiL
+ side = dsp.butter(np.concatenate([np.zeros(dsp.n_of(0.0007)), hiL])[:n], 'high', 150.0, 2)
+ topL, topR = lo + hiL, lo + rk * hiL + w * side
+ rumR = rk * rumL + w * rumR
+ rl = np.abs(np.stack([rumL, rumR])).max() + 1e-12
+ airR = rk * airL + w * airR
+ al = np.abs(np.stack([airL, airR])).max() + 1e-12
+ L = subL + topL + p['rumble'] * 0.7 * rumL / rl + p['air'] * 0.35 * airL / al
+ R = subR + topR + p['rumble'] * 0.7 * rumR / rl + p['air'] * 0.35 * airR / al
+ y = np.stack([L, R], axis=1)
+ y = dsp.butter(y, 'high', 24.0, 2)
+ y = _end(y, -60.0) # no near-silent tail when `length` outlives the decay
+ y = dsp.fade(y, 0.0004, min(p['fade'], 0.9 * len(y) / SR))
+ return y / (np.abs(y).max() + 1e-12) * 0.89
+
+
+def _end(y, end_db):
+ """y cut 30 ms after its 5 ms envelope has fallen end_db under its peak for good (it never comes back up)"""
+ h = dsp.n_of(0.005)
+ m = y.mean(axis=1)
+ k = len(m) // h
+ if k < 4:
+ return y
+ e = 20 * np.log10(np.sqrt((m[:k * h].reshape(k, h) ** 2).mean(1)) + 1e-12)
+ live = np.nonzero(e >= e.max() + end_db)[0]
+ return y[:min(len(y), (int(live[-1]) + 1) * h + dsp.n_of(0.03))]
+
+
+def space_for(cat='cut_hit'):
+ return dict(SPACE)
+
+
+def recipe_for(cat='cut_hit', preset=0):
+ """a recipe object for one family member (index or name), for forge(): see subdrop.recipe_for"""
+ fam = FAMILIES[cat]
+ i = preset if isinstance(preset, int) else [nm for nm, _ in fam].index(preset)
+ return types.SimpleNamespace(__name__=__name__, SPACE=space_for(cat), DEFAULTS=dict(fam[i][1]), render=render,
+ TARGET=TARGETS[cat], ALTS=ALTS, REFSET=REFSET, PRESET=fam[i][0])
diff --git a/earshot/forge/recipes/darkriser.py b/earshot/forge/recipes/darkriser.py
new file mode 100644
index 0000000..6eff142
--- /dev/null
+++ b/earshot/forge/recipes/darkriser.py
@@ -0,0 +1,182 @@
+"""A short dark riser: a build of noise and sub that speeds up through a stutter gate into a cut, with no rising
+synth tone; every sample is computed.
+
+What the reference clips do (a private licensed set, 'riser', 14 events in 8 films;
+the clips are local study material and are not shipped): risers are SHORT and dark: 0.74 s (0.42-1.77), the loudest
+point 248 ms (112-433) after the first moment within 20 dB of it, centroid 458 Hz (374-590), 17 % (10-57 %) of the
+energy under 150 Hz, near mono (L/R correlation 0.94); they end 23 ms before the cut (median) and hand over to a hit,
+falling 20 dB in 91 ms (79-128). The effects-led film's designed build is 1.3 s and sub-heavy (86 % under 150 Hz) with
+crackle and a speeding stutter gate on top. Every earshot 0.3 riser was 6-12x brighter (2.7-5.8 kHz), and the cheap
+riser is a synth tone sweeping up, which this recipe never draws: the build comes from level, a noise band that
+opens, a sub that swells at one pitch, and a gate that accelerates.
+Layers:
+ body pink noise through a low-Q band-pass whose centre opens body_f0 -> body_f1 with the build (Q body_q <= 2: a
+ band of noise, never a tone)
+ sub a sine at sub_f (constant pitch) with a little tanh drive, swelling with the level (sub_db re the body)
+ crackle sparse 3-8 ms grains high-passed at crackle_hp, their density rising to crackle_rate / s, independent per
+ channel (crackle_db re the body)
+ gate from gate_at (share of the length) a raised-cosine gate whose rate accelerates gate_f0 -> gate_f1 into the
+ peak, gate_depth deep, duty `duty`; it opens fully over the last 30 ms so the riser peaks on its end
+ level in dB: -start_db * (1 - t / length)^curve up to the peak at `length`, then a fall of time constant tail_tau
+ (the hand-over), an end fade
+ space width decorrelates the body and crackle above 200 Hz, a short room
+"""
+import types
+
+import numpy as np
+
+from .. import dsp
+
+SR = dsp.SR
+TARGET = 'a short dark riser building into a hit'
+ALTS = ['a jet engine', 'a vacuum cleaner', 'heavy rain on a roof', 'a helicopter']
+REFSET = 'riser'
+
+SPACE = {
+ 'length': (0.3, 1.8), # s to the peak
+ 'start_db': (12.0, 48.0), # the first sample's level below the peak
+ 'curve': (0.5, 3.5, 'log'), # > 1: slow, then accelerating into the peak
+ 'tail_tau': (0.01, 0.12, 'log'), # fall after the peak (time constant, s)
+ 'body_f0': (60.0, 600.0, 'log'), # body band centre at the start
+ 'body_f1': (150.0, 3000.0, 'log'), # and at the peak
+ 'body_q': (0.5, 2.0),
+ 'sub_f': (32.0, 90.0, 'log'),
+ 'sub_db': (-40.0, 12.0),
+ 'sub_drive': (0.0, 2.0),
+ 'crackle_db': (-50.0, -6.0),
+ 'crackle_rate': (20.0, 600.0, 'log'),
+ 'crackle_hp': (1500.0, 9000.0, 'log'),
+ 'gate_at': (0.2, 0.95), # where the stutter starts (share of the length)
+ 'gate_f0': (3.0, 16.0, 'log'), # its rate there (Hz)
+ 'gate_f1': (10.0, 45.0, 'log'), # and at the peak
+ 'gate_depth': (0.0, 1.0),
+ 'duty': (0.25, 0.85),
+ 'width': (0.0, 1.0),
+ 'room': (0.0, 0.4),
+}
+FAMILIES = {
+ # earshot 0.4 phase B: hand-designed corners, then tuned toward each style on the measured features (the music
+ # films' riser profile for dark and snatch; the study's dev-split designed build for build, with its length and
+ # stutter depth held, and its catalog glide left out: that +97 st is a ridge jump from the sub to the crackle, not
+ # a sweep), every take audited
+ 'riser': [
+ # the music films' short dark riser: 0.74 s, ~430 Hz, a fifth of the energy in the sub, a deep late gate
+ ('dark', {'length': 0.74, 'start_db': 41.86, 'curve': 1.378, 'tail_tau': 0.02767, 'body_f0': 148.4,
+ 'body_f1': 502.3, 'body_q': 1.136, 'sub_f': 47.85, 'sub_db': -10.93, 'sub_drive': 0.7114,
+ 'crackle_db': -50.0, 'crackle_rate': 134.9, 'crackle_hp': 3039.0, 'gate_at': 0.7039,
+ 'gate_f0': 7.817, 'gate_f1': 19.91, 'gate_depth': 0.8088, 'duty': 0.3958, 'width': 0.2022,
+ 'room': 0.2256}),
+ # the effects-led film's designed build: 1.2 s, a driven 34 Hz sub under a low body band, loud high crackle
+ # and a stutter gate speeding up from a fifth of the way in
+ ('build', {'length': 1.2, 'start_db': 44.04, 'curve': 0.8445, 'tail_tau': 0.07787, 'body_f0': 94.27,
+ 'body_f1': 150.0, 'body_q': 2.0, 'sub_f': 33.58, 'sub_db': 3.405, 'sub_drive': 1.116,
+ 'crackle_db': -6.0, 'crackle_rate': 112.1, 'crackle_hp': 9000.0, 'gate_at': 0.2,
+ 'gate_f0': 6.657, 'gate_f1': 12.49, 'gate_depth': 0.75, 'duty': 0.5742, 'width': 0.0,
+ 'room': 0.1399}),
+ # a half-second snatch: a steep late build (24 dB, mostly in its last 0.15 s) under a light fast stutter
+ ('snatch', {'length': 0.45, 'start_db': 24.0, 'curve': 3.108, 'tail_tau': 0.02393, 'body_f0': 279.2,
+ 'body_f1': 373.3, 'body_q': 2.0, 'sub_f': 37.65, 'sub_db': -13.57, 'sub_drive': 1.628,
+ 'crackle_db': -22.68, 'crackle_rate': 20.44, 'crackle_hp': 4463.0, 'gate_at': 0.337,
+ 'gate_f0': 7.732, 'gate_f1': 45.0, 'gate_depth': 0.2926, 'duty': 0.3132, 'width': 0.0431,
+ 'room': 0.2851}),
+ ],
+}
+DEFAULTS = dict(FAMILIES['riser'][0][1])
+TARGETS = {'riser': TARGET}
+
+
+def _peak1(x):
+ return x / (np.abs(x).max() + 1e-12)
+
+
+def _pink(n, r):
+ F = np.fft.rfft(r.standard_normal(n))
+ f = np.maximum(np.fft.rfftfreq(n, 1 / SR), 15.0)
+ w = np.fft.irfft(F / np.sqrt(f), n)
+ return w / (w.std() + 1e-12)
+
+
+def level_db(p, t):
+ """the build in dB re the peak (module doc)"""
+ T = p['length']
+ u = np.clip(t / T, 0.0, 1.0)
+ L = -p['start_db'] * (1.0 - u) ** p['curve']
+ late = t > T
+ L[late] = -8.686 * (t[late] - T) / p['tail_tau']
+ return L
+
+
+def gate(p, t):
+ """the accelerating stutter gate (1 = open): rate gate_f0 -> gate_f1 from gate_at to the peak, open over the last
+ 30 ms and after the peak"""
+ T = p['length']
+ t0 = p['gate_at'] * T
+ v = np.clip((t - t0) / max(T - t0, 1e-3), 0.0, 1.0)
+ rate = p['gate_f0'] * (p['gate_f1'] / p['gate_f0']) ** v
+ ph = np.cumsum(np.where(t >= t0, rate, 0.0)) / SR
+ frac = (ph + 0.5 * p['duty']) % 1.0 # starts on an open peak: no step where it begins
+ d = p['duty']
+ on = np.where(frac < d, 0.5 - 0.5 * np.cos(2 * np.pi * np.minimum(frac / d, 1.0)), 0.0)
+ g = 1.0 - p['gate_depth'] * (1.0 - on)
+ g = np.where(t < t0, 1.0, g)
+ k = np.clip((t - (T - 0.03)) / 0.03, 0.0, 1.0) # opens fully into the peak
+ g = g * (1 - k) + k
+ return np.where(t > T, 1.0, g)
+
+
+def render(p, r):
+ p = {**DEFAULTS, **p}
+ T = p['length']
+ n = dsp.n_of(T + p['tail_tau'] * 60.0 / 8.686 + 0.02)
+ t = np.arange(n) / SR
+ a = 10 ** (np.maximum(level_db(p, t), -120.0) / 20)
+ g = gate(p, t)
+ m = np.clip(t / T, 0.0, 1.0)
+ fc = p['body_f0'] * (p['body_f1'] / p['body_f0']) ** (m ** 1.5)
+ bodies = []
+ for _ in range(2):
+ b = dsp.svf(_pink(n, r), fc, p['body_q'], 'bandn')
+ bodies.append(b / (np.sqrt(np.mean(b ** 2)) + 1e-12))
+ ph = 2 * np.pi * p['sub_f'] * t + r.uniform(0, 2 * np.pi)
+ gd = 1.0 + 2.0 * p['sub_drive']
+ sub = np.tanh(gd * np.sin(ph)) / np.tanh(gd) / 0.7
+ crk = []
+ for _ in range(2):
+ c = np.zeros(n)
+ tg = 0.0
+ while True:
+ rate = p['crackle_rate'] * (0.15 + 0.85 * min(1.0, tg / T) ** 1.5)
+ tg += float(r.exponential(1.0 / rate))
+ if tg >= T:
+ break
+ k = dsp.n_of(r.uniform(0.003, 0.008)) # 3-8 ms Hann grains: crackle, not sample clicks
+ i = dsp.n_of(tg)
+ kk = min(k, n - i)
+ grain = r.standard_normal(k) * np.hanning(k) # (noise, then level: the draw order is the take)
+ c[i:i + kk] += grain[:kk] * 10 ** (12 * np.log10(r.uniform(0.05, 1.0)) / 20)
+ c = dsp.butter(c, 'high', p['crackle_hp'], 2)
+ crk.append(c / (np.sqrt(np.mean(c ** 2)) + 1e-12) * 0.25)
+ w = p['width']
+ kw = np.sqrt(max(0.0, 1 - w * w))
+ hiR = dsp.butter(bodies[1], 'high', 200.0, 2)
+ bR = (bodies[0] - dsp.butter(bodies[0], 'high', 200.0, 2)) + kw * dsp.butter(bodies[0], 'high', 200.0, 2) + w * hiR
+ out = []
+ for b, c in ((bodies[0], crk[0]), (bR, kw * crk[0] + w * crk[1])):
+ x = b + 10 ** (p['sub_db'] / 20) * sub + 10 ** (p['crackle_db'] / 20) * c / 0.25
+ out.append(x * a * g)
+ y = np.stack(out, axis=1)
+ if p['room'] > 0.01:
+ y = dsp.room(y, r, rt60=0.35, size=0.4, damp=0.6, wet=p['room'])[:n]
+ else:
+ dsp.room_ir(r, 0.35, 0.4, 0.6) # keep the draw order
+ y = dsp.butter(y, 'high', 25.0, 2)
+ y = dsp.butter(y, 'low', 18000.0, 4)
+ y = dsp.fade(y, 0.002, min(0.02, 0.5 * p['tail_tau'] * 60.0 / 8.686))
+ return y / (np.abs(y).max() + 1e-12) * 0.89
+
+
+def recipe_for(cat='riser', preset=0):
+ fam = FAMILIES[cat]
+ i = preset if isinstance(preset, int) else [nm for nm, _ in fam].index(preset)
+ return types.SimpleNamespace(__name__=__name__, SPACE=dict(SPACE), DEFAULTS=dict(fam[i][1]), render=render,
+ TARGET=TARGETS[cat], ALTS=ALTS, REFSET=REFSET, PRESET=fam[i][0])
diff --git a/earshot/forge/recipes/drip.py b/earshot/forge/recipes/drip.py
new file mode 100644
index 0000000..33c918d
--- /dev/null
+++ b/earshot/forge/recipes/drip.py
@@ -0,0 +1,161 @@
+"""A water drop / drip (the 'bloop' of a drop into water), written in code from the physics of a bubble; every sample is
+computed, no recorded audio anywhere.
+
+ from earshot.forge import dsp
+ from earshot.forge.recipes import drip
+ x = drip.render(drip.FAMILY['drip'][0], dsp.rng(1)) # 48 kHz stereo, one drop
+
+What the films' drip is (earshot 0.4 catalog, 29 drops of 9 music-led films standing >= 8 dB clear of the music; 51
+events in 14 films, the very first sound of three of them): 0.19 s (0.11-0.33), 39 ms (16-66) from the first sound to
+the peak, 20 dB down 129 ms (90-188) after it, centroid 596 Hz (379-1045), 10 % under 150 Hz, tonal share 0.55
+(0.48-0.61), near mono (0.95); the catalog's glide (the ridge's last frames vs its first, 43 ms frames) reads 0, yet the
+analysts hear the pitch RISE: it rises within the first tens of ms. No 0.3 bank member is a drip: the pops are 3-5x
+shorter and harder, pro_pop/bloop rises slowly (+6 st over 55-75 ms: the audit's synth-whip tell).
+
+The physics (Minnaert / Longuet-Higgins): a drop hits the surface (a short splash `click`, `click_hz`) and pinches off
+a bubble whose volume breathes at f = 3.26 Hz m / R; as the cavity under the drop closes, the bubble's pitch RISES
+(`rise` semitones, most of it within ~3 `rtau`) and its ring builds (`onset`) and decays (`tau`, damped by radiation
+and heat: Q ~ 10-30). Modelled: a sine on that rising track (`f0` = the pitch at the pinch-off) with a weak 2nd harmonic
+(`h2`, the breathing's nonlinearity, dying `hdec` x faster), the cavity's hiss following the pitch (`breath`, `bq`), a
+smaller daughter bubble (`daughter` dB, `d_ratio` x higher, `d_delay` later), a soft low `thump` of the drop's impact,
+then the finish (hp, lp, a small room `room` / `rt`, a little `width`).
+The rise is the design: by default it completes within ~40 ms (rtau <= 12 ms), where the model-free audit's
+rising-glide check (a climb of more than 4 st over at least 50 ms: earshot.forge.sfx) stays quiet. A slower bubble
+(a big drop, a 'bloop') climbs 6-12 st over 50-100 ms and trips it, although nothing about it is a synth whip: the
+audit allowance (allows(), check()) accepts a climb a bubble can make (at most RISE_MAX_ST semitones, starting within
+the first RISE_START_S and done within RISE_MAX_S) and keeps flagging anything longer or larger. sfx.check applies it
+to the drip category (earshot 0.4): 'bloop' is the one member whose climb (~5 st over 0.1-0.15 s) needs it, the others
+rise within the audit's 50 ms window.
+CHARACTER keys: f0, rise, daughter; FAMILY['drip'] = the palette (FAMILY_NAMES): drop, bubble, plink, bloop, tiny.
+"""
+import numpy as np
+
+from .. import dsp
+from . import _tonal as T
+
+SR = dsp.SR
+TARGET = 'a water drop falling into water, a drip'
+ALTS = ['a bubble pop', 'a mouse click', 'a wooden knock', 'a synth beep', 'a finger snap']
+STUDY = {'dur_s': (0.11, 0.33, 0.08), 'attack_ms': (16.0, 66.0, 15.0), 't20_ms': (90.0, 188.0, 30.0),
+ 'centroid_hz': (379.0, 1045.0, 200.0), 'lo150': (0.02, 0.25, 0.1), 'tonal': (0.48, 0.61, 0.1),
+ 'corr': (0.87, 0.99, 0.1)}
+RISES = True # the pitch rises by design (a drip): the audit's rising-glide check needs an allowance for it
+RISE_MAX_ST = 14.0 # the audit allowance (module doc): the largest climb a bubble makes (SPACE rise + its jitter) ...
+RISE_MAX_S = 0.25 # ... done within this long (rising_glide's from_s -> to_s: its exponential approach creeps) ...
+RISE_START_S = 0.06 # ... starting this early (the climb is the pinch-off, at the onset, never a late sweep)
+
+SPACE = {
+ 'f0': (250.0, 1600.0, 'log'), # the bubble's pitch at pinch-off
+ 'rise': (0.0, 14.0), # semitones it rises as the cavity closes
+ 'rtau': (0.003, 0.03, 'log'), # how fast (most of the rise within ~3 rtau)
+ 'onset': (0.001, 0.06, 'log'), # the ring builds up
+ 'curve': (0.6, 2.5),
+ 'tau': (0.015, 0.12, 'log'), # its decay (20 dB in 2.3 tau)
+ 'h2': (0.0, 0.6), # the breathing's 2nd harmonic
+ 'hdec': (1.0, 3.0),
+ 'breath': (-60.0, -2.0), # cavity hiss following the pitch, dB re the ring
+ 'bq': (1.0, 8.0, 'log'),
+ 'daughter': (-60.0, -3.0), # a smaller bubble (-60 = none)
+ 'd_ratio': (1.3, 2.6),
+ 'd_delay': (0.004, 0.04),
+ 'click': (-60.0, -6.0), # the drop hitting the surface
+ 'click_hz': (800.0, 8000.0, 'log'),
+ 'click_ms': (0.2, 3.0, 'log'),
+ 'thump': (-60.0, -6.0), # the impact's low thump
+ 'thump_f': (70.0, 220.0, 'log'),
+ 'hp': (60.0, 300.0, 'log'),
+ 'lp': (2500.0, 14000.0, 'log'),
+ 'room': (0.0, 0.35),
+ 'rt': (0.06, 0.5, 'log'),
+ 'width': (0.0, 0.8),
+ 'jit': (0.0, 1.0), # take-to-take variation (pitch +-3 %, rise +-10 %, decay +-8 % at 1)
+}
+DEFAULTS = {'f0': 520.0, 'rise': 6.0, 'rtau': 0.008, 'onset': 0.02, 'curve': 1.0, 'tau': 0.05, 'h2': 0.25,
+ 'hdec': 1.6, 'breath': -10.0, 'bq': 3.0, 'daughter': -60.0, 'd_ratio': 1.8, 'd_delay': 0.012,
+ 'click': -24.0, 'click_hz': 2500.0, 'click_ms': 0.6, 'thump': -20.0, 'thump_f': 120.0, 'hp': 80.0,
+ 'lp': 6000.0, 'room': 0.12, 'rt': 0.18, 'width': 0.15, 'jit': 0.5}
+FINE = ['rtau', 'onset', 'curve', 'tau', 'h2', 'hdec', 'breath', 'bq', 'd_ratio', 'd_delay', 'click', 'click_hz',
+ 'click_ms', 'thump', 'thump_f', 'hp', 'lp', 'room', 'rt', 'width']
+
+
+def _fam(**kw):
+ return {**DEFAULTS, **kw}
+
+
+FAMILY = {'drip': [
+ _fam(f0=306.4, rise=8.033, rtau=0.00719, onset=0.02135, curve=2.192, tau=0.0411, h2=0.09568, hdec=1.765,
+ breath=-22.71, bq=6.109, daughter=-3.0, d_ratio=2.271, d_delay=0.03833, click=-40.83, click_hz=2300.0,
+ click_ms=2.804, thump=-23.28, thump_f=164.8, hp=183.0, lp=10010.0, room=0.2097, rt=0.08963, width=0.164,
+ jit=0.2181), # the films' drop (profile)
+ _fam(f0=254.5, rise=9.767, rtau=0.00977, onset=0.01237, curve=1.123, tau=0.03743, h2=0.1299, hdec=1.755,
+ breath=-26.28, bq=1.0, daughter=-3.0, d_ratio=1.976, d_delay=0.02129, click=-51.96, click_hz=7393.0,
+ click_ms=0.4349, thump=-8.339, thump_f=155.3, hp=148.0, lp=5147.0, room=0.1926, rt=0.1608, width=0.297,
+ jit=0.7479), # a lower bubble with its daughter
+ _fam(f0=694.6, rise=3.332, rtau=0.01, onset=0.03436, curve=0.7727, tau=0.03, h2=0.1039, hdec=2.57, breath=-24.02,
+ bq=1.697, daughter=-8.628, d_ratio=1.607, d_delay=0.04, click=-44.91, click_hz=1378.0, click_ms=0.5007,
+ thump=-39.42, thump_f=121.8, hp=97.33, lp=4560.0, room=0.07537, rt=0.1075, width=0.1842,
+ jit=0.225), # a small high plink
+ _fam(f0=420.0, rise=10.0, rtau=0.025, daughter=-6.0, d_ratio=2.2, d_delay=0.03), # a big drop's slow bloop
+ _fam(f0=1150.0, rise=0.9682, rtau=0.004, onset=0.006, curve=1.296, tau=0.01727, h2=0.3661, breath=-2.0,
+ click=-21.63, click_hz=4898.0, thump=-40.0, hp=200.0, lp=12230.0, room=0.0, rt=0.12, width=0.2436,
+ jit=0.3), # a tiny fast droplet
+]}
+FAMILY_NAMES = {'drip': ['drop', 'bubble', 'plink', 'bloop', 'tiny']}
+# How they were found (the earshot 0.4 study; local, not shipped): random + local searches on the reference drip
+# profile (no dev clean clip exists: the one clean drip is held out), the audit run on the best. 'drop' d 0.36 (5 of 7
+# inside the IQRs), 'bubble' 0.34 (6 of 7), 'plink' 0.58 (4 of 7: higher and purer than the typical drop, on purpose).
+# The cavity's hiss (breath -22..-26 dB) keeps the tail from reading as a comb ring. Added for the 0.4 bank (a
+# model-free search from a hand-set corner toward a designed aim, every candidate's takes audited): 'bloop', the slow
+# bubble whose climb (~5 st over 0.1-0.15 s) only the drip allowance accepts, and 'tiny', a 1.15 kHz droplet of 0.1 s.
+
+
+def family_space(params):
+ return T.family_space(SPACE, {**DEFAULTS, **params}, FINE)
+
+
+def _bubble(p, r, n, f0, tau, rise):
+ t = dsp.t_of(n)
+ e = T.env(t, p['onset'], tau, 0.0, p['curve'])
+ f = T.rise_track(t, f0, rise, p['rtau'])
+ y = T.tone(f, r, [(2.0, p['h2'], p['hdec'])], e)
+ if p['breath'] > -59:
+ y = y + 10 ** (p['breath'] / 20) * T.follow_noise(n, r, f, p['bq'], e)
+ return y
+
+
+def render(p, r):
+ p = {**DEFAULTS, **p}
+ j = p['jit'] * r.standard_normal(3) # every drop is a slightly different bubble
+ p = {**p, 'f0': p['f0'] * np.exp(0.03 * j[0]), 'rise': p['rise'] * np.exp(0.1 * j[1]),
+ 'tau': p['tau'] * np.exp(0.08 * j[2])}
+ dau = p['daughter'] > -59
+ n = dsp.n_of(min(1.0, p['onset'] + 7.0 * p['tau'] + (p['d_delay'] if dau else 0.0) + 0.02))
+ y = _bubble(p, r, n, p['f0'], p['tau'], p['rise'])
+ if dau: # a smaller bubble pinched off a moment later
+ k = dsp.n_of(p['d_delay'])
+ y[k:] += 10 ** (p['daughter'] / 20) * _bubble(p, r, n - k, p['f0'] * p['d_ratio'], 0.6 * p['tau'],
+ 0.6 * p['rise'])
+ pk = np.abs(y).max() + 1e-12
+ if p['click'] > -59:
+ hz = p['click_hz']
+ y += pk * 10 ** (p['click'] / 20) * T.burst(n, r, hz / 2.0, hz * 2.0, p['click_ms'] / 1000, rise=0.0002)
+ if p['thump'] > -59:
+ y += pk * 10 ** (p['thump'] / 20) * T.thump(n, p['thump_f'], 0.012, rise=0.002)
+ return T.finish(y, r, hp=p['hp'], lp=p['lp'], room_wet=p['room'], rt60=p['rt'], width=p['width'], cut=400.0)
+
+
+# ------------------------------------------------------------------------------------------- the audit allowance
+def allows(glide):
+ """True when a climb measured by earshot.forge.sfx.rising_glide is one a bubble makes (module doc): at most
+ RISE_MAX_ST semitones, from within RISE_START_S of the start, done within RISE_MAX_S"""
+ if not glide or glide.get('from_s') is None:
+ return True
+ return bool(glide['rise_st'] <= RISE_MAX_ST and glide['from_s'] <= RISE_START_S
+ and glide['to_s'] - glide['from_s'] <= RISE_MAX_S)
+
+
+def check(x, role=None, sound=None):
+ """sfx.check for a drip: the audit with the category's allowance (sfx.check applies allows() to the drip
+ category since earshot 0.4: a bubble's climb is a note, a climb no bubble makes stays a warning)"""
+ from .. import sfx
+ return sfx.check(x, category='drip', role=role, sound=sound)
diff --git a/earshot/forge/recipes/knock.py b/earshot/forge/recipes/knock.py
new file mode 100644
index 0000000..330e532
--- /dev/null
+++ b/earshot/forge/recipes/knock.py
@@ -0,0 +1,189 @@
+"""A mid-band wood / plastic knock (a knuckle or a stick on a block, a shell, a desk), written in code; every sample is
+computed, no recorded audio anywhere.
+
+ from earshot.forge import dsp
+ from earshot.forge.recipes import knock
+ x = knock.render(knock.FAMILY['knock'][0], dsp.rng(1)) # 48 kHz stereo, the films' wooden knock
+
+What the films' knock is (earshot 0.4 catalog, 15 knocks of 7 films standing >= 8 dB clear of the music, 28 events in
+15 films: the widest spread of any foley touch): 0.18 s (0.11-0.26), 19 ms (10-28) from the first sound to the peak,
+20 dB down 34 ms (12-131) after it, centroid 661 Hz (422-1327), 10 % under 150 Hz (2-57 %), almost nothing over 4 kHz,
+tonal share 0.47 (0.42-0.55), near mono (0.95); kinds: a wooden block (~660 Hz), a plastic click (2.2-2.5 kHz, the
+collage hops), a tonal wood block (1.2 kHz, 30 ms ring); they lead the cut by ~40 ms. The 0.3 bank has only low knocks
+(tap / pro_tap 130-180 Hz, 4-5x too dark) and a 5.9 kHz bamboo tok (9x too bright).
+
+The model (a struck body, modal synthesis):
+ * the body: a material's mode set (`mat`, MATS: ratios, amplitudes x ratio ** `tilt`, decay multipliers) on the
+ lowest mode `f1`, each mode ringing with tau = `decay` x its multiplier x (f / f1) ** -`slope` (higher modes die
+ first; a negative slope: a hollow shell whose upper modes carry on), tiny per-take detuning (`jitter`), and a
+ strike that stiffens the body for a few ms (`bend`: the pitch starts that fraction high and settles in `bend_ms`;
+ a falling 'tock')
+ * the grain: a dense cloud of 28 weaker modes (`cloud` dB re the main modes, spread log-uniformly from 1.1 x f1 to
+ `cloud_hi` x f1, dying `cloud_dec` x as fast as the body): real wood and plastic have many modes, and without them
+ a few clean sines read as a struck bar (the films' knocks are noisy: tonal share 0.47, the 0.3 candidates 0.97)
+ * the strike: a contact pulse of `contact` s (a knuckle 1-3 ms, a stick 0.3 ms: a longer contact excites the high
+ modes less) with grit, plus the contact noise itself (`noise` dB, centred on `noise_hz`, dying in `noise_ms`)
+ * a second, softer contact `flam` dB before it, `flam_ms` earlier (two knuckles, a 'knock-knock': the films'
+ 10-28 ms to the peak), and / or one after it (`bounce` dB, `bounce_ms` later: a stick or a plastic part bouncing
+ back onto the body)
+ * the low body under it (`body` dB, `body_f`, `body_ms`: a desk or a table, the < 150 Hz share)
+ * the finish (recipes/_tonal.finish): hp, lp, a small room (`room`, `rt`), a little `width`
+CHARACTER keys: mat, f1, bend, body; FAMILY['knock'] = the palette (FAMILY_NAMES): wood, plastic, snap, desk,
+double (each described where it is defined).
+"""
+import numpy as np
+
+from .. import dsp
+from . import _tonal as T
+
+SR = dsp.SR
+TARGET = 'a knock on a wooden block'
+ALTS = ['a door knock', 'a mouse click', 'a hand clap', 'a bubble pop', 'a metal clank']
+STUDY = {'dur_s': (0.11, 0.26, 0.08), 'attack_ms': (10.0, 28.0, 10.0), 't20_ms': (12.0, 131.0, 30.0),
+ 'centroid_hz': (422.0, 1327.0, 300.0), 'lo150': (0.02, 0.57, 0.1), 'tonal': (0.42, 0.55, 0.1),
+ 'corr': (0.94, 0.98, 0.1)}
+
+MATS = { # (ratio, amplitude, decay multiplier): measured-shape sets, the lowest mode = f1
+ 'block': [(1.0, 1.0, 1.0), (1.48, 0.55, 0.6), (2.15, 0.45, 0.45), (3.4, 0.25, 0.3), (4.6, 0.12, 0.2)], # slit block
+ 'shell': [(1.0, 0.7, 1.0), (1.31, 1.0, 0.8), (1.77, 0.8, 0.6), (2.43, 0.6, 0.5), (3.1, 0.4, 0.35),
+ (4.2, 0.25, 0.25), (5.6, 0.15, 0.2)], # plastic case
+ 'tok': [(1.0, 1.0, 1.0), (2.7, 0.15, 0.3), (5.1, 0.05, 0.15)], # temple block
+ 'desk': [(1.0, 1.0, 1.0), (1.9, 0.6, 0.5), (2.8, 0.5, 0.4), (4.4, 0.3, 0.25), (6.3, 0.15, 0.15)], # a table top
+}
+
+SPACE = {
+ 'mat': list(MATS),
+ 'f1': (250.0, 2600.0, 'log'), # the lowest mode
+ 'decay': (0.004, 0.12, 'log'), # its time constant
+ 'slope': (-0.4, 1.4), # higher modes die faster: tau ~ (f / f1) ** -slope
+ 'tilt': (-1.0, 1.0), # mode amplitudes x ratio ** tilt (> 0: the upper modes lead)
+ 'cloud': (-60.0, 6.0), # the dense mode cloud (grain), dB re the main modes (-60 = none)
+ 'cloud_hi': (2.0, 10.0, 'log'), # its top, x f1
+ 'cloud_dec': (0.3, 2.0, 'log'), # its decay re the body's
+ 'jitter': (0.0, 0.02), # per-take mode detuning (fraction)
+ 'bend': (0.0, 4.0), # pitch starts this fraction high (a stiff strike; 1-4: a falling 'tock')
+ 'bend_ms': (1.0, 80.0, 'log'),
+ 'contact': (0.0002, 0.004, 'log'), # contact pulse length (s): longer = softer, darker
+ 'grit': (0.0, 1.0),
+ 'noise': (-60.0, 6.0), # the contact noise, dB re the body's peak
+ 'noise_hz': (300.0, 6000.0, 'log'),
+ 'noise_ms': (0.3, 20.0, 'log'),
+ 'flam': (-60.0, -2.0), # a softer first contact before the main one (-60 = none)
+ 'flam_ms': (4.0, 70.0),
+ 'bounce': (-60.0, -2.0), # a softer contact after the main one (-60 = none)
+ 'bounce_ms': (6.0, 60.0),
+ 'body': (-60.0, 6.0), # the low body under it (desk / table)
+ 'body_f': (50.0, 260.0, 'log'),
+ 'body_ms': (4.0, 60.0, 'log'),
+ 'hp': (40.0, 400.0, 'log'),
+ 'lp': (2500.0, 16000.0, 'log'),
+ 'room': (0.0, 0.3),
+ 'rt': (0.05, 0.4, 'log'),
+ 'width': (0.0, 0.6),
+ 'jit': (0.0, 1.0), # take-to-take variation (pitch +-2 %, decay +-10 %, contact +-15 % at 1)
+}
+DEFAULTS = {'mat': 'block', 'f1': 620.0, 'decay': 0.03, 'slope': 0.6, 'tilt': 0.0, 'cloud': -60.0, 'cloud_hi': 4.0,
+ 'cloud_dec': 0.8, 'jitter': 0.006, 'bend': 0.05, 'bend_ms': 4.0,
+ 'contact': 0.0012, 'grit': 0.4, 'noise': -18.0, 'noise_hz': 1800.0, 'noise_ms': 1.5, 'flam': -60.0,
+ 'flam_ms': 14.0, 'bounce': -60.0, 'bounce_ms': 20.0, 'body': -20.0, 'body_f': 140.0, 'body_ms': 15.0,
+ 'hp': 70.0, 'lp': 8000.0, 'room': 0.08, 'rt': 0.12, 'width': 0.08, 'jit': 0.5}
+FINE = ['decay', 'slope', 'tilt', 'cloud', 'cloud_hi', 'cloud_dec', 'jitter', 'bend_ms', 'contact', 'grit', 'noise',
+ 'noise_hz', 'noise_ms', 'flam', 'flam_ms', 'bounce', 'bounce_ms', 'body_f', 'body_ms', 'hp', 'lp', 'room', 'rt',
+ 'width']
+
+
+def _fam(**kw):
+ return {**DEFAULTS, **kw}
+
+
+FAMILY = {'knock': [
+ _fam(f1=400.0, decay=0.00898, slope=1.4, tilt=0.4048, cloud=-9.5, cloud_hi=6.712, cloud_dec=0.8552, jitter=0.01331,
+ bend=2.919, bend_ms=3.488, contact=0.00076, grit=0.6466, noise=0.01577, noise_hz=300.0, noise_ms=0.3,
+ flam=-42.5, flam_ms=12.92, bounce=-19.75, bounce_ms=44.74, body=-11.36, body_f=102.0, body_ms=4.521, hp=107.2,
+ lp=11210.0, room=0.1648, rt=0.1519, width=0.2037, jit=0.1328), # the films' wooden knock (profile)
+ _fam(f1=589.7, decay=0.0042, slope=1.4, tilt=0.2389, cloud_hi=6.513, cloud_dec=0.5565, jitter=0.00101, bend=3.485,
+ bend_ms=5.989, contact=0.004, grit=0.9598, noise=-29.01, noise_hz=304.7, noise_ms=9.585, flam=-26.35,
+ flam_ms=48.96, bounce=-10.06, bounce_ms=18.4, body=-48.31, body_f=177.7, body_ms=38.28, hp=40.0, lp=3815.0,
+ room=0.03, rt=0.08539, width=0.2528, jit=0.2616), # a plastic click that bounces back
+ _fam(f1=1055.0, decay=0.00446, slope=0.9923, tilt=0.4321, cloud=-53.72, cloud_hi=10.0, cloud_dec=0.4418,
+ jitter=0.01216, bend=4.0, bend_ms=1.017, contact=0.004, grit=1.0, noise=-21.06, noise_hz=1316.0,
+ noise_ms=11.51, flam=-15.46, flam_ms=38.32, bounce=-11.12, bounce_ms=21.61, body=-51.53, body_f=180.6,
+ body_ms=23.32, hp=94.95, lp=5813.0, room=0.03, rt=0.08, width=0.2403, jit=0.2051), # a bright snap
+ _fam(f1=699.2, decay=0.02025, slope=0.552, tilt=0.08284, cloud=-0.8436, cloud_hi=5.867, cloud_dec=0.9966,
+ jitter=0.01775, bend=2.157, bend_ms=71.36, contact=0.00066, grit=0.894, noise=3.033, noise_hz=1279.0,
+ noise_ms=14.94, flam=-20.16, flam_ms=12.09, bounce=-47.54, bounce_ms=16.56, body=4.088, body_f=95.0,
+ body_ms=28.8, lp=4889.0, room=0.09192, rt=0.276, width=0.5584, jit=0.8611), # a knuckle on a desk
+ _fam(mat='tok', f1=537.0, decay=0.005, slope=-0.00403, tilt=0.5245, cloud=-50.47, cloud_hi=3.995, cloud_dec=1.394,
+ jitter=0.01402, bend=1.762, bend_ms=9.208, contact=0.00244, grit=0.6739, noise=-27.15, noise_hz=2665.0,
+ noise_ms=3.251, flam=-2.088, flam_ms=55.14, bounce=-14.68, bounce_ms=28.8, body=-15.67, body_f=179.5,
+ body_ms=4.703, hp=169.2, lp=7249.0, room=0.00579, rt=0.2958, width=0.3936, jit=0.8699), # knock-knock
+]}
+FAMILY_NAMES = {'knock': ['wood', 'plastic', 'snap', 'desk', 'double']}
+# How they were found (the earshot 0.4 study; local, not shipped): random + local searches over
+# SPACE scored on the films' knock profile and the dev clean clips (CLAP in fixed 1.0 s windows + the model-free feature
+# distance). 'wood' sits inside 6-7 of the films' 7 IQRs on every take (profile d 0.34-0.42 over takes: scored over 4
+# takes, since one take's contact pulse can null a mode and fake a rounder knock); 'plastic' and 'snap' are bright
+# plastic hops (2.4-3 kHz, a contact 20 ms after the strike; one fair on each of two dev clips); 'desk' a low
+# knuckle knock with the table under it, 'double' a knock-knock 55 ms apart (its decay cut from 7.9 to 5 ms: a
+# longer pure tok tail read as a comb ring to the audit on 1-4 takes in 60).
+
+
+def family_space(params):
+ return T.family_space(SPACE, {**DEFAULTS, **params}, FINE)
+
+
+def _hit(p, r, n):
+ """one strike of the body (mono, the contact at t = 0)"""
+ f1 = p['f1']
+ fr, am, ta = [], [], []
+ for q, a, dm in MATS[p['mat']]:
+ f = f1 * q
+ if f >= 0.42 * SR:
+ continue
+ fr.append(f)
+ am.append(a * q ** p['tilt'])
+ ta.append(max(0.0008, p['decay'] * dm * q ** -p['slope']))
+ y = T.modes(n, r, fr, am, ta, jitter=p['jitter'], bend=p['bend'], bend_tau=p['bend_ms'] / 1000)
+ if p['cloud'] > -59: # the grain: many weak modes over the main ones
+ rc = np.random.default_rng(r.integers(1 << 31))
+ hi = min(f1 * p['cloud_hi'], 0.4 * SR)
+ fc = np.exp(rc.uniform(np.log(1.1 * f1), np.log(max(hi, 1.2 * f1)), 28))
+ tc = np.maximum(0.0008, p['decay'] * p['cloud_dec'] * (fc / f1) ** -p['slope'])
+ ac = rc.uniform(0.3, 1.0, 28) * (fc / f1) ** (p['tilt'] - 0.5)
+ c = T.modes(n, rc, fc, ac, tc, bend=p['bend'], bend_tau=p['bend_ms'] / 1000)
+ y = y / (np.abs(y).max() + 1e-12) + 10 ** (p['cloud'] / 20) * c / (np.abs(c).max() + 1e-12)
+ y = T.strike(y, r, p['contact'], p['grit'])[:n]
+ y = y / (np.abs(y).max() + 1e-12)
+ if p['noise'] > -59:
+ hz = p['noise_hz']
+ y += 10 ** (p['noise'] / 20) * T.burst(n, r, hz / 2.0, hz * 2.0, p['noise_ms'] / 1000, rise=0.0002)
+ return y
+
+
+def render(p, r):
+ p = {**DEFAULTS, **p}
+ j = p['jit'] * r.standard_normal(3) # every knock lands a little differently
+ p = {**p, 'f1': p['f1'] * np.exp(0.02 * j[0]), 'decay': p['decay'] * np.exp(0.1 * j[1]),
+ 'contact': p['contact'] * np.exp(0.15 * j[2])}
+ flam = p['flam'] > -59
+ lead = p['flam_ms'] / 1000 if flam else 0.0
+ ring = p['decay'] * max(dm * q ** -p['slope'] for q, _, dm in MATS[p['mat']]) # the longest mode (finish trims)
+ if p['cloud'] > -59:
+ ring = max(ring, p['decay'] * p['cloud_dec'] * max(1.1 ** -p['slope'], p['cloud_hi'] ** -p['slope']))
+ bounce = p['bounce'] > -59
+ dur = lead + (p['bounce_ms'] / 1000 if bounce else 0.0) + 7.0 * max(ring, p['body_ms'] / 1000 if p['body'] > -59
+ else 0.0) + 0.02
+ n = dsp.n_of(min(1.0, dur))
+ y = np.zeros(n)
+ k = dsp.n_of(lead) if flam else 0
+ y[k:] += _hit(p, r, n - k)
+ if flam: # a softer first contact (another knuckle)
+ y += 10 ** (p['flam'] / 20) * _hit({**p, 'contact': p['contact'] * 1.5}, r, n)
+ if bounce: # a softer contact after it (a bounce back)
+ kb = k + dsp.n_of(p['bounce_ms'] / 1000)
+ if kb < n - 8:
+ y[kb:] += 10 ** (p['bounce'] / 20) * _hit({**p, 'contact': p['contact'] * 1.3}, r, n - kb)
+ if p['body'] > -59: # the desk / table under the knock
+ tb = T.thump(n - k, p['body_f'] * (1 + 0.03 * r.standard_normal()), p['body_ms'] / 1000, rise=0.001)
+ y[k:] += 10 ** (p['body'] / 20) * tb
+ return T.finish(y, r, hp=p['hp'], lp=p['lp'], room_wet=p['room'], rt60=p['rt'], width=p['width'], cut=500.0)
diff --git a/earshot/forge/recipes/mallet.py b/earshot/forge/recipes/mallet.py
new file mode 100644
index 0000000..bc2978c
--- /dev/null
+++ b/earshot/forge/recipes/mallet.py
@@ -0,0 +1,272 @@
+"""Gated mallet notes (glockenspiel, celesta, metallophone, marimba), a short soft pluck, and a chime-run builder,
+written in code; every sample is computed, no recorded audio anywhere.
+
+ from earshot.forge import dsp
+ from earshot.forge.recipes import mallet
+ x = mallet.render(mallet.FAMILY['mallet'][0], dsp.rng(1)) # one gated glockenspiel note, stereo
+ run = mallet.render_run(mallet.RUNS['chime_run'][1], dsp.rng(1)) # gated notes, panned note by note
+
+What the films' mallet sounds are (earshot 0.4 catalog, music films, high + medium events >= 8 dB clear of the music):
+ * glockenspiel / celesta notes (28 events, 14 films): 0.33 s (0.28-0.44), 25 ms (16-45) to the peak, 20 dB down 129 ms
+ (38-256) after it, centroid 1079 Hz (550-1505), nothing under 150 Hz, tonal 0.62 (0.55-0.68), WIDE: L/R correlation
+ 0.67 (0.33-0.99). The notes are gated: they stop within ~0.35 s, where a free bar rings 1.5-3 s.
+ * short plucks (21 events, 8 films): 0.3 s (0.25-0.35), 49 ms (15-131) to the peak, t20 112 ms (104-150), centroid
+ 359 Hz (335-809), 12 % under 150 Hz, tonal 0.58, mono: a soft low pluck (a muted string, a felt-struck bar).
+ * chime runs (13 events, 11 films): 0.35-1 s of discrete gated notes ~110 ms apart, centroid ~980 Hz.
+The 0.3 kalimba rings 5x too long (1.7-2.7 s), stays mono, and faded to 0.33 s the audit calls it truncated.
+
+The note (style 'note'): a bar's partial set (`bar`, BARS: ratios, amplitudes) on `f0`, each partial decaying with
+tau = `decay` x (ratio) ** -`slope`, a mallet whose hardness (`hard`) sets how strongly it excites the upper partials
+(and how bright its contact noise is: `strike` dB), a slow doublet beat (`beat` Hz: the two bending planes), a soft
+rise (`onset`), and a DAMPER: from `gate` s on, every partial dies with `gate_tau` (a muted bar, a gated sample: the
+note stops in a few tens of ms instead of being faded), and an optional octave double (`oct` dB at `oct_ratio` x the
+pitch: a second bar an octave off, as film scores double a glockenspiel); then the finish: band limits, `width` (a
+decorrelated side) and `pan` (a per-note position), a small room.
+The pluck (style 'pluck'): a string's harmonics (k = 1 .. 12, amplitude k ** -`tilt` shaped by where it is plucked:
+`pos`), the upper ones dying faster (`slope`), a soft finger (`onset`, `contact` low-pass), muted by the same damper,
+plus a body resonance (`body_f`, `body`).
+A run (render_run): `notes` notes `step` s apart on a scale (`scale`, `pattern` up / down / arc, `span` scale steps),
+each a gated note of these params, panned note by note (`spread`), the last one accented (`accent` dB) and allowed to
+ring (`last_gate` x the gate).
+CHARACTER keys: style, bar, f0, gate, pan / spread; FAMILY['mallet'] (glock, pluck, celesta, marimba) /
+RUNS['chime_run'] (flourish, up4) = the palettes; RUN = a recipe object over whole runs (render blocks name
+render_run).
+"""
+import types
+
+import numpy as np
+
+from .. import dsp
+from . import _tonal as T
+
+SR = dsp.SR
+TARGET = 'a short glockenspiel note'
+ALTS = ['a wine glass clink', 'a phone notification', 'a xylophone note', 'a triangle', 'a music box']
+STUDY = {'dur_s': (0.28, 0.44, 0.1), 'attack_ms': (16.0, 45.0, 12.0), 't20_ms': (38.0, 256.0, 60.0),
+ 'centroid_hz': (550.0, 1505.0, 300.0), 'lo150': (0.0, 0.04, 0.05), 'tonal': (0.55, 0.68, 0.1),
+ 'corr': (0.33, 0.99, 0.2)}
+STUDY_PLUCK = {'dur_s': (0.25, 0.35, 0.08), 'attack_ms': (15.0, 131.0, 20.0), 't20_ms': (104.0, 150.0, 30.0),
+ 'centroid_hz': (335.0, 809.0, 100.0), 'lo150': (0.02, 0.17, 0.08), 'tonal': (0.4, 0.62, 0.1),
+ 'corr': (0.95, 0.99, 0.1)}
+
+BARS = { # (ratio, amplitude): free / tuned bars
+ 'glock': [(1.0, 1.0), (2.756, 0.35), (5.404, 0.12), (8.933, 0.05)], # glockenspiel: a free-free steel bar
+ 'celesta': [(1.0, 1.0), (2.0, 0.05), (3.98, 0.22), (6.9, 0.05)], # a steel bar over a resonator
+ 'metal': [(1.0, 1.0), (3.9, 0.25), (9.9, 0.08)], # a tuned metallophone bar (1 : 4 : 10)
+ 'marimba': [(1.0, 1.0), (3.92, 0.3), (9.8, 0.08)], # wood, the same tuning, dies faster
+ 'tine': [(1.0, 1.0), (5.8, 0.12), (6.27, 0.2)], # a clamped tine (music box / kalimba)
+}
+
+SPACE = {
+ 'style': ['note', 'pluck'],
+ 'bar': list(BARS),
+ 'f0': (150.0, 3200.0, 'log'),
+ 'decay': (0.05, 1.6, 'log'), # the fundamental's time constant (before the damper)
+ 'slope': (0.3, 1.6), # upper partials die faster: tau ~ ratio ** -slope
+ 'hard': (0.0, 1.0), # mallet hardness: excites the upper partials, brightens the contact
+ 'strike': (-60.0, -6.0), # the mallet's contact noise, dB re the note
+ 'beat': (0.0, 6.0), # doublet beat (Hz)
+ 'onset': (0.0005, 0.06, 'log'), # the soft rise to the peak
+ 'gate': (0.05, 1.0, 'log'), # the damper engages here (s) ...
+ 'gate_tau': (0.005, 0.08, 'log'), # ... and every partial then dies with this time constant
+ 'tilt': (0.6, 2.5), # pluck: harmonic amplitudes k ** -tilt
+ 'pos': (0.05, 0.5), # pluck: where the string is plucked (fraction of its length)
+ 'contact': (0.0003, 0.01, 'log'), # pluck: the finger's contact (low-passes the pluck)
+ 'body': (-60.0, 0.0), # pluck: a body resonance, dB re the string
+ 'body_f': (90.0, 400.0, 'log'),
+ 'hp': (60.0, 800.0, 'log'),
+ 'lp': (3000.0, 16000.0, 'log'),
+ 'width': (0.0, 1.0),
+ 'pan': (-1.0, 1.0),
+ 'room': (0.0, 0.35),
+ 'rt': (0.1, 0.8, 'log'),
+ 'oct': (-60.0, 0.0), # an octave double (dB re the note; -60 = none) ...
+ 'oct_ratio': [0.5, 2.0], # ... an octave under or over
+ 'jit': (0.0, 1.0), # take-to-take variation (decay +-8 %, gate +-5 %, hardness +-0.04 at 1; the
+} # note itself never moves)
+DEFAULTS = {'style': 'note', 'bar': 'glock', 'f0': 1046.5, 'decay': 0.6, 'slope': 0.9, 'hard': 0.5, 'strike': -26.0,
+ 'beat': 1.2, 'onset': 0.004, 'gate': 0.2, 'gate_tau': 0.03, 'tilt': 1.4, 'pos': 0.18, 'contact': 0.003,
+ 'body': -14.0, 'body_f': 180.0, 'hp': 300.0, 'lp': 12000.0, 'width': 0.5, 'pan': 0.0, 'room': 0.1,
+ 'rt': 0.3, 'oct': -60.0, 'oct_ratio': 0.5, 'jit': 0.5}
+FINE = ['decay', 'slope', 'hard', 'strike', 'beat', 'onset', 'gate', 'gate_tau', 'tilt', 'pos', 'contact', 'body',
+ 'body_f', 'hp', 'lp', 'width', 'room', 'rt', 'oct']
+
+
+def _fam(**kw):
+ return {**DEFAULTS, **kw}
+
+
+FAMILY = {'mallet': [
+ _fam(f0=1274.0, decay=0.5027, slope=0.8703, hard=0.6343, strike=-14.89, beat=4.807, onset=0.00162, gate=0.08478,
+ gate_tau=0.0422, tilt=0.6, pos=0.4314, contact=0.00436, body=-21.52, body_f=360.3, hp=194.3, lp=6499.0,
+ width=0.3488, room=0.2474, rt=0.4467, oct=-2.483, jit=0.4495), # a gated glockenspiel note, doubled
+ _fam(style='pluck', f0=284.2, decay=0.1234, slope=0.3789, hard=0.1259, strike=-49.8, beat=2.786, onset=0.06,
+ gate=0.1256, gate_tau=0.01994, tilt=0.7913, pos=0.07761, contact=0.00563, body=-40.86, body_f=125.1, hp=372.5,
+ lp=4270.0, width=0.08427, room=0.07512, rt=0.6068, jit=0.02373), # a soft low pluck
+ _fam(bar='celesta', f0=784.0, decay=0.7148, slope=0.4249, hard=0.5432, strike=-49.98, beat=1.934, onset=0.00548,
+ gate=0.08034, gate_tau=0.04521, hp=678.6, lp=8593.0, width=0.8211, room=0.1831, rt=0.4,
+ jit=0.4), # a wide celesta note (G5)
+ _fam(bar='marimba', f0=392.0, decay=1.6, slope=0.3, hard=0.45, strike=-16.89, beat=1.747, onset=0.004282,
+ gate=0.06156, hp=120.0, lp=16000.0, width=0.3335, room=0.1626, rt=0.6887,
+ jit=0.4), # a short wooden marimba note (G4)
+]}
+FAMILY_NAMES = {'mallet': ['glock', 'pluck', 'celesta', 'marimba']}
+# How they were found (the earshot 0.4 study; local, not shipped): random + local searches on the music films' profiles.
+# A struck bar alone stays too pure (tonal share 0.8-0.95 where the films' bell notes sit at 0.62) and too bright; the
+# same note doubled an octave under, 2.5 dB down (`oct`), lands all 7 features inside the bell-note IQRs (profile d
+# 0.17-0.32 over takes). 'pluck' is a felt-soft string pluck (profile d 0.34-0.38, 5-6 of 7 inside). Added for the
+# 0.4 bank (a model-free search from a hand-set corner, every candidate's takes audited): 'celesta', a wide G5 note
+# (L/R correlation ~0.5) gated at 80 ms, and 'marimba', a dry wooden G4 note; both purer than the typical bell note.
+
+
+def family_space(params):
+ return T.family_space(SPACE, {**DEFAULTS, **params}, FINE)
+
+
+def _damper(t, gate, gate_tau):
+ """1 until the damper engages at `gate` s, then an exponential stop with gate_tau (multiplied onto each partial's
+ own decay: the note keeps its timbre while it is muted)"""
+ return np.exp(-np.maximum(t - gate, 0) / max(gate_tau, 1e-4))
+
+
+def _vary(p, r):
+ """one take's small differences (decay, damper time, hardness): a played note, never a copy"""
+ j = p['jit'] * r.standard_normal(3)
+ return {**p, 'decay': p['decay'] * np.exp(0.08 * j[0]), 'gate': p['gate'] * np.exp(0.05 * j[1]),
+ 'hard': float(np.clip(p['hard'] + 0.04 * j[2], 0, 1))}
+
+
+def _note(p, r, n, f0):
+ """one struck bar note (mono, the strike at t = 0)"""
+ t = dsp.t_of(n)
+ y = np.zeros(n)
+ damp = _damper(t, p['gate'], p['gate_tau'])
+ for q, a in BARS[p['bar']]:
+ f = f0 * q
+ if f >= 0.42 * SR:
+ continue
+ a = a * q ** (1.5 * (p['hard'] - 0.5)) # a hard mallet lifts the upper partials
+ tau = max(p['decay'] * q ** -p['slope'], 0.003)
+ b = p['beat'] * r.uniform(0.6, 1.4)
+ am = 1 - 0.3 * (0.5 - 0.5 * np.cos(2 * np.pi * b * t)) if b > 0.01 else 1.0
+ y += a * np.exp(-t / tau) * am * np.sin(2 * np.pi * f * t + r.uniform(0, 2 * np.pi))
+ y *= damp
+ rise = 0.5 - 0.5 * np.cos(np.pi * np.clip(t / max(p['onset'], 1e-4), 0, 1))
+ y *= rise
+ pk = np.abs(y).max() + 1e-12
+ if p['strike'] > -59: # the mallet's contact: brighter when hard
+ lo = 800.0 + 3000.0 * p['hard']
+ y += pk * 10 ** (p['strike'] / 20) * T.burst(n, r, lo, min(lo * 4.0, 16000.0), 0.0006 + 0.002 * (1 - p['hard']),
+ rise=max(0.0002, 0.3 * p['onset']))
+ return y
+
+
+def _pluck(p, r, n, f0):
+ """one soft pluck (mono): a string's harmonics shaped by the pluck point, upper ones dying faster, a finger's soft
+ contact, the damper, a body resonance"""
+ t = dsp.t_of(n)
+ y = np.zeros(n)
+ for k in range(1, 13):
+ f = f0 * k * (1 + 0.0004 * k * k) # a little stiffness
+ if f >= 0.4 * SR:
+ break
+ a = k ** -p['tilt'] * abs(np.sin(np.pi * k * p['pos'])) / (1 + (2 * np.pi * f * p['contact'] / 6) ** 2)
+ tau = max(p['decay'] * k ** -p['slope'], 0.004)
+ y += a * np.exp(-t / tau) * np.sin(2 * np.pi * f * t + r.uniform(0, 0.3))
+ y *= _damper(t, p['gate'], p['gate_tau'])
+ y *= 0.5 - 0.5 * np.cos(np.pi * np.clip(t / max(p['onset'], 1e-4), 0, 1))
+ if p['body'] > -59: # the instrument's body, driven by the string
+ bd = dsp.svf(y, p['body_f'], 3.0, 'bandn')
+ y = y + 10 ** (p['body'] / 20) * bd / (np.abs(bd).max() + 1e-12) * np.abs(y).max()
+ return y
+
+
+def _voice(p, r, n, f0):
+ """one note of the style, doubled `oct` dB at `oct_ratio` x its pitch when oct > -59 (a second bar an octave off:
+ the celesta / glockenspiel doubling of film scores; two lines an octave apart bring the tonal share down to the
+ films' ~0.6 without noise)"""
+ fn = _pluck if p['style'] == 'pluck' else _note
+ y = fn(p, r, n, f0)
+ if p['oct'] > -59:
+ y = y + 10 ** (p['oct'] / 20) * fn(p, r, n, f0 * p['oct_ratio'])
+ return y
+
+
+def _len(p):
+ return min(2.0, p['gate'] + 7.0 * p['gate_tau'] + 0.02, max(p['onset'] + 7.0 * p['decay'], 0.06) + 0.02)
+
+
+def render(p, r):
+ p = _vary({**DEFAULTS, **p}, r)
+ n = dsp.n_of(_len(p))
+ y = _voice(p, r, n, p['f0'])
+ return T.finish(y, r, hp=p['hp'], lp=p['lp'], room_wet=p['room'], rt60=p['rt'], width=p['width'], cut=500.0,
+ pan=p['pan'], size=0.3)
+
+
+# ------------------------------------------------------------------------------------------------ the run builder
+SCALES = {'penta': [0, 2, 4, 7, 9], 'major': [0, 2, 4, 5, 7, 9, 11], 'lydian': [0, 2, 4, 6, 7, 9, 11],
+ 'sus': [0, 2, 5, 7, 10]}
+RUN_SPACE = {**SPACE, 'notes': (2, 8, 'int'), 'step': (0.05, 0.18), 'swing': (0.0, 0.3), 'scale': list(SCALES),
+ 'pattern': ['up', 'down', 'arc'], 'span': (1, 3, 'int'), 'spread': (0.0, 1.0), 'accent': (-6.0, 6.0),
+ 'last_gate': (1.0, 4.0), 'ramp': (-6.0, 6.0)}
+RUN_DEFAULTS = {**DEFAULTS, 'notes': 4, 'step': 0.11, 'swing': 0.0, 'scale': 'penta', 'pattern': 'up', 'span': 1,
+ 'spread': 0.6, 'accent': 2.0, 'last_gate': 2.0, 'ramp': 0.0}
+
+
+def run_freqs(p):
+ """the run's note frequencies: `notes` steps of `span` scale degrees from f0 along `pattern`"""
+ sc = SCALES[p['scale']]
+ k = int(p['notes'])
+ idx = [i * int(p['span']) for i in range(k)]
+ if p['pattern'] == 'down':
+ idx = idx[::-1]
+ elif p['pattern'] == 'arc':
+ h = (k + 1) // 2
+ idx = idx[:h] + idx[:k - h][::-1]
+ st = [12 * (i // len(sc)) + sc[i % len(sc)] for i in idx]
+ return [p['f0'] * 2 ** (s / 12) for s in st]
+
+
+def render_run(p, r):
+ """a chime run (module doc): discrete gated notes, panned note by note, the last accented and ringing longer"""
+ p = {**RUN_DEFAULTS, **p}
+ fs = run_freqs(p)
+ k = len(fs)
+ last = {**p, 'gate': p['gate'] * p['last_gate']}
+ times = [i * p['step'] * (1 + (p['swing'] if i % 2 else 0.0)) for i in range(k)]
+ n = dsp.n_of(times[-1] + _len(last) + 0.05)
+ out = np.zeros((n, 2))
+ for i, (f, t0) in enumerate(zip(fs, times)):
+ q = _vary(last if i == k - 1 else p, r)
+ g = 10 ** ((p['ramp'] * (i / max(1, k - 1)) + (p['accent'] if i == k - 1 else 0.0)) / 20)
+ pan = p['pan'] + p['spread'] * (((i % 2) * 2 - 1) * (0.4 + 0.6 * i / max(1, k - 1)))
+ m = dsp.n_of(_len(q))
+ y = _voice(q, r, m, f)
+ st = T.finish(y, r, hp=p['hp'], lp=p['lp'], width=p['width'], cut=500.0, pan=float(np.clip(pan, -1, 1)),
+ end_db=-70.0, fade=0.004)
+ i0 = dsp.n_of(t0)
+ j = min(len(st), n - i0)
+ out[i0:i0 + j] += g * st[:j]
+ out = T.room(out, r, p['room'], p['rt'], size=0.3, width=0.3 + p['width'])
+ out = dsp.trim_tail(out, -60.0, 0.01)
+ kf = min(len(out), dsp.n_of(0.006))
+ out[-kf:] *= (np.cos(np.linspace(0, np.pi / 2, kf)) ** 2)[:, None]
+ return out
+
+
+RUNS = {'chime_run': [
+ dict(RUN_DEFAULTS, f0=802.3, decay=0.06476, slope=0.4859, hard=0.3246, strike=-51.63, beat=2.417, onset=0.00098,
+ gate=0.2162, gate_tau=0.04794, tilt=0.7552, pos=0.3692, contact=0.00257, body=-19.32, body_f=400.0, hp=142.8,
+ lp=3000.0, width=0.01723, room=0.09026, rt=0.2059, jit=0.5908, notes=3, step=0.04412, swing=0.06969,
+ scale='lydian', pattern='arc', span=2, spread=0.1809, accent=-4.474, last_gate=3.365), # a quick flourish
+ dict(RUN_DEFAULTS, f0=1046.5, notes=4, step=0.11, span=2, gate=0.12, gate_tau=0.03), # up in thirds, 110 ms
+]}
+RUN_NAMES = {'chime_run': ['flourish', 'up4']}
+# 'flourish' is the music films' chime run (profile search: 3 gated notes in an arc, 44 ms apart, near mono; profile d
+# 0.50 with all 7 features inside the IQRs); 'up4' a plain run, notes ~110 ms apart (the reference runs' spacing),
+# a skip of two scale degrees per note: steps of 2-3 semitones read as one rising glide to the audit.
+# a recipe object for forge() / palette() over whole runs (as pop.V2): its render blocks name render_run
+RUN = types.SimpleNamespace(__name__='earshot.forge.recipes.mallet', SPACE=RUN_SPACE, DEFAULTS=RUN_DEFAULTS,
+ render=render_run, TARGET='a quick run of chime notes',
+ ALTS=['a music box melody', 'a harp glissando', 'a phone ringtone', 'a xylophone scale'])
diff --git a/earshot/forge/recipes/notify.py b/earshot/forge/recipes/notify.py
index 032c98c..ea0c823 100644
--- a/earshot/forge/recipes/notify.py
+++ b/earshot/forge/recipes/notify.py
@@ -495,11 +495,15 @@ def _end(y, p, n_len, fade=None):
def render(p, r):
p = {**DEFAULTS, **p}
+ if p.get('ring', 1.0) != 1.0: # earshot 0.4: the decay knob (off at 1: no change at all)
+ p = ring_scaled(p)
st = p['style']
- n_len = dsp.n_of(p['length'] if st != 'bell' else max(p['length'], 0.5))
+ n_len = dsp.n_of(p['length'] if st != 'bell' else (p['bell_len'] or max(p['length'], 0.5)))
n = n_len + dsp.n_of(0.05)
if st == 'bell':
y = _bell(p, r, n)
+ if p.get('soft', 0.0) > 0:
+ y = _soft(y, p['soft'])
y = _finish(y, p, r, n_len)
y = fx.decorrelate(y, p['width'] * 0.5, cut=600.0)
if p['room'] > 0:
@@ -509,7 +513,10 @@ def render(p, r):
return _end(y, p, n_len, fade=max(p['fade'], 0.25))
return _end(y, p, n_len, fade=max(p['fade'], 0.4 * n_len / SR))
if st == 'chime': # round 6: a struck material + motif
- y = _finish(_chime(p, r, n), p, r, n_len)
+ y = _chime(p, r, n)
+ if p.get('soft', 0.0) > 0:
+ y = _soft(y, p['soft'])
+ y = _finish(y, p, r, n_len)
y = fx.decorrelate(y, p['width'] * 0.5, cut=1200.0)
if p['verb'] > 0.005:
wet = fx.reverb(y, r, rt60=p['rt60'], size=0.25, predelay=0.006, damp=0.45, wet=1.0, dry=0.0,
@@ -535,6 +542,8 @@ def render(p, r):
wet = fx.reverb(send, r, rt60=p['rt60'], size=0.25, predelay=0.006, damp=0.45, wet=1.0, dry=0.0, stereo=True,
width=0.4 + p['width'])
y = np.concatenate([y, np.zeros((len(wet) - len(y), 2))]) + p['verb'] * wet
+ if p.get('soft', 0.0) > 0:
+ y = _soft(y, p['soft'])
return _end(y, p, n_len)
@@ -671,3 +680,63 @@ FAMILY_NAMES_R6 = {'pro_notify': ['film_ding', 'fm_bell', 'wood', 'ding_dong', '
# NOT delivered (held-out bench, one run at 19:10): variety 0.936 -> 0.814, phrase z 2.16 -> 1.45, margin 0.38 -> -0.03;
# by blind_v2.verdict (no real variety row for pro_notify) that is models 0 up / 2 down, so FAMILY['pro_notify'] stays
# the round-5 family (out/forge_v2/pro_notify/final/); the round-6 palette is in final_r6/ for a swap by ear.
+
+
+# ------------------------------------------------------------------------------------------------ earshot 0.4: decay
+# The decay knob (earshot 0.4). The music films' rounded mid ding rings 0.36 s
+# (0.24-0.5), 20 dB down 116 ms (25-229) after a 36 ms (16-121) onset, at ~690 Hz with a tonal share of 0.6; the 0.3
+# knob pass got notify/m1 / m3 to 600 Hz and 0.36 s only by fading the end of a 2 s ring (dur), so the ring stayed 2.6x
+# too slow, the onset 3.5x too hard and the audit called every such take truncated. Two keys fix that inside the
+# recipe: `ring` scales every decay constant of the style (bell: decay, early_tau, strike_tau; ding / success:
+# hold_tau, ring_tau, body_tau, air_tau, p3_tau; chime: c_tf, c_ts, c_itau), so a note rings DOWN to silence within its
+# file; `soft` (s) is a felt mallet's onset, a raised-cosine rise over the whole note (mallet and tick included).
+# Both are off by default (ring 1, soft 0): every earlier member renders sample for sample. knobs.py aims `ring` at a
+# t20 target (decay=) and `soft` at an attack target (onset=). bell_len (s, 0 = off) replaces the bell style's 0.5 s
+# minimum file length for a short note (the ring must still reach -45 dB inside it: knobs set it from the decay).
+SPACE.update({'ring': (0.1, 4.0, 'log'), 'soft': (0.0, 0.08), 'bell_len': (0.0, 2.6)})
+DEFAULTS.update({'ring': 1.0, 'soft': 0.0, 'bell_len': 0.0})
+RING_KEYS = {'bell': ('decay', 'early_tau', 'strike_tau'),
+ 'ding': ('hold_tau', 'ring_tau', 'body_tau', 'air_tau', 'p3_tau'),
+ 'chime': ('c_tf', 'c_ts', 'c_itau')}
+RING_KEYS['success'] = RING_KEYS['ding']
+
+
+def ring_scaled(p, ring=None):
+ """p with every decay constant of its style multiplied by `ring` (p['ring'] when None): the decay knob"""
+ ring = p.get('ring', 1.0) if ring is None else ring
+ if ring == 1.0:
+ return dict(p)
+ keys = RING_KEYS.get(p.get('style', 'ding'), ())
+ return {**p, **{k: p[k] * ring for k in keys if k in p}}
+
+
+def _soft(y, soft):
+ """a felt mallet: a raised-cosine rise over `soft` s on the whole note"""
+ k = min(len(y), dsp.n_of(soft))
+ if k > 1:
+ w = 0.5 - 0.5 * np.cos(np.linspace(0, np.pi, k))
+ y = np.array(y, np.float64)
+ y[:k] *= w[:, None] if y.ndim == 2 else w
+ return y
+
+
+# The earshot 0.4 mid ding: the music films' rounded counter / success ding. A struck bell (style 'bell')
+# cannot get there: its tonal share stays >= 0.8 and its centroid 1.6x high at every hardness (90 candidates: best
+# profile distance 0.64). A struck tine with its octave-under body (style 'chime', c_sub ~0.3-0.4: two lines an octave
+# apart give the films' tonal share of ~0.6 and pull the centroid to ~640-830 Hz) does, with no drive: the decay knob
+# (knobs.apply(decay=116)) and the onset knob (onset=36) set `ring` and `soft`. Profile distance 0.20 / 0.29, all 7 /
+# 6 of 7 features inside the films' IQRs (the earshot 0.4 study).
+_MID = dict(style='chime', drive=0.0, c_motif='single')
+FAMILY_MID = {'mid_ding': [
+ _fam(**{**_MID, 'f0': 830.61, 'mat': 'tine', 'att': 0.00316, 'detune': 0.9, 'verb': 0.255, 'rt60': 0.358,
+ 'width': 0.313, 'length': 0.425, 'fade': 0.0435, 'hp': 135.6, 'c_fast': 0.623, 'c_tf': 0.0187,
+ 'c_ts': 0.0623, 'c_mallet': -59.0, 'c_hard': 1.0, 'c_bend': 18.8, 'c_sub': 0.45, 'c_index': 1.655,
+ 'c_itau': 0.0097, 'ring': 0.82, 'soft': 0.049}), # a felt-struck tine over its octave
+ _fam(**{**_MID, 'f0': 880.0, 'mat': 'wood', 'att': 0.00814, 'detune': 1.68, 'verb': 0.35, 'rt60': 0.363,
+ 'width': 0.229, 'length': 0.317, 'fade': 0.0613, 'hp': 254.7, 'c_fast': 0.596, 'c_tf': 0.0291,
+ 'c_ts': 0.077, 'c_mallet': -25.3, 'c_hard': 0.058, 'c_bend': 22.9, 'c_sub': 0.45, 'c_index': 4.38,
+ 'c_itau': 0.0064, 'ring': 0.65, 'soft': 0.047}), # a soft wooden bar, a step higher
+# (the two lines an octave apart are near level, so which is the strongest bin flips from take to take: the measured
+# tonal share of one member spans 0.55-0.7 over seeds, its centroid 600-760 Hz; c_sub 0.45 keeps both inside the IQRs)
+]}
+FAMILY_NAMES_MID = {'mid_ding': ['tine', 'wood']}
diff --git a/earshot/forge/recipes/revcymbal.py b/earshot/forge/recipes/revcymbal.py
new file mode 100644
index 0000000..754b873
--- /dev/null
+++ b/earshot/forge/recipes/revcymbal.py
@@ -0,0 +1,184 @@
+"""A reverse cymbal: the bright, wide swell that rises into a cut and stops just after it, and the darker reverse swell
+of the music films; every sample is computed.
+
+What the reference clips do (a private licensed set, 'reverse_swell', 16 events in 10
+films; the clips are local study material and are not shipped): about one per film, at a section change, ~1 s long
+(0.57-1.29), the loudest point 42 ms after the cut (+23..+62). The effects-led film's are reverse CYMBALS: bright
+(centroid 2.8-3.2 kHz, the energy between 1 and 16 kHz), fully decorrelated (L/R correlation 0.08-0.16), a granular
+shimmer running through them, one stopping ~250 ms after it peaks, one ringing out (-20 dB 0.5 s later). The music
+films' are darker and near mono: centroid 556 Hz (310-884), 19 % under 150 Hz, rise 189 ms (76-413) to the loudest
+point, -20 dB 130 ms (68-243) after it. earshot 0.3 had only reverse whooshes (52-463 Hz, near mono).
+
+How it is built. A real reverse cymbal is a struck cymbal's ring played backwards: the partials that ring longest
+(the lower ones) are there first, the fast-dying highs arrive last, and it ends on the strike. Here the swell is built
+directly in that order (no recorded or rendered sound is reversed, so the stop is designed, not a reversed transient):
+ texture a stationary metal: `partials` inharmonic sines spread log-uniformly over `bw` octaves around cym_f
+ (Gaussian weights in log-frequency, each shimmering a little), mixed (`metal`) with noise in the same band;
+ a separate texture per channel, blended by `width` (correlation about sqrt(1 - width^2))
+ level in dB: -swell_db * (1 - t / length)^curve up to the peak (curve > 1: slow, then accelerating into it),
+ then `hold` s easing hold_db down (the plateau after the cut), then straight in dB with time constant
+ tail_tau (a stop or a ring-out); grains: a log-normal flutter at about flut_f (the striations heard in the
+ designed cymbals)
+ colour a low-pass that opens `open` octaves with the level (the highs arrive late), a high-pass at hp, an optional
+ low body (`low_db`: noise 100-450 Hz following the level, the music films' darker swells)
+ space a short smooth reverb (room, rt60), the edit ends at -60 dB with a fade.
+"""
+import types
+
+import numpy as np
+
+from .. import dsp
+from .. import fx
+
+SR = dsp.SR
+TARGET = 'a reverse cymbal swell'
+ALTS = ['a jet engine', 'a wind gust', 'rain', 'a sword being sharpened']
+REFSET = 'reverse_swell'
+
+SPACE = {
+ 'length': (0.3, 2.0), # s from the first sample to the peak
+ 'swell_db': (12.0, 60.0), # how far below the peak it starts
+ 'curve': (0.5, 3.5, 'log'), # shape of the rise in dB (1 = a straight dB ramp, a reversed exponential ring)
+ 'hold': (0.0, 0.45), # s of plateau after the peak
+ 'hold_db': (-12.0, 0.0), # level change across the plateau
+ 'tail_tau': (0.008, 0.6, 'log'), # s, the fall after the plateau (time constant)
+ 'cym_f': (300.0, 7000.0, 'log'), # centre of the metal band
+ 'bw': (1.0, 6.0), # its width (octaves)
+ 'metal': (0.0, 1.0), # partials vs noise
+ 'partials': (12, 160, 'int'),
+ 'shimmer': (0.0, 1.0), # slow random AM of each partial
+ 'open': (0.0, 4.0), # octaves the low-pass opens with the level
+ 'hp': (80.0, 2500.0, 'log'),
+ 'low_db': (-50.0, 0.0), # a low noise body following the level (re the metal)
+ 'flut_depth': (0.0, 1.0),
+ 'flut_f': (6.0, 60.0, 'log'),
+ 'width': (0.0, 1.0),
+ 'room': (0.0, 0.5),
+ 'rt60': (0.2, 2.0, 'log'),
+}
+FAMILIES = {
+ # earshot 0.4 phase B: hand-designed corners, then tuned toward each style on the measured features (the study's
+ # dev-split clips of the effects-led film for the cymbals, the music films' category profile for the dark swell)
+ # and, for the cymbals, on CLAP only up to the grade bar (cosine 0.70: no pull past it)
+ 'reverse_swell': [
+ # the effects-led film's opening cymbal: bright, wide, grainy, a plateau after the peak, then a stop
+ ('cymbal', {'length': 0.5037, 'swell_db': 19.55, 'curve': 1.831, 'hold': 0.22, 'hold_db': -8.039,
+ 'tail_tau': 0.03096, 'cym_f': 2600.0, 'bw': 3.469, 'metal': 0.6317, 'partials': 78,
+ 'shimmer': 0.5093, 'open': 0.0, 'hp': 118.7, 'low_db': -50.0, 'flut_depth': 0.6266,
+ 'flut_f': 18.8, 'width': 0.98, 'room': 0.0, 'rt60': 1.386}),
+ # a cymbal that swells harder and rings out after the peak (-20 dB a quarter second later)
+ ('ring', {'length': 0.808, 'swell_db': 40.86, 'curve': 2.308, 'hold': 0.0, 'hold_db': -2.062,
+ 'tail_tau': 0.1542, 'cym_f': 2070.0, 'bw': 5.575, 'metal': 0.7482, 'partials': 79,
+ 'shimmer': 0.8912, 'open': 3.093, 'hp': 658.9, 'low_db': -50.0, 'flut_depth': 0.4417,
+ 'flut_f': 21.97, 'width': 1.0, 'room': 0.129, 'rt60': 1.209}),
+ # the music films' reverse swell: darker, near mono, a low body under it, a quick fall after the peak
+ ('dark', {'length': 0.5391, 'swell_db': 30.0, 'curve': 0.5, 'hold': 0.03684, 'hold_db': -0.4249,
+ 'tail_tau': 0.03842, 'cym_f': 346.0, 'bw': 3.456, 'metal': 0.259, 'partials': 117,
+ 'shimmer': 0.3166, 'open': 2.554, 'hp': 80.0, 'low_db': 0.0, 'flut_depth': 0.004984,
+ 'flut_f': 28.16, 'width': 0.35, 'room': 0.08302, 'rt60': 0.5783}),
+ # added for the 0.4 bank (a model-free search from a hand-set corner toward a designed aim, takes audited):
+ # a short bright cymbal for a quick cut (0.33 s into the peak, a short plateau, a stop) ...
+ ('short', {'length': 0.33, 'swell_db': 24.0, 'curve': 0.8282, 'hold': 0.08, 'hold_db': -6.0,
+ 'tail_tau': 0.025, 'cym_f': 3200.0, 'bw': 3.2, 'metal': 0.6, 'partials': 70, 'shimmer': 0.04221,
+ 'open': 0.5, 'hp': 300.0, 'low_db': -50.0, 'flut_depth': 0.8351, 'flut_f': 24.0, 'width': 0.95,
+ 'room': 0.05, 'rt60': 0.8}),
+ # ... and a mid-band reverse breath (more noise than metal, half wide) between the dark swell and the cymbals
+ ('breath', {'length': 0.7, 'swell_db': 30.0, 'curve': 1.3, 'hold': 0.094, 'hold_db': 0.0, 'tail_tau': 0.06,
+ 'cym_f': 1200.0, 'bw': 1.499, 'metal': 0.12, 'partials': 60, 'shimmer': 0.3, 'open': 1.5,
+ 'hp': 150.0, 'low_db': -24.0, 'flut_depth': 0.366, 'flut_f': 14.0, 'width': 0.5818,
+ 'room': 0.2272, 'rt60': 0.5846}),
+ ],
+}
+DEFAULTS = dict(FAMILIES['reverse_swell'][0][1])
+TARGETS = {'reverse_swell': TARGET}
+
+
+def _lfnoise(n, fc, r):
+ w = dsp.butter(r.standard_normal(n), 'low', fc, order=2)
+ return w / (w.std() + 1e-12)
+
+
+def level_db(p, t):
+ """the level curve in dB re the peak (module doc) and the peak time"""
+ T, hd = p['length'], p['hold']
+ u = np.clip(t / T, 0.0, 1.0)
+ L = -p['swell_db'] * (1.0 - u) ** p['curve']
+ if hd > 0:
+ s = (t > T) & (t <= T + hd)
+ L[s] = p['hold_db'] * (t[s] - T) / hd
+ late = t > T + hd
+ L[late] = p['hold_db'] - 8.686 * (t[late] - T - hd) / p['tail_tau']
+ return L, T
+
+
+def _texture(p, n, r):
+ """one channel of stationary metal: inharmonic partials + band noise (module doc), unit RMS"""
+ t = np.arange(n) / SR
+ lo = max(60.0, p['cym_f'] / 2 ** (p['bw'] / 2))
+ hi = min(18000.0, p['cym_f'] * 2 ** (p['bw'] / 2))
+ k = int(round(p['partials']))
+ f = np.exp(r.uniform(np.log(lo), np.log(hi), k))
+ sig = max(0.3, p['bw'] / 3.0)
+ a = np.exp(-0.5 * (np.log2(f / p['cym_f']) / sig) ** 2) * r.uniform(0.4, 1.0, k)
+ met = np.zeros(n)
+ sh = _lfnoise(n, 3.0, r)
+ for fi, ai in zip(f, a):
+ am = 1.0 + 0.35 * p['shimmer'] * np.roll(sh, int(r.integers(0, n)))
+ met += ai * am * np.sin(2 * np.pi * fi * t + r.uniform(0, 2 * np.pi))
+ met /= np.sqrt(np.mean(met ** 2)) + 1e-12
+ nz = dsp.butter(r.standard_normal(n), 'band', (lo, hi), 2)
+ nz = dsp.peq(nz, p['cym_f'], 6.0, 1.0)
+ nz /= np.sqrt(np.mean(nz ** 2)) + 1e-12
+ x = p['metal'] * met + (1 - p['metal']) * nz
+ return x / (np.sqrt(np.mean(x ** 2)) + 1e-12), hi
+
+
+def render(p, r):
+ p = {**DEFAULTS, **p}
+ tail = p['length'] + p['hold'] + p['tail_tau'] * 60.0 / 8.686 + 0.02
+ n = dsp.n_of(min(4.0, tail + 0.3 * p['rt60'] * min(1.0, 4 * p['room'])))
+ t = np.arange(n) / SR
+ L, _ = level_db(p, t)
+ a = 10 ** (np.maximum(L, -120.0) / 20)
+ xL, hi = _texture(p, n, r)
+ xR, _ = _texture(p, n, r)
+ lowL = dsp.butter(r.standard_normal(n), 'band', (100.0, 450.0), 2)
+ lowR = dsp.butter(r.standard_normal(n), 'band', (100.0, 450.0), 2)
+ flut = [np.exp(p['flut_depth'] * _lfnoise(n, p['flut_f'], r) - 0.5 * p['flut_depth'] ** 2) for _ in range(2)]
+ w = p['width']
+ k = np.sqrt(max(0.0, 1 - w * w))
+ chans = []
+ for x, lo_, fl in ((xL, lowL, flut[0]), (k * xL + w * xR, k * lowL + w * lowR, k * flut[0] + w * flut[1])):
+ cut = np.clip(hi * 1.3 * 2.0 ** (-p['open'] * (1.0 - a ** 0.5)), 300.0, 20000.0)
+ y = dsp.svf(x, cut, 0.7, 'low')
+ if p['low_db'] > -49.5:
+ y = y + 10 ** (p['low_db'] / 20) * lo_ / (np.sqrt(np.mean(lo_ ** 2)) + 1e-12)
+ chans.append(y * a * fl)
+ y = np.stack(chans, axis=1)
+ y = dsp.butter(y, 'high', p['hp'], order=2)
+ if p['room'] > 0.01:
+ yr = fx.reverb(y, r, rt60=p['rt60'], size=0.5, predelay=0.008, damp=0.4, wet=p['room'], width=1.0,
+ lines=16, stereo=True, tail=max(0.2, p['rt60']))
+ y = yr[:n] if np.isfinite(yr).all() else y
+ y = dsp.butter(y, 'low', 19000, order=4)
+ y = _edit(y, -60.0)
+ return y / (np.abs(y).max() + 1e-12) * 0.89
+
+
+def _edit(y, end_db, fin=0.004, fout=0.02):
+ """a fade in from the first sample, the end where the 5 ms envelope has fallen end_db under its peak, a fade out"""
+ h = dsp.n_of(0.005)
+ m = y.mean(axis=1)
+ k = len(m) // h
+ e = 20 * np.log10(np.sqrt((m[:k * h].reshape(k, h) ** 2).mean(1)) + 1e-12)
+ i = int(np.argmax(e))
+ below = np.nonzero(e[i:] < e[i] + end_db)[0]
+ end = min(len(y), (i + (below[0] if len(below) else k - i)) * h + dsp.n_of(fout))
+ return dsp.fade(y[:end], fin, fout)
+
+
+def recipe_for(cat='reverse_swell', preset=0):
+ fam = FAMILIES[cat]
+ i = preset if isinstance(preset, int) else [nm for nm, _ in fam].index(preset)
+ return types.SimpleNamespace(__name__=__name__, SPACE=dict(SPACE), DEFAULTS=dict(fam[i][1]), render=render,
+ TARGET=TARGETS[cat], ALTS=ALTS, REFSET=REFSET, PRESET=fam[i][0])
diff --git a/earshot/forge/recipes/shutter.py b/earshot/forge/recipes/shutter.py
new file mode 100644
index 0000000..b3cab77
--- /dev/null
+++ b/earshot/forge/recipes/shutter.py
@@ -0,0 +1,143 @@
+"""A camera shutter: a two-stage mechanical click (release, then the curtain / mirror landing), written in code; every
+sample is computed, no recorded audio anywhere.
+
+ from earshot.forge import dsp
+ from earshot.forge.recipes import shutter
+ x = shutter.render(shutter.FAMILY['shutter'][0], dsp.rng(1)) # 48 kHz stereo, one shutter click
+
+What the films' shutter is (earshot 0.4 catalog, 6 shutters of 5 films standing >= 8 dB clear of the music; 21 events
+in 9 films, on snap zooms and whip-cuts, often stacked with a click): 0.19 s (0.16-0.38), 39 ms (16-170) from the
+first sound to the peak (the two stages: the louder one is often the second), 20 dB down 87 ms (20-123) after it,
+centroid 1032 Hz (624-2187), 7 % under 150 Hz, 3 % over 4 kHz, tonal share 0.4 (0.3-0.52): a darker, longer click
+than any 0.3 bank toggle (toggle/off, fit/snap/switch_flip decay 4-7x faster and sit 2-10x brighter).
+
+The mechanism, part by part (a focal-plane shutter, a mirror box):
+ * stage A, the release (`a_db` re stage B): a small latch letting go: a bright contact (band-passed noise around
+ `a_hz`, `a_ms`) over the latch's few modes (`a_modes`: 3 stiff steel modes from a_hz)
+ * the travel (`whirr` dB, `whirr_hz`): the curtain / mirror moving for the `gap` s between the two stages
+ * stage B, the landing (at `gap`): the curtain or mirror slapping its stop: modes of the box from `b_hz` (a plastic /
+ metal body, `b_decay`, darker than A), its contact noise (`b_noise`), the camera body's low thump (`body`,
+ `body_f`), and a short spring rattle after it (`rattle` dB)
+ * the finish (recipes/_tonal.finish): hp, lp, a small room (`room`, `rt`), a little `width`
+CHARACTER keys: gap, a_db, b_hz; FAMILY['shutter'] = the palette (FAMILY_NAMES): dslr, snap, mirror, film, quick.
+"""
+import numpy as np
+
+from .. import dsp
+from . import _tonal as T
+
+SR = dsp.SR
+TARGET = 'a camera shutter click'
+ALTS = ['a door latch', 'a stapler', 'a mouse click', 'a light switch', 'a gun being cocked']
+STUDY = {'dur_s': (0.16, 0.38, 0.08), 'attack_ms': (16.0, 170.0, 20.0), 't20_ms': (20.0, 123.0, 30.0),
+ 'centroid_hz': (624.0, 2187.0, 300.0), 'lo150': (0.01, 0.24, 0.1), 'tonal': (0.3, 0.52, 0.1),
+ 'corr': (0.96, 0.99, 0.1)}
+
+SPACE = {
+ 'gap': (0.015, 0.14, 'log'), # release -> landing
+ 'a_db': (-24.0, 6.0), # stage A re stage B
+ 'a_hz': (1500.0, 9000.0, 'log'),
+ 'a_ms': (0.2, 3.0, 'log'),
+ 'a_modes': (0.0, 1.0), # the latch's modes, re its contact noise
+ 'whirr': (-60.0, -6.0), # the travel between the stages (-60 = none)
+ 'whirr_hz': (600.0, 5000.0, 'log'),
+ 'b_hz': (300.0, 3000.0, 'log'), # stage B: the box's lowest mode
+ 'b_decay': (0.004, 0.08, 'log'),
+ 'b_noise': (-40.0, 0.0), # stage B's contact noise, dB re its modes
+ 'b_noise_hz': (600.0, 6000.0, 'log'),
+ 'b_contact': (0.0002, 0.003, 'log'),
+ 'body': (-60.0, 0.0), # the camera body's low thump
+ 'body_f': (70.0, 300.0, 'log'),
+ 'body_ms': (4.0, 50.0, 'log'),
+ 'rattle': (-60.0, -6.0), # a short spring rattle after B
+ 'rattle_hz': (2000.0, 7000.0, 'log'),
+ 'hp': (60.0, 500.0, 'log'),
+ 'lp': (3000.0, 16000.0, 'log'),
+ 'room': (0.0, 0.3),
+ 'rt': (0.05, 0.4, 'log'),
+ 'width': (0.0, 0.5),
+}
+DEFAULTS = {'gap': 0.045, 'a_db': -6.0, 'a_hz': 3500.0, 'a_ms': 0.8, 'a_modes': 0.5, 'whirr': -30.0,
+ 'whirr_hz': 1800.0, 'b_hz': 900.0, 'b_decay': 0.025, 'b_noise': -10.0, 'b_noise_hz': 2000.0,
+ 'b_contact': 0.0008, 'body': -16.0, 'body_f': 150.0, 'body_ms': 14.0, 'rattle': -30.0,
+ 'rattle_hz': 3500.0, 'hp': 90.0, 'lp': 9000.0, 'room': 0.1, 'rt': 0.14, 'width': 0.06}
+FINE = ['a_db', 'a_hz', 'a_ms', 'a_modes', 'whirr', 'whirr_hz', 'b_decay', 'b_noise', 'b_noise_hz', 'b_contact',
+ 'body', 'body_f', 'body_ms', 'rattle', 'rattle_hz', 'hp', 'lp', 'room', 'rt', 'width']
+
+B_MODES = [(1.0, 1.0, 1.0), (1.62, 0.7, 0.7), (2.31, 0.5, 0.5), (3.17, 0.35, 0.35), (4.4, 0.2, 0.25)]
+A_MODES = [(1.0, 1.0), (1.71, 0.6), (2.63, 0.35)]
+
+
+def _fam(**kw):
+ return {**DEFAULTS, **kw}
+
+
+FAMILY = {'shutter': [
+ _fam(gap=0.0391, a_db=-23.5, a_hz=5537.0, a_ms=0.5005, a_modes=0.3966, whirr=-9.218, whirr_hz=1085.0, b_hz=1433.0,
+ b_decay=0.006, b_noise=-1.243, b_noise_hz=1355.0, b_contact=0.00221, body=-20.61, body_f=238.2, body_ms=19.41,
+ rattle=-26.17, rattle_hz=5575.0, hp=92.91, lp=5091.0, room=0.2557, rt=0.2552, width=0.1069), # a DSLR
+ _fam(gap=0.05821, a_db=-22.88, a_hz=3300.0, a_ms=2.964, a_modes=0.1957, whirr=-15.59, whirr_hz=5000.0, b_hz=2037.0,
+ b_decay=0.004, b_noise=-2.783, b_noise_hz=2530.0, b_contact=0.00031, body=-10.33, body_f=156.8, body_ms=5.495,
+ rattle=-48.36, rattle_hz=2581.0, hp=173.8, lp=9437.0, room=0.01662, rt=0.0526, width=0.234), # a dry snap
+ _fam(gap=0.06462, a_db=-18.51, a_hz=8113.0, a_ms=0.5578, a_modes=0.1115, whirr=-6.0, whirr_hz=688.7, b_hz=1511.0,
+ b_decay=0.00622, b_noise=0.0, b_noise_hz=1468.0, b_contact=0.003, body=-33.33, body_f=300.0, body_ms=22.0,
+ rattle=-26.59, rattle_hz=7000.0, hp=128.8, lp=6009.0, room=0.3, rt=0.374, width=0.09233), # a mirror box
+ _fam(gap=0.095, a_db=-12.29, a_hz=4200.0, a_ms=0.9, whirr=-14.0, whirr_hz=900.0, b_hz=720.0, b_decay=0.01103,
+ b_noise=-7.79, b_noise_hz=600.0, b_contact=0.001728, body=-12.0, body_f=112.7, body_ms=26.32, rattle=-24.0,
+ rattle_hz=4200.0, hp=84.56, lp=6500.0, room=0.3, rt=0.2, width=0.08), # a heavier film camera
+ _fam(gap=0.021, a_db=-4.0, a_hz=3800.0, a_ms=0.2281, a_modes=0.4098, whirr=-40.0, b_hz=1250.0, b_decay=0.008,
+ b_noise=-6.0, b_noise_hz=2200.0, b_contact=0.001477, body=-17.09, body_f=199.6, body_ms=8.0, rattle=-50.0,
+ hp=150.0, room=0.09189, rt=0.2138, width=0.1), # a quick double click
+]}
+FAMILY_NAMES = {'shutter': ['dslr', 'snap', 'mirror', 'film', 'quick']}
+# How they were found (the earshot 0.4 study; local, not shipped): random + local searches on the reference shutter
+# profile and the one dev clean clip, the audit run on the best. 'dslr' sits inside all 7 profile IQRs (d 0.35): a faint
+# latch, 39 ms of travel, the curtain landing on a 1.4 kHz box with its contact noise, in a small room; 'snap' a dry
+# 2 kHz snap-zoom shutter (fair on its dev clip); 'mirror' a slower mirror box (65 ms travel). Added for the 0.4 bank (a
+# model-free search from a hand-set corner, every candidate's takes audited): 'film', a 720 Hz box after 95 ms of
+# travel with the body's thump and a spring rattle; 'quick', release and curtain 21 ms apart, mid-bright and dry.
+
+
+def family_space(params):
+ return T.family_space(SPACE, {**DEFAULTS, **params}, FINE)
+
+
+def render(p, r):
+ p = {**DEFAULTS, **p}
+ gap = p['gap'] * np.exp(0.03 * r.standard_normal()) # each take: the mechanism a little off its last run
+ p = {**p, 'b_hz': p['b_hz'] * np.exp(0.03 * r.standard_normal()),
+ 'a_hz': p['a_hz'] * np.exp(0.03 * r.standard_normal())}
+ tail = 7.0 * max(p['b_decay'], p['body_ms'] / 1000 if p['body'] > -59 else 0.0)
+ n = dsp.n_of(min(1.0, gap + tail + 0.03))
+ y = np.zeros(n)
+ # stage A: the release (a bright latch)
+ ka = dsp.n_of(0.03)
+ a = T.burst(ka, r, p['a_hz'] / 1.8, min(p['a_hz'] * 1.8, 18000.0), p['a_ms'] / 1000, rise=0.0002)
+ if p['a_modes'] > 0.005:
+ am = T.modes(ka, r, [p['a_hz'] * q for q, _ in A_MODES], [g for _, g in A_MODES],
+ [0.004 / q for q, _ in A_MODES], jitter=0.01)
+ a += p['a_modes'] * am / (np.abs(am).max() + 1e-12)
+ a /= np.abs(a).max() + 1e-12
+ # stage B: the landing (the box's modes, struck)
+ kb = n - dsp.n_of(gap)
+ bm = T.modes(kb, r, [p['b_hz'] * q for q, _, _ in B_MODES], [g for _, g, _ in B_MODES],
+ [max(0.0008, p['b_decay'] * d) for _, _, d in B_MODES], jitter=0.01)
+ b = T.strike(bm, r, p['b_contact'], 0.6)[:kb]
+ b /= np.abs(b).max() + 1e-12
+ if p['b_noise'] > -39:
+ hz = p['b_noise_hz']
+ b += 10 ** (p['b_noise'] / 20) * T.burst(kb, r, hz / 2.0, hz * 2.0, 0.001, rise=0.0002)
+ if p['body'] > -59:
+ b += 10 ** (p['body'] / 20) * T.thump(kb, p['body_f'], p['body_ms'] / 1000, rise=0.0008)
+ if p['rattle'] > -59:
+ rr = T.burst(kb, r, p['rattle_hz'] / 1.6, p['rattle_hz'] * 1.6, 0.006, rise=0.002)
+ s = min(kb, dsp.n_of(0.004)) # 4 ms after the slap
+ b += 10 ** (p['rattle'] / 20) * np.concatenate([np.zeros(s), rr[:kb - s]])
+ y[:ka] += 10 ** (p['a_db'] / 20) * a
+ y[n - kb:] += b
+ if p['whirr'] > -59: # the curtain travelling between the stages
+ kw = dsp.n_of(gap)
+ w = dsp.butter(r.standard_normal(kw), 'band', (p['whirr_hz'] / 1.7, p['whirr_hz'] * 1.7), order=2)
+ w *= np.sin(np.pi * np.linspace(0, 1, kw)) ** 0.7
+ y[:kw] += 10 ** (p['whirr'] / 20) * w / (np.abs(w).max() + 1e-12)
+ return T.finish(y, r, hp=p['hp'], lp=p['lp'], room_wet=p['room'], rt60=p['rt'], width=p['width'], cut=600.0)
diff --git a/earshot/forge/recipes/thump.py b/earshot/forge/recipes/thump.py
new file mode 100644
index 0000000..9087d75
--- /dev/null
+++ b/earshot/forge/recipes/thump.py
@@ -0,0 +1,124 @@
+"""A thump-whoosh: the big low whoosh that hits fast and rings out, the music films' scene-change whoosh (forge
+category 'whoosh_big', members on the pass engine of recipes/whoosh.py).
+
+What the reference clips do (a private licensed set, 'whoosh_big', 23 events in 11
+films, medians with the interquartile range; the clips are local study material and are not shipped): 0.69 s
+(0.42-0.84) long, its loudest point 82 ms (57-190) after the onset and within a frame of the cut, then a long low
+tail: -20 dB 475 ms (180-766) after the peak; centroid 336 Hz (176-415) with 80 % of the energy under 150 Hz, mono
+(L/R correlation 0.95). earshot 0.3's big whooshes approach for 0.25-0.6 s and die 3-6x faster after the peak (the
+profile distance stayed 0.99-1.67 whatever the knobs did).
+
+How it is built: the pass engine (`whoosh.render`: one level curve, moving air bands, low weight, sub swell, hiss,
+room, edit) with a short accelerating approach (rise ~0.1 s at rise_k < 1) and a held, convex fall (fall_k > 1:
+the tail stays up, then drops), most of the level in the sub and low bands; plus the THUMP: a low body struck at the
+pass peak (a sine sliding thump_f0 -> thump_f1, decaying in thump_tau, thump_lead s before the peak), which is what
+makes the whoosh land on the cut instead of drifting through it. The thump follows the engine's peak time, so the
+whoosh knobs (dur 'shape', apex: rise / hold / fall) move it with the pass.
+Every sample is computed; no recorded audio is used.
+"""
+import types
+
+import numpy as np
+
+from .. import dsp
+from . import whoosh as _w
+
+SR = dsp.SR
+TARGET = 'a deep low whoosh that lands with a thump'
+ALTS = ['a strong wind', 'a bass drum', 'a car passing', 'thunder']
+REFSET = 'whoosh_big'
+
+THUMP_SPACE = {
+ 'thump_db': (-40.0, 6.0), # the thump's peak re the pass's (-40 or less = off)
+ 'thump_f0': (60.0, 220.0, 'log'),
+ 'thump_f1': (32.0, 90.0, 'log'),
+ 'thump_tau': (0.03, 0.4, 'log'), # its amplitude time constant (s)
+ 'thump_lead': (-0.04, 0.03), # s before (+) or after (-) the pass peak that it strikes
+}
+SPACE = {**_w.SPACE, **THUMP_SPACE}
+THUMP_KEYS = tuple(THUMP_SPACE)
+
+# the base: a short accelerating approach, a held convex fall, sub + low weight, a low air band, a dull hiss
+BASE = {**_w.BIG, **_w.OPTIONAL,
+ 'rise': 0.13, 'rise_k': 0.8, 'hold': 0.01, 'fall': 0.55, 'fall_k': 1.6, 'start_db': -34.0, 'track': 0.7,
+ 'f_peak': 200.0, 'up_oct': 1.0, 'down_oct': 1.6, 'dop_st': 2.0, 'dop_w': 0.06, 'q_air': 1.0,
+ 'lp_ratio': 4.0, 'flut_depth': 0.2, 'flut_f': 10.0, 'low_db': -2.0, 'low_f': 110.0, 'low_smooth': 0.03,
+ 'sub_db': 0.0, 'sub_f': 52.0, 'sub_glide': 0.4, 'sub_drive': 1.0, 'hiss_db': -26.0, 'hiss_hp': 1500.0,
+ 'hiss_open': 0.8, 'hiss_pow': 1.3, 'tone_db': -50.0, 'grain_db': -50.0, 'room_wet': 0.15, 'rt60': 0.7,
+ 'room_damp': 0.45, 'pan': 0.05, 'width': 0.08, 'drive_db': 2.5, 'end_db': -64.0, 'end_fade': 0.08,
+ 'thump_db': -6.0, 'thump_f0': 120.0, 'thump_f1': 50.0, 'thump_tau': 0.12, 'thump_lead': 0.01}
+FAMILIES = {
+ # earshot 0.4 phase B: three hand-designed corners of BASE, each then tuned toward the music films' whoosh_big
+ # profile on the measured features (length, approach, tail, centroid, low share, tonal share, width); the deep and
+ # airy members keep their character keys (f_peak, sub_f / hiss, width) and a fixed thump level while tuning
+ 'whoosh_big': [
+ ('thump', {'sub_db': -14.85, 'lp_ratio': 4.211, 'up_oct': 2.118, 'flut_f': 10.37, 'hiss_hp': 3308.0,
+ 'thump_f1': 70.85, 'sub_drive': 1.462, 'rise_k': 1.266, 'flut_depth': 0.26, 'sub_f': 59.26,
+ 'low_db': -22.24, 'rt60': 0.3, 'sub_glide': 0.8055, 'low_f': 283.6, 'width': 0.4326,
+ 'hiss_db': -15.21, 'track': 0.871, 'down_oct': 1.68}),
+ # deeper and longer: the sub sinks further, the tail rings for ~0.8 s
+ ('thump_deep', {'rise': 0.1401, 'fall': 0.75, 'fall_k': 1.761, 'f_peak': 150.0, 'sub_f': 44.0,
+ 'sub_glide': 0.8703, 'low_f': 241.1, 'hiss_db': -15.95, 'thump_f0': 92.21, 'thump_f1': 41.61,
+ 'thump_tau': 0.1913, 'rt60': 0.8878, 'q_air': 1.343, 'lp_ratio': 1.959, 'sub_db': -20.64,
+ 'sub_drive': 0.9437, 'low_db': -17.48, 'flut_depth': 0.06493, 'width': 0.2907,
+ 'rise_k': 0.8922, 'flut_f': 22.93, 'drive_db': 5.561, 'thump_db': -9.0, 'up_oct': 2.965,
+ 'hiss_hp': 4168.0, 'thump_lead': 1e-05, 'track': 0.9656, 'down_oct': 1.4,
+ 'room_wet': 0.2214}),
+ # airier: more of the moving air band and a brighter hiss over a lighter sub, a little wider
+ ('thump_airy', {'rise': 0.11, 'fall': 0.45, 'f_peak': 320.0, 'q_air': 1.52, 'sub_db': -4.72,
+ 'low_db': -4.037, 'hiss_db': -20.0, 'hiss_hp': 5687.0, 'width': 0.2, 'flut_depth': 0.4371,
+ 'flut_f': 9.589, 'thump_db': -12.0, 'thump_tau': 0.06806, 'drive_db': 6.444, 'low_f': 50.94,
+ 'lp_ratio': 7.464, 'up_oct': 2.596, 'thump_f1': 45.69, 'thump_f0': 115.4, 'track': 0.7214,
+ 'down_oct': 2.257, 'sub_f': 57.99}),
+ ],
+}
+DEFAULTS = dict(BASE)
+TARGETS = {'whoosh_big': TARGET}
+
+
+def preset(name, cat='whoosh_big'):
+ """the full parameter dict of one family member"""
+ return {**BASE, **dict(FAMILIES[cat])[name]}
+
+
+def preset_full(cat, params):
+ return {**BASE, **params}
+
+
+def _thump(p, n, i0, r):
+ """the struck low body from sample i0: a sine sliding thump_f0 -> thump_f1, 0.6 ms rise, decay thump_tau"""
+ y = np.zeros(n)
+ m = n - i0
+ if m <= 16:
+ return y
+ t = np.arange(m) / SR
+ f = p['thump_f1'] + (p['thump_f0'] - p['thump_f1']) * np.exp(-t / 0.025)
+ ph = 2 * np.pi * np.cumsum(f) / SR + r.uniform(-0.3, 0.3)
+ y[i0:] = np.sin(ph) * np.exp(-t / p['thump_tau']) * (1 - np.exp(-t / 0.0006))
+ return y
+
+
+def render(p, r):
+ """the pass engine on BASE + p (whoosh.OPTIONAL keys absent from p are off), plus the thump at the pass peak"""
+ q = {**BASE, **p}
+ x = _w.render({k: v for k, v in q.items() if k not in THUMP_KEYS}, r)
+ _, _, tp, _ = _w.envelope(q)
+ n = len(x)
+ i0 = max(0, min(n - 1, dsp.n_of(max(0.0, tp - q['thump_lead']))))
+ th = _thump(q, n, i0, r) # drawn after the engine: the engine's noise is the same take
+ if q['thump_db'] > -39.5:
+ th = dsp.fade(th, 0.0, min(0.05, 0.5 * n / SR))
+ lvl = np.abs(x).max() + 1e-12
+ x = x + (10 ** (q['thump_db'] / 20) * lvl * th)[:, None]
+ return x / (np.abs(x).max() + 1e-12) * 0.89
+
+
+def recipe(cat='whoosh_big', preset_name='thump'):
+ """a recipe object for forge() around one member: the full pass-engine SPACE plus the thump keys"""
+ ns = types.SimpleNamespace(TARGET=TARGETS[cat], ALTS=ALTS, REFSET=REFSET)
+ ns.__name__ = __name__
+ ns.SPACE = SPACE
+ ns.DEFAULTS = preset(preset_name, cat)
+ ns.render = render
+ ns.PRESET = preset_name
+ return ns
diff --git a/earshot/forge/recipes/ui_pop.py b/earshot/forge/recipes/ui_pop.py
new file mode 100644
index 0000000..7118930
--- /dev/null
+++ b/earshot/forge/recipes/ui_pop.py
@@ -0,0 +1,181 @@
+"""A soft, rounded mid-register UI pop (the films' most used effect), written in code; every sample is computed.
+
+ from earshot.forge import dsp
+ from earshot.forge.recipes import ui_pop
+ x = ui_pop.render(ui_pop.FAMILY['ui_pop'][0], dsp.rng(1)) # 48 kHz stereo, the films' typical pop
+ xs = [ui_pop.render(p, dsp.rng(i)) for i, p in enumerate(ui_pop.FAMILY['ui_pop'])] # the palette
+
+What the films' pop is (earshot 0.4 catalog of a private set of licensed reference clips, 147 pops of 13 music-led
+films standing >= 8 dB clear of the music): 0.16 s long (IQR 0.10-0.24), a SOFT onset of 33 ms (18-62) to the peak,
+20 dB down 81 ms (57-129) after it, centroid 615 Hz (475-830) with almost nothing under 150 Hz (5 %) or over 4 kHz,
+a tonal share of 0.55 (0.48-0.63: a pitched body with air in it, not a pure beep), pitch flat or falling (0 .. -8
+st), mono (corr 0.97); they come in runs ~114 ms apart (4.7 per 10 s, 253 events in 20 films). Every earshot 0.3
+bank pop is 3-5x harder at the onset, 2x faster to decay and purer (tonal 0.82-0.93): the pop / pro_pop recipes model
+a bubble or a designed chirp, not this.
+
+The model, part by part:
+ * body: a sine on a pitch track that starts `bend` semitones above `f0` and settles on it in `ptau` (a membrane or
+ a mouth's cavity relaxing; bend 0 = flat; or with `sweep` > 0 a log-linear fall over `sweep` s, eased by `ease`:
+ the effects-led film's designed chirps), soft 2nd / 3rd partials (`h2`, `h3`) that die `hdec` times faster
+ (rounded, never square), an optional inharmonic second mode (`m2` at `m2r` x f0, dying `m2dec` x faster: a hollow
+ tube or a wooden body under the pop)
+ * envelope: a soft rise over `onset` (a raised cosine, `curve` > 1 starts slower), `hold`, then a real exponential
+ decay (`tau`: 20 dB in 2.3 tau; the file ends where it is 60 dB down, never a fade over a ring)
+ * air: noise through a band-pass that follows the pitch (`breath` dB re the body, `bq`, its envelope ** `bdec`:
+ < 1 lasts longer than the tone), which is what keeps the tonal share at the films' ~0.55; a short broadband
+ breath at the release (`puff`, `puff_hz`, `puff_ms`)
+ * a faint low `thump` (`thump_f`: the films' ~5 % under 150 Hz), an optional lip `click` (`click_hz`)
+ * an optional second, smaller pop (`dbl` dB, `dgap` s later, `dratio` x the pitch)
+ * the finish (recipes/_tonal.finish): high-pass `hp`, low-pass `lp`, a tiny room (`room`, `rt`), a little `width`
+ * `jit`: each take (seed) moves the pitch, decay and onset a little, so a run of pops never clones one sound
+CHARACTER keys (what a palette member is): f0, bend, sweep, m2 / m2r, dbl; the forge tunes the FINE keys per member
+(family_space()). FAMILY['ui_pop'] = the palette (FAMILY_NAMES): 'soft' = the music films' typical pop (DEFAULTS; all
+7 profile features inside the films' IQRs), 'step' the same a step higher falling in, 'boop' a rounder boop falling
+9 st, 'blip' the effects-led film's bright ~890 Hz blip with fully decorrelated channels (width 1.34: L / R corr ~0.1),
+'fall' an eased 7 st fall, 'wide' a wide 620 Hz pop with a lip click. How they were found
+(random + local search on the films' numbers and the dev clips, then earshot forge) is in the earshot 0.4 study
+notes (local, not shipped).
+"""
+import numpy as np
+
+from .. import dsp
+from . import _tonal as T
+
+SR = dsp.SR
+TARGET = 'a soft rounded pop, a small bubble popping in a user interface'
+ALTS = ['a mouse click', 'a water drop', 'a wooden knock', 'a synth beep', 'a finger snap']
+STUDY = {'dur_s': (0.10, 0.24, 0.08), 'attack_ms': (18.0, 62.0, 15.0), 't20_ms': (57.0, 129.0, 30.0),
+ 'centroid_hz': (475.0, 830.0, 200.0), 'lo150': (0.0, 0.14, 0.1), 'tonal': (0.48, 0.63, 0.1),
+ 'corr': (0.93, 1.0, 0.1)} # the reference IQRs: (lo, hi, scale) for _tonal.outside
+
+SPACE = {
+ 'f0': (250.0, 1200.0, 'log'), # the body's landing pitch
+ 'bend': (-3.0, 72.0), # semitones the pitch starts above f0 (> 0 falls into it; 40-72: designed chirp)
+ 'ptau': (0.004, 0.08, 'log'), # how fast it settles (sweep 0) ...
+ 'sweep': (0.0, 0.15), # ... or a log-linear fall over this long (s; the designed chirp of the effects
+ 'ease': (0.4, 2.5), # film: 19 kHz -> 274 Hz in ~0.1 s), eased (> 1 falls fast first)
+ 'onset': (0.004, 0.07, 'log'), # the soft rise to the peak
+ 'curve': (0.6, 2.5), # rise shape (> 1 starts slower)
+ 'hold': (0.0, 0.03),
+ 'tau': (0.004, 0.09, 'log'), # decay time constant (20 dB in 2.3 tau)
+ 'dcurve': (1.0, 2.5), # decay shape: > 1 = damped as it rings (falls faster late: shorter t40)
+ 'h2': (0.0, 0.8), # 2nd / 3rd partials and how much faster they die
+ 'h3': (0.0, 0.5),
+ 'hdec': (1.0, 3.0),
+ 'inh': (0.0, 0.08), # how sharp the 2nd / 3rd sit (x (1 + inh), x (1 + 2 inh)): a body, no oscillator
+ 'm2': (0.0, 0.8), # an inharmonic second mode (tube / wood)
+ 'm2r': (1.4, 4.5),
+ 'm2dec': (1.0, 4.0),
+ 'breath': (-60.0, -2.0), # pitch-following air, dB re the body (-60 = none)
+ 'bq': (1.0, 8.0, 'log'),
+ 'bdec': (0.4, 2.0),
+ 'puff': (-60.0, -6.0), # a broadband breath at the release
+ 'puff_hz': (600.0, 5000.0, 'log'),
+ 'puff_ms': (0.5, 8.0, 'log'),
+ 'thump': (-60.0, -6.0), # a faint low thump (the < 150 Hz share)
+ 'thump_f': (70.0, 200.0, 'log'),
+ 'click': (-60.0, -10.0), # a lip click on the onset
+ 'click_hz': (1500.0, 8000.0, 'log'),
+ 'dbl': (-60.0, 0.0), # a second pop (-60 = none)
+ 'dgap': (0.03, 0.12),
+ 'dratio': (0.6, 1.6),
+ 'hp': (60.0, 300.0, 'log'),
+ 'lp': (2500.0, 12000.0, 'log'),
+ 'room': (0.0, 0.35),
+ 'rt': (0.06, 0.35, 'log'),
+ 'width': (0.0, 1.5), # a decorrelated side above 400 Hz (1.43: L / R correlation ~0)
+ 'jit': (0.0, 1.0), # take-to-take variation (pitch +-2 %, decay +-8 %, onset +-10 % at 1)
+}
+# the films' typical pop (random + local search on the catalog profile, then the forge): a round
+# 370 Hz body with rich soft partials (2nd, 3rd and a near-octave mode at 1.72x: the tonal share lands at ~0.5), a
+# 24 ms soft rise held 15 ms, a damped decay (dcurve 2.1), low-passed at 3.5 kHz, a faint 130 Hz thump, and air that
+# outlasts the tone a little (breath -14 dB, bdec 0.6: without it the tail is three bare partials, which the audit's
+# comb check reads as a metallic ring at the pitch period, z 30-80; with it z 4-7)
+DEFAULTS = {'f0': 370.0, 'bend': 0.7, 'ptau': 0.0075, 'sweep': 0.0, 'ease': 1.0, 'onset': 0.0236, 'curve': 2.45,
+ 'hold': 0.0147, 'tau': 0.041, 'dcurve': 2.12, 'h2': 0.57, 'h3': 0.35, 'hdec': 1.0, 'inh': 0.0, 'm2': 0.66,
+ 'm2r': 1.72,
+ 'm2dec': 1.43, 'breath': -14.0, 'bq': 3.6, 'bdec': 0.6, 'puff': -40.0, 'puff_hz': 4270.0, 'puff_ms': 2.7,
+ 'thump': -15.7, 'thump_f': 129.0, 'click': -60.0, 'click_hz': 3500.0, 'dbl': -60.0, 'dgap': 0.07,
+ 'dratio': 0.8, 'hp': 112.0, 'lp': 3530.0, 'room': 0.15, 'rt': 0.1, 'width': 0.1, 'jit': 0.5}
+FINE = ['ptau', 'ease', 'onset', 'curve', 'hold', 'tau', 'dcurve', 'h2', 'h3', 'hdec', 'inh', 'm2dec', 'breath', 'bq',
+ 'bdec', 'puff', 'puff_hz', 'puff_ms', 'thump', 'thump_f', 'click', 'click_hz', 'hp', 'lp', 'room', 'rt',
+ 'width']
+
+
+def _fam(**kw):
+ return {**DEFAULTS, **kw}
+
+
+FAMILY = {'ui_pop': [
+ _fam(), # the films' typical pop
+ _fam(f0=466.16, bend=3.0, ptau=0.03), # a step up, falling in
+ _fam(f0=357.1, bend=9.0, ptau=0.03, onset=0.025, curve=2.0, hold=0.0062, tau=0.026, dcurve=1.4, h2=0.61,
+ h3=0.17, hdec=1.63, m2=0.79, m2r=3.69, m2dec=2.68, breath=-13.8, bq=7.0, bdec=0.4, puff=-51.0, puff_hz=4600.0,
+ puff_ms=1.9, thump=-8.0, thump_f=76.0, click=-54.0, hp=95.0, lp=12000.0, room=0.115, rt=0.093,
+ width=0.2), # a boop falling 9 st
+ _fam(f0=889.1, bend=-3.0, ptau=0.08, ease=1.576, onset=0.01359, curve=2.5, hold=0.00311, tau=0.01052, dcurve=2.007,
+ h2=0.3, h3=0.09244, hdec=1.107, inh=0.01188, m2=0.2913, m2r=4.115, m2dec=1.032, breath=-21.12, bq=2.26,
+ bdec=1.076, puff=-46.31, puff_hz=4264.0, puff_ms=0.5636, thump=-36.45, thump_f=108.6, click=-45.55,
+ click_hz=4013.0, dbl=-55.33, dgap=0.05156, dratio=0.7141, hp=60.0, lp=12000.0, room=0.0, rt=0.2241,
+ width=1.341, jit=0.6717), # a bright, fully wide blip
+ _fam(f0=345.76, bend=7.36, ptau=0.0058, sweep=0.0894, ease=1.123, onset=0.0177, curve=1.658, hold=0.0006,
+ tau=0.0225, dcurve=2.138, h2=0.671, h3=0.49, hdec=1.424, m2=0.53, m2r=4.5, m2dec=1.0, breath=-8.81, bq=2.61,
+ bdec=1.89, puff=-47.5, puff_hz=5000.0, puff_ms=6.13, thump=-26.1, thump_f=81.0, click=-33.5, click_hz=4083.0,
+ dbl=-29.6, dgap=0.113, dratio=1.155, hp=79.7, lp=11076.0, room=0.0, rt=0.076, width=0.64,
+ jit=0.83), # earshot forge's pick: an eased fall (dry: its room rang)
+ _fam(f0=622.5, bend=-0.9783, ptau=0.08, sweep=0.00291, ease=1.822, onset=0.04115, curve=2.5, hold=0.00244,
+ tau=0.03267, dcurve=1.844, h2=0.5426, h3=0.1129, hdec=1.054, inh=0.02561, m2=0.2683, m2r=4.5, m2dec=1.0,
+ breath=-9.013, bq=3.179, bdec=0.5391, puff=-13.68, puff_hz=5000.0, puff_ms=1.019, thump=-46.85, thump_f=107.4,
+ click=-10.1, click_hz=6070.0, dbl=-47.17, dgap=0.07519, dratio=0.6551, hp=67.89, lp=11620.0, room=0.00401,
+ rt=0.1363, width=0.8105, jit=0.3896), # a wide mid pop with a lip click
+]}
+FAMILY_NAMES = {'ui_pop': ['soft', 'step', 'boop', 'blip', 'fall', 'wide']}
+
+
+def family_space(params):
+ """the search space of one palette member: FINE keys free, the character keys pinned"""
+ return T.family_space(SPACE, {**DEFAULTS, **params}, FINE)
+
+
+def _one(p, r, n, f0, tau, gain=1.0):
+ """one pop of length n (mono, starts at 0): body + air, before the finish"""
+ t = dsp.t_of(n)
+ e = T.env(t, p['onset'], tau, p['hold'], p['curve'], p['dcurve'])
+ if p['sweep'] > 0.001: # a designed chirp: a log-linear fall, eased, then settled
+ u = np.clip(t / p['sweep'], 0, 1)
+ f = f0 * 2 ** (p['bend'] / 12 * (1 - u) ** p['ease'])
+ else:
+ f = T.glide(t, f0, p['bend'], p['ptau'])
+ s = p['inh'] # a cavity's overtones sit a little sharp of harmonic
+ parts = [(2.0 * (1 + s), p['h2'], p['hdec']), (3.0 * (1 + 2 * s), p['h3'], p['hdec'] * 1.5)]
+ if p['m2'] > 0:
+ parts.append((p['m2r'], p['m2'], p['m2dec']))
+ y = T.tone(f, r, parts, e)
+ if p['breath'] > -59:
+ y = y + 10 ** (p['breath'] / 20) * T.follow_noise(n, r, f, p['bq'], e ** p['bdec'])
+ return gain * y
+
+
+def render(p, r):
+ p = {**DEFAULTS, **p}
+ j = p['jit'] * r.standard_normal(3) # each take: a slightly different pop (a run never clones)
+ p = {**p, 'f0': p['f0'] * np.exp(0.02 * j[0]), 'tau': p['tau'] * np.exp(0.08 * j[1]),
+ 'onset': p['onset'] * np.exp(0.1 * j[2])}
+ dbl = p['dbl'] > -59
+ gap = p['dgap'] if dbl else 0.0
+ dur = p['onset'] + p['hold'] + 7.0 * p['tau'] + gap + 0.01
+ n = dsp.n_of(min(0.8, dur))
+ y = _one(p, r, n, p['f0'], p['tau'])
+ if dbl:
+ k = dsp.n_of(gap)
+ y[k:] += _one(p, r, n - k, p['f0'] * p['dratio'], p['tau'] * 0.9, 10 ** (p['dbl'] / 20))
+ pk = np.abs(y).max() + 1e-12
+ if p['puff'] > -59: # a breath at the release, riding the soft rise
+ y += pk * 10 ** (p['puff'] / 20) * T.burst(n, r, p['puff_hz'] / 2.2, p['puff_hz'] * 2.2, p['puff_ms'] / 1000,
+ rise=max(0.0006, 0.3 * p['onset']))
+ if p['thump'] > -59:
+ y += pk * 10 ** (p['thump'] / 20) * T.thump(n, p['thump_f'], max(0.012, 0.6 * p['tau']),
+ rise=max(0.002, 0.5 * p['onset']))
+ if p['click'] > -59:
+ y += pk * 10 ** (p['click'] / 20) * T.burst(n, r, p['click_hz'] / 1.6, p['click_hz'] * 1.6, 0.0008)
+ return T.finish(y, r, hp=p['hp'], lp=p['lp'], room_wet=p['room'], rt60=p['rt'], width=p['width'], cut=400.0)
diff --git a/tests/test_forge_recipes_cut_noise.py b/tests/test_forge_recipes_cut_noise.py
new file mode 100644
index 0000000..661d650
--- /dev/null
+++ b/tests/test_forge_recipes_cut_noise.py
@@ -0,0 +1,192 @@
+"""The earshot 0.4 impact / noise recipes (cuthit, thump, revcymbal, darkriser, brightswish, burstglitch): every family
+member renders deterministic, clean stereo audio from parameters inside its search space, passes the model-free audit
+in its kit role, lands on the character its category measured in the films (short low cut hits, a thump-whoosh with a
+long low tail, a bright wide reverse cymbal that peaks at the end of its swell, a dark riser that never sweeps a tone
+up, bright swishes, a glitch whose first burst is its loudest), and loads no recorded audio."""
+import inspect
+
+import numpy as np
+import pytest
+
+from earshot.forge import dsp, load_recipe, recipes, sfx
+
+SR = 48000
+MODULES = ('cuthit', 'thump', 'revcymbal', 'darkriser', 'brightswish', 'burstglitch')
+# category -> the kit role its takes are audited in (a hit warns on stacked attacks and long pre-swells)
+ROLE = {'cut_hit': 'hit', 'whoosh_big': 'whoosh.long', 'reverse_swell': 'swell', 'riser': 'riser',
+ 'swish': 'whoosh.short', 'whoosh_fast': 'whoosh.short', 'glitch': 'glitch'}
+DROP = {'sub', 'kick', 'bloom'} # cut_hit members meant for the drop role (a bloom is not a hit's pre-swell)
+
+
+def members():
+ for mod in MODULES:
+ m = load_recipe(mod)
+ for cat, fam in m.FAMILIES.items():
+ for name, p in fam:
+ full = m.preset_full(cat, p) if hasattr(m, 'preset_full') else {**m.DEFAULTS, **p}
+ yield mod, cat, name, full
+
+
+MEMBERS = list(members())
+IDS = [f'{c}/{n}' for _, c, n, _ in MEMBERS]
+
+
[email protected](scope='module')
+def takes():
+ return {f'{c}/{n}': np.asarray(load_recipe(mod).render(dict(p), dsp.rng(21)), np.float64)
+ for mod, c, n, p in MEMBERS}
+
+
+def _mono(x):
+ return x.mean(axis=1)
+
+
+def _env_db(x, ms=5.0):
+ m = _mono(x)
+ h = int(SR * ms / 1000)
+ k = len(m) // h
+ e = 20 * np.log10(np.sqrt((m[:k * h].reshape(k, h) ** 2).mean(1)) + 1e-12)
+ return e - e.max()
+
+
+def _centroid(x):
+ F = np.abs(np.fft.rfft(_mono(x))) ** 2
+ f = np.fft.rfftfreq(len(x), 1 / SR)
+ return float((F * f).sum() / (F.sum() + 1e-30))
+
+
+def _low_share(x, hz=150.0):
+ F = np.abs(np.fft.rfft(_mono(x))) ** 2
+ f = np.fft.rfftfreq(len(x), 1 / SR)
+ return float(F[f < hz].sum() / (F.sum() + 1e-30))
+
+
+def _corr(x):
+ L, R = x[:, 0], x[:, 1]
+ return float((L * R).sum() / (np.sqrt((L * L).sum() * (R * R).sum()) + 1e-20))
+
+
+def _attack_ms(x):
+ """the catalog's definition: the first ms within 20 dB of the loudest (5 ms RMS, 10 ms smoothed) to it"""
+ m = _mono(x)
+ c = np.concatenate([[0.0], np.cumsum(m * m)])
+ cen = np.arange(0, len(m), SR // 1000)
+ a, b = np.clip(cen - 120, 0, len(m)), np.clip(cen + 120, 0, len(m))
+ sm = np.convolve((c[b] - c[a]) / np.maximum(b - a, 1), np.ones(10) / 10, mode='same')
+ ip = int(np.argmax(sm))
+ return float(ip - np.nonzero(sm[:ip + 1] >= sm[ip] * 1e-2)[0][0])
+
+
+def test_listed_with_the_recipe_contract_and_no_recorded_audio():
+ assert set(MODULES) <= set(recipes())
+ for mod in MODULES:
+ m = load_recipe(mod)
+ for k in ('TARGET', 'ALTS', 'REFSET', 'SPACE', 'DEFAULTS', 'FAMILIES', 'render'):
+ assert hasattr(m, k), (mod, k)
+ src = inspect.getsource(m)
+ for bad in ('soundfile', 'sf.read', 'audio.load', 'wavfile', 'librosa.load'):
+ assert bad not in src, (mod, bad)
+ for mod, cat, name, p in MEMBERS: # every member stays inside its search space
+ space = load_recipe(mod).SPACE
+ for key, spec in space.items():
+ if key in p and isinstance(p[key], (int, float)) and not isinstance(spec, list):
+ assert spec[0] - 1e-9 <= p[key] <= spec[1] + 1e-9, (cat, name, key, p[key])
+
+
+def test_member_names_are_unique_bank_ids():
+ assert len(IDS) == len(set(IDS))
+
+
[email protected]('mod,cat,name,p', MEMBERS, ids=IDS)
+def test_members_render_clean_deterministic_stereo(mod, cat, name, p, takes):
+ x = takes[f'{cat}/{name}']
+ assert x.ndim == 2 and x.shape[1] == 2 and np.isfinite(x).all()
+ assert 0.08 < len(x) / SR < 3.0
+ assert np.abs(x).max() <= 0.9 and abs(float(x[0].max())) < 0.02 and np.abs(x[-1]).max() < 0.01
+ m = load_recipe(mod)
+ assert np.array_equal(x, np.asarray(m.render(dict(p), dsp.rng(21)))) # one seed, one take
+ assert not np.array_equal(x, np.asarray(m.render(dict(p), dsp.rng(22)))) # another seed, another take
+ role = 'drop' if cat == 'cut_hit' and name in DROP else ROLE[cat]
+ c = sfx.check(x.astype(np.float32), category=cat, role=role)
+ assert c['ok'], (cat, name, c['summary'])
+ g = sfx.rising_glide(x) # never a rising synth sweep (the audit's definition)
+ assert g['rise_st'] <= sfx.GLIDE_ST or g['to_s'] - g['from_s'] < sfx.GLIDE_MIN_S, (cat, name, g)
+
+
+def test_cut_hits_are_short_low_and_punchy(takes):
+ for name in ('sub', 'kick', 'punch'):
+ x = takes[f'cut_hit/{name}']
+ e = _env_db(x)
+ live = (np.nonzero(e > -45)[0][-1] - np.nonzero(e > -30)[0][0]) * 0.005
+ assert 0.1 <= live <= 0.7, (name, live) # the films: 0.11-0.59 s (sub), 0.11-0.88 (punch)
+ assert 120 <= _centroid(x) <= 700, name # a kick-lifted sub, not a 50 Hz bloom
+ assert 0.2 <= _low_share(x) <= 0.9, name
+ assert _corr(x) > 0.8, name # mono like the music films'
+ assert _corr(takes['cut_hit/rumble']) < 0.5 and _corr(takes['cut_hit/air']) < 0.5 # the designed ones are wide
+
+
+def test_thump_whoosh_hits_fast_and_rings_low(takes):
+ for name in ('thump', 'thump_deep', 'thump_airy'):
+ x = takes[f'whoosh_big/{name}']
+ e = _env_db(x)
+ ip = int(np.argmax(e))
+ assert ip * 0.005 < 0.3, name # loud within ~0.1-0.2 s
+ assert (e[ip:] > -20).sum() * 0.005 >= 0.15, name # a long tail, not a blip
+ assert _low_share(x) >= 0.4 and _centroid(x) < 800, name
+
+
+def test_reverse_cymbal_swells_into_its_peak(takes):
+ for name in ('cymbal', 'ring', 'dark'):
+ x = takes[f'reverse_swell/{name}']
+ e = _env_db(x)
+ ip = int(np.argmax(e))
+ assert ip * 0.005 >= 0.25 and e[0] < -12, name # it rises into the peak
+ for name in ('cymbal', 'ring'):
+ x = takes[f'reverse_swell/{name}']
+ assert _centroid(x) > 1500 and _corr(x) < 0.4, name # bright and wide
+ assert _centroid(takes['reverse_swell/dark']) < 1500
+
+
+def test_dark_riser_peaks_at_its_end_and_stays_dark(takes):
+ m = load_recipe('darkriser')
+ for name, p in m.FAMILIES['riser']:
+ x = takes[f'riser/{name}']
+ e = _env_db(x)
+ T = m.preset_full('riser', p)['length'] if hasattr(m, 'preset_full') else {**m.DEFAULTS, **p}['length']
+ assert abs(int(np.argmax(e)) * 0.005 - T) < 0.05, name # its loudest moment is the end of the build
+ assert _centroid(x) < 2500, name
+
+
+def test_bright_swishes_are_bright(takes):
+ for name in ('bright', 'flick'):
+ assert _centroid(takes[f'swish/{name}']) > 1500, name
+ w = takes['whoosh_fast/whip']
+ assert _centroid(w) > 1200 and _corr(w) < 0.5
+
+
[email protected]('mod,cat,name,dur,apex', [('thump', 'whoosh_big', 'thump', 0.8, 0.12),
+ ('brightswish', 'swish', 'bright', 0.3, 0.1),
+ ('darkriser', 'riser', 'dark', 0.6, None),
+ ('burstglitch', 'glitch', 'mid', 0.3, None)])
+def test_bank_knobs_aim_the_members(mod, cat, name, dur, apex):
+ """as bank entries in their proposed categories the members take the category's knobs: the pass engine's dur /
+ apex (thump, swishes), the recipe's own length key (riser: length, glitch: dur)"""
+ from earshot.forge import bank, knobs
+ m = load_recipe(mod)
+ p = dict(dict(m.FAMILIES[cat])[name])
+ full = m.preset_full(cat, p) if hasattr(m, 'preset_full') else {**m.DEFAULTS, **p}
+ e = {'id': f'{cat}/{name}', 'type': 'forge', 'category': cat, 'member': name, 'recipe': mod, 'fn': 'render',
+ 'params': full, 'seed': 5, 'peak_db': -1.0, 'gain_db': 0.0}
+ y, meta = bank.render(e, dur=dur, apex=apex, checks=False)
+ assert abs(len(y) / SR - dur) < 0.002
+ method = meta['edits']['dur']['method']
+ assert method == ('shape' if cat in knobs.WHOOSH else 'param'), method
+ if apex is not None:
+ assert meta['edits']['apex']['ok'], meta['edits']['apex']
+
+
+def test_burst_glitch_hits_first(takes):
+ for name in ('burst', 'mid', 'chirp'):
+ assert _attack_ms(takes[f'glitch/{name}']) < 40, name # the films: 16-22 ms (earshot 0.3: 300-450)
+ assert _centroid(takes['glitch/burst']) > 5000 and _corr(takes['glitch/burst']) < 0.5
+ assert _centroid(takes['glitch/mid']) < 2500
diff --git a/tests/test_forge_recipes_tonal04.py b/tests/test_forge_recipes_tonal04.py
new file mode 100644
index 0000000..aabde67
--- /dev/null
+++ b/tests/test_forge_recipes_tonal04.py
@@ -0,0 +1,295 @@
+"""earshot 0.4 tonal / UI recipes (ui_pop, knock, mallet + runs, drip, shutter; notify's decay knob) and the tonal knobs
+(decay / onset / bright / width): families render clean and deterministic, land in the films' measured ranges they
+were built for (the earshot 0.4 film catalog, section 1), pass the model-free audit on new takes, the knobs land their
+targets and refuse what a sound cannot take, and the old notify members still render sample for sample. No models."""
+import numpy as np
+import pytest
+
+from earshot.forge import dsp, knobs, sfx
+from earshot.forge.search import _decode, _encode, render
+
+SR = 48000
+NEW = ('ui_pop', 'knock', 'mallet', 'drip', 'shutter')
+
+
+def _mod(name):
+ import importlib
+ return importlib.import_module(f'earshot.forge.recipes.{name}')
+
+
+def _members(name):
+ m = _mod(name)
+ return [(m, p) for fam in m.FAMILY.values() for p in fam]
+
+
+def _m(x):
+ from earshot.forge.recipes._tonal import measure
+ return measure(x)
+
+
[email protected]('name', NEW)
+def test_new_families_render_clean_and_deterministic(name):
+ mod = _mod(name)
+ fams = mod.FAMILY
+ assert fams and all(len(v) == len(mod.FAMILY_NAMES[k]) for k, v in fams.items())
+ for i, (m, p) in enumerate(_members(name)):
+ assert set(p) <= set(m.SPACE) | {'style'}, set(p) - set(m.SPACE)
+ x = render(m, p, i + 1)
+ assert x is not None and np.isfinite(x).all() and x.ndim == 2
+ assert np.array_equal(x, render(m, p, i + 1)) # same seed, same samples
+ y = render(m, p, i + 11)
+ assert not np.array_equal(x[:min(len(x), len(y))], y[:min(len(x), len(y))]) # a new seed is a new take
+ mono = x.mean(1)
+ assert abs(mono[0]) < 1e-3 and abs(mono[-1]) < 1e-3, (name, i) # starts and ends on zero
+ assert 0.03 < len(x) / SR < 1.2, (name, i)
+
+
[email protected]('name', NEW)
+def test_new_takes_pass_the_audit(name):
+ """every member's takes (two new seeds) pass earshot's model-free audit (what kit check runs), the drip's rising
+ pitch included: it completes within the audit's 50 ms window"""
+ cat = name
+ for i, (m, p) in enumerate(_members(name)):
+ for s in (101 + i, 202 + i):
+ c = sfx.check(render(m, p, s), category=cat)
+ assert c['ok'], (name, i, s, c['summary'])
+
+
+def test_ui_pop_family_sits_in_the_films_pop():
+ """the palette's typical member lands inside the films' pop IQRs on onset, decay, register, tonal share and width"""
+ mod = _mod('ui_pop')
+ p = mod.FAMILY['ui_pop'][0]
+ m = _m(render(mod, p, 3))
+ assert 18 <= m['attack_ms'] <= 62 and 57 <= m['t20_ms'] <= 129, m
+ assert 475 <= m['centroid_hz'] <= 830 and m['lo150'] <= 0.14 and m['hi4k'] <= 0.03, m
+ assert 0.45 <= m['tonal'] <= 0.68 and m['corr'] >= 0.9, m
+ for i, q in enumerate(mod.FAMILY['ui_pop']): # falling or flat: never a rising whip
+ assert sfx.rising_glide(render(mod, q, 7))['rise_st'] <= 2.0, i
+ soft = [_m(render(mod, p, 5)) for p in mod.FAMILY['ui_pop'][:2]] # the typical pops sit near mono
+ assert all(m['corr'] >= 0.9 and m['glide_st'] <= 1.0 for m in soft), soft
+
+
+def test_knock_is_mid_band_and_short():
+ mod = _mod('knock')
+ for i, p in enumerate(mod.FAMILY['knock']):
+ m = _m(render(mod, p, i + 2))
+ assert 300 <= m['centroid_hz'] <= 3500 and m['hi4k'] < 0.2, (i, m)
+ assert m['t20_ms'] <= 140 and m['dur_s'] <= 0.45, (i, m)
+ wood = _m(render(mod, mod.FAMILY['knock'][0], 3)) # the films' wooden knock: inside the IQRs
+ assert 10 <= wood['attack_ms'] <= 28 and 12 <= wood['t20_ms'] <= 131, wood
+ assert 422 <= wood['centroid_hz'] <= 1327 and 0.42 <= wood['tonal'] <= 0.58, wood
+
+
+def test_knock_bounce_adds_a_second_contact():
+ mod = _mod('knock')
+ p = dict(mod.DEFAULTS, jit=0.0, room=0.0, decay=0.006, body=-60.0) # a short strike: quiet 25 ms later
+ one = render(mod, p, 1).mean(1)
+ two = render(mod, dict(p, bounce=-6.0, bounce_ms=25.0), 1).mean(1)
+ k, w = int(0.025 * SR), int(0.004 * SR)
+ assert np.abs(two[k:k + w]).max() > 4 * np.abs(one[k:k + w]).max() # a contact 25 ms after the strike
+ assert np.array_equal(render(mod, p, 1), render(mod, dict(p, bounce=-60.0), 1)) # off: the same samples
+
+
+def test_mallet_octave_double_rounds_the_note_and_runs_render_clean():
+ """the bell note doubled an octave under sits in the films' bell-note register and tonal share (a bare bar is
+ purer); every chime run renders deterministic and passes the audit"""
+ mod = _mod('mallet')
+ glock = mod.FAMILY['mallet'][0]
+ ms = [_m(render(mod, glock, s)) for s in (3, 4, 5, 6)]
+ bare = [_m(render(mod, dict(glock, oct=-60.0), s)) for s in (3, 4, 5, 6)]
+ assert all(550 <= m['centroid_hz'] <= 1505 and m['dur_s'] <= 0.5 for m in ms), ms
+ ton, ton_bare = np.mean([m['tonal'] for m in ms]), np.mean([m['tonal'] for m in bare])
+ assert ton <= 0.72 and ton_bare >= ton + 0.08, (ton, ton_bare) # the two lines an octave apart: less pure
+ assert len(mod.RUNS['chime_run']) == len(mod.RUN_NAMES['chime_run'])
+ for i, p in enumerate(mod.RUNS['chime_run']):
+ x = np.asarray(mod.render_run(dict(p), dsp.rng(i + 3)), np.float64)
+ assert np.array_equal(x, np.asarray(mod.render_run(dict(p), dsp.rng(i + 3)), np.float64))
+ c = sfx.check(dsp.normalize(x, -1.0), category='mallet')
+ assert c['ok'], (i, c['summary'])
+
+
+def test_mallet_notes_are_gated_and_wide_and_runs_step():
+ mod = _mod('mallet')
+ for i, p in enumerate(mod.FAMILY['mallet']):
+ x = render(mod, p, i + 2)
+ m = _m(x)
+ assert m['dur_s'] <= 0.6, (i, m) # gated: no 2 s ring
+ if p['style'] == 'note' and p['width'] >= 0.4:
+ assert m['corr'] <= 0.9, (i, m) # the films' wide bell notes
+ run = dict(mod.RUN_DEFAULTS, f0=1046.5, notes=4, step=0.11, pattern='up', swing=0.0, jit=0.0)
+ x = np.asarray(mod.render_run(run, dsp.rng(1)), np.float64)
+ fs = mod.run_freqs(run)
+ assert len(fs) == run['notes'] and all(b > a for a, b in zip(fs, fs[1:])) # 'up': rising scale notes
+ nf, hop = 1024, 96 # each note's own band: when it starts
+ m = np.pad(x.mean(1), (nf, nf))
+ fr = np.lib.stride_tricks.sliding_window_view(m, nf)[::hop] * np.hanning(nf)
+ P = np.abs(np.fft.rfft(fr, axis=1)) ** 2
+ F = np.fft.rfftfreq(nf, 1 / SR)
+ starts = []
+ for f in fs:
+ e = P[:, (F > f / 2 ** (1 / 24)) & (F < f * 2 ** (1 / 24))].sum(1)
+ starts.append(int(np.argmax(e >= e.max() * 10 ** -1.2)))
+ gaps = np.diff(starts) * hop / SR
+ assert np.allclose(gaps, run['step'], atol=0.008), gaps # discrete notes `step` apart
+ L, R = x[:, 0], x[:, 1]
+ k = int(run['step'] * SR)
+ bal = [np.sum(L[i * k:(i + 1) * k] ** 2) / (np.sum(R[i * k:(i + 1) * k] ** 2) + 1e-12) for i in range(2)]
+ assert (bal[0] - 1) * (bal[1] - 1) < 0 # panned note by note (L, then R)
+
+
+def test_drip_rises_and_says_so():
+ """every drop rises; all but the bloop inside the audit's 50 ms window, the bloop's slower climb is one the drip
+ allowance accepts"""
+ mod = _mod('drip')
+ assert mod.RISES is True
+ names = mod.FAMILY_NAMES['drip']
+ for i, p in enumerate(mod.FAMILY['drip']):
+ assert p['rise'] > 0, i
+ g = sfx.rising_glide(render(mod, p, i + 4))
+ inside = g['rise_st'] <= sfx.GLIDE_ST or (g['to_s'] - g['from_s']) < sfx.GLIDE_MIN_S
+ assert inside or (names[i] == 'bloop' and mod.allows(g)), (names[i], g)
+
+
+def test_drip_allowance_accepts_a_bubble_not_a_whip():
+ """a slow bubble (a big drop's 'bloop') trips the plain audit's rising-glide check; for the drip category
+ sfx.check (and drip.check) turn that into a note, and keep flagging a climb no bubble makes"""
+ mod = _mod('drip')
+ slow = dict(mod.DEFAULTS, f0=420.0, rise=10.0, rtau=0.025, jit=0.0)
+ x = render(mod, slow, 2)
+ plain = sfx.check(x) # no category: a rising tone is a warning
+ assert 'rising_glide' in [w['code'] for w in plain['warnings']], plain['summary']
+ for c in (sfx.check(x, category='drip'), mod.check(x)):
+ assert c['ok'] and 'rising_glide' in [n['code'] for n in c['notes']], c['summary']
+ assert 'drip allowance' in c['summary']
+ assert not sfx.check(x, category='pop')['ok'] # the allowance is the drip's only
+ assert not mod.allows({'rise_st': 20.0, 'from_s': 0.01, 'to_s': 0.2}) # too large for a bubble
+ assert not mod.allows({'rise_st': 8.0, 'from_s': 0.2, 'to_s': 0.35}) # a late sweep
+ assert not mod.allows({'rise_st': 8.0, 'from_s': 0.01, 'to_s': 0.5}) # too slow
+
+
+def test_shutter_has_two_stages():
+ """stage A (the release) starts the file, stage B (the landing) jumps in `gap` later (+-10 %: each take moves
+ the mechanism by ~3 %)"""
+ mod = _mod('shutter')
+ for i, p in enumerate(mod.FAMILY['shutter']):
+ x = render(mod, p, i + 2).mean(1)
+ h = SR // 1000
+ e = 20 * np.log10(np.sqrt((x[:len(x) // h * h].reshape(-1, h) ** 2).mean(1)) + 1e-9)
+ assert e[:3].max() > e.max() - 40, i # stage A at the start
+ g = p['gap'] * 1000
+ lo, hi = int(0.88 * g), int(np.ceil(1.12 * g)) + 2
+ jump = np.max(e[lo:hi] - np.maximum.accumulate(e)[lo - 4:hi - 4])
+ assert jump > 6, (i, p['gap'], jump) # stage B: a new contact, not a decay
+
+
[email protected]('name', NEW)
+def test_family_space_pins_the_character(name):
+ mod = _mod(name)
+ p = next(iter(mod.FAMILY.values()))[0]
+ sp = mod.family_space(p)
+ pinned = [k for k, v in sp.items() if isinstance(v, list) and len(v) == 1]
+ free = [k for k in sp if k not in pinned]
+ assert free and pinned and set(free) <= set(mod.FINE)
+ q = _decode(sp, np.clip(_encode(sp, p) + 0.3, 0, 1))
+ assert all(q[k] == p[k] for k in pinned)
+
+
+# ---------------------------------------------------------------------------------------------------- notify decay
+def test_notify_ring_and_soft_default_to_the_old_render():
+ notify = _mod('notify')
+ for p in (notify.FAMILY['notify'][2], notify.FAMILY['pro_notify'][0], notify.FAMILY_R6['pro_notify'][1]):
+ old = {k: v for k, v in p.items() if k not in ('ring', 'soft', 'bell_len')}
+ assert np.array_equal(render(notify, old, 3), render(notify, dict(old, ring=1.0, soft=0.0, bell_len=0.0), 3))
+
+
+def test_notify_ring_shortens_the_ring_down_not_the_file():
+ notify = _mod('notify')
+ p = dict(notify.FAMILY['notify'][1], bell_len=0.8)
+ long_, short = _m(render(notify, p, 2)), _m(render(notify, dict(p, ring=0.3), 2))
+ assert short['t20_ms'] < 0.6 * long_['t20_ms'], (long_, short)
+ c = sfx.check(render(notify, dict(p, ring=0.3), 2), category='notify')
+ assert 'truncated' not in [w['code'] for w in c['warnings']], c['summary'] # it rings out inside the file
+ soft = _m(render(notify, dict(p, ring=0.3, soft=0.03), 2))
+ assert soft['attack_ms'] > short['attack_ms'] + 15, (short, soft)
+
+
+def test_mid_ding_member_hits_the_films_ding():
+ notify = _mod('notify')
+ for i, p in enumerate(notify.FAMILY_MID['mid_ding']):
+ x = render(notify, p, i + 5)
+ m = _m(x)
+ assert 0.2 <= m['dur_s'] <= 0.55 and 25 <= m['t20_ms'] <= 230, (i, m)
+ assert 437 <= m['centroid_hz'] <= 1014, (i, m)
+ assert sfx.check(x, category='notify')['ok'], i
+
+
+# ---------------------------------------------------------------------------------------------------- tonal knobs
+def _entry(cat, recipe, params, seed=1):
+ return {'id': f'{cat}/test', 'type': 'forge', 'category': cat, 'recipe': recipe, 'fn': 'render',
+ 'params': dict(params), 'seed': seed, 'peak_db': -1.0, 'gain_db': 0.0}
+
+
+def test_decay_knob_lands_t20_on_a_bank_style_notify_entry():
+ from earshot.forge import bank
+ notify = _mod('notify')
+ p = {k: v for k, v in notify.FAMILY['notify'][1].items() if k not in ('ring', 'soft', 'bell_len')}
+ e = _entry('notify', 'notify', dict(p, bell_len=0.8))
+ x, ed = knobs.apply(e, bank.renderer(e), decay=120.0)
+ d = ed['decay']
+ assert d["param"] == "ring" and d["value"] < 1.0 and d["renders"] <= 1 + knobs.TONAL_FIX, d
+ assert d['ok'] and abs(_m(x)['t20_ms'] - 120.0) <= 12.0, d
+
+
+def test_onset_and_width_knobs_land_their_targets():
+ from earshot.forge import bank
+ mod = _mod('ui_pop')
+ e = _entry('ui_pop', 'ui_pop', mod.FAMILY['ui_pop'][0])
+ x, ed = knobs.apply(e, bank.renderer(e), onset=45.0, width=0.6)
+ assert ed['onset']['ok'] and ed['width']['ok'], ed
+ m = _m(x)
+ assert abs(m['attack_ms'] - 45.0) <= 7 and abs(m['corr'] - 0.6) <= 0.05, m
+
+
+def test_tonal_knobs_refuse_what_a_sound_cannot_take():
+ from earshot.forge import bank
+ with pytest.raises(knobs.KnobError, match='no decay knob'):
+ knobs.validate(bank.get('whoosh_fast/crisp'), decay=100.0)
+ with pytest.raises(knobs.KnobError, match='decay must be'):
+ knobs.validate(_entry('ui_pop', 'ui_pop', {}), decay=0.5)
+ fit = next(i for i in bank.ids() if i.startswith('fit/'))
+ with pytest.raises(knobs.KnobError, match='fitted recording'):
+ knobs.validate(bank.get(fit), width=0.5)
+ d = knobs.describe(bank.get('notify/m0'))
+ assert d['tonal']['decay'] == 'ring' and d['tonal']['onset'] == 'soft' and d['dur'] == 'param'
+ with pytest.raises(knobs.KnobError, match='no bright knob'): # a knock's brightness is its material
+ knobs.validate(_entry('knock', 'knock', {}), bright=800.0)
+ notify, mallet = _mod('notify'), _mod('mallet')
+ with pytest.raises(knobs.KnobError, match='chime style has no bright'):
+ knobs.validate(_entry('notify', 'notify', notify.FAMILY_MID['mid_ding'][0]), bright=900.0)
+ with pytest.raises(knobs.KnobError, match='pluck style has no bright'):
+ knobs.validate(_entry('mallet', 'mallet', mallet.FAMILY['mallet'][1]), bright=500.0)
+
+
+def test_bright_knob_moves_a_shutter_box():
+ from earshot.forge import bank
+ shutter = _mod('shutter')
+ e = _entry('shutter', 'shutter', shutter.FAMILY['shutter'][0])
+ x, ed = knobs.apply(e, bank.renderer(e), bright=1500.0)
+ assert ed['bright']['param'] == 'b_hz' and ed['bright']['ok'], ed
+ assert abs(_m(x)['centroid_hz'] - 1500.0) <= 120, ed
+
+
+def test_impact_members_take_their_knobs():
+ """the impact agent's requests: a reverse cymbal's dur moves its own `length`; a cut hit's sub lands on a note
+ (sub_f1, its start sub_f0 keeping the glide ratio, not measured) and its dur stays a trim"""
+ from earshot.forge.recipes import cuthit, revcymbal
+ rev = _entry('reverse_swell', 'revcymbal', revcymbal.DEFAULTS)
+ assert knobs.describe(rev)['dur'] == 'param'
+ cut = _entry('cut_hit', 'cuthit', cuthit.DEFAULTS)
+ d = knobs.describe(cut)
+ assert d['dur'] == 'trim' and d['pitch']['param'] == 'sub_f1', d
+ upd, _, _ = knobs._pitch(cut, 'A1')
+ assert abs(upd['sub_f1'] - 55.0) < 0.01, upd
+ assert abs(upd['sub_f0'] / upd['sub_f1'] - cuthit.DEFAULTS['sub_f0'] / cuthit.DEFAULTS['sub_f1']) < 1e-6, upd
+ with pytest.raises(knobs.KnobError, match='outside'):
+ knobs.validate(cut, pitch='C5')