1// Deterministic node-side tests: MIDI round trip, tempo math, editing
2// ops, DSP determinism, and mixing rules. Run with: npm test
4import assert from 'node:assert/strict';
5import { TempoMap } from '../src/midi/time.ts';
6import { parseMidi } from '../src/midi/parse.ts';
7import { writeMidi } from '../src/midi/write.ts';
8import { quantizeNotes, transposeNotes } from '../src/midi/ops.ts';
9import { drumNote, epianoNote, leadNote, pluckNote } from '../src/instruments/dsp.ts';
10import { builtinInstruments } from '../src/instruments/builtins.ts';
11import { audibleTracks, encodeWavMono16, mixTracks, trackRenderKey } from '../src/audio/render.ts';
12import { bucketVelocity, mapPitch, mapVelocity, parseManifest } from '../src/instruments/simulated/manifest.ts';
13import { readdirSync, readFileSync, existsSync } from 'node:fs';
14import { join } from 'node:path';
15import type { Note, Song, Track } from '../src/types.ts';
17let failed = 0;
18let passed = 0;
19function test(name: string, fn: () => void) {
20 try {
21 fn();
22 passed++;
23 console.log(`ok - ${name}`);
24 } catch (err) {
25 failed++;
26 console.error(`FAIL - ${name}`);
27 console.error(err);
28 }
29}
31function close(a: number, b: number, tol = 1e-9) {
32 assert.ok(Math.abs(a - b) <= tol, `${a} !~ ${b}`);
33}
35function hash(buf: Float32Array): number {
36 let h = 0x811c9dc5;
37 for (let i = 0; i < buf.length; i++) {
38 h ^= Math.round(buf[i] * 1e6) & 0xffff;
39 h = Math.imul(h, 0x01000193);
40 }
41 return h >>> 0;
42}
44function mkNote(tick: number, duration: number, pitch: number, velocity: number, id: string): Note {
45 return { id, tick, duration, pitch, velocity };
46}
48function mkTrack(id: string, instrumentId: string, notes: Note[], extra: Partial<Track> = {}): Track {
49 return { id, name: id, instrumentId, volume: 1, mute: false, solo: false, notes, ...extra };
50}
52// --- tempo map ---
54test('tempo map: constant 120 bpm', () => {
55 const tm = new TempoMap(480, [{ tick: 0, usPerQuarter: 500000 }]);
56 close(tm.tickToSec(480), 0.5);
57 close(tm.tickToSec(1920), 2);
58 close(tm.secToTick(1), 960);
59 close(tm.bpmAt(0), 120);
60});
62test('tempo map: tempo change mid-song', () => {
63 const tm = new TempoMap(480, [
64 { tick: 0, usPerQuarter: 500000 },
65 { tick: 960, usPerQuarter: 250000 },
66 ]);
67 close(tm.tickToSec(960), 1);
68 close(tm.tickToSec(1920), 1.5);
69 close(tm.secToTick(1.25), 1440);
70 close(tm.bpmAt(1000), 240);
71});
73test('tempo map: bar.beat display in 4/4 and 3/4', () => {
74 const tm44 = new TempoMap(480, [], [{ tick: 0, numerator: 4, denominator: 4 }]);
75 assert.deepEqual(tm44.barBeatAt(0), { bar: 1, beat: 1 });
76 assert.deepEqual(tm44.barBeatAt(480 * 5), { bar: 2, beat: 2 });
77 const tm34 = new TempoMap(480, [], [{ tick: 0, numerator: 3, denominator: 4 }]);
78 assert.deepEqual(tm34.barBeatAt(480 * 3), { bar: 2, beat: 1 });
79});
81test('tempo map: grid lines mark bars', () => {
82 const tm = new TempoMap(480, [], [{ tick: 0, numerator: 4, denominator: 4 }]);
83 const lines = tm.gridLines(0, 1920);
84 assert.equal(lines.length, 4);
85 assert.deepEqual(lines[0], { tick: 0, isBar: true });
86 assert.deepEqual(lines[1], { tick: 480, isBar: false });
87});
89// --- MIDI round trip ---
91function sortedNotes(t: Track): [number, number, number, number][] {
92 return t.notes
93 .map((n) => [n.tick, n.duration, n.pitch, n.velocity] as [number, number, number, number])
94 .sort((a, b) => a[0] - b[0] || a[2] - b[2]);
95}
97test('MIDI write/parse round trip preserves notes, tempo, and drums', () => {
98 const song: Song = {
99 ppq: 480,
100 tempo: [
101 { tick: 0, usPerQuarter: 500000 },
102 { tick: 1920, usPerQuarter: 400000 },
103 ],
104 timeSig: [{ tick: 0, numerator: 3, denominator: 4 }],
105 tracks: [
106 mkTrack('melody', 'pluck', [
107 mkNote(0, 480, 60, 100, 'a'),
108 mkNote(480, 240, 64, 90, 'b'),
109 mkNote(100000, 960, 72, 127, 'c'), // multi-byte delta times
110 mkNote(480, 240, 67, 1, 'd'), // chord + min velocity
111 ]),
112 mkTrack('kit', 'drumkit', [
113 mkNote(0, 120, 36, 110, 'e'),
114 mkNote(480, 120, 38, 80, 'f'),
115 ]),
116 ],
117 };
118 const bytes = writeMidi(song);
119 const back = parseMidi(bytes);
120 assert.equal(back.ppq, 480);
121 assert.equal(back.tracks.length, 2);
122 assert.deepEqual(sortedNotes(back.tracks[0]), sortedNotes(song.tracks[0]));
123 assert.deepEqual(sortedNotes(back.tracks[1]), sortedNotes(song.tracks[1]));
124 assert.equal(back.tracks[0].name, 'melody');
125 assert.equal(back.tracks[1].instrumentId, 'drumkit'); // came back on channel 10
126 assert.equal(back.tracks[0].instrumentId, 'pluck');
127 assert.deepEqual(back.tempo, song.tempo);
128 assert.equal(back.timeSig[0].numerator, 3);
129 assert.equal(back.timeSig[0].denominator, 4);
130});
132test('parse splits a multi-channel track by channel', () => {
133 const song: Song = {
134 ppq: 480,
135 tempo: [{ tick: 0, usPerQuarter: 500000 }],
136 timeSig: [{ tick: 0, numerator: 4, denominator: 4 }],
137 tracks: [
138 mkTrack('a', 'pluck', [mkNote(0, 480, 60, 100, 'a')]),
139 mkTrack('b', 'drumkit', [mkNote(0, 120, 42, 100, 'b')]),
140 ],
141 };
142 // write produces separate MTrks; merging them into one channel-mixed
143 // stream is what a format 0 file would look like, so parse the format 1
144 // bytes and just confirm channels landed apart.
145 const back = parseMidi(writeMidi(song));
146 assert.equal(back.tracks.length, 2);
147 assert.equal(back.tracks[1].instrumentId, 'drumkit');
148});
150// --- editing ops ---
152test('quantize rounds note starts to the grid', () => {
153 const notes = [mkNote(130, 100, 60, 100, 'a'), mkNote(59, 100, 61, 100, 'b')];
154 const q = quantizeNotes(notes, 120);
155 assert.equal(q[0].tick, 120);
156 assert.equal(q[1].tick, 0); // 59 rounds down to the grid origin
157 const onlyA = quantizeNotes(notes, 120, new Set(['a']));
158 assert.equal(onlyA[0].tick, 120);
159 assert.equal(onlyA[1].tick, 59);
160});
162test('transpose clamps to the MIDI range', () => {
163 const notes = [mkNote(0, 100, 126, 100, 'a')];
164 assert.equal(transposeNotes(notes, 12)[0].pitch, 127);
165 assert.equal(transposeNotes(notes, -300)[0].pitch, 0);
166});
168// --- DSP ---
170test('DSP is deterministic and finite', () => {
171 for (const [name, fn] of [
172 ['pluck', pluckNote],
173 ['epiano', epianoNote],
174 ['lead', leadNote],
175 ['drum', drumNote],
176 ] as const) {
177 const a = fn(44100, name === 'drum' ? 38 : 60, 0.8, 0.4);
178 const b = fn(44100, name === 'drum' ? 38 : 60, 0.8, 0.4);
179 assert.equal(hash(a), hash(b), `${name} not deterministic`);
180 assert.ok(a.length > 1000, `${name} too short`);
181 let peak = 0;
182 for (let i = 0; i < a.length; i++) {
183 assert.ok(Number.isFinite(a[i]), `${name} produced non-finite sample`);
184 peak = Math.max(peak, Math.abs(a[i]));
185 }
186 assert.ok(peak > 0.01, `${name} is silent`);
187 assert.ok(peak <= 1.5, `${name} peak too hot: ${peak}`);
188 }
189});
191test('builtin instrument render places notes at the right time', () => {
192 const pluck = builtinInstruments.find((i) => i.id === 'pluck')!;
193 const sr = 44100;
194 const out = pluck.render({
195 notes: [{ timeSec: 1, durationSec: 0.25, pitch: 69, velocity: 0.8 }],
196 sampleRate: sr,
197 lengthSamples: sr * 3,
198 }) as Float32Array;
199 assert.equal(out.length, sr * 3);
200 let before = 0;
201 for (let i = 0; i < sr - 10; i++) before = Math.max(before, Math.abs(out[i]));
202 let after = 0;
203 for (let i = sr; i < sr * 2; i++) after = Math.max(after, Math.abs(out[i]));
204 assert.equal(before, 0);
205 assert.ok(after > 0.01);
206});
208// --- mixing ---
210test('mute and solo select audible tracks', () => {
211 const a = mkTrack('a', 'pluck', []);
212 const b = mkTrack('b', 'pluck', [], { mute: true });
213 const c = mkTrack('c', 'pluck', []);
214 assert.deepEqual([...audibleTracks([a, b, c])].sort(), ['a', 'c']);
215 const cSolo = { ...c, solo: true };
216 assert.deepEqual([...audibleTracks([a, b, cSolo])], ['c']);
217});
219test('mixTracks applies volume and excludes muted tracks', () => {
220 const a = mkTrack('a', 'pluck', [], { volume: 0.5 });
221 const b = mkTrack('b', 'pluck', [], { mute: true });
222 const buffers = new Map<string, Float32Array>([
223 ['a', new Float32Array([0.4, 0.4])],
224 ['b', new Float32Array([0.9, 0.9])],
225 ]);
226 const mix = mixTracks([a, b], buffers);
227 close(mix[0], 0.2, 1e-6);
228});
230test('trackRenderKey changes when the notes change', () => {
231 const song: Song = {
232 ppq: 480,
233 tempo: [{ tick: 0, usPerQuarter: 500000 }],
234 timeSig: [{ tick: 0, numerator: 4, denominator: 4 }],
235 tracks: [],
236 };
237 const t1 = mkTrack('a', 'pluck', [mkNote(0, 480, 60, 100, 'a')]);
238 const t2 = mkTrack('a', 'pluck', [mkNote(0, 480, 61, 100, 'a')]);
239 const t3 = mkTrack('a', 'epiano', [mkNote(0, 480, 60, 100, 'a')]);
240 assert.equal(trackRenderKey(song, t1), trackRenderKey(song, mkTrack('a', 'pluck', [mkNote(0, 480, 60, 100, 'zzz')])));
241 assert.notEqual(trackRenderKey(song, t1), trackRenderKey(song, t2));
242 assert.notEqual(trackRenderKey(song, t1), trackRenderKey(song, t3));
243});
245test('WAV encoding writes a well-formed header', () => {
246 const wav = encodeWavMono16(new Float32Array([0, 0.5, -0.5, 2]), 44100);
247 assert.equal(wav.length, 44 + 8);
248 assert.equal(String.fromCharCode(...wav.subarray(0, 4)), 'RIFF');
249 assert.equal(String.fromCharCode(...wav.subarray(8, 12)), 'WAVE');
250 const dv = new DataView(wav.buffer);
251 assert.equal(dv.getUint32(24, true), 44100);
252 assert.equal(dv.getInt16(44 + 6, true), 32767); // clipped to full scale
253});
255// --- simulated-instrument manifests ---
257const SIM_ROOT = join(import.meta.dirname, '../../../simulated_instruments');
259test('every instrument.json in ../simulated_instruments validates', () => {
260 if (!existsSync(SIM_ROOT)) return; // vault layout absent; nothing to check
261 const dirs = readdirSync(SIM_ROOT).filter((d) => existsSync(join(SIM_ROOT, d, 'instrument.json')));
262 assert.ok(dirs.length >= 1, 'no manifests found');
263 for (const d of dirs) {
264 const m = parseManifest(readFileSync(join(SIM_ROOT, d, 'instrument.json'), 'utf8'));
265 assert.equal(m.name, d, `manifest name '${m.name}' should match its directory '${d}'`);
266 assert.ok(existsSync(join(SIM_ROOT, d, 'matlab', `${m.entry}.m`)), `${d}: entry ${m.entry}.m missing`);
267 assert.ok(existsSync(join(SIM_ROOT, d, 'matlab', `${m.defaults}.m`)), `${d}: defaults ${m.defaults}.m missing`);
268 }
269});
271test('manifest pitch and velocity mapping', () => {
272 const m = parseManifest(JSON.stringify({
273 format: 'simulated-instrument-v1', name: 't', label: 'T', entry: 'e', defaults: 'd',
274 fixed: {}, preview: {},
275 pitch: { param: 'root_midi', mode: 'midi', min: 28, max: 55 },
276 velocity: { param: 'force', min: 2, max: 12 },
277 knobs: [],
278 }));
279 assert.deepEqual(mapPitch(m, 40), { key: 'root_midi', value: 40 });
280 assert.deepEqual(mapPitch(m, 10), { key: 'root_midi', value: 28 }); // clamped
281 assert.deepEqual(mapVelocity(m, 0), { key: 'force', value: 2 });
282 assert.deepEqual(mapVelocity(m, 1), { key: 'force', value: 12 });
283 const t = parseManifest(JSON.stringify({
284 format: 'simulated-instrument-v1', name: 't2', label: 'T', entry: 'e', defaults: 'd',
285 fixed: {}, preview: {},
286 pitch: { param: 'note1', mode: 'table', table: [{ midi: 72, value: 1 }, { midi: 74, value: 2 }] },
287 velocity: { param: 'v', min: 0, max: 1 },
288 knobs: [],
289 }));
290 assert.deepEqual(mapPitch(t, 73), { key: 'note1', value: 1 }); // nearest, ties go low
291 assert.deepEqual(mapPitch(t, 90), { key: 'note1', value: 2 });
292 const un = parseManifest(JSON.stringify({
293 format: 'simulated-instrument-v1', name: 't3', label: 'T', entry: 'e', defaults: 'd',
294 fixed: {}, preview: {}, velocity: { param: 'v', min: 0, max: 1 }, knobs: [],
295 }));
296 assert.equal(mapPitch(un, 60), null);
297});
299test('velocity bucketing quantizes into few levels', () => {
300 assert.equal(bucketVelocity(1), 1);
301 assert.equal(bucketVelocity(0.999), 1);
302 assert.equal(bucketVelocity(0.51), 0.625);
303 assert.equal(bucketVelocity(0.01), 0.125);
304 assert.ok(bucketVelocity(0) > 0);
305});
307test('manifest validation rejects malformed knobs', () => {
308 assert.throws(() => parseManifest(JSON.stringify({
309 format: 'simulated-instrument-v1', name: 'x', label: 'X', entry: 'e', defaults: 'd',
310 fixed: {}, preview: {}, velocity: { param: 'v', min: 0, max: 1 },
311 knobs: [{ key: 'k', label: 'K', min: 5, max: 1, default: 2 }],
312 })));
313 assert.throws(() => parseManifest(JSON.stringify({
314 format: 'wrong', name: 'x', label: 'X', entry: 'e', defaults: 'd',
315 fixed: {}, preview: {}, velocity: { param: 'v', min: 0, max: 1 }, knobs: [],
316 })));
317});
319console.log(`\n${passed} passed, ${failed} failed`);
320process.exit(failed > 0 ? 1 : 0);