summaryrefslogtreecommitdiff
path: root/src/host/timeline.zig
blob: e755433fcbbc3459ec212dc42d37ecdbcae5a209 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
//! 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);
    }
}