forge
Explore
Log in

Don't you dare go Hollow

Depth-2 pipelined Vulkan encode: shim slots, ec-vk and ec-hw submit/flush, hw_pipeline example

Browse files at this commit

87336a0b9ccfb03cb4f1b743254ad3f74ad43f59Ahmet Kaan GümüşParent: a9418fa
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+134 -0
@@ -7,6 +7,7 @@ use std::os::fd::BorrowedFd;
77 use ec_vk::DmaBuf;
88
99 use std::cell::RefCell;
10+use std::collections::VecDeque;
1011
1112 use crate::error::{Error, Result};
1213 use crate::picture::{Decoded, I420, I420_16, RgbPicture};
@@ -239,6 +240,20 @@ pub struct DmaBufFrame<'a> {
239240 pub order: RgbOrder,
240241 }
241242
243+/// One picture for [`HwEncoder::submit`].
244+#[derive(Debug, Clone, Copy)]
245+pub enum EncodeInput<'a> {
246+ /// 8-bit I420.
247+ I420(&'a I420),
248+ /// 10-bit I420 of a 10-bit encoder (H.265 and AV1).
249+ I420_16(&'a I420_16),
250+ /// Packed RGB, box-downscaled to the encoder size.
251+ Rgb(&'a RgbFrame<'a>),
252+ /// DMA-BUF of packed RGB, Vulkan only.
253+ #[cfg(target_os = "linux")]
254+ DmaBuf(&'a DmaBufFrame<'a>),
255+}
256+
242257 #[cfg(target_os = "linux")]
243258 fn rgb_to_i420(frame: &RgbFrame, (w, h): (usize, usize)) -> Result<I420> {
244259 let (sw, sh, stride) = (
@@ -297,7 +312,74 @@ enum VkEncoder {
297312 Av1(ec_vk::Av1Encoder),
298313 }
299314
315+fn stamp(pending: &mut VecDeque<i64>, coded: ec_vk::CodedFrame) -> CodedFrame {
316+ CodedFrame {
317+ data: coded.data,
318+ timestamp: pending.pop_front().unwrap_or_default(),
319+ is_keyframe: coded.keyframe,
320+ }
321+}
322+
300323 impl VkEncoder {
324+ fn submit(
325+ &mut self,
326+ input: EncodeInput,
327+ force_keyframe: bool,
328+ ) -> std::result::Result<Option<ec_vk::CodedFrame>, ec_vk::Error> {
329+ match input {
330+ EncodeInput::I420(frame) => {
331+ let (y, u, v) = (&frame.y, &frame.u, &frame.v);
332+ match self {
333+ VkEncoder::H264(e) => e.submit(y, u, v, force_keyframe),
334+ VkEncoder::H265(e) => e.submit(y, u, v, force_keyframe),
335+ VkEncoder::Av1(e) => e.submit(y, u, v, force_keyframe),
336+ }
337+ }
338+ EncodeInput::I420_16(frame) => {
339+ let (y, u, v) = (&frame.y, &frame.u, &frame.v);
340+ match self {
341+ VkEncoder::H264(_) => Err(ec_vk::Error::Unsupported("10-bit H.264 encode".into())),
342+ VkEncoder::H265(e) => e.submit_16(y, u, v, force_keyframe),
343+ VkEncoder::Av1(e) => e.submit_16(y, u, v, force_keyframe),
344+ }
345+ }
346+ EncodeInput::Rgb(frame) => {
347+ let bgr = frame.order == RgbOrder::Bgra;
348+ let (data, sw, sh, stride) = (frame.data, frame.width, frame.height, frame.stride);
349+ match self {
350+ VkEncoder::H264(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe),
351+ VkEncoder::H265(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe),
352+ VkEncoder::Av1(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe),
353+ }
354+ }
355+ #[cfg(target_os = "linux")]
356+ EncodeInput::DmaBuf(frame) => {
357+ let src = DmaBuf {
358+ fd: frame.fd,
359+ width: frame.width,
360+ height: frame.height,
361+ stride: frame.stride,
362+ offset: frame.offset,
363+ modifier: frame.modifier,
364+ bgr: frame.order == RgbOrder::Bgra,
365+ };
366+ match self {
367+ VkEncoder::H264(e) => e.submit_dmabuf(&src, force_keyframe),
368+ VkEncoder::H265(e) => e.submit_dmabuf(&src, force_keyframe),
369+ VkEncoder::Av1(e) => e.submit_dmabuf(&src, force_keyframe),
370+ }
371+ }
372+ }
373+ }
374+
375+ fn flush(&mut self) -> std::result::Result<Vec<ec_vk::CodedFrame>, ec_vk::Error> {
376+ match self {
377+ VkEncoder::H264(e) => e.flush(),
378+ VkEncoder::H265(e) => e.flush(),
379+ VkEncoder::Av1(e) => e.flush(),
380+ }
381+ }
382+
301383 fn encode(
302384 &mut self,
303385 frame: &I420,
@@ -386,6 +468,7 @@ pub struct HwEncoder {
386468 config: EncoderConfig,
387469 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
388470 size: (usize, usize),
471+ pending: VecDeque<i64>,
389472 }
390473
391474 impl HwEncoder {
@@ -406,6 +489,7 @@ impl HwEncoder {
406489 born_epoch,
407490 config,
408491 size,
492+ pending: VecDeque::new(),
409493 });
410494 }
411495 Err(e) => reasons.push(format!("{backend:?}: {e}")),
@@ -445,8 +529,55 @@ impl HwEncoder {
445529 Ok(())
446530 }
447531
532+ /// Submit one picture without waiting; the oldest coded picture comes back once two are in flight. Call [`HwEncoder::flush`] at the end.
533+ pub fn submit(&mut self, input: EncodeInput, meta: FrameMetadata) -> Result<Option<CodedFrame>> {
534+ match &mut self.inner {
535+ EncInner::Vk(enc) => {
536+ vk_session_alive(self.born_epoch)?;
537+ self.pending.push_back(meta.timestamp);
538+ let out = enc.submit(input, meta.force_keyframe)?;
539+ Ok(out.map(|coded| stamp(&mut self.pending, coded)))
540+ }
541+ #[cfg(target_os = "linux")]
542+ EncInner::Va(enc) => match input {
543+ EncodeInput::I420(frame) => enc.submit(frame, meta),
544+ EncodeInput::I420_16(frame) => enc.submit_16(frame, meta),
545+ EncodeInput::Rgb(frame) => enc.submit(&rgb_to_i420(frame, self.size)?, meta),
546+ EncodeInput::DmaBuf(_) => Err(Error::unsupported(
547+ "DMA-BUF encode",
548+ "the VA-API backend has no DMA-BUF input here",
549+ )),
550+ },
551+ }
552+ }
553+
554+ /// Wait for every submitted picture and return them, oldest first.
555+ pub fn flush(&mut self) -> Result<Vec<CodedFrame>> {
556+ match &mut self.inner {
557+ EncInner::Vk(enc) => {
558+ vk_session_alive(self.born_epoch)?;
559+ let frames = enc.flush()?;
560+ Ok(frames
561+ .into_iter()
562+ .map(|coded| stamp(&mut self.pending, coded))
563+ .collect())
564+ }
565+ #[cfg(target_os = "linux")]
566+ EncInner::Va(enc) => enc.flush(),
567+ }
568+ }
569+
570+ fn idle(&self) -> Result<()> {
571+ if self.pending.is_empty() {
572+ Ok(())
573+ } else {
574+ Err(Error::config("pipelined frames pending; call flush first"))
575+ }
576+ }
577+
448578 /// Encode one frame; `meta.force_keyframe` starts a new GOP.
449579 pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> {
580+ self.idle()?;
450581 match &mut self.inner {
451582 EncInner::Vk(enc) => {
452583 vk_session_alive(self.born_epoch)?;
@@ -464,6 +595,7 @@ impl HwEncoder {
464595
465596 /// Encode one 10-bit frame of a 10-bit encoder (H.265 and AV1), the [`HwEncoder::encode`] of a 10-bit encoder.
466597 pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result<CodedFrame> {
598+ self.idle()?;
467599 match &mut self.inner {
468600 EncInner::Vk(enc) => {
469601 let coded = enc.encode_16(frame, meta.force_keyframe)?;
@@ -480,6 +612,7 @@ impl HwEncoder {
480612
481613 /// 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.
482614 pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result<CodedFrame> {
615+ self.idle()?;
483616 match &mut self.inner {
484617 EncInner::Vk(enc) => {
485618 vk_session_alive(self.born_epoch)?;
@@ -502,6 +635,7 @@ impl HwEncoder {
502635 frame: &DmaBufFrame,
503636 meta: FrameMetadata,
504637 ) -> Result<CodedFrame> {
638+ self.idle()?;
505639 match &mut self.inner {
506640 EncInner::Vk(enc) => {
507641 vk_session_alive(self.born_epoch)?;
crates/ec-hw/src/lib.rsmodified+2 -1
@@ -88,7 +88,8 @@ pub use error::{Error, Result};
8888 #[cfg(target_os = "linux")]
8989 pub use hw::DmaBufFrame;
9090 pub use hw::{
91- Backend, Capability, Direction, HwDecoder, HwEncoder, RgbFrame, RgbOrder, RgbOutput,
91+ Backend, Capability, Direction, EncodeInput, HwDecoder, HwEncoder, RgbFrame, RgbOrder,
92+ RgbOutput,
9293 capabilities,
9394 };
9495 #[cfg(target_os = "linux")]
crates/ec-vk/src/av1.rsmodified+91 -28
@@ -2,7 +2,7 @@ use vk_video_ffi::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref};
22
33 #[cfg(target_os = "linux")]
44 use crate::DmaBuf;
5-use crate::{CodedFrame, Error, Gpu, RateControl};
5+use crate::{CodedFrame, Error, Flight, Gpu, RateControl, last_frame};
66
77 const TEMPORAL_DELIMITER: [u8; 2] = [0x12, 0x00];
88
@@ -35,6 +35,7 @@ pub struct Av1Encoder {
3535 reference: Option<Av1Ref>,
3636 uv: Vec<u8>,
3737 uv16: Vec<u16>,
38+ flight: Flight,
3839 }
3940
4041 impl Av1Encoder {
@@ -65,17 +66,18 @@ impl Av1Encoder {
6566 reference: None,
6667 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],
6768 uv16: vec![0; cfg.width as usize * cfg.height as usize / 2],
69+ flight: Flight::default(),
6870 })
6971 }
7072
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(
7375 &mut self,
7476 y: &[u8],
7577 u: &[u8],
7678 v: &[u8],
7779 force_keyframe: bool,
78- ) -> Result<CodedFrame, Error> {
80+ ) -> Result<Option<CodedFrame>, Error> {
7981 let chroma = self.width * self.height / 4;
8082 if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {
8183 return Err(Error::Invalid("I420 plane size".into()));
@@ -85,18 +87,31 @@ impl Av1Encoder {
8587 pair[1] = v[i];
8688 }
8789 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)))
9092 }
9193
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(
94109 &mut self,
95110 y: &[u16],
96111 u: &[u16],
97112 v: &[u16],
98113 force_keyframe: bool,
99- ) -> Result<CodedFrame, Error> {
114+ ) -> Result<Option<CodedFrame>, Error> {
100115 let chroma = self.width * self.height / 4;
101116 if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {
102117 return Err(Error::Invalid("I420 plane size".into()));
@@ -106,8 +121,27 @@ impl Av1Encoder {
106121 pair[1] = v[i];
107122 }
108123 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())
111145 }
112146
113147 /// Changes bitrate or frame rate; takes effect on the next frame.
@@ -115,6 +149,23 @@ impl Av1Encoder {
115149 Ok(self.session.set_rate(rate, fps)?)
116150 }
117151
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+
118169 /// 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.
119170 pub fn encode_rgb(
120171 &mut self,
@@ -125,9 +176,21 @@ impl Av1Encoder {
125176 bgr: bool,
126177 force_keyframe: bool,
127178 ) -> 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> {
128191 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)))
131194 }
132195
133196 /// 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 {
137200 src: &DmaBuf<'_>,
138201 force_keyframe: bool,
139202 ) -> 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)
143206 }
144207
145208 fn next_picture(&mut self, force_keyframe: bool) -> Av1Picture {
@@ -151,28 +214,28 @@ impl Av1Encoder {
151214 };
152215 let reference = if keyframe { None } else { self.reference };
153216 let slot = reference.map_or(0, |r| 1 - r.slot);
154- Av1Picture {
217+ let pic = Av1Picture {
155218 key: keyframe,
156219 order_hint: self.order_hint,
157220 slot,
158221 reference,
159- }
160- }
161-
162- fn finish(&mut self, pic: &Av1Picture, frame: Vec<u8>) -> CodedFrame {
222+ };
163223 self.reference = Some(Av1Ref {
164224 slot: pic.slot,
165225 order_hint: pic.order_hint,
166226 });
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();
168234 let mut data = TEMPORAL_DELIMITER.to_vec();
169- if pic.key {
235+ if keyframe {
170236 data.extend_from_slice(&self.sequence_header);
171237 }
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 }
177240 }
178241 }
crates/ec-vk/src/h265.rsmodified+92 -29
@@ -2,7 +2,7 @@ use vk_video_ffi::{H265EncodeConfig, H265EncodeSession, H265Picture, H265Ref};
22
33 #[cfg(target_os = "linux")]
44 use crate::DmaBuf;
5-use crate::{CodedFrame, Error, Gpu, RateControl};
5+use crate::{CodedFrame, Error, Flight, Gpu, RateControl, last_frame};
66
77 /// H.265 encoder settings.
88 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -33,6 +33,7 @@ pub struct H265Encoder {
3333 reference: Option<H265Ref>,
3434 uv: Vec<u8>,
3535 uv16: Vec<u16>,
36+ flight: Flight,
3637 }
3738
3839 impl H265Encoder {
@@ -63,17 +64,18 @@ impl H265Encoder {
6364 reference: None,
6465 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],
6566 uv16: vec![0; cfg.width as usize * cfg.height as usize / 2],
67+ flight: Flight::default(),
6668 })
6769 }
6870
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(
7173 &mut self,
7274 y: &[u8],
7375 u: &[u8],
7476 v: &[u8],
7577 force_keyframe: bool,
76- ) -> Result<CodedFrame, Error> {
78+ ) -> Result<Option<CodedFrame>, Error> {
7779 let chroma = self.width * self.height / 4;
7880 if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {
7981 return Err(Error::Invalid("I420 plane size".into()));
@@ -83,18 +85,31 @@ impl H265Encoder {
8385 pair[1] = v[i];
8486 }
8587 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)))
8890 }
8991
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(
92107 &mut self,
93108 y: &[u16],
94109 u: &[u16],
95110 v: &[u16],
96111 force_keyframe: bool,
97- ) -> Result<CodedFrame, Error> {
112+ ) -> Result<Option<CodedFrame>, Error> {
98113 let chroma = self.width * self.height / 4;
99114 if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {
100115 return Err(Error::Invalid("I420 plane size".into()));
@@ -104,8 +119,27 @@ impl H265Encoder {
104119 pair[1] = v[i];
105120 }
106121 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())
109143 }
110144
111145 /// Changes bitrate or frame rate; takes effect on the next frame.
@@ -113,6 +147,23 @@ impl H265Encoder {
113147 Ok(self.session.set_rate(rate, fps)?)
114148 }
115149
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+
116167 /// 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.
117168 pub fn encode_rgb(
118169 &mut self,
@@ -123,9 +174,21 @@ impl H265Encoder {
123174 bgr: bool,
124175 force_keyframe: bool,
125176 ) -> 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> {
126189 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)))
129192 }
130193
131194 /// 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 {
135198 src: &DmaBuf<'_>,
136199 force_keyframe: bool,
137200 ) -> 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)
141204 }
142205
143206 fn next_picture(&mut self, force_keyframe: bool) -> H265Picture {
@@ -145,28 +208,28 @@ impl H265Encoder {
145208 self.poc = if keyframe { 0 } else { self.poc + 1 };
146209 let reference = if keyframe { None } else { self.reference };
147210 let slot = reference.map_or(0, |r| 1 - r.slot);
148- H265Picture {
211+ let pic = H265Picture {
149212 idr: keyframe,
150213 poc: self.poc,
151214 slot,
152215 reference,
153- }
154- }
155-
156- fn finish(&mut self, pic: &H265Picture, slice: Vec<u8>) -> CodedFrame {
216+ };
157217 self.reference = Some(H265Ref {
158218 slot: pic.slot,
159219 poc: pic.poc,
160220 });
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()
164230 } else {
165- slice
231+ bytes
166232 };
167- CodedFrame {
168- data,
169- keyframe: pic.idr,
170- }
233+ CodedFrame { data, keyframe }
171234 }
172235 }
crates/ec-vk/src/lib.rsmodified+99 -24
@@ -2,6 +2,8 @@
22 #![forbid(unsafe_code)]
33 #![deny(missing_docs)]
44
5+use std::collections::VecDeque;
6+
57 use vk_video_ffi::{H264EncodeConfig, H264EncodeSession, H264Picture, H264Ref};
68
79 mod av1;
@@ -48,6 +50,29 @@ pub struct CodedFrame {
4850 pub keyframe: bool,
4951 }
5052
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+
5176 /// H.264 encoder: GOP, frame_num, POC and DPB slot bookkeeping over [`H264EncodeSession`].
5277 pub struct H264Encoder {
5378 session: H264EncodeSession,
@@ -61,6 +86,7 @@ pub struct H264Encoder {
6186 idr_pic_id: u16,
6287 reference: Option<H264Ref>,
6388 uv: Vec<u8>,
89+ flight: Flight,
6490 }
6591
6692 impl H264Encoder {
@@ -92,17 +118,18 @@ impl H264Encoder {
92118 idr_pic_id: 0,
93119 reference: None,
94120 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],
121+ flight: Flight::default(),
95122 })
96123 }
97124
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(
100127 &mut self,
101128 y: &[u8],
102129 u: &[u8],
103130 v: &[u8],
104131 force_keyframe: bool,
105- ) -> Result<CodedFrame, Error> {
132+ ) -> Result<Option<CodedFrame>, Error> {
106133 let chroma = self.width * self.height / 4;
107134 if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {
108135 return Err(Error::Invalid("I420 plane size".into()));
@@ -112,8 +139,27 @@ impl H264Encoder {
112139 pair[1] = v[i];
113140 }
114141 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())
117163 }
118164
119165 /// Changes bitrate or frame rate; takes effect on the next frame.
@@ -121,6 +167,23 @@ impl H264Encoder {
121167 Ok(self.session.set_rate(rate, fps)?)
122168 }
123169
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+
124187 /// 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.
125188 pub fn encode_rgb(
126189 &mut self,
@@ -131,9 +194,21 @@ impl H264Encoder {
131194 bgr: bool,
132195 force_keyframe: bool,
133196 ) -> 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> {
134209 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)))
137212 }
138213
139214 /// 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 {
143218 src: &DmaBuf<'_>,
144219 force_keyframe: bool,
145220 ) -> 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)
149224 }
150225
151226 fn next_picture(&mut self, force_keyframe: bool) -> H264Picture {
@@ -159,34 +234,34 @@ impl H264Encoder {
159234 }
160235 let reference = if keyframe { None } else { self.reference };
161236 let slot = reference.map_or(0, |r| 1 - r.slot);
162- H264Picture {
237+ let pic = H264Picture {
163238 idr: keyframe,
164239 idr_pic_id: self.idr_pic_id,
165240 frame_num: self.frame_num,
166241 poc: self.poc,
167242 slot,
168243 reference,
169- }
170- }
171-
172- fn finish(&mut self, pic: &H264Picture, slice: Vec<u8>) -> CodedFrame {
244+ };
173245 self.reference = Some(H264Ref {
174246 slot: pic.slot,
175247 frame_num: pic.frame_num,
176248 poc: pic.poc,
177249 });
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 {
180252 self.idr_pic_id = self.idr_pic_id.wrapping_add(1);
181253 }
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()
184262 } else {
185- slice
263+ bytes
186264 };
187- CodedFrame {
188- data,
189- keyframe: pic.idr,
190- }
265+ CodedFrame { data, keyframe }
191266 }
192267 }
shims/vk-video-ffi/src/av1_encode.rsmodified+49 -11
@@ -224,8 +224,8 @@ impl Av1EncodeSession {
224224 self.seq.clone()
225225 }
226226
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> {
229229 if y.len() != self.enc.input.0 * self.enc.input.1
230230 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2
231231 {
@@ -236,8 +236,8 @@ impl Av1EncodeSession {
236236 self.encode_uploaded(pic)
237237 }
238238
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> {
241241 if y.len() != self.enc.input.0 * self.enc.input.1
242242 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2
243243 {
@@ -249,7 +249,7 @@ impl Av1EncodeSession {
249249 }
250250
251251 /// 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(
253253 &mut self,
254254 rgb: &[u8],
255255 src_width: u32,
@@ -257,7 +257,7 @@ impl Av1EncodeSession {
257257 stride_bytes: u32,
258258 bgr: bool,
259259 pic: &Av1Picture,
260- ) -> Result<Vec<u8>, Error> {
260+ ) -> Result<Option<Vec<u8>>, Error> {
261261 self.check(pic)?;
262262 let src = (src_width as usize, src_height as usize);
263263 check_rgb(
@@ -277,13 +277,13 @@ impl Av1EncodeSession {
277277 }
278278 /// Encodes one picture from a DMA-BUF of BGRx or RGBx pixels, box-downscaled to the encoder size on the GPU.
279279 #[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> {
281281 self.check(pic)?;
282282 self.enc.upload_dmabuf(src)?;
283283 self.encode_uploaded(pic)
284284 }
285285
286- fn encode_uploaded(&mut self, pic: &Av1Picture) -> Result<Vec<u8>, Error> {
286+ fn encode_uploaded(&mut self, pic: &Av1Picture) -> Result<Option<Vec<u8>>, Error> {
287287 let extent = self.enc.extent;
288288
289289 let refresh: u8 = if pic.key { 0xff } else { 1 << pic.slot };
@@ -291,7 +291,7 @@ impl Av1EncodeSession {
291291 picture_resource(self.enc.dpb[0].view, extent),
292292 picture_resource(self.enc.dpb[1].view, extent),
293293 ];
294- let src_pr = picture_resource(self.enc.src.view, extent);
294+ let src_pr = picture_resource(self.enc.src_view(), extent);
295295
296296 let key_of = self.slot_key;
297297 let mut new_std = zeroed::<vk::video::StdVideoEncodeAV1ReferenceInfo>();
@@ -393,7 +393,7 @@ impl Av1EncodeSession {
393393 };
394394
395395 let encode = vk::VideoEncodeInfoKHR::builder()
396- .dst_buffer(self.enc.bitstream.buffer)
396+ .dst_buffer(self.enc.bitstream_buffer())
397397 .dst_buffer_offset(0)
398398 .dst_buffer_range(self.enc.bitstream_len)
399399 .src_picture_resource(src_pr)
@@ -406,7 +406,7 @@ impl Av1EncodeSession {
406406 let mut chain = RateChain::new(self.enc.rate, self.enc.fps);
407407 let out = self
408408 .enc
409- .run(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)?;
409+ .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)?;
410410 for i in 0..DPB_SLOTS {
411411 if refresh >> i & 1 == 1 {
412412 self.slot_key[i] = pic.key;
@@ -420,6 +420,44 @@ impl Av1EncodeSession {
420420 Ok(out)
421421 }
422422
423+ /// Encodes one picture synchronously and returns its coded bytes.
424+ pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &Av1Picture) -> Result<Vec<u8>, Error> {
425+ self.submit(y, uv, pic)?;
426+ self.enc.flush_last()
427+ }
428+
429+ /// Encodes one picture synchronously and returns its coded bytes.
430+ pub fn encode_16(&mut self, y: &[u16], uv: &[u16], pic: &Av1Picture) -> Result<Vec<u8>, Error> {
431+ self.submit_16(y, uv, pic)?;
432+ self.enc.flush_last()
433+ }
434+
435+ /// Encodes one picture synchronously and returns its coded bytes.
436+ pub fn encode_rgb(
437+ &mut self,
438+ rgb: &[u8],
439+ src_width: u32,
440+ src_height: u32,
441+ stride_bytes: u32,
442+ bgr: bool,
443+ pic: &Av1Picture,
444+ ) -> Result<Vec<u8>, Error> {
445+ self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?;
446+ self.enc.flush_last()
447+ }
448+
449+ #[cfg(target_os = "linux")]
450+ /// Encodes one picture synchronously and returns its coded bytes.
451+ pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &Av1Picture) -> Result<Vec<u8>, Error> {
452+ self.submit_dmabuf(src, pic)?;
453+ self.enc.flush_last()
454+ }
455+
456+ /// Waits for queued pictures and returns their coded bytes in order.
457+ pub fn flush(&mut self) -> Result<Vec<Vec<u8>>, Error> {
458+ self.enc.flush()
459+ }
460+
423461 /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change.
424462 pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {
425463 self.enc.set_rate(rate, fps)
shims/vk-video-ffi/src/h264_encode.rsmodified+41 -9
@@ -253,8 +253,8 @@ impl H264EncodeSession {
253253 )
254254 }
255255
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> {
258258 let (w, h) = self.enc.input;
259259 if y.len() != w * h || uv.len() != w * h / 2 {
260260 return Err(Error::Invalid("NV12 plane size".into()));
@@ -265,7 +265,7 @@ impl H264EncodeSession {
265265 }
266266
267267 /// 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(
269269 &mut self,
270270 rgb: &[u8],
271271 src_width: u32,
@@ -273,7 +273,7 @@ impl H264EncodeSession {
273273 stride_bytes: u32,
274274 bgr: bool,
275275 pic: &H264Picture,
276- ) -> Result<Vec<u8>, Error> {
276+ ) -> Result<Option<Vec<u8>>, Error> {
277277 self.check(pic)?;
278278 let src = (src_width as usize, src_height as usize);
279279 check_rgb(self.enc.input, src, rgb, stride_bytes as usize)?;
@@ -289,13 +289,13 @@ impl H264EncodeSession {
289289
290290 /// Encodes one picture from a DMA-BUF of BGRx or RGBx pixels, box-downscaled to the encoder size on the GPU.
291291 #[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> {
293293 self.check(pic)?;
294294 self.enc.upload_dmabuf(src)?;
295295 self.encode_uploaded(pic)
296296 }
297297
298- fn encode_uploaded(&mut self, pic: &H264Picture) -> Result<Vec<u8>, Error> {
298+ fn encode_uploaded(&mut self, pic: &H264Picture) -> Result<Option<Vec<u8>>, Error> {
299299 let extent = self.enc.extent;
300300
301301 let primary = if pic.idr {
@@ -307,7 +307,7 @@ impl H264EncodeSession {
307307 picture_resource(self.enc.dpb[0].view, extent),
308308 picture_resource(self.enc.dpb[1].view, extent),
309309 ];
310- let src_pr = picture_resource(self.enc.src.view, extent);
310+ let src_pr = picture_resource(self.enc.src_view(), extent);
311311
312312 let new_std = reference_info(primary, pic.frame_num, pic.poc);
313313 let ref_std = pic
@@ -394,7 +394,7 @@ impl H264EncodeSession {
394394 .build();
395395
396396 let encode = vk::VideoEncodeInfoKHR::builder()
397- .dst_buffer(self.enc.bitstream.buffer)
397+ .dst_buffer(self.enc.bitstream_buffer())
398398 .dst_buffer_offset(0)
399399 .dst_buffer_range(self.enc.bitstream_len)
400400 .src_picture_resource(src_pr)
@@ -406,7 +406,39 @@ impl H264EncodeSession {
406406 let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1);
407407 let mut chain = RateChain::new(self.enc.rate, self.enc.fps);
408408 self.enc
409- .run(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)
409+ .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)
410+ }
411+
412+ /// Encodes one picture synchronously and returns its coded bytes.
413+ pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &H264Picture) -> Result<Vec<u8>, Error> {
414+ self.submit(y, uv, pic)?;
415+ self.enc.flush_last()
416+ }
417+
418+ /// Encodes one picture synchronously and returns its coded bytes.
419+ pub fn encode_rgb(
420+ &mut self,
421+ rgb: &[u8],
422+ src_width: u32,
423+ src_height: u32,
424+ stride_bytes: u32,
425+ bgr: bool,
426+ pic: &H264Picture,
427+ ) -> Result<Vec<u8>, Error> {
428+ self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?;
429+ self.enc.flush_last()
430+ }
431+
432+ #[cfg(target_os = "linux")]
433+ /// Encodes one picture synchronously and returns its coded bytes.
434+ pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H264Picture) -> Result<Vec<u8>, Error> {
435+ self.submit_dmabuf(src, pic)?;
436+ self.enc.flush_last()
437+ }
438+
439+ /// Waits for queued pictures and returns their coded bytes in order.
440+ pub fn flush(&mut self) -> Result<Vec<Vec<u8>>, Error> {
441+ self.enc.flush()
410442 }
411443
412444 /// 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 {
258258 )
259259 }
260260
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> {
263263 if y.len() != self.enc.input.0 * self.enc.input.1
264264 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2
265265 {
@@ -270,13 +270,13 @@ impl H265EncodeSession {
270270 self.encode_uploaded(pic)
271271 }
272272
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(
275275 &mut self,
276276 y: &[u16],
277277 uv: &[u16],
278278 pic: &H265Picture,
279- ) -> Result<Vec<u8>, Error> {
279+ ) -> Result<Option<Vec<u8>>, Error> {
280280 if y.len() != self.enc.input.0 * self.enc.input.1
281281 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2
282282 {
@@ -288,7 +288,7 @@ impl H265EncodeSession {
288288 }
289289
290290 /// 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(
292292 &mut self,
293293 rgb: &[u8],
294294 src_width: u32,
@@ -296,7 +296,7 @@ impl H265EncodeSession {
296296 stride_bytes: u32,
297297 bgr: bool,
298298 pic: &H265Picture,
299- ) -> Result<Vec<u8>, Error> {
299+ ) -> Result<Option<Vec<u8>>, Error> {
300300 self.check(pic)?;
301301 let src = (src_width as usize, src_height as usize);
302302 check_rgb(
@@ -317,13 +317,13 @@ impl H265EncodeSession {
317317
318318 /// Encodes one picture from a DMA-BUF of BGRx or RGBx pixels, box-downscaled to the encoder size on the GPU.
319319 #[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> {
321321 self.check(pic)?;
322322 self.enc.upload_dmabuf(src)?;
323323 self.encode_uploaded(pic)
324324 }
325325
326- fn encode_uploaded(&mut self, pic: &H265Picture) -> Result<Vec<u8>, Error> {
326+ fn encode_uploaded(&mut self, pic: &H265Picture) -> Result<Option<Vec<u8>>, Error> {
327327 let extent = self.enc.extent;
328328
329329 let primary = if pic.idr {
@@ -335,7 +335,7 @@ impl H265EncodeSession {
335335 picture_resource(self.enc.dpb[0].view, extent),
336336 picture_resource(self.enc.dpb[1].view, extent),
337337 ];
338- let src_pr = picture_resource(self.enc.src.view, extent);
338+ let src_pr = picture_resource(self.enc.src_view(), extent);
339339
340340 let new_std = reference_info(primary, pic.poc);
341341 let ref_std = pic
@@ -425,7 +425,7 @@ impl H265EncodeSession {
425425 .build();
426426
427427 let encode = vk::VideoEncodeInfoKHR::builder()
428- .dst_buffer(self.enc.bitstream.buffer)
428+ .dst_buffer(self.enc.bitstream_buffer())
429429 .dst_buffer_offset(0)
430430 .dst_buffer_range(self.enc.bitstream_len)
431431 .src_picture_resource(src_pr)
@@ -437,7 +437,45 @@ impl H265EncodeSession {
437437 let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1);
438438 let mut chain = RateChain::new(self.enc.rate, self.enc.fps);
439439 self.enc
440- .run(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)
440+ .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)
441+ }
442+
443+ /// Encodes one picture synchronously and returns its coded bytes.
444+ pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &H265Picture) -> Result<Vec<u8>, Error> {
445+ self.submit(y, uv, pic)?;
446+ self.enc.flush_last()
447+ }
448+
449+ /// Encodes one picture synchronously and returns its coded bytes.
450+ pub fn encode_16(&mut self, y: &[u16], uv: &[u16], pic: &H265Picture) -> Result<Vec<u8>, Error> {
451+ self.submit_16(y, uv, pic)?;
452+ self.enc.flush_last()
453+ }
454+
455+ /// Encodes one picture synchronously and returns its coded bytes.
456+ pub fn encode_rgb(
457+ &mut self,
458+ rgb: &[u8],
459+ src_width: u32,
460+ src_height: u32,
461+ stride_bytes: u32,
462+ bgr: bool,
463+ pic: &H265Picture,
464+ ) -> Result<Vec<u8>, Error> {
465+ self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?;
466+ self.enc.flush_last()
467+ }
468+
469+ #[cfg(target_os = "linux")]
470+ /// Encodes one picture synchronously and returns its coded bytes.
471+ pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H265Picture) -> Result<Vec<u8>, Error> {
472+ self.submit_dmabuf(src, pic)?;
473+ self.enc.flush_last()
474+ }
475+
476+ /// Waits for queued pictures and returns their coded bytes in order.
477+ pub fn flush(&mut self) -> Result<Vec<Vec<u8>>, Error> {
478+ self.enc.flush()
441479 }
442480
443481 /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change.
shims/vk-video-ffi/src/session.rsmodified+260 -123
@@ -1,3 +1,5 @@
1+use std::collections::VecDeque;
2+
13 use vulkanalia::prelude::v1_3::*;
24 use vulkanalia::vk::{
35 KhrVideoDecodeQueueExtensionDeviceCommands, KhrVideoEncodeQueueExtensionDeviceCommands,
@@ -657,22 +659,38 @@ impl Lane {
657659 }
658660 }
659661
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> {
661667 let d = self.gpu.device();
662668 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();
664676 unsafe {
665677 vk(d.reset_fences(&[self.fence]), "vkResetFences")?;
666678 vk(
667679 d.queue_submit(self.queue, &[submit], self.fence),
668680 "vkQueueSubmit",
669- )?;
670- vk(
671- d.wait_for_fences(&[self.fence], true, u64::MAX),
672- "vkWaitForFences",
673- )?;
681+ )
674682 }
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()
676694 }
677695 }
678696
@@ -686,101 +704,143 @@ impl Drop for Lane {
686704 }
687705 }
688706
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,
704721 staging: Buffer,
705- rgb: Option<RgbConverter>,
706- pub(crate) bitstream: Buffer,
707- query: vk::QueryPool,
722+ rgb: RgbConverter,
723+ bitstream: Buffer,
724+ main: Lane,
725+ upload: Lane,
726+ ready: vk::Semaphore,
727+ encoded: vk::Semaphore,
728+ #[cfg(target_os = "linux")]
729+ import: Option<Import>,
708730 }
709731
710-impl Encoder {
711- pub(crate) fn new(
712- vs: VideoSession,
732+impl Slot {
733+ fn new(
734+ vs: &mut VideoSession,
713735 profile: &vk::VideoProfileInfoKHR,
714736 upload_family: u32,
715737 input: (u32, u32),
716738 extent: vk::Extent2D,
717- setting: (RateControl, (u32, u32)),
718- size_align: u64,
739+ frame_bytes: u64,
740+ bitstream_len: u64,
719741 ) -> Result<Self, Error> {
720742 let gpu = vs.gpu.clone();
721- let main = Lane::new(&gpu, vs.family)?;
722- let upload = Lane::new(&gpu, upload_family)?;
723- let mut e = Encoder {
724- vs,
725- main,
726- upload,
727- input: (input.0 as usize, input.1 as usize),
728- extent,
729- rate: setting.0,
730- fps: setting.1,
731- applied: setting,
732- dirty: false,
733- coded: false,
734- bitstream_len: 0,
735- dpb: Default::default(),
736- src: Default::default(),
737- staging: Default::default(),
738- rgb: None,
739- bitstream: Default::default(),
740- query: Default::default(),
741- };
742- let bytes = bytes_per_sample(e.vs.format) as u64;
743- let frame_bytes = extent.width as u64 * extent.height as u64 * 3 / 2 * bytes;
744- let usage = vk::ImageUsageFlags::VIDEO_ENCODE_DPB_KHR;
743+ let d = gpu.device();
744+ let family = vs.family;
745745 let mut list = vk::VideoProfileListInfoKHR::builder()
746746 .profiles(std::slice::from_ref(profile))
747747 .build();
748- let family = e.vs.family;
749- e.dpb[0] = e.vs.image(extent, usage, usage, &[family], &mut list)?;
750- e.dpb[1] = e.vs.image(extent, usage, usage, &[family], &mut list)?;
751748 let shared = if upload_family == family {
752749 vec![family]
753750 } else {
754751 vec![upload_family, family]
755752 };
756- e.src = e.vs.image(
753+ let src = vs.image(
757754 extent,
758755 vk::ImageUsageFlags::VIDEO_ENCODE_SRC_KHR | vk::ImageUsageFlags::TRANSFER_DST,
759756 vk::ImageUsageFlags::VIDEO_ENCODE_SRC_KHR | vk::ImageUsageFlags::TRANSFER_DST,
760757 &shared,
761758 &mut list,
762759 )?;
763- e.staging = e.vs.buffer(
760+ let staging = vs.buffer(
764761 frame_bytes,
765762 vk::BufferUsageFlags::TRANSFER_SRC | vk::BufferUsageFlags::STORAGE_BUFFER,
766763 &[vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT],
767764 None,
768765 )?;
769- e.rgb = Some(RgbConverter::new(
770- &gpu,
771- input,
772- (extent.width, extent.height),
773- e.staging.buffer,
774- )?);
775- e.bitstream_len = align_u64(frame_bytes, size_align);
776- e.bitstream = e.vs.buffer(
777- e.bitstream_len,
766+ let rgb = RgbConverter::new(&gpu, input, (extent.width, extent.height), staging.buffer)?;
767+ let bitstream = vs.buffer(
768+ bitstream_len,
778769 vk::BufferUsageFlags::VIDEO_ENCODE_DST_KHR,
779770 &[vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT],
780771 Some(&mut list),
781772 )?;
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+ }
782786
787+ fn release(&mut self, d: &Device) {
788+ #[cfg(target_os = "linux")]
789+ if let Some(import) = self.import.take() {
790+ import.destroy(d);
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+ slots: [Slot; FLIGHT],
808+ cur: usize,
809+ next: usize,
810+ last: Option<usize>,
811+ pending: VecDeque<usize>,
812+ query: vk::QueryPool,
813+}
814+
815+impl Encoder {
816+ pub(crate) fn new(
817+ mut vs: VideoSession,
818+ profile: &vk::VideoProfileInfoKHR,
819+ upload_family: u32,
820+ input: (u32, u32),
821+ extent: vk::Extent2D,
822+ setting: (RateControl, (u32, u32)),
823+ size_align: u64,
824+ ) -> Result<Self, Error> {
825+ let gpu = vs.gpu.clone();
783826 let d = gpu.device();
827+ let bytes = bytes_per_sample(vs.format) as u64;
828+ let frame_bytes = extent.width as u64 * extent.height as u64 * 3 / 2 * bytes;
829+ let bitstream_len = align_u64(frame_bytes, size_align);
830+ let usage = vk::ImageUsageFlags::VIDEO_ENCODE_DPB_KHR;
831+ let mut list = vk::VideoProfileListInfoKHR::builder()
832+ .profiles(std::slice::from_ref(profile))
833+ .build();
834+ let family = vs.family;
835+ let dpb = [
836+ vs.image(extent, usage, usage, &[family], &mut list)?,
837+ vs.image(extent, usage, usage, &[family], &mut list)?,
838+ ];
839+ let slots = [
840+ Slot::new(&mut vs, profile, upload_family, input, extent, frame_bytes, bitstream_len)?,
841+ Slot::new(&mut vs, profile, upload_family, input, extent, frame_bytes, bitstream_len)?,
842+ ];
843+
784844 let mut feedback = vk::QueryPoolVideoEncodeFeedbackCreateInfoKHR::builder()
785845 .encode_feedback_flags(
786846 vk::VideoEncodeFeedbackFlagsKHR::BITSTREAM_BUFFER_OFFSET
@@ -790,28 +850,51 @@ impl Encoder {
790850 let mut prof = *profile;
791851 let query_info = vk::QueryPoolCreateInfo::builder()
792852 .query_type(vk::QueryType::VIDEO_ENCODE_FEEDBACK_KHR)
793- .query_count(1)
853+ .query_count(FLIGHT as u32)
794854 .push_next(&mut feedback)
795855 .push_next(&mut prof)
796856 .build();
797- e.query = unsafe { vk(d.create_query_pool(&query_info, None), "vkCreateQueryPool")? };
857+ let query = unsafe { vk(d.create_query_pool(&query_info, None), "vkCreateQueryPool")? };
798858
799- e.main.begin()?;
859+ let e = Encoder {
860+ vs,
861+ input: (input.0 as usize, input.1 as usize),
862+ extent,
863+ rate: setting.0,
864+ fps: setting.1,
865+ applied: setting,
866+ dirty: false,
867+ coded: false,
868+ bitstream_len,
869+ dpb,
870+ slots,
871+ cur: 0,
872+ next: 0,
873+ last: None,
874+ pending: VecDeque::new(),
875+ query,
876+ };
877+ let lane = &e.slots[0].main;
878+ lane.begin()?;
800879 for img in &e.dpb {
801- init_barrier(
802- d,
803- e.main.cb,
804- img.image,
805- vk::ImageLayout::VIDEO_ENCODE_DPB_KHR,
806- );
880+ init_barrier(d, lane.cb, img.image, vk::ImageLayout::VIDEO_ENCODE_DPB_KHR);
807881 }
808- e.main.end()?;
809- e.main.submit()?;
882+ lane.end()?;
883+ lane.submit()?;
810884 Ok(e)
811885 }
812886
813- pub(crate) fn staging_ptr(&self) -> Result<*mut u8, Error> {
814- self.staging
887+ pub(crate) fn src_view(&self) -> vk::ImageView {
888+ self.slots[self.cur].src.view
889+ }
890+
891+ pub(crate) fn bitstream_buffer(&self) -> vk::Buffer {
892+ self.slots[self.cur].bitstream.buffer
893+ }
894+
895+ fn staging_ptr(&self) -> Result<*mut u8, Error> {
896+ self.slots[self.cur]
897+ .staging
815898 .ptr
816899 .ok_or_else(|| Error::Invalid("staging buffer not mapped".into()))
817900 }
@@ -844,6 +927,8 @@ impl Encoder {
844927 _ => {}
845928 }
846929 let gpu = self.vs.gpu.clone();
930+ let k = self.next;
931+ self.cur = k;
847932 match input {
848933 Input::Nv12 { y, uv } => {
849934 let staging =
@@ -862,42 +947,36 @@ impl Encoder {
862947 stride,
863948 ..
864949 } => {
865- let rgb = self
866- .rgb
867- .as_mut()
868- .ok_or_else(|| Error::Invalid("RGB converter not created".into()))?;
950+ let rgb = &mut self.slots[k].rgb;
869951 rgb.reserve(&gpu, width, height)?;
870952 rgb.load(data, stride);
871953 }
872954 #[cfg(target_os = "linux")]
873955 Input::DmaBuf { width, height, .. } => {
874- let rgb = self
875- .rgb
876- .as_mut()
877- .ok_or_else(|| Error::Invalid("RGB converter not created".into()))?;
878- rgb.reserve(&gpu, width, height)?;
956+ self.slots[k].rgb.reserve(&gpu, width, height)?;
879957 }
880958 }
881959
882960 let d = gpu.device();
883- let cb = self.upload.cb;
961+ let slot = &self.slots[k];
962+ let cb = slot.upload.cb;
884963 let luma = (aw * ah * bytes) as u64;
885964 let copies = [
886965 copy_region(0, PLANE_0, aw as u32, ah as u32),
887966 copy_region(luma, PLANE_1, (aw / 2) as u32, (ah / 2) as u32),
888967 ];
889- self.upload.begin()?;
968+ slot.upload.begin()?;
890969 unsafe {
891- if let (Some(bgr), Some(rgb)) = (input.bgr(), &self.rgb) {
970+ if let Some(bgr) = input.bgr() {
892971 if let Some(image) = input.source_image() {
893- rgb.record_import(d, cb, image, self.upload.family);
972+ slot.rgb.record_import(d, cb, image, slot.upload.family);
894973 }
895- rgb.record(d, cb, bgr);
974+ slot.rgb.record(d, cb, bgr);
896975 }
897976 barrier(
898977 d,
899978 cb,
900- self.src.image,
979+ slot.src.image,
901980 (
902981 vk::ImageLayout::UNDEFINED,
903982 vk::PipelineStageFlags2::NONE,
@@ -911,15 +990,15 @@ impl Encoder {
911990 );
912991 d.cmd_copy_buffer_to_image(
913992 cb,
914- self.staging.buffer,
915- self.src.image,
993+ slot.staging.buffer,
994+ slot.src.image,
916995 vk::ImageLayout::TRANSFER_DST_OPTIMAL,
917996 &copies,
918997 );
919998 barrier(
920999 d,
9211000 cb,
922- self.src.image,
1001+ slot.src.image,
9231002 (
9241003 vk::ImageLayout::TRANSFER_DST_OPTIMAL,
9251004 vk::PipelineStageFlags2::COPY,
@@ -932,8 +1011,8 @@ impl Encoder {
9321011 ),
9331012 );
9341013 }
935- self.upload.end()?;
936- self.upload.submit()
1014+ slot.upload.end()?;
1015+ slot.upload.submit_with(&[], &[slot.ready])
9371016 }
9381017
9391018 #[cfg(target_os = "linux")]
@@ -948,30 +1027,41 @@ impl Encoder {
9481027 height,
9491028 bgr: src.bgr,
9501029 });
951- import.destroy(gpu.device());
952- result
1030+ match result {
1031+ Ok(()) => {
1032+ self.slots[self.cur].import = Some(import);
1033+ Ok(())
1034+ }
1035+ Err(e) => {
1036+ import.destroy(gpu.device());
1037+ Err(e)
1038+ }
1039+ }
9531040 }
9541041
955- /// Records one encode with its rate control chains, submits it and returns the coded bytes.
956- pub(crate) fn run(
1042+ /// Records the encode of the uploaded slot and submits it without waiting. Returns the oldest picture once FLIGHT are queued.
1043+ pub(crate) fn submit(
9571044 &mut self,
9581045 begin_slots: &[vk::VideoReferenceSlotInfoKHR],
9591046 applied: &mut vk::VideoEncodeRateControlInfoKHR,
9601047 chain: &mut vk::VideoEncodeRateControlInfoKHR,
9611048 encode: &vk::VideoEncodeInfoKHR,
962- ) -> Result<Vec<u8>, Error> {
1049+ ) -> Result<Option<Vec<u8>>, Error> {
9631050 let gpu = self.vs.gpu.clone();
9641051 let d = gpu.device();
965- let cb = self.main.cb;
1052+ let k = self.cur;
1053+ let slot = &self.slots[k];
1054+ let cb = slot.main.cb;
1055+ let query = k as u32;
9661056 let mut quality = vk::VideoEncodeQualityLevelInfoKHR::builder()
9671057 .quality_level(0)
9681058 .build();
9691059 let reset = !self.coded;
9701060 let update = reset || self.dirty;
9711061
972- self.main.begin()?;
1062+ slot.main.begin()?;
9731063 unsafe {
974- d.cmd_reset_query_pool(cb, self.query, 0, 1);
1064+ d.cmd_reset_query_pool(cb, self.query, query, 1);
9751065 let begin = vk::VideoBeginCodingInfoKHR::builder()
9761066 .video_session(self.vs.session)
9771067 .video_session_parameters(self.vs.params)
@@ -999,27 +1089,68 @@ impl Encoder {
9991089 d.cmd_control_video_coding_khr(cb, &control);
10001090 }
10011091
1002- d.cmd_begin_query(cb, self.query, 0, vk::QueryControlFlags::empty());
1092+ d.cmd_begin_query(cb, self.query, query, vk::QueryControlFlags::empty());
10031093 d.cmd_encode_video_khr(cb, encode);
1004- d.cmd_end_query(cb, self.query, 0);
1094+ d.cmd_end_query(cb, self.query, query);
10051095 let end = vk::VideoEndCodingInfoKHR::builder().build();
10061096 d.cmd_end_video_coding_khr(cb, &end);
10071097 }
1008- self.main.end()?;
1009- self.main.submit()?;
1098+ slot.main.end()?;
1099+ let mut wait = vec![slot.ready];
1100+ if let Some(p) = self.last {
1101+ wait.push(self.slots[p].encoded);
1102+ }
1103+ slot.main.submit_with(&wait, &[slot.encoded])?;
1104+
1105+ self.last = Some(k);
1106+ self.next = k ^ 1;
10101107 self.coded = true;
10111108 self.applied = (self.rate, self.fps);
10121109 self.dirty = false;
1013- self.read_bitstream()
1110+ self.pending.push_back(k);
1111+ if self.pending.len() < FLIGHT {
1112+ return Ok(None);
1113+ }
1114+ let oldest = self
1115+ .pending
1116+ .pop_front()
1117+ .ok_or_else(|| Error::Invalid("no picture in flight".into()))?;
1118+ self.finish(oldest).map(Some)
1119+ }
1120+
1121+ /// Waits for every queued picture and returns their bytes in submission order.
1122+ pub(crate) fn flush(&mut self) -> Result<Vec<Vec<u8>>, Error> {
1123+ let mut out = Vec::new();
1124+ while let Some(k) = self.pending.pop_front() {
1125+ out.push(self.finish(k)?);
1126+ }
1127+ Ok(out)
1128+ }
1129+
1130+ /// Flushes and returns the last picture, for synchronous use where one picture is queued per call.
1131+ pub(crate) fn flush_last(&mut self) -> Result<Vec<u8>, Error> {
1132+ self.flush()?
1133+ .pop()
1134+ .ok_or_else(|| Error::Invalid("no picture encoded".into()))
10141135 }
10151136
1016- fn read_bitstream(&self) -> Result<Vec<u8>, Error> {
1137+ fn finish(&mut self, k: usize) -> Result<Vec<u8>, Error> {
1138+ let slot = &self.slots[k];
1139+ slot.main.wait()?;
1140+ slot.upload.wait()?;
1141+ let bytes = self.read_bitstream(k)?;
1142+ let d = self.vs.gpu.device();
1143+ self.slots[k].release(d);
1144+ Ok(bytes)
1145+ }
1146+
1147+ fn read_bitstream(&self, k: usize) -> Result<Vec<u8>, Error> {
10171148 let mut feedback = [0u8; 8];
10181149 unsafe {
10191150 vk(
10201151 self.vs.gpu.device().get_query_pool_results(
10211152 self.query,
1022- 0,
1153+ k as u32,
10231154 1,
10241155 &mut feedback,
10251156 8,
@@ -1037,7 +1168,7 @@ impl Encoder {
10371168 "encoded size exceeds bitstream buffer".into(),
10381169 ));
10391170 }
1040- let ptr = self
1171+ let ptr = self.slots[k]
10411172 .bitstream
10421173 .ptr
10431174 .ok_or_else(|| Error::Invalid("bitstream buffer not mapped".into()))?;
@@ -1054,14 +1185,20 @@ impl Drop for Encoder {
10541185 let _ = d.device_wait_idle();
10551186 d.destroy_query_pool(self.query, None);
10561187 }
1057- for img in self.dpb.iter().chain(std::iter::once(&self.src)) {
1188+ for img in &self.dpb {
10581189 img.destroy(d);
10591190 }
1060- if let Some(rgb) = &self.rgb {
1061- rgb.destroy(d);
1191+ for slot in self.slots.iter_mut() {
1192+ slot.release(d);
1193+ unsafe {
1194+ d.destroy_semaphore(slot.ready, None);
1195+ d.destroy_semaphore(slot.encoded, None);
1196+ }
1197+ slot.src.destroy(d);
1198+ slot.rgb.destroy(d);
1199+ slot.staging.destroy(d);
1200+ slot.bitstream.destroy(d);
10621201 }
1063- self.staging.destroy(d);
1064- self.bitstream.destroy(d);
10651202 }
10661203 }
10671204