1use crate::devtools_trace::{now_ms, DevtoolsTrace};
12use std::cell::Cell;
13use std::sync::Mutex;
14
15const CAPACITY: usize = 512;
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum TimelineKind {
21 CpuFrame,
23 GpuFrame,
25 Custom,
28}
29
30#[derive(Clone, Debug)]
32pub struct TimelineEntry {
33 pub timestamp_ms: u64,
34 pub kind: TimelineKind,
35 pub track: &'static str,
38 pub duration_ns: u64,
39 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 pub rebuilt: bool,
48 pub scoped_rebuilt: usize,
50 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
70thread_local! {
76 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
83fn 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
91pub fn set_enabled(on: bool) {
97 TRACE_ENABLED.with(|c| c.set(on));
98 with_trace(|t| t.set_enabled(on));
99}
100
101pub fn enabled() -> bool {
103 TRACE_ENABLED.with(|c| c.get())
104}
105
106pub fn clear() {
108 with_trace(|t| t.clear());
109}
110
111#[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 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
153pub 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
180pub 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
210pub 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
238fn 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
256pub 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
295fn 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
311fn csv_field(s: &str) -> String {
313 if s.contains([',', '"', '\n', '\r']) {
314 format!("\"{}\"", s.replace('"', "\"\""))
315 } else {
316 s.to_owned()
317 }
318}
319
320pub 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#[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); 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 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 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}