forge
Explore
Log in

Don't you dare go Hollow

The software H.264 seat decodes with ec-h264

Browse files at this commit

e24fe61c36247c4abd9fe974fc92dc32513e9cfaAhmet Kaan GümüşParent: 429bf04
  • refactor
    • the software H.264 seat decodes with ec-h264
Show full message
♻️ refactor(engine): the software H.264 seat decodes with ec-h264

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.lockmodified+43 -2
@@ -1588,6 +1588,26 @@ version = "1.0.20"
1588 source = "registry+https://github.com/rust-lang/crates.io-index"1588 source = "registry+https://github.com/rust-lang/crates.io-index"
1589 checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"1589 checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
1590 1590
1591+[[package]]
1592+name = "ec-core"
1593+version = "0.1.0"
1594+
1595+[[package]]
1596+name = "ec-h264"
1597+version = "0.1.0"
1598+dependencies = [
1599+ "ec-core",
1600+ "ec-h264-syntax",
1601+ "wide 1.7.0",
1602+]
1603+
1604+[[package]]
1605+name = "ec-h264-syntax"
1606+version = "0.1.0"
1607+dependencies = [
1608+ "ec-core",
1609+]
1610+
1591 [[package]]1611 [[package]]
1592 name = "edith"1612 name = "edith"
1593 version = "0.1.0"1613 version = "0.1.0"
@@ -1636,6 +1656,8 @@ checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
1636 name = "engine"1656 name = "engine"
1637 version = "0.1.0"1657 version = "0.1.0"
1638 dependencies = [1658 dependencies = [
1659+ "ec-core",
1660+ "ec-h264",
1639 "flacenc",1661 "flacenc",
1640 "hound",1662 "hound",
1641 "image",1663 "image",
@@ -5149,7 +5171,7 @@ name = "rusty_h264-common"
5149 version = "0.9.1"5171 version = "0.9.1"
5150 dependencies = [5172 dependencies = [
5151 "bytemuck",5173 "bytemuck",
5152- "wide",5174+ "wide 0.7.33",
5153 ]5175 ]
5154 5176
5155 [[package]]5177 [[package]]
@@ -5232,6 +5254,15 @@ dependencies = [
5232 "bytemuck",5254 "bytemuck",
5233 ]5255 ]
5234 5256
5257+[[package]]
5258+name = "safe_arch"
5259+version = "1.2.0"
5260+source = "registry+https://github.com/rust-lang/crates.io-index"
5261+checksum = "42c6efa15875e6ecb39ca61fb0b0c1a40b84fac5a5ffe71eef7d1000c8eb3f5f"
5262+dependencies = [
5263+ "bytemuck",
5264+]
5265+
5235 [[package]]5266 [[package]]
5236 name = "same-file"5267 name = "same-file"
5237 version = "1.0.6"5268 version = "1.0.6"
@@ -7077,7 +7108,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
7077 checksum = "0ce5da8ecb62bcd8ec8b7ea19f69a51275e91299be594ea5cc6ef7819e16cd03"7108 checksum = "0ce5da8ecb62bcd8ec8b7ea19f69a51275e91299be594ea5cc6ef7819e16cd03"
7078 dependencies = [7109 dependencies = [
7079 "bytemuck",7110 "bytemuck",
7080- "safe_arch",7111+ "safe_arch 0.7.4",
7112+]
7113+
7114+[[package]]
7115+name = "wide"
7116+version = "1.7.0"
7117+source = "registry+https://github.com/rust-lang/crates.io-index"
7118+checksum = "8cf05ca94c9fba0c51316899caa1d1e74a064fc310a5efa7375e614343d415be"
7119+dependencies = [
7120+ "bytemuck",
7121+ "safe_arch 1.2.0",
7081 ]7122 ]
7082 7123
7083 [[package]]7124 [[package]]
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 `ruopus` and `oxideav-ac3` below, because a38+# above, the only seat still on this crate. Pinned exactly, like `ruopus` and
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+2 -2
@@ -27,7 +27,7 @@ const HW_CODECS: [(u32, &str); 4] = [
27 /// because the answer to "why is my HEVC file so large" is `oxideav-h26527 /// because the answer to "why is my HEVC file so large" is `oxideav-h265
28 /// intra`, and the row that says so is the row that answers it.28 /// intra`, and the row that says so is the row that answers it.
29 const SW_CODECS: [(&str, &str, bool, bool); 10] = [29 const SW_CODECS: [(&str, &str, bool, bool); 10] = [
30- ("H.264", "rusty_h264", true, true),30+ ("H.264", "ec-h264 / rusty_h264", true, true),
31 ("HEVC", "oxideav-h265 intra", false, true),31 ("HEVC", "oxideav-h265 intra", false, true),
32 ("AV1", "rav1e", false, true),32 ("AV1", "rav1e", false, true),
33 ("AAC", "rusty_aac", true, true),33 ("AAC", "rusty_aac", true, true),
@@ -137,7 +137,7 @@ mod tests {
137 // Decode-only crates must not read as encoders, and the seat words are137 // Decode-only crates must not read as encoders, and the seat words are
138 // the only thing saying which is which.138 // the only thing saying which is which.
139 assert!(line.contains("AC-3 dec (oxideav-ac3)"));139 assert!(line.contains("AC-3 dec (oxideav-ac3)"));
140- assert!(line.contains("H.264 dec+enc (rusty_h264)"));140+ assert!(line.contains("H.264 dec+enc (ec-h264 / rusty_h264)"));
141 assert!(line.contains("HEVC enc (oxideav-h265 intra)"));141 assert!(line.contains("HEVC enc (oxideav-h265 intra)"));
142 }142 }
143 }143 }
crates/engine/src/decode.rsmodified+102 -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,12 @@ 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 or VP91012 // ...except where there is nothing to fall back to. Feeding HEVC or VP9
1009- // bytes to `rusty_h264` would be garbage, not a fallback.1013+ // bytes to the H.264 decoder would be garbage, not a fallback.
1010 if opened.meta.codec != Codec::H264 {1014 if opened.meta.codec != Codec::H264 {
1011 eprintln!("{}", opened.meta.codec.needs_plugin());1015 eprintln!("{}", opened.meta.codec.needs_plugin());
1012 return;1016 return;
1013 }1017 }
1014- eprintln!("decode backend: software (rusty_h264)");1018+ eprintln!("decode backend: software (ec-h264)");
1015 backend.set(Backend::Software);1019 backend.set(Backend::Software);
1016 run(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed)1020 run(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed)
1017 }1021 }
@@ -1620,78 +1624,120 @@ fn run(
1620 // A decoder per span, and cheap: it is a parameter-set map and a picture1624 // 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 the1625 // buffer, while the *demuxer* -- whose index cost seconds to build -- is the
1622 // one this worker keeps.1626 // one this worker keeps.
1623- let mut decoder = Decoder::new();1627+ let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264))
1628+ .expect("ec-h264 takes its own codec id");
1624 // Decoding has to restart at a sync sample, so pictures between it and1629 // Decoding has to restart at a sync sample, so pictures between it and
1625 // `start_frame` are decoded (the target frame references them) but never1630 // `start_frame` are decoded (the target frame references them) but never
1626 // converted or sent. Signed, because the landing sync sample can sit inside1631 // 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.1632 // 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);1633 let mut index = demuxer.seek_to_sync_at_or_before(start_frame);
1634+ // Pictures leave the decoder in display order -- clause C.4.5.3 bumps the
1635+ // decoded picture buffer -- and the landing index above is a display index
1636+ // by the demuxer's own contract, so the two count one to one. The decode
1637+ // order this loop used to emit was a corner-cut that only held for
1638+ // Baseline: a stream with B pictures arrived scrambled and mislabelled,
1639+ // and every reader of `index` (the transport's playhead, `skip_for_speed`,
1640+ // the export's frame map) reads it as a timeline position.
1629 let mut skipped = 0;1641 let mut skipped = 0;
1630-1642+ // 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);1643+ // picture its reorder delay still holds, and the drain below ends on
1632- // reordering streams need POC-sorted output before display.1644+ // `Error::Eof` once they are out.
1633- loop {1645+ let mut flushed = false;
1646+ // Every way this span ends: abort, consumer gone, end of the requested
1647+ // range, end of stream.
1648+ let mut done = false;
1649+ while !done {
1634 if abort.hit() {1650 if abort.hit() {
1635 break;1651 break;
1636 }1652 }
1637- let au = match demuxer.next_access_unit() {1653+ // One access unit is one packet. No timestamps travel with it: the
1638- Ok(Some(au)) => au,1654+ // presentation order comes out of the bitstream's own POC, and `index`
1639- Ok(None) => break,1655+ // is counted off the pictures as the decoder releases them.
1656+ match demuxer.next_access_unit() {
1657+ Ok(Some(au)) => {
1658+ let packet = Packet::new(0, TimeBase::new(1, 1), au);
1659+ if let Err(e) = decoder.send_packet(&packet) {
1660+ eprintln!("decode error at access unit {index}: {e}");
1661+ break;
1662+ }
1663+ }
1664+ Ok(None) => {
1665+ flushed = true;
1666+ if let Err(e) = decoder.flush() {
1667+ eprintln!("decode error at end of stream: {e}");
1668+ break;
1669+ }
1670+ }
1640 Err(e) => {1671 Err(e) => {
1641 eprintln!("demux error: {e}");1672 eprintln!("demux error: {e}");
1642 break;1673 break;
1643 }1674 }
1644- };1675+ }
1645- let yuv = match decoder.decode(&au) {1676+ // Take everything the packet released; `NeedMore` is the signal to go
1646- Ok(Some(yuv)) => yuv,1677+ // back for the next access unit.
1647- Ok(None) => continue,1678+ loop {
1648- Err(e) => {1679+ let pic = match decoder.receive_frame() {
1649- eprintln!("decode error at access unit {index}: {e}");1680+ Ok(pic) => pic,
1650- break;1681+ Err(e) if e.is_need_more() || e.is_eof() => break,
1682+ Err(e) => {
1683+ eprintln!("decode error at access unit {index}: {e}");
1684+ break;
1685+ }
1686+ };
1687+ let ec_core::frame::Frame::Video(pic) = pic else {
1688+ continue;
1689+ };
1690+ if index < i64::from(start_frame) {
1691+ index += 1;
1692+ continue;
1651 }1693 }
1652- };1694+ let due = index as u32;
1653- if index < i64::from(start_frame) {
1654 index += 1;1695 index += 1;
1655- continue;1696+ if abort.late(due) {
1656- }1697+ if skipped < LATE_RUN {
1657- let due = index as u32;1698+ skipped += 1;
1658- index += 1;1699+ } else {
1659- if abort.late(due) {1700+ skipped = 0;
1660- if skipped < LATE_RUN {1701+ if send_picture(&pic, due, render, tx) {
1661- skipped += 1;1702+ done = true; // consumer went away
1703+ break;
1704+ }
1705+ }
1706+ } else if skip_for_speed(speed, start_frame, due, end_frame) {
1707+ // Redundant by construction, not by lateness: no run limit
1708+ // needed (see `skip_for_speed`).
1662 } else {1709 } else {
1663 skipped = 0;1710 skipped = 0;
1664- let frame = render.frame(1711+ if send_picture(&pic, due, render, tx) {
1665- due,1712+ done = true; // consumer went away
1666- &yuv.y,1713+ 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 }1714 }
1675 }1715 }
1676- } else if skip_for_speed(speed, start_frame, due, end_frame) {1716+ if index >= i64::from(end_frame) {
1677- // Redundant by construction, not by lateness: no run limit needed1717+ done = true; // end of the requested range
1678- // (see `skip_for_speed`).1718+ 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 }1719 }
1692 }1720 }
1693- if index >= i64::from(end_frame) {1721+ if flushed {
1694- break; // end of the requested range1722+ done = true;
1695 }1723 }
1696 }1724 }
1697 }1725 }
1726+
1727+/// Converts one decoded picture and queues it. `true` when the consumer went
1728+/// away, so the span stops rather than keeps decoding into a void.
1729+fn send_picture(pic: &VideoFrame, due: u32, render: &mut Render, tx: &SyncSender<Frame>) -> bool {
1730+ // The decoder crops each picture into tightly packed planes, the shape
1731+ // every converter below takes. A padded plane would render skewed rather
1732+ // than subtly wrong, so the assumption is pinned where it is relied on --
1733+ // free in a release build.
1734+ let (y, u, v) = (&pic.planes[0], &pic.planes[1], &pic.planes[2]);
1735+ debug_assert_eq!(y.stride, pic.width as usize, "padded luma plane");
1736+ debug_assert_eq!(
1737+ u.stride,
1738+ pic.width.div_ceil(2) as usize,
1739+ "padded chroma plane"
1740+ );
1741+ let frame = render.frame(due, &y.data, &u.data, &v.data, pic.width, pic.height);
1742+ tx.send(frame).is_err()
1743+}
crates/engine/src/demux.rsmodified+4 -4
@@ -132,10 +132,10 @@ impl Codec {
132 }132 }
133 }133 }
134 134
135- /// Why a file can be refused outright: `rusty_h264` is the only software135+ /// Why a file can be refused outright: the software decoder this project
136- /// decoder in the project and there is no pure-Rust HEVC or VP9 one to fall136+ /// carries is H.264's (`ec-h264`), and there is no pure-Rust HEVC or VP9
137- /// back to, so without the plugin there is nothing to decode with. Shared137+ /// one to fall back to, so without the plugin there is nothing to decode
138- /// so playback and export refuse in the same words.138+ /// with. Shared so playback and export refuse in the same words.
139 pub fn needs_plugin(self) -> String {139 pub fn needs_plugin(self) -> String {
140 format!(140 format!(
141 "{name} needs the VA-API plugin (libengine_hw.so) — there is no software {name} decoder",141 "{name} needs the VA-API plugin (libengine_hw.so) — there is no software {name} decoder",
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+}