Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

M9.7: AV1 tile, frame and post-filter threading

Brandon Thomas0e35e82e471c
diff --git a/crates/av1/README.md b/crates/av1/README.md
index d3fe1203a..8843e9558 100644
--- a/crates/av1/README.md
+++ b/crates/av1/README.md
@@ -22,7 +22,7 @@ reference) is used only as an external test oracle.
| Uncompressed frame header (all fields, frame size / superres / render size, tile info, quantiser, segmentation, delta q/lf, loop filter, CDEF, LR, tx mode, skip mode, global motion, film grain params) | 5.9 | done |
| Reference frame state: set_frame_refs, setup_past_independence, load_previous, reference update, show_existing_frame | 7.8, 7.20, 7.21 | done |
| Symbol decoder, CDF adaptation, init / load / save / frame-end CDF update | 8.2, 8.3 | done |
-| Tiles and tile groups (uniform and explicit spacing, tile size bytes) | 5.11 | done (decoded sequentially) |
+| Tiles and tile groups (uniform and explicit spacing, tile size bytes) | 5.11 | done (tiles decoded in parallel) |
| Intra frame mode info: partitions, skip, segment id, CDEF index, delta q / lf, y / uv modes, angle deltas, CfL alphas, palette (colors, cache, color index map), filter intra, tx size (incl. var-tx syntax) | 5.11 | done, bit-exact |
| Coefficients (all_zero, eob, base / br levels, Golomb, dc sign, tx type sets, scans) | 5.11.39 | done, bit-exact |
| Dequantisation incl. quantiser matrices | 7.12 | done (qmatrix not yet oracle-tested) |
@@ -63,13 +63,42 @@ OBMC / warped motion, motion-field projection, all loop filters; presets 3–8,
sizes), plus super-resolution (denominator 12) and film-grain streams, and compares every frame
with libdav1d: **bit-exact** on all 6 fixtures.
+## Threading and performance
+
+`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. 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.
+
+`tests/perf.rs` (ignored) prints single-threaded fps (thread CPU time), per-stage ms/frame
+(`Decoder::stats()`) and all-core fps for 1080p fixtures. The hot loops (sub-pixel filters,
+CDEF, inverse transforms, deblocking, entropy decoding) are written for auto-vectorisation.
+
+Measured 2026-10-01 on a 14-core Apple Silicon Mac (release build, SVT-AV1 preset 8 1080p
+fixtures from `tests/perf.rs`), before (`31f8b3d`: hot loops only, no threading) and after tile / frame /
+post-filter threading. The machine was heavily loaded by other builds during both runs (load
+average 200–400), so the all-core wall figures understate what an idle machine reaches and are
+noisy; single-threaded figures use thread CPU time and are comparable.
+
+| Fixture | 1 thread before | 1 thread after | 14 threads before | 14 threads after |
+|---|---|---|---|---|
+| `perf_1080p_intra` (10 key frames) | 43.3 fps | 43.0 fps | 6.5 fps | 20.8 fps |
+| `perf_1080p_gop` (60 frames, crf 30) | 45.5 fps | 40.7 fps | 7.7 fps | 11.0 fps |
+| `perf_1080p_gop_10bit` | 41.3 fps | 35.9 fps | 8.0 fps | 6.6 fps |
+| `perf_1080p_gop_hq` (crf 18) | 19.5 fps | 19.4 fps | 2.4 fps | 3.6 fps |
+| `perf_1080p_gop_tiles` (4x2 tiles) | 44.4 fps | 44.7 fps | 2.7 fps | 16.3 fps |
+
## API
```rust
let mut dec = filmcraft_av1::Decoder::new();
for sample in samples { // one temporal unit (MP4 / Matroska sample) each
- for pic in dec.decode(&sample)? { // shown frames, planar u16
- // pic.width, pic.height, pic.bit_depth, pic.planes[0..3]
+ for pic in dec.decode_pts(&sample, pts)? { // shown frames ready so far, planar u16
+ // pic.width, pic.height, pic.bit_depth, pic.planes[0..3], pic.pts
}
}
+let rest = dec.flush(); // pictures still in flight at the end
```
diff --git a/crates/av1/src/decoder.rs b/crates/av1/src/decoder.rs
index 7d905526e..c4dcfb3f3 100644
--- a/crates/av1/src/decoder.rs
+++ b/crates/av1/src/decoder.rs
@@ -1,14 +1,24 @@
//! Top-level decoder: OBU parsing (5.3), frame / tile group handling, reference frame update
//! (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.
-use std::sync::Arc;
+use std::collections::VecDeque;
+use std::sync::{Arc, Condvar, Mutex};
use crate::bits::{BitReader, leb128};
use crate::cdf::Cdfs;
use crate::frame::FrameBuf;
-use crate::header::{FrameHeader, HeaderState, LoopFilterDeltas, RefInfo, SegmentationFeatures, SequenceHeader, default_gm_params};
+use crate::header::{FilmGrainParams, FrameHeader, HeaderState, LoopFilterDeltas, RefInfo, SegmentationFeatures, SequenceHeader, default_gm_params};
+use crate::par::Pool;
use crate::spec_tables::*;
-use crate::state::FrameState;
+use crate::state::{FrameShared, FrameState, TileState};
use crate::stats::{DecodeStats, Stage, Timer};
use crate::tile::TileDecoder;
use crate::{Error, Picture, Result};
@@ -39,29 +49,162 @@ pub(crate) struct RefFrame {
pub saved_mvs: Vec<[i32; 2]>,
}
+/// A value produced by a decoding job, waited for by later jobs and by the output.
+pub(crate) struct Slot<T> {
+ value: Mutex<Option<std::result::Result<T, Error>>>,
+ cv: Condvar,
+}
+
+impl<T: Clone> Slot<T> {
+ fn new() -> Arc<Slot<T>> {
+ Arc::new(Slot { value: Mutex::new(None), cv: Condvar::new() })
+ }
+
+ fn set(&self, v: Result<T>) {
+ let mut g = self.value.lock().unwrap_or_else(|e| e.into_inner());
+ *g = Some(v);
+ self.cv.notify_all();
+ }
+
+ fn is_set(&self) -> bool {
+ self.value.lock().map(|g| g.is_some()).unwrap_or(true)
+ }
+
+ fn wait(&self) -> Result<T> {
+ let mut g = self.value.lock().unwrap_or_else(|e| e.into_inner());
+ while g.is_none() {
+ g = self.cv.wait(g).unwrap_or_else(|e| e.into_inner());
+ }
+ g.as_ref().expect("slot value").clone()
+ }
+}
+
+type FrameSlot = Slot<Arc<RefFrame>>;
+
+/// Everything needed to decode one frame, captured when its header is parsed.
+struct FrameJob {
+ seq: SequenceHeader,
+ fh: FrameHeader,
+ /// Reference slots at the start of the frame (only the used ones are waited for).
+ refs: [Option<Arc<FrameSlot>>; NUM_REF_FRAMES],
+ ref_info: [RefInfo; NUM_REF_FRAMES],
+ /// Tile payloads (tile number, data).
+ tiles: Vec<(usize, Vec<u8>)>,
+ slot: Arc<FrameSlot>,
+ /// The output picture, when the frame is shown.
+ picture: Option<Arc<Slot<Arc<Picture>>>>,
+ pts: i64,
+ apply_film_grain: bool,
+}
+
+/// A shown picture in output order.
+#[allow(clippy::large_enum_variant)]
+enum Output {
+ Decoded(Arc<Slot<Arc<Picture>>>),
+ /// show_existing_frame: built from the reference slot when it is finished.
+ Existing {
+ slot: Arc<FrameSlot>,
+ seq: SequenceHeader,
+ width: usize,
+ height: usize,
+ grain: FilmGrainParams,
+ apply_film_grain: bool,
+ pts: i64,
+ },
+}
+
+impl Output {
+ fn is_ready(&self) -> bool {
+ match self {
+ Output::Decoded(s) => s.is_set(),
+ Output::Existing { slot, .. } => slot.is_set(),
+ }
+ }
+
+ fn take(self) -> Result<Picture> {
+ match self {
+ Output::Decoded(s) => s.wait().map(|p| Arc::try_unwrap(p).unwrap_or_else(|p| (*p).clone())),
+ Output::Existing { slot, seq, width, height, grain, apply_film_grain, pts } => {
+ let rf = slot.wait()?;
+ Ok(output_picture(&seq, &rf, width, height, &grain, apply_film_grain, pts))
+ }
+ }
+ }
+}
+
+/// Frame worker threads taking jobs in submission order.
+#[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
+struct Workers {
+ tx: Option<std::sync::mpsc::Sender<Box<FrameJob>>>,
+ handles: Vec<std::thread::JoinHandle<()>>,
+}
+
+#[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
+impl Workers {
+ fn new(n: usize, pool: &Pool, stats: &Arc<Mutex<DecodeStats>>) -> Option<Workers> {
+ let (tx, rx) = std::sync::mpsc::channel::<Box<FrameJob>>();
+ let rx = Arc::new(Mutex::new(rx));
+ let mut handles = Vec::new();
+ for i in 0..n {
+ let (rx, pool, stats) = (rx.clone(), pool.clone(), stats.clone());
+ let h = std::thread::Builder::new()
+ .name(format!("av1-frame-{i}"))
+ .spawn(move || {
+ loop {
+ let job = match rx.lock() {
+ Ok(r) => r.recv(),
+ Err(_) => break,
+ };
+ match job {
+ Ok(job) => run_job(*job, &pool, &stats),
+ Err(_) => break,
+ }
+ }
+ })
+ .ok()?;
+ handles.push(h);
+ }
+ Some(Workers { tx: Some(tx), handles })
+ }
+}
+
+#[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
+impl Drop for Workers {
+ fn drop(&mut self) {
+ self.tx.take();
+ for h in self.handles.drain(..) {
+ let _ = h.join();
+ }
+ }
+}
+
/// An AV1 decoder. Feed it temporal units (one MP4 / Matroska sample each, or any run of
/// OBUs in the low-overhead format) and collect the shown frames.
pub struct Decoder {
seq: Option<SequenceHeader>,
refs: [RefInfo; NUM_REF_FRAMES],
- ref_frames: [Option<Arc<RefFrame>>; NUM_REF_FRAMES],
+ ref_frames: [Option<Arc<FrameSlot>>; NUM_REF_FRAMES],
lf_deltas: LoopFilterDeltas,
seg_features: SegmentationFeatures,
prev_gm_params: [[i32; 6]; 8],
current_frame_id: u32,
- /// Frame being decoded (between its header and its last tile group).
- cur: Option<Box<CurFrame>>,
+ /// Frame being collected (between its header and its last tile group).
+ pending: Option<Box<FrameJob>>,
seen_frame_header: bool,
/// Apply film grain synthesis to output frames (default true).
pub apply_film_grain: bool,
- stats: DecodeStats,
+ stats: Arc<Mutex<DecodeStats>>,
threads: usize,
-}
-
-struct CurFrame {
- fs: FrameState,
- cdfs: Box<Cdfs>,
- saved_cdfs: Option<Box<Cdfs>>,
+ pool: Pool,
+ #[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
+ workers: Option<Workers>,
+ /// Frames submitted to the workers and not known to be finished (oldest first).
+ in_flight: VecDeque<Arc<FrameSlot>>,
+ max_in_flight: usize,
+ /// Shown pictures not yet returned, in output order.
+ out: VecDeque<Output>,
+ /// pts of the temporal unit being decoded.
+ pts: i64,
}
fn default_threads() -> usize {
@@ -75,6 +218,12 @@ fn default_threads() -> usize {
}
}
+/// Frames decoded concurrently with `threads` threads (each in-flight 1080p frame holds a few
+/// tens of MB of state).
+fn frame_threads(threads: usize) -> usize {
+ if threads <= 1 { 1 } else { threads.div_ceil(2).clamp(2, 8) }
+}
+
impl Default for Decoder {
fn default() -> Self {
Self::new()
@@ -89,6 +238,12 @@ impl Decoder {
/// A decoder using up to `threads` worker threads (1 = decode on the calling thread).
pub fn with_threads(threads: usize) -> Decoder {
+ let threads = threads.max(1);
+ let pool = Pool::new(threads);
+ let stats = Arc::new(Mutex::new(DecodeStats::default()));
+ let fthreads = if pool.is_parallel() { frame_threads(threads) } else { 1 };
+ #[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
+ let workers = if fthreads > 1 { Workers::new(fthreads, &pool, &stats) } else { None };
Decoder {
seq: None,
refs: Default::default(),
@@ -97,22 +252,24 @@ impl Decoder {
seg_features: SegmentationFeatures::default(),
prev_gm_params: default_gm_params(),
current_frame_id: 0,
- cur: None,
+ pending: None,
seen_frame_header: false,
apply_film_grain: true,
- stats: DecodeStats::default(),
- threads: threads.max(1),
+ stats,
+ threads,
+ pool,
+ #[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
+ workers,
+ in_flight: VecDeque::new(),
+ max_in_flight: fthreads + 2,
+ out: VecDeque::new(),
+ pts: 0,
}
}
- /// Output every picture still held by the decoder (end of stream / before a seek).
- pub fn flush(&mut self) -> Vec<Picture> {
- Vec::new()
- }
-
- /// Frame / tile counts and per-stage busy time accumulated so far.
+ /// Frame / tile counts and per-stage busy time of the frames finished so far.
pub fn stats(&self) -> DecodeStats {
- self.stats
+ self.stats.lock().map(|s| *s).unwrap_or_default()
}
/// The active sequence header, once one has been decoded.
@@ -120,10 +277,91 @@ impl Decoder {
self.seq.as_ref()
}
- /// Decode a chunk of OBUs; returns the frames shown by it.
+ /// Decode a chunk of OBUs; returns the frames that are ready for output, in order (with
+ /// frame threads, pictures shown by this chunk may come from a later call or [`flush`]).
+ ///
+ /// [`flush`]: Decoder::flush
pub fn decode(&mut self, data: &[u8]) -> Result<Vec<Picture>> {
- // (picture, temporal unit, spatial_id)
- let mut out: Vec<(Picture, usize, u32)> = Vec::new();
+ self.decode_pts(data, 0)
+ }
+
+ /// [`Decoder::decode`] with a timestamp that the pictures shown by this chunk carry.
+ pub fn decode_pts(&mut self, data: &[u8], pts: i64) -> Result<Vec<Picture>> {
+ self.pts = pts;
+ let parsed = self.parse(data);
+ // Hand out what is finished, then report a parse error.
+ let mut pics = Vec::new();
+ let max_queue = 2 * self.max_in_flight;
+ while let Some(o) = self.out.front() {
+ if !o.is_ready() && self.out.len() <= max_queue {
+ break;
+ }
+ let o = self.out.pop_front().expect("front");
+ pics.push(o.take()?);
+ }
+ parsed?;
+ Ok(pics)
+ }
+
+ /// Output every picture still held by the decoder (end of stream / before a seek); the
+ /// first decoding error is returned instead.
+ pub fn flush(&mut self) -> Vec<Picture> {
+ self.flush_result().unwrap_or_default()
+ }
+
+ /// [`Decoder::flush`] reporting decoding errors.
+ pub fn flush_result(&mut self) -> Result<Vec<Picture>> {
+ let mut pics = Vec::new();
+ let mut err = None;
+ while let Some(o) = self.out.pop_front() {
+ match o.take() {
+ Ok(p) => pics.push(p),
+ Err(e) => {
+ err.get_or_insert(e);
+ }
+ }
+ }
+ while let Some(s) = self.in_flight.pop_front() {
+ let _ = s.wait();
+ }
+ match err {
+ Some(e) => Err(e),
+ None => Ok(pics),
+ }
+ }
+
+ fn parse(&mut self, data: &[u8]) -> Result<()> {
+ // (output, temporal unit, spatial_id)
+ let mut out: Vec<(Output, usize, u32)> = Vec::new();
+ let r = self.parse_obus(data, &mut out);
+ // Output policy (7.18.1 note): with scalability, show one frame per temporal unit, the
+ // highest spatial layer present.
+ let scalable = self.seq.as_ref().is_some_and(|s| s.op_idc != 0);
+ if !scalable {
+ self.out.extend(out.into_iter().map(|(o, _, _)| o));
+ } else {
+ let mut last: Option<(usize, u32)> = None;
+ let mut sel: Vec<Output> = Vec::new();
+ for (o, t, sid) in out {
+ match last {
+ Some((lt, lsid)) if lt == t => {
+ if sid >= lsid {
+ *sel.last_mut().expect("picture") = o;
+ last = Some((t, sid));
+ }
+ }
+ _ => {
+ sel.push(o);
+ last = Some((t, sid));
+ }
+ }
+ }
+ self.out.extend(sel);
+ }
+ r
+ }
+
+ fn parse_obus(&mut self, data: &[u8], out: &mut Vec<(Output, usize, u32)>) -> Result<()> {
let mut tu = 0usize;
let mut pos = 0;
while pos < data.len() {
@@ -143,11 +381,11 @@ impl Decoder {
p += 1;
}
let size = if has_size {
- let (v, n) = leb128(&data[p..])?;
+ let (v, n) = leb128(data.get(p..).ok_or(Error::Truncated)?)?;
p += n;
v as usize
} else {
- data.len() - p
+ data.len().checked_sub(p).ok_or(Error::Truncated)?
};
let end = p.checked_add(size).filter(|&e| e <= data.len()).ok_or(Error::Truncated)?;
let payload = &data[p..end];
@@ -183,54 +421,32 @@ impl Decoder {
}
let mut r = BitReader::new(payload);
let shown = self.frame_header(&mut r, temporal_id, spatial_id)?;
- if let Some(pic) = shown {
- out.push((pic, tu, spatial_id));
+ if let Some(o) = shown {
+ out.push((o, tu, spatial_id));
continue;
}
if obu_type == OBU_FRAME_T {
r.byte_align();
- let rest = &payload[r.byte_pos()..];
- if let Some(pic) = self.tile_group(rest)? {
- out.push((pic, tu, spatial_id));
+ let rest = payload.get(r.byte_pos()..).ok_or(Error::Truncated)?;
+ if let Some(o) = self.tile_group(rest)? {
+ out.push((o, tu, spatial_id));
}
}
}
OBU_TILE_GROUP_T => {
- if let Some(pic) = self.tile_group(payload)? {
- out.push((pic, tu, spatial_id));
+ if let Some(o) = self.tile_group(payload)? {
+ out.push((o, tu, spatial_id));
}
}
OBU_METADATA_T | OBU_TILE_LIST_T => {}
_ => {}
}
}
- // Output policy (7.18.1 note): with scalability, show one frame per temporal unit, the
- // highest spatial layer present.
- let scalable = self.seq.as_ref().is_some_and(|s| s.op_idc != 0);
- if !scalable {
- return Ok(out.into_iter().map(|(p, _, _)| p).collect());
- }
- let mut pics: Vec<Picture> = Vec::new();
- let mut last: Option<(usize, u32)> = None;
- for (p, t, sid) in out {
- match last {
- Some((lt, lsid)) if lt == t => {
- if sid >= lsid {
- *pics.last_mut().expect("picture") = p;
- last = Some((t, sid));
- }
- }
- _ => {
- pics.push(p);
- last = Some((t, sid));
- }
- }
- }
- Ok(pics)
+ Ok(())
}
- /// frame_header_obu( ): returns a picture for show_existing_frame.
- fn frame_header(&mut self, r: &mut BitReader, temporal_id: u32, spatial_id: u32) -> Result<Option<Picture>> {
+ /// frame_header_obu( ): returns the output for show_existing_frame.
+ fn frame_header(&mut self, r: &mut BitReader, temporal_id: u32, spatial_id: u32) -> Result<Option<Output>> {
let seq = self.seq.clone().ok_or(Error::Invalid("frame before sequence header"))?;
self.seen_frame_header = true;
let mut st = HeaderState {
@@ -249,71 +465,64 @@ impl Decoder {
if fh.show_existing_frame {
self.seen_frame_header = false;
let idx = fh.frame_to_show_map_idx;
- let rf = self.ref_frames[idx].clone().ok_or(Error::Invalid("show_existing_frame of an empty slot"))?;
+ let slot = self.ref_frames[idx].clone().ok_or(Error::Invalid("show_existing_frame of an empty slot"))?;
let info = self.refs[idx].clone();
- let t = Timer::start();
- let pic = self.output_picture(&seq, &rf, info.upscaled_width as usize, info.frame_height as usize, &fh.film_grain);
+ let o = Output::Existing {
+ slot: slot.clone(),
+ seq: seq.clone(),
+ width: info.upscaled_width as usize,
+ height: info.frame_height as usize,
+ grain: fh.film_grain.clone(),
+ apply_film_grain: self.apply_film_grain,
+ pts: self.pts,
+ };
if fh.frame_type == KEY_FRAME as u8 {
// reference frame loading process (7.21) then refresh every slot (7.20)
self.lf_deltas = info.lf_deltas;
self.seg_features = info.seg_features;
for i in 0..NUM_REF_FRAMES {
self.refs[i] = info.clone();
- self.ref_frames[i] = Some(rf.clone());
+ self.ref_frames[i] = Some(slot.clone());
}
}
- self.stats.add(Stage::Output, t.secs());
- return Ok(Some(pic));
+ return Ok(Some(o));
}
// Encoders exist that code frames slightly larger than the sequence maximum (e.g. a
// 270-line stream coded as 272 lines); like other decoders we accept them.
if fh.upscaled_width > 65536 || fh.frame_height > 65536 {
return Err(Error::Invalid("frame size"));
}
- let t = Timer::start();
- let mut fs = FrameState::new(&seq, &fh);
- fs.refs = self.ref_frames.clone();
- fs.ref_info = self.refs.clone();
if !fh.frame_is_intra {
for i in 0..REFS_PER_FRAME {
- if fs.refs[fh.ref_frame_idx[i]].is_none() {
+ if self.ref_frames[fh.ref_frame_idx[i]].is_none() {
return Err(Error::Invalid("missing reference frame"));
}
}
}
- if fh.primary_ref_frame != PRIMARY_REF_NONE {
- // load_previous_segment_ids( )
- if let Some(rf) = &self.ref_frames[fh.ref_frame_idx[fh.primary_ref_frame]]
- && fh.seg.enabled
- && rf.mi_cols == fs.mi.cols
- && rf.mi_rows == fs.mi.rows
- {
- fs.prev_segment_ids.copy_from_slice(&rf.segment_ids);
- }
+ if fh.primary_ref_frame != PRIMARY_REF_NONE && self.ref_frames[fh.ref_frame_idx[fh.primary_ref_frame]].is_none() {
+ return Err(Error::Invalid("primary reference frame missing"));
}
- 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 slot = fh.ref_frame_idx[fh.primary_ref_frame];
- let rf = self.ref_frames[slot].as_ref().ok_or(Error::Invalid("primary reference frame missing"))?;
- let mut c = rf.cdfs.clone();
- c.clear_counts();
- c
- };
- self.cur = Some(Box::new(CurFrame { fs, cdfs, saved_cdfs: None }));
- self.stats.add(Stage::Setup, t.secs());
+ let picture = fh.show_frame.then(Slot::new);
+ self.pending = Some(Box::new(FrameJob {
+ seq,
+ fh,
+ refs: self.ref_frames.clone(),
+ ref_info: self.refs.clone(),
+ tiles: Vec::new(),
+ slot: Slot::new(),
+ picture,
+ pts: self.pts,
+ apply_film_grain: self.apply_film_grain,
+ }));
Ok(None)
}
- /// tile_group_obu( sz ): returns the output picture when the frame completes and is shown.
- fn tile_group(&mut self, data: &[u8]) -> Result<Option<Picture>> {
- let mut cur = self.cur.take().ok_or(Error::Invalid("tile group without a frame header"))?;
- let (cols, rows, cols_log2, rows_log2, tsb, ctx_tile) = {
- let t = &cur.fs.fh.tile_info;
- (t.cols, t.rows, t.cols_log2, t.rows_log2, t.tile_size_bytes, t.context_update_tile_id as usize)
+ /// tile_group_obu( sz ): returns the output when the frame is complete and shown.
+ fn tile_group(&mut self, data: &[u8]) -> Result<Option<Output>> {
+ let mut job = self.pending.take().ok_or(Error::Invalid("tile group without a frame header"))?;
+ let (cols, rows, cols_log2, rows_log2, tsb) = {
+ let t = &job.fh.tile_info;
+ (t.cols, t.rows, t.cols_log2, t.rows_log2, t.tile_size_bytes)
};
let num_tiles = cols * rows;
let mut r = BitReader::new(data);
@@ -330,10 +539,8 @@ impl Decoder {
}
let mut pos = r.byte_pos();
for tile_num in tg_start..=tg_end {
- let tile_row = tile_num / cols;
- let tile_col = tile_num % cols;
let size = if tile_num == tg_end {
- data.len() - pos
+ data.len().checked_sub(pos).ok_or(Error::Truncated)?
} else {
let mut v = 0usize;
for i in 0..tsb as usize {
@@ -343,60 +550,21 @@ impl Decoder {
v + 1
};
let end = pos.checked_add(size).filter(|&e| e <= data.len()).ok_or(Error::Truncated)?;
- let tile_data = &data[pos..end];
+ job.tiles.push((tile_num, data[pos..end].to_vec()));
pos = end;
- let t = Timer::start();
- let cdfs = cur.cdfs.clone();
- cur.fs.intra_frame_y_mode_cdf = DEFAULT_INTRA_FRAME_Y_MODE_CDF;
- let mut td = TileDecoder::new(&mut cur.fs, tile_data, cdfs, tile_row, tile_col);
- td.decode_tile()?;
- if !td.fs.fh.disable_frame_end_update_cdf && tile_num == ctx_tile {
- cur.saved_cdfs = Some(td.cdf);
- }
- self.stats.tiles += 1;
- self.stats.add(Stage::Tiles, t.secs());
}
if tg_end != num_tiles - 1 {
- self.cur = Some(cur);
+ self.pending = Some(job);
return Ok(None);
}
- let mut cur = *cur;
- if !cur.fs.fh.disable_frame_end_update_cdf
- && let Some(saved) = cur.saved_cdfs.take()
- {
- cur.cdfs = saved;
- }
self.seen_frame_header = false;
- self.decode_frame_wrapup(cur)
- }
-
- fn decode_frame_wrapup(&mut self, cur: CurFrame) -> Result<Option<Picture>> {
- let CurFrame { mut fs, cdfs, .. } = cur;
- crate::postfilter::apply(&mut fs, &mut self.stats);
- let t = Timer::start();
- self.stats.frames += 1;
- let seq = fs.seq.clone();
- let fh = fs.fh.clone();
- 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,
- 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,
- film_grain_present: seq.film_grain_params_present,
- 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,
- });
- // reference frame update process (7.20)
+ Ok(self.submit(job))
+ }
+
+ /// The frame's data is complete: update the reference state (7.20) and decode it (on a
+ /// frame worker when there are any).
+ fn submit(&mut self, job: Box<FrameJob>) -> Option<Output> {
+ let fh = &job.fh;
for i in 0..NUM_REF_FRAMES {
if (fh.refresh_frame_flags >> i) & 1 == 1 {
let ri = &mut self.refs[i];
@@ -416,46 +584,227 @@ impl Decoder {
ri.lf_deltas = fh.lf.deltas;
ri.seg_features = fh.seg.features;
ri.grain = fh.film_grain.clone();
- self.ref_frames[i] = Some(rf.clone());
+ self.ref_frames[i] = Some(job.slot.clone());
}
}
- let pic = if fh.show_frame { Some(self.output_picture(&seq, &rf, fh.upscaled_width as usize, fh.frame_height as usize, &fh.film_grain)) } else { None };
- self.stats.add(Stage::Output, t.secs());
- Ok(pic)
- }
-
- fn output_picture(&self, seq: &SequenceHeader, rf: &RefFrame, w: usize, h: usize, grain: &crate::header::FilmGrainParams) -> Picture {
- let ssx = rf.subsampling_x as usize;
- let ssy = rf.subsampling_y as usize;
- let num_planes = rf.buf.num_planes;
- let mut planes: [Vec<u16>; 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 mut v = Vec::with_capacity(pw * ph);
- for y in 0..ph {
- v.extend_from_slice(&src.row(y)[..pw]);
+ let output = job.picture.clone().map(Output::Decoded);
+ #[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
+ if let Some(w) = &self.workers
+ && let Some(tx) = &w.tx
+ {
+ let slot = job.slot.clone();
+ match tx.send(job) {
+ 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 s = self.in_flight.pop_front().expect("in flight");
+ let _ = s.wait();
+ }
+ self.in_flight.retain(|s| !s.is_set());
+ }
+ Err(e) => run_job(*e.0, &self.pool, &self.stats),
}
- planes[p] = v;
- }
- let mut pic = Picture {
- width: w as u32,
- height: h as u32,
- bit_depth: rf.bit_depth,
- subsampling_x: rf.subsampling_x,
- subsampling_y: rf.subsampling_y,
- mono_chrome: num_planes == 1,
- planes,
- color_primaries: rf.color.0,
- transfer_characteristics: rf.color.1,
- matrix_coefficients: rf.color.2,
- full_range: rf.color.3,
- };
- if self.apply_film_grain && seq.film_grain_params_present && grain.apply_grain {
- crate::grain::apply(&mut pic, grain, seq);
+ return output;
}
- pic
+ run_job(*job, &self.pool, &self.stats);
+ output
+ }
+}
+
+/// Decode a frame job and publish its results.
+fn run_job(job: FrameJob, pool: &Pool, stats: &Mutex<DecodeStats>) {
+ let mut st = DecodeStats::default();
+ match decode_frame(&job, pool, &mut st) {
+ Ok((rf, pic)) => {
+ if let Some(ps) = &job.picture {
+ ps.set(pic.map(Arc::new).ok_or(Error::Invalid("shown frame without picture")));
+ }
+ job.slot.set(Ok(rf));
+ }
+ Err(e) => {
+ if let Some(ps) = &job.picture {
+ ps.set(Err(e.clone()));
+ }
+ job.slot.set(Err(e));
+ }
+ }
+ if let Ok(mut s) = stats.lock() {
+ s.merge(&st);
+ }
+}
+
+/// The whole decoding process of one frame: setup, tiles, post-filters, motion vector storage
+/// and the output picture.
+fn decode_frame(job: &FrameJob, pool: &Pool, stats: &mut DecodeStats) -> Result<(Arc<RefFrame>, Option<Picture>)> {
+ let fh = &job.fh;
+ let seq = &job.seq;
+ // Wait for the reference frames this frame reads.
+ 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;
+ }
+ }
+ if fh.primary_ref_frame != PRIMARY_REF_NONE {
+ used[fh.ref_frame_idx[fh.primary_ref_frame]] = true;
+ }
+ let mut refs: [Option<Arc<RefFrame>>; 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()?);
+ }
+ }
+ let t = Timer::start();
+ let mut fs = FrameState::new(seq, fh);
+ fs.refs = refs;
+ fs.ref_info = job.ref_info.clone();
+ if fh.primary_ref_frame != PRIMARY_REF_NONE {
+ // load_previous_segment_ids( )
+ if let Some(rf) = &fs.refs[fh.ref_frame_idx[fh.primary_ref_frame]]
+ && fh.seg.enabled
+ && rf.mi_cols == fs.mi.cols
+ && rf.mi_rows == fs.mi.rows
+ {
+ let ids = rf.segment_ids.clone();
+ fs.prev_segment_ids.copy_from_slice(&ids);
+ }
+ }
+ if fh.use_ref_frame_mvs {
+ motion_field_estimation(&mut fs);
+ }
+ 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
+ };
+ stats.add(Stage::Setup, t.secs());
+ let t = Timer::start();
+ let saved = decode_tiles(pool, &mut fs, &cdfs, &job.tiles)?;
+ stats.tiles += job.tiles.len() as u64;
+ stats.add(Stage::Tiles, t.secs());
+ if !fh.disable_frame_end_update_cdf
+ && let Some(s) = saved
+ {
+ cdfs = s;
+ }
+ crate::postfilter::apply(&mut fs, stats, pool);
+ 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,
+ 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,
+ film_grain_present: seq.film_grain_params_present,
+ 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,
+ });
+ let pic =
+ fh.show_frame.then(|| output_picture(seq, &rf, fh.upscaled_width as usize, fh.frame_height as usize, &fh.film_grain, job.apply_film_grain, job.pts));
+ stats.add(Stage::Output, t.secs());
+ Ok((rf, pic))
+}
+
+/// 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<u8>)]) -> Result<Option<Box<Cdfs>>> {
+ 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<Option<Box<Cdfs>>> {
+ 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.decode_tile()?;
+ Ok((num == ctx_tile).then_some(td.cdf))
+ };
+ // Intra block copy reads the current frame through the tile's own buffer: keep whole-frame
+ // buffers (tiles one after another) for it.
+ if tiles.len() > 1 && pool.is_parallel() && !fs.fh.allow_intrabc {
+ let mut states: Vec<TileState> = tiles
+ .iter()
+ .map(|(num, _)| {
+ let (row, col) = (num / ti.cols, num % ti.cols);
+ let (r0, r1) = (ti.mi_row_starts[row] as usize, ti.mi_row_starts[row + 1] as usize);
+ let (c0, c1) = (ti.mi_col_starts[col] as usize, ti.mi_col_starts[col + 1] as usize);
+ fs.tile_state(r0, r1.min(fs.mi.rows), c0, c1.min(fs.mi.cols))
+ })
+ .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);
+ }
+ }
+ return Ok(saved);
+ }
+ let mut t = fs.take_tile_state();
+ let mut saved = None;
+ 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) => {}
+ Err(e) => {
+ res = Err(e);
+ break;
+ }
+ }
+ }
+ fs.put_tile_state(t);
+ res.map(|_| saved)
+}
+
+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 mut planes: [Vec<u16>; 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 mut v = Vec::with_capacity(pw * ph);
+ for y in 0..ph {
+ v.extend_from_slice(&src.row(y)[..pw]);
+ }
+ planes[p] = v;
+ }
+ let mut pic = Picture {
+ width: w as u32,
+ height: h as u32,
+ bit_depth: rf.bit_depth,
+ subsampling_x: rf.subsampling_x,
+ subsampling_y: rf.subsampling_y,
+ mono_chrome: num_planes == 1,
+ planes,
+ color_primaries: rf.color.0,
+ transfer_characteristics: rf.color.1,
+ matrix_coefficients: rf.color.2,
+ full_range: rf.color.3,
+ pts,
+ };
+ if apply_film_grain && seq.film_grain_params_present && grain.apply_grain {
+ crate::grain::apply(&mut pic, grain, seq);
}
+ pic
}
/// Motion field motion vector storage process (7.19): (MfRefFrames, MfMvs).
diff --git a/crates/av1/src/frame.rs b/crates/av1/src/frame.rs
index f7239b7a4..f6617105a 100644
--- a/crates/av1/src/frame.rs
+++ b/crates/av1/src/frame.rs
@@ -1,31 +1,65 @@
//! Frame sample buffers and per-4x4 mode info storage.
+//!
+//! Tiles decode in parallel into private buffers that cover only the tile's area: a [`Plane`]
+//! or [`MiInfo`] may hold a region of the frame (origin `ox`, `oy`), addressed with frame
+//! coordinates throughout.
-/// One plane of samples (u16 at every bit depth).
+/// One plane of samples (u16 at every bit depth), or a rectangular region of one.
#[derive(Clone, Default)]
pub struct Plane {
pub data: Vec<u16>,
pub stride: usize,
/// Allocated rows.
pub rows: usize,
+ /// Frame coordinates of `data[0]` (0 for whole planes).
+ pub ox: usize,
+ pub oy: usize,
}
impl Plane {
pub fn new(width: usize, height: usize) -> Plane {
- Plane { data: vec![0; width * height], stride: width, rows: height }
+ Plane { data: vec![0; width * height], stride: width, rows: height, ox: 0, oy: 0 }
+ }
+ /// A `width` x `height` region with its top-left sample at frame position (ox, oy).
+ pub fn region(ox: usize, oy: usize, width: usize, height: usize) -> Plane {
+ Plane { data: vec![0; width * height], stride: width, rows: height, ox, oy }
}
#[inline(always)]
pub fn at(&self, x: usize, y: usize) -> u16 {
- self.data[y * self.stride + x]
+ self.data[(y - self.oy) * self.stride + x - self.ox]
}
#[inline(always)]
pub fn set(&mut self, x: usize, y: usize, v: u16) {
- self.data[y * self.stride + x] = v;
+ self.data[(y - self.oy) * self.stride + x - self.ox] = v;
}
+ /// Row `y`; index 0 is column `ox` (whole planes: column 0).
+ #[inline(always)]
pub fn row(&self, y: usize) -> &[u16] {
- &self.data[y * self.stride..(y + 1) * self.stride]
+ let o = (y - self.oy) * self.stride;
+ &self.data[o..o + self.stride]
}
+ #[inline(always)]
pub fn row_mut(&mut self, y: usize) -> &mut [u16] {
- &mut self.data[y * self.stride..(y + 1) * self.stride]
+ let o = (y - self.oy) * self.stride;
+ &mut self.data[o..o + self.stride]
+ }
+ /// Row `y` from column `x` (frame coordinates) to the end of the stored row.
+ #[inline(always)]
+ pub fn row_from(&self, y: usize, x: usize) -> &[u16] {
+ let o = (y - self.oy) * self.stride;
+ &self.data[o + x - self.ox..o + self.stride]
+ }
+ #[inline(always)]
+ pub fn row_from_mut(&mut self, y: usize, x: usize) -> &mut [u16] {
+ let o = (y - self.oy) * self.stride;
+ &mut self.data[o + x - self.ox..o + self.stride]
+ }
+ /// Copy this region into the whole plane `dst` (same frame coordinates).
+ pub fn copy_into(&self, dst: &mut Plane) {
+ for y in 0..self.rows {
+ let s = &self.data[y * self.stride..(y + 1) * self.stride];
+ dst.row_from_mut(self.oy + y, self.ox)[..self.stride].copy_from_slice(s);
+ }
}
}
@@ -56,6 +90,29 @@ impl FrameBuf {
FrameBuf { planes, num_planes, subsampling_x, subsampling_y, bit_depth, width, height }
}
+ /// The region of a frame of this geometry covering luma samples [x0, x1) x [y0, y1)
+ /// (chroma scaled down); the bounds are multiples of 8, or the allocated size.
+ pub fn region_like(&self, x0: usize, y0: usize, x1: usize, y1: usize) -> FrameBuf {
+ let mut planes: [Plane; 3] = Default::default();
+ for (p, pl) in planes.iter_mut().enumerate().take(self.num_planes) {
+ let (sx, sy) = if p == 0 { (0, 0) } else { (self.subsampling_x, self.subsampling_y) };
+ let full = &self.planes[p];
+ let (px0, py0) = (x0 >> sx, y0 >> sy);
+ let px1 = (x1 >> sx).min(full.stride);
+ let py1 = (y1 >> sy).min(full.rows);
+ *pl = Plane::region(px0, py0, px1 - px0, py1 - py0);
+ }
+ FrameBuf {
+ planes,
+ num_planes: self.num_planes,
+ subsampling_x: self.subsampling_x,
+ subsampling_y: self.subsampling_y,
+ bit_depth: self.bit_depth,
+ width: self.width,
+ height: self.height,
+ }
+ }
+
pub fn plane_width(&self, plane: usize) -> usize {
if plane == 0 { self.width } else { (self.width + self.subsampling_x) >> self.subsampling_x }
}
@@ -83,8 +140,14 @@ impl Mv {
/// `[ row ][ col ]` in mode-info units).
#[derive(Clone, Default)]
pub struct MiInfo {
+ /// Frame size in mode info units.
pub cols: usize,
pub rows: usize,
+ /// Stored region: origin and width (the whole frame unless a tile's private copy).
+ pub ox: usize,
+ pub oy: usize,
+ pub stride: usize,
+ pub region_rows: usize,
pub y_mode: Vec<u8>,
pub uv_mode: Vec<u8>,
pub ref_frame: Vec<[i8; 2]>,
@@ -111,10 +174,19 @@ pub struct MiInfo {
impl MiInfo {
pub fn new(cols: usize, rows: usize) -> MiInfo {
- let n = cols * rows;
+ MiInfo::region(cols, rows, 0, 0, cols, rows)
+ }
+
+ /// Storage for the w x h mode info units at (ox, oy) of a cols x rows frame.
+ pub fn region(cols: usize, rows: usize, ox: usize, oy: usize, w: usize, h: usize) -> MiInfo {
+ let n = w * h;
MiInfo {
cols,
rows,
+ ox,
+ oy,
+ stride: w,
+ region_rows: h,
y_mode: vec![0; n],
uv_mode: vec![0; n],
ref_frame: vec![[0, -1]; n],
@@ -140,6 +212,28 @@ impl MiInfo {
#[inline(always)]
pub fn idx(&self, row: usize, col: usize) -> usize {
- row * self.cols + col
+ debug_assert!(col >= self.ox && col < self.ox + self.stride && row >= self.oy, "mode info ({row}, {col}) outside the stored region");
+ (row - self.oy) * self.stride + col - self.ox
+ }
+
+ /// Copy this region into the whole-frame `dst`.
+ pub fn copy_into(&self, dst: &mut MiInfo) {
+ let (w, h) = (self.stride, self.region_rows);
+ macro_rules! copy {
+ ($($f:ident)*) => {$(
+ for y in 0..h {
+ let d = dst.idx(self.oy + y, self.ox);
+ dst.$f[d..d + w].copy_from_slice(&self.$f[y * w..(y + 1) * w]);
+ }
+ )*};
+ }
+ copy!(y_mode uv_mode ref_frame mv is_inter skip_mode skip tx_size inter_tx_size mi_size segment_id delta_lf comp_group_idx compound_idx interp_filter motion_mode tx_type written);
+ for k in 0..2 {
+ for y in 0..h {
+ let d = dst.idx(self.oy + y, self.ox);
+ dst.palette_size[k][d..d + w].copy_from_slice(&self.palette_size[k][y * w..(y + 1) * w]);
+ dst.palette_colors[k][d..d + w].copy_from_slice(&self.palette_colors[k][y * w..(y + 1) * w]);
+ }
+ }
}
}
diff --git a/crates/av1/src/inter.rs b/crates/av1/src/inter.rs
index bbe5da443..87fd80c74 100644
--- a/crates/av1/src/inter.rs
+++ b/crates/av1/src/inter.rs
@@ -180,7 +180,7 @@ impl TileDecoder<'_, '_> {
}
fn ref_plane(&self, ref_idx: i32, plane: usize) -> &Plane {
- if ref_idx < 0 { &self.fs.cur.planes[plane] } else { &self.fs.refs[ref_idx as usize].as_ref().expect("reference frame").buf.planes[plane] }
+ if ref_idx < 0 { &self.t.cur.planes[plane] } else { &self.fs.refs[ref_idx as usize].as_ref().expect("reference frame").buf.planes[plane] }
}
/// Block inter prediction process (7.11.3.4) into `pred` (stride PRED_STRIDE); `tmp` holds
@@ -388,10 +388,10 @@ impl TileDecoder<'_, '_> {
#[allow(clippy::too_many_arguments)]
pub(crate) fn predict_inter(&mut self, plane: usize, x: usize, y: usize, w: usize, h: usize, cand_row: usize, cand_col: usize) {
let bd = self.fs.bit_depth;
- let mi_i = self.fs.mi.idx(cand_row, cand_col);
- let cand_refs = self.fs.mi.ref_frame[mi_i];
- let cand_mvs = self.fs.mi.mv[mi_i];
- let filters = self.fs.mi.interp_filter[mi_i];
+ let mi_i = self.t.mi.idx(cand_row, cand_col);
+ let cand_refs = self.t.mi.ref_frame[mi_i];
+ let cand_mvs = self.t.mi.mv[mi_i];
+ let filters = self.t.mi.interp_filter[mi_i];
let is_compound = cand_refs[1] > INTRA_FRAME as i8;
let rnd = rounding(is_compound, bd);
if plane == 0 && self.b.motion_mode as usize == LOCALWARP {
@@ -471,26 +471,26 @@ impl TileDecoder<'_, '_> {
let max = (1i32 << bd) - 1;
let is_inter_intra = self.b.is_inter && self.b.ref_frame[1] == INTRA_FRAME as i8;
if !is_compound && !is_inter_intra {
- let pl = &mut self.fs.cur.planes[plane];
+ let pl = &mut self.t.cur.planes[plane];
for i in 0..h {
- let row = &mut pl.row_mut(y + i)[x..x + w];
+ let row = &mut pl.row_from_mut(y + i, x)[..w];
for j in 0..w {
row[j] = preds[0][i * PRED_STRIDE + j].clamp(0, max) as u16;
}
}
} else if ct == COMPOUND_AVERAGE {
- let pl = &mut self.fs.cur.planes[plane];
+ let pl = &mut self.t.cur.planes[plane];
for i in 0..h {
- let row = &mut pl.row_mut(y + i)[x..x + w];
+ let row = &mut pl.row_from_mut(y + i, x)[..w];
for j in 0..w {
let k = i * PRED_STRIDE + j;
row[j] = round2(preds[0][k] + preds[1][k], 1 + rnd.2).clamp(0, max) as u16;
}
}
} else if ct == COMPOUND_DISTANCE {
- let pl = &mut self.fs.cur.planes[plane];
+ let pl = &mut self.t.cur.planes[plane];
for i in 0..h {
- let row = &mut pl.row_mut(y + i)[x..x + w];
+ let row = &mut pl.row_from_mut(y + i, x)[..w];
for j in 0..w {
let k = i * PRED_STRIDE + j;
row[j] = round2(fwd * preds[0][k] + bck * preds[1][k], 4 + rnd.2).clamp(0, max) as u16;
@@ -533,7 +533,7 @@ impl TileDecoder<'_, '_> {
round2(mk(2 * yy, 2 * xx) + mk(2 * yy, 2 * xx + 1) + mk(2 * yy + 1, 2 * xx) + mk(2 * yy + 1, 2 * xx + 1), 2)
};
let k = yy * PRED_STRIDE + xx;
- let pl = &mut self.fs.cur.planes[plane];
+ let pl = &mut self.t.cur.planes[plane];
if interintra {
let p0 = round2(preds[0][k], post).clamp(0, max);
let p1 = pl.at(dx + xx, dy + yy) as i32;
@@ -602,7 +602,7 @@ impl TileDecoder<'_, '_> {
while n < limit && x4 < mi_cols.min(self.b.mi_col + w4) {
let cr = self.b.mi_row - 1;
let cc = x4 | 1;
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let ci = mi.idx(cr, cc);
let step4 = (NUM_4X4_BLOCKS_WIDE[mi.mi_size[ci] as usize] as usize).clamp(2, 16);
if mi.ref_frame[ci][0] > INTRA_FRAME as i8 {
@@ -623,7 +623,7 @@ impl TileDecoder<'_, '_> {
while n < limit && y4 < mi_rows.min(self.b.mi_row + h4) {
let cc = self.b.mi_col - 1;
let cr = y4 | 1;
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let ci = mi.idx(cr, cc);
let step4 = (NUM_4X4_BLOCKS_HIGH[mi.mi_size[ci] as usize] as usize).clamp(2, 16);
if mi.ref_frame[ci][0] > INTRA_FRAME as i8 {
@@ -637,18 +637,18 @@ impl TileDecoder<'_, '_> {
}
// the above pass completes before the left pass reads samples; jobs keep that order
for (pass, cr, cc, x4, y4, pw, ph) in jobs {
- let ci = self.fs.mi.idx(cr, cc);
- let m = self.fs.mi.mv[ci][0];
+ let ci = self.t.mi.idx(cr, cc);
+ let m = self.t.mi.mv[ci][0];
let mv = [m.row as i32, m.col as i32];
- let ref_idx = self.fs.fh.ref_frame_idx[self.fs.mi.ref_frame[ci][0] as usize - LAST_FRAME] as i32;
+ let ref_idx = self.fs.fh.ref_frame_idx[self.t.mi.ref_frame[ci][0] as usize - LAST_FRAME] as i32;
let px = (x4 * 4) >> sx;
let py = (y4 * 4) >> sy;
let (stx, sty, sxs, sys) = self.mv_scaling(plane, ref_idx, px as i32, py as i32, mv);
- let filters = self.fs.mi.interp_filter[ci];
+ let filters = self.t.mi.interp_filter[ci];
let rnd = rounding(false, bd);
self.block_inter_prediction(plane, ref_idx, stx, sty, sxs, sys, pw, ph, filters, rnd, &mut obmc, &mut tmp);
let mask = get_mask(if pass == 0 { ph } else { pw });
- let pl = &mut self.fs.cur.planes[plane];
+ let pl = &mut self.t.cur.planes[plane];
for i in 0..ph {
for j in 0..pw {
let mm = if pass == 0 { mask[i] } else { mask[j] } as i32;
diff --git a/crates/av1/src/inter_info.rs b/crates/av1/src/inter_info.rs
index 7c4053e55..3bc132d1a 100644
--- a/crates/av1/src/inter_info.rs
+++ b/crates/av1/src/inter_info.rs
@@ -28,7 +28,7 @@ impl TileDecoder<'_, '_> {
pub(crate) fn inter_frame_mode_info_impl(&mut self) -> Result<()> {
self.b.use_intrabc = false;
let (r, c) = (self.b.mi_row, self.b.mi_col);
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let mut n = Neighbours {
left: if self.b.avail_l { mi.ref_frame[mi.idx(r, c - 1)] } else { [INTRA_FRAME as i8, -1] },
above: if self.b.avail_u { mi.ref_frame[mi.idx(r - 1, c)] } else { [INTRA_FRAME as i8, -1] },
@@ -72,7 +72,7 @@ impl TileDecoder<'_, '_> {
let mut seg = 7u8;
for y in 0..y_mis {
for x in 0..x_mis {
- let i = (self.b.mi_row + y) * self.fs.mi.cols + self.b.mi_col + x;
+ let i = (self.b.mi_row + y) * self.t.mi.cols + self.b.mi_col + x;
seg = seg.min(self.fs.prev_segment_ids[i]);
}
}
@@ -81,13 +81,13 @@ impl TileDecoder<'_, '_> {
fn set_seg_pred_context(&mut self, v: u8) {
for i in 0..self.b.bw4 {
- if self.b.mi_col + i < self.fs.above_seg_pred.len() {
- self.fs.above_seg_pred[self.b.mi_col + i] = v;
+ if self.b.mi_col + i < self.t.above_seg_pred.len() {
+ self.t.above_seg_pred[self.b.mi_col + i] = v;
}
}
for i in 0..self.b.bh4 {
- if self.b.mi_row + i < self.fs.left_seg_pred.len() {
- self.fs.left_seg_pred[self.b.mi_row + i] = v;
+ if self.b.mi_row + i < self.t.left_seg_pred.len() {
+ self.t.left_seg_pred[self.b.mi_row + i] = v;
}
}
}
@@ -110,7 +110,7 @@ impl TileDecoder<'_, '_> {
return;
}
if seg.temporal_update {
- let ctx = self.fs.left_seg_pred[self.b.mi_row] as usize + self.fs.above_seg_pred[self.b.mi_col] as usize;
+ let ctx = self.t.left_seg_pred[self.b.mi_row] as usize + self.t.above_seg_pred[self.b.mi_col] as usize;
let pred_flag = self.sd.read_symbol(&mut self.cdf.segment_id_predicted[ctx]);
if pred_flag == 1 {
self.b.segment_id = predicted;
@@ -138,7 +138,7 @@ impl TileDecoder<'_, '_> {
self.b.skip_mode = false;
} else {
let (r, c) = (self.b.mi_row, self.b.mi_col);
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let mut ctx = 0;
if self.b.avail_u {
ctx += mi.skip_mode[mi.idx(r - 1, c)] as usize;
@@ -490,7 +490,7 @@ impl TileDecoder<'_, '_> {
let mut left_type = 3u8;
let mut above_type = 3u8;
let (r, c) = (self.b.mi_row, self.b.mi_col);
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let rf0 = self.b.ref_frame[0];
if self.b.avail_l {
let i = mi.idx(r, c - 1);
@@ -718,7 +718,7 @@ impl TileDecoder<'_, '_> {
fn comp_group_idx_ctx(&self) -> usize {
let n = self.nb;
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let (r, c) = (self.b.mi_row, self.b.mi_col);
let mut ctx = 0;
if self.b.avail_u {
@@ -745,7 +745,7 @@ impl TileDecoder<'_, '_> {
let bck = crate::header::relative_dist(seq, fh.order_hints[self.b.ref_frame[1] as usize], fh.order_hint).abs();
let mut ctx = if fwd == bck { 3 } else { 0 };
let n = self.nb;
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let (r, c) = (self.b.mi_row, self.b.mi_col);
if self.b.avail_u {
if !n.above_single {
diff --git a/crates/av1/src/intra.rs b/crates/av1/src/intra.rs
index 4d68e09fb..893bb86f5 100644
--- a/crates/av1/src/intra.rs
+++ b/crates/av1/src/intra.rs
@@ -57,9 +57,9 @@ pub(crate) fn predict_intra(pl: &mut Plane, p: &IntraParams) {
above[EDGE..EDGE + n].iter_mut().for_each(|a| *a = v);
} else {
let above_limit = (p.max_x).min(x as i32 + if p.have_above_right { 2 * w as i32 } else { w as i32 } - 1);
- let row = pl.row(y - 1);
+ let row = pl.row_from(y - 1, x);
for i in 0..n {
- above[EDGE + i] = row[(above_limit.min(x as i32 + i as i32)) as usize] as i32;
+ above[EDGE + i] = row[(above_limit.min(x as i32 + i as i32)) as usize - x] as i32;
}
}
if !p.have_left && p.have_above {
@@ -117,7 +117,7 @@ pub(crate) fn predict_intra(pl: &mut Plane, p: &IntraParams) {
}
}
for i in 0..h {
- pl.row_mut(y + i)[x..x + w].copy_from_slice(&pred[i * w..i * w + w]);
+ pl.row_from_mut(y + i, x)[..w].copy_from_slice(&pred[i * w..i * w + w]);
}
}
diff --git a/crates/av1/src/lib.rs b/crates/av1/src/lib.rs
index fecb3cad5..43a002cb6 100644
--- a/crates/av1/src/lib.rs
+++ b/crates/av1/src/lib.rs
@@ -17,6 +17,7 @@ mod inter;
mod inter_info;
mod intra;
mod mvpred;
+mod par;
mod postfilter;
mod restoration;
mod spec_tables;
@@ -59,6 +60,8 @@ pub struct Picture {
pub transfer_characteristics: u8,
pub matrix_coefficients: u8,
pub full_range: bool,
+ /// Timestamp of the temporal unit that showed the picture ([`Decoder::decode_pts`]).
+ pub pts: i64,
}
impl Picture {
diff --git a/crates/av1/src/mvpred.rs b/crates/av1/src/mvpred.rs
index 734100dd1..a25e37450 100644
--- a/crates/av1/src/mvpred.rs
+++ b/crates/av1/src/mvpred.rs
@@ -188,7 +188,7 @@ impl TileDecoder<'_, '_> {
if !self.inside(mv_row, mv_col) {
break;
}
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let mut len = bw4.min(NUM_4X4_BLOCKS_WIDE[mi.mi_size[mi.idx(mv_row as usize, mv_col as usize)] as usize] as isize);
if delta_row.abs() > 1 {
len = len.max(2);
@@ -221,7 +221,7 @@ impl TileDecoder<'_, '_> {
if !self.inside(mv_row, mv_col) {
break;
}
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let mut len = bh4.min(NUM_4X4_BLOCKS_HIGH[mi.mi_size[mi.idx(mv_row as usize, mv_col as usize)] as usize] as isize);
if delta_col.abs() > 1 {
len = len.max(2);
@@ -238,7 +238,7 @@ impl TileDecoder<'_, '_> {
fn scan_point(&mut self, delta_row: isize, delta_col: isize, is_compound: bool) {
let mv_row = self.b.mi_row as isize + delta_row;
let mv_col = self.b.mi_col as isize + delta_col;
- if self.inside(mv_row, mv_col) && self.fs.mi.written[self.fs.mi.idx(mv_row as usize, mv_col as usize)] {
+ if self.inside(mv_row, mv_col) && self.t.mi.written[self.t.mi.idx(mv_row as usize, mv_col as usize)] {
self.add_ref_mv_candidate(mv_row as usize, mv_col as usize, is_compound, 4);
}
}
@@ -332,7 +332,7 @@ impl TileDecoder<'_, '_> {
}
fn add_ref_mv_candidate(&mut self, mv_row: usize, mv_col: usize, is_compound: bool, weight: u32) {
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let i = mi.idx(mv_row, mv_col);
if !mi.is_inter[i] {
return;
@@ -350,7 +350,7 @@ impl TileDecoder<'_, '_> {
}
fn search_stack(&mut self, mv_row: usize, mv_col: usize, cand_list: usize, weight: u32) {
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let i = mi.idx(mv_row, mv_col);
let cand_mode = mi.y_mode[i] as usize;
let cand_size = mi.mi_size[i] as usize;
@@ -378,7 +378,7 @@ impl TileDecoder<'_, '_> {
}
fn compound_search_stack(&mut self, mv_row: usize, mv_col: usize, weight: u32) {
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let i = mi.idx(mv_row, mv_col);
let mut cand = [[mi.mv[i][0].row as i32, mi.mv[i][0].col as i32], [mi.mv[i][1].row as i32, mi.mv[i][1].col as i32]];
let cand_mode = mi.y_mode[i] as usize;
@@ -443,7 +443,7 @@ impl TileDecoder<'_, '_> {
break;
}
self.add_extra_mv_candidate(mv_row as usize, mv_col as usize, is_compound);
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let sz = mi.mi_size[mi.idx(mv_row as usize, mv_col as usize)] as usize;
idx += if pass == 0 { NUM_4X4_BLOCKS_WIDE[sz] } else { NUM_4X4_BLOCKS_HIGH[sz] } as isize;
}
@@ -492,7 +492,7 @@ impl TileDecoder<'_, '_> {
}
fn add_extra_mv_candidate(&mut self, mv_row: usize, mv_col: usize, is_compound: bool) {
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let i = mi.idx(mv_row, mv_col);
let rfs = mi.ref_frame[i];
let mvs = mi.mv[i];
@@ -593,7 +593,7 @@ impl TileDecoder<'_, '_> {
/// has_overlappable_candidates( ) (7.10.3)
pub(crate) fn has_overlappable_candidates(&self) -> bool {
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let (mi_rows, mi_cols) = (self.fs.fh.mi_rows as usize, self.fs.fh.mi_cols as usize);
if self.b.avail_u {
let mut x4 = self.b.mi_col;
@@ -629,7 +629,7 @@ impl TileDecoder<'_, '_> {
let mut do_top_left = true;
let mut do_top_right = true;
if self.b.avail_u {
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let src_w = NUM_4X4_BLOCKS_WIDE[mi.mi_size[mi.idx(mi_row as usize - 1, mi_col as usize)] as usize] as isize;
if w4 <= src_w {
let col_offset = -(mi_col & (src_w - 1));
@@ -643,7 +643,7 @@ impl TileDecoder<'_, '_> {
} else {
let mut i = 0;
while i < w4.min(mi_cols - mi_col) {
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let src_w = NUM_4X4_BLOCKS_WIDE[mi.mi_size[mi.idx(mi_row as usize - 1, (mi_col + i) as usize)] as usize] as isize;
let step = w4.min(src_w);
self.add_sample(-1, i);
@@ -652,7 +652,7 @@ impl TileDecoder<'_, '_> {
}
}
if self.b.avail_l {
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let src_h = NUM_4X4_BLOCKS_HIGH[mi.mi_size[mi.idx(mi_row as usize, mi_col as usize - 1)] as usize] as isize;
if h4 <= src_h {
let row_offset = -(mi_row & (src_h - 1));
@@ -663,7 +663,7 @@ impl TileDecoder<'_, '_> {
} else {
let mut i = 0;
while i < h4.min(mi_rows - mi_row) {
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let src_h = NUM_4X4_BLOCKS_HIGH[mi.mi_size[mi.idx((mi_row + i) as usize, mi_col as usize - 1)] as usize] as isize;
let step = h4.min(src_h);
self.add_sample(i, -1);
@@ -691,7 +691,7 @@ impl TileDecoder<'_, '_> {
if !self.inside(mv_row, mv_col) {
return;
}
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let i = mi.idx(mv_row as usize, mv_col as usize);
if !mi.written[i] {
return;
diff --git a/crates/av1/src/par.rs b/crates/av1/src/par.rs
new file mode 100644
index 000000000..cab460d12
--- /dev/null
+++ b/crates/av1/src/par.rs
@@ -0,0 +1,72 @@
+//! Optional data parallelism (rayon behind the `threads` feature; sequential otherwise and on
+//! wasm32).
+
+#[cfg(feature = "threads")]
+use std::sync::Arc;
+
+/// A handle to the decoder's worker pool (or none: run on the calling thread).
+#[derive(Clone, Default)]
+pub(crate) struct Pool {
+ #[cfg(feature = "threads")]
+ pool: Option<Arc<rayon::ThreadPool>>,
+}
+
+impl Pool {
+ /// A pool of `threads` workers (sequential when `threads` <= 1, without the `threads`
+ /// feature, or on wasm32).
+ pub fn new(threads: usize) -> Pool {
+ #[cfg(feature = "threads")]
+ {
+ let pool = if threads > 1 && cfg!(not(target_arch = "wasm32")) {
+ rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|i| format!("av1-{i}")).build().ok().map(Arc::new)
+ } else {
+ None
+ };
+ Pool { pool }
+ }
+ #[cfg(not(feature = "threads"))]
+ {
+ let _ = threads;
+ Pool {}
+ }
+ }
+
+ pub fn is_parallel(&self) -> bool {
+ #[cfg(feature = "threads")]
+ {
+ self.pool.is_some()
+ }
+ #[cfg(not(feature = "threads"))]
+ {
+ false
+ }
+ }
+
+ /// `f(i, &mut items[i])` for every item, in parallel when possible; results in order.
+ pub fn map_mut<T: Send, R: Send>(&self, items: &mut [T], f: impl Fn(usize, &mut T) -> R + Sync + Send) -> Vec<R> {
+ #[cfg(feature = "threads")]
+ if let Some(pool) = &self.pool
+ && items.len() > 1
+ {
+ use rayon::prelude::*;
+ return pool.install(|| items.par_iter_mut().enumerate().map(|(i, t)| f(i, t)).collect());
+ }
+ items.iter_mut().enumerate().map(|(i, t)| f(i, t)).collect()
+ }
+
+ /// `f(i, chunk)` for the consecutive `chunk_len`-element chunks of `data`.
+ pub fn chunks<T: Send>(&self, data: &mut [T], chunk_len: usize, f: impl Fn(usize, &mut [T]) + Sync + Send) {
+ let chunk_len = chunk_len.max(1);
+ #[cfg(feature = "threads")]
+ if let Some(pool) = &self.pool
+ && data.len() > chunk_len
+ {
+ use rayon::prelude::*;
+ pool.install(|| data.par_chunks_mut(chunk_len).enumerate().for_each(|(i, c)| f(i, c)));
+ return;
+ }
+ for (i, c) in data.chunks_mut(chunk_len).enumerate() {
+ f(i, c);
+ }
+ }
+}
diff --git a/crates/av1/src/postfilter.rs b/crates/av1/src/postfilter.rs
index 24358c580..fd0ae8be1 100644
--- a/crates/av1/src/postfilter.rs
+++ b/crates/av1/src/postfilter.rs
@@ -5,7 +5,8 @@ use crate::spec_tables::*;
use crate::state::FrameState;
use crate::stats::{DecodeStats, Stage, Timer};
-pub(crate) fn apply(fs: &mut FrameState, stats: &mut DecodeStats) {
+/// The post-filters run on the frame worker; `_pool` is for row-parallel filtering (not yet used).
+pub(crate) fn apply(fs: &mut FrameState, stats: &mut DecodeStats, _pool: &crate::par::Pool) {
let mut t = Timer::start();
let lvl = fs.fh.lf.level;
if lvl[0] != 0 || lvl[1] != 0 {
diff --git a/crates/av1/src/restoration.rs b/crates/av1/src/restoration.rs
index 8701c924f..693e27284 100644
--- a/crates/av1/src/restoration.rs
+++ b/crates/av1/src/restoration.rs
@@ -104,7 +104,7 @@ pub(crate) fn loop_restoration(fs: &FrameState, cur: &FrameBuf, cdef: &FrameBuf)
let h = (4 >> sub_y).min(plane_end_y - y + 1);
if w > 0 && h > 0 {
let ui = (unit_row * unit_cols + unit_col) as usize;
- match fs.lr_type[plane][ui] {
+ match fs.lr.lr_type[plane][ui] {
t if t == RESTORE_WIENER as u8 => wiener(fs, &ctx, &mut lr.planes[plane], plane, ui, x, y, w, h, bd),
t if t == RESTORE_SGRPROJ as u8 => self_guided(fs, &ctx, &mut lr.planes[plane], plane, ui, x, y, w, h, bd),
_ => {}
@@ -122,7 +122,7 @@ pub(crate) fn loop_restoration(fs: &FrameState, cur: &FrameBuf, cdef: &FrameBuf)
fn wiener(fs: &FrameState, ctx: &LrCtx, out: &mut Plane, plane: usize, ui: usize, x: i32, y: i32, w: i32, h: i32, bd: u32) {
let round0: u32 = if bd == 12 { 5 } else { 3 };
let round1: u32 = if bd == 12 { 9 } else { 11 };
- let coef = &fs.lr_wiener[plane][ui];
+ let coef = &fs.lr.lr_wiener[plane][ui];
let mk = |c: &[i8; 3]| -> [i32; 7] {
let mut f = [0i32; 7];
f[3] = 128;
@@ -164,12 +164,12 @@ fn wiener(fs: &FrameState, ctx: &LrCtx, out: &mut Plane, plane: usize, ui: usize
#[allow(clippy::too_many_arguments)]
fn self_guided(fs: &FrameState, ctx: &LrCtx, out: &mut Plane, plane: usize, ui: usize, x: i32, y: i32, w: i32, h: i32, bd: u32) {
- let set = fs.lr_sgr_set[plane][ui] as usize;
+ let set = fs.lr.lr_sgr_set[plane][ui] as usize;
let mut flt0 = [[0i32; 4]; 4];
let mut flt1 = [[0i32; 4]; 4];
box_filter(ctx, x, y, w, h, set, 0, bd, &mut flt0);
box_filter(ctx, x, y, w, h, set, 1, bd, &mut flt1);
- let xqd = fs.lr_sgr_xqd[plane][ui];
+ let xqd = fs.lr.lr_sgr_xqd[plane][ui];
let w0 = xqd[0] as i32;
let w1 = xqd[1] as i32;
let w2 = (1 << SGRPROJ_PRJ_BITS) - w0 - w1;
diff --git a/crates/av1/src/state.rs b/crates/av1/src/state.rs
index b108ab14e..0073f3e99 100644
--- a/crates/av1/src/state.rs
+++ b/crates/av1/src/state.rs
@@ -1,46 +1,170 @@
//! Per-frame decoding state shared by the tiles and the post-filters.
+//!
+//! [`FrameShared`] holds what tiles only read (headers, references, projected motion field);
+//! [`TileState`] what a tile writes (reconstruction, mode info, per-block filter parameters,
+//! entropy contexts). With one tile the frame's own buffers move into the tile state and back;
+//! 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::decoder::RefFrame;
use crate::frame::{FrameBuf, MiInfo};
use crate::header::{FrameHeader, RefInfo, SequenceHeader};
use crate::spec_tables::*;
+use std::ops::{Deref, DerefMut};
use std::sync::Arc;
-pub(crate) struct FrameState {
+/// Read-only (during tile decoding) frame state.
+pub(crate) struct FrameShared {
pub seq: SequenceHeader,
pub fh: FrameHeader,
pub num_planes: usize,
pub ssx: usize,
pub ssy: usize,
pub bit_depth: u32,
+ pub lr_unit_rows: [usize; 3],
+ pub lr_unit_cols: [usize; 3],
+ pub cdef_cols: usize,
+ /// Reference slots (FrameStore and saved state) used by this frame.
+ pub refs: [Option<Arc<RefFrame>>; 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],
+ /// PrevSegmentIds (mi units).
+ pub prev_segment_ids: Vec<u8>,
+}
+
+impl FrameShared {
+ 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 };
+ SUBSAMPLED_SIZE[subsize][sx][sy] as usize
+ }
+}
+
+/// A byte per 4x4 unit of a plane (LoopfilterTxSizes), possibly for a region only.
+#[derive(Clone, Default)]
+pub(crate) struct Grid8 {
+ pub data: Vec<u8>,
+ pub ox: usize,
+ pub oy: usize,
+ pub stride: usize,
+ pub rows: usize,
+}
+
+impl Grid8 {
+ fn new(ox: usize, oy: usize, stride: usize, rows: usize) -> Grid8 {
+ Grid8 { data: vec![0; stride * rows], ox, oy, stride, rows }
+ }
+ #[inline]
+ pub fn get(&self, row: usize, col: usize) -> u8 {
+ self.data[(row - self.oy) * self.stride + col - self.ox]
+ }
+ /// Stores outside the grid are dropped (blocks reaching past the allocated margin).
+ #[inline]
+ pub fn set(&mut self, row: usize, col: usize, v: u8) {
+ if col >= self.ox && col < self.ox + self.stride && row >= self.oy && row < self.oy + self.rows {
+ self.data[(row - self.oy) * self.stride + col - self.ox] = v;
+ }
+ }
+ fn copy_into(&self, dst: &mut Grid8) {
+ for y in 0..self.rows {
+ let d = (self.oy + y - dst.oy) * dst.stride + self.ox - dst.ox;
+ dst.data[d..d + self.stride].copy_from_slice(&self.data[y * self.stride..(y + 1) * self.stride]);
+ }
+ }
+}
+
+/// Loop restoration parameters per unit.
+#[derive(Clone, Default)]
+pub(crate) struct LrUnits {
+ pub lr_type: [Vec<u8>; 3],
+ pub lr_wiener: [Vec<[[i8; 3]; 2]>; 3],
+ pub lr_sgr_set: [Vec<u8>; 3],
+ pub lr_sgr_xqd: [Vec<[i8; 2]>; 3],
+}
+
+/// What tile decoding writes.
+pub(crate) struct TileState {
pub cur: FrameBuf,
pub mi: MiInfo,
+ /// cdef_idx per 64x64 block (-1: not coded).
+ pub cdef: Vec<i8>,
+ /// LoopfilterTxSizes[ plane ][ row ][ col ] in 4x4 units of each plane.
+ pub lf_tx_size: [Grid8; 3],
+ pub lr: LrUnits,
+ /// LR units this tile coded (per plane), for merging.
+ pub lr_written: [Vec<usize>; 3],
pub above_level: [Vec<u8>; 3],
pub above_dc: [Vec<u8>; 3],
pub above_seg_pred: Vec<u8>,
pub left_level: [Vec<u8>; 3],
pub left_dc: [Vec<u8>; 3],
pub left_seg_pred: Vec<u8>,
- /// cdef_idx per 64x64 block.
- cdef: Vec<i8>,
- cdef_cols: usize,
- /// LoopfilterTxSizes[ plane ][ row ][ col ] in 4x4 units of each plane.
- pub lf_tx_size: [Vec<u8>; 3],
- pub lr_unit_rows: [usize; 3],
- pub lr_unit_cols: [usize; 3],
- pub lr_type: [Vec<u8>; 3],
- pub lr_wiener: [Vec<[[i8; 3]; 2]>; 3],
- pub lr_sgr_set: [Vec<u8>; 3],
- pub lr_sgr_xqd: [Vec<[i8; 2]>; 3],
/// TileIntraFrameYModeCdf (reset per tile).
pub intra_frame_y_mode_cdf: [[[u16; 14]; 5]; 5],
- /// Reference slots (FrameStore and saved state) at the start of this frame.
- pub refs: [Option<Arc<RefFrame>>; 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],
- /// PrevSegmentIds (mi units).
- pub prev_segment_ids: Vec<u8>,
+ cdef_cols: usize,
+}
+
+impl TileState {
+ fn with(cur: FrameBuf, mi: MiInfo, cdef: Vec<i8>, lf_tx_size: [Grid8; 3], lr: LrUnits, cdef_cols: usize) -> TileState {
+ let (mi_cols, mi_rows) = (mi.cols, mi.rows);
+ TileState {
+ cur,
+ mi,
+ cdef,
+ lf_tx_size,
+ lr,
+ lr_written: Default::default(),
+ above_level: std::array::from_fn(|_| vec![0; mi_cols + 64]),
+ above_dc: std::array::from_fn(|_| vec![0; mi_cols + 64]),
+ above_seg_pred: vec![0; mi_cols + 64],
+ left_level: std::array::from_fn(|_| vec![0; mi_rows + 64]),
+ left_dc: std::array::from_fn(|_| vec![0; mi_rows + 64]),
+ left_seg_pred: vec![0; mi_rows + 64],
+ intra_frame_y_mode_cdf: DEFAULT_INTRA_FRAME_Y_MODE_CDF,
+ cdef_cols,
+ }
+ }
+
+ #[inline]
+ pub fn cdef_idx(&self, r: usize, c: usize) -> i8 {
+ self.cdef[(r >> 4) * self.cdef_cols + (c >> 4)]
+ }
+
+ #[inline]
+ pub fn set_cdef_idx(&mut self, r: usize, c: usize, v: i8) {
+ let i = (r >> 4) * self.cdef_cols + (c >> 4);
+ if i < self.cdef.len() {
+ self.cdef[i] = v;
+ }
+ }
+
+ #[inline]
+ pub fn set_lf_tx_size(&mut self, plane: usize, row: usize, col: usize, v: u8) {
+ self.lf_tx_size[plane].set(row, col, v);
+ }
+}
+
+pub(crate) struct FrameState {
+ pub sh: FrameShared,
+ pub cur: FrameBuf,
+ pub mi: MiInfo,
+ cdef: Vec<i8>,
+ lf_tx_size: [Grid8; 3],
+ pub lr: LrUnits,
+}
+
+impl Deref for FrameState {
+ type Target = FrameShared;
+ fn deref(&self) -> &FrameShared {
+ &self.sh
+ }
+}
+
+impl DerefMut for FrameState {
+ fn deref_mut(&mut self) -> &mut FrameShared {
+ &mut self.sh
+ }
}
fn count_units_in_frame(unit_size: usize, frame_size: usize) -> usize {
@@ -58,10 +182,7 @@ impl FrameState {
let cdef_rows = mi_rows.div_ceil(16) + 2;
let mut lr_unit_rows = [0; 3];
let mut lr_unit_cols = [0; 3];
- let mut lr_type: [Vec<u8>; 3] = Default::default();
- let mut lr_wiener: [Vec<[[i8; 3]; 2]>; 3] = Default::default();
- let mut lr_sgr_set: [Vec<u8>; 3] = Default::default();
- let mut lr_sgr_xqd: [Vec<[i8; 2]>; 3] = Default::default();
+ let mut lr = LrUnits::default();
for plane in 0..c.num_planes {
if fh.lr.frame_restoration_type[plane] == RESTORE_NONE as u8 {
continue;
@@ -72,72 +193,102 @@ impl FrameState {
lr_unit_rows[plane] = count_units_in_frame(unit, (fh.frame_height as usize + sub_y) >> sub_y);
lr_unit_cols[plane] = count_units_in_frame(unit, (fh.upscaled_width as usize + sub_x) >> sub_x);
let n = lr_unit_rows[plane] * lr_unit_cols[plane];
- lr_type[plane] = vec![RESTORE_NONE as u8; n];
- lr_wiener[plane] = vec![[[0; 3]; 2]; n];
- lr_sgr_set[plane] = vec![0; n];
- lr_sgr_xqd[plane] = vec![[0; 2]; n];
+ lr.lr_type[plane] = vec![RESTORE_NONE as u8; n];
+ lr.lr_wiener[plane] = vec![[[0; 3]; 2]; n];
+ lr.lr_sgr_set[plane] = vec![0; n];
+ lr.lr_sgr_xqd[plane] = vec![[0; 2]; n];
}
FrameState {
- seq: seq.clone(),
- fh: fh.clone(),
- num_planes: c.num_planes,
- ssx,
- ssy,
- bit_depth: c.bit_depth as u32,
+ sh: FrameShared {
+ seq: seq.clone(),
+ fh: fh.clone(),
+ num_planes: c.num_planes,
+ ssx,
+ ssy,
+ bit_depth: c.bit_depth as u32,
+ lr_unit_rows,
+ lr_unit_cols,
+ cdef_cols,
+ refs: Default::default(),
+ ref_info: Default::default(),
+ motion_field: Default::default(),
+ prev_segment_ids: vec![0; mi_cols * mi_rows],
+ },
cur,
mi: MiInfo::new(mi_cols, mi_rows),
- above_level: std::array::from_fn(|_| vec![0; mi_cols + 64]),
- above_dc: std::array::from_fn(|_| vec![0; mi_cols + 64]),
- above_seg_pred: vec![0; mi_cols + 64],
- left_level: std::array::from_fn(|_| vec![0; mi_rows + 64]),
- left_dc: std::array::from_fn(|_| vec![0; mi_rows + 64]),
- left_seg_pred: vec![0; mi_rows + 64],
cdef: vec![-1; cdef_cols * cdef_rows],
- cdef_cols,
- lf_tx_size: std::array::from_fn(|_| vec![0; (mi_cols + 32) * (mi_rows + 32)]),
- lr_unit_rows,
- lr_unit_cols,
- lr_type,
- lr_wiener,
- lr_sgr_set,
- lr_sgr_xqd,
- intra_frame_y_mode_cdf: DEFAULT_INTRA_FRAME_Y_MODE_CDF,
- refs: Default::default(),
- ref_info: Default::default(),
- motion_field: Default::default(),
- prev_segment_ids: vec![0; mi_cols * mi_rows],
+ lf_tx_size: std::array::from_fn(|_| Grid8::new(0, 0, mi_cols + 32, mi_rows + 32)),
+ lr,
}
}
- 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 };
- SUBSAMPLED_SIZE[subsize][sx][sy] as usize
- }
-
#[inline]
pub fn cdef_idx(&self, r: usize, c: usize) -> i8 {
self.cdef[(r >> 4) * self.cdef_cols + (c >> 4)]
}
#[inline]
- pub fn set_cdef_idx(&mut self, r: usize, c: usize, v: i8) {
- let i = (r >> 4) * self.cdef_cols + (c >> 4);
- if i < self.cdef.len() {
- self.cdef[i] = v;
- }
+ pub fn lf_tx_size(&self, plane: usize, row: usize, col: usize) -> usize {
+ self.lf_tx_size[plane].get(row, col) as usize
}
- #[inline]
- pub fn lf_tx_size(&self, plane: usize, row: usize, col: usize) -> usize {
- self.lf_tx_size[plane][row * (self.mi.cols + 32) + col] as usize
+ /// Move the frame's buffers into a tile state covering the whole frame.
+ pub fn take_tile_state(&mut self) -> TileState {
+ TileState::with(
+ std::mem::take(&mut self.cur),
+ std::mem::take(&mut self.mi),
+ std::mem::take(&mut self.cdef),
+ std::mem::take(&mut self.lf_tx_size),
+ std::mem::take(&mut self.lr),
+ self.cdef_cols,
+ )
}
- #[inline]
- pub fn set_lf_tx_size(&mut self, plane: usize, row: usize, col: usize, v: u8) {
- let stride = self.mi.cols + 32;
- if col < stride && row < self.mi.rows + 32 {
- self.lf_tx_size[plane][row * stride + col] = v;
+ /// Return the buffers taken by [`FrameState::take_tile_state`].
+ pub fn put_tile_state(&mut self, t: TileState) {
+ self.cur = t.cur;
+ self.mi = t.mi;
+ self.cdef = t.cdef;
+ self.lf_tx_size = t.lf_tx_size;
+ self.lr = t.lr;
+ }
+
+ /// Private buffers for the tile covering mode info rows [r0, r1) x columns [c0, c1); tiles
+ /// on the right / bottom frame edge also cover the allocation margins.
+ pub fn tile_state(&self, r0: usize, r1: usize, c0: usize, c1: usize) -> TileState {
+ let (mi_cols, mi_rows) = (self.mi.cols, self.mi.rows);
+ let x1 = if c1 >= mi_cols { usize::MAX } else { c1 * 4 };
+ let y1 = if r1 >= mi_rows { usize::MAX } else { r1 * 4 };
+ let cur = self.cur.region_like(c0 * 4, r0 * 4, x1, y1);
+ let mi = MiInfo::region(mi_cols, mi_rows, c0, r0, c1 - c0, r1 - r0);
+ let lf = std::array::from_fn(|p| {
+ let (sx, sy) = if p == 0 { (0, 0) } else { (self.ssx, self.ssy) };
+ let full = &self.lf_tx_size[p];
+ let (gx0, gy0) = (c0 >> sx, r0 >> sy);
+ let gx1 = if c1 >= mi_cols { full.stride } else { c1 >> sx };
+ let gy1 = if r1 >= mi_rows { full.rows } else { r1 >> sy };
+ Grid8::new(gx0, gy0, gx1 - gx0, gy1 - gy0)
+ });
+ TileState::with(cur, mi, vec![-1; self.cdef.len()], lf, self.lr.clone(), self.cdef_cols)
+ }
+
+ /// Copy a tile's private buffers into the frame.
+ 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]);
+ 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];
+ self.lr.lr_wiener[p][u] = t.lr.lr_wiener[p][u];
+ self.lr.lr_sgr_set[p][u] = t.lr.lr_sgr_set[p][u];
+ self.lr.lr_sgr_xqd[p][u] = t.lr.lr_sgr_xqd[p][u];
+ }
+ }
+ t.mi.copy_into(&mut self.mi);
+ for (d, &s) in self.cdef.iter_mut().zip(&t.cdef) {
+ if s != -1 {
+ *d = s;
+ }
}
}
}
diff --git a/crates/av1/src/tile.rs b/crates/av1/src/tile.rs
index 14bce6903..13278b019 100644
--- a/crates/av1/src/tile.rs
+++ b/crates/av1/src/tile.rs
@@ -7,7 +7,7 @@ use crate::frame::{MiInfo, Mv};
use crate::header::{FrameHeader, NONE, SequenceHeader};
use crate::intra::{IntraParams, is_directional_mode, predict_intra, round2_signed};
use crate::spec_tables::*;
-use crate::state::FrameState;
+use crate::state::{FrameShared, TileState};
use crate::symbol::SymbolDecoder;
use crate::transform::inverse_transform_2d;
@@ -69,7 +69,8 @@ pub(crate) struct Block {
/// Decoder for one tile.
pub(crate) struct TileDecoder<'a, 'f> {
- pub fs: &'f mut FrameState,
+ pub fs: &'f FrameShared,
+ pub t: &'f mut TileState,
pub sd: SymbolDecoder<'a>,
pub cdf: Box<Cdfs>,
pub mi_row_start: usize,
@@ -111,7 +112,7 @@ fn block_height(bs: usize) -> usize {
}
impl<'a, 'f> TileDecoder<'a, 'f> {
- pub fn new(fs: &'f mut FrameState, data: &'a [u8], cdf: Box<Cdfs>, tile_row: usize, tile_col: usize) -> Self {
+ pub fn new(fs: &'f FrameShared, t: &'f mut TileState, data: &'a [u8], cdf: Box<Cdfs>, tile_row: usize, tile_col: usize) -> Self {
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);
@@ -119,6 +120,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
let q = fs.fh.quant.base_q_idx as i32;
TileDecoder {
fs,
+ t,
sd: SymbolDecoder::new(data, disable),
cdf,
mi_row_start: rs,
@@ -162,12 +164,12 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
/// decode_tile( )
pub fn decode_tile(&mut self) -> Result<()> {
// clear_above_context( )
- let fs = &mut *self.fs;
+ let t = &mut *self.t;
for p in 0..3 {
- fs.above_level[p].iter_mut().for_each(|v| *v = 0);
- fs.above_dc[p].iter_mut().for_each(|v| *v = 0);
+ t.above_level[p].fill(0);
+ t.above_dc[p].fill(0);
}
- fs.above_seg_pred.iter_mut().for_each(|v| *v = 0);
+ t.above_seg_pred.fill(0);
self.delta_lf = [0; 4];
for plane in 0..self.fs.num_planes {
for pass in 0..2 {
@@ -181,12 +183,12 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
let mut r = self.mi_row_start;
while r < self.mi_row_end {
// clear_left_context( )
- let fs = &mut *self.fs;
+ let t = &mut *self.t;
for p in 0..3 {
- fs.left_level[p].iter_mut().for_each(|v| *v = 0);
- fs.left_dc[p].iter_mut().for_each(|v| *v = 0);
+ t.left_level[p].fill(0);
+ t.left_dc[p].fill(0);
}
- fs.left_seg_pred.iter_mut().for_each(|v| *v = 0);
+ t.left_seg_pred.fill(0);
let mut c = self.mi_col_start;
while c < self.mi_col_end {
self.read_deltas = self.fh().delta_q_present;
@@ -202,12 +204,12 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
}
fn clear_cdef(&mut self, r: usize, c: usize) {
- let fs = &mut *self.fs;
- fs.set_cdef_idx(r, c, -1);
- if fs.seq.use_128x128_superblock {
- fs.set_cdef_idx(r, c + 16, -1);
- fs.set_cdef_idx(r + 16, c, -1);
- fs.set_cdef_idx(r + 16, c + 16, -1);
+ let t = &mut *self.t;
+ t.set_cdef_idx(r, c, -1);
+ if self.fs.seq.use_128x128_superblock {
+ t.set_cdef_idx(r, c + 16, -1);
+ t.set_cdef_idx(r + 16, c, -1);
+ t.set_cdef_idx(r + 16, c + 16, -1);
}
}
@@ -254,7 +256,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
PARTITION_NONE
} else {
let bsl = MI_WIDTH_LOG2[bsize] as usize;
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let above = avail_u && (MI_WIDTH_LOG2[mi.mi_size[mi.idx(r - 1, c)] as usize] as usize) < bsl;
let left = avail_l && (MI_HEIGHT_LOG2[mi.mi_size[mi.idx(r, c - 1)] as usize] as usize) < bsl;
let ctx = left as usize * 2 + above as usize;
@@ -426,7 +428,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
let b = &self.b;
let is_compound = b.ref_frame[1] > INTRA_FRAME as i8;
{
- let mi = &mut self.fs.mi;
+ let mi = &mut self.t.mi;
let rows = b.bh4.min(mi.rows.saturating_sub(r));
let cols = b.bw4.min(mi.cols.saturating_sub(c));
let set_uv = b.ref_frame[0] == INTRA_FRAME as i8 && b.has_chroma;
@@ -459,7 +461,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
self.residual()?;
let b = &self.b;
let delta_lf = self.delta_lf;
- let mi = &mut self.fs.mi;
+ let mi = &mut self.t.mi;
let rows = b.bh4.min(mi.rows.saturating_sub(r));
let cols = b.bw4.min(mi.cols.saturating_sub(c));
let dlf = [delta_lf[0] as i8, delta_lf[1] as i8, delta_lf[2] as i8, delta_lf[3] as i8];
@@ -489,12 +491,12 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
let sub_x = if plane > 0 { ssx } else { 0 };
let sub_y = if plane > 0 { ssy } else { 0 };
for i in (b.mi_col >> sub_x)..((b.mi_col + b.bw4) >> sub_x) {
- self.fs.above_level[plane][i] = 0;
- self.fs.above_dc[plane][i] = 0;
+ self.t.above_level[plane][i] = 0;
+ self.t.above_dc[plane][i] = 0;
}
for i in (b.mi_row >> sub_y)..((b.mi_row + b.bh4) >> sub_y) {
- self.fs.left_level[plane][i] = 0;
- self.fs.left_dc[plane][i] = 0;
+ self.t.left_level[plane][i] = 0;
+ self.t.left_dc[plane][i] = 0;
}
}
}
@@ -530,15 +532,15 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
return Ok(());
}
self.b.is_inter = false;
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let (r, c) = (self.b.mi_row, self.b.mi_col);
let above = if self.b.avail_u { mi.y_mode[mi.idx(r - 1, c)] as usize } else { DC_PRED };
let left = if self.b.avail_l { mi.y_mode[mi.idx(r, c - 1)] as usize } else { DC_PRED };
let actx = INTRA_MODE_CONTEXT[above] as usize;
let lctx = INTRA_MODE_CONTEXT[left] as usize;
- let mut cdf = self.fs.intra_frame_y_mode_cdf[actx][lctx];
+ let mut cdf = self.t.intra_frame_y_mode_cdf[actx][lctx];
self.b.y_mode = self.sd.read_symbol(&mut cdf);
- self.fs.intra_frame_y_mode_cdf[actx][lctx] = cdf;
+ self.t.intra_frame_y_mode_cdf[actx][lctx] = cdf;
self.intra_angle_info_y();
if self.b.has_chroma {
self.read_uv_mode();
@@ -616,7 +618,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
pub(crate) fn read_segment_id(&mut self) {
let (r, c) = (self.b.mi_row, self.b.mi_col);
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let prev_ul = if self.b.avail_u && self.b.avail_l { mi.segment_id[mi.idx(r - 1, c - 1)] as i32 } else { -1 };
let prev_u = if self.b.avail_u { mi.segment_id[mi.idx(r - 1, c)] as i32 } else { -1 };
let prev_l = if self.b.avail_l { mi.segment_id[mi.idx(r, c - 1)] as i32 } else { -1 };
@@ -654,7 +656,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
self.b.skip = true;
} else {
let (r, c) = (self.b.mi_row, self.b.mi_col);
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let mut ctx = 0;
if self.b.avail_u {
ctx += mi.skip[mi.idx(r - 1, c)] as usize;
@@ -675,7 +677,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
let mask = !(cdef_size4 - 1);
let r = self.b.mi_row & mask;
let c = self.b.mi_col & mask;
- if self.fs.cdef_idx(r, c) == -1 {
+ if self.t.cdef_idx(r, c) == -1 {
let bits = fh.cdef.bits;
let v = self.sd.read_literal(bits) as i8;
let w4 = self.b.bw4;
@@ -684,7 +686,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
while i < r + h4 {
let mut j = c;
while j < c + w4 {
- self.fs.set_cdef_idx(i, j, v);
+ self.t.set_cdef_idx(i, j, v);
j += cdef_size4;
}
i += cdef_size4;
@@ -757,7 +759,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
let bd = self.fs.bit_depth;
let (r, c) = (self.b.mi_row, self.b.mi_col);
if self.b.y_mode == DC_PRED {
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let mut ctx = 0;
if self.b.avail_u && mi.palette_size[0][mi.idx(r - 1, c)] > 0 {
ctx += 1;
@@ -866,7 +868,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
fn get_palette_cache(&self, plane: usize) -> Vec<u16> {
let (r, c) = (self.b.mi_row, self.b.mi_col);
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let above_n = if (r * 4) % 64 != 0 { mi.palette_size[plane][mi.idx(r - 1, c)] as usize } else { 0 };
let left_n = if self.b.avail_l { mi.palette_size[plane][mi.idx(r, c - 1)] as usize } else { 0 };
let above: &[u16] = if above_n > 0 { &mi.palette_colors[plane][mi.idx(r - 1, c)][..above_n] } else { &[] };
@@ -1003,7 +1005,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
let allow = !b.skip || !b.is_inter;
self.read_tx_size(allow);
let (r0, c0, ts) = (self.b.mi_row, self.b.mi_col, self.b.tx_size as u8);
- let mi = &mut self.fs.mi;
+ let mi = &mut self.t.mi;
for row in r0..(r0 + bh4).min(mi.rows) {
for col in c0..(c0 + bw4).min(mi.cols) {
let i = mi.idx(row, col);
@@ -1038,7 +1040,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
fn tx_depth_ctx(&self, max_rect: usize) -> usize {
let (r, c) = (self.b.mi_row, self.b.mi_col);
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let max_w = TX_WIDTH[max_rect] as usize;
let max_h = TX_HEIGHT[max_rect] as usize;
let above_w = if self.b.avail_u && mi.is_inter[mi.idx(r - 1, c)] {
@@ -1059,7 +1061,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
}
fn get_above_tx_width(&self, row: usize, col: usize) -> usize {
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
if row == self.b.mi_row {
if !self.b.avail_u {
return 64;
@@ -1071,7 +1073,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
}
fn get_left_tx_height(&self, row: usize, col: usize) -> usize {
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
if col == self.b.mi_col {
if !self.b.avail_l {
return 64;
@@ -1115,7 +1117,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
i += sh;
}
} else {
- let mi = &mut self.fs.mi;
+ let mi = &mut self.t.mi;
for i in 0..h4 {
for j in 0..w4 {
if row + i < mi.rows && col + j < mi.cols {
@@ -1183,7 +1185,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
enable_intra_edge_filter: self.fs.seq.enable_intra_edge_filter,
filter_type: if is_directional_mode(mode) && self.fs.seq.enable_intra_edge_filter { self.get_filter_type(plane) } else { false },
};
- predict_intra(&mut self.fs.cur.planes[plane], &params);
+ predict_intra(&mut self.t.cur.planes[plane], &params);
}
let mut pred_w = block_width(self.b.mi_size) >> sub_x;
let mut pred_h = block_height(self.b.mi_size) >> sub_y;
@@ -1191,7 +1193,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
for r in 0..(n4h << sub_y) {
for c in 0..(n4w << sub_x) {
let (rr, cc) = (cand_row + r, cand_col + c);
- if rr < self.fs.mi.rows && cc < self.fs.mi.cols && self.fs.mi.ref_frame[self.fs.mi.idx(rr, cc)][0] == INTRA_FRAME as i8 {
+ if rr < self.t.mi.rows && cc < self.t.mi.cols && self.t.mi.ref_frame[self.t.mi.idx(rr, cc)][0] == INTRA_FRAME as i8 {
some_use_intra = true;
}
}
@@ -1288,7 +1290,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
}
let row = start_y >> 2;
let col = start_x >> 2;
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let luma_tx = mi.inter_tx_size[mi.idx(row, col)] as usize;
let lw = TX_WIDTH[luma_tx] as usize;
let lh = TX_HEIGHT[luma_tx] as usize;
@@ -1370,7 +1372,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
enable_intra_edge_filter: self.fs.seq.enable_intra_edge_filter,
filter_type,
};
- predict_intra(&mut self.fs.cur.planes[plane], &params);
+ predict_intra(&mut self.t.cur.planes[plane], &params);
if is_cfl {
self.predict_cfl(plane, start_x, start_y, tx_sz);
}
@@ -1390,7 +1392,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
for j in 0..step_x {
let rr = (row >> sub_y) + i;
let cc = (col >> sub_x) + j;
- self.fs.set_lf_tx_size(plane, rr, cc, tx_sz as u8);
+ self.t.set_lf_tx_size(plane, rr, cc, tx_sz as u8);
let by = (sub_block_mi_row >> sub_y) + i;
let bx = (sub_block_mi_col >> sub_x) + j;
if by + 1 < 35 && bx + 1 < 35 {
@@ -1404,7 +1406,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
pub(crate) fn get_filter_type(&self, plane: usize) -> bool {
let (ssx, ssy) = (self.fs.ssx, self.fs.ssy);
let b = &self.b;
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
let is_smooth = |row: usize, col: usize| -> bool {
let i = mi.idx(row, col);
let mode = if plane == 0 {
@@ -1457,7 +1459,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
_ => self.b.palette_colors_v,
};
let map = if plane == 0 { &self.color_map_y } else { &self.color_map_uv };
- let pl = &mut self.fs.cur.planes[plane];
+ let pl = &mut self.t.cur.planes[plane];
for i in 0..h {
for j in 0..w {
let idx = map[(y * 4 + i) * 64 + x * 4 + j] as usize;
@@ -1475,7 +1477,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
let mut l = [0i32; 32 * 32];
let mut avg: i64 = 0;
{
- let luma = &self.fs.cur.planes[0];
+ let luma = &self.t.cur.planes[0];
for i in 0..h {
let ly = ((start_y + i) << sub_y).min(self.b.max_luma_h - (1 << sub_y));
for j in 0..w {
@@ -1494,7 +1496,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
}
let shift = TX_WIDTH_LOG2[tx_sz] as u32 + TX_HEIGHT_LOG2[tx_sz] as u32;
let avg = ((avg + (1i64 << (shift - 1))) >> shift) as i32;
- let pl = &mut self.fs.cur.planes[plane];
+ let pl = &mut self.t.cur.planes[plane];
for i in 0..h {
for j in 0..w {
let dc = pl.at(start_x + j, start_y + i) as i32;
@@ -1540,7 +1542,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
return DCT_DCT;
}
let set = self.get_tx_set(tx_sz);
- let mi = &self.fs.mi;
+ let mi = &self.t.mi;
if plane == 0 {
return mi.tx_type[mi.idx(block_y, block_x)] as usize;
}
@@ -1587,7 +1589,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
}
fn set_tx_types(&mut self, x4: usize, y4: usize, tx_sz: usize, tx_type: usize) {
- let mi = &mut self.fs.mi;
+ let mi = &mut self.t.mi;
for i in 0..(TX_WIDTH[tx_sz] as usize >> 2) {
for j in 0..(TX_HEIGHT[tx_sz] as usize >> 2) {
if y4 + j < mi.rows && x4 + i < mi.cols {
@@ -1782,15 +1784,15 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
cul_level = cul_level.min(63);
}
for i in 0..w4 {
- if x4 + i < self.fs.above_level[plane].len() {
- self.fs.above_level[plane][x4 + i] = cul_level as u8;
- self.fs.above_dc[plane][x4 + i] = dc_category;
+ if x4 + i < self.t.above_level[plane].len() {
+ self.t.above_level[plane][x4 + i] = cul_level as u8;
+ self.t.above_dc[plane][x4 + i] = dc_category;
}
}
for i in 0..h4 {
- if y4 + i < self.fs.left_level[plane].len() {
- self.fs.left_level[plane][y4 + i] = cul_level as u8;
- self.fs.left_dc[plane][y4 + i] = dc_category;
+ if y4 + i < self.t.left_level[plane].len() {
+ self.t.left_level[plane][y4 + i] = cul_level as u8;
+ self.t.left_dc[plane][y4 + i] = dc_category;
}
}
eob
@@ -1808,8 +1810,8 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
let bsize = self.fs.plane_residual_size(self.b.mi_size, plane);
let bw = block_width(bsize);
let bh = block_height(bsize);
- let al = &self.fs.above_level[plane];
- let ll = &self.fs.left_level[plane];
+ let al = &self.t.above_level[plane];
+ let ll = &self.t.left_level[plane];
if plane == 0 {
let mut top = 0u32;
let mut left = 0u32;
@@ -1839,8 +1841,8 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
6
}
} else {
- let ad = &self.fs.above_dc[plane];
- let ld = &self.fs.left_dc[plane];
+ let ad = &self.t.above_dc[plane];
+ let ld = &self.t.left_dc[plane];
let mut above = 0u8;
let mut left = 0u8;
for i in 0..w4 {
@@ -1874,7 +1876,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
let mut dc_sign = 0i32;
for k in 0..w4 {
if x4 + k < max_x4 {
- match self.fs.above_dc[plane][x4 + k] {
+ match self.t.above_dc[plane][x4 + k] {
1 => dc_sign -= 1,
2 => dc_sign += 1,
_ => {}
@@ -1883,7 +1885,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
}
for k in 0..h4 {
if y4 + k < max_y4 {
- match self.fs.left_dc[plane][y4 + k] {
+ match self.t.left_dc[plane][y4 + k] {
1 => dc_sign -= 1,
2 => dc_sign += 1,
_ => {}
@@ -1952,11 +1954,11 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
}
let lossless = self.b.lossless;
inverse_transform_2d(&self.dequant, &mut self.residual, tx_sz, t, lossless, bd);
- let pl = &mut self.fs.cur.planes[plane];
+ let pl = &mut self.t.cur.planes[plane];
let max = (1i32 << bd) - 1;
for i in 0..h {
let yy = if flip_ud { h - i - 1 } else { i };
- let row = &mut pl.row_mut(y + yy)[x..x + w];
+ let row = &mut pl.row_from_mut(y + yy, x)[..w];
let res = &self.residual[i * w..i * w + w];
if flip_lr {
for (o, &r) in row.iter_mut().rev().zip(res) {
@@ -2015,27 +2017,28 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
}
};
let idx = unit_row * self.fs.lr_unit_cols[plane] + unit_col;
- self.fs.lr_type[plane][idx] = rtype;
+ self.t.lr.lr_type[plane][idx] = rtype;
+ self.t.lr_written[plane].push(idx);
if rtype == RESTORE_WIENER as u8 {
const MIN: [i32; 3] = [-5, -23, -17];
const MAX: [i32; 3] = [10, 8, 46];
const K: [u32; 3] = [1, 2, 3];
for pass in 0..2 {
let first = if plane > 0 {
- self.fs.lr_wiener[plane][idx][pass][0] = 0;
+ self.t.lr.lr_wiener[plane][idx][pass][0] = 0;
1
} else {
0
};
for j in first..3 {
let v = self.decode_signed_subexp_with_ref_bool(MIN[j], MAX[j] + 1, K[j], self.ref_lr_wiener[plane][pass][j]);
- self.fs.lr_wiener[plane][idx][pass][j] = v as i8;
+ self.t.lr.lr_wiener[plane][idx][pass][j] = v as i8;
self.ref_lr_wiener[plane][pass][j] = v;
}
}
} else if rtype == RESTORE_SGRPROJ as u8 {
let set = self.sd.read_literal(SGRPROJ_PARAMS_BITS as u32) as usize;
- self.fs.lr_sgr_set[plane][idx] = set as u8;
+ self.t.lr.lr_sgr_set[plane][idx] = set as u8;
const MIN: [i32; 2] = [-96, -32];
const MAX: [i32; 2] = [31, 95];
for i in 0..2 {
@@ -2047,7 +2050,7 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
} else {
0
};
- self.fs.lr_sgr_xqd[plane][idx][i] = v as i8;
+ self.t.lr.lr_sgr_xqd[plane][idx][i] = v as i8;
self.ref_sgr_xqd[plane][i] = v;
}
}
diff --git a/crates/av1/tests/common/mod.rs b/crates/av1/tests/common/mod.rs
index 2132692f7..daa9105a0 100644
--- a/crates/av1/tests/common/mod.rs
+++ b/crates/av1/tests/common/mod.rs
@@ -82,14 +82,20 @@ pub fn reference(ff: &Path, path: &Path, pix_fmt: &str) -> Vec<u16> {
}
}
-/// Decode every frame of an IVF file with our decoder.
+/// Decode every frame of an IVF file with our decoder (all cores).
pub fn decode_all(path: &Path) -> Result<Vec<Picture>, String> {
- let mut dec = Decoder::new();
+ decode_all_threads(path, std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1))
+}
+
+/// Decode every frame of an IVF file with a decoder using `threads` threads.
+pub fn decode_all_threads(path: &Path, threads: usize) -> Result<Vec<Picture>, String> {
+ let mut dec = Decoder::with_threads(threads);
let mut pics = Vec::new();
for (i, f) in ivf_frames(path).iter().enumerate() {
- let p = dec.decode(f).map_err(|e| format!("frame {i}: {e}"))?;
+ let p = dec.decode_pts(f, i as i64).map_err(|e| format!("frame {i}: {e}"))?;
pics.extend(p);
}
+ pics.extend(dec.flush_result().map_err(|e| format!("flush: {e}"))?);
Ok(pics)
}
@@ -159,7 +165,14 @@ pub fn check_bit_exact(ff: &Path, spec: &Spec) {
/// Decode an IVF file and compare every frame with libdav1d; panics with details on mismatch.
pub fn check_file(ff: &Path, name: &str, path: &Path) {
- let pics = decode_all(path).unwrap_or_else(|e| panic!("{name}: {e}"));
+ let pics = decode_all_threads(path, 1).unwrap_or_else(|e| panic!("{name}: {e}"));
+ // Tile, post-filter and frame threading must give the same pictures.
+ let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1).max(4);
+ let mt = decode_all_threads(path, threads).unwrap_or_else(|e| panic!("{name} ({threads} threads): {e}"));
+ assert_eq!(mt.len(), pics.len(), "{name}: frame count with {threads} threads");
+ for (i, (a, b)) in pics.iter().zip(&mt).enumerate() {
+ assert!(a == b, "{name}: frame {i} differs with {threads} threads");
+ }
assert!(!pics.is_empty(), "{name}: no frames");
let raw = reference(ff, path, pix_fmt_for(&pics[0]));
let per = picture_samples(&pics[0]);
diff --git a/crates/av1/tests/oracle_inter.rs b/crates/av1/tests/oracle_inter.rs
index abfd63d7d..80e78e45b 100644
--- a/crates/av1/tests/oracle_inter.rs
+++ b/crates/av1/tests/oracle_inter.rs
@@ -39,3 +39,37 @@ fn inter_gops() {
check_bit_exact(&ff, &s);
}
}
+
+/// Several tiles (decoded in parallel into private buffers, then merged).
+fn specs_tiles() -> Vec<Spec> {
+ let p = |preset: &'static str, params: &'static str| -> Vec<&'static str> { vec!["-preset", preset, "-crf", "32", "-svtav1-params", params] };
+ vec![
+ Spec::new("inter_tiles_4x2", "testsrc2=s=1280x720:r=25,noise=alls=4:allf=t", 8, "yuv420p", &p("8", "tile-columns=2:tile-rows=1")),
+ Spec::new("inter_tiles_odd_10bit", "mandelbrot=s=650x370:r=25", 8, "yuv420p10le", &p("6", "tile-columns=1:tile-rows=1")),
+ ]
+}
+
+#[test]
+fn inter_tiles() {
+ let Some(ff) = ffmpeg() else { return };
+ for s in specs_tiles() {
+ check_bit_exact(&ff, &s);
+ }
+}
+
+/// The 1080p performance fixtures (slow; part of the extended run).
+#[test]
+#[ignore]
+fn inter_1080p() {
+ let Some(ff) = ffmpeg() else { return };
+ let p = |crf: &'static str, params: &'static str| -> Vec<&'static str> { vec!["-preset", "8", "-crf", crf, "-svtav1-params", params] };
+ let src = "testsrc2=s=1920x1080:r=25,noise=alls=6:allf=t";
+ for s in [
+ Spec::new("perf_1080p_gop", src, 60, "yuv420p", &p("30", "keyint=60")),
+ Spec::new("perf_1080p_gop_10bit", src, 60, "yuv420p10le", &p("30", "keyint=60")),
+ Spec::new("perf_1080p_gop_hq", src, 60, "yuv420p", &p("18", "keyint=60")),
+ Spec::new("perf_1080p_gop_tiles", src, 60, "yuv420p", &p("30", "keyint=60:tile-columns=2:tile-rows=1")),
+ ] {
+ check_bit_exact(&ff, &s);
+ }
+}
diff --git a/crates/codecs/src/video.rs b/crates/codecs/src/video.rs
index 2ced3d537..c83de2c03 100644
--- a/crates/codecs/src/video.rs
+++ b/crates/codecs/src/video.rs
@@ -427,11 +427,25 @@ impl VideoDecoder for Av1Decoder {
self.dec.decode(&self.config_obus).map_err(|e| CodecError::Decode(e.to_string()))?;
}
}
- let pics = self.dec.decode(sample).map_err(|e| CodecError::Decode(e.to_string()))?;
- Ok(pics.into_iter().map(|p| Self::convert(p, pts)).collect())
+ // With frame threads pictures can come out of a later call; each carries its own pts.
+ let pics = self.dec.decode_pts(sample, pts).map_err(|e| CodecError::Decode(e.to_string()))?;
+ Ok(pics
+ .into_iter()
+ .map(|p| {
+ let pts = p.pts;
+ Self::convert(p, pts)
+ })
+ .collect())
}
fn flush(&mut self) -> Vec<DecodedFrame> {
- Vec::new()
+ self.dec
+ .flush()
+ .into_iter()
+ .map(|p| {
+ let pts = p.pts;
+ Self::convert(p, pts)
+ })
+ .collect()
}
fn reset(&mut self) {
self.dec = filmcraft_av1::Decoder::new();