diff --git a/crates/ec-av1/examples/decode_probe.rs b/crates/ec-av1/examples/decode_probe.rs index 4c2ad7e9..7646c773 100644 --- a/crates/ec-av1/examples/decode_probe.rs +++ b/crates/ec-av1/examples/decode_probe.rs @@ -257,40 +257,71 @@ fn main() { println!("TILING: no frame header parsed"); } - match ec_av1::stream::decode_stream(&data) { - Ok(frames) if frames.is_empty() => { + // lane-streamsink r1: decode through the streaming entry point and write + // each shown frame out as it completes. The old path collected every + // picture in a Vec and then built a second full copy of the raw dump + // before one `fs::write`, so peak RSS was 2x the whole decoded segment (a + // 4K 8 s window needed >20 GiB, a whole film terabytes). Here at most one + // frame is held beyond the decoder's own DPB, and the printed lines are + // byte-identical to the old ones. + // `EC_PROBE_OUT16` is yuv420p10le (u16 LE); `EC_PROBE_OUT` / argv[2] is + // 8-bit (planes are u16, low byte taken). Either target may be a FIFO. + use std::io::Write; + let open = |path: &str| { + std::fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .open(path) + .unwrap_or_else(|e| panic!("opening {path}: {e}")) + }; + let out16 = std::env::var("EC_PROBE_OUT16").ok(); + let out8 = std::env::args().nth(2).or_else(|| std::env::var("EC_PROBE_OUT").ok()); + let mut f16 = out16.as_deref().map(open); + let mut f8 = out8.as_deref().map(open); + let mut written16 = 0usize; + let mut written8 = 0usize; + let mut shown = 0usize; + let mut dims = (0usize, 0usize); + let mut buf: Vec = Vec::new(); + let result = ec_av1::stream::decode_stream_with(&data, |f, _idx, is_shown| { + if !is_shown { + return Ok(()); + } + shown += 1; + if shown == 1 { + dims = (f.width, f.height); + } + if let Some(w) = f16.as_mut() { + buf.clear(); + for p in [&f.y, &f.u, &f.v] { + buf.extend(p.iter().flat_map(|&s| s.to_le_bytes())); + } + w.write_all(&buf).expect("writing raw planes"); + written16 += buf.len(); + } + if let Some(w) = f8.as_mut() { + buf.clear(); + for p in [&f.y, &f.u, &f.v] { + buf.extend(p.iter().map(|&s| s as u8)); + } + w.write_all(&buf).expect("writing raw planes"); + written8 += buf.len(); + } + Ok(()) + }); + match result { + Ok(()) if shown == 0 => { println!("OK but EMPTY: no frames -- is {path} an IVF rather than a raw OBU stream?"); } - Ok(frames) => { - // Optional second arg, or EC_PROBE_OUT=: dump the decoded - // planes as raw yuv420p so a pixel diff against `ffmpeg -i s.obu - // -f rawvideo` needs no test harness. - // 10-bit streams: EC_PROBE_OUT16 dumps the planes as little-endian - // u16 (yuv420p10le), the only form a pixel diff against - // `ffmpeg -pix_fmt yuv420p10le` can use (lane-band63). - if let Ok(out) = std::env::var("EC_PROBE_OUT16") { - let mut buf: Vec = Vec::new(); - for f in &frames { - for p in [&f.y, &f.u, &f.v] { - buf.extend(p.iter().flat_map(|&s| s.to_le_bytes())); - } - } - std::fs::write(&out, &buf).expect("writing raw planes"); - println!("wrote {} bytes of yuv420p10le to {out}", buf.len()); + Ok(()) => { + if let Some(out) = &out16 { + println!("wrote {written16} bytes of yuv420p10le to {out}"); } - let out = std::env::args().nth(2).or_else(|| std::env::var("EC_PROBE_OUT").ok()); - if let Some(out) = out { - // 8-bit only: planes are u16, take the low byte. - let mut buf: Vec = Vec::new(); - for f in &frames { - for p in [&f.y, &f.u, &f.v] { - buf.extend(p.iter().map(|&s| s as u8)); - } - } - std::fs::write(&out, &buf).expect("writing raw planes"); - println!("wrote {} bytes of yuv420p to {out}", buf.len()); + if let Some(out) = &out8 { + println!("wrote {written8} bytes of yuv420p to {out}"); } - println!("OK: {} frames decoded, {}x{}", frames.len(), frames[0].width, frames[0].height); + println!("OK: {shown} frames decoded, {}x{}", dims.0, dims.1); } Err(e) => println!("REFUSED: {e}"), } diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 9d1c0b80..38fbd4ae 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -221,9 +221,39 @@ pub fn rect_inter_tu_counters() -> (usize, usize, usize) { /// 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 pictures = Vec::new(); + decode_stream_with(data, |picture, _decode_idx, shown| { + if shown { + pictures.push(picture.clone()); + } + Ok(()) + })?; + Ok(pictures) +} + +/// Streaming form of [`decode_stream`]: hand every completed picture to +/// `sink` the moment it exists and drop it right after, so peak memory is one +/// output picture plus the 8-slot DPB instead of the whole decoded stream -- +/// a 4K long-GOP segment costs the same as a short one. `decode_stream` +/// itself is this function collecting into a `Vec`. +/// +/// `sink` is called with the picture, the decode-order index of the coded +/// frame it came from, and whether it is output: a hidden reference frame +/// (`show_frame == 0`) is reported with `shown == false` and is NOT part of +/// `decode_stream`'s output, a `show_existing_frame` output with `true`. +/// The grain-synthesised picture is what a shown frame's sink sees; the +/// reference bank keeps the clean one (spec 7.18.3.1). An `Err` the sink +/// returns aborts the decode and is returned unchanged. +/// +/// # Errors +/// As [`decode_stream`], plus whatever `sink` returns. +pub fn decode_stream_with( + data: &[u8], + mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>, +) -> Result<()> { let final_dump = final_dump_prefix(); let mut parser = Av1Parser::new(); - let mut pictures = Vec::new(); + let mut pictures_shown: usize = 0; let mut pictures_decoded: usize = 0; // Spec 7.20/7.4: each of the 8 reference slots remembers the picture a // previous frame's `refresh_frame_flags` stored into it, exactly like the @@ -329,7 +359,8 @@ pub fn decode_stream(data: &[u8]) -> Result> { } else { picture }; - pictures.push(output); + sink(&output, pictures_decoded, true)?; + pictures_shown += 1; continue; } // `tiles_base_offset` is added to every `Tile::offset` below to reach @@ -931,7 +962,7 @@ pub fn decode_stream(data: &[u8]) -> Result> { .append(true) .open(&path) { - let _ = writeln!(f, "=== frame idx={} ===", pictures.len()); + let _ = writeln!(f, "=== frame idx={} ===", pictures_shown); let _ = writeln!(f, "partition_w64 {:?}", stored_cdfs.partition_w64); let _ = writeln!(f, "partition_w32 {:?}", stored_cdfs.partition_w32); let _ = writeln!(f, "partition_w16 {:?}", stored_cdfs.partition_w16); @@ -1023,10 +1054,17 @@ pub fn decode_stream(data: &[u8]) -> Result> { } else { picture }; - pictures.push(output); + sink(&output, pictures_decoded - 1, true)?; + pictures_shown += 1; + } else { + // Hidden (alt-ref/forward-key) frames never reach + // `decode_stream`'s output, but a decode-order consumer -- the + // `EC_AV1_FINAL_DUMP` comparison against aomdec, say -- needs + // them, so they are reported too, with `shown == false`. + sink(&picture, pictures_decoded - 1, false)?; } } - Ok(pictures) + Ok(()) } @@ -1482,6 +1520,53 @@ mod tests { gop_round_trips(216, 96); } + /// lane-streamsink r1: `decode_stream_with` emits exactly the pictures + /// `decode_stream` collects, in the same order -- the streaming path is + /// the decoder now (`decode_stream` is a collecting wrapper), so an + /// equivalence check here is what keeps every gate's Vec-shaped assert + /// meaningful. Also pins the sink contract: one call per shown picture, + /// decode indices non-decreasing, and an `Err` from the sink aborting. + #[test] + fn streaming_decode_matches_the_collecting_one() { + let pictures: Vec<_> = (0..4).map(|i| panned_test_card(128, 64, i * 3)).collect(); + let stream = encode_sequence(&pictures, 100, 0.5).unwrap().stream; + let collected = decode_stream(&stream).unwrap(); + + let mut shown = Vec::new(); + let mut idxs = Vec::new(); + let mut live = 0usize; + decode_stream_with(&stream, |p, idx, is_shown| { + live += 1; + if is_shown { + idxs.push(idx); + shown.push(p.clone()); + } + Ok(()) + }) + .unwrap(); + assert_eq!(shown.len(), collected.len(), "callback count vs shown frames"); + assert!(live >= shown.len(), "every shown picture is also a callback"); + assert!( + idxs.windows(2).all(|w| w[0] <= w[1]), + "decode indices out of order: {idxs:?}" + ); + for (i, (got, want)) in shown.iter().zip(&collected).enumerate() { + assert_eq!(got.y, want.y, "frame {i} luma"); + assert_eq!(got.u, want.u, "frame {i} U"); + assert_eq!(got.v, want.v, "frame {i} V"); + } + + // A sink error stops the decode and comes back unchanged. + let mut seen = 0usize; + let err = decode_stream_with(&stream, |_, _, _| { + seen += 1; + Err(Error::corrupt("sink says stop")) + }) + .unwrap_err(); + assert_eq!(seen, 1, "decode continued past a failing sink"); + assert!(format!("{err}").contains("sink says stop"), "{err}"); + } + use std::io::Write; use std::process::{Command, Stdio};