forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

hwvideo.charter.md18.3 KiBHistoryRawDownload

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

enum Backend { Va(VaSession), Vk(VkSession) }

impl Backend {
    fn decode(&mut self, pic: &DecodePicture) -> Result<Frame>;
    fn encode(&mut self, pic: &EncodePicture, src: &Source) -> Result<Pending>;
}

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<Display>, Surface<PrimeImport>, 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.

Status 2026-11-25

Done (RADV, RX 9060 XT; every stream bit-exact vs ffmpeg for decode):

  • Phase 1: Vk encode H.264/H.265/AV1 (CQP, CBR), CPU NV12 upload; RGB/BGR input with GPU compute RGB->NV12 + box downscale (one capture feeds every simulcast layer).

  • Phase 2: ec-hw compiles on every OS; HwEncoder/HwDecoder/capabilities(), Vk first, VA fallback on Linux (decoder replays its prefix when Vk refuses a stream, e.g. 10-bit).

  • Phase 5 (pulled forward): Vk decode H.264/H.265/AV1 8-bit behind HwDecoder, shared generic DPB/RPS/ref-slot logic with VA (dpb264, hevc_dpb, av1_refs).

  • Phase 3: DMA-BUF import (encode_dmabuf, linear + tiled modifiers, byte-identical to encode_rgb).

  • 10-bit Vk decode (H.265 Main10, AV1), equal to VA. 10-bit encode not needed (8-bit input API).

  • Runtime rate change on Vk (tune, no IDR); CBR virtual buffer 25/12 ms, rate within ~1%.

  • GPU decode to BGRA/RGBA with downscale (open_rgb/next_rgb), pixel-exact vs CPU reference.

  • Validation layer: zero VUIDs on all examples.

  • VA parity (1:1), d0fd4cb8: Vk VP9 decode (0/2), AV1 film grain (CPU synthesis), 10-bit encode H.265/AV1 + 16-bit decode out, decode DMA-BUF export (NV12/P010) + reset() + missing-ref errors, per-profile capabilities, device-lost -> shared reset epoch, encode config (H.264 profile, colour, gop, forced keyframes), shared VA/Vk rate control (hrd_buffer_ms + RateFeedback; CBR PSNR mean -0.02 dB vs VA), pipelined submit/flush (depth 2; 4K10 HEVC 4.45 vs VA 11.61 ms/frame), NV12/P010 DMA-BUF import with LRU cache. Decode faster than VA on most streams.

  • edith fully on HwDecoder/HwEncoder (edith ff99ad61 on 9c38a593), no ec_va dep: 4K HEVC Main10 export VA 32.9 fps -> Vk 153 fps, output identical. Copy-free decode export spec-invalid on RADV (no modifier/LINEAR decode-dst, VUID 06811); parked on branch worktree-agent-abace82af3984ff7e.

  • ffmpeg oracle (hw_oracle: per-frame framecrc vs ffmpeg/libdav1d sw decode; corpora ~/tmp/ec_corpus): H.264 59, H.265 24, VP9 51, AV1 56 bit-exact on Vk; every other stream is a clean Unsupported (hardware limits: High10/4:2:2/4:4:4 H.264, VP9 profile 1/3 + 12-bit, AV1 mono/12-bit/4:2:2/4:4:4, sizes below minCodedExtent, AMD HEVC CTB16 chroma bug shared by ffmpeg's hwaccels; 49/112 CTB16 streams bad, all with SAO but data-dependent (per-CTU chroma SAO), not decidable from SPS/PPS/slice headers, so all CTB16 on AMD is refused). Fixed on the way: mid-stream size/DPB/depth change, AV1 CDEF raw sec strength (all SVT streams), odd AV1 sizes, sessions sized with driver DPB/active-ref maxima like ffmpeg (stale state after an earlier session). Encode: level selection matches ffmpeg's tables, AV1 timing_info, VA H.264 8x8 transform, VA HEVC VPS timing; 156 streams clean under ffmpeg strict decode.

Open:

  • VA stays (user, 2026-11-25): both backends supported for a while, Vk first, VA fallback. Without Vulkan Video (pre-RDNA AMD, older Intel) VA is the only HW path.
  • Closed: grained AV1 DMA-BUF export (CPU grain + ring upload), two-object NV12/P010 import (single-plane images + copy; RADV has no DISJOINT for modifiers), AV1 seq/frame tools matched to VA (switchable interp, loop filter, primary_ref LAST). AV1 CBR 1 Mb/s: drivers identical at equal rate (unsteered 38.98 vs 38.99 dB); short-clip PSNR delta is VA overshooting target (1043 vs Vk 982 kb/s), not quality. Encode bitstream readback from HOST_CACHED (e22e714c): AV1 1080p pipelined 1.16 vs VA 1.33 ms/frame. Vk >= VA on every measured axis on RX 9060 XT.
  • Phase 4: Windows D3D11 shared-texture import; no Windows GPU to test on (skipped by user).