diff --git a/crates/ec-av1/examples/enc_probe.rs b/crates/ec-av1/examples/enc_probe.rs index 8b9da7ca..4f9afc34 100644 --- a/crates/ec-av1/examples/enc_probe.rs +++ b/crates/ec-av1/examples/enc_probe.rs @@ -3,48 +3,45 @@ //! our encoder. Also the byte-exactness gate for encoder-internal rewrites: //! it prints each point's stream length and a hash of its bytes. //! -//! Usage: `enc_probe [q,q,..]` - -use std::process::Command; +//! Usage: `enc_probe [q,q,..]` +//! +//! `gate` as the width takes the native BD gate's own window on the clip +//! (`probe::gate_crop`, superblock-aligned centre crop) and ignores the height +//! argument; `EC_ENC_SS` is the gate's seek and `EC_ENC_VF` overrides the +//! filter chain. Without both of those the probe measures different pixels +//! than the gate it reports on. fn main() { let a: Vec = std::env::args().skip(1).collect(); - let (clip, width, height, frames) = ( - a[0].clone(), - a[1].parse::().unwrap(), - a[2].parse::().unwrap(), - a[3].parse::().unwrap(), - ); + let clip = a[0].clone(); + let frames: usize = a[3].parse().unwrap(); + let gate = a[1] == "gate"; + let (width, height) = match gate { + true => (0, 0), + false => (a[1].parse().unwrap(), a[2].parse().unwrap()), + }; let qs: Vec = a .get(4) .map_or_else(|| vec![150, 120, 90, 60], |s| s.split(',').map(|q| q.parse().unwrap()).collect()); - let out = Command::new("ffmpeg") - .args(["-v", "error", "-i", &clip, "-frames:v", &frames.to_string()]) - // lane-census: the BD gate's native rows CROP, they do not scale, so - // the census can ask for the gate's own recipe (`EC_ENC_VF`). - .args([ - "-vf", - &std::env::var("EC_ENC_VF").unwrap_or_else(|_| format!("scale={width}:{height}")), - ]) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) - .output() - .expect("ffmpeg failed to run"); - assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); - let (luma, chroma) = (width * height, width * height / 4); - let frame_len = luma + 2 * chroma; - let source: Vec = (0..frames) - .map(|i| { - let b = &out.stdout[i * frame_len..][..frame_len]; - ec_av1::encode::Picture { - width, - height, - y: b[..luma].iter().map(|&v| u16::from(v)).collect(), - u: b[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), - v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), - } - }) - .collect(); + // lane-census/lane-probe: the BD gate's native rows CROP (`EC_ENC_VF`) and + // SEEK (`EC_ENC_SS`) -- without the seek this probe read film B's black + // leader and every census off it was probe-relative. + let (vf, width, height) = match gate { + true => ec_av1::probe::gate_crop(&clip), + false => ( + std::env::var("EC_ENC_VF").unwrap_or_else(|_| format!("scale={width}:{height}")), + width, + height, + ), + }; + let vf = match gate { + true => std::env::var("EC_ENC_VF").unwrap_or(vf), + false => vf, + }; + eprintln!("probe: {width}x{height} vf={vf}"); + let skip = std::env::var("EC_ENC_SS").unwrap_or_else(|_| "0".into()); + let source = ec_av1::probe::source(&clip, &skip, &vf, width, height, frames); let start = std::time::Instant::now(); for q in qs { diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 20d0ff9e..d55c563b 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -12996,37 +12996,11 @@ mod tests { height: usize, frames: usize, ) -> Vec { - let out = Command::new("ffmpeg") - .args(["-v", "error", "-ss", skip, "-i", clip]) - .args(["-frames:v", &frames.to_string()]) - .args(["-vf", vf]) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) - .output() - .expect("ffmpeg failed to run"); - assert!( - out.status.success(), - "ffmpeg: {}", - String::from_utf8_lossy(&out.stderr) - ); - let (luma, chroma) = (width * height, width * height / 4); - let frame_len = luma + 2 * chroma; - assert_eq!( - out.stdout.len(), - frame_len * frames, - "expected {frames} 4:2:0 frames" - ); - (0..frames) - .map(|i| { - let bytes = &out.stdout[i * frame_len..][..frame_len]; - Picture { - width, - height, - y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), - u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), - v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), - } - }) - .collect() + // ONE definition of the gate's loader recipe, shared with + // `examples/enc_probe` so the instrument cannot arm a different source + // than the gate it reports on (class `instrument disagrees with the + // gate`; lane-probe). + crate::probe::source(clip, skip, vf, width, height, frames) } /// The standing regression gate on real content: 12 frames of a real @@ -14507,15 +14481,7 @@ mod tests { /// The video stream's coded size, from ffprobe. fn probe_dims(clip: &str) -> Option<(usize, usize)> { - let out = Command::new("ffprobe") - .args(["-v", "error", "-select_streams", "v:0"]) - .args(["-show_entries", "stream=width,height", "-of", "csv=p=0"]) - .arg(clip) - .output() - .ok()?; - let text = String::from_utf8_lossy(&out.stdout); - let mut f = text.trim().split(','); - Some((f.next()?.trim().parse().ok()?, f.next()?.trim().parse().ok()?)) + crate::probe::dims(clip) } /// The rows of [`bd_rate_screen_native`] -- (label, path, seek) -- shared @@ -14777,24 +14743,16 @@ mod tests { println!("|---|---|---|---|---|"); for (name, path, seek) in &clips { let fctx = &crate::decode::FrameCtx::new(); - let Some((nw, nh)) = probe_dims(path) else { + if probe_dims(path).is_none() { eprintln!("SKIP {name}: ffprobe gave no size"); continue; - }; + } // A whole number of 128-wide superblocks, at most 1920x1024, out // of the middle of the frame; the offsets stay even for 4:2:0. - let cw = nw.min(1920) / 128 * 128; - let ch = nh.min(1024) / 128 * 128; - assert!(cw >= 128 && ch >= 128, "{name}: {nw}x{nh} is smaller than a superblock"); - let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1); - let source = clip_frames_vf( - path, - seek, - &format!("crop={cw}:{ch}:{x}:{y}"), - cw, - ch, - frames, - ); + // ONE definition, shared with `examples/enc_probe` so the probe + // cannot measure a different window than this gate (lane-probe). + let (vf, cw, ch) = crate::probe::gate_crop(path); + let source = clip_frames_vf(path, seek, &vf, cw, ch, frames); SCREEN_FRAMES.iter().for_each(|c| { c.store(0, std::sync::atomic::Ordering::Relaxed); }); @@ -14951,4 +14909,92 @@ mod tests { ); } } + + /// The probe arms the gate's source (lane-probe, class `instrument + /// disagrees with the gate`). `examples/enc_probe` built its own ffmpeg + /// command line and had no `-ss`, so it read film B from frame 0 -- a + /// black leader -- and coded 59 kB where the gate's own ladder point + /// coded 89 kB of the same title; every census taken through it was + /// probe-relative. Both now call [`crate::probe::source`]; this pins that + /// the shared loader honours the seek (arming the probe's way and the + /// gate's way gives byte-identical streams, and dropping the seek does + /// not), on a synthetic clip whose content moves over time. + #[test] + fn the_probe_arms_the_gates_source() { + let _knobs = crate::speed::knob_write(); + if !have_ffmpeg() { + eprintln!("SKIP the_probe_arms_the_gates_source: no ffmpeg"); + return; + } + let dir = std::env::temp_dir().join(format!("ec-av1-probe-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let clip = dir.join("testsrc2.y4m"); + // 384x202: neither side is a multiple of 128, so the gate's centre + // window is a real derivation and not the frame itself -- exactly the + // shape film B has (3840x1608, never 3840x2160). + let ok = Command::new("ffmpeg") + .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=384x202:rate=10"]) + .args(["-frames:v", "20", "-pix_fmt", "yuv420p"]) + .arg(&clip) + .status() + .expect("ffmpeg failed to run") + .success(); + assert!(ok, "ffmpeg could not write the synthetic clip"); + let path = clip.to_str().unwrap(); + + // The window: superblock-aligned, centred, even offsets. + let (vf, w, h) = crate::probe::gate_crop(path); + assert_eq!((vf.as_str(), w, h), ("crop=384:128:0:36", 384, 128)); + + let (seek, q) = ("00:00:01", 150u8); + let gate = clip_frames_vf(path, seek, &vf, w, h, 6); + let probe = crate::probe::source(path, seek, &vf, w, h, 6); + assert!( + gate.iter().zip(&probe).all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v), + "the probe's source differs from the gate's at the same window" + ); + let bytes = |src: &[Picture]| { + encode_sequence_with_ctx(src, q, 0.5, &crate::decode::FrameCtx::new()) + .unwrap() + .stream + }; + assert_eq!(bytes(&gate), bytes(&probe), "probe and gate code different bytes"); + // The two witnesses that both halves of the arming reach ffmpeg: the + // seek, and the crop's own offset (the film-B defect in miniature -- + // the probe was reading `crop=..:568` of a 1608-high frame). + let unseeked = crate::probe::source(path, "0", &vf, w, h, 6); + assert_ne!( + bytes(&gate), + bytes(&unseeked), + "seeked and unseeked arming coded the same bytes -- the seek is inert" + ); + let offset = crate::probe::source(path, seek, "crop=384:128:0:0", w, h, 6); + assert_ne!( + bytes(&gate), + bytes(&offset), + "centred and top-aligned windows coded the same bytes -- the crop is inert" + ); + std::fs::remove_dir_all(&dir).ok(); + } + + /// lane-probe diagnostic: the gate's own loader + ladder call for ONE + /// point inside the test binary, to compare against `examples/enc_probe`. + #[test] + #[ignore = "diagnostic: needs ffmpeg and a clip"] + fn probe_parity_point() { + let _knobs = crate::speed::knob_write(); + let g = |k: &str| std::env::var(k).unwrap(); + let (w, h) = g("EC_PARITY_DIMS").split_once(':').map(|(a, b)| (a.parse::().unwrap(), b.parse::().unwrap())).unwrap(); + let frames: usize = g("EC_PARITY_FRAMES").parse().unwrap(); + let q: u8 = g("EC_PARITY_Q").parse().unwrap(); + let source = clip_frames_vf(&g("EC_PARITY_CLIP"), &g("EC_PARITY_SS"), &g("EC_PARITY_VF"), w, h, frames); + let fctx = &crate::decode::FrameCtx::new(); + let e = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap(); + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + for &b in &e.stream { + hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3); + } + eprintln!("PARITY q={q} bytes={} fnv1a={hash:016x} speed={} pyramid {:?} effective {:?}", + e.stream.len(), crate::speed::speed(), crate::encoder::Pyramid::from_env(), last_sequence_pyramid()); + } } diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index 497cca04..ee977bcb 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -45,6 +45,7 @@ pub mod msac; pub mod mvstack; pub mod obu; mod par; +pub mod probe; pub mod quant; mod refusal_inventory; pub mod speed; diff --git a/crates/ec-av1/src/probe.rs b/crates/ec-av1/src/probe.rs new file mode 100644 index 00000000..d7159055 --- /dev/null +++ b/crates/ec-av1/src/probe.rs @@ -0,0 +1,86 @@ +//! The BD gate's source arming, shared with `examples/enc_probe` (lane-probe). +//! +//! The probe used to build its own ffmpeg command line and dropped the gate's +//! `-ss` seek, so it read film B's black leader and every census taken through +//! it was probe-relative (59 kB where the gate's own ladder point coded 89 kB +//! of the same title). One definition now serves both: the gate's +//! `clip_frames_vf` and the probe both call [`source`], so the two can only +//! differ in the arguments they pass, which +//! `encode::tests::the_probe_arms_the_gates_source` pins. + +use crate::encode::Picture; +use std::process::Command; + +/// The video stream's coded size, from ffprobe. +#[must_use] +pub fn dims(clip: &str) -> Option<(usize, usize)> { + let out = Command::new("ffprobe") + .args(["-v", "error", "-select_streams", "v:0"]) + .args(["-show_entries", "stream=width,height", "-of", "csv=p=0"]) + .arg(clip) + .output() + .ok()?; + let text = String::from_utf8_lossy(&out.stdout); + let mut f = text.trim().split(','); + Some((f.next()?.trim().parse().ok()?, f.next()?.trim().parse().ok()?)) +} + +/// The native BD gate's window on `clip`: a whole number of 128-wide +/// superblocks, at most 1920x1024, out of the MIDDLE of the coded frame, with +/// even offsets for 4:2:0 -- as an ffmpeg `crop` filter plus its size. +/// +/// This lives here because the probe used to be handed the crop by hand, and +/// a hand-written `crop=1920:1024:960:568` (a 2160-high frame that film B, +/// coded 3840x1608, is not) put the instrument on different pixels than the +/// gate: 60 kB where the gate's own q=150 point coded 90 kB. +/// +/// # Panics +/// When ffprobe cannot read the size, or the frame is under one superblock. +#[must_use] +pub fn gate_crop(clip: &str) -> (String, usize, usize) { + let (nw, nh) = dims(clip).expect("ffprobe gave no size"); + let cw = nw.min(1920) / 128 * 128; + let ch = nh.min(1024) / 128 * 128; + assert!(cw >= 128 && ch >= 128, "{nw}x{nh} is smaller than a superblock"); + let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1); + (format!("crop={cw}:{ch}:{x}:{y}"), cw, ch) +} + +/// `frames` pictures of `clip` from `skip` through the filter chain `vf`, as +/// planar 8-bit 4:2:0 at `width`x`height` -- the BD gate's loader recipe. +/// +/// # Panics +/// When ffmpeg cannot be run, fails, or delivers a different number of frames. +#[must_use] +pub fn source( + clip: &str, + skip: &str, + vf: &str, + width: usize, + height: usize, + frames: usize, +) -> Vec { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-ss", skip, "-i", clip]) + .args(["-frames:v", &frames.to_string()]) + .args(["-vf", vf]) + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) + .output() + .expect("ffmpeg failed to run"); + assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); + let (luma, chroma) = (width * height, width * height / 4); + let frame_len = luma + 2 * chroma; + assert_eq!(out.stdout.len(), frame_len * frames, "expected {frames} 4:2:0 frames"); + (0..frames) + .map(|i| { + let b = &out.stdout[i * frame_len..][..frame_len]; + Picture { + width, + height, + y: b[..luma].iter().map(|&v| u16::from(v)).collect(), + u: b[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), + v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), + } + }) + .collect() +} diff --git a/lanes/census-longgop-v2.md b/lanes/census-longgop-v2.md new file mode 100644 index 00000000..5883fe30 --- /dev/null +++ b/lanes/census-longgop-v2.md @@ -0,0 +1,56 @@ +# Long-GOP census v2 — film B, 48 frames, q=150 (lane-probe) + +The v1 census (and every "probe-relative" number quoted from it) measured the +WRONG PIXELS. `examples/enc_probe` was handed its window by hand as +`crop=1920:1024:960:568`, i.e. the centre of a 3840x**2160** frame — film B is +coded **3840x1608**, so the gate's own window is `crop=1920:1024:960:292`. Same +q, same source file, different picture: 60466 B (v1) vs **90674 B** (v2). + +Arming, now derived by one shared function (`ec_av1::probe::gate_crop`, called +by both the probe and `encode::tests::native_bd_arm`): + + EC_ENC_SS=00:40:00 EC_ENC_OUT= EC_AV1_BITCENSUS=1 \ + enc_probe gate 0 48 150 # -> 90674 bytes + EC_AV1_BITCENSUS=1 syntax_census /ours-q150.obu /source.yuv + +90674 B is **byte-exact with `encode::tests::bd_rate_film_long_gop`'s own +q=150 ladder point** (gate row: `46.76 dB/90674 B`). Every number below is +therefore the gate's stream. + +Pyramid: default `mini_gop 8, arf -32, leaf +12, mid -8, key -48` (requested = +effective; the content gate leaves this clip on the pyramid). 48 pictures = +1 key + 6 ARF + 6 mid + 35 leaf. + +## Per level (payload bytes as the decoder censuses them; 89514 B of the +## 90674 B stream, the rest is sequence/frame OBU overhead) + +| level | frames | qindex | bytes | share | bytes/frame | PSNR-Y (display) | +|---|---|---|---|---|---|---| +| key | 1 | 102 | 19321 | 21.6% | 19321 | 47.67 dB | +| ARF | 6 | 118 | 48126 | 53.8% | 8021 | 46.01 dB | +| mid | 6 | 142 | 10331 | 11.5% | 1722 | 45.79 dB | +| leaf | 35 | 162 | 11736 | 13.1% | 335 | 45.27 dB | +| ALL | 48 | - | 89514 | 100% | 1865 | 45.47 dB | + +Where the bits go (census bits, per level): + +| level | coeff | literal | mode | mv | partition | tx size/type | +|---|---|---|---|---|---|---| +| key | 66.6% | 22.0% | 9.4% | – | 0.8% | 1.3% | +| ALL | 53.6% | 17.1% | 17.6% | 8.0% | 2.9% | 0.7% | + +Structure: ALL = intra 3.0% / single-ref 93.0% / compound 4.0% area, skip +85.7%; refs LAST 95.9%, GOLDEN 0.8%, ALTREF 0.3%; blocks 64x64 54.3%, 32x32 +26.3%, 16x16 14.7%, 8x8 4.8%. The ARF level carries the group (53.8% of the +bytes on 12.5% of the frames, skip 66.4%); the leaf level is 94.8% skip area +and 335 B a picture. + +## For the allocation lanes + +- Quote THIS table, not v1: the level shares moved (ARF 49.3% -> 53.8%, key + 25.6% -> 21.6%) because the v1 window was a different, flatter part of the + frame. +- Any probe run on a real film must pass `gate` as the width argument and set + `EC_ENC_SS` to the gate's pinned seek (film A `00:35:00`, film B `00:40:00`); + a hand-written `crop=` is how v1 went wrong. +- Regression cover: `encode::tests::the_probe_arms_the_gates_source`.