//! Clips 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. //! //! A clip is whole frames of a session (Sessions.zig) and the keyframe they //! start from: each frame's events, then its `tick`. Playback, seek and step //! only ever stop between frames, and `frames` cuts a run of events into //! them, so `update` sees exactly the frames it saw live, one call each, //! at the times it saw. const std = @import("std"); const abi = @import("abi"); const memory = @import("memory.zig"); const Sessions = @import("Sessions.zig"); /// The largest frame boundary at or before `index`: 0, or just after a tick. pub fn frameStart(events: []const abi.Event, index: usize) usize { var i = @min(index, events.len); while (i > 0 and events[i - 1].kind != .tick) i -= 1; return i; } /// Cuts events into frames, each ending with its tick. Events after the /// last tick (a frame not finished) are never returned. pub fn frames(events: []const abi.Event) Frames { return .{ .events = events }; } pub const Frames = struct { events: []const abi.Event, start: usize = 0, pub fn next(f: *Frames) ?[]const abi.Event { var i = f.start; while (i < f.events.len) : (i += 1) { if (f.events[i].kind != .tick) continue; const frame = f.events[f.start .. i + 1]; f.start = i + 1; return frame; } return null; } }; pub const Timeline = struct { gpa: std.mem.Allocator, /// Live State. state: *memory.State, /// The running sketch's: a restore starts from its defaults. defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void, mode: abi.Mode = .live, /// The clip loaded: its start keyframe and its frames, `gpa`'s. key: ?Sessions.Loaded = null, events: std.ArrayList(abi.Event) = .empty, /// The clip's first tick: positions count from it. base: u64 = 0, cursor: usize = 0, position: u64 = 0, clock: u64 = 0, /// Set whenever live state is restored from a keyframe, for the host /// to reset the input state that went with the old bytes. restored: bool = false, /// Frames fed since the keyframe was restored. fed: u64 = 0, /// A past session played (`play session`), not a clip: its index, and /// its keyframes after the one played from, checked against the replay /// as their frames are reached (Host.resync). session: ?u64 = null, checks: std.ArrayList(Check) = .empty, next_check: usize = 0, pub const Check = struct { frame: u64, key: u64, /// Taken of what `update` made (periodic, a mark, before a reload, /// at exit): a replay must match it. Other keyframes follow a jump /// the log does not hold, and are restored without a word. observed: bool, }; pub fn deinit(self: *Timeline) void { if (self.key) |k| k.free(self.gpa); self.key = null; self.events.deinit(self.gpa); self.checks.deinit(self.gpa); } /// Puts a keyframe, in whatever layout it was taken, into live state. pub fn restore(self: *Timeline, key: Sessions.Loaded) !void { var arena: std.heap.ArenaAllocator = .init(self.gpa); defer arena.deinit(); _ = try memory.restore(arena.allocator(), key.layout, key.state, self.state.layout, self.state.live(), self.defaults); self.restored = true; self.fed = 0; self.next_check = 0; } /// Makes a clip, its start keyframe and its frames, the one played; both /// become the timeline's. pub fn load(self: *Timeline, key: Sessions.Loaded, events: std.ArrayList(abi.Event)) void { self.deinit(); self.key = key; self.events = events; self.session = null; self.checks = .empty; var it = frames(events.items); const first = it.next(); self.base = if (first) |f| f[f.len - 1].time else 0; } fn at(self: *const Timeline, i: usize) u64 { return self.events.items[i].time -| self.base; } /// The last whole frame's tick, from the first. fn duration(self: *const Timeline) u64 { const end = frameStart(self.events.items, self.events.items.len); return if (end == 0) 0 else self.at(end - 1); } pub fn startRecording(self: *Timeline) void { self.cursor = 0; self.position = 0; self.mode = .recording; } pub fn stop(self: *Timeline) void { self.mode = .live; } pub fn play(self: *Timeline, now: u64) !void { try self.restore(self.key orelse return error.EmptyRecording); 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 frames due by `now`: whole frames, whose ticks are due /// (a frame's input comes before its tick, so input alone is never /// due). 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 end = self.duration(); self.position = @min(end, self.position +| (now -| self.clock)); self.clock = now; const start = self.cursor; var i = self.cursor; while (i < self.events.items.len and self.at(i) <= self.position) : (i += 1) { if (self.events.items[i].kind == .tick) self.cursor = i + 1; } if (self.position == end) self.mode = .paused; return self.events.items[start..self.cursor]; } /// Restores the start keyframe and returns the frames that make up the /// first `count` events (rounded down to a whole frame) to replay, so /// seeking backwards works too. pub fn seekCount(self: *Timeline, count: usize) ![]const abi.Event { try self.restore(self.key orelse return error.EmptyRecording); self.cursor = frameStart(self.events.items, count); self.position = if (self.cursor == 0) 0 else self.at(self.cursor - 1); self.mode = .paused; return self.events.items[0..self.cursor]; } /// To the last frame whose tick is at or before `time` into the clip. pub fn seekTime(self: *Timeline, time: u64) ![]const abi.Event { const position = @min(time, self.duration()); var count: usize = 0; for (self.events.items, 0..) |e, i| { if (self.at(i) > position) break; if (e.kind == .tick) count = i + 1; } const events = try self.seekCount(count); self.position = position; return events; } /// Moves by `steps` frames, forwards or back. pub fn step(self: *Timeline, steps: i64) ![]const abi.Event { const events = self.events.items; var cursor = frameStart(events, self.cursor); var remaining = @abs(steps); const end = frameStart(events, events.len); while (remaining > 0) : (remaining -= 1) { if (steps > 0) { if (cursor == end) break; cursor += 1; while (cursor < end and events[cursor - 1].kind != .tick) cursor += 1; } else { if (cursor == 0) break; cursor = frameStart(events, cursor - 1); } } return self.seekCount(cursor); } }; test "frames are whole: input waits for its tick, in playback, seek and step" { const gpa = std.testing.allocator; // Live State: 8 bytes, no fields. const D = struct { fn f(_: abi.Memory, _: [*]u8) callconv(.c) void {} }; var state: memory.State = .init(gpa); defer state.deinit(gpa); _ = try state.adopt(gpa, .{ .size = 8, .alignment = 1, .hash = 1, .fields = &.{} }, D.f); var t: Timeline = .{ .gpa = gpa, .state = &state, .defaults = D.f }; defer t.deinit(); // Frame k: a move at 10k ms, its tick 5 ms later; then a move with no // tick (a frame cut off). var events: std.ArrayList(abi.Event) = .empty; for (0..4) |k| { try events.append(gpa, .{ .kind = .mouse_move, .time = 1000 + k * 10_000_000, .x = @floatFromInt(k) }); try events.append(gpa, abi.Event.tick(1000 + k * 10_000_000 + 5_000_000, 16_666_667)); } try events.append(gpa, .{ .kind = .mouse_move, .time = 40_000_000 }); const key: Sessions.Loaded = .{ .frame = 0, .batch = 0, .why = .mark, .time = 0, .stretch = 0, .build = 7, .state = try gpa.dupe(u8, &@as([8]u8, @splat(0))), .line = try gpa.dupe(u8, ""), .source = try gpa.dupe(u8, ""), .layout = try gpa.dupe(u8, state.header) }; t.load(key, events); try t.play(0); try std.testing.expect(t.restored); var delivered: usize = 0; // Every moment between 0 and the end, 1 ms apart. var now: u64 = 0; while (t.mode == .playing) : (now += 1_000_000) { const due = t.tick(now); if (due.len == 0) continue; try std.testing.expectEqual(abi.Event.Kind.tick, due[due.len - 1].kind); var it = frames(due); while (it.next()) |frame| { try std.testing.expectEqual(@as(usize, 2), frame.len); // Fed at the times it was recorded at. try std.testing.expectEqual(1000 + delivered * 10_000_000 + 5_000_000, frame[1].time); delivered += 1; } } try std.testing.expectEqual(@as(usize, 4), delivered); try std.testing.expectEqual(@as(usize, 8), t.cursor); // A seek between a frame's input and its tick stops before the frame. try std.testing.expectEqual(@as(usize, 6), (try t.seekTime(27_000_000)).len); try std.testing.expectEqual(@as(usize, 8), (try t.seekCount(t.events.items.len)).len); try std.testing.expectEqual(@as(usize, 6), (try t.step(-1)).len); try std.testing.expectEqual(@as(usize, 8), (try t.step(5)).len); try std.testing.expectEqual(@as(usize, 2), (try t.step(-3)).len); // The cut-off frame is never fed. var it = frames(t.events.items); var n: usize = 0; while (it.next()) |_| n += 1; try std.testing.expectEqual(@as(usize, 4), n); } test "a tick's dt reads back the same live and replayed" { // E4: nanoseconds do not survive f32 seconds; both sides read the f32. for ([_]u64{ 16_666_667, 16_666_666, 15_000_001, 33_333_333, 0, 1 }) |dt| { const live = abi.Event.tick(5, dt); var recorded = live; recorded.time = 0; try std.testing.expectEqual(live.tickDt(), recorded.tickDt()); try std.testing.expect(@abs(@as(i64, @intCast(live.tickDt())) - @as(i64, @intCast(dt))) < 8); } }