Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

Add opt-in late rendering and a frame timing trace

oxydizerd95002cd2bd1
diff --git a/AGENTS.md b/AGENTS.md
index f9734e5..2c2e903 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -101,6 +101,19 @@ panel painting. The key rules:
* **Commit through `Output.commitFrameState`** and build output state through
`Server.buildOutputState`, including capture. Register new commit reasons
in `commitIsRedundant`; skipped callbacks wait for `vblank_timer`.
+* **Late rendering is opt-in** (`[compositor] late_render`; glue in
+ `output/late.zig`, model in `late_render.zig`). Off, nothing in the frame path
+ changes. On, a frame event that finds work and a trusted presentation
+ timeline (vsync + hardware clock, a stream of frames, no VRR/tearing) is
+ deferred: frame callbacks go out *then* so clients answer inside the wait,
+ `late_timer` runs `runFrame`, which takes the plan and skips its own
+ post-commit callbacks, and frame events meanwhile are ignored. Frames after
+ idle always render at once. The deadline is `vblank - worst recent
+ cost - margin`, cost = max(CPU to commit, build + GPU elapsed from
+ `server.gpu_recent`); a missed vblank grows the margin, three in two seconds
+ pause it with backoff. Headless presents synchronously and nested pipelines
+ are deeper, so only `late_render_tests.zig` and a DRM run reach the engaged
+ path (`tests/frame_latency.py`).
* **Window frames are shapes:** every ring pixel needs body content beneath
it. Shadows, resize grabs, popups and other nodes outside the window need
`setTreeUnclipped`. Capture the client alone with its shape supplied
diff --git a/TESTING.md b/TESTING.md
index 18c2c44..2cbeb77 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -62,6 +62,14 @@ and [startup_perf.py](tests/startup_perf.py). Stats requests enable timers and
add overhead; keep CPU comparisons free of them. `frame_time_ms` is the commit
interval; CPU and GPU work overlap, so do not add their timings.
+Measure frame scheduling (frame event, render start, commit, presentation, age
+of the content shown) with a `-Dframe-trace=true` build and
+[frame_latency.py](tests/frame_latency.py), which runs an isolated session or
+analyses a traced compositor's log. The option compiles the trace in; normal
+builds contain none of it. Headless presents synchronously, so only the cost
+columns mean anything there; presentation latency needs DRM (a spare VT) and
+the `present flags` line showing vsync with a hardware clock.
+
Audit memory retention with [memory_retention.py](tests/memory_retention.py):
```sh
diff --git a/build.zig b/build.zig
index b2c7313..ffc515c 100644
--- a/build.zig
+++ b/build.zig
@@ -27,6 +27,11 @@ pub fn build(b: *std.Build) void {
const use_llvm = b.option(bool, "llvm", "Use LLVM and LLD (default for optimized builds)") orelse (optimize != .debug);
// Debug aid (TESTING.md): redraw every frame whole and log what the damage missed.
const damage_audit = b.option(bool, "damage-audit", "Compare every frame with a full repaint and log the difference (slow)") orelse false;
+ // Debug aid: log the timing of every frame (event, render, commit, presentation).
+ const frame_trace = b.option(bool, "frame-trace", "Log per-frame timing for frame scheduling measurements (src/output/frame_trace.zig)") orelse false;
+ const trace_options = b.addOptions();
+ trace_options.addOption(bool, "frame_trace", frame_trace);
+ const trace_mod = trace_options.createModule();
// Set by scripts/build-wlroots.sh builds on distros without wlroots 0.20
// (Debian/Ubuntu). pkg-config runs in zig build's own environment, so
// start it through scripts/with-wlroots.sh to find the prefix.
@@ -178,6 +183,7 @@ pub fn build(b: *std.Build) void {
compositor.root_module.addCSourceFile(.{ .file = b.path("src/session/auth.c"), .flags = &.{"-std=c11"} });
compositor.root_module.addCSourceFile(.{ .file = b.path("src/polkit/native.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
addGlass(b, compositor.root_module, damage_audit);
+ if (frame_trace) compositor.root_module.addCMacro("REDIWM_FRAME_TRACE", "1");
compositor.root_module.addCSourceFile(.{ .file = b.path("src/gpu_timing.c"), .flags = &.{"-std=c11"} });
b.step("rediwm", "Build the compositor").dependOn(&compositor.step);
@@ -259,6 +265,7 @@ pub fn build(b: *std.Build) void {
}
inline for (.{ compositor.root_module, ui_tests_module, files.root_module, images.root_module, editor.root_module, pdf.root_module, share_picker.root_module, monitor.root_module, calculator.root_module, editor_tests.root_module, images_tests.root_module, pdf_tests.root_module, files_tests.root_module, ipc_tests_module, protocol_mod, session_supervisor.root_module, session_tests.root_module, share_picker_tests.root_module, dbus_tests.root_module }) |module| {
module.addImport("install_paths", layout.options);
+ module.addImport("trace", trace_mod);
module.addImport("ui", ui_mod);
module.addImport("i18n", i18n_mod);
module.addImport("config", config_mod);
diff --git a/docs/wiki/Configuration.md b/docs/wiki/Configuration.md
index da629f7..69c2670 100644
--- a/docs/wiki/Configuration.md
+++ b/docs/wiki/Configuration.md
@@ -142,6 +142,8 @@ time and date (`clock_bold` and `clock_italic` in `[theme]`, or
| Key | Default | Notes |
| --- | --- | --- |
| `allow_tearing` | `false` | lets focused fullscreen clients request async presentation |
+| `late_render` | `false` | start each frame of a stream (dragging, scrolling, animation) as late as the display allows so input made just before a refresh still reaches it: roughly one refresh period less latency for continuous input, none for a single event. Needs a display that reports presentation times (DRM); VRR, tearing and nested sessions keep the normal path, and repeated missed deadlines pause it for a while |
+| `late_render_margin_ms` | `2.0` | 0.5 to 8, the least safety time kept before the refresh; it grows by itself after a miss |
| `window_tab_apps` | `[]` | app IDs that get tabs |
| `default_file_manager`, `default_terminal` | `""` | desktop IDs, empty means Files / auto terminal |
| `taskbar_position` | `"bottom"` | `top` or `bottom` |
diff --git a/src/Output.zig b/src/Output.zig
index 81e497f..26c9929 100644
--- a/src/Output.zig
+++ b/src/Output.zig
@@ -19,6 +19,7 @@ const output_layout = @import("output/layout.zig");
const output_panels = @import("output/panels.zig");
const output_wallpaper = @import("output/wallpaper.zig");
const output_frame = @import("output/frame.zig");
+const output_late = @import("output/late.zig");
pub const wlr_color_transform_init_lut_3x1d = wlr.color.transformInitLut3x1d;
pub const wlr_color_transform_unref = wlr.color.transformUnref;
@@ -98,6 +99,15 @@ frame_wanted: bool = false,
/// Last known vblank: a page-flip frame event or a fired `vblank_timer`.
last_vblank_ns: u64 = 0,
flip_pending: bool = false,
+/// Late rendering (`output/late.zig`): the decision model, the timer that
+/// starts a deferred frame, whether one is waiting (frame events are ignored
+/// meanwhile), the plan `runFrame` takes when it runs, and whether the last
+/// frame asked for another (an animation) so the next is worth deferring.
+late: @import("output/late_render.zig").State = .{},
+late_timer: ?*wl.EventSource = null,
+late_armed: bool = false,
+late_plan: ?@import("output/late_render.zig").Plan = null,
+late_animating: bool = false,
/// Decides, once this dispatch's commits are handled, whether client frame
/// callbacks need a frame (`frameCallbacksWanted`).
callback_idle: ?*wl.EventSource = null,
@@ -244,6 +254,8 @@ pub fn create(server: *Server, wlr_output: *wlr.Output) !void {
}
output.vblank_timer = server.wl_server.getEventLoop().addTimer(*Output, handleVblank, output) catch null;
errdefer if (output.vblank_timer) |timer| timer.remove();
+ output.late_timer = server.wl_server.getEventLoop().addTimer(*Output, lateFire, output) catch null;
+ errdefer if (output.late_timer) |timer| timer.remove();
// Layout entry and scene output are addons on `wlr_output`. On error the
// caller destroys that output, which is safer than a second explicit
@@ -475,6 +487,9 @@ pub const handleRequestState = output_frame.handleRequestState;
pub const handlePresent = output_frame.handlePresent;
pub const startupVisible = output_frame.startupVisible;
+// output/late.zig
+pub const lateFire = output_late.fire;
+
pub const CursorState = struct {
cursor: ?*wlr.OutputCursor = null,
buffer: ?*wlr.Buffer = null,
@@ -575,6 +590,7 @@ pub fn handleDestroy(listener: *wl.Listener(*wlr.Output), _: *wlr.Output) void {
if (output.power_menu) |pm| pm.destroy();
output.color.deinit();
if (output.vblank_timer) |timer| timer.remove();
+ if (output.late_timer) |timer| timer.remove();
if (output.callback_idle) |idle| idle.remove();
output.link.remove();
output.frame.link.remove();
diff --git a/src/Server.zig b/src/Server.zig
index 91e8d78..b147c85 100644
--- a/src/Server.zig
+++ b/src/Server.zig
@@ -102,6 +102,10 @@ renderer: *wlr.Renderer,
gpu_timer: ?*@import("gpu_timing.zig").Timer = null,
gpu_timer_tried: bool = false,
gpu_timer_used_ns: u64 = 0,
+/// Late rendering needs the GPU's elapsed times too: it keeps the timer alive
+/// while it schedules (`keepGpuTimer`) and reads this ring of recent samples.
+gpu_timer_sched_ns: u64 = 0,
+gpu_recent: @import("output/late_render.zig").PeakRing(32) = .{},
allocator: *wlr.Allocator,
/// What each output keeps besides the output itself (scene_outputs.h).
scene_outputs: *scene_outputs_mod.SceneOutputs,
@@ -531,6 +535,7 @@ pub const handleAudioWake = server_wakeups.handleAudioWake;
pub const handleBatteryUevent = server_wakeups.handleBatteryUevent;
pub const updateBatteryWarning = server_wakeups.updateBatteryWarning;
pub const ensureGpuTimer = server_wakeups.ensureGpuTimer;
+pub const keepGpuTimer = server_wakeups.keepGpuTimer;
pub const observingStats = server_wakeups.observingStats;
pub const expireGpuTimer = server_wakeups.expireGpuTimer;
diff --git a/src/config/default.zig b/src/config/default.zig
index 39934e9..6133f74 100644
--- a/src/config/default.zig
+++ b/src/config/default.zig
@@ -126,6 +126,12 @@ pub const source =
\\floating_apps = [] # app ID glob patterns that float in workspaces
\\# Allow fullscreen clients to request asynchronous presentation (may tear).
\\allow_tearing = false
+ \\# Render as late as the display allows, so input made just before a refresh
+ \\# still reaches it. Only displays that report presentation times qualify
+ \\# (DRM; not VRR, tearing or nested ones), and it steps back by itself when
+ \\# deadlines are missed. The margin is the least safety time kept (ms).
+ \\late_render = false
+ \\late_render_margin_ms = 2.0
\\# Only windows launched with the chrome + join that window’s tabs.
\\window_tab_apps = [] # app IDs; Appearance provides a checkbox list
\\# Desktop application IDs; empty keeps Files and the automatic terminal.
diff --git a/src/config/loader.zig b/src/config/loader.zig
index e137b68..be9ce1c 100644
--- a/src/config/loader.zig
+++ b/src/config/loader.zig
@@ -242,6 +242,11 @@ pub const CompositorConfig = struct {
switcher_opacity: f32 = 1.0,
border_radius: u32 = 10,
allow_tearing: bool = false,
+ /// Start frames as late as the display allows instead of right after
+ /// each vblank (`output/late_render.zig`).
+ late_render: bool = false,
+ /// The least safety time (ms) late rendering keeps before a vblank.
+ late_render_margin_ms: f32 = 2.0,
xwayland: bool = true,
xwayland_native_scaling: bool = false,
/// 0 follows the native-scaling policy; explicit factors require restart.
diff --git a/src/config/loader_fields.zig b/src/config/loader_fields.zig
index 0ff0218..5664dca 100644
--- a/src/config/loader_fields.zig
+++ b/src/config/loader_fields.zig
@@ -155,6 +155,8 @@ pub const compositor_rules: std.enums.EnumFieldStruct(std.meta.FieldEnum(Composi
.switcher_opacity = .{ .float = .{ .min = 0, .max = 1 } },
.border_radius = .{ .uint = .{ .min = 0, .max = 128 } },
.allow_tearing = .boolean,
+ .late_render = .boolean,
+ .late_render_margin_ms = .{ .float = .{ .min = 0.5, .max = 8 } },
.xwayland = .boolean,
.xwayland_native_scaling = .boolean,
.xwayland_scale = .{ .float = .{ .min = 0, .max = 4 } },
diff --git a/src/config/loader_fields_tests.zig b/src/config/loader_fields_tests.zig
index 9e55cd2..49f8da8 100644
--- a/src/config/loader_fields_tests.zig
+++ b/src/config/loader_fields_tests.zig
@@ -119,6 +119,17 @@ test "config field parsing preserves ranges and derived zoom state" {
try std.testing.expectError(error.InvalidValue, applyCompositorKey(&c, a, fixture[0], fixture[3]));
try std.testing.expectError(error.InvalidValue, applyCompositorKey(&c, a, fixture[0], fixture[4]));
}
+ try std.testing.expect(!c.late_render);
+ try applyCompositorKey(&c, a, "late_render", "true");
+ try std.testing.expect(c.late_render);
+ try std.testing.expectEqual(@as(f32, 2.0), c.late_render_margin_ms);
+ inline for (.{ "0.5", "8", "3.25" }) |value| {
+ try applyCompositorKey(&c, a, "late_render_margin_ms", value);
+ try std.testing.expectEqual(try std.fmt.parseFloat(f32, value), c.late_render_margin_ms);
+ }
+ inline for (.{ "0.4", "8.5", "-1" }) |value| {
+ try std.testing.expectError(error.InvalidValue, applyCompositorKey(&c, a, "late_render_margin_ms", value));
+ }
inline for (.{ "1", "1.05", "1.5" }) |value| {
try applyCompositorKey(&c, a, "dock_hover_zoom", value);
try std.testing.expectEqual(try std.fmt.parseFloat(f32, value), c.dock_hover_zoom);
diff --git a/src/gpu_timing.zig b/src/gpu_timing.zig
index 9137fa3..ab81311 100644
--- a/src/gpu_timing.zig
+++ b/src/gpu_timing.zig
@@ -1,5 +1,6 @@
const wlr = @import("wlroots");
const stats = @import("ipc/stats.zig");
+const late_render = @import("output/late_render.zig");
const Sample = extern struct { ns: u64, generation: u64 };
pub const Timer = opaque {
@@ -17,12 +18,15 @@ pub const Timer = opaque {
if (!ok) stats.global_stats.gpu_samples_dropped +%= 1;
return ok;
}
- pub fn collect(self: *Timer) void {
+ /// Records finished samples in the stats window and in `recent`, which
+ /// keeps them whatever the stats generation (late rendering reads it).
+ pub fn collect(self: *Timer, recent: *late_render.PeakRing(32)) void {
var samples: [8]Sample = undefined;
var dropped: u64 = 0;
const n = rediwm_gpu_timer_collect(self, stats.global_stats.generation, &samples, &dropped);
stats.global_stats.gpu_samples_dropped +%= dropped;
for (samples[0..n]) |sample| {
+ recent.push(sample.ns);
if (sample.generation == stats.global_stats.generation)
stats.global_stats.gpu_elapsed.record(sample.ns);
}
diff --git a/src/ipc/handlers_frames.zig b/src/ipc/handlers_frames.zig
index 31a7a28..fb41a16 100644
--- a/src/ipc/handlers_frames.zig
+++ b/src/ipc/handlers_frames.zig
@@ -135,7 +135,7 @@ pub fn handleFrameAction(
},
.get_performance_stats => {
server.ensureGpuTimer();
- if (server.gpu_timer) |timer| timer.collect();
+ if (server.gpu_timer) |timer| timer.collect(&server.gpu_recent);
const panel_s = @import("../panel_present.zig").snapshot();
const timing = stats.global_stats.timing();
return .{ .ok = .{ .performance_stats = .{
diff --git a/src/output/frame.zig b/src/output/frame.zig
index e43bc2a..cf2a9c6 100644
--- a/src/output/frame.zig
+++ b/src/output/frame.zig
@@ -9,6 +9,8 @@ const Taskbar = @import("../Taskbar.zig");
const anim = @import("ui").anim;
const glass = @import("../glass.zig");
const stats = @import("../ipc/stats.zig");
+const trace = @import("frame_trace.zig");
+const late = @import("late.zig");
const wlr_color_transform_unref = Output.wlr_color_transform_unref;
const log = std.log.scoped(.output);
const CursorState = Output.CursorState;
@@ -188,6 +190,10 @@ pub fn tearingIdle(output: *Output) void {
pub fn handleFrame(listener: *wl.Listener(*wlr.Output), _: *wlr.Output) void {
const output: *Output = @fieldParentPtr("frame", listener);
+ // A deferred frame is on its way; this event is damage asking for it.
+ // (Not traced: the frame's event is the one that deferred it.)
+ if (output.late_armed) return;
+ trace.frameEvent(output.wlr_output);
// Only the vblank timer paces frames after a skipped commit.
if (output.vblank_armed) {
output.frame_wanted = true;
@@ -197,11 +203,13 @@ pub fn handleFrame(listener: *wl.Listener(*wlr.Output), _: *wlr.Output) void {
output.flip_pending = false;
output.last_vblank_ns = stats.nowNs();
}
+ if (late.tryDefer(output)) return;
runFrame(output);
}
pub fn runFrame(output: *Output) void {
const frame_started = stats.nowNs();
+ const late_plan = late.takePlan(output);
// Stage timing costs a clock read per boundary (and two per animation
// sample); only pay it while someone is reading the stats.
const observing = output.server.observingStats(frame_started);
@@ -214,7 +222,7 @@ pub fn runFrame(output: *Output) void {
output.animation_budget.record(elapsed, output.wlr_output.refresh);
}
output.server.expireGpuTimer();
- if (output.server.gpu_timer) |timer| timer.collect();
+ if (output.server.gpu_timer) |timer| timer.collect(&output.server.gpu_recent);
output.server.screenshot_selector.flush(output);
const now_ms = Taskbar.nowMs();
@@ -305,6 +313,8 @@ pub fn runFrame(output: *Output) void {
captured = sm.handleOutputFrame(output);
}
var deferred = false;
+ var timing = trace.Frame{ .start = frame_started, .active = trace.enabled or late.enabled(output), .plan = late_plan };
+ defer timing.finish(output.wlr_output);
if (!captured) {
const started = stats.nowNs();
var state = wlr.Output.State.init();
@@ -321,7 +331,9 @@ pub fn runFrame(output: *Output) void {
var committed = true;
if (should_commit) {
if (output.server.capture_mgr) |cm| cm.guardScreencopy(output.wlr_output);
- if (output.server.buildOutputState(scene_output, &state)) {
+ const built_ok = output.server.buildOutputState(scene_output, &state);
+ timing.markBuilt();
+ if (built_ok) {
if (@import("../startup.zig").marks.first_visible_ns == 0) {
output.startup_commit_seq = output.wlr_output.commit_seq +% 1;
output.startup_presented = false;
@@ -331,6 +343,7 @@ pub fn runFrame(output: *Output) void {
output.startup_committing = true;
committed = output.commitFrameState(&state);
output.startup_committing = false;
+ timing.markCommitted(if (committed) output.wlr_output.commit_seq else null);
if (!committed) {
output.startup_commit_seq = null;
output.greeter_commit_seq = null;
@@ -341,6 +354,7 @@ pub fn runFrame(output: *Output) void {
if (committed) {
output.committed_cursor = CursorState.of(output.wlr_output);
output.flip_pending = true;
+ if (timing.commit_seq) |seq| late.noteCommitted(output, seq, frame_started, timing.built, timing.done, late_plan);
if (output.lock_commit_pending) {
output.lock_commit_pending = false;
if (output.server.locker) |lock| lock.outputCovered();
@@ -359,14 +373,15 @@ pub fn runFrame(output: *Output) void {
// Headless backends can acknowledge synchronously inside commit.
if (output.startup_presented) output.startupVisible();
}
- if (!deferred) {
+ // A deferred frame's callbacks went out when it was deferred.
+ if (!deferred and late_plan == null) {
var now = timestamp();
output.server.sendFrameDone(scene_output, &now);
}
}
if (deferred) {
deferFrameDone(output);
- } else {
+ } else if (late_plan == null) {
var preview_time = timestamp();
output.server.switcher.frameDone(output, &preview_time);
}
@@ -381,6 +396,7 @@ pub fn runFrame(output: *Output) void {
// animation settles; otherwise chrome and the bar only redraw when a
// client does.
const keep_going = mini_map_animating or switcher_animating or osd_animating or dock_animating or bar_animating or chrome_animating or cc_animating or sm_animating or pm_animating or taskbar_popup_animating or notif_animating or desktop_animating or lock_animating or polkit_animating or reveal_animating;
+ output.late_animating = keep_going;
// A pinned clock is advanced explicitly by IPC, which schedules its own
// frame. Global window/taskbar springs must not spin between those steps.
if (keep_going and !anim.clockOverridden()) {
@@ -401,6 +417,7 @@ pub fn setDisplayMode(output: *Output, mode: @import("../output_modes.zig").Choi
defer state.finish();
mode.setState(&state);
if (!output.wlr_output.testState(&state) or !output.wlr_output.commitState(&state)) return false;
+ late.reset(output);
syncLayout(output.server);
output.color.key = null;
output.server.night_light.retargetOutput(output);
@@ -434,6 +451,7 @@ pub fn handleRequestState(
log.err("handleRequestState: commitState failed for {s}", .{output.wlr_output.name});
return;
}
+ late.reset(output);
output.applyConfig();
syncLayout(output.server);
output.color.key = null;
@@ -443,6 +461,8 @@ pub fn handleRequestState(
pub fn handlePresent(listener: *wl.Listener(*wlr.Output.event.Present), event: *wlr.Output.event.Present) void {
const output: *Output = @fieldParentPtr("present", listener);
+ trace.presented(event);
+ late.notePresent(output, event);
if (event.presented and output.greeter_commit_seq == event.commit_seq) {
output.greeter_presented = true;
@import("../session/greeter_ready.zig").check(output.server);
diff --git a/src/output/frame_trace.zig b/src/output/frame_trace.zig
new file mode 100644
index 0000000..6574ea8
--- /dev/null
+++ b/src/output/frame_trace.zig
@@ -0,0 +1,92 @@
+//! Frame timing trace for scheduling measurements (`-Dframe-trace=true`).
+//!
+//! Every `runFrame` logs one `F` line and every presentation one `P` line,
+//! both with CLOCK_MONOTONIC nanoseconds, so `tests/frame_latency.py` can pair
+//! them by `cseq`:
+//!
+//! F ev the output's frame event arrived (0: run without one)
+//! start `runFrame` began built scene state built (render submitted)
+//! done commit returned d1/d2 first/last content damage since the previous frame
+//! late 1 when late rendering deferred it, then vexp (the vblank it aimed
+//! for), est (worst recent cost) and mrg (safety margin) in ns
+//! P when the display's presentation time now when we heard of it
+//! vseq retrace counter refresh predicted period flags `wlr_output_present_flag`
+//!
+//! Without the option nothing here is compiled in.
+
+const std = @import("std");
+const wlr = @import("wlroots");
+const stats = @import("../ipc/stats.zig");
+const late_render = @import("late_render.zig");
+
+pub const enabled = @import("trace").frame_trace;
+const log = std.log.scoped(.frame_trace);
+
+extern fn rediwm_trace_take_damage(output: *wlr.Output, last_ns: *u64) u64;
+
+const max_outputs = 8;
+var slots: [max_outputs]struct { output: ?*wlr.Output = null, event_ns: u64 = 0 } = @splat(.{});
+
+fn slotFor(output: *wlr.Output) ?*@TypeOf(slots[0]) {
+ for (&slots) |*slot| {
+ if (slot.output == output or slot.output == null) {
+ slot.output = output;
+ return slot;
+ }
+ }
+ return null;
+}
+
+pub fn frameEvent(output: *wlr.Output) void {
+ if (!enabled) return;
+ if (slotFor(output)) |slot| slot.event_ns = stats.nowNs();
+}
+
+/// One `runFrame`: its stage times, logged when it ends. The clock is read
+/// only when `active`: the trace is compiled in, or late rendering feeds on
+/// the times.
+pub const Frame = struct {
+ start: u64,
+ active: bool = enabled,
+ built: u64 = 0,
+ done: u64 = 0,
+ /// Null when the frame committed nothing (skipped, captured or failed).
+ commit_seq: ?u32 = null,
+ /// The plan this frame was deferred by, if it was.
+ plan: ?late_render.Plan = null,
+
+ pub fn markBuilt(self: *Frame) void {
+ if (self.active) self.built = stats.nowNs();
+ }
+
+ pub fn markCommitted(self: *Frame, commit_seq: ?u32) void {
+ if (!self.active) return;
+ self.done = stats.nowNs();
+ self.commit_seq = commit_seq;
+ }
+
+ pub fn finish(self: *const Frame, output: *wlr.Output) void {
+ if (!enabled) return;
+ var last: u64 = 0;
+ const first = rediwm_trace_take_damage(output, &last);
+ var event_ns: u64 = 0;
+ if (slotFor(output)) |slot| {
+ event_ns = slot.event_ns;
+ slot.event_ns = 0;
+ }
+ const plan = self.plan orelse late_render.Plan{ .start_ns = 0, .vblank_ns = 0, .estimate_ns = 0, .margin_ns = 0 };
+ log.info("F out={s} ev={d} start={d} built={d} done={d} d1={d} d2={d} cseq={d} commit={d} late={d} vexp={d} est={d} mrg={d}", .{
+ output.name, event_ns, self.start, self.built, self.done, first, last,
+ self.commit_seq orelse 0, @intFromBool(self.commit_seq != null),
+ @intFromBool(self.plan != null), plan.vblank_ns, plan.estimate_ns, plan.margin_ns,
+ });
+ }
+};
+
+pub fn presented(event: *const wlr.Output.event.Present) void {
+ if (!enabled) return;
+ const when: u64 = @as(u64, @intCast(@max(event.when.sec, 0))) *% 1_000_000_000 +% @as(u64, @intCast(@max(event.when.nsec, 0)));
+ log.info("P out={s} cseq={d} presented={d} when={d} now={d} vseq={d} refresh={d} flags={d}", .{
+ event.output.name, event.commit_seq, @intFromBool(event.presented), when, stats.nowNs(), event.seq, event.refresh, event.flags,
+ });
+}
diff --git a/src/output/late.zig b/src/output/late.zig
new file mode 100644
index 0000000..30afef0
--- /dev/null
+++ b/src/output/late.zig
@@ -0,0 +1,110 @@
+//! Late rendering on an `Output`: connects `late_render.State` to the frame
+//! loop. Off unless `[compositor] late_render` is set; with it off every entry
+//! point returns before touching anything, and frames run as they always did.
+//!
+//! A frame event that finds work to do and a trusted presentation timeline is
+//! not rendered at once. Frame callbacks go out right then, so clients draw
+//! during the wait and their commits join the frame, and `late_timer` starts
+//! `runFrame` at the planned time. Further frame events are ignored while it
+//! waits: they are only damage asking for a frame it is about to produce.
+
+const std = @import("std");
+const wlr = @import("wlroots");
+const Output = @import("../Output.zig");
+const late_render = @import("late_render.zig");
+const stats = @import("../ipc/stats.zig");
+const log = std.log.scoped(.late_render);
+
+pub fn enabled(output: *const Output) bool {
+ const server = output.server;
+ return server.config.compositor.late_render and output.late_timer != null and !server.greeter_mode;
+}
+
+fn floorNs(output: *const Output) u64 {
+ const margin_ms: f64 = output.server.config.compositor.late_render_margin_ms;
+ return @intFromFloat(@round(margin_ms * std.time.ns_per_ms));
+}
+
+/// Called for a frame event. True: a frame is deferred (frame callbacks are
+/// sent, the timer is armed); false: render now.
+pub fn tryDefer(output: *Output) bool {
+ if (!enabled(output) or !output.late.timeline_valid) return false;
+ const wlr_output = output.wlr_output;
+ if (!wlr_output.enabled or output.power_off or wlr_output.adaptive_sync_status == .enabled or output.tearingAllowed()) return false;
+ const server = output.server;
+ const scene_output = server.scene_outputs.get(wlr_output) orelse return false;
+ // Only a frame that will change something is worth waiting for.
+ if (!output.late_animating and output.commitIsRedundant(scene_output)) return false;
+
+ const now = stats.nowNs();
+ server.keepGpuTimer(now);
+ const gpu_known = server.gpu_timer != null and server.gpu_recent.len() >= late_render.tuning.min_samples;
+ const plan = switch (output.late.plan(now, floorNs(output), gpu_known)) {
+ .immediate => return false,
+ .wait => |p| p,
+ };
+ // Whole milliseconds, rounded down: starting early costs a little
+ // freshness, starting late could cost the vblank.
+ const delay_ms: c_int = @intCast(@max(1, (plan.start_ns - now) / std.time.ns_per_ms));
+ output.late_timer.?.timerUpdate(delay_ms) catch return false;
+ output.late_armed = true;
+ output.late_plan = plan;
+ output.sendFrameDone();
+ return true;
+}
+
+/// `late_timer`: the deferred frame's time has come.
+pub fn fire(output: *Output) c_int {
+ output.late_armed = false;
+ const wlr_output = output.wlr_output;
+ if (!wlr_output.enabled) {
+ output.late_plan = null;
+ } else if (wlr_output.frame_pending) {
+ output.late_plan = null;
+ wlr_output.scheduleFrame();
+ } else {
+ output.runFrame();
+ }
+ return 0;
+}
+
+/// The plan of the frame `runFrame` is starting, if it was deferred.
+pub fn takePlan(output: *Output) ?late_render.Plan {
+ const plan = output.late_plan;
+ output.late_plan = null;
+ return plan;
+}
+
+/// A frame committed; its stage times feed the cost estimate.
+pub fn noteCommitted(output: *Output, commit_seq: u32, start_ns: u64, built_ns: u64, done_ns: u64, plan: ?late_render.Plan) void {
+ if (!enabled(output)) return;
+ output.late.committed(commit_seq, start_ns, built_ns, done_ns, output.server.gpu_recent.peak(), plan);
+}
+
+/// The display reported a presentation: the timeline, and the verdict on a
+/// deferred frame's deadline.
+pub fn notePresent(output: *Output, event: *const wlr.Output.event.Present) void {
+ if (!enabled(output)) return;
+ const refresh_ns: u64 = if (event.refresh > 0) @intCast(event.refresh) else 0;
+ const when_ns = @as(u64, @intCast(@max(event.when.sec, 0))) *% std.time.ns_per_s +% @as(u64, @intCast(@max(event.when.nsec, 0)));
+ const trips = output.late.trips;
+ output.late.presented(stats.nowNs(), .{
+ .when_ns = when_ns,
+ .refresh_ns = refresh_ns,
+ .flags = event.flags,
+ .presented = event.presented,
+ .commit_seq = event.commit_seq,
+ }, output.refreshPeriodNs());
+ if (output.late.trips != trips) {
+ log.warn("{s}: late rendering paused for {d} ms after repeated missed deadlines (margin now {d:.2} ms)", .{
+ output.wlr_output.name,
+ (output.late.fallback_until_ns -| stats.nowNs()) / std.time.ns_per_ms,
+ @as(f64, @floatFromInt(output.late.margin_ns)) / std.time.ns_per_ms,
+ });
+ }
+}
+
+/// A mode change or similar: the old timeline says nothing about the new one.
+pub fn reset(output: *Output) void {
+ output.late.invalidate();
+}
diff --git a/src/output/late_render.zig b/src/output/late_render.zig
new file mode 100644
index 0000000..391a136
--- /dev/null
+++ b/src/output/late_render.zig
@@ -0,0 +1,243 @@
+//! Late rendering: start a frame as late as the display allows, so input and
+//! client commits made while it waits still reach the vblank it targets.
+//!
+//! This is the decision model: plain data in, a decision out, no wlroots and no
+//! clock of its own, so the timing cases are tested with synthetic timelines.
+//! `late.zig` connects it to an `Output`.
+//!
+//! Only a *stream* of frames gains anything. A lone damage event renders at
+//! once and is shown at the next vblank either way, so a frame after idle
+//! always runs immediately; the stream it starts is then scheduled against the
+//! presentation times the display reports.
+//!
+//! The deadline is `vblank - estimate - margin`:
+//! * estimate: the worst critical path of the last frames, from the start of
+//! a frame to its commit returning, or to the GPU finishing what that
+//! commit waits on (build time plus the GPU's own elapsed time). Commit
+//! time, the KMS submission, is part of the first.
+//! * margin: never below the configured floor; grows when a frame misses its
+//! vblank (fast) and shrinks only after a long clean run (slow).
+//! A miss costs a whole refresh period, so the model is built for consistency:
+//! it takes the worst recent cost, not the typical one, and three misses in
+//! two seconds hand scheduling back to the normal path for a growing pause.
+
+const std = @import("std");
+
+const ms = std.time.ns_per_ms;
+
+pub const tuning = struct {
+ /// Frames measured before the first late start.
+ pub const min_samples = 8;
+ /// Waits shorter than this just render now.
+ pub const min_wait_ns = 1 * ms;
+ /// Started later than this fraction of a period is not worth the risk.
+ pub const max_budget_percent = 90;
+ /// Without GPU timing the estimate misses the GPU tail; cover it.
+ pub const unknown_gpu_extra_ns = 2 * ms;
+ /// The last present older than this many periods means no stream.
+ pub const stale_periods = 2;
+ /// A missed vblank grows the margin by half of it, at least this much.
+ pub const miss_step_ns = 1 * ms;
+ pub const near_miss_step_ns = 250_000;
+ pub const decay_step_ns = 250_000;
+ /// A clean run this long gives one decay step back.
+ pub const decay_after_ns = 4 * std.time.ns_per_s;
+ /// This many misses within `trip_window_ns` pause late rendering.
+ pub const trip_misses = 3;
+ pub const trip_window_ns = 2 * std.time.ns_per_s;
+ pub const backoff_min_ns = 2 * std.time.ns_per_s;
+ pub const backoff_max_ns = 60 * std.time.ns_per_s;
+ /// No pause for this long starts the next one at the minimum again.
+ pub const backoff_reset_ns = 120 * std.time.ns_per_s;
+};
+
+/// `wlr_output_present_flag`: vsync, and a time from the display's own clock.
+/// Anything less (headless, X11) is not a vblank to schedule against.
+pub const usable_flags: u32 = 0x1 | 0x2;
+
+pub fn PeakRing(comptime capacity: usize) type {
+ return struct {
+ values: [capacity]u64 = @splat(0),
+ count: usize = 0,
+ next: usize = 0,
+
+ pub fn push(self: *@This(), value: u64) void {
+ self.values[self.next] = value;
+ self.next = (self.next + 1) % capacity;
+ self.count +|= 1;
+ }
+
+ pub fn len(self: *const @This()) usize {
+ return @min(self.count, capacity);
+ }
+
+ pub fn peak(self: *const @This()) u64 {
+ var result: u64 = 0;
+ for (self.values[0..self.len()]) |value| result = @max(result, value);
+ return result;
+ }
+ };
+}
+
+pub const Plan = struct {
+ /// When to start rendering.
+ start_ns: u64,
+ /// The vblank this frame is meant to reach.
+ vblank_ns: u64,
+ estimate_ns: u64,
+ margin_ns: u64,
+};
+
+pub const Decision = union(enum) {
+ /// Render now: nothing to gain, or the timing is not trusted.
+ immediate,
+ wait: Plan,
+};
+
+pub const Present = struct {
+ when_ns: u64,
+ refresh_ns: u64,
+ flags: u32,
+ presented: bool,
+ commit_seq: u32,
+};
+
+/// The frame last committed from a plan, waiting for its presentation.
+const Pending = struct {
+ commit_seq: u32 = 0,
+ vblank_ns: u64 = 0,
+ done_ns: u64 = 0,
+ margin_ns: u64 = 0,
+};
+
+pub const State = struct {
+ cost: PeakRing(64) = .{},
+ timeline_valid: bool = false,
+ last_when_ns: u64 = 0,
+ period_ns: u64 = 0,
+ margin_ns: u64 = 0,
+ floor_ns: u64 = 0,
+ last_adjust_ns: u64 = 0,
+ pending: Pending = .{},
+ recent_misses: [tuning.trip_misses]u64 = @splat(0),
+ miss_next: usize = 0,
+ fallback_until_ns: u64 = 0,
+ backoff_ns: u64 = tuning.backoff_min_ns,
+ last_trip_ns: u64 = 0,
+ late_frames: u64 = 0,
+ misses: u64 = 0,
+ near_misses: u64 = 0,
+ trips: u64 = 0,
+
+ /// What to do with a frame event arriving at `now`.
+ pub fn plan(self: *State, now: u64, floor_ns: u64, gpu_known: bool) Decision {
+ self.setFloor(floor_ns);
+ if (!self.timeline_valid or self.cost.len() < tuning.min_samples) return .immediate;
+ if (now < self.fallback_until_ns) return .immediate;
+ // A presentation time ahead of our clock means the clocks disagree.
+ if (now + ms < self.last_when_ns) {
+ self.invalidate();
+ return .immediate;
+ }
+ const age = now -| self.last_when_ns;
+ if (age > tuning.stale_periods * self.period_ns) return .immediate;
+ const vblank = self.last_when_ns + (age / self.period_ns + 1) * self.period_ns;
+ var budget = self.cost.peak() + self.margin_ns;
+ if (!gpu_known) budget += tuning.unknown_gpu_extra_ns;
+ if (budget >= self.period_ns * tuning.max_budget_percent / 100) return .immediate;
+ const start = vblank - budget;
+ if (start < now + tuning.min_wait_ns) return .immediate;
+ return .{ .wait = .{ .start_ns = start, .vblank_ns = vblank, .estimate_ns = self.cost.peak(), .margin_ns = self.margin_ns } };
+ }
+
+ /// A frame committed. `gpu_peak_ns` is the recent worst GPU elapsed time
+ /// (0 when unknown); `from` is the plan it ran from, if any.
+ pub fn committed(self: *State, commit_seq: u32, start_ns: u64, built_ns: u64, done_ns: u64, gpu_peak_ns: u64, from: ?Plan) void {
+ const cpu = done_ns -| start_ns;
+ const gpu = (built_ns -| start_ns) +| gpu_peak_ns;
+ const path = @max(cpu, gpu);
+ self.cost.push(path);
+ self.pending = .{};
+ if (from) |p| {
+ self.late_frames +|= 1;
+ // The frame is ready when the commit has returned and the GPU is done.
+ self.pending = .{ .commit_seq = commit_seq, .vblank_ns = p.vblank_ns, .done_ns = start_ns + path, .margin_ns = p.margin_ns };
+ }
+ }
+
+ /// A presentation report. `fallback_period_ns` is the mode's own period,
+ /// used when the report predicts none.
+ pub fn presented(self: *State, now: u64, p: Present, fallback_period_ns: u64) void {
+ const period = if (p.refresh_ns >= 2 * ms and p.refresh_ns <= 100 * ms) p.refresh_ns else fallback_period_ns;
+ if (!p.presented or p.when_ns == 0 or p.flags & usable_flags != usable_flags or
+ period < 2 * ms or period > 100 * ms or
+ (self.timeline_valid and p.when_ns <= self.last_when_ns))
+ {
+ self.invalidate();
+ return;
+ }
+ if (self.pending.vblank_ns != 0 and self.pending.commit_seq == p.commit_seq) self.judge(now, p.when_ns, period);
+ self.last_when_ns = p.when_ns;
+ self.period_ns = period;
+ self.timeline_valid = true;
+ }
+
+ /// The timeline cannot be trusted until the next usable presentation.
+ pub fn invalidate(self: *State) void {
+ self.timeline_valid = false;
+ self.pending = .{};
+ }
+
+ fn judge(self: *State, now: u64, when_ns: u64, period: u64) void {
+ const pending = self.pending;
+ self.pending = .{};
+ const lateness = @as(i64, @intCast(@min(when_ns, std.math.maxInt(i63)))) - @as(i64, @intCast(@min(pending.vblank_ns, std.math.maxInt(i63))));
+ const half: i64 = @intCast(period / 2);
+ if (lateness > half) return self.miss(now, true);
+ // Shown a period early: the prediction itself was wrong.
+ if (lateness < -half) return self.miss(now, false);
+ const slack = @as(i64, @intCast(@min(pending.vblank_ns, std.math.maxInt(i63)))) - @as(i64, @intCast(@min(pending.done_ns, std.math.maxInt(i63))));
+ if (slack < @as(i64, @intCast(pending.margin_ns / 4))) {
+ self.near_misses +|= 1;
+ self.grow(now, tuning.near_miss_step_ns);
+ } else if (now -| self.last_adjust_ns >= tuning.decay_after_ns and self.margin_ns > self.floor_ns) {
+ self.margin_ns = @max(self.floor_ns, self.margin_ns -| tuning.decay_step_ns);
+ self.last_adjust_ns = now;
+ }
+ }
+
+ fn miss(self: *State, now: u64, late: bool) void {
+ if (late) {
+ self.misses +|= 1;
+ self.grow(now, @max(tuning.miss_step_ns, self.margin_ns / 2));
+ }
+ self.recent_misses[self.miss_next] = now;
+ self.miss_next = (self.miss_next + 1) % tuning.trip_misses;
+ const oldest = self.recent_misses[self.miss_next];
+ if (oldest != 0 and now -| oldest <= tuning.trip_window_ns) self.trip(now);
+ }
+
+ pub fn trip(self: *State, now: u64) void {
+ if (self.last_trip_ns != 0 and now -| self.last_trip_ns > tuning.backoff_reset_ns) self.backoff_ns = tuning.backoff_min_ns;
+ self.fallback_until_ns = now + self.backoff_ns;
+ self.backoff_ns = @min(self.backoff_ns * 2, tuning.backoff_max_ns);
+ self.last_trip_ns = now;
+ self.trips +|= 1;
+ self.recent_misses = @splat(0);
+ self.pending = .{};
+ }
+
+ pub fn grow(self: *State, now: u64, step_ns: u64) void {
+ self.margin_ns = @min(self.margin_ns + step_ns, self.cap());
+ self.last_adjust_ns = now;
+ }
+
+ fn cap(self: *const State) u64 {
+ return @max(self.floor_ns, self.period_ns / 3);
+ }
+
+ fn setFloor(self: *State, floor_ns: u64) void {
+ self.floor_ns = floor_ns;
+ self.margin_ns = @max(self.margin_ns, floor_ns);
+ }
+};
diff --git a/src/output/late_render_tests.zig b/src/output/late_render_tests.zig
new file mode 100644
index 0000000..c1df888
--- /dev/null
+++ b/src/output/late_render_tests.zig
@@ -0,0 +1,215 @@
+//! Tests for the late-render decision model (`late_render.zig`), on synthetic
+//! 60 Hz timelines.
+
+const std = @import("std");
+const late_render = @import("late_render.zig");
+const State = late_render.State;
+const Plan = late_render.Plan;
+const Present = late_render.Present;
+const Decision = late_render.Decision;
+const tuning = late_render.tuning;
+const usable_flags = late_render.usable_flags;
+
+const ms = std.time.ns_per_ms;
+const testing = std.testing;
+const hz60: u64 = 16_666_667;
+const hw: u32 = usable_flags | 0x4;
+
+fn report(when: u64, seq: u32) Present {
+ return .{ .when_ns = when, .refresh_ns = hz60, .flags = hw, .presented = true, .commit_seq = seq };
+}
+
+/// A 60 Hz timeline with `n` clean streaming frames of `cost` ns behind it;
+/// returns the last presentation time.
+fn warmed(state: *State, n: usize, cost: u64) u64 {
+ var when: u64 = 1_000 * ms;
+ for (0..n) |i| {
+ when += hz60;
+ const start = when - hz60 + 100_000;
+ state.committed(@intCast(i), start, start + cost / 2, start + cost, 0, null);
+ state.presented(when, report(when, @intCast(i)), hz60);
+ }
+ return when;
+}
+
+/// Commits a planned frame that finishes `finish_ns` after its start and is
+/// shown at `shown`.
+fn planned(state: *State, plan: Plan, seq: u32, finish_ns: u64, shown: u64) void {
+ state.committed(seq, plan.start_ns, plan.start_ns + finish_ns / 2, plan.start_ns + finish_ns, 0, plan);
+ state.presented(shown, report(shown, seq), hz60);
+}
+
+test "a frame without a trusted timeline or enough history renders now" {
+ var state = State{};
+ try testing.expectEqual(Decision.immediate, state.plan(5_000 * ms, 2 * ms, true));
+ const few = warmed(&state, tuning.min_samples - 1, 2 * ms);
+ try testing.expectEqual(Decision.immediate, state.plan(few + 100_000, 2 * ms, true));
+ state = State{};
+ const when = warmed(&state, 20, 2 * ms);
+ var unusable = report(when + hz60, 99);
+ unusable.flags = 0;
+ state.presented(when + hz60, unusable, hz60);
+ try testing.expectEqual(Decision.immediate, state.plan(when + hz60 + 100_000, 2 * ms, true));
+}
+
+test "a stream is scheduled against the next vblank, worst cost plus margin" {
+ var state = State{};
+ const when = warmed(&state, 20, 3 * ms);
+ const now = when + 200_000;
+ const d = state.plan(now, 2 * ms, true);
+ try testing.expectEqual(when + hz60, d.wait.vblank_ns);
+ try testing.expectEqual(3 * ms, d.wait.estimate_ns);
+ try testing.expectEqual(2 * ms, d.wait.margin_ns);
+ try testing.expectEqual(when + hz60 - 5 * ms, d.wait.start_ns);
+ // Unknown GPU time adds its allowance.
+ try testing.expectEqual(when + hz60 - 7 * ms, state.plan(now, 2 * ms, false).wait.start_ns);
+}
+
+test "the estimate follows the worst recent frame, not the typical one" {
+ var state = State{};
+ var when = warmed(&state, 30, 2 * ms);
+ state.committed(100, when, when + ms, when + 6 * ms, 0, null);
+ when += hz60;
+ state.presented(when, report(when, 100), hz60);
+ try testing.expectEqual(6 * ms, state.plan(when + 100_000, 2 * ms, true).wait.estimate_ns);
+}
+
+test "the GPU's tail counts, not just the CPU's time" {
+ var state = State{};
+ var when = warmed(&state, 30, 1 * ms);
+ // The CPU is done in 1.2 ms; the commit waits for a GPU busy 4 ms after the build.
+ state.committed(100, when, when + 1 * ms, when + 1_200_000, 4 * ms, null);
+ when += hz60;
+ state.presented(when, report(when, 100), hz60);
+ try testing.expectEqual(5 * ms, state.plan(when + 100_000, 2 * ms, true).wait.estimate_ns);
+}
+
+test "frames after idle and frames with no room to wait render now" {
+ var state = State{};
+ const when = warmed(&state, 20, 3 * ms);
+ try testing.expectEqual(Decision.immediate, state.plan(when + 3 * hz60, 2 * ms, true));
+ // Already inside the late window: the target has passed.
+ try testing.expectEqual(Decision.immediate, state.plan(when + hz60 - 4 * ms, 2 * ms, true));
+ // A budget of most of the period gains nothing.
+ var heavy = State{};
+ const heavy_when = warmed(&heavy, 20, 14 * ms);
+ try testing.expectEqual(Decision.immediate, heavy.plan(heavy_when + 100_000, 2 * ms, true));
+}
+
+test "a missed vblank grows the margin; repeated misses pause late rendering and back off" {
+ var state = State{};
+ var when = warmed(&state, 20, 3 * ms);
+ var seq: u32 = 200;
+ for (0..3) |i| {
+ const p = state.plan(when + 100_000, 2 * ms, true).wait;
+ when = p.vblank_ns + hz60; // shown a period late
+ planned(&state, p, seq, 3 * ms, when);
+ seq += 1;
+ if (i < 2) {
+ try testing.expect(state.margin_ns > 2 * ms);
+ try testing.expectEqual(@as(u64, 0), state.trips);
+ }
+ }
+ try testing.expectEqual(@as(u64, 3), state.misses);
+ try testing.expectEqual(@as(u64, 1), state.trips);
+ try testing.expectEqual(Decision.immediate, state.plan(when + 100_000, 2 * ms, true));
+ try testing.expectEqual(when + tuning.backoff_min_ns, state.fallback_until_ns);
+ try testing.expectEqual(2 * tuning.backoff_min_ns, state.backoff_ns);
+}
+
+test "a pause ends, keeps the margin it learned, and the next pause is longer" {
+ var state = State{};
+ var when = warmed(&state, 20, 3 * ms);
+ _ = state.plan(when + 100_000, 2 * ms, true);
+ state.grow(when, ms);
+ const learned = state.margin_ns;
+ state.trip(when);
+ try testing.expectEqual(Decision.immediate, state.plan(when + 100_000, 2 * ms, true));
+ when += tuning.backoff_min_ns + hz60;
+ state.presented(when, report(when, 1), hz60);
+ try testing.expect(state.plan(when + 100_000, 2 * ms, true) == .wait);
+ try testing.expectEqual(learned, state.margin_ns);
+ state.trip(when);
+ try testing.expectEqual(when + 2 * tuning.backoff_min_ns, state.fallback_until_ns);
+ // Left alone long enough, the next pause starts short again.
+ state.trip(when + tuning.backoff_reset_ns + 1);
+ try testing.expectEqual(when + tuning.backoff_reset_ns + 1 + tuning.backoff_min_ns, state.fallback_until_ns);
+}
+
+test "a near miss nudges the margin up and a long clean run gives it back" {
+ var state = State{};
+ var when = warmed(&state, 20, 3 * ms);
+ var p = state.plan(when + 100_000, 2 * ms, true).wait;
+ when = p.vblank_ns;
+ // The commit returned 0.2 ms before the vblank it made.
+ planned(&state, p, 300, p.vblank_ns - 200_000 - p.start_ns, when);
+ try testing.expectEqual(@as(u64, 1), state.near_misses);
+ const raised = state.margin_ns;
+ try testing.expect(raised > 2 * ms);
+ for (0..400) |i| {
+ p = state.plan(when + 100_000, 2 * ms, true).wait;
+ when = p.vblank_ns;
+ planned(&state, p, @intCast(400 + i), 3 * ms, when);
+ }
+ try testing.expect(state.margin_ns < raised);
+ try testing.expect(state.margin_ns >= 2 * ms);
+ try testing.expectEqual(@as(u64, 0), state.trips);
+}
+
+test "the margin never leaves its floor and cap" {
+ var state = State{};
+ _ = warmed(&state, 20, 3 * ms);
+ _ = state.plan(1_020 * ms, 5 * ms, true);
+ try testing.expectEqual(5 * ms, state.margin_ns);
+ state.grow(1, 100 * ms);
+ try testing.expectEqual(@max(5 * ms, hz60 / 3), state.margin_ns);
+}
+
+test "an unusable presentation report invalidates the timeline until a good one" {
+ var state = State{};
+ var when = warmed(&state, 20, 3 * ms);
+ var not_presented = report(when + hz60, 1);
+ not_presented.presented = false;
+ var no_time = report(0, 1);
+ no_time.when_ns = 0;
+ var no_vsync = report(when + hz60, 1);
+ no_vsync.flags = 0x1;
+ var no_refresh = report(when + hz60, 1);
+ no_refresh.refresh_ns = 0;
+ for ([_]Present{ not_presented, no_time, no_vsync, report(when - 1, 1), no_refresh }) |bad| {
+ state.presented(when + hz60, bad, 0);
+ try testing.expect(!state.timeline_valid);
+ try testing.expectEqual(Decision.immediate, state.plan(when + hz60 + 100_000, 2 * ms, true));
+ state.presented(when + hz60, report(when + hz60, 1), hz60);
+ when += hz60;
+ try testing.expect(state.timeline_valid);
+ }
+}
+
+test "a clock that disagrees with the display's does not schedule" {
+ var state = State{};
+ const when = warmed(&state, 20, 3 * ms);
+ try testing.expectEqual(Decision.immediate, state.plan(when - 5 * ms, 2 * ms, true));
+ try testing.expect(!state.timeline_valid);
+}
+
+test "a frame shown a period early counts toward a pause but does not grow the margin" {
+ var state = State{};
+ const when = warmed(&state, 20, 3 * ms);
+ const p = state.plan(when + 100_000, 2 * ms, true).wait;
+ const before = state.margin_ns;
+ planned(&state, p, 400, 3 * ms, p.vblank_ns - hz60 + 1);
+ try testing.expectEqual(before, state.margin_ns);
+ try testing.expectEqual(@as(u64, 0), state.misses);
+ try testing.expect(state.recent_misses[0] != 0);
+}
+
+test "slack is measured to when the GPU is done, not just the commit" {
+ var state = State{};
+ const when = warmed(&state, 20, 3 * ms);
+ const p = state.plan(when + 100_000, 2 * ms, true).wait;
+ // The commit returns early, but the GPU finishes 0.2 ms before the vblank.
+ state.committed(500, p.start_ns, p.start_ns + ms, p.start_ns + 2 * ms, p.vblank_ns - 200_000 - (p.start_ns + ms), p);
+ state.presented(p.vblank_ns, report(p.vblank_ns, 500), hz60);
+ try testing.expectEqual(@as(u64, 1), state.near_misses);
+}
diff --git a/src/projection_internal.h b/src/projection_internal.h
index b65e6ab..dbbe14e 100644
--- a/src/projection_internal.h
+++ b/src/projection_internal.h
@@ -210,8 +210,10 @@ static inline void mark_group(struct rediwm_projection *p, struct group *g) {
}
static inline void schedule(struct rediwm_projection *p) {
struct rediwm_scene_output *out;
- wl_list_for_each(out, &p->outputs->outputs, link)
+ wl_list_for_each(out, &p->outputs->outputs, link) {
+ rediwm_trace_damage(out->output);
wlr_output_schedule_frame(out->output);
+ }
}
// ---- Surface feedback (stage 6 of docs/plans/scene-graph.md) ---------------------
// wlr_scene tells a surface where it is shown by emitting its scene buffer's own
diff --git a/src/scene_damage.c b/src/scene_damage.c
index 0006f6c..2b99633 100644
--- a/src/scene_damage.c
+++ b/src/scene_damage.c
@@ -34,6 +34,7 @@ void rediwm_scene_damage_layout(struct rediwm_scene_outputs *outputs, const pixm
wlr_damage_ring_add(&out->damage_ring, &device);
pixman_region32_union(&out->pending_commit_damage,
&out->pending_commit_damage, &device);
+ rediwm_trace_damage(output);
wlr_output_schedule_frame(output);
}
pixman_region32_fini(&device);
diff --git a/src/scene_outputs.c b/src/scene_outputs.c
index d8f4517..68e7fd3 100644
--- a/src/scene_outputs.c
+++ b/src/scene_outputs.c
@@ -4,6 +4,7 @@
#include "scene_outputs.h"
#include <assert.h>
#include <stdlib.h>
+#include <time.h>
#include <wlr/backend.h>
#include <wlr/backend/drm.h>
#include <wlr/render/drm_syncobj.h>
@@ -14,6 +15,41 @@
#include <wlr/util/region.h>
#include <wlr/util/transform.h>
+#ifdef REDIWM_FRAME_TRACE
+static struct {
+ struct wlr_output *output;
+ uint64_t first_ns, last_ns;
+} trace_slots[8];
+
+static uint64_t trace_now_ns(void) {
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
+}
+
+void rediwm_trace_damage(struct wlr_output *output) {
+ for (size_t i = 0; i < 8; i++) {
+ if (trace_slots[i].output != output && trace_slots[i].output != NULL) continue;
+ trace_slots[i].output = output;
+ trace_slots[i].last_ns = trace_now_ns();
+ if (trace_slots[i].first_ns == 0) trace_slots[i].first_ns = trace_slots[i].last_ns;
+ return;
+ }
+}
+
+uint64_t rediwm_trace_take_damage(struct wlr_output *output, uint64_t *last_ns) {
+ for (size_t i = 0; i < 8; i++) {
+ if (trace_slots[i].output != output) continue;
+ uint64_t first = trace_slots[i].first_ns;
+ *last_ns = trace_slots[i].last_ns;
+ trace_slots[i].first_ns = trace_slots[i].last_ns = 0;
+ return first;
+ }
+ *last_ns = 0;
+ return 0;
+}
+#endif
+
void rediwm_scene_output_damage(struct rediwm_scene_output *out, const pixman_region32_t *damage) {
struct wlr_output *output = out->output;
@@ -22,6 +58,7 @@ void rediwm_scene_output_damage(struct rediwm_scene_output *out, const pixman_re
pixman_region32_intersect_rect(&clipped, damage, 0, 0, output->width, output->height);
if (!pixman_region32_empty(&clipped)) {
+ rediwm_trace_damage(output);
wlr_output_schedule_frame(output);
wlr_damage_ring_add(&out->damage_ring, &clipped);
pixman_region32_union(&out->pending_commit_damage, &out->pending_commit_damage, &clipped);
@@ -34,6 +71,7 @@ void rediwm_scene_output_damage_whole(struct rediwm_scene_output *out) {
wlr_damage_ring_add_whole(&out->damage_ring);
pixman_region32_union_rect(&out->pending_commit_damage, &out->pending_commit_damage, 0, 0,
out->output->width, out->output->height);
+ rediwm_trace_damage(out->output);
wlr_output_schedule_frame(out->output);
}
@@ -87,6 +125,7 @@ static void output_damage(struct wl_listener *listener, void *data) {
static void output_needs_frame(struct wl_listener *listener, void *data) {
(void)data;
struct rediwm_scene_output *out = wl_container_of(listener, out, output_needs_frame);
+ rediwm_trace_damage(out->output);
wlr_output_schedule_frame(out->output);
}
diff --git a/src/scene_outputs.h b/src/scene_outputs.h
index a83b2b2..2c32af8 100644
--- a/src/scene_outputs.h
+++ b/src/scene_outputs.h
@@ -88,3 +88,13 @@ void rediwm_scene_output_damage_whole(struct rediwm_scene_output *);
// Whether anything asks for a frame: the output itself, or damage not yet committed.
bool rediwm_scene_output_needs_frame(const struct rediwm_scene_output *);
bool rediwm_scene_output_has_pending_damage(const struct rediwm_scene_output *);
+
+// Frame timing trace (-Dframe-trace, src/output/frame_trace.zig): when content last asked
+// this output for a frame. A no-op in every other build.
+#ifdef REDIWM_FRAME_TRACE
+void rediwm_trace_damage(struct wlr_output *);
+// The first damage since the last take (0 if none); `last_ns` gets the latest.
+uint64_t rediwm_trace_take_damage(struct wlr_output *, uint64_t *last_ns);
+#else
+static inline void rediwm_trace_damage(struct wlr_output *output) { (void)output; }
+#endif
diff --git a/src/server/wakeups.zig b/src/server/wakeups.zig
index 0aa3979..aee2bd6 100644
--- a/src/server/wakeups.zig
+++ b/src/server/wakeups.zig
@@ -7,6 +7,7 @@ const wl = @import("wayland").server.wl;
const battery_mod = @import("../taskbar/battery.zig");
const Taskbar = @import("../Taskbar.zig");
const gpu_timer_idle_ns = Server.gpu_timer_idle_ns;
+const gpu_timer_sched_keep_ns = 10 * std.time.ns_per_s;
/// Best-effort: `null` on any failure just means the taskbar/control-center
/// UI catches up to an external volume change (another app, `pactl`) on its
@@ -88,10 +89,20 @@ pub fn ensureGpuTimer(server: *Server) void {
server.gpu_timer = @import("../gpu_timing.zig").Timer.create(server.renderer);
}
+/// Late rendering's claim on the GPU timer: starts it if needed and keeps it
+/// for `gpu_timer_sched_keep_ns` after the last scheduling decision. It does
+/// not turn on the per-stage timing that stats requests enable.
+pub fn keepGpuTimer(server: *Server, now_ns: u64) void {
+ server.gpu_timer_sched_ns = now_ns;
+ if (server.gpu_timer_tried) return;
+ server.gpu_timer_tried = true;
+ server.gpu_timer = @import("../gpu_timing.zig").Timer.create(server.renderer);
+}
+
/// Whether a stats request came in recently enough that per-stage frame timing
/// is worth its clock reads (the same window the GPU timer uses).
pub fn observingStats(server: *const Server, now_ns: u64) bool {
- return server.gpu_timer_tried and now_ns -% server.gpu_timer_used_ns < gpu_timer_idle_ns;
+ return server.gpu_timer_tried and server.gpu_timer_used_ns != 0 and now_ns -% server.gpu_timer_used_ns < gpu_timer_idle_ns;
}
/// One `perf` query must not leave the timer's per-frame cost (measured
@@ -99,7 +110,9 @@ pub fn observingStats(server: *const Server, now_ns: u64) bool {
/// five minutes without a stats request it stops; the next request restarts it.
pub fn expireGpuTimer(server: *Server) void {
const timer = server.gpu_timer orelse return;
- if (@import("../ipc/stats.zig").nowNs() -% server.gpu_timer_used_ns < gpu_timer_idle_ns) return;
+ const now = @import("../ipc/stats.zig").nowNs();
+ if (server.gpu_timer_used_ns != 0 and now -% server.gpu_timer_used_ns < gpu_timer_idle_ns) return;
+ if (server.gpu_timer_sched_ns != 0 and now -% server.gpu_timer_sched_ns < gpu_timer_sched_keep_ns) return;
timer.destroy();
server.gpu_timer = null;
server.gpu_timer_tried = false;
diff --git a/src/ui_tests.zig b/src/ui_tests.zig
index ff4aaa2..c51fd67 100644
--- a/src/ui_tests.zig
+++ b/src/ui_tests.zig
@@ -71,6 +71,7 @@ test {
_ = @import("color.zig");
_ = @import("ipc/stats.zig");
_ = @import("ipc/frame_metrics.zig");
+ _ = @import("output/late_render_tests.zig");
_ = @import("config").keybinds;
_ = @import("osd_paint.zig");
_ = @import("osd.zig");
diff --git a/src/wlr/output.zig b/src/wlr/output.zig
index fe79521..1f07a8b 100644
--- a/src/wlr/output.zig
+++ b/src/wlr/output.zig
@@ -27,9 +27,8 @@
//! regardless of T, see signal.zig), but not a real payload type.
//! Connecting one of those later needs its real event struct filled
//! in first -- that's a compile error pointing here, not a silent bug.
-//! - `Present`'s payload is truncated after `presented` (only
-//! `commit_seq`/`presented` are read); `Damage`/`Precommit`/`Bind`
-//! aren't defined at all since nothing connects those signals.
+//! - `Damage`/`Precommit`/`Bind` aren't defined at all since nothing
+//! connects those signals.
//!
//! Dependencies are supplied by wlr.zig from the same header-backed module.
const std = @import("std");
@@ -261,17 +260,28 @@ pub fn Types(
};
pub const event = struct {
- /// Truncated after `presented`: nothing else is read.
pub const Present = extern struct {
output: *Output,
commit_seq: u32,
presented: bool,
+ /// When the content turned into light (the display's clock).
+ when: std.posix.timespec,
+ /// Vertical retrace counter; zero if unavailable.
+ seq: c_uint,
+ /// Predicted nanoseconds from `when` to the next refresh; zero if unknown.
+ refresh: c_int,
+ flags: u32,
comptime {
const Real = c.wlr_output_event_present;
assertFieldOffset(Present, Real, "output");
assertFieldOffset(Present, Real, "commit_seq");
assertFieldOffset(Present, Real, "presented");
+ assertFieldOffset(Present, Real, "when");
+ assertFieldOffset(Present, Real, "seq");
+ assertFieldOffset(Present, Real, "refresh");
+ assertFieldOffset(Present, Real, "flags");
+ assertSameLayout(Present, Real);
}
};
diff --git a/tests/frame_latency.py b/tests/frame_latency.py
new file mode 100644
index 0000000..0006016
--- /dev/null
+++ b/tests/frame_latency.py
@@ -0,0 +1,314 @@
+#!/usr/bin/env python3
+"""Frame scheduling and latency measurements, with and without late rendering.
+
+Needs a compositor built with `-Dframe-trace=true`:
+
+ zig build install -Dframe-trace=true -Doptimize=ReleaseSafe --prefix zig-out/frame-trace-late
+
+Each scenario runs in its own isolated compositor (private runtime dir and
+config, no D-Bus; the host session is never touched) with `late_render` off
+and/or on:
+
+ idle nothing happens: CPU and wakeups must not change
+ pointer synthetic pointer motion over the desktop (IPC automation)
+ event a probe client commits on every pointer motion over its window
+ paced a probe client animates, one commit per frame callback
+
+The probe client (frame_probe_client.c) records, per commit, when it was made
+and when wp_presentation says the display showed it: the end-to-end latency,
+and the number to judge by. The compositor trace (see output/frame_trace.zig)
+adds the stages inside the compositor.
+
+ python3 tests/frame_latency.py --late both # headless: cost only
+ python3 tests/frame_latency.py --backend drm --late both # on a spare text VT
+
+The headless backend presents synchronously, so its latencies mean nothing and
+late rendering never engages there. Only `--backend drm` (a text VT; it takes
+the display) and `--backend wayland` (nested, opens a window on the host)
+report real presentation times. `--bin-dir` selects the binary, so a build from
+before late rendering can supply the baseline (`--late off`). To analyse a log
+from any traced compositor: `--analyze LOG [--probe FILE]`.
+"""
+import argparse
+import os
+from pathlib import Path
+import random
+import re
+import statistics
+import subprocess
+import tempfile
+import time
+
+from desktop_zoom import ROOT, wait_for
+from ipc_client import IPCClient
+
+TRACE_LINE = re.compile(r"frame_trace\): ([FP]) (.*)$")
+# Presentation gaps longer than this many periods are idle, not missed frames.
+BURST_PERIODS = 8
+SCENARIOS = ("idle", "pointer", "event", "paced")
+
+
+def parse(text):
+ frames, presents = [], {}
+ for raw in text.splitlines():
+ match = TRACE_LINE.search(raw)
+ if not match:
+ continue
+ kind, rest = match.groups()
+ record = {k: (v if k == "out" else int(v)) for k, v in (kv.split("=", 1) for kv in rest.split())}
+ if kind == "F":
+ frames.append(record)
+ else:
+ presents[(record["out"], record["cseq"])] = record
+ return frames, presents
+
+
+def percentile(values, p):
+ ordered = sorted(values)
+ return ordered[min(len(ordered) - 1, max(0, -(-len(ordered) * p // 100) - 1))]
+
+
+def stats_line(name, values):
+ if not values:
+ return f"{name:26s} (no samples)"
+ return (f"{name:26s} n={len(values):6d} p50={percentile(values, 50):8.3f} p95={percentile(values, 95):8.3f} "
+ f"p99={percentile(values, 99):8.3f} max={max(values):8.3f} avg={statistics.fmean(values):8.3f}")
+
+
+def trace_rows(text, skip):
+ frames, presents = parse(text)
+ committed = [f for f in frames if f["commit"]]
+ rows = []
+ for f in committed:
+ p = presents.get((f["out"], f["cseq"]))
+ if p and p["presented"]:
+ rows.append(dict(f, when=p["when"], now=p["now"], flags=p["flags"], refresh=p["refresh"]))
+ return frames, rows[skip:]
+
+
+def analyze_trace(text, skip=30):
+ """Pair each committed frame with its presentation; all values in ms."""
+ frames, rows = trace_rows(text, skip)
+ ms = 1e6
+ out = [f"{len(frames)} frames ({sum(1 for f in frames if not f['commit'])} without a commit), {len(rows)} presented and analysed"]
+ out.append(stats_line("frame event -> start", [(r["start"] - r["ev"]) / ms for r in rows if r["ev"]]))
+ out.append(stats_line("render (start->built)", [(r["built"] - r["start"]) / ms for r in rows]))
+ out.append(stats_line("commit (built->done)", [(r["done"] - r["built"]) / ms for r in rows]))
+ out.append(stats_line("cpu (start->done)", [(r["done"] - r["start"]) / ms for r in rows]))
+ out.append(stats_line("slack (done->light)", [(r["when"] - r["done"]) / ms for r in rows]))
+ out.append(stats_line("age of render start", [(r["when"] - r["start"]) / ms for r in rows]))
+ out.append(stats_line("age of oldest damage", [(r["when"] - r["d1"]) / ms for r in rows if r["d1"]]))
+ out.append(stats_line("age of newest damage", [(r["when"] - r["d2"]) / ms for r in rows if r["d2"]]))
+ phase, gaps, missed, last = [], [], 0, None
+ for r in rows:
+ if last is not None and last["out"] == r["out"]:
+ gap = (r["when"] - last["when"]) / ms
+ period = (r["refresh"] or last["refresh"]) / ms or 16.667
+ if gap < period * BURST_PERIODS:
+ gaps.append(gap)
+ missed += max(0, round(gap / period) - 1)
+ phase.append((r["start"] - last["when"]) / ms)
+ last = r
+ out.append(stats_line("start after last light", phase))
+ out.append(stats_line("present interval", gaps))
+ flags = {}
+ for r in rows:
+ flags[r["flags"]] = flags.get(r["flags"], 0) + 1
+ refresh = statistics.median([r["refresh"] for r in rows]) if rows else 0
+ out.append(f"missed refreshes in bursts: {missed}; present flags: {flags}; predicted refresh: {refresh / ms:.3f} ms")
+ late = [r for r in rows if r.get("late")]
+ if late:
+ hits = sum(1 for r in late if r["when"] - r["vexp"] <= (r["refresh"] or 16_666_667) / 2)
+ out.append(f"late-rendered frames: {len(late)} ({len(late) * 100 // max(len(rows), 1)}% of presented), "
+ f"deadline hits {hits}, misses {len(late) - hits}")
+ out.append(stats_line("late: estimate", [r["est"] / ms for r in late]))
+ out.append(stats_line("late: margin", [r["mrg"] / ms for r in late]))
+ out.append(stats_line("late: slack (done->vexp)", [(r["vexp"] - r["done"]) / ms for r in late]))
+ return "\n".join(out)
+
+
+def probe_latencies(path):
+ """Commit-to-photon per commit: a replaced frame is shown with the next presented one."""
+ records = []
+ for line in Path(path).read_text().splitlines():
+ commit, presented, _flags = (int(x) for x in line.split())
+ records.append((commit, presented))
+ shown, latencies = None, []
+ for commit, presented in reversed(records):
+ if presented:
+ shown = presented
+ if shown:
+ latencies.append((shown - commit) / 1e6)
+ return latencies[::-1]
+
+
+def process_load(pid):
+ """CPU seconds and context switches of the whole process so far."""
+ fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()
+ cpu = (int(fields[11]) + int(fields[12])) / os.sysconf("SC_CLK_TCK")
+ switches = 0
+ for task in Path(f"/proc/{pid}/task").iterdir():
+ try:
+ for line in (task / "status").read_text().splitlines():
+ if "ctxt_switches" in line:
+ switches += int(line.split()[1])
+ except OSError:
+ pass
+ return cpu, switches
+
+
+def build_probe(tmp):
+ protocols = subprocess.check_output(["pkg-config", "--variable=pkgdatadir", "wayland-protocols"], text=True).strip()
+ for xml, name in (("stable/xdg-shell/xdg-shell.xml", "xdg-shell"),
+ ("stable/presentation-time/presentation-time.xml", "presentation-time")):
+ for mode, target in (("client-header", f"{name}-client-protocol.h"), ("private-code", f"{name}-protocol.c")):
+ subprocess.run(["wayland-scanner", mode, str(Path(protocols) / xml), str(tmp / target)], check=True)
+ subprocess.run(["cc", "-Wall", "-Wextra", f"-I{tmp}", str(ROOT / "tests/frame_probe_client.c"),
+ str(tmp / "xdg-shell-protocol.c"), str(tmp / "presentation-time-protocol.c"),
+ "-lwayland-client", "-o", str(tmp / "frame_probe_client")], check=True)
+ return tmp / "frame_probe_client"
+
+
+def session_env(args, tmp):
+ env = dict(os.environ, XDG_RUNTIME_DIR=str(tmp), XDG_CONFIG_HOME=str(tmp / "config"),
+ XDG_CACHE_HOME=str(tmp / "cache"), XDG_DATA_HOME=str(tmp / "data"), XDG_STATE_HOME=str(tmp / "state"),
+ REDIWM_CONFIG=str(tmp / "config.toml"), WLR_RENDERER_ALLOW_SOFTWARE="1",
+ WLR_RENDERER=os.environ.get("REDIWM_TEST_RENDERER", "gles2"),
+ REDIWM_SCALE=os.environ.get("REDIWM_TEST_SCALE", "1"), REDIWM_IPC_AUTOMATION="1", DBUS_SESSION_BUS_ADDRESS="")
+ for name in ("REDIWM_SOCKET", "DISPLAY", "WLR_BACKENDS", "WLR_HEADLESS_OUTPUTS"):
+ env.pop(name, None)
+ if args.backend == "wayland":
+ # The private runtime dir hides the host's socket: name it in full.
+ host = Path(os.environ.get("XDG_RUNTIME_DIR", "")) / os.environ.get("WAYLAND_DISPLAY", "")
+ if not host.is_socket():
+ raise SystemExit("--backend wayland needs a host Wayland session")
+ env["WAYLAND_DISPLAY"] = str(host)
+ else:
+ env.pop("WAYLAND_DISPLAY", None)
+ if args.backend == "headless":
+ env.update(WLR_BACKENDS="headless", WLR_HEADLESS_OUTPUTS="1")
+ return env
+
+
+def jitter_pointer(ipc, area, seconds, rng):
+ """Pointer motion at about 125 Hz with jitter, back and forth across `area` (x, y, w, h)."""
+ x0, y0, w, h = area
+ started, count = time.monotonic(), 0
+ while time.monotonic() - started < seconds:
+ count += 1
+ ipc.move_cursor(int(x0 + w * (0.1 + 0.8 * abs((count % 200) / 100 - 1))), int(y0 + h * (0.3 + 0.4 * abs((count % 50) / 25 - 1))))
+ time.sleep(rng.uniform(.005, .011))
+
+
+def run_scenario(args, scenario, late, probe_bin):
+ with tempfile.TemporaryDirectory(prefix="rediwm-frame-latency-") as directory:
+ tmp = Path(directory)
+ # Off writes no key at all, so a build from before late rendering takes the same config.
+ (tmp / "config.toml").write_text(("[compositor]\nlate_render = true\n" if late else "") + args.config)
+ env = session_env(args, tmp)
+ log_path = tmp / "compositor.log"
+ with log_path.open("w") as log:
+ compositor = subprocess.Popen([str(args.bin_dir / "rediwm")], env=env, stdout=log, stderr=log)
+ client = None
+ result = {"scenario": scenario, "late": late}
+ try:
+ socket = wait_for(lambda: next(tmp.glob("rediwm-*.sock"), None), "IPC unavailable", 30)
+ display = wait_for(lambda: next((p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock")), None), "display unavailable")
+ with IPCClient(socket) as ipc:
+ ipc.action("wait_for", {"condition": "wallpaper_presented", "timeout_ms": 15000})
+ time.sleep(1)
+ output = ipc.get_outputs()[0]
+ width, height = output["logical_width"], output["logical_height"]
+ area = (0, 0, width, height)
+ probe_file = tmp / "probe.txt"
+ if scenario in ("event", "paced"):
+ mode = "event" if scenario == "event" else "paced"
+ client = subprocess.Popen([str(probe_bin), mode, str(args.seconds + 1), str(probe_file)],
+ env=dict(env, WAYLAND_DISPLAY=display))
+ window = wait_for(lambda: next((w for w in ipc.get_windows() if w.get("app_id") == "frame-probe"), None), "probe window never mapped")
+ ipc.wait_for("window_geometry_settled", window_id=window["id"])
+ window = next(w for w in ipc.get_windows() if w.get("app_id") == "frame-probe")
+ area = (window["x"], window["y"], window["width"], window["height"])
+ time.sleep(.5)
+ cpu0, switches0 = process_load(compositor.pid)
+ started = time.monotonic()
+ rng = random.Random(1)
+ if scenario in ("pointer", "event"):
+ jitter_pointer(ipc, area, args.seconds, rng)
+ else:
+ time.sleep(args.seconds)
+ elapsed = time.monotonic() - started
+ cpu1, switches1 = process_load(compositor.pid)
+ result["cpu_percent"] = (cpu1 - cpu0) * 100 / elapsed
+ result["switches_per_s"] = (switches1 - switches0) / elapsed
+ if client:
+ client.wait(timeout=30)
+ result["probe"] = probe_latencies(probe_file) if probe_file.exists() else []
+ finally:
+ for process in (client, compositor):
+ if process and process.poll() is None:
+ process.terminate()
+ try:
+ process.wait(5)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ result["log"] = log_path.read_text(errors="replace")
+ return result
+
+
+def summary_row(result, skip):
+ probe = result.get("probe", [])[skip:]
+ _, rows = trace_rows(result["log"], skip)
+ late = sum(1 for r in rows if r.get("late"))
+ row = f"{result['scenario']:8s} late={'on ' if result['late'] else 'off'} cpu={result['cpu_percent']:5.2f}% wakeups={result['switches_per_s']:7.1f}/s frames={len(rows):5d} late_frames={late:5d}"
+ if probe:
+ row += (f"\n{'':9s}commit->photon ms: p50={percentile(probe, 50):6.2f} p95={percentile(probe, 95):6.2f} "
+ f"p99={percentile(probe, 99):6.2f} max={max(probe):6.2f} spread(p99-p50)={percentile(probe, 99) - percentile(probe, 50):5.2f} n={len(probe)}")
+ return row
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ parser.add_argument("--bin-dir", type=Path, default=ROOT / "zig-out/frame-trace-late/bin")
+ parser.add_argument("--analyze", type=Path, help="analyse this compositor log instead of running sessions")
+ parser.add_argument("--probe", type=Path, help="with --analyze: a probe client's output file")
+ parser.add_argument("--backend", choices=("headless", "wayland", "drm"), default="headless")
+ parser.add_argument("--late", choices=("off", "on", "both"), default="both")
+ parser.add_argument("--scenario", default="all", help="comma separated: " + ", ".join(SCENARIOS) + ", or all")
+ parser.add_argument("--seconds", type=float, default=12)
+ parser.add_argument("--config", default="", help="more config.toml text, e.g. '[compositor]' keys after late_render")
+ parser.add_argument("--keep", type=Path, help="save each run's compositor log in this directory")
+ parser.add_argument("--skip", type=int, default=30, help="warm-up frames to drop")
+ args = parser.parse_args()
+
+ if args.analyze:
+ print(analyze_trace(args.analyze.read_text(errors="replace"), args.skip))
+ if args.probe:
+ print(stats_line("commit->photon (probe)", probe_latencies(args.probe)[args.skip:]))
+ return
+ if args.backend == "drm" and os.environ.get("XDG_SESSION_TYPE") != "tty":
+ raise SystemExit("--backend drm takes the display: run it from a text VT (XDG_SESSION_TYPE=tty), not inside a desktop session")
+ scenarios = SCENARIOS if args.scenario == "all" else tuple(s for s in args.scenario.split(",") if s in SCENARIOS)
+ modes = {"off": (False,), "on": (True,), "both": (False, True)}[args.late]
+ with tempfile.TemporaryDirectory(prefix="rediwm-probe-build-") as build_dir:
+ probe_bin = build_probe(Path(build_dir)) if any(s in ("event", "paced") for s in scenarios) else None
+ results = []
+ for scenario in scenarios:
+ for late in modes:
+ print(f"running {scenario}, late_render {'on' if late else 'off'} ...", flush=True)
+ result = run_scenario(args, scenario, late, probe_bin)
+ results.append(result)
+ if args.keep:
+ args.keep.mkdir(parents=True, exist_ok=True)
+ (args.keep / f"{scenario}-{'late' if late else 'normal'}.log").write_text(result["log"])
+ print()
+ for result in results:
+ print(summary_row(result, args.skip))
+ for result in results:
+ if result["scenario"] != "idle":
+ print(f"\n== {result['scenario']}, late_render {'on' if result['late'] else 'off'}")
+ print(analyze_trace(result["log"], args.skip))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/frame_probe_client.c b/tests/frame_probe_client.c
new file mode 100644
index 0000000..13d6652
--- /dev/null
+++ b/tests/frame_probe_client.c
@@ -0,0 +1,251 @@
+// Probe client for frame_latency.py: commits frames and records, for each, when it
+// was committed and when the display showed it (wp_presentation feedback).
+//
+// frame_probe_client paced|event SECONDS OUTPUT_FILE
+//
+// paced: animates, one commit per frame callback (a game or video player).
+// event: commits on every pointer motion over its window (drawing, dragging, a
+// terminal echoing keys): content arriving at arbitrary points of the period.
+//
+// The output file has one line per commit: commit_ns presented_ns flags
+// (presented_ns 0: the frame was replaced before it was shown).
+#define _GNU_SOURCE
+#include "presentation-time-client-protocol.h"
+#include "xdg-shell-client-protocol.h"
+#include <poll.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <time.h>
+#include <unistd.h>
+#include <wayland-client.h>
+
+#define W 640
+#define H 400
+#define BUFFERS 8
+#define MAX_RECORDS 65536
+
+struct frame_buffer {
+ struct wl_buffer *buffer;
+ uint32_t *pixels;
+ bool busy;
+};
+struct record {
+ uint64_t commit_ns, presented_ns;
+ uint32_t flags;
+};
+
+static struct wl_display *display;
+static struct wl_compositor *compositor;
+static struct wl_shm *shm;
+static struct wl_seat *seat;
+static struct xdg_wm_base *wm;
+static struct wp_presentation *presentation;
+static struct wl_surface *surface;
+static struct frame_buffer buffers[BUFFERS];
+static struct record records[MAX_RECORDS];
+static int record_count, pending_feedback;
+static clockid_t clock_id = CLOCK_MONOTONIC;
+static bool paced, mapped, running = true;
+static uint64_t stop_ns;
+static int frame_number;
+
+static uint64_t now_ns(void) {
+ struct timespec ts;
+ clock_gettime(clock_id, &ts);
+ return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
+}
+
+static void draw(uint32_t *pixels, int x, int y) {
+ for (int i = 0; i < W * H; i++) pixels[i] = 0xff202830;
+ for (int row = y - 16; row < y + 16; row++) {
+ if (row < 0 || row >= H) continue;
+ for (int col = x - 16; col < x + 16; col++)
+ if (col >= 0 && col < W) pixels[row * W + col] = 0xfff0f0f0;
+ }
+}
+
+static void released(void *data, struct wl_buffer *buffer) {
+ (void)buffer;
+ ((struct frame_buffer *)data)->busy = false;
+}
+static const struct wl_buffer_listener buffer_listener = {released};
+
+static void feedback_sync_output(void *d, struct wp_presentation_feedback *f, struct wl_output *o) {
+ (void)d; (void)f; (void)o;
+}
+static void feedback_presented(void *data, struct wp_presentation_feedback *feedback, uint32_t sec_hi, uint32_t sec_lo,
+ uint32_t nsec, uint32_t refresh, uint32_t seq_hi, uint32_t seq_lo, uint32_t flags) {
+ (void)refresh; (void)seq_hi; (void)seq_lo;
+ struct record *r = &records[(intptr_t)data];
+ r->presented_ns = (((uint64_t)sec_hi << 32 | sec_lo) * 1000000000ull) + nsec;
+ r->flags = flags;
+ pending_feedback--;
+ wp_presentation_feedback_destroy(feedback);
+}
+static void feedback_discarded(void *data, struct wp_presentation_feedback *feedback) {
+ (void)data;
+ pending_feedback--;
+ wp_presentation_feedback_destroy(feedback);
+}
+static const struct wp_presentation_feedback_listener feedback_listener = {feedback_sync_output, feedback_presented,
+ feedback_discarded};
+
+static void frame_done(void *data, struct wl_callback *callback, uint32_t time);
+static const struct wl_callback_listener frame_listener = {frame_done};
+
+static void commit_frame(int x, int y) {
+ if (!mapped || !running || record_count >= MAX_RECORDS) return;
+ struct frame_buffer *b = NULL;
+ for (int i = 0; i < BUFFERS && !b; i++)
+ if (!buffers[i].busy) b = &buffers[i];
+ if (!b) return;
+ draw(b->pixels, x, y);
+ wl_surface_attach(surface, b->buffer, 0, 0);
+ b->busy = true;
+ wl_surface_damage_buffer(surface, 0, 0, W, H);
+ struct wp_presentation_feedback *feedback = wp_presentation_feedback(presentation, surface);
+ wp_presentation_feedback_add_listener(feedback, &feedback_listener, (void *)(intptr_t)record_count);
+ pending_feedback++;
+ if (paced) wl_callback_add_listener(wl_surface_frame(surface), &frame_listener, NULL);
+ records[record_count].commit_ns = now_ns();
+ record_count++;
+ wl_surface_commit(surface);
+ wl_display_flush(display);
+}
+
+static void frame_done(void *data, struct wl_callback *callback, uint32_t time) {
+ (void)data; (void)time;
+ wl_callback_destroy(callback);
+ frame_number++;
+ commit_frame(40 + (frame_number * 7) % (W - 80), H / 2);
+}
+
+static void pointer_enter(void *d, struct wl_pointer *p, uint32_t s, struct wl_surface *sf, wl_fixed_t x, wl_fixed_t y) {
+ (void)d; (void)p; (void)s; (void)sf; (void)x; (void)y;
+}
+static void pointer_leave(void *d, struct wl_pointer *p, uint32_t s, struct wl_surface *sf) {
+ (void)d; (void)p; (void)s; (void)sf;
+}
+static void pointer_motion(void *d, struct wl_pointer *p, uint32_t t, wl_fixed_t x, wl_fixed_t y) {
+ (void)d; (void)p; (void)t;
+ if (!paced) commit_frame(wl_fixed_to_int(x), wl_fixed_to_int(y));
+}
+static void pointer_button(void *d, struct wl_pointer *p, uint32_t s, uint32_t t, uint32_t b, uint32_t st) {
+ (void)d; (void)p; (void)s; (void)t; (void)b; (void)st;
+}
+static void pointer_axis(void *d, struct wl_pointer *p, uint32_t t, uint32_t a, wl_fixed_t v) {
+ (void)d; (void)p; (void)t; (void)a; (void)v;
+}
+static const struct wl_pointer_listener pointer_listener = {
+ .enter = pointer_enter, .leave = pointer_leave, .motion = pointer_motion, .button = pointer_button, .axis = pointer_axis};
+
+static void seat_capabilities(void *data, struct wl_seat *s, uint32_t caps) {
+ (void)data;
+ if (caps & WL_SEAT_CAPABILITY_POINTER) wl_pointer_add_listener(wl_seat_get_pointer(s), &pointer_listener, NULL);
+}
+static void seat_name(void *d, struct wl_seat *s, const char *n) { (void)d; (void)s; (void)n; }
+static const struct wl_seat_listener seat_listener = {.capabilities = seat_capabilities, .name = seat_name};
+
+static void wm_ping(void *d, struct xdg_wm_base *b, uint32_t serial) { (void)d; xdg_wm_base_pong(b, serial); }
+static const struct xdg_wm_base_listener wm_listener = {wm_ping};
+
+static void presentation_clock(void *d, struct wp_presentation *p, uint32_t id) { (void)d; (void)p; clock_id = id; }
+static const struct wp_presentation_listener presentation_listener = {presentation_clock};
+
+static void xdg_configure(void *d, struct xdg_surface *s, uint32_t serial) {
+ (void)d;
+ xdg_surface_ack_configure(s, serial);
+ if (!mapped) {
+ mapped = true;
+ commit_frame(W / 2, H / 2);
+ }
+}
+static const struct xdg_surface_listener xdg_listener = {xdg_configure};
+static void top_configure(void *d, struct xdg_toplevel *t, int32_t w, int32_t h, struct wl_array *s) {
+ (void)d; (void)t; (void)w; (void)h; (void)s;
+}
+static void top_close(void *d, struct xdg_toplevel *t) { (void)d; (void)t; running = false; }
+static const struct xdg_toplevel_listener top_listener = {.configure = top_configure, .close = top_close};
+
+static void global(void *d, struct wl_registry *r, uint32_t name, const char *iface, uint32_t version) {
+ (void)d;
+ if (!strcmp(iface, "wl_compositor")) compositor = wl_registry_bind(r, name, &wl_compositor_interface, 4);
+ else if (!strcmp(iface, "wl_shm")) shm = wl_registry_bind(r, name, &wl_shm_interface, 1);
+ else if (!strcmp(iface, "wl_seat")) seat = wl_registry_bind(r, name, &wl_seat_interface, 1);
+ else if (!strcmp(iface, "xdg_wm_base")) wm = wl_registry_bind(r, name, &xdg_wm_base_interface, 1);
+ else if (!strcmp(iface, "wp_presentation"))
+ presentation = wl_registry_bind(r, name, &wp_presentation_interface, version < 1 ? version : 1);
+}
+static void global_remove(void *d, struct wl_registry *r, uint32_t n) { (void)d; (void)r; (void)n; }
+static const struct wl_registry_listener registry_listener = {global, global_remove};
+
+int main(int argc, char **argv) {
+ if (argc != 4 || (strcmp(argv[1], "paced") && strcmp(argv[1], "event"))) {
+ fprintf(stderr, "usage: %s paced|event SECONDS OUTPUT_FILE\n", argv[0]);
+ return 2;
+ }
+ paced = !strcmp(argv[1], "paced");
+ double seconds = atof(argv[2]);
+ display = wl_display_connect(NULL);
+ if (!display) { fprintf(stderr, "no display\n"); return 1; }
+ struct wl_registry *registry = wl_display_get_registry(display);
+ wl_registry_add_listener(registry, &registry_listener, NULL);
+ wl_display_roundtrip(display);
+ if (!compositor || !shm || !wm || !presentation) { fprintf(stderr, "missing globals\n"); return 1; }
+ wp_presentation_add_listener(presentation, &presentation_listener, NULL);
+ xdg_wm_base_add_listener(wm, &wm_listener, NULL);
+ if (seat) wl_seat_add_listener(seat, &seat_listener, NULL);
+ wl_display_roundtrip(display);
+
+ int fd = memfd_create("frame-probe", 0);
+ size_t size = (size_t)W * H * 4;
+ if (fd < 0 || ftruncate(fd, size * BUFFERS) < 0) return 1;
+ uint32_t *map = mmap(NULL, size * BUFFERS, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
+ if (map == MAP_FAILED) return 1;
+ struct wl_shm_pool *pool = wl_shm_create_pool(shm, fd, size * BUFFERS);
+ for (int i = 0; i < BUFFERS; i++) {
+ buffers[i].pixels = map + (size / 4) * i;
+ buffers[i].buffer = wl_shm_pool_create_buffer(pool, size * i, W, H, W * 4, WL_SHM_FORMAT_XRGB8888);
+ wl_buffer_add_listener(buffers[i].buffer, &buffer_listener, &buffers[i]);
+ }
+
+ surface = wl_compositor_create_surface(compositor);
+ struct xdg_surface *xdg = xdg_wm_base_get_xdg_surface(wm, surface);
+ xdg_surface_add_listener(xdg, &xdg_listener, NULL);
+ struct xdg_toplevel *toplevel = xdg_surface_get_toplevel(xdg);
+ xdg_toplevel_add_listener(toplevel, &top_listener, NULL);
+ xdg_toplevel_set_app_id(toplevel, "frame-probe");
+ xdg_toplevel_set_title(toplevel, "frame probe");
+ wl_surface_commit(surface);
+
+ uint64_t end_ns = 0;
+ while (true) {
+ while (wl_display_prepare_read(display) != 0) wl_display_dispatch_pending(display);
+ wl_display_flush(display);
+ struct pollfd pfd = {wl_display_get_fd(display), POLLIN, 0};
+ poll(&pfd, 1, 20);
+ if (pfd.revents & POLLIN) wl_display_read_events(display);
+ else wl_display_cancel_read(display);
+ wl_display_dispatch_pending(display);
+ uint64_t now = now_ns();
+ if (mapped && !stop_ns) stop_ns = now + (uint64_t)(seconds * 1e9);
+ if (running && stop_ns && now >= stop_ns) {
+ running = false;
+ end_ns = now + 500000000ull;
+ }
+ if (!running && !end_ns) end_ns = now + 500000000ull;
+ if (!running && (pending_feedback <= 0 || now >= end_ns)) break;
+ }
+
+ FILE *out = fopen(argv[3], "w");
+ if (!out) return 1;
+ for (int i = 0; i < record_count; i++)
+ fprintf(out, "%llu %llu %u\n", (unsigned long long)records[i].commit_ns, (unsigned long long)records[i].presented_ns,
+ records[i].flags);
+ fclose(out);
+ return 0;
+}