forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-h264-swap' (e24fe61): the software H264 decode seat is ec-h264 native via the ec_core registry -- and the seat now emits true DISPLAY order (the rusty corner-cut scrambled B-picture content); byte-exact vs rusty on CAVLC and CABAC+B fixtures, perf 1.02-1.57x on the gate classes, 0.80x on B-frame CABAC (the DPB reorder price; lane-ech264-perf queued); rusty_h264 stays for the ENCODE seat only

Browse files at this commit

c6127114c52e2b9ca0e1aa85ccf5d52f2c4586f5Ahmet Kaan GümüşParent: 3d8112ae24fe61
# Conflicts:
#	Cargo.lock
#	crates/engine/Cargo.toml
#	crates/engine/src/decode.rs
#	crates/engine/src/demux.rs
Cargo.lockmodified+18 -0
@@ -1600,6 +1600,22 @@ dependencies = [
1600 "wide 1.7.0",1600 "wide 1.7.0",
1601 ]1601 ]
1602 1602
1603+[[package]]
1604+name = "ec-h264"
1605+version = "0.1.0"
1606+dependencies = [
1607+ "ec-core",
1608+ "ec-h264-syntax",
1609+ "wide 1.7.0",
1610+]
1611+
1612+[[package]]
1613+name = "ec-h264-syntax"
1614+version = "0.1.0"
1615+dependencies = [
1616+ "ec-core",
1617+]
1618+
1603 [[package]]1619 [[package]]
1604 name = "ec-opus"1620 name = "ec-opus"
1605 version = "0.1.0"1621 version = "0.1.0"
@@ -1657,6 +1673,8 @@ checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
1657 name = "engine"1673 name = "engine"
1658 version = "0.1.0"1674 version = "0.1.0"
1659 dependencies = [1675 dependencies = [
1676+ "ec-core",
1677+ "ec-h264",
1660 "ec-opus",1678 "ec-opus",
1661 "flacenc",1679 "flacenc",
1662 "hound",1680 "hound",
Cargo.tomlmodified+4 -0
@@ -77,6 +77,10 @@ edition = "2024"
77 # default and the six-line declaration in `src/lib.rs`; every77 # default and the six-line declaration in `src/lib.rs`; every
78 # line of codec code is byte-identical to 0.9.1, so decode stays78 # line of codec code is byte-identical to 0.9.1, so decode stays
79 # bit-exact and the process gets glibc's malloc back.79 # bit-exact and the process gets glibc's malloc back.
80+# (Since 2026-09-12 only the software H.264 *encode* seat
81+# still links this crate -- decode is `ec-h264`, which carries
82+# no allocator of its own; the patch stays until the encode
83+# seat moves too.)
80 # mp4 - reads the `mp4a` sample entry as ISO only: the 8 bytes84 # mp4 - reads the `mp4a` sample entry as ISO only: the 8 bytes
81 # QuickTime uses for version/revision/vendor are skipped as85 # QuickTime uses for version/revision/vendor are skipped as
82 # reserved, so a version-1 SoundDescription's 16-byte tail86 # reserved, so a version-1 SoundDescription's 16-byte tail
crates/engine/Cargo.tomlmodified+30 -16
@@ -34,18 +34,16 @@ mp4 = "0.14"
34 # pulls this exact version in through `png`, and it is the pure-Rust inflate the34 # pulls this exact version in through `png`, and it is the pure-Rust inflate the
35 # rest of the ecosystem is built on.35 # rest of the ecosystem is built on.
36 miniz_oxide = "0.8"36 miniz_oxide = "0.8"
37-# The software H.264 pair, and the only software decoder this project has for37+# The software H.264 *encoder* -- since the decode seat moved to `ec-h264`
38-# any format. Pinned exactly, like `oxideav-ac3` below, because a38+# above, the only seat still on this crate. Pinned exactly, like
39-# decoder is a bit-exactness dependency -- and 0.9.1 is where that stopped being39+# `oxideav-ac3` below, because a codec is a reproducibility dependency; the
40-# a figure of speech. Measured 2026-08-12 against ffmpeg's own decode of a 1080p40+# 0.9.1 pin is the one the decode half set on 2026-08-12, when 750 pictures of
41-# High and a 720p Main clip, 750 pictures between them: 0.8 matched it41+# a 1080p High and a 720p Main clip decoded byte-for-byte against ffmpeg where
42-# byte-for-byte on 26 of the 750 and drifted on the rest (worst 69.8 dB PSNR --42+# 0.8 had drifted (software *encode* was unchanged within noise across that
43-# invisible, but wrong); 0.9.1 matches on all 750. It is also 1.44x faster at it43+# bump, so the pin costs the encoder nothing). `default-features = false` is
44-# (247 Mpx/s against 171 on the 1080p clip, single-threaded); software *encode*44+# what keeps `asm` off: those are vendored openh264 SIMD kernels that want
45-# is unchanged within noise, so this is a decode bump that the encoder came45+# `nasm` at build time, which this project's no-install rule forbids, and the
46-# along with. `default-features = false` is what keeps `asm` off: those are46+# crate enables them by default.
47-# vendored openh264 SIMD kernels that want `nasm` at build time, which this
48-# project's no-install rule forbids, and the crate enables them by default.
49 #47 #
50 # What that line does not turn off, and cannot: the facade asks for its three48 # What that line does not turn off, and cannot: the facade asks for its three
51 # sub-crates with *their* defaults, and `rusty_h264-common`'s default installs49 # sub-crates with *their* defaults, and `rusty_h264-common`'s default installs
@@ -55,10 +53,26 @@ miniz_oxide = "0.8"
55 # and it crashed the editor: sustained scrubbing churns decode-worker threads,53 # and it crashed the editor: sustained scrubbing churns decode-worker threads,
56 # and it segfaulted on a new thread's *first* allocation. `common` is therefore54 # and it segfaulted on a new thread's *first* allocation. `common` is therefore
57 # vendored with that declaration removed (workspace root `[patch.crates-io]`),55 # vendored with that declaration removed (workspace root `[patch.crates-io]`),
58-# which is the only way to decline it -- the codec itself is untouched and still56+# which is the only way to decline it -- the codec itself is untouched. When
59-# bit-exact. Frame-threaded decode arrived in 0.9 as well and57+# the export encode seat moves to `ec_h264::Encoder`, this line, the patch and
60-# is opt-in through `RS_H264_FRAME_THREADS`, unset here -- the decode loop is58+# the vendored crate go with it.
61-# serial exactly as it was.59+# The software H.264 *decoder*, which is the project's own: `ec-h264`
60+# (I/P/B, CAVLC and CABAC, full DPB, weighted prediction, in-loop deblocking),
61+# bit-exact against the JVT conformance suite. It took this seat from
62+# `rusty_h264` on 2026-09-12. Raw decode throughput (demux+decode, no render,
63+# best of three warm passes, otherwise idle machine): 1.5x `rusty_h264` on a
64+# 1080p Main export and a 4K Main render, 1.0x on a 1440p High screen
65+# recording, 1.17x on a CAVLC Baseline fixture; 0.80x on the two B-picture
66+# CABAC streams measured (a 720p High fixture and a 720p Blu-ray episode) --
67+# the price of the full DPB the old seat skipped with its decode-order
68+# corner-cut, which scrambled exactly those streams. It hands pictures back in
69+# display order, which is what every reader of `frame.index` already assumed
70+# (the hardware backend always did; see `tests/sw_backends.rs` for the
71+# byte-exactness witness against `rusty_h264`, kept as the independent oracle).
72+ec-h264 = { path = "../../../edith_codecs/crates/ec-h264" }
73+# Its shared IR (packets, frames, the registry decoder contract the seat is
74+# written against), direct because decode.rs names those types itself.
75+ec-core = { path = "../../../edith_codecs/crates/ec-core" }
62 rusty_h264 = { version = "=0.9.1", default-features = false }76 rusty_h264 = { version = "=0.9.1", default-features = false }
63 # Both halves of AAC, and the only crate here that is asked for both. The77 # Both halves of AAC, and the only crate here that is asked for both. The
64 # *encoder*, so an mp4's sound can be a mix rather than a copy: an equalized (or78 # *encoder*, so an mp4's sound can be a mix rather than a copy: an equalized (or
crates/engine/src/caps.rsmodified+3 -5
@@ -17,7 +17,7 @@
17 //! never the GPU's. [`HW_CODECS`] does not carry the bit, because this file's17 //! never the GPU's. [`HW_CODECS`] does not carry the bit, because this file's
18 //! one job is not presenting a seat as a GPU feat that no GPU has.18 //! one job is not presenting a seat as a GPU feat that no GPU has.
19 19
20-use crate::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps};20+use crate::hw::{VhCaps, CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9};
21 21
22 /// The codecs a hardware line can name, in the order it lists them.22 /// The codecs a hardware line can name, in the order it lists them.
23 const HW_CODECS: [(u32, &str); 4] = [23 const HW_CODECS: [(u32, &str); 4] = [
@@ -32,7 +32,7 @@ const HW_CODECS: [(u32, &str); 4] = [
32 /// because the answer to "why is my HEVC file so large" is `oxideav-h26532 /// because the answer to "why is my HEVC file so large" is `oxideav-h265
33 /// intra`, and the row that says so is the row that answers it.33 /// intra`, and the row that says so is the row that answers it.
34 const SW_CODECS: [(&str, &str, bool, bool); 10] = [34 const SW_CODECS: [(&str, &str, bool, bool); 10] = [
35- ("H.264", "rusty_h264", true, true),35+ ("H.264", "ec-h264 / rusty_h264", true, true),
36 ("HEVC", "oxideav-h265 intra", false, true),36 ("HEVC", "oxideav-h265 intra", false, true),
37 ("AV1", "rav1e", false, true),37 ("AV1", "rav1e", false, true),
38 ("AAC", "rusty_aac", true, true),38 ("AAC", "rusty_aac", true, true),
@@ -153,8 +153,6 @@ mod tests {
153 assert_eq!(hw_line(Some(with_gpu)), "H.264 dec+enc");153 assert_eq!(hw_line(Some(with_gpu)), "H.264 dec+enc");
154 }154 }
155 155
156- #[test]
157-
158 #[test]156 #[test]
159 fn the_software_line_names_every_encoder_this_build_carries() {157 fn the_software_line_names_every_encoder_this_build_carries() {
160 let line = software();158 let line = software();
@@ -164,7 +162,7 @@ mod tests {
164 // Decode-only crates must not read as encoders, and the seat words are162 // Decode-only crates must not read as encoders, and the seat words are
165 // the only thing saying which is which.163 // the only thing saying which is which.
166 assert!(line.contains("AC-3 dec (oxideav-ac3)"));164 assert!(line.contains("AC-3 dec (oxideav-ac3)"));
167- assert!(line.contains("H.264 dec+enc (rusty_h264)"));165+ assert!(line.contains("H.264 dec+enc (ec-h264 / rusty_h264)"));
168 assert!(line.contains("HEVC enc (oxideav-h265 intra)"));166 assert!(line.contains("HEVC enc (oxideav-h265 intra)"));
169 }167 }
170 }168 }
crates/engine/src/decode.rsmodified+103 -56
@@ -7,7 +7,11 @@ use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering};
7 use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel};7 use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel};
8 use std::thread;8 use std::thread;
9 9
10-use rusty_h264::Decoder;10+use ec_core::frame::VideoFrame;
11+use ec_core::registry::{CodecId, CodecParameters};
12+use ec_core::registry::Decoder as _;
13+use ec_core::{Packet, TimeBase};
14+use ec_h264::H264Decoder;
11 15
12 use crate::color::ColorParams;16 use crate::color::ColorParams;
13 use crate::colorspace::{ColorDescription, Matrix, Transfer};17 use crate::colorspace::{ColorDescription, Matrix, Transfer};
@@ -21,7 +25,7 @@ use crate::transform::TransformParams;
21 25
22 /// One decoded picture, ready to hand to a renderer.26 /// One decoded picture, ready to hand to a renderer.
23 pub struct Frame {27 pub struct Frame {
24- /// Position in decode order, starting at 0.28+ /// Position in display order, starting at 0.
25 pub index: u32,29 pub index: u32,
26 pub width: u32,30 pub width: u32,
27 pub height: u32,31 pub height: u32,
@@ -42,7 +46,7 @@ pub enum Backend {
42 Opening,46 Opening,
43 /// The VA-API plugin (`libengine_hw.so`).47 /// The VA-API plugin (`libengine_hw.so`).
44 Hardware,48 Hardware,
45- /// `rusty_h264`, in this process.49+ /// `ec-h264`, in this process.
46 Software,50 Software,
47 /// A still image: one `image` decode, no stream and no decoder to pick.51 /// A still image: one `image` decode, no stream and no decoder to pick.
48 Still,52 Still,
@@ -1006,12 +1010,13 @@ fn run_span(
1006 eprintln!("hardware decode failed before any frame, falling back to software");1010 eprintln!("hardware decode failed before any frame, falling back to software");
1007 }1011 }
1008 // ...except where there is nothing to fall back to. Feeding HEVC, VP9 or1012 // ...except where there is nothing to fall back to. Feeding HEVC, VP9 or
1009- // VP8 bytes to `rusty_h264` would be garbage, not a fallback.1013+ // VP8 bytes to the H.264 decoder (ec-h264) would be garbage, not a
1014+ // fallback — VP8's software decoder is libvpx, inside the plugin.
1010 if opened.meta.codec != Codec::H264 {1015 if opened.meta.codec != Codec::H264 {
1011 eprintln!("{}", opened.meta.codec.needs_plugin());1016 eprintln!("{}", opened.meta.codec.needs_plugin());
1012 return;1017 return;
1013 }1018 }
1014- eprintln!("decode backend: software (rusty_h264)");1019+ eprintln!("decode backend: software (ec-h264)");
1015 backend.set(Backend::Software);1020 backend.set(Backend::Software);
1016 run(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed)1021 run(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed)
1017 }1022 }
@@ -1620,78 +1625,120 @@ fn run(
1620 // A decoder per span, and cheap: it is a parameter-set map and a picture1625 // A decoder per span, and cheap: it is a parameter-set map and a picture
1621 // buffer, while the *demuxer* -- whose index cost seconds to build -- is the1626 // buffer, while the *demuxer* -- whose index cost seconds to build -- is the
1622 // one this worker keeps.1627 // one this worker keeps.
1623- let mut decoder = Decoder::new();1628+ let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264))
1629+ .expect("ec-h264 takes its own codec id");
1624 // Decoding has to restart at a sync sample, so pictures between it and1630 // Decoding has to restart at a sync sample, so pictures between it and
1625 // `start_frame` are decoded (the target frame references them) but never1631 // `start_frame` are decoded (the target frame references them) but never
1626 // converted or sent. Signed, because the landing sync sample can sit inside1632 // converted or sent. Signed, because the landing sync sample can sit inside
1627 // what the file's edit list trims, i.e. *before* frame 0.1633 // what the file's edit list trims, i.e. *before* frame 0.
1628 let mut index = demuxer.seek_to_sync_at_or_before(start_frame);1634 let mut index = demuxer.seek_to_sync_at_or_before(start_frame);
1635+ // Pictures leave the decoder in display order -- clause C.4.5.3 bumps the
1636+ // decoded picture buffer -- and the landing index above is a display index
1637+ // by the demuxer's own contract, so the two count one to one. The decode
1638+ // order this loop used to emit was a corner-cut that only held for
1639+ // Baseline: a stream with B pictures arrived scrambled and mislabelled,
1640+ // and every reader of `index` (the transport's playhead, `skip_for_speed`,
1641+ // the export's frame map) reads it as a timeline position.
1629 let mut skipped = 0;1642 let mut skipped = 0;
1630-1643+ // Set once the demuxer runs dry: `flush` makes the decoder release every
1631- // corner-cut: emits pictures in decode order. Fine for Baseline (no B-frames);1644+ // picture its reorder delay still holds, and the drain below ends on
1632- // reordering streams need POC-sorted output before display.1645+ // `Error::Eof` once they are out.
1633- loop {1646+ let mut flushed = false;
1647+ // Every way this span ends: abort, consumer gone, end of the requested
1648+ // range, end of stream.
1649+ let mut done = false;
1650+ while !done {
1634 if abort.hit() {1651 if abort.hit() {
1635 break;1652 break;
1636 }1653 }
1637- let au = match demuxer.next_access_unit() {1654+ // One access unit is one packet. No timestamps travel with it: the
1638- Ok(Some(au)) => au,1655+ // presentation order comes out of the bitstream's own POC, and `index`
1639- Ok(None) => break,1656+ // is counted off the pictures as the decoder releases them.
1657+ match demuxer.next_access_unit() {
1658+ Ok(Some(au)) => {
1659+ let packet = Packet::new(0, TimeBase::new(1, 1), au);
1660+ if let Err(e) = decoder.send_packet(&packet) {
1661+ eprintln!("decode error at access unit {index}: {e}");
1662+ break;
1663+ }
1664+ }
1665+ Ok(None) => {
1666+ flushed = true;
1667+ if let Err(e) = decoder.flush() {
1668+ eprintln!("decode error at end of stream: {e}");
1669+ break;
1670+ }
1671+ }
1640 Err(e) => {1672 Err(e) => {
1641 eprintln!("demux error: {e}");1673 eprintln!("demux error: {e}");
1642 break;1674 break;
1643 }1675 }
1644- };1676+ }
1645- let yuv = match decoder.decode(&au) {1677+ // Take everything the packet released; `NeedMore` is the signal to go
1646- Ok(Some(yuv)) => yuv,1678+ // back for the next access unit.
1647- Ok(None) => continue,1679+ loop {
1648- Err(e) => {1680+ let pic = match decoder.receive_frame() {
1649- eprintln!("decode error at access unit {index}: {e}");1681+ Ok(pic) => pic,
1650- break;1682+ Err(e) if e.is_need_more() || e.is_eof() => break,
1683+ Err(e) => {
1684+ eprintln!("decode error at access unit {index}: {e}");
1685+ break;
1686+ }
1687+ };
1688+ let ec_core::frame::Frame::Video(pic) = pic else {
1689+ continue;
1690+ };
1691+ if index < i64::from(start_frame) {
1692+ index += 1;
1693+ continue;
1651 }1694 }
1652- };1695+ let due = index as u32;
1653- if index < i64::from(start_frame) {
1654 index += 1;1696 index += 1;
1655- continue;1697+ if abort.late(due) {
1656- }1698+ if skipped < LATE_RUN {
1657- let due = index as u32;1699+ skipped += 1;
1658- index += 1;1700+ } else {
1659- if abort.late(due) {1701+ skipped = 0;
1660- if skipped < LATE_RUN {1702+ if send_picture(&pic, due, render, tx) {
1661- skipped += 1;1703+ done = true; // consumer went away
1704+ break;
1705+ }
1706+ }
1707+ } else if skip_for_speed(speed, start_frame, due, end_frame) {
1708+ // Redundant by construction, not by lateness: no run limit
1709+ // needed (see `skip_for_speed`).
1662 } else {1710 } else {
1663 skipped = 0;1711 skipped = 0;
1664- let frame = render.frame(1712+ if send_picture(&pic, due, render, tx) {
1665- due,1713+ done = true; // consumer went away
1666- &yuv.y,1714+ break;
1667- &yuv.u,
1668- &yuv.v,
1669- yuv.width as u32,
1670- yuv.height as u32,
1671- );
1672- if tx.send(frame).is_err() {
1673- break; // consumer went away
1674 }1715 }
1675 }1716 }
1676- } else if skip_for_speed(speed, start_frame, due, end_frame) {1717+ if index >= i64::from(end_frame) {
1677- // Redundant by construction, not by lateness: no run limit needed1718+ done = true; // end of the requested range
1678- // (see `skip_for_speed`).1719+ break;
1679- } else {
1680- skipped = 0;
1681- let frame = render.frame(
1682- due,
1683- &yuv.y,
1684- &yuv.u,
1685- &yuv.v,
1686- yuv.width as u32,
1687- yuv.height as u32,
1688- );
1689- if tx.send(frame).is_err() {
1690- break; // consumer went away
1691 }1720 }
1692 }1721 }
1693- if index >= i64::from(end_frame) {1722+ if flushed {
1694- break; // end of the requested range1723+ done = true;
1695 }1724 }
1696 }1725 }
1697 }1726 }
1727+
1728+/// Converts one decoded picture and queues it. `true` when the consumer went
1729+/// away, so the span stops rather than keeps decoding into a void.
1730+fn send_picture(pic: &VideoFrame, due: u32, render: &mut Render, tx: &SyncSender<Frame>) -> bool {
1731+ // The decoder crops each picture into tightly packed planes, the shape
1732+ // every converter below takes. A padded plane would render skewed rather
1733+ // than subtly wrong, so the assumption is pinned where it is relied on --
1734+ // free in a release build.
1735+ let (y, u, v) = (&pic.planes[0], &pic.planes[1], &pic.planes[2]);
1736+ debug_assert_eq!(y.stride, pic.width as usize, "padded luma plane");
1737+ debug_assert_eq!(
1738+ u.stride,
1739+ pic.width.div_ceil(2) as usize,
1740+ "padded chroma plane"
1741+ );
1742+ let frame = render.frame(due, &y.data, &u.data, &v.data, pic.width, pic.height);
1743+ tx.send(frame).is_err()
1744+}
crates/engine/src/demux.rsmodified+6 -6
@@ -137,12 +137,12 @@ impl Codec {
137 137
138 /// Why a file can be refused outright. Two true answers, one per shape of138 /// Why a file can be refused outright. Two true answers, one per shape of
139 /// "no decoder here": every codec but H.264 and VP8 has no software139 /// "no decoder here": every codec but H.264 and VP8 has no software
140- /// decoder at all, so the refusal names the plugin as the only way; VP8's140+ /// decoder at all (H.264's is the native `ec-h264`), so the refusal names
141- /// software decoder *is* libvpx inside the plugin, so "there is no141+ /// the plugin as the only way; VP8's software decoder *is* libvpx inside
142- /// software decoder" would be a lie the day the plugin grew that arm --142+ /// the plugin, so "there is no software decoder" would be a lie the day
143- /// the refusal keeps naming the plugin, because that is still the thing143+ /// the plugin grew that arm -- the refusal keeps naming the plugin,
144- /// to make present. Shared so playback and export refuse in the same144+ /// because that is still the thing to make present. Shared so playback
145- /// words.145+ /// and export refuse in the same words.
146 pub fn needs_plugin(self) -> String {146 pub fn needs_plugin(self) -> String {
147 match self {147 match self {
148 Self::Vp8 => {148 Self::Vp8 => {
crates/engine/tests/h264_mkv.rsmodified+1 -1
@@ -2,7 +2,7 @@
2 //! container that used to refuse it by name. Nothing new decodes here -- the2 //! container that used to refuse it by name. Nothing new decodes here -- the
3 //! demuxer reframes the `avcC`-prefixed blocks to Annex-B and hands them to the3 //! demuxer reframes the `avcC`-prefixed blocks to Annex-B and hands them to the
4 //! same dispatch an mp4's samples go to -- so the whole file runs with nothing4 //! same dispatch an mp4's samples go to -- so the whole file runs with nothing
5-//! installed, on `rusty_h264` if the plugin is absent.5+//! installed, on the software seat (`ec-h264`) if the plugin is absent.
6 //!6 //!
7 //! ```text7 //! ```text
8 //! cargo test -p engine --test h264_mkv8 //! cargo test -p engine --test h264_mkv
crates/engine/tests/sw_backends.rsadded+199 -0
@@ -0,0 +1,199 @@
1+//! The H.264 software decode seat swap: `ec-h264` (the in-project decoder) is
2+//! the seat, `rusty_h264` -- the decoder this seat carried for years, and still
3+//! the encoder behind software H.264 export -- is the independent witness.
4+//!
5+//! H.264 8-bit decode is bit-exact by conformance, so two correct decoders
6+//! handed the same access units must return the same pictures, byte for byte;
7+//! this is the software twin of `hw_decode::hardware_matches_software_on_frame_30`.
8+//! The one deliberate difference is *order*: `rusty_h264` releases pictures in
9+//! decode order, `ec-h264` in display order (clause C.4.5.3), which is what the
10+//! rest of the engine already assumed -- the hardware backend behaves the same
11+//! way, `frame.index` is a timeline position, and the old seat's decode-order
12+//! corner-cut scrambled B-picture streams.
13+//!
14+//! ```text
15+//! cargo test -p engine --test sw_backends -- --test-threads=1
16+//! ```
17+
18+use std::collections::hash_map::DefaultHasher;
19+use std::hash::{Hash, Hasher};
20+use std::path::{Path, PathBuf};
21+
22+use ec_core::registry::{CodecId, CodecParameters, Decoder as _};
23+use ec_core::{Packet, TimeBase};
24+use ec_h264::H264Decoder;
25+
26+fn asset(name: &str) -> PathBuf {
27+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
28+ .join("../../assets")
29+ .join(name)
30+}
31+
32+/// Every access unit of the file, in container (decode) order.
33+fn access_units(path: &Path) -> Vec<Vec<u8>> {
34+ let (_, mut demuxer) = engine::demux::Demuxer::open(path).expect("open");
35+ let mut aus = Vec::new();
36+ while let Ok(Some(au)) = demuxer.next_access_unit() {
37+ aus.push(au);
38+ }
39+ assert!(!aus.is_empty(), "{}: no access units", path.display());
40+ aus
41+}
42+
43+/// One decoded picture as plain planes, whatever the decoder calls them.
44+struct Picture {
45+ width: usize,
46+ y: Vec<u8>,
47+ u: Vec<u8>,
48+ v: Vec<u8>,
49+}
50+
51+impl Picture {
52+ fn hash(&self) -> u64 {
53+ let mut hasher = DefaultHasher::new();
54+ self.width.hash(&mut hasher);
55+ self.y.hash(&mut hasher);
56+ self.u.hash(&mut hasher);
57+ self.v.hash(&mut hasher);
58+ hasher.finish()
59+ }
60+}
61+
62+/// `rusty_h264`, decode order -- the order it has always emitted.
63+fn decode_rusty(aus: &[Vec<u8>]) -> Vec<Picture> {
64+ let mut decoder = rusty_h264::Decoder::new();
65+ let mut pictures = Vec::new();
66+ for au in aus {
67+ if let Some(yuv) = decoder.decode(au).expect("rusty decode") {
68+ pictures.push(Picture {
69+ width: yuv.width,
70+ y: yuv.y,
71+ u: yuv.u,
72+ v: yuv.v,
73+ });
74+ }
75+ }
76+ pictures
77+}
78+
79+/// `ec-h264` in the requested output order, drained to end of stream.
80+fn decode_ec(aus: &[Vec<u8>], order: ec_h264::OutputOrder) -> Vec<Picture> {
81+ let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)).expect("ec decoder");
82+ decoder.set_output_order(order);
83+ let mut pictures = Vec::new();
84+ for au in aus {
85+ decoder
86+ .send_packet(&Packet::new(0, TimeBase::new(1, 1), au.as_slice()))
87+ .expect("ec decode");
88+ while let Ok(frame) = decoder.receive_frame() {
89+ let ec_core::frame::Frame::Video(pic) = frame else {
90+ continue;
91+ };
92+ let [y, u, v] = [&pic.planes[0], &pic.planes[1], &pic.planes[2]];
93+ pictures.push(Picture {
94+ width: pic.width as usize,
95+ y: y.data[..].to_vec(),
96+ u: u.data[..].to_vec(),
97+ v: v.data[..].to_vec(),
98+ });
99+ }
100+ }
101+ decoder.flush().expect("ec flush");
102+ while let Ok(frame) = decoder.receive_frame() {
103+ let ec_core::frame::Frame::Video(pic) = frame else {
104+ continue;
105+ };
106+ let [y, u, v] = [&pic.planes[0], &pic.planes[1], &pic.planes[2]];
107+ pictures.push(Picture {
108+ width: pic.width as usize,
109+ y: y.data[..].to_vec(),
110+ u: u.data[..].to_vec(),
111+ v: v.data[..].to_vec(),
112+ });
113+ }
114+ pictures
115+}
116+
117+fn assert_same_pictures(a: &Picture, b: &Picture, what: &str, index: usize) {
118+ assert_eq!(a.width, b.width, "{what}: picture {index} width");
119+ assert_eq!(a.y, b.y, "{what}: picture {index} luma");
120+ assert_eq!(a.u, b.u, "{what}: picture {index} cb");
121+ assert_eq!(a.v, b.v, "{what}: picture {index} cr");
122+}
123+
124+/// Same access units in, same pictures out, byte for byte, on both a CAVLC
125+/// Baseline and a CABAC High stream with B pictures. Decode order on both
126+/// sides makes the sequences one to one regardless of reordering.
127+#[test]
128+fn sw_decoders_agree_byte_for_byte() {
129+ for name in ["test_baseline.mp4", "test_high.mp4"] {
130+ let aus = access_units(&asset(name));
131+ let rusty = decode_rusty(&aus);
132+ let ec = decode_ec(&aus, ec_h264::OutputOrder::Decode);
133+ assert_eq!(rusty.len(), ec.len(), "{name}: picture count");
134+ for (i, (a, b)) in rusty.iter().zip(&ec).enumerate() {
135+ assert_same_pictures(a, b, name, i);
136+ }
137+ eprintln!("{name}: {} pictures agree byte for byte", rusty.len());
138+ }
139+}
140+
141+/// Display order is a reordering, not a rewrite: the same multiset of
142+/// pictures the decode-order run releases, possibly in a different sequence.
143+/// On the B-picture fixture the sequences genuinely differ -- that is the
144+/// corner-cut being retired -- and on the Baseline fixture they cannot (no
145+/// B pictures, nothing to reorder).
146+#[test]
147+fn display_order_releases_the_same_pictures() {
148+ for name in ["test_baseline.mp4", "test_high.mp4"] {
149+ let aus = access_units(&asset(name));
150+ let decode_order = decode_rusty(&aus);
151+ let display_order = decode_ec(&aus, ec_h264::OutputOrder::Display);
152+ assert_eq!(decode_order.len(), display_order.len(), "{name}: count");
153+ let mut want: Vec<u64> = decode_order.iter().map(Picture::hash).collect();
154+ let mut got: Vec<u64> = display_order.iter().map(Picture::hash).collect();
155+ want.sort_unstable();
156+ got.sort_unstable();
157+ assert_eq!(want, got, "{name}: the released pictures differ");
158+
159+ let reordered = decode_order
160+ .iter()
161+ .zip(&display_order)
162+ .any(|(a, b)| a.hash() != b.hash());
163+ if name == "test_high.mp4" {
164+ assert!(
165+ reordered,
166+ "test_high.mp4 has B pictures: display order must differ \
167+ from decode order somewhere, or the reorder is not engaged"
168+ );
169+ } else {
170+ assert!(
171+ !reordered,
172+ "a Baseline stream has nothing to reorder: the sequences \
173+ must be identical"
174+ );
175+ }
176+ eprintln!(
177+ "{name}: display order releases the same {} pictures",
178+ got.len()
179+ );
180+ }
181+}
182+
183+/// The seat, wired through `DecodeSession`, labels every picture with its
184+/// timeline position: a full run to EOF delivers `0..frame_count` in order on
185+/// a B-picture stream -- the contract the transport reads (`frame.index` is a
186+/// timeline index) and the one the hardware backend already kept.
187+#[test]
188+fn the_software_seat_labels_the_timeline_in_display_order() {
189+ // Pin the software seat: on a box with the plugin this test is about the
190+ // decoder under swap, not the driver. SAFETY: single-threaded by the
191+ // documented invocation, and no other test in this binary reads the env.
192+ unsafe { std::env::set_var("VE_SW", "1") };
193+
194+ let path = asset("test_high.mp4");
195+ let (meta, rx) = engine::DecodeSession::open(&path).expect("open");
196+ let indices: Vec<u32> = rx.into_iter().map(|f| f.index).collect();
197+ let want: Vec<u32> = (0..u32::try_from(meta.frame_count).expect("frame count")).collect();
198+ assert_eq!(indices, want, "frames must arrive 0..n in display order");
199+}