Skip to main content

oa/video/
encoder.rs

1//! Hardware-independent encoder settings, exact device preflight, and the
2//! public hardware encoder session.
3//!
4//! Donor: `source/cpp/include/oa/vision/videoEncoder.h` and
5//! `source/cpp/lib/oa/vision/video/encoder/videoEncoder.cpp`.
6
7use crate::{Engine, Error, Result, runtime::VideoEncoderBackend};
8
9use super::{
10	VideoChromaSubsampling, VideoComponentBitDepth, VideoEncodeCapabilities,
11	VideoEncodeCodecCapabilities, VideoEncodeProfile, VideoExtent,
12};
13pub use crate::video::types::VideoEncodeConfig;
14
15/// Rate-control policy requested for a future Vulkan Video encoder session.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum VideoRateControl {
18	ConstantQp,
19	Cbr,
20	Vbr,
21}
22
23impl VideoEncodeConfig {
24	/// Construct the donor's default encode settings for a visible extent.
25	pub const fn new(profile: VideoEncodeProfile, width: u32, height: u32) -> Self {
26		Self {
27			profile,
28			width,
29			height,
30			frame_rate: 30,
31			gop_size: 30,
32			rate_control: VideoRateControl::ConstantQp,
33			bitrate: 4_000_000,
34			max_bitrate: 0,
35			constant_qp: 26,
36			quality_level: 0,
37			async_depth: 3,
38			max_b_frames: 0,
39			max_dpb_slots: 0,
40		}
41	}
42
43	/// Validate this request against the exact queried codec profile.
44	///
45	/// The returned coded extent and resolved peak bitrate are inputs to a
46	/// future session. No device resource is allocated by this method.
47	///
48	/// # Errors
49	///
50	/// Returns an error for an unsupported profile, invalid geometry or rate
51	/// control, arithmetic overflow, or device limits that cannot admit the
52	/// requested stream.
53	pub fn validate_for_device(self, caps: VideoEncodeCapabilities) -> Result<VideoEncodePlan> {
54		if self.profile != caps.profile() {
55			return Err(Error::invalid_argument(
56				"encode capabilities belong to a different profile",
57			));
58		}
59		let donor_profile = matches!(
60			self.profile,
61			VideoEncodeProfile::H264 {
62				profile: super::H264Profile::High,
63				chroma_subsampling: VideoChromaSubsampling::Yuv420,
64				luma_bit_depth: VideoComponentBitDepth::Eight,
65				chroma_bit_depth: VideoComponentBitDepth::Eight,
66			} | VideoEncodeProfile::H264 {
67				profile: super::H264Profile::High10,
68				chroma_subsampling: VideoChromaSubsampling::Yuv420,
69				luma_bit_depth: VideoComponentBitDepth::Ten,
70				chroma_bit_depth: VideoComponentBitDepth::Ten,
71			} | VideoEncodeProfile::H265 {
72				profile: super::H265Profile::Main,
73				chroma_subsampling: VideoChromaSubsampling::Yuv420,
74				luma_bit_depth: VideoComponentBitDepth::Eight,
75				chroma_bit_depth: VideoComponentBitDepth::Eight,
76			} | VideoEncodeProfile::H265 {
77				profile: super::H265Profile::Main10 | super::H265Profile::FormatRangeExtensions,
78				chroma_subsampling: VideoChromaSubsampling::Yuv420,
79				luma_bit_depth: VideoComponentBitDepth::Ten,
80				chroma_bit_depth: VideoComponentBitDepth::Ten,
81			}
82		);
83		if !donor_profile {
84			return Err(Error::missing_capability(
85				"encoder picture recording is limited to H.264 High 8-bit, H.264 High10 10-bit, H.265 Main 8-bit, and H.265 Main10/REx 10-bit 4:2:0",
86			));
87		}
88		if !matches!(
89			(self.profile, caps.codec()),
90			(
91				VideoEncodeProfile::H264 { .. },
92				VideoEncodeCodecCapabilities::H264 { .. }
93			) | (
94				VideoEncodeProfile::H265 { .. },
95				VideoEncodeCodecCapabilities::H265 { .. }
96			)
97		) {
98			return Err(Error::invalid_argument(
99				"encode capability codec does not match its profile",
100			));
101		}
102		if self.width == 0 || self.height == 0 || self.frame_rate == 0 || self.gop_size == 0 {
103			return Err(Error::invalid_argument(
104				"encode extent, frame rate, and GOP size must be non-zero",
105			));
106		}
107		if self.async_depth == 0 {
108			return Err(Error::invalid_argument(
109				"encode async depth must be non-zero",
110			));
111		}
112		if self.max_b_frames != 0 {
113			return Err(Error::missing_capability(
114				"B-picture encoding requires a reorder and reference path",
115			));
116		}
117		if self.constant_qp > 51 {
118			return Err(Error::invalid_argument(
119				"encode constant QP must be in 0..=51",
120			));
121		}
122		if self.quality_level >= caps.max_quality_levels() {
123			return Err(Error::missing_capability(
124				"encode quality level exceeds device capabilities",
125			));
126		}
127		let supported_rate_control = match self.rate_control {
128			VideoRateControl::ConstantQp => caps.supports_constant_qp(),
129			VideoRateControl::Cbr => caps.supports_cbr(),
130			VideoRateControl::Vbr => caps.supports_vbr(),
131		};
132		if !supported_rate_control {
133			return Err(Error::missing_capability(
134				"requested encode rate control is unavailable",
135			));
136		}
137		if self.rate_control != VideoRateControl::ConstantQp && caps.max_rate_control_layers() == 0 {
138			return Err(Error::missing_capability(
139				"device reports no encode rate-control layers",
140			));
141		}
142		if self.rate_control != VideoRateControl::ConstantQp && self.bitrate == 0 {
143			return Err(Error::invalid_argument(
144				"CBR/VBR target bitrate must be non-zero",
145			));
146		}
147		if self.max_bitrate != 0 && self.max_bitrate < self.bitrate {
148			return Err(Error::invalid_argument(
149				"peak bitrate must be at least target bitrate",
150			));
151		}
152		if caps.max_bitrate() != 0
153			&& (u64::from(self.bitrate) > caps.max_bitrate()
154				|| (self.max_bitrate != 0 && u64::from(self.max_bitrate) > caps.max_bitrate()))
155		{
156			return Err(Error::missing_capability(
157				"requested bitrate exceeds device capabilities",
158			));
159		}
160		let peak_bitrate = match self.rate_control {
161			VideoRateControl::ConstantQp => 0,
162			VideoRateControl::Cbr => self.bitrate,
163			VideoRateControl::Vbr if self.max_bitrate != 0 => self.max_bitrate,
164			VideoRateControl::Vbr => self.bitrate.saturating_mul(2),
165		};
166		let peak_bitrate = if caps.max_bitrate() == 0 {
167			peak_bitrate
168		} else {
169			peak_bitrate.min(caps.max_bitrate().min(u64::from(u32::MAX)) as u32)
170		};
171		if self.rate_control == VideoRateControl::Vbr && peak_bitrate < self.bitrate {
172			return Err(Error::missing_capability(
173				"device peak bitrate is below requested target",
174			));
175		}
176		if let VideoEncodeCodecCapabilities::H265 { min_qp, max_qp, .. } = caps.codec()
177			&& (self.constant_qp < min_qp.max(0) as u32 || self.constant_qp > max_qp.max(0) as u32)
178		{
179			return Err(Error::missing_capability(
180				"H.265 QP is outside device limits",
181			));
182		}
183		let min = caps.min_coded_extent();
184		let max = caps.max_coded_extent();
185		let granularity = caps.picture_access_granularity();
186		let coded_width = align_up(self.width, granularity.width.max(16))?;
187		let coded_height = align_up(self.height, granularity.height.max(16))?;
188		if coded_width < min.width || coded_height < min.height {
189			return Err(Error::missing_capability(
190				"aligned encode extent is below device minimum",
191			));
192		}
193		if coded_width > max.width || coded_height > max.height {
194			return Err(Error::missing_capability(
195				"aligned encode extent exceeds device maximum",
196			));
197		}
198		if self.gop_size > 1 && (caps.max_dpb_slots() < 2 || caps.max_active_reference_pictures() == 0)
199		{
200			return Err(Error::missing_capability(
201				"P-picture encoding requires two DPB slots and an active reference",
202			));
203		}
204		let h264_level = if let VideoEncodeCodecCapabilities::H264 { max_level, .. } = caps.codec() {
205			let level =
206				h264_level_for_extent(self.width, self.height, self.frame_rate).ok_or_else(|| {
207					Error::missing_capability("H.264 extent or frame rate exceeds supported levels")
208				})?;
209			if level > max_level {
210				return Err(Error::missing_capability(
211					"H.264 extent and frame rate require an unsupported device level",
212				));
213			}
214			Some(level)
215		} else {
216			None
217		};
218		Ok(VideoEncodePlan {
219			coded_extent: VideoExtent {
220				width: coded_width,
221				height: coded_height,
222			},
223			peak_bitrate,
224			h264_level,
225		})
226	}
227}
228
229/// Validated, hardware-independent settings for session creation.
230#[derive(Clone, Copy, Debug, PartialEq, Eq)]
231pub struct VideoEncodePlan {
232	coded_extent: VideoExtent,
233	peak_bitrate: u32,
234	h264_level: Option<u32>,
235}
236
237impl VideoEncodePlan {
238	pub const fn coded_extent(self) -> VideoExtent {
239		self.coded_extent
240	}
241	pub const fn peak_bitrate(self) -> u32 {
242		self.peak_bitrate
243	}
244	/// Numeric H.264 level IDC selected from the donor's progressive High table.
245	pub const fn h264_level(self) -> Option<u32> {
246		self.h264_level
247	}
248}
249
250// Donor: videoEncoder.cpp::h264LevelForExtent, Table A-1 subset. Division
251// avoids overflowing while checking macroblocks per second.
252fn h264_level_for_extent(width: u32, height: u32, frame_rate: u32) -> Option<u32> {
253	let width_mbs = u64::from(width).div_ceil(16);
254	let height_mbs = u64::from(height).div_ceil(16);
255	let frame_mbs = width_mbs * height_mbs;
256	const LIMITS: [(u32, u64, u64); 7] = [
257		(42, 522_240, 8_704),
258		(50, 589_824, 22_080),
259		(51, 983_040, 36_864),
260		(52, 2_073_600, 36_864),
261		(60, 4_177_920, 139_264),
262		(61, 8_355_840, 139_264),
263		(62, 16_711_680, 139_264),
264	];
265	LIMITS.iter().find_map(|&(level, per_second, max_frame)| {
266		(frame_mbs <= max_frame
267			&& frame_mbs <= per_second / u64::from(frame_rate)
268			&& width_mbs * width_mbs <= 8 * max_frame
269			&& height_mbs * height_mbs <= 8 * max_frame)
270			.then_some(level)
271	})
272}
273
274fn align_up(value: u32, granularity: u32) -> Result<u32> {
275	let blocks = value
276		.checked_add(granularity - 1)
277		.ok_or_else(|| Error::out_of_range("encode coded extent alignment overflow"))?
278		/ granularity;
279	blocks
280		.checked_mul(granularity)
281		.ok_or_else(|| Error::out_of_range("encode coded extent alignment overflow"))
282}
283
284/// Stateful hardware encoder session for H.264 High or H.265 Main.
285///
286/// One encoder owns a private Vulkan Video encode session, per-slot NV12 input
287/// pictures, and the RGBA→NV12 conversion on the selected [`Engine`]'s queues.
288/// Frames enter as packed RGBA8 bytes sized exactly
289/// `visible_extent().width * visible_extent().height * 4`; conversion, GOP
290/// cadence, rate control, DPB management, and Annex-B framing stay private.
291/// Every emitted [`EncodedVideoPacket`] is one access unit; keyframe packets
292/// carry the session's cached SPS/PPS (and VPS for H.265) parameter sets so
293/// each random-access point is self-describing.
294///
295/// `encode` waits for the submitted frame and returns its packet. `flush`
296/// waits for every outstanding encode job and drains the remainder — required
297/// before `close` when asynchronous submissions left frames in flight.
298///
299/// [`EncodedVideoPacket`]: crate::video::EncodedVideoPacket
300pub struct VideoEncoder {
301	state: Option<VideoEncoderBackend>,
302}
303
304impl VideoEncoder {
305	/// Create a session admitted by exact capability preflight.
306	///
307	/// Settings are validated against the engine's queried encode capabilities;
308	/// session creation then performs the Vulkan-level admission a second time.
309	/// A device without an encode queue family for the requested codec profile
310	/// fails here, not on the first `encode` call.
311	///
312	/// # Errors
313	///
314	/// Returns an error when settings fail preflight or the engine's device
315	/// does not admit a hardware encode session for the profile.
316	pub fn new(engine: &Engine, settings: VideoEncodeConfig) -> Result<Self> {
317		Ok(Self {
318			state: Some(VideoEncoderBackend::create(engine, settings)?),
319		})
320	}
321
322	/// Encode one packed RGBA8 frame and return its access unit.
323	///
324	/// `rgba` must contain exactly
325	/// `visible_extent().width * visible_extent().height * 4` bytes in
326	/// row-major RGBA8 order. The frame is converted to the session's coded
327	/// NV12 extent, queued on the hardware encode queue, and awaited before the
328	/// packet is returned; presentation timestamps are in microseconds.
329	///
330	/// # Errors
331	///
332	/// Returns an error after close, for a mismatched input size, or when
333	/// conversion, encode submission, feedback, or bitstream readback fails.
334	pub fn encode(
335		&mut self,
336		rgba: &[u8],
337		presentation_timestamp_micros: u64,
338	) -> Result<super::EncodedVideoPacket> {
339		self
340			.state
341			.as_mut()
342			.ok_or_else(|| Error::failed_precondition("VideoEncoder is closed"))?
343			.encode_rgba(rgba, presentation_timestamp_micros)
344	}
345
346	/// Encode one packed RGBA64 frame and return its access unit.
347	///
348	/// `rgba` must contain exactly
349	/// `visible_extent().width * visible_extent().height * 4` little-endian
350	/// 16-bit samples in row-major RGBA order; the session must carry a
351	/// wide-component profile such as H.265 Main10. An 8-bit session rejects
352	/// the input through its length validation.
353	///
354	/// # Errors
355	///
356	/// Returns an error after close, for a mismatched input size, or when
357	/// conversion, encode submission, feedback, or bitstream readback fails.
358	pub fn encode_rgba16(
359		&mut self,
360		rgba: &[u16],
361		presentation_timestamp_micros: u64,
362	) -> Result<super::EncodedVideoPacket> {
363		self
364			.state
365			.as_mut()
366			.ok_or_else(|| Error::failed_precondition("VideoEncoder is closed"))?
367			.encode_rgba16(rgba, presentation_timestamp_micros)
368	}
369
370	/// Wait for every outstanding encode job and drain all remaining packets.
371	///
372	/// Synchronous [`encode`](Self::encode) leaves nothing pending; flush is the
373	/// tail drain for asynchronous submissions and returns an empty list when
374	/// the session is already drained.
375	///
376	/// # Errors
377	///
378	/// Returns an error after close or when an outstanding job fails feedback
379	/// or bitstream readback.
380	pub fn flush(&mut self) -> Result<Vec<super::EncodedVideoPacket>> {
381		self
382			.state
383			.as_mut()
384			.ok_or_else(|| Error::failed_precondition("VideoEncoder is closed"))?
385			.flush()
386	}
387
388	/// Close the encoder and release its session resources.
389	///
390	/// Unharvested asynchronous jobs are released without being drained;
391	/// call [`flush`](Self::flush) first to keep every submitted frame.
392	pub fn close(&mut self) {
393		if let Some(backend) = self.state.take() {
394			backend.retire();
395		}
396	}
397
398	/// Return whether the encoder still accepts frames.
399	#[must_use]
400	pub const fn is_open(&self) -> bool {
401		self.state.is_some()
402	}
403
404	/// Return the aligned NV12 coded extent the driver encodes at.
405	#[must_use]
406	pub fn coded_extent(&self) -> Option<VideoExtent> {
407		self.state.as_ref().map(VideoEncoderBackend::coded_extent)
408	}
409
410	/// Return the visible input extent expected by `encode`.
411	#[must_use]
412	pub fn visible_extent(&self) -> Option<VideoExtent> {
413		self.state.as_ref().map(VideoEncoderBackend::visible_extent)
414	}
415
416	/// Borrow the session's cached codec parameter sets in Annex-B form.
417	///
418	/// H.264 sessions carry SPS+PPS and H.265 sessions carry VPS+SPS+PPS; the
419	/// bytes are already prepended to every keyframe packet, so muxers that
420	/// need out-of-band codec configuration should derive it from a keyframe
421	/// or use this reference directly.
422	#[must_use]
423	pub fn codec_headers(&self) -> Option<&[u8]> {
424		self.state.as_ref().map(VideoEncoderBackend::cached_headers)
425	}
426
427	/// Queue one RGBA8 frame asynchronously and harvest completed packets.
428	///
429	/// Crate-internal media bridge — the donor's `VideoEncoderAccess` route
430	/// used by `VideoRecorder`. `color_space` selects the conversion matrix
431	/// (0 = BT.601, 1 = BT.709, 2 = BT.2020); `full_range` selects PC range.
432	pub(crate) fn submit_rgba(
433		&mut self,
434		rgba: &[u8],
435		presentation_timestamp_micros: u64,
436		color_space: u32,
437		full_range: bool,
438	) -> Result<Vec<super::EncodedVideoPacket>> {
439		self
440			.state
441			.as_mut()
442			.ok_or_else(|| Error::failed_precondition("VideoEncoder is closed"))?
443			.submit_rgba(rgba, presentation_timestamp_micros, color_space, full_range)
444	}
445
446	/// Record RGBA8 frame encodes into an active execution capture.
447	///
448	/// Inside [`Engine::capture`] this opens a retained session, records each
449	/// frame's RGBA→native conversion on the compute family and its
450	/// `vkCmdEncodeVideoKHR` picture on the encode family as execution-graph
451	/// nodes, and restores this encoder's live session afterwards. The
452	/// resulting plan replays the same frames without host work; packets
453	/// materialize from the plan's completion `Event` through
454	/// `Event::encoded_packets`.
455	///
456	/// Returns an error outside capture, after close, for an empty frame list,
457	/// or when a frame's length does not match `visible_extent()`.
458	pub fn record_frames(&mut self, frames: &[(&[u8], u64)]) -> Result<()> {
459		let state = self
460			.state
461			.as_mut()
462			.ok_or_else(|| Error::failed_precondition("VideoEncoder is closed"))?;
463		if frames.is_empty() {
464			return Err(Error::invalid_argument(
465				"encode capture requires at least one frame",
466			));
467		}
468		let mut recording = state.begin_encode_capture()?;
469		for (rgba, presentation_timestamp_micros) in frames {
470			// BT.709 limited range — the synchronous encode path's default.
471			recording.record_rgba(rgba, *presentation_timestamp_micros, 1, false)?;
472		}
473		recording.finish_encode_capture()
474	}
475
476	/// Record one frame whose input planes are already engine matrices.
477	///
478	/// Each entry supplies the session's native-format planes in order (Y
479	/// then UV for NV12/P010) plus a presentation timestamp in microseconds.
480	/// Inside [`Engine::capture`], each frame's buffer→image staging records
481	/// on the compute family and its `vkCmdEncodeVideoKHR` picture on the
482	/// encode family, so a decoded-and-transformed `oa::Matrix` plane can be
483	/// re-encoded without a host round trip.
484	///
485	/// Returns an error outside capture, after close, for an empty frame
486	/// list, or when a frame's plane count or extent mismatches the session.
487	pub fn record_planes(&mut self, frames: &[(&[crate::Matrix], u64)]) -> Result<()> {
488		let state = self
489			.state
490			.as_mut()
491			.ok_or_else(|| Error::failed_precondition("VideoEncoder is closed"))?;
492		if frames.is_empty() {
493			return Err(Error::invalid_argument(
494				"encode capture requires at least one frame",
495			));
496		}
497		let mut recording = state.begin_encode_capture()?;
498		for (planes, presentation_timestamp_micros) in frames {
499			recording.record_planes(planes, *presentation_timestamp_micros)?;
500		}
501		recording.finish_encode_capture()
502	}
503}
504
505impl Drop for VideoEncoder {
506	fn drop(&mut self) {
507		self.close();
508	}
509}