forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'worktree-agent-ab057528cdea26a6b'

Browse files at this commit

5d4b8b4dada6a8fadcbd3bf148865a6c7a48c514Ahmet Kaan GümüşParent: 7996a9587336a0
# Conflicts:
#	crates/ec-hw/src/hw.rs
#	shims/vk-video-ffi/src/av1_encode.rs
#	shims/vk-video-ffi/src/h264_encode.rs
#	shims/vk-video-ffi/src/h265_encode.rs
#	shims/vk-video-ffi/src/session.rs

11 changed files +1039 -254

crates/ec-hw/examples/hw_pipeline.rsadded+165 -0
@@ -0,0 +1,165 @@
1+use std::time::Instant;
2+
3+use ec_hw::{
4+ Backend, EncCodec, EncodeInput, EncoderConfig, FrameMetadata, HwEncoder, I420, I420_16,
5+ RateControlMode,
6+};
7+
8+const FRAMES: usize = 120;
9+const PATTERN: usize = 6;
10+
11+struct Case {
12+ codec: EncCodec,
13+ width: u32,
14+ height: u32,
15+ ten: bool,
16+}
17+
18+enum Source {
19+ Eight(Vec<I420>),
20+ Ten(Vec<I420_16>),
21+}
22+
23+fn main() {
24+ let cases = [
25+ Case {
26+ codec: EncCodec::H265,
27+ width: 3840,
28+ height: 2160,
29+ ten: true,
30+ },
31+ Case {
32+ codec: EncCodec::H264,
33+ width: 1920,
34+ height: 1080,
35+ ten: false,
36+ },
37+ Case {
38+ codec: EncCodec::H265,
39+ width: 1920,
40+ height: 1080,
41+ ten: false,
42+ },
43+ Case {
44+ codec: EncCodec::Av1,
45+ width: 1920,
46+ height: 1080,
47+ ten: false,
48+ },
49+ ];
50+ for case in &cases {
51+ let source = if case.ten {
52+ Source::Ten(pattern_16(case))
53+ } else {
54+ Source::Eight(pattern(case))
55+ };
56+ for backend in [Backend::Vk, Backend::Va] {
57+ if let Err(e) = run(case, &source, backend) {
58+ println!(
59+ "{:?} {}x{} {backend:?}: error: {e}",
60+ case.codec, case.width, case.height
61+ );
62+ }
63+ }
64+ }
65+}
66+
67+fn config(case: &Case) -> EncoderConfig {
68+ let base = EncoderConfig {
69+ rate_control: RateControlMode::ConstantQp { qp: 30 },
70+ ..EncoderConfig::new(case.codec, case.width, case.height)
71+ };
72+ if case.ten {
73+ base.ten_bit()
74+ } else {
75+ base
76+ }
77+}
78+
79+fn meta(index: usize) -> FrameMetadata {
80+ FrameMetadata {
81+ timestamp: index as i64,
82+ force_keyframe: index == 0,
83+ }
84+}
85+
86+fn run(case: &Case, source: &Source, backend: Backend) -> ec_hw::Result<()> {
87+ let mut encoder = HwEncoder::open(config(case), Some(backend))?;
88+ let start = Instant::now();
89+ let mut sync = Vec::with_capacity(FRAMES);
90+ for index in 0..FRAMES {
91+ let coded = match source {
92+ Source::Eight(frames) => encoder.encode(&frames[index % PATTERN], meta(index))?,
93+ Source::Ten(frames) => encoder.encode_16(&frames[index % PATTERN], meta(index))?,
94+ };
95+ sync.push(coded);
96+ }
97+ let sync_ms = start.elapsed().as_secs_f64() * 1000.0 / FRAMES as f64;
98+
99+ let mut encoder = HwEncoder::open(config(case), Some(backend))?;
100+ let start = Instant::now();
101+ let mut piped = Vec::with_capacity(FRAMES);
102+ for index in 0..FRAMES {
103+ let input = match source {
104+ Source::Eight(frames) => EncodeInput::I420(&frames[index % PATTERN]),
105+ Source::Ten(frames) => EncodeInput::I420_16(&frames[index % PATTERN]),
106+ };
107+ piped.extend(encoder.submit(input, meta(index))?);
108+ }
109+ piped.extend(encoder.flush()?);
110+ let piped_ms = start.elapsed().as_secs_f64() * 1000.0 / FRAMES as f64;
111+
112+ if matches!(backend, Backend::Vk) {
113+ assert_eq!(sync, piped, "{:?} sync and pipelined bitstreams differ", case.codec);
114+ }
115+ println!(
116+ "{:?} {}x{} {}-bit {backend:?}: sync {sync_ms:.2} ms/frame, pipelined {piped_ms:.2} ms/frame, {} frames",
117+ case.codec,
118+ case.width,
119+ case.height,
120+ if case.ten { 10 } else { 8 },
121+ piped.len()
122+ );
123+ Ok(())
124+}
125+
126+fn pattern(case: &Case) -> Vec<I420> {
127+ let (w, h) = (case.width as usize, case.height as usize);
128+ let (cw, ch) = (w / 2, h / 2);
129+ (0..PATTERN)
130+ .map(|k| I420 {
131+ y: (0..h)
132+ .flat_map(move |row| (0..w).map(move |x| ((x + row + 3 * k) & 0xff) as u8))
133+ .collect(),
134+ u: (0..ch)
135+ .flat_map(move |row| (0..cw).map(move |x| ((x + 2 * row + 5 * k) & 0xff) as u8))
136+ .collect(),
137+ v: (0..ch)
138+ .flat_map(move |row| (0..cw).map(move |x| ((2 * x + row + 7 * k) & 0xff) as u8))
139+ .collect(),
140+ width: case.width,
141+ height: case.height,
142+ })
143+ .collect()
144+}
145+
146+fn pattern_16(case: &Case) -> Vec<I420_16> {
147+ let (w, h) = (case.width as usize, case.height as usize);
148+ let (cw, ch) = (w / 2, h / 2);
149+ (0..PATTERN)
150+ .map(|k| I420_16 {
151+ y: (0..h)
152+ .flat_map(move |row| (0..w).map(move |x| ((x + row + 3 * k) & 0x3ff) as u16))
153+ .collect(),
154+ u: (0..ch)
155+ .flat_map(move |row| (0..cw).map(move |x| ((x + 2 * row + 5 * k) & 0x3ff) as u16))
156+ .collect(),
157+ v: (0..ch)
158+ .flat_map(move |row| (0..cw).map(move |x| ((2 * x + row + 7 * k) & 0x3ff) as u16))
159+ .collect(),
160+ width: case.width,
161+ height: case.height,
162+ bit_depth: 10,
163+ })
164+ .collect()
165+}
crates/ec-hw/src/hw.rsmodified+166 -0
@@ -7,6 +7,7 @@ use std::os::fd::BorrowedFd;
77 use ec_vk::{DmaBuf, DmaBufFormat, DmaBufPlane};
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};
@@ -257,6 +258,23 @@ pub struct DmaBufFrame<'a> {
257258 pub order: RgbOrder,
258259 }
259260
261+/// One picture for [`HwEncoder::submit`].
262+#[derive(Debug, Clone, Copy)]
263+pub enum EncodeInput<'a> {
264+ /// 8-bit I420.
265+ I420(&'a I420),
266+ /// 10-bit I420 of a 10-bit encoder (H.265 and AV1).
267+ I420_16(&'a I420_16),
268+ /// Packed RGB, box-downscaled to the encoder size.
269+ Rgb(&'a RgbFrame<'a>),
270+ /// DMA-BUF of packed RGB, Vulkan only.
271+ #[cfg(target_os = "linux")]
272+ DmaBuf(&'a DmaBufFrame<'a>),
273+ /// DMA-BUF of NV12 or P010 at the encoder size, Vulkan only.
274+ #[cfg(target_os = "linux")]
275+ DmaBufYuv(&'a DmaBufYuvFrame<'a>),
276+}
277+
260278 #[cfg(target_os = "linux")]
261279 fn rgb_to_i420(frame: &RgbFrame, (w, h): (usize, usize)) -> Result<I420> {
262280 let (sw, sh, stride) = (
@@ -315,7 +333,103 @@ enum VkEncoder {
315333 Av1(ec_vk::Av1Encoder),
316334 }
317335
336+fn stamp(pending: &mut VecDeque<i64>, coded: ec_vk::CodedFrame) -> CodedFrame {
337+ CodedFrame {
338+ data: coded.data,
339+ timestamp: pending.pop_front().unwrap_or_default(),
340+ is_keyframe: coded.keyframe,
341+ }
342+}
343+
318344 impl VkEncoder {
345+ fn submit(
346+ &mut self,
347+ input: EncodeInput,
348+ force_keyframe: bool,
349+ ) -> std::result::Result<Option<ec_vk::CodedFrame>, ec_vk::Error> {
350+ match input {
351+ EncodeInput::I420(frame) => {
352+ let (y, u, v) = (&frame.y, &frame.u, &frame.v);
353+ match self {
354+ VkEncoder::H264(e) => e.submit(y, u, v, force_keyframe),
355+ VkEncoder::H265(e) => e.submit(y, u, v, force_keyframe),
356+ VkEncoder::Av1(e) => e.submit(y, u, v, force_keyframe),
357+ }
358+ }
359+ EncodeInput::I420_16(frame) => {
360+ let (y, u, v) = (&frame.y, &frame.u, &frame.v);
361+ match self {
362+ VkEncoder::H264(_) => Err(ec_vk::Error::Unsupported("10-bit H.264 encode".into())),
363+ VkEncoder::H265(e) => e.submit_16(y, u, v, force_keyframe),
364+ VkEncoder::Av1(e) => e.submit_16(y, u, v, force_keyframe),
365+ }
366+ }
367+ EncodeInput::Rgb(frame) => {
368+ let bgr = frame.order == RgbOrder::Bgra;
369+ let (data, sw, sh, stride) = (frame.data, frame.width, frame.height, frame.stride);
370+ match self {
371+ VkEncoder::H264(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe),
372+ VkEncoder::H265(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe),
373+ VkEncoder::Av1(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe),
374+ }
375+ }
376+ #[cfg(target_os = "linux")]
377+ EncodeInput::DmaBuf(frame) => {
378+ let planes = [DmaBufPlane {
379+ fd: 0,
380+ offset: frame.offset,
381+ pitch: frame.stride,
382+ }];
383+ let src = DmaBuf {
384+ fds: std::slice::from_ref(&frame.fd),
385+ planes: &planes,
386+ width: frame.width,
387+ height: frame.height,
388+ modifier: frame.modifier,
389+ format: if frame.order == RgbOrder::Bgra {
390+ DmaBufFormat::Bgrx
391+ } else {
392+ DmaBufFormat::Rgbx
393+ },
394+ };
395+ self.submit_dma(&src, force_keyframe)
396+ }
397+ #[cfg(target_os = "linux")]
398+ EncodeInput::DmaBufYuv(frame) => {
399+ let src = DmaBuf {
400+ fds: frame.fds,
401+ planes: &frame.planes,
402+ width: frame.width,
403+ height: frame.height,
404+ modifier: frame.modifier,
405+ format: frame.format,
406+ };
407+ self.submit_dma(&src, force_keyframe)
408+ }
409+ }
410+ }
411+
412+ #[cfg(target_os = "linux")]
413+ fn submit_dma(
414+ &mut self,
415+ src: &DmaBuf,
416+ force_keyframe: bool,
417+ ) -> std::result::Result<Option<ec_vk::CodedFrame>, ec_vk::Error> {
418+ match self {
419+ VkEncoder::H264(e) => e.submit_dmabuf(src, force_keyframe),
420+ VkEncoder::H265(e) => e.submit_dmabuf(src, force_keyframe),
421+ VkEncoder::Av1(e) => e.submit_dmabuf(src, force_keyframe),
422+ }
423+ }
424+
425+ fn flush(&mut self) -> std::result::Result<Vec<ec_vk::CodedFrame>, ec_vk::Error> {
426+ match self {
427+ VkEncoder::H264(e) => e.flush(),
428+ VkEncoder::H265(e) => e.flush(),
429+ VkEncoder::Av1(e) => e.flush(),
430+ }
431+ }
432+
319433 fn encode(
320434 &mut self,
321435 frame: &I420,
@@ -395,6 +509,7 @@ pub struct HwEncoder {
395509 config: EncoderConfig,
396510 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
397511 size: (usize, usize),
512+ pending: VecDeque<i64>,
398513 }
399514
400515 impl HwEncoder {
@@ -415,6 +530,7 @@ impl HwEncoder {
415530 born_epoch,
416531 config,
417532 size,
533+ pending: VecDeque::new(),
418534 });
419535 }
420536 Err(e) => reasons.push(format!("{backend:?}: {e}")),
@@ -454,8 +570,55 @@ impl HwEncoder {
454570 Ok(())
455571 }
456572
573+ /// Submit one picture without waiting; the oldest coded picture comes back once two are in flight. Call [`HwEncoder::flush`] at the end.
574+ pub fn submit(&mut self, input: EncodeInput, meta: FrameMetadata) -> Result<Option<CodedFrame>> {
575+ match &mut self.inner {
576+ EncInner::Vk(enc) => {
577+ vk_session_alive(self.born_epoch)?;
578+ self.pending.push_back(meta.timestamp);
579+ let out = enc.submit(input, meta.force_keyframe)?;
580+ Ok(out.map(|coded| stamp(&mut self.pending, coded)))
581+ }
582+ #[cfg(target_os = "linux")]
583+ EncInner::Va(enc) => match input {
584+ EncodeInput::I420(frame) => enc.submit(frame, meta),
585+ EncodeInput::I420_16(frame) => enc.submit_16(frame, meta),
586+ EncodeInput::Rgb(frame) => enc.submit(&rgb_to_i420(frame, self.size)?, meta),
587+ EncodeInput::DmaBuf(_) | EncodeInput::DmaBufYuv(_) => Err(Error::unsupported(
588+ "DMA-BUF encode",
589+ "the VA-API backend has no DMA-BUF input here",
590+ )),
591+ },
592+ }
593+ }
594+
595+ /// Wait for every submitted picture and return them, oldest first.
596+ pub fn flush(&mut self) -> Result<Vec<CodedFrame>> {
597+ match &mut self.inner {
598+ EncInner::Vk(enc) => {
599+ vk_session_alive(self.born_epoch)?;
600+ let frames = enc.flush()?;
601+ Ok(frames
602+ .into_iter()
603+ .map(|coded| stamp(&mut self.pending, coded))
604+ .collect())
605+ }
606+ #[cfg(target_os = "linux")]
607+ EncInner::Va(enc) => enc.flush(),
608+ }
609+ }
610+
611+ fn idle(&self) -> Result<()> {
612+ if self.pending.is_empty() {
613+ Ok(())
614+ } else {
615+ Err(Error::config("pipelined frames pending; call flush first"))
616+ }
617+ }
618+
457619 /// Encode one frame; `meta.force_keyframe` starts a new GOP.
458620 pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> {
621+ self.idle()?;
459622 match &mut self.inner {
460623 EncInner::Vk(enc) => {
461624 vk_session_alive(self.born_epoch)?;
@@ -473,6 +636,7 @@ impl HwEncoder {
473636
474637 /// Encode one 10-bit frame of a 10-bit encoder (H.265 and AV1), the [`HwEncoder::encode`] of a 10-bit encoder.
475638 pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result<CodedFrame> {
639+ self.idle()?;
476640 match &mut self.inner {
477641 EncInner::Vk(enc) => {
478642 let coded = enc.encode_16(frame, meta.force_keyframe)?;
@@ -489,6 +653,7 @@ impl HwEncoder {
489653
490654 /// 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.
491655 pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result<CodedFrame> {
656+ self.idle()?;
492657 match &mut self.inner {
493658 EncInner::Vk(enc) => {
494659 vk_session_alive(self.born_epoch)?;
@@ -551,6 +716,7 @@ impl HwEncoder {
551716
552717 #[cfg(target_os = "linux")]
553718 fn encode_dma(&mut self, src: &DmaBuf, meta: FrameMetadata) -> Result<CodedFrame> {
719+ self.idle()?;
554720 match &mut self.inner {
555721 EncInner::Vk(enc) => {
556722 vk_session_alive(self.born_epoch)?;
crates/ec-hw/src/lib.rsmodified+2 -1
@@ -90,7 +90,8 @@ pub use ec_vk::{DmaBufFormat, DmaBufPlane};
9090 #[cfg(target_os = "linux")]
9191 pub use hw::{DmaBufFrame, DmaBufYuvFrame};
9292 pub use hw::{
93- Backend, Capability, Direction, HwDecoder, HwEncoder, RgbFrame, RgbOrder, RgbOutput,
93+ Backend, Capability, Direction, EncodeInput, HwDecoder, HwEncoder, RgbFrame, RgbOrder,
94+ RgbOutput,
9495 capabilities,
9596 };
9697 #[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,7 +277,7 @@ impl Av1EncodeSession {
277277 }
278278 /// Encodes one picture from a DMA-BUF: BGRx or RGBx box-downscaled to the encoder size, or NV12 or P010 of the encoder size.
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)
@@ -289,7 +289,7 @@ impl Av1EncodeSession {
289289 self.enc.import_count()
290290 }
291291
292- fn encode_uploaded(&mut self, pic: &Av1Picture) -> Result<Vec<u8>, Error> {
292+ fn encode_uploaded(&mut self, pic: &Av1Picture) -> Result<Option<Vec<u8>>, Error> {
293293 let extent = self.enc.extent;
294294
295295 let refresh: u8 = if pic.key { 0xff } else { 1 << pic.slot };
@@ -297,7 +297,7 @@ impl Av1EncodeSession {
297297 picture_resource(self.enc.dpb[0].view, extent),
298298 picture_resource(self.enc.dpb[1].view, extent),
299299 ];
300- let src_pr = picture_resource(self.enc.src.view, extent);
300+ let src_pr = picture_resource(self.enc.src_view(), extent);
301301
302302 let key_of = self.slot_key;
303303 let mut new_std = zeroed::<vk::video::StdVideoEncodeAV1ReferenceInfo>();
@@ -399,7 +399,7 @@ impl Av1EncodeSession {
399399 };
400400
401401 let encode = vk::VideoEncodeInfoKHR::builder()
402- .dst_buffer(self.enc.bitstream.buffer)
402+ .dst_buffer(self.enc.bitstream_buffer())
403403 .dst_buffer_offset(0)
404404 .dst_buffer_range(self.enc.bitstream_len)
405405 .src_picture_resource(src_pr)
@@ -412,7 +412,7 @@ impl Av1EncodeSession {
412412 let mut chain = RateChain::new(self.enc.rate, self.enc.fps);
413413 let out = self
414414 .enc
415- .run(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)?;
415+ .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)?;
416416 for i in 0..DPB_SLOTS {
417417 if refresh >> i & 1 == 1 {
418418 self.slot_key[i] = pic.key;
@@ -426,6 +426,44 @@ impl Av1EncodeSession {
426426 Ok(out)
427427 }
428428
429+ /// Encodes one picture synchronously and returns its coded bytes.
430+ pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &Av1Picture) -> Result<Vec<u8>, Error> {
431+ self.submit(y, uv, pic)?;
432+ self.enc.flush_last()
433+ }
434+
435+ /// Encodes one picture synchronously and returns its coded bytes.
436+ pub fn encode_16(&mut self, y: &[u16], uv: &[u16], pic: &Av1Picture) -> Result<Vec<u8>, Error> {
437+ self.submit_16(y, uv, pic)?;
438+ self.enc.flush_last()
439+ }
440+
441+ /// Encodes one picture synchronously and returns its coded bytes.
442+ pub fn encode_rgb(
443+ &mut self,
444+ rgb: &[u8],
445+ src_width: u32,
446+ src_height: u32,
447+ stride_bytes: u32,
448+ bgr: bool,
449+ pic: &Av1Picture,
450+ ) -> Result<Vec<u8>, Error> {
451+ self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?;
452+ self.enc.flush_last()
453+ }
454+
455+ #[cfg(target_os = "linux")]
456+ /// Encodes one picture synchronously and returns its coded bytes.
457+ pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &Av1Picture) -> Result<Vec<u8>, Error> {
458+ self.submit_dmabuf(src, pic)?;
459+ self.enc.flush_last()
460+ }
461+
462+ /// Waits for queued pictures and returns their coded bytes in order.
463+ pub fn flush(&mut self) -> Result<Vec<Vec<u8>>, Error> {
464+ self.enc.flush()
465+ }
466+
429467 /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change.
430468 pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {
431469 self.enc.set_rate(rate, fps)
shims/vk-video-ffi/src/dmabuf.rsmodified+14 -6
@@ -213,11 +213,12 @@ impl Key {
213213
214214 pub(crate) struct Import {
215215 pub(crate) image: vk::Image,
216+ id: u64,
216217 memories: Vec<vk::DeviceMemory>,
217218 }
218219
219220 impl Import {
220- fn new(gpu: &Gpu, src: &DmaBuf) -> Result<Self, Error> {
221+ fn new(gpu: &Gpu, src: &DmaBuf, id: u64) -> Result<Self, Error> {
221222 check(gpu)?;
222223 validate(src)?;
223224 let d = gpu.device();
@@ -271,7 +272,7 @@ impl Import {
271272 .build();
272273 let image = unsafe { vk(d.create_image(&info, None), "vkCreateImage")? };
273274 match bind(gpu, image, src) {
274- Ok(memories) => Ok(Import { image, memories }),
275+ Ok(memories) => Ok(Import { image, id, memories }),
275276 Err(e) => {
276277 unsafe { d.destroy_image(image, None) };
277278 Err(e)
@@ -292,11 +293,12 @@ impl Import {
292293 #[derive(Default)]
293294 pub(crate) struct ImportCache {
294295 entries: Vec<(Key, Import)>,
296+ next_id: u64,
295297 pub(crate) count: usize,
296298 }
297299
298300 impl ImportCache {
299- pub(crate) fn get(&mut self, gpu: &Gpu, src: &DmaBuf) -> Result<vk::Image, Error> {
301+ pub(crate) fn get(&mut self, gpu: &Gpu, src: &DmaBuf, busy: &[u64]) -> Result<(vk::Image, u64), Error> {
300302 validate(src)?;
301303 let key = Key::new(src)?;
302304 match self.entries.iter().position(|(k, _)| *k == key) {
@@ -306,17 +308,23 @@ impl ImportCache {
306308 }
307309 None => {
308310 if self.entries.len() == CACHE_SIZE {
309- let (_, old) = self.entries.remove(0);
311+ let i = self
312+ .entries
313+ .iter()
314+ .position(|(_, import)| !busy.contains(&import.id))
315+ .ok_or_else(|| Error::Invalid("DMA-BUF import cache is full of in-flight imports".into()))?;
316+ let (_, old) = self.entries.remove(i);
310317 old.destroy(gpu.device());
311318 }
312- let import = Import::new(gpu, src)?;
319+ self.next_id += 1;
320+ let import = Import::new(gpu, src, self.next_id)?;
313321 self.count += 1;
314322 self.entries.push((key, import));
315323 }
316324 }
317325 self.entries
318326 .last()
319- .map(|(_, import)| import.image)
327+ .map(|(_, import)| (import.image, import.id))
320328 .ok_or_else(|| Error::Invalid("DMA-BUF import cache".into()))
321329 }
322330
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,7 +289,7 @@ impl H264EncodeSession {
289289
290290 /// Encodes one picture from a DMA-BUF: BGRx or RGBx box-downscaled to the encoder size, or NV12 of the encoder size.
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)
@@ -301,7 +301,7 @@ impl H264EncodeSession {
301301 self.enc.import_count()
302302 }
303303
304- fn encode_uploaded(&mut self, pic: &H264Picture) -> Result<Vec<u8>, Error> {
304+ fn encode_uploaded(&mut self, pic: &H264Picture) -> Result<Option<Vec<u8>>, Error> {
305305 let extent = self.enc.extent;
306306
307307 let primary = if pic.idr {
@@ -313,7 +313,7 @@ impl H264EncodeSession {
313313 picture_resource(self.enc.dpb[0].view, extent),
314314 picture_resource(self.enc.dpb[1].view, extent),
315315 ];
316- let src_pr = picture_resource(self.enc.src.view, extent);
316+ let src_pr = picture_resource(self.enc.src_view(), extent);
317317
318318 let new_std = reference_info(primary, pic.frame_num, pic.poc);
319319 let ref_std = pic
@@ -400,7 +400,7 @@ impl H264EncodeSession {
400400 .build();
401401
402402 let encode = vk::VideoEncodeInfoKHR::builder()
403- .dst_buffer(self.enc.bitstream.buffer)
403+ .dst_buffer(self.enc.bitstream_buffer())
404404 .dst_buffer_offset(0)
405405 .dst_buffer_range(self.enc.bitstream_len)
406406 .src_picture_resource(src_pr)
@@ -412,7 +412,39 @@ impl H264EncodeSession {
412412 let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1);
413413 let mut chain = RateChain::new(self.enc.rate, self.enc.fps);
414414 self.enc
415- .run(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)
415+ .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)
416+ }
417+
418+ /// Encodes one picture synchronously and returns its coded bytes.
419+ pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &H264Picture) -> Result<Vec<u8>, Error> {
420+ self.submit(y, uv, pic)?;
421+ self.enc.flush_last()
422+ }
423+
424+ /// Encodes one picture synchronously and returns its coded bytes.
425+ pub fn encode_rgb(
426+ &mut self,
427+ rgb: &[u8],
428+ src_width: u32,
429+ src_height: u32,
430+ stride_bytes: u32,
431+ bgr: bool,
432+ pic: &H264Picture,
433+ ) -> Result<Vec<u8>, Error> {
434+ self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?;
435+ self.enc.flush_last()
436+ }
437+
438+ #[cfg(target_os = "linux")]
439+ /// Encodes one picture synchronously and returns its coded bytes.
440+ pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H264Picture) -> Result<Vec<u8>, Error> {
441+ self.submit_dmabuf(src, pic)?;
442+ self.enc.flush_last()
443+ }
444+
445+ /// Waits for queued pictures and returns their coded bytes in order.
446+ pub fn flush(&mut self) -> Result<Vec<Vec<u8>>, Error> {
447+ self.enc.flush()
416448 }
417449
418450 /// 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,7 +317,7 @@ impl H265EncodeSession {
317317
318318 /// Encodes one picture from a DMA-BUF: BGRx or RGBx box-downscaled to the encoder size, or NV12 or P010 of the encoder size.
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)
@@ -329,7 +329,7 @@ impl H265EncodeSession {
329329 self.enc.import_count()
330330 }
331331
332- fn encode_uploaded(&mut self, pic: &H265Picture) -> Result<Vec<u8>, Error> {
332+ fn encode_uploaded(&mut self, pic: &H265Picture) -> Result<Option<Vec<u8>>, Error> {
333333 let extent = self.enc.extent;
334334
335335 let primary = if pic.idr {
@@ -341,7 +341,7 @@ impl H265EncodeSession {
341341 picture_resource(self.enc.dpb[0].view, extent),
342342 picture_resource(self.enc.dpb[1].view, extent),
343343 ];
344- let src_pr = picture_resource(self.enc.src.view, extent);
344+ let src_pr = picture_resource(self.enc.src_view(), extent);
345345
346346 let new_std = reference_info(primary, pic.poc);
347347 let ref_std = pic
@@ -431,7 +431,7 @@ impl H265EncodeSession {
431431 .build();
432432
433433 let encode = vk::VideoEncodeInfoKHR::builder()
434- .dst_buffer(self.enc.bitstream.buffer)
434+ .dst_buffer(self.enc.bitstream_buffer())
435435 .dst_buffer_offset(0)
436436 .dst_buffer_range(self.enc.bitstream_len)
437437 .src_picture_resource(src_pr)
@@ -443,7 +443,45 @@ impl H265EncodeSession {
443443 let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1);
444444 let mut chain = RateChain::new(self.enc.rate, self.enc.fps);
445445 self.enc
446- .run(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)
446+ .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)
447+ }
448+
449+ /// Encodes one picture synchronously and returns its coded bytes.
450+ pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &H265Picture) -> Result<Vec<u8>, Error> {
451+ self.submit(y, uv, pic)?;
452+ self.enc.flush_last()
453+ }
454+
455+ /// Encodes one picture synchronously and returns its coded bytes.
456+ pub fn encode_16(&mut self, y: &[u16], uv: &[u16], pic: &H265Picture) -> Result<Vec<u8>, Error> {
457+ self.submit_16(y, uv, pic)?;
458+ self.enc.flush_last()
459+ }
460+
461+ /// Encodes one picture synchronously and returns its coded bytes.
462+ pub fn encode_rgb(
463+ &mut self,
464+ rgb: &[u8],
465+ src_width: u32,
466+ src_height: u32,
467+ stride_bytes: u32,
468+ bgr: bool,
469+ pic: &H265Picture,
470+ ) -> Result<Vec<u8>, Error> {
471+ self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?;
472+ self.enc.flush_last()
473+ }
474+
475+ #[cfg(target_os = "linux")]
476+ /// Encodes one picture synchronously and returns its coded bytes.
477+ pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H265Picture) -> Result<Vec<u8>, Error> {
478+ self.submit_dmabuf(src, pic)?;
479+ self.enc.flush_last()
480+ }
481+
482+ /// Waits for queued pictures and returns their coded bytes in order.
483+ pub fn flush(&mut self) -> Result<Vec<Vec<u8>>, Error> {
484+ self.enc.flush()
447485 }
448486
449487 /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change.
shims/vk-video-ffi/src/session.rsmodified+270 -134
@@ -1,3 +1,5 @@
1+use std::collections::VecDeque;
2+
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,105 +704,145 @@ 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>,
722+ rgb: RgbConverter,
723+ bitstream: Buffer,
724+ main: Lane,
725+ upload: Lane,
726+ ready: vk::Semaphore,
727+ encoded: vk::Semaphore,
706728 #[cfg(target_os = "linux")]
707- pub(crate) imports: ImportCache,
708- pub(crate) bitstream: Buffer,
709- query: vk::QueryPool,
729+ import: Option<u64>,
710730 }
711731
712-impl Encoder {
713- pub(crate) fn new(
714- vs: VideoSession,
732+impl Slot {
733+ fn new(
734+ vs: &mut VideoSession,
715735 profile: &vk::VideoProfileInfoKHR,
716736 upload_family: u32,
717737 input: (u32, u32),
718738 extent: vk::Extent2D,
719- setting: (RateControl, (u32, u32)),
720- size_align: u64,
739+ frame_bytes: u64,
740+ bitstream_len: u64,
721741 ) -> Result<Self, Error> {
722742 let gpu = vs.gpu.clone();
723- let main = Lane::new(&gpu, vs.family)?;
724- let upload = Lane::new(&gpu, upload_family)?;
725- let mut e = Encoder {
726- vs,
727- main,
728- upload,
729- input: (input.0 as usize, input.1 as usize),
730- extent,
731- rate: setting.0,
732- fps: setting.1,
733- applied: setting,
734- dirty: false,
735- coded: false,
736- bitstream_len: 0,
737- dpb: Default::default(),
738- src: Default::default(),
739- staging: Default::default(),
740- rgb: None,
741- #[cfg(target_os = "linux")]
742- imports: Default::default(),
743- bitstream: Default::default(),
744- query: Default::default(),
745- };
746- let bytes = bytes_per_sample(e.vs.format) as u64;
747- let frame_bytes = extent.width as u64 * extent.height as u64 * 3 / 2 * bytes;
748- let usage = vk::ImageUsageFlags::VIDEO_ENCODE_DPB_KHR;
743+ let d = gpu.device();
744+ let family = vs.family;
749745 let mut list = vk::VideoProfileListInfoKHR::builder()
750746 .profiles(std::slice::from_ref(profile))
751747 .build();
752- let family = e.vs.family;
753- e.dpb[0] = e.vs.image(extent, usage, usage, &[family], &mut list)?;
754- e.dpb[1] = e.vs.image(extent, usage, usage, &[family], &mut list)?;
755748 let shared = if upload_family == family {
756749 vec![family]
757750 } else {
758751 vec![upload_family, family]
759752 };
760- e.src = e.vs.image(
753+ let src = vs.image(
761754 extent,
762755 vk::ImageUsageFlags::VIDEO_ENCODE_SRC_KHR | vk::ImageUsageFlags::TRANSFER_DST,
763756 vk::ImageUsageFlags::VIDEO_ENCODE_SRC_KHR | vk::ImageUsageFlags::TRANSFER_DST,
764757 &shared,
765758 &mut list,
766759 )?;
767- e.staging = e.vs.buffer(
760+ let staging = vs.buffer(
768761 frame_bytes,
769762 vk::BufferUsageFlags::TRANSFER_SRC | vk::BufferUsageFlags::STORAGE_BUFFER,
770763 &[vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT],
771764 None,
772765 )?;
773- e.rgb = Some(RgbConverter::new(
774- &gpu,
775- input,
776- (extent.width, extent.height),
777- e.staging.buffer,
778- )?);
779- e.bitstream_len = align_u64(frame_bytes, size_align);
780- e.bitstream = e.vs.buffer(
781- e.bitstream_len,
766+ let rgb = RgbConverter::new(&gpu, input, (extent.width, extent.height), staging.buffer)?;
767+ let bitstream = vs.buffer(
768+ bitstream_len,
782769 vk::BufferUsageFlags::VIDEO_ENCODE_DST_KHR,
783770 &[vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT],
784771 Some(&mut list),
785772 )?;
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+ }
786786
787+ fn retire(&mut self) {
788+ #[cfg(target_os = "linux")]
789+ {
790+ self.import = None;
791+ }
792+ }
793+}
794+
795+/// Encode session plumbing shared by H.264, H.265 and AV1: DPB, picture slots, bitstream and upload path.
796+pub(crate) struct Encoder {
797+ pub(crate) vs: VideoSession,
798+ pub(crate) input: (usize, usize),
799+ pub(crate) extent: vk::Extent2D,
800+ pub(crate) rate: RateControl,
801+ pub(crate) fps: (u32, u32),
802+ pub(crate) applied: (RateControl, (u32, u32)),
803+ pub(crate) dirty: bool,
804+ pub(crate) coded: bool,
805+ pub(crate) bitstream_len: u64,
806+ pub(crate) dpb: [Image; DPB_SLOTS],
807+ #[cfg(target_os = "linux")]
808+ pub(crate) imports: ImportCache,
809+ slots: [Slot; FLIGHT],
810+ cur: usize,
811+ next: usize,
812+ last: Option<usize>,
813+ pending: VecDeque<usize>,
814+ query: vk::QueryPool,
815+}
816+
817+impl Encoder {
818+ pub(crate) fn new(
819+ mut vs: VideoSession,
820+ profile: &vk::VideoProfileInfoKHR,
821+ upload_family: u32,
822+ input: (u32, u32),
823+ extent: vk::Extent2D,
824+ setting: (RateControl, (u32, u32)),
825+ size_align: u64,
826+ ) -> Result<Self, Error> {
827+ let gpu = vs.gpu.clone();
787828 let d = gpu.device();
829+ let bytes = bytes_per_sample(vs.format) as u64;
830+ let frame_bytes = extent.width as u64 * extent.height as u64 * 3 / 2 * bytes;
831+ let bitstream_len = align_u64(frame_bytes, size_align);
832+ let usage = vk::ImageUsageFlags::VIDEO_ENCODE_DPB_KHR;
833+ let mut list = vk::VideoProfileListInfoKHR::builder()
834+ .profiles(std::slice::from_ref(profile))
835+ .build();
836+ let family = vs.family;
837+ let dpb = [
838+ vs.image(extent, usage, usage, &[family], &mut list)?,
839+ vs.image(extent, usage, usage, &[family], &mut list)?,
840+ ];
841+ let slots = [
842+ Slot::new(&mut vs, profile, upload_family, input, extent, frame_bytes, bitstream_len)?,
843+ Slot::new(&mut vs, profile, upload_family, input, extent, frame_bytes, bitstream_len)?,
844+ ];
845+
788846 let mut feedback = vk::QueryPoolVideoEncodeFeedbackCreateInfoKHR::builder()
789847 .encode_feedback_flags(
790848 vk::VideoEncodeFeedbackFlagsKHR::BITSTREAM_BUFFER_OFFSET
@@ -794,28 +852,53 @@ impl Encoder {
794852 let mut prof = *profile;
795853 let query_info = vk::QueryPoolCreateInfo::builder()
796854 .query_type(vk::QueryType::VIDEO_ENCODE_FEEDBACK_KHR)
797- .query_count(1)
855+ .query_count(FLIGHT as u32)
798856 .push_next(&mut feedback)
799857 .push_next(&mut prof)
800858 .build();
801- e.query = unsafe { vk(d.create_query_pool(&query_info, None), "vkCreateQueryPool")? };
859+ let query = unsafe { vk(d.create_query_pool(&query_info, None), "vkCreateQueryPool")? };
802860
803- e.main.begin()?;
861+ let e = Encoder {
862+ vs,
863+ input: (input.0 as usize, input.1 as usize),
864+ extent,
865+ rate: setting.0,
866+ fps: setting.1,
867+ applied: setting,
868+ dirty: false,
869+ coded: false,
870+ bitstream_len,
871+ dpb,
872+ #[cfg(target_os = "linux")]
873+ imports: Default::default(),
874+ slots,
875+ cur: 0,
876+ next: 0,
877+ last: None,
878+ pending: VecDeque::new(),
879+ query,
880+ };
881+ let lane = &e.slots[0].main;
882+ lane.begin()?;
804883 for img in &e.dpb {
805- init_barrier(
806- d,
807- e.main.cb,
808- img.image,
809- vk::ImageLayout::VIDEO_ENCODE_DPB_KHR,
810- );
884+ init_barrier(d, lane.cb, img.image, vk::ImageLayout::VIDEO_ENCODE_DPB_KHR);
811885 }
812- e.main.end()?;
813- e.main.submit()?;
886+ lane.end()?;
887+ lane.submit()?;
814888 Ok(e)
815889 }
816890
817- pub(crate) fn staging_ptr(&self) -> Result<*mut u8, Error> {
818- self.staging
891+ pub(crate) fn src_view(&self) -> vk::ImageView {
892+ self.slots[self.cur].src.view
893+ }
894+
895+ pub(crate) fn bitstream_buffer(&self) -> vk::Buffer {
896+ self.slots[self.cur].bitstream.buffer
897+ }
898+
899+ fn staging_ptr(&self) -> Result<*mut u8, Error> {
900+ self.slots[self.cur]
901+ .staging
819902 .ptr
820903 .ok_or_else(|| Error::Invalid("staging buffer not mapped".into()))
821904 }
@@ -848,6 +931,8 @@ impl Encoder {
848931 _ => {}
849932 }
850933 let gpu = self.vs.gpu.clone();
934+ let k = self.next;
935+ self.cur = k;
851936 match input {
852937 Input::Nv12 { y, uv } => {
853938 let staging =
@@ -866,42 +951,36 @@ impl Encoder {
866951 stride,
867952 ..
868953 } => {
869- let rgb = self
870- .rgb
871- .as_mut()
872- .ok_or_else(|| Error::Invalid("RGB converter not created".into()))?;
954+ let rgb = &mut self.slots[k].rgb;
873955 rgb.reserve(&gpu, width, height)?;
874956 rgb.load(data, stride);
875957 }
876958 #[cfg(target_os = "linux")]
877959 Input::DmaBuf { width, height, .. } => {
878- let rgb = self
879- .rgb
880- .as_mut()
881- .ok_or_else(|| Error::Invalid("RGB converter not created".into()))?;
882- rgb.reserve(&gpu, width, height)?;
960+ self.slots[k].rgb.reserve(&gpu, width, height)?;
883961 }
884962 }
885963
886964 let d = gpu.device();
887- let cb = self.upload.cb;
965+ let slot = &self.slots[k];
966+ let cb = slot.upload.cb;
888967 let luma = (aw * ah * bytes) as u64;
889968 let copies = [
890969 copy_region(0, PLANE_0, aw as u32, ah as u32),
891970 copy_region(luma, PLANE_1, (aw / 2) as u32, (ah / 2) as u32),
892971 ];
893- self.upload.begin()?;
972+ slot.upload.begin()?;
894973 unsafe {
895- if let (Some(bgr), Some(rgb)) = (input.bgr(), &self.rgb) {
974+ if let Some(bgr) = input.bgr() {
896975 if let Some(image) = input.source_image() {
897- rgb.record_import(d, cb, image, self.upload.family);
976+ slot.rgb.record_import(d, cb, image, slot.upload.family);
898977 }
899- rgb.record(d, cb, bgr);
978+ slot.rgb.record(d, cb, bgr);
900979 }
901980 barrier(
902981 d,
903982 cb,
904- self.src.image,
983+ slot.src.image,
905984 (
906985 vk::ImageLayout::UNDEFINED,
907986 vk::PipelineStageFlags2::NONE,
@@ -915,15 +994,15 @@ impl Encoder {
915994 );
916995 d.cmd_copy_buffer_to_image(
917996 cb,
918- self.staging.buffer,
919- self.src.image,
997+ slot.staging.buffer,
998+ slot.src.image,
920999 vk::ImageLayout::TRANSFER_DST_OPTIMAL,
9211000 &copies,
9221001 );
9231002 barrier(
9241003 d,
9251004 cb,
926- self.src.image,
1005+ slot.src.image,
9271006 (
9281007 vk::ImageLayout::TRANSFER_DST_OPTIMAL,
9291008 vk::PipelineStageFlags2::COPY,
@@ -936,8 +1015,8 @@ impl Encoder {
9361015 ),
9371016 );
9381017 }
939- self.upload.end()?;
940- self.upload.submit()
1018+ slot.upload.end()?;
1019+ slot.upload.submit_with(&[], &[slot.ready])
9411020 }
9421021
9431022 #[cfg(target_os = "linux")]
@@ -948,8 +1027,10 @@ impl Encoder {
9481027 DmaBufFormat::Bgrx | DmaBufFormat::Rgbx => check_size(self.input, (width, height))?,
9491028 DmaBufFormat::Nv12 | DmaBufFormat::P010 => self.check_planar(src)?,
9501029 }
951- let image = self.imports.get(&gpu, src)?;
952- match src.format {
1030+ let busy: Vec<u64> = self.slots.iter().filter_map(|s| s.import).collect();
1031+ let (image, id) = self.imports.get(&gpu, src, &busy)?;
1032+ let k = self.next;
1033+ let result = match src.format {
9531034 DmaBufFormat::Bgrx | DmaBufFormat::Rgbx => self.upload(Input::DmaBuf {
9541035 image,
9551036 width,
@@ -957,7 +1038,11 @@ impl Encoder {
9571038 bgr: src.format == DmaBufFormat::Bgrx,
9581039 }),
9591040 DmaBufFormat::Nv12 | DmaBufFormat::P010 => self.copy_planes(image),
1041+ };
1042+ if result.is_ok() {
1043+ self.slots[k].import = Some(id);
9601044 }
1045+ result
9611046 }
9621047
9631048 #[cfg(target_os = "linux")]
@@ -978,17 +1063,20 @@ impl Encoder {
9781063 fn copy_planes(&mut self, image: vk::Image) -> Result<(), Error> {
9791064 let gpu = self.vs.gpu.clone();
9801065 let d = gpu.device();
981- let cb = self.upload.cb;
1066+ let k = self.next;
1067+ self.cur = k;
1068+ let slot = &self.slots[k];
1069+ let cb = slot.upload.cb;
9821070 let (w, h) = (self.input.0 as u32, self.input.1 as u32);
9831071 let aspects = [PLANE_0, PLANE_1];
9841072 let regions = [plane_copy(PLANE_0, w, h), plane_copy(PLANE_1, w / 2, h / 2)];
985- self.upload.begin()?;
986- acquire(d, cb, image, &aspects, self.upload.family);
1073+ slot.upload.begin()?;
1074+ acquire(d, cb, image, &aspects, slot.upload.family);
9871075 unsafe {
9881076 barrier(
9891077 d,
9901078 cb,
991- self.src.image,
1079+ slot.src.image,
9921080 (
9931081 vk::ImageLayout::UNDEFINED,
9941082 vk::PipelineStageFlags2::NONE,
@@ -1004,14 +1092,14 @@ impl Encoder {
10041092 cb,
10051093 image,
10061094 vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
1007- self.src.image,
1095+ slot.src.image,
10081096 vk::ImageLayout::TRANSFER_DST_OPTIMAL,
10091097 &regions,
10101098 );
10111099 barrier(
10121100 d,
10131101 cb,
1014- self.src.image,
1102+ slot.src.image,
10151103 (
10161104 vk::ImageLayout::TRANSFER_DST_OPTIMAL,
10171105 vk::PipelineStageFlags2::COPY,
@@ -1025,8 +1113,8 @@ impl Encoder {
10251113 );
10261114 }
10271115 release(d, cb, image, &aspects);
1028- self.upload.end()?;
1029- self.upload.submit()
1116+ slot.upload.end()?;
1117+ slot.upload.submit_with(&[], &[slot.ready])
10301118 }
10311119
10321120 #[cfg(target_os = "linux")]
@@ -1034,26 +1122,29 @@ impl Encoder {
10341122 self.imports.count
10351123 }
10361124
1037- /// Records one encode with its rate control chains, submits it and returns the coded bytes.
1038- pub(crate) fn run(
1125+ /// Records the encode of the uploaded slot and submits it without waiting. Returns the oldest picture once FLIGHT are queued.
1126+ pub(crate) fn submit(
10391127 &mut self,
10401128 begin_slots: &[vk::VideoReferenceSlotInfoKHR],
10411129 applied: &mut vk::VideoEncodeRateControlInfoKHR,
10421130 chain: &mut vk::VideoEncodeRateControlInfoKHR,
10431131 encode: &vk::VideoEncodeInfoKHR,
1044- ) -> Result<Vec<u8>, Error> {
1132+ ) -> Result<Option<Vec<u8>>, Error> {
10451133 let gpu = self.vs.gpu.clone();
10461134 let d = gpu.device();
1047- let cb = self.main.cb;
1135+ let k = self.cur;
1136+ let slot = &self.slots[k];
1137+ let cb = slot.main.cb;
1138+ let query = k as u32;
10481139 let mut quality = vk::VideoEncodeQualityLevelInfoKHR::builder()
10491140 .quality_level(0)
10501141 .build();
10511142 let reset = !self.coded;
10521143 let update = reset || self.dirty;
10531144
1054- self.main.begin()?;
1145+ slot.main.begin()?;
10551146 unsafe {
1056- d.cmd_reset_query_pool(cb, self.query, 0, 1);
1147+ d.cmd_reset_query_pool(cb, self.query, query, 1);
10571148 let begin = vk::VideoBeginCodingInfoKHR::builder()
10581149 .video_session(self.vs.session)
10591150 .video_session_parameters(self.vs.params)
@@ -1081,27 +1172,67 @@ impl Encoder {
10811172 d.cmd_control_video_coding_khr(cb, &control);
10821173 }
10831174
1084- d.cmd_begin_query(cb, self.query, 0, vk::QueryControlFlags::empty());
1175+ d.cmd_begin_query(cb, self.query, query, vk::QueryControlFlags::empty());
10851176 d.cmd_encode_video_khr(cb, encode);
1086- d.cmd_end_query(cb, self.query, 0);
1177+ d.cmd_end_query(cb, self.query, query);
10871178 let end = vk::VideoEndCodingInfoKHR::builder().build();
10881179 d.cmd_end_video_coding_khr(cb, &end);
10891180 }
1090- self.main.end()?;
1091- self.main.submit()?;
1181+ slot.main.end()?;
1182+ let mut wait = vec![slot.ready];
1183+ if let Some(p) = self.last {
1184+ wait.push(self.slots[p].encoded);
1185+ }
1186+ slot.main.submit_with(&wait, &[slot.encoded])?;
1187+
1188+ self.last = Some(k);
1189+ self.next = k ^ 1;
10921190 self.coded = true;
10931191 self.applied = (self.rate, self.fps);
10941192 self.dirty = false;
1095- self.read_bitstream()
1193+ self.pending.push_back(k);
1194+ if self.pending.len() < FLIGHT {
1195+ return Ok(None);
1196+ }
1197+ let oldest = self
1198+ .pending
1199+ .pop_front()
1200+ .ok_or_else(|| Error::Invalid("no picture in flight".into()))?;
1201+ self.finish(oldest).map(Some)
1202+ }
1203+
1204+ /// Waits for every queued picture and returns their bytes in submission order.
1205+ pub(crate) fn flush(&mut self) -> Result<Vec<Vec<u8>>, Error> {
1206+ let mut out = Vec::new();
1207+ while let Some(k) = self.pending.pop_front() {
1208+ out.push(self.finish(k)?);
1209+ }
1210+ Ok(out)
1211+ }
1212+
1213+ /// Flushes and returns the last picture, for synchronous use where one picture is queued per call.
1214+ pub(crate) fn flush_last(&mut self) -> Result<Vec<u8>, Error> {
1215+ self.flush()?
1216+ .pop()
1217+ .ok_or_else(|| Error::Invalid("no picture encoded".into()))
10961218 }
10971219
1098- fn read_bitstream(&self) -> Result<Vec<u8>, Error> {
1220+ fn finish(&mut self, k: usize) -> Result<Vec<u8>, Error> {
1221+ let slot = &self.slots[k];
1222+ slot.main.wait()?;
1223+ slot.upload.wait()?;
1224+ let bytes = self.read_bitstream(k)?;
1225+ self.slots[k].retire();
1226+ Ok(bytes)
1227+ }
1228+
1229+ fn read_bitstream(&self, k: usize) -> Result<Vec<u8>, Error> {
10991230 let mut feedback = [0u8; 8];
11001231 unsafe {
11011232 vk(
11021233 self.vs.gpu.device().get_query_pool_results(
11031234 self.query,
1104- 0,
1235+ k as u32,
11051236 1,
11061237 &mut feedback,
11071238 8,
@@ -1119,7 +1250,7 @@ impl Encoder {
11191250 "encoded size exceeds bitstream buffer".into(),
11201251 ));
11211252 }
1122- let ptr = self
1253+ let ptr = self.slots[k]
11231254 .bitstream
11241255 .ptr
11251256 .ok_or_else(|| Error::Invalid("bitstream buffer not mapped".into()))?;
@@ -1136,16 +1267,21 @@ impl Drop for Encoder {
11361267 let _ = d.device_wait_idle();
11371268 d.destroy_query_pool(self.query, None);
11381269 }
1139- for img in self.dpb.iter().chain(std::iter::once(&self.src)) {
1270+ for img in &self.dpb {
11401271 img.destroy(d);
11411272 }
11421273 #[cfg(target_os = "linux")]
11431274 self.imports.destroy(d);
1144- if let Some(rgb) = &self.rgb {
1145- rgb.destroy(d);
1275+ for slot in self.slots.iter_mut() {
1276+ unsafe {
1277+ d.destroy_semaphore(slot.ready, None);
1278+ d.destroy_semaphore(slot.encoded, None);
1279+ }
1280+ slot.src.destroy(d);
1281+ slot.rgb.destroy(d);
1282+ slot.staging.destroy(d);
1283+ slot.bitstream.destroy(d);
11461284 }
1147- self.staging.destroy(d);
1148- self.bitstream.destroy(d);
11491285 }
11501286 }
11511287