diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index fb589431..a8788ba4 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -19725,6 +19725,16 @@ pub(crate) struct FilterReplay { frame_height: usize, width: usize, height: usize, + /// The reconstructed extent (`mi_cols`/`mi_rows` * 4), for the wide-margin + /// 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 @@ -19745,6 +19755,17 @@ pub(crate) fn arm_filter_replay() { REPLAY_ARMED.set(true); } +/// Test-only: force every filter candidate through a full decode, so a gate +/// can hold the replay against the decode it stands in for +/// (`encoder::tests::filter_replay_codes_the_same_stream_as_a_full_decode`). +#[cfg(test)] +static REPLAY_DISABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +#[cfg(test)] +pub(crate) fn set_filter_replay_disabled(off: bool) { + REPLAY_DISABLED.store(off, std::sync::atomic::Ordering::Relaxed); +} + /// Drop the armed flag and anything captured: the tile it belongs to is done. pub(crate) fn clear_filter_replay() { REPLAY_ARMED.set(false); @@ -19762,6 +19783,8 @@ fn capture_filter_replay( frame_height: usize, width: usize, height: usize, + true_width: usize, + true_height: usize, ) { if !REPLAY_ARMED.replace(false) { return; @@ -19777,11 +19800,38 @@ fn capture_filter_replay( frame_height, width, 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 @@ -19791,18 +19841,30 @@ pub(crate) fn replay_filters( cdef: &CdefParams, fctx: &FrameCtx, ) -> Option { + #[cfg(test)] + if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) { + return None; + } 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, &mut u, @@ -19813,21 +19875,67 @@ 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); - // The capture only happens on the shape the decoder's own tail - // returns whole (no superres, no loop restoration, no crop), so this - // is that tail. - fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None); - Some(Picture { - width: r.width, - height: r.height, - y: y.data.into_owned(), - u: u.data.into_owned(), - v: v.data.into_owned(), - }) + drop(ct); + // The capture only happens on the shape whose tail is the two + // filter calls and the crop (no superres, no loop restoration), so + // what is left is that crop -- byte for byte the cropped return path + // of the decode this replaces, wide-margin stash included. + // + // lane-av1fpar: the crop is why this arm exists at all. The capture + // used to demand `frame == plane` dimensions, which no editor size + // meets (1080 and 1608 both pad to a superblock row), so every + // candidate of every frame at those sizes fell through to a full + // re-decode -- 57% of a 1080p frame's wall. + let (fw, fh) = (r.frame_width, r.frame_height); + if fw == r.width && fh == r.height { + fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None); + return Some(Picture { + width: r.width, + height: r.height, + y: y.data.into_owned(), + u: u.data.into_owned(), + v: v.data.into_owned(), + }); + } + let crop = |plane: &PlaneBuf<'_>, w: usize, h: usize| -> Vec { + let mut out = Vec::with_capacity(w * h); + for row in 0..h { + out.extend(plane.data[row * plane.width..][..w].iter().copied()); + } + out + }; + let (tw, th) = (r.true_width, r.true_height); + fctx.last_frame_wide_margin.with(|m| { + *m.borrow_mut() = (tw > fw || th > fh).then(|| Picture { + width: tw, + height: th, + y: crop(&y, tw, th), + u: crop(&u, tw.div_ceil(2), th.div_ceil(2)), + v: crop(&v, tw.div_ceil(2), th.div_ceil(2)), + }); + }); + let out = Picture { + width: fw, + height: fh, + 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) }) } @@ -23110,8 +23218,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // frame tile per candidate -- capture it once (see [`FilterReplay`]), // on the shape whose tail is the two filter calls and nothing else. if superres(fctx).is_none() - && frame_width as usize == width - && frame_height as usize == height && !(0..3).any(|p| { lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None && lr.loop_restoration_size[p] != 0 @@ -23126,6 +23232,8 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( frame_height as usize, width, height, + true_width, + true_height, ); } apply_deblock( @@ -35847,12 +35955,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // same coded tile ([`FilterReplay`]). Capture the reconstruction here, // before either filter has touched it -- but only on the shape whose // tail is exactly `apply_deblock` + `apply_cdef` and nothing else. - if !pipelined - && !lr_active - && superres(fctx).is_none() - && frame_width as usize == width - && frame_height as usize == height - { + if !pipelined && !lr_active && superres(fctx).is_none() { capture_filter_replay( &y, &u, @@ -35862,6 +35965,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( frame_height as usize, width, height, + true_width, + true_height, ); } if pipelined { diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 2fd8beab..a21cb930 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -3498,6 +3498,7 @@ fn write_tiles(tiles: usize, store: usize, code: F) -> Result<(Vec>, where F: Fn(usize) -> Result<(Vec, Option)> + Sync + Send, { + let _t = crate::par::timer(crate::par::S_TILE_WRITE); type Slot = Option, Option)>>; let threads = crate::par::tile_threads().min(tiles); let mut slots: Vec = Vec::new(); @@ -3553,6 +3554,7 @@ where T: Send, F: Fn(usize, &crate::decode::FrameCtx) -> Result + Sync, { + let _t = crate::par::timer(crate::par::S_TILE_SEARCH); let threads = crate::par::tile_threads().min(tiles); if threads <= 1 { return (0..tiles).map(|index| job(index, fctx)).collect(); @@ -4333,12 +4335,19 @@ 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| { if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) { 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, @@ -4348,6 +4357,7 @@ fn pick_and_apply_filters( (sb_cols, sb_rows), lambda, ); + drop(ft); crate::decode::clear_filter_replay(); let (lf, cdef, idx_grid, picture) = search_result?; header.loop_filter = lf; @@ -4370,12 +4380,14 @@ fn pick_and_apply_filters( fctx.capture_stages.set(lr_on); let mut filtered = if idx_grid.is_empty() { if lr_on { + let _t = crate::par::timer(crate::par::S_CAPTURE); decode(&lf, &cdef, &hdr, tiles, &none_lr)? } else { picture } } else { let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?; + let _t = crate::par::timer(crate::par::S_CAPTURE); let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?; *tiles = coded; picture @@ -4389,6 +4401,7 @@ fn pick_and_apply_filters( ..LoopRestorationParams::default() }; want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener; + let lrt = crate::par::timer(crate::par::S_LR); let units = match crate::decode::take_filter_stages(fctx) { Some(stages) => crate::filter_search::pick_restoration( &stages, @@ -4405,8 +4418,10 @@ fn pick_and_apply_filters( // rather than paying ~1 bit per 64x64 for a tile full of // `restore_wiener = 0` symbols (the BD gate saw exactly that on the // clip whose units never take a filter). + drop(lrt); if units.iter().any(Option::is_some) { let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?; + let _t = crate::par::timer(crate::par::S_CAPTURE); filtered = decode(&lf, &cdef, &hdr, &coded, &want)?; *tiles = coded; lr = want; diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index b31d2980..d5fa718a 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -1862,6 +1862,178 @@ 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, + /// byte for byte -- including at a size that CROPS (1080 and 1608 both + /// pad to a superblock row, i.e. every export size the editor uses), + /// which is the arm this lane opened. + #[test] + fn filter_replay_codes_the_same_stream_as_a_full_decode() { + let _gate_lock = crate::stream::tests::lock_gate_counters(); + let run = |width: usize, height: usize, off: bool| { + let sources: Vec = (0..4).map(|t| test_card(width, height, t * 3)).collect(); + crate::decode::set_filter_replay_disabled(off); + 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); + } + crate::decode::set_filter_replay_disabled(false); + stream + }; + // 320x160 crops (the coding surface is 320x192, one superblock row + // taller); 320x192 is a whole number of superblocks, the shape the + // replay already covered. + for (width, height) in [(320usize, 160usize), (320, 192)] { + let replayed = run(width, height, false); + let decoded = run(width, height, true); + assert_eq!( + replayed, + decoded, + "{width}x{height}: the filter replay is not the decode it stands in for \ + ({} bytes replayed, {} decoded)", + replayed.len(), + decoded.len(), + ); + } + } + + /// lane-av1fpar: where a frame's wall actually goes, stage by stage -- + /// the per-tile search, the tile write, the frame-level filter search + /// (with its deblock/CDEF replay and per-64 SSE inside it), the capture + /// decode the loop-restoration search rides on, and that search itself. + /// Measurement, not a pass/fail gate. + #[test] + #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] + fn filter_stage_wall_1080p() { + filter_stage_wall(1920, 1080, 8, (2, 1), &[8]); + } + + #[test] + #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] + fn filter_stage_wall_4k() { + filter_stage_wall(3840, 1608, 4, (2, 1), &[8, 12]); + } + + fn filter_stage_wall( + width: usize, + height: usize, + frames: usize, + (cols_log2, rows_log2): (u32, u32), + threads: &[usize], + ) { + let _gate_lock = crate::stream::tests::lock_gate_counters(); + let Some(sources) = h264_clip_frames(width, height, frames) else { + eprintln!("SKIP the filter-stage breakdown: no fixture or no ffmpeg"); + return; + }; + crate::par::set_stage_times(true); + for &t in threads { + crate::par::set_tile_threads(t); + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: frames, + colour: Colour::Bt709Limited, + tile_cols_log2: cols_log2, + tile_rows_log2: rows_log2, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let _ = crate::par::take_stage_ns(); + let start = std::time::Instant::now(); + for picture in &sources { + assert!(!enc.encode(picture).unwrap().data.is_empty()); + } + let wall = start.elapsed().as_secs_f64(); + let ns = crate::par::take_stage_ns(); + let ms = |i: usize| ns[i] as f64 / 1e6; + eprintln!( + "\n{width}x{height}, {frames} frames, {}x{} tiles, {t} tile threads: \ + {wall:.2}s wall, {:.2} fps", + 1 << cols_log2, + 1 << rows_log2, + frames as f64 / wall, + ); + eprintln!("| stage | ms | ms/frame | % of wall |"); + for (i, name) in crate::par::STAGES.iter().enumerate() { + eprintln!( + "| {name} | {:.0} | {:.1} | {:.1}% |", + ms(i), + ms(i) / frames as f64, + 100.0 * ms(i) / (wall * 1e3), + ); + } + // Top-level stages only (the deblock/CDEF/SSE rows are inside + // the filter-search total); the rest is per-frame setup, the + // source conversion and the splice. + let top: f64 = [ + crate::par::S_TILE_SEARCH, + crate::par::S_TILE_WRITE, + crate::par::S_FILTER, + crate::par::S_CAPTURE, + crate::par::S_LR, + ] + .iter() + .map(|&i| ms(i)) + .sum(); + eprintln!( + "accounted {:.1}% of wall; outside the tile search {:.1}%", + 100.0 * top / (wall * 1e3), + 100.0 * (1.0 - ms(crate::par::S_TILE_SEARCH) / (wall * 1e3)), + ); + } + crate::par::set_stage_times(false); + crate::par::set_tile_threads(1); + } + fn tile_search_wall( width: usize, height: usize, diff --git a/crates/ec-av1/src/filter_search.rs b/crates/ec-av1/src/filter_search.rs index 40372902..d2e94a5d 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; @@ -196,6 +238,7 @@ pub(crate) fn pick_filters( (cand.lf.0, cand.y), (if cand.uv == (0, 0) { 0 } else { cand.lf.0 }, cand.lf.1, cand.uv), ); + let sst = crate::par::timer(crate::par::S_SSE); if !st.luma.iter().any(|(k, _)| *k == lkey) { let mut units = vec![0u64; nsb]; let sse = @@ -208,6 +251,7 @@ pub(crate) fn pick_filters( + unit_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch, 32, sb_cols, &mut units); st.chroma.push((ckey, (sse, units))); } + drop(sst); let (sse_y, sse_uv, sse64) = { let l = &st.luma.iter().find(|(k, _)| *k == lkey).expect("just inserted").1; let c = &st.chroma.iter().find(|(k, _)| *k == ckey).expect("just inserted").1; @@ -456,13 +500,33 @@ pub(crate) fn pick_restoration( sse }; // Cost of leaving every unit alone, then one whole-plane pass per - // candidate to price taking it. - let mut best: Vec<(f64, Option)> = (0..horz * vert) - .map(|i| { - let sse = unit_sse(&stages.cdefed[0], i / horz, i % horz) as f64; - (sse + lambda * LR_NONE_BITS, None) - }) - .collect(); + // candidate to price taking it. Both walks are banded by unit ROW + // (lane-av1fpar): a unit's cost is read off its own samples alone and + // written to its own slot, so the bands are `chunks_mut` of the same + // `best` and the choice cannot depend on how many of them there are. + let rows_of = |plane: &[u16], r0: usize, slice: &mut [(f64, Option)], score: &dyn Fn(u64, &mut (f64, Option))| { + for (i, slot) in slice.iter_mut().enumerate() { + score(unit_sse(plane, r0 + i / horz, i % horz), slot); + } + }; + let banded = |plane: &[u16], best: &mut [(f64, Option)], score: &(dyn Fn(u64, &mut (f64, Option)) + Sync)| { + let threads = crate::par::filter_threads().min(vert); + if threads <= 1 { + rows_of(plane, 0, best, score); + return; + } + let per = vert.div_ceil(threads); + let batch = crate::par::Batch::new("ec-av1-filter"); + for (band, slice) in best.chunks_mut(per * horz).enumerate() { + let rows_of = &rows_of; + batch.submit(move || rows_of(plane, band * per, slice, score)); + } + }; + let mut best: Vec<(f64, Option)> = + vec![(0.0, None); horz * vert]; + banded(&stages.cdefed[0], &mut best, &|sse, slot| { + *slot = (sse as f64 + lambda * LR_NONE_BITS, None); + }); let mut out = Vec::new(); for taps in WIENER_CANDIDATES { let info = crate::restoration::wiener_from_taps(taps, taps); @@ -487,15 +551,12 @@ pub(crate) fn pick_restoration( None, fctx, ); - for rrow in 0..vert { - for rcol in 0..horz { - let cost = unit_sse(&out, rrow, rcol) as f64 + lambda * LR_WIENER_BITS; - let slot = &mut best[rcol + rrow * horz]; - if cost < slot.0 { - *slot = (cost, Some(info)); - } + banded(&out, &mut best, &|sse, slot| { + let cost = sse as f64 + lambda * LR_WIENER_BITS; + if cost < slot.0 { + *slot = (cost, Some(info)); } - } + }); } let chosen: Vec> = best.into_iter().map(|(_, f)| f).collect(); @@ -554,5 +615,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 3ad04f74..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") @@ -459,3 +492,80 @@ impl Drop for Batch<'_> { } } } + +// --- lane-av1fpar: encoder per-stage wall breakdown ----------------------- +// +// Amdahl on the per-tile search (lane-av1tsearch) put ~43% of an inter frame +// OUTSIDE the tile search without saying what it was. These counters name it: +// one accumulator per serial stage of `encode_*_frame`, added to on whatever +// thread runs the stage and printed by `encoder::tests::filter_stage_wall_*`. +// 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; 10] = [ + "tile search", + "tile write", + "filter: deblock replay", + "filter: cdef replay", + "filter: sse", + "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; +pub(crate) const S_DEBLOCK: usize = 2; +pub(crate) const S_CDEF: usize = 3; +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()]; +/// 0 = not read yet, 1 = off, 2 = on. `EC_AV1_STAGE_TIMES`, or +/// [`set_stage_times`] from a gate (the env snapshot is process-constant). +static STAGE_ON: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +fn stage_times() -> bool { + match STAGE_ON.load(std::sync::atomic::Ordering::Relaxed) { + 0 => { + let on = 1 + usize::from(crate::envflags::is_set("EC_AV1_STAGE_TIMES")); + STAGE_ON.store(on, std::sync::atomic::Ordering::Relaxed); + on == 2 + } + n => n == 2, + } +} + +/// Test-only override of [`stage_times`]; process-global. +#[cfg(test)] +pub(crate) fn set_stage_times(on: bool) { + STAGE_ON.store(1 + usize::from(on), std::sync::atomic::Ordering::Relaxed); +} + +/// A live stage measurement: added to stage `i` when it drops. `None` when +/// the breakdown is off, so a call site is `let _t = par::timer(S_X);`. +pub(crate) struct Timer(usize, std::time::Instant); + +#[inline] +pub(crate) fn timer(i: usize) -> Option { + stage_times().then(|| Timer(i, std::time::Instant::now())) +} + +impl Drop for Timer { + fn drop(&mut self) { + STAGE_NS[self.0] + .fetch_add(self.1.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed); + } +} + +/// Takes and clears the breakdown, in [`STAGES`] order. +#[cfg(test)] +pub(crate) fn take_stage_ns() -> [u64; STAGES.len()] { + std::array::from_fn(|i| STAGE_NS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +}