Skip to content

Art and animation, written as code. Illustrations, loops, interactive web art, launch-videos and scored films in dozens of styles, identical on every render.

piano: tone follows the real takes between layers and keys, the grand's bass hums after key-up, and a ruler that measures it

Alex Greenshpun0ab8d4d632eb
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/pianoRuler.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/pianoRuler.ts
new file mode 100644
index 0000000..901f01f
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/pianoRuler.ts
@@ -0,0 +1,57 @@
+// The piano ruler. Measures how far a played note sits from a real recording of the same note, in a
+// unit a listener can feel: the real piano's own change from soft to loud at that key. A score of 1.0
+// means the note is as far off as playing it a whole dynamic step wrong; 0.3 and under reads as close.
+// Pure functions on mono PCM (unit-tested on synthetic tones); tools/pianoruler.mjs runs them on the
+// recorded grand with each recording held out in turn, so the truth is always a real take.
+import { fft } from "./meter";
+import { PIANO_BANDS } from "./keysTables";
+
+const FRAME = 2048, HOP = 1024;
+const edges = PIANO_BANDS.map((c) => [c / Math.SQRT2, c * Math.SQRT2]);
+/** Onset: the first sample within 30 dB of the peak, so a quiet lead-in does not shift every window. */
+export const onsetOf = (x: Float32Array) => { let pk = 0; for (let i = 0; i < x.length; i++) pk = Math.max(pk, Math.abs(x[i])); const th = pk * 0.0316; for (let i = 0; i < x.length; i++) if (Math.abs(x[i]) >= th) return i; return 0; };
+/** Hann-framed power spectra between two times (s) after the onset, averaged. */
+const meanPower = (x: Float32Array, sr: number, from: number, to: number) => {
+ const o = onsetOf(x), a = o + Math.round(from * sr), b = Math.min(x.length, o + Math.round(to * sr)), acc = new Float64Array(FRAME / 2); let frames = 0;
+ const re = new Float64Array(FRAME), im = new Float64Array(FRAME);
+ for (let s = a; s + FRAME <= b || (frames === 0 && s < b); s += HOP) {
+ for (let i = 0; i < FRAME; i++) { const j = s + i; re[i] = (j < x.length ? x[j] : 0) * (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / FRAME)); im[i] = 0; }
+ fft(re, im); for (let k = 0; k < FRAME / 2; k++) acc[k] += re[k] * re[k] + im[k] * im[k]; frames++;
+ }
+ for (let k = 0; k < acc.length; k++) acc[k] /= Math.max(1, frames);
+ return acc;
+};
+const toBands = (p: Float64Array, sr: number) => edges.map(([lo, hi]) => { let e = 1e-20; for (let k = 0; k < p.length; k++) { const f = (k * sr) / FRAME; if (f >= lo && f < hi) e += p[k]; } return 10 * Math.log10(e); });
+/** Energy per half-octave piano band (dB), in a window measured from the onset. */
+export const bandEnvelope = (x: Float32Array, sr: number, from: number, to: number) => toBands(meanPower(x, sr, from, to), sr);
+/** Mean absolute difference (dB) of two envelopes after each is set to its own loudest band; bands far
+ * below both are ignored so noise floors do not count. Level-free: only the tone colour is compared. */
+export const envelopeGap = (a: number[], b: number[], floorDb = -50) => {
+ const ma = Math.max(...a), mb = Math.max(...b); let s = 0, n = 0;
+ for (let i = 0; i < a.length; i++) { const x = a[i] - ma, y = b[i] - mb; if (Math.max(x, y) < floorDb) continue; s += Math.abs(Math.max(x, floorDb) - Math.max(y, floorDb)); n++; }
+ return n ? s / n : 0;
+};
+/** Spectral centroid (Hz) of a window after the onset. */
+export const centroidHz = (x: Float32Array, sr: number, from: number, to: number) => { const p = meanPower(x, sr, from, to); let s = 0, w = 0; for (let k = 1; k < p.length; k++) { const f = (k * sr) / FRAME; if (f < 30) continue; s += f * p[k]; w += p[k]; } return w ? s / w : 0; };
+/** Decay rate per band (dB per second, positive = falling): a least-squares line through 1024-sample
+ * band levels between two times after `start` (s, absolute). Bands that start under `floorDb` from the
+ * loudest band, or reach the noise floor inside the window, come back NaN. */
+export const bandDecay = (x: Float32Array, sr: number, start: number, from: number, to: number, bands: [number, number][], floorDb = -60) => {
+ const a = Math.round((start + from) * sr), b = Math.min(x.length, Math.round((start + to) * sr)), re = new Float64Array(FRAME), im = new Float64Array(FRAME), series: number[][] = bands.map(() => []), ts: number[] = [];
+ for (let s = a; s + FRAME <= b; s += HOP) {
+ for (let i = 0; i < FRAME; i++) { re[i] = x[s + i] * (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / FRAME)); im[i] = 0; }
+ fft(re, im); ts.push((s - a) / sr);
+ bands.forEach(([lo, hi], j) => { let e = 1e-20; for (let k = 1; k < FRAME / 2; k++) { const f = (k * sr) / FRAME; if (f >= lo && f < hi) e += re[k] * re[k] + im[k] * im[k]; } series[j].push(10 * Math.log10(e)); });
+ }
+ const top = Math.max(...series.map((s) => s[0] ?? -Infinity));
+ return series.map((s) => {
+ if (s.length < 3 || s[0] < top + floorDb) return NaN;
+ const mt = ts.reduce((p, t) => p + t, 0) / ts.length, my = s.reduce((p, y) => p + y, 0) / s.length; let num = 0, den = 0;
+ ts.forEach((t, i) => { num += (t - mt) * (s[i] - my); den += (t - mt) * (t - mt); });
+ return -num / den;
+ });
+};
+/** How far `played` sits from `truth`, as a fraction of the real soft-to-loud step (`soft` vs `loud`). */
+export const ruled = (played: number[], truth: number[], soft: number[], loud: number[]) => envelopeGap(played, truth) / Math.max(0.5, envelopeGap(soft, loud));
+export const RULER_WINDOWS = Object.freeze({ attack: [0, 0.15] as const, body: [0.3, 1.5] as const, centroid: [0, 0.3] as const });
+export const mono = (ch: Float32Array[]) => { if (ch.length === 1) return ch[0]; const m = new Float32Array(ch[0].length); for (let i = 0; i < m.length; i++) m[i] = 0.5 * (ch[0][i] + ch[1][i]); return m; };
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.ts
index 486f3de..7312e67 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.ts
@@ -6,7 +6,7 @@ import { type Piece, type Part, resequence, beatsPerBar } from "./plan";
import { perform, type Performance, type Played } from "./perform";
import { renderPiano, PIANO_REAL, type PianoOpts } from "./piano";
import { keysVoice, renderPianoV2 } from "./keys";
-import { bankFor, pinnedPitch, samplerVoice, sampleZones, registerBank, type SampleBank, type SampleTrim } from "./sampler";
+import { bankFor, measuredTone, pinnedPitch, samplerVoice, sampleZones, registerBank, type SampleBank, type SampleTrim } from "./sampler";
import * as I from "./instruments";
import * as O from "./orchestra";
import { chokeTimes, type KitCtx } from "./drums";
@@ -262,7 +262,7 @@ const renderV2 = (piece: Piece, sr: number, o: RenderOpts = {}): Rendered => {
let e = partEq(prof, pt.inst, pt.role);
if (job.kind === "sampled" && (pt.role === "bass" || pt.role === "accomp")) {
const bank = bankFor(pt.inst, typeof pt.opts?.variant === "string" ? pt.opts.variant : undefined)!;
- const selected = sampleZones(bank, (o.mixKeys?.[pi] ?? keys).slice().sort((a, b) => a.t - b.t || a.p - b.p), job.seed, pt.opts?.pedal === false ? [] : perf.pedal);
+ const selected = sampleZones(bank, (o.mixKeys?.[pi] ?? keys).slice().sort((a, b) => a.t - b.t || a.p - b.p), job.seed, pt.opts?.pedal === false ? [] : perf.pedal, undefined, measuredTone(bank, pt.opts ?? {}));
const spectra = selected.map(z => bank.trim?.find(t => t.file === z.zone.file));
const median = (xs: number[], fallback: number) => xs.length ? xs.sort((a, b) => a - b)[Math.floor(xs.length / 2)] : fallback;
e = recordedEq(e, pt.role, median(spectra.map(t => t?.bandExcessDb ?? 0), 0), median(spectra.map(t => t?.bandFractionDb ?? -Infinity), -Infinity));
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sampler.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sampler.ts
index 93148ce..f8a9995 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sampler.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sampler.ts
@@ -7,6 +7,8 @@ import { nameOf } from "./theory";
import { rng } from "../core";
import { pianoVelocity } from "./keysPiano";
import { bandWidth } from "./mixDsp";
+import { bandEnvelope, mono } from "./pianoRuler";
+import { PIANO_BANDS } from "./keysTables";
// Recordings made with spaced microphones can disagree between the sides in the body of the sound
// (150 Hz to 2 kHz), and a phone or any mono fold then cancels part of it. Each stereo recording is
@@ -80,11 +82,75 @@ export const sampleCutoff = (e: SampleEntry, z: SampleZone, k: Played, sr: numbe
const t = mode !== "asis" ? 1 - Math.max(0, centre - tone) : tone;
return Math.min(sr * 0.45, 350 + 17650 * t * t);
};
+// Tone colour. A key played between two recorded loudness layers should take on the tone of a blow at
+// that strength, not only its level: a harder hammer brings the upper partials up much faster than the
+// fundamental. A louder take is picked and softened toward the blow: the measurements showed that
+// darkening a loud take lands far closer to the real softer take than brightening a soft one. A take
+// moved to a neighbouring key also drags its body resonances along with the pitch, so the colour is
+// read between the real takes on either side of the key instead. Each take's tone at the strike (first
+// 150 ms, half-octave bands, level removed) is measured once; the difference between the colour asked
+// for and the colour the moved take brings becomes a gentle octave-band EQ that leaves the overall level
+// to the velocity law. Cuts go deeper than boosts because a boost also lifts the take's noise.
+export const TONE_COLOUR = Object.freeze({ attack: 0.15, cutDb: -18, boostDb: 6, minDb: 0.25, q: 1.41 });
+type Zone = SampleBank["zones"][number];
+const colours = new WeakMap<Float32Array, number[]>();
+const colourOf = (ch: Float32Array[]) => {
+ let c = colours.get(ch[0]); if (c) return c;
+ const env = bandEnvelope(mono(ch), 48000, 0, TONE_COLOUR.attack), total = 10 * Math.log10(env.reduce((s, x) => s + Math.pow(10, x / 10), 0));
+ c = env.map((x) => x - total); colours.set(ch[0], c); return c;
+};
+/** The colour of key `midi` at velocity `v`, read between its layers (one layer step past the end ones at most). */
+const colourAt = (bank: SampleBank, midi: number, art: SampleZone["art"], v: number) => {
+ const byLayer = new Map<number, Zone>();
+ for (const o of bank.zones) if (o.zone.midi === midi && o.zone.art === art && (!byLayer.has(o.zone.layer) || o.zone.rr < byLayer.get(o.zone.layer)!.zone.rr)) byLayer.set(o.zone.layer, o);
+ const pts = [...byLayer.values()].sort((a, b) => a.zone.layer - b.zone.layer).map((o) => ({ c: layerV(bank.entry, o.zone.layer), env: colourOf(o.channels) }));
+ if (pts.length < 2) return pts[0]?.env ?? null;
+ const lo = pts[0].c - (pts[1].c - pts[0].c), hi = pts[pts.length - 1].c + (pts[pts.length - 1].c - pts[pts.length - 2].c), x = clamp(v, lo, hi);
+ let i = 0; while (i < pts.length - 2 && x > pts[i + 1].c) i++;
+ const a = pts[i], b = pts[i + 1], t = (x - a.c) / (b.c - a.c);
+ return a.env.map((y, j) => y + (b.env[j] - y) * t);
+};
+/** A colour moved up by `semis` (half-octave bands: six semitones per band), as resampling moves it. */
+const shiftBands = (c: number[], semis: number) => c.map((_, j) => { const x = clamp(j - semis / 6, 0, c.length - 1), i = Math.min(c.length - 2, Math.floor(x)), t = x - i; return c[i] + (c[i + 1] - c[i]) * t; });
+/** The per-band change (dB, one per PIANO_BANDS entry) that gives zone `z`, played at key `p` and velocity `v`, the colour of the real
+ * takes around it; null when there is nothing to correct. A velocity at or above the take's own layer is never brightened. */
+export const toneColour = (bank: SampleBank, z: Zone, p: number, v: number): number[] | null => {
+ const art = z.zone.art, ownV = layerV(bank.entry, z.zone.layer), vv = Math.min(v, ownV), d = z.zone.unpitched ? 0 : p - z.zone.midi;
+ const keys = [...new Set(bank.zones.filter((o) => o.zone.art === art).map((o) => o.zone.midi))], lo = Math.max(...keys.filter((m) => m <= p)), hi = Math.min(...keys.filter((m) => m >= p));
+ const between = d !== 0 && Number.isFinite(lo) && Number.isFinite(hi) && lo !== hi;
+ if (vv >= ownV && !between) return null;
+ let target: number[] | null;
+ if (between) { const a = colourAt(bank, lo, art, vv), b = colourAt(bank, hi, art, vv), t = (p - lo) / (hi - lo); target = a && b ? a.map((y, j) => y + (b[j] - y) * t) : null; }
+ else target = colourAt(bank, z.zone.midi, art, vv);
+ if (!target) return null;
+ const own = between ? shiftBands(colourOf(z.channels), d) : colourOf(z.channels), raw = target.map((y, j) => y - own[j]);
+ const capped = raw.map((_, j) => clamp((raw[Math.max(0, j - 1)] + 2 * raw[j] + raw[Math.min(raw.length - 1, j + 1)]) / 4, TONE_COLOUR.cutDb, TONE_COLOUR.boostDb));
+ // keep the overall level where the velocity law puts it
+ const before = own.reduce((s, y) => s + Math.pow(10, y / 10), 0), after = own.reduce((s, y, j) => s + Math.pow(10, (y + capped[j]) / 10), 0), shift = 10 * Math.log10(before / after);
+ return capped.map((x) => x + shift);
+};
+const peakDb = (f: number, fc: number, g: number, q: number, sr: number) => {
+ const bq = Biquad.make(sr, "peak", fc, q, g), w = (2 * Math.PI * f) / sr, c1 = Math.cos(w), s1 = Math.sin(w), c2 = Math.cos(2 * w), s2 = Math.sin(2 * w);
+ const nr = bq.b0 + bq.b1 * c1 + bq.b2 * c2, ni = -bq.b1 * s1 - bq.b2 * s2, dr = 1 + bq.a1 * c1 + bq.a2 * c2, di = -bq.a1 * s1 - bq.a2 * s2;
+ return 10 * Math.log10((nr * nr + ni * ni) / (dr * dr + di * di));
+};
+/** Octave peaking filters whose combined response lands on the colour at each octave centre (a few rounds of correction, because neighbours overlap). */
+export const colourFilters = (delta: number[], sr: number) => {
+ const centres = PIANO_BANDS.filter((_, j) => j % 2 === 0), want = delta.filter((_, j) => j % 2 === 0).map((d, k) => (centres[k] < 0.45 * sr ? d : 0)), g = want.slice();
+ for (let round = 0; round < 6; round++) {
+ const got = centres.map((f) => centres.reduce((s, fc, k) => s + (centres[k] < 0.45 * sr ? peakDb(f, fc, g[k], TONE_COLOUR.q, sr) : 0), 0));
+ for (let k = 0; k < g.length; k++) g[k] = clamp(g[k] + 0.8 * (want[k] - got[k]), TONE_COLOUR.cutDb - 6, TONE_COLOUR.boostDb + 6);
+ }
+ return centres.flatMap((fc, k) => (fc < 0.45 * sr && Math.abs(g[k]) >= TONE_COLOUR.minDb ? [Biquad.make(sr, "peak", fc, TONE_COLOUR.q, g[k])] : []));
+};
+const pianoFamily = (bank: SampleBank) => ("id" in bank ? String((bank as RegisteredBank).id) : "").split(".")[0] === "piano";
+/** Tone colour is on for the piano banks unless a voice asks for the older lowpass (or a sampleFilter audition). */
+export const measuredTone = (bank: SampleBank, opts: Opts) => (opts.velocityTone ?? (pianoFamily(bank) ? "measured" : "lowpass")) === "measured" && opts.sampleFilter === undefined;
export const sampleGain = (e: SampleEntry, z: SampleZone, v: number) => e.normalized ? pianoVelocity(v) * db(-8 * Math.max(0, 0.6 - v)) : v <= 0 ? 0 : db(clamp(16 * (v - layerV(e, z.layer)), -6, 6));
/** A drum tuned to one note (a timpani in a drum lane) plays that note whatever the lane wrote, moved by octaves into what was recorded. */
export const pinnedPitch = (pitch: number, range: readonly [number, number] | readonly number[]) => { if (!Number.isFinite(pitch)) throw new Error(`a pinned pitch must be a note number, got ${pitch}`); let p = Math.round(pitch); while (p < range[0]) p += 12; while (p > range[1]) p -= 12; return p < range[0] ? range[0] : p; };
/** Nearest pitch, then nearest layer, then this note's seeded recording. State stays local to a render. */
-export const sampleZones = (bank: SampleBank, keys: Played[], seed: number, pedal: PedalSpan[] = [], art?: "rel") => {
+export const sampleZones = (bank: SampleBank, keys: Played[], seed: number, pedal: PedalSpan[] = [], art?: "rel", louder = false) => {
const previous = new Map<string, SampleBank["zones"][number]>(), e = bank.entry, pool = bank.zones.filter(({ zone }) => zone.art === art);
return keys.map((k, i) => {
if (k.p < e.range[0] || k.p > e.range[1]) throw new Error(`${e.title}: note ${nameOf(k.p)} (${k.p}) outside range ${nameOf(e.range[0])}-${nameOf(e.range[1])} (${e.range.join("-")})`);
@@ -93,6 +159,8 @@ export const sampleZones = (bank: SampleBank, keys: Played[], seed: number, peda
const atPitch = pool.filter(({ zone }) => zone.midi === pitch), v = clamp(k.v, 0, 1);
let layer = 0, delta = Infinity;
for (const { zone: z } of atPitch) { const d = Math.abs(layerV(e, z.layer) - v); if (d < delta || (Math.abs(d - delta) < 1e-12 && z.layer > layer)) { layer = z.layer; delta = d; } }
+ // with tone colour on, the take at or just above the blow is softened instead (a soft take cannot grow the partials it never had)
+ if (louder) { const up = atPitch.map(({ zone }) => zone.layer).filter((l) => layerV(e, l) >= v - 1e-9); if (up.length) layer = Math.min(...up); }
const down = !art && pedal.some(([a, b]) => k.t >= a && k.t < b), r = rng(k.vary?.seed ?? ((seed * 7919 + i * 104729 + k.p * 31) >>> 0));
const pick = (layer: number) => {
const sus = down ? bank.zones.filter(({ zone }) => zone.art === "sus" && zone.midi === pitch && zone.layer === layer) : [];
@@ -126,11 +194,19 @@ const sincRead = (a: Float32Array, x: number, table: Float64Array) => {
return y;
};
+// Key-up on a damped string. The felt kills everything above the split in tDamp; below it a bass string
+// rings on for longer (by the recorded release takes: the 30-250 Hz band of the lowest keys falls at
+// roughly a third of the rate of the band above it). `lowMul` is the bass end's stretch, fading to none
+// by middle C, where the fundamental sits above the split anyway. On by default for the grand only: its
+// release takes are what the numbers were checked against (the upright's release takes are key noise).
+export const RELEASE_SPLIT = Object.freeze({ crossHz: 250, lowMul: 3 });
+export const releaseLow = (p: number, tDamp: number, lowMul: number = RELEASE_SPLIT.lowMul) => tDamp * (1 + (lowMul - 1) * clamp((60 - p) / 36, 0, 1));
export const samplerVoice = (bank: SampleBank, keys: Played[], pedal: PedalSpan[], sr: number, n: number, opts: Opts, seed: number) => {
if (!Number.isFinite(sr) || sr <= 0 || !Number.isInteger(n) || n < 0) throw new Error("sampler: invalid sample rate or length");
if (bank.entry.kind !== "struck") throw new Error(`${bank.entry.title}: ${bank.entry.zones.some((z) => !z.loop) ? "sustained zone without a loop" : "sustained banks are not supported in pack version 1"}`);
const L = new Float32Array(n), R = new Float32Array(n), halo = new Float32Array(n), e = bank.entry;
- const sorted = keys.slice().sort((a, b) => a.t - b.t || a.p - b.p), usePedal = opts.pedal !== false, zones = sampleZones(bank, sorted, seed, usePedal ? pedal : []);
+ const measured = measuredTone(bank, opts);
+ const sorted = keys.slice().sort((a, b) => a.t - b.t || a.p - b.p), usePedal = opts.pedal !== false, zones = sampleZones(bank, sorted, seed, usePedal ? pedal : [], undefined, measured);
const releases = e.damped && bank.zones.some(({ zone }) => zone.art === "rel") ? sampleZones(bank, sorted, seed + 401, [], "rel") : null;
const id = "id" in bank ? String(bank.id) : "", grand = id.split(".")[0] === "piano" && !["upright", "honky"].includes(id.split(".")[1] ?? String(opts.variant));
const pedalAt = (t: number) => usePedal && pedal.some(([a, b]) => t >= a && t < b);
@@ -141,21 +217,32 @@ export const samplerVoice = (bank: SampleBank, keys: Played[], pedal: PedalSpan[
const table = rate !== 1 ? sincTable(rate) : null, v = clamp(k.v, 0, 1);
// Keep the source's layer levels intact. A normalized source gets all its dynamics from this law.
const gain = sampleGain(e, z, v) * db((k.vary?.db ?? 0) + (bank.trim?.find((t) => t.file === z.file)?.correctionDb ?? 0));
- const fc = sampleCutoff(e, z, k, sr, typeof opts.sampleFilter === "string" ? opts.sampleFilter : undefined), alpha = 1 - Math.exp(-2 * Math.PI * fc / sr);
+ const tone = clamp(k.tone ?? k.v, 0, 1), colour = measured ? toneColour(bank, zones[idx], k.p, tone) : null;
+ const eqL = colour ? colourFilters(colour, sr) : [], eqR = colour ? colourFilters(colour, sr) : [];
+ const fc = colour ? Infinity : sampleCutoff(e, z, k, sr, typeof opts.sampleFilter === "string" ? opts.sampleFilter : undefined), alpha = 1 - Math.exp(-2 * Math.PI * fc / sr);
let damp = e.damped ? (pedalAt(k.off) ? pedalUpAfter(k.off) : k.off) : Infinity;
if (grand && k.p >= 89) damp = Infinity; // the top grand keys have no dampers; vibes and uprights still stop
const releaseAt = damp;
if (e.damped) for (let j = idx + 1; j < sorted.length; j++) if (sorted[j].p === k.p && sorted[j].t > k.t) { damp = Math.min(damp, sorted[j].t + 0.004); break; }
const tDamp = 0.08 + 0.45 * clamp((60 - k.p) / 36, 0, 1), dampI = Math.round((damp - k.t) * sr), dec = Math.exp(-6.91 / (tDamp * sr));
- const len = Math.min(n - i0, Math.ceil(z.frames / rate), damp === Infinity ? Infinity : dampI + Math.round(tDamp * 1.6 * sr) + 1), inPedal = e.damped && (pedalAt(k.t) || pedalAt(k.t + 0.25));
+ // felt stops the upper partials at once while a long bass string keeps humming under it
+ const split = e.damped && (opts.release ?? (id === "piano" ? "two-band" : "flat")) === "two-band", tLow = split ? releaseLow(k.p, tDamp, typeof opts.releaseLowMul === "number" ? opts.releaseLowMul : undefined) : tDamp, decLow = Math.exp(-6.91 / (tLow * sr)), lowBqL = split ? Biquad.make(sr, "lp", RELEASE_SPLIT.crossHz, 0.707) : null, lowBqR = split ? Biquad.make(sr, "lp", RELEASE_SPLIT.crossHz, 0.707) : null;
+ const len = Math.min(n - i0, Math.ceil(z.frames / rate), damp === Infinity ? Infinity : dampI + Math.round(Math.max(tDamp, tLow) * 1.6 * sr) + 1), inPedal = e.damped && (pedalAt(k.t) || pedalAt(k.t + 0.25));
const read = (a: Float32Array, i: number) => table ? sincRead(a, i * rate, table) : a[i];
const rel = releases?.[idx], window = Math.max(1, Math.round(0.02 * sr)); let remaining = 0, count = 0;
- let l = 0, r = 0, env = 1;
+ let l = 0, r = 0, env = 1, envLow = 1, lowL = 0, lowR = 0;
for (let i = 0; i < len; i++) {
- if (i >= dampI) env *= dec;
- l = fc === Infinity ? read(channels[0], i) : l + alpha * (read(channels[0], i) - l); r = channels.length === 1 ? l : fc === Infinity ? read(channels[1], i) : r + alpha * (read(channels[1], i) - r);
- const j = i0 + i; if (j < 0) continue;
- const a = l * gain * env, b = r * gain * env; L[j] += a; R[j] += b;
+ if (i >= dampI) { env *= dec; envLow *= decLow; }
+ let x = read(channels[0], i), y = channels.length === 1 ? x : read(channels[1], i);
+ for (const f of eqL) x = f.tick(x);
+ for (const f of eqR) y = f.tick(y);
+ l = fc === Infinity ? x : l + alpha * (x - l); r = channels.length === 1 && !eqR.length ? l : fc === Infinity ? y : r + alpha * (y - r);
+ const j = i0 + i;
+ let a: number, b: number;
+ if (split) { lowL = lowBqL!.tick(l); lowR = lowBqR!.tick(r); a = (lowL * envLow + (l - lowL) * env) * gain; b = (lowR * envLow + (r - lowR) * env) * gain; }
+ else { a = l * gain * env; b = r * gain * env; }
+ if (j < 0) continue;
+ L[j] += a; R[j] += b;
if (rel && i >= Math.max(0, dampI - window) && i < dampI) { remaining += (a * a + b * b) * 0.5; count++; }
if (inPedal) halo[j] += 0.5 * (a + b);
}
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/pianoTone.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/pianoTone.test.ts
new file mode 100644
index 0000000..210b88b
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/test/pianoTone.test.ts
@@ -0,0 +1,84 @@
+// The piano ruler's measures, tone colour between recorded layers and keys, and the two-band release, on synthetic takes.
+import { bandEnvelope, envelopeGap, ruled, bandDecay, centroidHz, onsetOf } from "../src/canvas-core/music/pianoRuler";
+import { registerBank, clearBanks, samplerVoice, sampleZones, toneColour, colourFilters, releaseLow, measuredTone, RELEASE_SPLIT, type SampleBank, type SampleZone } from "../src/canvas-core/music/sampler";
+import { PIANO_BANDS } from "../src/canvas-core/music/keysTables";
+import { hz } from "../src/canvas-core/music/theory";
+import type { Played } from "../src/canvas-core/music/perform";
+
+export const name = "piano tone";
+export const run = (ok: (cond: boolean, label: string) => void) => {
+ const SR = 48000;
+ // a take whose upper partials grow with the layer: brightness b sets partial n to b^(n-1)
+ const tone = (f: number, b: number, secs = 2, tau = 1.2) => { const a = new Float32Array(Math.round(secs * SR)); for (let i = 0; i < a.length; i++) { let s = 0; for (let n = 1; n <= 24 && n * f < 20000; n++) s += Math.pow(b, n - 1) * Math.sin((2 * Math.PI * n * f * i) / SR); a[i] = 0.2 * s * Math.exp(-i / (SR * tau)); } return a; };
+ const BRIGHT = [0.45, 0.65, 0.85];
+ const bank = (id: string, pitches: number[], layers = 3, damped = true): SampleBank & { id?: string } => {
+ const zones: SampleBank["zones"] = [];
+ for (const midi of pitches) for (let layer = 1; layer <= layers; layer++) {
+ const a = tone(hz(midi), BRIGHT[layer - 1]);
+ const zone: SampleZone = { file: `${id}_${midi}_${layer}.flac`, midi, layer, rr: 1, frames: a.length, channels: 1, peakDb: -6, rmsDb: -14, sha256: (midi * 100 + layer * 10).toString(16).padStart(64, "0") };
+ zones.push({ zone, channels: [a] });
+ }
+ return { entry: { title: id, source: "synthetic", license: "CC0-1.0", kind: "struck", range: [21, 108], layers, damped, normalized: true, zones: zones.map((z) => z.zone) }, zones };
+ };
+ const key = (p: number, v: number, off = 1.8): Played => ({ p, v, tone: v, t: 0, off, role: "melody", w: v });
+ const centroidOf = (x: Float32Array) => centroidHz(x, SR, 0, 0.3);
+
+ // ruler measures
+ const dark = tone(220, 0.4), bright = tone(220, 0.85), mid = tone(220, 0.65);
+ const eD = bandEnvelope(dark, SR, 0, 0.15), eB = bandEnvelope(bright, SR, 0, 0.15), eM = bandEnvelope(mid, SR, 0, 0.15);
+ ok(eD.length === PIANO_BANDS.length, "one envelope value per piano band");
+ ok(envelopeGap(eD, eD) === 0 && envelopeGap(eD, eB) > 3, `envelope gap: zero for the same take, large dark vs bright (${envelopeGap(eD, eB).toFixed(1)} dB)`);
+ ok(Math.abs(envelopeGap(eD, eB.map((x) => x - 20)) - envelopeGap(eD, eB)) < 1e-9, "envelope gap ignores level");
+ ok(ruled(eD, eD, eD, eB) === 0 && Math.abs(ruled(eB, eD, eD, eB) - 1) < 1e-9, "ruled: 0 on the truth, 1.0 a whole soft-to-loud step off");
+ ok(ruled(eM, eD, eD, eB) > 0.2 && ruled(eM, eD, eD, eB) < 0.9, `ruled: a middle take sits between (${ruled(eM, eD, eD, eB).toFixed(2)})`);
+ ok(centroidOf(bright) > centroidOf(dark) * 1.3, "centroid rises with brightness");
+ const lead = new Float32Array(SR); lead.set(tone(220, 0.5, 0.5), 4800); ok(Math.abs(onsetOf(lead) - 4800) < 50, "onset found after a silent lead-in");
+ const falling = tone(440, 0.5, 2, 0.5), rate = bandDecay(falling, SR, 0, 0.1, 1.5, [[300, 600]])[0];
+ ok(Math.abs(rate - 20 * Math.log10(Math.E) / 0.5) < 2, `band decay reads an exponential's rate (${rate.toFixed(1)} dB/s, want 17.4)`);
+ ok(Number.isNaN(bandDecay(falling, SR, 0, 0.1, 1.5, [[300, 600], [12000, 16000]])[1]), "band decay: an empty band is NaN, not a number");
+
+ // tone colour
+ clearBanks();
+ try {
+ const grand = registerBank("piano", bank("piano", [56, 60, 64]));
+ const other = registerBank("vibes", bank("vibes", [56, 60, 64]));
+ ok(measuredTone(grand, {}) && !measuredTone(other, {}) && !measuredTone(grand, { velocityTone: "lowpass" }) && !measuredTone(grand, { sampleFilter: "off" }), "tone colour: on for the piano banks, off elsewhere, and off on request");
+ const ks = [key(60, 0.3)], picked = sampleZones(grand, ks, 1, [], undefined, true)[0].zone.layer, nearest = sampleZones(grand, ks, 1)[0].zone.layer;
+ ok(picked === 2 && nearest === 1, `a blow between layers takes the louder layer to soften (louder ${picked}, nearest ${nearest})`);
+ const loud = grand.zones.find((z) => z.zone.midi === 60 && z.zone.layer === 3)!, soft = grand.zones.find((z) => z.zone.midi === 60 && z.zone.layer === 1)!;
+ ok(toneColour(grand, loud, 60, 0.9) === null && toneColour(grand, soft, 60, 0.9) === null, "never brightens: at or above the take's own layer there is nothing to do");
+ const d = toneColour(grand, loud, 60, 0.5)!;
+ ok(d.length === PIANO_BANDS.length && d[16] < d[6] - 3, `softening cuts the top more than the body (7.7 kHz ${d[16].toFixed(1)} dB vs 240 Hz ${d[6].toFixed(1)} dB)`);
+ ok(d.every((x) => x <= 6 + 12 && x >= -18 - 12), "colour stays inside its caps (plus the level shift)");
+ const truth = soft.channels[0].length ? grand.zones.find((z) => z.zone.midi === 60 && z.zone.layer === 2)!.channels[0] : new Float32Array(0);
+ const asIs = samplerVoice(grand, [key(60, 0.5)], [], SR, SR * 2, { velocityTone: "lowpass", release: "flat" }, 1).L;
+ const held = { ...grand, zones: grand.zones.filter((z) => !(z.zone.midi === 60 && z.zone.layer === 2)) };
+ const fromLoud = samplerVoice(held, [key(60, 0.5)], [], SR, SR * 2, { release: "flat" }, 1).L, fromLoudPlain = samplerVoice(held, [key(60, 0.5)], [], SR, SR * 2, { velocityTone: "lowpass", release: "flat" }, 1).L;
+ const tE = bandEnvelope(truth, SR, 0, 0.15), sE = bandEnvelope(soft.channels[0], SR, 0, 0.15), lE = bandEnvelope(loud.channels[0], SR, 0, 0.15);
+ const gOn = ruled(bandEnvelope(fromLoud, SR, 0, 0.15), tE, sE, lE), gOff = ruled(bandEnvelope(fromLoudPlain, SR, 0, 0.15), tE, sE, lE);
+ ok(gOn < gOff * 0.6, `held-out middle layer: the softened loud take lands nearer the real one (${gOn.toFixed(2)} vs ${gOff.toFixed(2)})`);
+ ok(ruled(bandEnvelope(asIs, SR, 0, 0.15), tE, sE, lE) < 0.05, "a blow at a recorded layer plays that take untouched");
+ // a key between recorded pitches: the colour is read between its neighbours
+ const shifted = toneColour(grand, grand.zones.find((z) => z.zone.midi === 60 && z.zone.layer === 2)!, 62, 0.5)!;
+ ok(Array.isArray(shifted) && shifted.length === PIANO_BANDS.length, "a moved take gets a colour from the keys either side");
+ ok(toneColour(grand, grand.zones.find((z) => z.zone.midi === 64 && z.zone.layer === 2)!, 66, 0.5) === null, "past the last recorded key there is no neighbour to read, so nothing changes");
+ // filters land on the colour asked for
+ let seed = 12345; const noise = Float32Array.from({ length: SR }, () => ((seed = (seed * 1103515245 + 12345) >>> 0) / 2 ** 32) - 0.5);
+ const want = PIANO_BANDS.map((f) => (f > 1000 ? -9 : 0)), fs = colourFilters(want, SR), shaped = Float32Array.from(noise); for (const f of fs) f.run(shaped);
+ const resp = bandEnvelope(shaped, SR, 0, 1), ref = bandEnvelope(noise, SR, 0, 1);
+ const err = [8, 10, 12, 14].map((j) => Math.abs(resp[j] - ref[j] - want[j]));
+ ok(Math.max(...err) < 2, `octave filters land within 2 dB of the colour at the octave centres (worst ${Math.max(...err).toFixed(2)} dB)`);
+ ok(colourFilters(PIANO_BANDS.map(() => 0), SR).length === 0, "a flat colour builds no filters");
+
+ // two-band release
+ ok(releaseLow(24, 0.5) === 0.5 * RELEASE_SPLIT.lowMul && releaseLow(60, 0.1) === 0.1 && releaseLow(84, 0.08) === 0.08, "the low band lingers longest at the bottom and not at all from middle C up");
+ const lowKey = registerBank("piano", bank("piano", [36, 40], 1)), keyUp = 0.6;
+ const twoBand = samplerVoice(lowKey, [key(36, 0.8, keyUp)], [], SR, SR * 2, {}, 1).L, flatRel = samplerVoice(lowKey, [key(36, 0.8, keyUp)], [], SR, SR * 2, { release: "flat" }, 1).L;
+ const bands: [number, number][] = [[30, 250], [500, 1000]], r2 = bandDecay(twoBand, SR, keyUp, 0.02, 0.2, bands), r1 = bandDecay(flatRel, SR, keyUp, 0.02, 0.2, bands);
+ ok(r2[0] < r1[0] * 0.6, `two-band: the bass hum falls slower after key-up (${r2[0].toFixed(0)} vs ${r1[0].toFixed(0)} dB/s)`);
+ ok(Math.abs(r2[1] - r1[1]) < r1[1] * 0.25, `two-band: the upper partials still stop as fast (${r2[1].toFixed(0)} vs ${r1[1].toFixed(0)} dB/s)`);
+ const before = Math.round(0.5 * SR); ok(twoBand.slice(0, before).every((x, i) => Math.abs(x - flatRel[i]) < 1e-6), "before key-up the split sums back to the take exactly");
+ const up = registerBank("piano.upright", bank("piano.upright", [36, 40], 1)), u2 = samplerVoice(up, [key(36, 0.8, keyUp)], [], SR, SR * 2, {}, 1).L, u1 = samplerVoice(up, [key(36, 0.8, keyUp)], [], SR, SR * 2, { release: "flat" }, 1).L;
+ ok(u2.every((x, i) => x === u1[i]), "the upright keeps its single-rate release unless asked");
+ } finally { clearBanks(); }
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/pianoruler.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/pianoruler.mjs
new file mode 100644
index 0000000..9c241a9
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/pianoruler.mjs
@@ -0,0 +1,72 @@
+// PIANO RULER. Holds each recording of the grand out in turn, plays that note from what is left, and
+// scores the result against the real take it replaced. The unit is the real piano's own soft-to-loud
+// change at that key (1.0 = a whole dynamic step off), so "sounds wrong" becomes a number.
+// node tools/pianoruler.mjs [--sounds <pack>] [--bank piano] [--json out.json] [--set key=value ...]
+// Three probes: velocity (a layer held out, played from its neighbour), pitch (a whole key held out,
+// played from the recording four keys away) and release (key-up decay per band against the recorded
+// release takes). `--set velocityTone=lowpass` or `--set release=flat` replays the older behaviour, so
+// one change at a time can be judged by whether it moves the number. The release probe needs release
+// takes that hold the string's own dying ring (the grand's do; the upright's are key noise, so its
+// release row is not a real measure).
+import { build } from "esbuild";
+import { writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { loadBanks } from "./sounds.mjs";
+import { soundsDir } from "./soundfetch.mjs";
+
+const here = dirname(fileURLToPath(import.meta.url)), SR = 48000;
+const args = process.argv.slice(2), val = (k, d) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : d; };
+const sets = args.flatMap((a, i) => (a === "--set" ? [args[i + 1]] : [])).map((s) => s.split("="));
+const opts = Object.fromEntries(sets.map(([k, v]) => [k, v === "true" ? true : v === "false" ? false : Number.isFinite(Number(v)) ? Number(v) : v]));
+const bankId = val("--bank", "piano"), dir = val("--sounds", process.env.ANIDOODLE_SOUNDS || soundsDir());
+
+const r = await build({ stdin: { contents: `export * from "./index"; export * as Ruler from "./pianoRuler";`, resolveDir: join(here, "../src/canvas-core/music"), loader: "ts" }, bundle: true, write: false, format: "esm", platform: "neutral", target: "es2022", logLevel: "error" });
+const M = await import("data:text/javascript;base64," + Buffer.from(r.outputFiles[0].text).toString("base64"));
+const U = M.Ruler, log = console.log; console.log = () => {}; loadBanks(M, dir, [bankId]); console.log = log;
+const [inst, ...variant] = bankId.split("."), bank = M.bankFor(inst, variant.join(".") || undefined);
+if (!bank) { console.error(`pianoruler: no bank ${bankId} in ${dir}`); process.exit(2); }
+
+const e = bank.entry, ord = bank.zones.filter((z) => !z.zone.art), pitches = [...new Set(ord.map((z) => z.zone.midi))].sort((a, b) => a - b);
+const layerV = (l) => e.layerVelocity?.[l - 1] ?? (l - 0.5) / e.layers;
+const take = (p, l, art) => bank.zones.find((z) => z.zone.midi === p && z.zone.layer === l && z.zone.art === art);
+const play = (zones, p, v, off, secs) => { const n = Math.round(secs * SR), out = M.samplerVoice({ ...bank, zones }, [{ p, v, tone: v, t: 0.05, off, role: "melody", w: v }], [], SR, n, opts, 7); return U.mono([out.L, out.R]); };
+const W = U.RULER_WINDOWS, env = (x, w) => U.bandEnvelope(x, SR, w[0], w[1]), cents = (a, b) => 1200 * Math.log2(a / b);
+const mean = (xs) => { const f = xs.filter(Number.isFinite); return f.length ? f.reduce((s, x) => s + x, 0) / f.length : NaN; };
+const f2 = (x) => (Number.isFinite(x) ? x.toFixed(2) : " - ");
+
+// the ruler at each key: real soft take vs real loud take, attack and body windows
+const ruler = new Map(pitches.map((p) => { const s = U.mono(take(p, 1).channels), l = U.mono(take(p, e.layers).channels); return [p, { s, l, attack: [env(s, W.attack), env(l, W.attack)], body: [env(s, W.body), env(l, W.body)] }]; }));
+const score = (x, truth, p) => { const R = ruler.get(p); return { attack: U.ruled(env(x, W.attack), env(truth, W.attack), ...R.attack), body: U.ruled(env(x, W.body), env(truth, W.body), ...R.body), cents: cents(U.centroidHz(x, SR, ...W.centroid), U.centroidHz(truth, SR, ...W.centroid)) }; };
+
+const velocity = [], pitch = [], release = [];
+for (const p of pitches) {
+ for (let h = 1; h <= e.layers; h++) {
+ const truth = take(p, h); if (!truth) continue;
+ const x = play(bank.zones.filter((z) => z !== truth), p, layerV(h), 3.2, 3.5);
+ velocity.push({ p, layer: h, ...score(x, U.mono(truth.channels), p) });
+ }
+ const mid = take(p, Math.ceil(e.layers / 2));
+ if (mid && pitches.some((q) => Math.abs(q - p) === 4)) pitch.push({ p, ...score(play(bank.zones.filter((z) => z.zone.midi !== p), p, layerV(mid.zone.layer), 3.2, 3.5), U.mono(mid.channels), p) });
+ const rel = take(p, Math.ceil(e.layers / 2), "rel");
+ if (mid && rel) {
+ const bands = [[30, 250], [250, 1000], [1000, 4000]], keyUp = 1.05;
+ const truthR = U.bandDecay(U.mono(rel.channels), SR, U.onsetOf(U.mono(rel.channels)) / SR, 0.02, 0.2, bands, -40);
+ const held = play(bank.zones, p, layerV(mid.zone.layer), keyUp, 1.6), ring = play(bank.zones, p, layerV(mid.zone.layer), 3.2, 1.6);
+ const played = U.bandDecay(held, SR, keyUp, 0.02, 0.2, bands, -40), natural = U.bandDecay(ring, SR, keyUp, 0.02, 0.2, bands, -40);
+ // 1.0 = as far from the real release as not damping at all
+ const off = bands.map((_, j) => Math.abs(played[j] - truthR[j]) / Math.max(20, Math.abs(truthR[j] - natural[j])));
+ release.push({ p, truth: truthR, played, natural, ruled: mean(off) });
+ }
+}
+
+const summary = { bank: bankId, opts, velocity: { attack: mean(velocity.map((r) => r.attack)), body: mean(velocity.map((r) => r.body)), absCents: mean(velocity.map((r) => Math.abs(r.cents))) }, pitch: { attack: mean(pitch.map((r) => r.attack)), body: mean(pitch.map((r) => r.body)), absCents: mean(pitch.map((r) => Math.abs(r.cents))) }, release: { ruled: mean(release.map((r) => r.ruled)) } };
+log(`piano ruler: ${bankId}${sets.length ? ` (${sets.map((s) => s.join("=")).join(", ")})` : ""} 1.00 = one whole soft-to-loud step off`);
+log("\nvelocity key layer attack body centroid cents");
+for (const v of velocity) log(` ${String(v.p).padStart(3)} ${v.layer} ${f2(v.attack)} ${f2(v.body)} ${v.cents.toFixed(0)}`);
+log("\npitch key attack body centroid cents (played from four keys away)");
+for (const v of pitch) log(` ${String(v.p).padStart(3)} ${f2(v.attack)} ${f2(v.body)} ${v.cents.toFixed(0)}`);
+log("\nrelease key dB/s low/mid/high: real | played | undamped ruled");
+for (const v of release) log(` ${String(v.p).padStart(3)} ${v.truth.map((x) => f2(x).padStart(6)).join("")} | ${v.played.map((x) => f2(x).padStart(6)).join("")} | ${v.natural.map((x) => f2(x).padStart(6)).join("")} ${f2(v.ruled)}`);
+log(`\nMEAN velocity attack ${f2(summary.velocity.attack)} body ${f2(summary.velocity.body)} |centroid| ${summary.velocity.absCents.toFixed(0)} c pitch attack ${f2(summary.pitch.attack)} body ${f2(summary.pitch.body)} |centroid| ${summary.pitch.absCents.toFixed(0)} c release ${f2(summary.release.ruled)}`);
+const out = val("--json"); if (out) writeFileSync(out, JSON.stringify({ summary, velocity, pitch, release }, null, 1));
diff --git a/plugins/anidoodle/skills/anidoodle/references/music/README.md b/plugins/anidoodle/skills/anidoodle/references/music/README.md
index 2276cae..7c2cdb9 100644
--- a/plugins/anidoodle/skills/anidoodle/references/music/README.md
+++ b/plugins/anidoodle/skills/anidoodle/references/music/README.md
@@ -194,6 +194,17 @@ drums and every sound effect are code and stay code.
- **Soft playing keeps a real attack.** The Steinway bank has three velocity layers and its source
was normalized, so soft notes come from the soft recording with the modeled piano's velocity law
rather than a quiet copy of a loud one. Do not add an attack that isn't there.
+- **Between layers and between keys, the tone follows the real takes.** A velocity between two
+ layers plays the louder take softened to the colour read between the real takes of that key
+ (a softer blow is darker, not only quieter), and a key between two recordings takes the colour
+ of the recordings either side, so a moved take does not drag its body resonances along. Both
+ piano banks do this; `opts: { velocityTone: "lowpass" }` brings back the older single filter.
+- **Key-up lets the bass hum.** On the grand the felt stops the upper partials at once while the
+ lowest strings keep a low hum for a moment, as the recorded release takes do.
+ `opts: { release: "flat" }` damps every frequency at one rate.
+- **Measure before you tune.** `node tools/pianoruler.mjs` holds each recording out in turn, plays
+ it from what is left and scores the gap in the real piano's own soft-to-loud steps (1.0 = a
+ whole step off). Change one thing, rerun, keep it only if the number moves the right way.
- **A real marimba's low notes are rich.** D2 to C4 carries as much as the top of the instrument.
Keep bass lines out of the melody's register rather than reaching down for the modeled marimba's
thin bass.
diff --git a/skills/anidoodle/engine/src/canvas-core/music/pianoRuler.ts b/skills/anidoodle/engine/src/canvas-core/music/pianoRuler.ts
new file mode 100644
index 0000000..901f01f
--- /dev/null
+++ b/skills/anidoodle/engine/src/canvas-core/music/pianoRuler.ts
@@ -0,0 +1,57 @@
+// The piano ruler. Measures how far a played note sits from a real recording of the same note, in a
+// unit a listener can feel: the real piano's own change from soft to loud at that key. A score of 1.0
+// means the note is as far off as playing it a whole dynamic step wrong; 0.3 and under reads as close.
+// Pure functions on mono PCM (unit-tested on synthetic tones); tools/pianoruler.mjs runs them on the
+// recorded grand with each recording held out in turn, so the truth is always a real take.
+import { fft } from "./meter";
+import { PIANO_BANDS } from "./keysTables";
+
+const FRAME = 2048, HOP = 1024;
+const edges = PIANO_BANDS.map((c) => [c / Math.SQRT2, c * Math.SQRT2]);
+/** Onset: the first sample within 30 dB of the peak, so a quiet lead-in does not shift every window. */
+export const onsetOf = (x: Float32Array) => { let pk = 0; for (let i = 0; i < x.length; i++) pk = Math.max(pk, Math.abs(x[i])); const th = pk * 0.0316; for (let i = 0; i < x.length; i++) if (Math.abs(x[i]) >= th) return i; return 0; };
+/** Hann-framed power spectra between two times (s) after the onset, averaged. */
+const meanPower = (x: Float32Array, sr: number, from: number, to: number) => {
+ const o = onsetOf(x), a = o + Math.round(from * sr), b = Math.min(x.length, o + Math.round(to * sr)), acc = new Float64Array(FRAME / 2); let frames = 0;
+ const re = new Float64Array(FRAME), im = new Float64Array(FRAME);
+ for (let s = a; s + FRAME <= b || (frames === 0 && s < b); s += HOP) {
+ for (let i = 0; i < FRAME; i++) { const j = s + i; re[i] = (j < x.length ? x[j] : 0) * (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / FRAME)); im[i] = 0; }
+ fft(re, im); for (let k = 0; k < FRAME / 2; k++) acc[k] += re[k] * re[k] + im[k] * im[k]; frames++;
+ }
+ for (let k = 0; k < acc.length; k++) acc[k] /= Math.max(1, frames);
+ return acc;
+};
+const toBands = (p: Float64Array, sr: number) => edges.map(([lo, hi]) => { let e = 1e-20; for (let k = 0; k < p.length; k++) { const f = (k * sr) / FRAME; if (f >= lo && f < hi) e += p[k]; } return 10 * Math.log10(e); });
+/** Energy per half-octave piano band (dB), in a window measured from the onset. */
+export const bandEnvelope = (x: Float32Array, sr: number, from: number, to: number) => toBands(meanPower(x, sr, from, to), sr);
+/** Mean absolute difference (dB) of two envelopes after each is set to its own loudest band; bands far
+ * below both are ignored so noise floors do not count. Level-free: only the tone colour is compared. */
+export const envelopeGap = (a: number[], b: number[], floorDb = -50) => {
+ const ma = Math.max(...a), mb = Math.max(...b); let s = 0, n = 0;
+ for (let i = 0; i < a.length; i++) { const x = a[i] - ma, y = b[i] - mb; if (Math.max(x, y) < floorDb) continue; s += Math.abs(Math.max(x, floorDb) - Math.max(y, floorDb)); n++; }
+ return n ? s / n : 0;
+};
+/** Spectral centroid (Hz) of a window after the onset. */
+export const centroidHz = (x: Float32Array, sr: number, from: number, to: number) => { const p = meanPower(x, sr, from, to); let s = 0, w = 0; for (let k = 1; k < p.length; k++) { const f = (k * sr) / FRAME; if (f < 30) continue; s += f * p[k]; w += p[k]; } return w ? s / w : 0; };
+/** Decay rate per band (dB per second, positive = falling): a least-squares line through 1024-sample
+ * band levels between two times after `start` (s, absolute). Bands that start under `floorDb` from the
+ * loudest band, or reach the noise floor inside the window, come back NaN. */
+export const bandDecay = (x: Float32Array, sr: number, start: number, from: number, to: number, bands: [number, number][], floorDb = -60) => {
+ const a = Math.round((start + from) * sr), b = Math.min(x.length, Math.round((start + to) * sr)), re = new Float64Array(FRAME), im = new Float64Array(FRAME), series: number[][] = bands.map(() => []), ts: number[] = [];
+ for (let s = a; s + FRAME <= b; s += HOP) {
+ for (let i = 0; i < FRAME; i++) { re[i] = x[s + i] * (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / FRAME)); im[i] = 0; }
+ fft(re, im); ts.push((s - a) / sr);
+ bands.forEach(([lo, hi], j) => { let e = 1e-20; for (let k = 1; k < FRAME / 2; k++) { const f = (k * sr) / FRAME; if (f >= lo && f < hi) e += re[k] * re[k] + im[k] * im[k]; } series[j].push(10 * Math.log10(e)); });
+ }
+ const top = Math.max(...series.map((s) => s[0] ?? -Infinity));
+ return series.map((s) => {
+ if (s.length < 3 || s[0] < top + floorDb) return NaN;
+ const mt = ts.reduce((p, t) => p + t, 0) / ts.length, my = s.reduce((p, y) => p + y, 0) / s.length; let num = 0, den = 0;
+ ts.forEach((t, i) => { num += (t - mt) * (s[i] - my); den += (t - mt) * (t - mt); });
+ return -num / den;
+ });
+};
+/** How far `played` sits from `truth`, as a fraction of the real soft-to-loud step (`soft` vs `loud`). */
+export const ruled = (played: number[], truth: number[], soft: number[], loud: number[]) => envelopeGap(played, truth) / Math.max(0.5, envelopeGap(soft, loud));
+export const RULER_WINDOWS = Object.freeze({ attack: [0, 0.15] as const, body: [0.3, 1.5] as const, centroid: [0, 0.3] as const });
+export const mono = (ch: Float32Array[]) => { if (ch.length === 1) return ch[0]; const m = new Float32Array(ch[0].length); for (let i = 0; i < m.length; i++) m[i] = 0.5 * (ch[0][i] + ch[1][i]); return m; };
diff --git a/skills/anidoodle/engine/src/canvas-core/music/render.ts b/skills/anidoodle/engine/src/canvas-core/music/render.ts
index 486f3de..7312e67 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/render.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/render.ts
@@ -6,7 +6,7 @@ import { type Piece, type Part, resequence, beatsPerBar } from "./plan";
import { perform, type Performance, type Played } from "./perform";
import { renderPiano, PIANO_REAL, type PianoOpts } from "./piano";
import { keysVoice, renderPianoV2 } from "./keys";
-import { bankFor, pinnedPitch, samplerVoice, sampleZones, registerBank, type SampleBank, type SampleTrim } from "./sampler";
+import { bankFor, measuredTone, pinnedPitch, samplerVoice, sampleZones, registerBank, type SampleBank, type SampleTrim } from "./sampler";
import * as I from "./instruments";
import * as O from "./orchestra";
import { chokeTimes, type KitCtx } from "./drums";
@@ -262,7 +262,7 @@ const renderV2 = (piece: Piece, sr: number, o: RenderOpts = {}): Rendered => {
let e = partEq(prof, pt.inst, pt.role);
if (job.kind === "sampled" && (pt.role === "bass" || pt.role === "accomp")) {
const bank = bankFor(pt.inst, typeof pt.opts?.variant === "string" ? pt.opts.variant : undefined)!;
- const selected = sampleZones(bank, (o.mixKeys?.[pi] ?? keys).slice().sort((a, b) => a.t - b.t || a.p - b.p), job.seed, pt.opts?.pedal === false ? [] : perf.pedal);
+ const selected = sampleZones(bank, (o.mixKeys?.[pi] ?? keys).slice().sort((a, b) => a.t - b.t || a.p - b.p), job.seed, pt.opts?.pedal === false ? [] : perf.pedal, undefined, measuredTone(bank, pt.opts ?? {}));
const spectra = selected.map(z => bank.trim?.find(t => t.file === z.zone.file));
const median = (xs: number[], fallback: number) => xs.length ? xs.sort((a, b) => a - b)[Math.floor(xs.length / 2)] : fallback;
e = recordedEq(e, pt.role, median(spectra.map(t => t?.bandExcessDb ?? 0), 0), median(spectra.map(t => t?.bandFractionDb ?? -Infinity), -Infinity));
diff --git a/skills/anidoodle/engine/src/canvas-core/music/sampler.ts b/skills/anidoodle/engine/src/canvas-core/music/sampler.ts
index 93148ce..f8a9995 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/sampler.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/sampler.ts
@@ -7,6 +7,8 @@ import { nameOf } from "./theory";
import { rng } from "../core";
import { pianoVelocity } from "./keysPiano";
import { bandWidth } from "./mixDsp";
+import { bandEnvelope, mono } from "./pianoRuler";
+import { PIANO_BANDS } from "./keysTables";
// Recordings made with spaced microphones can disagree between the sides in the body of the sound
// (150 Hz to 2 kHz), and a phone or any mono fold then cancels part of it. Each stereo recording is
@@ -80,11 +82,75 @@ export const sampleCutoff = (e: SampleEntry, z: SampleZone, k: Played, sr: numbe
const t = mode !== "asis" ? 1 - Math.max(0, centre - tone) : tone;
return Math.min(sr * 0.45, 350 + 17650 * t * t);
};
+// Tone colour. A key played between two recorded loudness layers should take on the tone of a blow at
+// that strength, not only its level: a harder hammer brings the upper partials up much faster than the
+// fundamental. A louder take is picked and softened toward the blow: the measurements showed that
+// darkening a loud take lands far closer to the real softer take than brightening a soft one. A take
+// moved to a neighbouring key also drags its body resonances along with the pitch, so the colour is
+// read between the real takes on either side of the key instead. Each take's tone at the strike (first
+// 150 ms, half-octave bands, level removed) is measured once; the difference between the colour asked
+// for and the colour the moved take brings becomes a gentle octave-band EQ that leaves the overall level
+// to the velocity law. Cuts go deeper than boosts because a boost also lifts the take's noise.
+export const TONE_COLOUR = Object.freeze({ attack: 0.15, cutDb: -18, boostDb: 6, minDb: 0.25, q: 1.41 });
+type Zone = SampleBank["zones"][number];
+const colours = new WeakMap<Float32Array, number[]>();
+const colourOf = (ch: Float32Array[]) => {
+ let c = colours.get(ch[0]); if (c) return c;
+ const env = bandEnvelope(mono(ch), 48000, 0, TONE_COLOUR.attack), total = 10 * Math.log10(env.reduce((s, x) => s + Math.pow(10, x / 10), 0));
+ c = env.map((x) => x - total); colours.set(ch[0], c); return c;
+};
+/** The colour of key `midi` at velocity `v`, read between its layers (one layer step past the end ones at most). */
+const colourAt = (bank: SampleBank, midi: number, art: SampleZone["art"], v: number) => {
+ const byLayer = new Map<number, Zone>();
+ for (const o of bank.zones) if (o.zone.midi === midi && o.zone.art === art && (!byLayer.has(o.zone.layer) || o.zone.rr < byLayer.get(o.zone.layer)!.zone.rr)) byLayer.set(o.zone.layer, o);
+ const pts = [...byLayer.values()].sort((a, b) => a.zone.layer - b.zone.layer).map((o) => ({ c: layerV(bank.entry, o.zone.layer), env: colourOf(o.channels) }));
+ if (pts.length < 2) return pts[0]?.env ?? null;
+ const lo = pts[0].c - (pts[1].c - pts[0].c), hi = pts[pts.length - 1].c + (pts[pts.length - 1].c - pts[pts.length - 2].c), x = clamp(v, lo, hi);
+ let i = 0; while (i < pts.length - 2 && x > pts[i + 1].c) i++;
+ const a = pts[i], b = pts[i + 1], t = (x - a.c) / (b.c - a.c);
+ return a.env.map((y, j) => y + (b.env[j] - y) * t);
+};
+/** A colour moved up by `semis` (half-octave bands: six semitones per band), as resampling moves it. */
+const shiftBands = (c: number[], semis: number) => c.map((_, j) => { const x = clamp(j - semis / 6, 0, c.length - 1), i = Math.min(c.length - 2, Math.floor(x)), t = x - i; return c[i] + (c[i + 1] - c[i]) * t; });
+/** The per-band change (dB, one per PIANO_BANDS entry) that gives zone `z`, played at key `p` and velocity `v`, the colour of the real
+ * takes around it; null when there is nothing to correct. A velocity at or above the take's own layer is never brightened. */
+export const toneColour = (bank: SampleBank, z: Zone, p: number, v: number): number[] | null => {
+ const art = z.zone.art, ownV = layerV(bank.entry, z.zone.layer), vv = Math.min(v, ownV), d = z.zone.unpitched ? 0 : p - z.zone.midi;
+ const keys = [...new Set(bank.zones.filter((o) => o.zone.art === art).map((o) => o.zone.midi))], lo = Math.max(...keys.filter((m) => m <= p)), hi = Math.min(...keys.filter((m) => m >= p));
+ const between = d !== 0 && Number.isFinite(lo) && Number.isFinite(hi) && lo !== hi;
+ if (vv >= ownV && !between) return null;
+ let target: number[] | null;
+ if (between) { const a = colourAt(bank, lo, art, vv), b = colourAt(bank, hi, art, vv), t = (p - lo) / (hi - lo); target = a && b ? a.map((y, j) => y + (b[j] - y) * t) : null; }
+ else target = colourAt(bank, z.zone.midi, art, vv);
+ if (!target) return null;
+ const own = between ? shiftBands(colourOf(z.channels), d) : colourOf(z.channels), raw = target.map((y, j) => y - own[j]);
+ const capped = raw.map((_, j) => clamp((raw[Math.max(0, j - 1)] + 2 * raw[j] + raw[Math.min(raw.length - 1, j + 1)]) / 4, TONE_COLOUR.cutDb, TONE_COLOUR.boostDb));
+ // keep the overall level where the velocity law puts it
+ const before = own.reduce((s, y) => s + Math.pow(10, y / 10), 0), after = own.reduce((s, y, j) => s + Math.pow(10, (y + capped[j]) / 10), 0), shift = 10 * Math.log10(before / after);
+ return capped.map((x) => x + shift);
+};
+const peakDb = (f: number, fc: number, g: number, q: number, sr: number) => {
+ const bq = Biquad.make(sr, "peak", fc, q, g), w = (2 * Math.PI * f) / sr, c1 = Math.cos(w), s1 = Math.sin(w), c2 = Math.cos(2 * w), s2 = Math.sin(2 * w);
+ const nr = bq.b0 + bq.b1 * c1 + bq.b2 * c2, ni = -bq.b1 * s1 - bq.b2 * s2, dr = 1 + bq.a1 * c1 + bq.a2 * c2, di = -bq.a1 * s1 - bq.a2 * s2;
+ return 10 * Math.log10((nr * nr + ni * ni) / (dr * dr + di * di));
+};
+/** Octave peaking filters whose combined response lands on the colour at each octave centre (a few rounds of correction, because neighbours overlap). */
+export const colourFilters = (delta: number[], sr: number) => {
+ const centres = PIANO_BANDS.filter((_, j) => j % 2 === 0), want = delta.filter((_, j) => j % 2 === 0).map((d, k) => (centres[k] < 0.45 * sr ? d : 0)), g = want.slice();
+ for (let round = 0; round < 6; round++) {
+ const got = centres.map((f) => centres.reduce((s, fc, k) => s + (centres[k] < 0.45 * sr ? peakDb(f, fc, g[k], TONE_COLOUR.q, sr) : 0), 0));
+ for (let k = 0; k < g.length; k++) g[k] = clamp(g[k] + 0.8 * (want[k] - got[k]), TONE_COLOUR.cutDb - 6, TONE_COLOUR.boostDb + 6);
+ }
+ return centres.flatMap((fc, k) => (fc < 0.45 * sr && Math.abs(g[k]) >= TONE_COLOUR.minDb ? [Biquad.make(sr, "peak", fc, TONE_COLOUR.q, g[k])] : []));
+};
+const pianoFamily = (bank: SampleBank) => ("id" in bank ? String((bank as RegisteredBank).id) : "").split(".")[0] === "piano";
+/** Tone colour is on for the piano banks unless a voice asks for the older lowpass (or a sampleFilter audition). */
+export const measuredTone = (bank: SampleBank, opts: Opts) => (opts.velocityTone ?? (pianoFamily(bank) ? "measured" : "lowpass")) === "measured" && opts.sampleFilter === undefined;
export const sampleGain = (e: SampleEntry, z: SampleZone, v: number) => e.normalized ? pianoVelocity(v) * db(-8 * Math.max(0, 0.6 - v)) : v <= 0 ? 0 : db(clamp(16 * (v - layerV(e, z.layer)), -6, 6));
/** A drum tuned to one note (a timpani in a drum lane) plays that note whatever the lane wrote, moved by octaves into what was recorded. */
export const pinnedPitch = (pitch: number, range: readonly [number, number] | readonly number[]) => { if (!Number.isFinite(pitch)) throw new Error(`a pinned pitch must be a note number, got ${pitch}`); let p = Math.round(pitch); while (p < range[0]) p += 12; while (p > range[1]) p -= 12; return p < range[0] ? range[0] : p; };
/** Nearest pitch, then nearest layer, then this note's seeded recording. State stays local to a render. */
-export const sampleZones = (bank: SampleBank, keys: Played[], seed: number, pedal: PedalSpan[] = [], art?: "rel") => {
+export const sampleZones = (bank: SampleBank, keys: Played[], seed: number, pedal: PedalSpan[] = [], art?: "rel", louder = false) => {
const previous = new Map<string, SampleBank["zones"][number]>(), e = bank.entry, pool = bank.zones.filter(({ zone }) => zone.art === art);
return keys.map((k, i) => {
if (k.p < e.range[0] || k.p > e.range[1]) throw new Error(`${e.title}: note ${nameOf(k.p)} (${k.p}) outside range ${nameOf(e.range[0])}-${nameOf(e.range[1])} (${e.range.join("-")})`);
@@ -93,6 +159,8 @@ export const sampleZones = (bank: SampleBank, keys: Played[], seed: number, peda
const atPitch = pool.filter(({ zone }) => zone.midi === pitch), v = clamp(k.v, 0, 1);
let layer = 0, delta = Infinity;
for (const { zone: z } of atPitch) { const d = Math.abs(layerV(e, z.layer) - v); if (d < delta || (Math.abs(d - delta) < 1e-12 && z.layer > layer)) { layer = z.layer; delta = d; } }
+ // with tone colour on, the take at or just above the blow is softened instead (a soft take cannot grow the partials it never had)
+ if (louder) { const up = atPitch.map(({ zone }) => zone.layer).filter((l) => layerV(e, l) >= v - 1e-9); if (up.length) layer = Math.min(...up); }
const down = !art && pedal.some(([a, b]) => k.t >= a && k.t < b), r = rng(k.vary?.seed ?? ((seed * 7919 + i * 104729 + k.p * 31) >>> 0));
const pick = (layer: number) => {
const sus = down ? bank.zones.filter(({ zone }) => zone.art === "sus" && zone.midi === pitch && zone.layer === layer) : [];
@@ -126,11 +194,19 @@ const sincRead = (a: Float32Array, x: number, table: Float64Array) => {
return y;
};
+// Key-up on a damped string. The felt kills everything above the split in tDamp; below it a bass string
+// rings on for longer (by the recorded release takes: the 30-250 Hz band of the lowest keys falls at
+// roughly a third of the rate of the band above it). `lowMul` is the bass end's stretch, fading to none
+// by middle C, where the fundamental sits above the split anyway. On by default for the grand only: its
+// release takes are what the numbers were checked against (the upright's release takes are key noise).
+export const RELEASE_SPLIT = Object.freeze({ crossHz: 250, lowMul: 3 });
+export const releaseLow = (p: number, tDamp: number, lowMul: number = RELEASE_SPLIT.lowMul) => tDamp * (1 + (lowMul - 1) * clamp((60 - p) / 36, 0, 1));
export const samplerVoice = (bank: SampleBank, keys: Played[], pedal: PedalSpan[], sr: number, n: number, opts: Opts, seed: number) => {
if (!Number.isFinite(sr) || sr <= 0 || !Number.isInteger(n) || n < 0) throw new Error("sampler: invalid sample rate or length");
if (bank.entry.kind !== "struck") throw new Error(`${bank.entry.title}: ${bank.entry.zones.some((z) => !z.loop) ? "sustained zone without a loop" : "sustained banks are not supported in pack version 1"}`);
const L = new Float32Array(n), R = new Float32Array(n), halo = new Float32Array(n), e = bank.entry;
- const sorted = keys.slice().sort((a, b) => a.t - b.t || a.p - b.p), usePedal = opts.pedal !== false, zones = sampleZones(bank, sorted, seed, usePedal ? pedal : []);
+ const measured = measuredTone(bank, opts);
+ const sorted = keys.slice().sort((a, b) => a.t - b.t || a.p - b.p), usePedal = opts.pedal !== false, zones = sampleZones(bank, sorted, seed, usePedal ? pedal : [], undefined, measured);
const releases = e.damped && bank.zones.some(({ zone }) => zone.art === "rel") ? sampleZones(bank, sorted, seed + 401, [], "rel") : null;
const id = "id" in bank ? String(bank.id) : "", grand = id.split(".")[0] === "piano" && !["upright", "honky"].includes(id.split(".")[1] ?? String(opts.variant));
const pedalAt = (t: number) => usePedal && pedal.some(([a, b]) => t >= a && t < b);
@@ -141,21 +217,32 @@ export const samplerVoice = (bank: SampleBank, keys: Played[], pedal: PedalSpan[
const table = rate !== 1 ? sincTable(rate) : null, v = clamp(k.v, 0, 1);
// Keep the source's layer levels intact. A normalized source gets all its dynamics from this law.
const gain = sampleGain(e, z, v) * db((k.vary?.db ?? 0) + (bank.trim?.find((t) => t.file === z.file)?.correctionDb ?? 0));
- const fc = sampleCutoff(e, z, k, sr, typeof opts.sampleFilter === "string" ? opts.sampleFilter : undefined), alpha = 1 - Math.exp(-2 * Math.PI * fc / sr);
+ const tone = clamp(k.tone ?? k.v, 0, 1), colour = measured ? toneColour(bank, zones[idx], k.p, tone) : null;
+ const eqL = colour ? colourFilters(colour, sr) : [], eqR = colour ? colourFilters(colour, sr) : [];
+ const fc = colour ? Infinity : sampleCutoff(e, z, k, sr, typeof opts.sampleFilter === "string" ? opts.sampleFilter : undefined), alpha = 1 - Math.exp(-2 * Math.PI * fc / sr);
let damp = e.damped ? (pedalAt(k.off) ? pedalUpAfter(k.off) : k.off) : Infinity;
if (grand && k.p >= 89) damp = Infinity; // the top grand keys have no dampers; vibes and uprights still stop
const releaseAt = damp;
if (e.damped) for (let j = idx + 1; j < sorted.length; j++) if (sorted[j].p === k.p && sorted[j].t > k.t) { damp = Math.min(damp, sorted[j].t + 0.004); break; }
const tDamp = 0.08 + 0.45 * clamp((60 - k.p) / 36, 0, 1), dampI = Math.round((damp - k.t) * sr), dec = Math.exp(-6.91 / (tDamp * sr));
- const len = Math.min(n - i0, Math.ceil(z.frames / rate), damp === Infinity ? Infinity : dampI + Math.round(tDamp * 1.6 * sr) + 1), inPedal = e.damped && (pedalAt(k.t) || pedalAt(k.t + 0.25));
+ // felt stops the upper partials at once while a long bass string keeps humming under it
+ const split = e.damped && (opts.release ?? (id === "piano" ? "two-band" : "flat")) === "two-band", tLow = split ? releaseLow(k.p, tDamp, typeof opts.releaseLowMul === "number" ? opts.releaseLowMul : undefined) : tDamp, decLow = Math.exp(-6.91 / (tLow * sr)), lowBqL = split ? Biquad.make(sr, "lp", RELEASE_SPLIT.crossHz, 0.707) : null, lowBqR = split ? Biquad.make(sr, "lp", RELEASE_SPLIT.crossHz, 0.707) : null;
+ const len = Math.min(n - i0, Math.ceil(z.frames / rate), damp === Infinity ? Infinity : dampI + Math.round(Math.max(tDamp, tLow) * 1.6 * sr) + 1), inPedal = e.damped && (pedalAt(k.t) || pedalAt(k.t + 0.25));
const read = (a: Float32Array, i: number) => table ? sincRead(a, i * rate, table) : a[i];
const rel = releases?.[idx], window = Math.max(1, Math.round(0.02 * sr)); let remaining = 0, count = 0;
- let l = 0, r = 0, env = 1;
+ let l = 0, r = 0, env = 1, envLow = 1, lowL = 0, lowR = 0;
for (let i = 0; i < len; i++) {
- if (i >= dampI) env *= dec;
- l = fc === Infinity ? read(channels[0], i) : l + alpha * (read(channels[0], i) - l); r = channels.length === 1 ? l : fc === Infinity ? read(channels[1], i) : r + alpha * (read(channels[1], i) - r);
- const j = i0 + i; if (j < 0) continue;
- const a = l * gain * env, b = r * gain * env; L[j] += a; R[j] += b;
+ if (i >= dampI) { env *= dec; envLow *= decLow; }
+ let x = read(channels[0], i), y = channels.length === 1 ? x : read(channels[1], i);
+ for (const f of eqL) x = f.tick(x);
+ for (const f of eqR) y = f.tick(y);
+ l = fc === Infinity ? x : l + alpha * (x - l); r = channels.length === 1 && !eqR.length ? l : fc === Infinity ? y : r + alpha * (y - r);
+ const j = i0 + i;
+ let a: number, b: number;
+ if (split) { lowL = lowBqL!.tick(l); lowR = lowBqR!.tick(r); a = (lowL * envLow + (l - lowL) * env) * gain; b = (lowR * envLow + (r - lowR) * env) * gain; }
+ else { a = l * gain * env; b = r * gain * env; }
+ if (j < 0) continue;
+ L[j] += a; R[j] += b;
if (rel && i >= Math.max(0, dampI - window) && i < dampI) { remaining += (a * a + b * b) * 0.5; count++; }
if (inPedal) halo[j] += 0.5 * (a + b);
}
diff --git a/skills/anidoodle/engine/test/pianoTone.test.ts b/skills/anidoodle/engine/test/pianoTone.test.ts
new file mode 100644
index 0000000..210b88b
--- /dev/null
+++ b/skills/anidoodle/engine/test/pianoTone.test.ts
@@ -0,0 +1,84 @@
+// The piano ruler's measures, tone colour between recorded layers and keys, and the two-band release, on synthetic takes.
+import { bandEnvelope, envelopeGap, ruled, bandDecay, centroidHz, onsetOf } from "../src/canvas-core/music/pianoRuler";
+import { registerBank, clearBanks, samplerVoice, sampleZones, toneColour, colourFilters, releaseLow, measuredTone, RELEASE_SPLIT, type SampleBank, type SampleZone } from "../src/canvas-core/music/sampler";
+import { PIANO_BANDS } from "../src/canvas-core/music/keysTables";
+import { hz } from "../src/canvas-core/music/theory";
+import type { Played } from "../src/canvas-core/music/perform";
+
+export const name = "piano tone";
+export const run = (ok: (cond: boolean, label: string) => void) => {
+ const SR = 48000;
+ // a take whose upper partials grow with the layer: brightness b sets partial n to b^(n-1)
+ const tone = (f: number, b: number, secs = 2, tau = 1.2) => { const a = new Float32Array(Math.round(secs * SR)); for (let i = 0; i < a.length; i++) { let s = 0; for (let n = 1; n <= 24 && n * f < 20000; n++) s += Math.pow(b, n - 1) * Math.sin((2 * Math.PI * n * f * i) / SR); a[i] = 0.2 * s * Math.exp(-i / (SR * tau)); } return a; };
+ const BRIGHT = [0.45, 0.65, 0.85];
+ const bank = (id: string, pitches: number[], layers = 3, damped = true): SampleBank & { id?: string } => {
+ const zones: SampleBank["zones"] = [];
+ for (const midi of pitches) for (let layer = 1; layer <= layers; layer++) {
+ const a = tone(hz(midi), BRIGHT[layer - 1]);
+ const zone: SampleZone = { file: `${id}_${midi}_${layer}.flac`, midi, layer, rr: 1, frames: a.length, channels: 1, peakDb: -6, rmsDb: -14, sha256: (midi * 100 + layer * 10).toString(16).padStart(64, "0") };
+ zones.push({ zone, channels: [a] });
+ }
+ return { entry: { title: id, source: "synthetic", license: "CC0-1.0", kind: "struck", range: [21, 108], layers, damped, normalized: true, zones: zones.map((z) => z.zone) }, zones };
+ };
+ const key = (p: number, v: number, off = 1.8): Played => ({ p, v, tone: v, t: 0, off, role: "melody", w: v });
+ const centroidOf = (x: Float32Array) => centroidHz(x, SR, 0, 0.3);
+
+ // ruler measures
+ const dark = tone(220, 0.4), bright = tone(220, 0.85), mid = tone(220, 0.65);
+ const eD = bandEnvelope(dark, SR, 0, 0.15), eB = bandEnvelope(bright, SR, 0, 0.15), eM = bandEnvelope(mid, SR, 0, 0.15);
+ ok(eD.length === PIANO_BANDS.length, "one envelope value per piano band");
+ ok(envelopeGap(eD, eD) === 0 && envelopeGap(eD, eB) > 3, `envelope gap: zero for the same take, large dark vs bright (${envelopeGap(eD, eB).toFixed(1)} dB)`);
+ ok(Math.abs(envelopeGap(eD, eB.map((x) => x - 20)) - envelopeGap(eD, eB)) < 1e-9, "envelope gap ignores level");
+ ok(ruled(eD, eD, eD, eB) === 0 && Math.abs(ruled(eB, eD, eD, eB) - 1) < 1e-9, "ruled: 0 on the truth, 1.0 a whole soft-to-loud step off");
+ ok(ruled(eM, eD, eD, eB) > 0.2 && ruled(eM, eD, eD, eB) < 0.9, `ruled: a middle take sits between (${ruled(eM, eD, eD, eB).toFixed(2)})`);
+ ok(centroidOf(bright) > centroidOf(dark) * 1.3, "centroid rises with brightness");
+ const lead = new Float32Array(SR); lead.set(tone(220, 0.5, 0.5), 4800); ok(Math.abs(onsetOf(lead) - 4800) < 50, "onset found after a silent lead-in");
+ const falling = tone(440, 0.5, 2, 0.5), rate = bandDecay(falling, SR, 0, 0.1, 1.5, [[300, 600]])[0];
+ ok(Math.abs(rate - 20 * Math.log10(Math.E) / 0.5) < 2, `band decay reads an exponential's rate (${rate.toFixed(1)} dB/s, want 17.4)`);
+ ok(Number.isNaN(bandDecay(falling, SR, 0, 0.1, 1.5, [[300, 600], [12000, 16000]])[1]), "band decay: an empty band is NaN, not a number");
+
+ // tone colour
+ clearBanks();
+ try {
+ const grand = registerBank("piano", bank("piano", [56, 60, 64]));
+ const other = registerBank("vibes", bank("vibes", [56, 60, 64]));
+ ok(measuredTone(grand, {}) && !measuredTone(other, {}) && !measuredTone(grand, { velocityTone: "lowpass" }) && !measuredTone(grand, { sampleFilter: "off" }), "tone colour: on for the piano banks, off elsewhere, and off on request");
+ const ks = [key(60, 0.3)], picked = sampleZones(grand, ks, 1, [], undefined, true)[0].zone.layer, nearest = sampleZones(grand, ks, 1)[0].zone.layer;
+ ok(picked === 2 && nearest === 1, `a blow between layers takes the louder layer to soften (louder ${picked}, nearest ${nearest})`);
+ const loud = grand.zones.find((z) => z.zone.midi === 60 && z.zone.layer === 3)!, soft = grand.zones.find((z) => z.zone.midi === 60 && z.zone.layer === 1)!;
+ ok(toneColour(grand, loud, 60, 0.9) === null && toneColour(grand, soft, 60, 0.9) === null, "never brightens: at or above the take's own layer there is nothing to do");
+ const d = toneColour(grand, loud, 60, 0.5)!;
+ ok(d.length === PIANO_BANDS.length && d[16] < d[6] - 3, `softening cuts the top more than the body (7.7 kHz ${d[16].toFixed(1)} dB vs 240 Hz ${d[6].toFixed(1)} dB)`);
+ ok(d.every((x) => x <= 6 + 12 && x >= -18 - 12), "colour stays inside its caps (plus the level shift)");
+ const truth = soft.channels[0].length ? grand.zones.find((z) => z.zone.midi === 60 && z.zone.layer === 2)!.channels[0] : new Float32Array(0);
+ const asIs = samplerVoice(grand, [key(60, 0.5)], [], SR, SR * 2, { velocityTone: "lowpass", release: "flat" }, 1).L;
+ const held = { ...grand, zones: grand.zones.filter((z) => !(z.zone.midi === 60 && z.zone.layer === 2)) };
+ const fromLoud = samplerVoice(held, [key(60, 0.5)], [], SR, SR * 2, { release: "flat" }, 1).L, fromLoudPlain = samplerVoice(held, [key(60, 0.5)], [], SR, SR * 2, { velocityTone: "lowpass", release: "flat" }, 1).L;
+ const tE = bandEnvelope(truth, SR, 0, 0.15), sE = bandEnvelope(soft.channels[0], SR, 0, 0.15), lE = bandEnvelope(loud.channels[0], SR, 0, 0.15);
+ const gOn = ruled(bandEnvelope(fromLoud, SR, 0, 0.15), tE, sE, lE), gOff = ruled(bandEnvelope(fromLoudPlain, SR, 0, 0.15), tE, sE, lE);
+ ok(gOn < gOff * 0.6, `held-out middle layer: the softened loud take lands nearer the real one (${gOn.toFixed(2)} vs ${gOff.toFixed(2)})`);
+ ok(ruled(bandEnvelope(asIs, SR, 0, 0.15), tE, sE, lE) < 0.05, "a blow at a recorded layer plays that take untouched");
+ // a key between recorded pitches: the colour is read between its neighbours
+ const shifted = toneColour(grand, grand.zones.find((z) => z.zone.midi === 60 && z.zone.layer === 2)!, 62, 0.5)!;
+ ok(Array.isArray(shifted) && shifted.length === PIANO_BANDS.length, "a moved take gets a colour from the keys either side");
+ ok(toneColour(grand, grand.zones.find((z) => z.zone.midi === 64 && z.zone.layer === 2)!, 66, 0.5) === null, "past the last recorded key there is no neighbour to read, so nothing changes");
+ // filters land on the colour asked for
+ let seed = 12345; const noise = Float32Array.from({ length: SR }, () => ((seed = (seed * 1103515245 + 12345) >>> 0) / 2 ** 32) - 0.5);
+ const want = PIANO_BANDS.map((f) => (f > 1000 ? -9 : 0)), fs = colourFilters(want, SR), shaped = Float32Array.from(noise); for (const f of fs) f.run(shaped);
+ const resp = bandEnvelope(shaped, SR, 0, 1), ref = bandEnvelope(noise, SR, 0, 1);
+ const err = [8, 10, 12, 14].map((j) => Math.abs(resp[j] - ref[j] - want[j]));
+ ok(Math.max(...err) < 2, `octave filters land within 2 dB of the colour at the octave centres (worst ${Math.max(...err).toFixed(2)} dB)`);
+ ok(colourFilters(PIANO_BANDS.map(() => 0), SR).length === 0, "a flat colour builds no filters");
+
+ // two-band release
+ ok(releaseLow(24, 0.5) === 0.5 * RELEASE_SPLIT.lowMul && releaseLow(60, 0.1) === 0.1 && releaseLow(84, 0.08) === 0.08, "the low band lingers longest at the bottom and not at all from middle C up");
+ const lowKey = registerBank("piano", bank("piano", [36, 40], 1)), keyUp = 0.6;
+ const twoBand = samplerVoice(lowKey, [key(36, 0.8, keyUp)], [], SR, SR * 2, {}, 1).L, flatRel = samplerVoice(lowKey, [key(36, 0.8, keyUp)], [], SR, SR * 2, { release: "flat" }, 1).L;
+ const bands: [number, number][] = [[30, 250], [500, 1000]], r2 = bandDecay(twoBand, SR, keyUp, 0.02, 0.2, bands), r1 = bandDecay(flatRel, SR, keyUp, 0.02, 0.2, bands);
+ ok(r2[0] < r1[0] * 0.6, `two-band: the bass hum falls slower after key-up (${r2[0].toFixed(0)} vs ${r1[0].toFixed(0)} dB/s)`);
+ ok(Math.abs(r2[1] - r1[1]) < r1[1] * 0.25, `two-band: the upper partials still stop as fast (${r2[1].toFixed(0)} vs ${r1[1].toFixed(0)} dB/s)`);
+ const before = Math.round(0.5 * SR); ok(twoBand.slice(0, before).every((x, i) => Math.abs(x - flatRel[i]) < 1e-6), "before key-up the split sums back to the take exactly");
+ const up = registerBank("piano.upright", bank("piano.upright", [36, 40], 1)), u2 = samplerVoice(up, [key(36, 0.8, keyUp)], [], SR, SR * 2, {}, 1).L, u1 = samplerVoice(up, [key(36, 0.8, keyUp)], [], SR, SR * 2, { release: "flat" }, 1).L;
+ ok(u2.every((x, i) => x === u1[i]), "the upright keeps its single-rate release unless asked");
+ } finally { clearBanks(); }
+};
diff --git a/skills/anidoodle/engine/tools/pianoruler.mjs b/skills/anidoodle/engine/tools/pianoruler.mjs
new file mode 100644
index 0000000..9c241a9
--- /dev/null
+++ b/skills/anidoodle/engine/tools/pianoruler.mjs
@@ -0,0 +1,72 @@
+// PIANO RULER. Holds each recording of the grand out in turn, plays that note from what is left, and
+// scores the result against the real take it replaced. The unit is the real piano's own soft-to-loud
+// change at that key (1.0 = a whole dynamic step off), so "sounds wrong" becomes a number.
+// node tools/pianoruler.mjs [--sounds <pack>] [--bank piano] [--json out.json] [--set key=value ...]
+// Three probes: velocity (a layer held out, played from its neighbour), pitch (a whole key held out,
+// played from the recording four keys away) and release (key-up decay per band against the recorded
+// release takes). `--set velocityTone=lowpass` or `--set release=flat` replays the older behaviour, so
+// one change at a time can be judged by whether it moves the number. The release probe needs release
+// takes that hold the string's own dying ring (the grand's do; the upright's are key noise, so its
+// release row is not a real measure).
+import { build } from "esbuild";
+import { writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { loadBanks } from "./sounds.mjs";
+import { soundsDir } from "./soundfetch.mjs";
+
+const here = dirname(fileURLToPath(import.meta.url)), SR = 48000;
+const args = process.argv.slice(2), val = (k, d) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : d; };
+const sets = args.flatMap((a, i) => (a === "--set" ? [args[i + 1]] : [])).map((s) => s.split("="));
+const opts = Object.fromEntries(sets.map(([k, v]) => [k, v === "true" ? true : v === "false" ? false : Number.isFinite(Number(v)) ? Number(v) : v]));
+const bankId = val("--bank", "piano"), dir = val("--sounds", process.env.ANIDOODLE_SOUNDS || soundsDir());
+
+const r = await build({ stdin: { contents: `export * from "./index"; export * as Ruler from "./pianoRuler";`, resolveDir: join(here, "../src/canvas-core/music"), loader: "ts" }, bundle: true, write: false, format: "esm", platform: "neutral", target: "es2022", logLevel: "error" });
+const M = await import("data:text/javascript;base64," + Buffer.from(r.outputFiles[0].text).toString("base64"));
+const U = M.Ruler, log = console.log; console.log = () => {}; loadBanks(M, dir, [bankId]); console.log = log;
+const [inst, ...variant] = bankId.split("."), bank = M.bankFor(inst, variant.join(".") || undefined);
+if (!bank) { console.error(`pianoruler: no bank ${bankId} in ${dir}`); process.exit(2); }
+
+const e = bank.entry, ord = bank.zones.filter((z) => !z.zone.art), pitches = [...new Set(ord.map((z) => z.zone.midi))].sort((a, b) => a - b);
+const layerV = (l) => e.layerVelocity?.[l - 1] ?? (l - 0.5) / e.layers;
+const take = (p, l, art) => bank.zones.find((z) => z.zone.midi === p && z.zone.layer === l && z.zone.art === art);
+const play = (zones, p, v, off, secs) => { const n = Math.round(secs * SR), out = M.samplerVoice({ ...bank, zones }, [{ p, v, tone: v, t: 0.05, off, role: "melody", w: v }], [], SR, n, opts, 7); return U.mono([out.L, out.R]); };
+const W = U.RULER_WINDOWS, env = (x, w) => U.bandEnvelope(x, SR, w[0], w[1]), cents = (a, b) => 1200 * Math.log2(a / b);
+const mean = (xs) => { const f = xs.filter(Number.isFinite); return f.length ? f.reduce((s, x) => s + x, 0) / f.length : NaN; };
+const f2 = (x) => (Number.isFinite(x) ? x.toFixed(2) : " - ");
+
+// the ruler at each key: real soft take vs real loud take, attack and body windows
+const ruler = new Map(pitches.map((p) => { const s = U.mono(take(p, 1).channels), l = U.mono(take(p, e.layers).channels); return [p, { s, l, attack: [env(s, W.attack), env(l, W.attack)], body: [env(s, W.body), env(l, W.body)] }]; }));
+const score = (x, truth, p) => { const R = ruler.get(p); return { attack: U.ruled(env(x, W.attack), env(truth, W.attack), ...R.attack), body: U.ruled(env(x, W.body), env(truth, W.body), ...R.body), cents: cents(U.centroidHz(x, SR, ...W.centroid), U.centroidHz(truth, SR, ...W.centroid)) }; };
+
+const velocity = [], pitch = [], release = [];
+for (const p of pitches) {
+ for (let h = 1; h <= e.layers; h++) {
+ const truth = take(p, h); if (!truth) continue;
+ const x = play(bank.zones.filter((z) => z !== truth), p, layerV(h), 3.2, 3.5);
+ velocity.push({ p, layer: h, ...score(x, U.mono(truth.channels), p) });
+ }
+ const mid = take(p, Math.ceil(e.layers / 2));
+ if (mid && pitches.some((q) => Math.abs(q - p) === 4)) pitch.push({ p, ...score(play(bank.zones.filter((z) => z.zone.midi !== p), p, layerV(mid.zone.layer), 3.2, 3.5), U.mono(mid.channels), p) });
+ const rel = take(p, Math.ceil(e.layers / 2), "rel");
+ if (mid && rel) {
+ const bands = [[30, 250], [250, 1000], [1000, 4000]], keyUp = 1.05;
+ const truthR = U.bandDecay(U.mono(rel.channels), SR, U.onsetOf(U.mono(rel.channels)) / SR, 0.02, 0.2, bands, -40);
+ const held = play(bank.zones, p, layerV(mid.zone.layer), keyUp, 1.6), ring = play(bank.zones, p, layerV(mid.zone.layer), 3.2, 1.6);
+ const played = U.bandDecay(held, SR, keyUp, 0.02, 0.2, bands, -40), natural = U.bandDecay(ring, SR, keyUp, 0.02, 0.2, bands, -40);
+ // 1.0 = as far from the real release as not damping at all
+ const off = bands.map((_, j) => Math.abs(played[j] - truthR[j]) / Math.max(20, Math.abs(truthR[j] - natural[j])));
+ release.push({ p, truth: truthR, played, natural, ruled: mean(off) });
+ }
+}
+
+const summary = { bank: bankId, opts, velocity: { attack: mean(velocity.map((r) => r.attack)), body: mean(velocity.map((r) => r.body)), absCents: mean(velocity.map((r) => Math.abs(r.cents))) }, pitch: { attack: mean(pitch.map((r) => r.attack)), body: mean(pitch.map((r) => r.body)), absCents: mean(pitch.map((r) => Math.abs(r.cents))) }, release: { ruled: mean(release.map((r) => r.ruled)) } };
+log(`piano ruler: ${bankId}${sets.length ? ` (${sets.map((s) => s.join("=")).join(", ")})` : ""} 1.00 = one whole soft-to-loud step off`);
+log("\nvelocity key layer attack body centroid cents");
+for (const v of velocity) log(` ${String(v.p).padStart(3)} ${v.layer} ${f2(v.attack)} ${f2(v.body)} ${v.cents.toFixed(0)}`);
+log("\npitch key attack body centroid cents (played from four keys away)");
+for (const v of pitch) log(` ${String(v.p).padStart(3)} ${f2(v.attack)} ${f2(v.body)} ${v.cents.toFixed(0)}`);
+log("\nrelease key dB/s low/mid/high: real | played | undamped ruled");
+for (const v of release) log(` ${String(v.p).padStart(3)} ${v.truth.map((x) => f2(x).padStart(6)).join("")} | ${v.played.map((x) => f2(x).padStart(6)).join("")} | ${v.natural.map((x) => f2(x).padStart(6)).join("")} ${f2(v.ruled)}`);
+log(`\nMEAN velocity attack ${f2(summary.velocity.attack)} body ${f2(summary.velocity.body)} |centroid| ${summary.velocity.absCents.toFixed(0)} c pitch attack ${f2(summary.pitch.attack)} body ${f2(summary.pitch.body)} |centroid| ${summary.pitch.absCents.toFixed(0)} c release ${f2(summary.release.ruled)}`);
+const out = val("--json"); if (out) writeFileSync(out, JSON.stringify({ summary, velocity, pitch, release }, null, 1));
diff --git a/skills/anidoodle/references/music/README.md b/skills/anidoodle/references/music/README.md
index 2276cae..7c2cdb9 100644
--- a/skills/anidoodle/references/music/README.md
+++ b/skills/anidoodle/references/music/README.md
@@ -194,6 +194,17 @@ drums and every sound effect are code and stay code.
- **Soft playing keeps a real attack.** The Steinway bank has three velocity layers and its source
was normalized, so soft notes come from the soft recording with the modeled piano's velocity law
rather than a quiet copy of a loud one. Do not add an attack that isn't there.
+- **Between layers and between keys, the tone follows the real takes.** A velocity between two
+ layers plays the louder take softened to the colour read between the real takes of that key
+ (a softer blow is darker, not only quieter), and a key between two recordings takes the colour
+ of the recordings either side, so a moved take does not drag its body resonances along. Both
+ piano banks do this; `opts: { velocityTone: "lowpass" }` brings back the older single filter.
+- **Key-up lets the bass hum.** On the grand the felt stops the upper partials at once while the
+ lowest strings keep a low hum for a moment, as the recorded release takes do.
+ `opts: { release: "flat" }` damps every frequency at one rate.
+- **Measure before you tune.** `node tools/pianoruler.mjs` holds each recording out in turn, plays
+ it from what is left and scores the gap in the real piano's own soft-to-loud steps (1.0 = a
+ whole step off). Change one thing, rerun, keep it only if the number moves the right way.
- **A real marimba's low notes are rich.** D2 to C4 carries as much as the top of the instrument.
Keep bass lines out of the melody's register rather than reaching down for the modeled marimba's
thin bass.