forge
Explore
Log in

Don't you dare go Hollow

Run the loop filters per superblock row, pipelined behind reconstruction

Browse files at this commit

7fd0e677ca0e9e6049b481a74b9584a8dee0205bAhmet Kaan GümüşParent: a360df6
  • perf
    • run the loop filters per superblock row, pipelined behind reconstruction
Show full message
perf(av1): run the loop filters per superblock row, pipelined behind reconstruction

The frame's filters used to run only once the whole tile was parsed and
reconstructed: the tile loop ended, the wavefront drained, and then
apply_deblock / plane_snapshot / apply_cdef walked the whole picture on the
frame thread. With ~2.5 frames in flight the wall tracks that frame thread's
own latency, and the whole-frame filter stage is ~19% of it. dav1d and libaom
instead run the filters a few superblock rows behind reconstruction, so the
filter work overlaps the parse.

DEPENDENCY SHAPE (a band = 64 luma rows = one superblock row; derived from
this decoder's own whole-frame order: all vertical deblock edges, then all
horizontal ones, then CDEF, then superres, then loop restoration):

  * intra prediction of band r+1 reads the UNFILTERED bottom rows of band r,
    so no filter may touch band r until band r+1 is fully reconstructed:
    V(r) waits for ready >= r+2.
  * the horizontal edge at y = r*64 reads and writes 6-7 rows either side of
    the band boundary, so H(r-1)'s last edge reaches into band r, which the
    whole-frame order has already vertical-filtered. Running V(r) before
    H(r-1) reproduces that exactly.
  * band j's own bottom rows are still rewritten by H(j+1)'s first edge, so
    j's post-deblock snapshot may only be taken after H(j+1).
  * CDEF(j) reads the post-deblock picture 2-3 rows across its 64x64
    boundaries, i.e. bands j-1..j+1, so it runs after snap(j+1).

Iteration k therefore runs V(k), H(k-1), snap(k-2), CDEF(k-3), on the filter
pool, released by the frame thread at every superblock row start from the
wavefront's own per-row completion (WaveQueue now tracks the last column
parsed and the last job pushed per row, so a row that recorded no write still
counts as complete). Rows still pending at the end of the tile loop are
drained there; loop restoration, the superres upscale, motion field and grain
stay in the frame thread's tail, and LR reads the snapshot the pipeline built
band by band (whole rows when CDEF is on, else only the four rows per stripe
boundary plane_snapshot copied).

Kept whole-frame, and counted (EC_AV1_WAVE_STATS prints pipe=<pipelined>/<frames>):
superres frames (a whole-plane resample between CDEF and LR), segmentation
(the deblocker reads seg_ids while the parse thread is still filling it),
delta_lf, more than one tile COLUMN, every pixel-dump/stage-skip debug flag,
and the (1,1) thread setting -- where the filters would move to a worker
thread for nothing and the crate's thread_local gate counters would miss them.
EC_AV1_PIPE_FILTERS=0 forces the whole-frame path. Key frames keep it too:
only the inter tile decoder is wired.

Byte-exact: the 12-hash gate at 4 and at 16/(4,2) reproduces every reference
hash; seg4k reports pipe=272/272.
crates/ec-av1/src/decode.rsmodified+570 -88
@@ -2537,6 +2537,13 @@ struct WaveQueue {
25372537 queued: usize,
25382538 /// Per superblock row, the last column reconstructed (-1 = none yet).
25392539 done: Vec<isize>,
2540+ /// Per superblock row, the last column PARSED (submitted, whether or not
2541+ /// it recorded any write) and the last column actually pushed as a job
2542+ /// (-1 = none). A row is fully reconstructed once it has been parsed to
2543+ /// `last_col` and `done` has caught up with `last_push` -- lane-pipefilt
2544+ /// reads that to release the row's filters (see [`wave_rows_complete`]).
2545+ last_sub: Vec<isize>,
2546+ last_push: Vec<isize>,
25402547 /// Jobs popped but not finished -- what [`wave_barrier`] waits out.
25412548 active: usize,
25422549 closed: bool,
@@ -2633,6 +2640,11 @@ fn wave_stats_dump() {
26332640 WS_WAIT[i].load(Relaxed) as f64 / jobs as f64 / 1e3,
26342641 );
26352642 }
2643+ s += &format!(
2644+ " | pipe={}/{}",
2645+ PIPE_FRAMES.load(Relaxed),
2646+ PIPE_FRAMES.load(Relaxed) + PIPE_WHOLE.load(Relaxed),
2647+ );
26362648 s += &format!(
26372649 " | parse={:.0}ms barrier={:.0}ms/{} drain={:.0}ms block_above={} block_left={}",
26382650 ms(WS_PARSE.load(Relaxed)),
@@ -2722,6 +2734,8 @@ impl<'a> WaveGuard<'a> {
27222734 rows: (0..rows).map(|_| std::collections::VecDeque::new()).collect(),
27232735 queued: 0,
27242736 done: vec![-1; rows],
2737+ last_sub: vec![-1; rows],
2738+ last_push: vec![-1; rows],
27252739 active: 0,
27262740 closed: false,
27272741 }),
@@ -2794,10 +2808,16 @@ fn wave_submit(fctx: &crate::decode::FrameCtx, r: usize, c: usize) -> bool {
27942808 let cap = c.len();
27952809 std::mem::replace(&mut *c, Vec::with_capacity(cap))
27962810 });
2797- if !ops.is_empty() {
2811+ {
27982812 let mut q = st.q.lock().unwrap();
2799- q.rows[r].push_back((c, ReconJob { ops, coeffs, preds }));
2800- q.queued += 1;
2813+ if (c as isize) > q.last_sub[r] {
2814+ q.last_sub[r] = c as isize;
2815+ }
2816+ if !ops.is_empty() {
2817+ q.rows[r].push_back((c, ReconJob { ops, coeffs, preds }));
2818+ q.queued += 1;
2819+ q.last_push[r] = c as isize;
2820+ }
28012821 drop(q);
28022822 st.cv.notify_all();
28032823 }
@@ -16383,6 +16403,36 @@ fn apply_deblock(
1638316403 }
1638416404 }
1638516405
16406+/// [`apply_deblock`] for ONE pass over ONE band of luma rows
16407+/// (`y_lo..y_hi`), the form [`pipe_run`] calls it in. Running the three
16408+/// planes' vertical passes and then their three horizontal ones is the same
16409+/// output as `apply_deblock`'s plane-at-a-time order: the planes are
16410+/// separate buffers and neither pass reads another plane.
16411+#[allow(clippy::too_many_arguments)]
16412+fn deblock_span(
16413+ y: &mut PlaneBuf<'static>,
16414+ u: &mut PlaneBuf<'static>,
16415+ v: &mut PlaneBuf<'static>,
16416+ lf: &LoopFilterParams,
16417+ n: &Neighbours,
16418+ frame_width: usize,
16419+ frame_height: usize,
16420+ y_lo: usize,
16421+ y_hi: usize,
16422+ horz: bool,
16423+ fctx: &crate::decode::FrameCtx,
16424+) {
16425+ if lf.level[0] != 0 || lf.level[1] != 0 {
16426+ deblock_plane_span(y, 0, lf, n, frame_width, frame_height, y_lo, y_hi, horz, fctx);
16427+ }
16428+ if lf.level[2] != 0 {
16429+ deblock_plane_span(u, 1, lf, n, frame_width, frame_height, y_lo / 2, y_hi / 2, horz, fctx);
16430+ }
16431+ if lf.level[3] != 0 {
16432+ deblock_plane_span(v, 2, lf, n, frame_width, frame_height, y_lo / 2, y_hi / 2, horz, fctx);
16433+ }
16434+}
16435+
1638616436 /// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
1638716437 /// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
1638816438 /// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
@@ -18920,6 +18970,34 @@ fn deblock_plane(
1892018970 n: &Neighbours,
1892118971 frame_width: usize,
1892218972 frame_height: usize, fctx: &crate::decode::FrameCtx,
18973+) {
18974+ // spec 7.14's order: this plane's whole vertical pass, then its whole
18975+ // horizontal one. lane-pipefilt split the two into one row-ranged
18976+ // function so the per-superblock-row pipeline can run them a band at a
18977+ // time; `0..usize::MAX` is the whole plane, i.e. exactly this call.
18978+ deblock_plane_span(plane, plane_idx, lf, n, frame_width, frame_height, 0, usize::MAX, false, fctx);
18979+ deblock_plane_span(plane, plane_idx, lf, n, frame_width, frame_height, 0, usize::MAX, true, fctx);
18980+}
18981+
18982+/// One pass of [`deblock_plane`] -- vertical edges (`horz == false`) or
18983+/// horizontal ones -- restricted to the plane rows `span_lo..span_hi`.
18984+///
18985+/// A row span is a legal cut of either pass because a band boundary is a
18986+/// multiple of 16 rows and every edge's kernel stays inside its own
18987+/// 4-sample group's reach; the pipeline's row lags (see [`pipe_run`]) are
18988+/// what keep the two passes in spec order across bands.
18989+#[allow(clippy::too_many_arguments)]
18990+fn deblock_plane_span(
18991+ plane: &mut PlaneBuf<'static>,
18992+ plane_idx: usize,
18993+ lf: &LoopFilterParams,
18994+ n: &Neighbours,
18995+ frame_width: usize,
18996+ frame_height: usize,
18997+ span_lo: usize,
18998+ span_hi: usize,
18999+ horz: bool,
19000+ fctx: &crate::decode::FrameCtx,
1892319001 ) {
1892419002 let chroma = plane_idx != 0;
1892519003 // r7: libaom clips the deblock loop to the CODED frame's own
@@ -18980,10 +19058,15 @@ fn deblock_plane(
1898019058 plane.data.to_mut();
1898119059 let threads = crate::par::filter_threads();
1898219060 let sp = crate::par::Shared::new(plane);
18983- let vbands: Vec<(usize, usize)> = crate::par::bands(th.div_ceil(16), threads)
18984- .into_iter()
18985- .map(|(a, b)| (a * 16, (b * 16).min(th)))
18986- .collect();
19061+ let (sp_lo, sp_hi) = (span_lo.min(th), span_hi.min(th));
19062+ let vbands: Vec<(usize, usize)> = if horz || sp_lo >= sp_hi {
19063+ Vec::new()
19064+ } else {
19065+ crate::par::bands((sp_hi - sp_lo).div_ceil(16), threads)
19066+ .into_iter()
19067+ .map(|(a, b)| (sp_lo + a * 16, (sp_lo + b * 16).min(sp_hi)))
19068+ .collect()
19069+ };
1898719070 crate::par::run_bands(&vbands, fctx, |y_lo, y_hi, fctx| {
1898819071 // SAFETY: this band writes only rows `y_lo..y_hi` of the plane, which
1898919072 // no other band touches (see `Shared`'s own corner-cut note).
@@ -19052,17 +19135,21 @@ fn deblock_plane(
1905219135 });
1905319136 // The horizontal pass runs only after the WHOLE vertical pass of this
1905419137 // plane (spec 7.14 order), which `run_bands` guarantees by joining.
19055- let hbands: Vec<(usize, usize)> = crate::par::bands(tw.div_ceil(16), threads)
19056- .into_iter()
19057- .map(|(a, b)| (a * 16, (b * 16).min(tw)))
19058- .collect();
19138+ let hbands: Vec<(usize, usize)> = if !horz || sp_lo >= sp_hi {
19139+ Vec::new()
19140+ } else {
19141+ crate::par::bands(tw.div_ceil(16), threads)
19142+ .into_iter()
19143+ .map(|(a, b)| (a * 16, (b * 16).min(tw)))
19144+ .collect()
19145+ };
1905919146 crate::par::run_bands(&hbands, fctx, |x_lo, x_hi, fctx| {
1906019147 // SAFETY: this band writes only columns `x_lo..x_hi`.
1906119148 #[allow(unsafe_code)]
1906219149 let plane = unsafe { sp.get() };
1906319150 let hctx = EdgeCtx::new(lf, n, plane_idx, 1, chroma, seg_lf_active, fctx);
19064- let mut y0 = 4usize;
19065- while y0 < th {
19151+ let mut y0 = sp_lo.max(4);
19152+ while y0 < sp_hi {
1906619153 let mut x0 = x_lo;
1906719154 while x0 < x_hi {
1906819155 if x0 + 16 <= x_hi && y0 >= 8 && y0 + 7 <= rows {
@@ -19179,6 +19266,10 @@ fn scratch_sized(n: usize) -> Vec<u16> {
1917919266 /// memmove per plane per frame into 4 rows in 64 (luma). Every other row of
1918019267 /// the pooled buffer keeps whatever a previous frame left there -- an
1918119268 /// initialised value that no reader ever reaches.
19269+fn snap_alloc(p: &PlaneBuf<'_>) -> PlaneBuf<'static> {
19270+ PlaneBuf { data: std::borrow::Cow::Owned(scratch_sized(p.data.len())), ..*p }
19271+}
19272+
1918219273 fn plane_snapshot(p: &PlaneBuf<'_>, ss_y: u32) -> PlaneBuf<'static> {
1918319274 let mut data = scratch_sized(p.data.len());
1918419275 let rows = if p.width == 0 { 0 } else { p.data.len() / p.width };
@@ -19370,27 +19461,272 @@ fn cdef_band(
1937019461 }
1937119462 }
1937219463
19373-fn apply_cdef(
19374- y: &mut PlaneBuf<'static>,
19375- u: &mut PlaneBuf<'static>,
19376- v: &mut PlaneBuf<'static>,
19377- cdef: &CdefParams,
19378- skip_grid: &Neighbours,
19379- // This frame header's own CROPPED luma size, for the straddling-unit
19380- // counter only -- CDEF itself walks the mi-rounded plane.
19381- (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx,
19382-) {
19383- // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
19384- if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_CDEF") {
19464+
19465+// --- lane-pipefilt: the per-superblock-row loop filter pipeline ----------
19466+//
19467+// DEPENDENCY SHAPE (derived from this decoder's own whole-frame pass order:
19468+// every plane's vertical deblock edges, then every plane's horizontal ones,
19469+// then CDEF, then -- unpipelined -- superres and loop restoration).
19470+// A band is 64 luma rows, one superblock row (a 128 superblock is two).
19471+//
19472+// * recon: intra prediction of band r+1 reads the UNFILTERED bottom rows of
19473+// band r, so no filter may touch band r before band r+1 is reconstructed.
19474+// Hence V(r) waits for `ready >= r + 2`.
19475+// * V(r) (vertical edges whose 4-sample groups live in band r's rows) then
19476+// H(r-1) (horizontal edges at `y` in band r-1, including the one at its
19477+// own top boundary): the edge at `y = r*64` reads/writes 6-7 rows either
19478+// side of the band boundary, so H(r-1)'s last edge reaches into band r,
19479+// which the whole-frame order has already vertical-filtered -- V(r)
19480+// before H(r-1) reproduces exactly that.
19481+// * post-deblock finality: band j's own bottom rows are still rewritten by
19482+// H(j+1)'s first edge, so band j's post-deblock snapshot (`snap`) may
19483+// only be taken after H(j+1).
19484+// * CDEF(j) reads the post-deblock picture 2-3 rows across its 64x64
19485+// boundaries, i.e. bands j-1..j+1, so it runs after snap(j+1).
19486+//
19487+// One iteration k therefore runs V(k), H(k-1), snap(k-2), CDEF(k-3), and the
19488+// loop runs k in `0..nbands+3` so the tail drains. Loop restoration (and the
19489+// superres upscale, which is a whole-frame refusal for this path) stay in the
19490+// frame thread's tail; the snapshot the pipeline built is what LR reads.
19491+struct PipeQ {
19492+ /// Bands whose reconstruction the frame thread has released.
19493+ ready: usize,
19494+ abort: bool,
19495+}
19496+
19497+pub(crate) struct PipeSync {
19498+ m: std::sync::Mutex<PipeQ>,
19499+ cv: std::sync::Condvar,
19500+}
19501+
19502+impl PipeSync {
19503+ fn new() -> Self {
19504+ Self {
19505+ m: std::sync::Mutex::new(PipeQ { ready: 0, abort: false }),
19506+ cv: std::sync::Condvar::new(),
19507+ }
19508+ }
19509+ fn note(&self, ready: usize) {
19510+ let mut q = self.m.lock().unwrap();
19511+ if ready > q.ready {
19512+ q.ready = ready;
19513+ self.cv.notify_all();
19514+ }
19515+ }
19516+ /// Releases every remaining band (`abort` = the tile decoder is bailing
19517+ /// out, so the worker returns instead of finishing the frame).
19518+ fn close(&self, all: usize, abort: bool) {
19519+ let mut q = self.m.lock().unwrap();
19520+ q.ready = q.ready.max(all);
19521+ q.abort |= abort;
19522+ self.cv.notify_all();
19523+ }
19524+ /// `false` when the frame was aborted.
19525+ fn wait_for(&self, want: usize) -> bool {
19526+ let mut q = self.m.lock().unwrap();
19527+ while q.ready < want && !q.abort {
19528+ q = self.cv.wait(q).unwrap();
19529+ }
19530+ !q.abort
19531+ }
19532+}
19533+
19534+/// Band `j`'s rows of `src` copied into the pipeline's post-deblock
19535+/// snapshot. `full` mirrors [`apply_cdef`]'s whole-plane pre-CDEF copy;
19536+/// otherwise only the four rows around each stripe boundary that loop
19537+/// restoration reads are taken, exactly [`plane_snapshot`]'s rows.
19538+fn snap_band(dst: &mut [u16], src: &PlaneBuf<'_>, ss_y: u32, y_lo: usize, y_hi: usize, full: bool) {
19539+ let w = src.width;
19540+ if w == 0 {
1938519541 return;
1938619542 }
19387- // lane-cdefstrip r1 instrument, BEFORE either early return so it is valid
19388- // for every frame: an 8x8 CDEF unit none of whose four mi cells a coded
19389- // block wrote this frame. `Neighbours` seeds `skip_grid` all-false, so a
19390- // decode arm that forgets `fill_skip_grid_rect` reads "not skip" and CDEF
19391- // filters a unit libaom's `is_8x8_block_skip` (`cdef.c:29-38`) may exclude.
19392- // Always 0 on every stream measured; a gate asserts it stays 0.
19393- {
19543+ let rows = src.data.len() / w;
19544+ let (lo, hi) = (y_lo.min(rows), y_hi.min(rows));
19545+ if lo >= hi {
19546+ return;
19547+ }
19548+ if full {
19549+ dst[lo * w..hi * w].copy_from_slice(&src.data[lo * w..hi * w]);
19550+ return;
19551+ }
19552+ let stripe_h = 64usize >> ss_y;
19553+ let offset = 8usize >> ss_y;
19554+ let mut b = stripe_h - offset;
19555+ while b < rows {
19556+ let (a, e) = ((b - 2).max(lo), (b + 2).min(rows).min(hi));
19557+ if a < e {
19558+ dst[a * w..e * w].copy_from_slice(&src.data[a * w..e * w]);
19559+ }
19560+ b += stripe_h;
19561+ }
19562+}
19563+
19564+/// Everything the pipeline worker needs that is not a plane or a grid.
19565+struct PipeCfg<'a> {
19566+ lf: &'a LoopFilterParams,
19567+ cdef: &'a CdefParams,
19568+ /// `(cdef_idx_grid.as_ptr(), len)` -- the frame thread keeps filling the
19569+ /// entries of the superblock rows the pipeline has not reached; the Vec
19570+ /// itself is sized once per frame, so the pointer stays valid.
19571+ idx_grid: (*const u8, usize),
19572+ sb_cols: usize,
19573+ frame_w: usize,
19574+ frame_h: usize,
19575+ nbands: usize,
19576+ cdef_on: bool,
19577+ snap_on: bool,
19578+}
19579+
19580+// SAFETY: the `*const u8` is a read-only view of a Vec that is allocated once
19581+// per frame and only ever written at indices the pipeline is three bands
19582+// behind (see this module's dependency note).
19583+#[allow(unsafe_code)]
19584+unsafe impl Send for PipeCfg<'_> {}
19585+
19586+#[allow(unsafe_code)]
19587+#[allow(clippy::too_many_arguments)]
19588+fn pipe_run(
19589+ sync: &PipeSync,
19590+ sy: crate::par::Shared<'_, PlaneBuf<'static>>,
19591+ su: crate::par::Shared<'_, PlaneBuf<'static>>,
19592+ sv: crate::par::Shared<'_, PlaneBuf<'static>>,
19593+ sn: crate::par::Shared<'_, Neighbours>,
19594+ cfg: PipeCfg<'_>,
19595+ snap: &mut Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
19596+ fctx: &crate::decode::FrameCtx,
19597+) {
19598+ // SAFETY: the frame thread parses (and reconstructs) bands the pipeline
19599+ // is at least two behind, and the two ranges never meet -- see the
19600+ // dependency note above and `Shared`'s own corner-cut.
19601+ let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
19602+ let n: &Neighbours = unsafe { sn.get() };
19603+ let idx_grid = unsafe { std::slice::from_raw_parts(cfg.idx_grid.0, cfg.idx_grid.1) };
19604+ let coeff_shift = i32::from(bit_depth(fctx)) - 8;
19605+ let damping = i32::from(cfg.cdef.damping) + coeff_shift;
19606+ let damping_uv = (damping - 1).max(0);
19607+ let (fw, fh) = (cfg.frame_w, cfg.frame_h);
19608+ let nb = cfg.nbands;
19609+ for k in 0..nb + 3 {
19610+ if !sync.wait_for((k + 2).min(nb)) {
19611+ return;
19612+ }
19613+ if k < nb {
19614+ deblock_span(y, u, v, cfg.lf, n, fw, fh, k * 64, (k + 1) * 64, false, fctx);
19615+ }
19616+ if k >= 1 && k - 1 < nb {
19617+ deblock_span(y, u, v, cfg.lf, n, fw, fh, (k - 1) * 64, k * 64, true, fctx);
19618+ }
19619+ if cfg.snap_on && k >= 2 && k - 2 < nb {
19620+ let j = k - 2;
19621+ if let Some((sy2, su2, sv2)) = snap.as_mut() {
19622+ snap_band(sy2.data.to_mut(), y, 0, j * 64, (j + 1) * 64, cfg.cdef_on);
19623+ snap_band(su2.data.to_mut(), u, 1, j * 32, (j + 1) * 32, cfg.cdef_on);
19624+ snap_band(sv2.data.to_mut(), v, 1, j * 32, (j + 1) * 32, cfg.cdef_on);
19625+ }
19626+ }
19627+ if cfg.cdef_on && k >= 3 && k - 3 < nb {
19628+ let j = k - 3;
19629+ if let Some((sy2, su2, sv2)) = snap.as_ref() {
19630+ cdef_rows(
19631+ y, u, v, &sy2.data, &su2.data, &sv2.data, cfg.cdef, n, idx_grid, cfg.sb_cols,
19632+ coeff_shift, damping, damping_uv, (fw, fh), j * 16, (j + 1) * 16, fctx,
19633+ );
19634+ }
19635+ }
19636+ }
19637+}
19638+
19639+/// The pipeline's handle on the frame thread: [`PipeGuard::note`] releases
19640+/// bands as reconstruction completes, [`PipeGuard::finish`] drains it, and
19641+/// `Drop` aborts it on any `?` out of the tile decoder (the worker holds raw
19642+/// pointers into the frame's planes, so it may not outlive them).
19643+struct PipeGuard<'a> {
19644+ sync: std::sync::Arc<PipeSync>,
19645+ batch: Option<crate::par::Batch<'a>>,
19646+ nbands: usize,
19647+}
19648+
19649+impl PipeGuard<'_> {
19650+ fn note(&self, bands: usize) {
19651+ self.sync.note(bands);
19652+ }
19653+ fn finish(&mut self) {
19654+ self.sync.close(self.nbands, false);
19655+ // Dropping the batch waits the worker out.
19656+ self.batch.take();
19657+ }
19658+}
19659+
19660+impl Drop for PipeGuard<'_> {
19661+ fn drop(&mut self) {
19662+ self.sync.close(self.nbands, true);
19663+ }
19664+}
19665+
19666+/// Leading superblock rows of the live tile's wavefront that are fully
19667+/// reconstructed: parsed out to the last column and with every job that
19668+/// carried a write finished. 0 when reconstruction is inline (no wavefront),
19669+/// where the caller uses the parse position instead.
19670+fn wave_rows_complete(fctx: &crate::decode::FrameCtx) -> usize {
19671+ let st = fctx.wave.with(|w| w.borrow().clone());
19672+ let Some(st) = st else { return 0 };
19673+ let q = st.q.lock().unwrap();
19674+ let mut n = 0;
19675+ while n < q.rows.len() {
19676+ if q.last_sub[n] < st.last_col as isize || q.done[n] < q.last_push[n] {
19677+ break;
19678+ }
19679+ n += 1;
19680+ }
19681+ n
19682+}
19683+
19684+/// Frames whose loop filters ran pipelined, and frames that took the
19685+/// whole-frame path instead (`EC_AV1_WAVE_STATS`).
19686+static PIPE_FRAMES: AtomicU64 = AtomicU64::new(0);
19687+static PIPE_WHOLE: AtomicU64 = AtomicU64::new(0);
19688+
19689+/// Whether this frame's filters may run per superblock row. Everything that
19690+/// reads the picture out of band order, or the pipeline's own inputs out of
19691+/// row order, keeps the whole-frame path: superres (a between-CDEF-and-LR
19692+/// whole-plane resample), segmentation (the deblocker reads `seg_ids`, which
19693+/// the parse thread is still filling), delta_lf, more than one tile COLUMN (a
19694+/// frame row is only complete after the last tile column's own parse), and
19695+/// every pixel-dump / stage-skip debug flag, whose whole point is the
19696+/// unpipelined stage boundary. The pipeline also stays off unless some
19697+/// threading is on -- at (1, 1) the filters would run on a worker thread for
19698+/// nothing and the crate's `thread_local!` gate counters would miss them.
19699+fn pipe_filters_ok(fctx: &crate::decode::FrameCtx, tile_cols: u32, lf_present: bool) -> bool {
19700+ if crate::envflags::var("EC_AV1_PIPE_FILTERS").map(|v| v.trim() == "0").unwrap_or(false) {
19701+ return false;
19702+ }
19703+ if crate::par::filter_threads() == 1 && crate::par::recon_threads() == 1 {
19704+ return false;
19705+ }
19706+ if tile_cols != 1 || lf_present || superres(fctx).is_some() {
19707+ return false;
19708+ }
19709+ if fctx.seg.with(|s| s.borrow().enabled) {
19710+ return false;
19711+ }
19712+ !(crate::envflags::is_set("EC_AV1_PREFILT_DUMP")
19713+ || crate::envflags::is_set("EC_AV1_PREFILT_DUMP16")
19714+ || crate::envflags::is_set("EC_AV1_PREFILT_WIDE_DUMP")
19715+ || crate::envflags::is_set("EC_AV1_POSTDEBLOCK_DUMP")
19716+ || crate::envflags::is_set("EC_AV1_POSTDEBLOCK_DUMP16")
19717+ || crate::envflags::is_set("EC_AV1_POSTCDEF_DUMP")
19718+ || crate::envflags::is_set("EC_AV1_POSTCDEF_DUMP16")
19719+ || crate::envflags::is_set("EC_AV1_DEBUG_SKIP_DEBLOCK")
19720+ || crate::envflags::is_set("EC_AV1_DEBUG_SKIP_CDEF")
19721+ || crate::envflags::is_set("EC_AV1_DEBUG_CDEF_BAND")
19722+ || crate::envflags::is_set("EC_AV1_DEBLOCK_TRACE")
19723+ || crate::envflags::is_set("EC_AV1_DEBLOCK_TRACE_V"))
19724+}
19725+
19726+/// lane-cdefstrip r1 instrument, run for every frame BEFORE either of
19727+/// [`apply_cdef`]'s early returns (lane-pipefilt: the pipelined path
19728+/// never enters `apply_cdef`, so it calls this itself).
19729+fn cdef_scan_counters(skip_grid: &Neighbours) {
1939419730 let mut r = 0usize;
1939519731 while r < skip_grid.mi_rows {
1939619732 let mut c = 0usize;
@@ -19422,47 +19758,55 @@ fn apply_cdef(
1942219758 }
1942319759 r += 2;
1942419760 }
19425- }
19426- // `cdef.bits == 0` still means "no filtering at all" whenever the single
19427- // (index 0) strength pair is all-zero -- the fast path every existing
19428- // gate stream takes. A `bits > 0` frame can still be all-zero-strength
19429- // at every index, but that is rare enough not to special-case; the
19430- // per-superblock lookup below degrades to the same index-0 read anyway
19431- // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
19432- if cdef.bits == 0
19761+}
19762+
19763+/// `true` when this frame's CDEF cannot change a sample: `bits == 0` still
19764+/// means "no filtering at all" whenever the single (index 0) strength pair
19765+/// is all-zero, the fast path every existing gate stream takes.
19766+fn cdef_all_zero(cdef: &CdefParams) -> bool {
19767+ cdef.bits == 0
1943319768 && cdef.y_pri_strength[0] == 0
1943419769 && cdef.y_sec_strength[0] == 0
1943519770 && cdef.uv_pri_strength[0] == 0
1943619771 && cdef.uv_sec_strength[0] == 0
19437- {
19772+}
19773+
19774+/// [`apply_cdef`]'s band loop over the mi rows `r_lo0..r_hi0` only (the
19775+/// whole frame when `0..mi_rows`, which is what `apply_cdef` passes).
19776+/// `src_*` are the PRE-CDEF planes every unit reads; the writes are this
19777+/// row range's own pixels.
19778+#[allow(clippy::too_many_arguments)]
19779+fn cdef_rows(
19780+ y: &mut PlaneBuf<'static>,
19781+ u: &mut PlaneBuf<'static>,
19782+ v: &mut PlaneBuf<'static>,
19783+ src_y: &[u16],
19784+ src_u: &[u16],
19785+ src_v: &[u16],
19786+ cdef: &CdefParams,
19787+ skip_grid: &Neighbours,
19788+ idx_grid: &[u8],
19789+ sb_cols: usize,
19790+ coeff_shift: i32,
19791+ damping: i32,
19792+ damping_uv: i32,
19793+ (frame_w, frame_h): (usize, usize),
19794+ r_lo0: usize,
19795+ r_hi0: usize, fctx: &crate::decode::FrameCtx,
19796+) {
19797+ let mi_rows = skip_grid.mi_rows;
19798+ let (lo, hi) = (r_lo0.min(mi_rows), r_hi0.min(mi_rows));
19799+ if lo >= hi {
1943819800 return;
1943919801 }
19440- let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
19441- // One entry per superblock (a few hundred at 4K), so this clone is not
19442- // one of the per-frame copies lane-perf6 pooled below.
19443- let idx_grid = fctx.cdef_idx_grid.with(|g| g.borrow().clone());
19444- let src_y = scratch_from(&y.data);
19445- let src_u = scratch_from(&u.data);
19446- let src_v = scratch_from(&v.data);
19447- // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
19448- // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
19449- let coeff_shift = i32::from(bit_depth(fctx)) - 8;
19450- let damping = i32::from(cdef.damping) + coeff_shift;
19451- let damping_uv = (damping - 1).max(0);
19452- // lane-filt1: every CDEF unit reads ONLY the pre-CDEF snapshots
19453- // (`src_y`/`src_u`/`src_v`, immutable here) and writes its own 8x8 luma /
19454- // 4x4 chroma square, so units are independent. Bands are mi ROW bands (2
19455- // mi = 8 luma rows, 4 chroma rows), which makes each band's writes a
19456- // disjoint row range of all three planes.
1945719802 let (sy, su, sv) = (
1945819803 crate::par::Shared::new(y),
1945919804 crate::par::Shared::new(u),
1946019805 crate::par::Shared::new(v),
1946119806 );
19462- let mi_rows = skip_grid.mi_rows;
19463- let cbands: Vec<(usize, usize)> = crate::par::bands(mi_rows.div_ceil(2), crate::par::filter_threads())
19807+ let cbands: Vec<(usize, usize)> = crate::par::bands((hi - lo).div_ceil(2), crate::par::filter_threads())
1946419808 .into_iter()
19465- .map(|(a, b)| (a * 2, (b * 2).min(mi_rows)))
19809+ .map(|(a, b)| (lo + a * 2, (lo + b * 2).min(hi)))
1946619810 .collect();
1946719811 crate::par::run_bands(&cbands, fctx, |r_lo, r_hi, fctx| {
1946819812 // SAFETY: this band writes only the plane rows its own mi rows cover,
@@ -19475,12 +19819,12 @@ fn apply_cdef(
1947519819 y,
1947619820 u,
1947719821 v,
19478- &src_y,
19479- &src_u,
19480- &src_v,
19822+ src_y,
19823+ src_u,
19824+ src_v,
1948119825 cdef,
1948219826 skip_grid,
19483- &idx_grid,
19827+ idx_grid,
1948419828 sb_cols,
1948519829 coeff_shift,
1948619830 damping,
@@ -19489,6 +19833,53 @@ fn apply_cdef(
1948919833 fctx,
1949019834 );
1949119835 });
19836+}
19837+
19838+fn apply_cdef(
19839+ y: &mut PlaneBuf<'static>,
19840+ u: &mut PlaneBuf<'static>,
19841+ v: &mut PlaneBuf<'static>,
19842+ cdef: &CdefParams,
19843+ skip_grid: &Neighbours,
19844+ // This frame header's own CROPPED luma size, for the straddling-unit
19845+ // counter only -- CDEF itself walks the mi-rounded plane.
19846+ (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx,
19847+) {
19848+ // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
19849+ if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_CDEF") {
19850+ return;
19851+ }
19852+ cdef_scan_counters(skip_grid);
19853+ // `cdef.bits == 0` still means "no filtering at all" whenever the single
19854+ // (index 0) strength pair is all-zero -- the fast path every existing
19855+ // gate stream takes. A `bits > 0` frame can still be all-zero-strength
19856+ // at every index, but that is rare enough not to special-case; the
19857+ // per-superblock lookup below degrades to the same index-0 read anyway
19858+ // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
19859+ if cdef_all_zero(cdef) {
19860+ return;
19861+ }
19862+ let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
19863+ // One entry per superblock (a few hundred at 4K), so this clone is not
19864+ // one of the per-frame copies lane-perf6 pooled below.
19865+ let idx_grid = fctx.cdef_idx_grid.with(|g| g.borrow().clone());
19866+ let src_y = scratch_from(&y.data);
19867+ let src_u = scratch_from(&u.data);
19868+ let src_v = scratch_from(&v.data);
19869+ // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
19870+ // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
19871+ let coeff_shift = i32::from(bit_depth(fctx)) - 8;
19872+ let damping = i32::from(cdef.damping) + coeff_shift;
19873+ let damping_uv = (damping - 1).max(0);
19874+ // lane-filt1: every CDEF unit reads ONLY the pre-CDEF snapshots
19875+ // (`src_y`/`src_u`/`src_v`, immutable here) and writes its own 8x8 luma /
19876+ // 4x4 chroma square, so units are independent. Bands are mi ROW bands (2
19877+ // mi = 8 luma rows, 4 chroma rows), which makes each band's writes a
19878+ // disjoint row range of all three planes.
19879+ cdef_rows(
19880+ y, u, v, &src_y, &src_u, &src_v, cdef, skip_grid, &idx_grid, sb_cols, coeff_shift,
19881+ damping, damping_uv, (frame_w, frame_h), 0, skip_grid.mi_rows, fctx,
19882+ );
1949219883 scratch_return(src_y);
1949319884 scratch_return(src_u);
1949419885 scratch_return(src_v);
@@ -31587,6 +31978,62 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3158731978 frame_height,
3158831979 );
3158931980
31981+ // lane-pipefilt: the loop filters of superblock row r run as soon as row
31982+ // r+1 is reconstructed, on the filter pool, so the frame thread's latency
31983+ // is the parse plus the last rows' filters instead of parse plus the
31984+ // whole frame's filter chain. See `pipe_run` for the row lags.
31985+ let lr_active = (0..3).any(|p| {
31986+ lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None
31987+ && lr.loop_restoration_size[p] != 0
31988+ });
31989+ let pipe_on = pipe_filters_ok(fctx, tile_info.cols, delta.lf_present);
31990+ let cdef_on = !cdef_all_zero(cdef);
31991+ let snap_on = pipe_on && (cdef_on || lr_active);
31992+ let mut pipe_snap = snap_on.then(|| (snap_alloc(&y), snap_alloc(&u), snap_alloc(&v)));
31993+ let mut pipe = pipe_on.then(|| {
31994+ if wave_stats() {
31995+ PIPE_FRAMES.fetch_add(1, Relaxed);
31996+ }
31997+ let nbands = (mi_rows as usize).div_ceil(16);
31998+ let sync = std::sync::Arc::new(PipeSync::new());
31999+ let batch = crate::par::Batch::new("ec-av1-filter");
32000+ // SAFETY (all four): the pipeline only ever touches superblock rows
32001+ // the frame thread has finished reconstructing and will not revisit
32002+ // -- the row-lag argument in `pipe_run`'s module note, checked
32003+ // end to end by the byte-exact gate.
32004+ #[allow(unsafe_code)]
32005+ let (sy, su, sv, sn) = unsafe {
32006+ (
32007+ crate::par::Shared::from_ptr(std::ptr::from_mut(&mut y)),
32008+ crate::par::Shared::from_ptr(std::ptr::from_mut(&mut u)),
32009+ crate::par::Shared::from_ptr(std::ptr::from_mut(&mut v)),
32010+ crate::par::Shared::from_ptr(std::ptr::from_mut(&mut neighbours)),
32011+ )
32012+ };
32013+ let cfg = PipeCfg {
32014+ lf: loop_filter,
32015+ cdef,
32016+ idx_grid: fctx.cdef_idx_grid.with(|g| {
32017+ let g = g.borrow();
32018+ (g.as_ptr(), g.len())
32019+ }),
32020+ sb_cols: fctx.cdef_sb_cols.with(std::cell::Cell::get),
32021+ frame_w: frame_width as usize,
32022+ frame_h: frame_height as usize,
32023+ nbands,
32024+ cdef_on,
32025+ snap_on,
32026+ };
32027+ let ctx = crate::decode::filter_ctx_copy(fctx);
32028+ let sync2 = std::sync::Arc::clone(&sync);
32029+ let snap = &mut pipe_snap;
32030+ batch.submit(move || pipe_run(&sync2, sy, su, sv, sn, cfg, snap, &ctx));
32031+ PipeGuard { sync, batch: Some(batch), nbands }
32032+ });
32033+ if !pipe_on && wave_stats() {
32034+ PIPE_WHOLE.fetch_add(1, Relaxed);
32035+ }
32036+
3159032037 // lane-tiles r6: mirrors decode_key_frame_tile_with_cdfs's own per-tile
3159132038 // loop (spec 5.11.2 decode_tile / 7.20 exit_symbol) -- each tile gets
3159232039 // its own fresh SymbolDecoder over its own byte range and its own fresh
@@ -31711,6 +32158,17 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3171132158 flush_recon(fctx, &mut y, &mut u, &mut v);
3171232159 }
3171332160 if row_start {
32161+ if let Some(p) = &pipe {
32162+ // Reconstruction complete through this pixel row: the parse
32163+ // position itself when reconstruction is inline, the
32164+ // wavefront's own leading completed rows otherwise.
32165+ let px = if waving {
32166+ ((wave_r0 + wave_rows_complete(fctx)) << wave_shift) * 64
32167+ } else {
32168+ sb_r as usize * 64
32169+ };
32170+ p.note(px / 64);
32171+ }
3171432172 neighbours.start_row();
3171532173 }
3171632174 if sb_start {
@@ -34091,40 +34549,64 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3409134549 } else {
3409234550 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
3409334551 }
34094- apply_deblock(
34095- &mut y,
34096- &mut u,
34097- &mut v,
34098- loop_filter,
34099- &neighbours,
34100- frame_width as usize,
34101- frame_height as usize, fctx,
34102- );
34552+ // lane-pipefilt: release the rows still pending and wait the pipeline
34553+ // out; from here the picture is deblocked and CDEF-filtered exactly as
34554+ // the whole-frame path leaves it.
34555+ let pipelined = pipe.is_some();
34556+ if let Some(p) = &mut pipe {
34557+ p.finish();
34558+ }
34559+ drop(pipe);
34560+ if pipelined {
34561+ cdef_scan_counters(&neighbours);
34562+ } else {
34563+ apply_deblock(
34564+ &mut y,
34565+ &mut u,
34566+ &mut v,
34567+ loop_filter,
34568+ &neighbours,
34569+ frame_width as usize,
34570+ frame_height as usize, fctx,
34571+ );
34572+ }
3410334573 // lane-perf4: loop restoration is the only reader of the pre-CDEF planes,
3410434574 // and a frame that restores nothing copied every plane twice for nothing
3410534575 // (three `PlaneBuf` clones here plus the `cdef.to_vec()` inside
3410634576 // [`crate::restoration::apply_loop_restoration_plane`], which returns its
3410734577 // input unchanged when the plane's type is `None`). Clone only when some
3410834578 // plane actually restores.
34109- let lr_active = (0..3).any(|p| {
34110- lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None
34111- && lr.loop_restoration_size[p] != 0
34112- });
34113- let deblocked =
34114- lr_active.then(|| (plane_snapshot(&y, 0), plane_snapshot(&u, 1), plane_snapshot(&v, 1)));
34579+ let deblocked = if pipelined {
34580+ // The pipeline already snapshotted every band on its way past it.
34581+ let snap = pipe_snap.take();
34582+ match (lr_active, snap) {
34583+ (true, snap) => snap,
34584+ (false, Some((a, b, c))) => {
34585+ scratch_return(c.data.into_owned());
34586+ scratch_return(b.data.into_owned());
34587+ scratch_return(a.data.into_owned());
34588+ None
34589+ }
34590+ (false, None) => None,
34591+ }
34592+ } else {
34593+ lr_active.then(|| (plane_snapshot(&y, 0), plane_snapshot(&u, 1), plane_snapshot(&v, 1)))
34594+ };
3411534595 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
3411634596 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
3411734597 // dump above these bisect WHICH filter stage introduced a mismatch.
3411834598 dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
3411934599 dump_stage16("EC_AV1_POSTDEBLOCK_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
34120- apply_cdef(
34121- &mut y,
34122- &mut u,
34123- &mut v,
34124- cdef,
34125- &neighbours,
34126- (frame_width as usize, frame_height as usize), fctx,
34127- );
34600+ if !pipelined {
34601+ apply_cdef(
34602+ &mut y,
34603+ &mut u,
34604+ &mut v,
34605+ cdef,
34606+ &neighbours,
34607+ (frame_width as usize, frame_height as usize), fctx,
34608+ );
34609+ }
3412834610 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
3412934611 dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
3413034612 // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called
crates/ec-av1/src/par.rsmodified+13 -0
@@ -101,6 +101,19 @@ impl<'a, T: ?Sized> Shared<'a, T> {
101101 Self(v, std::marker::PhantomData)
102102 }
103103
104+ /// [`Shared::new`] from a raw pointer, for a caller that keeps using the
105+ /// `&mut T` itself (lane-pipefilt: the frame thread parses into the
106+ /// planes and the mode-info grids while the filter pipeline reads the
107+ /// superblock rows the parse is already three bands past).
108+ ///
109+ /// # Safety
110+ /// `p` must stay valid and unaliased-in-practice for `'a` -- the same
111+ /// band-disjointness contract as [`Shared::get`], proved by the caller's
112+ /// row-lag arithmetic and the byte-exact gate.
113+ pub(crate) unsafe fn from_ptr(p: *mut T) -> Self {
114+ Self(p, std::marker::PhantomData)
115+ }
116+
104117 /// # Safety
105118 /// The caller must touch only its own band, disjoint from every other
106119 /// worker's, for as long as the returned reference lives.