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;
7 use ec_vk::DmaBuf;7 use ec_vk::DmaBuf;
8 8
9 use std::cell::RefCell;9 use std::cell::RefCell;
10+use std::collections::VecDeque;
10 11
11 use crate::error::{Error, Result};12 use crate::error::{Error, Result};
12 use crate::picture::{Decoded, I420, I420_16, RgbPicture};13 use crate::picture::{Decoded, I420, I420_16, RgbPicture};
@@ -239,6 +240,20 @@ pub struct DmaBufFrame<'a> {
239 pub order: RgbOrder,240 pub order: RgbOrder,
240 }241 }
241 242
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+
242 #[cfg(target_os = "linux")]257 #[cfg(target_os = "linux")]
243 fn rgb_to_i420(frame: &RgbFrame, (w, h): (usize, usize)) -> Result<I420> {258 fn rgb_to_i420(frame: &RgbFrame, (w, h): (usize, usize)) -> Result<I420> {
244 let (sw, sh, stride) = (259 let (sw, sh, stride) = (
@@ -297,7 +312,74 @@ enum VkEncoder {
297 Av1(ec_vk::Av1Encoder),312 Av1(ec_vk::Av1Encoder),
298 }313 }
299 314
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+
300 impl VkEncoder {323 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+
301 fn encode(383 fn encode(
302 &mut self,384 &mut self,
303 frame: &I420,385 frame: &I420,
@@ -386,6 +468,7 @@ pub struct HwEncoder {
386 config: EncoderConfig,468 config: EncoderConfig,
387 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]469 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
388 size: (usize, usize),470 size: (usize, usize),
471+ pending: VecDeque<i64>,
389 }472 }
390 473
391 impl HwEncoder {474 impl HwEncoder {
@@ -406,6 +489,7 @@ impl HwEncoder {
406 born_epoch,489 born_epoch,
407 config,490 config,
408 size,491 size,
492+ pending: VecDeque::new(),
409 });493 });
410 }494 }
411 Err(e) => reasons.push(format!("{backend:?}: {e}")),495 Err(e) => reasons.push(format!("{backend:?}: {e}")),
@@ -445,8 +529,55 @@ impl HwEncoder {
445 Ok(())529 Ok(())
446 }530 }
447 531
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+
448 /// Encode one frame; `meta.force_keyframe` starts a new GOP.578 /// Encode one frame; `meta.force_keyframe` starts a new GOP.
449 pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> {579 pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> {
580+ self.idle()?;
450 match &mut self.inner {581 match &mut self.inner {
451 EncInner::Vk(enc) => {582 EncInner::Vk(enc) => {
452 vk_session_alive(self.born_epoch)?;583 vk_session_alive(self.born_epoch)?;
@@ -464,6 +595,7 @@ impl HwEncoder {
464 595
465 /// Encode one 10-bit frame of a 10-bit encoder (H.265 and AV1), the [`HwEncoder::encode`] of a 10-bit encoder.596 /// Encode one 10-bit frame of a 10-bit encoder (H.265 and AV1), the [`HwEncoder::encode`] of a 10-bit encoder.
466 pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result<CodedFrame> {597 pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result<CodedFrame> {
598+ self.idle()?;
467 match &mut self.inner {599 match &mut self.inner {
468 EncInner::Vk(enc) => {600 EncInner::Vk(enc) => {
469 let coded = enc.encode_16(frame, meta.force_keyframe)?;601 let coded = enc.encode_16(frame, meta.force_keyframe)?;
@@ -480,6 +612,7 @@ impl HwEncoder {
480 612
481 /// 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.613 /// 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.
482 pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result<CodedFrame> {614 pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result<CodedFrame> {
615+ self.idle()?;
483 match &mut self.inner {616 match &mut self.inner {
484 EncInner::Vk(enc) => {617 EncInner::Vk(enc) => {
485 vk_session_alive(self.born_epoch)?;618 vk_session_alive(self.born_epoch)?;
@@ -502,6 +635,7 @@ impl HwEncoder {
502 frame: &DmaBufFrame,635 frame: &DmaBufFrame,
503 meta: FrameMetadata,636 meta: FrameMetadata,
504 ) -> Result<CodedFrame> {637 ) -> Result<CodedFrame> {
638+ self.idle()?;
505 match &mut self.inner {639 match &mut self.inner {
506 EncInner::Vk(enc) => {640 EncInner::Vk(enc) => {
507 vk_session_alive(self.born_epoch)?;641 vk_session_alive(self.born_epoch)?;
crates/ec-hw/src/lib.rsmodified+2 -1
@@ -88,7 +88,8 @@ pub use error::{Error, Result};
88 #[cfg(target_os = "linux")]88 #[cfg(target_os = "linux")]
89 pub use hw::DmaBufFrame;89 pub use hw::DmaBufFrame;
90 pub use hw::{90 pub use hw::{
91- Backend, Capability, Direction, HwDecoder, HwEncoder, RgbFrame, RgbOrder, RgbOutput,91+ Backend, Capability, Direction, EncodeInput, HwDecoder, HwEncoder, RgbFrame, RgbOrder,
92+ RgbOutput,
92 capabilities,93 capabilities,
93 };94 };
94 #[cfg(target_os = "linux")]95 #[cfg(target_os = "linux")]
crates/ec-vk/src/av1.rsmodified+91 -28
@@ -2,7 +2,7 @@ use vk_video_ffi::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref};
2 2
3 #[cfg(target_os = "linux")]3 #[cfg(target_os = "linux")]
4 use crate::DmaBuf;4 use crate::DmaBuf;
5-use crate::{CodedFrame, Error, Gpu, RateControl};5+use crate::{CodedFrame, Error, Flight, Gpu, RateControl, last_frame};
6 6
7 const TEMPORAL_DELIMITER: [u8; 2] = [0x12, 0x00];7 const TEMPORAL_DELIMITER: [u8; 2] = [0x12, 0x00];
8 8
@@ -35,6 +35,7 @@ pub struct Av1Encoder {
35 reference: Option<Av1Ref>,35 reference: Option<Av1Ref>,
36 uv: Vec<u8>,36 uv: Vec<u8>,
37 uv16: Vec<u16>,37 uv16: Vec<u16>,
38+ flight: Flight,
38 }39 }
39 40
40 impl Av1Encoder {41 impl Av1Encoder {
@@ -65,17 +66,18 @@ impl Av1Encoder {
65 reference: None,66 reference: None,
66 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],67 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],
67 uv16: vec![0; cfg.width as usize * cfg.height as usize / 2],68 uv16: vec![0; cfg.width as usize * cfg.height as usize / 2],
69+ flight: Flight::default(),
68 })70 })
69 }71 }
70 72
71- /// Encodes one I420 frame as a temporal unit; `force_keyframe` makes it a KEY frame and restarts the GOP.73+ /// Submits one I420 frame without waiting; returns the oldest temporal unit once a second one is queued.
72- pub fn encode(74+ pub fn submit(
73 &mut self,75 &mut self,
74 y: &[u8],76 y: &[u8],
75 u: &[u8],77 u: &[u8],
76 v: &[u8],78 v: &[u8],
77 force_keyframe: bool,79 force_keyframe: bool,
78- ) -> Result<CodedFrame, Error> {80+ ) -> Result<Option<CodedFrame>, Error> {
79 let chroma = self.width * self.height / 4;81 let chroma = self.width * self.height / 4;
80 if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {82 if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {
81 return Err(Error::Invalid("I420 plane size".into()));83 return Err(Error::Invalid("I420 plane size".into()));
@@ -85,18 +87,31 @@ impl Av1Encoder {
85 pair[1] = v[i];87 pair[1] = v[i];
86 }88 }
87 let pic = self.next_picture(force_keyframe);89 let pic = self.next_picture(force_keyframe);
88- let frame = self.session.encode(y, &self.uv, &pic)?;90+ let out = self.session.submit(y, &self.uv, &pic)?;
89- Ok(self.finish(&pic, frame))91+ Ok(out.map(|bytes| self.coded(bytes)))
90 }92 }
91 93
92- /// Encodes one 10-bit I420 frame of a 10-bit encoder; `force_keyframe` makes it a KEY frame and restarts the GOP.94+ /// Encodes one I420 frame as a temporal unit; `force_keyframe` makes it a KEY frame and restarts the GOP.
93- pub fn encode_16(95+ pub fn encode(
96+ &mut self,
97+ y: &[u8],
98+ u: &[u8],
99+ v: &[u8],
100+ force_keyframe: bool,
101+ ) -> Result<CodedFrame, Error> {
102+ let first = self.submit(y, u, v, force_keyframe)?;
103+ let rest = self.flush()?;
104+ last_frame(first, rest)
105+ }
106+
107+ /// Submits one 10-bit I420 frame of a 10-bit encoder without waiting.
108+ pub fn submit_16(
94 &mut self,109 &mut self,
95 y: &[u16],110 y: &[u16],
96 u: &[u16],111 u: &[u16],
97 v: &[u16],112 v: &[u16],
98 force_keyframe: bool,113 force_keyframe: bool,
99- ) -> Result<CodedFrame, Error> {114+ ) -> Result<Option<CodedFrame>, Error> {
100 let chroma = self.width * self.height / 4;115 let chroma = self.width * self.height / 4;
101 if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {116 if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {
102 return Err(Error::Invalid("I420 plane size".into()));117 return Err(Error::Invalid("I420 plane size".into()));
@@ -106,8 +121,27 @@ impl Av1Encoder {
106 pair[1] = v[i];121 pair[1] = v[i];
107 }122 }
108 let pic = self.next_picture(force_keyframe);123 let pic = self.next_picture(force_keyframe);
109- let frame = self.session.encode_16(y, &self.uv16, &pic)?;124+ let out = self.session.submit_16(y, &self.uv16, &pic)?;
110- Ok(self.finish(&pic, frame))125+ Ok(out.map(|bytes| self.coded(bytes)))
126+ }
127+
128+ /// Encodes one 10-bit I420 frame of a 10-bit encoder; `force_keyframe` makes it a KEY frame and restarts the GOP.
129+ pub fn encode_16(
130+ &mut self,
131+ y: &[u16],
132+ u: &[u16],
133+ v: &[u16],
134+ force_keyframe: bool,
135+ ) -> Result<CodedFrame, Error> {
136+ let first = self.submit_16(y, u, v, force_keyframe)?;
137+ let rest = self.flush()?;
138+ last_frame(first, rest)
139+ }
140+
141+ /// Waits for every submitted frame and returns them in order.
142+ pub fn flush(&mut self) -> Result<Vec<CodedFrame>, Error> {
143+ let bytes = self.session.flush()?;
144+ Ok(bytes.into_iter().map(|b| self.coded(b)).collect())
111 }145 }
112 146
113 /// Changes bitrate or frame rate; takes effect on the next frame.147 /// Changes bitrate or frame rate; takes effect on the next frame.
@@ -115,6 +149,23 @@ impl Av1Encoder {
115 Ok(self.session.set_rate(rate, fps)?)149 Ok(self.session.set_rate(rate, fps)?)
116 }150 }
117 151
152+ /// Submits one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes) without waiting.
153+ pub fn submit_rgb(
154+ &mut self,
155+ rgb: &[u8],
156+ src_width: u32,
157+ src_height: u32,
158+ stride_bytes: u32,
159+ bgr: bool,
160+ force_keyframe: bool,
161+ ) -> Result<Option<CodedFrame>, Error> {
162+ let pic = self.next_picture(force_keyframe);
163+ let out = self
164+ .session
165+ .submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?;
166+ Ok(out.map(|bytes| self.coded(bytes)))
167+ }
168+
118 /// 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.169 /// Encodes one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes), box-downscaled to the encoder size on the GPU.
119 pub fn encode_rgb(170 pub fn encode_rgb(
120 &mut self,171 &mut self,
@@ -125,9 +176,21 @@ impl Av1Encoder {
125 bgr: bool,176 bgr: bool,
126 force_keyframe: bool,177 force_keyframe: bool,
127 ) -> Result<CodedFrame, Error> {178 ) -> Result<CodedFrame, Error> {
179+ let first = self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, force_keyframe)?;
180+ let rest = self.flush()?;
181+ last_frame(first, rest)
182+ }
183+
184+ /// Submits one DMA-BUF frame of the source size without waiting.
185+ #[cfg(target_os = "linux")]
186+ pub fn submit_dmabuf(
187+ &mut self,
188+ src: &DmaBuf<'_>,
189+ force_keyframe: bool,
190+ ) -> Result<Option<CodedFrame>, Error> {
128 let pic = self.next_picture(force_keyframe);191 let pic = self.next_picture(force_keyframe);
129- let frame = self.session.encode_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?;192+ let out = self.session.submit_dmabuf(src, &pic)?;
130- Ok(self.finish(&pic, frame))193+ Ok(out.map(|bytes| self.coded(bytes)))
131 }194 }
132 195
133 /// Encodes one DMA-BUF frame of the source size (BGRx if `bgr`, else RGBx), box-downscaled to the encoder size on the GPU.196 /// Encodes one DMA-BUF frame of the source size (BGRx if `bgr`, else RGBx), box-downscaled to the encoder size on the GPU.
@@ -137,9 +200,9 @@ impl Av1Encoder {
137 src: &DmaBuf<'_>,200 src: &DmaBuf<'_>,
138 force_keyframe: bool,201 force_keyframe: bool,
139 ) -> Result<CodedFrame, Error> {202 ) -> Result<CodedFrame, Error> {
140- let pic = self.next_picture(force_keyframe);203+ let first = self.submit_dmabuf(src, force_keyframe)?;
141- let frame = self.session.encode_dmabuf(src, &pic)?;204+ let rest = self.flush()?;
142- Ok(self.finish(&pic, frame))205+ last_frame(first, rest)
143 }206 }
144 207
145 fn next_picture(&mut self, force_keyframe: bool) -> Av1Picture {208 fn next_picture(&mut self, force_keyframe: bool) -> Av1Picture {
@@ -151,28 +214,28 @@ impl Av1Encoder {
151 };214 };
152 let reference = if keyframe { None } else { self.reference };215 let reference = if keyframe { None } else { self.reference };
153 let slot = reference.map_or(0, |r| 1 - r.slot);216 let slot = reference.map_or(0, |r| 1 - r.slot);
154- Av1Picture {217+ let pic = Av1Picture {
155 key: keyframe,218 key: keyframe,
156 order_hint: self.order_hint,219 order_hint: self.order_hint,
157 slot,220 slot,
158 reference,221 reference,
159- }222+ };
160- }
161-
162- fn finish(&mut self, pic: &Av1Picture, frame: Vec<u8>) -> CodedFrame {
163 self.reference = Some(Av1Ref {223 self.reference = Some(Av1Ref {
164 slot: pic.slot,224 slot: pic.slot,
165 order_hint: pic.order_hint,225 order_hint: pic.order_hint,
166 });226 });
167- self.position = if pic.key { 1 } else { self.position + 1 };227+ self.position = if keyframe { 1 } else { self.position + 1 };
228+ self.flight.push(keyframe);
229+ pic
230+ }
231+
232+ fn coded(&mut self, bytes: Vec<u8>) -> CodedFrame {
233+ let keyframe = self.flight.pop();
168 let mut data = TEMPORAL_DELIMITER.to_vec();234 let mut data = TEMPORAL_DELIMITER.to_vec();
169- if pic.key {235+ if keyframe {
170 data.extend_from_slice(&self.sequence_header);236 data.extend_from_slice(&self.sequence_header);
171 }237 }
172- data.extend_from_slice(&frame);238+ data.extend_from_slice(&bytes);
173- CodedFrame {239+ CodedFrame { data, keyframe }
174- data,
175- keyframe: pic.key,
176- }
177 }240 }
178 }241 }
crates/ec-vk/src/h265.rsmodified+92 -29
@@ -2,7 +2,7 @@ use vk_video_ffi::{H265EncodeConfig, H265EncodeSession, H265Picture, H265Ref};
2 2
3 #[cfg(target_os = "linux")]3 #[cfg(target_os = "linux")]
4 use crate::DmaBuf;4 use crate::DmaBuf;
5-use crate::{CodedFrame, Error, Gpu, RateControl};5+use crate::{CodedFrame, Error, Flight, Gpu, RateControl, last_frame};
6 6
7 /// H.265 encoder settings.7 /// H.265 encoder settings.
8 #[derive(Debug, Clone, Copy, PartialEq, Eq)]8 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -33,6 +33,7 @@ pub struct H265Encoder {
33 reference: Option<H265Ref>,33 reference: Option<H265Ref>,
34 uv: Vec<u8>,34 uv: Vec<u8>,
35 uv16: Vec<u16>,35 uv16: Vec<u16>,
36+ flight: Flight,
36 }37 }
37 38
38 impl H265Encoder {39 impl H265Encoder {
@@ -63,17 +64,18 @@ impl H265Encoder {
63 reference: None,64 reference: None,
64 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],65 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],
65 uv16: vec![0; cfg.width as usize * cfg.height as usize / 2],66 uv16: vec![0; cfg.width as usize * cfg.height as usize / 2],
67+ flight: Flight::default(),
66 })68 })
67 }69 }
68 70
69- /// Encodes one I420 frame; `force_keyframe` makes it an IDR and restarts the GOP.71+ /// Submits one I420 frame without waiting; returns the oldest frame once a second one is queued.
70- pub fn encode(72+ pub fn submit(
71 &mut self,73 &mut self,
72 y: &[u8],74 y: &[u8],
73 u: &[u8],75 u: &[u8],
74 v: &[u8],76 v: &[u8],
75 force_keyframe: bool,77 force_keyframe: bool,
76- ) -> Result<CodedFrame, Error> {78+ ) -> Result<Option<CodedFrame>, Error> {
77 let chroma = self.width * self.height / 4;79 let chroma = self.width * self.height / 4;
78 if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {80 if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {
79 return Err(Error::Invalid("I420 plane size".into()));81 return Err(Error::Invalid("I420 plane size".into()));
@@ -83,18 +85,31 @@ impl H265Encoder {
83 pair[1] = v[i];85 pair[1] = v[i];
84 }86 }
85 let pic = self.next_picture(force_keyframe);87 let pic = self.next_picture(force_keyframe);
86- let slice = self.session.encode(y, &self.uv, &pic)?;88+ let out = self.session.submit(y, &self.uv, &pic)?;
87- Ok(self.finish(&pic, slice))89+ Ok(out.map(|bytes| self.coded(bytes)))
88 }90 }
89 91
90- /// Encodes one 10-bit I420 frame of a 10-bit encoder; `force_keyframe` makes it IDR and restarts the GOP.92+ /// Encodes one I420 frame; `force_keyframe` makes it an IDR and restarts the GOP.
91- pub fn encode_16(93+ pub fn encode(
94+ &mut self,
95+ y: &[u8],
96+ u: &[u8],
97+ v: &[u8],
98+ force_keyframe: bool,
99+ ) -> Result<CodedFrame, Error> {
100+ let first = self.submit(y, u, v, force_keyframe)?;
101+ let rest = self.flush()?;
102+ last_frame(first, rest)
103+ }
104+
105+ /// Submits one 10-bit I420 frame of a 10-bit encoder without waiting.
106+ pub fn submit_16(
92 &mut self,107 &mut self,
93 y: &[u16],108 y: &[u16],
94 u: &[u16],109 u: &[u16],
95 v: &[u16],110 v: &[u16],
96 force_keyframe: bool,111 force_keyframe: bool,
97- ) -> Result<CodedFrame, Error> {112+ ) -> Result<Option<CodedFrame>, Error> {
98 let chroma = self.width * self.height / 4;113 let chroma = self.width * self.height / 4;
99 if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {114 if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {
100 return Err(Error::Invalid("I420 plane size".into()));115 return Err(Error::Invalid("I420 plane size".into()));
@@ -104,8 +119,27 @@ impl H265Encoder {
104 pair[1] = v[i];119 pair[1] = v[i];
105 }120 }
106 let pic = self.next_picture(force_keyframe);121 let pic = self.next_picture(force_keyframe);
107- let slice = self.session.encode_16(y, &self.uv16, &pic)?;122+ let out = self.session.submit_16(y, &self.uv16, &pic)?;
108- Ok(self.finish(&pic, slice))123+ Ok(out.map(|bytes| self.coded(bytes)))
124+ }
125+
126+ /// Encodes one 10-bit I420 frame of a 10-bit encoder; `force_keyframe` makes it IDR and restarts the GOP.
127+ pub fn encode_16(
128+ &mut self,
129+ y: &[u16],
130+ u: &[u16],
131+ v: &[u16],
132+ force_keyframe: bool,
133+ ) -> Result<CodedFrame, Error> {
134+ let first = self.submit_16(y, u, v, force_keyframe)?;
135+ let rest = self.flush()?;
136+ last_frame(first, rest)
137+ }
138+
139+ /// Waits for every submitted frame and returns them in order.
140+ pub fn flush(&mut self) -> Result<Vec<CodedFrame>, Error> {
141+ let bytes = self.session.flush()?;
142+ Ok(bytes.into_iter().map(|b| self.coded(b)).collect())
109 }143 }
110 144
111 /// Changes bitrate or frame rate; takes effect on the next frame.145 /// Changes bitrate or frame rate; takes effect on the next frame.
@@ -113,6 +147,23 @@ impl H265Encoder {
113 Ok(self.session.set_rate(rate, fps)?)147 Ok(self.session.set_rate(rate, fps)?)
114 }148 }
115 149
150+ /// Submits one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes) without waiting.
151+ pub fn submit_rgb(
152+ &mut self,
153+ rgb: &[u8],
154+ src_width: u32,
155+ src_height: u32,
156+ stride_bytes: u32,
157+ bgr: bool,
158+ force_keyframe: bool,
159+ ) -> Result<Option<CodedFrame>, Error> {
160+ let pic = self.next_picture(force_keyframe);
161+ let out = self
162+ .session
163+ .submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?;
164+ Ok(out.map(|bytes| self.coded(bytes)))
165+ }
166+
116 /// 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.167 /// Encodes one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes), box-downscaled to the encoder size on the GPU.
117 pub fn encode_rgb(168 pub fn encode_rgb(
118 &mut self,169 &mut self,
@@ -123,9 +174,21 @@ impl H265Encoder {
123 bgr: bool,174 bgr: bool,
124 force_keyframe: bool,175 force_keyframe: bool,
125 ) -> Result<CodedFrame, Error> {176 ) -> Result<CodedFrame, Error> {
177+ let first = self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, force_keyframe)?;
178+ let rest = self.flush()?;
179+ last_frame(first, rest)
180+ }
181+
182+ /// Submits one DMA-BUF frame of the source size without waiting.
183+ #[cfg(target_os = "linux")]
184+ pub fn submit_dmabuf(
185+ &mut self,
186+ src: &DmaBuf<'_>,
187+ force_keyframe: bool,
188+ ) -> Result<Option<CodedFrame>, Error> {
126 let pic = self.next_picture(force_keyframe);189 let pic = self.next_picture(force_keyframe);
127- let slice = self.session.encode_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?;190+ let out = self.session.submit_dmabuf(src, &pic)?;
128- Ok(self.finish(&pic, slice))191+ Ok(out.map(|bytes| self.coded(bytes)))
129 }192 }
130 193
131 /// Encodes one DMA-BUF frame of the source size (BGRx if `bgr`, else RGBx), box-downscaled to the encoder size on the GPU.194 /// Encodes one DMA-BUF frame of the source size (BGRx if `bgr`, else RGBx), box-downscaled to the encoder size on the GPU.
@@ -135,9 +198,9 @@ impl H265Encoder {
135 src: &DmaBuf<'_>,198 src: &DmaBuf<'_>,
136 force_keyframe: bool,199 force_keyframe: bool,
137 ) -> Result<CodedFrame, Error> {200 ) -> Result<CodedFrame, Error> {
138- let pic = self.next_picture(force_keyframe);201+ let first = self.submit_dmabuf(src, force_keyframe)?;
139- let slice = self.session.encode_dmabuf(src, &pic)?;202+ let rest = self.flush()?;
140- Ok(self.finish(&pic, slice))203+ last_frame(first, rest)
141 }204 }
142 205
143 fn next_picture(&mut self, force_keyframe: bool) -> H265Picture {206 fn next_picture(&mut self, force_keyframe: bool) -> H265Picture {
@@ -145,28 +208,28 @@ impl H265Encoder {
145 self.poc = if keyframe { 0 } else { self.poc + 1 };208 self.poc = if keyframe { 0 } else { self.poc + 1 };
146 let reference = if keyframe { None } else { self.reference };209 let reference = if keyframe { None } else { self.reference };
147 let slot = reference.map_or(0, |r| 1 - r.slot);210 let slot = reference.map_or(0, |r| 1 - r.slot);
148- H265Picture {211+ let pic = H265Picture {
149 idr: keyframe,212 idr: keyframe,
150 poc: self.poc,213 poc: self.poc,
151 slot,214 slot,
152 reference,215 reference,
153- }216+ };
154- }
155-
156- fn finish(&mut self, pic: &H265Picture, slice: Vec<u8>) -> CodedFrame {
157 self.reference = Some(H265Ref {217 self.reference = Some(H265Ref {
158 slot: pic.slot,218 slot: pic.slot,
159 poc: pic.poc,219 poc: pic.poc,
160 });220 });
161- self.position = if pic.idr { 1 } else { self.position + 1 };221+ self.position = if keyframe { 1 } else { self.position + 1 };
162- let data = if pic.idr {222+ self.flight.push(keyframe);
163- [self.parameter_sets.as_slice(), slice.as_slice()].concat()223+ pic
224+ }
225+
226+ fn coded(&mut self, bytes: Vec<u8>) -> CodedFrame {
227+ let keyframe = self.flight.pop();
228+ let data = if keyframe {
229+ [self.parameter_sets.as_slice(), bytes.as_slice()].concat()
164 } else {230 } else {
165- slice231+ bytes
166 };232 };
167- CodedFrame {233+ CodedFrame { data, keyframe }
168- data,
169- keyframe: pic.idr,
170- }
171 }234 }
172 }235 }
crates/ec-vk/src/lib.rsmodified+99 -24
@@ -2,6 +2,8 @@
2 #![forbid(unsafe_code)]2 #![forbid(unsafe_code)]
3 #![deny(missing_docs)]3 #![deny(missing_docs)]
4 4
5+use std::collections::VecDeque;
6+
5 use vk_video_ffi::{H264EncodeConfig, H264EncodeSession, H264Picture, H264Ref};7 use vk_video_ffi::{H264EncodeConfig, H264EncodeSession, H264Picture, H264Ref};
6 8
7 mod av1;9 mod av1;
@@ -48,6 +50,29 @@ pub struct CodedFrame {
48 pub keyframe: bool,50 pub keyframe: bool,
49 }51 }
50 52
53+#[derive(Default)]
54+pub(crate) struct Flight(VecDeque<bool>);
55+
56+impl Flight {
57+ pub(crate) fn push(&mut self, keyframe: bool) {
58+ self.0.push_back(keyframe);
59+ }
60+
61+ pub(crate) fn pop(&mut self) -> bool {
62+ self.0.pop_front().unwrap_or(false)
63+ }
64+}
65+
66+pub(crate) fn last_frame(
67+ first: Option<CodedFrame>,
68+ rest: Vec<CodedFrame>,
69+) -> Result<CodedFrame, Error> {
70+ rest.into_iter()
71+ .last()
72+ .or(first)
73+ .ok_or_else(|| Error::Invalid("no coded frame".into()))
74+}
75+
51 /// H.264 encoder: GOP, frame_num, POC and DPB slot bookkeeping over [`H264EncodeSession`].76 /// H.264 encoder: GOP, frame_num, POC and DPB slot bookkeeping over [`H264EncodeSession`].
52 pub struct H264Encoder {77 pub struct H264Encoder {
53 session: H264EncodeSession,78 session: H264EncodeSession,
@@ -61,6 +86,7 @@ pub struct H264Encoder {
61 idr_pic_id: u16,86 idr_pic_id: u16,
62 reference: Option<H264Ref>,87 reference: Option<H264Ref>,
63 uv: Vec<u8>,88 uv: Vec<u8>,
89+ flight: Flight,
64 }90 }
65 91
66 impl H264Encoder {92 impl H264Encoder {
@@ -92,17 +118,18 @@ impl H264Encoder {
92 idr_pic_id: 0,118 idr_pic_id: 0,
93 reference: None,119 reference: None,
94 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],120 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],
121+ flight: Flight::default(),
95 })122 })
96 }123 }
97 124
98- /// Encodes one I420 frame; `force_keyframe` makes it an IDR and restarts the GOP.125+ /// Submits one I420 frame without waiting; returns the oldest frame once a second one is queued.
99- pub fn encode(126+ pub fn submit(
100 &mut self,127 &mut self,
101 y: &[u8],128 y: &[u8],
102 u: &[u8],129 u: &[u8],
103 v: &[u8],130 v: &[u8],
104 force_keyframe: bool,131 force_keyframe: bool,
105- ) -> Result<CodedFrame, Error> {132+ ) -> Result<Option<CodedFrame>, Error> {
106 let chroma = self.width * self.height / 4;133 let chroma = self.width * self.height / 4;
107 if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {134 if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {
108 return Err(Error::Invalid("I420 plane size".into()));135 return Err(Error::Invalid("I420 plane size".into()));
@@ -112,8 +139,27 @@ impl H264Encoder {
112 pair[1] = v[i];139 pair[1] = v[i];
113 }140 }
114 let pic = self.next_picture(force_keyframe);141 let pic = self.next_picture(force_keyframe);
115- let slice = self.session.encode(y, &self.uv, &pic)?;142+ let out = self.session.submit(y, &self.uv, &pic)?;
116- Ok(self.finish(&pic, slice))143+ Ok(out.map(|bytes| self.coded(bytes)))
144+ }
145+
146+ /// Encodes one I420 frame; `force_keyframe` makes it an IDR and restarts the GOP.
147+ pub fn encode(
148+ &mut self,
149+ y: &[u8],
150+ u: &[u8],
151+ v: &[u8],
152+ force_keyframe: bool,
153+ ) -> Result<CodedFrame, Error> {
154+ let first = self.submit(y, u, v, force_keyframe)?;
155+ let rest = self.flush()?;
156+ last_frame(first, rest)
157+ }
158+
159+ /// Waits for every submitted frame and returns them in order.
160+ pub fn flush(&mut self) -> Result<Vec<CodedFrame>, Error> {
161+ let bytes = self.session.flush()?;
162+ Ok(bytes.into_iter().map(|b| self.coded(b)).collect())
117 }163 }
118 164
119 /// Changes bitrate or frame rate; takes effect on the next frame.165 /// Changes bitrate or frame rate; takes effect on the next frame.
@@ -121,6 +167,23 @@ impl H264Encoder {
121 Ok(self.session.set_rate(rate, fps)?)167 Ok(self.session.set_rate(rate, fps)?)
122 }168 }
123 169
170+ /// Submits one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes) without waiting.
171+ pub fn submit_rgb(
172+ &mut self,
173+ rgb: &[u8],
174+ src_width: u32,
175+ src_height: u32,
176+ stride_bytes: u32,
177+ bgr: bool,
178+ force_keyframe: bool,
179+ ) -> Result<Option<CodedFrame>, Error> {
180+ let pic = self.next_picture(force_keyframe);
181+ let out = self
182+ .session
183+ .submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?;
184+ Ok(out.map(|bytes| self.coded(bytes)))
185+ }
186+
124 /// 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.187 /// Encodes one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes), box-downscaled to the encoder size on the GPU.
125 pub fn encode_rgb(188 pub fn encode_rgb(
126 &mut self,189 &mut self,
@@ -131,9 +194,21 @@ impl H264Encoder {
131 bgr: bool,194 bgr: bool,
132 force_keyframe: bool,195 force_keyframe: bool,
133 ) -> Result<CodedFrame, Error> {196 ) -> Result<CodedFrame, Error> {
197+ let first = self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, force_keyframe)?;
198+ let rest = self.flush()?;
199+ last_frame(first, rest)
200+ }
201+
202+ /// Submits one DMA-BUF frame of the source size without waiting.
203+ #[cfg(target_os = "linux")]
204+ pub fn submit_dmabuf(
205+ &mut self,
206+ src: &DmaBuf<'_>,
207+ force_keyframe: bool,
208+ ) -> Result<Option<CodedFrame>, Error> {
134 let pic = self.next_picture(force_keyframe);209 let pic = self.next_picture(force_keyframe);
135- let slice = self.session.encode_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?;210+ let out = self.session.submit_dmabuf(src, &pic)?;
136- Ok(self.finish(&pic, slice))211+ Ok(out.map(|bytes| self.coded(bytes)))
137 }212 }
138 213
139 /// Encodes one DMA-BUF frame of the source size (BGRx if `bgr`, else RGBx), box-downscaled to the encoder size on the GPU.214 /// Encodes one DMA-BUF frame of the source size (BGRx if `bgr`, else RGBx), box-downscaled to the encoder size on the GPU.
@@ -143,9 +218,9 @@ impl H264Encoder {
143 src: &DmaBuf<'_>,218 src: &DmaBuf<'_>,
144 force_keyframe: bool,219 force_keyframe: bool,
145 ) -> Result<CodedFrame, Error> {220 ) -> Result<CodedFrame, Error> {
146- let pic = self.next_picture(force_keyframe);221+ let first = self.submit_dmabuf(src, force_keyframe)?;
147- let slice = self.session.encode_dmabuf(src, &pic)?;222+ let rest = self.flush()?;
148- Ok(self.finish(&pic, slice))223+ last_frame(first, rest)
149 }224 }
150 225
151 fn next_picture(&mut self, force_keyframe: bool) -> H264Picture {226 fn next_picture(&mut self, force_keyframe: bool) -> H264Picture {
@@ -159,34 +234,34 @@ impl H264Encoder {
159 }234 }
160 let reference = if keyframe { None } else { self.reference };235 let reference = if keyframe { None } else { self.reference };
161 let slot = reference.map_or(0, |r| 1 - r.slot);236 let slot = reference.map_or(0, |r| 1 - r.slot);
162- H264Picture {237+ let pic = H264Picture {
163 idr: keyframe,238 idr: keyframe,
164 idr_pic_id: self.idr_pic_id,239 idr_pic_id: self.idr_pic_id,
165 frame_num: self.frame_num,240 frame_num: self.frame_num,
166 poc: self.poc,241 poc: self.poc,
167 slot,242 slot,
168 reference,243 reference,
169- }244+ };
170- }
171-
172- fn finish(&mut self, pic: &H264Picture, slice: Vec<u8>) -> CodedFrame {
173 self.reference = Some(H264Ref {245 self.reference = Some(H264Ref {
174 slot: pic.slot,246 slot: pic.slot,
175 frame_num: pic.frame_num,247 frame_num: pic.frame_num,
176 poc: pic.poc,248 poc: pic.poc,
177 });249 });
178- self.position = if pic.idr { 1 } else { self.position + 1 };250+ self.position = if keyframe { 1 } else { self.position + 1 };
179- if pic.idr {251+ if keyframe {
180 self.idr_pic_id = self.idr_pic_id.wrapping_add(1);252 self.idr_pic_id = self.idr_pic_id.wrapping_add(1);
181 }253 }
182- let data = if pic.idr {254+ self.flight.push(keyframe);
183- [self.parameter_sets.as_slice(), slice.as_slice()].concat()255+ pic
256+ }
257+
258+ fn coded(&mut self, bytes: Vec<u8>) -> CodedFrame {
259+ let keyframe = self.flight.pop();
260+ let data = if keyframe {
261+ [self.parameter_sets.as_slice(), bytes.as_slice()].concat()
184 } else {262 } else {
185- slice263+ bytes
186 };264 };
187- CodedFrame {265+ CodedFrame { data, keyframe }
188- data,
189- keyframe: pic.idr,
190- }
191 }266 }
192 }267 }
shims/vk-video-ffi/src/av1_encode.rsmodified+49 -11
@@ -224,8 +224,8 @@ impl Av1EncodeSession {
224 self.seq.clone()224 self.seq.clone()
225 }225 }
226 226
227- /// Encodes one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) and returns its frame OBUs.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 encode(&mut self, y: &[u8], uv: &[u8], pic: &Av1Picture) -> Result<Vec<u8>, Error> {228+ pub fn submit(&mut self, y: &[u8], uv: &[u8], pic: &Av1Picture) -> Result<Option<Vec<u8>>, Error> {
229 if y.len() != self.enc.input.0 * self.enc.input.1229 if y.len() != self.enc.input.0 * self.enc.input.1
230 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2230 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2
231 {231 {
@@ -236,8 +236,8 @@ impl Av1EncodeSession {
236 self.encode_uploaded(pic)236 self.encode_uploaded(pic)
237 }237 }
238 238
239- /// Encodes one 10-bit picture (y: width*height, uv: interleaved CbCr width*height/2, samples in the low 10 bits) of a 10-bit session and returns its frame OBUs.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 encode_16(&mut self, y: &[u16], uv: &[u16], pic: &Av1Picture) -> Result<Vec<u8>, Error> {240+ pub fn submit_16(&mut self, y: &[u16], uv: &[u16], pic: &Av1Picture) -> Result<Option<Vec<u8>>, Error> {
241 if y.len() != self.enc.input.0 * self.enc.input.1241 if y.len() != self.enc.input.0 * self.enc.input.1
242 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2242 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2
243 {243 {
@@ -249,7 +249,7 @@ impl Av1EncodeSession {
249 }249 }
250 250
251 /// Encodes one packed RGB picture (src_width x src_height, row stride in bytes, BGRx or RGBx byte order), box-downscaled to the encoder size on the GPU.251 /// Encodes one packed RGB picture (src_width x src_height, row stride in bytes, BGRx or RGBx byte order), box-downscaled to the encoder size on the GPU.
252- pub fn encode_rgb(252+ pub fn submit_rgb(
253 &mut self,253 &mut self,
254 rgb: &[u8],254 rgb: &[u8],
255 src_width: u32,255 src_width: u32,
@@ -257,7 +257,7 @@ impl Av1EncodeSession {
257 stride_bytes: u32,257 stride_bytes: u32,
258 bgr: bool,258 bgr: bool,
259 pic: &Av1Picture,259 pic: &Av1Picture,
260- ) -> Result<Vec<u8>, Error> {260+ ) -> Result<Option<Vec<u8>>, Error> {
261 self.check(pic)?;261 self.check(pic)?;
262 let src = (src_width as usize, src_height as usize);262 let src = (src_width as usize, src_height as usize);
263 check_rgb(263 check_rgb(
@@ -277,13 +277,13 @@ impl Av1EncodeSession {
277 }277 }
278 /// Encodes one picture from a DMA-BUF of BGRx or RGBx pixels, box-downscaled to the encoder size on the GPU.278 /// Encodes one picture from a DMA-BUF of BGRx or RGBx pixels, box-downscaled to the encoder size on the GPU.
279 #[cfg(target_os = "linux")]279 #[cfg(target_os = "linux")]
280- pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &Av1Picture) -> Result<Vec<u8>, Error> {280+ pub fn submit_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &Av1Picture) -> Result<Option<Vec<u8>>, Error> {
281 self.check(pic)?;281 self.check(pic)?;
282 self.enc.upload_dmabuf(src)?;282 self.enc.upload_dmabuf(src)?;
283 self.encode_uploaded(pic)283 self.encode_uploaded(pic)
284 }284 }
285 285
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> {
287 let extent = self.enc.extent;287 let extent = self.enc.extent;
288 288
289 let refresh: u8 = if pic.key { 0xff } else { 1 << pic.slot };289 let refresh: u8 = if pic.key { 0xff } else { 1 << pic.slot };
@@ -291,7 +291,7 @@ impl Av1EncodeSession {
291 picture_resource(self.enc.dpb[0].view, extent),291 picture_resource(self.enc.dpb[0].view, extent),
292 picture_resource(self.enc.dpb[1].view, extent),292 picture_resource(self.enc.dpb[1].view, extent),
293 ];293 ];
294- let src_pr = picture_resource(self.enc.src.view, extent);294+ let src_pr = picture_resource(self.enc.src_view(), extent);
295 295
296 let key_of = self.slot_key;296 let key_of = self.slot_key;
297 let mut new_std = zeroed::<vk::video::StdVideoEncodeAV1ReferenceInfo>();297 let mut new_std = zeroed::<vk::video::StdVideoEncodeAV1ReferenceInfo>();
@@ -393,7 +393,7 @@ impl Av1EncodeSession {
393 };393 };
394 394
395 let encode = vk::VideoEncodeInfoKHR::builder()395 let encode = vk::VideoEncodeInfoKHR::builder()
396- .dst_buffer(self.enc.bitstream.buffer)396+ .dst_buffer(self.enc.bitstream_buffer())
397 .dst_buffer_offset(0)397 .dst_buffer_offset(0)
398 .dst_buffer_range(self.enc.bitstream_len)398 .dst_buffer_range(self.enc.bitstream_len)
399 .src_picture_resource(src_pr)399 .src_picture_resource(src_pr)
@@ -406,7 +406,7 @@ impl Av1EncodeSession {
406 let mut chain = RateChain::new(self.enc.rate, self.enc.fps);406 let mut chain = RateChain::new(self.enc.rate, self.enc.fps);
407 let out = self407 let out = self
408 .enc408 .enc
409- .run(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)?;409+ .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)?;
410 for i in 0..DPB_SLOTS {410 for i in 0..DPB_SLOTS {
411 if refresh >> i & 1 == 1 {411 if refresh >> i & 1 == 1 {
412 self.slot_key[i] = pic.key;412 self.slot_key[i] = pic.key;
@@ -420,6 +420,44 @@ impl Av1EncodeSession {
420 Ok(out)420 Ok(out)
421 }421 }
422 422
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+
423 /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change.461 /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change.
424 pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {462 pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {
425 self.enc.set_rate(rate, fps)463 self.enc.set_rate(rate, fps)
shims/vk-video-ffi/src/h264_encode.rsmodified+41 -9
@@ -253,8 +253,8 @@ impl H264EncodeSession {
253 )253 )
254 }254 }
255 255
256- /// Encodes one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) and returns its Annex-B slice NAL units.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 encode(&mut self, y: &[u8], uv: &[u8], pic: &H264Picture) -> Result<Vec<u8>, Error> {257+ pub fn submit(&mut self, y: &[u8], uv: &[u8], pic: &H264Picture) -> Result<Option<Vec<u8>>, Error> {
258 let (w, h) = self.enc.input;258 let (w, h) = self.enc.input;
259 if y.len() != w * h || uv.len() != w * h / 2 {259 if y.len() != w * h || uv.len() != w * h / 2 {
260 return Err(Error::Invalid("NV12 plane size".into()));260 return Err(Error::Invalid("NV12 plane size".into()));
@@ -265,7 +265,7 @@ impl H264EncodeSession {
265 }265 }
266 266
267 /// Encodes one packed RGB picture (src_width x src_height, row stride in bytes, BGRx or RGBx byte order), box-downscaled to the encoder size on the GPU.267 /// Encodes one packed RGB picture (src_width x src_height, row stride in bytes, BGRx or RGBx byte order), box-downscaled to the encoder size on the GPU.
268- pub fn encode_rgb(268+ pub fn submit_rgb(
269 &mut self,269 &mut self,
270 rgb: &[u8],270 rgb: &[u8],
271 src_width: u32,271 src_width: u32,
@@ -273,7 +273,7 @@ impl H264EncodeSession {
273 stride_bytes: u32,273 stride_bytes: u32,
274 bgr: bool,274 bgr: bool,
275 pic: &H264Picture,275 pic: &H264Picture,
276- ) -> Result<Vec<u8>, Error> {276+ ) -> Result<Option<Vec<u8>>, Error> {
277 self.check(pic)?;277 self.check(pic)?;
278 let src = (src_width as usize, src_height as usize);278 let src = (src_width as usize, src_height as usize);
279 check_rgb(self.enc.input, src, rgb, stride_bytes as usize)?;279 check_rgb(self.enc.input, src, rgb, stride_bytes as usize)?;
@@ -289,13 +289,13 @@ impl H264EncodeSession {
289 289
290 /// Encodes one picture from a DMA-BUF of BGRx or RGBx pixels, box-downscaled to the encoder size on the GPU.290 /// Encodes one picture from a DMA-BUF of BGRx or RGBx pixels, box-downscaled to the encoder size on the GPU.
291 #[cfg(target_os = "linux")]291 #[cfg(target_os = "linux")]
292- pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H264Picture) -> Result<Vec<u8>, Error> {292+ pub fn submit_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H264Picture) -> Result<Option<Vec<u8>>, Error> {
293 self.check(pic)?;293 self.check(pic)?;
294 self.enc.upload_dmabuf(src)?;294 self.enc.upload_dmabuf(src)?;
295 self.encode_uploaded(pic)295 self.encode_uploaded(pic)
296 }296 }
297 297
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> {
299 let extent = self.enc.extent;299 let extent = self.enc.extent;
300 300
301 let primary = if pic.idr {301 let primary = if pic.idr {
@@ -307,7 +307,7 @@ impl H264EncodeSession {
307 picture_resource(self.enc.dpb[0].view, extent),307 picture_resource(self.enc.dpb[0].view, extent),
308 picture_resource(self.enc.dpb[1].view, extent),308 picture_resource(self.enc.dpb[1].view, extent),
309 ];309 ];
310- let src_pr = picture_resource(self.enc.src.view, extent);310+ let src_pr = picture_resource(self.enc.src_view(), extent);
311 311
312 let new_std = reference_info(primary, pic.frame_num, pic.poc);312 let new_std = reference_info(primary, pic.frame_num, pic.poc);
313 let ref_std = pic313 let ref_std = pic
@@ -394,7 +394,7 @@ impl H264EncodeSession {
394 .build();394 .build();
395 395
396 let encode = vk::VideoEncodeInfoKHR::builder()396 let encode = vk::VideoEncodeInfoKHR::builder()
397- .dst_buffer(self.enc.bitstream.buffer)397+ .dst_buffer(self.enc.bitstream_buffer())
398 .dst_buffer_offset(0)398 .dst_buffer_offset(0)
399 .dst_buffer_range(self.enc.bitstream_len)399 .dst_buffer_range(self.enc.bitstream_len)
400 .src_picture_resource(src_pr)400 .src_picture_resource(src_pr)
@@ -406,7 +406,39 @@ impl H264EncodeSession {
406 let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1);406 let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1);
407 let mut chain = RateChain::new(self.enc.rate, self.enc.fps);407 let mut chain = RateChain::new(self.enc.rate, self.enc.fps);
408 self.enc408 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()
410 }442 }
411 443
412 /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change.444 /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change.
shims/vk-video-ffi/src/h265_encode.rsmodified+50 -12
@@ -258,8 +258,8 @@ impl H265EncodeSession {
258 )258 )
259 }259 }
260 260
261- /// Encodes one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) and returns its Annex-B slice NAL units.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 encode(&mut self, y: &[u8], uv: &[u8], pic: &H265Picture) -> Result<Vec<u8>, Error> {262+ pub fn submit(&mut self, y: &[u8], uv: &[u8], pic: &H265Picture) -> Result<Option<Vec<u8>>, Error> {
263 if y.len() != self.enc.input.0 * self.enc.input.1263 if y.len() != self.enc.input.0 * self.enc.input.1
264 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2264 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2
265 {265 {
@@ -270,13 +270,13 @@ impl H265EncodeSession {
270 self.encode_uploaded(pic)270 self.encode_uploaded(pic)
271 }271 }
272 272
273- /// Encodes one 10-bit picture (y: width*height, uv: interleaved CbCr width*height/2, samples in the low 10 bits) of a 10-bit session and returns its Annex-B slice NAL units.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 encode_16(274+ pub fn submit_16(
275 &mut self,275 &mut self,
276 y: &[u16],276 y: &[u16],
277 uv: &[u16],277 uv: &[u16],
278 pic: &H265Picture,278 pic: &H265Picture,
279- ) -> Result<Vec<u8>, Error> {279+ ) -> Result<Option<Vec<u8>>, Error> {
280 if y.len() != self.enc.input.0 * self.enc.input.1280 if y.len() != self.enc.input.0 * self.enc.input.1
281 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2281 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2
282 {282 {
@@ -288,7 +288,7 @@ impl H265EncodeSession {
288 }288 }
289 289
290 /// Encodes one packed RGB picture (src_width x src_height, row stride in bytes, BGRx or RGBx byte order), box-downscaled to the encoder size on the GPU.290 /// Encodes one packed RGB picture (src_width x src_height, row stride in bytes, BGRx or RGBx byte order), box-downscaled to the encoder size on the GPU.
291- pub fn encode_rgb(291+ pub fn submit_rgb(
292 &mut self,292 &mut self,
293 rgb: &[u8],293 rgb: &[u8],
294 src_width: u32,294 src_width: u32,
@@ -296,7 +296,7 @@ impl H265EncodeSession {
296 stride_bytes: u32,296 stride_bytes: u32,
297 bgr: bool,297 bgr: bool,
298 pic: &H265Picture,298 pic: &H265Picture,
299- ) -> Result<Vec<u8>, Error> {299+ ) -> Result<Option<Vec<u8>>, Error> {
300 self.check(pic)?;300 self.check(pic)?;
301 let src = (src_width as usize, src_height as usize);301 let src = (src_width as usize, src_height as usize);
302 check_rgb(302 check_rgb(
@@ -317,13 +317,13 @@ impl H265EncodeSession {
317 317
318 /// Encodes one picture from a DMA-BUF of BGRx or RGBx pixels, box-downscaled to the encoder size on the GPU.318 /// Encodes one picture from a DMA-BUF of BGRx or RGBx pixels, box-downscaled to the encoder size on the GPU.
319 #[cfg(target_os = "linux")]319 #[cfg(target_os = "linux")]
320- pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H265Picture) -> Result<Vec<u8>, Error> {320+ pub fn submit_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H265Picture) -> Result<Option<Vec<u8>>, Error> {
321 self.check(pic)?;321 self.check(pic)?;
322 self.enc.upload_dmabuf(src)?;322 self.enc.upload_dmabuf(src)?;
323 self.encode_uploaded(pic)323 self.encode_uploaded(pic)
324 }324 }
325 325
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> {
327 let extent = self.enc.extent;327 let extent = self.enc.extent;
328 328
329 let primary = if pic.idr {329 let primary = if pic.idr {
@@ -335,7 +335,7 @@ impl H265EncodeSession {
335 picture_resource(self.enc.dpb[0].view, extent),335 picture_resource(self.enc.dpb[0].view, extent),
336 picture_resource(self.enc.dpb[1].view, extent),336 picture_resource(self.enc.dpb[1].view, extent),
337 ];337 ];
338- let src_pr = picture_resource(self.enc.src.view, extent);338+ let src_pr = picture_resource(self.enc.src_view(), extent);
339 339
340 let new_std = reference_info(primary, pic.poc);340 let new_std = reference_info(primary, pic.poc);
341 let ref_std = pic341 let ref_std = pic
@@ -425,7 +425,7 @@ impl H265EncodeSession {
425 .build();425 .build();
426 426
427 let encode = vk::VideoEncodeInfoKHR::builder()427 let encode = vk::VideoEncodeInfoKHR::builder()
428- .dst_buffer(self.enc.bitstream.buffer)428+ .dst_buffer(self.enc.bitstream_buffer())
429 .dst_buffer_offset(0)429 .dst_buffer_offset(0)
430 .dst_buffer_range(self.enc.bitstream_len)430 .dst_buffer_range(self.enc.bitstream_len)
431 .src_picture_resource(src_pr)431 .src_picture_resource(src_pr)
@@ -437,7 +437,45 @@ impl H265EncodeSession {
437 let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1);437 let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1);
438 let mut chain = RateChain::new(self.enc.rate, self.enc.fps);438 let mut chain = RateChain::new(self.enc.rate, self.enc.fps);
439 self.enc439 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()
441 }479 }
442 480
443 /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change.481 /// 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+
1 use vulkanalia::prelude::v1_3::*;3 use vulkanalia::prelude::v1_3::*;
2 use vulkanalia::vk::{4 use vulkanalia::vk::{
3 KhrVideoDecodeQueueExtensionDeviceCommands, KhrVideoEncodeQueueExtensionDeviceCommands,5 KhrVideoDecodeQueueExtensionDeviceCommands, KhrVideoEncodeQueueExtensionDeviceCommands,
@@ -657,22 +659,38 @@ impl Lane {
657 }659 }
658 }660 }
659 661
660- pub(crate) fn submit(&self) -> Result<(), Error> {662+ pub(crate) fn submit_with(
663+ &self,
664+ wait: &[vk::Semaphore],
665+ signal: &[vk::Semaphore],
666+ ) -> Result<(), Error> {
661 let d = self.gpu.device();667 let d = self.gpu.device();
662 let cbs = [self.cb];668 let cbs = [self.cb];
663- let submit = vk::SubmitInfo::builder().command_buffers(&cbs).build();669+ let stages = vec![vk::PipelineStageFlags::ALL_COMMANDS; wait.len()];
670+ let submit = vk::SubmitInfo::builder()
671+ .wait_semaphores(wait)
672+ .wait_dst_stage_mask(&stages)
673+ .command_buffers(&cbs)
674+ .signal_semaphores(signal)
675+ .build();
664 unsafe {676 unsafe {
665 vk(d.reset_fences(&[self.fence]), "vkResetFences")?;677 vk(d.reset_fences(&[self.fence]), "vkResetFences")?;
666 vk(678 vk(
667 d.queue_submit(self.queue, &[submit], self.fence),679 d.queue_submit(self.queue, &[submit], self.fence),
668 "vkQueueSubmit",680 "vkQueueSubmit",
669- )?;681+ )
670- vk(
671- d.wait_for_fences(&[self.fence], true, u64::MAX),
672- "vkWaitForFences",
673- )?;
674 }682 }
675- Ok(())683+ }
684+
685+ pub(crate) fn wait(&self) -> Result<(), Error> {
686+ let fences = [self.fence];
687+ let r = unsafe { self.gpu.device().wait_for_fences(&fences, true, u64::MAX) };
688+ vk(r.map(drop), "vkWaitForFences")
689+ }
690+
691+ pub(crate) fn submit(&self) -> Result<(), Error> {
692+ self.submit_with(&[], &[])?;
693+ self.wait()
676 }694 }
677 }695 }
678 696
@@ -686,101 +704,143 @@ impl Drop for Lane {
686 }704 }
687 }705 }
688 706
689-/// Encode session plumbing shared by H.264, H.265 and AV1: DPB, source, bitstream and upload path.707+const FLIGHT: usize = 2;
690-pub(crate) struct Encoder {708+
691- pub(crate) vs: VideoSession,709+fn semaphore(d: &Device) -> Result<vk::Semaphore, Error> {
692- pub(crate) main: Lane,710+ unsafe {
693- pub(crate) upload: Lane,711+ vk(
694- pub(crate) input: (usize, usize),712+ d.create_semaphore(&vk::SemaphoreCreateInfo::builder().build(), None),
695- pub(crate) extent: vk::Extent2D,713+ "vkCreateSemaphore",
696- pub(crate) rate: RateControl,714+ )
697- pub(crate) fps: (u32, u32),715+ }
698- pub(crate) applied: (RateControl, (u32, u32)),716+}
699- pub(crate) dirty: bool,717+
700- pub(crate) coded: bool,718+/// One in-flight picture: its own source, staging, bitstream, command buffers and sync objects.
701- pub(crate) bitstream_len: u64,719+struct Slot {
702- pub(crate) dpb: [Image; DPB_SLOTS],720+ src: Image,
703- pub(crate) src: Image,
704 staging: Buffer,721 staging: Buffer,
705- rgb: Option<RgbConverter>,722+ rgb: RgbConverter,
706- pub(crate) bitstream: Buffer,723+ bitstream: Buffer,
707- query: vk::QueryPool,724+ main: Lane,
725+ upload: Lane,
726+ ready: vk::Semaphore,
727+ encoded: vk::Semaphore,
728+ #[cfg(target_os = "linux")]
729+ import: Option<Import>,
708 }730 }
709 731
710-impl Encoder {732+impl Slot {
711- pub(crate) fn new(733+ fn new(
712- vs: VideoSession,734+ vs: &mut VideoSession,
713 profile: &vk::VideoProfileInfoKHR,735 profile: &vk::VideoProfileInfoKHR,
714 upload_family: u32,736 upload_family: u32,
715 input: (u32, u32),737 input: (u32, u32),
716 extent: vk::Extent2D,738 extent: vk::Extent2D,
717- setting: (RateControl, (u32, u32)),739+ frame_bytes: u64,
718- size_align: u64,740+ bitstream_len: u64,
719 ) -> Result<Self, Error> {741 ) -> Result<Self, Error> {
720 let gpu = vs.gpu.clone();742 let gpu = vs.gpu.clone();
721- let main = Lane::new(&gpu, vs.family)?;743+ let d = gpu.device();
722- let upload = Lane::new(&gpu, upload_family)?;744+ let family = vs.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;
745 let mut list = vk::VideoProfileListInfoKHR::builder()745 let mut list = vk::VideoProfileListInfoKHR::builder()
746 .profiles(std::slice::from_ref(profile))746 .profiles(std::slice::from_ref(profile))
747 .build();747 .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)?;
751 let shared = if upload_family == family {748 let shared = if upload_family == family {
752 vec![family]749 vec![family]
753 } else {750 } else {
754 vec![upload_family, family]751 vec![upload_family, family]
755 };752 };
756- e.src = e.vs.image(753+ let src = vs.image(
757 extent,754 extent,
758 vk::ImageUsageFlags::VIDEO_ENCODE_SRC_KHR | vk::ImageUsageFlags::TRANSFER_DST,755 vk::ImageUsageFlags::VIDEO_ENCODE_SRC_KHR | vk::ImageUsageFlags::TRANSFER_DST,
759 vk::ImageUsageFlags::VIDEO_ENCODE_SRC_KHR | vk::ImageUsageFlags::TRANSFER_DST,756 vk::ImageUsageFlags::VIDEO_ENCODE_SRC_KHR | vk::ImageUsageFlags::TRANSFER_DST,
760 &shared,757 &shared,
761 &mut list,758 &mut list,
762 )?;759 )?;
763- e.staging = e.vs.buffer(760+ let staging = vs.buffer(
764 frame_bytes,761 frame_bytes,
765 vk::BufferUsageFlags::TRANSFER_SRC | vk::BufferUsageFlags::STORAGE_BUFFER,762 vk::BufferUsageFlags::TRANSFER_SRC | vk::BufferUsageFlags::STORAGE_BUFFER,
766 &[vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT],763 &[vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT],
767 None,764 None,
768 )?;765 )?;
769- e.rgb = Some(RgbConverter::new(766+ let rgb = RgbConverter::new(&gpu, input, (extent.width, extent.height), staging.buffer)?;
770- &gpu,767+ let bitstream = vs.buffer(
771- input,768+ bitstream_len,
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,
778 vk::BufferUsageFlags::VIDEO_ENCODE_DST_KHR,769 vk::BufferUsageFlags::VIDEO_ENCODE_DST_KHR,
779 &[vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT],770 &[vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT],
780 Some(&mut list),771 Some(&mut list),
781 )?;772 )?;
773+ Ok(Slot {
774+ src,
775+ staging,
776+ rgb,
777+ bitstream,
778+ main: Lane::new(&gpu, family)?,
779+ upload: Lane::new(&gpu, upload_family)?,
780+ ready: semaphore(d)?,
781+ encoded: semaphore(d)?,
782+ #[cfg(target_os = "linux")]
783+ import: None,
784+ })
785+ }
782 786
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();
783 let d = gpu.device();826 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+
784 let mut feedback = vk::QueryPoolVideoEncodeFeedbackCreateInfoKHR::builder()844 let mut feedback = vk::QueryPoolVideoEncodeFeedbackCreateInfoKHR::builder()
785 .encode_feedback_flags(845 .encode_feedback_flags(
786 vk::VideoEncodeFeedbackFlagsKHR::BITSTREAM_BUFFER_OFFSET846 vk::VideoEncodeFeedbackFlagsKHR::BITSTREAM_BUFFER_OFFSET
@@ -790,28 +850,51 @@ impl Encoder {
790 let mut prof = *profile;850 let mut prof = *profile;
791 let query_info = vk::QueryPoolCreateInfo::builder()851 let query_info = vk::QueryPoolCreateInfo::builder()
792 .query_type(vk::QueryType::VIDEO_ENCODE_FEEDBACK_KHR)852 .query_type(vk::QueryType::VIDEO_ENCODE_FEEDBACK_KHR)
793- .query_count(1)853+ .query_count(FLIGHT as u32)
794 .push_next(&mut feedback)854 .push_next(&mut feedback)
795 .push_next(&mut prof)855 .push_next(&mut prof)
796 .build();856 .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")? };
798 858
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()?;
800 for img in &e.dpb {879 for img in &e.dpb {
801- init_barrier(880+ init_barrier(d, lane.cb, img.image, vk::ImageLayout::VIDEO_ENCODE_DPB_KHR);
802- d,
803- e.main.cb,
804- img.image,
805- vk::ImageLayout::VIDEO_ENCODE_DPB_KHR,
806- );
807 }881 }
808- e.main.end()?;882+ lane.end()?;
809- e.main.submit()?;883+ lane.submit()?;
810 Ok(e)884 Ok(e)
811 }885 }
812 886
813- pub(crate) fn staging_ptr(&self) -> Result<*mut u8, Error> {887+ pub(crate) fn src_view(&self) -> vk::ImageView {
814- self.staging888+ 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
815 .ptr898 .ptr
816 .ok_or_else(|| Error::Invalid("staging buffer not mapped".into()))899 .ok_or_else(|| Error::Invalid("staging buffer not mapped".into()))
817 }900 }
@@ -844,6 +927,8 @@ impl Encoder {
844 _ => {}927 _ => {}
845 }928 }
846 let gpu = self.vs.gpu.clone();929 let gpu = self.vs.gpu.clone();
930+ let k = self.next;
931+ self.cur = k;
847 match input {932 match input {
848 Input::Nv12 { y, uv } => {933 Input::Nv12 { y, uv } => {
849 let staging =934 let staging =
@@ -862,42 +947,36 @@ impl Encoder {
862 stride,947 stride,
863 ..948 ..
864 } => {949 } => {
865- let rgb = self950+ let rgb = &mut self.slots[k].rgb;
866- .rgb
867- .as_mut()
868- .ok_or_else(|| Error::Invalid("RGB converter not created".into()))?;
869 rgb.reserve(&gpu, width, height)?;951 rgb.reserve(&gpu, width, height)?;
870 rgb.load(data, stride);952 rgb.load(data, stride);
871 }953 }
872 #[cfg(target_os = "linux")]954 #[cfg(target_os = "linux")]
873 Input::DmaBuf { width, height, .. } => {955 Input::DmaBuf { width, height, .. } => {
874- let rgb = self956+ self.slots[k].rgb.reserve(&gpu, width, height)?;
875- .rgb
876- .as_mut()
877- .ok_or_else(|| Error::Invalid("RGB converter not created".into()))?;
878- rgb.reserve(&gpu, width, height)?;
879 }957 }
880 }958 }
881 959
882 let d = gpu.device();960 let d = gpu.device();
883- let cb = self.upload.cb;961+ let slot = &self.slots[k];
962+ let cb = slot.upload.cb;
884 let luma = (aw * ah * bytes) as u64;963 let luma = (aw * ah * bytes) as u64;
885 let copies = [964 let copies = [
886 copy_region(0, PLANE_0, aw as u32, ah as u32),965 copy_region(0, PLANE_0, aw as u32, ah as u32),
887 copy_region(luma, PLANE_1, (aw / 2) as u32, (ah / 2) as u32),966 copy_region(luma, PLANE_1, (aw / 2) as u32, (ah / 2) as u32),
888 ];967 ];
889- self.upload.begin()?;968+ slot.upload.begin()?;
890 unsafe {969 unsafe {
891- if let (Some(bgr), Some(rgb)) = (input.bgr(), &self.rgb) {970+ if let Some(bgr) = input.bgr() {
892 if let Some(image) = input.source_image() {971 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);
894 }973 }
895- rgb.record(d, cb, bgr);974+ slot.rgb.record(d, cb, bgr);
896 }975 }
897 barrier(976 barrier(
898 d,977 d,
899 cb,978 cb,
900- self.src.image,979+ slot.src.image,
901 (980 (
902 vk::ImageLayout::UNDEFINED,981 vk::ImageLayout::UNDEFINED,
903 vk::PipelineStageFlags2::NONE,982 vk::PipelineStageFlags2::NONE,
@@ -911,15 +990,15 @@ impl Encoder {
911 );990 );
912 d.cmd_copy_buffer_to_image(991 d.cmd_copy_buffer_to_image(
913 cb,992 cb,
914- self.staging.buffer,993+ slot.staging.buffer,
915- self.src.image,994+ slot.src.image,
916 vk::ImageLayout::TRANSFER_DST_OPTIMAL,995 vk::ImageLayout::TRANSFER_DST_OPTIMAL,
917 &copies,996 &copies,
918 );997 );
919 barrier(998 barrier(
920 d,999 d,
921 cb,1000 cb,
922- self.src.image,1001+ slot.src.image,
923 (1002 (
924 vk::ImageLayout::TRANSFER_DST_OPTIMAL,1003 vk::ImageLayout::TRANSFER_DST_OPTIMAL,
925 vk::PipelineStageFlags2::COPY,1004 vk::PipelineStageFlags2::COPY,
@@ -932,8 +1011,8 @@ impl Encoder {
932 ),1011 ),
933 );1012 );
934 }1013 }
935- self.upload.end()?;1014+ slot.upload.end()?;
936- self.upload.submit()1015+ slot.upload.submit_with(&[], &[slot.ready])
937 }1016 }
938 1017
939 #[cfg(target_os = "linux")]1018 #[cfg(target_os = "linux")]
@@ -948,30 +1027,41 @@ impl Encoder {
948 height,1027 height,
949 bgr: src.bgr,1028 bgr: src.bgr,
950 });1029 });
951- import.destroy(gpu.device());1030+ match result {
952- result1031+ 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+ }
953 }1040 }
954 1041
955- /// Records one encode with its rate control chains, submits it and returns the coded bytes.1042+ /// Records the encode of the uploaded slot and submits it without waiting. Returns the oldest picture once FLIGHT are queued.
956- pub(crate) fn run(1043+ pub(crate) fn submit(
957 &mut self,1044 &mut self,
958 begin_slots: &[vk::VideoReferenceSlotInfoKHR],1045 begin_slots: &[vk::VideoReferenceSlotInfoKHR],
959 applied: &mut vk::VideoEncodeRateControlInfoKHR,1046 applied: &mut vk::VideoEncodeRateControlInfoKHR,
960 chain: &mut vk::VideoEncodeRateControlInfoKHR,1047 chain: &mut vk::VideoEncodeRateControlInfoKHR,
961 encode: &vk::VideoEncodeInfoKHR,1048 encode: &vk::VideoEncodeInfoKHR,
962- ) -> Result<Vec<u8>, Error> {1049+ ) -> Result<Option<Vec<u8>>, Error> {
963 let gpu = self.vs.gpu.clone();1050 let gpu = self.vs.gpu.clone();
964 let d = gpu.device();1051 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;
966 let mut quality = vk::VideoEncodeQualityLevelInfoKHR::builder()1056 let mut quality = vk::VideoEncodeQualityLevelInfoKHR::builder()
967 .quality_level(0)1057 .quality_level(0)
968 .build();1058 .build();
969 let reset = !self.coded;1059 let reset = !self.coded;
970 let update = reset || self.dirty;1060 let update = reset || self.dirty;
971 1061
972- self.main.begin()?;1062+ slot.main.begin()?;
973 unsafe {1063 unsafe {
974- d.cmd_reset_query_pool(cb, self.query, 0, 1);1064+ d.cmd_reset_query_pool(cb, self.query, query, 1);
975 let begin = vk::VideoBeginCodingInfoKHR::builder()1065 let begin = vk::VideoBeginCodingInfoKHR::builder()
976 .video_session(self.vs.session)1066 .video_session(self.vs.session)
977 .video_session_parameters(self.vs.params)1067 .video_session_parameters(self.vs.params)
@@ -999,27 +1089,68 @@ impl Encoder {
999 d.cmd_control_video_coding_khr(cb, &control);1089 d.cmd_control_video_coding_khr(cb, &control);
1000 }1090 }
1001 1091
1002- d.cmd_begin_query(cb, self.query, 0, vk::QueryControlFlags::empty());1092+ d.cmd_begin_query(cb, self.query, query, vk::QueryControlFlags::empty());
1003 d.cmd_encode_video_khr(cb, encode);1093 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);
1005 let end = vk::VideoEndCodingInfoKHR::builder().build();1095 let end = vk::VideoEndCodingInfoKHR::builder().build();
1006 d.cmd_end_video_coding_khr(cb, &end);1096 d.cmd_end_video_coding_khr(cb, &end);
1007 }1097 }
1008- self.main.end()?;1098+ slot.main.end()?;
1009- self.main.submit()?;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;
1010 self.coded = true;1107 self.coded = true;
1011 self.applied = (self.rate, self.fps);1108 self.applied = (self.rate, self.fps);
1012 self.dirty = false;1109 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()))
1014 }1135 }
1015 1136
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> {
1017 let mut feedback = [0u8; 8];1148 let mut feedback = [0u8; 8];
1018 unsafe {1149 unsafe {
1019 vk(1150 vk(
1020 self.vs.gpu.device().get_query_pool_results(1151 self.vs.gpu.device().get_query_pool_results(
1021 self.query,1152 self.query,
1022- 0,1153+ k as u32,
1023 1,1154 1,
1024 &mut feedback,1155 &mut feedback,
1025 8,1156 8,
@@ -1037,7 +1168,7 @@ impl Encoder {
1037 "encoded size exceeds bitstream buffer".into(),1168 "encoded size exceeds bitstream buffer".into(),
1038 ));1169 ));
1039 }1170 }
1040- let ptr = self1171+ let ptr = self.slots[k]
1041 .bitstream1172 .bitstream
1042 .ptr1173 .ptr
1043 .ok_or_else(|| Error::Invalid("bitstream buffer not mapped".into()))?;1174 .ok_or_else(|| Error::Invalid("bitstream buffer not mapped".into()))?;
@@ -1054,14 +1185,20 @@ impl Drop for Encoder {
1054 let _ = d.device_wait_idle();1185 let _ = d.device_wait_idle();
1055 d.destroy_query_pool(self.query, None);1186 d.destroy_query_pool(self.query, None);
1056 }1187 }
1057- for img in self.dpb.iter().chain(std::iter::once(&self.src)) {1188+ for img in &self.dpb {
1058 img.destroy(d);1189 img.destroy(d);
1059 }1190 }
1060- if let Some(rgb) = &self.rgb {1191+ for slot in self.slots.iter_mut() {
1061- rgb.destroy(d);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);
1062 }1201 }
1063- self.staging.destroy(d);
1064- self.bitstream.destroy(d);
1065 }1202 }
1066 }1203 }
1067 1204