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}; diff --git a/lanes/streamsink-r1-run_film_fifo.sh b/lanes/streamsink-r1-run_film_fifo.sh new file mode 100755 index 00000000..b4d6307c --- /dev/null +++ b/lanes/streamsink-r1-run_film_fifo.sh @@ -0,0 +1,52 @@ +#!/bin/bash +# lane-streamsink r1: same census as run_film.sh, but our decoder streams its +# frames into a FIFO (ec_av1::stream::decode_stream_with, one frame written the +# moment it completes) and cmp2.py reads one frame from that FIFO and one from +# ffmpeg's stdout at a time. Neither side ever holds more than a frame, so the +# segment length no longer bounds memory -- peak RSS of the decoder is ~0.44 GB +# on a 4K 10-bit window regardless of how long the window is. +# usage: run_film_fifo.sh [probe] +set -u +S="$(cd "$(dirname "$0")" && pwd)" +NAME="$1"; FILM="$2"; W="$3"; H="$4"; SEG="$5" +PROBE="${6:-$HOME/.cache/cargo-target-streamsink/release/examples/decode_probe}" +T=$HOME/.cache/fullfilm-fifo/$NAME +rm -rf "$T"; mkdir -p "$T" +STATE=$T/state.json +DUR=$(ffprobe -v error -show_entries format=duration -of default=nw=1:nk=1 "$FILM" | cut -d. -f1) +echo "START name=$NAME res=${W}x${H} depth=10 codec=av1 duration_s=$DUR seg_s=$SEG mode=fifo" +T0=$(date +%s) +s=0 +while [ "$s" -lt "$DUR" ]; do + seg=$T/seg.obu; fifo=$T/ours.fifo + rm -f "$seg" "$fifo" + ffmpeg -nostdin -loglevel error -ss "$s" -t "$SEG" -i "$FILM" -map 0:v:0 -c:v copy -an -f obu "$seg" -y 2>/dev/null + if [ ! -s "$seg" ]; then echo "t=${s}s NO-SEGMENT"; s=$((s+SEG)); continue; fi + mkfifo "$fifo" + base=$(python3 -c 'import json,sys,os +p=sys.argv[1] +print(json.load(open(p))["compared"] if os.path.exists(p) else 0)' "$STATE") + EC_PROBE_OUT16="$fifo" timeout 7200 "$PROBE" "$seg" > "$T/probe.log" 2>&1 & + probe=$! + line=$(ffmpeg -nostdin -loglevel error -i "$seg" -pix_fmt yuv420p10le -f rawvideo - 2>/dev/null \ + | python3 "$S/cmp2.py" "$fifo" "$W" "$H" "$STATE" "$base") + wait $probe; rc=$? + r=$(grep -E '^REFUSED|^OK|panick|rror' "$T/probe.log" | head -1) + [ $rc -ge 128 ] && r="KILLED(rc=$rc)" + [ -z "$r" ] && r="NO-MATCH-LINE(rc=$rc)" + now=$(date +%s); el=$((now-T0)); [ "$el" -lt 1 ] && el=1 + tot=$(python3 -c 'import json,sys,os +p=sys.argv[1] +print(json.load(open(p))["compared"] if os.path.exists(p) else 0)' "$STATE") + fpm=$(python3 -c "print(round($tot*60.0/$el,2))") + printf 't=%ss\t%s\t%b\telapsed_s=%s\tfpm=%s\n' "$s" "$r" "$line" "$el" "$fpm" + rm -f "$seg" "$fifo" + s=$((s+SEG)) +done +now=$(date +%s); el=$((now-T0)); [ "$el" -lt 1 ] && el=1 +python3 -c ' +import json,sys +st=json.load(open(sys.argv[1])); el=int(sys.argv[2]); name=sys.argv[3] +print("FULLFILM name=%s compared=%d differing=%d first_bad=%s first_bad_bytes=%d max_bytes=%d segments=%d elapsed_s=%d fpm=%.2f" + % (name, st["compared"], st["differing"], st["first_bad"] if st["first_bad"] is not None else "-", + st["first_bad_bytes"], st["max_bytes"], st["segments"], el, st["compared"]*60.0/el))' "$STATE" "$el" "$NAME" diff --git a/lanes/streamsink-r1.report.md b/lanes/streamsink-r1.report.md new file mode 100644 index 00000000..2200fc82 --- /dev/null +++ b/lanes/streamsink-r1.report.md @@ -0,0 +1,50 @@ +# lane-streamsink r1 -- streaming decode entry point + +## What changed +- `crates/ec-av1/src/stream.rs:223` -- `decode_stream` is now a thin collecting wrapper; + the decode loop lives in **`decode_stream_with(data, sink)`** (stream.rs:236), + `sink: impl FnMut(&Picture, decode_idx: usize, shown: bool) -> Result<()>`. + Each completed picture is handed to the sink and dropped; only the 8 reference + slots (+ CDF/motion-field/segment-map slots) and the current frame stay alive. + Hidden (`show_frame == 0`) frames are reported with `shown == false` and are not + part of `decode_stream`'s Vec; `show_existing_frame` outputs and shown frames come + with `shown == true` (grain applied, as before). A sink `Err` aborts the decode. +- Same file: the `EC_AV1_DUMP_TABLES` label used `pictures.len()`; it is a shown-output + counter (`pictures_shown`) now, same numbers. `EC_AV1_FINAL_DUMP` / + `EC_AV1_DECODE_ORDER_DUMP` already wrote one frame at a time (one frame-sized buffer). +- `crates/ec-av1/examples/decode_probe.rs:~270` -- decodes through `decode_stream_with` + and writes each shown frame to `EC_PROBE_OUT16` (yuv420p10le) / `EC_PROBE_OUT`|argv[2] + (8-bit) as it completes, into a file **or a FIFO**. The old path collected every + Picture and then built a second full copy of the dump before one `fs::write` -- 2x the + whole segment. OK/REFUSED/`wrote N bytes`/counter lines are unchanged. +- `crates/ec-av1/src/stream.rs` tests: `streaming_decode_matches_the_collecting_one` + (same pictures, same order, one callback per shown frame, monotone decode idx, sink + error aborts after 1 call). +- Runner: `/fullfilm/run_film_fifo.sh` -- our decoder streams into a FIFO, + `cmp2.py` (unchanged) reads one frame from the FIFO and one from ffmpeg per iteration. + +## Peak RSS (4K 10-bit 3840x1608, `systemd-run --scope -p MemoryMax=6G /usr/bin/time -v`, EC_PROBE_OUT16=/dev/null) +| stream | old (collect + 2nd copy) | new (streaming) | +|---|---|---| +| 8 s window, 384 shown frames | **6,280,804 kB (6.28 GB, at the cap)** | **436,404 kB (0.44 GB)** | +| 32 s window, 960 shown frames | not run (old scales linearly; 20+ GiB) | **437,860 kB (0.44 GB)** | + +EVIDENCE: ~/.cache/streamsink-tmp/h8.obu, rss32.log | `/usr/bin/time -v` on the old and new decode_probe over an 8 s and a 32 s 4K 10-bit window under a 6 GiB scope | peak RSS 6,280,804 kB -> 436,404 kB (8 s); 437,860 kB at 960 frames, i.e. flat in segment length (target <2.5 GB met, 14x under) + +EVIDENCE: ~/.cache/streamsink-tmp/{old,new}.raw | both probes, EC_PROBE_OUT16, on a 48-frame 4K 10-bit cut | `cmp` identical, 889,159,680 bytes both, "OK: 48 frames decoded, 3840x1608" both + +EVIDENCE: /fullfilm/run_film_fifo.sh h8w | FIFO-fed streaming decode vs ffmpeg yuv420p10le, 2 segments of the 4K 10-bit stream | FULLFILM compared=584 differing=0 max_bytes=0 + +## Suite +SUITE: `cargo test -p ec-av1 --lib` (systemd unit, EC_NOMEMGUARD=1 EC_AV1_REQUIRE_AOMENC=1, log +`$HOME/.cache/streamsink-suite.log`) -- **test result: ok. 430 passed; 0 failed; 38 ignored; +0 measured; 0 filtered out; finished in 891.27s**. Includes refusal_inventory (3), +gate_coverage (9), and the named film gates (128sb, hidden_arf, gm small-side, +mv-clamp/frame-edge) -- all ok. + +## Residue +- accepted: `decode_stream` clones each shown picture into its Vec (one extra frame at + peak on the collecting path). Gates are small; the streaming path is the one that matters. +- deferred: the whole-Vec probe path was NOT kept behind an env -- the streaming output is + byte-identical and the printed lines unchanged, so a second path would be dead code + (unblocks: nothing; `git revert` of this commit if a consumer ever needs it).