use super::Result; use super::TxParams; use super::block::PlaneBuf; use super::{CflSrc, FrameCtx, Reach, RefPix, SharedRefs, exec_intra, exec_mc}; use crate::encode::Picture; use crate::par::Batch; use std::borrow::Cow; use std::cell::{Cell, RefCell}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError, mpsc}; pub(super) enum Residual { Zero, Ready(usize, usize), Tx(TxParams, usize, usize), } impl Residual { pub(super) fn ready(residual: &[i32]) -> Self { if residual.is_empty() || std::ptr::eq(residual.as_ptr(), super::ZERO_RESIDUAL.as_ptr()) { Self::Zero } else { let off = push_coeffs(residual); Self::Ready(off, residual.len()) } } pub(super) fn tx(tx: TxParams, grid: &[i32]) -> Self { if super::is_zero_grid(grid) { Self::Zero } else { let off = push_coeffs(grid); Self::Tx(tx, off, grid.len()) } } fn resolve<'a>(self, arena: &'a [i32], scratch: &'a mut Vec) -> &'a [i32] { match self { Self::Zero => &[], Self::Ready(off, len) => &arena[off..][..len], Self::Tx(tx, off, len) => { *scratch = tx.run(&arena[off..][..len]); scratch } } } } fn push_coeffs(v: &[i32]) -> usize { QUEUE.with(|q| { let mut q = q.borrow_mut(); let off = q.coeffs.len(); q.coeffs.extend_from_slice(v); off }) } #[derive(Default)] struct Queue { ops: Vec, coeffs: Vec, } pub(super) type PredFn = Box< dyn FnOnce( &mut PlaneBuf<'static>, &mut PlaneBuf<'static>, &mut PlaneBuf<'static>, &RefPix<'_>, &FrameCtx, &mut [Vec; 3], ) + Send, >; pub(super) enum PredSrc { Owned(Vec), Cur { plane: usize, off: usize, src: usize, }, } pub(super) enum ReconOp { Pred(PredFn), Intra { plane: usize, x: usize, oy: usize, bw: usize, bh: usize, rect: bool, mode: usize, angle_delta: i32, reach: Reach, residual: Residual, cfl: Option<(i32, CflSrc)>, filter_intra: Option, smooth_neighbor: bool, pred: Option>, }, Mc { plane: usize, x: usize, oy: usize, stride: usize, w: usize, h: usize, prediction: PredSrc, residual: Residual, }, } thread_local! { static ACTIVE: Cell = const { Cell::new(false) }; static GUARD: RefCell> = const { RefCell::new(None) }; static CURRENT: Cell> = const { Cell::new(None) }; static QUEUE: RefCell = const { RefCell::new(Queue { ops: Vec::new(), coeffs: Vec::new() }) }; static POOL: RefCell; 3]>> = const { RefCell::new(Vec::new()) }; } const POOL_SETS: usize = 4; pub(super) struct TileScope; impl Drop for TileScope { fn drop(&mut self) { let guard = GUARD.with(|g| g.borrow_mut().take()); drop(guard); ACTIVE.with(|a| a.set(false)); CURRENT.with(|c| c.set(None)); QUEUE.with(|q| { let mut q = q.borrow_mut(); q.ops.clear(); q.coeffs.clear(); }); } } pub(super) fn active() -> bool { ACTIVE.with(Cell::get) } pub(super) fn push(op: ReconOp) { QUEUE.with(|q| q.borrow_mut().ops.push(op)); } #[derive(Clone, Copy)] struct Grid { ux: [usize; 3], uy: [usize; 3], row0: usize, col0: usize, cols: usize, rows: usize, } struct Job { row: usize, col: usize, ops: Vec, coeffs: Vec, } struct Shared { done: Vec, lines: Vec<[Vec; 3]>, abort: bool, } struct Link { state: Mutex, moved: Condvar, } impl Link { fn lock(&self) -> MutexGuard<'_, Shared> { self.state.lock().unwrap_or_else(PoisonError::into_inner) } fn abort(&self) { self.lock().abort = true; self.moved.notify_all(); } } struct Out { planes: [PlaneBuf<'static>; 3], corrupt: Option<&'static str>, err: Option, } struct AbortOnPanic(Arc); impl Drop for AbortOnPanic { fn drop(&mut self) { if std::thread::panicking() { self.0.abort(); } } } struct Worker { link: Arc, grid: Grid, planes: [PlaneBuf<'static>; 3], fctx: FrameCtx, refs: Option, cur: [Vec; 3], } impl Worker { fn run(mut self, jobs: mpsc::Receiver) -> Out { let _abort = AbortOnPanic(Arc::clone(&self.link)); let shared = self.refs.take(); let pics: OnceLock<[Option>; 8]> = OnceLock::new(); let wait = || -> Result<[Option<&Picture>; 8]> { let Some(shared) = &shared else { return Ok([None; 8]); }; let got = match pics.get() { Some(got) => got, None => { let waited = (shared.wait)()?; pics.get_or_init(|| waited) } }; Ok(std::array::from_fn(|i| got[i].as_deref())) }; let refpix = RefPix::lazy(shared.as_ref().map_or([None; 8], |s| s.dims), &wait, None); while let Ok(job) = jobs.recv() { if !self.job(job, &refpix) { break; } } Out { planes: self.planes, corrupt: self.fctx.corrupt.get(), err: refpix.take_err().err(), } } fn job(&mut self, job: Job, refpix: &RefPix<'_>) -> bool { crate::fault::point("recon"); let Job { row, col, ops, coeffs, } = job; let mut scratch = Vec::new(); if row > 0 && !self.halo(row, col) { return false; } let [y, u, v] = &mut self.planes; for op in ops { match op { ReconOp::Pred(build) => build(y, u, v, refpix, &self.fctx, &mut self.cur), ReconOp::Intra { plane, x, oy, bw, bh, rect, mode, angle_delta, reach, residual, cfl, filter_intra, smooth_neighbor, pred, } => { let res = residual.resolve(&coeffs, &mut scratch); exec_intra( y, u, v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach, res, cfl, filter_intra, smooth_neighbor, pred, &self.fctx, ); } ReconOp::Mc { plane, x, oy, stride, w, h, prediction, residual, } => { let res = residual.resolve(&coeffs, &mut scratch); let window: Cow<[u16]> = match prediction { PredSrc::Owned(p) => Cow::Owned(p), PredSrc::Cur { plane: sp, off, src, } => { let block = &self.cur[sp][off..]; if src == stride { Cow::Borrowed(block) } else { let mut dense = Vec::with_capacity(w * h); for row in 0..h { dense.extend_from_slice(&block[row * src..][..w]); } Cow::Owned(dense) } } }; exec_mc(y, u, v, plane, x, oy, stride, w, h, &window, res, &self.fctx); } } } self.publish(row, col); true } fn halo(&mut self, row: usize, col: usize) -> bool { let g = self.grid; let need = (col + 2).min(g.cols); let mut s = self.link.lock(); while s.done[row - 1] < need && !s.abort { s = self .link .moved .wait(s) .unwrap_or_else(PoisonError::into_inner); } if s.abort { return false; } for p in 0..3 { let w = self.planes[p].width; if w == 0 { continue; } let halo_row = (g.row0 + row) * g.uy[p] - 1; let c0 = (g.col0 + col) * g.ux[p]; let from = c0.saturating_sub(1); let to = (c0 + 2 * g.ux[p]).min(w); self.planes[p].data.to_mut()[halo_row * w + from..halo_row * w + to] .copy_from_slice(&s.lines[row - 1][p][from..to]); } true } fn publish(&self, row: usize, col: usize) { let g = self.grid; let mut s = self.link.lock(); for p in 0..3 { let w = self.planes[p].width; if w == 0 { continue; } let h = self.planes[p].height; let last = ((g.row0 + row + 1) * g.uy[p]).min(h).saturating_sub(1); let c0 = (g.col0 + col) * g.ux[p]; let end = (c0 + g.ux[p]).min(w); s.lines[row][p][c0..end] .copy_from_slice(&self.planes[p].data[last * w + c0..last * w + end]); } s.done[row] = col + 1; drop(s); self.link.moved.notify_all(); } } pub(super) struct WaveGuard { link: Arc, grid: Grid, jobs: Vec>, batch: Option, outs: mpsc::Receiver<(usize, Out)>, } pub(super) fn install( fctx: &FrameCtx, refpix: &RefPix<'_>, planes: [&PlaneBuf<'static>; 3], unit: usize, span: (usize, usize, usize, usize), ) { let (row0, rows, col0, cols) = span; let workers = crate::par::recon_threads().min(rows); if workers < 2 || cols == 0 { return; } let (ss_x, ss_y) = (super::ss_x(fctx), super::ss_y(fctx)); let grid = Grid { ux: [unit, unit >> ss_x, unit >> ss_x], uy: [unit, unit >> ss_y, unit >> ss_y], row0, col0, cols, rows, }; let link = Arc::new(Link { state: Mutex::new(Shared { done: vec![0; rows], lines: (0..rows) .map(|_| [0, 1, 2].map(|p| vec![0u16; planes[p].width])) .collect(), abort: false, }), moved: Condvar::new(), }); let mut jobs = Vec::with_capacity(workers); let batch = Batch::new("ec-av1-recon"); let (out_tx, outs) = mpsc::channel(); for w in 0..workers { let mut own = take_planes(planes); for rr in (w..rows).step_by(workers) { for p in 0..3 { let src = planes[p]; let (top, end, x0, x1) = strip(&grid, p, row0 + rr, src); for y in top..end { own[p].data.to_mut()[y * src.width + x0..y * src.width + x1] .copy_from_slice(&src.data[y * src.width + x0..y * src.width + x1]); } } } let worker = Worker { link: Arc::clone(&link), grid, planes: own, fctx: recon_ctx(fctx), refs: refpix.shared(), cur: Default::default(), }; let (tx, rx) = mpsc::channel(); jobs.push(tx); let out_tx = out_tx.clone(); batch.submit(move || { let out = worker.run(rx); let _ = out_tx.send((w, out)); }); } CURRENT.with(|c| c.set(None)); ACTIVE.with(|a| a.set(true)); let guard = WaveGuard { link, grid, jobs, batch: Some(batch), outs, }; GUARD.with(|g| *g.borrow_mut() = Some(guard)); } pub(super) fn begin_sb(row: usize, col: usize) { if !active() { return; } if let Some((r, c)) = CURRENT.with(|cur| cur.replace(Some((row, col)))) { send(r, c); } } fn send(row: usize, col: usize) { let (ops, coeffs) = QUEUE.with(|q| { let mut q = q.borrow_mut(); let next = Queue { ops: Vec::with_capacity(q.ops.len()), coeffs: Vec::with_capacity(q.coeffs.len()), }; let Queue { ops, coeffs } = std::mem::replace(&mut *q, next); (ops, coeffs) }); GUARD.with(|g| { if let Some(guard) = g.borrow().as_ref() { let _ = guard.jobs[row % guard.jobs.len()].send(Job { row, col, ops, coeffs, }); } }); } pub(super) fn finish_tile( fctx: &FrameCtx, refpix: &RefPix<'_>, planes: [&mut PlaneBuf<'static>; 3], ) { if !active() { return; } if let Some((row, col)) = CURRENT.with(|c| c.take()) { send(row, col); } ACTIVE.with(|a| a.set(false)); let guard = GUARD.with(|g| g.borrow_mut().take()); if let Some(guard) = guard { guard.finish(fctx, refpix, planes); } } impl WaveGuard { pub(super) fn finish( mut self, fctx: &FrameCtx, refpix: &RefPix<'_>, mut planes: [&mut PlaneBuf<'static>; 3], ) { self.jobs.clear(); drop(self.batch.take()); let mut outs: Vec<(usize, Out)> = self.outs.try_iter().collect(); outs.sort_by_key(|(w, _)| *w); let nw = outs.len(); let g = self.grid; for (w, out) in outs { for rr in (w..g.rows).step_by(nw) { for (p, dst) in planes.iter_mut().enumerate() { let width = dst.width; let (top, end, x0, x1) = strip(&g, p, g.row0 + rr, dst); for y in top..end { dst.data.to_mut()[y * width + x0..y * width + x1] .copy_from_slice(&out.planes[p].data[y * width + x0..y * width + x1]); } } } if let Some(why) = out.corrupt { fctx.flag_corrupt(why); } if let Some(e) = out.err { refpix.park_err(e); } let [a, b, c] = out.planes; give_planes([ a.data.into_owned(), b.data.into_owned(), c.data.into_owned(), ]); } } } impl Drop for WaveGuard { fn drop(&mut self) { self.link.abort(); self.jobs.clear(); if let Some(batch) = self.batch.take() { if std::thread::panicking() { std::mem::forget(batch); } else { drop(batch); } } } } fn strip( g: &Grid, p: usize, unit_row: usize, plane: &PlaneBuf<'static>, ) -> (usize, usize, usize, usize) { let top = unit_row * g.uy[p]; let end = ((unit_row + 1) * g.uy[p]).min(plane.height); let x0 = (g.col0 * g.ux[p]).min(plane.width); let x1 = ((g.col0 + g.cols) * g.ux[p]).min(plane.width); if top >= end { (0, 0, 0, 0) } else { (top, end, x0, x1) } } fn take_planes(planes: [&PlaneBuf<'static>; 3]) -> [PlaneBuf<'static>; 3] { let lens = planes.map(|p| p.data.len()); let reuse = POOL.with(|pool| { let mut pool = pool.borrow_mut(); let at = pool .iter() .position(|set| [0, 1, 2].iter().all(|&p| set[p].len() == lens[p]))?; Some(pool.swap_remove(at)) }); let bufs = reuse.unwrap_or_else(|| lens.map(|n| vec![0u16; n])); let [a, b, c] = bufs; [ blank_like(planes[0], a), blank_like(planes[1], b), blank_like(planes[2], c), ] } fn give_planes(set: [Vec; 3]) { POOL.with(|pool| { let mut pool = pool.borrow_mut(); if pool.len() < POOL_SETS { pool.push(set); } }); } fn blank_like(src: &PlaneBuf<'static>, data: Vec) -> PlaneBuf<'static> { PlaneBuf { data: Cow::Owned(data), width: src.width, height: src.height, true_width: src.true_width, true_height: src.true_height, tile_x0: src.tile_x0, tile_y0: src.tile_y0, tile_x1: src.tile_x1, tile_y1: src.tile_y1, plane: src.plane, } } fn recon_ctx(fctx: &FrameCtx) -> FrameCtx { let out = super::filter_ctx_copy(fctx); out.enable_edge_filter.set(fctx.enable_edge_filter.get()); out }