afd5157Add instrument/: the bass behind the track-render interfaceJeremy Magland 1// Node-side test of the bass track-render instrument: executes the actual
2// MATLAB model through numbl (no browser, no worker) and checks the audio.
3// Run from webapp/ or here with: npx tsx test.ts
4import { readdirSync, readFileSync } from 'node:fs';
5import { join, dirname } from 'node:path';
6import { fileURLToPath } from 'node:url';
7import { renderRequest, type RenderEnv } from './core.ts';
8import type { NoteSpec, TrackRenderRequest } from './types.ts';
10const matlabDir = join(dirname(fileURLToPath(import.meta.url)), '..', 'matlab');
11const mfiles = readdirSync(matlabDir)
12 .filter((f) => f.endsWith('.m'))
13 .sort()
14 .map((f) => ({ name: f, source: readFileSync(join(matlabDir, f), 'utf8') }));
16const env: RenderEnv = {
17 mfiles,
18 post: () => {},
19 checkCancel: () => {},
20 yieldToHost: async () => {},
21};
23let failures = 0;
24function check(label: string, ok: boolean, detail = ''): void {
25 console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${detail ? ` (${detail})` : ''}`);
26 if (!ok) failures++;
27}
29function stats(y: Float32Array) {
30 let peak = 0;
31 let finite = true;
32 for (let i = 0; i < y.length; i++) {
33 if (!Number.isFinite(y[i])) finite = false;
34 peak = Math.max(peak, Math.abs(y[i]));
35 }
36 return { peak, finite };
37}
39function req(notes: NoteSpec[], overrides: Partial<TrackRenderRequest> = {}): TrackRenderRequest {
40 const end = notes.reduce((m, n) => Math.max(m, n.timeSec + n.durationSec), 0);
41 return {
42 notes,
43 sampleRate: 22050,
44 lengthSamples: Math.ceil((end + 1.5) * 22050),
45 quality: 'preview',
46 settings: { tail_s: 1 },
47 ...overrides,
48 };
49}
51const note = (timeSec: number, pitch: number, velocity: number): NoteSpec =>
52 ({ timeSec, durationSec: 0.5, pitch, velocity });
54const t0 = performance.now();
56// One note: finite, audible, decaying tail.
57const a = await renderRequest('bass', req([note(0, 36, 0.7)]), env);
58{
59 const s = stats(a.audio);
60 check('single note is finite', s.finite);
61 check('single note is audible', s.peak > 1e-4, `peak ${s.peak.toExponential(2)}`);
62 const n = a.audio.length;
63 const head = stats(a.audio.slice(0, Math.floor(n / 3))).peak;
64 const tail = stats(a.audio.slice(Math.floor((2 * n) / 3))).peak;
65 check('single note decays', tail < head * 0.8, `head ${head.toExponential(2)} tail ${tail.toExponential(2)}`);
66}
68// Determinism: the identical request renders identical audio.
69const b = await renderRequest('bass', req([note(0, 36, 0.7)]), env);
70{
71 let same = a.audio.length === b.audio.length;
72 if (same) for (let i = 0; i < a.audio.length; i++) if (a.audio[i] !== b.audio[i]) { same = false; break; }
73 check('render is deterministic', same);
74}
76// The second identical render must come from the note cache (no numbl run).
77{
78 const t = performance.now();
79 await renderRequest('bass', req([note(0, 36, 0.7)]), env);
80 const ms = performance.now() - t;
81 check('repeat render hits the note cache', ms < 250, `${ms.toFixed(0)} ms`);
82}
84// Velocity and knobs change the sound; a repeated pitch shares the solve.
85const soft = await renderRequest('bass', req([note(0, 36, 0.2)]), env);
86{
87 const pa = stats(a.audio).peak;
88 const ps = stats(soft.audio).peak;
89 check('velocity changes the sound', ps < pa, `soft ${ps.toExponential(2)} < hard ${pa.toExponential(2)}`);
90}
91const bridge = await renderRequest('bass', req([note(0, 36, 0.7)], { settings: { tail_s: 1, pluck_pos: 0.08 } }), env);
92{
93 let diff = false;
94 const n = Math.min(a.audio.length, bridge.audio.length);
95 for (let i = 0; i < n; i++) if (Math.abs(a.audio[i] - bridge.audio[i]) > 1e-9) { diff = true; break; }
96 check('pluck_pos knob changes the sound', diff);
97}
99// A track: two pitches and a repeat; the repeat is placed, not re-rendered,
100// and the mixed buffer has energy at both onsets.
101const tr = await renderRequest('bass', req([note(0, 36, 0.7), note(0.8, 43, 0.7), note(1.6, 36, 0.7)]), env);
102{
103 const s = stats(tr.audio);
104 check('track render is finite', s.finite);
105 const at = (sec: number) => stats(tr.audio.slice(Math.floor(sec * 22050), Math.floor((sec + 0.3) * 22050))).peak;
106 check('energy at first onset', at(0.0) > 1e-4);
107 check('energy at second onset', at(0.8) > 1e-4);
108 check('energy at third onset', at(1.6) > 1e-4);
109 const asked = req([note(0, 36, 0.7), note(0.8, 43, 0.7), note(1.6, 36, 0.7)]).lengthSamples;
110 check('buffer covers the requested length', tr.audio.length >= asked, `${tr.audio.length} >= ${asked}`);
111 const lastOnset = Math.round(1.6 * 22050);
112 check('final tail is not clipped', tr.audio.length >= lastOnset, 'ring extends past the last onset');
113}
115// The muted variant differs from the standup.
116const muted = await renderRequest('bass-muted', req([note(0, 36, 0.7)], { settings: {} }), env);
117{
118 let diff = muted.audio.length !== a.audio.length;
119 if (!diff) for (let i = 0; i < a.audio.length; i++) if (Math.abs(a.audio[i] - muted.audio[i]) > 1e-9) { diff = true; break; }
120 check('muted variant differs', diff);
121}
123console.log(`total time: ${((performance.now() - t0) / 1000).toFixed(1)} s`);
124if (failures > 0) { console.error(`${failures} check(s) failed`); process.exit(1); }