From 87336a0b9ccfb03cb4f1b743254ad3f74ad43f59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 25 Nov 2026 15:21:50 +0300 Subject: [PATCH] Depth-2 pipelined Vulkan encode: shim slots, ec-vk and ec-hw submit/flush, hw_pipeline example --- crates/ec-hw/examples/hw_pipeline.rs | 165 +++++++++++ crates/ec-hw/src/hw.rs | 134 +++++++++ crates/ec-hw/src/lib.rs | 3 +- crates/ec-vk/src/av1.rs | 119 ++++++-- crates/ec-vk/src/h265.rs | 121 ++++++-- crates/ec-vk/src/lib.rs | 123 +++++++-- shims/vk-video-ffi/src/av1_encode.rs | 60 +++- shims/vk-video-ffi/src/h264_encode.rs | 50 +++- shims/vk-video-ffi/src/h265_encode.rs | 62 ++++- shims/vk-video-ffi/src/session.rs | 383 +++++++++++++++++--------- 10 files changed, 983 insertions(+), 237 deletions(-) create mode 100644 crates/ec-hw/examples/hw_pipeline.rs diff --git a/crates/ec-hw/examples/hw_pipeline.rs b/crates/ec-hw/examples/hw_pipeline.rs new file mode 100644 index 00000000..0afbaec2 --- /dev/null +++ b/crates/ec-hw/examples/hw_pipeline.rs @@ -0,0 +1,165 @@ +use std::time::Instant; + +use ec_hw::{ + Backend, EncCodec, EncodeInput, EncoderConfig, FrameMetadata, HwEncoder, I420, I420_16, + RateControlMode, +}; + +const FRAMES: usize = 120; +const PATTERN: usize = 6; + +struct Case { + codec: EncCodec, + width: u32, + height: u32, + ten: bool, +} + +enum Source { + Eight(Vec), + Ten(Vec), +} + +fn main() { + let cases = [ + Case { + codec: EncCodec::H265, + width: 3840, + height: 2160, + ten: true, + }, + Case { + codec: EncCodec::H264, + width: 1920, + height: 1080, + ten: false, + }, + Case { + codec: EncCodec::H265, + width: 1920, + height: 1080, + ten: false, + }, + Case { + codec: EncCodec::Av1, + width: 1920, + height: 1080, + ten: false, + }, + ]; + for case in &cases { + let source = if case.ten { + Source::Ten(pattern_16(case)) + } else { + Source::Eight(pattern(case)) + }; + for backend in [Backend::Vk, Backend::Va] { + if let Err(e) = run(case, &source, backend) { + println!( + "{:?} {}x{} {backend:?}: error: {e}", + case.codec, case.width, case.height + ); + } + } + } +} + +fn config(case: &Case) -> EncoderConfig { + let base = EncoderConfig { + rate_control: RateControlMode::ConstantQp { qp: 30 }, + ..EncoderConfig::new(case.codec, case.width, case.height) + }; + if case.ten { + base.ten_bit() + } else { + base + } +} + +fn meta(index: usize) -> FrameMetadata { + FrameMetadata { + timestamp: index as i64, + force_keyframe: index == 0, + } +} + +fn run(case: &Case, source: &Source, backend: Backend) -> ec_hw::Result<()> { + let mut encoder = HwEncoder::open(config(case), Some(backend))?; + let start = Instant::now(); + let mut sync = Vec::with_capacity(FRAMES); + for index in 0..FRAMES { + let coded = match source { + Source::Eight(frames) => encoder.encode(&frames[index % PATTERN], meta(index))?, + Source::Ten(frames) => encoder.encode_16(&frames[index % PATTERN], meta(index))?, + }; + sync.push(coded); + } + let sync_ms = start.elapsed().as_secs_f64() * 1000.0 / FRAMES as f64; + + let mut encoder = HwEncoder::open(config(case), Some(backend))?; + let start = Instant::now(); + let mut piped = Vec::with_capacity(FRAMES); + for index in 0..FRAMES { + let input = match source { + Source::Eight(frames) => EncodeInput::I420(&frames[index % PATTERN]), + Source::Ten(frames) => EncodeInput::I420_16(&frames[index % PATTERN]), + }; + piped.extend(encoder.submit(input, meta(index))?); + } + piped.extend(encoder.flush()?); + let piped_ms = start.elapsed().as_secs_f64() * 1000.0 / FRAMES as f64; + + if matches!(backend, Backend::Vk) { + assert_eq!(sync, piped, "{:?} sync and pipelined bitstreams differ", case.codec); + } + println!( + "{:?} {}x{} {}-bit {backend:?}: sync {sync_ms:.2} ms/frame, pipelined {piped_ms:.2} ms/frame, {} frames", + case.codec, + case.width, + case.height, + if case.ten { 10 } else { 8 }, + piped.len() + ); + Ok(()) +} + +fn pattern(case: &Case) -> Vec { + let (w, h) = (case.width as usize, case.height as usize); + let (cw, ch) = (w / 2, h / 2); + (0..PATTERN) + .map(|k| I420 { + y: (0..h) + .flat_map(move |row| (0..w).map(move |x| ((x + row + 3 * k) & 0xff) as u8)) + .collect(), + u: (0..ch) + .flat_map(move |row| (0..cw).map(move |x| ((x + 2 * row + 5 * k) & 0xff) as u8)) + .collect(), + v: (0..ch) + .flat_map(move |row| (0..cw).map(move |x| ((2 * x + row + 7 * k) & 0xff) as u8)) + .collect(), + width: case.width, + height: case.height, + }) + .collect() +} + +fn pattern_16(case: &Case) -> Vec { + let (w, h) = (case.width as usize, case.height as usize); + let (cw, ch) = (w / 2, h / 2); + (0..PATTERN) + .map(|k| I420_16 { + y: (0..h) + .flat_map(move |row| (0..w).map(move |x| ((x + row + 3 * k) & 0x3ff) as u16)) + .collect(), + u: (0..ch) + .flat_map(move |row| (0..cw).map(move |x| ((x + 2 * row + 5 * k) & 0x3ff) as u16)) + .collect(), + v: (0..ch) + .flat_map(move |row| (0..cw).map(move |x| ((2 * x + row + 7 * k) & 0x3ff) as u16)) + .collect(), + width: case.width, + height: case.height, + bit_depth: 10, + }) + .collect() +} diff --git a/crates/ec-hw/src/hw.rs b/crates/ec-hw/src/hw.rs index fab811b6..d17bb902 100644 --- a/crates/ec-hw/src/hw.rs +++ b/crates/ec-hw/src/hw.rs @@ -7,6 +7,7 @@ use std::os::fd::BorrowedFd; use ec_vk::DmaBuf; use std::cell::RefCell; +use std::collections::VecDeque; use crate::error::{Error, Result}; use crate::picture::{Decoded, I420, I420_16, RgbPicture}; @@ -239,6 +240,20 @@ pub struct DmaBufFrame<'a> { pub order: RgbOrder, } +/// One picture for [`HwEncoder::submit`]. +#[derive(Debug, Clone, Copy)] +pub enum EncodeInput<'a> { + /// 8-bit I420. + I420(&'a I420), + /// 10-bit I420 of a 10-bit encoder (H.265 and AV1). + I420_16(&'a I420_16), + /// Packed RGB, box-downscaled to the encoder size. + Rgb(&'a RgbFrame<'a>), + /// DMA-BUF of packed RGB, Vulkan only. + #[cfg(target_os = "linux")] + DmaBuf(&'a DmaBufFrame<'a>), +} + #[cfg(target_os = "linux")] fn rgb_to_i420(frame: &RgbFrame, (w, h): (usize, usize)) -> Result { let (sw, sh, stride) = ( @@ -297,7 +312,74 @@ enum VkEncoder { Av1(ec_vk::Av1Encoder), } +fn stamp(pending: &mut VecDeque, coded: ec_vk::CodedFrame) -> CodedFrame { + CodedFrame { + data: coded.data, + timestamp: pending.pop_front().unwrap_or_default(), + is_keyframe: coded.keyframe, + } +} + impl VkEncoder { + fn submit( + &mut self, + input: EncodeInput, + force_keyframe: bool, + ) -> std::result::Result, ec_vk::Error> { + match input { + EncodeInput::I420(frame) => { + let (y, u, v) = (&frame.y, &frame.u, &frame.v); + match self { + VkEncoder::H264(e) => e.submit(y, u, v, force_keyframe), + VkEncoder::H265(e) => e.submit(y, u, v, force_keyframe), + VkEncoder::Av1(e) => e.submit(y, u, v, force_keyframe), + } + } + EncodeInput::I420_16(frame) => { + let (y, u, v) = (&frame.y, &frame.u, &frame.v); + match self { + VkEncoder::H264(_) => Err(ec_vk::Error::Unsupported("10-bit H.264 encode".into())), + VkEncoder::H265(e) => e.submit_16(y, u, v, force_keyframe), + VkEncoder::Av1(e) => e.submit_16(y, u, v, force_keyframe), + } + } + EncodeInput::Rgb(frame) => { + let bgr = frame.order == RgbOrder::Bgra; + let (data, sw, sh, stride) = (frame.data, frame.width, frame.height, frame.stride); + match self { + VkEncoder::H264(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), + VkEncoder::H265(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), + VkEncoder::Av1(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe), + } + } + #[cfg(target_os = "linux")] + EncodeInput::DmaBuf(frame) => { + let src = DmaBuf { + fd: frame.fd, + width: frame.width, + height: frame.height, + stride: frame.stride, + offset: frame.offset, + modifier: frame.modifier, + bgr: frame.order == RgbOrder::Bgra, + }; + match self { + VkEncoder::H264(e) => e.submit_dmabuf(&src, force_keyframe), + VkEncoder::H265(e) => e.submit_dmabuf(&src, force_keyframe), + VkEncoder::Av1(e) => e.submit_dmabuf(&src, force_keyframe), + } + } + } + } + + fn flush(&mut self) -> std::result::Result, ec_vk::Error> { + match self { + VkEncoder::H264(e) => e.flush(), + VkEncoder::H265(e) => e.flush(), + VkEncoder::Av1(e) => e.flush(), + } + } + fn encode( &mut self, frame: &I420, @@ -386,6 +468,7 @@ pub struct HwEncoder { config: EncoderConfig, #[cfg_attr(not(target_os = "linux"), allow(dead_code))] size: (usize, usize), + pending: VecDeque, } impl HwEncoder { @@ -406,6 +489,7 @@ impl HwEncoder { born_epoch, config, size, + pending: VecDeque::new(), }); } Err(e) => reasons.push(format!("{backend:?}: {e}")), @@ -445,8 +529,55 @@ impl HwEncoder { Ok(()) } + /// Submit one picture without waiting; the oldest coded picture comes back once two are in flight. Call [`HwEncoder::flush`] at the end. + pub fn submit(&mut self, input: EncodeInput, meta: FrameMetadata) -> Result> { + match &mut self.inner { + EncInner::Vk(enc) => { + vk_session_alive(self.born_epoch)?; + self.pending.push_back(meta.timestamp); + let out = enc.submit(input, meta.force_keyframe)?; + Ok(out.map(|coded| stamp(&mut self.pending, coded))) + } + #[cfg(target_os = "linux")] + EncInner::Va(enc) => match input { + EncodeInput::I420(frame) => enc.submit(frame, meta), + EncodeInput::I420_16(frame) => enc.submit_16(frame, meta), + EncodeInput::Rgb(frame) => enc.submit(&rgb_to_i420(frame, self.size)?, meta), + EncodeInput::DmaBuf(_) => Err(Error::unsupported( + "DMA-BUF encode", + "the VA-API backend has no DMA-BUF input here", + )), + }, + } + } + + /// Wait for every submitted picture and return them, oldest first. + pub fn flush(&mut self) -> Result> { + match &mut self.inner { + EncInner::Vk(enc) => { + vk_session_alive(self.born_epoch)?; + let frames = enc.flush()?; + Ok(frames + .into_iter() + .map(|coded| stamp(&mut self.pending, coded)) + .collect()) + } + #[cfg(target_os = "linux")] + EncInner::Va(enc) => enc.flush(), + } + } + + fn idle(&self) -> Result<()> { + if self.pending.is_empty() { + Ok(()) + } else { + Err(Error::config("pipelined frames pending; call flush first")) + } + } + /// Encode one frame; `meta.force_keyframe` starts a new GOP. pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result { + self.idle()?; match &mut self.inner { EncInner::Vk(enc) => { vk_session_alive(self.born_epoch)?; @@ -464,6 +595,7 @@ impl HwEncoder { /// Encode one 10-bit frame of a 10-bit encoder (H.265 and AV1), the [`HwEncoder::encode`] of a 10-bit encoder. pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result { + self.idle()?; match &mut self.inner { EncInner::Vk(enc) => { let coded = enc.encode_16(frame, meta.force_keyframe)?; @@ -480,6 +612,7 @@ impl HwEncoder { /// Encode one packed RGB frame of the source size; it is box-downscaled to the encoder size. Vulkan does this and the NV12 conversion on the GPU, VA-API on the CPU. pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result { + self.idle()?; match &mut self.inner { EncInner::Vk(enc) => { vk_session_alive(self.born_epoch)?; @@ -502,6 +635,7 @@ impl HwEncoder { frame: &DmaBufFrame, meta: FrameMetadata, ) -> Result { + self.idle()?; match &mut self.inner { EncInner::Vk(enc) => { vk_session_alive(self.born_epoch)?; diff --git a/crates/ec-hw/src/lib.rs b/crates/ec-hw/src/lib.rs index 70322185..70657b50 100644 --- a/crates/ec-hw/src/lib.rs +++ b/crates/ec-hw/src/lib.rs @@ -88,7 +88,8 @@ pub use error::{Error, Result}; #[cfg(target_os = "linux")] pub use hw::DmaBufFrame; pub use hw::{ - Backend, Capability, Direction, HwDecoder, HwEncoder, RgbFrame, RgbOrder, RgbOutput, + Backend, Capability, Direction, EncodeInput, HwDecoder, HwEncoder, RgbFrame, RgbOrder, + RgbOutput, capabilities, }; #[cfg(target_os = "linux")] diff --git a/crates/ec-vk/src/av1.rs b/crates/ec-vk/src/av1.rs index 341c48a2..b597394d 100644 --- a/crates/ec-vk/src/av1.rs +++ b/crates/ec-vk/src/av1.rs @@ -2,7 +2,7 @@ use vk_video_ffi::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref}; #[cfg(target_os = "linux")] use crate::DmaBuf; -use crate::{CodedFrame, Error, Gpu, RateControl}; +use crate::{CodedFrame, Error, Flight, Gpu, RateControl, last_frame}; const TEMPORAL_DELIMITER: [u8; 2] = [0x12, 0x00]; @@ -35,6 +35,7 @@ pub struct Av1Encoder { reference: Option, uv: Vec, uv16: Vec, + flight: Flight, } impl Av1Encoder { @@ -65,17 +66,18 @@ impl Av1Encoder { reference: None, uv: vec![0; cfg.width as usize * cfg.height as usize / 2], uv16: vec![0; cfg.width as usize * cfg.height as usize / 2], + flight: Flight::default(), }) } - /// Encodes one I420 frame as a temporal unit; `force_keyframe` makes it a KEY frame and restarts the GOP. - pub fn encode( + /// Submits one I420 frame without waiting; returns the oldest temporal unit once a second one is queued. + pub fn submit( &mut self, y: &[u8], u: &[u8], v: &[u8], force_keyframe: bool, - ) -> Result { + ) -> Result, Error> { let chroma = self.width * self.height / 4; if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma { return Err(Error::Invalid("I420 plane size".into())); @@ -85,18 +87,31 @@ impl Av1Encoder { pair[1] = v[i]; } let pic = self.next_picture(force_keyframe); - let frame = self.session.encode(y, &self.uv, &pic)?; - Ok(self.finish(&pic, frame)) + let out = self.session.submit(y, &self.uv, &pic)?; + Ok(out.map(|bytes| self.coded(bytes))) } - /// Encodes one 10-bit I420 frame of a 10-bit encoder; `force_keyframe` makes it a KEY frame and restarts the GOP. - pub fn encode_16( + /// Encodes one I420 frame as a temporal unit; `force_keyframe` makes it a KEY frame and restarts the GOP. + pub fn encode( + &mut self, + y: &[u8], + u: &[u8], + v: &[u8], + force_keyframe: bool, + ) -> Result { + let first = self.submit(y, u, v, force_keyframe)?; + let rest = self.flush()?; + last_frame(first, rest) + } + + /// Submits one 10-bit I420 frame of a 10-bit encoder without waiting. + pub fn submit_16( &mut self, y: &[u16], u: &[u16], v: &[u16], force_keyframe: bool, - ) -> Result { + ) -> Result, Error> { let chroma = self.width * self.height / 4; if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma { return Err(Error::Invalid("I420 plane size".into())); @@ -106,8 +121,27 @@ impl Av1Encoder { pair[1] = v[i]; } let pic = self.next_picture(force_keyframe); - let frame = self.session.encode_16(y, &self.uv16, &pic)?; - Ok(self.finish(&pic, frame)) + let out = self.session.submit_16(y, &self.uv16, &pic)?; + Ok(out.map(|bytes| self.coded(bytes))) + } + + /// Encodes one 10-bit I420 frame of a 10-bit encoder; `force_keyframe` makes it a KEY frame and restarts the GOP. + pub fn encode_16( + &mut self, + y: &[u16], + u: &[u16], + v: &[u16], + force_keyframe: bool, + ) -> Result { + let first = self.submit_16(y, u, v, force_keyframe)?; + let rest = self.flush()?; + last_frame(first, rest) + } + + /// Waits for every submitted frame and returns them in order. + pub fn flush(&mut self) -> Result, Error> { + let bytes = self.session.flush()?; + Ok(bytes.into_iter().map(|b| self.coded(b)).collect()) } /// Changes bitrate or frame rate; takes effect on the next frame. @@ -115,6 +149,23 @@ impl Av1Encoder { Ok(self.session.set_rate(rate, fps)?) } + /// Submits one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes) without waiting. + pub fn submit_rgb( + &mut self, + rgb: &[u8], + src_width: u32, + src_height: u32, + stride_bytes: u32, + bgr: bool, + force_keyframe: bool, + ) -> Result, Error> { + let pic = self.next_picture(force_keyframe); + let out = self + .session + .submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?; + Ok(out.map(|bytes| self.coded(bytes))) + } + /// 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. pub fn encode_rgb( &mut self, @@ -125,9 +176,21 @@ impl Av1Encoder { bgr: bool, force_keyframe: bool, ) -> Result { + let first = self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, force_keyframe)?; + let rest = self.flush()?; + last_frame(first, rest) + } + + /// Submits one DMA-BUF frame of the source size without waiting. + #[cfg(target_os = "linux")] + pub fn submit_dmabuf( + &mut self, + src: &DmaBuf<'_>, + force_keyframe: bool, + ) -> Result, Error> { let pic = self.next_picture(force_keyframe); - let frame = self.session.encode_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?; - Ok(self.finish(&pic, frame)) + let out = self.session.submit_dmabuf(src, &pic)?; + Ok(out.map(|bytes| self.coded(bytes))) } /// 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 { src: &DmaBuf<'_>, force_keyframe: bool, ) -> Result { - let pic = self.next_picture(force_keyframe); - let frame = self.session.encode_dmabuf(src, &pic)?; - Ok(self.finish(&pic, frame)) + let first = self.submit_dmabuf(src, force_keyframe)?; + let rest = self.flush()?; + last_frame(first, rest) } fn next_picture(&mut self, force_keyframe: bool) -> Av1Picture { @@ -151,28 +214,28 @@ impl Av1Encoder { }; let reference = if keyframe { None } else { self.reference }; let slot = reference.map_or(0, |r| 1 - r.slot); - Av1Picture { + let pic = Av1Picture { key: keyframe, order_hint: self.order_hint, slot, reference, - } - } - - fn finish(&mut self, pic: &Av1Picture, frame: Vec) -> CodedFrame { + }; self.reference = Some(Av1Ref { slot: pic.slot, order_hint: pic.order_hint, }); - self.position = if pic.key { 1 } else { self.position + 1 }; + self.position = if keyframe { 1 } else { self.position + 1 }; + self.flight.push(keyframe); + pic + } + + fn coded(&mut self, bytes: Vec) -> CodedFrame { + let keyframe = self.flight.pop(); let mut data = TEMPORAL_DELIMITER.to_vec(); - if pic.key { + if keyframe { data.extend_from_slice(&self.sequence_header); } - data.extend_from_slice(&frame); - CodedFrame { - data, - keyframe: pic.key, - } + data.extend_from_slice(&bytes); + CodedFrame { data, keyframe } } } diff --git a/crates/ec-vk/src/h265.rs b/crates/ec-vk/src/h265.rs index ee416044..b9153e44 100644 --- a/crates/ec-vk/src/h265.rs +++ b/crates/ec-vk/src/h265.rs @@ -2,7 +2,7 @@ use vk_video_ffi::{H265EncodeConfig, H265EncodeSession, H265Picture, H265Ref}; #[cfg(target_os = "linux")] use crate::DmaBuf; -use crate::{CodedFrame, Error, Gpu, RateControl}; +use crate::{CodedFrame, Error, Flight, Gpu, RateControl, last_frame}; /// H.265 encoder settings. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -33,6 +33,7 @@ pub struct H265Encoder { reference: Option, uv: Vec, uv16: Vec, + flight: Flight, } impl H265Encoder { @@ -63,17 +64,18 @@ impl H265Encoder { reference: None, uv: vec![0; cfg.width as usize * cfg.height as usize / 2], uv16: vec![0; cfg.width as usize * cfg.height as usize / 2], + flight: Flight::default(), }) } - /// Encodes one I420 frame; `force_keyframe` makes it an IDR and restarts the GOP. - pub fn encode( + /// Submits one I420 frame without waiting; returns the oldest frame once a second one is queued. + pub fn submit( &mut self, y: &[u8], u: &[u8], v: &[u8], force_keyframe: bool, - ) -> Result { + ) -> Result, Error> { let chroma = self.width * self.height / 4; if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma { return Err(Error::Invalid("I420 plane size".into())); @@ -83,18 +85,31 @@ impl H265Encoder { pair[1] = v[i]; } let pic = self.next_picture(force_keyframe); - let slice = self.session.encode(y, &self.uv, &pic)?; - Ok(self.finish(&pic, slice)) + let out = self.session.submit(y, &self.uv, &pic)?; + Ok(out.map(|bytes| self.coded(bytes))) } - /// Encodes one 10-bit I420 frame of a 10-bit encoder; `force_keyframe` makes it IDR and restarts the GOP. - pub fn encode_16( + /// Encodes one I420 frame; `force_keyframe` makes it an IDR and restarts the GOP. + pub fn encode( + &mut self, + y: &[u8], + u: &[u8], + v: &[u8], + force_keyframe: bool, + ) -> Result { + let first = self.submit(y, u, v, force_keyframe)?; + let rest = self.flush()?; + last_frame(first, rest) + } + + /// Submits one 10-bit I420 frame of a 10-bit encoder without waiting. + pub fn submit_16( &mut self, y: &[u16], u: &[u16], v: &[u16], force_keyframe: bool, - ) -> Result { + ) -> Result, Error> { let chroma = self.width * self.height / 4; if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma { return Err(Error::Invalid("I420 plane size".into())); @@ -104,8 +119,27 @@ impl H265Encoder { pair[1] = v[i]; } let pic = self.next_picture(force_keyframe); - let slice = self.session.encode_16(y, &self.uv16, &pic)?; - Ok(self.finish(&pic, slice)) + let out = self.session.submit_16(y, &self.uv16, &pic)?; + Ok(out.map(|bytes| self.coded(bytes))) + } + + /// Encodes one 10-bit I420 frame of a 10-bit encoder; `force_keyframe` makes it IDR and restarts the GOP. + pub fn encode_16( + &mut self, + y: &[u16], + u: &[u16], + v: &[u16], + force_keyframe: bool, + ) -> Result { + let first = self.submit_16(y, u, v, force_keyframe)?; + let rest = self.flush()?; + last_frame(first, rest) + } + + /// Waits for every submitted frame and returns them in order. + pub fn flush(&mut self) -> Result, Error> { + let bytes = self.session.flush()?; + Ok(bytes.into_iter().map(|b| self.coded(b)).collect()) } /// Changes bitrate or frame rate; takes effect on the next frame. @@ -113,6 +147,23 @@ impl H265Encoder { Ok(self.session.set_rate(rate, fps)?) } + /// Submits one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes) without waiting. + pub fn submit_rgb( + &mut self, + rgb: &[u8], + src_width: u32, + src_height: u32, + stride_bytes: u32, + bgr: bool, + force_keyframe: bool, + ) -> Result, Error> { + let pic = self.next_picture(force_keyframe); + let out = self + .session + .submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?; + Ok(out.map(|bytes| self.coded(bytes))) + } + /// 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. pub fn encode_rgb( &mut self, @@ -123,9 +174,21 @@ impl H265Encoder { bgr: bool, force_keyframe: bool, ) -> Result { + let first = self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, force_keyframe)?; + let rest = self.flush()?; + last_frame(first, rest) + } + + /// Submits one DMA-BUF frame of the source size without waiting. + #[cfg(target_os = "linux")] + pub fn submit_dmabuf( + &mut self, + src: &DmaBuf<'_>, + force_keyframe: bool, + ) -> Result, Error> { let pic = self.next_picture(force_keyframe); - let slice = self.session.encode_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?; - Ok(self.finish(&pic, slice)) + let out = self.session.submit_dmabuf(src, &pic)?; + Ok(out.map(|bytes| self.coded(bytes))) } /// 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 { src: &DmaBuf<'_>, force_keyframe: bool, ) -> Result { - let pic = self.next_picture(force_keyframe); - let slice = self.session.encode_dmabuf(src, &pic)?; - Ok(self.finish(&pic, slice)) + let first = self.submit_dmabuf(src, force_keyframe)?; + let rest = self.flush()?; + last_frame(first, rest) } fn next_picture(&mut self, force_keyframe: bool) -> H265Picture { @@ -145,28 +208,28 @@ impl H265Encoder { self.poc = if keyframe { 0 } else { self.poc + 1 }; let reference = if keyframe { None } else { self.reference }; let slot = reference.map_or(0, |r| 1 - r.slot); - H265Picture { + let pic = H265Picture { idr: keyframe, poc: self.poc, slot, reference, - } - } - - fn finish(&mut self, pic: &H265Picture, slice: Vec) -> CodedFrame { + }; self.reference = Some(H265Ref { slot: pic.slot, poc: pic.poc, }); - self.position = if pic.idr { 1 } else { self.position + 1 }; - let data = if pic.idr { - [self.parameter_sets.as_slice(), slice.as_slice()].concat() + self.position = if keyframe { 1 } else { self.position + 1 }; + self.flight.push(keyframe); + pic + } + + fn coded(&mut self, bytes: Vec) -> CodedFrame { + let keyframe = self.flight.pop(); + let data = if keyframe { + [self.parameter_sets.as_slice(), bytes.as_slice()].concat() } else { - slice + bytes }; - CodedFrame { - data, - keyframe: pic.idr, - } + CodedFrame { data, keyframe } } } diff --git a/crates/ec-vk/src/lib.rs b/crates/ec-vk/src/lib.rs index bdac45a0..c4c1f371 100644 --- a/crates/ec-vk/src/lib.rs +++ b/crates/ec-vk/src/lib.rs @@ -2,6 +2,8 @@ #![forbid(unsafe_code)] #![deny(missing_docs)] +use std::collections::VecDeque; + use vk_video_ffi::{H264EncodeConfig, H264EncodeSession, H264Picture, H264Ref}; mod av1; @@ -48,6 +50,29 @@ pub struct CodedFrame { pub keyframe: bool, } +#[derive(Default)] +pub(crate) struct Flight(VecDeque); + +impl Flight { + pub(crate) fn push(&mut self, keyframe: bool) { + self.0.push_back(keyframe); + } + + pub(crate) fn pop(&mut self) -> bool { + self.0.pop_front().unwrap_or(false) + } +} + +pub(crate) fn last_frame( + first: Option, + rest: Vec, +) -> Result { + rest.into_iter() + .last() + .or(first) + .ok_or_else(|| Error::Invalid("no coded frame".into())) +} + /// H.264 encoder: GOP, frame_num, POC and DPB slot bookkeeping over [`H264EncodeSession`]. pub struct H264Encoder { session: H264EncodeSession, @@ -61,6 +86,7 @@ pub struct H264Encoder { idr_pic_id: u16, reference: Option, uv: Vec, + flight: Flight, } impl H264Encoder { @@ -92,17 +118,18 @@ impl H264Encoder { idr_pic_id: 0, reference: None, uv: vec![0; cfg.width as usize * cfg.height as usize / 2], + flight: Flight::default(), }) } - /// Encodes one I420 frame; `force_keyframe` makes it an IDR and restarts the GOP. - pub fn encode( + /// Submits one I420 frame without waiting; returns the oldest frame once a second one is queued. + pub fn submit( &mut self, y: &[u8], u: &[u8], v: &[u8], force_keyframe: bool, - ) -> Result { + ) -> Result, Error> { let chroma = self.width * self.height / 4; if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma { return Err(Error::Invalid("I420 plane size".into())); @@ -112,8 +139,27 @@ impl H264Encoder { pair[1] = v[i]; } let pic = self.next_picture(force_keyframe); - let slice = self.session.encode(y, &self.uv, &pic)?; - Ok(self.finish(&pic, slice)) + let out = self.session.submit(y, &self.uv, &pic)?; + Ok(out.map(|bytes| self.coded(bytes))) + } + + /// Encodes one I420 frame; `force_keyframe` makes it an IDR and restarts the GOP. + pub fn encode( + &mut self, + y: &[u8], + u: &[u8], + v: &[u8], + force_keyframe: bool, + ) -> Result { + let first = self.submit(y, u, v, force_keyframe)?; + let rest = self.flush()?; + last_frame(first, rest) + } + + /// Waits for every submitted frame and returns them in order. + pub fn flush(&mut self) -> Result, Error> { + let bytes = self.session.flush()?; + Ok(bytes.into_iter().map(|b| self.coded(b)).collect()) } /// Changes bitrate or frame rate; takes effect on the next frame. @@ -121,6 +167,23 @@ impl H264Encoder { Ok(self.session.set_rate(rate, fps)?) } + /// Submits one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes) without waiting. + pub fn submit_rgb( + &mut self, + rgb: &[u8], + src_width: u32, + src_height: u32, + stride_bytes: u32, + bgr: bool, + force_keyframe: bool, + ) -> Result, Error> { + let pic = self.next_picture(force_keyframe); + let out = self + .session + .submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?; + Ok(out.map(|bytes| self.coded(bytes))) + } + /// 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. pub fn encode_rgb( &mut self, @@ -131,9 +194,21 @@ impl H264Encoder { bgr: bool, force_keyframe: bool, ) -> Result { + let first = self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, force_keyframe)?; + let rest = self.flush()?; + last_frame(first, rest) + } + + /// Submits one DMA-BUF frame of the source size without waiting. + #[cfg(target_os = "linux")] + pub fn submit_dmabuf( + &mut self, + src: &DmaBuf<'_>, + force_keyframe: bool, + ) -> Result, Error> { let pic = self.next_picture(force_keyframe); - let slice = self.session.encode_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?; - Ok(self.finish(&pic, slice)) + let out = self.session.submit_dmabuf(src, &pic)?; + Ok(out.map(|bytes| self.coded(bytes))) } /// 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 { src: &DmaBuf<'_>, force_keyframe: bool, ) -> Result { - let pic = self.next_picture(force_keyframe); - let slice = self.session.encode_dmabuf(src, &pic)?; - Ok(self.finish(&pic, slice)) + let first = self.submit_dmabuf(src, force_keyframe)?; + let rest = self.flush()?; + last_frame(first, rest) } fn next_picture(&mut self, force_keyframe: bool) -> H264Picture { @@ -159,34 +234,34 @@ impl H264Encoder { } let reference = if keyframe { None } else { self.reference }; let slot = reference.map_or(0, |r| 1 - r.slot); - H264Picture { + let pic = H264Picture { idr: keyframe, idr_pic_id: self.idr_pic_id, frame_num: self.frame_num, poc: self.poc, slot, reference, - } - } - - fn finish(&mut self, pic: &H264Picture, slice: Vec) -> CodedFrame { + }; self.reference = Some(H264Ref { slot: pic.slot, frame_num: pic.frame_num, poc: pic.poc, }); - self.position = if pic.idr { 1 } else { self.position + 1 }; - if pic.idr { + self.position = if keyframe { 1 } else { self.position + 1 }; + if keyframe { self.idr_pic_id = self.idr_pic_id.wrapping_add(1); } - let data = if pic.idr { - [self.parameter_sets.as_slice(), slice.as_slice()].concat() + self.flight.push(keyframe); + pic + } + + fn coded(&mut self, bytes: Vec) -> CodedFrame { + let keyframe = self.flight.pop(); + let data = if keyframe { + [self.parameter_sets.as_slice(), bytes.as_slice()].concat() } else { - slice + bytes }; - CodedFrame { - data, - keyframe: pic.idr, - } + CodedFrame { data, keyframe } } } diff --git a/shims/vk-video-ffi/src/av1_encode.rs b/shims/vk-video-ffi/src/av1_encode.rs index 2c15be1d..afa55dfa 100644 --- a/shims/vk-video-ffi/src/av1_encode.rs +++ b/shims/vk-video-ffi/src/av1_encode.rs @@ -224,8 +224,8 @@ impl Av1EncodeSession { self.seq.clone() } - /// Encodes one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) and returns its frame OBUs. - pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &Av1Picture) -> Result, Error> { + /// Submits one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) without waiting; returns the oldest picture once two are in flight. + pub fn submit(&mut self, y: &[u8], uv: &[u8], pic: &Av1Picture) -> Result>, Error> { if y.len() != self.enc.input.0 * self.enc.input.1 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2 { @@ -236,8 +236,8 @@ impl Av1EncodeSession { self.encode_uploaded(pic) } - /// 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. - pub fn encode_16(&mut self, y: &[u16], uv: &[u16], pic: &Av1Picture) -> Result, Error> { + /// 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. + pub fn submit_16(&mut self, y: &[u16], uv: &[u16], pic: &Av1Picture) -> Result>, Error> { if y.len() != self.enc.input.0 * self.enc.input.1 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2 { @@ -249,7 +249,7 @@ impl Av1EncodeSession { } /// 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. - pub fn encode_rgb( + pub fn submit_rgb( &mut self, rgb: &[u8], src_width: u32, @@ -257,7 +257,7 @@ impl Av1EncodeSession { stride_bytes: u32, bgr: bool, pic: &Av1Picture, - ) -> Result, Error> { + ) -> Result>, Error> { self.check(pic)?; let src = (src_width as usize, src_height as usize); check_rgb( @@ -277,13 +277,13 @@ impl Av1EncodeSession { } /// Encodes one picture from a DMA-BUF of BGRx or RGBx pixels, box-downscaled to the encoder size on the GPU. #[cfg(target_os = "linux")] - pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &Av1Picture) -> Result, Error> { + pub fn submit_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &Av1Picture) -> Result>, Error> { self.check(pic)?; self.enc.upload_dmabuf(src)?; self.encode_uploaded(pic) } - fn encode_uploaded(&mut self, pic: &Av1Picture) -> Result, Error> { + fn encode_uploaded(&mut self, pic: &Av1Picture) -> Result>, Error> { let extent = self.enc.extent; let refresh: u8 = if pic.key { 0xff } else { 1 << pic.slot }; @@ -291,7 +291,7 @@ impl Av1EncodeSession { picture_resource(self.enc.dpb[0].view, extent), picture_resource(self.enc.dpb[1].view, extent), ]; - let src_pr = picture_resource(self.enc.src.view, extent); + let src_pr = picture_resource(self.enc.src_view(), extent); let key_of = self.slot_key; let mut new_std = zeroed::(); @@ -393,7 +393,7 @@ impl Av1EncodeSession { }; let encode = vk::VideoEncodeInfoKHR::builder() - .dst_buffer(self.enc.bitstream.buffer) + .dst_buffer(self.enc.bitstream_buffer()) .dst_buffer_offset(0) .dst_buffer_range(self.enc.bitstream_len) .src_picture_resource(src_pr) @@ -406,7 +406,7 @@ impl Av1EncodeSession { let mut chain = RateChain::new(self.enc.rate, self.enc.fps); let out = self .enc - .run(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)?; + .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)?; for i in 0..DPB_SLOTS { if refresh >> i & 1 == 1 { self.slot_key[i] = pic.key; @@ -420,6 +420,44 @@ impl Av1EncodeSession { Ok(out) } + /// Encodes one picture synchronously and returns its coded bytes. + pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &Av1Picture) -> Result, Error> { + self.submit(y, uv, pic)?; + self.enc.flush_last() + } + + /// Encodes one picture synchronously and returns its coded bytes. + pub fn encode_16(&mut self, y: &[u16], uv: &[u16], pic: &Av1Picture) -> Result, Error> { + self.submit_16(y, uv, pic)?; + self.enc.flush_last() + } + + /// Encodes one picture synchronously and returns its coded bytes. + pub fn encode_rgb( + &mut self, + rgb: &[u8], + src_width: u32, + src_height: u32, + stride_bytes: u32, + bgr: bool, + pic: &Av1Picture, + ) -> Result, Error> { + self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?; + self.enc.flush_last() + } + + #[cfg(target_os = "linux")] + /// Encodes one picture synchronously and returns its coded bytes. + pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &Av1Picture) -> Result, Error> { + self.submit_dmabuf(src, pic)?; + self.enc.flush_last() + } + + /// Waits for queued pictures and returns their coded bytes in order. + pub fn flush(&mut self) -> Result>, Error> { + self.enc.flush() + } + /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change. pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> { self.enc.set_rate(rate, fps) diff --git a/shims/vk-video-ffi/src/h264_encode.rs b/shims/vk-video-ffi/src/h264_encode.rs index a56186f9..91c7ee2e 100644 --- a/shims/vk-video-ffi/src/h264_encode.rs +++ b/shims/vk-video-ffi/src/h264_encode.rs @@ -253,8 +253,8 @@ impl H264EncodeSession { ) } - /// Encodes one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) and returns its Annex-B slice NAL units. - pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &H264Picture) -> Result, Error> { + /// Submits one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) without waiting; returns the oldest picture once two are in flight. + pub fn submit(&mut self, y: &[u8], uv: &[u8], pic: &H264Picture) -> Result>, Error> { let (w, h) = self.enc.input; if y.len() != w * h || uv.len() != w * h / 2 { return Err(Error::Invalid("NV12 plane size".into())); @@ -265,7 +265,7 @@ impl H264EncodeSession { } /// 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. - pub fn encode_rgb( + pub fn submit_rgb( &mut self, rgb: &[u8], src_width: u32, @@ -273,7 +273,7 @@ impl H264EncodeSession { stride_bytes: u32, bgr: bool, pic: &H264Picture, - ) -> Result, Error> { + ) -> Result>, Error> { self.check(pic)?; let src = (src_width as usize, src_height as usize); check_rgb(self.enc.input, src, rgb, stride_bytes as usize)?; @@ -289,13 +289,13 @@ impl H264EncodeSession { /// Encodes one picture from a DMA-BUF of BGRx or RGBx pixels, box-downscaled to the encoder size on the GPU. #[cfg(target_os = "linux")] - pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H264Picture) -> Result, Error> { + pub fn submit_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H264Picture) -> Result>, Error> { self.check(pic)?; self.enc.upload_dmabuf(src)?; self.encode_uploaded(pic) } - fn encode_uploaded(&mut self, pic: &H264Picture) -> Result, Error> { + fn encode_uploaded(&mut self, pic: &H264Picture) -> Result>, Error> { let extent = self.enc.extent; let primary = if pic.idr { @@ -307,7 +307,7 @@ impl H264EncodeSession { picture_resource(self.enc.dpb[0].view, extent), picture_resource(self.enc.dpb[1].view, extent), ]; - let src_pr = picture_resource(self.enc.src.view, extent); + let src_pr = picture_resource(self.enc.src_view(), extent); let new_std = reference_info(primary, pic.frame_num, pic.poc); let ref_std = pic @@ -394,7 +394,7 @@ impl H264EncodeSession { .build(); let encode = vk::VideoEncodeInfoKHR::builder() - .dst_buffer(self.enc.bitstream.buffer) + .dst_buffer(self.enc.bitstream_buffer()) .dst_buffer_offset(0) .dst_buffer_range(self.enc.bitstream_len) .src_picture_resource(src_pr) @@ -406,7 +406,39 @@ impl H264EncodeSession { let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1); let mut chain = RateChain::new(self.enc.rate, self.enc.fps); self.enc - .run(&begin_slots, &mut applied.rc, &mut chain.rc, &encode) + .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode) + } + + /// Encodes one picture synchronously and returns its coded bytes. + pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &H264Picture) -> Result, Error> { + self.submit(y, uv, pic)?; + self.enc.flush_last() + } + + /// Encodes one picture synchronously and returns its coded bytes. + pub fn encode_rgb( + &mut self, + rgb: &[u8], + src_width: u32, + src_height: u32, + stride_bytes: u32, + bgr: bool, + pic: &H264Picture, + ) -> Result, Error> { + self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?; + self.enc.flush_last() + } + + #[cfg(target_os = "linux")] + /// Encodes one picture synchronously and returns its coded bytes. + pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H264Picture) -> Result, Error> { + self.submit_dmabuf(src, pic)?; + self.enc.flush_last() + } + + /// Waits for queued pictures and returns their coded bytes in order. + pub fn flush(&mut self) -> Result>, Error> { + self.enc.flush() } /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change. diff --git a/shims/vk-video-ffi/src/h265_encode.rs b/shims/vk-video-ffi/src/h265_encode.rs index efb0da23..9e5cce3c 100644 --- a/shims/vk-video-ffi/src/h265_encode.rs +++ b/shims/vk-video-ffi/src/h265_encode.rs @@ -258,8 +258,8 @@ impl H265EncodeSession { ) } - /// Encodes one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) and returns its Annex-B slice NAL units. - pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &H265Picture) -> Result, Error> { + /// Submits one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) without waiting; returns the oldest picture once two are in flight. + pub fn submit(&mut self, y: &[u8], uv: &[u8], pic: &H265Picture) -> Result>, Error> { if y.len() != self.enc.input.0 * self.enc.input.1 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2 { @@ -270,13 +270,13 @@ impl H265EncodeSession { self.encode_uploaded(pic) } - /// 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. - pub fn encode_16( + /// 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. + pub fn submit_16( &mut self, y: &[u16], uv: &[u16], pic: &H265Picture, - ) -> Result, Error> { + ) -> Result>, Error> { if y.len() != self.enc.input.0 * self.enc.input.1 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2 { @@ -288,7 +288,7 @@ impl H265EncodeSession { } /// 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. - pub fn encode_rgb( + pub fn submit_rgb( &mut self, rgb: &[u8], src_width: u32, @@ -296,7 +296,7 @@ impl H265EncodeSession { stride_bytes: u32, bgr: bool, pic: &H265Picture, - ) -> Result, Error> { + ) -> Result>, Error> { self.check(pic)?; let src = (src_width as usize, src_height as usize); check_rgb( @@ -317,13 +317,13 @@ impl H265EncodeSession { /// Encodes one picture from a DMA-BUF of BGRx or RGBx pixels, box-downscaled to the encoder size on the GPU. #[cfg(target_os = "linux")] - pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H265Picture) -> Result, Error> { + pub fn submit_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H265Picture) -> Result>, Error> { self.check(pic)?; self.enc.upload_dmabuf(src)?; self.encode_uploaded(pic) } - fn encode_uploaded(&mut self, pic: &H265Picture) -> Result, Error> { + fn encode_uploaded(&mut self, pic: &H265Picture) -> Result>, Error> { let extent = self.enc.extent; let primary = if pic.idr { @@ -335,7 +335,7 @@ impl H265EncodeSession { picture_resource(self.enc.dpb[0].view, extent), picture_resource(self.enc.dpb[1].view, extent), ]; - let src_pr = picture_resource(self.enc.src.view, extent); + let src_pr = picture_resource(self.enc.src_view(), extent); let new_std = reference_info(primary, pic.poc); let ref_std = pic @@ -425,7 +425,7 @@ impl H265EncodeSession { .build(); let encode = vk::VideoEncodeInfoKHR::builder() - .dst_buffer(self.enc.bitstream.buffer) + .dst_buffer(self.enc.bitstream_buffer()) .dst_buffer_offset(0) .dst_buffer_range(self.enc.bitstream_len) .src_picture_resource(src_pr) @@ -437,7 +437,45 @@ impl H265EncodeSession { let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1); let mut chain = RateChain::new(self.enc.rate, self.enc.fps); self.enc - .run(&begin_slots, &mut applied.rc, &mut chain.rc, &encode) + .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode) + } + + /// Encodes one picture synchronously and returns its coded bytes. + pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &H265Picture) -> Result, Error> { + self.submit(y, uv, pic)?; + self.enc.flush_last() + } + + /// Encodes one picture synchronously and returns its coded bytes. + pub fn encode_16(&mut self, y: &[u16], uv: &[u16], pic: &H265Picture) -> Result, Error> { + self.submit_16(y, uv, pic)?; + self.enc.flush_last() + } + + /// Encodes one picture synchronously and returns its coded bytes. + pub fn encode_rgb( + &mut self, + rgb: &[u8], + src_width: u32, + src_height: u32, + stride_bytes: u32, + bgr: bool, + pic: &H265Picture, + ) -> Result, Error> { + self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?; + self.enc.flush_last() + } + + #[cfg(target_os = "linux")] + /// Encodes one picture synchronously and returns its coded bytes. + pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H265Picture) -> Result, Error> { + self.submit_dmabuf(src, pic)?; + self.enc.flush_last() + } + + /// Waits for queued pictures and returns their coded bytes in order. + pub fn flush(&mut self) -> Result>, Error> { + self.enc.flush() } /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change. diff --git a/shims/vk-video-ffi/src/session.rs b/shims/vk-video-ffi/src/session.rs index b1057fff..f8f1dfcd 100644 --- a/shims/vk-video-ffi/src/session.rs +++ b/shims/vk-video-ffi/src/session.rs @@ -1,3 +1,5 @@ +use std::collections::VecDeque; + use vulkanalia::prelude::v1_3::*; use vulkanalia::vk::{ KhrVideoDecodeQueueExtensionDeviceCommands, KhrVideoEncodeQueueExtensionDeviceCommands, @@ -657,22 +659,38 @@ impl Lane { } } - pub(crate) fn submit(&self) -> Result<(), Error> { + pub(crate) fn submit_with( + &self, + wait: &[vk::Semaphore], + signal: &[vk::Semaphore], + ) -> Result<(), Error> { let d = self.gpu.device(); let cbs = [self.cb]; - let submit = vk::SubmitInfo::builder().command_buffers(&cbs).build(); + let stages = vec![vk::PipelineStageFlags::ALL_COMMANDS; wait.len()]; + let submit = vk::SubmitInfo::builder() + .wait_semaphores(wait) + .wait_dst_stage_mask(&stages) + .command_buffers(&cbs) + .signal_semaphores(signal) + .build(); unsafe { vk(d.reset_fences(&[self.fence]), "vkResetFences")?; vk( d.queue_submit(self.queue, &[submit], self.fence), "vkQueueSubmit", - )?; - vk( - d.wait_for_fences(&[self.fence], true, u64::MAX), - "vkWaitForFences", - )?; + ) } - Ok(()) + } + + pub(crate) fn wait(&self) -> Result<(), Error> { + let fences = [self.fence]; + let r = unsafe { self.gpu.device().wait_for_fences(&fences, true, u64::MAX) }; + vk(r.map(drop), "vkWaitForFences") + } + + pub(crate) fn submit(&self) -> Result<(), Error> { + self.submit_with(&[], &[])?; + self.wait() } } @@ -686,101 +704,143 @@ impl Drop for Lane { } } -/// Encode session plumbing shared by H.264, H.265 and AV1: DPB, source, bitstream and upload path. -pub(crate) struct Encoder { - pub(crate) vs: VideoSession, - pub(crate) main: Lane, - pub(crate) upload: Lane, - pub(crate) input: (usize, usize), - pub(crate) extent: vk::Extent2D, - pub(crate) rate: RateControl, - pub(crate) fps: (u32, u32), - pub(crate) applied: (RateControl, (u32, u32)), - pub(crate) dirty: bool, - pub(crate) coded: bool, - pub(crate) bitstream_len: u64, - pub(crate) dpb: [Image; DPB_SLOTS], - pub(crate) src: Image, +const FLIGHT: usize = 2; + +fn semaphore(d: &Device) -> Result { + unsafe { + vk( + d.create_semaphore(&vk::SemaphoreCreateInfo::builder().build(), None), + "vkCreateSemaphore", + ) + } +} + +/// One in-flight picture: its own source, staging, bitstream, command buffers and sync objects. +struct Slot { + src: Image, staging: Buffer, - rgb: Option, - pub(crate) bitstream: Buffer, - query: vk::QueryPool, + rgb: RgbConverter, + bitstream: Buffer, + main: Lane, + upload: Lane, + ready: vk::Semaphore, + encoded: vk::Semaphore, + #[cfg(target_os = "linux")] + import: Option, } -impl Encoder { - pub(crate) fn new( - vs: VideoSession, +impl Slot { + fn new( + vs: &mut VideoSession, profile: &vk::VideoProfileInfoKHR, upload_family: u32, input: (u32, u32), extent: vk::Extent2D, - setting: (RateControl, (u32, u32)), - size_align: u64, + frame_bytes: u64, + bitstream_len: u64, ) -> Result { let gpu = vs.gpu.clone(); - let main = Lane::new(&gpu, vs.family)?; - let upload = Lane::new(&gpu, upload_family)?; - let mut e = Encoder { - vs, - main, - upload, - input: (input.0 as usize, input.1 as usize), - extent, - rate: setting.0, - fps: setting.1, - applied: setting, - dirty: false, - coded: false, - bitstream_len: 0, - dpb: Default::default(), - src: Default::default(), - staging: Default::default(), - rgb: None, - bitstream: Default::default(), - query: Default::default(), - }; - let bytes = bytes_per_sample(e.vs.format) as u64; - let frame_bytes = extent.width as u64 * extent.height as u64 * 3 / 2 * bytes; - let usage = vk::ImageUsageFlags::VIDEO_ENCODE_DPB_KHR; + let d = gpu.device(); + let family = vs.family; let mut list = vk::VideoProfileListInfoKHR::builder() .profiles(std::slice::from_ref(profile)) .build(); - let family = e.vs.family; - e.dpb[0] = e.vs.image(extent, usage, usage, &[family], &mut list)?; - e.dpb[1] = e.vs.image(extent, usage, usage, &[family], &mut list)?; let shared = if upload_family == family { vec![family] } else { vec![upload_family, family] }; - e.src = e.vs.image( + let src = vs.image( extent, vk::ImageUsageFlags::VIDEO_ENCODE_SRC_KHR | vk::ImageUsageFlags::TRANSFER_DST, vk::ImageUsageFlags::VIDEO_ENCODE_SRC_KHR | vk::ImageUsageFlags::TRANSFER_DST, &shared, &mut list, )?; - e.staging = e.vs.buffer( + let staging = vs.buffer( frame_bytes, vk::BufferUsageFlags::TRANSFER_SRC | vk::BufferUsageFlags::STORAGE_BUFFER, &[vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT], None, )?; - e.rgb = Some(RgbConverter::new( - &gpu, - input, - (extent.width, extent.height), - e.staging.buffer, - )?); - e.bitstream_len = align_u64(frame_bytes, size_align); - e.bitstream = e.vs.buffer( - e.bitstream_len, + let rgb = RgbConverter::new(&gpu, input, (extent.width, extent.height), staging.buffer)?; + let bitstream = vs.buffer( + bitstream_len, vk::BufferUsageFlags::VIDEO_ENCODE_DST_KHR, &[vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT], Some(&mut list), )?; + Ok(Slot { + src, + staging, + rgb, + bitstream, + main: Lane::new(&gpu, family)?, + upload: Lane::new(&gpu, upload_family)?, + ready: semaphore(d)?, + encoded: semaphore(d)?, + #[cfg(target_os = "linux")] + import: None, + }) + } + fn release(&mut self, d: &Device) { + #[cfg(target_os = "linux")] + if let Some(import) = self.import.take() { + import.destroy(d); + } + } +} + +/// Encode session plumbing shared by H.264, H.265 and AV1: DPB, picture slots, bitstream and upload path. +pub(crate) struct Encoder { + pub(crate) vs: VideoSession, + pub(crate) input: (usize, usize), + pub(crate) extent: vk::Extent2D, + pub(crate) rate: RateControl, + pub(crate) fps: (u32, u32), + pub(crate) applied: (RateControl, (u32, u32)), + pub(crate) dirty: bool, + pub(crate) coded: bool, + pub(crate) bitstream_len: u64, + pub(crate) dpb: [Image; DPB_SLOTS], + slots: [Slot; FLIGHT], + cur: usize, + next: usize, + last: Option, + pending: VecDeque, + query: vk::QueryPool, +} + +impl Encoder { + pub(crate) fn new( + mut vs: VideoSession, + profile: &vk::VideoProfileInfoKHR, + upload_family: u32, + input: (u32, u32), + extent: vk::Extent2D, + setting: (RateControl, (u32, u32)), + size_align: u64, + ) -> Result { + let gpu = vs.gpu.clone(); let d = gpu.device(); + let bytes = bytes_per_sample(vs.format) as u64; + let frame_bytes = extent.width as u64 * extent.height as u64 * 3 / 2 * bytes; + let bitstream_len = align_u64(frame_bytes, size_align); + let usage = vk::ImageUsageFlags::VIDEO_ENCODE_DPB_KHR; + let mut list = vk::VideoProfileListInfoKHR::builder() + .profiles(std::slice::from_ref(profile)) + .build(); + let family = vs.family; + let dpb = [ + vs.image(extent, usage, usage, &[family], &mut list)?, + vs.image(extent, usage, usage, &[family], &mut list)?, + ]; + let slots = [ + Slot::new(&mut vs, profile, upload_family, input, extent, frame_bytes, bitstream_len)?, + Slot::new(&mut vs, profile, upload_family, input, extent, frame_bytes, bitstream_len)?, + ]; + let mut feedback = vk::QueryPoolVideoEncodeFeedbackCreateInfoKHR::builder() .encode_feedback_flags( vk::VideoEncodeFeedbackFlagsKHR::BITSTREAM_BUFFER_OFFSET @@ -790,28 +850,51 @@ impl Encoder { let mut prof = *profile; let query_info = vk::QueryPoolCreateInfo::builder() .query_type(vk::QueryType::VIDEO_ENCODE_FEEDBACK_KHR) - .query_count(1) + .query_count(FLIGHT as u32) .push_next(&mut feedback) .push_next(&mut prof) .build(); - e.query = unsafe { vk(d.create_query_pool(&query_info, None), "vkCreateQueryPool")? }; + let query = unsafe { vk(d.create_query_pool(&query_info, None), "vkCreateQueryPool")? }; - e.main.begin()?; + let e = Encoder { + vs, + input: (input.0 as usize, input.1 as usize), + extent, + rate: setting.0, + fps: setting.1, + applied: setting, + dirty: false, + coded: false, + bitstream_len, + dpb, + slots, + cur: 0, + next: 0, + last: None, + pending: VecDeque::new(), + query, + }; + let lane = &e.slots[0].main; + lane.begin()?; for img in &e.dpb { - init_barrier( - d, - e.main.cb, - img.image, - vk::ImageLayout::VIDEO_ENCODE_DPB_KHR, - ); + init_barrier(d, lane.cb, img.image, vk::ImageLayout::VIDEO_ENCODE_DPB_KHR); } - e.main.end()?; - e.main.submit()?; + lane.end()?; + lane.submit()?; Ok(e) } - pub(crate) fn staging_ptr(&self) -> Result<*mut u8, Error> { - self.staging + pub(crate) fn src_view(&self) -> vk::ImageView { + self.slots[self.cur].src.view + } + + pub(crate) fn bitstream_buffer(&self) -> vk::Buffer { + self.slots[self.cur].bitstream.buffer + } + + fn staging_ptr(&self) -> Result<*mut u8, Error> { + self.slots[self.cur] + .staging .ptr .ok_or_else(|| Error::Invalid("staging buffer not mapped".into())) } @@ -844,6 +927,8 @@ impl Encoder { _ => {} } let gpu = self.vs.gpu.clone(); + let k = self.next; + self.cur = k; match input { Input::Nv12 { y, uv } => { let staging = @@ -862,42 +947,36 @@ impl Encoder { stride, .. } => { - let rgb = self - .rgb - .as_mut() - .ok_or_else(|| Error::Invalid("RGB converter not created".into()))?; + let rgb = &mut self.slots[k].rgb; rgb.reserve(&gpu, width, height)?; rgb.load(data, stride); } #[cfg(target_os = "linux")] Input::DmaBuf { width, height, .. } => { - let rgb = self - .rgb - .as_mut() - .ok_or_else(|| Error::Invalid("RGB converter not created".into()))?; - rgb.reserve(&gpu, width, height)?; + self.slots[k].rgb.reserve(&gpu, width, height)?; } } let d = gpu.device(); - let cb = self.upload.cb; + let slot = &self.slots[k]; + let cb = slot.upload.cb; let luma = (aw * ah * bytes) as u64; let copies = [ copy_region(0, PLANE_0, aw as u32, ah as u32), copy_region(luma, PLANE_1, (aw / 2) as u32, (ah / 2) as u32), ]; - self.upload.begin()?; + slot.upload.begin()?; unsafe { - if let (Some(bgr), Some(rgb)) = (input.bgr(), &self.rgb) { + if let Some(bgr) = input.bgr() { if let Some(image) = input.source_image() { - rgb.record_import(d, cb, image, self.upload.family); + slot.rgb.record_import(d, cb, image, slot.upload.family); } - rgb.record(d, cb, bgr); + slot.rgb.record(d, cb, bgr); } barrier( d, cb, - self.src.image, + slot.src.image, ( vk::ImageLayout::UNDEFINED, vk::PipelineStageFlags2::NONE, @@ -911,15 +990,15 @@ impl Encoder { ); d.cmd_copy_buffer_to_image( cb, - self.staging.buffer, - self.src.image, + slot.staging.buffer, + slot.src.image, vk::ImageLayout::TRANSFER_DST_OPTIMAL, &copies, ); barrier( d, cb, - self.src.image, + slot.src.image, ( vk::ImageLayout::TRANSFER_DST_OPTIMAL, vk::PipelineStageFlags2::COPY, @@ -932,8 +1011,8 @@ impl Encoder { ), ); } - self.upload.end()?; - self.upload.submit() + slot.upload.end()?; + slot.upload.submit_with(&[], &[slot.ready]) } #[cfg(target_os = "linux")] @@ -948,30 +1027,41 @@ impl Encoder { height, bgr: src.bgr, }); - import.destroy(gpu.device()); - result + match result { + Ok(()) => { + self.slots[self.cur].import = Some(import); + Ok(()) + } + Err(e) => { + import.destroy(gpu.device()); + Err(e) + } + } } - /// Records one encode with its rate control chains, submits it and returns the coded bytes. - pub(crate) fn run( + /// Records the encode of the uploaded slot and submits it without waiting. Returns the oldest picture once FLIGHT are queued. + pub(crate) fn submit( &mut self, begin_slots: &[vk::VideoReferenceSlotInfoKHR], applied: &mut vk::VideoEncodeRateControlInfoKHR, chain: &mut vk::VideoEncodeRateControlInfoKHR, encode: &vk::VideoEncodeInfoKHR, - ) -> Result, Error> { + ) -> Result>, Error> { let gpu = self.vs.gpu.clone(); let d = gpu.device(); - let cb = self.main.cb; + let k = self.cur; + let slot = &self.slots[k]; + let cb = slot.main.cb; + let query = k as u32; let mut quality = vk::VideoEncodeQualityLevelInfoKHR::builder() .quality_level(0) .build(); let reset = !self.coded; let update = reset || self.dirty; - self.main.begin()?; + slot.main.begin()?; unsafe { - d.cmd_reset_query_pool(cb, self.query, 0, 1); + d.cmd_reset_query_pool(cb, self.query, query, 1); let begin = vk::VideoBeginCodingInfoKHR::builder() .video_session(self.vs.session) .video_session_parameters(self.vs.params) @@ -999,27 +1089,68 @@ impl Encoder { d.cmd_control_video_coding_khr(cb, &control); } - d.cmd_begin_query(cb, self.query, 0, vk::QueryControlFlags::empty()); + d.cmd_begin_query(cb, self.query, query, vk::QueryControlFlags::empty()); d.cmd_encode_video_khr(cb, encode); - d.cmd_end_query(cb, self.query, 0); + d.cmd_end_query(cb, self.query, query); let end = vk::VideoEndCodingInfoKHR::builder().build(); d.cmd_end_video_coding_khr(cb, &end); } - self.main.end()?; - self.main.submit()?; + slot.main.end()?; + let mut wait = vec![slot.ready]; + if let Some(p) = self.last { + wait.push(self.slots[p].encoded); + } + slot.main.submit_with(&wait, &[slot.encoded])?; + + self.last = Some(k); + self.next = k ^ 1; self.coded = true; self.applied = (self.rate, self.fps); self.dirty = false; - self.read_bitstream() + self.pending.push_back(k); + if self.pending.len() < FLIGHT { + return Ok(None); + } + let oldest = self + .pending + .pop_front() + .ok_or_else(|| Error::Invalid("no picture in flight".into()))?; + self.finish(oldest).map(Some) + } + + /// Waits for every queued picture and returns their bytes in submission order. + pub(crate) fn flush(&mut self) -> Result>, Error> { + let mut out = Vec::new(); + while let Some(k) = self.pending.pop_front() { + out.push(self.finish(k)?); + } + Ok(out) + } + + /// Flushes and returns the last picture, for synchronous use where one picture is queued per call. + pub(crate) fn flush_last(&mut self) -> Result, Error> { + self.flush()? + .pop() + .ok_or_else(|| Error::Invalid("no picture encoded".into())) } - fn read_bitstream(&self) -> Result, Error> { + fn finish(&mut self, k: usize) -> Result, Error> { + let slot = &self.slots[k]; + slot.main.wait()?; + slot.upload.wait()?; + let bytes = self.read_bitstream(k)?; + let d = self.vs.gpu.device(); + self.slots[k].release(d); + Ok(bytes) + } + + fn read_bitstream(&self, k: usize) -> Result, Error> { let mut feedback = [0u8; 8]; unsafe { vk( self.vs.gpu.device().get_query_pool_results( self.query, - 0, + k as u32, 1, &mut feedback, 8, @@ -1037,7 +1168,7 @@ impl Encoder { "encoded size exceeds bitstream buffer".into(), )); } - let ptr = self + let ptr = self.slots[k] .bitstream .ptr .ok_or_else(|| Error::Invalid("bitstream buffer not mapped".into()))?; @@ -1054,14 +1185,20 @@ impl Drop for Encoder { let _ = d.device_wait_idle(); d.destroy_query_pool(self.query, None); } - for img in self.dpb.iter().chain(std::iter::once(&self.src)) { + for img in &self.dpb { img.destroy(d); } - if let Some(rgb) = &self.rgb { - rgb.destroy(d); + for slot in self.slots.iter_mut() { + slot.release(d); + unsafe { + d.destroy_semaphore(slot.ready, None); + d.destroy_semaphore(slot.encoded, None); + } + slot.src.destroy(d); + slot.rgb.destroy(d); + slot.staging.destroy(d); + slot.bitstream.destroy(d); } - self.staging.destroy(d); - self.bitstream.destroy(d); } }