Public: anyone can read this; the crew can change it.

A MIDI file shows its tracks, tempo and notes before anyone downloads it #16032

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/16013-a-midi-file-shows-its-tracks-tempo-and-n → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/16013-a-midi-file-shows-its-tracks-tempo-and-n was merged into main as 5c48389.

Review

Sign in to review this change.
13 files changed +437 −4
docs/features/file-kinds.md +1
@@ -18,6 +18,7 @@ The forge draws a file on its page when its kind is below and it is within the s
1818 - **SQLite database**, drawn up to 5 MB: `.db`, `.sqlite`, `.sqlite3`
1919 - **Parquet**, drawn up to 5 MB: `.parquet`
2020 - **Packet capture**, drawn up to 5 MB: `.pcap`, `.pcapng`, `.cap`
21 - **MIDI file**, drawn up to 5 MB: `.mid`, `.midi`
2122 - **Point cloud (PCD)**, drawn up to 5 MB: `.pcd`
2223 - **3D model**, drawn up to 100 MB: `.stl`, `.3mf`, `.ply`, `.glb`, `.gltf`, `.obj`, `.dae`
2324 - **Archive**, drawn up to 50 MB: `.zip`, `.tar`, `.tgz`, `.tar.gz`
docs/features/midi.md added +15
@@ -0,0 +1,15 @@
1 ---
2 topic: Files in the browser
3 row: MIDI files (.mid, .midi) as their header, tracks and first notes
4 ---
5 # MIDI files (.mid, .midi)
6
7 A Standard MIDI File opens as its header facts, a table of tracks and the first 200 notes, before anyone downloads it.
8
9 - **Page:** the file page shows format, track count, time division (ticks per quarter or SMPTE), tempo in BPM and length; a track table (name, channels, notes, events); and the first 200 notes by time (tick, track, channel, note name, velocity). No script, nothing is played.
10 - **Terminal:** opening a `.mid` in the workspace (`src/tui/screens/workspace_facts.ts`, `factsView`) shows the track table with the tempo in its first header; `s` flips to the source. Same gate as the page.
11 - **MCP:** `read_file` on a `.mid` or `.midi` carries `about: { kind: "midi", format, ppq?, bpm, seconds?, tracks, notes, says }`, with the first 20 notes as `[tick, track, channel, key, velocity]`; no new tool, ceilings in `test/mcp-size.test.ts` untouched.
12 - **Gate:** the name must end `.mid` or `.midi` and the first bytes must be `MThd`, and the file must be at most 5 MB; past that, or when it does not parse (no header, a cut-short header, a zero time division), the page keeps the source view with one line saying why.
13 - **Hostile input:** every read is checked against the bytes left in its chunk and every event consumes at least one byte, so a lying length cannot spin the walk; a chunk length past the file is clamped and reported. At most 256 tracks and 2,000,000 events are walked, 200 notes kept per track. Every track name and text is escaped.
14 - **Left out:** playback, a piano roll, lyrics and markers, key and time signatures beyond the header, RIFF-wrapped (`.rmi`) files.
15 - **Code:** `src/web/render/midi.ts`, kind `midi` in `kinds.ts`, registered in `renderers.ts`; test `test/midi-render.test.ts`, sample in `test/fuzz-renderers.test.ts`.
scripts/kinds-guide.ts +1 −1
@@ -10,7 +10,7 @@ export const END = "<!-- file-kinds:end -->";
1010 /** The name a person says for each kind. A new kind without one fails the type check. */
1111 export const NAMES: Readonly<Record<FileKind, string>> = {
1212 image: "Image", svg: "SVG", pdf: "PDF", html: "HTML page", audio: "Audio", video: "Video", csv: "Table (CSV, TSV, JSON lines)",
13 sqlite: "SQLite database", parquet: "Parquet", pcap: "Packet capture", pcd: "Point cloud (PCD)", model3d: "3D model", archive: "Archive", sheet: "Spreadsheet", document: "Word document",
13 sqlite: "SQLite database", parquet: "Parquet", pcap: "Packet capture", pcd: "Point cloud (PCD)", midi: "MIDI file", model3d: "3D model", archive: "Archive", sheet: "Spreadsheet", document: "Word document",
1414 slides: "Slides", layers: "Layered image", font: "Font", psd: "Photoshop", xcf: "GIMP", cad: "CAD or 3D source (header facts)", cert: "PEM certificate", sbom: "Bill of materials (CycloneDX, SPDX)", wasm: "WebAssembly module", config: "Config", markdown: "Markdown",
1515 notebook: "Notebook", patch: "Patch", log: "Log", subtitles: "Subtitles", gpx: "GPS track", har: "HTTP archive",
1616 geojson: "GeoJSON", kml: "KML", calendar: "Calendar", otio: "OpenTimelineIO", edl: "Edit list", fcpxml: "Final Cut XML", kdenlive: "Kdenlive project",
src/http/mcp/tools/read_file.ts +21 −1
@@ -4,6 +4,7 @@ import { isSafeRef, isSafeTreePath } from "../../../git/guard.ts";
44 import { blobForRender, listTree } from "../../../git/read.ts";
55 import { readStl, sayStl, stlSize, TOO_LARGE } from "../../../text/stl.ts";
66 import { checkConfig, configKind, type ConfigKind } from "../../../text/config_check.ts";
7 import { readMidi, Unreadable } from "../../../web/render/midi.ts";
78 import { aboutPcd } from "../../../web/render/pcd.ts";
89 import { describeMedia } from "../../../text/mp4.ts";
910 import { readXcf } from "../../../web/render/xcf-read.ts";
@@ -12,7 +13,7 @@ import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts"
1213
1314 export const tool: Tool = {
1415 name: "read_file",
15 doc: "`{ repo, path, ref? }`: a file (utf-8, or base64 for binary) or a directory listing at a ref, as GET …/contents; MP4/MOV/M4A files also carry about: {kind, seconds, width?, height?, says}, a .pcd {kind: pcd, points, width, height, data, fields, bounds?, says}",
16 doc: "`{ repo, path, ref? }`: a file (utf-8 or base64) or a directory listing at a ref, as GET …/contents; MP4/MOV/M4A files also carry about: {kind, seconds, width?, height?, says}, a .pcd {kind: pcd, points, width, height, data, fields, bounds?, says}; .mid {bpm, tracks}",
1617 description:
1718 "No shell? Read a file or list a directory at a ref (default branch); over 5 MB answers tooLarge.",
1819 inputSchema: {
@@ -74,6 +75,7 @@ function aboutFile(path: string, body: Uint8Array, text: string | undefined): Re
7475 const { format, triangles } = stl.value;
7576 return { kind: "stl", format, triangles, size: stlSize(stl.value), says: sayStl(stl.value) };
7677 }
78 if (/\.midi?$/i.test(path)) return aboutMidi(body);
7779 if (/\.pcd$/i.test(path)) return aboutPcd(body);
7880 if (/\.xcf$/i.test(path)) return aboutXcf(body);
7981 if (text !== undefined && /\.tfstate$/i.test(path)) return aboutTfstate(text);
@@ -84,6 +86,24 @@ function aboutFile(path: string, body: Uint8Array, text: string | undefined): Re
8486 return kind === null ? undefined : aboutConfig(kind, text);
8587 }
8688
89 function aboutMidi(body: Uint8Array): Record<string, unknown> {
90 try {
91 const m = readMidi(body);
92 return {
93 kind: "midi",
94 format: m.format,
95 ...(m.ppq === undefined ? {} : { ppq: m.ppq }),
96 bpm: Math.round((60_000_000 / m.tempo) * 100) / 100,
97 ...(m.seconds === undefined ? {} : { seconds: Math.round(m.seconds * 100) / 100 }),
98 tracks: m.tracks.map((t) => ({ name: t.name, channels: t.channels, notes: t.notes })),
99 notes: m.notes.slice(0, 20).map((n) => [n.tick, n.track, n.channel, n.key, n.velocity]),
100 says: `MIDI, format ${m.format}, ${m.tracks.length} tracks`,
101 };
102 } catch (e) {
103 return { kind: "midi", says: `MIDI, unreadable: ${e instanceof Unreadable ? e.message : "it could not be read"}` };
104 }
105 }
106
87107 function aboutConfig(kind: ConfigKind, content: string) {
88108 const check = checkConfig(kind, content);
89109 if (check.ok) return { kind, parses: true };
src/tui/screens/workspace_facts.ts +14 −1
@@ -13,13 +13,14 @@ import { holdsPrivateKey, PRIVATE_KEY_NOTICE } from "../../core/private_key.ts";
1313 import { readCerts, SAN_CAP } from "../../web/render/cert.ts";
1414 import { COMPONENT_CAP, parseSbom } from "../../web/render/sbom.ts";
1515 import { parseWasm } from "../../web/render/wasm.ts";
16 import { readMidi, Unreadable } from "../../web/render/midi.ts";
1617 import type { Table } from "../../text/csv.ts";
1718
1819 const table = (header: string[], rows: string[][], more: number): Table => ({ header, rows, more, delimiter: ",", columns: header.length });
1920
2021 export function factsView(path: string, body: Uint8Array, now: number = Date.now()): Table | string | null {
2122 const kind = fileKind(path, body.subarray(0, HEAD_BYTES));
22 if (kind !== "cert" && kind !== "sbom" && kind !== "wasm") return null;
23 if (kind !== "cert" && kind !== "sbom" && kind !== "wasm" && kind !== "midi") return null;
2324 if (body.length > RENDER_CAP[kind])
2425 return `This file is over ${RENDER_CAP[kind] / 1_000_000} MB, too large to open here. Download it instead.`;
2526 if (kind === "cert") {
@@ -31,6 +32,18 @@ export function factsView(path: string, body: Uint8Array, now: number = Date.now
3132 if (bad > 0) rows.push(["", "", "", `${bad} could not be read`]);
3233 return table(["Subject", "Issuer", "Not after", "Names"], rows, total - certs.length);
3334 }
35 if (kind === "midi") {
36 try {
37 const m = readMidi(body);
38 const bpm = Math.round(60_000_000 / m.tempo);
39 const rows = m.tracks.map((t, i) => [String(i + 1), t.name === "" ? "-" : t.name, t.channels.join(" ") || "-", String(t.notes)]);
40 if (rows.length === 0) return `MIDI format ${m.format}: no tracks.`;
41 return table([`Track (${bpm} BPM)`, "Name", "Channels", "Notes"], rows, Math.max(0, m.declared - m.tracks.length));
42 } catch (e) {
43 if (e instanceof Unreadable) return `This file is not drawn as MIDI: ${e.message}`;
44 throw e;
45 }
46 }
3447 if (kind === "sbom") {
3548 const doc = parseSbom(new TextDecoder().decode(body));
3649 if ("error" in doc) return `This file is not drawn as a bill of materials: ${doc.error}.`;
src/web/render/kinds.ts +11
@@ -30,6 +30,7 @@ export type FileKind =
3030 | "sqlite"
3131 | "parquet"
3232 | "pcap"
33 | "midi"
3334 | "pcd"
3435 | "model3d"
3536 | "archive"
@@ -126,6 +127,8 @@ export const RENDER_CAP: Readonly<Record<FileKind, number>> = {
126127 parquet: 5 * MB,
127128 // Packet records are walked by their headers; the page reads the whole body.
128129 pcap: 5 * MB,
130 // Events are walked by their lengths, bounded by the chunk; the page reads the whole body.
131 midi: 5 * MB,
129132 // Parsed whole for its header and a sample of at most 5,000 points; over it the source is kept.
130133 pcd: 5 * MB,
131134 model3d: 100 * MB,
@@ -480,6 +483,9 @@ const isPcap = (path: string, head: Uint8Array): boolean =>
480483 bytes(0x4d, 0x3c, 0xb2, 0xa1)(head) ||
481484 bytes(0x0a, 0x0d, 0x0d, 0x0a)(head));
482485
486 /** A MIDI file opens on `MThd`. */
487 const isMidi = (path: string, head: Uint8Array): boolean =>
488 (extension(path) === "mid" || extension(path) === "midi") && ascii("MThd")(head);
483489 /**
484490 * A PCD file opens on comment lines and then `VERSION`; a binary body follows its `DATA` line, so
485491 * only the header is looked at, and NUL bytes in the head are expected.
@@ -574,6 +580,7 @@ export function fileKind(path: string, head: Uint8Array): FileKind {
574580 if (office !== undefined) return office;
575581 if (isArchive(path, head)) return "archive";
576582 if (isPcap(path, head)) return "pcap";
583 if (isMidi(path, head)) return "midi";
577584 if (isPcd(path, head)) return "pcd";
578585 // A CAD or 3D source is named by its magic as well as its name, and has NULs in its head.
579586 if (binaryFacts(extension(path), head) !== undefined) return "cad";
@@ -638,6 +645,7 @@ export function kindByName(path: string): FileKind {
638645 if (isComposeName(path)) return "compose";
639646 if (ext === "xlsx") return "sheet";
640647 if (ext === "pcap" || ext === "pcapng" || ext === "cap") return "pcap";
648 if (ext === "mid" || ext === "midi") return "midi";
641649 if (ext === "pcd") return "pcd";
642650 if (ext === "wasm") return "wasm";
643651 if (OFFICE[ext] !== undefined) return OFFICE[ext]!;
@@ -677,6 +685,8 @@ export const KNOWN_EXTENSIONS: readonly string[] = [
677685 "pcap",
678686 "pcapng",
679687 "cap",
688 "mid",
689 "midi",
680690 "wasm",
681691 ...Object.keys(OFFICE),
682692 ];
@@ -750,6 +760,7 @@ const SNIFFED_EXTENSIONS: Readonly<Partial<Record<FileKind, readonly string[]>>>
750760 sheet: ["xlsx"],
751761 archive: ["zip", "tar", "tgz"],
752762 pcap: ["pcap", "pcapng", "cap"],
763 midi: ["mid", "midi"],
753764 pcd: ["pcd"],
754765 wasm: ["wasm"],
755766 cad: [...FACTS_EXTENSIONS],
src/web/render/midi.ts added +224
@@ -0,0 +1,224 @@
1 /**
2 * A Standard MIDI File as a header, a table of tracks and the first notes. Parsed by hand: the
3 * `MThd` header, then each `MTrk` chunk's events, keeping only what a person needs (track name,
4 * channels, note count, length, tempo) and the earliest `NOTE_CAP` notes. Nothing is played and
5 * nothing runs.
6 *
7 * Bounds: the file is capped by `RENDER_CAP.midi` before it gets here. Every event consumes at
8 * least one byte and every read is checked against the bytes left in its chunk, so a lying length
9 * cannot spin or overrun the walk; a chunk length past the file is clamped and reported. At most
10 * `TRACK_CAP` tracks and `EVENT_CAP` events are walked, at most `NOTE_CAP` notes kept per track.
11 * A file that is not MIDI, or whose header is cut short, falls back to the source view with one
12 * sentence.
13 */
14
15 import { escapeHtml, html, raw } from "../html.ts";
16 import { fileSize } from "../ui.ts";
17 import type { Rendered, RenderInput } from "./renderers.ts";
18
19 export const NOTE_CAP = 200;
20 export const TRACK_CAP = 256;
21 export const EVENT_CAP = 2_000_000;
22 const TEMPO_CAP = 4096;
23
24 export interface Note {
25 readonly track: number;
26 readonly tick: number;
27 readonly channel: number;
28 readonly key: number;
29 readonly velocity: number;
30 }
31 export interface Track {
32 readonly name: string;
33 /** Channels used, 1 to 16. */
34 readonly channels: readonly number[];
35 readonly notes: number;
36 readonly events: number;
37 readonly ticks: number;
38 }
39 export interface Midi {
40 readonly format: number;
41 /** Tracks the header claims, whether or not they are all in the file. */
42 readonly declared: number;
43 /** Ticks per quarter note, or undefined for SMPTE time. */
44 readonly ppq: number | undefined;
45 /** For SMPTE division: frames per second and ticks per frame. */
46 readonly smpte: { readonly fps: number; readonly perFrame: number } | undefined;
47 /** Microseconds per quarter note at the start; 500000 (120 BPM) when none is set. */
48 readonly tempo: number;
49 readonly seconds: number | undefined;
50 readonly tracks: readonly Track[];
51 readonly notes: readonly Note[];
52 readonly truncated: boolean;
53 }
54
55 /** Thrown with a sentence-sized reason when the file cannot be shown. */
56 export class Unreadable extends Error {}
57
58 const NAMES = ["C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B"];
59 export const noteName = (key: number): string => `${NAMES[key % 12]}${Math.floor(key / 12) - 1}`;
60
61 /** Bytes as Latin-1 text with control characters made harmless, at most 80 characters. */
62 function text(b: Uint8Array): string {
63 let s = "";
64 for (let i = 0; i < b.length && i < 80; i++) s += b[i]! < 32 || b[i] === 127 ? "�" : String.fromCharCode(b[i]!);
65 return s;
66 }
67
68 /** Channel message data length by status high nibble. */
69 const DATA: Readonly<Record<number, number>> = { 0x8: 2, 0x9: 2, 0xa: 2, 0xb: 2, 0xc: 1, 0xd: 1, 0xe: 2 };
70
71 export function readMidi(body: Uint8Array): Midi {
72 if (body.length < 4 || String.fromCharCode(body[0]!, body[1]!, body[2]!, body[3]!) !== "MThd")
73 throw new Unreadable("it does not start with a MIDI header (MThd)");
74 if (body.length < 14) throw new Unreadable("its header is cut short");
75 const dv = new DataView(body.buffer, body.byteOffset, body.byteLength);
76 const headLen = dv.getUint32(4, false);
77 if (headLen < 6) throw new Unreadable("its header is shorter than a MIDI header");
78 const format = dv.getUint16(8, false);
79 const declared = dv.getUint16(10, false);
80 const division = dv.getUint16(12, false);
81 if (division === 0) throw new Unreadable("its time division is zero");
82 const smpte =
83 division & 0x8000 ? { fps: 256 - (division >> 8), perFrame: division & 255 } : undefined;
84 if (smpte !== undefined && (smpte.fps === 0 || smpte.perFrame === 0)) throw new Unreadable("its time division is zero");
85 const ppq = smpte === undefined ? division : undefined;
86
87 const tracks: Track[] = [];
88 const notes: Note[] = [];
89 const tempos: { tick: number; us: number }[] = [];
90 let truncated = false;
91 let events = 0;
92 let pos = 8 + Math.min(headLen, body.length - 8);
93 while (pos + 8 <= body.length && tracks.length < TRACK_CAP && events < EVENT_CAP) {
94 const id = String.fromCharCode(body[pos]!, body[pos + 1]!, body[pos + 2]!, body[pos + 3]!);
95 const len = dv.getUint32(pos + 4, false);
96 const start = pos + 8;
97 let end = start + len;
98 if (end > body.length) { end = body.length; truncated = true; }
99 pos = end;
100 if (id !== "MTrk") continue;
101
102 const index = tracks.length;
103 const channels = new Set<number>();
104 const mine: Note[] = [];
105 let name = "";
106 let count = 0;
107 let n = 0;
108 let tick = 0;
109 let status = 0;
110 let at = start;
111 const vlq = (): number => {
112 let v = 0;
113 for (let i = 0; i < 4 && at < end; i++) {
114 const c = body[at++]!;
115 v = v * 128 + (c & 127);
116 if (!(c & 128)) return v;
117 }
118 return v;
119 };
120 while (at < end && events < EVENT_CAP) {
121 tick += vlq();
122 if (at >= end) break;
123 events++;
124 n++;
125 let s = body[at]!;
126 if (s & 128) { at++; if (s < 0xf0) status = s; else status = 0; } else s = status;
127 if (s === 0xff) {
128 if (at >= end) break;
129 const type = body[at++]!;
130 const mlen = vlq();
131 const stop = Math.min(at + mlen, end);
132 if (type === 3 && name === "") name = text(body.subarray(at, stop));
133 else if (type === 0x51 && stop - at >= 3 && tempos.length < TEMPO_CAP)
134 tempos.push({ tick, us: (body[at]! << 16) | (body[at + 1]! << 8) | body[at + 2]! });
135 at = stop;
136 if (type === 0x2f) break;
137 } else if (s === 0xf0 || s === 0xf7) {
138 at = Math.min(at + vlq(), end);
139 } else if (s >= 0x80 && s < 0xf0) {
140 const need = DATA[s >> 4]!;
141 if (at + need > end) { at = end; break; }
142 const a = body[at]! & 127;
143 const v = need === 2 ? body[at + 1]! & 127 : 0;
144 at += need;
145 const channel = (s & 15) + 1;
146 channels.add(channel);
147 if (s >> 4 === 9 && v > 0) {
148 count++;
149 if (mine.length < NOTE_CAP) mine.push({ track: index + 1, tick, channel, key: a, velocity: v });
150 }
151 } else {
152 // Running status with none set, or a system byte: nothing here can be walked past.
153 break;
154 }
155 }
156 notes.push(...mine);
157 tracks.push({ name, channels: [...channels].sort((x, y) => x - y), notes: count, events: n, ticks: tick });
158 }
159 notes.sort((x, y) => x.tick - y.tick || x.track - y.track);
160 tempos.sort((x, y) => x.tick - y.tick);
161 const tempo = tempos.find((t) => t.us > 0)?.us ?? 500000;
162 const maxTicks = tracks.reduce((m, t) => Math.max(m, t.ticks), 0);
163 let seconds: number | undefined;
164 if (smpte !== undefined) seconds = maxTicks / (smpte.fps * smpte.perFrame);
165 else if (tracks.length > 0) {
166 // Walk the tempo changes up to the last tick, each holding until the next.
167 seconds = 0;
168 let last = 0;
169 let us = 500000;
170 for (const t of tempos) {
171 if (t.us <= 0) continue;
172 const to = Math.min(t.tick, maxTicks);
173 seconds += ((to - last) * us) / (ppq! * 1e6);
174 last = to;
175 us = t.us;
176 }
177 seconds += ((maxTicks - last) * us) / (ppq! * 1e6);
178 }
179 return { format, declared, ppq, smpte, tempo, seconds, tracks, notes: notes.slice(0, NOTE_CAP), truncated };
180 }
181
182 const plural = (n: number, one: string): string => `${n.toLocaleString()} ${one}${n === 1 ? "" : "s"}`;
183 const clock = (s: number): string => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}`;
184
185 export function midi(input: RenderInput): Rendered {
186 let m: Midi;
187 try {
188 m = readMidi(input.body);
189 } catch (e) {
190 const why = e instanceof Unreadable ? e.message : "it could not be read";
191 return { content: html``, lines: 0, fallback: `This file cannot be shown as MIDI: ${why}.` };
192 }
193 const bpm = Math.round((60_000_000 / m.tempo) * 100) / 100;
194 const division = m.ppq !== undefined ? `${m.ppq} ticks per quarter note` : `${m.smpte!.fps} frames per second, ${m.smpte!.perFrame} ticks per frame`;
195 const length = m.seconds === undefined ? "" : clock(m.seconds);
196 const summary = `MIDI · format ${m.format} · ${plural(m.tracks.length, "track")} · ${bpm} BPM${length ? ` · ${length}` : ""} · ${fileSize(input.size)}`;
197 // The summary line states format, tracks, tempo and length; the table adds only what it does not.
outdated

Principle 1: this summary repeats format, tracks, BPM and length, which the Header table below states again. Say it once: drop the summary or the Header table.

198 const facts: [string, string][] = [["Division", division]];
199 if (m.declared !== m.tracks.length) facts.push(["Tracks", `${m.tracks.length} found, ${m.declared} declared`]);
200 const head = facts.map(([k, v]) => `<tr><th scope="row">${escapeHtml(k)}</th><td>${escapeHtml(v)}</td></tr>`).join("");
201 const trackRows = m.tracks
202 .map(
203 (t, i) =>
204 `<tr><td class="num">${i + 1}</td><td>${escapeHtml(t.name)}</td><td>${escapeHtml(t.channels.join(", "))}</td><td class="num">${t.notes}</td><td class="num">${t.events}</td></tr>`,
205 )
206 .join("");
207 const noteRows = m.notes
208 .map(
209 (k) =>
210 `<tr><td class="num">${k.tick}</td><td class="num">${k.track}</td><td class="num">${k.channel}</td><td>${escapeHtml(noteName(k.key))}</td><td class="num">${k.velocity}</td></tr>`,
211 )
212 .join("");
213 const total = m.tracks.reduce((s, t) => s + t.notes, 0);
214 const notes: string[] = [];
215 if (total > m.notes.length) notes.push(`The first ${m.notes.length} of ${total.toLocaleString()} notes are shown.`);
216 if (m.truncated) notes.push("The file ends inside a chunk, so it is cut short.");
217 const content = [
218 `<div class="csv-scroll"><table class="table" data-dense aria-label="Header"><tbody>${head}</tbody></table></div>`,
219 `<div class="csv-scroll"><table class="table" data-dense aria-label="Tracks"><thead><tr><th class="num">Track</th><th>Name</th><th>Channels</th><th class="num">Notes</th><th class="num">Events</th></tr></thead><tbody>${trackRows}</tbody></table></div>`,
220 `<div class="csv-scroll"><table class="table" data-dense aria-label="Notes"><thead><tr><th class="num">Tick</th><th class="num">Track</th><th class="num">Channel</th><th>Note</th><th class="num">Velocity</th></tr></thead><tbody>${noteRows}</tbody></table></div>`,
221 ...notes.map((n) => `<p class="muted small">${escapeHtml(n)}</p>`),
222 ].join("\n");
223 return { content: html`${raw(content)}`, lines: 0, summary };
224 }
src/web/render/renderers.ts +2
@@ -76,6 +76,7 @@ import { ora } from "./ora.ts";
7676 import { sqlite } from "./sqlite.ts";
7777 import { parquet } from "./parquet.ts";
7878 import { pcap } from "./pcap.ts";
79 import { midi } from "./midi.ts";
7980 import { pcd } from "./pcd.ts";
8081 import { subtitles } from "./subtitles.ts";
8182 import { video } from "./video.ts";
@@ -148,6 +149,7 @@ export const RENDERERS: Partial<Readonly<Record<FileKind, Renderer>>> = {
148149 sqlite,
149150 parquet,
150151 pcap,
152 midi,
151153 pcd,
152154 audio,
153155 video,
test/fuzz-renderers.test.ts +8 −1
@@ -92,6 +92,12 @@ export const SAMPLES: Readonly<Record<string, { path: string; files: readonly st
9292 "From: Ada <[email protected]>\r\nSubject: =?utf-8?Q?<script>?=\r\nMIME-Version: 1.0\r\nContent-Type: text/html\r\n\r\n<p onclick=x>hi</p>\r\n",
9393 ],
9494 },
95 midi: {
96 path: "song.mid",
97 files: [
98 "MThd\0\0\0\x06\0\x01\0\x02\x01\xe0MTrk\0\0\0\x1c\0\xff\x03\x05Piano\0\xff\x51\x03\x07\xa1\x20\0\x90\x3c\x64\x60\x80\x3c\0\0\xff\x2f\0MTrk\0\0\0\x14\0\xff\x03\x04<b>x\0\x91\x40\x50\x10\x81\x40\0\0\xff\x2f\0",
99 ],
100 },
95101 gpx: {
96102 path: "track.gpx",
97103 files: [
@@ -549,7 +555,8 @@ describe("fuzz: file renderers", () => {
549555 });
550556
551557 function input(path: string, text: string, all = false) {
552 const body = encoder.encode(text);
558 // A MIDI sample is bytes written as Latin-1 characters; UTF-8 would split every byte past 0x7f.
559 const body = /\.midi?$/.test(path) ? Uint8Array.from(text, (c) => c.charCodeAt(0) & 255) : encoder.encode(text);
553560 return {
554561 path,
555562 size: body.length,
test/mcp-read-file.test.ts +9
@@ -75,6 +75,8 @@ beforeAll(async () => {
7575 await commitToBranch(app, owner, pub, {
7676 message: "models",
7777 files: [
78 { path: "song.mid", content: Uint8Array.from([0x4d, 0x54, 0x68, 0x64, 0, 0, 0, 6, 0, 0, 0, 1, 1, 0xe0, 0x4d, 0x54, 0x72, 0x6b, 0, 0, 0, 12, 0, 0x90, 60, 100, 0x60, 0x80, 60, 0, 0, 0xff, 0x2f, 0]) },
79 { path: "bad.mid", content: "not midi" },
7880 { path: "cube.stl", content: binaryBox(40, 20, 10) },
7981 { path: "cube-ascii.STL", content: asciiBox(40, 20, 10) },
8082 { path: "broken.stl", content: binaryBox(1, 1, 1).subarray(0, 100) },
@@ -148,6 +150,13 @@ test("an STL file is described in words", async () => {
148150 expect(huge.about).toEqual({ kind: "stl", says: "STL, too large to describe here" });
149151 });
150152
153 test("a MIDI file is described by its tracks, tempo and first notes", async () => {
154 const t = tok["stranger"]!;
155 const about = (await read(t, { repo: "ada/pub", path: "song.mid" })).value.about;
156 expect(about).toMatchObject({ kind: "midi", format: 0, ppq: 480, bpm: 120, tracks: [{ name: "", channels: [1], notes: 1 }], notes: [[0, 1, 1, 60, 100]] });
157 expect((await read(t, { repo: "ada/pub", path: "bad.mid" })).value.about.says).toContain("unreadable");
158 });
159
151160 test("a config file says whether it parses; other files carry no about", async () => {
152161 const t = tok["owner"]!;
153162 const bad = await read(t, { repo: "ada/pub", path: "bad.json" });
test/midi-render.test.ts added +116
@@ -0,0 +1,116 @@
1 /** A Standard MIDI File (built here) as a header, tracks and notes. */
2 import { describe, expect, test } from "bun:test";
3 import { fileKind, kindMatches, RENDER_CAP } from "../src/web/render/kinds.ts";
4 import { midi, NOTE_CAP, readMidi } from "../src/web/render/midi.ts";
5 import { RENDERERS } from "../src/web/render/renderers.ts";
6
7 const u32 = (n: number) => [n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255];
8 const u16 = (n: number) => [n >> 8, n & 255];
9 const ascii = (s: string) => [...s].map((c) => c.charCodeAt(0));
10 const chunk = (id: string, data: number[]) => [...ascii(id), ...u32(data.length), ...data];
11 const file = (tracks: number[][], o: { format?: number; division?: number; declared?: number } = {}) =>
12 Uint8Array.from([
13 ...ascii("MThd"), ...u32(6), ...u16(o.format ?? 1), ...u16(o.declared ?? tracks.length), ...u16(o.division ?? 480),
14 ...tracks.flatMap((t) => chunk("MTrk", t)),
15 ]);
16 const name = (s: string) => [0, 0xff, 3, s.length, ...ascii(s)];
17 const tempo = (us: number) => [0, 0xff, 0x51, 3, us >> 16, (us >> 8) & 255, us & 255];
18 const end = [0, 0xff, 0x2f, 0];
19 const song = () =>
20 file([
21 [...name("Piano"), ...tempo(500000), 0, 0x90, 60, 100, 0x83, 0x60, 0x80, 60, 0, ...end],
22 [...name("Bass"), 0, 0x91, 36, 80, 0x10, 0x91, 40, 0 /* velocity 0 is a note off */, ...end],
23 ]);
24 const input = (body: Uint8Array, path = "a.mid") => ({
25 path, size: body.length, body, media: "/m", download: "/d", pathHref: "/p",
26 repo: { base: "/o/r", ref: "main" }, all: false, table: "", layer: 2,
27 });
28
29 describe("midi parse", () => {
30 test("reads the header, tracks, tempo, length and notes", () => {
31 const m = readMidi(song());
32 expect(m.format).toBe(1);
33 expect(m.ppq).toBe(480);
34 expect(m.tempo).toBe(500000);
35 expect(m.tracks.map((t) => [t.name, t.notes, t.channels])).toEqual([["Piano", 1, [1]], ["Bass", 1, [2]]]);
36 // 0x83 0x60 = 480 ticks = one quarter at 120 BPM = 0.5 s.
37 expect(m.seconds).toBeCloseTo(0.5);
38 expect(m.notes.map((n) => [n.tick, n.key])).toEqual([[0, 60], [0, 36]]);
39 });
40 test("a tempo change moves the length", () => {
41 const m = readMidi(file([[...tempo(1_000_000), 0x83, 0x60, 0x90, 60, 1, ...end]]));
42 expect(m.seconds).toBeCloseTo(1);
43 });
44 test("running status and SMPTE division", () => {
45 const m = readMidi(file([[0, 0x90, 60, 90, 0, 62, 90, ...end]], { division: 0xe728 }));
46 expect(m.tracks[0]!.notes).toBe(2);
47 expect(m.smpte).toEqual({ fps: 25, perFrame: 40 });
48 });
49 test("only the first notes are kept", () => {
50 const evs = Array.from({ length: NOTE_CAP + 50 }, () => [1, 0x90, 60, 90]).flat();
51 const m = readMidi(file([[...evs, ...end]]));
52 expect(m.notes).toHaveLength(NOTE_CAP);
53 expect(m.tracks[0]!.notes).toBe(NOTE_CAP + 50);
54 expect(midi(input(file([[...evs, ...end]]))).content.text).toContain("first 200 of 250");
55 });
56 });
57
58 describe("midi render", () => {
59 test("draws the tables and a summary", () => {
60 const out = midi(input(song()));
61 expect(out.fallback).toBeUndefined();
62 expect(out.summary).toContain("2 tracks");
63 expect(out.summary).toContain("120 BPM");
64 expect(out.content.text).toContain("Piano");
65 expect(out.content.text).not.toContain("BPM");
66 expect(out.content.text).toContain("C4");
67 });
68 test("escapes every value drawn from the file", () => {
69 const out = midi(input(file([[...name('<script>alert(1)</script>"'), 0, 0x90, 60, 90, ...end]])));
70 expect(out.content.text).not.toContain("<script>");
71 expect(out.content.text).toContain("&lt;script&gt;");
72 });
73 test("is the renderer for a .mid file, by name and by signature", () => {
74 expect(fileKind("a.mid", song())).toBe("midi");
75 expect(fileKind("a.midi", song())).toBe("midi");
76 expect(fileKind("a.mid", Uint8Array.from(ascii("RIFF....")))).not.toBe("midi");
77 expect(RENDERERS.midi).toBe(midi);
78 expect(kindMatches("midi")).toEqual([".mid", ".midi"]);
79 expect(RENDER_CAP.midi).toBeGreaterThan(0);
80 });
81 });
82
83 describe("midi malformed and hostile", () => {
84 test("not MIDI keeps the source view and says why in one line", () => {
85 const out = midi(input(Uint8Array.from(ascii("hello world, not midi"))));
86 expect(out.fallback).toContain("MThd");
87 expect(out.fallback).not.toContain("\n");
88 });
89 test("a cut header falls back", () => {
90 expect(midi(input(Uint8Array.from(ascii("MThd\0\0")))).fallback).toContain("cut short");
91 });
92 test("a lying chunk length, a huge declared count and a cut event are bounded", () => {
93 const lying = Uint8Array.from([...ascii("MThd"), ...u32(6), ...u16(1), ...u16(65535), ...u16(96), ...ascii("MTrk"), ...u32(0xffffffff), 0, 0x90, 60]);
94 const m = readMidi(lying);
95 expect(m.truncated).toBe(true);
96 expect(m.tracks).toHaveLength(1);
97 expect(m.declared).toBe(65535);
98 expect(midi(input(lying)).fallback).toBeUndefined();
99 });
100 test("a meta or sysex length past the chunk, and endless delta bytes, terminate", () => {
101 readMidi(file([[0, 0xff, 3, 0x7f, 65], [0, 0xf0, 0xff, 0xff, 0xff, 0x7f, 1], Array(5000).fill(0xff)]));
102 });
103 test("many empty chunks stop at the track cap", () => {
104 const body = Uint8Array.from([...ascii("MThd"), ...u32(6), ...u16(1), ...u16(5000), ...u16(96), ...Array.from({ length: 5000 }, () => chunk("MTrk", [])).flat()]);
105 expect(readMidi(body).tracks.length).toBeLessThanOrEqual(256);
106 });
107 test("random bytes after a valid header never throw", () => {
outdated

Math.random makes this test non-deterministic; a failure cannot be replayed. Use a seeded generator (e.g. a small LCG) so it never flakes.

108 let seed = 12345;
109 const next = () => (seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0) >>> 24;
110 for (let i = 0; i < 200; i++) {
111 const rnd = Uint8Array.from({ length: 80 }, next);
112 const body = Uint8Array.from([...ascii("MThd"), ...u32(6), 0, 1, 0, 1, 1, 0xe0, ...ascii("MTrk"), ...u32(80), ...rnd]);
113 expect(() => midi(input(body))).not.toThrow();
114 }
115 });
116 });
test/render-kinds.test.ts +2
@@ -51,6 +51,8 @@ const SAMPLES: Record<string, [Uint8Array, FileKind, string]> = {
5151 pcap: [of(0xd4, 0xc3, 0xb2, 0xa1, 2, 0, 4, 0), "pcap", "application/octet-stream"],
5252 pcapng: [of(0x0a, 0x0d, 0x0d, 0x0a, 28, 0, 0, 0), "pcap", "application/octet-stream"],
5353 cap: [of(0xa1, 0xb2, 0xc3, 0xd4, 0, 2, 0, 4), "pcap", "application/octet-stream"],
54 mid: [enc("MThd\0\0\0\x06"), "midi", "application/octet-stream"],
55 midi: [enc("MThd\0\0\0\x06"), "midi", "application/octet-stream"],
5456 csv: [enc("a,b\n1,2\n"), "csv", "application/octet-stream"],
5557 tsv: [enc("a\tb\n"), "csv", "application/octet-stream"],
5658 jsonl: [enc("{\"a\":1}\n"), "csv", "application/octet-stream"],
test/workspace-facts.test.ts +13
@@ -58,3 +58,16 @@ test("a file over the page's cap is not opened", () => {
5858 const bigBom = enc(`{"bomFormat":"CycloneDX","x":"${"a".repeat(5_100_000)}"}`);
5959 expect(factsView("bom.json", bigBom)).toContain("over 5 MB");
6060 });
61
62 test("a MIDI file opens as a table of tracks with their notes and tempo", () => {
63 const ascii = (s: string) => [...s].map((c) => c.charCodeAt(0));
64 const trk = [0, 0xff, 3, 5, ...ascii("Piano"), 0, 0x90, 60, 100, 0x10, 0x80, 60, 0, 0, 0xff, 0x2f, 0];
65 const body = Uint8Array.from([
66 ...ascii("MThd"), 0, 0, 0, 6, 0, 1, 0, 1, 1, 0xe0,
67 ...ascii("MTrk"), 0, 0, 0, trk.length, ...trk,
68 ]);
69 const v = factsView("a.mid", body);
70 expect(header(v)).toEqual(["Track (120 BPM)", "Name", "Channels", "Notes"]);
71 expect(rows(v)).toEqual([["1", "Piano", "1", "1"]]);
72 expect(factsView("a.mid", enc("MThd"))).toContain("not drawn as MIDI");
73 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs