summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-16 20:31:59 -0300
committerGabriel Schneider <[email protected]>2026-11-16 20:31:59 -0300
commit82fca5c9f29124f37f6dcd08e73e6999ce44a69d (patch)
treeb3d5487659aa933d47699e5e420fa6140b0b75f3
parente77b01d4b5504cea08a3f88cf8502897d868a1d3 (diff)
downloadsketchbook-82fca5c9f29124f37f6dcd08e73e6999ce44a69d.tar.gz
sketchbook-82fca5c9f29124f37f6dcd08e73e6999ce44a69d.zip
Add display-paced frame timing and presentation feedback in Zig
-rw-r--r--README.md73
-rw-r--r--build.zig16
-rw-r--r--src/abi.zig3
-rw-r--r--src/host/Console.zig41
-rw-r--r--src/host/Host.zig81
-rw-r--r--src/host/Presentation.zig331
-rw-r--r--src/host/Timing.zig169
-rw-r--r--src/host/TimingAtlas.zig138
-rw-r--r--src/host/control.zig94
-rw-r--r--src/host/gfx.zig13
-rw-r--r--src/host/overlay.zig48
-rw-r--r--src/host/root.zig5
-rw-r--r--src/host/timeline.zig2
-rw-r--r--src/host/timing_marker.zig45
-rw-r--r--vendor/README.md21
-rw-r--r--vendor/presentation-time/presentation-time.xml296
16 files changed, 1362 insertions, 14 deletions
diff --git a/README.md b/README.md
index eb82bda..298dde4 100644
--- a/README.md
+++ b/README.md
@@ -93,7 +93,10 @@ trackpad's or a touch screen's pinch arrives as ctrl+wheel with no key
events at all. `update` is called once per frame, with that frame's events
ending in its tick, live and replayed alike; in `update`, `input.now` and
`input.dt` come from that tick (`dt` read back from the tick's f32
-seconds, so a replay sees the same bits). `input.mouse_x`/`buttons`/`held`
+seconds, so a replay sees the same bits). Interactive Wayland frames use the
+display-paced clock for update and draw automatically; unsupported backends use
+wall time, and the browser uses its animation-frame timestamp.
+`input.mouse_x`/`buttons`/`held`
follow the events fed so far. So time-driven and pointer-driven sketches
replay exactly. Fields no event carries (`width`, `window_width`,
`console`, `frame`) are not replayed: a sketch that reads them in `update`
@@ -609,7 +612,7 @@ object.
replay may then diverge.
- **Console and overlays.** `get`/`set <field path>` (`get` of a vector,
array or struct shows its values, in memory order), snapshots, recordings and
- the memory and scope overlays come from the host; unknown lines go to the
+ the memory, scope and frame timing overlays come from the host; unknown lines go to the
sketch. Paths index arrays and vector lanes: `get pos[0]`,
`set boids.buffer[3].pos[1] 20`. `diff N` compares live state with
snapshot N leaf by leaf, so padding (a Debug `@Vector`'s spare lane)
@@ -1015,6 +1018,72 @@ printf 'screenshot\n' | 9p -a unix!/tmp/drat.sock write ctl
printf 'quit\n' | 9p -a unix!/tmp/drat.sock write ctl
```
+The native host's `timing` command toggles a scrolling graph with average, p90
+and p99 in milliseconds. `timing on|off` sets visibility;
+`timing frame|work` selects the graph and shows it; `overlay timing` also toggles.
+`timing stats` prints current average/p90/p99/maximum; `timing reset` clears history
+without changing visibility or metric. Collection continues while hidden.
+Readouts refresh about four times a second from fixed text buffers. All glyphs
+reuse one immutable atlas texture, so changing values neither rasterizes text
+nor switches textures per digit. Fixed vertex/index arrays batch the entire
+panel, graph and text into one geometry draw, without per-frame overlay allocation.
+Percentiles use nearest rank over the last 240 individual frames. A separate
+fixed graph ring holds 240 peaks, each over eight frames: eight times slower
+scrolling, with single-frame spikes preserved across 1920 frames. Its scale
+label updates when the peak range changes. Frame measures wall-clock cadence
+between completed host frames, including pacing, event/9P polling and present.
+Work measures update/draw through the deferred 2D command flush, before present.
+Both include visible overlays and screenshot capture and use real time even
+during replay/export. These are not GPU hardware timestamps, and frame can
+include vsync waits. No GPU synchronization is added. Test with
+`zig build test-timing`.
+
+The read-only 9P file `timing-trace` exports paired raw samples as CSV:
+`index,frame_ns,work_ns,outside_work_ns`. Indices start at zero within the captured
+history, oldest first. `outside_work_ns` is saturating `frame_ns - work_ns`, including
+pacing, polling, presentation and cleanup; it is not a hardware GPU duration. Each
+open pins the bounded timing history, so subsequent frames or `timing reset`
+cannot change a partially read trace. It works without `--profile-gpu`:
+`9p -a unix!/tmp/drat.sock read timing-trace > timing.csv`.
+
+For compositor/video measurements, launch with `--timing-marker`. This opt-in
+marker is drawn last, independently of the timing overlay: 80 black/white cells,
+each 4×8 canvas pixels, at the bottom-left (320×8 total). Cells encode, LSB-first,
+16-bit magic `0xD3A7`, the low 32 bits of `Input.frame`, then the low 32 bits of
+`Input.now` in whole milliseconds. It identifies submitted frames and draw
+sample times in captured video; repeated decoded IDs reveal repeated presented
+frames. Decode at canvas scale, accounting for any window/compositor scaling.
+The marker is omitted when the canvas is smaller than 320×8 and is disabled by
+default. `zig build test-timing` checks its encoding, placement and counter wrap.
+
+On Wayland, `presentation-trace` provides immutable CSV snapshots of
+`wp_presentation` feedback: frame ID, sample time, request time, presented/discarded
+result, presentation timestamp, refresh period, sequence and flags. Status and
+clock metadata make unsupported backends explicit. `commit_ns` is the feedback
+request time before present, not an intercepted surface commit. Only subtract
+timestamps in the same clock domain; sample time uses SDL's elapsed clock.
+Feedback attaches to the next surface commit, which the binary marker lets a
+compositor capture independently verify.
+
+Interactive Wayland windows use this feedback to pace submissions and sample
+one shared frame clock before update and draw. Ordinary `Input.now`, tick events
+and `Input.dt` therefore follow display refresh automatically; sketches need no
+separate rendering clock or animation correction. A tick never precedes the
+previous frame or its queued input, so newly arrived input can move it slightly
+past the scheduled instant. Recording stores these exact ticks; replay, scripts
+and export retain their existing clocks. The browser already uses the
+`requestAnimationFrame` timestamp for its shared update/draw clock.
+Without usable feedback, rendering falls back to SDL's normal presentation and
+wall-clock ticks. Hidden/minimized windows keep servicing controls but skip
+animation and drawing until visible again.
+The implementation is `src/host/Presentation.zig`, including the Wayland callbacks
+and trace writer. `zig build test-presentation` checks its clock and feedback
+behavior. Linux builds require `wayland-scanner` plus the `wayland-client`
+development package and pkg-config metadata. The build generates the protocol
+header/tables from the vendored XML and translates the header into Zig bindings;
+only the generated protocol tables are compiled as C.
+
+
`ctl` accepts complete console command lines (up to 4096 bytes per write),
including game commands and host `set`, `get`, `pause`, `step`, `seek`, and `quit`.
Errors return as 9P errors. `log` exposes the console's latest five lines;
diff --git a/build.zig b/build.zig
index efb4dfb..1933d92 100644
--- a/build.zig
+++ b/build.zig
@@ -79,6 +79,9 @@ pub fn build(b: *Build) void {
});
b.step("test-control", "Test 9P control validation and screenshot snapshots").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{ "control writes", "9P reads" } })).step);
+ b.step("test-timing", "Test display clock, recorded ticks, timing history and console controls").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{ "timing", "presentation", "frames are whole", "a tick's dt" } })).step);
+
+ b.step("test-presentation", "Test presentation feedback, pacing and trace snapshots").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{"presentation"} })).step);
const setup_tests = b.step("test-setup", "Test resource setup lifecycle and arguments");
for ([_]*Build.Module{ host, b.createModule(.{ .root_source_file = b.path("src/sketch/root.zig"), .target = target, .optimize = optimize, .imports = sketch_imports }) }) |module| setup_tests.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module, .filters = &.{"setup"} })).step);
@@ -356,6 +359,11 @@ fn cModule(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.Optimi
\\#include <SDL3/SDL.h>
\\#include "codecs.h"
\\#include "text.h"
+ \\#if defined(__linux__)
+ \\#include <time.h>
+ \\#include <wayland-client.h>
+ \\#include "presentation-time-client-protocol.h"
+ \\#endif
),
.target = target,
.optimize = optimize,
@@ -364,6 +372,14 @@ fn cModule(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.Optimi
translator.addIncludePath(b.path("vendor"));
translator.mod.addCSourceFile(.{ .file = b.path("vendor/codecs.c"), .flags = &.{"-fno-sanitize=undefined"} });
if (target.result.os.tag == .linux) {
+ const protocol = b.path("vendor/presentation-time/presentation-time.xml");
+ const header = b.addSystemCommand(&.{ "wayland-scanner", "client-header" });
+ header.addFileArg(protocol);
+ translator.addIncludePath(header.addOutputFileArg("presentation-time-client-protocol.h").dirname());
+ const source = b.addSystemCommand(&.{ "wayland-scanner", "private-code" });
+ source.addFileArg(protocol);
+ translator.mod.addCSourceFile(.{ .file = source.addOutputFileArg("presentation-time-protocol.c"), .flags = &.{"-std=c99"} });
+ translator.mod.linkSystemLibrary("wayland-client", .{ .use_pkg_config = .force });
translator.mod.addCSourceFile(.{ .file = b.path("vendor/text.c"), .flags = &.{"-std=c23"} });
translator.mod.linkSystemLibrary("pangocairo-1.0", .{ .use_pkg_config = .force });
translator.mod.linkSystemLibrary("pangoft2-1.0", .{ .use_pkg_config = .force });
diff --git a/src/abi.zig b/src/abi.zig
index 2eed3a7..d91fa23 100644
--- a/src/abi.zig
+++ b/src/abi.zig
@@ -164,7 +164,8 @@ pub const Stream = struct {
pub const Input = struct {
/// In `update`, the frame's tick time (`Event.time`: since the
/// recording began while recording or replaying); in `draw`, the host
- /// clock, or the playback position.
+ /// clock, or the playback position. Interactive native frames align
+ /// this clock and dt to display refresh when feedback is available.
now: u64 = 0,
/// In `update`, the frame's tick `dt` (`Event.tickDt`), the same live
/// and replayed; in `draw`, likewise for the frame just updated.
diff --git a/src/host/Console.zig b/src/host/Console.zig
index 40845f7..0c44ea2 100644
--- a/src/host/Console.zig
+++ b/src/host/Console.zig
@@ -14,8 +14,9 @@ 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",
- "record", "stop", "play", "pause", "step", "seek start", "seek end", "diff", "quit", "exit",
+ "help", "overlay memory", "overlay sound", "get", "set", "reset", "save", "load", "snapshot", "recording",
+ "record", "stop", "play", "pause", "step", "seek start", "seek end", "diff", "quit", "exit",
+ "overlay timing", "timing on", "timing off", "timing frame", "timing work", "timing reset", "timing stats",
};
visible: bool = false,
@@ -135,14 +136,29 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const
if (eq(command, "help")) {
self.log("save|load [1..7] snapshot N | record|play [0..15] recording N | stop | pause | step N (frames) | seek start|end|<ms>");
self.log("diff [N] | reset | get <field> | set <field> <value> | overlay memory|sound | quit");
+ self.log("timing [on|off|frame|work|reset|stats] | overlay timing");
if (host.forward(self, line, now) == .unknown) self.log("Backtick hides the console. Tab completes.");
return &.{};
}
if (eq(command, "overlay")) {
const name = arg orelse return error.ExpectedOverlay;
- const flag = if (eq(name, "memory")) &self.overlay_memory else if (eq(name, "sound")) &self.overlay_sound else return error.UnknownOverlay;
+ if (rest.len != 0) return error.UnexpectedArgument;
+ const flag = if (eq(name, "memory")) &self.overlay_memory else if (eq(name, "sound")) &self.overlay_sound else if (eq(name, "timing")) &host.timing.visible else return error.UnknownOverlay;
flag.* = !flag.*;
+ host.timing.dirty = true;
self.print("{s} overlay: {s}", .{ name, if (flag.*) "on" else "off" });
+ } else if (eq(command, "timing")) {
+ if (rest.len != 0) return error.UnexpectedArgument;
+ if (eq(arg orelse "", "stats")) {
+ self.print("Timing: last {d}/240 frames; frame includes present, work excludes present (wall clock).", .{host.timing.count});
+ inline for (.{ .frame, .work }) |metric| {
+ const s = host.timing.stats(metric);
+ self.print("{s}: avg {d:.3} ms | p90 {d:.3} ms | p99 {d:.3} ms | max {d:.3} ms", .{ @tagName(metric), s.mean, s.p90, s.p99, s.max });
+ }
+ } else {
+ try host.timing.command(arg);
+ self.print("Timing overlay: {s}, graph: {t}, samples: {d}", .{ if (host.timing.visible) "on" else "off", host.timing.metric, host.timing.count });
+ }
} else if (eq(command, "get")) {
const path = arg orelse return error.ExpectedField;
var buf: [160]u8 = undefined;
@@ -276,3 +292,22 @@ test "line editing, completion and submission" {
try std.testing.expectEqualStrings("", c.text());
try std.testing.expect(c.edit(.submit, &.{}) == null);
}
+
+test "timing console controls and validation" {
+ var host: Host = undefined;
+ host.timing = .{};
+ var console: Console = .{};
+ _ = try console.execute(&host, "timing work", 0);
+ try std.testing.expect(host.timing.visible and host.timing.metric == .work);
+ _ = try console.execute(&host, "overlay timing", 0);
+ try std.testing.expect(!host.timing.visible);
+ host.timing.add(.{ .frame = 17000000, .work = 500000 });
+ _ = try console.execute(&host, "timing stats", 0);
+ const last = console.lines[console.lines.len - 1];
+ try std.testing.expect(std.mem.indexOf(u8, last.bytes[0..last.len], "p99 0.500 ms") != null);
+ try std.testing.expectError(error.UnexpectedArgument, console.execute(&host, "timing on extra", 0));
+ try std.testing.expect(!host.timing.visible);
+ try std.testing.expectError(error.ExpectedTimingOnOffFrameWorkResetStats, console.execute(&host, "timing bogus", 0));
+ _ = try console.execute(&host, "timing reset", 0);
+ try std.testing.expectEqual(@as(usize, 0), host.timing.count);
+}
diff --git a/src/host/Host.zig b/src/host/Host.zig
index 02a88c7..745d9a1 100644
--- a/src/host/Host.zig
+++ b/src/host/Host.zig
@@ -15,6 +15,9 @@ const sound = @import("audio.zig");
const Gpu = @import("gpu");
const overlay = @import("overlay.zig");
const Console = @import("Console.zig");
+const Timing = @import("Timing.zig");
+const Presentation = @import("Presentation.zig");
+const timing_marker = @import("timing_marker.zig");
const Control = @import("control.zig").Control;
const Library = @import("library.zig").Library;
const Watch = @import("library.zig").Watch;
@@ -32,6 +35,8 @@ pub const Options = struct {
fresh: bool = false,
/// Time every GPU command alone and print the times at exit.
profile_gpu: bool = false,
+ /// Binary frame/time marker for external video measurements.
+ timing_marker: bool = false,
/// Export every frame: PNGs `<dir>/000000.png`, ..., or for "-" raw RGBA
/// rows on stdout. Frames run on a clock of their own (see `fps`).
export_to: ?[]const u8 = null,
@@ -52,6 +57,7 @@ renderer: *c.SDL_Renderer,
/// Runs sketches' GPU passes, and the 2D renderer draws through it too.
/// Null when the machine has no usable GPU driver.
gpu: ?*c.SDL_GPUDevice,
+presentation: ?*Presentation = null,
passes: ?Gpu = null,
/// GPU canvas, shared by native/headless drawing, backdrop filters and screenshots.
offscreen: ?*c.SDL_Texture = null,
@@ -71,6 +77,8 @@ made: struct { images: std.ArrayList(abi.Image) = .empty, buffers: std.ArrayList
recordings: []align(memory.page) u8,
timeline: Timeline,
console: Console = .{},
+timing: Timing = .{},
+timing_atlas: overlay.TimingAtlas = .{},
sketch: abi.Sketch,
library: ?Library = null,
watch: ?Watch = null,
@@ -98,6 +106,7 @@ reloaded: bool = true,
jumped: bool = true,
started: bool = true,
last_now: u64 = 0,
+last_frame_end: u64 = 0,
/// Saved after the next frame is drawn (scripts).
screenshot: ?[:0]const u8 = null,
/// Frames exported so far (`Options.export_to`).
@@ -203,6 +212,10 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
@memset(self.recordings, 0);
self.resetState();
}
+ if (!options.headless and options.export_to == null) {
+ self.presentation = Presentation.init(gpa, self.window) catch null;
+ if (options.timing_marker) self.print("presentation tracing: {s}", .{if (self.presentation) |p| p.status else "disabled_or_allocation_failed"});
+ }
}
pub fn deinit(self: *Host) void {
@@ -215,6 +228,7 @@ pub fn deinit(self: *Host) void {
if (self.passes) |*g| g.deinit();
if (self.pointer_cursor) |cursor| c.SDL_DestroyCursor(cursor);
if (self.offscreen) |texture| c.SDL_DestroyTexture(texture);
+ if (self.presentation) |p| p.deinit(self.gpa);
c.SDL_DestroyRenderer(self.renderer);
if (self.gpu) |device| c.SDL_DestroyGPUDevice(device);
c.SDL_DestroyWindow(self.window);
@@ -244,11 +258,54 @@ pub fn run(self: *Host) !void {
while (!self.quit) {
if (self.control) |control| control.poll(self);
try self.poll();
- try self.frame(if (self.options.export_to == null) c.SDL_GetTicksNS() else std.time.ns_per_s + self.exported * std.time.ns_per_s / self.options.fps);
+ if (self.presentation) |p| p.poll();
+ if (!self.options.headless and self.options.export_to == null and
+ c.SDL_GetWindowFlags(self.window) & (c.SDL_WINDOW_OCCLUDED | c.SDL_WINDOW_MINIMIZED | c.SDL_WINDOW_HIDDEN) != 0 and
+ self.screenshot == null and !(self.control != null and self.control.?.capture_pending))
+ {
+ // Occluded Wayland presentation can block for a second; keep controls alive and resume without a camera jump.
+ self.last_now = 0;
+ self.last_frame_end = 0;
+ _ = c.SDL_Delay(10);
+ continue;
+ }
+ // GPU fences do not limit presentation rate; follow the measured display clock.
+ const wait_ns = if (self.presentation) |p| p.waitNs() else 0;
+ if (wait_ns != 0) {
+ c.SDL_DelayPrecise(@min(wait_ns, std.time.ns_per_ms));
+ continue;
+ }
+ const wall = c.SDL_GetTicksNS();
+ const now = if (self.options.export_to != null)
+ std.time.ns_per_s + self.exported * std.time.ns_per_s / self.options.fps
+ else
+ frameTime(wall, if (self.presentation) |p| p.sampleNs(wall) else wall, self.last_now, self.timeline.mode, self.pending.items);
+ try self.frame(now);
}
self.timeline.stop(c.SDL_GetTicksNS());
}
+// Live animation uses the display clock, but a tick must not predate its input.
+fn frameTime(wall: u64, scheduled: u64, previous: u64, mode: abi.Mode, events: []const abi.Event) u64 {
+ if (mode != .live and mode != .recording) return wall;
+ var now = @max(scheduled, previous);
+ for (events) |event| now = @max(now, event.time);
+ return now;
+}
+
+test "timing clock drives ordinary ticks without moving input or replay time" {
+ const expectEqual = std.testing.expectEqual;
+ try expectEqual(@as(u64, 100), frameTime(103, 100, 80, .live, &.{}));
+ try expectEqual(@as(u64, 120), frameTime(127, 120, 100, .recording, &.{}));
+ const events = [_]abi.Event{ .{ .kind = .key_down, .time = 102 }, .{ .kind = .key_up, .time = 101 } };
+ try expectEqual(@as(u64, 102), frameTime(103, 100, 80, .live, &events));
+ try expectEqual(@as(u64, 102), events[0].time);
+ try expectEqual(@as(u64, 101), events[1].time);
+ try expectEqual(@as(u64, 103), frameTime(103, 103, 80, .live, &.{})); // No feedback.
+ try expectEqual(@as(u64, 110), frameTime(103, 100, 110, .live, &.{})); // Clock reversal.
+ for ([_]abi.Mode{ .playing, .paused }) |mode| try expectEqual(@as(u64, 103), frameTime(103, 100, 110, mode, &events));
+}
+
pub fn live(self: *Host) []u8 {
return self.state.slot(0);
}
@@ -256,6 +313,7 @@ pub fn live(self: *Host) []u8 {
/// One frame: reload if a build replaced the library, feed input through
/// `update`, then `draw` and present.
pub fn frame(self: *Host, now: u64) !void {
+ const started = c.SDL_GetTicksNS();
const zone = tracy.zone(@src(), "frame");
tracy.frameMark();
defer zone.end();
@@ -281,7 +339,10 @@ pub fn frame(self: *Host, now: u64) !void {
},
}
self.pending.clearRetainingCapacity();
- try self.draw(if (h.mode == .live or h.mode == .recording) now else h.position);
+ const work = try self.draw(if (h.mode == .live or h.mode == .recording) now else h.position, started);
+ const ended = c.SDL_GetTicksNS();
+ self.timing.add(.{ .frame = ended - (if (self.last_frame_end == 0) started else self.last_frame_end), .work = work });
+ self.last_frame_end = ended;
}
/// Feeds whole frames to the sketch's deterministic `update`, one call per
@@ -331,7 +392,7 @@ fn restoredInput(self: *Host, now: u64) !void {
try self.pending.insertSlice(self.gpa, 0, seed.items);
}
-fn draw(self: *Host, now: u64) !void {
+fn draw(self: *Host, now: u64, started: u64) !u64 {
const zone = tracy.zone(@src(), "Host.zig:draw");
defer zone.end();
const arena = self.frame_arena.allocator();
@@ -405,7 +466,14 @@ fn draw(self: *Host, now: u64) !void {
const samples = self.audio.scope.snapshot();
try overlay.drawScope(&extra, arena, &samples, self.audio.scope.rate, self.canvas);
}
+ if (self.timing.visible) {
+ if (self.timing_atlas.image == .none) self.timing_atlas = try overlay.TimingAtlas.init(&self.images, &self.painter);
+ for (extra.items) |command| self.painter.draw(command);
+ extra.clearRetainingCapacity();
+ try overlay.drawTiming(&self.painter, &self.timing, self.canvas, self.timing_atlas);
+ }
if (self.console.visible) try self.console.draw(self, &extra, arena);
+ if (self.options.timing_marker) try timing_marker.draw(&extra, arena, self.canvas, self.input.frame, self.input.now);
for (extra.items) |command| self.painter.draw(command);
self.painter.end();
self.applyCursor();
@@ -425,10 +493,15 @@ fn draw(self: *Host, now: u64) !void {
_ = c.SDL_SetTextureBlendMode(canvas, c.SDL_BLENDMODE_NONE);
_ = c.SDL_RenderTexture(self.renderer, canvas, null, null);
};
+ // Present otherwise encodes the deferred 2D commands after the work timestamp.
+ if (!c.SDL_FlushRenderer(self.renderer)) return sdlError("SDL_FlushRenderer");
+ const work = c.SDL_GetTicksNS() - started;
const present_zone = tracy.zone(@src(), "present");
+ if (self.presentation) |p| p.request(self.input.frame, self.input.now);
_ = c.SDL_RenderPresent(self.renderer);
present_zone.end();
if (self.passes) |*g| g.endFrame();
+ return work;
}
/// One exported frame: `<to>/<its number, six digits>.png`, or for "-" its
@@ -577,7 +650,7 @@ pub fn runLine(self: *Host, line: []const u8, now: u64) !void {
fn movesState(line: []const u8) bool {
var words = std.mem.tokenizeAny(u8, line, " \t");
const verb = words.next() orelse return false;
- const still = [_][]const u8{ "help", "overlay", "get", "snapshot", "recording", "diff", "stop", "pause", "save", "quit", "exit" };
+ const still = [_][]const u8{ "help", "overlay", "timing", "get", "snapshot", "recording", "diff", "stop", "pause", "save", "quit", "exit" };
for (still) |w| if (std.mem.eql(u8, verb, w)) return false;
return true;
}
diff --git a/src/host/Presentation.zig b/src/host/Presentation.zig
new file mode 100644
index 0000000..c191c79
--- /dev/null
+++ b/src/host/Presentation.zig
@@ -0,0 +1,331 @@
+//! Wayland feedback and display-clock pacing; other backends keep SDL's pacing.
+const Presentation = @This();
+const std = @import("std");
+const c = @import("c");
+const linux = @import("builtin").os.tag == .linux;
+const capacity = 8192;
+const pending_capacity = 256;
+
+pub const Record = struct {
+ frame: u64 = 0,
+ sample_ms: u64 = 0,
+ commit_ns: u64 = 0,
+ presented_ns: u64 = 0,
+ refresh_ns: u64 = 0,
+ sequence: u64 = 0,
+ flags: u32 = 0,
+ result: enum { presented, discarded } = .discarded,
+};
+status: []const u8 = if (linux) "not_wayland" else "unsupported_platform",
+clock_id: u32 = 0,
+have_clock: bool = false,
+completed: u64 = 0,
+exhausted: u64 = 0,
+last_submit_ns: u64 = 0,
+next_submit_ns: u64 = 0,
+submit_period_ns: u64 = 0,
+records: [capacity]Record = @splat(.{}),
+wl: Wayland = .{},
+
+const Wayland = if (linux) struct {
+ display: ?*c.wl_display = null,
+ surface: ?*c.wl_surface = null,
+ queue: ?*c.wl_event_queue = null,
+ registry: ?*c.wl_registry = null,
+ presentation: ?*c.wp_presentation = null,
+ global_name: u32 = 0,
+ pending: [pending_capacity]Pending = @splat(.{}),
+
+ const Pending = struct {
+ owner: *Presentation = undefined,
+ feedback: ?*c.struct_wp_presentation_feedback = null,
+ record: Record = .{},
+ };
+ fn finish(pending: *Pending, result: @FieldType(Record, "result")) void {
+ const self = pending.owner;
+ pending.record.result = result;
+ self.records[self.completed % capacity] = pending.record;
+ self.completed += 1;
+ if (pending.feedback) |feedback| c.wp_presentation_feedback_destroy(feedback);
+ pending.feedback = null;
+ }
+ fn syncOutput(_: ?*anyopaque, _: ?*c.struct_wp_presentation_feedback, _: ?*c.wl_output) callconv(.c) void {}
+ fn presented(data: ?*anyopaque, _: ?*c.struct_wp_presentation_feedback, sec_hi: u32, sec_lo: u32, nsec: u32, refresh: u32, seq_hi: u32, seq_lo: u32, flags: u32) callconv(.c) void {
+ const pending: *Pending = @ptrCast(@alignCast(data.?));
+ pending.record.presented_ns = ((@as(u64, sec_hi) << 32) | sec_lo) * std.time.ns_per_s + nsec;
+ pending.record.refresh_ns = refresh;
+ pending.record.sequence = (@as(u64, seq_hi) << 32) | seq_lo;
+ pending.record.flags = flags;
+ finish(pending, .presented);
+ }
+ fn discarded(data: ?*anyopaque, _: ?*c.struct_wp_presentation_feedback) callconv(.c) void {
+ finish(@ptrCast(@alignCast(data.?)), .discarded);
+ }
+ const feedback_listener: c.wp_presentation_feedback_listener = .{ .sync_output = syncOutput, .presented = presented, .discarded = discarded };
+ fn clockId(data: ?*anyopaque, _: ?*c.wp_presentation, id: u32) callconv(.c) void {
+ const self: *Presentation = @ptrCast(@alignCast(data.?));
+ self.clock_id = id;
+ var now: c.timespec = undefined;
+ self.have_clock = c.clock_gettime(@bitCast(id), &now) == 0;
+ self.status = if (self.have_clock) "ready" else "unsupported_presentation_clock";
+ }
+ const presentation_listener: c.wp_presentation_listener = .{ .clock_id = clockId };
+ fn global(data: ?*anyopaque, registry: ?*c.wl_registry, name: u32, interface: [*c]const u8, version: u32) callconv(.c) void {
+ const self: *Presentation = @ptrCast(@alignCast(data.?));
+ if (!std.mem.eql(u8, std.mem.span(interface), "wp_presentation") or self.wl.presentation != null or version < 1) return;
+ self.wl.global_name = name;
+ self.wl.presentation = @ptrCast(c.wl_registry_bind(registry, name, &c.wp_presentation_interface, 1));
+ if (self.wl.presentation) |presentation| _ = c.wp_presentation_add_listener(presentation, &presentation_listener, self);
+ }
+ fn globalRemove(data: ?*anyopaque, _: ?*c.wl_registry, name: u32) callconv(.c) void {
+ const self: *Presentation = @ptrCast(@alignCast(data.?));
+ if (name == self.wl.global_name) {
+ self.have_clock = false;
+ self.status = "presentation_global_removed";
+ }
+ }
+ const registry_listener: c.wl_registry_listener = .{ .global = global, .global_remove = globalRemove };
+} else struct {};
+
+pub fn init(gpa: std.mem.Allocator, window: *c.SDL_Window) !*Presentation {
+ const self = try gpa.create(Presentation);
+ self.* = .{};
+ if (!linux) return self;
+ const props = c.SDL_GetWindowProperties(window);
+ self.wl.display = @ptrCast(c.SDL_GetPointerProperty(props, c.SDL_PROP_WINDOW_WAYLAND_DISPLAY_POINTER, null));
+ self.wl.surface = @ptrCast(c.SDL_GetPointerProperty(props, c.SDL_PROP_WINDOW_WAYLAND_SURFACE_POINTER, null));
+ if (self.wl.display == null or self.wl.surface == null) return self;
+ self.status = "wayland_queue_failed";
+ self.wl.queue = c.wl_display_create_queue(self.wl.display) orelse return self;
+ const wrapper = c.wl_proxy_create_wrapper(self.wl.display) orelse return self;
+ c.wl_proxy_set_queue(@ptrCast(wrapper), self.wl.queue);
+ self.wl.registry = c.wl_display_get_registry(@ptrCast(wrapper));
+ c.wl_proxy_wrapper_destroy(wrapper);
+ if (self.wl.registry == null) return self;
+ self.status = "wp_presentation_unavailable";
+ _ = c.wl_registry_add_listener(self.wl.registry, &Wayland.registry_listener, self);
+ // Only initialization reads/waits on SDL's shared display connection.
+ if (c.wl_display_roundtrip_queue(self.wl.display, self.wl.queue) < 0 or
+ c.wl_display_roundtrip_queue(self.wl.display, self.wl.queue) < 0)
+ {
+ self.have_clock = false;
+ self.status = "wayland_roundtrip_failed";
+ }
+ return self;
+}
+
+pub fn deinit(self: *Presentation, gpa: std.mem.Allocator) void {
+ if (linux) {
+ for (&self.wl.pending) |*pending| if (pending.feedback) |feedback| c.wp_presentation_feedback_destroy(feedback);
+ if (self.wl.presentation) |presentation| c.wp_presentation_destroy(presentation);
+ if (self.wl.registry) |registry| c.wl_registry_destroy(registry);
+ if (self.wl.queue) |queue| c.wl_event_queue_destroy(queue);
+ }
+ gpa.destroy(self);
+}
+pub fn poll(self: *Presentation) void {
+ if (!linux) return;
+ // SDL_PollEvent reads the connection; dispatch only our already-queued events.
+ if (self.wl.queue) |queue| if (c.wl_display_dispatch_queue_pending(self.wl.display, queue) < 0) {
+ self.have_clock = false;
+ self.status = "wayland_dispatch_failed";
+ };
+}
+fn protocolNow(self: *Presentation) ?u64 {
+ if (!linux or !self.have_clock) return null;
+ var now: c.timespec = undefined;
+ if (c.clock_gettime(@bitCast(self.clock_id), &now) != 0) {
+ self.have_clock = false;
+ self.status = "presentation_clock_failed";
+ return null;
+ }
+ return @as(u64, @intCast(now.tv_sec)) * std.time.ns_per_s + @as(u64, @intCast(now.tv_nsec));
+}
+fn validPeriod(period: u64) bool {
+ return period >= std.time.ns_per_ms and period <= 100 * std.time.ns_per_ms;
+}
+fn nextDeadline(record: ?*const Record, now: u64) u64 {
+ const r = record orelse return 0;
+ if (r.flags & 1 == 0 or !validPeriod(r.refresh_ns) or r.presented_ns > now) return 0;
+ var remaining = r.refresh_ns - (now - r.presented_ns) % r.refresh_ns;
+ if (remaining < r.refresh_ns / 2) remaining += r.refresh_ns;
+ return std.math.add(u64, now, remaining) catch 0;
+}
+fn remainingWait(deadline: u64, submitted: u64, period: u64, now: u64) u64 {
+ if (!validPeriod(period) or now < submitted or deadline <= now or deadline - now > period + period / 2) return 0;
+ return deadline - now;
+}
+fn waitAt(self: *Presentation, now: u64) u64 {
+ if (!self.have_clock) return 0;
+ const r = self.latest();
+ if (r == null or r.?.flags & 1 == 0 or r.?.refresh_ns != self.submit_period_ns or r.?.presented_ns > now or
+ now < self.last_submit_ns or (self.next_submit_ns > now and self.next_submit_ns - now > self.submit_period_ns + self.submit_period_ns / 2))
+ {
+ self.next_submit_ns = 0;
+ return 0;
+ }
+ // Keep a reached deadline until request replaces it, for sampling this frame.
+ return remainingWait(self.next_submit_ns, self.last_submit_ns, self.submit_period_ns, now);
+}
+pub fn waitNs(self: *Presentation) u64 {
+ return self.waitAt(self.protocolNow() orelse return 0);
+}
+fn scheduledSample(deadline: u64, period: u64, protocol_now: u64, sdl_now: u64) u64 {
+ if (deadline == 0 or !validPeriod(period) or protocol_now < deadline) return sdl_now;
+ const age = protocol_now - deadline;
+ if (age > period / 2 or age > sdl_now) return sdl_now;
+ return sdl_now - age;
+}
+pub fn sampleNs(self: *Presentation, sdl_now: u64) u64 {
+ const now = self.protocolNow() orelse return sdl_now;
+ _ = self.waitAt(now);
+ return scheduledSample(self.next_submit_ns, self.submit_period_ns, now, sdl_now);
+}
+pub fn request(self: *Presentation, frame: u64, sample_ns: u64) void {
+ if (!linux) return;
+ const now = self.protocolNow() orelse return;
+ const r = self.latest();
+ self.last_submit_ns = now;
+ self.submit_period_ns = if (r) |record| record.refresh_ns else 0;
+ self.next_submit_ns = nextDeadline(r, now);
+ for (&self.wl.pending) |*pending| {
+ if (pending.feedback != null) continue;
+ pending.owner = self;
+ pending.record = .{ .frame = frame, .sample_ms = sample_ns / std.time.ns_per_ms, .commit_ns = now };
+ // The next surface commit consumes this request, normally Vulkan present.
+ pending.feedback = c.wp_presentation_feedback(self.wl.presentation, self.wl.surface) orelse {
+ self.exhausted += 1;
+ return;
+ };
+ _ = c.wp_presentation_feedback_add_listener(pending.feedback, &Wayland.feedback_listener, pending);
+ return;
+ }
+ self.exhausted += 1;
+}
+pub fn latest(self: *const Presentation) ?*const Record {
+ for (0..@min(self.completed, capacity)) |i| {
+ const r = &self.records[(self.completed - i - 1) % capacity];
+ if (r.result == .presented) return r;
+ }
+ return null;
+}
+pub fn csv(self: ?*const Presentation, writer: *std.Io.Writer) !void {
+ try writer.print("# status {s}\n", .{if (self) |s| s.status else "disabled_or_allocation_failed"});
+ try writer.writeAll("# commit_ns is feedback-request time before SDL_RenderPresent, not a wl_surface.commit interception\n# sample_ms uses SDL elapsed time; commit_ns and presented_ns use the protocol clock\n");
+ if (linux) {
+ var pending: usize = 0;
+ if (self) |s| for (s.wl.pending) |p| {
+ pending += @intFromBool(p.feedback != null);
+ };
+ try writer.print("# clock_id {d}\n# completed {d}\n# pending {d}\n# exhausted {d}\n# retained_limit {d}\n", .{ if (self) |s| s.clock_id else 0, if (self) |s| s.completed else 0, pending, if (self) |s| s.exhausted else 0, capacity });
+ }
+ try writer.writeAll("frame_id,sample_ms,commit_ns,result,presented_ns,refresh_ns,sequence,flags\n");
+ if (self) |s| {
+ const start = s.completed -| capacity;
+ for (start..s.completed) |i| {
+ const r = s.records[i % capacity];
+ try writer.print("{d},{d},{d},{t},{d},{d},{d},{d}\n", .{ r.frame, r.sample_ms, r.commit_ns, r.result, r.presented_ns, r.refresh_ns, r.sequence, r.flags });
+ }
+ }
+}
+
+test "presentation display deadlines reject invalid clocks and avoid phase-jitter bursts" {
+ const expectEqual = std.testing.expectEqual;
+ var r: Record = .{ .presented_ns = 100000000, .refresh_ns = 10000000, .flags = 1 };
+ try expectEqual(@as(u64, 110000000), nextDeadline(&r, 100000000));
+ try expectEqual(@as(u64, 150000000), nextDeadline(&r, 137000000));
+ try expectEqual(@as(u64, 140000000), nextDeadline(&r, 135000000));
+ try expectEqual(@as(u64, 150000000), nextDeadline(&r, 139900000));
+ try expectEqual(@as(u64, 150000000), nextDeadline(&r, 140000000));
+ try expectEqual(@as(u64, 0), nextDeadline(&r, 99000000));
+ try expectEqual(@as(u64, 0), nextDeadline(null, 100000000));
+ r.flags = 0;
+ try expectEqual(@as(u64, 0), nextDeadline(&r, 100000000));
+ r.flags = 1;
+ r.refresh_ns = 999999;
+ try expectEqual(@as(u64, 0), nextDeadline(&r, 100000000));
+ r.refresh_ns = 100000001;
+ try expectEqual(@as(u64, 0), nextDeadline(&r, 100000000));
+ r.refresh_ns = 100000000;
+ try expectEqual(@as(u64, 200000000), nextDeadline(&r, 100000000));
+ r.refresh_ns = 1000000;
+ try expectEqual(@as(u64, 101000000), nextDeadline(&r, 100000000));
+ r.presented_ns = std.math.maxInt(u64) - 500;
+ try expectEqual(@as(u64, 0), nextDeadline(&r, std.math.maxInt(u64) - 100));
+ try expectEqual(@as(u64, 3000000), remainingWait(140000000, 137000000, 10000000, 137000000));
+ try expectEqual(@as(u64, 1), remainingWait(140000000, 137000000, 10000000, 139999999));
+ try expectEqual(@as(u64, 0), remainingWait(140000000, 137000000, 10000000, 140000000));
+ try expectEqual(@as(u64, 0), remainingWait(140000000, 137000000, 10000000, 136000000));
+ try expectEqual(@as(u64, 0), remainingWait(std.math.maxInt(u64), 137000000, 10000000, 138000000));
+}
+
+test "presentation reached deadlines survive sampling but refresh changes invalidate them" {
+ const self = try std.testing.allocator.create(Presentation);
+ defer self.deinit(std.testing.allocator);
+ self.* = .{ .have_clock = true, .completed = 1, .last_submit_ns = 137000000, .submit_period_ns = 10000000, .next_submit_ns = 140000000 };
+ self.records[0] = .{ .presented_ns = 100000000, .refresh_ns = 10000000, .flags = 1, .result = .presented };
+ try std.testing.expectEqual(@as(u64, 2000000), self.waitAt(138000000));
+ try std.testing.expectEqual(@as(u64, 0), self.waitAt(140000000));
+ try std.testing.expectEqual(@as(u64, 140000000), self.next_submit_ns);
+ self.records[0].refresh_ns = 20000000;
+ try std.testing.expectEqual(@as(u64, 0), self.waitAt(138000000));
+ try std.testing.expectEqual(@as(u64, 0), self.next_submit_ns);
+ self.have_clock = false;
+ try std.testing.expectEqual(@as(u64, 0), self.waitNs());
+ try std.testing.expectEqual(@as(u64, 99), self.sampleNs(99));
+}
+
+test "presentation scheduled sample converts clocks without overflow or stale adjustment" {
+ const expectEqual = std.testing.expectEqual;
+ try expectEqual(@as(u64, 998000000), scheduledSample(140000000, 10000000, 142000000, 1000000000));
+ try expectEqual(@as(u64, 995000000), scheduledSample(140000000, 10000000, 145000000, 1000000000));
+ try expectEqual(@as(u64, 1000000000), scheduledSample(140000000, 10000000, 145000001, 1000000000));
+ try expectEqual(@as(u64, 1000000000), scheduledSample(140000000, 10000000, 139999999, 1000000000));
+ try expectEqual(@as(u64, 1), scheduledSample(140000000, 10000000, 142000000, 1));
+ try expectEqual(std.math.maxInt(u64) - 1, scheduledSample(std.math.maxInt(u64) - 1, 10000000, std.math.maxInt(u64), std.math.maxInt(u64)));
+ try expectEqual(@as(u64, 99), scheduledSample(0, 10000000, 1, 99));
+ try expectEqual(@as(u64, 99), scheduledSample(140000000, 0, 142000000, 99));
+}
+
+test "presentation feedback callbacks retain 64-bit clocks and sequences, ring CSV stays chronological" {
+ if (!linux) return error.SkipZigTest;
+ const self = try std.testing.allocator.create(Presentation);
+ defer self.deinit(std.testing.allocator);
+ self.* = .{ .status = "ready" };
+ var pending: Wayland.Pending = .{ .owner = self, .record = .{ .frame = 7, .sample_ms = 9, .commit_ns = 11 } };
+ Wayland.presented(&pending, null, 1, 2, 3, 16666666, 4, 5, 7);
+ try std.testing.expectEqual(@as(u64, 1), self.completed);
+ try std.testing.expectEqual((((@as(u64, 1) << 32) + 2) * std.time.ns_per_s) + 3, self.records[0].presented_ns);
+ try std.testing.expectEqual((@as(u64, 4) << 32) + 5, self.records[0].sequence);
+ try std.testing.expectEqual(@as(u32, 7), self.records[0].flags);
+ pending.record = .{ .frame = 8 };
+ Wayland.discarded(&pending, null);
+ try std.testing.expectEqual(.discarded, self.records[1].result);
+ try std.testing.expectEqual(@as(u64, 0), self.records[1].presented_ns);
+ try std.testing.expectEqual(@as(u64, 7), self.latest().?.frame);
+ for (2..capacity + 3) |i| {
+ pending.record = .{ .frame = i };
+ Wayland.finish(&pending, .presented);
+ }
+ var out: std.Io.Writer.Allocating = .init(std.testing.allocator);
+ defer out.deinit();
+ try csv(self, &out.writer);
+ try std.testing.expect(std.mem.indexOf(u8, out.written(), "\n3,0,0,presented,0,0,0,0\n") != null);
+ try std.testing.expect(std.mem.indexOf(u8, out.written(), "\n2,0,0,presented,0,0,0,0\n") == null);
+ try std.testing.expect(std.mem.indexOfScalar(u8, out.written(), 0) == null);
+ var small: [9]u8 = undefined;
+ var writer: std.Io.Writer = .fixed(&small);
+ try std.testing.expectError(error.WriteFailed, csv(self, &writer));
+}
+
+test "presentation disabled CSV is explicit and has a valid header" {
+ var out: std.Io.Writer.Allocating = .init(std.testing.allocator);
+ defer out.deinit();
+ try csv(null, &out.writer);
+ try std.testing.expect(std.mem.startsWith(u8, out.written(), "# status disabled_or_allocation_failed\n"));
+ try std.testing.expect(std.mem.indexOf(u8, out.written(), "frame_id,sample_ms,commit_ns,result,presented_ns,refresh_ns,sequence,flags\n") != null);
+}
+
+test "presentation runtime declarations compile for the target backend" {
+ std.testing.refAllDecls(Presentation);
+}
diff --git a/src/host/Timing.zig b/src/host/Timing.zig
new file mode 100644
index 0000000..1e5d991
--- /dev/null
+++ b/src/host/Timing.zig
@@ -0,0 +1,169 @@
+//! Wall-clock frame history, independent of the sketch's replay clock.
+const Timing = @This();
+const std = @import("std");
+
+pub const capacity = 240;
+pub const frames_per_column = 8;
+pub const Metric = enum { frame, work };
+pub const Sample = struct { frame: u64 = 0, work: u64 = 0 };
+pub const Stats = struct {
+ mean: f64 = 0,
+ p90: f64 = 0,
+ p99: f64 = 0,
+ max: f64 = 0,
+};
+
+visible: bool = false,
+metric: Metric = .frame,
+samples: [capacity]Sample = @splat(.{}),
+count: usize = 0,
+next: usize = 0,
+dirty: bool = true,
+cached: [2]Stats = @splat(.{}),
+labels: [4][96]u8 = undefined,
+label_lengths: [4]usize = @splat(0),
+label_elapsed: u64 = 0,
+ceiling: f64 = 1.25,
+graph: [capacity]Sample = @splat(.{}),
+graph_count: usize = 0,
+graph_next: usize = 0,
+group_count: usize = 0,
+group_peak: Sample = .{},
+
+pub fn add(self: *Timing, sample: Sample) void {
+ self.samples[self.next] = sample;
+ self.next = (self.next + 1) % capacity;
+ self.count = @min(self.count + 1, capacity);
+ self.label_elapsed +|= sample.frame;
+ // Refresh text at most four times a second; collection never allocates or sorts.
+ if (self.label_elapsed >= 250 * std.time.ns_per_ms) {
+ self.dirty = true;
+ self.label_elapsed = 0;
+ }
+ self.group_peak.frame = @max(self.group_peak.frame, sample.frame);
+ self.group_peak.work = @max(self.group_peak.work, sample.work);
+ self.group_count += 1;
+ if (self.group_count == frames_per_column) {
+ self.graph[self.graph_next] = self.group_peak;
+ self.graph_next = (self.graph_next + 1) % capacity;
+ self.graph_count = @min(self.graph_count + 1, capacity);
+ self.group_count = 0;
+ self.group_peak = .{};
+ }
+}
+
+pub fn graphAt(self: *const Timing, index: usize) Sample {
+ std.debug.assert(index < self.graph_count);
+ return self.graph[(self.graph_next + capacity - self.graph_count + index) % capacity];
+}
+
+pub fn label(self: *const Timing, index: usize) []const u8 {
+ return self.labels[index][0..self.label_lengths[index]];
+}
+
+pub fn setLabel(self: *Timing, index: usize, comptime fmt: []const u8, args: anytype) void {
+ const text = std.mem.print(&self.labels[index], fmt, args) catch unreachable;
+ self.label_lengths[index] = text.len;
+}
+
+pub fn sampleAt(self: *const Timing, index: usize) Sample {
+ std.debug.assert(index < self.count);
+ return self.samples[(self.next + capacity - self.count + index) % capacity];
+}
+
+pub fn value(sample: Sample, metric: Metric) u64 {
+ return switch (metric) {
+ .frame => sample.frame,
+ .work => sample.work,
+ };
+}
+
+pub fn ms(ns: u64) f64 {
+ return @as(f64, @floatFromInt(ns)) / std.time.ns_per_ms;
+}
+
+pub fn stats(self: *const Timing, metric: Metric) Stats {
+ if (self.count == 0) return .{};
+ var sorted: [capacity]u64 = undefined;
+ var total: f64 = 0;
+ for (sorted[0..self.count], 0..) |*v, i| {
+ v.* = value(self.sampleAt(i), metric);
+ total += ms(v.*);
+ }
+ const values = sorted[0..self.count];
+ std.mem.sort(u64, values, {}, std.sort.asc(u64));
+ return .{
+ .mean = total / @as(f64, @floatFromInt(values.len)),
+ .p90 = ms(values[(values.len * 90 + 99) / 100 - 1]),
+ .p99 = ms(values[(values.len * 99 + 99) / 100 - 1]),
+ .max = ms(values[values.len - 1]),
+ };
+}
+
+pub fn command(self: *Timing, arg: ?[]const u8) !void {
+ if (arg) |name| {
+ if (std.mem.eql(u8, name, "on")) {
+ self.visible = true;
+ } else if (std.mem.eql(u8, name, "off")) {
+ self.visible = false;
+ } else if (std.mem.eql(u8, name, "reset")) {
+ self.* = .{ .visible = self.visible, .metric = self.metric };
+ } else if (std.meta.stringToEnum(Metric, name)) |metric| {
+ self.metric = metric;
+ self.visible = true;
+ } else return error.ExpectedTimingOnOffFrameWorkResetStats;
+ } else self.visible = !self.visible;
+ self.dirty = true;
+}
+
+test "timing history percentiles, wrap, reset and commands" {
+ var t: Timing = .{};
+ try std.testing.expectEqual(@as(f64, 0), t.stats(.frame).p99);
+ t.add(.{ .frame = 1000000, .work = 500000 });
+ try std.testing.expectEqual(@as(f64, 0.5), t.stats(.work).p90);
+ try t.command("reset");
+ for (1..401) |i| t.add(.{ .frame = i * 1000000, .work = i * 1000 });
+ try std.testing.expectEqual(capacity, t.count);
+ try std.testing.expectEqual(@as(u64, 161000000), t.sampleAt(0).frame);
+ const s = t.stats(.frame);
+ try std.testing.expectEqual(@as(f64, 280.5), s.mean);
+ try std.testing.expectEqual(@as(f64, 376), s.p90);
+ try std.testing.expectEqual(@as(f64, 398), s.p99);
+ try std.testing.expectEqual(@as(f64, 400), s.max);
+ try t.command("work");
+ try t.command("reset");
+ try std.testing.expect(t.visible and t.metric == .work and t.count == 0);
+ try t.command(null);
+ try std.testing.expect(!t.visible);
+ try t.command("on");
+ try std.testing.expect(t.visible);
+ try t.command("off");
+ try std.testing.expect(!t.visible);
+ try std.testing.expectError(error.ExpectedTimingOnOffFrameWorkResetStats, t.command("bogus"));
+}
+
+test "timing graph keeps peaks while scrolling eight times slower" {
+ var t: Timing = .{};
+ for (0..7) |_| t.add(.{ .frame = 10, .work = 1 });
+ try std.testing.expectEqual(@as(usize, 0), t.graph_count);
+ t.add(.{ .frame = 100, .work = 5 });
+ try std.testing.expectEqual(@as(usize, 1), t.graph_count);
+ try std.testing.expectEqual(Sample{ .frame = 100, .work = 5 }, t.graphAt(0));
+ for (0..capacity * frames_per_column) |_| t.add(.{ .frame = 20, .work = 2 });
+ try std.testing.expectEqual(capacity, t.graph_count);
+ try std.testing.expectEqual(Sample{ .frame = 20, .work = 2 }, t.graphAt(0));
+ try t.command("reset");
+ try std.testing.expectEqual(@as(usize, 0), t.graph_count);
+ try std.testing.expectEqual(@as(usize, 0), t.group_count);
+}
+
+test "timing readouts refresh quarterly and use fixed text storage" {
+ var t: Timing = .{};
+ t.dirty = false;
+ for (0..24) |_| t.add(.{ .frame = 10 * std.time.ns_per_ms });
+ try std.testing.expect(!t.dirty);
+ t.add(.{ .frame = 10 * std.time.ns_per_ms });
+ try std.testing.expect(t.dirty);
+ t.setLabel(0, "p99 {d:.3}", .{@as(f64, 0.123)});
+ try std.testing.expectEqualStrings("p99 0.123", t.label(0));
+}
diff --git a/src/host/TimingAtlas.zig b/src/host/TimingAtlas.zig
new file mode 100644
index 0000000..bde8a0a
--- /dev/null
+++ b/src/host/TimingAtlas.zig
@@ -0,0 +1,138 @@
+//! One immutable texture for the timing overlay's printable ASCII glyphs.
+const Atlas = @This();
+const std = @import("std");
+const abi = @import("abi");
+const gfx = @import("gfx.zig");
+const c = @import("c");
+
+image: abi.Image = .none,
+advance: f32 = 0,
+cell_width: f32 = 0,
+cell_height: f32 = 0,
+
+const padding = 1;
+const glyphs = blk: {
+ var bytes: [95]u8 = undefined;
+ for (&bytes, 0..) |*byte, i| byte.* = @intCast(i + 32);
+ break :blk bytes;
+};
+
+/// Called once with Painter on its canvas. Images owns the texture until shutdown.
+pub fn init(images: *gfx.Images, painter: *gfx.Painter) !Atlas {
+ const size = gfx.textSize(images.renderer, 1, "0", .mono);
+ var atlas: Atlas = .{
+ .advance = size[0],
+ .cell_width = @ceil(size[0]) + padding * 2,
+ .cell_height = @ceil(size[1]) + padding * 2,
+ };
+ atlas.image = images.new(@intFromFloat(atlas.cell_width * glyphs.len), @intFromFloat(atlas.cell_height));
+ errdefer images.free(atlas.image);
+ const entry = images.get(atlas.image) orelse return error.TimingAtlasCreationFailed;
+ if (entry.texture == null) return error.TimingAtlasCreationFailed;
+ // The atlas stores the native scale-one raster; do not supersample this cache.
+ const smooth = painter.smooth;
+ painter.smooth = false;
+ defer painter.smooth = smooth;
+ painter.draw(.{ .target = atlas.image });
+ painter.draw(.{ .clear = .{ .r = 0, .g = 0, .b = 0, .a = 0 } });
+ for (glyphs, 0..) |_, i| painter.draw(.{ .text = .{
+ .x = @as(f32, @floatFromInt(i)) * atlas.cell_width + padding,
+ .y = padding,
+ .scale = 1,
+ .raster = 1,
+ .color = .white,
+ .bytes = glyphs[i..][0..1],
+ } });
+ // The unused space cell also supplies an opaque texel for bars/backgrounds.
+ painter.draw(.{ .rect = .{ .dst = .{ .x = 0, .y = 0, .w = 1, .h = 1 }, .color = .white } });
+ painter.draw(.{ .target = .none });
+ return atlas;
+}
+
+fn source(atlas: Atlas, byte: u8) abi.Rect {
+ const printable = if (byte >= 32 and byte <= 126) byte else '?';
+ return .{ .x = @as(f32, @floatFromInt(printable - 32)) * atlas.cell_width, .y = 0, .w = atlas.cell_width, .h = atlas.cell_height };
+}
+
+/// The complete overlay fits one fixed vertex/index batch and one SDL draw call.
+pub const Batch = struct {
+ const capacity = 4 * 96 + 48 + @import("Timing.zig").capacity + 2;
+ atlas: Atlas,
+ vertices: [capacity * 4]c.SDL_Vertex = undefined,
+ indices: [capacity * 6]u16 = undefined,
+ count: usize = 0,
+
+ pub fn rect(batch: *Batch, dst: abi.Rect, color: abi.Color) !void {
+ try batch.quad(dst, .{ .x = 0.5, .y = 0.5, .w = 0, .h = 0 }, color);
+ }
+
+ pub fn text(batch: *Batch, bytes: []const u8, x: f32, y: f32, scale: f32, color: abi.Color) !void {
+ const atlas = batch.atlas;
+ for (bytes, 0..) |byte, i| {
+ if (byte == ' ') continue;
+ try batch.quad(.{
+ .x = x + (@as(f32, @floatFromInt(i)) * atlas.advance - padding) * scale,
+ .y = y - padding * scale,
+ .w = atlas.cell_width * scale,
+ .h = atlas.cell_height * scale,
+ }, atlas.source(byte), color);
+ }
+ }
+
+ fn quad(batch: *Batch, dst: abi.Rect, src: abi.Rect, color: abi.Color) !void {
+ if (batch.count == capacity) return error.TimingBatchFull;
+ const width = batch.atlas.cell_width * glyphs.len;
+ const height = batch.atlas.cell_height;
+ const alpha = @as(f32, @floatFromInt(color.a)) / 255;
+ const tint: c.SDL_FColor = .{
+ .r = @as(f32, @floatFromInt(color.r)) / 255 * alpha,
+ .g = @as(f32, @floatFromInt(color.g)) / 255 * alpha,
+ .b = @as(f32, @floatFromInt(color.b)) / 255 * alpha,
+ .a = alpha,
+ };
+ const base = batch.count * 4;
+ const corners = [4][2]f32{ .{ 0, 0 }, .{ 1, 0 }, .{ 1, 1 }, .{ 0, 1 } };
+ for (corners, 0..) |corner, i| batch.vertices[base + i] = .{
+ .position = .{ .x = dst.x + corner[0] * dst.w, .y = dst.y + corner[1] * dst.h },
+ .color = tint,
+ .tex_coord = .{ .x = (src.x + corner[0] * src.w) / width, .y = (src.y + corner[1] * src.h) / height },
+ };
+ for ([_]u16{ 0, 1, 2, 0, 2, 3 }, 0..) |index, i| batch.indices[batch.count * 6 + i] = @as(u16, @intCast(base)) + index;
+ batch.count += 1;
+ }
+
+ pub fn draw(batch: *const Batch, painter: *gfx.Painter) void {
+ painter.texturedTriangles(batch.atlas.image, batch.vertices[0 .. batch.count * 4], batch.indices[0 .. batch.count * 6]);
+ }
+};
+
+test "timing atlas ASCII cells and scaled glyph positions share one image" {
+ const atlas: Atlas = .{ .image = @fromBackingInt(7), .advance = 7.5, .cell_width = 10, .cell_height = 16 };
+ try std.testing.expectEqual(@as(f32, 0), atlas.source(' ').x);
+ try std.testing.expectEqual(@as(f32, 940), atlas.source('~').x);
+ try std.testing.expectEqual(atlas.source('?'), atlas.source(0xff));
+ var batch: Batch = .{ .atlas = atlas };
+ try batch.text("1 2", 10, 20, 0.5, .white);
+ try std.testing.expectEqual(@as(usize, 2), batch.count);
+ try std.testing.expectEqual(@as(f32, 9.5), batch.vertices[0].position.x);
+ try std.testing.expectEqual(@as(f32, 19.5), batch.vertices[0].position.y);
+ try std.testing.expectEqual(@as(f32, 14.5), batch.vertices[2].position.x);
+ try std.testing.expectEqual(@as(f32, 27.5), batch.vertices[2].position.y);
+ try std.testing.expectEqual(@as(f32, 17), batch.vertices[4].position.x);
+ try std.testing.expectEqual(@as(f32, 170.0 / 950.0), batch.vertices[0].tex_coord.x);
+ try std.testing.expectEqual(@as(f32, 180.0 / 950.0), batch.vertices[4].tex_coord.x);
+ try std.testing.expectEqualSlices(u16, &.{ 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7 }, batch.indices[0..12]);
+}
+
+test "timing batch is bounded and solid quads sample one opaque atlas texel" {
+ var batch: Batch = .{ .atlas = .{ .image = @fromBackingInt(1), .advance = 8, .cell_width = 10, .cell_height = 16 } };
+ const box: abi.Rect = .{ .x = 10, .y = 20, .w = 5, .h = 8 };
+ for (0..Batch.capacity) |_| try batch.rect(box, .{ .r = 255, .g = 128, .b = 0, .a = 128 });
+ try std.testing.expectError(error.TimingBatchFull, batch.rect(box, .white));
+ for (batch.indices) |index| try std.testing.expect(index < batch.vertices.len);
+ for (batch.vertices[0..4]) |vertex| {
+ try std.testing.expectEqual(batch.vertices[0].tex_coord, vertex.tex_coord);
+ try std.testing.expectApproxEqAbs(@as(f32, 128.0 / 255.0), vertex.color.r, 0.00001);
+ try std.testing.expectApproxEqAbs(@as(f32, 128.0 / 255.0), vertex.color.a, 0.00001);
+ }
+}
diff --git a/src/host/control.zig b/src/host/control.zig
index 58b41b3..8cc8296 100644
--- a/src/host/control.zig
+++ b/src/host/control.zig
@@ -3,6 +3,7 @@ const std = @import("std");
const c9 = @import("cloud9");
const c = @import("c");
const Host = @import("Host.zig");
+const Presentation = @import("Presentation.zig");
const fs = c9.fs;
const transport = c9.transport;
const Backend = struct {
@@ -11,7 +12,7 @@ const Backend = struct {
};
const Server = fs.Server(Backend, .{ .fid_capacity = 32, .slot_capacity = 4 });
const msize = 16384;
-const names = [_][]const u8{ "/", "ctl", "status", "log", "screen.png", "profile", "profile-trace" };
+const names = [_][]const u8{ "/", "ctl", "status", "log", "screen.png", "profile", "profile-trace", "timing-trace", "presentation-trace" };
const Connection = struct {
fd: c_int = -1,
@@ -139,14 +140,20 @@ pub const Control = struct {
},
.getattr => reply.attr = self.attr(req.node),
.open => {
- if (req.node == 5 or req.node == 7) {
+ if (req.node == 5 or req.node == 7 or req.node == 8 or req.node == 9) {
if (req.node == 5) {
if (self.capture_pending) return error.CapturePending;
if (self.capture_error) |err| return err;
if (self.png.len == 0) return error.CaptureScreenshotFirst;
}
for (&conn.snapshots, 1..) |*slot, handle| if (slot.* == null) {
- slot.* = if (req.node == 5) try self.allocator.dupe(u8, self.png) else try self.trace(host);
+ slot.* = switch (req.node) {
+ 5 => try self.allocator.dupe(u8, self.png),
+ 7 => try self.trace(host),
+ 8 => try self.timingTrace(host),
+ 9 => try self.presentationTrace(host),
+ else => unreachable,
+ };
reply.handle = @intCast(handle);
return &.{};
};
@@ -186,7 +193,7 @@ pub const Control = struct {
}
break :blk writer.buffered();
},
- 5, 7 => if (req.handle > 0 and req.handle <= conn.snapshots.len) conn.snapshots[req.handle - 1] orelse return error.InvalidHandle else return error.InvalidHandle,
+ 5, 7, 8, 9 => if (req.handle > 0 and req.handle <= conn.snapshots.len) conn.snapshots[req.handle - 1] orelse return error.InvalidHandle else return error.InvalidHandle,
6 => blk: {
const gpu = if (host.passes) |*gpu| gpu else return error.ProfilingDisabled;
const profile = if (gpu.profile) |*profile| profile else return error.ProfilingDisabled;
@@ -252,6 +259,25 @@ pub const Control = struct {
return self.allocator.dupe(u8, writer.buffered());
}
+ fn timingTrace(self: *Control, host: *const Host) ![]u8 {
+ var csv: std.ArrayList(u8) = .empty;
+ errdefer csv.deinit(self.allocator);
+ try csv.appendSlice(self.allocator, "index,frame_ns,work_ns,outside_work_ns\n");
+ for (0..host.timing.count) |i| {
+ const sample = host.timing.sampleAt(i);
+ try csv.print(self.allocator, "{d},{d},{d},{d}\n", .{ i, sample.frame, sample.work, sample.frame -| sample.work });
+ }
+ return csv.toOwnedSlice(self.allocator);
+ }
+
+ fn presentationTrace(self: *Control, host: *const Host) ![]u8 {
+ var csv: std.Io.Writer.Allocating = .init(self.allocator);
+ defer csv.deinit();
+ try Presentation.csv(host.presentation, &csv.writer);
+ if (csv.written().len > 2 << 20) return error.TraceTooLarge;
+ return csv.toOwnedSlice();
+ }
+
fn attr(self: *Control, node: u64) fs.Attr {
return .{ .name = names[@intCast(node - 1)], .node = node, .dir = node == 1, .mode = if (node == 1) 0o700 else if (node == 2) 0o600 else 0o400, .size = if (node == 5) self.png.len else 0, .version = if (node == 5) @truncate(self.generation) else 0 };
}
@@ -366,3 +392,63 @@ test "control writes profiling ring retains latest samples and nearest rank perc
entry.add(20);
try std.testing.expectEqual([2]u64{ 20, 20 }, entry.percentiles());
}
+
+test "control writes reject timing trace mutations and opens pin chronological samples" {
+ const a = std.testing.allocator;
+ var control: Control = .{ .allocator = a, .path = undefined, .listener = -1 };
+ var host: Host = undefined;
+ host.timing = .{};
+ for (0..@import("Timing.zig").capacity + 2) |i| host.timing.add(.{ .frame = i + 1, .work = i });
+ var conn: Connection = .{};
+ var reply: fs.Reply = .{ .tag = 1 };
+ var buf: [256]u8 = undefined;
+ _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .lookup, .node = 1, .data = "timing-trace" }, &reply, &buf);
+ try std.testing.expectEqual(@as(u64, 8), reply.attr.node);
+ try std.testing.expectEqual(@as(u16, 0o400), reply.attr.mode);
+ try std.testing.expectError(error.ReadOnly, control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 8, .data = "reset" }, &reply, &buf));
+ _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 8 }, &reply, &buf);
+ const first = reply.handle;
+ host.timing = .{};
+ host.timing.add(.{ .frame = 4, .work = 7 });
+ const original = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 8, .handle = first, .size = 100 }, &reply, &buf);
+ try std.testing.expect(std.mem.startsWith(u8, original, "index,frame_ns,work_ns,outside_work_ns\n0,3,2,1\n1,4,3,1\n"));
+ _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 8 }, &reply, &buf);
+ const second = reply.handle;
+ const latest = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 8, .handle = second, .size = 100 }, &reply, &buf);
+ try std.testing.expectEqualStrings("index,frame_ns,work_ns,outside_work_ns\n0,4,7,0\n", latest);
+ for ([_]u32{ first, second }) |handle| {
+ _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = 8, .handle = handle, .opened = true }, &reply, &buf);
+ try std.testing.expect(conn.snapshots[handle - 1] == null);
+ }
+}
+
+test "control writes reject presentation trace mutations and opens own independent snapshots" {
+ const a = std.testing.allocator;
+ var control: Control = .{ .allocator = a, .path = undefined, .listener = -1 };
+ var host: Host = undefined;
+ host.presentation = null;
+ var conn: Connection = .{};
+ var reply: fs.Reply = .{ .tag = 1 };
+ var buf: [512]u8 = undefined;
+ _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .lookup, .node = 1, .data = "presentation-trace" }, &reply, &buf);
+ try std.testing.expectEqual(@as(u64, 9), reply.attr.node);
+ try std.testing.expectEqual(@as(u16, 0o400), reply.attr.mode);
+ try std.testing.expectError(error.ReadOnly, control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 9, .data = "reset" }, &reply, &buf));
+ _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 9 }, &reply, &buf);
+ const first = reply.handle;
+ _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 9 }, &reply, &buf);
+ const second = reply.handle;
+ try std.testing.expect(conn.snapshots[first - 1].?.ptr != conn.snapshots[second - 1].?.ptr);
+ const original = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 9, .handle = first, .size = 4096 }, &reply, &buf);
+ try std.testing.expect(std.mem.startsWith(u8, original, "# status "));
+ try std.testing.expect(std.mem.indexOf(u8, original, "disabled_or_allocation_failed") != null);
+ try std.testing.expect(std.mem.endsWith(u8, original, "frame_id,sample_ms,commit_ns,result,presented_ns,refresh_ns,sequence,flags\n"));
+ try std.testing.expect(std.mem.indexOfScalar(u8, original, 0) == null);
+ const expected = try a.dupe(u8, original);
+ defer a.free(expected);
+ _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = 9, .handle = first, .opened = true }, &reply, &buf);
+ const retained = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 9, .handle = second, .size = 4096 }, &reply, &buf);
+ try std.testing.expectEqualStrings(expected, retained);
+ _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = 9, .handle = second, .opened = true }, &reply, &buf);
+ try std.testing.expect(conn.snapshots[first - 1] == null and conn.snapshots[second - 1] == null);
+}
diff --git a/src/host/gfx.zig b/src/host/gfx.zig
index fef58c3..94e154f 100644
--- a/src/host/gfx.zig
+++ b/src/host/gfx.zig
@@ -434,6 +434,19 @@ pub const Painter = struct {
} else _ = c.SDL_RenderTexture(renderer, t, srcp, &frect(dst));
}
+ /// One atlas batch; vertex colors are premultiplied when the image is.
+ pub fn texturedTriangles(p: *Painter, image: abi.Image, vertices: []const c.SDL_Vertex, indices: []const u16) void {
+ if (vertices.len == 0 or indices.len == 0 or vertices.len > std.math.maxInt(c_int) or indices.len > std.math.maxInt(c_int)) return;
+ const entry = p.images.get(image) orelse return;
+ const texture = entry.texture orelse return;
+ if (image == p.target) return;
+ p.flush();
+ if (entry.stale) p.resolve(entry);
+ _ = c.SDL_SetTextureBlendMode(texture, textureBlend(p.blend, entry.premultiplied));
+ const stride = @sizeOf(c.SDL_Vertex);
+ _ = c.SDL_RenderGeometryRaw(p.renderer, texture, @ptrCast(&vertices[0].position), stride, &vertices[0].color, stride, @ptrCast(&vertices[0].tex_coord), stride, @intCast(vertices.len), indices.ptr, @intCast(indices.len), @sizeOf(u16));
+ }
+
/// `Command.shape`: its triangles in one geometry call, one colour for
/// every vertex (stride 0, nothing copied) or each subpath's. The
/// subpaths are for the web; native needs only the triangles.
diff --git a/src/host/overlay.zig b/src/host/overlay.zig
index 5219a83..e1fc45d 100644
--- a/src/host/overlay.zig
+++ b/src/host/overlay.zig
@@ -4,10 +4,58 @@ const std = @import("std");
const abi = @import("abi");
const memory = @import("memory.zig");
const fields = @import("fields.zig");
+const Timing = @import("Timing.zig");
+const gfx = @import("gfx.zig");
+pub const TimingAtlas = @import("TimingAtlas.zig");
const List = std.ArrayList(abi.Command);
const shown_bytes = 0x100;
+pub fn drawTiming(painter: *gfx.Painter, timing: *Timing, canvas: [2]u32, atlas: TimingAtlas) !void {
+ var batch: TimingAtlas.Batch = .{ .atlas = atlas };
+ const reference: f64 = if (timing.metric == .frame) 1000.0 / 60.0 else 1;
+ var ceiling = reference * 1.25;
+ for (0..timing.graph_count) |i| ceiling = @max(ceiling, Timing.ms(Timing.value(timing.graphAt(i), timing.metric)) * 1.1);
+ if (timing.dirty or ceiling != timing.ceiling) {
+ timing.ceiling = ceiling;
+ timing.setLabel(3, "8 frames/peak / 0..{d:.2} ms / line {d:.2}", .{ ceiling, reference });
+ }
+ if (timing.dirty) {
+ timing.cached = .{ timing.stats(.frame), timing.stats(.work) };
+ timing.setLabel(0, "TIMING / {t} / stats: {d} frames / ms", .{ timing.metric, timing.count });
+ for (timing.cached, 0..) |s, i| timing.setLabel(i + 1, "{s} avg {d:.3} p90 {d:.3} p99 {d:.3}", .{ if (i == 0) "Frame" else "Work ", s.mean, s.p90, s.p99 });
+ timing.dirty = false;
+ }
+ const width = @min(@as(f32, @floatFromInt(canvas[0])), 480);
+ const scale = width / 480;
+ const x = @as(f32, @floatFromInt(canvas[0])) - width;
+ const green: abi.Color = .{ .r = 105, .g = 245, .b = 160 };
+ const muted: abi.Color = .{ .r = 165, .g = 180, .b = 195 };
+ try batch.rect(.{ .x = x, .y = 0, .w = width, .h = 200 * scale }, .{ .r = 20, .g = 25, .b = 32 });
+ for (0..4) |i| {
+ const y: f32 = switch (i) {
+ 0 => 8,
+ 1 => 30,
+ 2 => 48,
+ else => 70,
+ };
+ try batch.text(timing.label(i), x + 12 * scale, y * scale, scale, if (i == 0) green else if (i == 3) muted else .white);
+ }
+ const left = x + 12 * scale;
+ const bottom = 170 * scale;
+ const height = 78 * scale;
+ const step = 456 * scale / Timing.capacity;
+ const line_y = bottom - height * @as(f32, @floatCast(reference / ceiling));
+ try batch.rect(.{ .x = left, .y = line_y, .w = 456 * scale, .h = 1 }, muted);
+ for (0..timing.graph_count) |i| {
+ const value = Timing.ms(Timing.value(timing.graphAt(i), timing.metric));
+ const h = @max(1, height * @as(f32, @floatCast(value / ceiling)));
+ try batch.rect(.{ .x = left + @as(f32, @floatFromInt(Timing.capacity - timing.graph_count + i)) * step, .y = bottom - h, .w = step, .h = h }, green);
+ }
+ try batch.text("Frame includes present / Work stops before it", left, 180 * scale, scale, muted);
+ batch.draw(painter);
+}
+
/// Each field hashes its path into a dark shade; bytes it owns wear the same
/// shade in the hex view below, and padding stays gray.
fn shade(path: []const u8) abi.Color {
diff --git a/src/host/root.zig b/src/host/root.zig
index c9cdde6..158f894 100644
--- a/src/host/root.zig
+++ b/src/host/root.zig
@@ -6,6 +6,7 @@
//! --headless offscreen video, silent audio
//! --script FILE play a script instead of reading devices
//! --fresh start from default state: no snapshots or recordings
+//! --timing-marker encode frame ID and draw sample time for video analysis
//! --profile-gpu time each GPU command alone, print the times at exit
//! --console LINE run a console line once the sketch is loaded (repeatable)
//! --define NAME=VALUE substitute {NAME} in the script
@@ -45,6 +46,8 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void {
options.fresh = true;
} else if (std.mem.eql(u8, arg, "--headless")) {
options.headless = true;
+ } else if (std.mem.eql(u8, arg, "--timing-marker")) {
+ options.timing_marker = true;
} else if (std.mem.eql(u8, arg, "--profile-gpu")) {
options.profile_gpu = true;
} else if (std.mem.eql(u8, arg, "--console")) {
@@ -128,6 +131,7 @@ const usage =
\\ --headless offscreen video, silent audio, no vsync
\\ --script FILE play a script instead of reading devices
\\ --fresh start from default state: no snapshots or recordings
+ \\ --timing-marker encode frame ID and draw sample time for video analysis
\\ --profile-gpu time each GPU command alone, print the times at exit
\\ --console LINE run a console line once the sketch is loaded (repeatable)
\\ --define NAME=VALUE substitute {NAME} in the script
@@ -201,4 +205,5 @@ test {
_ = @import("audio.zig");
_ = @import("Console.zig");
_ = @import("control.zig");
+ _ = @import("timing_marker.zig");
}
diff --git a/src/host/timeline.zig b/src/host/timeline.zig
index 8a5448a..b52c74d 100644
--- a/src/host/timeline.zig
+++ b/src/host/timeline.zig
@@ -295,6 +295,7 @@ test "frames are whole: input waits for its tick, live and in playback" {
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());
}
const r = t.bank.recording(0);
r.events[r.count] = .{ .kind = .mouse_move, .time = 40_000_000 };
@@ -313,6 +314,7 @@ test "frames are whole: input waits for its tick, live and in playback" {
var it = frames(events);
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());
delivered += 1;
}
}
diff --git a/src/host/timing_marker.zig b/src/host/timing_marker.zig
new file mode 100644
index 0000000..2d641c9
--- /dev/null
+++ b/src/host/timing_marker.zig
@@ -0,0 +1,45 @@
+//! Opt-in video marker: submitted frame ID and draw sample time, LSB-first.
+const std = @import("std");
+const abi = @import("abi");
+
+pub fn draw(out: *std.ArrayList(abi.Command), arena: std.mem.Allocator, canvas: [2]u32, frame: u64, now: u64) !void {
+ if (canvas[0] < 320 or canvas[1] < 8) return;
+ const y: f32 = @floatFromInt(canvas[1] - 8);
+ const milliseconds: u32 = @truncate(now / std.time.ns_per_ms);
+ const bits: u80 = 0xD3A7 | (@as(u80, @as(u32, @truncate(frame))) << 16) | (@as(u80, milliseconds) << 48);
+ try out.append(arena, .{ .clip = null });
+ try out.append(arena, .{ .rect = .{ .dst = .{ .x = 0, .y = y, .w = 320, .h = 8 }, .color = .black } });
+ for (0..80) |i| {
+ if ((bits >> @intCast(i)) & 1 == 0) continue;
+ try out.append(arena, .{ .rect = .{ .dst = .{ .x = @floatFromInt(i * 4), .y = y, .w = 4, .h = 8 }, .color = .white } });
+ }
+}
+
+test "timing marker encodes LSB-first fields, wraps counters and fits the canvas" {
+ const a = std.testing.allocator;
+ var commands: std.ArrayList(abi.Command) = .empty;
+ defer commands.deinit(a);
+ try draw(&commands, a, .{ 960, 600 }, 0x1_0000_1234, 0x1_0000_5678 * std.time.ns_per_ms + 999999);
+ try std.testing.expect(commands.items[0] == .clip and commands.items[0].clip == null);
+ const background = commands.items[1].rect;
+ try std.testing.expectEqual(abi.Rect{ .x = 0, .y = 592, .w = 320, .h = 8 }, background.dst);
+ try std.testing.expectEqual(abi.Color.black, background.color);
+ var decoded: u80 = 0;
+ for (commands.items[2..]) |command| {
+ const rect = command.rect;
+ try std.testing.expectEqual(abi.Color.white, rect.color);
+ try std.testing.expectEqual(@as(f32, 592), rect.dst.y);
+ try std.testing.expectEqual(@as(f32, 4), rect.dst.w);
+ try std.testing.expectEqual(@as(f32, 8), rect.dst.h);
+ try std.testing.expect(rect.dst.x >= 0 and rect.dst.x < 320 and @mod(rect.dst.x, 4) == 0);
+ const bit: u7 = @intFromFloat(rect.dst.x / 4);
+ decoded |= @as(u80, 1) << bit;
+ }
+ try std.testing.expectEqual(@as(u16, 0xD3A7), @as(u16, @truncate(decoded)));
+ try std.testing.expectEqual(@as(u32, 0x1234), @as(u32, @truncate(decoded >> 16)));
+ try std.testing.expectEqual(@as(u32, 0x5678), @as(u32, @truncate(decoded >> 48)));
+ commands.clearRetainingCapacity();
+ try draw(&commands, a, .{ 319, 8 }, 0, 0);
+ try draw(&commands, a, .{ 320, 7 }, 0, 0);
+ try std.testing.expectEqual(@as(usize, 0), commands.items.len);
+}
diff --git a/vendor/README.md b/vendor/README.md
index 2d01105..c23a785 100644
--- a/vendor/README.md
+++ b/vendor/README.md
@@ -8,3 +8,24 @@ Single-file codecs, vendored unchanged; `codecs.c` compiles them for the host.
| `cgltf.h` | https://github.com/jkuhlmann/cgltf | 1.15, commit `85cd62382dfea638278962690cf515023f33ed00` (MIT, license in header) |
`cgltf.c` compiles the unchanged cgltf header for the optional `gltf` module.
+
+`presentation-time/presentation-time.xml` is the Wayland presentation-time v3
+protocol description (the client binds v1; its license is included in the XML).
+On Linux, `build.zig` runs `wayland-scanner` to generate a client header and C
+protocol tables in the build cache, then translates that header into the existing
+Zig `c` module alongside SDL. No generated C/header files are checked in.
+
+All handwritten callbacks, resource ownership, clock conversion, pacing and trace
+formatting live in `src/host/Presentation.zig`. Run `zig build test-presentation`
+(or `zig build test-timing`) from the project root to test them. Linux builds need
+`wayland-scanner` and the `wayland-client` development package.
+
+The trace uses a private event queue dispatched on the SDL thread. Per-frame
+feedback objects are owned by libwayland; our pending slots and completed-record
+ring are fixed capacity. CSV `commit_ns` timestamps the feedback request before
+`SDL_RenderPresent`, rather than intercepting `wl_surface.commit`; the protocol
+associates feedback with the next commit of the SDL surface. Presented times,
+refresh periods, sequence numbers and flags are supplied by the compositor.
+`sample_ms` is the draw sample clock in SDL's epoch; `commit_ns` and `presented_ns` use the
+advertised protocol clock. Discarded rows have no presentation timestamp. A
+trace snapshot reports pending requests, exhausted slots and its retention limit.
diff --git a/vendor/presentation-time/presentation-time.xml b/vendor/presentation-time/presentation-time.xml
new file mode 100644
index 0000000..2ce9d8d
--- /dev/null
+++ b/vendor/presentation-time/presentation-time.xml
@@ -0,0 +1,296 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<protocol name="presentation_time">
+<!-- wrap:70 -->
+
+ <copyright>
+ Copyright © 2013-2014 Collabora, Ltd.
+
+ Permission is hereby granted, free of charge, to any person obtaining a
+ copy of this software and associated documentation files (the "Software"),
+ to deal in the Software without restriction, including without limitation
+ the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ and/or sell copies of the Software, and to permit persons to whom the
+ Software is furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice (including the next
+ paragraph) shall be included in all copies or substantial portions of the
+ Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+ </copyright>
+
+ <interface name="wp_presentation" version="3">
+ <description summary="timed presentation related wl_surface requests">
+
+<!-- Introduction -->
+
+ The main feature of this interface is accurate presentation
+ timing feedback to ensure smooth video playback while maintaining
+ audio/video synchronization. Some features use the concept of a
+ presentation clock, which is defined in the
+ presentation.clock_id event.
+
+ A content update for a wl_surface is submitted by a
+ wl_surface.commit request. Request 'feedback' associates with
+ the wl_surface.commit and provides feedback on the content
+ update, particularly the final realized presentation time.
+
+<!-- Completing presentation -->
+
+ When the final realized presentation time is available, e.g.
+ after a framebuffer flip completes, the requested
+ presentation_feedback.presented events are sent. The final
+ presentation time can differ from the compositor's predicted
+ display update time and the update's target time, especially
+ when the compositor misses its target vertical blanking period.
+ </description>
+
+ <enum name="error">
+ <description summary="fatal presentation errors">
+ These fatal protocol errors may be emitted in response to
+ illegal presentation requests.
+ </description>
+ <entry name="invalid_timestamp" value="0"
+ summary="invalid value in tv_nsec"/>
+ <entry name="invalid_flag" value="1"
+ summary="invalid flag"/>
+ </enum>
+
+ <request name="destroy" type="destructor">
+ <description summary="unbind from the presentation interface">
+ Informs the server that the client will no longer be using
+ this protocol object. Existing objects created by this object
+ are not affected.
+ </description>
+ </request>
+
+ <request name="feedback">
+ <description summary="request presentation feedback information">
+ Request presentation feedback for the current content submission
+ on the given surface. This creates a new presentation_feedback
+ object, which will deliver the feedback information once. If
+ multiple presentation_feedback objects are created for the same
+ submission, they will all deliver the same information.
+
+ For details on what information is returned, see the
+ presentation_feedback interface.
+ </description>
+ <arg name="surface" type="object" interface="wl_surface"
+ summary="target surface"/>
+ <arg name="callback" type="new_id" interface="wp_presentation_feedback"
+ summary="new feedback object"/>
+ </request>
+
+ <event name="clock_id">
+ <description summary="clock ID for timestamps">
+ This event tells the client in which clock domain the
+ compositor interprets the timestamps used by the presentation
+ extension. This clock is called the presentation clock.
+
+ The compositor sends this event when the client binds to the
+ presentation interface. The presentation clock does not change
+ during the lifetime of the client connection.
+
+ The clock identifier is platform dependent. On POSIX platforms, the
+ identifier value is one of the clockid_t values accepted by
+ clock_gettime(). clock_gettime() is defined by POSIX.1-2001.
+
+ Timestamps in this clock domain are expressed as tv_sec_hi,
+ tv_sec_lo, tv_nsec triples, each component being an unsigned
+ 32-bit value. Whole seconds are in tv_sec which is a 64-bit
+ value combined from tv_sec_hi and tv_sec_lo, and the
+ additional fractional part in tv_nsec as nanoseconds. Hence,
+ for valid timestamps tv_nsec must be in [0, 999999999].
+
+ Note that clock_id applies only to the presentation clock,
+ and implies nothing about e.g. the timestamps used in the
+ Wayland core protocol input events.
+
+ Compositors should prefer a clock which does not jump and is
+ not slewed e.g. by NTP. The absolute value of the clock is
+ irrelevant. Precision of one millisecond or better is
+ recommended. Clients must be able to query the current clock
+ value directly, not by asking the compositor.
+ </description>
+ <arg name="clk_id" type="uint" summary="platform clock identifier"/>
+ </event>
+
+ </interface>
+
+ <interface name="wp_presentation_feedback" version="3">
+ <description summary="presentation time feedback event">
+ A presentation_feedback object returns an indication that a
+ wl_surface content update has become visible to the user.
+ One object corresponds to one content update submission
+ (wl_surface.commit). There are two possible outcomes: the
+ content update is presented to the user, and a presentation
+ timestamp delivered; or, the user did not see the content
+ update because it was superseded or its surface destroyed,
+ and the content update is discarded.
+
+ Once a presentation_feedback object has delivered a 'presented'
+ or 'discarded' event it is automatically destroyed.
+ </description>
+
+ <event name="sync_output">
+ <description summary="presentation synchronized to this output">
+ As presentation can be synchronized to only one output at a
+ time, this event tells which output it was. This event is only
+ sent prior to the presented event.
+
+ As clients may bind to the same global wl_output multiple
+ times, this event is sent for each bound instance that matches
+ the synchronized output. If a client has not bound to the
+ right wl_output global at all, this event is not sent.
+ </description>
+ <arg name="output" type="object" interface="wl_output"
+ summary="presentation output"/>
+ </event>
+
+ <enum name="kind" bitfield="true">
+ <description summary="bitmask of flags in presented event">
+ These flags provide information about how the presentation of
+ the related content update was done. The intent is to help
+ clients assess the reliability of the feedback and the visual
+ quality with respect to possible tearing and timings.
+ </description>
+ <entry name="vsync" value="0x1">
+ <description summary="presentation was vsync'd">
+ The presentation was synchronized to the "vertical retrace" by
+ the display hardware such that tearing does not happen.
+ Relying on software scheduling is not acceptable for this
+ flag. If presentation is done by a copy to the active
+ frontbuffer, then it must guarantee that tearing cannot
+ happen.
+ </description>
+ </entry>
+ <entry name="hw_clock" value="0x2">
+ <description summary="hardware provided the presentation timestamp">
+ The display hardware provided measurements that the hardware
+ driver converted into a presentation timestamp. Sampling a
+ clock in software is not acceptable for this flag.
+ </description>
+ </entry>
+ <entry name="hw_completion" value="0x4">
+ <description summary="hardware signalled the start of the presentation">
+ The display hardware signalled that it started using the new
+ image content. The opposite of this is e.g. a timer being used
+ to guess when the display hardware has switched to the new
+ image content.
+ </description>
+ </entry>
+ <entry name="zero_copy" value="0x8">
+ <description summary="presentation was done zero-copy">
+ The presentation of this update was done zero-copy. This means
+ the buffer from the client was given to display hardware as
+ is, without copying it. Compositing with OpenGL counts as
+ copying, even if textured directly from the client buffer.
+ Possible zero-copy cases include direct scanout of a
+ fullscreen surface and a surface on a hardware overlay.
+ </description>
+ </entry>
+ <entry name="fixed_rate" value="0x10" since="3">
+ <description summary="presentation is at a fixed refresh rate">
+ The display hardware is operating at a fixed refresh rate.
+ The presentation was aligned to a multiple of this event's
+ 'refresh' argument.
+ If this is set, the refresh argument must not be 0.
+ </description>
+ </entry>
+ <entry name="variable_rate" value="0x20" since="3">
+ <description summary="presentation is at a variable refresh rate">
+ The display hardware is operating at a variable refresh rate, with
+ updates to this surface consistently determining the display refresh
+ timing. The definition of 'consistent' is compositor policy.
+
+ The content update was displayed as soon as possible after it became
+ ready, but no sooner than 'refresh' nanoseconds after the previous
+ presentation on this surface. In other words, the presentation time
+ was determined by when this surface's content became ready, not by
+ a periodic display refresh or by updates to other surfaces.
+
+ If this is set, the refresh argument must not be 0.
+ </description>
+ </entry>
+ </enum>
+
+ <event name="presented" type="destructor">
+ <description summary="the content update was displayed">
+ The associated content update was displayed to the user at the
+ indicated time (tv_sec_hi/lo, tv_nsec). For the interpretation of
+ the timestamp, see presentation.clock_id event.
+
+ The timestamp corresponds to the time when the content update
+ turned into light the first time on the surface's main output.
+ Compositors may approximate this from the framebuffer flip
+ completion events from the system, and the latency of the
+ physical display path if known.
+
+ This event is preceded by all related sync_output events
+ telling which output's refresh cycle the feedback corresponds
+ to, i.e. the main output for the surface. Compositors are
+ recommended to choose the output containing the largest part
+ of the wl_surface, or keeping the output they previously
+ chose. Having a stable presentation output association helps
+ clients predict future output refreshes (vblank).
+
+ The 'refresh' argument gives the compositor's prediction of how
+ many nanoseconds after tv_sec, tv_nsec the very next output
+ refresh may occur. This is to further aid clients in
+ predicting future refreshes, i.e., estimating the timestamps
+ targeting the next few vblanks. If such prediction cannot
+ usefully be done, the argument is zero.
+
+ For version 2 and later, if the output does not have a constant
+ refresh rate, explicit video mode switches excluded, then the
+ refresh argument must be either an appropriate rate picked by the
+ compositor (e.g. fastest rate), or 0 if no such rate exists.
+ For version 1, if the output does not have a constant refresh rate,
+ the refresh argument must be zero.
+
+ If the 'fixed_rate' flag is set, then the refresh argument is
+ the output's constant refresh rate. If the 'variable_rate' flag
+ is set, then the refresh argument is the output's fastest refresh
+ rate.
+
+ The 64-bit value combined from seq_hi and seq_lo is the value
+ of the output's vertical retrace counter when the content
+ update was first scanned out to the display. This value must
+ be compatible with the definition of MSC in
+ GLX_OML_sync_control specification. Note, that if the display
+ path has a non-zero latency, the time instant specified by
+ this counter may differ from the timestamp's.
+
+ If the output does not have a concept of vertical retrace or a
+ refresh cycle, or the output device is self-refreshing without
+ a way to query the refresh count, then the arguments seq_hi
+ and seq_lo must be zero.
+ </description>
+ <arg name="tv_sec_hi" type="uint"
+ summary="high 32 bits of the seconds part of the presentation timestamp"/>
+ <arg name="tv_sec_lo" type="uint"
+ summary="low 32 bits of the seconds part of the presentation timestamp"/>
+ <arg name="tv_nsec" type="uint"
+ summary="nanoseconds part of the presentation timestamp"/>
+ <arg name="refresh" type="uint" summary="nanoseconds till next refresh"/>
+ <arg name="seq_hi" type="uint"
+ summary="high 32 bits of refresh counter"/>
+ <arg name="seq_lo" type="uint"
+ summary="low 32 bits of refresh counter"/>
+ <arg name="flags" type="uint" enum="kind" summary="combination of 'kind' values"/>
+ </event>
+
+ <event name="discarded" type="destructor">
+ <description summary="the content update was not displayed">
+ The content update was never displayed to the user.
+ </description>
+ </event>
+ </interface>
+
+</protocol>