From 184c87ba1fd722fe9c478bed23c8e189319fbec1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 15:18:52 +0300 Subject: [PATCH] S2: hw.rs split into hw/{caps,input,encoder,decoder} by line range (move only; four helpers widened to pub(super) for the new boundaries) --- crates/ec-hw/src/hw.rs | 1348 +------------------------------- crates/ec-hw/src/hw/caps.rs | 231 ++++++ crates/ec-hw/src/hw/decoder.rs | 256 ++++++ crates/ec-hw/src/hw/encoder.rs | 621 +++++++++++++++ crates/ec-hw/src/hw/input.rs | 239 ++++++ 5 files changed, 1356 insertions(+), 1339 deletions(-) create mode 100644 crates/ec-hw/src/hw/caps.rs create mode 100644 crates/ec-hw/src/hw/decoder.rs create mode 100644 crates/ec-hw/src/hw/encoder.rs create mode 100644 crates/ec-hw/src/hw/input.rs diff --git a/crates/ec-hw/src/hw.rs b/crates/ec-hw/src/hw.rs index 49180b56..4ad2f1d6 100644 --- a/crates/ec-hw/src/hw.rs +++ b/crates/ec-hw/src/hw.rs @@ -27,1342 +27,12 @@ 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, -} - -/// Profile of a [`Capability`], 4:2:0 only. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum CodecProfile { - /// H.264 Constrained Baseline, 8-bit. - H264ConstrainedBaseline, - /// H.264 Main, 8-bit. - H264Main, - /// H.264 High, 8-bit. - H264High, - /// H.265 Main, 8-bit. - H265Main, - /// H.265 Main 10, 10-bit. - H265Main10, - /// AV1 Main, 8-bit. - Av1Main, - /// AV1 Main, 10-bit. - Av1Main10, - /// VP9 Profile 0, 8-bit. - Vp9Profile0, - /// VP9 Profile 2, 10-bit. - Vp9Profile2, -} - -/// One codec, profile, direction and backend this machine offers. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Capability { - /// Codec. - pub codec: Codec, - /// Profile. - pub profile: CodecProfile, - /// 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: RefCell)>> = const { RefCell::new(None) }; -} - -pub(crate) fn vk_gpu() -> Option { - GPU.with_borrow_mut(|cached| { - let epoch = crate::reset::gpu_reset_epoch(); - match cached { - Some((born, gpu)) if *born == epoch => gpu.clone(), - _ => { - let gpu = ec_vk::Gpu::open().ok(); - *cached = Some((epoch, gpu.clone())); - gpu - } - } - }) -} - -fn vk_session_alive(born_epoch: u64) -> Result<()> { - if crate::reset::gpu_reset_epoch() == born_epoch { - Ok(()) - } else { - Err(Error::hw_reset( - "the GPU was reset after this Vulkan session was created; its device is lost", - )) - } -} - -fn vk_grace() -> Result<()> { - if crate::reset::gpu_recently_reset() { - Err(Error::hw_reset( - "the GPU was reset moments ago; new Vulkan sessions wait out the grace period", - )) - } else { - Ok(()) - } -} - -/// 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() { - 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, - profile: vk_profile(caps.profile), - 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.profile == cap.profile - && 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 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), - }; - for profile in va_profiles(entry.profile, entry.rt_formats) { - push( - out, - Capability { - codec: profile.codec(), - profile, - direction, - max_width, - max_height, - backend: Backend::Va, - }, - ); - } - } -} - -#[cfg(target_os = "linux")] -impl CodecProfile { - fn codec(self) -> Codec { - match self { - CodecProfile::H264ConstrainedBaseline - | CodecProfile::H264Main - | CodecProfile::H264High => Codec::H264, - CodecProfile::H265Main | CodecProfile::H265Main10 => Codec::H265, - CodecProfile::Av1Main | CodecProfile::Av1Main10 => Codec::Av1, - CodecProfile::Vp9Profile0 | CodecProfile::Vp9Profile2 => Codec::Vp9, - } - } -} - -#[cfg(target_os = "linux")] -fn va_profiles(profile: ec_va::Profile, rt_formats: u32) -> Vec { - let yuv420 = ec_va::va::VA_RT_FORMAT_YUV420; - let yuv420_10 = ec_va::va::VA_RT_FORMAT_YUV420_10; - match profile { - ec_va::Profile::H264ConstrainedBaseline => vec![CodecProfile::H264ConstrainedBaseline], - ec_va::Profile::H264Main => vec![CodecProfile::H264Main], - ec_va::Profile::H264High => vec![CodecProfile::H264High], - ec_va::Profile::HEVCMain => vec![CodecProfile::H265Main], - ec_va::Profile::HEVCMain10 => vec![CodecProfile::H265Main10], - ec_va::Profile::VP9Profile0 => vec![CodecProfile::Vp9Profile0], - ec_va::Profile::VP9Profile2 if rt_formats & yuv420_10 != 0 => vec![CodecProfile::Vp9Profile2], - ec_va::Profile::AV1Profile0 => [ - (yuv420, CodecProfile::Av1Main), - (yuv420_10, CodecProfile::Av1Main10), - ] - .into_iter() - .filter(|(bit, _)| rt_formats & bit != 0) - .map(|(_, p)| p) - .collect(), - _ => Vec::new(), - } -} - -fn vk_profile(profile: ec_vk::CodecProfile) -> CodecProfile { - match profile { - ec_vk::CodecProfile::H264High => CodecProfile::H264High, - ec_vk::CodecProfile::H265Main => CodecProfile::H265Main, - ec_vk::CodecProfile::H265Main10 => CodecProfile::H265Main10, - ec_vk::CodecProfile::Av1Main => CodecProfile::Av1Main, - ec_vk::CodecProfile::Av1Main10 => CodecProfile::Av1Main10, - ec_vk::CodecProfile::Vp9Profile0 => CodecProfile::Vp9Profile0, - ec_vk::CodecProfile::Vp9Profile2 => CodecProfile::Vp9Profile2, - ec_vk::CodecProfile::H264ConstrainedBaseline => CodecProfile::H264ConstrainedBaseline, - ec_vk::CodecProfile::H264Main => CodecProfile::H264Main, - } -} - -/// Byte order of a packed 32-bit RGB pixel; the X or A byte is ignored. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum RgbOrder { - /// Bytes R, G, B, X. - Rgba, - /// Bytes B, G, R, X. - Bgra, -} - -/// A packed 32-bit RGB picture with a row stride in bytes. -#[derive(Debug, Clone, Copy)] -pub struct RgbFrame<'a> { - /// Pixels, `stride * height` bytes at least. - pub data: &'a [u8], - /// Source width in pixels, even; at least the encoder width. - pub width: u32, - /// Source height in pixels, even; at least the encoder height. - pub height: u32, - /// Row stride in bytes, a multiple of 4 and at least `width * 4`. - pub stride: u32, - /// Byte order of each pixel. - pub order: RgbOrder, -} - -/// A two-plane DMA-BUF of NV12 or P010 pixels, one or two objects (one per plane). -#[cfg(target_os = "linux")] -#[derive(Debug, Clone, Copy)] -pub struct DmaBufYuvFrame<'a> { - /// DMA-BUF file descriptors, duplicated by the encoder. - pub fds: &'a [BorrowedFd<'a>], - /// Y then UV plane. - pub planes: [DmaBufPlane; 2], - /// Width in pixels, even; equal to the encoder width. - pub width: u32, - /// Height in pixels, even; equal to the encoder height. - pub height: u32, - /// DRM format modifier. - pub modifier: u64, - /// NV12 or P010. - pub format: DmaBufFormat, -} - -/// A single-plane DMA-BUF of packed 32-bit RGB pixels, linear or DRM format modifier tiled. -#[cfg(target_os = "linux")] -#[derive(Debug, Clone, Copy)] -pub struct DmaBufFrame<'a> { - /// DMA-BUF file descriptor, duplicated by the encoder. - pub fd: BorrowedFd<'a>, - /// Width in pixels, even; at least the encoder width. - pub width: u32, - /// Height in pixels, even; at least the encoder height. - pub height: u32, - /// Row pitch in bytes. - pub stride: u32, - /// Byte offset of the plane. - pub offset: u32, - /// DRM format modifier. - pub modifier: u64, - /// Byte order of each pixel. - pub order: RgbOrder, -} - -#[cfg(target_os = "linux")] -impl<'a> DmaBufFrame<'a> { - fn planes(&self) -> [DmaBufPlane; 1] { - [DmaBufPlane { - fd: 0, - offset: self.offset, - pitch: self.stride, - }] - } - - fn as_dmabuf<'b>(&'b self, planes: &'b [DmaBufPlane; 1]) -> DmaBuf<'b> { - DmaBuf { - fds: std::slice::from_ref(&self.fd), - planes, - width: self.width, - height: self.height, - modifier: self.modifier, - format: if self.order == RgbOrder::Bgra { - DmaBufFormat::Bgrx - } else { - DmaBufFormat::Rgbx - }, - } - } -} - -/// DRM format modifiers [`HwEncoder::encode_dmabuf`] imports for `order`, empty when Vulkan or its DMA-BUF import is unavailable. -#[cfg(target_os = "linux")] -pub fn dmabuf_modifiers(order: RgbOrder) -> Vec { - vk_gpu().map_or_else(Vec::new, |gpu| { - ec_vk::rgb_import_modifiers(&gpu, order == RgbOrder::Bgra) - }) -} - -/// Duplicates raw descriptor `fd`, which the caller keeps open for this call, so it can back a [`DmaBufFrame`]; the encoder's import cache keys on the buffer, not the descriptor. -#[cfg(target_os = "linux")] -pub fn dup_fd(fd: std::os::fd::RawFd) -> Result { - Ok(ec_vk::dup_raw_fd(fd)?) -} - -/// A D3D11 texture of packed 32-bit RGB pixels (DXGI_FORMAT_B8G8R8A8_UNORM or R8G8B8A8_UNORM, one mip, one layer) shared as an NT handle from `IDXGIResource1::CreateSharedHandle`. -/// -/// [`D3d11Pool::submit`] makes these. The encoder's import cache keys on `id`, unique per texture. The D3D11 writes must be finished before the call, and the texture left unwritten until its coded picture is returned. -#[cfg(windows)] -#[derive(Debug, Clone, Copy)] -pub struct D3d11Frame<'a> { - /// Shared NT handle; borrowed, not closed. - pub handle: std::os::windows::io::BorrowedHandle<'a>, - /// Identity of the texture, unique for the process lifetime. - pub id: u64, - /// Width in pixels, even; at least the encoder width. - pub width: u32, - /// Height in pixels, even; at least the encoder height. - pub height: u32, - /// Byte order of each pixel. - pub order: RgbOrder, -} - -#[cfg(windows)] -impl D3d11Frame<'_> { - fn texture(&self) -> ec_vk::D3d11Texture<'_> { - ec_vk::D3d11Texture { - handle: self.handle, - id: self.id, - width: self.width, - height: self.height, - bgr: self.order == RgbOrder::Bgra, - } - } -} - -/// Copies captured D3D11 frames into a ring of shared textures for [`HwEncoder::encode_d3d11`], waiting for each copy to finish. Use it on the thread that owns the device's immediate context (the capture callback). -#[cfg(windows)] -pub struct D3d11Pool(ec_vk::D3d11Pool); - -#[cfg(windows)] -impl D3d11Pool { - /// A pool on the device that produces the frames. - pub fn new(device: &ec_vk::windows::Win32::Graphics::Direct3D11::ID3D11Device) -> Result { - Ok(D3d11Pool(ec_vk::D3d11Pool::new(device)?)) - } - - /// Copies `frame` (B8G8R8A8 or R8G8B8A8, one mip, one layer) into the next shared texture. The result is valid until the pool reuses that texture, four calls later. - pub fn submit( - &mut self, - frame: &ec_vk::windows::Win32::Graphics::Direct3D11::ID3D11Texture2D, - ) -> Result> { - let t = self.0.submit(frame)?; - Ok(D3d11Frame { - handle: t.handle, - id: t.id, - width: t.width, - height: t.height, - order: if t.bgr { RgbOrder::Bgra } else { RgbOrder::Rgba }, - }) - } -} - -/// Whether [`HwEncoder::encode_d3d11`] can import textures of `order` on this machine's Vulkan device. -#[cfg(windows)] -pub fn d3d11_supported(order: RgbOrder) -> bool { - vk_gpu().is_some_and(|gpu| ec_vk::d3d11_importable(&gpu, order == RgbOrder::Bgra)) -} - -/// One picture for [`HwEncoder::submit`]. -#[derive(Debug, Clone, Copy)] -pub enum EncodeInput<'a> { - /// 8-bit I420. - I420(&'a I420), - /// 10-bit I420 of a 10-bit encoder (H.265 and AV1). - I420_16(&'a I420_16), - /// Packed RGB, box-downscaled to the encoder size. - Rgb(&'a RgbFrame<'a>), - /// DMA-BUF of packed RGB, Vulkan only. - #[cfg(target_os = "linux")] - DmaBuf(&'a DmaBufFrame<'a>), - /// DMA-BUF of NV12 or P010 at the encoder size, Vulkan only. - #[cfg(target_os = "linux")] - DmaBufYuv(&'a DmaBufYuvFrame<'a>), - /// Shared D3D11 texture of packed RGB, Vulkan only. - #[cfg(windows)] - D3d11(&'a D3d11Frame<'a>), -} - -#[cfg(target_os = "linux")] -fn rgb_to_i420(frame: &RgbFrame, (w, h): (usize, usize)) -> Result { - let (sw, sh, stride) = ( - frame.width as usize, - frame.height as usize, - frame.stride as usize, - ); - if sw % 2 != 0 - || sh % 2 != 0 - || stride % 4 != 0 - || stride < sw * 4 - || frame.data.len() < stride * sh - { - return Err(Error::config("RGB frame size or stride")); - } - if sw < w || sh < h { - return Err(Error::config("RGB source smaller than encoder")); - } - let packed: Vec = frame - .data - .chunks(stride) - .take(sh) - .flat_map(|row| &row[..sw * 4]) - .copied() - .collect(); - let packed = if (sw, sh) == (w, h) { - packed - } else { - let mut scaled = vec![0; w * h * 4]; - ec_dsp::rgb::rgb_box_downscale(&packed, sw, sh, sw * 4, &mut scaled, w, h); - scaled - }; - let chroma = (w / 2) * (h / 2); - let mut out = I420 { - y: vec![0; w * h], - u: vec![0; chroma], - v: vec![0; chroma], - width: w as u32, - height: h as u32, - }; - match frame.order { - RgbOrder::Rgba => { - ec_dsp::rgb::rgba_to_i420_709(&packed, w, h, &mut out.y, &mut out.u, &mut out.v) - } - RgbOrder::Bgra => { - ec_dsp::rgb::bgra_to_i420_709(&packed, w, h, &mut out.y, &mut out.u, &mut out.v) - } - } - Ok(out) -} - -/// The Vulkan encoder for one codec. -enum VkEncoder { - H264(ec_vk::H264Encoder), - H265(ec_vk::H265Encoder), - Av1(ec_vk::Av1Encoder), -} - -const ID_HISTORY: usize = 512; - -impl VkEncoder { - fn submit( - &mut self, - input: EncodeInput, - force_keyframe: bool, - ) -> std::result::Result, ec_vk::Error> { - match input { - EncodeInput::I420(frame) => { - let (y, u, v) = (&frame.y, &frame.u, &frame.v); - match self { - VkEncoder::H264(e) => e.submit(y, u, v, force_keyframe), - VkEncoder::H265(e) => e.submit(y, u, v, force_keyframe), - VkEncoder::Av1(e) => e.submit(y, u, v, force_keyframe), - } - } - EncodeInput::I420_16(frame) => { - let (y, u, v) = (&frame.y, &frame.u, &frame.v); - match self { - VkEncoder::H264(_) => Err(ec_vk::Error::Unsupported("10-bit H.264 encode".into())), - VkEncoder::H265(e) => e.submit_16(y, u, v, force_keyframe), - VkEncoder::Av1(e) => e.submit_16(y, u, v, force_keyframe), - } - } - EncodeInput::Rgb(frame) => { - let bgr = frame.order == RgbOrder::Bgra; - let (data, sw, sh, stride) = (frame.data, frame.width, frame.height, frame.stride); - match self { - VkEncoder::H264(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), - VkEncoder::H265(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), - VkEncoder::Av1(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), - } - } - #[cfg(target_os = "linux")] - EncodeInput::DmaBuf(frame) => { - let planes = [DmaBufPlane { - fd: 0, - offset: frame.offset, - pitch: frame.stride, - }]; - let src = DmaBuf { - fds: std::slice::from_ref(&frame.fd), - planes: &planes, - width: frame.width, - height: frame.height, - modifier: frame.modifier, - format: if frame.order == RgbOrder::Bgra { - DmaBufFormat::Bgrx - } else { - DmaBufFormat::Rgbx - }, - }; - self.submit_dma(&src, force_keyframe) - } - #[cfg(target_os = "linux")] - EncodeInput::DmaBufYuv(frame) => { - let src = DmaBuf { - fds: frame.fds, - planes: &frame.planes, - width: frame.width, - height: frame.height, - modifier: frame.modifier, - format: frame.format, - }; - self.submit_dma(&src, force_keyframe) - } - #[cfg(windows)] - EncodeInput::D3d11(frame) => { - let src = frame.texture(); - match self { - VkEncoder::H264(e) => e.submit_d3d11(&src, force_keyframe), - VkEncoder::H265(e) => e.submit_d3d11(&src, force_keyframe), - VkEncoder::Av1(e) => e.submit_d3d11(&src, force_keyframe), - } - } - } - } - - #[cfg(target_os = "linux")] - fn submit_dma( - &mut self, - src: &DmaBuf, - force_keyframe: bool, - ) -> std::result::Result, ec_vk::Error> { - match self { - VkEncoder::H264(e) => e.submit_dmabuf(src, force_keyframe), - VkEncoder::H265(e) => e.submit_dmabuf(src, force_keyframe), - VkEncoder::Av1(e) => e.submit_dmabuf(src, force_keyframe), - } - } - - fn flush(&mut self) -> std::result::Result, ec_vk::Error> { - match self { - VkEncoder::H264(e) => e.flush(), - VkEncoder::H265(e) => e.flush(), - VkEncoder::Av1(e) => e.flush(), - } - } - - 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), - } - } - - fn encode_16( - &mut self, - frame: &I420_16, - force_keyframe: bool, - ) -> std::result::Result { - let (y, u, v) = (&frame.y, &frame.u, &frame.v); - match self { - VkEncoder::H264(_) => Err(ec_vk::Error::Unsupported("10-bit H.264 encode".into())), - VkEncoder::H265(e) => e.encode_16(y, u, v, force_keyframe), - VkEncoder::Av1(e) => e.encode_16(y, u, v, force_keyframe), - } - } - - fn set_rate( - &mut self, - rate: ec_vk::RateControl, - fps: (u32, u32), - ) -> std::result::Result<(), ec_vk::Error> { - match self { - VkEncoder::H264(e) => e.set_rate(rate, fps), - VkEncoder::H265(e) => e.set_rate(rate, fps), - VkEncoder::Av1(e) => e.set_rate(rate, fps), - } - } - - fn encode_rgb( - &mut self, - frame: &RgbFrame, - force_keyframe: bool, - ) -> std::result::Result { - let bgr = frame.order == RgbOrder::Bgra; - let (data, sw, sh, stride) = (frame.data, frame.width, frame.height, frame.stride); - match self { - VkEncoder::H264(e) => e.encode_rgb(data, sw, sh, stride, bgr, force_keyframe), - VkEncoder::H265(e) => e.encode_rgb(data, sw, sh, stride, bgr, force_keyframe), - VkEncoder::Av1(e) => e.encode_rgb(data, sw, sh, stride, bgr, force_keyframe), - } - } - - #[cfg(target_os = "linux")] - fn encode_dmabuf( - &mut self, - src: &DmaBuf, - force_keyframe: bool, - ) -> std::result::Result { - match self { - VkEncoder::H264(e) => e.encode_dmabuf(src, force_keyframe), - VkEncoder::H265(e) => e.encode_dmabuf(src, force_keyframe), - VkEncoder::Av1(e) => e.encode_dmabuf(src, force_keyframe), - } - } -} - -enum EncInner { - Vk(VkEncoder), - #[cfg(target_os = "linux")] - Va(VaEncoder), -} - -/// A hardware encoder on whichever backend opened. -pub struct HwEncoder { - inner: EncInner, - born_epoch: u64, - config: EncoderConfig, - #[cfg_attr(not(target_os = "linux"), allow(dead_code))] - size: (usize, usize), - pending: VecDeque, - ids: VecDeque<(i64, u64)>, - keyframe_next: bool, - tunings: Tunings, - rc: RateFeedback, -} - -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 { - let born_epoch = crate::reset::gpu_reset_epoch(); - match open_backend(backend, config) { - Ok(inner) => { - let size = (config.width as usize, config.height as usize); - return Ok(HwEncoder { - inner, - born_epoch, - config, - size, - pending: VecDeque::new(), - ids: VecDeque::new(), - keyframe_next: false, - tunings: Tunings { - bitrate: config.bitrate, - framerate: config.framerate, - }, - rc: RateFeedback::default(), - }); - } - 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, - } - } - - /// Change bitrate or frame rate from the next frame; a constant-QP encoder keeps its QP. - pub fn tune(&mut self, tunings: Tunings) -> Result<()> { - match &mut self.inner { - EncInner::Vk(enc) => { - vk_session_alive(self.born_epoch)?; - self.tunings = tunings; - self.rc = RateFeedback::default(); - let rate = vk_rate(&self.config, tunings.bitrate); - enc.set_rate(rate, tunings.framerate)?; - } - #[cfg(target_os = "linux")] - EncInner::Va(enc) => enc.tune(tunings), - } - Ok(()) - } - - /// Submit one picture without waiting; the oldest coded picture comes back once two are in flight. Call [`HwEncoder::flush`] at the end. - pub fn submit(&mut self, input: EncodeInput, meta: FrameMetadata) -> Result> { - let meta = self.with_recovery(meta); - match &mut self.inner { - EncInner::Vk(enc) => { - vk_session_alive(self.born_epoch)?; - let coded = enc.submit(input, meta.force_keyframe)?; - self.pending.push_back(meta.timestamp); - let Some(coded) = coded else { - return Ok(None); - }; - let timestamp = self.pending.pop_front().unwrap_or_default(); - self.steer(coded.data.len())?; - Ok(Some(self.vk_frame(coded, timestamp))) - } - #[cfg(target_os = "linux")] - EncInner::Va(enc) => match input { - EncodeInput::I420(frame) => enc.submit(frame, meta), - EncodeInput::I420_16(frame) => enc.submit_16(frame, meta), - EncodeInput::Rgb(frame) => enc.submit(&rgb_to_i420(frame, self.size)?, meta), - EncodeInput::DmaBuf(_) | EncodeInput::DmaBufYuv(_) => Err(Error::unsupported( - "DMA-BUF encode", - "the VA-API backend has no DMA-BUF input here", - )), - }, - } - } - - /// Wait for every submitted picture and return them, oldest first. - pub fn flush(&mut self) -> Result> { - match &mut self.inner { - EncInner::Vk(enc) => { - vk_session_alive(self.born_epoch)?; - let frames = enc.flush()?; - let out: Vec = frames - .into_iter() - .map(|coded| { - let timestamp = self.pending.pop_front().unwrap_or_default(); - self.vk_frame(coded, timestamp) - }) - .collect(); - let mut steered = Ok(()); - for frame in &out { - steered = steered.and(self.steer(frame.data.len())); - } - steered?; - Ok(out) - } - #[cfg(target_os = "linux")] - EncInner::Va(enc) => enc.flush(), - } - } - - fn idle(&self) -> Result<()> { - if self.pending.is_empty() { - Ok(()) - } else { - Err(Error::config("pipelined frames pending; call flush first")) - } - } - - /// Every frame up to `timestamp` was decoded by every receiver. A frame after [`HwEncoder::recover`] may then reference one of them instead of being a keyframe. Vulkan only; a no-op on VA-API. - pub fn ack(&mut self, timestamp: i64) { - let Some(&(_, id)) = self.ids.iter().rev().find(|(ts, _)| *ts <= timestamp) else { - return; - }; - match &mut self.inner { - EncInner::Vk(VkEncoder::Av1(enc)) => enc.ack(id), - EncInner::Vk(VkEncoder::H265(enc)) => enc.ack(id), - EncInner::Vk(VkEncoder::H264(enc)) => enc.ack(id), - #[cfg(target_os = "linux")] - EncInner::Va(_) => {} - } - } - - /// Recover the receivers from loss: the next frame references the newest acknowledged frame still held ([`CodedFrame::recovery`]), or is a keyframe when none is. VA-API always sends a keyframe. - pub fn recover(&mut self) { - match &mut self.inner { - EncInner::Vk(VkEncoder::Av1(enc)) => enc.recover(), - EncInner::Vk(VkEncoder::H265(enc)) => enc.recover(), - EncInner::Vk(VkEncoder::H264(enc)) => enc.recover(), - #[cfg(target_os = "linux")] - EncInner::Va(_) => self.keyframe_next = true, - } - } - - fn with_recovery(&mut self, meta: FrameMetadata) -> FrameMetadata { - FrameMetadata { - force_keyframe: meta.force_keyframe || std::mem::take(&mut self.keyframe_next), - ..meta - } - } - - fn vk_frame(&mut self, coded: ec_vk::CodedFrame, timestamp: i64) -> CodedFrame { - if self.ids.len() == ID_HISTORY { - self.ids.pop_front(); - } - self.ids.push_back((timestamp, coded.id)); - CodedFrame { - data: coded.data, - timestamp, - is_keyframe: coded.keyframe, - recovery: coded.recovery, - } - } - - fn steer(&mut self, bytes: usize) -> Result<()> { - if !self.rc.track(bytes, self.config.rate_control, self.tunings) { - return Ok(()); - } - let rate = vk_rate(&self.config, self.rc.steered_bitrate(self.tunings.bitrate)); - match &mut self.inner { - EncInner::Vk(enc) => enc.set_rate(rate, self.tunings.framerate)?, - #[cfg(target_os = "linux")] - EncInner::Va(_) => {} - } - Ok(()) - } - - /// Encode one frame; `meta.force_keyframe` starts a new GOP. - pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result { - let meta = self.with_recovery(meta); - self.idle()?; - match &mut self.inner { - EncInner::Vk(enc) => { - vk_session_alive(self.born_epoch)?; - let coded = enc.encode(frame, meta.force_keyframe)?; - self.steer(coded.data.len())?; - Ok(self.vk_frame(coded, meta.timestamp)) - } - #[cfg(target_os = "linux")] - EncInner::Va(enc) => enc.encode(frame, meta), - } - } - - /// Encode one 10-bit frame of a 10-bit encoder (H.265 and AV1), the [`HwEncoder::encode`] of a 10-bit encoder. - pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result { - let meta = self.with_recovery(meta); - self.idle()?; - match &mut self.inner { - EncInner::Vk(enc) => { - vk_session_alive(self.born_epoch)?; - let coded = enc.encode_16(frame, meta.force_keyframe)?; - self.steer(coded.data.len())?; - Ok(self.vk_frame(coded, meta.timestamp)) - } - #[cfg(target_os = "linux")] - EncInner::Va(enc) => enc.encode_16(frame, meta), - } - } - - /// Encode one packed RGB frame of the source size; it is box-downscaled to the encoder size. Vulkan does this and the NV12 conversion on the GPU, VA-API on the CPU. - pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result { - let meta = self.with_recovery(meta); - self.idle()?; - match &mut self.inner { - EncInner::Vk(enc) => { - vk_session_alive(self.born_epoch)?; - let coded = enc.encode_rgb(frame, meta.force_keyframe)?; - self.steer(coded.data.len())?; - Ok(self.vk_frame(coded, meta.timestamp)) - } - #[cfg(target_os = "linux")] - EncInner::Va(enc) => enc.encode(&rgb_to_i420(frame, self.size)?, meta), - } - } - - /// Encode one DMA-BUF frame of the source size, box-downscaled to the encoder size. Vulkan only; VA-API has its own PRIME path. - #[cfg(target_os = "linux")] - pub fn encode_dmabuf(&mut self, frame: &DmaBufFrame, meta: FrameMetadata) -> Result { - let planes = frame.planes(); - self.encode_dma(&frame.as_dmabuf(&planes), meta) - } - - /// Encode one NV12 or P010 DMA-BUF frame of the encoder size. Vulkan only; VA-API has its own PRIME path. - #[cfg(target_os = "linux")] - pub fn encode_dmabuf_yuv( - &mut self, - frame: &DmaBufYuvFrame, - meta: FrameMetadata, - ) -> Result { - let src = DmaBuf { - fds: frame.fds, - planes: &frame.planes, - width: frame.width, - height: frame.height, - modifier: frame.modifier, - format: frame.format, - }; - self.encode_dma(&src, meta) - } - - /// Encode one shared D3D11 texture of the source size, downscaled to the encoder size on the GPU. - #[cfg(windows)] - pub fn encode_d3d11(&mut self, frame: &D3d11Frame, meta: FrameMetadata) -> Result { - let meta = self.with_recovery(meta); - self.idle()?; - let EncInner::Vk(enc) = &mut self.inner; - vk_session_alive(self.born_epoch)?; - let src = frame.texture(); - let coded = match enc { - VkEncoder::H264(e) => e.encode_d3d11(&src, meta.force_keyframe), - VkEncoder::H265(e) => e.encode_d3d11(&src, meta.force_keyframe), - VkEncoder::Av1(e) => e.encode_d3d11(&src, meta.force_keyframe), - }?; - self.steer(coded.data.len())?; - Ok(self.vk_frame(coded, meta.timestamp)) - } - - #[cfg(target_os = "linux")] - fn encode_dma(&mut self, src: &DmaBuf, meta: FrameMetadata) -> Result { - let meta = self.with_recovery(meta); - self.idle()?; - match &mut self.inner { - EncInner::Vk(enc) => { - vk_session_alive(self.born_epoch)?; - let coded = enc.encode_dmabuf(src, meta.force_keyframe)?; - self.steer(coded.data.len())?; - Ok(self.vk_frame(coded, meta.timestamp)) - } - EncInner::Va(_) => Err(Error::unsupported( - "DMA-BUF encode", - "the VA-API backend has no DMA-BUF input here", - )), - } - } -} - -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 { - vk_grace()?; - if config.bit_depth == 10 && config.codec == EncCodec::H264 { - return Err(Error::unsupported( - "10-bit H.264 Vulkan Video encode", - "the driver offers no High 10 H.264 encode", - )); - } - if config.bit_depth != 8 && config.bit_depth != 10 { - return Err(Error::config(format!( - "encoder bit depth {}: Vulkan encodes 8-bit, or 10-bit H.265 and AV1", - config.bit_depth - ))); - } - let gpu = vk_gpu() - .ok_or_else(|| Error::unsupported("Vulkan Video encode", "no Vulkan Video device"))?; - let rate = vk_rate(&config, config.bitrate); - let level = match config.codec { - EncCodec::H264 => crate::level::h264(&config), - EncCodec::H265 => crate::level::hevc(&config), - EncCodec::Av1 => crate::level::av1(&config), - }; - let (width, height, fps, gop_size) = ( - config.width, - config.height, - config.framerate, - config.gop_size, - ); - let colour = config.colour.map(|c| ec_vk::Colour { - primaries: c.primaries, - transfer: c.transfer, - matrix: c.matrix, - full_range: c.full_range, - }); - Ok(match config.codec { - EncCodec::H264 => VkEncoder::H264(ec_vk::H264Encoder::new( - &gpu, - ec_vk::H264EncoderConfig { - width, - height, - fps, - gop_size, - rate, - profile: vk_h264_profile(config.h264_profile), - level, - colour, - quality: config.quality, - }, - )?), - EncCodec::H265 => VkEncoder::H265(ec_vk::H265Encoder::new( - &gpu, - ec_vk::H265EncoderConfig { - width, - height, - fps, - gop_size, - rate, - bit_depth: config.bit_depth, - level, - colour, - quality: config.quality, - }, - )?), - EncCodec::Av1 => VkEncoder::Av1(ec_vk::Av1Encoder::new( - &gpu, - ec_vk::Av1EncoderConfig { - width, - height, - fps, - gop_size, - rate, - bit_depth: config.bit_depth, - level, - colour, - quality: config.quality, - }, - )?), - }) -} - -fn vk_h264_profile(profile: H264Profile) -> ec_vk::H264Profile { - match profile { - H264Profile::ConstrainedBaseline => ec_vk::H264Profile::ConstrainedBaseline, - H264Profile::Main => ec_vk::H264Profile::Main, - H264Profile::High => ec_vk::H264Profile::High, - } -} - -fn vk_rate(config: &EncoderConfig, bitrate: u32) -> 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, - }, - (RateControlMode::ConstantBitrate, _) => ec_vk::RateControl::Cbr { - bitrate, - buffer_ms: hrd_buffer_ms(config), - }, - (RateControlMode::VariableBitrate, _) => ec_vk::RateControl::Vbr { - bitrate, - max_bitrate: bitrate.saturating_mul(3) / 2, - buffer_ms: hrd_buffer_ms(config), - min_qp: None, - }, - (RateControlMode::Qvbr { quality }, _) => ec_vk::RateControl::Vbr { - bitrate, - max_bitrate: bitrate, - buffer_ms: hrd_buffer_ms(config), - min_qp: Some(quality.min(51) as u8), - }, - } -} - -#[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", - )) -} - -enum VkDecoder { - H264(VkH264Decoder), - H265(VkH265Decoder), - Av1(VkAv1Decoder), - Vp9(VkVp9Decoder), -} - -impl VkDecoder { - fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { - match self { - VkDecoder::H264(d) => d.decode(data, timestamp), - VkDecoder::H265(d) => d.decode(data, timestamp), - VkDecoder::Av1(d) => d.decode(data, timestamp), - VkDecoder::Vp9(d) => d.decode(data, timestamp), - } - } - - fn next_frame(&mut self) -> Option { - match self { - VkDecoder::H264(d) => d.next_frame(), - VkDecoder::H265(d) => d.next_frame(), - VkDecoder::Av1(d) => d.next_frame(), - VkDecoder::Vp9(d) => d.next_frame(), - } - } - - fn flush(&mut self) -> Result<()> { - match self { - VkDecoder::H264(d) => d.flush(), - VkDecoder::H265(d) => d.flush(), - VkDecoder::Av1(d) => d.flush(), - VkDecoder::Vp9(d) => d.flush(), - } - } - - fn reset(&mut self) { - match self { - VkDecoder::H264(d) => d.reset(), - VkDecoder::H265(d) => d.reset(), - VkDecoder::Av1(d) => d.reset(), - VkDecoder::Vp9(d) => d.reset(), - } - } -} - -enum DecInner { - Vk(VkDecoder), - #[cfg(target_os = "linux")] - Va(VaDecoder), -} - -const REPLAY_LIMIT: usize = 64; - -/// What a decoder hands out: 8-bit I420, or packed RGB converted on the way out. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct RgbOutput { - /// Byte order of each output pixel. - pub order: RgbOrder, - /// Scale pictures wider than this down to it, keeping the aspect ratio. - pub max_width: Option, - /// Scale pictures taller than this down to it, keeping the aspect ratio. - pub max_height: Option, -} - -impl RgbOutput { - pub(crate) fn bound(&self) -> (Option, Option) { - (self.max_width, self.max_height) - } -} - -/// A hardware decoder on whichever backend opened. -pub struct HwDecoder { - inner: DecInner, - born_epoch: u64, - #[cfg_attr(not(target_os = "linux"), allow(dead_code))] - codec: Codec, - rgb: Option, - #[cfg_attr(not(target_os = "linux"), allow(dead_code))] - replay: Option, i64)>>, -} - -impl HwDecoder { - /// Open a decoder for `codec`. Every codec tries Vulkan Video first, then VA-API (Linux). - pub fn open(codec: Codec) -> Result { - HwDecoder::open_with(codec, None) - } - - /// Open a decoder for `codec` whose [`HwDecoder::next_rgb`] hands out packed RGB, converted on the GPU by Vulkan and on the CPU by VA-API. - pub fn open_rgb(codec: Codec, output: RgbOutput) -> Result { - HwDecoder::open_with(codec, Some(output)) - } - - fn open_with(codec: Codec, rgb: Option) -> Result { - let mut reasons = Vec::new(); - let born_epoch = crate::reset::gpu_reset_epoch(); - let vk = vk_grace().and_then(|()| match codec { - Codec::H264 => VkH264Decoder::new().map(VkDecoder::H264), - Codec::H265 => VkH265Decoder::new().map(VkDecoder::H265), - Codec::Av1 => VkAv1Decoder::new().map(VkDecoder::Av1), - Codec::Vp9 => VkVp9Decoder::new().map(VkDecoder::Vp9), - }); - match vk { - Ok(inner) => { - return Ok(HwDecoder { - inner: DecInner::Vk(inner), - born_epoch, - codec, - rgb, - replay: Some(Vec::new()), - }); - } - Err(e) => reasons.push(format!("Vk: {e}")), - } - #[cfg(target_os = "linux")] - { - match open_va_decoder(codec) { - Ok(inner) => { - return Ok(HwDecoder { - inner: DecInner::Va(inner), - born_epoch, - codec, - rgb, - replay: None, - }); - } - Err(e) => reasons.push(format!("Va: {e}")), - } - } - Err(Error::unsupported( - format!("{codec:?} hardware decode"), - reasons.join("; "), - )) - } - - /// The backend this decoder runs on. - pub fn backend(&self) -> Backend { - match self.inner { - DecInner::Vk(_) => Backend::Vk, - #[cfg(target_os = "linux")] - DecInner::Va(_) => Backend::Va, - } - } - - /// Feed one access unit. A stream Vulkan refuses (an unsupported profile) before its first - /// picture comes out moves to VA-API on Linux, replaying what was fed so far. - pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { - let born_epoch = self.born_epoch; - let result = match &mut self.inner { - DecInner::Vk(d) => vk_session_alive(born_epoch).and_then(|()| d.decode(data, timestamp)), - #[cfg(target_os = "linux")] - DecInner::Va(d) => d.decode(data, timestamp), - }; - if let Some(fed) = self.replay.as_mut() { - fed.push((data.to_vec(), timestamp)); - if fed.len() > REPLAY_LIMIT { - self.replay = None; - } - } - #[cfg(target_os = "linux")] - if let Err(Error::Unsupported { .. }) = result - && let Some(fed) = &self.replay - && let Ok(mut va) = open_va_decoder(self.codec) - && fed.iter().all(|(chunk, ts)| va.decode(chunk, *ts).is_ok()) - { - self.replay = None; - self.inner = DecInner::Va(va); - return Ok(()); - } - result - } - - /// The next picture in display order, held in its decode slot until dropped. Convert it with the `to_*` methods of [`HwPicture`]. - pub fn next_picture(&mut self) -> Result> { - self.pull() - } - - /// The next picture in display order, as 8-bit I420 with its timestamp. - pub fn next_frame(&mut self) -> Result> { - match self.pull()? { - None => Ok(None), - Some(picture) => Ok(Some((picture.timestamp, picture.to_i420()?))), - } - } - - /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder not opened with [`HwDecoder::open_rgb`]. - pub fn next_rgb(&mut self) -> Result> { - let mut dst = RgbPicture::default(); - Ok(self.next_rgb_into(&mut dst)?.map(|ts| (ts, dst))) - } - - /// Changes the RGB output of a decoder opened with [`HwDecoder::open_rgb`] from the next picture on. - pub fn set_rgb_output(&mut self, output: RgbOutput) -> Result<()> { - let rgb = self - .rgb - .as_mut() - .ok_or_else(|| Error::config("set_rgb_output on a decoder not opened with open_rgb"))?; - *rgb = output; - Ok(()) - } - - /// [`HwDecoder::next_rgb`] into `dst`, reusing its allocation across pictures; returns the timestamp. - pub fn next_rgb_into(&mut self, dst: &mut RgbPicture) -> Result> { - let output = self - .rgb - .ok_or_else(|| Error::config("next_rgb on a decoder not opened with open_rgb"))?; - match self.pull()? { - None => Ok(None), - Some(picture) => { - picture.rgb_into(&output, dst)?; - Ok(Some(picture.timestamp)) - } - } - } - - fn pull(&mut self) -> Result> { - match &mut self.inner { - DecInner::Vk(d) => { - vk_session_alive(self.born_epoch)?; - let picture = d.next_frame(); - if picture.is_some() { - self.replay = None; - } - Ok(picture) - } - #[cfg(target_os = "linux")] - DecInner::Va(d) => Ok(d.next_frame().map(HwPicture::va)), - } - } - - /// Drop every held picture and all reference state so decoding restarts at a sync sample after a seek. Parameter sets and the GPU session survive. After a reset an inter picture whose references were not decoded since is an error, never a guess. - pub fn reset(&mut self) { - match &mut self.inner { - DecInner::Vk(d) => d.reset(), - #[cfg(target_os = "linux")] - DecInner::Va(d) => d.reset(), - } - self.replay = None; - } - - /// Emit every picture still held for reordering. - pub fn flush(&mut self) -> Result<()> { - match &mut self.inner { - DecInner::Vk(d) => d.flush(), - #[cfg(target_os = "linux")] - DecInner::Va(d) => d.flush(), - } - } -} - -#[cfg(target_os = "linux")] -fn open_va_decoder(codec: Codec) -> Result { - let display = ec_va::open()?; - VaDecoder::new(&display, codec) -} +mod caps; +mod decoder; +mod encoder; +mod input; + +pub use caps::*; +pub use decoder::*; +pub use encoder::*; +pub use input::*; diff --git a/crates/ec-hw/src/hw/caps.rs b/crates/ec-hw/src/hw/caps.rs new file mode 100644 index 00000000..81f51f4e --- /dev/null +++ b/crates/ec-hw/src/hw/caps.rs @@ -0,0 +1,231 @@ +use super::*; + +/// 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, +} + +/// Profile of a [`Capability`], 4:2:0 only. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CodecProfile { + /// H.264 Constrained Baseline, 8-bit. + H264ConstrainedBaseline, + /// H.264 Main, 8-bit. + H264Main, + /// H.264 High, 8-bit. + H264High, + /// H.265 Main, 8-bit. + H265Main, + /// H.265 Main 10, 10-bit. + H265Main10, + /// AV1 Main, 8-bit. + Av1Main, + /// AV1 Main, 10-bit. + Av1Main10, + /// VP9 Profile 0, 8-bit. + Vp9Profile0, + /// VP9 Profile 2, 10-bit. + Vp9Profile2, +} + +/// One codec, profile, direction and backend this machine offers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Capability { + /// Codec. + pub codec: Codec, + /// Profile. + pub profile: CodecProfile, + /// 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: RefCell)>> = const { RefCell::new(None) }; +} + +pub(crate) fn vk_gpu() -> Option { + GPU.with_borrow_mut(|cached| { + let epoch = crate::reset::gpu_reset_epoch(); + match cached { + Some((born, gpu)) if *born == epoch => gpu.clone(), + _ => { + let gpu = ec_vk::Gpu::open().ok(); + *cached = Some((epoch, gpu.clone())); + gpu + } + } + }) +} + +pub(super) fn vk_session_alive(born_epoch: u64) -> Result<()> { + if crate::reset::gpu_reset_epoch() == born_epoch { + Ok(()) + } else { + Err(Error::hw_reset( + "the GPU was reset after this Vulkan session was created; its device is lost", + )) + } +} + +pub(super) fn vk_grace() -> Result<()> { + if crate::reset::gpu_recently_reset() { + Err(Error::hw_reset( + "the GPU was reset moments ago; new Vulkan sessions wait out the grace period", + )) + } else { + Ok(()) + } +} + +/// 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() { + 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, + profile: vk_profile(caps.profile), + 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.profile == cap.profile + && 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 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), + }; + for profile in va_profiles(entry.profile, entry.rt_formats) { + push( + out, + Capability { + codec: profile.codec(), + profile, + direction, + max_width, + max_height, + backend: Backend::Va, + }, + ); + } + } +} + +#[cfg(target_os = "linux")] +impl CodecProfile { + fn codec(self) -> Codec { + match self { + CodecProfile::H264ConstrainedBaseline + | CodecProfile::H264Main + | CodecProfile::H264High => Codec::H264, + CodecProfile::H265Main | CodecProfile::H265Main10 => Codec::H265, + CodecProfile::Av1Main | CodecProfile::Av1Main10 => Codec::Av1, + CodecProfile::Vp9Profile0 | CodecProfile::Vp9Profile2 => Codec::Vp9, + } + } +} + +#[cfg(target_os = "linux")] +fn va_profiles(profile: ec_va::Profile, rt_formats: u32) -> Vec { + let yuv420 = ec_va::va::VA_RT_FORMAT_YUV420; + let yuv420_10 = ec_va::va::VA_RT_FORMAT_YUV420_10; + match profile { + ec_va::Profile::H264ConstrainedBaseline => vec![CodecProfile::H264ConstrainedBaseline], + ec_va::Profile::H264Main => vec![CodecProfile::H264Main], + ec_va::Profile::H264High => vec![CodecProfile::H264High], + ec_va::Profile::HEVCMain => vec![CodecProfile::H265Main], + ec_va::Profile::HEVCMain10 => vec![CodecProfile::H265Main10], + ec_va::Profile::VP9Profile0 => vec![CodecProfile::Vp9Profile0], + ec_va::Profile::VP9Profile2 if rt_formats & yuv420_10 != 0 => vec![CodecProfile::Vp9Profile2], + ec_va::Profile::AV1Profile0 => [ + (yuv420, CodecProfile::Av1Main), + (yuv420_10, CodecProfile::Av1Main10), + ] + .into_iter() + .filter(|(bit, _)| rt_formats & bit != 0) + .map(|(_, p)| p) + .collect(), + _ => Vec::new(), + } +} + +fn vk_profile(profile: ec_vk::CodecProfile) -> CodecProfile { + match profile { + ec_vk::CodecProfile::H264High => CodecProfile::H264High, + ec_vk::CodecProfile::H265Main => CodecProfile::H265Main, + ec_vk::CodecProfile::H265Main10 => CodecProfile::H265Main10, + ec_vk::CodecProfile::Av1Main => CodecProfile::Av1Main, + ec_vk::CodecProfile::Av1Main10 => CodecProfile::Av1Main10, + ec_vk::CodecProfile::Vp9Profile0 => CodecProfile::Vp9Profile0, + ec_vk::CodecProfile::Vp9Profile2 => CodecProfile::Vp9Profile2, + ec_vk::CodecProfile::H264ConstrainedBaseline => CodecProfile::H264ConstrainedBaseline, + ec_vk::CodecProfile::H264Main => CodecProfile::H264Main, + } +} + diff --git a/crates/ec-hw/src/hw/decoder.rs b/crates/ec-hw/src/hw/decoder.rs new file mode 100644 index 00000000..73b00742 --- /dev/null +++ b/crates/ec-hw/src/hw/decoder.rs @@ -0,0 +1,256 @@ +use super::*; + +enum VkDecoder { + H264(VkH264Decoder), + H265(VkH265Decoder), + Av1(VkAv1Decoder), + Vp9(VkVp9Decoder), +} + +impl VkDecoder { + fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { + match self { + VkDecoder::H264(d) => d.decode(data, timestamp), + VkDecoder::H265(d) => d.decode(data, timestamp), + VkDecoder::Av1(d) => d.decode(data, timestamp), + VkDecoder::Vp9(d) => d.decode(data, timestamp), + } + } + + fn next_frame(&mut self) -> Option { + match self { + VkDecoder::H264(d) => d.next_frame(), + VkDecoder::H265(d) => d.next_frame(), + VkDecoder::Av1(d) => d.next_frame(), + VkDecoder::Vp9(d) => d.next_frame(), + } + } + + fn flush(&mut self) -> Result<()> { + match self { + VkDecoder::H264(d) => d.flush(), + VkDecoder::H265(d) => d.flush(), + VkDecoder::Av1(d) => d.flush(), + VkDecoder::Vp9(d) => d.flush(), + } + } + + fn reset(&mut self) { + match self { + VkDecoder::H264(d) => d.reset(), + VkDecoder::H265(d) => d.reset(), + VkDecoder::Av1(d) => d.reset(), + VkDecoder::Vp9(d) => d.reset(), + } + } +} + +enum DecInner { + Vk(VkDecoder), + #[cfg(target_os = "linux")] + Va(VaDecoder), +} + +const REPLAY_LIMIT: usize = 64; + +/// What a decoder hands out: 8-bit I420, or packed RGB converted on the way out. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RgbOutput { + /// Byte order of each output pixel. + pub order: RgbOrder, + /// Scale pictures wider than this down to it, keeping the aspect ratio. + pub max_width: Option, + /// Scale pictures taller than this down to it, keeping the aspect ratio. + pub max_height: Option, +} + +impl RgbOutput { + pub(crate) fn bound(&self) -> (Option, Option) { + (self.max_width, self.max_height) + } +} + +/// A hardware decoder on whichever backend opened. +pub struct HwDecoder { + inner: DecInner, + born_epoch: u64, + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] + codec: Codec, + rgb: Option, + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] + replay: Option, i64)>>, +} + +impl HwDecoder { + /// Open a decoder for `codec`. Every codec tries Vulkan Video first, then VA-API (Linux). + pub fn open(codec: Codec) -> Result { + HwDecoder::open_with(codec, None) + } + + /// Open a decoder for `codec` whose [`HwDecoder::next_rgb`] hands out packed RGB, converted on the GPU by Vulkan and on the CPU by VA-API. + pub fn open_rgb(codec: Codec, output: RgbOutput) -> Result { + HwDecoder::open_with(codec, Some(output)) + } + + fn open_with(codec: Codec, rgb: Option) -> Result { + let mut reasons = Vec::new(); + let born_epoch = crate::reset::gpu_reset_epoch(); + let vk = vk_grace().and_then(|()| match codec { + Codec::H264 => VkH264Decoder::new().map(VkDecoder::H264), + Codec::H265 => VkH265Decoder::new().map(VkDecoder::H265), + Codec::Av1 => VkAv1Decoder::new().map(VkDecoder::Av1), + Codec::Vp9 => VkVp9Decoder::new().map(VkDecoder::Vp9), + }); + match vk { + Ok(inner) => { + return Ok(HwDecoder { + inner: DecInner::Vk(inner), + born_epoch, + codec, + rgb, + replay: Some(Vec::new()), + }); + } + Err(e) => reasons.push(format!("Vk: {e}")), + } + #[cfg(target_os = "linux")] + { + match open_va_decoder(codec) { + Ok(inner) => { + return Ok(HwDecoder { + inner: DecInner::Va(inner), + born_epoch, + codec, + rgb, + replay: None, + }); + } + Err(e) => reasons.push(format!("Va: {e}")), + } + } + Err(Error::unsupported( + format!("{codec:?} hardware decode"), + reasons.join("; "), + )) + } + + /// The backend this decoder runs on. + pub fn backend(&self) -> Backend { + match self.inner { + DecInner::Vk(_) => Backend::Vk, + #[cfg(target_os = "linux")] + DecInner::Va(_) => Backend::Va, + } + } + + /// Feed one access unit. A stream Vulkan refuses (an unsupported profile) before its first + /// picture comes out moves to VA-API on Linux, replaying what was fed so far. + pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { + let born_epoch = self.born_epoch; + let result = match &mut self.inner { + DecInner::Vk(d) => vk_session_alive(born_epoch).and_then(|()| d.decode(data, timestamp)), + #[cfg(target_os = "linux")] + DecInner::Va(d) => d.decode(data, timestamp), + }; + if let Some(fed) = self.replay.as_mut() { + fed.push((data.to_vec(), timestamp)); + if fed.len() > REPLAY_LIMIT { + self.replay = None; + } + } + #[cfg(target_os = "linux")] + if let Err(Error::Unsupported { .. }) = result + && let Some(fed) = &self.replay + && let Ok(mut va) = open_va_decoder(self.codec) + && fed.iter().all(|(chunk, ts)| va.decode(chunk, *ts).is_ok()) + { + self.replay = None; + self.inner = DecInner::Va(va); + return Ok(()); + } + result + } + + /// The next picture in display order, held in its decode slot until dropped. Convert it with the `to_*` methods of [`HwPicture`]. + pub fn next_picture(&mut self) -> Result> { + self.pull() + } + + /// The next picture in display order, as 8-bit I420 with its timestamp. + pub fn next_frame(&mut self) -> Result> { + match self.pull()? { + None => Ok(None), + Some(picture) => Ok(Some((picture.timestamp, picture.to_i420()?))), + } + } + + /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder not opened with [`HwDecoder::open_rgb`]. + pub fn next_rgb(&mut self) -> Result> { + let mut dst = RgbPicture::default(); + Ok(self.next_rgb_into(&mut dst)?.map(|ts| (ts, dst))) + } + + /// Changes the RGB output of a decoder opened with [`HwDecoder::open_rgb`] from the next picture on. + pub fn set_rgb_output(&mut self, output: RgbOutput) -> Result<()> { + let rgb = self + .rgb + .as_mut() + .ok_or_else(|| Error::config("set_rgb_output on a decoder not opened with open_rgb"))?; + *rgb = output; + Ok(()) + } + + /// [`HwDecoder::next_rgb`] into `dst`, reusing its allocation across pictures; returns the timestamp. + pub fn next_rgb_into(&mut self, dst: &mut RgbPicture) -> Result> { + let output = self + .rgb + .ok_or_else(|| Error::config("next_rgb on a decoder not opened with open_rgb"))?; + match self.pull()? { + None => Ok(None), + Some(picture) => { + picture.rgb_into(&output, dst)?; + Ok(Some(picture.timestamp)) + } + } + } + + fn pull(&mut self) -> Result> { + match &mut self.inner { + DecInner::Vk(d) => { + vk_session_alive(self.born_epoch)?; + let picture = d.next_frame(); + if picture.is_some() { + self.replay = None; + } + Ok(picture) + } + #[cfg(target_os = "linux")] + DecInner::Va(d) => Ok(d.next_frame().map(HwPicture::va)), + } + } + + /// Drop every held picture and all reference state so decoding restarts at a sync sample after a seek. Parameter sets and the GPU session survive. After a reset an inter picture whose references were not decoded since is an error, never a guess. + pub fn reset(&mut self) { + match &mut self.inner { + DecInner::Vk(d) => d.reset(), + #[cfg(target_os = "linux")] + DecInner::Va(d) => d.reset(), + } + self.replay = None; + } + + /// Emit every picture still held for reordering. + pub fn flush(&mut self) -> Result<()> { + match &mut self.inner { + DecInner::Vk(d) => d.flush(), + #[cfg(target_os = "linux")] + DecInner::Va(d) => d.flush(), + } + } +} + +#[cfg(target_os = "linux")] +fn open_va_decoder(codec: Codec) -> Result { + let display = ec_va::open()?; + VaDecoder::new(&display, codec) +} diff --git a/crates/ec-hw/src/hw/encoder.rs b/crates/ec-hw/src/hw/encoder.rs new file mode 100644 index 00000000..8a6d4f8a --- /dev/null +++ b/crates/ec-hw/src/hw/encoder.rs @@ -0,0 +1,621 @@ +use super::*; + +/// The Vulkan encoder for one codec. +enum VkEncoder { + H264(ec_vk::H264Encoder), + H265(ec_vk::H265Encoder), + Av1(ec_vk::Av1Encoder), +} + +const ID_HISTORY: usize = 512; + +impl VkEncoder { + fn submit( + &mut self, + input: EncodeInput, + force_keyframe: bool, + ) -> std::result::Result, ec_vk::Error> { + match input { + EncodeInput::I420(frame) => { + let (y, u, v) = (&frame.y, &frame.u, &frame.v); + match self { + VkEncoder::H264(e) => e.submit(y, u, v, force_keyframe), + VkEncoder::H265(e) => e.submit(y, u, v, force_keyframe), + VkEncoder::Av1(e) => e.submit(y, u, v, force_keyframe), + } + } + EncodeInput::I420_16(frame) => { + let (y, u, v) = (&frame.y, &frame.u, &frame.v); + match self { + VkEncoder::H264(_) => Err(ec_vk::Error::Unsupported("10-bit H.264 encode".into())), + VkEncoder::H265(e) => e.submit_16(y, u, v, force_keyframe), + VkEncoder::Av1(e) => e.submit_16(y, u, v, force_keyframe), + } + } + EncodeInput::Rgb(frame) => { + let bgr = frame.order == RgbOrder::Bgra; + let (data, sw, sh, stride) = (frame.data, frame.width, frame.height, frame.stride); + match self { + VkEncoder::H264(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), + VkEncoder::H265(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), + VkEncoder::Av1(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), + } + } + #[cfg(target_os = "linux")] + EncodeInput::DmaBuf(frame) => { + let planes = [DmaBufPlane { + fd: 0, + offset: frame.offset, + pitch: frame.stride, + }]; + let src = DmaBuf { + fds: std::slice::from_ref(&frame.fd), + planes: &planes, + width: frame.width, + height: frame.height, + modifier: frame.modifier, + format: if frame.order == RgbOrder::Bgra { + DmaBufFormat::Bgrx + } else { + DmaBufFormat::Rgbx + }, + }; + self.submit_dma(&src, force_keyframe) + } + #[cfg(target_os = "linux")] + EncodeInput::DmaBufYuv(frame) => { + let src = DmaBuf { + fds: frame.fds, + planes: &frame.planes, + width: frame.width, + height: frame.height, + modifier: frame.modifier, + format: frame.format, + }; + self.submit_dma(&src, force_keyframe) + } + #[cfg(windows)] + EncodeInput::D3d11(frame) => { + let src = frame.texture(); + match self { + VkEncoder::H264(e) => e.submit_d3d11(&src, force_keyframe), + VkEncoder::H265(e) => e.submit_d3d11(&src, force_keyframe), + VkEncoder::Av1(e) => e.submit_d3d11(&src, force_keyframe), + } + } + } + } + + #[cfg(target_os = "linux")] + fn submit_dma( + &mut self, + src: &DmaBuf, + force_keyframe: bool, + ) -> std::result::Result, ec_vk::Error> { + match self { + VkEncoder::H264(e) => e.submit_dmabuf(src, force_keyframe), + VkEncoder::H265(e) => e.submit_dmabuf(src, force_keyframe), + VkEncoder::Av1(e) => e.submit_dmabuf(src, force_keyframe), + } + } + + fn flush(&mut self) -> std::result::Result, ec_vk::Error> { + match self { + VkEncoder::H264(e) => e.flush(), + VkEncoder::H265(e) => e.flush(), + VkEncoder::Av1(e) => e.flush(), + } + } + + 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), + } + } + + fn encode_16( + &mut self, + frame: &I420_16, + force_keyframe: bool, + ) -> std::result::Result { + let (y, u, v) = (&frame.y, &frame.u, &frame.v); + match self { + VkEncoder::H264(_) => Err(ec_vk::Error::Unsupported("10-bit H.264 encode".into())), + VkEncoder::H265(e) => e.encode_16(y, u, v, force_keyframe), + VkEncoder::Av1(e) => e.encode_16(y, u, v, force_keyframe), + } + } + + fn set_rate( + &mut self, + rate: ec_vk::RateControl, + fps: (u32, u32), + ) -> std::result::Result<(), ec_vk::Error> { + match self { + VkEncoder::H264(e) => e.set_rate(rate, fps), + VkEncoder::H265(e) => e.set_rate(rate, fps), + VkEncoder::Av1(e) => e.set_rate(rate, fps), + } + } + + fn encode_rgb( + &mut self, + frame: &RgbFrame, + force_keyframe: bool, + ) -> std::result::Result { + let bgr = frame.order == RgbOrder::Bgra; + let (data, sw, sh, stride) = (frame.data, frame.width, frame.height, frame.stride); + match self { + VkEncoder::H264(e) => e.encode_rgb(data, sw, sh, stride, bgr, force_keyframe), + VkEncoder::H265(e) => e.encode_rgb(data, sw, sh, stride, bgr, force_keyframe), + VkEncoder::Av1(e) => e.encode_rgb(data, sw, sh, stride, bgr, force_keyframe), + } + } + + #[cfg(target_os = "linux")] + fn encode_dmabuf( + &mut self, + src: &DmaBuf, + force_keyframe: bool, + ) -> std::result::Result { + match self { + VkEncoder::H264(e) => e.encode_dmabuf(src, force_keyframe), + VkEncoder::H265(e) => e.encode_dmabuf(src, force_keyframe), + VkEncoder::Av1(e) => e.encode_dmabuf(src, force_keyframe), + } + } +} + +enum EncInner { + Vk(VkEncoder), + #[cfg(target_os = "linux")] + Va(VaEncoder), +} + +/// A hardware encoder on whichever backend opened. +pub struct HwEncoder { + inner: EncInner, + born_epoch: u64, + config: EncoderConfig, + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] + size: (usize, usize), + pending: VecDeque, + ids: VecDeque<(i64, u64)>, + keyframe_next: bool, + tunings: Tunings, + rc: RateFeedback, +} + +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 { + let born_epoch = crate::reset::gpu_reset_epoch(); + match open_backend(backend, config) { + Ok(inner) => { + let size = (config.width as usize, config.height as usize); + return Ok(HwEncoder { + inner, + born_epoch, + config, + size, + pending: VecDeque::new(), + ids: VecDeque::new(), + keyframe_next: false, + tunings: Tunings { + bitrate: config.bitrate, + framerate: config.framerate, + }, + rc: RateFeedback::default(), + }); + } + 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, + } + } + + /// Change bitrate or frame rate from the next frame; a constant-QP encoder keeps its QP. + pub fn tune(&mut self, tunings: Tunings) -> Result<()> { + match &mut self.inner { + EncInner::Vk(enc) => { + vk_session_alive(self.born_epoch)?; + self.tunings = tunings; + self.rc = RateFeedback::default(); + let rate = vk_rate(&self.config, tunings.bitrate); + enc.set_rate(rate, tunings.framerate)?; + } + #[cfg(target_os = "linux")] + EncInner::Va(enc) => enc.tune(tunings), + } + Ok(()) + } + + /// Submit one picture without waiting; the oldest coded picture comes back once two are in flight. Call [`HwEncoder::flush`] at the end. + pub fn submit(&mut self, input: EncodeInput, meta: FrameMetadata) -> Result> { + let meta = self.with_recovery(meta); + match &mut self.inner { + EncInner::Vk(enc) => { + vk_session_alive(self.born_epoch)?; + let coded = enc.submit(input, meta.force_keyframe)?; + self.pending.push_back(meta.timestamp); + let Some(coded) = coded else { + return Ok(None); + }; + let timestamp = self.pending.pop_front().unwrap_or_default(); + self.steer(coded.data.len())?; + Ok(Some(self.vk_frame(coded, timestamp))) + } + #[cfg(target_os = "linux")] + EncInner::Va(enc) => match input { + EncodeInput::I420(frame) => enc.submit(frame, meta), + EncodeInput::I420_16(frame) => enc.submit_16(frame, meta), + EncodeInput::Rgb(frame) => enc.submit(&rgb_to_i420(frame, self.size)?, meta), + EncodeInput::DmaBuf(_) | EncodeInput::DmaBufYuv(_) => Err(Error::unsupported( + "DMA-BUF encode", + "the VA-API backend has no DMA-BUF input here", + )), + }, + } + } + + /// Wait for every submitted picture and return them, oldest first. + pub fn flush(&mut self) -> Result> { + match &mut self.inner { + EncInner::Vk(enc) => { + vk_session_alive(self.born_epoch)?; + let frames = enc.flush()?; + let out: Vec = frames + .into_iter() + .map(|coded| { + let timestamp = self.pending.pop_front().unwrap_or_default(); + self.vk_frame(coded, timestamp) + }) + .collect(); + let mut steered = Ok(()); + for frame in &out { + steered = steered.and(self.steer(frame.data.len())); + } + steered?; + Ok(out) + } + #[cfg(target_os = "linux")] + EncInner::Va(enc) => enc.flush(), + } + } + + fn idle(&self) -> Result<()> { + if self.pending.is_empty() { + Ok(()) + } else { + Err(Error::config("pipelined frames pending; call flush first")) + } + } + + /// Every frame up to `timestamp` was decoded by every receiver. A frame after [`HwEncoder::recover`] may then reference one of them instead of being a keyframe. Vulkan only; a no-op on VA-API. + pub fn ack(&mut self, timestamp: i64) { + let Some(&(_, id)) = self.ids.iter().rev().find(|(ts, _)| *ts <= timestamp) else { + return; + }; + match &mut self.inner { + EncInner::Vk(VkEncoder::Av1(enc)) => enc.ack(id), + EncInner::Vk(VkEncoder::H265(enc)) => enc.ack(id), + EncInner::Vk(VkEncoder::H264(enc)) => enc.ack(id), + #[cfg(target_os = "linux")] + EncInner::Va(_) => {} + } + } + + /// Recover the receivers from loss: the next frame references the newest acknowledged frame still held ([`CodedFrame::recovery`]), or is a keyframe when none is. VA-API always sends a keyframe. + pub fn recover(&mut self) { + match &mut self.inner { + EncInner::Vk(VkEncoder::Av1(enc)) => enc.recover(), + EncInner::Vk(VkEncoder::H265(enc)) => enc.recover(), + EncInner::Vk(VkEncoder::H264(enc)) => enc.recover(), + #[cfg(target_os = "linux")] + EncInner::Va(_) => self.keyframe_next = true, + } + } + + fn with_recovery(&mut self, meta: FrameMetadata) -> FrameMetadata { + FrameMetadata { + force_keyframe: meta.force_keyframe || std::mem::take(&mut self.keyframe_next), + ..meta + } + } + + fn vk_frame(&mut self, coded: ec_vk::CodedFrame, timestamp: i64) -> CodedFrame { + if self.ids.len() == ID_HISTORY { + self.ids.pop_front(); + } + self.ids.push_back((timestamp, coded.id)); + CodedFrame { + data: coded.data, + timestamp, + is_keyframe: coded.keyframe, + recovery: coded.recovery, + } + } + + fn steer(&mut self, bytes: usize) -> Result<()> { + if !self.rc.track(bytes, self.config.rate_control, self.tunings) { + return Ok(()); + } + let rate = vk_rate(&self.config, self.rc.steered_bitrate(self.tunings.bitrate)); + match &mut self.inner { + EncInner::Vk(enc) => enc.set_rate(rate, self.tunings.framerate)?, + #[cfg(target_os = "linux")] + EncInner::Va(_) => {} + } + Ok(()) + } + + /// Encode one frame; `meta.force_keyframe` starts a new GOP. + pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result { + let meta = self.with_recovery(meta); + self.idle()?; + match &mut self.inner { + EncInner::Vk(enc) => { + vk_session_alive(self.born_epoch)?; + let coded = enc.encode(frame, meta.force_keyframe)?; + self.steer(coded.data.len())?; + Ok(self.vk_frame(coded, meta.timestamp)) + } + #[cfg(target_os = "linux")] + EncInner::Va(enc) => enc.encode(frame, meta), + } + } + + /// Encode one 10-bit frame of a 10-bit encoder (H.265 and AV1), the [`HwEncoder::encode`] of a 10-bit encoder. + pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result { + let meta = self.with_recovery(meta); + self.idle()?; + match &mut self.inner { + EncInner::Vk(enc) => { + vk_session_alive(self.born_epoch)?; + let coded = enc.encode_16(frame, meta.force_keyframe)?; + self.steer(coded.data.len())?; + Ok(self.vk_frame(coded, meta.timestamp)) + } + #[cfg(target_os = "linux")] + EncInner::Va(enc) => enc.encode_16(frame, meta), + } + } + + /// Encode one packed RGB frame of the source size; it is box-downscaled to the encoder size. Vulkan does this and the NV12 conversion on the GPU, VA-API on the CPU. + pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result { + let meta = self.with_recovery(meta); + self.idle()?; + match &mut self.inner { + EncInner::Vk(enc) => { + vk_session_alive(self.born_epoch)?; + let coded = enc.encode_rgb(frame, meta.force_keyframe)?; + self.steer(coded.data.len())?; + Ok(self.vk_frame(coded, meta.timestamp)) + } + #[cfg(target_os = "linux")] + EncInner::Va(enc) => enc.encode(&rgb_to_i420(frame, self.size)?, meta), + } + } + + /// Encode one DMA-BUF frame of the source size, box-downscaled to the encoder size. Vulkan only; VA-API has its own PRIME path. + #[cfg(target_os = "linux")] + pub fn encode_dmabuf(&mut self, frame: &DmaBufFrame, meta: FrameMetadata) -> Result { + let planes = frame.planes(); + self.encode_dma(&frame.as_dmabuf(&planes), meta) + } + + /// Encode one NV12 or P010 DMA-BUF frame of the encoder size. Vulkan only; VA-API has its own PRIME path. + #[cfg(target_os = "linux")] + pub fn encode_dmabuf_yuv( + &mut self, + frame: &DmaBufYuvFrame, + meta: FrameMetadata, + ) -> Result { + let src = DmaBuf { + fds: frame.fds, + planes: &frame.planes, + width: frame.width, + height: frame.height, + modifier: frame.modifier, + format: frame.format, + }; + self.encode_dma(&src, meta) + } + + /// Encode one shared D3D11 texture of the source size, downscaled to the encoder size on the GPU. + #[cfg(windows)] + pub fn encode_d3d11(&mut self, frame: &D3d11Frame, meta: FrameMetadata) -> Result { + let meta = self.with_recovery(meta); + self.idle()?; + let EncInner::Vk(enc) = &mut self.inner; + vk_session_alive(self.born_epoch)?; + let src = frame.texture(); + let coded = match enc { + VkEncoder::H264(e) => e.encode_d3d11(&src, meta.force_keyframe), + VkEncoder::H265(e) => e.encode_d3d11(&src, meta.force_keyframe), + VkEncoder::Av1(e) => e.encode_d3d11(&src, meta.force_keyframe), + }?; + self.steer(coded.data.len())?; + Ok(self.vk_frame(coded, meta.timestamp)) + } + + #[cfg(target_os = "linux")] + fn encode_dma(&mut self, src: &DmaBuf, meta: FrameMetadata) -> Result { + let meta = self.with_recovery(meta); + self.idle()?; + match &mut self.inner { + EncInner::Vk(enc) => { + vk_session_alive(self.born_epoch)?; + let coded = enc.encode_dmabuf(src, meta.force_keyframe)?; + self.steer(coded.data.len())?; + Ok(self.vk_frame(coded, meta.timestamp)) + } + EncInner::Va(_) => Err(Error::unsupported( + "DMA-BUF encode", + "the VA-API backend has no DMA-BUF input here", + )), + } + } +} + +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 { + vk_grace()?; + if config.bit_depth == 10 && config.codec == EncCodec::H264 { + return Err(Error::unsupported( + "10-bit H.264 Vulkan Video encode", + "the driver offers no High 10 H.264 encode", + )); + } + if config.bit_depth != 8 && config.bit_depth != 10 { + return Err(Error::config(format!( + "encoder bit depth {}: Vulkan encodes 8-bit, or 10-bit H.265 and AV1", + config.bit_depth + ))); + } + let gpu = vk_gpu() + .ok_or_else(|| Error::unsupported("Vulkan Video encode", "no Vulkan Video device"))?; + let rate = vk_rate(&config, config.bitrate); + let level = match config.codec { + EncCodec::H264 => crate::level::h264(&config), + EncCodec::H265 => crate::level::hevc(&config), + EncCodec::Av1 => crate::level::av1(&config), + }; + let (width, height, fps, gop_size) = ( + config.width, + config.height, + config.framerate, + config.gop_size, + ); + let colour = config.colour.map(|c| ec_vk::Colour { + primaries: c.primaries, + transfer: c.transfer, + matrix: c.matrix, + full_range: c.full_range, + }); + Ok(match config.codec { + EncCodec::H264 => VkEncoder::H264(ec_vk::H264Encoder::new( + &gpu, + ec_vk::H264EncoderConfig { + width, + height, + fps, + gop_size, + rate, + profile: vk_h264_profile(config.h264_profile), + level, + colour, + quality: config.quality, + }, + )?), + EncCodec::H265 => VkEncoder::H265(ec_vk::H265Encoder::new( + &gpu, + ec_vk::H265EncoderConfig { + width, + height, + fps, + gop_size, + rate, + bit_depth: config.bit_depth, + level, + colour, + quality: config.quality, + }, + )?), + EncCodec::Av1 => VkEncoder::Av1(ec_vk::Av1Encoder::new( + &gpu, + ec_vk::Av1EncoderConfig { + width, + height, + fps, + gop_size, + rate, + bit_depth: config.bit_depth, + level, + colour, + quality: config.quality, + }, + )?), + }) +} + +fn vk_h264_profile(profile: H264Profile) -> ec_vk::H264Profile { + match profile { + H264Profile::ConstrainedBaseline => ec_vk::H264Profile::ConstrainedBaseline, + H264Profile::Main => ec_vk::H264Profile::Main, + H264Profile::High => ec_vk::H264Profile::High, + } +} + +fn vk_rate(config: &EncoderConfig, bitrate: u32) -> 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, + }, + (RateControlMode::ConstantBitrate, _) => ec_vk::RateControl::Cbr { + bitrate, + buffer_ms: hrd_buffer_ms(config), + }, + (RateControlMode::VariableBitrate, _) => ec_vk::RateControl::Vbr { + bitrate, + max_bitrate: bitrate.saturating_mul(3) / 2, + buffer_ms: hrd_buffer_ms(config), + min_qp: None, + }, + (RateControlMode::Qvbr { quality }, _) => ec_vk::RateControl::Vbr { + bitrate, + max_bitrate: bitrate, + buffer_ms: hrd_buffer_ms(config), + min_qp: Some(quality.min(51) as u8), + }, + } +} + +#[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", + )) +} + diff --git a/crates/ec-hw/src/hw/input.rs b/crates/ec-hw/src/hw/input.rs new file mode 100644 index 00000000..5f069aca --- /dev/null +++ b/crates/ec-hw/src/hw/input.rs @@ -0,0 +1,239 @@ +use super::*; + +/// Byte order of a packed 32-bit RGB pixel; the X or A byte is ignored. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RgbOrder { + /// Bytes R, G, B, X. + Rgba, + /// Bytes B, G, R, X. + Bgra, +} + +/// A packed 32-bit RGB picture with a row stride in bytes. +#[derive(Debug, Clone, Copy)] +pub struct RgbFrame<'a> { + /// Pixels, `stride * height` bytes at least. + pub data: &'a [u8], + /// Source width in pixels, even; at least the encoder width. + pub width: u32, + /// Source height in pixels, even; at least the encoder height. + pub height: u32, + /// Row stride in bytes, a multiple of 4 and at least `width * 4`. + pub stride: u32, + /// Byte order of each pixel. + pub order: RgbOrder, +} + +/// A two-plane DMA-BUF of NV12 or P010 pixels, one or two objects (one per plane). +#[cfg(target_os = "linux")] +#[derive(Debug, Clone, Copy)] +pub struct DmaBufYuvFrame<'a> { + /// DMA-BUF file descriptors, duplicated by the encoder. + pub fds: &'a [BorrowedFd<'a>], + /// Y then UV plane. + pub planes: [DmaBufPlane; 2], + /// Width in pixels, even; equal to the encoder width. + pub width: u32, + /// Height in pixels, even; equal to the encoder height. + pub height: u32, + /// DRM format modifier. + pub modifier: u64, + /// NV12 or P010. + pub format: DmaBufFormat, +} + +/// A single-plane DMA-BUF of packed 32-bit RGB pixels, linear or DRM format modifier tiled. +#[cfg(target_os = "linux")] +#[derive(Debug, Clone, Copy)] +pub struct DmaBufFrame<'a> { + /// DMA-BUF file descriptor, duplicated by the encoder. + pub fd: BorrowedFd<'a>, + /// Width in pixels, even; at least the encoder width. + pub width: u32, + /// Height in pixels, even; at least the encoder height. + pub height: u32, + /// Row pitch in bytes. + pub stride: u32, + /// Byte offset of the plane. + pub offset: u32, + /// DRM format modifier. + pub modifier: u64, + /// Byte order of each pixel. + pub order: RgbOrder, +} + +#[cfg(target_os = "linux")] +impl<'a> DmaBufFrame<'a> { + pub(super) fn planes(&self) -> [DmaBufPlane; 1] { + [DmaBufPlane { + fd: 0, + offset: self.offset, + pitch: self.stride, + }] + } + + pub(super) fn as_dmabuf<'b>(&'b self, planes: &'b [DmaBufPlane; 1]) -> DmaBuf<'b> { + DmaBuf { + fds: std::slice::from_ref(&self.fd), + planes, + width: self.width, + height: self.height, + modifier: self.modifier, + format: if self.order == RgbOrder::Bgra { + DmaBufFormat::Bgrx + } else { + DmaBufFormat::Rgbx + }, + } + } +} + +/// DRM format modifiers [`HwEncoder::encode_dmabuf`] imports for `order`, empty when Vulkan or its DMA-BUF import is unavailable. +#[cfg(target_os = "linux")] +pub fn dmabuf_modifiers(order: RgbOrder) -> Vec { + vk_gpu().map_or_else(Vec::new, |gpu| { + ec_vk::rgb_import_modifiers(&gpu, order == RgbOrder::Bgra) + }) +} + +/// Duplicates raw descriptor `fd`, which the caller keeps open for this call, so it can back a [`DmaBufFrame`]; the encoder's import cache keys on the buffer, not the descriptor. +#[cfg(target_os = "linux")] +pub fn dup_fd(fd: std::os::fd::RawFd) -> Result { + Ok(ec_vk::dup_raw_fd(fd)?) +} + +/// A D3D11 texture of packed 32-bit RGB pixels (DXGI_FORMAT_B8G8R8A8_UNORM or R8G8B8A8_UNORM, one mip, one layer) shared as an NT handle from `IDXGIResource1::CreateSharedHandle`. +/// +/// [`D3d11Pool::submit`] makes these. The encoder's import cache keys on `id`, unique per texture. The D3D11 writes must be finished before the call, and the texture left unwritten until its coded picture is returned. +#[cfg(windows)] +#[derive(Debug, Clone, Copy)] +pub struct D3d11Frame<'a> { + /// Shared NT handle; borrowed, not closed. + pub handle: std::os::windows::io::BorrowedHandle<'a>, + /// Identity of the texture, unique for the process lifetime. + pub id: u64, + /// Width in pixels, even; at least the encoder width. + pub width: u32, + /// Height in pixels, even; at least the encoder height. + pub height: u32, + /// Byte order of each pixel. + pub order: RgbOrder, +} + +#[cfg(windows)] +impl D3d11Frame<'_> { + fn texture(&self) -> ec_vk::D3d11Texture<'_> { + ec_vk::D3d11Texture { + handle: self.handle, + id: self.id, + width: self.width, + height: self.height, + bgr: self.order == RgbOrder::Bgra, + } + } +} + +/// Copies captured D3D11 frames into a ring of shared textures for [`HwEncoder::encode_d3d11`], waiting for each copy to finish. Use it on the thread that owns the device's immediate context (the capture callback). +#[cfg(windows)] +pub struct D3d11Pool(ec_vk::D3d11Pool); + +#[cfg(windows)] +impl D3d11Pool { + /// A pool on the device that produces the frames. + pub fn new(device: &ec_vk::windows::Win32::Graphics::Direct3D11::ID3D11Device) -> Result { + Ok(D3d11Pool(ec_vk::D3d11Pool::new(device)?)) + } + + /// Copies `frame` (B8G8R8A8 or R8G8B8A8, one mip, one layer) into the next shared texture. The result is valid until the pool reuses that texture, four calls later. + pub fn submit( + &mut self, + frame: &ec_vk::windows::Win32::Graphics::Direct3D11::ID3D11Texture2D, + ) -> Result> { + let t = self.0.submit(frame)?; + Ok(D3d11Frame { + handle: t.handle, + id: t.id, + width: t.width, + height: t.height, + order: if t.bgr { RgbOrder::Bgra } else { RgbOrder::Rgba }, + }) + } +} + +/// Whether [`HwEncoder::encode_d3d11`] can import textures of `order` on this machine's Vulkan device. +#[cfg(windows)] +pub fn d3d11_supported(order: RgbOrder) -> bool { + vk_gpu().is_some_and(|gpu| ec_vk::d3d11_importable(&gpu, order == RgbOrder::Bgra)) +} + +/// One picture for [`HwEncoder::submit`]. +#[derive(Debug, Clone, Copy)] +pub enum EncodeInput<'a> { + /// 8-bit I420. + I420(&'a I420), + /// 10-bit I420 of a 10-bit encoder (H.265 and AV1). + I420_16(&'a I420_16), + /// Packed RGB, box-downscaled to the encoder size. + Rgb(&'a RgbFrame<'a>), + /// DMA-BUF of packed RGB, Vulkan only. + #[cfg(target_os = "linux")] + DmaBuf(&'a DmaBufFrame<'a>), + /// DMA-BUF of NV12 or P010 at the encoder size, Vulkan only. + #[cfg(target_os = "linux")] + DmaBufYuv(&'a DmaBufYuvFrame<'a>), + /// Shared D3D11 texture of packed RGB, Vulkan only. + #[cfg(windows)] + D3d11(&'a D3d11Frame<'a>), +} + +#[cfg(target_os = "linux")] +pub(super) fn rgb_to_i420(frame: &RgbFrame, (w, h): (usize, usize)) -> Result { + let (sw, sh, stride) = ( + frame.width as usize, + frame.height as usize, + frame.stride as usize, + ); + if sw % 2 != 0 + || sh % 2 != 0 + || stride % 4 != 0 + || stride < sw * 4 + || frame.data.len() < stride * sh + { + return Err(Error::config("RGB frame size or stride")); + } + if sw < w || sh < h { + return Err(Error::config("RGB source smaller than encoder")); + } + let packed: Vec = frame + .data + .chunks(stride) + .take(sh) + .flat_map(|row| &row[..sw * 4]) + .copied() + .collect(); + let packed = if (sw, sh) == (w, h) { + packed + } else { + let mut scaled = vec![0; w * h * 4]; + ec_dsp::rgb::rgb_box_downscale(&packed, sw, sh, sw * 4, &mut scaled, w, h); + scaled + }; + let chroma = (w / 2) * (h / 2); + let mut out = I420 { + y: vec![0; w * h], + u: vec![0; chroma], + v: vec![0; chroma], + width: w as u32, + height: h as u32, + }; + match frame.order { + RgbOrder::Rgba => { + ec_dsp::rgb::rgba_to_i420_709(&packed, w, h, &mut out.y, &mut out.u, &mut out.v) + } + RgbOrder::Bgra => { + ec_dsp::rgb::bgra_to_i420_709(&packed, w, h, &mut out.y, &mut out.u, &mut out.v) + } + } + Ok(out) +} +