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