summaryrefslogtreecommitdiff
path: root/src/host/timeline.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-16 23:31:18 -0300
committerGabriel Schneider <[email protected]>2026-11-17 12:15:01 -0300
commitb2f7c605c279b2dea0c25180730c3d2e7b4b7d45 (patch)
tree142f0258cefd71ed210c64ae73f852e386f71991 /src/host/timeline.zig
parent57e254470e11ab40b6bae31b2cbf62aebca27ce4 (diff)
downloadsketchbook-b2f7c605c279b2dea0c25180730c3d2e7b4b7d45.tar.gz
sketchbook-b2f7c605c279b2dea0c25180730c3d2e7b4b7d45.zip
Make snapshots named marks and recordings named clips of sessions
The state file keeps live state only (SKETCH03, one slot). save NAME is a keyframe and a mark in the sessions database, synced to disk; load, diff, snapshot and expect-snapshot take mark names, through the keyframe's own layout migrated to today's, compared over the leaves migration kept. A file from before (SKETCH01/02) has its used snapshot slots imported as marks "1".."7" at open, then drops them; a run that records nothing leaves them alone. record NAME, stop and play NAME make and play clips: a frame range of a session and its start keyframe, nothing overwritten, nothing invalidated by a later save, no capacity. The 64 MiB .inputs file, its --fresh memset and Timeline's Bank are gone; numbers still work as names, so every existing script runs unchanged. Event times in a clip are the session's, not restarted at record. reload.script also checks that a field a reload drops is still in the keyframe taken before it (expect-key). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'src/host/timeline.zig')
-rw-r--r--src/host/timeline.zig308
1 files changed, 105 insertions, 203 deletions
diff --git a/src/host/timeline.zig b/src/host/timeline.zig
index b52c74d..697a9df 100644
--- a/src/host/timeline.zig
+++ b/src/host/timeline.zig
@@ -1,47 +1,18 @@
-//! Snapshots, input recordings and replay: generic over state bytes and
-//! `abi.Event`s, so any sketch gets time travel for free.
+//! 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.
//!
-//! Recordings are frames: 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.
+//! 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 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,
- /// The build that recorded it (`build`, two halves), 0 when unknown.
- build_low: u32,
- build_high: u32,
- reserved: 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];
- }
- pub fn build(r: *const Recording) u64 {
- return @as(u64, r.build_high) << 32 | r.build_low;
- }
- /// Events up to the end of the last whole frame.
- pub fn whole(r: *const Recording) usize {
- return frameStart(r.slice(), r.count);
- }
-};
+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 {
@@ -72,119 +43,69 @@ pub const Frames = struct {
}
};
-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;
- }
- /// Leaf by leaf (`memory.compare`): padding never differs.
- pub fn compare(self: Bank, a: usize, b: usize) memory.Diff {
- return memory.compare(self.state.layout, self.slot(a), self.slot(b));
- }
-};
-
pub const Timeline = struct {
- bank: Bank,
+ gpa: std.mem.Allocator,
+ /// Live state is its slot 0.
+ state: *memory.StateFile,
+ /// The running sketch's: a restore starts from its defaults.
+ defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void,
mode: abi.Mode = .live,
- selected: usize = 0,
+ /// 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 snapshot, for the host
+ /// 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,
- /// Restores a snapshot into live state.
- pub fn restore(self: *Timeline, index: usize) !void {
- try self.bank.restore(index);
+ pub fn deinit(self: *Timeline) void {
+ if (self.key) |k| k.free(self.gpa);
+ self.events.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.slot(0), self.defaults);
self.restored = true;
}
- /// `build` identifies the code recording (0: unknown); `play` warns
- /// when it differs.
- pub fn startRecording(self: *Timeline, index: usize, snapshot: usize, now: u64, build: 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.restore(snapshot);
- const r = self.bank.recording(index);
- @memset(std.mem.asBytes(r)[0..32], 0);
- r.magic = recording_magic;
- r.snapshot = @intCast(snapshot);
- r.build_low = @truncate(build);
- r.build_high = @truncate(build >> 32);
- self.selected = index;
+ /// 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;
+ 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.clock = now;
self.mode = .recording;
}
- /// Records one frame (its events, then its tick) and rewrites their
- /// times as recorded, so live `update` sees exactly what a replay will.
- /// A frame that does not fit ends the recording before it.
- pub fn capture(self: *Timeline, frame: []abi.Event) !void {
- if (self.mode != .recording) return;
- const r = self.bank.recording(self.selected);
- if (frame.len > capacity - r.count) {
- self.mode = .live;
- return error.RecordingFull;
- }
- for (frame) |*e| {
- // 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 = r.duration;
- 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;
- }
+ pub fn stop(self: *Timeline) void {
self.mode = .live;
}
- pub fn play(self: *Timeline, index: usize, now: u64) !void {
- const r = try self.bank.get(index);
- try self.restore(r.snapshot);
- self.selected = index;
+ 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;
@@ -203,35 +124,33 @@ pub const Timeline = struct {
/// 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 r = self.bank.recording(self.selected);
- self.position = @min(r.duration, self.position +| (now -| self.clock));
+ 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 < r.count and r.events[i].time <= self.position) : (i += 1) {
- if (r.events[i].kind == .tick) self.cursor = i + 1;
+ 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 == r.duration) self.mode = .paused;
- return r.events[start..self.cursor];
+ if (self.position == end) self.mode = .paused;
+ return self.events.items[start..self.cursor];
}
- /// Restores the snapshot and returns the frames that make up the first
- /// `count` events (rounded down to a whole frame) to replay, so seeking
- /// backwards works too.
+ /// 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 {
- const r = try self.bank.get(self.selected);
- try self.restore(r.snapshot);
- self.cursor = frameStart(r.slice(), count);
- self.position = if (self.cursor == 0) 0 else r.events[self.cursor - 1].time;
+ 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 r.events[0..self.cursor];
+ return self.events.items[0..self.cursor];
}
- /// To the last frame whose tick is at or before `time`.
+ /// 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 r = try self.bank.get(self.selected);
- const position = @min(time, r.duration);
+ const position = @min(time, self.duration());
var count: usize = 0;
- for (r.slice(), 0..) |e, i| {
- if (e.time > position) break;
+ 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);
@@ -240,13 +159,12 @@ pub const Timeline = struct {
}
/// Moves by `steps` frames, forwards or back.
pub fn step(self: *Timeline, steps: i64) ![]const abi.Event {
- const r = try self.bank.get(self.selected);
- const events = r.slice();
+ 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) {
- const end = r.whole();
if (cursor == end) break;
cursor += 1;
while (cursor < end and events[cursor - 1].kind != .tick) cursor += 1;
@@ -259,62 +177,46 @@ pub const Timeline = struct {
}
};
-/// 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 });
-}
-
-test "frames are whole: input waits for its tick, live and in playback" {
- var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
- defer arena.deinit();
- const a = arena.allocator();
- // A bank on plain memory: one slot of 8 bytes, snapshot 1 used.
+test "frames are whole: input waits for its tick, in playback, seek and step" {
+ const gpa = std.testing.allocator;
+ // Live state on plain memory: 8 bytes, no fields.
var file: memory.StateFile = undefined;
- file.map = try a.alignedAlloc(u8, .fromByteUnits(memory.page), memory.header_len + memory.slot_count * memory.page);
+ file.map = try gpa.alignedAlloc(u8, .fromByteUnits(memory.page), memory.header_len + memory.page);
+ defer gpa.free(file.map);
@memset(file.map, 0);
- file.header().* = .{ .size = 8, .alignment = 1, .hash = 1, .stride = memory.page, .used = 0b11, .field_count = 0, .strings_len = 0 };
- file.layout = .{};
- const inputs = try a.alignedAlloc(u8, .fromByteUnits(memory.page), recording_len);
- @memset(inputs, 0);
- var t: Timeline = .{ .bank = .{ .state = &file, .inputs = inputs } };
- // Frame k: a move at 10k ms, its tick at 10k + 5 ms; then a move with
- // no tick (a frame cut off).
- try t.startRecording(0, 1, 1000, 7);
- try std.testing.expect(t.restored);
+ file.slots = 1;
+ file.header().* = .{ .size = 8, .alignment = 1, .hash = 1, .stride = memory.page, .used = 1, .field_count = 0, .strings_len = 0 };
+ file.layout = .{ .size = 8, .hash = 1 };
+ const D = struct {
+ fn f(_: abi.Memory, _: [*]u8) callconv(.c) void {}
+ };
+ var t: Timeline = .{ .gpa = gpa, .state = &file, .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| {
- var frame = [_]abi.Event{
- .{ .kind = .mouse_move, .time = 1000 + k * 10_000_000, .x = @floatFromInt(k) },
- abi.Event.tick(1000 + k * 10_000_000 + 5_000_000, 16_666_667),
- };
- try t.capture(&frame);
- // Live update sees the recorded times.
- try std.testing.expectEqual(@as(u64, k * 10_000_000 + 5_000_000), frame[1].time);
- try std.testing.expectEqual(abi.Event.tick(0, 16_666_667).tickDt(), frame[1].tickDt());
+ 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));
}
- const r = t.bank.recording(0);
- r.events[r.count] = .{ .kind = .mouse_move, .time = 40_000_000 };
- r.count += 1;
- t.stop(1000 + 41_000_000);
- try std.testing.expectEqual(@as(u64, 7), r.build());
+ 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, file.layoutBytes()) };
+ t.load(key, events);
- try t.play(0, 0);
+ 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 events = t.tick(now);
- if (events.len == 0) continue;
- try std.testing.expectEqual(abi.Event.Kind.tick, events[events.len - 1].kind);
- var it = frames(events);
+ 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);
- try std.testing.expectEqual(abi.Event.tick(0, 16_666_667).tickDt(), frame[1].tickDt());
+ // 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;
}
}
@@ -322,13 +224,13 @@ test "frames are whole: input waits for its tick, live and in playback" {
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, 4), (try t.seekTime(22_000_000)).len);
- try std.testing.expectEqual(@as(usize, 8), (try t.seekCount(r.count)).len);
+ 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(r.slice());
+ var it = frames(t.events.items);
var n: usize = 0;
while (it.next()) |_| n += 1;
try std.testing.expectEqual(@as(usize, 4), n);