forge
Explore
Log in

Don't you dare go Hollow

The VA-API parameter buffers, surface pool and frame readback

Browse files at this commit

89d28a744fe55eae8f17f0a1b1dc5168005dff70Ahmet Kaan GümüşParent: a1a1150
  • feat
    • the VA-API parameter buffers, surface pool and frame readback
Show full message
feat(hw): the VA-API parameter buffers, surface pool and frame readback

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.lockmodified+12 -0
@@ -312,6 +312,18 @@ dependencies = [
312312 "ec-core",
313313 ]
314314
315+[[package]]
316+name = "ec-hw"
317+version = "0.1.0"
318+dependencies = [
319+ "ec-av1-syntax",
320+ "ec-core",
321+ "ec-h264-syntax",
322+ "ec-h265-syntax",
323+ "ec-va",
324+ "ec-vp9-syntax",
325+]
326+
315327 [[package]]
316328 name = "ec-image"
317329 version = "0.1.0"
Cargo.tomlmodified+3 -0
@@ -18,7 +18,9 @@ ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" }
1818 ec-flac = { path = "crates/ec-flac", version = "0.1.0" }
1919 ec-h264 = { path = "crates/ec-h264", version = "0.1.0" }
2020 ec-h264-syntax = { path = "crates/ec-h264-syntax", version = "0.1.0" }
21+ec-h265 = { path = "crates/ec-h265", version = "0.1.0" }
2122 ec-h265-syntax = { path = "crates/ec-h265-syntax", version = "0.1.0" }
23+ec-hw = { path = "crates/ec-hw", version = "0.1.0" }
2224 ec-image = { path = "crates/ec-image", version = "0.1.0" }
2325 ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" }
2426 ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" }
@@ -28,6 +30,7 @@ ec-ogg = { path = "crates/ec-ogg", version = "0.1.0" }
2830 ec-opus = { path = "crates/ec-opus", version = "0.1.0" }
2931 ec-probe = { path = "crates/ec-probe", version = "0.1.0" }
3032 ec-riff = { path = "crates/ec-riff", version = "0.1.0" }
33+ec-va = { path = "crates/ec-va", version = "0.1.0" }
3134 ec-vorbis = { path = "crates/ec-vorbis", version = "0.1.0" }
3235 ec-vp9-syntax = { path = "crates/ec-vp9-syntax", version = "0.1.0" }
3336 # Portable SIMD without asm or build-time tooling (family rule: pure Rust only).
crates/ec-hw/Cargo.tomladded+15 -0
@@ -0,0 +1,15 @@
1+[package]
2+name = "ec-hw"
3+description = "Stateless VA-API hardware decoding and encoding: H.264, HEVC, VP9, AV1."
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+authors.workspace = true
8+
9+[dependencies]
10+ec-av1-syntax.workspace = true
11+ec-core.workspace = true
12+ec-h264-syntax.workspace = true
13+ec-h265-syntax.workspace = true
14+ec-va.workspace = true
15+ec-vp9-syntax.workspace = true
crates/ec-hw/abi-probe.cadded+271 -0
@@ -0,0 +1,271 @@
1+/* abi-probe.c — print the layout of every libva codec parameter struct this
2+ * crate transcribes, compiled against the *system* headers.
3+ *
4+ * The numbers it prints are pasted into the `const _: () = assert!(...)` block
5+ * at the end of each `src/params/*.rs`, so a transcription slip is a compile
6+ * error rather than a driver reading garbage. Rerun after a libva upgrade:
7+ *
8+ * cc -o /tmp/abi-probe crates/ec-hw/abi-probe.c $(pkg-config --cflags libva) && /tmp/abi-probe
9+ *
10+ * Same contract as crates/ec-va/abi-probe.c, one level up the stack.
11+ */
12+#include <stdio.h>
13+#include <stddef.h>
14+#include <va/va.h>
15+#include <va/va_dec_hevc.h>
16+#include <va/va_dec_vp9.h>
17+#include <va/va_dec_av1.h>
18+#include <va/va_enc_h264.h>
19+#include <va/va_enc_hevc.h>
20+#include <va/va_enc_av1.h>
21+
22+#define S(t) printf("%-46s size=%-6zu align=%zu\n", #t, sizeof(t), _Alignof(t))
23+#define O(t, f) printf(" %-44s %zu\n", #t "." #f, offsetof(t, f))
24+
25+int main(void)
26+{
27+ printf("libva %d.%d.%d\n", VA_MAJOR_VERSION, VA_MINOR_VERSION, VA_MICRO_VERSION);
28+
29+ S(VAPictureH264);
30+ O(VAPictureH264, frame_idx);
31+ O(VAPictureH264, flags);
32+ O(VAPictureH264, TopFieldOrderCnt);
33+ O(VAPictureH264, BottomFieldOrderCnt);
34+
35+ S(VAPictureParameterBufferH264);
36+ O(VAPictureParameterBufferH264, ReferenceFrames);
37+ O(VAPictureParameterBufferH264, picture_width_in_mbs_minus1);
38+ O(VAPictureParameterBufferH264, bit_depth_luma_minus8);
39+ O(VAPictureParameterBufferH264, num_ref_frames);
40+ O(VAPictureParameterBufferH264, seq_fields);
41+ O(VAPictureParameterBufferH264, pic_init_qp_minus26);
42+ O(VAPictureParameterBufferH264, pic_fields);
43+ O(VAPictureParameterBufferH264, frame_num);
44+
45+ S(VAIQMatrixBufferH264);
46+ O(VAIQMatrixBufferH264, ScalingList8x8);
47+
48+ S(VASliceParameterBufferH264);
49+ O(VASliceParameterBufferH264, slice_data_bit_offset);
50+ O(VASliceParameterBufferH264, slice_type);
51+ O(VASliceParameterBufferH264, cabac_init_idc);
52+ O(VASliceParameterBufferH264, RefPicList0);
53+ O(VASliceParameterBufferH264, RefPicList1);
54+ O(VASliceParameterBufferH264, luma_log2_weight_denom);
55+ O(VASliceParameterBufferH264, luma_weight_l0);
56+ O(VASliceParameterBufferH264, chroma_weight_l0);
57+ O(VASliceParameterBufferH264, luma_weight_l1_flag);
58+ O(VASliceParameterBufferH264, chroma_offset_l1);
59+
60+ S(VAPictureHEVC);
61+ O(VAPictureHEVC, pic_order_cnt);
62+ O(VAPictureHEVC, flags);
63+
64+ S(VAPictureParameterBufferHEVC);
65+ O(VAPictureParameterBufferHEVC, ReferenceFrames);
66+ O(VAPictureParameterBufferHEVC, pic_width_in_luma_samples);
67+ O(VAPictureParameterBufferHEVC, pic_fields);
68+ O(VAPictureParameterBufferHEVC, sps_max_dec_pic_buffering_minus1);
69+ O(VAPictureParameterBufferHEVC, column_width_minus1);
70+ O(VAPictureParameterBufferHEVC, row_height_minus1);
71+ O(VAPictureParameterBufferHEVC, slice_parsing_fields);
72+ O(VAPictureParameterBufferHEVC, log2_max_pic_order_cnt_lsb_minus4);
73+ O(VAPictureParameterBufferHEVC, st_rps_bits);
74+
75+ S(VASliceParameterBufferHEVC);
76+ O(VASliceParameterBufferHEVC, slice_segment_address);
77+ O(VASliceParameterBufferHEVC, RefPicList);
78+ O(VASliceParameterBufferHEVC, LongSliceFlags);
79+ O(VASliceParameterBufferHEVC, collocated_ref_idx);
80+ O(VASliceParameterBufferHEVC, luma_log2_weight_denom);
81+ O(VASliceParameterBufferHEVC, delta_luma_weight_l0);
82+ O(VASliceParameterBufferHEVC, delta_luma_weight_l1);
83+ O(VASliceParameterBufferHEVC, five_minus_max_num_merge_cand);
84+ O(VASliceParameterBufferHEVC, num_entry_point_offsets);
85+ O(VASliceParameterBufferHEVC, slice_data_num_emu_prevn_bytes);
86+
87+ S(VAIQMatrixBufferHEVC);
88+ O(VAIQMatrixBufferHEVC, ScalingList32x32);
89+ O(VAIQMatrixBufferHEVC, ScalingListDC16x16);
90+
91+ S(VADecPictureParameterBufferVP9);
92+ O(VADecPictureParameterBufferVP9, reference_frames);
93+ O(VADecPictureParameterBufferVP9, pic_fields);
94+ O(VADecPictureParameterBufferVP9, filter_level);
95+ O(VADecPictureParameterBufferVP9, first_partition_size);
96+ O(VADecPictureParameterBufferVP9, mb_segment_tree_probs);
97+ O(VADecPictureParameterBufferVP9, profile);
98+
99+ S(VASegmentParameterVP9);
100+ O(VASegmentParameterVP9, filter_level);
101+ O(VASegmentParameterVP9, luma_ac_quant_scale);
102+
103+ S(VASliceParameterBufferVP9);
104+ O(VASliceParameterBufferVP9, seg_param);
105+
106+ S(VASegmentationStructAV1);
107+ O(VASegmentationStructAV1, feature_data);
108+ O(VASegmentationStructAV1, feature_mask);
109+ S(VAFilmGrainStructAV1);
110+ O(VAFilmGrainStructAV1, grain_seed);
111+ O(VAFilmGrainStructAV1, ar_coeffs_y);
112+ O(VAFilmGrainStructAV1, cr_offset);
113+ S(VAWarpedMotionParamsAV1);
114+ O(VAWarpedMotionParamsAV1, wmmat);
115+ O(VAWarpedMotionParamsAV1, invalid);
116+
117+ S(VADecPictureParameterBufferAV1);
118+ O(VADecPictureParameterBufferAV1, seq_info_fields);
119+ O(VADecPictureParameterBufferAV1, current_frame);
120+ O(VADecPictureParameterBufferAV1, anchor_frames_num);
121+ O(VADecPictureParameterBufferAV1, anchor_frames_list);
122+ O(VADecPictureParameterBufferAV1, frame_width_minus1);
123+ O(VADecPictureParameterBufferAV1, ref_frame_map);
124+ O(VADecPictureParameterBufferAV1, ref_frame_idx);
125+ O(VADecPictureParameterBufferAV1, seg_info);
126+ O(VADecPictureParameterBufferAV1, film_grain_info);
127+ O(VADecPictureParameterBufferAV1, tile_cols);
128+ O(VADecPictureParameterBufferAV1, width_in_sbs_minus_1);
129+ O(VADecPictureParameterBufferAV1, height_in_sbs_minus_1);
130+ O(VADecPictureParameterBufferAV1, tile_count_minus_1);
131+ O(VADecPictureParameterBufferAV1, pic_info_fields);
132+ O(VADecPictureParameterBufferAV1, superres_scale_denominator);
133+ O(VADecPictureParameterBufferAV1, loop_filter_info_fields);
134+ O(VADecPictureParameterBufferAV1, ref_deltas);
135+ O(VADecPictureParameterBufferAV1, base_qindex);
136+ O(VADecPictureParameterBufferAV1, qmatrix_fields);
137+ O(VADecPictureParameterBufferAV1, mode_control_fields);
138+ O(VADecPictureParameterBufferAV1, cdef_damping_minus_3);
139+ O(VADecPictureParameterBufferAV1, cdef_y_strengths);
140+ O(VADecPictureParameterBufferAV1, loop_restoration_fields);
141+ O(VADecPictureParameterBufferAV1, wm);
142+
143+ S(VASliceParameterBufferAV1);
144+ O(VASliceParameterBufferAV1, tile_row);
145+ O(VASliceParameterBufferAV1, anchor_frame_idx);
146+ O(VASliceParameterBufferAV1, tile_idx_in_tile_list);
147+
148+ S(VAEncSequenceParameterBufferH264);
149+ O(VAEncSequenceParameterBufferH264, intra_period);
150+ O(VAEncSequenceParameterBufferH264, picture_width_in_mbs);
151+ O(VAEncSequenceParameterBufferH264, seq_fields);
152+ O(VAEncSequenceParameterBufferH264, bit_depth_luma_minus8);
153+ O(VAEncSequenceParameterBufferH264, offset_for_non_ref_pic);
154+ O(VAEncSequenceParameterBufferH264, offset_for_ref_frame);
155+ O(VAEncSequenceParameterBufferH264, frame_cropping_flag);
156+ O(VAEncSequenceParameterBufferH264, frame_crop_left_offset);
157+ O(VAEncSequenceParameterBufferH264, vui_parameters_present_flag);
158+ O(VAEncSequenceParameterBufferH264, vui_fields);
159+ O(VAEncSequenceParameterBufferH264, aspect_ratio_idc);
160+ O(VAEncSequenceParameterBufferH264, num_units_in_tick);
161+ O(VAEncSequenceParameterBufferH264, time_scale);
162+
163+ S(VAEncPictureParameterBufferH264);
164+ O(VAEncPictureParameterBufferH264, ReferenceFrames);
165+ O(VAEncPictureParameterBufferH264, coded_buf);
166+ O(VAEncPictureParameterBufferH264, pic_parameter_set_id);
167+ O(VAEncPictureParameterBufferH264, frame_num);
168+ O(VAEncPictureParameterBufferH264, pic_init_qp);
169+ O(VAEncPictureParameterBufferH264, pic_fields);
170+
171+ S(VAEncSliceParameterBufferH264);
172+ O(VAEncSliceParameterBufferH264, macroblock_info);
173+ O(VAEncSliceParameterBufferH264, slice_type);
174+ O(VAEncSliceParameterBufferH264, idr_pic_id);
175+ O(VAEncSliceParameterBufferH264, delta_pic_order_cnt_bottom);
176+ O(VAEncSliceParameterBufferH264, direct_spatial_mv_pred_flag);
177+ O(VAEncSliceParameterBufferH264, RefPicList0);
178+ O(VAEncSliceParameterBufferH264, RefPicList1);
179+ O(VAEncSliceParameterBufferH264, luma_log2_weight_denom);
180+ O(VAEncSliceParameterBufferH264, cabac_init_idc);
181+
182+ S(VAEncSequenceParameterBufferHEVC);
183+ O(VAEncSequenceParameterBufferHEVC, intra_period);
184+ O(VAEncSequenceParameterBufferHEVC, pic_width_in_luma_samples);
185+ O(VAEncSequenceParameterBufferHEVC, seq_fields);
186+ O(VAEncSequenceParameterBufferHEVC, log2_min_luma_coding_block_size_minus3);
187+ O(VAEncSequenceParameterBufferHEVC, pcm_sample_bit_depth_luma_minus1);
188+ O(VAEncSequenceParameterBufferHEVC, vui_parameters_present_flag);
189+ O(VAEncSequenceParameterBufferHEVC, vui_fields);
190+ O(VAEncSequenceParameterBufferHEVC, aspect_ratio_idc);
191+ O(VAEncSequenceParameterBufferHEVC, vui_num_units_in_tick);
192+ O(VAEncSequenceParameterBufferHEVC, min_spatial_segmentation_idc);
193+ O(VAEncSequenceParameterBufferHEVC, scc_fields);
194+
195+ S(VAEncPictureParameterBufferHEVC);
196+ O(VAEncPictureParameterBufferHEVC, reference_frames);
197+ O(VAEncPictureParameterBufferHEVC, coded_buf);
198+ O(VAEncPictureParameterBufferHEVC, collocated_ref_pic_index);
199+ O(VAEncPictureParameterBufferHEVC, column_width_minus1);
200+ O(VAEncPictureParameterBufferHEVC, row_height_minus1);
201+ O(VAEncPictureParameterBufferHEVC, log2_parallel_merge_level_minus2);
202+ O(VAEncPictureParameterBufferHEVC, nal_unit_type);
203+ O(VAEncPictureParameterBufferHEVC, pic_fields);
204+ O(VAEncPictureParameterBufferHEVC, hierarchical_level_plus1);
205+ O(VAEncPictureParameterBufferHEVC, scc_fields);
206+
207+ S(VAEncSliceParameterBufferHEVC);
208+ O(VAEncSliceParameterBufferHEVC, num_ctu_in_slice);
209+ O(VAEncSliceParameterBufferHEVC, slice_type);
210+ O(VAEncSliceParameterBufferHEVC, ref_pic_list0);
211+ O(VAEncSliceParameterBufferHEVC, ref_pic_list1);
212+ O(VAEncSliceParameterBufferHEVC, luma_log2_weight_denom);
213+ O(VAEncSliceParameterBufferHEVC, max_num_merge_cand);
214+ O(VAEncSliceParameterBufferHEVC, slice_fields);
215+ O(VAEncSliceParameterBufferHEVC, pred_weight_table_bit_offset);
216+
217+ S(VAEncSequenceParameterBufferAV1);
218+ O(VAEncSequenceParameterBufferAV1, intra_period);
219+ O(VAEncSequenceParameterBufferAV1, seq_fields);
220+ O(VAEncSequenceParameterBufferAV1, order_hint_bits_minus_1);
221+ S(VAEncSegParamAV1);
222+ O(VAEncSegParamAV1, feature_data);
223+ O(VAEncSegParamAV1, feature_mask);
224+ S(VAEncWarpedMotionParamsAV1);
225+ S(VAEncPictureParameterBufferAV1);
226+ O(VAEncPictureParameterBufferAV1, reconstructed_frame);
227+ O(VAEncPictureParameterBufferAV1, coded_buf);
228+ O(VAEncPictureParameterBufferAV1, reference_frames);
229+ O(VAEncPictureParameterBufferAV1, ref_frame_idx);
230+ O(VAEncPictureParameterBufferAV1, ref_frame_ctrl_l0);
231+ O(VAEncPictureParameterBufferAV1, picture_flags);
232+ O(VAEncPictureParameterBufferAV1, seg_id_block_size);
233+ O(VAEncPictureParameterBufferAV1, filter_level);
234+ O(VAEncPictureParameterBufferAV1, loop_filter_flags);
235+ O(VAEncPictureParameterBufferAV1, ref_deltas);
236+ O(VAEncPictureParameterBufferAV1, base_qindex);
237+ O(VAEncPictureParameterBufferAV1, min_base_qindex);
238+ O(VAEncPictureParameterBufferAV1, qmatrix_flags);
239+ O(VAEncPictureParameterBufferAV1, mode_control_flags);
240+ O(VAEncPictureParameterBufferAV1, segments);
241+ O(VAEncPictureParameterBufferAV1, tile_cols);
242+ O(VAEncPictureParameterBufferAV1, width_in_sbs_minus_1);
243+ O(VAEncPictureParameterBufferAV1, context_update_tile_id);
244+ O(VAEncPictureParameterBufferAV1, cdef_damping_minus_3);
245+ O(VAEncPictureParameterBufferAV1, loop_restoration_flags);
246+ O(VAEncPictureParameterBufferAV1, wm);
247+ O(VAEncPictureParameterBufferAV1, bit_offset_qindex);
248+ O(VAEncPictureParameterBufferAV1, tile_group_obu_hdr_info);
249+ O(VAEncPictureParameterBufferAV1, number_skip_frames);
250+ O(VAEncPictureParameterBufferAV1, skip_frames_reduced_size);
251+ S(VAEncTileGroupBufferAV1);
252+
253+ S(VAEncMiscParameterRateControl);
254+ O(VAEncMiscParameterRateControl, rc_flags);
255+ O(VAEncMiscParameterRateControl, ICQ_quality_factor);
256+ O(VAEncMiscParameterRateControl, max_qp);
257+ S(VAEncMiscParameterFrameRate);
258+ O(VAEncMiscParameterFrameRate, framerate_flags);
259+ S(VAEncMiscParameterHRD);
260+ O(VAEncMiscParameterHRD, buffer_size);
261+ S(VAEncMiscParameterBufferQualityLevel);
262+ S(VAEncPackedHeaderParameterBuffer);
263+ O(VAEncPackedHeaderParameterBuffer, bit_length);
264+ O(VAEncPackedHeaderParameterBuffer, has_emulation_bytes);
265+ S(VACodedBufferSegment);
266+ O(VACodedBufferSegment, bit_offset);
267+ O(VACodedBufferSegment, status);
268+ O(VACodedBufferSegment, buf);
269+ O(VACodedBufferSegment, next);
270+ return 0;
271+}
crates/ec-hw/src/error.rsadded+89 -0
@@ -0,0 +1,89 @@
1+//! Typed errors. Nothing in this crate panics on a driver or bitstream fault.
2+//!
3+//! That is a hard requirement rather than a style preference: edith loads the
4+//! VA-API path as a `dlopen`ed plugin behind `catch_unwind`, and its
5+//! fall-back-to-software guarantee is only as good as this crate's promise to
6+//! return instead of unwinding. Every `VAStatus` becomes an [`Error::Va`],
7+//! every malformed bitstream an [`Error::Stream`], and every capability this
8+//! GPU does not have an [`Error::Unsupported`] naming what and why.
9+
10+use std::fmt;
11+
12+/// Result alias for this crate.
13+pub type Result<T> = std::result::Result<T, Error>;
14+
15+/// Everything that can go wrong on the hardware path.
16+#[derive(Debug)]
17+#[non_exhaustive]
18+pub enum Error {
19+ /// A libva call failed, or the driver contradicted its own API.
20+ Va(ec_va::Error),
21+ /// The bitstream could not be parsed.
22+ Stream(ec_core::Error),
23+ /// A capability this GPU or this build genuinely does not have.
24+ Unsupported {
25+ /// What was asked for, e.g. `"VP9 Profile 1 decode"`.
26+ what: String,
27+ /// Why it cannot be served, e.g. `"driver reports no VLD entrypoint"`.
28+ why: String,
29+ },
30+ /// The caller asked for something inconsistent, e.g. feeding H.264 to a
31+ /// decoder configured for AV1, or encoding a frame of the wrong size.
32+ Config(String),
33+}
34+
35+impl Error {
36+ /// Build an [`Error::Unsupported`].
37+ pub fn unsupported(what: impl Into<String>, why: impl Into<String>) -> Error {
38+ Error::Unsupported {
39+ what: what.into(),
40+ why: why.into(),
41+ }
42+ }
43+
44+ /// Build an [`Error::Config`].
45+ pub fn config(what: impl Into<String>) -> Error {
46+ Error::Config(what.into())
47+ }
48+
49+ /// The raw `VAStatus`, when this came from a libva call.
50+ pub fn va_status(&self) -> Option<i32> {
51+ match self {
52+ Error::Va(e) => e.status(),
53+ _ => None,
54+ }
55+ }
56+}
57+
58+impl From<ec_va::Error> for Error {
59+ fn from(e: ec_va::Error) -> Error {
60+ Error::Va(e)
61+ }
62+}
63+
64+impl From<ec_core::Error> for Error {
65+ fn from(e: ec_core::Error) -> Error {
66+ Error::Stream(e)
67+ }
68+}
69+
70+impl fmt::Display for Error {
71+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72+ match self {
73+ Error::Va(e) => write!(f, "VA-API: {e}"),
74+ Error::Stream(e) => write!(f, "bitstream: {e}"),
75+ Error::Unsupported { what, why } => write!(f, "{what} is not supported: {why}"),
76+ Error::Config(what) => write!(f, "{what}"),
77+ }
78+ }
79+}
80+
81+impl std::error::Error for Error {
82+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
83+ match self {
84+ Error::Va(e) => Some(e),
85+ Error::Stream(e) => Some(e),
86+ _ => None,
87+ }
88+ }
89+}
crates/ec-hw/src/frame.rsadded+413 -0
@@ -0,0 +1,413 @@
1+//! Decoded frames: what comes out of a decoder, and the two ways to get at the
2+//! pixels — DRM PRIME export (zero copy) and mapped readback.
3+
4+use std::sync::{Arc, Mutex};
5+
6+use ec_va::sys::{VA_FOURCC_NV12, VA_FOURCC_P010};
7+use ec_va::{Image, MappedImage, PrimeSurface, Surface};
8+
9+use crate::error::{Error, Result};
10+use crate::pool::PooledSurface;
11+
12+/// The readback image a decoder reuses across frames.
13+///
14+/// One `vaCreateImage`/`vaDestroyImage` pair per frame costs ~20 ms at 1080p on
15+/// this driver — more than the decode — because each one allocates and frees a
16+/// 3 MB driver buffer. The image is therefore created once per stream and kept
17+/// here, shared by every frame that stream produces.
18+pub(crate) type ImageCache = Arc<Mutex<Option<Image>>>;
19+
20+/// One decoded picture, in display order.
21+///
22+/// Holding a frame holds its surface out of the decoder's pool, so a consumer
23+/// that keeps every frame will starve the decoder — by design: that is the back
24+/// pressure a zero-copy pipeline needs.
25+pub struct Frame {
26+ surface: Arc<PooledSurface>,
27+ images: ImageCache,
28+ /// Presentation timestamp carried through from the access unit.
29+ pub timestamp: i64,
30+ /// Size the picture is displayed at, after cropping.
31+ pub display_size: (u32, u32),
32+ /// Size the picture is coded at (a multiple of the codec's block size).
33+ pub coded_size: (u32, u32),
34+ /// Luma bit depth: 8 for NV12 surfaces, 10 for P010.
35+ pub bit_depth: u8,
36+}
37+
38+/// 8-bit planar 4:2:0, the currency edith's software path speaks.
39+#[derive(Debug, Clone, PartialEq, Eq)]
40+pub struct I420 {
41+ /// Luma plane, `width * height`.
42+ pub y: Vec<u8>,
43+ /// Cb plane, `(width + 1) / 2 * ((height + 1) / 2)`.
44+ pub u: Vec<u8>,
45+ /// Cr plane, same size as `u`.
46+ pub v: Vec<u8>,
47+ /// Width in luma samples.
48+ pub width: u32,
49+ /// Height in luma samples.
50+ pub height: u32,
51+}
52+
53+/// 10-bit planar 4:2:0, samples right-aligned in the low 10 bits.
54+#[derive(Debug, Clone, PartialEq, Eq)]
55+pub struct I420_16 {
56+ /// Luma plane.
57+ pub y: Vec<u16>,
58+ /// Cb plane.
59+ pub u: Vec<u16>,
60+ /// Cr plane.
61+ pub v: Vec<u16>,
62+ /// Width in luma samples.
63+ pub width: u32,
64+ /// Height in luma samples.
65+ pub height: u32,
66+}
67+
68+impl Frame {
69+ pub(crate) fn new(
70+ surface: Arc<PooledSurface>,
71+ images: ImageCache,
72+ timestamp: i64,
73+ display_size: (u32, u32),
74+ coded_size: (u32, u32),
75+ bit_depth: u8,
76+ ) -> Frame {
77+ Frame {
78+ surface,
79+ images,
80+ timestamp,
81+ display_size,
82+ coded_size,
83+ bit_depth,
84+ }
85+ }
86+
87+ /// The surface this frame lives on.
88+ pub fn surface(&self) -> &Arc<Surface> {
89+ &self.surface
90+ }
91+
92+ /// Export the surface as DRM PRIME file descriptors.
93+ ///
94+ /// This is the path edith's `engine-hw` takes: the fds are imported into
95+ /// gbm on the other side, so no pixel ever crosses the PCIe bus. The frame
96+ /// is synchronised first, because an exported fd carries no fence.
97+ pub fn export_prime(&self) -> Result<PrimeSurface> {
98+ self.surface.sync()?;
99+ Ok(self
100+ .surface
101+ .export_prime(ec_va::sys::VA_EXPORT_SURFACE_READ_ONLY)?)
102+ }
103+
104+ /// Read the frame back as 8-bit I420, truncating a 10-bit surface.
105+ ///
106+ /// Truncation is what the `vh_*` C ABI takes today (one byte per sample);
107+ /// [`Frame::to_i420_16`] is the lossless path for a caller that wants the
108+ /// ten bits.
109+ pub fn to_i420(&self) -> Result<I420> {
110+ let (w, h) = self.display_size;
111+ let (cw, ch) = ((w as usize).div_ceil(2), (h as usize).div_ceil(2));
112+ let (w, h) = (w as usize, h as usize);
113+ let mut out = I420 {
114+ y: vec![0; w * h],
115+ u: vec![0; cw * ch],
116+ v: vec![0; cw * ch],
117+ width: self.display_size.0,
118+ height: self.display_size.1,
119+ };
120+
121+ self.with_planes(|mapped| {
122+ let y_pitch = mapped.pitch(0).unwrap_or(0) as usize;
123+ let uv_pitch = mapped.pitch(1).unwrap_or(0) as usize;
124+ let y_plane = mapped
125+ .plane(0)
126+ .ok_or_else(|| Error::config("VA image has no luma plane"))?;
127+ let uv_plane = mapped
128+ .plane(1)
129+ .ok_or_else(|| Error::config("VA image has no chroma plane"))?;
130+
131+ // Mapped VA memory is uncached (write-combining on this driver), where a
132+ // byte-at-a-time read runs at a few hundred MB/s. Every plane is
133+ // therefore pulled out one whole row at a time with `copy_from_slice`
134+ // and unpacked from ordinary memory afterwards: same result, 10x the
135+ // throughput (27 ms -> 2.6 ms per 1080p frame, measured).
136+ let mut row_buf = vec![0u8; (uv_pitch.max(y_pitch)).max(w * 2)];
137+ match self.bit_depth {
138+ 8 => {
139+ for row in 0..h {
140+ let src = row * y_pitch;
141+ out.y[row * w..(row + 1) * w].copy_from_slice(&y_plane[src..src + w]);
142+ }
143+ for row in 0..ch {
144+ let src = row * uv_pitch;
145+ let line = &mut row_buf[..cw * 2];
146+ line.copy_from_slice(&uv_plane[src..src + cw * 2]);
147+ for col in 0..cw {
148+ out.u[row * cw + col] = line[col * 2];
149+ out.v[row * cw + col] = line[col * 2 + 1];
150+ }
151+ }
152+ }
153+ _ => {
154+ // P010 keeps the sample in the *high* bits of each u16, so the
155+ // 8-bit value is the high byte — a shift by 8, not by 2.
156+ for row in 0..h {
157+ let src = row * y_pitch;
158+ let line = &mut row_buf[..w * 2];
159+ line.copy_from_slice(&y_plane[src..src + w * 2]);
160+ for col in 0..w {
161+ out.y[row * w + col] = line[col * 2 + 1];
162+ }
163+ }
164+ for row in 0..ch {
165+ let src = row * uv_pitch;
166+ let line = &mut row_buf[..cw * 4];
167+ line.copy_from_slice(&uv_plane[src..src + cw * 4]);
168+ for col in 0..cw {
169+ out.u[row * cw + col] = line[col * 4 + 1];
170+ out.v[row * cw + col] = line[col * 4 + 3];
171+ }
172+ }
173+ }
174+ }
175+ Ok(out)
176+ })
177+ }
178+
179+ /// Read the frame back as 10-bit I420 (samples in the low 10 bits).
180+ ///
181+ /// An 8-bit surface is widened rather than refused, so a caller can hold
182+ /// one frame type across a mixed-depth timeline.
183+ pub fn to_i420_16(&self) -> Result<I420_16> {
184+ let (w, h) = self.display_size;
185+ let (cw, ch) = ((w as usize).div_ceil(2), (h as usize).div_ceil(2));
186+ let (w, h) = (w as usize, h as usize);
187+ let mut out = I420_16 {
188+ y: vec![0; w * h],
189+ u: vec![0; cw * ch],
190+ v: vec![0; cw * ch],
191+ width: self.display_size.0,
192+ height: self.display_size.1,
193+ };
194+
195+ self.with_planes(|mapped| {
196+ let y_pitch = mapped.pitch(0).unwrap_or(0) as usize;
197+ let uv_pitch = mapped.pitch(1).unwrap_or(0) as usize;
198+ let y_plane = mapped
199+ .plane(0)
200+ .ok_or_else(|| Error::config("VA image has no luma plane"))?;
201+ let uv_plane = mapped
202+ .plane(1)
203+ .ok_or_else(|| Error::config("VA image has no chroma plane"))?;
204+
205+ // Row at a time, for the reason given in `to_i420`.
206+ let mut row_buf = vec![0u8; (uv_pitch.max(y_pitch)).max(w * 2)];
207+ match self.bit_depth {
208+ 8 => {
209+ for row in 0..h {
210+ let src = row * y_pitch;
211+ row_buf[..w].copy_from_slice(&y_plane[src..src + w]);
212+ for (dst, &sample) in
213+ out.y[row * w..(row + 1) * w].iter_mut().zip(&row_buf[..w])
214+ {
215+ *dst = u16::from(sample) << 2;
216+ }
217+ }
218+ for row in 0..ch {
219+ let src = row * uv_pitch;
220+ let line = &mut row_buf[..cw * 2];
221+ line.copy_from_slice(&uv_plane[src..src + cw * 2]);
222+ for col in 0..cw {
223+ out.u[row * cw + col] = u16::from(line[col * 2]) << 2;
224+ out.v[row * cw + col] = u16::from(line[col * 2 + 1]) << 2;
225+ }
226+ }
227+ }
228+ _ => {
229+ // P010 is 16-bit little endian with the sample in the top ten
230+ // bits; the low six are zero padding.
231+ for row in 0..h {
232+ let src = row * y_pitch;
233+ let line = &mut row_buf[..w * 2];
234+ line.copy_from_slice(&y_plane[src..src + w * 2]);
235+ for col in 0..w {
236+ out.y[row * w + col] =
237+ u16::from_le_bytes([line[col * 2], line[col * 2 + 1]]) >> 6;
238+ }
239+ }
240+ for row in 0..ch {
241+ let src = row * uv_pitch;
242+ let line = &mut row_buf[..cw * 4];
243+ line.copy_from_slice(&uv_plane[src..src + cw * 4]);
244+ for col in 0..cw {
245+ out.u[row * cw + col] =
246+ u16::from_le_bytes([line[col * 4], line[col * 4 + 1]]) >> 6;
247+ out.v[row * cw + col] =
248+ u16::from_le_bytes([line[col * 4 + 2], line[col * 4 + 3]]) >> 6;
249+ }
250+ }
251+ }
252+ }
253+ Ok(out)
254+ })
255+ }
256+
257+ /// Map the surface's pixels and hand the planes to `read`.
258+ ///
259+ /// `vaGetImage` into an image kept for the life of the stream, *not*
260+ /// `vaDeriveImage`. Deriving looks cheaper — it is a view rather than a
261+ /// copy — and it does return the same pixels here (checked row for row),
262+ /// but the view is device memory across the PCIe bar: reading a 1080p frame
263+ /// through it costs 48 ms against 10 ms for a driver-side copy into system
264+ /// memory followed by a normal read (measured, 719-frame loop).
265+ fn with_planes<R>(&self, read: impl FnOnce(&MappedImage<'_>) -> Result<R>) -> Result<R> {
266+ self.surface.sync()?;
267+ let fourcc = if self.bit_depth > 8 {
268+ VA_FOURCC_P010
269+ } else {
270+ VA_FOURCC_NV12
271+ };
272+ let (w, h) = self.coded_size;
273+
274+ let mut slot = match self.images.lock() {
275+ Ok(slot) => slot,
276+ // The lock guards a cached image, not an invariant: a panicking
277+ // reader leaves it perfectly usable.
278+ Err(poisoned) => poisoned.into_inner(),
279+ };
280+ let reusable = slot
281+ .as_ref()
282+ .is_some_and(|image| image.fourcc() == fourcc && image.size() == (w, h));
283+ if !reusable {
284+ *slot = Some(Image::create(self.surface.display(), fourcc, w, h)?);
285+ }
286+ let image = slot
287+ .as_mut()
288+ .ok_or_else(|| Error::config("no readback image"))?;
289+ self.surface.read_into(image, 0, 0, w, h)?;
290+ let mapped = image.map()?;
291+ read(&mapped)
292+ }
293+}
294+
295+impl std::fmt::Debug for Frame {
296+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
297+ f.debug_struct("Frame")
298+ .field("surface", &self.surface.id())
299+ .field("timestamp", &self.timestamp)
300+ .field("display_size", &self.display_size)
301+ .field("bit_depth", &self.bit_depth)
302+ .finish()
303+ }
304+}
305+
306+/// Deinterleave an NV12 chroma plane into I420 U and V planes.
307+///
308+/// Parity with `cros-codecs`' `image_processing::nv12_to_i420`, which is what
309+/// edith calls today; kept as a free function because the conversion is also
310+/// what an encoder input path needs, in reverse.
311+pub fn nv12_to_i420(
312+ y_plane: &[u8],
313+ y_pitch: usize,
314+ uv_plane: &[u8],
315+ uv_pitch: usize,
316+ width: usize,
317+ height: usize,
318+) -> I420 {
319+ let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
320+ let mut out = I420 {
321+ y: vec![0; width * height],
322+ u: vec![0; cw * ch],
323+ v: vec![0; cw * ch],
324+ width: width as u32,
325+ height: height as u32,
326+ };
327+ for row in 0..height {
328+ let src = row * y_pitch;
329+ if src + width > y_plane.len() {
330+ break;
331+ }
332+ out.y[row * width..(row + 1) * width].copy_from_slice(&y_plane[src..src + width]);
333+ }
334+ for row in 0..ch {
335+ let src = row * uv_pitch;
336+ if src + cw * 2 > uv_plane.len() {
337+ break;
338+ }
339+ for col in 0..cw {
340+ out.u[row * cw + col] = uv_plane[src + col * 2];
341+ out.v[row * cw + col] = uv_plane[src + col * 2 + 1];
342+ }
343+ }
344+ out
345+}
346+
347+/// Interleave I420 chroma into an NV12 buffer, for the encoder input path.
348+pub fn i420_to_nv12(
349+ src: &I420,
350+ y_out: &mut [u8],
351+ y_pitch: usize,
352+ uv_out: &mut [u8],
353+ uv_pitch: usize,
354+) {
355+ let (w, h) = (src.width as usize, src.height as usize);
356+ let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
357+ for row in 0..h {
358+ let dst = row * y_pitch;
359+ if dst + w > y_out.len() {
360+ break;
361+ }
362+ y_out[dst..dst + w].copy_from_slice(&src.y[row * w..row * w + w]);
363+ }
364+ for row in 0..ch {
365+ let dst = row * uv_pitch;
366+ if dst + cw * 2 > uv_out.len() {
367+ break;
368+ }
369+ for col in 0..cw {
370+ uv_out[dst + col * 2] = src.u[row * cw + col];
371+ uv_out[dst + col * 2 + 1] = src.v[row * cw + col];
372+ }
373+ }
374+}
375+
376+#[cfg(test)]
377+mod tests {
378+ use super::*;
379+
380+ #[test]
381+ fn nv12_round_trips_through_i420() {
382+ let (w, h) = (6usize, 4usize);
383+ let (y_pitch, uv_pitch) = (8usize, 8usize);
384+ let mut y = vec![0u8; y_pitch * h];
385+ let mut uv = vec![0u8; uv_pitch * h / 2];
386+ for row in 0..h {
387+ for col in 0..w {
388+ y[row * y_pitch + col] = (row * w + col) as u8;
389+ }
390+ }
391+ for row in 0..h / 2 {
392+ for col in 0..w {
393+ uv[row * uv_pitch + col] = (100 + row * w + col) as u8;
394+ }
395+ }
396+
397+ let i420 = nv12_to_i420(&y, y_pitch, &uv, uv_pitch, w, h);
398+ assert_eq!(i420.y.len(), w * h);
399+ assert_eq!(i420.u.len(), (w / 2) * (h / 2));
400+ assert_eq!(i420.y[0], 0);
401+ assert_eq!(i420.y[w], w as u8);
402+ // U takes the even bytes of the interleaved plane, V the odd ones.
403+ assert_eq!(i420.u[0], 100);
404+ assert_eq!(i420.v[0], 101);
405+ assert_eq!(i420.u[1], 102);
406+
407+ let mut y2 = vec![0u8; y_pitch * h];
408+ let mut uv2 = vec![0u8; uv_pitch * h / 2];
409+ i420_to_nv12(&i420, &mut y2, y_pitch, &mut uv2, uv_pitch);
410+ let back = nv12_to_i420(&y2, y_pitch, &uv2, uv_pitch, w, h);
411+ assert_eq!(back, i420);
412+ }
413+}
crates/ec-hw/src/lib.rsadded+60 -0
@@ -0,0 +1,60 @@
1+//! Stateless VA-API video decoding and encoding.
2+//!
3+//! "Stateless" is the VA-API decode model, not a description of this crate: the
4+//! driver decodes one picture at a time and knows nothing between pictures, so
5+//! everything a codec spreads across frames — the decoded picture buffer,
6+//! reference lists, picture order counts, reference slot updates — is kept
7+//! here, in Rust, and handed to the driver per picture. That is the whole job.
8+//!
9+//! ```no_run
10+//! use ec_hw::{Codec, Decoder};
11+//!
12+//! let display = ec_va::Display::open()?;
13+//! let mut decoder = Decoder::new(&display, Codec::H264)?;
14+//! decoder.decode(annex_b_access_unit, 0)?;
15+//! while let Some(frame) = decoder.next_frame() {
16+//! let planes = frame.to_i420()?; // or frame.export_prime() for zero copy
17+//! }
18+//! # Ok::<(), ec_hw::Error>(())
19+//! # fn annex_b_access_unit() -> &'static [u8] { &[] }
20+//! ```
21+//!
22+//! # Shape
23+//!
24+//! * [`params`] — the `#[repr(C)]` codec parameter buffers, each checked
25+//! against the system headers by a `const` assertion.
26+//! * [`dec`] — one stateless decoder per codec behind [`Decoder`].
27+//! * [`enc`] — H.264 and HEVC encoders, and an opt-in AV1 one.
28+//! * [`SurfacePool`] / [`Frame`] — surface recycling and pixel access.
29+//!
30+//! # Unsafe
31+//!
32+//! This crate is not `forbid(unsafe_code)`: handing a parameter struct to the
33+//! driver and walking a coded-buffer segment list are both pointer work that
34+//! `ec-va` cannot type for us. Both are confined to two functions —
35+//! [`params::param_buffer`] and `enc::coded_bytes` — and everything else,
36+//! including every codec's parameter derivation, is safe Rust.
37+//!
38+//! # Panics
39+//!
40+//! None by contract. Every driver and bitstream fault is an [`Error`], because
41+//! edith loads this path as a `dlopen`ed plugin whose fall back to software is
42+//! only as good as that promise.
43+
44+#![deny(missing_docs)]
45+#![deny(unsafe_op_in_unsafe_fn)]
46+
47+pub mod dec;
48+pub mod enc;
49+pub mod error;
50+pub mod frame;
51+pub mod params;
52+pub mod pool;
53+
54+pub use dec::{Codec, Decoder, StreamInfo};
55+pub use enc::{
56+ CodedFrame, EncCodec, Encoder, EncoderConfig, FrameMetadata, RateControlMode, Tunings,
57+};
58+pub use error::{Error, Result};
59+pub use frame::{Frame, I420, I420_16, i420_to_nv12, nv12_to_i420};
60+pub use pool::{PooledSurface, SurfacePool};
crates/ec-hw/src/params/av1.rsadded+480 -0
@@ -0,0 +1,480 @@
1+//! AV1 decode parameter buffers (`va_dec_av1.h`).
2+
3+use std::ffi::c_void;
4+
5+use ec_va::sys::{VAPictureParameterBufferType, VASliceParameterBufferType, VASurfaceID};
6+
7+use super::{INVALID_SURFACE, VaParam};
8+use crate::va_bits;
9+
10+va_bits! {
11+ /// `VASegmentationStructAV1::segment_info_fields`.
12+ SegmentInfoFields: u32 {
13+ enabled: 1,
14+ update_map: 1,
15+ temporal_update: 1,
16+ update_data: 1,
17+ }
18+}
19+
20+/// `VASegmentationStructAV1`, `va_dec_av1.h:65`.
21+#[repr(C)]
22+#[derive(Debug, Clone, Copy, Default)]
23+pub struct SegmentationStructAV1 {
24+ /// Segmentation flags.
25+ pub segment_info_fields: SegmentInfoFields,
26+ /// `FeatureData[segment][feature]`.
27+ pub feature_data: [[i16; 8]; 8],
28+ /// `FeatureEnabled[segment]` as a bitmask over features.
29+ pub feature_mask: [u8; 8],
30+ pub(crate) va_reserved: [u32; 4],
31+}
32+
33+va_bits! {
34+ /// `VAFilmGrainStructAV1::film_grain_info_fields`.
35+ FilmGrainInfoFields: u32 {
36+ apply_grain: 1,
37+ chroma_scaling_from_luma: 1,
38+ grain_scaling_minus_8: 2,
39+ ar_coeff_lag: 2,
40+ ar_coeff_shift_minus_6: 2,
41+ grain_scale_shift: 2,
42+ overlap_flag: 1,
43+ clip_to_restricted_range: 1,
44+ }
45+}
46+
47+/// `VAFilmGrainStructAV1`, `va_dec_av1.h:100`.
48+///
49+/// Film grain synthesis is a display-side effect; the decoder fills this so a
50+/// driver that applies grain can, and edith's own path leaves `apply_grain`
51+/// clear (the frame it wants is the ungrained reconstruction).
52+#[repr(C)]
53+#[derive(Debug, Clone, Copy, Default)]
54+pub struct FilmGrainStructAV1 {
55+ /// Film grain flags.
56+ pub film_grain_info_fields: FilmGrainInfoFields,
57+ /// `grain_seed`.
58+ pub grain_seed: u16,
59+ /// `num_y_points`.
60+ pub num_y_points: u8,
61+ /// `point_y_value`.
62+ pub point_y_value: [u8; 14],
63+ /// `point_y_scaling`.
64+ pub point_y_scaling: [u8; 14],
65+ /// `num_cb_points`.
66+ pub num_cb_points: u8,
67+ /// `point_cb_value`.
68+ pub point_cb_value: [u8; 10],
69+ /// `point_cb_scaling`.
70+ pub point_cb_scaling: [u8; 10],
71+ /// `num_cr_points`.
72+ pub num_cr_points: u8,
73+ /// `point_cr_value`.
74+ pub point_cr_value: [u8; 10],
75+ /// `point_cr_scaling`.
76+ pub point_cr_scaling: [u8; 10],
77+ /// `ar_coeffs_y_plus_128 - 128`.
78+ pub ar_coeffs_y: [i8; 24],
79+ /// `ar_coeffs_cb_plus_128 - 128`.
80+ pub ar_coeffs_cb: [i8; 25],
81+ /// `ar_coeffs_cr_plus_128 - 128`.
82+ pub ar_coeffs_cr: [i8; 25],
83+ /// `cb_mult`.
84+ pub cb_mult: u8,
85+ /// `cb_luma_mult`.
86+ pub cb_luma_mult: u8,
87+ /// `cb_offset`.
88+ pub cb_offset: u16,
89+ /// `cr_mult`.
90+ pub cr_mult: u8,
91+ /// `cr_luma_mult`.
92+ pub cr_luma_mult: u8,
93+ /// `cr_offset`.
94+ pub cr_offset: u16,
95+ pub(crate) va_reserved: [u32; 4],
96+}
97+
98+/// `VAWarpedMotionParamsAV1`, `va_dec_av1.h:180`.
99+#[repr(C)]
100+#[derive(Debug, Clone, Copy, Default)]
101+pub struct WarpedMotionParamsAV1 {
102+ /// `VAAV1Transformation*`: identity, translation, rotzoom or affine.
103+ pub wmtype: i32,
104+ /// `gm_params`, six meaningful entries.
105+ pub wmmat: [i32; 8],
106+ /// Set when the model was rejected as non-invertible.
107+ pub invalid: u8,
108+ pub(crate) va_reserved: [u32; 4],
109+}
110+
111+va_bits! {
112+ /// `VADecPictureParameterBufferAV1::seq_info_fields`.
113+ SeqInfoFields: u32 {
114+ still_picture: 1,
115+ use_128x128_superblock: 1,
116+ enable_filter_intra: 1,
117+ enable_intra_edge_filter: 1,
118+ enable_interintra_compound: 1,
119+ enable_masked_compound: 1,
120+ enable_dual_filter: 1,
121+ enable_order_hint: 1,
122+ enable_jnt_comp: 1,
123+ enable_cdef: 1,
124+ mono_chrome: 1,
125+ color_range: 1,
126+ subsampling_x: 1,
127+ subsampling_y: 1,
128+ chroma_sample_position: 1,
129+ film_grain_params_present: 1,
130+ }
131+}
132+
133+va_bits! {
134+ /// `VADecPictureParameterBufferAV1::pic_info_fields`.
135+ PicInfoFields: u32 {
136+ frame_type: 2,
137+ show_frame: 1,
138+ showable_frame: 1,
139+ error_resilient_mode: 1,
140+ disable_cdf_update: 1,
141+ allow_screen_content_tools: 1,
142+ force_integer_mv: 1,
143+ allow_intrabc: 1,
144+ use_superres: 1,
145+ allow_high_precision_mv: 1,
146+ is_motion_mode_switchable: 1,
147+ use_ref_frame_mvs: 1,
148+ disable_frame_end_update_cdf: 1,
149+ uniform_tile_spacing_flag: 1,
150+ allow_warped_motion: 1,
151+ large_scale_tile: 1,
152+ }
153+}
154+
155+va_bits! {
156+ /// `VADecPictureParameterBufferAV1::loop_filter_info_fields`.
157+ LoopFilterInfoFields: u8 {
158+ sharpness_level: 3,
159+ mode_ref_delta_enabled: 1,
160+ mode_ref_delta_update: 1,
161+ }
162+}
163+
164+va_bits! {
165+ /// `VADecPictureParameterBufferAV1::qmatrix_fields`.
166+ QMatrixFields: u16 {
167+ using_qmatrix: 1,
168+ qm_y: 4,
169+ qm_u: 4,
170+ qm_v: 4,
171+ }
172+}
173+
174+va_bits! {
175+ /// `VADecPictureParameterBufferAV1::mode_control_fields`.
176+ ModeControlFields: u32 {
177+ delta_q_present_flag: 1,
178+ log2_delta_q_res: 2,
179+ delta_lf_present_flag: 1,
180+ log2_delta_lf_res: 2,
181+ delta_lf_multi: 1,
182+ tx_mode: 2,
183+ reference_select: 1,
184+ reduced_tx_set_used: 1,
185+ skip_mode_present: 1,
186+ }
187+}
188+
189+va_bits! {
190+ /// `VADecPictureParameterBufferAV1::loop_restoration_fields`.
191+ LoopRestorationFields: u16 {
192+ yframe_restoration_type: 2,
193+ cbframe_restoration_type: 2,
194+ crframe_restoration_type: 2,
195+ lr_unit_shift: 2,
196+ lr_uv_shift: 1,
197+ }
198+}
199+
200+/// `VADecPictureParameterBufferAV1`, `va_dec_av1.h:206`.
201+#[repr(C)]
202+#[derive(Debug, Clone, Copy)]
203+pub struct PictureParameterBufferAV1 {
204+ /// `seq_profile`.
205+ pub profile: u8,
206+ /// `OrderHintBits - 1`.
207+ pub order_hint_bits_minus_1: u8,
208+ /// 0 for 8-bit, 1 for 10-bit, 2 for 12-bit.
209+ pub bit_depth_idx: u8,
210+ /// `matrix_coefficients` (H.273).
211+ pub matrix_coefficients: u8,
212+ /// Sequence header flags.
213+ pub seq_info_fields: SeqInfoFields,
214+ /// Surface being decoded into.
215+ pub current_frame: VASurfaceID,
216+ /// Surface to display for a `show_existing_frame`, else the current frame.
217+ pub current_display_picture: VASurfaceID,
218+ /// Large scale tile only; always zero here.
219+ pub anchor_frames_num: u8,
220+ /// Large scale tile only; always NULL here.
221+ pub anchor_frames_list: *mut c_void,
222+ /// `FrameWidth - 1`.
223+ pub frame_width_minus1: u16,
224+ /// `FrameHeight - 1`.
225+ pub frame_height_minus1: u16,
226+ /// Large scale tile only.
227+ pub output_frame_width_in_tiles_minus_1: u16,
228+ /// Large scale tile only.
229+ pub output_frame_height_in_tiles_minus_1: u16,
230+ /// The eight reference slots.
231+ pub ref_frame_map: [VASurfaceID; 8],
232+ /// `ref_frame_idx`, LAST through ALTREF.
233+ pub ref_frame_idx: [u8; 7],
234+ /// `primary_ref_frame`.
235+ pub primary_ref_frame: u8,
236+ /// `OrderHint`.
237+ pub order_hint: u8,
238+ /// Segmentation parameters.
239+ pub seg_info: SegmentationStructAV1,
240+ /// Film grain parameters.
241+ pub film_grain_info: FilmGrainStructAV1,
242+ /// `TileCols`.
243+ pub tile_cols: u8,
244+ /// `TileRows`.
245+ pub tile_rows: u8,
246+ /// Per-column widths in superblocks, minus one.
247+ pub width_in_sbs_minus_1: [u16; 63],
248+ /// Per-row heights in superblocks, minus one.
249+ pub height_in_sbs_minus_1: [u16; 63],
250+ /// `TileCols * TileRows - 1`.
251+ pub tile_count_minus_1: u16,
252+ /// `context_update_tile_id`.
253+ pub context_update_tile_id: u16,
254+ /// Frame header flags.
255+ pub pic_info_fields: PicInfoFields,
256+ /// `SuperresDenom`.
257+ pub superres_scale_denominator: u8,
258+ /// `interpolation_filter`.
259+ pub interp_filter: u8,
260+ /// `loop_filter_level[0..2]`.
261+ pub filter_level: [u8; 2],
262+ /// `loop_filter_level[2]`.
263+ pub filter_level_u: u8,
264+ /// `loop_filter_level[3]`.
265+ pub filter_level_v: u8,
266+ /// Loop filter flags.
267+ pub loop_filter_info_fields: LoopFilterInfoFields,
268+ /// `loop_filter_ref_deltas`.
269+ pub ref_deltas: [i8; 8],
270+ /// `loop_filter_mode_deltas`.
271+ pub mode_deltas: [i8; 2],
272+ /// `base_q_idx`.
273+ pub base_qindex: u8,
274+ /// `DeltaQYDc`.
275+ pub y_dc_delta_q: i8,
276+ /// `DeltaQUDc`.
277+ pub u_dc_delta_q: i8,
278+ /// `DeltaQUAc`.
279+ pub u_ac_delta_q: i8,
280+ /// `DeltaQVDc`.
281+ pub v_dc_delta_q: i8,
282+ /// `DeltaQVAc`.
283+ pub v_ac_delta_q: i8,
284+ /// Quantiser matrix flags.
285+ pub qmatrix_fields: QMatrixFields,
286+ /// Mode control flags.
287+ pub mode_control_fields: ModeControlFields,
288+ /// `CdefDamping - 3`.
289+ pub cdef_damping_minus_3: u8,
290+ /// `cdef_bits`.
291+ pub cdef_bits: u8,
292+ /// Combined luma primary/secondary strengths, as libva packs them.
293+ pub cdef_y_strengths: [u8; 8],
294+ /// Combined chroma primary/secondary strengths.
295+ pub cdef_uv_strengths: [u8; 8],
296+ /// Loop restoration flags.
297+ pub loop_restoration_fields: LoopRestorationFields,
298+ /// Global motion for LAST..ALTREF.
299+ pub wm: [WarpedMotionParamsAV1; 7],
300+ pub(crate) va_reserved: [u32; 8],
301+}
302+
303+impl Default for PictureParameterBufferAV1 {
304+ fn default() -> Self {
305+ PictureParameterBufferAV1 {
306+ profile: 0,
307+ order_hint_bits_minus_1: 0,
308+ bit_depth_idx: 0,
309+ matrix_coefficients: 2, // MC_UNSPECIFIED
310+ seq_info_fields: SeqInfoFields::default(),
311+ current_frame: INVALID_SURFACE,
312+ current_display_picture: INVALID_SURFACE,
313+ anchor_frames_num: 0,
314+ anchor_frames_list: std::ptr::null_mut(),
315+ frame_width_minus1: 0,
316+ frame_height_minus1: 0,
317+ output_frame_width_in_tiles_minus_1: 0,
318+ output_frame_height_in_tiles_minus_1: 0,
319+ ref_frame_map: [INVALID_SURFACE; 8],
320+ ref_frame_idx: [0; 7],
321+ primary_ref_frame: 0,
322+ order_hint: 0,
323+ seg_info: SegmentationStructAV1::default(),
324+ film_grain_info: FilmGrainStructAV1::default(),
325+ tile_cols: 1,
326+ tile_rows: 1,
327+ width_in_sbs_minus_1: [0; 63],
328+ height_in_sbs_minus_1: [0; 63],
329+ tile_count_minus_1: 0,
330+ context_update_tile_id: 0,
331+ pic_info_fields: PicInfoFields::default(),
332+ superres_scale_denominator: 8,
333+ interp_filter: 0,
334+ filter_level: [0; 2],
335+ filter_level_u: 0,
336+ filter_level_v: 0,
337+ loop_filter_info_fields: LoopFilterInfoFields::default(),
338+ ref_deltas: [0; 8],
339+ mode_deltas: [0; 2],
340+ base_qindex: 0,
341+ y_dc_delta_q: 0,
342+ u_dc_delta_q: 0,
343+ u_ac_delta_q: 0,
344+ v_dc_delta_q: 0,
345+ v_ac_delta_q: 0,
346+ qmatrix_fields: QMatrixFields::default(),
347+ mode_control_fields: ModeControlFields::default(),
348+ cdef_damping_minus_3: 0,
349+ cdef_bits: 0,
350+ cdef_y_strengths: [0; 8],
351+ cdef_uv_strengths: [0; 8],
352+ loop_restoration_fields: LoopRestorationFields::default(),
353+ wm: [WarpedMotionParamsAV1::default(); 7],
354+ va_reserved: [0; 8],
355+ }
356+ }
357+}
358+
359+// SAFETY: `#[repr(C)]` transcription of `VADecPictureParameterBufferAV1`,
360+// checked by the assertion block below. The one pointer field is the large
361+// scale tile anchor list, which this crate always leaves NULL (that mode is out
362+// of scope), so no dangling pointer can reach the driver.
363+unsafe impl VaParam for PictureParameterBufferAV1 {
364+ const TYPE: i32 = VAPictureParameterBufferType;
365+}
366+
367+/// `VASliceParameterBufferAV1`, `va_dec_av1.h:660` — one per tile.
368+#[repr(C)]
369+#[derive(Debug, Clone, Copy, Default)]
370+pub struct SliceParameterBufferAV1 {
371+ /// Bytes of tile data.
372+ pub slice_data_size: u32,
373+ /// Offset of the tile within the data buffer.
374+ pub slice_data_offset: u32,
375+ /// `VA_SLICE_DATA_FLAG_*`.
376+ pub slice_data_flag: u32,
377+ /// Tile row.
378+ pub tile_row: u16,
379+ /// Tile column.
380+ pub tile_column: u16,
381+ pub(crate) tg_start: u16,
382+ pub(crate) tg_end: u16,
383+ /// Large scale tile only.
384+ pub anchor_frame_idx: u8,
385+ /// Large scale tile only.
386+ pub tile_idx_in_tile_list: u16,
387+ pub(crate) va_reserved: [u32; 4],
388+}
389+
390+// SAFETY: as `PictureParameterBufferAV1`; integers only.
391+unsafe impl VaParam for SliceParameterBufferAV1 {
392+ const TYPE: i32 = VASliceParameterBufferType;
393+}
394+
395+// ---------------------------------------------------------------------------
396+// ABI transcription check — `crates/ec-hw/abi-probe.c`, libva 1.23.0, x86_64:
397+//
398+// VASegmentationStructAV1 size=156 align=4 feature_data=4
399+// feature_mask=132
400+// VAFilmGrainStructAV1 size=176 align=4 grain_seed=4
401+// ar_coeffs_y=77 cr_offset=158
402+// VAWarpedMotionParamsAV1 size=56 align=4 wmmat=4 invalid=36
403+// VADecPictureParameterBufferAV1 size=1160 align=8 seq_info_fields=4
404+// current_frame=8
405+// anchor_frames_num=16
406+// anchor_frames_list=24
407+// frame_width_minus1=32
408+// ref_frame_map=40
409+// ref_frame_idx=72
410+// seg_info=84
411+// film_grain_info=240
412+// tile_cols=416
413+// width_in_sbs_minus_1=418
414+// height_in_sbs_minus_1=544
415+// tile_count_minus_1=670
416+// pic_info_fields=676
417+// superres_scale_denominator=680
418+// loop_filter_info_fields=686
419+// ref_deltas=687 base_qindex=697
420+// qmatrix_fields=704
421+// mode_control_fields=708
422+// cdef_damping_minus_3=712
423+// cdef_y_strengths=714
424+// loop_restoration_fields=730
425+// wm=732
426+// VASliceParameterBufferAV1 size=40 align=4 tile_row=12
427+// anchor_frame_idx=20
428+// tile_idx_in_tile_list=22
429+const _: () = {
430+ use std::mem::{align_of, offset_of, size_of};
431+
432+ assert!(size_of::<SegmentationStructAV1>() == 156 && align_of::<SegmentationStructAV1>() == 4);
433+ assert!(offset_of!(SegmentationStructAV1, feature_data) == 4);
434+ assert!(offset_of!(SegmentationStructAV1, feature_mask) == 132);
435+
436+ assert!(size_of::<FilmGrainStructAV1>() == 176 && align_of::<FilmGrainStructAV1>() == 4);
437+ assert!(offset_of!(FilmGrainStructAV1, grain_seed) == 4);
438+ assert!(offset_of!(FilmGrainStructAV1, ar_coeffs_y) == 77);
439+ assert!(offset_of!(FilmGrainStructAV1, cr_offset) == 158);
440+
441+ assert!(size_of::<WarpedMotionParamsAV1>() == 56 && align_of::<WarpedMotionParamsAV1>() == 4);
442+ assert!(offset_of!(WarpedMotionParamsAV1, wmmat) == 4);
443+ assert!(offset_of!(WarpedMotionParamsAV1, invalid) == 36);
444+
445+ assert!(
446+ size_of::<PictureParameterBufferAV1>() == 1160
447+ && align_of::<PictureParameterBufferAV1>() == 8
448+ );
449+ assert!(offset_of!(PictureParameterBufferAV1, seq_info_fields) == 4);
450+ assert!(offset_of!(PictureParameterBufferAV1, current_frame) == 8);
451+ assert!(offset_of!(PictureParameterBufferAV1, anchor_frames_num) == 16);
452+ assert!(offset_of!(PictureParameterBufferAV1, anchor_frames_list) == 24);
453+ assert!(offset_of!(PictureParameterBufferAV1, frame_width_minus1) == 32);
454+ assert!(offset_of!(PictureParameterBufferAV1, ref_frame_map) == 40);
455+ assert!(offset_of!(PictureParameterBufferAV1, ref_frame_idx) == 72);
456+ assert!(offset_of!(PictureParameterBufferAV1, seg_info) == 84);
457+ assert!(offset_of!(PictureParameterBufferAV1, film_grain_info) == 240);
458+ assert!(offset_of!(PictureParameterBufferAV1, tile_cols) == 416);
459+ assert!(offset_of!(PictureParameterBufferAV1, width_in_sbs_minus_1) == 418);
460+ assert!(offset_of!(PictureParameterBufferAV1, height_in_sbs_minus_1) == 544);
461+ assert!(offset_of!(PictureParameterBufferAV1, tile_count_minus_1) == 670);
462+ assert!(offset_of!(PictureParameterBufferAV1, pic_info_fields) == 676);
463+ assert!(offset_of!(PictureParameterBufferAV1, superres_scale_denominator) == 680);
464+ assert!(offset_of!(PictureParameterBufferAV1, loop_filter_info_fields) == 686);
465+ assert!(offset_of!(PictureParameterBufferAV1, ref_deltas) == 687);
466+ assert!(offset_of!(PictureParameterBufferAV1, base_qindex) == 697);
467+ assert!(offset_of!(PictureParameterBufferAV1, qmatrix_fields) == 704);
468+ assert!(offset_of!(PictureParameterBufferAV1, mode_control_fields) == 708);
469+ assert!(offset_of!(PictureParameterBufferAV1, cdef_damping_minus_3) == 712);
470+ assert!(offset_of!(PictureParameterBufferAV1, cdef_y_strengths) == 714);
471+ assert!(offset_of!(PictureParameterBufferAV1, loop_restoration_fields) == 730);
472+ assert!(offset_of!(PictureParameterBufferAV1, wm) == 732);
473+
474+ assert!(
475+ size_of::<SliceParameterBufferAV1>() == 40 && align_of::<SliceParameterBufferAV1>() == 4
476+ );
477+ assert!(offset_of!(SliceParameterBufferAV1, tile_row) == 12);
478+ assert!(offset_of!(SliceParameterBufferAV1, anchor_frame_idx) == 20);
479+ assert!(offset_of!(SliceParameterBufferAV1, tile_idx_in_tile_list) == 22);
480+};
crates/ec-hw/src/params/enc.rsadded+1494 -0
@@ -0,0 +1,1494 @@
1+//! Encode parameter buffers: H.264, HEVC and AV1, plus the codec-independent
2+//! misc-parameter and packed-header buffers (`va.h`, `va_enc_*.h`).
3+
4+use ec_va::sys::{
5+ VAEncPackedHeaderParameterBufferType, VAEncPictureParameterBufferType,
6+ VAEncSequenceParameterBufferType, VAEncSliceParameterBufferType, VASurfaceID,
7+};
8+
9+use super::VaParam;
10+use super::h264::VAPictureH264;
11+use super::hevc::VAPictureHEVC;
12+use crate::va_bits;
13+
14+/// `VAEncPackedHeaderSequence` (`va.h:2421`) — SPS/VPS.
15+pub const PACKED_HEADER_SEQUENCE: u32 = 1;
16+/// `VAEncPackedHeaderPicture` — PPS.
17+pub const PACKED_HEADER_PICTURE: u32 = 2;
18+/// `VAEncPackedHeaderSlice` — slice header.
19+pub const PACKED_HEADER_SLICE: u32 = 3;
20+/// `VAEncPackedHeaderRawData` — anything else, e.g. an AV1 OBU.
21+pub const PACKED_HEADER_RAW_DATA: u32 = 4;
22+
23+/// `VAEncMiscParameterTypeFrameRate`.
24+pub const MISC_FRAME_RATE: u32 = 0;
25+/// `VAEncMiscParameterTypeRateControl`.
26+pub const MISC_RATE_CONTROL: u32 = 1;
27+/// `VAEncMiscParameterTypeHRD`.
28+pub const MISC_HRD: u32 = 5;
29+/// `VAEncMiscParameterTypeQualityLevel`.
30+pub const MISC_QUALITY_LEVEL: u32 = 6;
31+
32+/// `VAEncPackedHeaderParameterBuffer`, `va.h:2446`.
33+#[repr(C)]
34+#[derive(Debug, Clone, Copy, Default)]
35+pub struct PackedHeaderParameterBuffer {
36+ /// One of the `PACKED_HEADER_*` constants.
37+ pub type_: u32,
38+ /// Length of the packed header in bits.
39+ pub bit_length: u32,
40+ /// Whether the data already carries emulation prevention bytes.
41+ pub has_emulation_bytes: u8,
42+ pub(crate) va_reserved: [u32; 4],
43+}
44+
45+impl PackedHeaderParameterBuffer {
46+ /// A header whose bytes are already escaped, as everything this crate
47+ /// writes is (the syntax crates emit Annex B ready bytes).
48+ pub fn escaped(type_: u32, bytes: usize) -> PackedHeaderParameterBuffer {
49+ PackedHeaderParameterBuffer {
50+ type_,
51+ bit_length: (bytes * 8) as u32,
52+ has_emulation_bytes: 1,
53+ va_reserved: [0; 4],
54+ }
55+ }
56+}
57+
58+// SAFETY: `#[repr(C)]` transcription of `VAEncPackedHeaderParameterBuffer`,
59+// checked below; integers only.
60+unsafe impl VaParam for PackedHeaderParameterBuffer {
61+ const TYPE: i32 = VAEncPackedHeaderParameterBufferType;
62+}
63+
64+/// `VAEncMiscParameterRateControl`, `va.h:2492`.
65+///
66+/// Built as words rather than as a struct because a misc parameter is submitted
67+/// as `{ type, payload }` in one buffer: the payload of every misc type this
68+/// crate sends is a run of `uint32_t`, so it can be assembled without ever
69+/// taking a byte view of a Rust struct.
70+#[derive(Debug, Clone, Copy, Default)]
71+pub struct RateControl {
72+ /// Target bitrate, or the peak bitrate under VBR.
73+ pub bits_per_second: u32,
74+ /// Percentage of `bits_per_second` to target (VBR); 0 means CBR.
75+ pub target_percentage: u32,
76+ /// Rate control window in milliseconds.
77+ pub window_size: u32,
78+ /// Initial quantiser, 0 to let the driver choose.
79+ pub initial_qp: u32,
80+ /// Minimum quantiser.
81+ pub min_qp: u32,
82+ /// Maximum quantiser.
83+ pub max_qp: u32,
84+}
85+
86+impl RateControl {
87+ /// The payload words in header order.
88+ pub fn words(&self) -> [u32; 15] {
89+ [
90+ self.bits_per_second,
91+ self.target_percentage,
92+ self.window_size,
93+ self.initial_qp,
94+ self.min_qp,
95+ 0, // basic_unit_size
96+ 0, // rc_flags
97+ 0, // ICQ_quality_factor
98+ self.max_qp,
99+ 0, // quality_factor
100+ 0, // target_frame_size
101+ 0,
102+ 0,
103+ 0,
104+ 0, // va_reserved[4]
105+ ]
106+ }
107+}
108+
109+/// `VAEncMiscParameterFrameRate`, `va.h:2617`.
110+#[derive(Debug, Clone, Copy)]
111+pub struct FrameRate {
112+ /// Numerator of the frame rate.
113+ pub num: u32,
114+ /// Denominator of the frame rate.
115+ pub den: u32,
116+}
117+
118+impl FrameRate {
119+ /// The payload words. libva packs a fractional rate as
120+ /// `den << 16 | num`, and a whole one as the plain numerator.
121+ pub fn words(&self) -> [u32; 6] {
122+ let packed = if self.den <= 1 {
123+ self.num
124+ } else {
125+ (self.den << 16) | (self.num & 0xffff)
126+ };
127+ [packed, 0, 0, 0, 0, 0]
128+ }
129+}
130+
131+/// `VAEncMiscParameterHRD`, `va.h:2721`.
132+#[derive(Debug, Clone, Copy, Default)]
133+pub struct Hrd {
134+ /// Initial CPB fullness in bits.
135+ pub initial_buffer_fullness: u32,
136+ /// CPB size in bits.
137+ pub buffer_size: u32,
138+}
139+
140+impl Hrd {
141+ /// The payload words in header order.
142+ pub fn words(&self) -> [u32; 6] {
143+ [self.initial_buffer_fullness, self.buffer_size, 0, 0, 0, 0]
144+ }
145+}
146+
147+/// Serialise a misc parameter buffer: the type word followed by its payload.
148+pub fn misc_bytes(type_: u32, words: &[u32]) -> Vec<u8> {
149+ let mut out = Vec::with_capacity(4 + words.len() * 4);
150+ out.extend_from_slice(&type_.to_ne_bytes());
151+ for w in words {
152+ out.extend_from_slice(&w.to_ne_bytes());
153+ }
154+ out
155+}
156+
157+// ---------------------------------------------------------------------------
158+// H.264 encode
159+// ---------------------------------------------------------------------------
160+
161+va_bits! {
162+ /// `VAEncSequenceParameterBufferH264::seq_fields`.
163+ H264SeqFields: u32 {
164+ chroma_format_idc: 2,
165+ frame_mbs_only_flag: 1,
166+ mb_adaptive_frame_field_flag: 1,
167+ seq_scaling_matrix_present_flag: 1,
168+ direct_8x8_inference_flag: 1,
169+ log2_max_frame_num_minus4: 4,
170+ pic_order_cnt_type: 2,
171+ log2_max_pic_order_cnt_lsb_minus4: 4,
172+ delta_pic_order_always_zero_flag: 1,
173+ }
174+}
175+
176+va_bits! {
177+ /// `VAEncSequenceParameterBufferH264::vui_fields`.
178+ H264VuiFields: u32 {
179+ aspect_ratio_info_present_flag: 1,
180+ timing_info_present_flag: 1,
181+ bitstream_restriction_flag: 1,
182+ log2_max_mv_length_horizontal: 5,
183+ log2_max_mv_length_vertical: 5,
184+ fixed_frame_rate_flag: 1,
185+ low_delay_hrd_flag: 1,
186+ motion_vectors_over_pic_boundaries_flag: 1,
187+ }
188+}
189+
190+/// `VAEncSequenceParameterBufferH264`, `va_enc_h264.h:78`.
191+#[repr(C)]
192+#[derive(Debug, Clone, Copy)]
193+pub struct EncSequenceParameterBufferH264 {
194+ /// `seq_parameter_set_id`.
195+ pub seq_parameter_set_id: u8,
196+ /// `level_idc`.
197+ pub level_idc: u8,
198+ /// Frames between I frames.
199+ pub intra_period: u32,
200+ /// Frames between IDR frames.
201+ pub intra_idr_period: u32,
202+ /// Distance between P frames (1 = no B frames).
203+ pub ip_period: u32,
204+ /// Target bitrate.
205+ pub bits_per_second: u32,
206+ /// `max_num_ref_frames`.
207+ pub max_num_ref_frames: u32,
208+ /// `PicWidthInMbs`.
209+ pub picture_width_in_mbs: u16,
210+ /// `PicHeightInMapUnits`.
211+ pub picture_height_in_mbs: u16,
212+ /// Sequence flags.
213+ pub seq_fields: H264SeqFields,
214+ /// `bit_depth_luma_minus8`.
215+ pub bit_depth_luma_minus8: u8,
216+ /// `bit_depth_chroma_minus8`.
217+ pub bit_depth_chroma_minus8: u8,
218+ /// `num_ref_frames_in_pic_order_cnt_cycle`.
219+ pub num_ref_frames_in_pic_order_cnt_cycle: u8,
220+ /// `offset_for_non_ref_pic`.
221+ pub offset_for_non_ref_pic: i32,
222+ /// `offset_for_top_to_bottom_field`.
223+ pub offset_for_top_to_bottom_field: i32,
224+ /// `offset_for_ref_frame`.
225+ pub offset_for_ref_frame: [i32; 256],
226+ /// `frame_cropping_flag`.
227+ pub frame_cropping_flag: u8,
228+ /// `frame_crop_left_offset`.
229+ pub frame_crop_left_offset: u32,
230+ /// `frame_crop_right_offset`.
231+ pub frame_crop_right_offset: u32,
232+ /// `frame_crop_top_offset`.
233+ pub frame_crop_top_offset: u32,
234+ /// `frame_crop_bottom_offset`.
235+ pub frame_crop_bottom_offset: u32,
236+ /// `vui_parameters_present_flag`.
237+ pub vui_parameters_present_flag: u8,
238+ /// VUI flags.
239+ pub vui_fields: H264VuiFields,
240+ /// `aspect_ratio_idc`.
241+ pub aspect_ratio_idc: u8,
242+ /// `sar_width`.
243+ pub sar_width: u32,
244+ /// `sar_height`.
245+ pub sar_height: u32,
246+ /// `num_units_in_tick`.
247+ pub num_units_in_tick: u32,
248+ /// `time_scale`.
249+ pub time_scale: u32,
250+ pub(crate) va_reserved: [u32; 4],
251+}
252+
253+impl Default for EncSequenceParameterBufferH264 {
254+ fn default() -> Self {
255+ EncSequenceParameterBufferH264 {
256+ seq_parameter_set_id: 0,
257+ level_idc: 41,
258+ intra_period: 0,
259+ intra_idr_period: 0,
260+ ip_period: 1,
261+ bits_per_second: 0,
262+ max_num_ref_frames: 1,
263+ picture_width_in_mbs: 0,
264+ picture_height_in_mbs: 0,
265+ seq_fields: H264SeqFields::default(),
266+ bit_depth_luma_minus8: 0,
267+ bit_depth_chroma_minus8: 0,
268+ num_ref_frames_in_pic_order_cnt_cycle: 0,
269+ offset_for_non_ref_pic: 0,
270+ offset_for_top_to_bottom_field: 0,
271+ offset_for_ref_frame: [0; 256],
272+ frame_cropping_flag: 0,
273+ frame_crop_left_offset: 0,
274+ frame_crop_right_offset: 0,
275+ frame_crop_top_offset: 0,
276+ frame_crop_bottom_offset: 0,
277+ vui_parameters_present_flag: 0,
278+ vui_fields: H264VuiFields::default(),
279+ aspect_ratio_idc: 0,
280+ sar_width: 0,
281+ sar_height: 0,
282+ num_units_in_tick: 0,
283+ time_scale: 0,
284+ va_reserved: [0; 4],
285+ }
286+ }
287+}
288+
289+// SAFETY: `#[repr(C)]` transcription checked by the assertion block below.
290+unsafe impl VaParam for EncSequenceParameterBufferH264 {
291+ const TYPE: i32 = VAEncSequenceParameterBufferType;
292+}
293+
294+va_bits! {
295+ /// `VAEncPictureParameterBufferH264::pic_fields`.
296+ H264EncPicFields: u32 {
297+ idr_pic_flag: 1,
298+ reference_pic_flag: 2,
299+ entropy_coding_mode_flag: 1,
300+ weighted_pred_flag: 1,
301+ weighted_bipred_idc: 2,
302+ constrained_intra_pred_flag: 1,
303+ transform_8x8_mode_flag: 1,
304+ deblocking_filter_control_present_flag: 1,
305+ redundant_pic_cnt_present_flag: 1,
306+ pic_order_present_flag: 1,
307+ pic_scaling_matrix_present_flag: 1,
308+ }
309+}
310+
311+/// `VAEncPictureParameterBufferH264`, `va_enc_h264.h:222`.
312+#[repr(C)]
313+#[derive(Debug, Clone, Copy)]
314+pub struct EncPictureParameterBufferH264 {
315+ /// Reconstructed picture surface for this frame.
316+ pub curr_pic: VAPictureH264,
317+ /// Reference pictures available to this frame.
318+ pub reference_frames: [VAPictureH264; 16],
319+ /// Buffer the coded bits are written to.
320+ pub coded_buf: u32,
321+ /// `pic_parameter_set_id`.
322+ pub pic_parameter_set_id: u8,
323+ /// `seq_parameter_set_id`.
324+ pub seq_parameter_set_id: u8,
325+ /// `H264_LAST_PICTURE_*` when this is the last picture.
326+ pub last_picture: u8,
327+ /// `frame_num`.
328+ pub frame_num: u16,
329+ /// `pic_init_qp_minus26 + 26`.
330+ pub pic_init_qp: u8,
331+ /// `num_ref_idx_l0_active_minus1`.
332+ pub num_ref_idx_l0_active_minus1: u8,
333+ /// `num_ref_idx_l1_active_minus1`.
334+ pub num_ref_idx_l1_active_minus1: u8,
335+ /// `chroma_qp_index_offset`.
336+ pub chroma_qp_index_offset: i8,
337+ /// `second_chroma_qp_index_offset`.
338+ pub second_chroma_qp_index_offset: i8,
339+ /// Picture flags.
340+ pub pic_fields: H264EncPicFields,
341+ pub(crate) va_reserved: [u32; 4],
342+}
343+
344+impl Default for EncPictureParameterBufferH264 {
345+ fn default() -> Self {
346+ EncPictureParameterBufferH264 {
347+ curr_pic: VAPictureH264::INVALID,
348+ reference_frames: [VAPictureH264::INVALID; 16],
349+ coded_buf: 0,
350+ pic_parameter_set_id: 0,
351+ seq_parameter_set_id: 0,
352+ last_picture: 0,
353+ frame_num: 0,
354+ pic_init_qp: 26,
355+ num_ref_idx_l0_active_minus1: 0,
356+ num_ref_idx_l1_active_minus1: 0,
357+ chroma_qp_index_offset: 0,
358+ second_chroma_qp_index_offset: 0,
359+ pic_fields: H264EncPicFields::default(),
360+ va_reserved: [0; 4],
361+ }
362+ }
363+}
364+
365+// SAFETY: `#[repr(C)]` transcription checked by the assertion block below.
366+unsafe impl VaParam for EncPictureParameterBufferH264 {
367+ const TYPE: i32 = VAEncPictureParameterBufferType;
368+}
369+
370+/// `VAEncSliceParameterBufferH264`, `va_enc_h264.h:290`.
371+#[repr(C)]
372+#[derive(Debug, Clone, Copy)]
373+pub struct EncSliceParameterBufferH264 {
374+ /// First macroblock of this slice.
375+ pub macroblock_address: u32,
376+ /// Macroblocks in this slice.
377+ pub num_macroblocks: u32,
378+ /// Optional per-macroblock parameter buffer; `VA_INVALID_ID` for none.
379+ pub macroblock_info: u32,
380+ /// `slice_type`.
381+ pub slice_type: u8,
382+ /// `pic_parameter_set_id`.
383+ pub pic_parameter_set_id: u8,
384+ /// `idr_pic_id`.
385+ pub idr_pic_id: u16,
386+ /// `pic_order_cnt_lsb`.
387+ pub pic_order_cnt_lsb: u16,
388+ /// `delta_pic_order_cnt_bottom`.
389+ pub delta_pic_order_cnt_bottom: i32,
390+ /// `delta_pic_order_cnt`.
391+ pub delta_pic_order_cnt: [i32; 2],
392+ /// `direct_spatial_mv_pred_flag`.
393+ pub direct_spatial_mv_pred_flag: u8,
394+ /// `num_ref_idx_active_override_flag`.
395+ pub num_ref_idx_active_override_flag: u8,
396+ /// `num_ref_idx_l0_active_minus1`.
397+ pub num_ref_idx_l0_active_minus1: u8,
398+ /// `num_ref_idx_l1_active_minus1`.
399+ pub num_ref_idx_l1_active_minus1: u8,
400+ /// `RefPicList0`.
401+ pub ref_pic_list0: [VAPictureH264; 32],
402+ /// `RefPicList1`.
403+ pub ref_pic_list1: [VAPictureH264; 32],
404+ /// `luma_log2_weight_denom`.
405+ pub luma_log2_weight_denom: u8,
406+ /// `chroma_log2_weight_denom`.
407+ pub chroma_log2_weight_denom: u8,
408+ /// `luma_weight_l0_flag`.
409+ pub luma_weight_l0_flag: u8,
410+ /// `luma_weight_l0`.
411+ pub luma_weight_l0: [i16; 32],
412+ /// `luma_offset_l0`.
413+ pub luma_offset_l0: [i16; 32],
414+ /// `chroma_weight_l0_flag`.
415+ pub chroma_weight_l0_flag: u8,
416+ /// `chroma_weight_l0`.
417+ pub chroma_weight_l0: [[i16; 2]; 32],
418+ /// `chroma_offset_l0`.
419+ pub chroma_offset_l0: [[i16; 2]; 32],
420+ /// `luma_weight_l1_flag`.
421+ pub luma_weight_l1_flag: u8,
422+ /// `luma_weight_l1`.
423+ pub luma_weight_l1: [i16; 32],
424+ /// `luma_offset_l1`.
425+ pub luma_offset_l1: [i16; 32],
426+ /// `chroma_weight_l1_flag`.
427+ pub chroma_weight_l1_flag: u8,
428+ /// `chroma_weight_l1`.
429+ pub chroma_weight_l1: [[i16; 2]; 32],
430+ /// `chroma_offset_l1`.
431+ pub chroma_offset_l1: [[i16; 2]; 32],
432+ /// `cabac_init_idc`.
433+ pub cabac_init_idc: u8,
434+ /// `slice_qp_delta`.
435+ pub slice_qp_delta: i8,
436+ /// `disable_deblocking_filter_idc`.
437+ pub disable_deblocking_filter_idc: u8,
438+ /// `slice_alpha_c0_offset_div2`.
439+ pub slice_alpha_c0_offset_div2: i8,
440+ /// `slice_beta_offset_div2`.
441+ pub slice_beta_offset_div2: i8,
442+ pub(crate) va_reserved: [u32; 4],
443+}
444+
445+impl Default for EncSliceParameterBufferH264 {
446+ fn default() -> Self {
447+ EncSliceParameterBufferH264 {
448+ macroblock_address: 0,
449+ num_macroblocks: 0,
450+ macroblock_info: ec_va::sys::VA_INVALID_ID,
451+ slice_type: 2,
452+ pic_parameter_set_id: 0,
453+ idr_pic_id: 0,
454+ pic_order_cnt_lsb: 0,
455+ delta_pic_order_cnt_bottom: 0,
456+ delta_pic_order_cnt: [0; 2],
457+ direct_spatial_mv_pred_flag: 0,
458+ num_ref_idx_active_override_flag: 0,
459+ num_ref_idx_l0_active_minus1: 0,
460+ num_ref_idx_l1_active_minus1: 0,
461+ ref_pic_list0: [VAPictureH264::INVALID; 32],
462+ ref_pic_list1: [VAPictureH264::INVALID; 32],
463+ luma_log2_weight_denom: 0,
464+ chroma_log2_weight_denom: 0,
465+ luma_weight_l0_flag: 0,
466+ luma_weight_l0: [0; 32],
467+ luma_offset_l0: [0; 32],
468+ chroma_weight_l0_flag: 0,
469+ chroma_weight_l0: [[0; 2]; 32],
470+ chroma_offset_l0: [[0; 2]; 32],
471+ luma_weight_l1_flag: 0,
472+ luma_weight_l1: [0; 32],
473+ luma_offset_l1: [0; 32],
474+ chroma_weight_l1_flag: 0,
475+ chroma_weight_l1: [[0; 2]; 32],
476+ chroma_offset_l1: [[0; 2]; 32],
477+ cabac_init_idc: 0,
478+ slice_qp_delta: 0,
479+ disable_deblocking_filter_idc: 0,
480+ slice_alpha_c0_offset_div2: 0,
481+ slice_beta_offset_div2: 0,
482+ va_reserved: [0; 4],
483+ }
484+ }
485+}
486+
487+// SAFETY: `#[repr(C)]` transcription checked by the assertion block below.
488+unsafe impl VaParam for EncSliceParameterBufferH264 {
489+ const TYPE: i32 = VAEncSliceParameterBufferType;
490+}
491+
492+// ---------------------------------------------------------------------------
493+// HEVC encode
494+// ---------------------------------------------------------------------------
495+
496+va_bits! {
497+ /// `VAEncSequenceParameterBufferHEVC::seq_fields`.
498+ HevcSeqFields: u32 {
499+ chroma_format_idc: 2,
500+ separate_colour_plane_flag: 1,
501+ bit_depth_luma_minus8: 3,
502+ bit_depth_chroma_minus8: 3,
503+ scaling_list_enabled_flag: 1,
504+ strong_intra_smoothing_enabled_flag: 1,
505+ amp_enabled_flag: 1,
506+ sample_adaptive_offset_enabled_flag: 1,
507+ pcm_enabled_flag: 1,
508+ pcm_loop_filter_disabled_flag: 1,
509+ sps_temporal_mvp_enabled_flag: 1,
510+ low_delay_seq: 1,
511+ hierachical_flag: 1,
512+ }
513+}
514+
515+va_bits! {
516+ /// `VAEncSequenceParameterBufferHEVC::vui_fields`.
517+ HevcVuiFields: u32 {
518+ aspect_ratio_info_present_flag: 1,
519+ neutral_chroma_indication_flag: 1,
520+ field_seq_flag: 1,
521+ vui_timing_info_present_flag: 1,
522+ bitstream_restriction_flag: 1,
523+ tiles_fixed_structure_flag: 1,
524+ motion_vectors_over_pic_boundaries_flag: 1,
525+ restricted_ref_pic_lists_flag: 1,
526+ log2_max_mv_length_horizontal: 5,
527+ log2_max_mv_length_vertical: 5,
528+ }
529+}
530+
531+/// `VAEncSequenceParameterBufferHEVC`, `va_enc_hevc.h:139`.
532+#[repr(C)]
533+#[derive(Debug, Clone, Copy)]
534+pub struct EncSequenceParameterBufferHEVC {
535+ /// `general_profile_idc`.
536+ pub general_profile_idc: u8,
537+ /// `general_level_idc`.
538+ pub general_level_idc: u8,
539+ /// `general_tier_flag`.
540+ pub general_tier_flag: u8,
541+ /// Frames between I frames.
542+ pub intra_period: u32,
543+ /// Frames between IDR frames.
544+ pub intra_idr_period: u32,
545+ /// Distance between P frames.
546+ pub ip_period: u32,
547+ /// Target bitrate.
548+ pub bits_per_second: u32,
549+ /// `pic_width_in_luma_samples`.
550+ pub pic_width_in_luma_samples: u16,
551+ /// `pic_height_in_luma_samples`.
552+ pub pic_height_in_luma_samples: u16,
553+ /// Sequence flags.
554+ pub seq_fields: HevcSeqFields,
555+ /// `log2_min_luma_coding_block_size_minus3`.
556+ pub log2_min_luma_coding_block_size_minus3: u8,
557+ /// `log2_diff_max_min_luma_coding_block_size`.
558+ pub log2_diff_max_min_luma_coding_block_size: u8,
559+ /// `log2_min_transform_block_size_minus2`.
560+ pub log2_min_transform_block_size_minus2: u8,
561+ /// `log2_diff_max_min_transform_block_size`.
562+ pub log2_diff_max_min_transform_block_size: u8,
563+ /// `max_transform_hierarchy_depth_inter`.
564+ pub max_transform_hierarchy_depth_inter: u8,
565+ /// `max_transform_hierarchy_depth_intra`.
566+ pub max_transform_hierarchy_depth_intra: u8,
567+ /// `pcm_sample_bit_depth_luma_minus1`.
568+ pub pcm_sample_bit_depth_luma_minus1: u32,
569+ /// `pcm_sample_bit_depth_chroma_minus1`.
570+ pub pcm_sample_bit_depth_chroma_minus1: u32,
571+ /// `log2_min_pcm_luma_coding_block_size_minus3`.
572+ pub log2_min_pcm_luma_coding_block_size_minus3: u32,
573+ /// `log2_max_pcm_luma_coding_block_size_minus3`.
574+ pub log2_max_pcm_luma_coding_block_size_minus3: u32,
575+ /// `vui_parameters_present_flag`.
576+ pub vui_parameters_present_flag: u8,
577+ /// VUI flags.
578+ pub vui_fields: HevcVuiFields,
579+ /// `aspect_ratio_idc`.
580+ pub aspect_ratio_idc: u8,
581+ /// `sar_width`.
582+ pub sar_width: u32,
583+ /// `sar_height`.
584+ pub sar_height: u32,
585+ /// `vui_num_units_in_tick`.
586+ pub vui_num_units_in_tick: u32,
587+ /// `vui_time_scale`.
588+ pub vui_time_scale: u32,
589+ /// `min_spatial_segmentation_idc`.
590+ pub min_spatial_segmentation_idc: u16,
591+ /// `max_bytes_per_pic_denom`.
592+ pub max_bytes_per_pic_denom: u8,
593+ /// `max_bits_per_min_cu_denom`.
594+ pub max_bits_per_min_cu_denom: u8,
595+ /// Screen content flags.
596+ pub scc_fields: u32,
597+ pub(crate) va_reserved: [u32; 7],
598+}
599+
600+impl Default for EncSequenceParameterBufferHEVC {
601+ fn default() -> Self {
602+ EncSequenceParameterBufferHEVC {
603+ general_profile_idc: 1,
604+ general_level_idc: 120,
605+ general_tier_flag: 0,
606+ intra_period: 0,
607+ intra_idr_period: 0,
608+ ip_period: 1,
609+ bits_per_second: 0,
610+ pic_width_in_luma_samples: 0,
611+ pic_height_in_luma_samples: 0,
612+ seq_fields: HevcSeqFields::default(),
613+ log2_min_luma_coding_block_size_minus3: 0,
614+ log2_diff_max_min_luma_coding_block_size: 3,
615+ log2_min_transform_block_size_minus2: 0,
616+ log2_diff_max_min_transform_block_size: 3,
617+ max_transform_hierarchy_depth_inter: 0,
618+ max_transform_hierarchy_depth_intra: 0,
619+ pcm_sample_bit_depth_luma_minus1: 7,
620+ pcm_sample_bit_depth_chroma_minus1: 7,
621+ log2_min_pcm_luma_coding_block_size_minus3: 0,
622+ log2_max_pcm_luma_coding_block_size_minus3: 0,
623+ vui_parameters_present_flag: 0,
624+ vui_fields: HevcVuiFields::default(),
625+ aspect_ratio_idc: 0,
626+ sar_width: 0,
627+ sar_height: 0,
628+ vui_num_units_in_tick: 0,
629+ vui_time_scale: 0,
630+ min_spatial_segmentation_idc: 0,
631+ max_bytes_per_pic_denom: 0,
632+ max_bits_per_min_cu_denom: 0,
633+ scc_fields: 0,
634+ va_reserved: [0; 7],
635+ }
636+ }
637+}
638+
639+// SAFETY: `#[repr(C)]` transcription checked by the assertion block below.
640+unsafe impl VaParam for EncSequenceParameterBufferHEVC {
641+ const TYPE: i32 = VAEncSequenceParameterBufferType;
642+}
643+
644+va_bits! {
645+ /// `VAEncPictureParameterBufferHEVC::pic_fields`.
646+ HevcEncPicFields: u32 {
647+ idr_pic_flag: 1,
648+ coding_type: 3,
649+ reference_pic_flag: 1,
650+ dependent_slice_segments_enabled_flag: 1,
651+ sign_data_hiding_enabled_flag: 1,
652+ constrained_intra_pred_flag: 1,
653+ transform_skip_enabled_flag: 1,
654+ cu_qp_delta_enabled_flag: 1,
655+ weighted_pred_flag: 1,
656+ weighted_bipred_flag: 1,
657+ transquant_bypass_enabled_flag: 1,
658+ tiles_enabled_flag: 1,
659+ entropy_coding_sync_enabled_flag: 1,
660+ loop_filter_across_tiles_enabled_flag: 1,
661+ pps_loop_filter_across_slices_enabled_flag: 1,
662+ scaling_list_data_present_flag: 1,
663+ screen_content_flag: 1,
664+ enable_gpu_weighted_prediction: 1,
665+ no_output_of_prior_pics_flag: 1,
666+ }
667+}
668+
669+/// `VAEncPictureParameterBufferHEVC`, `va_enc_hevc.h:270`.
670+#[repr(C)]
671+#[derive(Debug, Clone, Copy)]
672+pub struct EncPictureParameterBufferHEVC {
673+ /// Reconstructed picture surface for this frame.
674+ pub decoded_curr_pic: VAPictureHEVC,
675+ /// Reference pictures available to this frame.
676+ pub reference_frames: [VAPictureHEVC; 15],
677+ /// Buffer the coded bits are written to.
678+ pub coded_buf: u32,
679+ /// Index into `reference_frames` of the collocated picture.
680+ pub collocated_ref_pic_index: u8,
681+ /// `HEVC_LAST_PICTURE_*` when this is the last picture.
682+ pub last_picture: u8,
683+ /// `init_qp_minus26 + 26`.
684+ pub pic_init_qp: u8,
685+ /// `diff_cu_qp_delta_depth`.
686+ pub diff_cu_qp_delta_depth: u8,
687+ /// `pps_cb_qp_offset`.
688+ pub pps_cb_qp_offset: i8,
689+ /// `pps_cr_qp_offset`.
690+ pub pps_cr_qp_offset: i8,
691+ /// `num_tile_columns_minus1`.
692+ pub num_tile_columns_minus1: u8,
693+ /// `num_tile_rows_minus1`.
694+ pub num_tile_rows_minus1: u8,
695+ /// `column_width_minus1`.
696+ pub column_width_minus1: [u8; 19],
697+ /// `row_height_minus1`.
698+ pub row_height_minus1: [u8; 21],
699+ /// `log2_parallel_merge_level_minus2`.
700+ pub log2_parallel_merge_level_minus2: u8,
701+ /// Maximum bits a CTU may use, 0 for no limit.
702+ pub ctu_max_bitsize_allowed: u8,
703+ /// `num_ref_idx_l0_default_active_minus1`.
704+ pub num_ref_idx_l0_default_active_minus1: u8,
705+ /// `num_ref_idx_l1_default_active_minus1`.
706+ pub num_ref_idx_l1_default_active_minus1: u8,
707+ /// `slice_pic_parameter_set_id`.
708+ pub slice_pic_parameter_set_id: u8,
709+ /// NAL unit type to code the slices as.
710+ pub nal_unit_type: u8,
711+ /// Picture flags.
712+ pub pic_fields: HevcEncPicFields,
713+ /// Temporal layer + 1, 0 when unused.
714+ pub hierarchical_level_plus1: u8,
715+ pub(crate) va_byte_reserved: u8,
716+ /// Screen content flags.
717+ pub scc_fields: u16,
718+ pub(crate) va_reserved: [u32; 15],
719+}
720+
721+impl Default for EncPictureParameterBufferHEVC {
722+ fn default() -> Self {
723+ EncPictureParameterBufferHEVC {
724+ decoded_curr_pic: VAPictureHEVC::INVALID,
725+ reference_frames: [VAPictureHEVC::INVALID; 15],
726+ coded_buf: 0,
727+ collocated_ref_pic_index: 0xff,
728+ last_picture: 0,
729+ pic_init_qp: 26,
730+ diff_cu_qp_delta_depth: 0,
731+ pps_cb_qp_offset: 0,
732+ pps_cr_qp_offset: 0,
733+ num_tile_columns_minus1: 0,
734+ num_tile_rows_minus1: 0,
735+ column_width_minus1: [0; 19],
736+ row_height_minus1: [0; 21],
737+ log2_parallel_merge_level_minus2: 0,
738+ ctu_max_bitsize_allowed: 0,
739+ num_ref_idx_l0_default_active_minus1: 0,
740+ num_ref_idx_l1_default_active_minus1: 0,
741+ slice_pic_parameter_set_id: 0,
742+ nal_unit_type: 19, // IDR_W_RADL
743+ pic_fields: HevcEncPicFields::default(),
744+ hierarchical_level_plus1: 0,
745+ va_byte_reserved: 0,
746+ scc_fields: 0,
747+ va_reserved: [0; 15],
748+ }
749+ }
750+}
751+
752+// SAFETY: `#[repr(C)]` transcription checked by the assertion block below.
753+unsafe impl VaParam for EncPictureParameterBufferHEVC {
754+ const TYPE: i32 = VAEncPictureParameterBufferType;
755+}
756+
757+va_bits! {
758+ /// `VAEncSliceParameterBufferHEVC::slice_fields`.
759+ HevcEncSliceFields: u32 {
760+ last_slice_of_pic_flag: 1,
761+ dependent_slice_segment_flag: 1,
762+ colour_plane_id: 2,
763+ slice_temporal_mvp_enabled_flag: 1,
764+ slice_sao_luma_flag: 1,
765+ slice_sao_chroma_flag: 1,
766+ num_ref_idx_active_override_flag: 1,
767+ mvd_l1_zero_flag: 1,
768+ cabac_init_flag: 1,
769+ slice_deblocking_filter_disabled_flag: 2,
770+ slice_loop_filter_across_slices_enabled_flag: 1,
771+ collocated_from_l0_flag: 1,
772+ }
773+}
774+
775+/// `VAEncSliceParameterBufferHEVC`, `va_enc_hevc.h:449`.
776+#[repr(C)]
777+#[derive(Debug, Clone, Copy)]
778+pub struct EncSliceParameterBufferHEVC {
779+ /// `slice_segment_address`.
780+ pub slice_segment_address: u32,
781+ /// CTUs in this slice.
782+ pub num_ctu_in_slice: u32,
783+ /// `slice_type`.
784+ pub slice_type: u8,
785+ /// `slice_pic_parameter_set_id`.
786+ pub slice_pic_parameter_set_id: u8,
787+ /// `num_ref_idx_l0_active_minus1`.
788+ pub num_ref_idx_l0_active_minus1: u8,
789+ /// `num_ref_idx_l1_active_minus1`.
790+ pub num_ref_idx_l1_active_minus1: u8,
791+ /// `RefPicList0`.
792+ pub ref_pic_list0: [VAPictureHEVC; 15],
793+ /// `RefPicList1`.
794+ pub ref_pic_list1: [VAPictureHEVC; 15],
795+ /// `luma_log2_weight_denom`.
796+ pub luma_log2_weight_denom: u8,
797+ /// `delta_chroma_log2_weight_denom`.
798+ pub delta_chroma_log2_weight_denom: i8,
799+ /// `delta_luma_weight_l0`.
800+ pub delta_luma_weight_l0: [i8; 15],
801+ /// `luma_offset_l0`.
802+ pub luma_offset_l0: [i8; 15],
803+ /// `delta_chroma_weight_l0`.
804+ pub delta_chroma_weight_l0: [[i8; 2]; 15],
805+ /// `chroma_offset_l0`.
806+ pub chroma_offset_l0: [[i8; 2]; 15],
807+ /// `delta_luma_weight_l1`.
808+ pub delta_luma_weight_l1: [i8; 15],
809+ /// `luma_offset_l1`.
810+ pub luma_offset_l1: [i8; 15],
811+ /// `delta_chroma_weight_l1`.
812+ pub delta_chroma_weight_l1: [[i8; 2]; 15],
813+ /// `chroma_offset_l1`.
814+ pub chroma_offset_l1: [[i8; 2]; 15],
815+ /// `MaxNumMergeCand`.
816+ pub max_num_merge_cand: u8,
817+ /// `slice_qp_delta`.
818+ pub slice_qp_delta: i8,
819+ /// `slice_cb_qp_offset`.
820+ pub slice_cb_qp_offset: i8,
821+ /// `slice_cr_qp_offset`.
822+ pub slice_cr_qp_offset: i8,
823+ /// `slice_beta_offset_div2`.
824+ pub slice_beta_offset_div2: i8,
825+ /// `slice_tc_offset_div2`.
826+ pub slice_tc_offset_div2: i8,
827+ /// Slice flags.
828+ pub slice_fields: HevcEncSliceFields,
829+ /// Bit offset of `pred_weight_table()` inside the packed slice header.
830+ pub pred_weight_table_bit_offset: u32,
831+ /// Bit length of `pred_weight_table()`.
832+ pub pred_weight_table_bit_length: u32,
833+ pub(crate) va_reserved: [u32; 6],
834+}
835+
836+impl Default for EncSliceParameterBufferHEVC {
837+ fn default() -> Self {
838+ EncSliceParameterBufferHEVC {
839+ slice_segment_address: 0,
840+ num_ctu_in_slice: 0,
841+ slice_type: 2,
842+ slice_pic_parameter_set_id: 0,
843+ num_ref_idx_l0_active_minus1: 0,
844+ num_ref_idx_l1_active_minus1: 0,
845+ ref_pic_list0: [VAPictureHEVC::INVALID; 15],
846+ ref_pic_list1: [VAPictureHEVC::INVALID; 15],
847+ luma_log2_weight_denom: 0,
848+ delta_chroma_log2_weight_denom: 0,
849+ delta_luma_weight_l0: [0; 15],
850+ luma_offset_l0: [0; 15],
851+ delta_chroma_weight_l0: [[0; 2]; 15],
852+ chroma_offset_l0: [[0; 2]; 15],
853+ delta_luma_weight_l1: [0; 15],
854+ luma_offset_l1: [0; 15],
855+ delta_chroma_weight_l1: [[0; 2]; 15],
856+ chroma_offset_l1: [[0; 2]; 15],
857+ max_num_merge_cand: 5,
858+ slice_qp_delta: 0,
859+ slice_cb_qp_offset: 0,
860+ slice_cr_qp_offset: 0,
861+ slice_beta_offset_div2: 0,
862+ slice_tc_offset_div2: 0,
863+ slice_fields: HevcEncSliceFields::default(),
864+ pred_weight_table_bit_offset: 0,
865+ pred_weight_table_bit_length: 0,
866+ va_reserved: [0; 6],
867+ }
868+ }
869+}
870+
871+// SAFETY: `#[repr(C)]` transcription checked by the assertion block below.
872+unsafe impl VaParam for EncSliceParameterBufferHEVC {
873+ const TYPE: i32 = VAEncSliceParameterBufferType;
874+}
875+
876+// ---------------------------------------------------------------------------
877+// AV1 encode
878+// ---------------------------------------------------------------------------
879+
880+va_bits! {
881+ /// `VAEncSequenceParameterBufferAV1::seq_fields`.
882+ Av1SeqFields: u32 {
883+ still_picture: 1,
884+ use_128x128_superblock: 1,
885+ enable_filter_intra: 1,
886+ enable_intra_edge_filter: 1,
887+ enable_interintra_compound: 1,
888+ enable_masked_compound: 1,
889+ enable_warped_motion: 1,
890+ enable_dual_filter: 1,
891+ enable_order_hint: 1,
892+ enable_jnt_comp: 1,
893+ enable_ref_frame_mvs: 1,
894+ enable_superres: 1,
895+ enable_cdef: 1,
896+ enable_restoration: 1,
897+ bit_depth_minus8: 3,
898+ subsampling_x: 1,
899+ subsampling_y: 1,
900+ mono_chrome: 1,
901+ }
902+}
903+
904+/// `VAEncSequenceParameterBufferAV1`, `va_enc_av1.h:118`.
905+#[repr(C)]
906+#[derive(Debug, Clone, Copy)]
907+pub struct EncSequenceParameterBufferAV1 {
908+ /// `seq_profile`.
909+ pub seq_profile: u8,
910+ /// `seq_level_idx`.
911+ pub seq_level_idx: u8,
912+ /// `seq_tier`.
913+ pub seq_tier: u8,
914+ /// Temporal layering flag.
915+ pub hierarchical_flag: u8,
916+ /// Frames between key frames.
917+ pub intra_period: u32,
918+ /// Distance between P frames.
919+ pub ip_period: u32,
920+ /// Target bitrate.
921+ pub bits_per_second: u32,
922+ /// Sequence flags.
923+ pub seq_fields: Av1SeqFields,
924+ /// `OrderHintBits - 1`.
925+ pub order_hint_bits_minus_1: u8,
926+ pub(crate) va_reserved: [u32; 16],
927+}
928+
929+impl Default for EncSequenceParameterBufferAV1 {
930+ fn default() -> Self {
931+ EncSequenceParameterBufferAV1 {
932+ seq_profile: 0,
933+ seq_level_idx: 0,
934+ seq_tier: 0,
935+ hierarchical_flag: 0,
936+ intra_period: 0,
937+ ip_period: 1,
938+ bits_per_second: 0,
939+ seq_fields: Av1SeqFields::default(),
940+ order_hint_bits_minus_1: 0,
941+ va_reserved: [0; 16],
942+ }
943+ }
944+}
945+
946+// SAFETY: `#[repr(C)]` transcription checked by the assertion block below.
947+unsafe impl VaParam for EncSequenceParameterBufferAV1 {
948+ const TYPE: i32 = VAEncSequenceParameterBufferType;
949+}
950+
951+va_bits! {
952+ /// `VAEncSegParamAV1::seg_flags`.
953+ Av1SegFlags: u8 {
954+ segmentation_enabled: 1,
955+ segmentation_update_map: 1,
956+ segmentation_temporal_update: 1,
957+ }
958+}
959+
960+/// `VAEncSegParamAV1`, `va_enc_av1.h:216`.
961+#[repr(C)]
962+#[derive(Debug, Clone, Copy, Default)]
963+pub struct EncSegParamAV1 {
964+ /// Segmentation flags.
965+ pub seg_flags: Av1SegFlags,
966+ /// Number of segments in use.
967+ pub segment_number: u8,
968+ /// `FeatureData`.
969+ pub feature_data: [[i16; 8]; 8],
970+ /// `FeatureEnabled` bitmask per segment.
971+ pub feature_mask: [u8; 8],
972+ pub(crate) va_reserved: [u32; 4],
973+}
974+
975+/// `VAEncWarpedMotionParamsAV1`, `va_enc_av1.h:262`.
976+#[repr(C)]
977+#[derive(Debug, Clone, Copy, Default)]
978+pub struct EncWarpedMotionParamsAV1 {
979+ /// Transformation type.
980+ pub wmtype: i32,
981+ /// Model parameters.
982+ pub wmmat: [i32; 8],
983+ /// Set when the model was rejected.
984+ pub invalid: u8,
985+ pub(crate) va_reserved: [u32; 4],
986+}
987+
988+va_bits! {
989+ /// `VAEncPictureParameterBufferAV1::picture_flags`.
990+ Av1EncPicFlags: u32 {
991+ frame_type: 2,
992+ error_resilient_mode: 1,
993+ disable_cdf_update: 1,
994+ use_superres: 1,
995+ allow_high_precision_mv: 1,
996+ use_ref_frame_mvs: 1,
997+ disable_frame_end_update_cdf: 1,
998+ reduced_tx_set: 1,
999+ enable_frame_obu: 1,
1000+ long_term_reference: 1,
1001+ disable_frame_recon: 1,
1002+ allow_intrabc: 1,
1003+ palette_mode_enable: 1,
1004+ allow_screen_content_tools: 1,
1005+ force_integer_mv: 1,
1006+ }
1007+}
1008+
1009+va_bits! {
1010+ /// `VAEncPictureParameterBufferAV1::mode_control_flags`.
1011+ Av1ModeControlFlags: u32 {
1012+ delta_q_present: 1,
1013+ delta_q_res: 2,
1014+ delta_lf_present: 1,
1015+ delta_lf_res: 2,
1016+ delta_lf_multi: 1,
1017+ tx_mode: 2,
1018+ reference_mode: 2,
1019+ skip_mode_present: 1,
1020+ }
1021+}
1022+
1023+va_bits! {
1024+ /// `VAEncPictureParameterBufferAV1::tile_group_obu_hdr_info`.
1025+ Av1TileGroupObuHdrInfo: u8 {
1026+ obu_extension_flag: 1,
1027+ obu_has_size_field: 1,
1028+ temporal_id: 3,
1029+ spatial_id: 2,
1030+ }
1031+}
1032+
1033+/// `VAEncPictureParameterBufferAV1`, `va_enc_av1.h:322`.
1034+#[repr(C)]
1035+#[derive(Debug, Clone, Copy)]
1036+pub struct EncPictureParameterBufferAV1 {
1037+ /// `frame_width_minus_1`.
1038+ pub frame_width_minus_1: u16,
1039+ /// `frame_height_minus_1`.
1040+ pub frame_height_minus_1: u16,
1041+ /// Surface the reconstruction is written to.
1042+ pub reconstructed_frame: VASurfaceID,
1043+ /// Buffer the coded bits are written to.
1044+ pub coded_buf: u32,
1045+ /// The eight reference slots.
1046+ pub reference_frames: [VASurfaceID; 8],
1047+ /// `ref_frame_idx`.
1048+ pub ref_frame_idx: [u8; 7],
1049+ /// Temporal layer + 1.
1050+ pub hierarchical_level_plus1: u8,
1051+ /// `primary_ref_frame`.
1052+ pub primary_ref_frame: u8,
1053+ /// `order_hint`.
1054+ pub order_hint: u8,
1055+ /// `refresh_frame_flags`.
1056+ pub refresh_frame_flags: u8,
1057+ pub(crate) reserved8bits1: u8,
1058+ /// Reference control for list 0.
1059+ pub ref_frame_ctrl_l0: u32,
1060+ /// Reference control for list 1.
1061+ pub ref_frame_ctrl_l1: u32,
1062+ /// Picture flags.
1063+ pub picture_flags: Av1EncPicFlags,
1064+ /// Segment id block size.
1065+ pub seg_id_block_size: u8,
1066+ /// `num_tile_groups_minus1`.
1067+ pub num_tile_groups_minus1: u8,
1068+ /// Temporal id.
1069+ pub temporal_id: u8,
1070+ /// `loop_filter_level[0..2]`.
1071+ pub filter_level: [u8; 2],
1072+ /// `loop_filter_level[2]`.
1073+ pub filter_level_u: u8,
1074+ /// `loop_filter_level[3]`.
1075+ pub filter_level_v: u8,
1076+ /// Loop filter flags.
1077+ pub loop_filter_flags: u8,
1078+ /// `SuperresDenom`.
1079+ pub superres_scale_denominator: u8,
1080+ /// `interpolation_filter`.
1081+ pub interpolation_filter: u8,
1082+ /// `loop_filter_ref_deltas`.
1083+ pub ref_deltas: [i8; 8],
1084+ /// `loop_filter_mode_deltas`.
1085+ pub mode_deltas: [i8; 2],
1086+ /// `base_q_idx`.
1087+ pub base_qindex: u8,
1088+ /// `DeltaQYDc`.
1089+ pub y_dc_delta_q: i8,
1090+ /// `DeltaQUDc`.
1091+ pub u_dc_delta_q: i8,
1092+ /// `DeltaQUAc`.
1093+ pub u_ac_delta_q: i8,
1094+ /// `DeltaQVDc`.
1095+ pub v_dc_delta_q: i8,
1096+ /// `DeltaQVAc`.
1097+ pub v_ac_delta_q: i8,
1098+ /// Lower bound the rate controller may pick.
1099+ pub min_base_qindex: u8,
1100+ /// Upper bound the rate controller may pick.
1101+ pub max_base_qindex: u8,
1102+ /// Quantiser matrix flags.
1103+ pub qmatrix_flags: u16,
1104+ pub(crate) reserved16bits1: u16,
1105+ /// Mode control flags.
1106+ pub mode_control_flags: Av1ModeControlFlags,
1107+ /// Segmentation parameters.
1108+ pub segments: EncSegParamAV1,
1109+ /// `TileCols`.
1110+ pub tile_cols: u8,
1111+ /// `TileRows`.
1112+ pub tile_rows: u8,
1113+ pub(crate) reserved16bits2: u16,
1114+ /// Per-column widths in superblocks, minus one.
1115+ pub width_in_sbs_minus_1: [u16; 63],
1116+ /// Per-row heights in superblocks, minus one.
1117+ pub height_in_sbs_minus_1: [u16; 63],
1118+ /// `context_update_tile_id`.
1119+ pub context_update_tile_id: u16,
1120+ /// `CdefDamping - 3`.
1121+ pub cdef_damping_minus_3: u8,
1122+ /// `cdef_bits`.
1123+ pub cdef_bits: u8,
1124+ /// Combined luma strengths.
1125+ pub cdef_y_strengths: [u8; 8],
1126+ /// Combined chroma strengths.
1127+ pub cdef_uv_strengths: [u8; 8],
1128+ /// Loop restoration flags.
1129+ pub loop_restoration_flags: u16,
1130+ /// Global motion.
1131+ pub wm: [EncWarpedMotionParamsAV1; 7],
1132+ /// Bit offset of `base_q_idx` in the packed frame header.
1133+ pub bit_offset_qindex: u32,
1134+ /// Bit offset of `segmentation_params()`.
1135+ pub bit_offset_segmentation: u32,
1136+ /// Bit offset of `loop_filter_params()`.
1137+ pub bit_offset_loopfilter_params: u32,
1138+ /// Bit offset of `cdef_params()`.
1139+ pub bit_offset_cdef_params: u32,
1140+ /// Bit length of `cdef_params()`.
1141+ pub size_in_bits_cdef_params: u32,
1142+ /// Byte offset of the frame OBU's size field.
1143+ pub byte_offset_frame_hdr_obu_size: u32,
1144+ /// Bit length of the frame header OBU.
1145+ pub size_in_bits_frame_hdr_obu: u32,
1146+ /// Tile group OBU header flags.
1147+ pub tile_group_obu_hdr_info: Av1TileGroupObuHdrInfo,
1148+ /// Number of skipped frames represented by this one.
1149+ pub number_skip_frames: u8,
1150+ pub(crate) reserved16bits3: u16,
1151+ /// Size reduction for skipped frames.
1152+ pub skip_frames_reduced_size: i32,
1153+ pub(crate) va_reserved: [u32; 16],
1154+}
1155+
1156+impl Default for EncPictureParameterBufferAV1 {
1157+ fn default() -> Self {
1158+ EncPictureParameterBufferAV1 {
1159+ frame_width_minus_1: 0,
1160+ frame_height_minus_1: 0,
1161+ reconstructed_frame: super::INVALID_SURFACE,
1162+ coded_buf: 0,
1163+ reference_frames: [super::INVALID_SURFACE; 8],
1164+ ref_frame_idx: [0; 7],
1165+ hierarchical_level_plus1: 0,
1166+ primary_ref_frame: 7, // PRIMARY_REF_NONE
1167+ order_hint: 0,
1168+ refresh_frame_flags: 0xff,
1169+ reserved8bits1: 0,
1170+ ref_frame_ctrl_l0: 0,
1171+ ref_frame_ctrl_l1: 0,
1172+ picture_flags: Av1EncPicFlags::default(),
1173+ seg_id_block_size: 0,
1174+ num_tile_groups_minus1: 0,
1175+ temporal_id: 0,
1176+ filter_level: [0; 2],
1177+ filter_level_u: 0,
1178+ filter_level_v: 0,
1179+ loop_filter_flags: 0,
1180+ superres_scale_denominator: 8,
1181+ interpolation_filter: 0,
1182+ ref_deltas: [0; 8],
1183+ mode_deltas: [0; 2],
1184+ base_qindex: 128,
1185+ y_dc_delta_q: 0,
1186+ u_dc_delta_q: 0,
1187+ u_ac_delta_q: 0,
1188+ v_dc_delta_q: 0,
1189+ v_ac_delta_q: 0,
1190+ min_base_qindex: 0,
1191+ max_base_qindex: 255,
1192+ qmatrix_flags: 0,
1193+ reserved16bits1: 0,
1194+ mode_control_flags: Av1ModeControlFlags::default(),
1195+ segments: EncSegParamAV1::default(),
1196+ tile_cols: 1,
1197+ tile_rows: 1,
1198+ reserved16bits2: 0,
1199+ width_in_sbs_minus_1: [0; 63],
1200+ height_in_sbs_minus_1: [0; 63],
1201+ context_update_tile_id: 0,
1202+ cdef_damping_minus_3: 0,
1203+ cdef_bits: 0,
1204+ cdef_y_strengths: [0; 8],
1205+ cdef_uv_strengths: [0; 8],
1206+ loop_restoration_flags: 0,
1207+ wm: [EncWarpedMotionParamsAV1::default(); 7],
1208+ bit_offset_qindex: 0,
1209+ bit_offset_segmentation: 0,
1210+ bit_offset_loopfilter_params: 0,
1211+ bit_offset_cdef_params: 0,
1212+ size_in_bits_cdef_params: 0,
1213+ byte_offset_frame_hdr_obu_size: 0,
1214+ size_in_bits_frame_hdr_obu: 0,
1215+ tile_group_obu_hdr_info: Av1TileGroupObuHdrInfo::default(),
1216+ number_skip_frames: 0,
1217+ reserved16bits3: 0,
1218+ skip_frames_reduced_size: 0,
1219+ va_reserved: [0; 16],
1220+ }
1221+ }
1222+}
1223+
1224+// SAFETY: `#[repr(C)]` transcription checked by the assertion block below.
1225+unsafe impl VaParam for EncPictureParameterBufferAV1 {
1226+ const TYPE: i32 = VAEncPictureParameterBufferType;
1227+}
1228+
1229+/// `VAEncTileGroupBufferAV1`, `va_enc_av1.h:590`.
1230+#[repr(C)]
1231+#[derive(Debug, Clone, Copy, Default)]
1232+pub struct EncTileGroupBufferAV1 {
1233+ /// First tile in the group.
1234+ pub tg_start: u8,
1235+ /// Last tile in the group.
1236+ pub tg_end: u8,
1237+ pub(crate) va_reserved: [u32; 4],
1238+}
1239+
1240+// SAFETY: `#[repr(C)]` transcription checked by the assertion block below.
1241+unsafe impl VaParam for EncTileGroupBufferAV1 {
1242+ const TYPE: i32 = VAEncSliceParameterBufferType;
1243+}
1244+
1245+// ---------------------------------------------------------------------------
1246+// ABI transcription check — `crates/ec-hw/abi-probe.c`, libva 1.23.0, x86_64:
1247+//
1248+// VAEncPackedHeaderParameterBuffer size=28 align=4 bit_length=4
1249+// has_emulation_bytes=8
1250+// VAEncMiscParameterRateControl size=60 (15 u32 payload words)
1251+// VAEncMiscParameterFrameRate size=24 (6 u32)
1252+// VAEncMiscParameterHRD size=24 (6 u32)
1253+// VAEncSequenceParameterBufferH264 size=1132 align=4 intra_period=4
1254+// picture_width_in_mbs=24
1255+// seq_fields=28
1256+// bit_depth_luma_minus8=32
1257+// offset_for_non_ref_pic=36
1258+// offset_for_ref_frame=44
1259+// frame_cropping_flag=1068
1260+// frame_crop_left_offset=1072
1261+// vui_parameters_present_flag=1088
1262+// vui_fields=1092
1263+// aspect_ratio_idc=1096
1264+// num_units_in_tick=1108
1265+// time_scale=1112
1266+// VAEncPictureParameterBufferH264 size=648 align=4 ReferenceFrames=36
1267+// coded_buf=612
1268+// pic_parameter_set_id=616
1269+// frame_num=620 pic_init_qp=622
1270+// pic_fields=628
1271+// VAEncSliceParameterBufferH264 size=3140 align=4 macroblock_info=8
1272+// slice_type=12 idr_pic_id=14
1273+// delta_pic_order_cnt_bottom=20
1274+// direct_spatial_mv_pred_flag=32
1275+// RefPicList0=36 RefPicList1=1188
1276+// luma_log2_weight_denom=2340
1277+// cabac_init_idc=3118
1278+// VAEncSequenceParameterBufferHEVC size=116 align=4 intra_period=4
1279+// pic_width_in_luma_samples=20
1280+// seq_fields=24
1281+// log2_min_luma_coding_block_size_minus3=28
1282+// pcm_sample_bit_depth_luma_minus1=36
1283+// vui_parameters_present_flag=52
1284+// vui_fields=56 aspect_ratio_idc=60
1285+// vui_num_units_in_tick=72
1286+// min_spatial_segmentation_idc=80
1287+// scc_fields=84
1288+// VAEncPictureParameterBufferHEVC size=576 align=4 reference_frames=28
1289+// coded_buf=448
1290+// collocated_ref_pic_index=452
1291+// column_width_minus1=460
1292+// row_height_minus1=479
1293+// log2_parallel_merge_level_minus2=500
1294+// nal_unit_type=505 pic_fields=508
1295+// hierarchical_level_plus1=512
1296+// scc_fields=514
1297+// VAEncSliceParameterBufferHEVC size=1076 align=4 num_ctu_in_slice=4
1298+// slice_type=8 ref_pic_list0=12
1299+// ref_pic_list1=432
1300+// luma_log2_weight_denom=852
1301+// max_num_merge_cand=1034
1302+// slice_fields=1040
1303+// pred_weight_table_bit_offset=1044
1304+// VAEncSequenceParameterBufferAV1 size=88 align=4 intra_period=4 seq_fields=16
1305+// order_hint_bits_minus_1=20
1306+// VAEncSegParamAV1 size=156 align=4 feature_data=2
1307+// feature_mask=130
1308+// VAEncWarpedMotionParamsAV1 size=56 align=4
1309+// VAEncPictureParameterBufferAV1 size=1032 align=4 reconstructed_frame=4
1310+// coded_buf=8
1311+// reference_frames=12
1312+// ref_frame_idx=44
1313+// ref_frame_ctrl_l0=56
1314+// picture_flags=64
1315+// seg_id_block_size=68
1316+// filter_level=71
1317+// loop_filter_flags=75
1318+// ref_deltas=78 base_qindex=88
1319+// min_base_qindex=94
1320+// qmatrix_flags=96
1321+// mode_control_flags=100
1322+// segments=104 tile_cols=260
1323+// width_in_sbs_minus_1=264
1324+// context_update_tile_id=516
1325+// cdef_damping_minus_3=518
1326+// loop_restoration_flags=536
1327+// wm=540 bit_offset_qindex=932
1328+// tile_group_obu_hdr_info=960
1329+// number_skip_frames=961
1330+// skip_frames_reduced_size=964
1331+// VAEncTileGroupBufferAV1 size=20 align=4
1332+const _: () = {
1333+ use std::mem::{align_of, offset_of, size_of};
1334+
1335+ assert!(
1336+ size_of::<PackedHeaderParameterBuffer>() == 28
1337+ && align_of::<PackedHeaderParameterBuffer>() == 4
1338+ );
1339+ assert!(offset_of!(PackedHeaderParameterBuffer, bit_length) == 4);
1340+ assert!(offset_of!(PackedHeaderParameterBuffer, has_emulation_bytes) == 8);
1341+
1342+ // Misc payloads are submitted as `{ type, words... }`; the word counts are
1343+ // the header sizes minus the 4-byte type each buffer carries.
1344+ assert!(size_of::<u32>() * (1 + 15) == 64);
1345+ assert!(size_of::<u32>() * (1 + 6) == 28);
1346+
1347+ assert!(
1348+ size_of::<EncSequenceParameterBufferH264>() == 1132
1349+ && align_of::<EncSequenceParameterBufferH264>() == 4
1350+ );
1351+ assert!(offset_of!(EncSequenceParameterBufferH264, intra_period) == 4);
1352+ assert!(offset_of!(EncSequenceParameterBufferH264, picture_width_in_mbs) == 24);
1353+ assert!(offset_of!(EncSequenceParameterBufferH264, seq_fields) == 28);
1354+ assert!(offset_of!(EncSequenceParameterBufferH264, bit_depth_luma_minus8) == 32);
1355+ assert!(offset_of!(EncSequenceParameterBufferH264, offset_for_non_ref_pic) == 36);
1356+ assert!(offset_of!(EncSequenceParameterBufferH264, offset_for_ref_frame) == 44);
1357+ assert!(offset_of!(EncSequenceParameterBufferH264, frame_cropping_flag) == 1068);
1358+ assert!(offset_of!(EncSequenceParameterBufferH264, frame_crop_left_offset) == 1072);
1359+ assert!(offset_of!(EncSequenceParameterBufferH264, vui_parameters_present_flag) == 1088);
1360+ assert!(offset_of!(EncSequenceParameterBufferH264, vui_fields) == 1092);
1361+ assert!(offset_of!(EncSequenceParameterBufferH264, aspect_ratio_idc) == 1096);
1362+ assert!(offset_of!(EncSequenceParameterBufferH264, num_units_in_tick) == 1108);
1363+ assert!(offset_of!(EncSequenceParameterBufferH264, time_scale) == 1112);
1364+
1365+ assert!(
1366+ size_of::<EncPictureParameterBufferH264>() == 648
1367+ && align_of::<EncPictureParameterBufferH264>() == 4
1368+ );
1369+ assert!(offset_of!(EncPictureParameterBufferH264, reference_frames) == 36);
1370+ assert!(offset_of!(EncPictureParameterBufferH264, coded_buf) == 612);
1371+ assert!(offset_of!(EncPictureParameterBufferH264, pic_parameter_set_id) == 616);
1372+ assert!(offset_of!(EncPictureParameterBufferH264, frame_num) == 620);
1373+ assert!(offset_of!(EncPictureParameterBufferH264, pic_init_qp) == 622);
1374+ assert!(offset_of!(EncPictureParameterBufferH264, pic_fields) == 628);
1375+
1376+ assert!(
1377+ size_of::<EncSliceParameterBufferH264>() == 3140
1378+ && align_of::<EncSliceParameterBufferH264>() == 4
1379+ );
1380+ assert!(offset_of!(EncSliceParameterBufferH264, macroblock_info) == 8);
1381+ assert!(offset_of!(EncSliceParameterBufferH264, slice_type) == 12);
1382+ assert!(offset_of!(EncSliceParameterBufferH264, idr_pic_id) == 14);
1383+ assert!(offset_of!(EncSliceParameterBufferH264, delta_pic_order_cnt_bottom) == 20);
1384+ assert!(offset_of!(EncSliceParameterBufferH264, direct_spatial_mv_pred_flag) == 32);
1385+ assert!(offset_of!(EncSliceParameterBufferH264, ref_pic_list0) == 36);
1386+ assert!(offset_of!(EncSliceParameterBufferH264, ref_pic_list1) == 1188);
1387+ assert!(offset_of!(EncSliceParameterBufferH264, luma_log2_weight_denom) == 2340);
1388+ assert!(offset_of!(EncSliceParameterBufferH264, cabac_init_idc) == 3118);
1389+
1390+ assert!(
1391+ size_of::<EncSequenceParameterBufferHEVC>() == 116
1392+ && align_of::<EncSequenceParameterBufferHEVC>() == 4
1393+ );
1394+ assert!(offset_of!(EncSequenceParameterBufferHEVC, intra_period) == 4);
1395+ assert!(offset_of!(EncSequenceParameterBufferHEVC, pic_width_in_luma_samples) == 20);
1396+ assert!(offset_of!(EncSequenceParameterBufferHEVC, seq_fields) == 24);
1397+ assert!(
1398+ offset_of!(
1399+ EncSequenceParameterBufferHEVC,
1400+ log2_min_luma_coding_block_size_minus3
1401+ ) == 28
1402+ );
1403+ assert!(
1404+ offset_of!(
1405+ EncSequenceParameterBufferHEVC,
1406+ pcm_sample_bit_depth_luma_minus1
1407+ ) == 36
1408+ );
1409+ assert!(offset_of!(EncSequenceParameterBufferHEVC, vui_parameters_present_flag) == 52);
1410+ assert!(offset_of!(EncSequenceParameterBufferHEVC, vui_fields) == 56);
1411+ assert!(offset_of!(EncSequenceParameterBufferHEVC, aspect_ratio_idc) == 60);
1412+ assert!(offset_of!(EncSequenceParameterBufferHEVC, vui_num_units_in_tick) == 72);
1413+ assert!(offset_of!(EncSequenceParameterBufferHEVC, min_spatial_segmentation_idc) == 80);
1414+ assert!(offset_of!(EncSequenceParameterBufferHEVC, scc_fields) == 84);
1415+
1416+ assert!(
1417+ size_of::<EncPictureParameterBufferHEVC>() == 576
1418+ && align_of::<EncPictureParameterBufferHEVC>() == 4
1419+ );
1420+ assert!(offset_of!(EncPictureParameterBufferHEVC, reference_frames) == 28);
1421+ assert!(offset_of!(EncPictureParameterBufferHEVC, coded_buf) == 448);
1422+ assert!(offset_of!(EncPictureParameterBufferHEVC, collocated_ref_pic_index) == 452);
1423+ assert!(offset_of!(EncPictureParameterBufferHEVC, column_width_minus1) == 460);
1424+ assert!(offset_of!(EncPictureParameterBufferHEVC, row_height_minus1) == 479);
1425+ assert!(
1426+ offset_of!(
1427+ EncPictureParameterBufferHEVC,
1428+ log2_parallel_merge_level_minus2
1429+ ) == 500
1430+ );
1431+ assert!(offset_of!(EncPictureParameterBufferHEVC, nal_unit_type) == 505);
1432+ assert!(offset_of!(EncPictureParameterBufferHEVC, pic_fields) == 508);
1433+ assert!(offset_of!(EncPictureParameterBufferHEVC, hierarchical_level_plus1) == 512);
1434+ assert!(offset_of!(EncPictureParameterBufferHEVC, scc_fields) == 514);
1435+
1436+ assert!(
1437+ size_of::<EncSliceParameterBufferHEVC>() == 1076
1438+ && align_of::<EncSliceParameterBufferHEVC>() == 4
1439+ );
1440+ assert!(offset_of!(EncSliceParameterBufferHEVC, num_ctu_in_slice) == 4);
1441+ assert!(offset_of!(EncSliceParameterBufferHEVC, slice_type) == 8);
1442+ assert!(offset_of!(EncSliceParameterBufferHEVC, ref_pic_list0) == 12);
1443+ assert!(offset_of!(EncSliceParameterBufferHEVC, ref_pic_list1) == 432);
1444+ assert!(offset_of!(EncSliceParameterBufferHEVC, luma_log2_weight_denom) == 852);
1445+ assert!(offset_of!(EncSliceParameterBufferHEVC, max_num_merge_cand) == 1034);
1446+ assert!(offset_of!(EncSliceParameterBufferHEVC, slice_fields) == 1040);
1447+ assert!(offset_of!(EncSliceParameterBufferHEVC, pred_weight_table_bit_offset) == 1044);
1448+
1449+ assert!(
1450+ size_of::<EncSequenceParameterBufferAV1>() == 88
1451+ && align_of::<EncSequenceParameterBufferAV1>() == 4
1452+ );
1453+ assert!(offset_of!(EncSequenceParameterBufferAV1, intra_period) == 4);
1454+ assert!(offset_of!(EncSequenceParameterBufferAV1, seq_fields) == 16);
1455+ assert!(offset_of!(EncSequenceParameterBufferAV1, order_hint_bits_minus_1) == 20);
1456+
1457+ assert!(size_of::<EncSegParamAV1>() == 156 && align_of::<EncSegParamAV1>() == 4);
1458+ assert!(offset_of!(EncSegParamAV1, feature_data) == 2);
1459+ assert!(offset_of!(EncSegParamAV1, feature_mask) == 130);
1460+
1461+ assert!(size_of::<EncWarpedMotionParamsAV1>() == 56);
1462+
1463+ assert!(
1464+ size_of::<EncPictureParameterBufferAV1>() == 1032
1465+ && align_of::<EncPictureParameterBufferAV1>() == 4
1466+ );
1467+ assert!(offset_of!(EncPictureParameterBufferAV1, reconstructed_frame) == 4);
1468+ assert!(offset_of!(EncPictureParameterBufferAV1, coded_buf) == 8);
1469+ assert!(offset_of!(EncPictureParameterBufferAV1, reference_frames) == 12);
1470+ assert!(offset_of!(EncPictureParameterBufferAV1, ref_frame_idx) == 44);
1471+ assert!(offset_of!(EncPictureParameterBufferAV1, ref_frame_ctrl_l0) == 56);
1472+ assert!(offset_of!(EncPictureParameterBufferAV1, picture_flags) == 64);
1473+ assert!(offset_of!(EncPictureParameterBufferAV1, seg_id_block_size) == 68);
1474+ assert!(offset_of!(EncPictureParameterBufferAV1, filter_level) == 71);
1475+ assert!(offset_of!(EncPictureParameterBufferAV1, loop_filter_flags) == 75);
1476+ assert!(offset_of!(EncPictureParameterBufferAV1, ref_deltas) == 78);
1477+ assert!(offset_of!(EncPictureParameterBufferAV1, base_qindex) == 88);
1478+ assert!(offset_of!(EncPictureParameterBufferAV1, min_base_qindex) == 94);
1479+ assert!(offset_of!(EncPictureParameterBufferAV1, qmatrix_flags) == 96);
1480+ assert!(offset_of!(EncPictureParameterBufferAV1, mode_control_flags) == 100);
1481+ assert!(offset_of!(EncPictureParameterBufferAV1, segments) == 104);
1482+ assert!(offset_of!(EncPictureParameterBufferAV1, tile_cols) == 260);
1483+ assert!(offset_of!(EncPictureParameterBufferAV1, width_in_sbs_minus_1) == 264);
1484+ assert!(offset_of!(EncPictureParameterBufferAV1, context_update_tile_id) == 516);
1485+ assert!(offset_of!(EncPictureParameterBufferAV1, cdef_damping_minus_3) == 518);
1486+ assert!(offset_of!(EncPictureParameterBufferAV1, loop_restoration_flags) == 536);
1487+ assert!(offset_of!(EncPictureParameterBufferAV1, wm) == 540);
1488+ assert!(offset_of!(EncPictureParameterBufferAV1, bit_offset_qindex) == 932);
1489+ assert!(offset_of!(EncPictureParameterBufferAV1, tile_group_obu_hdr_info) == 960);
1490+ assert!(offset_of!(EncPictureParameterBufferAV1, number_skip_frames) == 961);
1491+ assert!(offset_of!(EncPictureParameterBufferAV1, skip_frames_reduced_size) == 964);
1492+
1493+ assert!(size_of::<EncTileGroupBufferAV1>() == 20);
1494+};
crates/ec-hw/src/params/h264.rsadded+376 -0
@@ -0,0 +1,376 @@
1+//! H.264 decode parameter buffers (`va.h:3572-3716`).
2+
3+use ec_va::sys::{
4+ VAIQMatrixBufferType, VAPictureParameterBufferType, VASliceParameterBufferType, VASurfaceID,
5+};
6+
7+use super::{INVALID_SURFACE, VaParam};
8+use crate::va_bits;
9+
10+/// `VA_PICTURE_H264_INVALID` (`va.h:3583`).
11+pub const PICTURE_INVALID: u32 = 0x0000_0001;
12+/// `VA_PICTURE_H264_TOP_FIELD`.
13+pub const PICTURE_TOP_FIELD: u32 = 0x0000_0002;
14+/// `VA_PICTURE_H264_BOTTOM_FIELD`.
15+pub const PICTURE_BOTTOM_FIELD: u32 = 0x0000_0004;
16+/// `VA_PICTURE_H264_SHORT_TERM_REFERENCE`.
17+pub const PICTURE_SHORT_TERM_REFERENCE: u32 = 0x0000_0008;
18+/// `VA_PICTURE_H264_LONG_TERM_REFERENCE`.
19+pub const PICTURE_LONG_TERM_REFERENCE: u32 = 0x0000_0010;
20+
21+/// `VAPictureH264`, `va.h:3572`.
22+#[repr(C)]
23+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24+pub struct VAPictureH264 {
25+ /// Surface holding the picture, or [`INVALID_SURFACE`].
26+ pub picture_id: VASurfaceID,
27+ /// `FrameNum` (short term) or `LongTermFrameIdx` (long term).
28+ pub frame_idx: u32,
29+ /// `VA_PICTURE_H264_*` bitmask.
30+ pub flags: u32,
31+ /// `TopFieldOrderCnt`.
32+ pub top_field_order_cnt: i32,
33+ /// `BottomFieldOrderCnt`.
34+ pub bottom_field_order_cnt: i32,
35+ pub(crate) va_reserved: [u32; 4],
36+}
37+
38+impl VAPictureH264 {
39+ /// The "no picture here" entry every unused list slot must carry.
40+ ///
41+ /// Not `Default::default()` by accident: a zeroed entry names surface 0,
42+ /// which is a real surface id, and drivers have been known to read it.
43+ pub const INVALID: VAPictureH264 = VAPictureH264 {
44+ picture_id: INVALID_SURFACE,
45+ frame_idx: 0,
46+ flags: PICTURE_INVALID,
47+ top_field_order_cnt: 0,
48+ bottom_field_order_cnt: 0,
49+ va_reserved: [0; 4],
50+ };
51+
52+ /// A frame picture with both field order counts set to its POC.
53+ pub fn frame(picture_id: VASurfaceID, frame_idx: u32, poc: i32, flags: u32) -> VAPictureH264 {
54+ VAPictureH264 {
55+ picture_id,
56+ frame_idx,
57+ flags,
58+ top_field_order_cnt: poc,
59+ bottom_field_order_cnt: poc,
60+ va_reserved: [0; 4],
61+ }
62+ }
63+}
64+
65+impl Default for VAPictureH264 {
66+ fn default() -> Self {
67+ VAPictureH264::INVALID
68+ }
69+}
70+
71+va_bits! {
72+ /// `VAPictureParameterBufferH264::seq_fields`.
73+ SeqFields: u32 {
74+ chroma_format_idc: 2,
75+ residual_colour_transform_flag: 1,
76+ gaps_in_frame_num_value_allowed_flag: 1,
77+ frame_mbs_only_flag: 1,
78+ mb_adaptive_frame_field_flag: 1,
79+ direct_8x8_inference_flag: 1,
80+ min_luma_bipred_size8x8: 1,
81+ log2_max_frame_num_minus4: 4,
82+ pic_order_cnt_type: 2,
83+ log2_max_pic_order_cnt_lsb_minus4: 4,
84+ delta_pic_order_always_zero_flag: 1,
85+ }
86+}
87+
88+va_bits! {
89+ /// `VAPictureParameterBufferH264::pic_fields`.
90+ PicFields: u32 {
91+ entropy_coding_mode_flag: 1,
92+ weighted_pred_flag: 1,
93+ weighted_bipred_idc: 2,
94+ transform_8x8_mode_flag: 1,
95+ field_pic_flag: 1,
96+ constrained_intra_pred_flag: 1,
97+ pic_order_present_flag: 1,
98+ deblocking_filter_control_present_flag: 1,
99+ redundant_pic_cnt_present_flag: 1,
100+ reference_pic_flag: 1,
101+ }
102+}
103+
104+/// `VAPictureParameterBufferH264`, `va.h:3594`.
105+#[repr(C)]
106+#[derive(Debug, Clone, Copy)]
107+pub struct PictureParameterBufferH264 {
108+ /// The picture being decoded.
109+ pub curr_pic: VAPictureH264,
110+ /// Every picture in the DPB; unused slots are [`VAPictureH264::INVALID`].
111+ pub reference_frames: [VAPictureH264; 16],
112+ /// `PicWidthInMbs - 1`.
113+ pub picture_width_in_mbs_minus1: u16,
114+ /// `PicHeightInMapUnits - 1` for a frame-only stream.
115+ pub picture_height_in_mbs_minus1: u16,
116+ /// `bit_depth_luma_minus8`.
117+ pub bit_depth_luma_minus8: u8,
118+ /// `bit_depth_chroma_minus8`.
119+ pub bit_depth_chroma_minus8: u8,
120+ /// `max_num_ref_frames`.
121+ pub num_ref_frames: u8,
122+ /// Sequence flags.
123+ pub seq_fields: SeqFields,
124+ /// Deprecated FMO fields; libva ignores them, we write zero.
125+ pub(crate) num_slice_groups_minus1: u8,
126+ pub(crate) slice_group_map_type: u8,
127+ pub(crate) slice_group_change_rate_minus1: u16,
128+ /// `pic_init_qp_minus26`.
129+ pub pic_init_qp_minus26: i8,
130+ /// `pic_init_qs_minus26`.
131+ pub pic_init_qs_minus26: i8,
132+ /// `chroma_qp_index_offset`.
133+ pub chroma_qp_index_offset: i8,
134+ /// `second_chroma_qp_index_offset`.
135+ pub second_chroma_qp_index_offset: i8,
136+ /// Picture flags.
137+ pub pic_fields: PicFields,
138+ /// `frame_num` of the current picture.
139+ pub frame_num: u16,
140+ pub(crate) va_reserved: [u32; 8],
141+}
142+
143+impl Default for PictureParameterBufferH264 {
144+ fn default() -> Self {
145+ PictureParameterBufferH264 {
146+ curr_pic: VAPictureH264::INVALID,
147+ reference_frames: [VAPictureH264::INVALID; 16],
148+ picture_width_in_mbs_minus1: 0,
149+ picture_height_in_mbs_minus1: 0,
150+ bit_depth_luma_minus8: 0,
151+ bit_depth_chroma_minus8: 0,
152+ num_ref_frames: 0,
153+ seq_fields: SeqFields::default(),
154+ num_slice_groups_minus1: 0,
155+ slice_group_map_type: 0,
156+ slice_group_change_rate_minus1: 0,
157+ pic_init_qp_minus26: 0,
158+ pic_init_qs_minus26: 0,
159+ chroma_qp_index_offset: 0,
160+ second_chroma_qp_index_offset: 0,
161+ pic_fields: PicFields::default(),
162+ frame_num: 0,
163+ va_reserved: [0; 8],
164+ }
165+ }
166+}
167+
168+// SAFETY: `#[repr(C)]` transcription of `VAPictureParameterBufferH264`, checked
169+// field for field by the assertion block below; every field is an integer or an
170+// array of integers, so any bit pattern is valid.
171+unsafe impl VaParam for PictureParameterBufferH264 {
172+ const TYPE: i32 = VAPictureParameterBufferType;
173+}
174+
175+/// `VAIQMatrixBufferH264`, `va.h:3648`.
176+#[repr(C)]
177+#[derive(Debug, Clone, Copy)]
178+pub struct IQMatrixBufferH264 {
179+ /// 4x4 scaling lists in raster scan order.
180+ pub scaling_list_4x4: [[u8; 16]; 6],
181+ /// 8x8 scaling lists in raster scan order.
182+ pub scaling_list_8x8: [[u8; 64]; 2],
183+ pub(crate) va_reserved: [u32; 4],
184+}
185+
186+impl Default for IQMatrixBufferH264 {
187+ fn default() -> Self {
188+ IQMatrixBufferH264 {
189+ scaling_list_4x4: [[16; 16]; 6],
190+ scaling_list_8x8: [[16; 64]; 2],
191+ va_reserved: [0; 4],
192+ }
193+ }
194+}
195+
196+// SAFETY: as `PictureParameterBufferH264`; plain `u8` arrays plus padding.
197+unsafe impl VaParam for IQMatrixBufferH264 {
198+ const TYPE: i32 = VAIQMatrixBufferType;
199+}
200+
201+/// `VASliceParameterBufferH264`, `va.h:3659`.
202+///
203+/// The weight tables are the bulk of it: 3 KB per slice, which is why the
204+/// decoder builds one on the stack and hands it straight to `vaCreateBuffer`
205+/// rather than keeping a queue of them.
206+#[repr(C)]
207+#[derive(Debug, Clone, Copy)]
208+pub struct SliceParameterBufferH264 {
209+ /// Bytes of slice data for this slice.
210+ pub slice_data_size: u32,
211+ /// Offset of this slice's NAL unit within the data buffer.
212+ pub slice_data_offset: u32,
213+ /// `VA_SLICE_DATA_FLAG_*`.
214+ pub slice_data_flag: u32,
215+ /// Bits from the start of the NAL unit byte to `slice_data()`, counted in
216+ /// the *unescaped* RBSP.
217+ pub slice_data_bit_offset: u16,
218+ /// `first_mb_in_slice`.
219+ pub first_mb_in_slice: u16,
220+ /// `slice_type` (0..=4, i.e. the modulo-5 value).
221+ pub slice_type: u8,
222+ /// `direct_spatial_mv_pred_flag`.
223+ pub direct_spatial_mv_pred_flag: u8,
224+ /// `num_ref_idx_l0_active_minus1`, override applied.
225+ pub num_ref_idx_l0_active_minus1: u8,
226+ /// `num_ref_idx_l1_active_minus1`, override applied.
227+ pub num_ref_idx_l1_active_minus1: u8,
228+ /// `cabac_init_idc`.
229+ pub cabac_init_idc: u8,
230+ /// `slice_qp_delta`.
231+ pub slice_qp_delta: i8,
232+ /// `disable_deblocking_filter_idc`.
233+ pub disable_deblocking_filter_idc: u8,
234+ /// `slice_alpha_c0_offset_div2`.
235+ pub slice_alpha_c0_offset_div2: i8,
236+ /// `slice_beta_offset_div2`.
237+ pub slice_beta_offset_div2: i8,
238+ /// `RefPicList0` after initialisation and modification (8.2.4).
239+ pub ref_pic_list0: [VAPictureH264; 32],
240+ /// `RefPicList1`.
241+ pub ref_pic_list1: [VAPictureH264; 32],
242+ /// `luma_log2_weight_denom`.
243+ pub luma_log2_weight_denom: u8,
244+ /// `chroma_log2_weight_denom`.
245+ pub chroma_log2_weight_denom: u8,
246+ /// Whether any `luma_weight_l0_flag` was set.
247+ pub luma_weight_l0_flag: u8,
248+ /// `luma_weight_l0`.
249+ pub luma_weight_l0: [i16; 32],
250+ /// `luma_offset_l0`.
251+ pub luma_offset_l0: [i16; 32],
252+ /// Whether any `chroma_weight_l0_flag` was set.
253+ pub chroma_weight_l0_flag: u8,
254+ /// `chroma_weight_l0`.
255+ pub chroma_weight_l0: [[i16; 2]; 32],
256+ /// `chroma_offset_l0`.
257+ pub chroma_offset_l0: [[i16; 2]; 32],
258+ /// Whether any `luma_weight_l1_flag` was set.
259+ pub luma_weight_l1_flag: u8,
260+ /// `luma_weight_l1`.
261+ pub luma_weight_l1: [i16; 32],
262+ /// `luma_offset_l1`.
263+ pub luma_offset_l1: [i16; 32],
264+ /// Whether any `chroma_weight_l1_flag` was set.
265+ pub chroma_weight_l1_flag: u8,
266+ /// `chroma_weight_l1`.
267+ pub chroma_weight_l1: [[i16; 2]; 32],
268+ /// `chroma_offset_l1`.
269+ pub chroma_offset_l1: [[i16; 2]; 32],
270+ pub(crate) va_reserved: [u32; 4],
271+}
272+
273+impl Default for SliceParameterBufferH264 {
274+ fn default() -> Self {
275+ SliceParameterBufferH264 {
276+ slice_data_size: 0,
277+ slice_data_offset: 0,
278+ slice_data_flag: 0,
279+ slice_data_bit_offset: 0,
280+ first_mb_in_slice: 0,
281+ slice_type: 0,
282+ direct_spatial_mv_pred_flag: 0,
283+ num_ref_idx_l0_active_minus1: 0,
284+ num_ref_idx_l1_active_minus1: 0,
285+ cabac_init_idc: 0,
286+ slice_qp_delta: 0,
287+ disable_deblocking_filter_idc: 0,
288+ slice_alpha_c0_offset_div2: 0,
289+ slice_beta_offset_div2: 0,
290+ ref_pic_list0: [VAPictureH264::INVALID; 32],
291+ ref_pic_list1: [VAPictureH264::INVALID; 32],
292+ luma_log2_weight_denom: 0,
293+ chroma_log2_weight_denom: 0,
294+ luma_weight_l0_flag: 0,
295+ luma_weight_l0: [0; 32],
296+ luma_offset_l0: [0; 32],
297+ chroma_weight_l0_flag: 0,
298+ chroma_weight_l0: [[0; 2]; 32],
299+ chroma_offset_l0: [[0; 2]; 32],
300+ luma_weight_l1_flag: 0,
301+ luma_weight_l1: [0; 32],
302+ luma_offset_l1: [0; 32],
303+ chroma_weight_l1_flag: 0,
304+ chroma_weight_l1: [[0; 2]; 32],
305+ chroma_offset_l1: [[0; 2]; 32],
306+ va_reserved: [0; 4],
307+ }
308+ }
309+}
310+
311+// SAFETY: as `PictureParameterBufferH264`.
312+unsafe impl VaParam for SliceParameterBufferH264 {
313+ const TYPE: i32 = VASliceParameterBufferType;
314+}
315+
316+// ---------------------------------------------------------------------------
317+// ABI transcription check — `crates/ec-hw/abi-probe.c`, libva 1.23.0, x86_64:
318+//
319+// VAPictureH264 size=36 align=4 frame_idx=4 flags=8
320+// TopFieldOrderCnt=12
321+// BottomFieldOrderCnt=16
322+// VAPictureParameterBufferH264 size=672 align=4 ReferenceFrames=36
323+// picture_width_in_mbs_minus1=612
324+// bit_depth_luma_minus8=616
325+// num_ref_frames=618 seq_fields=620
326+// pic_init_qp_minus26=628
327+// pic_fields=632 frame_num=636
328+// VAIQMatrixBufferH264 size=240 align=4 ScalingList8x8=96
329+// VASliceParameterBufferH264 size=3128 align=4 slice_data_bit_offset=12
330+// slice_type=16 cabac_init_idc=20
331+// RefPicList0=28 RefPicList1=1180
332+// luma_log2_weight_denom=2332
333+// luma_weight_l0=2336
334+// chroma_weight_l0=2466
335+// luma_weight_l1_flag=2722
336+// chroma_offset_l1=2982
337+const _: () = {
338+ use std::mem::{align_of, offset_of, size_of};
339+
340+ assert!(size_of::<VAPictureH264>() == 36 && align_of::<VAPictureH264>() == 4);
341+ assert!(offset_of!(VAPictureH264, frame_idx) == 4);
342+ assert!(offset_of!(VAPictureH264, flags) == 8);
343+ assert!(offset_of!(VAPictureH264, top_field_order_cnt) == 12);
344+ assert!(offset_of!(VAPictureH264, bottom_field_order_cnt) == 16);
345+
346+ assert!(
347+ size_of::<PictureParameterBufferH264>() == 672
348+ && align_of::<PictureParameterBufferH264>() == 4
349+ );
350+ assert!(offset_of!(PictureParameterBufferH264, reference_frames) == 36);
351+ assert!(offset_of!(PictureParameterBufferH264, picture_width_in_mbs_minus1) == 612);
352+ assert!(offset_of!(PictureParameterBufferH264, bit_depth_luma_minus8) == 616);
353+ assert!(offset_of!(PictureParameterBufferH264, num_ref_frames) == 618);
354+ assert!(offset_of!(PictureParameterBufferH264, seq_fields) == 620);
355+ assert!(offset_of!(PictureParameterBufferH264, pic_init_qp_minus26) == 628);
356+ assert!(offset_of!(PictureParameterBufferH264, pic_fields) == 632);
357+ assert!(offset_of!(PictureParameterBufferH264, frame_num) == 636);
358+
359+ assert!(size_of::<IQMatrixBufferH264>() == 240 && align_of::<IQMatrixBufferH264>() == 4);
360+ assert!(offset_of!(IQMatrixBufferH264, scaling_list_8x8) == 96);
361+
362+ assert!(
363+ size_of::<SliceParameterBufferH264>() == 3128
364+ && align_of::<SliceParameterBufferH264>() == 4
365+ );
366+ assert!(offset_of!(SliceParameterBufferH264, slice_data_bit_offset) == 12);
367+ assert!(offset_of!(SliceParameterBufferH264, slice_type) == 16);
368+ assert!(offset_of!(SliceParameterBufferH264, cabac_init_idc) == 20);
369+ assert!(offset_of!(SliceParameterBufferH264, ref_pic_list0) == 28);
370+ assert!(offset_of!(SliceParameterBufferH264, ref_pic_list1) == 1180);
371+ assert!(offset_of!(SliceParameterBufferH264, luma_log2_weight_denom) == 2332);
372+ assert!(offset_of!(SliceParameterBufferH264, luma_weight_l0) == 2336);
373+ assert!(offset_of!(SliceParameterBufferH264, chroma_weight_l0) == 2466);
374+ assert!(offset_of!(SliceParameterBufferH264, luma_weight_l1_flag) == 2722);
375+ assert!(offset_of!(SliceParameterBufferH264, chroma_offset_l1) == 2982);
376+};
crates/ec-hw/src/params/hevc.rsadded+473 -0
@@ -0,0 +1,473 @@
1+//! HEVC decode parameter buffers (`va.h:5287`, `va_dec_hevc.h`).
2+
3+use ec_va::sys::{
4+ VAIQMatrixBufferType, VAPictureParameterBufferType, VASliceParameterBufferType, VASurfaceID,
5+};
6+
7+use super::{INVALID_SURFACE, VaParam};
8+use crate::va_bits;
9+
10+/// `VA_PICTURE_HEVC_INVALID`.
11+pub const PICTURE_INVALID: u32 = 0x0000_0001;
12+/// `VA_PICTURE_HEVC_FIELD_PIC`.
13+pub const PICTURE_FIELD_PIC: u32 = 0x0000_0002;
14+/// `VA_PICTURE_HEVC_BOTTOM_FIELD`.
15+pub const PICTURE_BOTTOM_FIELD: u32 = 0x0000_0004;
16+/// `VA_PICTURE_HEVC_LONG_TERM_REFERENCE`.
17+pub const PICTURE_LONG_TERM_REFERENCE: u32 = 0x0000_0008;
18+/// `VA_PICTURE_HEVC_RPS_ST_CURR_BEFORE`.
19+pub const PICTURE_RPS_ST_CURR_BEFORE: u32 = 0x0000_0010;
20+/// `VA_PICTURE_HEVC_RPS_ST_CURR_AFTER`.
21+pub const PICTURE_RPS_ST_CURR_AFTER: u32 = 0x0000_0020;
22+/// `VA_PICTURE_HEVC_RPS_LT_CURR`.
23+pub const PICTURE_RPS_LT_CURR: u32 = 0x0000_0040;
24+
25+/// `VAPictureHEVC`, `va.h:5287`.
26+#[repr(C)]
27+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28+pub struct VAPictureHEVC {
29+ /// Surface holding the picture, or [`INVALID_SURFACE`].
30+ pub picture_id: VASurfaceID,
31+ /// `PicOrderCntVal`.
32+ pub pic_order_cnt: i32,
33+ /// `VA_PICTURE_HEVC_*` bitmask.
34+ pub flags: u32,
35+ pub(crate) va_reserved: [u32; 4],
36+}
37+
38+impl VAPictureHEVC {
39+ /// The "no picture here" entry for unused reference slots.
40+ pub const INVALID: VAPictureHEVC = VAPictureHEVC {
41+ picture_id: INVALID_SURFACE,
42+ pic_order_cnt: 0,
43+ flags: PICTURE_INVALID,
44+ va_reserved: [0; 4],
45+ };
46+
47+ /// A reference or current picture.
48+ pub fn new(picture_id: VASurfaceID, pic_order_cnt: i32, flags: u32) -> VAPictureHEVC {
49+ VAPictureHEVC {
50+ picture_id,
51+ pic_order_cnt,
52+ flags,
53+ va_reserved: [0; 4],
54+ }
55+ }
56+}
57+
58+impl Default for VAPictureHEVC {
59+ fn default() -> Self {
60+ VAPictureHEVC::INVALID
61+ }
62+}
63+
64+va_bits! {
65+ /// `VAPictureParameterBufferHEVC::pic_fields`.
66+ PicFields: u32 {
67+ chroma_format_idc: 2,
68+ separate_colour_plane_flag: 1,
69+ pcm_enabled_flag: 1,
70+ scaling_list_enabled_flag: 1,
71+ transform_skip_enabled_flag: 1,
72+ amp_enabled_flag: 1,
73+ strong_intra_smoothing_enabled_flag: 1,
74+ sign_data_hiding_enabled_flag: 1,
75+ constrained_intra_pred_flag: 1,
76+ cu_qp_delta_enabled_flag: 1,
77+ weighted_pred_flag: 1,
78+ weighted_bipred_flag: 1,
79+ transquant_bypass_enabled_flag: 1,
80+ tiles_enabled_flag: 1,
81+ entropy_coding_sync_enabled_flag: 1,
82+ pps_loop_filter_across_slices_enabled_flag: 1,
83+ loop_filter_across_tiles_enabled_flag: 1,
84+ pcm_loop_filter_disabled_flag: 1,
85+ no_pic_reordering_flag: 1,
86+ no_bi_pred_flag: 1,
87+ }
88+}
89+
90+va_bits! {
91+ /// `VAPictureParameterBufferHEVC::slice_parsing_fields`.
92+ SliceParsingFields: u32 {
93+ lists_modification_present_flag: 1,
94+ long_term_ref_pics_present_flag: 1,
95+ sps_temporal_mvp_enabled_flag: 1,
96+ cabac_init_present_flag: 1,
97+ output_flag_present_flag: 1,
98+ dependent_slice_segments_enabled_flag: 1,
99+ pps_slice_chroma_qp_offsets_present_flag: 1,
100+ sample_adaptive_offset_enabled_flag: 1,
101+ deblocking_filter_override_enabled_flag: 1,
102+ pps_disable_deblocking_filter_flag: 1,
103+ slice_segment_header_extension_present_flag: 1,
104+ rap_pic_flag: 1,
105+ idr_pic_flag: 1,
106+ intra_pic_flag: 1,
107+ }
108+}
109+
110+/// `VAPictureParameterBufferHEVC`, `va_dec_hevc.h:57`.
111+#[repr(C)]
112+#[derive(Debug, Clone, Copy)]
113+pub struct PictureParameterBufferHEVC {
114+ /// The picture being decoded.
115+ pub curr_pic: VAPictureHEVC,
116+ /// The DPB; unused slots are [`VAPictureHEVC::INVALID`].
117+ pub reference_frames: [VAPictureHEVC; 15],
118+ /// `pic_width_in_luma_samples`.
119+ pub pic_width_in_luma_samples: u16,
120+ /// `pic_height_in_luma_samples`.
121+ pub pic_height_in_luma_samples: u16,
122+ /// Picture flags.
123+ pub pic_fields: PicFields,
124+ /// `sps_max_dec_pic_buffering_minus1`.
125+ pub sps_max_dec_pic_buffering_minus1: u8,
126+ /// `bit_depth_luma_minus8`.
127+ pub bit_depth_luma_minus8: u8,
128+ /// `bit_depth_chroma_minus8`.
129+ pub bit_depth_chroma_minus8: u8,
130+ /// `pcm_sample_bit_depth_luma_minus1`.
131+ pub pcm_sample_bit_depth_luma_minus1: u8,
132+ /// `pcm_sample_bit_depth_chroma_minus1`.
133+ pub pcm_sample_bit_depth_chroma_minus1: u8,
134+ /// `log2_min_luma_coding_block_size_minus3`.
135+ pub log2_min_luma_coding_block_size_minus3: u8,
136+ /// `log2_diff_max_min_luma_coding_block_size`.
137+ pub log2_diff_max_min_luma_coding_block_size: u8,
138+ /// `log2_min_transform_block_size_minus2`.
139+ pub log2_min_transform_block_size_minus2: u8,
140+ /// `log2_diff_max_min_transform_block_size`.
141+ pub log2_diff_max_min_transform_block_size: u8,
142+ /// `log2_min_pcm_luma_coding_block_size_minus3`.
143+ pub log2_min_pcm_luma_coding_block_size_minus3: u8,
144+ /// `log2_diff_max_min_pcm_luma_coding_block_size`.
145+ pub log2_diff_max_min_pcm_luma_coding_block_size: u8,
146+ /// `max_transform_hierarchy_depth_intra`.
147+ pub max_transform_hierarchy_depth_intra: u8,
148+ /// `max_transform_hierarchy_depth_inter`.
149+ pub max_transform_hierarchy_depth_inter: u8,
150+ /// `init_qp_minus26`.
151+ pub init_qp_minus26: i8,
152+ /// `diff_cu_qp_delta_depth`.
153+ pub diff_cu_qp_delta_depth: u8,
154+ /// `pps_cb_qp_offset`.
155+ pub pps_cb_qp_offset: i8,
156+ /// `pps_cr_qp_offset`.
157+ pub pps_cr_qp_offset: i8,
158+ /// `log2_parallel_merge_level_minus2`.
159+ pub log2_parallel_merge_level_minus2: u8,
160+ /// `num_tile_columns_minus1`.
161+ pub num_tile_columns_minus1: u8,
162+ /// `num_tile_rows_minus1`.
163+ pub num_tile_rows_minus1: u8,
164+ /// `column_width_minus1`, filled even for uniform spacing.
165+ pub column_width_minus1: [u16; 19],
166+ /// `row_height_minus1`, filled even for uniform spacing.
167+ pub row_height_minus1: [u16; 21],
168+ /// Flags a driver needs to parse slice segment headers.
169+ pub slice_parsing_fields: SliceParsingFields,
170+ /// `log2_max_pic_order_cnt_lsb_minus4`.
171+ pub log2_max_pic_order_cnt_lsb_minus4: u8,
172+ /// `num_short_term_ref_pic_sets`.
173+ pub num_short_term_ref_pic_sets: u8,
174+ /// `num_long_term_ref_pics_sps`.
175+ pub num_long_term_ref_pic_sps: u8,
176+ /// `num_ref_idx_l0_default_active_minus1`.
177+ pub num_ref_idx_l0_default_active_minus1: u8,
178+ /// `num_ref_idx_l1_default_active_minus1`.
179+ pub num_ref_idx_l1_default_active_minus1: u8,
180+ /// `pps_beta_offset_div2`.
181+ pub pps_beta_offset_div2: i8,
182+ /// `pps_tc_offset_div2`.
183+ pub pps_tc_offset_div2: i8,
184+ /// `num_extra_slice_header_bits`.
185+ pub num_extra_slice_header_bits: u8,
186+ /// Size in bits of the `st_ref_pic_set()` written in the slice header, so
187+ /// the driver can skip it; zero when the slice referenced an SPS set.
188+ pub st_rps_bits: u32,
189+ pub(crate) va_reserved: [u32; 8],
190+}
191+
192+impl Default for PictureParameterBufferHEVC {
193+ fn default() -> Self {
194+ PictureParameterBufferHEVC {
195+ curr_pic: VAPictureHEVC::INVALID,
196+ reference_frames: [VAPictureHEVC::INVALID; 15],
197+ pic_width_in_luma_samples: 0,
198+ pic_height_in_luma_samples: 0,
199+ pic_fields: PicFields::default(),
200+ sps_max_dec_pic_buffering_minus1: 0,
201+ bit_depth_luma_minus8: 0,
202+ bit_depth_chroma_minus8: 0,
203+ pcm_sample_bit_depth_luma_minus1: 0,
204+ pcm_sample_bit_depth_chroma_minus1: 0,
205+ log2_min_luma_coding_block_size_minus3: 0,
206+ log2_diff_max_min_luma_coding_block_size: 0,
207+ log2_min_transform_block_size_minus2: 0,
208+ log2_diff_max_min_transform_block_size: 0,
209+ log2_min_pcm_luma_coding_block_size_minus3: 0,
210+ log2_diff_max_min_pcm_luma_coding_block_size: 0,
211+ max_transform_hierarchy_depth_intra: 0,
212+ max_transform_hierarchy_depth_inter: 0,
213+ init_qp_minus26: 0,
214+ diff_cu_qp_delta_depth: 0,
215+ pps_cb_qp_offset: 0,
216+ pps_cr_qp_offset: 0,
217+ log2_parallel_merge_level_minus2: 0,
218+ num_tile_columns_minus1: 0,
219+ num_tile_rows_minus1: 0,
220+ column_width_minus1: [0; 19],
221+ row_height_minus1: [0; 21],
222+ slice_parsing_fields: SliceParsingFields::default(),
223+ log2_max_pic_order_cnt_lsb_minus4: 0,
224+ num_short_term_ref_pic_sets: 0,
225+ num_long_term_ref_pic_sps: 0,
226+ num_ref_idx_l0_default_active_minus1: 0,
227+ num_ref_idx_l1_default_active_minus1: 0,
228+ pps_beta_offset_div2: 0,
229+ pps_tc_offset_div2: 0,
230+ num_extra_slice_header_bits: 0,
231+ st_rps_bits: 0,
232+ va_reserved: [0; 8],
233+ }
234+ }
235+}
236+
237+// SAFETY: `#[repr(C)]` transcription of `VAPictureParameterBufferHEVC`, checked
238+// by the assertion block below; all fields are integers or integer arrays.
239+unsafe impl VaParam for PictureParameterBufferHEVC {
240+ const TYPE: i32 = VAPictureParameterBufferType;
241+}
242+
243+va_bits! {
244+ /// `VASliceParameterBufferHEVC::LongSliceFlags`.
245+ LongSliceFlags: u32 {
246+ last_slice_of_pic: 1,
247+ dependent_slice_segment_flag: 1,
248+ slice_type: 2,
249+ color_plane_id: 2,
250+ slice_sao_luma_flag: 1,
251+ slice_sao_chroma_flag: 1,
252+ mvd_l1_zero_flag: 1,
253+ cabac_init_flag: 1,
254+ slice_temporal_mvp_enabled_flag: 1,
255+ slice_deblocking_filter_disabled_flag: 1,
256+ collocated_from_l0_flag: 1,
257+ slice_loop_filter_across_slices_enabled_flag: 1,
258+ }
259+}
260+
261+/// `VASliceParameterBufferHEVC`, `va_dec_hevc.h:352`.
262+#[repr(C)]
263+#[derive(Debug, Clone, Copy)]
264+pub struct SliceParameterBufferHEVC {
265+ /// Bytes of slice data, NAL unit header included.
266+ pub slice_data_size: u32,
267+ /// Offset of this slice's NAL unit within the data buffer.
268+ pub slice_data_offset: u32,
269+ /// `VA_SLICE_DATA_FLAG_*`.
270+ pub slice_data_flag: u32,
271+ /// Bytes from the NAL unit header to `slice_data()`, in escaped bytes.
272+ pub slice_data_byte_offset: u32,
273+ /// `slice_segment_address`.
274+ pub slice_segment_address: u32,
275+ /// Indices into `reference_frames`, `0xff` for unused entries.
276+ pub ref_pic_list: [[u8; 15]; 2],
277+ /// Slice flags.
278+ pub long_slice_flags: LongSliceFlags,
279+ /// Index into `ref_pic_list`, `0xff` when there is no collocated picture.
280+ pub collocated_ref_idx: u8,
281+ /// `num_ref_idx_l0_active_minus1`, override applied.
282+ pub num_ref_idx_l0_active_minus1: u8,
283+ /// `num_ref_idx_l1_active_minus1`, override applied.
284+ pub num_ref_idx_l1_active_minus1: u8,
285+ /// `slice_qp_delta`.
286+ pub slice_qp_delta: i8,
287+ /// `slice_cb_qp_offset`.
288+ pub slice_cb_qp_offset: i8,
289+ /// `slice_cr_qp_offset`.
290+ pub slice_cr_qp_offset: i8,
291+ /// `slice_beta_offset_div2`.
292+ pub slice_beta_offset_div2: i8,
293+ /// `slice_tc_offset_div2`.
294+ pub slice_tc_offset_div2: i8,
295+ /// `luma_log2_weight_denom`.
296+ pub luma_log2_weight_denom: u8,
297+ /// `delta_chroma_log2_weight_denom`.
298+ pub delta_chroma_log2_weight_denom: i8,
299+ /// `delta_luma_weight_l0`.
300+ pub delta_luma_weight_l0: [i8; 15],
301+ /// `luma_offset_l0`.
302+ pub luma_offset_l0: [i8; 15],
303+ /// `delta_chroma_weight_l0`.
304+ pub delta_chroma_weight_l0: [[i8; 2]; 15],
305+ /// `ChromaOffsetL0`.
306+ pub chroma_offset_l0: [[i8; 2]; 15],
307+ /// `delta_luma_weight_l1`.
308+ pub delta_luma_weight_l1: [i8; 15],
309+ /// `luma_offset_l1`.
310+ pub luma_offset_l1: [i8; 15],
311+ /// `delta_chroma_weight_l1`.
312+ pub delta_chroma_weight_l1: [[i8; 2]; 15],
313+ /// `ChromaOffsetL1`.
314+ pub chroma_offset_l1: [[i8; 2]; 15],
315+ /// `five_minus_max_num_merge_cand`.
316+ pub five_minus_max_num_merge_cand: u8,
317+ /// `num_entry_point_offsets`.
318+ pub num_entry_point_offsets: u16,
319+ /// `entry_offset_to_subset_array`.
320+ pub entry_offset_to_subset_array: u16,
321+ /// Emulation prevention bytes inside the slice header.
322+ pub slice_data_num_emu_prevn_bytes: u16,
323+ pub(crate) va_reserved: [u32; 2],
324+}
325+
326+impl Default for SliceParameterBufferHEVC {
327+ fn default() -> Self {
328+ SliceParameterBufferHEVC {
329+ slice_data_size: 0,
330+ slice_data_offset: 0,
331+ slice_data_flag: 0,
332+ slice_data_byte_offset: 0,
333+ slice_segment_address: 0,
334+ ref_pic_list: [[0xff; 15]; 2],
335+ long_slice_flags: LongSliceFlags::default(),
336+ collocated_ref_idx: 0xff,
337+ num_ref_idx_l0_active_minus1: 0,
338+ num_ref_idx_l1_active_minus1: 0,
339+ slice_qp_delta: 0,
340+ slice_cb_qp_offset: 0,
341+ slice_cr_qp_offset: 0,
342+ slice_beta_offset_div2: 0,
343+ slice_tc_offset_div2: 0,
344+ luma_log2_weight_denom: 0,
345+ delta_chroma_log2_weight_denom: 0,
346+ delta_luma_weight_l0: [0; 15],
347+ luma_offset_l0: [0; 15],
348+ delta_chroma_weight_l0: [[0; 2]; 15],
349+ chroma_offset_l0: [[0; 2]; 15],
350+ delta_luma_weight_l1: [0; 15],
351+ luma_offset_l1: [0; 15],
352+ delta_chroma_weight_l1: [[0; 2]; 15],
353+ chroma_offset_l1: [[0; 2]; 15],
354+ five_minus_max_num_merge_cand: 0,
355+ num_entry_point_offsets: 0,
356+ entry_offset_to_subset_array: 0,
357+ slice_data_num_emu_prevn_bytes: 0,
358+ va_reserved: [0; 2],
359+ }
360+ }
361+}
362+
363+// SAFETY: as `PictureParameterBufferHEVC`.
364+unsafe impl VaParam for SliceParameterBufferHEVC {
365+ const TYPE: i32 = VASliceParameterBufferType;
366+}
367+
368+/// `VAIQMatrixBufferHEVC`, `va_dec_hevc.h:561`.
369+#[repr(C)]
370+#[derive(Debug, Clone, Copy)]
371+pub struct IQMatrixBufferHEVC {
372+ /// `ScalingList[0]`.
373+ pub scaling_list_4x4: [[u8; 16]; 6],
374+ /// `ScalingList[1]`.
375+ pub scaling_list_8x8: [[u8; 64]; 6],
376+ /// `ScalingList[2]`.
377+ pub scaling_list_16x16: [[u8; 64]; 6],
378+ /// `ScalingList[3]`.
379+ pub scaling_list_32x32: [[u8; 64]; 2],
380+ /// DC coefficients of the 16x16 lists.
381+ pub scaling_list_dc_16x16: [u8; 6],
382+ /// DC coefficients of the 32x32 lists.
383+ pub scaling_list_dc_32x32: [u8; 2],
384+ pub(crate) va_reserved: [u32; 4],
385+}
386+
387+impl Default for IQMatrixBufferHEVC {
388+ fn default() -> Self {
389+ IQMatrixBufferHEVC {
390+ scaling_list_4x4: [[16; 16]; 6],
391+ scaling_list_8x8: [[16; 64]; 6],
392+ scaling_list_16x16: [[16; 64]; 6],
393+ scaling_list_32x32: [[16; 64]; 2],
394+ scaling_list_dc_16x16: [16; 6],
395+ scaling_list_dc_32x32: [16; 2],
396+ va_reserved: [0; 4],
397+ }
398+ }
399+}
400+
401+// SAFETY: as `PictureParameterBufferHEVC`.
402+unsafe impl VaParam for IQMatrixBufferHEVC {
403+ const TYPE: i32 = VAIQMatrixBufferType;
404+}
405+
406+// ---------------------------------------------------------------------------
407+// ABI transcription check — `crates/ec-hw/abi-probe.c`, libva 1.23.0, x86_64:
408+//
409+// VAPictureHEVC size=28 align=4 pic_order_cnt=4 flags=8
410+// VAPictureParameterBufferHEVC size=604 align=4 ReferenceFrames=28
411+// pic_width_in_luma_samples=448
412+// pic_fields=452
413+// sps_max_dec_pic_buffering_minus1=456
414+// column_width_minus1=476
415+// row_height_minus1=514
416+// slice_parsing_fields=556
417+// log2_max_pic_order_cnt_lsb_minus4=560
418+// st_rps_bits=568
419+// VASliceParameterBufferHEVC size=264 align=4 slice_segment_address=16
420+// RefPicList=20 LongSliceFlags=52
421+// collocated_ref_idx=56
422+// luma_log2_weight_denom=64
423+// delta_luma_weight_l0=66
424+// delta_luma_weight_l1=156
425+// five_minus_max_num_merge_cand=246
426+// num_entry_point_offsets=248
427+// slice_data_num_emu_prevn_bytes=252
428+// VAIQMatrixBufferHEVC size=1016 align=4 ScalingList32x32=864
429+// ScalingListDC16x16=992
430+const _: () = {
431+ use std::mem::{align_of, offset_of, size_of};
432+
433+ assert!(size_of::<VAPictureHEVC>() == 28 && align_of::<VAPictureHEVC>() == 4);
434+ assert!(offset_of!(VAPictureHEVC, pic_order_cnt) == 4);
435+ assert!(offset_of!(VAPictureHEVC, flags) == 8);
436+
437+ assert!(
438+ size_of::<PictureParameterBufferHEVC>() == 604
439+ && align_of::<PictureParameterBufferHEVC>() == 4
440+ );
441+ assert!(offset_of!(PictureParameterBufferHEVC, reference_frames) == 28);
442+ assert!(offset_of!(PictureParameterBufferHEVC, pic_width_in_luma_samples) == 448);
443+ assert!(offset_of!(PictureParameterBufferHEVC, pic_fields) == 452);
444+ assert!(offset_of!(PictureParameterBufferHEVC, sps_max_dec_pic_buffering_minus1) == 456);
445+ assert!(offset_of!(PictureParameterBufferHEVC, column_width_minus1) == 476);
446+ assert!(offset_of!(PictureParameterBufferHEVC, row_height_minus1) == 514);
447+ assert!(offset_of!(PictureParameterBufferHEVC, slice_parsing_fields) == 556);
448+ assert!(
449+ offset_of!(
450+ PictureParameterBufferHEVC,
451+ log2_max_pic_order_cnt_lsb_minus4
452+ ) == 560
453+ );
454+ assert!(offset_of!(PictureParameterBufferHEVC, st_rps_bits) == 568);
455+
456+ assert!(
457+ size_of::<SliceParameterBufferHEVC>() == 264 && align_of::<SliceParameterBufferHEVC>() == 4
458+ );
459+ assert!(offset_of!(SliceParameterBufferHEVC, slice_segment_address) == 16);
460+ assert!(offset_of!(SliceParameterBufferHEVC, ref_pic_list) == 20);
461+ assert!(offset_of!(SliceParameterBufferHEVC, long_slice_flags) == 52);
462+ assert!(offset_of!(SliceParameterBufferHEVC, collocated_ref_idx) == 56);
463+ assert!(offset_of!(SliceParameterBufferHEVC, luma_log2_weight_denom) == 64);
464+ assert!(offset_of!(SliceParameterBufferHEVC, delta_luma_weight_l0) == 66);
465+ assert!(offset_of!(SliceParameterBufferHEVC, delta_luma_weight_l1) == 156);
466+ assert!(offset_of!(SliceParameterBufferHEVC, five_minus_max_num_merge_cand) == 246);
467+ assert!(offset_of!(SliceParameterBufferHEVC, num_entry_point_offsets) == 248);
468+ assert!(offset_of!(SliceParameterBufferHEVC, slice_data_num_emu_prevn_bytes) == 252);
469+
470+ assert!(size_of::<IQMatrixBufferHEVC>() == 1016 && align_of::<IQMatrixBufferHEVC>() == 4);
471+ assert!(offset_of!(IQMatrixBufferHEVC, scaling_list_32x32) == 864);
472+ assert!(offset_of!(IQMatrixBufferHEVC, scaling_list_dc_16x16) == 992);
473+};
crates/ec-hw/src/params/mod.rsadded+134 -0
@@ -0,0 +1,134 @@
1+//! `#[repr(C)]` transcriptions of the libva codec parameter structs.
2+//!
3+//! `ec-va` deliberately stops at the generic VA surface (display, config,
4+//! context, buffer, picture); the per-codec buffers live here because they are
5+//! what a *decoder* is, field for field. Every struct is transcribed by hand
6+//! from the system headers, in header order, and every one of them is checked
7+//! against `crates/ec-hw/abi-probe.c` output by the `const` assertion block at
8+//! the end of its module. A transcription slip is therefore a compile error,
9+//! not a driver reading garbage.
10+//!
11+//! Reference output of the probe (libva 1.23.0, x86_64 System V) is pasted
12+//! above each assertion block. Rerun it after a libva upgrade:
13+//!
14+//! ```text
15+//! cc -o /tmp/abi-probe crates/ec-hw/abi-probe.c $(pkg-config --cflags libva)
16+//! ```
17+//!
18+//! # Bit fields
19+//!
20+//! The C headers pack flags into `union { struct { uint32_t a : 2; ... } bits;
21+//! uint32_t value; }`. Rust has no bit fields, so each union becomes a
22+//! `#[repr(transparent)]` newtype over its storage integer with one chained
23+//! setter per flag, generated by [`va_bits`]. The System V ABI allocates
24+//! bit fields LSB first within the storage unit, which is what the generated
25+//! shifts assume — the one ABI assumption in this module that the probe cannot
26+//! see, and the reason every generated setter is exercised by a unit test.
27+
28+use std::sync::Arc;
29+
30+use ec_va::sys::{VABufferType, VASurfaceID};
31+use ec_va::{Buffer, Context};
32+
33+use crate::error::Result;
34+
35+pub mod av1;
36+pub mod enc;
37+pub mod h264;
38+pub mod hevc;
39+pub mod vp9;
40+
41+/// A plain-old-data parameter struct libva reads verbatim.
42+///
43+/// # Safety
44+///
45+/// The implementing type must be a `#[repr(C)]` transcription of exactly the
46+/// libva struct that belongs to [`VaParam::TYPE`], with the same size and field
47+/// offsets (which is what the `const` assertions in this module check), and
48+/// must be valid for any bit pattern it is constructed with — the driver reads
49+/// `size_of::<Self>()` bytes of it, padding included.
50+pub unsafe trait VaParam: Copy {
51+ /// The `VABufferType` this struct is submitted as.
52+ const TYPE: VABufferType;
53+}
54+
55+/// Create a VA buffer holding one parameter struct.
56+///
57+/// This is the *only* place `ec-hw` hands a Rust value to the driver as bytes;
58+/// the [`VaParam`] bound is what makes it sound, and every implementation of
59+/// that trait sits next to the transcription it vouches for.
60+pub fn param_buffer<T: VaParam>(context: &Arc<Context>, param: &T) -> Result<Buffer> {
61+ // SAFETY: `T: VaParam` guarantees `T` is the `#[repr(C)]` transcription of
62+ // the libva parameter struct for `T::TYPE`, and the layout assertions in
63+ // this module check that guarantee at compile time against the system
64+ // headers. libva copies the bytes during the call.
65+ Ok(unsafe { Buffer::from_param(context, T::TYPE, param) }?)
66+}
67+
68+/// `VA_INVALID_SURFACE`, spelled out where a parameter struct means "no picture".
69+pub const INVALID_SURFACE: VASurfaceID = ec_va::sys::VA_INVALID_SURFACE;
70+
71+/// Generate a `#[repr(transparent)]` newtype standing in for a C bit field union.
72+///
73+/// Fields are listed in header order with their widths; the generated setters
74+/// place them LSB first, which is how the System V ABI allocates `uint32_t`
75+/// bit fields. Each setter masks its value, so an out-of-range argument cannot
76+/// corrupt a neighbouring field.
77+#[macro_export]
78+macro_rules! va_bits {
79+ (
80+ $(#[$meta:meta])*
81+ $name:ident : $storage:ty { $( $field:ident : $width:expr ),* $(,)? }
82+ ) => {
83+ $(#[$meta])*
84+ #[repr(transparent)]
85+ #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
86+ pub struct $name(pub $storage);
87+
88+ impl $name {
89+ $crate::va_bits!(@fields $name, $storage, 0, $( $field : $width, )*);
90+
91+ /// The packed value, as the C union's `value` member.
92+ pub fn value(self) -> $storage {
93+ self.0
94+ }
95+ }
96+ };
97+ (@fields $name:ident, $storage:ty, $offset:expr,) => {};
98+ (@fields $name:ident, $storage:ty, $offset:expr, $field:ident : $width:expr, $($rest:tt)*) => {
99+ #[doc = concat!("Set `", stringify!($field), "` (", stringify!($width), " bit(s)).")]
100+ #[must_use]
101+ pub fn $field(mut self, value: $storage) -> Self {
102+ let mask: $storage = ((1 as $storage) << $width) - 1;
103+ self.0 &= !(mask << $offset);
104+ self.0 |= (value & mask) << $offset;
105+ self
106+ }
107+ $crate::va_bits!(@fields $name, $storage, $offset + $width, $($rest)*);
108+ };
109+}
110+
111+#[cfg(test)]
112+mod tests {
113+ va_bits! {
114+ /// Three fields spanning a byte boundary, to pin the LSB-first order.
115+ Probe: u32 { a: 2, b: 1, c: 4, d: 8 }
116+ }
117+
118+ #[test]
119+ fn bit_fields_pack_least_significant_first() {
120+ let v = Probe::default().a(3).b(1).c(0xf).d(0xff);
121+ assert_eq!(v.value(), 0x7fff);
122+ // Each setter is independent and masks its argument.
123+ let v = Probe::default().c(0xff);
124+ assert_eq!(v.value(), 0b111_1000);
125+ let v = Probe::default().d(1).c(0).a(1);
126+ assert_eq!(v.value(), (1 << 7) | 1);
127+ }
128+
129+ #[test]
130+ fn setters_overwrite_rather_than_or() {
131+ let v = Probe::default().a(3).a(1);
132+ assert_eq!(v.value(), 1);
133+ }
134+}
crates/ec-hw/src/params/vp9.rsadded+182 -0
@@ -0,0 +1,182 @@
1+//! VP9 decode parameter buffers (`va_dec_vp9.h`).
2+
3+use ec_va::sys::{VAPictureParameterBufferType, VASliceParameterBufferType, VASurfaceID};
4+
5+use super::{INVALID_SURFACE, VaParam};
6+use crate::va_bits;
7+
8+va_bits! {
9+ /// `VADecPictureParameterBufferVP9::pic_fields`.
10+ PicFields: u32 {
11+ subsampling_x: 1,
12+ subsampling_y: 1,
13+ frame_type: 1,
14+ show_frame: 1,
15+ error_resilient_mode: 1,
16+ intra_only: 1,
17+ allow_high_precision_mv: 1,
18+ mcomp_filter_type: 3,
19+ frame_parallel_decoding_mode: 1,
20+ reset_frame_context: 2,
21+ refresh_frame_context: 1,
22+ frame_context_idx: 2,
23+ segmentation_enabled: 1,
24+ segmentation_temporal_update: 1,
25+ segmentation_update_map: 1,
26+ last_ref_frame: 3,
27+ last_ref_frame_sign_bias: 1,
28+ golden_ref_frame: 3,
29+ golden_ref_frame_sign_bias: 1,
30+ alt_ref_frame: 3,
31+ alt_ref_frame_sign_bias: 1,
32+ lossless_flag: 1,
33+ }
34+}
35+
36+/// `VADecPictureParameterBufferVP9`, `va_dec_vp9.h:56`.
37+#[repr(C)]
38+#[derive(Debug, Clone, Copy)]
39+pub struct PictureParameterBufferVP9 {
40+ /// `FrameWidth`.
41+ pub frame_width: u16,
42+ /// `FrameHeight`.
43+ pub frame_height: u16,
44+ /// The eight reference slots, `VA_INVALID_SURFACE` where empty.
45+ pub reference_frames: [VASurfaceID; 8],
46+ /// Picture flags.
47+ pub pic_fields: PicFields,
48+ /// `loop_filter_level`.
49+ pub filter_level: u8,
50+ /// `loop_filter_sharpness`.
51+ pub sharpness_level: u8,
52+ /// `tile_rows_log2`.
53+ pub log2_tile_rows: u8,
54+ /// `tile_cols_log2`.
55+ pub log2_tile_columns: u8,
56+ /// Size of the uncompressed header in bytes.
57+ pub frame_header_length_in_bytes: u8,
58+ /// `header_size_in_bytes`: the compressed header length.
59+ pub first_partition_size: u16,
60+ /// `segmentation_tree_probs`.
61+ pub mb_segment_tree_probs: [u8; 7],
62+ /// `segmentation_pred_prob`.
63+ pub segment_pred_probs: [u8; 3],
64+ /// `profile`.
65+ pub profile: u8,
66+ /// `BitDepth`.
67+ pub bit_depth: u8,
68+ pub(crate) va_reserved: [u32; 8],
69+}
70+
71+impl Default for PictureParameterBufferVP9 {
72+ fn default() -> Self {
73+ PictureParameterBufferVP9 {
74+ frame_width: 0,
75+ frame_height: 0,
76+ reference_frames: [INVALID_SURFACE; 8],
77+ pic_fields: PicFields::default(),
78+ filter_level: 0,
79+ sharpness_level: 0,
80+ log2_tile_rows: 0,
81+ log2_tile_columns: 0,
82+ frame_header_length_in_bytes: 0,
83+ first_partition_size: 0,
84+ // 255 is the "no update" probability VP9 infers when segmentation
85+ // is off; zero would name a real probability.
86+ mb_segment_tree_probs: [255; 7],
87+ segment_pred_probs: [255; 3],
88+ profile: 0,
89+ bit_depth: 8,
90+ va_reserved: [0; 8],
91+ }
92+ }
93+}
94+
95+// SAFETY: `#[repr(C)]` transcription of `VADecPictureParameterBufferVP9`,
96+// checked by the assertion block below; integers and integer arrays only.
97+unsafe impl VaParam for PictureParameterBufferVP9 {
98+ const TYPE: i32 = VAPictureParameterBufferType;
99+}
100+
101+va_bits! {
102+ /// `VASegmentParameterVP9::segment_flags`.
103+ SegmentFlags: u16 {
104+ segment_reference_enabled: 1,
105+ segment_reference: 2,
106+ segment_reference_skipped: 1,
107+ }
108+}
109+
110+/// `VASegmentParameterVP9`, `va_dec_vp9.h:196`.
111+#[repr(C)]
112+#[derive(Debug, Clone, Copy, Default)]
113+pub struct SegmentParameterVP9 {
114+ /// Segment feature flags.
115+ pub segment_flags: SegmentFlags,
116+ /// `LoopFilterLevel[ref][mode]` for this segment.
117+ pub filter_level: [[u8; 2]; 4],
118+ /// Dequantised AC scale, luma.
119+ pub luma_ac_quant_scale: i16,
120+ /// Dequantised DC scale, luma.
121+ pub luma_dc_quant_scale: i16,
122+ /// Dequantised AC scale, chroma.
123+ pub chroma_ac_quant_scale: i16,
124+ /// Dequantised DC scale, chroma.
125+ pub chroma_dc_quant_scale: i16,
126+ pub(crate) va_reserved: [u32; 4],
127+}
128+
129+/// `VASliceParameterBufferVP9`, `va_dec_vp9.h:245`.
130+#[repr(C)]
131+#[derive(Debug, Clone, Copy, Default)]
132+pub struct SliceParameterBufferVP9 {
133+ /// Bytes of frame data.
134+ pub slice_data_size: u32,
135+ /// Offset of the frame within the data buffer.
136+ pub slice_data_offset: u32,
137+ /// `VA_SLICE_DATA_FLAG_*`.
138+ pub slice_data_flag: u32,
139+ /// Per-segment parameters; all eight are always sent.
140+ pub seg_param: [SegmentParameterVP9; 8],
141+ pub(crate) va_reserved: [u32; 4],
142+}
143+
144+// SAFETY: as `PictureParameterBufferVP9`.
145+unsafe impl VaParam for SliceParameterBufferVP9 {
146+ const TYPE: i32 = VASliceParameterBufferType;
147+}
148+
149+// ---------------------------------------------------------------------------
150+// ABI transcription check — `crates/ec-hw/abi-probe.c`, libva 1.23.0, x86_64:
151+//
152+// VADecPictureParameterBufferVP9 size=92 align=4 reference_frames=4
153+// pic_fields=36 filter_level=40
154+// first_partition_size=46
155+// mb_segment_tree_probs=48
156+// profile=58
157+// VASegmentParameterVP9 size=36 align=4 filter_level=2
158+// luma_ac_quant_scale=10
159+// VASliceParameterBufferVP9 size=316 align=4 seg_param=12
160+const _: () = {
161+ use std::mem::{align_of, offset_of, size_of};
162+
163+ assert!(
164+ size_of::<PictureParameterBufferVP9>() == 92
165+ && align_of::<PictureParameterBufferVP9>() == 4
166+ );
167+ assert!(offset_of!(PictureParameterBufferVP9, reference_frames) == 4);
168+ assert!(offset_of!(PictureParameterBufferVP9, pic_fields) == 36);
169+ assert!(offset_of!(PictureParameterBufferVP9, filter_level) == 40);
170+ assert!(offset_of!(PictureParameterBufferVP9, first_partition_size) == 46);
171+ assert!(offset_of!(PictureParameterBufferVP9, mb_segment_tree_probs) == 48);
172+ assert!(offset_of!(PictureParameterBufferVP9, profile) == 58);
173+
174+ assert!(size_of::<SegmentParameterVP9>() == 36 && align_of::<SegmentParameterVP9>() == 4);
175+ assert!(offset_of!(SegmentParameterVP9, filter_level) == 2);
176+ assert!(offset_of!(SegmentParameterVP9, luma_ac_quant_scale) == 10);
177+
178+ assert!(
179+ size_of::<SliceParameterBufferVP9>() == 316 && align_of::<SliceParameterBufferVP9>() == 4
180+ );
181+ assert!(offset_of!(SliceParameterBufferVP9, seg_param) == 12);
182+};
crates/ec-hw/src/pool.rsadded+132 -0
@@ -0,0 +1,132 @@
1+//! A recycling pool of decode/encode surfaces.
2+//!
3+//! Surfaces are allocated once, in one `vaCreateSurfaces` call, and handed out
4+//! as [`PooledSurface`]s that return themselves to the free list on drop.
5+//! Two things hold a surface at the same time — the reference picture buffer
6+//! and a frame the caller has not finished with — so ownership is an
7+//! `Arc<PooledSurface>` and the recycle happens when the last of them goes.
8+//!
9+//! Reallocating per frame would be the alternative, and it is precisely what
10+//! makes a VA-API pipeline stutter: every `vaCreateSurfaces` is a kernel
11+//! allocation plus a driver-side tiling decision.
12+
13+use std::ops::Deref;
14+use std::sync::{Arc, Mutex, Weak};
15+
16+use ec_va::{Display, Surface, SurfaceSpec};
17+
18+use crate::error::Result;
19+
20+struct PoolInner {
21+ /// Every surface, in allocation order. Also the context's render targets.
22+ all: Vec<Arc<Surface>>,
23+ free: Mutex<Vec<Arc<Surface>>>,
24+}
25+
26+/// A fixed-size pool of identically specified surfaces.
27+#[derive(Clone)]
28+pub struct SurfacePool {
29+ inner: Arc<PoolInner>,
30+ spec: SurfaceSpec,
31+}
32+
33+impl SurfacePool {
34+ /// Allocate `count` surfaces matching `spec`.
35+ pub fn new(display: &Arc<Display>, spec: &SurfaceSpec, count: usize) -> Result<SurfacePool> {
36+ let all = Surface::create_pool(display, spec, count)?;
37+ Ok(SurfacePool {
38+ inner: Arc::new(PoolInner {
39+ free: Mutex::new(all.clone()),
40+ all,
41+ }),
42+ spec: *spec,
43+ })
44+ }
45+
46+ /// Every surface in the pool — what a `Context` wants as its render targets.
47+ pub fn targets(&self) -> &[Arc<Surface>] {
48+ &self.inner.all
49+ }
50+
51+ /// The spec every surface in this pool was allocated with.
52+ pub fn spec(&self) -> &SurfaceSpec {
53+ &self.spec
54+ }
55+
56+ /// Total surfaces in the pool.
57+ pub fn len(&self) -> usize {
58+ self.inner.all.len()
59+ }
60+
61+ /// True when the pool holds no surfaces at all.
62+ pub fn is_empty(&self) -> bool {
63+ self.inner.all.is_empty()
64+ }
65+
66+ /// Surfaces currently available.
67+ pub fn available(&self) -> usize {
68+ self.inner.free.lock().map(|f| f.len()).unwrap_or(0)
69+ }
70+
71+ /// Take a free surface, or `None` when every one is still in use.
72+ ///
73+ /// A `None` is the caller's cue to release output frames, not an error: a
74+ /// decoder that has handed out its whole pool is waiting on the consumer.
75+ pub fn acquire(&self) -> Option<Arc<PooledSurface>> {
76+ // A poisoned lock means another thread panicked while holding it; the
77+ // free list is a plain Vec, so its contents are still consistent and
78+ // there is nothing to recover from.
79+ let mut free = match self.inner.free.lock() {
80+ Ok(free) => free,
81+ Err(poisoned) => poisoned.into_inner(),
82+ };
83+ let surface = free.pop()?;
84+ Some(Arc::new(PooledSurface {
85+ surface,
86+ pool: Arc::downgrade(&self.inner),
87+ }))
88+ }
89+}
90+
91+/// A surface on loan from a [`SurfacePool`]; returns to it on drop.
92+pub struct PooledSurface {
93+ surface: Arc<Surface>,
94+ pool: Weak<PoolInner>,
95+}
96+
97+impl PooledSurface {
98+ /// The surface itself, for the calls that want an owned `Arc<Surface>`.
99+ pub fn surface(&self) -> &Arc<Surface> {
100+ &self.surface
101+ }
102+}
103+
104+impl Deref for PooledSurface {
105+ type Target = Arc<Surface>;
106+
107+ fn deref(&self) -> &Arc<Surface> {
108+ &self.surface
109+ }
110+}
111+
112+impl std::fmt::Debug for PooledSurface {
113+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114+ f.debug_struct("PooledSurface")
115+ .field("id", &self.surface.id())
116+ .finish()
117+ }
118+}
119+
120+impl Drop for PooledSurface {
121+ fn drop(&mut self) {
122+ let Some(pool) = self.pool.upgrade() else {
123+ // The pool is gone, so the surface simply drops with this handle.
124+ return;
125+ };
126+ let mut free = match pool.free.lock() {
127+ Ok(free) => free,
128+ Err(poisoned) => poisoned.into_inner(),
129+ };
130+ free.push(Arc::clone(&self.surface));
131+ }
132+}