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;
7 use ec_vk::{DmaBuf, DmaBufFormat, DmaBufPlane};7 use ec_vk::{DmaBuf, DmaBufFormat, DmaBufPlane};
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};
@@ -257,6 +258,23 @@ pub struct DmaBufFrame<'a> {
257 pub order: RgbOrder,258 pub order: RgbOrder,
258 }259 }
259 260
261+/// One picture for [`HwEncoder::submit`].
262+#[derive(Debug, Clone, Copy)]
263+pub enum EncodeInput<'a> {
264+ /// 8-bit I420.
265+ I420(&'a I420),
266+ /// 10-bit I420 of a 10-bit encoder (H.265 and AV1).
267+ I420_16(&'a I420_16),
268+ /// Packed RGB, box-downscaled to the encoder size.
269+ Rgb(&'a RgbFrame<'a>),
270+ /// DMA-BUF of packed RGB, Vulkan only.
271+ #[cfg(target_os = "linux")]
272+ DmaBuf(&'a DmaBufFrame<'a>),
273+ /// DMA-BUF of NV12 or P010 at the encoder size, Vulkan only.
274+ #[cfg(target_os = "linux")]
275+ DmaBufYuv(&'a DmaBufYuvFrame<'a>),
276+}
277+
260 #[cfg(target_os = "linux")]278 #[cfg(target_os = "linux")]
261 fn rgb_to_i420(frame: &RgbFrame, (w, h): (usize, usize)) -> Result<I420> {279 fn rgb_to_i420(frame: &RgbFrame, (w, h): (usize, usize)) -> Result<I420> {
262 let (sw, sh, stride) = (280 let (sw, sh, stride) = (
@@ -315,7 +333,103 @@ enum VkEncoder {
315 Av1(ec_vk::Av1Encoder),333 Av1(ec_vk::Av1Encoder),
316 }334 }
317 335
336+fn stamp(pending: &mut VecDeque<i64>, coded: ec_vk::CodedFrame) -> CodedFrame {
337+ CodedFrame {
338+ data: coded.data,
339+ timestamp: pending.pop_front().unwrap_or_default(),
340+ is_keyframe: coded.keyframe,
341+ }
342+}
343+
318 impl VkEncoder {344 impl VkEncoder {
345+ fn submit(
346+ &mut self,
347+ input: EncodeInput,
348+ force_keyframe: bool,
349+ ) -> std::result::Result<Option<ec_vk::CodedFrame>, ec_vk::Error> {
350+ match input {
351+ EncodeInput::I420(frame) => {
352+ let (y, u, v) = (&frame.y, &frame.u, &frame.v);
353+ match self {
354+ VkEncoder::H264(e) => e.submit(y, u, v, force_keyframe),
355+ VkEncoder::H265(e) => e.submit(y, u, v, force_keyframe),
356+ VkEncoder::Av1(e) => e.submit(y, u, v, force_keyframe),
357+ }
358+ }
359+ EncodeInput::I420_16(frame) => {
360+ let (y, u, v) = (&frame.y, &frame.u, &frame.v);
361+ match self {
362+ VkEncoder::H264(_) => Err(ec_vk::Error::Unsupported("10-bit H.264 encode".into())),
363+ VkEncoder::H265(e) => e.submit_16(y, u, v, force_keyframe),
364+ VkEncoder::Av1(e) => e.submit_16(y, u, v, force_keyframe),
365+ }
366+ }
367+ EncodeInput::Rgb(frame) => {
368+ let bgr = frame.order == RgbOrder::Bgra;
369+ let (data, sw, sh, stride) = (frame.data, frame.width, frame.height, frame.stride);
370+ match self {
371+ VkEncoder::H264(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe),
372+ VkEncoder::H265(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe),
373+ VkEncoder::Av1(e) => e.submit_rgb(data, sw, sh, stride, bgr, force_keyframe),
374+ }
375+ }
376+ #[cfg(target_os = "linux")]
377+ EncodeInput::DmaBuf(frame) => {
378+ let planes = [DmaBufPlane {
379+ fd: 0,
380+ offset: frame.offset,
381+ pitch: frame.stride,
382+ }];
383+ let src = DmaBuf {
384+ fds: std::slice::from_ref(&frame.fd),
385+ planes: &planes,
386+ width: frame.width,
387+ height: frame.height,
388+ modifier: frame.modifier,
389+ format: if frame.order == RgbOrder::Bgra {
390+ DmaBufFormat::Bgrx
391+ } else {
392+ DmaBufFormat::Rgbx
393+ },
394+ };
395+ self.submit_dma(&src, force_keyframe)
396+ }
397+ #[cfg(target_os = "linux")]
398+ EncodeInput::DmaBufYuv(frame) => {
399+ let src = DmaBuf {
400+ fds: frame.fds,
401+ planes: &frame.planes,
402+ width: frame.width,
403+ height: frame.height,
404+ modifier: frame.modifier,
405+ format: frame.format,
406+ };
407+ self.submit_dma(&src, force_keyframe)
408+ }
409+ }
410+ }
411+
412+ #[cfg(target_os = "linux")]
413+ fn submit_dma(
414+ &mut self,
415+ src: &DmaBuf,
416+ force_keyframe: bool,
417+ ) -> std::result::Result<Option<ec_vk::CodedFrame>, ec_vk::Error> {
418+ match self {
419+ VkEncoder::H264(e) => e.submit_dmabuf(src, force_keyframe),
420+ VkEncoder::H265(e) => e.submit_dmabuf(src, force_keyframe),
421+ VkEncoder::Av1(e) => e.submit_dmabuf(src, force_keyframe),
422+ }
423+ }
424+
425+ fn flush(&mut self) -> std::result::Result<Vec<ec_vk::CodedFrame>, ec_vk::Error> {
426+ match self {
427+ VkEncoder::H264(e) => e.flush(),
428+ VkEncoder::H265(e) => e.flush(),
429+ VkEncoder::Av1(e) => e.flush(),
430+ }
431+ }
432+
319 fn encode(433 fn encode(
320 &mut self,434 &mut self,
321 frame: &I420,435 frame: &I420,
@@ -395,6 +509,7 @@ pub struct HwEncoder {
395 config: EncoderConfig,509 config: EncoderConfig,
396 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]510 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
397 size: (usize, usize),511 size: (usize, usize),
512+ pending: VecDeque<i64>,
398 }513 }
399 514
400 impl HwEncoder {515 impl HwEncoder {
@@ -415,6 +530,7 @@ impl HwEncoder {
415 born_epoch,530 born_epoch,
416 config,531 config,
417 size,532 size,
533+ pending: VecDeque::new(),
418 });534 });
419 }535 }
420 Err(e) => reasons.push(format!("{backend:?}: {e}")),536 Err(e) => reasons.push(format!("{backend:?}: {e}")),
@@ -454,8 +570,55 @@ impl HwEncoder {
454 Ok(())570 Ok(())
455 }571 }
456 572
573+ /// Submit one picture without waiting; the oldest coded picture comes back once two are in flight. Call [`HwEncoder::flush`] at the end.
574+ pub fn submit(&mut self, input: EncodeInput, meta: FrameMetadata) -> Result<Option<CodedFrame>> {
575+ match &mut self.inner {
576+ EncInner::Vk(enc) => {
577+ vk_session_alive(self.born_epoch)?;
578+ self.pending.push_back(meta.timestamp);
579+ let out = enc.submit(input, meta.force_keyframe)?;
580+ Ok(out.map(|coded| stamp(&mut self.pending, coded)))
581+ }
582+ #[cfg(target_os = "linux")]
583+ EncInner::Va(enc) => match input {
584+ EncodeInput::I420(frame) => enc.submit(frame, meta),
585+ EncodeInput::I420_16(frame) => enc.submit_16(frame, meta),
586+ EncodeInput::Rgb(frame) => enc.submit(&rgb_to_i420(frame, self.size)?, meta),
587+ EncodeInput::DmaBuf(_) | EncodeInput::DmaBufYuv(_) => Err(Error::unsupported(
588+ "DMA-BUF encode",
589+ "the VA-API backend has no DMA-BUF input here",
590+ )),
591+ },
592+ }
593+ }
594+
595+ /// Wait for every submitted picture and return them, oldest first.
596+ pub fn flush(&mut self) -> Result<Vec<CodedFrame>> {
597+ match &mut self.inner {
598+ EncInner::Vk(enc) => {
599+ vk_session_alive(self.born_epoch)?;
600+ let frames = enc.flush()?;
601+ Ok(frames
602+ .into_iter()
603+ .map(|coded| stamp(&mut self.pending, coded))
604+ .collect())
605+ }
606+ #[cfg(target_os = "linux")]
607+ EncInner::Va(enc) => enc.flush(),
608+ }
609+ }
610+
611+ fn idle(&self) -> Result<()> {
612+ if self.pending.is_empty() {
613+ Ok(())
614+ } else {
615+ Err(Error::config("pipelined frames pending; call flush first"))
616+ }
617+ }
618+
457 /// Encode one frame; `meta.force_keyframe` starts a new GOP.619 /// Encode one frame; `meta.force_keyframe` starts a new GOP.
458 pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> {620 pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> {
621+ self.idle()?;
459 match &mut self.inner {622 match &mut self.inner {
460 EncInner::Vk(enc) => {623 EncInner::Vk(enc) => {
461 vk_session_alive(self.born_epoch)?;624 vk_session_alive(self.born_epoch)?;
@@ -473,6 +636,7 @@ impl HwEncoder {
473 636
474 /// Encode one 10-bit frame of a 10-bit encoder (H.265 and AV1), the [`HwEncoder::encode`] of a 10-bit encoder.637 /// Encode one 10-bit frame of a 10-bit encoder (H.265 and AV1), the [`HwEncoder::encode`] of a 10-bit encoder.
475 pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result<CodedFrame> {638 pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result<CodedFrame> {
639+ self.idle()?;
476 match &mut self.inner {640 match &mut self.inner {
477 EncInner::Vk(enc) => {641 EncInner::Vk(enc) => {
478 let coded = enc.encode_16(frame, meta.force_keyframe)?;642 let coded = enc.encode_16(frame, meta.force_keyframe)?;
@@ -489,6 +653,7 @@ impl HwEncoder {
489 653
490 /// 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.654 /// Encode one packed RGB frame of the source size; it is box-downscaled to the encoder size. Vulkan does this and the NV12 conversion on the GPU, VA-API on the CPU.
491 pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result<CodedFrame> {655 pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result<CodedFrame> {
656+ self.idle()?;
492 match &mut self.inner {657 match &mut self.inner {
493 EncInner::Vk(enc) => {658 EncInner::Vk(enc) => {
494 vk_session_alive(self.born_epoch)?;659 vk_session_alive(self.born_epoch)?;
@@ -551,6 +716,7 @@ impl HwEncoder {
551 716
552 #[cfg(target_os = "linux")]717 #[cfg(target_os = "linux")]
553 fn encode_dma(&mut self, src: &DmaBuf, meta: FrameMetadata) -> Result<CodedFrame> {718 fn encode_dma(&mut self, src: &DmaBuf, meta: FrameMetadata) -> Result<CodedFrame> {
719+ self.idle()?;
554 match &mut self.inner {720 match &mut self.inner {
555 EncInner::Vk(enc) => {721 EncInner::Vk(enc) => {
556 vk_session_alive(self.born_epoch)?;722 vk_session_alive(self.born_epoch)?;
crates/ec-hw/src/lib.rsmodified+2 -1
@@ -90,7 +90,8 @@ pub use ec_vk::{DmaBufFormat, DmaBufPlane};
90 #[cfg(target_os = "linux")]90 #[cfg(target_os = "linux")]
91 pub use hw::{DmaBufFrame, DmaBufYuvFrame};91 pub use hw::{DmaBufFrame, DmaBufYuvFrame};
92 pub use hw::{92 pub use hw::{
93- Backend, Capability, Direction, HwDecoder, HwEncoder, RgbFrame, RgbOrder, RgbOutput,93+ Backend, Capability, Direction, EncodeInput, HwDecoder, HwEncoder, RgbFrame, RgbOrder,
94+ RgbOutput,
94 capabilities,95 capabilities,
95 };96 };
96 #[cfg(target_os = "linux")]97 #[cfg(target_os = "linux")]
crates/ec-vk/src/av1.rsmodified+91 -28
@@ -2,7 +2,7 @@ use vk_video_ffi::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref};
2 2
3 #[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,7 +277,7 @@ impl Av1EncodeSession {
277 }277 }
278 /// Encodes one picture from a DMA-BUF: BGRx or RGBx box-downscaled to the encoder size, or NV12 or P010 of the encoder size.278 /// Encodes one picture from a DMA-BUF: BGRx or RGBx box-downscaled to the encoder size, or NV12 or P010 of the encoder size.
279 #[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)
@@ -289,7 +289,7 @@ impl Av1EncodeSession {
289 self.enc.import_count()289 self.enc.import_count()
290 }290 }
291 291
292- fn encode_uploaded(&mut self, pic: &Av1Picture) -> Result<Vec<u8>, Error> {292+ fn encode_uploaded(&mut self, pic: &Av1Picture) -> Result<Option<Vec<u8>>, Error> {
293 let extent = self.enc.extent;293 let extent = self.enc.extent;
294 294
295 let refresh: u8 = if pic.key { 0xff } else { 1 << pic.slot };295 let refresh: u8 = if pic.key { 0xff } else { 1 << pic.slot };
@@ -297,7 +297,7 @@ impl Av1EncodeSession {
297 picture_resource(self.enc.dpb[0].view, extent),297 picture_resource(self.enc.dpb[0].view, extent),
298 picture_resource(self.enc.dpb[1].view, extent),298 picture_resource(self.enc.dpb[1].view, extent),
299 ];299 ];
300- let src_pr = picture_resource(self.enc.src.view, extent);300+ let src_pr = picture_resource(self.enc.src_view(), extent);
301 301
302 let key_of = self.slot_key;302 let key_of = self.slot_key;
303 let mut new_std = zeroed::<vk::video::StdVideoEncodeAV1ReferenceInfo>();303 let mut new_std = zeroed::<vk::video::StdVideoEncodeAV1ReferenceInfo>();
@@ -399,7 +399,7 @@ impl Av1EncodeSession {
399 };399 };
400 400
401 let encode = vk::VideoEncodeInfoKHR::builder()401 let encode = vk::VideoEncodeInfoKHR::builder()
402- .dst_buffer(self.enc.bitstream.buffer)402+ .dst_buffer(self.enc.bitstream_buffer())
403 .dst_buffer_offset(0)403 .dst_buffer_offset(0)
404 .dst_buffer_range(self.enc.bitstream_len)404 .dst_buffer_range(self.enc.bitstream_len)
405 .src_picture_resource(src_pr)405 .src_picture_resource(src_pr)
@@ -412,7 +412,7 @@ impl Av1EncodeSession {
412 let mut chain = RateChain::new(self.enc.rate, self.enc.fps);412 let mut chain = RateChain::new(self.enc.rate, self.enc.fps);
413 let out = self413 let out = self
414 .enc414 .enc
415- .run(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)?;415+ .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)?;
416 for i in 0..DPB_SLOTS {416 for i in 0..DPB_SLOTS {
417 if refresh >> i & 1 == 1 {417 if refresh >> i & 1 == 1 {
418 self.slot_key[i] = pic.key;418 self.slot_key[i] = pic.key;
@@ -426,6 +426,44 @@ impl Av1EncodeSession {
426 Ok(out)426 Ok(out)
427 }427 }
428 428
429+ /// Encodes one picture synchronously and returns its coded bytes.
430+ pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &Av1Picture) -> Result<Vec<u8>, Error> {
431+ self.submit(y, uv, pic)?;
432+ self.enc.flush_last()
433+ }
434+
435+ /// Encodes one picture synchronously and returns its coded bytes.
436+ pub fn encode_16(&mut self, y: &[u16], uv: &[u16], pic: &Av1Picture) -> Result<Vec<u8>, Error> {
437+ self.submit_16(y, uv, pic)?;
438+ self.enc.flush_last()
439+ }
440+
441+ /// Encodes one picture synchronously and returns its coded bytes.
442+ pub fn encode_rgb(
443+ &mut self,
444+ rgb: &[u8],
445+ src_width: u32,
446+ src_height: u32,
447+ stride_bytes: u32,
448+ bgr: bool,
449+ pic: &Av1Picture,
450+ ) -> Result<Vec<u8>, Error> {
451+ self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?;
452+ self.enc.flush_last()
453+ }
454+
455+ #[cfg(target_os = "linux")]
456+ /// Encodes one picture synchronously and returns its coded bytes.
457+ pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &Av1Picture) -> Result<Vec<u8>, Error> {
458+ self.submit_dmabuf(src, pic)?;
459+ self.enc.flush_last()
460+ }
461+
462+ /// Waits for queued pictures and returns their coded bytes in order.
463+ pub fn flush(&mut self) -> Result<Vec<Vec<u8>>, Error> {
464+ self.enc.flush()
465+ }
466+
429 /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change.467 /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change.
430 pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {468 pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {
431 self.enc.set_rate(rate, fps)469 self.enc.set_rate(rate, fps)
shims/vk-video-ffi/src/dmabuf.rsmodified+14 -6
@@ -213,11 +213,12 @@ impl Key {
213 213
214 pub(crate) struct Import {214 pub(crate) struct Import {
215 pub(crate) image: vk::Image,215 pub(crate) image: vk::Image,
216+ id: u64,
216 memories: Vec<vk::DeviceMemory>,217 memories: Vec<vk::DeviceMemory>,
217 }218 }
218 219
219 impl Import {220 impl Import {
220- fn new(gpu: &Gpu, src: &DmaBuf) -> Result<Self, Error> {221+ fn new(gpu: &Gpu, src: &DmaBuf, id: u64) -> Result<Self, Error> {
221 check(gpu)?;222 check(gpu)?;
222 validate(src)?;223 validate(src)?;
223 let d = gpu.device();224 let d = gpu.device();
@@ -271,7 +272,7 @@ impl Import {
271 .build();272 .build();
272 let image = unsafe { vk(d.create_image(&info, None), "vkCreateImage")? };273 let image = unsafe { vk(d.create_image(&info, None), "vkCreateImage")? };
273 match bind(gpu, image, src) {274 match bind(gpu, image, src) {
274- Ok(memories) => Ok(Import { image, memories }),275+ Ok(memories) => Ok(Import { image, id, memories }),
275 Err(e) => {276 Err(e) => {
276 unsafe { d.destroy_image(image, None) };277 unsafe { d.destroy_image(image, None) };
277 Err(e)278 Err(e)
@@ -292,11 +293,12 @@ impl Import {
292 #[derive(Default)]293 #[derive(Default)]
293 pub(crate) struct ImportCache {294 pub(crate) struct ImportCache {
294 entries: Vec<(Key, Import)>,295 entries: Vec<(Key, Import)>,
296+ next_id: u64,
295 pub(crate) count: usize,297 pub(crate) count: usize,
296 }298 }
297 299
298 impl ImportCache {300 impl ImportCache {
299- pub(crate) fn get(&mut self, gpu: &Gpu, src: &DmaBuf) -> Result<vk::Image, Error> {301+ pub(crate) fn get(&mut self, gpu: &Gpu, src: &DmaBuf, busy: &[u64]) -> Result<(vk::Image, u64), Error> {
300 validate(src)?;302 validate(src)?;
301 let key = Key::new(src)?;303 let key = Key::new(src)?;
302 match self.entries.iter().position(|(k, _)| *k == key) {304 match self.entries.iter().position(|(k, _)| *k == key) {
@@ -306,17 +308,23 @@ impl ImportCache {
306 }308 }
307 None => {309 None => {
308 if self.entries.len() == CACHE_SIZE {310 if self.entries.len() == CACHE_SIZE {
309- let (_, old) = self.entries.remove(0);311+ let i = self
312+ .entries
313+ .iter()
314+ .position(|(_, import)| !busy.contains(&import.id))
315+ .ok_or_else(|| Error::Invalid("DMA-BUF import cache is full of in-flight imports".into()))?;
316+ let (_, old) = self.entries.remove(i);
310 old.destroy(gpu.device());317 old.destroy(gpu.device());
311 }318 }
312- let import = Import::new(gpu, src)?;319+ self.next_id += 1;
320+ let import = Import::new(gpu, src, self.next_id)?;
313 self.count += 1;321 self.count += 1;
314 self.entries.push((key, import));322 self.entries.push((key, import));
315 }323 }
316 }324 }
317 self.entries325 self.entries
318 .last()326 .last()
319- .map(|(_, import)| import.image)327+ .map(|(_, import)| (import.image, import.id))
320 .ok_or_else(|| Error::Invalid("DMA-BUF import cache".into()))328 .ok_or_else(|| Error::Invalid("DMA-BUF import cache".into()))
321 }329 }
322 330
shims/vk-video-ffi/src/h264_encode.rsmodified+41 -9
@@ -253,8 +253,8 @@ impl H264EncodeSession {
253 )253 )
254 }254 }
255 255
256- /// Encodes one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) and returns its Annex-B slice NAL units.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,7 +289,7 @@ impl H264EncodeSession {
289 289
290 /// Encodes one picture from a DMA-BUF: BGRx or RGBx box-downscaled to the encoder size, or NV12 of the encoder size.290 /// Encodes one picture from a DMA-BUF: BGRx or RGBx box-downscaled to the encoder size, or NV12 of the encoder size.
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)
@@ -301,7 +301,7 @@ impl H264EncodeSession {
301 self.enc.import_count()301 self.enc.import_count()
302 }302 }
303 303
304- fn encode_uploaded(&mut self, pic: &H264Picture) -> Result<Vec<u8>, Error> {304+ fn encode_uploaded(&mut self, pic: &H264Picture) -> Result<Option<Vec<u8>>, Error> {
305 let extent = self.enc.extent;305 let extent = self.enc.extent;
306 306
307 let primary = if pic.idr {307 let primary = if pic.idr {
@@ -313,7 +313,7 @@ impl H264EncodeSession {
313 picture_resource(self.enc.dpb[0].view, extent),313 picture_resource(self.enc.dpb[0].view, extent),
314 picture_resource(self.enc.dpb[1].view, extent),314 picture_resource(self.enc.dpb[1].view, extent),
315 ];315 ];
316- let src_pr = picture_resource(self.enc.src.view, extent);316+ let src_pr = picture_resource(self.enc.src_view(), extent);
317 317
318 let new_std = reference_info(primary, pic.frame_num, pic.poc);318 let new_std = reference_info(primary, pic.frame_num, pic.poc);
319 let ref_std = pic319 let ref_std = pic
@@ -400,7 +400,7 @@ impl H264EncodeSession {
400 .build();400 .build();
401 401
402 let encode = vk::VideoEncodeInfoKHR::builder()402 let encode = vk::VideoEncodeInfoKHR::builder()
403- .dst_buffer(self.enc.bitstream.buffer)403+ .dst_buffer(self.enc.bitstream_buffer())
404 .dst_buffer_offset(0)404 .dst_buffer_offset(0)
405 .dst_buffer_range(self.enc.bitstream_len)405 .dst_buffer_range(self.enc.bitstream_len)
406 .src_picture_resource(src_pr)406 .src_picture_resource(src_pr)
@@ -412,7 +412,39 @@ impl H264EncodeSession {
412 let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1);412 let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1);
413 let mut chain = RateChain::new(self.enc.rate, self.enc.fps);413 let mut chain = RateChain::new(self.enc.rate, self.enc.fps);
414 self.enc414 self.enc
415- .run(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)415+ .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)
416+ }
417+
418+ /// Encodes one picture synchronously and returns its coded bytes.
419+ pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &H264Picture) -> Result<Vec<u8>, Error> {
420+ self.submit(y, uv, pic)?;
421+ self.enc.flush_last()
422+ }
423+
424+ /// Encodes one picture synchronously and returns its coded bytes.
425+ pub fn encode_rgb(
426+ &mut self,
427+ rgb: &[u8],
428+ src_width: u32,
429+ src_height: u32,
430+ stride_bytes: u32,
431+ bgr: bool,
432+ pic: &H264Picture,
433+ ) -> Result<Vec<u8>, Error> {
434+ self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?;
435+ self.enc.flush_last()
436+ }
437+
438+ #[cfg(target_os = "linux")]
439+ /// Encodes one picture synchronously and returns its coded bytes.
440+ pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H264Picture) -> Result<Vec<u8>, Error> {
441+ self.submit_dmabuf(src, pic)?;
442+ self.enc.flush_last()
443+ }
444+
445+ /// Waits for queued pictures and returns their coded bytes in order.
446+ pub fn flush(&mut self) -> Result<Vec<Vec<u8>>, Error> {
447+ self.enc.flush()
416 }448 }
417 449
418 /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change.450 /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change.
shims/vk-video-ffi/src/h265_encode.rsmodified+50 -12
@@ -258,8 +258,8 @@ impl H265EncodeSession {
258 )258 )
259 }259 }
260 260
261- /// Encodes one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) and returns its Annex-B slice NAL units.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,7 +317,7 @@ impl H265EncodeSession {
317 317
318 /// Encodes one picture from a DMA-BUF: BGRx or RGBx box-downscaled to the encoder size, or NV12 or P010 of the encoder size.318 /// Encodes one picture from a DMA-BUF: BGRx or RGBx box-downscaled to the encoder size, or NV12 or P010 of the encoder size.
319 #[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)
@@ -329,7 +329,7 @@ impl H265EncodeSession {
329 self.enc.import_count()329 self.enc.import_count()
330 }330 }
331 331
332- fn encode_uploaded(&mut self, pic: &H265Picture) -> Result<Vec<u8>, Error> {332+ fn encode_uploaded(&mut self, pic: &H265Picture) -> Result<Option<Vec<u8>>, Error> {
333 let extent = self.enc.extent;333 let extent = self.enc.extent;
334 334
335 let primary = if pic.idr {335 let primary = if pic.idr {
@@ -341,7 +341,7 @@ impl H265EncodeSession {
341 picture_resource(self.enc.dpb[0].view, extent),341 picture_resource(self.enc.dpb[0].view, extent),
342 picture_resource(self.enc.dpb[1].view, extent),342 picture_resource(self.enc.dpb[1].view, extent),
343 ];343 ];
344- let src_pr = picture_resource(self.enc.src.view, extent);344+ let src_pr = picture_resource(self.enc.src_view(), extent);
345 345
346 let new_std = reference_info(primary, pic.poc);346 let new_std = reference_info(primary, pic.poc);
347 let ref_std = pic347 let ref_std = pic
@@ -431,7 +431,7 @@ impl H265EncodeSession {
431 .build();431 .build();
432 432
433 let encode = vk::VideoEncodeInfoKHR::builder()433 let encode = vk::VideoEncodeInfoKHR::builder()
434- .dst_buffer(self.enc.bitstream.buffer)434+ .dst_buffer(self.enc.bitstream_buffer())
435 .dst_buffer_offset(0)435 .dst_buffer_offset(0)
436 .dst_buffer_range(self.enc.bitstream_len)436 .dst_buffer_range(self.enc.bitstream_len)
437 .src_picture_resource(src_pr)437 .src_picture_resource(src_pr)
@@ -443,7 +443,45 @@ impl H265EncodeSession {
443 let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1);443 let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1);
444 let mut chain = RateChain::new(self.enc.rate, self.enc.fps);444 let mut chain = RateChain::new(self.enc.rate, self.enc.fps);
445 self.enc445 self.enc
446- .run(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)446+ .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)
447+ }
448+
449+ /// Encodes one picture synchronously and returns its coded bytes.
450+ pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &H265Picture) -> Result<Vec<u8>, Error> {
451+ self.submit(y, uv, pic)?;
452+ self.enc.flush_last()
453+ }
454+
455+ /// Encodes one picture synchronously and returns its coded bytes.
456+ pub fn encode_16(&mut self, y: &[u16], uv: &[u16], pic: &H265Picture) -> Result<Vec<u8>, Error> {
457+ self.submit_16(y, uv, pic)?;
458+ self.enc.flush_last()
459+ }
460+
461+ /// Encodes one picture synchronously and returns its coded bytes.
462+ pub fn encode_rgb(
463+ &mut self,
464+ rgb: &[u8],
465+ src_width: u32,
466+ src_height: u32,
467+ stride_bytes: u32,
468+ bgr: bool,
469+ pic: &H265Picture,
470+ ) -> Result<Vec<u8>, Error> {
471+ self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?;
472+ self.enc.flush_last()
473+ }
474+
475+ #[cfg(target_os = "linux")]
476+ /// Encodes one picture synchronously and returns its coded bytes.
477+ pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H265Picture) -> Result<Vec<u8>, Error> {
478+ self.submit_dmabuf(src, pic)?;
479+ self.enc.flush_last()
480+ }
481+
482+ /// Waits for queued pictures and returns their coded bytes in order.
483+ pub fn flush(&mut self) -> Result<Vec<Vec<u8>>, Error> {
484+ self.enc.flush()
447 }485 }
448 486
449 /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change.487 /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change.
shims/vk-video-ffi/src/session.rsmodified+270 -134
@@ -1,3 +1,5 @@
1+use std::collections::VecDeque;
2+
1 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,105 +704,145 @@ impl Drop for Lane {
686 }704 }
687 }705 }
688 706
689-/// Encode session plumbing shared by H.264, H.265 and AV1: DPB, source, bitstream and upload path.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,
723+ bitstream: Buffer,
724+ main: Lane,
725+ upload: Lane,
726+ ready: vk::Semaphore,
727+ encoded: vk::Semaphore,
706 #[cfg(target_os = "linux")]728 #[cfg(target_os = "linux")]
707- pub(crate) imports: ImportCache,729+ import: Option<u64>,
708- pub(crate) bitstream: Buffer,
709- query: vk::QueryPool,
710 }730 }
711 731
712-impl Encoder {732+impl Slot {
713- pub(crate) fn new(733+ fn new(
714- vs: VideoSession,734+ vs: &mut VideoSession,
715 profile: &vk::VideoProfileInfoKHR,735 profile: &vk::VideoProfileInfoKHR,
716 upload_family: u32,736 upload_family: u32,
717 input: (u32, u32),737 input: (u32, u32),
718 extent: vk::Extent2D,738 extent: vk::Extent2D,
719- setting: (RateControl, (u32, u32)),739+ frame_bytes: u64,
720- size_align: u64,740+ bitstream_len: u64,
721 ) -> Result<Self, Error> {741 ) -> Result<Self, Error> {
722 let gpu = vs.gpu.clone();742 let gpu = vs.gpu.clone();
723- let main = Lane::new(&gpu, vs.family)?;743+ let d = gpu.device();
724- let upload = Lane::new(&gpu, upload_family)?;744+ let family = vs.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;
749 let mut list = vk::VideoProfileListInfoKHR::builder()745 let mut list = vk::VideoProfileListInfoKHR::builder()
750 .profiles(std::slice::from_ref(profile))746 .profiles(std::slice::from_ref(profile))
751 .build();747 .build();
752- let family = e.vs.family;
753- e.dpb[0] = e.vs.image(extent, usage, usage, &[family], &mut list)?;
754- e.dpb[1] = e.vs.image(extent, usage, usage, &[family], &mut list)?;
755 let shared = if upload_family == family {748 let shared = if upload_family == family {
756 vec![family]749 vec![family]
757 } else {750 } else {
758 vec![upload_family, family]751 vec![upload_family, family]
759 };752 };
760- e.src = e.vs.image(753+ let src = vs.image(
761 extent,754 extent,
762 vk::ImageUsageFlags::VIDEO_ENCODE_SRC_KHR | vk::ImageUsageFlags::TRANSFER_DST,755 vk::ImageUsageFlags::VIDEO_ENCODE_SRC_KHR | vk::ImageUsageFlags::TRANSFER_DST,
763 vk::ImageUsageFlags::VIDEO_ENCODE_SRC_KHR | vk::ImageUsageFlags::TRANSFER_DST,756 vk::ImageUsageFlags::VIDEO_ENCODE_SRC_KHR | vk::ImageUsageFlags::TRANSFER_DST,
764 &shared,757 &shared,
765 &mut list,758 &mut list,
766 )?;759 )?;
767- e.staging = e.vs.buffer(760+ let staging = vs.buffer(
768 frame_bytes,761 frame_bytes,
769 vk::BufferUsageFlags::TRANSFER_SRC | vk::BufferUsageFlags::STORAGE_BUFFER,762 vk::BufferUsageFlags::TRANSFER_SRC | vk::BufferUsageFlags::STORAGE_BUFFER,
770 &[vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT],763 &[vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT],
771 None,764 None,
772 )?;765 )?;
773- e.rgb = Some(RgbConverter::new(766+ let rgb = RgbConverter::new(&gpu, input, (extent.width, extent.height), staging.buffer)?;
774- &gpu,767+ let bitstream = vs.buffer(
775- input,768+ bitstream_len,
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,
782 vk::BufferUsageFlags::VIDEO_ENCODE_DST_KHR,769 vk::BufferUsageFlags::VIDEO_ENCODE_DST_KHR,
783 &[vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT],770 &[vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT],
784 Some(&mut list),771 Some(&mut list),
785 )?;772 )?;
773+ Ok(Slot {
774+ src,
775+ staging,
776+ rgb,
777+ bitstream,
778+ main: Lane::new(&gpu, family)?,
779+ upload: Lane::new(&gpu, upload_family)?,
780+ ready: semaphore(d)?,
781+ encoded: semaphore(d)?,
782+ #[cfg(target_os = "linux")]
783+ import: None,
784+ })
785+ }
786 786
787+ fn retire(&mut self) {
788+ #[cfg(target_os = "linux")]
789+ {
790+ self.import = None;
791+ }
792+ }
793+}
794+
795+/// Encode session plumbing shared by H.264, H.265 and AV1: DPB, picture slots, bitstream and upload path.
796+pub(crate) struct Encoder {
797+ pub(crate) vs: VideoSession,
798+ pub(crate) input: (usize, usize),
799+ pub(crate) extent: vk::Extent2D,
800+ pub(crate) rate: RateControl,
801+ pub(crate) fps: (u32, u32),
802+ pub(crate) applied: (RateControl, (u32, u32)),
803+ pub(crate) dirty: bool,
804+ pub(crate) coded: bool,
805+ pub(crate) bitstream_len: u64,
806+ pub(crate) dpb: [Image; DPB_SLOTS],
807+ #[cfg(target_os = "linux")]
808+ pub(crate) imports: ImportCache,
809+ slots: [Slot; FLIGHT],
810+ cur: usize,
811+ next: usize,
812+ last: Option<usize>,
813+ pending: VecDeque<usize>,
814+ query: vk::QueryPool,
815+}
816+
817+impl Encoder {
818+ pub(crate) fn new(
819+ mut vs: VideoSession,
820+ profile: &vk::VideoProfileInfoKHR,
821+ upload_family: u32,
822+ input: (u32, u32),
823+ extent: vk::Extent2D,
824+ setting: (RateControl, (u32, u32)),
825+ size_align: u64,
826+ ) -> Result<Self, Error> {
827+ let gpu = vs.gpu.clone();
787 let d = gpu.device();828 let d = gpu.device();
829+ let bytes = bytes_per_sample(vs.format) as u64;
830+ let frame_bytes = extent.width as u64 * extent.height as u64 * 3 / 2 * bytes;
831+ let bitstream_len = align_u64(frame_bytes, size_align);
832+ let usage = vk::ImageUsageFlags::VIDEO_ENCODE_DPB_KHR;
833+ let mut list = vk::VideoProfileListInfoKHR::builder()
834+ .profiles(std::slice::from_ref(profile))
835+ .build();
836+ let family = vs.family;
837+ let dpb = [
838+ vs.image(extent, usage, usage, &[family], &mut list)?,
839+ vs.image(extent, usage, usage, &[family], &mut list)?,
840+ ];
841+ let slots = [
842+ Slot::new(&mut vs, profile, upload_family, input, extent, frame_bytes, bitstream_len)?,
843+ Slot::new(&mut vs, profile, upload_family, input, extent, frame_bytes, bitstream_len)?,
844+ ];
845+
788 let mut feedback = vk::QueryPoolVideoEncodeFeedbackCreateInfoKHR::builder()846 let mut feedback = vk::QueryPoolVideoEncodeFeedbackCreateInfoKHR::builder()
789 .encode_feedback_flags(847 .encode_feedback_flags(
790 vk::VideoEncodeFeedbackFlagsKHR::BITSTREAM_BUFFER_OFFSET848 vk::VideoEncodeFeedbackFlagsKHR::BITSTREAM_BUFFER_OFFSET
@@ -794,28 +852,53 @@ impl Encoder {
794 let mut prof = *profile;852 let mut prof = *profile;
795 let query_info = vk::QueryPoolCreateInfo::builder()853 let query_info = vk::QueryPoolCreateInfo::builder()
796 .query_type(vk::QueryType::VIDEO_ENCODE_FEEDBACK_KHR)854 .query_type(vk::QueryType::VIDEO_ENCODE_FEEDBACK_KHR)
797- .query_count(1)855+ .query_count(FLIGHT as u32)
798 .push_next(&mut feedback)856 .push_next(&mut feedback)
799 .push_next(&mut prof)857 .push_next(&mut prof)
800 .build();858 .build();
801- e.query = unsafe { vk(d.create_query_pool(&query_info, None), "vkCreateQueryPool")? };859+ let query = unsafe { vk(d.create_query_pool(&query_info, None), "vkCreateQueryPool")? };
802 860
803- e.main.begin()?;861+ let e = Encoder {
862+ vs,
863+ input: (input.0 as usize, input.1 as usize),
864+ extent,
865+ rate: setting.0,
866+ fps: setting.1,
867+ applied: setting,
868+ dirty: false,
869+ coded: false,
870+ bitstream_len,
871+ dpb,
872+ #[cfg(target_os = "linux")]
873+ imports: Default::default(),
874+ slots,
875+ cur: 0,
876+ next: 0,
877+ last: None,
878+ pending: VecDeque::new(),
879+ query,
880+ };
881+ let lane = &e.slots[0].main;
882+ lane.begin()?;
804 for img in &e.dpb {883 for img in &e.dpb {
805- init_barrier(884+ init_barrier(d, lane.cb, img.image, vk::ImageLayout::VIDEO_ENCODE_DPB_KHR);
806- d,
807- e.main.cb,
808- img.image,
809- vk::ImageLayout::VIDEO_ENCODE_DPB_KHR,
810- );
811 }885 }
812- e.main.end()?;886+ lane.end()?;
813- e.main.submit()?;887+ lane.submit()?;
814 Ok(e)888 Ok(e)
815 }889 }
816 890
817- pub(crate) fn staging_ptr(&self) -> Result<*mut u8, Error> {891+ pub(crate) fn src_view(&self) -> vk::ImageView {
818- self.staging892+ self.slots[self.cur].src.view
893+ }
894+
895+ pub(crate) fn bitstream_buffer(&self) -> vk::Buffer {
896+ self.slots[self.cur].bitstream.buffer
897+ }
898+
899+ fn staging_ptr(&self) -> Result<*mut u8, Error> {
900+ self.slots[self.cur]
901+ .staging
819 .ptr902 .ptr
820 .ok_or_else(|| Error::Invalid("staging buffer not mapped".into()))903 .ok_or_else(|| Error::Invalid("staging buffer not mapped".into()))
821 }904 }
@@ -848,6 +931,8 @@ impl Encoder {
848 _ => {}931 _ => {}
849 }932 }
850 let gpu = self.vs.gpu.clone();933 let gpu = self.vs.gpu.clone();
934+ let k = self.next;
935+ self.cur = k;
851 match input {936 match input {
852 Input::Nv12 { y, uv } => {937 Input::Nv12 { y, uv } => {
853 let staging =938 let staging =
@@ -866,42 +951,36 @@ impl Encoder {
866 stride,951 stride,
867 ..952 ..
868 } => {953 } => {
869- let rgb = self954+ let rgb = &mut self.slots[k].rgb;
870- .rgb
871- .as_mut()
872- .ok_or_else(|| Error::Invalid("RGB converter not created".into()))?;
873 rgb.reserve(&gpu, width, height)?;955 rgb.reserve(&gpu, width, height)?;
874 rgb.load(data, stride);956 rgb.load(data, stride);
875 }957 }
876 #[cfg(target_os = "linux")]958 #[cfg(target_os = "linux")]
877 Input::DmaBuf { width, height, .. } => {959 Input::DmaBuf { width, height, .. } => {
878- let rgb = self960+ self.slots[k].rgb.reserve(&gpu, width, height)?;
879- .rgb
880- .as_mut()
881- .ok_or_else(|| Error::Invalid("RGB converter not created".into()))?;
882- rgb.reserve(&gpu, width, height)?;
883 }961 }
884 }962 }
885 963
886 let d = gpu.device();964 let d = gpu.device();
887- let cb = self.upload.cb;965+ let slot = &self.slots[k];
966+ let cb = slot.upload.cb;
888 let luma = (aw * ah * bytes) as u64;967 let luma = (aw * ah * bytes) as u64;
889 let copies = [968 let copies = [
890 copy_region(0, PLANE_0, aw as u32, ah as u32),969 copy_region(0, PLANE_0, aw as u32, ah as u32),
891 copy_region(luma, PLANE_1, (aw / 2) as u32, (ah / 2) as u32),970 copy_region(luma, PLANE_1, (aw / 2) as u32, (ah / 2) as u32),
892 ];971 ];
893- self.upload.begin()?;972+ slot.upload.begin()?;
894 unsafe {973 unsafe {
895- if let (Some(bgr), Some(rgb)) = (input.bgr(), &self.rgb) {974+ if let Some(bgr) = input.bgr() {
896 if let Some(image) = input.source_image() {975 if let Some(image) = input.source_image() {
897- rgb.record_import(d, cb, image, self.upload.family);976+ slot.rgb.record_import(d, cb, image, slot.upload.family);
898 }977 }
899- rgb.record(d, cb, bgr);978+ slot.rgb.record(d, cb, bgr);
900 }979 }
901 barrier(980 barrier(
902 d,981 d,
903 cb,982 cb,
904- self.src.image,983+ slot.src.image,
905 (984 (
906 vk::ImageLayout::UNDEFINED,985 vk::ImageLayout::UNDEFINED,
907 vk::PipelineStageFlags2::NONE,986 vk::PipelineStageFlags2::NONE,
@@ -915,15 +994,15 @@ impl Encoder {
915 );994 );
916 d.cmd_copy_buffer_to_image(995 d.cmd_copy_buffer_to_image(
917 cb,996 cb,
918- self.staging.buffer,997+ slot.staging.buffer,
919- self.src.image,998+ slot.src.image,
920 vk::ImageLayout::TRANSFER_DST_OPTIMAL,999 vk::ImageLayout::TRANSFER_DST_OPTIMAL,
921 &copies,1000 &copies,
922 );1001 );
923 barrier(1002 barrier(
924 d,1003 d,
925 cb,1004 cb,
926- self.src.image,1005+ slot.src.image,
927 (1006 (
928 vk::ImageLayout::TRANSFER_DST_OPTIMAL,1007 vk::ImageLayout::TRANSFER_DST_OPTIMAL,
929 vk::PipelineStageFlags2::COPY,1008 vk::PipelineStageFlags2::COPY,
@@ -936,8 +1015,8 @@ impl Encoder {
936 ),1015 ),
937 );1016 );
938 }1017 }
939- self.upload.end()?;1018+ slot.upload.end()?;
940- self.upload.submit()1019+ slot.upload.submit_with(&[], &[slot.ready])
941 }1020 }
942 1021
943 #[cfg(target_os = "linux")]1022 #[cfg(target_os = "linux")]
@@ -948,8 +1027,10 @@ impl Encoder {
948 DmaBufFormat::Bgrx | DmaBufFormat::Rgbx => check_size(self.input, (width, height))?,1027 DmaBufFormat::Bgrx | DmaBufFormat::Rgbx => check_size(self.input, (width, height))?,
949 DmaBufFormat::Nv12 | DmaBufFormat::P010 => self.check_planar(src)?,1028 DmaBufFormat::Nv12 | DmaBufFormat::P010 => self.check_planar(src)?,
950 }1029 }
951- let image = self.imports.get(&gpu, src)?;1030+ let busy: Vec<u64> = self.slots.iter().filter_map(|s| s.import).collect();
952- match src.format {1031+ let (image, id) = self.imports.get(&gpu, src, &busy)?;
1032+ let k = self.next;
1033+ let result = match src.format {
953 DmaBufFormat::Bgrx | DmaBufFormat::Rgbx => self.upload(Input::DmaBuf {1034 DmaBufFormat::Bgrx | DmaBufFormat::Rgbx => self.upload(Input::DmaBuf {
954 image,1035 image,
955 width,1036 width,
@@ -957,7 +1038,11 @@ impl Encoder {
957 bgr: src.format == DmaBufFormat::Bgrx,1038 bgr: src.format == DmaBufFormat::Bgrx,
958 }),1039 }),
959 DmaBufFormat::Nv12 | DmaBufFormat::P010 => self.copy_planes(image),1040 DmaBufFormat::Nv12 | DmaBufFormat::P010 => self.copy_planes(image),
1041+ };
1042+ if result.is_ok() {
1043+ self.slots[k].import = Some(id);
960 }1044 }
1045+ result
961 }1046 }
962 1047
963 #[cfg(target_os = "linux")]1048 #[cfg(target_os = "linux")]
@@ -978,17 +1063,20 @@ impl Encoder {
978 fn copy_planes(&mut self, image: vk::Image) -> Result<(), Error> {1063 fn copy_planes(&mut self, image: vk::Image) -> Result<(), Error> {
979 let gpu = self.vs.gpu.clone();1064 let gpu = self.vs.gpu.clone();
980 let d = gpu.device();1065 let d = gpu.device();
981- let cb = self.upload.cb;1066+ let k = self.next;
1067+ self.cur = k;
1068+ let slot = &self.slots[k];
1069+ let cb = slot.upload.cb;
982 let (w, h) = (self.input.0 as u32, self.input.1 as u32);1070 let (w, h) = (self.input.0 as u32, self.input.1 as u32);
983 let aspects = [PLANE_0, PLANE_1];1071 let aspects = [PLANE_0, PLANE_1];
984 let regions = [plane_copy(PLANE_0, w, h), plane_copy(PLANE_1, w / 2, h / 2)];1072 let regions = [plane_copy(PLANE_0, w, h), plane_copy(PLANE_1, w / 2, h / 2)];
985- self.upload.begin()?;1073+ slot.upload.begin()?;
986- acquire(d, cb, image, &aspects, self.upload.family);1074+ acquire(d, cb, image, &aspects, slot.upload.family);
987 unsafe {1075 unsafe {
988 barrier(1076 barrier(
989 d,1077 d,
990 cb,1078 cb,
991- self.src.image,1079+ slot.src.image,
992 (1080 (
993 vk::ImageLayout::UNDEFINED,1081 vk::ImageLayout::UNDEFINED,
994 vk::PipelineStageFlags2::NONE,1082 vk::PipelineStageFlags2::NONE,
@@ -1004,14 +1092,14 @@ impl Encoder {
1004 cb,1092 cb,
1005 image,1093 image,
1006 vk::ImageLayout::TRANSFER_SRC_OPTIMAL,1094 vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
1007- self.src.image,1095+ slot.src.image,
1008 vk::ImageLayout::TRANSFER_DST_OPTIMAL,1096 vk::ImageLayout::TRANSFER_DST_OPTIMAL,
1009 &regions,1097 &regions,
1010 );1098 );
1011 barrier(1099 barrier(
1012 d,1100 d,
1013 cb,1101 cb,
1014- self.src.image,1102+ slot.src.image,
1015 (1103 (
1016 vk::ImageLayout::TRANSFER_DST_OPTIMAL,1104 vk::ImageLayout::TRANSFER_DST_OPTIMAL,
1017 vk::PipelineStageFlags2::COPY,1105 vk::PipelineStageFlags2::COPY,
@@ -1025,8 +1113,8 @@ impl Encoder {
1025 );1113 );
1026 }1114 }
1027 release(d, cb, image, &aspects);1115 release(d, cb, image, &aspects);
1028- self.upload.end()?;1116+ slot.upload.end()?;
1029- self.upload.submit()1117+ slot.upload.submit_with(&[], &[slot.ready])
1030 }1118 }
1031 1119
1032 #[cfg(target_os = "linux")]1120 #[cfg(target_os = "linux")]
@@ -1034,26 +1122,29 @@ impl Encoder {
1034 self.imports.count1122 self.imports.count
1035 }1123 }
1036 1124
1037- /// Records one encode with its rate control chains, submits it and returns the coded bytes.1125+ /// Records the encode of the uploaded slot and submits it without waiting. Returns the oldest picture once FLIGHT are queued.
1038- pub(crate) fn run(1126+ pub(crate) fn submit(
1039 &mut self,1127 &mut self,
1040 begin_slots: &[vk::VideoReferenceSlotInfoKHR],1128 begin_slots: &[vk::VideoReferenceSlotInfoKHR],
1041 applied: &mut vk::VideoEncodeRateControlInfoKHR,1129 applied: &mut vk::VideoEncodeRateControlInfoKHR,
1042 chain: &mut vk::VideoEncodeRateControlInfoKHR,1130 chain: &mut vk::VideoEncodeRateControlInfoKHR,
1043 encode: &vk::VideoEncodeInfoKHR,1131 encode: &vk::VideoEncodeInfoKHR,
1044- ) -> Result<Vec<u8>, Error> {1132+ ) -> Result<Option<Vec<u8>>, Error> {
1045 let gpu = self.vs.gpu.clone();1133 let gpu = self.vs.gpu.clone();
1046 let d = gpu.device();1134 let d = gpu.device();
1047- let cb = self.main.cb;1135+ let k = self.cur;
1136+ let slot = &self.slots[k];
1137+ let cb = slot.main.cb;
1138+ let query = k as u32;
1048 let mut quality = vk::VideoEncodeQualityLevelInfoKHR::builder()1139 let mut quality = vk::VideoEncodeQualityLevelInfoKHR::builder()
1049 .quality_level(0)1140 .quality_level(0)
1050 .build();1141 .build();
1051 let reset = !self.coded;1142 let reset = !self.coded;
1052 let update = reset || self.dirty;1143 let update = reset || self.dirty;
1053 1144
1054- self.main.begin()?;1145+ slot.main.begin()?;
1055 unsafe {1146 unsafe {
1056- d.cmd_reset_query_pool(cb, self.query, 0, 1);1147+ d.cmd_reset_query_pool(cb, self.query, query, 1);
1057 let begin = vk::VideoBeginCodingInfoKHR::builder()1148 let begin = vk::VideoBeginCodingInfoKHR::builder()
1058 .video_session(self.vs.session)1149 .video_session(self.vs.session)
1059 .video_session_parameters(self.vs.params)1150 .video_session_parameters(self.vs.params)
@@ -1081,27 +1172,67 @@ impl Encoder {
1081 d.cmd_control_video_coding_khr(cb, &control);1172 d.cmd_control_video_coding_khr(cb, &control);
1082 }1173 }
1083 1174
1084- d.cmd_begin_query(cb, self.query, 0, vk::QueryControlFlags::empty());1175+ d.cmd_begin_query(cb, self.query, query, vk::QueryControlFlags::empty());
1085 d.cmd_encode_video_khr(cb, encode);1176 d.cmd_encode_video_khr(cb, encode);
1086- d.cmd_end_query(cb, self.query, 0);1177+ d.cmd_end_query(cb, self.query, query);
1087 let end = vk::VideoEndCodingInfoKHR::builder().build();1178 let end = vk::VideoEndCodingInfoKHR::builder().build();
1088 d.cmd_end_video_coding_khr(cb, &end);1179 d.cmd_end_video_coding_khr(cb, &end);
1089 }1180 }
1090- self.main.end()?;1181+ slot.main.end()?;
1091- self.main.submit()?;1182+ let mut wait = vec![slot.ready];
1183+ if let Some(p) = self.last {
1184+ wait.push(self.slots[p].encoded);
1185+ }
1186+ slot.main.submit_with(&wait, &[slot.encoded])?;
1187+
1188+ self.last = Some(k);
1189+ self.next = k ^ 1;
1092 self.coded = true;1190 self.coded = true;
1093 self.applied = (self.rate, self.fps);1191 self.applied = (self.rate, self.fps);
1094 self.dirty = false;1192 self.dirty = false;
1095- self.read_bitstream()1193+ self.pending.push_back(k);
1194+ if self.pending.len() < FLIGHT {
1195+ return Ok(None);
1196+ }
1197+ let oldest = self
1198+ .pending
1199+ .pop_front()
1200+ .ok_or_else(|| Error::Invalid("no picture in flight".into()))?;
1201+ self.finish(oldest).map(Some)
1202+ }
1203+
1204+ /// Waits for every queued picture and returns their bytes in submission order.
1205+ pub(crate) fn flush(&mut self) -> Result<Vec<Vec<u8>>, Error> {
1206+ let mut out = Vec::new();
1207+ while let Some(k) = self.pending.pop_front() {
1208+ out.push(self.finish(k)?);
1209+ }
1210+ Ok(out)
1211+ }
1212+
1213+ /// Flushes and returns the last picture, for synchronous use where one picture is queued per call.
1214+ pub(crate) fn flush_last(&mut self) -> Result<Vec<u8>, Error> {
1215+ self.flush()?
1216+ .pop()
1217+ .ok_or_else(|| Error::Invalid("no picture encoded".into()))
1096 }1218 }
1097 1219
1098- fn read_bitstream(&self) -> Result<Vec<u8>, Error> {1220+ fn finish(&mut self, k: usize) -> Result<Vec<u8>, Error> {
1221+ let slot = &self.slots[k];
1222+ slot.main.wait()?;
1223+ slot.upload.wait()?;
1224+ let bytes = self.read_bitstream(k)?;
1225+ self.slots[k].retire();
1226+ Ok(bytes)
1227+ }
1228+
1229+ fn read_bitstream(&self, k: usize) -> Result<Vec<u8>, Error> {
1099 let mut feedback = [0u8; 8];1230 let mut feedback = [0u8; 8];
1100 unsafe {1231 unsafe {
1101 vk(1232 vk(
1102 self.vs.gpu.device().get_query_pool_results(1233 self.vs.gpu.device().get_query_pool_results(
1103 self.query,1234 self.query,
1104- 0,1235+ k as u32,
1105 1,1236 1,
1106 &mut feedback,1237 &mut feedback,
1107 8,1238 8,
@@ -1119,7 +1250,7 @@ impl Encoder {
1119 "encoded size exceeds bitstream buffer".into(),1250 "encoded size exceeds bitstream buffer".into(),
1120 ));1251 ));
1121 }1252 }
1122- let ptr = self1253+ let ptr = self.slots[k]
1123 .bitstream1254 .bitstream
1124 .ptr1255 .ptr
1125 .ok_or_else(|| Error::Invalid("bitstream buffer not mapped".into()))?;1256 .ok_or_else(|| Error::Invalid("bitstream buffer not mapped".into()))?;
@@ -1136,16 +1267,21 @@ impl Drop for Encoder {
1136 let _ = d.device_wait_idle();1267 let _ = d.device_wait_idle();
1137 d.destroy_query_pool(self.query, None);1268 d.destroy_query_pool(self.query, None);
1138 }1269 }
1139- for img in self.dpb.iter().chain(std::iter::once(&self.src)) {1270+ for img in &self.dpb {
1140 img.destroy(d);1271 img.destroy(d);
1141 }1272 }
1142 #[cfg(target_os = "linux")]1273 #[cfg(target_os = "linux")]
1143 self.imports.destroy(d);1274 self.imports.destroy(d);
1144- if let Some(rgb) = &self.rgb {1275+ for slot in self.slots.iter_mut() {
1145- rgb.destroy(d);1276+ unsafe {
1277+ d.destroy_semaphore(slot.ready, None);
1278+ d.destroy_semaphore(slot.encoded, None);
1279+ }
1280+ slot.src.destroy(d);
1281+ slot.rgb.destroy(d);
1282+ slot.staging.destroy(d);
1283+ slot.bitstream.destroy(d);
1146 }1284 }
1147- self.staging.destroy(d);
1148- self.bitstream.destroy(d);
1149 }1285 }
1150 }1286 }
1151 1287