Skip to main content

mgui_core/
frame_timeline.rs

1//! DT-03 统一帧时间线:把 CPU frame pipeline / GPU timestamp query 与
2//! **任意扩展轨道**对齐到同一条单调时间轴。
3//!
4//! 框架只认识自己的两条轨道(CPU/GPU);扩展组件(如视频)用 [`push`] 以
5//! 自带的名字注册轨道("VideoDecode" 之类),DevTools 只透传显示轨道名,
6//! 不认识任何具体扩展 —— 组件是扩展,可观测设施是框架级,两边不互相定制。
7//!
8//! 存储基础设施复用 [`crate::devtools_trace::DevtoolsTrace`](三处 trace 共用同一套)。
9//! 开关默认关闭;关闭时入口先做一次 thread-local 开关判断就返回,不拿锁、不构造记录。
10
11use crate::devtools_trace::{now_ms, DevtoolsTrace};
12use std::cell::Cell;
13use std::sync::Mutex;
14
15const CAPACITY: usize = 512;
16
17/// 时间线条目类型。框架级只有 CPU/GPU 两条;扩展组件走 [`TimelineKind::Custom`],
18/// 轨道名由调用方自带(见 [`TimelineEntry::track`])。
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum TimelineKind {
21    /// CPU 帧管线一帧:六个阶段的完整统计
22    CpuFrame,
23    /// GPU 一次 render pass 的 timestamp query 结果
24    GpuFrame,
25    /// 扩展组件注册的轨道(视频、音频、任何长时间运行的子系统)。
26    /// DevTools 只显示名字,不理解语义 —— 那是扩展自己的事。
27    Custom,
28}
29
30/// 统一时间线的一条记录。
31#[derive(Clone, Debug)]
32pub struct TimelineEntry {
33    pub timestamp_ms: u64,
34    pub kind: TimelineKind,
35    /// 扩展轨道的名字(`kind == Custom` 时由调用方给,如 `"VideoDecode"`)。
36    /// 框架级两条轨道此字段为空串,`kind_label` 走固定名。
37    pub track: &'static str,
38    pub duration_ns: u64,
39    /// CPU FrameStats 六阶段拆分(仅 CpuFrame 有意义;其他为 0)
40    pub head_ns: u64,
41    pub rebuild_ns: u64,
42    pub after_tick_ns: u64,
43    pub overlay_ns: u64,
44    pub paint_ns: u64,
45    pub layout_ns: u64,
46    /// 本帧是否有全树 rebuild(CpuFrame)
47    pub rebuilt: bool,
48    /// 本帧 scoped dirty rebuild 的 element 数(CpuFrame)
49    pub scoped_rebuilt: usize,
50    /// 业务侧可选 detail(如 video session id / overlay name)
51    pub detail: String,
52}
53
54impl TimelineEntry {
55    pub fn kind_label(&self) -> &'static str {
56        match self.kind {
57            TimelineKind::CpuFrame => "CPU",
58            TimelineKind::GpuFrame => "GPU",
59            TimelineKind::Custom => {
60                if self.track.is_empty() {
61                    "custom"
62                } else {
63                    self.track
64                }
65            }
66        }
67    }
68}
69
70// ============================================================
71// 线程级全局 trace(mgui 单 UI 线程模型,用 thread_local 零竞争)
72// DevtoolsTrace 本身用 Mutex——单线程无竞争 ≈ RefCell
73// ============================================================
74
75thread_local! {
76    /// 开关镜像:让关闭路径在拿 TRACE 锁之前就能返回。
77    /// DevtoolsTrace 自己的 enabled 在锁内,只查它会先付出一次锁成本。
78    static TRACE_ENABLED: Cell<bool> = const { Cell::new(false) };
79    static TRACE: Mutex<DevtoolsTrace<TimelineEntry>> =
80        std::sync::Mutex::new(DevtoolsTrace::new(CAPACITY));
81}
82
83/// 在 TRACE 上执行一个闭包。Mutex 保护单线程不会重入。
84fn with_trace<R>(f: impl FnOnce(&DevtoolsTrace<TimelineEntry>) -> R) -> R {
85    TRACE.with(|t| {
86        let guard = t.lock().unwrap_or_else(|e| e.into_inner());
87        f(&guard)
88    })
89}
90
91// ============================================================
92// 公共 API(与原 API 完全保持一致,调用方零改动)
93// ============================================================
94
95/// DT-03:开启/关闭 frame timeline 采集。默认关闭(零开销)。
96pub fn set_enabled(on: bool) {
97    TRACE_ENABLED.with(|c| c.set(on));
98    with_trace(|t| t.set_enabled(on));
99}
100
101/// DT-03:是否正在采集 frame timeline。只读 thread-local 镜像,不拿锁。
102pub fn enabled() -> bool {
103    TRACE_ENABLED.with(|c| c.get())
104}
105
106/// DT-03:清空 timeline(切换窗口会话时)。
107pub fn clear() {
108    with_trace(|t| t.clear());
109}
110
111/// DT-03:记录一次完整的 CPU 帧管线统计(由 `run_frame` 末尾调)。
112#[allow(clippy::too_many_arguments)]
113pub fn push_cpu_frame(
114    head_ns: u64,
115    rebuild_ns: u64,
116    after_tick_ns: u64,
117    overlay_ns: u64,
118    paint_ns: u64,
119    layout_ns: u64,
120    rebuilt: bool,
121    scoped_rebuilt: usize,
122) {
123    if !enabled() {
124        return;
125    }
126    with_trace(|t| {
127        // 关闭时必须先返回,避免 now_ms / 结构体构造仍然发生。
128        if !t.enabled() {
129            return;
130        }
131        t.push(TimelineEntry {
132            timestamp_ms: now_ms(),
133            kind: TimelineKind::CpuFrame,
134            track: "",
135            duration_ns: head_ns
136                .saturating_add(rebuild_ns)
137                .saturating_add(after_tick_ns)
138                .saturating_add(overlay_ns)
139                .saturating_add(paint_ns),
140            head_ns,
141            rebuild_ns,
142            after_tick_ns,
143            overlay_ns,
144            paint_ns,
145            layout_ns,
146            rebuilt,
147            scoped_rebuilt,
148            detail: String::new(),
149        })
150    });
151}
152
153/// DT-03:记录一次 GPU render pass timestamp query 结果(由 GpuProfiler.resolve 调)。
154pub fn push_gpu_frame(gpu_ns: u64) {
155    if !enabled() {
156        return;
157    }
158    with_trace(|t| {
159        if !t.enabled() {
160            return;
161        }
162        t.push(TimelineEntry {
163            timestamp_ms: now_ms(),
164            kind: TimelineKind::GpuFrame,
165            track: "",
166            duration_ns: gpu_ns,
167            head_ns: 0,
168            rebuild_ns: 0,
169            after_tick_ns: 0,
170            overlay_ns: 0,
171            paint_ns: 0,
172            layout_ns: 0,
173            rebuilt: false,
174            scoped_rebuilt: 0,
175            detail: String::new(),
176        })
177    });
178}
179
180/// DT-03:记录一条扩展轨道(由扩展组件调,如视频的 decode / take / input)。
181///
182/// `track` 是扩展自己起的名字(`'static` 是因为它是编译期常量标签,不入 detail 的
183/// 运行时分配路径)。框架与 DevTools 都不解释它 —— 扩展组件换了名字,面板照常显示。
184pub fn push(track: &'static str, duration_ns: u64, detail: impl Into<String>) {
185    if !enabled() {
186        return;
187    }
188    with_trace(|t| {
189        if !t.enabled() {
190            return;
191        }
192        t.push(TimelineEntry {
193            timestamp_ms: now_ms(),
194            kind: TimelineKind::Custom,
195            track,
196            duration_ns,
197            head_ns: 0,
198            rebuild_ns: 0,
199            after_tick_ns: 0,
200            overlay_ns: 0,
201            paint_ns: 0,
202            layout_ns: 0,
203            rebuilt: false,
204            scoped_rebuilt: 0,
205            detail: detail.into(),
206        })
207    });
208}
209
210/// DT-03 导出:最近 `max` 条时间线的 JSON(`max == 0` = 全部)。
211/// 手写序列化(本 crate 不加 serde):detail 里的引号/反斜杠/控制符必须转义,
212/// 否则一条带特殊字符的会话名就能让整个导出成不了 JSON。
213pub fn export_json(max: usize) -> String {
214    let entries = peek(max);
215    let mut out = String::from("[\n");
216    for (i, e) in entries.iter().enumerate() {
217        if i > 0 {
218            out.push_str(",\n");
219        }
220        let _ = std::fmt::Write::write_fmt(
221            &mut out,
222            format_args!(
223                "  {{\"t_ms\":{},\"track\":\"{}\",\"kind\":\"{}\",\"dur_ms\":{:.3},\"detail\":\"{}\"{}",
224                e.timestamp_ms,
225                escape_json(e.track),
226                escape_json(e.kind_label()),
227                e.duration_ns as f64 / 1_000_000.0,
228                escape_json(&e.detail),
229                cpu_breakdown_json(e),
230            ),
231        );
232        out.push('}');
233    }
234    out.push_str("\n]\n");
235    out
236}
237
238/// CpuFrame 的六阶段拆分(其他轨道这六项全 0,不输出假字段)。
239fn cpu_breakdown_json(e: &TimelineEntry) -> String {
240    if !matches!(e.kind, TimelineKind::CpuFrame) {
241        return String::new();
242    }
243    format!(
244        ",\"head_ms\":{:.3},\"rebuild_ms\":{:.3},\"after_tick_ms\":{:.3},\"overlay_ms\":{:.3},\"paint_ms\":{:.3},\"layout_ms\":{:.3},\"rebuilt\":{},\"scoped_rebuilt\":{}",
245        e.head_ns as f64 / 1_000_000.0,
246        e.rebuild_ns as f64 / 1_000_000.0,
247        e.after_tick_ns as f64 / 1_000_000.0,
248        e.overlay_ns as f64 / 1_000_000.0,
249        e.paint_ns as f64 / 1_000_000.0,
250        e.layout_ns as f64 / 1_000_000.0,
251        e.rebuilt,
252        e.scoped_rebuilt,
253    )
254}
255
256/// DT-03 导出:最近 `max` 条时间线的 CSV(`max == 0` = 全部)。表头平铺六阶段,
257/// 非 CPU 轨道留空 —— 与 JSON 的"不输出假字段"同一条纪律的 CSV 表达。
258pub fn export_csv(max: usize) -> String {
259    let entries = peek(max);
260    let mut out = String::from(
261        "t_ms,track,kind,dur_ms,detail,head_ms,rebuild_ms,after_tick_ms,overlay_ms,paint_ms,layout_ms,rebuilt,scoped_rebuilt\n",
262    );
263    for e in &entries {
264        let cpu = if matches!(e.kind, TimelineKind::CpuFrame) {
265            format!(
266                "{:.3},{:.3},{:.3},{:.3},{:.3},{:.3},{},{}",
267                e.head_ns as f64 / 1_000_000.0,
268                e.rebuild_ns as f64 / 1_000_000.0,
269                e.after_tick_ns as f64 / 1_000_000.0,
270                e.overlay_ns as f64 / 1_000_000.0,
271                e.paint_ns as f64 / 1_000_000.0,
272                e.layout_ns as f64 / 1_000_000.0,
273                e.rebuilt,
274                e.scoped_rebuilt,
275            )
276        } else {
277            String::from(",,,,,,,,")
278        };
279        let _ = std::fmt::Write::write_fmt(
280            &mut out,
281            format_args!(
282                "{},{},{},{:.3},\"{}\",{}\n",
283                e.timestamp_ms,
284                csv_field(e.track),
285                csv_field(e.kind_label()),
286                e.duration_ns as f64 / 1_000_000.0,
287                csv_field(&e.detail),
288                cpu,
289            ),
290        );
291    }
292    out
293}
294
295/// JSON 字符串转义(引号、反斜杠、控制符;detail/track 是外部输入,不可信)。
296fn escape_json(s: &str) -> String {
297    let mut out = String::with_capacity(s.len());
298    for c in s.chars() {
299        match c {
300            '"' => out.push_str("\\\""),
301            '\\' => out.push_str("\\\\"),
302            c if (c as u32) < 0x20 => {
303                let _ = std::fmt::Write::write_fmt(&mut out, format_args!("\\u{:04x}", c as u32));
304            }
305            c => out.push(c),
306        }
307    }
308    out
309}
310
311/// CSV 字段:含逗号/引号/换行的字段按 RFC 4180 加引号转义。
312fn csv_field(s: &str) -> String {
313    if s.contains([',', '"', '\n', '\r']) {
314        format!("\"{}\"", s.replace('"', "\"\""))
315    } else {
316        s.to_owned()
317    }
318}
319
320/// DT-03:取最近 `max` 条 timeline(不 drain,可重复调用)。关闭时返回空,不构造快照。
321pub fn peek(max: usize) -> Vec<TimelineEntry> {
322    if !enabled() {
323        return Vec::new();
324    }
325    with_trace(|t| {
326        if !t.enabled() {
327            return Vec::new();
328        }
329        t.peek(max)
330    })
331}
332
333// ============================================================
334// 单元测试
335// ============================================================
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340
341    fn reset() {
342        set_enabled(true);
343        clear();
344    }
345
346    fn cleanup() {
347        clear();
348        set_enabled(false);
349    }
350
351    #[test]
352    fn disabled_push_is_noop() {
353        set_enabled(false);
354        clear();
355        push_cpu_frame(1, 2, 3, 4, 5, 1, false, 0);
356        push_gpu_frame(100);
357        assert!(peek(0).is_empty());
358    }
359
360    #[test]
361    fn clear_works_while_disabled() {
362        reset();
363        push_cpu_frame(1, 2, 3, 4, 5, 1, false, 0);
364        assert_eq!(peek(0).len(), 1);
365
366        set_enabled(false);
367        clear();
368        set_enabled(true);
369        assert!(peek(0).is_empty(), "关闭期间的显式 clear 必须生效");
370        cleanup();
371    }
372
373    #[test]
374    fn disabled_custom_push_does_not_materialize_detail() {
375        use std::cell::Cell;
376        use std::rc::Rc;
377
378        struct LazyDetail(Rc<Cell<bool>>);
379
380        impl From<LazyDetail> for String {
381            fn from(v: LazyDetail) -> Self {
382                v.0.set(true);
383                String::from("materialized")
384            }
385        }
386
387        set_enabled(false);
388        clear();
389        let called = Rc::new(Cell::new(false));
390        push("VideoTake", 1, LazyDetail(called.clone()));
391        push("VideoDecode", 1, LazyDetail(called.clone()));
392        assert!(!called.get(), "关闭时不应构造扩展 detail");
393        cleanup();
394    }
395
396    #[test]
397    fn enabled_collects_cpu_and_gpu() {
398        reset();
399        push_cpu_frame(100, 200, 50, 100, 500, 80, false, 3);
400        push_gpu_frame(300);
401        push_cpu_frame(120, 250, 60, 90, 550, 90, true, 0);
402        let snap = peek(0);
403        assert_eq!(snap.len(), 3);
404        assert!(matches!(snap[0].kind, TimelineKind::CpuFrame));
405        assert_eq!(snap[0].duration_ns, 950); // 100+200+50+100+500
406        assert!(matches!(snap[1].kind, TimelineKind::GpuFrame));
407        assert_eq!(snap[1].duration_ns, 300);
408        assert!(snap[2].rebuilt);
409        assert_eq!(snap[2].scoped_rebuilt, 0);
410        cleanup();
411    }
412
413    #[test]
414    fn capacity_evicts_oldest() {
415        reset();
416        for i in 0..CAPACITY + 10 {
417            push_cpu_frame(i as u64, 0, 0, 0, 0, 0, false, 0);
418        }
419        let snap = peek(0);
420        assert_eq!(snap.len(), CAPACITY);
421        assert_eq!(snap[0].head_ns, 10);
422        cleanup();
423    }
424
425    #[test]
426    fn max_truncates_recent() {
427        reset();
428        for i in 0..20 {
429            push_cpu_frame(i, 0, 0, 0, 0, 0, false, 0);
430        }
431        let snap = peek(5);
432        assert_eq!(snap.len(), 5);
433        assert_eq!(snap[0].head_ns, 15);
434        assert_eq!(snap[4].head_ns, 19);
435        cleanup();
436    }
437
438    #[test]
439    fn custom_tracks_recorded_with_their_own_names() {
440        reset();
441        // 扩展组件用自己的名字注册轨道;框架只保证它们同轴、同格式。
442        push("VideoTake", 1500, "cam-01");
443        push("VideoDecode", 25_000, "cam-01");
444        push("VideoInput", 5_000, "cam-01");
445        let snap = peek(0);
446        assert_eq!(snap.len(), 3);
447        assert!(matches!(snap[0].kind, TimelineKind::Custom));
448        assert_eq!(snap[0].track, "VideoTake");
449        assert_eq!(snap[0].kind_label(), "VideoTake");
450        assert_eq!(snap[0].duration_ns, 1500);
451        assert_eq!(snap[0].detail, "cam-01");
452        assert_eq!(snap[1].track, "VideoDecode");
453        assert_eq!(snap[2].track, "VideoInput");
454        cleanup();
455    }
456
457    #[test]
458    fn export_formats_escape_and_omit_fake_fields() {
459        reset();
460        push("VideoTake", 1_500_000, "cam-\"01\"");
461        // 各段给足纳秒,毫秒三位小数不至于全舍成 0。
462        push_cpu_frame(100_000, 200_000, 50_000, 100_000, 500_000, 80_000, true, 3);
463        let json = export_json(0);
464        assert!(json.starts_with("[\n"), "JSON 该以数组起头:{json}");
465        assert!(json.contains("cam-\\\"01\\\""), "detail 里的引号必须转义:{json}");
466        assert!(json.contains("\"rebuilt\":true"), "CpuFrame 要带六阶段与 rebuild 标记:{json}");
467        let video_line = json.lines().find(|l| l.contains("VideoTake")).expect("有 VideoTake 行");
468        assert!(!video_line.contains("head_ms"), "非 CPU 轨道不许输出假拆分:{video_line}");
469        let csv = export_csv(0);
470        let lines: Vec<&str> = csv.lines().collect();
471        assert_eq!(lines.len(), 3, "表头 + 两条:{csv}");
472        assert!(lines[1].contains("\"cam-\"\"01\"\""), "CSV 含引号的字段必须 RFC4180 引号包裹:{csv}");
473        assert!(lines[2].contains("true,3"), "CpuFrame 行的 rebuilt/scoped 要落在末尾两列:{csv}");
474        assert_eq!(export_json(1).matches("\"t_ms\"").count(), 1, "max 截断只留最近一条");
475        cleanup();
476    }
477
478    #[test]
479    fn clear_empties() {
480        reset();
481        for _ in 0..10 {
482            push_cpu_frame(1, 0, 0, 0, 0, 0, false, 0);
483        }
484        clear();
485        assert!(peek(0).is_empty());
486        cleanup();
487    }
488}