/ simulated_instruments / maraca
Sign in
simulated_instruments / maraca
maraca / instrument / test.ts
113 lines · 4.1 KBCodeBlameHistory
373d415Add instrument/: the maraca behind the track-render interfaceJeremy Magland 1// Node-side test of the maraca track-render instrument: executes the
2// actual MATLAB model through numbl (no browser, no worker) and checks the
3// audio. Run 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++;
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 };
39const SR = 22050;
41function req(notes: NoteSpec[], overrides: Partial<TrackRenderRequest> = {}): TrackRenderRequest {
42 const end = notes.reduce((m, n) => Math.max(m, n.timeSec + n.durationSec), 0);
43 return {
44 notes,
45 sampleRate: SR,
46 lengthSamples: Math.ceil((end + 1.0) * SR),
47 quality: 'preview',
48 settings: {},
49 ...overrides,
50 };
53const note = (timeSec: number, pitch: number, velocity: number): NoteSpec =>
54 ({ timeSec, durationSec: 0.1, pitch, velocity });
56const t0 = performance.now();
58// One stroke: finite, audible, decaying.
59const a = await renderRequest('maraca', req([note(0, 60, 0.7)]), env);
61 const s = stats(a.audio);
62 check('single stroke is finite', s.finite);
63 check('single stroke is audible', s.peak > 1e-5, `peak ${s.peak.toExponential(2)}`);
64 const n = a.audio.length;
65 const head = stats(a.audio.slice(0, Math.floor(n / 3))).peak;
66 const tail = stats(a.audio.slice(Math.floor((2 * n) / 3))).peak;
67 check('single stroke decays', tail < head * 0.8, `head ${head.toExponential(2)} tail ${tail.toExponential(2)}`);
70// The note cache.
72 const t = performance.now();
73 await renderRequest('maraca', req([note(0, 60, 0.7)]), env);
74 const ms = performance.now() - t;
75 check('repeat render hits the note cache', ms < 250, `${ms.toFixed(0)} ms`);
78// Velocity changes the sound (normalize is off, so amplitude scales).
79const soft = await renderRequest('maraca', req([note(0, 60, 0.2)]), env);
81 const pa = stats(a.audio).peak;
82 const ps = stats(soft.audio).peak;
83 check('velocity changes the sound', ps < pa, `soft ${ps.toExponential(2)} < hard ${pa.toExponential(2)}`);
86// Pitch and knobs change the sound.
87const high = await renderRequest('maraca', req([note(0, 67, 0.7)]), env);
89 let diff = high.audio.length !== a.audio.length;
90 if (!diff) for (let i = 0; i < a.audio.length; i++) if (Math.abs(a.audio[i] - high.audio[i]) > 1e-9) { diff = true; break; }
91 check('pitch changes the sound', diff);
93const sparse = await renderRequest('maraca', req([note(0, 60, 0.7)], { settings: { grain_count: 60 } }), env);
95 let diff = false;
96 const n = Math.min(a.audio.length, sparse.audio.length);
97 for (let i = 0; i < n; i++) if (Math.abs(a.audio[i] - sparse.audio[i]) > 1e-9) { diff = true; break; }
98 check('grain_count knob changes the sound', diff);
101// A pattern: repeats from the cache, distinct sounds at their onsets.
102const tr = await renderRequest('maraca', req([note(0, 60, 0.7), note(0.5, 60, 0.7), note(1.0, 67, 0.7)]), env);
104 const s = stats(tr.audio);
105 check('track render is finite', s.finite);
106 const at = (sec: number) => stats(tr.audio.slice(Math.floor(sec * SR), Math.floor((sec + 0.25) * SR))).peak;
107 check('energy at first onset', at(0.0) > 1e-5);
108 check('energy at second onset', at(0.5) > 1e-5);
109 check('energy at third onset', at(1.0) > 1e-5);
112console.log(`total time: ${((performance.now() - t0) / 1000).toFixed(1)} s`);
113if (failures > 0) { console.error(`${failures} check(s) failed`); process.exit(1); }
↑↓ move↵openescclose