forge
Explore
Log in

Don't you dare go Hollow

ec-av1: StreamDecoder, a persistent decoder fed one temporal unit at a time (decode / decode_temporal_unit), so inter frames decode across calls; decode_stream_with_threads is a wrapper over it; lanes: hwvideo charter (Vulkan Video first, VA frozen)

Browse files at this commit

b63bf80b30de2314eadb4ffd66d23402184a55b1Ahmet Kaan GümüşParent: 19320a9
crates/ec-av1/src/stream/mod.rsmodified+155 -58
@@ -856,43 +856,13 @@ fn collect_one(
856 reorder.drain(sink)856 reorder.drain(sink)
857 }857 }
858 858
859-/// [`decode_stream_with`] with an explicit worker count (lane-thread2).859+/// A persistent AV1 stream decoder: feed it temporal units in decode order.
860-///860+pub struct StreamDecoder {
861-/// `threads == 1` is the serial decoder. Above that, frames that no later
862-/// frame can reference -- a shown, non-key frame whose `refresh_frame_flags`
863-/// is 0, i.e. a leaf of the reference graph -- are decoded on worker threads
864-/// while the main thread keeps parsing headers and decoding the frames that
865-/// DO feed the reference banks; `sink` still sees every picture in coded
866-/// order. Each worker owns a fresh [`crate::decode::FrameCtx`] and a snapshot
867-/// of the banks taken before dispatch, so no decode state is shared.
868-///
869-/// The per-decode counters this crate's gates read are thread-local, so at
870-/// `threads > 1` a leaf frame's counts land on the worker and are invisible
871-/// to the caller; that is why the default is 1.
872-///
873-/// # Errors
874-/// As [`decode_stream_with`]; a worker's error aborts the stream.
875-pub fn decode_stream_with_threads(
876- data: &[u8],
877 threads: usize,861 threads: usize,
878- mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>,862+ final_dump: Option<String>,
879-) -> Result<()> {863+ parser: Av1Parser,
880- // lane-pool1: this replaced a `std::thread::scope` -- frame workers now864+ pictures_shown: usize,
881- // come from a persistent pool (one per submitting thread, workers reused865+ pictures_decoded: usize,
882- // across frames, so their `thread_local!` decode scratch survives the
883- // frame). `jobs` is declared here and dropped at the end of the function,
884- // including on `?`, so no job outlives the data it borrows.
885- let jobs = crate::par::Batch::new("ec-av1-frame");
886- // lane-av1recon: at more than one decode thread the recon wavefront and
887- // the filter bands default on (an explicit env value still wins).
888- let _split = crate::par::DecodeSplit::install(threads);
889- // lane-thread1: this stream's per-frame decode state (was 38 thread_local
890- // statics in decode.rs) -- one object, threaded down the decode call graph.
891- let fctx = &crate::decode::FrameCtx::new();
892- let final_dump = final_dump_prefix();
893- let mut parser = Av1Parser::new();
894- let mut pictures_shown: usize = 0;
895- let mut pictures_decoded: usize = 0;
896 // Spec 7.20/7.4: each of the 8 reference slots remembers the picture a866 // Spec 7.20/7.4: each of the 8 reference slots remembers the picture a
897 // previous frame's `refresh_frame_flags` stored into it, exactly like the867 // previous frame's `refresh_frame_flags` stored into it, exactly like the
898 // CDF slots below -- `LAST_FRAME` names a slot via `ref_frame_idx[0]`,868 // CDF slots below -- `LAST_FRAME` names a slot via `ref_frame_idx[0]`,
@@ -907,55 +877,49 @@ pub fn decode_stream_with_threads(
907 // what made it look like a rounding bug rather than a wrong reference.877 // what made it look like a rounding bug rather than a wrong reference.
908 // lane-pool1: shared, not owned -- a frame refreshing k slots used to copy878 // lane-pool1: shared, not owned -- a frame refreshing k slots used to copy
909 // its whole picture k times, and its output a (k+1)-th time.879 // its whole picture k times, and its output a (k+1)-th time.
910- let mut ref_slots: [Option<std::sync::Arc<Picture>>; NUM_REF_FRAMES] =880+ ref_slots: [Option<std::sync::Arc<Picture>>; NUM_REF_FRAMES],
911- std::array::from_fn(|_| None);
912 // lane-av1tmvp: each of the 8 reference slots' own saved temporal motion881 // lane-av1tmvp: each of the 8 reference slots' own saved temporal motion
913 // field (spec 7.9's per-frame `MotionFieldMvs` storage, libaom882 // field (spec 7.9's per-frame `MotionFieldMvs` storage, libaom
914 // `cur_frame->mvs`) plus the `OrderHint` the picture in that slot was883 // `cur_frame->mvs`) plus the `OrderHint` the picture in that slot was
915 // decoded with -- `Picture` itself carries neither, so both ride884 // decoded with -- `Picture` itself carries neither, so both ride
916 // alongside `ref_slots` on the exact same `refresh_frame_flags` update.885 // alongside `ref_slots` on the exact same `refresh_frame_flags` update.
917- let mut motion_field_slots: [Option<crate::motion_field::MotionField>; NUM_REF_FRAMES] =886+ motion_field_slots: [Option<crate::motion_field::MotionField>; NUM_REF_FRAMES],
918- std::array::from_fn(|_| None);887+ order_hint_slots: [u32; NUM_REF_FRAMES],
919- let mut order_hint_slots: [u32; NUM_REF_FRAMES] = [0; NUM_REF_FRAMES];
920 // Spec 7.20/7.4: each of the 8 reference slots remembers the CDF state a888 // Spec 7.20/7.4: each of the 8 reference slots remembers the CDF state a
921 // previous frame's `refresh_frame_flags` stored into it -- the frame's889 // previous frame's `refresh_frame_flags` stored into it -- the frame's
922 // own end-of-tile adapted table, or (when the frame set890 // own end-of-tile adapted table, or (when the frame set
923 // `disable_frame_end_update_cdf`) the table it started from, unchanged.891 // `disable_frame_end_update_cdf`) the table it started from, unchanged.
924- let mut cdf_slots: [Option<Cdfs>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);892+ cdf_slots: [Option<Cdfs>; NUM_REF_FRAMES],
925 // lane-seg, spec 7.20's `SavedSegmentIds`: each reference slot also893 // lane-seg, spec 7.20's `SavedSegmentIds`: each reference slot also
926 // remembers the segment map the frame stored there decoded, which is what894 // remembers the segment map the frame stored there decoded, which is what
927 // a later frame's `primary_ref_frame` reads back as `PrevSegmentIds`895 // a later frame's `primary_ref_frame` reads back as `PrevSegmentIds`
928 // (spec `load_previous_segment_ids`) for temporal segment-id prediction896 // (spec `load_previous_segment_ids`) for temporal segment-id prediction
929 // and for a `segmentation_update_map == 0` frame's inherited map.897 // and for a `segmentation_update_map == 0` frame's inherited map.
930- let mut seg_map_slots: [Option<Vec<u8>>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);898+ seg_map_slots: [Option<Vec<u8>>; NUM_REF_FRAMES],
931-
932 // lane-thread2: output plumbing (inert at `threads == 1`, where nothing899 // lane-thread2: output plumbing (inert at `threads == 1`, where nothing
933 // is ever dispatched and `reorder` emits each picture the moment it is900 // is ever dispatched and `reorder` emits each picture the moment it is
934 // pushed).901 // pushed).
935- let mut emit_seq = 0usize;902+ emit_seq: usize,
936- let mut reorder = Reorder::default();903+ reorder: Reorder,
937 // lane-thread3: frame decodes and `show_existing_frame` outputs are904 // lane-thread3: frame decodes and `show_existing_frame` outputs are
938 // bounded separately -- an output job is a promise wait plus a memcpy, so905 // bounded separately -- an output job is a promise wait plus a memcpy, so
939 // letting it eat a decode's budget just idles a core (measured: sharing906 // letting it eat a decode's budget just idles a core (measured: sharing
940 // one bound cost 4K 18.7 s at 244% CPU against 17.7 s at 287%).907 // one bound cost 4K 18.7 s at 244% CPU against 17.7 s at 287%).
941- let mut in_flight_decodes = 0usize;908+ in_flight_decodes: usize,
942- let mut in_flight_shows = 0usize;909+ in_flight_shows: usize,
943- let in_flight_cap = threads + 2;910+ tx: std::sync::mpsc::Sender<LeafResult>,
944- let (tx, rx) = std::sync::mpsc::channel::<LeafResult>();911+ rx: std::sync::mpsc::Receiver<LeafResult>,
945 // lane-thread3: at `threads > 1` THIS is the reference bank -- one912 // lane-thread3: at `threads > 1` THIS is the reference bank -- one
946 // [`SlotPromise`] per DPB slot, ready for a slot the parsing thread filled913 // [`SlotPromise`] per DPB slot, ready for a slot the parsing thread filled
947 // itself and pending for one an in-flight frame will fill. The owned914 // itself and pending for one an in-flight frame will fill. The owned
948 // arrays above are then untouched (and the single-threaded path never915 // arrays above are then untouched (and the single-threaded path never
949 // creates a promise: it stays exactly the decoder it was, which is what916 // creates a promise: it stays exactly the decoder it was, which is what
950 // keeps every counter-reading gate meaningful).917 // keeps every counter-reading gate meaningful).
951- let mut slot_promises: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES] =918+ slot_promises: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES],
952- std::array::from_fn(|_| None);
953 // lane-timeline: which decoded frame installed each slot's promise, so919 // lane-timeline: which decoded frame installed each slot's promise, so
954 // the timeline records a dependency EDGE (frame -> producing frame) and920 // the timeline records a dependency EDGE (frame -> producing frame) and
955 // not just a slot number. `usize::MAX` = nobody yet.921 // not just a slot number. `usize::MAX` = nobody yet.
956- let mut slot_owner = [usize::MAX; NUM_REF_FRAMES];922+ slot_owner: [usize; NUM_REF_FRAMES],
957-
958- let mut pos = 0usize;
959 // A frame whose tiles are split across several `OBU_TILE_GROUP`s (spec923 // A frame whose tiles are split across several `OBU_TILE_GROUP`s (spec
960 // 5.11.1, aomenc's `--num-tile-groups`) sends a standalone924 // 5.11.1, aomenc's `--num-tile-groups`) sends a standalone
961 // `OBU_FRAME_HEADER` first, with `show_existing_frame == false` and no925 // `OBU_FRAME_HEADER` first, with `show_existing_frame == false` and no
@@ -963,8 +927,101 @@ pub fn decode_stream_with_threads(
963 // only ever folds ONE tile group into the header's own OBU. Stash the927 // only ever folds ONE tile group into the header's own OBU. Stash the
964 // header here and accumulate tiles from each `OBU_TILE_GROUP` that928 // header here and accumulate tiles from each `OBU_TILE_GROUP` that
965 // follows until every tile of the frame has arrived.929 // follows until every tile of the frame has arrived.
966- let mut pending_header: Option<Box<FrameHeader>> = None;930+ pending_header: Option<Box<FrameHeader>>,
967- let mut pending_tiles: Vec<Tile> = Vec::new();931+ pending_tiles: Vec<Tile>,
932+ // lane-thread1: this stream's per-frame decode state (was 38 thread_local
933+ // statics in decode.rs) -- one object, threaded down the decode call graph.
934+ fctx: crate::decode::FrameCtx,
935+}
936+impl StreamDecoder {
937+ /// A decoder with `threads` frame workers (see [`decode_stream_with_threads`]).
938+ pub fn new(threads: usize) -> Self {
939+ let (tx, rx) = std::sync::mpsc::channel::<LeafResult>();
940+ Self {
941+ threads,
942+ final_dump: final_dump_prefix(),
943+ parser: Av1Parser::new(),
944+ pictures_shown: 0,
945+ pictures_decoded: 0,
946+ ref_slots: std::array::from_fn(|_| None),
947+ motion_field_slots: std::array::from_fn(|_| None),
948+ order_hint_slots: [0; NUM_REF_FRAMES],
949+ cdf_slots: std::array::from_fn(|_| None),
950+ seg_map_slots: std::array::from_fn(|_| None),
951+ emit_seq: 0,
952+ reorder: Reorder::default(),
953+ in_flight_decodes: 0,
954+ in_flight_shows: 0,
955+ tx,
956+ rx,
957+ slot_promises: std::array::from_fn(|_| None),
958+ slot_owner: [usize::MAX; NUM_REF_FRAMES],
959+ pending_header: None,
960+ pending_tiles: Vec::new(),
961+ fctx: crate::decode::FrameCtx::new(),
962+ }
963+ }
964+
965+ /// Decode one temporal unit and return its shown pictures.
966+ ///
967+ /// # Errors
968+ /// As [`decode_stream`]. After an error, start a new decoder at a key frame.
969+ pub fn decode_temporal_unit(&mut self, data: &[u8]) -> Result<Vec<Picture>> {
970+ let mut pictures = Vec::new();
971+ self.decode(data, |picture, _decode_idx, shown| {
972+ if shown {
973+ pictures.push(picture.clone());
974+ }
975+ Ok(())
976+ })?;
977+ Ok(pictures)
978+ }
979+
980+ /// Decode whole frames from `data` (one or more temporal units), handing
981+ /// every picture to `sink` as [`decode_stream_with`] does, before returning.
982+ ///
983+ /// # Errors
984+ /// As [`decode_stream_with`].
985+ pub fn decode(
986+ &mut self,
987+ data: &[u8],
988+ mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
989+ ) -> Result<()> {
990+ let mut pictures_shown = self.pictures_shown;
991+ let mut pictures_decoded = self.pictures_decoded;
992+ let mut emit_seq = self.emit_seq;
993+ let mut in_flight_decodes = self.in_flight_decodes;
994+ let mut in_flight_shows = self.in_flight_shows;
995+ let mut order_hint_slots = self.order_hint_slots;
996+ let mut slot_owner = self.slot_owner;
997+ let mut reorder = std::mem::take(&mut self.reorder);
998+ let mut pending_header = self.pending_header.take();
999+ let mut pending_tiles = std::mem::take(&mut self.pending_tiles);
1000+ let threads = self.threads;
1001+ let StreamDecoder {
1002+ final_dump,
1003+ parser,
1004+ ref_slots,
1005+ motion_field_slots,
1006+ cdf_slots,
1007+ seg_map_slots,
1008+ tx,
1009+ rx,
1010+ slot_promises,
1011+ fctx,
1012+ ..
1013+ } = self;
1014+ // lane-pool1: this replaced a `std::thread::scope` -- frame workers now
1015+ // come from a persistent pool (one per submitting thread, workers reused
1016+ // across frames, so their `thread_local!` decode scratch survives the
1017+ // frame). `jobs` is declared here and dropped at the end of the function,
1018+ // including on `?`, so no job outlives the data it borrows.
1019+ let jobs = crate::par::Batch::new("ec-av1-frame");
1020+ // lane-av1recon: at more than one decode thread the recon wavefront and
1021+ // the filter bands default on (an explicit env value still wins).
1022+ let _split = crate::par::DecodeSplit::install(threads);
1023+ let in_flight_cap = threads + 2;
1024+ let mut pos = 0usize;
968 while pos < data.len() {1025 while pos < data.len() {
969 let obu = parser.parse_obu(&data[pos..])?;1026 let obu = parser.parse_obu(&data[pos..])?;
970 let obu_offset = pos;1027 let obu_offset = pos;
@@ -1637,7 +1694,47 @@ pub fn decode_stream_with_threads(
1637 &mut sink,1694 &mut sink,
1638 )?;1695 )?;
1639 }1696 }
1640- debug_assert!(reorder.pending.is_empty(), "a frame was never emitted");1697+ self.pictures_shown = pictures_shown;
1698+ self.pictures_decoded = pictures_decoded;
1699+ self.emit_seq = emit_seq;
1700+ self.in_flight_decodes = in_flight_decodes;
1701+ self.in_flight_shows = in_flight_shows;
1702+ self.order_hint_slots = order_hint_slots;
1703+ self.slot_owner = slot_owner;
1704+ self.reorder = reorder;
1705+ self.pending_header = pending_header;
1706+ self.pending_tiles = pending_tiles;
1707+ Ok(())
1708+ }
1709+}
1710+
1711+/// [`decode_stream_with`] with an explicit worker count (lane-thread2).
1712+///
1713+/// `threads == 1` is the serial decoder. Above that, frames that no later
1714+/// frame can reference -- a shown, non-key frame whose `refresh_frame_flags`
1715+/// is 0, i.e. a leaf of the reference graph -- are decoded on worker threads
1716+/// while the main thread keeps parsing headers and decoding the frames that
1717+/// DO feed the reference banks; `sink` still sees every picture in coded
1718+/// order. Each worker owns a fresh [`crate::decode::FrameCtx`] and a snapshot
1719+/// of the banks taken before dispatch, so no decode state is shared.
1720+///
1721+/// The per-decode counters this crate's gates read are thread-local, so at
1722+/// `threads > 1` a leaf frame's counts land on the worker and are invisible
1723+/// to the caller; that is why the default is 1.
1724+///
1725+/// # Errors
1726+/// As [`decode_stream_with`]; a worker's error aborts the stream.
1727+pub fn decode_stream_with_threads(
1728+ data: &[u8],
1729+ threads: usize,
1730+ sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
1731+) -> Result<()> {
1732+ let mut decoder = StreamDecoder::new(threads);
1733+ decoder.decode(data, sink)?;
1734+ debug_assert!(
1735+ decoder.reorder.pending.is_empty(),
1736+ "a frame was never emitted"
1737+ );
1641 crate::timeline::dump();1738 crate::timeline::dump();
1642 Ok(())1739 Ok(())
1643 }1740 }
crates/ec-av1/src/stream/tests/mod.rsmodified+3 -2
@@ -3,9 +3,11 @@ use crate::encode::{Picture as Pic, encode_sequence_with_ctx};
3 use crate::probe::run_with_stdin;3 use crate::probe::run_with_stdin;
4 use std::process::{Command, Stdio};4 use std::process::{Command, Stdio};
5 5
6-mod support;
7 mod gates_a;6 mod gates_a;
8 mod gates_b;7 mod gates_b;
8+mod layers;
9+mod streaming;
10+mod support;
9 mod t01;11 mod t01;
10 mod t02;12 mod t02;
11 mod t03;13 mod t03;
@@ -16,6 +18,5 @@ mod t07;
16 mod t08;18 mod t08;
17 mod t09;19 mod t09;
18 mod t10;20 mod t10;
19-mod layers;
20 21
21 pub(crate) use gates_a::lock_gate_counters;22 pub(crate) use gates_a::lock_gate_counters;
crates/ec-av1/src/stream/tests/streaming.rsadded+35 -0
@@ -0,0 +1,35 @@
1+use super::*;
2+use crate::encoder::{Av1Encoder, Colour, EncoderConfig};
3+
4+#[test]
5+fn stream_decoder_fed_per_packet_matches_decode_stream() {
6+ let (w, h) = (64, 64);
7+ let mut enc = Av1Encoder::new(EncoderConfig::new(w, h, 120, 30, Colour::Unspecified)).unwrap();
8+ let mut packets: Vec<Vec<u8>> = (0..6)
9+ .flat_map(|t| {
10+ let mut p = Pic::grey(w, h);
11+ for (i, v) in p.y.iter_mut().enumerate() {
12+ *v = ((i % w + t * 3 + (i / w) * 2) % 230) as u16;
13+ }
14+ enc.encode_frames(&p).unwrap()
15+ })
16+ .map(|p| p.data)
17+ .collect();
18+ packets.extend(enc.flush().unwrap().into_iter().map(|p| p.data));
19+ let want = decode_stream(&packets.concat()).unwrap();
20+ let mut dec = StreamDecoder::new(1);
21+ let got: Vec<Picture> = packets
22+ .iter()
23+ .flat_map(|p| {
24+ let pics = dec.decode_temporal_unit(p).unwrap();
25+ assert_eq!(pics.len(), 1);
26+ pics
27+ })
28+ .collect();
29+ assert_eq!(got.len(), want.len());
30+ assert!(
31+ got.iter()
32+ .zip(&want)
33+ .all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v)
34+ );
35+}
lanes/hwvideo.charter.mdadded+147 -0
@@ -0,0 +1,147 @@
1+# lane hwvideo: hardware video backend strategy (charter)
2+
3+Date 2026-11-25. Base `19320a9d`. Decision + plan only; no code changed.
4+Consumer: yumush (QUIC screen share: low latency, simulcast, keyframe on request, no B-frames).
5+
6+## Decision
7+
8+**(c) Hybrid, Vulkan-first.**
9+
10+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).
11+2. **VA-API stays on Linux, frozen** (no new features): fallback for hardware without Vulkan Video, and the test oracle.
12+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.
13+
14+Why:
15+- 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.
16+- 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.
17+- Linux gain: NVIDIA proprietary has no VA-API encode; Vulkan Video covers it.
18+- 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.
19+- Known hole: Intel on Windows (see Q1). Until phase 6 it falls back to the software encoders already in this workspace.
20+
21+## Evidence
22+
23+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).
24+
25+### Measured on this machine (RX 9060 XT, RADV, Mesa 26.2.7, `RADV_PERFTEST` unset)
26+
27+Probes: `/tmp/claude-1000/-home-tahinli-Documents-Code-Rust-edith-codecs/7157f4ec-94bf-4064-bfe0-585b17ba11a7/scratchpad/vkprobe` and `.../scratchpad/vkprobe2`.
28+
29+- **No `RADV_PERFTEST` needed**: video queues enumerate by default (qf2 decode, qf3 encode).
30+- **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`.
31+ 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.
32+- 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`.
33+- H.264/H.265 capability queries returned SUCCESS anyway (RADV answers without checking the build). Those numbers are not trustworthy until freeworld is installed.
34+- 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`.
35+- `B8G8R8A8_UNORM`: 9 DRM modifiers, all with `SAMPLED|STORAGE|COLOR_ATTACHMENT|BLIT_SRC|BLIT_DST`.
36+- 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).
37+- **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.
38+
39+### Crates (checked in the registry / crates.io today)
40+
41+| crate | state | verdict |
42+|---|---|---|
43+| 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 |
44+| 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 |
45+| 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** |
46+| vulkano 0.35.2 | no video API (draft PR closed 2026-05, issue open) | rejected |
47+| 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 |
48+| windows 0.62.2 | covers D3D11, D3D12 Video, MF, WGC; every COM method is `unsafe fn` | only for phase 4/6 shims |
49+
50+No safe wrapper with Vulkan Video exists. Every Vulkan call is `unsafe` in all bindings.
51+
52+### Binding choice: own crate, borrowed types
53+
54+User direction (2026-11-25): forging our own Vulkan crate is acceptable. So:
55+- The safe layer **is** our own crate (`shims/vk-video-ffi`); no existing wrapper is adopted.
56+- 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.
57+- 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).
58+- 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.
59+
60+### Web research (delegated; source quality noted)
61+
62+- 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).
63+- 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).
64+- Intel Windows: H.264/H.265 **decode** only (driver 101.4314, snippet). **No evidence of Vulkan encode.**
65+- D3D12 Video Encode: H.264/HEVC on Windows 11, AV1 on 24H2; NVIDIA GTX 10+, Intel Tiger Lake+, AMD RX 5000+ (Microsoft docs/devblog).
66+- Dozen/WARP: no evidence of Vulkan Video. A GPU-less VM has no video queues.
67+
68+## Answers
69+
70+**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.
71+
72+**Q2 Linux zero-copy.** Feasible, three paths, picked per device at session creation:
73+- `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.
74+- `BlitRgb`: `vkCmdBlitImage` (linear) from the import to a smaller BGRA encode-source image. Simulcast layers on RADV, no shader.
75+- `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.
76+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.
77+
78+**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.
79+
80+**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).
81+
82+**Q5 Testing without a Windows GPU.**
83+1. All codec logic and the whole Vulkan path run on Linux against VA-API and ffmpeg.
84+2. `cargo check --target x86_64-pc-windows-msvc` (target installed; no linker needed) for `cfg(windows)` code.
85+3. Khronos validation layers on in every Linux test run: RADV is lenient, NVIDIA is not.
86+4. Windows VM: probe + "no video queue gives `Error::Unsupported` and software fallback" (this is exactly what the VM can show).
87+5. `ec-vk` example `selftest` (headless: encode, decode, PSNR, caps dump) to run on any borrowed Windows GPU machine.
88+6. An NVIDIA Linux box approximates NVIDIA Windows (shared driver core).
89+
90+**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.
91+
92+## Crate layout
93+
94+| crate | unsafe | role |
95+|---|---|---|
96+| `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 |
97+| `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 |
98+| `crates/ec-hw` (refactor) | forbid | codec core + `enum Backend { Va, Vk }`, features `va` (Linux) and `vk` |
99+| `shims/d3d11-share` (phase 4) | yes, ~150 lines | shared-NT-handle texture + `CopyResource`, over `windows` |
100+
101+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.
102+
103+### Backend shape
104+
105+```rust
106+enum Backend { Va(VaSession), Vk(VkSession) }
107+
108+impl Backend {
109+ fn decode(&mut self, pic: &DecodePicture) -> Result<Frame>;
110+ fn encode(&mut self, pic: &EncodePicture, src: &Source) -> Result<Pending>;
111+}
112+```
113+
114+`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`.
115+
116+Share estimate of ec-hw (11.5k lines):
117+- 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.
118+- 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).
119+- Public API leaks VA types today (`Rc<Display>`, `Surface<PrimeImport>`, `Frame::surface()`). New neutral constructors are added; the VA signatures stay.
120+
121+## Phases
122+
123+Effort in focused dev-days. Subagents run `cargo check` only; the parent runs tests.
124+
125+| # | work | days | acceptance |
126+|---|---|---|---|
127+| 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 |
128+| 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 |
129+| 2 | ec-hw refactor to `enum Backend`; neutral picture structs | 4 | existing VA tests and md5 gates unchanged |
130+| 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 |
131+| 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 |
132+| 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) |
133+| 6 | Conditional: D3D12 Video backend as third `Backend` variant | 10+ | only with a Windows GPU box and probe data showing Intel demand |
134+
135+AV1 encode and AV1/VP9 decode can start before phase 0 completes; they work on the stock driver.
136+
137+## Risks
138+
139+- **Intel Windows has no hardware encode until phase 6.** Mitigation: software fallback, probe data, phase 6.
140+- Windows results rest on release notes and snippets, not measurements. Phase 0 probe fixes that.
141+- D3D11 texture import into Vulkan is unproven per vendor. Fallback is a CPU upload for that layer.
142+- Driver spread: RADV accepts what NVIDIA rejects. Validation layers in tests; selftest on real hardware before claiming Windows support.
143+- 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.
144+- `RgbDirect` is confirmed by capability query only, and is BT.709 narrow only; `ComputeNv12` is the baseline, `RgbDirect` an optimisation.
145+- H.264 CQP: AV1 reports `DISABLED|CBR|VBR`; H.264/H.265 RC modes must be re-read after phase 0.
146+- The unsafe shim is new first-party unsafe code (~3k lines). Keep the command set closed and small; no general Vulkan wrapper.
147+- Fedora-stock users get AV1/VP9 only on both VA and Vulkan; software codecs cover the rest.