1use crate::{Error, Result, Runtime, runtime::VideoEncoderBackend};
8
9use super::{
10 VideoChromaSubsampling, VideoComponentBitDepth, VideoEncodeCapabilities,
11 VideoEncodeCodecCapabilities, VideoEncodeProfile, VideoExtent,
12};
13pub use crate::video::types::VideoEncodeConfig;
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum VideoRateControl {
18 ConstantQp,
19 Cbr,
20 Vbr,
21}
22
23impl VideoEncodeConfig {
24 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 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#[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 pub const fn h264_level(self) -> Option<u32> {
246 self.h264_level
247 }
248}
249
250fn 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
284pub struct VideoEncoder {
301 state: Option<VideoEncoderBackend>,
302}
303
304impl VideoEncoder {
305 pub fn new(runtime: &Runtime, settings: VideoEncodeConfig) -> Result<Self> {
317 Ok(Self {
318 state: Some(VideoEncoderBackend::create(runtime, settings)?),
319 })
320 }
321
322 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 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 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 pub fn close(&mut self) {
393 if let Some(backend) = self.state.take() {
394 backend.retire();
395 }
396 }
397
398 #[must_use]
400 pub const fn is_open(&self) -> bool {
401 self.state.is_some()
402 }
403
404 #[must_use]
406 pub fn coded_extent(&self) -> Option<VideoExtent> {
407 self.state.as_ref().map(VideoEncoderBackend::coded_extent)
408 }
409
410 #[must_use]
412 pub fn visible_extent(&self) -> Option<VideoExtent> {
413 self.state.as_ref().map(VideoEncoderBackend::visible_extent)
414 }
415
416 #[must_use]
423 pub fn codec_headers(&self) -> Option<&[u8]> {
424 self.state.as_ref().map(VideoEncoderBackend::cached_headers)
425 }
426
427 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 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 recording.record_rgba(rgba, *presentation_timestamp_micros, 1, false)?;
472 }
473 recording.finish_encode_capture()
474 }
475
476 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}