From 82fca5c9f29124f37f6dcd08e73e6999ce44a69d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 16 Nov 2026 20:31:59 -0300 Subject: Add display-paced frame timing and presentation feedback in Zig --- src/host/Console.zig | 41 +++++- src/host/Host.zig | 81 ++++++++++- src/host/Presentation.zig | 331 +++++++++++++++++++++++++++++++++++++++++++++ src/host/Timing.zig | 169 +++++++++++++++++++++++ src/host/TimingAtlas.zig | 138 +++++++++++++++++++ src/host/control.zig | 94 ++++++++++++- src/host/gfx.zig | 13 ++ src/host/overlay.zig | 48 +++++++ src/host/root.zig | 5 + src/host/timeline.zig | 2 + src/host/timing_marker.zig | 45 ++++++ 11 files changed, 956 insertions(+), 11 deletions(-) create mode 100644 src/host/Presentation.zig create mode 100644 src/host/Timing.zig create mode 100644 src/host/TimingAtlas.zig create mode 100644 src/host/timing_marker.zig (limited to 'src/host') 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|"); self.log("diff [N] | reset | get | set | 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 `/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: `/.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); +} -- cgit v1.3