xiaohan-tian's picture
Copy files from datasets/KGAudioLab/InstVELA-models-onnx
26e7ebe verified
Raw History Blame Contribute Delete
10.9 kB
// Read MIDI and convert to the M01 format. The conversion retains notes, velocities, tempo, time signature,
// and the bar-origin marker. Inputs and outputs are Uint8Array.
export const DEFAULT_ARTICULATION = "sustain";
export const BAR_ORIGIN_TEXT = "M01 bar_origin_beats=";
const u32 = (d, p) => ((d[p] << 24) | (d[p + 1] << 16) | (d[p + 2] << 8) | d[p + 3]) >>> 0;
const u16 = (d, p) => (d[p] << 8) | d[p + 1];
const ascii = (d, p, n) => String.fromCharCode(...d.subarray(p, p + n));
function readVlq(d, q) {
let v = 0;
for (;;) {
const x = d[q++];
if (x === undefined) throw new Error("truncated variable-length quantity");
v = v * 128 + (x & 0x7f);
if (x < 0x80) return [v, q];
}
}
function vlq(n) {
const out = [n & 0x7f];
n = Math.floor(n / 128);
while (n) {
out.push(0x80 | (n & 0x7f));
n = Math.floor(n / 128);
}
return out.reverse();
}
const cmpTuple = (a, b) => {
for (let i = 0; i < Math.min(a.length, b.length); i++) {
if (a[i] < b[i]) return -1;
if (a[i] > b[i]) return 1;
}
return a.length - b.length;
};
/** Minimal SMF reader: { notes, tempos, sigs, div }, exactly as m01_features.read_midi. */
export function readMidi(d) {
if (ascii(d, 0, 4) !== "MThd") throw new Error("not a MIDI file");
const ntrk = u16(d, 10), div = u16(d, 12);
if (div & 0x8000) throw new Error("SMPTE timing is not supported");
let p = 8 + u32(d, 4);
const notes = [], tempos = [], sigs = [];
for (let t = 0; t < ntrk; t++) {
if (ascii(d, p, 4) !== "MTrk") throw new Error("bad track header");
let q = p + 8;
const end = p + 8 + u32(d, p + 4);
p = end;
let tick = 0, rs = null;
const open = new Map(); // "ch,pitch" -> FIFO of [tick, velocity]
while (q < end) {
let delta;
[delta, q] = readVlq(d, q);
tick += delta;
const st = d[q];
if (st === 0xff) {
const ty = d[q + 1];
let n;
[n, q] = readVlq(d, q + 2);
if (ty === 0x51) tempos.push([tick, (d[q] << 16) | (d[q + 1] << 8) | d[q + 2]]);
else if (ty === 0x58) sigs.push([tick, d[q], 2 ** d[q + 1]]);
q += n;
continue;
}
if (st === 0xf0 || st === 0xf7) {
let n;
[n, q] = readVlq(d, q + 1);
q += n;
continue;
}
if (st & 0x80) { rs = st; q += 1; }
if (rs === null) throw new Error("running status without a status byte");
const kind = rs >> 4, ch = rs & 0x0f;
const n = kind === 0xc || kind === 0xd ? 1 : 2;
const a = d.subarray(q, q + n);
q += n;
if (kind === 0x9 && a[1] > 0) {
const k = `${ch},${a[0]}`;
if (!open.has(k)) open.set(k, []);
open.get(k).push([tick, a[1]]);
} else if (kind === 0x8 || (kind === 0x9 && a[1] === 0)) {
const fifo = open.get(`${ch},${a[0]}`);
if (!fifo || !fifo.length) throw new Error(`note-off without note-on (pitch ${a[0]}, tick ${tick})`);
const [start, vel] = fifo.shift();
notes.push({ start_tick: start, end_tick: tick, pitch: a[0], velocity: vel, channel: ch, track: t });
}
}
for (const fifo of open.values()) if (fifo.length) throw new Error(`track ${t} has unterminated notes`);
}
notes.sort((x, y) => x.start_tick - y.start_tick || x.pitch - y.pitch);
tempos.sort(cmpTuple);
sigs.sort(cmpTuple);
return { notes, tempos, sigs, div };
}
/** Python's f"{x:g}" for the plain values used here (no exponent notation). */
export function formatG(x) {
if (x === 0) return "0";
let s = x.toPrecision(6);
if (s.includes("e")) return String(Number(s));
if (s.includes(".")) s = s.replace(/0+$/, "").replace(/\.$/, "");
return s;
}
/** Python's round(x, 3) for the tempo (ties cannot occur for binary doubles at 3 decimals). */
export const round3 = (x) => Number(x.toFixed(3));
/**
* Optional pitch map (user decision 2026-11-01), as m01_midi_convert.parse_pitch_map: a JSON object {"from": "to"} of
* MIDI pitches 0–127, written as numbers or strings.
* Accepts the JSON text or an already parsed object; "" / null → null (no map). Throws with a readable message.
*/
export function parsePitchMap(input) {
if (input === null || input === undefined || (typeof input === "string" && !input.trim())) return null;
let obj = input;
if (typeof input === "string") {
try { obj = JSON.parse(input); } catch (e) { throw new Error(`pitch map is not valid JSON: ${e.message}`); }
}
if (!obj || typeof obj !== "object" || Array.isArray(obj)) throw new Error('the pitch map must be a JSON object such as {"38": "37"}');
const out = {};
for (const [k, v] of Object.entries(obj)) {
const ks = String(k).trim(), vs = String(v).trim();
const a = Number(ks), b = Number(vs);
if (!/^\d+$/.test(ks) || !/^\d+$/.test(vs) || String(a) !== ks || String(b) !== vs || a > 127 || b > 127) {
throw new Error(`pitch map entry ${JSON.stringify(k)}: ${JSON.stringify(v)} is not a pair of MIDI pitches 0-127`);
}
out[a] = b;
}
return out;
}
/** Notes with their pitches mapped (all at once), re-sorted as readMidi sorts: { notes, changed }. */
export function applyPitchMap(notes, pitchMap) {
if (!pitchMap || !Object.keys(pitchMap).length) return { notes, changed: 0 };
const out = notes.map((n) => ({ ...n, pitch: pitchMap[n.pitch] ?? n.pitch }));
const changed = out.filter((n, i) => n.pitch !== notes[i].pitch).length;
out.sort((x, y) => x.start_tick - y.start_tick || x.pitch - y.pitch);
return { notes: out, changed };
}
/** Read and map the input score before flattening its tracks or channels. */
export function prepareM01Input(d, { keyswitches, range, pitchMap = null }) {
const score = readMidi(d);
const pm = parsePitchMap(pitchMap);
const { notes, changed: remapped } = applyPitchMap(score.notes, pm);
if (new Set(score.tempos.map(([, us]) => us)).size > 1) throw new Error("tempo changes are not supported in M01Preview (constant tempo per request)");
const music = notes.filter((n) => !(n.pitch in keyswitches));
if (!music.length) throw new Error("the file has no notes");
const warnings = [];
const outside = music.filter(({ pitch }) => pitch < range[0] || pitch > range[1]).length;
if (outside) warnings.push(`${outside} note(s) outside the instrument range (MIDI ${range.join("–")}). Check the score and keyswitches.`);
const removed = { controlOrOther: countNonNoteEvents(d), keyswitchNotes: notes.length - music.length };
return { score: { ...score, notes }, music, warnings, removed, pitchMap: pm, remapped };
}
/** Convert to M01 MIDI and emit a keyswitch for the first note's articulation, which defaults to sustain. */
export function convertToM01(d, { keyswitches, keyswitchPitches, range, barOriginBeats = 0, pitchMap = null }) {
const { score: { notes, tempos, sigs, div }, music, warnings, removed, pitchMap: pm, remapped } = prepareM01Input(d, { keyswitches, range, pitchMap });
const ks = notes.filter((n) => n.pitch in keyswitches).map((n) => [n.start_tick, keyswitches[n.pitch]]).sort(cmpTuple);
const events = []; // [tick, order, bytes]; note-offs (order 0) before note-ons (order 1) at the same tick
const articulations = new Set();
let current = null;
let previousOnset = -1;
const lead = Math.floor(div / 8), length = Math.max(1, Math.floor(div / 16));
for (const n of music) {
let art = DEFAULT_ARTICULATION;
for (const [t, a] of ks) if (t <= n.start_tick) art = a;
if (art !== current) {
// A switch moved earlier must still follow the previous note's onset.
const t = Math.max(n.start_tick - lead, previousOnset + 1), p = keyswitchPitches[art];
events.push([t, 1, [0x90, p, 64]], [t + length, 0, [0x80, p, 0]]);
articulations.add(art);
current = art;
}
events.push([n.start_tick, 1, [0x90, n.pitch, n.velocity]], [n.end_tick, 0, [0x80, n.pitch, 0]]);
previousOnset = n.start_tick;
}
const us = tempos.length ? tempos[0][1] : 500000;
const [num, den] = sigs.length ? [sigs[0][1], sigs[0][2]] : [4, 4];
const text = Array.from(new TextEncoder().encode(`${BAR_ORIGIN_TEXT}${formatG(barOriginBeats)}`));
const meta = [
[0, -3, [0xff, 0x51, 0x03, (us >> 16) & 0xff, (us >> 8) & 0xff, us & 0xff]],
[0, -2, [0xff, 0x58, 0x04, num, Math.log2(den), 24, 8]],
[0, -1, [0xff, 0x01, ...vlq(text.length), ...text]],
];
const all = [...meta, ...events].sort((a, b) => a[0] - b[0] || a[1] - b[1]); // stable, like Python's sorted
const track = [];
let last = 0;
for (const [t, , ev] of all) {
track.push(...vlq(t - last), ...ev);
last = t;
}
track.push(0x00, 0xff, 0x2f, 0x00);
const head = [0x4d, 0x54, 0x68, 0x64, 0, 0, 0, 6, 0, 0, 0, 1, (div >> 8) & 0xff, div & 0xff];
const tl = track.length;
const bytes = Uint8Array.from([...head, 0x4d, 0x54, 0x72, 0x6b, (tl >>> 24) & 0xff, (tl >> 16) & 0xff, (tl >> 8) & 0xff, tl & 0xff, ...track]);
return {
bytes, warnings,
info: { notes: music.length, keyswitches_in: ks.length, articulations: [...articulations].sort(),
ticks_per_beat: div, tempo_bpm: round3(60e6 / us), time_signature: [num, den], bar_origin_beats: barOriginBeats,
pitch_map: Object.fromEntries(Object.entries(pm ?? {}).map(([k, v]) => [String(k), String(v)])), remapped_notes: remapped, removed },
};
}
/** Number of channel events other than notes (control changes, pitch bends, program changes, aftertouch),
* plus sysex and meta events other than tempo and time signature: what the conversion drops (for the page). */
export function countNonNoteEvents(d) {
const ntrk = u16(d, 10);
let p = 8 + u32(d, 4), count = 0;
for (let t = 0; t < ntrk; t++) {
let q = p + 8;
const end = p + 8 + u32(d, p + 4);
p = end;
let rs = null;
while (q < end) {
[, q] = readVlq(d, q);
const st = d[q];
if (st === 0xff) {
const ty = d[q + 1];
let n;
[n, q] = readVlq(d, q + 2);
if (ty !== 0x51 && ty !== 0x58 && ty !== 0x2f) count++;
q += n;
continue;
}
if (st === 0xf0 || st === 0xf7) {
let n;
[n, q] = readVlq(d, q + 1);
q += n;
count++;
continue;
}
if (st & 0x80) { rs = st; q += 1; }
const kind = rs >> 4;
q += kind === 0xc || kind === 0xd ? 1 : 2;
if (kind !== 0x8 && kind !== 0x9) count++;
}
}
return count;
}
/** The `M01 bar_origin_beats=` text event value, or null (byte search, as read_bar_origin). */
export function readBarOrigin(d) {
const pat = new TextEncoder().encode(BAR_ORIGIN_TEXT);
outer: for (let i = 0; i + pat.length <= d.length; i++) {
for (let j = 0; j < pat.length; j++) if (d[i + j] !== pat[j]) continue outer;
let k = i + pat.length;
while (k < d.length && "0123456789.-".includes(String.fromCharCode(d[k]))) k++;
return parseFloat(ascii(d, i + pat.length, k - i - pat.length));
}
return null;
}