Merge branch 'simplify/s2' into simplify/w2
Browse files at this commit10 changed files +1438 -1470
- crates/ec-hw/src/dec/mod.rs +9 -16
- crates/ec-hw/src/enc/headers.rs +20 -22
- crates/ec-hw/src/enc/mod.rs +29 -49
- crates/ec-hw/src/hw.rs +9 -1333
- 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/picture.rs +13 -25
- crates/ec-hw/src/pool.rs +11 -25
crates/ec-hw/src/dec/mod.rsmodified+9 -16
| @@ -19,7 +19,6 @@ | |||
| 19 | 19 | ||
| 20 | use std::collections::VecDeque; | 20 | use std::collections::VecDeque; |
| 21 | use std::rc::Rc; | 21 | use std::rc::Rc; |
| 22 | -use std::sync::atomic::Ordering; | ||
| 23 | use std::time::{Duration, Instant}; | 22 | use std::time::{Duration, Instant}; |
| 24 | 23 | ||
| 25 | use ec_va::caps::{Entrypoint, Profile}; | 24 | use ec_va::caps::{Entrypoint, Profile}; |
| @@ -264,12 +263,12 @@ pub(crate) struct Session { | |||
| 264 | born_epoch: u64, | 263 | born_epoch: u64, |
| 265 | /// The last submitted picture, waited for after the next one is submitted | 264 | /// The last submitted picture, waited for after the next one is submitted |
| 266 | /// (depth-1 pipelining; see [`Session::submit`]). | 265 | /// (depth-1 pipelining; see [`Session::submit`]). |
| 267 | - pending: std::sync::Mutex<Option<Pending>>, | 266 | + pending: std::cell::RefCell<Option<Pending>>, |
| 268 | /// Set once a picture hung or lost the GPU context. Every submission after | 267 | /// Set once a picture hung or lost the GPU context. Every submission after |
| 269 | /// that is refused: on Mesa, submitting to a context the kernel has reset | 268 | /// that is refused: on Mesa, submitting to a context the kernel has reset |
| 270 | /// aborts the whole process from the driver's own thread, which no | 269 | /// aborts the whole process from the driver's own thread, which no |
| 271 | /// `catch_unwind` can stop. | 270 | /// `catch_unwind` can stop. |
| 272 | - pub(crate) poisoned: std::sync::atomic::AtomicBool, | 271 | + pub(crate) poisoned: std::cell::Cell<bool>, |
| 273 | pub(crate) context: Rc<Context>, | 272 | pub(crate) context: Rc<Context>, |
| 274 | display: Rc<Display>, | 273 | display: Rc<Display>, |
| 275 | /// The readback image every frame of this stream reuses. | 274 | /// The readback image every frame of this stream reuses. |
| @@ -363,8 +362,8 @@ impl Session { | |||
| 363 | } | 362 | } |
| 364 | Ok(Session { | 363 | Ok(Session { |
| 365 | born_epoch, | 364 | born_epoch, |
| 366 | - pending: std::sync::Mutex::new(None), | 365 | + pending: std::cell::RefCell::new(None), |
| 367 | - poisoned: std::sync::atomic::AtomicBool::new(false), | 366 | + poisoned: std::cell::Cell::new(false), |
| 368 | context, | 367 | context, |
| 369 | display: Rc::clone(display), | 368 | display: Rc::clone(display), |
| 370 | pool, | 369 | pool, |
| @@ -416,7 +415,8 @@ impl Session { | |||
| 416 | // An old pending picture is waited for first: its wait is instant when | 415 | // An old pending picture is waited for first: its wait is instant when |
| 417 | // it is done, and an error condemns the session before we submit. | 416 | // it is done, and an error condemns the session before we submit. |
| 418 | let stale = self | 417 | let stale = self |
| 419 | - .pending_slot() | 418 | + .pending |
| 419 | + .borrow() | ||
| 420 | .as_ref() | 420 | .as_ref() |
| 421 | .filter(|p| p.since.elapsed() > IDLE_SETTLE) | 421 | .filter(|p| p.since.elapsed() > IDLE_SETTLE) |
| 422 | .map(|p| Rc::clone(&p.surface)); | 422 | .map(|p| Rc::clone(&p.surface)); |
| @@ -443,7 +443,7 @@ impl Session { | |||
| 443 | } | 443 | } |
| 444 | return Err(e.into()); | 444 | return Err(e.into()); |
| 445 | } | 445 | } |
| 446 | - let previous = self.pending_slot().replace(Pending { | 446 | + let previous = self.pending.borrow_mut().replace(Pending { |
| 447 | surface: Rc::clone(target), | 447 | surface: Rc::clone(target), |
| 448 | since: Instant::now(), | 448 | since: Instant::now(), |
| 449 | }); | 449 | }); |
| @@ -453,27 +453,20 @@ impl Session { | |||
| 453 | Ok(()) | 453 | Ok(()) |
| 454 | } | 454 | } |
| 455 | 455 | ||
| 456 | - fn pending_slot(&self) -> std::sync::MutexGuard<'_, Option<Pending>> { | ||
| 457 | - match self.pending.lock() { | ||
| 458 | - Ok(slot) => slot, | ||
| 459 | - Err(poisoned) => poisoned.into_inner(), | ||
| 460 | - } | ||
| 461 | - } | ||
| 462 | - | ||
| 463 | fn check_alive(&self) -> Result<()> { | 456 | fn check_alive(&self) -> Result<()> { |
| 464 | if crate::reset::gpu_reset_epoch() != self.born_epoch { | 457 | if crate::reset::gpu_reset_epoch() != self.born_epoch { |
| 465 | return Err(Error::hw_reset( | 458 | return Err(Error::hw_reset( |
| 466 | "the GPU was reset after this session was created; its context is lost", | 459 | "the GPU was reset after this session was created; its context is lost", |
| 467 | )); | 460 | )); |
| 468 | } | 461 | } |
| 469 | - if self.poisoned.load(Ordering::Acquire) { | 462 | + if self.poisoned.get() { |
| 470 | return Err(Error::poisoned("an earlier picture failed on the GPU")); | 463 | return Err(Error::poisoned("an earlier picture failed on the GPU")); |
| 471 | } | 464 | } |
| 472 | Ok(()) | 465 | Ok(()) |
| 473 | } | 466 | } |
| 474 | 467 | ||
| 475 | fn poison(&self) { | 468 | fn poison(&self) { |
| 476 | - if !self.poisoned.swap(true, Ordering::AcqRel) { | 469 | + if !self.poisoned.replace(true) { |
| 477 | crate::reset::report_gpu_reset(); | 470 | crate::reset::report_gpu_reset(); |
| 478 | } | 471 | } |
| 479 | } | 472 | } |
crates/ec-hw/src/enc/headers.rsmodified+20 -22
| @@ -10,12 +10,12 @@ | |||
| 10 | //! driver was given, or the header describes a picture other than the one the | 10 | //! driver was given, or the header describes a picture other than the one the |
| 11 | //! hardware coded. | 11 | //! hardware coded. |
| 12 | 12 | ||
| 13 | -/// `VAEncPackedHeaderSequence`: packed sequence-level header bits. | 13 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 14 | -pub const PACKED_HEADER_SEQUENCE: u32 = 1; | 14 | +pub(crate) enum PackedKind { |
| 15 | -/// `VAEncPackedHeaderPicture`: packed picture-level header bits. | 15 | + Sequence, |
| 16 | -pub const PACKED_HEADER_PICTURE: u32 = 2; | 16 | + Picture, |
| 17 | -/// `VAEncPackedHeaderSlice`: packed slice-level header bits. | 17 | + Slice, |
| 18 | -pub const PACKED_HEADER_SLICE: u32 = 3; | 18 | +} |
| 19 | 19 | ||
| 20 | use ec_core::BitWriter; | 20 | use ec_core::BitWriter; |
| 21 | 21 | ||
| @@ -26,13 +26,13 @@ use super::Colour; | |||
| 26 | /// The bit length matters for slice headers, which do not end on a byte | 26 | /// The bit length matters for slice headers, which do not end on a byte |
| 27 | /// boundary — the driver continues the bitstream from exactly that bit. | 27 | /// boundary — the driver continues the bitstream from exactly that bit. |
| 28 | pub(crate) struct Packed { | 28 | pub(crate) struct Packed { |
| 29 | - pub(crate) kind: u32, | 29 | + pub(crate) kind: PackedKind, |
| 30 | pub(crate) bytes: Vec<u8>, | 30 | pub(crate) bytes: Vec<u8>, |
| 31 | pub(crate) bits: u32, | 31 | pub(crate) bits: u32, |
| 32 | } | 32 | } |
| 33 | 33 | ||
| 34 | /// Wrap a complete NAL: start code, header byte(s), escaped payload. | 34 | /// Wrap a complete NAL: start code, header byte(s), escaped payload. |
| 35 | -fn nal(kind: u32, header: &[u8], rbsp: &[u8], padding_bits: u32) -> Packed { | 35 | +fn nal(kind: PackedKind, header: &[u8], rbsp: &[u8], padding_bits: u32) -> Packed { |
| 36 | let mut bytes = vec![0, 0, 0, 1]; | 36 | let mut bytes = vec![0, 0, 0, 1]; |
| 37 | bytes.extend_from_slice(header); | 37 | bytes.extend_from_slice(header); |
| 38 | let mut escaped = Vec::with_capacity(rbsp.len() + 8); | 38 | let mut escaped = Vec::with_capacity(rbsp.len() + 8); |
| @@ -133,7 +133,7 @@ pub(super) fn h264_sps(p: &H264Params) -> Packed { | |||
| 133 | w.write_ue(0); // max_num_reorder_frames | 133 | w.write_ue(0); // max_num_reorder_frames |
| 134 | w.write_ue(1); // max_dec_frame_buffering = max_num_ref_frames | 134 | w.write_ue(1); // max_dec_frame_buffering = max_num_ref_frames |
| 135 | trailing(&mut w); | 135 | trailing(&mut w); |
| 136 | - nal(PACKED_HEADER_SEQUENCE, &[0x67], &w.into_bytes(), 0) | 136 | + nal(PackedKind::Sequence, &[0x67], &w.into_bytes(), 0) |
| 137 | } | 137 | } |
| 138 | 138 | ||
| 139 | /// The picture parameter set (7.3.2.2). | 139 | /// The picture parameter set (7.3.2.2). |
| @@ -160,7 +160,7 @@ pub(super) fn h264_pps(p: &H264Params) -> Packed { | |||
| 160 | w.write_se(0); // second_chroma_qp_index_offset | 160 | w.write_se(0); // second_chroma_qp_index_offset |
| 161 | } | 161 | } |
| 162 | trailing(&mut w); | 162 | trailing(&mut w); |
| 163 | - nal(PACKED_HEADER_PICTURE, &[0x68], &w.into_bytes(), 0) | 163 | + nal(PackedKind::Picture, &[0x68], &w.into_bytes(), 0) |
| 164 | } | 164 | } |
| 165 | 165 | ||
| 166 | /// The slice header (7.3.3), up to but *not* including the slice data. | 166 | /// The slice header (7.3.3), up to but *not* including the slice data. |
| @@ -202,7 +202,7 @@ pub(super) fn h264_slice_header(idr: bool, frame_num: u32, idr_pic_id: u32) -> P | |||
| 202 | let padding = (8 - bits % 8) % 8; | 202 | let padding = (8 - bits % 8) % 8; |
| 203 | w.align_to_byte(); | 203 | w.align_to_byte(); |
| 204 | let header = if idr { 0x65 } else { 0x61 }; | 204 | let header = if idr { 0x65 } else { 0x61 }; |
| 205 | - nal(PACKED_HEADER_SLICE, &[header], &w.into_bytes(), padding) | 205 | + nal(PackedKind::Slice, &[header], &w.into_bytes(), padding) |
| 206 | } | 206 | } |
| 207 | 207 | ||
| 208 | /// `rbsp_trailing_bits` (7.3.2.11). | 208 | /// `rbsp_trailing_bits` (7.3.2.11). |
| @@ -220,8 +220,7 @@ fn trailing(w: &mut BitWriter) { | |||
| 220 | /// The syntax crate writes all four structures, so the encoder and the software | 220 | /// The syntax crate writes all four structures, so the encoder and the software |
| 221 | /// HEVC path in this family share one definition of what a parameter set is. | 221 | /// HEVC path in this family share one definition of what a parameter set is. |
| 222 | pub(super) mod hevc { | 222 | pub(super) mod hevc { |
| 223 | - #[allow(unused_imports)] | 223 | + use super::PackedKind; |
| 224 | - use super::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE}; | ||
| 225 | use ec_h265_syntax::{ | 224 | use ec_h265_syntax::{ |
| 226 | ConformanceWindow, NalHeader, NalUnitType, Pps, ProfileTierLevel, ShortTermRefPicSet, | 225 | ConformanceWindow, NalHeader, NalUnitType, Pps, ProfileTierLevel, ShortTermRefPicSet, |
| 227 | SliceHeader, SliceType, Sps, Vps, | 226 | SliceHeader, SliceType, Sps, Vps, |
| @@ -350,7 +349,7 @@ pub(super) mod hevc { | |||
| 350 | 349 | ||
| 351 | pub(in crate::enc) fn packed_vps(vps: &Vps) -> Packed { | 350 | pub(in crate::enc) fn packed_vps(vps: &Vps) -> Packed { |
| 352 | nal( | 351 | nal( |
| 353 | - PACKED_HEADER_SEQUENCE, | 352 | + PackedKind::Sequence, |
| 354 | &NalHeader::new(NalUnitType::Vps).to_bytes(), | 353 | &NalHeader::new(NalUnitType::Vps).to_bytes(), |
| 355 | &vps.to_rbsp(), | 354 | &vps.to_rbsp(), |
| 356 | 0, | 355 | 0, |
| @@ -359,7 +358,7 @@ pub(super) mod hevc { | |||
| 359 | 358 | ||
| 360 | pub(in crate::enc) fn packed_sps(sps: &Sps) -> Packed { | 359 | pub(in crate::enc) fn packed_sps(sps: &Sps) -> Packed { |
| 361 | nal( | 360 | nal( |
| 362 | - PACKED_HEADER_SEQUENCE, | 361 | + PackedKind::Sequence, |
| 363 | &NalHeader::new(NalUnitType::Sps).to_bytes(), | 362 | &NalHeader::new(NalUnitType::Sps).to_bytes(), |
| 364 | &sps.to_rbsp(), | 363 | &sps.to_rbsp(), |
| 365 | 0, | 364 | 0, |
| @@ -368,7 +367,7 @@ pub(super) mod hevc { | |||
| 368 | 367 | ||
| 369 | pub(in crate::enc) fn packed_pps(pps: &Pps) -> Packed { | 368 | pub(in crate::enc) fn packed_pps(pps: &Pps) -> Packed { |
| 370 | nal( | 369 | nal( |
| 371 | - PACKED_HEADER_PICTURE, | 370 | + PackedKind::Picture, |
| 372 | &NalHeader::new(NalUnitType::Pps).to_bytes(), | 371 | &NalHeader::new(NalUnitType::Pps).to_bytes(), |
| 373 | &pps.to_rbsp(), | 372 | &pps.to_rbsp(), |
| 374 | 0, | 373 | 0, |
| @@ -399,7 +398,7 @@ pub(super) mod hevc { | |||
| 399 | // alignment bit has to be in what it is given. | 398 | // alignment bit has to be in what it is given. |
| 400 | header.write(&mut w, sps, pps, nal_type); | 399 | header.write(&mut w, sps, pps, nal_type); |
| 401 | nal( | 400 | nal( |
| 402 | - PACKED_HEADER_SLICE, | 401 | + PackedKind::Slice, |
| 403 | &NalHeader::new(nal_type).to_bytes(), | 402 | &NalHeader::new(nal_type).to_bytes(), |
| 404 | &w.into_bytes(), | 403 | &w.into_bytes(), |
| 405 | 0, | 404 | 0, |
| @@ -422,8 +421,7 @@ pub(super) mod hevc { | |||
| 422 | /// syntax: a field written here that disagrees with the parameter buffer is a | 421 | /// syntax: a field written here that disagrees with the parameter buffer is a |
| 423 | /// picture described two ways, and the driver believes this one. | 422 | /// picture described two ways, and the driver believes this one. |
| 424 | pub(super) mod av1 { | 423 | pub(super) mod av1 { |
| 425 | - #[allow(unused_imports)] | 424 | + use super::PackedKind; |
| 426 | - use super::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE}; | ||
| 427 | use ec_core::BitWriter; | 425 | use ec_core::BitWriter; |
| 428 | 426 | ||
| 429 | use super::{Colour, Packed}; | 427 | use super::{Colour, Packed}; |
| @@ -438,7 +436,7 @@ pub(super) mod av1 { | |||
| 438 | const OBU_SIZE_BYTES: usize = 2; | 436 | const OBU_SIZE_BYTES: usize = 2; |
| 439 | 437 | ||
| 440 | /// Wrap a payload as one OBU: header byte, fixed-width `obu_size`, payload. | 438 | /// Wrap a payload as one OBU: header byte, fixed-width `obu_size`, payload. |
| 441 | - fn obu(kind: u32, obu_type: u8, payload: Vec<u8>) -> Packed { | 439 | + fn obu(kind: PackedKind, obu_type: u8, payload: Vec<u8>) -> Packed { |
| 442 | let mut bytes = Vec::with_capacity(payload.len() + 1 + OBU_SIZE_BYTES); | 440 | let mut bytes = Vec::with_capacity(payload.len() + 1 + OBU_SIZE_BYTES); |
| 443 | // forbidden(0) type(4) extension(0) has_size(1) reserved(0) | 441 | // forbidden(0) type(4) extension(0) has_size(1) reserved(0) |
| 444 | bytes.push(obu_type << 3 | 0b010); | 442 | bytes.push(obu_type << 3 | 0b010); |
| @@ -538,7 +536,7 @@ pub(super) mod av1 { | |||
| 538 | w.write_bit(false); // separate_uv_delta_q | 536 | w.write_bit(false); // separate_uv_delta_q |
| 539 | w.write_bit(false); // film_grain_params_present | 537 | w.write_bit(false); // film_grain_params_present |
| 540 | trailing(&mut w); | 538 | trailing(&mut w); |
| 541 | - obu(PACKED_HEADER_SEQUENCE, 1, w.into_bytes()) | 539 | + obu(PackedKind::Sequence, 1, w.into_bytes()) |
| 542 | } | 540 | } |
| 543 | 541 | ||
| 544 | /// What one picture's uncompressed header says. | 542 | /// What one picture's uncompressed header says. |
| @@ -649,7 +647,7 @@ pub(super) mod av1 { | |||
| 649 | } | 647 | } |
| 650 | } | 648 | } |
| 651 | trailing(&mut w); | 649 | trailing(&mut w); |
| 652 | - let packed = obu(PACKED_HEADER_PICTURE, 3, w.into_bytes()); | 650 | + let packed = obu(PackedKind::Picture, 3, w.into_bytes()); |
| 653 | let offsets = FrameHeaderOffsets { | 651 | let offsets = FrameHeaderOffsets { |
| 654 | qindex, | 652 | qindex, |
| 655 | segmentation, | 653 | segmentation, |
crates/ec-hw/src/enc/mod.rsmodified+29 -49
| @@ -108,7 +108,11 @@ struct InFlight<D: SurfaceMemoryDescriptor> { | |||
| 108 | keyframe: bool, | 108 | keyframe: bool, |
| 109 | } | 109 | } |
| 110 | 110 | ||
| 111 | -/// A hardware encoder. | 111 | +enum EncFrame<'a> { |
| 112 | + I420(&'a I420), | ||
| 113 | + I420_16(&'a I420_16), | ||
| 114 | +} | ||
| 115 | + | ||
| 112 | /// A hardware encoder. | 116 | /// A hardware encoder. |
| 113 | pub struct Encoder { | 117 | pub struct Encoder { |
| 114 | /// The GPU reset epoch this encoder was created in. | 118 | /// The GPU reset epoch this encoder was created in. |
| @@ -275,36 +279,14 @@ impl Encoder { | |||
| 275 | "encode: pipelined frames pending; call flush first", | 279 | "encode: pipelined frames pending; call flush first", |
| 276 | )); | 280 | )); |
| 277 | } | 281 | } |
| 278 | - if self.config.bit_depth != 8 { | 282 | + let input = self.stage(EncFrame::I420(frame))?; |
| 279 | - return Err(Error::config(format!( | ||
| 280 | - "encode: this encoder is configured for {} bits; call encode_16", | ||
| 281 | - self.config.bit_depth | ||
| 282 | - ))); | ||
| 283 | - } | ||
| 284 | - self.check_size(frame.width, frame.height)?; | ||
| 285 | - let input = self | ||
| 286 | - .pool | ||
| 287 | - .acquire() | ||
| 288 | - .ok_or_else(|| Error::config("encode: every surface is still in use"))?; | ||
| 289 | - upload(&self.context, frame, input.surface(), self.coded_size)?; | ||
| 290 | self.encode_settled(Rc::clone(input.surface()), meta) | 283 | self.encode_settled(Rc::clone(input.surface()), meta) |
| 291 | } | 284 | } |
| 292 | 285 | ||
| 293 | /// Submit one frame without waiting for it; the oldest pending frame comes back | 286 | /// Submit one frame without waiting for it; the oldest pending frame comes back |
| 294 | /// once more than [`DEPTH`] are in flight. | 287 | /// once more than [`DEPTH`] are in flight. |
| 295 | pub fn submit(&mut self, frame: &I420, meta: FrameMetadata) -> Result<Option<CodedFrame>> { | 288 | pub fn submit(&mut self, frame: &I420, meta: FrameMetadata) -> Result<Option<CodedFrame>> { |
| 296 | - if self.config.bit_depth != 8 { | 289 | + let input = self.stage(EncFrame::I420(frame))?; |
| 297 | - return Err(Error::config(format!( | ||
| 298 | - "submit: this encoder is configured for {} bits; call submit_16", | ||
| 299 | - self.config.bit_depth | ||
| 300 | - ))); | ||
| 301 | - } | ||
| 302 | - self.check_size(frame.width, frame.height)?; | ||
| 303 | - let input = self | ||
| 304 | - .pool | ||
| 305 | - .acquire() | ||
| 306 | - .ok_or_else(|| Error::config("submit: every surface is still in use"))?; | ||
| 307 | - upload(&self.context, frame, input.surface(), self.coded_size)?; | ||
| 308 | self.push_pipelined(input, meta) | 290 | self.push_pipelined(input, meta) |
| 309 | } | 291 | } |
| 310 | 292 | ||
| @@ -314,18 +296,7 @@ impl Encoder { | |||
| 314 | frame: &I420_16, | 296 | frame: &I420_16, |
| 315 | meta: FrameMetadata, | 297 | meta: FrameMetadata, |
| 316 | ) -> Result<Option<CodedFrame>> { | 298 | ) -> Result<Option<CodedFrame>> { |
| 317 | - if self.config.bit_depth != 10 { | 299 | + let input = self.stage(EncFrame::I420_16(frame))?; |
| 318 | - return Err(Error::config(format!( | ||
| 319 | - "submit_16: this encoder is configured for {} bits; call submit", | ||
| 320 | - self.config.bit_depth | ||
| 321 | - ))); | ||
| 322 | - } | ||
| 323 | - self.check_size(frame.width, frame.height)?; | ||
| 324 | - let input = self | ||
| 325 | - .pool | ||
| 326 | - .acquire() | ||
| 327 | - .ok_or_else(|| Error::config("submit_16: every surface is still in use"))?; | ||
| 328 | - upload_16(&self.context, frame, input.surface(), self.coded_size)?; | ||
| 329 | self.push_pipelined(input, meta) | 300 | self.push_pipelined(input, meta) |
| 330 | } | 301 | } |
| 331 | 302 | ||
| @@ -370,19 +341,31 @@ impl Encoder { | |||
| 370 | "encode_16: pipelined frames pending; call flush first", | 341 | "encode_16: pipelined frames pending; call flush first", |
| 371 | )); | 342 | )); |
| 372 | } | 343 | } |
| 373 | - if self.config.bit_depth != 10 { | 344 | + let input = self.stage(EncFrame::I420_16(frame))?; |
| 345 | + self.encode_settled(Rc::clone(input.surface()), meta) | ||
| 346 | + } | ||
| 347 | + | ||
| 348 | + fn stage(&mut self, frame: EncFrame) -> Result<Rc<PooledSurface>> { | ||
| 349 | + let (bits, width, height) = match frame { | ||
| 350 | + EncFrame::I420(f) => (8, f.width, f.height), | ||
| 351 | + EncFrame::I420_16(f) => (10, f.width, f.height), | ||
| 352 | + }; | ||
| 353 | + if self.config.bit_depth != bits { | ||
| 374 | return Err(Error::config(format!( | 354 | return Err(Error::config(format!( |
| 375 | - "encode_16: this encoder is configured for {} bits; call encode", | 355 | + "this encoder is configured for {} bits", |
| 376 | self.config.bit_depth | 356 | self.config.bit_depth |
| 377 | ))); | 357 | ))); |
| 378 | } | 358 | } |
| 379 | - self.check_size(frame.width, frame.height)?; | 359 | + self.check_size(width, height)?; |
| 380 | let input = self | 360 | let input = self |
| 381 | .pool | 361 | .pool |
| 382 | .acquire() | 362 | .acquire() |
| 383 | - .ok_or_else(|| Error::config("encode: every surface is still in use"))?; | 363 | + .ok_or_else(|| Error::config("every surface is still in use"))?; |
| 384 | - upload_16(&self.context, frame, input.surface(), self.coded_size)?; | 364 | + match frame { |
| 385 | - self.encode_settled(Rc::clone(input.surface()), meta) | 365 | + EncFrame::I420(f) => upload(&self.context, f, input.surface(), self.coded_size)?, |
| 366 | + EncFrame::I420_16(f) => upload_16(&self.context, f, input.surface(), self.coded_size)?, | ||
| 367 | + } | ||
| 368 | + Ok(input) | ||
| 386 | } | 369 | } |
| 387 | 370 | ||
| 388 | fn check_size(&self, width: u32, height: u32) -> Result<()> { | 371 | fn check_size(&self, width: u32, height: u32) -> Result<()> { |
| @@ -593,12 +576,9 @@ impl Encoder { | |||
| 593 | out: &mut Vec<BufferType>, | 576 | out: &mut Vec<BufferType>, |
| 594 | ) -> Result<()> { | 577 | ) -> Result<()> { |
| 595 | let kind = match packed.kind { | 578 | let kind = match packed.kind { |
| 596 | - headers::PACKED_HEADER_SEQUENCE => EncPackedHeaderType::Sequence, | 579 | + headers::PackedKind::Sequence => EncPackedHeaderType::Sequence, |
| 597 | - headers::PACKED_HEADER_PICTURE => EncPackedHeaderType::Picture, | 580 | + headers::PackedKind::Picture => EncPackedHeaderType::Picture, |
| 598 | - headers::PACKED_HEADER_SLICE => EncPackedHeaderType::Slice, | 581 | + headers::PackedKind::Slice => EncPackedHeaderType::Slice, |
| 599 | - other => { | ||
| 600 | - return Err(Error::config(format!("unknown packed header kind {other}"))); | ||
| 601 | - } | ||
| 602 | }; | 582 | }; |
| 603 | out.push(BufferType::EncPackedHeaderParameter( | 583 | out.push(BufferType::EncPackedHeaderParameter( |
| 604 | EncPackedHeaderParameter::new(kind, packed.bits, true), | 584 | EncPackedHeaderParameter::new(kind, packed.bits, true), |
crates/ec-hw/src/hw.rsmodified+9 -1333
| @@ -27,1336 +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 | -/// DRM format modifiers [`HwEncoder::encode_dmabuf`] imports for `order`, empty when Vulkan or its DMA-BUF import is unavailable. | ||
| 322 | -#[cfg(target_os = "linux")] | ||
| 323 | -pub fn dmabuf_modifiers(order: RgbOrder) -> Vec<u64> { | ||
| 324 | - vk_gpu().map_or_else(Vec::new, |gpu| { | ||
| 325 | - ec_vk::rgb_import_modifiers(&gpu, order == RgbOrder::Bgra) | ||
| 326 | - }) | ||
| 327 | -} | ||
| 328 | - | ||
| 329 | -/// 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. | ||
| 330 | -#[cfg(target_os = "linux")] | ||
| 331 | -pub fn dup_fd(fd: std::os::fd::RawFd) -> Result<std::os::fd::OwnedFd> { | ||
| 332 | - Ok(ec_vk::dup_raw_fd(fd)?) | ||
| 333 | -} | ||
| 334 | - | ||
| 335 | -/// 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`. | ||
| 336 | -/// | ||
| 337 | -/// [`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. | ||
| 338 | -#[cfg(windows)] | ||
| 339 | -#[derive(Debug, Clone, Copy)] | ||
| 340 | -pub struct D3d11Frame<'a> { | ||
| 341 | - /// Shared NT handle; borrowed, not closed. | ||
| 342 | - pub handle: std::os::windows::io::BorrowedHandle<'a>, | ||
| 343 | - /// Identity of the texture, unique for the process lifetime. | ||
| 344 | - pub id: u64, | ||
| 345 | - /// Width in pixels, even; at least the encoder width. | ||
| 346 | - pub width: u32, | ||
| 347 | - /// Height in pixels, even; at least the encoder height. | ||
| 348 | - pub height: u32, | ||
| 349 | - /// Byte order of each pixel. | ||
| 350 | - pub order: RgbOrder, | ||
| 351 | -} | ||
| 352 | - | ||
| 353 | -#[cfg(windows)] | ||
| 354 | -impl D3d11Frame<'_> { | ||
| 355 | - fn texture(&self) -> ec_vk::D3d11Texture<'_> { | ||
| 356 | - ec_vk::D3d11Texture { | ||
| 357 | - handle: self.handle, | ||
| 358 | - id: self.id, | ||
| 359 | - width: self.width, | ||
| 360 | - height: self.height, | ||
| 361 | - bgr: self.order == RgbOrder::Bgra, | ||
| 362 | - } | ||
| 363 | - } | ||
| 364 | -} | ||
| 365 | - | ||
| 366 | -/// 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). | ||
| 367 | -#[cfg(windows)] | ||
| 368 | -pub struct D3d11Pool(ec_vk::D3d11Pool); | ||
| 369 | - | ||
| 370 | -#[cfg(windows)] | ||
| 371 | -impl D3d11Pool { | ||
| 372 | - /// A pool on the device that produces the frames. | ||
| 373 | - pub fn new(device: &ec_vk::windows::Win32::Graphics::Direct3D11::ID3D11Device) -> Result<Self> { | ||
| 374 | - Ok(D3d11Pool(ec_vk::D3d11Pool::new(device)?)) | ||
| 375 | - } | ||
| 376 | - | ||
| 377 | - /// 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. | ||
| 378 | - pub fn submit( | ||
| 379 | - &mut self, | ||
| 380 | - frame: &ec_vk::windows::Win32::Graphics::Direct3D11::ID3D11Texture2D, | ||
| 381 | - ) -> Result<D3d11Frame<'_>> { | ||
| 382 | - let t = self.0.submit(frame)?; | ||
| 383 | - Ok(D3d11Frame { | ||
| 384 | - handle: t.handle, | ||
| 385 | - id: t.id, | ||
| 386 | - width: t.width, | ||
| 387 | - height: t.height, | ||
| 388 | - order: if t.bgr { RgbOrder::Bgra } else { RgbOrder::Rgba }, | ||
| 389 | - }) | ||
| 390 | - } | ||
| 391 | -} | ||
| 392 | - | ||
| 393 | -/// Whether [`HwEncoder::encode_d3d11`] can import textures of `order` on this machine's Vulkan device. | ||
| 394 | -#[cfg(windows)] | ||
| 395 | -pub fn d3d11_supported(order: RgbOrder) -> bool { | ||
| 396 | - vk_gpu().is_some_and(|gpu| ec_vk::d3d11_importable(&gpu, order == RgbOrder::Bgra)) | ||
| 397 | -} | ||
| 398 | - | ||
| 399 | -/// One picture for [`HwEncoder::submit`]. | ||
| 400 | -#[derive(Debug, Clone, Copy)] | ||
| 401 | -pub enum EncodeInput<'a> { | ||
| 402 | - /// 8-bit I420. | ||
| 403 | - I420(&'a I420), | ||
| 404 | - /// 10-bit I420 of a 10-bit encoder (H.265 and AV1). | ||
| 405 | - I420_16(&'a I420_16), | ||
| 406 | - /// Packed RGB, box-downscaled to the encoder size. | ||
| 407 | - Rgb(&'a RgbFrame<'a>), | ||
| 408 | - /// DMA-BUF of packed RGB, Vulkan only. | ||
| 409 | - #[cfg(target_os = "linux")] | ||
| 410 | - DmaBuf(&'a DmaBufFrame<'a>), | ||
| 411 | - /// DMA-BUF of NV12 or P010 at the encoder size, Vulkan only. | ||
| 412 | - #[cfg(target_os = "linux")] | ||
| 413 | - DmaBufYuv(&'a DmaBufYuvFrame<'a>), | ||
| 414 | - /// Shared D3D11 texture of packed RGB, Vulkan only. | ||
| 415 | - #[cfg(windows)] | ||
| 416 | - D3d11(&'a D3d11Frame<'a>), | ||
| 417 | -} | ||
| 418 | - | ||
| 419 | -#[cfg(target_os = "linux")] | ||
| 420 | -fn rgb_to_i420(frame: &RgbFrame, (w, h): (usize, usize)) -> Result<I420> { | ||
| 421 | - let (sw, sh, stride) = ( | ||
| 422 | - frame.width as usize, | ||
| 423 | - frame.height as usize, | ||
| 424 | - frame.stride as usize, | ||
| 425 | - ); | ||
| 426 | - if sw % 2 != 0 | ||
| 427 | - || sh % 2 != 0 | ||
| 428 | - || stride % 4 != 0 | ||
| 429 | - || stride < sw * 4 | ||
| 430 | - || frame.data.len() < stride * sh | ||
| 431 | - { | ||
| 432 | - return Err(Error::config("RGB frame size or stride")); | ||
| 433 | - } | ||
| 434 | - if sw < w || sh < h { | ||
| 435 | - return Err(Error::config("RGB source smaller than encoder")); | ||
| 436 | - } | ||
| 437 | - let packed: Vec<u8> = frame | ||
| 438 | - .data | ||
| 439 | - .chunks(stride) | ||
| 440 | - .take(sh) | ||
| 441 | - .flat_map(|row| &row[..sw * 4]) | ||
| 442 | - .copied() | ||
| 443 | - .collect(); | ||
| 444 | - let packed = if (sw, sh) == (w, h) { | ||
| 445 | - packed | ||
| 446 | - } else { | ||
| 447 | - let mut scaled = vec![0; w * h * 4]; | ||
| 448 | - ec_dsp::rgb::rgb_box_downscale(&packed, sw, sh, sw * 4, &mut scaled, w, h); | ||
| 449 | - scaled | ||
| 450 | - }; | ||
| 451 | - let chroma = (w / 2) * (h / 2); | ||
| 452 | - let mut out = I420 { | ||
| 453 | - y: vec![0; w * h], | ||
| 454 | - u: vec![0; chroma], | ||
| 455 | - v: vec![0; chroma], | ||
| 456 | - width: w as u32, | ||
| 457 | - height: h as u32, | ||
| 458 | - }; | ||
| 459 | - match frame.order { | ||
| 460 | - RgbOrder::Rgba => { | ||
| 461 | - ec_dsp::rgb::rgba_to_i420_709(&packed, w, h, &mut out.y, &mut out.u, &mut out.v) | ||
| 462 | - } | ||
| 463 | - RgbOrder::Bgra => { | ||
| 464 | - ec_dsp::rgb::bgra_to_i420_709(&packed, w, h, &mut out.y, &mut out.u, &mut out.v) | ||
| 465 | - } | ||
| 466 | - } | ||
| 467 | - Ok(out) | ||
| 468 | -} | ||
| 469 | - | ||
| 470 | -/// The Vulkan encoder for one codec. | ||
| 471 | -enum VkEncoder { | ||
| 472 | - H264(ec_vk::H264Encoder), | ||
| 473 | - H265(ec_vk::H265Encoder), | ||
| 474 | - Av1(ec_vk::Av1Encoder), | ||
| 475 | -} | ||
| 476 | - | ||
| 477 | -const ID_HISTORY: usize = 512; | ||
| 478 | - | ||
| 479 | -impl VkEncoder { | ||
| 480 | - fn submit( | ||
| 481 | - &mut self, | ||
| 482 | - input: EncodeInput, | ||
| 483 | - force_keyframe: bool, | ||
| 484 | - ) -> std::result::Result<Option<ec_vk::CodedFrame>, ec_vk::Error> { | ||
| 485 | - match input { | ||
| 486 | - EncodeInput::I420(frame) => { | ||
| 487 | - let (y, u, v) = (&frame.y, &frame.u, &frame.v); | ||
| 488 | - match self { | ||
| 489 | - VkEncoder::H264(e) => e.submit(y, u, v, force_keyframe), | ||
| 490 | - VkEncoder::H265(e) => e.submit(y, u, v, force_keyframe), | ||
| 491 | - VkEncoder::Av1(e) => e.submit(y, u, v, force_keyframe), | ||
| 492 | - } | ||
| 493 | - } | ||
| 494 | - EncodeInput::I420_16(frame) => { | ||
| 495 | - let (y, u, v) = (&frame.y, &frame.u, &frame.v); | ||
| 496 | - match self { | ||
| 497 | - VkEncoder::H264(_) => Err(ec_vk::Error::Unsupported("10-bit H.264 encode".into())), | ||
| 498 | - VkEncoder::H265(e) => e.submit_16(y, u, v, force_keyframe), | ||
| 499 | - VkEncoder::Av1(e) => e.submit_16(y, u, v, force_keyframe), | ||
| 500 | - } | ||
| 501 | - } | ||
| 502 | - EncodeInput::Rgb(frame) => { | ||
| 503 | - let bgr = frame.order == RgbOrder::Bgra; | ||
| 504 | - let (data, sw, sh, stride) = (frame.data, frame.width, frame.height, frame.stride); | ||
| 505 | - match self { | ||
| 506 | - VkEncoder::H264(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), | ||
| 507 | - VkEncoder::H265(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), | ||
| 508 | - VkEncoder::Av1(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), | ||
| 509 | - } | ||
| 510 | - } | ||
| 511 | - #[cfg(target_os = "linux")] | ||
| 512 | - EncodeInput::DmaBuf(frame) => { | ||
| 513 | - let planes = [DmaBufPlane { | ||
| 514 | - fd: 0, | ||
| 515 | - offset: frame.offset, | ||
| 516 | - pitch: frame.stride, | ||
| 517 | - }]; | ||
| 518 | - let src = DmaBuf { | ||
| 519 | - fds: std::slice::from_ref(&frame.fd), | ||
| 520 | - planes: &planes, | ||
| 521 | - width: frame.width, | ||
| 522 | - height: frame.height, | ||
| 523 | - modifier: frame.modifier, | ||
| 524 | - format: if frame.order == RgbOrder::Bgra { | ||
| 525 | - DmaBufFormat::Bgrx | ||
| 526 | - } else { | ||
| 527 | - DmaBufFormat::Rgbx | ||
| 528 | - }, | ||
| 529 | - }; | ||
| 530 | - self.submit_dma(&src, force_keyframe) | ||
| 531 | - } | ||
| 532 | - #[cfg(target_os = "linux")] | ||
| 533 | - EncodeInput::DmaBufYuv(frame) => { | ||
| 534 | - let src = DmaBuf { | ||
| 535 | - fds: frame.fds, | ||
| 536 | - planes: &frame.planes, | ||
| 537 | - width: frame.width, | ||
| 538 | - height: frame.height, | ||
| 539 | - modifier: frame.modifier, | ||
| 540 | - format: frame.format, | ||
| 541 | - }; | ||
| 542 | - self.submit_dma(&src, force_keyframe) | ||
| 543 | - } | ||
| 544 | - #[cfg(windows)] | ||
| 545 | - EncodeInput::D3d11(frame) => { | ||
| 546 | - let src = frame.texture(); | ||
| 547 | - match self { | ||
| 548 | - VkEncoder::H264(e) => e.submit_d3d11(&src, force_keyframe), | ||
| 549 | - VkEncoder::H265(e) => e.submit_d3d11(&src, force_keyframe), | ||
| 550 | - VkEncoder::Av1(e) => e.submit_d3d11(&src, force_keyframe), | ||
| 551 | - } | ||
| 552 | - } | ||
| 553 | - } | ||
| 554 | - } | ||
| 555 | - | ||
| 556 | - #[cfg(target_os = "linux")] | ||
| 557 | - fn submit_dma( | ||
| 558 | - &mut self, | ||
| 559 | - src: &DmaBuf, | ||
| 560 | - force_keyframe: bool, | ||
| 561 | - ) -> std::result::Result<Option<ec_vk::CodedFrame>, ec_vk::Error> { | ||
| 562 | - match self { | ||
| 563 | - VkEncoder::H264(e) => e.submit_dmabuf(src, force_keyframe), | ||
| 564 | - VkEncoder::H265(e) => e.submit_dmabuf(src, force_keyframe), | ||
| 565 | - VkEncoder::Av1(e) => e.submit_dmabuf(src, force_keyframe), | ||
| 566 | - } | ||
| 567 | - } | ||
| 568 | - | ||
| 569 | - fn flush(&mut self) -> std::result::Result<Vec<ec_vk::CodedFrame>, ec_vk::Error> { | ||
| 570 | - match self { | ||
| 571 | - VkEncoder::H264(e) => e.flush(), | ||
| 572 | - VkEncoder::H265(e) => e.flush(), | ||
| 573 | - VkEncoder::Av1(e) => e.flush(), | ||
| 574 | - } | ||
| 575 | - } | ||
| 576 | - | ||
| 577 | - fn encode( | ||
| 578 | - &mut self, | ||
| 579 | - frame: &I420, | ||
| 580 | - force_keyframe: bool, | ||
| 581 | - ) -> std::result::Result<ec_vk::CodedFrame, ec_vk::Error> { | ||
| 582 | - let (y, u, v) = (&frame.y, &frame.u, &frame.v); | ||
| 583 | - match self { | ||
| 584 | - VkEncoder::H264(e) => e.encode(y, u, v, force_keyframe), | ||
| 585 | - VkEncoder::H265(e) => e.encode(y, u, v, force_keyframe), | ||
| 586 | - VkEncoder::Av1(e) => e.encode(y, u, v, force_keyframe), | ||
| 587 | - } | ||
| 588 | - } | ||
| 589 | - | ||
| 590 | - fn encode_16( | ||
| 591 | - &mut self, | ||
| 592 | - frame: &I420_16, | ||
| 593 | - force_keyframe: bool, | ||
| 594 | - ) -> std::result::Result<ec_vk::CodedFrame, ec_vk::Error> { | ||
| 595 | - let (y, u, v) = (&frame.y, &frame.u, &frame.v); | ||
| 596 | - match self { | ||
| 597 | - VkEncoder::H264(_) => Err(ec_vk::Error::Unsupported("10-bit H.264 encode".into())), | ||
| 598 | - VkEncoder::H265(e) => e.encode_16(y, u, v, force_keyframe), | ||
| 599 | - VkEncoder::Av1(e) => e.encode_16(y, u, v, force_keyframe), | ||
| 600 | - } | ||
| 601 | - } | ||
| 602 | - | ||
| 603 | - fn set_rate( | ||
| 604 | - &mut self, | ||
| 605 | - rate: ec_vk::RateControl, | ||
| 606 | - fps: (u32, u32), | ||
| 607 | - ) -> std::result::Result<(), ec_vk::Error> { | ||
| 608 | - match self { | ||
| 609 | - VkEncoder::H264(e) => e.set_rate(rate, fps), | ||
| 610 | - VkEncoder::H265(e) => e.set_rate(rate, fps), | ||
| 611 | - VkEncoder::Av1(e) => e.set_rate(rate, fps), | ||
| 612 | - } | ||
| 613 | - } | ||
| 614 | - | ||
| 615 | - fn encode_rgb( | ||
| 616 | - &mut self, | ||
| 617 | - frame: &RgbFrame, | ||
| 618 | - force_keyframe: bool, | ||
| 619 | - ) -> std::result::Result<ec_vk::CodedFrame, ec_vk::Error> { | ||
| 620 | - let bgr = frame.order == RgbOrder::Bgra; | ||
| 621 | - let (data, sw, sh, stride) = (frame.data, frame.width, frame.height, frame.stride); | ||
| 622 | - match self { | ||
| 623 | - VkEncoder::H264(e) => e.encode_rgb(data, sw, sh, stride, bgr, force_keyframe), | ||
| 624 | - VkEncoder::H265(e) => e.encode_rgb(data, sw, sh, stride, bgr, force_keyframe), | ||
| 625 | - VkEncoder::Av1(e) => e.encode_rgb(data, sw, sh, stride, bgr, force_keyframe), | ||
| 626 | - } | ||
| 627 | - } | ||
| 628 | - | ||
| 629 | - #[cfg(target_os = "linux")] | ||
| 630 | - fn encode_dmabuf( | ||
| 631 | - &mut self, | ||
| 632 | - src: &DmaBuf, | ||
| 633 | - force_keyframe: bool, | ||
| 634 | - ) -> std::result::Result<ec_vk::CodedFrame, ec_vk::Error> { | ||
| 635 | - match self { | ||
| 636 | - VkEncoder::H264(e) => e.encode_dmabuf(src, force_keyframe), | ||
| 637 | - VkEncoder::H265(e) => e.encode_dmabuf(src, force_keyframe), | ||
| 638 | - VkEncoder::Av1(e) => e.encode_dmabuf(src, force_keyframe), | ||
| 639 | - } | ||
| 640 | - } | ||
| 641 | -} | ||
| 642 | - | ||
| 643 | -enum EncInner { | ||
| 644 | - Vk(VkEncoder), | ||
| 645 | - #[cfg(target_os = "linux")] | ||
| 646 | - Va(VaEncoder), | ||
| 647 | -} | ||
| 648 | - | ||
| 649 | -/// A hardware encoder on whichever backend opened. | ||
| 650 | -pub struct HwEncoder { | ||
| 651 | - inner: EncInner, | ||
| 652 | - born_epoch: u64, | ||
| 653 | - config: EncoderConfig, | ||
| 654 | - #[cfg_attr(not(target_os = "linux"), allow(dead_code))] | ||
| 655 | - size: (usize, usize), | ||
| 656 | - pending: VecDeque<i64>, | ||
| 657 | - ids: VecDeque<(i64, u64)>, | ||
| 658 | - keyframe_next: bool, | ||
| 659 | - tunings: Tunings, | ||
| 660 | - rc: RateFeedback, | ||
| 661 | -} | ||
| 662 | - | ||
| 663 | -impl HwEncoder { | ||
| 664 | - /// Open an encoder. `prefer` = `None` tries Vulkan, then VA-API. | ||
| 665 | - pub fn open(config: EncoderConfig, prefer: Option<Backend>) -> Result<HwEncoder> { | ||
| 666 | - let order = match prefer { | ||
| 667 | - Some(backend) => vec![backend], | ||
| 668 | - None => vec![Backend::Vk, Backend::Va], | ||
| 669 | - }; | ||
| 670 | - let mut reasons = Vec::new(); | ||
| 671 | - for backend in order { | ||
| 672 | - let born_epoch = crate::reset::gpu_reset_epoch(); | ||
| 673 | - match open_backend(backend, config) { | ||
| 674 | - Ok(inner) => { | ||
| 675 | - let size = (config.width as usize, config.height as usize); | ||
| 676 | - return Ok(HwEncoder { | ||
| 677 | - inner, | ||
| 678 | - born_epoch, | ||
| 679 | - config, | ||
| 680 | - size, | ||
| 681 | - pending: VecDeque::new(), | ||
| 682 | - ids: VecDeque::new(), | ||
| 683 | - keyframe_next: false, | ||
| 684 | - tunings: Tunings { | ||
| 685 | - bitrate: config.bitrate, | ||
| 686 | - framerate: config.framerate, | ||
| 687 | - }, | ||
| 688 | - rc: RateFeedback::default(), | ||
| 689 | - }); | ||
| 690 | - } | ||
| 691 | - Err(e) => reasons.push(format!("{backend:?}: {e}")), | ||
| 692 | - } | ||
| 693 | - } | ||
| 694 | - Err(Error::unsupported( | ||
| 695 | - format!("{:?} hardware encode", config.codec), | ||
| 696 | - reasons.join("; "), | ||
| 697 | - )) | ||
| 698 | - } | ||
| 699 | - | ||
| 700 | - /// The backend this encoder runs on. | ||
| 701 | - pub fn backend(&self) -> Backend { | ||
| 702 | - match self.inner { | ||
| 703 | - EncInner::Vk(_) => Backend::Vk, | ||
| 704 | - #[cfg(target_os = "linux")] | ||
| 705 | - EncInner::Va(_) => Backend::Va, | ||
| 706 | - } | ||
| 707 | - } | ||
| 708 | - | ||
| 709 | - /// Change bitrate or frame rate from the next frame; a constant-QP encoder keeps its QP. | ||
| 710 | - pub fn tune(&mut self, tunings: Tunings) -> Result<()> { | ||
| 711 | - match &mut self.inner { | ||
| 712 | - EncInner::Vk(enc) => { | ||
| 713 | - vk_session_alive(self.born_epoch)?; | ||
| 714 | - self.tunings = tunings; | ||
| 715 | - self.rc = RateFeedback::default(); | ||
| 716 | - let rate = vk_rate(&self.config, tunings.bitrate); | ||
| 717 | - enc.set_rate(rate, tunings.framerate)?; | ||
| 718 | - } | ||
| 719 | - #[cfg(target_os = "linux")] | ||
| 720 | - EncInner::Va(enc) => enc.tune(tunings), | ||
| 721 | - } | ||
| 722 | - Ok(()) | ||
| 723 | - } | ||
| 724 | - | ||
| 725 | - /// Submit one picture without waiting; the oldest coded picture comes back once two are in flight. Call [`HwEncoder::flush`] at the end. | ||
| 726 | - pub fn submit(&mut self, input: EncodeInput, meta: FrameMetadata) -> Result<Option<CodedFrame>> { | ||
| 727 | - let meta = self.with_recovery(meta); | ||
| 728 | - match &mut self.inner { | ||
| 729 | - EncInner::Vk(enc) => { | ||
| 730 | - vk_session_alive(self.born_epoch)?; | ||
| 731 | - let coded = enc.submit(input, meta.force_keyframe)?; | ||
| 732 | - self.pending.push_back(meta.timestamp); | ||
| 733 | - let Some(coded) = coded else { | ||
| 734 | - return Ok(None); | ||
| 735 | - }; | ||
| 736 | - let timestamp = self.pending.pop_front().unwrap_or_default(); | ||
| 737 | - self.steer(coded.data.len())?; | ||
| 738 | - Ok(Some(self.vk_frame(coded, timestamp))) | ||
| 739 | - } | ||
| 740 | - #[cfg(target_os = "linux")] | ||
| 741 | - EncInner::Va(enc) => match input { | ||
| 742 | - EncodeInput::I420(frame) => enc.submit(frame, meta), | ||
| 743 | - EncodeInput::I420_16(frame) => enc.submit_16(frame, meta), | ||
| 744 | - EncodeInput::Rgb(frame) => enc.submit(&rgb_to_i420(frame, self.size)?, meta), | ||
| 745 | - EncodeInput::DmaBuf(_) | EncodeInput::DmaBufYuv(_) => Err(Error::unsupported( | ||
| 746 | - "DMA-BUF encode", | ||
| 747 | - "the VA-API backend has no DMA-BUF input here", | ||
| 748 | - )), | ||
| 749 | - }, | ||
| 750 | - } | ||
| 751 | - } | ||
| 752 | - | ||
| 753 | - /// Wait for every submitted picture and return them, oldest first. | ||
| 754 | - pub fn flush(&mut self) -> Result<Vec<CodedFrame>> { | ||
| 755 | - match &mut self.inner { | ||
| 756 | - EncInner::Vk(enc) => { | ||
| 757 | - vk_session_alive(self.born_epoch)?; | ||
| 758 | - let frames = enc.flush()?; | ||
| 759 | - let out: Vec<CodedFrame> = frames | ||
| 760 | - .into_iter() | ||
| 761 | - .map(|coded| { | ||
| 762 | - let timestamp = self.pending.pop_front().unwrap_or_default(); | ||
| 763 | - self.vk_frame(coded, timestamp) | ||
| 764 | - }) | ||
| 765 | - .collect(); | ||
| 766 | - let mut steered = Ok(()); | ||
| 767 | - for frame in &out { | ||
| 768 | - steered = steered.and(self.steer(frame.data.len())); | ||
| 769 | - } | ||
| 770 | - steered?; | ||
| 771 | - Ok(out) | ||
| 772 | - } | ||
| 773 | - #[cfg(target_os = "linux")] | ||
| 774 | - EncInner::Va(enc) => enc.flush(), | ||
| 775 | - } | ||
| 776 | - } | ||
| 777 | - | ||
| 778 | - fn idle(&self) -> Result<()> { | ||
| 779 | - if self.pending.is_empty() { | ||
| 780 | - Ok(()) | ||
| 781 | - } else { | ||
| 782 | - Err(Error::config("pipelined frames pending; call flush first")) | ||
| 783 | - } | ||
| 784 | - } | ||
| 785 | - | ||
| 786 | - /// 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. | ||
| 787 | - pub fn ack(&mut self, timestamp: i64) { | ||
| 788 | - let Some(&(_, id)) = self.ids.iter().rev().find(|(ts, _)| *ts <= timestamp) else { | ||
| 789 | - return; | ||
| 790 | - }; | ||
| 791 | - match &mut self.inner { | ||
| 792 | - EncInner::Vk(VkEncoder::Av1(enc)) => enc.ack(id), | ||
| 793 | - EncInner::Vk(VkEncoder::H265(enc)) => enc.ack(id), | ||
| 794 | - EncInner::Vk(VkEncoder::H264(enc)) => enc.ack(id), | ||
| 795 | - #[cfg(target_os = "linux")] | ||
| 796 | - EncInner::Va(_) => {} | ||
| 797 | - } | ||
| 798 | - } | ||
| 799 | - | ||
| 800 | - /// 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. | ||
| 801 | - pub fn recover(&mut self) { | ||
| 802 | - match &mut self.inner { | ||
| 803 | - EncInner::Vk(VkEncoder::Av1(enc)) => enc.recover(), | ||
| 804 | - EncInner::Vk(VkEncoder::H265(enc)) => enc.recover(), | ||
| 805 | - EncInner::Vk(VkEncoder::H264(enc)) => enc.recover(), | ||
| 806 | - #[cfg(target_os = "linux")] | ||
| 807 | - EncInner::Va(_) => self.keyframe_next = true, | ||
| 808 | - } | ||
| 809 | - } | ||
| 810 | - | ||
| 811 | - fn with_recovery(&mut self, meta: FrameMetadata) -> FrameMetadata { | ||
| 812 | - FrameMetadata { | ||
| 813 | - force_keyframe: meta.force_keyframe || std::mem::take(&mut self.keyframe_next), | ||
| 814 | - ..meta | ||
| 815 | - } | ||
| 816 | - } | ||
| 817 | - | ||
| 818 | - fn vk_frame(&mut self, coded: ec_vk::CodedFrame, timestamp: i64) -> CodedFrame { | ||
| 819 | - if self.ids.len() == ID_HISTORY { | ||
| 820 | - self.ids.pop_front(); | ||
| 821 | - } | ||
| 822 | - self.ids.push_back((timestamp, coded.id)); | ||
| 823 | - CodedFrame { | ||
| 824 | - data: coded.data, | ||
| 825 | - timestamp, | ||
| 826 | - is_keyframe: coded.keyframe, | ||
| 827 | - recovery: coded.recovery, | ||
| 828 | - } | ||
| 829 | - } | ||
| 830 | - | ||
| 831 | - fn steer(&mut self, bytes: usize) -> Result<()> { | ||
| 832 | - if !self.rc.track(bytes, self.config.rate_control, self.tunings) { | ||
| 833 | - return Ok(()); | ||
| 834 | - } | ||
| 835 | - let rate = vk_rate(&self.config, self.rc.steered_bitrate(self.tunings.bitrate)); | ||
| 836 | - match &mut self.inner { | ||
| 837 | - EncInner::Vk(enc) => enc.set_rate(rate, self.tunings.framerate)?, | ||
| 838 | - #[cfg(target_os = "linux")] | ||
| 839 | - EncInner::Va(_) => {} | ||
| 840 | - } | ||
| 841 | - Ok(()) | ||
| 842 | - } | ||
| 843 | - | ||
| 844 | - /// Encode one frame; `meta.force_keyframe` starts a new GOP. | ||
| 845 | - pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> { | ||
| 846 | - let meta = self.with_recovery(meta); | ||
| 847 | - self.idle()?; | ||
| 848 | - match &mut self.inner { | ||
| 849 | - EncInner::Vk(enc) => { | ||
| 850 | - vk_session_alive(self.born_epoch)?; | ||
| 851 | - let coded = enc.encode(frame, meta.force_keyframe)?; | ||
| 852 | - self.steer(coded.data.len())?; | ||
| 853 | - Ok(self.vk_frame(coded, meta.timestamp)) | ||
| 854 | - } | ||
| 855 | - #[cfg(target_os = "linux")] | ||
| 856 | - EncInner::Va(enc) => enc.encode(frame, meta), | ||
| 857 | - } | ||
| 858 | - } | ||
| 859 | - | ||
| 860 | - /// Encode one 10-bit frame of a 10-bit encoder (H.265 and AV1), the [`HwEncoder::encode`] of a 10-bit encoder. | ||
| 861 | - pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result<CodedFrame> { | ||
| 862 | - let meta = self.with_recovery(meta); | ||
| 863 | - self.idle()?; | ||
| 864 | - match &mut self.inner { | ||
| 865 | - EncInner::Vk(enc) => { | ||
| 866 | - vk_session_alive(self.born_epoch)?; | ||
| 867 | - let coded = enc.encode_16(frame, meta.force_keyframe)?; | ||
| 868 | - self.steer(coded.data.len())?; | ||
| 869 | - Ok(self.vk_frame(coded, meta.timestamp)) | ||
| 870 | - } | ||
| 871 | - #[cfg(target_os = "linux")] | ||
| 872 | - EncInner::Va(enc) => enc.encode_16(frame, meta), | ||
| 873 | - } | ||
| 874 | - } | ||
| 875 | - | ||
| 876 | - /// 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. | ||
| 877 | - pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result<CodedFrame> { | ||
| 878 | - let meta = self.with_recovery(meta); | ||
| 879 | - self.idle()?; | ||
| 880 | - match &mut self.inner { | ||
| 881 | - EncInner::Vk(enc) => { | ||
| 882 | - vk_session_alive(self.born_epoch)?; | ||
| 883 | - let coded = enc.encode_rgb(frame, meta.force_keyframe)?; | ||
| 884 | - self.steer(coded.data.len())?; | ||
| 885 | - Ok(self.vk_frame(coded, meta.timestamp)) | ||
| 886 | - } | ||
| 887 | - #[cfg(target_os = "linux")] | ||
| 888 | - EncInner::Va(enc) => enc.encode(&rgb_to_i420(frame, self.size)?, meta), | ||
| 889 | - } | ||
| 890 | - } | ||
| 891 | - | ||
| 892 | - /// Encode one DMA-BUF frame of the source size, box-downscaled to the encoder size. Vulkan only; VA-API has its own PRIME path. | ||
| 893 | - #[cfg(target_os = "linux")] | ||
| 894 | - pub fn encode_dmabuf( | ||
| 895 | - &mut self, | ||
| 896 | - frame: &DmaBufFrame, | ||
| 897 | - meta: FrameMetadata, | ||
| 898 | - ) -> Result<CodedFrame> { | ||
| 899 | - let planes = [DmaBufPlane { | ||
| 900 | - fd: 0, | ||
| 901 | - offset: frame.offset, | ||
| 902 | - pitch: frame.stride, | ||
| 903 | - }]; | ||
| 904 | - let src = DmaBuf { | ||
| 905 | - fds: std::slice::from_ref(&frame.fd), | ||
| 906 | - planes: &planes, | ||
| 907 | - width: frame.width, | ||
| 908 | - height: frame.height, | ||
| 909 | - modifier: frame.modifier, | ||
| 910 | - format: if frame.order == RgbOrder::Bgra { | ||
| 911 | - DmaBufFormat::Bgrx | ||
| 912 | - } else { | ||
| 913 | - DmaBufFormat::Rgbx | ||
| 914 | - }, | ||
| 915 | - }; | ||
| 916 | - self.encode_dma(&src, meta) | ||
| 917 | - } | ||
| 918 | - | ||
| 919 | - /// Encode one NV12 or P010 DMA-BUF frame of the encoder size. Vulkan only; VA-API has its own PRIME path. | ||
| 920 | - #[cfg(target_os = "linux")] | ||
| 921 | - pub fn encode_dmabuf_yuv( | ||
| 922 | - &mut self, | ||
| 923 | - frame: &DmaBufYuvFrame, | ||
| 924 | - meta: FrameMetadata, | ||
| 925 | - ) -> Result<CodedFrame> { | ||
| 926 | - let src = DmaBuf { | ||
| 927 | - fds: frame.fds, | ||
| 928 | - planes: &frame.planes, | ||
| 929 | - width: frame.width, | ||
| 930 | - height: frame.height, | ||
| 931 | - modifier: frame.modifier, | ||
| 932 | - format: frame.format, | ||
| 933 | - }; | ||
| 934 | - self.encode_dma(&src, meta) | ||
| 935 | - } | ||
| 936 | - | ||
| 937 | - /// Encode one shared D3D11 texture of the source size, downscaled to the encoder size on the GPU. | ||
| 938 | - #[cfg(windows)] | ||
| 939 | - pub fn encode_d3d11(&mut self, frame: &D3d11Frame, meta: FrameMetadata) -> Result<CodedFrame> { | ||
| 940 | - let meta = self.with_recovery(meta); | ||
| 941 | - self.idle()?; | ||
| 942 | - let EncInner::Vk(enc) = &mut self.inner; | ||
| 943 | - vk_session_alive(self.born_epoch)?; | ||
| 944 | - let src = frame.texture(); | ||
| 945 | - let coded = match enc { | ||
| 946 | - VkEncoder::H264(e) => e.encode_d3d11(&src, meta.force_keyframe), | ||
| 947 | - VkEncoder::H265(e) => e.encode_d3d11(&src, meta.force_keyframe), | ||
| 948 | - VkEncoder::Av1(e) => e.encode_d3d11(&src, meta.force_keyframe), | ||
| 949 | - }?; | ||
| 950 | - self.steer(coded.data.len())?; | ||
| 951 | - Ok(self.vk_frame(coded, meta.timestamp)) | ||
| 952 | - } | ||
| 953 | - | ||
| 954 | - #[cfg(target_os = "linux")] | ||
| 955 | - fn encode_dma(&mut self, src: &DmaBuf, meta: FrameMetadata) -> Result<CodedFrame> { | ||
| 956 | - let meta = self.with_recovery(meta); | ||
| 957 | - self.idle()?; | ||
| 958 | - match &mut self.inner { | ||
| 959 | - EncInner::Vk(enc) => { | ||
| 960 | - vk_session_alive(self.born_epoch)?; | ||
| 961 | - let coded = enc.encode_dmabuf(src, meta.force_keyframe)?; | ||
| 962 | - self.steer(coded.data.len())?; | ||
| 963 | - Ok(self.vk_frame(coded, meta.timestamp)) | ||
| 964 | - } | ||
| 965 | - EncInner::Va(_) => Err(Error::unsupported( | ||
| 966 | - "DMA-BUF encode", | ||
| 967 | - "the VA-API backend has no DMA-BUF input here", | ||
| 968 | - )), | ||
| 969 | - } | ||
| 970 | - } | ||
| 971 | -} | ||
| 972 | - | ||
| 973 | -fn open_backend(backend: Backend, config: EncoderConfig) -> Result<EncInner> { | ||
| 974 | - match backend { | ||
| 975 | - Backend::Vk => open_vk(config).map(EncInner::Vk), | ||
| 976 | - Backend::Va => open_va(config), | ||
| 977 | - } | ||
| 978 | -} | ||
| 979 | - | ||
| 980 | -fn open_vk(config: EncoderConfig) -> Result<VkEncoder> { | ||
| 981 | - vk_grace()?; | ||
| 982 | - if config.bit_depth == 10 && config.codec == EncCodec::H264 { | ||
| 983 | - return Err(Error::unsupported( | ||
| 984 | - "10-bit H.264 Vulkan Video encode", | ||
| 985 | - "the driver offers no High 10 H.264 encode", | ||
| 986 | - )); | ||
| 987 | - } | ||
| 988 | - if config.bit_depth != 8 && config.bit_depth != 10 { | ||
| 989 | - return Err(Error::config(format!( | ||
| 990 | - "encoder bit depth {}: Vulkan encodes 8-bit, or 10-bit H.265 and AV1", | ||
| 991 | - config.bit_depth | ||
| 992 | - ))); | ||
| 993 | - } | ||
| 994 | - let gpu = vk_gpu() | ||
| 995 | - .ok_or_else(|| Error::unsupported("Vulkan Video encode", "no Vulkan Video device"))?; | ||
| 996 | - let rate = vk_rate(&config, config.bitrate); | ||
| 997 | - let level = match config.codec { | ||
| 998 | - EncCodec::H264 => crate::level::h264(&config), | ||
| 999 | - EncCodec::H265 => crate::level::hevc(&config), | ||
| 1000 | - EncCodec::Av1 => crate::level::av1(&config), | ||
| 1001 | - }; | ||
| 1002 | - let (width, height, fps, gop_size) = ( | ||
| 1003 | - config.width, | ||
| 1004 | - config.height, | ||
| 1005 | - config.framerate, | ||
| 1006 | - config.gop_size, | ||
| 1007 | - ); | ||
| 1008 | - let colour = config.colour.map(|c| ec_vk::Colour { | ||
| 1009 | - primaries: c.primaries, | ||
| 1010 | - transfer: c.transfer, | ||
| 1011 | - matrix: c.matrix, | ||
| 1012 | - full_range: c.full_range, | ||
| 1013 | - }); | ||
| 1014 | - Ok(match config.codec { | ||
| 1015 | - EncCodec::H264 => VkEncoder::H264(ec_vk::H264Encoder::new( | ||
| 1016 | - &gpu, | ||
| 1017 | - ec_vk::H264EncoderConfig { | ||
| 1018 | - width, | ||
| 1019 | - height, | ||
| 1020 | - fps, | ||
| 1021 | - gop_size, | ||
| 1022 | - rate, | ||
| 1023 | - profile: vk_h264_profile(config.h264_profile), | ||
| 1024 | - level, | ||
| 1025 | - colour, | ||
| 1026 | - quality: config.quality, | ||
| 1027 | - }, | ||
| 1028 | - )?), | ||
| 1029 | - EncCodec::H265 => VkEncoder::H265(ec_vk::H265Encoder::new( | ||
| 1030 | - &gpu, | ||
| 1031 | - ec_vk::H265EncoderConfig { | ||
| 1032 | - width, | ||
| 1033 | - height, | ||
| 1034 | - fps, | ||
| 1035 | - gop_size, | ||
| 1036 | - rate, | ||
| 1037 | - bit_depth: config.bit_depth, | ||
| 1038 | - level, | ||
| 1039 | - colour, | ||
| 1040 | - quality: config.quality, | ||
| 1041 | - }, | ||
| 1042 | - )?), | ||
| 1043 | - EncCodec::Av1 => VkEncoder::Av1(ec_vk::Av1Encoder::new( | ||
| 1044 | - &gpu, | ||
| 1045 | - ec_vk::Av1EncoderConfig { | ||
| 1046 | - width, | ||
| 1047 | - height, | ||
| 1048 | - fps, | ||
| 1049 | - gop_size, | ||
| 1050 | - rate, | ||
| 1051 | - bit_depth: config.bit_depth, | ||
| 1052 | - level, | ||
| 1053 | - colour, | ||
| 1054 | - quality: config.quality, | ||
| 1055 | - }, | ||
| 1056 | - )?), | ||
| 1057 | - }) | ||
| 1058 | -} | ||
| 1059 | - | ||
| 1060 | -fn vk_h264_profile(profile: H264Profile) -> ec_vk::H264Profile { | ||
| 1061 | - match profile { | ||
| 1062 | - H264Profile::ConstrainedBaseline => ec_vk::H264Profile::ConstrainedBaseline, | ||
| 1063 | - H264Profile::Main => ec_vk::H264Profile::Main, | ||
| 1064 | - H264Profile::High => ec_vk::H264Profile::High, | ||
| 1065 | - } | ||
| 1066 | -} | ||
| 1067 | - | ||
| 1068 | -fn vk_rate(config: &EncoderConfig, bitrate: u32) -> ec_vk::RateControl { | ||
| 1069 | - match (config.rate_control, config.codec) { | ||
| 1070 | - (RateControlMode::ConstantQp { qp }, EncCodec::Av1) => ec_vk::RateControl::ConstantQp { | ||
| 1071 | - qp: (qp / 5).min(51) as u8, | ||
| 1072 | - }, | ||
| 1073 | - (RateControlMode::ConstantQp { qp }, _) => ec_vk::RateControl::ConstantQp { | ||
| 1074 | - qp: qp.min(51) as u8, | ||
| 1075 | - }, | ||
| 1076 | - (RateControlMode::ConstantBitrate, _) => ec_vk::RateControl::Cbr { | ||
| 1077 | - bitrate, | ||
| 1078 | - buffer_ms: hrd_buffer_ms(config), | ||
| 1079 | - }, | ||
| 1080 | - (RateControlMode::VariableBitrate, _) => ec_vk::RateControl::Vbr { | ||
| 1081 | - bitrate, | ||
| 1082 | - max_bitrate: bitrate.saturating_mul(3) / 2, | ||
| 1083 | - buffer_ms: hrd_buffer_ms(config), | ||
| 1084 | - min_qp: None, | ||
| 1085 | - }, | ||
| 1086 | - (RateControlMode::Qvbr { quality }, _) => ec_vk::RateControl::Vbr { | ||
| 1087 | - bitrate, | ||
| 1088 | - max_bitrate: bitrate, | ||
| 1089 | - buffer_ms: hrd_buffer_ms(config), | ||
| 1090 | - min_qp: Some(quality.min(51) as u8), | ||
| 1091 | - }, | ||
| 1092 | - } | ||
| 1093 | -} | ||
| 1094 | - | ||
| 1095 | -#[cfg(target_os = "linux")] | ||
| 1096 | -fn open_va(config: EncoderConfig) -> Result<EncInner> { | ||
| 1097 | - let display = ec_va::open()?; | ||
| 1098 | - Ok(EncInner::Va(VaEncoder::new(&display, config)?)) | ||
| 1099 | -} | ||
| 1100 | - | ||
| 1101 | -#[cfg(not(target_os = "linux"))] | ||
| 1102 | -fn open_va(config: EncoderConfig) -> Result<EncInner> { | ||
| 1103 | - Err(Error::unsupported( | ||
| 1104 | - format!("{:?} VA-API encode", config.codec), | ||
| 1105 | - "VA-API is Linux only", | ||
| 1106 | - )) | ||
| 1107 | -} | ||
| 1108 | - | ||
| 1109 | -enum VkDecoder { | ||
| 1110 | - H264(VkH264Decoder), | ||
| 1111 | - H265(VkH265Decoder), | ||
| 1112 | - Av1(VkAv1Decoder), | ||
| 1113 | - Vp9(VkVp9Decoder), | ||
| 1114 | -} | ||
| 1115 | - | ||
| 1116 | -impl VkDecoder { | ||
| 1117 | - fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { | ||
| 1118 | - match self { | ||
| 1119 | - VkDecoder::H264(d) => d.decode(data, timestamp), | ||
| 1120 | - VkDecoder::H265(d) => d.decode(data, timestamp), | ||
| 1121 | - VkDecoder::Av1(d) => d.decode(data, timestamp), | ||
| 1122 | - VkDecoder::Vp9(d) => d.decode(data, timestamp), | ||
| 1123 | - } | ||
| 1124 | - } | ||
| 1125 | - | ||
| 1126 | - fn next_frame(&mut self) -> Option<HwPicture> { | ||
| 1127 | - match self { | ||
| 1128 | - VkDecoder::H264(d) => d.next_frame(), | ||
| 1129 | - VkDecoder::H265(d) => d.next_frame(), | ||
| 1130 | - VkDecoder::Av1(d) => d.next_frame(), | ||
| 1131 | - VkDecoder::Vp9(d) => d.next_frame(), | ||
| 1132 | - } | ||
| 1133 | - } | ||
| 1134 | - | ||
| 1135 | - fn flush(&mut self) -> Result<()> { | ||
| 1136 | - match self { | ||
| 1137 | - VkDecoder::H264(d) => d.flush(), | ||
| 1138 | - VkDecoder::H265(d) => d.flush(), | ||
| 1139 | - VkDecoder::Av1(d) => d.flush(), | ||
| 1140 | - VkDecoder::Vp9(d) => d.flush(), | ||
| 1141 | - } | ||
| 1142 | - } | ||
| 1143 | - | ||
| 1144 | - fn reset(&mut self) { | ||
| 1145 | - match self { | ||
| 1146 | - VkDecoder::H264(d) => d.reset(), | ||
| 1147 | - VkDecoder::H265(d) => d.reset(), | ||
| 1148 | - VkDecoder::Av1(d) => d.reset(), | ||
| 1149 | - VkDecoder::Vp9(d) => d.reset(), | ||
| 1150 | - } | ||
| 1151 | - } | ||
| 1152 | -} | ||
| 1153 | - | ||
| 1154 | -enum DecInner { | ||
| 1155 | - Vk(VkDecoder), | ||
| 1156 | - #[cfg(target_os = "linux")] | ||
| 1157 | - Va(VaDecoder), | ||
| 1158 | -} | ||
| 1159 | - | ||
| 1160 | -const REPLAY_LIMIT: usize = 64; | ||
| 1161 | - | ||
| 1162 | -/// What a decoder hands out: 8-bit I420, or packed RGB converted on the way out. | ||
| 1163 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 1164 | -pub struct RgbOutput { | ||
| 1165 | - /// Byte order of each output pixel. | ||
| 1166 | - pub order: RgbOrder, | ||
| 1167 | - /// Scale pictures wider than this down to it, keeping the aspect ratio. | ||
| 1168 | - pub max_width: Option<u32>, | ||
| 1169 | - /// Scale pictures taller than this down to it, keeping the aspect ratio. | ||
| 1170 | - pub max_height: Option<u32>, | ||
| 1171 | -} | ||
| 1172 | - | ||
| 1173 | -impl RgbOutput { | ||
| 1174 | - pub(crate) fn bound(&self) -> (Option<u32>, Option<u32>) { | ||
| 1175 | - (self.max_width, self.max_height) | ||
| 1176 | - } | ||
| 1177 | -} | ||
| 1178 | - | ||
| 1179 | -/// A hardware decoder on whichever backend opened. | ||
| 1180 | -pub struct HwDecoder { | ||
| 1181 | - inner: DecInner, | ||
| 1182 | - born_epoch: u64, | ||
| 1183 | - #[cfg_attr(not(target_os = "linux"), allow(dead_code))] | ||
| 1184 | - codec: Codec, | ||
| 1185 | - rgb: Option<RgbOutput>, | ||
| 1186 | - #[cfg_attr(not(target_os = "linux"), allow(dead_code))] | ||
| 1187 | - replay: Option<Vec<(Vec<u8>, i64)>>, | ||
| 1188 | -} | ||
| 1189 | - | ||
| 1190 | -impl HwDecoder { | ||
| 1191 | - /// Open a decoder for `codec`. Every codec tries Vulkan Video first, then VA-API (Linux). | ||
| 1192 | - pub fn open(codec: Codec) -> Result<HwDecoder> { | ||
| 1193 | - HwDecoder::open_with(codec, None) | ||
| 1194 | - } | ||
| 1195 | - | ||
| 1196 | - /// 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. | ||
| 1197 | - pub fn open_rgb(codec: Codec, output: RgbOutput) -> Result<HwDecoder> { | ||
| 1198 | - HwDecoder::open_with(codec, Some(output)) | ||
| 1199 | - } | ||
| 1200 | - | ||
| 1201 | - fn open_with(codec: Codec, rgb: Option<RgbOutput>) -> Result<HwDecoder> { | ||
| 1202 | - let mut reasons = Vec::new(); | ||
| 1203 | - let born_epoch = crate::reset::gpu_reset_epoch(); | ||
| 1204 | - let vk = vk_grace().and_then(|()| match codec { | ||
| 1205 | - Codec::H264 => VkH264Decoder::new().map(VkDecoder::H264), | ||
| 1206 | - Codec::H265 => VkH265Decoder::new().map(VkDecoder::H265), | ||
| 1207 | - Codec::Av1 => VkAv1Decoder::new().map(VkDecoder::Av1), | ||
| 1208 | - Codec::Vp9 => VkVp9Decoder::new().map(VkDecoder::Vp9), | ||
| 1209 | - }); | ||
| 1210 | - match vk { | ||
| 1211 | - Ok(inner) => { | ||
| 1212 | - return Ok(HwDecoder { | ||
| 1213 | - inner: DecInner::Vk(inner), | ||
| 1214 | - born_epoch, | ||
| 1215 | - codec, | ||
| 1216 | - rgb, | ||
| 1217 | - replay: Some(Vec::new()), | ||
| 1218 | - }); | ||
| 1219 | - } | ||
| 1220 | - Err(e) => reasons.push(format!("Vk: {e}")), | ||
| 1221 | - } | ||
| 1222 | - #[cfg(target_os = "linux")] | ||
| 1223 | - { | ||
| 1224 | - match open_va_decoder(codec) { | ||
| 1225 | - Ok(inner) => { | ||
| 1226 | - return Ok(HwDecoder { | ||
| 1227 | - inner: DecInner::Va(inner), | ||
| 1228 | - born_epoch, | ||
| 1229 | - codec, | ||
| 1230 | - rgb, | ||
| 1231 | - replay: None, | ||
| 1232 | - }); | ||
| 1233 | - } | ||
| 1234 | - Err(e) => reasons.push(format!("Va: {e}")), | ||
| 1235 | - } | ||
| 1236 | - } | ||
| 1237 | - Err(Error::unsupported( | ||
| 1238 | - format!("{codec:?} hardware decode"), | ||
| 1239 | - reasons.join("; "), | ||
| 1240 | - )) | ||
| 1241 | - } | ||
| 1242 | - | ||
| 1243 | - /// The backend this decoder runs on. | ||
| 1244 | - pub fn backend(&self) -> Backend { | ||
| 1245 | - match self.inner { | ||
| 1246 | - DecInner::Vk(_) => Backend::Vk, | ||
| 1247 | - #[cfg(target_os = "linux")] | ||
| 1248 | - DecInner::Va(_) => Backend::Va, | ||
| 1249 | - } | ||
| 1250 | - } | ||
| 1251 | - | ||
| 1252 | - /// Feed one access unit. A stream Vulkan refuses (an unsupported profile) before its first | ||
| 1253 | - /// picture comes out moves to VA-API on Linux, replaying what was fed so far. | ||
| 1254 | - pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { | ||
| 1255 | - let born_epoch = self.born_epoch; | ||
| 1256 | - let result = match &mut self.inner { | ||
| 1257 | - DecInner::Vk(d) => vk_session_alive(born_epoch).and_then(|()| d.decode(data, timestamp)), | ||
| 1258 | - #[cfg(target_os = "linux")] | ||
| 1259 | - DecInner::Va(d) => d.decode(data, timestamp), | ||
| 1260 | - }; | ||
| 1261 | - if let Some(fed) = self.replay.as_mut() { | ||
| 1262 | - fed.push((data.to_vec(), timestamp)); | ||
| 1263 | - if fed.len() > REPLAY_LIMIT { | ||
| 1264 | - self.replay = None; | ||
| 1265 | - } | ||
| 1266 | - } | ||
| 1267 | - #[cfg(target_os = "linux")] | ||
| 1268 | - if let Err(Error::Unsupported { .. }) = result | ||
| 1269 | - && let Some(fed) = &self.replay | ||
| 1270 | - && let Ok(mut va) = open_va_decoder(self.codec) | ||
| 1271 | - && fed.iter().all(|(chunk, ts)| va.decode(chunk, *ts).is_ok()) | ||
| 1272 | - { | ||
| 1273 | - self.replay = None; | ||
| 1274 | - self.inner = DecInner::Va(va); | ||
| 1275 | - return Ok(()); | ||
| 1276 | - } | ||
| 1277 | - result | ||
| 1278 | - } | ||
| 1279 | - | ||
| 1280 | - /// The next picture in display order, held in its decode slot until dropped. Convert it with the `to_*` methods of [`HwPicture`]. | ||
| 1281 | - pub fn next_picture(&mut self) -> Result<Option<HwPicture>> { | ||
| 1282 | - self.pull() | ||
| 1283 | - } | ||
| 1284 | - | ||
| 1285 | - /// The next picture in display order, as 8-bit I420 with its timestamp. | ||
| 1286 | - pub fn next_frame(&mut self) -> Result<Option<(i64, I420)>> { | ||
| 1287 | - match self.pull()? { | ||
| 1288 | - None => Ok(None), | ||
| 1289 | - Some(picture) => Ok(Some((picture.timestamp, picture.to_i420()?))), | ||
| 1290 | - } | ||
| 1291 | - } | ||
| 1292 | - | ||
| 1293 | - /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder not opened with [`HwDecoder::open_rgb`]. | ||
| 1294 | - pub fn next_rgb(&mut self) -> Result<Option<(i64, RgbPicture)>> { | ||
| 1295 | - let mut dst = RgbPicture::default(); | ||
| 1296 | - Ok(self.next_rgb_into(&mut dst)?.map(|ts| (ts, dst))) | ||
| 1297 | - } | ||
| 1298 | - | ||
| 1299 | - /// Changes the RGB output of a decoder opened with [`HwDecoder::open_rgb`] from the next picture on. | ||
| 1300 | - pub fn set_rgb_output(&mut self, output: RgbOutput) -> Result<()> { | ||
| 1301 | - let rgb = self | ||
| 1302 | - .rgb | ||
| 1303 | - .as_mut() | ||
| 1304 | - .ok_or_else(|| Error::config("set_rgb_output on a decoder not opened with open_rgb"))?; | ||
| 1305 | - *rgb = output; | ||
| 1306 | - Ok(()) | ||
| 1307 | - } | ||
| 1308 | - | ||
| 1309 | - /// [`HwDecoder::next_rgb`] into `dst`, reusing its allocation across pictures; returns the timestamp. | ||
| 1310 | - pub fn next_rgb_into(&mut self, dst: &mut RgbPicture) -> Result<Option<i64>> { | ||
| 1311 | - let output = self | ||
| 1312 | - .rgb | ||
| 1313 | - .ok_or_else(|| Error::config("next_rgb on a decoder not opened with open_rgb"))?; | ||
| 1314 | - match self.pull()? { | ||
| 1315 | - None => Ok(None), | ||
| 1316 | - Some(picture) => { | ||
| 1317 | - picture.rgb_into(&output, dst)?; | ||
| 1318 | - Ok(Some(picture.timestamp)) | ||
| 1319 | - } | ||
| 1320 | - } | ||
| 1321 | - } | ||
| 1322 | - | ||
| 1323 | - fn pull(&mut self) -> Result<Option<HwPicture>> { | ||
| 1324 | - match &mut self.inner { | ||
| 1325 | - DecInner::Vk(d) => { | ||
| 1326 | - vk_session_alive(self.born_epoch)?; | ||
| 1327 | - let picture = d.next_frame(); | ||
| 1328 | - if picture.is_some() { | ||
| 1329 | - self.replay = None; | ||
| 1330 | - } | ||
| 1331 | - Ok(picture) | ||
| 1332 | - } | ||
| 1333 | - #[cfg(target_os = "linux")] | ||
| 1334 | - DecInner::Va(d) => Ok(d.next_frame().map(HwPicture::va)), | ||
| 1335 | - } | ||
| 1336 | - } | ||
| 1337 | - | ||
| 1338 | - /// 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. | ||
| 1339 | - pub fn reset(&mut self) { | ||
| 1340 | - match &mut self.inner { | ||
| 1341 | - DecInner::Vk(d) => d.reset(), | ||
| 1342 | - #[cfg(target_os = "linux")] | ||
| 1343 | - DecInner::Va(d) => d.reset(), | ||
| 1344 | - } | ||
| 1345 | - self.replay = None; | ||
| 1346 | - } | ||
| 1347 | - | ||
| 1348 | - /// Emit every picture still held for reordering. | ||
| 1349 | - pub fn flush(&mut self) -> Result<()> { | ||
| 1350 | - match &mut self.inner { | ||
| 1351 | - DecInner::Vk(d) => d.flush(), | ||
| 1352 | - #[cfg(target_os = "linux")] | ||
| 1353 | - DecInner::Va(d) => d.flush(), | ||
| 1354 | - } | ||
| 1355 | - } | ||
| 1356 | -} | ||
| 1357 | - | ||
| 1358 | -#[cfg(target_os = "linux")] | ||
| 1359 | -fn open_va_decoder(codec: Codec) -> Result<VaDecoder> { | ||
| 1360 | - let display = ec_va::open()?; | ||
| 1361 | - VaDecoder::new(&display, codec) | ||
| 1362 | -} | ||
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 | + pub(super) 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 | + | ||
crates/ec-hw/src/picture.rsmodified+13 -25
| @@ -258,20 +258,16 @@ pub(crate) fn fill_i420_16( | |||
| 258 | let bytes = if bit_depth == 8 { 1 } else { 2 }; | 258 | let bytes = if bit_depth == 8 { 1 } else { 2 }; |
| 259 | check_plane("luma", y_plane.len(), y_pitch, h, w * bytes)?; | 259 | check_plane("luma", y_plane.len(), y_pitch, h, w * bytes)?; |
| 260 | check_plane("chroma", uv_plane.len(), uv_pitch, ch, cw * 2 * bytes)?; | 260 | check_plane("chroma", uv_plane.len(), uv_pitch, ch, cw * 2 * bytes)?; |
| 261 | - let mut row_buf = vec![0u8; uv_pitch.max(y_pitch).max(w * 2)]; | ||
| 262 | match bit_depth { | 261 | match bit_depth { |
| 263 | 8 => { | 262 | 8 => { |
| 264 | for row in 0..h { | 263 | for row in 0..h { |
| 265 | - let src = row * y_pitch; | 264 | + let line = plane_row(y_plane, y_pitch, row, w); |
| 266 | - row_buf[..w].copy_from_slice(&y_plane[src..src + w]); | 265 | + for (dst, &sample) in out.y[row * w..(row + 1) * w].iter_mut().zip(line) { |
| 267 | - for (dst, &sample) in out.y[row * w..(row + 1) * w].iter_mut().zip(&row_buf[..w]) { | ||
| 268 | *dst = u16::from(sample) << 2; | 266 | *dst = u16::from(sample) << 2; |
| 269 | } | 267 | } |
| 270 | } | 268 | } |
| 271 | for row in 0..ch { | 269 | for row in 0..ch { |
| 272 | - let src = row * uv_pitch; | 270 | + let line = plane_row(uv_plane, uv_pitch, row, cw * 2); |
| 273 | - let line = &mut row_buf[..cw * 2]; | ||
| 274 | - line.copy_from_slice(&uv_plane[src..src + cw * 2]); | ||
| 275 | for col in 0..cw { | 271 | for col in 0..cw { |
| 276 | out.u[row * cw + col] = u16::from(line[col * 2]) << 2; | 272 | out.u[row * cw + col] = u16::from(line[col * 2]) << 2; |
| 277 | out.v[row * cw + col] = u16::from(line[col * 2 + 1]) << 2; | 273 | out.v[row * cw + col] = u16::from(line[col * 2 + 1]) << 2; |
| @@ -282,18 +278,14 @@ pub(crate) fn fill_i420_16( | |||
| 282 | // P010 is 16-bit little endian with the sample in the top ten | 278 | // P010 is 16-bit little endian with the sample in the top ten |
| 283 | // bits; the low six are zero padding. | 279 | // bits; the low six are zero padding. |
| 284 | for row in 0..h { | 280 | for row in 0..h { |
| 285 | - let src = row * y_pitch; | 281 | + let line = plane_row(y_plane, y_pitch, row, w * 2); |
| 286 | - let line = &mut row_buf[..w * 2]; | ||
| 287 | - line.copy_from_slice(&y_plane[src..src + w * 2]); | ||
| 288 | for col in 0..w { | 282 | for col in 0..w { |
| 289 | out.y[row * w + col] = | 283 | out.y[row * w + col] = |
| 290 | u16::from_le_bytes([line[col * 2], line[col * 2 + 1]]) >> 6; | 284 | u16::from_le_bytes([line[col * 2], line[col * 2 + 1]]) >> 6; |
| 291 | } | 285 | } |
| 292 | } | 286 | } |
| 293 | for row in 0..ch { | 287 | for row in 0..ch { |
| 294 | - let src = row * uv_pitch; | 288 | + let line = plane_row(uv_plane, uv_pitch, row, cw * 4); |
| 295 | - let line = &mut row_buf[..cw * 4]; | ||
| 296 | - line.copy_from_slice(&uv_plane[src..src + cw * 4]); | ||
| 297 | for col in 0..cw { | 289 | for col in 0..cw { |
| 298 | out.u[row * cw + col] = | 290 | out.u[row * cw + col] = |
| 299 | u16::from_le_bytes([line[col * 4], line[col * 4 + 1]]) >> 6; | 291 | u16::from_le_bytes([line[col * 4], line[col * 4 + 1]]) >> 6; |
| @@ -347,17 +339,13 @@ pub(crate) fn fill_i420( | |||
| 347 | let bytes = if bit_depth == 8 { 1 } else { 2 }; | 339 | let bytes = if bit_depth == 8 { 1 } else { 2 }; |
| 348 | check_plane("luma", y_plane.len(), y_pitch, h, w * bytes)?; | 340 | check_plane("luma", y_plane.len(), y_pitch, h, w * bytes)?; |
| 349 | check_plane("chroma", uv_plane.len(), uv_pitch, ch, cw * 2 * bytes)?; | 341 | check_plane("chroma", uv_plane.len(), uv_pitch, ch, cw * 2 * bytes)?; |
| 350 | - let mut row_buf = vec![0u8; uv_pitch.max(y_pitch).max(w * 2)]; | ||
| 351 | match bit_depth { | 342 | match bit_depth { |
| 352 | 8 => { | 343 | 8 => { |
| 353 | for row in 0..h { | 344 | for row in 0..h { |
| 354 | - let src = row * y_pitch; | 345 | + out.y[row * w..(row + 1) * w].copy_from_slice(plane_row(y_plane, y_pitch, row, w)); |
| 355 | - out.y[row * w..(row + 1) * w].copy_from_slice(&y_plane[src..src + w]); | ||
| 356 | } | 346 | } |
| 357 | for row in 0..ch { | 347 | for row in 0..ch { |
| 358 | - let src = row * uv_pitch; | 348 | + let line = plane_row(uv_plane, uv_pitch, row, cw * 2); |
| 359 | - let line = &mut row_buf[..cw * 2]; | ||
| 360 | - line.copy_from_slice(&uv_plane[src..src + cw * 2]); | ||
| 361 | for col in 0..cw { | 349 | for col in 0..cw { |
| 362 | out.u[row * cw + col] = line[col * 2]; | 350 | out.u[row * cw + col] = line[col * 2]; |
| 363 | out.v[row * cw + col] = line[col * 2 + 1]; | 351 | out.v[row * cw + col] = line[col * 2 + 1]; |
| @@ -368,17 +356,13 @@ pub(crate) fn fill_i420( | |||
| 368 | // P010 keeps the sample in the *high* bits of each u16, so the | 356 | // P010 keeps the sample in the *high* bits of each u16, so the |
| 369 | // 8-bit value is the high byte — a shift by 8, not by 2. | 357 | // 8-bit value is the high byte — a shift by 8, not by 2. |
| 370 | for row in 0..h { | 358 | for row in 0..h { |
| 371 | - let src = row * y_pitch; | 359 | + let line = plane_row(y_plane, y_pitch, row, w * 2); |
| 372 | - let line = &mut row_buf[..w * 2]; | ||
| 373 | - line.copy_from_slice(&y_plane[src..src + w * 2]); | ||
| 374 | for col in 0..w { | 360 | for col in 0..w { |
| 375 | out.y[row * w + col] = line[col * 2 + 1]; | 361 | out.y[row * w + col] = line[col * 2 + 1]; |
| 376 | } | 362 | } |
| 377 | } | 363 | } |
| 378 | for row in 0..ch { | 364 | for row in 0..ch { |
| 379 | - let src = row * uv_pitch; | 365 | + let line = plane_row(uv_plane, uv_pitch, row, cw * 4); |
| 380 | - let line = &mut row_buf[..cw * 4]; | ||
| 381 | - line.copy_from_slice(&uv_plane[src..src + cw * 4]); | ||
| 382 | for col in 0..cw { | 366 | for col in 0..cw { |
| 383 | out.u[row * cw + col] = line[col * 4 + 1]; | 367 | out.u[row * cw + col] = line[col * 4 + 1]; |
| 384 | out.v[row * cw + col] = line[col * 4 + 3]; | 368 | out.v[row * cw + col] = line[col * 4 + 3]; |
| @@ -389,6 +373,10 @@ pub(crate) fn fill_i420( | |||
| 389 | Ok(()) | 373 | Ok(()) |
| 390 | } | 374 | } |
| 391 | 375 | ||
| 376 | +fn plane_row(plane: &[u8], pitch: usize, row: usize, len: usize) -> &[u8] { | ||
| 377 | + &plane[row * pitch..row * pitch + len] | ||
| 378 | +} | ||
| 379 | + | ||
| 392 | /// Check that `rows` rows of `row_bytes` bytes at `pitch` fit in a plane of | 380 | /// Check that `rows` rows of `row_bytes` bytes at `pitch` fit in a plane of |
| 393 | /// `len` bytes. A lost or half-initialised GPU context can hand back a short | 381 | /// `len` bytes. A lost or half-initialised GPU context can hand back a short |
| 394 | /// or odd mapping; this turns what would be a slice panic into an error. | 382 | /// or odd mapping; this turns what would be a slice panic into an error. |
crates/ec-hw/src/pool.rsmodified+11 -25
| @@ -13,12 +13,12 @@ | |||
| 13 | use ec_va::{Surface, SurfaceSpec}; | 13 | use ec_va::{Surface, SurfaceSpec}; |
| 14 | use std::ops::Deref; | 14 | use std::ops::Deref; |
| 15 | use std::rc::{Rc, Weak}; | 15 | use std::rc::{Rc, Weak}; |
| 16 | -use std::sync::Mutex; | 16 | +use std::cell::RefCell; |
| 17 | 17 | ||
| 18 | struct PoolInner { | 18 | struct PoolInner { |
| 19 | /// Every surface, in allocation order. | 19 | /// Every surface, in allocation order. |
| 20 | - all: Mutex<Vec<Rc<Surface>>>, | 20 | + all: RefCell<Vec<Rc<Surface>>>, |
| 21 | - free: Mutex<Vec<Rc<Surface>>>, | 21 | + free: RefCell<Vec<Rc<Surface>>>, |
| 22 | } | 22 | } |
| 23 | 23 | ||
| 24 | /// A fixed-size pool of identically specified surfaces. | 24 | /// A fixed-size pool of identically specified surfaces. |
| @@ -36,8 +36,8 @@ impl SurfacePool { | |||
| 36 | let all: Vec<Rc<Surface>> = surfaces.into_iter().map(Rc::new).collect(); | 36 | let all: Vec<Rc<Surface>> = surfaces.into_iter().map(Rc::new).collect(); |
| 37 | SurfacePool { | 37 | SurfacePool { |
| 38 | inner: Rc::new(PoolInner { | 38 | inner: Rc::new(PoolInner { |
| 39 | - free: Mutex::new(all.clone()), | 39 | + free: RefCell::new(all.clone()), |
| 40 | - all: Mutex::new(all), | 40 | + all: RefCell::new(all), |
| 41 | }), | 41 | }), |
| 42 | spec: *spec, | 42 | spec: *spec, |
| 43 | } | 43 | } |
| @@ -50,7 +50,7 @@ impl SurfacePool { | |||
| 50 | 50 | ||
| 51 | /// Total surfaces in the pool. | 51 | /// Total surfaces in the pool. |
| 52 | pub fn len(&self) -> usize { | 52 | pub fn len(&self) -> usize { |
| 53 | - self.inner.all.lock().map(|all| all.len()).unwrap_or(0) | 53 | + self.inner.all.borrow().len() |
| 54 | } | 54 | } |
| 55 | 55 | ||
| 56 | /// True when the pool holds no surfaces at all. | 56 | /// True when the pool holds no surfaces at all. |
| @@ -61,17 +61,13 @@ impl SurfacePool { | |||
| 61 | /// Add surfaces allocated with the pool's spec, free for [`SurfacePool::acquire`]. | 61 | /// Add surfaces allocated with the pool's spec, free for [`SurfacePool::acquire`]. |
| 62 | pub fn grow(&self, surfaces: Vec<Surface>) { | 62 | pub fn grow(&self, surfaces: Vec<Surface>) { |
| 63 | let surfaces: Vec<Rc<Surface>> = surfaces.into_iter().map(Rc::new).collect(); | 63 | let surfaces: Vec<Rc<Surface>> = surfaces.into_iter().map(Rc::new).collect(); |
| 64 | - if let Ok(mut all) = self.inner.all.lock() { | 64 | + self.inner.all.borrow_mut().extend(surfaces.iter().cloned()); |
| 65 | - all.extend(surfaces.iter().cloned()); | 65 | + self.inner.free.borrow_mut().extend(surfaces); |
| 66 | - } | ||
| 67 | - if let Ok(mut free) = self.inner.free.lock() { | ||
| 68 | - free.extend(surfaces); | ||
| 69 | - } | ||
| 70 | } | 66 | } |
| 71 | 67 | ||
| 72 | /// Surfaces currently available. | 68 | /// Surfaces currently available. |
| 73 | pub fn available(&self) -> usize { | 69 | pub fn available(&self) -> usize { |
| 74 | - self.inner.free.lock().map(|f| f.len()).unwrap_or(0) | 70 | + self.inner.free.borrow().len() |
| 75 | } | 71 | } |
| 76 | 72 | ||
| 77 | /// Take a free surface, or `None` when every one is still in use. | 73 | /// Take a free surface, or `None` when every one is still in use. |
| @@ -79,13 +75,7 @@ impl SurfacePool { | |||
| 79 | /// A `None` is the caller's cue to release output frames, not an error: a | 75 | /// A `None` is the caller's cue to release output frames, not an error: a |
| 80 | /// decoder that has handed out its whole pool is waiting on the consumer. | 76 | /// decoder that has handed out its whole pool is waiting on the consumer. |
| 81 | pub fn acquire(&self) -> Option<Rc<PooledSurface>> { | 77 | pub fn acquire(&self) -> Option<Rc<PooledSurface>> { |
| 82 | - // A poisoned lock means another thread panicked while holding it; the | 78 | + let surface = self.inner.free.borrow_mut().pop()?; |
| 83 | - // free list is a plain Vec, so its contents are still consistent. | ||
| 84 | - let mut free = match self.inner.free.lock() { | ||
| 85 | - Ok(free) => free, | ||
| 86 | - Err(poisoned) => poisoned.into_inner(), | ||
| 87 | - }; | ||
| 88 | - let surface = free.pop()?; | ||
| 89 | Some(Rc::new(PooledSurface { | 79 | Some(Rc::new(PooledSurface { |
| 90 | surface, | 80 | surface, |
| 91 | pool: Rc::downgrade(&self.inner), | 81 | pool: Rc::downgrade(&self.inner), |
| @@ -128,10 +118,6 @@ impl Drop for PooledSurface { | |||
| 128 | // The pool is gone, so the surface simply drops with this handle. | 118 | // The pool is gone, so the surface simply drops with this handle. |
| 129 | return; | 119 | return; |
| 130 | }; | 120 | }; |
| 131 | - let mut free = match pool.free.lock() { | 121 | + pool.free.borrow_mut().push(Rc::clone(&self.surface)); |
| 132 | - Ok(free) => free, | ||
| 133 | - Err(poisoned) => poisoned.into_inner(), | ||
| 134 | - }; | ||
| 135 | - free.push(Rc::clone(&self.surface)); | ||
| 136 | } | 122 | } |
| 137 | } | 123 | } |