forge
Explore
Log in

Don't you dare go Hollow

U7: remove ec-h265 trace hooks (trace.rs) and the EC_H265_THREADS env read; thread budget is available_parallelism (no output change)

Browse files at this commit

1d28fe66693e297c623be6c9e7557d5e150f6672Ahmet Kaan GümüşParent: 349abd6
crates/ec-h265/src/dec/cu_syntax/wpp.rsmodified+1 -9
@@ -24,7 +24,6 @@ use crate::dec::inter::InterRefs;
24 use crate::dec::motion_field::{FieldCell, MotionField, SliceMotion};24 use crate::dec::motion_field::{FieldCell, MotionField, SliceMotion};
25 use crate::dec::pic::{BlockInfo, CtbInfo, PicState, SliceFilter};25 use crate::dec::pic::{BlockInfo, CtbInfo, PicState, SliceFilter};
26 use crate::dec::tiles::TileScan;26 use crate::dec::tiles::TileScan;
27-use crate::dec::trace::{self, Phase};
28 use ec_core::error::{Error, Result};27 use ec_core::error::{Error, Result};
29 use ec_h265_syntax::slice::{SliceHeader, SliceType};28 use ec_h265_syntax::slice::{SliceHeader, SliceType};
30 use ec_h265_syntax::{Pps, Sps};29 use ec_h265_syntax::{Pps, Sps};
@@ -139,7 +138,6 @@ impl Board {
139 let cols = self.cols;138 let cols = self.cols;
140 let need = (x + 2).min(cols);139 let need = (x + 2).min(cols);
141 let mut st = lock(&self.state);140 let mut st = lock(&self.state);
142- let t = trace::now();
143 loop {141 loop {
144 if let Some(why) = &st.failed {142 if let Some(why) = &st.failed {
145 return Err(Error::corrupt(format!("HEVC slice (wavefront): {why}")));143 return Err(Error::corrupt(format!("HEVC slice (wavefront): {why}")));
@@ -149,7 +147,6 @@ impl Board {
149 }147 }
150 st = self.changed.wait(st).unwrap_or_else(|e| e.into_inner());148 st = self.changed.wait(st).unwrap_or_else(|e| e.into_inner());
151 }149 }
152- trace::since(Phase::WaitSync, t);
153 let slot = &st.slots[ry - 1];150 let slot = &st.slots[ry - 1];
154 let k0 = x.saturating_sub(1);151 let k0 = x.saturating_sub(1);
155 let k1 = (x + 1).min(cols - 1);152 let k1 = (x + 1).min(cols - 1);
@@ -569,9 +566,7 @@ pub(in crate::dec) fn parse_segment(
569 break;566 break;
570 }567 }
571 let ry = ry0 + i;568 let ry = ry0 + i;
572- let t = trace::now();
573 let outcome = catch_unwind(AssertUnwindSafe(|| do_row(ry)));569 let outcome = catch_unwind(AssertUnwindSafe(|| do_row(ry)));
574- trace::since(Phase::Decode, t);
575 match outcome {570 match outcome {
576 Ok(Ok(row)) => done.push(row),571 Ok(Ok(row)) => done.push(row),
577 Ok(Err(e)) => {572 Ok(Err(e)) => {
@@ -589,10 +584,7 @@ pub(in crate::dec) fn parse_segment(
589 let results: Vec<Result<Vec<RowDone>>> = std::thread::scope(|s| {584 let results: Vec<Result<Vec<RowDone>>> = std::thread::scope(|s| {
590 let helpers: Vec<_> = (1..workers.clamp(1, nrows))585 let helpers: Vec<_> = (1..workers.clamp(1, nrows))
591 .map(|_| {586 .map(|_| {
592- s.spawn(|| {587+ s.spawn(|| run())
593- trace::set_role("wpp-helper");
594- run()
595- })
596 })588 })
597 .collect();589 .collect();
598 let mut all = vec![run()];590 let mut all = vec![run()];
crates/ec-h265/src/dec/mod.rsmodified+2 -18
@@ -47,7 +47,6 @@ pub mod sao;
47 pub mod shared;47 pub mod shared;
48 pub mod slice_seg;48 pub mod slice_seg;
49 pub mod tiles;49 pub mod tiles;
50-pub mod trace;
51 pub mod weighted;50 pub mod weighted;
52 51
53 use std::collections::VecDeque;52 use std::collections::VecDeque;
@@ -132,15 +131,9 @@ fn picture_limit(threads: usize) -> usize {
132 }131 }
133 }132 }
134 133
135-/// The worker-thread budget: `EC_H265_THREADS` when it is a positive number, else134+/// The worker-thread budget: the machine's available parallelism, capped at [`MAX_THREADS`].
136-/// the machine's available parallelism. Either way capped at [`MAX_THREADS`].
137 pub fn configured_threads() -> usize {135 pub fn configured_threads() -> usize {
138- let requested = std::env::var("EC_H265_THREADS")136+ std::thread::available_parallelism().map_or(1, |n| n.get()).min(MAX_THREADS)
139- .ok()
140- .and_then(|v| v.trim().parse::<usize>().ok())
141- .filter(|&n| n > 0)
142- .unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |n| n.get()));
143- requested.min(MAX_THREADS)
144 }137 }
145 138
146 /// Streaming HEVC decoder with the same surface as the H.264 one: feed NAL139 /// Streaming HEVC decoder with the same surface as the H.264 one: feed NAL
@@ -324,12 +317,9 @@ impl Decoder {
324 for pending in &self.out {317 for pending in &self.out {
325 pending.picture.wait_done()?;318 pending.picture.wait_done()?;
326 }319 }
327- let t = trace::now();
328 for handle in self.in_flight.drain(..) {320 for handle in self.in_flight.drain(..) {
329 let _ = handle.join();321 let _ = handle.join();
330 }322 }
331- trace::since(trace::Phase::WaitJoin, t);
332- trace::report();
333 Ok(())323 Ok(())
334 }324 }
335 325
@@ -571,13 +561,11 @@ impl Decoder {
571 // Frame threads: at most `threads` pictures in flight, so wait for the oldest.561 // Frame threads: at most `threads` pictures in flight, so wait for the oldest.
572 let threaded = self.threads > 1 && self.pixel_decode;562 let threaded = self.threads > 1 && self.pixel_decode;
573 if threaded {563 if threaded {
574- let t = trace::now();
575 while self.in_flight.len() >= self.max_in_flight {564 while self.in_flight.len() >= self.max_in_flight {
576 if let Some(handle) = self.in_flight.pop_front() {565 if let Some(handle) = self.in_flight.pop_front() {
577 let _ = handle.join();566 let _ = handle.join();
578 }567 }
579 }568 }
580- trace::since(trace::Phase::WaitAdmit, t);
581 }569 }
582 let shared = Arc::new(SharedPic::new(570 let shared = Arc::new(SharedPic::new(
583 poc,571 poc,
@@ -666,7 +654,6 @@ impl Decoder {
666 [Vec::new(), Vec::new()]654 [Vec::new(), Vec::new()]
667 };655 };
668 let col = motion_field::collocated(dpb, slice, &cur.lists);656 let col = motion_field::collocated(dpb, slice, &cur.lists);
669- let t = trace::now();
670 let submitted = cur.runner.submit(SliceJob {657 let submitted = cur.runner.submit(SliceJob {
671 rbsp,658 rbsp,
672 data_off,659 data_off,
@@ -680,7 +667,6 @@ impl Decoder {
680 pixel,667 pixel,
681 substreams,668 substreams,
682 });669 });
683- trace::since(trace::Phase::Decode, t);
684 submitted670 submitted
685 }671 }
686 672
@@ -688,9 +674,7 @@ impl Decoder {
688 /// bumping. Idempotent when no picture is open. The picture's samples may still be674 /// bumping. Idempotent when no picture is open. The picture's samples may still be
689 /// being decoded (on its worker); output waits for them.675 /// being decoded (on its worker); output waits for them.
690 fn finish_picture(&mut self) {676 fn finish_picture(&mut self) {
691- let t = trace::now();
692 self.finish_picture_inner();677 self.finish_picture_inner();
693- trace::since(trace::Phase::Serial, t);
694 }678 }
695 679
696 fn finish_picture_inner(&mut self) {680 fn finish_picture_inner(&mut self) {
crates/ec-h265/src/dec/runner.rsmodified+0 -7
@@ -19,7 +19,6 @@ use std::sync::{Arc, Condvar, Mutex, MutexGuard};
19 use std::thread::JoinHandle;19 use std::thread::JoinHandle;
20 20
21 use super::picjob::{PicJob, SliceJob};21 use super::picjob::{PicJob, SliceJob};
22-use super::trace::{self, Phase};
23 use ec_core::error::{Error, Result};22 use ec_core::error::{Error, Result};
24 23
25 fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {24 fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
@@ -209,23 +208,17 @@ impl Runner {
209 /// its finish marks the picture as failed, so that nothing waits on it forever.208 /// its finish marks the picture as failed, so that nothing waits on it forever.
210 fn run_worker(rx: Receiver<Msg>, mut job: PicJob, checksum: Arc<Checksum>) {209 fn run_worker(rx: Receiver<Msg>, mut job: PicJob, checksum: Arc<Checksum>) {
211 let shared = Arc::clone(job.shared());210 let shared = Arc::clone(job.shared());
212- trace::set_role("picture");
213 let outcome = catch_unwind(AssertUnwindSafe(|| -> Result<Option<u64>> {211 let outcome = catch_unwind(AssertUnwindSafe(|| -> Result<Option<u64>> {
214 loop {212 loop {
215- let idle = trace::now();
216 let msg = rx.recv();213 let msg = rx.recv();
217- trace::since(Phase::WaitMsg, idle);
218 let Ok(msg) = msg else { break };214 let Ok(msg) = msg else { break };
219- let busy = trace::now();
220 match msg {215 match msg {
221 Msg::Slice(slice) => job.run_slice(*slice)?,216 Msg::Slice(slice) => job.run_slice(*slice)?,
222 Msg::Finish => {217 Msg::Finish => {
223 let sum = job.finish();218 let sum = job.finish();
224- trace::since(Phase::Decode, busy);
225 return Ok(sum);219 return Ok(sum);
226 }220 }
227 }221 }
228- trace::since(Phase::Decode, busy);
229 }222 }
230 Err(Error::corrupt(223 Err(Error::corrupt(
231 "HEVC decode: a picture was dropped before it finished".to_string(),224 "HEVC decode: a picture was dropped before it finished".to_string(),
crates/ec-h265/src/dec/shared.rsmodified+1 -4
@@ -122,10 +122,7 @@ impl SharedPic {
122 /// Wait until at least `rows` luma rows are final. Returns the picture's failure122 /// Wait until at least `rows` luma rows are final. Returns the picture's failure
123 /// instead when it has one.123 /// instead when it has one.
124 pub fn wait_rows(&self, rows: usize) -> Result<()> {124 pub fn wait_rows(&self, rows: usize) -> Result<()> {
125- let t = super::trace::now();125+ self.wait_for(rows, |p| p.rows)
126- let r = self.wait_for(rows, |p| p.rows);
127- super::trace::since(super::trace::Phase::WaitRows, t);
128- r
129 }126 }
130 127
131 /// Wait until the collocated motion of at least `rows` luma rows is published.128 /// Wait until the collocated motion of at least `rows` luma rows is published.
crates/ec-h265/src/dec/trace.rsdeleted+0 -155
@@ -1,155 +0,0 @@
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-
9-use std::cell::RefCell;
10-use std::collections::BTreeMap;
11-use std::sync::{Mutex, MutexGuard, OnceLock};
12-use std::time::{Duration, Instant};
13-
14-/// The phases a thread's time is split into.
15-#[derive(Clone, Copy, Debug)]
16-pub 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-
37-const N: usize = 8;
38-/// Whether tracing is on (`EC_H265_TRACE` set to anything but `0`).
39-pub 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]
46-pub 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]
52-pub fn since(phase: Phase, start: Option<Instant>) {
53- if let Some(t) = start {
54- add(phase, t.elapsed());
55- }
56-}
57-
58-fn 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`).
65-pub 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)]
72-struct Totals {
73- threads: usize,
74- ns: [u64; N],
75-}
76-
77-fn 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-
82-struct Acc {
83- role: &'static str,
84- ns: [u64; N],
85-}
86-
87-impl 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-
103-impl Drop for Acc {
104- fn drop(&mut self) {
105- self.merge();
106- }
107-}
108-
109-thread_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.
115-pub 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-}