S2: hw.rs split into hw/{caps,input,encoder,decoder} by line range (move only; four helpers widened to pub(super) for the new boundaries)
Browse files at this commit184c87ba1fd722fe9c478bed23c8e189319fbec1Parent: db2a8965 changed files +1356 -1339
- crates/ec-hw/src/hw.rs +9 -1339
- crates/ec-hw/src/hw/caps.rs +231 -0
- crates/ec-hw/src/hw/decoder.rs +256 -0
- crates/ec-hw/src/hw/encoder.rs +621 -0
- crates/ec-hw/src/hw/input.rs +239 -0
crates/ec-hw/src/hw.rsmodified+9 -1339
| @@ -27,1342 +27,12 @@ use crate::dec::Decoder as VaDecoder; | |||
| 27 | #[cfg(target_os = "linux")] | 27 | #[cfg(target_os = "linux")] |
| 28 | use crate::enc::Encoder as VaEncoder; | 28 | use crate::enc::Encoder as VaEncoder; |
| 29 | 29 | ||
| 30 | -/// Where a codec runs. | 30 | +mod caps; |
| 31 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | 31 | +mod decoder; |
| 32 | -pub enum Backend { | 32 | +mod encoder; |
| 33 | - /// Vulkan Video, every OS. | 33 | +mod input; |
| 34 | - Vk, | 34 | + |
| 35 | - /// VA-API, Linux only. | 35 | +pub use caps::*; |
| 36 | - Va, | 36 | +pub use decoder::*; |
| 37 | -} | 37 | +pub use encoder::*; |
| 38 | - | 38 | +pub use input::*; |
| 39 | -/// Which way a codec runs. | ||
| 40 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 41 | -pub enum Direction { | ||
| 42 | - /// Encode. | ||
| 43 | - Encode, | ||
| 44 | - /// Decode. | ||
| 45 | - Decode, | ||
| 46 | -} | ||
| 47 | - | ||
| 48 | -/// Profile of a [`Capability`], 4:2:0 only. | ||
| 49 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 50 | -pub enum CodecProfile { | ||
| 51 | - /// H.264 Constrained Baseline, 8-bit. | ||
| 52 | - H264ConstrainedBaseline, | ||
| 53 | - /// H.264 Main, 8-bit. | ||
| 54 | - H264Main, | ||
| 55 | - /// H.264 High, 8-bit. | ||
| 56 | - H264High, | ||
| 57 | - /// H.265 Main, 8-bit. | ||
| 58 | - H265Main, | ||
| 59 | - /// H.265 Main 10, 10-bit. | ||
| 60 | - H265Main10, | ||
| 61 | - /// AV1 Main, 8-bit. | ||
| 62 | - Av1Main, | ||
| 63 | - /// AV1 Main, 10-bit. | ||
| 64 | - Av1Main10, | ||
| 65 | - /// VP9 Profile 0, 8-bit. | ||
| 66 | - Vp9Profile0, | ||
| 67 | - /// VP9 Profile 2, 10-bit. | ||
| 68 | - Vp9Profile2, | ||
| 69 | -} | ||
| 70 | - | ||
| 71 | -/// One codec, profile, direction and backend this machine offers. | ||
| 72 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 73 | -pub struct Capability { | ||
| 74 | - /// Codec. | ||
| 75 | - pub codec: Codec, | ||
| 76 | - /// Profile. | ||
| 77 | - pub profile: CodecProfile, | ||
| 78 | - /// Direction. | ||
| 79 | - pub direction: Direction, | ||
| 80 | - /// Largest width in luma samples. | ||
| 81 | - pub max_width: u32, | ||
| 82 | - /// Largest height in luma samples. | ||
| 83 | - pub max_height: u32, | ||
| 84 | - /// Backend offering it. | ||
| 85 | - pub backend: Backend, | ||
| 86 | -} | ||
| 87 | - | ||
| 88 | -thread_local! { | ||
| 89 | - static GPU: RefCell<Option<(u64, Option<ec_vk::Gpu>)>> = const { RefCell::new(None) }; | ||
| 90 | -} | ||
| 91 | - | ||
| 92 | -pub(crate) fn vk_gpu() -> Option<ec_vk::Gpu> { | ||
| 93 | - GPU.with_borrow_mut(|cached| { | ||
| 94 | - let epoch = crate::reset::gpu_reset_epoch(); | ||
| 95 | - match cached { | ||
| 96 | - Some((born, gpu)) if *born == epoch => gpu.clone(), | ||
| 97 | - _ => { | ||
| 98 | - let gpu = ec_vk::Gpu::open().ok(); | ||
| 99 | - *cached = Some((epoch, gpu.clone())); | ||
| 100 | - gpu | ||
| 101 | - } | ||
| 102 | - } | ||
| 103 | - }) | ||
| 104 | -} | ||
| 105 | - | ||
| 106 | -fn vk_session_alive(born_epoch: u64) -> Result<()> { | ||
| 107 | - if crate::reset::gpu_reset_epoch() == born_epoch { | ||
| 108 | - Ok(()) | ||
| 109 | - } else { | ||
| 110 | - Err(Error::hw_reset( | ||
| 111 | - "the GPU was reset after this Vulkan session was created; its device is lost", | ||
| 112 | - )) | ||
| 113 | - } | ||
| 114 | -} | ||
| 115 | - | ||
| 116 | -fn vk_grace() -> Result<()> { | ||
| 117 | - if crate::reset::gpu_recently_reset() { | ||
| 118 | - Err(Error::hw_reset( | ||
| 119 | - "the GPU was reset moments ago; new Vulkan sessions wait out the grace period", | ||
| 120 | - )) | ||
| 121 | - } else { | ||
| 122 | - Ok(()) | ||
| 123 | - } | ||
| 124 | -} | ||
| 125 | - | ||
| 126 | -/// Every codec, direction and backend this machine can use. Never fails. | ||
| 127 | -pub fn capabilities() -> Vec<Capability> { | ||
| 128 | - let mut out = Vec::new(); | ||
| 129 | - if let Some(gpu) = vk_gpu() { | ||
| 130 | - for caps in gpu.caps() { | ||
| 131 | - let codec = match caps.codec { | ||
| 132 | - ec_vk::Codec::H264 => Codec::H264, | ||
| 133 | - ec_vk::Codec::H265 => Codec::H265, | ||
| 134 | - ec_vk::Codec::Av1 => Codec::Av1, | ||
| 135 | - ec_vk::Codec::Vp9 => Codec::Vp9, | ||
| 136 | - }; | ||
| 137 | - let direction = match caps.direction { | ||
| 138 | - ec_vk::Direction::Encode => Direction::Encode, | ||
| 139 | - ec_vk::Direction::Decode => Direction::Decode, | ||
| 140 | - }; | ||
| 141 | - push( | ||
| 142 | - &mut out, | ||
| 143 | - Capability { | ||
| 144 | - codec, | ||
| 145 | - profile: vk_profile(caps.profile), | ||
| 146 | - direction, | ||
| 147 | - max_width: caps.max_width, | ||
| 148 | - max_height: caps.max_height, | ||
| 149 | - backend: Backend::Vk, | ||
| 150 | - }, | ||
| 151 | - ); | ||
| 152 | - } | ||
| 153 | - } | ||
| 154 | - #[cfg(target_os = "linux")] | ||
| 155 | - va_capabilities(&mut out); | ||
| 156 | - out | ||
| 157 | -} | ||
| 158 | - | ||
| 159 | -fn push(out: &mut Vec<Capability>, cap: Capability) { | ||
| 160 | - let known = out | ||
| 161 | - .iter() | ||
| 162 | - .any(|c| { | ||
| 163 | - c.codec == cap.codec | ||
| 164 | - && c.profile == cap.profile | ||
| 165 | - && c.direction == cap.direction | ||
| 166 | - && c.backend == cap.backend | ||
| 167 | - }); | ||
| 168 | - if !known { | ||
| 169 | - out.push(cap); | ||
| 170 | - } | ||
| 171 | -} | ||
| 172 | - | ||
| 173 | -#[cfg(target_os = "linux")] | ||
| 174 | -fn va_capabilities(out: &mut Vec<Capability>) { | ||
| 175 | - let Ok(display) = ec_va::open() else { | ||
| 176 | - return; | ||
| 177 | - }; | ||
| 178 | - let Ok(report) = ec_va::CapReport::probe(&display) else { | ||
| 179 | - return; | ||
| 180 | - }; | ||
| 181 | - for entry in &report.entries { | ||
| 182 | - let direction = match entry.entrypoint { | ||
| 183 | - ec_va::Entrypoint::VLD => Direction::Decode, | ||
| 184 | - ec_va::Entrypoint::EncSlice | ec_va::Entrypoint::EncSliceLP => Direction::Encode, | ||
| 185 | - _ => continue, | ||
| 186 | - }; | ||
| 187 | - let (max_width, max_height) = match &entry.surfaces { | ||
| 188 | - Some(s) => (s.max_width.unwrap_or(4096), s.max_height.unwrap_or(4096)), | ||
| 189 | - None => (4096, 4096), | ||
| 190 | - }; | ||
| 191 | - for profile in va_profiles(entry.profile, entry.rt_formats) { | ||
| 192 | - push( | ||
| 193 | - out, | ||
| 194 | - Capability { | ||
| 195 | - codec: profile.codec(), | ||
| 196 | - profile, | ||
| 197 | - direction, | ||
| 198 | - max_width, | ||
| 199 | - max_height, | ||
| 200 | - backend: Backend::Va, | ||
| 201 | - }, | ||
| 202 | - ); | ||
| 203 | - } | ||
| 204 | - } | ||
| 205 | -} | ||
| 206 | - | ||
| 207 | -#[cfg(target_os = "linux")] | ||
| 208 | -impl CodecProfile { | ||
| 209 | - fn codec(self) -> Codec { | ||
| 210 | - match self { | ||
| 211 | - CodecProfile::H264ConstrainedBaseline | ||
| 212 | - | CodecProfile::H264Main | ||
| 213 | - | CodecProfile::H264High => Codec::H264, | ||
| 214 | - CodecProfile::H265Main | CodecProfile::H265Main10 => Codec::H265, | ||
| 215 | - CodecProfile::Av1Main | CodecProfile::Av1Main10 => Codec::Av1, | ||
| 216 | - CodecProfile::Vp9Profile0 | CodecProfile::Vp9Profile2 => Codec::Vp9, | ||
| 217 | - } | ||
| 218 | - } | ||
| 219 | -} | ||
| 220 | - | ||
| 221 | -#[cfg(target_os = "linux")] | ||
| 222 | -fn va_profiles(profile: ec_va::Profile, rt_formats: u32) -> Vec<CodecProfile> { | ||
| 223 | - let yuv420 = ec_va::va::VA_RT_FORMAT_YUV420; | ||
| 224 | - let yuv420_10 = ec_va::va::VA_RT_FORMAT_YUV420_10; | ||
| 225 | - match profile { | ||
| 226 | - ec_va::Profile::H264ConstrainedBaseline => vec![CodecProfile::H264ConstrainedBaseline], | ||
| 227 | - ec_va::Profile::H264Main => vec![CodecProfile::H264Main], | ||
| 228 | - ec_va::Profile::H264High => vec![CodecProfile::H264High], | ||
| 229 | - ec_va::Profile::HEVCMain => vec![CodecProfile::H265Main], | ||
| 230 | - ec_va::Profile::HEVCMain10 => vec![CodecProfile::H265Main10], | ||
| 231 | - ec_va::Profile::VP9Profile0 => vec![CodecProfile::Vp9Profile0], | ||
| 232 | - ec_va::Profile::VP9Profile2 if rt_formats & yuv420_10 != 0 => vec![CodecProfile::Vp9Profile2], | ||
| 233 | - ec_va::Profile::AV1Profile0 => [ | ||
| 234 | - (yuv420, CodecProfile::Av1Main), | ||
| 235 | - (yuv420_10, CodecProfile::Av1Main10), | ||
| 236 | - ] | ||
| 237 | - .into_iter() | ||
| 238 | - .filter(|(bit, _)| rt_formats & bit != 0) | ||
| 239 | - .map(|(_, p)| p) | ||
| 240 | - .collect(), | ||
| 241 | - _ => Vec::new(), | ||
| 242 | - } | ||
| 243 | -} | ||
| 244 | - | ||
| 245 | -fn vk_profile(profile: ec_vk::CodecProfile) -> CodecProfile { | ||
| 246 | - match profile { | ||
| 247 | - ec_vk::CodecProfile::H264High => CodecProfile::H264High, | ||
| 248 | - ec_vk::CodecProfile::H265Main => CodecProfile::H265Main, | ||
| 249 | - ec_vk::CodecProfile::H265Main10 => CodecProfile::H265Main10, | ||
| 250 | - ec_vk::CodecProfile::Av1Main => CodecProfile::Av1Main, | ||
| 251 | - ec_vk::CodecProfile::Av1Main10 => CodecProfile::Av1Main10, | ||
| 252 | - ec_vk::CodecProfile::Vp9Profile0 => CodecProfile::Vp9Profile0, | ||
| 253 | - ec_vk::CodecProfile::Vp9Profile2 => CodecProfile::Vp9Profile2, | ||
| 254 | - ec_vk::CodecProfile::H264ConstrainedBaseline => CodecProfile::H264ConstrainedBaseline, | ||
| 255 | - ec_vk::CodecProfile::H264Main => CodecProfile::H264Main, | ||
| 256 | - } | ||
| 257 | -} | ||
| 258 | - | ||
| 259 | -/// Byte order of a packed 32-bit RGB pixel; the X or A byte is ignored. | ||
| 260 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 261 | -pub enum RgbOrder { | ||
| 262 | - /// Bytes R, G, B, X. | ||
| 263 | - Rgba, | ||
| 264 | - /// Bytes B, G, R, X. | ||
| 265 | - Bgra, | ||
| 266 | -} | ||
| 267 | - | ||
| 268 | -/// A packed 32-bit RGB picture with a row stride in bytes. | ||
| 269 | -#[derive(Debug, Clone, Copy)] | ||
| 270 | -pub struct RgbFrame<'a> { | ||
| 271 | - /// Pixels, `stride * height` bytes at least. | ||
| 272 | - pub data: &'a [u8], | ||
| 273 | - /// Source width in pixels, even; at least the encoder width. | ||
| 274 | - pub width: u32, | ||
| 275 | - /// Source height in pixels, even; at least the encoder height. | ||
| 276 | - pub height: u32, | ||
| 277 | - /// Row stride in bytes, a multiple of 4 and at least `width * 4`. | ||
| 278 | - pub stride: u32, | ||
| 279 | - /// Byte order of each pixel. | ||
| 280 | - pub order: RgbOrder, | ||
| 281 | -} | ||
| 282 | - | ||
| 283 | -/// A two-plane DMA-BUF of NV12 or P010 pixels, one or two objects (one per plane). | ||
| 284 | -#[cfg(target_os = "linux")] | ||
| 285 | -#[derive(Debug, Clone, Copy)] | ||
| 286 | -pub struct DmaBufYuvFrame<'a> { | ||
| 287 | - /// DMA-BUF file descriptors, duplicated by the encoder. | ||
| 288 | - pub fds: &'a [BorrowedFd<'a>], | ||
| 289 | - /// Y then UV plane. | ||
| 290 | - pub planes: [DmaBufPlane; 2], | ||
| 291 | - /// Width in pixels, even; equal to the encoder width. | ||
| 292 | - pub width: u32, | ||
| 293 | - /// Height in pixels, even; equal to the encoder height. | ||
| 294 | - pub height: u32, | ||
| 295 | - /// DRM format modifier. | ||
| 296 | - pub modifier: u64, | ||
| 297 | - /// NV12 or P010. | ||
| 298 | - pub format: DmaBufFormat, | ||
| 299 | -} | ||
| 300 | - | ||
| 301 | -/// A single-plane DMA-BUF of packed 32-bit RGB pixels, linear or DRM format modifier tiled. | ||
| 302 | -#[cfg(target_os = "linux")] | ||
| 303 | -#[derive(Debug, Clone, Copy)] | ||
| 304 | -pub struct DmaBufFrame<'a> { | ||
| 305 | - /// DMA-BUF file descriptor, duplicated by the encoder. | ||
| 306 | - pub fd: BorrowedFd<'a>, | ||
| 307 | - /// Width in pixels, even; at least the encoder width. | ||
| 308 | - pub width: u32, | ||
| 309 | - /// Height in pixels, even; at least the encoder height. | ||
| 310 | - pub height: u32, | ||
| 311 | - /// Row pitch in bytes. | ||
| 312 | - pub stride: u32, | ||
| 313 | - /// Byte offset of the plane. | ||
| 314 | - pub offset: u32, | ||
| 315 | - /// DRM format modifier. | ||
| 316 | - pub modifier: u64, | ||
| 317 | - /// Byte order of each pixel. | ||
| 318 | - pub order: RgbOrder, | ||
| 319 | -} | ||
| 320 | - | ||
| 321 | -#[cfg(target_os = "linux")] | ||
| 322 | -impl<'a> DmaBufFrame<'a> { | ||
| 323 | - fn planes(&self) -> [DmaBufPlane; 1] { | ||
| 324 | - [DmaBufPlane { | ||
| 325 | - fd: 0, | ||
| 326 | - offset: self.offset, | ||
| 327 | - pitch: self.stride, | ||
| 328 | - }] | ||
| 329 | - } | ||
| 330 | - | ||
| 331 | - fn as_dmabuf<'b>(&'b self, planes: &'b [DmaBufPlane; 1]) -> DmaBuf<'b> { | ||
| 332 | - DmaBuf { | ||
| 333 | - fds: std::slice::from_ref(&self.fd), | ||
| 334 | - planes, | ||
| 335 | - width: self.width, | ||
| 336 | - height: self.height, | ||
| 337 | - modifier: self.modifier, | ||
| 338 | - format: if self.order == RgbOrder::Bgra { | ||
| 339 | - DmaBufFormat::Bgrx | ||
| 340 | - } else { | ||
| 341 | - DmaBufFormat::Rgbx | ||
| 342 | - }, | ||
| 343 | - } | ||
| 344 | - } | ||
| 345 | -} | ||
| 346 | - | ||
| 347 | -/// DRM format modifiers [`HwEncoder::encode_dmabuf`] imports for `order`, empty when Vulkan or its DMA-BUF import is unavailable. | ||
| 348 | -#[cfg(target_os = "linux")] | ||
| 349 | -pub fn dmabuf_modifiers(order: RgbOrder) -> Vec<u64> { | ||
| 350 | - vk_gpu().map_or_else(Vec::new, |gpu| { | ||
| 351 | - ec_vk::rgb_import_modifiers(&gpu, order == RgbOrder::Bgra) | ||
| 352 | - }) | ||
| 353 | -} | ||
| 354 | - | ||
| 355 | -/// 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. | ||
| 356 | -#[cfg(target_os = "linux")] | ||
| 357 | -pub fn dup_fd(fd: std::os::fd::RawFd) -> Result<std::os::fd::OwnedFd> { | ||
| 358 | - Ok(ec_vk::dup_raw_fd(fd)?) | ||
| 359 | -} | ||
| 360 | - | ||
| 361 | -/// 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`. | ||
| 362 | -/// | ||
| 363 | -/// [`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. | ||
| 364 | -#[cfg(windows)] | ||
| 365 | -#[derive(Debug, Clone, Copy)] | ||
| 366 | -pub struct D3d11Frame<'a> { | ||
| 367 | - /// Shared NT handle; borrowed, not closed. | ||
| 368 | - pub handle: std::os::windows::io::BorrowedHandle<'a>, | ||
| 369 | - /// Identity of the texture, unique for the process lifetime. | ||
| 370 | - pub id: u64, | ||
| 371 | - /// Width in pixels, even; at least the encoder width. | ||
| 372 | - pub width: u32, | ||
| 373 | - /// Height in pixels, even; at least the encoder height. | ||
| 374 | - pub height: u32, | ||
| 375 | - /// Byte order of each pixel. | ||
| 376 | - pub order: RgbOrder, | ||
| 377 | -} | ||
| 378 | - | ||
| 379 | -#[cfg(windows)] | ||
| 380 | -impl D3d11Frame<'_> { | ||
| 381 | - fn texture(&self) -> ec_vk::D3d11Texture<'_> { | ||
| 382 | - ec_vk::D3d11Texture { | ||
| 383 | - handle: self.handle, | ||
| 384 | - id: self.id, | ||
| 385 | - width: self.width, | ||
| 386 | - height: self.height, | ||
| 387 | - bgr: self.order == RgbOrder::Bgra, | ||
| 388 | - } | ||
| 389 | - } | ||
| 390 | -} | ||
| 391 | - | ||
| 392 | -/// 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). | ||
| 393 | -#[cfg(windows)] | ||
| 394 | -pub struct D3d11Pool(ec_vk::D3d11Pool); | ||
| 395 | - | ||
| 396 | -#[cfg(windows)] | ||
| 397 | -impl D3d11Pool { | ||
| 398 | - /// A pool on the device that produces the frames. | ||
| 399 | - pub fn new(device: &ec_vk::windows::Win32::Graphics::Direct3D11::ID3D11Device) -> Result<Self> { | ||
| 400 | - Ok(D3d11Pool(ec_vk::D3d11Pool::new(device)?)) | ||
| 401 | - } | ||
| 402 | - | ||
| 403 | - /// 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. | ||
| 404 | - pub fn submit( | ||
| 405 | - &mut self, | ||
| 406 | - frame: &ec_vk::windows::Win32::Graphics::Direct3D11::ID3D11Texture2D, | ||
| 407 | - ) -> Result<D3d11Frame<'_>> { | ||
| 408 | - let t = self.0.submit(frame)?; | ||
| 409 | - Ok(D3d11Frame { | ||
| 410 | - handle: t.handle, | ||
| 411 | - id: t.id, | ||
| 412 | - width: t.width, | ||
| 413 | - height: t.height, | ||
| 414 | - order: if t.bgr { RgbOrder::Bgra } else { RgbOrder::Rgba }, | ||
| 415 | - }) | ||
| 416 | - } | ||
| 417 | -} | ||
| 418 | - | ||
| 419 | -/// Whether [`HwEncoder::encode_d3d11`] can import textures of `order` on this machine's Vulkan device. | ||
| 420 | -#[cfg(windows)] | ||
| 421 | -pub fn d3d11_supported(order: RgbOrder) -> bool { | ||
| 422 | - vk_gpu().is_some_and(|gpu| ec_vk::d3d11_importable(&gpu, order == RgbOrder::Bgra)) | ||
| 423 | -} | ||
| 424 | - | ||
| 425 | -/// One picture for [`HwEncoder::submit`]. | ||
| 426 | -#[derive(Debug, Clone, Copy)] | ||
| 427 | -pub enum EncodeInput<'a> { | ||
| 428 | - /// 8-bit I420. | ||
| 429 | - I420(&'a I420), | ||
| 430 | - /// 10-bit I420 of a 10-bit encoder (H.265 and AV1). | ||
| 431 | - I420_16(&'a I420_16), | ||
| 432 | - /// Packed RGB, box-downscaled to the encoder size. | ||
| 433 | - Rgb(&'a RgbFrame<'a>), | ||
| 434 | - /// DMA-BUF of packed RGB, Vulkan only. | ||
| 435 | - #[cfg(target_os = "linux")] | ||
| 436 | - DmaBuf(&'a DmaBufFrame<'a>), | ||
| 437 | - /// DMA-BUF of NV12 or P010 at the encoder size, Vulkan only. | ||
| 438 | - #[cfg(target_os = "linux")] | ||
| 439 | - DmaBufYuv(&'a DmaBufYuvFrame<'a>), | ||
| 440 | - /// Shared D3D11 texture of packed RGB, Vulkan only. | ||
| 441 | - #[cfg(windows)] | ||
| 442 | - D3d11(&'a D3d11Frame<'a>), | ||
| 443 | -} | ||
| 444 | - | ||
| 445 | -#[cfg(target_os = "linux")] | ||
| 446 | -fn rgb_to_i420(frame: &RgbFrame, (w, h): (usize, usize)) -> Result<I420> { | ||
| 447 | - let (sw, sh, stride) = ( | ||
| 448 | - frame.width as usize, | ||
| 449 | - frame.height as usize, | ||
| 450 | - frame.stride as usize, | ||
| 451 | - ); | ||
| 452 | - if sw % 2 != 0 | ||
| 453 | - || sh % 2 != 0 | ||
| 454 | - || stride % 4 != 0 | ||
| 455 | - || stride < sw * 4 | ||
| 456 | - || frame.data.len() < stride * sh | ||
| 457 | - { | ||
| 458 | - return Err(Error::config("RGB frame size or stride")); | ||
| 459 | - } | ||
| 460 | - if sw < w || sh < h { | ||
| 461 | - return Err(Error::config("RGB source smaller than encoder")); | ||
| 462 | - } | ||
| 463 | - let packed: Vec<u8> = frame | ||
| 464 | - .data | ||
| 465 | - .chunks(stride) | ||
| 466 | - .take(sh) | ||
| 467 | - .flat_map(|row| &row[..sw * 4]) | ||
| 468 | - .copied() | ||
| 469 | - .collect(); | ||
| 470 | - let packed = if (sw, sh) == (w, h) { | ||
| 471 | - packed | ||
| 472 | - } else { | ||
| 473 | - let mut scaled = vec![0; w * h * 4]; | ||
| 474 | - ec_dsp::rgb::rgb_box_downscale(&packed, sw, sh, sw * 4, &mut scaled, w, h); | ||
| 475 | - scaled | ||
| 476 | - }; | ||
| 477 | - let chroma = (w / 2) * (h / 2); | ||
| 478 | - let mut out = I420 { | ||
| 479 | - y: vec![0; w * h], | ||
| 480 | - u: vec![0; chroma], | ||
| 481 | - v: vec![0; chroma], | ||
| 482 | - width: w as u32, | ||
| 483 | - height: h as u32, | ||
| 484 | - }; | ||
| 485 | - match frame.order { | ||
| 486 | - RgbOrder::Rgba => { | ||
| 487 | - ec_dsp::rgb::rgba_to_i420_709(&packed, w, h, &mut out.y, &mut out.u, &mut out.v) | ||
| 488 | - } | ||
| 489 | - RgbOrder::Bgra => { | ||
| 490 | - ec_dsp::rgb::bgra_to_i420_709(&packed, w, h, &mut out.y, &mut out.u, &mut out.v) | ||
| 491 | - } | ||
| 492 | - } | ||
| 493 | - Ok(out) | ||
| 494 | -} | ||
| 495 | - | ||
| 496 | -/// The Vulkan encoder for one codec. | ||
| 497 | -enum VkEncoder { | ||
| 498 | - H264(ec_vk::H264Encoder), | ||
| 499 | - H265(ec_vk::H265Encoder), | ||
| 500 | - Av1(ec_vk::Av1Encoder), | ||
| 501 | -} | ||
| 502 | - | ||
| 503 | -const ID_HISTORY: usize = 512; | ||
| 504 | - | ||
| 505 | -impl VkEncoder { | ||
| 506 | - fn submit( | ||
| 507 | - &mut self, | ||
| 508 | - input: EncodeInput, | ||
| 509 | - force_keyframe: bool, | ||
| 510 | - ) -> std::result::Result<Option<ec_vk::CodedFrame>, ec_vk::Error> { | ||
| 511 | - match input { | ||
| 512 | - EncodeInput::I420(frame) => { | ||
| 513 | - let (y, u, v) = (&frame.y, &frame.u, &frame.v); | ||
| 514 | - match self { | ||
| 515 | - VkEncoder::H264(e) => e.submit(y, u, v, force_keyframe), | ||
| 516 | - VkEncoder::H265(e) => e.submit(y, u, v, force_keyframe), | ||
| 517 | - VkEncoder::Av1(e) => e.submit(y, u, v, force_keyframe), | ||
| 518 | - } | ||
| 519 | - } | ||
| 520 | - EncodeInput::I420_16(frame) => { | ||
| 521 | - let (y, u, v) = (&frame.y, &frame.u, &frame.v); | ||
| 522 | - match self { | ||
| 523 | - VkEncoder::H264(_) => Err(ec_vk::Error::Unsupported("10-bit H.264 encode".into())), | ||
| 524 | - VkEncoder::H265(e) => e.submit_16(y, u, v, force_keyframe), | ||
| 525 | - VkEncoder::Av1(e) => e.submit_16(y, u, v, force_keyframe), | ||
| 526 | - } | ||
| 527 | - } | ||
| 528 | - EncodeInput::Rgb(frame) => { | ||
| 529 | - let bgr = frame.order == RgbOrder::Bgra; | ||
| 530 | - let (data, sw, sh, stride) = (frame.data, frame.width, frame.height, frame.stride); | ||
| 531 | - match self { | ||
| 532 | - VkEncoder::H264(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), | ||
| 533 | - VkEncoder::H265(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), | ||
| 534 | - VkEncoder::Av1(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), | ||
| 535 | - } | ||
| 536 | - } | ||
| 537 | - #[cfg(target_os = "linux")] | ||
| 538 | - EncodeInput::DmaBuf(frame) => { | ||
| 539 | - let planes = [DmaBufPlane { | ||
| 540 | - fd: 0, | ||
| 541 | - offset: frame.offset, | ||
| 542 | - pitch: frame.stride, | ||
| 543 | - }]; | ||
| 544 | - let src = DmaBuf { | ||
| 545 | - fds: std::slice::from_ref(&frame.fd), | ||
| 546 | - planes: &planes, | ||
| 547 | - width: frame.width, | ||
| 548 | - height: frame.height, | ||
| 549 | - modifier: frame.modifier, | ||
| 550 | - format: if frame.order == RgbOrder::Bgra { | ||
| 551 | - DmaBufFormat::Bgrx | ||
| 552 | - } else { | ||
| 553 | - DmaBufFormat::Rgbx | ||
| 554 | - }, | ||
| 555 | - }; | ||
| 556 | - self.submit_dma(&src, force_keyframe) | ||
| 557 | - } | ||
| 558 | - #[cfg(target_os = "linux")] | ||
| 559 | - EncodeInput::DmaBufYuv(frame) => { | ||
| 560 | - let src = DmaBuf { | ||
| 561 | - fds: frame.fds, | ||
| 562 | - planes: &frame.planes, | ||
| 563 | - width: frame.width, | ||
| 564 | - height: frame.height, | ||
| 565 | - modifier: frame.modifier, | ||
| 566 | - format: frame.format, | ||
| 567 | - }; | ||
| 568 | - self.submit_dma(&src, force_keyframe) | ||
| 569 | - } | ||
| 570 | - #[cfg(windows)] | ||
| 571 | - EncodeInput::D3d11(frame) => { | ||
| 572 | - let src = frame.texture(); | ||
| 573 | - match self { | ||
| 574 | - VkEncoder::H264(e) => e.submit_d3d11(&src, force_keyframe), | ||
| 575 | - VkEncoder::H265(e) => e.submit_d3d11(&src, force_keyframe), | ||
| 576 | - VkEncoder::Av1(e) => e.submit_d3d11(&src, force_keyframe), | ||
| 577 | - } | ||
| 578 | - } | ||
| 579 | - } | ||
| 580 | - } | ||
| 581 | - | ||
| 582 | - #[cfg(target_os = "linux")] | ||
| 583 | - fn submit_dma( | ||
| 584 | - &mut self, | ||
| 585 | - src: &DmaBuf, | ||
| 586 | - force_keyframe: bool, | ||
| 587 | - ) -> std::result::Result<Option<ec_vk::CodedFrame>, ec_vk::Error> { | ||
| 588 | - match self { | ||
| 589 | - VkEncoder::H264(e) => e.submit_dmabuf(src, force_keyframe), | ||
| 590 | - VkEncoder::H265(e) => e.submit_dmabuf(src, force_keyframe), | ||
| 591 | - VkEncoder::Av1(e) => e.submit_dmabuf(src, force_keyframe), | ||
| 592 | - } | ||
| 593 | - } | ||
| 594 | - | ||
| 595 | - fn flush(&mut self) -> std::result::Result<Vec<ec_vk::CodedFrame>, ec_vk::Error> { | ||
| 596 | - match self { | ||
| 597 | - VkEncoder::H264(e) => e.flush(), | ||
| 598 | - VkEncoder::H265(e) => e.flush(), | ||
| 599 | - VkEncoder::Av1(e) => e.flush(), | ||
| 600 | - } | ||
| 601 | - } | ||
| 602 | - | ||
| 603 | - fn encode( | ||
| 604 | - &mut self, | ||
| 605 | - frame: &I420, | ||
| 606 | - force_keyframe: bool, | ||
| 607 | - ) -> std::result::Result<ec_vk::CodedFrame, ec_vk::Error> { | ||
| 608 | - let (y, u, v) = (&frame.y, &frame.u, &frame.v); | ||
| 609 | - match self { | ||
| 610 | - VkEncoder::H264(e) => e.encode(y, u, v, force_keyframe), | ||
| 611 | - VkEncoder::H265(e) => e.encode(y, u, v, force_keyframe), | ||
| 612 | - VkEncoder::Av1(e) => e.encode(y, u, v, force_keyframe), | ||
| 613 | - } | ||
| 614 | - } | ||
| 615 | - | ||
| 616 | - fn encode_16( | ||
| 617 | - &mut self, | ||
| 618 | - frame: &I420_16, | ||
| 619 | - force_keyframe: bool, | ||
| 620 | - ) -> std::result::Result<ec_vk::CodedFrame, ec_vk::Error> { | ||
| 621 | - let (y, u, v) = (&frame.y, &frame.u, &frame.v); | ||
| 622 | - match self { | ||
| 623 | - VkEncoder::H264(_) => Err(ec_vk::Error::Unsupported("10-bit H.264 encode".into())), | ||
| 624 | - VkEncoder::H265(e) => e.encode_16(y, u, v, force_keyframe), | ||
| 625 | - VkEncoder::Av1(e) => e.encode_16(y, u, v, force_keyframe), | ||
| 626 | - } | ||
| 627 | - } | ||
| 628 | - | ||
| 629 | - fn set_rate( | ||
| 630 | - &mut self, | ||
| 631 | - rate: ec_vk::RateControl, | ||
| 632 | - fps: (u32, u32), | ||
| 633 | - ) -> std::result::Result<(), ec_vk::Error> { | ||
| 634 | - match self { | ||
| 635 | - VkEncoder::H264(e) => e.set_rate(rate, fps), | ||
| 636 | - VkEncoder::H265(e) => e.set_rate(rate, fps), | ||
| 637 | - VkEncoder::Av1(e) => e.set_rate(rate, fps), | ||
| 638 | - } | ||
| 639 | - } | ||
| 640 | - | ||
| 641 | - fn encode_rgb( | ||
| 642 | - &mut self, | ||
| 643 | - frame: &RgbFrame, | ||
| 644 | - force_keyframe: bool, | ||
| 645 | - ) -> std::result::Result<ec_vk::CodedFrame, ec_vk::Error> { | ||
| 646 | - let bgr = frame.order == RgbOrder::Bgra; | ||
| 647 | - let (data, sw, sh, stride) = (frame.data, frame.width, frame.height, frame.stride); | ||
| 648 | - match self { | ||
| 649 | - VkEncoder::H264(e) => e.encode_rgb(data, sw, sh, stride, bgr, force_keyframe), | ||
| 650 | - VkEncoder::H265(e) => e.encode_rgb(data, sw, sh, stride, bgr, force_keyframe), | ||
| 651 | - VkEncoder::Av1(e) => e.encode_rgb(data, sw, sh, stride, bgr, force_keyframe), | ||
| 652 | - } | ||
| 653 | - } | ||
| 654 | - | ||
| 655 | - #[cfg(target_os = "linux")] | ||
| 656 | - fn encode_dmabuf( | ||
| 657 | - &mut self, | ||
| 658 | - src: &DmaBuf, | ||
| 659 | - force_keyframe: bool, | ||
| 660 | - ) -> std::result::Result<ec_vk::CodedFrame, ec_vk::Error> { | ||
| 661 | - match self { | ||
| 662 | - VkEncoder::H264(e) => e.encode_dmabuf(src, force_keyframe), | ||
| 663 | - VkEncoder::H265(e) => e.encode_dmabuf(src, force_keyframe), | ||
| 664 | - VkEncoder::Av1(e) => e.encode_dmabuf(src, force_keyframe), | ||
| 665 | - } | ||
| 666 | - } | ||
| 667 | -} | ||
| 668 | - | ||
| 669 | -enum EncInner { | ||
| 670 | - Vk(VkEncoder), | ||
| 671 | - #[cfg(target_os = "linux")] | ||
| 672 | - Va(VaEncoder), | ||
| 673 | -} | ||
| 674 | - | ||
| 675 | -/// A hardware encoder on whichever backend opened. | ||
| 676 | -pub struct HwEncoder { | ||
| 677 | - inner: EncInner, | ||
| 678 | - born_epoch: u64, | ||
| 679 | - config: EncoderConfig, | ||
| 680 | - #[cfg_attr(not(target_os = "linux"), allow(dead_code))] | ||
| 681 | - size: (usize, usize), | ||
| 682 | - pending: VecDeque<i64>, | ||
| 683 | - ids: VecDeque<(i64, u64)>, | ||
| 684 | - keyframe_next: bool, | ||
| 685 | - tunings: Tunings, | ||
| 686 | - rc: RateFeedback, | ||
| 687 | -} | ||
| 688 | - | ||
| 689 | -impl HwEncoder { | ||
| 690 | - /// Open an encoder. `prefer` = `None` tries Vulkan, then VA-API. | ||
| 691 | - pub fn open(config: EncoderConfig, prefer: Option<Backend>) -> Result<HwEncoder> { | ||
| 692 | - let order = match prefer { | ||
| 693 | - Some(backend) => vec![backend], | ||
| 694 | - None => vec![Backend::Vk, Backend::Va], | ||
| 695 | - }; | ||
| 696 | - let mut reasons = Vec::new(); | ||
| 697 | - for backend in order { | ||
| 698 | - let born_epoch = crate::reset::gpu_reset_epoch(); | ||
| 699 | - match open_backend(backend, config) { | ||
| 700 | - Ok(inner) => { | ||
| 701 | - let size = (config.width as usize, config.height as usize); | ||
| 702 | - return Ok(HwEncoder { | ||
| 703 | - inner, | ||
| 704 | - born_epoch, | ||
| 705 | - config, | ||
| 706 | - size, | ||
| 707 | - pending: VecDeque::new(), | ||
| 708 | - ids: VecDeque::new(), | ||
| 709 | - keyframe_next: false, | ||
| 710 | - tunings: Tunings { | ||
| 711 | - bitrate: config.bitrate, | ||
| 712 | - framerate: config.framerate, | ||
| 713 | - }, | ||
| 714 | - rc: RateFeedback::default(), | ||
| 715 | - }); | ||
| 716 | - } | ||
| 717 | - Err(e) => reasons.push(format!("{backend:?}: {e}")), | ||
| 718 | - } | ||
| 719 | - } | ||
| 720 | - Err(Error::unsupported( | ||
| 721 | - format!("{:?} hardware encode", config.codec), | ||
| 722 | - reasons.join("; "), | ||
| 723 | - )) | ||
| 724 | - } | ||
| 725 | - | ||
| 726 | - /// The backend this encoder runs on. | ||
| 727 | - pub fn backend(&self) -> Backend { | ||
| 728 | - match self.inner { | ||
| 729 | - EncInner::Vk(_) => Backend::Vk, | ||
| 730 | - #[cfg(target_os = "linux")] | ||
| 731 | - EncInner::Va(_) => Backend::Va, | ||
| 732 | - } | ||
| 733 | - } | ||
| 734 | - | ||
| 735 | - /// Change bitrate or frame rate from the next frame; a constant-QP encoder keeps its QP. | ||
| 736 | - pub fn tune(&mut self, tunings: Tunings) -> Result<()> { | ||
| 737 | - match &mut self.inner { | ||
| 738 | - EncInner::Vk(enc) => { | ||
| 739 | - vk_session_alive(self.born_epoch)?; | ||
| 740 | - self.tunings = tunings; | ||
| 741 | - self.rc = RateFeedback::default(); | ||
| 742 | - let rate = vk_rate(&self.config, tunings.bitrate); | ||
| 743 | - enc.set_rate(rate, tunings.framerate)?; | ||
| 744 | - } | ||
| 745 | - #[cfg(target_os = "linux")] | ||
| 746 | - EncInner::Va(enc) => enc.tune(tunings), | ||
| 747 | - } | ||
| 748 | - Ok(()) | ||
| 749 | - } | ||
| 750 | - | ||
| 751 | - /// Submit one picture without waiting; the oldest coded picture comes back once two are in flight. Call [`HwEncoder::flush`] at the end. | ||
| 752 | - pub fn submit(&mut self, input: EncodeInput, meta: FrameMetadata) -> Result<Option<CodedFrame>> { | ||
| 753 | - let meta = self.with_recovery(meta); | ||
| 754 | - match &mut self.inner { | ||
| 755 | - EncInner::Vk(enc) => { | ||
| 756 | - vk_session_alive(self.born_epoch)?; | ||
| 757 | - let coded = enc.submit(input, meta.force_keyframe)?; | ||
| 758 | - self.pending.push_back(meta.timestamp); | ||
| 759 | - let Some(coded) = coded else { | ||
| 760 | - return Ok(None); | ||
| 761 | - }; | ||
| 762 | - let timestamp = self.pending.pop_front().unwrap_or_default(); | ||
| 763 | - self.steer(coded.data.len())?; | ||
| 764 | - Ok(Some(self.vk_frame(coded, timestamp))) | ||
| 765 | - } | ||
| 766 | - #[cfg(target_os = "linux")] | ||
| 767 | - EncInner::Va(enc) => match input { | ||
| 768 | - EncodeInput::I420(frame) => enc.submit(frame, meta), | ||
| 769 | - EncodeInput::I420_16(frame) => enc.submit_16(frame, meta), | ||
| 770 | - EncodeInput::Rgb(frame) => enc.submit(&rgb_to_i420(frame, self.size)?, meta), | ||
| 771 | - EncodeInput::DmaBuf(_) | EncodeInput::DmaBufYuv(_) => Err(Error::unsupported( | ||
| 772 | - "DMA-BUF encode", | ||
| 773 | - "the VA-API backend has no DMA-BUF input here", | ||
| 774 | - )), | ||
| 775 | - }, | ||
| 776 | - } | ||
| 777 | - } | ||
| 778 | - | ||
| 779 | - /// Wait for every submitted picture and return them, oldest first. | ||
| 780 | - pub fn flush(&mut self) -> Result<Vec<CodedFrame>> { | ||
| 781 | - match &mut self.inner { | ||
| 782 | - EncInner::Vk(enc) => { | ||
| 783 | - vk_session_alive(self.born_epoch)?; | ||
| 784 | - let frames = enc.flush()?; | ||
| 785 | - let out: Vec<CodedFrame> = frames | ||
| 786 | - .into_iter() | ||
| 787 | - .map(|coded| { | ||
| 788 | - let timestamp = self.pending.pop_front().unwrap_or_default(); | ||
| 789 | - self.vk_frame(coded, timestamp) | ||
| 790 | - }) | ||
| 791 | - .collect(); | ||
| 792 | - let mut steered = Ok(()); | ||
| 793 | - for frame in &out { | ||
| 794 | - steered = steered.and(self.steer(frame.data.len())); | ||
| 795 | - } | ||
| 796 | - steered?; | ||
| 797 | - Ok(out) | ||
| 798 | - } | ||
| 799 | - #[cfg(target_os = "linux")] | ||
| 800 | - EncInner::Va(enc) => enc.flush(), | ||
| 801 | - } | ||
| 802 | - } | ||
| 803 | - | ||
| 804 | - fn idle(&self) -> Result<()> { | ||
| 805 | - if self.pending.is_empty() { | ||
| 806 | - Ok(()) | ||
| 807 | - } else { | ||
| 808 | - Err(Error::config("pipelined frames pending; call flush first")) | ||
| 809 | - } | ||
| 810 | - } | ||
| 811 | - | ||
| 812 | - /// 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. | ||
| 813 | - pub fn ack(&mut self, timestamp: i64) { | ||
| 814 | - let Some(&(_, id)) = self.ids.iter().rev().find(|(ts, _)| *ts <= timestamp) else { | ||
| 815 | - return; | ||
| 816 | - }; | ||
| 817 | - match &mut self.inner { | ||
| 818 | - EncInner::Vk(VkEncoder::Av1(enc)) => enc.ack(id), | ||
| 819 | - EncInner::Vk(VkEncoder::H265(enc)) => enc.ack(id), | ||
| 820 | - EncInner::Vk(VkEncoder::H264(enc)) => enc.ack(id), | ||
| 821 | - #[cfg(target_os = "linux")] | ||
| 822 | - EncInner::Va(_) => {} | ||
| 823 | - } | ||
| 824 | - } | ||
| 825 | - | ||
| 826 | - /// 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. | ||
| 827 | - pub fn recover(&mut self) { | ||
| 828 | - match &mut self.inner { | ||
| 829 | - EncInner::Vk(VkEncoder::Av1(enc)) => enc.recover(), | ||
| 830 | - EncInner::Vk(VkEncoder::H265(enc)) => enc.recover(), | ||
| 831 | - EncInner::Vk(VkEncoder::H264(enc)) => enc.recover(), | ||
| 832 | - #[cfg(target_os = "linux")] | ||
| 833 | - EncInner::Va(_) => self.keyframe_next = true, | ||
| 834 | - } | ||
| 835 | - } | ||
| 836 | - | ||
| 837 | - fn with_recovery(&mut self, meta: FrameMetadata) -> FrameMetadata { | ||
| 838 | - FrameMetadata { | ||
| 839 | - force_keyframe: meta.force_keyframe || std::mem::take(&mut self.keyframe_next), | ||
| 840 | - ..meta | ||
| 841 | - } | ||
| 842 | - } | ||
| 843 | - | ||
| 844 | - fn vk_frame(&mut self, coded: ec_vk::CodedFrame, timestamp: i64) -> CodedFrame { | ||
| 845 | - if self.ids.len() == ID_HISTORY { | ||
| 846 | - self.ids.pop_front(); | ||
| 847 | - } | ||
| 848 | - self.ids.push_back((timestamp, coded.id)); | ||
| 849 | - CodedFrame { | ||
| 850 | - data: coded.data, | ||
| 851 | - timestamp, | ||
| 852 | - is_keyframe: coded.keyframe, | ||
| 853 | - recovery: coded.recovery, | ||
| 854 | - } | ||
| 855 | - } | ||
| 856 | - | ||
| 857 | - fn steer(&mut self, bytes: usize) -> Result<()> { | ||
| 858 | - if !self.rc.track(bytes, self.config.rate_control, self.tunings) { | ||
| 859 | - return Ok(()); | ||
| 860 | - } | ||
| 861 | - let rate = vk_rate(&self.config, self.rc.steered_bitrate(self.tunings.bitrate)); | ||
| 862 | - match &mut self.inner { | ||
| 863 | - EncInner::Vk(enc) => enc.set_rate(rate, self.tunings.framerate)?, | ||
| 864 | - #[cfg(target_os = "linux")] | ||
| 865 | - EncInner::Va(_) => {} | ||
| 866 | - } | ||
| 867 | - Ok(()) | ||
| 868 | - } | ||
| 869 | - | ||
| 870 | - /// Encode one frame; `meta.force_keyframe` starts a new GOP. | ||
| 871 | - pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> { | ||
| 872 | - let meta = self.with_recovery(meta); | ||
| 873 | - self.idle()?; | ||
| 874 | - match &mut self.inner { | ||
| 875 | - EncInner::Vk(enc) => { | ||
| 876 | - vk_session_alive(self.born_epoch)?; | ||
| 877 | - let coded = enc.encode(frame, meta.force_keyframe)?; | ||
| 878 | - self.steer(coded.data.len())?; | ||
| 879 | - Ok(self.vk_frame(coded, meta.timestamp)) | ||
| 880 | - } | ||
| 881 | - #[cfg(target_os = "linux")] | ||
| 882 | - EncInner::Va(enc) => enc.encode(frame, meta), | ||
| 883 | - } | ||
| 884 | - } | ||
| 885 | - | ||
| 886 | - /// Encode one 10-bit frame of a 10-bit encoder (H.265 and AV1), the [`HwEncoder::encode`] of a 10-bit encoder. | ||
| 887 | - pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result<CodedFrame> { | ||
| 888 | - let meta = self.with_recovery(meta); | ||
| 889 | - self.idle()?; | ||
| 890 | - match &mut self.inner { | ||
| 891 | - EncInner::Vk(enc) => { | ||
| 892 | - vk_session_alive(self.born_epoch)?; | ||
| 893 | - let coded = enc.encode_16(frame, meta.force_keyframe)?; | ||
| 894 | - self.steer(coded.data.len())?; | ||
| 895 | - Ok(self.vk_frame(coded, meta.timestamp)) | ||
| 896 | - } | ||
| 897 | - #[cfg(target_os = "linux")] | ||
| 898 | - EncInner::Va(enc) => enc.encode_16(frame, meta), | ||
| 899 | - } | ||
| 900 | - } | ||
| 901 | - | ||
| 902 | - /// 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. | ||
| 903 | - pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result<CodedFrame> { | ||
| 904 | - let meta = self.with_recovery(meta); | ||
| 905 | - self.idle()?; | ||
| 906 | - match &mut self.inner { | ||
| 907 | - EncInner::Vk(enc) => { | ||
| 908 | - vk_session_alive(self.born_epoch)?; | ||
| 909 | - let coded = enc.encode_rgb(frame, meta.force_keyframe)?; | ||
| 910 | - self.steer(coded.data.len())?; | ||
| 911 | - Ok(self.vk_frame(coded, meta.timestamp)) | ||
| 912 | - } | ||
| 913 | - #[cfg(target_os = "linux")] | ||
| 914 | - EncInner::Va(enc) => enc.encode(&rgb_to_i420(frame, self.size)?, meta), | ||
| 915 | - } | ||
| 916 | - } | ||
| 917 | - | ||
| 918 | - /// Encode one DMA-BUF frame of the source size, box-downscaled to the encoder size. Vulkan only; VA-API has its own PRIME path. | ||
| 919 | - #[cfg(target_os = "linux")] | ||
| 920 | - pub fn encode_dmabuf(&mut self, frame: &DmaBufFrame, meta: FrameMetadata) -> Result<CodedFrame> { | ||
| 921 | - let planes = frame.planes(); | ||
| 922 | - self.encode_dma(&frame.as_dmabuf(&planes), meta) | ||
| 923 | - } | ||
| 924 | - | ||
| 925 | - /// Encode one NV12 or P010 DMA-BUF frame of the encoder size. Vulkan only; VA-API has its own PRIME path. | ||
| 926 | - #[cfg(target_os = "linux")] | ||
| 927 | - pub fn encode_dmabuf_yuv( | ||
| 928 | - &mut self, | ||
| 929 | - frame: &DmaBufYuvFrame, | ||
| 930 | - meta: FrameMetadata, | ||
| 931 | - ) -> Result<CodedFrame> { | ||
| 932 | - let src = DmaBuf { | ||
| 933 | - fds: frame.fds, | ||
| 934 | - planes: &frame.planes, | ||
| 935 | - width: frame.width, | ||
| 936 | - height: frame.height, | ||
| 937 | - modifier: frame.modifier, | ||
| 938 | - format: frame.format, | ||
| 939 | - }; | ||
| 940 | - self.encode_dma(&src, meta) | ||
| 941 | - } | ||
| 942 | - | ||
| 943 | - /// Encode one shared D3D11 texture of the source size, downscaled to the encoder size on the GPU. | ||
| 944 | - #[cfg(windows)] | ||
| 945 | - pub fn encode_d3d11(&mut self, frame: &D3d11Frame, meta: FrameMetadata) -> Result<CodedFrame> { | ||
| 946 | - let meta = self.with_recovery(meta); | ||
| 947 | - self.idle()?; | ||
| 948 | - let EncInner::Vk(enc) = &mut self.inner; | ||
| 949 | - vk_session_alive(self.born_epoch)?; | ||
| 950 | - let src = frame.texture(); | ||
| 951 | - let coded = match enc { | ||
| 952 | - VkEncoder::H264(e) => e.encode_d3d11(&src, meta.force_keyframe), | ||
| 953 | - VkEncoder::H265(e) => e.encode_d3d11(&src, meta.force_keyframe), | ||
| 954 | - VkEncoder::Av1(e) => e.encode_d3d11(&src, meta.force_keyframe), | ||
| 955 | - }?; | ||
| 956 | - self.steer(coded.data.len())?; | ||
| 957 | - Ok(self.vk_frame(coded, meta.timestamp)) | ||
| 958 | - } | ||
| 959 | - | ||
| 960 | - #[cfg(target_os = "linux")] | ||
| 961 | - fn encode_dma(&mut self, src: &DmaBuf, meta: FrameMetadata) -> Result<CodedFrame> { | ||
| 962 | - let meta = self.with_recovery(meta); | ||
| 963 | - self.idle()?; | ||
| 964 | - match &mut self.inner { | ||
| 965 | - EncInner::Vk(enc) => { | ||
| 966 | - vk_session_alive(self.born_epoch)?; | ||
| 967 | - let coded = enc.encode_dmabuf(src, meta.force_keyframe)?; | ||
| 968 | - self.steer(coded.data.len())?; | ||
| 969 | - Ok(self.vk_frame(coded, meta.timestamp)) | ||
| 970 | - } | ||
| 971 | - EncInner::Va(_) => Err(Error::unsupported( | ||
| 972 | - "DMA-BUF encode", | ||
| 973 | - "the VA-API backend has no DMA-BUF input here", | ||
| 974 | - )), | ||
| 975 | - } | ||
| 976 | - } | ||
| 977 | -} | ||
| 978 | - | ||
| 979 | -fn open_backend(backend: Backend, config: EncoderConfig) -> Result<EncInner> { | ||
| 980 | - match backend { | ||
| 981 | - Backend::Vk => open_vk(config).map(EncInner::Vk), | ||
| 982 | - Backend::Va => open_va(config), | ||
| 983 | - } | ||
| 984 | -} | ||
| 985 | - | ||
| 986 | -fn open_vk(config: EncoderConfig) -> Result<VkEncoder> { | ||
| 987 | - vk_grace()?; | ||
| 988 | - if config.bit_depth == 10 && config.codec == EncCodec::H264 { | ||
| 989 | - return Err(Error::unsupported( | ||
| 990 | - "10-bit H.264 Vulkan Video encode", | ||
| 991 | - "the driver offers no High 10 H.264 encode", | ||
| 992 | - )); | ||
| 993 | - } | ||
| 994 | - if config.bit_depth != 8 && config.bit_depth != 10 { | ||
| 995 | - return Err(Error::config(format!( | ||
| 996 | - "encoder bit depth {}: Vulkan encodes 8-bit, or 10-bit H.265 and AV1", | ||
| 997 | - config.bit_depth | ||
| 998 | - ))); | ||
| 999 | - } | ||
| 1000 | - let gpu = vk_gpu() | ||
| 1001 | - .ok_or_else(|| Error::unsupported("Vulkan Video encode", "no Vulkan Video device"))?; | ||
| 1002 | - let rate = vk_rate(&config, config.bitrate); | ||
| 1003 | - let level = match config.codec { | ||
| 1004 | - EncCodec::H264 => crate::level::h264(&config), | ||
| 1005 | - EncCodec::H265 => crate::level::hevc(&config), | ||
| 1006 | - EncCodec::Av1 => crate::level::av1(&config), | ||
| 1007 | - }; | ||
| 1008 | - let (width, height, fps, gop_size) = ( | ||
| 1009 | - config.width, | ||
| 1010 | - config.height, | ||
| 1011 | - config.framerate, | ||
| 1012 | - config.gop_size, | ||
| 1013 | - ); | ||
| 1014 | - let colour = config.colour.map(|c| ec_vk::Colour { | ||
| 1015 | - primaries: c.primaries, | ||
| 1016 | - transfer: c.transfer, | ||
| 1017 | - matrix: c.matrix, | ||
| 1018 | - full_range: c.full_range, | ||
| 1019 | - }); | ||
| 1020 | - Ok(match config.codec { | ||
| 1021 | - EncCodec::H264 => VkEncoder::H264(ec_vk::H264Encoder::new( | ||
| 1022 | - &gpu, | ||
| 1023 | - ec_vk::H264EncoderConfig { | ||
| 1024 | - width, | ||
| 1025 | - height, | ||
| 1026 | - fps, | ||
| 1027 | - gop_size, | ||
| 1028 | - rate, | ||
| 1029 | - profile: vk_h264_profile(config.h264_profile), | ||
| 1030 | - level, | ||
| 1031 | - colour, | ||
| 1032 | - quality: config.quality, | ||
| 1033 | - }, | ||
| 1034 | - )?), | ||
| 1035 | - EncCodec::H265 => VkEncoder::H265(ec_vk::H265Encoder::new( | ||
| 1036 | - &gpu, | ||
| 1037 | - ec_vk::H265EncoderConfig { | ||
| 1038 | - width, | ||
| 1039 | - height, | ||
| 1040 | - fps, | ||
| 1041 | - gop_size, | ||
| 1042 | - rate, | ||
| 1043 | - bit_depth: config.bit_depth, | ||
| 1044 | - level, | ||
| 1045 | - colour, | ||
| 1046 | - quality: config.quality, | ||
| 1047 | - }, | ||
| 1048 | - )?), | ||
| 1049 | - EncCodec::Av1 => VkEncoder::Av1(ec_vk::Av1Encoder::new( | ||
| 1050 | - &gpu, | ||
| 1051 | - ec_vk::Av1EncoderConfig { | ||
| 1052 | - width, | ||
| 1053 | - height, | ||
| 1054 | - fps, | ||
| 1055 | - gop_size, | ||
| 1056 | - rate, | ||
| 1057 | - bit_depth: config.bit_depth, | ||
| 1058 | - level, | ||
| 1059 | - colour, | ||
| 1060 | - quality: config.quality, | ||
| 1061 | - }, | ||
| 1062 | - )?), | ||
| 1063 | - }) | ||
| 1064 | -} | ||
| 1065 | - | ||
| 1066 | -fn vk_h264_profile(profile: H264Profile) -> ec_vk::H264Profile { | ||
| 1067 | - match profile { | ||
| 1068 | - H264Profile::ConstrainedBaseline => ec_vk::H264Profile::ConstrainedBaseline, | ||
| 1069 | - H264Profile::Main => ec_vk::H264Profile::Main, | ||
| 1070 | - H264Profile::High => ec_vk::H264Profile::High, | ||
| 1071 | - } | ||
| 1072 | -} | ||
| 1073 | - | ||
| 1074 | -fn vk_rate(config: &EncoderConfig, bitrate: u32) -> ec_vk::RateControl { | ||
| 1075 | - match (config.rate_control, config.codec) { | ||
| 1076 | - (RateControlMode::ConstantQp { qp }, EncCodec::Av1) => ec_vk::RateControl::ConstantQp { | ||
| 1077 | - qp: (qp / 5).min(51) as u8, | ||
| 1078 | - }, | ||
| 1079 | - (RateControlMode::ConstantQp { qp }, _) => ec_vk::RateControl::ConstantQp { | ||
| 1080 | - qp: qp.min(51) as u8, | ||
| 1081 | - }, | ||
| 1082 | - (RateControlMode::ConstantBitrate, _) => ec_vk::RateControl::Cbr { | ||
| 1083 | - bitrate, | ||
| 1084 | - buffer_ms: hrd_buffer_ms(config), | ||
| 1085 | - }, | ||
| 1086 | - (RateControlMode::VariableBitrate, _) => ec_vk::RateControl::Vbr { | ||
| 1087 | - bitrate, | ||
| 1088 | - max_bitrate: bitrate.saturating_mul(3) / 2, | ||
| 1089 | - buffer_ms: hrd_buffer_ms(config), | ||
| 1090 | - min_qp: None, | ||
| 1091 | - }, | ||
| 1092 | - (RateControlMode::Qvbr { quality }, _) => ec_vk::RateControl::Vbr { | ||
| 1093 | - bitrate, | ||
| 1094 | - max_bitrate: bitrate, | ||
| 1095 | - buffer_ms: hrd_buffer_ms(config), | ||
| 1096 | - min_qp: Some(quality.min(51) as u8), | ||
| 1097 | - }, | ||
| 1098 | - } | ||
| 1099 | -} | ||
| 1100 | - | ||
| 1101 | -#[cfg(target_os = "linux")] | ||
| 1102 | -fn open_va(config: EncoderConfig) -> Result<EncInner> { | ||
| 1103 | - let display = ec_va::open()?; | ||
| 1104 | - Ok(EncInner::Va(VaEncoder::new(&display, config)?)) | ||
| 1105 | -} | ||
| 1106 | - | ||
| 1107 | -#[cfg(not(target_os = "linux"))] | ||
| 1108 | -fn open_va(config: EncoderConfig) -> Result<EncInner> { | ||
| 1109 | - Err(Error::unsupported( | ||
| 1110 | - format!("{:?} VA-API encode", config.codec), | ||
| 1111 | - "VA-API is Linux only", | ||
| 1112 | - )) | ||
| 1113 | -} | ||
| 1114 | - | ||
| 1115 | -enum VkDecoder { | ||
| 1116 | - H264(VkH264Decoder), | ||
| 1117 | - H265(VkH265Decoder), | ||
| 1118 | - Av1(VkAv1Decoder), | ||
| 1119 | - Vp9(VkVp9Decoder), | ||
| 1120 | -} | ||
| 1121 | - | ||
| 1122 | -impl VkDecoder { | ||
| 1123 | - fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { | ||
| 1124 | - match self { | ||
| 1125 | - VkDecoder::H264(d) => d.decode(data, timestamp), | ||
| 1126 | - VkDecoder::H265(d) => d.decode(data, timestamp), | ||
| 1127 | - VkDecoder::Av1(d) => d.decode(data, timestamp), | ||
| 1128 | - VkDecoder::Vp9(d) => d.decode(data, timestamp), | ||
| 1129 | - } | ||
| 1130 | - } | ||
| 1131 | - | ||
| 1132 | - fn next_frame(&mut self) -> Option<HwPicture> { | ||
| 1133 | - match self { | ||
| 1134 | - VkDecoder::H264(d) => d.next_frame(), | ||
| 1135 | - VkDecoder::H265(d) => d.next_frame(), | ||
| 1136 | - VkDecoder::Av1(d) => d.next_frame(), | ||
| 1137 | - VkDecoder::Vp9(d) => d.next_frame(), | ||
| 1138 | - } | ||
| 1139 | - } | ||
| 1140 | - | ||
| 1141 | - fn flush(&mut self) -> Result<()> { | ||
| 1142 | - match self { | ||
| 1143 | - VkDecoder::H264(d) => d.flush(), | ||
| 1144 | - VkDecoder::H265(d) => d.flush(), | ||
| 1145 | - VkDecoder::Av1(d) => d.flush(), | ||
| 1146 | - VkDecoder::Vp9(d) => d.flush(), | ||
| 1147 | - } | ||
| 1148 | - } | ||
| 1149 | - | ||
| 1150 | - fn reset(&mut self) { | ||
| 1151 | - match self { | ||
| 1152 | - VkDecoder::H264(d) => d.reset(), | ||
| 1153 | - VkDecoder::H265(d) => d.reset(), | ||
| 1154 | - VkDecoder::Av1(d) => d.reset(), | ||
| 1155 | - VkDecoder::Vp9(d) => d.reset(), | ||
| 1156 | - } | ||
| 1157 | - } | ||
| 1158 | -} | ||
| 1159 | - | ||
| 1160 | -enum DecInner { | ||
| 1161 | - Vk(VkDecoder), | ||
| 1162 | - #[cfg(target_os = "linux")] | ||
| 1163 | - Va(VaDecoder), | ||
| 1164 | -} | ||
| 1165 | - | ||
| 1166 | -const REPLAY_LIMIT: usize = 64; | ||
| 1167 | - | ||
| 1168 | -/// What a decoder hands out: 8-bit I420, or packed RGB converted on the way out. | ||
| 1169 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 1170 | -pub struct RgbOutput { | ||
| 1171 | - /// Byte order of each output pixel. | ||
| 1172 | - pub order: RgbOrder, | ||
| 1173 | - /// Scale pictures wider than this down to it, keeping the aspect ratio. | ||
| 1174 | - pub max_width: Option<u32>, | ||
| 1175 | - /// Scale pictures taller than this down to it, keeping the aspect ratio. | ||
| 1176 | - pub max_height: Option<u32>, | ||
| 1177 | -} | ||
| 1178 | - | ||
| 1179 | -impl RgbOutput { | ||
| 1180 | - pub(crate) fn bound(&self) -> (Option<u32>, Option<u32>) { | ||
| 1181 | - (self.max_width, self.max_height) | ||
| 1182 | - } | ||
| 1183 | -} | ||
| 1184 | - | ||
| 1185 | -/// A hardware decoder on whichever backend opened. | ||
| 1186 | -pub struct HwDecoder { | ||
| 1187 | - inner: DecInner, | ||
| 1188 | - born_epoch: u64, | ||
| 1189 | - #[cfg_attr(not(target_os = "linux"), allow(dead_code))] | ||
| 1190 | - codec: Codec, | ||
| 1191 | - rgb: Option<RgbOutput>, | ||
| 1192 | - #[cfg_attr(not(target_os = "linux"), allow(dead_code))] | ||
| 1193 | - replay: Option<Vec<(Vec<u8>, i64)>>, | ||
| 1194 | -} | ||
| 1195 | - | ||
| 1196 | -impl HwDecoder { | ||
| 1197 | - /// Open a decoder for `codec`. Every codec tries Vulkan Video first, then VA-API (Linux). | ||
| 1198 | - pub fn open(codec: Codec) -> Result<HwDecoder> { | ||
| 1199 | - HwDecoder::open_with(codec, None) | ||
| 1200 | - } | ||
| 1201 | - | ||
| 1202 | - /// 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. | ||
| 1203 | - pub fn open_rgb(codec: Codec, output: RgbOutput) -> Result<HwDecoder> { | ||
| 1204 | - HwDecoder::open_with(codec, Some(output)) | ||
| 1205 | - } | ||
| 1206 | - | ||
| 1207 | - fn open_with(codec: Codec, rgb: Option<RgbOutput>) -> Result<HwDecoder> { | ||
| 1208 | - let mut reasons = Vec::new(); | ||
| 1209 | - let born_epoch = crate::reset::gpu_reset_epoch(); | ||
| 1210 | - let vk = vk_grace().and_then(|()| match codec { | ||
| 1211 | - Codec::H264 => VkH264Decoder::new().map(VkDecoder::H264), | ||
| 1212 | - Codec::H265 => VkH265Decoder::new().map(VkDecoder::H265), | ||
| 1213 | - Codec::Av1 => VkAv1Decoder::new().map(VkDecoder::Av1), | ||
| 1214 | - Codec::Vp9 => VkVp9Decoder::new().map(VkDecoder::Vp9), | ||
| 1215 | - }); | ||
| 1216 | - match vk { | ||
| 1217 | - Ok(inner) => { | ||
| 1218 | - return Ok(HwDecoder { | ||
| 1219 | - inner: DecInner::Vk(inner), | ||
| 1220 | - born_epoch, | ||
| 1221 | - codec, | ||
| 1222 | - rgb, | ||
| 1223 | - replay: Some(Vec::new()), | ||
| 1224 | - }); | ||
| 1225 | - } | ||
| 1226 | - Err(e) => reasons.push(format!("Vk: {e}")), | ||
| 1227 | - } | ||
| 1228 | - #[cfg(target_os = "linux")] | ||
| 1229 | - { | ||
| 1230 | - match open_va_decoder(codec) { | ||
| 1231 | - Ok(inner) => { | ||
| 1232 | - return Ok(HwDecoder { | ||
| 1233 | - inner: DecInner::Va(inner), | ||
| 1234 | - born_epoch, | ||
| 1235 | - codec, | ||
| 1236 | - rgb, | ||
| 1237 | - replay: None, | ||
| 1238 | - }); | ||
| 1239 | - } | ||
| 1240 | - Err(e) => reasons.push(format!("Va: {e}")), | ||
| 1241 | - } | ||
| 1242 | - } | ||
| 1243 | - Err(Error::unsupported( | ||
| 1244 | - format!("{codec:?} hardware decode"), | ||
| 1245 | - reasons.join("; "), | ||
| 1246 | - )) | ||
| 1247 | - } | ||
| 1248 | - | ||
| 1249 | - /// The backend this decoder runs on. | ||
| 1250 | - pub fn backend(&self) -> Backend { | ||
| 1251 | - match self.inner { | ||
| 1252 | - DecInner::Vk(_) => Backend::Vk, | ||
| 1253 | - #[cfg(target_os = "linux")] | ||
| 1254 | - DecInner::Va(_) => Backend::Va, | ||
| 1255 | - } | ||
| 1256 | - } | ||
| 1257 | - | ||
| 1258 | - /// Feed one access unit. A stream Vulkan refuses (an unsupported profile) before its first | ||
| 1259 | - /// picture comes out moves to VA-API on Linux, replaying what was fed so far. | ||
| 1260 | - pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { | ||
| 1261 | - let born_epoch = self.born_epoch; | ||
| 1262 | - let result = match &mut self.inner { | ||
| 1263 | - DecInner::Vk(d) => vk_session_alive(born_epoch).and_then(|()| d.decode(data, timestamp)), | ||
| 1264 | - #[cfg(target_os = "linux")] | ||
| 1265 | - DecInner::Va(d) => d.decode(data, timestamp), | ||
| 1266 | - }; | ||
| 1267 | - if let Some(fed) = self.replay.as_mut() { | ||
| 1268 | - fed.push((data.to_vec(), timestamp)); | ||
| 1269 | - if fed.len() > REPLAY_LIMIT { | ||
| 1270 | - self.replay = None; | ||
| 1271 | - } | ||
| 1272 | - } | ||
| 1273 | - #[cfg(target_os = "linux")] | ||
| 1274 | - if let Err(Error::Unsupported { .. }) = result | ||
| 1275 | - && let Some(fed) = &self.replay | ||
| 1276 | - && let Ok(mut va) = open_va_decoder(self.codec) | ||
| 1277 | - && fed.iter().all(|(chunk, ts)| va.decode(chunk, *ts).is_ok()) | ||
| 1278 | - { | ||
| 1279 | - self.replay = None; | ||
| 1280 | - self.inner = DecInner::Va(va); | ||
| 1281 | - return Ok(()); | ||
| 1282 | - } | ||
| 1283 | - result | ||
| 1284 | - } | ||
| 1285 | - | ||
| 1286 | - /// The next picture in display order, held in its decode slot until dropped. Convert it with the `to_*` methods of [`HwPicture`]. | ||
| 1287 | - pub fn next_picture(&mut self) -> Result<Option<HwPicture>> { | ||
| 1288 | - self.pull() | ||
| 1289 | - } | ||
| 1290 | - | ||
| 1291 | - /// The next picture in display order, as 8-bit I420 with its timestamp. | ||
| 1292 | - pub fn next_frame(&mut self) -> Result<Option<(i64, I420)>> { | ||
| 1293 | - match self.pull()? { | ||
| 1294 | - None => Ok(None), | ||
| 1295 | - Some(picture) => Ok(Some((picture.timestamp, picture.to_i420()?))), | ||
| 1296 | - } | ||
| 1297 | - } | ||
| 1298 | - | ||
| 1299 | - /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder not opened with [`HwDecoder::open_rgb`]. | ||
| 1300 | - pub fn next_rgb(&mut self) -> Result<Option<(i64, RgbPicture)>> { | ||
| 1301 | - let mut dst = RgbPicture::default(); | ||
| 1302 | - Ok(self.next_rgb_into(&mut dst)?.map(|ts| (ts, dst))) | ||
| 1303 | - } | ||
| 1304 | - | ||
| 1305 | - /// Changes the RGB output of a decoder opened with [`HwDecoder::open_rgb`] from the next picture on. | ||
| 1306 | - pub fn set_rgb_output(&mut self, output: RgbOutput) -> Result<()> { | ||
| 1307 | - let rgb = self | ||
| 1308 | - .rgb | ||
| 1309 | - .as_mut() | ||
| 1310 | - .ok_or_else(|| Error::config("set_rgb_output on a decoder not opened with open_rgb"))?; | ||
| 1311 | - *rgb = output; | ||
| 1312 | - Ok(()) | ||
| 1313 | - } | ||
| 1314 | - | ||
| 1315 | - /// [`HwDecoder::next_rgb`] into `dst`, reusing its allocation across pictures; returns the timestamp. | ||
| 1316 | - pub fn next_rgb_into(&mut self, dst: &mut RgbPicture) -> Result<Option<i64>> { | ||
| 1317 | - let output = self | ||
| 1318 | - .rgb | ||
| 1319 | - .ok_or_else(|| Error::config("next_rgb on a decoder not opened with open_rgb"))?; | ||
| 1320 | - match self.pull()? { | ||
| 1321 | - None => Ok(None), | ||
| 1322 | - Some(picture) => { | ||
| 1323 | - picture.rgb_into(&output, dst)?; | ||
| 1324 | - Ok(Some(picture.timestamp)) | ||
| 1325 | - } | ||
| 1326 | - } | ||
| 1327 | - } | ||
| 1328 | - | ||
| 1329 | - fn pull(&mut self) -> Result<Option<HwPicture>> { | ||
| 1330 | - match &mut self.inner { | ||
| 1331 | - DecInner::Vk(d) => { | ||
| 1332 | - vk_session_alive(self.born_epoch)?; | ||
| 1333 | - let picture = d.next_frame(); | ||
| 1334 | - if picture.is_some() { | ||
| 1335 | - self.replay = None; | ||
| 1336 | - } | ||
| 1337 | - Ok(picture) | ||
| 1338 | - } | ||
| 1339 | - #[cfg(target_os = "linux")] | ||
| 1340 | - DecInner::Va(d) => Ok(d.next_frame().map(HwPicture::va)), | ||
| 1341 | - } | ||
| 1342 | - } | ||
| 1343 | - | ||
| 1344 | - /// 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. | ||
| 1345 | - pub fn reset(&mut self) { | ||
| 1346 | - match &mut self.inner { | ||
| 1347 | - DecInner::Vk(d) => d.reset(), | ||
| 1348 | - #[cfg(target_os = "linux")] | ||
| 1349 | - DecInner::Va(d) => d.reset(), | ||
| 1350 | - } | ||
| 1351 | - self.replay = None; | ||
| 1352 | - } | ||
| 1353 | - | ||
| 1354 | - /// Emit every picture still held for reordering. | ||
| 1355 | - pub fn flush(&mut self) -> Result<()> { | ||
| 1356 | - match &mut self.inner { | ||
| 1357 | - DecInner::Vk(d) => d.flush(), | ||
| 1358 | - #[cfg(target_os = "linux")] | ||
| 1359 | - DecInner::Va(d) => d.flush(), | ||
| 1360 | - } | ||
| 1361 | - } | ||
| 1362 | -} | ||
| 1363 | - | ||
| 1364 | -#[cfg(target_os = "linux")] | ||
| 1365 | -fn open_va_decoder(codec: Codec) -> Result<VaDecoder> { | ||
| 1366 | - let display = ec_va::open()?; | ||
| 1367 | - VaDecoder::new(&display, codec) | ||
| 1368 | -} | ||
crates/ec-hw/src/hw/caps.rsadded+231 -0
| @@ -0,0 +1,231 @@ | |||
| 1 | +use super::*; | ||
| 2 | + | ||
| 3 | +/// Where a codec runs. | ||
| 4 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 5 | +pub enum Backend { | ||
| 6 | + /// Vulkan Video, every OS. | ||
| 7 | + Vk, | ||
| 8 | + /// VA-API, Linux only. | ||
| 9 | + Va, | ||
| 10 | +} | ||
| 11 | + | ||
| 12 | +/// Which way a codec runs. | ||
| 13 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 14 | +pub enum Direction { | ||
| 15 | + /// Encode. | ||
| 16 | + Encode, | ||
| 17 | + /// Decode. | ||
| 18 | + Decode, | ||
| 19 | +} | ||
| 20 | + | ||
| 21 | +/// Profile of a [`Capability`], 4:2:0 only. | ||
| 22 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 23 | +pub enum CodecProfile { | ||
| 24 | + /// H.264 Constrained Baseline, 8-bit. | ||
| 25 | + H264ConstrainedBaseline, | ||
| 26 | + /// H.264 Main, 8-bit. | ||
| 27 | + H264Main, | ||
| 28 | + /// H.264 High, 8-bit. | ||
| 29 | + H264High, | ||
| 30 | + /// H.265 Main, 8-bit. | ||
| 31 | + H265Main, | ||
| 32 | + /// H.265 Main 10, 10-bit. | ||
| 33 | + H265Main10, | ||
| 34 | + /// AV1 Main, 8-bit. | ||
| 35 | + Av1Main, | ||
| 36 | + /// AV1 Main, 10-bit. | ||
| 37 | + Av1Main10, | ||
| 38 | + /// VP9 Profile 0, 8-bit. | ||
| 39 | + Vp9Profile0, | ||
| 40 | + /// VP9 Profile 2, 10-bit. | ||
| 41 | + Vp9Profile2, | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +/// One codec, profile, direction and backend this machine offers. | ||
| 45 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 46 | +pub struct Capability { | ||
| 47 | + /// Codec. | ||
| 48 | + pub codec: Codec, | ||
| 49 | + /// Profile. | ||
| 50 | + pub profile: CodecProfile, | ||
| 51 | + /// Direction. | ||
| 52 | + pub direction: Direction, | ||
| 53 | + /// Largest width in luma samples. | ||
| 54 | + pub max_width: u32, | ||
| 55 | + /// Largest height in luma samples. | ||
| 56 | + pub max_height: u32, | ||
| 57 | + /// Backend offering it. | ||
| 58 | + pub backend: Backend, | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +thread_local! { | ||
| 62 | + static GPU: RefCell<Option<(u64, Option<ec_vk::Gpu>)>> = const { RefCell::new(None) }; | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +pub(crate) fn vk_gpu() -> Option<ec_vk::Gpu> { | ||
| 66 | + GPU.with_borrow_mut(|cached| { | ||
| 67 | + let epoch = crate::reset::gpu_reset_epoch(); | ||
| 68 | + match cached { | ||
| 69 | + Some((born, gpu)) if *born == epoch => gpu.clone(), | ||
| 70 | + _ => { | ||
| 71 | + let gpu = ec_vk::Gpu::open().ok(); | ||
| 72 | + *cached = Some((epoch, gpu.clone())); | ||
| 73 | + gpu | ||
| 74 | + } | ||
| 75 | + } | ||
| 76 | + }) | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +pub(super) fn vk_session_alive(born_epoch: u64) -> Result<()> { | ||
| 80 | + if crate::reset::gpu_reset_epoch() == born_epoch { | ||
| 81 | + Ok(()) | ||
| 82 | + } else { | ||
| 83 | + Err(Error::hw_reset( | ||
| 84 | + "the GPU was reset after this Vulkan session was created; its device is lost", | ||
| 85 | + )) | ||
| 86 | + } | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +pub(super) fn vk_grace() -> Result<()> { | ||
| 90 | + if crate::reset::gpu_recently_reset() { | ||
| 91 | + Err(Error::hw_reset( | ||
| 92 | + "the GPU was reset moments ago; new Vulkan sessions wait out the grace period", | ||
| 93 | + )) | ||
| 94 | + } else { | ||
| 95 | + Ok(()) | ||
| 96 | + } | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +/// Every codec, direction and backend this machine can use. Never fails. | ||
| 100 | +pub fn capabilities() -> Vec<Capability> { | ||
| 101 | + let mut out = Vec::new(); | ||
| 102 | + if let Some(gpu) = vk_gpu() { | ||
| 103 | + for caps in gpu.caps() { | ||
| 104 | + let codec = match caps.codec { | ||
| 105 | + ec_vk::Codec::H264 => Codec::H264, | ||
| 106 | + ec_vk::Codec::H265 => Codec::H265, | ||
| 107 | + ec_vk::Codec::Av1 => Codec::Av1, | ||
| 108 | + ec_vk::Codec::Vp9 => Codec::Vp9, | ||
| 109 | + }; | ||
| 110 | + let direction = match caps.direction { | ||
| 111 | + ec_vk::Direction::Encode => Direction::Encode, | ||
| 112 | + ec_vk::Direction::Decode => Direction::Decode, | ||
| 113 | + }; | ||
| 114 | + push( | ||
| 115 | + &mut out, | ||
| 116 | + Capability { | ||
| 117 | + codec, | ||
| 118 | + profile: vk_profile(caps.profile), | ||
| 119 | + direction, | ||
| 120 | + max_width: caps.max_width, | ||
| 121 | + max_height: caps.max_height, | ||
| 122 | + backend: Backend::Vk, | ||
| 123 | + }, | ||
| 124 | + ); | ||
| 125 | + } | ||
| 126 | + } | ||
| 127 | + #[cfg(target_os = "linux")] | ||
| 128 | + va_capabilities(&mut out); | ||
| 129 | + out | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +fn push(out: &mut Vec<Capability>, cap: Capability) { | ||
| 133 | + let known = out | ||
| 134 | + .iter() | ||
| 135 | + .any(|c| { | ||
| 136 | + c.codec == cap.codec | ||
| 137 | + && c.profile == cap.profile | ||
| 138 | + && c.direction == cap.direction | ||
| 139 | + && c.backend == cap.backend | ||
| 140 | + }); | ||
| 141 | + if !known { | ||
| 142 | + out.push(cap); | ||
| 143 | + } | ||
| 144 | +} | ||
| 145 | + | ||
| 146 | +#[cfg(target_os = "linux")] | ||
| 147 | +fn va_capabilities(out: &mut Vec<Capability>) { | ||
| 148 | + let Ok(display) = ec_va::open() else { | ||
| 149 | + return; | ||
| 150 | + }; | ||
| 151 | + let Ok(report) = ec_va::CapReport::probe(&display) else { | ||
| 152 | + return; | ||
| 153 | + }; | ||
| 154 | + for entry in &report.entries { | ||
| 155 | + let direction = match entry.entrypoint { | ||
| 156 | + ec_va::Entrypoint::VLD => Direction::Decode, | ||
| 157 | + ec_va::Entrypoint::EncSlice | ec_va::Entrypoint::EncSliceLP => Direction::Encode, | ||
| 158 | + _ => continue, | ||
| 159 | + }; | ||
| 160 | + let (max_width, max_height) = match &entry.surfaces { | ||
| 161 | + Some(s) => (s.max_width.unwrap_or(4096), s.max_height.unwrap_or(4096)), | ||
| 162 | + None => (4096, 4096), | ||
| 163 | + }; | ||
| 164 | + for profile in va_profiles(entry.profile, entry.rt_formats) { | ||
| 165 | + push( | ||
| 166 | + out, | ||
| 167 | + Capability { | ||
| 168 | + codec: profile.codec(), | ||
| 169 | + profile, | ||
| 170 | + direction, | ||
| 171 | + max_width, | ||
| 172 | + max_height, | ||
| 173 | + backend: Backend::Va, | ||
| 174 | + }, | ||
| 175 | + ); | ||
| 176 | + } | ||
| 177 | + } | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +#[cfg(target_os = "linux")] | ||
| 181 | +impl CodecProfile { | ||
| 182 | + fn codec(self) -> Codec { | ||
| 183 | + match self { | ||
| 184 | + CodecProfile::H264ConstrainedBaseline | ||
| 185 | + | CodecProfile::H264Main | ||
| 186 | + | CodecProfile::H264High => Codec::H264, | ||
| 187 | + CodecProfile::H265Main | CodecProfile::H265Main10 => Codec::H265, | ||
| 188 | + CodecProfile::Av1Main | CodecProfile::Av1Main10 => Codec::Av1, | ||
| 189 | + CodecProfile::Vp9Profile0 | CodecProfile::Vp9Profile2 => Codec::Vp9, | ||
| 190 | + } | ||
| 191 | + } | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +#[cfg(target_os = "linux")] | ||
| 195 | +fn va_profiles(profile: ec_va::Profile, rt_formats: u32) -> Vec<CodecProfile> { | ||
| 196 | + let yuv420 = ec_va::va::VA_RT_FORMAT_YUV420; | ||
| 197 | + let yuv420_10 = ec_va::va::VA_RT_FORMAT_YUV420_10; | ||
| 198 | + match profile { | ||
| 199 | + ec_va::Profile::H264ConstrainedBaseline => vec![CodecProfile::H264ConstrainedBaseline], | ||
| 200 | + ec_va::Profile::H264Main => vec![CodecProfile::H264Main], | ||
| 201 | + ec_va::Profile::H264High => vec![CodecProfile::H264High], | ||
| 202 | + ec_va::Profile::HEVCMain => vec![CodecProfile::H265Main], | ||
| 203 | + ec_va::Profile::HEVCMain10 => vec![CodecProfile::H265Main10], | ||
| 204 | + ec_va::Profile::VP9Profile0 => vec![CodecProfile::Vp9Profile0], | ||
| 205 | + ec_va::Profile::VP9Profile2 if rt_formats & yuv420_10 != 0 => vec![CodecProfile::Vp9Profile2], | ||
| 206 | + ec_va::Profile::AV1Profile0 => [ | ||
| 207 | + (yuv420, CodecProfile::Av1Main), | ||
| 208 | + (yuv420_10, CodecProfile::Av1Main10), | ||
| 209 | + ] | ||
| 210 | + .into_iter() | ||
| 211 | + .filter(|(bit, _)| rt_formats & bit != 0) | ||
| 212 | + .map(|(_, p)| p) | ||
| 213 | + .collect(), | ||
| 214 | + _ => Vec::new(), | ||
| 215 | + } | ||
| 216 | +} | ||
| 217 | + | ||
| 218 | +fn vk_profile(profile: ec_vk::CodecProfile) -> CodecProfile { | ||
| 219 | + match profile { | ||
| 220 | + ec_vk::CodecProfile::H264High => CodecProfile::H264High, | ||
| 221 | + ec_vk::CodecProfile::H265Main => CodecProfile::H265Main, | ||
| 222 | + ec_vk::CodecProfile::H265Main10 => CodecProfile::H265Main10, | ||
| 223 | + ec_vk::CodecProfile::Av1Main => CodecProfile::Av1Main, | ||
| 224 | + ec_vk::CodecProfile::Av1Main10 => CodecProfile::Av1Main10, | ||
| 225 | + ec_vk::CodecProfile::Vp9Profile0 => CodecProfile::Vp9Profile0, | ||
| 226 | + ec_vk::CodecProfile::Vp9Profile2 => CodecProfile::Vp9Profile2, | ||
| 227 | + ec_vk::CodecProfile::H264ConstrainedBaseline => CodecProfile::H264ConstrainedBaseline, | ||
| 228 | + ec_vk::CodecProfile::H264Main => CodecProfile::H264Main, | ||
| 229 | + } | ||
| 230 | +} | ||
| 231 | + | ||
crates/ec-hw/src/hw/decoder.rsadded+256 -0
| @@ -0,0 +1,256 @@ | |||
| 1 | +use super::*; | ||
| 2 | + | ||
| 3 | +enum VkDecoder { | ||
| 4 | + H264(VkH264Decoder), | ||
| 5 | + H265(VkH265Decoder), | ||
| 6 | + Av1(VkAv1Decoder), | ||
| 7 | + Vp9(VkVp9Decoder), | ||
| 8 | +} | ||
| 9 | + | ||
| 10 | +impl VkDecoder { | ||
| 11 | + fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { | ||
| 12 | + match self { | ||
| 13 | + VkDecoder::H264(d) => d.decode(data, timestamp), | ||
| 14 | + VkDecoder::H265(d) => d.decode(data, timestamp), | ||
| 15 | + VkDecoder::Av1(d) => d.decode(data, timestamp), | ||
| 16 | + VkDecoder::Vp9(d) => d.decode(data, timestamp), | ||
| 17 | + } | ||
| 18 | + } | ||
| 19 | + | ||
| 20 | + fn next_frame(&mut self) -> Option<HwPicture> { | ||
| 21 | + match self { | ||
| 22 | + VkDecoder::H264(d) => d.next_frame(), | ||
| 23 | + VkDecoder::H265(d) => d.next_frame(), | ||
| 24 | + VkDecoder::Av1(d) => d.next_frame(), | ||
| 25 | + VkDecoder::Vp9(d) => d.next_frame(), | ||
| 26 | + } | ||
| 27 | + } | ||
| 28 | + | ||
| 29 | + fn flush(&mut self) -> Result<()> { | ||
| 30 | + match self { | ||
| 31 | + VkDecoder::H264(d) => d.flush(), | ||
| 32 | + VkDecoder::H265(d) => d.flush(), | ||
| 33 | + VkDecoder::Av1(d) => d.flush(), | ||
| 34 | + VkDecoder::Vp9(d) => d.flush(), | ||
| 35 | + } | ||
| 36 | + } | ||
| 37 | + | ||
| 38 | + fn reset(&mut self) { | ||
| 39 | + match self { | ||
| 40 | + VkDecoder::H264(d) => d.reset(), | ||
| 41 | + VkDecoder::H265(d) => d.reset(), | ||
| 42 | + VkDecoder::Av1(d) => d.reset(), | ||
| 43 | + VkDecoder::Vp9(d) => d.reset(), | ||
| 44 | + } | ||
| 45 | + } | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +enum DecInner { | ||
| 49 | + Vk(VkDecoder), | ||
| 50 | + #[cfg(target_os = "linux")] | ||
| 51 | + Va(VaDecoder), | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +const REPLAY_LIMIT: usize = 64; | ||
| 55 | + | ||
| 56 | +/// What a decoder hands out: 8-bit I420, or packed RGB converted on the way out. | ||
| 57 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 58 | +pub struct RgbOutput { | ||
| 59 | + /// Byte order of each output pixel. | ||
| 60 | + pub order: RgbOrder, | ||
| 61 | + /// Scale pictures wider than this down to it, keeping the aspect ratio. | ||
| 62 | + pub max_width: Option<u32>, | ||
| 63 | + /// Scale pictures taller than this down to it, keeping the aspect ratio. | ||
| 64 | + pub max_height: Option<u32>, | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +impl RgbOutput { | ||
| 68 | + pub(crate) fn bound(&self) -> (Option<u32>, Option<u32>) { | ||
| 69 | + (self.max_width, self.max_height) | ||
| 70 | + } | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// A hardware decoder on whichever backend opened. | ||
| 74 | +pub struct HwDecoder { | ||
| 75 | + inner: DecInner, | ||
| 76 | + born_epoch: u64, | ||
| 77 | + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] | ||
| 78 | + codec: Codec, | ||
| 79 | + rgb: Option<RgbOutput>, | ||
| 80 | + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] | ||
| 81 | + replay: Option<Vec<(Vec<u8>, i64)>>, | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +impl HwDecoder { | ||
| 85 | + /// Open a decoder for `codec`. Every codec tries Vulkan Video first, then VA-API (Linux). | ||
| 86 | + pub fn open(codec: Codec) -> Result<HwDecoder> { | ||
| 87 | + HwDecoder::open_with(codec, None) | ||
| 88 | + } | ||
| 89 | + | ||
| 90 | + /// 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. | ||
| 91 | + pub fn open_rgb(codec: Codec, output: RgbOutput) -> Result<HwDecoder> { | ||
| 92 | + HwDecoder::open_with(codec, Some(output)) | ||
| 93 | + } | ||
| 94 | + | ||
| 95 | + fn open_with(codec: Codec, rgb: Option<RgbOutput>) -> Result<HwDecoder> { | ||
| 96 | + let mut reasons = Vec::new(); | ||
| 97 | + let born_epoch = crate::reset::gpu_reset_epoch(); | ||
| 98 | + let vk = vk_grace().and_then(|()| match codec { | ||
| 99 | + Codec::H264 => VkH264Decoder::new().map(VkDecoder::H264), | ||
| 100 | + Codec::H265 => VkH265Decoder::new().map(VkDecoder::H265), | ||
| 101 | + Codec::Av1 => VkAv1Decoder::new().map(VkDecoder::Av1), | ||
| 102 | + Codec::Vp9 => VkVp9Decoder::new().map(VkDecoder::Vp9), | ||
| 103 | + }); | ||
| 104 | + match vk { | ||
| 105 | + Ok(inner) => { | ||
| 106 | + return Ok(HwDecoder { | ||
| 107 | + inner: DecInner::Vk(inner), | ||
| 108 | + born_epoch, | ||
| 109 | + codec, | ||
| 110 | + rgb, | ||
| 111 | + replay: Some(Vec::new()), | ||
| 112 | + }); | ||
| 113 | + } | ||
| 114 | + Err(e) => reasons.push(format!("Vk: {e}")), | ||
| 115 | + } | ||
| 116 | + #[cfg(target_os = "linux")] | ||
| 117 | + { | ||
| 118 | + match open_va_decoder(codec) { | ||
| 119 | + Ok(inner) => { | ||
| 120 | + return Ok(HwDecoder { | ||
| 121 | + inner: DecInner::Va(inner), | ||
| 122 | + born_epoch, | ||
| 123 | + codec, | ||
| 124 | + rgb, | ||
| 125 | + replay: None, | ||
| 126 | + }); | ||
| 127 | + } | ||
| 128 | + Err(e) => reasons.push(format!("Va: {e}")), | ||
| 129 | + } | ||
| 130 | + } | ||
| 131 | + Err(Error::unsupported( | ||
| 132 | + format!("{codec:?} hardware decode"), | ||
| 133 | + reasons.join("; "), | ||
| 134 | + )) | ||
| 135 | + } | ||
| 136 | + | ||
| 137 | + /// The backend this decoder runs on. | ||
| 138 | + pub fn backend(&self) -> Backend { | ||
| 139 | + match self.inner { | ||
| 140 | + DecInner::Vk(_) => Backend::Vk, | ||
| 141 | + #[cfg(target_os = "linux")] | ||
| 142 | + DecInner::Va(_) => Backend::Va, | ||
| 143 | + } | ||
| 144 | + } | ||
| 145 | + | ||
| 146 | + /// Feed one access unit. A stream Vulkan refuses (an unsupported profile) before its first | ||
| 147 | + /// picture comes out moves to VA-API on Linux, replaying what was fed so far. | ||
| 148 | + pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { | ||
| 149 | + let born_epoch = self.born_epoch; | ||
| 150 | + let result = match &mut self.inner { | ||
| 151 | + DecInner::Vk(d) => vk_session_alive(born_epoch).and_then(|()| d.decode(data, timestamp)), | ||
| 152 | + #[cfg(target_os = "linux")] | ||
| 153 | + DecInner::Va(d) => d.decode(data, timestamp), | ||
| 154 | + }; | ||
| 155 | + if let Some(fed) = self.replay.as_mut() { | ||
| 156 | + fed.push((data.to_vec(), timestamp)); | ||
| 157 | + if fed.len() > REPLAY_LIMIT { | ||
| 158 | + self.replay = None; | ||
| 159 | + } | ||
| 160 | + } | ||
| 161 | + #[cfg(target_os = "linux")] | ||
| 162 | + if let Err(Error::Unsupported { .. }) = result | ||
| 163 | + && let Some(fed) = &self.replay | ||
| 164 | + && let Ok(mut va) = open_va_decoder(self.codec) | ||
| 165 | + && fed.iter().all(|(chunk, ts)| va.decode(chunk, *ts).is_ok()) | ||
| 166 | + { | ||
| 167 | + self.replay = None; | ||
| 168 | + self.inner = DecInner::Va(va); | ||
| 169 | + return Ok(()); | ||
| 170 | + } | ||
| 171 | + result | ||
| 172 | + } | ||
| 173 | + | ||
| 174 | + /// The next picture in display order, held in its decode slot until dropped. Convert it with the `to_*` methods of [`HwPicture`]. | ||
| 175 | + pub fn next_picture(&mut self) -> Result<Option<HwPicture>> { | ||
| 176 | + self.pull() | ||
| 177 | + } | ||
| 178 | + | ||
| 179 | + /// The next picture in display order, as 8-bit I420 with its timestamp. | ||
| 180 | + pub fn next_frame(&mut self) -> Result<Option<(i64, I420)>> { | ||
| 181 | + match self.pull()? { | ||
| 182 | + None => Ok(None), | ||
| 183 | + Some(picture) => Ok(Some((picture.timestamp, picture.to_i420()?))), | ||
| 184 | + } | ||
| 185 | + } | ||
| 186 | + | ||
| 187 | + /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder not opened with [`HwDecoder::open_rgb`]. | ||
| 188 | + pub fn next_rgb(&mut self) -> Result<Option<(i64, RgbPicture)>> { | ||
| 189 | + let mut dst = RgbPicture::default(); | ||
| 190 | + Ok(self.next_rgb_into(&mut dst)?.map(|ts| (ts, dst))) | ||
| 191 | + } | ||
| 192 | + | ||
| 193 | + /// Changes the RGB output of a decoder opened with [`HwDecoder::open_rgb`] from the next picture on. | ||
| 194 | + pub fn set_rgb_output(&mut self, output: RgbOutput) -> Result<()> { | ||
| 195 | + let rgb = self | ||
| 196 | + .rgb | ||
| 197 | + .as_mut() | ||
| 198 | + .ok_or_else(|| Error::config("set_rgb_output on a decoder not opened with open_rgb"))?; | ||
| 199 | + *rgb = output; | ||
| 200 | + Ok(()) | ||
| 201 | + } | ||
| 202 | + | ||
| 203 | + /// [`HwDecoder::next_rgb`] into `dst`, reusing its allocation across pictures; returns the timestamp. | ||
| 204 | + pub fn next_rgb_into(&mut self, dst: &mut RgbPicture) -> Result<Option<i64>> { | ||
| 205 | + let output = self | ||
| 206 | + .rgb | ||
| 207 | + .ok_or_else(|| Error::config("next_rgb on a decoder not opened with open_rgb"))?; | ||
| 208 | + match self.pull()? { | ||
| 209 | + None => Ok(None), | ||
| 210 | + Some(picture) => { | ||
| 211 | + picture.rgb_into(&output, dst)?; | ||
| 212 | + Ok(Some(picture.timestamp)) | ||
| 213 | + } | ||
| 214 | + } | ||
| 215 | + } | ||
| 216 | + | ||
| 217 | + fn pull(&mut self) -> Result<Option<HwPicture>> { | ||
| 218 | + match &mut self.inner { | ||
| 219 | + DecInner::Vk(d) => { | ||
| 220 | + vk_session_alive(self.born_epoch)?; | ||
| 221 | + let picture = d.next_frame(); | ||
| 222 | + if picture.is_some() { | ||
| 223 | + self.replay = None; | ||
| 224 | + } | ||
| 225 | + Ok(picture) | ||
| 226 | + } | ||
| 227 | + #[cfg(target_os = "linux")] | ||
| 228 | + DecInner::Va(d) => Ok(d.next_frame().map(HwPicture::va)), | ||
| 229 | + } | ||
| 230 | + } | ||
| 231 | + | ||
| 232 | + /// 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. | ||
| 233 | + pub fn reset(&mut self) { | ||
| 234 | + match &mut self.inner { | ||
| 235 | + DecInner::Vk(d) => d.reset(), | ||
| 236 | + #[cfg(target_os = "linux")] | ||
| 237 | + DecInner::Va(d) => d.reset(), | ||
| 238 | + } | ||
| 239 | + self.replay = None; | ||
| 240 | + } | ||
| 241 | + | ||
| 242 | + /// Emit every picture still held for reordering. | ||
| 243 | + pub fn flush(&mut self) -> Result<()> { | ||
| 244 | + match &mut self.inner { | ||
| 245 | + DecInner::Vk(d) => d.flush(), | ||
| 246 | + #[cfg(target_os = "linux")] | ||
| 247 | + DecInner::Va(d) => d.flush(), | ||
| 248 | + } | ||
| 249 | + } | ||
| 250 | +} | ||
| 251 | + | ||
| 252 | +#[cfg(target_os = "linux")] | ||
| 253 | +fn open_va_decoder(codec: Codec) -> Result<VaDecoder> { | ||
| 254 | + let display = ec_va::open()?; | ||
| 255 | + VaDecoder::new(&display, codec) | ||
| 256 | +} | ||
crates/ec-hw/src/hw/encoder.rsadded+621 -0
| @@ -0,0 +1,621 @@ | |||
| 1 | +use super::*; | ||
| 2 | + | ||
| 3 | +/// The Vulkan encoder for one codec. | ||
| 4 | +enum VkEncoder { | ||
| 5 | + H264(ec_vk::H264Encoder), | ||
| 6 | + H265(ec_vk::H265Encoder), | ||
| 7 | + Av1(ec_vk::Av1Encoder), | ||
| 8 | +} | ||
| 9 | + | ||
| 10 | +const ID_HISTORY: usize = 512; | ||
| 11 | + | ||
| 12 | +impl VkEncoder { | ||
| 13 | + fn submit( | ||
| 14 | + &mut self, | ||
| 15 | + input: EncodeInput, | ||
| 16 | + force_keyframe: bool, | ||
| 17 | + ) -> std::result::Result<Option<ec_vk::CodedFrame>, ec_vk::Error> { | ||
| 18 | + match input { | ||
| 19 | + EncodeInput::I420(frame) => { | ||
| 20 | + let (y, u, v) = (&frame.y, &frame.u, &frame.v); | ||
| 21 | + match self { | ||
| 22 | + VkEncoder::H264(e) => e.submit(y, u, v, force_keyframe), | ||
| 23 | + VkEncoder::H265(e) => e.submit(y, u, v, force_keyframe), | ||
| 24 | + VkEncoder::Av1(e) => e.submit(y, u, v, force_keyframe), | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + EncodeInput::I420_16(frame) => { | ||
| 28 | + let (y, u, v) = (&frame.y, &frame.u, &frame.v); | ||
| 29 | + match self { | ||
| 30 | + VkEncoder::H264(_) => Err(ec_vk::Error::Unsupported("10-bit H.264 encode".into())), | ||
| 31 | + VkEncoder::H265(e) => e.submit_16(y, u, v, force_keyframe), | ||
| 32 | + VkEncoder::Av1(e) => e.submit_16(y, u, v, force_keyframe), | ||
| 33 | + } | ||
| 34 | + } | ||
| 35 | + EncodeInput::Rgb(frame) => { | ||
| 36 | + let bgr = frame.order == RgbOrder::Bgra; | ||
| 37 | + let (data, sw, sh, stride) = (frame.data, frame.width, frame.height, frame.stride); | ||
| 38 | + match self { | ||
| 39 | + VkEncoder::H264(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), | ||
| 40 | + VkEncoder::H265(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), | ||
| 41 | + VkEncoder::Av1(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), | ||
| 42 | + } | ||
| 43 | + } | ||
| 44 | + #[cfg(target_os = "linux")] | ||
| 45 | + EncodeInput::DmaBuf(frame) => { | ||
| 46 | + let planes = [DmaBufPlane { | ||
| 47 | + fd: 0, | ||
| 48 | + offset: frame.offset, | ||
| 49 | + pitch: frame.stride, | ||
| 50 | + }]; | ||
| 51 | + let src = DmaBuf { | ||
| 52 | + fds: std::slice::from_ref(&frame.fd), | ||
| 53 | + planes: &planes, | ||
| 54 | + width: frame.width, | ||
| 55 | + height: frame.height, | ||
| 56 | + modifier: frame.modifier, | ||
| 57 | + format: if frame.order == RgbOrder::Bgra { | ||
| 58 | + DmaBufFormat::Bgrx | ||
| 59 | + } else { | ||
| 60 | + DmaBufFormat::Rgbx | ||
| 61 | + }, | ||
| 62 | + }; | ||
| 63 | + self.submit_dma(&src, force_keyframe) | ||
| 64 | + } | ||
| 65 | + #[cfg(target_os = "linux")] | ||
| 66 | + EncodeInput::DmaBufYuv(frame) => { | ||
| 67 | + let src = DmaBuf { | ||
| 68 | + fds: frame.fds, | ||
| 69 | + planes: &frame.planes, | ||
| 70 | + width: frame.width, | ||
| 71 | + height: frame.height, | ||
| 72 | + modifier: frame.modifier, | ||
| 73 | + format: frame.format, | ||
| 74 | + }; | ||
| 75 | + self.submit_dma(&src, force_keyframe) | ||
| 76 | + } | ||
| 77 | + #[cfg(windows)] | ||
| 78 | + EncodeInput::D3d11(frame) => { | ||
| 79 | + let src = frame.texture(); | ||
| 80 | + match self { | ||
| 81 | + VkEncoder::H264(e) => e.submit_d3d11(&src, force_keyframe), | ||
| 82 | + VkEncoder::H265(e) => e.submit_d3d11(&src, force_keyframe), | ||
| 83 | + VkEncoder::Av1(e) => e.submit_d3d11(&src, force_keyframe), | ||
| 84 | + } | ||
| 85 | + } | ||
| 86 | + } | ||
| 87 | + } | ||
| 88 | + | ||
| 89 | + #[cfg(target_os = "linux")] | ||
| 90 | + fn submit_dma( | ||
| 91 | + &mut self, | ||
| 92 | + src: &DmaBuf, | ||
| 93 | + force_keyframe: bool, | ||
| 94 | + ) -> std::result::Result<Option<ec_vk::CodedFrame>, ec_vk::Error> { | ||
| 95 | + match self { | ||
| 96 | + VkEncoder::H264(e) => e.submit_dmabuf(src, force_keyframe), | ||
| 97 | + VkEncoder::H265(e) => e.submit_dmabuf(src, force_keyframe), | ||
| 98 | + VkEncoder::Av1(e) => e.submit_dmabuf(src, force_keyframe), | ||
| 99 | + } | ||
| 100 | + } | ||
| 101 | + | ||
| 102 | + fn flush(&mut self) -> std::result::Result<Vec<ec_vk::CodedFrame>, ec_vk::Error> { | ||
| 103 | + match self { | ||
| 104 | + VkEncoder::H264(e) => e.flush(), | ||
| 105 | + VkEncoder::H265(e) => e.flush(), | ||
| 106 | + VkEncoder::Av1(e) => e.flush(), | ||
| 107 | + } | ||
| 108 | + } | ||
| 109 | + | ||
| 110 | + fn encode( | ||
| 111 | + &mut self, | ||
| 112 | + frame: &I420, | ||
| 113 | + force_keyframe: bool, | ||
| 114 | + ) -> std::result::Result<ec_vk::CodedFrame, ec_vk::Error> { | ||
| 115 | + let (y, u, v) = (&frame.y, &frame.u, &frame.v); | ||
| 116 | + match self { | ||
| 117 | + VkEncoder::H264(e) => e.encode(y, u, v, force_keyframe), | ||
| 118 | + VkEncoder::H265(e) => e.encode(y, u, v, force_keyframe), | ||
| 119 | + VkEncoder::Av1(e) => e.encode(y, u, v, force_keyframe), | ||
| 120 | + } | ||
| 121 | + } | ||
| 122 | + | ||
| 123 | + fn encode_16( | ||
| 124 | + &mut self, | ||
| 125 | + frame: &I420_16, | ||
| 126 | + force_keyframe: bool, | ||
| 127 | + ) -> std::result::Result<ec_vk::CodedFrame, ec_vk::Error> { | ||
| 128 | + let (y, u, v) = (&frame.y, &frame.u, &frame.v); | ||
| 129 | + match self { | ||
| 130 | + VkEncoder::H264(_) => Err(ec_vk::Error::Unsupported("10-bit H.264 encode".into())), | ||
| 131 | + VkEncoder::H265(e) => e.encode_16(y, u, v, force_keyframe), | ||
| 132 | + VkEncoder::Av1(e) => e.encode_16(y, u, v, force_keyframe), | ||
| 133 | + } | ||
| 134 | + } | ||
| 135 | + | ||
| 136 | + fn set_rate( | ||
| 137 | + &mut self, | ||
| 138 | + rate: ec_vk::RateControl, | ||
| 139 | + fps: (u32, u32), | ||
| 140 | + ) -> std::result::Result<(), ec_vk::Error> { | ||
| 141 | + match self { | ||
| 142 | + VkEncoder::H264(e) => e.set_rate(rate, fps), | ||
| 143 | + VkEncoder::H265(e) => e.set_rate(rate, fps), | ||
| 144 | + VkEncoder::Av1(e) => e.set_rate(rate, fps), | ||
| 145 | + } | ||
| 146 | + } | ||
| 147 | + | ||
| 148 | + fn encode_rgb( | ||
| 149 | + &mut self, | ||
| 150 | + frame: &RgbFrame, | ||
| 151 | + force_keyframe: bool, | ||
| 152 | + ) -> std::result::Result<ec_vk::CodedFrame, ec_vk::Error> { | ||
| 153 | + let bgr = frame.order == RgbOrder::Bgra; | ||
| 154 | + let (data, sw, sh, stride) = (frame.data, frame.width, frame.height, frame.stride); | ||
| 155 | + match self { | ||
| 156 | + VkEncoder::H264(e) => e.encode_rgb(data, sw, sh, stride, bgr, force_keyframe), | ||
| 157 | + VkEncoder::H265(e) => e.encode_rgb(data, sw, sh, stride, bgr, force_keyframe), | ||
| 158 | + VkEncoder::Av1(e) => e.encode_rgb(data, sw, sh, stride, bgr, force_keyframe), | ||
| 159 | + } | ||
| 160 | + } | ||
| 161 | + | ||
| 162 | + #[cfg(target_os = "linux")] | ||
| 163 | + fn encode_dmabuf( | ||
| 164 | + &mut self, | ||
| 165 | + src: &DmaBuf, | ||
| 166 | + force_keyframe: bool, | ||
| 167 | + ) -> std::result::Result<ec_vk::CodedFrame, ec_vk::Error> { | ||
| 168 | + match self { | ||
| 169 | + VkEncoder::H264(e) => e.encode_dmabuf(src, force_keyframe), | ||
| 170 | + VkEncoder::H265(e) => e.encode_dmabuf(src, force_keyframe), | ||
| 171 | + VkEncoder::Av1(e) => e.encode_dmabuf(src, force_keyframe), | ||
| 172 | + } | ||
| 173 | + } | ||
| 174 | +} | ||
| 175 | + | ||
| 176 | +enum EncInner { | ||
| 177 | + Vk(VkEncoder), | ||
| 178 | + #[cfg(target_os = "linux")] | ||
| 179 | + Va(VaEncoder), | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +/// A hardware encoder on whichever backend opened. | ||
| 183 | +pub struct HwEncoder { | ||
| 184 | + inner: EncInner, | ||
| 185 | + born_epoch: u64, | ||
| 186 | + config: EncoderConfig, | ||
| 187 | + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] | ||
| 188 | + size: (usize, usize), | ||
| 189 | + pending: VecDeque<i64>, | ||
| 190 | + ids: VecDeque<(i64, u64)>, | ||
| 191 | + keyframe_next: bool, | ||
| 192 | + tunings: Tunings, | ||
| 193 | + rc: RateFeedback, | ||
| 194 | +} | ||
| 195 | + | ||
| 196 | +impl HwEncoder { | ||
| 197 | + /// Open an encoder. `prefer` = `None` tries Vulkan, then VA-API. | ||
| 198 | + pub fn open(config: EncoderConfig, prefer: Option<Backend>) -> Result<HwEncoder> { | ||
| 199 | + let order = match prefer { | ||
| 200 | + Some(backend) => vec![backend], | ||
| 201 | + None => vec![Backend::Vk, Backend::Va], | ||
| 202 | + }; | ||
| 203 | + let mut reasons = Vec::new(); | ||
| 204 | + for backend in order { | ||
| 205 | + let born_epoch = crate::reset::gpu_reset_epoch(); | ||
| 206 | + match open_backend(backend, config) { | ||
| 207 | + Ok(inner) => { | ||
| 208 | + let size = (config.width as usize, config.height as usize); | ||
| 209 | + return Ok(HwEncoder { | ||
| 210 | + inner, | ||
| 211 | + born_epoch, | ||
| 212 | + config, | ||
| 213 | + size, | ||
| 214 | + pending: VecDeque::new(), | ||
| 215 | + ids: VecDeque::new(), | ||
| 216 | + keyframe_next: false, | ||
| 217 | + tunings: Tunings { | ||
| 218 | + bitrate: config.bitrate, | ||
| 219 | + framerate: config.framerate, | ||
| 220 | + }, | ||
| 221 | + rc: RateFeedback::default(), | ||
| 222 | + }); | ||
| 223 | + } | ||
| 224 | + Err(e) => reasons.push(format!("{backend:?}: {e}")), | ||
| 225 | + } | ||
| 226 | + } | ||
| 227 | + Err(Error::unsupported( | ||
| 228 | + format!("{:?} hardware encode", config.codec), | ||
| 229 | + reasons.join("; "), | ||
| 230 | + )) | ||
| 231 | + } | ||
| 232 | + | ||
| 233 | + /// The backend this encoder runs on. | ||
| 234 | + pub fn backend(&self) -> Backend { | ||
| 235 | + match self.inner { | ||
| 236 | + EncInner::Vk(_) => Backend::Vk, | ||
| 237 | + #[cfg(target_os = "linux")] | ||
| 238 | + EncInner::Va(_) => Backend::Va, | ||
| 239 | + } | ||
| 240 | + } | ||
| 241 | + | ||
| 242 | + /// Change bitrate or frame rate from the next frame; a constant-QP encoder keeps its QP. | ||
| 243 | + pub fn tune(&mut self, tunings: Tunings) -> Result<()> { | ||
| 244 | + match &mut self.inner { | ||
| 245 | + EncInner::Vk(enc) => { | ||
| 246 | + vk_session_alive(self.born_epoch)?; | ||
| 247 | + self.tunings = tunings; | ||
| 248 | + self.rc = RateFeedback::default(); | ||
| 249 | + let rate = vk_rate(&self.config, tunings.bitrate); | ||
| 250 | + enc.set_rate(rate, tunings.framerate)?; | ||
| 251 | + } | ||
| 252 | + #[cfg(target_os = "linux")] | ||
| 253 | + EncInner::Va(enc) => enc.tune(tunings), | ||
| 254 | + } | ||
| 255 | + Ok(()) | ||
| 256 | + } | ||
| 257 | + | ||
| 258 | + /// Submit one picture without waiting; the oldest coded picture comes back once two are in flight. Call [`HwEncoder::flush`] at the end. | ||
| 259 | + pub fn submit(&mut self, input: EncodeInput, meta: FrameMetadata) -> Result<Option<CodedFrame>> { | ||
| 260 | + let meta = self.with_recovery(meta); | ||
| 261 | + match &mut self.inner { | ||
| 262 | + EncInner::Vk(enc) => { | ||
| 263 | + vk_session_alive(self.born_epoch)?; | ||
| 264 | + let coded = enc.submit(input, meta.force_keyframe)?; | ||
| 265 | + self.pending.push_back(meta.timestamp); | ||
| 266 | + let Some(coded) = coded else { | ||
| 267 | + return Ok(None); | ||
| 268 | + }; | ||
| 269 | + let timestamp = self.pending.pop_front().unwrap_or_default(); | ||
| 270 | + self.steer(coded.data.len())?; | ||
| 271 | + Ok(Some(self.vk_frame(coded, timestamp))) | ||
| 272 | + } | ||
| 273 | + #[cfg(target_os = "linux")] | ||
| 274 | + EncInner::Va(enc) => match input { | ||
| 275 | + EncodeInput::I420(frame) => enc.submit(frame, meta), | ||
| 276 | + EncodeInput::I420_16(frame) => enc.submit_16(frame, meta), | ||
| 277 | + EncodeInput::Rgb(frame) => enc.submit(&rgb_to_i420(frame, self.size)?, meta), | ||
| 278 | + EncodeInput::DmaBuf(_) | EncodeInput::DmaBufYuv(_) => Err(Error::unsupported( | ||
| 279 | + "DMA-BUF encode", | ||
| 280 | + "the VA-API backend has no DMA-BUF input here", | ||
| 281 | + )), | ||
| 282 | + }, | ||
| 283 | + } | ||
| 284 | + } | ||
| 285 | + | ||
| 286 | + /// Wait for every submitted picture and return them, oldest first. | ||
| 287 | + pub fn flush(&mut self) -> Result<Vec<CodedFrame>> { | ||
| 288 | + match &mut self.inner { | ||
| 289 | + EncInner::Vk(enc) => { | ||
| 290 | + vk_session_alive(self.born_epoch)?; | ||
| 291 | + let frames = enc.flush()?; | ||
| 292 | + let out: Vec<CodedFrame> = frames | ||
| 293 | + .into_iter() | ||
| 294 | + .map(|coded| { | ||
| 295 | + let timestamp = self.pending.pop_front().unwrap_or_default(); | ||
| 296 | + self.vk_frame(coded, timestamp) | ||
| 297 | + }) | ||
| 298 | + .collect(); | ||
| 299 | + let mut steered = Ok(()); | ||
| 300 | + for frame in &out { | ||
| 301 | + steered = steered.and(self.steer(frame.data.len())); | ||
| 302 | + } | ||
| 303 | + steered?; | ||
| 304 | + Ok(out) | ||
| 305 | + } | ||
| 306 | + #[cfg(target_os = "linux")] | ||
| 307 | + EncInner::Va(enc) => enc.flush(), | ||
| 308 | + } | ||
| 309 | + } | ||
| 310 | + | ||
| 311 | + fn idle(&self) -> Result<()> { | ||
| 312 | + if self.pending.is_empty() { | ||
| 313 | + Ok(()) | ||
| 314 | + } else { | ||
| 315 | + Err(Error::config("pipelined frames pending; call flush first")) | ||
| 316 | + } | ||
| 317 | + } | ||
| 318 | + | ||
| 319 | + /// 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. | ||
| 320 | + pub fn ack(&mut self, timestamp: i64) { | ||
| 321 | + let Some(&(_, id)) = self.ids.iter().rev().find(|(ts, _)| *ts <= timestamp) else { | ||
| 322 | + return; | ||
| 323 | + }; | ||
| 324 | + match &mut self.inner { | ||
| 325 | + EncInner::Vk(VkEncoder::Av1(enc)) => enc.ack(id), | ||
| 326 | + EncInner::Vk(VkEncoder::H265(enc)) => enc.ack(id), | ||
| 327 | + EncInner::Vk(VkEncoder::H264(enc)) => enc.ack(id), | ||
| 328 | + #[cfg(target_os = "linux")] | ||
| 329 | + EncInner::Va(_) => {} | ||
| 330 | + } | ||
| 331 | + } | ||
| 332 | + | ||
| 333 | + /// 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. | ||
| 334 | + pub fn recover(&mut self) { | ||
| 335 | + match &mut self.inner { | ||
| 336 | + EncInner::Vk(VkEncoder::Av1(enc)) => enc.recover(), | ||
| 337 | + EncInner::Vk(VkEncoder::H265(enc)) => enc.recover(), | ||
| 338 | + EncInner::Vk(VkEncoder::H264(enc)) => enc.recover(), | ||
| 339 | + #[cfg(target_os = "linux")] | ||
| 340 | + EncInner::Va(_) => self.keyframe_next = true, | ||
| 341 | + } | ||
| 342 | + } | ||
| 343 | + | ||
| 344 | + fn with_recovery(&mut self, meta: FrameMetadata) -> FrameMetadata { | ||
| 345 | + FrameMetadata { | ||
| 346 | + force_keyframe: meta.force_keyframe || std::mem::take(&mut self.keyframe_next), | ||
| 347 | + ..meta | ||
| 348 | + } | ||
| 349 | + } | ||
| 350 | + | ||
| 351 | + fn vk_frame(&mut self, coded: ec_vk::CodedFrame, timestamp: i64) -> CodedFrame { | ||
| 352 | + if self.ids.len() == ID_HISTORY { | ||
| 353 | + self.ids.pop_front(); | ||
| 354 | + } | ||
| 355 | + self.ids.push_back((timestamp, coded.id)); | ||
| 356 | + CodedFrame { | ||
| 357 | + data: coded.data, | ||
| 358 | + timestamp, | ||
| 359 | + is_keyframe: coded.keyframe, | ||
| 360 | + recovery: coded.recovery, | ||
| 361 | + } | ||
| 362 | + } | ||
| 363 | + | ||
| 364 | + fn steer(&mut self, bytes: usize) -> Result<()> { | ||
| 365 | + if !self.rc.track(bytes, self.config.rate_control, self.tunings) { | ||
| 366 | + return Ok(()); | ||
| 367 | + } | ||
| 368 | + let rate = vk_rate(&self.config, self.rc.steered_bitrate(self.tunings.bitrate)); | ||
| 369 | + match &mut self.inner { | ||
| 370 | + EncInner::Vk(enc) => enc.set_rate(rate, self.tunings.framerate)?, | ||
| 371 | + #[cfg(target_os = "linux")] | ||
| 372 | + EncInner::Va(_) => {} | ||
| 373 | + } | ||
| 374 | + Ok(()) | ||
| 375 | + } | ||
| 376 | + | ||
| 377 | + /// Encode one frame; `meta.force_keyframe` starts a new GOP. | ||
| 378 | + pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> { | ||
| 379 | + let meta = self.with_recovery(meta); | ||
| 380 | + self.idle()?; | ||
| 381 | + match &mut self.inner { | ||
| 382 | + EncInner::Vk(enc) => { | ||
| 383 | + vk_session_alive(self.born_epoch)?; | ||
| 384 | + let coded = enc.encode(frame, meta.force_keyframe)?; | ||
| 385 | + self.steer(coded.data.len())?; | ||
| 386 | + Ok(self.vk_frame(coded, meta.timestamp)) | ||
| 387 | + } | ||
| 388 | + #[cfg(target_os = "linux")] | ||
| 389 | + EncInner::Va(enc) => enc.encode(frame, meta), | ||
| 390 | + } | ||
| 391 | + } | ||
| 392 | + | ||
| 393 | + /// Encode one 10-bit frame of a 10-bit encoder (H.265 and AV1), the [`HwEncoder::encode`] of a 10-bit encoder. | ||
| 394 | + pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result<CodedFrame> { | ||
| 395 | + let meta = self.with_recovery(meta); | ||
| 396 | + self.idle()?; | ||
| 397 | + match &mut self.inner { | ||
| 398 | + EncInner::Vk(enc) => { | ||
| 399 | + vk_session_alive(self.born_epoch)?; | ||
| 400 | + let coded = enc.encode_16(frame, meta.force_keyframe)?; | ||
| 401 | + self.steer(coded.data.len())?; | ||
| 402 | + Ok(self.vk_frame(coded, meta.timestamp)) | ||
| 403 | + } | ||
| 404 | + #[cfg(target_os = "linux")] | ||
| 405 | + EncInner::Va(enc) => enc.encode_16(frame, meta), | ||
| 406 | + } | ||
| 407 | + } | ||
| 408 | + | ||
| 409 | + /// 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. | ||
| 410 | + pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result<CodedFrame> { | ||
| 411 | + let meta = self.with_recovery(meta); | ||
| 412 | + self.idle()?; | ||
| 413 | + match &mut self.inner { | ||
| 414 | + EncInner::Vk(enc) => { | ||
| 415 | + vk_session_alive(self.born_epoch)?; | ||
| 416 | + let coded = enc.encode_rgb(frame, meta.force_keyframe)?; | ||
| 417 | + self.steer(coded.data.len())?; | ||
| 418 | + Ok(self.vk_frame(coded, meta.timestamp)) | ||
| 419 | + } | ||
| 420 | + #[cfg(target_os = "linux")] | ||
| 421 | + EncInner::Va(enc) => enc.encode(&rgb_to_i420(frame, self.size)?, meta), | ||
| 422 | + } | ||
| 423 | + } | ||
| 424 | + | ||
| 425 | + /// Encode one DMA-BUF frame of the source size, box-downscaled to the encoder size. Vulkan only; VA-API has its own PRIME path. | ||
| 426 | + #[cfg(target_os = "linux")] | ||
| 427 | + pub fn encode_dmabuf(&mut self, frame: &DmaBufFrame, meta: FrameMetadata) -> Result<CodedFrame> { | ||
| 428 | + let planes = frame.planes(); | ||
| 429 | + self.encode_dma(&frame.as_dmabuf(&planes), meta) | ||
| 430 | + } | ||
| 431 | + | ||
| 432 | + /// Encode one NV12 or P010 DMA-BUF frame of the encoder size. Vulkan only; VA-API has its own PRIME path. | ||
| 433 | + #[cfg(target_os = "linux")] | ||
| 434 | + pub fn encode_dmabuf_yuv( | ||
| 435 | + &mut self, | ||
| 436 | + frame: &DmaBufYuvFrame, | ||
| 437 | + meta: FrameMetadata, | ||
| 438 | + ) -> Result<CodedFrame> { | ||
| 439 | + let src = DmaBuf { | ||
| 440 | + fds: frame.fds, | ||
| 441 | + planes: &frame.planes, | ||
| 442 | + width: frame.width, | ||
| 443 | + height: frame.height, | ||
| 444 | + modifier: frame.modifier, | ||
| 445 | + format: frame.format, | ||
| 446 | + }; | ||
| 447 | + self.encode_dma(&src, meta) | ||
| 448 | + } | ||
| 449 | + | ||
| 450 | + /// Encode one shared D3D11 texture of the source size, downscaled to the encoder size on the GPU. | ||
| 451 | + #[cfg(windows)] | ||
| 452 | + pub fn encode_d3d11(&mut self, frame: &D3d11Frame, meta: FrameMetadata) -> Result<CodedFrame> { | ||
| 453 | + let meta = self.with_recovery(meta); | ||
| 454 | + self.idle()?; | ||
| 455 | + let EncInner::Vk(enc) = &mut self.inner; | ||
| 456 | + vk_session_alive(self.born_epoch)?; | ||
| 457 | + let src = frame.texture(); | ||
| 458 | + let coded = match enc { | ||
| 459 | + VkEncoder::H264(e) => e.encode_d3d11(&src, meta.force_keyframe), | ||
| 460 | + VkEncoder::H265(e) => e.encode_d3d11(&src, meta.force_keyframe), | ||
| 461 | + VkEncoder::Av1(e) => e.encode_d3d11(&src, meta.force_keyframe), | ||
| 462 | + }?; | ||
| 463 | + self.steer(coded.data.len())?; | ||
| 464 | + Ok(self.vk_frame(coded, meta.timestamp)) | ||
| 465 | + } | ||
| 466 | + | ||
| 467 | + #[cfg(target_os = "linux")] | ||
| 468 | + fn encode_dma(&mut self, src: &DmaBuf, meta: FrameMetadata) -> Result<CodedFrame> { | ||
| 469 | + let meta = self.with_recovery(meta); | ||
| 470 | + self.idle()?; | ||
| 471 | + match &mut self.inner { | ||
| 472 | + EncInner::Vk(enc) => { | ||
| 473 | + vk_session_alive(self.born_epoch)?; | ||
| 474 | + let coded = enc.encode_dmabuf(src, meta.force_keyframe)?; | ||
| 475 | + self.steer(coded.data.len())?; | ||
| 476 | + Ok(self.vk_frame(coded, meta.timestamp)) | ||
| 477 | + } | ||
| 478 | + EncInner::Va(_) => Err(Error::unsupported( | ||
| 479 | + "DMA-BUF encode", | ||
| 480 | + "the VA-API backend has no DMA-BUF input here", | ||
| 481 | + )), | ||
| 482 | + } | ||
| 483 | + } | ||
| 484 | +} | ||
| 485 | + | ||
| 486 | +fn open_backend(backend: Backend, config: EncoderConfig) -> Result<EncInner> { | ||
| 487 | + match backend { | ||
| 488 | + Backend::Vk => open_vk(config).map(EncInner::Vk), | ||
| 489 | + Backend::Va => open_va(config), | ||
| 490 | + } | ||
| 491 | +} | ||
| 492 | + | ||
| 493 | +fn open_vk(config: EncoderConfig) -> Result<VkEncoder> { | ||
| 494 | + vk_grace()?; | ||
| 495 | + if config.bit_depth == 10 && config.codec == EncCodec::H264 { | ||
| 496 | + return Err(Error::unsupported( | ||
| 497 | + "10-bit H.264 Vulkan Video encode", | ||
| 498 | + "the driver offers no High 10 H.264 encode", | ||
| 499 | + )); | ||
| 500 | + } | ||
| 501 | + if config.bit_depth != 8 && config.bit_depth != 10 { | ||
| 502 | + return Err(Error::config(format!( | ||
| 503 | + "encoder bit depth {}: Vulkan encodes 8-bit, or 10-bit H.265 and AV1", | ||
| 504 | + config.bit_depth | ||
| 505 | + ))); | ||
| 506 | + } | ||
| 507 | + let gpu = vk_gpu() | ||
| 508 | + .ok_or_else(|| Error::unsupported("Vulkan Video encode", "no Vulkan Video device"))?; | ||
| 509 | + let rate = vk_rate(&config, config.bitrate); | ||
| 510 | + let level = match config.codec { | ||
| 511 | + EncCodec::H264 => crate::level::h264(&config), | ||
| 512 | + EncCodec::H265 => crate::level::hevc(&config), | ||
| 513 | + EncCodec::Av1 => crate::level::av1(&config), | ||
| 514 | + }; | ||
| 515 | + let (width, height, fps, gop_size) = ( | ||
| 516 | + config.width, | ||
| 517 | + config.height, | ||
| 518 | + config.framerate, | ||
| 519 | + config.gop_size, | ||
| 520 | + ); | ||
| 521 | + let colour = config.colour.map(|c| ec_vk::Colour { | ||
| 522 | + primaries: c.primaries, | ||
| 523 | + transfer: c.transfer, | ||
| 524 | + matrix: c.matrix, | ||
| 525 | + full_range: c.full_range, | ||
| 526 | + }); | ||
| 527 | + Ok(match config.codec { | ||
| 528 | + EncCodec::H264 => VkEncoder::H264(ec_vk::H264Encoder::new( | ||
| 529 | + &gpu, | ||
| 530 | + ec_vk::H264EncoderConfig { | ||
| 531 | + width, | ||
| 532 | + height, | ||
| 533 | + fps, | ||
| 534 | + gop_size, | ||
| 535 | + rate, | ||
| 536 | + profile: vk_h264_profile(config.h264_profile), | ||
| 537 | + level, | ||
| 538 | + colour, | ||
| 539 | + quality: config.quality, | ||
| 540 | + }, | ||
| 541 | + )?), | ||
| 542 | + EncCodec::H265 => VkEncoder::H265(ec_vk::H265Encoder::new( | ||
| 543 | + &gpu, | ||
| 544 | + ec_vk::H265EncoderConfig { | ||
| 545 | + width, | ||
| 546 | + height, | ||
| 547 | + fps, | ||
| 548 | + gop_size, | ||
| 549 | + rate, | ||
| 550 | + bit_depth: config.bit_depth, | ||
| 551 | + level, | ||
| 552 | + colour, | ||
| 553 | + quality: config.quality, | ||
| 554 | + }, | ||
| 555 | + )?), | ||
| 556 | + EncCodec::Av1 => VkEncoder::Av1(ec_vk::Av1Encoder::new( | ||
| 557 | + &gpu, | ||
| 558 | + ec_vk::Av1EncoderConfig { | ||
| 559 | + width, | ||
| 560 | + height, | ||
| 561 | + fps, | ||
| 562 | + gop_size, | ||
| 563 | + rate, | ||
| 564 | + bit_depth: config.bit_depth, | ||
| 565 | + level, | ||
| 566 | + colour, | ||
| 567 | + quality: config.quality, | ||
| 568 | + }, | ||
| 569 | + )?), | ||
| 570 | + }) | ||
| 571 | +} | ||
| 572 | + | ||
| 573 | +fn vk_h264_profile(profile: H264Profile) -> ec_vk::H264Profile { | ||
| 574 | + match profile { | ||
| 575 | + H264Profile::ConstrainedBaseline => ec_vk::H264Profile::ConstrainedBaseline, | ||
| 576 | + H264Profile::Main => ec_vk::H264Profile::Main, | ||
| 577 | + H264Profile::High => ec_vk::H264Profile::High, | ||
| 578 | + } | ||
| 579 | +} | ||
| 580 | + | ||
| 581 | +fn vk_rate(config: &EncoderConfig, bitrate: u32) -> ec_vk::RateControl { | ||
| 582 | + match (config.rate_control, config.codec) { | ||
| 583 | + (RateControlMode::ConstantQp { qp }, EncCodec::Av1) => ec_vk::RateControl::ConstantQp { | ||
| 584 | + qp: (qp / 5).min(51) as u8, | ||
| 585 | + }, | ||
| 586 | + (RateControlMode::ConstantQp { qp }, _) => ec_vk::RateControl::ConstantQp { | ||
| 587 | + qp: qp.min(51) as u8, | ||
| 588 | + }, | ||
| 589 | + (RateControlMode::ConstantBitrate, _) => ec_vk::RateControl::Cbr { | ||
| 590 | + bitrate, | ||
| 591 | + buffer_ms: hrd_buffer_ms(config), | ||
| 592 | + }, | ||
| 593 | + (RateControlMode::VariableBitrate, _) => ec_vk::RateControl::Vbr { | ||
| 594 | + bitrate, | ||
| 595 | + max_bitrate: bitrate.saturating_mul(3) / 2, | ||
| 596 | + buffer_ms: hrd_buffer_ms(config), | ||
| 597 | + min_qp: None, | ||
| 598 | + }, | ||
| 599 | + (RateControlMode::Qvbr { quality }, _) => ec_vk::RateControl::Vbr { | ||
| 600 | + bitrate, | ||
| 601 | + max_bitrate: bitrate, | ||
| 602 | + buffer_ms: hrd_buffer_ms(config), | ||
| 603 | + min_qp: Some(quality.min(51) as u8), | ||
| 604 | + }, | ||
| 605 | + } | ||
| 606 | +} | ||
| 607 | + | ||
| 608 | +#[cfg(target_os = "linux")] | ||
| 609 | +fn open_va(config: EncoderConfig) -> Result<EncInner> { | ||
| 610 | + let display = ec_va::open()?; | ||
| 611 | + Ok(EncInner::Va(VaEncoder::new(&display, config)?)) | ||
| 612 | +} | ||
| 613 | + | ||
| 614 | +#[cfg(not(target_os = "linux"))] | ||
| 615 | +fn open_va(config: EncoderConfig) -> Result<EncInner> { | ||
| 616 | + Err(Error::unsupported( | ||
| 617 | + format!("{:?} VA-API encode", config.codec), | ||
| 618 | + "VA-API is Linux only", | ||
| 619 | + )) | ||
| 620 | +} | ||
| 621 | + | ||
crates/ec-hw/src/hw/input.rsadded+239 -0
| @@ -0,0 +1,239 @@ | |||
| 1 | +use super::*; | ||
| 2 | + | ||
| 3 | +/// Byte order of a packed 32-bit RGB pixel; the X or A byte is ignored. | ||
| 4 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 5 | +pub enum RgbOrder { | ||
| 6 | + /// Bytes R, G, B, X. | ||
| 7 | + Rgba, | ||
| 8 | + /// Bytes B, G, R, X. | ||
| 9 | + Bgra, | ||
| 10 | +} | ||
| 11 | + | ||
| 12 | +/// A packed 32-bit RGB picture with a row stride in bytes. | ||
| 13 | +#[derive(Debug, Clone, Copy)] | ||
| 14 | +pub struct RgbFrame<'a> { | ||
| 15 | + /// Pixels, `stride * height` bytes at least. | ||
| 16 | + pub data: &'a [u8], | ||
| 17 | + /// Source width in pixels, even; at least the encoder width. | ||
| 18 | + pub width: u32, | ||
| 19 | + /// Source height in pixels, even; at least the encoder height. | ||
| 20 | + pub height: u32, | ||
| 21 | + /// Row stride in bytes, a multiple of 4 and at least `width * 4`. | ||
| 22 | + pub stride: u32, | ||
| 23 | + /// Byte order of each pixel. | ||
| 24 | + pub order: RgbOrder, | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +/// A two-plane DMA-BUF of NV12 or P010 pixels, one or two objects (one per plane). | ||
| 28 | +#[cfg(target_os = "linux")] | ||
| 29 | +#[derive(Debug, Clone, Copy)] | ||
| 30 | +pub struct DmaBufYuvFrame<'a> { | ||
| 31 | + /// DMA-BUF file descriptors, duplicated by the encoder. | ||
| 32 | + pub fds: &'a [BorrowedFd<'a>], | ||
| 33 | + /// Y then UV plane. | ||
| 34 | + pub planes: [DmaBufPlane; 2], | ||
| 35 | + /// Width in pixels, even; equal to the encoder width. | ||
| 36 | + pub width: u32, | ||
| 37 | + /// Height in pixels, even; equal to the encoder height. | ||
| 38 | + pub height: u32, | ||
| 39 | + /// DRM format modifier. | ||
| 40 | + pub modifier: u64, | ||
| 41 | + /// NV12 or P010. | ||
| 42 | + pub format: DmaBufFormat, | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +/// A single-plane DMA-BUF of packed 32-bit RGB pixels, linear or DRM format modifier tiled. | ||
| 46 | +#[cfg(target_os = "linux")] | ||
| 47 | +#[derive(Debug, Clone, Copy)] | ||
| 48 | +pub struct DmaBufFrame<'a> { | ||
| 49 | + /// DMA-BUF file descriptor, duplicated by the encoder. | ||
| 50 | + pub fd: BorrowedFd<'a>, | ||
| 51 | + /// Width in pixels, even; at least the encoder width. | ||
| 52 | + pub width: u32, | ||
| 53 | + /// Height in pixels, even; at least the encoder height. | ||
| 54 | + pub height: u32, | ||
| 55 | + /// Row pitch in bytes. | ||
| 56 | + pub stride: u32, | ||
| 57 | + /// Byte offset of the plane. | ||
| 58 | + pub offset: u32, | ||
| 59 | + /// DRM format modifier. | ||
| 60 | + pub modifier: u64, | ||
| 61 | + /// Byte order of each pixel. | ||
| 62 | + pub order: RgbOrder, | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +#[cfg(target_os = "linux")] | ||
| 66 | +impl<'a> DmaBufFrame<'a> { | ||
| 67 | + pub(super) fn planes(&self) -> [DmaBufPlane; 1] { | ||
| 68 | + [DmaBufPlane { | ||
| 69 | + fd: 0, | ||
| 70 | + offset: self.offset, | ||
| 71 | + pitch: self.stride, | ||
| 72 | + }] | ||
| 73 | + } | ||
| 74 | + | ||
| 75 | + pub(super) fn as_dmabuf<'b>(&'b self, planes: &'b [DmaBufPlane; 1]) -> DmaBuf<'b> { | ||
| 76 | + DmaBuf { | ||
| 77 | + fds: std::slice::from_ref(&self.fd), | ||
| 78 | + planes, | ||
| 79 | + width: self.width, | ||
| 80 | + height: self.height, | ||
| 81 | + modifier: self.modifier, | ||
| 82 | + format: if self.order == RgbOrder::Bgra { | ||
| 83 | + DmaBufFormat::Bgrx | ||
| 84 | + } else { | ||
| 85 | + DmaBufFormat::Rgbx | ||
| 86 | + }, | ||
| 87 | + } | ||
| 88 | + } | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +/// DRM format modifiers [`HwEncoder::encode_dmabuf`] imports for `order`, empty when Vulkan or its DMA-BUF import is unavailable. | ||
| 92 | +#[cfg(target_os = "linux")] | ||
| 93 | +pub fn dmabuf_modifiers(order: RgbOrder) -> Vec<u64> { | ||
| 94 | + vk_gpu().map_or_else(Vec::new, |gpu| { | ||
| 95 | + ec_vk::rgb_import_modifiers(&gpu, order == RgbOrder::Bgra) | ||
| 96 | + }) | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +/// 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. | ||
| 100 | +#[cfg(target_os = "linux")] | ||
| 101 | +pub fn dup_fd(fd: std::os::fd::RawFd) -> Result<std::os::fd::OwnedFd> { | ||
| 102 | + Ok(ec_vk::dup_raw_fd(fd)?) | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +/// 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`. | ||
| 106 | +/// | ||
| 107 | +/// [`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. | ||
| 108 | +#[cfg(windows)] | ||
| 109 | +#[derive(Debug, Clone, Copy)] | ||
| 110 | +pub struct D3d11Frame<'a> { | ||
| 111 | + /// Shared NT handle; borrowed, not closed. | ||
| 112 | + pub handle: std::os::windows::io::BorrowedHandle<'a>, | ||
| 113 | + /// Identity of the texture, unique for the process lifetime. | ||
| 114 | + pub id: u64, | ||
| 115 | + /// Width in pixels, even; at least the encoder width. | ||
| 116 | + pub width: u32, | ||
| 117 | + /// Height in pixels, even; at least the encoder height. | ||
| 118 | + pub height: u32, | ||
| 119 | + /// Byte order of each pixel. | ||
| 120 | + pub order: RgbOrder, | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +#[cfg(windows)] | ||
| 124 | +impl D3d11Frame<'_> { | ||
| 125 | + fn texture(&self) -> ec_vk::D3d11Texture<'_> { | ||
| 126 | + ec_vk::D3d11Texture { | ||
| 127 | + handle: self.handle, | ||
| 128 | + id: self.id, | ||
| 129 | + width: self.width, | ||
| 130 | + height: self.height, | ||
| 131 | + bgr: self.order == RgbOrder::Bgra, | ||
| 132 | + } | ||
| 133 | + } | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +/// 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). | ||
| 137 | +#[cfg(windows)] | ||
| 138 | +pub struct D3d11Pool(ec_vk::D3d11Pool); | ||
| 139 | + | ||
| 140 | +#[cfg(windows)] | ||
| 141 | +impl D3d11Pool { | ||
| 142 | + /// A pool on the device that produces the frames. | ||
| 143 | + pub fn new(device: &ec_vk::windows::Win32::Graphics::Direct3D11::ID3D11Device) -> Result<Self> { | ||
| 144 | + Ok(D3d11Pool(ec_vk::D3d11Pool::new(device)?)) | ||
| 145 | + } | ||
| 146 | + | ||
| 147 | + /// 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. | ||
| 148 | + pub fn submit( | ||
| 149 | + &mut self, | ||
| 150 | + frame: &ec_vk::windows::Win32::Graphics::Direct3D11::ID3D11Texture2D, | ||
| 151 | + ) -> Result<D3d11Frame<'_>> { | ||
| 152 | + let t = self.0.submit(frame)?; | ||
| 153 | + Ok(D3d11Frame { | ||
| 154 | + handle: t.handle, | ||
| 155 | + id: t.id, | ||
| 156 | + width: t.width, | ||
| 157 | + height: t.height, | ||
| 158 | + order: if t.bgr { RgbOrder::Bgra } else { RgbOrder::Rgba }, | ||
| 159 | + }) | ||
| 160 | + } | ||
| 161 | +} | ||
| 162 | + | ||
| 163 | +/// Whether [`HwEncoder::encode_d3d11`] can import textures of `order` on this machine's Vulkan device. | ||
| 164 | +#[cfg(windows)] | ||
| 165 | +pub fn d3d11_supported(order: RgbOrder) -> bool { | ||
| 166 | + vk_gpu().is_some_and(|gpu| ec_vk::d3d11_importable(&gpu, order == RgbOrder::Bgra)) | ||
| 167 | +} | ||
| 168 | + | ||
| 169 | +/// One picture for [`HwEncoder::submit`]. | ||
| 170 | +#[derive(Debug, Clone, Copy)] | ||
| 171 | +pub enum EncodeInput<'a> { | ||
| 172 | + /// 8-bit I420. | ||
| 173 | + I420(&'a I420), | ||
| 174 | + /// 10-bit I420 of a 10-bit encoder (H.265 and AV1). | ||
| 175 | + I420_16(&'a I420_16), | ||
| 176 | + /// Packed RGB, box-downscaled to the encoder size. | ||
| 177 | + Rgb(&'a RgbFrame<'a>), | ||
| 178 | + /// DMA-BUF of packed RGB, Vulkan only. | ||
| 179 | + #[cfg(target_os = "linux")] | ||
| 180 | + DmaBuf(&'a DmaBufFrame<'a>), | ||
| 181 | + /// DMA-BUF of NV12 or P010 at the encoder size, Vulkan only. | ||
| 182 | + #[cfg(target_os = "linux")] | ||
| 183 | + DmaBufYuv(&'a DmaBufYuvFrame<'a>), | ||
| 184 | + /// Shared D3D11 texture of packed RGB, Vulkan only. | ||
| 185 | + #[cfg(windows)] | ||
| 186 | + D3d11(&'a D3d11Frame<'a>), | ||
| 187 | +} | ||
| 188 | + | ||
| 189 | +#[cfg(target_os = "linux")] | ||
| 190 | +pub(super) fn rgb_to_i420(frame: &RgbFrame, (w, h): (usize, usize)) -> Result<I420> { | ||
| 191 | + let (sw, sh, stride) = ( | ||
| 192 | + frame.width as usize, | ||
| 193 | + frame.height as usize, | ||
| 194 | + frame.stride as usize, | ||
| 195 | + ); | ||
| 196 | + if sw % 2 != 0 | ||
| 197 | + || sh % 2 != 0 | ||
| 198 | + || stride % 4 != 0 | ||
| 199 | + || stride < sw * 4 | ||
| 200 | + || frame.data.len() < stride * sh | ||
| 201 | + { | ||
| 202 | + return Err(Error::config("RGB frame size or stride")); | ||
| 203 | + } | ||
| 204 | + if sw < w || sh < h { | ||
| 205 | + return Err(Error::config("RGB source smaller than encoder")); | ||
| 206 | + } | ||
| 207 | + let packed: Vec<u8> = frame | ||
| 208 | + .data | ||
| 209 | + .chunks(stride) | ||
| 210 | + .take(sh) | ||
| 211 | + .flat_map(|row| &row[..sw * 4]) | ||
| 212 | + .copied() | ||
| 213 | + .collect(); | ||
| 214 | + let packed = if (sw, sh) == (w, h) { | ||
| 215 | + packed | ||
| 216 | + } else { | ||
| 217 | + let mut scaled = vec![0; w * h * 4]; | ||
| 218 | + ec_dsp::rgb::rgb_box_downscale(&packed, sw, sh, sw * 4, &mut scaled, w, h); | ||
| 219 | + scaled | ||
| 220 | + }; | ||
| 221 | + let chroma = (w / 2) * (h / 2); | ||
| 222 | + let mut out = I420 { | ||
| 223 | + y: vec![0; w * h], | ||
| 224 | + u: vec![0; chroma], | ||
| 225 | + v: vec![0; chroma], | ||
| 226 | + width: w as u32, | ||
| 227 | + height: h as u32, | ||
| 228 | + }; | ||
| 229 | + match frame.order { | ||
| 230 | + RgbOrder::Rgba => { | ||
| 231 | + ec_dsp::rgb::rgba_to_i420_709(&packed, w, h, &mut out.y, &mut out.u, &mut out.v) | ||
| 232 | + } | ||
| 233 | + RgbOrder::Bgra => { | ||
| 234 | + ec_dsp::rgb::bgra_to_i420_709(&packed, w, h, &mut out.y, &mut out.u, &mut out.v) | ||
| 235 | + } | ||
| 236 | + } | ||
| 237 | + Ok(out) | ||
| 238 | +} | ||
| 239 | + | ||