//! 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); }