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

Revert "A .mid file shows its tracks, tempo and a piano roll" #14606

Merged opened this

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

Merged

revert-14470 → main 1 commit

  • Merged. revert-14470 was merged into main as bbac9a7.

Review

Sign in to review this change.
17 files changed +5 −523
docs/design/areas/render.md −4
@@ -91,10 +91,6 @@ A .zip, .tar or .tar.gz is drawn by `src/web/render/archive-view.ts` as the exis
9191
9292 - `.pdf-facts`: the page count, title and author above a PDF's viewer, one line of label and value pairs.
9393
94 ## MIDI piano roll
95
96 `src/web/render/midi.ts`, styles in `midi-css.ts`. `.midi-view` is a figure with no box: the facts as `status-rows`, the roll, one caption line, a dense `table` of tracks (a Shade swatch cell keys each row to its shade), Download. The roll is a `.midi-roll` scroll wrapper (swatches are `.midi-key`) (a thumb pans it; `tabindex` 0 for keys) around an SVG at least 720px wide with a `<g>` and `<title>` per track. It adds no colour token and uses no accent: data is `currentColor` at four opacities, cycled, with no frame. The terminal door is `src/tui/screens/workspace_midi.ts` (the same parse as a table).
97
9894 ## Copper layer (.gbr)
9995
10096 `src/web/render/gerber.ts` draws a Gerber layer as one inline SVG in `.gerber-view` (same rules as `.dxf-view`: no fixed size, `max-width: 100%`, `currentColor`, no accent), with its units, board size and counts as the existing `.status-rows`.
docs/features/file-kinds.md −3
@@ -39,7 +39,6 @@ The forge draws a file on its page when its kind is below and it is within the s
3939 - **Calendar**, drawn up to 5 MB: `.ics`
4040 - **OpenTimelineIO**, drawn up to 1 MB: `.otio`
4141 - **Edit list**, drawn up to 1 MB: `.edl`
42 - **MIDI file**, drawn up to 1 MB: `.mid`, `.midi`
4342 - **Final Cut XML**, drawn up to 1 MB: `.fcpxml`
4443 - **Contacts**, drawn up to 1 MB: `.vcf`, `.vcard`
4544 - **Email**, drawn up to 5 MB: `.eml`
@@ -73,5 +72,3 @@ The forge draws a file on its page when its kind is below and it is within the s
7372 - **Other binary**, none: download only: any other bytes
7473
7574 <!-- file-kinds:end -->
76
77 In the terminal workspace, a MIDI file opens as its facts and a table of its tracks (`src/tui/screens/workspace_midi.ts`); the piano roll stays on the web page.
scripts/kinds-guide.ts +1 −1
@@ -13,7 +13,7 @@ export const NAMES: Readonly<Record<FileKind, string>> = {
1313 sqlite: "SQLite database", parquet: "Parquet", model3d: "3D model", archive: "Archive", sheet: "Spreadsheet", document: "Word document",
1414 slides: "Slides", layers: "Layered image", font: "Font", psd: "Photoshop", config: "Config", markdown: "Markdown",
1515 notebook: "Notebook", patch: "Patch", log: "Log", subtitles: "Subtitles", gpx: "GPS track", har: "HTTP archive",
16 geojson: "GeoJSON", kml: "KML", calendar: "Calendar", otio: "OpenTimelineIO", edl: "Edit list", midi: "MIDI file", fcpxml: "Final Cut XML",
16 geojson: "GeoJSON", kml: "KML", calendar: "Calendar", otio: "OpenTimelineIO", edl: "Edit list", fcpxml: "Final Cut XML",
1717 contacts: "Contacts", mail: "Email", gcode: "G-code", dxf: "DXF drawing", gerber: "Gerber layer", mermaid: "Mermaid diagram", drawio: "draw.io diagram",
1818 excalidraw: "Excalidraw", step: "STEP model", sarif: "SARIF report", lcov: "Coverage (lcov)", junit: "JUnit report",
1919 opml: "OPML", feed: "RSS or Atom feed", env: "Env example", openapi: "OpenAPI", package: "package.json", makefile: "Makefile",
src/spawn/preview-looks.ts +2 −3
@@ -110,14 +110,14 @@ export const PREVIEW_SEARCH_PAGE = "/search?q=sample";
110110 export const PREVIEW_STEP_PAGE = `${PREVIEW_REPO_HOME}/blob/main/part.step`;
111111
112112 /**
113 * The fixture repository (#12928): a .docx, a .pptx, an .ora and a .mid, each with a
113 * The fixture repository (#12928): a .docx, a .pptx and an .ora, each with a
114114 * desk and a phone look. The seed refuses to finish unless each page answers
115115 * 200 and its first-paint HTML holds the marker below, drawn by the office
116116 * renderer from the fixture (a plain file page holds none of them).
117117 */
118118 export const PREVIEW_FIXTURES = "fixtures";
119119 export const PREVIEW_FIXTURES_HOME = `/${PREVIEW_ADMIN}/${PREVIEW_FIXTURES}`;
120 export const PREVIEW_OFFICE_FILES: readonly string[] = ["notes.docx", "deck.pptx", "sketch.ora", "tune.mid"];
120 export const PREVIEW_OFFICE_FILES: readonly string[] = ["notes.docx", "deck.pptx", "sketch.ora"];
121121 export const PREVIEW_OFFICE_PAGES: readonly string[] = PREVIEW_OFFICE_FILES.map(
122122 (file) => `${PREVIEW_FIXTURES_HOME}/blob/main/${file}`,
123123 );
@@ -126,7 +126,6 @@ export const PREVIEW_OFFICE_MARKERS: Readonly<Record<string, string>> = {
126126 "notes.docx": "Heading one",
127127 "deck.pptx": "Welcome to the forge",
128128 "sketch.ora": "Stripe",
129 "tune.mid": "Piano roll of",
130129 };
131130
132131 /** The waves page, whose long headlines must wrap at a 390 px phone (#9325). */
src/spawn/preview-office.ts −18
@@ -136,23 +136,6 @@ export function buildOra(): Uint8Array {
136136 ]);
137137 }
138138
139 /**
140 * A small Standard MIDI File: a conductor track (120 bpm, 4/4) and two named tracks that play a
141 * C major arpeggio over two bars, so the roll has several rows and two shades.
142 */
143 export function buildMid(): Uint8Array {
144 const u32 = (n: number) => [n >>> 24, (n >> 16) & 255, (n >> 8) & 255, n & 255];
145 const chunk = (id: string, d: number[]) => [...enc(id), ...u32(d.length), ...d];
146 const name = (s: string) => [0, 0xff, 0x03, s.length, ...enc(s)];
147 const end = [0, 0xff, 0x2f, 0];
148 const conductor = chunk("MTrk", [...name("Tune"), 0, 0xff, 0x51, 3, 0x07, 0xa1, 0x20, 0, 0xff, 0x58, 4, 4, 2, 24, 8, ...end]);
149 // Each note: on at delta 0, off 240 ticks later (a quaver at 480 per quarter), on channel `ch`.
150 const notes = (keys: number[], ch: number) => keys.flatMap((k) => [0, 0x90 | ch, k, 80, 0x81, 0x70, 0x80 | ch, k, 0]);
151 const lead = chunk("MTrk", [...name("Lead"), ...notes([72, 76, 79, 84, 79, 76, 72, 67], 0), ...end]);
152 const bass = chunk("MTrk", [...name("Bass"), ...notes([48, 55, 52, 55, 48, 55, 52, 43], 1), ...end]);
153 return new Uint8Array([...chunk("MThd", [0, 1, 0, 3, 0x01, 0xe0]), ...conductor, ...lead, ...bass]);
154 }
155
156139 /** The fixture repository's files, in the order they are committed. */
157140 export function officeFixtures(): readonly { readonly path: string; readonly content: Uint8Array }[] {
158141 return [
@@ -160,6 +143,5 @@ export function officeFixtures(): readonly { readonly path: string; readonly con
160143 { path: "notes.docx", content: buildDocx() },
161144 { path: "deck.pptx", content: buildPptx() },
162145 { path: "sketch.ora", content: buildOra() },
163 { path: "tune.mid", content: buildMid() },
164146 ];
165147 }
src/tui/screens/workspace.ts +1 −2
@@ -95,7 +95,6 @@ import { sheetView } from "./workspace_sheet.ts";
9595 import { sqliteStep, sqliteView, type SqliteAt } from "./workspace_sqlite.ts";
9696 import { officeView } from "./workspace_office.ts";
9797 import { parquetView } from "./workspace_parquet.ts";
98 import { midiView } from "./workspace_midi.ts";
9998 import { layoutTable, type Grid } from "../ui/grid.ts";
10099 import type { Ctx, Screen } from "../app/app.ts";
101100 import { stripAnsi } from "../term/ansi.ts";
@@ -1553,7 +1552,7 @@ export function workspaceScreen(
15531552 // bytes as text is how a terminal ends up beeping at you.
15541553 const base = looksLikeImage(t.path) ? null : sqliteView(t.path, read.value.body, { table: 0, page: 1 });
15551554 if (base !== null && typeof base !== "string") db = read.value.body;
1556 const book = looksLikeImage(t.path) ? null : (base ?? sheetView(t.path, read.value.body) ?? officeView(t.path, read.value.body) ?? parquetView(t.path, read.value.body) ?? midiView(t.path, read.value.body));
1555 const book = looksLikeImage(t.path) ? null : (base ?? sheetView(t.path, read.value.body) ?? officeView(t.path, read.value.body) ?? parquetView(t.path, read.value.body));
15571556 if (looksLikeImage(t.path)) picture = read.value.body;
15581557 else if (book !== null && typeof book !== "string") sheet = book;
15591558 else if (typeof book === "string") note = book;
src/tui/screens/workspace_midi.ts deleted −28
@@ -1,28 +0,0 @@
1 /**
2 * A .mid file in the terminal workspace, read the way the page reads it: the same `parseMidi`, its
3 * facts first and then the tracks, drawn as a table. The same gate too: the name and the bytes must
4 * say so (`fileKind`), under the page's cap, and a file that cannot be read answers its reason. The
5 * piano roll is a picture and stays on the page; the table names every track the roll shades.
6 *
7 * `midiView(path, body)` answers a table, a sentence (the workspace shows it as its note), or
8 * `null` for a file that is not MIDI.
9 */
10
11 import { fileKind, HEAD_BYTES, RENDER_CAP } from "../../web/render/kinds.ts";
12 import { midiFacts, parseMidi, trackRows } from "../../web/render/midi.ts";
13 import type { Table } from "../../text/csv.ts";
14
15 export function midiView(path: string, body: Uint8Array): Table | string | null {
16 if (fileKind(path, body.subarray(0, HEAD_BYTES)) !== "midi") return null;
17 if (body.length > RENDER_CAP.midi) return `This file is over ${RENDER_CAP.midi / 1_000_000} MB, too large to open here. Download it instead.`;
18 const parsed = parseMidi(body);
19 if ("error" in parsed) return `This MIDI file cannot be shown: ${parsed.error}.`;
20 const m = parsed.midi;
21 const header = ["#", "Name", "Channels", "Notes", "Events"];
22 const pad = (cells: readonly string[]): string[] => [...cells, ...Array<string>(header.length - cells.length).fill("")];
23 // One fact a line, so a narrow first column still shows each whole; then a blank, then the
24 // tracks.
25 const facts = midiFacts(m).map(([k, v]) => pad([`${k}: ${v}`]));
26 const rows = [...facts, pad([]), ...trackRows(m)];
27 return { header, rows, more: Math.max(0, m.tracks.length - (rows.length - facts.length - 1)), delimiter: ",", columns: header.length };
28 }
src/web/render/kinds.ts −5
@@ -45,7 +45,6 @@ export type FileKind =
4545 | "calendar"
4646 | "otio"
4747 | "edl"
48 | "midi"
4948 | "fcpxml"
5049 | "contacts"
5150 | "mail"
@@ -131,8 +130,6 @@ export const RENDER_CAP: Readonly<Record<FileKind, number>> = {
131130 // not drawn.
132131 otio: 1 * MB,
133132 edl: 1 * MB,
134 // A MIDI file is read whole and parsed once; 1 MB holds a long score.
135 midi: 1 * MB,
136133 fcpxml: 1 * MB,
137134 contacts: 1 * MB,
138135 mail: 5 * MB,
@@ -245,8 +242,6 @@ const MEDIA: Readonly<Record<string, Media>> = {
245242 sqlite: { kind: "sqlite", name: "SQLite", type: "application/vnd.sqlite3", magic: ascii("SQLite format 3\0") },
246243 sqlite3: { kind: "sqlite", name: "SQLite", type: "application/vnd.sqlite3", magic: ascii("SQLite format 3\0") },
247244 parquet: { kind: "parquet", name: "Parquet", type: "application/vnd.apache.parquet", magic: ascii("PAR1") },
248 mid: { kind: "midi", name: "MIDI", type: "audio/midi", magic: ascii("MThd") },
249 midi: { kind: "midi", name: "MIDI", type: "audio/midi", magic: ascii("MThd") },
250245 stl: { kind: "model3d", name: "STL", type: "model/stl" },
251246 ttf: { kind: "font", name: "TrueType", type: "font/ttf", magic: bytes(0x00, 0x01, 0x00, 0x00) },
252247 otf: { kind: "font", name: "OpenType", type: "font/otf", magic: ascii("OTTO") },
src/web/render/midi-css.ts deleted −10
@@ -1,10 +0,0 @@
1 /** The MIDI piano roll's styles, apart from `midi.ts` so `style.ts` imports no renderer. */
2
3 export const midiCss = /* css */ `
4 @layer content {
5 .midi-view { margin: 0; }
6 .midi-roll { margin: 12px 0; max-height: 60dvh; overflow: auto; color: var(--fg); }
7 .midi-roll svg { display: block; width: 100%; min-width: 720px; height: auto; }
8 .midi-key { display: block; color: var(--fg); }
9 }
10 `;
src/web/render/midi.ts deleted −283
@@ -1,283 +0,0 @@
1 /**
2 * A Standard MIDI File (`.mid`, `.midi`) as its facts and a piano roll.
3 *
4 * Layout (Standard MIDI Files 1.0, MMA): an `MThd` chunk (format, track count, division), then
5 * `MTrk` chunks of events, each a variable-length delta time and a status byte. A data byte in
6 * status position reuses the last channel status (running status); meta events (`FF type len`)
7 * and sysex (`F0`/`F7 len`) carry a length and cancel it. Note On with velocity 0 is Note Off.
8 *
9 * Time: with a positive division, it is ticks per quarter note and the tempo (meta `51`, µs per
10 * quarter, default 500000 = 120 bpm) turns ticks to seconds, summed over the tempo map of all
11 * tracks; with SMPTE division (high bit set), ticks per second is frames × ticks per frame.
12 *
13 * The file is untrusted, and the caller has capped its size: every loop here advances at least one
14 * byte and stops at the end of the body, every length is checked against what is left, and only
15 * the first `NOTE_CAP` notes are kept. A file that is not a well-formed MIDI file is refused
16 * (the source view stays); nothing here throws.
17 */
18
19 import { escapeHtml, html, raw, type Html } from "../html.ts";
20 import { fileSize } from "../ui.ts";
21 import type { Rendered, RenderInput } from "./renderers.ts";
22
23 /** Notes drawn; the rest are counted and left out. */
24 export const NOTE_CAP = 5000;
25 /** Track rows listed; the rest are counted. */
26 const TRACK_ROWS = 100;
27
28 export interface Note { readonly track: number; readonly pitch: number; readonly start: number; readonly end: number }
29 export interface MidiTrack { name: string; notes: number; events: number; channels: Set<number> }
30 export interface Midi {
31 readonly format: number;
32 /** Ticks per quarter note, or 0 when the file uses SMPTE time. */
33 readonly ppq: number;
34 /** Ticks per second for SMPTE division, else 0. */
35 readonly tps: number;
36 readonly tracks: readonly MidiTrack[];
37 readonly notes: readonly Note[];
38 readonly totalNotes: number;
39 /** Tempo changes: tick and microseconds per quarter note, by tick. */
40 readonly tempos: readonly (readonly [number, number])[];
41 readonly signature: { readonly num: number; readonly den: number } | undefined;
42 readonly lengthTicks: number;
43 readonly seconds: number;
44 }
45
46 export type Parsed = { readonly midi: Midi } | { readonly error: string };
47
48 const text = (b: Uint8Array, from: number, to: number): string =>
49 Array.from(b.subarray(from, to), (c) => (c >= 32 && c < 127 ? String.fromCharCode(c) : c >= 160 ? String.fromCharCode(c) : "")).join("").trim().slice(0, 100);
50
51 export function parseMidi(b: Uint8Array): Parsed {
52 if (b.length < 14 || String.fromCharCode(b[0]!, b[1]!, b[2]!, b[3]!) !== "MThd") return { error: "it has no MIDI header" };
53 const v = new DataView(b.buffer, b.byteOffset, b.byteLength);
54 const hlen = v.getUint32(4, false);
55 if (hlen < 6 || 8 + hlen > b.length) return { error: "its header is cut off" };
56 const format = v.getUint16(8, false);
57 const division = v.getUint16(12, false);
58 if (format > 2) return { error: `format ${format} is not a MIDI file format` };
59 let ppq = 0;
60 let tps = 0;
61 if (division & 0x8000) {
62 const fps = 256 - (division >> 8);
63 tps = fps * (division & 0xff);
64 if (![24, 25, 29, 30].includes(fps) || tps === 0) return { error: "its SMPTE time division is not valid" };
65 } else {
66 ppq = division;
67 if (ppq === 0) return { error: "its time division is zero" };
68 }
69
70 const tracks: MidiTrack[] = [];
71 const notes: Note[] = [];
72 const tempos: [number, number][] = [];
73 let signature: Midi["signature"];
74 let totalNotes = 0;
75 let lengthTicks = 0;
76 let pos = 8 + hlen;
77
78 while (pos + 8 <= b.length) {
79 const id = String.fromCharCode(b[pos]!, b[pos + 1]!, b[pos + 2]!, b[pos + 3]!);
80 const len = v.getUint32(pos + 4, false);
81 const start = pos + 8;
82 if (len > b.length - start) return { error: `chunk ${tracks.length + 1} is cut off` };
83 pos = start + len;
84 if (id !== "MTrk") continue; // unknown chunks are skipped, as the standard asks
85 const index = tracks.length;
86 const track: MidiTrack = { name: "", notes: 0, events: 0, channels: new Set() };
87 const open = new Map<number, number[]>();
88 let p = start;
89 let tick = 0;
90 let status = 0;
91 const vlq = (): number => {
92 let n = 0;
93 for (let i = 0; i < 4; i++) {
94 if (p >= pos) return -1;
95 const c = b[p++]!;
96 n = n * 128 + (c & 0x7f);
97 if ((c & 0x80) === 0) return n;
98 }
99 return -1;
100 };
101 const close = (key: number, at: number): void => {
102 const q = open.get(key);
103 const s = q?.shift();
104 if (s === undefined) return;
105 if (notes.length < NOTE_CAP) notes.push({ track: index, pitch: key & 127, start: s, end: Math.max(s, at) });
106 };
107 while (p < pos) {
108 const delta = vlq();
109 if (delta < 0) return { error: `track ${index + 1} has a bad delta time` };
110 tick += delta;
111 if (p >= pos) return { error: `track ${index + 1} is cut off` };
112 let first = b[p]!;
113 if (first >= 0x80) { p++; if (first < 0xf0) status = first; } else if (status === 0) return { error: `track ${index + 1} starts without a status` };
114 else first = status;
115 track.events++;
116 if (first === 0xff) {
117 if (p >= pos) return { error: `track ${index + 1} is cut off` };
118 const type = b[p++]!;
119 const n = vlq();
120 if (n < 0 || p + n > pos) return { error: `track ${index + 1} has a cut-off meta event` };
121 if (type === 0x03 && track.name === "") track.name = text(b, p, p + n);
122 else if (type === 0x51 && n === 3) {
123 const us = (b[p]! << 16) | (b[p + 1]! << 8) | b[p + 2]!;
124 if (us > 0) tempos.push([tick, us]); // a tempo of 0 µs is no tempo: it would be infinite bpm
125 } else if (type === 0x58 && n >= 2 && signature === undefined && b[p + 1]! <= 15)
126 signature = { num: b[p]!, den: 2 ** b[p + 1]! };
127 p += n;
128 if (type === 0x2f) break;
129 continue;
130 }
131 if (first === 0xf0 || first === 0xf7) {
132 const n = vlq();
133 if (n < 0 || p + n > pos) return { error: `track ${index + 1} has a cut-off system message` };
134 p += n;
135 continue;
136 }
137 if (first >= 0xf1) return { error: `track ${index + 1} holds an invalid status byte` };
138 const kind = first & 0xf0;
139 const size = kind === 0xc0 || kind === 0xd0 ? 1 : 2;
140 if (p + size > pos) return { error: `track ${index + 1} is cut off` };
141 const d1 = b[p]!;
142 const d2 = size === 2 ? b[p + 1]! : 0;
143 if (d1 > 127 || d2 > 127) return { error: `track ${index + 1} holds a data byte over 127` };
144 p += size;
145 const channel = first & 0x0f;
146 track.channels.add(channel);
147 const key = channel * 128 + d1;
148 if (kind === 0x90 && d2 > 0) {
149 track.notes++;
150 totalNotes++;
151 const q = open.get(key);
152 if (q === undefined) open.set(key, [tick]);
153 else q.push(tick);
154 } else if (kind === 0x80 || kind === 0x90) close(key, tick);
155 }
156 for (const key of open.keys()) while (open.get(key)!.length > 0) close(key, tick);
157 lengthTicks = Math.max(lengthTicks, tick);
158 tracks.push(track);
159 }
160 if (tracks.length === 0) return { error: "it has no tracks" };
161 // The header's declared track count is not used: a wrong one is common; the chunks present are
162 // read.
163
164 tempos.sort((x, y) => x[0] - y[0]);
165 let seconds: number;
166 if (tps > 0) seconds = lengthTicks / tps;
167 else {
168 seconds = 0;
169 let at = 0;
170 let us = 500_000;
171 for (const [t, tempo] of tempos) {
172 if (t >= lengthTicks) break;
173 seconds += ((t - at) * us) / ppq / 1e6;
174 at = t;
175 us = tempo;
176 }
177 seconds += ((lengthTicks - at) * us) / ppq / 1e6;
178 }
179 return { midi: { format, ppq, tps, tracks, notes, totalNotes, tempos, signature, lengthTicks, seconds } };
180 }
181
182 /** Beats per minute from microseconds per quarter note: 60 000 000 / µs (MMA, SMF 1.0). */
183 export const bpm = (us: number): number => Math.round((6e7 / us) * 100) / 100;
184
185 const clock = (s: number): string => {
186 const m = Math.floor(s / 60);
187 return `${m}:${(s - m * 60).toFixed(1).padStart(4, "0")}`;
188 };
189
190 /**
191 * A track is told by its shade, not a hue: the roll is data, so it takes the text colour at four
192 * opacities, cycled, and the table beside it names each track beside its swatch.
193 */
194 const SHADES = [0.95, 0.7, 0.5, 0.3];
195 const shade = (track: number): number => SHADES[track % SHADES.length]!;
196 const W = 960;
197 const ROW = 8;
198
199 /** The piano roll: a `<g>` per track (named by a `<title>`), one rect per note; no frame. */
200 export function rollSvg(m: Midi): Html {
201 if (m.notes.length === 0) return raw("");
202 let lo = 127;
203 let hi = 0;
204 for (const n of m.notes) { lo = Math.min(lo, n.pitch); hi = Math.max(hi, n.pitch); }
205 lo = Math.max(0, Math.min(lo, hi - 11));
206 const rows = hi - lo + 1;
207 const H = rows * ROW;
208 const span = Math.max(1, m.lengthTicks);
209 const byTrack = new Map<number, string[]>();
210 for (const n of m.notes) {
211 const x = (n.start / span) * W;
212 const w = Math.max(1, ((n.end - n.start) / span) * W);
213 const y = (hi - n.pitch) * ROW;
214 const list = byTrack.get(n.track) ?? [];
215 list.push(`<rect x="${x.toFixed(1)}" y="${y}" width="${w.toFixed(1)}" height="${ROW - 1}"/>`);
216 byTrack.set(n.track, list);
217 }
218 const groups = [...byTrack]
219 .sort((x, y) => x[0] - y[0])
220 .map(([t, rects]) => {
221 const tr = m.tracks[t];
222 const label = `Track ${t + 1}${tr !== undefined && tr.name !== "" ? `: ${tr.name}` : ""}`;
223 return `<g fill="currentColor" fill-opacity="${shade(t)}"><title>${escapeHtml(label)}</title>${rects.join("")}</g>`;
224 })
225 .join("");
226 return raw(
227 `<div class="midi-roll" tabindex="0" role="group" aria-label="Piano roll, scrolls sideways"><svg viewBox="0 0 ${W} ${H}" role="img" aria-label="Piano roll of ${m.notes.length} notes, pitches ${lo} to ${hi}">${groups}</svg></div>`,
228 );
229 }
230
231 /** The facts above the roll, as label and value; the page and the terminal screen share them. */
232 export function midiFacts(m: Midi): [string, string][] {
233 const first = m.tempos[0];
234 const distinct = new Set(m.tempos.map((t) => t[1])).size;
235 const tempo =
236 m.tps > 0 ? "none (SMPTE time)"
237 : first === undefined ? "120 bpm (none set; the standard's default)"
238 : distinct > 1 ? `${bpm(first[1])} bpm at the start, then ${distinct - 1} other ${distinct === 2 ? "tempo" : "tempos"}`
239 : `${bpm(first[1])} bpm`;
240 const sig = m.signature === undefined ? "4/4 (none set; the standard's default)" : `${m.signature.num}/${m.signature.den}`;
241 const division = m.ppq > 0 ? `${m.ppq} ticks per quarter note` : `${m.tps} ticks per second`;
242 return [
243 ["Format", `${m.format} (${["one track", "simultaneous tracks", "independent sequences"][m.format]})`],
244 ["Tracks", m.tracks.length.toLocaleString("en")],
245 ["Tempo", tempo],
246 ["Time signature", sig],
247 ["Length", `${clock(m.seconds)} (${m.lengthTicks.toLocaleString("en")} ticks; ${division})`],
248 ["Notes", m.totalNotes.toLocaleString("en")],
249 ];
250 }
251
252 /** The tracks listed, one row each: channels are one-based, as a player shows them. */
253 export const trackRows = (m: Midi): string[][] =>
254 m.tracks.slice(0, TRACK_ROWS).map((t, i) => [
255 String(i + 1),
256 t.name,
257 [...t.channels].sort((a, b) => a - b).map((c) => c + 1).join(", "),
258 t.notes.toLocaleString("en"),
259 t.events.toLocaleString("en"),
260 ]);
261
262 const swatch = (i: number): Html =>
263 raw(`<svg class="midi-key" viewBox="0 0 16 8" width="16" height="8" aria-hidden="true"><rect width="16" height="8" fill="currentColor" fill-opacity="${shade(i)}"/></svg>`);
264
265 export function midi(input: RenderInput): Rendered {
266 const parsed = parseMidi(input.body);
267 if ("error" in parsed) return { content: html``, lines: 0, fallback: `This MIDI file cannot be drawn: ${parsed.error}.` };
268 const m = parsed.midi;
269 const facts = midiFacts(m);
270 const rows = trackRows(m);
271 const content = html`<figure class="midi-view">
272 <dl class="status-rows">${facts.map(([k, v]) => html`<div class="status-row"><dt>${k}</dt><dd>${v}</dd></div>`)}</dl>
273 ${rollSvg(m)}
274 <p class="muted small">${m.totalNotes === 0 ? "The file has no notes to draw." : `Pitch runs up, time runs right; each track has its own shade, keyed in the table.${m.totalNotes > m.notes.length ? ` Drawing the first ${m.notes.length.toLocaleString("en")} of ${m.totalNotes.toLocaleString("en")} notes.` : ""}`}</p>
275 <div class="table-scroll"><table class="table" data-dense><caption>Tracks</caption>
276 <thead><tr>${["Shade", "#", "Name", "Channels", "Notes", "Events"].map((h) => html`<th scope="col">${h}</th>`)}</tr></thead>
277 <tbody>${rows.map((r, i) => html`<tr><td>${swatch(i)}</td>${r.map((c) => html`<td>${c}</td>`)}</tr>`)}${
278 m.tracks.length > rows.length ? html`<tr><td colspan="6" class="muted small">${(m.tracks.length - rows.length).toLocaleString("en")} more tracks are in the raw file.</td></tr>` : ""
279 }</tbody></table></div>
280 <p class="small"><a href="${input.download}">Download</a></p>
281 </figure>`;
282 return { content, lines: 0, summary: `${m.tracks.length.toLocaleString("en")} ${m.tracks.length === 1 ? "track" : "tracks"} · ${clock(m.seconds)} · ${fileSize(input.size)}` };
283 }
src/web/render/renderers.ts −2
@@ -33,7 +33,6 @@ import { font } from "./font.ts";
3333 import { ics } from "./ics.ts";
3434 import { otio } from "./otio.ts";
3535 import { edl } from "./edl.ts";
36 import { midi } from "./midi.ts";
3736 import { fcpxml } from "./fcpxml.ts";
3837 import { junit } from "./junit.ts";
3938 import { feedXml } from "./feed-xml.ts";
@@ -155,7 +154,6 @@ export const RENDERERS: Partial<Readonly<Record<FileKind, Renderer>>> = {
155154 calendar: ics,
156155 otio,
157156 edl,
158 midi,
159157 fcpxml,
160158 contacts: vcf,
161159 sarif,
src/web/style.ts −2
@@ -28,7 +28,6 @@ import { homeFlowCss } from "./pages/home_flow_style.ts";
2828 import { base, layers, reset, utilities } from "./style/base.ts";
2929 import { components } from "./style/components.ts";
3030 import { content } from "./style/content.ts";
31 import { midiCss } from "./render/midi-css.ts";
3231 import { gcodeCss } from "./render/gcode-css.ts";
3332 import { model3dCss } from "./render/model3d-css.ts";
3433 import { pickCss } from "./pick.ts";
@@ -47,7 +46,6 @@ export const css = [
4746 content,
4847 model3dCss,
4948 gcodeCss,
50 midiCss,
5149 utilities,
5250 pickCss,
5351 ].join("\n");
test/fuzz-renderers.test.ts −1
@@ -331,7 +331,6 @@ export const EXCLUDED: Readonly<Record<string, string>> = {
331331 layers: "a zip of images (ora); needs a fixture to splice into",
332332 font: "binary font tables; needs a fixture to splice into",
333333 psd: "binary Photoshop layers; needs a fixture to splice into",
334 midi: "binary track chunks; test/render-midi.test.ts hand-builds the file and feeds it malformed bytes instead",
335334 };
336335
337336 /**
test/preview-office.test.ts +1 −1
@@ -16,7 +16,7 @@ const text = (b: Uint8Array | null): string => new TextDecoder().decode(b ?? und
1616
1717 test("every office page has a desk and a phone look", () => {
1818 expect(PREVIEW_OFFICE_PAGES).toEqual(
19 ["notes.docx", "deck.pptx", "sketch.ora", "tune.mid"].map((f) => `/${PREVIEW_ADMIN}/${PREVIEW_FIXTURES}/blob/main/${f}`),
19 ["notes.docx", "deck.pptx", "sketch.ora"].map((f) => `/${PREVIEW_ADMIN}/${PREVIEW_FIXTURES}/blob/main/${f}`),
2020 );
2121 for (const page of PREVIEW_OFFICE_PAGES)
2222 for (const kind of ["desktop", "phone"] as const)
test/render-kinds.test.ts −2
@@ -46,8 +46,6 @@ const SAMPLES: Record<string, [Uint8Array, FileKind, string]> = {
4646 db: [enc("SQLite format 3\0"), "sqlite", "application/vnd.sqlite3"],
4747 sqlite: [enc("SQLite format 3\0"), "sqlite", "application/vnd.sqlite3"],
4848 sqlite3: [enc("SQLite format 3\0"), "sqlite", "application/vnd.sqlite3"],
49 mid: [enc("MThd\0\0\0\x06"), "midi", "audio/midi"],
50 midi: [enc("MThd\0\0\0\x06"), "midi", "audio/midi"],
5149 parquet: [enc("PAR1"), "parquet", "application/vnd.apache.parquet"],
5250 csv: [enc("a,b\n1,2\n"), "csv", "application/octet-stream"],
5351 tsv: [enc("a\tb\n"), "csv", "application/octet-stream"],
test/render-midi.test.ts deleted −139
@@ -1,139 +0,0 @@
1 /**
2 * A MIDI file: parsed by hand-checked numbers, drawn as escaped SVG, and refused without throwing.
3 */
4
5 import { describe, expect, test } from "bun:test";
6 import { fileKind, RENDER_CAP } from "../src/web/render/kinds.ts";
7 import { bpm, midi, midiFacts, NOTE_CAP, parseMidi, rollSvg } from "../src/web/render/midi.ts";
8 import { midiView } from "../src/tui/screens/workspace_midi.ts";
9 import { rendererFor } from "../src/web/render/renderers.ts";
10
11 const u32 = (n: number): number[] => [n >>> 24, (n >> 16) & 255, (n >> 8) & 255, n & 255];
12 const chunk = (id: string, data: number[]): number[] => [...[...id].map((c) => c.charCodeAt(0)), ...u32(data.length), ...data];
13 const ascii = (s: string): number[] => [...new TextEncoder().encode(s)];
14 const header = (tracks: number, division = 480): number[] => chunk("MThd", [0, 1, 0, tracks, division >> 8, division & 255]);
15 const name = (s: string): number[] => [0, 0xff, 0x03, s.length, ...ascii(s)];
16 const END = [0, 0xff, 0x2f, 0];
17
18 // Track 1: 120 bpm (500000 µs = 07 A1 20), 3/4, named with markup.
19 const conductor = chunk("MTrk", [...name("A<b>&"), 0, 0xff, 0x51, 3, 0x07, 0xa1, 0x20, 0, 0xff, 0x58, 4, 3, 2, 24, 8, ...END]);
20 // Track 2: C4 on at 0, then running status: off (vel 0) at 480, E4 on at 0+0 delta, off at 960.
21 // 0x90 3C 40 | d=480 3C 00 (running) | d=0 40 40 (running) | d=480 40 00 (running).
22 const lead = chunk("MTrk", [
23 ...name("Lead"),
24 0, 0x90, 0x3c, 0x40,
25 0x83, 0x60, 0x3c, 0x00,
26 0, 0x40, 0x40,
27 0x83, 0x60, 0x40, 0x00,
28 ...END,
29 ]);
30 const FILE = new Uint8Array([...header(2), ...conductor, ...lead]);
31 const input = (body: Uint8Array) => ({ path: "a.mid", size: body.length, body, media: "/m", download: "/d" });
32
33 describe("parseMidi", () => {
34 test("reads tracks, tempo, signature, notes and length as a hand calculation does", () => {
35 const r = parseMidi(FILE);
36 if (!("midi" in r)) throw new Error(r.error);
37 const m = r.midi;
38 expect(m.format).toBe(1);
39 expect(m.tracks.map((t) => t.name)).toEqual(["A<b>&", "Lead"]);
40 expect(m.tempos).toEqual([[0, 500000]]);
41 expect(bpm(500000)).toBe(120);
42 expect(m.signature).toEqual({ num: 3, den: 4 });
43 expect(m.totalNotes).toBe(2);
44 expect(m.notes.map((n) => [n.pitch, n.start, n.end])).toEqual([[60, 0, 480], [64, 480, 960]]);
45 // 960 ticks at 480 ticks per quarter and 0.5 s per quarter is exactly 1 s.
46 expect(m.lengthTicks).toBe(960);
47 expect(m.seconds).toBeCloseTo(1, 9);
48 });
49
50 test("a tempo change counts from its tick: 480 ticks at 0.5 s, 480 at 0.25 s", () => {
51 const t = chunk("MTrk", [0, 0xff, 0x51, 3, 0x07, 0xa1, 0x20, 0x83, 0x60, 0xff, 0x51, 3, 0x03, 0xd0, 0x90, 0x83, 0x60, 0xff, 0x2f, 0]);
52 const r = parseMidi(new Uint8Array([...header(1), ...t]));
53 if (!("midi" in r)) throw new Error(r.error);
54 expect(r.midi.seconds).toBeCloseTo(0.75, 9);
55 });
56
57 test("malformed input is an error, never a throw", () => {
58 for (const cut of [0, 3, 13, 20, 30, FILE.length - 3]) {
59 expect(parseMidi(FILE.subarray(0, cut))).toHaveProperty("error");
60 }
61 expect(parseMidi(new Uint8Array([...header(1), ...chunk("MTrk", [0, 0x90, 0x3c])]))).toHaveProperty("error");
62 expect(parseMidi(new Uint8Array([...header(1), ...chunk("MTrk", [0, 0xff, 0x03, 9, 65])]))).toHaveProperty("error");
63 expect(parseMidi(new Uint8Array([...header(1), ...chunk("MTrk", [0x80, 0x80, 0x80, 0x80, 0x01, 0x90])]))).toHaveProperty("error");
64 expect(parseMidi(new Uint8Array([...header(1, 0), ...lead]))).toHaveProperty("error");
65 expect(parseMidi(new TextEncoder().encode("MThd but not really a midi file"))).toHaveProperty("error");
66 const noise = new Uint8Array(5000).map((_, i) => (i * 2654435761) >>> 24);
67 noise.set(ascii("MThd"), 0);
68 expect(() => parseMidi(noise)).not.toThrow();
69 });
70 });
71
72 describe("the MIDI view", () => {
73 test("lists the facts, escapes the track name and draws one rect per note", () => {
74 const out = midi(input(FILE));
75 expect(out.fallback).toBeUndefined();
76 const text = out.content.text;
77 expect(text).toContain("120 bpm");
78 expect(text).toContain("3/4");
79 expect(text).toContain("0:01.0");
80 expect(text).toContain("A&lt;b&gt;&amp;");
81 expect(text).not.toContain("<b>");
82 expect(text.match(/<rect x=/g)?.length).toBe(2);
83 expect(text).not.toContain("<script");
84 });
85
86 test("notes past the cap are counted, not drawn", () => {
87 const ev: number[] = [];
88 for (let i = 0; i < NOTE_CAP + 10; i++) ev.push(0, 0x90, 0x3c, 0x40, 1, 0x3c, 0);
89 const out = midi(input(new Uint8Array([...header(1), ...chunk("MTrk", [...ev, ...END])])));
90 expect(out.content.text.match(/<rect x=/g)?.length).toBe(NOTE_CAP);
91 expect(out.content.text).toContain("Drawing the first 5,000 of 5,010 notes");
92 });
93
94 test("a malformed file asks for the source view", () => {
95 const out = midi(input(FILE.subarray(0, 30)));
96 expect(out.fallback).toContain("cannot be drawn");
97 });
98 });
99
100 describe("the MIDI kind", () => {
101 test("is found by name and signature, drawn from the registry, and capped", () => {
102 expect(fileKind("x.mid", FILE)).toBe("midi");
103 expect(fileKind("x.MIDI", FILE)).toBe("midi");
104 expect(fileKind("x.mid", new Uint8Array([0, 1, 2, 0]))).toBe("binary");
105 const blob = { kind: "binary", body: FILE, size: FILE.length } as const;
106 expect(rendererFor("x.mid", blob)).toBeDefined();
107 expect(rendererFor("x.mid", { kind: "binary", body: FILE, size: RENDER_CAP.midi + 1 })).toBeUndefined();
108 });
109 });
110
111 describe("review round: tempo, key, terminal", () => {
112 test("a tempo of 0 µs is ignored, not drawn as Infinity bpm", () => {
113 const t = chunk("MTrk", [0, 0xff, 0x51, 3, 0, 0, 0, 0x83, 0x60, 0xff, 0x2f, 0]);
114 const r = parseMidi(new Uint8Array([...header(1), ...t]));
115 if (!("midi" in r)) throw new Error(r.error);
116 expect(r.midi.tempos).toEqual([]);
117 expect(r.midi.seconds).toBeCloseTo(0.5, 9);
118 expect(JSON.stringify(midiFacts(r.midi))).not.toContain("Infinity");
119 });
120 test("each track is a <g> named by its title, shaded by currentColor, with no frame and no accent", () => {
121 const r = parseMidi(FILE);
122 if (!("midi" in r)) throw new Error(r.error);
123 const svg = rollSvg(r.midi).text;
124 expect(svg).toContain("<title>Track 2: Lead</title>");
125 expect(svg).toContain('fill="currentColor"');
126 expect(svg).not.toContain("stroke");
127 expect(svg).not.toContain("var(--");
128 expect(svg).toContain('class="midi-roll"');
129 });
130 test("the terminal table: facts, a blank, then one row a track", () => {
131 const v = midiView("a.mid", FILE);
132 if (typeof v === "string" || v === null) throw new Error(String(v));
133 expect(v.rows[0]![0]).toBe("Format: 1 (simultaneous tracks)");
134 expect(v.rows.some((r) => r[0] === "Tempo: 120 bpm")).toBe(true);
135 expect(v.rows.at(-1)).toEqual(["2", "Lead", "1", "2", "6"]);
136 expect(midiView("a.txt", FILE)).toBeNull();
137 expect(midiView("a.mid", new TextEncoder().encode("MThd nope nope nope"))).toContain("cannot be shown");
138 });
139 });
test/tui-workspace-formats.test.ts −19
@@ -970,25 +970,6 @@ describe("the terminal workspace, by file type", () => {
970970 h.stop();
971971 }
972972 });
973 test("a .mid file opens as its facts and its tracks, read by the page's parser", async () => {
974 const made = await createRepo(forge, alice, { name: "tunes", visibility: "public", description: "midi" });
975 if (!made.ok) throw new Error("repo failed");
976 const u32 = (n: number) => [n >>> 24, (n >> 16) & 255, (n >> 8) & 255, n & 255];
977 const chunk = (id: string, d: number[]) => [...[...id].map((c) => c.charCodeAt(0)), ...u32(d.length), ...d];
978 const name = [...[0, 0xff, 0x03, 4], ...[..."Lead"].map((c) => c.charCodeAt(0))];
979 const body = [...chunk("MThd", [0, 1, 0, 1, 1, 0xe0]), ...chunk("MTrk", [...name, 0, 0xff, 0x51, 3, 0x07, 0xa1, 0x20, 0, 0x90, 60, 64, 0x60, 0x80, 60, 0, 0, 0xff, 0x2f, 0])];
980 await commitToBranch(forge, alice, made.value, { message: "seed", files: [{ path: "tune.mid", content: new Uint8Array(body) }] });
981 const h = boot();
982 try {
983 await h.settle();
984 await open(h, "tunes");
985 await openFile(h, "tune.mid");
986 expect(h.text()).toContain("Tempo: 120 bpm");
987 expect(h.text()).toContain("Lead");
988 } finally {
989 h.stop();
990 }
991 });
992973 test("a SQLite file opens as one table, its schema on top, paged by 100 with > < and } {", async () => {
993974 const made = await createRepo(forge, alice, { name: "dbs", visibility: "public", description: "data" });
994975 if (!made.ok) throw new Error("repo failed");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs