use crate::devtools_trace::{now_ms, DevtoolsTrace};
use std::cell::Cell;
use std::sync::Mutex;
const CAPACITY: usize = 512;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TimelineKind {
CpuFrame,
GpuFrame,
Custom,
}
#[derive(Clone, Debug)]
pub struct TimelineEntry {
pub timestamp_ms: u64,
pub kind: TimelineKind,
pub track: &'static str,
pub duration_ns: u64,
pub head_ns: u64,
pub rebuild_ns: u64,
pub after_tick_ns: u64,
pub overlay_ns: u64,
pub paint_ns: u64,
pub layout_ns: u64,
pub rebuilt: bool,
pub scoped_rebuilt: usize,
pub detail: String,
}
impl TimelineEntry {
pub fn kind_label(&self) -> &'static str {
match self.kind {
TimelineKind::CpuFrame => "CPU",
TimelineKind::GpuFrame => "GPU",
TimelineKind::Custom => {
if self.track.is_empty() {
"custom"
} else {
self.track
}
}
}
}
}
thread_local! {
static TRACE_ENABLED: Cell<bool> = const { Cell::new(false) };
static TRACE: Mutex<DevtoolsTrace<TimelineEntry>> =
std::sync::Mutex::new(DevtoolsTrace::new(CAPACITY));
}
fn with_trace<R>(f: impl FnOnce(&DevtoolsTrace<TimelineEntry>) -> R) -> R {
TRACE.with(|t| {
let guard = t.lock().unwrap_or_else(|e| e.into_inner());
f(&guard)
})
}
pub fn set_enabled(on: bool) {
TRACE_ENABLED.with(|c| c.set(on));
with_trace(|t| t.set_enabled(on));
}
pub fn enabled() -> bool {
TRACE_ENABLED.with(|c| c.get())
}
pub fn clear() {
with_trace(|t| t.clear());
}
#[allow(clippy::too_many_arguments)]
pub fn push_cpu_frame(
head_ns: u64,
rebuild_ns: u64,
after_tick_ns: u64,
overlay_ns: u64,
paint_ns: u64,
layout_ns: u64,
rebuilt: bool,
scoped_rebuilt: usize,
) {
if !enabled() {
return;
}
with_trace(|t| {
if !t.enabled() {
return;
}
t.push(TimelineEntry {
timestamp_ms: now_ms(),
kind: TimelineKind::CpuFrame,
track: "",
duration_ns: head_ns
.saturating_add(rebuild_ns)
.saturating_add(after_tick_ns)
.saturating_add(overlay_ns)
.saturating_add(paint_ns),
head_ns,
rebuild_ns,
after_tick_ns,
overlay_ns,
paint_ns,
layout_ns,
rebuilt,
scoped_rebuilt,
detail: String::new(),
})
});
}
pub fn push_gpu_frame(gpu_ns: u64) {
if !enabled() {
return;
}
with_trace(|t| {
if !t.enabled() {
return;
}
t.push(TimelineEntry {
timestamp_ms: now_ms(),
kind: TimelineKind::GpuFrame,
track: "",
duration_ns: gpu_ns,
head_ns: 0,
rebuild_ns: 0,
after_tick_ns: 0,
overlay_ns: 0,
paint_ns: 0,
layout_ns: 0,
rebuilt: false,
scoped_rebuilt: 0,
detail: String::new(),
})
});
}
pub fn push(track: &'static str, duration_ns: u64, detail: impl Into<String>) {
if !enabled() {
return;
}
with_trace(|t| {
if !t.enabled() {
return;
}
t.push(TimelineEntry {
timestamp_ms: now_ms(),
kind: TimelineKind::Custom,
track,
duration_ns,
head_ns: 0,
rebuild_ns: 0,
after_tick_ns: 0,
overlay_ns: 0,
paint_ns: 0,
layout_ns: 0,
rebuilt: false,
scoped_rebuilt: 0,
detail: detail.into(),
})
});
}
pub fn export_json(max: usize) -> String {
let entries = peek(max);
let mut out = String::from("[\n");
for (i, e) in entries.iter().enumerate() {
if i > 0 {
out.push_str(",\n");
}
let _ = std::fmt::Write::write_fmt(
&mut out,
format_args!(
" {{\"t_ms\":{},\"track\":\"{}\",\"kind\":\"{}\",\"dur_ms\":{:.3},\"detail\":\"{}\"{}",
e.timestamp_ms,
escape_json(e.track),
escape_json(e.kind_label()),
e.duration_ns as f64 / 1_000_000.0,
escape_json(&e.detail),
cpu_breakdown_json(e),
),
);
out.push('}');
}
out.push_str("\n]\n");
out
}
fn cpu_breakdown_json(e: &TimelineEntry) -> String {
if !matches!(e.kind, TimelineKind::CpuFrame) {
return String::new();
}
format!(
",\"head_ms\":{:.3},\"rebuild_ms\":{:.3},\"after_tick_ms\":{:.3},\"overlay_ms\":{:.3},\"paint_ms\":{:.3},\"layout_ms\":{:.3},\"rebuilt\":{},\"scoped_rebuilt\":{}",
e.head_ns as f64 / 1_000_000.0,
e.rebuild_ns as f64 / 1_000_000.0,
e.after_tick_ns as f64 / 1_000_000.0,
e.overlay_ns as f64 / 1_000_000.0,
e.paint_ns as f64 / 1_000_000.0,
e.layout_ns as f64 / 1_000_000.0,
e.rebuilt,
e.scoped_rebuilt,
)
}
pub fn export_csv(max: usize) -> String {
let entries = peek(max);
let mut out = String::from(
"t_ms,track,kind,dur_ms,detail,head_ms,rebuild_ms,after_tick_ms,overlay_ms,paint_ms,layout_ms,rebuilt,scoped_rebuilt\n",
);
for e in &entries {
let cpu = if matches!(e.kind, TimelineKind::CpuFrame) {
format!(
"{:.3},{:.3},{:.3},{:.3},{:.3},{:.3},{},{}",
e.head_ns as f64 / 1_000_000.0,
e.rebuild_ns as f64 / 1_000_000.0,
e.after_tick_ns as f64 / 1_000_000.0,
e.overlay_ns as f64 / 1_000_000.0,
e.paint_ns as f64 / 1_000_000.0,
e.layout_ns as f64 / 1_000_000.0,
e.rebuilt,
e.scoped_rebuilt,
)
} else {
String::from(",,,,,,,,")
};
let _ = std::fmt::Write::write_fmt(
&mut out,
format_args!(
"{},{},{},{:.3},\"{}\",{}\n",
e.timestamp_ms,
csv_field(e.track),
csv_field(e.kind_label()),
e.duration_ns as f64 / 1_000_000.0,
csv_field(&e.detail),
cpu,
),
);
}
out
}
fn escape_json(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
c if (c as u32) < 0x20 => {
let _ = std::fmt::Write::write_fmt(&mut out, format_args!("\\u{:04x}", c as u32));
}
c => out.push(c),
}
}
out
}
fn csv_field(s: &str) -> String {
if s.contains([',', '"', '\n', '\r']) {
format!("\"{}\"", s.replace('"', "\"\""))
} else {
s.to_owned()
}
}
pub fn peek(max: usize) -> Vec<TimelineEntry> {
if !enabled() {
return Vec::new();
}
with_trace(|t| {
if !t.enabled() {
return Vec::new();
}
t.peek(max)
})
}
#[cfg(test)]
mod tests {
use super::*;
fn reset() {
set_enabled(true);
clear();
}
fn cleanup() {
clear();
set_enabled(false);
}
#[test]
fn disabled_push_is_noop() {
set_enabled(false);
clear();
push_cpu_frame(1, 2, 3, 4, 5, 1, false, 0);
push_gpu_frame(100);
assert!(peek(0).is_empty());
}
#[test]
fn clear_works_while_disabled() {
reset();
push_cpu_frame(1, 2, 3, 4, 5, 1, false, 0);
assert_eq!(peek(0).len(), 1);
set_enabled(false);
clear();
set_enabled(true);
assert!(peek(0).is_empty(), "关闭期间的显式 clear 必须生效");
cleanup();
}
#[test]
fn disabled_custom_push_does_not_materialize_detail() {
use std::cell::Cell;
use std::rc::Rc;
struct LazyDetail(Rc<Cell<bool>>);
impl From<LazyDetail> for String {
fn from(v: LazyDetail) -> Self {
v.0.set(true);
String::from("materialized")
}
}
set_enabled(false);
clear();
let called = Rc::new(Cell::new(false));
push("VideoTake", 1, LazyDetail(called.clone()));
push("VideoDecode", 1, LazyDetail(called.clone()));
assert!(!called.get(), "关闭时不应构造扩展 detail");
cleanup();
}
#[test]
fn enabled_collects_cpu_and_gpu() {
reset();
push_cpu_frame(100, 200, 50, 100, 500, 80, false, 3);
push_gpu_frame(300);
push_cpu_frame(120, 250, 60, 90, 550, 90, true, 0);
let snap = peek(0);
assert_eq!(snap.len(), 3);
assert!(matches!(snap[0].kind, TimelineKind::CpuFrame));
assert_eq!(snap[0].duration_ns, 950); assert!(matches!(snap[1].kind, TimelineKind::GpuFrame));
assert_eq!(snap[1].duration_ns, 300);
assert!(snap[2].rebuilt);
assert_eq!(snap[2].scoped_rebuilt, 0);
cleanup();
}
#[test]
fn capacity_evicts_oldest() {
reset();
for i in 0..CAPACITY + 10 {
push_cpu_frame(i as u64, 0, 0, 0, 0, 0, false, 0);
}
let snap = peek(0);
assert_eq!(snap.len(), CAPACITY);
assert_eq!(snap[0].head_ns, 10);
cleanup();
}
#[test]
fn max_truncates_recent() {
reset();
for i in 0..20 {
push_cpu_frame(i, 0, 0, 0, 0, 0, false, 0);
}
let snap = peek(5);
assert_eq!(snap.len(), 5);
assert_eq!(snap[0].head_ns, 15);
assert_eq!(snap[4].head_ns, 19);
cleanup();
}
#[test]
fn custom_tracks_recorded_with_their_own_names() {
reset();
push("VideoTake", 1500, "cam-01");
push("VideoDecode", 25_000, "cam-01");
push("VideoInput", 5_000, "cam-01");
let snap = peek(0);
assert_eq!(snap.len(), 3);
assert!(matches!(snap[0].kind, TimelineKind::Custom));
assert_eq!(snap[0].track, "VideoTake");
assert_eq!(snap[0].kind_label(), "VideoTake");
assert_eq!(snap[0].duration_ns, 1500);
assert_eq!(snap[0].detail, "cam-01");
assert_eq!(snap[1].track, "VideoDecode");
assert_eq!(snap[2].track, "VideoInput");
cleanup();
}
#[test]
fn export_formats_escape_and_omit_fake_fields() {
reset();
push("VideoTake", 1_500_000, "cam-\"01\"");
push_cpu_frame(100_000, 200_000, 50_000, 100_000, 500_000, 80_000, true, 3);
let json = export_json(0);
assert!(json.starts_with("[\n"), "JSON 该以数组起头:{json}");
assert!(json.contains("cam-\\\"01\\\""), "detail 里的引号必须转义:{json}");
assert!(json.contains("\"rebuilt\":true"), "CpuFrame 要带六阶段与 rebuild 标记:{json}");
let video_line = json.lines().find(|l| l.contains("VideoTake")).expect("有 VideoTake 行");
assert!(!video_line.contains("head_ms"), "非 CPU 轨道不许输出假拆分:{video_line}");
let csv = export_csv(0);
let lines: Vec<&str> = csv.lines().collect();
assert_eq!(lines.len(), 3, "表头 + 两条:{csv}");
assert!(lines[1].contains("\"cam-\"\"01\"\""), "CSV 含引号的字段必须 RFC4180 引号包裹:{csv}");
assert!(lines[2].contains("true,3"), "CpuFrame 行的 rebuilt/scoped 要落在末尾两列:{csv}");
assert_eq!(export_json(1).matches("\"t_ms\"").count(), 1, "max 截断只留最近一条");
cleanup();
}
#[test]
fn clear_empties() {
reset();
for _ in 0..10 {
push_cpu_frame(1, 0, 0, 0, 0, 0, false, 0);
}
clear();
assert!(peek(0).is_empty());
cleanup();
}
}