From e24fe61c36247c4abd9fe974fc92dc32513e9cfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 12 Sep 2026 16:27:15 +0300 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor(engine):=20the=20?= =?UTF-8?q?software=20H.264=20seat=20decodes=20with=20ec-h264?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit decode::run leaves `rusty_h264` for `ec_h264::H264Decoder` (path dep on ../../edith_codecs, `ec_core` beside it for the registry contract): packets in over the demuxer's Annex-B access units, frames out through send_packet/receive_frame with a flush at end of stream so the reorder delay releases its tail. Semantics: the old loop emitted pictures in decode order and counted access units -- a corner-cut that only held for Baseline, and scrambled exactly the B-picture streams it could not reorder. ec-h264 bumps the DPB (clause C.4.5.3) and hands pictures back in display order, so the landing index the demuxer's seek reports and the label each frame ships with now count the same thing: timeline positions, which the transport, skip_for_speed and the hardware backend already assumed. Witnessed on test_high.mp4 (B pictures): the seat delivers 0..150 in order where the old seat delivered the same frames reshuffled and mislabelled. Tests: tests/sw_backends.rs is the byte-exactness witness -- ec-h264 against rusty_h264 (kept as the independent oracle) on CAVLC Baseline and CABAC High fixtures, decode order per position and display order as a multiset, with the reorder engaged only where the stream reorders; hw_decode's software halves (seek_matches_linear, range_stops_at_end, hardware_matches_software_on_frame_30) pass against the VA-API backend. Throughput (raw demux+decode, idle machine, best of three): 1.52x rusty_h264 on a 1080p Main export and 1.57x on a 4K Main render, 1.02x on a 1440p High screen recording, 1.17x on CAVLC Baseline; 0.80-0.81x on the two B-picture CABAC streams measured -- the measured price of the full DPB the old seat skipped. cargo check -p engine: 0 warnings. rusty_h264 stays linked for the export encode seat (Encoder, EncoderConfig, Preset, YuvFrame) and export's own SwDecoder, so the dep, the rusty_h264-common vendored patch (the rusty_alloc global_allocator landmine) and their Cargo.lock entries are load-bearing until that seat moves to ec_h264::Encoder; caps names the split honestly ('ec-h264 / rusty_h264'). --- Cargo.lock | 45 ++++++- Cargo.toml | 4 + crates/engine/Cargo.toml | 46 ++++--- crates/engine/src/caps.rs | 4 +- crates/engine/src/decode.rs | 158 +++++++++++++++-------- crates/engine/src/demux.rs | 8 +- crates/engine/tests/h264_mkv.rs | 2 +- crates/engine/tests/sw_backends.rs | 199 +++++++++++++++++++++++++++++ 8 files changed, 385 insertions(+), 81 deletions(-) create mode 100644 crates/engine/tests/sw_backends.rs diff --git a/Cargo.lock b/Cargo.lock index 8e32099..d313dd1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1588,6 +1588,26 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" +[[package]] +name = "ec-core" +version = "0.1.0" + +[[package]] +name = "ec-h264" +version = "0.1.0" +dependencies = [ + "ec-core", + "ec-h264-syntax", + "wide 1.7.0", +] + +[[package]] +name = "ec-h264-syntax" +version = "0.1.0" +dependencies = [ + "ec-core", +] + [[package]] name = "edith" version = "0.1.0" @@ -1636,6 +1656,8 @@ checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" name = "engine" version = "0.1.0" dependencies = [ + "ec-core", + "ec-h264", "flacenc", "hound", "image", @@ -5149,7 +5171,7 @@ name = "rusty_h264-common" version = "0.9.1" dependencies = [ "bytemuck", - "wide", + "wide 0.7.33", ] [[package]] @@ -5232,6 +5254,15 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "safe_arch" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42c6efa15875e6ecb39ca61fb0b0c1a40b84fac5a5ffe71eef7d1000c8eb3f5f" +dependencies = [ + "bytemuck", +] + [[package]] name = "same-file" version = "1.0.6" @@ -7077,7 +7108,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ce5da8ecb62bcd8ec8b7ea19f69a51275e91299be594ea5cc6ef7819e16cd03" dependencies = [ "bytemuck", - "safe_arch", + "safe_arch 0.7.4", +] + +[[package]] +name = "wide" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cf05ca94c9fba0c51316899caa1d1e74a064fc310a5efa7375e614343d415be" +dependencies = [ + "bytemuck", + "safe_arch 1.2.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 1cd39ee..ddee086 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -77,6 +77,10 @@ edition = "2024" # default and the six-line declaration in `src/lib.rs`; every # line of codec code is byte-identical to 0.9.1, so decode stays # bit-exact and the process gets glibc's malloc back. +# (Since 2026-09-12 only the software H.264 *encode* seat +# still links this crate -- decode is `ec-h264`, which carries +# no allocator of its own; the patch stays until the encode +# seat moves too.) # mp4 - reads the `mp4a` sample entry as ISO only: the 8 bytes # QuickTime uses for version/revision/vendor are skipped as # reserved, so a version-1 SoundDescription's 16-byte tail diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index a80cb5e..2cd4245 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -34,18 +34,16 @@ mp4 = "0.14" # pulls this exact version in through `png`, and it is the pure-Rust inflate the # rest of the ecosystem is built on. miniz_oxide = "0.8" -# The software H.264 pair, and the only software decoder this project has for -# any format. Pinned exactly, like `ruopus` and `oxideav-ac3` below, because a -# decoder is a bit-exactness dependency -- and 0.9.1 is where that stopped being -# a figure of speech. Measured 2026-08-12 against ffmpeg's own decode of a 1080p -# High and a 720p Main clip, 750 pictures between them: 0.8 matched it -# byte-for-byte on 26 of the 750 and drifted on the rest (worst 69.8 dB PSNR -- -# invisible, but wrong); 0.9.1 matches on all 750. It is also 1.44x faster at it -# (247 Mpx/s against 171 on the 1080p clip, single-threaded); software *encode* -# is unchanged within noise, so this is a decode bump that the encoder came -# along with. `default-features = false` is what keeps `asm` off: those are -# vendored openh264 SIMD kernels that want `nasm` at build time, which this -# project's no-install rule forbids, and the crate enables them by default. +# The software H.264 *encoder* -- since the decode seat moved to `ec-h264` +# above, the only seat still on this crate. Pinned exactly, like `ruopus` and +# `oxideav-ac3` below, because a codec is a reproducibility dependency; the +# 0.9.1 pin is the one the decode half set on 2026-08-12, when 750 pictures of +# a 1080p High and a 720p Main clip decoded byte-for-byte against ffmpeg where +# 0.8 had drifted (software *encode* was unchanged within noise across that +# bump, so the pin costs the encoder nothing). `default-features = false` is +# what keeps `asm` off: those are vendored openh264 SIMD kernels that want +# `nasm` at build time, which this project's no-install rule forbids, and the +# crate enables them by default. # # What that line does not turn off, and cannot: the facade asks for its three # sub-crates with *their* defaults, and `rusty_h264-common`'s default installs @@ -55,10 +53,26 @@ miniz_oxide = "0.8" # and it crashed the editor: sustained scrubbing churns decode-worker threads, # and it segfaulted on a new thread's *first* allocation. `common` is therefore # vendored with that declaration removed (workspace root `[patch.crates-io]`), -# which is the only way to decline it -- the codec itself is untouched and still -# bit-exact. Frame-threaded decode arrived in 0.9 as well and -# is opt-in through `RS_H264_FRAME_THREADS`, unset here -- the decode loop is -# serial exactly as it was. +# which is the only way to decline it -- the codec itself is untouched. When +# the export encode seat moves to `ec_h264::Encoder`, this line, the patch and +# the vendored crate go with it. +# The software H.264 *decoder*, which is the project's own: `ec-h264` +# (I/P/B, CAVLC and CABAC, full DPB, weighted prediction, in-loop deblocking), +# bit-exact against the JVT conformance suite. It took this seat from +# `rusty_h264` on 2026-09-12. Raw decode throughput (demux+decode, no render, +# best of three warm passes, otherwise idle machine): 1.5x `rusty_h264` on a +# 1080p Main export and a 4K Main render, 1.0x on a 1440p High screen +# recording, 1.17x on a CAVLC Baseline fixture; 0.80x on the two B-picture +# CABAC streams measured (a 720p High fixture and a 720p Blu-ray episode) -- +# the price of the full DPB the old seat skipped with its decode-order +# corner-cut, which scrambled exactly those streams. It hands pictures back in +# display order, which is what every reader of `frame.index` already assumed +# (the hardware backend always did; see `tests/sw_backends.rs` for the +# byte-exactness witness against `rusty_h264`, kept as the independent oracle). +ec-h264 = { path = "../../../edith_codecs/crates/ec-h264" } +# Its shared IR (packets, frames, the registry decoder contract the seat is +# written against), direct because decode.rs names those types itself. +ec-core = { path = "../../../edith_codecs/crates/ec-core" } rusty_h264 = { version = "=0.9.1", default-features = false } # Both halves of AAC, and the only crate here that is asked for both. The # *encoder*, so an mp4's sound can be a mix rather than a copy: an equalized (or diff --git a/crates/engine/src/caps.rs b/crates/engine/src/caps.rs index 27c5862..5b75d58 100644 --- a/crates/engine/src/caps.rs +++ b/crates/engine/src/caps.rs @@ -27,7 +27,7 @@ const HW_CODECS: [(u32, &str); 4] = [ /// because the answer to "why is my HEVC file so large" is `oxideav-h265 /// intra`, and the row that says so is the row that answers it. const SW_CODECS: [(&str, &str, bool, bool); 10] = [ - ("H.264", "rusty_h264", true, true), + ("H.264", "ec-h264 / rusty_h264", true, true), ("HEVC", "oxideav-h265 intra", false, true), ("AV1", "rav1e", false, true), ("AAC", "rusty_aac", true, true), @@ -137,7 +137,7 @@ mod tests { // Decode-only crates must not read as encoders, and the seat words are // the only thing saying which is which. assert!(line.contains("AC-3 dec (oxideav-ac3)")); - assert!(line.contains("H.264 dec+enc (rusty_h264)")); + assert!(line.contains("H.264 dec+enc (ec-h264 / rusty_h264)")); assert!(line.contains("HEVC enc (oxideav-h265 intra)")); } } diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 7fbca00..371d99d 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -7,7 +7,11 @@ use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel}; use std::thread; -use rusty_h264::Decoder; +use ec_core::frame::VideoFrame; +use ec_core::registry::{CodecId, CodecParameters}; +use ec_core::registry::Decoder as _; +use ec_core::{Packet, TimeBase}; +use ec_h264::H264Decoder; use crate::color::ColorParams; use crate::colorspace::{ColorDescription, Matrix, Transfer}; @@ -21,7 +25,7 @@ use crate::transform::TransformParams; /// One decoded picture, ready to hand to a renderer. pub struct Frame { - /// Position in decode order, starting at 0. + /// Position in display order, starting at 0. pub index: u32, pub width: u32, pub height: u32, @@ -42,7 +46,7 @@ pub enum Backend { Opening, /// The VA-API plugin (`libengine_hw.so`). Hardware, - /// `rusty_h264`, in this process. + /// `ec-h264`, in this process. Software, /// A still image: one `image` decode, no stream and no decoder to pick. Still, @@ -1006,12 +1010,12 @@ fn run_span( eprintln!("hardware decode failed before any frame, falling back to software"); } // ...except where there is nothing to fall back to. Feeding HEVC or VP9 - // bytes to `rusty_h264` would be garbage, not a fallback. + // bytes to the H.264 decoder would be garbage, not a fallback. if opened.meta.codec != Codec::H264 { eprintln!("{}", opened.meta.codec.needs_plugin()); return; } - eprintln!("decode backend: software (rusty_h264)"); + eprintln!("decode backend: software (ec-h264)"); backend.set(Backend::Software); run(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed) } @@ -1620,78 +1624,120 @@ fn run( // A decoder per span, and cheap: it is a parameter-set map and a picture // buffer, while the *demuxer* -- whose index cost seconds to build -- is the // one this worker keeps. - let mut decoder = Decoder::new(); + let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)) + .expect("ec-h264 takes its own codec id"); // Decoding has to restart at a sync sample, so pictures between it and // `start_frame` are decoded (the target frame references them) but never // converted or sent. Signed, because the landing sync sample can sit inside // what the file's edit list trims, i.e. *before* frame 0. let mut index = demuxer.seek_to_sync_at_or_before(start_frame); + // Pictures leave the decoder in display order -- clause C.4.5.3 bumps the + // decoded picture buffer -- and the landing index above is a display index + // by the demuxer's own contract, so the two count one to one. The decode + // order this loop used to emit was a corner-cut that only held for + // Baseline: a stream with B pictures arrived scrambled and mislabelled, + // and every reader of `index` (the transport's playhead, `skip_for_speed`, + // the export's frame map) reads it as a timeline position. let mut skipped = 0; - - // corner-cut: emits pictures in decode order. Fine for Baseline (no B-frames); - // reordering streams need POC-sorted output before display. - loop { + // Set once the demuxer runs dry: `flush` makes the decoder release every + // picture its reorder delay still holds, and the drain below ends on + // `Error::Eof` once they are out. + let mut flushed = false; + // Every way this span ends: abort, consumer gone, end of the requested + // range, end of stream. + let mut done = false; + while !done { if abort.hit() { break; } - let au = match demuxer.next_access_unit() { - Ok(Some(au)) => au, - Ok(None) => break, + // One access unit is one packet. No timestamps travel with it: the + // presentation order comes out of the bitstream's own POC, and `index` + // is counted off the pictures as the decoder releases them. + match demuxer.next_access_unit() { + Ok(Some(au)) => { + let packet = Packet::new(0, TimeBase::new(1, 1), au); + if let Err(e) = decoder.send_packet(&packet) { + eprintln!("decode error at access unit {index}: {e}"); + break; + } + } + Ok(None) => { + flushed = true; + if let Err(e) = decoder.flush() { + eprintln!("decode error at end of stream: {e}"); + break; + } + } Err(e) => { eprintln!("demux error: {e}"); break; } - }; - let yuv = match decoder.decode(&au) { - Ok(Some(yuv)) => yuv, - Ok(None) => continue, - Err(e) => { - eprintln!("decode error at access unit {index}: {e}"); - break; + } + // Take everything the packet released; `NeedMore` is the signal to go + // back for the next access unit. + loop { + let pic = match decoder.receive_frame() { + Ok(pic) => pic, + Err(e) if e.is_need_more() || e.is_eof() => break, + Err(e) => { + eprintln!("decode error at access unit {index}: {e}"); + break; + } + }; + let ec_core::frame::Frame::Video(pic) = pic else { + continue; + }; + if index < i64::from(start_frame) { + index += 1; + continue; } - }; - if index < i64::from(start_frame) { + let due = index as u32; index += 1; - continue; - } - let due = index as u32; - index += 1; - if abort.late(due) { - if skipped < LATE_RUN { - skipped += 1; + if abort.late(due) { + if skipped < LATE_RUN { + skipped += 1; + } else { + skipped = 0; + if send_picture(&pic, due, render, tx) { + done = true; // consumer went away + break; + } + } + } else if skip_for_speed(speed, start_frame, due, end_frame) { + // Redundant by construction, not by lateness: no run limit + // needed (see `skip_for_speed`). } else { skipped = 0; - let frame = render.frame( - due, - &yuv.y, - &yuv.u, - &yuv.v, - yuv.width as u32, - yuv.height as u32, - ); - if tx.send(frame).is_err() { - break; // consumer went away + if send_picture(&pic, due, render, tx) { + done = true; // consumer went away + break; } } - } else if skip_for_speed(speed, start_frame, due, end_frame) { - // Redundant by construction, not by lateness: no run limit needed - // (see `skip_for_speed`). - } else { - skipped = 0; - let frame = render.frame( - due, - &yuv.y, - &yuv.u, - &yuv.v, - yuv.width as u32, - yuv.height as u32, - ); - if tx.send(frame).is_err() { - break; // consumer went away + if index >= i64::from(end_frame) { + done = true; // end of the requested range + break; } } - if index >= i64::from(end_frame) { - break; // end of the requested range + if flushed { + done = true; } } } + +/// Converts one decoded picture and queues it. `true` when the consumer went +/// away, so the span stops rather than keeps decoding into a void. +fn send_picture(pic: &VideoFrame, due: u32, render: &mut Render, tx: &SyncSender) -> bool { + // The decoder crops each picture into tightly packed planes, the shape + // every converter below takes. A padded plane would render skewed rather + // than subtly wrong, so the assumption is pinned where it is relied on -- + // free in a release build. + let (y, u, v) = (&pic.planes[0], &pic.planes[1], &pic.planes[2]); + debug_assert_eq!(y.stride, pic.width as usize, "padded luma plane"); + debug_assert_eq!( + u.stride, + pic.width.div_ceil(2) as usize, + "padded chroma plane" + ); + let frame = render.frame(due, &y.data, &u.data, &v.data, pic.width, pic.height); + tx.send(frame).is_err() +} diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 6581359..33208f1 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -132,10 +132,10 @@ impl Codec { } } - /// Why a file can be refused outright: `rusty_h264` is the only software - /// decoder in the project and there is no pure-Rust HEVC or VP9 one to fall - /// back to, so without the plugin there is nothing to decode with. Shared - /// so playback and export refuse in the same words. + /// Why a file can be refused outright: the software decoder this project + /// carries is H.264's (`ec-h264`), and there is no pure-Rust HEVC or VP9 + /// one to fall back to, so without the plugin there is nothing to decode + /// with. Shared so playback and export refuse in the same words. pub fn needs_plugin(self) -> String { format!( "{name} needs the VA-API plugin (libengine_hw.so) — there is no software {name} decoder", diff --git a/crates/engine/tests/h264_mkv.rs b/crates/engine/tests/h264_mkv.rs index 098a888..627e523 100644 --- a/crates/engine/tests/h264_mkv.rs +++ b/crates/engine/tests/h264_mkv.rs @@ -2,7 +2,7 @@ //! container that used to refuse it by name. Nothing new decodes here -- the //! demuxer reframes the `avcC`-prefixed blocks to Annex-B and hands them to the //! same dispatch an mp4's samples go to -- so the whole file runs with nothing -//! installed, on `rusty_h264` if the plugin is absent. +//! installed, on the software seat (`ec-h264`) if the plugin is absent. //! //! ```text //! cargo test -p engine --test h264_mkv diff --git a/crates/engine/tests/sw_backends.rs b/crates/engine/tests/sw_backends.rs new file mode 100644 index 0000000..3509037 --- /dev/null +++ b/crates/engine/tests/sw_backends.rs @@ -0,0 +1,199 @@ +//! The H.264 software decode seat swap: `ec-h264` (the in-project decoder) is +//! the seat, `rusty_h264` -- the decoder this seat carried for years, and still +//! the encoder behind software H.264 export -- is the independent witness. +//! +//! H.264 8-bit decode is bit-exact by conformance, so two correct decoders +//! handed the same access units must return the same pictures, byte for byte; +//! this is the software twin of `hw_decode::hardware_matches_software_on_frame_30`. +//! The one deliberate difference is *order*: `rusty_h264` releases pictures in +//! decode order, `ec-h264` in display order (clause C.4.5.3), which is what the +//! rest of the engine already assumed -- the hardware backend behaves the same +//! way, `frame.index` is a timeline position, and the old seat's decode-order +//! corner-cut scrambled B-picture streams. +//! +//! ```text +//! cargo test -p engine --test sw_backends -- --test-threads=1 +//! ``` + +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; +use std::path::{Path, PathBuf}; + +use ec_core::registry::{CodecId, CodecParameters, Decoder as _}; +use ec_core::{Packet, TimeBase}; +use ec_h264::H264Decoder; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// Every access unit of the file, in container (decode) order. +fn access_units(path: &Path) -> Vec> { + let (_, mut demuxer) = engine::demux::Demuxer::open(path).expect("open"); + let mut aus = Vec::new(); + while let Ok(Some(au)) = demuxer.next_access_unit() { + aus.push(au); + } + assert!(!aus.is_empty(), "{}: no access units", path.display()); + aus +} + +/// One decoded picture as plain planes, whatever the decoder calls them. +struct Picture { + width: usize, + y: Vec, + u: Vec, + v: Vec, +} + +impl Picture { + fn hash(&self) -> u64 { + let mut hasher = DefaultHasher::new(); + self.width.hash(&mut hasher); + self.y.hash(&mut hasher); + self.u.hash(&mut hasher); + self.v.hash(&mut hasher); + hasher.finish() + } +} + +/// `rusty_h264`, decode order -- the order it has always emitted. +fn decode_rusty(aus: &[Vec]) -> Vec { + let mut decoder = rusty_h264::Decoder::new(); + let mut pictures = Vec::new(); + for au in aus { + if let Some(yuv) = decoder.decode(au).expect("rusty decode") { + pictures.push(Picture { + width: yuv.width, + y: yuv.y, + u: yuv.u, + v: yuv.v, + }); + } + } + pictures +} + +/// `ec-h264` in the requested output order, drained to end of stream. +fn decode_ec(aus: &[Vec], order: ec_h264::OutputOrder) -> Vec { + let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)).expect("ec decoder"); + decoder.set_output_order(order); + let mut pictures = Vec::new(); + for au in aus { + decoder + .send_packet(&Packet::new(0, TimeBase::new(1, 1), au.as_slice())) + .expect("ec decode"); + while let Ok(frame) = decoder.receive_frame() { + let ec_core::frame::Frame::Video(pic) = frame else { + continue; + }; + let [y, u, v] = [&pic.planes[0], &pic.planes[1], &pic.planes[2]]; + pictures.push(Picture { + width: pic.width as usize, + y: y.data[..].to_vec(), + u: u.data[..].to_vec(), + v: v.data[..].to_vec(), + }); + } + } + decoder.flush().expect("ec flush"); + while let Ok(frame) = decoder.receive_frame() { + let ec_core::frame::Frame::Video(pic) = frame else { + continue; + }; + let [y, u, v] = [&pic.planes[0], &pic.planes[1], &pic.planes[2]]; + pictures.push(Picture { + width: pic.width as usize, + y: y.data[..].to_vec(), + u: u.data[..].to_vec(), + v: v.data[..].to_vec(), + }); + } + pictures +} + +fn assert_same_pictures(a: &Picture, b: &Picture, what: &str, index: usize) { + assert_eq!(a.width, b.width, "{what}: picture {index} width"); + assert_eq!(a.y, b.y, "{what}: picture {index} luma"); + assert_eq!(a.u, b.u, "{what}: picture {index} cb"); + assert_eq!(a.v, b.v, "{what}: picture {index} cr"); +} + +/// Same access units in, same pictures out, byte for byte, on both a CAVLC +/// Baseline and a CABAC High stream with B pictures. Decode order on both +/// sides makes the sequences one to one regardless of reordering. +#[test] +fn sw_decoders_agree_byte_for_byte() { + for name in ["test_baseline.mp4", "test_high.mp4"] { + let aus = access_units(&asset(name)); + let rusty = decode_rusty(&aus); + let ec = decode_ec(&aus, ec_h264::OutputOrder::Decode); + assert_eq!(rusty.len(), ec.len(), "{name}: picture count"); + for (i, (a, b)) in rusty.iter().zip(&ec).enumerate() { + assert_same_pictures(a, b, name, i); + } + eprintln!("{name}: {} pictures agree byte for byte", rusty.len()); + } +} + +/// Display order is a reordering, not a rewrite: the same multiset of +/// pictures the decode-order run releases, possibly in a different sequence. +/// On the B-picture fixture the sequences genuinely differ -- that is the +/// corner-cut being retired -- and on the Baseline fixture they cannot (no +/// B pictures, nothing to reorder). +#[test] +fn display_order_releases_the_same_pictures() { + for name in ["test_baseline.mp4", "test_high.mp4"] { + let aus = access_units(&asset(name)); + let decode_order = decode_rusty(&aus); + let display_order = decode_ec(&aus, ec_h264::OutputOrder::Display); + assert_eq!(decode_order.len(), display_order.len(), "{name}: count"); + let mut want: Vec = decode_order.iter().map(Picture::hash).collect(); + let mut got: Vec = display_order.iter().map(Picture::hash).collect(); + want.sort_unstable(); + got.sort_unstable(); + assert_eq!(want, got, "{name}: the released pictures differ"); + + let reordered = decode_order + .iter() + .zip(&display_order) + .any(|(a, b)| a.hash() != b.hash()); + if name == "test_high.mp4" { + assert!( + reordered, + "test_high.mp4 has B pictures: display order must differ \ + from decode order somewhere, or the reorder is not engaged" + ); + } else { + assert!( + !reordered, + "a Baseline stream has nothing to reorder: the sequences \ + must be identical" + ); + } + eprintln!( + "{name}: display order releases the same {} pictures", + got.len() + ); + } +} + +/// The seat, wired through `DecodeSession`, labels every picture with its +/// timeline position: a full run to EOF delivers `0..frame_count` in order on +/// a B-picture stream -- the contract the transport reads (`frame.index` is a +/// timeline index) and the one the hardware backend already kept. +#[test] +fn the_software_seat_labels_the_timeline_in_display_order() { + // Pin the software seat: on a box with the plugin this test is about the + // decoder under swap, not the driver. SAFETY: single-threaded by the + // documented invocation, and no other test in this binary reads the env. + unsafe { std::env::set_var("VE_SW", "1") }; + + let path = asset("test_high.mp4"); + let (meta, rx) = engine::DecodeSession::open(&path).expect("open"); + let indices: Vec = rx.into_iter().map(|f| f.index).collect(); + let want: Vec = (0..u32::try_from(meta.frame_count).expect("frame count")).collect(); + assert_eq!(indices, want, "frames must arrive 0..n in display order"); +}