From a588a1ea2ba5f066767cdb963a543b1864b48993 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 25 Nov 2026 08:28:30 +0300 Subject: [PATCH] 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 --- crates/ec-hw/Cargo.toml | 4 +- crates/ec-hw/src/dec/mod.rs | 14 +-- crates/ec-hw/src/enc/mod.rs | 193 +-------------------------------- crates/ec-hw/src/error.rs | 5 + crates/ec-hw/src/frame.rs | 117 +------------------- crates/ec-hw/src/lib.rs | 25 +++-- crates/ec-hw/src/picture.rs | 120 +++++++++++++++++++++ crates/ec-hw/src/reset.rs | 3 + crates/ec-hw/src/types.rs | 209 ++++++++++++++++++++++++++++++++++++ 9 files changed, 366 insertions(+), 324 deletions(-) create mode 100644 crates/ec-hw/src/picture.rs create mode 100644 crates/ec-hw/src/types.rs diff --git a/crates/ec-hw/Cargo.toml b/crates/ec-hw/Cargo.toml index 69485502..0bd2e617 100644 --- a/crates/ec-hw/Cargo.toml +++ b/crates/ec-hw/Cargo.toml @@ -11,9 +11,11 @@ ec-av1-syntax.workspace = true ec-core.workspace = true ec-h264-syntax.workspace = true ec-h265-syntax.workspace = true -ec-va.workspace = true ec-vp9-syntax.workspace = true +[target.'cfg(target_os = "linux")'.dependencies] +ec-va.workspace = true + [dev-dependencies] # The second, independent decoder the AV1 encode gate compares ffmpeg against. ec-av1.workspace = true diff --git a/crates/ec-hw/src/dec/mod.rs b/crates/ec-hw/src/dec/mod.rs index d1542d88..215fa262 100644 --- a/crates/ec-hw/src/dec/mod.rs +++ b/crates/ec-hw/src/dec/mod.rs @@ -30,6 +30,8 @@ use crate::error::{Error, Result}; use crate::frame::Frame; use crate::pool::SurfacePool; +pub use crate::types::Codec; + mod av1; mod dpb264; mod h264; @@ -52,18 +54,6 @@ pub use vp9::fuzz_build_parameters as vp9_fuzz_build_parameters; pub use hevc::HevcDecoder; #[doc(hidden)] pub use hevc::fuzz_build_parameters as hevc_fuzz_build_parameters; -/// The codecs this crate decodes in hardware. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Codec { - /// H.264 / AVC, Annex B byte stream. - H264, - /// H.265 / HEVC, Annex B byte stream. - H265, - /// VP9, one frame (or superframe) per call. - Vp9, - /// AV1, one temporal unit per call. - Av1, -} /// What the stream turned out to be, once its first headers were parsed. #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/ec-hw/src/enc/mod.rs b/crates/ec-hw/src/enc/mod.rs index 07c7f997..8251414d 100644 --- a/crates/ec-hw/src/enc/mod.rs +++ b/crates/ec-hw/src/enc/mod.rs @@ -54,6 +54,10 @@ use crate::error::{Error, Result}; use crate::frame::{Frame, I420, I420_16}; use crate::pool::{PooledSurface, SurfacePool}; +pub use crate::types::{ + CodedFrame, Colour, EncCodec, EncoderConfig, FrameMetadata, H264Profile, RateControlMode, Tunings, +}; + mod av1; mod h264; mod headers; @@ -63,36 +67,6 @@ mod hevc; /// `VAConfigAttribRateControl` (probed 0x416 = CQP|CBR|VBR|QVBR on mesa 26.1.8). const VA_RC_QVBR: u32 = 0x0000_0400; -/// The codecs this crate encodes in hardware. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum EncCodec { - /// H.264 / AVC; the profile is [`EncoderConfig::h264_profile`]. - H264, - /// H.265 / HEVC, Main profile. - H265, - /// AV1 Profile 0. - Av1, -} - -/// The H.264 profile an [`Encoder`] writes. -/// -/// Each profile is a strict subset of the next in what a decoder must accept: -/// [`H264Profile::ConstrainedBaseline`] is CAVLC with no B slices, [`H264Profile::Main`] -/// adds CABAC, and [`H264Profile::High`] adds the High-only SPS tail -/// (chroma format, bit depth, scaling lists). This encoder codes no B slices and no -/// 8x8 transform, so the three differ only in what the SPS and PPS say. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum H264Profile { - /// `profile_idc` 66 with `constraint_set1_flag`; CAVLC entropy coding. - ConstrainedBaseline, - /// `profile_idc` 77; CABAC entropy coding, no High-only syntax. - Main, - /// `profile_idc` 100; CABAC, with the High SPS tail. The default, and what - /// this encoder wrote before the profile was selectable. - #[default] - High, -} - impl H264Profile { /// The VA profile the driver is asked for. fn va_profile(self) -> Profile { @@ -102,11 +76,6 @@ impl H264Profile { H264Profile::High => Profile::H264High, } } - - /// True when the slice data is CABAC (`entropy_coding_mode_flag` = 1). - pub(crate) fn cabac(self) -> bool { - !matches!(self, H264Profile::ConstrainedBaseline) - } } /// The rate window the request is spread over, in milliseconds (`window_size`). @@ -167,28 +136,6 @@ impl Default for RateFeedback { } } -/// How the driver should spend bits. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum RateControlMode { - /// Constant quantiser: `qp` for every picture, bitrate ignored. - ConstantQp { - /// The quantiser, 0..51 for H.264/HEVC, 0..255 for AV1. - qp: u32, - }, - /// Constant bitrate, the driver picking quantisers to hold it. - ConstantBitrate, - /// Variable bitrate: `bitrate` is the average asked for, and the driver - /// may spend up to 1.5x it inside the rate window. - VariableBitrate, - /// Quality-defined variable bitrate: the driver holds `quality` (a - /// quantiser-like target, lower is better quality) and treats `bitrate` - /// as the ceiling it may not exceed. - Qvbr { - /// The quality factor, in the codec's quantiser scale. - quality: u32, - }, -} - impl RateControlMode { /// The `VAConfigAttribRateControl` value this mode is configured with. /// @@ -203,138 +150,6 @@ impl RateControlMode { RateControlMode::Qvbr { .. } => VA_RC_QVBR, } } - - /// True when the driver is told exactly which quantiser to use, so it has - /// nothing to back-annotate into the header this crate packs. - pub(crate) fn is_cqp(self) -> bool { - matches!(self, RateControlMode::ConstantQp { .. }) - } -} - -/// What can be changed between frames without rebuilding the encoder. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Tunings { - /// Target bitrate in bits per second. - pub bitrate: u32, - /// Frame rate as `(numerator, denominator)`. - pub framerate: (u32, u32), -} - -/// Per-frame instructions from the caller. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub struct FrameMetadata { - /// Presentation timestamp, carried through to the coded frame. - pub timestamp: i64, - /// Start a new GOP with this frame. - pub force_keyframe: bool, -} - -/// How an encoder is set up. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct EncoderConfig { - /// Which codec. - pub codec: EncCodec, - /// Displayed width; the coded size is rounded up for the codec's blocks. - pub width: u32, - /// Displayed height. - pub height: u32, - /// Frame rate as `(numerator, denominator)`. - pub framerate: (u32, u32), - /// Target bitrate in bits per second. - pub bitrate: u32, - /// Pictures per GOP; the first of each is an IDR / key frame. - pub gop_size: u32, - /// The H.264 profile to write (ignored by HEVC and AV1). - pub h264_profile: H264Profile, - /// Rate control mode. - pub rate_control: RateControlMode, - /// Driver quality/speed level, 1 (best quality) upwards; 0 = driver default. - pub quality: u32, - /// The colour description to write into the VUI, or `None` to leave it - /// unsignalled (`video_signal_type_present_flag = 0`) as before. - pub colour: Option, - /// Luma bit depth: 8, or 10 for AV1 (his own library is `yuv420p10le`). - /// A 10-bit encoder takes its pixels through [`Encoder::encode_16`] or - /// straight from a 10-bit [`crate::Frame`]. - pub bit_depth: u8, -} - -/// H.265 E.2.1 / H.264 E.1.1 colour description code points for the VUI. -/// -/// Carried verbatim into `colour_primaries`, `transfer_characteristics` and -/// `matrix_coeffs` — this crate does not interpret them, so a caller wanting -/// BT.2020/PQ passes `(9, 16, 9)`, BT.709 SDR `(1, 1, 1)`, and so on (H.273 -/// tables 2/3/4). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Colour { - /// `colour_primaries`. - pub primaries: u8, - /// `transfer_characteristics`. - pub transfer: u8, - /// `matrix_coeffs`. - pub matrix: u8, - /// `video_full_range_flag`. - pub full_range: bool, -} - -impl EncoderConfig { - /// A configuration with sensible defaults for `codec` at `width x height`. - pub fn new(codec: EncCodec, width: u32, height: u32) -> EncoderConfig { - EncoderConfig { - codec, - width, - height, - framerate: (30, 1), - bitrate: 8_000_000, - gop_size: 60, - h264_profile: H264Profile::High, - rate_control: RateControlMode::ConstantBitrate, - quality: 0, - colour: None, - bit_depth: 8, - } - } - - /// Encode at 10 bits (H.265 Main10 or AV1); see [`EncoderConfig::bit_depth`]. - pub fn ten_bit(mut self) -> EncoderConfig { - self.bit_depth = 10; - self - } - - /// Choose the H.264 profile written into the SPS and PPS. - pub fn h264_profile(mut self, profile: H264Profile) -> EncoderConfig { - self.h264_profile = profile; - self - } - - /// Set the VUI colour description; H.265 E.2.1 / H.264 E.1.1 code points. - pub fn colour( - mut self, - primaries: u8, - transfer: u8, - matrix: u8, - full_range: bool, - ) -> EncoderConfig { - self.colour = Some(Colour { - primaries, - transfer, - matrix, - full_range, - }); - self - } -} - -/// One coded picture. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CodedFrame { - /// The bitstream: an Annex B access unit for H.264/HEVC, an OBU sequence - /// for AV1. - pub data: Vec, - /// The timestamp the caller supplied with the source frame. - pub timestamp: i64, - /// True for an IDR / key frame. - pub is_keyframe: bool, } /// A picture submitted but not yet read back. diff --git a/crates/ec-hw/src/error.rs b/crates/ec-hw/src/error.rs index 1e1e69d4..8c94ccbf 100644 --- a/crates/ec-hw/src/error.rs +++ b/crates/ec-hw/src/error.rs @@ -17,6 +17,7 @@ pub type Result = std::result::Result; #[non_exhaustive] pub enum Error { /// A libva call failed, or the driver contradicted its own API. + #[cfg(target_os = "linux")] Va(ec_va::Error), /// The bitstream could not be parsed. Stream(ec_core::Error), @@ -68,12 +69,14 @@ impl Error { /// The raw `VAStatus`, when this came from a libva call. pub fn va_status(&self) -> Option { match self { + #[cfg(target_os = "linux")] Error::Va(e) => e.status(), _ => None, } } } +#[cfg(target_os = "linux")] impl From for Error { fn from(e: ec_va::Error) -> Error { Error::Va(e) @@ -89,6 +92,7 @@ impl From for Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { + #[cfg(target_os = "linux")] Error::Va(e) => write!(f, "VA-API: {e}"), Error::Stream(e) => write!(f, "bitstream: {e}"), Error::Unsupported { what, why } => write!(f, "{what} is not supported: {why}"), @@ -101,6 +105,7 @@ impl fmt::Display for Error { impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { + #[cfg(target_os = "linux")] Error::Va(e) => Some(e), Error::Stream(e) => Some(e), _ => None, diff --git a/crates/ec-hw/src/frame.rs b/crates/ec-hw/src/frame.rs index 36e1c1b5..e136b8d7 100644 --- a/crates/ec-hw/src/frame.rs +++ b/crates/ec-hw/src/frame.rs @@ -3,26 +3,13 @@ use std::rc::Rc; -use ec_core::color::{ColorDescription, ContentLight}; use ec_va::va::{VA_FOURCC_NV12, VA_FOURCC_P010}; use ec_va::{Display, Image, PrimeSurface, Surface, SurfaceExt}; use crate::error::{Error, Result}; use crate::pool::PooledSurface; -/// A stream's colour metadata, resolved from its own headers: VUI tags for the -/// primaries/transfer/matrix triplet, and — for HEVC — the two HDR prefix SEI -/// messages for the peak the mastering grade and the content itself declared. -/// No container tier here: ec-hw only ever sees the elementary stream, so a -/// caller that also holds the container's tags resolves those over this. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Colour { - /// Matrix/transfer/range, resolved from the bitstream's own VUI. - pub description: ColorDescription, - /// HDR peak: MaxCLL/MaxFALL and the mastering display's luminance, when - /// the stream carried them (HEVC prefix SEI only). - pub light: ContentLight, -} +pub use crate::picture::{Colour, I420, I420_16, i420_to_nv12, nv12_to_i420}; /// One decoded picture, in display order. /// @@ -46,38 +33,6 @@ pub struct Frame { epoch: u64, } -/// 8-bit planar 4:2:0, the currency edith's software path speaks. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct I420 { - /// Luma plane, `width * height`. - pub y: Vec, - /// Cb plane, `(width + 1) / 2 * ((height + 1) / 2)`. - pub u: Vec, - /// Cr plane, same size as `u`. - pub v: Vec, - /// Width in luma samples. - pub width: u32, - /// Height in luma samples. - pub height: u32, -} - -/// 10-bit planar 4:2:0, samples right-aligned in the low 10 bits. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct I420_16 { - /// Luma plane. - pub y: Vec, - /// Cb plane. - pub u: Vec, - /// Cr plane. - pub v: Vec, - /// Width in luma samples. - pub width: u32, - /// Height in luma samples. - pub height: u32, - /// Luma bit depth: always 10 for this format. - pub bit_depth: u8, -} - impl Frame { pub(crate) fn new( surface: Rc, @@ -391,76 +346,6 @@ fn check_plane(name: &str, len: usize, pitch: usize, rows: usize, row_bytes: usi } } -/// Deinterleave an NV12 chroma plane into I420 U and V planes. -/// -/// The same conversion the software path in edith expects on the way out of a -/// hardware frame; kept as a free function because an encoder's input path -/// needs it in reverse. -pub fn nv12_to_i420( - y_plane: &[u8], - y_pitch: usize, - uv_plane: &[u8], - uv_pitch: usize, - width: usize, - height: usize, -) -> I420 { - let (cw, ch) = (width.div_ceil(2), height.div_ceil(2)); - let mut out = I420 { - y: vec![0; width * height], - u: vec![0; cw * ch], - v: vec![0; cw * ch], - width: width as u32, - height: height as u32, - }; - for row in 0..height { - let src = row * y_pitch; - if src + width > y_plane.len() { - break; - } - out.y[row * width..(row + 1) * width].copy_from_slice(&y_plane[src..src + width]); - } - for row in 0..ch { - let src = row * uv_pitch; - if src + cw * 2 > uv_plane.len() { - break; - } - for col in 0..cw { - out.u[row * cw + col] = uv_plane[src + col * 2]; - out.v[row * cw + col] = uv_plane[src + col * 2 + 1]; - } - } - out -} - -/// Interleave I420 chroma into an NV12 buffer, for the encoder input path. -pub fn i420_to_nv12( - src: &I420, - y_out: &mut [u8], - y_pitch: usize, - uv_out: &mut [u8], - uv_pitch: usize, -) { - let (w, h) = (src.width as usize, src.height as usize); - let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); - for row in 0..h { - let dst = row * y_pitch; - if dst + w > y_out.len() { - break; - } - y_out[dst..dst + w].copy_from_slice(&src.y[row * w..row * w + w]); - } - for row in 0..ch { - let dst = row * uv_pitch; - if dst + cw * 2 > uv_out.len() { - break; - } - for col in 0..cw { - uv_out[dst + col * 2] = src.u[row * cw + col]; - uv_out[dst + col * 2 + 1] = src.v[row * cw + col]; - } - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/ec-hw/src/lib.rs b/crates/ec-hw/src/lib.rs index 6955c883..04072bc7 100644 --- a/crates/ec-hw/src/lib.rs +++ b/crates/ec-hw/src/lib.rs @@ -54,20 +54,33 @@ #![forbid(unsafe_code)] #![deny(missing_docs)] +#[cfg(target_os = "linux")] pub mod dec; +#[cfg(target_os = "linux")] pub mod enc; pub mod error; +#[cfg(target_os = "linux")] pub mod frame; +pub mod picture; +#[cfg(target_os = "linux")] pub mod params; +#[cfg(target_os = "linux")] pub mod pool; pub mod reset; +pub mod types; -pub use dec::{Codec, Decoder, StreamInfo}; -pub use enc::{ - CodedFrame, EncCodec, Encoder, EncoderConfig, FrameMetadata, H264Profile, RateControlMode, - Tunings, -}; +#[cfg(target_os = "linux")] +pub use dec::{Decoder, StreamInfo}; +#[cfg(target_os = "linux")] +pub use enc::Encoder; pub use error::{Error, Result}; -pub use frame::{Colour, Frame, I420, I420_16, i420_to_nv12, nv12_to_i420}; +#[cfg(target_os = "linux")] +pub use frame::Frame; +pub use picture::{Colour, I420, I420_16, i420_to_nv12, nv12_to_i420}; +#[cfg(target_os = "linux")] pub use pool::{PooledSurface, SurfacePool}; pub use reset::{gpu_recently_reset, gpu_reset_epoch, report_gpu_reset}; +pub use types::{ + Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, H264Profile, RateControlMode, + Tunings, +}; diff --git a/crates/ec-hw/src/picture.rs b/crates/ec-hw/src/picture.rs new file mode 100644 index 00000000..167fc98a --- /dev/null +++ b/crates/ec-hw/src/picture.rs @@ -0,0 +1,120 @@ +//! Pixel buffers and conversions that need no VA-API: planar I420 and its +//! 10-bit sibling, the colour metadata, and the NV12 conversions. + +use ec_core::color::{ColorDescription, ContentLight}; + +/// A stream's colour metadata, resolved from its own headers: VUI tags for the +/// primaries/transfer/matrix triplet, and — for HEVC — the two HDR prefix SEI +/// messages for the peak the mastering grade and the content itself declared. +/// No container tier here: ec-hw only ever sees the elementary stream, so a +/// caller that also holds the container's tags resolves those over this. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Colour { + /// Matrix/transfer/range, resolved from the bitstream's own VUI. + pub description: ColorDescription, + /// HDR peak: MaxCLL/MaxFALL and the mastering display's luminance, when + /// the stream carried them (HEVC prefix SEI only). + pub light: ContentLight, +} + +/// 8-bit planar 4:2:0, the currency edith's software path speaks. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct I420 { + /// Luma plane, `width * height`. + pub y: Vec, + /// Cb plane, `(width + 1) / 2 * ((height + 1) / 2)`. + pub u: Vec, + /// Cr plane, same size as `u`. + pub v: Vec, + /// Width in luma samples. + pub width: u32, + /// Height in luma samples. + pub height: u32, +} + +/// 10-bit planar 4:2:0, samples right-aligned in the low 10 bits. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct I420_16 { + /// Luma plane. + pub y: Vec, + /// Cb plane. + pub u: Vec, + /// Cr plane. + pub v: Vec, + /// Width in luma samples. + pub width: u32, + /// Height in luma samples. + pub height: u32, + /// Luma bit depth: always 10 for this format. + pub bit_depth: u8, +} + +/// Deinterleave an NV12 chroma plane into I420 U and V planes. +/// +/// The same conversion the software path in edith expects on the way out of a +/// hardware frame; kept as a free function because an encoder's input path +/// needs it in reverse. +pub fn nv12_to_i420( + y_plane: &[u8], + y_pitch: usize, + uv_plane: &[u8], + uv_pitch: usize, + width: usize, + height: usize, +) -> I420 { + let (cw, ch) = (width.div_ceil(2), height.div_ceil(2)); + let mut out = I420 { + y: vec![0; width * height], + u: vec![0; cw * ch], + v: vec![0; cw * ch], + width: width as u32, + height: height as u32, + }; + for row in 0..height { + let src = row * y_pitch; + if src + width > y_plane.len() { + break; + } + out.y[row * width..(row + 1) * width].copy_from_slice(&y_plane[src..src + width]); + } + for row in 0..ch { + let src = row * uv_pitch; + if src + cw * 2 > uv_plane.len() { + break; + } + for col in 0..cw { + out.u[row * cw + col] = uv_plane[src + col * 2]; + out.v[row * cw + col] = uv_plane[src + col * 2 + 1]; + } + } + out +} + +/// Interleave I420 chroma into an NV12 buffer, for the encoder input path. +pub fn i420_to_nv12( + src: &I420, + y_out: &mut [u8], + y_pitch: usize, + uv_out: &mut [u8], + uv_pitch: usize, +) { + let (w, h) = (src.width as usize, src.height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + for row in 0..h { + let dst = row * y_pitch; + if dst + w > y_out.len() { + break; + } + y_out[dst..dst + w].copy_from_slice(&src.y[row * w..row * w + w]); + } + for row in 0..ch { + let dst = row * uv_pitch; + if dst + cw * 2 > uv_out.len() { + break; + } + for col in 0..cw { + uv_out[dst + col * 2] = src.u[row * cw + col]; + uv_out[dst + col * 2 + 1] = src.v[row * cw + col]; + } + } +} diff --git a/crates/ec-hw/src/reset.rs b/crates/ec-hw/src/reset.rs index 40f43836..e8327df2 100644 --- a/crates/ec-hw/src/reset.rs +++ b/crates/ec-hw/src/reset.rs @@ -57,14 +57,17 @@ impl ResetClock { } /// Hard limit on one wait for a picture; past it the sync gives up. +#[cfg(target_os = "linux")] pub(crate) const SYNC_LIMIT: Duration = Duration::from_secs(8); /// A wait that took longer than this spent its time in a ring reset: a /// healthy picture takes milliseconds. 1080p..8K pictures stay far below it. +#[cfg(target_os = "linux")] pub(crate) const SLOW_PICTURE: Duration = Duration::from_millis(1500); /// Wait for `surface`, and condemn every session if the wait shows that the /// GPU was reset: an error, or a wait longer than [`SLOW_PICTURE`]. +#[cfg(target_os = "linux")] pub(crate) fn sync_watched( surface: &ec_va::va::Surface, ) -> crate::Result<()> { diff --git a/crates/ec-hw/src/types.rs b/crates/ec-hw/src/types.rs new file mode 100644 index 00000000..16b61468 --- /dev/null +++ b/crates/ec-hw/src/types.rs @@ -0,0 +1,209 @@ +//! Platform-neutral types shared by the hardware encoder and decoder. + +/// The codecs this crate encodes in hardware. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EncCodec { + /// H.264 / AVC; the profile is [`EncoderConfig::h264_profile`]. + H264, + /// H.265 / HEVC, Main profile. + H265, + /// AV1 Profile 0. + Av1, +} + +/// The H.264 profile an [`Encoder`] writes. +/// +/// Each profile is a strict subset of the next in what a decoder must accept: +/// [`H264Profile::ConstrainedBaseline`] is CAVLC with no B slices, [`H264Profile::Main`] +/// adds CABAC, and [`H264Profile::High`] adds the High-only SPS tail +/// (chroma format, bit depth, scaling lists). This encoder codes no B slices and no +/// 8x8 transform, so the three differ only in what the SPS and PPS say. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum H264Profile { + /// `profile_idc` 66 with `constraint_set1_flag`; CAVLC entropy coding. + ConstrainedBaseline, + /// `profile_idc` 77; CABAC entropy coding, no High-only syntax. + Main, + /// `profile_idc` 100; CABAC, with the High SPS tail. The default, and what + /// this encoder wrote before the profile was selectable. + #[default] + High, +} + +impl H264Profile { + /// True when the slice data is CABAC (`entropy_coding_mode_flag` = 1). + #[cfg(target_os = "linux")] + pub(crate) fn cabac(self) -> bool { + !matches!(self, H264Profile::ConstrainedBaseline) + } +} + +/// How the driver should spend bits. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RateControlMode { + /// Constant quantiser: `qp` for every picture, bitrate ignored. + ConstantQp { + /// The quantiser, 0..51 for H.264/HEVC, 0..255 for AV1. + qp: u32, + }, + /// Constant bitrate, the driver picking quantisers to hold it. + ConstantBitrate, + /// Variable bitrate: `bitrate` is the average asked for, and the driver + /// may spend up to 1.5x it inside the rate window. + VariableBitrate, + /// Quality-defined variable bitrate: the driver holds `quality` (a + /// quantiser-like target, lower is better quality) and treats `bitrate` + /// as the ceiling it may not exceed. + Qvbr { + /// The quality factor, in the codec's quantiser scale. + quality: u32, + }, +} + +impl RateControlMode { + /// True when the driver is told exactly which quantiser to use, so it has + /// nothing to back-annotate into the header this crate packs. + #[cfg(target_os = "linux")] + pub(crate) fn is_cqp(self) -> bool { + matches!(self, RateControlMode::ConstantQp { .. }) + } +} + +/// What can be changed between frames without rebuilding the encoder. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Tunings { + /// Target bitrate in bits per second. + pub bitrate: u32, + /// Frame rate as `(numerator, denominator)`. + pub framerate: (u32, u32), +} + +/// Per-frame instructions from the caller. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct FrameMetadata { + /// Presentation timestamp, carried through to the coded frame. + pub timestamp: i64, + /// Start a new GOP with this frame. + pub force_keyframe: bool, +} + +/// How an encoder is set up. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct EncoderConfig { + /// Which codec. + pub codec: EncCodec, + /// Displayed width; the coded size is rounded up for the codec's blocks. + pub width: u32, + /// Displayed height. + pub height: u32, + /// Frame rate as `(numerator, denominator)`. + pub framerate: (u32, u32), + /// Target bitrate in bits per second. + pub bitrate: u32, + /// Pictures per GOP; the first of each is an IDR / key frame. + pub gop_size: u32, + /// The H.264 profile to write (ignored by HEVC and AV1). + pub h264_profile: H264Profile, + /// Rate control mode. + pub rate_control: RateControlMode, + /// Driver quality/speed level, 1 (best quality) upwards; 0 = driver default. + pub quality: u32, + /// The colour description to write into the VUI, or `None` to leave it + /// unsignalled (`video_signal_type_present_flag = 0`) as before. + pub colour: Option, + /// Luma bit depth: 8, or 10 for AV1 (his own library is `yuv420p10le`). + /// A 10-bit encoder takes its pixels through [`Encoder::encode_16`] or + /// straight from a 10-bit [`crate::Frame`]. + pub bit_depth: u8, +} + +/// H.265 E.2.1 / H.264 E.1.1 colour description code points for the VUI. +/// +/// Carried verbatim into `colour_primaries`, `transfer_characteristics` and +/// `matrix_coeffs` — this crate does not interpret them, so a caller wanting +/// BT.2020/PQ passes `(9, 16, 9)`, BT.709 SDR `(1, 1, 1)`, and so on (H.273 +/// tables 2/3/4). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Colour { + /// `colour_primaries`. + pub primaries: u8, + /// `transfer_characteristics`. + pub transfer: u8, + /// `matrix_coeffs`. + pub matrix: u8, + /// `video_full_range_flag`. + pub full_range: bool, +} + +impl EncoderConfig { + /// A configuration with sensible defaults for `codec` at `width x height`. + pub fn new(codec: EncCodec, width: u32, height: u32) -> EncoderConfig { + EncoderConfig { + codec, + width, + height, + framerate: (30, 1), + bitrate: 8_000_000, + gop_size: 60, + h264_profile: H264Profile::High, + rate_control: RateControlMode::ConstantBitrate, + quality: 0, + colour: None, + bit_depth: 8, + } + } + + /// Encode at 10 bits (H.265 Main10 or AV1); see [`EncoderConfig::bit_depth`]. + pub fn ten_bit(mut self) -> EncoderConfig { + self.bit_depth = 10; + self + } + + /// Choose the H.264 profile written into the SPS and PPS. + pub fn h264_profile(mut self, profile: H264Profile) -> EncoderConfig { + self.h264_profile = profile; + self + } + + /// Set the VUI colour description; H.265 E.2.1 / H.264 E.1.1 code points. + pub fn colour( + mut self, + primaries: u8, + transfer: u8, + matrix: u8, + full_range: bool, + ) -> EncoderConfig { + self.colour = Some(Colour { + primaries, + transfer, + matrix, + full_range, + }); + self + } +} + +/// One coded picture. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CodedFrame { + /// The bitstream: an Annex B access unit for H.264/HEVC, an OBU sequence + /// for AV1. + pub data: Vec, + /// The timestamp the caller supplied with the source frame. + pub timestamp: i64, + /// True for an IDR / key frame. + pub is_keyframe: bool, +} + +/// The codecs this crate decodes in hardware. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Codec { + /// H.264 / AVC, Annex B byte stream. + H264, + /// H.265 / HEVC, Annex B byte stream. + H265, + /// VP9, one frame (or superframe) per call. + Vp9, + /// AV1, one temporal unit per call. + Av1, +}