diff --git a/crates/ec-hw/src/dec/mod.rs b/crates/ec-hw/src/dec/mod.rs
index 8f776ac0..35d522df 100644
--- a/crates/ec-hw/src/dec/mod.rs
+++ b/crates/ec-hw/src/dec/mod.rs
@@ -19,7 +19,6 @@
use std::collections::VecDeque;
use std::rc::Rc;
-use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use ec_va::caps::{Entrypoint, Profile};
@@ -264,12 +263,12 @@ pub(crate) struct Session {
born_epoch: u64,
/// The last submitted picture, waited for after the next one is submitted
/// (depth-1 pipelining; see [`Session::submit`]).
- pending: std::sync::Mutex>,
+ pending: std::cell::RefCell >,
/// Set once a picture hung or lost the GPU context. Every submission after
/// that is refused: on Mesa, submitting to a context the kernel has reset
/// aborts the whole process from the driver's own thread, which no
/// `catch_unwind` can stop.
- pub(crate) poisoned: std::sync::atomic::AtomicBool,
+ pub(crate) poisoned: std::cell::Cell,
pub(crate) context: Rc,
display: Rc,
/// The readback image every frame of this stream reuses.
@@ -363,8 +362,8 @@ impl Session {
}
Ok(Session {
born_epoch,
- pending: std::sync::Mutex::new(None),
- poisoned: std::sync::atomic::AtomicBool::new(false),
+ pending: std::cell::RefCell::new(None),
+ poisoned: std::cell::Cell::new(false),
context,
display: Rc::clone(display),
pool,
@@ -416,7 +415,8 @@ impl Session {
// An old pending picture is waited for first: its wait is instant when
// it is done, and an error condemns the session before we submit.
let stale = self
- .pending_slot()
+ .pending
+ .borrow()
.as_ref()
.filter(|p| p.since.elapsed() > IDLE_SETTLE)
.map(|p| Rc::clone(&p.surface));
@@ -443,7 +443,7 @@ impl Session {
}
return Err(e.into());
}
- let previous = self.pending_slot().replace(Pending {
+ let previous = self.pending.borrow_mut().replace(Pending {
surface: Rc::clone(target),
since: Instant::now(),
});
@@ -453,27 +453,20 @@ impl Session {
Ok(())
}
- fn pending_slot(&self) -> std::sync::MutexGuard<'_, Option> {
- match self.pending.lock() {
- Ok(slot) => slot,
- Err(poisoned) => poisoned.into_inner(),
- }
- }
-
fn check_alive(&self) -> Result<()> {
if crate::reset::gpu_reset_epoch() != self.born_epoch {
return Err(Error::hw_reset(
"the GPU was reset after this session was created; its context is lost",
));
}
- if self.poisoned.load(Ordering::Acquire) {
+ if self.poisoned.get() {
return Err(Error::poisoned("an earlier picture failed on the GPU"));
}
Ok(())
}
fn poison(&self) {
- if !self.poisoned.swap(true, Ordering::AcqRel) {
+ if !self.poisoned.replace(true) {
crate::reset::report_gpu_reset();
}
}
diff --git a/crates/ec-hw/src/enc/headers.rs b/crates/ec-hw/src/enc/headers.rs
index a9023700..ef1d7d19 100644
--- a/crates/ec-hw/src/enc/headers.rs
+++ b/crates/ec-hw/src/enc/headers.rs
@@ -10,12 +10,12 @@
//! driver was given, or the header describes a picture other than the one the
//! hardware coded.
-/// `VAEncPackedHeaderSequence`: packed sequence-level header bits.
-pub const PACKED_HEADER_SEQUENCE: u32 = 1;
-/// `VAEncPackedHeaderPicture`: packed picture-level header bits.
-pub const PACKED_HEADER_PICTURE: u32 = 2;
-/// `VAEncPackedHeaderSlice`: packed slice-level header bits.
-pub const PACKED_HEADER_SLICE: u32 = 3;
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum PackedKind {
+ Sequence,
+ Picture,
+ Slice,
+}
use ec_core::BitWriter;
@@ -26,13 +26,13 @@ use super::Colour;
/// The bit length matters for slice headers, which do not end on a byte
/// boundary — the driver continues the bitstream from exactly that bit.
pub(crate) struct Packed {
- pub(crate) kind: u32,
+ pub(crate) kind: PackedKind,
pub(crate) bytes: Vec,
pub(crate) bits: u32,
}
/// Wrap a complete NAL: start code, header byte(s), escaped payload.
-fn nal(kind: u32, header: &[u8], rbsp: &[u8], padding_bits: u32) -> Packed {
+fn nal(kind: PackedKind, header: &[u8], rbsp: &[u8], padding_bits: u32) -> Packed {
let mut bytes = vec![0, 0, 0, 1];
bytes.extend_from_slice(header);
let mut escaped = Vec::with_capacity(rbsp.len() + 8);
@@ -133,7 +133,7 @@ pub(super) fn h264_sps(p: &H264Params) -> Packed {
w.write_ue(0); // max_num_reorder_frames
w.write_ue(1); // max_dec_frame_buffering = max_num_ref_frames
trailing(&mut w);
- nal(PACKED_HEADER_SEQUENCE, &[0x67], &w.into_bytes(), 0)
+ nal(PackedKind::Sequence, &[0x67], &w.into_bytes(), 0)
}
/// The picture parameter set (7.3.2.2).
@@ -160,7 +160,7 @@ pub(super) fn h264_pps(p: &H264Params) -> Packed {
w.write_se(0); // second_chroma_qp_index_offset
}
trailing(&mut w);
- nal(PACKED_HEADER_PICTURE, &[0x68], &w.into_bytes(), 0)
+ nal(PackedKind::Picture, &[0x68], &w.into_bytes(), 0)
}
/// The slice header (7.3.3), up to but *not* including the slice data.
@@ -202,7 +202,7 @@ pub(super) fn h264_slice_header(idr: bool, frame_num: u32, idr_pic_id: u32) -> P
let padding = (8 - bits % 8) % 8;
w.align_to_byte();
let header = if idr { 0x65 } else { 0x61 };
- nal(PACKED_HEADER_SLICE, &[header], &w.into_bytes(), padding)
+ nal(PackedKind::Slice, &[header], &w.into_bytes(), padding)
}
/// `rbsp_trailing_bits` (7.3.2.11).
@@ -220,8 +220,7 @@ fn trailing(w: &mut BitWriter) {
/// The syntax crate writes all four structures, so the encoder and the software
/// HEVC path in this family share one definition of what a parameter set is.
pub(super) mod hevc {
- #[allow(unused_imports)]
- use super::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE};
+ use super::PackedKind;
use ec_h265_syntax::{
ConformanceWindow, NalHeader, NalUnitType, Pps, ProfileTierLevel, ShortTermRefPicSet,
SliceHeader, SliceType, Sps, Vps,
@@ -350,7 +349,7 @@ pub(super) mod hevc {
pub(in crate::enc) fn packed_vps(vps: &Vps) -> Packed {
nal(
- PACKED_HEADER_SEQUENCE,
+ PackedKind::Sequence,
&NalHeader::new(NalUnitType::Vps).to_bytes(),
&vps.to_rbsp(),
0,
@@ -359,7 +358,7 @@ pub(super) mod hevc {
pub(in crate::enc) fn packed_sps(sps: &Sps) -> Packed {
nal(
- PACKED_HEADER_SEQUENCE,
+ PackedKind::Sequence,
&NalHeader::new(NalUnitType::Sps).to_bytes(),
&sps.to_rbsp(),
0,
@@ -368,7 +367,7 @@ pub(super) mod hevc {
pub(in crate::enc) fn packed_pps(pps: &Pps) -> Packed {
nal(
- PACKED_HEADER_PICTURE,
+ PackedKind::Picture,
&NalHeader::new(NalUnitType::Pps).to_bytes(),
&pps.to_rbsp(),
0,
@@ -399,7 +398,7 @@ pub(super) mod hevc {
// alignment bit has to be in what it is given.
header.write(&mut w, sps, pps, nal_type);
nal(
- PACKED_HEADER_SLICE,
+ PackedKind::Slice,
&NalHeader::new(nal_type).to_bytes(),
&w.into_bytes(),
0,
@@ -422,8 +421,7 @@ pub(super) mod hevc {
/// syntax: a field written here that disagrees with the parameter buffer is a
/// picture described two ways, and the driver believes this one.
pub(super) mod av1 {
- #[allow(unused_imports)]
- use super::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE};
+ use super::PackedKind;
use ec_core::BitWriter;
use super::{Colour, Packed};
@@ -438,7 +436,7 @@ pub(super) mod av1 {
const OBU_SIZE_BYTES: usize = 2;
/// Wrap a payload as one OBU: header byte, fixed-width `obu_size`, payload.
- fn obu(kind: u32, obu_type: u8, payload: Vec) -> Packed {
+ fn obu(kind: PackedKind, obu_type: u8, payload: Vec) -> Packed {
let mut bytes = Vec::with_capacity(payload.len() + 1 + OBU_SIZE_BYTES);
// forbidden(0) type(4) extension(0) has_size(1) reserved(0)
bytes.push(obu_type << 3 | 0b010);
@@ -538,7 +536,7 @@ pub(super) mod av1 {
w.write_bit(false); // separate_uv_delta_q
w.write_bit(false); // film_grain_params_present
trailing(&mut w);
- obu(PACKED_HEADER_SEQUENCE, 1, w.into_bytes())
+ obu(PackedKind::Sequence, 1, w.into_bytes())
}
/// What one picture's uncompressed header says.
@@ -649,7 +647,7 @@ pub(super) mod av1 {
}
}
trailing(&mut w);
- let packed = obu(PACKED_HEADER_PICTURE, 3, w.into_bytes());
+ let packed = obu(PackedKind::Picture, 3, w.into_bytes());
let offsets = FrameHeaderOffsets {
qindex,
segmentation,
diff --git a/crates/ec-hw/src/enc/mod.rs b/crates/ec-hw/src/enc/mod.rs
index eb2e9aa2..7f52416c 100644
--- a/crates/ec-hw/src/enc/mod.rs
+++ b/crates/ec-hw/src/enc/mod.rs
@@ -108,7 +108,11 @@ struct InFlight {
keyframe: bool,
}
-/// A hardware encoder.
+enum EncFrame<'a> {
+ I420(&'a I420),
+ I420_16(&'a I420_16),
+}
+
/// A hardware encoder.
pub struct Encoder {
/// The GPU reset epoch this encoder was created in.
@@ -275,36 +279,14 @@ impl Encoder {
"encode: pipelined frames pending; call flush first",
));
}
- if self.config.bit_depth != 8 {
- return Err(Error::config(format!(
- "encode: this encoder is configured for {} bits; call encode_16",
- self.config.bit_depth
- )));
- }
- self.check_size(frame.width, frame.height)?;
- let input = self
- .pool
- .acquire()
- .ok_or_else(|| Error::config("encode: every surface is still in use"))?;
- upload(&self.context, frame, input.surface(), self.coded_size)?;
+ let input = self.stage(EncFrame::I420(frame))?;
self.encode_settled(Rc::clone(input.surface()), meta)
}
/// Submit one frame without waiting for it; the oldest pending frame comes back
/// once more than [`DEPTH`] are in flight.
pub fn submit(&mut self, frame: &I420, meta: FrameMetadata) -> Result> {
- if self.config.bit_depth != 8 {
- return Err(Error::config(format!(
- "submit: this encoder is configured for {} bits; call submit_16",
- self.config.bit_depth
- )));
- }
- self.check_size(frame.width, frame.height)?;
- let input = self
- .pool
- .acquire()
- .ok_or_else(|| Error::config("submit: every surface is still in use"))?;
- upload(&self.context, frame, input.surface(), self.coded_size)?;
+ let input = self.stage(EncFrame::I420(frame))?;
self.push_pipelined(input, meta)
}
@@ -314,18 +296,7 @@ impl Encoder {
frame: &I420_16,
meta: FrameMetadata,
) -> Result > {
- if self.config.bit_depth != 10 {
- return Err(Error::config(format!(
- "submit_16: this encoder is configured for {} bits; call submit",
- self.config.bit_depth
- )));
- }
- self.check_size(frame.width, frame.height)?;
- let input = self
- .pool
- .acquire()
- .ok_or_else(|| Error::config("submit_16: every surface is still in use"))?;
- upload_16(&self.context, frame, input.surface(), self.coded_size)?;
+ let input = self.stage(EncFrame::I420_16(frame))?;
self.push_pipelined(input, meta)
}
@@ -370,19 +341,31 @@ impl Encoder {
"encode_16: pipelined frames pending; call flush first",
));
}
- if self.config.bit_depth != 10 {
+ let input = self.stage(EncFrame::I420_16(frame))?;
+ self.encode_settled(Rc::clone(input.surface()), meta)
+ }
+
+ fn stage(&mut self, frame: EncFrame) -> Result> {
+ let (bits, width, height) = match frame {
+ EncFrame::I420(f) => (8, f.width, f.height),
+ EncFrame::I420_16(f) => (10, f.width, f.height),
+ };
+ if self.config.bit_depth != bits {
return Err(Error::config(format!(
- "encode_16: this encoder is configured for {} bits; call encode",
+ "this encoder is configured for {} bits",
self.config.bit_depth
)));
}
- self.check_size(frame.width, frame.height)?;
+ self.check_size(width, height)?;
let input = self
.pool
.acquire()
- .ok_or_else(|| Error::config("encode: every surface is still in use"))?;
- upload_16(&self.context, frame, input.surface(), self.coded_size)?;
- self.encode_settled(Rc::clone(input.surface()), meta)
+ .ok_or_else(|| Error::config("every surface is still in use"))?;
+ match frame {
+ EncFrame::I420(f) => upload(&self.context, f, input.surface(), self.coded_size)?,
+ EncFrame::I420_16(f) => upload_16(&self.context, f, input.surface(), self.coded_size)?,
+ }
+ Ok(input)
}
fn check_size(&self, width: u32, height: u32) -> Result<()> {
@@ -593,12 +576,9 @@ impl Encoder {
out: &mut Vec,
) -> Result<()> {
let kind = match packed.kind {
- headers::PACKED_HEADER_SEQUENCE => EncPackedHeaderType::Sequence,
- headers::PACKED_HEADER_PICTURE => EncPackedHeaderType::Picture,
- headers::PACKED_HEADER_SLICE => EncPackedHeaderType::Slice,
- other => {
- return Err(Error::config(format!("unknown packed header kind {other}")));
- }
+ headers::PackedKind::Sequence => EncPackedHeaderType::Sequence,
+ headers::PackedKind::Picture => EncPackedHeaderType::Picture,
+ headers::PackedKind::Slice => EncPackedHeaderType::Slice,
};
out.push(BufferType::EncPackedHeaderParameter(
EncPackedHeaderParameter::new(kind, packed.bits, true),
diff --git a/crates/ec-hw/src/hw.rs b/crates/ec-hw/src/hw.rs
index 42966ef4..4ad2f1d6 100644
--- a/crates/ec-hw/src/hw.rs
+++ b/crates/ec-hw/src/hw.rs
@@ -27,1336 +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,
-}
-
-/// 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 = [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.encode_dma(&src, 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..9e8f4edf
--- /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<'_> {
+ pub(super) 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)
+}
+
diff --git a/crates/ec-hw/src/picture.rs b/crates/ec-hw/src/picture.rs
index d96a824f..0265cb9c 100644
--- a/crates/ec-hw/src/picture.rs
+++ b/crates/ec-hw/src/picture.rs
@@ -258,20 +258,16 @@ pub(crate) fn fill_i420_16(
let bytes = if bit_depth == 8 { 1 } else { 2 };
check_plane("luma", y_plane.len(), y_pitch, h, w * bytes)?;
check_plane("chroma", uv_plane.len(), uv_pitch, ch, cw * 2 * bytes)?;
- let mut row_buf = vec![0u8; uv_pitch.max(y_pitch).max(w * 2)];
match bit_depth {
8 => {
for row in 0..h {
- let src = row * y_pitch;
- row_buf[..w].copy_from_slice(&y_plane[src..src + w]);
- for (dst, &sample) in out.y[row * w..(row + 1) * w].iter_mut().zip(&row_buf[..w]) {
+ let line = plane_row(y_plane, y_pitch, row, w);
+ for (dst, &sample) in out.y[row * w..(row + 1) * w].iter_mut().zip(line) {
*dst = u16::from(sample) << 2;
}
}
for row in 0..ch {
- let src = row * uv_pitch;
- let line = &mut row_buf[..cw * 2];
- line.copy_from_slice(&uv_plane[src..src + cw * 2]);
+ let line = plane_row(uv_plane, uv_pitch, row, cw * 2);
for col in 0..cw {
out.u[row * cw + col] = u16::from(line[col * 2]) << 2;
out.v[row * cw + col] = u16::from(line[col * 2 + 1]) << 2;
@@ -282,18 +278,14 @@ pub(crate) fn fill_i420_16(
// P010 is 16-bit little endian with the sample in the top ten
// bits; the low six are zero padding.
for row in 0..h {
- let src = row * y_pitch;
- let line = &mut row_buf[..w * 2];
- line.copy_from_slice(&y_plane[src..src + w * 2]);
+ let line = plane_row(y_plane, y_pitch, row, w * 2);
for col in 0..w {
out.y[row * w + col] =
u16::from_le_bytes([line[col * 2], line[col * 2 + 1]]) >> 6;
}
}
for row in 0..ch {
- let src = row * uv_pitch;
- let line = &mut row_buf[..cw * 4];
- line.copy_from_slice(&uv_plane[src..src + cw * 4]);
+ let line = plane_row(uv_plane, uv_pitch, row, cw * 4);
for col in 0..cw {
out.u[row * cw + col] =
u16::from_le_bytes([line[col * 4], line[col * 4 + 1]]) >> 6;
@@ -347,17 +339,13 @@ pub(crate) fn fill_i420(
let bytes = if bit_depth == 8 { 1 } else { 2 };
check_plane("luma", y_plane.len(), y_pitch, h, w * bytes)?;
check_plane("chroma", uv_plane.len(), uv_pitch, ch, cw * 2 * bytes)?;
- let mut row_buf = vec![0u8; uv_pitch.max(y_pitch).max(w * 2)];
match bit_depth {
8 => {
for row in 0..h {
- let src = row * y_pitch;
- out.y[row * w..(row + 1) * w].copy_from_slice(&y_plane[src..src + w]);
+ out.y[row * w..(row + 1) * w].copy_from_slice(plane_row(y_plane, y_pitch, row, w));
}
for row in 0..ch {
- let src = row * uv_pitch;
- let line = &mut row_buf[..cw * 2];
- line.copy_from_slice(&uv_plane[src..src + cw * 2]);
+ let line = plane_row(uv_plane, uv_pitch, row, cw * 2);
for col in 0..cw {
out.u[row * cw + col] = line[col * 2];
out.v[row * cw + col] = line[col * 2 + 1];
@@ -368,17 +356,13 @@ pub(crate) fn fill_i420(
// P010 keeps the sample in the *high* bits of each u16, so the
// 8-bit value is the high byte — a shift by 8, not by 2.
for row in 0..h {
- let src = row * y_pitch;
- let line = &mut row_buf[..w * 2];
- line.copy_from_slice(&y_plane[src..src + w * 2]);
+ let line = plane_row(y_plane, y_pitch, row, w * 2);
for col in 0..w {
out.y[row * w + col] = line[col * 2 + 1];
}
}
for row in 0..ch {
- let src = row * uv_pitch;
- let line = &mut row_buf[..cw * 4];
- line.copy_from_slice(&uv_plane[src..src + cw * 4]);
+ let line = plane_row(uv_plane, uv_pitch, row, cw * 4);
for col in 0..cw {
out.u[row * cw + col] = line[col * 4 + 1];
out.v[row * cw + col] = line[col * 4 + 3];
@@ -389,6 +373,10 @@ pub(crate) fn fill_i420(
Ok(())
}
+fn plane_row(plane: &[u8], pitch: usize, row: usize, len: usize) -> &[u8] {
+ &plane[row * pitch..row * pitch + len]
+}
+
/// Check that `rows` rows of `row_bytes` bytes at `pitch` fit in a plane of
/// `len` bytes. A lost or half-initialised GPU context can hand back a short
/// or odd mapping; this turns what would be a slice panic into an error.
diff --git a/crates/ec-hw/src/pool.rs b/crates/ec-hw/src/pool.rs
index b795188b..1896c3ed 100644
--- a/crates/ec-hw/src/pool.rs
+++ b/crates/ec-hw/src/pool.rs
@@ -13,12 +13,12 @@
use ec_va::{Surface, SurfaceSpec};
use std::ops::Deref;
use std::rc::{Rc, Weak};
-use std::sync::Mutex;
+use std::cell::RefCell;
struct PoolInner {
/// Every surface, in allocation order.
- all: Mutex>>,
- free: Mutex>>,
+ all: RefCell>>,
+ free: RefCell>>,
}
/// A fixed-size pool of identically specified surfaces.
@@ -36,8 +36,8 @@ impl SurfacePool {
let all: Vec> = surfaces.into_iter().map(Rc::new).collect();
SurfacePool {
inner: Rc::new(PoolInner {
- free: Mutex::new(all.clone()),
- all: Mutex::new(all),
+ free: RefCell::new(all.clone()),
+ all: RefCell::new(all),
}),
spec: *spec,
}
@@ -50,7 +50,7 @@ impl SurfacePool {
/// Total surfaces in the pool.
pub fn len(&self) -> usize {
- self.inner.all.lock().map(|all| all.len()).unwrap_or(0)
+ self.inner.all.borrow().len()
}
/// True when the pool holds no surfaces at all.
@@ -61,17 +61,13 @@ impl SurfacePool {
/// Add surfaces allocated with the pool's spec, free for [`SurfacePool::acquire`].
pub fn grow(&self, surfaces: Vec) {
let surfaces: Vec> = surfaces.into_iter().map(Rc::new).collect();
- if let Ok(mut all) = self.inner.all.lock() {
- all.extend(surfaces.iter().cloned());
- }
- if let Ok(mut free) = self.inner.free.lock() {
- free.extend(surfaces);
- }
+ self.inner.all.borrow_mut().extend(surfaces.iter().cloned());
+ self.inner.free.borrow_mut().extend(surfaces);
}
/// Surfaces currently available.
pub fn available(&self) -> usize {
- self.inner.free.lock().map(|f| f.len()).unwrap_or(0)
+ self.inner.free.borrow().len()
}
/// Take a free surface, or `None` when every one is still in use.
@@ -79,13 +75,7 @@ impl SurfacePool {
/// A `None` is the caller's cue to release output frames, not an error: a
/// decoder that has handed out its whole pool is waiting on the consumer.
pub fn acquire(&self) -> Option> {
- // A poisoned lock means another thread panicked while holding it; the
- // free list is a plain Vec, so its contents are still consistent.
- let mut free = match self.inner.free.lock() {
- Ok(free) => free,
- Err(poisoned) => poisoned.into_inner(),
- };
- let surface = free.pop()?;
+ let surface = self.inner.free.borrow_mut().pop()?;
Some(Rc::new(PooledSurface {
surface,
pool: Rc::downgrade(&self.inner),
@@ -128,10 +118,6 @@ impl Drop for PooledSurface {
// The pool is gone, so the surface simply drops with this handle.
return;
};
- let mut free = match pool.free.lock() {
- Ok(free) => free,
- Err(poisoned) => poisoned.into_inner(),
- };
- free.push(Rc::clone(&self.surface));
+ pool.free.borrow_mut().push(Rc::clone(&self.surface));
}
}