From 89d28a744fe55eae8f17f0a1b1dc5168005dff70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 18:46:12 +0300 Subject: [PATCH] feat(hw): the VA-API parameter buffers, surface pool and frame readback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The foundation of the hardware crate: every codec parameter struct libva defines for the paths this family uses, transcribed by hand from the system headers and checked field for field by a `const` assertion against `crates/ec-hw/abi-probe.c`. A transcription slip is a compile error rather than a driver reading garbage. Around them: - `SurfacePool`, which allocates once and recycles: a surface returns to the free list when the reference buffer and the caller are both done with it, so nothing leaks and nothing is reallocated per frame. - `Frame`, with the two ways to reach the pixels — DRM PRIME export for the zero-copy path, and `vaGetImage` readback into I420 (8 or 10 bit) for callers that want the samples. The readback image is created once per stream: one `vaCreateImage`/`vaDestroyImage` pair per frame costs ~20 ms at 1080p on this driver, more than the decode itself. - A typed error for every failure. Nothing here panics: edith loads this path as a dlopen'd plugin whose fall back to software is only as good as that promise. --- Cargo.lock | 12 + Cargo.toml | 3 + crates/ec-hw/Cargo.toml | 15 + crates/ec-hw/abi-probe.c | 271 ++++++ crates/ec-hw/src/error.rs | 89 ++ crates/ec-hw/src/frame.rs | 413 +++++++++ crates/ec-hw/src/lib.rs | 60 ++ crates/ec-hw/src/params/av1.rs | 480 ++++++++++ crates/ec-hw/src/params/enc.rs | 1494 +++++++++++++++++++++++++++++++ crates/ec-hw/src/params/h264.rs | 376 ++++++++ crates/ec-hw/src/params/hevc.rs | 473 ++++++++++ crates/ec-hw/src/params/mod.rs | 134 +++ crates/ec-hw/src/params/vp9.rs | 182 ++++ crates/ec-hw/src/pool.rs | 132 +++ 14 files changed, 4134 insertions(+) create mode 100644 crates/ec-hw/Cargo.toml create mode 100644 crates/ec-hw/abi-probe.c create mode 100644 crates/ec-hw/src/error.rs create mode 100644 crates/ec-hw/src/frame.rs create mode 100644 crates/ec-hw/src/lib.rs create mode 100644 crates/ec-hw/src/params/av1.rs create mode 100644 crates/ec-hw/src/params/enc.rs create mode 100644 crates/ec-hw/src/params/h264.rs create mode 100644 crates/ec-hw/src/params/hevc.rs create mode 100644 crates/ec-hw/src/params/mod.rs create mode 100644 crates/ec-hw/src/params/vp9.rs create mode 100644 crates/ec-hw/src/pool.rs diff --git a/Cargo.lock b/Cargo.lock index 3cd5b8ca..f0832419 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -312,6 +312,18 @@ dependencies = [ "ec-core", ] +[[package]] +name = "ec-hw" +version = "0.1.0" +dependencies = [ + "ec-av1-syntax", + "ec-core", + "ec-h264-syntax", + "ec-h265-syntax", + "ec-va", + "ec-vp9-syntax", +] + [[package]] name = "ec-image" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index ee68cd99..41db14c8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,7 +18,9 @@ ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" } ec-flac = { path = "crates/ec-flac", version = "0.1.0" } ec-h264 = { path = "crates/ec-h264", version = "0.1.0" } ec-h264-syntax = { path = "crates/ec-h264-syntax", version = "0.1.0" } +ec-h265 = { path = "crates/ec-h265", version = "0.1.0" } ec-h265-syntax = { path = "crates/ec-h265-syntax", version = "0.1.0" } +ec-hw = { path = "crates/ec-hw", version = "0.1.0" } ec-image = { path = "crates/ec-image", version = "0.1.0" } ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" } ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" } @@ -28,6 +30,7 @@ ec-ogg = { path = "crates/ec-ogg", version = "0.1.0" } ec-opus = { path = "crates/ec-opus", version = "0.1.0" } ec-probe = { path = "crates/ec-probe", version = "0.1.0" } ec-riff = { path = "crates/ec-riff", version = "0.1.0" } +ec-va = { path = "crates/ec-va", version = "0.1.0" } ec-vorbis = { path = "crates/ec-vorbis", version = "0.1.0" } ec-vp9-syntax = { path = "crates/ec-vp9-syntax", version = "0.1.0" } # Portable SIMD without asm or build-time tooling (family rule: pure Rust only). diff --git a/crates/ec-hw/Cargo.toml b/crates/ec-hw/Cargo.toml new file mode 100644 index 00000000..9069f1ee --- /dev/null +++ b/crates/ec-hw/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "ec-hw" +description = "Stateless VA-API hardware decoding and encoding: H.264, HEVC, VP9, AV1." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +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 diff --git a/crates/ec-hw/abi-probe.c b/crates/ec-hw/abi-probe.c new file mode 100644 index 00000000..43784c30 --- /dev/null +++ b/crates/ec-hw/abi-probe.c @@ -0,0 +1,271 @@ +/* abi-probe.c — print the layout of every libva codec parameter struct this + * crate transcribes, compiled against the *system* headers. + * + * The numbers it prints are pasted into the `const _: () = assert!(...)` block + * at the end of each `src/params/*.rs`, so a transcription slip is a compile + * error rather than a driver reading garbage. Rerun after a libva upgrade: + * + * cc -o /tmp/abi-probe crates/ec-hw/abi-probe.c $(pkg-config --cflags libva) && /tmp/abi-probe + * + * Same contract as crates/ec-va/abi-probe.c, one level up the stack. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define S(t) printf("%-46s size=%-6zu align=%zu\n", #t, sizeof(t), _Alignof(t)) +#define O(t, f) printf(" %-44s %zu\n", #t "." #f, offsetof(t, f)) + +int main(void) +{ + printf("libva %d.%d.%d\n", VA_MAJOR_VERSION, VA_MINOR_VERSION, VA_MICRO_VERSION); + + S(VAPictureH264); + O(VAPictureH264, frame_idx); + O(VAPictureH264, flags); + O(VAPictureH264, TopFieldOrderCnt); + O(VAPictureH264, BottomFieldOrderCnt); + + S(VAPictureParameterBufferH264); + O(VAPictureParameterBufferH264, ReferenceFrames); + O(VAPictureParameterBufferH264, picture_width_in_mbs_minus1); + O(VAPictureParameterBufferH264, bit_depth_luma_minus8); + O(VAPictureParameterBufferH264, num_ref_frames); + O(VAPictureParameterBufferH264, seq_fields); + O(VAPictureParameterBufferH264, pic_init_qp_minus26); + O(VAPictureParameterBufferH264, pic_fields); + O(VAPictureParameterBufferH264, frame_num); + + S(VAIQMatrixBufferH264); + O(VAIQMatrixBufferH264, ScalingList8x8); + + S(VASliceParameterBufferH264); + O(VASliceParameterBufferH264, slice_data_bit_offset); + O(VASliceParameterBufferH264, slice_type); + O(VASliceParameterBufferH264, cabac_init_idc); + O(VASliceParameterBufferH264, RefPicList0); + O(VASliceParameterBufferH264, RefPicList1); + O(VASliceParameterBufferH264, luma_log2_weight_denom); + O(VASliceParameterBufferH264, luma_weight_l0); + O(VASliceParameterBufferH264, chroma_weight_l0); + O(VASliceParameterBufferH264, luma_weight_l1_flag); + O(VASliceParameterBufferH264, chroma_offset_l1); + + S(VAPictureHEVC); + O(VAPictureHEVC, pic_order_cnt); + O(VAPictureHEVC, flags); + + S(VAPictureParameterBufferHEVC); + O(VAPictureParameterBufferHEVC, ReferenceFrames); + O(VAPictureParameterBufferHEVC, pic_width_in_luma_samples); + O(VAPictureParameterBufferHEVC, pic_fields); + O(VAPictureParameterBufferHEVC, sps_max_dec_pic_buffering_minus1); + O(VAPictureParameterBufferHEVC, column_width_minus1); + O(VAPictureParameterBufferHEVC, row_height_minus1); + O(VAPictureParameterBufferHEVC, slice_parsing_fields); + O(VAPictureParameterBufferHEVC, log2_max_pic_order_cnt_lsb_minus4); + O(VAPictureParameterBufferHEVC, st_rps_bits); + + S(VASliceParameterBufferHEVC); + O(VASliceParameterBufferHEVC, slice_segment_address); + O(VASliceParameterBufferHEVC, RefPicList); + O(VASliceParameterBufferHEVC, LongSliceFlags); + O(VASliceParameterBufferHEVC, collocated_ref_idx); + O(VASliceParameterBufferHEVC, luma_log2_weight_denom); + O(VASliceParameterBufferHEVC, delta_luma_weight_l0); + O(VASliceParameterBufferHEVC, delta_luma_weight_l1); + O(VASliceParameterBufferHEVC, five_minus_max_num_merge_cand); + O(VASliceParameterBufferHEVC, num_entry_point_offsets); + O(VASliceParameterBufferHEVC, slice_data_num_emu_prevn_bytes); + + S(VAIQMatrixBufferHEVC); + O(VAIQMatrixBufferHEVC, ScalingList32x32); + O(VAIQMatrixBufferHEVC, ScalingListDC16x16); + + S(VADecPictureParameterBufferVP9); + O(VADecPictureParameterBufferVP9, reference_frames); + O(VADecPictureParameterBufferVP9, pic_fields); + O(VADecPictureParameterBufferVP9, filter_level); + O(VADecPictureParameterBufferVP9, first_partition_size); + O(VADecPictureParameterBufferVP9, mb_segment_tree_probs); + O(VADecPictureParameterBufferVP9, profile); + + S(VASegmentParameterVP9); + O(VASegmentParameterVP9, filter_level); + O(VASegmentParameterVP9, luma_ac_quant_scale); + + S(VASliceParameterBufferVP9); + O(VASliceParameterBufferVP9, seg_param); + + S(VASegmentationStructAV1); + O(VASegmentationStructAV1, feature_data); + O(VASegmentationStructAV1, feature_mask); + S(VAFilmGrainStructAV1); + O(VAFilmGrainStructAV1, grain_seed); + O(VAFilmGrainStructAV1, ar_coeffs_y); + O(VAFilmGrainStructAV1, cr_offset); + S(VAWarpedMotionParamsAV1); + O(VAWarpedMotionParamsAV1, wmmat); + O(VAWarpedMotionParamsAV1, invalid); + + S(VADecPictureParameterBufferAV1); + O(VADecPictureParameterBufferAV1, seq_info_fields); + O(VADecPictureParameterBufferAV1, current_frame); + O(VADecPictureParameterBufferAV1, anchor_frames_num); + O(VADecPictureParameterBufferAV1, anchor_frames_list); + O(VADecPictureParameterBufferAV1, frame_width_minus1); + O(VADecPictureParameterBufferAV1, ref_frame_map); + O(VADecPictureParameterBufferAV1, ref_frame_idx); + O(VADecPictureParameterBufferAV1, seg_info); + O(VADecPictureParameterBufferAV1, film_grain_info); + O(VADecPictureParameterBufferAV1, tile_cols); + O(VADecPictureParameterBufferAV1, width_in_sbs_minus_1); + O(VADecPictureParameterBufferAV1, height_in_sbs_minus_1); + O(VADecPictureParameterBufferAV1, tile_count_minus_1); + O(VADecPictureParameterBufferAV1, pic_info_fields); + O(VADecPictureParameterBufferAV1, superres_scale_denominator); + O(VADecPictureParameterBufferAV1, loop_filter_info_fields); + O(VADecPictureParameterBufferAV1, ref_deltas); + O(VADecPictureParameterBufferAV1, base_qindex); + O(VADecPictureParameterBufferAV1, qmatrix_fields); + O(VADecPictureParameterBufferAV1, mode_control_fields); + O(VADecPictureParameterBufferAV1, cdef_damping_minus_3); + O(VADecPictureParameterBufferAV1, cdef_y_strengths); + O(VADecPictureParameterBufferAV1, loop_restoration_fields); + O(VADecPictureParameterBufferAV1, wm); + + S(VASliceParameterBufferAV1); + O(VASliceParameterBufferAV1, tile_row); + O(VASliceParameterBufferAV1, anchor_frame_idx); + O(VASliceParameterBufferAV1, tile_idx_in_tile_list); + + S(VAEncSequenceParameterBufferH264); + O(VAEncSequenceParameterBufferH264, intra_period); + O(VAEncSequenceParameterBufferH264, picture_width_in_mbs); + O(VAEncSequenceParameterBufferH264, seq_fields); + O(VAEncSequenceParameterBufferH264, bit_depth_luma_minus8); + O(VAEncSequenceParameterBufferH264, offset_for_non_ref_pic); + O(VAEncSequenceParameterBufferH264, offset_for_ref_frame); + O(VAEncSequenceParameterBufferH264, frame_cropping_flag); + O(VAEncSequenceParameterBufferH264, frame_crop_left_offset); + O(VAEncSequenceParameterBufferH264, vui_parameters_present_flag); + O(VAEncSequenceParameterBufferH264, vui_fields); + O(VAEncSequenceParameterBufferH264, aspect_ratio_idc); + O(VAEncSequenceParameterBufferH264, num_units_in_tick); + O(VAEncSequenceParameterBufferH264, time_scale); + + S(VAEncPictureParameterBufferH264); + O(VAEncPictureParameterBufferH264, ReferenceFrames); + O(VAEncPictureParameterBufferH264, coded_buf); + O(VAEncPictureParameterBufferH264, pic_parameter_set_id); + O(VAEncPictureParameterBufferH264, frame_num); + O(VAEncPictureParameterBufferH264, pic_init_qp); + O(VAEncPictureParameterBufferH264, pic_fields); + + S(VAEncSliceParameterBufferH264); + O(VAEncSliceParameterBufferH264, macroblock_info); + O(VAEncSliceParameterBufferH264, slice_type); + O(VAEncSliceParameterBufferH264, idr_pic_id); + O(VAEncSliceParameterBufferH264, delta_pic_order_cnt_bottom); + O(VAEncSliceParameterBufferH264, direct_spatial_mv_pred_flag); + O(VAEncSliceParameterBufferH264, RefPicList0); + O(VAEncSliceParameterBufferH264, RefPicList1); + O(VAEncSliceParameterBufferH264, luma_log2_weight_denom); + O(VAEncSliceParameterBufferH264, cabac_init_idc); + + S(VAEncSequenceParameterBufferHEVC); + O(VAEncSequenceParameterBufferHEVC, intra_period); + O(VAEncSequenceParameterBufferHEVC, pic_width_in_luma_samples); + O(VAEncSequenceParameterBufferHEVC, seq_fields); + O(VAEncSequenceParameterBufferHEVC, log2_min_luma_coding_block_size_minus3); + O(VAEncSequenceParameterBufferHEVC, pcm_sample_bit_depth_luma_minus1); + O(VAEncSequenceParameterBufferHEVC, vui_parameters_present_flag); + O(VAEncSequenceParameterBufferHEVC, vui_fields); + O(VAEncSequenceParameterBufferHEVC, aspect_ratio_idc); + O(VAEncSequenceParameterBufferHEVC, vui_num_units_in_tick); + O(VAEncSequenceParameterBufferHEVC, min_spatial_segmentation_idc); + O(VAEncSequenceParameterBufferHEVC, scc_fields); + + S(VAEncPictureParameterBufferHEVC); + O(VAEncPictureParameterBufferHEVC, reference_frames); + O(VAEncPictureParameterBufferHEVC, coded_buf); + O(VAEncPictureParameterBufferHEVC, collocated_ref_pic_index); + O(VAEncPictureParameterBufferHEVC, column_width_minus1); + O(VAEncPictureParameterBufferHEVC, row_height_minus1); + O(VAEncPictureParameterBufferHEVC, log2_parallel_merge_level_minus2); + O(VAEncPictureParameterBufferHEVC, nal_unit_type); + O(VAEncPictureParameterBufferHEVC, pic_fields); + O(VAEncPictureParameterBufferHEVC, hierarchical_level_plus1); + O(VAEncPictureParameterBufferHEVC, scc_fields); + + S(VAEncSliceParameterBufferHEVC); + O(VAEncSliceParameterBufferHEVC, num_ctu_in_slice); + O(VAEncSliceParameterBufferHEVC, slice_type); + O(VAEncSliceParameterBufferHEVC, ref_pic_list0); + O(VAEncSliceParameterBufferHEVC, ref_pic_list1); + O(VAEncSliceParameterBufferHEVC, luma_log2_weight_denom); + O(VAEncSliceParameterBufferHEVC, max_num_merge_cand); + O(VAEncSliceParameterBufferHEVC, slice_fields); + O(VAEncSliceParameterBufferHEVC, pred_weight_table_bit_offset); + + S(VAEncSequenceParameterBufferAV1); + O(VAEncSequenceParameterBufferAV1, intra_period); + O(VAEncSequenceParameterBufferAV1, seq_fields); + O(VAEncSequenceParameterBufferAV1, order_hint_bits_minus_1); + S(VAEncSegParamAV1); + O(VAEncSegParamAV1, feature_data); + O(VAEncSegParamAV1, feature_mask); + S(VAEncWarpedMotionParamsAV1); + S(VAEncPictureParameterBufferAV1); + O(VAEncPictureParameterBufferAV1, reconstructed_frame); + O(VAEncPictureParameterBufferAV1, coded_buf); + O(VAEncPictureParameterBufferAV1, reference_frames); + O(VAEncPictureParameterBufferAV1, ref_frame_idx); + O(VAEncPictureParameterBufferAV1, ref_frame_ctrl_l0); + O(VAEncPictureParameterBufferAV1, picture_flags); + O(VAEncPictureParameterBufferAV1, seg_id_block_size); + O(VAEncPictureParameterBufferAV1, filter_level); + O(VAEncPictureParameterBufferAV1, loop_filter_flags); + O(VAEncPictureParameterBufferAV1, ref_deltas); + O(VAEncPictureParameterBufferAV1, base_qindex); + O(VAEncPictureParameterBufferAV1, min_base_qindex); + O(VAEncPictureParameterBufferAV1, qmatrix_flags); + O(VAEncPictureParameterBufferAV1, mode_control_flags); + O(VAEncPictureParameterBufferAV1, segments); + O(VAEncPictureParameterBufferAV1, tile_cols); + O(VAEncPictureParameterBufferAV1, width_in_sbs_minus_1); + O(VAEncPictureParameterBufferAV1, context_update_tile_id); + O(VAEncPictureParameterBufferAV1, cdef_damping_minus_3); + O(VAEncPictureParameterBufferAV1, loop_restoration_flags); + O(VAEncPictureParameterBufferAV1, wm); + O(VAEncPictureParameterBufferAV1, bit_offset_qindex); + O(VAEncPictureParameterBufferAV1, tile_group_obu_hdr_info); + O(VAEncPictureParameterBufferAV1, number_skip_frames); + O(VAEncPictureParameterBufferAV1, skip_frames_reduced_size); + S(VAEncTileGroupBufferAV1); + + S(VAEncMiscParameterRateControl); + O(VAEncMiscParameterRateControl, rc_flags); + O(VAEncMiscParameterRateControl, ICQ_quality_factor); + O(VAEncMiscParameterRateControl, max_qp); + S(VAEncMiscParameterFrameRate); + O(VAEncMiscParameterFrameRate, framerate_flags); + S(VAEncMiscParameterHRD); + O(VAEncMiscParameterHRD, buffer_size); + S(VAEncMiscParameterBufferQualityLevel); + S(VAEncPackedHeaderParameterBuffer); + O(VAEncPackedHeaderParameterBuffer, bit_length); + O(VAEncPackedHeaderParameterBuffer, has_emulation_bytes); + S(VACodedBufferSegment); + O(VACodedBufferSegment, bit_offset); + O(VACodedBufferSegment, status); + O(VACodedBufferSegment, buf); + O(VACodedBufferSegment, next); + return 0; +} diff --git a/crates/ec-hw/src/error.rs b/crates/ec-hw/src/error.rs new file mode 100644 index 00000000..2d2f86c6 --- /dev/null +++ b/crates/ec-hw/src/error.rs @@ -0,0 +1,89 @@ +//! Typed errors. Nothing in this crate panics on a driver or bitstream fault. +//! +//! That is a hard requirement rather than a style preference: edith loads the +//! VA-API path as a `dlopen`ed plugin behind `catch_unwind`, and its +//! fall-back-to-software guarantee is only as good as this crate's promise to +//! return instead of unwinding. Every `VAStatus` becomes an [`Error::Va`], +//! every malformed bitstream an [`Error::Stream`], and every capability this +//! GPU does not have an [`Error::Unsupported`] naming what and why. + +use std::fmt; + +/// Result alias for this crate. +pub type Result = std::result::Result; + +/// Everything that can go wrong on the hardware path. +#[derive(Debug)] +#[non_exhaustive] +pub enum Error { + /// A libva call failed, or the driver contradicted its own API. + Va(ec_va::Error), + /// The bitstream could not be parsed. + Stream(ec_core::Error), + /// A capability this GPU or this build genuinely does not have. + Unsupported { + /// What was asked for, e.g. `"VP9 Profile 1 decode"`. + what: String, + /// Why it cannot be served, e.g. `"driver reports no VLD entrypoint"`. + why: String, + }, + /// The caller asked for something inconsistent, e.g. feeding H.264 to a + /// decoder configured for AV1, or encoding a frame of the wrong size. + Config(String), +} + +impl Error { + /// Build an [`Error::Unsupported`]. + pub fn unsupported(what: impl Into, why: impl Into) -> Error { + Error::Unsupported { + what: what.into(), + why: why.into(), + } + } + + /// Build an [`Error::Config`]. + pub fn config(what: impl Into) -> Error { + Error::Config(what.into()) + } + + /// The raw `VAStatus`, when this came from a libva call. + pub fn va_status(&self) -> Option { + match self { + Error::Va(e) => e.status(), + _ => None, + } + } +} + +impl From for Error { + fn from(e: ec_va::Error) -> Error { + Error::Va(e) + } +} + +impl From for Error { + fn from(e: ec_core::Error) -> Error { + Error::Stream(e) + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + 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}"), + Error::Config(what) => write!(f, "{what}"), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + 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 new file mode 100644 index 00000000..2ec8b5f2 --- /dev/null +++ b/crates/ec-hw/src/frame.rs @@ -0,0 +1,413 @@ +//! Decoded frames: what comes out of a decoder, and the two ways to get at the +//! pixels — DRM PRIME export (zero copy) and mapped readback. + +use std::sync::{Arc, Mutex}; + +use ec_va::sys::{VA_FOURCC_NV12, VA_FOURCC_P010}; +use ec_va::{Image, MappedImage, PrimeSurface, Surface}; + +use crate::error::{Error, Result}; +use crate::pool::PooledSurface; + +/// The readback image a decoder reuses across frames. +/// +/// One `vaCreateImage`/`vaDestroyImage` pair per frame costs ~20 ms at 1080p on +/// this driver — more than the decode — because each one allocates and frees a +/// 3 MB driver buffer. The image is therefore created once per stream and kept +/// here, shared by every frame that stream produces. +pub(crate) type ImageCache = Arc>>; + +/// One decoded picture, in display order. +/// +/// Holding a frame holds its surface out of the decoder's pool, so a consumer +/// that keeps every frame will starve the decoder — by design: that is the back +/// pressure a zero-copy pipeline needs. +pub struct Frame { + surface: Arc, + images: ImageCache, + /// Presentation timestamp carried through from the access unit. + pub timestamp: i64, + /// Size the picture is displayed at, after cropping. + pub display_size: (u32, u32), + /// Size the picture is coded at (a multiple of the codec's block size). + pub coded_size: (u32, u32), + /// Luma bit depth: 8 for NV12 surfaces, 10 for P010. + pub bit_depth: u8, +} + +/// 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, +} + +impl Frame { + pub(crate) fn new( + surface: Arc, + images: ImageCache, + timestamp: i64, + display_size: (u32, u32), + coded_size: (u32, u32), + bit_depth: u8, + ) -> Frame { + Frame { + surface, + images, + timestamp, + display_size, + coded_size, + bit_depth, + } + } + + /// The surface this frame lives on. + pub fn surface(&self) -> &Arc { + &self.surface + } + + /// Export the surface as DRM PRIME file descriptors. + /// + /// This is the path edith's `engine-hw` takes: the fds are imported into + /// gbm on the other side, so no pixel ever crosses the PCIe bus. The frame + /// is synchronised first, because an exported fd carries no fence. + pub fn export_prime(&self) -> Result { + self.surface.sync()?; + Ok(self + .surface + .export_prime(ec_va::sys::VA_EXPORT_SURFACE_READ_ONLY)?) + } + + /// Read the frame back as 8-bit I420, truncating a 10-bit surface. + /// + /// Truncation is what the `vh_*` C ABI takes today (one byte per sample); + /// [`Frame::to_i420_16`] is the lossless path for a caller that wants the + /// ten bits. + pub fn to_i420(&self) -> Result { + let (w, h) = self.display_size; + let (cw, ch) = ((w as usize).div_ceil(2), (h as usize).div_ceil(2)); + let (w, h) = (w as usize, h as usize); + let mut out = I420 { + y: vec![0; w * h], + u: vec![0; cw * ch], + v: vec![0; cw * ch], + width: self.display_size.0, + height: self.display_size.1, + }; + + self.with_planes(|mapped| { + let y_pitch = mapped.pitch(0).unwrap_or(0) as usize; + let uv_pitch = mapped.pitch(1).unwrap_or(0) as usize; + let y_plane = mapped + .plane(0) + .ok_or_else(|| Error::config("VA image has no luma plane"))?; + let uv_plane = mapped + .plane(1) + .ok_or_else(|| Error::config("VA image has no chroma plane"))?; + + // Mapped VA memory is uncached (write-combining on this driver), where a + // byte-at-a-time read runs at a few hundred MB/s. Every plane is + // therefore pulled out one whole row at a time with `copy_from_slice` + // and unpacked from ordinary memory afterwards: same result, 10x the + // throughput (27 ms -> 2.6 ms per 1080p frame, measured). + let mut row_buf = vec![0u8; (uv_pitch.max(y_pitch)).max(w * 2)]; + match self.bit_depth { + 8 => { + for row in 0..h { + let src = row * y_pitch; + out.y[row * w..(row + 1) * w].copy_from_slice(&y_plane[src..src + w]); + } + for row in 0..ch { + let src = row * uv_pitch; + let line = &mut row_buf[..cw * 2]; + line.copy_from_slice(&uv_plane[src..src + cw * 2]); + for col in 0..cw { + out.u[row * cw + col] = line[col * 2]; + out.v[row * cw + col] = line[col * 2 + 1]; + } + } + } + _ => { + // P010 keeps the sample in the *high* bits of each u16, so the + // 8-bit value is the high byte — a shift by 8, not by 2. + for row in 0..h { + let src = row * y_pitch; + let line = &mut row_buf[..w * 2]; + line.copy_from_slice(&y_plane[src..src + w * 2]); + for col in 0..w { + out.y[row * w + col] = line[col * 2 + 1]; + } + } + for row in 0..ch { + let src = row * uv_pitch; + let line = &mut row_buf[..cw * 4]; + line.copy_from_slice(&uv_plane[src..src + cw * 4]); + for col in 0..cw { + out.u[row * cw + col] = line[col * 4 + 1]; + out.v[row * cw + col] = line[col * 4 + 3]; + } + } + } + } + Ok(out) + }) + } + + /// Read the frame back as 10-bit I420 (samples in the low 10 bits). + /// + /// An 8-bit surface is widened rather than refused, so a caller can hold + /// one frame type across a mixed-depth timeline. + pub fn to_i420_16(&self) -> Result { + let (w, h) = self.display_size; + let (cw, ch) = ((w as usize).div_ceil(2), (h as usize).div_ceil(2)); + let (w, h) = (w as usize, h as usize); + let mut out = I420_16 { + y: vec![0; w * h], + u: vec![0; cw * ch], + v: vec![0; cw * ch], + width: self.display_size.0, + height: self.display_size.1, + }; + + self.with_planes(|mapped| { + let y_pitch = mapped.pitch(0).unwrap_or(0) as usize; + let uv_pitch = mapped.pitch(1).unwrap_or(0) as usize; + let y_plane = mapped + .plane(0) + .ok_or_else(|| Error::config("VA image has no luma plane"))?; + let uv_plane = mapped + .plane(1) + .ok_or_else(|| Error::config("VA image has no chroma plane"))?; + + // Row at a time, for the reason given in `to_i420`. + let mut row_buf = vec![0u8; (uv_pitch.max(y_pitch)).max(w * 2)]; + match self.bit_depth { + 8 => { + for row in 0..h { + let src = row * y_pitch; + row_buf[..w].copy_from_slice(&y_plane[src..src + w]); + for (dst, &sample) in + out.y[row * w..(row + 1) * w].iter_mut().zip(&row_buf[..w]) + { + *dst = u16::from(sample) << 2; + } + } + for row in 0..ch { + let src = row * uv_pitch; + let line = &mut row_buf[..cw * 2]; + line.copy_from_slice(&uv_plane[src..src + cw * 2]); + for col in 0..cw { + out.u[row * cw + col] = u16::from(line[col * 2]) << 2; + out.v[row * cw + col] = u16::from(line[col * 2 + 1]) << 2; + } + } + } + _ => { + // P010 is 16-bit little endian with the sample in the top ten + // bits; the low six are zero padding. + for row in 0..h { + let src = row * y_pitch; + let line = &mut row_buf[..w * 2]; + line.copy_from_slice(&y_plane[src..src + w * 2]); + for col in 0..w { + out.y[row * w + col] = + u16::from_le_bytes([line[col * 2], line[col * 2 + 1]]) >> 6; + } + } + for row in 0..ch { + let src = row * uv_pitch; + let line = &mut row_buf[..cw * 4]; + line.copy_from_slice(&uv_plane[src..src + cw * 4]); + for col in 0..cw { + out.u[row * cw + col] = + u16::from_le_bytes([line[col * 4], line[col * 4 + 1]]) >> 6; + out.v[row * cw + col] = + u16::from_le_bytes([line[col * 4 + 2], line[col * 4 + 3]]) >> 6; + } + } + } + } + Ok(out) + }) + } + + /// Map the surface's pixels and hand the planes to `read`. + /// + /// `vaGetImage` into an image kept for the life of the stream, *not* + /// `vaDeriveImage`. Deriving looks cheaper — it is a view rather than a + /// copy — and it does return the same pixels here (checked row for row), + /// but the view is device memory across the PCIe bar: reading a 1080p frame + /// through it costs 48 ms against 10 ms for a driver-side copy into system + /// memory followed by a normal read (measured, 719-frame loop). + fn with_planes(&self, read: impl FnOnce(&MappedImage<'_>) -> Result) -> Result { + self.surface.sync()?; + let fourcc = if self.bit_depth > 8 { + VA_FOURCC_P010 + } else { + VA_FOURCC_NV12 + }; + let (w, h) = self.coded_size; + + let mut slot = match self.images.lock() { + Ok(slot) => slot, + // The lock guards a cached image, not an invariant: a panicking + // reader leaves it perfectly usable. + Err(poisoned) => poisoned.into_inner(), + }; + let reusable = slot + .as_ref() + .is_some_and(|image| image.fourcc() == fourcc && image.size() == (w, h)); + if !reusable { + *slot = Some(Image::create(self.surface.display(), fourcc, w, h)?); + } + let image = slot + .as_mut() + .ok_or_else(|| Error::config("no readback image"))?; + self.surface.read_into(image, 0, 0, w, h)?; + let mapped = image.map()?; + read(&mapped) + } +} + +impl std::fmt::Debug for Frame { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Frame") + .field("surface", &self.surface.id()) + .field("timestamp", &self.timestamp) + .field("display_size", &self.display_size) + .field("bit_depth", &self.bit_depth) + .finish() + } +} + +/// Deinterleave an NV12 chroma plane into I420 U and V planes. +/// +/// Parity with `cros-codecs`' `image_processing::nv12_to_i420`, which is what +/// edith calls today; kept as a free function because the conversion is also +/// what an encoder input path needs, 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::*; + + #[test] + fn nv12_round_trips_through_i420() { + let (w, h) = (6usize, 4usize); + let (y_pitch, uv_pitch) = (8usize, 8usize); + let mut y = vec![0u8; y_pitch * h]; + let mut uv = vec![0u8; uv_pitch * h / 2]; + for row in 0..h { + for col in 0..w { + y[row * y_pitch + col] = (row * w + col) as u8; + } + } + for row in 0..h / 2 { + for col in 0..w { + uv[row * uv_pitch + col] = (100 + row * w + col) as u8; + } + } + + let i420 = nv12_to_i420(&y, y_pitch, &uv, uv_pitch, w, h); + assert_eq!(i420.y.len(), w * h); + assert_eq!(i420.u.len(), (w / 2) * (h / 2)); + assert_eq!(i420.y[0], 0); + assert_eq!(i420.y[w], w as u8); + // U takes the even bytes of the interleaved plane, V the odd ones. + assert_eq!(i420.u[0], 100); + assert_eq!(i420.v[0], 101); + assert_eq!(i420.u[1], 102); + + let mut y2 = vec![0u8; y_pitch * h]; + let mut uv2 = vec![0u8; uv_pitch * h / 2]; + i420_to_nv12(&i420, &mut y2, y_pitch, &mut uv2, uv_pitch); + let back = nv12_to_i420(&y2, y_pitch, &uv2, uv_pitch, w, h); + assert_eq!(back, i420); + } +} diff --git a/crates/ec-hw/src/lib.rs b/crates/ec-hw/src/lib.rs new file mode 100644 index 00000000..3cd21123 --- /dev/null +++ b/crates/ec-hw/src/lib.rs @@ -0,0 +1,60 @@ +//! Stateless VA-API video decoding and encoding. +//! +//! "Stateless" is the VA-API decode model, not a description of this crate: the +//! driver decodes one picture at a time and knows nothing between pictures, so +//! everything a codec spreads across frames — the decoded picture buffer, +//! reference lists, picture order counts, reference slot updates — is kept +//! here, in Rust, and handed to the driver per picture. That is the whole job. +//! +//! ```no_run +//! use ec_hw::{Codec, Decoder}; +//! +//! let display = ec_va::Display::open()?; +//! let mut decoder = Decoder::new(&display, Codec::H264)?; +//! decoder.decode(annex_b_access_unit, 0)?; +//! while let Some(frame) = decoder.next_frame() { +//! let planes = frame.to_i420()?; // or frame.export_prime() for zero copy +//! } +//! # Ok::<(), ec_hw::Error>(()) +//! # fn annex_b_access_unit() -> &'static [u8] { &[] } +//! ``` +//! +//! # Shape +//! +//! * [`params`] — the `#[repr(C)]` codec parameter buffers, each checked +//! against the system headers by a `const` assertion. +//! * [`dec`] — one stateless decoder per codec behind [`Decoder`]. +//! * [`enc`] — H.264 and HEVC encoders, and an opt-in AV1 one. +//! * [`SurfacePool`] / [`Frame`] — surface recycling and pixel access. +//! +//! # Unsafe +//! +//! This crate is not `forbid(unsafe_code)`: handing a parameter struct to the +//! driver and walking a coded-buffer segment list are both pointer work that +//! `ec-va` cannot type for us. Both are confined to two functions — +//! [`params::param_buffer`] and `enc::coded_bytes` — and everything else, +//! including every codec's parameter derivation, is safe Rust. +//! +//! # Panics +//! +//! None by contract. Every driver and bitstream fault is an [`Error`], because +//! edith loads this path as a `dlopen`ed plugin whose fall back to software is +//! only as good as that promise. + +#![deny(missing_docs)] +#![deny(unsafe_op_in_unsafe_fn)] + +pub mod dec; +pub mod enc; +pub mod error; +pub mod frame; +pub mod params; +pub mod pool; + +pub use dec::{Codec, Decoder, StreamInfo}; +pub use enc::{ + CodedFrame, EncCodec, Encoder, EncoderConfig, FrameMetadata, RateControlMode, Tunings, +}; +pub use error::{Error, Result}; +pub use frame::{Frame, I420, I420_16, i420_to_nv12, nv12_to_i420}; +pub use pool::{PooledSurface, SurfacePool}; diff --git a/crates/ec-hw/src/params/av1.rs b/crates/ec-hw/src/params/av1.rs new file mode 100644 index 00000000..ca3636a6 --- /dev/null +++ b/crates/ec-hw/src/params/av1.rs @@ -0,0 +1,480 @@ +//! AV1 decode parameter buffers (`va_dec_av1.h`). + +use std::ffi::c_void; + +use ec_va::sys::{VAPictureParameterBufferType, VASliceParameterBufferType, VASurfaceID}; + +use super::{INVALID_SURFACE, VaParam}; +use crate::va_bits; + +va_bits! { + /// `VASegmentationStructAV1::segment_info_fields`. + SegmentInfoFields: u32 { + enabled: 1, + update_map: 1, + temporal_update: 1, + update_data: 1, + } +} + +/// `VASegmentationStructAV1`, `va_dec_av1.h:65`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub struct SegmentationStructAV1 { + /// Segmentation flags. + pub segment_info_fields: SegmentInfoFields, + /// `FeatureData[segment][feature]`. + pub feature_data: [[i16; 8]; 8], + /// `FeatureEnabled[segment]` as a bitmask over features. + pub feature_mask: [u8; 8], + pub(crate) va_reserved: [u32; 4], +} + +va_bits! { + /// `VAFilmGrainStructAV1::film_grain_info_fields`. + FilmGrainInfoFields: u32 { + apply_grain: 1, + chroma_scaling_from_luma: 1, + grain_scaling_minus_8: 2, + ar_coeff_lag: 2, + ar_coeff_shift_minus_6: 2, + grain_scale_shift: 2, + overlap_flag: 1, + clip_to_restricted_range: 1, + } +} + +/// `VAFilmGrainStructAV1`, `va_dec_av1.h:100`. +/// +/// Film grain synthesis is a display-side effect; the decoder fills this so a +/// driver that applies grain can, and edith's own path leaves `apply_grain` +/// clear (the frame it wants is the ungrained reconstruction). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub struct FilmGrainStructAV1 { + /// Film grain flags. + pub film_grain_info_fields: FilmGrainInfoFields, + /// `grain_seed`. + pub grain_seed: u16, + /// `num_y_points`. + pub num_y_points: u8, + /// `point_y_value`. + pub point_y_value: [u8; 14], + /// `point_y_scaling`. + pub point_y_scaling: [u8; 14], + /// `num_cb_points`. + pub num_cb_points: u8, + /// `point_cb_value`. + pub point_cb_value: [u8; 10], + /// `point_cb_scaling`. + pub point_cb_scaling: [u8; 10], + /// `num_cr_points`. + pub num_cr_points: u8, + /// `point_cr_value`. + pub point_cr_value: [u8; 10], + /// `point_cr_scaling`. + pub point_cr_scaling: [u8; 10], + /// `ar_coeffs_y_plus_128 - 128`. + pub ar_coeffs_y: [i8; 24], + /// `ar_coeffs_cb_plus_128 - 128`. + pub ar_coeffs_cb: [i8; 25], + /// `ar_coeffs_cr_plus_128 - 128`. + pub ar_coeffs_cr: [i8; 25], + /// `cb_mult`. + pub cb_mult: u8, + /// `cb_luma_mult`. + pub cb_luma_mult: u8, + /// `cb_offset`. + pub cb_offset: u16, + /// `cr_mult`. + pub cr_mult: u8, + /// `cr_luma_mult`. + pub cr_luma_mult: u8, + /// `cr_offset`. + pub cr_offset: u16, + pub(crate) va_reserved: [u32; 4], +} + +/// `VAWarpedMotionParamsAV1`, `va_dec_av1.h:180`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub struct WarpedMotionParamsAV1 { + /// `VAAV1Transformation*`: identity, translation, rotzoom or affine. + pub wmtype: i32, + /// `gm_params`, six meaningful entries. + pub wmmat: [i32; 8], + /// Set when the model was rejected as non-invertible. + pub invalid: u8, + pub(crate) va_reserved: [u32; 4], +} + +va_bits! { + /// `VADecPictureParameterBufferAV1::seq_info_fields`. + SeqInfoFields: u32 { + still_picture: 1, + use_128x128_superblock: 1, + enable_filter_intra: 1, + enable_intra_edge_filter: 1, + enable_interintra_compound: 1, + enable_masked_compound: 1, + enable_dual_filter: 1, + enable_order_hint: 1, + enable_jnt_comp: 1, + enable_cdef: 1, + mono_chrome: 1, + color_range: 1, + subsampling_x: 1, + subsampling_y: 1, + chroma_sample_position: 1, + film_grain_params_present: 1, + } +} + +va_bits! { + /// `VADecPictureParameterBufferAV1::pic_info_fields`. + PicInfoFields: u32 { + frame_type: 2, + show_frame: 1, + showable_frame: 1, + error_resilient_mode: 1, + disable_cdf_update: 1, + allow_screen_content_tools: 1, + force_integer_mv: 1, + allow_intrabc: 1, + use_superres: 1, + allow_high_precision_mv: 1, + is_motion_mode_switchable: 1, + use_ref_frame_mvs: 1, + disable_frame_end_update_cdf: 1, + uniform_tile_spacing_flag: 1, + allow_warped_motion: 1, + large_scale_tile: 1, + } +} + +va_bits! { + /// `VADecPictureParameterBufferAV1::loop_filter_info_fields`. + LoopFilterInfoFields: u8 { + sharpness_level: 3, + mode_ref_delta_enabled: 1, + mode_ref_delta_update: 1, + } +} + +va_bits! { + /// `VADecPictureParameterBufferAV1::qmatrix_fields`. + QMatrixFields: u16 { + using_qmatrix: 1, + qm_y: 4, + qm_u: 4, + qm_v: 4, + } +} + +va_bits! { + /// `VADecPictureParameterBufferAV1::mode_control_fields`. + ModeControlFields: u32 { + delta_q_present_flag: 1, + log2_delta_q_res: 2, + delta_lf_present_flag: 1, + log2_delta_lf_res: 2, + delta_lf_multi: 1, + tx_mode: 2, + reference_select: 1, + reduced_tx_set_used: 1, + skip_mode_present: 1, + } +} + +va_bits! { + /// `VADecPictureParameterBufferAV1::loop_restoration_fields`. + LoopRestorationFields: u16 { + yframe_restoration_type: 2, + cbframe_restoration_type: 2, + crframe_restoration_type: 2, + lr_unit_shift: 2, + lr_uv_shift: 1, + } +} + +/// `VADecPictureParameterBufferAV1`, `va_dec_av1.h:206`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct PictureParameterBufferAV1 { + /// `seq_profile`. + pub profile: u8, + /// `OrderHintBits - 1`. + pub order_hint_bits_minus_1: u8, + /// 0 for 8-bit, 1 for 10-bit, 2 for 12-bit. + pub bit_depth_idx: u8, + /// `matrix_coefficients` (H.273). + pub matrix_coefficients: u8, + /// Sequence header flags. + pub seq_info_fields: SeqInfoFields, + /// Surface being decoded into. + pub current_frame: VASurfaceID, + /// Surface to display for a `show_existing_frame`, else the current frame. + pub current_display_picture: VASurfaceID, + /// Large scale tile only; always zero here. + pub anchor_frames_num: u8, + /// Large scale tile only; always NULL here. + pub anchor_frames_list: *mut c_void, + /// `FrameWidth - 1`. + pub frame_width_minus1: u16, + /// `FrameHeight - 1`. + pub frame_height_minus1: u16, + /// Large scale tile only. + pub output_frame_width_in_tiles_minus_1: u16, + /// Large scale tile only. + pub output_frame_height_in_tiles_minus_1: u16, + /// The eight reference slots. + pub ref_frame_map: [VASurfaceID; 8], + /// `ref_frame_idx`, LAST through ALTREF. + pub ref_frame_idx: [u8; 7], + /// `primary_ref_frame`. + pub primary_ref_frame: u8, + /// `OrderHint`. + pub order_hint: u8, + /// Segmentation parameters. + pub seg_info: SegmentationStructAV1, + /// Film grain parameters. + pub film_grain_info: FilmGrainStructAV1, + /// `TileCols`. + pub tile_cols: u8, + /// `TileRows`. + pub tile_rows: u8, + /// Per-column widths in superblocks, minus one. + pub width_in_sbs_minus_1: [u16; 63], + /// Per-row heights in superblocks, minus one. + pub height_in_sbs_minus_1: [u16; 63], + /// `TileCols * TileRows - 1`. + pub tile_count_minus_1: u16, + /// `context_update_tile_id`. + pub context_update_tile_id: u16, + /// Frame header flags. + pub pic_info_fields: PicInfoFields, + /// `SuperresDenom`. + pub superres_scale_denominator: u8, + /// `interpolation_filter`. + pub interp_filter: u8, + /// `loop_filter_level[0..2]`. + pub filter_level: [u8; 2], + /// `loop_filter_level[2]`. + pub filter_level_u: u8, + /// `loop_filter_level[3]`. + pub filter_level_v: u8, + /// Loop filter flags. + pub loop_filter_info_fields: LoopFilterInfoFields, + /// `loop_filter_ref_deltas`. + pub ref_deltas: [i8; 8], + /// `loop_filter_mode_deltas`. + pub mode_deltas: [i8; 2], + /// `base_q_idx`. + pub base_qindex: u8, + /// `DeltaQYDc`. + pub y_dc_delta_q: i8, + /// `DeltaQUDc`. + pub u_dc_delta_q: i8, + /// `DeltaQUAc`. + pub u_ac_delta_q: i8, + /// `DeltaQVDc`. + pub v_dc_delta_q: i8, + /// `DeltaQVAc`. + pub v_ac_delta_q: i8, + /// Quantiser matrix flags. + pub qmatrix_fields: QMatrixFields, + /// Mode control flags. + pub mode_control_fields: ModeControlFields, + /// `CdefDamping - 3`. + pub cdef_damping_minus_3: u8, + /// `cdef_bits`. + pub cdef_bits: u8, + /// Combined luma primary/secondary strengths, as libva packs them. + pub cdef_y_strengths: [u8; 8], + /// Combined chroma primary/secondary strengths. + pub cdef_uv_strengths: [u8; 8], + /// Loop restoration flags. + pub loop_restoration_fields: LoopRestorationFields, + /// Global motion for LAST..ALTREF. + pub wm: [WarpedMotionParamsAV1; 7], + pub(crate) va_reserved: [u32; 8], +} + +impl Default for PictureParameterBufferAV1 { + fn default() -> Self { + PictureParameterBufferAV1 { + profile: 0, + order_hint_bits_minus_1: 0, + bit_depth_idx: 0, + matrix_coefficients: 2, // MC_UNSPECIFIED + seq_info_fields: SeqInfoFields::default(), + current_frame: INVALID_SURFACE, + current_display_picture: INVALID_SURFACE, + anchor_frames_num: 0, + anchor_frames_list: std::ptr::null_mut(), + frame_width_minus1: 0, + frame_height_minus1: 0, + output_frame_width_in_tiles_minus_1: 0, + output_frame_height_in_tiles_minus_1: 0, + ref_frame_map: [INVALID_SURFACE; 8], + ref_frame_idx: [0; 7], + primary_ref_frame: 0, + order_hint: 0, + seg_info: SegmentationStructAV1::default(), + film_grain_info: FilmGrainStructAV1::default(), + tile_cols: 1, + tile_rows: 1, + width_in_sbs_minus_1: [0; 63], + height_in_sbs_minus_1: [0; 63], + tile_count_minus_1: 0, + context_update_tile_id: 0, + pic_info_fields: PicInfoFields::default(), + superres_scale_denominator: 8, + interp_filter: 0, + filter_level: [0; 2], + filter_level_u: 0, + filter_level_v: 0, + loop_filter_info_fields: LoopFilterInfoFields::default(), + ref_deltas: [0; 8], + mode_deltas: [0; 2], + base_qindex: 0, + y_dc_delta_q: 0, + u_dc_delta_q: 0, + u_ac_delta_q: 0, + v_dc_delta_q: 0, + v_ac_delta_q: 0, + qmatrix_fields: QMatrixFields::default(), + mode_control_fields: ModeControlFields::default(), + cdef_damping_minus_3: 0, + cdef_bits: 0, + cdef_y_strengths: [0; 8], + cdef_uv_strengths: [0; 8], + loop_restoration_fields: LoopRestorationFields::default(), + wm: [WarpedMotionParamsAV1::default(); 7], + va_reserved: [0; 8], + } + } +} + +// SAFETY: `#[repr(C)]` transcription of `VADecPictureParameterBufferAV1`, +// checked by the assertion block below. The one pointer field is the large +// scale tile anchor list, which this crate always leaves NULL (that mode is out +// of scope), so no dangling pointer can reach the driver. +unsafe impl VaParam for PictureParameterBufferAV1 { + const TYPE: i32 = VAPictureParameterBufferType; +} + +/// `VASliceParameterBufferAV1`, `va_dec_av1.h:660` — one per tile. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub struct SliceParameterBufferAV1 { + /// Bytes of tile data. + pub slice_data_size: u32, + /// Offset of the tile within the data buffer. + pub slice_data_offset: u32, + /// `VA_SLICE_DATA_FLAG_*`. + pub slice_data_flag: u32, + /// Tile row. + pub tile_row: u16, + /// Tile column. + pub tile_column: u16, + pub(crate) tg_start: u16, + pub(crate) tg_end: u16, + /// Large scale tile only. + pub anchor_frame_idx: u8, + /// Large scale tile only. + pub tile_idx_in_tile_list: u16, + pub(crate) va_reserved: [u32; 4], +} + +// SAFETY: as `PictureParameterBufferAV1`; integers only. +unsafe impl VaParam for SliceParameterBufferAV1 { + const TYPE: i32 = VASliceParameterBufferType; +} + +// --------------------------------------------------------------------------- +// ABI transcription check — `crates/ec-hw/abi-probe.c`, libva 1.23.0, x86_64: +// +// VASegmentationStructAV1 size=156 align=4 feature_data=4 +// feature_mask=132 +// VAFilmGrainStructAV1 size=176 align=4 grain_seed=4 +// ar_coeffs_y=77 cr_offset=158 +// VAWarpedMotionParamsAV1 size=56 align=4 wmmat=4 invalid=36 +// VADecPictureParameterBufferAV1 size=1160 align=8 seq_info_fields=4 +// current_frame=8 +// anchor_frames_num=16 +// anchor_frames_list=24 +// frame_width_minus1=32 +// ref_frame_map=40 +// ref_frame_idx=72 +// seg_info=84 +// film_grain_info=240 +// tile_cols=416 +// width_in_sbs_minus_1=418 +// height_in_sbs_minus_1=544 +// tile_count_minus_1=670 +// pic_info_fields=676 +// superres_scale_denominator=680 +// loop_filter_info_fields=686 +// ref_deltas=687 base_qindex=697 +// qmatrix_fields=704 +// mode_control_fields=708 +// cdef_damping_minus_3=712 +// cdef_y_strengths=714 +// loop_restoration_fields=730 +// wm=732 +// VASliceParameterBufferAV1 size=40 align=4 tile_row=12 +// anchor_frame_idx=20 +// tile_idx_in_tile_list=22 +const _: () = { + use std::mem::{align_of, offset_of, size_of}; + + assert!(size_of::() == 156 && align_of::() == 4); + assert!(offset_of!(SegmentationStructAV1, feature_data) == 4); + assert!(offset_of!(SegmentationStructAV1, feature_mask) == 132); + + assert!(size_of::() == 176 && align_of::() == 4); + assert!(offset_of!(FilmGrainStructAV1, grain_seed) == 4); + assert!(offset_of!(FilmGrainStructAV1, ar_coeffs_y) == 77); + assert!(offset_of!(FilmGrainStructAV1, cr_offset) == 158); + + assert!(size_of::() == 56 && align_of::() == 4); + assert!(offset_of!(WarpedMotionParamsAV1, wmmat) == 4); + assert!(offset_of!(WarpedMotionParamsAV1, invalid) == 36); + + assert!( + size_of::() == 1160 + && align_of::() == 8 + ); + assert!(offset_of!(PictureParameterBufferAV1, seq_info_fields) == 4); + assert!(offset_of!(PictureParameterBufferAV1, current_frame) == 8); + assert!(offset_of!(PictureParameterBufferAV1, anchor_frames_num) == 16); + assert!(offset_of!(PictureParameterBufferAV1, anchor_frames_list) == 24); + assert!(offset_of!(PictureParameterBufferAV1, frame_width_minus1) == 32); + assert!(offset_of!(PictureParameterBufferAV1, ref_frame_map) == 40); + assert!(offset_of!(PictureParameterBufferAV1, ref_frame_idx) == 72); + assert!(offset_of!(PictureParameterBufferAV1, seg_info) == 84); + assert!(offset_of!(PictureParameterBufferAV1, film_grain_info) == 240); + assert!(offset_of!(PictureParameterBufferAV1, tile_cols) == 416); + assert!(offset_of!(PictureParameterBufferAV1, width_in_sbs_minus_1) == 418); + assert!(offset_of!(PictureParameterBufferAV1, height_in_sbs_minus_1) == 544); + assert!(offset_of!(PictureParameterBufferAV1, tile_count_minus_1) == 670); + assert!(offset_of!(PictureParameterBufferAV1, pic_info_fields) == 676); + assert!(offset_of!(PictureParameterBufferAV1, superres_scale_denominator) == 680); + assert!(offset_of!(PictureParameterBufferAV1, loop_filter_info_fields) == 686); + assert!(offset_of!(PictureParameterBufferAV1, ref_deltas) == 687); + assert!(offset_of!(PictureParameterBufferAV1, base_qindex) == 697); + assert!(offset_of!(PictureParameterBufferAV1, qmatrix_fields) == 704); + assert!(offset_of!(PictureParameterBufferAV1, mode_control_fields) == 708); + assert!(offset_of!(PictureParameterBufferAV1, cdef_damping_minus_3) == 712); + assert!(offset_of!(PictureParameterBufferAV1, cdef_y_strengths) == 714); + assert!(offset_of!(PictureParameterBufferAV1, loop_restoration_fields) == 730); + assert!(offset_of!(PictureParameterBufferAV1, wm) == 732); + + assert!( + size_of::() == 40 && align_of::() == 4 + ); + assert!(offset_of!(SliceParameterBufferAV1, tile_row) == 12); + assert!(offset_of!(SliceParameterBufferAV1, anchor_frame_idx) == 20); + assert!(offset_of!(SliceParameterBufferAV1, tile_idx_in_tile_list) == 22); +}; diff --git a/crates/ec-hw/src/params/enc.rs b/crates/ec-hw/src/params/enc.rs new file mode 100644 index 00000000..ce1fa07c --- /dev/null +++ b/crates/ec-hw/src/params/enc.rs @@ -0,0 +1,1494 @@ +//! Encode parameter buffers: H.264, HEVC and AV1, plus the codec-independent +//! misc-parameter and packed-header buffers (`va.h`, `va_enc_*.h`). + +use ec_va::sys::{ + VAEncPackedHeaderParameterBufferType, VAEncPictureParameterBufferType, + VAEncSequenceParameterBufferType, VAEncSliceParameterBufferType, VASurfaceID, +}; + +use super::VaParam; +use super::h264::VAPictureH264; +use super::hevc::VAPictureHEVC; +use crate::va_bits; + +/// `VAEncPackedHeaderSequence` (`va.h:2421`) — SPS/VPS. +pub const PACKED_HEADER_SEQUENCE: u32 = 1; +/// `VAEncPackedHeaderPicture` — PPS. +pub const PACKED_HEADER_PICTURE: u32 = 2; +/// `VAEncPackedHeaderSlice` — slice header. +pub const PACKED_HEADER_SLICE: u32 = 3; +/// `VAEncPackedHeaderRawData` — anything else, e.g. an AV1 OBU. +pub const PACKED_HEADER_RAW_DATA: u32 = 4; + +/// `VAEncMiscParameterTypeFrameRate`. +pub const MISC_FRAME_RATE: u32 = 0; +/// `VAEncMiscParameterTypeRateControl`. +pub const MISC_RATE_CONTROL: u32 = 1; +/// `VAEncMiscParameterTypeHRD`. +pub const MISC_HRD: u32 = 5; +/// `VAEncMiscParameterTypeQualityLevel`. +pub const MISC_QUALITY_LEVEL: u32 = 6; + +/// `VAEncPackedHeaderParameterBuffer`, `va.h:2446`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub struct PackedHeaderParameterBuffer { + /// One of the `PACKED_HEADER_*` constants. + pub type_: u32, + /// Length of the packed header in bits. + pub bit_length: u32, + /// Whether the data already carries emulation prevention bytes. + pub has_emulation_bytes: u8, + pub(crate) va_reserved: [u32; 4], +} + +impl PackedHeaderParameterBuffer { + /// A header whose bytes are already escaped, as everything this crate + /// writes is (the syntax crates emit Annex B ready bytes). + pub fn escaped(type_: u32, bytes: usize) -> PackedHeaderParameterBuffer { + PackedHeaderParameterBuffer { + type_, + bit_length: (bytes * 8) as u32, + has_emulation_bytes: 1, + va_reserved: [0; 4], + } + } +} + +// SAFETY: `#[repr(C)]` transcription of `VAEncPackedHeaderParameterBuffer`, +// checked below; integers only. +unsafe impl VaParam for PackedHeaderParameterBuffer { + const TYPE: i32 = VAEncPackedHeaderParameterBufferType; +} + +/// `VAEncMiscParameterRateControl`, `va.h:2492`. +/// +/// Built as words rather than as a struct because a misc parameter is submitted +/// as `{ type, payload }` in one buffer: the payload of every misc type this +/// crate sends is a run of `uint32_t`, so it can be assembled without ever +/// taking a byte view of a Rust struct. +#[derive(Debug, Clone, Copy, Default)] +pub struct RateControl { + /// Target bitrate, or the peak bitrate under VBR. + pub bits_per_second: u32, + /// Percentage of `bits_per_second` to target (VBR); 0 means CBR. + pub target_percentage: u32, + /// Rate control window in milliseconds. + pub window_size: u32, + /// Initial quantiser, 0 to let the driver choose. + pub initial_qp: u32, + /// Minimum quantiser. + pub min_qp: u32, + /// Maximum quantiser. + pub max_qp: u32, +} + +impl RateControl { + /// The payload words in header order. + pub fn words(&self) -> [u32; 15] { + [ + self.bits_per_second, + self.target_percentage, + self.window_size, + self.initial_qp, + self.min_qp, + 0, // basic_unit_size + 0, // rc_flags + 0, // ICQ_quality_factor + self.max_qp, + 0, // quality_factor + 0, // target_frame_size + 0, + 0, + 0, + 0, // va_reserved[4] + ] + } +} + +/// `VAEncMiscParameterFrameRate`, `va.h:2617`. +#[derive(Debug, Clone, Copy)] +pub struct FrameRate { + /// Numerator of the frame rate. + pub num: u32, + /// Denominator of the frame rate. + pub den: u32, +} + +impl FrameRate { + /// The payload words. libva packs a fractional rate as + /// `den << 16 | num`, and a whole one as the plain numerator. + pub fn words(&self) -> [u32; 6] { + let packed = if self.den <= 1 { + self.num + } else { + (self.den << 16) | (self.num & 0xffff) + }; + [packed, 0, 0, 0, 0, 0] + } +} + +/// `VAEncMiscParameterHRD`, `va.h:2721`. +#[derive(Debug, Clone, Copy, Default)] +pub struct Hrd { + /// Initial CPB fullness in bits. + pub initial_buffer_fullness: u32, + /// CPB size in bits. + pub buffer_size: u32, +} + +impl Hrd { + /// The payload words in header order. + pub fn words(&self) -> [u32; 6] { + [self.initial_buffer_fullness, self.buffer_size, 0, 0, 0, 0] + } +} + +/// Serialise a misc parameter buffer: the type word followed by its payload. +pub fn misc_bytes(type_: u32, words: &[u32]) -> Vec { + let mut out = Vec::with_capacity(4 + words.len() * 4); + out.extend_from_slice(&type_.to_ne_bytes()); + for w in words { + out.extend_from_slice(&w.to_ne_bytes()); + } + out +} + +// --------------------------------------------------------------------------- +// H.264 encode +// --------------------------------------------------------------------------- + +va_bits! { + /// `VAEncSequenceParameterBufferH264::seq_fields`. + H264SeqFields: u32 { + chroma_format_idc: 2, + frame_mbs_only_flag: 1, + mb_adaptive_frame_field_flag: 1, + seq_scaling_matrix_present_flag: 1, + direct_8x8_inference_flag: 1, + log2_max_frame_num_minus4: 4, + pic_order_cnt_type: 2, + log2_max_pic_order_cnt_lsb_minus4: 4, + delta_pic_order_always_zero_flag: 1, + } +} + +va_bits! { + /// `VAEncSequenceParameterBufferH264::vui_fields`. + H264VuiFields: u32 { + aspect_ratio_info_present_flag: 1, + timing_info_present_flag: 1, + bitstream_restriction_flag: 1, + log2_max_mv_length_horizontal: 5, + log2_max_mv_length_vertical: 5, + fixed_frame_rate_flag: 1, + low_delay_hrd_flag: 1, + motion_vectors_over_pic_boundaries_flag: 1, + } +} + +/// `VAEncSequenceParameterBufferH264`, `va_enc_h264.h:78`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct EncSequenceParameterBufferH264 { + /// `seq_parameter_set_id`. + pub seq_parameter_set_id: u8, + /// `level_idc`. + pub level_idc: u8, + /// Frames between I frames. + pub intra_period: u32, + /// Frames between IDR frames. + pub intra_idr_period: u32, + /// Distance between P frames (1 = no B frames). + pub ip_period: u32, + /// Target bitrate. + pub bits_per_second: u32, + /// `max_num_ref_frames`. + pub max_num_ref_frames: u32, + /// `PicWidthInMbs`. + pub picture_width_in_mbs: u16, + /// `PicHeightInMapUnits`. + pub picture_height_in_mbs: u16, + /// Sequence flags. + pub seq_fields: H264SeqFields, + /// `bit_depth_luma_minus8`. + pub bit_depth_luma_minus8: u8, + /// `bit_depth_chroma_minus8`. + pub bit_depth_chroma_minus8: u8, + /// `num_ref_frames_in_pic_order_cnt_cycle`. + pub num_ref_frames_in_pic_order_cnt_cycle: u8, + /// `offset_for_non_ref_pic`. + pub offset_for_non_ref_pic: i32, + /// `offset_for_top_to_bottom_field`. + pub offset_for_top_to_bottom_field: i32, + /// `offset_for_ref_frame`. + pub offset_for_ref_frame: [i32; 256], + /// `frame_cropping_flag`. + pub frame_cropping_flag: u8, + /// `frame_crop_left_offset`. + pub frame_crop_left_offset: u32, + /// `frame_crop_right_offset`. + pub frame_crop_right_offset: u32, + /// `frame_crop_top_offset`. + pub frame_crop_top_offset: u32, + /// `frame_crop_bottom_offset`. + pub frame_crop_bottom_offset: u32, + /// `vui_parameters_present_flag`. + pub vui_parameters_present_flag: u8, + /// VUI flags. + pub vui_fields: H264VuiFields, + /// `aspect_ratio_idc`. + pub aspect_ratio_idc: u8, + /// `sar_width`. + pub sar_width: u32, + /// `sar_height`. + pub sar_height: u32, + /// `num_units_in_tick`. + pub num_units_in_tick: u32, + /// `time_scale`. + pub time_scale: u32, + pub(crate) va_reserved: [u32; 4], +} + +impl Default for EncSequenceParameterBufferH264 { + fn default() -> Self { + EncSequenceParameterBufferH264 { + seq_parameter_set_id: 0, + level_idc: 41, + intra_period: 0, + intra_idr_period: 0, + ip_period: 1, + bits_per_second: 0, + max_num_ref_frames: 1, + picture_width_in_mbs: 0, + picture_height_in_mbs: 0, + seq_fields: H264SeqFields::default(), + bit_depth_luma_minus8: 0, + bit_depth_chroma_minus8: 0, + num_ref_frames_in_pic_order_cnt_cycle: 0, + offset_for_non_ref_pic: 0, + offset_for_top_to_bottom_field: 0, + offset_for_ref_frame: [0; 256], + frame_cropping_flag: 0, + frame_crop_left_offset: 0, + frame_crop_right_offset: 0, + frame_crop_top_offset: 0, + frame_crop_bottom_offset: 0, + vui_parameters_present_flag: 0, + vui_fields: H264VuiFields::default(), + aspect_ratio_idc: 0, + sar_width: 0, + sar_height: 0, + num_units_in_tick: 0, + time_scale: 0, + va_reserved: [0; 4], + } + } +} + +// SAFETY: `#[repr(C)]` transcription checked by the assertion block below. +unsafe impl VaParam for EncSequenceParameterBufferH264 { + const TYPE: i32 = VAEncSequenceParameterBufferType; +} + +va_bits! { + /// `VAEncPictureParameterBufferH264::pic_fields`. + H264EncPicFields: u32 { + idr_pic_flag: 1, + reference_pic_flag: 2, + entropy_coding_mode_flag: 1, + weighted_pred_flag: 1, + weighted_bipred_idc: 2, + constrained_intra_pred_flag: 1, + transform_8x8_mode_flag: 1, + deblocking_filter_control_present_flag: 1, + redundant_pic_cnt_present_flag: 1, + pic_order_present_flag: 1, + pic_scaling_matrix_present_flag: 1, + } +} + +/// `VAEncPictureParameterBufferH264`, `va_enc_h264.h:222`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct EncPictureParameterBufferH264 { + /// Reconstructed picture surface for this frame. + pub curr_pic: VAPictureH264, + /// Reference pictures available to this frame. + pub reference_frames: [VAPictureH264; 16], + /// Buffer the coded bits are written to. + pub coded_buf: u32, + /// `pic_parameter_set_id`. + pub pic_parameter_set_id: u8, + /// `seq_parameter_set_id`. + pub seq_parameter_set_id: u8, + /// `H264_LAST_PICTURE_*` when this is the last picture. + pub last_picture: u8, + /// `frame_num`. + pub frame_num: u16, + /// `pic_init_qp_minus26 + 26`. + pub pic_init_qp: u8, + /// `num_ref_idx_l0_active_minus1`. + pub num_ref_idx_l0_active_minus1: u8, + /// `num_ref_idx_l1_active_minus1`. + pub num_ref_idx_l1_active_minus1: u8, + /// `chroma_qp_index_offset`. + pub chroma_qp_index_offset: i8, + /// `second_chroma_qp_index_offset`. + pub second_chroma_qp_index_offset: i8, + /// Picture flags. + pub pic_fields: H264EncPicFields, + pub(crate) va_reserved: [u32; 4], +} + +impl Default for EncPictureParameterBufferH264 { + fn default() -> Self { + EncPictureParameterBufferH264 { + curr_pic: VAPictureH264::INVALID, + reference_frames: [VAPictureH264::INVALID; 16], + coded_buf: 0, + pic_parameter_set_id: 0, + seq_parameter_set_id: 0, + last_picture: 0, + frame_num: 0, + pic_init_qp: 26, + num_ref_idx_l0_active_minus1: 0, + num_ref_idx_l1_active_minus1: 0, + chroma_qp_index_offset: 0, + second_chroma_qp_index_offset: 0, + pic_fields: H264EncPicFields::default(), + va_reserved: [0; 4], + } + } +} + +// SAFETY: `#[repr(C)]` transcription checked by the assertion block below. +unsafe impl VaParam for EncPictureParameterBufferH264 { + const TYPE: i32 = VAEncPictureParameterBufferType; +} + +/// `VAEncSliceParameterBufferH264`, `va_enc_h264.h:290`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct EncSliceParameterBufferH264 { + /// First macroblock of this slice. + pub macroblock_address: u32, + /// Macroblocks in this slice. + pub num_macroblocks: u32, + /// Optional per-macroblock parameter buffer; `VA_INVALID_ID` for none. + pub macroblock_info: u32, + /// `slice_type`. + pub slice_type: u8, + /// `pic_parameter_set_id`. + pub pic_parameter_set_id: u8, + /// `idr_pic_id`. + pub idr_pic_id: u16, + /// `pic_order_cnt_lsb`. + pub pic_order_cnt_lsb: u16, + /// `delta_pic_order_cnt_bottom`. + pub delta_pic_order_cnt_bottom: i32, + /// `delta_pic_order_cnt`. + pub delta_pic_order_cnt: [i32; 2], + /// `direct_spatial_mv_pred_flag`. + pub direct_spatial_mv_pred_flag: u8, + /// `num_ref_idx_active_override_flag`. + pub num_ref_idx_active_override_flag: u8, + /// `num_ref_idx_l0_active_minus1`. + pub num_ref_idx_l0_active_minus1: u8, + /// `num_ref_idx_l1_active_minus1`. + pub num_ref_idx_l1_active_minus1: u8, + /// `RefPicList0`. + pub ref_pic_list0: [VAPictureH264; 32], + /// `RefPicList1`. + pub ref_pic_list1: [VAPictureH264; 32], + /// `luma_log2_weight_denom`. + pub luma_log2_weight_denom: u8, + /// `chroma_log2_weight_denom`. + pub chroma_log2_weight_denom: u8, + /// `luma_weight_l0_flag`. + pub luma_weight_l0_flag: u8, + /// `luma_weight_l0`. + pub luma_weight_l0: [i16; 32], + /// `luma_offset_l0`. + pub luma_offset_l0: [i16; 32], + /// `chroma_weight_l0_flag`. + pub chroma_weight_l0_flag: u8, + /// `chroma_weight_l0`. + pub chroma_weight_l0: [[i16; 2]; 32], + /// `chroma_offset_l0`. + pub chroma_offset_l0: [[i16; 2]; 32], + /// `luma_weight_l1_flag`. + pub luma_weight_l1_flag: u8, + /// `luma_weight_l1`. + pub luma_weight_l1: [i16; 32], + /// `luma_offset_l1`. + pub luma_offset_l1: [i16; 32], + /// `chroma_weight_l1_flag`. + pub chroma_weight_l1_flag: u8, + /// `chroma_weight_l1`. + pub chroma_weight_l1: [[i16; 2]; 32], + /// `chroma_offset_l1`. + pub chroma_offset_l1: [[i16; 2]; 32], + /// `cabac_init_idc`. + pub cabac_init_idc: u8, + /// `slice_qp_delta`. + pub slice_qp_delta: i8, + /// `disable_deblocking_filter_idc`. + pub disable_deblocking_filter_idc: u8, + /// `slice_alpha_c0_offset_div2`. + pub slice_alpha_c0_offset_div2: i8, + /// `slice_beta_offset_div2`. + pub slice_beta_offset_div2: i8, + pub(crate) va_reserved: [u32; 4], +} + +impl Default for EncSliceParameterBufferH264 { + fn default() -> Self { + EncSliceParameterBufferH264 { + macroblock_address: 0, + num_macroblocks: 0, + macroblock_info: ec_va::sys::VA_INVALID_ID, + slice_type: 2, + pic_parameter_set_id: 0, + idr_pic_id: 0, + pic_order_cnt_lsb: 0, + delta_pic_order_cnt_bottom: 0, + delta_pic_order_cnt: [0; 2], + direct_spatial_mv_pred_flag: 0, + num_ref_idx_active_override_flag: 0, + num_ref_idx_l0_active_minus1: 0, + num_ref_idx_l1_active_minus1: 0, + ref_pic_list0: [VAPictureH264::INVALID; 32], + ref_pic_list1: [VAPictureH264::INVALID; 32], + luma_log2_weight_denom: 0, + chroma_log2_weight_denom: 0, + luma_weight_l0_flag: 0, + luma_weight_l0: [0; 32], + luma_offset_l0: [0; 32], + chroma_weight_l0_flag: 0, + chroma_weight_l0: [[0; 2]; 32], + chroma_offset_l0: [[0; 2]; 32], + luma_weight_l1_flag: 0, + luma_weight_l1: [0; 32], + luma_offset_l1: [0; 32], + chroma_weight_l1_flag: 0, + chroma_weight_l1: [[0; 2]; 32], + chroma_offset_l1: [[0; 2]; 32], + cabac_init_idc: 0, + slice_qp_delta: 0, + disable_deblocking_filter_idc: 0, + slice_alpha_c0_offset_div2: 0, + slice_beta_offset_div2: 0, + va_reserved: [0; 4], + } + } +} + +// SAFETY: `#[repr(C)]` transcription checked by the assertion block below. +unsafe impl VaParam for EncSliceParameterBufferH264 { + const TYPE: i32 = VAEncSliceParameterBufferType; +} + +// --------------------------------------------------------------------------- +// HEVC encode +// --------------------------------------------------------------------------- + +va_bits! { + /// `VAEncSequenceParameterBufferHEVC::seq_fields`. + HevcSeqFields: u32 { + chroma_format_idc: 2, + separate_colour_plane_flag: 1, + bit_depth_luma_minus8: 3, + bit_depth_chroma_minus8: 3, + scaling_list_enabled_flag: 1, + strong_intra_smoothing_enabled_flag: 1, + amp_enabled_flag: 1, + sample_adaptive_offset_enabled_flag: 1, + pcm_enabled_flag: 1, + pcm_loop_filter_disabled_flag: 1, + sps_temporal_mvp_enabled_flag: 1, + low_delay_seq: 1, + hierachical_flag: 1, + } +} + +va_bits! { + /// `VAEncSequenceParameterBufferHEVC::vui_fields`. + HevcVuiFields: u32 { + aspect_ratio_info_present_flag: 1, + neutral_chroma_indication_flag: 1, + field_seq_flag: 1, + vui_timing_info_present_flag: 1, + bitstream_restriction_flag: 1, + tiles_fixed_structure_flag: 1, + motion_vectors_over_pic_boundaries_flag: 1, + restricted_ref_pic_lists_flag: 1, + log2_max_mv_length_horizontal: 5, + log2_max_mv_length_vertical: 5, + } +} + +/// `VAEncSequenceParameterBufferHEVC`, `va_enc_hevc.h:139`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct EncSequenceParameterBufferHEVC { + /// `general_profile_idc`. + pub general_profile_idc: u8, + /// `general_level_idc`. + pub general_level_idc: u8, + /// `general_tier_flag`. + pub general_tier_flag: u8, + /// Frames between I frames. + pub intra_period: u32, + /// Frames between IDR frames. + pub intra_idr_period: u32, + /// Distance between P frames. + pub ip_period: u32, + /// Target bitrate. + pub bits_per_second: u32, + /// `pic_width_in_luma_samples`. + pub pic_width_in_luma_samples: u16, + /// `pic_height_in_luma_samples`. + pub pic_height_in_luma_samples: u16, + /// Sequence flags. + pub seq_fields: HevcSeqFields, + /// `log2_min_luma_coding_block_size_minus3`. + pub log2_min_luma_coding_block_size_minus3: u8, + /// `log2_diff_max_min_luma_coding_block_size`. + pub log2_diff_max_min_luma_coding_block_size: u8, + /// `log2_min_transform_block_size_minus2`. + pub log2_min_transform_block_size_minus2: u8, + /// `log2_diff_max_min_transform_block_size`. + pub log2_diff_max_min_transform_block_size: u8, + /// `max_transform_hierarchy_depth_inter`. + pub max_transform_hierarchy_depth_inter: u8, + /// `max_transform_hierarchy_depth_intra`. + pub max_transform_hierarchy_depth_intra: u8, + /// `pcm_sample_bit_depth_luma_minus1`. + pub pcm_sample_bit_depth_luma_minus1: u32, + /// `pcm_sample_bit_depth_chroma_minus1`. + pub pcm_sample_bit_depth_chroma_minus1: u32, + /// `log2_min_pcm_luma_coding_block_size_minus3`. + pub log2_min_pcm_luma_coding_block_size_minus3: u32, + /// `log2_max_pcm_luma_coding_block_size_minus3`. + pub log2_max_pcm_luma_coding_block_size_minus3: u32, + /// `vui_parameters_present_flag`. + pub vui_parameters_present_flag: u8, + /// VUI flags. + pub vui_fields: HevcVuiFields, + /// `aspect_ratio_idc`. + pub aspect_ratio_idc: u8, + /// `sar_width`. + pub sar_width: u32, + /// `sar_height`. + pub sar_height: u32, + /// `vui_num_units_in_tick`. + pub vui_num_units_in_tick: u32, + /// `vui_time_scale`. + pub vui_time_scale: u32, + /// `min_spatial_segmentation_idc`. + pub min_spatial_segmentation_idc: u16, + /// `max_bytes_per_pic_denom`. + pub max_bytes_per_pic_denom: u8, + /// `max_bits_per_min_cu_denom`. + pub max_bits_per_min_cu_denom: u8, + /// Screen content flags. + pub scc_fields: u32, + pub(crate) va_reserved: [u32; 7], +} + +impl Default for EncSequenceParameterBufferHEVC { + fn default() -> Self { + EncSequenceParameterBufferHEVC { + general_profile_idc: 1, + general_level_idc: 120, + general_tier_flag: 0, + intra_period: 0, + intra_idr_period: 0, + ip_period: 1, + bits_per_second: 0, + pic_width_in_luma_samples: 0, + pic_height_in_luma_samples: 0, + seq_fields: HevcSeqFields::default(), + log2_min_luma_coding_block_size_minus3: 0, + log2_diff_max_min_luma_coding_block_size: 3, + log2_min_transform_block_size_minus2: 0, + log2_diff_max_min_transform_block_size: 3, + max_transform_hierarchy_depth_inter: 0, + max_transform_hierarchy_depth_intra: 0, + pcm_sample_bit_depth_luma_minus1: 7, + pcm_sample_bit_depth_chroma_minus1: 7, + log2_min_pcm_luma_coding_block_size_minus3: 0, + log2_max_pcm_luma_coding_block_size_minus3: 0, + vui_parameters_present_flag: 0, + vui_fields: HevcVuiFields::default(), + aspect_ratio_idc: 0, + sar_width: 0, + sar_height: 0, + vui_num_units_in_tick: 0, + vui_time_scale: 0, + min_spatial_segmentation_idc: 0, + max_bytes_per_pic_denom: 0, + max_bits_per_min_cu_denom: 0, + scc_fields: 0, + va_reserved: [0; 7], + } + } +} + +// SAFETY: `#[repr(C)]` transcription checked by the assertion block below. +unsafe impl VaParam for EncSequenceParameterBufferHEVC { + const TYPE: i32 = VAEncSequenceParameterBufferType; +} + +va_bits! { + /// `VAEncPictureParameterBufferHEVC::pic_fields`. + HevcEncPicFields: u32 { + idr_pic_flag: 1, + coding_type: 3, + reference_pic_flag: 1, + dependent_slice_segments_enabled_flag: 1, + sign_data_hiding_enabled_flag: 1, + constrained_intra_pred_flag: 1, + transform_skip_enabled_flag: 1, + cu_qp_delta_enabled_flag: 1, + weighted_pred_flag: 1, + weighted_bipred_flag: 1, + transquant_bypass_enabled_flag: 1, + tiles_enabled_flag: 1, + entropy_coding_sync_enabled_flag: 1, + loop_filter_across_tiles_enabled_flag: 1, + pps_loop_filter_across_slices_enabled_flag: 1, + scaling_list_data_present_flag: 1, + screen_content_flag: 1, + enable_gpu_weighted_prediction: 1, + no_output_of_prior_pics_flag: 1, + } +} + +/// `VAEncPictureParameterBufferHEVC`, `va_enc_hevc.h:270`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct EncPictureParameterBufferHEVC { + /// Reconstructed picture surface for this frame. + pub decoded_curr_pic: VAPictureHEVC, + /// Reference pictures available to this frame. + pub reference_frames: [VAPictureHEVC; 15], + /// Buffer the coded bits are written to. + pub coded_buf: u32, + /// Index into `reference_frames` of the collocated picture. + pub collocated_ref_pic_index: u8, + /// `HEVC_LAST_PICTURE_*` when this is the last picture. + pub last_picture: u8, + /// `init_qp_minus26 + 26`. + pub pic_init_qp: u8, + /// `diff_cu_qp_delta_depth`. + pub diff_cu_qp_delta_depth: u8, + /// `pps_cb_qp_offset`. + pub pps_cb_qp_offset: i8, + /// `pps_cr_qp_offset`. + pub pps_cr_qp_offset: i8, + /// `num_tile_columns_minus1`. + pub num_tile_columns_minus1: u8, + /// `num_tile_rows_minus1`. + pub num_tile_rows_minus1: u8, + /// `column_width_minus1`. + pub column_width_minus1: [u8; 19], + /// `row_height_minus1`. + pub row_height_minus1: [u8; 21], + /// `log2_parallel_merge_level_minus2`. + pub log2_parallel_merge_level_minus2: u8, + /// Maximum bits a CTU may use, 0 for no limit. + pub ctu_max_bitsize_allowed: u8, + /// `num_ref_idx_l0_default_active_minus1`. + pub num_ref_idx_l0_default_active_minus1: u8, + /// `num_ref_idx_l1_default_active_minus1`. + pub num_ref_idx_l1_default_active_minus1: u8, + /// `slice_pic_parameter_set_id`. + pub slice_pic_parameter_set_id: u8, + /// NAL unit type to code the slices as. + pub nal_unit_type: u8, + /// Picture flags. + pub pic_fields: HevcEncPicFields, + /// Temporal layer + 1, 0 when unused. + pub hierarchical_level_plus1: u8, + pub(crate) va_byte_reserved: u8, + /// Screen content flags. + pub scc_fields: u16, + pub(crate) va_reserved: [u32; 15], +} + +impl Default for EncPictureParameterBufferHEVC { + fn default() -> Self { + EncPictureParameterBufferHEVC { + decoded_curr_pic: VAPictureHEVC::INVALID, + reference_frames: [VAPictureHEVC::INVALID; 15], + coded_buf: 0, + collocated_ref_pic_index: 0xff, + last_picture: 0, + pic_init_qp: 26, + diff_cu_qp_delta_depth: 0, + pps_cb_qp_offset: 0, + pps_cr_qp_offset: 0, + num_tile_columns_minus1: 0, + num_tile_rows_minus1: 0, + column_width_minus1: [0; 19], + row_height_minus1: [0; 21], + log2_parallel_merge_level_minus2: 0, + ctu_max_bitsize_allowed: 0, + num_ref_idx_l0_default_active_minus1: 0, + num_ref_idx_l1_default_active_minus1: 0, + slice_pic_parameter_set_id: 0, + nal_unit_type: 19, // IDR_W_RADL + pic_fields: HevcEncPicFields::default(), + hierarchical_level_plus1: 0, + va_byte_reserved: 0, + scc_fields: 0, + va_reserved: [0; 15], + } + } +} + +// SAFETY: `#[repr(C)]` transcription checked by the assertion block below. +unsafe impl VaParam for EncPictureParameterBufferHEVC { + const TYPE: i32 = VAEncPictureParameterBufferType; +} + +va_bits! { + /// `VAEncSliceParameterBufferHEVC::slice_fields`. + HevcEncSliceFields: u32 { + last_slice_of_pic_flag: 1, + dependent_slice_segment_flag: 1, + colour_plane_id: 2, + slice_temporal_mvp_enabled_flag: 1, + slice_sao_luma_flag: 1, + slice_sao_chroma_flag: 1, + num_ref_idx_active_override_flag: 1, + mvd_l1_zero_flag: 1, + cabac_init_flag: 1, + slice_deblocking_filter_disabled_flag: 2, + slice_loop_filter_across_slices_enabled_flag: 1, + collocated_from_l0_flag: 1, + } +} + +/// `VAEncSliceParameterBufferHEVC`, `va_enc_hevc.h:449`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct EncSliceParameterBufferHEVC { + /// `slice_segment_address`. + pub slice_segment_address: u32, + /// CTUs in this slice. + pub num_ctu_in_slice: u32, + /// `slice_type`. + pub slice_type: u8, + /// `slice_pic_parameter_set_id`. + pub slice_pic_parameter_set_id: u8, + /// `num_ref_idx_l0_active_minus1`. + pub num_ref_idx_l0_active_minus1: u8, + /// `num_ref_idx_l1_active_minus1`. + pub num_ref_idx_l1_active_minus1: u8, + /// `RefPicList0`. + pub ref_pic_list0: [VAPictureHEVC; 15], + /// `RefPicList1`. + pub ref_pic_list1: [VAPictureHEVC; 15], + /// `luma_log2_weight_denom`. + pub luma_log2_weight_denom: u8, + /// `delta_chroma_log2_weight_denom`. + pub delta_chroma_log2_weight_denom: i8, + /// `delta_luma_weight_l0`. + pub delta_luma_weight_l0: [i8; 15], + /// `luma_offset_l0`. + pub luma_offset_l0: [i8; 15], + /// `delta_chroma_weight_l0`. + pub delta_chroma_weight_l0: [[i8; 2]; 15], + /// `chroma_offset_l0`. + pub chroma_offset_l0: [[i8; 2]; 15], + /// `delta_luma_weight_l1`. + pub delta_luma_weight_l1: [i8; 15], + /// `luma_offset_l1`. + pub luma_offset_l1: [i8; 15], + /// `delta_chroma_weight_l1`. + pub delta_chroma_weight_l1: [[i8; 2]; 15], + /// `chroma_offset_l1`. + pub chroma_offset_l1: [[i8; 2]; 15], + /// `MaxNumMergeCand`. + pub max_num_merge_cand: u8, + /// `slice_qp_delta`. + pub slice_qp_delta: i8, + /// `slice_cb_qp_offset`. + pub slice_cb_qp_offset: i8, + /// `slice_cr_qp_offset`. + pub slice_cr_qp_offset: i8, + /// `slice_beta_offset_div2`. + pub slice_beta_offset_div2: i8, + /// `slice_tc_offset_div2`. + pub slice_tc_offset_div2: i8, + /// Slice flags. + pub slice_fields: HevcEncSliceFields, + /// Bit offset of `pred_weight_table()` inside the packed slice header. + pub pred_weight_table_bit_offset: u32, + /// Bit length of `pred_weight_table()`. + pub pred_weight_table_bit_length: u32, + pub(crate) va_reserved: [u32; 6], +} + +impl Default for EncSliceParameterBufferHEVC { + fn default() -> Self { + EncSliceParameterBufferHEVC { + slice_segment_address: 0, + num_ctu_in_slice: 0, + slice_type: 2, + slice_pic_parameter_set_id: 0, + num_ref_idx_l0_active_minus1: 0, + num_ref_idx_l1_active_minus1: 0, + ref_pic_list0: [VAPictureHEVC::INVALID; 15], + ref_pic_list1: [VAPictureHEVC::INVALID; 15], + luma_log2_weight_denom: 0, + delta_chroma_log2_weight_denom: 0, + delta_luma_weight_l0: [0; 15], + luma_offset_l0: [0; 15], + delta_chroma_weight_l0: [[0; 2]; 15], + chroma_offset_l0: [[0; 2]; 15], + delta_luma_weight_l1: [0; 15], + luma_offset_l1: [0; 15], + delta_chroma_weight_l1: [[0; 2]; 15], + chroma_offset_l1: [[0; 2]; 15], + max_num_merge_cand: 5, + slice_qp_delta: 0, + slice_cb_qp_offset: 0, + slice_cr_qp_offset: 0, + slice_beta_offset_div2: 0, + slice_tc_offset_div2: 0, + slice_fields: HevcEncSliceFields::default(), + pred_weight_table_bit_offset: 0, + pred_weight_table_bit_length: 0, + va_reserved: [0; 6], + } + } +} + +// SAFETY: `#[repr(C)]` transcription checked by the assertion block below. +unsafe impl VaParam for EncSliceParameterBufferHEVC { + const TYPE: i32 = VAEncSliceParameterBufferType; +} + +// --------------------------------------------------------------------------- +// AV1 encode +// --------------------------------------------------------------------------- + +va_bits! { + /// `VAEncSequenceParameterBufferAV1::seq_fields`. + Av1SeqFields: u32 { + still_picture: 1, + use_128x128_superblock: 1, + enable_filter_intra: 1, + enable_intra_edge_filter: 1, + enable_interintra_compound: 1, + enable_masked_compound: 1, + enable_warped_motion: 1, + enable_dual_filter: 1, + enable_order_hint: 1, + enable_jnt_comp: 1, + enable_ref_frame_mvs: 1, + enable_superres: 1, + enable_cdef: 1, + enable_restoration: 1, + bit_depth_minus8: 3, + subsampling_x: 1, + subsampling_y: 1, + mono_chrome: 1, + } +} + +/// `VAEncSequenceParameterBufferAV1`, `va_enc_av1.h:118`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct EncSequenceParameterBufferAV1 { + /// `seq_profile`. + pub seq_profile: u8, + /// `seq_level_idx`. + pub seq_level_idx: u8, + /// `seq_tier`. + pub seq_tier: u8, + /// Temporal layering flag. + pub hierarchical_flag: u8, + /// Frames between key frames. + pub intra_period: u32, + /// Distance between P frames. + pub ip_period: u32, + /// Target bitrate. + pub bits_per_second: u32, + /// Sequence flags. + pub seq_fields: Av1SeqFields, + /// `OrderHintBits - 1`. + pub order_hint_bits_minus_1: u8, + pub(crate) va_reserved: [u32; 16], +} + +impl Default for EncSequenceParameterBufferAV1 { + fn default() -> Self { + EncSequenceParameterBufferAV1 { + seq_profile: 0, + seq_level_idx: 0, + seq_tier: 0, + hierarchical_flag: 0, + intra_period: 0, + ip_period: 1, + bits_per_second: 0, + seq_fields: Av1SeqFields::default(), + order_hint_bits_minus_1: 0, + va_reserved: [0; 16], + } + } +} + +// SAFETY: `#[repr(C)]` transcription checked by the assertion block below. +unsafe impl VaParam for EncSequenceParameterBufferAV1 { + const TYPE: i32 = VAEncSequenceParameterBufferType; +} + +va_bits! { + /// `VAEncSegParamAV1::seg_flags`. + Av1SegFlags: u8 { + segmentation_enabled: 1, + segmentation_update_map: 1, + segmentation_temporal_update: 1, + } +} + +/// `VAEncSegParamAV1`, `va_enc_av1.h:216`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub struct EncSegParamAV1 { + /// Segmentation flags. + pub seg_flags: Av1SegFlags, + /// Number of segments in use. + pub segment_number: u8, + /// `FeatureData`. + pub feature_data: [[i16; 8]; 8], + /// `FeatureEnabled` bitmask per segment. + pub feature_mask: [u8; 8], + pub(crate) va_reserved: [u32; 4], +} + +/// `VAEncWarpedMotionParamsAV1`, `va_enc_av1.h:262`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub struct EncWarpedMotionParamsAV1 { + /// Transformation type. + pub wmtype: i32, + /// Model parameters. + pub wmmat: [i32; 8], + /// Set when the model was rejected. + pub invalid: u8, + pub(crate) va_reserved: [u32; 4], +} + +va_bits! { + /// `VAEncPictureParameterBufferAV1::picture_flags`. + Av1EncPicFlags: u32 { + frame_type: 2, + error_resilient_mode: 1, + disable_cdf_update: 1, + use_superres: 1, + allow_high_precision_mv: 1, + use_ref_frame_mvs: 1, + disable_frame_end_update_cdf: 1, + reduced_tx_set: 1, + enable_frame_obu: 1, + long_term_reference: 1, + disable_frame_recon: 1, + allow_intrabc: 1, + palette_mode_enable: 1, + allow_screen_content_tools: 1, + force_integer_mv: 1, + } +} + +va_bits! { + /// `VAEncPictureParameterBufferAV1::mode_control_flags`. + Av1ModeControlFlags: u32 { + delta_q_present: 1, + delta_q_res: 2, + delta_lf_present: 1, + delta_lf_res: 2, + delta_lf_multi: 1, + tx_mode: 2, + reference_mode: 2, + skip_mode_present: 1, + } +} + +va_bits! { + /// `VAEncPictureParameterBufferAV1::tile_group_obu_hdr_info`. + Av1TileGroupObuHdrInfo: u8 { + obu_extension_flag: 1, + obu_has_size_field: 1, + temporal_id: 3, + spatial_id: 2, + } +} + +/// `VAEncPictureParameterBufferAV1`, `va_enc_av1.h:322`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct EncPictureParameterBufferAV1 { + /// `frame_width_minus_1`. + pub frame_width_minus_1: u16, + /// `frame_height_minus_1`. + pub frame_height_minus_1: u16, + /// Surface the reconstruction is written to. + pub reconstructed_frame: VASurfaceID, + /// Buffer the coded bits are written to. + pub coded_buf: u32, + /// The eight reference slots. + pub reference_frames: [VASurfaceID; 8], + /// `ref_frame_idx`. + pub ref_frame_idx: [u8; 7], + /// Temporal layer + 1. + pub hierarchical_level_plus1: u8, + /// `primary_ref_frame`. + pub primary_ref_frame: u8, + /// `order_hint`. + pub order_hint: u8, + /// `refresh_frame_flags`. + pub refresh_frame_flags: u8, + pub(crate) reserved8bits1: u8, + /// Reference control for list 0. + pub ref_frame_ctrl_l0: u32, + /// Reference control for list 1. + pub ref_frame_ctrl_l1: u32, + /// Picture flags. + pub picture_flags: Av1EncPicFlags, + /// Segment id block size. + pub seg_id_block_size: u8, + /// `num_tile_groups_minus1`. + pub num_tile_groups_minus1: u8, + /// Temporal id. + pub temporal_id: u8, + /// `loop_filter_level[0..2]`. + pub filter_level: [u8; 2], + /// `loop_filter_level[2]`. + pub filter_level_u: u8, + /// `loop_filter_level[3]`. + pub filter_level_v: u8, + /// Loop filter flags. + pub loop_filter_flags: u8, + /// `SuperresDenom`. + pub superres_scale_denominator: u8, + /// `interpolation_filter`. + pub interpolation_filter: u8, + /// `loop_filter_ref_deltas`. + pub ref_deltas: [i8; 8], + /// `loop_filter_mode_deltas`. + pub mode_deltas: [i8; 2], + /// `base_q_idx`. + pub base_qindex: u8, + /// `DeltaQYDc`. + pub y_dc_delta_q: i8, + /// `DeltaQUDc`. + pub u_dc_delta_q: i8, + /// `DeltaQUAc`. + pub u_ac_delta_q: i8, + /// `DeltaQVDc`. + pub v_dc_delta_q: i8, + /// `DeltaQVAc`. + pub v_ac_delta_q: i8, + /// Lower bound the rate controller may pick. + pub min_base_qindex: u8, + /// Upper bound the rate controller may pick. + pub max_base_qindex: u8, + /// Quantiser matrix flags. + pub qmatrix_flags: u16, + pub(crate) reserved16bits1: u16, + /// Mode control flags. + pub mode_control_flags: Av1ModeControlFlags, + /// Segmentation parameters. + pub segments: EncSegParamAV1, + /// `TileCols`. + pub tile_cols: u8, + /// `TileRows`. + pub tile_rows: u8, + pub(crate) reserved16bits2: u16, + /// Per-column widths in superblocks, minus one. + pub width_in_sbs_minus_1: [u16; 63], + /// Per-row heights in superblocks, minus one. + pub height_in_sbs_minus_1: [u16; 63], + /// `context_update_tile_id`. + pub context_update_tile_id: u16, + /// `CdefDamping - 3`. + pub cdef_damping_minus_3: u8, + /// `cdef_bits`. + pub cdef_bits: u8, + /// Combined luma strengths. + pub cdef_y_strengths: [u8; 8], + /// Combined chroma strengths. + pub cdef_uv_strengths: [u8; 8], + /// Loop restoration flags. + pub loop_restoration_flags: u16, + /// Global motion. + pub wm: [EncWarpedMotionParamsAV1; 7], + /// Bit offset of `base_q_idx` in the packed frame header. + pub bit_offset_qindex: u32, + /// Bit offset of `segmentation_params()`. + pub bit_offset_segmentation: u32, + /// Bit offset of `loop_filter_params()`. + pub bit_offset_loopfilter_params: u32, + /// Bit offset of `cdef_params()`. + pub bit_offset_cdef_params: u32, + /// Bit length of `cdef_params()`. + pub size_in_bits_cdef_params: u32, + /// Byte offset of the frame OBU's size field. + pub byte_offset_frame_hdr_obu_size: u32, + /// Bit length of the frame header OBU. + pub size_in_bits_frame_hdr_obu: u32, + /// Tile group OBU header flags. + pub tile_group_obu_hdr_info: Av1TileGroupObuHdrInfo, + /// Number of skipped frames represented by this one. + pub number_skip_frames: u8, + pub(crate) reserved16bits3: u16, + /// Size reduction for skipped frames. + pub skip_frames_reduced_size: i32, + pub(crate) va_reserved: [u32; 16], +} + +impl Default for EncPictureParameterBufferAV1 { + fn default() -> Self { + EncPictureParameterBufferAV1 { + frame_width_minus_1: 0, + frame_height_minus_1: 0, + reconstructed_frame: super::INVALID_SURFACE, + coded_buf: 0, + reference_frames: [super::INVALID_SURFACE; 8], + ref_frame_idx: [0; 7], + hierarchical_level_plus1: 0, + primary_ref_frame: 7, // PRIMARY_REF_NONE + order_hint: 0, + refresh_frame_flags: 0xff, + reserved8bits1: 0, + ref_frame_ctrl_l0: 0, + ref_frame_ctrl_l1: 0, + picture_flags: Av1EncPicFlags::default(), + seg_id_block_size: 0, + num_tile_groups_minus1: 0, + temporal_id: 0, + filter_level: [0; 2], + filter_level_u: 0, + filter_level_v: 0, + loop_filter_flags: 0, + superres_scale_denominator: 8, + interpolation_filter: 0, + ref_deltas: [0; 8], + mode_deltas: [0; 2], + base_qindex: 128, + y_dc_delta_q: 0, + u_dc_delta_q: 0, + u_ac_delta_q: 0, + v_dc_delta_q: 0, + v_ac_delta_q: 0, + min_base_qindex: 0, + max_base_qindex: 255, + qmatrix_flags: 0, + reserved16bits1: 0, + mode_control_flags: Av1ModeControlFlags::default(), + segments: EncSegParamAV1::default(), + tile_cols: 1, + tile_rows: 1, + reserved16bits2: 0, + width_in_sbs_minus_1: [0; 63], + height_in_sbs_minus_1: [0; 63], + context_update_tile_id: 0, + cdef_damping_minus_3: 0, + cdef_bits: 0, + cdef_y_strengths: [0; 8], + cdef_uv_strengths: [0; 8], + loop_restoration_flags: 0, + wm: [EncWarpedMotionParamsAV1::default(); 7], + bit_offset_qindex: 0, + bit_offset_segmentation: 0, + bit_offset_loopfilter_params: 0, + bit_offset_cdef_params: 0, + size_in_bits_cdef_params: 0, + byte_offset_frame_hdr_obu_size: 0, + size_in_bits_frame_hdr_obu: 0, + tile_group_obu_hdr_info: Av1TileGroupObuHdrInfo::default(), + number_skip_frames: 0, + reserved16bits3: 0, + skip_frames_reduced_size: 0, + va_reserved: [0; 16], + } + } +} + +// SAFETY: `#[repr(C)]` transcription checked by the assertion block below. +unsafe impl VaParam for EncPictureParameterBufferAV1 { + const TYPE: i32 = VAEncPictureParameterBufferType; +} + +/// `VAEncTileGroupBufferAV1`, `va_enc_av1.h:590`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub struct EncTileGroupBufferAV1 { + /// First tile in the group. + pub tg_start: u8, + /// Last tile in the group. + pub tg_end: u8, + pub(crate) va_reserved: [u32; 4], +} + +// SAFETY: `#[repr(C)]` transcription checked by the assertion block below. +unsafe impl VaParam for EncTileGroupBufferAV1 { + const TYPE: i32 = VAEncSliceParameterBufferType; +} + +// --------------------------------------------------------------------------- +// ABI transcription check — `crates/ec-hw/abi-probe.c`, libva 1.23.0, x86_64: +// +// VAEncPackedHeaderParameterBuffer size=28 align=4 bit_length=4 +// has_emulation_bytes=8 +// VAEncMiscParameterRateControl size=60 (15 u32 payload words) +// VAEncMiscParameterFrameRate size=24 (6 u32) +// VAEncMiscParameterHRD size=24 (6 u32) +// VAEncSequenceParameterBufferH264 size=1132 align=4 intra_period=4 +// picture_width_in_mbs=24 +// seq_fields=28 +// bit_depth_luma_minus8=32 +// offset_for_non_ref_pic=36 +// offset_for_ref_frame=44 +// frame_cropping_flag=1068 +// frame_crop_left_offset=1072 +// vui_parameters_present_flag=1088 +// vui_fields=1092 +// aspect_ratio_idc=1096 +// num_units_in_tick=1108 +// time_scale=1112 +// VAEncPictureParameterBufferH264 size=648 align=4 ReferenceFrames=36 +// coded_buf=612 +// pic_parameter_set_id=616 +// frame_num=620 pic_init_qp=622 +// pic_fields=628 +// VAEncSliceParameterBufferH264 size=3140 align=4 macroblock_info=8 +// slice_type=12 idr_pic_id=14 +// delta_pic_order_cnt_bottom=20 +// direct_spatial_mv_pred_flag=32 +// RefPicList0=36 RefPicList1=1188 +// luma_log2_weight_denom=2340 +// cabac_init_idc=3118 +// VAEncSequenceParameterBufferHEVC size=116 align=4 intra_period=4 +// pic_width_in_luma_samples=20 +// seq_fields=24 +// log2_min_luma_coding_block_size_minus3=28 +// pcm_sample_bit_depth_luma_minus1=36 +// vui_parameters_present_flag=52 +// vui_fields=56 aspect_ratio_idc=60 +// vui_num_units_in_tick=72 +// min_spatial_segmentation_idc=80 +// scc_fields=84 +// VAEncPictureParameterBufferHEVC size=576 align=4 reference_frames=28 +// coded_buf=448 +// collocated_ref_pic_index=452 +// column_width_minus1=460 +// row_height_minus1=479 +// log2_parallel_merge_level_minus2=500 +// nal_unit_type=505 pic_fields=508 +// hierarchical_level_plus1=512 +// scc_fields=514 +// VAEncSliceParameterBufferHEVC size=1076 align=4 num_ctu_in_slice=4 +// slice_type=8 ref_pic_list0=12 +// ref_pic_list1=432 +// luma_log2_weight_denom=852 +// max_num_merge_cand=1034 +// slice_fields=1040 +// pred_weight_table_bit_offset=1044 +// VAEncSequenceParameterBufferAV1 size=88 align=4 intra_period=4 seq_fields=16 +// order_hint_bits_minus_1=20 +// VAEncSegParamAV1 size=156 align=4 feature_data=2 +// feature_mask=130 +// VAEncWarpedMotionParamsAV1 size=56 align=4 +// VAEncPictureParameterBufferAV1 size=1032 align=4 reconstructed_frame=4 +// coded_buf=8 +// reference_frames=12 +// ref_frame_idx=44 +// ref_frame_ctrl_l0=56 +// picture_flags=64 +// seg_id_block_size=68 +// filter_level=71 +// loop_filter_flags=75 +// ref_deltas=78 base_qindex=88 +// min_base_qindex=94 +// qmatrix_flags=96 +// mode_control_flags=100 +// segments=104 tile_cols=260 +// width_in_sbs_minus_1=264 +// context_update_tile_id=516 +// cdef_damping_minus_3=518 +// loop_restoration_flags=536 +// wm=540 bit_offset_qindex=932 +// tile_group_obu_hdr_info=960 +// number_skip_frames=961 +// skip_frames_reduced_size=964 +// VAEncTileGroupBufferAV1 size=20 align=4 +const _: () = { + use std::mem::{align_of, offset_of, size_of}; + + assert!( + size_of::() == 28 + && align_of::() == 4 + ); + assert!(offset_of!(PackedHeaderParameterBuffer, bit_length) == 4); + assert!(offset_of!(PackedHeaderParameterBuffer, has_emulation_bytes) == 8); + + // Misc payloads are submitted as `{ type, words... }`; the word counts are + // the header sizes minus the 4-byte type each buffer carries. + assert!(size_of::() * (1 + 15) == 64); + assert!(size_of::() * (1 + 6) == 28); + + assert!( + size_of::() == 1132 + && align_of::() == 4 + ); + assert!(offset_of!(EncSequenceParameterBufferH264, intra_period) == 4); + assert!(offset_of!(EncSequenceParameterBufferH264, picture_width_in_mbs) == 24); + assert!(offset_of!(EncSequenceParameterBufferH264, seq_fields) == 28); + assert!(offset_of!(EncSequenceParameterBufferH264, bit_depth_luma_minus8) == 32); + assert!(offset_of!(EncSequenceParameterBufferH264, offset_for_non_ref_pic) == 36); + assert!(offset_of!(EncSequenceParameterBufferH264, offset_for_ref_frame) == 44); + assert!(offset_of!(EncSequenceParameterBufferH264, frame_cropping_flag) == 1068); + assert!(offset_of!(EncSequenceParameterBufferH264, frame_crop_left_offset) == 1072); + assert!(offset_of!(EncSequenceParameterBufferH264, vui_parameters_present_flag) == 1088); + assert!(offset_of!(EncSequenceParameterBufferH264, vui_fields) == 1092); + assert!(offset_of!(EncSequenceParameterBufferH264, aspect_ratio_idc) == 1096); + assert!(offset_of!(EncSequenceParameterBufferH264, num_units_in_tick) == 1108); + assert!(offset_of!(EncSequenceParameterBufferH264, time_scale) == 1112); + + assert!( + size_of::() == 648 + && align_of::() == 4 + ); + assert!(offset_of!(EncPictureParameterBufferH264, reference_frames) == 36); + assert!(offset_of!(EncPictureParameterBufferH264, coded_buf) == 612); + assert!(offset_of!(EncPictureParameterBufferH264, pic_parameter_set_id) == 616); + assert!(offset_of!(EncPictureParameterBufferH264, frame_num) == 620); + assert!(offset_of!(EncPictureParameterBufferH264, pic_init_qp) == 622); + assert!(offset_of!(EncPictureParameterBufferH264, pic_fields) == 628); + + assert!( + size_of::() == 3140 + && align_of::() == 4 + ); + assert!(offset_of!(EncSliceParameterBufferH264, macroblock_info) == 8); + assert!(offset_of!(EncSliceParameterBufferH264, slice_type) == 12); + assert!(offset_of!(EncSliceParameterBufferH264, idr_pic_id) == 14); + assert!(offset_of!(EncSliceParameterBufferH264, delta_pic_order_cnt_bottom) == 20); + assert!(offset_of!(EncSliceParameterBufferH264, direct_spatial_mv_pred_flag) == 32); + assert!(offset_of!(EncSliceParameterBufferH264, ref_pic_list0) == 36); + assert!(offset_of!(EncSliceParameterBufferH264, ref_pic_list1) == 1188); + assert!(offset_of!(EncSliceParameterBufferH264, luma_log2_weight_denom) == 2340); + assert!(offset_of!(EncSliceParameterBufferH264, cabac_init_idc) == 3118); + + assert!( + size_of::() == 116 + && align_of::() == 4 + ); + assert!(offset_of!(EncSequenceParameterBufferHEVC, intra_period) == 4); + assert!(offset_of!(EncSequenceParameterBufferHEVC, pic_width_in_luma_samples) == 20); + assert!(offset_of!(EncSequenceParameterBufferHEVC, seq_fields) == 24); + assert!( + offset_of!( + EncSequenceParameterBufferHEVC, + log2_min_luma_coding_block_size_minus3 + ) == 28 + ); + assert!( + offset_of!( + EncSequenceParameterBufferHEVC, + pcm_sample_bit_depth_luma_minus1 + ) == 36 + ); + assert!(offset_of!(EncSequenceParameterBufferHEVC, vui_parameters_present_flag) == 52); + assert!(offset_of!(EncSequenceParameterBufferHEVC, vui_fields) == 56); + assert!(offset_of!(EncSequenceParameterBufferHEVC, aspect_ratio_idc) == 60); + assert!(offset_of!(EncSequenceParameterBufferHEVC, vui_num_units_in_tick) == 72); + assert!(offset_of!(EncSequenceParameterBufferHEVC, min_spatial_segmentation_idc) == 80); + assert!(offset_of!(EncSequenceParameterBufferHEVC, scc_fields) == 84); + + assert!( + size_of::() == 576 + && align_of::() == 4 + ); + assert!(offset_of!(EncPictureParameterBufferHEVC, reference_frames) == 28); + assert!(offset_of!(EncPictureParameterBufferHEVC, coded_buf) == 448); + assert!(offset_of!(EncPictureParameterBufferHEVC, collocated_ref_pic_index) == 452); + assert!(offset_of!(EncPictureParameterBufferHEVC, column_width_minus1) == 460); + assert!(offset_of!(EncPictureParameterBufferHEVC, row_height_minus1) == 479); + assert!( + offset_of!( + EncPictureParameterBufferHEVC, + log2_parallel_merge_level_minus2 + ) == 500 + ); + assert!(offset_of!(EncPictureParameterBufferHEVC, nal_unit_type) == 505); + assert!(offset_of!(EncPictureParameterBufferHEVC, pic_fields) == 508); + assert!(offset_of!(EncPictureParameterBufferHEVC, hierarchical_level_plus1) == 512); + assert!(offset_of!(EncPictureParameterBufferHEVC, scc_fields) == 514); + + assert!( + size_of::() == 1076 + && align_of::() == 4 + ); + assert!(offset_of!(EncSliceParameterBufferHEVC, num_ctu_in_slice) == 4); + assert!(offset_of!(EncSliceParameterBufferHEVC, slice_type) == 8); + assert!(offset_of!(EncSliceParameterBufferHEVC, ref_pic_list0) == 12); + assert!(offset_of!(EncSliceParameterBufferHEVC, ref_pic_list1) == 432); + assert!(offset_of!(EncSliceParameterBufferHEVC, luma_log2_weight_denom) == 852); + assert!(offset_of!(EncSliceParameterBufferHEVC, max_num_merge_cand) == 1034); + assert!(offset_of!(EncSliceParameterBufferHEVC, slice_fields) == 1040); + assert!(offset_of!(EncSliceParameterBufferHEVC, pred_weight_table_bit_offset) == 1044); + + assert!( + size_of::() == 88 + && align_of::() == 4 + ); + assert!(offset_of!(EncSequenceParameterBufferAV1, intra_period) == 4); + assert!(offset_of!(EncSequenceParameterBufferAV1, seq_fields) == 16); + assert!(offset_of!(EncSequenceParameterBufferAV1, order_hint_bits_minus_1) == 20); + + assert!(size_of::() == 156 && align_of::() == 4); + assert!(offset_of!(EncSegParamAV1, feature_data) == 2); + assert!(offset_of!(EncSegParamAV1, feature_mask) == 130); + + assert!(size_of::() == 56); + + assert!( + size_of::() == 1032 + && align_of::() == 4 + ); + assert!(offset_of!(EncPictureParameterBufferAV1, reconstructed_frame) == 4); + assert!(offset_of!(EncPictureParameterBufferAV1, coded_buf) == 8); + assert!(offset_of!(EncPictureParameterBufferAV1, reference_frames) == 12); + assert!(offset_of!(EncPictureParameterBufferAV1, ref_frame_idx) == 44); + assert!(offset_of!(EncPictureParameterBufferAV1, ref_frame_ctrl_l0) == 56); + assert!(offset_of!(EncPictureParameterBufferAV1, picture_flags) == 64); + assert!(offset_of!(EncPictureParameterBufferAV1, seg_id_block_size) == 68); + assert!(offset_of!(EncPictureParameterBufferAV1, filter_level) == 71); + assert!(offset_of!(EncPictureParameterBufferAV1, loop_filter_flags) == 75); + assert!(offset_of!(EncPictureParameterBufferAV1, ref_deltas) == 78); + assert!(offset_of!(EncPictureParameterBufferAV1, base_qindex) == 88); + assert!(offset_of!(EncPictureParameterBufferAV1, min_base_qindex) == 94); + assert!(offset_of!(EncPictureParameterBufferAV1, qmatrix_flags) == 96); + assert!(offset_of!(EncPictureParameterBufferAV1, mode_control_flags) == 100); + assert!(offset_of!(EncPictureParameterBufferAV1, segments) == 104); + assert!(offset_of!(EncPictureParameterBufferAV1, tile_cols) == 260); + assert!(offset_of!(EncPictureParameterBufferAV1, width_in_sbs_minus_1) == 264); + assert!(offset_of!(EncPictureParameterBufferAV1, context_update_tile_id) == 516); + assert!(offset_of!(EncPictureParameterBufferAV1, cdef_damping_minus_3) == 518); + assert!(offset_of!(EncPictureParameterBufferAV1, loop_restoration_flags) == 536); + assert!(offset_of!(EncPictureParameterBufferAV1, wm) == 540); + assert!(offset_of!(EncPictureParameterBufferAV1, bit_offset_qindex) == 932); + assert!(offset_of!(EncPictureParameterBufferAV1, tile_group_obu_hdr_info) == 960); + assert!(offset_of!(EncPictureParameterBufferAV1, number_skip_frames) == 961); + assert!(offset_of!(EncPictureParameterBufferAV1, skip_frames_reduced_size) == 964); + + assert!(size_of::() == 20); +}; diff --git a/crates/ec-hw/src/params/h264.rs b/crates/ec-hw/src/params/h264.rs new file mode 100644 index 00000000..494b89a2 --- /dev/null +++ b/crates/ec-hw/src/params/h264.rs @@ -0,0 +1,376 @@ +//! H.264 decode parameter buffers (`va.h:3572-3716`). + +use ec_va::sys::{ + VAIQMatrixBufferType, VAPictureParameterBufferType, VASliceParameterBufferType, VASurfaceID, +}; + +use super::{INVALID_SURFACE, VaParam}; +use crate::va_bits; + +/// `VA_PICTURE_H264_INVALID` (`va.h:3583`). +pub const PICTURE_INVALID: u32 = 0x0000_0001; +/// `VA_PICTURE_H264_TOP_FIELD`. +pub const PICTURE_TOP_FIELD: u32 = 0x0000_0002; +/// `VA_PICTURE_H264_BOTTOM_FIELD`. +pub const PICTURE_BOTTOM_FIELD: u32 = 0x0000_0004; +/// `VA_PICTURE_H264_SHORT_TERM_REFERENCE`. +pub const PICTURE_SHORT_TERM_REFERENCE: u32 = 0x0000_0008; +/// `VA_PICTURE_H264_LONG_TERM_REFERENCE`. +pub const PICTURE_LONG_TERM_REFERENCE: u32 = 0x0000_0010; + +/// `VAPictureH264`, `va.h:3572`. +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct VAPictureH264 { + /// Surface holding the picture, or [`INVALID_SURFACE`]. + pub picture_id: VASurfaceID, + /// `FrameNum` (short term) or `LongTermFrameIdx` (long term). + pub frame_idx: u32, + /// `VA_PICTURE_H264_*` bitmask. + pub flags: u32, + /// `TopFieldOrderCnt`. + pub top_field_order_cnt: i32, + /// `BottomFieldOrderCnt`. + pub bottom_field_order_cnt: i32, + pub(crate) va_reserved: [u32; 4], +} + +impl VAPictureH264 { + /// The "no picture here" entry every unused list slot must carry. + /// + /// Not `Default::default()` by accident: a zeroed entry names surface 0, + /// which is a real surface id, and drivers have been known to read it. + pub const INVALID: VAPictureH264 = VAPictureH264 { + picture_id: INVALID_SURFACE, + frame_idx: 0, + flags: PICTURE_INVALID, + top_field_order_cnt: 0, + bottom_field_order_cnt: 0, + va_reserved: [0; 4], + }; + + /// A frame picture with both field order counts set to its POC. + pub fn frame(picture_id: VASurfaceID, frame_idx: u32, poc: i32, flags: u32) -> VAPictureH264 { + VAPictureH264 { + picture_id, + frame_idx, + flags, + top_field_order_cnt: poc, + bottom_field_order_cnt: poc, + va_reserved: [0; 4], + } + } +} + +impl Default for VAPictureH264 { + fn default() -> Self { + VAPictureH264::INVALID + } +} + +va_bits! { + /// `VAPictureParameterBufferH264::seq_fields`. + SeqFields: u32 { + chroma_format_idc: 2, + residual_colour_transform_flag: 1, + gaps_in_frame_num_value_allowed_flag: 1, + frame_mbs_only_flag: 1, + mb_adaptive_frame_field_flag: 1, + direct_8x8_inference_flag: 1, + min_luma_bipred_size8x8: 1, + log2_max_frame_num_minus4: 4, + pic_order_cnt_type: 2, + log2_max_pic_order_cnt_lsb_minus4: 4, + delta_pic_order_always_zero_flag: 1, + } +} + +va_bits! { + /// `VAPictureParameterBufferH264::pic_fields`. + PicFields: u32 { + entropy_coding_mode_flag: 1, + weighted_pred_flag: 1, + weighted_bipred_idc: 2, + transform_8x8_mode_flag: 1, + field_pic_flag: 1, + constrained_intra_pred_flag: 1, + pic_order_present_flag: 1, + deblocking_filter_control_present_flag: 1, + redundant_pic_cnt_present_flag: 1, + reference_pic_flag: 1, + } +} + +/// `VAPictureParameterBufferH264`, `va.h:3594`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct PictureParameterBufferH264 { + /// The picture being decoded. + pub curr_pic: VAPictureH264, + /// Every picture in the DPB; unused slots are [`VAPictureH264::INVALID`]. + pub reference_frames: [VAPictureH264; 16], + /// `PicWidthInMbs - 1`. + pub picture_width_in_mbs_minus1: u16, + /// `PicHeightInMapUnits - 1` for a frame-only stream. + pub picture_height_in_mbs_minus1: u16, + /// `bit_depth_luma_minus8`. + pub bit_depth_luma_minus8: u8, + /// `bit_depth_chroma_minus8`. + pub bit_depth_chroma_minus8: u8, + /// `max_num_ref_frames`. + pub num_ref_frames: u8, + /// Sequence flags. + pub seq_fields: SeqFields, + /// Deprecated FMO fields; libva ignores them, we write zero. + pub(crate) num_slice_groups_minus1: u8, + pub(crate) slice_group_map_type: u8, + pub(crate) slice_group_change_rate_minus1: u16, + /// `pic_init_qp_minus26`. + pub pic_init_qp_minus26: i8, + /// `pic_init_qs_minus26`. + pub pic_init_qs_minus26: i8, + /// `chroma_qp_index_offset`. + pub chroma_qp_index_offset: i8, + /// `second_chroma_qp_index_offset`. + pub second_chroma_qp_index_offset: i8, + /// Picture flags. + pub pic_fields: PicFields, + /// `frame_num` of the current picture. + pub frame_num: u16, + pub(crate) va_reserved: [u32; 8], +} + +impl Default for PictureParameterBufferH264 { + fn default() -> Self { + PictureParameterBufferH264 { + curr_pic: VAPictureH264::INVALID, + reference_frames: [VAPictureH264::INVALID; 16], + picture_width_in_mbs_minus1: 0, + picture_height_in_mbs_minus1: 0, + bit_depth_luma_minus8: 0, + bit_depth_chroma_minus8: 0, + num_ref_frames: 0, + seq_fields: SeqFields::default(), + num_slice_groups_minus1: 0, + slice_group_map_type: 0, + slice_group_change_rate_minus1: 0, + pic_init_qp_minus26: 0, + pic_init_qs_minus26: 0, + chroma_qp_index_offset: 0, + second_chroma_qp_index_offset: 0, + pic_fields: PicFields::default(), + frame_num: 0, + va_reserved: [0; 8], + } + } +} + +// SAFETY: `#[repr(C)]` transcription of `VAPictureParameterBufferH264`, checked +// field for field by the assertion block below; every field is an integer or an +// array of integers, so any bit pattern is valid. +unsafe impl VaParam for PictureParameterBufferH264 { + const TYPE: i32 = VAPictureParameterBufferType; +} + +/// `VAIQMatrixBufferH264`, `va.h:3648`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct IQMatrixBufferH264 { + /// 4x4 scaling lists in raster scan order. + pub scaling_list_4x4: [[u8; 16]; 6], + /// 8x8 scaling lists in raster scan order. + pub scaling_list_8x8: [[u8; 64]; 2], + pub(crate) va_reserved: [u32; 4], +} + +impl Default for IQMatrixBufferH264 { + fn default() -> Self { + IQMatrixBufferH264 { + scaling_list_4x4: [[16; 16]; 6], + scaling_list_8x8: [[16; 64]; 2], + va_reserved: [0; 4], + } + } +} + +// SAFETY: as `PictureParameterBufferH264`; plain `u8` arrays plus padding. +unsafe impl VaParam for IQMatrixBufferH264 { + const TYPE: i32 = VAIQMatrixBufferType; +} + +/// `VASliceParameterBufferH264`, `va.h:3659`. +/// +/// The weight tables are the bulk of it: 3 KB per slice, which is why the +/// decoder builds one on the stack and hands it straight to `vaCreateBuffer` +/// rather than keeping a queue of them. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct SliceParameterBufferH264 { + /// Bytes of slice data for this slice. + pub slice_data_size: u32, + /// Offset of this slice's NAL unit within the data buffer. + pub slice_data_offset: u32, + /// `VA_SLICE_DATA_FLAG_*`. + pub slice_data_flag: u32, + /// Bits from the start of the NAL unit byte to `slice_data()`, counted in + /// the *unescaped* RBSP. + pub slice_data_bit_offset: u16, + /// `first_mb_in_slice`. + pub first_mb_in_slice: u16, + /// `slice_type` (0..=4, i.e. the modulo-5 value). + pub slice_type: u8, + /// `direct_spatial_mv_pred_flag`. + pub direct_spatial_mv_pred_flag: u8, + /// `num_ref_idx_l0_active_minus1`, override applied. + pub num_ref_idx_l0_active_minus1: u8, + /// `num_ref_idx_l1_active_minus1`, override applied. + pub num_ref_idx_l1_active_minus1: u8, + /// `cabac_init_idc`. + pub cabac_init_idc: u8, + /// `slice_qp_delta`. + pub slice_qp_delta: i8, + /// `disable_deblocking_filter_idc`. + pub disable_deblocking_filter_idc: u8, + /// `slice_alpha_c0_offset_div2`. + pub slice_alpha_c0_offset_div2: i8, + /// `slice_beta_offset_div2`. + pub slice_beta_offset_div2: i8, + /// `RefPicList0` after initialisation and modification (8.2.4). + pub ref_pic_list0: [VAPictureH264; 32], + /// `RefPicList1`. + pub ref_pic_list1: [VAPictureH264; 32], + /// `luma_log2_weight_denom`. + pub luma_log2_weight_denom: u8, + /// `chroma_log2_weight_denom`. + pub chroma_log2_weight_denom: u8, + /// Whether any `luma_weight_l0_flag` was set. + pub luma_weight_l0_flag: u8, + /// `luma_weight_l0`. + pub luma_weight_l0: [i16; 32], + /// `luma_offset_l0`. + pub luma_offset_l0: [i16; 32], + /// Whether any `chroma_weight_l0_flag` was set. + pub chroma_weight_l0_flag: u8, + /// `chroma_weight_l0`. + pub chroma_weight_l0: [[i16; 2]; 32], + /// `chroma_offset_l0`. + pub chroma_offset_l0: [[i16; 2]; 32], + /// Whether any `luma_weight_l1_flag` was set. + pub luma_weight_l1_flag: u8, + /// `luma_weight_l1`. + pub luma_weight_l1: [i16; 32], + /// `luma_offset_l1`. + pub luma_offset_l1: [i16; 32], + /// Whether any `chroma_weight_l1_flag` was set. + pub chroma_weight_l1_flag: u8, + /// `chroma_weight_l1`. + pub chroma_weight_l1: [[i16; 2]; 32], + /// `chroma_offset_l1`. + pub chroma_offset_l1: [[i16; 2]; 32], + pub(crate) va_reserved: [u32; 4], +} + +impl Default for SliceParameterBufferH264 { + fn default() -> Self { + SliceParameterBufferH264 { + slice_data_size: 0, + slice_data_offset: 0, + slice_data_flag: 0, + slice_data_bit_offset: 0, + first_mb_in_slice: 0, + slice_type: 0, + direct_spatial_mv_pred_flag: 0, + num_ref_idx_l0_active_minus1: 0, + num_ref_idx_l1_active_minus1: 0, + cabac_init_idc: 0, + slice_qp_delta: 0, + disable_deblocking_filter_idc: 0, + slice_alpha_c0_offset_div2: 0, + slice_beta_offset_div2: 0, + ref_pic_list0: [VAPictureH264::INVALID; 32], + ref_pic_list1: [VAPictureH264::INVALID; 32], + luma_log2_weight_denom: 0, + chroma_log2_weight_denom: 0, + luma_weight_l0_flag: 0, + luma_weight_l0: [0; 32], + luma_offset_l0: [0; 32], + chroma_weight_l0_flag: 0, + chroma_weight_l0: [[0; 2]; 32], + chroma_offset_l0: [[0; 2]; 32], + luma_weight_l1_flag: 0, + luma_weight_l1: [0; 32], + luma_offset_l1: [0; 32], + chroma_weight_l1_flag: 0, + chroma_weight_l1: [[0; 2]; 32], + chroma_offset_l1: [[0; 2]; 32], + va_reserved: [0; 4], + } + } +} + +// SAFETY: as `PictureParameterBufferH264`. +unsafe impl VaParam for SliceParameterBufferH264 { + const TYPE: i32 = VASliceParameterBufferType; +} + +// --------------------------------------------------------------------------- +// ABI transcription check — `crates/ec-hw/abi-probe.c`, libva 1.23.0, x86_64: +// +// VAPictureH264 size=36 align=4 frame_idx=4 flags=8 +// TopFieldOrderCnt=12 +// BottomFieldOrderCnt=16 +// VAPictureParameterBufferH264 size=672 align=4 ReferenceFrames=36 +// picture_width_in_mbs_minus1=612 +// bit_depth_luma_minus8=616 +// num_ref_frames=618 seq_fields=620 +// pic_init_qp_minus26=628 +// pic_fields=632 frame_num=636 +// VAIQMatrixBufferH264 size=240 align=4 ScalingList8x8=96 +// VASliceParameterBufferH264 size=3128 align=4 slice_data_bit_offset=12 +// slice_type=16 cabac_init_idc=20 +// RefPicList0=28 RefPicList1=1180 +// luma_log2_weight_denom=2332 +// luma_weight_l0=2336 +// chroma_weight_l0=2466 +// luma_weight_l1_flag=2722 +// chroma_offset_l1=2982 +const _: () = { + use std::mem::{align_of, offset_of, size_of}; + + assert!(size_of::() == 36 && align_of::() == 4); + assert!(offset_of!(VAPictureH264, frame_idx) == 4); + assert!(offset_of!(VAPictureH264, flags) == 8); + assert!(offset_of!(VAPictureH264, top_field_order_cnt) == 12); + assert!(offset_of!(VAPictureH264, bottom_field_order_cnt) == 16); + + assert!( + size_of::() == 672 + && align_of::() == 4 + ); + assert!(offset_of!(PictureParameterBufferH264, reference_frames) == 36); + assert!(offset_of!(PictureParameterBufferH264, picture_width_in_mbs_minus1) == 612); + assert!(offset_of!(PictureParameterBufferH264, bit_depth_luma_minus8) == 616); + assert!(offset_of!(PictureParameterBufferH264, num_ref_frames) == 618); + assert!(offset_of!(PictureParameterBufferH264, seq_fields) == 620); + assert!(offset_of!(PictureParameterBufferH264, pic_init_qp_minus26) == 628); + assert!(offset_of!(PictureParameterBufferH264, pic_fields) == 632); + assert!(offset_of!(PictureParameterBufferH264, frame_num) == 636); + + assert!(size_of::() == 240 && align_of::() == 4); + assert!(offset_of!(IQMatrixBufferH264, scaling_list_8x8) == 96); + + assert!( + size_of::() == 3128 + && align_of::() == 4 + ); + assert!(offset_of!(SliceParameterBufferH264, slice_data_bit_offset) == 12); + assert!(offset_of!(SliceParameterBufferH264, slice_type) == 16); + assert!(offset_of!(SliceParameterBufferH264, cabac_init_idc) == 20); + assert!(offset_of!(SliceParameterBufferH264, ref_pic_list0) == 28); + assert!(offset_of!(SliceParameterBufferH264, ref_pic_list1) == 1180); + assert!(offset_of!(SliceParameterBufferH264, luma_log2_weight_denom) == 2332); + assert!(offset_of!(SliceParameterBufferH264, luma_weight_l0) == 2336); + assert!(offset_of!(SliceParameterBufferH264, chroma_weight_l0) == 2466); + assert!(offset_of!(SliceParameterBufferH264, luma_weight_l1_flag) == 2722); + assert!(offset_of!(SliceParameterBufferH264, chroma_offset_l1) == 2982); +}; diff --git a/crates/ec-hw/src/params/hevc.rs b/crates/ec-hw/src/params/hevc.rs new file mode 100644 index 00000000..9061b72f --- /dev/null +++ b/crates/ec-hw/src/params/hevc.rs @@ -0,0 +1,473 @@ +//! HEVC decode parameter buffers (`va.h:5287`, `va_dec_hevc.h`). + +use ec_va::sys::{ + VAIQMatrixBufferType, VAPictureParameterBufferType, VASliceParameterBufferType, VASurfaceID, +}; + +use super::{INVALID_SURFACE, VaParam}; +use crate::va_bits; + +/// `VA_PICTURE_HEVC_INVALID`. +pub const PICTURE_INVALID: u32 = 0x0000_0001; +/// `VA_PICTURE_HEVC_FIELD_PIC`. +pub const PICTURE_FIELD_PIC: u32 = 0x0000_0002; +/// `VA_PICTURE_HEVC_BOTTOM_FIELD`. +pub const PICTURE_BOTTOM_FIELD: u32 = 0x0000_0004; +/// `VA_PICTURE_HEVC_LONG_TERM_REFERENCE`. +pub const PICTURE_LONG_TERM_REFERENCE: u32 = 0x0000_0008; +/// `VA_PICTURE_HEVC_RPS_ST_CURR_BEFORE`. +pub const PICTURE_RPS_ST_CURR_BEFORE: u32 = 0x0000_0010; +/// `VA_PICTURE_HEVC_RPS_ST_CURR_AFTER`. +pub const PICTURE_RPS_ST_CURR_AFTER: u32 = 0x0000_0020; +/// `VA_PICTURE_HEVC_RPS_LT_CURR`. +pub const PICTURE_RPS_LT_CURR: u32 = 0x0000_0040; + +/// `VAPictureHEVC`, `va.h:5287`. +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct VAPictureHEVC { + /// Surface holding the picture, or [`INVALID_SURFACE`]. + pub picture_id: VASurfaceID, + /// `PicOrderCntVal`. + pub pic_order_cnt: i32, + /// `VA_PICTURE_HEVC_*` bitmask. + pub flags: u32, + pub(crate) va_reserved: [u32; 4], +} + +impl VAPictureHEVC { + /// The "no picture here" entry for unused reference slots. + pub const INVALID: VAPictureHEVC = VAPictureHEVC { + picture_id: INVALID_SURFACE, + pic_order_cnt: 0, + flags: PICTURE_INVALID, + va_reserved: [0; 4], + }; + + /// A reference or current picture. + pub fn new(picture_id: VASurfaceID, pic_order_cnt: i32, flags: u32) -> VAPictureHEVC { + VAPictureHEVC { + picture_id, + pic_order_cnt, + flags, + va_reserved: [0; 4], + } + } +} + +impl Default for VAPictureHEVC { + fn default() -> Self { + VAPictureHEVC::INVALID + } +} + +va_bits! { + /// `VAPictureParameterBufferHEVC::pic_fields`. + PicFields: u32 { + chroma_format_idc: 2, + separate_colour_plane_flag: 1, + pcm_enabled_flag: 1, + scaling_list_enabled_flag: 1, + transform_skip_enabled_flag: 1, + amp_enabled_flag: 1, + strong_intra_smoothing_enabled_flag: 1, + sign_data_hiding_enabled_flag: 1, + constrained_intra_pred_flag: 1, + cu_qp_delta_enabled_flag: 1, + weighted_pred_flag: 1, + weighted_bipred_flag: 1, + transquant_bypass_enabled_flag: 1, + tiles_enabled_flag: 1, + entropy_coding_sync_enabled_flag: 1, + pps_loop_filter_across_slices_enabled_flag: 1, + loop_filter_across_tiles_enabled_flag: 1, + pcm_loop_filter_disabled_flag: 1, + no_pic_reordering_flag: 1, + no_bi_pred_flag: 1, + } +} + +va_bits! { + /// `VAPictureParameterBufferHEVC::slice_parsing_fields`. + SliceParsingFields: u32 { + lists_modification_present_flag: 1, + long_term_ref_pics_present_flag: 1, + sps_temporal_mvp_enabled_flag: 1, + cabac_init_present_flag: 1, + output_flag_present_flag: 1, + dependent_slice_segments_enabled_flag: 1, + pps_slice_chroma_qp_offsets_present_flag: 1, + sample_adaptive_offset_enabled_flag: 1, + deblocking_filter_override_enabled_flag: 1, + pps_disable_deblocking_filter_flag: 1, + slice_segment_header_extension_present_flag: 1, + rap_pic_flag: 1, + idr_pic_flag: 1, + intra_pic_flag: 1, + } +} + +/// `VAPictureParameterBufferHEVC`, `va_dec_hevc.h:57`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct PictureParameterBufferHEVC { + /// The picture being decoded. + pub curr_pic: VAPictureHEVC, + /// The DPB; unused slots are [`VAPictureHEVC::INVALID`]. + pub reference_frames: [VAPictureHEVC; 15], + /// `pic_width_in_luma_samples`. + pub pic_width_in_luma_samples: u16, + /// `pic_height_in_luma_samples`. + pub pic_height_in_luma_samples: u16, + /// Picture flags. + pub pic_fields: PicFields, + /// `sps_max_dec_pic_buffering_minus1`. + pub sps_max_dec_pic_buffering_minus1: u8, + /// `bit_depth_luma_minus8`. + pub bit_depth_luma_minus8: u8, + /// `bit_depth_chroma_minus8`. + pub bit_depth_chroma_minus8: u8, + /// `pcm_sample_bit_depth_luma_minus1`. + pub pcm_sample_bit_depth_luma_minus1: u8, + /// `pcm_sample_bit_depth_chroma_minus1`. + pub pcm_sample_bit_depth_chroma_minus1: u8, + /// `log2_min_luma_coding_block_size_minus3`. + pub log2_min_luma_coding_block_size_minus3: u8, + /// `log2_diff_max_min_luma_coding_block_size`. + pub log2_diff_max_min_luma_coding_block_size: u8, + /// `log2_min_transform_block_size_minus2`. + pub log2_min_transform_block_size_minus2: u8, + /// `log2_diff_max_min_transform_block_size`. + pub log2_diff_max_min_transform_block_size: u8, + /// `log2_min_pcm_luma_coding_block_size_minus3`. + pub log2_min_pcm_luma_coding_block_size_minus3: u8, + /// `log2_diff_max_min_pcm_luma_coding_block_size`. + pub log2_diff_max_min_pcm_luma_coding_block_size: u8, + /// `max_transform_hierarchy_depth_intra`. + pub max_transform_hierarchy_depth_intra: u8, + /// `max_transform_hierarchy_depth_inter`. + pub max_transform_hierarchy_depth_inter: u8, + /// `init_qp_minus26`. + pub init_qp_minus26: i8, + /// `diff_cu_qp_delta_depth`. + pub diff_cu_qp_delta_depth: u8, + /// `pps_cb_qp_offset`. + pub pps_cb_qp_offset: i8, + /// `pps_cr_qp_offset`. + pub pps_cr_qp_offset: i8, + /// `log2_parallel_merge_level_minus2`. + pub log2_parallel_merge_level_minus2: u8, + /// `num_tile_columns_minus1`. + pub num_tile_columns_minus1: u8, + /// `num_tile_rows_minus1`. + pub num_tile_rows_minus1: u8, + /// `column_width_minus1`, filled even for uniform spacing. + pub column_width_minus1: [u16; 19], + /// `row_height_minus1`, filled even for uniform spacing. + pub row_height_minus1: [u16; 21], + /// Flags a driver needs to parse slice segment headers. + pub slice_parsing_fields: SliceParsingFields, + /// `log2_max_pic_order_cnt_lsb_minus4`. + pub log2_max_pic_order_cnt_lsb_minus4: u8, + /// `num_short_term_ref_pic_sets`. + pub num_short_term_ref_pic_sets: u8, + /// `num_long_term_ref_pics_sps`. + pub num_long_term_ref_pic_sps: u8, + /// `num_ref_idx_l0_default_active_minus1`. + pub num_ref_idx_l0_default_active_minus1: u8, + /// `num_ref_idx_l1_default_active_minus1`. + pub num_ref_idx_l1_default_active_minus1: u8, + /// `pps_beta_offset_div2`. + pub pps_beta_offset_div2: i8, + /// `pps_tc_offset_div2`. + pub pps_tc_offset_div2: i8, + /// `num_extra_slice_header_bits`. + pub num_extra_slice_header_bits: u8, + /// Size in bits of the `st_ref_pic_set()` written in the slice header, so + /// the driver can skip it; zero when the slice referenced an SPS set. + pub st_rps_bits: u32, + pub(crate) va_reserved: [u32; 8], +} + +impl Default for PictureParameterBufferHEVC { + fn default() -> Self { + PictureParameterBufferHEVC { + curr_pic: VAPictureHEVC::INVALID, + reference_frames: [VAPictureHEVC::INVALID; 15], + pic_width_in_luma_samples: 0, + pic_height_in_luma_samples: 0, + pic_fields: PicFields::default(), + sps_max_dec_pic_buffering_minus1: 0, + bit_depth_luma_minus8: 0, + bit_depth_chroma_minus8: 0, + pcm_sample_bit_depth_luma_minus1: 0, + pcm_sample_bit_depth_chroma_minus1: 0, + log2_min_luma_coding_block_size_minus3: 0, + log2_diff_max_min_luma_coding_block_size: 0, + log2_min_transform_block_size_minus2: 0, + log2_diff_max_min_transform_block_size: 0, + log2_min_pcm_luma_coding_block_size_minus3: 0, + log2_diff_max_min_pcm_luma_coding_block_size: 0, + max_transform_hierarchy_depth_intra: 0, + max_transform_hierarchy_depth_inter: 0, + init_qp_minus26: 0, + diff_cu_qp_delta_depth: 0, + pps_cb_qp_offset: 0, + pps_cr_qp_offset: 0, + log2_parallel_merge_level_minus2: 0, + num_tile_columns_minus1: 0, + num_tile_rows_minus1: 0, + column_width_minus1: [0; 19], + row_height_minus1: [0; 21], + slice_parsing_fields: SliceParsingFields::default(), + log2_max_pic_order_cnt_lsb_minus4: 0, + num_short_term_ref_pic_sets: 0, + num_long_term_ref_pic_sps: 0, + num_ref_idx_l0_default_active_minus1: 0, + num_ref_idx_l1_default_active_minus1: 0, + pps_beta_offset_div2: 0, + pps_tc_offset_div2: 0, + num_extra_slice_header_bits: 0, + st_rps_bits: 0, + va_reserved: [0; 8], + } + } +} + +// SAFETY: `#[repr(C)]` transcription of `VAPictureParameterBufferHEVC`, checked +// by the assertion block below; all fields are integers or integer arrays. +unsafe impl VaParam for PictureParameterBufferHEVC { + const TYPE: i32 = VAPictureParameterBufferType; +} + +va_bits! { + /// `VASliceParameterBufferHEVC::LongSliceFlags`. + LongSliceFlags: u32 { + last_slice_of_pic: 1, + dependent_slice_segment_flag: 1, + slice_type: 2, + color_plane_id: 2, + slice_sao_luma_flag: 1, + slice_sao_chroma_flag: 1, + mvd_l1_zero_flag: 1, + cabac_init_flag: 1, + slice_temporal_mvp_enabled_flag: 1, + slice_deblocking_filter_disabled_flag: 1, + collocated_from_l0_flag: 1, + slice_loop_filter_across_slices_enabled_flag: 1, + } +} + +/// `VASliceParameterBufferHEVC`, `va_dec_hevc.h:352`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct SliceParameterBufferHEVC { + /// Bytes of slice data, NAL unit header included. + pub slice_data_size: u32, + /// Offset of this slice's NAL unit within the data buffer. + pub slice_data_offset: u32, + /// `VA_SLICE_DATA_FLAG_*`. + pub slice_data_flag: u32, + /// Bytes from the NAL unit header to `slice_data()`, in escaped bytes. + pub slice_data_byte_offset: u32, + /// `slice_segment_address`. + pub slice_segment_address: u32, + /// Indices into `reference_frames`, `0xff` for unused entries. + pub ref_pic_list: [[u8; 15]; 2], + /// Slice flags. + pub long_slice_flags: LongSliceFlags, + /// Index into `ref_pic_list`, `0xff` when there is no collocated picture. + pub collocated_ref_idx: u8, + /// `num_ref_idx_l0_active_minus1`, override applied. + pub num_ref_idx_l0_active_minus1: u8, + /// `num_ref_idx_l1_active_minus1`, override applied. + pub num_ref_idx_l1_active_minus1: u8, + /// `slice_qp_delta`. + pub slice_qp_delta: i8, + /// `slice_cb_qp_offset`. + pub slice_cb_qp_offset: i8, + /// `slice_cr_qp_offset`. + pub slice_cr_qp_offset: i8, + /// `slice_beta_offset_div2`. + pub slice_beta_offset_div2: i8, + /// `slice_tc_offset_div2`. + pub slice_tc_offset_div2: i8, + /// `luma_log2_weight_denom`. + pub luma_log2_weight_denom: u8, + /// `delta_chroma_log2_weight_denom`. + pub delta_chroma_log2_weight_denom: i8, + /// `delta_luma_weight_l0`. + pub delta_luma_weight_l0: [i8; 15], + /// `luma_offset_l0`. + pub luma_offset_l0: [i8; 15], + /// `delta_chroma_weight_l0`. + pub delta_chroma_weight_l0: [[i8; 2]; 15], + /// `ChromaOffsetL0`. + pub chroma_offset_l0: [[i8; 2]; 15], + /// `delta_luma_weight_l1`. + pub delta_luma_weight_l1: [i8; 15], + /// `luma_offset_l1`. + pub luma_offset_l1: [i8; 15], + /// `delta_chroma_weight_l1`. + pub delta_chroma_weight_l1: [[i8; 2]; 15], + /// `ChromaOffsetL1`. + pub chroma_offset_l1: [[i8; 2]; 15], + /// `five_minus_max_num_merge_cand`. + pub five_minus_max_num_merge_cand: u8, + /// `num_entry_point_offsets`. + pub num_entry_point_offsets: u16, + /// `entry_offset_to_subset_array`. + pub entry_offset_to_subset_array: u16, + /// Emulation prevention bytes inside the slice header. + pub slice_data_num_emu_prevn_bytes: u16, + pub(crate) va_reserved: [u32; 2], +} + +impl Default for SliceParameterBufferHEVC { + fn default() -> Self { + SliceParameterBufferHEVC { + slice_data_size: 0, + slice_data_offset: 0, + slice_data_flag: 0, + slice_data_byte_offset: 0, + slice_segment_address: 0, + ref_pic_list: [[0xff; 15]; 2], + long_slice_flags: LongSliceFlags::default(), + collocated_ref_idx: 0xff, + num_ref_idx_l0_active_minus1: 0, + num_ref_idx_l1_active_minus1: 0, + slice_qp_delta: 0, + slice_cb_qp_offset: 0, + slice_cr_qp_offset: 0, + slice_beta_offset_div2: 0, + slice_tc_offset_div2: 0, + luma_log2_weight_denom: 0, + delta_chroma_log2_weight_denom: 0, + delta_luma_weight_l0: [0; 15], + luma_offset_l0: [0; 15], + delta_chroma_weight_l0: [[0; 2]; 15], + chroma_offset_l0: [[0; 2]; 15], + delta_luma_weight_l1: [0; 15], + luma_offset_l1: [0; 15], + delta_chroma_weight_l1: [[0; 2]; 15], + chroma_offset_l1: [[0; 2]; 15], + five_minus_max_num_merge_cand: 0, + num_entry_point_offsets: 0, + entry_offset_to_subset_array: 0, + slice_data_num_emu_prevn_bytes: 0, + va_reserved: [0; 2], + } + } +} + +// SAFETY: as `PictureParameterBufferHEVC`. +unsafe impl VaParam for SliceParameterBufferHEVC { + const TYPE: i32 = VASliceParameterBufferType; +} + +/// `VAIQMatrixBufferHEVC`, `va_dec_hevc.h:561`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct IQMatrixBufferHEVC { + /// `ScalingList[0]`. + pub scaling_list_4x4: [[u8; 16]; 6], + /// `ScalingList[1]`. + pub scaling_list_8x8: [[u8; 64]; 6], + /// `ScalingList[2]`. + pub scaling_list_16x16: [[u8; 64]; 6], + /// `ScalingList[3]`. + pub scaling_list_32x32: [[u8; 64]; 2], + /// DC coefficients of the 16x16 lists. + pub scaling_list_dc_16x16: [u8; 6], + /// DC coefficients of the 32x32 lists. + pub scaling_list_dc_32x32: [u8; 2], + pub(crate) va_reserved: [u32; 4], +} + +impl Default for IQMatrixBufferHEVC { + fn default() -> Self { + IQMatrixBufferHEVC { + scaling_list_4x4: [[16; 16]; 6], + scaling_list_8x8: [[16; 64]; 6], + scaling_list_16x16: [[16; 64]; 6], + scaling_list_32x32: [[16; 64]; 2], + scaling_list_dc_16x16: [16; 6], + scaling_list_dc_32x32: [16; 2], + va_reserved: [0; 4], + } + } +} + +// SAFETY: as `PictureParameterBufferHEVC`. +unsafe impl VaParam for IQMatrixBufferHEVC { + const TYPE: i32 = VAIQMatrixBufferType; +} + +// --------------------------------------------------------------------------- +// ABI transcription check — `crates/ec-hw/abi-probe.c`, libva 1.23.0, x86_64: +// +// VAPictureHEVC size=28 align=4 pic_order_cnt=4 flags=8 +// VAPictureParameterBufferHEVC size=604 align=4 ReferenceFrames=28 +// pic_width_in_luma_samples=448 +// pic_fields=452 +// sps_max_dec_pic_buffering_minus1=456 +// column_width_minus1=476 +// row_height_minus1=514 +// slice_parsing_fields=556 +// log2_max_pic_order_cnt_lsb_minus4=560 +// st_rps_bits=568 +// VASliceParameterBufferHEVC size=264 align=4 slice_segment_address=16 +// RefPicList=20 LongSliceFlags=52 +// collocated_ref_idx=56 +// luma_log2_weight_denom=64 +// delta_luma_weight_l0=66 +// delta_luma_weight_l1=156 +// five_minus_max_num_merge_cand=246 +// num_entry_point_offsets=248 +// slice_data_num_emu_prevn_bytes=252 +// VAIQMatrixBufferHEVC size=1016 align=4 ScalingList32x32=864 +// ScalingListDC16x16=992 +const _: () = { + use std::mem::{align_of, offset_of, size_of}; + + assert!(size_of::() == 28 && align_of::() == 4); + assert!(offset_of!(VAPictureHEVC, pic_order_cnt) == 4); + assert!(offset_of!(VAPictureHEVC, flags) == 8); + + assert!( + size_of::() == 604 + && align_of::() == 4 + ); + assert!(offset_of!(PictureParameterBufferHEVC, reference_frames) == 28); + assert!(offset_of!(PictureParameterBufferHEVC, pic_width_in_luma_samples) == 448); + assert!(offset_of!(PictureParameterBufferHEVC, pic_fields) == 452); + assert!(offset_of!(PictureParameterBufferHEVC, sps_max_dec_pic_buffering_minus1) == 456); + assert!(offset_of!(PictureParameterBufferHEVC, column_width_minus1) == 476); + assert!(offset_of!(PictureParameterBufferHEVC, row_height_minus1) == 514); + assert!(offset_of!(PictureParameterBufferHEVC, slice_parsing_fields) == 556); + assert!( + offset_of!( + PictureParameterBufferHEVC, + log2_max_pic_order_cnt_lsb_minus4 + ) == 560 + ); + assert!(offset_of!(PictureParameterBufferHEVC, st_rps_bits) == 568); + + assert!( + size_of::() == 264 && align_of::() == 4 + ); + assert!(offset_of!(SliceParameterBufferHEVC, slice_segment_address) == 16); + assert!(offset_of!(SliceParameterBufferHEVC, ref_pic_list) == 20); + assert!(offset_of!(SliceParameterBufferHEVC, long_slice_flags) == 52); + assert!(offset_of!(SliceParameterBufferHEVC, collocated_ref_idx) == 56); + assert!(offset_of!(SliceParameterBufferHEVC, luma_log2_weight_denom) == 64); + assert!(offset_of!(SliceParameterBufferHEVC, delta_luma_weight_l0) == 66); + assert!(offset_of!(SliceParameterBufferHEVC, delta_luma_weight_l1) == 156); + assert!(offset_of!(SliceParameterBufferHEVC, five_minus_max_num_merge_cand) == 246); + assert!(offset_of!(SliceParameterBufferHEVC, num_entry_point_offsets) == 248); + assert!(offset_of!(SliceParameterBufferHEVC, slice_data_num_emu_prevn_bytes) == 252); + + assert!(size_of::() == 1016 && align_of::() == 4); + assert!(offset_of!(IQMatrixBufferHEVC, scaling_list_32x32) == 864); + assert!(offset_of!(IQMatrixBufferHEVC, scaling_list_dc_16x16) == 992); +}; diff --git a/crates/ec-hw/src/params/mod.rs b/crates/ec-hw/src/params/mod.rs new file mode 100644 index 00000000..3eec8004 --- /dev/null +++ b/crates/ec-hw/src/params/mod.rs @@ -0,0 +1,134 @@ +//! `#[repr(C)]` transcriptions of the libva codec parameter structs. +//! +//! `ec-va` deliberately stops at the generic VA surface (display, config, +//! context, buffer, picture); the per-codec buffers live here because they are +//! what a *decoder* is, field for field. Every struct is transcribed by hand +//! from the system headers, in header order, and every one of them is checked +//! against `crates/ec-hw/abi-probe.c` output by the `const` assertion block at +//! the end of its module. A transcription slip is therefore a compile error, +//! not a driver reading garbage. +//! +//! Reference output of the probe (libva 1.23.0, x86_64 System V) is pasted +//! above each assertion block. Rerun it after a libva upgrade: +//! +//! ```text +//! cc -o /tmp/abi-probe crates/ec-hw/abi-probe.c $(pkg-config --cflags libva) +//! ``` +//! +//! # Bit fields +//! +//! The C headers pack flags into `union { struct { uint32_t a : 2; ... } bits; +//! uint32_t value; }`. Rust has no bit fields, so each union becomes a +//! `#[repr(transparent)]` newtype over its storage integer with one chained +//! setter per flag, generated by [`va_bits`]. The System V ABI allocates +//! bit fields LSB first within the storage unit, which is what the generated +//! shifts assume — the one ABI assumption in this module that the probe cannot +//! see, and the reason every generated setter is exercised by a unit test. + +use std::sync::Arc; + +use ec_va::sys::{VABufferType, VASurfaceID}; +use ec_va::{Buffer, Context}; + +use crate::error::Result; + +pub mod av1; +pub mod enc; +pub mod h264; +pub mod hevc; +pub mod vp9; + +/// A plain-old-data parameter struct libva reads verbatim. +/// +/// # Safety +/// +/// The implementing type must be a `#[repr(C)]` transcription of exactly the +/// libva struct that belongs to [`VaParam::TYPE`], with the same size and field +/// offsets (which is what the `const` assertions in this module check), and +/// must be valid for any bit pattern it is constructed with — the driver reads +/// `size_of::()` bytes of it, padding included. +pub unsafe trait VaParam: Copy { + /// The `VABufferType` this struct is submitted as. + const TYPE: VABufferType; +} + +/// Create a VA buffer holding one parameter struct. +/// +/// This is the *only* place `ec-hw` hands a Rust value to the driver as bytes; +/// the [`VaParam`] bound is what makes it sound, and every implementation of +/// that trait sits next to the transcription it vouches for. +pub fn param_buffer(context: &Arc, param: &T) -> Result { + // SAFETY: `T: VaParam` guarantees `T` is the `#[repr(C)]` transcription of + // the libva parameter struct for `T::TYPE`, and the layout assertions in + // this module check that guarantee at compile time against the system + // headers. libva copies the bytes during the call. + Ok(unsafe { Buffer::from_param(context, T::TYPE, param) }?) +} + +/// `VA_INVALID_SURFACE`, spelled out where a parameter struct means "no picture". +pub const INVALID_SURFACE: VASurfaceID = ec_va::sys::VA_INVALID_SURFACE; + +/// Generate a `#[repr(transparent)]` newtype standing in for a C bit field union. +/// +/// Fields are listed in header order with their widths; the generated setters +/// place them LSB first, which is how the System V ABI allocates `uint32_t` +/// bit fields. Each setter masks its value, so an out-of-range argument cannot +/// corrupt a neighbouring field. +#[macro_export] +macro_rules! va_bits { + ( + $(#[$meta:meta])* + $name:ident : $storage:ty { $( $field:ident : $width:expr ),* $(,)? } + ) => { + $(#[$meta])* + #[repr(transparent)] + #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] + pub struct $name(pub $storage); + + impl $name { + $crate::va_bits!(@fields $name, $storage, 0, $( $field : $width, )*); + + /// The packed value, as the C union's `value` member. + pub fn value(self) -> $storage { + self.0 + } + } + }; + (@fields $name:ident, $storage:ty, $offset:expr,) => {}; + (@fields $name:ident, $storage:ty, $offset:expr, $field:ident : $width:expr, $($rest:tt)*) => { + #[doc = concat!("Set `", stringify!($field), "` (", stringify!($width), " bit(s)).")] + #[must_use] + pub fn $field(mut self, value: $storage) -> Self { + let mask: $storage = ((1 as $storage) << $width) - 1; + self.0 &= !(mask << $offset); + self.0 |= (value & mask) << $offset; + self + } + $crate::va_bits!(@fields $name, $storage, $offset + $width, $($rest)*); + }; +} + +#[cfg(test)] +mod tests { + va_bits! { + /// Three fields spanning a byte boundary, to pin the LSB-first order. + Probe: u32 { a: 2, b: 1, c: 4, d: 8 } + } + + #[test] + fn bit_fields_pack_least_significant_first() { + let v = Probe::default().a(3).b(1).c(0xf).d(0xff); + assert_eq!(v.value(), 0x7fff); + // Each setter is independent and masks its argument. + let v = Probe::default().c(0xff); + assert_eq!(v.value(), 0b111_1000); + let v = Probe::default().d(1).c(0).a(1); + assert_eq!(v.value(), (1 << 7) | 1); + } + + #[test] + fn setters_overwrite_rather_than_or() { + let v = Probe::default().a(3).a(1); + assert_eq!(v.value(), 1); + } +} diff --git a/crates/ec-hw/src/params/vp9.rs b/crates/ec-hw/src/params/vp9.rs new file mode 100644 index 00000000..0ac620ba --- /dev/null +++ b/crates/ec-hw/src/params/vp9.rs @@ -0,0 +1,182 @@ +//! VP9 decode parameter buffers (`va_dec_vp9.h`). + +use ec_va::sys::{VAPictureParameterBufferType, VASliceParameterBufferType, VASurfaceID}; + +use super::{INVALID_SURFACE, VaParam}; +use crate::va_bits; + +va_bits! { + /// `VADecPictureParameterBufferVP9::pic_fields`. + PicFields: u32 { + subsampling_x: 1, + subsampling_y: 1, + frame_type: 1, + show_frame: 1, + error_resilient_mode: 1, + intra_only: 1, + allow_high_precision_mv: 1, + mcomp_filter_type: 3, + frame_parallel_decoding_mode: 1, + reset_frame_context: 2, + refresh_frame_context: 1, + frame_context_idx: 2, + segmentation_enabled: 1, + segmentation_temporal_update: 1, + segmentation_update_map: 1, + last_ref_frame: 3, + last_ref_frame_sign_bias: 1, + golden_ref_frame: 3, + golden_ref_frame_sign_bias: 1, + alt_ref_frame: 3, + alt_ref_frame_sign_bias: 1, + lossless_flag: 1, + } +} + +/// `VADecPictureParameterBufferVP9`, `va_dec_vp9.h:56`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct PictureParameterBufferVP9 { + /// `FrameWidth`. + pub frame_width: u16, + /// `FrameHeight`. + pub frame_height: u16, + /// The eight reference slots, `VA_INVALID_SURFACE` where empty. + pub reference_frames: [VASurfaceID; 8], + /// Picture flags. + pub pic_fields: PicFields, + /// `loop_filter_level`. + pub filter_level: u8, + /// `loop_filter_sharpness`. + pub sharpness_level: u8, + /// `tile_rows_log2`. + pub log2_tile_rows: u8, + /// `tile_cols_log2`. + pub log2_tile_columns: u8, + /// Size of the uncompressed header in bytes. + pub frame_header_length_in_bytes: u8, + /// `header_size_in_bytes`: the compressed header length. + pub first_partition_size: u16, + /// `segmentation_tree_probs`. + pub mb_segment_tree_probs: [u8; 7], + /// `segmentation_pred_prob`. + pub segment_pred_probs: [u8; 3], + /// `profile`. + pub profile: u8, + /// `BitDepth`. + pub bit_depth: u8, + pub(crate) va_reserved: [u32; 8], +} + +impl Default for PictureParameterBufferVP9 { + fn default() -> Self { + PictureParameterBufferVP9 { + frame_width: 0, + frame_height: 0, + reference_frames: [INVALID_SURFACE; 8], + pic_fields: PicFields::default(), + filter_level: 0, + sharpness_level: 0, + log2_tile_rows: 0, + log2_tile_columns: 0, + frame_header_length_in_bytes: 0, + first_partition_size: 0, + // 255 is the "no update" probability VP9 infers when segmentation + // is off; zero would name a real probability. + mb_segment_tree_probs: [255; 7], + segment_pred_probs: [255; 3], + profile: 0, + bit_depth: 8, + va_reserved: [0; 8], + } + } +} + +// SAFETY: `#[repr(C)]` transcription of `VADecPictureParameterBufferVP9`, +// checked by the assertion block below; integers and integer arrays only. +unsafe impl VaParam for PictureParameterBufferVP9 { + const TYPE: i32 = VAPictureParameterBufferType; +} + +va_bits! { + /// `VASegmentParameterVP9::segment_flags`. + SegmentFlags: u16 { + segment_reference_enabled: 1, + segment_reference: 2, + segment_reference_skipped: 1, + } +} + +/// `VASegmentParameterVP9`, `va_dec_vp9.h:196`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub struct SegmentParameterVP9 { + /// Segment feature flags. + pub segment_flags: SegmentFlags, + /// `LoopFilterLevel[ref][mode]` for this segment. + pub filter_level: [[u8; 2]; 4], + /// Dequantised AC scale, luma. + pub luma_ac_quant_scale: i16, + /// Dequantised DC scale, luma. + pub luma_dc_quant_scale: i16, + /// Dequantised AC scale, chroma. + pub chroma_ac_quant_scale: i16, + /// Dequantised DC scale, chroma. + pub chroma_dc_quant_scale: i16, + pub(crate) va_reserved: [u32; 4], +} + +/// `VASliceParameterBufferVP9`, `va_dec_vp9.h:245`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub struct SliceParameterBufferVP9 { + /// Bytes of frame data. + pub slice_data_size: u32, + /// Offset of the frame within the data buffer. + pub slice_data_offset: u32, + /// `VA_SLICE_DATA_FLAG_*`. + pub slice_data_flag: u32, + /// Per-segment parameters; all eight are always sent. + pub seg_param: [SegmentParameterVP9; 8], + pub(crate) va_reserved: [u32; 4], +} + +// SAFETY: as `PictureParameterBufferVP9`. +unsafe impl VaParam for SliceParameterBufferVP9 { + const TYPE: i32 = VASliceParameterBufferType; +} + +// --------------------------------------------------------------------------- +// ABI transcription check — `crates/ec-hw/abi-probe.c`, libva 1.23.0, x86_64: +// +// VADecPictureParameterBufferVP9 size=92 align=4 reference_frames=4 +// pic_fields=36 filter_level=40 +// first_partition_size=46 +// mb_segment_tree_probs=48 +// profile=58 +// VASegmentParameterVP9 size=36 align=4 filter_level=2 +// luma_ac_quant_scale=10 +// VASliceParameterBufferVP9 size=316 align=4 seg_param=12 +const _: () = { + use std::mem::{align_of, offset_of, size_of}; + + assert!( + size_of::() == 92 + && align_of::() == 4 + ); + assert!(offset_of!(PictureParameterBufferVP9, reference_frames) == 4); + assert!(offset_of!(PictureParameterBufferVP9, pic_fields) == 36); + assert!(offset_of!(PictureParameterBufferVP9, filter_level) == 40); + assert!(offset_of!(PictureParameterBufferVP9, first_partition_size) == 46); + assert!(offset_of!(PictureParameterBufferVP9, mb_segment_tree_probs) == 48); + assert!(offset_of!(PictureParameterBufferVP9, profile) == 58); + + assert!(size_of::() == 36 && align_of::() == 4); + assert!(offset_of!(SegmentParameterVP9, filter_level) == 2); + assert!(offset_of!(SegmentParameterVP9, luma_ac_quant_scale) == 10); + + assert!( + size_of::() == 316 && align_of::() == 4 + ); + assert!(offset_of!(SliceParameterBufferVP9, seg_param) == 12); +}; diff --git a/crates/ec-hw/src/pool.rs b/crates/ec-hw/src/pool.rs new file mode 100644 index 00000000..2b03b9cc --- /dev/null +++ b/crates/ec-hw/src/pool.rs @@ -0,0 +1,132 @@ +//! A recycling pool of decode/encode surfaces. +//! +//! Surfaces are allocated once, in one `vaCreateSurfaces` call, and handed out +//! as [`PooledSurface`]s that return themselves to the free list on drop. +//! Two things hold a surface at the same time — the reference picture buffer +//! and a frame the caller has not finished with — so ownership is an +//! `Arc` and the recycle happens when the last of them goes. +//! +//! Reallocating per frame would be the alternative, and it is precisely what +//! makes a VA-API pipeline stutter: every `vaCreateSurfaces` is a kernel +//! allocation plus a driver-side tiling decision. + +use std::ops::Deref; +use std::sync::{Arc, Mutex, Weak}; + +use ec_va::{Display, Surface, SurfaceSpec}; + +use crate::error::Result; + +struct PoolInner { + /// Every surface, in allocation order. Also the context's render targets. + all: Vec>, + free: Mutex>>, +} + +/// A fixed-size pool of identically specified surfaces. +#[derive(Clone)] +pub struct SurfacePool { + inner: Arc, + spec: SurfaceSpec, +} + +impl SurfacePool { + /// Allocate `count` surfaces matching `spec`. + pub fn new(display: &Arc, spec: &SurfaceSpec, count: usize) -> Result { + let all = Surface::create_pool(display, spec, count)?; + Ok(SurfacePool { + inner: Arc::new(PoolInner { + free: Mutex::new(all.clone()), + all, + }), + spec: *spec, + }) + } + + /// Every surface in the pool — what a `Context` wants as its render targets. + pub fn targets(&self) -> &[Arc] { + &self.inner.all + } + + /// The spec every surface in this pool was allocated with. + pub fn spec(&self) -> &SurfaceSpec { + &self.spec + } + + /// Total surfaces in the pool. + pub fn len(&self) -> usize { + self.inner.all.len() + } + + /// True when the pool holds no surfaces at all. + pub fn is_empty(&self) -> bool { + self.inner.all.is_empty() + } + + /// Surfaces currently available. + pub fn available(&self) -> usize { + self.inner.free.lock().map(|f| f.len()).unwrap_or(0) + } + + /// Take a free surface, or `None` when every one is still in use. + /// + /// A `None` is the caller's cue to release output frames, not an error: a + /// decoder that has handed out its whole pool is waiting on the consumer. + pub fn acquire(&self) -> Option> { + // A poisoned lock means another thread panicked while holding it; the + // free list is a plain Vec, so its contents are still consistent and + // there is nothing to recover from. + let mut free = match self.inner.free.lock() { + Ok(free) => free, + Err(poisoned) => poisoned.into_inner(), + }; + let surface = free.pop()?; + Some(Arc::new(PooledSurface { + surface, + pool: Arc::downgrade(&self.inner), + })) + } +} + +/// A surface on loan from a [`SurfacePool`]; returns to it on drop. +pub struct PooledSurface { + surface: Arc, + pool: Weak, +} + +impl PooledSurface { + /// The surface itself, for the calls that want an owned `Arc`. + pub fn surface(&self) -> &Arc { + &self.surface + } +} + +impl Deref for PooledSurface { + type Target = Arc; + + fn deref(&self) -> &Arc { + &self.surface + } +} + +impl std::fmt::Debug for PooledSurface { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PooledSurface") + .field("id", &self.surface.id()) + .finish() + } +} + +impl Drop for PooledSurface { + fn drop(&mut self) { + let Some(pool) = self.pool.upgrade() else { + // The pool is gone, so the surface simply drops with this handle. + return; + }; + let mut free = match pool.free.lock() { + Ok(free) => free, + Err(poisoned) => poisoned.into_inner(), + }; + free.push(Arc::clone(&self.surface)); + } +}