summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-16 23:35:54 -0300
committerGabriel Schneider <[email protected]>2026-11-17 12:15:01 -0300
commitc3b9938e9cb381bc7378fdca9073520ff1711ad6 (patch)
tree33f707ef2075bc26083a3c21d34a41b4a0e9c7ac /src
parentb2f7c605c279b2dea0c25180730c3d2e7b4b7d45 (diff)
downloadsketchbook-c3b9938e9cb381bc7378fdca9073520ff1711ad6.tar.gz
sketchbook-c3b9938e9cb381bc7378fdca9073520ff1711ad6.zip
Play past sessions back, re-synced at their keyframes
play session S [at SECONDS] restores the session's keyframe before that time (a binary search over its keyframes' times), replays its frames up to it and leaves it paused there; without a time it plays from the start. At each later keyframe the replay reaches, the State is compared with it over the leaves migration kept: a keyframe taken of what update made (periodic, mark, before a reload, exit) that differs is reported once, "diverged before frame F: N values, first <field>", and every keyframe is restored, so a replay across a jump the log does not hold (set, load, a sketch command) goes on from the State that followed it. A session built from another source or build says so. The console's status line names the session, frame and time, the mark, the clip and where it records. test-past records a session, replays it by the same build (the mark's State exactly, frame 120's two seconds in, no divergence), then by a build with an edited fixture (one divergence, before the mark). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'src')
-rw-r--r--src/host/Console.zig55
-rw-r--r--src/host/Host.zig32
-rw-r--r--src/host/Sessions.zig16
-rw-r--r--src/host/timeline.zig23
4 files changed, 122 insertions, 4 deletions
diff --git a/src/host/Console.zig b/src/host/Console.zig
index 88e4864..9f14830 100644
--- a/src/host/Console.zig
+++ b/src/host/Console.zig
@@ -14,7 +14,7 @@ pub const Key = enum { left, right, home, end, backspace, delete, clear, tab, su
const Line = struct { bytes: [118]u8 = @splat(0), len: usize = 0 };
const host_commands = [_][]const u8{
- "help", "overlay memory", "overlay sound", "get", "set", "reset", "save", "load", "snapshot", "recording", "marks", "clips",
+ "help", "overlay memory", "overlay sound", "get", "set", "reset", "save", "load", "snapshot", "recording", "marks", "clips", "play session",
"record", "stop", "play", "pause", "step", "seek start", "seek end", "diff", "quit", "exit",
"overlay timing", "sessions", "timing on", "timing off", "timing frame", "timing work", "timing reset", "timing stats",
};
@@ -238,6 +238,17 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const
h.startRecording();
self.recording = .of(n);
self.print("Started recording {s} from snapshot {s}.", .{ n, from });
+ } else if (eq(command, "play") and arg != null and eq(arg.?, "session")) {
+ var more = std.mem.tokenizeAny(u8, rest, " \t");
+ const index = std.fmt.parseInt(u64, more.next() orelse return error.ExpectedSession, 10) catch return error.InvalidSession;
+ var at: ?u64 = null;
+ if (more.next()) |word| {
+ if (!eq(word, "at")) return error.UnexpectedArgument;
+ const seconds = std.fmt.parseFloat(f64, more.next() orelse return error.ExpectedPosition) catch return error.InvalidPosition;
+ at = @intFromFloat(@max(0, seconds) * std.time.ns_per_s);
+ }
+ try stop(host);
+ return self.playSession(host, index, at, now);
} else if (eq(command, "play")) {
const n = try nameOr(arg, &self.recording);
try stop(host);
@@ -301,8 +312,12 @@ pub fn draw(self: *const Console, host: *Host, out: *std.ArrayList(abi.Command),
const width: f32 = @floatFromInt(host.canvas[0]);
const h = &host.timeline;
try out.append(arena, .{ .rect = .{ .dst = .{ .x = 0, .y = top, .w = width, .h = panel_height }, .color = .{ .r = 24, .g = 28, .b = 28 } } });
- const status = try std.fmt.allocPrint(arena, "{s} | {t} | snapshot {s} | recording {s} | event {d} | {d}ms | rec {t}", .{
- host.name, h.mode, self.snapshot.get(), self.recording.get(), h.cursor, h.position / std.time.ns_per_ms, host.sessions.mode(),
+ const s = &host.sessions;
+ const playing = h.mode == .playing or h.mode == .paused;
+ const frame = if (playing) (if (h.key) |k| k.frame else 0) + h.fed else s.frames;
+ const at = (if (playing) h.position else s.last_time -| s.first_time) / std.time.ns_per_s;
+ const status = try std.fmt.allocPrint(arena, "{s} | {t} | session {d} frame {d} ({d}:{d:0>2}) | mark {s} | clip {s} | rec {t}", .{
+ host.name, h.mode, if (playing) h.session orelse s.session else s.session, frame, at / 60, at % 60, self.snapshot.get(), self.recording.get(), s.mode(),
});
try out.append(arena, .{ .text = .{ .x = 12, .y = top + 8, .scale = 1, .color = hint, .bytes = status } });
for (&self.lines, 0..) |*line, i| {
@@ -378,6 +393,40 @@ fn loadClip(host: *Host, n: []const u8) !void {
host.timeline.load(key, events);
}
+/// Plays session `index` from its start, or paused `at` nanoseconds into
+/// it: from the newest keyframe before then, replayed up to it.
+fn playSession(self: *Console, host: *Host, index: u64, at: ?u64, now: u64) ![]const abi.Event {
+ const s = &host.sessions;
+ const h = &host.timeline;
+ if (index == s.session) try s.commit(.none);
+ const sum = try s.summary(index);
+ if (sum.keys == 0) return error.EmptyRecording;
+ const t0 = (try s.keyAt(index, 0)).time;
+ const k = if (at) |t| try s.keyBefore(index, .time, t0 + t) orelse 0 else 0;
+ const key = try s.load(index, k);
+ errdefer key.free(host.gpa);
+ var events: std.ArrayList(abi.Event) = .empty;
+ errdefer events.deinit(host.gpa);
+ try s.events(index, key.batch, key.frame, sum.frames, &events);
+ var checks: @TypeOf(h.checks) = .empty;
+ errdefer checks.deinit(host.gpa);
+ for (k + 1..sum.keys) |j| {
+ const later = try s.keyAt(index, j);
+ try checks.append(host.gpa, .{ .frame = later.frame, .key = j, .observed = switch (later.why) {
+ .periodic, .mark, .before_reload, .exit => true,
+ else => false,
+ } });
+ }
+ h.load(key, events);
+ h.session = index;
+ h.checks = checks;
+ try h.play(now);
+ self.print("Playing session {d} from frame {d}.", .{ index, key.frame });
+ if (key.build != host.build or !eq(key.source, host.source)) self.print("session {d} frame {d} was built from {s}; replaying with {s}", .{ index, key.frame, key.source, host.source });
+ if (at) |t| return h.seekTime((t0 + t) -| h.base);
+ return &.{};
+}
+
/// A replay of a clip made by other code may diverge: say so.
fn warnBuild(self: *Console, host: *const Host) void {
const key = host.timeline.key orelse return;
diff --git a/src/host/Host.zig b/src/host/Host.zig
index 1fe1db2..1c9d65a 100644
--- a/src/host/Host.zig
+++ b/src/host/Host.zig
@@ -373,10 +373,42 @@ pub fn update(self: *Host, events: []const abi.Event) void {
self.started = false;
const ctx = self.context();
self.sketch.update(&ctx, self.live().ptr);
+ if (self.timeline.mode == .playing or self.timeline.mode == .paused) self.resync();
}
self.input.events = &.{};
}
+/// After a replayed frame of a past session: at each keyframe it reaches,
+/// live state is compared with the keyframe (over the leaves migration
+/// kept), any difference said, and the keyframe restored.
+fn resync(self: *Host) void {
+ const h = &self.timeline;
+ h.fed += 1;
+ const session = h.session orelse return;
+ const reached = h.key.?.frame + h.fed;
+ while (h.next_check < h.checks.items.len and h.checks.items[h.next_check].frame <= reached) {
+ const check = h.checks.items[h.next_check];
+ h.next_check += 1;
+ if (check.frame < reached) continue;
+ const key = self.sessions.load(session, check.key) catch |err| return self.print("session {d} keyframe {d}: {t}", .{ session, check.key, err });
+ defer key.free(self.gpa);
+ var arena: std.heap.ArenaAllocator = .init(self.gpa);
+ defer arena.deinit();
+ const saved = arena.allocator().alignedAlloc(u8, .fromByteUnits(memory.page), self.state.layout.size) catch return;
+ const from = memory.restore(arena.allocator(), key.layout, key.state, self.state.layout, saved, self.sketch.defaults) catch |err| return self.print("session {d} keyframe {d}: {t}", .{ session, check.key, err });
+ if (check.observed) {
+ const diff = memory.compareKept(from, self.state.layout, self.live(), saved);
+ if (diff.first) |first| {
+ var buf: [96]u8 = undefined;
+ var w: std.Io.Writer = .fixed(&buf);
+ first.leaf.name(first.offset, &w) catch {};
+ self.print("diverged before frame {d}: {d} values, first {s}", .{ reached, diff.count, w.buffered() });
+ }
+ }
+ @memcpy(self.live(), saved);
+ }
+}
+
/// After live state was restored from a snapshot: the pointer, buttons and
/// keys tracked so far belong to other bytes, so they start over. A new
/// recording then begins with events that bring back what is held now, so
diff --git a/src/host/Sessions.zig b/src/host/Sessions.zig
index 6f10bba..4399c63 100644
--- a/src/host/Sessions.zig
+++ b/src/host/Sessions.zig
@@ -81,7 +81,8 @@ keys: u64 = 0,
batch: std.ArrayList(u8) = .empty,
/// The first pending frame's tick.
batch_time: u64 = 0,
-/// The latest event time logged: times never go back.
+/// The first and latest event time logged: times never go back.
+first_time: u64 = 0,
last_time: u64 = 0,
/// The last keyframe's time, stretch and bytes' hash.
key_time: u64 = 0,
@@ -191,6 +192,7 @@ pub fn frame(s: *Sessions, one: []abi.Event, state: []const u8, why: ?Why) !void
if (why) |w| {
_ = try s.keyframe(w, state);
} else if (tick -| s.key_time >= periodic_ns) _ = try s.keyframe(.periodic, state);
+ if (s.frames == 0) s.first_time = tick;
if (s.batch.items.len == 0) {
try s.batch.appendSlice(s.gpa, std.mem.asBytes(&std.mem.nativeToLittle(u64, s.frames)));
s.batch_time = tick;
@@ -487,6 +489,18 @@ pub fn load(s: *Sessions, session: u64, k: u64) !Loaded {
}
}
+/// Keyframe `k`'s frame, time and why, without its bytes.
+pub fn keyAt(s: *Sessions, session: u64, k: u64) !struct { frame: u64, time: u64, why: Why } {
+ switch (s.db) {
+ .off => return error.NotRecording,
+ inline .memory, .file => |*db| {
+ const R = Read(@TypeOf(db.*));
+ const e = try R.at(try R.list(try R.session(db, session), .keys) orelse return error.NoSuchKeyframe, k);
+ return .{ .frame = try R.uint(e, .frame), .time = try R.uint(e, .time), .why = std.enums.fromInt(Why, try R.uint(e, .why)) orelse return error.CorruptSession };
+ },
+ }
+}
+
/// The newest keyframe of `session` whose `by` (`.frame` or `.time`) is at
/// most `value`: a binary search.
pub fn keyBefore(s: *Sessions, session: u64, by: K, value: u64) !?u64 {
diff --git a/src/host/timeline.zig b/src/host/timeline.zig
index 697a9df..c2eeff3 100644
--- a/src/host/timeline.zig
+++ b/src/host/timeline.zig
@@ -61,10 +61,29 @@ pub const Timeline = struct {
/// 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.
@@ -73,6 +92,8 @@ pub const Timeline = struct {
defer arena.deinit();
_ = try memory.restore(arena.allocator(), key.layout, key.state, self.state.layout, self.state.slot(0), 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
@@ -81,6 +102,8 @@ pub const Timeline = struct {
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;