深度解析:RedrawState 状态机与帧回调节流机制)
niri 重绘循环Redraw Loop深度解析RedrawState 状态机与帧回调节流机制【免费下载链接】niriA scrollable-tiling Wayland compositor.项目地址: https://gitcode.com/GitHub_Trending/ni/niriniri 是一款可滚动平铺的 Wayland 合成器其渲染管线以输出output重绘为基本单位。在 TTY 环境下每个输出同一时刻只能向内核提交一帧画面合成器必须等到下一次 VBlank 事件后才能提交新帧。本文围绕官方开发文档 Development: Redraw-Loop 展开深入剖析 niri 内部用于协调重绘与 VBlank 节奏的RedrawState状态机并结合源码说明其如何通过帧回调frame callback节流来避免应用空转浪费 CPU。读完本文你将掌握 niri 从画面需要更新到帧真正呈现的完整调用链以及每个状态存在的底层原因。一、问题背景为什么重绘不能随叫随到在 Wayland 合成器中屏幕需要更新和帧真正提交给显示硬件是两件不同步的事。文档开篇就点明了约束的核心On a TTY, only one frame can be submitted to an output at a time, and the compositor must wait until the output repaints (indicated by a VBlank) to be able to submit the next frame.即在 TTYKMS/DRM环境下同一输出同时只能提交一帧帧提交后必须等待硬件完成呈现、产生 VBlank 信号才能提交下一帧。如果合成器无视这一节律盲目提交就会导致撕裂tearing或帧排队混乱。niri 解决这一问题的做法是在每个OutputState中维护一个名为RedrawState的状态枚举用一套显式的状态机来跟踪这个输出当前处于重绘流程的哪个阶段。定义位于 src/niri.rs#[derive(Debug, Default)] pub enum RedrawState { /// The compositor is idle. #[default] Idle, /// A redraw is queued. Queued, /// We submitted a frame to the KMS and waiting for it to be presented. WaitingForVBlank { redraw_needed: bool }, /// We did not submit anything to KMS and made a timer to fire at the estimated VBlank. WaitingForEstimatedVBlank(RegistrationToken), /// A redraw is queued on top of the above. WaitingForEstimatedVBlankAndQueued(RegistrationToken), }从源码结构看这套状态机共包含五个状态分别对应重绘流程中的五个阶段空闲、已排队、等待真实 VBlank、等待估计 VBlank以及在等待估计 VBlank 期间又有新重绘请求的复合状态。二、状态机全景一张图看懂五个状态的流转官方文档给出了RedrawState的完整状态转移图同时提供深色与浅色两个版本随系统配色自动切换整张图的逻辑可以用一句话概括从Idle出发经过Queued进入真正渲染渲染产生 damage 则等待 VBlank不产生 damage 则等待估计 VBlank最终总是回到Idle或再次进入Queued。三、五个状态逐一解析结合 src/niri.rs 中每个变体的源码注释各状态含义如下状态含义触发进入的途径Idle输出空闲当前不需要重绘重绘完成且无后续请求默认初始状态Queued已有一次重绘被排队任何可能导致屏幕更新的操作调用queue_redraw()WaitingForVBlank { redraw_needed }帧已提交给 KMS正在等待呈现真实 VBlankredraw_needed标记 VBlank 后是否还需再重绘redraw()渲染产生了 damage提交帧后WaitingForEstimatedVBlank(token)未向 KMS 提交任何内容而是设了一个定时器让其大约在下一个 VBlank 时刻触发redraw()渲染没有产生 damage不提交帧WaitingForEstimatedVBlankAndQueued(token)在等待估计 VBlank 的期间又收到了一次新的重绘请求处于WaitingForEstimatedVBlank时再次调用queue_redraw()其中WaitingForVBlank { redraw_needed: bool }这个字段值得特别说明当输出已经向 KMS 提交了一帧、正在等待 VBlank 时如果期间又发生了需要重绘的事件niri 不会粗暴打断当前提交而是把redraw_needed置为true等 VBlank 到来后再补一次重绘见下文queue_redraw()的源码。四、状态转移的源码级实现4.1 入队queue_redraw()文档指出任何可能导致屏幕更新的操作都会调用queue_redraw()使输出进入Queued状态。这是整个状态机的唯一入口其实现位于 src/niri.rsimpl RedrawState { fn queue_redraw(self) - Self { match self { RedrawState::Idle RedrawState::Queued, RedrawState::WaitingForEstimatedVBlank(token) { RedrawState::WaitingForEstimatedVBlankAndQueued(token) } // A redraw is already queued. value (RedrawState::Queued | RedrawState::WaitingForEstimatedVBlankAndQueued(_)) { value } // Were waiting for VBlank, request a redraw afterwards. RedrawState::WaitingForVBlank { .. } RedrawState::WaitingForVBlank { redraw_needed: true, }, } } }这段代码体现了四个关键设计决策Idle → Queued空闲时收到重绘请求直接入队WaitingForEstimatedVBlank → WaitingForEstimatedVBlankAndQueued正在等估计 VBlank 时又来新请求不取消原定时器而是叠加一个排队标记VBlank 定时器触发后立即补做一次重绘幂等如果已经处于Queued或WaitingForEstimatedVBlankAndQueued重复请求直接忽略A redraw is already queued避免重复渲染浪费WaitingForVBlank → WaitingForVBlank { redraw_needed: true }正在等真实 VBlank 时把需求记入redraw_needed待 VBlank 事件处理时再决定是否补帧。对外暴露的入口有两个位于 src/niri.rs/// Schedules an immediate redraw on all outputs if one is not already scheduled. pub fn queue_redraw_all(mut self) { for state in self.output_state.values_mut() { state.redraw_state mem::take(mut state.redraw_state).queue_redraw(); } } /// Schedules an immediate redraw if one is not already scheduled. pub fn queue_redraw(mut self, output: Output) { let state self.output_state.get_mut(output).unwrap(); state.redraw_state mem::take(mut state.redraw_state).queue_redraw(); }queue_redraw_all()遍历所有输出例如全局动画、光标移动、桌面状态变化时使用queue_redraw(output)则只针对单个输出例如某个窗口或 layer-surface 的内容更新。从调用点来看输入处理src/input/mod.rs、xdg-shell 与 layer-shell 处理器src/handlers/xdg_shell.rs、src/handlers/layer_shell.rs、IPC 服务器src/ipc/server.rs等模块都会在事件发生时触发重绘请求。4.2 统一出队redraw_queued_outputs()queue_redraw()只负责记账真正的渲染动作发生在事件循环一次分发dispatch的末尾。文档描述为在事件循环分发结束时niri 为每个Queued输出调用redraw()。实现位于 src/niri.rs采用while循环持续扫描保证处理过程中新排队的输出也能在同一次分发中被渲染pub fn redraw_queued_outputs(mut self, backend: mut Backend) { let _span tracy_client::span!(Niri::redraw_queued_outputs); while let Some((output, _)) self.output_state.iter().find(|(_, state)| { matches!( state.redraw_state, RedrawState::Queued | RedrawState::WaitingForEstimatedVBlankAndQueued(_) ) }) { trace!(redrawing output); let output output.clone(); self.redraw(backend, output); } }注意它只匹配Queued和WaitingForEstimatedVBlankAndQueued两种状态——这正是redraw()入口断言所要求的见下文。这也意味着处于WaitingForVBlank帧已提交等待呈现或WaitingForEstimatedVBlank等待定时器状态的输出不会被提前打扰。4.3 核心渲染redraw()redraw()是单个输出的实际渲染函数位于 src/niri.rs。其开头先验证不变式invariant确保调用时机正确fn redraw(mut self, backend: mut Backend, output: Output) { let _span tracy_client::span!(Niri::redraw); // Verify our invariant. let state self.output_state.get_mut(output).unwrap(); assert!(matches!( state.redraw_state, RedrawState::Queued | RedrawState::WaitingForEstimatedVBlankAndQueued(_) )); ...随后它完成了一系列关键步骤可以概括为确定目标呈现时间 → 冻结动画时钟 → 渲染 → 依据结果更新状态 → 发送帧回调确定目标呈现时间调用state.frame_clock.next_presentation_time()算出这一帧预计呈现的时刻冻结动画时钟self.clock.set_unadjusted(target_presentation_time)让所有动画以目标呈现时间为基准推进保证动画的每一帧都对应到真实的硬件刷新时刻这一点与 Development: Animation-Timing 中的计时思路一致更新渲染元素self.update_render_elements(Some(output))重建该输出上的所有渲染元素窗口、边框、光标、layer-surface 等检查是否有未完成的动画依次检查布局动画、配置错误通知、退出确认对话框、截图 UI、窗口 MRU UI、屏幕转场、光标动画以及 layer-surface 动画任何一个仍在进行都会让unfinished_animations_remain为真从而驱动后续持续重绘真正渲染res backend.render(self, output, target_presentation_time)交给后端执行依据渲染结果更新状态机见下文发送帧回调并处理 screencast / screencopy。渲染结果如何决定下一个状态redraw()的第 56 步是状态机最精妙的部分。渲染结果有三种可能分别对应不同的状态迁移if res RenderResult::Skipped { // Update the redraw state on failed render. state.redraw_state if let RedrawState::WaitingForEstimatedVBlank(token) | RedrawState::WaitingForEstimatedVBlankAndQueued(token) state.redraw_state { RedrawState::WaitingForEstimatedVBlank(token) } else { RedrawState::Idle }; }结合文档描述可以整理出三条路径渲染产生了 damage画面有实际变化帧被提交给 KMS进入WaitingForVBlank等待真实 VBlank 事件到来后才能提交下一帧渲染没有产生 damage画面无变化不会立即回到Idle而是设置一个定时器、让其在大约下一次 VBlank 时刻触发进入WaitingForEstimatedVBlank渲染失败被跳过RenderResult::Skipped恢复为进入前的状态若是从估计 VBlank 路径来的则维持该定时器否则回到Idle。文档特别强调了第二点的重要性This is necessary in order to throttle frame callbacks sent to applications to at most once per output refresh cycle. Without this throttling, applications can start continuously redrawing without damage (for instance, if the application window is partially off-screen, and it is only the off-screen part that changes), and eating a lot of CPU in the process.即使没有 damage也要按刷新周期空走一遍重绘流程目的是把发送给应用的帧回调限制在每个输出刷新周期最多一次。如果省掉这一步应用就可能陷入无 damage 的连续重绘典型场景窗口部分在屏幕外只有屏幕外部分发生变化从而持续消耗大量 CPU。等待估计 VBlank 的两个出口文档描述了该状态的两种结束方式Then, either the estimated VBlank timer completes, and we go back toIdle, or maybe we callqueue_redraw()once more and try to redraw again.定时器正常触发且没有新的重绘请求 → 回到Idle定时器触发前又收到了queue_redraw()→ 状态变成WaitingForEstimatedVBlankAndQueued定时器触发后立刻再走一遍redraw()。从状态机的角度WaitingForEstimatedVBlankAndQueued是一个复合态它保证 niri 既不会错过新事件也不会破坏既定的刷新节律——定时器仍然按估计 VBlank 触发只是触发后的动作从回到 Idle变成补一次重绘。五、帧回调节流为什么每个刷新周期只发一次5.1 帧回调与空转陷阱在 Wayland 协议中应用通过请求frame callback来与合成器的刷新节奏同步应用收到回调后才会渲染下一帧。如果合成器无条件、频繁地发送帧回调应用就会以最高速率持续渲染提交——即使画面根本没有实际变化如部分离屏的窗口白白烧掉 CPU。这正是文档中eating a lot of CPU警告的由来。5.2 实现一FrameClock 估算呈现时间估计 VBlank 定时器该设在什么时候由 src/frame_clock.rs 中的FrameClock负责。它记录上一次呈现时间last_presentation_time与输出刷新间隔refresh_interval_ns通过next_presentation_time()计算下一帧应该在哪个时刻呈现正常情况下取last_presentation_time 整数倍刷新间隔中下一个未来的时刻若收到提前的 VBlanknow last_presentation_time自动顺延一个刷新间隔若开启 VRR可变刷新率且自上次呈现已超过一个刷新周期则允许立即呈现self.vrr to_next_ns refresh_interval_ns时直接返回now。redraw()中state.frame_clock.next_presentation_time()返回的值既被用作clock.set_unadjusted()的动画时间基准也被传入backend.render()作为目标呈现时间从而把何时画、画到哪一帧与何时真正上屏统一起来。5.3 实现二每个表面记录上次回调时刻除了全局的frame_callback_sequence序列号niri 还给每个 surface 维护了 SurfaceFrameThrottlingState// Not related to the one in Smithay. // // This state keeps track of when a surface last received a frame callback. struct SurfaceFrameThrottlingState { /// Output and sequence that the frame callback was last sent at. last_sent_at: RefCellOption(Output, u32), }send_frame_callbacks()src/niri.rs在发送帧回调前的判据非常直白// If we already sent a frame callback to this surface this output refresh // cycle, dont send one again to prevent empty-damage commit busy loops. if let Some((last_output, last_sequence)) *last_sent_at { if last_output output *last_sequence sequence { send false; } }同一个输出、同一个刷新序列号每个 surface 至多收到一次帧回调。这从机制上杜绝了应用提交空 damage → 合成器发回调 → 应用再提交空 damage的忙碌循环。此外should_send闭包还做了主扫描输出primary scanout output检查只有当前主扫描输出与正在重绘的输出一致时才会发送回调这既为指针表面在多个输出间去重也避免向不可见表面发送帧回调。回调覆盖的对象包括布局中的窗口、layer-shell 表面、锁屏表面、拖拽图标DnD icon以及光标表面。5.4 兜底1 秒一次的 fallback 定时器并不是所有窗口在每一帧都可见例如在平铺布局中被完全遮挡的窗口。为了不让这些窗口饿死——永远收不到帧回调而无法推进自己的动画——niri 还注册了一个周期为 1 秒的兜底定时器src/niri.rsevent_loop .insert_source( Timer::from_duration(Duration::from_secs(1)), |_, _, state| { state.niri.send_frame_callbacks_on_fallback_timer(); TimeoutAction::ToDuration(Duration::from_secs(1)) }, ) .unwrap();send_frame_callbacks_on_fallback_timer()src/niri.rs会构造一个假的空输出大小 0×0、名称空字符串向所有窗口、layer-shell 表面、锁屏表面等统一发送帧回调。这个每秒一次的节拍保证了隐藏窗口至少能以 1 FPS 的速率推进同时又不至于造成明显 CPU 开销。5.5 防御VBlankThrottle 处理过早的 VBlank作为节流的最后一道防线src/utils/vblank_throttle.rs 专门应对某些有问题的显卡驱动提前发送 VBlank的情况。其模块注释写得很清楚Some buggy drivers deliver VBlanks way earlier than necessary. This helper throttles the VBlank in such cases to avoid tearing and to get more consistent timings.实现逻辑是记录上一次 VBlank 时间戳若本次 VBlank 距离上次的时间不足半个刷新周期passed refresh / 2则不直接当作 VBlank 处理而是注册一个定时器在剩余时间refresh - passed之后才真正触发回调同时只打印一次警告output ... running faster than expected, throttling vblanks避免刷屏。这样一来即使驱动过于积极niri 也能维持一致的呈现节奏避免撕裂。六、一次完整重绘的时序回顾把上面的机制串起来niri 在 TTY 后端下一次典型重绘的完整生命周期如下某事件发生窗口提交新内容、光标移动、动画推进等调用queue_redraw(output)或queue_redraw_all()输出进入Queued事件循环分发结束redraw_queued_outputs()找出所有Queued/WaitingForEstimatedVBlankAndQueued输出逐个调用redraw()redraw()用FrameClock::next_presentation_time()确定目标呈现时间、冻结动画时钟、重建渲染元素并渲染若渲染产生 damage帧提交 KMS进入WaitingForVBlank { redraw_needed }待 VBlank 事件经VBlankThrottle过滤到达后再决定是否补帧若渲染无 damage不提交帧设置估计 VBlank定时器进入WaitingForEstimatedVBlank把帧回调节流在每刷新周期一次redraw()末尾调用send_frame_callbacks()向主扫描输出上的可见表面发送帧回调受序列号与SurfaceFrameThrottlingState双重去重定时器触发若无新请求则回Idle若有则经WaitingForEstimatedVBlankAndQueued补一次重绘被遮挡的窗口则依赖 1 秒兜底定时器获得帧回调。七、延伸与相关阅读重绘循环是 niri 渲染与动画体系的基石与之紧密相关的还有Development: Animation-Timing动画时钟如何以目标呈现时间为基准推进与clock.set_unadjusted()直接关联Development: Redraw-Loop本文所依据的官方开发文档后端差异本机制在 TTY 后端src/backend/tty.rs下最为关键因为它受 KMS 单帧提交约束而 winit 与 headless 后端src/backend/winit.rs、src/backend/headless.rs同样复用RedrawState与queue_redraw接口保持了状态机逻辑的统一性能观测redraw、redraw_queued_outputs、send_frame_callbacks等关键路径均埋有tracy_client::span!可用 Tracy Profiler 直观观测每次重绘的耗时与触发频率。八、小结RedrawState状态机是 niri 在 TTY 单帧提交约束下保证渲染节奏与硬件刷新节奏对齐的核心抽象。它以五个状态精确刻画了空闲 → 排队 → 渲染 → 等待 VBlank/估计 VBlank的完整闭环并通过帧回调节流、估计 VBlank 定时器、1 秒兜底定时器与 VBlankThrottle 四层机制从根上杜绝了应用无 damage 空转导致的 CPU 浪费。理解这套状态机也就理解了 niri 渲染管线高效与省电的底层原因。【免费下载链接】niriA scrollable-tiling Wayland compositor.项目地址: https://gitcode.com/GitHub_Trending/ni/niri创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考