forge
Explore
Log in

Don't you dare go Hollow

Reconstruction on a superblock-row wavefront (EC_AV1_RECON_THREADS)

Browse files at this commit

f7306dde2fb1e120acbeaca20ee4c99fbef5b43fAhmet Kaan GümüşParent: 9258b06
  • perf
    • reconstruction on a superblock-row wavefront (EC_AV1_RECON_THREADS)
Show full message
perf(av1): reconstruction on a superblock-row wavefront (EC_AV1_RECON_THREADS)

lane-wave1 step (ii). Above one reconstruction thread the parser keeps
parsing and never writes the planes: each superblock's drained
`Vec<ReconOp>` becomes one job (one per 128x128 superblock when `sb128`,
since a 128 block writes across its four 64x64 visits), and N scoped-per-
tile workers reconstruct them in wavefront order -- job `(r, c)` starts
once `(r - 1, min(c + 1, last_col))` and `(r, c - 1)` are complete, which
covers every pixel an intra predictor can reach and every CfL AC read.
Jobs are handed out in raster order, so the oldest outstanding one always
has its dependencies met; a `WaveGuard` joins every worker on each exit
from the tile decoder, including the `?` ones.

The two parse-time pixel READS (the intrabc source fetch, the interintra
intra predictor) keep their `flush_recon`, which now waits the wavefront
out first and replays the current superblock inline -- so an intrabc block
serialises the tile at that point instead of trusting the spec's 256-px
delay against our lag, and stays byte-exact.

MEASURED and it does not pay: seg4k 31.8 s at (frame, filter, recon) =
(1,1,1) vs 31.9 s at (1,1,4) with CPU 99% -> 117%, seg1080 9.4 -> 9.9 s;
with frame threading it is a loss (seg4k 13.5 s at (6,2,1) vs 14.5 s at
(6,2,4)). Recording the ops copies the residual and the MC prediction on
the PARSE thread, which cancels what the workers take off it. Default
stays 1 (inline), where nothing is recorded at all.

Byte-exact: sha6 on seg1080/seg4k/seg4k_lr/palette at recon 1, at recon 4,
and at EC_AV1_THREADS=6 EC_AV1_FILTER_THREADS=2 EC_AV1_RECON_THREADS=4;
new gate `a_real_stream_reconstructs_identically_with_one_and_four_recon_threads`
on reelb_arf_witness (hidden ARF, 10-bit) and both palette/intrabc screen
witnesses.
crates/ec-av1/src/decode.rsmodified+243 -4
@@ -90,6 +90,9 @@ pub(crate) struct FrameCtx {
90 /// `None` while the queue is in use (wavefront workers) and outside a90 /// `None` while the queue is in use (wavefront workers) and outside a
91 /// tile. See [`push_op`].91 /// tile. See [`push_op`].
92 pub(crate) recon_planes: std::cell::Cell<Option<ReconPlanes>>,92 pub(crate) recon_planes: std::cell::Cell<Option<ReconPlanes>>,
93+ /// lane-wave1 step (ii): the superblock wavefront this tile's recorded
94+ /// writes are handed to, at more than one reconstruction thread.
95+ pub(crate) wave: std::cell::RefCell<Option<std::sync::Arc<WaveState>>>,
93 }96 }
94 97
95 impl std::fmt::Debug for FrameCtx {98 impl std::fmt::Debug for FrameCtx {
@@ -150,6 +153,7 @@ impl FrameCtx {
150 recon_ops: std::cell::RefCell::new(Vec::new()),153 recon_ops: std::cell::RefCell::new(Vec::new()),
151 recon_spare: std::cell::RefCell::new(Vec::new()),154 recon_spare: std::cell::RefCell::new(Vec::new()),
152 recon_planes: std::cell::Cell::new(None),155 recon_planes: std::cell::Cell::new(None),
156+ wave: std::cell::RefCell::new(None),
153 }157 }
154 }158 }
155 }159 }
@@ -2113,6 +2117,11 @@ pub(crate) struct ReconPlanes(
2113 // own thread.2117 // own thread.
2114 #[allow(unsafe_code)]2118 #[allow(unsafe_code)]
2115 unsafe impl Send for ReconPlanes {}2119 unsafe impl Send for ReconPlanes {}
2120+// SAFETY: the wavefront's workers share one `ReconPlanes` and write provably
2121+// disjoint superblocks of it (see [`WaveState`]) -- the [`crate::par::Shared`]
2122+// contract, one superblock per band instead of one row band.
2123+#[allow(unsafe_code)]
2124+unsafe impl Sync for ReconPlanes {}
2116 2125
2117 /// Registers the tile's planes for inline reconstruction and unregisters them2126 /// Registers the tile's planes for inline reconstruction and unregisters them
2118 /// on every exit from the tile decoder, including the `?` ones -- a stale2127 /// on every exit from the tile decoder, including the `?` ones -- a stale
@@ -2164,6 +2173,173 @@ fn push_op(fctx: &crate::decode::FrameCtx, op: ReconOp) {
2164 fctx.recon_ops.with(|c| c.borrow_mut().push(op));2173 fctx.recon_ops.with(|c| c.borrow_mut().push(op));
2165 }2174 }
2166 2175
2176+/// lane-wave1 step (ii): the superblock-row wavefront a tile's recorded
2177+/// writes are reconstructed on when `EC_AV1_RECON_THREADS > 1`.
2178+///
2179+/// The parser keeps parsing and never touches the planes; each superblock's
2180+/// drained `Vec<ReconOp>` becomes one job, keyed by the superblock's own
2181+/// `(row, column)` inside the tile (128x128 superblocks are one job for all
2182+/// four of their 64x64 visits, since a 128 block writes across quadrants).
2183+/// A worker may start job `(r, c)` once `(r - 1, min(c + 1, last_col))` and
2184+/// `(r, c - 1)` are complete -- the classic wavefront rule, which covers
2185+/// every pixel an intra predictor can read (its edges reach one block right
2186+/// along the row above and one block down the column to the left, both
2187+/// inside those two neighbours) and every CfL AC read (this block's own
2188+/// luma, written by this same job). Jobs are handed out in raster order, so
2189+/// the oldest outstanding one always has its dependencies met: no deadlock.
2190+///
2191+/// Gate counters incremented inside `reconstruct*`/`intra`/`mc` are
2192+/// `thread_local!` and miss every worker, which is why the default is 1.
2193+pub(crate) struct WaveState {
2194+ q: std::sync::Mutex<WaveQueue>,
2195+ cv: std::sync::Condvar,
2196+ planes: ReconPlanes,
2197+ /// The two [`FrameCtx`] fields reconstruction reads (`sample_max` is
2198+ /// `bit_depth`'s; everything else a `reconstruct*` needs is in the op).
2199+ bit_depth: u8,
2200+ enable_edge_filter: bool,
2201+ last_col: usize,
2202+}
2203+
2204+struct WaveQueue {
2205+ jobs: std::collections::VecDeque<(usize, usize, Vec<ReconOp>)>,
2206+ /// Per superblock row, the last column reconstructed (-1 = none yet).
2207+ done: Vec<isize>,
2208+ /// Jobs popped but not finished -- what [`wave_barrier`] waits out.
2209+ active: usize,
2210+ closed: bool,
2211+}
2212+
2213+#[allow(unsafe_code)]
2214+fn wave_worker(st: &WaveState) {
2215+ let fctx = FrameCtx::new();
2216+ fctx.bit_depth.set(st.bit_depth);
2217+ fctx.enable_edge_filter.set(st.enable_edge_filter);
2218+ loop {
2219+ let mut q = st.q.lock().unwrap();
2220+ let (r, c, ops) = loop {
2221+ if let Some(job) = q.jobs.pop_front() {
2222+ break job;
2223+ }
2224+ if q.closed {
2225+ return;
2226+ }
2227+ q = st.cv.wait(q).unwrap();
2228+ };
2229+ q.active += 1;
2230+ loop {
2231+ let above = r == 0 || q.done[r - 1] >= (c + 1).min(st.last_col) as isize;
2232+ let left = c == 0 || q.done[r] >= c as isize - 1;
2233+ if above && left {
2234+ break;
2235+ }
2236+ q = st.cv.wait(q).unwrap();
2237+ }
2238+ drop(q);
2239+ let ReconPlanes(y, u, v) = st.planes;
2240+ // SAFETY: this job writes only superblock (r, c)'s own pixels, and
2241+ // every superblock that could have written or be reading them is
2242+ // complete by the wavefront rule above.
2243+ unsafe {
2244+ for op in ops {
2245+ exec_op(op, &mut *y, &mut *u, &mut *v, &fctx);
2246+ }
2247+ }
2248+ let mut q = st.q.lock().unwrap();
2249+ q.done[r] = c as isize;
2250+ q.active -= 1;
2251+ st.cv.notify_all();
2252+ }
2253+}
2254+
2255+/// Installs the wavefront for one tile and joins its workers on every exit
2256+/// from the tile decoder, including the `?` ones -- the jobs hold raw
2257+/// pointers into the tile's planes, so no worker may outlive them.
2258+pub(crate) struct WaveGuard<'a>(&'a crate::decode::FrameCtx, Vec<std::thread::JoinHandle<()>>);
2259+
2260+#[allow(unsafe_code)]
2261+impl<'a> WaveGuard<'a> {
2262+ fn install(
2263+ fctx: &'a crate::decode::FrameCtx,
2264+ y: &mut PlaneBuf<'static>,
2265+ u: &mut PlaneBuf<'static>,
2266+ v: &mut PlaneBuf<'static>,
2267+ rows: usize,
2268+ cols: usize,
2269+ ) -> Option<Self> {
2270+ let threads = crate::par::recon_threads();
2271+ if threads == 1 || rows == 0 || cols == 0 {
2272+ return None;
2273+ }
2274+ let st = std::sync::Arc::new(WaveState {
2275+ q: std::sync::Mutex::new(WaveQueue {
2276+ jobs: std::collections::VecDeque::new(),
2277+ done: vec![-1; rows],
2278+ active: 0,
2279+ closed: false,
2280+ }),
2281+ cv: std::sync::Condvar::new(),
2282+ // SAFETY: the planes are locals of the tile decoder and outlive
2283+ // this guard, which joins every worker in `drop`.
2284+ planes: ReconPlanes(
2285+ std::ptr::from_mut(y),
2286+ std::ptr::from_mut(u),
2287+ std::ptr::from_mut(v),
2288+ ),
2289+ bit_depth: fctx.bit_depth.with(std::cell::Cell::get),
2290+ enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get),
2291+ last_col: cols - 1,
2292+ });
2293+ let workers = (0..threads)
2294+ .map(|_| {
2295+ let st = std::sync::Arc::clone(&st);
2296+ std::thread::spawn(move || wave_worker(&st))
2297+ })
2298+ .collect();
2299+ fctx.wave.with(|w| *w.borrow_mut() = Some(st));
2300+ Some(Self(fctx, workers))
2301+ }
2302+}
2303+
2304+impl Drop for WaveGuard<'_> {
2305+ fn drop(&mut self) {
2306+ let st = self.0.wave.with(|w| w.borrow_mut().take());
2307+ if let Some(st) = st {
2308+ st.q.lock().unwrap().closed = true;
2309+ st.cv.notify_all();
2310+ }
2311+ for h in self.1.drain(..) {
2312+ let _ = h.join();
2313+ }
2314+ }
2315+}
2316+
2317+/// Hands superblock `(r, c)`'s recorded writes to the wavefront. `false`
2318+/// when there is no wavefront (one reconstruction thread), in which case the
2319+/// caller replays them itself.
2320+fn wave_submit(fctx: &crate::decode::FrameCtx, r: usize, c: usize) -> bool {
2321+ let st = fctx.wave.with(|w| w.borrow().clone());
2322+ let Some(st) = st else { return false };
2323+ let ops = fctx.recon_ops.with(|c| std::mem::take(&mut *c.borrow_mut()));
2324+ if !ops.is_empty() {
2325+ st.q.lock().unwrap().jobs.push_back((r, c, ops));
2326+ st.cv.notify_all();
2327+ }
2328+ true
2329+}
2330+
2331+/// Waits until every submitted job is reconstructed, so the parser may read
2332+/// the planes itself (the intrabc source fetch and the interintra intra
2333+/// predictor -- see [`flush_recon`]).
2334+fn wave_barrier(fctx: &crate::decode::FrameCtx) {
2335+ let st = fctx.wave.with(|w| w.borrow().clone());
2336+ let Some(st) = st else { return };
2337+ let mut q = st.q.lock().unwrap();
2338+ while !q.jobs.is_empty() || q.active > 0 {
2339+ q = st.cv.wait(q).unwrap();
2340+ }
2341+}
2342+
2167 /// Performs an intra write at its push site when the tile registered its2343 /// Performs an intra write at its push site when the tile registered its
2168 /// planes for inline reconstruction ([`ReconPlanes`]); `false` when the2344 /// planes for inline reconstruction ([`ReconPlanes`]); `false` when the
2169 /// caller must record it for the wavefront workers instead.2345 /// caller must record it for the wavefront workers instead.
@@ -2376,6 +2552,9 @@ fn flush_recon(
2376 u: &mut PlaneBuf<'static>,2552 u: &mut PlaneBuf<'static>,
2377 v: &mut PlaneBuf<'static>,2553 v: &mut PlaneBuf<'static>,
2378 ) {2554 ) {
2555+ // lane-wave1 step (ii): a parse-time pixel READ needs every worker's
2556+ // writes in place, not just this superblock's queue.
2557+ wave_barrier(fctx);
2379 let mut ops = fctx.recon_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));2558 let mut ops = fctx.recon_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
2380 fctx.recon_ops.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut ops));2559 fctx.recon_ops.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut ops));
2381 for op in ops.drain(..) {2560 for op in ops.drain(..) {
@@ -18854,9 +19033,36 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
18854 // lane-wave1 step (ii): at one reconstruction thread the recorded writes19033 // lane-wave1 step (ii): at one reconstruction thread the recorded writes
18855 // are performed at their push sites (nothing reaches the queue below).19034 // are performed at their push sites (nothing reaches the queue below).
18856 let _recon_inline = ReconInline::install(fctx, &mut y, &mut u, &mut v);19035 let _recon_inline = ReconInline::install(fctx, &mut y, &mut u, &mut v);
19036+ // lane-wave1 step (ii): one job per superblock (per 128x128 superblock
19037+ // when `sb128`, since a 128 block writes across its four 64x64 visits).
19038+ let wave_shift = u32::from(sb128);
19039+ let (wave_r0, wave_c0) = ((sb_r0 >> wave_shift) as usize, (sb_c0 >> wave_shift) as usize);
19040+ let (wave_rows, wave_cols) = if sb_r1 > sb_r0 && sb_c1 > sb_c0 {
19041+ (
19042+ ((sb_r1 - 1) >> wave_shift) as usize - wave_r0 + 1,
19043+ ((sb_c1 - 1) >> wave_shift) as usize - wave_c0 + 1,
19044+ )
19045+ } else {
19046+ (0, 0)
19047+ };
19048+ let _wave = WaveGuard::install(fctx, &mut y, &mut u, &mut v, wave_rows, wave_cols);
19049+ let waving = fctx.wave.with(|w| w.borrow().is_some());
19050+ let mut wave_job = (0usize, 0usize);
18857 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {19051 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {
18858- // lane-wave1 step (i): the previous superblock's recorded writes.19052+ // lane-wave1: the previous superblock's recorded writes -- handed to
18859- flush_recon(fctx, &mut y, &mut u, &mut v);19053+ // the wavefront workers, or replayed here at one recon thread (where
19054+ // the queue is empty, every write having run at its push site).
19055+ if waving {
19056+ if sb_start {
19057+ wave_submit(fctx, wave_job.0, wave_job.1);
19058+ wave_job = (
19059+ (sb_r >> wave_shift) as usize - wave_r0,
19060+ (sb_c >> wave_shift) as usize - wave_c0,
19061+ );
19062+ }
19063+ } else {
19064+ flush_recon(fctx, &mut y, &mut u, &mut v);
19065+ }
18860 if row_start {19066 if row_start {
18861 neighbours.start_row();19067 neighbours.start_row();
18862 }19068 }
@@ -20597,6 +20803,9 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
20597 }20803 }
20598 }20804 }
20599 }20805 }
20806+ if waving {
20807+ wave_submit(fctx, wave_job.0, wave_job.1);
20808+ }
20600 flush_recon(fctx, &mut y, &mut u, &mut v);20809 flush_recon(fctx, &mut y, &mut u, &mut v);
20601 20810
20602 if tile_num == tile_info.context_update_tile_id {20811 if tile_num == tile_info.context_update_tile_id {
@@ -30309,9 +30518,36 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
30309 // lane-wave1 step (ii): at one reconstruction thread the recorded writes30518 // lane-wave1 step (ii): at one reconstruction thread the recorded writes
30310 // are performed at their push sites (nothing reaches the queue below).30519 // are performed at their push sites (nothing reaches the queue below).
30311 let _recon_inline = ReconInline::install(fctx, &mut y, &mut u, &mut v);30520 let _recon_inline = ReconInline::install(fctx, &mut y, &mut u, &mut v);
30521+ // lane-wave1 step (ii): one job per superblock (per 128x128 superblock
30522+ // when `sb128`, since a 128 block writes across its four 64x64 visits).
30523+ let wave_shift = u32::from(sb128);
30524+ let (wave_r0, wave_c0) = ((sb_r0 >> wave_shift) as usize, (sb_c0 >> wave_shift) as usize);
30525+ let (wave_rows, wave_cols) = if sb_r1 > sb_r0 && sb_c1 > sb_c0 {
30526+ (
30527+ ((sb_r1 - 1) >> wave_shift) as usize - wave_r0 + 1,
30528+ ((sb_c1 - 1) >> wave_shift) as usize - wave_c0 + 1,
30529+ )
30530+ } else {
30531+ (0, 0)
30532+ };
30533+ let _wave = WaveGuard::install(fctx, &mut y, &mut u, &mut v, wave_rows, wave_cols);
30534+ let waving = fctx.wave.with(|w| w.borrow().is_some());
30535+ let mut wave_job = (0usize, 0usize);
30312 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {30536 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {
30313- // lane-wave1 step (i): the previous superblock's recorded writes.30537+ // lane-wave1: the previous superblock's recorded writes -- handed to
30314- flush_recon(fctx, &mut y, &mut u, &mut v);30538+ // the wavefront workers, or replayed here at one recon thread (where
30539+ // the queue is empty, every write having run at its push site).
30540+ if waving {
30541+ if sb_start {
30542+ wave_submit(fctx, wave_job.0, wave_job.1);
30543+ wave_job = (
30544+ (sb_r >> wave_shift) as usize - wave_r0,
30545+ (sb_c >> wave_shift) as usize - wave_c0,
30546+ );
30547+ }
30548+ } else {
30549+ flush_recon(fctx, &mut y, &mut u, &mut v);
30550+ }
30315 if row_start {30551 if row_start {
30316 neighbours.start_row();30552 neighbours.start_row();
30317 }30553 }
@@ -32655,6 +32891,9 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
32655 }32891 }
32656 }32892 }
32657 }32893 }
32894+ if waving {
32895+ wave_submit(fctx, wave_job.0, wave_job.1);
32896+ }
32658 flush_recon(fctx, &mut y, &mut u, &mut v);32897 flush_recon(fctx, &mut y, &mut u, &mut v);
32659 32898
32660 if tile_num == tile_info.context_update_tile_id {32899 if tile_num == tile_info.context_update_tile_id {
crates/ec-av1/src/stream.rsmodified+44 -0
@@ -6106,6 +6106,50 @@ mod tests {
6106 /// `--denoise-noise-level=25` stream whose frames carry film grain6106 /// `--denoise-noise-level=25` stream whose frames carry film grain
6107 /// parameters (small enough that 4 bands is one block row each, which is6107 /// parameters (small enough that 4 bands is one block row each, which is
6108 /// what exercises the grain band's one-row `prelude` replay).6108 /// what exercises the grain band's one-row `prelude` replay).
6109+ /// lane-wave1 step (ii): the superblock-row wavefront
6110+ /// (`EC_AV1_RECON_THREADS`) reconstructs every output frame byte for
6111+ /// byte as the inline path does, on a hidden-ARF 10-bit stream (no-show
6112+ /// frames, CfL, 128 superblocks) and on the two screen-content streams
6113+ /// whose palette/intrabc blocks READ the current frame's pixels while
6114+ /// parsing -- the sites that make the workers barrier.
6115+ #[test]
6116+ fn a_real_stream_reconstructs_identically_with_one_and_four_recon_threads() {
6117+ const NAME: &str = "a_real_stream_reconstructs_identically_with_one_and_four_recon_threads";
6118+ let _gate_lock = lock_gate_counters();
6119+ for fixture in [
6120+ "reelb_arf_witness.obu",
6121+ "palette_screen_witness.obu",
6122+ "palette_screen_witness_10bit.obu",
6123+ ] {
6124+ let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
6125+ .join("fixtures")
6126+ .join(fixture);
6127+ let stream = std::fs::read(&path)
6128+ .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
6129+ crate::par::set_recon_threads(1);
6130+ let one = match decode_stream(&stream) {
6131+ Ok(frames) => frames,
6132+ Err(e) => panic!("{NAME}: {fixture} refused at 1 recon thread: {e}"),
6133+ };
6134+ crate::par::set_recon_threads(4);
6135+ let four = match decode_stream(&stream) {
6136+ Ok(frames) => frames,
6137+ Err(e) => {
6138+ crate::par::set_recon_threads(1);
6139+ panic!("{NAME}: {fixture} refused at 4 recon threads: {e}")
6140+ }
6141+ };
6142+ crate::par::set_recon_threads(1);
6143+ assert!(!one.is_empty(), "{NAME}: {fixture} decoded nothing");
6144+ assert_eq!(one.len(), four.len(), "{NAME}: {fixture} frame count");
6145+ for (i, (a, b)) in one.iter().zip(four.iter()).enumerate() {
6146+ assert_eq!(a.y, b.y, "{NAME}: {fixture} frame {i} luma differs at 4 recon threads");
6147+ assert_eq!(a.u, b.u, "{NAME}: {fixture} frame {i} U differs at 4 recon threads");
6148+ assert_eq!(a.v, b.v, "{NAME}: {fixture} frame {i} V differs at 4 recon threads");
6149+ }
6150+ }
6151+ }
6152+
6109 #[test]6153 #[test]
6110 fn a_real_stream_filters_identically_with_one_and_four_filter_threads() {6154 fn a_real_stream_filters_identically_with_one_and_four_filter_threads() {
6111 const NAME: &str = "a_real_stream_filters_identically_with_one_and_four_filter_threads";6155 const NAME: &str = "a_real_stream_filters_identically_with_one_and_four_filter_threads";