forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-streamsink' (2dc8d13b): decode_stream_with streams each picture to a sink; decode_probe writes frames as they complete; 4K peak RSS 6.3 GB -> 0.44 GB, flat in stream length

Browse files at this commit

11648e02823aff50d91009801a563ba1631a7530Ahmet Kaan GümüşParent: 8506f63d9a2cb4
crates/ec-av1/examples/decode_probe.rsmodified+61 -30
@@ -257,40 +257,71 @@ fn main() {
257 println!("TILING: no frame header parsed");257 println!("TILING: no frame header parsed");
258 }258 }
259 259
260- match ec_av1::stream::decode_stream(&data) {260+ // lane-streamsink r1: decode through the streaming entry point and write
261- Ok(frames) if frames.is_empty() => {261+ // each shown frame out as it completes. The old path collected every
262+ // picture in a Vec and then built a second full copy of the raw dump
263+ // before one `fs::write`, so peak RSS was 2x the whole decoded segment (a
264+ // 4K 8 s window needed >20 GiB, a whole film terabytes). Here at most one
265+ // frame is held beyond the decoder's own DPB, and the printed lines are
266+ // byte-identical to the old ones.
267+ // `EC_PROBE_OUT16` is yuv420p10le (u16 LE); `EC_PROBE_OUT` / argv[2] is
268+ // 8-bit (planes are u16, low byte taken). Either target may be a FIFO.
269+ use std::io::Write;
270+ let open = |path: &str| {
271+ std::fs::OpenOptions::new()
272+ .write(true)
273+ .create(true)
274+ .truncate(true)
275+ .open(path)
276+ .unwrap_or_else(|e| panic!("opening {path}: {e}"))
277+ };
278+ let out16 = std::env::var("EC_PROBE_OUT16").ok();
279+ let out8 = std::env::args().nth(2).or_else(|| std::env::var("EC_PROBE_OUT").ok());
280+ let mut f16 = out16.as_deref().map(open);
281+ let mut f8 = out8.as_deref().map(open);
282+ let mut written16 = 0usize;
283+ let mut written8 = 0usize;
284+ let mut shown = 0usize;
285+ let mut dims = (0usize, 0usize);
286+ let mut buf: Vec<u8> = Vec::new();
287+ let result = ec_av1::stream::decode_stream_with(&data, |f, _idx, is_shown| {
288+ if !is_shown {
289+ return Ok(());
290+ }
291+ shown += 1;
292+ if shown == 1 {
293+ dims = (f.width, f.height);
294+ }
295+ if let Some(w) = f16.as_mut() {
296+ buf.clear();
297+ for p in [&f.y, &f.u, &f.v] {
298+ buf.extend(p.iter().flat_map(|&s| s.to_le_bytes()));
299+ }
300+ w.write_all(&buf).expect("writing raw planes");
301+ written16 += buf.len();
302+ }
303+ if let Some(w) = f8.as_mut() {
304+ buf.clear();
305+ for p in [&f.y, &f.u, &f.v] {
306+ buf.extend(p.iter().map(|&s| s as u8));
307+ }
308+ w.write_all(&buf).expect("writing raw planes");
309+ written8 += buf.len();
310+ }
311+ Ok(())
312+ });
313+ match result {
314+ Ok(()) if shown == 0 => {
262 println!("OK but EMPTY: no frames -- is {path} an IVF rather than a raw OBU stream?");315 println!("OK but EMPTY: no frames -- is {path} an IVF rather than a raw OBU stream?");
263 }316 }
264- Ok(frames) => {317+ Ok(()) => {
265- // Optional second arg, or EC_PROBE_OUT=<path>: dump the decoded318+ if let Some(out) = &out16 {
266- // planes as raw yuv420p so a pixel diff against `ffmpeg -i s.obu319+ println!("wrote {written16} bytes of yuv420p10le to {out}");
267- // -f rawvideo` needs no test harness.
268- // 10-bit streams: EC_PROBE_OUT16 dumps the planes as little-endian
269- // u16 (yuv420p10le), the only form a pixel diff against
270- // `ffmpeg -pix_fmt yuv420p10le` can use (lane-band63).
271- if let Ok(out) = std::env::var("EC_PROBE_OUT16") {
272- let mut buf: Vec<u8> = Vec::new();
273- for f in &frames {
274- for p in [&f.y, &f.u, &f.v] {
275- buf.extend(p.iter().flat_map(|&s| s.to_le_bytes()));
276- }
277- }
278- std::fs::write(&out, &buf).expect("writing raw planes");
279- println!("wrote {} bytes of yuv420p10le to {out}", buf.len());
280 }320 }
281- let out = std::env::args().nth(2).or_else(|| std::env::var("EC_PROBE_OUT").ok());321+ if let Some(out) = &out8 {
282- if let Some(out) = out {322+ println!("wrote {written8} bytes of yuv420p to {out}");
283- // 8-bit only: planes are u16, take the low byte.
284- let mut buf: Vec<u8> = Vec::new();
285- for f in &frames {
286- for p in [&f.y, &f.u, &f.v] {
287- buf.extend(p.iter().map(|&s| s as u8));
288- }
289- }
290- std::fs::write(&out, &buf).expect("writing raw planes");
291- println!("wrote {} bytes of yuv420p to {out}", buf.len());
292 }323 }
293- println!("OK: {} frames decoded, {}x{}", frames.len(), frames[0].width, frames[0].height);324+ println!("OK: {shown} frames decoded, {}x{}", dims.0, dims.1);
294 }325 }
295 Err(e) => println!("REFUSED: {e}"),326 Err(e) => println!("REFUSED: {e}"),
296 }327 }
crates/ec-av1/src/stream.rsmodified+90 -5
@@ -221,9 +221,39 @@ pub fn rect_inter_tu_counters() -> (usize, usize, usize) {
221 /// crate's tile decoders do not reconstruct (see their own docs), or when an221 /// crate's tile decoders do not reconstruct (see their own docs), or when an
222 /// inter frame appears before any key frame has supplied a reference.222 /// inter frame appears before any key frame has supplied a reference.
223 pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {223 pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
224+ let mut pictures = Vec::new();
225+ decode_stream_with(data, |picture, _decode_idx, shown| {
226+ if shown {
227+ pictures.push(picture.clone());
228+ }
229+ Ok(())
230+ })?;
231+ Ok(pictures)
232+}
233+
234+/// Streaming form of [`decode_stream`]: hand every completed picture to
235+/// `sink` the moment it exists and drop it right after, so peak memory is one
236+/// output picture plus the 8-slot DPB instead of the whole decoded stream --
237+/// a 4K long-GOP segment costs the same as a short one. `decode_stream`
238+/// itself is this function collecting into a `Vec`.
239+///
240+/// `sink` is called with the picture, the decode-order index of the coded
241+/// frame it came from, and whether it is output: a hidden reference frame
242+/// (`show_frame == 0`) is reported with `shown == false` and is NOT part of
243+/// `decode_stream`'s output, a `show_existing_frame` output with `true`.
244+/// The grain-synthesised picture is what a shown frame's sink sees; the
245+/// reference bank keeps the clean one (spec 7.18.3.1). An `Err` the sink
246+/// returns aborts the decode and is returned unchanged.
247+///
248+/// # Errors
249+/// As [`decode_stream`], plus whatever `sink` returns.
250+pub fn decode_stream_with(
251+ data: &[u8],
252+ mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
253+) -> Result<()> {
224 let final_dump = final_dump_prefix();254 let final_dump = final_dump_prefix();
225 let mut parser = Av1Parser::new();255 let mut parser = Av1Parser::new();
226- let mut pictures = Vec::new();256+ let mut pictures_shown: usize = 0;
227 let mut pictures_decoded: usize = 0;257 let mut pictures_decoded: usize = 0;
228 // Spec 7.20/7.4: each of the 8 reference slots remembers the picture a258 // Spec 7.20/7.4: each of the 8 reference slots remembers the picture a
229 // previous frame's `refresh_frame_flags` stored into it, exactly like the259 // previous frame's `refresh_frame_flags` stored into it, exactly like the
@@ -329,7 +359,8 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
329 } else {359 } else {
330 picture360 picture
331 };361 };
332- pictures.push(output);362+ sink(&output, pictures_decoded, true)?;
363+ pictures_shown += 1;
333 continue;364 continue;
334 }365 }
335 // `tiles_base_offset` is added to every `Tile::offset` below to reach366 // `tiles_base_offset` is added to every `Tile::offset` below to reach
@@ -931,7 +962,7 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
931 .append(true)962 .append(true)
932 .open(&path)963 .open(&path)
933 {964 {
934- let _ = writeln!(f, "=== frame idx={} ===", pictures.len());965+ let _ = writeln!(f, "=== frame idx={} ===", pictures_shown);
935 let _ = writeln!(f, "partition_w64 {:?}", stored_cdfs.partition_w64);966 let _ = writeln!(f, "partition_w64 {:?}", stored_cdfs.partition_w64);
936 let _ = writeln!(f, "partition_w32 {:?}", stored_cdfs.partition_w32);967 let _ = writeln!(f, "partition_w32 {:?}", stored_cdfs.partition_w32);
937 let _ = writeln!(f, "partition_w16 {:?}", stored_cdfs.partition_w16);968 let _ = writeln!(f, "partition_w16 {:?}", stored_cdfs.partition_w16);
@@ -1023,10 +1054,17 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
1023 } else {1054 } else {
1024 picture1055 picture
1025 };1056 };
1026- pictures.push(output);1057+ sink(&output, pictures_decoded - 1, true)?;
1058+ pictures_shown += 1;
1059+ } else {
1060+ // Hidden (alt-ref/forward-key) frames never reach
1061+ // `decode_stream`'s output, but a decode-order consumer -- the
1062+ // `EC_AV1_FINAL_DUMP` comparison against aomdec, say -- needs
1063+ // them, so they are reported too, with `shown == false`.
1064+ sink(&picture, pictures_decoded - 1, false)?;
1027 }1065 }
1028 }1066 }
1029- Ok(pictures)1067+ Ok(())
1030 }1068 }
1031 1069
1032 1070
@@ -1482,6 +1520,53 @@ mod tests {
1482 gop_round_trips(216, 96);1520 gop_round_trips(216, 96);
1483 }1521 }
1484 1522
1523+ /// lane-streamsink r1: `decode_stream_with` emits exactly the pictures
1524+ /// `decode_stream` collects, in the same order -- the streaming path is
1525+ /// the decoder now (`decode_stream` is a collecting wrapper), so an
1526+ /// equivalence check here is what keeps every gate's Vec-shaped assert
1527+ /// meaningful. Also pins the sink contract: one call per shown picture,
1528+ /// decode indices non-decreasing, and an `Err` from the sink aborting.
1529+ #[test]
1530+ fn streaming_decode_matches_the_collecting_one() {
1531+ let pictures: Vec<_> = (0..4).map(|i| panned_test_card(128, 64, i * 3)).collect();
1532+ let stream = encode_sequence(&pictures, 100, 0.5).unwrap().stream;
1533+ let collected = decode_stream(&stream).unwrap();
1534+
1535+ let mut shown = Vec::new();
1536+ let mut idxs = Vec::new();
1537+ let mut live = 0usize;
1538+ decode_stream_with(&stream, |p, idx, is_shown| {
1539+ live += 1;
1540+ if is_shown {
1541+ idxs.push(idx);
1542+ shown.push(p.clone());
1543+ }
1544+ Ok(())
1545+ })
1546+ .unwrap();
1547+ assert_eq!(shown.len(), collected.len(), "callback count vs shown frames");
1548+ assert!(live >= shown.len(), "every shown picture is also a callback");
1549+ assert!(
1550+ idxs.windows(2).all(|w| w[0] <= w[1]),
1551+ "decode indices out of order: {idxs:?}"
1552+ );
1553+ for (i, (got, want)) in shown.iter().zip(&collected).enumerate() {
1554+ assert_eq!(got.y, want.y, "frame {i} luma");
1555+ assert_eq!(got.u, want.u, "frame {i} U");
1556+ assert_eq!(got.v, want.v, "frame {i} V");
1557+ }
1558+
1559+ // A sink error stops the decode and comes back unchanged.
1560+ let mut seen = 0usize;
1561+ let err = decode_stream_with(&stream, |_, _, _| {
1562+ seen += 1;
1563+ Err(Error::corrupt("sink says stop"))
1564+ })
1565+ .unwrap_err();
1566+ assert_eq!(seen, 1, "decode continued past a failing sink");
1567+ assert!(format!("{err}").contains("sink says stop"), "{err}");
1568+ }
1569+
1485 use std::io::Write;1570 use std::io::Write;
1486 use std::process::{Command, Stdio};1571 use std::process::{Command, Stdio};
1487 1572
lanes/streamsink-r1-run_film_fifo.shadded+52 -0
@@ -0,0 +1,52 @@
1+#!/bin/bash
2+# lane-streamsink r1: same census as run_film.sh, but our decoder streams its
3+# frames into a FIFO (ec_av1::stream::decode_stream_with, one frame written the
4+# moment it completes) and cmp2.py reads one frame from that FIFO and one from
5+# ffmpeg's stdout at a time. Neither side ever holds more than a frame, so the
6+# segment length no longer bounds memory -- peak RSS of the decoder is ~0.44 GB
7+# on a 4K 10-bit window regardless of how long the window is.
8+# usage: run_film_fifo.sh <name> <film> <width> <height> <seg_seconds> [probe]
9+set -u
10+S="$(cd "$(dirname "$0")" && pwd)"
11+NAME="$1"; FILM="$2"; W="$3"; H="$4"; SEG="$5"
12+PROBE="${6:-$HOME/.cache/cargo-target-streamsink/release/examples/decode_probe}"
13+T=$HOME/.cache/fullfilm-fifo/$NAME
14+rm -rf "$T"; mkdir -p "$T"
15+STATE=$T/state.json
16+DUR=$(ffprobe -v error -show_entries format=duration -of default=nw=1:nk=1 "$FILM" | cut -d. -f1)
17+echo "START name=$NAME res=${W}x${H} depth=10 codec=av1 duration_s=$DUR seg_s=$SEG mode=fifo"
18+T0=$(date +%s)
19+s=0
20+while [ "$s" -lt "$DUR" ]; do
21+ seg=$T/seg.obu; fifo=$T/ours.fifo
22+ rm -f "$seg" "$fifo"
23+ 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
24+ if [ ! -s "$seg" ]; then echo "t=${s}s NO-SEGMENT"; s=$((s+SEG)); continue; fi
25+ mkfifo "$fifo"
26+ base=$(python3 -c 'import json,sys,os
27+p=sys.argv[1]
28+print(json.load(open(p))["compared"] if os.path.exists(p) else 0)' "$STATE")
29+ EC_PROBE_OUT16="$fifo" timeout 7200 "$PROBE" "$seg" > "$T/probe.log" 2>&1 &
30+ probe=$!
31+ line=$(ffmpeg -nostdin -loglevel error -i "$seg" -pix_fmt yuv420p10le -f rawvideo - 2>/dev/null \
32+ | python3 "$S/cmp2.py" "$fifo" "$W" "$H" "$STATE" "$base")
33+ wait $probe; rc=$?
34+ r=$(grep -E '^REFUSED|^OK|panick|rror' "$T/probe.log" | head -1)
35+ [ $rc -ge 128 ] && r="KILLED(rc=$rc)"
36+ [ -z "$r" ] && r="NO-MATCH-LINE(rc=$rc)"
37+ now=$(date +%s); el=$((now-T0)); [ "$el" -lt 1 ] && el=1
38+ tot=$(python3 -c 'import json,sys,os
39+p=sys.argv[1]
40+print(json.load(open(p))["compared"] if os.path.exists(p) else 0)' "$STATE")
41+ fpm=$(python3 -c "print(round($tot*60.0/$el,2))")
42+ printf 't=%ss\t%s\t%b\telapsed_s=%s\tfpm=%s\n' "$s" "$r" "$line" "$el" "$fpm"
43+ rm -f "$seg" "$fifo"
44+ s=$((s+SEG))
45+done
46+now=$(date +%s); el=$((now-T0)); [ "$el" -lt 1 ] && el=1
47+python3 -c '
48+import json,sys
49+st=json.load(open(sys.argv[1])); el=int(sys.argv[2]); name=sys.argv[3]
50+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"
51+ % (name, st["compared"], st["differing"], st["first_bad"] if st["first_bad"] is not None else "-",
52+ st["first_bad_bytes"], st["max_bytes"], st["segments"], el, st["compared"]*60.0/el))' "$STATE" "$el" "$NAME"
lanes/streamsink-r1.report.mdadded+50 -0
@@ -0,0 +1,50 @@
1+# lane-streamsink r1 -- streaming decode entry point
2+
3+## What changed
4+- `crates/ec-av1/src/stream.rs:223` -- `decode_stream` is now a thin collecting wrapper;
5+ the decode loop lives in **`decode_stream_with(data, sink)`** (stream.rs:236),
6+ `sink: impl FnMut(&Picture, decode_idx: usize, shown: bool) -> Result<()>`.
7+ Each completed picture is handed to the sink and dropped; only the 8 reference
8+ slots (+ CDF/motion-field/segment-map slots) and the current frame stay alive.
9+ Hidden (`show_frame == 0`) frames are reported with `shown == false` and are not
10+ part of `decode_stream`'s Vec; `show_existing_frame` outputs and shown frames come
11+ with `shown == true` (grain applied, as before). A sink `Err` aborts the decode.
12+- Same file: the `EC_AV1_DUMP_TABLES` label used `pictures.len()`; it is a shown-output
13+ counter (`pictures_shown`) now, same numbers. `EC_AV1_FINAL_DUMP` /
14+ `EC_AV1_DECODE_ORDER_DUMP` already wrote one frame at a time (one frame-sized buffer).
15+- `crates/ec-av1/examples/decode_probe.rs:~270` -- decodes through `decode_stream_with`
16+ and writes each shown frame to `EC_PROBE_OUT16` (yuv420p10le) / `EC_PROBE_OUT`|argv[2]
17+ (8-bit) as it completes, into a file **or a FIFO**. The old path collected every
18+ Picture and then built a second full copy of the dump before one `fs::write` -- 2x the
19+ whole segment. OK/REFUSED/`wrote N bytes`/counter lines are unchanged.
20+- `crates/ec-av1/src/stream.rs` tests: `streaming_decode_matches_the_collecting_one`
21+ (same pictures, same order, one callback per shown frame, monotone decode idx, sink
22+ error aborts after 1 call).
23+- Runner: `<scratchpad>/fullfilm/run_film_fifo.sh` -- our decoder streams into a FIFO,
24+ `cmp2.py` (unchanged) reads one frame from the FIFO and one from ffmpeg per iteration.
25+
26+## Peak RSS (4K 10-bit 3840x1608, `systemd-run --scope -p MemoryMax=6G /usr/bin/time -v`, EC_PROBE_OUT16=/dev/null)
27+| stream | old (collect + 2nd copy) | new (streaming) |
28+|---|---|---|
29+| 8 s window, 384 shown frames | **6,280,804 kB (6.28 GB, at the cap)** | **436,404 kB (0.44 GB)** |
30+| 32 s window, 960 shown frames | not run (old scales linearly; 20+ GiB) | **437,860 kB (0.44 GB)** |
31+
32+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)
33+
34+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
35+
36+EVIDENCE: <scratchpad>/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
37+
38+## Suite
39+SUITE: `cargo test -p ec-av1 --lib` (systemd unit, EC_NOMEMGUARD=1 EC_AV1_REQUIRE_AOMENC=1, log
40+`$HOME/.cache/streamsink-suite.log`) -- **test result: ok. 430 passed; 0 failed; 38 ignored;
41+0 measured; 0 filtered out; finished in 891.27s**. Includes refusal_inventory (3),
42+gate_coverage (9), and the named film gates (128sb, hidden_arf, gm small-side,
43+mv-clamp/frame-edge) -- all ok.
44+
45+## Residue
46+- accepted: `decode_stream` clones each shown picture into its Vec (one extra frame at
47+ peak on the collecting path). Gates are small; the streaming path is the one that matters.
48+- deferred: the whole-Vec probe path was NOT kept behind an env -- the streaming output is
49+ byte-identical and the printed lines unchanged, so a second path would be dead code
50+ (unblocks: nothing; `git revert` of this commit if a consumer ever needs it).