diff --git a/crates/ec-av1/src/stream/mod.rs b/crates/ec-av1/src/stream/mod.rs index 477e99db..9e08bf97 100644 --- a/crates/ec-av1/src/stream/mod.rs +++ b/crates/ec-av1/src/stream/mod.rs @@ -856,43 +856,13 @@ fn collect_one( reorder.drain(sink) } -/// [`decode_stream_with`] with an explicit worker count (lane-thread2). -/// -/// `threads == 1` is the serial decoder. Above that, frames that no later -/// frame can reference -- a shown, non-key frame whose `refresh_frame_flags` -/// is 0, i.e. a leaf of the reference graph -- are decoded on worker threads -/// while the main thread keeps parsing headers and decoding the frames that -/// DO feed the reference banks; `sink` still sees every picture in coded -/// order. Each worker owns a fresh [`crate::decode::FrameCtx`] and a snapshot -/// of the banks taken before dispatch, so no decode state is shared. -/// -/// The per-decode counters this crate's gates read are thread-local, so at -/// `threads > 1` a leaf frame's counts land on the worker and are invisible -/// to the caller; that is why the default is 1. -/// -/// # Errors -/// As [`decode_stream_with`]; a worker's error aborts the stream. -pub fn decode_stream_with_threads( - data: &[u8], +/// A persistent AV1 stream decoder: feed it temporal units in decode order. +pub struct StreamDecoder { threads: usize, - mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>, -) -> Result<()> { - // lane-pool1: this replaced a `std::thread::scope` -- frame workers now - // come from a persistent pool (one per submitting thread, workers reused - // across frames, so their `thread_local!` decode scratch survives the - // frame). `jobs` is declared here and dropped at the end of the function, - // including on `?`, so no job outlives the data it borrows. - let jobs = crate::par::Batch::new("ec-av1-frame"); - // lane-av1recon: at more than one decode thread the recon wavefront and - // the filter bands default on (an explicit env value still wins). - let _split = crate::par::DecodeSplit::install(threads); - // lane-thread1: this stream's per-frame decode state (was 38 thread_local - // statics in decode.rs) -- one object, threaded down the decode call graph. - let fctx = &crate::decode::FrameCtx::new(); - let final_dump = final_dump_prefix(); - let mut parser = Av1Parser::new(); - let mut pictures_shown: usize = 0; - let mut pictures_decoded: usize = 0; + final_dump: Option, + parser: Av1Parser, + pictures_shown: usize, + pictures_decoded: usize, // Spec 7.20/7.4: each of the 8 reference slots remembers the picture a // previous frame's `refresh_frame_flags` stored into it, exactly like the // CDF slots below -- `LAST_FRAME` names a slot via `ref_frame_idx[0]`, @@ -907,55 +877,49 @@ pub fn decode_stream_with_threads( // what made it look like a rounding bug rather than a wrong reference. // lane-pool1: shared, not owned -- a frame refreshing k slots used to copy // its whole picture k times, and its output a (k+1)-th time. - let mut ref_slots: [Option>; NUM_REF_FRAMES] = - std::array::from_fn(|_| None); + ref_slots: [Option>; NUM_REF_FRAMES], // lane-av1tmvp: each of the 8 reference slots' own saved temporal motion // field (spec 7.9's per-frame `MotionFieldMvs` storage, libaom // `cur_frame->mvs`) plus the `OrderHint` the picture in that slot was // decoded with -- `Picture` itself carries neither, so both ride // alongside `ref_slots` on the exact same `refresh_frame_flags` update. - let mut motion_field_slots: [Option; NUM_REF_FRAMES] = - std::array::from_fn(|_| None); - let mut order_hint_slots: [u32; NUM_REF_FRAMES] = [0; NUM_REF_FRAMES]; + motion_field_slots: [Option; NUM_REF_FRAMES], + order_hint_slots: [u32; NUM_REF_FRAMES], // Spec 7.20/7.4: each of the 8 reference slots remembers the CDF state a // previous frame's `refresh_frame_flags` stored into it -- the frame's // own end-of-tile adapted table, or (when the frame set // `disable_frame_end_update_cdf`) the table it started from, unchanged. - let mut cdf_slots: [Option; NUM_REF_FRAMES] = std::array::from_fn(|_| None); + cdf_slots: [Option; NUM_REF_FRAMES], // lane-seg, spec 7.20's `SavedSegmentIds`: each reference slot also // remembers the segment map the frame stored there decoded, which is what // a later frame's `primary_ref_frame` reads back as `PrevSegmentIds` // (spec `load_previous_segment_ids`) for temporal segment-id prediction // and for a `segmentation_update_map == 0` frame's inherited map. - let mut seg_map_slots: [Option>; NUM_REF_FRAMES] = std::array::from_fn(|_| None); - + seg_map_slots: [Option>; NUM_REF_FRAMES], // lane-thread2: output plumbing (inert at `threads == 1`, where nothing // is ever dispatched and `reorder` emits each picture the moment it is // pushed). - let mut emit_seq = 0usize; - let mut reorder = Reorder::default(); + emit_seq: usize, + reorder: Reorder, // lane-thread3: frame decodes and `show_existing_frame` outputs are // bounded separately -- an output job is a promise wait plus a memcpy, so // letting it eat a decode's budget just idles a core (measured: sharing // one bound cost 4K 18.7 s at 244% CPU against 17.7 s at 287%). - let mut in_flight_decodes = 0usize; - let mut in_flight_shows = 0usize; - let in_flight_cap = threads + 2; - let (tx, rx) = std::sync::mpsc::channel::(); + in_flight_decodes: usize, + in_flight_shows: usize, + tx: std::sync::mpsc::Sender, + rx: std::sync::mpsc::Receiver, // lane-thread3: at `threads > 1` THIS is the reference bank -- one // [`SlotPromise`] per DPB slot, ready for a slot the parsing thread filled // itself and pending for one an in-flight frame will fill. The owned // arrays above are then untouched (and the single-threaded path never // creates a promise: it stays exactly the decoder it was, which is what // keeps every counter-reading gate meaningful). - let mut slot_promises: [Option>; NUM_REF_FRAMES] = - std::array::from_fn(|_| None); + slot_promises: [Option>; NUM_REF_FRAMES], // lane-timeline: which decoded frame installed each slot's promise, so // the timeline records a dependency EDGE (frame -> producing frame) and // not just a slot number. `usize::MAX` = nobody yet. - let mut slot_owner = [usize::MAX; NUM_REF_FRAMES]; - - let mut pos = 0usize; + slot_owner: [usize; NUM_REF_FRAMES], // A frame whose tiles are split across several `OBU_TILE_GROUP`s (spec // 5.11.1, aomenc's `--num-tile-groups`) sends a standalone // `OBU_FRAME_HEADER` first, with `show_existing_frame == false` and no @@ -963,67 +927,371 @@ pub fn decode_stream_with_threads( // only ever folds ONE tile group into the header's own OBU. Stash the // header here and accumulate tiles from each `OBU_TILE_GROUP` that // follows until every tile of the frame has arrived. - let mut pending_header: Option> = None; - let mut pending_tiles: Vec = Vec::new(); - while pos < data.len() { - let obu = parser.parse_obu(&data[pos..])?; - let obu_offset = pos; - pos += obu.total_size; - - if let ObuKind::FrameHeader(header) = &obu.kind { - if !header.show_existing_frame { - // Before this fix, this branch fired unconditionally for - // EVERY `FrameHeader` OBU (including this one), so a - // standalone header always fell into the `show_existing_frame` - // slot lookup below and misreported "a show_existing_frame - // header naming an empty reference slot" for a frame that was - // never a show_existing_frame header at all. - pending_header = Some(header.clone()); - pending_tiles = Vec::new(); - continue; + pending_header: Option>, + pending_tiles: Vec, + // lane-thread1: this stream's per-frame decode state (was 38 thread_local + // statics in decode.rs) -- one object, threaded down the decode call graph. + fctx: crate::decode::FrameCtx, +} +impl StreamDecoder { + /// A decoder with `threads` frame workers (see [`decode_stream_with_threads`]). + pub fn new(threads: usize) -> Self { + let (tx, rx) = std::sync::mpsc::channel::(); + Self { + threads, + final_dump: final_dump_prefix(), + parser: Av1Parser::new(), + pictures_shown: 0, + pictures_decoded: 0, + ref_slots: std::array::from_fn(|_| None), + motion_field_slots: std::array::from_fn(|_| None), + order_hint_slots: [0; NUM_REF_FRAMES], + cdf_slots: std::array::from_fn(|_| None), + seg_map_slots: std::array::from_fn(|_| None), + emit_seq: 0, + reorder: Reorder::default(), + in_flight_decodes: 0, + in_flight_shows: 0, + tx, + rx, + slot_promises: std::array::from_fn(|_| None), + slot_owner: [usize::MAX; NUM_REF_FRAMES], + pending_header: None, + pending_tiles: Vec::new(), + fctx: crate::decode::FrameCtx::new(), + } + } + + /// Decode one temporal unit and return its shown pictures. + /// + /// # Errors + /// As [`decode_stream`]. After an error, start a new decoder at a key frame. + pub fn decode_temporal_unit(&mut self, data: &[u8]) -> Result> { + let mut pictures = Vec::new(); + self.decode(data, |picture, _decode_idx, shown| { + if shown { + pictures.push(picture.clone()); } - // `show_existing_frame` (spec 7.21/5.9.2): no tile payload, this - // OBU only names a DPB slot to output again -- the coded-frame - // count and the shown-picture count are different things (a - // hidden altref's own `Frame` OBU below is never pushed to - // `pictures` on its own; it is only pushed here, later, when a - // `show_existing_frame` header names its slot). Before r15 this - // arm didn't exist at all: every `ObuKind::Frame` was pushed - // unconditionally regardless of `show_frame`, so a hidden altref - // was emitted (wrongly, in decode order) and its real - // `show_existing_frame` output was silently dropped. - let slot = header.frame_to_show_map_idx as usize; - // lane-hdrlossless: libaom errors on the same stream - // (`decodeframe.c:4651`: `if (frame_to_show == NULL) - // aom_internal_error(... AOM_CODEC_UNSUP_BITSTREAM, "Buffer does - // not contain a decoded frame")`) -- a spec-conformant guard. - let empty_slot = || { - Error::unsupported( - "AV1 decode_stream", - "a show_existing_frame header naming an empty reference slot", - ) - }; - if threads > 1 { - // lane-thread3: the named slot may still be decoding on a - // worker, and the copy into the slots this header refreshes - // is then just the promise -- no value needed. The OUTPUT - // does need the picture, so it is produced on a worker too: - // waiting for it here would stall the parsing thread, and a - // stalled parser dispatches nothing (measured before this - // arm existed: 7.9 s of an 8.8 s 1080p decode, 18.9 s of - // 23.3 s at 4K, spent in this one wait). The wait still - // points at an earlier coded frame, so the argument in - // [`SlotPromise`] is unchanged. - let promise = slot_promises[slot].clone().ok_or_else(empty_slot)?; - for i in 0..NUM_REF_FRAMES { - if header.refresh_frame_flags & (1 << i) != 0 { - slot_promises[i] = Some(promise.clone()); - slot_owner[i] = slot_owner[slot]; + Ok(()) + })?; + Ok(pictures) + } + + /// Decode whole frames from `data` (one or more temporal units), handing + /// every picture to `sink` as [`decode_stream_with`] does, before returning. + /// + /// # Errors + /// As [`decode_stream_with`]. + pub fn decode( + &mut self, + data: &[u8], + mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>, + ) -> Result<()> { + let mut pictures_shown = self.pictures_shown; + let mut pictures_decoded = self.pictures_decoded; + let mut emit_seq = self.emit_seq; + let mut in_flight_decodes = self.in_flight_decodes; + let mut in_flight_shows = self.in_flight_shows; + let mut order_hint_slots = self.order_hint_slots; + let mut slot_owner = self.slot_owner; + let mut reorder = std::mem::take(&mut self.reorder); + let mut pending_header = self.pending_header.take(); + let mut pending_tiles = std::mem::take(&mut self.pending_tiles); + let threads = self.threads; + let StreamDecoder { + final_dump, + parser, + ref_slots, + motion_field_slots, + cdf_slots, + seg_map_slots, + tx, + rx, + slot_promises, + fctx, + .. + } = self; + // lane-pool1: this replaced a `std::thread::scope` -- frame workers now + // come from a persistent pool (one per submitting thread, workers reused + // across frames, so their `thread_local!` decode scratch survives the + // frame). `jobs` is declared here and dropped at the end of the function, + // including on `?`, so no job outlives the data it borrows. + let jobs = crate::par::Batch::new("ec-av1-frame"); + // lane-av1recon: at more than one decode thread the recon wavefront and + // the filter bands default on (an explicit env value still wins). + let _split = crate::par::DecodeSplit::install(threads); + let in_flight_cap = threads + 2; + let mut pos = 0usize; + while pos < data.len() { + let obu = parser.parse_obu(&data[pos..])?; + let obu_offset = pos; + pos += obu.total_size; + + if let ObuKind::FrameHeader(header) = &obu.kind { + if !header.show_existing_frame { + // Before this fix, this branch fired unconditionally for + // EVERY `FrameHeader` OBU (including this one), so a + // standalone header always fell into the `show_existing_frame` + // slot lookup below and misreported "a show_existing_frame + // header naming an empty reference slot" for a frame that was + // never a show_existing_frame header at all. + pending_header = Some(header.clone()); + pending_tiles = Vec::new(); + continue; + } + // `show_existing_frame` (spec 7.21/5.9.2): no tile payload, this + // OBU only names a DPB slot to output again -- the coded-frame + // count and the shown-picture count are different things (a + // hidden altref's own `Frame` OBU below is never pushed to + // `pictures` on its own; it is only pushed here, later, when a + // `show_existing_frame` header names its slot). Before r15 this + // arm didn't exist at all: every `ObuKind::Frame` was pushed + // unconditionally regardless of `show_frame`, so a hidden altref + // was emitted (wrongly, in decode order) and its real + // `show_existing_frame` output was silently dropped. + let slot = header.frame_to_show_map_idx as usize; + // lane-hdrlossless: libaom errors on the same stream + // (`decodeframe.c:4651`: `if (frame_to_show == NULL) + // aom_internal_error(... AOM_CODEC_UNSUP_BITSTREAM, "Buffer does + // not contain a decoded frame")`) -- a spec-conformant guard. + let empty_slot = || { + Error::unsupported( + "AV1 decode_stream", + "a show_existing_frame header naming an empty reference slot", + ) + }; + if threads > 1 { + // lane-thread3: the named slot may still be decoding on a + // worker, and the copy into the slots this header refreshes + // is then just the promise -- no value needed. The OUTPUT + // does need the picture, so it is produced on a worker too: + // waiting for it here would stall the parsing thread, and a + // stalled parser dispatches nothing (measured before this + // arm existed: 7.9 s of an 8.8 s 1080p decode, 18.9 s of + // 23.3 s at 4K, spent in this one wait). The wait still + // points at an earlier coded frame, so the argument in + // [`SlotPromise`] is unchanged. + let promise = slot_promises[slot].clone().ok_or_else(empty_slot)?; + for i in 0..NUM_REF_FRAMES { + if header.refresh_frame_flags & (1 << i) != 0 { + slot_promises[i] = Some(promise.clone()); + slot_owner[i] = slot_owner[slot]; + } + } + let cap_t0 = crate::timeline::now(); + let capped = in_flight_shows >= in_flight_cap; + while in_flight_shows >= in_flight_cap { + collect_one( + &rx, + &mut in_flight_decodes, + &mut in_flight_shows, + &mut reorder, + &mut sink, + )?; + } + if capped { + crate::timeline::cap_wait("show", cap_t0, crate::timeline::now()); + } + let (job_seq, decode_idx) = (emit_seq, pictures_decoded); + emit_seq += 1; + pictures_shown += 1; + let grain = header.film_grain; + let seq = SeqFlags::read(&parser); + let tx = tx.clone(); + jobs.submit(move || { + let mut answer = JobAnswer::new(tx, job_seq, false, None, None); + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let value = promise.wait()?; + let shown_picture = value.pixels.wait()?; + let output = if grain.apply_grain && !no_grain() { + std::sync::Arc::new(crate::film_grain::apply_grain( + &shown_picture, + &grain, + seq.mc_identity, + u32::from(seq.bit_depth), + &crate::decode::FrameCtx::new(), + )) + } else { + std::sync::Arc::clone(&shown_picture) + }; + Ok((output, decode_idx, true)) + })) + .unwrap_or_else(|_| { + Err(Error::corrupt( + "AV1 decode_stream: a worker thread panicked on a show_existing_frame output", + )) + }); + answer.send(reply); + })); + }); + in_flight_shows += 1; + while let Ok((seq, decode_job, result)) = rx.try_recv() { + if decode_job { + in_flight_decodes -= 1; + } else { + in_flight_shows -= 1; + } + let (picture, decode_idx, shown) = result?; + reorder.push(seq, picture, decode_idx, shown); + reorder.drain(&mut sink)?; } + continue; } + let picture = { + let picture = ref_slots[slot].clone().ok_or_else(empty_slot)?; + for i in 0..NUM_REF_FRAMES { + if header.refresh_frame_flags & (1 << i) != 0 { + cdf_slots[i] = cdf_slots[slot].clone(); + ref_slots[i] = Some(picture.clone()); + motion_field_slots[i] = motion_field_slots[slot].clone(); + seg_map_slots[i] = seg_map_slots[slot].clone(); + order_hint_slots[i] = order_hint_slots[slot]; + } + } + picture + }; + let output = if header.film_grain.apply_grain && !no_grain() { + // lane-hbd10 r1: grain synthesis is bit-depth generic + // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3). + let bit_depth = parser + .sequence_header() + .map_or(8, |seq| seq.color_config.bit_depth); + let mc_identity = parser + .sequence_header() + .is_some_and(|seq| seq.color_config.matrix_coefficients == 0); + std::sync::Arc::new(crate::film_grain::apply_grain( + &picture, + &header.film_grain, + mc_identity, + bit_depth as u32, + fctx, + )) + } else { + picture + }; + reorder.push(emit_seq, output, pictures_decoded, true); + emit_seq += 1; + reorder.drain(&mut sink)?; + pictures_shown += 1; + continue; + } + // `tiles_base_offset` is added to every `Tile::offset` below to reach + // an absolute position in `data`. `OBU_FRAME`'s tiles are relative to + // this OBU's own `obu_offset`; an accumulated run of `OBU_TILE_GROUP`s + // may span several different OBUs (each at a different offset in + // `data`), so those tiles are normalised to an absolute offset the + // moment they are appended to `pending_tiles`, and `tiles_base_offset` + // is 0 for that case. + let (header, tiles, tiles_base_offset): (Box, Vec, usize) = + match obu.kind { + ObuKind::Frame(header, tiles) => (header, tiles, obu_offset), + ObuKind::TileGroup(new_tiles) => { + let header = pending_header.clone().ok_or_else(|| { + Error::corrupt( + "AV1 decode_stream: a tile group OBU with no preceding frame header", + ) + })?; + let expected = header.tile_info.cols * header.tile_info.rows; + pending_tiles.extend(new_tiles.into_iter().map(|mut t| { + t.offset += obu_offset; + t + })); + if (pending_tiles.len() as u32) < expected { + continue; + } + pending_header = None; + (header, std::mem::take(&mut pending_tiles), 0) + } + _ => continue, + }; + // Every tile is decoded below through `tile_bufs`; this only rejects a + // frame OBU that carries no tile group at all. + if tiles.is_empty() { + return Err(Error::unsupported( + "AV1 decode_stream", + "a frame OBU with no tile group", + )); + } + // `read_cdef` (spec `decodeframe.c`, called at the first non-skip + // block of each 64x64) only reads a literal `cdef_idx` when + // `cdef_bits > 0`; at `cdef_bits == 0` there is nothing to read (a + // true no-op). lane-realworld r1: the per-64x64 `cdef_idx` literal is + // now read (`maybe_read_cdef_idx` in decode.rs) and threaded into + // [`crate::decode::apply_cdef`]'s per-superblock strength lookup, so + // a `cdef_bits > 0` stream no longer needs this refusal. + // Both frame types now read their transform size under + // `TxMode::Select`: an intra frame's `decode_key_frame_tile*` reads + // `tx_depth` (lane-av1txsel, spec 5.11.16), and an inter frame's + // `decode_inter_block`/`decode_inter_block8` read the recursive + // `txfm_split` var-tx tree (lane-txselect, spec 5.11.17) -- so the + // blanket inter-frame refusal that used to stand here is gone. What + // remains refused is named at its own site in `read_block_tx_size`. + // lane-av1real r11's blindness-audit sweep (`read_intra_frame_mode_info`, + // libaom decodemv.c): three more per-block/per-SB symbols this crate + // never reads at all, each gated by a header field this decoder + // otherwise accepts uncomplaining -- the same silent-desync shape + // `use_filter_intra` was. `allow_screen_content_tools` gates both + // `read_intrabc_info` and `read_palette_mode_info`; `delta.q_present`/ + // `delta.lf_present` gate `read_delta_qindex`/`read_delta_lflevel` + // (spec 5.11.10/5.11.11, one symbol group per superblock). Refuse + // before desyncing rather than silently miscode, the same pattern as + // the CDEF/TxMode::Select refusals above. + // lane-screen r2: key frames consume (not reconstruct) palette/ + // intrabc syntax via read_intra_mode, and decode_inter_block/ + // decode_inter_block8's own intra-sub-block branches now consume + // palette the same way (libaom's read_intra_block_mode_info has no + // intrabc call at all -- that symbol is intra-frame-only). A + // genuine palette/intrabc use still refuses by name deeper in the + // block readers, so no whole-frame refusal is needed here anymore. + // lane-realworld r5: both delta_q (maybe_read_delta_q, CURRENT_Q_IDX) + // and delta_lf (maybe_read_delta_lf, CURRENT_DELTA_LF -> + // Neighbours::delta_lf_grid -> lf_level) are now read and applied; + // no whole-frame refusal needed here anymore. + // + // lane-hbd r5: `Picture`'s `y`/`u`/`v` are `u16` now (widened an + // earlier round), `BIT_DEPTH` is wired from this frame's own sequence + // header (`set_bit_depth` above), and a real `aomenc --bit-depth=10` + // stream decodes pixel-exact against ffmpeg's own decode of the same + // bytes (`a_real_aomenc_10bit_stream_decodes_pixel_exact`). The + // blanket refusal that used to be here is gone; `film_grain.rs` and + // `superres.rs` still refuse narrowly by name (their own hardcoded + // 8-bit LUT/clamp, above), and any other rounding gap 10-bit exposes + // will show up as a real pixel mismatch, not a silent truncation -- + // the whole reason the widen (and this wiring) happened. + // lane-seg: `segment_id` is read per block now (spec 5.11.7-5.11.9, + // `decode::intra_segment_id`/`inter_segment_id`) and consumed by the + // per-segment quantizer (spec 7.12.2) and loop-filter level + // (spec 7.14.4). The three features that instead REWRITE a block's + // mode/reference decisions -- `SEG_LVL_REF_FRAME` (forces the + // reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both suppress + // symbols `decode_inter_block` unconditionally reads) -- have no + // reader on the inter path, so they still refuse by name rather than + // desyncing. aomenc's `--aq-mode` segmentation only ever sets + // `SEG_LVL_ALT_Q` (census gate + // `a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature`: + // 1-pass, alt-ref-lag and two-pass arms, every frame header parsed). + let tile_bufs: Vec<&[u8]> = tiles + .iter() + .map(|t| { + data.get(tiles_base_offset + t.offset..tiles_base_offset + t.offset + t.size) + .ok_or(Error::NeedMore) + }) + .collect::>()?; + let seq = SeqFlags::read(&parser); + // lane-thread3: at `threads > 1` every coded frame that is not a key + // frame is decoded on a worker -- frames that refresh reference slots + // included, which on a pyramid stream is nearly all of them. Its + // inputs are taken as promises and its output is published as one, + // installed into the slots it refreshes HERE, on the parsing thread, + // in decode order, so the next frame's dependencies are known without + // waiting for this one to finish (see [`SlotPromise`] for the + // deadlock argument). A key frame stays inline: it resets the whole + // bank and reads nothing, so there is nothing to gain. + if threads > 1 && header.frame_type != FrameType::Key && !header.show_existing_frame { let cap_t0 = crate::timeline::now(); - let capped = in_flight_shows >= in_flight_cap; - while in_flight_shows >= in_flight_cap { + let capped = in_flight_decodes >= in_flight_cap; + while in_flight_decodes >= in_flight_cap { collect_one( &rx, &mut in_flight_decodes, @@ -1033,42 +1301,265 @@ pub fn decode_stream_with_threads( )?; } if capped { - crate::timeline::cap_wait("show", cap_t0, crate::timeline::now()); + crate::timeline::cap_wait("decode", cap_t0, crate::timeline::now()); + } + // Exactly the slots this frame reads: `ref_frame_idx` names its + // references, and its `primary_ref_frame` CDFs/segment map, its + // reference order hints and every field `setup_motion_field` + // projects all come from those same slots. Nothing else is + // waited on. + let mut deps: [Option>; NUM_REF_FRAMES] = + std::array::from_fn(|_| None); + for i in 0..7 { + let slot = header.ref_frame_idx[i] as usize; + deps[slot] = slot_promises[slot].clone(); } - let (job_seq, decode_idx) = (emit_seq, pictures_decoded); + let dep_owner = slot_owner; + let produces = (header.refresh_frame_flags != 0).then(SlotPromise::pending); + if let Some(promise) = &produces { + for i in 0..NUM_REF_FRAMES { + if header.refresh_frame_flags & (1 << i) != 0 { + slot_promises[i] = Some(promise.clone()); + slot_owner[i] = pictures_decoded; + } + } + } + let (job_seq, decode_idx, shown_idx) = (emit_seq, pictures_decoded, pictures_shown); emit_seq += 1; - pictures_shown += 1; - let grain = header.film_grain; - let seq = SeqFlags::read(&parser); + pictures_decoded += 1; + let shown = header.show_frame; + if shown { + pictures_shown += 1; + } let tx = tx.clone(); + let dump = final_dump.clone(); + crate::timeline::submit(decode_idx, if shown { 'P' } else { 'A' }, shown); + // The job outlives this call, so it owns its tile bytes (a copy of + // this frame's compressed tiles) instead of borrowing `data`. + let owned_tiles: Vec> = tile_bufs.iter().map(|t| t.to_vec()).collect(); jobs.submit(move || { - let mut answer = JobAnswer::new(tx, job_seq, false, None, None); + let tile_views: Vec<&[u8]> = owned_tiles.iter().map(Vec::as_slice).collect(); + let promise = produces; + // lane-twostage: stage 2 -- this frame's filtered pixels. Its + // consumers hold this promise from the moment stage 1 (CDFs, + // segment map, motion field, size) is published at the tile + // boundary, and wait on it at their first prediction. + let pixels: std::sync::Arc>> = + SlotPromise::pending(); + let mut answer = JobAnswer::new( + tx, + job_seq, + true, + promise.clone(), + Some(pixels.clone()), + ); let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let value = promise.wait()?; - let shown_picture = value.pixels.wait()?; - let output = if grain.apply_grain && !no_grain() { - std::sync::Arc::new(crate::film_grain::apply_grain( - &shown_picture, - &grain, - seq.mc_identity, - u32::from(seq.bit_depth), - &crate::decode::FrameCtx::new(), + let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + crate::fault::point("frame"); + crate::timeline::start(decode_idx); + // The wait happens HERE, off the parsing thread, and only + // for this frame's own references. + let mut resolved: [Option>; NUM_REF_FRAMES] = + std::array::from_fn(|_| None); + for (slot, dep) in deps.iter().enumerate() { + if let Some(dep) = dep { + let t0 = crate::timeline::now(); + resolved[slot] = Some(dep.wait()?); + crate::timeline::ref_wait( + decode_idx, + slot, + dep_owner[slot], + crate::timeline::now().saturating_sub(t0), + ); + } + } + crate::timeline::refs_ready(); + // Fresh per-thread state: every field this path reads is + // written from this frame's own header before it is read. + let fctx = crate::decode::FrameCtx::new(); + // lane-twostage: the pictures behind this frame's own + // references, waited for at the first `ref_planes` call + // inside the tile decode rather than here. + let ref_metas: [Option>; 8] = + std::array::from_fn(|i| { + if i == 0 { + None + } else { + resolved + .get(header.ref_frame_idx[i - 1] as usize) + .cloned() + .flatten() + } + }); + let pix_cell: std::sync::OnceLock< + [Option>; 8], + > = std::sync::OnceLock::new(); + let wait_pixels = || -> Result<[Option<&Picture>; 8]> { + if pix_cell.get().is_none() { + let mut pics: [Option>; 8] = + Default::default(); + for (i, meta) in ref_metas.iter().enumerate() { + if let Some(meta) = meta { + let slot = header.ref_frame_idx[i - 1] as usize; + let t0 = crate::timeline::now(); + pics[i] = Some(meta.pixels.wait()?); + crate::timeline::ref_wait( + decode_idx, + slot, + dep_owner[slot], + crate::timeline::now().saturating_sub(t0), + ); + } + } + let _ = pix_cell.set(pics); + } + let pics = pix_cell.get().expect("the pictures were just set"); + Ok(std::array::from_fn(|i| pics[i].as_deref())) + }; + let ref_dims: [Option<(usize, usize)>; 8] = + std::array::from_fn(|i| { + ref_metas[i].as_ref().map(|m| (m.width, m.height)) + }); + // The same references for the recon workers, which wait + // for the pictures themselves (off the parse thread). + let shared_refs = { + let metas = ref_metas.clone(); + let ref_idx = header.ref_frame_idx; + let owners = dep_owner; + decode::SharedRefs { + dims: ref_dims, + wait: std::sync::Arc::new(move || { + let mut pics: [Option>; 8] = + Default::default(); + for (i, meta) in metas.iter().enumerate() { + if let Some(meta) = meta { + let slot = ref_idx[i - 1] as usize; + let t0 = crate::timeline::now(); + pics[i] = Some(meta.pixels.wait()?); + crate::timeline::ref_wait( + decode_idx, + slot, + owners[slot], + crate::timeline::now().saturating_sub(t0), + ); + } + } + Ok(pics) + }), + } + }; + let refpix = + decode::RefPix::lazy(ref_dims, &wait_pixels, Some(shared_refs)); + // Stage 1: published at this frame's tile boundary, before + // its filters run (`take_segment_ids` copies the map, so + // the filters that read it are unaffected). + let stage1 = |cdfs: Cdfs, + motion_field: crate::motion_field::MotionField, + width: usize, + height: usize| { + if let Some(promise) = &promise { + promise.fulfil(std::sync::Arc::new(SlotValue { + pixels: pixels.clone(), + width, + height, + cdfs, + motion_field, + seg_map: decode::take_segment_ids(&fctx), + order_hint: header.order_hint, + })); + crate::timeline::slot_fulfil(); + } + }; + // spec 7.9's `av1_setup_motion_field` runs inside + // `RefSnapshot::take`, i.e. here, after those waits -- + // it reads the referenced slots' saved motion fields. + let motion_fields = + std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.motion_field)); + let snap = RefSnapshot::take( + &header, + seq, + &refpix, + std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.cdfs)), + std::array::from_fn(|i| { + resolved[i].as_ref().map(|v| v.seg_map.as_slice()) + }), + &motion_fields, + std::array::from_fn(|i| resolved[i].as_ref().map_or(0, |v| v.order_hint)), + ); + let out = decode_frame( + &fctx, + &header, + &tile_views, + seq, + snap, + decode_idx, + shown_idx, + dump.as_deref(), + // lane-twostage publishes a frame's meta at its tile + // boundary instead of after its filters, so a consumer + // parses over its producer's filter tail. It is ON by + // default since lane-sub8group: with every reference + // pixel read deferred to the recon workers, the + // consumer parses its WHOLE tile before it needs a + // pixel, and the 4K critical chain shortens by 11-14% + // in three interleaved pairs (14450/10594/14407 ms off + // vs 12790/9207/12463 ms on) where it moved 3-7% + // before. `EC_AV1_TWO_STAGE=0` turns it back off. + (crate::envflags::var("EC_AV1_TWO_STAGE").as_deref() != Ok("0")) + .then_some(&stage1 as &dyn Fn(_, _, _, _)), + )?; + // Publish before grain synthesis: every frame waiting on + // this slot can start the moment the clean picture exists + // (spec 7.18.3.1 -- the bank never stores grain). + let picture = std::sync::Arc::new(out.picture); + pixels.fulfil(picture.clone()); + if let Some(promise) = &promise { + // Only a frame whose stage-1 sink never fired (a + // superres frame) still has meta to publish here. + promise.fulfil_if_pending(|| { + std::sync::Arc::new(SlotValue { + pixels: pixels.clone(), + width: picture.width, + height: picture.height, + cdfs: out.stored_cdfs, + motion_field: out.motion_field.expect( + "a frame that published no stage 1 carries its motion field back", + ), + seg_map: out.seg_map, + order_hint: header.order_hint, + }) + }); + crate::timeline::slot_fulfil(); + } + // Grain is synthesised for OUTPUT only: a hidden frame is + // reported to the sink clean, exactly as the inline path + // below reports it (spec 7.18.3.1). + let output = if shown && header.film_grain.apply_grain && !no_grain() { + std::sync::Arc::new(crate::film_grain::apply_grain( + &picture, + &header.film_grain, + seq.mc_identity, + u32::from(seq.bit_depth), + &fctx, + )) + } else { + picture + }; + crate::timeline::grain_done(); + Ok((output, decode_idx, shown)) + })) + .unwrap_or_else(|_| { + Err(Error::corrupt( + "AV1 decode_stream: a worker thread panicked decoding a frame", )) - } else { - std::sync::Arc::clone(&shown_picture) - }; - Ok((output, decode_idx, true)) - })) - .unwrap_or_else(|_| { - Err(Error::corrupt( - "AV1 decode_stream: a worker thread panicked on a show_existing_frame output", - )) - }); - answer.send(reply); + }); + crate::fault::point("frame-after"); + answer.send(reply); })); }); - in_flight_shows += 1; + in_flight_decodes += 1; + FRAMES_DISPATCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + // Anything that finished while this frame was being set up. while let Ok((seq, decode_job, result)) = rx.try_recv() { if decode_job { in_flight_decodes -= 1; @@ -1081,563 +1572,169 @@ pub fn decode_stream_with_threads( } continue; } - let picture = { - let picture = ref_slots[slot].clone().ok_or_else(empty_slot)?; - for i in 0..NUM_REF_FRAMES { - if header.refresh_frame_flags & (1 << i) != 0 { - cdf_slots[i] = cdf_slots[slot].clone(); - ref_slots[i] = Some(picture.clone()); - motion_field_slots[i] = motion_field_slots[slot].clone(); - seg_map_slots[i] = seg_map_slots[slot].clone(); - order_hint_slots[i] = order_hint_slots[slot]; - } + // lane-twostage: the inline path's references are decoded already, + // so its handle never waits. + let inline_refpix = decode::RefPix::ready(std::array::from_fn(|i| { + if i == 0 { + None + } else { + ref_slots + .get(header.ref_frame_idx[i - 1] as usize) + .and_then(|p| p.as_deref()) } - picture - }; - let output = if header.film_grain.apply_grain && !no_grain() { - // lane-hbd10 r1: grain synthesis is bit-depth generic - // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3). - let bit_depth = parser - .sequence_header() - .map_or(8, |seq| seq.color_config.bit_depth); - let mc_identity = parser - .sequence_header() - .is_some_and(|seq| seq.color_config.matrix_coefficients == 0); - std::sync::Arc::new(crate::film_grain::apply_grain( - &picture, - &header.film_grain, - mc_identity, - bit_depth as u32, - fctx, - )) - } else { - picture - }; - reorder.push(emit_seq, output, pictures_decoded, true); - emit_seq += 1; - reorder.drain(&mut sink)?; - pictures_shown += 1; - continue; - } - // `tiles_base_offset` is added to every `Tile::offset` below to reach - // an absolute position in `data`. `OBU_FRAME`'s tiles are relative to - // this OBU's own `obu_offset`; an accumulated run of `OBU_TILE_GROUP`s - // may span several different OBUs (each at a different offset in - // `data`), so those tiles are normalised to an absolute offset the - // moment they are appended to `pending_tiles`, and `tiles_base_offset` - // is 0 for that case. - let (header, tiles, tiles_base_offset): (Box, Vec, usize) = - match obu.kind { - ObuKind::Frame(header, tiles) => (header, tiles, obu_offset), - ObuKind::TileGroup(new_tiles) => { - let header = pending_header.clone().ok_or_else(|| { - Error::corrupt( - "AV1 decode_stream: a tile group OBU with no preceding frame header", - ) - })?; - let expected = header.tile_info.cols * header.tile_info.rows; - pending_tiles.extend(new_tiles.into_iter().map(|mut t| { - t.offset += obu_offset; - t + })); + let snap = RefSnapshot::take( + &header, + seq, + &inline_refpix, + std::array::from_fn(|i| cdf_slots[i].as_ref()), + std::array::from_fn(|i| seg_map_slots[i].as_deref()), + &std::array::from_fn(|i| motion_field_slots[i].as_ref()), + order_hint_slots, + ); + let bit_depth = seq.bit_depth; + let FrameOutput { + picture, + stored_cdfs, + motion_field, + seg_map: decoded_seg_map, + } = decode_frame( + fctx, + &header, + &tile_bufs, + seq, + snap, + pictures_decoded, + pictures_shown, + final_dump.as_deref(), + None, + )?; + let motion_field = motion_field.expect("the inline path passes no stage-1 sink"); + pictures_decoded += 1; + // lane-pool1: one allocation, then every slot store and the output + // itself are refcount bumps instead of plane copies. + let picture = std::sync::Arc::new(picture); + if threads > 1 { + // lane-thread3: only a key frame reaches this inline path at + // `threads > 1`, and the bank it fills is the promise array -- + // already resolved, since the picture exists right here. + if header.refresh_frame_flags != 0 { + let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue { + pixels: SlotPromise::ready(std::sync::Arc::clone(&picture)), + width: picture.width, + height: picture.height, + cdfs: stored_cdfs, + motion_field, + seg_map: decoded_seg_map, + order_hint: header.order_hint, })); - if (pending_tiles.len() as u32) < expected { - continue; + for i in 0..NUM_REF_FRAMES { + if header.refresh_frame_flags & (1 << i) != 0 { + slot_promises[i] = Some(promise.clone()); + slot_owner[i] = pictures_decoded - 1; + } } - pending_header = None; - (header, std::mem::take(&mut pending_tiles), 0) } - _ => continue, - }; - // Every tile is decoded below through `tile_bufs`; this only rejects a - // frame OBU that carries no tile group at all. - if tiles.is_empty() { - return Err(Error::unsupported( - "AV1 decode_stream", - "a frame OBU with no tile group", - )); - } - // `read_cdef` (spec `decodeframe.c`, called at the first non-skip - // block of each 64x64) only reads a literal `cdef_idx` when - // `cdef_bits > 0`; at `cdef_bits == 0` there is nothing to read (a - // true no-op). lane-realworld r1: the per-64x64 `cdef_idx` literal is - // now read (`maybe_read_cdef_idx` in decode.rs) and threaded into - // [`crate::decode::apply_cdef`]'s per-superblock strength lookup, so - // a `cdef_bits > 0` stream no longer needs this refusal. - // Both frame types now read their transform size under - // `TxMode::Select`: an intra frame's `decode_key_frame_tile*` reads - // `tx_depth` (lane-av1txsel, spec 5.11.16), and an inter frame's - // `decode_inter_block`/`decode_inter_block8` read the recursive - // `txfm_split` var-tx tree (lane-txselect, spec 5.11.17) -- so the - // blanket inter-frame refusal that used to stand here is gone. What - // remains refused is named at its own site in `read_block_tx_size`. - // lane-av1real r11's blindness-audit sweep (`read_intra_frame_mode_info`, - // libaom decodemv.c): three more per-block/per-SB symbols this crate - // never reads at all, each gated by a header field this decoder - // otherwise accepts uncomplaining -- the same silent-desync shape - // `use_filter_intra` was. `allow_screen_content_tools` gates both - // `read_intrabc_info` and `read_palette_mode_info`; `delta.q_present`/ - // `delta.lf_present` gate `read_delta_qindex`/`read_delta_lflevel` - // (spec 5.11.10/5.11.11, one symbol group per superblock). Refuse - // before desyncing rather than silently miscode, the same pattern as - // the CDEF/TxMode::Select refusals above. - // lane-screen r2: key frames consume (not reconstruct) palette/ - // intrabc syntax via read_intra_mode, and decode_inter_block/ - // decode_inter_block8's own intra-sub-block branches now consume - // palette the same way (libaom's read_intra_block_mode_info has no - // intrabc call at all -- that symbol is intra-frame-only). A - // genuine palette/intrabc use still refuses by name deeper in the - // block readers, so no whole-frame refusal is needed here anymore. - // lane-realworld r5: both delta_q (maybe_read_delta_q, CURRENT_Q_IDX) - // and delta_lf (maybe_read_delta_lf, CURRENT_DELTA_LF -> - // Neighbours::delta_lf_grid -> lf_level) are now read and applied; - // no whole-frame refusal needed here anymore. - // - // lane-hbd r5: `Picture`'s `y`/`u`/`v` are `u16` now (widened an - // earlier round), `BIT_DEPTH` is wired from this frame's own sequence - // header (`set_bit_depth` above), and a real `aomenc --bit-depth=10` - // stream decodes pixel-exact against ffmpeg's own decode of the same - // bytes (`a_real_aomenc_10bit_stream_decodes_pixel_exact`). The - // blanket refusal that used to be here is gone; `film_grain.rs` and - // `superres.rs` still refuse narrowly by name (their own hardcoded - // 8-bit LUT/clamp, above), and any other rounding gap 10-bit exposes - // will show up as a real pixel mismatch, not a silent truncation -- - // the whole reason the widen (and this wiring) happened. - // lane-seg: `segment_id` is read per block now (spec 5.11.7-5.11.9, - // `decode::intra_segment_id`/`inter_segment_id`) and consumed by the - // per-segment quantizer (spec 7.12.2) and loop-filter level - // (spec 7.14.4). The three features that instead REWRITE a block's - // mode/reference decisions -- `SEG_LVL_REF_FRAME` (forces the - // reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both suppress - // symbols `decode_inter_block` unconditionally reads) -- have no - // reader on the inter path, so they still refuse by name rather than - // desyncing. aomenc's `--aq-mode` segmentation only ever sets - // `SEG_LVL_ALT_Q` (census gate - // `a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature`: - // 1-pass, alt-ref-lag and two-pass arms, every frame header parsed). - let tile_bufs: Vec<&[u8]> = tiles - .iter() - .map(|t| { - data.get(tiles_base_offset + t.offset..tiles_base_offset + t.offset + t.size) - .ok_or(Error::NeedMore) - }) - .collect::>()?; - let seq = SeqFlags::read(&parser); - // lane-thread3: at `threads > 1` every coded frame that is not a key - // frame is decoded on a worker -- frames that refresh reference slots - // included, which on a pyramid stream is nearly all of them. Its - // inputs are taken as promises and its output is published as one, - // installed into the slots it refreshes HERE, on the parsing thread, - // in decode order, so the next frame's dependencies are known without - // waiting for this one to finish (see [`SlotPromise`] for the - // deadlock argument). A key frame stays inline: it resets the whole - // bank and reads nothing, so there is nothing to gain. - if threads > 1 && header.frame_type != FrameType::Key && !header.show_existing_frame { - let cap_t0 = crate::timeline::now(); - let capped = in_flight_decodes >= in_flight_cap; - while in_flight_decodes >= in_flight_cap { - collect_one( - &rx, - &mut in_flight_decodes, - &mut in_flight_shows, - &mut reorder, - &mut sink, - )?; - } - if capped { - crate::timeline::cap_wait("decode", cap_t0, crate::timeline::now()); - } - // Exactly the slots this frame reads: `ref_frame_idx` names its - // references, and its `primary_ref_frame` CDFs/segment map, its - // reference order hints and every field `setup_motion_field` - // projects all come from those same slots. Nothing else is - // waited on. - let mut deps: [Option>; NUM_REF_FRAMES] = - std::array::from_fn(|_| None); - for i in 0..7 { - let slot = header.ref_frame_idx[i] as usize; - deps[slot] = slot_promises[slot].clone(); - } - let dep_owner = slot_owner; - let produces = (header.refresh_frame_flags != 0).then(SlotPromise::pending); - if let Some(promise) = &produces { + } else { for i in 0..NUM_REF_FRAMES { if header.refresh_frame_flags & (1 << i) != 0 { - slot_promises[i] = Some(promise.clone()); - slot_owner[i] = pictures_decoded; + cdf_slots[i] = Some(stored_cdfs.clone()); + // Spec 7.18.3.1: synthesized grain is never stored for + // later prediction -- the reference bank always keeps the + // clean, pre-grain decode, even though the frame pushed + // onto the caller's output below carries the grained + // picture. + ref_slots[i] = Some(std::sync::Arc::clone(&picture)); + motion_field_slots[i] = Some(motion_field.clone()); + seg_map_slots[i] = Some(decoded_seg_map.clone()); + order_hint_slots[i] = header.order_hint; } } } - let (job_seq, decode_idx, shown_idx) = (emit_seq, pictures_decoded, pictures_shown); - emit_seq += 1; - pictures_decoded += 1; - let shown = header.show_frame; - if shown { - pictures_shown += 1; + // lane-defon r1: a forward keyframe (aomenc `--enable-fwd-kf`) is a + // KEY frame coded with `show_frame == 0`, output later by a + // `show_existing_frame` header -- counted only once its tiles have + // decoded, so the gate's assert covers decoded-and-compared frames. + if header.frame_type == FrameType::Key && !header.show_frame { + decode::note_fwd_kf(); } - let tx = tx.clone(); - let dump = final_dump.clone(); - crate::timeline::submit(decode_idx, if shown { 'P' } else { 'A' }, shown); - // The job outlives this call, so it owns its tile bytes (a copy of - // this frame's compressed tiles) instead of borrowing `data`. - let owned_tiles: Vec> = tile_bufs.iter().map(|t| t.to_vec()).collect(); - jobs.submit(move || { - let tile_views: Vec<&[u8]> = owned_tiles.iter().map(Vec::as_slice).collect(); - let promise = produces; - // lane-twostage: stage 2 -- this frame's filtered pixels. Its - // consumers hold this promise from the moment stage 1 (CDFs, - // segment map, motion field, size) is published at the tile - // boundary, and wait on it at their first prediction. - let pixels: std::sync::Arc>> = - SlotPromise::pending(); - let mut answer = JobAnswer::new( - tx, - job_seq, - true, - promise.clone(), - Some(pixels.clone()), - ); - let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - crate::fault::point("frame"); - crate::timeline::start(decode_idx); - // The wait happens HERE, off the parsing thread, and only - // for this frame's own references. - let mut resolved: [Option>; NUM_REF_FRAMES] = - std::array::from_fn(|_| None); - for (slot, dep) in deps.iter().enumerate() { - if let Some(dep) = dep { - let t0 = crate::timeline::now(); - resolved[slot] = Some(dep.wait()?); - crate::timeline::ref_wait( - decode_idx, - slot, - dep_owner[slot], - crate::timeline::now().saturating_sub(t0), - ); - } - } - crate::timeline::refs_ready(); - // Fresh per-thread state: every field this path reads is - // written from this frame's own header before it is read. - let fctx = crate::decode::FrameCtx::new(); - // lane-twostage: the pictures behind this frame's own - // references, waited for at the first `ref_planes` call - // inside the tile decode rather than here. - let ref_metas: [Option>; 8] = - std::array::from_fn(|i| { - if i == 0 { - None - } else { - resolved - .get(header.ref_frame_idx[i - 1] as usize) - .cloned() - .flatten() - } - }); - let pix_cell: std::sync::OnceLock< - [Option>; 8], - > = std::sync::OnceLock::new(); - let wait_pixels = || -> Result<[Option<&Picture>; 8]> { - if pix_cell.get().is_none() { - let mut pics: [Option>; 8] = - Default::default(); - for (i, meta) in ref_metas.iter().enumerate() { - if let Some(meta) = meta { - let slot = header.ref_frame_idx[i - 1] as usize; - let t0 = crate::timeline::now(); - pics[i] = Some(meta.pixels.wait()?); - crate::timeline::ref_wait( - decode_idx, - slot, - dep_owner[slot], - crate::timeline::now().saturating_sub(t0), - ); - } - } - let _ = pix_cell.set(pics); - } - let pics = pix_cell.get().expect("the pictures were just set"); - Ok(std::array::from_fn(|i| pics[i].as_deref())) - }; - let ref_dims: [Option<(usize, usize)>; 8] = - std::array::from_fn(|i| { - ref_metas[i].as_ref().map(|m| (m.width, m.height)) - }); - // The same references for the recon workers, which wait - // for the pictures themselves (off the parse thread). - let shared_refs = { - let metas = ref_metas.clone(); - let ref_idx = header.ref_frame_idx; - let owners = dep_owner; - decode::SharedRefs { - dims: ref_dims, - wait: std::sync::Arc::new(move || { - let mut pics: [Option>; 8] = - Default::default(); - for (i, meta) in metas.iter().enumerate() { - if let Some(meta) = meta { - let slot = ref_idx[i - 1] as usize; - let t0 = crate::timeline::now(); - pics[i] = Some(meta.pixels.wait()?); - crate::timeline::ref_wait( - decode_idx, - slot, - owners[slot], - crate::timeline::now().saturating_sub(t0), - ); - } - } - Ok(pics) - }), - } - }; - let refpix = - decode::RefPix::lazy(ref_dims, &wait_pixels, Some(shared_refs)); - // Stage 1: published at this frame's tile boundary, before - // its filters run (`take_segment_ids` copies the map, so - // the filters that read it are unaffected). - let stage1 = |cdfs: Cdfs, - motion_field: crate::motion_field::MotionField, - width: usize, - height: usize| { - if let Some(promise) = &promise { - promise.fulfil(std::sync::Arc::new(SlotValue { - pixels: pixels.clone(), - width, - height, - cdfs, - motion_field, - seg_map: decode::take_segment_ids(&fctx), - order_hint: header.order_hint, - })); - crate::timeline::slot_fulfil(); - } - }; - // spec 7.9's `av1_setup_motion_field` runs inside - // `RefSnapshot::take`, i.e. here, after those waits -- - // it reads the referenced slots' saved motion fields. - let motion_fields = - std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.motion_field)); - let snap = RefSnapshot::take( - &header, - seq, - &refpix, - std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.cdfs)), - std::array::from_fn(|i| { - resolved[i].as_ref().map(|v| v.seg_map.as_slice()) - }), - &motion_fields, - std::array::from_fn(|i| resolved[i].as_ref().map_or(0, |v| v.order_hint)), - ); - let out = decode_frame( - &fctx, - &header, - &tile_views, - seq, - snap, - decode_idx, - shown_idx, - dump.as_deref(), - // lane-twostage publishes a frame's meta at its tile - // boundary instead of after its filters, so a consumer - // parses over its producer's filter tail. It is ON by - // default since lane-sub8group: with every reference - // pixel read deferred to the recon workers, the - // consumer parses its WHOLE tile before it needs a - // pixel, and the 4K critical chain shortens by 11-14% - // in three interleaved pairs (14450/10594/14407 ms off - // vs 12790/9207/12463 ms on) where it moved 3-7% - // before. `EC_AV1_TWO_STAGE=0` turns it back off. - (crate::envflags::var("EC_AV1_TWO_STAGE").as_deref() != Ok("0")) - .then_some(&stage1 as &dyn Fn(_, _, _, _)), - )?; - // Publish before grain synthesis: every frame waiting on - // this slot can start the moment the clean picture exists - // (spec 7.18.3.1 -- the bank never stores grain). - let picture = std::sync::Arc::new(out.picture); - pixels.fulfil(picture.clone()); - if let Some(promise) = &promise { - // Only a frame whose stage-1 sink never fired (a - // superres frame) still has meta to publish here. - promise.fulfil_if_pending(|| { - std::sync::Arc::new(SlotValue { - pixels: pixels.clone(), - width: picture.width, - height: picture.height, - cdfs: out.stored_cdfs, - motion_field: out.motion_field.expect( - "a frame that published no stage 1 carries its motion field back", - ), - seg_map: out.seg_map, - order_hint: header.order_hint, - }) - }); - crate::timeline::slot_fulfil(); - } - // Grain is synthesised for OUTPUT only: a hidden frame is - // reported to the sink clean, exactly as the inline path - // below reports it (spec 7.18.3.1). - let output = if shown && header.film_grain.apply_grain && !no_grain() { - std::sync::Arc::new(crate::film_grain::apply_grain( - &picture, - &header.film_grain, - seq.mc_identity, - u32::from(seq.bit_depth), - &fctx, - )) - } else { - picture - }; - crate::timeline::grain_done(); - Ok((output, decode_idx, shown)) - })) - .unwrap_or_else(|_| { - Err(Error::corrupt( - "AV1 decode_stream: a worker thread panicked decoding a frame", - )) - }); - crate::fault::point("frame-after"); - answer.send(reply); - })); - }); - in_flight_decodes += 1; - FRAMES_DISPATCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - // Anything that finished while this frame was being set up. - while let Ok((seq, decode_job, result)) = rx.try_recv() { - if decode_job { - in_flight_decodes -= 1; + if header.show_frame { + let output = if header.film_grain.apply_grain && !no_grain() { + let mc_identity = seq.mc_identity; + std::sync::Arc::new(crate::film_grain::apply_grain( + &picture, + &header.film_grain, + mc_identity, + bit_depth as u32, + fctx, + )) } else { - in_flight_shows -= 1; - } - let (picture, decode_idx, shown) = result?; - reorder.push(seq, picture, decode_idx, shown); + picture + }; + reorder.push(emit_seq, output, pictures_decoded - 1, true); + emit_seq += 1; reorder.drain(&mut sink)?; - } - continue; - } - // lane-twostage: the inline path's references are decoded already, - // so its handle never waits. - let inline_refpix = decode::RefPix::ready(std::array::from_fn(|i| { - if i == 0 { - None + pictures_shown += 1; } else { - ref_slots - .get(header.ref_frame_idx[i - 1] as usize) - .and_then(|p| p.as_deref()) - } - })); - let snap = RefSnapshot::take( - &header, - seq, - &inline_refpix, - std::array::from_fn(|i| cdf_slots[i].as_ref()), - std::array::from_fn(|i| seg_map_slots[i].as_deref()), - &std::array::from_fn(|i| motion_field_slots[i].as_ref()), - order_hint_slots, - ); - let bit_depth = seq.bit_depth; - let FrameOutput { - picture, - stored_cdfs, - motion_field, - seg_map: decoded_seg_map, - } = decode_frame( - fctx, - &header, - &tile_bufs, - seq, - snap, - pictures_decoded, - pictures_shown, - final_dump.as_deref(), - None, - )?; - let motion_field = motion_field.expect("the inline path passes no stage-1 sink"); - pictures_decoded += 1; - // lane-pool1: one allocation, then every slot store and the output - // itself are refcount bumps instead of plane copies. - let picture = std::sync::Arc::new(picture); - if threads > 1 { - // lane-thread3: only a key frame reaches this inline path at - // `threads > 1`, and the bank it fills is the promise array -- - // already resolved, since the picture exists right here. - if header.refresh_frame_flags != 0 { - let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue { - pixels: SlotPromise::ready(std::sync::Arc::clone(&picture)), - width: picture.width, - height: picture.height, - cdfs: stored_cdfs, - motion_field, - seg_map: decoded_seg_map, - order_hint: header.order_hint, - })); - for i in 0..NUM_REF_FRAMES { - if header.refresh_frame_flags & (1 << i) != 0 { - slot_promises[i] = Some(promise.clone()); - slot_owner[i] = pictures_decoded - 1; - } - } - } - } else { - for i in 0..NUM_REF_FRAMES { - if header.refresh_frame_flags & (1 << i) != 0 { - cdf_slots[i] = Some(stored_cdfs.clone()); - // Spec 7.18.3.1: synthesized grain is never stored for - // later prediction -- the reference bank always keeps the - // clean, pre-grain decode, even though the frame pushed - // onto the caller's output below carries the grained - // picture. - ref_slots[i] = Some(std::sync::Arc::clone(&picture)); - motion_field_slots[i] = Some(motion_field.clone()); - seg_map_slots[i] = Some(decoded_seg_map.clone()); - order_hint_slots[i] = header.order_hint; - } + // Hidden (alt-ref/forward-key) frames never reach + // `decode_stream`'s output, but a decode-order consumer -- the + // `EC_AV1_FINAL_DUMP` comparison against aomdec, say -- needs + // them, so they are reported too, with `shown == false`. + reorder.push(emit_seq, picture, pictures_decoded - 1, false); + emit_seq += 1; + reorder.drain(&mut sink)?; } } - // lane-defon r1: a forward keyframe (aomenc `--enable-fwd-kf`) is a - // KEY frame coded with `show_frame == 0`, output later by a - // `show_existing_frame` header -- counted only once its tiles have - // decoded, so the gate's assert covers decoded-and-compared frames. - if header.frame_type == FrameType::Key && !header.show_frame { - decode::note_fwd_kf(); - } - if header.show_frame { - let output = if header.film_grain.apply_grain && !no_grain() { - let mc_identity = seq.mc_identity; - std::sync::Arc::new(crate::film_grain::apply_grain( - &picture, - &header.film_grain, - mc_identity, - bit_depth as u32, - fctx, - )) - } else { - picture - }; - reorder.push(emit_seq, output, pictures_decoded - 1, true); - emit_seq += 1; - reorder.drain(&mut sink)?; - pictures_shown += 1; - } else { - // Hidden (alt-ref/forward-key) frames never reach - // `decode_stream`'s output, but a decode-order consumer -- the - // `EC_AV1_FINAL_DUMP` comparison against aomdec, say -- needs - // them, so they are reported too, with `shown == false`. - reorder.push(emit_seq, picture, pictures_decoded - 1, false); - emit_seq += 1; - reorder.drain(&mut sink)?; + while in_flight_decodes + in_flight_shows > 0 { + collect_one( + &rx, + &mut in_flight_decodes, + &mut in_flight_shows, + &mut reorder, + &mut sink, + )?; } + self.pictures_shown = pictures_shown; + self.pictures_decoded = pictures_decoded; + self.emit_seq = emit_seq; + self.in_flight_decodes = in_flight_decodes; + self.in_flight_shows = in_flight_shows; + self.order_hint_slots = order_hint_slots; + self.slot_owner = slot_owner; + self.reorder = reorder; + self.pending_header = pending_header; + self.pending_tiles = pending_tiles; + Ok(()) } - while in_flight_decodes + in_flight_shows > 0 { - collect_one( - &rx, - &mut in_flight_decodes, - &mut in_flight_shows, - &mut reorder, - &mut sink, - )?; - } - debug_assert!(reorder.pending.is_empty(), "a frame was never emitted"); +} + +/// [`decode_stream_with`] with an explicit worker count (lane-thread2). +/// +/// `threads == 1` is the serial decoder. Above that, frames that no later +/// frame can reference -- a shown, non-key frame whose `refresh_frame_flags` +/// is 0, i.e. a leaf of the reference graph -- are decoded on worker threads +/// while the main thread keeps parsing headers and decoding the frames that +/// DO feed the reference banks; `sink` still sees every picture in coded +/// order. Each worker owns a fresh [`crate::decode::FrameCtx`] and a snapshot +/// of the banks taken before dispatch, so no decode state is shared. +/// +/// The per-decode counters this crate's gates read are thread-local, so at +/// `threads > 1` a leaf frame's counts land on the worker and are invisible +/// to the caller; that is why the default is 1. +/// +/// # Errors +/// As [`decode_stream_with`]; a worker's error aborts the stream. +pub fn decode_stream_with_threads( + data: &[u8], + threads: usize, + sink: impl FnMut(&Picture, usize, bool) -> Result<()>, +) -> Result<()> { + let mut decoder = StreamDecoder::new(threads); + decoder.decode(data, sink)?; + debug_assert!( + decoder.reorder.pending.is_empty(), + "a frame was never emitted" + ); crate::timeline::dump(); Ok(()) } diff --git a/crates/ec-av1/src/stream/tests/mod.rs b/crates/ec-av1/src/stream/tests/mod.rs index 46d9200d..07bf7a39 100644 --- a/crates/ec-av1/src/stream/tests/mod.rs +++ b/crates/ec-av1/src/stream/tests/mod.rs @@ -3,9 +3,11 @@ use crate::encode::{Picture as Pic, encode_sequence_with_ctx}; use crate::probe::run_with_stdin; use std::process::{Command, Stdio}; -mod support; mod gates_a; mod gates_b; +mod layers; +mod streaming; +mod support; mod t01; mod t02; mod t03; @@ -16,6 +18,5 @@ mod t07; mod t08; mod t09; mod t10; -mod layers; pub(crate) use gates_a::lock_gate_counters; diff --git a/crates/ec-av1/src/stream/tests/streaming.rs b/crates/ec-av1/src/stream/tests/streaming.rs new file mode 100644 index 00000000..ed899263 --- /dev/null +++ b/crates/ec-av1/src/stream/tests/streaming.rs @@ -0,0 +1,35 @@ +use super::*; +use crate::encoder::{Av1Encoder, Colour, EncoderConfig}; + +#[test] +fn stream_decoder_fed_per_packet_matches_decode_stream() { + let (w, h) = (64, 64); + let mut enc = Av1Encoder::new(EncoderConfig::new(w, h, 120, 30, Colour::Unspecified)).unwrap(); + let mut packets: Vec> = (0..6) + .flat_map(|t| { + let mut p = Pic::grey(w, h); + for (i, v) in p.y.iter_mut().enumerate() { + *v = ((i % w + t * 3 + (i / w) * 2) % 230) as u16; + } + enc.encode_frames(&p).unwrap() + }) + .map(|p| p.data) + .collect(); + packets.extend(enc.flush().unwrap().into_iter().map(|p| p.data)); + let want = decode_stream(&packets.concat()).unwrap(); + let mut dec = StreamDecoder::new(1); + let got: Vec = packets + .iter() + .flat_map(|p| { + let pics = dec.decode_temporal_unit(p).unwrap(); + assert_eq!(pics.len(), 1); + pics + }) + .collect(); + assert_eq!(got.len(), want.len()); + assert!( + got.iter() + .zip(&want) + .all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v) + ); +} diff --git a/lanes/hwvideo.charter.md b/lanes/hwvideo.charter.md new file mode 100644 index 00000000..4636f017 --- /dev/null +++ b/lanes/hwvideo.charter.md @@ -0,0 +1,147 @@ +# lane hwvideo: hardware video backend strategy (charter) + +Date 2026-11-25. Base `19320a9d`. Decision + plan only; no code changed. +Consumer: yumush (QUIC screen share: low latency, simulcast, keyframe on request, no B-frames). + +## Decision + +**(c) Hybrid, Vulkan-first.** + +1. **Vulkan Video is the one new backend**, for Linux and Windows (encode H.264/H.265/AV1, decode H.264/H.265/AV1/VP9). +2. **VA-API stays on Linux, frozen** (no new features): fallback for hardware without Vulkan Video, and the test oracle. +3. **No Media Foundation.** A Windows-native backend is deferred and, if needed, is **D3D12 Video** (same stateless model as VA/Vulkan, so it reuses the ec-hw core). Trigger: measured demand for Intel-on-Windows encode plus access to a Windows GPU. + +Why: +- Only Vulkan can be developed and verified on the machine we have. ~90% of the Windows path (session, DPB, RC, headers, convert) is the same code that runs here; only handle import differs. +- Vulkan Video has the same shape as ec-hw (app owns parameter sets, DPB slots, GOP, RC), so the codec logic is shared. MF is a black-box async MFT with per-vendor quirks and shares nothing. +- Linux gain: NVIDIA proprietary has no VA-API encode; Vulkan Video covers it. +- Cost of (a) alone: loses pre-VCN AMD, older Intel, and the existing proven path. Cost of (b): a Windows backend nobody here can test, and zero shared code. +- Known hole: Intel on Windows (see Q1). Until phase 6 it falls back to the software encoders already in this workspace. + +## Evidence + +Update 2026-11-25 (after the charter): `mesa-vulkan-drivers-freeworld` 26.2.7 is installed. H.264/H.265 encode and decode now enumerate (qf2 decode H264|H265|AV1|VP9, qf3 encode H264|H265|AV1); H.264 encode: refs 2, maxP 2, CABAC/CAVLC, 8x8 transform, NV12 encode source with STORAGE usage. User: first-party unsafe shim approved (option 1). + +### Measured on this machine (RX 9060 XT, RADV, Mesa 26.2.7, `RADV_PERFTEST` unset) + +Probes: `/tmp/claude-1000/-home-tahinli-Documents-Code-Rust-edith-codecs/7157f4ec-94bf-4064-bfe0-585b17ba11a7/scratchpad/vkprobe` and `.../scratchpad/vkprobe2`. + +- **No `RADV_PERFTEST` needed**: video queues enumerate by default (qf2 decode, qf3 encode). +- **The brief's "machine fact" is wrong for H.264/H.265.** Device extensions present: `video_queue`, `video_decode_queue`, `video_encode_queue`, `video_decode_av1`, `video_decode_vp9`, `video_encode_av1`, `video_encode_intra_refresh`, `video_encode_quantization_map`, `video_maintenance1/2`, `VALVE_video_encode_rgb_conversion`. **Absent: `video_decode_h264/h265`, `video_encode_h264/h265`.** Queue families advertise only `DECODE_AV1|DECODE_VP9` and `ENCODE_AV1`. + Cause: `mesa-vulkan-drivers` is Fedora stock (patent-stripped); only `mesa-va-drivers-freeworld` is installed. The strings exist in `libvulkan_radeon.so`, but the codecs are compiled out. `mesa-vulkan-drivers-freeworld-26.2.7` is available in the enabled repos. +- AV1 encode: 8192x4352, RC `DISABLED|CBR|VBR`, 4 RC layers, 4 temporal layers, 1 single reference, SB 64. VP9/AV1 decode: 8192x4352, 9 DPB slots, `DPB_AND_OUTPUT_DISTINCT`. +- H.264/H.265 capability queries returned SUCCESS anyway (RADV answers without checking the build). Those numbers are not trustworthy until freeworld is installed. +- Interop extensions present: `EXT_external_memory_dma_buf`, `EXT_image_drm_format_modifier`, `EXT_queue_family_foreign`, `KHR_external_memory_fd`, `KHR_sampler_ycbcr_conversion`. +- `B8G8R8A8_UNORM`: 9 DRM modifiers, all with `SAMPLED|STORAGE|COLOR_ATTACHMENT|BLIT_SRC|BLIT_DST`. +- NV12 encode-source images accept extra usage `STORAGE` and `COLOR_ATTACHMENT`, tilings OPTIMAL/LINEAR/DRM_FORMAT_MODIFIER, create flags `MUTABLE_FORMAT|EXTENDED_USAGE` (per-plane R8/RG8 views are allowed). +- **RGB encode source works on RADV** (`VALVE_video_encode_rgb_conversion`, AV1 profile): `B8G8R8A8`/`R8G8B8A8` as `VIDEO_ENCODE_SRC`, including **DRM_FORMAT_MODIFIER tiling**, with `TRANSFER_DST|SAMPLED|COLOR_ATTACHMENT`. BT.709 narrow range only. + +### Crates (checked in the registry / crates.io today) + +| crate | state | verdict | +|---|---|---| +| ash 0.38.0+1.3.281 | latest release (2024). Has H.264/H.265 encode, AV1 decode. **No AV1 encode, no VP9 decode.** 0.39 unreleased | rejected: misses exactly the codecs this machine exposes | +| pixelforge-ash 0.38.1+1.4.352 | single-maintainer fork of ash master (different API from 0.38: `push`, `load`). Has everything | usable, bus factor 1 | +| vulkanalia / vulkanalia-sys 0.35.0 | upstream release. `structs.rs`/`video.rs` contain AV1 encode, VP9 decode, intra refresh, VALVE RGB conversion, StdVideo* | **chosen binding** | +| vulkano 0.35.2 | no video API (draft PR closed 2026-05, issue open) | rejected | +| gpu-video 0.5.0 (ex vk-video) | 22.5k lines, 289 `unsafe`, pulls wgpu 30 + ash 0.38 + vk-mem; H.264 enc/dec, H.265 enc only; no DMA-BUF import | rejected as dependency, useful as reference | +| windows 0.62.2 | covers D3D11, D3D12 Video, MF, WGC; every COM method is `unsafe fn` | only for phase 4/6 shims | + +No safe wrapper with Vulkan Video exists. Every Vulkan call is `unsafe` in all bindings. + +### Binding choice: own crate, borrowed types + +User direction (2026-11-25): forging our own Vulkan crate is acceptable. So: +- The safe layer **is** our own crate (`shims/vk-video-ffi`); no existing wrapper is adopted. +- Raw types and function pointers come from `vulkanalia-sys 0.35` only (generated structs, no logic). The high-level `vulkanalia` crate is not needed; the loader is `libloading` plus ~40 `vkGet*ProcAddr` lookups inside the shim. +- Not hand-writing the raw layer now: the video subset is ~40 commands but several hundred `Vk*`/`StdVideo*` structs with bitfields, about 4-6k lines of transcription with layout risk and no gain (YAGNI). +- Exit: if vulkanalia-sys lags a header we need, replace it inside the shim with a hand-written or `vk.xml`/`video.xml`-generated subset. Nothing above the shim sees raw types, so the swap is local. + +### Web research (delegated; source quality noted) + +- NVIDIA Windows: decode H.264/H.265 since 2022, AV1 2024, VP9 2025; encode H.264/H.265 since late 2023, AV1 since 2024-11 (NVIDIA Vulkan driver page). +- AMD Windows: encode H.264/H.265 in Adrenalin 25.6.1, AV1 in 25.10.2 (**search snippets only**; AMD decode on Windows unconfirmed). +- Intel Windows: H.264/H.265 **decode** only (driver 101.4314, snippet). **No evidence of Vulkan encode.** +- D3D12 Video Encode: H.264/HEVC on Windows 11, AV1 on 24H2; NVIDIA GTX 10+, Intel Tiger Lake+, AMD RX 5000+ (Microsoft docs/devblog). +- Dozen/WARP: no evidence of Vulkan Video. A GPU-less VM has no video queues. + +## Answers + +**Q1 Windows driver reality.** Vulkan Video: NVIDIA complete; AMD encode yes (snippet-level), decode unconfirmed; Intel no encode. D3D12 Video/MF cover all three vendors. So Vulkan-only on Windows misses Intel encode. Phase 0 ships a probe binary so this is measured on real machines instead of read from release notes. + +**Q2 Linux zero-copy.** Feasible, three paths, picked per device at session creation: +- `RgbDirect`: import the BGRx DMA-BUF (`dma_buf` + `drm_format_modifier`, explicit modifier and plane layout) as the encode source itself. Zero passes. RADV only (VALVE extension), BT.709 narrow. Confirmed by capability query; not yet by an actual encode. +- `BlitRgb`: `vkCmdBlitImage` (linear) from the import to a smaller BGRA encode-source image. Simulcast layers on RADV, no shader. +- `ComputeNv12`: portable path. One compute pass samples the import and writes the NV12 encode-source image through R8 and RG8 plane views (`STORAGE` on encode source confirmed here). Scale and RGB to YCbCr in the same pass. One SPIR-V blob, committed. +Open: the imported image must be created with the video profile list when used as direct encode source; queue-family transfer from graphics/compute to the encode queue costs one barrier pair. + +**Q3 Windows capture.** `VK_KHR_external_memory_win32` defines `D3D11_TEXTURE` (NT handle) and `D3D11_TEXTURE_KMT`. WGC frame-pool textures are not shareable, so: `CopyResource` into a texture created with `SHARED_NTHANDLE` (GPU copy, no CPU touch), import that into Vulkan, then `ComputeNv12`. Per-vendor import support is unconfirmed (NVIDIA reported working, Intel reported failing, both anecdotal). Session creation queries `vkGetPhysicalDeviceImageFormatProperties2` with the handle type; on failure the layer takes a CPU upload. Feeding D3D11 textures straight into a D3D11 video processor + encoder is more robust; that is the price of this decision and the argument for phase 6. + +**Q4 First value.** VA-API already gives yumush zero-copy encode on AMD/Intel Linux. New value is Windows and NVIDIA Linux, so **encode comes before decode**, and H.264 first (the codec all Windows Vulkan encoders have). + +**Q5 Testing without a Windows GPU.** +1. All codec logic and the whole Vulkan path run on Linux against VA-API and ffmpeg. +2. `cargo check --target x86_64-pc-windows-msvc` (target installed; no linker needed) for `cfg(windows)` code. +3. Khronos validation layers on in every Linux test run: RADV is lenient, NVIDIA is not. +4. Windows VM: probe + "no video queue gives `Error::Unsupported` and software fallback" (this is exactly what the VM can show). +5. `ec-vk` example `selftest` (headless: encode, decode, PSNR, caps dump) to run on any borrowed Windows GPU machine. +6. An NVIDIA Linux box approximates NVIDIA Windows (shared driver core). + +**Q6 Keep VA-API.** Yes, frozen. Cost: only the vendored cros-libva. Value: pre-VCN AMD and older Intel, md5 oracle for the Vulkan decoder, PSNR reference for the encoder. Default on Linux stays VA until phase 3 gates pass, then Vulkan first, VA second. + +## Crate layout + +| crate | unsafe | role | +|---|---|---| +| `shims/vk-video-ffi` (new, ours) | **yes, the only place** | safe RAII API over `vulkanalia-sys` raw types: instance/device/queues, images (create, import fd / win32 handle, export), mapped bitstream buffers behind slice closures, video session + parameters, a closed command set (video begin/end/control, decode, encode, blit, copy, barrier, dispatch), fences, feedback queries, compute pipeline from SPIR-V bytes. Builds every `StdVideo*`/`pNext` chain from plain owned Rust structs, so no pointer crosses its API. Estimate 2.5-3k lines, ~40 Vulkan entry points, ~70 unsafe call sites | +| `crates/ec-vk` (new) | forbid | analog of ec-va: device pick, caps (`enum Codec x enum Direction`), image pool, `enum Convert { RgbDirect, BlitRgb, ComputeNv12 }`, frame export | +| `crates/ec-hw` (refactor) | forbid | codec core + `enum Backend { Va, Vk }`, features `va` (Linux) and `vk` | +| `shims/d3d11-share` (phase 4) | yes, ~150 lines | shared-NT-handle texture + `CopyResource`, over `windows` | + +Soundness limit, stated plainly: Vulkan validity rules (image layouts, slot activation) cannot all be typed. The shim enforces them with runtime state enums on a closed command set and is tested under validation layers. This follows the cros-libva precedent in spirit, but the shim is ours, not vendored third-party code. + +### Backend shape + +```rust +enum Backend { Va(VaSession), Vk(VkSession) } + +impl Backend { + fn decode(&mut self, pic: &DecodePicture) -> Result; + fn encode(&mut self, pic: &EncodePicture, src: &Source) -> Result; +} +``` + +`DecodePicture`/`EncodePicture` are neutral per-codec enums (parsed parameter sets, slot index, reference slots with POC/frame_num, slice offsets). Each backend translates them: VA through today's `params/*`, Vulkan through `vk-video-ffi`. + +Share estimate of ec-hw (11.5k lines): +- Backend-independent, ~60%: `dec/dpb264.rs`, the DPB/RPS/ref logic in `dec/{h264,hevc,av1,vp9}.rs`, `enc/headers.rs` SPS/PPS/VPS/AV1 sequence header, GOP + keyframe-on-demand, RC feedback, level selection, `reset.rs`, errors. +- VA-specific, ~40%: `params/*` (1.8k), `Session` in `dec/mod.rs`, surface upload/VPP half of `enc/mod.rs`, `frame.rs`, `pool.rs`, and `headers::h264_slice_header` (Vulkan drivers write slice headers themselves). +- Public API leaks VA types today (`Rc`, `Surface`, `Frame::surface()`). New neutral constructors are added; the VA signatures stay. + +## Phases + +Effort in focused dev-days. Subagents run `cargo check` only; the parent runs tests. + +| # | work | days | acceptance | +|---|---|---|---| +| 0 | Install `mesa-vulkan-drivers-freeworld` (user, sudo). `ec-vk` example `caps` from the probes. Run it in the Windows VM | 1 | H.264/H.265 extensions enumerate here; caps matrix recorded in the report | +| 1 | `vk-video-ffi` core + `ec-vk`; **H.264 encode** from I420 upload; then H.265 and AV1 | 8 | ffmpeg decodes every frame; PSNR within 0.3 dB of the VA encoder at equal bitrate (CBR 8 Mb/s 1080p); bitrate within 5%; forced IDR lands on the requested frame; SPS/PPS from `vkGetEncodedVideoSessionParametersKHR` equal `headers.rs` bytes when the driver reports no overrides (otherwise the driver's bytes are the single source); validation layers clean | +| 2 | ec-hw refactor to `enum Backend`; neutral picture structs | 4 | existing VA tests and md5 gates unchanged | +| 3 | **Linux zero-copy**: DMA-BUF import + `Convert`; simulcast (one import, N layers) | 5 | BGRx import at 3 layer sizes; PSNR within 0.5 dB of VA `submit_prime`; no CPU map on the path; then flip Linux default to Vulkan | +| 4 | **Windows**: `cfg(windows)` build, win32 handle import, `d3d11-share`, `selftest` | 4 + hardware access | `cargo check` for msvc clean; VM returns `Unsupported` cleanly; selftest passes on one real NVIDIA or AMD Windows machine | +| 5 | **Decode** H.264, H.265, AV1, VP9 on the shared DPB code; output as DMA-BUF / win32 handle / I420 | 8 | md5 equals VA path equals ffmpeg on the benchhw clips (1800/1800 each) | +| 6 | Conditional: D3D12 Video backend as third `Backend` variant | 10+ | only with a Windows GPU box and probe data showing Intel demand | + +AV1 encode and AV1/VP9 decode can start before phase 0 completes; they work on the stock driver. + +## Risks + +- **Intel Windows has no hardware encode until phase 6.** Mitigation: software fallback, probe data, phase 6. +- Windows results rest on release notes and snippets, not measurements. Phase 0 probe fixes that. +- D3D11 texture import into Vulkan is unproven per vendor. Fallback is a CPU upload for that layer. +- Driver spread: RADV accepts what NVIDIA rejects. Validation layers in tests; selftest on real hardware before claiming Windows support. +- Probe caveat: a capabilities query without the codec capability struct in the chain segfaults inside RADV (probe bug, fixed), and the RGB-conversion check was run for AV1 only; H.264/H.265 with RGB source is unmeasured until phase 0. +- `RgbDirect` is confirmed by capability query only, and is BT.709 narrow only; `ComputeNv12` is the baseline, `RgbDirect` an optimisation. +- H.264 CQP: AV1 reports `DISABLED|CBR|VBR`; H.264/H.265 RC modes must be re-read after phase 0. +- The unsafe shim is new first-party unsafe code (~3k lines). Keep the command set closed and small; no general Vulkan wrapper. +- Fedora-stock users get AV1/VP9 only on both VA and Vulkan; software codecs cover the rest.