diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index c73110a3..7e0de7ff 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -1131,9 +1131,10 @@ fn read_inter_plane( /// /// # Errors /// Returns an error when a symbol names anything this decoder does not -/// reconstruct: a reference other than `LAST_FRAME`, an inter mode other -/// than `NEARESTMV`/`NEWMV`, or an intra mode/tx-type outside what -/// [`read_intra_mode`]/[`read_coeffs`] already refuse. +/// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3; +/// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra +/// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already +/// refuse. #[allow(clippy::too_many_arguments)] fn decode_inter_block( dec: &mut SymbolDecoder, @@ -1212,13 +1213,29 @@ fn decode_inter_block( ) } else { let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1; - let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; - if !not_zero || !nearest { - return Err(unsupported( - "an inter mode other than NEARESTMV/NEWMV (round 2)", - )); + if !not_zero { + return Err(unsupported("GLOBALMV (round 3)")); } - (stack.nearest_mv, false) + let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; + let mv = if nearest { + stack.nearest_mv + } else { + // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting + // at 1): read at most two more `drl_mode` bits, one per stack + // entry past the second, stopping at the first `0`. + // `drl_ctx[idx]` is the context between `entries[idx]` and + // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is + // exactly the pair this index is choosing between. + let mut idx = 1usize; + while idx < 3 && stack.entries.len() > idx + 1 { + if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 { + break; + } + idx += 1; + } + stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv) + }; + (mv, false) }; for dr in 0..bw4 { for dc in 0..bw4 { @@ -2117,6 +2134,191 @@ mod tests { /// The GOP cross-oracle: ffmpeg decodes the whole sequence the same way /// this module does, frame for frame. + /// A NEARMV block (`not_new`, `not_zero`, `!nearest`) predicts from the + /// MV stack's *second* candidate (`near_mv`), not its first + /// (`nearest_mv`) -- a hand-built symbol stream drives + /// [`decode_inter_block`] directly, since this crate's own encoder never + /// writes NEARMV (round 3: it never chooses the mode). + #[test] + fn a_nearmv_block_predicts_from_the_stacks_second_candidate() { + use crate::msac::SymbolEncoder; + use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx}; + + const LAST_FRAME: i8 = 1; + let (mi_cols, mi_rows) = (12u32, 12u32); + let side = 16usize; // one 16x16 leaf block + let (r, c) = (1usize, 1usize); // `at`, in SUB (16px) units + let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); + let bw4 = side / 4; + + let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize); + let (above_mv, left_mv) = ((4, 4), (8, 8)); + let neighbour = |mv| MiInfo { + is_inter: true, + ref_frame: LAST_FRAME, + mv, + is_new_mv: false, + size: 1, + }; + for col in mi_col..mi_col + bw4 { + grid.set(mi_row - 1, col, neighbour(above_mv)); + } + for row in mi_row..mi_row + bw4 { + grid.set(row, mi_col - 1, neighbour(left_mv)); + } + + let stack = find_mv_stack( + &grid, + mi_row, + mi_col, + bw4, + bw4, + LAST_FRAME, + mi_cols as usize, + mi_rows as usize, + ); + // Sanity on the test's own setup, not the code under test: two equal- + // weight candidates keep scan order (above, then left -- module doc). + assert_eq!(stack.entries.len(), 2); + assert_eq!(stack.nearest_mv, above_mv); + assert_eq!(stack.near_mv, left_mv); + + let (skip_ctx, ii_ctx, sr_ctx) = ( + 0usize, + intra_inter_ctx(true, true, false, false), + single_ref_ctx(false), + ); + + let mut cdfs = Cdfs::new(q_ctx_of(100)); + let mut enc = SymbolEncoder::new(); + enc.symbol(1, &mut cdfs.skip[skip_ctx]); // skip + enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter + enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // LAST_FRAME + enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]); + enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]); + enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new + enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero + enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // !nearest -> NEARMV + let data = enc.finish(); + + let (width, height) = (64usize, 64usize); + let ref_pattern: Vec = (0..width * height).map(|i| (i % 251) as u8).collect(); + let ref_plane = |scale: usize| PlaneBuf { + data: ref_pattern + .iter() + .step_by(scale.max(1)) + .take((width / scale) * (height / scale)) + .copied() + .collect(), + width: width / scale, + height: height / scale, + true_width: width / scale, + true_height: height / scale, + }; + let ref_y = PlaneBuf { + data: ref_pattern.clone(), + width, + height, + true_width: width, + true_height: height, + }; + let ref_u = ref_plane(2); + let ref_v = ref_plane(2); + + let mut y = PlaneBuf { + data: vec![0u8; width * height], + width, + height, + true_width: width, + true_height: height, + }; + let mut u = PlaneBuf { + data: vec![0u8; (width / 2) * (height / 2)], + width: width / 2, + height: height / 2, + true_width: width / 2, + true_height: height / 2, + }; + let mut v = PlaneBuf { + data: vec![0u8; (width / 2) * (height / 2)], + width: width / 2, + height: height / 2, + true_width: width / 2, + true_height: height / 2, + }; + + let mut cdfs = Cdfs::new(q_ctx_of(100)); + let mut dec = SymbolDecoder::new(&data); + let mut neighbours = Neighbours::new(3, 3, mi_cols as usize, mi_rows as usize); + decode_inter_block( + &mut dec, + &mut cdfs, + &mut neighbours, + &mut grid, + (r, c), + side, + mi_cols, + mi_rows, + &mut y, + &mut u, + &mut v, + &ref_y, + &ref_u, + &ref_v, + 100, + TxbSet::Luma16, + TxbSet::Luma16Inter, + TxbSet::Chroma8, + TX16, + TX8, + &[], + &[], + 0, + ) + .unwrap(); + + let (px, py) = (c * SUB, r * SUB); + let mut want_near = vec![0u8; side * side]; + crate::mc::predict( + &ref_y.data, + ref_y.width, + ref_y.true_width, + ref_y.true_height, + mv_to_q4(px, left_mv.1, true), + mv_to_q4(py, left_mv.0, true), + side, + side, + &mut want_near, + ); + let mut want_nearest = vec![0u8; side * side]; + crate::mc::predict( + &ref_y.data, + ref_y.width, + ref_y.true_width, + ref_y.true_height, + mv_to_q4(px, above_mv.1, true), + mv_to_q4(py, above_mv.0, true), + side, + side, + &mut want_nearest, + ); + assert_ne!( + want_near, want_nearest, + "test setup: the two candidate MVs must predict differently" + ); + + let mut got = vec![0u8; side * side]; + for row in 0..side { + got[row * side..(row + 1) * side].copy_from_slice( + &y.data[(py + row) * y.width + px..(py + row) * y.width + px + side], + ); + } + assert_eq!( + got, want_near, + "NEARMV predicted from the wrong stack entry" + ); + } + #[test] fn ffmpeg_and_this_decoder_agree_on_a_gop() { if !have_ffmpeg() { diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index c895c779..628a4f31 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -27,5 +27,6 @@ pub mod mvstack; pub mod obu; pub mod quant; pub mod sequence; +pub mod stream; pub mod tile; pub mod transform; diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs new file mode 100644 index 00000000..e9597cbb --- /dev/null +++ b/crates/ec-av1/src/stream.rs @@ -0,0 +1,282 @@ +//! The stream-level entry point a real decoder needs: walk a raw AV1 OBU +//! stream (`Encoded::stream`, or any low-overhead-format bitstream this +//! crate's own writers produce) via [`ec_av1_syntax::Av1Parser`] and dispatch +//! each frame's tile payload to [`crate::decode::decode_key_frame_tile`] / +//! [`crate::decode::decode_inter_frame_tile`], threading a single-slot DPB +//! exactly as [`crate::encode::encode_sequence`] does on the write side. +//! +//! This is the only reachable path for a caller that does not have the +//! encoder's own `Encoded::tile`/`mi_cols`/`mi_rows`/`base_q_idx` fields (they +//! are `pub(crate)`, and rightly so: the wire is `stream`, everything else is +//! an implementation detail of how this crate happens to build it). + +use ec_av1_syntax::{Av1Parser, FrameType, ObuKind}; +use ec_core::{Error, Result}; + +use crate::decode::{decode_inter_frame_tile, decode_key_frame_tile}; +use crate::encode::Picture; + +/// Decode every frame in a raw AV1 OBU stream, in coding order. +/// +/// A key frame becomes the reference for the inter frames that follow it, +/// until the next key frame resets the DPB — the same single-slot chain +/// [`crate::encode::encode_sequence`] threads on the write side. Only a +/// `Frame` OBU (an uncompressed header and its tile group in one OBU, which +/// is all this crate's encoder ever writes) carries a tile payload; sequence +/// headers and temporal delimiters are consumed for the state they carry (or +/// skipped) and produce no picture. +/// +/// # Errors +/// Returns an error when the stream is truncated or malformed (as +/// [`Av1Parser`] reports it), when a frame header names anything this +/// crate's tile decoders do not reconstruct (see their own docs), or when an +/// inter frame appears before any key frame has supplied a reference. +pub fn decode_stream(data: &[u8]) -> Result> { + let mut parser = Av1Parser::new(); + let mut pictures = Vec::new(); + let mut reference: Option = None; + + let mut pos = 0usize; + while pos < data.len() { + let obu = parser.parse_obu(&data[pos..])?; + let obu_offset = pos; + pos += obu.total_size; + + let ObuKind::Frame(header, tiles) = obu.kind else { + continue; + }; + let tile = tiles.first().ok_or_else(|| { + Error::unsupported("AV1 decode_stream", "a frame OBU with no tile group") + })?; + // `Tile::offset` is relative to the buffer `parse_obu` was handed + // (`&data[pos..]` at the time this OBU was parsed), so it is relative + // to `obu_offset`, not to `data` as a whole. + let start = obu_offset + tile.offset; + let tile_bytes = data.get(start..start + tile.size).ok_or(Error::NeedMore)?; + + let picture = if header.frame_type == FrameType::Key { + decode_key_frame_tile( + tile_bytes, + header.mi_cols, + header.mi_rows, + header.quantization.base_q_idx, + header.frame_width, + header.frame_height, + )? + } else { + let reference = reference.as_ref().ok_or_else(|| { + Error::unsupported( + "AV1 decode_stream", + "an inter frame with no key frame before it", + ) + })?; + decode_inter_frame_tile( + tile_bytes, + header.mi_cols, + header.mi_rows, + header.quantization.base_q_idx, + header.frame_width, + header.frame_height, + reference, + )? + }; + reference = Some(picture.clone()); + pictures.push(picture); + } + Ok(pictures) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::encode::{Picture as Pic, encode_key_frame, encode_sequence}; + + fn test_card(width: usize, height: usize) -> Pic { + let mut picture = Pic::grey(width, height); + for row in 0..height { + for col in 0..width { + picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u8; + } + } + for row in 0..height / 2 { + for col in 0..width / 2 { + let i = row * width / 2 + col; + picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u8; + picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u8; + } + } + picture + } + + fn panned_test_card(width: usize, height: usize, shift: i64) -> Pic { + let mut picture = Pic::grey(width, height); + for y in 0..height { + for x in 0..width { + let sx = (x as i64 - shift).rem_euclid(width as i64) as f64; + let gradient = sx * 200.0 / width as f64; + picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u8; + } + } + for y in 0..height / 2 { + for x in 0..width / 2 { + let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize; + let i = y * width / 2 + x; + picture.u[i] = (100 + (sx * 60 / (width / 2))) as u8; + picture.v[i] = (200 - (y * 80 / (height / 2))) as u8; + } + } + picture + } + + /// `decode_stream` on a lone key frame's stream matches both the tile + /// path (`decode_key_frame_tile` called directly on `Encoded::tile`) and + /// the encoder's own reconstruction, at an even and an odd size. + #[test] + fn decode_stream_matches_the_tile_path_on_a_key_frame() { + for &(width, height) in &[(64usize, 64usize), (216, 96)] { + let picture = test_card(width, height); + let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); + let via_tile = decode_key_frame_tile( + &encoded.tile, + encoded.mi_cols, + encoded.mi_rows, + encoded.base_q_idx, + width as u32, + height as u32, + ) + .unwrap(); + let via_stream = decode_stream(&encoded.stream).unwrap(); + assert_eq!(via_stream.len(), 1, "{width}x{height}: one picture"); + assert_eq!(via_stream[0].y, via_tile.y, "{width}x{height}: luma"); + assert_eq!(via_stream[0].u, via_tile.u, "{width}x{height}: U"); + assert_eq!(via_stream[0].v, via_tile.v, "{width}x{height}: V"); + assert_eq!( + via_stream[0].y, encoded.reconstruction.y, + "{width}x{height}: luma vs encoder reconstruction" + ); + } + } + + /// A GOP (key frame plus panned inter frames, so blocks actually take + /// motion) decodes bit-exact through `decode_stream` alone, threading its + /// own DPB rather than a test-supplied reference. + fn gop_round_trips(width: usize, height: usize) { + let pictures: Vec<_> = (0..4) + .map(|i| panned_test_card(width, height, i * 3)) + .collect(); + let encoded = encode_sequence(&pictures, 100, 0.5).unwrap(); + let decoded = decode_stream(&encoded.stream).unwrap(); + assert_eq!(decoded.len(), encoded.frames.len()); + for (i, (got, frame)) in decoded.iter().zip(&encoded.frames).enumerate() { + assert_eq!( + got.y, frame.reconstruction.y, + "{width}x{height} frame {i} luma" + ); + assert_eq!( + got.u, frame.reconstruction.u, + "{width}x{height} frame {i} U" + ); + assert_eq!( + got.v, frame.reconstruction.v, + "{width}x{height} frame {i} V" + ); + } + } + + #[test] + fn decode_stream_round_trips_a_gop() { + gop_round_trips(128, 64); + } + + /// Same claim at a size that is not a whole number of 32x32 blocks, so + /// the inter frame's 16x16-leaf split path is exercised too. + #[test] + fn decode_stream_round_trips_an_odd_size_gop() { + gop_round_trips(216, 96); + } + + use std::io::Write; + use std::process::{Command, Stdio}; + + fn have_ffmpeg() -> bool { + Command::new("ffmpeg") + .arg("-version") + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .is_ok_and(|s| s.success()) + } + + /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream. + fn ffmpeg_decode_sequence( + stream: &[u8], + width: usize, + height: usize, + frames: usize, + ) -> Vec { + let mut child = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("ffmpeg failed to start"); + child + .stdin + .take() + .expect("ffmpeg stdin") + .write_all(stream) + .expect("writing the stream to ffmpeg"); + let out = child.wait_with_output().expect("ffmpeg failed to run"); + assert!( + out.status.success(), + "ffmpeg refused the stream: {}", + String::from_utf8_lossy(&out.stderr) + ); + let (luma, chroma) = (width * height, width * height / 4); + let frame_bytes = luma + 2 * chroma; + assert_eq!( + out.stdout.len(), + frame_bytes * frames, + "expected {frames} 4:2:0 frames, ffmpeg said: {}", + String::from_utf8_lossy(&out.stderr) + ); + (0..frames) + .map(|i| { + let base = i * frame_bytes; + Pic { + width, + height, + y: out.stdout[base..base + luma].to_vec(), + u: out.stdout[base + luma..base + luma + chroma].to_vec(), + v: out.stdout[base + luma + chroma..base + frame_bytes].to_vec(), + } + }) + .collect() + } + + /// `decode_stream` agrees with ffmpeg/dav1d on the same wire bytes -- an + /// independent decoder, not just this crate checking its own tile path. + #[test] + fn decode_stream_agrees_with_ffmpeg_on_a_gop() { + if !have_ffmpeg() { + eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg"); + return; + } + let (width, height) = (128usize, 64usize); + let pictures: Vec<_> = (0..3) + .map(|i| panned_test_card(width, height, i * 3)) + .collect(); + let encoded = encode_sequence(&pictures, 100, 0.5).unwrap(); + let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); + let decoded = decode_stream(&encoded.stream).unwrap(); + assert_eq!(decoded.len(), 3); + for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg"); + assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg"); + assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg"); + } + } +} diff --git a/tools/ec-bench/src/main.rs b/tools/ec-bench/src/main.rs index 07b7a4e5..5f71b842 100644 --- a/tools/ec-bench/src/main.rs +++ b/tools/ec-bench/src/main.rs @@ -312,19 +312,16 @@ fn bench_h265_encode(rows: &mut Vec) { // --------------------------------------------------------------------------- fn bench_av1_encode(rows: &mut Vec) { - rows.push(missing_direction( - "ec-av1", - "decode", - "encode-only crate, no decoder present", - )); let Some(src) = real_video("h264") else { rows.push(missing("ec-av1", "encode")); + rows.push(missing("ec-av1", "decode")); return; }; // AV1's block grid is 32x32 superblocks: pick a size already a multiple of it. let (planes, w, h, n) = extract_yuv420p(&src, 640, 384, 10); if n == 0 { rows.push(missing("ec-av1", "encode")); + rows.push(missing("ec-av1", "decode")); return; } let cfg = Av1Config { @@ -336,6 +333,7 @@ fn bench_av1_encode(rows: &mut Vec) { }; let mut enc = Av1Encoder::new(cfg).expect("av1 encoder"); let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize; + let mut stream = Vec::new(); let start = Instant::now(); for frame in planes.chunks_exact(frame_len) { let (y, rest) = frame.split_at((w * h) as usize); @@ -347,7 +345,8 @@ fn bench_av1_encode(rows: &mut Vec) { u: u.to_vec(), v: v.to_vec(), }; - enc.encode(&pic).expect("av1 encode"); + let packet = enc.encode(&pic).expect("av1 encode"); + stream.extend_from_slice(&packet.data); } let wall = start.elapsed().as_secs_f64(); let media_s = n as f64 / 30.0; @@ -359,6 +358,19 @@ fn bench_av1_encode(rows: &mut Vec) { wall_ms: wall * 1000.0, rtf: (wall > 0.0).then_some(media_s / wall), }); + + let start = Instant::now(); + let pictures = ec_av1::stream::decode_stream(&stream).expect("av1 decode_stream"); + let wall = start.elapsed().as_secs_f64(); + assert_eq!(pictures.len(), n as usize, "decode_stream frame count"); + rows.push(Row { + component: "ec-av1", + direction: "decode", + content: format!("{w}x{h}, {n} frames, gop=10"), + media: format!("{media_s:.1}s"), + wall_ms: wall * 1000.0, + rtf: (wall > 0.0).then_some(media_s / wall), + }); } // ---------------------------------------------------------------------------