diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 7b76ac74..a8788ba4 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -19729,6 +19729,12 @@ pub(crate) struct FilterReplay { /// stash the cropped return path leaves behind. true_width: usize, true_height: usize, + /// lane-av1fpar: plane buffers this replay is done with. Every candidate + /// works on its own copy of three ~6 MB planes, and a fresh `Vec` per + /// copy is a fresh mmap the kernel faults in page by page -- 12.6% of a + /// 1080p frame's wall in allocation, not in filtering. Recycled here + /// instead; the pool holds at most the six planes one candidate has live. + scratch: Vec>, /// The last deblocked planes and the levels that produced them. /// Deblocking depends on nothing else the search moves, and the search /// fixes the levels before it walks the CDEF strengths, so every @@ -19796,11 +19802,36 @@ fn capture_filter_replay( height, true_width, true_height, + scratch: Vec::new(), deblocked: None, }); }); } +/// One candidate's working copy of a captured plane, off [`FilterReplay`]'s +/// own buffer pool: a cleared `Vec` that already has the capacity keeps the +/// allocator and the page fault handler out of the filter search. +fn pooled(p: &PlaneBuf<'_>, scratch: &mut Vec>) -> PlaneBuf<'static> { + let mut buf = scratch.pop().unwrap_or_default(); + let src: &[u16] = &p.data; + let threads = crate::par::filter_threads(); + if buf.len() != src.len() || threads <= 1 { + buf.clear(); + buf.extend_from_slice(src); + } else { + // A recycled buffer is already the right length, so the copy is a + // plain `copy_from_slice` -- and one worth banding: ~6 MB per + // candidate is memory bandwidth, not arithmetic, and the halves are + // disjoint `&mut` slices (no `par::Shared` needed). + let per = src.len().div_ceil(threads); + let batch = crate::par::Batch::new("ec-av1-filter"); + for (dst, src) in buf.chunks_mut(per).zip(src.chunks(per)) { + batch.submit(move || dst.copy_from_slice(src)); + } + } + PlaneBuf { data: std::borrow::Cow::Owned(buf), ..*p } +} + /// The filter half of a captured decode, under new parameters: exactly the /// [`apply_deblock`] / [`apply_cdef`] pair the decoder's own tail runs, on a /// copy of the captured planes. `None` when nothing is captured (the caller @@ -19816,16 +19847,23 @@ pub(crate) fn replay_filters( } REPLAY.with_borrow_mut(|slot| { let r = slot.as_mut()?; - let copy = |p: &PlaneBuf<'_>| PlaneBuf { - data: std::borrow::Cow::Owned(p.data.to_vec()), - ..*p - }; let hit = matches!(&r.deblocked, Some((lf, ..)) if lf == loop_filter); + let cpt = crate::par::timer(crate::par::S_COPY); let (mut y, mut u, mut v) = if hit { - let (_, dy, du, dv) = r.deblocked.as_ref().expect("just matched"); - (copy(dy), copy(du), copy(dv)) + let (deblocked, scratch) = (&r.deblocked, &mut r.scratch); + let (_, dy, du, dv) = deblocked.as_ref().expect("just matched"); + (pooled(dy, scratch), pooled(du, scratch), pooled(dv, scratch)) } else { - let (mut y, mut u, mut v) = (copy(&r.y), copy(&r.u), copy(&r.v)); + // The levels moved, so the cached deblocked planes are dead: + // their buffers are this candidate's working copies. + if let Some((_, dy, du, dv)) = r.deblocked.take() { + r.scratch.push(dy.data.into_owned()); + r.scratch.push(du.data.into_owned()); + r.scratch.push(dv.data.into_owned()); + } + let (cap_y, cap_u, cap_v, scratch) = (&r.y, &r.u, &r.v, &mut r.scratch); + let (mut y, mut u, mut v) = + (pooled(cap_y, scratch), pooled(cap_u, scratch), pooled(cap_v, scratch)); let _t = crate::par::timer(crate::par::S_DEBLOCK); apply_deblock( &mut y, @@ -19837,9 +19875,12 @@ pub(crate) fn replay_filters( r.frame_height, fctx, ); - r.deblocked = Some((*loop_filter, copy(&y), copy(&u), copy(&v))); + let scratch = &mut r.scratch; + r.deblocked = + Some((*loop_filter, pooled(&y, scratch), pooled(&u, scratch), pooled(&v, scratch))); (y, u, v) }; + drop(cpt); let ct = crate::par::timer(crate::par::S_CDEF); apply_cdef(&mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx); drop(ct); @@ -19881,13 +19922,20 @@ pub(crate) fn replay_filters( v: crop(&v, tw.div_ceil(2), th.div_ceil(2)), }); }); - Some(Picture { + let out = Picture { width: fw, height: fh, - y: crop_owned(y, fw, fh), - u: crop_owned(u, fw.div_ceil(2), fh.div_ceil(2)), - v: crop_owned(v, fw.div_ceil(2), fh.div_ceil(2)), - }) + y: crop(&y, fw, fh), + u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)), + v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)), + }; + // The working planes outlive the crop, so they go back to the pool. + for plane in [y, u, v] { + if r.scratch.len() < 6 { + r.scratch.push(plane.data.into_owned()); + } + } + Some(out) }) } diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index d75f16a0..8719a563 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -4146,6 +4146,11 @@ fn pick_and_apply_filters( // preset search reads comes off the REPLAYED picture, which is the same // picture a decode produces -- that is what the replay is pinned on. crate::decode::clear_filter_replay(); + // lane-av1fpar: the per-tile search is over, so every core is idle from + // here to the end of the frame -- band each candidate's deblock/CDEF + // replay, the capture decode's own filter chain and the loop-restoration + // passes across the same workers the search used. + let _bands = crate::par::override_filter_threads(crate::par::tile_threads()); let ft = crate::par::timer(crate::par::S_FILTER); let search_result = crate::filter_search::pick_filters( |lf, cdef| { @@ -4153,6 +4158,7 @@ fn pick_and_apply_filters( return Ok(picture); } crate::decode::arm_filter_replay(); + let _t = crate::par::timer(crate::par::S_FIRST); decode(lf, cdef, &hdr, tiles, &none_lr) }, source, diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index d331570b..d5fa718a 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -1862,6 +1862,43 @@ mod tests { tile_search_wall(3840, 1608, 6, &[(2, 1), (3, 2)], &[1, 8, 12]); } + /// lane-av1fpar: the frame-level FILTER stage is banded across the same + /// workers the tile search uses (`par::override_filter_threads`), so the + /// deblock/CDEF replays, the per-64 SSE and the plane copies all run in + /// pieces. Every piece is a disjoint band of the same integers, so the + /// stream must not move -- at a size that crops and is several superblock + /// rows tall, which is what makes the bands non-trivial. + #[test] + fn filter_stage_bytes_do_not_depend_on_the_thread_count() { + let _gate_lock = crate::stream::tests::lock_gate_counters(); + let (width, height) = (384usize, 288usize); + let sources: Vec = (0..4).map(|t| test_card(width, height, t * 3)).collect(); + let coded = |threads: usize| { + crate::par::set_tile_threads(threads); + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: 2, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let mut stream = Vec::new(); + for picture in &sources { + stream.extend_from_slice(&enc.encode(picture).unwrap().data); + } + stream + }; + // One tile, so only the filter stage can differ between these. + let one = coded(1); + for threads in [2usize, 4, 8] { + assert_eq!(one, coded(threads), "the filter stage moved at {threads} threads"); + } + crate::par::set_tile_threads(1); + } + /// lane-av1fpar: the filter search scores its ~30 candidates by replaying /// the loop filters on one captured reconstruction instead of decoding /// the coded tile again per candidate. The replay must be that decode, diff --git a/crates/ec-av1/src/filter_search.rs b/crates/ec-av1/src/filter_search.rs index b9403a17..ac01ee4a 100644 --- a/crates/ec-av1/src/filter_search.rs +++ b/crates/ec-av1/src/filter_search.rs @@ -81,10 +81,52 @@ fn unit_sse( unit: usize, sb_cols: usize, out: &mut [u64], +) -> u64 { + // lane-av1fpar: the whole-frame pass, split across the filter workers by + // UNIT ROW -- each band owns its own rows of `out` (`chunks_mut`, so the + // disjointness is the borrow checker's) and its partial totals are `u64` + // integers, which add up to the same value in any order. + let threads = crate::par::filter_threads().min(h.div_ceil(unit)); + if threads <= 1 { + return unit_sse_rows(dec, dec_w, src, src_w, w, 0, h, unit, sb_cols, out); + } + let per = h.div_ceil(unit).div_ceil(threads); + let total = std::sync::atomic::AtomicU64::new(0); + { + let batch = crate::par::Batch::new("ec-av1-filter"); + for (band, rows) in out.chunks_mut(per * sb_cols).enumerate() { + let (r0, r1) = ((band * per * unit).min(h), ((band + 1) * per * unit).min(h)); + if r0 == r1 { + continue; + } + let total = &total; + batch.submit(move || { + let sse = unit_sse_rows(dec, dec_w, src, src_w, w, r0, r1, unit, sb_cols, rows); + total.fetch_add(sse, std::sync::atomic::Ordering::Relaxed); + }); + } + } + total.into_inner() +} + +/// [`unit_sse`] over rows `r0..r1` alone, accumulating into `out` as if it +/// started at unit row `r0 / unit`. +#[allow(clippy::too_many_arguments)] +fn unit_sse_rows( + dec: &[u16], + dec_w: usize, + src: &[u8], + src_w: usize, + w: usize, + r0: usize, + r1: usize, + unit: usize, + sb_cols: usize, + out: &mut [u64], ) -> u64 { let mut total = 0u64; - for row in 0..h { - let base = (row / unit) * sb_cols; + for row in r0..r1 { + let base = ((row - r0) / unit) * sb_cols; let (d, s) = (&dec[row * dec_w..][..w], &src[row * src_w..][..w]); for (i, (dc, sc)) in d.chunks(unit).zip(s.chunks(unit)).enumerate() { let mut acc = 0u32; @@ -556,5 +598,17 @@ mod tests { let mut got = vec![7u64; sb_cols * 4]; assert_eq!(unit_sse(&dec, dec_w, &src, src_w, w, h, unit, sb_cols, &mut got), total); assert_eq!(got, want); + // lane-av1fpar: and banded across workers -- same per-unit slots, + // same frame total (the partial sums are integers). + for threads in [2usize, 4, 8] { + let _bands = crate::par::override_filter_threads(threads); + let mut banded = vec![7u64; sb_cols * 4]; + assert_eq!( + unit_sse(&dec, dec_w, &src, src_w, w, h, unit, sb_cols, &mut banded), + total, + "{threads} bands: the frame total moved" + ); + assert_eq!(banded, want, "{threads} bands: a unit's error moved"); + } } } diff --git a/crates/ec-av1/src/par.rs b/crates/ec-av1/src/par.rs index db791017..517ad409 100644 --- a/crates/ec-av1/src/par.rs +++ b/crates/ec-av1/src/par.rs @@ -32,7 +32,40 @@ /// touching the process environment. static FILTER_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +thread_local! { + /// This thread's override of [`filter_threads`], 0 = none. The ENCODER's + /// frame-level filter search sets it for the span of that search + /// (lane-av1fpar): the tile search is over by then, so every core is + /// free, and each candidate's deblock/CDEF replay is exactly the banded + /// stage the decoder already splits -- same bands, same byte-exact + /// output, gated by + /// `a_real_stream_filters_identically_with_one_and_four_filter_threads` + /// on the decode side and by + /// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count` here. + static FILTER_BANDS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Restores the previous [`FILTER_BANDS`] override when it drops. +pub(crate) struct FilterBands(usize); + +impl Drop for FilterBands { + fn drop(&mut self) { + FILTER_BANDS.set(self.0); + } +} + +/// Bands every filter stage on THIS thread across `n` workers until the +/// returned guard drops; `n <= 1` leaves the process default in place. +pub(crate) fn override_filter_threads(n: usize) -> FilterBands { + let previous = FILTER_BANDS.replace(if n > 1 { n.clamp(1, 64) } else { 0 }); + FilterBands(previous) +} + pub(crate) fn filter_threads() -> usize { + let over = FILTER_BANDS.get(); + if over > 0 { + return over; + } match FILTER_THREADS.load(std::sync::atomic::Ordering::Relaxed) { 0 => { let n = crate::envflags::var("EC_AV1_FILTER_THREADS") @@ -469,7 +502,7 @@ impl Drop for Batch<'_> { // Off (the default) each `stage` call is one relaxed atomic load. /// The stages [`stage`] accumulates, in the order a frame runs them. -pub(crate) const STAGES: [&str; 8] = [ +pub(crate) const STAGES: [&str; 10] = [ "tile search", "tile write", "filter: deblock replay", @@ -478,6 +511,8 @@ pub(crate) const STAGES: [&str; 8] = [ "filter search (total)", "capture decode", "lr search", + "filter: plane copies", + "filter: first decode", ]; pub(crate) const S_TILE_SEARCH: usize = 0; pub(crate) const S_TILE_WRITE: usize = 1; @@ -487,6 +522,8 @@ pub(crate) const S_SSE: usize = 4; pub(crate) const S_FILTER: usize = 5; pub(crate) const S_CAPTURE: usize = 6; pub(crate) const S_LR: usize = 7; +pub(crate) const S_COPY: usize = 8; +pub(crate) const S_FIRST: usize = 9; static STAGE_NS: [std::sync::atomic::AtomicU64; STAGES.len()] = [const { std::sync::atomic::AtomicU64::new(0) }; STAGES.len()];