forge
Explore
Log in

Don't you dare go Hollow

ec-hw: compiles on every OS; VA (ec-va) is linux-only, pure config/frame types move to ungated types.rs/picture.rs with old paths re-exported

Browse files at this commit

a588a1ea2ba5f066767cdb963a543b1864b48993Ahmet Kaan GümüşParent: 5c027c8
crates/ec-hw/Cargo.tomlmodified+3 -1
@@ -11,9 +11,11 @@ ec-av1-syntax.workspace = true
11 ec-core.workspace = true11 ec-core.workspace = true
12 ec-h264-syntax.workspace = true12 ec-h264-syntax.workspace = true
13 ec-h265-syntax.workspace = true13 ec-h265-syntax.workspace = true
14-ec-va.workspace = true
15 ec-vp9-syntax.workspace = true14 ec-vp9-syntax.workspace = true
16 15
16+[target.'cfg(target_os = "linux")'.dependencies]
17+ec-va.workspace = true
18+
17 [dev-dependencies]19 [dev-dependencies]
18 # The second, independent decoder the AV1 encode gate compares ffmpeg against.20 # The second, independent decoder the AV1 encode gate compares ffmpeg against.
19 ec-av1.workspace = true21 ec-av1.workspace = true
crates/ec-hw/src/dec/mod.rsmodified+2 -12
@@ -30,6 +30,8 @@ use crate::error::{Error, Result};
30 use crate::frame::Frame;30 use crate::frame::Frame;
31 use crate::pool::SurfacePool;31 use crate::pool::SurfacePool;
32 32
33+pub use crate::types::Codec;
34+
33 mod av1;35 mod av1;
34 mod dpb264;36 mod dpb264;
35 mod h264;37 mod h264;
@@ -52,18 +54,6 @@ pub use vp9::fuzz_build_parameters as vp9_fuzz_build_parameters;
52 pub use hevc::HevcDecoder;54 pub use hevc::HevcDecoder;
53 #[doc(hidden)]55 #[doc(hidden)]
54 pub use hevc::fuzz_build_parameters as hevc_fuzz_build_parameters;56 pub use hevc::fuzz_build_parameters as hevc_fuzz_build_parameters;
55-/// The codecs this crate decodes in hardware.
56-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57-pub enum Codec {
58- /// H.264 / AVC, Annex B byte stream.
59- H264,
60- /// H.265 / HEVC, Annex B byte stream.
61- H265,
62- /// VP9, one frame (or superframe) per call.
63- Vp9,
64- /// AV1, one temporal unit per call.
65- Av1,
66-}
67 57
68 /// What the stream turned out to be, once its first headers were parsed.58 /// What the stream turned out to be, once its first headers were parsed.
69 #[derive(Debug, Clone, Copy, PartialEq, Eq)]59 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
crates/ec-hw/src/enc/mod.rsmodified+4 -189
@@ -54,6 +54,10 @@ use crate::error::{Error, Result};
54 use crate::frame::{Frame, I420, I420_16};54 use crate::frame::{Frame, I420, I420_16};
55 use crate::pool::{PooledSurface, SurfacePool};55 use crate::pool::{PooledSurface, SurfacePool};
56 56
57+pub use crate::types::{
58+ CodedFrame, Colour, EncCodec, EncoderConfig, FrameMetadata, H264Profile, RateControlMode, Tunings,
59+};
60+
57 mod av1;61 mod av1;
58 mod h264;62 mod h264;
59 mod headers;63 mod headers;
@@ -63,36 +67,6 @@ mod hevc;
63 /// `VAConfigAttribRateControl` (probed 0x416 = CQP|CBR|VBR|QVBR on mesa 26.1.8).67 /// `VAConfigAttribRateControl` (probed 0x416 = CQP|CBR|VBR|QVBR on mesa 26.1.8).
64 const VA_RC_QVBR: u32 = 0x0000_0400;68 const VA_RC_QVBR: u32 = 0x0000_0400;
65 69
66-/// The codecs this crate encodes in hardware.
67-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68-pub enum EncCodec {
69- /// H.264 / AVC; the profile is [`EncoderConfig::h264_profile`].
70- H264,
71- /// H.265 / HEVC, Main profile.
72- H265,
73- /// AV1 Profile 0.
74- Av1,
75-}
76-
77-/// The H.264 profile an [`Encoder`] writes.
78-///
79-/// Each profile is a strict subset of the next in what a decoder must accept:
80-/// [`H264Profile::ConstrainedBaseline`] is CAVLC with no B slices, [`H264Profile::Main`]
81-/// adds CABAC, and [`H264Profile::High`] adds the High-only SPS tail
82-/// (chroma format, bit depth, scaling lists). This encoder codes no B slices and no
83-/// 8x8 transform, so the three differ only in what the SPS and PPS say.
84-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
85-pub enum H264Profile {
86- /// `profile_idc` 66 with `constraint_set1_flag`; CAVLC entropy coding.
87- ConstrainedBaseline,
88- /// `profile_idc` 77; CABAC entropy coding, no High-only syntax.
89- Main,
90- /// `profile_idc` 100; CABAC, with the High SPS tail. The default, and what
91- /// this encoder wrote before the profile was selectable.
92- #[default]
93- High,
94-}
95-
96 impl H264Profile {70 impl H264Profile {
97 /// The VA profile the driver is asked for.71 /// The VA profile the driver is asked for.
98 fn va_profile(self) -> Profile {72 fn va_profile(self) -> Profile {
@@ -102,11 +76,6 @@ impl H264Profile {
102 H264Profile::High => Profile::H264High,76 H264Profile::High => Profile::H264High,
103 }77 }
104 }78 }
105-
106- /// True when the slice data is CABAC (`entropy_coding_mode_flag` = 1).
107- pub(crate) fn cabac(self) -> bool {
108- !matches!(self, H264Profile::ConstrainedBaseline)
109- }
110 }79 }
111 80
112 /// The rate window the request is spread over, in milliseconds (`window_size`).81 /// The rate window the request is spread over, in milliseconds (`window_size`).
@@ -167,28 +136,6 @@ impl Default for RateFeedback {
167 }136 }
168 }137 }
169 138
170-/// How the driver should spend bits.
171-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172-pub enum RateControlMode {
173- /// Constant quantiser: `qp` for every picture, bitrate ignored.
174- ConstantQp {
175- /// The quantiser, 0..51 for H.264/HEVC, 0..255 for AV1.
176- qp: u32,
177- },
178- /// Constant bitrate, the driver picking quantisers to hold it.
179- ConstantBitrate,
180- /// Variable bitrate: `bitrate` is the average asked for, and the driver
181- /// may spend up to 1.5x it inside the rate window.
182- VariableBitrate,
183- /// Quality-defined variable bitrate: the driver holds `quality` (a
184- /// quantiser-like target, lower is better quality) and treats `bitrate`
185- /// as the ceiling it may not exceed.
186- Qvbr {
187- /// The quality factor, in the codec's quantiser scale.
188- quality: u32,
189- },
190-}
191-
192 impl RateControlMode {139 impl RateControlMode {
193 /// The `VAConfigAttribRateControl` value this mode is configured with.140 /// The `VAConfigAttribRateControl` value this mode is configured with.
194 ///141 ///
@@ -203,138 +150,6 @@ impl RateControlMode {
203 RateControlMode::Qvbr { .. } => VA_RC_QVBR,150 RateControlMode::Qvbr { .. } => VA_RC_QVBR,
204 }151 }
205 }152 }
206-
207- /// True when the driver is told exactly which quantiser to use, so it has
208- /// nothing to back-annotate into the header this crate packs.
209- pub(crate) fn is_cqp(self) -> bool {
210- matches!(self, RateControlMode::ConstantQp { .. })
211- }
212-}
213-
214-/// What can be changed between frames without rebuilding the encoder.
215-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
216-pub struct Tunings {
217- /// Target bitrate in bits per second.
218- pub bitrate: u32,
219- /// Frame rate as `(numerator, denominator)`.
220- pub framerate: (u32, u32),
221-}
222-
223-/// Per-frame instructions from the caller.
224-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
225-pub struct FrameMetadata {
226- /// Presentation timestamp, carried through to the coded frame.
227- pub timestamp: i64,
228- /// Start a new GOP with this frame.
229- pub force_keyframe: bool,
230-}
231-
232-/// How an encoder is set up.
233-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
234-pub struct EncoderConfig {
235- /// Which codec.
236- pub codec: EncCodec,
237- /// Displayed width; the coded size is rounded up for the codec's blocks.
238- pub width: u32,
239- /// Displayed height.
240- pub height: u32,
241- /// Frame rate as `(numerator, denominator)`.
242- pub framerate: (u32, u32),
243- /// Target bitrate in bits per second.
244- pub bitrate: u32,
245- /// Pictures per GOP; the first of each is an IDR / key frame.
246- pub gop_size: u32,
247- /// The H.264 profile to write (ignored by HEVC and AV1).
248- pub h264_profile: H264Profile,
249- /// Rate control mode.
250- pub rate_control: RateControlMode,
251- /// Driver quality/speed level, 1 (best quality) upwards; 0 = driver default.
252- pub quality: u32,
253- /// The colour description to write into the VUI, or `None` to leave it
254- /// unsignalled (`video_signal_type_present_flag = 0`) as before.
255- pub colour: Option<Colour>,
256- /// Luma bit depth: 8, or 10 for AV1 (his own library is `yuv420p10le`).
257- /// A 10-bit encoder takes its pixels through [`Encoder::encode_16`] or
258- /// straight from a 10-bit [`crate::Frame`].
259- pub bit_depth: u8,
260-}
261-
262-/// H.265 E.2.1 / H.264 E.1.1 colour description code points for the VUI.
263-///
264-/// Carried verbatim into `colour_primaries`, `transfer_characteristics` and
265-/// `matrix_coeffs` — this crate does not interpret them, so a caller wanting
266-/// BT.2020/PQ passes `(9, 16, 9)`, BT.709 SDR `(1, 1, 1)`, and so on (H.273
267-/// tables 2/3/4).
268-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
269-pub struct Colour {
270- /// `colour_primaries`.
271- pub primaries: u8,
272- /// `transfer_characteristics`.
273- pub transfer: u8,
274- /// `matrix_coeffs`.
275- pub matrix: u8,
276- /// `video_full_range_flag`.
277- pub full_range: bool,
278-}
279-
280-impl EncoderConfig {
281- /// A configuration with sensible defaults for `codec` at `width x height`.
282- pub fn new(codec: EncCodec, width: u32, height: u32) -> EncoderConfig {
283- EncoderConfig {
284- codec,
285- width,
286- height,
287- framerate: (30, 1),
288- bitrate: 8_000_000,
289- gop_size: 60,
290- h264_profile: H264Profile::High,
291- rate_control: RateControlMode::ConstantBitrate,
292- quality: 0,
293- colour: None,
294- bit_depth: 8,
295- }
296- }
297-
298- /// Encode at 10 bits (H.265 Main10 or AV1); see [`EncoderConfig::bit_depth`].
299- pub fn ten_bit(mut self) -> EncoderConfig {
300- self.bit_depth = 10;
301- self
302- }
303-
304- /// Choose the H.264 profile written into the SPS and PPS.
305- pub fn h264_profile(mut self, profile: H264Profile) -> EncoderConfig {
306- self.h264_profile = profile;
307- self
308- }
309-
310- /// Set the VUI colour description; H.265 E.2.1 / H.264 E.1.1 code points.
311- pub fn colour(
312- mut self,
313- primaries: u8,
314- transfer: u8,
315- matrix: u8,
316- full_range: bool,
317- ) -> EncoderConfig {
318- self.colour = Some(Colour {
319- primaries,
320- transfer,
321- matrix,
322- full_range,
323- });
324- self
325- }
326-}
327-
328-/// One coded picture.
329-#[derive(Debug, Clone, PartialEq, Eq)]
330-pub struct CodedFrame {
331- /// The bitstream: an Annex B access unit for H.264/HEVC, an OBU sequence
332- /// for AV1.
333- pub data: Vec<u8>,
334- /// The timestamp the caller supplied with the source frame.
335- pub timestamp: i64,
336- /// True for an IDR / key frame.
337- pub is_keyframe: bool,
338 }153 }
339 154
340 /// A picture submitted but not yet read back.155 /// A picture submitted but not yet read back.
crates/ec-hw/src/error.rsmodified+5 -0
@@ -17,6 +17,7 @@ pub type Result<T> = std::result::Result<T, Error>;
17 #[non_exhaustive]17 #[non_exhaustive]
18 pub enum Error {18 pub enum Error {
19 /// A libva call failed, or the driver contradicted its own API.19 /// A libva call failed, or the driver contradicted its own API.
20+ #[cfg(target_os = "linux")]
20 Va(ec_va::Error),21 Va(ec_va::Error),
21 /// The bitstream could not be parsed.22 /// The bitstream could not be parsed.
22 Stream(ec_core::Error),23 Stream(ec_core::Error),
@@ -68,12 +69,14 @@ impl Error {
68 /// The raw `VAStatus`, when this came from a libva call.69 /// The raw `VAStatus`, when this came from a libva call.
69 pub fn va_status(&self) -> Option<i32> {70 pub fn va_status(&self) -> Option<i32> {
70 match self {71 match self {
72+ #[cfg(target_os = "linux")]
71 Error::Va(e) => e.status(),73 Error::Va(e) => e.status(),
72 _ => None,74 _ => None,
73 }75 }
74 }76 }
75 }77 }
76 78
79+#[cfg(target_os = "linux")]
77 impl From<ec_va::Error> for Error {80 impl From<ec_va::Error> for Error {
78 fn from(e: ec_va::Error) -> Error {81 fn from(e: ec_va::Error) -> Error {
79 Error::Va(e)82 Error::Va(e)
@@ -89,6 +92,7 @@ impl From<ec_core::Error> for Error {
89 impl fmt::Display for Error {92 impl fmt::Display for Error {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 match self {94 match self {
95+ #[cfg(target_os = "linux")]
92 Error::Va(e) => write!(f, "VA-API: {e}"),96 Error::Va(e) => write!(f, "VA-API: {e}"),
93 Error::Stream(e) => write!(f, "bitstream: {e}"),97 Error::Stream(e) => write!(f, "bitstream: {e}"),
94 Error::Unsupported { what, why } => write!(f, "{what} is not supported: {why}"),98 Error::Unsupported { what, why } => write!(f, "{what} is not supported: {why}"),
@@ -101,6 +105,7 @@ impl fmt::Display for Error {
101 impl std::error::Error for Error {105 impl std::error::Error for Error {
102 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {106 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
103 match self {107 match self {
108+ #[cfg(target_os = "linux")]
104 Error::Va(e) => Some(e),109 Error::Va(e) => Some(e),
105 Error::Stream(e) => Some(e),110 Error::Stream(e) => Some(e),
106 _ => None,111 _ => None,
crates/ec-hw/src/frame.rsmodified+1 -116
@@ -3,26 +3,13 @@
3 3
4 use std::rc::Rc;4 use std::rc::Rc;
5 5
6-use ec_core::color::{ColorDescription, ContentLight};
7 use ec_va::va::{VA_FOURCC_NV12, VA_FOURCC_P010};6 use ec_va::va::{VA_FOURCC_NV12, VA_FOURCC_P010};
8 use ec_va::{Display, Image, PrimeSurface, Surface, SurfaceExt};7 use ec_va::{Display, Image, PrimeSurface, Surface, SurfaceExt};
9 8
10 use crate::error::{Error, Result};9 use crate::error::{Error, Result};
11 use crate::pool::PooledSurface;10 use crate::pool::PooledSurface;
12 11
13-/// A stream's colour metadata, resolved from its own headers: VUI tags for the12+pub use crate::picture::{Colour, I420, I420_16, i420_to_nv12, nv12_to_i420};
14-/// primaries/transfer/matrix triplet, and — for HEVC — the two HDR prefix SEI
15-/// messages for the peak the mastering grade and the content itself declared.
16-/// No container tier here: ec-hw only ever sees the elementary stream, so a
17-/// caller that also holds the container's tags resolves those over this.
18-#[derive(Debug, Clone, Copy, PartialEq)]
19-pub struct Colour {
20- /// Matrix/transfer/range, resolved from the bitstream's own VUI.
21- pub description: ColorDescription,
22- /// HDR peak: MaxCLL/MaxFALL and the mastering display's luminance, when
23- /// the stream carried them (HEVC prefix SEI only).
24- pub light: ContentLight,
25-}
26 13
27 /// One decoded picture, in display order.14 /// One decoded picture, in display order.
28 ///15 ///
@@ -46,38 +33,6 @@ pub struct Frame {
46 epoch: u64,33 epoch: u64,
47 }34 }
48 35
49-/// 8-bit planar 4:2:0, the currency edith's software path speaks.
50-#[derive(Debug, Clone, PartialEq, Eq)]
51-pub struct I420 {
52- /// Luma plane, `width * height`.
53- pub y: Vec<u8>,
54- /// Cb plane, `(width + 1) / 2 * ((height + 1) / 2)`.
55- pub u: Vec<u8>,
56- /// Cr plane, same size as `u`.
57- pub v: Vec<u8>,
58- /// Width in luma samples.
59- pub width: u32,
60- /// Height in luma samples.
61- pub height: u32,
62-}
63-
64-/// 10-bit planar 4:2:0, samples right-aligned in the low 10 bits.
65-#[derive(Debug, Clone, PartialEq, Eq)]
66-pub struct I420_16 {
67- /// Luma plane.
68- pub y: Vec<u16>,
69- /// Cb plane.
70- pub u: Vec<u16>,
71- /// Cr plane.
72- pub v: Vec<u16>,
73- /// Width in luma samples.
74- pub width: u32,
75- /// Height in luma samples.
76- pub height: u32,
77- /// Luma bit depth: always 10 for this format.
78- pub bit_depth: u8,
79-}
80-
81 impl Frame {36 impl Frame {
82 pub(crate) fn new(37 pub(crate) fn new(
83 surface: Rc<PooledSurface>,38 surface: Rc<PooledSurface>,
@@ -391,76 +346,6 @@ fn check_plane(name: &str, len: usize, pitch: usize, rows: usize, row_bytes: usi
391 }346 }
392 }347 }
393 348
394-/// Deinterleave an NV12 chroma plane into I420 U and V planes.
395-///
396-/// The same conversion the software path in edith expects on the way out of a
397-/// hardware frame; kept as a free function because an encoder's input path
398-/// needs it in reverse.
399-pub fn nv12_to_i420(
400- y_plane: &[u8],
401- y_pitch: usize,
402- uv_plane: &[u8],
403- uv_pitch: usize,
404- width: usize,
405- height: usize,
406-) -> I420 {
407- let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
408- let mut out = I420 {
409- y: vec![0; width * height],
410- u: vec![0; cw * ch],
411- v: vec![0; cw * ch],
412- width: width as u32,
413- height: height as u32,
414- };
415- for row in 0..height {
416- let src = row * y_pitch;
417- if src + width > y_plane.len() {
418- break;
419- }
420- out.y[row * width..(row + 1) * width].copy_from_slice(&y_plane[src..src + width]);
421- }
422- for row in 0..ch {
423- let src = row * uv_pitch;
424- if src + cw * 2 > uv_plane.len() {
425- break;
426- }
427- for col in 0..cw {
428- out.u[row * cw + col] = uv_plane[src + col * 2];
429- out.v[row * cw + col] = uv_plane[src + col * 2 + 1];
430- }
431- }
432- out
433-}
434-
435-/// Interleave I420 chroma into an NV12 buffer, for the encoder input path.
436-pub fn i420_to_nv12(
437- src: &I420,
438- y_out: &mut [u8],
439- y_pitch: usize,
440- uv_out: &mut [u8],
441- uv_pitch: usize,
442-) {
443- let (w, h) = (src.width as usize, src.height as usize);
444- let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
445- for row in 0..h {
446- let dst = row * y_pitch;
447- if dst + w > y_out.len() {
448- break;
449- }
450- y_out[dst..dst + w].copy_from_slice(&src.y[row * w..row * w + w]);
451- }
452- for row in 0..ch {
453- let dst = row * uv_pitch;
454- if dst + cw * 2 > uv_out.len() {
455- break;
456- }
457- for col in 0..cw {
458- uv_out[dst + col * 2] = src.u[row * cw + col];
459- uv_out[dst + col * 2 + 1] = src.v[row * cw + col];
460- }
461- }
462-}
463-
464 #[cfg(test)]349 #[cfg(test)]
465 mod tests {350 mod tests {
466 use super::*;351 use super::*;
crates/ec-hw/src/lib.rsmodified+19 -6
@@ -54,20 +54,33 @@
54 #![forbid(unsafe_code)]54 #![forbid(unsafe_code)]
55 #![deny(missing_docs)]55 #![deny(missing_docs)]
56 56
57+#[cfg(target_os = "linux")]
57 pub mod dec;58 pub mod dec;
59+#[cfg(target_os = "linux")]
58 pub mod enc;60 pub mod enc;
59 pub mod error;61 pub mod error;
62+#[cfg(target_os = "linux")]
60 pub mod frame;63 pub mod frame;
64+pub mod picture;
65+#[cfg(target_os = "linux")]
61 pub mod params;66 pub mod params;
67+#[cfg(target_os = "linux")]
62 pub mod pool;68 pub mod pool;
63 pub mod reset;69 pub mod reset;
70+pub mod types;
64 71
65-pub use dec::{Codec, Decoder, StreamInfo};72+#[cfg(target_os = "linux")]
66-pub use enc::{73+pub use dec::{Decoder, StreamInfo};
67- CodedFrame, EncCodec, Encoder, EncoderConfig, FrameMetadata, H264Profile, RateControlMode,74+#[cfg(target_os = "linux")]
68- Tunings,75+pub use enc::Encoder;
69-};
70 pub use error::{Error, Result};76 pub use error::{Error, Result};
71-pub use frame::{Colour, Frame, I420, I420_16, i420_to_nv12, nv12_to_i420};77+#[cfg(target_os = "linux")]
78+pub use frame::Frame;
79+pub use picture::{Colour, I420, I420_16, i420_to_nv12, nv12_to_i420};
80+#[cfg(target_os = "linux")]
72 pub use pool::{PooledSurface, SurfacePool};81 pub use pool::{PooledSurface, SurfacePool};
73 pub use reset::{gpu_recently_reset, gpu_reset_epoch, report_gpu_reset};82 pub use reset::{gpu_recently_reset, gpu_reset_epoch, report_gpu_reset};
83+pub use types::{
84+ Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, H264Profile, RateControlMode,
85+ Tunings,
86+};
crates/ec-hw/src/picture.rsadded+120 -0
@@ -0,0 +1,120 @@
1+//! Pixel buffers and conversions that need no VA-API: planar I420 and its
2+//! 10-bit sibling, the colour metadata, and the NV12 conversions.
3+
4+use ec_core::color::{ColorDescription, ContentLight};
5+
6+/// A stream's colour metadata, resolved from its own headers: VUI tags for the
7+/// primaries/transfer/matrix triplet, and — for HEVC — the two HDR prefix SEI
8+/// messages for the peak the mastering grade and the content itself declared.
9+/// No container tier here: ec-hw only ever sees the elementary stream, so a
10+/// caller that also holds the container's tags resolves those over this.
11+#[derive(Debug, Clone, Copy, PartialEq)]
12+pub struct Colour {
13+ /// Matrix/transfer/range, resolved from the bitstream's own VUI.
14+ pub description: ColorDescription,
15+ /// HDR peak: MaxCLL/MaxFALL and the mastering display's luminance, when
16+ /// the stream carried them (HEVC prefix SEI only).
17+ pub light: ContentLight,
18+}
19+
20+/// 8-bit planar 4:2:0, the currency edith's software path speaks.
21+#[derive(Debug, Clone, PartialEq, Eq)]
22+pub struct I420 {
23+ /// Luma plane, `width * height`.
24+ pub y: Vec<u8>,
25+ /// Cb plane, `(width + 1) / 2 * ((height + 1) / 2)`.
26+ pub u: Vec<u8>,
27+ /// Cr plane, same size as `u`.
28+ pub v: Vec<u8>,
29+ /// Width in luma samples.
30+ pub width: u32,
31+ /// Height in luma samples.
32+ pub height: u32,
33+}
34+
35+/// 10-bit planar 4:2:0, samples right-aligned in the low 10 bits.
36+#[derive(Debug, Clone, PartialEq, Eq)]
37+pub struct I420_16 {
38+ /// Luma plane.
39+ pub y: Vec<u16>,
40+ /// Cb plane.
41+ pub u: Vec<u16>,
42+ /// Cr plane.
43+ pub v: Vec<u16>,
44+ /// Width in luma samples.
45+ pub width: u32,
46+ /// Height in luma samples.
47+ pub height: u32,
48+ /// Luma bit depth: always 10 for this format.
49+ pub bit_depth: u8,
50+}
51+
52+/// Deinterleave an NV12 chroma plane into I420 U and V planes.
53+///
54+/// The same conversion the software path in edith expects on the way out of a
55+/// hardware frame; kept as a free function because an encoder's input path
56+/// needs it in reverse.
57+pub fn nv12_to_i420(
58+ y_plane: &[u8],
59+ y_pitch: usize,
60+ uv_plane: &[u8],
61+ uv_pitch: usize,
62+ width: usize,
63+ height: usize,
64+) -> I420 {
65+ let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
66+ let mut out = I420 {
67+ y: vec![0; width * height],
68+ u: vec![0; cw * ch],
69+ v: vec![0; cw * ch],
70+ width: width as u32,
71+ height: height as u32,
72+ };
73+ for row in 0..height {
74+ let src = row * y_pitch;
75+ if src + width > y_plane.len() {
76+ break;
77+ }
78+ out.y[row * width..(row + 1) * width].copy_from_slice(&y_plane[src..src + width]);
79+ }
80+ for row in 0..ch {
81+ let src = row * uv_pitch;
82+ if src + cw * 2 > uv_plane.len() {
83+ break;
84+ }
85+ for col in 0..cw {
86+ out.u[row * cw + col] = uv_plane[src + col * 2];
87+ out.v[row * cw + col] = uv_plane[src + col * 2 + 1];
88+ }
89+ }
90+ out
91+}
92+
93+/// Interleave I420 chroma into an NV12 buffer, for the encoder input path.
94+pub fn i420_to_nv12(
95+ src: &I420,
96+ y_out: &mut [u8],
97+ y_pitch: usize,
98+ uv_out: &mut [u8],
99+ uv_pitch: usize,
100+) {
101+ let (w, h) = (src.width as usize, src.height as usize);
102+ let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
103+ for row in 0..h {
104+ let dst = row * y_pitch;
105+ if dst + w > y_out.len() {
106+ break;
107+ }
108+ y_out[dst..dst + w].copy_from_slice(&src.y[row * w..row * w + w]);
109+ }
110+ for row in 0..ch {
111+ let dst = row * uv_pitch;
112+ if dst + cw * 2 > uv_out.len() {
113+ break;
114+ }
115+ for col in 0..cw {
116+ uv_out[dst + col * 2] = src.u[row * cw + col];
117+ uv_out[dst + col * 2 + 1] = src.v[row * cw + col];
118+ }
119+ }
120+}
crates/ec-hw/src/reset.rsmodified+3 -0
@@ -57,14 +57,17 @@ impl ResetClock {
57 }57 }
58 58
59 /// Hard limit on one wait for a picture; past it the sync gives up.59 /// Hard limit on one wait for a picture; past it the sync gives up.
60+#[cfg(target_os = "linux")]
60 pub(crate) const SYNC_LIMIT: Duration = Duration::from_secs(8);61 pub(crate) const SYNC_LIMIT: Duration = Duration::from_secs(8);
61 62
62 /// A wait that took longer than this spent its time in a ring reset: a63 /// A wait that took longer than this spent its time in a ring reset: a
63 /// healthy picture takes milliseconds. 1080p..8K pictures stay far below it.64 /// healthy picture takes milliseconds. 1080p..8K pictures stay far below it.
65+#[cfg(target_os = "linux")]
64 pub(crate) const SLOW_PICTURE: Duration = Duration::from_millis(1500);66 pub(crate) const SLOW_PICTURE: Duration = Duration::from_millis(1500);
65 67
66 /// Wait for `surface`, and condemn every session if the wait shows that the68 /// Wait for `surface`, and condemn every session if the wait shows that the
67 /// GPU was reset: an error, or a wait longer than [`SLOW_PICTURE`].69 /// GPU was reset: an error, or a wait longer than [`SLOW_PICTURE`].
70+#[cfg(target_os = "linux")]
68 pub(crate) fn sync_watched<D: ec_va::va::SurfaceMemoryDescriptor>(71 pub(crate) fn sync_watched<D: ec_va::va::SurfaceMemoryDescriptor>(
69 surface: &ec_va::va::Surface<D>,72 surface: &ec_va::va::Surface<D>,
70 ) -> crate::Result<()> {73 ) -> crate::Result<()> {
crates/ec-hw/src/types.rsadded+209 -0
@@ -0,0 +1,209 @@
1+//! Platform-neutral types shared by the hardware encoder and decoder.
2+
3+/// The codecs this crate encodes in hardware.
4+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5+pub enum EncCodec {
6+ /// H.264 / AVC; the profile is [`EncoderConfig::h264_profile`].
7+ H264,
8+ /// H.265 / HEVC, Main profile.
9+ H265,
10+ /// AV1 Profile 0.
11+ Av1,
12+}
13+
14+/// The H.264 profile an [`Encoder`] writes.
15+///
16+/// Each profile is a strict subset of the next in what a decoder must accept:
17+/// [`H264Profile::ConstrainedBaseline`] is CAVLC with no B slices, [`H264Profile::Main`]
18+/// adds CABAC, and [`H264Profile::High`] adds the High-only SPS tail
19+/// (chroma format, bit depth, scaling lists). This encoder codes no B slices and no
20+/// 8x8 transform, so the three differ only in what the SPS and PPS say.
21+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
22+pub enum H264Profile {
23+ /// `profile_idc` 66 with `constraint_set1_flag`; CAVLC entropy coding.
24+ ConstrainedBaseline,
25+ /// `profile_idc` 77; CABAC entropy coding, no High-only syntax.
26+ Main,
27+ /// `profile_idc` 100; CABAC, with the High SPS tail. The default, and what
28+ /// this encoder wrote before the profile was selectable.
29+ #[default]
30+ High,
31+}
32+
33+impl H264Profile {
34+ /// True when the slice data is CABAC (`entropy_coding_mode_flag` = 1).
35+ #[cfg(target_os = "linux")]
36+ pub(crate) fn cabac(self) -> bool {
37+ !matches!(self, H264Profile::ConstrainedBaseline)
38+ }
39+}
40+
41+/// How the driver should spend bits.
42+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43+pub enum RateControlMode {
44+ /// Constant quantiser: `qp` for every picture, bitrate ignored.
45+ ConstantQp {
46+ /// The quantiser, 0..51 for H.264/HEVC, 0..255 for AV1.
47+ qp: u32,
48+ },
49+ /// Constant bitrate, the driver picking quantisers to hold it.
50+ ConstantBitrate,
51+ /// Variable bitrate: `bitrate` is the average asked for, and the driver
52+ /// may spend up to 1.5x it inside the rate window.
53+ VariableBitrate,
54+ /// Quality-defined variable bitrate: the driver holds `quality` (a
55+ /// quantiser-like target, lower is better quality) and treats `bitrate`
56+ /// as the ceiling it may not exceed.
57+ Qvbr {
58+ /// The quality factor, in the codec's quantiser scale.
59+ quality: u32,
60+ },
61+}
62+
63+impl RateControlMode {
64+ /// True when the driver is told exactly which quantiser to use, so it has
65+ /// nothing to back-annotate into the header this crate packs.
66+ #[cfg(target_os = "linux")]
67+ pub(crate) fn is_cqp(self) -> bool {
68+ matches!(self, RateControlMode::ConstantQp { .. })
69+ }
70+}
71+
72+/// What can be changed between frames without rebuilding the encoder.
73+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74+pub struct Tunings {
75+ /// Target bitrate in bits per second.
76+ pub bitrate: u32,
77+ /// Frame rate as `(numerator, denominator)`.
78+ pub framerate: (u32, u32),
79+}
80+
81+/// Per-frame instructions from the caller.
82+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
83+pub struct FrameMetadata {
84+ /// Presentation timestamp, carried through to the coded frame.
85+ pub timestamp: i64,
86+ /// Start a new GOP with this frame.
87+ pub force_keyframe: bool,
88+}
89+
90+/// How an encoder is set up.
91+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92+pub struct EncoderConfig {
93+ /// Which codec.
94+ pub codec: EncCodec,
95+ /// Displayed width; the coded size is rounded up for the codec's blocks.
96+ pub width: u32,
97+ /// Displayed height.
98+ pub height: u32,
99+ /// Frame rate as `(numerator, denominator)`.
100+ pub framerate: (u32, u32),
101+ /// Target bitrate in bits per second.
102+ pub bitrate: u32,
103+ /// Pictures per GOP; the first of each is an IDR / key frame.
104+ pub gop_size: u32,
105+ /// The H.264 profile to write (ignored by HEVC and AV1).
106+ pub h264_profile: H264Profile,
107+ /// Rate control mode.
108+ pub rate_control: RateControlMode,
109+ /// Driver quality/speed level, 1 (best quality) upwards; 0 = driver default.
110+ pub quality: u32,
111+ /// The colour description to write into the VUI, or `None` to leave it
112+ /// unsignalled (`video_signal_type_present_flag = 0`) as before.
113+ pub colour: Option<Colour>,
114+ /// Luma bit depth: 8, or 10 for AV1 (his own library is `yuv420p10le`).
115+ /// A 10-bit encoder takes its pixels through [`Encoder::encode_16`] or
116+ /// straight from a 10-bit [`crate::Frame`].
117+ pub bit_depth: u8,
118+}
119+
120+/// H.265 E.2.1 / H.264 E.1.1 colour description code points for the VUI.
121+///
122+/// Carried verbatim into `colour_primaries`, `transfer_characteristics` and
123+/// `matrix_coeffs` — this crate does not interpret them, so a caller wanting
124+/// BT.2020/PQ passes `(9, 16, 9)`, BT.709 SDR `(1, 1, 1)`, and so on (H.273
125+/// tables 2/3/4).
126+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127+pub struct Colour {
128+ /// `colour_primaries`.
129+ pub primaries: u8,
130+ /// `transfer_characteristics`.
131+ pub transfer: u8,
132+ /// `matrix_coeffs`.
133+ pub matrix: u8,
134+ /// `video_full_range_flag`.
135+ pub full_range: bool,
136+}
137+
138+impl EncoderConfig {
139+ /// A configuration with sensible defaults for `codec` at `width x height`.
140+ pub fn new(codec: EncCodec, width: u32, height: u32) -> EncoderConfig {
141+ EncoderConfig {
142+ codec,
143+ width,
144+ height,
145+ framerate: (30, 1),
146+ bitrate: 8_000_000,
147+ gop_size: 60,
148+ h264_profile: H264Profile::High,
149+ rate_control: RateControlMode::ConstantBitrate,
150+ quality: 0,
151+ colour: None,
152+ bit_depth: 8,
153+ }
154+ }
155+
156+ /// Encode at 10 bits (H.265 Main10 or AV1); see [`EncoderConfig::bit_depth`].
157+ pub fn ten_bit(mut self) -> EncoderConfig {
158+ self.bit_depth = 10;
159+ self
160+ }
161+
162+ /// Choose the H.264 profile written into the SPS and PPS.
163+ pub fn h264_profile(mut self, profile: H264Profile) -> EncoderConfig {
164+ self.h264_profile = profile;
165+ self
166+ }
167+
168+ /// Set the VUI colour description; H.265 E.2.1 / H.264 E.1.1 code points.
169+ pub fn colour(
170+ mut self,
171+ primaries: u8,
172+ transfer: u8,
173+ matrix: u8,
174+ full_range: bool,
175+ ) -> EncoderConfig {
176+ self.colour = Some(Colour {
177+ primaries,
178+ transfer,
179+ matrix,
180+ full_range,
181+ });
182+ self
183+ }
184+}
185+
186+/// One coded picture.
187+#[derive(Debug, Clone, PartialEq, Eq)]
188+pub struct CodedFrame {
189+ /// The bitstream: an Annex B access unit for H.264/HEVC, an OBU sequence
190+ /// for AV1.
191+ pub data: Vec<u8>,
192+ /// The timestamp the caller supplied with the source frame.
193+ pub timestamp: i64,
194+ /// True for an IDR / key frame.
195+ pub is_keyframe: bool,
196+}
197+
198+/// The codecs this crate decodes in hardware.
199+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
200+pub enum Codec {
201+ /// H.264 / AVC, Annex B byte stream.
202+ H264,
203+ /// H.265 / HEVC, Annex B byte stream.
204+ H265,
205+ /// VP9, one frame (or superframe) per call.
206+ Vp9,
207+ /// AV1, one temporal unit per call.
208+ Av1,
209+}