From 274b9cb95d91511f24b2ddf82e02073ee31a0568 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 25 Nov 2026 08:35:58 +0300 Subject: [PATCH] ec-hw: HwEncoder (Vulkan first, VA fallback on Linux), HwDecoder (VA for now), capabilities() without opening an encoder; compiles on every OS; hw_caps example --- Cargo.lock | 1 + Cargo.toml | 1 + crates/ec-hw/Cargo.toml | 1 + crates/ec-hw/examples/hw_caps.rs | 102 +++++++++ crates/ec-hw/src/error.rs | 9 + crates/ec-hw/src/hw.rs | 373 +++++++++++++++++++++++++++++++ crates/ec-hw/src/lib.rs | 2 + crates/ec-vk/src/lib.rs | 2 +- 8 files changed, 490 insertions(+), 1 deletion(-) create mode 100644 crates/ec-hw/examples/hw_caps.rs create mode 100644 crates/ec-hw/src/hw.rs diff --git a/Cargo.lock b/Cargo.lock index 19393df2..1ea44b76 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -531,6 +531,7 @@ dependencies = [ "ec-h264-syntax", "ec-h265-syntax", "ec-va", + "ec-vk", "ec-vp9-syntax", ] diff --git a/Cargo.toml b/Cargo.toml index 218d0de9..d5f97967 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,6 +29,7 @@ ec-h264-syntax = { path = "crates/ec-h264-syntax", version = "0.1.0" } ec-h265 = { path = "crates/ec-h265", version = "0.1.0" } ec-h265-syntax = { path = "crates/ec-h265-syntax", version = "0.1.0" } ec-hw = { path = "crates/ec-hw", version = "0.1.0" } +ec-vk = { path = "crates/ec-vk", version = "0.1.0" } ec-image = { path = "crates/ec-image", version = "0.1.0" } ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" } ec-mpegts = { path = "crates/ec-mpegts", version = "0.1.0" } diff --git a/crates/ec-hw/Cargo.toml b/crates/ec-hw/Cargo.toml index 0bd2e617..239304e8 100644 --- a/crates/ec-hw/Cargo.toml +++ b/crates/ec-hw/Cargo.toml @@ -11,6 +11,7 @@ ec-av1-syntax.workspace = true ec-core.workspace = true ec-h264-syntax.workspace = true ec-h265-syntax.workspace = true +ec-vk.workspace = true ec-vp9-syntax.workspace = true [target.'cfg(target_os = "linux")'.dependencies] diff --git a/crates/ec-hw/examples/hw_caps.rs b/crates/ec-hw/examples/hw_caps.rs new file mode 100644 index 00000000..e8599e92 --- /dev/null +++ b/crates/ec-hw/examples/hw_caps.rs @@ -0,0 +1,102 @@ +//! Lists hardware capabilities, then encodes a gradient with each codec and decodes the Vulkan streams back. +//! +//! ```text +//! cargo run -p ec-hw --example hw_caps +//! ``` + +use ec_hw::{ + Backend, Codec, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, I420, + RateControlMode, capabilities, +}; + +const FRAMES: u32 = 30; +const WIDTH: u32 = 1280; +const HEIGHT: u32 = 720; + +fn main() { + for cap in capabilities() { + println!( + "{:?} {:?} {:?} max {}x{}", + cap.backend, cap.direction, cap.codec, cap.max_width, cap.max_height + ); + } + for codec in [EncCodec::H264, EncCodec::H265, EncCodec::Av1] { + if let Err(e) = run(codec) { + println!("{codec:?}: error: {e}"); + } + } +} + +fn run(codec: EncCodec) -> ec_hw::Result<()> { + let config = EncoderConfig { + bitrate: 2_000_000, + rate_control: RateControlMode::ConstantBitrate, + ..EncoderConfig::new(codec, WIDTH, HEIGHT) + }; + let mut encoder = match HwEncoder::open(config, None) { + Ok(encoder) => encoder, + Err(e) => { + println!("{codec:?}: no encoder: {e}"); + return Ok(()); + } + }; + let backend = encoder.backend(); + let mut coded = Vec::with_capacity(FRAMES as usize); + for index in 0..FRAMES { + let meta = FrameMetadata { + timestamp: index as i64, + force_keyframe: index == 0, + }; + coded.push(encoder.encode(&gray_gradient(index), meta)?); + } + let bytes: usize = coded.iter().map(|c| c.data.len()).sum(); + println!("{codec:?} {backend:?} {FRAMES} frames {bytes} bytes"); + + if backend != Backend::Vk { + return Ok(()); + } + let mut decoder = match HwDecoder::open(decode_codec(codec)) { + Ok(decoder) => decoder, + Err(e) => { + println!(" decode unavailable: {e}"); + return Ok(()); + } + }; + let mut frames = 0; + for c in &coded { + decoder.decode(&c.data, c.timestamp)?; + while decoder.next_frame()?.is_some() { + frames += 1; + } + } + decoder.flush()?; + while decoder.next_frame()?.is_some() { + frames += 1; + } + println!(" decoded {frames} frames"); + Ok(()) +} + +fn decode_codec(codec: EncCodec) -> Codec { + match codec { + EncCodec::H264 => Codec::H264, + EncCodec::H265 => Codec::H265, + EncCodec::Av1 => Codec::Av1, + } +} + +fn gray_gradient(index: u32) -> I420 { + let (w, h) = (WIDTH as usize, HEIGHT as usize); + let shift = 4 * index as usize; + let y = (0..h) + .flat_map(|row| (0..w).map(move |col| ((col + row + shift) & 0xff) as u8)) + .collect(); + let chroma = w.div_ceil(2) * h.div_ceil(2); + I420 { + y, + u: vec![128; chroma], + v: vec![128; chroma], + width: WIDTH, + height: HEIGHT, + } +} diff --git a/crates/ec-hw/src/error.rs b/crates/ec-hw/src/error.rs index 8c94ccbf..970b1628 100644 --- a/crates/ec-hw/src/error.rs +++ b/crates/ec-hw/src/error.rs @@ -31,6 +31,8 @@ pub enum Error { /// The caller asked for something inconsistent, e.g. feeding H.264 to a /// decoder configured for AV1, or encoding a frame of the wrong size. Config(String), + /// A Vulkan Video call failed or the Vulkan path refused the request. + Vk(String), /// The GPU was reset (a hung ring, a lost context) while this session was /// alive, or a session was asked for during the grace period after one. /// The session is dead; use software. See [`crate::reset`]. @@ -83,6 +85,12 @@ impl From for Error { } } +impl From for Error { + fn from(e: ec_vk::Error) -> Error { + Error::Vk(e.to_string()) + } +} + impl From for Error { fn from(e: ec_core::Error) -> Error { Error::Stream(e) @@ -97,6 +105,7 @@ impl fmt::Display for Error { Error::Stream(e) => write!(f, "bitstream: {e}"), Error::Unsupported { what, why } => write!(f, "{what} is not supported: {why}"), Error::Config(what) => write!(f, "{what}"), + Error::Vk(what) => write!(f, "Vulkan Video: {what}"), Error::HwReset(what) => write!(f, "GPU reset: {what}"), } } diff --git a/crates/ec-hw/src/hw.rs b/crates/ec-hw/src/hw.rs new file mode 100644 index 00000000..fb416cf6 --- /dev/null +++ b/crates/ec-hw/src/hw.rs @@ -0,0 +1,373 @@ +//! One API over Vulkan Video and VA-API. + +use crate::error::{Error, Result}; +use crate::picture::I420; +use crate::types::{Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, RateControlMode}; + +#[cfg(target_os = "linux")] +use crate::dec::Decoder as VaDecoder; +#[cfg(target_os = "linux")] +use crate::enc::Encoder as VaEncoder; + +/// Where a codec runs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Backend { + /// Vulkan Video, every OS. + Vk, + /// VA-API, Linux only. + Va, +} + +/// Which way a codec runs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Direction { + /// Encode. + Encode, + /// Decode. + Decode, +} + +/// One codec, direction and backend this machine offers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Capability { + /// Codec. + pub codec: Codec, + /// Direction. + pub direction: Direction, + /// Largest width in luma samples. + pub max_width: u32, + /// Largest height in luma samples. + pub max_height: u32, + /// Backend offering it. + pub backend: Backend, +} + +thread_local! { + static GPU: Option = ec_vk::Gpu::open().ok(); +} + +fn vk_gpu() -> Option { + GPU.with(|gpu| gpu.clone()) +} + +/// Every codec, direction and backend this machine can use. Never fails. +pub fn capabilities() -> Vec { + let mut out = Vec::new(); + if let Some(gpu) = vk_gpu() { + for caps in gpu.caps().into_iter().filter(|c| c.direction == ec_vk::Direction::Encode) { + let codec = match caps.codec { + ec_vk::Codec::H264 => Codec::H264, + ec_vk::Codec::H265 => Codec::H265, + ec_vk::Codec::Av1 => Codec::Av1, + ec_vk::Codec::Vp9 => Codec::Vp9, + }; + let direction = match caps.direction { + ec_vk::Direction::Encode => Direction::Encode, + ec_vk::Direction::Decode => Direction::Decode, + }; + push( + &mut out, + Capability { + codec, + direction, + max_width: caps.max_width, + max_height: caps.max_height, + backend: Backend::Vk, + }, + ); + } + } + #[cfg(target_os = "linux")] + va_capabilities(&mut out); + out +} + +fn push(out: &mut Vec, cap: Capability) { + let known = out.iter().any(|c| { + c.codec == cap.codec && c.direction == cap.direction && c.backend == cap.backend + }); + if !known { + out.push(cap); + } +} + +#[cfg(target_os = "linux")] +fn va_capabilities(out: &mut Vec) { + let Ok(display) = ec_va::open() else { + return; + }; + let Ok(report) = ec_va::CapReport::probe(&display) else { + return; + }; + for entry in &report.entries { + let Some(codec) = va_codec(entry.profile) else { + continue; + }; + let direction = match entry.entrypoint { + ec_va::Entrypoint::VLD => Direction::Decode, + ec_va::Entrypoint::EncSlice | ec_va::Entrypoint::EncSliceLP => Direction::Encode, + _ => continue, + }; + let (max_width, max_height) = match &entry.surfaces { + Some(s) => (s.max_width.unwrap_or(4096), s.max_height.unwrap_or(4096)), + None => (4096, 4096), + }; + push( + out, + Capability { + codec, + direction, + max_width, + max_height, + backend: Backend::Va, + }, + ); + } +} + +#[cfg(target_os = "linux")] +fn va_codec(profile: ec_va::Profile) -> Option { + Some(match profile { + ec_va::Profile::H264Baseline + | ec_va::Profile::H264ConstrainedBaseline + | ec_va::Profile::H264Main + | ec_va::Profile::H264High + | ec_va::Profile::H264High10 => Codec::H264, + ec_va::Profile::HEVCMain | ec_va::Profile::HEVCMain10 => Codec::H265, + ec_va::Profile::VP9Profile0 => Codec::Vp9, + ec_va::Profile::AV1Profile0 => Codec::Av1, + _ => return None, + }) +} + +/// The Vulkan encoder for one codec. +enum VkEncoder { + H264(ec_vk::H264Encoder), + H265(ec_vk::H265Encoder), + Av1(ec_vk::Av1Encoder), +} + +impl VkEncoder { + fn encode( + &mut self, + frame: &I420, + force_keyframe: bool, + ) -> std::result::Result { + let (y, u, v) = (&frame.y, &frame.u, &frame.v); + match self { + VkEncoder::H264(e) => e.encode(y, u, v, force_keyframe), + VkEncoder::H265(e) => e.encode(y, u, v, force_keyframe), + VkEncoder::Av1(e) => e.encode(y, u, v, force_keyframe), + } + } +} + +enum EncInner { + Vk(VkEncoder), + #[cfg(target_os = "linux")] + Va(VaEncoder), +} + +/// A hardware encoder on whichever backend opened. +pub struct HwEncoder { + inner: EncInner, +} + +impl HwEncoder { + /// Open an encoder. `prefer` = `None` tries Vulkan, then VA-API. + pub fn open(config: EncoderConfig, prefer: Option) -> Result { + let order = match prefer { + Some(backend) => vec![backend], + None => vec![Backend::Vk, Backend::Va], + }; + let mut reasons = Vec::new(); + for backend in order { + match open_backend(backend, config) { + Ok(inner) => return Ok(HwEncoder { inner }), + Err(e) => reasons.push(format!("{backend:?}: {e}")), + } + } + Err(Error::unsupported( + format!("{:?} hardware encode", config.codec), + reasons.join("; "), + )) + } + + /// The backend this encoder runs on. + pub fn backend(&self) -> Backend { + match self.inner { + EncInner::Vk(_) => Backend::Vk, + #[cfg(target_os = "linux")] + EncInner::Va(_) => Backend::Va, + } + } + + /// Encode one frame; `meta.force_keyframe` starts a new GOP. + pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result { + match &mut self.inner { + EncInner::Vk(enc) => { + let coded = enc.encode(frame, meta.force_keyframe)?; + Ok(CodedFrame { + data: coded.data, + timestamp: meta.timestamp, + is_keyframe: coded.keyframe, + }) + } + #[cfg(target_os = "linux")] + EncInner::Va(enc) => enc.encode(frame, meta), + } + } +} + +fn open_backend(backend: Backend, config: EncoderConfig) -> Result { + match backend { + Backend::Vk => open_vk(config).map(EncInner::Vk), + Backend::Va => open_va(config), + } +} + +fn open_vk(config: EncoderConfig) -> Result { + if config.bit_depth != 8 { + return Err(Error::unsupported( + "10-bit Vulkan Video encode", + "the Vulkan encoders are 8-bit", + )); + } + let gpu = vk_gpu().ok_or_else(|| { + Error::unsupported("Vulkan Video encode", "no Vulkan Video device") + })?; + let rate = vk_rate(&config); + let (width, height, fps, gop_size) = + (config.width, config.height, config.framerate, config.gop_size); + Ok(match config.codec { + EncCodec::H264 => VkEncoder::H264(ec_vk::H264Encoder::new( + &gpu, + ec_vk::H264EncoderConfig { + width, + height, + fps, + gop_size, + rate, + }, + )?), + EncCodec::H265 => VkEncoder::H265(ec_vk::H265Encoder::new( + &gpu, + ec_vk::H265EncoderConfig { + width, + height, + fps, + gop_size, + rate, + }, + )?), + EncCodec::Av1 => VkEncoder::Av1(ec_vk::Av1Encoder::new( + &gpu, + ec_vk::Av1EncoderConfig { + width, + height, + fps, + gop_size, + rate, + }, + )?), + }) +} + +fn vk_rate(config: &EncoderConfig) -> ec_vk::RateControl { + match (config.rate_control, config.codec) { + (RateControlMode::ConstantQp { qp }, EncCodec::Av1) => ec_vk::RateControl::ConstantQp { + qp: (qp / 5).min(51) as u8, + }, + (RateControlMode::ConstantQp { qp }, _) => ec_vk::RateControl::ConstantQp { + qp: qp.min(51) as u8, + }, + _ => ec_vk::RateControl::Cbr { + bitrate: config.bitrate, + }, + } +} + +#[cfg(target_os = "linux")] +fn open_va(config: EncoderConfig) -> Result { + let display = ec_va::open()?; + Ok(EncInner::Va(VaEncoder::new(&display, config)?)) +} + +#[cfg(not(target_os = "linux"))] +fn open_va(config: EncoderConfig) -> Result { + Err(Error::unsupported( + format!("{:?} VA-API encode", config.codec), + "VA-API is Linux only", + )) +} + +/// A hardware decoder. Only VA-API decodes for now. +pub struct HwDecoder { + #[cfg(target_os = "linux")] + inner: VaDecoder, +} + +impl HwDecoder { + /// Open a decoder for `codec`. Non-Linux: always `Unsupported`. + pub fn open(codec: Codec) -> Result { + #[cfg(target_os = "linux")] + { + let display = ec_va::open()?; + Ok(HwDecoder { + inner: VaDecoder::new(&display, codec)?, + }) + } + #[cfg(not(target_os = "linux"))] + { + Err(Error::unsupported( + format!("{codec:?} hardware decode"), + "VA-API is Linux only", + )) + } + } + + /// The backend this decoder runs on. + pub fn backend(&self) -> Backend { + Backend::Va + } + + /// Feed one access unit. + pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { + #[cfg(target_os = "linux")] + { + self.inner.decode(data, timestamp) + } + #[cfg(not(target_os = "linux"))] + { + let _ = (data, timestamp); + Err(Error::unsupported("hardware decode", "VA-API is Linux only")) + } + } + + /// The next picture in display order, as 8-bit I420 with its timestamp. + pub fn next_frame(&mut self) -> Result> { + #[cfg(target_os = "linux")] + { + match self.inner.next_frame() { + Some(frame) => Ok(Some((frame.timestamp, frame.to_i420()?))), + None => Ok(None), + } + } + #[cfg(not(target_os = "linux"))] + { + Ok(None) + } + } + + /// Emit every picture still held for reordering. + pub fn flush(&mut self) -> Result<()> { + #[cfg(target_os = "linux")] + { + self.inner.flush() + } + #[cfg(not(target_os = "linux"))] + { + Ok(()) + } + } +} diff --git a/crates/ec-hw/src/lib.rs b/crates/ec-hw/src/lib.rs index 04072bc7..080a8566 100644 --- a/crates/ec-hw/src/lib.rs +++ b/crates/ec-hw/src/lib.rs @@ -59,6 +59,7 @@ pub mod dec; #[cfg(target_os = "linux")] pub mod enc; pub mod error; +pub mod hw; #[cfg(target_os = "linux")] pub mod frame; pub mod picture; @@ -74,6 +75,7 @@ pub use dec::{Decoder, StreamInfo}; #[cfg(target_os = "linux")] pub use enc::Encoder; pub use error::{Error, Result}; +pub use hw::{Backend, Capability, Direction, HwDecoder, HwEncoder, capabilities}; #[cfg(target_os = "linux")] pub use frame::Frame; pub use picture::{Colour, I420, I420_16, i420_to_nv12, nv12_to_i420}; diff --git a/crates/ec-vk/src/lib.rs b/crates/ec-vk/src/lib.rs index 38720386..341021ef 100644 --- a/crates/ec-vk/src/lib.rs +++ b/crates/ec-vk/src/lib.rs @@ -9,7 +9,7 @@ mod h265; pub use av1::{Av1Encoder, Av1EncoderConfig}; pub use h265::{H265Encoder, H265EncoderConfig}; -pub use vk_video_ffi::{Error, Gpu, RateControl}; +pub use vk_video_ffi::{Codec, Direction, Error, Gpu, RateControl}; /// Encoder settings. #[derive(Debug, Clone, Copy, PartialEq, Eq)]