forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1-seat' (1213004): AV1 joins H264 with a native software decode seat -- ec-av1 per-chunk whole-stream decode, byte-exact against the VA-API seat on 8-bit and 10-bit fixtures (60/60 frames, 0 differing bytes), seek-landing equivalence, refusal-in-words posture, AV1 imports work with no plugin at 1.70x realtime at 1080p-class

Browse files at this commit

ccfe87c105fd87906713c3a22255d5e51f8796edAhmet Kaan GümüşParent: a9674531213004
# Conflicts:
#	Cargo.lock
#	crates/engine/Cargo.toml
Cargo.lockmodified+16 -0
@@ -1596,6 +1596,21 @@ dependencies = [
1596 "ec-dsp",1596 "ec-dsp",
1597 ]1597 ]
1598 1598
1599+[[package]]
1600+name = "ec-av1"
1601+version = "0.1.0"
1602+dependencies = [
1603+ "ec-av1-syntax",
1604+ "ec-core",
1605+]
1606+
1607+[[package]]
1608+name = "ec-av1-syntax"
1609+version = "0.1.0"
1610+dependencies = [
1611+ "ec-core",
1612+]
1613+
1599 [[package]]1614 [[package]]
1600 name = "ec-core"1615 name = "ec-core"
1601 version = "0.1.0"1616 version = "0.1.0"
@@ -1682,6 +1697,7 @@ name = "engine"
1682 version = "0.1.0"1697 version = "0.1.0"
1683 dependencies = [1698 dependencies = [
1684 "ec-aac",1699 "ec-aac",
1700+ "ec-av1",
1685 "ec-core",1701 "ec-core",
1686 "ec-h264",1702 "ec-h264",
1687 "ec-opus",1703 "ec-opus",
crates/engine/Cargo.tomlmodified+7 -0
@@ -65,6 +65,13 @@ ec-core = { path = "../../../edith_codecs/crates/ec-core" }
65 # into FL, FR, FC, LFE, BL, BR, the order the downmix in `audio` folds, the65 # into FL, FR, FC, LFE, BL, BR, the order the downmix in `audio` folds, the
66 # same one the seat always delivered.66 # same one the seat always delivered.
67 ec-aac = { path = "../../../edith_codecs/crates/ec-aac" }67 ec-aac = { path = "../../../edith_codecs/crates/ec-aac" }
68+# The software AV1 decode seat, the project's own: a whole AV1 decoder
69+# (entropy, prediction, transforms, loop filters, film grain) with no
70+# third-party codec library under it, the same claim `ec-h264` makes for H.264.
71+# The seat decodes one GOP chunk at a time off the demuxer's reassembled OBU
72+# stream (`decode::run_av1`), so peak memory is one output picture plus the
73+# reference bank, and seeks stay the demuxer's job.
74+ec-av1 = { path = "../../../edith_codecs/crates/ec-av1" }
68 # The AAC *encoder*, and its last seat in the tree: so an mp4's sound can be a75 # The AAC *encoder*, and its last seat in the tree: so an mp4's sound can be a
69 # mix rather than a copy, an equalized (or otherwise processed) lane has to be76 # mix rather than a copy, an equalized (or otherwise processed) lane has to be
70 # decoded, and what is decoded has to be encoded again. Pure Rust with no C or77 # decoded, and what is decoded has to be encoded again. Pure Rust with no C or
crates/engine/src/decode.rsmodified+202 -13
@@ -8,9 +8,11 @@ use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel};
8 use std::thread;8 use std::thread;
9 9
10 use ec_core::frame::VideoFrame;10 use ec_core::frame::VideoFrame;
11+use ec_av1::encode::Picture as Av1Picture;
12+use ec_av1::stream::decode_stream_with;
11 use ec_core::registry::{CodecId, CodecParameters};13 use ec_core::registry::{CodecId, CodecParameters};
12 use ec_core::registry::Decoder as _;14 use ec_core::registry::Decoder as _;
13-use ec_core::{Packet, TimeBase};15+use ec_core::{Error as Av1Error, Packet, TimeBase};
14 use ec_h264::H264Decoder;16 use ec_h264::H264Decoder;
15 17
16 use crate::color::ColorParams;18 use crate::color::ColorParams;
@@ -46,7 +48,8 @@ pub enum Backend {
46 Opening,48 Opening,
47 /// The VA-API plugin (`libengine_hw.so`).49 /// The VA-API plugin (`libengine_hw.so`).
48 Hardware,50 Hardware,
49- /// `ec-h264`, in this process.51+ /// This project's own software seat: `ec-h264` or `ec-av1`, in this
52+ /// process.
50 Software,53 Software,
51 /// A still image: one `image` decode, no stream and no decoder to pick.54 /// A still image: one `image` decode, no stream and no decoder to pick.
52 Still,55 Still,
@@ -126,7 +129,7 @@ pub fn probe(path: &Path) -> crate::Result<(Option<Codec>, Backend)> {
126 let (meta, _demuxer) = Demuxer::open(&path)?;129 let (meta, _demuxer) = Demuxer::open(&path)?;
127 match hw_decodes(&path, 0, meta.codec) {130 match hw_decodes(&path, 0, meta.codec) {
128 Ok(()) => return Ok((Some(meta.codec), Backend::Hardware)),131 Ok(()) => return Ok((Some(meta.codec), Backend::Hardware)),
129- Err(e) if meta.codec != Codec::H264 => return Err(e.into()),132+ Err(e) if !matches!(meta.codec, Codec::H264 | Codec::Av1) => return Err(e.into()),
130 Err(_) => {}133 Err(_) => {}
131 }134 }
132 Ok((Some(meta.codec), Backend::Software))135 Ok((Some(meta.codec), Backend::Software))
@@ -634,8 +637,10 @@ impl DecodeSession {
634 // show it -- a worker that opened and then produced nothing is a black637 // show it -- a worker that opened and then produced nothing is a black
635 // screen with no explanation. The probe session is opened, made to638 // screen with no explanation. The probe session is opened, made to
636 // decode one picture and dropped: it costs one extra VA-API init639 // decode one picture and dropped: it costs one extra VA-API init
637- // (~90 ms) plus that frame, and only off the H.264 path.640+ // (~90 ms) plus that frame, and only off the two codecs with a software
638- if meta.codec != Codec::H264 {641+ // seat of their own -- H.264 through `ec-h264`, AV1 through `ec-av1` --
642+ // which fall back to it exactly where this probe would have refused.
643+ if !matches!(meta.codec, Codec::H264 | Codec::Av1) {
639 hw_decodes(&path, start_frame, meta.codec)?;644 hw_decodes(&path, start_frame, meta.codec)?;
640 }645 }
641 let end_frame = end_frame.min(meta.frame_count);646 let end_frame = end_frame.min(meta.frame_count);
@@ -1010,15 +1015,22 @@ fn run_span(
1010 eprintln!("hardware decode failed before any frame, falling back to software");1015 eprintln!("hardware decode failed before any frame, falling back to software");
1011 }1016 }
1012 // ...except where there is nothing to fall back to. Feeding HEVC, VP9 or1017 // ...except where there is nothing to fall back to. Feeding HEVC, VP9 or
1013- // VP8 bytes to the H.264 decoder (ec-h264) would be garbage, not a1018+ // VP8 bytes to either software seat would be garbage, not a fallback --
1014- // fallback — VP8's software decoder is libvpx, inside the plugin.1019+ // VP8's software decoder is libvpx, inside the plugin. H.264 and AV1 each
1015- if opened.meta.codec != Codec::H264 {1020+ // have one of this project's own: `ec-h264`, `ec-av1`.
1016- eprintln!("{}", opened.meta.codec.needs_plugin());1021+ match opened.meta.codec {
1017- return;1022+ Codec::H264 => {
1023+ eprintln!("decode backend: software (ec-h264)");
1024+ backend.set(Backend::Software);
1025+ run(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed);
1026+ }
1027+ Codec::Av1 => {
1028+ eprintln!("decode backend: software (ec-av1)");
1029+ backend.set(Backend::Software);
1030+ run_av1(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed);
1031+ }
1032+ other => eprintln!("{}", other.needs_plugin()),
1018 }1033 }
1019- eprintln!("decode backend: software (ec-h264)");
1020- backend.set(Backend::Software);
1021- run(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed)
1022 }1034 }
1023 1035
1024 /// One clip's pictures on their way to the renderer: graded, placed on the1036 /// One clip's pictures on their way to the renderer: graded, placed on the
@@ -1725,6 +1737,183 @@ fn run(
1725 }1737 }
1726 }1738 }
1727 1739
1740+/// Whether an access unit leads with a sequence header OBU, which is how both
1741+/// containers mark a random-access point for AV1: the demuxer prepends the
1742+/// `av1C`/`CodecPrivate` record (itself one sequence header OBU) ahead of every
1743+/// sync sample, so the marker rides on the same bytes the decoder needs. Type 1
1744+/// in bits 6..3 of the first OBU header byte.
1745+fn leads_with_sequence_header(au: &[u8]) -> bool {
1746+ matches!(au.first(), Some(&first) if first >> 3 & 0xF == 1)
1747+}
1748+
1749+/// One [`Av1Picture`] down to the tightly packed 8-bit I420 every converter
1750+/// here takes. 8-bit samples arrive as `u16` in `0..=255` and narrow losslessly;
1751+/// a 10-bit stream's `0..=1023` downshifts by two, the same truncation the
1752+/// hardware seat's P010 read-back performs when it takes the high byte of each
1753+/// pair (`p010_to_i420`, engine-hw) -- so the two seats hand the renderer
1754+/// byte-identical planes off the same file. 12-bit never reaches a seat: the
1755+/// demuxer refuses it at open, where `parse_av1c` reads the depth.
1756+fn narrow_av1(
1757+ picture: &Av1Picture,
1758+ ten_bit: bool,
1759+ y: &mut Vec<u8>,
1760+ u: &mut Vec<u8>,
1761+ v: &mut Vec<u8>,
1762+) {
1763+ let shift = u8::from(ten_bit) * 2;
1764+ let plane = |src: &[u16], dst: &mut Vec<u8>| {
1765+ dst.clear();
1766+ dst.extend(src.iter().map(|&sample| (sample >> shift) as u8));
1767+ };
1768+ plane(&picture.y, y);
1769+ plane(&picture.u, u);
1770+ plane(&picture.v, v);
1771+}
1772+
1773+/// Narrows one [`Av1Picture`] ([`narrow_av1`]) and queues it through the same
1774+/// [`Render`] every other seat's pictures go through. `true` when the consumer
1775+/// went away, so the span stops rather than keeps decoding into a void.
1776+fn send_av1(
1777+ picture: &Av1Picture,
1778+ due: u32,
1779+ ten_bit: bool,
1780+ render: &mut Render,
1781+ tx: &SyncSender<Frame>,
1782+ y: &mut Vec<u8>,
1783+ u: &mut Vec<u8>,
1784+ v: &mut Vec<u8>,
1785+) -> bool {
1786+ narrow_av1(picture, ten_bit, y, u, v);
1787+ let frame = render.frame(due, y, u, v, picture.width as u32, picture.height as u32);
1788+ tx.send(frame).is_err()
1789+}
1790+
1791+/// The AV1 software seat: one span of [`ec_av1`] through the same loop
1792+/// [`run`] drives `ec-h264` through. A decoder per span, and cheap -- it is the
1793+/// reference bank and one output picture, while the *demuxer* is the one this
1794+/// worker keeps. `ec-av1` has no packet-by-packet door; it takes one whole OBU
1795+/// stream, so the span is fed as it is built: every access unit from the landing
1796+/// sync sample up to (not including) the next one is one chunk, and a chunk is
1797+/// a legal random-access stream on its own -- it leads with the sequence header
1798+/// and a key frame, which is exactly what makes the chunk boundary detectable
1799+/// here ([`leads_with_sequence_header`]). A stream whose inter frames carried
1800+/// an in-band sequence header would be cut mid-GOP and refused by name below,
1801+/// never silently misread; container storage keeps the sequence header in the
1802+/// config record precisely so that does not happen.
1803+///
1804+/// Chunks decode to their end, so the reorder window of the chunk the span
1805+/// ends in always drains: hidden frames (`show_frame == 0`) are references
1806+/// and arrive at the sink with `shown == false`, and the frames they hold
1807+/// back in output order are the tail the sink still has to see.
1808+///
1809+/// A refusal out of `ec-av1` -- a real-world stream hitting a shape the
1810+/// decoder does not reconstruct -- fails the span in words, mid-film, the way
1811+/// the hardware seat's errors do: named on stderr, the pictures decoded so
1812+/// far stand, and no garbage is sent. The same sentinel ends a span that has
1813+/// delivered everything asked of it without decoding the rest of its last
1814+/// chunk.
1815+fn run_av1(
1816+ demuxer: &mut Demuxer,
1817+ tx: &SyncSender<Frame>,
1818+ start_frame: u32,
1819+ end_frame: u32,
1820+ render: &mut Render,
1821+ abort: &Abort,
1822+ speed: Speed,
1823+) {
1824+ // Signed, for the same reason [`run`]'s is: the landing sync sample can
1825+ // sit inside what an mp4's edit list trims, i.e. before frame 0.
1826+ let mut index = demuxer.seek_to_sync_at_or_before(start_frame);
1827+ // Reusable plane buffers: one allocation each for the whole span, refilled
1828+ // per picture by [`narrow_av1`].
1829+ let (mut y, mut u, mut v) = (Vec::new(), Vec::new(), Vec::new());
1830+ let mut skipped = 0;
1831+ // Every way this span ends: abort, consumer gone, the requested range
1832+ // delivered, the demuxer dry, or a refusal out of the decoder.
1833+ let mut done = false;
1834+ let mut demux_dry = false;
1835+ // An access unit read past a chunk boundary, waiting to head the next one.
1836+ let mut pending: Option<Vec<u8>> = None;
1837+ while !done && !demux_dry {
1838+ if abort.hit() {
1839+ break;
1840+ }
1841+ // One chunk: the access units from a sync sample up to the next one.
1842+ let mut stream = pending.take().unwrap_or_default();
1843+ while !demux_dry && pending.is_none() {
1844+ match demuxer.next_access_unit() {
1845+ Ok(Some(au)) => {
1846+ if !stream.is_empty() && leads_with_sequence_header(&au) {
1847+ pending = Some(au);
1848+ } else {
1849+ stream.extend_from_slice(&au);
1850+ }
1851+ }
1852+ Ok(None) => demux_dry = true,
1853+ Err(e) => {
1854+ eprintln!("demux error: {e}");
1855+ return;
1856+ }
1857+ }
1858+ }
1859+ let ten_bit = demuxer.bit_depth() == 10;
1860+ let decode = decode_stream_with(&stream, |picture, _, shown| {
1861+ // Hidden frames are references: they take no display slot and
1862+ // are never sent, but they do hold the chunk's output order
1863+ // back, which is why the chunk decodes to its end.
1864+ if !shown {
1865+ return Ok(());
1866+ }
1867+ let due = index;
1868+ index += 1;
1869+ if due < i64::from(start_frame) {
1870+ return Ok(());
1871+ }
1872+ let due = due as u32;
1873+ // The three ends [`run`] reaches per picture, in its own shape:
1874+ // late for the playhead (one in [`LATE_RUN`] still goes through),
1875+ // redundant by construction at speed, or a conversion and a send.
1876+ let sent = if abort.late(due) {
1877+ if skipped < LATE_RUN {
1878+ skipped += 1;
1879+ false
1880+ } else {
1881+ skipped = 0;
1882+ send_av1(picture, due, ten_bit, render, tx, &mut y, &mut u, &mut v)
1883+ }
1884+ } else if skip_for_speed(speed, start_frame, due, end_frame) {
1885+ // Redundant by construction, not by lateness: no run limit
1886+ // needed (see `skip_for_speed`).
1887+ false
1888+ } else {
1889+ skipped = 0;
1890+ send_av1(picture, due, ten_bit, render, tx, &mut y, &mut u, &mut v)
1891+ };
1892+ if sent {
1893+ done = true; // consumer went away
1894+ }
1895+ if done || i64::from(due) + 1 >= i64::from(end_frame) {
1896+ done = true; // the range is out, or nobody is left to take it
1897+ // Stops the decode inside the chunk: everything the span
1898+ // asked for has been sent, and the chunk's remaining coded
1899+ // frames are references for pictures nobody asked for.
1900+ return Err(Av1Error::Eof);
1901+ }
1902+ Ok(())
1903+ });
1904+ // `done` was set by the sink itself for the `Eof` it returns -- the
1905+ // sentinel, not a refusal. Any other `Err` is a refusal out of the
1906+ // decoder, named where the hardware seat's decode errors are named;
1907+ // the pictures decoded so far stand and the span ends.
1908+ if let Err(e) = decode {
1909+ if !done {
1910+ eprintln!("software AV1 decode failed at frame {index}: {e}");
1911+ done = true;
1912+ }
1913+ }
1914+ }
1915+}
1916+
1728 /// Converts one decoded picture and queues it. `true` when the consumer went1917 /// 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.1918 /// 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 {1919 fn send_picture(pic: &VideoFrame, due: u32, render: &mut Render, tx: &SyncSender<Frame>) -> bool {
crates/engine/src/demux.rsmodified+20 -11
@@ -136,22 +136,30 @@ impl Codec {
136 }136 }
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": H.264 and AV1 have software seats of this project's
140- /// decoder at all (H.264's is the native `ec-h264`), so the refusal names140+ /// own (`ec-h264`, `ec-av1`) and are never refused for missing hardware on
141- /// the plugin as the only way; VP8's software decoder *is* libvpx inside141+ /// the *playback* path; HEVC and VP9 have no software decoder at all, so
142- /// the plugin, so "there is no software decoder" would be a lie the day142+ /// the refusal names the plugin as the only way. VP8's software decoder
143- /// the plugin grew that arm -- the refusal keeps naming the plugin,143+ /// *is* libvpx inside the plugin, so "there is no software decoder" would
144- /// because that is still the thing to make present. Shared so playback144+ /// be a lie the day the plugin grew that arm -- the refusal keeps naming
145- /// and export refuse in the same words.145+ /// the plugin, because that is still the thing to make present. AV1's arm
146+ /// is the one refusal left that can reach it: the software *export*
147+ /// decoder is H.264-only (`export::SwDecoder`), so an AV1 source on a
148+ /// machine with no plugin exports through nothing. Shared so playback and
149+ /// export refuse in the same words.
146 pub fn needs_plugin(self) -> String {150 pub fn needs_plugin(self) -> String {
147 match self {151 match self {
148 Self::Vp8 => {152 Self::Vp8 => {
149 "VP8 needs the VA-API plugin (libengine_hw.so) — its decoder is libvpx, inside the plugin"153 "VP8 needs the VA-API plugin (libengine_hw.so) — its decoder is libvpx, inside the plugin"
150 .to_string()154 .to_string()
151 }155 }
156+ Self::Av1 => {
157+ "AV1 needs the VA-API plugin (libengine_hw.so) — playback decodes it in software, the software export path does not"
158+ .to_string()
159+ }
152 other => format!(160 other => format!(
153 "{name} needs the VA-API plugin (libengine_hw.so) — there is no software {name} decoder",161 "{name} needs the VA-API plugin (libengine_hw.so) — there is no software {name} decoder",
154- name = other.name()162+ name = other.name(),
155 ),163 ),
156 }164 }
157 }165 }
@@ -616,9 +624,10 @@ impl Demuxer {
616 624
617 /// Bits per luma sample the stream is coded at: 8 for everything but an625 /// Bits per luma sample the stream is coded at: 8 for everything but an
618 /// HEVC Main 10 or a 10-bit AV1 track, which decode into a P010 surface626 /// HEVC Main 10 or a 10-bit AV1 track, which decode into a P010 surface
619- /// rather than an NV12 one. Not part of [`VideoMeta`] because nothing above627+ /// rather than an NV12 one. Not part of [`VideoMeta`] because the read-back
620- /// the plugin has a use for it -- what comes out of the read-back is 8-bit628+ /// is 8-bit either way -- the two readers are the plugin's surface pool and
621- /// either way.629+ /// the software AV1 seat's narrowing ([`crate::decode::narrow_av1`]), and
630+ /// both consume the depth and hand out bytes.
622 pub fn bit_depth(&self) -> u8 {631 pub fn bit_depth(&self) -> u8 {
623 match self {632 match self {
624 Self::Mp4(d) => d.bit_depth,633 Self::Mp4(d) => d.bit_depth,
crates/engine/tests/av1.rsmodified+236 -29
@@ -2,9 +2,10 @@
2 //! arrives in a container of its own -- `mp4 0.14` knows no `av01` sample entry2 //! arrives in a container of its own -- `mp4 0.14` knows no `av01` sample entry
3 //! at all, so AV1 comes in as Matroska and the demuxer walks the EBML itself.3 //! at all, so AV1 comes in as Matroska and the demuxer walks the EBML itself.
4 //!4 //!
5-//! The container and refusal checks need nothing installed. The decode and5+//! Decoding has two seats: the project's own `ec-av1` in this process, and the
6-//! export twins need a built `libengine_hw.so` and a VA-API driver with an AV16+//! VA-API plugin's (`vainfo | grep AV1`) in front of it. The software seat needs
7-//! decode entrypoint (`vainfo | grep AV1`), so they are `#[ignore]`d:7+//! nothing installed, so its witnesses run unignored (`VE_SW` pins it); the
8+//! hardware twins need a built `libengine_hw.so` and are `#[ignore]`d:
8 //!9 //!
9 //! ```text10 //! ```text
10 //! cargo build -p engine -p engine-hw --release11 //! cargo build -p engine -p engine-hw --release
@@ -12,8 +13,8 @@
12 //! cargo test -p engine --release --test av1 -- --include-ignored --nocapture --test-threads=113 //! cargo test -p engine --release --test av1 -- --include-ignored --nocapture --test-threads=1
13 //! ```14 //! ```
14 //!15 //!
15-//! `VE_SW` is process-wide, hence `--test-threads=1`: the refusal test sets it16+//! `VE_SW` is process-wide, hence `--test-threads=1`: the software-seat tests
16-//! and puts it back so the hardware twins below really are hardware.17+//! set it and put it back so the hardware twins below really are hardware.
17 18
18 use std::path::PathBuf;19 use std::path::PathBuf;
19 use std::time::{Duration, Instant};20 use std::time::{Duration, Instant};
@@ -142,44 +143,250 @@ fn every_block_comes_back_and_keyframes_carry_the_sequence_header() {
142 assert_eq!((after[0] >> 3) & 0xF, 1, "{}", after[0]);143 assert_eq!((after[0] >> 3) & 0xF, 1, "{}", after[0]);
143 }144 }
144 145
145-/// There is no software AV1 decoder, so the software path must refuse by name146+/// The seat this file used to refuse by name now exists: `ec-av1`, in this
146-/// rather than feed AV1 bytes to `ec-h264` -- and it must refuse where a147+/// process, behind the same `VE_SW` pin the H.264 seat takes. A linear open
147-/// caller can still show it, i.e. out of `open`, not from inside the worker.148+/// delivers every frame the container indexes, labelled `0..n` in display
149+/// order -- the contract the transport reads and the one the hardware seat
150+/// always kept.
148 #[test]151 #[test]
149-fn the_software_path_refuses_av1_by_name() {152+fn the_software_seat_decodes_every_frame() {
150- // SAFETY: the suite is documented to run with --test-threads=1.153+ // SAFETY: the suite is documented to run with --test-threads=1. The pin
154+ // stays up until the frames are drained: it is read on the worker thread
155+ // when the span opens, not only at the door here.
151 unsafe { std::env::set_var("VE_SW", "1") };156 unsafe { std::env::set_var("VE_SW", "1") };
152- let refused =157+ let (meta, rx) = DecodeSession::open(asset("test_av1.mkv")).expect("software AV1 open");
153- DecodeSession::open(asset("test_av1.mkv")).expect_err("software must not accept AV1");158+ assert_eq!(meta.frame_count, FRAMES);
154- let refused = refused.to_string();159+ let indices: Vec<u32> = rx.into_iter().map(|f| f.index).collect();
155- // Restored immediately: the hardware tests in this binary share the process.
156 unsafe { std::env::remove_var("VE_SW") };160 unsafe { std::env::remove_var("VE_SW") };
161+ assert_eq!(indices, (0..FRAMES).collect::<Vec<_>>(), "frames must arrive 0..n in display order");
162+}
157 163
158- assert!(refused.contains("AV1"), "{refused}");164+/// ...and the 10-bit twin, whose samples arrive as `u16` in `0..=1023` and
159- assert!(refused.contains("plugin"), "{refused}");165+/// narrow to the same 8-bit planes the plugin's P010 read-back produces.
166+#[test]
167+fn the_software_seat_decodes_ten_bit_av1() {
168+ // SAFETY: the suite is documented to run with --test-threads=1; held
169+ // through the drain, as above.
170+ unsafe { std::env::set_var("VE_SW", "1") };
171+ let (meta, rx) = DecodeSession::open(asset("test_av1_10.mkv")).expect("software AV1 open");
172+ assert_eq!(meta.frame_count, FRAMES);
173+ let count = rx.into_iter().count();
174+ unsafe { std::env::remove_var("VE_SW") };
175+ assert_eq!(count, FRAMES as usize, "every 10-bit frame came out");
176+}
177+
178+/// Seeking may only change *when* a picture arrives, never the picture: a seek
179+/// onto the software seat lands on the very bytes a linear decode of the same
180+/// index delivered, on either side of and away from a keyframe. The promise
181+/// `hw_decode::seek_matches_linear_every_container` makes of the hardware
182+/// seat, made here of the software one -- which is why this runs unignored.
183+#[test]
184+fn seek_lands_on_the_picture_a_linear_software_decode_delivered() {
185+ // SAFETY: the suite is documented to run with --test-threads=1.
186+ unsafe { std::env::set_var("VE_SW", "1") };
187+ let path = asset("test_av1.mkv");
188+ let (meta, rx) = DecodeSession::open(&path).expect("software open");
189+ let mut targets = vec![0, 1, 29, 30, 31, 45, meta.frame_count - 1];
190+ targets.retain(|&t| t < meta.frame_count);
191+ targets.sort_unstable();
192+ targets.dedup();
193+ let linear: Vec<(u32, Vec<u8>)> = rx
194+ .into_iter()
195+ .filter(|f| targets.contains(&f.index))
196+ .map(|f| (f.index, f.bgra))
197+ .collect();
198+ assert_eq!(
199+ linear.iter().map(|(i, _)| *i).collect::<Vec<_>>(),
200+ targets,
201+ "linear decode never delivered every target"
202+ );
203+ for (target, want) in linear {
204+ let (_, rx, _cancel) = DecodeSession::open_at(&path, target).expect("open_at");
205+ let seeked = rx
206+ .into_iter()
207+ .next()
208+ .unwrap_or_else(|| panic!("no frame after seek to {target}"));
209+ assert_eq!(seeked.index, target, "first frame after seek is not the target");
210+ assert!(
211+ seeked.bgra == want,
212+ "seek to {target} handed back a different picture than a linear decode of {target}"
213+ );
214+ }
215+ unsafe { std::env::remove_var("VE_SW") };
160 }216 }
161 217
162 /// A timeline is *not* refused a source coded differently -- every clip opens218 /// A timeline is *not* refused a source coded differently -- every clip opens
163-/// its own decoder. What survives is the reason the codec gate existed: on a219+/// its own decoder, and since the `ec-av1` seat that is true with no plugin
164-/// machine that cannot decode AV1 the file is refused at the door, by the220+/// and no driver in the room: the no-plugin machine, forced, takes the AV1
165-/// decoder's own name, rather than becoming a clip of black frames.221+/// source beside its H.264 one.
166 #[test]222 #[test]
167-fn a_timeline_takes_the_other_codec_or_names_the_missing_decoder() {223+fn a_timeline_takes_av1_on_a_machine_with_no_plugin() {
168 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");224 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
169- // The no-plugin machine, forced.225+ // SAFETY: the suite is documented to run with --test-threads=1. The pin
170- // SAFETY: the suite is documented to run with --test-threads=1.226+ // stays up until the import has been through the seat's door (and the
227+ // worker it spawned has opened its span on it), then comes back down.
171 unsafe { std::env::set_var("VE_SW", "1") };228 unsafe { std::env::set_var("VE_SW", "1") };
172- let refused = session229+ let imported = session
173 .import(&asset("test_av1.mkv"))230 .import(&asset("test_av1.mkv"))
174- .expect_err("no AV1 decoder means no AV1 clip")231+ .is_ok();
175- .to_string();232+ assert!(imported, "the software seat is a seat: the timeline takes AV1");
233+ assert_eq!(session.sources().len(), 2, "both sources stand");
176 unsafe { std::env::remove_var("VE_SW") };234 unsafe { std::env::remove_var("VE_SW") };
177- assert_eq!(refused, Codec::Av1.needs_plugin());235+}
236+
237+// --- the refusal witness ---------------------------------------------------
238+//
239+// The minimal EBML this file's refusal fixture is written with -- the same
240+// builders `mkv_encodings.rs` uses, kept local because test binaries do not
241+// share code. Every size goes out in the 8-byte long form, legal everywhere
242+// and arithmetic-free.
243+
244+const SEGMENT: u32 = 0x1853_8067;
245+const INFO: u32 = 0x1549_A966;
246+const TIMESTAMP_SCALE: u32 = 0x2AD7B1;
247+const TRACKS: u32 = 0x1654_AE6B;
248+const TRACK_ENTRY: u32 = 0xAE;
249+const TRACK_NUMBER: u32 = 0xD7;
250+const TRACK_TYPE: u32 = 0x83;
251+const CODEC_ID: u32 = 0x86;
252+const CODEC_PRIVATE: u32 = 0x63A2;
253+const DEFAULT_DURATION: u32 = 0x23E383;
254+const VIDEO: u32 = 0xE0;
255+const PIXEL_WIDTH: u32 = 0xB0;
256+const PIXEL_HEIGHT: u32 = 0xBA;
257+const CLUSTER: u32 = 0x1F43_B675;
258+const CLUSTER_TIMESTAMP: u32 = 0xE7;
259+const SIMPLE_BLOCK: u32 = 0xA3;
260+
261+fn el(id: u32, body: &[u8]) -> Vec<u8> {
262+ let mut out: Vec<u8> = id.to_be_bytes()[(id.leading_zeros() / 8) as usize..].to_vec();
263+ out.push(0x01);
264+ out.extend_from_slice(&(body.len() as u64).to_be_bytes()[1..]);
265+ out.extend_from_slice(body);
266+ out
267+}
268+
269+fn uint(id: u32, value: u64) -> Vec<u8> {
270+ el(id, &value.to_be_bytes())
271+}
272+
273+/// A `SimpleBlock` of `track`, `rel` ticks into its cluster; `flags` carries
274+/// the keyframe bit (0x80).
275+fn block(track: u8, rel: i16, flags: u8, body: &[u8]) -> Vec<u8> {
276+ let mut b = vec![0x80 | track];
277+ b.extend_from_slice(&rel.to_be_bytes());
278+ b.push(flags);
279+ b.extend_from_slice(body);
280+ el(SIMPLE_BLOCK, &b)
281+}
282+
283+/// One OBU's total length inside a low-overhead stream: the header byte (plus
284+/// its extension byte, which this fixture format never writes) and the
285+/// leb128 size that `obu_has_size_field` promises.
286+fn obu_len(stream: &[u8]) -> usize {
287+ assert_eq!(stream[0] & 0x2, 2, "obu_has_size_field: low-overhead format");
288+ let mut len = 1;
289+ let mut size: usize = 0;
290+ loop {
291+ let byte = stream[len];
292+ len += 1;
293+ size = size << 7 | usize::from(byte & 0x7F);
294+ if byte & 0x80 == 0 {
295+ break;
296+ }
297+ }
298+ len + size
299+}
300+
301+/// A stream whose GOP structure is broken in a way the container cannot see:
302+/// the second keyframe-flagged block carries an *inter* frame's bytes, as a
303+/// remux that trusted the wrong key index would write one. The demuxer opens
304+/// it, injects the sequence header ahead of it, and `ec-av1` refuses it by
305+/// name -- an inter frame with no key frame behind it finds no saved CDF state
306+/// to resume from, one of the live refusals its inventory pins -- and the seat
307+/// fails the span in words instead of a panic or a garbage picture: the frames
308+/// decoded so far stand, then the channel closes.
309+#[test]
310+fn a_broken_gop_is_refused_in_words_and_never_a_panic() {
311+ // The pieces, off the real fixture: the sequence header OBU the demuxer
312+ // injects (the `av1C` payload) and a real inter frame's block bytes.
313+ let (_, mut demuxer) = Demuxer::open(&asset("test_av1.mkv")).expect("open test_av1.mkv");
314+ let key_au = demuxer.next_access_unit().expect("read").expect("key au");
315+ let seq_len = obu_len(&key_au);
316+ let seq_header = &key_au[..seq_len];
317+ let key_body = &key_au[seq_len..];
318+ // The very next access unit is frame 1, a real inter frame: no injection
319+ // ahead of a non-sync sample, so its bytes are the block verbatim.
320+ let inter_body = demuxer.next_access_unit().expect("read").expect("inter au");
321+
322+ // The words first, at the decoder's own door: the crafted chunk is
323+ // refused, and the refusal is a sentence, not a panic.
324+ let mut broken = seq_header.to_vec();
325+ broken.extend_from_slice(&inter_body);
326+ let refused = ec_av1::stream::decode_stream(&broken)
327+ .expect_err("an inter frame with no key frame behind it is refused");
178 assert!(328 assert!(
179- !refused.contains("H.264"),329+ refused.to_string().contains("no saved CDF state"),
180- "the timeline's own codec is no longer a reason: {refused}"330+ "the refusal names its reason: {refused}"
331+ );
332+
333+ // The same broken stream as a file, through the seat: open succeeds (the
334+ // container is valid), the first GOP decodes, the second chunk refuses,
335+ // and the span ends cleanly with exactly the pictures decoded so far.
336+ let av1c = [0x81u8, 0x00, 0x0C, 0x00];
337+ let mut private = av1c.to_vec();
338+ private.extend_from_slice(seq_header);
339+ let track = el(
340+ TRACK_ENTRY,
341+ &[
342+ uint(TRACK_NUMBER, 1),
343+ uint(TRACK_TYPE, 1),
344+ el(CODEC_ID, b"V_AV1"),
345+ el(CODEC_PRIVATE, &private),
346+ uint(DEFAULT_DURATION, 33_333_333),
347+ el(VIDEO, &[uint(PIXEL_WIDTH, 1280), uint(PIXEL_HEIGHT, 720)].concat()),
348+ ]
349+ .concat(),
350+ );
351+ let cluster = el(
352+ CLUSTER,
353+ &[
354+ uint(CLUSTER_TIMESTAMP, 0),
355+ block(1, 0, 0x80, key_body),
356+ block(1, 33, 0x80, &inter_body),
357+ ]
358+ .concat(),
181 );359 );
182- assert_eq!(session.sources().len(), 1, "a refusal left no row");360+ let segment = [
361+ el(INFO, &uint(TIMESTAMP_SCALE, 1_000_000)),
362+ el(TRACKS, &track),
363+ cluster,
364+ ]
365+ .concat();
366+ let file = [
367+ el(0x1A45_DFA3, &[]),
368+ el(SEGMENT, &segment),
369+ ]
370+ .concat();
371+ let scratch = Scratch::file("broken_gop_av1", "mkv");
372+ std::fs::write(&scratch, &file).expect("write fixture");
373+
374+ let (meta, mut opened) = Demuxer::open(&scratch).expect("the container itself is valid");
375+ assert_eq!(meta.codec, Codec::Av1);
376+ assert_eq!(meta.frame_count, 2);
377+ // Both blocks are key-flagged, so both lead with the injected sequence
378+ // header -- which is what makes the second one a chunk boundary, and the
379+ // refusal the decoder's own answer to what it finds there.
380+ let first = opened.next_access_unit().expect("read").expect("au");
381+ assert_eq!((first[0] >> 3) & 0xF, 1);
382+
383+ // SAFETY: the suite is documented to run with --test-threads=1; the pin
384+ // held through the drain, as in every seat test above.
385+ unsafe { std::env::set_var("VE_SW", "1") };
386+ let (_, rx) = DecodeSession::open(&scratch).expect("open succeeds; the container is fine");
387+ let frames: Vec<u32> = rx.into_iter().map(|f| f.index).collect();
388+ unsafe { std::env::remove_var("VE_SW") };
389+ assert_eq!(frames, vec![0], "the first GOP stands, the broken one refuses");
183 }390 }
184 391
185 /// The end-to-end user path: opening the file yields pictures, all of them,392 /// The end-to-end user path: opening the file yields pictures, all of them,
crates/engine/tests/hw_decode.rsmodified+74 -2
@@ -201,8 +201,12 @@ fn seek_matches_linear() {
201 #[test]201 #[test]
202 #[ignore = "needs libengine_hw.so and a VA-API driver"]202 #[ignore = "needs libengine_hw.so and a VA-API driver"]
203 fn seek_matches_linear_every_container() {203 fn seek_matches_linear_every_container() {
204- // The hardware path for all of these: there is no software HEVC or AV1204+ // Sanitize at entry: sibling tests leak `VE_SW=1` by design and run before
205- // decoder to compare against. SAFETY: --test-threads=1.205+ // this one alphabetically, and a leaked pin makes the plugin-only HEVC
206+ // fixtures refuse at open. The hardware path for these, including AV1's
207+ // fixture: the point is the seek against the same seat a linear decode ran
208+ // on, which the tests below pin for the software seat. SAFETY:
209+ // --test-threads=1, which the documented invocation keeps.
206 unsafe { std::env::remove_var("VE_SW") };210 unsafe { std::env::remove_var("VE_SW") };
207 for name in [211 for name in [
208 "test_baseline.mp4",212 "test_baseline.mp4",
@@ -405,3 +409,71 @@ fn hardware_matches_software_on_frame_30() {
405 eprintln!("frame 30 differing bytes: {diff} / {}", hw.len());409 eprintln!("frame 30 differing bytes: {diff} / {}", hw.len());
406 assert_eq!(diff, 0, "hardware and software decode disagree");410 assert_eq!(diff, 0, "hardware and software decode disagree");
407 }411 }
412+
413+/// The AV1 twin of [`hardware_matches_software_on_frame_30`]: the plugin's
414+/// VA-API decoder against the project's own `ec-av1`, whole file, byte for
415+/// byte -- 8-bit AV1 decode is bit-exact by the same conformance argument the
416+/// H.264 twin makes, and a mismatch means a deviation in one of the two
417+/// decoders, reported rather than swallowed.
418+#[test]
419+#[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"]
420+fn av1_hardware_matches_software_on_every_frame() {
421+ const NAME: &str = "test_av1.mkv";
422+ let (hw_count, hw_frame_30) = decode_all_hw(NAME);
423+
424+ // Pin the comparison side to software ourselves: without this, running the
425+ // suite without VE_SW=1 would compare hardware against hardware and pass
426+ // vacuously. SAFETY: the suite is documented to run with --test-threads=1.
427+ unsafe { std::env::set_var("VE_SW", "1") };
428+ let path = asset(NAME);
429+ let start = Instant::now();
430+ let (meta, rx) = DecodeSession::open(&path).expect("software open");
431+ let mut sw_count = 0usize;
432+ let mut sw_frame_30 = Vec::new();
433+ for frame in rx {
434+ if frame.index == 30 {
435+ sw_frame_30 = frame.bgra;
436+ }
437+ sw_count += 1;
438+ }
439+ let sw_elapsed = start.elapsed();
440+ unsafe { std::env::remove_var("VE_SW") };
441+ eprintln!("{NAME}: hardware {hw_count} frames, software {sw_count} frames in {sw_elapsed:?}");
442+ assert_eq!(sw_count, hw_count, "frame count");
443+ assert_eq!(sw_count, usize::try_from(meta.frame_count).expect("count"));
444+ assert_eq!(hw_frame_30.len(), sw_frame_30.len(), "frame size");
445+ let diff = hw_frame_30.iter().zip(&sw_frame_30).filter(|(a, b)| a != b).count();
446+ eprintln!("frame 30 differing bytes: {diff} / {}", sw_frame_30.len());
447+ assert_eq!(diff, 0, "hardware and software AV1 decode disagree");
448+}
449+
450+/// The 10-bit twin: the plugin reads a P010 surface back as the high byte of
451+/// each pair; `ec-av1` hands `u16` planes the seat downshifts by two. Same
452+/// truncation, same picture -- or one of the two seats is wrong.
453+#[test]
454+#[ignore = "needs libengine_hw.so and a VA-API driver with 10-bit AV1 decode"]
455+fn av1_ten_bit_hardware_matches_software_on_every_frame() {
456+ const NAME: &str = "test_av1_10.mkv";
457+ let (hw_count, hw_frame_30) = decode_all_hw(NAME);
458+ // SAFETY: the suite is documented to run with --test-threads=1.
459+ unsafe { std::env::set_var("VE_SW", "1") };
460+ let path = asset(NAME);
461+ let start = Instant::now();
462+ let (_, rx) = DecodeSession::open(&path).expect("software open");
463+ let mut sw_count = 0usize;
464+ let mut sw_frame_30 = Vec::new();
465+ for frame in rx {
466+ if frame.index == 30 {
467+ sw_frame_30 = frame.bgra;
468+ }
469+ sw_count += 1;
470+ }
471+ let sw_elapsed = start.elapsed();
472+ unsafe { std::env::remove_var("VE_SW") };
473+ eprintln!("{NAME}: hardware {hw_count} frames, software {sw_count} frames in {sw_elapsed:?}");
474+ assert_eq!(sw_count, hw_count, "frame count");
475+ assert_eq!(hw_frame_30.len(), sw_frame_30.len(), "frame size");
476+ let diff = hw_frame_30.iter().zip(&sw_frame_30).filter(|(a, b)| a != b).count();
477+ eprintln!("frame 30 differing bytes: {diff} / {}", sw_frame_30.len());
478+ assert_eq!(diff, 0, "hardware and software 10-bit AV1 decode disagree");
479+}