diff --git a/crates/video/src/av1/decode/README.md b/crates/video/src/av1/decode/README.md index 1518df92c..e1b8e4732 100644 --- a/crates/video/src/av1/decode/README.md +++ b/crates/video/src/av1/decode/README.md @@ -73,11 +73,17 @@ with libdav1d: **bit-exact** on all 6 fixtures. `Decoder::new()` uses all cores (`Decoder::with_threads(1)` decodes on the calling thread; on wasm32, or without the default `threads` feature, everything runs on the calling thread). Headers are parsed in order; each frame is -then decoded by a frame worker once the reference frames it reads are finished, so independent -frames (hierarchical GOP layers) decode concurrently; tiles of a frame decode in parallel into -private buffers that are merged afterwards; the in-loop filters (deblocking, CDEF, loop -restoration) each run in parallel bands of 64 rows (`postfilter.rs` explains why the bands are -independent). Results never depend on scheduling (the oracle tests compare 1 thread, many threads +then decoded by a frame worker. With worker threads it first reads the symbols of all its tiles, +which needs only the parse results of its references (CDFs, segment ids, saved motion vectors), +publishes its own, and then reconstructs from the recorded blocks. Frames with several tiles +read the symbols of their tiles in parallel (one after another with intra block copy). A frame reconstructs superblock row by superblock +row (that row of every tile), each row waiting only for the reference rows its motion vectors +reach (row wavefront), and the in-loop filters (deblocking, CDEF, loop restoration) follow a few +64-row bands behind and publish each final band for the frames predicting from it +(`decoder.rs` and `postfilter.rs` give the dependency rules). Super-resolution frames wait for +their whole references and filter the whole frame. There is one frame worker per thread (at most +16), and the frames in flight are bounded by their size. Independent frames (hierarchical GOP +layers) decode concurrently. Results never depend on scheduling (the oracle tests compare 1 thread, many threads and libdav1d). With frame threads, pictures may be returned by a later `decode_pts` call or by `flush`; each carries the `pts` of the temporal unit that showed it. @@ -130,6 +136,44 @@ motion vectors nor CDFs reach another frame — skip deblocking, CDEF and loop r (super-resolution still runs, it sets the output size) and are flagged `Picture::draft`. In SVT-AV1's hierarchical GOPs that is the top layer, half of the frames. +Frame threading on a Ryzen 7800X3D (8 cores / 16 threads, release `examples/av1_av1dec`, median of 7 +alternating runs against Filmcraft `6909e461`, 2026-11-08), wall time for the whole file: + +| Fixture | Threads | Before | After | Speed-up | +|---|---|---|---|---| +| `perf_1080p_gop` (60 frames) | 1 | 69.2 fps | 69.1 fps | 1.00x | +| `perf_1080p_gop` | 16 | 159.6 fps | 227.3 fps | 1.42x | +| `perf_2160p_gop` (30 frames) | 1 | 17.9 fps | 17.8 fps | 1.00x | +| `perf_2160p_gop` | 16 | 40.2 fps | 57.7 fps | 1.43x | + +Peak RSS at 16 threads goes from 278 to 365 MB (1080p) and from 1031 to 1217 MB (2160p, +18%): +every frame in flight holds its parse record and its final samples are kept in 64-row bands. + +With one frame worker per thread, the row wavefront for frames with several tiles and parse +waits limited to what parsing reads (same machine, median of 5 alternating runs, 2026-11-08): + +| Fixture | Threads | Before (`6909e461`) | After | Speed-up | Peak RSS before / after | +|---|---|---|---|---|---| +| `perf_1080p_gop` | 4 | 95.7 fps | 185.2 fps | 1.94x | 148 / 236 MB | +| `perf_1080p_gop` | 16 | 155.0 fps | 259.7 fps | 1.68x | 274 / 560 MB | +| `perf_2160p_gop` | 4 | 23.6 fps | 47.1 fps | 2.00x | 512 / 798 MB | +| `perf_2160p_gop` | 16 | 39.9 fps | 65.8 fps | 1.65x | 994 / 1353 MB | +| `perf_1080p_gop_tiles` (4x2 tiles) | 16 | 186.3 fps | 237.2 fps | 1.27x | 328 / 617 MB | +| SVT-AV1 2160p, 4x2 tiles (30 frames) | 16 | 57.1 fps | 70.8 fps | 1.24x | 1197 / 1502 MB | + +Known limitations of the frame threading (the output is the same in every case, only the +overlap is smaller): + +- A frame whose parse record would pass 32 bytes per luma sample of a tile (pathological streams: + tiny blocks, large palettes, every coefficient coded), or that cannot reserve its record from + the decoder-wide budget of 1 GiB shared by the frames in flight, is decoded again in one pass. +- A superblock row using local warped motion, global motion beyond translation or a scaled + reference waits for the whole reference instead of the rows its motion vectors reach. +- Super-resolution frames do not use the row wavefront: they wait for their whole references + and filter the whole frame. +- The tile columns of a superblock row are reconstructed one after another on the frame's worker + (their symbols are still read in parallel). + ## Limits Frames beyond the AV1 level 6.x limits (Annex A: at most 16384 wide, 8704 high and 35 651 584 luma samples diff --git a/crates/video/src/av1/decode/cdef.rs b/crates/video/src/av1/decode/cdef.rs index edd119292..05eb0a2a7 100644 --- a/crates/video/src/av1/decode/cdef.rs +++ b/crates/video/src/av1/decode/cdef.rs @@ -10,19 +10,33 @@ use crate::av1::decode::state::FrameState; /// equals CurrFrame). Bands of 64 luma rows (whole 64x64 filter blocks) are filtered in /// parallel: every block reads only CurrFrame and writes only its own samples. pub(crate) fn apply(fs: &FrameState, pool: &Pool) -> Option { + if !active(fs) { + return None; + } + let mut out = fs.cur.clone(); + let ranges = bands(pool, fs.fh.mi_rows as usize * 4); + filter_bands(fs, pool, out.row_bands(&ranges), &ranges); + Some(out) +} + +/// Whether CDEF filters any block of the frame (it reads only parse results). +pub(crate) fn active(fs: &FrameState) -> bool { let fh = &fs.fh; if fh.coded_lossless || fh.allow_intrabc || !fs.seq.enable_cdef { - return None; + return false; } let (mi_rows, mi_cols) = (fh.mi_rows as usize, fh.mi_cols as usize); let fb_rows = mi_rows.div_ceil(16); let fb_cols = mi_cols.div_ceil(16); - if !(0..fb_rows).any(|fr| (0..fb_cols).any(|fc| fb_skip_mask(fs, fr * 16, fc * 16).is_some())) { - return None; - } - let mut out = fs.cur.clone(); - let ranges = bands(pool, mi_rows * 4); - let mut planes = out.row_bands(&ranges); + (0..fb_rows).any(|fr| (0..fb_cols).any(|fc| fb_skip_mask(fs, fr * 16, fc * 16).is_some())) +} + +/// Filter the bands `planes` covering luma rows `ranges` (whole 64x64 filter block rows), which +/// hold CurrFrame; reads CurrFrame up to 2 rows beyond each band. +pub(crate) fn filter_bands(fs: &FrameState, pool: &Pool, mut planes: Vec<[RowBand; 3]>, ranges: &[(usize, usize)]) { + let (mi_rows, mi_cols) = (fs.fh.mi_rows as usize, fs.fh.mi_cols as usize); + let fb_rows = mi_rows.div_ceil(16); + let fb_cols = mi_cols.div_ceil(16); pool.map_mut(&mut planes, |b, band| { let (start, end) = ranges[b]; let mut buf = [0i16; BUF_LEN]; @@ -34,8 +48,6 @@ pub(crate) fn apply(fs: &FrameState, pool: &Pool) -> Option { } } }); - drop(planes); - Some(out) } /// The filtered 8x8 blocks of the 64x64 filter block at (r, c): bit `(i << 3) | j` is set for diff --git a/crates/video/src/av1/decode/decoder.rs b/crates/video/src/av1/decode/decoder.rs index 65c3de6ef..4a922cce1 100644 --- a/crates/video/src/av1/decode/decoder.rs +++ b/crates/video/src/av1/decode/decoder.rs @@ -2,31 +2,37 @@ //! (7.20), show-existing-frame and output (7.18). //! //! Threading: headers are parsed in order on the calling thread; each frame then becomes a job -//! that waits for the reference frames it uses and decodes on a frame worker thread, so frames -//! that do not depend on each other decode concurrently. Within a frame, tiles and the -//! post-filter row bands run on a shared worker pool. Every result depends only on finished -//! reference frames, so the output is identical whatever the scheduling. Shown pictures are -//! returned in order; with frame threads they can come out of a later `decode` call (or -//! `flush`), each carrying the `pts` of the temporal unit that showed it. +//! on a frame worker thread. A job first reads the symbols of its tiles (parse), which needs +//! only the parse results of its references (CDFs, segment ids, saved motion vectors), and +//! publishes its own; it then reconstructs. A frame is reconstructed superblock row by +//! superblock row (that row of every tile), each row waiting only for the reference rows its +//! motion vectors reach, with the in-loop filters following a few bands behind and every final +//! band published for the frames that predict from it (row wavefront); super-resolution frames +//! wait for their whole references. So a frame can parse while its references are still being reconstructed, and reconstruct +//! while their bottom is still being filtered. Within a frame, tiles and the post-filter row +//! bands run on a shared worker pool; waits happen only on frame worker threads. Every result +//! depends only on final reference data, so the output is identical whatever the scheduling. +//! Shown pictures are returned in order; with frame threads they can come out of a later +//! `decode` call (or `flush`), each carrying the `pts` of the temporal unit that showed it. use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use crate::av1::decode::bits::{BitReader, leb128}; use crate::av1::decode::cdf::Cdfs; -use crate::av1::decode::frame::FrameBuf; +use crate::av1::decode::frame::{BandFrame, FrameBuf, PlaneRef}; use crate::av1::decode::header::{ ColorConfig, FilmGrainParams, FrameHeader, HeaderState, LoopFilterDeltas, RefInfo, SegmentationFeatures, SequenceHeader, default_gm_params, }; use crate::av1::decode::par::Pool; use crate::av1::decode::spec_tables::{ - ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, DEFAULT_INTRA_FRAME_Y_MODE_CDF, DIV_MULT, GOLDEN_FRAME, INTRA_FRAME, INTRA_ONLY_FRAME, KEY_FRAME, - LAST_FRAME, LAST2_FRAME, MAX_FRAME_DISTANCE, MAX_OFFSET_HEIGHT, MAX_OFFSET_WIDTH, MFMV_STACK_SIZE, NUM_REF_FRAMES, PRIMARY_REF_NONE, - REFMVS_LIMIT, REFS_PER_FRAME, + ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, DEFAULT_INTRA_FRAME_Y_MODE_CDF, DIV_MULT, GLOBAL_GLOBALMV, GLOBALMV, GOLDEN_FRAME, INTRA_FRAME, + INTRA_ONLY_FRAME, KEY_FRAME, LAST_FRAME, LAST2_FRAME, LOCALWARP, MAX_FRAME_DISTANCE, MAX_OFFSET_HEIGHT, MAX_OFFSET_WIDTH, MFMV_STACK_SIZE, + NUM_REF_FRAMES, PRIMARY_REF_NONE, REFMVS_LIMIT, REFS_PER_FRAME, TRANSLATION, }; use crate::av1::decode::state::{FrameShared, FrameState, TileState}; use crate::av1::decode::stats::{DecodeStats, Stage, Timer}; -use crate::av1::decode::tile::TileDecoder; +use crate::av1::decode::tile::{Pass, TileDecoder, TileRecord}; use crate::av1::decode::{Error, Picture, Result}; /// Largest accepted frame: the AV1 level 6.x limits (Annex A: MaxHSize 16384, MaxVSize 8704, MaxPicSize @@ -49,22 +55,156 @@ const OBU_FRAME_T: u32 = 6; const OBU_REDUNDANT_FRAME_HEADER_T: u32 = 7; const OBU_TILE_LIST_T: u32 = 8; -/// A stored reference frame (FrameStore plus the saved per-frame state). +/// The samples of a stored reference frame (FrameStore), after every in-loop filter: a whole +/// buffer (decoding on one thread) or the bands published while decoding (with worker threads). pub(crate) struct RefFrame { pub buf: FrameBuf, - pub cdfs: Box, + pub bands: Option>, + pub num_planes: usize, pub bit_depth: u8, pub subsampling_x: u8, pub subsampling_y: u8, + pub color: (u8, u8, u8, bool), +} + +impl RefFrame { + pub fn plane(&self, p: usize) -> PlaneRef<'_> { + match &self.bands { + Some(b) => PlaneRef::Bands(&b.planes[p]), + None => PlaneRef::Whole(&self.buf.planes[p]), + } + } +} + +/// The saved per-frame state that later frames read while parsing (CDFs, segment ids and the +/// motion vectors for motion field estimation). It depends only on the frame's symbols, so it +/// is published as soon as the tiles are decoded, before the in-loop filters run. +pub(crate) struct Parsed { + pub cdfs: Box, pub segment_ids: Vec, pub mi_cols: usize, pub mi_rows: usize, - pub color: (u8, u8, u8, bool), - /// SavedRefFrames / SavedMvs (MfRefFrames / MfMvs of 7.19), mi units. + /// SavedRefFrames / SavedMvs (MfRefFrames / MfMvs of 7.19) at the odd row and column of + /// every 8x8 block, the only positions the projection reads. pub saved_ref_frames: Vec, pub saved_mvs: Vec<[i32; 2]>, } +/// How many luma rows of a frame are final (every in-loop filter applied), or that the frame +/// failed. Rows only ever grow; a failure wakes every waiter with an error. +pub(crate) struct Progress { + state: Mutex, + cv: Condvar, +} + +#[derive(Clone, Copy, Default)] +struct ProgressState { + rows: usize, + failed: bool, +} + +impl Progress { + fn new() -> Progress { + Progress { state: Mutex::new(ProgressState::default()), cv: Condvar::new() } + } + + /// Rows [0, rows) are final. A smaller value than already published is ignored. + pub fn publish(&self, rows: usize) { + #[cfg(test)] + tests::jitter(); + let mut g = self.state.lock().unwrap_or_else(|e| e.into_inner()); + if rows > g.rows { + g.rows = rows; + self.cv.notify_all(); + } + } + + /// The frame will publish no more rows. + pub fn fail(&self) { + let mut g = self.state.lock().unwrap_or_else(|e| e.into_inner()); + g.failed = true; + self.cv.notify_all(); + } + + /// Rows published so far. + #[cfg(test)] + fn rows(&self) -> usize { + self.state.lock().map(|g| g.rows).unwrap_or(0) + } + + /// Blocks until rows [0, rows) are final; an error when the frame failed first. + pub fn wait(&self, rows: usize) -> Result<()> { + #[cfg(test)] + tests::jitter(); + let mut g = self.state.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if g.rows >= rows { + return Ok(()); + } + if g.failed { + return Err(Error::Invalid("reference frame failed to decode")); + } + g = self.cv.wait(g).unwrap_or_else(|e| e.into_inner()); + } + } +} + +/// Everything a decoding frame publishes for the frames that reference it and for the output: +/// its parse results, its final rows (bands, then the row progress) and the finished frame. The +/// parse results and the frame are set exactly once and the progress ends complete or failed, +/// also when decoding fails, so no waiter blocks forever. +pub(crate) struct FrameSlot { + parsed: Slot>, + pub progress: Progress, + /// The final samples, published band by band before the progress covers them (with + /// worker threads). + pub bands: Arc, + frame: Slot>, +} + +impl FrameSlot { + fn new(bands: BandFrame) -> Arc { + Arc::new(FrameSlot { parsed: Slot::new_plain(), progress: Progress::new(), bands: Arc::new(bands), frame: Slot::new_plain() }) + } + + /// The finished frame. + fn wait(&self) -> Result> { + self.frame.wait() + } + + fn is_set(&self) -> bool { + self.frame.is_set() + } + + /// The frame's parse results (available before its samples are final). + fn wait_parsed(&self) -> Result> { + self.parsed.wait() + } + + /// Publish the parse results (ignored when already set). + fn set_parsed(&self, v: Result>) { + self.parsed.set_once(v); + } + + /// Publish the finished frame: every row is final. On an error, the parse results (when + /// not yet published) and the progress fail too. + fn finish(&self, v: Result>, rows: usize) { + match &v { + Ok(_) => {} + Err(e) => { + self.parsed.set_once(Err(e.clone())); + } + } + let ok = v.is_ok(); + self.frame.set(v); + if ok { + self.progress.publish(rows); + } else { + self.progress.fail(); + } + } +} + /// A value produced by a decoding job, waited for by later jobs and by the output. pub(crate) struct Slot { value: Mutex>>, @@ -73,7 +213,11 @@ pub(crate) struct Slot { impl Slot { fn new() -> Arc> { - Arc::new(Slot { value: Mutex::new(None), cv: Condvar::new() }) + Arc::new(Slot::new_plain()) + } + + fn new_plain() -> Slot { + Slot { value: Mutex::new(None), cv: Condvar::new() } } fn set(&self, v: Result) { @@ -82,6 +226,15 @@ impl Slot { self.cv.notify_all(); } + /// [`Slot::set`] unless a value is already there. + fn set_once(&self, v: Result) { + let mut g = self.value.lock().unwrap_or_else(|e| e.into_inner()); + if g.is_none() { + *g = Some(v); + self.cv.notify_all(); + } + } + fn is_set(&self) -> bool { self.value.lock().map(|g| g.is_some()).unwrap_or(true) } @@ -108,8 +261,6 @@ impl Slot { } } -type FrameSlot = Slot>; - /// Everything needed to decode one frame, captured when its header is parsed. struct FrameJob { seq: SequenceHeader, @@ -130,6 +281,15 @@ struct FrameJob { draft: bool, #[cfg(test)] force_panic: bool, + /// Panic in the row wavefront at the first superblock row from this one after which rows + /// are published (tests). + #[cfg(test)] + panic_at_row: Option, + /// Overrides [`RECORD_BYTES_PER_SAMPLE`] (tests). + #[cfg(test)] + record_limit: Option, + /// The decoder's parse record budget. + record_budget: Arc, } /// A shown picture in output order. @@ -254,6 +414,8 @@ pub struct Decoder { draft: bool, stats: Arc>, pool: Pool, + /// Parse record bytes all frames in flight may hold together. + record_budget: Arc, #[cfg(all(feature = "threads", not(target_arch = "wasm32")))] workers: Option, /// Frames submitted to the workers and not known to be finished (oldest first). @@ -268,6 +430,14 @@ pub struct Decoder { /// Make every frame job panic (tests of the worker panic handling). #[cfg(test)] force_panic: bool, + /// (frame number, superblock row): that frame panics in the row wavefront after that row, + /// once it has published rows that later frames may already be using (tests). + #[cfg(test)] + panic_at_row: Option<(usize, usize)>, + #[cfg(test)] + record_limit: Option, + #[cfg(test)] + frame_number: usize, } fn default_threads() -> usize { @@ -281,10 +451,25 @@ fn default_threads() -> usize { } } -/// Frames decoded concurrently with `threads` threads (each in-flight 1080p frame holds a few -/// tens of MB of state). +/// Frame worker threads with `threads` threads. A frame worker spends most of its time waiting +/// for the parse results and rows of its references, so there is one per thread (at least two, +/// at most [`MAX_FRAME_THREADS`]); the memory is bounded by `in_flight_limit` instead. fn frame_threads(threads: usize) -> usize { - if threads <= 1 { 1 } else { threads.div_ceil(2).clamp(2, 8) } + if threads <= 1 { 1 } else { threads.clamp(2, MAX_FRAME_THREADS) } +} + +const MAX_FRAME_THREADS: usize = 16; + +/// Luma samples of the frames in flight (each in-flight frame holds its state, parse record and +/// samples, roughly 10 bytes per luma sample): ten 2160p frames. +#[cfg(all(feature = "threads", not(target_arch = "wasm32")))] +const IN_FLIGHT_SAMPLES: usize = 10 * 3840 * 2160; + +/// Frames submitted to the frame workers that may be unfinished: two more than the workers, +/// fewer for large frames (at least four). +#[cfg(all(feature = "threads", not(target_arch = "wasm32")))] +fn in_flight_limit(frame_threads: usize, luma_samples: usize) -> usize { + (frame_threads + 2).min((IN_FLIGHT_SAMPLES / luma_samples.max(1)).max(4)) } impl Default for Decoder { @@ -391,6 +576,7 @@ impl Decoder { draft: false, stats, pool, + record_budget: Arc::new(crate::av1::decode::tile::RecordBudget::new(RECORD_BUDGET_BYTES)), #[cfg(all(feature = "threads", not(target_arch = "wasm32")))] workers, in_flight: VecDeque::new(), @@ -400,6 +586,12 @@ impl Decoder { pts: 0, #[cfg(test)] force_panic: false, + #[cfg(test)] + panic_at_row: None, + #[cfg(test)] + record_limit: None, + #[cfg(test)] + frame_number: 0, } } @@ -667,6 +859,13 @@ impl Decoder { let picture = fh.show_frame.then(Slot::new); let draft = self.draft && fh.show_frame && fh.refresh_frame_flags == 0; let tile_count = fh.tile_info.cols.checked_mul(fh.tile_info.rows).ok_or(Error::Invalid("tile count overflows"))?; + let slot = FrameSlot::new(BandFrame::new( + fh.upscaled_width as usize, + fh.frame_height as usize, + seq.color.num_planes, + seq.color.subsampling_x as usize, + seq.color.subsampling_y as usize, + )); self.pending = Some(Box::new(FrameJob { seq, fh, @@ -674,14 +873,23 @@ impl Decoder { ref_info: self.refs.clone(), tiles: Vec::new(), tile_covered: vec![false; tile_count], - slot: Slot::new(), + slot, picture, pts: self.pts, apply_film_grain: self.apply_film_grain, draft, #[cfg(test)] force_panic: self.force_panic, + #[cfg(test)] + panic_at_row: self.panic_at_row.filter(|&(f, _)| f == self.frame_number).map(|(_, r)| r), + #[cfg(test)] + record_limit: self.record_limit, + record_budget: self.record_budget.clone(), })); + #[cfg(test)] + { + self.frame_number += 1; + } Ok(None) } @@ -779,6 +987,8 @@ impl Decoder { .clone() .map(|p| Output::Decoded(p, picture_bytes(job.fh.upscaled_width as usize, job.fh.frame_height as usize, &job.seq.color))); #[cfg(all(feature = "threads", not(target_arch = "wasm32")))] + let fh_samples = (fh.upscaled_width as usize).max(fh.frame_width as usize) * fh.frame_height as usize; + #[cfg(all(feature = "threads", not(target_arch = "wasm32")))] if let Some(w) = &self.workers && let Some(tx) = &w.tx { @@ -787,7 +997,8 @@ impl Decoder { Ok(()) => { self.in_flight.push_back(slot); // Bound the frames in flight (memory): wait for the oldest. - while self.in_flight.len() > self.max_in_flight { + let limit = in_flight_limit(w.handles.len(), fh_samples); + while self.in_flight.len() > limit { let Some(s) = self.in_flight.pop_front() else { break }; let _ = s.wait(); } @@ -808,18 +1019,19 @@ impl Decoder { fn run_job(job: FrameJob, pool: &Pool, stats: &Mutex) { let mut st = DecodeStats::default(); let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| decode_frame(&job, pool, &mut st))); + let rows = job.fh.frame_height as usize; match res.unwrap_or(Err(Error::Invalid("decoder panicked"))) { Ok((rf, pic)) => { if let Some(ps) = &job.picture { ps.set(pic.ok_or(Error::Invalid("shown frame without picture"))); } - job.slot.set(Ok(rf)); + job.slot.finish(Ok(rf), rows); } Err(e) => { if let Some(ps) = &job.picture { ps.set(Err(e.clone())); } - job.slot.set(Err(e)); + job.slot.finish(Err(e), rows); } } if let Ok(mut s) = stats.lock() { @@ -844,71 +1056,191 @@ fn decode_frame(job: &FrameJob, pool: &Pool, stats: &mut DecodeStats) -> Result< if fh.primary_ref_frame != PRIMARY_REF_NONE { used[fh.ref_frame_idx[fh.primary_ref_frame]] = true; } - let mut refs: [Option>; NUM_REF_FRAMES] = Default::default(); - for i in 0..NUM_REF_FRAMES { - if used[i] { - let slot = job.refs[i].as_ref().ok_or(Error::Invalid("missing reference frame"))?; - refs[i] = Some(slot.wait()?); + // Prediction reads the reference planes with this frame's chroma format. + if !fh.frame_is_intra { + for i in 0..NUM_REF_FRAMES { + let Some(slot) = job.refs[i].as_ref().filter(|_| used[i]) else { continue }; + let b = &slot.bands; + let c = &seq.color; + if b.num_planes != c.num_planes || b.subsampling_x != c.subsampling_x as usize || b.subsampling_y != c.subsampling_y as usize { + return Err(Error::Invalid("reference frame has another chroma format")); + } } } - let t = Timer::start(); - let mut fs = FrameState::new(seq, fh); - fs.refs = refs; - fs.ref_info = job.ref_info.clone(); + // Parse dependencies first, then the samples. Parsing reads the CDFs and segment ids of + // the primary reference frame, and the saved motion vectors of the inter references only + // with use_ref_frame_mvs; the parse results of the other references are not waited for + // (their failures still fail this frame through the waits for their samples below). + let mut parse_deps = [false; NUM_REF_FRAMES]; if fh.primary_ref_frame != PRIMARY_REF_NONE { - // load_previous_segment_ids( ) - let (mi_cols, mi_rows) = (fs.mi.cols, fs.mi.rows); - let sh = &mut fs.sh; - if let Some(rf) = &sh.refs[fh.ref_frame_idx[fh.primary_ref_frame]] - && fh.seg.enabled - && rf.mi_cols == mi_cols - && rf.mi_rows == mi_rows - { - sh.prev_segment_ids.copy_from_slice(&rf.segment_ids); - } + parse_deps[fh.ref_frame_idx[fh.primary_ref_frame]] = true; } if fh.use_ref_frame_mvs { - motion_field_estimation(&mut fs); + for i in 0..REFS_PER_FRAME { + parse_deps[fh.ref_frame_idx[i]] = true; + } } - let mut cdfs = if fh.primary_ref_frame == PRIMARY_REF_NONE { - Cdfs::new(fh.quant.base_q_idx) - } else { - let rf = fs.refs[fh.ref_frame_idx[fh.primary_ref_frame]].as_ref().ok_or(Error::Invalid("primary reference frame missing"))?; - let mut c = rf.cdfs.clone(); - c.clear_counts(); - c + let mut parsed: [Option>; NUM_REF_FRAMES] = Default::default(); + for i in 0..NUM_REF_FRAMES { + if parse_deps[i] { + let slot = job.refs[i].as_ref().ok_or(Error::Invalid("missing reference frame"))?; + parsed[i] = Some(slot.wait_parsed()?); + } + } + // The samples of the references predicted from (inter frames only). + let wait_samples = || -> Result<[Option>; NUM_REF_FRAMES]> { + let mut refs: [Option>; NUM_REF_FRAMES] = Default::default(); + if !fh.frame_is_intra { + for i in 0..NUM_REF_FRAMES { + if used[i] { + let slot = job.refs[i].as_ref().ok_or(Error::Invalid("missing reference frame"))?; + slot.progress.wait(job.ref_info[i].frame_height as usize)?; + refs[i] = Some(slot.wait()?); + } + } + } + Ok(refs) }; + // With worker threads, the symbols of every tile are read first, so the parse results + // (which the next frames need before they can read their own symbols) are published + // before reconstruction, and parsing does not wait for the reference samples; on one + // thread each block is reconstructed as it is read. + let split = pool.is_parallel(); + // The frame state before tile decoding (with the reference samples when `with_refs`). + let setup = |with_refs: bool| -> Result<(FrameState, Box)> { + let mut fs = FrameState::new(seq, fh); + if with_refs { + fs.refs = wait_samples()?; + } + fs.parsed = parsed.clone(); + fs.ref_info = job.ref_info.clone(); + if fh.primary_ref_frame != PRIMARY_REF_NONE { + // load_previous_segment_ids( ) + let (mi_cols, mi_rows) = (fs.mi.cols, fs.mi.rows); + let sh = &mut fs.sh; + if let Some(rf) = &sh.parsed[fh.ref_frame_idx[fh.primary_ref_frame]] + && fh.seg.enabled + && rf.mi_cols == mi_cols + && rf.mi_rows == mi_rows + { + sh.prev_segment_ids.copy_from_slice(&rf.segment_ids); + } + } + if fh.use_ref_frame_mvs { + motion_field_estimation(&mut fs); + } + let cdfs = if fh.primary_ref_frame == PRIMARY_REF_NONE { + Cdfs::new(fh.quant.base_q_idx) + } else { + let rf = fs.parsed[fh.ref_frame_idx[fh.primary_ref_frame]].as_ref().ok_or(Error::Invalid("primary reference frame missing"))?; + let mut c = rf.cdfs.clone(); + c.clear_counts(); + c + }; + Ok((fs, cdfs)) + }; + let t = Timer::start(); + let (mut fs, mut cdfs) = setup(!split)?; stats.add(Stage::Setup, t.secs()); let t = Timer::start(); - let saved = decode_tiles(pool, &mut fs, &cdfs, &job.tiles)?; + // Time spent waiting for reference samples is not decoding time. + let mut waited = 0.0; + #[cfg(not(test))] + let record_limit = RECORD_BYTES_PER_SAMPLE; + #[cfg(test)] + let record_limit = job.record_limit.unwrap_or(RECORD_BYTES_PER_SAMPLE); + let mut tiles = parse_tiles(pool, &mut fs, &cdfs, &job.tiles, if split { Pass::Parse } else { Pass::Full }, record_limit, &job.record_budget)?; + // A frame whose record would take too much memory (pathological streams) is decoded again + // in one pass, as on one thread. + let one_pass = split && tiles.records.iter().any(|(_, r)| r.over_limit()); + if one_pass { + // The fallback starts again from the tile data: release the records first. + drop(tiles); + let wait = Timer::start(); + (fs, cdfs) = setup(true)?; + waited = wait.secs(); + tiles = parse_tiles(pool, &mut fs, &cdfs, &job.tiles, Pass::Full, record_limit, &job.record_budget)?; + } stats.tiles += job.tiles.len() as u64; - stats.add(Stage::Tiles, t.secs()); if !fh.disable_frame_end_update_cdf - && let Some(s) = saved + && let Some(s) = tiles.saved.take() { cdfs = s; } - crate::av1::decode::postfilter::apply(&mut fs, stats, pool, job.draft); + if split && !one_pass { + if tiles.whole { + if let Some(state) = tiles.states.pop() { + fs.put_tile_state(state); + job.slot.set_parsed(Ok(Arc::new(parse_results(&fs, cdfs)))); + tiles.states.push(fs.take_tile_state()); + } + } else { + for state in &tiles.states { + fs.merge_tile_modes(state); + } + job.slot.set_parsed(Ok(Arc::new(parse_results(&fs, cdfs)))); + } + if !fh.use_superres { + if !tiles.whole { + // The tiles were parsed into private buffers, merged into the frame above: + // reconstruct them in the frame's own buffers. + tiles.states.clear(); + tiles.states.push(fs.take_tile_state()); + tiles.whole = true; + } + // Reconstruct superblock row by superblock row (every tile of the row), each + // waiting only for the reference rows it reads, with the in-loop filters following + // behind. + waited = reconstruct_wavefront(job, pool, &mut fs, &mut tiles, stats)?; + } else { + let wait = Timer::start(); + fs.refs = wait_samples()?; + waited = wait.secs(); + reconstruct_tiles(pool, &fs.sh, &mut tiles)?; + tiles.finish(&mut fs); + let f = Timer::start(); + if fh.use_superres { + crate::av1::decode::postfilter::apply(&mut fs, stats, pool, job.draft); + publish_bands(&job.slot, &fs.cur, 0, usize::MAX, fh.frame_height as usize); + } else { + let mut pipe = crate::av1::decode::postfilter::Pipeline::new(&fs, job.draft); + let done = pipe.advance(&mut fs, stats, pool, usize::MAX); + publish_final(&job.slot, done, fh.frame_height as usize); + } + waited += f.secs(); + } + } else { + tiles.finish(&mut fs); + job.slot.set_parsed(Ok(Arc::new(parse_results(&fs, cdfs)))); + } + stats.add(Stage::Tiles, t.secs() - waited); + if !split || one_pass { + crate::av1::decode::postfilter::apply(&mut fs, stats, pool, job.draft); + } + if one_pass { + publish_bands(&job.slot, &fs.cur, 0, usize::MAX, fh.frame_height as usize); + } + if split { + // A frame using a reference only for its parse results (an intra frame's CDFs) still + // fails with it, as it does on one thread. + for i in 0..NUM_REF_FRAMES { + if used[i] { + job.refs[i].as_ref().ok_or(Error::Invalid("missing reference frame"))?.wait()?; + } + } + } stats.draft_frames += job.draft as u64; let t = Timer::start(); stats.frames += 1; - if fh.seg.enabled && !fh.seg.update_map { - let prev = std::mem::take(&mut fs.prev_segment_ids); - fs.mi.segment_id.copy_from_slice(&prev); - } - let (mf_refs, mf_mvs) = motion_vector_storage(&fs); let rf = Arc::new(RefFrame { - buf: std::mem::take(&mut fs.cur), - cdfs, + // With worker threads the samples are in the published bands. + buf: if split { FrameBuf::default() } else { std::mem::take(&mut fs.cur) }, + bands: split.then(|| job.slot.bands.clone()), + num_planes: seq.color.num_planes, bit_depth: seq.color.bit_depth, subsampling_x: seq.color.subsampling_x, subsampling_y: seq.color.subsampling_y, - segment_ids: std::mem::take(&mut fs.mi.segment_id), - mi_cols: fs.mi.cols, - mi_rows: fs.mi.rows, color: (seq.color.color_primaries, seq.color.transfer_characteristics, seq.color.matrix_coefficients, seq.color.color_range), - saved_ref_frames: mf_refs, - saved_mvs: mf_mvs, }); // job.picture is None for a shown frame refused for its size (see tile_group) let pic = job.picture.is_some().then(|| { @@ -920,6 +1252,232 @@ fn decode_frame(job: &FrameJob, pool: &Pool, stats: &mut DecodeStats) -> Result< Ok((rf, pic)) } +/// Publish bands [from, to) copied from the final samples `src`, and the row progress they make +/// final. +fn publish_bands(slot: &FrameSlot, src: &FrameBuf, from: usize, to: usize, height: usize) { + let to = to.min(slot.bands.bands()); + for b in from..to { + slot.bands.publish(b, src); + } + slot.progress.publish((to << crate::av1::decode::frame::BAND_LOG2).min(height)); +} + +/// Publish the bands that became final (in order, following those published before) and the +/// row progress they make final. +fn publish_final(slot: &FrameSlot, bands: crate::av1::decode::postfilter::FinalBands, height: usize) { + let mut end = None; + for (b, planes) in bands { + slot.bands.publish_owned(b, planes); + end = Some(b + 1); + } + if let Some(end) = end { + slot.progress.publish((end << crate::av1::decode::frame::BAND_LOG2).min(height)); + } +} + +/// Extra luma rows waited for below what a motion vector reaches: the 8-tap filters read 4 +/// rows below a block, chroma positions round, and the vertical sub-sample phase adds one. +const ROW_WAIT_MARGIN: usize = 16; + +/// The rows of each reference slot that reconstructing the blocks `blocks` (a superblock row +/// and the row above it, whose motion overlapped block motion compensation can reuse) reads, +/// for blocks ending at luma row `bottom`: their reach plus a margin, or everything +/// (`usize::MAX`) for warped motion and scaled references, whose reach is not bounded by the +/// motion vector. +fn rows_needed( + fh: &FrameHeader, + ref_info: &[RefInfo; NUM_REF_FRAMES], + blocks: impl Iterator, + bottom: usize, +) -> [usize; NUM_REF_FRAMES] { + let mut need = [0usize; NUM_REF_FRAMES]; + let mut used = [false; NUM_REF_FRAMES]; + let mut warp = false; + let global = (LAST_FRAME..=ALTREF_FRAME).any(|r| fh.gm_type[r] as usize > TRANSLATION); + for b in blocks { + if !b.inter { + continue; + } + if b.motion_mode as usize == LOCALWARP || (global && (b.y_mode == GLOBALMV || b.y_mode == GLOBAL_GLOBALMV)) { + warp = true; + } + let bottom = bottom.max((b.mi_row + b.bh4) * 4); + for list in 0..2 { + let rf = b.ref_frame[list]; + if rf <= INTRA_FRAME as i8 { + continue; + } + let Some(&i) = fh.ref_frame_idx.get(rf as usize - LAST_FRAME) else { continue }; + used[i] = true; + let ri = &ref_info[i]; + if ri.upscaled_width != fh.frame_width || ri.frame_height != fh.frame_height { + need[i] = usize::MAX; + continue; + } + let down = (b.mv[list][0].max(0) as usize).div_ceil(8); + need[i] = need[i].max(bottom.saturating_add(down).saturating_add(ROW_WAIT_MARGIN)); + } + } + if warp { + for i in 0..NUM_REF_FRAMES { + if used[i] { + need[i] = usize::MAX; + } + } + } + need +} + +/// Reconstructed luma rows between two runs of the in-loop filter pipeline in +/// [`reconstruct_wavefront`] (finer steps publish rows sooner, coarser ones filter more bands in +/// parallel). +const FILTER_STEP_ROWS: usize = 128; + +/// Reconstruct a frame superblock row by superblock row (row wavefront): before each row, wait +/// only for the reference rows it reads; then reconstruct that row in every tile it crosses +/// (tiles share no prediction context, so the order of the tiles within a row does not matter) +/// and run the in-loop filters on what that allows, publishing the bands that became final. +/// `tiles` holds the whole frame's buffers. Returns the seconds spent waiting for references +/// and filtering (not tile decoding). +fn reconstruct_wavefront(job: &FrameJob, pool: &Pool, fs: &mut FrameState, tiles: &mut FrameTiles, stats: &mut DecodeStats) -> Result { + let fh = &job.fh; + let mut other = 0.0; + let ti = fh.tile_info.clone(); + let Some(state) = tiles.states.pop() else { + return Err(Error::Invalid("no tile to reconstruct")); + }; + // The record of every tile, by tile number. + let mut recs: Vec> = (0..ti.rows * ti.cols).map(|_| None).collect(); + for (num, rec) in std::mem::take(&mut tiles.records) { + *recs.get_mut(num).ok_or(Error::Invalid("tile number out of range"))? = Some(rec); + } + let mut used = [false; NUM_REF_FRAMES]; + if !fh.frame_is_intra { + for i in 0..REFS_PER_FRAME { + used[fh.ref_frame_idx[i]] = true; + } + } + for i in 0..NUM_REF_FRAMES { + if used[i] { + let slot = job.refs[i].as_ref().ok_or(Error::Invalid("missing reference frame"))?; + fs.ref_rows[i] = Some(slot.bands.clone()); + } + } + fs.put_tile_state(state); + let mut pipe = crate::av1::decode::postfilter::Pipeline::new(fs, job.draft); + let sb4 = if job.seq.use_128x128_superblock { 32 } else { 16 }; + let mi_rows = fh.mi_rows as usize; + let sb_rows = mi_rows.div_ceil(sb4); + let mut bufs = (crate::av1::decode::tile::Buffers::new(), Cdfs::new(fh.quant.base_q_idx)); + let mut filtered = 0; + let mut tile_row = 0; + for row in 0..sb_rows { + // Tile rows start on superblock rows. + while tile_row + 1 < ti.rows && row * sb4 >= ti.mi_row_starts[tile_row + 1] as usize { + tile_row += 1; + } + let local = (row * sb4).saturating_sub(ti.mi_row_starts[tile_row] as usize) / sb4; + let w = Timer::start(); + if !fh.frame_is_intra { + let mut need = [0usize; NUM_REF_FRAMES]; + for col in 0..ti.cols { + let Some(rec) = &recs[tile_row * ti.cols + col] else { continue }; + let width = (ti.mi_col_starts[col + 1] as usize).min(fh.mi_cols as usize).saturating_sub(ti.mi_col_starts[col] as usize); + let n = rows_needed(fh, &job.ref_info, rec.row_blocks(width.div_ceil(sb4), local.saturating_sub(1), local + 1), (row + 1) * sb4 * 4); + for i in 0..NUM_REF_FRAMES { + need[i] = need[i].max(n[i]); + } + } + for i in 0..NUM_REF_FRAMES { + if used[i] && need[i] > 0 { + let slot = job.refs[i].as_ref().ok_or(Error::Invalid("missing reference frame"))?; + slot.progress.wait(need[i].min(job.ref_info[i].frame_height as usize))?; + } + } + } + other += w.secs(); + let mut t = fs.take_tile_state(); + let mut res = Ok(()); + for col in 0..ti.cols { + let Some(rec) = recs[tile_row * ti.cols + col].as_mut() else { continue }; + let (b, cdf) = bufs; + let mut td = TileDecoder::with_buffers(&fs.sh, &mut t, &[], cdf, tile_row, col, b); + td.pass = Pass::Reconstruct; + td.record = std::mem::take(rec); + res = td.reconstruct_sb_rows(1); + *rec = std::mem::take(&mut td.record); + bufs = td.into_buffers(); + if res.is_err() { + break; + } + } + fs.put_tile_state(t); + res?; + let f = Timer::start(); + let recon_rows = ((row + 1) * sb4 * 4).min(mi_rows * 4); + // Filter in steps of a few bands, so the bands of a step run in parallel. + if recon_rows >= filtered + FILTER_STEP_ROWS || recon_rows == mi_rows * 4 { + filtered = recon_rows; + let done = pipe.advance(fs, stats, pool, recon_rows); + publish_final(&job.slot, done, fh.frame_height as usize); + } + other += f.secs(); + #[cfg(test)] + assert!( + !(job.panic_at_row.is_some_and(|r| row >= r) && job.slot.progress.rows() > 0), + "forced panic in the row wavefront after publishing rows" + ); + } + // A reference that failed after publishing the rows used here still fails this frame, as + // it does when frames are decoded one after another. + for i in 0..NUM_REF_FRAMES { + if used[i] { + let slot = job.refs[i].as_ref().ok_or(Error::Invalid("missing reference frame"))?; + slot.wait()?; + } + } + Ok(other) +} + +/// Most bytes a tile's parse record may take per luma sample of the tile. Typical streams need +/// a fraction of this; past it (pathological streams: tiny blocks, large palettes, every +/// coefficient coded) the frame is decoded in one pass instead, so memory stays bounded. +const RECORD_BYTES_PER_SAMPLE: usize = 32; + +/// Most parse record bytes all frames of a decoder hold at once. Past it, the frames that +/// cannot reserve more are decoded in one pass, so the frames in flight together stay bounded +/// too (typical streams need a few bytes per luma sample: under 100 MB for a 2160p frame). +const RECORD_BUDGET_BYTES: usize = 1 << 30; + +/// The tiles of a frame between parsing and reconstruction. +struct FrameTiles { + /// One state per tile (decoded in parallel into private buffers), or one for the whole + /// frame (tiles one after another). + states: Vec, + /// Per tile: (tile number, record of [`Pass::Parse`]). + records: Vec<(usize, TileRecord)>, + /// The final CDFs of tile context_update_tile_id. + saved: Option>, + /// `states` holds the frame's own buffers (taken with [`FrameState::take_tile_state`]). + whole: bool, +} + +impl FrameTiles { + /// Move the tile buffers (mode info, filter parameters and, after reconstruction, the + /// samples) into the frame. + fn finish(self, fs: &mut FrameState) { + if self.whole { + if let Some(t) = self.states.into_iter().next() { + fs.put_tile_state(t); + } + } else { + for t in &self.states { + fs.merge_tile_state(t); + } + } + } +} + /// Bytes all parallel tile states may hold of whole-frame CDEF and restoration metadata; past it /// the tiles decode one after another on the frame's own metadata. const TILE_METADATA_BUDGET: usize = 256 << 20; @@ -928,16 +1486,30 @@ fn tile_metadata_fits(tiles: usize, per_tile: usize) -> bool { tiles.checked_mul(per_tile).is_some_and(|n| n <= TILE_METADATA_BUDGET) } -/// Decode the tiles of a frame (tile number, data), in parallel when several; returns the final -/// CDFs of tile context_update_tile_id. -fn decode_tiles(pool: &Pool, fs: &mut FrameState, cdfs: &Cdfs, tiles: &[(usize, Vec)]) -> Result>> { +/// Run `pass` (Full or Parse) over the tiles of a frame. +/// `record_limit`: most record bytes per luma sample of a tile (see [`RECORD_BYTES_PER_SAMPLE`]). +/// `budget`: the decoder-wide budget the records are reserved from. +fn parse_tiles( + pool: &Pool, + fs: &mut FrameState, + cdfs: &Cdfs, + tiles: &[(usize, Vec)], + pass: Pass, + record_limit: usize, + budget: &Arc, +) -> Result { let ti = fs.fh.tile_info.clone(); let ctx_tile = ti.context_update_tile_id as usize; - let run = |sh: &FrameShared, t: &mut TileState, num: usize, data: &[u8]| -> Result>> { + let run = |sh: &FrameShared, t: &mut TileState, num: usize, data: &[u8]| -> Result<(Option>, TileRecord)> { t.intra_frame_y_mode_cdf = DEFAULT_INTRA_FRAME_Y_MODE_CDF; let mut td = TileDecoder::new(sh, t, data, Box::new(cdfs.clone()), num / ti.cols, num % ti.cols); + td.pass = pass; + let (rows, cols) = (td.mi_row_end.saturating_sub(td.mi_row_start), td.mi_col_end.saturating_sub(td.mi_col_start)); + td.record.limit = rows.saturating_mul(cols).saturating_mul(16 * record_limit); + td.record.budget = Some(budget.clone()); td.decode_tile()?; - Ok((num == ctx_tile).then_some(td.cdf)) + let rec = std::mem::take(&mut td.record); + Ok(((num == ctx_tile).then_some(td.cdf), rec)) }; // Intra block copy reads the current frame through the tile's own buffer: keep whole-frame // buffers (tiles one after another) for it. @@ -953,42 +1525,75 @@ fn decode_tiles(pool: &Pool, fs: &mut FrameState, cdfs: &Cdfs, tiles: &[(usize, .collect(); let sh = &fs.sh; let results = pool.map_mut(&mut states, |i, t| run(sh, t, tiles[i].0, &tiles[i].1)); - for t in &states { - fs.merge_tile_state(t); - } let mut saved = None; - for r in results { - if let Some(c) = r? { - saved = Some(c); + let mut records = Vec::with_capacity(tiles.len()); + for (r, (num, _)) in results.into_iter().zip(tiles) { + let (c, rec) = r?; + if c.is_some() { + saved = c; } + records.push((*num, rec)); } - return Ok(saved); + return Ok(FrameTiles { states, records, saved, whole: false }); } let mut t = fs.take_tile_state(); let mut saved = None; + let mut records = Vec::with_capacity(tiles.len()); let mut res = Ok(()); for (num, data) in tiles { match run(&fs.sh, &mut t, *num, data) { - Ok(Some(c)) => saved = Some(c), - Ok(None) => {} + Ok((c, rec)) => { + if c.is_some() { + saved = c; + } + records.push((*num, rec)); + } Err(e) => { res = Err(e); break; } } } - fs.put_tile_state(t); - res.map(|_| saved) + if let Err(e) = res { + fs.put_tile_state(t); + return Err(e); + } + Ok(FrameTiles { states: vec![t], records, saved, whole: true }) +} + +/// Reconstruct parsed tiles (in parallel when each has its own state). +fn reconstruct_tiles(pool: &Pool, fs: &FrameShared, tiles: &mut FrameTiles) -> Result<()> { + let ti = fs.fh.tile_info.clone(); + let run = |t: &mut TileState, num: usize, rec: TileRecord| -> Result<()> { + let mut td = TileDecoder::new(fs, t, &[], Cdfs::new(fs.fh.quant.base_q_idx), num / ti.cols, num % ti.cols); + td.pass = Pass::Reconstruct; + td.record = rec; + td.decode_tile() + }; + let records = std::mem::take(&mut tiles.records); + if !tiles.whole { + let mut items: Vec<(&mut TileState, Option<(usize, TileRecord)>)> = tiles.states.iter_mut().zip(records.into_iter().map(Some)).collect(); + let results = pool.map_mut(&mut items, |_, (t, rec)| match rec.take() { + Some((num, rec)) => run(t, num, rec), + None => Ok(()), + }); + return results.into_iter().collect(); + } + let Some(t) = tiles.states.first_mut() else { return Ok(()) }; + for (num, rec) in records { + run(t, num, rec)?; + } + Ok(()) } fn output_picture(seq: &SequenceHeader, rf: &RefFrame, w: usize, h: usize, grain: &FilmGrainParams, apply_film_grain: bool, pts: i64) -> Picture { let ssx = rf.subsampling_x as usize; let ssy = rf.subsampling_y as usize; - let num_planes = rf.buf.num_planes; + let num_planes = rf.num_planes; let mut planes: [Vec; 3] = Default::default(); for p in 0..num_planes { let (pw, ph) = if p == 0 { (w, h) } else { ((w + ssx) >> ssx, (h + ssy) >> ssy) }; - let src = &rf.buf.planes[p]; + let src = rf.plane(p); let mut v = Vec::with_capacity(pw * ph); for y in 0..ph { v.extend_from_slice(&src.row(y)[..pw]); @@ -1016,25 +1621,40 @@ fn output_picture(seq: &SequenceHeader, rf: &RefFrame, w: usize, h: usize, grain pic } -/// Motion field motion vector storage process (7.19): (MfRefFrames, MfMvs). +/// What later frames read from this one while parsing: the final CDFs, the segment ids (the +/// previous frame's when the map is not updated) and the stored motion vectors (7.19). The +/// in-loop filters read the decoded segment ids, so the frame's own map is left alone. +fn parse_results(fs: &FrameState, cdfs: Box) -> Parsed { + let fh = &fs.fh; + let segment_ids = if fh.seg.enabled && !fh.seg.update_map { fs.prev_segment_ids.clone() } else { fs.mi.segment_id.clone() }; + let (saved_ref_frames, saved_mvs) = motion_vector_storage(fs); + Parsed { cdfs, segment_ids, mi_cols: fs.mi.cols, mi_rows: fs.mi.rows, saved_ref_frames, saved_mvs } +} + +/// Motion field motion vector storage process (7.19): (MfRefFrames, MfMvs), kept only where +/// the projection process (7.9.2) reads them, the odd row and column of every 8x8 block +/// (index `y8 * (MiCols >> 1) + x8`). fn motion_vector_storage(fs: &FrameState) -> (Vec, Vec<[i32; 2]>) { let mi = &fs.mi; - let n = mi.rows * mi.cols; - let mut refs = vec![-1i8; n]; - let mut mvs = vec![[0i32; 2]; n]; let fh = &fs.fh; - for i in 0..n { - for list in 0..2 { - let r = mi.ref_frame[i][list]; - if r > INTRA_FRAME as i8 { - let ref_idx = fh.ref_frame_idx[r as usize - LAST_FRAME]; - let dist = crate::av1::decode::header::relative_dist(&fs.seq, fs.ref_info[ref_idx].order_hint, fh.order_hint); - if dist < 0 { - let m = mi.mv[i][list]; - let (row, col) = (m.row as i32, m.col as i32); - if row.abs() <= REFMVS_LIMIT as i32 && col.abs() <= REFMVS_LIMIT as i32 { - refs[i] = r; - mvs[i] = [row, col]; + let (mi_cols, w8, h8) = (fh.mi_cols as usize, fh.mi_cols as usize >> 1, fh.mi_rows as usize >> 1); + let mut refs = vec![-1i8; w8 * h8]; + let mut mvs = vec![[0i32; 2]; w8 * h8]; + for y8 in 0..h8 { + for x8 in 0..w8 { + let (i, o) = ((2 * y8 + 1) * mi_cols + 2 * x8 + 1, y8 * w8 + x8); + for list in 0..2 { + let r = mi.ref_frame[i][list]; + if r > INTRA_FRAME as i8 { + let ref_idx = fh.ref_frame_idx[r as usize - LAST_FRAME]; + let dist = crate::av1::decode::header::relative_dist(&fs.seq, fs.ref_info[ref_idx].order_hint, fh.order_hint); + if dist < 0 { + let m = mi.mv[i][list]; + let (row, col) = (m.row as i32, m.col as i32); + if row.abs() <= REFMVS_LIMIT as i32 && col.abs() <= REFMVS_LIMIT as i32 { + refs[o] = r; + mvs[o] = [row, col]; + } } } } @@ -1092,7 +1712,7 @@ fn project_pos(v8: i32, delta: i32, dst_sign: i32, max8: i32, max_off8: i32) -> /// Projection process (7.9.2). fn project(fs: &mut FrameState, src: usize, dst_sign: i32) -> bool { - let FrameShared { seq, fh, refs, ref_info, motion_field, .. } = &mut fs.sh; + let FrameShared { seq, fh, parsed, ref_info, motion_field, .. } = &mut fs.sh; let src_idx = fh.ref_frame_idx[src - LAST_FRAME]; let w8 = fh.mi_cols as i32 >> 1; let h8 = fh.mi_rows as i32 >> 1; @@ -1100,20 +1720,18 @@ fn project(fs: &mut FrameState, src: usize, dst_sign: i32) -> bool { if ri.mi_rows != fh.mi_rows || ri.mi_cols != fh.mi_cols || ri.frame_type == INTRA_ONLY_FRAME as u8 || ri.frame_type == KEY_FRAME as u8 { return false; } - let Some(rf) = &refs[src_idx] else { return false }; + let Some(rf) = &parsed[src_idx] else { return false }; let rd = |a: u32, b: u32| crate::av1::decode::header::relative_dist(seq, a, b); - let mi_cols = fh.mi_cols as usize; for y8 in 0..h8 { for x8 in 0..w8 { - let row = (2 * y8 + 1) as usize; - let col = (2 * x8 + 1) as usize; - let src_ref = rf.saved_ref_frames[row * mi_cols + col]; + let at = (y8 * w8 + x8) as usize; + let src_ref = rf.saved_ref_frames[at]; if src_ref > INTRA_FRAME as i8 { let ref_to_cur = rd(fh.order_hints[src], fh.order_hint); let ref_offset = rd(fh.order_hints[src], ri.saved_order_hints[src_ref as usize]); let pos_valid = ref_to_cur.abs() <= MAX_FRAME_DISTANCE as i32 && ref_offset.abs() <= MAX_FRAME_DISTANCE as i32 && ref_offset > 0; if pos_valid { - let mv = rf.saved_mvs[row * mi_cols + col]; + let mv = rf.saved_mvs[at]; let proj = get_mv_projection(mv, ref_to_cur * dst_sign, ref_offset); let py = project_pos(y8, proj[0], dst_sign, h8, MAX_OFFSET_HEIGHT as i32); let px = project_pos(x8, proj[1], dst_sign, w8, MAX_OFFSET_WIDTH as i32); @@ -1145,13 +1763,18 @@ mod tests { ref_info: Default::default(), tiles: Vec::new(), tile_covered: vec![false; 3], - slot: Slot::new(), + slot: FrameSlot::new(BandFrame::new(0, 0, 1, 0, 0)), picture: None, pts: 0, apply_film_grain: false, draft: false, #[cfg(test)] force_panic: false, + #[cfg(test)] + panic_at_row: None, + #[cfg(test)] + record_limit: None, + record_budget: decoder.record_budget.clone(), })); decoder } @@ -1298,6 +1921,317 @@ mod tests { assert!(frame_size_allowed(1, 1)); } + /// Random short sleeps in row progress publishing and waiting, to shake out scheduling + /// orders a quiet machine never produces (enabled by [`JitterGuard`]). + static JITTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + + pub(super) fn jitter() { + use std::cell::Cell; + use std::sync::atomic::Ordering; + if JITTER.load(Ordering::Relaxed) == 0 { + return; + } + static SEED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0x2545_f491_4f6c_dd1d); + thread_local!(static RNG: Cell = Cell::new(SEED.fetch_add(0x9e37_79b9_7f4a_7c15, Ordering::Relaxed) | 1)); + let r = RNG.with(|c| { + let mut x = c.get(); + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + c.set(x); + x + }); + match r % 4 { + 0 => std::thread::yield_now(), + 1 => std::thread::sleep(std::time::Duration::from_micros(r % 300)), + _ => {} + } + } + + struct JitterGuard; + impl JitterGuard { + fn on() -> JitterGuard { + JITTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + JitterGuard + } + } + impl Drop for JitterGuard { + fn drop(&mut self) { + JITTER.fetch_sub(1, std::sync::atomic::Ordering::SeqCst); + } + } + + /// Inter test streams made with ffmpeg / SVT-AV1 (None, reported, without them): several + /// superblock rows and hierarchical references; odd size; super-resolution; 2x2 tiles. + const STREAMS: [(&str, &str, &str); 4] = [ + ("wavefront_unit_352x288", "testsrc2=size=352x288:rate=25", "-preset 8 -crf 35"), + ("wavefront_unit_odd", "testsrc2=size=203x117:rate=25,noise=alls=15:allf=t", "-preset 8 -crf 40"), + ("wavefront_unit_superres", "testsrc2=size=416x240:rate=25", "-preset 8 -crf 35 -svtav1-params superres-mode=1:superres-denom=12"), + ("wavefront_unit_tiles", "mandelbrot=size=650x370:rate=25", "-preset 8 -crf 32 -svtav1-params tile-columns=1:tile-rows=1"), + ]; + + fn inter_stream((name, src, args): (&str, &str, &str)) -> Option>> { + let ff = craft_media_testkit::ffmpeg_or_skip("av1 wavefront")?; + if !craft_media_testkit::ffmpeg_has_encoder(&ff, "libsvtav1") { + craft_media_testkit::skip_test("av1 wavefront", "this ffmpeg has no libsvtav1 encoder"); + return None; + } + let out = craft_media_testkit::fixtures_dir("av1").join(format!("{name}.ivf")); + let path = craft_media_testkit::fixtures::generate(&out, |tmp| { + std::process::Command::new(&ff) + .args([ + "-hide_banner", + "-loglevel", + "error", + "-y", + "-f", + "lavfi", + "-i", + src, + "-frames:v", + "16", + "-pix_fmt", + "yuv420p", + "-c:v", + "libsvtav1", + ]) + .args(args.split_whitespace()) + .args(["-f", "ivf"]) + .arg(tmp) + .stdin(std::process::Stdio::null()) + .status() + .is_ok_and(|s| s.success()) + }); + let path = path.unwrap_or_else(|| panic!("ffmpeg has libsvtav1 but could not encode {name}")); + let d = std::fs::read(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display())); + let mut pos = usize::from(u16::from_le_bytes([d[6], d[7]])); + let mut out = Vec::new(); + while let Some(h) = d.get(pos..pos + 12) { + let n = u32::from_le_bytes([h[0], h[1], h[2], h[3]]) as usize; + pos += 12; + out.push(d[pos..pos + n].to_vec()); + pos += n; + } + assert_eq!(out.len(), 16, "{name}: temporal units"); + Some(out) + } + + /// Decode `tus` with `dec`: (pictures, errors). + fn decode_tus(mut dec: Decoder, tus: &[Vec]) -> (Vec, usize) { + let (mut pics, mut errors) = (Vec::new(), 0); + for (i, tu) in tus.iter().enumerate() { + match dec.decode_pts(tu, i as i64) { + Ok(p) => pics.extend(p), + Err(_) => errors += 1, + } + } + match dec.flush_result() { + Ok(p) => pics.extend(p), + Err(_) => errors += 1, + } + (pics, errors) + } + + #[test] + fn jittered_wavefront_gives_the_single_thread_pictures() { + for stream in STREAMS { + let Some(tus) = inter_stream(stream) else { return }; + let name = stream.0; + let (want, errors) = decode_tus(Decoder::with_threads(1), &tus); + assert_eq!(errors, 0, "{name}"); + let _jitter = JitterGuard::on(); + for threads in [2, 3, 5, 8] { + for round in 0..2 { + let tus = tus.clone(); + let (got, errors) = within_a_minute(move || decode_tus(Decoder::with_threads(threads), &tus)); + assert_eq!(errors, 0, "{name}: threads {threads} round {round}"); + assert!(got == want, "{name}: threads {threads} round {round}: pictures differ"); + } + } + } + } + + #[test] + fn frames_over_the_record_limit_decode_in_one_pass() { + for stream in [STREAMS[0], STREAMS[3]] { + let Some(tus) = inter_stream(stream) else { return }; + let name = stream.0; + let (want, _) = decode_tus(Decoder::with_threads(1), &tus); + for (threads, limit) in [(3, 0), (8, 0), (8, 1)] { + let tus = tus.clone(); + let (got, errors) = within_a_minute(move || { + let mut dec = Decoder::with_threads(threads); + dec.record_limit = Some(limit); + decode_tus(dec, &tus) + }); + assert_eq!(errors, 0, "{name}: threads {threads}, limit {limit}"); + assert!(got == want, "{name}: threads {threads}, limit {limit}: pictures differ"); + } + } + } + + #[test] + fn the_parse_records_of_all_frames_stay_within_the_decoder_budget() { + for stream in [STREAMS[0], STREAMS[3]] { + let Some(tus) = inter_stream(stream) else { return }; + let name = stream.0; + let (want, _) = decode_tus(Decoder::with_threads(1), &tus); + // Room for about one frame's records: the other frames in flight decode in one pass. + for (threads, budget) in [(3, 0), (8, 3 << 20), (16, 1 << 20)] { + let tus = tus.clone(); + let b = Arc::new(crate::av1::decode::tile::RecordBudget::new(budget)); + let mut dec = Decoder::with_threads(threads); + dec.record_budget = b.clone(); + let (got, errors) = within_a_minute(move || decode_tus(dec, &tus)); + assert_eq!(errors, 0, "{name}: threads {threads}, budget {budget}"); + assert!(got == want, "{name}: threads {threads}, budget {budget}: pictures differ"); + assert!(b.peak.load(std::sync::atomic::Ordering::Acquire) <= budget, "{name}: threads {threads}: over the budget"); + assert_eq!(b.used(), 0, "{name}: threads {threads}: records not released"); + } + } + } + + #[cfg(all(feature = "threads", not(target_arch = "wasm32")))] + #[test] + fn a_reference_panicking_after_publishing_rows_fails_without_a_hang() { + let Some(tus) = inter_stream(STREAMS[0]) else { return }; + let _jitter = JitterGuard::on(); + // Frame 1 is the first inter frame; later frames predict from it. + for threads in [2, 3, 8] { + for frame in [0, 1, 2] { + let tus = tus.clone(); + let (pics, errors) = within_a_minute(move || { + let mut dec = Decoder::with_threads(threads); + dec.panic_at_row = Some((frame, 1)); + decode_tus(dec, &tus) + }); + assert!(errors > 0, "threads {threads}, frame {frame}: the panic was not reported ({} pictures)", pics.len()); + } + } + } + + #[test] + fn dropping_a_busy_decoder_does_not_hang() { + let Some(tus) = inter_stream(STREAMS[0]) else { return }; + for threads in [2, 3, 8, 16] { + for cut in [1, 3, tus.len() / 2] { + let tus = tus.clone(); + within_a_minute(move || { + let mut dec = Decoder::with_threads(threads); + for (i, tu) in tus.iter().take(cut).enumerate() { + let _ = dec.decode_pts(tu, i as i64); + } + drop(dec); + }); + } + } + } + + #[test] + fn a_flush_mid_stream_keeps_the_pictures() { + let Some(tus) = inter_stream(STREAMS[0]) else { return }; + let (want, _) = decode_tus(Decoder::with_threads(1), &tus); + for threads in [2, 8] { + for cut in [2, 5, tus.len() / 2] { + let tus = tus.clone(); + let got = within_a_minute(move || { + let mut dec = Decoder::with_threads(threads); + let mut pics = Vec::new(); + for (i, tu) in tus.iter().enumerate() { + if i == cut { + pics.extend(dec.flush_result().expect("flush")); + } + pics.extend(dec.decode_pts(tu, i as i64).expect("decode")); + } + pics.extend(dec.flush_result().expect("flush")); + pics + }); + assert!(got == want, "threads {threads}, flush before unit {cut}"); + } + } + } + + #[test] + fn progress_wakes_every_waiter_with_the_rows_or_the_failure() { + let p = Arc::new(Progress::new()); + let waiters: Vec<_> = (1..=8) + .map(|k| { + let p = p.clone(); + std::thread::spawn(move || p.wait(k * 10)) + }) + .collect(); + p.publish(40); + p.publish(20); // never goes back + assert_eq!(p.wait(40), Ok(())); + p.fail(); + let res: Vec<_> = waiters.into_iter().map(|w| w.join().expect("waiter")).collect(); + assert!(res[..4].iter().all(|r| r.is_ok()), "{res:?}"); + assert!(res[4..].iter().all(|r| r.is_err()), "{res:?}"); + assert_eq!(p.wait(40), Ok(()), "rows published before a failure stay readable"); + } + + #[test] + fn a_failed_frame_keeps_its_published_parse_results() { + let slot = FrameSlot::new(BandFrame::new(16, 16, 1, 0, 0)); + let parsed = Parsed { cdfs: Cdfs::new(0), segment_ids: vec![], mi_cols: 4, mi_rows: 4, saved_ref_frames: vec![], saved_mvs: vec![] }; + slot.set_parsed(Ok(Arc::new(parsed))); + slot.finish(Err(Error::Invalid("x")), 16); + assert!(slot.wait_parsed().is_ok()); + assert!(slot.wait().is_err()); + assert!(slot.progress.wait(1).is_err()); + // A frame failing before its parse results: every waiter gets the error. + let slot = FrameSlot::new(BandFrame::new(16, 16, 1, 0, 0)); + slot.finish(Err(Error::Invalid("y")), 16); + assert!(slot.wait_parsed().is_err()); + } + + fn motion(mi_row: usize, bh4: usize, ref_frame: [i8; 2], mv: [[i32; 2]; 2]) -> crate::av1::decode::tile::BlockMotion { + crate::av1::decode::tile::BlockMotion { + mi_row, + bh4, + inter: true, + ref_frame, + mv, + motion_mode: 0, + y_mode: crate::av1::decode::spec_tables::NEARESTMV, + } + } + + #[test] + fn rows_needed_follow_the_motion_vectors() { + let mut fh = FrameHeader { frame_width: 64, upscaled_width: 64, frame_height: 256, ..Default::default() }; + fh.ref_frame_idx = [0, 1, 2, 3, 4, 5, 6]; + let mut ri: [RefInfo; NUM_REF_FRAMES] = Default::default(); + for r in ri.iter_mut() { + (r.upscaled_width, r.frame_height) = (64, 256); + } + let none = [[0; 2]; 2]; + // 41/8 rows down rounds up to 6; upward motion needs only the block's own rows. + let need = rows_needed(&fh, &ri, [motion(0, 16, [1, -1], [[41, 0], [0, 0]]), motion(0, 16, [2, 3], [[-80, 0], [7, 0]])].into_iter(), 64); + assert_eq!(need[0], 64 + 6 + ROW_WAIT_MARGIN); + assert_eq!(need[1], 64 + ROW_WAIT_MARGIN); + assert_eq!(need[2], 64 + 1 + ROW_WAIT_MARGIN); + assert_eq!(need[3], 0); + // Intra blocks and intra block copy read no reference. + let intra = crate::av1::decode::tile::BlockMotion { inter: false, ..motion(0, 16, [1, -1], none) }; + assert_eq!(rows_needed(&fh, &ri, [intra].into_iter(), 64), [0; NUM_REF_FRAMES]); + // Blocks reaching below the superblock row count from their own bottom. + assert_eq!(rows_needed(&fh, &ri, [motion(12, 8, [1, -1], none)].into_iter(), 64)[0], 80 + ROW_WAIT_MARGIN); + // Local warp: the whole of every reference the rows use. + let warp = + crate::av1::decode::tile::BlockMotion { motion_mode: crate::av1::decode::spec_tables::LOCALWARP as u8, ..motion(0, 16, [1, -1], none) }; + let need = rows_needed(&fh, &ri, [warp, motion(0, 16, [2, -1], none)].into_iter(), 64); + assert_eq!((need[0], need[1], need[2]), (usize::MAX, usize::MAX, 0)); + // Global motion beyond translation for GLOBALMV blocks. + fh.gm_type[3] = (TRANSLATION + 1) as u8; + let global = crate::av1::decode::tile::BlockMotion { y_mode: GLOBALMV, ..motion(0, 16, [1, -1], none) }; + assert_eq!(rows_needed(&fh, &ri, [global].into_iter(), 64)[0], usize::MAX); + fh.gm_type[3] = 0; + // A scaled reference. + ri[0].frame_height = 128; + assert_eq!(rows_needed(&fh, &ri, [motion(0, 16, [1, -1], none)].into_iter(), 64)[0], usize::MAX); + } + #[test] fn frames_beyond_the_limits_are_refused() { assert!(!frame_size_allowed(16384, 2177)); // one row over MaxPicSize diff --git a/crates/video/src/av1/decode/frame.rs b/crates/video/src/av1/decode/frame.rs index d0432e2a8..e28ca89e9 100644 --- a/crates/video/src/av1/decode/frame.rs +++ b/crates/video/src/av1/decode/frame.rs @@ -197,6 +197,50 @@ impl FrameBuf { } } + /// Copy luma rows [y0, y1) (chroma rows scaled down; clipped to the stored rows) of `src`, a + /// frame of the same geometry. + pub fn copy_rows_from(&mut self, src: &FrameBuf, y0: usize, y1: usize) { + for p in 0..self.num_planes { + let sy = if p == 0 { 0 } else { self.subsampling_y }; + let (d, s) = (&mut self.planes[p], &src.planes[p]); + if d.stride != s.stride { + continue; + } + let a = (y0 >> sy).min(d.rows).min(s.rows) * d.stride; + let b = (y1 >> sy).min(d.rows).min(s.rows) * d.stride; + if let (Some(dst), Some(src)) = (d.data.get_mut(a..b), s.data.get(a..b)) { + dst.copy_from_slice(src); + } + } + } + + /// Copies of luma rows [y0, y1) (chroma rows scaled down; clipped to the stored rows), one + /// plane region each. + pub fn rows_copy(&self, y0: usize, y1: usize) -> [Plane; 3] { + std::array::from_fn(|p| { + if p >= self.num_planes { + return Plane::default(); + } + let sy = if p == 0 { 0 } else { self.subsampling_y }; + let s = &self.planes[p]; + let (a, b) = ((y0 >> sy).min(s.rows), (y1 >> sy).min(s.rows)); + let mut out = Plane::region(0, a, s.stride, b - a); + if let Some(src) = s.data.get(a * s.stride..b * s.stride) { + out.data.copy_from_slice(src); + } + out + }) + } + + /// A frame of this geometry (samples not copied: zero). + pub fn same_geometry(&self) -> FrameBuf { + let planes = std::array::from_fn(|p| { + let pl = &self.planes[p]; + Plane { data: zeroed(pl.data.len()), stride: pl.stride, rows: pl.rows, ox: pl.ox, oy: pl.oy } + }); + FrameBuf { planes, ..*self } + } + /// [`Plane::row_bands`] of all three planes for ranges of luma rows (chroma rows scaled /// down): element `i` holds the bands of range `i`. pub fn row_bands(&mut self, luma: &[(usize, usize)]) -> Vec<[RowBand<'_>; 3]> { @@ -208,6 +252,128 @@ impl FrameBuf { } } +/// Luma rows per published band of a [`BandFrame`] (log2). +pub const BAND_LOG2: u32 = 6; + +/// One plane of a frame's final samples, published band by band while the rest of the frame +/// is still being decoded (see [`BandFrame`]). A band is written once and then only read. +pub struct BandPlane { + bands: Vec>, + stride: usize, + rows: usize, + log2: u32, + /// Returned for rows of a band that is not published: zeros instead of a panic. Readers wait + /// for the row progress first and references of another chroma format are refused, so + /// this only happens through a scheduling bug. + missing: Box<[u16]>, +} + +impl BandPlane { + fn new(stride: usize, rows: usize, log2: u32) -> BandPlane { + let n = rows.div_ceil(1 << log2); + BandPlane { bands: (0..n).map(|_| std::sync::OnceLock::new()).collect(), stride, rows, log2, missing: vec![0; stride].into_boxed_slice() } + } + + /// Row `y` (`stride` samples) of a published band. + #[inline(always)] + pub fn row(&self, y: usize) -> &[u16] { + let o = (y & ((1 << self.log2) - 1)) * self.stride; + match self.bands.get(y >> self.log2).and_then(|b| b.get()).and_then(|b| b.data.get(o..o + self.stride)) { + Some(r) => r, + None => { + debug_assert!(false, "row {y} read before its band was published"); + &self.missing + } + } + } + + /// Publish band `band` copied from the rows of the whole plane `src` (same geometry); a + /// band is published once. + fn publish(&self, band: usize, src: &Plane) { + let y0 = band << self.log2; + let y1 = ((band + 1) << self.log2).min(self.rows); + let mut p = Plane::region(0, y0, self.stride, y1.saturating_sub(y0)); + let w = self.stride.min(src.stride); + for (y, out) in (y0..y1).zip(p.data.chunks_exact_mut(self.stride.max(1))) { + if let Some(r) = src.data.get(y * src.stride..y * src.stride + w) { + out[..w].copy_from_slice(r); + } + } + self.publish_owned(band, p); + } + + /// Publish band `band` as `p`, whose rows start at the band's first row (stride `stride`; + /// rows past the band are ignored). + fn publish_owned(&self, band: usize, p: Plane) { + if let Some(slot) = self.bands.get(band) + && p.stride == self.stride + { + let _ = slot.set(p); + } + } +} + +/// A frame's final samples (every in-loop filter applied) in bands of 64 luma rows, so later +/// frames can predict from the top of a reference while its bottom is still being decoded. +/// Each band is published once, before the frame's row progress says it is final. +pub struct BandFrame { + pub planes: [BandPlane; 3], + pub num_planes: usize, + pub subsampling_x: usize, + pub subsampling_y: usize, +} + +impl BandFrame { + /// Bands for the visible rows of a `width` x `height` frame stored like [`FrameBuf::new`]. + pub fn new(width: usize, height: usize, num_planes: usize, subsampling_x: usize, subsampling_y: usize) -> BandFrame { + let aw = width.div_ceil(128) * 128 + 160; + let planes = std::array::from_fn(|p| { + if p >= num_planes { + return BandPlane::new(0, 0, BAND_LOG2); + } + let (sx, sy) = if p == 0 { (0, 0) } else { (subsampling_x, subsampling_y) }; + BandPlane::new(aw >> sx, (height + sy) >> sy, BAND_LOG2 - sy as u32) + }); + BandFrame { planes, num_planes, subsampling_x, subsampling_y } + } + + /// Number of bands (of 64 luma rows). + pub fn bands(&self) -> usize { + self.planes[0].bands.len() + } + + /// Publish luma band `band` (and the chroma rows it covers) copied from `src`. + pub fn publish(&self, band: usize, src: &FrameBuf) { + for p in 0..self.num_planes { + self.planes[p].publish(band, &src.planes[p]); + } + } + + /// Publish luma band `band` from per-plane buffers starting at the band's first row. + pub fn publish_owned(&self, band: usize, planes: [Plane; 3]) { + for (p, pl) in planes.into_iter().enumerate().take(self.num_planes) { + self.planes[p].publish_owned(band, pl); + } + } +} + +/// A plane to predict from: a whole stored plane or the published bands of a reference. +#[derive(Clone, Copy)] +pub enum PlaneRef<'a> { + Whole(&'a Plane), + Bands(&'a BandPlane), +} + +impl<'a> PlaneRef<'a> { + #[inline(always)] + pub fn row(&self, y: usize) -> &'a [u16] { + match *self { + PlaneRef::Whole(p) => p.row(y), + PlaneRef::Bands(b) => b.row(y), + } + } +} + /// A motion vector (row, col) in 1/8 sample units. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Mv { diff --git a/crates/video/src/av1/decode/inter.rs b/crates/video/src/av1/decode/inter.rs index 8b40717a3..8d80e96b0 100644 --- a/crates/video/src/av1/decode/inter.rs +++ b/crates/video/src/av1/decode/inter.rs @@ -3,7 +3,7 @@ use std::sync::OnceLock; -use crate::av1::decode::frame::Plane; +use crate::av1::decode::frame::{Plane, PlaneRef}; use crate::av1::decode::mvpred::round2_signed64; use crate::av1::decode::spec_tables::{ BLOCK_8X8, BLOCK_SIZES, COMPOUND_AVERAGE, COMPOUND_DIFFWTD, COMPOUND_DISTANCE, COMPOUND_INTRA, COMPOUND_WEDGE, DIV_LUT, DIV_LUT_BITS, @@ -227,12 +227,9 @@ impl TileDecoder<'_, '_> { (start_x as i32, start_y as i32, step_x as i32, step_y as i32) } - fn ref_plane(&self, ref_idx: i32, plane: usize) -> &Plane { + fn ref_plane(&self, ref_idx: i32, plane: usize) -> PlaneRef<'_> { // A missing reference (rejected earlier for valid streams) predicts from the current frame. - match usize::try_from(ref_idx).ok().and_then(|i| self.fs.refs.get(i)).and_then(|r| r.as_ref()) { - Some(r) => &r.buf.planes[plane], - None => &self.t.cur.planes[plane], - } + self.fs.ref_samples(ref_idx, plane).unwrap_or(PlaneRef::Whole(&self.t.cur.planes[plane])) } /// Block inter prediction process (7.11.3.4) into `pred` (stride PRED_STRIDE); `tmp` holds @@ -512,12 +509,12 @@ impl TileDecoder<'_, '_> { return false; } let fs = self.fs; - let Some(r) = usize::try_from(ref_idx).ok().and_then(|i| fs.refs.get(i)).and_then(|r| r.as_ref()) else { + let Some(refp) = fs.ref_samples(ref_idx, plane) else { return false; }; let dims = self.ref_plane_dims(ref_idx, plane); let max = ((1u32 << fs.bit_depth) - 1) as u16; - copy_fullpel(&r.buf.planes[plane], dims, McBlock { x: sx, y: sy, w, h }, &mut self.t.cur.planes[plane], (x, y), max); + copy_fullpel(refp, dims, McBlock { x: sx, y: sy, w, h }, &mut self.t.cur.planes[plane], (x, y), max); true } @@ -763,7 +760,7 @@ impl TileDecoder<'_, '_> { /// Unscaled single-reference prediction at a whole-sample position: both filter phases are the /// identity and Round2(128 * Round2(128 * v, InterRound0), InterRound1) == v for every bit /// depth, so the prediction is the (clamped) reference sample. -fn copy_fullpel(refp: &Plane, (last_x, last_y): (i32, i32), src_blk: McBlock, dst: &mut Plane, (dx, dy): (usize, usize), max: u16) { +fn copy_fullpel(refp: PlaneRef, (last_x, last_y): (i32, i32), src_blk: McBlock, dst: &mut Plane, (dx, dy): (usize, usize), max: u16) { let McBlock { x, y, w, h } = src_blk; let x0 = x >> 10; let y0 = y >> 10; @@ -831,7 +828,7 @@ fn vpass(rows: &[i32], vf: &[i16; 8], out: &mut [i32], half: i32 /// Block inter prediction without reference scaling: every column / row uses the same filter /// phase, so the filters run over whole rows (bit-identical to the per-sample process). fn mc_unscaled( - refp: &Plane, + refp: PlaneRef, (last_x, last_y): (i32, i32), blk: McBlock, (hf, vf): (&[i16; 8], &[i16; 8]), @@ -982,9 +979,17 @@ mod tests { [(0, 0), (-5, -3), (7, 9), (last_x - w as i32 / 2, last_y - h as i32 / 2), (last_x + 3, last_y + 2), (-(w as i32) - 4, 3)] { let (x, y) = ((px << 10) | 32, (py << 10) | 32); - mc_unscaled(&refp, (last_x, last_y), McBlock { x, y, w, h }, (&IDENTITY_TAPS, &IDENTITY_TAPS), rnd, &mut pred, &mut tmp); + mc_unscaled( + PlaneRef::Whole(&refp), + (last_x, last_y), + McBlock { x, y, w, h }, + (&IDENTITY_TAPS, &IDENTITY_TAPS), + rnd, + &mut pred, + &mut tmp, + ); let mut dst = Plane::new(w + 3, h); - copy_fullpel(&refp, (last_x, last_y), McBlock { x, y, w, h }, &mut dst, (3, 0), max); + copy_fullpel(PlaneRef::Whole(&refp), (last_x, last_y), McBlock { x, y, w, h }, &mut dst, (3, 0), max); for i in 0..h { for j in 0..w { let want = spec_phase0(&refp, (last_x, last_y), (px, py), (j, i), (w * 3 + h) % SUBPEL_FILTERS.len(), rnd) diff --git a/crates/video/src/av1/decode/postfilter.rs b/crates/video/src/av1/decode/postfilter.rs index 6304fdfb6..aa9c2e3ea 100644 --- a/crates/video/src/av1/decode/postfilter.rs +++ b/crates/video/src/av1/decode/postfilter.rs @@ -1,7 +1,7 @@ //! In-loop post filters run by decode_frame_wrapup: loop filter (7.14), CDEF (7.15), //! super-resolution upscaling (7.16) and loop restoration (7.17). -use crate::av1::decode::frame::RowBand; +use crate::av1::decode::frame::{FrameBuf, Plane, RowBand}; use crate::av1::decode::spec_tables::{ GLOBAL_GLOBALMV, GLOBALMV, INTRA_FRAME, MAX_LOOP_FILTER, NEARESTMV, NUM_4X4_BLOCKS_HIGH, NUM_4X4_BLOCKS_WIDE, SEG_LVL_ALT_LF_Y_V, TX_HEIGHT, TX_WIDTH, @@ -48,6 +48,121 @@ pub(crate) fn apply(fs: &mut FrameState, stats: &mut DecodeStats, pool: &crate:: stats.add(Stage::Restoration, t.lap()); } +/// The in-loop filters run band by band behind reconstruction (row wavefront): each stage of a +/// band starts once the stage before has finished the band below it, which bounds what the +/// stage reads beyond the band (the loop filter changes up to 7 rows above a band and intra +/// prediction of the next superblock row reads the unfiltered row above it; CDEF reads 2 rows +/// and loop restoration 3 rows beyond a band). Bands are 64 luma rows. The result is the same +/// as running each filter over the whole frame. Super-resolution frames use [`apply`]. +/// +/// The last active stage writes each band into its own buffers, which are handed out as the +/// band's final samples without a copy. +pub(crate) struct Pipeline { + bands: Vec<(usize, usize)>, + /// Luma rows of the coded frame (mi_rows * 4). + rows: usize, + lf_on: bool, + cdef_on: bool, + lr_on: bool, + /// Bands finished by each stage. + lf: usize, + cdef: usize, + lr: usize, + pending: [Vec; 3], + /// CdefFrame when loop restoration reads it. + cdef_out: Option, +} + +/// Final bands from [`Pipeline::advance`]: (band, its samples starting at the band's first row). +pub(crate) type FinalBands = Vec<(usize, [Plane; 3])>; + +impl Pipeline { + pub fn new(fs: &FrameState, draft: bool) -> Pipeline { + let rows = fs.fh.mi_rows as usize * 4; + let n = rows.div_ceil(BAND_ROWS).max(1); + let bands = (0..n).map(|b| (b * BAND_ROWS, if b + 1 == n { usize::MAX } else { (b + 1) * BAND_ROWS })).collect(); + let lvl = fs.fh.lf.level; + let cdef_on = !draft && crate::av1::decode::cdef::active(fs); + let lr_on = fs.fh.lr.uses_lr && !draft; + let cdef_out = (cdef_on && lr_on).then(|| fs.cur.same_geometry()); + Pipeline { + bands, + rows, + lf_on: (lvl[0] != 0 || lvl[1] != 0) && !draft, + cdef_on, + lr_on, + lf: 0, + cdef: 0, + lr: 0, + pending: Default::default(), + cdef_out, + } + } + + /// Filter what luma rows [0, `recon_rows`) of reconstructed samples allow (everything once + /// they cover the frame); returns the bands whose samples became final. + pub fn advance(&mut self, fs: &mut FrameState, stats: &mut DecodeStats, pool: &crate::av1::decode::par::Pool, recon_rows: usize) -> FinalBands { + let n = self.bands.len(); + let all = recon_rows >= self.rows; + let mut out = FinalBands::new(); + let mut t = Timer::start(); + // The loop filter of a band waits for the band below it to be reconstructed. + let lf_to = if all { n } else { (recon_rows / BAND_ROWS).saturating_sub(1) }; + if lf_to > self.lf { + if self.lf_on { + loop_filter_bands(fs, pool, &self.bands, self.lf..lf_to, &mut self.pending); + } + self.lf = lf_to; + } + stats.add(Stage::LoopFilter, t.lap()); + let cdef_to = if all { n } else { self.lf.saturating_sub(1) }; + if cdef_to > self.cdef { + let r = &self.bands[self.cdef..cdef_to]; + if self.cdef_on { + if let Some(cdef) = &mut self.cdef_out { + cdef.copy_rows_from(&fs.cur, r[0].0, r[r.len() - 1].1); + crate::av1::decode::cdef::filter_bands(fs, pool, cdef.row_bands(r), r); + } else { + let mut own: Vec<[Plane; 3]> = r.iter().map(|&(a, b)| fs.cur.rows_copy(a, b)).collect(); + crate::av1::decode::cdef::filter_bands(fs, pool, own_bands(&mut own), r); + out.extend((self.cdef..cdef_to).zip(own)); + } + } else if !self.lr_on { + // The loop filter is the last stage: the band is final once the band below it + // is filtered. + out.extend((self.cdef..cdef_to).zip(r.iter().map(|&(a, b)| fs.cur.rows_copy(a, b)))); + } + self.cdef = cdef_to; + } + stats.add(Stage::Cdef, t.lap()); + let lr_to = if all { n } else { self.cdef.saturating_sub(1) }; + if self.lr_on && lr_to > self.lr { + let r = &self.bands[self.lr..lr_to]; + let cdef = self.cdef_out.as_ref().unwrap_or(&fs.cur); + let mut own: Vec<[Plane; 3]> = r.iter().map(|&(a, b)| cdef.rows_copy(a, b)).collect(); + crate::av1::decode::restoration::restore_bands(fs, &fs.cur, cdef, own_bands(&mut own), pool, r); + out.extend((self.lr..lr_to).zip(own)); + self.lr = lr_to; + } + stats.add(Stage::Restoration, t.lap()); + out + } +} + +/// Row bands over per-band buffers made by [`FrameBuf::rows_copy`]. +fn own_bands(own: &mut [[Plane; 3]]) -> Vec<[RowBand<'_>; 3]> { + fn band(p: &mut Plane) -> RowBand<'_> { + let (stride, y0) = (p.stride.max(1), p.oy); + RowBand { data: p.data.as_mut_slice(), stride, y0 } + } + own.iter_mut() + .map(|planes| { + let [a, b, c] = planes; + [band(a), band(b), band(c)] + }) + .collect() +} + // --------------------------------------------------------------------------------------------- // Loop filter (7.14) @@ -69,23 +184,40 @@ const LF_MARGIN: usize = 8; /// written back; the band above never touches them. fn loop_filter(fs: &mut FrameState, pool: &crate::av1::decode::par::Pool) { let luma = bands(pool, fs.fh.mi_rows as usize * 4); + loop_filter_bands(fs, pool, &luma, 0..luma.len(), &mut Default::default()); +} + +/// The loop filter on bands `range` of `all` (the frame's bands). The bands above the range +/// are filtered already: `pending` holds the unfiltered rows above the first band of the range +/// (empty for band 0), saved before the band above was filtered, and is set to those of the +/// band after the range. +fn loop_filter_bands( + fs: &mut FrameState, + pool: &crate::av1::decode::par::Pool, + all: &[(usize, usize)], + range: std::ops::Range, + pending: &mut [Vec; 3], +) { + let Some(luma) = all.get(range.clone()) else { return }; let planes: Vec = (0..fs.num_planes).filter(|&p| p == 0 || fs.fh.lf.level[1 + p] != 0).collect(); let mut cur = std::mem::take(&mut fs.cur); let f: &FrameState = fs; - // Unfiltered copies of the rows above each band but the first. - let margins: Vec<[Vec; 3]> = luma - .iter() - .map(|&(start, _)| { - std::array::from_fn(|p| { - let sub_y = if p == 0 { 0 } else { f.ssy }; - let pl = &cur.planes[p]; - let (y0, y1) = ((start.saturating_sub(LF_MARGIN)) >> sub_y, start >> sub_y); - let rows = pl.data.get(y0 * pl.stride..y1 * pl.stride); - if start == 0 || !planes.contains(&p) { Vec::new() } else { rows.map(<[u16]>::to_vec).unwrap_or_default() } - }) + // Unfiltered copies of the rows above a band (none above the first). + let margin = |cur: &crate::av1::decode::frame::FrameBuf, start: usize| -> [Vec; 3] { + std::array::from_fn(|p| { + let sub_y = if p == 0 { 0 } else { f.ssy }; + let pl = &cur.planes[p]; + let (y0, y1) = ((start.saturating_sub(LF_MARGIN)) >> sub_y, start >> sub_y); + let rows = pl.data.get(y0 * pl.stride..y1 * pl.stride); + if start == 0 || !planes.contains(&p) { Vec::new() } else { rows.map(<[u16]>::to_vec).unwrap_or_default() } }) - .collect(); - let mut bands: Vec<([RowBand; 3], [Vec; 3])> = cur.row_bands(&luma).into_iter().zip(margins).collect(); + }; + let margins: Vec<[Vec; 3]> = + luma.iter().enumerate().map(|(i, &(start, _))| if i == 0 { std::mem::take(pending) } else { margin(&cur, start) }).collect(); + if let Some(&(next, _)) = all.get(range.end) { + *pending = margin(&cur, next); + } + let mut bands: Vec<([RowBand; 3], [Vec; 3])> = cur.row_bands(luma).into_iter().zip(margins).collect(); let changed = pool.map_mut(&mut bands, |b, (band, margin)| { let mut changed: [Vec<(usize, u16)>; 3] = Default::default(); for &p in &planes { diff --git a/crates/video/src/av1/decode/restoration.rs b/crates/video/src/av1/decode/restoration.rs index efc5a751f..d252f7b06 100644 --- a/crates/video/src/av1/decode/restoration.rs +++ b/crates/video/src/av1/decode/restoration.rs @@ -70,10 +70,16 @@ struct LrPlane<'a> { /// Bands of 64 luma rows are restored in parallel: every unit reads only the two input frames /// and writes only its own samples. pub(crate) fn loop_restoration(fs: &FrameState, cur: &FrameBuf, cdef: &FrameBuf, pool: &Pool) -> FrameBuf { - let fh = &fs.fh; let mut lr = cdef.clone(); - let ranges = bands(pool, fh.frame_height as usize); - let mut planes = lr.row_bands(&ranges); + let ranges = bands(pool, fs.fh.frame_height as usize); + restore_bands(fs, cur, cdef, lr.row_bands(&ranges), pool, &ranges); + lr +} + +/// Restore the bands `planes` covering luma rows `ranges`, which hold UpscaledCdefFrame; reads +/// both inputs up to 3 rows beyond each band. +pub(crate) fn restore_bands(fs: &FrameState, cur: &FrameBuf, cdef: &FrameBuf, mut planes: Vec<[RowBand; 3]>, pool: &Pool, ranges: &[(usize, usize)]) { + let fh = &fs.fh; pool.map_mut(&mut planes, |b, band| { let (start, end) = ranges[b]; let mut scratch = Scratch::default(); @@ -100,8 +106,6 @@ pub(crate) fn loop_restoration(fs: &FrameState, cur: &FrameBuf, cdef: &FrameBuf, p.restore(out, start >> sub_y, end >> sub_y, &mut scratch); } }); - drop(planes); - lr } /// Row buffers reused across stripes. diff --git a/crates/video/src/av1/decode/state.rs b/crates/video/src/av1/decode/state.rs index 4c4806f16..f498a7f05 100644 --- a/crates/video/src/av1/decode/state.rs +++ b/crates/video/src/av1/decode/state.rs @@ -6,8 +6,8 @@ //! with several, each tile decodes into private buffers covering its area (tiles never read //! outside themselves), which are then copied into the frame. -use crate::av1::decode::decoder::RefFrame; -use crate::av1::decode::frame::{FrameBuf, MiInfo}; +use crate::av1::decode::decoder::{Parsed, RefFrame}; +use crate::av1::decode::frame::{BandFrame, FrameBuf, MiInfo, PlaneRef}; use crate::av1::decode::header::{FrameHeader, RefInfo, SequenceHeader}; use crate::av1::decode::spec_tables::{DEFAULT_INTRA_FRAME_Y_MODE_CDF, NUM_REF_FRAMES, RESTORE_NONE, SUBSAMPLED_SIZE}; use std::ops::{Deref, DerefMut}; @@ -26,6 +26,11 @@ pub(crate) struct FrameShared { pub cdef_cols: usize, /// Reference slots (FrameStore and saved state) used by this frame. pub refs: [Option>; NUM_REF_FRAMES], + /// Parse results (CDFs, segment ids, saved motion vectors) of the same slots. + pub parsed: [Option>; NUM_REF_FRAMES], + /// The published bands of references that are still being decoded (row wavefront): read + /// only below the row progress that was waited for. + pub ref_rows: [Option>; NUM_REF_FRAMES], pub ref_info: [RefInfo; NUM_REF_FRAMES], /// MotionFieldMvs[ ref ][ y8 * w8 + x8 ] (7.9); empty when unused. pub motion_field: [Vec<[i32; 2]>; 8], @@ -34,6 +39,16 @@ pub(crate) struct FrameShared { } impl FrameShared { + /// The samples of reference slot `ref_idx` to predict from (None for a missing reference). + #[inline] + pub fn ref_samples(&self, ref_idx: i32, plane: usize) -> Option> { + let i = usize::try_from(ref_idx).ok()?; + if let Some(b) = self.ref_rows.get(i)?.as_ref() { + return b.planes.get(plane).map(PlaneRef::Bands); + } + self.refs.get(i)?.as_ref().map(|r| r.plane(plane)) + } + pub fn plane_residual_size(&self, subsize: usize, plane: usize) -> usize { let sx = if plane > 0 { self.ssx } else { 0 }; let sy = if plane > 0 { self.ssy } else { 0 }; @@ -210,6 +225,8 @@ impl FrameState { lr_unit_cols, cdef_cols, refs: Default::default(), + parsed: Default::default(), + ref_rows: Default::default(), ref_info: Default::default(), motion_field: Default::default(), prev_segment_ids: vec![0; mi_cols * mi_rows], @@ -283,6 +300,14 @@ impl FrameState { pub fn merge_tile_state(&mut self, t: &TileState) { for p in 0..self.num_planes { t.cur.planes[p].copy_into(&mut self.cur.planes[p]); + } + self.merge_tile_modes(t); + } + + /// Copy a tile's private buffers except the samples (after parsing, before reconstruction) + /// into the frame. + pub fn merge_tile_modes(&mut self, t: &TileState) { + for p in 0..self.num_planes { t.lf_tx_size[p].copy_into(&mut self.lf_tx_size[p]); for &u in &t.lr_written[p] { self.lr.lr_type[p][u] = t.lr.lr_type[p][u]; diff --git a/crates/video/src/av1/decode/tile.rs b/crates/video/src/av1/decode/tile.rs index 16d59ed3a..2572f9d21 100644 --- a/crates/video/src/av1/decode/tile.rs +++ b/crates/video/src/av1/decode/tile.rs @@ -94,6 +94,191 @@ pub(crate) struct Block { pub local_warp_params: [i32; 6], } +/// What a tile decoder does with the blocks it visits. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Pass { + /// Read the symbols and reconstruct each block right away (single-threaded decoding). + Full, + /// Read the symbols only, recording what reconstruction needs in a [`TileRecord`]. + Parse, + /// Reconstruct from a [`TileRecord`], reading no symbols. + Reconstruct, +} + +/// The per-block values reconstruction needs beyond the mode info (which is final after +/// parsing): the block variables as parsed, its quantizer index and the warp samples / palette +/// color maps when used. +#[derive(Clone)] +pub(crate) struct BlockRecord { + b: Block, + current_q_index: i32, + warp_samples: Option>, + color_maps: Option, Vec)>>, +} + +/// A parsed tile: its blocks in decoding order, how many of them each superblock holds and the +/// coefficients of every coded transform block as a stream of +/// `eob, tx_type, count, (position, value) * count` (only non-zero values). +#[derive(Default)] +pub(crate) struct TileRecord { + blocks: Vec, + sb_blocks: Vec, + coeffs: Vec, + /// Read positions while reconstructing. + next_block: usize, + next_coeff: usize, + next_sb: usize, + next_sb_row: usize, + /// Bytes recorded and the most allowed. + pub bytes: usize, + pub limit: usize, + /// The decoder-wide budget the recorded bytes are reserved from, and how much is reserved. + pub budget: Option>, + reserved: usize, +} + +impl Drop for TileRecord { + fn drop(&mut self) { + if let Some(b) = &self.budget { + b.release(self.reserved); + } + } +} + +/// The parse record bytes all frames of a decoder may hold at once (frames in flight decode in +/// one pass once it is used up). +pub(crate) struct RecordBudget { + used: std::sync::atomic::AtomicUsize, + max: usize, + /// Most bytes ever reserved at once (tests). + #[cfg(test)] + pub peak: std::sync::atomic::AtomicUsize, +} + +/// Bytes reserved from a [`RecordBudget`] at a time. +const RESERVE_STEP: usize = 1 << 20; + +impl RecordBudget { + pub fn new(max: usize) -> RecordBudget { + RecordBudget { + used: Default::default(), + max, + #[cfg(test)] + peak: Default::default(), + } + } + + /// Reserve `n` bytes; false (nothing reserved) if that would go over the budget. + fn reserve(&self, n: usize) -> bool { + use std::sync::atomic::Ordering; + let ok = self.used.try_update(Ordering::AcqRel, Ordering::Acquire, |u| u.checked_add(n).filter(|&v| v <= self.max)).is_ok(); + #[cfg(test)] + if ok { + self.peak.fetch_max(self.used.load(Ordering::Acquire), Ordering::AcqRel); + } + ok + } + + fn release(&self, n: usize) { + self.used.fetch_sub(n, std::sync::atomic::Ordering::AcqRel); + } + + /// Bytes reserved now (tests). + #[cfg(test)] + pub fn used(&self) -> usize { + self.used.load(std::sync::atomic::Ordering::Acquire) + } +} + +/// The motion of a recorded block (what a reference row wait depends on). +pub(crate) struct BlockMotion { + pub mi_row: usize, + pub bh4: usize, + /// Inter prediction from reference frames (not intra block copy). + pub inter: bool, + pub ref_frame: [i8; 2], + /// Mv[ list ] (row, col) in 1/8 samples. + pub mv: [[i32; 2]; 2], + pub motion_mode: u8, + pub y_mode: usize, +} + +impl TileRecord { + /// Whether recording stopped at [`TileRecord::limit`] (the record is unusable). + pub fn over_limit(&self) -> bool { + self.bytes > self.limit + } + + /// Account for `n` more recorded bytes; false once over the limit (nothing more is kept). + fn grow(&mut self, n: usize) -> bool { + self.bytes = self.bytes.saturating_add(n); + if self.bytes > self.limit { + return false; + } + if self.bytes > self.reserved + && let Some(b) = &self.budget + { + let step = (self.bytes - self.reserved).max(RESERVE_STEP); + if !b.reserve(step) { + // The decoder-wide budget is used up: this frame is decoded in one pass. + self.limit = 0; + return false; + } + self.reserved += step; + } + true + } + /// The recorded blocks of superblock rows [first, end), for a tile `sbs_per_row` superblocks wide. + pub fn row_blocks(&self, sbs_per_row: usize, first: usize, end: usize) -> impl Iterator + '_ { + let start: usize = self.sb_blocks.iter().take(first * sbs_per_row).map(|&n| n as usize).sum(); + let count: usize = self.sb_blocks.iter().skip(first * sbs_per_row).take((end - first) * sbs_per_row).map(|&n| n as usize).sum(); + self.blocks.iter().skip(start).take(count).map(|r| BlockMotion { + mi_row: r.b.mi_row, + bh4: r.b.bh4, + inter: r.b.is_inter && !r.b.use_intrabc, + ref_frame: r.b.ref_frame, + mv: r.b.mv_i, + motion_mode: r.b.motion_mode, + y_mode: r.b.y_mode, + }) + } + + fn next_coeff(&mut self) -> Result { + let v = *self.coeffs.get(self.next_coeff).ok_or(crate::av1::decode::Error::Invalid("coefficient record exhausted"))?; + self.next_coeff += 1; + Ok(v) + } +} + +/// The work buffers of a [`TileDecoder`] (`quant` all zero between transform blocks). +pub(crate) struct Buffers { + quant: Vec, + dequant: Vec, + residual: Vec, + color_map_y: Vec, + color_map_uv: Vec, + pred_buf: [Vec; 2], + mask: Vec, + mc_tmp: Vec, + levels: Vec, +} + +impl Buffers { + pub fn new() -> Buffers { + Buffers { + quant: vec![0; 1024], + dequant: vec![0; 64 * 64], + residual: vec![0; 64 * 64], + color_map_y: vec![0; 64 * 64], + color_map_uv: vec![0; 64 * 64], + pred_buf: [vec![0; 128 * 128], vec![0; 128 * 128]], + mask: vec![0; 128 * 128], + mc_tmp: vec![0; (2 * 128 + 8) * 128], + levels: vec![0; (32 + TX_PAD) * (32 + TX_PAD)], + } + } +} + /// Decoder for one tile. pub(crate) struct TileDecoder<'a, 'f> { pub fs: &'f FrameShared, @@ -128,6 +313,9 @@ pub(crate) struct TileDecoder<'a, 'f> { pub mc_tmp: Vec, /// Coefficient levels of the current transform block, padded (see TX_PAD). levels: Vec, + pub pass: Pass, + /// Written by [`Pass::Parse`], read by [`Pass::Reconstruct`]. + pub record: TileRecord, } const SB_MAX: usize = 32; // superblock size in 4x4 units (128 / 4) @@ -141,6 +329,21 @@ fn block_height(bs: usize) -> usize { impl<'a, 'f> TileDecoder<'a, 'f> { pub fn new(fs: &'f FrameShared, t: &'f mut TileState, data: &'a [u8], cdf: Box, tile_row: usize, tile_col: usize) -> Self { + Self::with_buffers(fs, t, data, cdf, tile_row, tile_col, Buffers::new()) + } + + /// [`TileDecoder::new`] reusing the work buffers of an earlier decoder of the same frame + /// (see [`TileDecoder::into_buffers`]). + pub fn with_buffers( + fs: &'f FrameShared, + t: &'f mut TileState, + data: &'a [u8], + cdf: Box, + tile_row: usize, + tile_col: usize, + bufs: Buffers, + ) -> Self { + let Buffers { quant, dequant, residual, color_map_y, color_map_uv, pred_buf, mask, mc_tmp, levels } = bufs; let ti = &fs.fh.tile_info; let (rs, re) = (ti.mi_row_starts[tile_row] as usize, ti.mi_row_starts[tile_row + 1] as usize); let (cs, ce) = (ti.mi_col_starts[tile_col] as usize, ti.mi_col_starts[tile_col + 1] as usize); @@ -164,19 +367,27 @@ impl<'a, 'f> TileDecoder<'a, 'f> { b: Block::default(), mvs: Default::default(), nb: Default::default(), - quant: vec![0; 1024], - dequant: vec![0; 64 * 64], - residual: vec![0; 64 * 64], - color_map_y: vec![0; 64 * 64], - color_map_uv: vec![0; 64 * 64], + quant, + dequant, + residual, + color_map_y, + color_map_uv, plane_tx_type: 0, - pred_buf: [vec![0; 128 * 128], vec![0; 128 * 128]], - mask: vec![0; 128 * 128], - mc_tmp: vec![0; (2 * 128 + 8) * 128], - levels: vec![0; (32 + TX_PAD) * (32 + TX_PAD)], + pred_buf, + mask, + mc_tmp, + levels, + pass: Pass::Full, + record: TileRecord::default(), } } + /// The work buffers and CDFs, for [`TileDecoder::with_buffers`]. + pub fn into_buffers(self) -> (Buffers, Box) { + let TileDecoder { quant, dequant, residual, color_map_y, color_map_uv, pred_buf, mask, mc_tmp, levels, cdf, .. } = self; + (Buffers { quant, dequant, residual, color_map_y, color_map_uv, pred_buf, mask, mc_tmp, levels }, cdf) + } + fn seq(&self) -> &SequenceHeader { &self.fs.seq } @@ -189,8 +400,11 @@ impl<'a, 'f> TileDecoder<'a, 'f> { c >= self.mi_col_start as isize && c < self.mi_col_end as isize && r >= self.mi_row_start as isize && r < self.mi_row_end as isize } - /// decode_tile( ) + /// decode_tile( ), or its reconstruction from [`TileDecoder::record`] in [`Pass::Reconstruct`]. pub fn decode_tile(&mut self) -> Result<()> { + if self.pass == Pass::Reconstruct { + return self.reconstruct_tile(); + } // clear_above_context( ) let t = &mut *self.t; for p in 0..3 { @@ -223,7 +437,11 @@ impl<'a, 'f> TileDecoder<'a, 'f> { self.clear_cdef(r, c); self.clear_block_decoded_flags(r, c, sb4); self.read_lr(r, c, sb_size); + let before = self.record.blocks.len(); self.decode_partition(r, c, sb_size)?; + if self.pass == Pass::Parse { + self.record.sb_blocks.push((self.record.blocks.len() - before) as u32); + } c += sb4; } r += sb4; @@ -231,6 +449,76 @@ impl<'a, 'f> TileDecoder<'a, 'f> { Ok(()) } + /// The reconstruction half of decode_tile( ): the superblocks in the same order, each block + /// predicted and reconstructed from its record. + fn reconstruct_tile(&mut self) -> Result<()> { + self.reconstruct_sb_rows(usize::MAX) + } + + /// Reconstruct the next `rows` superblock rows of the tile (the record keeps the position). + pub fn reconstruct_sb_rows(&mut self, rows: usize) -> Result<()> { + let sb4 = if self.seq().use_128x128_superblock { 32 } else { 16 }; + let mut r = self.mi_row_start + self.record.next_sb_row * sb4; + let mut done = 0; + while r < self.mi_row_end && done < rows { + let mut c = self.mi_col_start; + while c < self.mi_col_end { + self.clear_block_decoded_flags(r, c, sb4); + let n = *self.record.sb_blocks.get(self.record.next_sb).ok_or(crate::av1::decode::Error::Invalid("block record exhausted"))?; + self.record.next_sb += 1; + for _ in 0..n { + self.reconstruct_block()?; + } + c += sb4; + } + r += sb4; + done += 1; + self.record.next_sb_row += 1; + } + Ok(()) + } + + fn reconstruct_block(&mut self) -> Result<()> { + let rec = self.record.blocks.get(self.record.next_block).ok_or(crate::av1::decode::Error::Invalid("block record exhausted"))?; + self.record.next_block += 1; + self.b = rec.b.clone(); + self.current_q_index = rec.current_q_index; + if let Some(w) = &rec.warp_samples { + self.mvs.num_samples = w.0; + self.mvs.cand_list = w.1; + } + if let Some(maps) = &rec.color_maps { + if let Some(d) = self.color_map_y.get_mut(..maps.0.len()) { + d.copy_from_slice(&maps.0); + } + if let Some(d) = self.color_map_uv.get_mut(..maps.1.len()) { + d.copy_from_slice(&maps.1); + } + } + self.compute_prediction()?; + self.residual() + } + + /// Records the block for [`Pass::Reconstruct`] (its variables as parsed). + fn record_block(&mut self) { + let b = &self.b; + // The rows of the color maps (stride 64) the block's palette prediction reads. + let map_rows = |n: usize, h: usize| if n > 0 { (h + 2).min(64) * 64 } else { 0 }; + let rows_y = map_rows(b.palette_size_y, block_height(b.mi_size)); + let rows_uv = map_rows(b.palette_size_uv, block_height(b.mi_size) >> self.fs.ssy); + let size = std::mem::size_of::() + + rows_y + + rows_uv + + if b.motion_mode as usize == crate::av1::decode::spec_tables::LOCALWARP { 160 } else { 0 }; + if !self.record.grow(size) { + return; + } + let warp_samples = + (b.motion_mode as usize == crate::av1::decode::spec_tables::LOCALWARP).then(|| Box::new((self.mvs.num_samples, self.mvs.cand_list))); + let color_maps = (rows_y + rows_uv > 0).then(|| Box::new((self.color_map_y[..rows_y].to_vec(), self.color_map_uv[..rows_uv].to_vec()))); + self.record.blocks.push(BlockRecord { b: b.clone(), current_q_index: self.current_q_index, warp_samples, color_maps }); + } + fn clear_cdef(&mut self, r: usize, c: usize) { let t = &mut *self.t; t.set_cdef_idx(r, c, -1); @@ -461,7 +749,11 @@ impl<'a, 'f> TileDecoder<'a, 'f> { } } } - self.compute_prediction()?; + if self.pass == Pass::Parse { + self.record_block(); + } else { + self.compute_prediction()?; + } self.residual()?; let b = &self.b; let delta_lf = self.delta_lf; diff --git a/crates/video/src/av1/decode/tile/coeffs.rs b/crates/video/src/av1/decode/tile/coeffs.rs index 6a704f8ac..df358e68d 100644 --- a/crates/video/src/av1/decode/tile/coeffs.rs +++ b/crates/video/src/av1/decode/tile/coeffs.rs @@ -459,6 +459,58 @@ impl<'a, 'f> TileDecoder<'a, 'f> { } } + /// Moves the coefficients `coeffs` left in `quant` into the record (leaving `quant` zero, as + /// reconstruction does). + pub(super) fn record_coeffs(&mut self, eob: usize, tx_sz: usize) { + let scan = self.get_scan(tx_sz); + let scan = scan.get(..eob).unwrap_or(scan); + if !self.record.grow(4 * (3 + 2 * scan.len())) { + // Over the limit: the record is dropped (the frame is decoded again in one pass); + // `quant` must still be left zero. + for &pos in scan { + if let Some(q) = self.quant.get_mut(pos as usize) { + *q = 0; + } + } + return; + } + let rec = &mut self.record.coeffs; + rec.push(eob as i32); + if eob == 0 { + return; + } + rec.push(self.plane_tx_type as i32); + let count_at = rec.len(); + rec.push(0); + let mut count = 0; + for &pos in scan { + let v = std::mem::take(&mut self.quant[pos as usize]); + if v != 0 { + rec.push(pos as i32); + rec.push(v); + count += 1; + } + } + rec[count_at] = count; + } + + /// The next transform block's coefficients from the record into `quant` (and its type); + /// returns its eob. + pub(super) fn replay_coeffs(&mut self) -> crate::av1::decode::Result { + let eob = self.record.next_coeff()?; + if eob <= 0 { + return Ok(0); + } + self.plane_tx_type = usize::try_from(self.record.next_coeff()?).map_err(|_| crate::av1::decode::Error::Invalid("coefficient record"))?; + let count = self.record.next_coeff()?; + for _ in 0..count { + let pos = self.record.next_coeff()? as usize; + let v = self.record.next_coeff()?; + *self.quant.get_mut(pos).ok_or(crate::av1::decode::Error::Invalid("coefficient record"))? = v; + } + Ok(eob as usize) + } + /// Reconstruct process (7.12.3). pub(super) fn reconstruct(&mut self, plane: usize, x: usize, y: usize, tx_sz: usize, dc_only: bool) { // dqDenom (7.12.3) is 1, 2 or 4 and the dividend is non-negative. diff --git a/crates/video/src/av1/decode/tile/predict.rs b/crates/video/src/av1/decode/tile/predict.rs index b1a53f399..244be62c6 100644 --- a/crates/video/src/av1/decode/tile/predict.rs +++ b/crates/video/src/av1/decode/tile/predict.rs @@ -213,7 +213,8 @@ impl<'a, 'f> TileDecoder<'a, 'f> { if start_x >= max_x || start_y >= max_y { return Ok(()); } - if !self.b.is_inter { + let parse_only = self.pass == super::Pass::Parse; + if !self.b.is_inter && !parse_only { let palette = if plane == 0 { self.b.palette_size_y } else { self.b.palette_size_uv }; if palette > 0 { self.predict_palette(plane, start_x, start_y, x, y, tx_sz); @@ -266,9 +267,23 @@ impl<'a, 'f> TileDecoder<'a, 'f> { } } if !self.b.skip { - let eob = self.coeffs(plane, start_x, start_y, tx_sz); - if eob > 0 { - self.reconstruct(plane, start_x, start_y, tx_sz, eob == 1); + match self.pass { + super::Pass::Full => { + let eob = self.coeffs(plane, start_x, start_y, tx_sz); + if eob > 0 { + self.reconstruct(plane, start_x, start_y, tx_sz, eob == 1); + } + } + super::Pass::Parse => { + let eob = self.coeffs(plane, start_x, start_y, tx_sz); + self.record_coeffs(eob, tx_sz); + } + super::Pass::Reconstruct => { + let eob = self.replay_coeffs()?; + if eob > 0 { + self.reconstruct(plane, start_x, start_y, tx_sz, eob == 1); + } + } } } for i in 0..step_y { diff --git a/crates/video/tests/av1_decode/fuzz_hostile.rs b/crates/video/tests/av1_decode/fuzz_hostile.rs index 05dbbe126..31cb66073 100644 --- a/crates/video/tests/av1_decode/fuzz_hostile.rs +++ b/crates/video/tests/av1_decode/fuzz_hostile.rs @@ -1,7 +1,6 @@ //! Hostile-input robustness: truncation, header-region sweeps and random mutation of small //! ffmpeg-generated AV1 streams (frame by frame) must never panic or run away. Skips without ffmpeg. -use std::panic::{AssertUnwindSafe, catch_unwind}; use std::process::{Command, Stdio}; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -20,8 +19,15 @@ impl Rng { } } -/// (name, encoder args, pix_fmt) -const SEEDS: &[(&str, &str, &str)] = &[("av1_fz_default", "-c:v libsvtav1 -g 4", "yuv420p"), ("av1_fz_10bit", "-c:v libsvtav1 -g 6", "yuv420p10le")]; +// Seeds are at least 64x64: SVT-AV1 before 3.0 (the Ubuntu runners have 2.3) refuses a source under 64 lines. +/// (name, encoder args, pix_fmt, size, decoder thread counts) +const SEEDS: &[(&str, &str, &str, &str, &[usize])] = &[ + ("av1_fz_default", "-c:v libsvtav1 -g 4", "yuv420p", "64x64", &[1, 3]), + ("av1_fz_10bit", "-c:v libsvtav1 -g 6", "yuv420p10le", "64x64", &[1, 3]), + // Several superblock rows, so corrupt references meet frames already predicting from their + // top rows (row wavefront with frame threads). + ("av1_fz_rows", "-c:v libsvtav1 -g 6", "yuv420p", "64x136", &[1, 8]), +]; fn ivf_frames(data: &[u8]) -> Vec> { let mut out = Vec::new(); @@ -37,14 +43,13 @@ fn ivf_frames(data: &[u8]) -> Vec> { out } -// Seeds are 64x64: SVT-AV1 before 3.0 (the Ubuntu runners have 2.3) refuses a source under 64 lines. -fn make(ff: &std::path::Path, name: &str, args: &str, pix: &str) -> Option>> { +fn make(ff: &std::path::Path, name: &str, args: &str, pix: &str, size: &str) -> Option>> { let out = craft_media_testkit::fixtures_dir("av1").join(format!("{name}.ivf")); let p = craft_media_testkit::fixtures::generate(&out, |tmp| { let a: Vec<&str> = args.split_whitespace().collect(); matches!( Command::new(ff) - .args(["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=64x64:rate=25", "-frames:v", "6", "-pix_fmt", pix]) + .args(["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i", &format!("testsrc2=size={size}:rate=25"), "-frames:v", "6", "-pix_fmt", pix]) .args(a) .args(["-f", "ivf"]) .arg(tmp) @@ -69,20 +74,29 @@ fn count_panics() { }); } -fn run_all(frames: &[Vec], label: &str) { +fn run_all(frames: &[Vec], threads: &[usize], label: &str) { craft_media_testkit::set_progress(label); count_panics(); let before = PANICS.load(Ordering::SeqCst); - let res = catch_unwind(AssertUnwindSafe(|| { - for threads in [1, 3] { - let mut dec = Decoder::with_threads(threads); - for (i, f) in frames.iter().enumerate() { - let _ = dec.decode_pts(f, i as i64); - } - let _ = dec.flush_result(); - } - })); - assert!(res.is_ok() && PANICS.load(Ordering::SeqCst) == before, "panic: {label}"); + // Every thread count decodes the stream at the same time, each on a thread of its own. + let ok = std::thread::scope(|s| { + let runs: Vec<_> = threads + .iter() + .map(|&threads| { + s.spawn(move || { + let mut dec = Decoder::with_threads(threads); + for (i, f) in frames.iter().enumerate() { + let _ = dec.decode_pts(f, i as i64); + } + let _ = dec.flush_result(); + }) + }) + .collect(); + // Join every run (no short cut), then check them all. + let joined: Vec = runs.into_iter().map(|r| r.join().is_ok()).collect(); + joined.into_iter().all(|ok| ok) + }); + assert!(ok && PANICS.load(Ordering::SeqCst) == before, "panic: {label}"); } /// Random-mutation rounds per seed (raise with FILMCRAFT_FUZZ_ITERS for a long hunt). @@ -95,17 +109,23 @@ const DEADLINE_SECS: u64 = 600; #[test] fn hostile_streams_never_panic() { - craft_media_testkit::with_deadline(DEADLINE_SECS, sweep); + craft_media_testkit::with_deadline(DEADLINE_SECS, || sweep(&SEEDS[..2])); } -fn sweep() { +/// The seed with several superblock rows, in a test of its own so it runs beside the others. +#[test] +fn hostile_streams_with_superblock_rows_never_panic() { + craft_media_testkit::with_deadline(DEADLINE_SECS, || sweep(&SEEDS[2..])); +} + +fn sweep(seeds: &[(&str, &str, &str, &str, &[usize])]) { let Some(ff) = craft_media_testkit::ffmpeg_or_skip("AV1 fuzz") else { return }; - for &(name, args, pix) in SEEDS { + for &(name, args, pix, size, threads) in seeds { if !craft_media_testkit::ffmpeg_has_encoder(&ff, "libsvtav1") { craft_media_testkit::skip_test("AV1 fuzz", &format!("this ffmpeg has no libsvtav1 encoder (seed {name})")); continue; } - let Some(seed) = make(&ff, name, args, pix) else { + let Some(seed) = make(&ff, name, args, pix, size) else { panic!("ffmpeg has libsvtav1 but could not encode the {name} seed"); }; if seed.is_empty() { @@ -118,7 +138,7 @@ fn sweep() { for n in (0..len).step_by((len / 200).max(1)) { let mut d = seed.clone(); d[fi].truncate(n); - run_all(&d, &format!("{name} frame {fi} truncate {n}")); + run_all(&d, threads, &format!("{name} frame {fi} truncate {n}")); } } // header region of every frame: every byte to a few values, every bit @@ -127,12 +147,12 @@ fn sweep() { for v in [0u8, 0xff, 0x80, 0x01, 0x7f] { let mut d = seed.clone(); d[fi][p] = v; - run_all(&d, &format!("{name} frame {fi} byte {p}={v:#x}")); + run_all(&d, threads, &format!("{name} frame {fi} byte {p}={v:#x}")); } for b in 0..8 { let mut d = seed.clone(); d[fi][p] ^= 1 << b; - run_all(&d, &format!("{name} frame {fi} flip {p}.{b}")); + run_all(&d, threads, &format!("{name} frame {fi} flip {p}.{b}")); } } } @@ -151,7 +171,7 @@ fn sweep() { d[fi][p] = rng.next() as u8; } } - run_all(&d, &format!("{name} random {i}")); + run_all(&d, threads, &format!("{name} random {i}")); } } } diff --git a/crates/video/tests/av1_decode/main.rs b/crates/video/tests/av1_decode/main.rs index 50c3939f6..76a5adfcf 100644 --- a/crates/video/tests/av1_decode/main.rs +++ b/crates/video/tests/av1_decode/main.rs @@ -9,3 +9,4 @@ mod hostile_dims; mod oracle_inter; mod oracle_intra; mod perf; +mod wavefront; diff --git a/crates/video/tests/av1_decode/wavefront.rs b/crates/video/tests/av1_decode/wavefront.rs new file mode 100644 index 000000000..725b02544 --- /dev/null +++ b/crates/video/tests/av1_decode/wavefront.rs @@ -0,0 +1,93 @@ +//! Stress tests of the frame threading (parse / reconstruct split and the row wavefront across +//! frames): every thread count gives the single-thread pictures, run after run, and dropping +//! or flushing a busy decoder never hangs. A hang fails the test through the deadline. + +use crate::common; +use common::*; +use craft_video::av1::decode::{Decoder, Picture}; + +/// A GOP with many superblock rows (the wavefront has rows to overlap), hierarchical +/// references and motion reaching across rows. +fn spec() -> Spec { + Spec::new("wavefront_640x480", "testsrc2=s=640x480:r=25,rotate=a=t*0.5:c=black", 24, "yuv420p", &["-preset", "8", "-crf", "38"]) +} + +/// Seconds a test may take before it counts as a hang (override: FILMCRAFT_HOSTILE_TIMEOUT_SECS). +const DEADLINE_SECS: u64 = 300; + +fn decode(tus: &[Vec], threads: usize) -> Vec { + let mut dec = Decoder::with_threads(threads); + let mut pics = Vec::new(); + for (i, tu) in tus.iter().enumerate() { + pics.extend(dec.decode_pts(tu, i as i64).unwrap_or_else(|e| panic!("threads {threads}, unit {i}: {e}"))); + } + pics.extend(dec.flush_result().unwrap_or_else(|e| panic!("threads {threads}, flush: {e}"))); + pics +} + +#[test] +fn every_thread_count_gives_the_single_thread_pictures_repeatedly() { + let Some(ff) = ffmpeg() else { return }; + let tus = ivf_frames(&make(&ff, &spec())); + craft_media_testkit::with_deadline(DEADLINE_SECS, move || { + let want = decode(&tus, 1); + assert_eq!(want.len(), 24); + for threads in [2, 3, 4, 5, 8, 16] { + for round in 0..4 { + assert!(decode(&tus, threads) == want, "threads {threads}, round {round}: pictures differ"); + } + } + }); +} + +/// 128x128 superblocks in two tile columns (libaom), with motion field estimation: the +/// wavefront over the superblock rows of every tile column. +fn spec_sb128_tiles() -> Spec { + let enc = ["-cpu-used", "8", "-crf", "40", "-tile-columns", "1", "-lag-in-frames", "16", "-aom-params", "sb-size=128:enable-ref-frame-mvs=1"]; + Spec::new("wavefront_sb128_tiles", "testsrc2=s=640x400:r=25,rotate=a=t*0.5:c=black", 16, "yuv420p", &enc).encoder("libaom-av1") +} + +#[test] +fn superblocks_of_128_in_tile_columns_give_the_single_thread_pictures() { + let Some(ff) = ffmpeg_libaom() else { return }; + let tus = ivf_frames(&make(&ff, &spec_sb128_tiles())); + craft_media_testkit::with_deadline(DEADLINE_SECS, move || { + let want = decode(&tus, 1); + assert_eq!(want.len(), 16); + for threads in [2, 3, 4, 8, 16] { + for round in 0..2 { + assert!(decode(&tus, threads) == want, "threads {threads}, round {round}: pictures differ"); + } + } + }); +} + +#[test] +fn dropping_or_flushing_a_busy_decoder_never_hangs() { + let Some(ff) = ffmpeg() else { return }; + let tus = ivf_frames(&make(&ff, &spec())); + craft_media_testkit::with_deadline(DEADLINE_SECS, move || { + let want = decode(&tus, 1); + for threads in [2, 3, 8, 16] { + for cut in [1, 2, 7, 12, 23] { + // Dropped with frames in flight (no flush). + let mut dec = Decoder::with_threads(threads); + for (i, tu) in tus.iter().take(cut).enumerate() { + dec.decode_pts(tu, i as i64).expect("decode"); + } + drop(dec); + // Flushed mid-stream (as before a seek), then continued: the same pictures. + let mut dec = Decoder::with_threads(threads); + let mut pics = Vec::new(); + for (i, tu) in tus.iter().enumerate() { + if i == cut { + pics.extend(dec.flush_result().expect("flush")); + } + pics.extend(dec.decode_pts(tu, i as i64).expect("decode")); + } + pics.extend(dec.flush_result().expect("flush")); + assert!(pics == want, "threads {threads}, flush before unit {cut}: pictures differ"); + } + } + }); +}