diff --git a/crates/ec-h265/src/dec/cu_syntax/wpp.rs b/crates/ec-h265/src/dec/cu_syntax/wpp.rs index 5d7d2995..efdf1792 100644 --- a/crates/ec-h265/src/dec/cu_syntax/wpp.rs +++ b/crates/ec-h265/src/dec/cu_syntax/wpp.rs @@ -24,7 +24,6 @@ use crate::dec::inter::InterRefs; use crate::dec::motion_field::{FieldCell, MotionField, SliceMotion}; use crate::dec::pic::{BlockInfo, CtbInfo, PicState, SliceFilter}; use crate::dec::tiles::TileScan; -use crate::dec::trace::{self, Phase}; use ec_core::error::{Error, Result}; use ec_h265_syntax::slice::{SliceHeader, SliceType}; use ec_h265_syntax::{Pps, Sps}; @@ -139,7 +138,6 @@ impl Board { let cols = self.cols; let need = (x + 2).min(cols); let mut st = lock(&self.state); - let t = trace::now(); loop { if let Some(why) = &st.failed { return Err(Error::corrupt(format!("HEVC slice (wavefront): {why}"))); @@ -149,7 +147,6 @@ impl Board { } st = self.changed.wait(st).unwrap_or_else(|e| e.into_inner()); } - trace::since(Phase::WaitSync, t); let slot = &st.slots[ry - 1]; let k0 = x.saturating_sub(1); let k1 = (x + 1).min(cols - 1); @@ -569,9 +566,7 @@ pub(in crate::dec) fn parse_segment( break; } let ry = ry0 + i; - let t = trace::now(); let outcome = catch_unwind(AssertUnwindSafe(|| do_row(ry))); - trace::since(Phase::Decode, t); match outcome { Ok(Ok(row)) => done.push(row), Ok(Err(e)) => { @@ -589,10 +584,7 @@ pub(in crate::dec) fn parse_segment( let results: Vec>> = std::thread::scope(|s| { let helpers: Vec<_> = (1..workers.clamp(1, nrows)) .map(|_| { - s.spawn(|| { - trace::set_role("wpp-helper"); - run() - }) + s.spawn(|| run()) }) .collect(); let mut all = vec![run()]; diff --git a/crates/ec-h265/src/dec/mod.rs b/crates/ec-h265/src/dec/mod.rs index cb92670f..2ba7bbc8 100644 --- a/crates/ec-h265/src/dec/mod.rs +++ b/crates/ec-h265/src/dec/mod.rs @@ -47,7 +47,6 @@ pub mod sao; pub mod shared; pub mod slice_seg; pub mod tiles; -pub mod trace; pub mod weighted; use std::collections::VecDeque; @@ -132,15 +131,9 @@ fn picture_limit(threads: usize) -> usize { } } -/// The worker-thread budget: `EC_H265_THREADS` when it is a positive number, else -/// the machine's available parallelism. Either way capped at [`MAX_THREADS`]. +/// The worker-thread budget: the machine's available parallelism, capped at [`MAX_THREADS`]. pub fn configured_threads() -> usize { - let requested = std::env::var("EC_H265_THREADS") - .ok() - .and_then(|v| v.trim().parse::().ok()) - .filter(|&n| n > 0) - .unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |n| n.get())); - requested.min(MAX_THREADS) + std::thread::available_parallelism().map_or(1, |n| n.get()).min(MAX_THREADS) } /// Streaming HEVC decoder with the same surface as the H.264 one: feed NAL @@ -324,12 +317,9 @@ impl Decoder { for pending in &self.out { pending.picture.wait_done()?; } - let t = trace::now(); for handle in self.in_flight.drain(..) { let _ = handle.join(); } - trace::since(trace::Phase::WaitJoin, t); - trace::report(); Ok(()) } @@ -571,13 +561,11 @@ impl Decoder { // Frame threads: at most `threads` pictures in flight, so wait for the oldest. let threaded = self.threads > 1 && self.pixel_decode; if threaded { - let t = trace::now(); while self.in_flight.len() >= self.max_in_flight { if let Some(handle) = self.in_flight.pop_front() { let _ = handle.join(); } } - trace::since(trace::Phase::WaitAdmit, t); } let shared = Arc::new(SharedPic::new( poc, @@ -666,7 +654,6 @@ impl Decoder { [Vec::new(), Vec::new()] }; let col = motion_field::collocated(dpb, slice, &cur.lists); - let t = trace::now(); let submitted = cur.runner.submit(SliceJob { rbsp, data_off, @@ -680,7 +667,6 @@ impl Decoder { pixel, substreams, }); - trace::since(trace::Phase::Decode, t); submitted } @@ -688,9 +674,7 @@ impl Decoder { /// bumping. Idempotent when no picture is open. The picture's samples may still be /// being decoded (on its worker); output waits for them. fn finish_picture(&mut self) { - let t = trace::now(); self.finish_picture_inner(); - trace::since(trace::Phase::Serial, t); } fn finish_picture_inner(&mut self) { diff --git a/crates/ec-h265/src/dec/runner.rs b/crates/ec-h265/src/dec/runner.rs index 606ca204..50ed779e 100644 --- a/crates/ec-h265/src/dec/runner.rs +++ b/crates/ec-h265/src/dec/runner.rs @@ -19,7 +19,6 @@ use std::sync::{Arc, Condvar, Mutex, MutexGuard}; use std::thread::JoinHandle; use super::picjob::{PicJob, SliceJob}; -use super::trace::{self, Phase}; use ec_core::error::{Error, Result}; fn lock(m: &Mutex) -> MutexGuard<'_, T> { @@ -209,23 +208,17 @@ impl Runner { /// its finish marks the picture as failed, so that nothing waits on it forever. fn run_worker(rx: Receiver, mut job: PicJob, checksum: Arc) { let shared = Arc::clone(job.shared()); - trace::set_role("picture"); let outcome = catch_unwind(AssertUnwindSafe(|| -> Result> { loop { - let idle = trace::now(); let msg = rx.recv(); - trace::since(Phase::WaitMsg, idle); let Ok(msg) = msg else { break }; - let busy = trace::now(); match msg { Msg::Slice(slice) => job.run_slice(*slice)?, Msg::Finish => { let sum = job.finish(); - trace::since(Phase::Decode, busy); return Ok(sum); } } - trace::since(Phase::Decode, busy); } Err(Error::corrupt( "HEVC decode: a picture was dropped before it finished".to_string(), diff --git a/crates/ec-h265/src/dec/shared.rs b/crates/ec-h265/src/dec/shared.rs index ea8380b5..5fd0b252 100644 --- a/crates/ec-h265/src/dec/shared.rs +++ b/crates/ec-h265/src/dec/shared.rs @@ -122,10 +122,7 @@ impl SharedPic { /// Wait until at least `rows` luma rows are final. Returns the picture's failure /// instead when it has one. pub fn wait_rows(&self, rows: usize) -> Result<()> { - let t = super::trace::now(); - let r = self.wait_for(rows, |p| p.rows); - super::trace::since(super::trace::Phase::WaitRows, t); - r + self.wait_for(rows, |p| p.rows) } /// Wait until the collocated motion of at least `rows` luma rows is published. diff --git a/crates/ec-h265/src/dec/trace.rs b/crates/ec-h265/src/dec/trace.rs deleted file mode 100644 index 1ac64bd7..00000000 --- a/crates/ec-h265/src/dec/trace.rs +++ /dev/null @@ -1,155 +0,0 @@ -//! Opt-in timing of the decoder's threads, for finding where they sit idle. -//! -//! `EC_H265_TRACE=1` turns it on. Off (the default), every hook is one check of a cached -//! flag and no clock is read. On, each thread adds the time it spends in each [`Phase`] to -//! its own totals. A thread's totals are merged into the table of its role when the thread -//! ends (or, for the calling thread, when [`report`] runs), and [`report`] prints the table -//! to stderr at the end of the stream. - -use std::cell::RefCell; -use std::collections::BTreeMap; -use std::sync::{Mutex, MutexGuard, OnceLock}; -use std::time::{Duration, Instant}; - -/// The phases a thread's time is split into. -#[derive(Clone, Copy, Debug)] -pub enum Phase { - /// Decoding a slice, a wavefront row, or finishing a picture (wall time; it includes - /// the waits below that happen inside it). - Decode = 0, - /// Blocked until a reference picture has the rows a motion compensation reads. - WaitRows = 1, - /// Blocked joining the oldest in-flight picture to free a picture slot. - WaitAdmit = 2, - /// Blocked on the CABAC row-sync: the row above must be two CTBs ahead. - WaitSync = 3, - /// A picture worker idle, waiting for the next slice or the finish message. - WaitMsg = 4, - /// Blocked joining the picture workers at end of stream. - WaitJoin = 5, - /// Serial work on the calling thread outside the slice decode: picture start and - /// finish (RPS, bumping, DPB insert). - Serial = 6, - /// Blocked until the collocated picture has the motion rows temporal prediction reads. - WaitCol = 7, -} - -const N: usize = 8; -/// Whether tracing is on (`EC_H265_TRACE` set to anything but `0`). -pub fn on() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("EC_H265_TRACE").is_some_and(|v| v != "0")) -} - -/// The start of a timed span, or `None` when tracing is off (no clock is read). -#[inline] -pub fn now() -> Option { - if on() { Some(Instant::now()) } else { None } -} - -/// Add the time since `start` to `phase` of this thread. -#[inline] -pub fn since(phase: Phase, start: Option) { - if let Some(t) = start { - add(phase, t.elapsed()); - } -} - -fn add(phase: Phase, d: Duration) { - let _ = ACC.try_with(|a| { - a.borrow_mut().ns[phase as usize] += d.as_nanos() as u64; - }); -} - -/// Name this thread's role in the report (the default is `caller`). -pub fn set_role(role: &'static str) { - if on() { - let _ = ACC.try_with(|a| a.borrow_mut().role = role); - } -} - -#[derive(Default)] -struct Totals { - threads: usize, - ns: [u64; N], -} - -fn totals() -> MutexGuard<'static, BTreeMap<&'static str, Totals>> { - static T: Mutex> = Mutex::new(BTreeMap::new()); - T.lock().unwrap_or_else(|e| e.into_inner()) -} - -struct Acc { - role: &'static str, - ns: [u64; N], -} - -impl Acc { - /// Merge this thread's totals into its role's table and clear them. - fn merge(&mut self) { - if self.ns.iter().all(|&n| n == 0) { - return; - } - let mut t = totals(); - let e = t.entry(self.role).or_default(); - e.threads += 1; - for (dst, src) in e.ns.iter_mut().zip(self.ns.iter()) { - *dst += src; - } - self.ns = [0; N]; - } -} - -impl Drop for Acc { - fn drop(&mut self) { - self.merge(); - } -} - -thread_local! { - static ACC: RefCell = const { RefCell::new(Acc { role: "caller", ns: [0; N] }) }; -} - -/// Merge the calling thread's totals, then print every role's table to stderr and clear -/// the tables. Worker threads have merged already: they are joined before this runs. -pub fn report() { - if !on() { - return; - } - let _ = ACC.try_with(|a| a.borrow_mut().merge()); - let mut t = totals(); - if t.is_empty() { - return; - } - eprintln!("EC_H265_TRACE (ms, summed over the threads of each role)"); - eprintln!( - "{:<12}{:>8}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}", - "role", - "threads", - "decode", - "wait_rows", - "wait_col", - "wait_admit", - "wait_sync", - "wait_msg", - "wait_join", - "serial" - ); - for (role, tot) in t.iter() { - let ms = |p: Phase| tot.ns[p as usize] as f64 / 1e6; - eprintln!( - "{:<12}{:>8}{:>12.1}{:>12.1}{:>12.1}{:>12.1}{:>12.1}{:>12.1}{:>12.1}{:>12.1}", - role, - tot.threads, - ms(Phase::Decode), - ms(Phase::WaitRows), - ms(Phase::WaitCol), - ms(Phase::WaitAdmit), - ms(Phase::WaitSync), - ms(Phase::WaitMsg), - ms(Phase::WaitJoin), - ms(Phase::Serial), - ); - } - t.clear(); -}