From 875b31a91b4269a28bb6c784a3043ada5b231c9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 12 Sep 2026 21:45:16 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(engine):=20a=20native=20AV1=20?= =?UTF-8?q?decode=20seat=20=E2=80=94=20ec-av1=20takes=20AV1=20sources=20wi?= =?UTF-8?q?th=20no=20plugin=20in=20the=20room?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The software arm of decode.rs grows a second seat beside ec-h264: probe(), open_worker()'s plugin gate and run_span() all take Codec::Av1 as a software-covered codec, falling back to ec-av1 exactly where H.264 falls back to ec-h264. VE_SW=1 pins it, Backend::Software reports it. The seat feeds ec-av1's whole-stream door the way the demuxer assembles AV1 anyway: access units from the landing sync sample to the next one are one chunk (the sequence header the demuxer injects ahead of every sync sample is the boundary marker), and each chunk is a legal random-access stream that decodes to its end — so hidden reference frames drain and the reorder tail lands. A span stops decoding at its last asked-for picture via a sink Eof sentinel; a refusal out of ec-av1 fails the span in words mid-film, the pictures decoded so far standing, never garbage. u16 planes narrow at the seat: 0..=255 casts, 10-bit downshifts by two — the same truncation the plugin's P010 read-back performs, so both seats hand the renderer byte-identical planes. Witnesses: plugin vs seat frame-for-frame byte-exact on test_av1.mkv and on the 10-bit twin (frame 30, 0 differing bytes both); seek-landing equals linear on the software seat across a keyframe interval; a crafted broken-GOP file (keyframe-flagged inter frame) is refused by name — "no saved CDF state" — with the first GOP standing and the channel closing clean. Perf (release, funnel incl. demux+convert, identical config both sides): VA-API 2.0x the seat on 720p8 (100 vs 51 fps), 1.8x on 720p10 (95 vs 53), 4.9x on a 1920x792 10-bit film (199 vs 41 fps, seat 1.70x realtime), 3.5x on a 3840x1608 10-bit film (22 vs 6.2 fps, seat 0.26x realtime — below 1x, but so is the plugin's own 0.92x there: the BGRA conversion dominates that funnel). 1.70x realtime at 1080p-class clears the threads-wiring bar, so EC_AV1_THREADS stays opt-in. demux::needs_plugin's AV1 arm now names the export path (whose software decoder stays H.264-only) instead of claiming no software decoder exists; bit_depth()'s doc gains its second reader. --- Cargo.lock | 16 ++ crates/engine/Cargo.toml | 7 + crates/engine/src/decode.rs | 215 +++++++++++++++++++++++-- crates/engine/src/demux.rs | 31 ++-- crates/engine/tests/av1.rs | 265 +++++++++++++++++++++++++++---- crates/engine/tests/hw_decode.rs | 74 ++++++++- 6 files changed, 552 insertions(+), 56 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 944a3f4..f1ca8ed 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1588,6 +1588,21 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" +[[package]] +name = "ec-av1" +version = "0.1.0" +dependencies = [ + "ec-av1-syntax", + "ec-core", +] + +[[package]] +name = "ec-av1-syntax" +version = "0.1.0" +dependencies = [ + "ec-core", +] + [[package]] name = "ec-core" version = "0.1.0" @@ -1673,6 +1688,7 @@ checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" name = "engine" version = "0.1.0" dependencies = [ + "ec-av1", "ec-core", "ec-h264", "ec-opus", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 3d5069a..c97fafe 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -58,6 +58,13 @@ ec-h264 = { path = "../../../edith_codecs/crates/ec-h264" } # Its shared IR (packets, frames, the registry decoder contract the seat is # written against), direct because decode.rs names those types itself. ec-core = { path = "../../../edith_codecs/crates/ec-core" } +# The software AV1 decode seat, the project's own: a whole AV1 decoder +# (entropy, prediction, transforms, loop filters, film grain) with no +# third-party codec library under it, the same claim `ec-h264` makes for H.264. +# The seat decodes one GOP chunk at a time off the demuxer's reassembled OBU +# stream (`decode::run_av1`), so peak memory is one output picture plus the +# reference bank, and seeks stay the demuxer's job. +ec-av1 = { path = "../../../edith_codecs/crates/ec-av1" } # Both halves of AAC, and the only crate here that is asked for both. The # *encoder*, so an mp4's sound can be a mix rather than a copy: an equalized (or # otherwise processed) lane has to be decoded, and what is decoded has to be diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index aa5122c..5920836 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -8,9 +8,11 @@ use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel}; use std::thread; use ec_core::frame::VideoFrame; +use ec_av1::encode::Picture as Av1Picture; +use ec_av1::stream::decode_stream_with; use ec_core::registry::{CodecId, CodecParameters}; use ec_core::registry::Decoder as _; -use ec_core::{Packet, TimeBase}; +use ec_core::{Error as Av1Error, Packet, TimeBase}; use ec_h264::H264Decoder; use crate::color::ColorParams; @@ -46,7 +48,8 @@ pub enum Backend { Opening, /// The VA-API plugin (`libengine_hw.so`). Hardware, - /// `ec-h264`, in this process. + /// This project's own software seat: `ec-h264` or `ec-av1`, in this + /// process. Software, /// A still image: one `image` decode, no stream and no decoder to pick. Still, @@ -126,7 +129,7 @@ pub fn probe(path: &Path) -> crate::Result<(Option, Backend)> { let (meta, _demuxer) = Demuxer::open(&path)?; match hw_decodes(&path, 0, meta.codec) { Ok(()) => return Ok((Some(meta.codec), Backend::Hardware)), - Err(e) if meta.codec != Codec::H264 => return Err(e.into()), + Err(e) if !matches!(meta.codec, Codec::H264 | Codec::Av1) => return Err(e.into()), Err(_) => {} } Ok((Some(meta.codec), Backend::Software)) @@ -634,8 +637,10 @@ impl DecodeSession { // show it -- a worker that opened and then produced nothing is a black // screen with no explanation. The probe session is opened, made to // decode one picture and dropped: it costs one extra VA-API init - // (~90 ms) plus that frame, and only off the H.264 path. - if meta.codec != Codec::H264 { + // (~90 ms) plus that frame, and only off the two codecs with a software + // seat of their own -- H.264 through `ec-h264`, AV1 through `ec-av1` -- + // which fall back to it exactly where this probe would have refused. + if !matches!(meta.codec, Codec::H264 | Codec::Av1) { hw_decodes(&path, start_frame, meta.codec)?; } let end_frame = end_frame.min(meta.frame_count); @@ -1010,15 +1015,22 @@ fn run_span( eprintln!("hardware decode failed before any frame, falling back to software"); } // ...except where there is nothing to fall back to. Feeding HEVC, VP9 or - // VP8 bytes to the H.264 decoder (ec-h264) would be garbage, not a - // fallback — VP8's software decoder is libvpx, inside the plugin. - if opened.meta.codec != Codec::H264 { - eprintln!("{}", opened.meta.codec.needs_plugin()); - return; + // VP8 bytes to either software seat would be garbage, not a fallback -- + // VP8's software decoder is libvpx, inside the plugin. H.264 and AV1 each + // have one of this project's own: `ec-h264`, `ec-av1`. + match opened.meta.codec { + Codec::H264 => { + eprintln!("decode backend: software (ec-h264)"); + backend.set(Backend::Software); + run(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed); + } + Codec::Av1 => { + eprintln!("decode backend: software (ec-av1)"); + backend.set(Backend::Software); + run_av1(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed); + } + other => eprintln!("{}", other.needs_plugin()), } - eprintln!("decode backend: software (ec-h264)"); - backend.set(Backend::Software); - run(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed) } /// One clip's pictures on their way to the renderer: graded, placed on the @@ -1725,6 +1737,183 @@ fn run( } } +/// Whether an access unit leads with a sequence header OBU, which is how both +/// containers mark a random-access point for AV1: the demuxer prepends the +/// `av1C`/`CodecPrivate` record (itself one sequence header OBU) ahead of every +/// sync sample, so the marker rides on the same bytes the decoder needs. Type 1 +/// in bits 6..3 of the first OBU header byte. +fn leads_with_sequence_header(au: &[u8]) -> bool { + matches!(au.first(), Some(&first) if first >> 3 & 0xF == 1) +} + +/// One [`Av1Picture`] down to the tightly packed 8-bit I420 every converter +/// here takes. 8-bit samples arrive as `u16` in `0..=255` and narrow losslessly; +/// a 10-bit stream's `0..=1023` downshifts by two, the same truncation the +/// hardware seat's P010 read-back performs when it takes the high byte of each +/// pair (`p010_to_i420`, engine-hw) -- so the two seats hand the renderer +/// byte-identical planes off the same file. 12-bit never reaches a seat: the +/// demuxer refuses it at open, where `parse_av1c` reads the depth. +fn narrow_av1( + picture: &Av1Picture, + ten_bit: bool, + y: &mut Vec, + u: &mut Vec, + v: &mut Vec, +) { + let shift = u8::from(ten_bit) * 2; + let plane = |src: &[u16], dst: &mut Vec| { + dst.clear(); + dst.extend(src.iter().map(|&sample| (sample >> shift) as u8)); + }; + plane(&picture.y, y); + plane(&picture.u, u); + plane(&picture.v, v); +} + +/// Narrows one [`Av1Picture`] ([`narrow_av1`]) and queues it through the same +/// [`Render`] every other seat's pictures go through. `true` when the consumer +/// went away, so the span stops rather than keeps decoding into a void. +fn send_av1( + picture: &Av1Picture, + due: u32, + ten_bit: bool, + render: &mut Render, + tx: &SyncSender, + y: &mut Vec, + u: &mut Vec, + v: &mut Vec, +) -> bool { + narrow_av1(picture, ten_bit, y, u, v); + let frame = render.frame(due, y, u, v, picture.width as u32, picture.height as u32); + tx.send(frame).is_err() +} + +/// The AV1 software seat: one span of [`ec_av1`] through the same loop +/// [`run`] drives `ec-h264` through. A decoder per span, and cheap -- it is the +/// reference bank and one output picture, while the *demuxer* is the one this +/// worker keeps. `ec-av1` has no packet-by-packet door; it takes one whole OBU +/// stream, so the span is fed as it is built: every access unit from the landing +/// sync sample up to (not including) the next one is one chunk, and a chunk is +/// a legal random-access stream on its own -- it leads with the sequence header +/// and a key frame, which is exactly what makes the chunk boundary detectable +/// here ([`leads_with_sequence_header`]). A stream whose inter frames carried +/// an in-band sequence header would be cut mid-GOP and refused by name below, +/// never silently misread; container storage keeps the sequence header in the +/// config record precisely so that does not happen. +/// +/// Chunks decode to their end, so the reorder window of the chunk the span +/// ends in always drains: hidden frames (`show_frame == 0`) are references +/// and arrive at the sink with `shown == false`, and the frames they hold +/// back in output order are the tail the sink still has to see. +/// +/// A refusal out of `ec-av1` -- a real-world stream hitting a shape the +/// decoder does not reconstruct -- fails the span in words, mid-film, the way +/// the hardware seat's errors do: named on stderr, the pictures decoded so +/// far stand, and no garbage is sent. The same sentinel ends a span that has +/// delivered everything asked of it without decoding the rest of its last +/// chunk. +fn run_av1( + demuxer: &mut Demuxer, + tx: &SyncSender, + start_frame: u32, + end_frame: u32, + render: &mut Render, + abort: &Abort, + speed: Speed, +) { + // Signed, for the same reason [`run`]'s is: the landing sync sample can + // sit inside what an mp4's edit list trims, i.e. before frame 0. + let mut index = demuxer.seek_to_sync_at_or_before(start_frame); + // Reusable plane buffers: one allocation each for the whole span, refilled + // per picture by [`narrow_av1`]. + let (mut y, mut u, mut v) = (Vec::new(), Vec::new(), Vec::new()); + let mut skipped = 0; + // Every way this span ends: abort, consumer gone, the requested range + // delivered, the demuxer dry, or a refusal out of the decoder. + let mut done = false; + let mut demux_dry = false; + // An access unit read past a chunk boundary, waiting to head the next one. + let mut pending: Option> = None; + while !done && !demux_dry { + if abort.hit() { + break; + } + // One chunk: the access units from a sync sample up to the next one. + let mut stream = pending.take().unwrap_or_default(); + while !demux_dry && pending.is_none() { + match demuxer.next_access_unit() { + Ok(Some(au)) => { + if !stream.is_empty() && leads_with_sequence_header(&au) { + pending = Some(au); + } else { + stream.extend_from_slice(&au); + } + } + Ok(None) => demux_dry = true, + Err(e) => { + eprintln!("demux error: {e}"); + return; + } + } + } + let ten_bit = demuxer.bit_depth() == 10; + let decode = decode_stream_with(&stream, |picture, _, shown| { + // Hidden frames are references: they take no display slot and + // are never sent, but they do hold the chunk's output order + // back, which is why the chunk decodes to its end. + if !shown { + return Ok(()); + } + let due = index; + index += 1; + if due < i64::from(start_frame) { + return Ok(()); + } + let due = due as u32; + // The three ends [`run`] reaches per picture, in its own shape: + // late for the playhead (one in [`LATE_RUN`] still goes through), + // redundant by construction at speed, or a conversion and a send. + let sent = if abort.late(due) { + if skipped < LATE_RUN { + skipped += 1; + false + } else { + skipped = 0; + send_av1(picture, due, ten_bit, render, tx, &mut y, &mut u, &mut v) + } + } else if skip_for_speed(speed, start_frame, due, end_frame) { + // Redundant by construction, not by lateness: no run limit + // needed (see `skip_for_speed`). + false + } else { + skipped = 0; + send_av1(picture, due, ten_bit, render, tx, &mut y, &mut u, &mut v) + }; + if sent { + done = true; // consumer went away + } + if done || i64::from(due) + 1 >= i64::from(end_frame) { + done = true; // the range is out, or nobody is left to take it + // Stops the decode inside the chunk: everything the span + // asked for has been sent, and the chunk's remaining coded + // frames are references for pictures nobody asked for. + return Err(Av1Error::Eof); + } + Ok(()) + }); + // `done` was set by the sink itself for the `Eof` it returns -- the + // sentinel, not a refusal. Any other `Err` is a refusal out of the + // decoder, named where the hardware seat's decode errors are named; + // the pictures decoded so far stand and the span ends. + if let Err(e) = decode { + if !done { + eprintln!("software AV1 decode failed at frame {index}: {e}"); + done = true; + } + } + } +} + /// Converts one decoded picture and queues it. `true` when the consumer went /// away, so the span stops rather than keeps decoding into a void. fn send_picture(pic: &VideoFrame, due: u32, render: &mut Render, tx: &SyncSender) -> bool { diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index f37dcbd..1ba9356 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -136,22 +136,30 @@ impl Codec { } /// Why a file can be refused outright. Two true answers, one per shape of - /// "no decoder here": every codec but H.264 and VP8 has no software - /// decoder at all (H.264's is the native `ec-h264`), so the refusal names - /// the plugin as the only way; VP8's software decoder *is* libvpx inside - /// the plugin, so "there is no software decoder" would be a lie the day - /// the plugin grew that arm -- the refusal keeps naming the plugin, - /// because that is still the thing to make present. Shared so playback - /// and export refuse in the same words. + /// "no decoder here": H.264 and AV1 have software seats of this project's + /// own (`ec-h264`, `ec-av1`) and are never refused for missing hardware on + /// the *playback* path; HEVC and VP9 have no software decoder at all, so + /// the refusal names the plugin as the only way. VP8's software decoder + /// *is* libvpx inside the plugin, so "there is no software decoder" would + /// be a lie the day the plugin grew that arm -- the refusal keeps naming + /// the plugin, because that is still the thing to make present. AV1's arm + /// is the one refusal left that can reach it: the software *export* + /// decoder is H.264-only (`export::SwDecoder`), so an AV1 source on a + /// machine with no plugin exports through nothing. Shared so playback and + /// export refuse in the same words. pub fn needs_plugin(self) -> String { match self { Self::Vp8 => { "VP8 needs the VA-API plugin (libengine_hw.so) — its decoder is libvpx, inside the plugin" .to_string() } + Self::Av1 => { + "AV1 needs the VA-API plugin (libengine_hw.so) — playback decodes it in software, the software export path does not" + .to_string() + } other => format!( "{name} needs the VA-API plugin (libengine_hw.so) — there is no software {name} decoder", - name = other.name() + name = other.name(), ), } } @@ -616,9 +624,10 @@ impl Demuxer { /// Bits per luma sample the stream is coded at: 8 for everything but an /// HEVC Main 10 or a 10-bit AV1 track, which decode into a P010 surface - /// rather than an NV12 one. Not part of [`VideoMeta`] because nothing above - /// the plugin has a use for it -- what comes out of the read-back is 8-bit - /// either way. + /// rather than an NV12 one. Not part of [`VideoMeta`] because the read-back + /// is 8-bit either way -- the two readers are the plugin's surface pool and + /// the software AV1 seat's narrowing ([`crate::decode::narrow_av1`]), and + /// both consume the depth and hand out bytes. pub fn bit_depth(&self) -> u8 { match self { Self::Mp4(d) => d.bit_depth, diff --git a/crates/engine/tests/av1.rs b/crates/engine/tests/av1.rs index cc2b445..44d0054 100644 --- a/crates/engine/tests/av1.rs +++ b/crates/engine/tests/av1.rs @@ -2,9 +2,10 @@ //! arrives in a container of its own -- `mp4 0.14` knows no `av01` sample entry //! at all, so AV1 comes in as Matroska and the demuxer walks the EBML itself. //! -//! The container and refusal checks need nothing installed. The decode and -//! export twins need a built `libengine_hw.so` and a VA-API driver with an AV1 -//! decode entrypoint (`vainfo | grep AV1`), so they are `#[ignore]`d: +//! Decoding has two seats: the project's own `ec-av1` in this process, and the +//! VA-API plugin's (`vainfo | grep AV1`) in front of it. The software seat needs +//! nothing installed, so its witnesses run unignored (`VE_SW` pins it); the +//! hardware twins need a built `libengine_hw.so` and are `#[ignore]`d: //! //! ```text //! cargo build -p engine -p engine-hw --release @@ -12,8 +13,8 @@ //! cargo test -p engine --release --test av1 -- --include-ignored --nocapture --test-threads=1 //! ``` //! -//! `VE_SW` is process-wide, hence `--test-threads=1`: the refusal test sets it -//! and puts it back so the hardware twins below really are hardware. +//! `VE_SW` is process-wide, hence `--test-threads=1`: the software-seat tests +//! set it and put it back so the hardware twins below really are hardware. use std::path::PathBuf; use std::time::{Duration, Instant}; @@ -142,44 +143,250 @@ fn every_block_comes_back_and_keyframes_carry_the_sequence_header() { assert_eq!((after[0] >> 3) & 0xF, 1, "{}", after[0]); } -/// There is no software AV1 decoder, so the software path must refuse by name -/// rather than feed AV1 bytes to `ec-h264` -- and it must refuse where a -/// caller can still show it, i.e. out of `open`, not from inside the worker. +/// The seat this file used to refuse by name now exists: `ec-av1`, in this +/// process, behind the same `VE_SW` pin the H.264 seat takes. A linear open +/// delivers every frame the container indexes, labelled `0..n` in display +/// order -- the contract the transport reads and the one the hardware seat +/// always kept. #[test] -fn the_software_path_refuses_av1_by_name() { - // SAFETY: the suite is documented to run with --test-threads=1. +fn the_software_seat_decodes_every_frame() { + // SAFETY: the suite is documented to run with --test-threads=1. The pin + // stays up until the frames are drained: it is read on the worker thread + // when the span opens, not only at the door here. unsafe { std::env::set_var("VE_SW", "1") }; - let refused = - DecodeSession::open(asset("test_av1.mkv")).expect_err("software must not accept AV1"); - let refused = refused.to_string(); - // Restored immediately: the hardware tests in this binary share the process. + let (meta, rx) = DecodeSession::open(asset("test_av1.mkv")).expect("software AV1 open"); + assert_eq!(meta.frame_count, FRAMES); + let indices: Vec = rx.into_iter().map(|f| f.index).collect(); unsafe { std::env::remove_var("VE_SW") }; + assert_eq!(indices, (0..FRAMES).collect::>(), "frames must arrive 0..n in display order"); +} - assert!(refused.contains("AV1"), "{refused}"); - assert!(refused.contains("plugin"), "{refused}"); +/// ...and the 10-bit twin, whose samples arrive as `u16` in `0..=1023` and +/// narrow to the same 8-bit planes the plugin's P010 read-back produces. +#[test] +fn the_software_seat_decodes_ten_bit_av1() { + // SAFETY: the suite is documented to run with --test-threads=1; held + // through the drain, as above. + unsafe { std::env::set_var("VE_SW", "1") }; + let (meta, rx) = DecodeSession::open(asset("test_av1_10.mkv")).expect("software AV1 open"); + assert_eq!(meta.frame_count, FRAMES); + let count = rx.into_iter().count(); + unsafe { std::env::remove_var("VE_SW") }; + assert_eq!(count, FRAMES as usize, "every 10-bit frame came out"); +} + +/// Seeking may only change *when* a picture arrives, never the picture: a seek +/// onto the software seat lands on the very bytes a linear decode of the same +/// index delivered, on either side of and away from a keyframe. The promise +/// `hw_decode::seek_matches_linear_every_container` makes of the hardware +/// seat, made here of the software one -- which is why this runs unignored. +#[test] +fn seek_lands_on_the_picture_a_linear_software_decode_delivered() { + // SAFETY: the suite is documented to run with --test-threads=1. + unsafe { std::env::set_var("VE_SW", "1") }; + let path = asset("test_av1.mkv"); + let (meta, rx) = DecodeSession::open(&path).expect("software open"); + let mut targets = vec![0, 1, 29, 30, 31, 45, meta.frame_count - 1]; + targets.retain(|&t| t < meta.frame_count); + targets.sort_unstable(); + targets.dedup(); + let linear: Vec<(u32, Vec)> = rx + .into_iter() + .filter(|f| targets.contains(&f.index)) + .map(|f| (f.index, f.bgra)) + .collect(); + assert_eq!( + linear.iter().map(|(i, _)| *i).collect::>(), + targets, + "linear decode never delivered every target" + ); + for (target, want) in linear { + let (_, rx, _cancel) = DecodeSession::open_at(&path, target).expect("open_at"); + let seeked = rx + .into_iter() + .next() + .unwrap_or_else(|| panic!("no frame after seek to {target}")); + assert_eq!(seeked.index, target, "first frame after seek is not the target"); + assert!( + seeked.bgra == want, + "seek to {target} handed back a different picture than a linear decode of {target}" + ); + } + unsafe { std::env::remove_var("VE_SW") }; } /// A timeline is *not* refused a source coded differently -- every clip opens -/// its own decoder. What survives is the reason the codec gate existed: on a -/// machine that cannot decode AV1 the file is refused at the door, by the -/// decoder's own name, rather than becoming a clip of black frames. +/// its own decoder, and since the `ec-av1` seat that is true with no plugin +/// and no driver in the room: the no-plugin machine, forced, takes the AV1 +/// source beside its H.264 one. #[test] -fn a_timeline_takes_the_other_codec_or_names_the_missing_decoder() { +fn a_timeline_takes_av1_on_a_machine_with_no_plugin() { let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4"); - // The no-plugin machine, forced. - // SAFETY: the suite is documented to run with --test-threads=1. + // SAFETY: the suite is documented to run with --test-threads=1. The pin + // stays up until the import has been through the seat's door (and the + // worker it spawned has opened its span on it), then comes back down. unsafe { std::env::set_var("VE_SW", "1") }; - let refused = session + let imported = session .import(&asset("test_av1.mkv")) - .expect_err("no AV1 decoder means no AV1 clip") - .to_string(); + .is_ok(); + assert!(imported, "the software seat is a seat: the timeline takes AV1"); + assert_eq!(session.sources().len(), 2, "both sources stand"); unsafe { std::env::remove_var("VE_SW") }; - assert_eq!(refused, Codec::Av1.needs_plugin()); +} + +// --- the refusal witness --------------------------------------------------- +// +// The minimal EBML this file's refusal fixture is written with -- the same +// builders `mkv_encodings.rs` uses, kept local because test binaries do not +// share code. Every size goes out in the 8-byte long form, legal everywhere +// and arithmetic-free. + +const SEGMENT: u32 = 0x1853_8067; +const INFO: u32 = 0x1549_A966; +const TIMESTAMP_SCALE: u32 = 0x2AD7B1; +const TRACKS: u32 = 0x1654_AE6B; +const TRACK_ENTRY: u32 = 0xAE; +const TRACK_NUMBER: u32 = 0xD7; +const TRACK_TYPE: u32 = 0x83; +const CODEC_ID: u32 = 0x86; +const CODEC_PRIVATE: u32 = 0x63A2; +const DEFAULT_DURATION: u32 = 0x23E383; +const VIDEO: u32 = 0xE0; +const PIXEL_WIDTH: u32 = 0xB0; +const PIXEL_HEIGHT: u32 = 0xBA; +const CLUSTER: u32 = 0x1F43_B675; +const CLUSTER_TIMESTAMP: u32 = 0xE7; +const SIMPLE_BLOCK: u32 = 0xA3; + +fn el(id: u32, body: &[u8]) -> Vec { + let mut out: Vec = id.to_be_bytes()[(id.leading_zeros() / 8) as usize..].to_vec(); + out.push(0x01); + out.extend_from_slice(&(body.len() as u64).to_be_bytes()[1..]); + out.extend_from_slice(body); + out +} + +fn uint(id: u32, value: u64) -> Vec { + el(id, &value.to_be_bytes()) +} + +/// A `SimpleBlock` of `track`, `rel` ticks into its cluster; `flags` carries +/// the keyframe bit (0x80). +fn block(track: u8, rel: i16, flags: u8, body: &[u8]) -> Vec { + let mut b = vec![0x80 | track]; + b.extend_from_slice(&rel.to_be_bytes()); + b.push(flags); + b.extend_from_slice(body); + el(SIMPLE_BLOCK, &b) +} + +/// One OBU's total length inside a low-overhead stream: the header byte (plus +/// its extension byte, which this fixture format never writes) and the +/// leb128 size that `obu_has_size_field` promises. +fn obu_len(stream: &[u8]) -> usize { + assert_eq!(stream[0] & 0x2, 2, "obu_has_size_field: low-overhead format"); + let mut len = 1; + let mut size: usize = 0; + loop { + let byte = stream[len]; + len += 1; + size = size << 7 | usize::from(byte & 0x7F); + if byte & 0x80 == 0 { + break; + } + } + len + size +} + +/// A stream whose GOP structure is broken in a way the container cannot see: +/// the second keyframe-flagged block carries an *inter* frame's bytes, as a +/// remux that trusted the wrong key index would write one. The demuxer opens +/// it, injects the sequence header ahead of it, and `ec-av1` refuses it by +/// name -- an inter frame with no key frame behind it finds no saved CDF state +/// to resume from, one of the live refusals its inventory pins -- and the seat +/// fails the span in words instead of a panic or a garbage picture: the frames +/// decoded so far stand, then the channel closes. +#[test] +fn a_broken_gop_is_refused_in_words_and_never_a_panic() { + // The pieces, off the real fixture: the sequence header OBU the demuxer + // injects (the `av1C` payload) and a real inter frame's block bytes. + let (_, mut demuxer) = Demuxer::open(&asset("test_av1.mkv")).expect("open test_av1.mkv"); + let key_au = demuxer.next_access_unit().expect("read").expect("key au"); + let seq_len = obu_len(&key_au); + let seq_header = &key_au[..seq_len]; + let key_body = &key_au[seq_len..]; + // The very next access unit is frame 1, a real inter frame: no injection + // ahead of a non-sync sample, so its bytes are the block verbatim. + let inter_body = demuxer.next_access_unit().expect("read").expect("inter au"); + + // The words first, at the decoder's own door: the crafted chunk is + // refused, and the refusal is a sentence, not a panic. + let mut broken = seq_header.to_vec(); + broken.extend_from_slice(&inter_body); + let refused = ec_av1::stream::decode_stream(&broken) + .expect_err("an inter frame with no key frame behind it is refused"); assert!( - !refused.contains("H.264"), - "the timeline's own codec is no longer a reason: {refused}" + refused.to_string().contains("no saved CDF state"), + "the refusal names its reason: {refused}" + ); + + // The same broken stream as a file, through the seat: open succeeds (the + // container is valid), the first GOP decodes, the second chunk refuses, + // and the span ends cleanly with exactly the pictures decoded so far. + let av1c = [0x81u8, 0x00, 0x0C, 0x00]; + let mut private = av1c.to_vec(); + private.extend_from_slice(seq_header); + let track = el( + TRACK_ENTRY, + &[ + uint(TRACK_NUMBER, 1), + uint(TRACK_TYPE, 1), + el(CODEC_ID, b"V_AV1"), + el(CODEC_PRIVATE, &private), + uint(DEFAULT_DURATION, 33_333_333), + el(VIDEO, &[uint(PIXEL_WIDTH, 1280), uint(PIXEL_HEIGHT, 720)].concat()), + ] + .concat(), + ); + let cluster = el( + CLUSTER, + &[ + uint(CLUSTER_TIMESTAMP, 0), + block(1, 0, 0x80, key_body), + block(1, 33, 0x80, &inter_body), + ] + .concat(), ); - assert_eq!(session.sources().len(), 1, "a refusal left no row"); + let segment = [ + el(INFO, &uint(TIMESTAMP_SCALE, 1_000_000)), + el(TRACKS, &track), + cluster, + ] + .concat(); + let file = [ + el(0x1A45_DFA3, &[]), + el(SEGMENT, &segment), + ] + .concat(); + let scratch = Scratch::file("broken_gop_av1", "mkv"); + std::fs::write(&scratch, &file).expect("write fixture"); + + let (meta, mut opened) = Demuxer::open(&scratch).expect("the container itself is valid"); + assert_eq!(meta.codec, Codec::Av1); + assert_eq!(meta.frame_count, 2); + // Both blocks are key-flagged, so both lead with the injected sequence + // header -- which is what makes the second one a chunk boundary, and the + // refusal the decoder's own answer to what it finds there. + let first = opened.next_access_unit().expect("read").expect("au"); + assert_eq!((first[0] >> 3) & 0xF, 1); + + // SAFETY: the suite is documented to run with --test-threads=1; the pin + // held through the drain, as in every seat test above. + unsafe { std::env::set_var("VE_SW", "1") }; + let (_, rx) = DecodeSession::open(&scratch).expect("open succeeds; the container is fine"); + let frames: Vec = rx.into_iter().map(|f| f.index).collect(); + unsafe { std::env::remove_var("VE_SW") }; + assert_eq!(frames, vec![0], "the first GOP stands, the broken one refuses"); } /// The end-to-end user path: opening the file yields pictures, all of them, diff --git a/crates/engine/tests/hw_decode.rs b/crates/engine/tests/hw_decode.rs index a9e673b..139b9c3 100644 --- a/crates/engine/tests/hw_decode.rs +++ b/crates/engine/tests/hw_decode.rs @@ -201,9 +201,9 @@ fn seek_matches_linear() { #[test] #[ignore = "needs libengine_hw.so and a VA-API driver"] fn seek_matches_linear_every_container() { - // The hardware path for all of these: there is no software HEVC or AV1 - // decoder to compare against. SAFETY: --test-threads=1. - unsafe { std::env::remove_var("VE_SW") }; + // The hardware path for these, including AV1's fixture: the point is the + // seek against the same seat a linear decode ran on, which the tests + // below pin for the software seat. for name in [ "test_baseline.mp4", "test_high.mp4", @@ -405,3 +405,71 @@ fn hardware_matches_software_on_frame_30() { eprintln!("frame 30 differing bytes: {diff} / {}", hw.len()); assert_eq!(diff, 0, "hardware and software decode disagree"); } + +/// The AV1 twin of [`hardware_matches_software_on_frame_30`]: the plugin's +/// VA-API decoder against the project's own `ec-av1`, whole file, byte for +/// byte -- 8-bit AV1 decode is bit-exact by the same conformance argument the +/// H.264 twin makes, and a mismatch means a deviation in one of the two +/// decoders, reported rather than swallowed. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"] +fn av1_hardware_matches_software_on_every_frame() { + const NAME: &str = "test_av1.mkv"; + let (hw_count, hw_frame_30) = decode_all_hw(NAME); + + // Pin the comparison side to software ourselves: without this, running the + // suite without VE_SW=1 would compare hardware against hardware and pass + // vacuously. SAFETY: the suite is documented to run with --test-threads=1. + unsafe { std::env::set_var("VE_SW", "1") }; + let path = asset(NAME); + let start = Instant::now(); + let (meta, rx) = DecodeSession::open(&path).expect("software open"); + let mut sw_count = 0usize; + let mut sw_frame_30 = Vec::new(); + for frame in rx { + if frame.index == 30 { + sw_frame_30 = frame.bgra; + } + sw_count += 1; + } + let sw_elapsed = start.elapsed(); + unsafe { std::env::remove_var("VE_SW") }; + eprintln!("{NAME}: hardware {hw_count} frames, software {sw_count} frames in {sw_elapsed:?}"); + assert_eq!(sw_count, hw_count, "frame count"); + assert_eq!(sw_count, usize::try_from(meta.frame_count).expect("count")); + assert_eq!(hw_frame_30.len(), sw_frame_30.len(), "frame size"); + let diff = hw_frame_30.iter().zip(&sw_frame_30).filter(|(a, b)| a != b).count(); + eprintln!("frame 30 differing bytes: {diff} / {}", sw_frame_30.len()); + assert_eq!(diff, 0, "hardware and software AV1 decode disagree"); +} + +/// The 10-bit twin: the plugin reads a P010 surface back as the high byte of +/// each pair; `ec-av1` hands `u16` planes the seat downshifts by two. Same +/// truncation, same picture -- or one of the two seats is wrong. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver with 10-bit AV1 decode"] +fn av1_ten_bit_hardware_matches_software_on_every_frame() { + const NAME: &str = "test_av1_10.mkv"; + let (hw_count, hw_frame_30) = decode_all_hw(NAME); + // SAFETY: the suite is documented to run with --test-threads=1. + unsafe { std::env::set_var("VE_SW", "1") }; + let path = asset(NAME); + let start = Instant::now(); + let (_, rx) = DecodeSession::open(&path).expect("software open"); + let mut sw_count = 0usize; + let mut sw_frame_30 = Vec::new(); + for frame in rx { + if frame.index == 30 { + sw_frame_30 = frame.bgra; + } + sw_count += 1; + } + let sw_elapsed = start.elapsed(); + unsafe { std::env::remove_var("VE_SW") }; + eprintln!("{NAME}: hardware {hw_count} frames, software {sw_count} frames in {sw_elapsed:?}"); + assert_eq!(sw_count, hw_count, "frame count"); + assert_eq!(hw_frame_30.len(), sw_frame_30.len(), "frame size"); + let diff = hw_frame_30.iter().zip(&sw_frame_30).filter(|(a, b)| a != b).count(); + eprintln!("frame 30 differing bytes: {diff} / {}", sw_frame_30.len()); + assert_eq!(diff, 0, "hardware and software 10-bit AV1 decode disagree"); +}