//! Snapshots, input recordings and replay: generic over state bytes and //! `abi.Event`s, so any sketch gets time travel for free. //! //! Playback is host state, not sketch state: wall clocks, modes and cursors //! must not contaminate byte comparisons between two runs of a sketch. const std = @import("std"); const posix = std.posix; const abi = @import("abi"); const memory = @import("memory.zig"); pub const recording_len = 4 * 1024 * 1024; pub const recording_count = 16; pub const recordings_len = recording_len * recording_count; const recording_magic = 0x52454305; pub const capacity = (recording_len - 32) / @sizeOf(abi.Event); pub const Recording = extern struct { duration: u64, count: u32, snapshot: u32, magic: u32, reserved: [3]u32, events: [capacity]abi.Event, slack: [recording_len - 32 - capacity * @sizeOf(abi.Event)]u8, pub fn slice(r: *const Recording) []const abi.Event { return r.events[0..r.count]; } }; comptime { std.debug.assert(@sizeOf(Recording) == recording_len); } /// Snapshot slots of a state file, and the recordings that start from them. pub const Bank = struct { state: *memory.StateFile, inputs: []align(memory.page) u8, pub fn slot(self: Bank, index: usize) []u8 { return self.state.slot(index); } pub fn recording(self: Bank, index: usize) *Recording { std.debug.assert(index < recording_count); return @ptrCast(@alignCast(self.inputs[index * recording_len ..].ptr)); } pub fn hasSnapshot(self: Bank, index: usize) bool { return index > 0 and index < memory.slot_count and self.state.used(index); } pub fn save(self: Bank, index: usize) void { std.debug.assert(index > 0 and index < memory.slot_count); for (0..recording_count) |i| { const r = self.recording(i); if (r.snapshot == index) r.magic = 0; } @memcpy(self.slot(index), self.slot(0)); self.state.markUsed(index, true); } pub fn restore(self: Bank, index: usize) !void { if (!self.hasSnapshot(index)) return error.EmptySnapshot; @memcpy(self.slot(0), self.slot(index)); } pub fn get(self: Bank, index: usize) !*Recording { const r = self.recording(index); if (r.magic != recording_magic or r.count > capacity or !self.hasSnapshot(r.snapshot)) return error.EmptyRecording; return r; } pub const Diff = struct { count: usize = 0, first: ?usize = null, last: ?usize = null }; pub fn compare(self: Bank, a: usize, b: usize) Diff { var diff: Diff = .{}; for (self.slot(a), self.slot(b), 0..) |x, y, i| { if (x == y) continue; diff.count += 1; if (diff.first == null) diff.first = i; diff.last = i; } return diff; } }; pub const Timeline = struct { bank: Bank, mode: abi.Mode = .live, selected: usize = 0, cursor: usize = 0, position: u64 = 0, clock: u64 = 0, pub fn startRecording(self: *Timeline, index: usize, snapshot: usize, now: u64) !void { // An unused snapshot captures the current state; an existing one is // restored, so several recordings can branch from exactly those bytes. if (!self.bank.hasSnapshot(snapshot)) self.bank.save(snapshot); try self.bank.restore(snapshot); const r = self.bank.recording(index); @memset(std.mem.asBytes(r)[0..32], 0); r.magic = recording_magic; r.snapshot = @intCast(snapshot); self.selected = index; self.cursor = 0; self.position = 0; self.clock = now; self.mode = .recording; } pub fn capture(self: *Timeline, event: abi.Event) !void { if (self.mode != .recording) return; const r = self.bank.recording(self.selected); if (r.count == capacity) { self.mode = .live; return error.RecordingFull; } var e = event; // Queued events can predate the start command. Keep insertion order and // nondecreasing times, including several events at the same timestamp. e.time = @max(e.time -| self.clock, r.duration); r.events[r.count] = e; r.count += 1; r.duration = e.time; self.position = e.time; self.cursor = r.count; } pub fn stop(self: *Timeline, now: u64) void { if (self.mode == .recording) { const r = self.bank.recording(self.selected); r.duration = @max(r.duration, now -| self.clock); self.position = r.duration; } self.mode = .live; } pub fn play(self: *Timeline, index: usize, now: u64) !void { const r = try self.bank.get(index); try self.bank.restore(r.snapshot); self.selected = index; self.cursor = 0; self.position = 0; self.clock = now; self.mode = .playing; } pub fn pause(self: *Timeline, now: u64) void { if (self.mode == .playing) { self.mode = .paused; } else if (self.mode == .paused) { self.clock = now; self.mode = .playing; } } /// The recorded events due by `now`. Feed them to the same `update` that /// live input goes through. pub fn tick(self: *Timeline, now: u64) []const abi.Event { if (self.mode != .playing) return &.{}; const r = self.bank.recording(self.selected); self.position = @min(r.duration, self.position +| (now -| self.clock)); self.clock = now; const start = self.cursor; while (self.cursor < r.count and r.events[self.cursor].time <= self.position) self.cursor += 1; if (self.position == r.duration) self.mode = .paused; return r.events[start..self.cursor]; } /// Restores the snapshot and returns the first `count` events to replay, /// so seeking backwards works too. pub fn seekCount(self: *Timeline, count: usize) ![]const abi.Event { const r = try self.bank.get(self.selected); try self.bank.restore(r.snapshot); self.cursor = @min(count, r.count); self.position = if (self.cursor == 0) 0 else r.events[self.cursor - 1].time; self.mode = .paused; return r.events[0..self.cursor]; } pub fn seekTime(self: *Timeline, time: u64) ![]const abi.Event { const r = try self.bank.get(self.selected); const position = @min(time, r.duration); var count: usize = 0; while (count < r.count and r.events[count].time <= position) count += 1; const events = try self.seekCount(count); self.position = position; return events; } /// Moves by `steps` input events, passing over frame ticks. pub fn step(self: *Timeline, steps: i64) ![]const abi.Event { const r = try self.bank.get(self.selected); var cursor = self.cursor; var remaining = @abs(steps); while (remaining > 0) : (remaining -= 1) { if (steps > 0) { while (cursor < r.count and r.events[cursor].kind == .tick) cursor += 1; if (cursor == r.count) break; cursor += 1; // Include the frame's tick so time-driven sketches advance too. while (cursor < r.count and r.events[cursor].kind == .tick) cursor += 1; } else { while (cursor > 0 and r.events[cursor - 1].kind == .tick) cursor -= 1; if (cursor == 0) break; cursor -= 1; } } return self.seekCount(cursor); } }; /// Maps the recordings file next to a state file, creating it when missing. pub fn mapRecordings(path: []const u8) ![]align(memory.page) u8 { const fd = try posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600); defer _ = posix.system.close(fd); if (try memory.fileSize(fd) != recordings_len) switch (posix.errno(posix.system.ftruncate(fd, recordings_len))) { .SUCCESS => {}, else => |err| return posix.unexpectedErrno(err), }; return memory.mapFile(fd, recordings_len, .{ .READ = true, .WRITE = true }); }