forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

trace.rs155 lines, 4.6 KiBHistoryRawDownload
1//! Opt-in timing of the decoder's threads, for finding where they sit idle.
2//!
3//! `EC_H265_TRACE=1` turns it on. Off (the default), every hook is one check of a cached
4//! flag and no clock is read. On, each thread adds the time it spends in each [`Phase`] to
5//! its own totals. A thread's totals are merged into the table of its role when the thread
6//! ends (or, for the calling thread, when [`report`] runs), and [`report`] prints the table
7//! to stderr at the end of the stream.
8
9use std::cell::RefCell;
10use std::collections::BTreeMap;
11use std::sync::{Mutex, MutexGuard, OnceLock};
12use std::time::{Duration, Instant};
13
14/// The phases a thread's time is split into.
15#[derive(Clone, Copy, Debug)]
16pub enum Phase {
17 /// Decoding a slice, a wavefront row, or finishing a picture (wall time; it includes
18 /// the waits below that happen inside it).
19 Decode = 0,
20 /// Blocked until a reference picture has the rows a motion compensation reads.
21 WaitRows = 1,
22 /// Blocked joining the oldest in-flight picture to free a picture slot.
23 WaitAdmit = 2,
24 /// Blocked on the CABAC row-sync: the row above must be two CTBs ahead.
25 WaitSync = 3,
26 /// A picture worker idle, waiting for the next slice or the finish message.
27 WaitMsg = 4,
28 /// Blocked joining the picture workers at end of stream.
29 WaitJoin = 5,
30 /// Serial work on the calling thread outside the slice decode: picture start and
31 /// finish (RPS, bumping, DPB insert).
32 Serial = 6,
33 /// Blocked until the collocated picture has the motion rows temporal prediction reads.
34 WaitCol = 7,
35}
36
37const N: usize = 8;
38/// Whether tracing is on (`EC_H265_TRACE` set to anything but `0`).
39pub fn on() -> bool {
40 static ON: OnceLock<bool> = OnceLock::new();
41 *ON.get_or_init(|| std::env::var_os("EC_H265_TRACE").is_some_and(|v| v != "0"))
42}
43
44/// The start of a timed span, or `None` when tracing is off (no clock is read).
45#[inline]
46pub fn now() -> Option<Instant> {
47 if on() { Some(Instant::now()) } else { None }
48}
49
50/// Add the time since `start` to `phase` of this thread.
51#[inline]
52pub fn since(phase: Phase, start: Option<Instant>) {
53 if let Some(t) = start {
54 add(phase, t.elapsed());
55 }
56}
57
58fn add(phase: Phase, d: Duration) {
59 let _ = ACC.try_with(|a| {
60 a.borrow_mut().ns[phase as usize] += d.as_nanos() as u64;
61 });
62}
63
64/// Name this thread's role in the report (the default is `caller`).
65pub fn set_role(role: &'static str) {
66 if on() {
67 let _ = ACC.try_with(|a| a.borrow_mut().role = role);
68 }
69}
70
71#[derive(Default)]
72struct Totals {
73 threads: usize,
74 ns: [u64; N],
75}
76
77fn totals() -> MutexGuard<'static, BTreeMap<&'static str, Totals>> {
78 static T: Mutex<BTreeMap<&'static str, Totals>> = Mutex::new(BTreeMap::new());
79 T.lock().unwrap_or_else(|e| e.into_inner())
80}
81
82struct Acc {
83 role: &'static str,
84 ns: [u64; N],
85}
86
87impl Acc {
88 /// Merge this thread's totals into its role's table and clear them.
89 fn merge(&mut self) {
90 if self.ns.iter().all(|&n| n == 0) {
91 return;
92 }
93 let mut t = totals();
94 let e = t.entry(self.role).or_default();
95 e.threads += 1;
96 for (dst, src) in e.ns.iter_mut().zip(self.ns.iter()) {
97 *dst += src;
98 }
99 self.ns = [0; N];
100 }
101}
102
103impl Drop for Acc {
104 fn drop(&mut self) {
105 self.merge();
106 }
107}
108
109thread_local! {
110 static ACC: RefCell<Acc> = const { RefCell::new(Acc { role: "caller", ns: [0; N] }) };
111}
112
113/// Merge the calling thread's totals, then print every role's table to stderr and clear
114/// the tables. Worker threads have merged already: they are joined before this runs.
115pub fn report() {
116 if !on() {
117 return;
118 }
119 let _ = ACC.try_with(|a| a.borrow_mut().merge());
120 let mut t = totals();
121 if t.is_empty() {
122 return;
123 }
124 eprintln!("EC_H265_TRACE (ms, summed over the threads of each role)");
125 eprintln!(
126 "{:<12}{:>8}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}",
127 "role",
128 "threads",
129 "decode",
130 "wait_rows",
131 "wait_col",
132 "wait_admit",
133 "wait_sync",
134 "wait_msg",
135 "wait_join",
136 "serial"
137 );
138 for (role, tot) in t.iter() {
139 let ms = |p: Phase| tot.ns[p as usize] as f64 / 1e6;
140 eprintln!(
141 "{:<12}{:>8}{:>12.1}{:>12.1}{:>12.1}{:>12.1}{:>12.1}{:>12.1}{:>12.1}{:>12.1}",
142 role,
143 tot.threads,
144 ms(Phase::Decode),
145 ms(Phase::WaitRows),
146 ms(Phase::WaitCol),
147 ms(Phase::WaitAdmit),
148 ms(Phase::WaitSync),
149 ms(Phase::WaitMsg),
150 ms(Phase::WaitJoin),
151 ms(Phase::Serial),
152 );
153 }
154 t.clear();
155}