Merge branch 'worktree-agent-ab057528cdea26a6b'
Browse files at this commit11 changed files +1039 -254
- crates/ec-hw/examples/hw_pipeline.rs +165 -0
- crates/ec-hw/src/hw.rs +166 -0
- crates/ec-hw/src/lib.rs +2 -1
- crates/ec-vk/src/av1.rs +91 -28
- crates/ec-vk/src/h265.rs +92 -29
- crates/ec-vk/src/lib.rs +99 -24
- shims/vk-video-ffi/src/av1_encode.rs +49 -11
- shims/vk-video-ffi/src/dmabuf.rs +14 -6
- shims/vk-video-ffi/src/h264_encode.rs +41 -9
- shims/vk-video-ffi/src/h265_encode.rs +50 -12
- shims/vk-video-ffi/src/session.rs +270 -134
crates/ec-hw/examples/hw_pipeline.rsadded+165 -0
| @@ -0,0 +1,165 @@ | ||
| 1 | +use std::time::Instant; | |
| 2 | + | |
| 3 | +use ec_hw::{ | |
| 4 | + Backend, EncCodec, EncodeInput, EncoderConfig, FrameMetadata, HwEncoder, I420, I420_16, | |
| 5 | + RateControlMode, | |
| 6 | +}; | |
| 7 | + | |
| 8 | +const FRAMES: usize = 120; | |
| 9 | +const PATTERN: usize = 6; | |
| 10 | + | |
| 11 | +struct Case { | |
| 12 | + codec: EncCodec, | |
| 13 | + width: u32, | |
| 14 | + height: u32, | |
| 15 | + ten: bool, | |
| 16 | +} | |
| 17 | + | |
| 18 | +enum Source { | |
| 19 | + Eight(Vec<I420>), | |
| 20 | + Ten(Vec<I420_16>), | |
| 21 | +} | |
| 22 | + | |
| 23 | +fn main() { | |
| 24 | + let cases = [ | |
| 25 | + Case { | |
| 26 | + codec: EncCodec::H265, | |
| 27 | + width: 3840, | |
| 28 | + height: 2160, | |
| 29 | + ten: true, | |
| 30 | + }, | |
| 31 | + Case { | |
| 32 | + codec: EncCodec::H264, | |
| 33 | + width: 1920, | |
| 34 | + height: 1080, | |
| 35 | + ten: false, | |
| 36 | + }, | |
| 37 | + Case { | |
| 38 | + codec: EncCodec::H265, | |
| 39 | + width: 1920, | |
| 40 | + height: 1080, | |
| 41 | + ten: false, | |
| 42 | + }, | |
| 43 | + Case { | |
| 44 | + codec: EncCodec::Av1, | |
| 45 | + width: 1920, | |
| 46 | + height: 1080, | |
| 47 | + ten: false, | |
| 48 | + }, | |
| 49 | + ]; | |
| 50 | + for case in &cases { | |
| 51 | + let source = if case.ten { | |
| 52 | + Source::Ten(pattern_16(case)) | |
| 53 | + } else { | |
| 54 | + Source::Eight(pattern(case)) | |
| 55 | + }; | |
| 56 | + for backend in [Backend::Vk, Backend::Va] { | |
| 57 | + if let Err(e) = run(case, &source, backend) { | |
| 58 | + println!( | |
| 59 | + "{:?} {}x{} {backend:?}: error: {e}", | |
| 60 | + case.codec, case.width, case.height | |
| 61 | + ); | |
| 62 | + } | |
| 63 | + } | |
| 64 | + } | |
| 65 | +} | |
| 66 | + | |
| 67 | +fn config(case: &Case) -> EncoderConfig { | |
| 68 | + let base = EncoderConfig { | |
| 69 | + rate_control: RateControlMode::ConstantQp { qp: 30 }, | |
| 70 | + ..EncoderConfig::new(case.codec, case.width, case.height) | |
| 71 | + }; | |
| 72 | + if case.ten { | |
| 73 | + base.ten_bit() | |
| 74 | + } else { | |
| 75 | + base | |
| 76 | + } | |
| 77 | +} | |
| 78 | + | |
| 79 | +fn meta(index: usize) -> FrameMetadata { | |
| 80 | + FrameMetadata { | |
| 81 | + timestamp: index as i64, | |
| 82 | + force_keyframe: index == 0, | |
| 83 | + } | |
| 84 | +} | |
| 85 | + | |
| 86 | +fn run(case: &Case, source: &Source, backend: Backend) -> ec_hw::Result<()> { | |
| 87 | + let mut encoder = HwEncoder::open(config(case), Some(backend))?; | |
| 88 | + let start = Instant::now(); | |
| 89 | + let mut sync = Vec::with_capacity(FRAMES); | |
| 90 | + for index in 0..FRAMES { | |
| 91 | + let coded = match source { | |
| 92 | + Source::Eight(frames) => encoder.encode(&frames[index % PATTERN], meta(index))?, | |
| 93 | + Source::Ten(frames) => encoder.encode_16(&frames[index % PATTERN], meta(index))?, | |
| 94 | + }; | |
| 95 | + sync.push(coded); | |
| 96 | + } | |
| 97 | + let sync_ms = start.elapsed().as_secs_f64() * 1000.0 / FRAMES as f64; | |
| 98 | + | |
| 99 | + let mut encoder = HwEncoder::open(config(case), Some(backend))?; | |
| 100 | + let start = Instant::now(); | |
| 101 | + let mut piped = Vec::with_capacity(FRAMES); | |
| 102 | + for index in 0..FRAMES { | |
| 103 | + let input = match source { | |
| 104 | + Source::Eight(frames) => EncodeInput::I420(&frames[index % PATTERN]), | |
| 105 | + Source::Ten(frames) => EncodeInput::I420_16(&frames[index % PATTERN]), | |
| 106 | + }; | |
| 107 | + piped.extend(encoder.submit(input, meta(index))?); | |
| 108 | + } | |
| 109 | + piped.extend(encoder.flush()?); | |
| 110 | + let piped_ms = start.elapsed().as_secs_f64() * 1000.0 / FRAMES as f64; | |
| 111 | + | |
| 112 | + if matches!(backend, Backend::Vk) { | |
| 113 | + assert_eq!(sync, piped, "{:?} sync and pipelined bitstreams differ", case.codec); | |
| 114 | + } | |
| 115 | + println!( | |
| 116 | + "{:?} {}x{} {}-bit {backend:?}: sync {sync_ms:.2} ms/frame, pipelined {piped_ms:.2} ms/frame, {} frames", | |
| 117 | + case.codec, | |
| 118 | + case.width, | |
| 119 | + case.height, | |
| 120 | + if case.ten { 10 } else { 8 }, | |
| 121 | + piped.len() | |
| 122 | + ); | |
| 123 | + Ok(()) | |
| 124 | +} | |
| 125 | + | |
| 126 | +fn pattern(case: &Case) -> Vec<I420> { | |
| 127 | + let (w, h) = (case.width as usize, case.height as usize); | |
| 128 | + let (cw, ch) = (w / 2, h / 2); | |
| 129 | + (0..PATTERN) | |
| 130 | + .map(|k| I420 { | |
| 131 | + y: (0..h) | |
| 132 | + .flat_map(move |row| (0..w).map(move |x| ((x + row + 3 * k) & 0xff) as u8)) | |
| 133 | + .collect(), | |
| 134 | + u: (0..ch) | |
| 135 | + .flat_map(move |row| (0..cw).map(move |x| ((x + 2 * row + 5 * k) & 0xff) as u8)) | |
| 136 | + .collect(), | |
| 137 | + v: (0..ch) | |
| 138 | + .flat_map(move |row| (0..cw).map(move |x| ((2 * x + row + 7 * k) & 0xff) as u8)) | |
| 139 | + .collect(), | |
| 140 | + width: case.width, | |
| 141 | + height: case.height, | |
| 142 | + }) | |
| 143 | + .collect() | |
| 144 | +} | |
| 145 | + | |
| 146 | +fn pattern_16(case: &Case) -> Vec<I420_16> { | |
| 147 | + let (w, h) = (case.width as usize, case.height as usize); | |
| 148 | + let (cw, ch) = (w / 2, h / 2); | |
| 149 | + (0..PATTERN) | |
| 150 | + .map(|k| I420_16 { | |
| 151 | + y: (0..h) | |
| 152 | + .flat_map(move |row| (0..w).map(move |x| ((x + row + 3 * k) & 0x3ff) as u16)) | |
| 153 | + .collect(), | |
| 154 | + u: (0..ch) | |
| 155 | + .flat_map(move |row| (0..cw).map(move |x| ((x + 2 * row + 5 * k) & 0x3ff) as u16)) | |
| 156 | + .collect(), | |
| 157 | + v: (0..ch) | |
| 158 | + .flat_map(move |row| (0..cw).map(move |x| ((2 * x + row + 7 * k) & 0x3ff) as u16)) | |
| 159 | + .collect(), | |
| 160 | + width: case.width, | |
| 161 | + height: case.height, | |
| 162 | + bit_depth: 10, | |
| 163 | + }) | |
| 164 | + .collect() | |
| 165 | +} |
crates/ec-hw/src/hw.rsmodified+166 -0
| @@ -7,6 +7,7 @@ use std::os::fd::BorrowedFd; | ||
| 7 | 7 | use ec_vk::{DmaBuf, DmaBufFormat, DmaBufPlane}; |
| 8 | 8 | |
| 9 | 9 | use std::cell::RefCell; |
| 10 | +use std::collections::VecDeque; | |
| 10 | 11 | |
| 11 | 12 | use crate::error::{Error, Result}; |
| 12 | 13 | use crate::picture::{Decoded, I420, I420_16, RgbPicture}; |
| @@ -257,6 +258,23 @@ pub struct DmaBufFrame<'a> { | ||
| 257 | 258 | pub order: RgbOrder, |
| 258 | 259 | } |
| 259 | 260 | |
| 261 | +/// One picture for [`HwEncoder::submit`]. | |
| 262 | +#[derive(Debug, Clone, Copy)] | |
| 263 | +pub enum EncodeInput<'a> { | |
| 264 | + /// 8-bit I420. | |
| 265 | + I420(&'a I420), | |
| 266 | + /// 10-bit I420 of a 10-bit encoder (H.265 and AV1). | |
| 267 | + I420_16(&'a I420_16), | |
| 268 | + /// Packed RGB, box-downscaled to the encoder size. | |
| 269 | + Rgb(&'a RgbFrame<'a>), | |
| 270 | + /// DMA-BUF of packed RGB, Vulkan only. | |
| 271 | + #[cfg(target_os = "linux")] | |
| 272 | + DmaBuf(&'a DmaBufFrame<'a>), | |
| 273 | + /// DMA-BUF of NV12 or P010 at the encoder size, Vulkan only. | |
| 274 | + #[cfg(target_os = "linux")] | |
| 275 | + DmaBufYuv(&'a DmaBufYuvFrame<'a>), | |
| 276 | +} | |
| 277 | + | |
| 260 | 278 | #[cfg(target_os = "linux")] |
| 261 | 279 | fn rgb_to_i420(frame: &RgbFrame, (w, h): (usize, usize)) -> Result<I420> { |
| 262 | 280 | let (sw, sh, stride) = ( |
| @@ -315,7 +333,103 @@ enum VkEncoder { | ||
| 315 | 333 | Av1(ec_vk::Av1Encoder), |
| 316 | 334 | } |
| 317 | 335 | |
| 336 | +fn stamp(pending: &mut VecDeque<i64>, coded: ec_vk::CodedFrame) -> CodedFrame { | |
| 337 | + CodedFrame { | |
| 338 | + data: coded.data, | |
| 339 | + timestamp: pending.pop_front().unwrap_or_default(), | |
| 340 | + is_keyframe: coded.keyframe, | |
| 341 | + } | |
| 342 | +} | |
| 343 | + | |
| 318 | 344 | impl VkEncoder { |
| 345 | + fn submit( | |
| 346 | + &mut self, | |
| 347 | + input: EncodeInput, | |
| 348 | + force_keyframe: bool, | |
| 349 | + ) -> std::result::Result<Option<ec_vk::CodedFrame>, ec_vk::Error> { | |
| 350 | + match input { | |
| 351 | + EncodeInput::I420(frame) => { | |
| 352 | + let (y, u, v) = (&frame.y, &frame.u, &frame.v); | |
| 353 | + match self { | |
| 354 | + VkEncoder::H264(e) => e.submit(y, u, v, force_keyframe), | |
| 355 | + VkEncoder::H265(e) => e.submit(y, u, v, force_keyframe), | |
| 356 | + VkEncoder::Av1(e) => e.submit(y, u, v, force_keyframe), | |
| 357 | + } | |
| 358 | + } | |
| 359 | + EncodeInput::I420_16(frame) => { | |
| 360 | + let (y, u, v) = (&frame.y, &frame.u, &frame.v); | |
| 361 | + match self { | |
| 362 | + VkEncoder::H264(_) => Err(ec_vk::Error::Unsupported("10-bit H.264 encode".into())), | |
| 363 | + VkEncoder::H265(e) => e.submit_16(y, u, v, force_keyframe), | |
| 364 | + VkEncoder::Av1(e) => e.submit_16(y, u, v, force_keyframe), | |
| 365 | + } | |
| 366 | + } | |
| 367 | + EncodeInput::Rgb(frame) => { | |
| 368 | + let bgr = frame.order == RgbOrder::Bgra; | |
| 369 | + let (data, sw, sh, stride) = (frame.data, frame.width, frame.height, frame.stride); | |
| 370 | + match self { | |
| 371 | + VkEncoder::H264(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), | |
| 372 | + VkEncoder::H265(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), | |
| 373 | + VkEncoder::Av1(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), | |
| 374 | + } | |
| 375 | + } | |
| 376 | + #[cfg(target_os = "linux")] | |
| 377 | + EncodeInput::DmaBuf(frame) => { | |
| 378 | + let planes = [DmaBufPlane { | |
| 379 | + fd: 0, | |
| 380 | + offset: frame.offset, | |
| 381 | + pitch: frame.stride, | |
| 382 | + }]; | |
| 383 | + let src = DmaBuf { | |
| 384 | + fds: std::slice::from_ref(&frame.fd), | |
| 385 | + planes: &planes, | |
| 386 | + width: frame.width, | |
| 387 | + height: frame.height, | |
| 388 | + modifier: frame.modifier, | |
| 389 | + format: if frame.order == RgbOrder::Bgra { | |
| 390 | + DmaBufFormat::Bgrx | |
| 391 | + } else { | |
| 392 | + DmaBufFormat::Rgbx | |
| 393 | + }, | |
| 394 | + }; | |
| 395 | + self.submit_dma(&src, force_keyframe) | |
| 396 | + } | |
| 397 | + #[cfg(target_os = "linux")] | |
| 398 | + EncodeInput::DmaBufYuv(frame) => { | |
| 399 | + let src = DmaBuf { | |
| 400 | + fds: frame.fds, | |
| 401 | + planes: &frame.planes, | |
| 402 | + width: frame.width, | |
| 403 | + height: frame.height, | |
| 404 | + modifier: frame.modifier, | |
| 405 | + format: frame.format, | |
| 406 | + }; | |
| 407 | + self.submit_dma(&src, force_keyframe) | |
| 408 | + } | |
| 409 | + } | |
| 410 | + } | |
| 411 | + | |
| 412 | + #[cfg(target_os = "linux")] | |
| 413 | + fn submit_dma( | |
| 414 | + &mut self, | |
| 415 | + src: &DmaBuf, | |
| 416 | + force_keyframe: bool, | |
| 417 | + ) -> std::result::Result<Option<ec_vk::CodedFrame>, ec_vk::Error> { | |
| 418 | + match self { | |
| 419 | + VkEncoder::H264(e) => e.submit_dmabuf(src, force_keyframe), | |
| 420 | + VkEncoder::H265(e) => e.submit_dmabuf(src, force_keyframe), | |
| 421 | + VkEncoder::Av1(e) => e.submit_dmabuf(src, force_keyframe), | |
| 422 | + } | |
| 423 | + } | |
| 424 | + | |
| 425 | + fn flush(&mut self) -> std::result::Result<Vec<ec_vk::CodedFrame>, ec_vk::Error> { | |
| 426 | + match self { | |
| 427 | + VkEncoder::H264(e) => e.flush(), | |
| 428 | + VkEncoder::H265(e) => e.flush(), | |
| 429 | + VkEncoder::Av1(e) => e.flush(), | |
| 430 | + } | |
| 431 | + } | |
| 432 | + | |
| 319 | 433 | fn encode( |
| 320 | 434 | &mut self, |
| 321 | 435 | frame: &I420, |
| @@ -395,6 +509,7 @@ pub struct HwEncoder { | ||
| 395 | 509 | config: EncoderConfig, |
| 396 | 510 | #[cfg_attr(not(target_os = "linux"), allow(dead_code))] |
| 397 | 511 | size: (usize, usize), |
| 512 | + pending: VecDeque<i64>, | |
| 398 | 513 | } |
| 399 | 514 | |
| 400 | 515 | impl HwEncoder { |
| @@ -415,6 +530,7 @@ impl HwEncoder { | ||
| 415 | 530 | born_epoch, |
| 416 | 531 | config, |
| 417 | 532 | size, |
| 533 | + pending: VecDeque::new(), | |
| 418 | 534 | }); |
| 419 | 535 | } |
| 420 | 536 | Err(e) => reasons.push(format!("{backend:?}: {e}")), |
| @@ -454,8 +570,55 @@ impl HwEncoder { | ||
| 454 | 570 | Ok(()) |
| 455 | 571 | } |
| 456 | 572 | |
| 573 | + /// Submit one picture without waiting; the oldest coded picture comes back once two are in flight. Call [`HwEncoder::flush`] at the end. | |
| 574 | + pub fn submit(&mut self, input: EncodeInput, meta: FrameMetadata) -> Result<Option<CodedFrame>> { | |
| 575 | + match &mut self.inner { | |
| 576 | + EncInner::Vk(enc) => { | |
| 577 | + vk_session_alive(self.born_epoch)?; | |
| 578 | + self.pending.push_back(meta.timestamp); | |
| 579 | + let out = enc.submit(input, meta.force_keyframe)?; | |
| 580 | + Ok(out.map(|coded| stamp(&mut self.pending, coded))) | |
| 581 | + } | |
| 582 | + #[cfg(target_os = "linux")] | |
| 583 | + EncInner::Va(enc) => match input { | |
| 584 | + EncodeInput::I420(frame) => enc.submit(frame, meta), | |
| 585 | + EncodeInput::I420_16(frame) => enc.submit_16(frame, meta), | |
| 586 | + EncodeInput::Rgb(frame) => enc.submit(&rgb_to_i420(frame, self.size)?, meta), | |
| 587 | + EncodeInput::DmaBuf(_) | EncodeInput::DmaBufYuv(_) => Err(Error::unsupported( | |
| 588 | + "DMA-BUF encode", | |
| 589 | + "the VA-API backend has no DMA-BUF input here", | |
| 590 | + )), | |
| 591 | + }, | |
| 592 | + } | |
| 593 | + } | |
| 594 | + | |
| 595 | + /// Wait for every submitted picture and return them, oldest first. | |
| 596 | + pub fn flush(&mut self) -> Result<Vec<CodedFrame>> { | |
| 597 | + match &mut self.inner { | |
| 598 | + EncInner::Vk(enc) => { | |
| 599 | + vk_session_alive(self.born_epoch)?; | |
| 600 | + let frames = enc.flush()?; | |
| 601 | + Ok(frames | |
| 602 | + .into_iter() | |
| 603 | + .map(|coded| stamp(&mut self.pending, coded)) | |
| 604 | + .collect()) | |
| 605 | + } | |
| 606 | + #[cfg(target_os = "linux")] | |
| 607 | + EncInner::Va(enc) => enc.flush(), | |
| 608 | + } | |
| 609 | + } | |
| 610 | + | |
| 611 | + fn idle(&self) -> Result<()> { | |
| 612 | + if self.pending.is_empty() { | |
| 613 | + Ok(()) | |
| 614 | + } else { | |
| 615 | + Err(Error::config("pipelined frames pending; call flush first")) | |
| 616 | + } | |
| 617 | + } | |
| 618 | + | |
| 457 | 619 | /// Encode one frame; `meta.force_keyframe` starts a new GOP. |
| 458 | 620 | pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> { |
| 621 | + self.idle()?; | |
| 459 | 622 | match &mut self.inner { |
| 460 | 623 | EncInner::Vk(enc) => { |
| 461 | 624 | vk_session_alive(self.born_epoch)?; |
| @@ -473,6 +636,7 @@ impl HwEncoder { | ||
| 473 | 636 | |
| 474 | 637 | /// Encode one 10-bit frame of a 10-bit encoder (H.265 and AV1), the [`HwEncoder::encode`] of a 10-bit encoder. |
| 475 | 638 | pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result<CodedFrame> { |
| 639 | + self.idle()?; | |
| 476 | 640 | match &mut self.inner { |
| 477 | 641 | EncInner::Vk(enc) => { |
| 478 | 642 | let coded = enc.encode_16(frame, meta.force_keyframe)?; |
| @@ -489,6 +653,7 @@ impl HwEncoder { | ||
| 489 | 653 | |
| 490 | 654 | /// 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. |
| 491 | 655 | pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result<CodedFrame> { |
| 656 | + self.idle()?; | |
| 492 | 657 | match &mut self.inner { |
| 493 | 658 | EncInner::Vk(enc) => { |
| 494 | 659 | vk_session_alive(self.born_epoch)?; |
| @@ -551,6 +716,7 @@ impl HwEncoder { | ||
| 551 | 716 | |
| 552 | 717 | #[cfg(target_os = "linux")] |
| 553 | 718 | fn encode_dma(&mut self, src: &DmaBuf, meta: FrameMetadata) -> Result<CodedFrame> { |
| 719 | + self.idle()?; | |
| 554 | 720 | match &mut self.inner { |
| 555 | 721 | EncInner::Vk(enc) => { |
| 556 | 722 | vk_session_alive(self.born_epoch)?; |
crates/ec-hw/src/lib.rsmodified+2 -1
| @@ -90,7 +90,8 @@ pub use ec_vk::{DmaBufFormat, DmaBufPlane}; | ||
| 90 | 90 | #[cfg(target_os = "linux")] |
| 91 | 91 | pub use hw::{DmaBufFrame, DmaBufYuvFrame}; |
| 92 | 92 | pub use hw::{ |
| 93 | - Backend, Capability, Direction, HwDecoder, HwEncoder, RgbFrame, RgbOrder, RgbOutput, | |
| 93 | + Backend, Capability, Direction, EncodeInput, HwDecoder, HwEncoder, RgbFrame, RgbOrder, | |
| 94 | + RgbOutput, | |
| 94 | 95 | capabilities, |
| 95 | 96 | }; |
| 96 | 97 | #[cfg(target_os = "linux")] |
crates/ec-vk/src/av1.rsmodified+91 -28
| @@ -2,7 +2,7 @@ use vk_video_ffi::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref}; | ||
| 2 | 2 | |
| 3 | 3 | #[cfg(target_os = "linux")] |
| 4 | 4 | use crate::DmaBuf; |
| 5 | -use crate::{CodedFrame, Error, Gpu, RateControl}; | |
| 5 | +use crate::{CodedFrame, Error, Flight, Gpu, RateControl, last_frame}; | |
| 6 | 6 | |
| 7 | 7 | const TEMPORAL_DELIMITER: [u8; 2] = [0x12, 0x00]; |
| 8 | 8 | |
| @@ -35,6 +35,7 @@ pub struct Av1Encoder { | ||
| 35 | 35 | reference: Option<Av1Ref>, |
| 36 | 36 | uv: Vec<u8>, |
| 37 | 37 | uv16: Vec<u16>, |
| 38 | + flight: Flight, | |
| 38 | 39 | } |
| 39 | 40 | |
| 40 | 41 | impl Av1Encoder { |
| @@ -65,17 +66,18 @@ impl Av1Encoder { | ||
| 65 | 66 | reference: None, |
| 66 | 67 | uv: vec![0; cfg.width as usize * cfg.height as usize / 2], |
| 67 | 68 | uv16: vec![0; cfg.width as usize * cfg.height as usize / 2], |
| 69 | + flight: Flight::default(), | |
| 68 | 70 | }) |
| 69 | 71 | } |
| 70 | 72 | |
| 71 | - /// Encodes one I420 frame as a temporal unit; `force_keyframe` makes it a KEY frame and restarts the GOP. | |
| 72 | - pub fn encode( | |
| 73 | + /// Submits one I420 frame without waiting; returns the oldest temporal unit once a second one is queued. | |
| 74 | + pub fn submit( | |
| 73 | 75 | &mut self, |
| 74 | 76 | y: &[u8], |
| 75 | 77 | u: &[u8], |
| 76 | 78 | v: &[u8], |
| 77 | 79 | force_keyframe: bool, |
| 78 | - ) -> Result<CodedFrame, Error> { | |
| 80 | + ) -> Result<Option<CodedFrame>, Error> { | |
| 79 | 81 | let chroma = self.width * self.height / 4; |
| 80 | 82 | if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma { |
| 81 | 83 | return Err(Error::Invalid("I420 plane size".into())); |
| @@ -85,18 +87,31 @@ impl Av1Encoder { | ||
| 85 | 87 | pair[1] = v[i]; |
| 86 | 88 | } |
| 87 | 89 | let pic = self.next_picture(force_keyframe); |
| 88 | - let frame = self.session.encode(y, &self.uv, &pic)?; | |
| 89 | - Ok(self.finish(&pic, frame)) | |
| 90 | + let out = self.session.submit(y, &self.uv, &pic)?; | |
| 91 | + Ok(out.map(|bytes| self.coded(bytes))) | |
| 90 | 92 | } |
| 91 | 93 | |
| 92 | - /// Encodes one 10-bit I420 frame of a 10-bit encoder; `force_keyframe` makes it a KEY frame and restarts the GOP. | |
| 93 | - pub fn encode_16( | |
| 94 | + /// Encodes one I420 frame as a temporal unit; `force_keyframe` makes it a KEY frame and restarts the GOP. | |
| 95 | + pub fn encode( | |
| 96 | + &mut self, | |
| 97 | + y: &[u8], | |
| 98 | + u: &[u8], | |
| 99 | + v: &[u8], | |
| 100 | + force_keyframe: bool, | |
| 101 | + ) -> Result<CodedFrame, Error> { | |
| 102 | + let first = self.submit(y, u, v, force_keyframe)?; | |
| 103 | + let rest = self.flush()?; | |
| 104 | + last_frame(first, rest) | |
| 105 | + } | |
| 106 | + | |
| 107 | + /// Submits one 10-bit I420 frame of a 10-bit encoder without waiting. | |
| 108 | + pub fn submit_16( | |
| 94 | 109 | &mut self, |
| 95 | 110 | y: &[u16], |
| 96 | 111 | u: &[u16], |
| 97 | 112 | v: &[u16], |
| 98 | 113 | force_keyframe: bool, |
| 99 | - ) -> Result<CodedFrame, Error> { | |
| 114 | + ) -> Result<Option<CodedFrame>, Error> { | |
| 100 | 115 | let chroma = self.width * self.height / 4; |
| 101 | 116 | if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma { |
| 102 | 117 | return Err(Error::Invalid("I420 plane size".into())); |
| @@ -106,8 +121,27 @@ impl Av1Encoder { | ||
| 106 | 121 | pair[1] = v[i]; |
| 107 | 122 | } |
| 108 | 123 | let pic = self.next_picture(force_keyframe); |
| 109 | - let frame = self.session.encode_16(y, &self.uv16, &pic)?; | |
| 110 | - Ok(self.finish(&pic, frame)) | |
| 124 | + let out = self.session.submit_16(y, &self.uv16, &pic)?; | |
| 125 | + Ok(out.map(|bytes| self.coded(bytes))) | |
| 126 | + } | |
| 127 | + | |
| 128 | + /// Encodes one 10-bit I420 frame of a 10-bit encoder; `force_keyframe` makes it a KEY frame and restarts the GOP. | |
| 129 | + pub fn encode_16( | |
| 130 | + &mut self, | |
| 131 | + y: &[u16], | |
| 132 | + u: &[u16], | |
| 133 | + v: &[u16], | |
| 134 | + force_keyframe: bool, | |
| 135 | + ) -> Result<CodedFrame, Error> { | |
| 136 | + let first = self.submit_16(y, u, v, force_keyframe)?; | |
| 137 | + let rest = self.flush()?; | |
| 138 | + last_frame(first, rest) | |
| 139 | + } | |
| 140 | + | |
| 141 | + /// Waits for every submitted frame and returns them in order. | |
| 142 | + pub fn flush(&mut self) -> Result<Vec<CodedFrame>, Error> { | |
| 143 | + let bytes = self.session.flush()?; | |
| 144 | + Ok(bytes.into_iter().map(|b| self.coded(b)).collect()) | |
| 111 | 145 | } |
| 112 | 146 | |
| 113 | 147 | /// Changes bitrate or frame rate; takes effect on the next frame. |
| @@ -115,6 +149,23 @@ impl Av1Encoder { | ||
| 115 | 149 | Ok(self.session.set_rate(rate, fps)?) |
| 116 | 150 | } |
| 117 | 151 | |
| 152 | + /// Submits one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes) without waiting. | |
| 153 | + pub fn submit_rgb( | |
| 154 | + &mut self, | |
| 155 | + rgb: &[u8], | |
| 156 | + src_width: u32, | |
| 157 | + src_height: u32, | |
| 158 | + stride_bytes: u32, | |
| 159 | + bgr: bool, | |
| 160 | + force_keyframe: bool, | |
| 161 | + ) -> Result<Option<CodedFrame>, Error> { | |
| 162 | + let pic = self.next_picture(force_keyframe); | |
| 163 | + let out = self | |
| 164 | + .session | |
| 165 | + .submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?; | |
| 166 | + Ok(out.map(|bytes| self.coded(bytes))) | |
| 167 | + } | |
| 168 | + | |
| 118 | 169 | /// Encodes one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes), box-downscaled to the encoder size on the GPU. |
| 119 | 170 | pub fn encode_rgb( |
| 120 | 171 | &mut self, |
| @@ -125,9 +176,21 @@ impl Av1Encoder { | ||
| 125 | 176 | bgr: bool, |
| 126 | 177 | force_keyframe: bool, |
| 127 | 178 | ) -> Result<CodedFrame, Error> { |
| 179 | + let first = self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, force_keyframe)?; | |
| 180 | + let rest = self.flush()?; | |
| 181 | + last_frame(first, rest) | |
| 182 | + } | |
| 183 | + | |
| 184 | + /// Submits one DMA-BUF frame of the source size without waiting. | |
| 185 | + #[cfg(target_os = "linux")] | |
| 186 | + pub fn submit_dmabuf( | |
| 187 | + &mut self, | |
| 188 | + src: &DmaBuf<'_>, | |
| 189 | + force_keyframe: bool, | |
| 190 | + ) -> Result<Option<CodedFrame>, Error> { | |
| 128 | 191 | let pic = self.next_picture(force_keyframe); |
| 129 | - let frame = self.session.encode_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?; | |
| 130 | - Ok(self.finish(&pic, frame)) | |
| 192 | + let out = self.session.submit_dmabuf(src, &pic)?; | |
| 193 | + Ok(out.map(|bytes| self.coded(bytes))) | |
| 131 | 194 | } |
| 132 | 195 | |
| 133 | 196 | /// Encodes one DMA-BUF frame of the source size (BGRx if `bgr`, else RGBx), box-downscaled to the encoder size on the GPU. |
| @@ -137,9 +200,9 @@ impl Av1Encoder { | ||
| 137 | 200 | src: &DmaBuf<'_>, |
| 138 | 201 | force_keyframe: bool, |
| 139 | 202 | ) -> Result<CodedFrame, Error> { |
| 140 | - let pic = self.next_picture(force_keyframe); | |
| 141 | - let frame = self.session.encode_dmabuf(src, &pic)?; | |
| 142 | - Ok(self.finish(&pic, frame)) | |
| 203 | + let first = self.submit_dmabuf(src, force_keyframe)?; | |
| 204 | + let rest = self.flush()?; | |
| 205 | + last_frame(first, rest) | |
| 143 | 206 | } |
| 144 | 207 | |
| 145 | 208 | fn next_picture(&mut self, force_keyframe: bool) -> Av1Picture { |
| @@ -151,28 +214,28 @@ impl Av1Encoder { | ||
| 151 | 214 | }; |
| 152 | 215 | let reference = if keyframe { None } else { self.reference }; |
| 153 | 216 | let slot = reference.map_or(0, |r| 1 - r.slot); |
| 154 | - Av1Picture { | |
| 217 | + let pic = Av1Picture { | |
| 155 | 218 | key: keyframe, |
| 156 | 219 | order_hint: self.order_hint, |
| 157 | 220 | slot, |
| 158 | 221 | reference, |
| 159 | - } | |
| 160 | - } | |
| 161 | - | |
| 162 | - fn finish(&mut self, pic: &Av1Picture, frame: Vec<u8>) -> CodedFrame { | |
| 222 | + }; | |
| 163 | 223 | self.reference = Some(Av1Ref { |
| 164 | 224 | slot: pic.slot, |
| 165 | 225 | order_hint: pic.order_hint, |
| 166 | 226 | }); |
| 167 | - self.position = if pic.key { 1 } else { self.position + 1 }; | |
| 227 | + self.position = if keyframe { 1 } else { self.position + 1 }; | |
| 228 | + self.flight.push(keyframe); | |
| 229 | + pic | |
| 230 | + } | |
| 231 | + | |
| 232 | + fn coded(&mut self, bytes: Vec<u8>) -> CodedFrame { | |
| 233 | + let keyframe = self.flight.pop(); | |
| 168 | 234 | let mut data = TEMPORAL_DELIMITER.to_vec(); |
| 169 | - if pic.key { | |
| 235 | + if keyframe { | |
| 170 | 236 | data.extend_from_slice(&self.sequence_header); |
| 171 | 237 | } |
| 172 | - data.extend_from_slice(&frame); | |
| 173 | - CodedFrame { | |
| 174 | - data, | |
| 175 | - keyframe: pic.key, | |
| 176 | - } | |
| 238 | + data.extend_from_slice(&bytes); | |
| 239 | + CodedFrame { data, keyframe } | |
| 177 | 240 | } |
| 178 | 241 | } |
crates/ec-vk/src/h265.rsmodified+92 -29
| @@ -2,7 +2,7 @@ use vk_video_ffi::{H265EncodeConfig, H265EncodeSession, H265Picture, H265Ref}; | ||
| 2 | 2 | |
| 3 | 3 | #[cfg(target_os = "linux")] |
| 4 | 4 | use crate::DmaBuf; |
| 5 | -use crate::{CodedFrame, Error, Gpu, RateControl}; | |
| 5 | +use crate::{CodedFrame, Error, Flight, Gpu, RateControl, last_frame}; | |
| 6 | 6 | |
| 7 | 7 | /// H.265 encoder settings. |
| 8 | 8 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| @@ -33,6 +33,7 @@ pub struct H265Encoder { | ||
| 33 | 33 | reference: Option<H265Ref>, |
| 34 | 34 | uv: Vec<u8>, |
| 35 | 35 | uv16: Vec<u16>, |
| 36 | + flight: Flight, | |
| 36 | 37 | } |
| 37 | 38 | |
| 38 | 39 | impl H265Encoder { |
| @@ -63,17 +64,18 @@ impl H265Encoder { | ||
| 63 | 64 | reference: None, |
| 64 | 65 | uv: vec![0; cfg.width as usize * cfg.height as usize / 2], |
| 65 | 66 | uv16: vec![0; cfg.width as usize * cfg.height as usize / 2], |
| 67 | + flight: Flight::default(), | |
| 66 | 68 | }) |
| 67 | 69 | } |
| 68 | 70 | |
| 69 | - /// Encodes one I420 frame; `force_keyframe` makes it an IDR and restarts the GOP. | |
| 70 | - pub fn encode( | |
| 71 | + /// Submits one I420 frame without waiting; returns the oldest frame once a second one is queued. | |
| 72 | + pub fn submit( | |
| 71 | 73 | &mut self, |
| 72 | 74 | y: &[u8], |
| 73 | 75 | u: &[u8], |
| 74 | 76 | v: &[u8], |
| 75 | 77 | force_keyframe: bool, |
| 76 | - ) -> Result<CodedFrame, Error> { | |
| 78 | + ) -> Result<Option<CodedFrame>, Error> { | |
| 77 | 79 | let chroma = self.width * self.height / 4; |
| 78 | 80 | if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma { |
| 79 | 81 | return Err(Error::Invalid("I420 plane size".into())); |
| @@ -83,18 +85,31 @@ impl H265Encoder { | ||
| 83 | 85 | pair[1] = v[i]; |
| 84 | 86 | } |
| 85 | 87 | let pic = self.next_picture(force_keyframe); |
| 86 | - let slice = self.session.encode(y, &self.uv, &pic)?; | |
| 87 | - Ok(self.finish(&pic, slice)) | |
| 88 | + let out = self.session.submit(y, &self.uv, &pic)?; | |
| 89 | + Ok(out.map(|bytes| self.coded(bytes))) | |
| 88 | 90 | } |
| 89 | 91 | |
| 90 | - /// Encodes one 10-bit I420 frame of a 10-bit encoder; `force_keyframe` makes it IDR and restarts the GOP. | |
| 91 | - pub fn encode_16( | |
| 92 | + /// Encodes one I420 frame; `force_keyframe` makes it an IDR and restarts the GOP. | |
| 93 | + pub fn encode( | |
| 94 | + &mut self, | |
| 95 | + y: &[u8], | |
| 96 | + u: &[u8], | |
| 97 | + v: &[u8], | |
| 98 | + force_keyframe: bool, | |
| 99 | + ) -> Result<CodedFrame, Error> { | |
| 100 | + let first = self.submit(y, u, v, force_keyframe)?; | |
| 101 | + let rest = self.flush()?; | |
| 102 | + last_frame(first, rest) | |
| 103 | + } | |
| 104 | + | |
| 105 | + /// Submits one 10-bit I420 frame of a 10-bit encoder without waiting. | |
| 106 | + pub fn submit_16( | |
| 92 | 107 | &mut self, |
| 93 | 108 | y: &[u16], |
| 94 | 109 | u: &[u16], |
| 95 | 110 | v: &[u16], |
| 96 | 111 | force_keyframe: bool, |
| 97 | - ) -> Result<CodedFrame, Error> { | |
| 112 | + ) -> Result<Option<CodedFrame>, Error> { | |
| 98 | 113 | let chroma = self.width * self.height / 4; |
| 99 | 114 | if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma { |
| 100 | 115 | return Err(Error::Invalid("I420 plane size".into())); |
| @@ -104,8 +119,27 @@ impl H265Encoder { | ||
| 104 | 119 | pair[1] = v[i]; |
| 105 | 120 | } |
| 106 | 121 | let pic = self.next_picture(force_keyframe); |
| 107 | - let slice = self.session.encode_16(y, &self.uv16, &pic)?; | |
| 108 | - Ok(self.finish(&pic, slice)) | |
| 122 | + let out = self.session.submit_16(y, &self.uv16, &pic)?; | |
| 123 | + Ok(out.map(|bytes| self.coded(bytes))) | |
| 124 | + } | |
| 125 | + | |
| 126 | + /// Encodes one 10-bit I420 frame of a 10-bit encoder; `force_keyframe` makes it IDR and restarts the GOP. | |
| 127 | + pub fn encode_16( | |
| 128 | + &mut self, | |
| 129 | + y: &[u16], | |
| 130 | + u: &[u16], | |
| 131 | + v: &[u16], | |
| 132 | + force_keyframe: bool, | |
| 133 | + ) -> Result<CodedFrame, Error> { | |
| 134 | + let first = self.submit_16(y, u, v, force_keyframe)?; | |
| 135 | + let rest = self.flush()?; | |
| 136 | + last_frame(first, rest) | |
| 137 | + } | |
| 138 | + | |
| 139 | + /// Waits for every submitted frame and returns them in order. | |
| 140 | + pub fn flush(&mut self) -> Result<Vec<CodedFrame>, Error> { | |
| 141 | + let bytes = self.session.flush()?; | |
| 142 | + Ok(bytes.into_iter().map(|b| self.coded(b)).collect()) | |
| 109 | 143 | } |
| 110 | 144 | |
| 111 | 145 | /// Changes bitrate or frame rate; takes effect on the next frame. |
| @@ -113,6 +147,23 @@ impl H265Encoder { | ||
| 113 | 147 | Ok(self.session.set_rate(rate, fps)?) |
| 114 | 148 | } |
| 115 | 149 | |
| 150 | + /// Submits one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes) without waiting. | |
| 151 | + pub fn submit_rgb( | |
| 152 | + &mut self, | |
| 153 | + rgb: &[u8], | |
| 154 | + src_width: u32, | |
| 155 | + src_height: u32, | |
| 156 | + stride_bytes: u32, | |
| 157 | + bgr: bool, | |
| 158 | + force_keyframe: bool, | |
| 159 | + ) -> Result<Option<CodedFrame>, Error> { | |
| 160 | + let pic = self.next_picture(force_keyframe); | |
| 161 | + let out = self | |
| 162 | + .session | |
| 163 | + .submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?; | |
| 164 | + Ok(out.map(|bytes| self.coded(bytes))) | |
| 165 | + } | |
| 166 | + | |
| 116 | 167 | /// Encodes one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes), box-downscaled to the encoder size on the GPU. |
| 117 | 168 | pub fn encode_rgb( |
| 118 | 169 | &mut self, |
| @@ -123,9 +174,21 @@ impl H265Encoder { | ||
| 123 | 174 | bgr: bool, |
| 124 | 175 | force_keyframe: bool, |
| 125 | 176 | ) -> Result<CodedFrame, Error> { |
| 177 | + let first = self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, force_keyframe)?; | |
| 178 | + let rest = self.flush()?; | |
| 179 | + last_frame(first, rest) | |
| 180 | + } | |
| 181 | + | |
| 182 | + /// Submits one DMA-BUF frame of the source size without waiting. | |
| 183 | + #[cfg(target_os = "linux")] | |
| 184 | + pub fn submit_dmabuf( | |
| 185 | + &mut self, | |
| 186 | + src: &DmaBuf<'_>, | |
| 187 | + force_keyframe: bool, | |
| 188 | + ) -> Result<Option<CodedFrame>, Error> { | |
| 126 | 189 | let pic = self.next_picture(force_keyframe); |
| 127 | - let slice = self.session.encode_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?; | |
| 128 | - Ok(self.finish(&pic, slice)) | |
| 190 | + let out = self.session.submit_dmabuf(src, &pic)?; | |
| 191 | + Ok(out.map(|bytes| self.coded(bytes))) | |
| 129 | 192 | } |
| 130 | 193 | |
| 131 | 194 | /// Encodes one DMA-BUF frame of the source size (BGRx if `bgr`, else RGBx), box-downscaled to the encoder size on the GPU. |
| @@ -135,9 +198,9 @@ impl H265Encoder { | ||
| 135 | 198 | src: &DmaBuf<'_>, |
| 136 | 199 | force_keyframe: bool, |
| 137 | 200 | ) -> Result<CodedFrame, Error> { |
| 138 | - let pic = self.next_picture(force_keyframe); | |
| 139 | - let slice = self.session.encode_dmabuf(src, &pic)?; | |
| 140 | - Ok(self.finish(&pic, slice)) | |
| 201 | + let first = self.submit_dmabuf(src, force_keyframe)?; | |
| 202 | + let rest = self.flush()?; | |
| 203 | + last_frame(first, rest) | |
| 141 | 204 | } |
| 142 | 205 | |
| 143 | 206 | fn next_picture(&mut self, force_keyframe: bool) -> H265Picture { |
| @@ -145,28 +208,28 @@ impl H265Encoder { | ||
| 145 | 208 | self.poc = if keyframe { 0 } else { self.poc + 1 }; |
| 146 | 209 | let reference = if keyframe { None } else { self.reference }; |
| 147 | 210 | let slot = reference.map_or(0, |r| 1 - r.slot); |
| 148 | - H265Picture { | |
| 211 | + let pic = H265Picture { | |
| 149 | 212 | idr: keyframe, |
| 150 | 213 | poc: self.poc, |
| 151 | 214 | slot, |
| 152 | 215 | reference, |
| 153 | - } | |
| 154 | - } | |
| 155 | - | |
| 156 | - fn finish(&mut self, pic: &H265Picture, slice: Vec<u8>) -> CodedFrame { | |
| 216 | + }; | |
| 157 | 217 | self.reference = Some(H265Ref { |
| 158 | 218 | slot: pic.slot, |
| 159 | 219 | poc: pic.poc, |
| 160 | 220 | }); |
| 161 | - self.position = if pic.idr { 1 } else { self.position + 1 }; | |
| 162 | - let data = if pic.idr { | |
| 163 | - [self.parameter_sets.as_slice(), slice.as_slice()].concat() | |
| 221 | + self.position = if keyframe { 1 } else { self.position + 1 }; | |
| 222 | + self.flight.push(keyframe); | |
| 223 | + pic | |
| 224 | + } | |
| 225 | + | |
| 226 | + fn coded(&mut self, bytes: Vec<u8>) -> CodedFrame { | |
| 227 | + let keyframe = self.flight.pop(); | |
| 228 | + let data = if keyframe { | |
| 229 | + [self.parameter_sets.as_slice(), bytes.as_slice()].concat() | |
| 164 | 230 | } else { |
| 165 | - slice | |
| 231 | + bytes | |
| 166 | 232 | }; |
| 167 | - CodedFrame { | |
| 168 | - data, | |
| 169 | - keyframe: pic.idr, | |
| 170 | - } | |
| 233 | + CodedFrame { data, keyframe } | |
| 171 | 234 | } |
| 172 | 235 | } |
crates/ec-vk/src/lib.rsmodified+99 -24
| @@ -2,6 +2,8 @@ | ||
| 2 | 2 | #![forbid(unsafe_code)] |
| 3 | 3 | #![deny(missing_docs)] |
| 4 | 4 | |
| 5 | +use std::collections::VecDeque; | |
| 6 | + | |
| 5 | 7 | use vk_video_ffi::{H264EncodeConfig, H264EncodeSession, H264Picture, H264Ref}; |
| 6 | 8 | |
| 7 | 9 | mod av1; |
| @@ -48,6 +50,29 @@ pub struct CodedFrame { | ||
| 48 | 50 | pub keyframe: bool, |
| 49 | 51 | } |
| 50 | 52 | |
| 53 | +#[derive(Default)] | |
| 54 | +pub(crate) struct Flight(VecDeque<bool>); | |
| 55 | + | |
| 56 | +impl Flight { | |
| 57 | + pub(crate) fn push(&mut self, keyframe: bool) { | |
| 58 | + self.0.push_back(keyframe); | |
| 59 | + } | |
| 60 | + | |
| 61 | + pub(crate) fn pop(&mut self) -> bool { | |
| 62 | + self.0.pop_front().unwrap_or(false) | |
| 63 | + } | |
| 64 | +} | |
| 65 | + | |
| 66 | +pub(crate) fn last_frame( | |
| 67 | + first: Option<CodedFrame>, | |
| 68 | + rest: Vec<CodedFrame>, | |
| 69 | +) -> Result<CodedFrame, Error> { | |
| 70 | + rest.into_iter() | |
| 71 | + .last() | |
| 72 | + .or(first) | |
| 73 | + .ok_or_else(|| Error::Invalid("no coded frame".into())) | |
| 74 | +} | |
| 75 | + | |
| 51 | 76 | /// H.264 encoder: GOP, frame_num, POC and DPB slot bookkeeping over [`H264EncodeSession`]. |
| 52 | 77 | pub struct H264Encoder { |
| 53 | 78 | session: H264EncodeSession, |
| @@ -61,6 +86,7 @@ pub struct H264Encoder { | ||
| 61 | 86 | idr_pic_id: u16, |
| 62 | 87 | reference: Option<H264Ref>, |
| 63 | 88 | uv: Vec<u8>, |
| 89 | + flight: Flight, | |
| 64 | 90 | } |
| 65 | 91 | |
| 66 | 92 | impl H264Encoder { |
| @@ -92,17 +118,18 @@ impl H264Encoder { | ||
| 92 | 118 | idr_pic_id: 0, |
| 93 | 119 | reference: None, |
| 94 | 120 | uv: vec![0; cfg.width as usize * cfg.height as usize / 2], |
| 121 | + flight: Flight::default(), | |
| 95 | 122 | }) |
| 96 | 123 | } |
| 97 | 124 | |
| 98 | - /// Encodes one I420 frame; `force_keyframe` makes it an IDR and restarts the GOP. | |
| 99 | - pub fn encode( | |
| 125 | + /// Submits one I420 frame without waiting; returns the oldest frame once a second one is queued. | |
| 126 | + pub fn submit( | |
| 100 | 127 | &mut self, |
| 101 | 128 | y: &[u8], |
| 102 | 129 | u: &[u8], |
| 103 | 130 | v: &[u8], |
| 104 | 131 | force_keyframe: bool, |
| 105 | - ) -> Result<CodedFrame, Error> { | |
| 132 | + ) -> Result<Option<CodedFrame>, Error> { | |
| 106 | 133 | let chroma = self.width * self.height / 4; |
| 107 | 134 | if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma { |
| 108 | 135 | return Err(Error::Invalid("I420 plane size".into())); |
| @@ -112,8 +139,27 @@ impl H264Encoder { | ||
| 112 | 139 | pair[1] = v[i]; |
| 113 | 140 | } |
| 114 | 141 | let pic = self.next_picture(force_keyframe); |
| 115 | - let slice = self.session.encode(y, &self.uv, &pic)?; | |
| 116 | - Ok(self.finish(&pic, slice)) | |
| 142 | + let out = self.session.submit(y, &self.uv, &pic)?; | |
| 143 | + Ok(out.map(|bytes| self.coded(bytes))) | |
| 144 | + } | |
| 145 | + | |
| 146 | + /// Encodes one I420 frame; `force_keyframe` makes it an IDR and restarts the GOP. | |
| 147 | + pub fn encode( | |
| 148 | + &mut self, | |
| 149 | + y: &[u8], | |
| 150 | + u: &[u8], | |
| 151 | + v: &[u8], | |
| 152 | + force_keyframe: bool, | |
| 153 | + ) -> Result<CodedFrame, Error> { | |
| 154 | + let first = self.submit(y, u, v, force_keyframe)?; | |
| 155 | + let rest = self.flush()?; | |
| 156 | + last_frame(first, rest) | |
| 157 | + } | |
| 158 | + | |
| 159 | + /// Waits for every submitted frame and returns them in order. | |
| 160 | + pub fn flush(&mut self) -> Result<Vec<CodedFrame>, Error> { | |
| 161 | + let bytes = self.session.flush()?; | |
| 162 | + Ok(bytes.into_iter().map(|b| self.coded(b)).collect()) | |
| 117 | 163 | } |
| 118 | 164 | |
| 119 | 165 | /// Changes bitrate or frame rate; takes effect on the next frame. |
| @@ -121,6 +167,23 @@ impl H264Encoder { | ||
| 121 | 167 | Ok(self.session.set_rate(rate, fps)?) |
| 122 | 168 | } |
| 123 | 169 | |
| 170 | + /// Submits one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes) without waiting. | |
| 171 | + pub fn submit_rgb( | |
| 172 | + &mut self, | |
| 173 | + rgb: &[u8], | |
| 174 | + src_width: u32, | |
| 175 | + src_height: u32, | |
| 176 | + stride_bytes: u32, | |
| 177 | + bgr: bool, | |
| 178 | + force_keyframe: bool, | |
| 179 | + ) -> Result<Option<CodedFrame>, Error> { | |
| 180 | + let pic = self.next_picture(force_keyframe); | |
| 181 | + let out = self | |
| 182 | + .session | |
| 183 | + .submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?; | |
| 184 | + Ok(out.map(|bytes| self.coded(bytes))) | |
| 185 | + } | |
| 186 | + | |
| 124 | 187 | /// Encodes one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes), box-downscaled to the encoder size on the GPU. |
| 125 | 188 | pub fn encode_rgb( |
| 126 | 189 | &mut self, |
| @@ -131,9 +194,21 @@ impl H264Encoder { | ||
| 131 | 194 | bgr: bool, |
| 132 | 195 | force_keyframe: bool, |
| 133 | 196 | ) -> Result<CodedFrame, Error> { |
| 197 | + let first = self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, force_keyframe)?; | |
| 198 | + let rest = self.flush()?; | |
| 199 | + last_frame(first, rest) | |
| 200 | + } | |
| 201 | + | |
| 202 | + /// Submits one DMA-BUF frame of the source size without waiting. | |
| 203 | + #[cfg(target_os = "linux")] | |
| 204 | + pub fn submit_dmabuf( | |
| 205 | + &mut self, | |
| 206 | + src: &DmaBuf<'_>, | |
| 207 | + force_keyframe: bool, | |
| 208 | + ) -> Result<Option<CodedFrame>, Error> { | |
| 134 | 209 | let pic = self.next_picture(force_keyframe); |
| 135 | - let slice = self.session.encode_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?; | |
| 136 | - Ok(self.finish(&pic, slice)) | |
| 210 | + let out = self.session.submit_dmabuf(src, &pic)?; | |
| 211 | + Ok(out.map(|bytes| self.coded(bytes))) | |
| 137 | 212 | } |
| 138 | 213 | |
| 139 | 214 | /// Encodes one DMA-BUF frame of the source size (BGRx if `bgr`, else RGBx), box-downscaled to the encoder size on the GPU. |
| @@ -143,9 +218,9 @@ impl H264Encoder { | ||
| 143 | 218 | src: &DmaBuf<'_>, |
| 144 | 219 | force_keyframe: bool, |
| 145 | 220 | ) -> Result<CodedFrame, Error> { |
| 146 | - let pic = self.next_picture(force_keyframe); | |
| 147 | - let slice = self.session.encode_dmabuf(src, &pic)?; | |
| 148 | - Ok(self.finish(&pic, slice)) | |
| 221 | + let first = self.submit_dmabuf(src, force_keyframe)?; | |
| 222 | + let rest = self.flush()?; | |
| 223 | + last_frame(first, rest) | |
| 149 | 224 | } |
| 150 | 225 | |
| 151 | 226 | fn next_picture(&mut self, force_keyframe: bool) -> H264Picture { |
| @@ -159,34 +234,34 @@ impl H264Encoder { | ||
| 159 | 234 | } |
| 160 | 235 | let reference = if keyframe { None } else { self.reference }; |
| 161 | 236 | let slot = reference.map_or(0, |r| 1 - r.slot); |
| 162 | - H264Picture { | |
| 237 | + let pic = H264Picture { | |
| 163 | 238 | idr: keyframe, |
| 164 | 239 | idr_pic_id: self.idr_pic_id, |
| 165 | 240 | frame_num: self.frame_num, |
| 166 | 241 | poc: self.poc, |
| 167 | 242 | slot, |
| 168 | 243 | reference, |
| 169 | - } | |
| 170 | - } | |
| 171 | - | |
| 172 | - fn finish(&mut self, pic: &H264Picture, slice: Vec<u8>) -> CodedFrame { | |
| 244 | + }; | |
| 173 | 245 | self.reference = Some(H264Ref { |
| 174 | 246 | slot: pic.slot, |
| 175 | 247 | frame_num: pic.frame_num, |
| 176 | 248 | poc: pic.poc, |
| 177 | 249 | }); |
| 178 | - self.position = if pic.idr { 1 } else { self.position + 1 }; | |
| 179 | - if pic.idr { | |
| 250 | + self.position = if keyframe { 1 } else { self.position + 1 }; | |
| 251 | + if keyframe { | |
| 180 | 252 | self.idr_pic_id = self.idr_pic_id.wrapping_add(1); |
| 181 | 253 | } |
| 182 | - let data = if pic.idr { | |
| 183 | - [self.parameter_sets.as_slice(), slice.as_slice()].concat() | |
| 254 | + self.flight.push(keyframe); | |
| 255 | + pic | |
| 256 | + } | |
| 257 | + | |
| 258 | + fn coded(&mut self, bytes: Vec<u8>) -> CodedFrame { | |
| 259 | + let keyframe = self.flight.pop(); | |
| 260 | + let data = if keyframe { | |
| 261 | + [self.parameter_sets.as_slice(), bytes.as_slice()].concat() | |
| 184 | 262 | } else { |
| 185 | - slice | |
| 263 | + bytes | |
| 186 | 264 | }; |
| 187 | - CodedFrame { | |
| 188 | - data, | |
| 189 | - keyframe: pic.idr, | |
| 190 | - } | |
| 265 | + CodedFrame { data, keyframe } | |
| 191 | 266 | } |
| 192 | 267 | } |
shims/vk-video-ffi/src/av1_encode.rsmodified+49 -11
| @@ -224,8 +224,8 @@ impl Av1EncodeSession { | ||
| 224 | 224 | self.seq.clone() |
| 225 | 225 | } |
| 226 | 226 | |
| 227 | - /// Encodes one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) and returns its frame OBUs. | |
| 228 | - pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &Av1Picture) -> Result<Vec<u8>, Error> { | |
| 227 | + /// Submits one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) without waiting; returns the oldest picture once two are in flight. | |
| 228 | + pub fn submit(&mut self, y: &[u8], uv: &[u8], pic: &Av1Picture) -> Result<Option<Vec<u8>>, Error> { | |
| 229 | 229 | if y.len() != self.enc.input.0 * self.enc.input.1 |
| 230 | 230 | || uv.len() != self.enc.input.0 * self.enc.input.1 / 2 |
| 231 | 231 | { |
| @@ -236,8 +236,8 @@ impl Av1EncodeSession { | ||
| 236 | 236 | self.encode_uploaded(pic) |
| 237 | 237 | } |
| 238 | 238 | |
| 239 | - /// Encodes one 10-bit picture (y: width*height, uv: interleaved CbCr width*height/2, samples in the low 10 bits) of a 10-bit session and returns its frame OBUs. | |
| 240 | - pub fn encode_16(&mut self, y: &[u16], uv: &[u16], pic: &Av1Picture) -> Result<Vec<u8>, Error> { | |
| 239 | + /// Submits one 10-bit picture (y: width*height, uv: interleaved CbCr width*height/2, samples in the low 10 bits) of a 10-bit session without waiting; returns the oldest picture once two are in flight. | |
| 240 | + pub fn submit_16(&mut self, y: &[u16], uv: &[u16], pic: &Av1Picture) -> Result<Option<Vec<u8>>, Error> { | |
| 241 | 241 | if y.len() != self.enc.input.0 * self.enc.input.1 |
| 242 | 242 | || uv.len() != self.enc.input.0 * self.enc.input.1 / 2 |
| 243 | 243 | { |
| @@ -249,7 +249,7 @@ impl Av1EncodeSession { | ||
| 249 | 249 | } |
| 250 | 250 | |
| 251 | 251 | /// Encodes one packed RGB picture (src_width x src_height, row stride in bytes, BGRx or RGBx byte order), box-downscaled to the encoder size on the GPU. |
| 252 | - pub fn encode_rgb( | |
| 252 | + pub fn submit_rgb( | |
| 253 | 253 | &mut self, |
| 254 | 254 | rgb: &[u8], |
| 255 | 255 | src_width: u32, |
| @@ -257,7 +257,7 @@ impl Av1EncodeSession { | ||
| 257 | 257 | stride_bytes: u32, |
| 258 | 258 | bgr: bool, |
| 259 | 259 | pic: &Av1Picture, |
| 260 | - ) -> Result<Vec<u8>, Error> { | |
| 260 | + ) -> Result<Option<Vec<u8>>, Error> { | |
| 261 | 261 | self.check(pic)?; |
| 262 | 262 | let src = (src_width as usize, src_height as usize); |
| 263 | 263 | check_rgb( |
| @@ -277,7 +277,7 @@ impl Av1EncodeSession { | ||
| 277 | 277 | } |
| 278 | 278 | /// Encodes one picture from a DMA-BUF: BGRx or RGBx box-downscaled to the encoder size, or NV12 or P010 of the encoder size. |
| 279 | 279 | #[cfg(target_os = "linux")] |
| 280 | - pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &Av1Picture) -> Result<Vec<u8>, Error> { | |
| 280 | + pub fn submit_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &Av1Picture) -> Result<Option<Vec<u8>>, Error> { | |
| 281 | 281 | self.check(pic)?; |
| 282 | 282 | self.enc.upload_dmabuf(src)?; |
| 283 | 283 | self.encode_uploaded(pic) |
| @@ -289,7 +289,7 @@ impl Av1EncodeSession { | ||
| 289 | 289 | self.enc.import_count() |
| 290 | 290 | } |
| 291 | 291 | |
| 292 | - fn encode_uploaded(&mut self, pic: &Av1Picture) -> Result<Vec<u8>, Error> { | |
| 292 | + fn encode_uploaded(&mut self, pic: &Av1Picture) -> Result<Option<Vec<u8>>, Error> { | |
| 293 | 293 | let extent = self.enc.extent; |
| 294 | 294 | |
| 295 | 295 | let refresh: u8 = if pic.key { 0xff } else { 1 << pic.slot }; |
| @@ -297,7 +297,7 @@ impl Av1EncodeSession { | ||
| 297 | 297 | picture_resource(self.enc.dpb[0].view, extent), |
| 298 | 298 | picture_resource(self.enc.dpb[1].view, extent), |
| 299 | 299 | ]; |
| 300 | - let src_pr = picture_resource(self.enc.src.view, extent); | |
| 300 | + let src_pr = picture_resource(self.enc.src_view(), extent); | |
| 301 | 301 | |
| 302 | 302 | let key_of = self.slot_key; |
| 303 | 303 | let mut new_std = zeroed::<vk::video::StdVideoEncodeAV1ReferenceInfo>(); |
| @@ -399,7 +399,7 @@ impl Av1EncodeSession { | ||
| 399 | 399 | }; |
| 400 | 400 | |
| 401 | 401 | let encode = vk::VideoEncodeInfoKHR::builder() |
| 402 | - .dst_buffer(self.enc.bitstream.buffer) | |
| 402 | + .dst_buffer(self.enc.bitstream_buffer()) | |
| 403 | 403 | .dst_buffer_offset(0) |
| 404 | 404 | .dst_buffer_range(self.enc.bitstream_len) |
| 405 | 405 | .src_picture_resource(src_pr) |
| @@ -412,7 +412,7 @@ impl Av1EncodeSession { | ||
| 412 | 412 | let mut chain = RateChain::new(self.enc.rate, self.enc.fps); |
| 413 | 413 | let out = self |
| 414 | 414 | .enc |
| 415 | - .run(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)?; | |
| 415 | + .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)?; | |
| 416 | 416 | for i in 0..DPB_SLOTS { |
| 417 | 417 | if refresh >> i & 1 == 1 { |
| 418 | 418 | self.slot_key[i] = pic.key; |
| @@ -426,6 +426,44 @@ impl Av1EncodeSession { | ||
| 426 | 426 | Ok(out) |
| 427 | 427 | } |
| 428 | 428 | |
| 429 | + /// Encodes one picture synchronously and returns its coded bytes. | |
| 430 | + pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &Av1Picture) -> Result<Vec<u8>, Error> { | |
| 431 | + self.submit(y, uv, pic)?; | |
| 432 | + self.enc.flush_last() | |
| 433 | + } | |
| 434 | + | |
| 435 | + /// Encodes one picture synchronously and returns its coded bytes. | |
| 436 | + pub fn encode_16(&mut self, y: &[u16], uv: &[u16], pic: &Av1Picture) -> Result<Vec<u8>, Error> { | |
| 437 | + self.submit_16(y, uv, pic)?; | |
| 438 | + self.enc.flush_last() | |
| 439 | + } | |
| 440 | + | |
| 441 | + /// Encodes one picture synchronously and returns its coded bytes. | |
| 442 | + pub fn encode_rgb( | |
| 443 | + &mut self, | |
| 444 | + rgb: &[u8], | |
| 445 | + src_width: u32, | |
| 446 | + src_height: u32, | |
| 447 | + stride_bytes: u32, | |
| 448 | + bgr: bool, | |
| 449 | + pic: &Av1Picture, | |
| 450 | + ) -> Result<Vec<u8>, Error> { | |
| 451 | + self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?; | |
| 452 | + self.enc.flush_last() | |
| 453 | + } | |
| 454 | + | |
| 455 | + #[cfg(target_os = "linux")] | |
| 456 | + /// Encodes one picture synchronously and returns its coded bytes. | |
| 457 | + pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &Av1Picture) -> Result<Vec<u8>, Error> { | |
| 458 | + self.submit_dmabuf(src, pic)?; | |
| 459 | + self.enc.flush_last() | |
| 460 | + } | |
| 461 | + | |
| 462 | + /// Waits for queued pictures and returns their coded bytes in order. | |
| 463 | + pub fn flush(&mut self) -> Result<Vec<Vec<u8>>, Error> { | |
| 464 | + self.enc.flush() | |
| 465 | + } | |
| 466 | + | |
| 429 | 467 | /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change. |
| 430 | 468 | pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> { |
| 431 | 469 | self.enc.set_rate(rate, fps) |
shims/vk-video-ffi/src/dmabuf.rsmodified+14 -6
| @@ -213,11 +213,12 @@ impl Key { | ||
| 213 | 213 | |
| 214 | 214 | pub(crate) struct Import { |
| 215 | 215 | pub(crate) image: vk::Image, |
| 216 | + id: u64, | |
| 216 | 217 | memories: Vec<vk::DeviceMemory>, |
| 217 | 218 | } |
| 218 | 219 | |
| 219 | 220 | impl Import { |
| 220 | - fn new(gpu: &Gpu, src: &DmaBuf) -> Result<Self, Error> { | |
| 221 | + fn new(gpu: &Gpu, src: &DmaBuf, id: u64) -> Result<Self, Error> { | |
| 221 | 222 | check(gpu)?; |
| 222 | 223 | validate(src)?; |
| 223 | 224 | let d = gpu.device(); |
| @@ -271,7 +272,7 @@ impl Import { | ||
| 271 | 272 | .build(); |
| 272 | 273 | let image = unsafe { vk(d.create_image(&info, None), "vkCreateImage")? }; |
| 273 | 274 | match bind(gpu, image, src) { |
| 274 | - Ok(memories) => Ok(Import { image, memories }), | |
| 275 | + Ok(memories) => Ok(Import { image, id, memories }), | |
| 275 | 276 | Err(e) => { |
| 276 | 277 | unsafe { d.destroy_image(image, None) }; |
| 277 | 278 | Err(e) |
| @@ -292,11 +293,12 @@ impl Import { | ||
| 292 | 293 | #[derive(Default)] |
| 293 | 294 | pub(crate) struct ImportCache { |
| 294 | 295 | entries: Vec<(Key, Import)>, |
| 296 | + next_id: u64, | |
| 295 | 297 | pub(crate) count: usize, |
| 296 | 298 | } |
| 297 | 299 | |
| 298 | 300 | impl ImportCache { |
| 299 | - pub(crate) fn get(&mut self, gpu: &Gpu, src: &DmaBuf) -> Result<vk::Image, Error> { | |
| 301 | + pub(crate) fn get(&mut self, gpu: &Gpu, src: &DmaBuf, busy: &[u64]) -> Result<(vk::Image, u64), Error> { | |
| 300 | 302 | validate(src)?; |
| 301 | 303 | let key = Key::new(src)?; |
| 302 | 304 | match self.entries.iter().position(|(k, _)| *k == key) { |
| @@ -306,17 +308,23 @@ impl ImportCache { | ||
| 306 | 308 | } |
| 307 | 309 | None => { |
| 308 | 310 | if self.entries.len() == CACHE_SIZE { |
| 309 | - let (_, old) = self.entries.remove(0); | |
| 311 | + let i = self | |
| 312 | + .entries | |
| 313 | + .iter() | |
| 314 | + .position(|(_, import)| !busy.contains(&import.id)) | |
| 315 | + .ok_or_else(|| Error::Invalid("DMA-BUF import cache is full of in-flight imports".into()))?; | |
| 316 | + let (_, old) = self.entries.remove(i); | |
| 310 | 317 | old.destroy(gpu.device()); |
| 311 | 318 | } |
| 312 | - let import = Import::new(gpu, src)?; | |
| 319 | + self.next_id += 1; | |
| 320 | + let import = Import::new(gpu, src, self.next_id)?; | |
| 313 | 321 | self.count += 1; |
| 314 | 322 | self.entries.push((key, import)); |
| 315 | 323 | } |
| 316 | 324 | } |
| 317 | 325 | self.entries |
| 318 | 326 | .last() |
| 319 | - .map(|(_, import)| import.image) | |
| 327 | + .map(|(_, import)| (import.image, import.id)) | |
| 320 | 328 | .ok_or_else(|| Error::Invalid("DMA-BUF import cache".into())) |
| 321 | 329 | } |
| 322 | 330 |
shims/vk-video-ffi/src/h264_encode.rsmodified+41 -9
| @@ -253,8 +253,8 @@ impl H264EncodeSession { | ||
| 253 | 253 | ) |
| 254 | 254 | } |
| 255 | 255 | |
| 256 | - /// Encodes one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) and returns its Annex-B slice NAL units. | |
| 257 | - pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &H264Picture) -> Result<Vec<u8>, Error> { | |
| 256 | + /// Submits one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) without waiting; returns the oldest picture once two are in flight. | |
| 257 | + pub fn submit(&mut self, y: &[u8], uv: &[u8], pic: &H264Picture) -> Result<Option<Vec<u8>>, Error> { | |
| 258 | 258 | let (w, h) = self.enc.input; |
| 259 | 259 | if y.len() != w * h || uv.len() != w * h / 2 { |
| 260 | 260 | return Err(Error::Invalid("NV12 plane size".into())); |
| @@ -265,7 +265,7 @@ impl H264EncodeSession { | ||
| 265 | 265 | } |
| 266 | 266 | |
| 267 | 267 | /// Encodes one packed RGB picture (src_width x src_height, row stride in bytes, BGRx or RGBx byte order), box-downscaled to the encoder size on the GPU. |
| 268 | - pub fn encode_rgb( | |
| 268 | + pub fn submit_rgb( | |
| 269 | 269 | &mut self, |
| 270 | 270 | rgb: &[u8], |
| 271 | 271 | src_width: u32, |
| @@ -273,7 +273,7 @@ impl H264EncodeSession { | ||
| 273 | 273 | stride_bytes: u32, |
| 274 | 274 | bgr: bool, |
| 275 | 275 | pic: &H264Picture, |
| 276 | - ) -> Result<Vec<u8>, Error> { | |
| 276 | + ) -> Result<Option<Vec<u8>>, Error> { | |
| 277 | 277 | self.check(pic)?; |
| 278 | 278 | let src = (src_width as usize, src_height as usize); |
| 279 | 279 | check_rgb(self.enc.input, src, rgb, stride_bytes as usize)?; |
| @@ -289,7 +289,7 @@ impl H264EncodeSession { | ||
| 289 | 289 | |
| 290 | 290 | /// Encodes one picture from a DMA-BUF: BGRx or RGBx box-downscaled to the encoder size, or NV12 of the encoder size. |
| 291 | 291 | #[cfg(target_os = "linux")] |
| 292 | - pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H264Picture) -> Result<Vec<u8>, Error> { | |
| 292 | + pub fn submit_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H264Picture) -> Result<Option<Vec<u8>>, Error> { | |
| 293 | 293 | self.check(pic)?; |
| 294 | 294 | self.enc.upload_dmabuf(src)?; |
| 295 | 295 | self.encode_uploaded(pic) |
| @@ -301,7 +301,7 @@ impl H264EncodeSession { | ||
| 301 | 301 | self.enc.import_count() |
| 302 | 302 | } |
| 303 | 303 | |
| 304 | - fn encode_uploaded(&mut self, pic: &H264Picture) -> Result<Vec<u8>, Error> { | |
| 304 | + fn encode_uploaded(&mut self, pic: &H264Picture) -> Result<Option<Vec<u8>>, Error> { | |
| 305 | 305 | let extent = self.enc.extent; |
| 306 | 306 | |
| 307 | 307 | let primary = if pic.idr { |
| @@ -313,7 +313,7 @@ impl H264EncodeSession { | ||
| 313 | 313 | picture_resource(self.enc.dpb[0].view, extent), |
| 314 | 314 | picture_resource(self.enc.dpb[1].view, extent), |
| 315 | 315 | ]; |
| 316 | - let src_pr = picture_resource(self.enc.src.view, extent); | |
| 316 | + let src_pr = picture_resource(self.enc.src_view(), extent); | |
| 317 | 317 | |
| 318 | 318 | let new_std = reference_info(primary, pic.frame_num, pic.poc); |
| 319 | 319 | let ref_std = pic |
| @@ -400,7 +400,7 @@ impl H264EncodeSession { | ||
| 400 | 400 | .build(); |
| 401 | 401 | |
| 402 | 402 | let encode = vk::VideoEncodeInfoKHR::builder() |
| 403 | - .dst_buffer(self.enc.bitstream.buffer) | |
| 403 | + .dst_buffer(self.enc.bitstream_buffer()) | |
| 404 | 404 | .dst_buffer_offset(0) |
| 405 | 405 | .dst_buffer_range(self.enc.bitstream_len) |
| 406 | 406 | .src_picture_resource(src_pr) |
| @@ -412,7 +412,39 @@ impl H264EncodeSession { | ||
| 412 | 412 | let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1); |
| 413 | 413 | let mut chain = RateChain::new(self.enc.rate, self.enc.fps); |
| 414 | 414 | self.enc |
| 415 | - .run(&begin_slots, &mut applied.rc, &mut chain.rc, &encode) | |
| 415 | + .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode) | |
| 416 | + } | |
| 417 | + | |
| 418 | + /// Encodes one picture synchronously and returns its coded bytes. | |
| 419 | + pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &H264Picture) -> Result<Vec<u8>, Error> { | |
| 420 | + self.submit(y, uv, pic)?; | |
| 421 | + self.enc.flush_last() | |
| 422 | + } | |
| 423 | + | |
| 424 | + /// Encodes one picture synchronously and returns its coded bytes. | |
| 425 | + pub fn encode_rgb( | |
| 426 | + &mut self, | |
| 427 | + rgb: &[u8], | |
| 428 | + src_width: u32, | |
| 429 | + src_height: u32, | |
| 430 | + stride_bytes: u32, | |
| 431 | + bgr: bool, | |
| 432 | + pic: &H264Picture, | |
| 433 | + ) -> Result<Vec<u8>, Error> { | |
| 434 | + self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?; | |
| 435 | + self.enc.flush_last() | |
| 436 | + } | |
| 437 | + | |
| 438 | + #[cfg(target_os = "linux")] | |
| 439 | + /// Encodes one picture synchronously and returns its coded bytes. | |
| 440 | + pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H264Picture) -> Result<Vec<u8>, Error> { | |
| 441 | + self.submit_dmabuf(src, pic)?; | |
| 442 | + self.enc.flush_last() | |
| 443 | + } | |
| 444 | + | |
| 445 | + /// Waits for queued pictures and returns their coded bytes in order. | |
| 446 | + pub fn flush(&mut self) -> Result<Vec<Vec<u8>>, Error> { | |
| 447 | + self.enc.flush() | |
| 416 | 448 | } |
| 417 | 449 | |
| 418 | 450 | /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change. |
shims/vk-video-ffi/src/h265_encode.rsmodified+50 -12
| @@ -258,8 +258,8 @@ impl H265EncodeSession { | ||
| 258 | 258 | ) |
| 259 | 259 | } |
| 260 | 260 | |
| 261 | - /// Encodes one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) and returns its Annex-B slice NAL units. | |
| 262 | - pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &H265Picture) -> Result<Vec<u8>, Error> { | |
| 261 | + /// Submits one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) without waiting; returns the oldest picture once two are in flight. | |
| 262 | + pub fn submit(&mut self, y: &[u8], uv: &[u8], pic: &H265Picture) -> Result<Option<Vec<u8>>, Error> { | |
| 263 | 263 | if y.len() != self.enc.input.0 * self.enc.input.1 |
| 264 | 264 | || uv.len() != self.enc.input.0 * self.enc.input.1 / 2 |
| 265 | 265 | { |
| @@ -270,13 +270,13 @@ impl H265EncodeSession { | ||
| 270 | 270 | self.encode_uploaded(pic) |
| 271 | 271 | } |
| 272 | 272 | |
| 273 | - /// Encodes one 10-bit picture (y: width*height, uv: interleaved CbCr width*height/2, samples in the low 10 bits) of a 10-bit session and returns its Annex-B slice NAL units. | |
| 274 | - pub fn encode_16( | |
| 273 | + /// Submits one 10-bit picture (y: width*height, uv: interleaved CbCr width*height/2, samples in the low 10 bits) of a 10-bit session without waiting; returns the oldest picture once two are in flight. | |
| 274 | + pub fn submit_16( | |
| 275 | 275 | &mut self, |
| 276 | 276 | y: &[u16], |
| 277 | 277 | uv: &[u16], |
| 278 | 278 | pic: &H265Picture, |
| 279 | - ) -> Result<Vec<u8>, Error> { | |
| 279 | + ) -> Result<Option<Vec<u8>>, Error> { | |
| 280 | 280 | if y.len() != self.enc.input.0 * self.enc.input.1 |
| 281 | 281 | || uv.len() != self.enc.input.0 * self.enc.input.1 / 2 |
| 282 | 282 | { |
| @@ -288,7 +288,7 @@ impl H265EncodeSession { | ||
| 288 | 288 | } |
| 289 | 289 | |
| 290 | 290 | /// Encodes one packed RGB picture (src_width x src_height, row stride in bytes, BGRx or RGBx byte order), box-downscaled to the encoder size on the GPU. |
| 291 | - pub fn encode_rgb( | |
| 291 | + pub fn submit_rgb( | |
| 292 | 292 | &mut self, |
| 293 | 293 | rgb: &[u8], |
| 294 | 294 | src_width: u32, |
| @@ -296,7 +296,7 @@ impl H265EncodeSession { | ||
| 296 | 296 | stride_bytes: u32, |
| 297 | 297 | bgr: bool, |
| 298 | 298 | pic: &H265Picture, |
| 299 | - ) -> Result<Vec<u8>, Error> { | |
| 299 | + ) -> Result<Option<Vec<u8>>, Error> { | |
| 300 | 300 | self.check(pic)?; |
| 301 | 301 | let src = (src_width as usize, src_height as usize); |
| 302 | 302 | check_rgb( |
| @@ -317,7 +317,7 @@ impl H265EncodeSession { | ||
| 317 | 317 | |
| 318 | 318 | /// Encodes one picture from a DMA-BUF: BGRx or RGBx box-downscaled to the encoder size, or NV12 or P010 of the encoder size. |
| 319 | 319 | #[cfg(target_os = "linux")] |
| 320 | - pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H265Picture) -> Result<Vec<u8>, Error> { | |
| 320 | + pub fn submit_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H265Picture) -> Result<Option<Vec<u8>>, Error> { | |
| 321 | 321 | self.check(pic)?; |
| 322 | 322 | self.enc.upload_dmabuf(src)?; |
| 323 | 323 | self.encode_uploaded(pic) |
| @@ -329,7 +329,7 @@ impl H265EncodeSession { | ||
| 329 | 329 | self.enc.import_count() |
| 330 | 330 | } |
| 331 | 331 | |
| 332 | - fn encode_uploaded(&mut self, pic: &H265Picture) -> Result<Vec<u8>, Error> { | |
| 332 | + fn encode_uploaded(&mut self, pic: &H265Picture) -> Result<Option<Vec<u8>>, Error> { | |
| 333 | 333 | let extent = self.enc.extent; |
| 334 | 334 | |
| 335 | 335 | let primary = if pic.idr { |
| @@ -341,7 +341,7 @@ impl H265EncodeSession { | ||
| 341 | 341 | picture_resource(self.enc.dpb[0].view, extent), |
| 342 | 342 | picture_resource(self.enc.dpb[1].view, extent), |
| 343 | 343 | ]; |
| 344 | - let src_pr = picture_resource(self.enc.src.view, extent); | |
| 344 | + let src_pr = picture_resource(self.enc.src_view(), extent); | |
| 345 | 345 | |
| 346 | 346 | let new_std = reference_info(primary, pic.poc); |
| 347 | 347 | let ref_std = pic |
| @@ -431,7 +431,7 @@ impl H265EncodeSession { | ||
| 431 | 431 | .build(); |
| 432 | 432 | |
| 433 | 433 | let encode = vk::VideoEncodeInfoKHR::builder() |
| 434 | - .dst_buffer(self.enc.bitstream.buffer) | |
| 434 | + .dst_buffer(self.enc.bitstream_buffer()) | |
| 435 | 435 | .dst_buffer_offset(0) |
| 436 | 436 | .dst_buffer_range(self.enc.bitstream_len) |
| 437 | 437 | .src_picture_resource(src_pr) |
| @@ -443,7 +443,45 @@ impl H265EncodeSession { | ||
| 443 | 443 | let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1); |
| 444 | 444 | let mut chain = RateChain::new(self.enc.rate, self.enc.fps); |
| 445 | 445 | self.enc |
| 446 | - .run(&begin_slots, &mut applied.rc, &mut chain.rc, &encode) | |
| 446 | + .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode) | |
| 447 | + } | |
| 448 | + | |
| 449 | + /// Encodes one picture synchronously and returns its coded bytes. | |
| 450 | + pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &H265Picture) -> Result<Vec<u8>, Error> { | |
| 451 | + self.submit(y, uv, pic)?; | |
| 452 | + self.enc.flush_last() | |
| 453 | + } | |
| 454 | + | |
| 455 | + /// Encodes one picture synchronously and returns its coded bytes. | |
| 456 | + pub fn encode_16(&mut self, y: &[u16], uv: &[u16], pic: &H265Picture) -> Result<Vec<u8>, Error> { | |
| 457 | + self.submit_16(y, uv, pic)?; | |
| 458 | + self.enc.flush_last() | |
| 459 | + } | |
| 460 | + | |
| 461 | + /// Encodes one picture synchronously and returns its coded bytes. | |
| 462 | + pub fn encode_rgb( | |
| 463 | + &mut self, | |
| 464 | + rgb: &[u8], | |
| 465 | + src_width: u32, | |
| 466 | + src_height: u32, | |
| 467 | + stride_bytes: u32, | |
| 468 | + bgr: bool, | |
| 469 | + pic: &H265Picture, | |
| 470 | + ) -> Result<Vec<u8>, Error> { | |
| 471 | + self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?; | |
| 472 | + self.enc.flush_last() | |
| 473 | + } | |
| 474 | + | |
| 475 | + #[cfg(target_os = "linux")] | |
| 476 | + /// Encodes one picture synchronously and returns its coded bytes. | |
| 477 | + pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H265Picture) -> Result<Vec<u8>, Error> { | |
| 478 | + self.submit_dmabuf(src, pic)?; | |
| 479 | + self.enc.flush_last() | |
| 480 | + } | |
| 481 | + | |
| 482 | + /// Waits for queued pictures and returns their coded bytes in order. | |
| 483 | + pub fn flush(&mut self) -> Result<Vec<Vec<u8>>, Error> { | |
| 484 | + self.enc.flush() | |
| 447 | 485 | } |
| 448 | 486 | |
| 449 | 487 | /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change. |
shims/vk-video-ffi/src/session.rsmodified+270 -134
| @@ -1,3 +1,5 @@ | ||
| 1 | +use std::collections::VecDeque; | |
| 2 | + | |
| 1 | 3 | use vulkanalia::prelude::v1_3::*; |
| 2 | 4 | use vulkanalia::vk::{ |
| 3 | 5 | KhrVideoDecodeQueueExtensionDeviceCommands, KhrVideoEncodeQueueExtensionDeviceCommands, |
| @@ -657,22 +659,38 @@ impl Lane { | ||
| 657 | 659 | } |
| 658 | 660 | } |
| 659 | 661 | |
| 660 | - pub(crate) fn submit(&self) -> Result<(), Error> { | |
| 662 | + pub(crate) fn submit_with( | |
| 663 | + &self, | |
| 664 | + wait: &[vk::Semaphore], | |
| 665 | + signal: &[vk::Semaphore], | |
| 666 | + ) -> Result<(), Error> { | |
| 661 | 667 | let d = self.gpu.device(); |
| 662 | 668 | let cbs = [self.cb]; |
| 663 | - let submit = vk::SubmitInfo::builder().command_buffers(&cbs).build(); | |
| 669 | + let stages = vec![vk::PipelineStageFlags::ALL_COMMANDS; wait.len()]; | |
| 670 | + let submit = vk::SubmitInfo::builder() | |
| 671 | + .wait_semaphores(wait) | |
| 672 | + .wait_dst_stage_mask(&stages) | |
| 673 | + .command_buffers(&cbs) | |
| 674 | + .signal_semaphores(signal) | |
| 675 | + .build(); | |
| 664 | 676 | unsafe { |
| 665 | 677 | vk(d.reset_fences(&[self.fence]), "vkResetFences")?; |
| 666 | 678 | vk( |
| 667 | 679 | d.queue_submit(self.queue, &[submit], self.fence), |
| 668 | 680 | "vkQueueSubmit", |
| 669 | - )?; | |
| 670 | - vk( | |
| 671 | - d.wait_for_fences(&[self.fence], true, u64::MAX), | |
| 672 | - "vkWaitForFences", | |
| 673 | - )?; | |
| 681 | + ) | |
| 674 | 682 | } |
| 675 | - Ok(()) | |
| 683 | + } | |
| 684 | + | |
| 685 | + pub(crate) fn wait(&self) -> Result<(), Error> { | |
| 686 | + let fences = [self.fence]; | |
| 687 | + let r = unsafe { self.gpu.device().wait_for_fences(&fences, true, u64::MAX) }; | |
| 688 | + vk(r.map(drop), "vkWaitForFences") | |
| 689 | + } | |
| 690 | + | |
| 691 | + pub(crate) fn submit(&self) -> Result<(), Error> { | |
| 692 | + self.submit_with(&[], &[])?; | |
| 693 | + self.wait() | |
| 676 | 694 | } |
| 677 | 695 | } |
| 678 | 696 | |
| @@ -686,105 +704,145 @@ impl Drop for Lane { | ||
| 686 | 704 | } |
| 687 | 705 | } |
| 688 | 706 | |
| 689 | -/// Encode session plumbing shared by H.264, H.265 and AV1: DPB, source, bitstream and upload path. | |
| 690 | -pub(crate) struct Encoder { | |
| 691 | - pub(crate) vs: VideoSession, | |
| 692 | - pub(crate) main: Lane, | |
| 693 | - pub(crate) upload: Lane, | |
| 694 | - pub(crate) input: (usize, usize), | |
| 695 | - pub(crate) extent: vk::Extent2D, | |
| 696 | - pub(crate) rate: RateControl, | |
| 697 | - pub(crate) fps: (u32, u32), | |
| 698 | - pub(crate) applied: (RateControl, (u32, u32)), | |
| 699 | - pub(crate) dirty: bool, | |
| 700 | - pub(crate) coded: bool, | |
| 701 | - pub(crate) bitstream_len: u64, | |
| 702 | - pub(crate) dpb: [Image; DPB_SLOTS], | |
| 703 | - pub(crate) src: Image, | |
| 707 | +const FLIGHT: usize = 2; | |
| 708 | + | |
| 709 | +fn semaphore(d: &Device) -> Result<vk::Semaphore, Error> { | |
| 710 | + unsafe { | |
| 711 | + vk( | |
| 712 | + d.create_semaphore(&vk::SemaphoreCreateInfo::builder().build(), None), | |
| 713 | + "vkCreateSemaphore", | |
| 714 | + ) | |
| 715 | + } | |
| 716 | +} | |
| 717 | + | |
| 718 | +/// One in-flight picture: its own source, staging, bitstream, command buffers and sync objects. | |
| 719 | +struct Slot { | |
| 720 | + src: Image, | |
| 704 | 721 | staging: Buffer, |
| 705 | - rgb: Option<RgbConverter>, | |
| 722 | + rgb: RgbConverter, | |
| 723 | + bitstream: Buffer, | |
| 724 | + main: Lane, | |
| 725 | + upload: Lane, | |
| 726 | + ready: vk::Semaphore, | |
| 727 | + encoded: vk::Semaphore, | |
| 706 | 728 | #[cfg(target_os = "linux")] |
| 707 | - pub(crate) imports: ImportCache, | |
| 708 | - pub(crate) bitstream: Buffer, | |
| 709 | - query: vk::QueryPool, | |
| 729 | + import: Option<u64>, | |
| 710 | 730 | } |
| 711 | 731 | |
| 712 | -impl Encoder { | |
| 713 | - pub(crate) fn new( | |
| 714 | - vs: VideoSession, | |
| 732 | +impl Slot { | |
| 733 | + fn new( | |
| 734 | + vs: &mut VideoSession, | |
| 715 | 735 | profile: &vk::VideoProfileInfoKHR, |
| 716 | 736 | upload_family: u32, |
| 717 | 737 | input: (u32, u32), |
| 718 | 738 | extent: vk::Extent2D, |
| 719 | - setting: (RateControl, (u32, u32)), | |
| 720 | - size_align: u64, | |
| 739 | + frame_bytes: u64, | |
| 740 | + bitstream_len: u64, | |
| 721 | 741 | ) -> Result<Self, Error> { |
| 722 | 742 | let gpu = vs.gpu.clone(); |
| 723 | - let main = Lane::new(&gpu, vs.family)?; | |
| 724 | - let upload = Lane::new(&gpu, upload_family)?; | |
| 725 | - let mut e = Encoder { | |
| 726 | - vs, | |
| 727 | - main, | |
| 728 | - upload, | |
| 729 | - input: (input.0 as usize, input.1 as usize), | |
| 730 | - extent, | |
| 731 | - rate: setting.0, | |
| 732 | - fps: setting.1, | |
| 733 | - applied: setting, | |
| 734 | - dirty: false, | |
| 735 | - coded: false, | |
| 736 | - bitstream_len: 0, | |
| 737 | - dpb: Default::default(), | |
| 738 | - src: Default::default(), | |
| 739 | - staging: Default::default(), | |
| 740 | - rgb: None, | |
| 741 | - #[cfg(target_os = "linux")] | |
| 742 | - imports: Default::default(), | |
| 743 | - bitstream: Default::default(), | |
| 744 | - query: Default::default(), | |
| 745 | - }; | |
| 746 | - let bytes = bytes_per_sample(e.vs.format) as u64; | |
| 747 | - let frame_bytes = extent.width as u64 * extent.height as u64 * 3 / 2 * bytes; | |
| 748 | - let usage = vk::ImageUsageFlags::VIDEO_ENCODE_DPB_KHR; | |
| 743 | + let d = gpu.device(); | |
| 744 | + let family = vs.family; | |
| 749 | 745 | let mut list = vk::VideoProfileListInfoKHR::builder() |
| 750 | 746 | .profiles(std::slice::from_ref(profile)) |
| 751 | 747 | .build(); |
| 752 | - let family = e.vs.family; | |
| 753 | - e.dpb[0] = e.vs.image(extent, usage, usage, &[family], &mut list)?; | |
| 754 | - e.dpb[1] = e.vs.image(extent, usage, usage, &[family], &mut list)?; | |
| 755 | 748 | let shared = if upload_family == family { |
| 756 | 749 | vec![family] |
| 757 | 750 | } else { |
| 758 | 751 | vec![upload_family, family] |
| 759 | 752 | }; |
| 760 | - e.src = e.vs.image( | |
| 753 | + let src = vs.image( | |
| 761 | 754 | extent, |
| 762 | 755 | vk::ImageUsageFlags::VIDEO_ENCODE_SRC_KHR | vk::ImageUsageFlags::TRANSFER_DST, |
| 763 | 756 | vk::ImageUsageFlags::VIDEO_ENCODE_SRC_KHR | vk::ImageUsageFlags::TRANSFER_DST, |
| 764 | 757 | &shared, |
| 765 | 758 | &mut list, |
| 766 | 759 | )?; |
| 767 | - e.staging = e.vs.buffer( | |
| 760 | + let staging = vs.buffer( | |
| 768 | 761 | frame_bytes, |
| 769 | 762 | vk::BufferUsageFlags::TRANSFER_SRC | vk::BufferUsageFlags::STORAGE_BUFFER, |
| 770 | 763 | &[vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT], |
| 771 | 764 | None, |
| 772 | 765 | )?; |
| 773 | - e.rgb = Some(RgbConverter::new( | |
| 774 | - &gpu, | |
| 775 | - input, | |
| 776 | - (extent.width, extent.height), | |
| 777 | - e.staging.buffer, | |
| 778 | - )?); | |
| 779 | - e.bitstream_len = align_u64(frame_bytes, size_align); | |
| 780 | - e.bitstream = e.vs.buffer( | |
| 781 | - e.bitstream_len, | |
| 766 | + let rgb = RgbConverter::new(&gpu, input, (extent.width, extent.height), staging.buffer)?; | |
| 767 | + let bitstream = vs.buffer( | |
| 768 | + bitstream_len, | |
| 782 | 769 | vk::BufferUsageFlags::VIDEO_ENCODE_DST_KHR, |
| 783 | 770 | &[vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT], |
| 784 | 771 | Some(&mut list), |
| 785 | 772 | )?; |
| 773 | + Ok(Slot { | |
| 774 | + src, | |
| 775 | + staging, | |
| 776 | + rgb, | |
| 777 | + bitstream, | |
| 778 | + main: Lane::new(&gpu, family)?, | |
| 779 | + upload: Lane::new(&gpu, upload_family)?, | |
| 780 | + ready: semaphore(d)?, | |
| 781 | + encoded: semaphore(d)?, | |
| 782 | + #[cfg(target_os = "linux")] | |
| 783 | + import: None, | |
| 784 | + }) | |
| 785 | + } | |
| 786 | 786 | |
| 787 | + fn retire(&mut self) { | |
| 788 | + #[cfg(target_os = "linux")] | |
| 789 | + { | |
| 790 | + self.import = None; | |
| 791 | + } | |
| 792 | + } | |
| 793 | +} | |
| 794 | + | |
| 795 | +/// Encode session plumbing shared by H.264, H.265 and AV1: DPB, picture slots, bitstream and upload path. | |
| 796 | +pub(crate) struct Encoder { | |
| 797 | + pub(crate) vs: VideoSession, | |
| 798 | + pub(crate) input: (usize, usize), | |
| 799 | + pub(crate) extent: vk::Extent2D, | |
| 800 | + pub(crate) rate: RateControl, | |
| 801 | + pub(crate) fps: (u32, u32), | |
| 802 | + pub(crate) applied: (RateControl, (u32, u32)), | |
| 803 | + pub(crate) dirty: bool, | |
| 804 | + pub(crate) coded: bool, | |
| 805 | + pub(crate) bitstream_len: u64, | |
| 806 | + pub(crate) dpb: [Image; DPB_SLOTS], | |
| 807 | + #[cfg(target_os = "linux")] | |
| 808 | + pub(crate) imports: ImportCache, | |
| 809 | + slots: [Slot; FLIGHT], | |
| 810 | + cur: usize, | |
| 811 | + next: usize, | |
| 812 | + last: Option<usize>, | |
| 813 | + pending: VecDeque<usize>, | |
| 814 | + query: vk::QueryPool, | |
| 815 | +} | |
| 816 | + | |
| 817 | +impl Encoder { | |
| 818 | + pub(crate) fn new( | |
| 819 | + mut vs: VideoSession, | |
| 820 | + profile: &vk::VideoProfileInfoKHR, | |
| 821 | + upload_family: u32, | |
| 822 | + input: (u32, u32), | |
| 823 | + extent: vk::Extent2D, | |
| 824 | + setting: (RateControl, (u32, u32)), | |
| 825 | + size_align: u64, | |
| 826 | + ) -> Result<Self, Error> { | |
| 827 | + let gpu = vs.gpu.clone(); | |
| 787 | 828 | let d = gpu.device(); |
| 829 | + let bytes = bytes_per_sample(vs.format) as u64; | |
| 830 | + let frame_bytes = extent.width as u64 * extent.height as u64 * 3 / 2 * bytes; | |
| 831 | + let bitstream_len = align_u64(frame_bytes, size_align); | |
| 832 | + let usage = vk::ImageUsageFlags::VIDEO_ENCODE_DPB_KHR; | |
| 833 | + let mut list = vk::VideoProfileListInfoKHR::builder() | |
| 834 | + .profiles(std::slice::from_ref(profile)) | |
| 835 | + .build(); | |
| 836 | + let family = vs.family; | |
| 837 | + let dpb = [ | |
| 838 | + vs.image(extent, usage, usage, &[family], &mut list)?, | |
| 839 | + vs.image(extent, usage, usage, &[family], &mut list)?, | |
| 840 | + ]; | |
| 841 | + let slots = [ | |
| 842 | + Slot::new(&mut vs, profile, upload_family, input, extent, frame_bytes, bitstream_len)?, | |
| 843 | + Slot::new(&mut vs, profile, upload_family, input, extent, frame_bytes, bitstream_len)?, | |
| 844 | + ]; | |
| 845 | + | |
| 788 | 846 | let mut feedback = vk::QueryPoolVideoEncodeFeedbackCreateInfoKHR::builder() |
| 789 | 847 | .encode_feedback_flags( |
| 790 | 848 | vk::VideoEncodeFeedbackFlagsKHR::BITSTREAM_BUFFER_OFFSET |
| @@ -794,28 +852,53 @@ impl Encoder { | ||
| 794 | 852 | let mut prof = *profile; |
| 795 | 853 | let query_info = vk::QueryPoolCreateInfo::builder() |
| 796 | 854 | .query_type(vk::QueryType::VIDEO_ENCODE_FEEDBACK_KHR) |
| 797 | - .query_count(1) | |
| 855 | + .query_count(FLIGHT as u32) | |
| 798 | 856 | .push_next(&mut feedback) |
| 799 | 857 | .push_next(&mut prof) |
| 800 | 858 | .build(); |
| 801 | - e.query = unsafe { vk(d.create_query_pool(&query_info, None), "vkCreateQueryPool")? }; | |
| 859 | + let query = unsafe { vk(d.create_query_pool(&query_info, None), "vkCreateQueryPool")? }; | |
| 802 | 860 | |
| 803 | - e.main.begin()?; | |
| 861 | + let e = Encoder { | |
| 862 | + vs, | |
| 863 | + input: (input.0 as usize, input.1 as usize), | |
| 864 | + extent, | |
| 865 | + rate: setting.0, | |
| 866 | + fps: setting.1, | |
| 867 | + applied: setting, | |
| 868 | + dirty: false, | |
| 869 | + coded: false, | |
| 870 | + bitstream_len, | |
| 871 | + dpb, | |
| 872 | + #[cfg(target_os = "linux")] | |
| 873 | + imports: Default::default(), | |
| 874 | + slots, | |
| 875 | + cur: 0, | |
| 876 | + next: 0, | |
| 877 | + last: None, | |
| 878 | + pending: VecDeque::new(), | |
| 879 | + query, | |
| 880 | + }; | |
| 881 | + let lane = &e.slots[0].main; | |
| 882 | + lane.begin()?; | |
| 804 | 883 | for img in &e.dpb { |
| 805 | - init_barrier( | |
| 806 | - d, | |
| 807 | - e.main.cb, | |
| 808 | - img.image, | |
| 809 | - vk::ImageLayout::VIDEO_ENCODE_DPB_KHR, | |
| 810 | - ); | |
| 884 | + init_barrier(d, lane.cb, img.image, vk::ImageLayout::VIDEO_ENCODE_DPB_KHR); | |
| 811 | 885 | } |
| 812 | - e.main.end()?; | |
| 813 | - e.main.submit()?; | |
| 886 | + lane.end()?; | |
| 887 | + lane.submit()?; | |
| 814 | 888 | Ok(e) |
| 815 | 889 | } |
| 816 | 890 | |
| 817 | - pub(crate) fn staging_ptr(&self) -> Result<*mut u8, Error> { | |
| 818 | - self.staging | |
| 891 | + pub(crate) fn src_view(&self) -> vk::ImageView { | |
| 892 | + self.slots[self.cur].src.view | |
| 893 | + } | |
| 894 | + | |
| 895 | + pub(crate) fn bitstream_buffer(&self) -> vk::Buffer { | |
| 896 | + self.slots[self.cur].bitstream.buffer | |
| 897 | + } | |
| 898 | + | |
| 899 | + fn staging_ptr(&self) -> Result<*mut u8, Error> { | |
| 900 | + self.slots[self.cur] | |
| 901 | + .staging | |
| 819 | 902 | .ptr |
| 820 | 903 | .ok_or_else(|| Error::Invalid("staging buffer not mapped".into())) |
| 821 | 904 | } |
| @@ -848,6 +931,8 @@ impl Encoder { | ||
| 848 | 931 | _ => {} |
| 849 | 932 | } |
| 850 | 933 | let gpu = self.vs.gpu.clone(); |
| 934 | + let k = self.next; | |
| 935 | + self.cur = k; | |
| 851 | 936 | match input { |
| 852 | 937 | Input::Nv12 { y, uv } => { |
| 853 | 938 | let staging = |
| @@ -866,42 +951,36 @@ impl Encoder { | ||
| 866 | 951 | stride, |
| 867 | 952 | .. |
| 868 | 953 | } => { |
| 869 | - let rgb = self | |
| 870 | - .rgb | |
| 871 | - .as_mut() | |
| 872 | - .ok_or_else(|| Error::Invalid("RGB converter not created".into()))?; | |
| 954 | + let rgb = &mut self.slots[k].rgb; | |
| 873 | 955 | rgb.reserve(&gpu, width, height)?; |
| 874 | 956 | rgb.load(data, stride); |
| 875 | 957 | } |
| 876 | 958 | #[cfg(target_os = "linux")] |
| 877 | 959 | Input::DmaBuf { width, height, .. } => { |
| 878 | - let rgb = self | |
| 879 | - .rgb | |
| 880 | - .as_mut() | |
| 881 | - .ok_or_else(|| Error::Invalid("RGB converter not created".into()))?; | |
| 882 | - rgb.reserve(&gpu, width, height)?; | |
| 960 | + self.slots[k].rgb.reserve(&gpu, width, height)?; | |
| 883 | 961 | } |
| 884 | 962 | } |
| 885 | 963 | |
| 886 | 964 | let d = gpu.device(); |
| 887 | - let cb = self.upload.cb; | |
| 965 | + let slot = &self.slots[k]; | |
| 966 | + let cb = slot.upload.cb; | |
| 888 | 967 | let luma = (aw * ah * bytes) as u64; |
| 889 | 968 | let copies = [ |
| 890 | 969 | copy_region(0, PLANE_0, aw as u32, ah as u32), |
| 891 | 970 | copy_region(luma, PLANE_1, (aw / 2) as u32, (ah / 2) as u32), |
| 892 | 971 | ]; |
| 893 | - self.upload.begin()?; | |
| 972 | + slot.upload.begin()?; | |
| 894 | 973 | unsafe { |
| 895 | - if let (Some(bgr), Some(rgb)) = (input.bgr(), &self.rgb) { | |
| 974 | + if let Some(bgr) = input.bgr() { | |
| 896 | 975 | if let Some(image) = input.source_image() { |
| 897 | - rgb.record_import(d, cb, image, self.upload.family); | |
| 976 | + slot.rgb.record_import(d, cb, image, slot.upload.family); | |
| 898 | 977 | } |
| 899 | - rgb.record(d, cb, bgr); | |
| 978 | + slot.rgb.record(d, cb, bgr); | |
| 900 | 979 | } |
| 901 | 980 | barrier( |
| 902 | 981 | d, |
| 903 | 982 | cb, |
| 904 | - self.src.image, | |
| 983 | + slot.src.image, | |
| 905 | 984 | ( |
| 906 | 985 | vk::ImageLayout::UNDEFINED, |
| 907 | 986 | vk::PipelineStageFlags2::NONE, |
| @@ -915,15 +994,15 @@ impl Encoder { | ||
| 915 | 994 | ); |
| 916 | 995 | d.cmd_copy_buffer_to_image( |
| 917 | 996 | cb, |
| 918 | - self.staging.buffer, | |
| 919 | - self.src.image, | |
| 997 | + slot.staging.buffer, | |
| 998 | + slot.src.image, | |
| 920 | 999 | vk::ImageLayout::TRANSFER_DST_OPTIMAL, |
| 921 | 1000 | &copies, |
| 922 | 1001 | ); |
| 923 | 1002 | barrier( |
| 924 | 1003 | d, |
| 925 | 1004 | cb, |
| 926 | - self.src.image, | |
| 1005 | + slot.src.image, | |
| 927 | 1006 | ( |
| 928 | 1007 | vk::ImageLayout::TRANSFER_DST_OPTIMAL, |
| 929 | 1008 | vk::PipelineStageFlags2::COPY, |
| @@ -936,8 +1015,8 @@ impl Encoder { | ||
| 936 | 1015 | ), |
| 937 | 1016 | ); |
| 938 | 1017 | } |
| 939 | - self.upload.end()?; | |
| 940 | - self.upload.submit() | |
| 1018 | + slot.upload.end()?; | |
| 1019 | + slot.upload.submit_with(&[], &[slot.ready]) | |
| 941 | 1020 | } |
| 942 | 1021 | |
| 943 | 1022 | #[cfg(target_os = "linux")] |
| @@ -948,8 +1027,10 @@ impl Encoder { | ||
| 948 | 1027 | DmaBufFormat::Bgrx | DmaBufFormat::Rgbx => check_size(self.input, (width, height))?, |
| 949 | 1028 | DmaBufFormat::Nv12 | DmaBufFormat::P010 => self.check_planar(src)?, |
| 950 | 1029 | } |
| 951 | - let image = self.imports.get(&gpu, src)?; | |
| 952 | - match src.format { | |
| 1030 | + let busy: Vec<u64> = self.slots.iter().filter_map(|s| s.import).collect(); | |
| 1031 | + let (image, id) = self.imports.get(&gpu, src, &busy)?; | |
| 1032 | + let k = self.next; | |
| 1033 | + let result = match src.format { | |
| 953 | 1034 | DmaBufFormat::Bgrx | DmaBufFormat::Rgbx => self.upload(Input::DmaBuf { |
| 954 | 1035 | image, |
| 955 | 1036 | width, |
| @@ -957,7 +1038,11 @@ impl Encoder { | ||
| 957 | 1038 | bgr: src.format == DmaBufFormat::Bgrx, |
| 958 | 1039 | }), |
| 959 | 1040 | DmaBufFormat::Nv12 | DmaBufFormat::P010 => self.copy_planes(image), |
| 1041 | + }; | |
| 1042 | + if result.is_ok() { | |
| 1043 | + self.slots[k].import = Some(id); | |
| 960 | 1044 | } |
| 1045 | + result | |
| 961 | 1046 | } |
| 962 | 1047 | |
| 963 | 1048 | #[cfg(target_os = "linux")] |
| @@ -978,17 +1063,20 @@ impl Encoder { | ||
| 978 | 1063 | fn copy_planes(&mut self, image: vk::Image) -> Result<(), Error> { |
| 979 | 1064 | let gpu = self.vs.gpu.clone(); |
| 980 | 1065 | let d = gpu.device(); |
| 981 | - let cb = self.upload.cb; | |
| 1066 | + let k = self.next; | |
| 1067 | + self.cur = k; | |
| 1068 | + let slot = &self.slots[k]; | |
| 1069 | + let cb = slot.upload.cb; | |
| 982 | 1070 | let (w, h) = (self.input.0 as u32, self.input.1 as u32); |
| 983 | 1071 | let aspects = [PLANE_0, PLANE_1]; |
| 984 | 1072 | let regions = [plane_copy(PLANE_0, w, h), plane_copy(PLANE_1, w / 2, h / 2)]; |
| 985 | - self.upload.begin()?; | |
| 986 | - acquire(d, cb, image, &aspects, self.upload.family); | |
| 1073 | + slot.upload.begin()?; | |
| 1074 | + acquire(d, cb, image, &aspects, slot.upload.family); | |
| 987 | 1075 | unsafe { |
| 988 | 1076 | barrier( |
| 989 | 1077 | d, |
| 990 | 1078 | cb, |
| 991 | - self.src.image, | |
| 1079 | + slot.src.image, | |
| 992 | 1080 | ( |
| 993 | 1081 | vk::ImageLayout::UNDEFINED, |
| 994 | 1082 | vk::PipelineStageFlags2::NONE, |
| @@ -1004,14 +1092,14 @@ impl Encoder { | ||
| 1004 | 1092 | cb, |
| 1005 | 1093 | image, |
| 1006 | 1094 | vk::ImageLayout::TRANSFER_SRC_OPTIMAL, |
| 1007 | - self.src.image, | |
| 1095 | + slot.src.image, | |
| 1008 | 1096 | vk::ImageLayout::TRANSFER_DST_OPTIMAL, |
| 1009 | 1097 | ®ions, |
| 1010 | 1098 | ); |
| 1011 | 1099 | barrier( |
| 1012 | 1100 | d, |
| 1013 | 1101 | cb, |
| 1014 | - self.src.image, | |
| 1102 | + slot.src.image, | |
| 1015 | 1103 | ( |
| 1016 | 1104 | vk::ImageLayout::TRANSFER_DST_OPTIMAL, |
| 1017 | 1105 | vk::PipelineStageFlags2::COPY, |
| @@ -1025,8 +1113,8 @@ impl Encoder { | ||
| 1025 | 1113 | ); |
| 1026 | 1114 | } |
| 1027 | 1115 | release(d, cb, image, &aspects); |
| 1028 | - self.upload.end()?; | |
| 1029 | - self.upload.submit() | |
| 1116 | + slot.upload.end()?; | |
| 1117 | + slot.upload.submit_with(&[], &[slot.ready]) | |
| 1030 | 1118 | } |
| 1031 | 1119 | |
| 1032 | 1120 | #[cfg(target_os = "linux")] |
| @@ -1034,26 +1122,29 @@ impl Encoder { | ||
| 1034 | 1122 | self.imports.count |
| 1035 | 1123 | } |
| 1036 | 1124 | |
| 1037 | - /// Records one encode with its rate control chains, submits it and returns the coded bytes. | |
| 1038 | - pub(crate) fn run( | |
| 1125 | + /// Records the encode of the uploaded slot and submits it without waiting. Returns the oldest picture once FLIGHT are queued. | |
| 1126 | + pub(crate) fn submit( | |
| 1039 | 1127 | &mut self, |
| 1040 | 1128 | begin_slots: &[vk::VideoReferenceSlotInfoKHR], |
| 1041 | 1129 | applied: &mut vk::VideoEncodeRateControlInfoKHR, |
| 1042 | 1130 | chain: &mut vk::VideoEncodeRateControlInfoKHR, |
| 1043 | 1131 | encode: &vk::VideoEncodeInfoKHR, |
| 1044 | - ) -> Result<Vec<u8>, Error> { | |
| 1132 | + ) -> Result<Option<Vec<u8>>, Error> { | |
| 1045 | 1133 | let gpu = self.vs.gpu.clone(); |
| 1046 | 1134 | let d = gpu.device(); |
| 1047 | - let cb = self.main.cb; | |
| 1135 | + let k = self.cur; | |
| 1136 | + let slot = &self.slots[k]; | |
| 1137 | + let cb = slot.main.cb; | |
| 1138 | + let query = k as u32; | |
| 1048 | 1139 | let mut quality = vk::VideoEncodeQualityLevelInfoKHR::builder() |
| 1049 | 1140 | .quality_level(0) |
| 1050 | 1141 | .build(); |
| 1051 | 1142 | let reset = !self.coded; |
| 1052 | 1143 | let update = reset || self.dirty; |
| 1053 | 1144 | |
| 1054 | - self.main.begin()?; | |
| 1145 | + slot.main.begin()?; | |
| 1055 | 1146 | unsafe { |
| 1056 | - d.cmd_reset_query_pool(cb, self.query, 0, 1); | |
| 1147 | + d.cmd_reset_query_pool(cb, self.query, query, 1); | |
| 1057 | 1148 | let begin = vk::VideoBeginCodingInfoKHR::builder() |
| 1058 | 1149 | .video_session(self.vs.session) |
| 1059 | 1150 | .video_session_parameters(self.vs.params) |
| @@ -1081,27 +1172,67 @@ impl Encoder { | ||
| 1081 | 1172 | d.cmd_control_video_coding_khr(cb, &control); |
| 1082 | 1173 | } |
| 1083 | 1174 | |
| 1084 | - d.cmd_begin_query(cb, self.query, 0, vk::QueryControlFlags::empty()); | |
| 1175 | + d.cmd_begin_query(cb, self.query, query, vk::QueryControlFlags::empty()); | |
| 1085 | 1176 | d.cmd_encode_video_khr(cb, encode); |
| 1086 | - d.cmd_end_query(cb, self.query, 0); | |
| 1177 | + d.cmd_end_query(cb, self.query, query); | |
| 1087 | 1178 | let end = vk::VideoEndCodingInfoKHR::builder().build(); |
| 1088 | 1179 | d.cmd_end_video_coding_khr(cb, &end); |
| 1089 | 1180 | } |
| 1090 | - self.main.end()?; | |
| 1091 | - self.main.submit()?; | |
| 1181 | + slot.main.end()?; | |
| 1182 | + let mut wait = vec![slot.ready]; | |
| 1183 | + if let Some(p) = self.last { | |
| 1184 | + wait.push(self.slots[p].encoded); | |
| 1185 | + } | |
| 1186 | + slot.main.submit_with(&wait, &[slot.encoded])?; | |
| 1187 | + | |
| 1188 | + self.last = Some(k); | |
| 1189 | + self.next = k ^ 1; | |
| 1092 | 1190 | self.coded = true; |
| 1093 | 1191 | self.applied = (self.rate, self.fps); |
| 1094 | 1192 | self.dirty = false; |
| 1095 | - self.read_bitstream() | |
| 1193 | + self.pending.push_back(k); | |
| 1194 | + if self.pending.len() < FLIGHT { | |
| 1195 | + return Ok(None); | |
| 1196 | + } | |
| 1197 | + let oldest = self | |
| 1198 | + .pending | |
| 1199 | + .pop_front() | |
| 1200 | + .ok_or_else(|| Error::Invalid("no picture in flight".into()))?; | |
| 1201 | + self.finish(oldest).map(Some) | |
| 1202 | + } | |
| 1203 | + | |
| 1204 | + /// Waits for every queued picture and returns their bytes in submission order. | |
| 1205 | + pub(crate) fn flush(&mut self) -> Result<Vec<Vec<u8>>, Error> { | |
| 1206 | + let mut out = Vec::new(); | |
| 1207 | + while let Some(k) = self.pending.pop_front() { | |
| 1208 | + out.push(self.finish(k)?); | |
| 1209 | + } | |
| 1210 | + Ok(out) | |
| 1211 | + } | |
| 1212 | + | |
| 1213 | + /// Flushes and returns the last picture, for synchronous use where one picture is queued per call. | |
| 1214 | + pub(crate) fn flush_last(&mut self) -> Result<Vec<u8>, Error> { | |
| 1215 | + self.flush()? | |
| 1216 | + .pop() | |
| 1217 | + .ok_or_else(|| Error::Invalid("no picture encoded".into())) | |
| 1096 | 1218 | } |
| 1097 | 1219 | |
| 1098 | - fn read_bitstream(&self) -> Result<Vec<u8>, Error> { | |
| 1220 | + fn finish(&mut self, k: usize) -> Result<Vec<u8>, Error> { | |
| 1221 | + let slot = &self.slots[k]; | |
| 1222 | + slot.main.wait()?; | |
| 1223 | + slot.upload.wait()?; | |
| 1224 | + let bytes = self.read_bitstream(k)?; | |
| 1225 | + self.slots[k].retire(); | |
| 1226 | + Ok(bytes) | |
| 1227 | + } | |
| 1228 | + | |
| 1229 | + fn read_bitstream(&self, k: usize) -> Result<Vec<u8>, Error> { | |
| 1099 | 1230 | let mut feedback = [0u8; 8]; |
| 1100 | 1231 | unsafe { |
| 1101 | 1232 | vk( |
| 1102 | 1233 | self.vs.gpu.device().get_query_pool_results( |
| 1103 | 1234 | self.query, |
| 1104 | - 0, | |
| 1235 | + k as u32, | |
| 1105 | 1236 | 1, |
| 1106 | 1237 | &mut feedback, |
| 1107 | 1238 | 8, |
| @@ -1119,7 +1250,7 @@ impl Encoder { | ||
| 1119 | 1250 | "encoded size exceeds bitstream buffer".into(), |
| 1120 | 1251 | )); |
| 1121 | 1252 | } |
| 1122 | - let ptr = self | |
| 1253 | + let ptr = self.slots[k] | |
| 1123 | 1254 | .bitstream |
| 1124 | 1255 | .ptr |
| 1125 | 1256 | .ok_or_else(|| Error::Invalid("bitstream buffer not mapped".into()))?; |
| @@ -1136,16 +1267,21 @@ impl Drop for Encoder { | ||
| 1136 | 1267 | let _ = d.device_wait_idle(); |
| 1137 | 1268 | d.destroy_query_pool(self.query, None); |
| 1138 | 1269 | } |
| 1139 | - for img in self.dpb.iter().chain(std::iter::once(&self.src)) { | |
| 1270 | + for img in &self.dpb { | |
| 1140 | 1271 | img.destroy(d); |
| 1141 | 1272 | } |
| 1142 | 1273 | #[cfg(target_os = "linux")] |
| 1143 | 1274 | self.imports.destroy(d); |
| 1144 | - if let Some(rgb) = &self.rgb { | |
| 1145 | - rgb.destroy(d); | |
| 1275 | + for slot in self.slots.iter_mut() { | |
| 1276 | + unsafe { | |
| 1277 | + d.destroy_semaphore(slot.ready, None); | |
| 1278 | + d.destroy_semaphore(slot.encoded, None); | |
| 1279 | + } | |
| 1280 | + slot.src.destroy(d); | |
| 1281 | + slot.rgb.destroy(d); | |
| 1282 | + slot.staging.destroy(d); | |
| 1283 | + slot.bitstream.destroy(d); | |
| 1146 | 1284 | } |
| 1147 | - self.staging.destroy(d); | |
| 1148 | - self.bitstream.destroy(d); | |
| 1149 | 1285 | } |
| 1150 | 1286 | } |
| 1151 | 1287 |