// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! Sound written to a file, because a terminal has no speaker. //! //! Neither front end here can make a noise: one draws an Apple II in a //! terminal window and the other an Apple IIgs, and a terminal window is not //! an audio device. What they can do is write down what the machine's sound //! hardware did, in a format anything will play — so `--audio` is how you hear //! a IIe's speaker or a IIgs's Ensoniq, a moment later and out of a player //! rather than out of the emulator. //! //! The format is the simplest WAV there is: uncompressed sixteen-bit PCM, one //! or two channels, and a forty-four byte header. The one wrinkle is that the //! header carries two sizes covering the whole file, and neither is known //! until the recording is finished — so they go in as zero, and are written //! again over the top when the file is closed. A recording cut short by a //! crash therefore has a header saying nothing was recorded, which most //! players will still play to the end of the data; `finish` is what makes it //! tidy. const std = @import("std"); /// How long the header is. Every field of it is a fixed size, so this is not /// going to change, but naming it keeps the seek at the end readable. pub const header_bytes = 44; /// A WAV file being written to as the machine runs. /// /// Always used through a pointer. It owns a buffered file writer, and a /// buffered writer holds a pointer into itself, so one that gets copied to a /// new address stops working — which is a bug that shows up as a truncated /// file long after the copy. pub const Writer = struct { file: std.Io.File, writer: std.Io.File.Writer, /// The writer's own buffer, held here so that it lives exactly as long as /// the writer does. buffer: []u8, rate: u32, channels: u16, /// How many samples have gone in, which is the number the header needs. /// Saturating, because a recording long enough to overflow it is one whose /// header cannot describe it anyway and the samples are still worth /// having. written: u32 = 0, /// The header, with whatever sizes are known at the time. fn header(rate: u32, channels: u16, samples: u32) [header_bytes]u8 { const data_bytes: u32 = samples * 2; var out: [header_bytes]u8 = undefined; @memcpy(out[0..4], "RIFF"); std.mem.writeInt(u32, out[4..8], 36 + data_bytes, .little); @memcpy(out[8..12], "WAVE"); @memcpy(out[12..16], "fmt "); std.mem.writeInt(u32, out[16..20], 16, .little); // the size of what follows std.mem.writeInt(u16, out[20..22], 1, .little); // uncompressed std.mem.writeInt(u16, out[22..24], channels, .little); std.mem.writeInt(u32, out[24..28], rate, .little); std.mem.writeInt(u32, out[28..32], rate * 2 * channels, .little); // bytes a second std.mem.writeInt(u16, out[32..34], 2 * channels, .little); // bytes a frame std.mem.writeInt(u16, out[34..36], 16, .little); // bits a sample @memcpy(out[36..40], "data"); std.mem.writeInt(u32, out[40..44], data_bytes, .little); return out; } /// Makes the file and writes a header that will need putting right. pub fn create( io: std.Io, alloc: std.mem.Allocator, path: []const u8, rate: u32, channels: u16, ) !*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, 64 * 1024); errdefer alloc.free(buffer); self.* = .{ .file = file, .writer = file.writer(io, buffer), .buffer = buffer, .rate = rate, .channels = channels, }; try self.writer.interface.writeAll(&header(rate, channels, 0)); return self; } /// One sample of one channel. A stereo recording is one of these for the /// left and then one for the right, which is the order a WAV frame is in. pub fn put(self: *Writer, sample: i16) !void { try self.writer.interface.writeInt(i16, sample, .little); self.written +|= 1; } /// The same, for hardware whose model works in floats. Anything outside /// the range is clipped rather than wrapped: sound that is too loud should /// distort, not turn inside out. pub fn putFloat(self: *Writer, sample: f32) !void { const clamped = std.math.clamp(sample, -1.0, 1.0); try self.put(@intFromFloat(clamped * 32767.0)); } /// Puts the sizes in the header right and closes the file. /// /// Nothing here can fail in a way worth telling anyone about: this is /// called while the emulator is shutting down, often because something /// else went wrong, and a recording that cannot be tidied is still a /// recording. pub fn finish(self: *Writer, io: std.Io, alloc: std.mem.Allocator) void { self.writer.interface.flush() catch {}; self.writer.pos = 0; self.writer.interface.writeAll(&header(self.rate, self.channels, self.written)) catch {}; self.writer.interface.flush() catch {}; self.file.close(io); alloc.free(self.buffer); alloc.destroy(self); } }; const testing = std.testing; test "the header says what a player needs to know" { const out = Writer.header(44_100, 1, 100); try testing.expectEqualSlices(u8, "RIFF", out[0..4]); try testing.expectEqualSlices(u8, "WAVE", out[8..12]); try testing.expectEqualSlices(u8, "fmt ", out[12..16]); try testing.expectEqualSlices(u8, "data", out[36..40]); // A hundred samples of one channel at two bytes each. try testing.expectEqual(@as(u32, 200), std.mem.readInt(u32, out[40..44], .little)); // And the size at the front covers everything after the first eight bytes. try testing.expectEqual(@as(u32, 236), std.mem.readInt(u32, out[4..8], .little)); try testing.expectEqual(@as(u16, 1), std.mem.readInt(u16, out[20..22], .little)); try testing.expectEqual(@as(u16, 1), std.mem.readInt(u16, out[22..24], .little)); try testing.expectEqual(@as(u32, 44_100), std.mem.readInt(u32, out[24..28], .little)); try testing.expectEqual(@as(u32, 88_200), std.mem.readInt(u32, out[28..32], .little)); try testing.expectEqual(@as(u16, 2), std.mem.readInt(u16, out[32..34], .little)); try testing.expectEqual(@as(u16, 16), std.mem.readInt(u16, out[34..36], .little)); } test "two channels are twice the bytes, everywhere it matters" { const out = Writer.header(22_050, 2, 100); try testing.expectEqual(@as(u16, 2), std.mem.readInt(u16, out[22..24], .little)); // Bytes a second and bytes a frame both double; the sample count does not, // because a stereo recording counts each channel's sample separately and // the caller has already done that. try testing.expectEqual(@as(u32, 88_200), std.mem.readInt(u32, out[28..32], .little)); try testing.expectEqual(@as(u16, 4), std.mem.readInt(u16, out[32..34], .little)); try testing.expectEqual(@as(u32, 200), std.mem.readInt(u32, out[40..44], .little)); } test "an empty recording still has a header a player will accept" { const out = Writer.header(44_100, 1, 0); try testing.expectEqual(@as(u32, 0), std.mem.readInt(u32, out[40..44], .little)); try testing.expectEqual(@as(u32, 36), std.mem.readInt(u32, out[4..8], .little)); }