Public: anyone can read this; the crew can change it.
A .mid file shows its tracks, tempo and a piano roll #14470
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/14452-a-mid-file-shows-its-tracks-tempo-and-a → main 11 commits fork 5 threads · 5 unresolved
docs/design/areas/render.md +4
| @@ -91,6 +91,10 @@ A .zip, .tar or .tar.gz is drawn by `src/web/render/archive-view.ts` as the exis | ||
| 91 | 91 | |
| 92 | 92 | - `.pdf-facts`: the page count, title and author above a PDF's viewer, one line of label and value pairs. |
| 93 | 93 | |
| 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 | ||
| 94 | 98 | ## Copper layer (.gbr) |
| 95 | 99 | |
| 96 | 100 | `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,6 +39,7 @@ The forge draws a file on its page when its kind is below and it is within the s | ||
| 39 | 39 | - **Calendar**, drawn up to 5 MB: `.ics` |
| 40 | 40 | - **OpenTimelineIO**, drawn up to 1 MB: `.otio` |
| 41 | 41 | - **Edit list**, drawn up to 1 MB: `.edl` |
| 42 | - **MIDI file**, drawn up to 1 MB: `.mid`, `.midi` | |
| 42 | 43 | - **Final Cut XML**, drawn up to 1 MB: `.fcpxml` |
| 43 | 44 | - **Contacts**, drawn up to 1 MB: `.vcf`, `.vcard` |
| 44 | 45 | - **Email**, drawn up to 5 MB: `.eml` |
| @@ -72,3 +73,5 @@ The forge draws a file on its page when its kind is below and it is within the s | ||
| 72 | 73 | - **Other binary**, none: download only: any other bytes |
| 73 | 74 | |
| 74 | 75 | <!-- 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>> = { | ||
| 13 | 13 | sqlite: "SQLite database", parquet: "Parquet", model3d: "3D model", archive: "Archive", sheet: "Spreadsheet", document: "Word document", |
| 14 | 14 | slides: "Slides", layers: "Layered image", font: "Font", psd: "Photoshop", config: "Config", markdown: "Markdown", |
| 15 | 15 | 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", fcpxml: "Final Cut XML", | |
| 16 | geojson: "GeoJSON", kml: "KML", calendar: "Calendar", otio: "OpenTimelineIO", edl: "Edit list", midi: "MIDI file", fcpxml: "Final Cut XML", | |
| 17 | 17 | contacts: "Contacts", mail: "Email", gcode: "G-code", dxf: "DXF drawing", gerber: "Gerber layer", mermaid: "Mermaid diagram", drawio: "draw.io diagram", |
| 18 | 18 | excalidraw: "Excalidraw", step: "STEP model", sarif: "SARIF report", lcov: "Coverage (lcov)", junit: "JUnit report", |
| 19 | 19 | opml: "OPML", feed: "RSS or Atom feed", env: "Env example", openapi: "OpenAPI", package: "package.json", makefile: "Makefile", |
src/spawn/preview-looks.ts +3 −2
| @@ -110,14 +110,14 @@ export const PREVIEW_SEARCH_PAGE = "/search?q=sample"; | ||
| 110 | 110 | export const PREVIEW_STEP_PAGE = `${PREVIEW_REPO_HOME}/blob/main/part.step`; |
| 111 | 111 | |
| 112 | 112 | /** |
| 113 | * The fixture repository (#12928): a .docx, a .pptx and an .ora, each with a | |
| 113 | * The fixture repository (#12928): a .docx, a .pptx, an .ora and a .mid, each with a | |
| 114 | 114 | * desk and a phone look. The seed refuses to finish unless each page answers |
| 115 | 115 | * 200 and its first-paint HTML holds the marker below, drawn by the office |
| 116 | 116 | * renderer from the fixture (a plain file page holds none of them). |
| 117 | 117 | */ |
| 118 | 118 | export const PREVIEW_FIXTURES = "fixtures"; |
| 119 | 119 | export const PREVIEW_FIXTURES_HOME = `/${PREVIEW_ADMIN}/${PREVIEW_FIXTURES}`; |
| 120 | export const PREVIEW_OFFICE_FILES: readonly string[] = ["notes.docx", "deck.pptx", "sketch.ora"]; | |
| 120 | export const PREVIEW_OFFICE_FILES: readonly string[] = ["notes.docx", "deck.pptx", "sketch.ora", "tune.mid"]; | |
| 121 | 121 | export const PREVIEW_OFFICE_PAGES: readonly string[] = PREVIEW_OFFICE_FILES.map( |
| 122 | 122 | (file) => `${PREVIEW_FIXTURES_HOME}/blob/main/${file}`, |
| 123 | 123 | ); |
| @@ -126,6 +126,7 @@ export const PREVIEW_OFFICE_MARKERS: Readonly<Record<string, string>> = { | ||
| 126 | 126 | "notes.docx": "Heading one", |
| 127 | 127 | "deck.pptx": "Welcome to the forge", |
| 128 | 128 | "sketch.ora": "Stripe", |
| 129 | "tune.mid": "Piano roll of", | |
| 129 | 130 | }; |
| 130 | 131 | |
| 131 | 132 | /** The waves page, whose long headlines must wrap at a 390 px phone (#9325). */ |
src/spawn/preview-office.ts +18
| @@ -136,6 +136,23 @@ export function buildOra(): Uint8Array { | ||
| 136 | 136 | ]); |
| 137 | 137 | } |
| 138 | 138 | |
| 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 | ||
| 139 | 156 | /** The fixture repository's files, in the order they are committed. */ |
| 140 | 157 | export function officeFixtures(): readonly { readonly path: string; readonly content: Uint8Array }[] { |
| 141 | 158 | return [ |
| @@ -143,5 +160,6 @@ export function officeFixtures(): readonly { readonly path: string; readonly con | ||
| 143 | 160 | { path: "notes.docx", content: buildDocx() }, |
| 144 | 161 | { path: "deck.pptx", content: buildPptx() }, |
| 145 | 162 | { path: "sketch.ora", content: buildOra() }, |
| 163 | { path: "tune.mid", content: buildMid() }, | |
| 146 | 164 | ]; |
| 147 | 165 | } |
src/tui/screens/workspace.ts +2 −1
| @@ -95,6 +95,7 @@ import { sheetView } from "./workspace_sheet.ts"; | ||
| 95 | 95 | import { sqliteStep, sqliteView, type SqliteAt } from "./workspace_sqlite.ts"; |
| 96 | 96 | import { officeView } from "./workspace_office.ts"; |
| 97 | 97 | import { parquetView } from "./workspace_parquet.ts"; |
| 98 | import { midiView } from "./workspace_midi.ts"; | |
| 98 | 99 | import { layoutTable, type Grid } from "../ui/grid.ts"; |
| 99 | 100 | import type { Ctx, Screen } from "../app/app.ts"; |
| 100 | 101 | import { stripAnsi } from "../term/ansi.ts"; |
| @@ -1552,7 +1553,7 @@ export function workspaceScreen( | ||
| 1552 | 1553 | // bytes as text is how a terminal ends up beeping at you. |
| 1553 | 1554 | const base = looksLikeImage(t.path) ? null : sqliteView(t.path, read.value.body, { table: 0, page: 1 }); |
| 1554 | 1555 | if (base !== null && typeof base !== "string") db = 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)); | |
| 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)); | |
| 1556 | 1557 | if (looksLikeImage(t.path)) picture = read.value.body; |
| 1557 | 1558 | else if (book !== null && typeof book !== "string") sheet = book; |
| 1558 | 1559 | else if (typeof book === "string") note = book; |
src/tui/screens/workspace_midi.ts added +28
| @@ -0,0 +1,28 @@ | ||
| 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,6 +45,7 @@ export type FileKind = | ||
| 45 | 45 | | "calendar" |
| 46 | 46 | | "otio" |
| 47 | 47 | | "edl" |
| 48 | | "midi" | |
| 48 | 49 | | "fcpxml" |
| 49 | 50 | | "contacts" |
| 50 | 51 | | "mail" |
| @@ -130,6 +131,8 @@ export const RENDER_CAP: Readonly<Record<FileKind, number>> = { | ||
| 130 | 131 | // not drawn. |
| 131 | 132 | otio: 1 * MB, |
| 132 | 133 | edl: 1 * MB, |
| 134 | // A MIDI file is read whole and parsed once; 1 MB holds a long score. | |
| 135 | midi: 1 * MB, | |
| 133 | 136 | fcpxml: 1 * MB, |
| 134 | 137 | contacts: 1 * MB, |
| 135 | 138 | mail: 5 * MB, |
| @@ -242,6 +245,8 @@ const MEDIA: Readonly<Record<string, Media>> = { | ||
| 242 | 245 | sqlite: { kind: "sqlite", name: "SQLite", type: "application/vnd.sqlite3", magic: ascii("SQLite format 3\0") }, |
| 243 | 246 | sqlite3: { kind: "sqlite", name: "SQLite", type: "application/vnd.sqlite3", magic: ascii("SQLite format 3\0") }, |
| 244 | 247 | 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") }, | |
| 245 | 250 | stl: { kind: "model3d", name: "STL", type: "model/stl" }, |
| 246 | 251 | ttf: { kind: "font", name: "TrueType", type: "font/ttf", magic: bytes(0x00, 0x01, 0x00, 0x00) }, |
| 247 | 252 | otf: { kind: "font", name: "OpenType", type: "font/otf", magic: ascii("OTTO") }, |
src/web/render/midi-css.ts added +10
| @@ -0,0 +1,10 @@ | ||
| 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 added +283
| @@ -0,0 +1,283 @@ | ||
| 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" }; | |
outdated
|
||
| 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 | ||
outdated
Principle 5: --accent (interaction only) and --danger/--attn/--success carry track identity here. Use one tone family and a text key. |
||
| 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; | |
outdated
Principle 6: a stroked rect is a box around the roll; drop it. Also at 360px the 960-wide viewBox shrinks rows to ~2px: add a scrollable min-width. |
||
| 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,6 +33,7 @@ import { font } from "./font.ts"; | ||
| 33 | 33 | import { ics } from "./ics.ts"; |
| 34 | 34 | import { otio } from "./otio.ts"; |
| 35 | 35 | import { edl } from "./edl.ts"; |
| 36 | import { midi } from "./midi.ts"; | |
| 36 | 37 | import { fcpxml } from "./fcpxml.ts"; |
| 37 | 38 | import { junit } from "./junit.ts"; |
| 38 | 39 | import { feedXml } from "./feed-xml.ts"; |
| @@ -154,6 +155,7 @@ export const RENDERERS: Partial<Readonly<Record<FileKind, Renderer>>> = { | ||
| 154 | 155 | calendar: ics, |
| 155 | 156 | otio, |
| 156 | 157 | edl, |
| 158 | midi, | |
| 157 | 159 | fcpxml, |
| 158 | 160 | contacts: vcf, |
| 159 | 161 | sarif, |
src/web/style.ts +2
| @@ -28,6 +28,7 @@ import { homeFlowCss } from "./pages/home_flow_style.ts"; | ||
| 28 | 28 | import { base, layers, reset, utilities } from "./style/base.ts"; |
| 29 | 29 | import { components } from "./style/components.ts"; |
| 30 | 30 | import { content } from "./style/content.ts"; |
| 31 | import { midiCss } from "./render/midi-css.ts"; | |
| 31 | 32 | import { gcodeCss } from "./render/gcode-css.ts"; |
| 32 | 33 | import { model3dCss } from "./render/model3d-css.ts"; |
| 33 | 34 | import { pickCss } from "./pick.ts"; |
| @@ -46,6 +47,7 @@ export const css = [ | ||
| 46 | 47 | content, |
| 47 | 48 | model3dCss, |
| 48 | 49 | gcodeCss, |
| 50 | midiCss, | |
| 49 | 51 | utilities, |
| 50 | 52 | pickCss, |
| 51 | 53 | ].join("\n"); |
test/fuzz-renderers.test.ts +1
| @@ -331,6 +331,7 @@ export const EXCLUDED: Readonly<Record<string, string>> = { | ||
| 331 | 331 | layers: "a zip of images (ora); needs a fixture to splice into", |
| 332 | 332 | font: "binary font tables; needs a fixture to splice into", |
| 333 | 333 | 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", | |
| 334 | 335 | }; |
| 335 | 336 | |
| 336 | 337 | /** |
test/preview-office.test.ts +1 −1
| @@ -16,7 +16,7 @@ const text = (b: Uint8Array | null): string => new TextDecoder().decode(b ?? und | ||
| 16 | 16 | |
| 17 | 17 | test("every office page has a desk and a phone look", () => { |
| 18 | 18 | expect(PREVIEW_OFFICE_PAGES).toEqual( |
| 19 | ["notes.docx", "deck.pptx", "sketch.ora"].map((f) => `/${PREVIEW_ADMIN}/${PREVIEW_FIXTURES}/blob/main/${f}`), | |
| 19 | ["notes.docx", "deck.pptx", "sketch.ora", "tune.mid"].map((f) => `/${PREVIEW_ADMIN}/${PREVIEW_FIXTURES}/blob/main/${f}`), | |
| 20 | 20 | ); |
| 21 | 21 | for (const page of PREVIEW_OFFICE_PAGES) |
| 22 | 22 | for (const kind of ["desktop", "phone"] as const) |
test/render-kinds.test.ts +2
| @@ -46,6 +46,8 @@ const SAMPLES: Record<string, [Uint8Array, FileKind, string]> = { | ||
| 46 | 46 | db: [enc("SQLite format 3\0"), "sqlite", "application/vnd.sqlite3"], |
| 47 | 47 | sqlite: [enc("SQLite format 3\0"), "sqlite", "application/vnd.sqlite3"], |
| 48 | 48 | 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"], | |
| 49 | 51 | parquet: [enc("PAR1"), "parquet", "application/vnd.apache.parquet"], |
| 50 | 52 | csv: [enc("a,b\n1,2\n"), "csv", "application/octet-stream"], |
| 51 | 53 | tsv: [enc("a\tb\n"), "csv", "application/octet-stream"], |
test/render-midi.test.ts added +139
| @@ -0,0 +1,139 @@ | ||
| 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]) { | |
outdated
|
||
| 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<b>&"); | |
| 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,6 +970,25 @@ describe("the terminal workspace, by file type", () => { | ||
| 970 | 970 | h.stop(); |
| 971 | 971 | } |
| 972 | 972 | }); |
| 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 | }); | |
| 973 | 992 | test("a SQLite file opens as one table, its schema on top, paged by 100 with > < and } {", async () => { |
| 974 | 993 | const made = await createRepo(forge, alice, { name: "dbs", visibility: "public", description: "data" }); |
| 975 | 994 | if (!made.ok) throw new Error("repo failed"); |
A tempo of 0 is accepted; bpm(0) prints Infinity and the length divides oddly. Skip tempos of 0.