// Deterministic node-side tests: MIDI round trip, tempo math, editing // ops, DSP determinism, and mixing rules. Run with: npm test import assert from 'node:assert/strict'; import { TempoMap } from '../src/midi/time.ts'; import { parseMidi } from '../src/midi/parse.ts'; import { writeMidi } from '../src/midi/write.ts'; import { quantizeNotes, transposeNotes } from '../src/midi/ops.ts'; import { drumNote, epianoNote, leadNote, pluckNote } from '../src/instruments/dsp.ts'; import { builtinInstruments } from '../src/instruments/builtins.ts'; import { audibleTracks, encodeWavMono16, mixTracks, trackRenderKey } from '../src/audio/render.ts'; import { bucketVelocity, mapPitch, mapVelocity, parseManifest } from '../src/instruments/simulated/manifest.ts'; import { readdirSync, readFileSync, existsSync } from 'node:fs'; import { join } from 'node:path'; import type { Note, Song, Track } from '../src/types.ts'; let failed = 0; let passed = 0; function test(name: string, fn: () => void) { try { fn(); passed++; console.log(`ok - ${name}`); } catch (err) { failed++; console.error(`FAIL - ${name}`); console.error(err); } } function close(a: number, b: number, tol = 1e-9) { assert.ok(Math.abs(a - b) <= tol, `${a} !~ ${b}`); } function hash(buf: Float32Array): number { let h = 0x811c9dc5; for (let i = 0; i < buf.length; i++) { h ^= Math.round(buf[i] * 1e6) & 0xffff; h = Math.imul(h, 0x01000193); } return h >>> 0; } function mkNote(tick: number, duration: number, pitch: number, velocity: number, id: string): Note { return { id, tick, duration, pitch, velocity }; } function mkTrack(id: string, instrumentId: string, notes: Note[], extra: Partial = {}): Track { return { id, name: id, instrumentId, volume: 1, mute: false, solo: false, notes, ...extra }; } // --- tempo map --- test('tempo map: constant 120 bpm', () => { const tm = new TempoMap(480, [{ tick: 0, usPerQuarter: 500000 }]); close(tm.tickToSec(480), 0.5); close(tm.tickToSec(1920), 2); close(tm.secToTick(1), 960); close(tm.bpmAt(0), 120); }); test('tempo map: tempo change mid-song', () => { const tm = new TempoMap(480, [ { tick: 0, usPerQuarter: 500000 }, { tick: 960, usPerQuarter: 250000 }, ]); close(tm.tickToSec(960), 1); close(tm.tickToSec(1920), 1.5); close(tm.secToTick(1.25), 1440); close(tm.bpmAt(1000), 240); }); test('tempo map: bar.beat display in 4/4 and 3/4', () => { const tm44 = new TempoMap(480, [], [{ tick: 0, numerator: 4, denominator: 4 }]); assert.deepEqual(tm44.barBeatAt(0), { bar: 1, beat: 1 }); assert.deepEqual(tm44.barBeatAt(480 * 5), { bar: 2, beat: 2 }); const tm34 = new TempoMap(480, [], [{ tick: 0, numerator: 3, denominator: 4 }]); assert.deepEqual(tm34.barBeatAt(480 * 3), { bar: 2, beat: 1 }); }); test('tempo map: grid lines mark bars', () => { const tm = new TempoMap(480, [], [{ tick: 0, numerator: 4, denominator: 4 }]); const lines = tm.gridLines(0, 1920); assert.equal(lines.length, 4); assert.deepEqual(lines[0], { tick: 0, isBar: true }); assert.deepEqual(lines[1], { tick: 480, isBar: false }); }); // --- MIDI round trip --- function sortedNotes(t: Track): [number, number, number, number][] { return t.notes .map((n) => [n.tick, n.duration, n.pitch, n.velocity] as [number, number, number, number]) .sort((a, b) => a[0] - b[0] || a[2] - b[2]); } test('MIDI write/parse round trip preserves notes, tempo, and drums', () => { const song: Song = { ppq: 480, tempo: [ { tick: 0, usPerQuarter: 500000 }, { tick: 1920, usPerQuarter: 400000 }, ], timeSig: [{ tick: 0, numerator: 3, denominator: 4 }], tracks: [ mkTrack('melody', 'pluck', [ mkNote(0, 480, 60, 100, 'a'), mkNote(480, 240, 64, 90, 'b'), mkNote(100000, 960, 72, 127, 'c'), // multi-byte delta times mkNote(480, 240, 67, 1, 'd'), // chord + min velocity ]), mkTrack('kit', 'drumkit', [ mkNote(0, 120, 36, 110, 'e'), mkNote(480, 120, 38, 80, 'f'), ]), ], }; const bytes = writeMidi(song); const back = parseMidi(bytes); assert.equal(back.ppq, 480); assert.equal(back.tracks.length, 2); assert.deepEqual(sortedNotes(back.tracks[0]), sortedNotes(song.tracks[0])); assert.deepEqual(sortedNotes(back.tracks[1]), sortedNotes(song.tracks[1])); assert.equal(back.tracks[0].name, 'melody'); assert.equal(back.tracks[1].instrumentId, 'drumkit'); // came back on channel 10 assert.equal(back.tracks[0].instrumentId, 'pluck'); assert.deepEqual(back.tempo, song.tempo); assert.equal(back.timeSig[0].numerator, 3); assert.equal(back.timeSig[0].denominator, 4); }); test('parse splits a multi-channel track by channel', () => { const song: Song = { ppq: 480, tempo: [{ tick: 0, usPerQuarter: 500000 }], timeSig: [{ tick: 0, numerator: 4, denominator: 4 }], tracks: [ mkTrack('a', 'pluck', [mkNote(0, 480, 60, 100, 'a')]), mkTrack('b', 'drumkit', [mkNote(0, 120, 42, 100, 'b')]), ], }; // write produces separate MTrks; merging them into one channel-mixed // stream is what a format 0 file would look like, so parse the format 1 // bytes and just confirm channels landed apart. const back = parseMidi(writeMidi(song)); assert.equal(back.tracks.length, 2); assert.equal(back.tracks[1].instrumentId, 'drumkit'); }); // --- editing ops --- test('quantize rounds note starts to the grid', () => { const notes = [mkNote(130, 100, 60, 100, 'a'), mkNote(59, 100, 61, 100, 'b')]; const q = quantizeNotes(notes, 120); assert.equal(q[0].tick, 120); assert.equal(q[1].tick, 0); // 59 rounds down to the grid origin const onlyA = quantizeNotes(notes, 120, new Set(['a'])); assert.equal(onlyA[0].tick, 120); assert.equal(onlyA[1].tick, 59); }); test('transpose clamps to the MIDI range', () => { const notes = [mkNote(0, 100, 126, 100, 'a')]; assert.equal(transposeNotes(notes, 12)[0].pitch, 127); assert.equal(transposeNotes(notes, -300)[0].pitch, 0); }); // --- DSP --- test('DSP is deterministic and finite', () => { for (const [name, fn] of [ ['pluck', pluckNote], ['epiano', epianoNote], ['lead', leadNote], ['drum', drumNote], ] as const) { const a = fn(44100, name === 'drum' ? 38 : 60, 0.8, 0.4); const b = fn(44100, name === 'drum' ? 38 : 60, 0.8, 0.4); assert.equal(hash(a), hash(b), `${name} not deterministic`); assert.ok(a.length > 1000, `${name} too short`); let peak = 0; for (let i = 0; i < a.length; i++) { assert.ok(Number.isFinite(a[i]), `${name} produced non-finite sample`); peak = Math.max(peak, Math.abs(a[i])); } assert.ok(peak > 0.01, `${name} is silent`); assert.ok(peak <= 1.5, `${name} peak too hot: ${peak}`); } }); test('builtin instrument render places notes at the right time', () => { const pluck = builtinInstruments.find((i) => i.id === 'pluck')!; const sr = 44100; const out = pluck.render({ notes: [{ timeSec: 1, durationSec: 0.25, pitch: 69, velocity: 0.8 }], sampleRate: sr, lengthSamples: sr * 3, }) as Float32Array; assert.equal(out.length, sr * 3); let before = 0; for (let i = 0; i < sr - 10; i++) before = Math.max(before, Math.abs(out[i])); let after = 0; for (let i = sr; i < sr * 2; i++) after = Math.max(after, Math.abs(out[i])); assert.equal(before, 0); assert.ok(after > 0.01); }); // --- mixing --- test('mute and solo select audible tracks', () => { const a = mkTrack('a', 'pluck', []); const b = mkTrack('b', 'pluck', [], { mute: true }); const c = mkTrack('c', 'pluck', []); assert.deepEqual([...audibleTracks([a, b, c])].sort(), ['a', 'c']); const cSolo = { ...c, solo: true }; assert.deepEqual([...audibleTracks([a, b, cSolo])], ['c']); }); test('mixTracks applies volume and excludes muted tracks', () => { const a = mkTrack('a', 'pluck', [], { volume: 0.5 }); const b = mkTrack('b', 'pluck', [], { mute: true }); const buffers = new Map([ ['a', new Float32Array([0.4, 0.4])], ['b', new Float32Array([0.9, 0.9])], ]); const mix = mixTracks([a, b], buffers); close(mix[0], 0.2, 1e-6); }); test('trackRenderKey changes when the notes change', () => { const song: Song = { ppq: 480, tempo: [{ tick: 0, usPerQuarter: 500000 }], timeSig: [{ tick: 0, numerator: 4, denominator: 4 }], tracks: [], }; const t1 = mkTrack('a', 'pluck', [mkNote(0, 480, 60, 100, 'a')]); const t2 = mkTrack('a', 'pluck', [mkNote(0, 480, 61, 100, 'a')]); const t3 = mkTrack('a', 'epiano', [mkNote(0, 480, 60, 100, 'a')]); assert.equal(trackRenderKey(song, t1), trackRenderKey(song, mkTrack('a', 'pluck', [mkNote(0, 480, 60, 100, 'zzz')]))); assert.notEqual(trackRenderKey(song, t1), trackRenderKey(song, t2)); assert.notEqual(trackRenderKey(song, t1), trackRenderKey(song, t3)); }); test('WAV encoding writes a well-formed header', () => { const wav = encodeWavMono16(new Float32Array([0, 0.5, -0.5, 2]), 44100); assert.equal(wav.length, 44 + 8); assert.equal(String.fromCharCode(...wav.subarray(0, 4)), 'RIFF'); assert.equal(String.fromCharCode(...wav.subarray(8, 12)), 'WAVE'); const dv = new DataView(wav.buffer); assert.equal(dv.getUint32(24, true), 44100); assert.equal(dv.getInt16(44 + 6, true), 32767); // clipped to full scale }); // --- simulated-instrument manifests --- const SIM_ROOT = join(import.meta.dirname, '../../../simulated_instruments'); test('every instrument.json in ../simulated_instruments validates', () => { if (!existsSync(SIM_ROOT)) return; // vault layout absent; nothing to check const dirs = readdirSync(SIM_ROOT).filter((d) => existsSync(join(SIM_ROOT, d, 'instrument.json'))); assert.ok(dirs.length >= 1, 'no manifests found'); for (const d of dirs) { const m = parseManifest(readFileSync(join(SIM_ROOT, d, 'instrument.json'), 'utf8')); assert.equal(m.name, d, `manifest name '${m.name}' should match its directory '${d}'`); assert.ok(existsSync(join(SIM_ROOT, d, 'matlab', `${m.entry}.m`)), `${d}: entry ${m.entry}.m missing`); assert.ok(existsSync(join(SIM_ROOT, d, 'matlab', `${m.defaults}.m`)), `${d}: defaults ${m.defaults}.m missing`); } }); test('manifest pitch and velocity mapping', () => { const m = parseManifest(JSON.stringify({ format: 'simulated-instrument-v1', name: 't', label: 'T', entry: 'e', defaults: 'd', fixed: {}, preview: {}, pitch: { param: 'root_midi', mode: 'midi', min: 28, max: 55 }, velocity: { param: 'force', min: 2, max: 12 }, knobs: [], })); assert.deepEqual(mapPitch(m, 40), { key: 'root_midi', value: 40 }); assert.deepEqual(mapPitch(m, 10), { key: 'root_midi', value: 28 }); // clamped assert.deepEqual(mapVelocity(m, 0), { key: 'force', value: 2 }); assert.deepEqual(mapVelocity(m, 1), { key: 'force', value: 12 }); const t = parseManifest(JSON.stringify({ format: 'simulated-instrument-v1', name: 't2', label: 'T', entry: 'e', defaults: 'd', fixed: {}, preview: {}, pitch: { param: 'note1', mode: 'table', table: [{ midi: 72, value: 1 }, { midi: 74, value: 2 }] }, velocity: { param: 'v', min: 0, max: 1 }, knobs: [], })); assert.deepEqual(mapPitch(t, 73), { key: 'note1', value: 1 }); // nearest, ties go low assert.deepEqual(mapPitch(t, 90), { key: 'note1', value: 2 }); const un = parseManifest(JSON.stringify({ format: 'simulated-instrument-v1', name: 't3', label: 'T', entry: 'e', defaults: 'd', fixed: {}, preview: {}, velocity: { param: 'v', min: 0, max: 1 }, knobs: [], })); assert.equal(mapPitch(un, 60), null); }); test('velocity bucketing quantizes into few levels', () => { assert.equal(bucketVelocity(1), 1); assert.equal(bucketVelocity(0.999), 1); assert.equal(bucketVelocity(0.51), 0.625); assert.equal(bucketVelocity(0.01), 0.125); assert.ok(bucketVelocity(0) > 0); }); test('manifest validation rejects malformed knobs', () => { assert.throws(() => parseManifest(JSON.stringify({ format: 'simulated-instrument-v1', name: 'x', label: 'X', entry: 'e', defaults: 'd', fixed: {}, preview: {}, velocity: { param: 'v', min: 0, max: 1 }, knobs: [{ key: 'k', label: 'K', min: 5, max: 1, default: 2 }], }))); assert.throws(() => parseManifest(JSON.stringify({ format: 'wrong', name: 'x', label: 'X', entry: 'e', defaults: 'd', fixed: {}, preview: {}, velocity: { param: 'v', min: 0, max: 1 }, knobs: [], }))); }); console.log(`\n${passed} passed, ${failed} failed`); process.exit(failed > 0 ? 1 : 0);