// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! Standard MIDI Files, written from and read into the machine's clock. //! //! A Passport MIDI card is a serial port that happens to speak MIDI: the //! machine clocks bytes out of the 6850 and other instruments clock bytes in. //! Neither front end here has a MIDI port to plug a synthesizer into, so what //! it does instead is the same trick `wav.zig` plays with sound — write down //! what went across the wire, and read a file back in as though it had. The //! file is a Standard MIDI File, which every sequencer and synthesizer reads. //! //! The recording is *timed*: a message is stamped with the machine cycle it //! went out on, so the file plays back at the speed the program sent it rather //! than as fast as it can be read. The mapping is fixed and tempo-free — one //! quarter note is one second (500,000... no, 1,000,000 microseconds) and the //! division is ten thousand ticks to the quarter, so a tick is a hundred //! microseconds and a cycle count turns straight into ticks. A reader is not //! so lucky: it must honor whatever division and tempo the file it is given //! carries, tempo changes included, which is what `read` does. //! //! The writer parses the MIDI byte stream as it arrives — running status, //! system-exclusive dumps, and the single-byte real-time messages that can //! appear in the middle of anything — because a Standard MIDI File is a list of //! whole messages with times, not the raw stream. (Standard MIDI Files 1.0, //! International MIDI Association, 1988.) const std = @import("std"); /// Ticks to the quarter note the writer uses. With the tempo below, one tick /// is a hundred microseconds, fine enough that no two MIDI bytes need share a /// tick. pub const division: u16 = 10_000; /// Microseconds to the quarter note the writer records: one full second, so /// that a tick is `tempo / division` = 100 µs and ticks a second is `division`. pub const tempo: u32 = 1_000_000; /// How many data bytes follow a status byte, or `null` for the ones that do /// not fit the pattern — system exclusive, which runs to its own terminator, /// and the real-time messages, which stand alone. fn dataBytes(status: u8) ?u8 { return switch (status & 0xf0) { 0x80, 0x90, 0xa0, 0xb0, 0xe0 => 2, // note off/on, aftertouch, control, pitch bend 0xc0, 0xd0 => 1, // program change, channel pressure 0xf0 => switch (status) { 0xf1, 0xf3 => 1, // MTC quarter frame, song select 0xf2 => 2, // song position pointer 0xf6 => 0, // tune request else => null, // F0 sysex, F7, and the real-time bytes F8..FF }, else => unreachable, }; } /// Writes a variable-length quantity, MIDI's big-endian base-128 with the top /// bit set on every byte but the last. Returns how many bytes it took. pub fn writeVarLen(out: *[4]u8, value: u32) usize { var buffer: [4]u8 = undefined; var v = value; var n: usize = 0; buffer[n] = @truncate(v & 0x7f); n += 1; v >>= 7; while (v != 0) : (v >>= 7) { buffer[n] = @as(u8, @truncate(v & 0x7f)) | 0x80; n += 1; } // Built low group first; the file wants high group first. for (0..n) |i| out[i] = buffer[n - 1 - i]; return n; } /// Reads a variable-length quantity, returning the value and how many bytes it /// spanned, or an error if it runs off the end or past four bytes. pub fn readVarLen(bytes: []const u8) !struct { value: u32, len: usize } { var value: u32 = 0; var i: usize = 0; while (i < bytes.len and i < 4) { const b = bytes[i]; value = (value << 7) | (b & 0x7f); i += 1; if (b & 0x80 == 0) return .{ .value = value, .len = i }; } return error.BadVarLen; } /// The fourteen-byte header of a format-0 single-track file. fn fileHeader(div: u16) [14]u8 { var out: [14]u8 = undefined; @memcpy(out[0..4], "MThd"); std.mem.writeInt(u32, out[4..8], 6, .big); // the header is six bytes long std.mem.writeInt(u16, out[8..10], 0, .big); // format 0: one track std.mem.writeInt(u16, out[10..12], 1, .big); // one track std.mem.writeInt(u16, out[12..14], div, .big); // ticks a quarter note return out; } /// Where the track's length field sits, and where its data begins, so `finish` /// can put the length right the way `wav.zig` fixes its sizes at the end. const track_length_at = 14 + 4; const track_data_at = 14 + 8; /// A Standard MIDI File being written as the machine runs. /// /// Always used through a pointer: it owns a buffered file writer, which holds a /// pointer into itself and breaks if it is moved. It parses the MIDI byte /// stream on the way through, so what the machine sends is fed in with /// `feed(bytes, cycle)` exactly as it came off the 6850. pub const Writer = struct { file: std.Io.File, writer: std.Io.File.Writer, buffer: []u8, /// How fast the machine runs, for turning a cycle into a tick. cycles_per_second: u64, /// The tick of the last event written, so the next one's delta is a /// subtraction. last_tick: u64 = 0, // The running MIDI stream parser's state, carried across `feed` calls. status: u8 = 0, // the current status byte, 0 before any running: bool = false, // whether `status` may be reused for a bare data byte want: u8 = 0, // data bytes still expected for the message being gathered data: [2]u8 = undefined, have: u8 = 0, msg_cycle: u64 = 0, // the cycle the message being gathered began on in_sysex: bool = false, sysex: std.ArrayList(u8) = .empty, sysex_cycle: u64 = 0, alloc: std.mem.Allocator, pub fn create( io: std.Io, alloc: std.mem.Allocator, path: []const u8, cycles_per_second: u64, ) !*Writer { const file = try std.Io.Dir.cwd().createFile(io, path, .{}); errdefer file.close(io); const self = try alloc.create(Writer); errdefer alloc.destroy(self); const buffer = try alloc.alloc(u8, 16 * 1024); errdefer alloc.free(buffer); self.* = .{ .file = file, .writer = file.writer(io, buffer), .buffer = buffer, .cycles_per_second = cycles_per_second, .alloc = alloc, }; try self.writer.interface.writeAll(&fileHeader(division)); try self.writer.interface.writeAll("MTrk"); try self.writer.interface.writeInt(u32, 0, .big); // patched by finish // A tempo meta at the head fixes what a tick is worth. try self.event(0, &.{ 0xff, 0x51, 0x03, @truncate(tempo >> 16), @truncate(tempo >> 8), @truncate(tempo) }); return self; } fn tickOf(self: *Writer, cycle: u64) u64 { return cycle * division / @max(1, self.cycles_per_second); } /// Writes one track event: a delta-time from the last event, then its /// bytes verbatim. fn event(self: *Writer, tick: u64, bytes: []const u8) !void { var vlq: [4]u8 = undefined; const delta: u32 = @intCast(tick -| self.last_tick); const n = writeVarLen(&vlq, delta); try self.writer.interface.writeAll(vlq[0..n]); try self.writer.interface.writeAll(bytes); self.last_tick = tick; } /// Emits the channel or system-common message gathered in `status`/`data`. fn emitMessage(self: *Writer) !void { var msg: [3]u8 = undefined; msg[0] = self.status; for (0..self.have) |i| msg[i + 1] = self.data[i]; try self.event(self.tickOf(self.msg_cycle), msg[0 .. 1 + self.have]); self.have = 0; } /// Emits the gathered system-exclusive dump as an SMF sysex event: the /// `F0`, then the length as a variable-length quantity, then the bytes /// after the `F0` (including the closing `F7`). fn emitSysex(self: *Writer) !void { const body = self.sysex.items[1..]; // everything past the leading F0 var vlq: [4]u8 = undefined; const delta: u32 = @intCast(self.tickOf(self.sysex_cycle) -| self.last_tick); const dn = writeVarLen(&vlq, delta); try self.writer.interface.writeAll(vlq[0..dn]); try self.writer.interface.writeByte(0xf0); const ln = writeVarLen(&vlq, @intCast(body.len)); try self.writer.interface.writeAll(vlq[0..ln]); try self.writer.interface.writeAll(body); self.last_tick = self.tickOf(self.sysex_cycle); self.sysex.clearRetainingCapacity(); self.in_sysex = false; } /// Hands the writer the bytes the machine sent, with the cycle they went /// out on. Bytes of one message share a cycle; that is fine. pub fn feed(self: *Writer, bytes: []const u8, cycle: u64) !void { for (bytes) |byte| try self.feedByte(byte, cycle); } fn feedByte(self: *Writer, byte: u8, cycle: u64) !void { // Real-time messages stand alone and may interrupt anything, running // status and sysex included, without disturbing it. if (byte >= 0xf8) { try self.event(self.tickOf(cycle), &.{byte}); return; } if (self.in_sysex) { try self.sysex.append(self.alloc, byte); if (byte == 0xf7) try self.emitSysex(); return; } if (byte >= 0x80) { if (byte == 0xf0) { self.sysex.clearRetainingCapacity(); try self.sysex.append(self.alloc, byte); self.in_sysex = true; self.sysex_cycle = cycle; self.running = false; return; } // A fresh status byte. System-common resets running status; a // channel status arms it. self.status = byte; self.msg_cycle = cycle; self.have = 0; const wants = dataBytes(byte) orelse 0; self.want = wants; self.running = byte < 0xf0; if (wants == 0) try self.emitMessage(); return; } // A data byte. With running status it belongs to `status`; the message // begins at the first such byte. if (self.status == 0) return; // stray data with no status: dropped if (self.have == 0) self.msg_cycle = cycle; if (self.have < 2) { self.data[self.have] = byte; self.have += 1; } if (self.have >= self.want) { try self.emitMessage(); if (!self.running) self.status = 0; } } /// Ends the track, puts its length right, and closes the file. Like the WAV /// writer, nothing here is worth failing over: a recording that cannot be /// tidied is still a recording. pub fn finish(self: *Writer, io: std.Io, alloc: std.mem.Allocator) void { // If a sysex was left open, close the file's copy so it is at least // well-formed. if (self.in_sysex) { self.sysex.append(self.alloc, 0xf7) catch {}; self.emitSysex() catch {}; } self.event(self.last_tick, &.{ 0xff, 0x2f, 0x00 }) catch {}; // end of track self.writer.interface.flush() catch {}; const end = self.writer.pos; const track_len: u32 = @intCast(end - track_data_at); self.writer.pos = track_length_at; self.writer.interface.writeInt(u32, track_len, .big) catch {}; self.writer.interface.flush() catch {}; self.file.close(io); self.sysex.deinit(self.alloc); alloc.free(self.buffer); alloc.destroy(self); } }; /// One MIDI byte to hand to the machine, and the earliest cycle it may go in. /// The cycles are absolute and already spaced no closer than the wire allows, /// so a pump need only wait for the cycle and for the chip to have room. pub const Delivery = struct { bytes: []u8, at: []u64, pub fn deinit(self: Delivery, alloc: std.mem.Allocator) void { alloc.free(self.bytes); alloc.free(self.at); } }; /// Reads a Standard MIDI File into a timed byte stream for the machine to /// receive. Honors the file's own division and every tempo change in it, and /// spaces the bytes of a message no closer than `byte_cycles` so the receiver /// is not fed faster than a MIDI wire runs. /// /// Formats 0 and 1 are read; a format-1 file's tracks are merged by absolute /// time. SMPTE division is not supported and is an error, since no MIDI file a /// sequencer writes for playback uses it. pub fn read( alloc: std.mem.Allocator, file: []const u8, cycles_per_second: u64, byte_cycles: u64, ) !Delivery { if (file.len < 14 or !std.mem.eql(u8, file[0..4], "MThd")) return error.NotMidi; const header_len = std.mem.readInt(u32, file[4..8], .big); if (header_len < 6) return error.BadHeader; const ntrks = std.mem.readInt(u16, file[10..12], .big); const div = std.mem.readInt(u16, file[12..14], .big); if (div & 0x8000 != 0 or div == 0) return error.UnsupportedDivision; // An event at an absolute tick, with the bytes to deliver. const TickEvent = struct { tick: u64, bytes: []u8 }; var events: std.ArrayList(TickEvent) = .empty; defer { for (events.items) |e| alloc.free(e.bytes); events.deinit(alloc); } var pos: usize = 8 + header_len; var track: u16 = 0; while (track < ntrks and pos + 8 <= file.len) : (track += 1) { if (!std.mem.eql(u8, file[pos .. pos + 4], "MTrk")) break; const len = std.mem.readInt(u32, file[pos + 4 ..][0..4], .big); const body_start = pos + 8; const body_end = @min(file.len, body_start + len); pos = body_end; try readTrack(alloc, file[body_start..body_end], TickEvent, &events); } // Stable-sort by tick so a format-1 file's tracks interleave correctly and // events already in order keep it. std.mem.sort(TickEvent, events.items, {}, struct { fn less(_: void, a: TickEvent, b: TickEvent) bool { return a.tick < b.tick; } }.less); // Walk the events applying the tempo map, turning ticks into microseconds // and then into cycles. var bytes: std.ArrayList(u8) = .empty; errdefer bytes.deinit(alloc); var at: std.ArrayList(u64) = .empty; errdefer at.deinit(alloc); var current_tempo: u64 = 500_000; // the MIDI default until a meta says otherwise var last_tick: u64 = 0; var micros: f64 = 0; var last_cycle: u64 = 0; for (events.items) |e| { micros += @as(f64, @floatFromInt(e.tick - last_tick)) * @as(f64, @floatFromInt(current_tempo)) / @as(f64, @floatFromInt(div)); last_tick = e.tick; // A tempo meta: FF 51 03 tt tt tt — change the map, deliver nothing. if (e.bytes.len == 6 and e.bytes[0] == 0xff and e.bytes[1] == 0x51) { current_tempo = (@as(u64, e.bytes[3]) << 16) | (@as(u64, e.bytes[4]) << 8) | e.bytes[5]; continue; } if (e.bytes.len == 0 or e.bytes[0] == 0xff) continue; // other metas are not sent const cycle: u64 = @intFromFloat(micros * @as(f64, @floatFromInt(cycles_per_second)) / 1_000_000.0); for (e.bytes) |b| { const due = @max(cycle, last_cycle + byte_cycles); try bytes.append(alloc, b); try at.append(alloc, due); last_cycle = due; } } return .{ .bytes = try bytes.toOwnedSlice(alloc), .at = try at.toOwnedSlice(alloc), }; } /// Parses one MTrk chunk's events into `events`, expanding running status and /// keeping system-exclusive and the tempo meta, dropping the rest. fn readTrack( alloc: std.mem.Allocator, body: []const u8, comptime TickEvent: type, events: *std.ArrayList(TickEvent), ) !void { var i: usize = 0; var tick: u64 = 0; var status: u8 = 0; while (i < body.len) { const delta = try readVarLen(body[i..]); i += delta.len; tick += delta.value; if (i >= body.len) break; var byte = body[i]; if (byte == 0xff) { // Meta event: FF type len data. i += 1; if (i >= body.len) break; const mtype = body[i]; i += 1; const mlen = try readVarLen(body[i..]); i += mlen.len; const end = @min(body.len, i + mlen.value); if (mtype == 0x51) { const bytes = try alloc.alloc(u8, 3 + (end - i)); bytes[0] = 0xff; bytes[1] = 0x51; bytes[2] = @intCast(end - i); @memcpy(bytes[3..], body[i..end]); try events.append(alloc, .{ .tick = tick, .bytes = bytes }); } i = end; continue; } if (byte == 0xf0 or byte == 0xf7) { // SysEx (F0) or an escape (F7): a length then that many bytes. const kind = byte; i += 1; const slen = try readVarLen(body[i..]); i += slen.len; const end = @min(body.len, i + slen.value); var bytes: std.ArrayList(u8) = .empty; errdefer bytes.deinit(alloc); if (kind == 0xf0) try bytes.append(alloc, 0xf0); try bytes.appendSlice(alloc, body[i..end]); try events.append(alloc, .{ .tick = tick, .bytes = try bytes.toOwnedSlice(alloc) }); i = end; status = 0; continue; } // A channel or system-common event, with running status. if (byte < 0x80) { byte = status; // running status: reuse the last, and this is a data byte } else { status = byte; i += 1; } if (status == 0) return error.BadRunningStatus; const want = dataBytes(status) orelse 0; const take = @min(want, body.len - i); const msg = try alloc.alloc(u8, 1 + take); msg[0] = status; @memcpy(msg[1..], body[i .. i + take]); i += take; try events.append(alloc, .{ .tick = tick, .bytes = msg }); if (status >= 0xf0) status = 0; // system-common does not run on } } const testing = std.testing; /// A path in the temporary directory, for the tests that write a real file: /// `Writer` makes its file through `cwd`, so a test hands it an absolute path /// and deletes it after. fn scratchPath(alloc: std.mem.Allocator, name: []const u8) ![]u8 { const dir = testing.environ.getPosix("TMPDIR") orelse "/tmp"; return std.fmt.allocPrint(alloc, "{s}/zig65-{s}", .{ dir, name }); } test "a variable-length quantity round-trips at the boundaries" { const cases = [_]u32{ 0, 0x7f, 0x80, 0x2000, 0x3fff, 0x4000, 0x0fffffff }; for (cases) |value| { var out: [4]u8 = undefined; const n = writeVarLen(&out, value); const back = try readVarLen(out[0..n]); try testing.expectEqual(value, back.value); try testing.expectEqual(n, back.len); } // The canonical encodings from the specification. var out: [4]u8 = undefined; try testing.expectEqual(@as(usize, 1), writeVarLen(&out, 0x40)); try testing.expectEqualSlices(u8, &.{0x40}, out[0..1]); try testing.expectEqual(@as(usize, 2), writeVarLen(&out, 0x80)); try testing.expectEqualSlices(u8, &.{ 0x81, 0x00 }, out[0..2]); try testing.expectEqual(@as(usize, 3), writeVarLen(&out, 0x100000)); try testing.expectEqualSlices(u8, &.{ 0xc0, 0x80, 0x00 }, out[0..3]); } test "the writer groups a note on and its running-status echo, and reads back" { const io = std.testing.io; const alloc = testing.allocator; const file_path = try scratchPath(alloc, "smf-out.mid"); defer { std.Io.Dir.cwd().deleteFile(io, file_path) catch {}; alloc.free(file_path); } const cps: u64 = 1_000_000; var w = try Writer.create(io, alloc, file_path, cps); // Note on 60, then 62 in running status a tenth of a second later, then a // note off using a real status byte. try w.feed(&.{ 0x90, 0x3c, 0x40 }, 0); try w.feed(&.{ 0x3e, 0x40 }, 100_000); // running status, +0.1 s try w.feed(&.{ 0x80, 0x3c, 0x00 }, 200_000); w.finish(io, alloc); const back = try std.Io.Dir.cwd().readFileAlloc(io, file_path, alloc, .unlimited); defer alloc.free(back); try testing.expectEqualSlices(u8, "MThd", back[0..4]); const delivery = try read(alloc, back, cps, 300); defer delivery.deinit(alloc); // Three messages, seven bytes; the tempo meta and end-of-track deliver // nothing. try testing.expectEqualSlices(u8, &.{ 0x90, 0x3c, 0x40, 0x90, 0x3e, 0x40, 0x80, 0x3c, 0x00 }, delivery.bytes); // The second message lands about a tenth of a second in. const second = delivery.at[3]; try testing.expect(second > 90_000 and second < 110_000); } test "a system-exclusive dump survives the round trip" { const io = std.testing.io; const alloc = testing.allocator; const file_path = try scratchPath(alloc, "smf-sysex.mid"); defer { std.Io.Dir.cwd().deleteFile(io, file_path) catch {}; alloc.free(file_path); } var w = try Writer.create(io, alloc, file_path, 1_000_000); try w.feed(&.{ 0xf0, 0x7e, 0x00, 0x06, 0x01, 0xf7 }, 0); // a MIDI identity request w.finish(io, alloc); const back = try std.Io.Dir.cwd().readFileAlloc(io, file_path, alloc, .unlimited); defer alloc.free(back); const delivery = try read(alloc, back, 1_000_000, 300); defer delivery.deinit(alloc); try testing.expectEqualSlices(u8, &.{ 0xf0, 0x7e, 0x00, 0x06, 0x01, 0xf7 }, delivery.bytes); } test "a tempo change moves later events in time" { const alloc = testing.allocator; // Build a one-track file by hand: division 480, a tempo of 1,000,000 µs at // tick 0 and a note at tick 480 (one quarter = one second at that tempo). var buf: std.ArrayList(u8) = .empty; defer buf.deinit(alloc); try buf.appendSlice(alloc, "MThd"); try buf.appendSlice(alloc, &.{ 0, 0, 0, 6, 0, 0, 0, 1, 0x01, 0xe0 }); // format 0, 1 track, div 480 try buf.appendSlice(alloc, "MTrk"); const track = [_]u8{ 0x00, 0xff, 0x51, 0x03, 0x0f, 0x42, 0x40, // tempo 1,000,000 µs/qn 0x83, 0x60, 0x90, 0x3c, 0x40, // delta 480, note on 0x00, 0xff, 0x2f, 0x00, // end of track }; var len: [4]u8 = undefined; std.mem.writeInt(u32, &len, track.len, .big); try buf.appendSlice(alloc, &len); try buf.appendSlice(alloc, &track); const delivery = try read(alloc, buf.items, 1_000_000, 300); defer delivery.deinit(alloc); try testing.expectEqualSlices(u8, &.{ 0x90, 0x3c, 0x40 }, delivery.bytes); // One quarter note at a microsecond a quarter... at 1,000,000 µs/qn that is // one second, so about 1,000,000 cycles at a megahertz. try testing.expect(delivery.at[0] > 950_000 and delivery.at[0] < 1_050_000); }