diff --git a/Cargo.lock b/Cargo.lock index 1b90e378..8e5b98d1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -275,10 +275,10 @@ dependencies = [ [[package]] name = "cros-libva" version = "0.0.13" -source = "git+https://github.com/chromeos/cros-libva?rev=59384456ac2ae78c0c3e5515f41ef1efd9b802cf#59384456ac2ae78c0c3e5515f41ef1efd9b802cf" dependencies = [ "bindgen", "bitflags", + "crc32fast", "log", "pkg-config", "regex", diff --git a/Cargo.toml b/Cargo.toml index 218d0de9..3d0d37f9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,3 +57,6 @@ opt-level = 3 [profile.dev] debug = "line-tables-only" + +[patch."https://github.com/chromeos/cros-libva"] +cros-libva = { path = "shims/cros-libva" } diff --git a/crates/ec-hw/src/enc/mod.rs b/crates/ec-hw/src/enc/mod.rs index 73fd0327..07c7f997 100644 --- a/crates/ec-hw/src/enc/mod.rs +++ b/crates/ec-hw/src/enc/mod.rs @@ -156,7 +156,14 @@ struct RateFeedback { impl Default for RateFeedback { fn default() -> Self { - RateFeedback { scale: 1.0, spent: 0.0, frames: 0, window: 0.0, window_frames: 0, steered: false } + RateFeedback { + scale: 1.0, + spent: 0.0, + frames: 0, + window: 0.0, + window_frames: 0, + steered: false, + } } } @@ -600,25 +607,26 @@ impl Encoder { } } - /// Pipelined encode of an imported surface of the encoder's coded size: a GPU copy - /// into a pool surface whose padding is then zeroed, matching the CPU upload path. + /// Pipelined encode of an imported surface: a GPU copy into a pool surface + /// whose padding is then zeroed, matching the CPU upload path. A surface of + /// the coded size is copied whole; any other size is scaled to the + /// configured width x height, so one capture can feed several layers. pub fn submit_prime( &mut self, surface: Rc>, meta: FrameMetadata, ) -> Result> { - if surface.size() != self.coded_size { - return Err(Error::config(format!( - "submit_prime: a {:?} surface for a {:?} encoder", - surface.size(), - self.coded_size - ))); - } let input = self .pool .acquire() .ok_or_else(|| Error::config("submit_prime: every surface is still in use"))?; - self.vpp()?.convert(&surface, Rc::clone(input.surface()))?; + let dest = if surface.size() == self.coded_size { + (0, 0, 0, 0) + } else { + (0, 0, self.config.width, self.config.height) + }; + self.vpp()? + .convert_region(&surface, (0, 0, 0, 0), Rc::clone(input.surface()), dest)?; zero_padding( self.context.display(), input.surface(), diff --git a/crates/ec-hw/tests/gpu.rs b/crates/ec-hw/tests/gpu.rs index 62da7cc8..36d55f88 100644 --- a/crates/ec-hw/tests/gpu.rs +++ b/crates/ec-hw/tests/gpu.rs @@ -3437,9 +3437,6 @@ fn cbr_lands_within_five_percent_of_the_request() { assert!(failures.is_empty(), "outside +/-5%: {failures:?}"); } -/// An NV12 surface holding `frame`, imported from DMA-BUFs: the surface is made -/// by the driver, exported, and imported back, as a foreign allocator's buffer -/// would arrive. fn imported_nv12( display: &Rc, frame: &I420, @@ -3472,7 +3469,25 @@ fn imported_nv12( } } let prime = surface.export().expect("export"); - Rc::new(ec_va::surface::import_prime(display, &prime).expect("import")) + let objects: Vec = prime + .objects + .iter() + .map(|o| ec_va::RawPrimeObject { + fd: std::os::fd::AsRawFd::as_raw_fd(&o.fd), + size: o.size, + modifier: o.modifier, + }) + .collect(); + let imported = ec_va::import_prime_raw( + display, + prime.fourcc, + (prime.width, prime.height), + &objects, + &prime.layers, + ) + .expect("import"); + drop(prime); + Rc::new(imported) } /// Encoding an imported DMA-BUF must give the bytes the CPU path gives for the @@ -3719,3 +3734,46 @@ fn h264_encode_decodes_with_no_reorder_delay() { assert!(decoder.next_frame().is_some(), "frame {t} held back"); } } + +#[test] +fn imported_dma_buf_scales_and_crops_through_vpp() { + let Some(display) = display() else { return }; + let mean = |y: &[u8]| y.iter().map(|&v| f64::from(v)).sum::() / y.len() as f64; + let meta = FrameMetadata { + timestamp: 0, + force_keyframe: false, + }; + for (source_w, source_h, scale) in [(1280, 720, true), (640, 360, false)] { + let source = source_frame(source_w, source_h, 0); + let mut config = EncoderConfig::new(EncCodec::H264, 640, 360); + config.rate_control = RateControlMode::ConstantQp { qp: 22 }; + let mut encoder = Encoder::new(&display, config).expect("encoder"); + let surface = imported_nv12(&display, &source); + let data = if scale { + let mut data = Vec::new(); + if let Some(c) = encoder.submit_prime(surface, meta).expect("submit_prime") { + data.extend(c.data); + } + data.extend( + encoder + .flush() + .expect("flush") + .into_iter() + .flat_map(|c| c.data), + ); + data + } else { + encoder + .encode_surface(&surface, (640, 360), meta) + .expect("encode_surface") + .data + }; + let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder"); + decoder.decode(&data, 0).expect("decode"); + decoder.flush().expect("flush"); + let frame = decoder.next_frame().expect("a picture"); + assert_eq!(frame.display_size, (640, 360)); + let got = frame.to_i420().expect("readback"); + assert!((mean(&got.y) - mean(&source.y)).abs() < 3.0); + } +} diff --git a/crates/ec-va/src/lib.rs b/crates/ec-va/src/lib.rs index f2467c78..d9a3b6ef 100644 --- a/crates/ec-va/src/lib.rs +++ b/crates/ec-va/src/lib.rs @@ -51,7 +51,7 @@ pub use display::{Display, open, open_path}; pub use error::{Error, Result}; pub use picture::{Buffer, Context, Picture, create_context}; pub use surface::{ - Image, PrimeLayer, PrimeObject, PrimeSurface, Surface, SurfaceExt, SurfaceSpec, create_pool, - import_prime, + Image, PrimeLayer, PrimeObject, PrimeSurface, RawPrimeObject, Surface, SurfaceExt, SurfaceSpec, + create_pool, import_prime, import_prime_raw, }; pub use vpp::Vpp; diff --git a/crates/ec-va/src/surface.rs b/crates/ec-va/src/surface.rs index d60e96a6..10550963 100644 --- a/crates/ec-va/src/surface.rs +++ b/crates/ec-va/src/surface.rs @@ -212,27 +212,67 @@ pub fn import_prime( display: &Rc, prime: &PrimeSurface, ) -> Result> { - if prime.objects.len() > 4 || prime.layers.len() > 4 { + let objects: Vec = prime + .objects + .iter() + .map(|o| RawPrimeObject { + fd: o.fd.as_raw_fd(), + size: o.size, + modifier: o.modifier, + }) + .collect(); + import_prime_raw( + display, + prime.fourcc, + (prime.width, prime.height), + &objects, + &prime.layers, + ) +} + +/// A DMA-BUF object borrowed by raw fd, for buffers another owner keeps +/// (e.g. a PipeWire `spa_data` fd). +#[derive(Debug, Clone, Copy)] +pub struct RawPrimeObject { + /// The DMA-BUF, borrowed only for the duration of the import call. + pub fd: std::os::fd::RawFd, + /// Size of the object in bytes. + pub size: u32, + /// DRM format modifier of the object. + pub modifier: u64, +} + +/// [`import_prime`] with borrowed raw fds. The driver takes its own reference +/// to each DMA-BUF during `vaCreateSurfaces`, so the fds may be closed after +/// this returns; the buffer contents must stay valid while the surface is read. +pub fn import_prime_raw( + display: &Rc, + fourcc: u32, + size: (u32, u32), + objects: &[RawPrimeObject], + layers: &[PrimeLayer], +) -> Result> { + if objects.len() > 4 || layers.len() > 4 { return Err(Error::Protocol(format!( "a PRIME surface has {} objects and {} layers, max 4 each", - prime.objects.len(), - prime.layers.len() + objects.len(), + layers.len() ))); } let mut desc = VADRMPRIMESurfaceDescriptor { - fourcc: prime.fourcc, - width: prime.width, - height: prime.height, - num_objects: prime.objects.len() as u32, - num_layers: prime.layers.len() as u32, + fourcc, + width: size.0, + height: size.1, + num_objects: objects.len() as u32, + num_layers: layers.len() as u32, ..Default::default() }; - for (i, o) in prime.objects.iter().enumerate() { - desc.objects[i].fd = o.fd.as_raw_fd(); + for (i, o) in objects.iter().enumerate() { + desc.objects[i].fd = o.fd; desc.objects[i].size = o.size; desc.objects[i].drm_format_modifier = o.modifier; } - for (i, l) in prime.layers.iter().enumerate() { + for (i, l) in layers.iter().enumerate() { if l.planes.len() > 4 { return Err(Error::Protocol(format!( "a PRIME layer has {} planes, max 4", @@ -251,9 +291,9 @@ pub fn import_prime( "vaCreateSurfaces", display.create_surfaces( cros_libva::VA_RT_FORMAT_YUV420, - Some(prime.fourcc), - prime.width, - prime.height, + Some(fourcc), + size.0, + size.1, None, vec![PrimeImport(desc)], ), diff --git a/crates/ec-va/src/vpp.rs b/crates/ec-va/src/vpp.rs index 6f60bc40..8cbc9b37 100644 --- a/crates/ec-va/src/vpp.rs +++ b/crates/ec-va/src/vpp.rs @@ -68,11 +68,9 @@ impl Vpp { self.convert_region(source, (0, 0, 0, 0), dest, (0, 0, 0, 0)) } - /// Convert `source_region` of `source` into `dest_region` of `dest` with - /// no scaling (both regions are the same size in every caller), leaving - /// the rest of `dest` as it was. A zero-sized region means "the whole - /// surface". This is how a visible picture smaller than its block-aligned - /// coded surface lands inside a differently-padded destination. + /// Convert `source_region` of `source` into `dest_region` of `dest`, + /// scaling when the regions differ in size and leaving the rest of `dest` + /// as it was. A zero-sized region means "the whole surface". pub fn convert_region( &self, source: &cros_libva::Surface, diff --git a/shims/cros-libva/Android.bp b/shims/cros-libva/Android.bp new file mode 100644 index 00000000..e1ae101c --- /dev/null +++ b/shims/cros-libva/Android.bp @@ -0,0 +1,63 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This file is generated by cargo_embargo. +// Do not modify this file because the changes will be overridden on upgrade. + +package { + default_applicable_licenses: ["external_rust_cros-libva_license"], +} + +soong_config_module_type_import { + from: "system/cros-codecs/Android.bp", + module_types: [ + "rust_defaults_cros_codecs_protected_content", + ], +} + +rust_defaults_cros_codecs_protected_content { + name: "cros_libva_protected_content_rust_library_defaults", + soong_config_variables: { + intel_protected_content: { + features: ["intel-protected-content-headers"], + }, + }, +} + +rust_library { + name: "libcros_libva", + crate_name: "cros_libva", + cargo_env_compat: true, + cargo_pkg_version: "0.0.8", + crate_root: "src/lib.rs", + edition: "2021", + defaults: ["cros_libva_protected_content_rust_library_defaults"], + rustlibs: [ + "libbitflags", + "liblog_rust", + "libthiserror", + ], + apex_available: [ + "//apex_available:platform", + "//apex_available:anyapex", + ], + + cfgs: [ + "libva_1_21_or_higher", + "libva_1_20_or_higher", + "libva_1_19_or_higher", + "libva_1_16_or_higher", + ], + + vendor: true, + enabled: false, + arch: { + x86_64: { + enabled: true, + // Bindgen-generated bindings of our local libva headers. + srcs: [":libcros_libva_bindgen"], + shared_libs: ["libva"], + }, + }, +} diff --git a/shims/cros-libva/Cargo.toml b/shims/cros-libva/Cargo.toml new file mode 100644 index 00000000..c2d9e978 --- /dev/null +++ b/shims/cros-libva/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "cros-libva" +version = "0.0.13" +license = "BSD-3-Clause" +description = "Safe bindings over libva" +repository = "https://github.com/chromeos/cros-libva" +authors = ["The Chromium OS Authors"] +edition = "2021" + + + +[features] +intel-protected-content-headers = [] + +[dependencies] +thiserror = "1" +bitflags = "2.5" +log = { version = "0", features = ["release_max_level_debug"] } + +[build-dependencies] +bindgen = "0.70.1" +pkg-config = "0.3.31" +regex = "1.11.1" + +[dev-dependencies] +crc32fast = "1.2.1" diff --git a/shims/cros-libva/LICENSE b/shims/cros-libva/LICENSE new file mode 100644 index 00000000..9c1f8394 --- /dev/null +++ b/shims/cros-libva/LICENSE @@ -0,0 +1,26 @@ +Copyright 2022 The ChromiumOS Authors + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/shims/cros-libva/bindgen_gen.rs b/shims/cros-libva/bindgen_gen.rs new file mode 100644 index 00000000..6571b9e1 --- /dev/null +++ b/shims/cros-libva/bindgen_gen.rs @@ -0,0 +1,22 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/// The allow list of VA structures and enum values. +const ALLOW_LIST_TYPE: &str = + ".*ExternalBuffers.*|.*PRIME.*|.*MPEG2.*|.*VP8.*|.*VP9.*|.*H264.*|.*HEVC.*|\ + .*JPEG.*|VACodedBufferSegment|.*AV1.*|VAEncMisc.*|VASurfaceDecodeMBErrors|\ + VADecodeErrorType|.*VAProc.*|VAEncPacked.*|\ + VACenc.*|VA_TEE_.*|VAEncryption.*|VA_PROTECTED_.*"; + +// The common bindgen builder for VA-API. +pub fn vaapi_gen_builder(builder: bindgen::Builder) -> bindgen::Builder { + builder + .derive_default(true) + .derive_eq(true) + .layout_tests(false) + .constified_enum_module("VA.*") + .allowlist_var("VA.*") + .allowlist_function("va.*") + .allowlist_type(ALLOW_LIST_TYPE) +} diff --git a/shims/cros-libva/build.rs b/shims/cros-libva/build.rs new file mode 100644 index 00000000..0aebab02 --- /dev/null +++ b/shims/cros-libva/build.rs @@ -0,0 +1,159 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use regex::Regex; +use std::env::VarError; +use std::env::{self}; +use std::fs::read_to_string; +use std::path::{Path, PathBuf}; + +mod bindgen_gen; +use bindgen_gen::vaapi_gen_builder; + +/// Environment variable that can be set to point to the directory containing the `va.h`, `va_drm.h` and `va_drmcommon.h` +/// files to use to generate the bindings. +const CROS_LIBVA_H_PATH_ENV: &str = "CROS_LIBVA_H_PATH"; +const CROS_LIBVA_LIB_PATH_ENV: &str = "CROS_LIBVA_LIB_PATH"; +const CROS_LIBVA_PROTECTED_CONTENT_H_PATH_ENV: &str = "CROS_LIBVA_PROTECTED_CONTENT_H_PATH"; + +/// Wrapper file to use as input of bindgen. +const WRAPPER_PATH: &str = "libva-wrapper.h"; + +// Return VA_MAJOR_VERSION and VA_MINOR_VERSION from va_version.h. +fn get_va_version(va_h_path: &str) -> (u32, u32) { + let va_version_h_path = Path::new(va_h_path).join("va/va_version.h"); + assert!( + va_version_h_path.exists(), + "{} doesn't exist", + va_version_h_path.display() + ); + let header_content = read_to_string(va_version_h_path).unwrap(); + let lines = header_content.lines(); + + const VERSION_REGEX_STRINGS: [&str; 2] = [ + r"#define VA_MAJOR_VERSION\s*[0-9]+", + r"#define VA_MINOR_VERSION\s*[0-9]+", + ]; + let mut numbers: [u32; 2] = [0; 2]; + for i in 0..2 { + let re = Regex::new(VERSION_REGEX_STRINGS[i]).unwrap(); + let match_line = lines + .clone() + .filter(|&s| re.is_match(s)) + .collect::>(); + assert_eq!( + match_line.len(), + 1, + "unexpected match for {}: {:?}", + VERSION_REGEX_STRINGS[i], + match_line + ); + let number_str = Regex::new(r"[0-9]+") + .unwrap() + .find(match_line[0]) + .unwrap() + .as_str(); + numbers[i] = number_str.parse::().unwrap(); + } + + (numbers[0], numbers[1]) +} + +fn main() { + // Do not require dependencies when generating docs. + if std::env::var("CARGO_DOC").is_ok() || std::env::var("DOCS_RS").is_ok() { + return; + } + + let va_h_path = env::var(CROS_LIBVA_H_PATH_ENV) + .or_else(|e| { + if let VarError::NotPresent = e { + let libva_library = pkg_config::probe_library("libva"); + match libva_library { + Ok(_) => Ok(libva_library.unwrap().include_paths[0] + .clone() + .into_os_string() + .into_string() + .unwrap()), + Err(e) => panic!("libva is not found in system: {}", e), + } + } else { + Err(e) + } + }) + .expect("libva header location is unknown"); + + let va_lib_path = env::var(CROS_LIBVA_LIB_PATH_ENV).unwrap_or_default(); + // Check the path exists. + if !va_h_path.is_empty() { + assert!( + Path::new(&va_h_path).exists(), + "{} doesn't exist", + va_h_path + ); + } + + let (major, minor) = get_va_version(&va_h_path); + println!("libva {}.{} is used to generate bindings", major, minor); + let va_check_version = |desired_major: u32, desired_minor: u32| { + major > desired_major || (major == desired_major && minor >= desired_minor) + }; + + if va_check_version(1, 23) { + println!("cargo::rustc-cfg=libva_1_23_or_higher"); + } + if va_check_version(1, 22) { + println!("cargo::rustc-cfg=libva_1_22_or_higher"); + } + if va_check_version(1, 21) { + println!("cargo::rustc-cfg=libva_1_21_or_higher"); + } + if va_check_version(1, 20) { + println!("cargo::rustc-cfg=libva_1_20_or_higher") + } + if va_check_version(1, 19) { + println!("cargo::rustc-cfg=libva_1_19_or_higher") + } + if va_check_version(1, 16) { + println!("cargo::rustc-cfg=libva_1_16_or_higher") + } + + if !va_lib_path.is_empty() { + assert!( + Path::new(&va_lib_path).exists(), + "{} doesn't exist", + va_lib_path + ); + println!("cargo:rustc-link-arg=-Wl,-rpath={}", va_lib_path); + } + + // Tell cargo to link va and va-drm objects dynamically. + println!("cargo:rustc-link-lib=dylib=va"); + println!("cargo:rustc-link-lib=dylib=va-drm"); // for the vaGetDisplayDRM entrypoint + + let mut bindings_builder = vaapi_gen_builder(bindgen::builder()).header(WRAPPER_PATH); + if !va_h_path.is_empty() { + bindings_builder = bindings_builder.clang_arg(format!("-I{}", va_h_path)); + } + + if std::env::var("CARGO_FEATURE_INTEL_PROTECTED_CONTENT_HEADERS").is_ok() { + println!("cargo:warning=Building with intel protected content headers!"); + bindings_builder = bindings_builder.clang_arg("-DINTEL_PROTECTED_CONTENT_HEADERS"); + let va_p_h_path_env = env::var(CROS_LIBVA_PROTECTED_CONTENT_H_PATH_ENV); + if va_p_h_path_env.is_ok() { + let va_p_h_path = va_p_h_path_env.unwrap(); + bindings_builder = bindings_builder.clang_arg(format!("-I{}", va_p_h_path)); + } + } + + let bindings = bindings_builder + .generate() + .expect("unable to generate bindings"); + + let out_path = PathBuf::from(env::var("OUT_DIR").expect("`OUT_DIR` is not set")); + + bindings + .write_to_file(out_path.join("bindings.rs")) + .expect("Couldn't write bindings!"); +} diff --git a/shims/cros-libva/libva-wrapper.h b/shims/cros-libva/libva-wrapper.h new file mode 100644 index 00000000..b9de8636 --- /dev/null +++ b/shims/cros-libva/libva-wrapper.h @@ -0,0 +1,11 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include + +#if defined(INTEL_PROTECTED_CONTENT_HEADERS) +#include +#endif // defined(INTEL_PROTECTED_CONTENT_HEADERS) diff --git a/shims/cros-libva/src/bindings.rs b/shims/cros-libva/src/bindings.rs new file mode 100644 index 00000000..1ee7a7dc --- /dev/null +++ b/shims/cros-libva/src/bindings.rs @@ -0,0 +1,15 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! This module implements the bindgen C FFI bindings for use within this crate + +#![allow(missing_docs)] +#![allow(clippy::useless_transmute)] +#![allow(clippy::too_many_arguments)] +#![allow(non_upper_case_globals)] +#![allow(non_snake_case)] +#![allow(non_camel_case_types)] +#![allow(dead_code)] + +include!(concat!(env!("OUT_DIR"), "/bindings.rs")); diff --git a/shims/cros-libva/src/buffer.rs b/shims/cros-libva/src/buffer.rs new file mode 100644 index 00000000..c5f2686d --- /dev/null +++ b/shims/cros-libva/src/buffer.rs @@ -0,0 +1,755 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Wrappers and helpers around `VABuffer`s. + +mod av1; +mod enc_jpeg; +mod enc_misc; +mod h264; +mod hevc; +mod jpeg_baseline; +mod mpeg2; +mod proc_pipeline; +mod vp8; +mod vp9; + +pub use av1::*; +pub use enc_jpeg::*; +pub use enc_misc::*; +pub use h264::*; +pub use hevc::*; +pub use jpeg_baseline::*; +pub use mpeg2::*; +pub use proc_pipeline::*; +pub use vp8::*; +pub use vp9::*; + +use std::rc::Rc; + +use log::error; + +use crate::bindings; +use crate::va_check; +use crate::Context; +use crate::VaError; + +/// Wrapper type representing a buffer created with `vaCreateBuffer`. +pub struct Buffer { + context: Rc, + id: bindings::VABufferID, + _params: Option, +} + +impl Buffer { + /// Creates a new buffer by wrapping a `vaCreateBuffer` call. This is just a helper for + /// [`Context::create_buffer`]. + pub(crate) fn new(context: Rc, mut type_: BufferType) -> Result { + let mut buffer_id = 0; + + /* we send all slices parameters as a single array in H264, AV1 */ + let nb_elements = match type_ { + BufferType::SliceParameter(SliceParameter::H264(ref mut params)) => { + params.inner_mut().len() + } + BufferType::SliceParameter(SliceParameter::AV1(ref mut params)) => { + params.inner_mut().len() + } + _ => 1, + }; + + let (ptr, size) = match type_ { + BufferType::PictureParameter(ref mut picture_param) => match picture_param { + PictureParameter::MPEG2(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + PictureParameter::VP8(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + PictureParameter::VP9(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + PictureParameter::H264(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + PictureParameter::HEVC(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + PictureParameter::HEVCRext(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + PictureParameter::HEVCScc(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + PictureParameter::AV1(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + PictureParameter::JPEGBaseline(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + PictureParameter::EncJPEG(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + }, + + BufferType::SliceParameter(ref mut slice_param) => match slice_param { + SliceParameter::MPEG2(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + SliceParameter::VP8(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + SliceParameter::VP9(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + SliceParameter::H264(ref mut wrapper) => ( + wrapper.inner_mut().as_mut_ptr() as *mut std::ffi::c_void, + std::mem::size_of::(), + ), + SliceParameter::HEVC(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + SliceParameter::HEVCRext(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + SliceParameter::AV1(ref mut wrapper) => ( + wrapper.inner_mut().as_mut_ptr() as *mut std::ffi::c_void, + std::mem::size_of::(), + ), + SliceParameter::JPEGBaseline(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + SliceParameter::EncJpeg(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + }, + + BufferType::IQMatrix(ref mut iq_matrix) => match iq_matrix { + IQMatrix::MPEG2(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + IQMatrix::VP8(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + IQMatrix::H264(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + IQMatrix::HEVC(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + IQMatrix::JPEGBaseline(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + }, + + BufferType::HuffmanTable(ref mut huffman_table) => match huffman_table { + HuffmanTable::JPEGBaseline(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + }, + + BufferType::Probability(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + + BufferType::SliceData(ref mut data) => { + (data.as_mut_ptr() as *mut std::ffi::c_void, data.len()) + } + + BufferType::EncSequenceParameter(ref mut seq_param) => match seq_param { + EncSequenceParameter::H264(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncSequenceParameter::HEVC(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncSequenceParameter::VP8(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncSequenceParameter::VP9(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncSequenceParameter::AV1(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + }, + + BufferType::EncPictureParameter(ref mut picture_param) => match picture_param { + EncPictureParameter::H264(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncPictureParameter::HEVC(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncPictureParameter::VP8(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncPictureParameter::VP9(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncPictureParameter::AV1(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + }, + + BufferType::EncSliceParameter(ref mut slice_param) => match slice_param { + EncSliceParameter::H264(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncSliceParameter::HEVC(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncSliceParameter::AV1(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + }, + + BufferType::EncMacroblockParameterBuffer(ref mut mb_param) => match mb_param { + EncMacroblockParameterBuffer::H264(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + }, + + BufferType::EncCodedBuffer(size) => (std::ptr::null_mut(), size), + + BufferType::EncMiscParameter(ref mut enc_misc_param) => match enc_misc_param { + EncMiscParameter::FrameRate(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncMiscParameter::RateControl(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncMiscParameter::MaxSliceSize(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncMiscParameter::MaxFrameSize(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncMiscParameter::SkipFrame(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncMiscParameter::HRD(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncMiscParameter::QualityLevel(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncMiscParameter::Quantization(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + }, + BufferType::ProcPipelineParameter(ref mut proc_pipeline_param) => ( + proc_pipeline_param.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(proc_pipeline_param.inner_mut()), + ), + BufferType::QMatrix(ref mut q_matrix) => match q_matrix { + QMatrix::JPEG(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + }, + BufferType::EncPackedHeaderParameter(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + + BufferType::EncPackedHeaderData(ref data) => { + (data.as_ptr() as *mut std::ffi::c_void, data.len()) + } + }; + + // Safe because `self` represents a valid `VAContext`. `ptr` and `size` are also ensured to + // be correct, as `ptr` is just a cast to `*c_void` from a Rust struct, and `size` is + // computed from `std::mem::size_of_val`. + va_check(unsafe { + bindings::vaCreateBuffer( + context.display().handle(), + context.id(), + type_.inner(), + size as u32, + nb_elements as u32, + ptr, + &mut buffer_id, + ) + })?; + + Ok(Self { + context, + id: buffer_id, + _params: Some(type_), + }) + } + + /// Convenience function to return a `VABufferID` vector from a slice of `Buffer`s in order to + /// easily interface with the C API where a buffer array might be needed. + pub fn as_id_vec(buffers: &[Self]) -> Vec { + buffers.iter().map(|buffer| buffer.id).collect() + } +} + +/// A borrowed version of `BufferType` that avoids copying data. +pub enum BorrowedBufferType<'a> { + /// Abstraction over `VASliceDataBufferType` that uses borrowed data. + SliceData(&'a [u8]), + /// Abstraction over `VAEncPackedHeaderDataBufferType` that uses borrowed data. + EncPackedHeaderData(&'a [u8]), + /// Abstraction over `VAProtectedSliceDataBufferType` that uses borrowed data. + ProtectedSliceDataBuffer(&'a [u8]), +} + +impl<'a> BorrowedBufferType<'a> { + /// Returns the inner FFI buffer type. + pub(crate) fn inner(&self) -> bindings::VABufferType::Type { + match self { + BorrowedBufferType::SliceData(_) => bindings::VABufferType::VASliceDataBufferType, + BorrowedBufferType::EncPackedHeaderData(_) => { + bindings::VABufferType::VAEncPackedHeaderDataBufferType + } + BorrowedBufferType::ProtectedSliceDataBuffer(_) => { + bindings::VABufferType::VAProtectedSliceDataBufferType + } + } + } +} + +impl Buffer { + /// Creates a new buffer from a `BorrowedBufferType`. + pub(crate) fn new_borrowed( + context: Rc, + type_: BorrowedBufferType, + ) -> Result { + let mut buffer_id = 0; + + let nb_elements = 1; + + let (ptr, size) = match type_ { + BorrowedBufferType::SliceData(data) => { + (data.as_ptr() as *mut std::ffi::c_void, data.len()) + } + BorrowedBufferType::EncPackedHeaderData(data) => { + (data.as_ptr() as *mut std::ffi::c_void, data.len()) + } + BorrowedBufferType::ProtectedSliceDataBuffer(data) => { + (data.as_ptr() as *mut std::ffi::c_void, data.len()) + } + }; + + // Safe because `self` represents a valid `VAContext`. `ptr` and `size` are also ensured to + // be correct. + va_check(unsafe { + bindings::vaCreateBuffer( + context.display().handle(), + context.id(), + type_.inner(), + size as u32, + nb_elements as u32, + ptr, + &mut buffer_id, + ) + })?; + + Ok(Self { + context, + id: buffer_id, + _params: None, + }) + } +} + +impl Drop for Buffer { + fn drop(&mut self) { + // Safe because `self` represents a valid buffer, created with + // vaCreateBuffers. + let status = va_check(unsafe { + bindings::vaDestroyBuffer(self.context.display().handle(), self.id) + }); + + if status.is_err() { + error!("vaDestroyBuffer failed: {}", status.unwrap_err()); + } + } +} + +/// Abstraction over `VABufferType`s. +pub enum BufferType { + /// Abstraction over `VAPictureParameterBufferType`. Needed for MPEG2, VP8, VP9, H264, JPEGBaseline. + PictureParameter(PictureParameter), + /// Abstraction over `VASliceParameterBufferType`. Needed for MPEG2, VP8, VP9, H264, JPEGBaseline. + SliceParameter(SliceParameter), + /// Abstraction over `VAIQMatrixBufferType`. Needed for VP8, H264, JPEGBaseline. + IQMatrix(IQMatrix), + /// Abstraction over `HuffmanTableBufferType`. Needed for JPEGBaseline. + HuffmanTable(HuffmanTable), + /// Abstraction over `VAProbabilityDataBufferType`. Needed for VP8. + Probability(vp8::ProbabilityDataBufferVP8), + /// Abstraction over `VASliceDataBufferType`. Needed for VP9, H264. + SliceData(Vec), + /// Abstraction over `VAEncSequenceParameterBufferType`. Needed for MPEG2, VP8, VP9, H264, HEVC. + EncSequenceParameter(EncSequenceParameter), + /// Abstraction over `VAEncPictureParameterBufferType`. Needed for MPEG2, VP8, VP9, H264, HEVC. + EncPictureParameter(EncPictureParameter), + /// Abstraction over `VAEncSliceParameterBufferType`. Needed for MPEG2, VP8, VP9, H264, HEVC. + EncSliceParameter(EncSliceParameter), + /// Abstraction over `VAEncMacroblockMapBufferType`. Needed for H264. + EncMacroblockParameterBuffer(EncMacroblockParameterBuffer), + /// Abstraction over `VAEncCodedBufferType`. Needed for MPEG2, VP8, VP9, H264, HEVC. + EncCodedBuffer(usize), + /// Abstraction over `VAEncMiscParameterBuffer`. + EncMiscParameter(EncMiscParameter), + /// Abstraction over `VAProcPipelineParameterBuffer`. + ProcPipelineParameter(proc_pipeline::ProcPipelineParameterBuffer), + /// Abstraction over `VAQMatrixBufferType`. + QMatrix(QMatrix), + /// Abstraction over `VAEncPackedHeaderParameterBufferType`. + EncPackedHeaderParameter(EncPackedHeaderParameter), + /// Abstraction over `VAEncPackedHeaderDataBufferType`. + EncPackedHeaderData(Vec), +} + +impl BufferType { + /// Returns the inner FFI buffer type. + pub(crate) fn inner(&self) -> bindings::VABufferType::Type { + match self { + BufferType::PictureParameter(_) => bindings::VABufferType::VAPictureParameterBufferType, + BufferType::SliceParameter(_) => bindings::VABufferType::VASliceParameterBufferType, + BufferType::IQMatrix(_) => bindings::VABufferType::VAIQMatrixBufferType, + BufferType::HuffmanTable(_) => bindings::VABufferType::VAHuffmanTableBufferType, + BufferType::Probability(_) => bindings::VABufferType::VAProbabilityBufferType, + BufferType::SliceData { .. } => bindings::VABufferType::VASliceDataBufferType, + + BufferType::EncSequenceParameter(_) => { + bindings::VABufferType::VAEncSequenceParameterBufferType + } + + BufferType::EncPictureParameter(_) => { + bindings::VABufferType::VAEncPictureParameterBufferType + } + + BufferType::EncSliceParameter(_) => { + bindings::VABufferType::VAEncSliceParameterBufferType + } + + BufferType::EncMacroblockParameterBuffer(_) => { + bindings::VABufferType::VAEncMacroblockMapBufferType + } + + BufferType::EncCodedBuffer(_) => bindings::VABufferType::VAEncCodedBufferType, + + BufferType::EncMiscParameter(_) => bindings::VABufferType::VAEncMiscParameterBufferType, + + BufferType::ProcPipelineParameter(_) => { + bindings::VABufferType::VAProcPipelineParameterBufferType + } + + BufferType::QMatrix(_) => bindings::VABufferType::VAQMatrixBufferType, + + BufferType::EncPackedHeaderParameter(_) => { + bindings::VABufferType::VAEncPackedHeaderParameterBufferType + } + + BufferType::EncPackedHeaderData(_) => { + bindings::VABufferType::VAEncPackedHeaderDataBufferType + } + } + } +} + +/// Abstraction over the `PictureParameterBuffer` types we support. +pub enum PictureParameter { + /// Wrapper over VAPictureParameterBufferMPEG2. + MPEG2(mpeg2::PictureParameterBufferMPEG2), + /// Wrapper over VAPictureParameterBufferVP8. + VP8(vp8::PictureParameterBufferVP8), + /// Wrapper over VAPictureParameterBufferVP9. + VP9(vp9::PictureParameterBufferVP9), + /// Wrapper over VAPictureParameterBufferH264. + H264(h264::PictureParameterBufferH264), + /// Wrapper over VAPictureParameterBufferHEVC + HEVC(hevc::PictureParameterBufferHEVC), + /// Wrapper over VAPictureParameterBufferHEVCRext + HEVCRext(hevc::PictureParameterBufferHEVCRext), + /// Wrapper over VAPictureParameterBufferHEVCScc + HEVCScc(hevc::PictureParameterBufferHEVCScc), + /// Wrapper over VADecPictureParameterBufferAV1 + AV1(av1::PictureParameterBufferAV1), + /// Wrapper over VAPictureParameterBufferJPEGBaseline + JPEGBaseline(jpeg_baseline::PictureParameterBufferJPEGBaseline), + /// Wrapper over VAEncPictureParameterBufferJPEG + EncJPEG(enc_jpeg::EncPictureParameterBufferJPEG), +} + +/// Abstraction over the `SliceParameterBuffer` types we support +pub enum SliceParameter { + /// Wrapper over VASliceParameterBufferMPEG2 + MPEG2(mpeg2::SliceParameterBufferMPEG2), + /// Wrapper over VASliceParameterBufferVP8 + VP8(vp8::SliceParameterBufferVP8), + /// Wrapper over VASliceParameterBufferVP9 + VP9(vp9::SliceParameterBufferVP9), + /// Wrapper over VASliceParameterBufferH264 + H264(h264::SliceParameterBufferH264), + /// Wrapper over VASliceParameterBufferHEVC + HEVC(hevc::SliceParameterBufferHEVC), + /// Wrapper over VASliceParameterBufferHEVCRext + HEVCRext(hevc::SliceParameterBufferHEVCRext), + /// Wrapper over VASliceParameterBufferAV1 + AV1(av1::SliceParameterBufferAV1), + /// Wrapper over VASliceParameterBufferJPEGBaseline + JPEGBaseline(jpeg_baseline::SliceParameterBufferJPEGBaseline), + /// Wrapper over VAEncSliceParameterBufferJPEG + EncJpeg(enc_jpeg::EncSliceParameterBufferJPEG), +} + +/// Abstraction over the `IQMatrixBuffer` types we support. +pub enum IQMatrix { + /// Abstraction over `VAIQMatrixBufferMPEG2` + MPEG2(mpeg2::IQMatrixBufferMPEG2), + /// Abstraction over `VAIQMatrixBufferVP8` + VP8(vp8::IQMatrixBufferVP8), + /// Abstraction over `VAIQMatrixBufferH264` + H264(h264::IQMatrixBufferH264), + /// Abstraction over `VAIQMatrixBufferHEVC` + HEVC(hevc::IQMatrixBufferHEVC), + /// Abstraction over `VAIQMatrixBufferJPEGBaseline`` + JPEGBaseline(jpeg_baseline::IQMatrixBufferJPEGBaseline), +} + +/// Abstraction over the `HuffmanTable` types we support. +pub enum HuffmanTable { + /// Abstraction over `VAHuffmanTableBufferJPEGBaseline` + JPEGBaseline(jpeg_baseline::HuffmanTableBufferJPEGBaseline), +} + +/// Abstraction over the `QMatrix` types we support. +pub enum QMatrix { + /// Abstraction over `VAQMatrixBufferJPEG` + JPEG(enc_jpeg::QMatrixBufferJPEG), +} + +/// Abstraction over the `EncSequenceParameter` types we support. +pub enum EncSequenceParameter { + /// Abstraction over `VAEncSequenceParameterBufferH264` + H264(h264::EncSequenceParameterBufferH264), + /// Abstraction over `VAEncSequenceParameterBufferHEVC` + HEVC(hevc::EncSequenceParameterBufferHEVC), + /// Abstraction over `VAEncSequenceParameterBufferVP8` + VP8(vp8::EncSequenceParameterBufferVP8), + /// Abstraction over `VAEncSequenceParameterBufferVP9` + VP9(vp9::EncSequenceParameterBufferVP9), + /// Abstraction over `VAEncSequenceParameterBufferAV1` + AV1(av1::EncSequenceParameterBufferAV1), +} + +/// Abstraction over the `EncPictureParameter` types we support. +pub enum EncPictureParameter { + /// Abstraction over `VAEncPictureParameterBufferH264` + H264(h264::EncPictureParameterBufferH264), + /// Abstraction over `VAEncPictureParameterBufferHEVC` + HEVC(hevc::EncPictureParameterBufferHEVC), + /// Abstraction over `VAEncPictureParameterBufferVP8` + VP8(vp8::EncPictureParameterBufferVP8), + /// Abstraction over `VAEncPictureParameterBufferVP9` + VP9(vp9::EncPictureParameterBufferVP9), + /// Abstraction over `VAEncPictureParameterBufferAV1` + AV1(av1::EncPictureParameterBufferAV1), +} + +/// Abstraction over the `EncSliceParameter` types we support. +pub enum EncSliceParameter { + /// Abstraction over `VAEncSliceParameterBufferH264` + H264(h264::EncSliceParameterBufferH264), + /// Abstraction over `VAEncSliceParameterBufferHEVC` + HEVC(hevc::EncSliceParameterBufferHEVC), + /// Abstraction over `VAEncTileGroupBufferAV1` + AV1(av1::EncTileGroupBufferAV1), +} + +/// Abstraction over the `EncMacroblockParameterBuffer` types we support. +pub enum EncMacroblockParameterBuffer { + /// Abstraction over `VAEncMacroblockParameterBufferH264` + H264(h264::EncMacroblockParameterBufferH264), +} + +/// Wrapper type representing a buffer created with `vaCreateBuffer` with VAEncCodedBufferType. +pub struct EncCodedBuffer(Buffer); + +impl EncCodedBuffer { + pub(crate) fn new(context: Rc, size: usize) -> Result { + Ok(Self(Buffer::new( + context, + BufferType::EncCodedBuffer(size), + )?)) + } + + /// Convenience function to return buffer's `VABufferID`. + pub fn id(&self) -> bindings::VABufferID { + self.0.id + } +} + +/// Helper to access a single segment of mapped coded buffer +pub struct MappedCodedSegment<'s> { + pub bit_offset: u32, + pub status: u32, + pub buf: &'s [u8], +} + +/// Helper to access segments of mapped coded buffer +pub struct MappedCodedBuffer<'p> { + segments: Vec>, + buffer: &'p EncCodedBuffer, +} + +impl<'p> MappedCodedBuffer<'p> { + /// Map a 'VAEncCodedBufferType' buffer. + pub fn new(buffer: &'p EncCodedBuffer) -> Result { + let mut addr = std::ptr::null_mut(); + let mut segments = Vec::new(); + + va_check(unsafe { + bindings::vaMapBuffer(buffer.0.context.display().handle(), buffer.id(), &mut addr) + })?; + + while !addr.is_null() { + let segment: &bindings::VACodedBufferSegment = + unsafe { &*(addr as *const bindings::VACodedBufferSegment) }; + + let size = segment.size; + let buf = segment.buf; + + let buf = unsafe { std::slice::from_raw_parts(buf as *mut u8, size as usize) }; + + segments.push(MappedCodedSegment { + bit_offset: segment.bit_offset, + status: segment.status, + buf, + }); + + addr = segment.next; + } + + Ok(Self { segments, buffer }) + } + + /// Returns the iterator over segments + pub fn iter(&self) -> impl Iterator> { + self.segments.iter() + } + + /// Returns the segments of mapped coded buffers. + pub fn segments(&self) -> &Vec> { + &self.segments + } +} + +impl<'p> Drop for MappedCodedBuffer<'p> { + fn drop(&mut self) { + let status = va_check(unsafe { + bindings::vaUnmapBuffer(self.buffer.0.context.display().handle(), self.buffer.id()) + }); + + if status.is_err() { + error!("vaUnmapBuffer failed: {}", status.unwrap_err()); + } + } +} + +/// Abstraction over the `EncMiscParameterBuffer` types we support. +pub enum EncMiscParameter { + /// Wrapper over `VAEncMiscParameterBuffer` with `VAEncMiscParameterFrameRate`. + FrameRate(EncMiscParameterFrameRate), + /// Wrapper over `VAEncMiscParameterBuffer` with `VAEncMiscParameterRateControl`. + RateControl(EncMiscParameterRateControl), + /// Wrapper over `VAEncMiscParameterBuffer` with `VAEncMiscParameterMaxSliceSize`. + MaxSliceSize(EncMiscParameterMaxSliceSize), + /// Wrapper over `VAEncMiscParameterBuffer` with `VAEncMiscParameterBufferMaxFrameSize`. + MaxFrameSize(EncMiscParameterBufferMaxFrameSize), + /// Wrapper over `VAEncMiscParameterBuffer` with `VAEncMiscParameterSkipFrame`. + SkipFrame(EncMiscParameterSkipFrame), + /// Wrapper over `VAEncMiscParameterBuffer` with `VAEncMiscParameterHRD`. + HRD(EncMiscParameterHRD), + /// Wrapper over `VAEncMiscParameterBuffer` with `VAEncMiscParameterBufferQualityLevel`. + QualityLevel(EncMiscParameterBufferQualityLevel), + /// Wrapper over `VAEncMiscParameterBuffer` with `VAEncMiscParameterQuantization`. + Quantization(EncMiscParameterQuantization), +} + +/// Abstraction over the `VAEncPackedHeaderType` enum values we support. +#[repr(u32)] +pub enum EncPackedHeaderType { + /// Sequence header + Sequence = bindings::VAEncPackedHeaderType::VAEncPackedHeaderSequence, + /// Picture header + Picture = bindings::VAEncPackedHeaderType::VAEncPackedHeaderPicture, + /// Slice header + Slice = bindings::VAEncPackedHeaderType::VAEncPackedHeaderSlice, + /// Raw data + RawData = bindings::VAEncPackedHeaderType::VAEncPackedHeaderRawData, +} + +/// Abstraction over `EncPackedHeaderParameterBuffer` types we support +pub struct EncPackedHeaderParameter(Box); + +impl EncPackedHeaderParameter { + /// Creates a new `EncPackedHeaderParameter` from the given `VAEncPackedHeaderParameterBuffer`. + pub fn new(type_: EncPackedHeaderType, length_in_bits: u32, has_emulation: bool) -> Self { + Self(Box::new(bindings::VAEncPackedHeaderParameterBuffer { + type_: type_ as _, + bit_length: length_in_bits, + has_emulation_bytes: has_emulation as u8, + ..Default::default() + })) + } + + /// Returns a mutable reference to the inner `VAEncPackedHeaderParameterBuffer`. + pub fn inner_mut(&mut self) -> &mut bindings::VAEncPackedHeaderParameterBuffer { + &mut self.0 + } +} diff --git a/shims/cros-libva/src/buffer/av1.rs b/shims/cros-libva/src/buffer/av1.rs new file mode 100644 index 00000000..bc607820 --- /dev/null +++ b/shims/cros-libva/src/buffer/av1.rs @@ -0,0 +1,1156 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Wrappers around AV1 `VABuffer` types. + +use crate::bindings; + +/// Wrapper over the `seq_fields` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1SeqFields(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_1); + +impl AV1SeqFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + still_picture: u32, + use_128x128_superblock: u32, + enable_filter_intra: u32, + enable_intra_edge_filter: u32, + enable_interintra_compound: u32, + enable_masked_compound: u32, + enable_dual_filter: u32, + enable_order_hint: u32, + enable_jnt_comp: u32, + enable_cdef: u32, + mono_chrome: u32, + color_range: u32, + subsampling_x: u32, + subsampling_y: u32, + chroma_sample_position: u32, + film_grain_params_present: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VADecPictureParameterBufferAV1__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + still_picture, + use_128x128_superblock, + enable_filter_intra, + enable_intra_edge_filter, + enable_interintra_compound, + enable_masked_compound, + enable_dual_filter, + enable_order_hint, + enable_jnt_comp, + enable_cdef, + mono_chrome, + color_range, + subsampling_x, + subsampling_y, + chroma_sample_position, + film_grain_params_present, + 0, + ); + + Self(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_1 { + fields: bindings::_VADecPictureParameterBufferAV1__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +/// Wrapper over the `segment_info_fields` bindgen field in `VASegmentationStructAV1`. +pub struct AV1SegmentInfoFields(bindings::_VASegmentationStructAV1__bindgen_ty_1); + +impl AV1SegmentInfoFields { + /// Creates the bindgen field + pub fn new(enabled: u32, update_map: u32, temporal_update: u32, update_data: u32) -> Self { + let _bitfield_1 = + bindings::_VASegmentationStructAV1__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + enabled, + update_map, + temporal_update, + update_data, + 0, + ); + + Self(bindings::_VASegmentationStructAV1__bindgen_ty_1 { + bits: bindings::_VASegmentationStructAV1__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +/// Wrapper over the `seg_info` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1Segmentation(bindings::VASegmentationStructAV1); + +impl AV1Segmentation { + /// Creates the bindgen field + pub fn new( + segment_info_fields: &AV1SegmentInfoFields, + feature_data: [[i16; 8usize]; 8usize], + feature_mask: [u8; 8usize], + ) -> Self { + let segment_info_fields = segment_info_fields.0; + Self(bindings::VASegmentationStructAV1 { + segment_info_fields, + feature_data, + feature_mask, + va_reserved: Default::default(), + }) + } +} + +/// Wrapper over the `film_grain_fields` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1FilmGrainFields(bindings::_VAFilmGrainStructAV1__bindgen_ty_1); + +impl AV1FilmGrainFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + apply_grain: u32, + chroma_scaling_from_luma: u32, + grain_scaling_minus_8: u32, + ar_coeff_lag: u32, + ar_coeff_shift_minus_6: u32, + grain_scale_shift: u32, + overlap_flag: u32, + clip_to_restricted_range: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAFilmGrainStructAV1__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + apply_grain, + chroma_scaling_from_luma, + grain_scaling_minus_8, + ar_coeff_lag, + ar_coeff_shift_minus_6, + grain_scale_shift, + overlap_flag, + clip_to_restricted_range, + 0, + ); + Self(bindings::_VAFilmGrainStructAV1__bindgen_ty_1 { + bits: bindings::_VAFilmGrainStructAV1__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +/// Wrapper over the `film_grain_info` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1FilmGrain(bindings::VAFilmGrainStructAV1); + +impl AV1FilmGrain { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + film_grain_info_fields: &AV1FilmGrainFields, + grain_seed: u16, + num_y_points: u8, + point_y_value: [u8; 14usize], + point_y_scaling: [u8; 14usize], + num_cb_points: u8, + point_cb_value: [u8; 10usize], + point_cb_scaling: [u8; 10usize], + num_cr_points: u8, + point_cr_value: [u8; 10usize], + point_cr_scaling: [u8; 10usize], + ar_coeffs_y: [i8; 24usize], + ar_coeffs_cb: [i8; 25usize], + ar_coeffs_cr: [i8; 25usize], + cb_mult: u8, + cb_luma_mult: u8, + cb_offset: u16, + cr_mult: u8, + cr_luma_mult: u8, + cr_offset: u16, + ) -> Self { + let film_grain_info_fields = film_grain_info_fields.0; + Self(bindings::VAFilmGrainStructAV1 { + film_grain_info_fields, + grain_seed, + num_y_points, + point_y_value, + point_y_scaling, + num_cb_points, + point_cb_value, + point_cb_scaling, + num_cr_points, + point_cr_value, + point_cr_scaling, + ar_coeffs_y, + ar_coeffs_cb, + ar_coeffs_cr, + cb_mult, + cb_luma_mult, + cb_offset, + cr_mult, + cr_luma_mult, + cr_offset, + va_reserved: Default::default(), + }) + } +} + +/// Wrapper over the `pic_info_fields` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1PicInfoFields(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_2); + +impl AV1PicInfoFields { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + frame_type: u32, + show_frame: u32, + showable_frame: u32, + error_resilient_mode: u32, + disable_cdf_update: u32, + allow_screen_content_tools: u32, + force_integer_mv: u32, + allow_intrabc: u32, + use_superres: u32, + allow_high_precision_mv: u32, + is_motion_mode_switchable: u32, + use_ref_frame_mvs: u32, + disable_frame_end_update_cdf: u32, + uniform_tile_spacing_flag: u32, + allow_warped_motion: u32, + large_scale_tile: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VADecPictureParameterBufferAV1__bindgen_ty_2__bindgen_ty_1::new_bitfield_1( + frame_type, + show_frame, + showable_frame, + error_resilient_mode, + disable_cdf_update, + allow_screen_content_tools, + force_integer_mv, + allow_intrabc, + use_superres, + allow_high_precision_mv, + is_motion_mode_switchable, + use_ref_frame_mvs, + disable_frame_end_update_cdf, + uniform_tile_spacing_flag, + allow_warped_motion, + large_scale_tile, + 0, + ); + Self(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_2 { + bits: bindings::_VADecPictureParameterBufferAV1__bindgen_ty_2__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +/// Wrapper over the `loop_filter_fields` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1LoopFilterFields(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_3); + +impl AV1LoopFilterFields { + /// Creates the wrapper + pub fn new(sharpness_level: u8, mode_ref_delta_enabled: u8, mode_ref_delta_update: u8) -> Self { + let _bitfield_1 = + bindings::_VADecPictureParameterBufferAV1__bindgen_ty_3__bindgen_ty_1::new_bitfield_1( + sharpness_level, + mode_ref_delta_enabled, + mode_ref_delta_update, + 0, + ); + Self(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_3 { + bits: bindings::_VADecPictureParameterBufferAV1__bindgen_ty_3__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +/// Wrapper over the `wm` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1WarpedMotionParams(bindings::VAWarpedMotionParamsAV1); + +impl AV1WarpedMotionParams { + /// Creates the wrapper + pub fn new( + wmtype: bindings::VAAV1TransformationType::Type, + wmmat: [i32; 8], + invalid: u8, + ) -> Self { + Self(bindings::VAWarpedMotionParamsAV1 { + wmtype, + wmmat, + invalid, + va_reserved: Default::default(), + }) + } +} + +/// Wrapper over the `loop_restoration_fields` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1LoopRestorationFields(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_6); + +impl AV1LoopRestorationFields { + /// Creates the wrapper + pub fn new( + yframe_restoration_type: u16, + cbframe_restoration_type: u16, + crframe_restoration_type: u16, + lr_unit_shift: u16, + lr_uv_shift: u16, + ) -> Self { + let _bitfield_1 = + bindings::_VADecPictureParameterBufferAV1__bindgen_ty_6__bindgen_ty_1::new_bitfield_1( + yframe_restoration_type, + cbframe_restoration_type, + crframe_restoration_type, + lr_unit_shift, + lr_uv_shift, + 0, + ); + Self(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_6 { + bits: bindings::_VADecPictureParameterBufferAV1__bindgen_ty_6__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +/// Wrapper over the `mode_control_fields` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1ModeControlFields(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_5); + +impl AV1ModeControlFields { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + delta_q_present_flag: u32, + log2_delta_q_res: u32, + delta_lf_present_flag: u32, + log2_delta_lf_res: u32, + delta_lf_multi: u32, + tx_mode: u32, + reference_select: u32, + reduced_tx_set_used: u32, + skip_mode_present: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VADecPictureParameterBufferAV1__bindgen_ty_5__bindgen_ty_1::new_bitfield_1( + delta_q_present_flag, + log2_delta_q_res, + delta_lf_present_flag, + log2_delta_lf_res, + delta_lf_multi, + tx_mode, + reference_select, + reduced_tx_set_used, + skip_mode_present, + 0, + ); + Self(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_5 { + bits: bindings::_VADecPictureParameterBufferAV1__bindgen_ty_5__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +/// Wrapper over the `qmatrix_fields` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1QMatrixFields(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_4); + +impl AV1QMatrixFields { + /// Creates the wrapper + pub fn new(using_qmatrix: u16, qm_y: u16, qm_u: u16, qm_v: u16) -> Self { + let _bitfield_1 = + bindings::_VADecPictureParameterBufferAV1__bindgen_ty_4__bindgen_ty_1::new_bitfield_1( + using_qmatrix, + qm_y, + qm_u, + qm_v, + 0, + ); + Self(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_4 { + bits: bindings::_VADecPictureParameterBufferAV1__bindgen_ty_4__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +/// A wrapper over `VADecPictureParameterBufferAV1` FFI type +pub struct PictureParameterBufferAV1(Box); + +impl PictureParameterBufferAV1 { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + profile: u8, + order_hint_bits_minus_1: u8, + bit_depth_idx: u8, + matrix_coefficients: u8, + seq_info_fields: &AV1SeqFields, + current_frame: bindings::VASurfaceID, + current_display_picture: bindings::VASurfaceID, + mut anchor_frames_list: Vec, + frame_width_minus1: u16, + frame_height_minus1: u16, + output_frame_width_in_tiles_minus_1: u16, + output_frame_height_in_tiles_minus_1: u16, + ref_frame_map: [bindings::VASurfaceID; 8usize], + ref_frame_idx: [u8; 7usize], + primary_ref_frame: u8, + order_hint: u8, + seg_info: &AV1Segmentation, + film_grain_info: &AV1FilmGrain, + tile_cols: u8, + tile_rows: u8, + width_in_sbs_minus_1: [u16; 63usize], + height_in_sbs_minus_1: [u16; 63usize], + tile_count_minus_1: u16, + context_update_tile_id: u16, + pic_info_fields: &AV1PicInfoFields, + superres_scale_denominator: u8, + interp_filter: u8, + filter_level: [u8; 2usize], + filter_level_u: u8, + filter_level_v: u8, + loop_filter_info_fields: &AV1LoopFilterFields, + ref_deltas: [i8; 8usize], + mode_deltas: [i8; 2usize], + base_qindex: u8, + y_dc_delta_q: i8, + u_dc_delta_q: i8, + u_ac_delta_q: i8, + v_dc_delta_q: i8, + v_ac_delta_q: i8, + qmatrix_fields: &AV1QMatrixFields, + mode_control_fields: &AV1ModeControlFields, + cdef_damping_minus_3: u8, + cdef_bits: u8, + cdef_y_strengths: [u8; 8usize], + cdef_uv_strengths: [u8; 8usize], + loop_restoration_fields: &AV1LoopRestorationFields, + wm: &[AV1WarpedMotionParams; 7usize], + ) -> Self { + let seq_info_fields = seq_info_fields.0; + let seg_info = seg_info.0; + let pic_info_fields = pic_info_fields.0; + let loop_filter_info_fields = loop_filter_info_fields.0; + let qmatrix_fields = qmatrix_fields.0; + let mode_control_fields = mode_control_fields.0; + + let anchor_frames_num = anchor_frames_list.len() as u8; + let anchor_frames_list = anchor_frames_list.as_mut_ptr(); + + let film_grain_info = film_grain_info.0; + let loop_restoration_fields = loop_restoration_fields.0; + + // Will not panic, as the arrays are the same size. + let wm = wm + .iter() + .map(|wm| wm.0) + .collect::>() + .try_into() + .unwrap(); + + Self(Box::new(bindings::VADecPictureParameterBufferAV1 { + profile, + order_hint_bits_minus_1, + bit_depth_idx, + matrix_coefficients, + seq_info_fields, + current_frame, + current_display_picture, + anchor_frames_num, + anchor_frames_list, + frame_width_minus1, + frame_height_minus1, + output_frame_width_in_tiles_minus_1, + output_frame_height_in_tiles_minus_1, + ref_frame_map, + ref_frame_idx, + primary_ref_frame, + order_hint, + seg_info, + film_grain_info, + tile_cols, + tile_rows, + width_in_sbs_minus_1, + height_in_sbs_minus_1, + tile_count_minus_1, + context_update_tile_id, + pic_info_fields, + superres_scale_denominator, + interp_filter, + filter_level, + filter_level_u, + filter_level_v, + loop_filter_info_fields, + ref_deltas, + mode_deltas, + base_qindex, + y_dc_delta_q, + u_dc_delta_q, + u_ac_delta_q, + v_dc_delta_q, + v_ac_delta_q, + qmatrix_fields, + mode_control_fields, + cdef_damping_minus_3, + cdef_bits, + cdef_y_strengths, + cdef_uv_strengths, + loop_restoration_fields, + wm, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VADecPictureParameterBufferAV1 { + self.0.as_mut() + } +} + +/// A wrapper over an array of the `VASliceParameterBufferAV1` FFI type. This +/// allows for passing all tile parameters in a single call if multiple tiles +/// are present in the tile group. +#[derive(Default)] +pub struct SliceParameterBufferAV1(Vec); + +impl SliceParameterBufferAV1 { + /// Creates the wrapper + pub fn new() -> Self { + Default::default() + } + + /// Adds a slice parameter to the wrapper + #[allow(clippy::too_many_arguments)] + pub fn add_slice_parameter( + &mut self, + slice_data_size: u32, + slice_data_offset: u32, + slice_data_flag: u32, + tile_row: u16, + tile_column: u16, + tg_start: u16, + tg_end: u16, + anchor_frame_idx: u8, + tile_idx_in_tile_list: u16, + ) { + self.0.push(bindings::VASliceParameterBufferAV1 { + slice_data_size, + slice_data_offset, + slice_data_flag, + tile_row, + tile_column, + tg_start, + tg_end, + anchor_frame_idx, + tile_idx_in_tile_list, + va_reserved: Default::default(), + }); + } + + pub(crate) fn inner_mut(&mut self) -> &mut Vec { + self.0.as_mut() + } +} + +pub struct AV1EncSeqFields(bindings::_VAEncSequenceParameterBufferAV1__bindgen_ty_1); + +impl AV1EncSeqFields { + pub fn new( + still_picture: bool, + use_128x128_superblock: bool, + enable_filter_intra: bool, + enable_intra_edge_filter: bool, + enable_interintra_compound: bool, + enable_masked_compound: bool, + enable_warped_motion: bool, + enable_dual_filter: bool, + enable_order_hint: bool, + enable_jnt_comp: bool, + enable_ref_frame_mvs: bool, + enable_superres: bool, + enable_cdef: bool, + enable_restoration: bool, + bit_depth_minus8: u32, + subsampling_x: bool, + subsampling_y: bool, + mono_chrome: bool, + ) -> Self { + let still_picture = still_picture as u32; + let use_128x128_superblock = use_128x128_superblock as u32; + let enable_filter_intra = enable_filter_intra as u32; + let enable_intra_edge_filter = enable_intra_edge_filter as u32; + let enable_interintra_compound = enable_interintra_compound as u32; + let enable_masked_compound = enable_masked_compound as u32; + let enable_warped_motion = enable_warped_motion as u32; + let enable_dual_filter = enable_dual_filter as u32; + let enable_order_hint = enable_order_hint as u32; + let enable_jnt_comp = enable_jnt_comp as u32; + let enable_ref_frame_mvs = enable_ref_frame_mvs as u32; + let enable_superres = enable_superres as u32; + let enable_cdef = enable_cdef as u32; + let enable_restoration = enable_restoration as u32; + let subsampling_x = subsampling_x as u32; + let subsampling_y = subsampling_y as u32; + let mono_chrome = mono_chrome as u32; + + let _bitfield_1 = + bindings::_VAEncSequenceParameterBufferAV1__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + still_picture, + use_128x128_superblock, + enable_filter_intra, + enable_intra_edge_filter, + enable_interintra_compound, + enable_masked_compound, + enable_warped_motion, + enable_dual_filter, + enable_order_hint, + enable_jnt_comp, + enable_ref_frame_mvs, + enable_superres, + enable_cdef, + enable_restoration, + bit_depth_minus8, + subsampling_x, + subsampling_y, + #[cfg(libva_1_19_or_higher)] + mono_chrome, + Default::default(), + ); + + Self(bindings::_VAEncSequenceParameterBufferAV1__bindgen_ty_1 { + bits: bindings::_VAEncSequenceParameterBufferAV1__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct EncSequenceParameterBufferAV1(Box); + +impl EncSequenceParameterBufferAV1 { + pub fn new( + seq_profile: u8, + seq_level_idx: u8, + seq_tier: u8, + hierarchical_flag: u8, + intra_period: u32, + ip_period: u32, + bits_per_second: u32, + seq_fields: &AV1EncSeqFields, + order_hint_bits_minus_1: u8, + ) -> Self { + let seq_fields = seq_fields.0; + + Self(Box::new(bindings::_VAEncSequenceParameterBufferAV1 { + seq_profile, + seq_level_idx, + seq_tier, + #[cfg(libva_1_16_or_higher)] + hierarchical_flag, + intra_period, + ip_period, + bits_per_second, + seq_fields, + order_hint_bits_minus_1, + ..Default::default() + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncSequenceParameterBufferAV1 { + &mut self.0 + } +} + +#[derive(Default)] +pub struct RefFrameCtrlAV1(bindings::VARefFrameCtrlAV1); + +impl RefFrameCtrlAV1 { + pub fn new( + search_idx0: u32, + search_idx1: u32, + search_idx2: u32, + search_idx3: u32, + search_idx4: u32, + search_idx5: u32, + search_idx6: u32, + ) -> Self { + let _bitfield_1 = bindings::VARefFrameCtrlAV1__bindgen_ty_1::new_bitfield_1( + search_idx0, + search_idx1, + search_idx2, + search_idx3, + search_idx4, + search_idx5, + search_idx6, + Default::default(), + ); + + Self(bindings::VARefFrameCtrlAV1 { + fields: bindings::VARefFrameCtrlAV1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct AV1EncPictureFlags(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_1); + +impl AV1EncPictureFlags { + pub fn new( + frame_type: u32, + error_resilient_mode: bool, + disable_cdf_update: bool, + use_superres: bool, + allow_high_precision_mv: bool, + use_ref_frame_mvs: bool, + disable_frame_end_update_cdf: bool, + reduced_tx_set: bool, + enable_frame_obu: bool, + long_term_reference: bool, + disable_frame_recon: bool, + allow_intrabc: bool, + palette_mode_enable: bool, + allow_screen_content_tools: bool, + force_integer_mv: bool, + ) -> Self { + let error_resilient_mode = error_resilient_mode as u32; + let disable_cdf_update = disable_cdf_update as u32; + let use_superres = use_superres as u32; + let allow_high_precision_mv = allow_high_precision_mv as u32; + let use_ref_frame_mvs = use_ref_frame_mvs as u32; + let disable_frame_end_update_cdf = disable_frame_end_update_cdf as u32; + let reduced_tx_set = reduced_tx_set as u32; + let enable_frame_obu = enable_frame_obu as u32; + let long_term_reference = long_term_reference as u32; + let disable_frame_recon = disable_frame_recon as u32; + let allow_intrabc = allow_intrabc as u32; + let palette_mode_enable = palette_mode_enable as u32; + #[cfg(libva_1_21_or_higher)] + let allow_screen_content_tools = allow_screen_content_tools as u32; + #[cfg(libva_1_21_or_higher)] + let force_integer_mv = force_integer_mv as u32; + + let _bitfield_1 = { + bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + frame_type, + error_resilient_mode, + disable_cdf_update, + use_superres, + allow_high_precision_mv, + use_ref_frame_mvs, + disable_frame_end_update_cdf, + reduced_tx_set, + enable_frame_obu, + long_term_reference, + disable_frame_recon, + allow_intrabc, + palette_mode_enable, + #[cfg(libva_1_21_or_higher)] + allow_screen_content_tools, + #[cfg(libva_1_21_or_higher)] + force_integer_mv, + Default::default(), + ) + }; + Self(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_1 { + bits: bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct AV1EncLoopFilterFlags(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_2); + +impl AV1EncLoopFilterFlags { + pub fn new( + sharpness_level: u8, + mode_ref_delta_enabled: bool, + mode_ref_delta_update: bool, + ) -> Self { + let mode_ref_delta_enabled = mode_ref_delta_enabled as u8; + let mode_ref_delta_update = mode_ref_delta_update as u8; + + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_2__bindgen_ty_1::new_bitfield_1( + sharpness_level, + mode_ref_delta_enabled, + mode_ref_delta_update, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_2 { + bits: bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_2__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct AV1EncQMatrixFlags(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_3); + +impl AV1EncQMatrixFlags { + pub fn new(using_qmatrix: bool, qm_y: u16, qm_u: u16, qm_v: u16) -> Self { + let using_qmatrix = using_qmatrix as u16; + + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_3__bindgen_ty_1::new_bitfield_1( + using_qmatrix, + qm_y, + qm_u, + qm_v, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_3 { + bits: bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_3__bindgen_ty_1 { + _bitfield_1, + _bitfield_align_1: Default::default(), + }, + }) + } +} + +#[derive(Default)] +pub struct AV1EncModeControlFlags(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_4); + +impl AV1EncModeControlFlags { + pub fn new( + delta_q_present: bool, + delta_q_res: u32, + delta_lf_present: bool, + delta_lf_res: u32, + delta_lf_multi: bool, + tx_mode: u32, + reference_mode: u32, + skip_mode_present: bool, + ) -> Self { + let delta_q_present = delta_q_present as u32; + let delta_lf_present = delta_lf_present as u32; + let delta_lf_multi = delta_lf_multi as u32; + let skip_mode_present = skip_mode_present as u32; + + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_4__bindgen_ty_1::new_bitfield_1( + delta_q_present, + delta_q_res, + delta_lf_present, + delta_lf_res, + delta_lf_multi, + tx_mode, + reference_mode, + skip_mode_present, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_4 { + bits: bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_4__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct EncSegParamFlagsAV1(bindings::_VAEncSegParamAV1__bindgen_ty_1); + +impl EncSegParamFlagsAV1 { + pub fn new( + segmentation_enabled: bool, + segmentation_update_map: bool, + segmentation_temporal_update: bool, + ) -> Self { + let segmentation_enabled = segmentation_enabled as u8; + let segmentation_update_map = segmentation_update_map as u8; + let segmentation_temporal_update = segmentation_temporal_update as u8; + + let _bitfield_1 = bindings::_VAEncSegParamAV1__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + segmentation_enabled, + segmentation_update_map, + segmentation_temporal_update, + Default::default(), + ); + + Self(bindings::_VAEncSegParamAV1__bindgen_ty_1 { + bits: bindings::_VAEncSegParamAV1__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct EncSegParamAV1(bindings::VAEncSegParamAV1); + +impl EncSegParamAV1 { + pub fn new( + seg_flags: &EncSegParamFlagsAV1, + segment_number: u8, + feature_data: [[i16; 8usize]; 8usize], + feature_mask: [u8; 8usize], + ) -> Self { + let seg_flags = seg_flags.0; + + Self(bindings::_VAEncSegParamAV1 { + seg_flags, + segment_number, + feature_data, + feature_mask, + va_reserved: Default::default(), + }) + } +} + +pub struct AV1EncLoopRestorationFlags(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_5); + +impl AV1EncLoopRestorationFlags { + pub fn new( + yframe_restoration_type: u16, + cbframe_restoration_type: u16, + crframe_restoration_type: u16, + lr_unit_shift: u16, + lr_uv_shift: bool, + ) -> Self { + let lr_uv_shift = lr_uv_shift as u16; + + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_5__bindgen_ty_1::new_bitfield_1( + yframe_restoration_type, + cbframe_restoration_type, + crframe_restoration_type, + lr_unit_shift, + lr_uv_shift, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_5 { + bits: bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_5__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default, Copy, Clone)] +pub struct EncWarpedMotionParamsAV1(bindings::VAEncWarpedMotionParamsAV1); + +impl EncWarpedMotionParamsAV1 { + pub fn new( + wmtype: bindings::VAEncTransformationTypeAV1::Type, + wmmat: [i32; 8usize], + invalid: u8, + ) -> Self { + Self(bindings::_VAEncWarpedMotionParamsAV1 { + wmtype, + wmmat, + invalid, + va_reserved: Default::default(), + }) + } +} + +pub struct AV1EncTileGroupObuHdrInfo(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_6); + +impl AV1EncTileGroupObuHdrInfo { + pub fn new( + obu_extension_flag: bool, + obu_has_size_field: bool, + temporal_id: u8, + spatial_id: u8, + ) -> Self { + let obu_extension_flag = obu_extension_flag as u8; + let obu_has_size_field = obu_has_size_field as u8; + + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_6__bindgen_ty_1::new_bitfield_1( + obu_extension_flag, + obu_has_size_field, + temporal_id, + spatial_id, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_6 { + bits: bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_6__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct EncPictureParameterBufferAV1(Box); + +impl EncPictureParameterBufferAV1 { + pub fn new( + frame_width_minus_1: u16, + frame_height_minus_1: u16, + reconstructed_frame: bindings::VASurfaceID, + coded_buf: bindings::VABufferID, + reference_frames: [bindings::VASurfaceID; 8usize], + ref_frame_idx: [u8; 7usize], + hierarchical_level_plus1: u8, + primary_ref_frame: u8, + order_hint: u8, + refresh_frame_flags: u8, + ref_frame_ctrl_l0: &RefFrameCtrlAV1, + ref_frame_ctrl_l1: &RefFrameCtrlAV1, + picture_flags: &AV1EncPictureFlags, + seg_id_block_size: u8, + num_tile_groups_minus1: u8, + temporal_id: u8, + filter_level: [u8; 2usize], + filter_level_u: u8, + filter_level_v: u8, + loop_filter_flags: &AV1EncLoopFilterFlags, + superres_scale_denominator: u8, + interpolation_filter: u8, + ref_deltas: [i8; 8usize], + mode_deltas: [i8; 2usize], + base_qindex: u8, + y_dc_delta_q: i8, + u_dc_delta_q: i8, + u_ac_delta_q: i8, + v_dc_delta_q: i8, + v_ac_delta_q: i8, + min_base_qindex: u8, + max_base_qindex: u8, + qmatrix_flags: &AV1EncQMatrixFlags, + mode_control_flags: &AV1EncModeControlFlags, + segments: &EncSegParamAV1, + tile_cols: u8, + tile_rows: u8, + width_in_sbs_minus_1: [u16; 63usize], + height_in_sbs_minus_1: [u16; 63usize], + context_update_tile_id: u16, + cdef_damping_minus_3: u8, + cdef_bits: u8, + cdef_y_strengths: [u8; 8usize], + cdef_uv_strengths: [u8; 8usize], + loop_restoration_flags: &AV1EncLoopRestorationFlags, + wm: [EncWarpedMotionParamsAV1; 7usize], + bit_offset_qindex: u32, + bit_offset_segmentation: u32, + bit_offset_loopfilter_params: u32, + bit_offset_cdef_params: u32, + size_in_bits_cdef_params: u32, + byte_offset_frame_hdr_obu_size: u32, + size_in_bits_frame_hdr_obu: u32, + tile_group_obu_hdr_info: &AV1EncTileGroupObuHdrInfo, + number_skip_frames: u8, + skip_frames_reduced_size: i32, + ) -> Self { + let ref_frame_ctrl_l0 = ref_frame_ctrl_l0.0; + let ref_frame_ctrl_l1 = ref_frame_ctrl_l1.0; + let picture_flags = picture_flags.0; + let loop_filter_flags = loop_filter_flags.0; + let qmatrix_flags = qmatrix_flags.0; + let mode_control_flags = mode_control_flags.0; + let segments = segments.0; + let loop_restoration_flags = loop_restoration_flags.0; + let wm = wm.map(|e| e.0); + let tile_group_obu_hdr_info = tile_group_obu_hdr_info.0; + + Self(Box::new(bindings::_VAEncPictureParameterBufferAV1 { + frame_width_minus_1, + frame_height_minus_1, + reconstructed_frame, + coded_buf, + reference_frames, + ref_frame_idx, + #[cfg(libva_1_19_or_higher)] + hierarchical_level_plus1, + primary_ref_frame, + order_hint, + refresh_frame_flags, + ref_frame_ctrl_l0, + ref_frame_ctrl_l1, + picture_flags, + seg_id_block_size, + num_tile_groups_minus1, + temporal_id, + filter_level, + filter_level_u, + filter_level_v, + loop_filter_flags, + superres_scale_denominator, + interpolation_filter, + ref_deltas, + mode_deltas, + base_qindex, + y_dc_delta_q, + u_dc_delta_q, + u_ac_delta_q, + v_dc_delta_q, + v_ac_delta_q, + min_base_qindex, + max_base_qindex, + qmatrix_flags, + mode_control_flags, + segments, + tile_cols, + tile_rows, + width_in_sbs_minus_1, + height_in_sbs_minus_1, + context_update_tile_id, + cdef_damping_minus_3, + cdef_bits, + cdef_y_strengths, + cdef_uv_strengths, + loop_restoration_flags, + wm, + bit_offset_qindex, + bit_offset_segmentation, + bit_offset_loopfilter_params, + bit_offset_cdef_params, + size_in_bits_cdef_params, + byte_offset_frame_hdr_obu_size, + size_in_bits_frame_hdr_obu, + tile_group_obu_hdr_info, + number_skip_frames, + skip_frames_reduced_size, + ..Default::default() + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncPictureParameterBufferAV1 { + &mut self.0 + } +} + +pub struct EncTileGroupBufferAV1(Box); + +impl EncTileGroupBufferAV1 { + pub fn new(tg_start: u8, tg_end: u8) -> Self { + Self(Box::new(bindings::VAEncTileGroupBufferAV1 { + tg_start, + tg_end, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncTileGroupBufferAV1 { + &mut self.0 + } +} diff --git a/shims/cros-libva/src/buffer/enc_jpeg.rs b/shims/cros-libva/src/buffer/enc_jpeg.rs new file mode 100644 index 00000000..3b656ed4 --- /dev/null +++ b/shims/cros-libva/src/buffer/enc_jpeg.rs @@ -0,0 +1,159 @@ +// Copyright 2025 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Wrappers around JPEG-Encoding `VABuffer` types. + +use crate::bindings; + +/// Wrapper over the `pic_flags` bindgen field in `VAEncPictureParameterBufferJPEG` +pub struct PicFlags(bindings::_VAEncPictureParameterBufferJPEG__bindgen_ty_1); + +impl PicFlags { + pub fn new( + profile: u32, + progressive: u32, + huffman: u32, + interleaved: u32, + differential: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferJPEG__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + profile, + progressive, + huffman, + interleaved, + differential, + ); + Self(bindings::_VAEncPictureParameterBufferJPEG__bindgen_ty_1 { + bits: bindings::_VAEncPictureParameterBufferJPEG__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + }, + }) + } +} + +/// Wrapper over the `VAEncPictureParameterBufferJPEG` FFI type. +pub struct EncPictureParameterBufferJPEG(Box); + +impl EncPictureParameterBufferJPEG { + /// Creates the wrapper. + pub fn new( + reconstructed_picture: bindings::VASurfaceID, + picture_width: u16, + picture_height: u16, + coded_buf: bindings::VABufferID, + pic_flags: PicFlags, + sample_bit_depth: u8, + num_scan: u8, + num_components: u16, + component_id: [u8; 4usize], + quantiser_table_selector: [u8; 4usize], + quality: u8, + ) -> Self { + Self(Box::new(bindings::VAEncPictureParameterBufferJPEG { + reconstructed_picture, + picture_width, + picture_height, + coded_buf, + pic_flags: pic_flags.0, + sample_bit_depth, + num_scan, + num_components, + component_id, + quantiser_table_selector, + quality, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncPictureParameterBufferJPEG { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAEncPictureParameterBufferJPEG { + self.0.as_ref() + } +} + +/// Wrapper over the `components` bindgen field in `VAEncSliceParameterBufferJPEG`. +pub struct EncSliceParameterBufferJPEGComponent( + bindings::_VAEncSliceParameterBufferJPEG__bindgen_ty_1, +); + +impl EncSliceParameterBufferJPEGComponent { + /// Creates the bindgen field. + pub fn new(component_selector: u8, dc_table_selector: u8, ac_table_selector: u8) -> Self { + Self(bindings::_VAEncSliceParameterBufferJPEG__bindgen_ty_1 { + component_selector, + dc_table_selector, + ac_table_selector, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::_VAEncSliceParameterBufferJPEG__bindgen_ty_1 { + &self.0 + } +} + +/// Wrapper over the `VAEncSliceParameterBufferJPEG` FFI type. +pub struct EncSliceParameterBufferJPEG(Box); + +impl EncSliceParameterBufferJPEG { + /// Creates the wrapper. + pub fn new( + restart_interval: u16, + num_components: u16, + components: [EncSliceParameterBufferJPEGComponent; 4usize], + ) -> Self { + Self(Box::new(bindings::VAEncSliceParameterBufferJPEG { + restart_interval, + num_components, + components: components.map(|component| component.0), + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncSliceParameterBufferJPEG { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAEncSliceParameterBufferJPEG { + self.0.as_ref() + } +} + +/// Wrapper over the `VAQMatrixBufferJPEG` FFI type. +pub struct QMatrixBufferJPEG(Box); + +impl QMatrixBufferJPEG { + /// Creates the wrapper. + pub fn new( + load_lum_quantiser_matrix: i32, + load_chroma_quantiser_matrix: i32, + lum_quantiser_matrix: [u8; 64usize], + chroma_quantiser_matrix: [u8; 64usize], + ) -> Self { + Self(Box::new(bindings::VAQMatrixBufferJPEG { + load_lum_quantiser_matrix, + load_chroma_quantiser_matrix, + lum_quantiser_matrix, + chroma_quantiser_matrix, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAQMatrixBufferJPEG { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAQMatrixBufferJPEG { + self.0.as_ref() + } +} diff --git a/shims/cros-libva/src/buffer/enc_misc.rs b/shims/cros-libva/src/buffer/enc_misc.rs new file mode 100644 index 00000000..5a5001c4 --- /dev/null +++ b/shims/cros-libva/src/buffer/enc_misc.rs @@ -0,0 +1,337 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Wrappers around `VAEncMisc*` types. + +use crate::bindings; + +#[repr(C)] +#[derive(Default)] +pub struct MiscEncParamBuffer { + hdr: bindings::VAEncMiscParameterBuffer, + value: T, +} + +impl MiscEncParamBuffer { + fn new(type_: bindings::VAEncMiscParameterType::Type, value: T) -> Self { + Self { + hdr: bindings::_VAEncMiscParameterBuffer { + type_, + data: Default::default(), + }, + value, + } + } + + fn new_boxed(type_: bindings::VAEncMiscParameterType::Type, value: T) -> Box { + Box::new(Self::new(type_, value)) + } +} + +#[derive(Default)] +pub struct EncMiscParameterFrameRate( + Box>, +); + +impl EncMiscParameterFrameRate { + pub fn new(framerate: u32, temporal_id: u32) -> Self { + let _bitfield_1 = + bindings::_VAEncMiscParameterFrameRate__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + temporal_id, + Default::default(), + ); + + Self(MiscEncParamBuffer::new_boxed( + bindings::VAEncMiscParameterType::VAEncMiscParameterTypeFrameRate, + bindings::_VAEncMiscParameterFrameRate { + framerate, + framerate_flags: bindings::_VAEncMiscParameterFrameRate__bindgen_ty_1 { + bits: bindings::_VAEncMiscParameterFrameRate__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }, + ..Default::default() + }, + )) + } + + pub fn inner(&self) -> &MiscEncParamBuffer { + &self.0 + } + + pub(crate) fn inner_mut( + &mut self, + ) -> &mut MiscEncParamBuffer { + &mut self.0 + } +} + +#[derive(Default)] +pub struct RcFlags(bindings::_VAEncMiscParameterRateControl__bindgen_ty_1); + +impl RcFlags { + pub fn new( + reset: u32, + disable_frame_skip: u32, + disable_bit_stuffing: u32, + mb_rate_control: u32, + temporal_id: u32, + cfs_i_frames: u32, + enable_parallel_brc: u32, + enable_dynamic_scaling: u32, + frame_tolerance_mode: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncMiscParameterRateControl__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + reset, + disable_frame_skip, + disable_bit_stuffing, + mb_rate_control, + temporal_id, + cfs_i_frames, + enable_parallel_brc, + enable_dynamic_scaling, + frame_tolerance_mode, + Default::default(), + ); + + Self(bindings::_VAEncMiscParameterRateControl__bindgen_ty_1 { + bits: bindings::_VAEncMiscParameterRateControl__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct EncMiscParameterRateControl( + Box>, +); + +impl EncMiscParameterRateControl { + pub fn new( + bits_per_second: u32, + target_percentage: u32, + window_size: u32, + initial_qp: u32, + min_qp: u32, + basic_unit_size: u32, + rc_flags: RcFlags, + icq_quality_factor: u32, + max_qp: u32, + quality_factor: u32, + target_frame_size: u32, + ) -> Self { + Self(MiscEncParamBuffer::new_boxed( + bindings::VAEncMiscParameterType::VAEncMiscParameterTypeRateControl, + bindings::VAEncMiscParameterRateControl { + bits_per_second, + target_percentage, + window_size, + initial_qp, + min_qp, + basic_unit_size, + rc_flags: rc_flags.0, + ICQ_quality_factor: icq_quality_factor, + max_qp, + quality_factor, + target_frame_size, + ..Default::default() + }, + )) + } + + pub fn inner(&self) -> &MiscEncParamBuffer { + &self.0 + } + + pub(crate) fn inner_mut( + &mut self, + ) -> &mut MiscEncParamBuffer { + &mut self.0 + } +} + +#[derive(Default)] +pub struct EncMiscParameterMaxSliceSize( + Box>, +); + +impl EncMiscParameterMaxSliceSize { + pub fn new(max_slice_size: u32) -> Self { + Self(MiscEncParamBuffer::new_boxed( + bindings::VAEncMiscParameterType::VAEncMiscParameterTypeMaxFrameSize, + bindings::VAEncMiscParameterMaxSliceSize { + max_slice_size, + ..Default::default() + }, + )) + } + + pub fn inner(&self) -> &MiscEncParamBuffer { + &self.0 + } + + pub(crate) fn inner_mut( + &mut self, + ) -> &mut MiscEncParamBuffer { + &mut self.0 + } +} + +#[derive(Default)] +pub struct EncMiscParameterBufferMaxFrameSize( + Box>, +); + +impl EncMiscParameterBufferMaxFrameSize { + pub fn new(max_frame_size: u32) -> Self { + Self(MiscEncParamBuffer::new_boxed( + bindings::VAEncMiscParameterType::VAEncMiscParameterTypeMaxFrameSize, + bindings::VAEncMiscParameterBufferMaxFrameSize { + type_: bindings::VAEncMiscParameterType::VAEncMiscParameterTypeMaxFrameSize, + max_frame_size, + ..Default::default() + }, + )) + } + + pub fn inner(&self) -> &MiscEncParamBuffer { + &self.0 + } + + pub(crate) fn inner_mut( + &mut self, + ) -> &mut MiscEncParamBuffer { + &mut self.0 + } +} + +#[derive(Default)] +pub struct EncMiscParameterSkipFrame( + Box>, +); + +impl EncMiscParameterSkipFrame { + pub fn new(skip_frame_flag: u8, num_skip_frames: u8, size_skip_frames: u32) -> Self { + Self(MiscEncParamBuffer::new_boxed( + bindings::VAEncMiscParameterType::VAEncMiscParameterTypeSkipFrame, + bindings::VAEncMiscParameterSkipFrame { + skip_frame_flag, + num_skip_frames, + size_skip_frames, + ..Default::default() + }, + )) + } + + pub fn inner(&self) -> &MiscEncParamBuffer { + &self.0 + } + + pub(crate) fn inner_mut( + &mut self, + ) -> &mut MiscEncParamBuffer { + &mut self.0 + } +} + +#[derive(Default)] +pub struct EncMiscParameterHRD(Box>); + +impl EncMiscParameterHRD { + pub fn new(initial_buffer_fullness: u32, buffer_size: u32) -> Self { + Self(MiscEncParamBuffer::new_boxed( + bindings::VAEncMiscParameterType::VAEncMiscParameterTypeHRD, + bindings::VAEncMiscParameterHRD { + initial_buffer_fullness, + buffer_size, + ..Default::default() + }, + )) + } + + pub fn inner(&self) -> &MiscEncParamBuffer { + &self.0 + } + + pub(crate) fn inner_mut(&mut self) -> &mut MiscEncParamBuffer { + &mut self.0 + } +} + +#[derive(Default)] +pub struct EncMiscParameterBufferQualityLevel( + Box>, +); + +impl EncMiscParameterBufferQualityLevel { + pub fn new(quality_level: u32) -> Self { + Self(MiscEncParamBuffer::new_boxed( + bindings::VAEncMiscParameterType::VAEncMiscParameterTypeQualityLevel, + bindings::VAEncMiscParameterBufferQualityLevel { + quality_level, + ..Default::default() + }, + )) + } + + pub fn inner(&self) -> &MiscEncParamBuffer { + &self.0 + } + + pub(crate) fn inner_mut( + &mut self, + ) -> &mut MiscEncParamBuffer { + &mut self.0 + } +} + +#[derive(Default)] +pub struct EncMiscParameterQuantization( + Box>, +); + +impl EncMiscParameterQuantization { + pub fn new( + disable_trellis: bool, + enable_trellis_i: bool, + enable_trellis_p: bool, + enable_trellis_b: bool, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncMiscParameterQuantization__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + disable_trellis as u32, + enable_trellis_i as u32, + enable_trellis_p as u32, + enable_trellis_b as u32, + Default::default(), + ); + + Self(MiscEncParamBuffer::new_boxed( + bindings::VAEncMiscParameterType::VAEncMiscParameterTypeQuantization, + bindings::VAEncMiscParameterQuantization { + quantization_flags: bindings::_VAEncMiscParameterQuantization__bindgen_ty_1 { + bits: bindings::_VAEncMiscParameterQuantization__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }, + ..Default::default() + }, + )) + } + + pub fn inner(&self) -> &MiscEncParamBuffer { + &self.0 + } + + pub(crate) fn inner_mut( + &mut self, + ) -> &mut MiscEncParamBuffer { + &mut self.0 + } +} diff --git a/shims/cros-libva/src/buffer/h264.rs b/shims/cros-libva/src/buffer/h264.rs new file mode 100644 index 00000000..883ee108 --- /dev/null +++ b/shims/cros-libva/src/buffer/h264.rs @@ -0,0 +1,807 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Wrappers around H264 `VABuffer` types. + +use crate::bindings; + +/// Wrapper over the `VAPictureH264` FFI type. +pub struct PictureH264(bindings::VAPictureH264); + +impl PictureH264 { + /// Creates the wrapper + pub fn new( + picture_id: bindings::VASurfaceID, + frame_idx: u32, + flags: u32, + top_field_order_cnt: i32, + bottom_field_order_cnt: i32, + ) -> Self { + Self(bindings::VAPictureH264 { + picture_id, + frame_idx, + flags, + TopFieldOrderCnt: top_field_order_cnt, + BottomFieldOrderCnt: bottom_field_order_cnt, + va_reserved: Default::default(), + }) + } +} + +/// Wrapper over the `seq_fields` bindgen field in `VAPictureParameterBufferH264`. +pub struct H264SeqFields(bindings::_VAPictureParameterBufferH264__bindgen_ty_1); + +impl H264SeqFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + chroma_format_idc: u32, + residual_colour_transform_flag: u32, + gaps_in_frame_num_value_allowed_flag: u32, + frame_mbs_only_flag: u32, + mb_adaptive_frame_field_flag: u32, + direct_8x8_inference_flag: u32, + min_luma_bi_pred_size8x8: u32, + log2_max_frame_num_minus4: u32, + pic_order_cnt_type: u32, + log2_max_pic_order_cnt_lsb_minus4: u32, + delta_pic_order_always_zero_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAPictureParameterBufferH264__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + chroma_format_idc, + residual_colour_transform_flag, + gaps_in_frame_num_value_allowed_flag, + frame_mbs_only_flag, + mb_adaptive_frame_field_flag, + direct_8x8_inference_flag, + min_luma_bi_pred_size8x8, + log2_max_frame_num_minus4, + pic_order_cnt_type, + log2_max_pic_order_cnt_lsb_minus4, + delta_pic_order_always_zero_flag, + ); + + Self(bindings::_VAPictureParameterBufferH264__bindgen_ty_1 { + bits: bindings::_VAPictureParameterBufferH264__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VAPictureParameterBufferH264__bindgen_ty_1 { + &self.0 + } +} + +/// Wrapper over the `pic_fields` bindgen field in `VAPictureParameterBufferH264`. +pub struct H264PicFields(bindings::_VAPictureParameterBufferH264__bindgen_ty_2); + +impl H264PicFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + entropy_coding_mode_flag: u32, + weighted_pred_flag: u32, + weighted_bipred_idc: u32, + transform_8x8_mode_flag: u32, + field_pic_flag: u32, + constrained_intra_pred_flag: u32, + pic_order_present_flag: u32, + deblocking_filter_control_present_flag: u32, + redundant_pic_cnt_present_flag: u32, + reference_pic_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAPictureParameterBufferH264__bindgen_ty_2__bindgen_ty_1::new_bitfield_1( + entropy_coding_mode_flag, + weighted_pred_flag, + weighted_bipred_idc, + transform_8x8_mode_flag, + field_pic_flag, + constrained_intra_pred_flag, + pic_order_present_flag, + deblocking_filter_control_present_flag, + redundant_pic_cnt_present_flag, + reference_pic_flag, + ); + + Self(bindings::_VAPictureParameterBufferH264__bindgen_ty_2 { + bits: bindings::_VAPictureParameterBufferH264__bindgen_ty_2__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VAPictureParameterBufferH264__bindgen_ty_2 { + &self.0 + } +} + +/// A wrapper over `VAPictureParameterBufferH264` FFI type +pub struct PictureParameterBufferH264(Box); + +impl PictureParameterBufferH264 { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + curr_pic: PictureH264, + reference_frames: [PictureH264; 16], + picture_width_in_mbs_minus1: u16, + picture_height_in_mbs_minus1: u16, + bit_depth_luma_minus8: u8, + bit_depth_chroma_minus8: u8, + num_ref_frames: u8, + seq_fields: &H264SeqFields, + num_slice_groups_minus1: u8, + slice_group_map_type: u8, + slice_group_change_rate_minus1: u16, + pic_init_qp_minus26: i8, + pic_init_qs_minus26: i8, + chroma_qp_index_offset: i8, + second_chroma_qp_index_offset: i8, + pic_fields: &H264PicFields, + frame_num: u16, + ) -> Self { + let reference_frames = (0..16usize) + .map(|i| reference_frames[i].0) + .collect::>() + .try_into() + // try_into is guaranteed to work because the iterator and target array have the same + // size. + .unwrap(); + + let seq_fields = seq_fields.0; + let pic_fields = pic_fields.0; + + Self(Box::new(bindings::VAPictureParameterBufferH264 { + CurrPic: curr_pic.0, + ReferenceFrames: reference_frames, + picture_width_in_mbs_minus1, + picture_height_in_mbs_minus1, + bit_depth_luma_minus8, + bit_depth_chroma_minus8, + num_ref_frames, + seq_fields, + num_slice_groups_minus1, + slice_group_map_type, + slice_group_change_rate_minus1, + pic_init_qp_minus26, + pic_init_qs_minus26, + chroma_qp_index_offset, + second_chroma_qp_index_offset, + pic_fields, + frame_num, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAPictureParameterBufferH264 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAPictureParameterBufferH264 { + self.0.as_ref() + } +} + +/// Wrapper over the `VASliceParameterBufferH264` FFI type. +pub struct SliceParameterBufferH264(Vec); + +impl SliceParameterBufferH264 { + pub fn new_array() -> Self { + Self(Vec::new()) + } + + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + slice_data_size: u32, + slice_data_offset: u32, + slice_data_flag: u32, + slice_data_bit_offset: u16, + first_mb_in_slice: u16, + slice_type: u8, + direct_spatial_mv_pred_flag: u8, + num_ref_idx_l0_active_minus1: u8, + num_ref_idx_l1_active_minus1: u8, + cabac_init_idc: u8, + slice_qp_delta: i8, + disable_deblocking_filter_idc: u8, + slice_alpha_c0_offset_div2: i8, + slice_beta_offset_div2: i8, + ref_pic_list_0: [PictureH264; 32usize], + ref_pic_list_1: [PictureH264; 32usize], + luma_log2_weight_denom: u8, + chroma_log2_weight_denom: u8, + luma_weight_l0_flag: u8, + luma_weight_l0: [i16; 32usize], + luma_offset_l0: [i16; 32usize], + chroma_weight_l0_flag: u8, + chroma_weight_l0: [[i16; 2usize]; 32usize], + chroma_offset_l0: [[i16; 2usize]; 32usize], + luma_weight_l1_flag: u8, + luma_weight_l1: [i16; 32usize], + luma_offset_l1: [i16; 32usize], + chroma_weight_l1_flag: u8, + chroma_weight_l1: [[i16; 2usize]; 32usize], + chroma_offset_l1: [[i16; 2usize]; 32usize], + ) -> Self { + let mut array = Self::new_array(); + + array.add_slice_parameter( + slice_data_size, + slice_data_offset, + slice_data_flag, + slice_data_bit_offset, + first_mb_in_slice, + slice_type, + direct_spatial_mv_pred_flag, + num_ref_idx_l0_active_minus1, + num_ref_idx_l1_active_minus1, + cabac_init_idc, + slice_qp_delta, + disable_deblocking_filter_idc, + slice_alpha_c0_offset_div2, + slice_beta_offset_div2, + ref_pic_list_0, + ref_pic_list_1, + luma_log2_weight_denom, + chroma_log2_weight_denom, + luma_weight_l0_flag, + luma_weight_l0, + luma_offset_l0, + chroma_weight_l0_flag, + chroma_weight_l0, + chroma_offset_l0, + luma_weight_l1_flag, + luma_weight_l1, + luma_offset_l1, + chroma_weight_l1_flag, + chroma_weight_l1, + chroma_offset_l1, + ); + + array + } + + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn add_slice_parameter( + &mut self, + slice_data_size: u32, + slice_data_offset: u32, + slice_data_flag: u32, + slice_data_bit_offset: u16, + first_mb_in_slice: u16, + slice_type: u8, + direct_spatial_mv_pred_flag: u8, + num_ref_idx_l0_active_minus1: u8, + num_ref_idx_l1_active_minus1: u8, + cabac_init_idc: u8, + slice_qp_delta: i8, + disable_deblocking_filter_idc: u8, + slice_alpha_c0_offset_div2: i8, + slice_beta_offset_div2: i8, + ref_pic_list_0: [PictureH264; 32usize], + ref_pic_list_1: [PictureH264; 32usize], + luma_log2_weight_denom: u8, + chroma_log2_weight_denom: u8, + luma_weight_l0_flag: u8, + luma_weight_l0: [i16; 32usize], + luma_offset_l0: [i16; 32usize], + chroma_weight_l0_flag: u8, + chroma_weight_l0: [[i16; 2usize]; 32usize], + chroma_offset_l0: [[i16; 2usize]; 32usize], + luma_weight_l1_flag: u8, + luma_weight_l1: [i16; 32usize], + luma_offset_l1: [i16; 32usize], + chroma_weight_l1_flag: u8, + chroma_weight_l1: [[i16; 2usize]; 32usize], + chroma_offset_l1: [[i16; 2usize]; 32usize], + ) { + let ref_pic_list_0 = ref_pic_list_0.map(|pic| pic.0); + let ref_pic_list_1 = ref_pic_list_1.map(|pic| pic.0); + + let buf = bindings::VASliceParameterBufferH264 { + slice_data_size, + slice_data_offset, + slice_data_flag, + slice_data_bit_offset, + first_mb_in_slice, + slice_type, + direct_spatial_mv_pred_flag, + num_ref_idx_l0_active_minus1, + num_ref_idx_l1_active_minus1, + cabac_init_idc, + slice_qp_delta, + disable_deblocking_filter_idc, + slice_alpha_c0_offset_div2, + slice_beta_offset_div2, + RefPicList0: ref_pic_list_0, + RefPicList1: ref_pic_list_1, + luma_log2_weight_denom, + chroma_log2_weight_denom, + luma_weight_l0_flag, + luma_weight_l0, + luma_offset_l0, + chroma_weight_l0_flag, + chroma_weight_l0, + chroma_offset_l0, + luma_weight_l1_flag, + luma_weight_l1, + luma_offset_l1, + chroma_weight_l1_flag, + chroma_weight_l1, + chroma_offset_l1, + va_reserved: Default::default(), + }; + + self.0.push(buf); + } + + pub(crate) fn inner_mut(&mut self) -> &mut Vec { + &mut self.0 + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &Vec { + &self.0 + } +} + +/// Wrapper over the `VAIQMatrixBufferH264` FFI type +pub struct IQMatrixBufferH264(Box); + +impl IQMatrixBufferH264 { + /// Creates the wrapper. + pub fn new( + scaling_list4x4: [[u8; 16usize]; 6usize], + scaling_list8x8: [[u8; 64usize]; 2usize], + ) -> Self { + Self(Box::new(bindings::VAIQMatrixBufferH264 { + ScalingList4x4: scaling_list4x4, + ScalingList8x8: scaling_list8x8, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAIQMatrixBufferH264 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAIQMatrixBufferH264 { + self.0.as_ref() + } +} + +/// Wrapper over the `seq_fields` bindgen field in `VAEncSequenceParameterBufferH264` +pub struct H264EncSeqFields(bindings::_VAEncSequenceParameterBufferH264__bindgen_ty_1); + +impl H264EncSeqFields { + #[allow(clippy::too_many_arguments)] + pub fn new( + chroma_format_idc: u32, + frame_mbs_only_flag: u32, + mb_adaptive_frame_field_flag: u32, + seq_scaling_matrix_present_flag: u32, + direct_8x8_inference_flag: u32, + log2_max_frame_num_minus4: u32, + pic_order_cnt_type: u32, + log2_max_pic_order_cnt_lsb_minus4: u32, + delta_pic_order_always_zero_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncSequenceParameterBufferH264__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + chroma_format_idc, + frame_mbs_only_flag, + mb_adaptive_frame_field_flag, + seq_scaling_matrix_present_flag, + direct_8x8_inference_flag, + log2_max_frame_num_minus4, + pic_order_cnt_type, + log2_max_pic_order_cnt_lsb_minus4, + delta_pic_order_always_zero_flag, + ); + + Self(bindings::_VAEncSequenceParameterBufferH264__bindgen_ty_1 { + bits: bindings::_VAEncSequenceParameterBufferH264__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + }, + }) + } + + pub fn inner(&self) -> &bindings::_VAEncSequenceParameterBufferH264__bindgen_ty_1 { + &self.0 + } +} + +#[derive(Default)] +pub struct H264VuiFields(bindings::_VAEncSequenceParameterBufferH264__bindgen_ty_2); + +impl H264VuiFields { + #[allow(clippy::too_many_arguments)] + pub fn new( + aspect_ratio_info_present_flag: u32, + timing_info_present_flag: u32, + bitstream_restriction_flag: u32, + log2_max_mv_length_horizontal: u32, + log2_max_mv_length_vertical: u32, + fixed_frame_rate_flag: u32, + low_delay_hrd_flag: u32, + motion_vectors_over_pic_boundaries_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncSequenceParameterBufferH264__bindgen_ty_2__bindgen_ty_1::new_bitfield_1( + aspect_ratio_info_present_flag, + timing_info_present_flag, + bitstream_restriction_flag, + log2_max_mv_length_horizontal, + log2_max_mv_length_vertical, + fixed_frame_rate_flag, + low_delay_hrd_flag, + motion_vectors_over_pic_boundaries_flag, + Default::default(), + ); + + Self(bindings::_VAEncSequenceParameterBufferH264__bindgen_ty_2 { + bits: bindings::_VAEncSequenceParameterBufferH264__bindgen_ty_2__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct H264EncFrameCropOffsets { + pub left: u32, + pub right: u32, + pub top: u32, + pub bottom: u32, +} + +impl H264EncFrameCropOffsets { + pub fn new( + frame_crop_left_offset: u32, + frame_crop_right_offset: u32, + frame_crop_top_offset: u32, + frame_crop_bottom_offset: u32, + ) -> Self { + Self { + left: frame_crop_left_offset, + right: frame_crop_right_offset, + top: frame_crop_top_offset, + bottom: frame_crop_bottom_offset, + } + } +} + +pub struct EncSequenceParameterBufferH264(Box); + +impl EncSequenceParameterBufferH264 { + #[allow(clippy::too_many_arguments)] + pub fn new( + seq_parameter_set_id: u8, + level_idc: u8, + intra_period: u32, + intra_idr_period: u32, + ip_period: u32, + bits_per_second: u32, + max_num_ref_frames: u32, + picture_width_in_mbs: u16, + picture_height_in_mbs: u16, + seq_fields: &H264EncSeqFields, + bit_depth_luma_minus8: u8, + bit_depth_chroma_minus8: u8, + num_ref_frames_in_pic_order_cnt_cycle: u8, + offset_for_non_ref_pic: i32, + offset_for_top_to_bottom_field: i32, + offset_for_ref_frame: [i32; 256usize], + frame_crop: Option, + vui_fields: Option, + aspect_ratio_idc: u8, + sar_width: u32, + sar_height: u32, + num_units_in_tick: u32, + time_scale: u32, + ) -> Self { + let seq_fields = seq_fields.0; + + let frame_cropping_flag = if frame_crop.is_some() { 1 } else { 0 }; + let frame_crop = frame_crop.unwrap_or_default(); + + let frame_crop_left_offset = frame_crop.left; + let frame_crop_right_offset = frame_crop.right; + let frame_crop_top_offset = frame_crop.top; + let frame_crop_bottom_offset = frame_crop.bottom; + + let vui_parameters_present_flag = if vui_fields.is_some() { 1 } else { 0 }; + let vui_fields = vui_fields.unwrap_or_default().0; + + Self(Box::new(bindings::VAEncSequenceParameterBufferH264 { + seq_parameter_set_id, + level_idc, + intra_period, + intra_idr_period, + ip_period, + bits_per_second, + max_num_ref_frames, + picture_width_in_mbs, + picture_height_in_mbs, + seq_fields, + bit_depth_luma_minus8, + bit_depth_chroma_minus8, + num_ref_frames_in_pic_order_cnt_cycle, + offset_for_non_ref_pic, + offset_for_top_to_bottom_field, + offset_for_ref_frame, + frame_cropping_flag, + frame_crop_left_offset, + frame_crop_right_offset, + frame_crop_top_offset, + frame_crop_bottom_offset, + vui_parameters_present_flag, + vui_fields, + aspect_ratio_idc, + sar_width, + sar_height, + num_units_in_tick, + time_scale, + ..Default::default() + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncSequenceParameterBufferH264 { + self.0.as_mut() + } +} + +pub struct H264EncPicFields(bindings::_VAEncPictureParameterBufferH264__bindgen_ty_1); + +impl H264EncPicFields { + #[allow(clippy::too_many_arguments)] + pub fn new( + idr_pic_flag: u32, + reference_pic_flag: u32, + entropy_coding_mode_flag: u32, + weighted_pred_flag: u32, + weighted_bipred_idc: u32, + constrained_intra_pred_flag: u32, + transform_8x8_mode_flag: u32, + deblocking_filter_control_present_flag: u32, + redundant_pic_cnt_present_flag: u32, + pic_order_present_flag: u32, + pic_scaling_matrix_present_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferH264__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + idr_pic_flag, + reference_pic_flag, + entropy_coding_mode_flag, + weighted_pred_flag, + weighted_bipred_idc, + constrained_intra_pred_flag, + transform_8x8_mode_flag, + deblocking_filter_control_present_flag, + redundant_pic_cnt_present_flag, + pic_order_present_flag, + pic_scaling_matrix_present_flag, + ); + + Self(bindings::_VAEncPictureParameterBufferH264__bindgen_ty_1 { + bits: bindings::_VAEncPictureParameterBufferH264__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + }, + }) + } +} + +pub struct EncPictureParameterBufferH264(Box); + +impl EncPictureParameterBufferH264 { + #[allow(clippy::too_many_arguments)] + pub fn new( + curr_pic: PictureH264, + reference_frames: [PictureH264; 16usize], + coded_buf: bindings::VABufferID, + pic_parameter_set_id: u8, + seq_parameter_set_id: u8, + last_picture: u8, + frame_num: u16, + pic_init_qp: u8, + num_ref_idx_l0_active_minus1: u8, + num_ref_idx_l1_active_minus1: u8, + chroma_qp_index_offset: i8, + second_chroma_qp_index_offset: i8, + pic_fields: &H264EncPicFields, + ) -> Self { + let reference_frames = (0..16usize) + .map(|i| reference_frames[i].0) + .collect::>() + .try_into() + // try_into is guaranteed to work because the iterator and target array have the same + // size. + .unwrap(); + + let pic_fields = pic_fields.0; + + Self(Box::new(bindings::_VAEncPictureParameterBufferH264 { + CurrPic: curr_pic.0, + ReferenceFrames: reference_frames, + coded_buf, + pic_parameter_set_id, + seq_parameter_set_id, + last_picture, + frame_num, + pic_init_qp, + num_ref_idx_l0_active_minus1, + num_ref_idx_l1_active_minus1, + chroma_qp_index_offset, + second_chroma_qp_index_offset, + pic_fields, + ..Default::default() + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncPictureParameterBufferH264 { + self.0.as_mut() + } +} + +pub struct EncSliceParameterBufferH264(Box); + +impl EncSliceParameterBufferH264 { + #[allow(clippy::too_many_arguments)] + pub fn new( + macroblock_address: u32, + num_macroblocks: u32, + macroblock_info: bindings::VABufferID, + slice_type: u8, + pic_parameter_set_id: u8, + idr_pic_id: u16, + pic_order_cnt_lsb: u16, + delta_pic_order_cnt_bottom: i32, + delta_pic_order_cnt: [i32; 2usize], + direct_spatial_mv_pred_flag: u8, + num_ref_idx_active_override_flag: u8, + num_ref_idx_l0_active_minus1: u8, + num_ref_idx_l1_active_minus1: u8, + ref_pic_list_0: [PictureH264; 32usize], + ref_pic_list_1: [PictureH264; 32usize], + luma_log2_weight_denom: u8, + chroma_log2_weight_denom: u8, + luma_weight_l0_flag: u8, + luma_weight_l0: [i16; 32usize], + luma_offset_l0: [i16; 32usize], + chroma_weight_l0_flag: u8, + chroma_weight_l0: [[i16; 2usize]; 32usize], + chroma_offset_l0: [[i16; 2usize]; 32usize], + luma_weight_l1_flag: u8, + luma_weight_l1: [i16; 32usize], + luma_offset_l1: [i16; 32usize], + chroma_weight_l1_flag: u8, + chroma_weight_l1: [[i16; 2usize]; 32usize], + chroma_offset_l1: [[i16; 2usize]; 32usize], + cabac_init_idc: u8, + slice_qp_delta: i8, + disable_deblocking_filter_idc: u8, + slice_alpha_c0_offset_div2: i8, + slice_beta_offset_div2: i8, + ) -> Self { + let ref_pic_list_0 = ref_pic_list_0.map(|pic| pic.0); + let ref_pic_list_1 = ref_pic_list_1.map(|pic| pic.0); + + Self(Box::new(bindings::VAEncSliceParameterBufferH264 { + macroblock_address, + num_macroblocks, + macroblock_info, + slice_type, + pic_parameter_set_id, + idr_pic_id, + pic_order_cnt_lsb, + delta_pic_order_cnt_bottom, + delta_pic_order_cnt, + direct_spatial_mv_pred_flag, + num_ref_idx_active_override_flag, + num_ref_idx_l0_active_minus1, + num_ref_idx_l1_active_minus1, + RefPicList0: ref_pic_list_0, + RefPicList1: ref_pic_list_1, + luma_log2_weight_denom, + chroma_log2_weight_denom, + luma_weight_l0_flag, + luma_weight_l0, + luma_offset_l0, + chroma_weight_l0_flag, + chroma_weight_l0, + chroma_offset_l0, + luma_weight_l1_flag, + luma_weight_l1, + luma_offset_l1, + chroma_weight_l1_flag, + chroma_weight_l1, + chroma_offset_l1, + cabac_init_idc, + slice_qp_delta, + disable_deblocking_filter_idc, + slice_alpha_c0_offset_div2, + slice_beta_offset_div2, + ..Default::default() + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncSliceParameterBufferH264 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAEncSliceParameterBufferH264 { + self.0.as_ref() + } +} + +pub struct H264EncMacroblockInfo(bindings::_VAEncMacroblockParameterBufferH264__bindgen_ty_1); + +impl H264EncMacroblockInfo { + pub fn new_intra(pred_avail_override_flag: u32, pred_avail_flags: u32) -> Self { + let _bitfield_1 = + bindings::_VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1::new_bitfield_1(pred_avail_override_flag, pred_avail_flags); + + Self(bindings::_VAEncMacroblockParameterBufferH264__bindgen_ty_1 { + intra_fields: bindings::_VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_1 { + bits: bindings::_VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + } + } + }) + } + + pub fn new_inter() -> Self { + Self(bindings::_VAEncMacroblockParameterBufferH264__bindgen_ty_1 { + inter_fields: bindings::_VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_2 { + bits: bindings::_VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_2__bindgen_ty_1 { + reserved: Default::default() + } + } + }) + } +} + +pub struct EncMacroblockParameterBufferH264(Box); + +impl EncMacroblockParameterBufferH264 { + pub fn new(qp: u8, info: &H264EncMacroblockInfo) -> Self { + let info = info.0; + + Self(Box::new(bindings::VAEncMacroblockParameterBufferH264 { + qp, + info, + ..Default::default() + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncMacroblockParameterBufferH264 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAEncMacroblockParameterBufferH264 { + self.0.as_ref() + } +} diff --git a/shims/cros-libva/src/buffer/hevc.rs b/shims/cros-libva/src/buffer/hevc.rs new file mode 100644 index 00000000..35a05b46 --- /dev/null +++ b/shims/cros-libva/src/buffer/hevc.rs @@ -0,0 +1,1154 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Wrappers around HEVC `VABuffer` types. + +use crate::bindings; + +/// Wrapper over the `VAPictureH264` FFI type. +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct PictureHEVC(bindings::VAPictureHEVC); + +impl PictureHEVC { + /// Creates the wrapper + pub fn new(picture_id: bindings::VASurfaceID, pic_order_cnt: i32, flags: u32) -> Self { + Self(bindings::VAPictureHEVC { + picture_id, + pic_order_cnt, + flags, + va_reserved: Default::default(), + }) + } + + /// Returns the `picture_id` field. + pub fn picture_id(&self) -> u32 { + self.0.picture_id + } + + /// Returns the `pic_order_cnt` field. + pub fn pic_order_cnt(&self) -> i32 { + self.0.pic_order_cnt + } + + /// Returns the `flags` field. + pub fn flags(&self) -> u32 { + self.0.flags + } +} + +/// Wrapper over the `pic_fields` bindgen field in `VAPictureParameterBufferHEVC`. +pub struct HevcPicFields(bindings::_VAPictureParameterBufferHEVC__bindgen_ty_1); + +impl HevcPicFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + chroma_format_idc: u32, + separate_colour_plane_flag: u32, + pcm_enabled_flag: u32, + scaling_list_enabled_flag: u32, + transform_skip_enabled_flag: u32, + amp_enabled_flag: u32, + strong_intra_smoothing_enabled_flag: u32, + sign_data_hiding_enabled_flag: u32, + constrained_intra_pred_flag: u32, + cu_qp_delta_enabled_flag: u32, + weighted_pred_flag: u32, + weighted_bipred_flag: u32, + transquant_bypass_enabled_flag: u32, + tiles_enabled_flag: u32, + entropy_coding_sync_enabled_flag: u32, + pps_loop_filter_across_slices_enabled_flag: u32, + loop_filter_across_tiles_enabled_flag: u32, + pcm_loop_filter_disabled_flag: u32, + no_pic_reordering_flag: u32, + no_bi_pred_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAPictureParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + chroma_format_idc, + separate_colour_plane_flag, + pcm_enabled_flag, + scaling_list_enabled_flag, + transform_skip_enabled_flag, + amp_enabled_flag, + strong_intra_smoothing_enabled_flag, + sign_data_hiding_enabled_flag, + constrained_intra_pred_flag, + cu_qp_delta_enabled_flag, + weighted_pred_flag, + weighted_bipred_flag, + transquant_bypass_enabled_flag, + tiles_enabled_flag, + entropy_coding_sync_enabled_flag, + pps_loop_filter_across_slices_enabled_flag, + loop_filter_across_tiles_enabled_flag, + pcm_loop_filter_disabled_flag, + no_pic_reordering_flag, + no_bi_pred_flag, + 0, + ); + + Self(bindings::_VAPictureParameterBufferHEVC__bindgen_ty_1 { + bits: bindings::_VAPictureParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VAPictureParameterBufferHEVC__bindgen_ty_1 { + &self.0 + } +} + +/// Wrapper over the `slice_parsing_fields` bindgen field in `VAPictureParameterBufferHEVC`. +pub struct HevcSliceParsingFields(bindings::_VAPictureParameterBufferHEVC__bindgen_ty_2); + +impl HevcSliceParsingFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + lists_modification_present_flag: u32, + long_term_ref_pics_present_flag: u32, + sps_temporal_mvp_enabled_flag: u32, + cabac_init_present_flag: u32, + output_flag_present_flag: u32, + dependent_slice_segments_enabled_flag: u32, + pps_slice_chroma_qp_offsets_present_flag: u32, + sample_adaptive_offset_enabled_flag: u32, + deblocking_filter_override_enabled_flag: u32, + pps_disable_deblocking_filter_flag: u32, + slice_segment_header_extension_present_flag: u32, + rap_pic_flag: u32, + idr_pic_flag: u32, + intra_pic_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAPictureParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1::new_bitfield_1( + lists_modification_present_flag, + long_term_ref_pics_present_flag, + sps_temporal_mvp_enabled_flag, + cabac_init_present_flag, + output_flag_present_flag, + dependent_slice_segments_enabled_flag, + pps_slice_chroma_qp_offsets_present_flag, + sample_adaptive_offset_enabled_flag, + deblocking_filter_override_enabled_flag, + pps_disable_deblocking_filter_flag, + slice_segment_header_extension_present_flag, + rap_pic_flag, + idr_pic_flag, + intra_pic_flag, + 0, + ); + + Self(bindings::_VAPictureParameterBufferHEVC__bindgen_ty_2 { + bits: bindings::_VAPictureParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VAPictureParameterBufferHEVC__bindgen_ty_2 { + &self.0 + } +} + +/// A wrapper over `VAPictureParameterBufferHEVC` FFI type +pub struct PictureParameterBufferHEVC(Box); + +impl PictureParameterBufferHEVC { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + curr_pic: PictureHEVC, + reference_frames: [PictureHEVC; 15], + pic_width_in_luma_samples: u16, + pic_height_in_luma_samples: u16, + pic_fields: &HevcPicFields, + sps_max_dec_pic_buffering_minus1: u8, + bit_depth_luma_minus8: u8, + bit_depth_chroma_minus8: u8, + pcm_sample_bit_depth_luma_minus1: u8, + pcm_sample_bit_depth_chroma_minus1: u8, + log2_min_luma_coding_block_size_minus3: u8, + log2_diff_max_min_luma_coding_block_size: u8, + log2_min_transform_block_size_minus2: u8, + log2_diff_max_min_transform_block_size: u8, + log2_min_pcm_luma_coding_block_size_minus3: u8, + log2_diff_max_min_pcm_luma_coding_block_size: u8, + max_transform_hierarchy_depth_intra: u8, + max_transform_hierarchy_depth_inter: u8, + init_qp_minus26: i8, + diff_cu_qp_delta_depth: u8, + pps_cb_qp_offset: i8, + pps_cr_qp_offset: i8, + log2_parallel_merge_level_minus2: u8, + num_tile_columns_minus1: u8, + num_tile_rows_minus1: u8, + column_width_minus1: [u16; 19], + row_height_minus1: [u16; 21], + slice_parsing_fields: &HevcSliceParsingFields, + log2_max_pic_order_cnt_lsb_minus4: u8, + num_short_term_ref_pic_sets: u8, + num_long_term_ref_pic_sps: u8, + num_ref_idx_l0_default_active_minus1: u8, + num_ref_idx_l1_default_active_minus1: u8, + pps_beta_offset_div2: i8, + pps_tc_offset_div2: i8, + num_extra_slice_header_bits: u8, + st_rps_bits: u32, + ) -> Self { + let reference_frames = (0..15usize) + .map(|i| reference_frames[i].0) + .collect::>() + .try_into() + // try_into is guaranteed to work because the iterator and target array have the same + // size. + .unwrap(); + + let pic_fields = pic_fields.0; + let slice_parsing_fields = slice_parsing_fields.0; + + Self(Box::new(bindings::VAPictureParameterBufferHEVC { + CurrPic: curr_pic.0, + ReferenceFrames: reference_frames, + pic_width_in_luma_samples, + pic_height_in_luma_samples, + pic_fields, + sps_max_dec_pic_buffering_minus1, + bit_depth_luma_minus8, + bit_depth_chroma_minus8, + pcm_sample_bit_depth_luma_minus1, + pcm_sample_bit_depth_chroma_minus1, + log2_min_luma_coding_block_size_minus3, + log2_diff_max_min_luma_coding_block_size, + log2_min_transform_block_size_minus2, + log2_diff_max_min_transform_block_size, + log2_min_pcm_luma_coding_block_size_minus3, + log2_diff_max_min_pcm_luma_coding_block_size, + max_transform_hierarchy_depth_intra, + max_transform_hierarchy_depth_inter, + init_qp_minus26, + diff_cu_qp_delta_depth, + pps_cb_qp_offset, + pps_cr_qp_offset, + log2_parallel_merge_level_minus2, + num_tile_columns_minus1, + num_tile_rows_minus1, + column_width_minus1, + row_height_minus1, + slice_parsing_fields, + log2_max_pic_order_cnt_lsb_minus4, + num_short_term_ref_pic_sets, + num_long_term_ref_pic_sps, + num_ref_idx_l0_default_active_minus1, + num_ref_idx_l1_default_active_minus1, + pps_beta_offset_div2, + pps_tc_offset_div2, + num_extra_slice_header_bits, + st_rps_bits, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAPictureParameterBufferHEVC { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAPictureParameterBufferHEVC { + self.0.as_ref() + } +} + +/// Wrapper over the `range_extension_pic_fields` bindgen field in `VAPictureParameterBufferHEVCRext`. +pub struct HevcRangeExtensionPicFields(bindings::_VAPictureParameterBufferHEVCRext__bindgen_ty_1); + +impl HevcRangeExtensionPicFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + transform_skip_rotation_enabled_flag: u32, + transform_skip_context_enabled_flag: u32, + implicit_rdpcm_enabled_flag: u32, + explicit_rdpcm_enabled_flag: u32, + extended_precision_processing_flag: u32, + intra_smoothing_disabled_flag: u32, + high_precision_offsets_enabled_flag: u32, + persistent_rice_adaptation_enabled_flag: u32, + cabac_bypass_alignment_enabled_flag: u32, + cross_component_prediction_enabled_flag: u32, + chroma_qp_offset_list_enabled_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAPictureParameterBufferHEVCRext__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + transform_skip_rotation_enabled_flag, + transform_skip_context_enabled_flag, + implicit_rdpcm_enabled_flag, + explicit_rdpcm_enabled_flag, + extended_precision_processing_flag, + intra_smoothing_disabled_flag, + high_precision_offsets_enabled_flag, + persistent_rice_adaptation_enabled_flag, + cabac_bypass_alignment_enabled_flag, + cross_component_prediction_enabled_flag, + chroma_qp_offset_list_enabled_flag, + 0, + ); + + Self(bindings::_VAPictureParameterBufferHEVCRext__bindgen_ty_1 { + bits: bindings::_VAPictureParameterBufferHEVCRext__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VAPictureParameterBufferHEVCRext__bindgen_ty_1 { + &self.0 + } +} + +/// A wrapper over `VAPictureParameterBufferHEVCRext` FFI type +pub struct PictureParameterBufferHEVCRext(Box); + +impl PictureParameterBufferHEVCRext { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + range_extension_pic_fields: &HevcRangeExtensionPicFields, + diff_cu_chroma_qp_offset_depth: u8, + chroma_qp_offset_list_len_minus1: u8, + log2_sao_offset_scale_luma: u8, + log2_sao_offset_scale_chroma: u8, + log2_max_transform_skip_block_size_minus2: u8, + cb_qp_offset_list: [i8; 6usize], + cr_qp_offset_list: [i8; 6usize], + ) -> Self { + let range_extension_pic_fields = range_extension_pic_fields.0; + + Self(Box::new(bindings::VAPictureParameterBufferHEVCRext { + range_extension_pic_fields, + diff_cu_chroma_qp_offset_depth, + chroma_qp_offset_list_len_minus1, + log2_sao_offset_scale_luma, + log2_sao_offset_scale_chroma, + log2_max_transform_skip_block_size_minus2, + cb_qp_offset_list, + cr_qp_offset_list, + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAPictureParameterBufferHEVCRext { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAPictureParameterBufferHEVCRext { + self.0.as_ref() + } +} + +/// Wrapper over the `screen_content_pic_fields` bindgen field in `VAPictureParameterBufferHEVCScc`. +pub struct HevcScreenContentPicFields(bindings::_VAPictureParameterBufferHEVCScc__bindgen_ty_1); + +impl HevcScreenContentPicFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + pps_curr_pic_ref_enabled_flag: u32, + palette_mode_enabled_flag: u32, + motion_vector_resolution_control_idc: u32, + intra_boundary_filtering_disabled_flag: u32, + residual_adaptive_colour_transform_enabled_flag: u32, + pps_slice_act_qp_offsets_present_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAPictureParameterBufferHEVCScc__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + pps_curr_pic_ref_enabled_flag, + palette_mode_enabled_flag, + motion_vector_resolution_control_idc, + intra_boundary_filtering_disabled_flag, + residual_adaptive_colour_transform_enabled_flag, + pps_slice_act_qp_offsets_present_flag, + 0, + ); + + Self(bindings::_VAPictureParameterBufferHEVCScc__bindgen_ty_1 { + bits: bindings::_VAPictureParameterBufferHEVCScc__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VAPictureParameterBufferHEVCScc__bindgen_ty_1 { + &self.0 + } +} + +/// A wrapper over `VAPictureParameterBufferScc` FFI type +pub struct PictureParameterBufferHEVCScc(Box); + +impl PictureParameterBufferHEVCScc { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + screen_content_pic_fields: &HevcScreenContentPicFields, + palette_max_size: u8, + delta_palette_max_predictor_size: u8, + predictor_palette_size: u8, + predictor_palette_entries: [[u16; 128usize]; 3usize], + pps_act_y_qp_offset_plus5: i8, + pps_act_cb_qp_offset_plus5: i8, + pps_act_cr_qp_offset_plus3: i8, + ) -> Self { + let screen_content_pic_fields = screen_content_pic_fields.0; + + Self(Box::new(bindings::VAPictureParameterBufferHEVCScc { + screen_content_pic_fields, + palette_max_size, + delta_palette_max_predictor_size, + predictor_palette_size, + predictor_palette_entries, + pps_act_y_qp_offset_plus5, + pps_act_cb_qp_offset_plus5, + pps_act_cr_qp_offset_plus3, + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAPictureParameterBufferHEVCScc { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAPictureParameterBufferHEVCScc { + self.0.as_ref() + } +} + +/// Wrapper over the `long_slice_flags` bindgen field in `VASliceParameterBufferHEVC`. +pub struct HevcLongSliceFlags(bindings::_VASliceParameterBufferHEVC__bindgen_ty_1); + +impl HevcLongSliceFlags { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + last_slice_of_pic: u32, + dependent_slice_segment_flag: u32, + slice_type: u32, + color_plane_id: u32, + slice_sao_luma_flag: u32, + slice_sao_chroma_flag: u32, + mvd_l1_zero_flag: u32, + cabac_init_flag: u32, + slice_temporal_mvp_enabled_flag: u32, + slice_deblocking_filter_disabled_flag: u32, + collocated_from_l0_flag: u32, + slice_loop_filter_across_slices_enabled_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VASliceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + last_slice_of_pic, + dependent_slice_segment_flag, + slice_type, + color_plane_id, + slice_sao_luma_flag, + slice_sao_chroma_flag, + mvd_l1_zero_flag, + cabac_init_flag, + slice_temporal_mvp_enabled_flag, + slice_deblocking_filter_disabled_flag, + collocated_from_l0_flag, + slice_loop_filter_across_slices_enabled_flag, + 0, + ); + + Self(bindings::_VASliceParameterBufferHEVC__bindgen_ty_1 { + fields: bindings::_VASliceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VASliceParameterBufferHEVC__bindgen_ty_1 { + &self.0 + } +} + +/// A wrapper over `VASliceParameterBufferHEVC` FFI type +pub struct SliceParameterBufferHEVC(Box); + +impl SliceParameterBufferHEVC { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + slice_data_size: u32, + slice_data_offset: u32, + slice_data_flag: u32, + slice_data_byte_offset: u32, + slice_segment_address: u32, + ref_pic_list: [[u8; 15usize]; 2usize], + long_slice_flags: &HevcLongSliceFlags, + collocated_ref_idx: u8, + num_ref_idx_l0_active_minus1: u8, + num_ref_idx_l1_active_minus1: u8, + slice_qp_delta: i8, + slice_cb_qp_offset: i8, + slice_cr_qp_offset: i8, + slice_beta_offset_div2: i8, + slice_tc_offset_div2: i8, + luma_log2_weight_denom: u8, + delta_chroma_log2_weight_denom: i8, + delta_luma_weight_l0: [i8; 15usize], + luma_offset_l0: [i8; 15usize], + delta_chroma_weight_l0: [[i8; 2usize]; 15usize], + chroma_offset_l0: [[i8; 2usize]; 15usize], + delta_luma_weight_l1: [i8; 15usize], + luma_offset_l1: [i8; 15usize], + delta_chroma_weight_l1: [[i8; 2usize]; 15usize], + chroma_offset_l1: [[i8; 2usize]; 15usize], + five_minus_max_num_merge_cand: u8, + num_entry_point_offsets: u16, + entry_offset_to_subset_array: u16, + slice_data_num_emu_prevn_bytes: u16, + ) -> Self { + let long_slice_flags = long_slice_flags.0; + + Self(Box::new(bindings::VASliceParameterBufferHEVC { + slice_data_size, + slice_data_offset, + slice_data_flag, + slice_data_byte_offset, + slice_segment_address, + RefPicList: ref_pic_list, + LongSliceFlags: long_slice_flags, + collocated_ref_idx, + num_ref_idx_l0_active_minus1, + num_ref_idx_l1_active_minus1, + slice_qp_delta, + slice_cb_qp_offset, + slice_cr_qp_offset, + slice_beta_offset_div2, + slice_tc_offset_div2, + luma_log2_weight_denom, + delta_chroma_log2_weight_denom, + delta_luma_weight_l0, + luma_offset_l0, + delta_chroma_weight_l0, + ChromaOffsetL0: chroma_offset_l0, + delta_luma_weight_l1, + luma_offset_l1, + delta_chroma_weight_l1, + ChromaOffsetL1: chroma_offset_l1, + five_minus_max_num_merge_cand, + num_entry_point_offsets, + entry_offset_to_subset_array, + slice_data_num_emu_prevn_bytes, + va_reserved: Default::default(), + })) + } + + /// Set this slice as the last one after creation. Implementations may only + /// be able to conveniently see if this is the last slice after it has been + /// created. + pub fn set_as_last(&mut self) { + // Safe because we know that both fields are valid at all times (just a + // different view on the data), and we are mutating through the bindgen + // function, respecting the padding in place. + unsafe { self.inner_mut().LongSliceFlags.fields.set_LastSliceOfPic(1) }; + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VASliceParameterBufferHEVC { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VASliceParameterBufferHEVC { + self.0.as_ref() + } +} + +/// Wrapper over the `slice_ext_flags` bindgen field in `VASliceParameterBufferHEVCRext`. +pub struct HevcSliceExtFlags(bindings::_VASliceParameterBufferHEVCRext__bindgen_ty_1); + +impl HevcSliceExtFlags { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new(cu_chroma_qp_offset_enabled_flag: u32, use_integer_mv_flag: u32) -> Self { + let _bitfield_1 = + bindings::_VASliceParameterBufferHEVCRext__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + cu_chroma_qp_offset_enabled_flag, + use_integer_mv_flag, + 0, + ); + + Self(bindings::_VASliceParameterBufferHEVCRext__bindgen_ty_1 { + bits: bindings::_VASliceParameterBufferHEVCRext__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VASliceParameterBufferHEVCRext__bindgen_ty_1 { + &self.0 + } +} + +/// A wrapper over `VASliceParameterBufferHEVCRext` FFI type +pub struct SliceParameterBufferHEVCRext(Box); + +impl SliceParameterBufferHEVCRext { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + luma_offset_l0: [i16; 15usize], + chroma_offset_l0: [[i16; 2usize]; 15usize], + luma_offset_l1: [i16; 15usize], + chroma_offset_l1: [[i16; 2usize]; 15usize], + slice_ext_flags: &HevcSliceExtFlags, + slice_act_y_qp_offset: i8, + slice_act_cb_qp_offset: i8, + slice_act_cr_qp_offset: i8, + ) -> Self { + let slice_ext_flags = slice_ext_flags.0; + + Self(Box::new(bindings::VASliceParameterBufferHEVCRext { + luma_offset_l0, + ChromaOffsetL0: chroma_offset_l0, + luma_offset_l1, + ChromaOffsetL1: chroma_offset_l1, + slice_ext_flags, + slice_act_y_qp_offset, + slice_act_cb_qp_offset, + slice_act_cr_qp_offset, + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VASliceParameterBufferHEVCRext { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VASliceParameterBufferHEVCRext { + self.0.as_ref() + } +} + +/// A wrapper over `VAIQMatrixBufferHEVC` FFI type +pub struct IQMatrixBufferHEVC(Box); + +impl IQMatrixBufferHEVC { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + scaling_list4x4: [[u8; 16usize]; 6usize], + scaling_list8x8: [[u8; 64usize]; 6usize], + scaling_list16x16: [[u8; 64usize]; 6usize], + scaling_list32x32: [[u8; 64usize]; 2usize], + scaling_list_dc16x16: [u8; 6usize], + scaling_list_dc32x32: [u8; 2usize], + ) -> Self { + Self(Box::new(bindings::VAIQMatrixBufferHEVC { + ScalingList4x4: scaling_list4x4, + ScalingList8x8: scaling_list8x8, + ScalingList16x16: scaling_list16x16, + ScalingList32x32: scaling_list32x32, + ScalingListDC16x16: scaling_list_dc16x16, + ScalingListDC32x32: scaling_list_dc32x32, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAIQMatrixBufferHEVC { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAIQMatrixBufferHEVC { + self.0.as_ref() + } +} + +pub struct HEVCEncSeqFields(bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_1); + +impl HEVCEncSeqFields { + #[allow(clippy::too_many_arguments)] + pub fn new( + chroma_format_idc: u32, + separate_colour_plane_flag: u32, + bit_depth_luma_minus8: u32, + bit_depth_chroma_minus8: u32, + scaling_list_enabled_flag: u32, + strong_intra_smoothing_enabled_flag: u32, + amp_enabled_flag: u32, + sample_adaptive_offset_enabled_flag: u32, + pcm_enabled_flag: u32, + pcm_loop_filter_disabled_flag: u32, + sps_temporal_mvp_enabled_flag: u32, + low_delay_seq: u32, + hierachical_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + chroma_format_idc, + separate_colour_plane_flag, + bit_depth_luma_minus8, + bit_depth_chroma_minus8, + scaling_list_enabled_flag, + strong_intra_smoothing_enabled_flag, + amp_enabled_flag, + sample_adaptive_offset_enabled_flag, + pcm_enabled_flag, + pcm_loop_filter_disabled_flag, + sps_temporal_mvp_enabled_flag, + low_delay_seq, + hierachical_flag, + Default::default(), + ); + + Self(bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_1 { + bits: bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct HevcEncVuiFields(bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_2); + +impl HevcEncVuiFields { + #[allow(clippy::too_many_arguments)] + pub fn new( + aspect_ratio_info_present_flag: u32, + neutral_chroma_indication_flag: u32, + field_seq_flag: u32, + vui_timing_info_present_flag: u32, + bitstream_restriction_flag: u32, + tiles_fixed_structure_flag: u32, + motion_vectors_over_pic_boundaries_flag: u32, + restricted_ref_pic_lists_flag: u32, + log2_max_mv_length_horizontal: u32, + log2_max_mv_length_vertical: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1::new_bitfield_1( + aspect_ratio_info_present_flag, + neutral_chroma_indication_flag, + field_seq_flag, + vui_timing_info_present_flag, + bitstream_restriction_flag, + tiles_fixed_structure_flag, + motion_vectors_over_pic_boundaries_flag, + restricted_ref_pic_lists_flag, + log2_max_mv_length_horizontal, + log2_max_mv_length_vertical, + ); + + Self(bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_2 { + bits: bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + }, + }) + } +} + +pub struct HevcEncSeqSccFields(bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_3); + +impl HevcEncSeqSccFields { + pub fn new(palette_mode_enabled_flag: u32) -> Self { + let _bitfield_1 = + bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_3__bindgen_ty_1::new_bitfield_1( + palette_mode_enabled_flag, + Default::default(), + ); + + Self(bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_3 { + bits: bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_3__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +pub struct EncSequenceParameterBufferHEVC(Box); + +impl EncSequenceParameterBufferHEVC { + #[allow(clippy::too_many_arguments)] + pub fn new( + general_profile_idc: u8, + general_level_idc: u8, + general_tier_flag: u8, + intra_period: u32, + intra_idr_period: u32, + ip_period: u32, + bits_per_second: u32, + pic_width_in_luma_samples: u16, + pic_height_in_luma_samples: u16, + seq_fields: &HEVCEncSeqFields, + log2_min_luma_coding_block_size_minus3: u8, + log2_diff_max_min_luma_coding_block_size: u8, + log2_min_transform_block_size_minus2: u8, + log2_diff_max_min_transform_block_size: u8, + max_transform_hierarchy_depth_inter: u8, + max_transform_hierarchy_depth_intra: u8, + pcm_sample_bit_depth_luma_minus1: u32, + pcm_sample_bit_depth_chroma_minus1: u32, + log2_min_pcm_luma_coding_block_size_minus3: u32, + log2_max_pcm_luma_coding_block_size_minus3: u32, + vui_fields: Option, + aspect_ratio_idc: u8, + sar_width: u32, + sar_height: u32, + vui_num_units_in_tick: u32, + vui_time_scale: u32, + min_spatial_segmentation_idc: u16, + max_bytes_per_pic_denom: u8, + max_bits_per_min_cu_denom: u8, + scc_fields: &HevcEncSeqSccFields, + ) -> Self { + let seq_fields = seq_fields.0; + let vui_parameters_present_flag = vui_fields.is_some() as u8; + let vui_fields = vui_fields.unwrap_or_default().0; + let scc_fields = scc_fields.0; + + Self(Box::new(bindings::VAEncSequenceParameterBufferHEVC { + general_profile_idc, + general_level_idc, + general_tier_flag, + intra_period, + intra_idr_period, + ip_period, + bits_per_second, + pic_width_in_luma_samples, + pic_height_in_luma_samples, + seq_fields, + log2_min_luma_coding_block_size_minus3, + log2_diff_max_min_luma_coding_block_size, + log2_min_transform_block_size_minus2, + log2_diff_max_min_transform_block_size, + max_transform_hierarchy_depth_inter, + max_transform_hierarchy_depth_intra, + pcm_sample_bit_depth_luma_minus1, + pcm_sample_bit_depth_chroma_minus1, + log2_min_pcm_luma_coding_block_size_minus3, + log2_max_pcm_luma_coding_block_size_minus3, + vui_parameters_present_flag, + vui_fields, + aspect_ratio_idc, + sar_width, + sar_height, + vui_num_units_in_tick, + vui_time_scale, + min_spatial_segmentation_idc, + max_bytes_per_pic_denom, + max_bits_per_min_cu_denom, + scc_fields, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncSequenceParameterBufferHEVC { + &mut self.0 + } +} + +pub struct HEVCEncPicFields(bindings::_VAEncPictureParameterBufferHEVC__bindgen_ty_1); + +impl HEVCEncPicFields { + #[allow(clippy::too_many_arguments)] + pub fn new( + idr_pic_flag: u32, + coding_type: u32, + reference_pic_flag: u32, + dependent_slice_segments_enabled_flag: u32, + sign_data_hiding_enabled_flag: u32, + constrained_intra_pred_flag: u32, + transform_skip_enabled_flag: u32, + cu_qp_delta_enabled_flag: u32, + weighted_pred_flag: u32, + weighted_bipred_flag: u32, + transquant_bypass_enabled_flag: u32, + tiles_enabled_flag: u32, + entropy_coding_sync_enabled_flag: u32, + loop_filter_across_tiles_enabled_flag: u32, + pps_loop_filter_across_slices_enabled_flag: u32, + scaling_list_data_present_flag: u32, + screen_content_flag: u32, + enable_gpu_weighted_prediction: u32, + no_output_of_prior_pics_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + idr_pic_flag, + coding_type, + reference_pic_flag, + dependent_slice_segments_enabled_flag, + sign_data_hiding_enabled_flag, + constrained_intra_pred_flag, + transform_skip_enabled_flag, + cu_qp_delta_enabled_flag, + weighted_pred_flag, + weighted_bipred_flag, + transquant_bypass_enabled_flag, + tiles_enabled_flag, + entropy_coding_sync_enabled_flag, + loop_filter_across_tiles_enabled_flag, + pps_loop_filter_across_slices_enabled_flag, + scaling_list_data_present_flag, + screen_content_flag, + enable_gpu_weighted_prediction, + no_output_of_prior_pics_flag, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferHEVC__bindgen_ty_1 { + bits: bindings::_VAEncPictureParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +pub struct HevcEncPicSccFields(bindings::_VAEncPictureParameterBufferHEVC__bindgen_ty_2); + +impl HevcEncPicSccFields { + pub fn new(pps_curr_pic_ref_enabled_flag: u16) -> Self { + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1::new_bitfield_1( + pps_curr_pic_ref_enabled_flag, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferHEVC__bindgen_ty_2 { + bits: bindings::_VAEncPictureParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +pub struct EncPictureParameterBufferHEVC(Box); + +impl EncPictureParameterBufferHEVC { + #[allow(clippy::too_many_arguments)] + pub fn new( + decoded_curr_pic: PictureHEVC, + reference_frames: [PictureHEVC; 15usize], + coded_buf: bindings::VABufferID, + collocated_ref_pic_index: u8, + last_picture: u8, + pic_init_qp: u8, + diff_cu_qp_delta_depth: u8, + pps_cb_qp_offset: i8, + pps_cr_qp_offset: i8, + num_tile_columns_minus1: u8, + num_tile_rows_minus1: u8, + column_width_minus1: [u8; 19usize], + row_height_minus1: [u8; 21usize], + log2_parallel_merge_level_minus2: u8, + ctu_max_bitsize_allowed: u8, + num_ref_idx_l0_default_active_minus1: u8, + num_ref_idx_l1_default_active_minus1: u8, + slice_pic_parameter_set_id: u8, + nal_unit_type: u8, + pic_fields: &HEVCEncPicFields, + hierarchical_level_plus1: u8, + va_byte_reserved: u8, + scc_fields: &HevcEncPicSccFields, + ) -> Self { + let decoded_curr_pic = decoded_curr_pic.0; + let reference_frames = (0..15usize) + .map(|i| reference_frames[i].0) + .collect::>() + .try_into() + // try_into is guaranteed to work because the iterator and target array have the same + // size. + .unwrap(); + + let pic_fields = pic_fields.0; + let scc_fields = scc_fields.0; + + Self(Box::new(bindings::VAEncPictureParameterBufferHEVC { + decoded_curr_pic, + reference_frames, + coded_buf, + collocated_ref_pic_index, + last_picture, + pic_init_qp, + diff_cu_qp_delta_depth, + pps_cb_qp_offset, + pps_cr_qp_offset, + num_tile_columns_minus1, + num_tile_rows_minus1, + column_width_minus1, + row_height_minus1, + log2_parallel_merge_level_minus2, + ctu_max_bitsize_allowed, + num_ref_idx_l0_default_active_minus1, + num_ref_idx_l1_default_active_minus1, + slice_pic_parameter_set_id, + nal_unit_type, + pic_fields, + hierarchical_level_plus1, + va_byte_reserved, + scc_fields, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncPictureParameterBufferHEVC { + &mut self.0 + } +} + +pub struct HevcEncSliceFields(bindings::_VAEncSliceParameterBufferHEVC__bindgen_ty_1); + +impl HevcEncSliceFields { + #[allow(clippy::too_many_arguments)] + pub fn new( + last_slice_of_pic_flag: u32, + dependent_slice_segment_flag: u32, + colour_plane_id: u32, + slice_temporal_mvp_enabled_flag: u32, + slice_sao_luma_flag: u32, + slice_sao_chroma_flag: u32, + num_ref_idx_active_override_flag: u32, + mvd_l1_zero_flag: u32, + cabac_init_flag: u32, + slice_deblocking_filter_disabled_flag: u32, + slice_loop_filter_across_slices_enabled_flag: u32, + collocated_from_l0_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncSliceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + last_slice_of_pic_flag, + dependent_slice_segment_flag, + colour_plane_id, + slice_temporal_mvp_enabled_flag, + slice_sao_luma_flag, + slice_sao_chroma_flag, + num_ref_idx_active_override_flag, + mvd_l1_zero_flag, + cabac_init_flag, + slice_deblocking_filter_disabled_flag, + slice_loop_filter_across_slices_enabled_flag, + collocated_from_l0_flag, + ); + + Self(bindings::_VAEncSliceParameterBufferHEVC__bindgen_ty_1 { + bits: bindings::_VAEncSliceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + }, + }) + } +} + +pub struct EncSliceParameterBufferHEVC(Box); + +impl EncSliceParameterBufferHEVC { + #[allow(clippy::too_many_arguments)] + pub fn new( + slice_segment_address: u32, + num_ctu_in_slice: u32, + slice_type: u8, + slice_pic_parameter_set_id: u8, + num_ref_idx_l0_active_minus1: u8, + num_ref_idx_l1_active_minus1: u8, + ref_pic_list0: [PictureHEVC; 15usize], + ref_pic_list1: [PictureHEVC; 15usize], + luma_log2_weight_denom: u8, + delta_chroma_log2_weight_denom: i8, + delta_luma_weight_l0: [i8; 15usize], + luma_offset_l0: [i8; 15usize], + delta_chroma_weight_l0: [[i8; 2usize]; 15usize], + chroma_offset_l0: [[i8; 2usize]; 15usize], + delta_luma_weight_l1: [i8; 15usize], + luma_offset_l1: [i8; 15usize], + delta_chroma_weight_l1: [[i8; 2usize]; 15usize], + chroma_offset_l1: [[i8; 2usize]; 15usize], + max_num_merge_cand: u8, + slice_qp_delta: i8, + slice_cb_qp_offset: i8, + slice_cr_qp_offset: i8, + slice_beta_offset_div2: i8, + slice_tc_offset_div2: i8, + slice_fields: &HevcEncSliceFields, + pred_weight_table_bit_offset: u32, + pred_weight_table_bit_length: u32, + ) -> Self { + let ref_pic_list0 = (0..15usize) + .map(|i| ref_pic_list0[i].0) + .collect::>() + .try_into() + // try_into is guaranteed to work because the iterator and target array have the same + // size. + .unwrap(); + + let ref_pic_list1 = (0..15usize) + .map(|i| ref_pic_list1[i].0) + .collect::>() + .try_into() + // try_into is guaranteed to work because the iterator and target array have the same + // size. + .unwrap(); + + let slice_fields = slice_fields.0; + + Self(Box::new(bindings::VAEncSliceParameterBufferHEVC { + slice_segment_address, + num_ctu_in_slice, + slice_type, + slice_pic_parameter_set_id, + num_ref_idx_l0_active_minus1, + num_ref_idx_l1_active_minus1, + ref_pic_list0, + ref_pic_list1, + luma_log2_weight_denom, + delta_chroma_log2_weight_denom, + delta_luma_weight_l0, + luma_offset_l0, + delta_chroma_weight_l0, + chroma_offset_l0, + delta_luma_weight_l1, + luma_offset_l1, + delta_chroma_weight_l1, + chroma_offset_l1, + max_num_merge_cand, + slice_qp_delta, + slice_cb_qp_offset, + slice_cr_qp_offset, + slice_beta_offset_div2, + slice_tc_offset_div2, + slice_fields, + pred_weight_table_bit_offset, + pred_weight_table_bit_length, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncSliceParameterBufferHEVC { + &mut self.0 + } +} diff --git a/shims/cros-libva/src/buffer/jpeg_baseline.rs b/shims/cros-libva/src/buffer/jpeg_baseline.rs new file mode 100644 index 00000000..92d962f4 --- /dev/null +++ b/shims/cros-libva/src/buffer/jpeg_baseline.rs @@ -0,0 +1,220 @@ +// Copyright 2025 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Wrappers around JPEGBaseline `VABuffer` types. + +use crate::bindings; + +/// Wrapper over the `components` bindgen field in `VAPictureParameterBufferJPEGBaseline`. +pub struct PictureParameterBufferJPEGBaselineComponent( + bindings::_VAPictureParameterBufferJPEGBaseline__bindgen_ty_1, +); + +impl PictureParameterBufferJPEGBaselineComponent { + /// Creates the bindgen field. + #[allow(clippy::too_many_arguments)] + pub fn new( + component_id: u8, + h_sampling_factor: u8, + v_sampling_factor: u8, + quantiser_table_selector: u8, + ) -> Self { + Self( + bindings::_VAPictureParameterBufferJPEGBaseline__bindgen_ty_1 { + component_id, + h_sampling_factor, + v_sampling_factor, + quantiser_table_selector, + }, + ) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VAPictureParameterBufferJPEGBaseline__bindgen_ty_1 { + &self.0 + } +} + +/// Wrapper over the `VAPictureParameterBufferJPEGBaseline` FFI type. +pub struct PictureParameterBufferJPEGBaseline(Box); + +impl PictureParameterBufferJPEGBaseline { + /// Creates the wrapper. + pub fn new( + picture_width: u16, + picture_height: u16, + components: [PictureParameterBufferJPEGBaselineComponent; 255usize], + num_components: u8, + color_space: u8, + rotation: u32, + crop_rectangle: bindings::VARectangle, + ) -> Self { + Self(Box::new(bindings::VAPictureParameterBufferJPEGBaseline { + picture_width, + picture_height, + components: components.map(|component| component.0), + num_components, + color_space, + rotation, + crop_rectangle, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAPictureParameterBufferJPEGBaseline { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::VAPictureParameterBufferJPEGBaseline { + self.0.as_ref() + } +} + +/// Wrapper over the `components` bindgen field in `VASliceParameterBufferJPEGBaseline`. +pub struct VASliceParameterBufferJPEGBaselineComponent( + bindings::_VASliceParameterBufferJPEGBaseline__bindgen_ty_1, +); + +impl VASliceParameterBufferJPEGBaselineComponent { + /// Creates the bindgen field. + #[allow(clippy::too_many_arguments)] + pub fn new(component_selector: u8, dc_table_selector: u8, ac_table_selector: u8) -> Self { + Self( + bindings::_VASliceParameterBufferJPEGBaseline__bindgen_ty_1 { + component_selector, + dc_table_selector, + ac_table_selector, + }, + ) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VASliceParameterBufferJPEGBaseline__bindgen_ty_1 { + &self.0 + } +} + +/// Wrapper over the `VASliceParameterBufferJPEGBaseline` FFI type. +pub struct SliceParameterBufferJPEGBaseline(Box); + +impl SliceParameterBufferJPEGBaseline { + /// Creates the wrapper. + pub fn new( + slice_data_size: u32, + slice_data_offset: u32, + slice_data_flag: u32, + slice_horizontal_position: u32, + slice_vertical_position: u32, + components: [VASliceParameterBufferJPEGBaselineComponent; 4usize], + num_components: u8, + restart_interval: u16, + num_mcus: u32, + ) -> Self { + Self(Box::new(bindings::VASliceParameterBufferJPEGBaseline { + slice_data_size, + slice_data_offset, + slice_data_flag, + slice_horizontal_position, + slice_vertical_position, + components: components.map(|component| component.0), + num_components, + restart_interval, + num_mcus, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VASliceParameterBufferJPEGBaseline { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::VASliceParameterBufferJPEGBaseline { + self.0.as_ref() + } +} + +/// Wrapper over the `VAIQMatrixBufferJPEGBaseline` FFI type. +pub struct IQMatrixBufferJPEGBaseline(Box); + +impl IQMatrixBufferJPEGBaseline { + /// Creates the wrapper. + #[allow(clippy::too_many_arguments)] + pub fn new( + load_quantiser_table: [u8; 4usize], + quantiser_table: [[u8; 64usize]; 4usize], + ) -> Self { + Self(Box::new(bindings::VAIQMatrixBufferJPEGBaseline { + load_quantiser_table, + quantiser_table, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAIQMatrixBufferJPEGBaseline { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAIQMatrixBufferJPEGBaseline { + self.0.as_ref() + } +} + +/// Wrapper over the `huffman_table` bindgen field in `VAHuffmanTableBufferJPEGBaseline`. +pub struct HuffmanTableBufferJPEGBaselineHuffmanTable( + bindings::_VAHuffmanTableBufferJPEGBaseline__bindgen_ty_1, +); + +impl HuffmanTableBufferJPEGBaselineHuffmanTable { + /// Creates the bindgen field. + #[allow(clippy::too_many_arguments)] + pub fn new( + num_dc_codes: [u8; 16usize], + dc_values: [u8; 12usize], + num_ac_codes: [u8; 16usize], + ac_values: [u8; 162usize], + pad: [u8; 2usize], + ) -> Self { + Self(bindings::_VAHuffmanTableBufferJPEGBaseline__bindgen_ty_1 { + num_dc_codes, + dc_values, + num_ac_codes, + ac_values, + pad, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VAHuffmanTableBufferJPEGBaseline__bindgen_ty_1 { + &self.0 + } +} + +/// Wrapper over the `VAHuffmanTableBufferJPEGBaseline` FFI type. +pub struct HuffmanTableBufferJPEGBaseline(Box); + +impl HuffmanTableBufferJPEGBaseline { + /// Creates the wrapper. + pub fn new( + load_huffman_table: [u8; 2usize], + huffman_table: [HuffmanTableBufferJPEGBaselineHuffmanTable; 2usize], + ) -> Self { + Self(Box::new(bindings::VAHuffmanTableBufferJPEGBaseline { + load_huffman_table, + huffman_table: huffman_table.map(|component| component.0), + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAHuffmanTableBufferJPEGBaseline { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::VAHuffmanTableBufferJPEGBaseline { + self.0.as_ref() + } +} diff --git a/shims/cros-libva/src/buffer/mpeg2.rs b/shims/cros-libva/src/buffer/mpeg2.rs new file mode 100644 index 00000000..22df3141 --- /dev/null +++ b/shims/cros-libva/src/buffer/mpeg2.rs @@ -0,0 +1,172 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Wrappers around MPEG2 `VABuffer` types. + +use crate::bindings; + +/// Wrapper over the `picture_coding_extension` bindgen field in `VAPictureParameterBufferMPEG2`. +pub struct MPEG2PictureCodingExtension(bindings::_VAPictureParameterBufferMPEG2__bindgen_ty_1); + +impl MPEG2PictureCodingExtension { + /// Creates the bindgen field. + #[allow(clippy::too_many_arguments)] + pub fn new( + intra_dc_precision: u32, + picture_structure: u32, + top_field_first: u32, + frame_pred_frame_dct: u32, + concealment_motion_vectors: u32, + q_scale_type: u32, + intra_vlc_format: u32, + alternate_scan: u32, + repeat_first_field: u32, + progressive_frame: u32, + is_first_field: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAPictureParameterBufferMPEG2__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + intra_dc_precision, + picture_structure, + top_field_first, + frame_pred_frame_dct, + concealment_motion_vectors, + q_scale_type, + intra_vlc_format, + alternate_scan, + repeat_first_field, + progressive_frame, + is_first_field, + ); + + Self(bindings::_VAPictureParameterBufferMPEG2__bindgen_ty_1 { + bits: bindings::_VAPictureParameterBufferMPEG2__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VAPictureParameterBufferMPEG2__bindgen_ty_1 { + &self.0 + } +} + +/// Wrapper over the `PictureParameterBufferMPEG2` FFI type. +pub struct PictureParameterBufferMPEG2(Box); + +impl PictureParameterBufferMPEG2 { + /// Creates the wrapper. + pub fn new( + horizontal_size: u16, + vertical_size: u16, + forward_reference_picture: bindings::VASurfaceID, + backward_reference_picture: bindings::VASurfaceID, + picture_coding_type: i32, + f_code: i32, + picture_coding_extension: &MPEG2PictureCodingExtension, + ) -> Self { + let picture_coding_extension = picture_coding_extension.0; + + Self(Box::new(bindings::VAPictureParameterBufferMPEG2 { + horizontal_size, + vertical_size, + forward_reference_picture, + backward_reference_picture, + picture_coding_type, + f_code, + picture_coding_extension, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAPictureParameterBufferMPEG2 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::VAPictureParameterBufferMPEG2 { + self.0.as_ref() + } +} + +/// Wrapper over the `VASliceParameterBufferMPEG2` FFI type. +pub struct SliceParameterBufferMPEG2(Box); + +impl SliceParameterBufferMPEG2 { + /// Creates the wrapper. + #[allow(clippy::too_many_arguments)] + pub fn new( + slice_data_size: u32, + slice_data_offset: u32, + slice_data_flag: u32, + macroblock_offset: u32, + slice_horizontal_position: u32, + slice_vertical_position: u32, + quantiser_scale_code: i32, + intra_slice_flag: i32, + ) -> Self { + Self(Box::new(bindings::VASliceParameterBufferMPEG2 { + slice_data_size, + slice_data_offset, + slice_data_flag, + macroblock_offset, + slice_horizontal_position, + slice_vertical_position, + quantiser_scale_code, + intra_slice_flag, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VASliceParameterBufferMPEG2 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VASliceParameterBufferMPEG2 { + self.0.as_ref() + } +} + +/// Wrapper over the `VAIQMatrixBufferMPEG2` FFI type. +pub struct IQMatrixBufferMPEG2(Box); + +impl IQMatrixBufferMPEG2 { + /// Creates the wrapper. + #[allow(clippy::too_many_arguments)] + pub fn new( + load_intra_quantiser_matrix: i32, + load_non_intra_quantiser_matrix: i32, + load_chroma_intra_quantiser_matrix: i32, + load_chroma_non_intra_quantiser_matrix: i32, + intra_quantiser_matrix: [u8; 64usize], + non_intra_quantiser_matrix: [u8; 64usize], + chroma_intra_quantiser_matrix: [u8; 64usize], + chroma_non_intra_quantiser_matrix: [u8; 64usize], + ) -> Self { + Self(Box::new(bindings::VAIQMatrixBufferMPEG2 { + load_intra_quantiser_matrix, + load_non_intra_quantiser_matrix, + load_chroma_intra_quantiser_matrix, + load_chroma_non_intra_quantiser_matrix, + intra_quantiser_matrix, + non_intra_quantiser_matrix, + chroma_intra_quantiser_matrix, + chroma_non_intra_quantiser_matrix, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAIQMatrixBufferMPEG2 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAIQMatrixBufferMPEG2 { + self.0.as_ref() + } +} diff --git a/shims/cros-libva/src/buffer/proc_pipeline.rs b/shims/cros-libva/src/buffer/proc_pipeline.rs new file mode 100644 index 00000000..2c2ea936 --- /dev/null +++ b/shims/cros-libva/src/buffer/proc_pipeline.rs @@ -0,0 +1,198 @@ +// Copyright 2025 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Wrappers around `VAProcPipeline` types. + +use crate::bindings; +use std::{marker::PhantomData, ptr}; + +/// Wrapper over the `VABlendState` ffi type. +pub struct BlendState(bindings::VABlendState); + +impl BlendState { + /// Creates the bindgen field + pub fn new(flags: u32, global_alpha: f32, min_luma: f32, max_luma: f32) -> Self { + Self(bindings::VABlendState { + flags, + global_alpha, + min_luma, + max_luma, + }) + } +} + +/// Wrapper over the `VAProcColorProperties` ffi type. +pub struct ProcColorProperties(bindings::VAProcColorProperties); + +impl ProcColorProperties { + /// Creates the bindgen field + pub fn new( + chroma_sample_location: u8, + color_range: u8, + colour_primaries: u8, + transfer_characteristics: u8, + matrix_coefficients: u8, + ) -> Self { + Self(bindings::VAProcColorProperties { + chroma_sample_location, + color_range, + colour_primaries, + transfer_characteristics, + matrix_coefficients, + reserved: Default::default(), + }) + } +} + +impl Default for ProcColorProperties { + fn default() -> Self { + Self::new(0, 0, 0, 0, 0) + } +} + +/// Wrapper over the `VAHdrMetaData` ffi type. +pub struct HdrMetaData(bindings::VAHdrMetaData); + +impl<'a> HdrMetaData { + /// Creates the bindgen field + pub fn new(metadata_type: u32, metadata: Option<&'a [u8]>, metadata_size: u32) -> Self { + Self(bindings::VAHdrMetaData { + metadata_type: metadata_type as _, + metadata: metadata.map_or(ptr::null_mut(), |f| f.as_ptr() as *mut _), + metadata_size, + reserved: Default::default(), + }) + } +} + +/// Wrapper over the `VAProcPipelineParameterBuffer` FFI type. +pub struct ProcPipelineParameterBuffer { + c_params: Box, + + // Fields that own the data for the pointers in `c_params`. + surface_region: Option>, + output_region: Option>, + filters: Option>, + forward_references: Option>, + backward_references: Option>, + blend_state: Option>, + additional_outputs: Option>, + output_hdr_metadata: Option>, +} + +impl ProcPipelineParameterBuffer { + /// Creates the wrapper. + #[allow(clippy::too_many_arguments)] + pub fn new( + surface: bindings::VASurfaceID, + surface_region: Option, + surface_color_standard: u8, + output_region: Option, + output_background_color: u32, + output_color_standard: u8, + pipeline_flags: u32, + filter_flags: u32, + filters: Option>, + forward_references: Option>, + backward_references: Option>, + rotation_state: u32, + blend_state: Option>, + mirror_state: u32, + additional_outputs: Option>, + input_surface_flag: u32, + output_surface_flag: u32, + input_color_properties: ProcColorProperties, + output_color_properties: ProcColorProperties, + processing_mode: u32, + output_hdr_metadata: Option>, + ) -> Self { + let mut slf = Self { + // SAFETY: The VA-API structures are C-compatible so zeroing is safe. + c_params: Box::new(unsafe { std::mem::zeroed() }), + surface_region: surface_region.map(Box::new), + output_region: output_region.map(Box::new), + filters, + forward_references, + backward_references, + blend_state, + additional_outputs, + output_hdr_metadata, + }; + + slf.c_params = Box::new(bindings::VAProcPipelineParameterBuffer { + surface, + surface_region: slf + .surface_region + .as_deref() + .map_or(ptr::null_mut(), |r| r as *const _ as *mut _), + surface_color_standard: surface_color_standard as _, + output_region: slf + .output_region + .as_deref() + .map_or(ptr::null_mut(), |r| r as *const _ as *mut _), + output_background_color, + output_color_standard: output_color_standard as _, + pipeline_flags, + filter_flags, + filters: slf + .filters + .as_deref() + .map_or(ptr::null_mut(), |f| f.as_ptr() as *mut _), + num_filters: slf.filters.as_ref().map_or(0, |f| f.len() as u32), + forward_references: slf + .forward_references + .as_deref() + .map_or(ptr::null_mut(), |r| r.as_ptr() as *mut _), + num_forward_references: slf + .forward_references + .as_ref() + .map_or(0, |f| f.len() as u32), + backward_references: slf + .backward_references + .as_deref() + .map_or(ptr::null_mut(), |r| r.as_ptr() as *mut _), + num_backward_references: slf + .backward_references + .as_ref() + .map_or(0, |b| b.len() as u32), + rotation_state, + blend_state: slf + .blend_state + .as_deref() + .map_or(ptr::null(), |b| b.as_ptr() as *const bindings::VABlendState), + mirror_state, + additional_outputs: slf + .additional_outputs + .as_deref() + .map_or(ptr::null_mut(), |a| a.as_ptr() as *mut _), + num_additional_outputs: slf + .additional_outputs + .as_ref() + .map_or(0, |a| a.len() as u32), + input_surface_flag, + output_surface_flag, + input_color_properties: input_color_properties.0, + output_color_properties: output_color_properties.0, + processing_mode, + output_hdr_metadata: slf + .output_hdr_metadata + .as_deref() + .map_or(ptr::null_mut(), |o| { + o.as_ptr() as *mut bindings::VAHdrMetaData + }), + va_reserved: Default::default(), + }); + + slf + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAProcPipelineParameterBuffer { + self.c_params.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAProcPipelineParameterBuffer { + self.c_params.as_ref() + } +} diff --git a/shims/cros-libva/src/buffer/vp8.rs b/shims/cros-libva/src/buffer/vp8.rs new file mode 100644 index 00000000..70989e1c --- /dev/null +++ b/shims/cros-libva/src/buffer/vp8.rs @@ -0,0 +1,397 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Wrappers around VP8 `VABuffer` types. + +use crate::bindings; + +/// Wrapper over the `pic_fields` bindgen field in `VAPictureParameterBufferVP8`. +pub struct VP8PicFields(bindings::_VAPictureParameterBufferVP8__bindgen_ty_1); + +impl VP8PicFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + key_frame: u32, + version: u32, + segmentation_enabled: u32, + update_mb_segmentation_map: u32, + update_segment_feature_data: u32, + filter_type: u32, + sharpness_level: u32, + loop_filter_adj_enable: u32, + mode_ref_lf_delta_update: u32, + sign_bias_golden: u32, + sign_bias_alternate: u32, + mb_no_coeff_skip: u32, + loop_filter_disable: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAPictureParameterBufferVP8__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + key_frame, + version, + segmentation_enabled, + update_mb_segmentation_map, + update_segment_feature_data, + filter_type, + sharpness_level, + loop_filter_adj_enable, + mode_ref_lf_delta_update, + sign_bias_golden, + sign_bias_alternate, + mb_no_coeff_skip, + loop_filter_disable, + ); + + Self(bindings::_VAPictureParameterBufferVP8__bindgen_ty_1 { + bits: bindings::_VAPictureParameterBufferVP8__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::_VAPictureParameterBufferVP8__bindgen_ty_1 { + &self.0 + } +} + +/// Wrapper over the `VABoolCoderContextVPX` FFI type. +pub struct BoolCoderContextVPX(bindings::VABoolCoderContextVPX); + +impl BoolCoderContextVPX { + /// Creates the wrapper + pub fn new(range: u8, value: u8, count: u8) -> Self { + Self(bindings::VABoolCoderContextVPX { + range, + value, + count, + }) + } +} + +/// Wrapper over the `PictureParameterBufferVP8` FFI type. +pub struct PictureParameterBufferVP8(Box); + +impl PictureParameterBufferVP8 { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + frame_width: u32, + frame_height: u32, + last_ref_frame: bindings::VASurfaceID, + golden_ref_frame: bindings::VASurfaceID, + alt_ref_frame: bindings::VASurfaceID, + pic_fields: &VP8PicFields, + mb_segment_tree_probs: [u8; 3usize], + loop_filter_level: [u8; 4usize], + loop_filter_deltas_ref_frame: [i8; 4usize], + loop_filter_deltas_mode: [i8; 4usize], + prob_skip_false: u8, + prob_intra: u8, + prob_last: u8, + prob_gf: u8, + y_mode_probs: [u8; 4usize], + uv_mode_probs: [u8; 3usize], + mv_probs: [[u8; 19usize]; 2usize], + bool_coder_ctx: &BoolCoderContextVPX, + ) -> Self { + let pic_fields = pic_fields.0; + let bool_coder_ctx = bool_coder_ctx.0; + + Self(Box::new(bindings::VAPictureParameterBufferVP8 { + frame_width, + frame_height, + last_ref_frame, + golden_ref_frame, + alt_ref_frame, + out_of_loop_frame: bindings::VA_INVALID_SURFACE, + pic_fields, + mb_segment_tree_probs, + loop_filter_level, + loop_filter_deltas_ref_frame, + loop_filter_deltas_mode, + prob_skip_false, + prob_intra, + prob_last, + prob_gf, + y_mode_probs, + uv_mode_probs, + mv_probs, + bool_coder_ctx, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAPictureParameterBufferVP8 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAPictureParameterBufferVP8 { + self.0.as_ref() + } +} + +/// Wrapper over the `VASliceParameterBufferVP8` FFI type. +pub struct SliceParameterBufferVP8(Box); + +impl SliceParameterBufferVP8 { + /// Creates the wrapper. + pub fn new( + slice_data_size: u32, + slice_data_offset: u32, + slice_data_flag: u32, + macroblock_offset: u32, + num_of_partitions: u8, + partition_size: [u32; 9usize], + ) -> Self { + Self(Box::new(bindings::VASliceParameterBufferVP8 { + slice_data_size, + slice_data_offset, + slice_data_flag, + macroblock_offset, + num_of_partitions, + partition_size, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VASliceParameterBufferVP8 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VASliceParameterBufferVP8 { + self.0.as_ref() + } +} + +/// Wrapper over the `VAIQMatrixBufferVP8` FFI type. +pub struct IQMatrixBufferVP8(Box); + +impl IQMatrixBufferVP8 { + /// Creates the wrapper. + pub fn new(quantization_index: [[u16; 6usize]; 4usize]) -> Self { + Self(Box::new(bindings::VAIQMatrixBufferVP8 { + quantization_index, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAIQMatrixBufferVP8 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAIQMatrixBufferVP8 { + self.0.as_ref() + } +} + +/// Wrapper over the VAProbabilityDataBufferVP8 FFI type. +pub struct ProbabilityDataBufferVP8(Box); + +impl ProbabilityDataBufferVP8 { + /// Creates the wrapper. + pub fn new(dct_coeff_probs: [[[[u8; 11usize]; 3usize]; 8usize]; 4usize]) -> Self { + Self(Box::new(bindings::VAProbabilityDataBufferVP8 { + dct_coeff_probs, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAProbabilityDataBufferVP8 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAProbabilityDataBufferVP8 { + self.0.as_ref() + } +} + +pub struct EncSequenceParameterBufferVP8(Box); + +impl EncSequenceParameterBufferVP8 { + #[allow(clippy::too_many_arguments)] + pub fn new( + frame_width: u32, + frame_height: u32, + frame_width_scale: u32, + frame_height_scale: u32, + error_resilient: u32, + kf_auto: u32, + kf_min_dist: u32, + kf_max_dist: u32, + bits_per_second: u32, + intra_period: u32, + reference_frames: [bindings::VASurfaceID; 4usize], + ) -> Self { + Self(Box::new(bindings::VAEncSequenceParameterBufferVP8 { + frame_width, + frame_height, + frame_width_scale, + frame_height_scale, + error_resilient, + kf_auto, + kf_min_dist, + kf_max_dist, + bits_per_second, + intra_period, + reference_frames, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncSequenceParameterBufferVP8 { + &mut self.0 + } +} + +pub struct VP8EncRefFlags(bindings::_VAEncPictureParameterBufferVP8__bindgen_ty_1); + +impl VP8EncRefFlags { + pub fn new( + force_kf: u32, + no_ref_last: u32, + no_ref_gf: u32, + no_ref_arf: u32, + temporal_id: u32, + first_ref: u32, + second_ref: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferVP8__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + force_kf, + no_ref_last, + no_ref_gf, + no_ref_arf, + temporal_id, + first_ref, + second_ref, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferVP8__bindgen_ty_1 { + bits: bindings::_VAEncPictureParameterBufferVP8__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +pub struct VP8EncPicFlags(bindings::_VAEncPictureParameterBufferVP8__bindgen_ty_2); + +impl VP8EncPicFlags { + #[allow(clippy::too_many_arguments)] + pub fn new( + frame_type: u32, + version: u32, + show_frame: u32, + color_space: u32, + recon_filter_type: u32, + loop_filter_type: u32, + auto_partitions: u32, + num_token_partitions: u32, + clamping_type: u32, + segmentation_enabled: u32, + update_mb_segmentation_map: u32, + update_segment_feature_data: u32, + loop_filter_adj_enable: u32, + refresh_entropy_probs: u32, + refresh_golden_frame: u32, + refresh_alternate_frame: u32, + refresh_last: u32, + copy_buffer_to_golden: u32, + copy_buffer_to_alternate: u32, + sign_bias_golden: u32, + sign_bias_alternate: u32, + mb_no_coeff_skip: u32, + forced_lf_adjustment: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferVP8__bindgen_ty_2__bindgen_ty_1::new_bitfield_1( + frame_type, + version, + show_frame, + color_space, + recon_filter_type, + loop_filter_type, + auto_partitions, + num_token_partitions, + clamping_type, + segmentation_enabled, + update_mb_segmentation_map, + update_segment_feature_data, + loop_filter_adj_enable, + refresh_entropy_probs, + refresh_golden_frame, + refresh_alternate_frame, + refresh_last, + copy_buffer_to_golden, + copy_buffer_to_alternate, + sign_bias_golden, + sign_bias_alternate, + mb_no_coeff_skip, + forced_lf_adjustment, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferVP8__bindgen_ty_2 { + bits: bindings::_VAEncPictureParameterBufferVP8__bindgen_ty_2__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +pub struct EncPictureParameterBufferVP8(Box); + +impl EncPictureParameterBufferVP8 { + #[allow(clippy::too_many_arguments)] + pub fn new( + reconstructed_frame: bindings::VASurfaceID, + ref_last_frame: bindings::VASurfaceID, + ref_gf_frame: bindings::VASurfaceID, + ref_arf_frame: bindings::VASurfaceID, + coded_buf: bindings::VABufferID, + ref_flags: &VP8EncRefFlags, + pic_flags: &VP8EncPicFlags, + loop_filter_level: [i8; 4usize], + ref_lf_delta: [i8; 4usize], + mode_lf_delta: [i8; 4usize], + sharpness_level: u8, + clamp_qindex_high: u8, + clamp_qindex_low: u8, + ) -> Self { + let ref_flags = ref_flags.0; + let pic_flags = pic_flags.0; + + Self(Box::new(bindings::VAEncPictureParameterBufferVP8 { + reconstructed_frame, + ref_last_frame, + ref_gf_frame, + ref_arf_frame, + coded_buf, + ref_flags, + pic_flags, + loop_filter_level, + ref_lf_delta, + mode_lf_delta, + sharpness_level, + clamp_qindex_high, + clamp_qindex_low, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncPictureParameterBufferVP8 { + &mut self.0 + } +} diff --git a/shims/cros-libva/src/buffer/vp9.rs b/shims/cros-libva/src/buffer/vp9.rs new file mode 100644 index 00000000..3117ec02 --- /dev/null +++ b/shims/cros-libva/src/buffer/vp9.rs @@ -0,0 +1,451 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Wrappers around VP9 `VABuffer` types. + +use crate::bindings; + +/// Wrapper over the `pic_fields` bindgen field in `VAPictureParameterBufferVP9`. +pub struct VP9PicFields(bindings::_VADecPictureParameterBufferVP9__bindgen_ty_1); + +impl VP9PicFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + subsampling_x: u32, + subsampling_y: u32, + frame_type: u32, + show_frame: u32, + error_resilient_mode: u32, + intra_only: u32, + allow_high_precision_mv: u32, + mcomp_filter_type: u32, + frame_parallel_decoding_mode: u32, + reset_frame_context: u32, + refresh_frame_context: u32, + frame_context_idx: u32, + segmentation_enabled: u32, + segmentation_temporal_update: u32, + segmentation_update_map: u32, + last_ref_frame: u32, + last_ref_frame_sign_bias: u32, + golden_ref_frame: u32, + golden_ref_frame_sign_bias: u32, + alt_ref_frame: u32, + alt_ref_frame_sign_bias: u32, + lossless_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VADecPictureParameterBufferVP9__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + subsampling_x, + subsampling_y, + frame_type, + show_frame, + error_resilient_mode, + intra_only, + allow_high_precision_mv, + mcomp_filter_type, + frame_parallel_decoding_mode, + reset_frame_context, + refresh_frame_context, + frame_context_idx, + segmentation_enabled, + segmentation_temporal_update, + segmentation_update_map, + last_ref_frame, + last_ref_frame_sign_bias, + golden_ref_frame, + golden_ref_frame_sign_bias, + alt_ref_frame, + alt_ref_frame_sign_bias, + lossless_flag, + ); + + Self(bindings::_VADecPictureParameterBufferVP9__bindgen_ty_1 { + bits: bindings::_VADecPictureParameterBufferVP9__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VADecPictureParameterBufferVP9__bindgen_ty_1 { + &self.0 + } +} + +/// Wrapper over the `PictureParameterBufferVP9` FFI type. +pub struct PictureParameterBufferVP9(Box); + +impl PictureParameterBufferVP9 { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + frame_width: u16, + frame_height: u16, + reference_frames: [bindings::VASurfaceID; 8], + pic_fields: &VP9PicFields, + filter_level: u8, + sharpness_level: u8, + log2_tile_rows: u8, + log2_tile_columns: u8, + frame_header_length_in_bytes: u8, + first_partition_size: u16, + mb_segment_tree_probs: [u8; 7usize], + segment_pred_probs: [u8; 3usize], + profile: u8, + bit_depth: u8, + ) -> Self { + let pic_fields = pic_fields.0; + + Self(Box::new(bindings::VADecPictureParameterBufferVP9 { + frame_width, + frame_height, + reference_frames, + pic_fields, + filter_level, + sharpness_level, + log2_tile_rows, + log2_tile_columns, + frame_header_length_in_bytes, + first_partition_size, + mb_segment_tree_probs, + segment_pred_probs, + profile, + bit_depth, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VADecPictureParameterBufferVP9 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VADecPictureParameterBufferVP9 { + self.0.as_ref() + } +} + +/// Wrapper over the `segment_flags` bindgen field in `VASegmentParameterVP9`. +pub struct VP9SegmentFlags(bindings::_VASegmentParameterVP9__bindgen_ty_1); + +impl VP9SegmentFlags { + /// Creates the wrapper. + pub fn new( + segment_reference_enabled: u16, + segment_reference: u16, + segment_reference_skipped: u16, + ) -> Self { + let _bitfield_1 = + bindings::_VASegmentParameterVP9__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + segment_reference_enabled, + segment_reference, + segment_reference_skipped, + ); + + Self(bindings::_VASegmentParameterVP9__bindgen_ty_1 { + fields: bindings::_VASegmentParameterVP9__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VASegmentParameterVP9__bindgen_ty_1 { + &self.0 + } +} + +/// Wrapper over the `VASegmentParameterVP9` FFI type. +pub struct SegmentParameterVP9(bindings::VASegmentParameterVP9); + +impl SegmentParameterVP9 { + /// Creates the wrapper. + pub fn new( + segment_flags: &VP9SegmentFlags, + filter_level: [[u8; 2usize]; 4usize], + luma_ac_quant_scale: i16, + luma_dc_quant_scale: i16, + chroma_ac_quant_scale: i16, + chroma_dc_quant_scale: i16, + ) -> Self { + let segment_flags = segment_flags.0; + + Self(bindings::VASegmentParameterVP9 { + segment_flags, + filter_level, + luma_ac_quant_scale, + luma_dc_quant_scale, + chroma_ac_quant_scale, + chroma_dc_quant_scale, + va_reserved: Default::default(), + }) + } +} + +/// Wrapper over the `VASliceParameterBufferVP9` FFI type. +pub struct SliceParameterBufferVP9(Box); + +impl SliceParameterBufferVP9 { + /// Creates the wrapper. + pub fn new( + slice_data_size: u32, + slice_data_offset: u32, + slice_data_flag: u32, + seg_param: [SegmentParameterVP9; 8usize], + ) -> Self { + let seg_param = seg_param.map(|param| param.0); + + Self(Box::new(bindings::VASliceParameterBufferVP9 { + slice_data_size, + slice_data_offset, + slice_data_flag, + seg_param, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VASliceParameterBufferVP9 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VASliceParameterBufferVP9 { + self.0.as_ref() + } +} + +pub struct CodedBufferVP9Status(Box); + +impl CodedBufferVP9Status { + pub fn new( + base_qp_index: u16, + loop_filter_level: u8, + long_term_indication: u8, + next_frame_width: u16, + next_frame_height: u16, + ) -> Self { + Self(Box::new(bindings::VACodedBufferVP9Status { + base_qp_index, + loop_filter_level, + long_term_indication, + next_frame_width, + next_frame_height, + va_reserved: Default::default(), + })) + } +} + +pub struct EncSequenceParameterBufferVP9(Box); + +impl EncSequenceParameterBufferVP9 { + pub fn new( + max_frame_width: u32, + max_frame_height: u32, + kf_auto: u32, + kf_min_dist: u32, + kf_max_dist: u32, + bits_per_second: u32, + intra_period: u32, + ) -> Self { + Self(Box::new(bindings::VAEncSequenceParameterBufferVP9 { + max_frame_width, + max_frame_height, + kf_auto, + kf_min_dist, + kf_max_dist, + bits_per_second, + intra_period, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncSequenceParameterBufferVP9 { + &mut self.0 + } +} + +pub struct VP9EncRefFlags(bindings::_VAEncPictureParameterBufferVP9__bindgen_ty_1); + +impl VP9EncRefFlags { + #[allow(clippy::too_many_arguments)] + pub fn new( + force_kf: u32, + ref_frame_ctrl_l0: u32, + ref_frame_ctrl_l1: u32, + ref_last_idx: u32, + ref_last_sign_bias: u32, + ref_gf_idx: u32, + ref_gf_sign_bias: u32, + ref_arf_idx: u32, + ref_arf_sign_bias: u32, + temporal_id: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferVP9__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + force_kf, + ref_frame_ctrl_l0, + ref_frame_ctrl_l1, + ref_last_idx, + ref_last_sign_bias, + ref_gf_idx, + ref_gf_sign_bias, + ref_arf_idx, + ref_arf_sign_bias, + temporal_id, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferVP9__bindgen_ty_1 { + bits: bindings::_VAEncPictureParameterBufferVP9__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +pub struct VP9EncPicFlags(bindings::_VAEncPictureParameterBufferVP9__bindgen_ty_2); + +impl VP9EncPicFlags { + #[allow(clippy::too_many_arguments)] + pub fn new( + frame_type: u32, + show_frame: u32, + error_resilient_mode: u32, + intra_only: u32, + allow_high_precision_mv: u32, + mcomp_filter_type: u32, + frame_parallel_decoding_mode: u32, + reset_frame_context: u32, + refresh_frame_context: u32, + frame_context_idx: u32, + segmentation_enabled: u32, + segmentation_temporal_update: u32, + segmentation_update_map: u32, + lossless_mode: u32, + comp_prediction_mode: u32, + auto_segmentation: u32, + super_frame_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferVP9__bindgen_ty_2__bindgen_ty_1::new_bitfield_1( + frame_type, + show_frame, + error_resilient_mode, + intra_only, + allow_high_precision_mv, + mcomp_filter_type, + frame_parallel_decoding_mode, + reset_frame_context, + refresh_frame_context, + frame_context_idx, + segmentation_enabled, + segmentation_temporal_update, + segmentation_update_map, + lossless_mode, + comp_prediction_mode, + auto_segmentation, + super_frame_flag, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferVP9__bindgen_ty_2 { + bits: bindings::_VAEncPictureParameterBufferVP9__bindgen_ty_2__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +pub struct EncPictureParameterBufferVP9(Box); + +impl EncPictureParameterBufferVP9 { + #[allow(clippy::too_many_arguments)] + pub fn new( + frame_width_src: u32, + frame_height_src: u32, + frame_width_dst: u32, + frame_height_dst: u32, + reconstructed_frame: bindings::VASurfaceID, + reference_frames: [bindings::VASurfaceID; 8usize], + coded_buf: bindings::VABufferID, + ref_flags: &VP9EncRefFlags, + pic_flags: &VP9EncPicFlags, + refresh_frame_flags: u8, + luma_ac_qindex: u8, + luma_dc_qindex_delta: i8, + chroma_ac_qindex_delta: i8, + chroma_dc_qindex_delta: i8, + filter_level: u8, + sharpness_level: u8, + ref_lf_delta: [i8; 4usize], + mode_lf_delta: [i8; 2usize], + bit_offset_ref_lf_delta: u16, + bit_offset_mode_lf_delta: u16, + bit_offset_lf_level: u16, + bit_offset_qindex: u16, + bit_offset_first_partition_size: u16, + bit_offset_segmentation: u16, + bit_size_segmentation: u16, + log2_tile_rows: u8, + log2_tile_columns: u8, + skip_frame_flag: u8, + number_skip_frames: u8, + skip_frames_size: u32, + seg_id_block_size: u8, + ) -> Self { + let ref_flags = ref_flags.0; + let pic_flags = pic_flags.0; + #[cfg(not(libva_1_23_or_higher))] + let _ = seg_id_block_size; + + Self(Box::new(bindings::VAEncPictureParameterBufferVP9 { + frame_width_src, + frame_height_src, + frame_width_dst, + frame_height_dst, + reconstructed_frame, + reference_frames, + coded_buf, + ref_flags, + pic_flags, + refresh_frame_flags, + luma_ac_qindex, + luma_dc_qindex_delta, + chroma_ac_qindex_delta, + chroma_dc_qindex_delta, + filter_level, + sharpness_level, + ref_lf_delta, + mode_lf_delta, + bit_offset_ref_lf_delta, + bit_offset_mode_lf_delta, + bit_offset_lf_level, + bit_offset_qindex, + bit_offset_first_partition_size, + bit_offset_segmentation, + bit_size_segmentation, + log2_tile_rows, + log2_tile_columns, + skip_frame_flag, + number_skip_frames, + skip_frames_size, + #[cfg(libva_1_23_or_higher)] + seg_id_block_size, + #[cfg(libva_1_23_or_higher)] + va_reserved8: Default::default(), + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncPictureParameterBufferVP9 { + &mut self.0 + } +} diff --git a/shims/cros-libva/src/config.rs b/shims/cros-libva/src/config.rs new file mode 100644 index 00000000..77550620 --- /dev/null +++ b/shims/cros-libva/src/config.rs @@ -0,0 +1,137 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::rc::Rc; + +use log::error; +use thiserror::Error; + +use crate::bindings; +use crate::display::Display; +use crate::generic_value::GenericValue; +use crate::va_check; +use crate::GenericValueError; +use crate::VaError; + +/// A configuration for a given [`Display`]. +pub struct Config { + display: Rc, + id: bindings::VAConfigID, +} + +#[derive(Debug, Error)] +pub enum QuerySurfaceAttributesError { + #[error("error while calling vaQuerySurfaceAttributes: {0}")] + VaError(#[from] VaError), + #[error("error while converting attribute: {0}")] + GenericValueError(#[from] GenericValueError), +} + +impl Config { + /// Creates a Config by wrapping around the `vaCreateConfig` call. This is just a helper for + /// [`Display::create_config`]. + pub(crate) fn new( + display: Rc, + mut attrs: Vec, + profile: bindings::VAProfile::Type, + entrypoint: bindings::VAEntrypoint::Type, + ) -> Result { + let mut config_id = 0u32; + + // Safe because `self` represents a valid `VADisplay`. + // + // The `attrs` vector is also properly initialized and its actual size is passed to + // `vaCreateConfig`, so it is impossible to write past the end of its storage by mistake. + va_check(unsafe { + bindings::vaCreateConfig( + display.handle(), + profile, + entrypoint, + attrs.as_mut_ptr(), + attrs.len() as i32, + &mut config_id, + ) + })?; + + Ok(Self { + display, + id: config_id, + }) + } + + /// Returns the ID of this config. + pub(crate) fn id(&self) -> bindings::VAConfigID { + self.id + } + + // Queries surface attributes for this config. + // + // This function queries for all supported attributes for this configuration. In particular, if + // the underlying hardware supports the creation of VA surfaces in various formats, then this + // function will enumerate all pixel formats that are supported. + fn query_surface_attributes(&mut self) -> Result, VaError> { + // Safe because `self` represents a valid VAConfig. We first query how + // much space is needed by the C API by passing in NULL in the first + // call to `vaQuerySurfaceAttributes`. + let attrs_len: std::os::raw::c_uint = 0; + va_check(unsafe { + bindings::vaQuerySurfaceAttributes( + self.display.handle(), + self.id, + std::ptr::null_mut(), + &attrs_len as *const _ as *mut std::os::raw::c_uint, + ) + })?; + + let mut attrs = Vec::with_capacity(attrs_len as usize); + // Safe because we allocate a vector with the required capacity as + // returned by the initial call to vaQuerySurfaceAttributes. We then + // pass a valid pointer to it. + va_check(unsafe { + bindings::vaQuerySurfaceAttributes( + self.display.handle(), + self.id, + attrs.as_mut_ptr(), + &attrs_len as *const _ as *mut std::os::raw::c_uint, + ) + })?; + + // Safe because vaQuerySurfaceAttributes will have written to + // exactly attrs_len entries in the vector. + unsafe { + attrs.set_len(attrs_len as usize); + } + + Ok(attrs) + } + + /// Query the surface attributes of type `attr_type`. The attribute may or may not be defined by + /// the driver. + pub fn query_surface_attributes_by_type( + &mut self, + attr_type: bindings::VASurfaceAttribType::Type, + ) -> Result, QuerySurfaceAttributesError> { + let surface_attributes = self.query_surface_attributes()?; + + surface_attributes + .into_iter() + .filter(|attr| attr.type_ == attr_type) + .map(|attr| { + GenericValue::try_from(attr.value) + .map_err(QuerySurfaceAttributesError::GenericValueError) + }) + .collect() + } +} + +impl Drop for Config { + fn drop(&mut self) { + // Safe because `self` represents a valid Config. + let status = va_check(unsafe { bindings::vaDestroyConfig(self.display.handle(), self.id) }); + + if status.is_err() { + error!("vaDestroyConfig failed: {}", status.unwrap_err()); + } + } +} diff --git a/shims/cros-libva/src/context.rs b/shims/cros-libva/src/context.rs new file mode 100644 index 00000000..ba327d44 --- /dev/null +++ b/shims/cros-libva/src/context.rs @@ -0,0 +1,110 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::rc::Rc; + +use log::error; + +use crate::bindings; +use crate::buffer::Buffer; +use crate::buffer::BufferType; +use crate::display::Display; +use crate::va_check; +use crate::Config; +use crate::EncCodedBuffer; +use crate::Surface; +use crate::SurfaceMemoryDescriptor; +use crate::VaError; + +/// A VA context for a particular [`Display`]. +pub struct Context { + display: Rc, + id: bindings::VAContextID, +} + +impl Context { + /// Creates a Context by wrapping around a `vaCreateContext` call. This is just a helper for + /// [`Display::create_context`]. + pub(crate) fn new( + display: Rc, + config: &Config, + coded_width: u32, + coded_height: u32, + surfaces: Option<&Vec>>, + progressive: bool, + ) -> Result, VaError> { + let mut context_id = 0; + let flags = if progressive { + bindings::VA_PROGRESSIVE as i32 + } else { + 0 + }; + + let mut render_targets = match surfaces { + Some(surfaces) => Surface::as_id_vec(surfaces), + None => Default::default(), + }; + + // Safe because `self` represents a valid VADisplay and render_targets + // and ntargets are properly initialized. Note that render_targets==NULL + // is valid so long as ntargets==0. + va_check(unsafe { + bindings::vaCreateContext( + display.handle(), + config.id(), + coded_width as i32, + coded_height as i32, + flags, + render_targets.as_mut_ptr(), + render_targets.len() as i32, + &mut context_id, + ) + })?; + + Ok(Rc::new(Self { + display, + id: context_id, + })) + } + + /// Returns a shared reference to the [`Display`] used by this context. + pub fn display(&self) -> &Rc { + &self.display + } + + /// Returns the ID of this context. + pub(crate) fn id(&self) -> bindings::VAContextID { + self.id + } + + /// Create a new buffer of type `type_`. + pub fn create_buffer(self: &Rc, type_: BufferType) -> Result { + Buffer::new(Rc::clone(self), type_) + } + + /// Create a new buffer from a `BorrowedBufferType`. + pub fn create_buffer_borrowed( + self: &Rc, + type_: crate::buffer::BorrowedBufferType<'_>, + ) -> Result { + Buffer::new_borrowed(Rc::clone(self), type_) + } + + /// Create a new buffer of type `type_`. + pub fn create_enc_coded(self: &Rc, size: usize) -> Result { + EncCodedBuffer::new(Rc::clone(self), size) + } +} + +impl Drop for Context { + fn drop(&mut self) { + // Safe because `self` represents a valid VAContext. + let status = + va_check(unsafe { bindings::vaDestroyContext(self.display.handle(), self.id) }); + + if status.is_err() { + error!("vaDestroyContext failed: {}", status.unwrap_err()); + } + } +} diff --git a/shims/cros-libva/src/display.rs b/shims/cros-libva/src/display.rs new file mode 100644 index 00000000..ef9eef6b --- /dev/null +++ b/shims/cros-libva/src/display.rs @@ -0,0 +1,362 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::ffi::CStr; +use std::fs::File; +use std::io; +use std::os::unix::io::AsRawFd; +use std::path::Path; +use std::path::PathBuf; +use std::rc::Rc; + +use thiserror::Error; + +use crate::bindings; +use crate::config::Config; +use crate::context::Context; +use crate::surface::Surface; +use crate::va_check; +use crate::SurfaceMemoryDescriptor; +use crate::UsageHint; +use crate::VaError; + +/// Iterates over existing DRM devices. +/// +/// DRM devices can be passed to [`Display::open_drm_display`] in order to create a `Display` on +/// that device. +pub struct DrmDeviceIterator { + cur_idx: usize, +} + +const DRM_NODE_DEFAULT_PREFIX: &str = "/dev/dri/renderD"; +const DRM_NUM_NODES: usize = 64; +const DRM_RENDER_NODE_START: usize = 128; + +impl Default for DrmDeviceIterator { + fn default() -> Self { + Self { + cur_idx: DRM_RENDER_NODE_START, + } + } +} + +impl Iterator for DrmDeviceIterator { + type Item = PathBuf; + + fn next(&mut self) -> Option { + match self.cur_idx { + idx if idx >= DRM_RENDER_NODE_START + DRM_NUM_NODES => None, + idx => { + let path = PathBuf::from(format!("{}{}", DRM_NODE_DEFAULT_PREFIX, idx)); + if !path.exists() { + None + } else { + self.cur_idx += 1; + Some(path) + } + } + } + } +} + +/// A VADisplay opened over DRM. +/// +/// A Display is the starting point to using libva. This struct is essentially a safe wrapper over +/// `VADisplay`, from which [`Surface`]s and [`Context`]s can be allocated in order to perform +/// actual work using [`Display::create_surfaces`] and [`Display::create_context`], respectively. +/// +/// Although libva offers several ways to create a display, this struct currently only supports +/// opening through DRM. It may be extended to support other display types (X11, Wayland) in the +/// future. +pub struct Display { + /// Handle to interact with the underlying `VADisplay`. + handle: bindings::VADisplay, + /// DRM file that must be kept open while the display is in use. + #[allow(dead_code)] + drm_file: File, +} + +/// Error type for `Display::open_drm_display`. +#[derive(Debug, Error)] +pub enum OpenDrmDisplayError { + #[error("cannot open DRM device: {0}")] + DeviceOpen(io::Error), + #[error("vaGetDisplayDRM returned NULL")] + VaGetDisplayDrm, + #[error("call to vaInitialize failed: {0}")] + VaInitialize(VaError), +} + +impl Display { + /// Opens and initializes a specific DRM `Display`. + /// + /// `path` is the path to a DRM device that supports VAAPI, e.g. `/dev/dri/renderD128`. + pub fn open_drm_display>(path: P) -> Result, OpenDrmDisplayError> { + let file = std::fs::File::options() + .read(true) + .write(true) + .open(path.as_ref()) + .map_err(OpenDrmDisplayError::DeviceOpen)?; + + // Safe because fd represents a valid file descriptor and the pointer is checked for + // NULL afterwards. + let display = unsafe { bindings::vaGetDisplayDRM(file.as_raw_fd()) }; + if display.is_null() { + return Err(OpenDrmDisplayError::VaGetDisplayDrm); + } + + let mut major = 0i32; + let mut minor = 0i32; + // Safe because we ensure that the display is valid (i.e not NULL) before calling + // vaInitialize. The File will close the DRM fd on drop. + va_check(unsafe { bindings::vaInitialize(display, &mut major, &mut minor) }) + .map(|()| { + Rc::new(Self { + handle: display, + drm_file: file, + }) + }) + .map_err(OpenDrmDisplayError::VaInitialize) + } + + /// Opens the first device that succeeds and returns its `Display`. + /// + /// If an error occurs on a given device, it is ignored and the next one is tried until one + /// succeeds or we reach the end of the iterator. + pub fn open() -> Option> { + let devices = DrmDeviceIterator::default(); + + // Try all the DRM devices until one succeeds. + for device in devices { + if let Ok(display) = Self::open_drm_display(device) { + return Some(display); + } + } + + None + } + + /// Returns the handle of this display. + pub(crate) fn handle(&self) -> bindings::VADisplay { + self.handle + } + + /// Queries supported profiles by this display by wrapping `vaQueryConfigProfiles`. + pub fn query_config_profiles(&self) -> Result, VaError> { + // Safe because `self` represents a valid VADisplay. + let mut max_num_profiles = unsafe { bindings::vaMaxNumProfiles(self.handle) }; + let mut profiles = Vec::with_capacity(max_num_profiles as usize); + + // Safe because `self` represents a valid `VADisplay` and the vector has `max_num_profiles` + // as capacity. + va_check(unsafe { + bindings::vaQueryConfigProfiles( + self.handle, + profiles.as_mut_ptr(), + &mut max_num_profiles, + ) + })?; + + // Safe because `profiles` is allocated with a `max_num_profiles` capacity and + // `vaQueryConfigProfiles` wrote the actual number of profiles to `max_num_entrypoints`. + unsafe { + profiles.set_len(max_num_profiles as usize); + }; + + Ok(profiles) + } + + /// Returns a string describing some aspects of the VA implemenation on the specific hardware + /// accelerator used by this display. Wrapper over `vaQueryVendorString`. + /// + /// The format of the returned string is vendor specific and at the discretion of the + /// implementer. e.g. for the Intel GMA500 implementation, an example would be: `Intel GMA500 - + /// 2.0.0.32L.0005`. + pub fn query_vendor_string(&self) -> std::result::Result { + // Safe because `self` represents a valid VADisplay. + let vendor_string = unsafe { bindings::vaQueryVendorString(self.handle) }; + + if vendor_string.is_null() { + return Err("vaQueryVendorString() returned NULL"); + } + + // Safe because we check the whether the vendor_String pointer is NULL + Ok(unsafe { CStr::from_ptr(vendor_string) } + .to_string_lossy() + .to_string()) + } + + /// Query supported entrypoints for a given profile by wrapping `vaQueryConfigEntrypoints`. + pub fn query_config_entrypoints( + &self, + profile: bindings::VAProfile::Type, + ) -> Result, VaError> { + // Safe because `self` represents a valid VADisplay. + let mut max_num_entrypoints = unsafe { bindings::vaMaxNumEntrypoints(self.handle) }; + let mut entrypoints = Vec::with_capacity(max_num_entrypoints as usize); + + // Safe because `self` represents a valid VADisplay and the vector has `max_num_entrypoints` + // as capacity. + va_check(unsafe { + bindings::vaQueryConfigEntrypoints( + self.handle, + profile, + entrypoints.as_mut_ptr(), + &mut max_num_entrypoints, + ) + })?; + + // Safe because `entrypoints` is allocated with a `max_num_entrypoints` capacity, and + // `vaQueryConfigEntrypoints` wrote the actual number of entrypoints to + // `max_num_entrypoints` + unsafe { + entrypoints.set_len(max_num_entrypoints as usize); + } + + Ok(entrypoints) + } + + /// Writes attributes for a given `profile`/`entrypoint` pair into `attributes`. Wrapper over + /// `vaGetConfigAttributes`. + /// + /// Entries of `attributes` must have their `type_` member initialized to the desired attribute + /// to retrieve. + pub fn get_config_attributes( + &self, + profile: bindings::VAProfile::Type, + entrypoint: bindings::VAEntrypoint::Type, + attributes: &mut [bindings::VAConfigAttrib], + ) -> Result<(), VaError> { + // Safe because `self` represents a valid VADisplay. The slice length is passed to the C + // function, so it is impossible to write past the end of the slice's storage by mistake. + va_check(unsafe { + bindings::vaGetConfigAttributes( + self.handle, + profile, + entrypoint, + attributes.as_mut_ptr(), + attributes.len() as i32, + ) + }) + } + + /// Creates `Surface`s by wrapping around a `vaCreateSurfaces` call. + /// + /// The number of surfaces created will be equal to the length of `descriptors`. + /// + /// # Arguments + /// + /// * `rt_format` - The desired surface format. See `VA_RT_FORMAT_*` + /// * `va_fourcc` - The desired pixel format (optional). See `VA_FOURCC_*` + /// * `width` - Width for the create surfaces + /// * `height` - Height for the created surfaces + /// * `usage_hint` - Optional hint of intended usage to optimize allocation (e.g. tiling) + /// * `num_surfaces` - Number of surfaces to create + /// * `descriptors` - Memory descriptors used as surface memory backing. + /// + /// # Return value + /// + /// Returns as many surfaces as the length of `descriptors`. + /// + /// Note that the `descriptors`'s ownership is irrevocably given to the surfaces, and that in + /// case of error the `descriptors` will be destroyed. Make sure to duplicate the descriptors + /// if you need something outside of libva to access them. + pub fn create_surfaces( + self: &Rc, + rt_format: u32, + va_fourcc: Option, + width: u32, + height: u32, + usage_hint: Option, + descriptors: Vec, + ) -> Result>, VaError> { + Surface::new( + Rc::clone(self), + rt_format, + va_fourcc, + width, + height, + usage_hint, + descriptors, + ) + } + + /// Creates a `Context` by wrapping around a `vaCreateContext` call. + /// + /// # Arguments + /// + /// * `config` - The configuration for the context + /// * `coded_width` - The coded picture width + /// * `coded_height` - The coded picture height + /// * `surfaces` - Optional hint for the amount of surfaces tied to the context + /// * `progressive` - Whether only progressive frame pictures are present in the sequence + pub fn create_context( + self: &Rc, + config: &Config, + coded_width: u32, + coded_height: u32, + surfaces: Option<&Vec>>, + progressive: bool, + ) -> Result, VaError> { + Context::new( + Rc::clone(self), + config, + coded_width, + coded_height, + surfaces, + progressive, + ) + } + + /// Creates a `Config` by wrapping around the `vaCreateConfig` call. + /// + /// `attrs` describe the attributes to set for this config. A list of the supported attributes + /// for a given profile/entrypoint pair can be retrieved using + /// [`Display::get_config_attributes`]. Other attributes will take their default values, and + /// `attrs` can be empty in order to obtain a default configuration. + pub fn create_config( + self: &Rc, + attrs: Vec, + profile: bindings::VAProfile::Type, + entrypoint: bindings::VAEntrypoint::Type, + ) -> Result { + Config::new(Rc::clone(self), attrs, profile, entrypoint) + } + + /// Returns available image formats for this display by wrapping around `vaQueryImageFormats`. + pub fn query_image_formats(&self) -> Result, VaError> { + // Safe because `self` represents a valid VADisplay. + let mut num_image_formats = unsafe { bindings::vaMaxNumImageFormats(self.handle) }; + let mut image_formats = Vec::with_capacity(num_image_formats as usize); + + // Safe because `self` represents a valid VADisplay. The `image_formats` vector is properly + // initialized and a valid size is passed to the C function, so it is impossible to write + // past the end of their storage by mistake. + va_check(unsafe { + bindings::vaQueryImageFormats( + self.handle, + image_formats.as_mut_ptr(), + &mut num_image_formats, + ) + })?; + + // Safe because the C function will have written exactly `num_image_format` entries, which + // is known to be within the vector's capacity. + unsafe { + image_formats.set_len(num_image_formats as usize); + } + + Ok(image_formats) + } +} + +impl Drop for Display { + fn drop(&mut self) { + // Safe because `self` represents a valid VADisplay. + unsafe { + bindings::vaTerminate(self.handle); + // The File will close the DRM fd on drop. + } + } +} diff --git a/shims/cros-libva/src/generic_value.rs b/shims/cros-libva/src/generic_value.rs new file mode 100644 index 00000000..621d0b08 --- /dev/null +++ b/shims/cros-libva/src/generic_value.rs @@ -0,0 +1,50 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use thiserror::Error; + +use crate::bindings; + +/// A wrapper over `VAGenericValue` giving us safe access to the underlying union members. +#[derive(Debug)] +pub enum GenericValue { + /// A wrapper over VAGenericValueTypeInteger + Integer(i32), + /// A wrapper over VAGenericValueTypeFloat + Float(f32), + /// A wrapper over VAGenericValueTypePointer + Pointer(*mut std::os::raw::c_void), + /// A wrapper over VAGenericValueTypeFunc + Func(bindings::VAGenericFunc), +} + +#[derive(Debug, Error)] +pub enum GenericValueError { + #[error("unexpected VAGenericValueType {0}")] + UnexpectedType(u32), +} + +impl TryFrom for GenericValue { + type Error = GenericValueError; + + fn try_from(value: bindings::VAGenericValue) -> Result { + // Safe because we check the type before accessing the union. + match value.type_ { + // Safe because we check the type before accessing the union. + bindings::VAGenericValueType::VAGenericValueTypeInteger => { + Ok(Self::Integer(unsafe { value.value.i })) + } + bindings::VAGenericValueType::VAGenericValueTypeFloat => { + Ok(Self::Float(unsafe { value.value.f })) + } + bindings::VAGenericValueType::VAGenericValueTypePointer => { + Ok(Self::Pointer(unsafe { value.value.p })) + } + bindings::VAGenericValueType::VAGenericValueTypeFunc => { + Ok(Self::Func(unsafe { value.value.fn_ })) + } + _ => Err(GenericValueError::UnexpectedType(value.type_)), + } + } +} diff --git a/shims/cros-libva/src/image.rs b/shims/cros-libva/src/image.rs new file mode 100644 index 00000000..2df503ba --- /dev/null +++ b/shims/cros-libva/src/image.rs @@ -0,0 +1,235 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::rc::Rc; + +use crate::bindings; +use crate::va_check; +use crate::Display; +use crate::Surface; +use crate::SurfaceMemoryDescriptor; +use crate::VaError; + +/// Wrapper around `VAImage` that is tied to the lifetime of a given `Picture`. +/// +/// An image is used to either get the surface data to client memory, or to copy image data in +/// client memory to a surface. +pub struct Image<'a> { + /// The display from which the image was created, so we can unmap it upon destruction. + display: Rc, + /// The `VAImage` returned by libva. + image: bindings::VAImage, + /// The mapped surface data. + /// + /// The lifetime also allows us to ensure that the `Surface` we have been created from + /// does not drop or get changed while we exist. + data: &'a mut [u8], + /// Whether the image was derived using the `vaDeriveImage` API or created using the + /// `vaCreateImage` API. + derived: bool, + /// The display resolution requested by the client. The implementation is + /// free to enlarge this value as needed. In any case, we guarantee that an + /// image at least as large is returned. + display_resolution: (u32, u32), + /// Tracks whether the underlying data has possibly been written to, i.e. an encoder will create + /// an image and map its buffer in order to write to it, so we must writeback later. + dirty: bool, + /// The ID of the `Surface` we have been created from. + surface_id: u32, +} + +impl<'a> Image<'a> { + /// Helper method to map a `VAImage` using `vaMapBuffer` and return an `Image`. + /// + /// Returns an error if the mapping failed. + fn new( + surface: &'a Surface, + image: bindings::VAImage, + derived: bool, + display_resolution: (u32, u32), + ) -> Result { + let mut addr = std::ptr::null_mut(); + + // Safe since `picture.inner.context` represents a valid `VAContext` and `image` has been + // successfully created at this point. + match va_check(unsafe { + bindings::vaMapBuffer(surface.display().handle(), image.buf, &mut addr) + }) { + Ok(_) => { + // Assert that libva provided us with a coded resolution that is + // at least as large as `display_resolution`. + assert!(u32::from(image.width) >= display_resolution.0); + assert!(u32::from(image.height) >= display_resolution.1); + + // Safe since `addr` points to data mapped onto our address space since we called + // `vaMapBuffer` above, which also guarantees that the data is valid for + // `image.data_size`. + let data = + unsafe { std::slice::from_raw_parts_mut(addr as _, image.data_size as usize) }; + Ok(Image { + display: Rc::clone(surface.display()), + image, + data, + derived, + display_resolution, + dirty: false, + surface_id: surface.id(), + }) + } + Err(e) => { + // Safe because `picture.inner.context` represents a valid `VAContext` and `image` + // represents a valid `VAImage`. + unsafe { + bindings::vaDestroyImage(surface.display().handle(), image.image_id); + } + + Err(e) + } + } + } + + /// Create a new derived image from this `surface` using `vaDeriveImage`. + /// + /// Derived images are a direct view (i.e. without any copy) on the buffer content of + /// `surface`. On the other hand, not all `Surface`s can be derived. + /// + /// `visible_rect` is the visible rectangle inside `surface` that we want to access. + pub fn derive_from( + surface: &'a Surface, + visible_rect: (u32, u32), + ) -> Result { + // An all-zero byte-pattern is a valid initial value for `VAImage`. + let mut image: bindings::VAImage = Default::default(); + + // Safe because `self` has a valid display handle and ID. + va_check(unsafe { + bindings::vaDeriveImage(surface.display().handle(), surface.id(), &mut image) + })?; + + Self::new(surface, image, true, visible_rect) + } + + /// Create new image from `surface` using `vaCreateImage` and `vaGetImage`. + /// + /// `visible_rect` is the visible rectangle inside `surface` that we want to access. + /// + /// The image will contain a copy of `surface`'s data' in the desired `format` and + /// `coded_resolution`, meaning the data can be scaled if `coded_resolution` and `visible_rect` + /// differ. + pub fn create_from( + surface: &'a Surface, + mut format: bindings::VAImageFormat, + coded_resolution: (u32, u32), + visible_rect: (u32, u32), + ) -> Result, VaError> { + // An all-zero byte-pattern is a valid initial value for `VAImage`. + let mut image: bindings::VAImage = Default::default(); + let dpy = surface.display().handle(); + + // Safe because `dpy` is a valid display handle. + va_check(unsafe { + bindings::vaCreateImage( + dpy, + &mut format, + coded_resolution.0 as i32, + coded_resolution.1 as i32, + &mut image, + ) + })?; + + // Safe because `dpy` is a valid display handle, `picture.surface` is a valid VASurface and + // `image` is a valid `VAImage`. + match va_check(unsafe { + bindings::vaGetImage( + dpy, + surface.id(), + 0, + 0, + coded_resolution.0, + coded_resolution.1, + image.image_id, + ) + }) { + Ok(()) => Self::new(surface, image, false, visible_rect), + + Err(e) => { + // Safe because `image` is a valid `VAImage`. + unsafe { + bindings::vaDestroyImage(dpy, image.image_id); + } + + Err(e) + } + } + } + + /// Get a reference to the underlying `VAImage` that describes this image. + pub fn image(&self) -> &bindings::VAImage { + &self.image + } + + /// Returns whether this image is directly derived from its underlying `Picture`, as opposed to + /// being a view/copy of said `Picture` in a guaranteed pixel format. + pub fn is_derived(&self) -> bool { + self.derived + } + + /// Returns the display resolution as passed in by the client. This is a + /// value that is less than or equal to the coded resolution. + pub fn display_resolution(&self) -> (u32, u32) { + self.display_resolution + } + + /// Returns the coded resolution. This value can be larger than the value + /// passed in when the image was created if the driver needs to. + pub fn coded_resolution(&self) -> (u32, u32) { + (self.image.width.into(), self.image.height.into()) + } +} + +impl<'a> AsRef<[u8]> for Image<'a> { + fn as_ref(&self) -> &[u8] { + self.data + } +} + +impl<'a> AsMut<[u8]> for Image<'a> { + fn as_mut(&mut self) -> &mut [u8] { + self.dirty = true; + self.data + } +} + +impl<'a> Drop for Image<'a> { + fn drop(&mut self) { + if !self.derived && self.dirty { + // Safe because `picture.inner.context` represents a valid `VAContext`, + // `picture.surface` represents a valid `VASurface` and `image` represents a valid + // `VAImage`. + unsafe { + bindings::vaPutImage( + self.display.handle(), + self.surface_id, + self.image.image_id, + 0, + 0, + self.image.width as u32, + self.image.height as u32, + 0, + 0, + self.image.width as u32, + self.image.height as u32, + ); + } + } + + unsafe { + // Safe since the buffer is mapped in `Image::new`, so `self.image.buf` points to a + // valid `VABufferID`. + bindings::vaUnmapBuffer(self.display.handle(), self.image.buf); + // Safe since `self.image` represents a valid `VAImage`. + bindings::vaDestroyImage(self.display.handle(), self.image.image_id); + } + } +} diff --git a/shims/cros-libva/src/lib.rs b/shims/cros-libva/src/lib.rs new file mode 100644 index 00000000..c7111f34 --- /dev/null +++ b/shims/cros-libva/src/lib.rs @@ -0,0 +1,536 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Implements a lightweight and safe interface over `libva`. +//! +//! The starting point to using this crate is to open a [`Display`], from which a [`Context`] and +//! [`Surface`]s can be allocated and used for doing actual work. + +mod bindings; +pub mod buffer; +mod config; +mod context; +mod display; +mod generic_value; +mod image; +mod picture; +mod surface; +mod usage_hint; + +pub use bindings::_VADRMPRIMESurfaceDescriptor__bindgen_ty_1 as VADRMPRIMESurfaceDescriptorObject; +pub use bindings::_VADRMPRIMESurfaceDescriptor__bindgen_ty_2 as VADRMPRIMESurfaceDescriptorLayer; +pub use bindings::*; +pub use buffer::*; +pub use config::*; +pub use context::*; +pub use display::*; +pub use generic_value::*; +pub use image::*; +pub use picture::*; +pub use surface::*; +pub use usage_hint::*; + +use std::num::NonZeroI32; + +/// A `VAStatus` that is guaranteed to not be `VA_STATUS_SUCCESS`. +#[derive(Debug)] +pub struct VaError(NonZeroI32); + +impl VaError { + /// Returns the `VAStatus` of this error. + pub fn va_status(&self) -> VAStatus { + self.0.get() as VAStatus + } +} + +impl std::fmt::Display for VaError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + use std::ffi::CStr; + + // Safe because `vaErrorStr` will return a pointer to a statically allocated, null + // terminated C string. The pointer is guaranteed to never be null. + let err_str = unsafe { CStr::from_ptr(bindings::vaErrorStr(self.0.get())) } + .to_str() + .unwrap(); + f.write_str(err_str) + } +} + +impl std::error::Error for VaError {} + +/// Checks a VA return value and returns a `VaError` if it is not `VA_STATUS_SUCCESS`. +/// +/// This can be used on the return value of any VA function returning `VAStatus` in order to +/// convert it to a proper Rust `Result`. +fn va_check(code: VAStatus) -> Result<(), VaError> { + match code as u32 { + bindings::VA_STATUS_SUCCESS => Ok(()), + _ => Err(VaError(unsafe { NonZeroI32::new_unchecked(code) })), + } +} + +#[cfg(test)] +mod tests { + use std::io::Write; + use std::rc::Rc; + + use super::*; + + /// Returns a 32-bit CRC for the visible part of `image`, which must be in NV12 format. + fn crc_nv12_image(image: &Image) -> u32 { + let data = image.as_ref(); + let va_image = image.image(); + let offsets = &va_image.offsets; + let pitches = &va_image.pitches; + let width = va_image.width as usize; + let height = va_image.height as usize; + + // We only support NV12 images + assert_eq!(va_image.format.fourcc, u32::from_ne_bytes(*b"NV12")); + // Consistency check + assert_eq!(va_image.num_planes, 2); + + let mut hasher = crc32fast::Hasher::new(); + + let offset = offsets[0] as usize; + let pitch = pitches[0] as usize; + let y_plane = data[offset..(offset + pitch * height)] + .chunks(pitch) + .map(|line| &line[0..width]); + + let offset = offsets[1] as usize; + let pitch = pitches[1] as usize; + let uv_plane = data[offset..(offset + pitch * ((height + 1) / 2))] + .chunks(pitch) + .map(|line| &line[0..width]); + + for line in y_plane.chain(uv_plane) { + hasher.update(line); + } + + hasher.finalize() + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn libva_utils_mpeg2vldemo() { + // Adapted from + let display = Display::open().unwrap(); + + assert!(!display.query_vendor_string().unwrap().is_empty()); + let profiles = display.query_config_profiles().unwrap(); + assert!(!profiles.is_empty()); + + let profile = bindings::VAProfile::VAProfileMPEG2Main; + let entrypoints = display.query_config_entrypoints(profile).unwrap(); + assert!(!entrypoints.is_empty()); + assert!(entrypoints + .iter() + .any(|e| *e == bindings::VAEntrypoint::VAEntrypointVLD)); + + let format = bindings::VA_RT_FORMAT_YUV420; + let width = 16u32; + let height = 16u32; + + let mut attrs = vec![bindings::VAConfigAttrib { + type_: bindings::VAConfigAttribType::VAConfigAttribRTFormat, + value: 0, + }]; + + let entrypoint = bindings::VAEntrypoint::VAEntrypointVLD; + display + .get_config_attributes(profile, entrypoint, &mut attrs) + .unwrap(); + assert!(attrs[0].value != bindings::VA_ATTRIB_NOT_SUPPORTED); + assert!(attrs[0].value & bindings::VA_RT_FORMAT_YUV420 != 0); + + let config = display.create_config(attrs, profile, entrypoint).unwrap(); + + let mut surfaces = display + .create_surfaces( + format, + None, + width, + height, + Some(UsageHint::USAGE_HINT_DECODER), + vec![()], + ) + .unwrap(); + let context = display + .create_context( + &config, + width, + ((height + 15) / 16) * 16, + Some(&surfaces), + true, + ) + .unwrap(); + + // The picture data is adapted from libva-utils at decode/mpeg2vldemo.cpp + // Data dump of a 16x16 MPEG2 video clip,it has one I frame + let mut mpeg2_clip: Vec = vec![ + 0x00, 0x00, 0x01, 0xb3, 0x01, 0x00, 0x10, 0x13, 0xff, 0xff, 0xe0, 0x18, 0x00, 0x00, + 0x01, 0xb5, 0x14, 0x8a, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0xb8, 0x00, 0x08, + 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0f, 0xff, 0xf8, 0x00, 0x00, 0x01, 0xb5, + 0x8f, 0xff, 0xf3, 0x41, 0x80, 0x00, 0x00, 0x01, 0x01, 0x13, 0xe1, 0x00, 0x15, 0x81, + 0x54, 0xe0, 0x2a, 0x05, 0x43, 0x00, 0x2d, 0x60, 0x18, 0x01, 0x4e, 0x82, 0xb9, 0x58, + 0xb1, 0x83, 0x49, 0xa4, 0xa0, 0x2e, 0x05, 0x80, 0x4b, 0x7a, 0x00, 0x01, 0x38, 0x20, + 0x80, 0xe8, 0x05, 0xff, 0x60, 0x18, 0xe0, 0x1d, 0x80, 0x98, 0x01, 0xf8, 0x06, 0x00, + 0x54, 0x02, 0xc0, 0x18, 0x14, 0x03, 0xb2, 0x92, 0x80, 0xc0, 0x18, 0x94, 0x42, 0x2c, + 0xb2, 0x11, 0x64, 0xa0, 0x12, 0x5e, 0x78, 0x03, 0x3c, 0x01, 0x80, 0x0e, 0x80, 0x18, + 0x80, 0x6b, 0xca, 0x4e, 0x01, 0x0f, 0xe4, 0x32, 0xc9, 0xbf, 0x01, 0x42, 0x69, 0x43, + 0x50, 0x4b, 0x01, 0xc9, 0x45, 0x80, 0x50, 0x01, 0x38, 0x65, 0xe8, 0x01, 0x03, 0xf3, + 0xc0, 0x76, 0x00, 0xe0, 0x03, 0x20, 0x28, 0x18, 0x01, 0xa9, 0x34, 0x04, 0xc5, 0xe0, + 0x0b, 0x0b, 0x04, 0x20, 0x06, 0xc0, 0x89, 0xff, 0x60, 0x12, 0x12, 0x8a, 0x2c, 0x34, + 0x11, 0xff, 0xf6, 0xe2, 0x40, 0xc0, 0x30, 0x1b, 0x7a, 0x01, 0xa9, 0x0d, 0x00, 0xac, + 0x64, + ]; + + let picture_coding_extension = + MPEG2PictureCodingExtension::new(0, 3, 0, 1, 0, 0, 0, 0, 0, 1, 1); + let pic_param = PictureParameterBufferMPEG2::new( + 16, + 16, + 0xffffffff, + 0xffffffff, + 1, + 0xffff, + &picture_coding_extension, + ); + + let pic_param = BufferType::PictureParameter(PictureParameter::MPEG2(pic_param)); + + let iq_matrix = IQMatrixBufferMPEG2::new( + 1, + 1, + 0, + 0, + [ + 8, 16, 16, 19, 16, 19, 22, 22, 22, 22, 22, 22, 26, 24, 26, 27, 27, 27, 26, 26, 26, + 26, 27, 27, 27, 29, 29, 29, 34, 34, 34, 29, 29, 29, 27, 27, 29, 29, 32, 32, 34, 34, + 37, 38, 37, 35, 35, 34, 35, 38, 38, 40, 40, 40, 48, 48, 46, 46, 56, 56, 58, 69, 69, + 83, + ], + [ + 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, + ], + [0; 64], + [0; 64], + ); + + let iq_matrix = BufferType::IQMatrix(IQMatrix::MPEG2(iq_matrix)); + + let slice_param = SliceParameterBufferMPEG2::new(150, 0, 0, 38, 0, 0, 2, 0); + + let slice_param = BufferType::SliceParameter(SliceParameter::MPEG2(slice_param)); + + let test_data_offset = 47; + let slice_data = BufferType::SliceData(mpeg2_clip.drain(test_data_offset..).collect()); + + let buffers = vec![ + context.create_buffer(pic_param).unwrap(), + context.create_buffer(slice_param).unwrap(), + context.create_buffer(iq_matrix).unwrap(), + context.create_buffer(slice_data).unwrap(), + ]; + + let mut picture = Picture::new(0, Rc::clone(&context), surfaces.remove(0)); + for buffer in buffers { + picture.add_buffer(buffer); + } + + // Actual client code can just chain the calls. + let picture = picture.begin().unwrap(); + let picture = picture.render().unwrap(); + let picture = picture.end().unwrap(); + let picture = picture.sync().map_err(|(e, _)| e).unwrap(); + + // Test whether we can map the resulting surface to obtain the raw yuv + // data + let image_fmts = display.query_image_formats().unwrap(); + let image_fmt = image_fmts + .into_iter() + .find(|f| f.fourcc == bindings::VA_FOURCC_NV12) + .expect("No valid VAImageFormat found for NV12"); + + let resolution = (width, height); + let image = picture + .create_image(image_fmt, resolution, resolution) + .unwrap(); + + assert_eq!(crc_nv12_image(&image), 0xa5713e52); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn enc_h264_demo() { + // Based on `gst-launch-1.0 videotestsrc num-buffers=1 ! video/x-raw,width=64,height=64,format=NV12 ! vaapih264enc ! filesink location=frame.h264` + // Frame created using `gst-launch-1.0 videotestsrc num-buffers=1 ! video/x-raw,width=64,height=64,format=NV12 ! filesink location=src/test_frame.nv12` + let raw_frame_nv12 = include_bytes!("test_frame.nv12"); + + let display = Display::open().unwrap(); + + let format = bindings::VA_RT_FORMAT_YUV420; + let entrypoint = bindings::VAEntrypoint::VAEntrypointEncSliceLP; + let profile = bindings::VAProfile::VAProfileH264ConstrainedBaseline; + let width = 64u32; + let height = 64u32; + + let mut attrs = vec![bindings::VAConfigAttrib { + type_: bindings::VAConfigAttribType::VAConfigAttribRTFormat, + value: 0, + }]; + + display + .get_config_attributes(profile, entrypoint, &mut attrs) + .unwrap(); + + let config = display.create_config(attrs, profile, entrypoint).unwrap(); + + let mut surfaces = display + .create_surfaces( + format, + None, + width, + height, + Some(UsageHint::USAGE_HINT_ENCODER), + vec![()], + ) + .unwrap(); + + let context = display + .create_context(&config, width, height, Some(&surfaces), true) + .unwrap(); + + let seq_fields = H264EncSeqFields::new( + 1, // 4:2:0 + 1, // Only frames + 0, 0, 0, 1, 0, 2, 0, + ); + + let image_fmts = display.query_image_formats().unwrap(); + let image_fmt = image_fmts + .into_iter() + .find(|f| f.fourcc == bindings::VA_FOURCC_NV12) + .expect("No valid VAImageFormat found for NV12"); + + let surface = surfaces.pop().unwrap(); + let surface_id = surface.id(); + + let coded_buffer = context.create_enc_coded(raw_frame_nv12.len()).unwrap(); + + let mut image = + Image::create_from(&surface, image_fmt, (width, height), (width, height)).unwrap(); + + let va_image = *image.image(); + let dest = image.as_mut(); + let data = &raw_frame_nv12[..]; + let width = width as usize; + let height = height as usize; + + let mut src = data; + let mut dst = &mut dest[va_image.offsets[0] as usize..]; + + // Copy luma + for _ in 0..height { + dst[..width].copy_from_slice(&src[..width]); + dst = &mut dst[va_image.pitches[0] as usize..]; + src = &src[width..]; + } + + // Advance to the offset of the chroma plane + let mut src = &data[width * height..]; + let mut dst = &mut dest[va_image.offsets[1] as usize..]; + + let height = height / 2; + + // Copy chroma + for _ in 0..height { + dst[..width].copy_from_slice(&src[..width]); + dst = &mut dst[va_image.pitches[1] as usize..]; + src = &src[width..]; + } + drop(image); + + let sps = BufferType::EncSequenceParameter(EncSequenceParameter::H264( + EncSequenceParameterBufferH264::new( + 0, + 10, + 10, + 30, + 1, + 0, + 1, + (width / 16) as u16, // width / 16 + (height / 16) as u16, // height / 16 + &seq_fields, + 0, + 0, + 0, + 0, + 0, + [0; 256], + None, + Some(H264VuiFields::new(1, 1, 0, 0, 0, 1, 0, 0)), + 255, + 1, + 1, + 1, + 60, + ), + )); + + let sps = context.create_buffer(sps).unwrap(); + + let ref_frames: [PictureH264; 16] = (0..16) + .map(|_| { + PictureH264::new( + bindings::VA_INVALID_ID, + 0, + bindings::VA_INVALID_SURFACE, + 0, + 0, + ) + }) + .collect::>() + .try_into() + .unwrap_or_else(|_| { + panic!(); + }); + + let pps = BufferType::EncPictureParameter(EncPictureParameter::H264( + EncPictureParameterBufferH264::new( + PictureH264::new(surface_id, 0, 0, 0, 0), + ref_frames, + coded_buffer.id(), + 0, + 0, + 0, + 0, + 26, + 0, + 0, + 0, + 0, + &H264EncPicFields::new(1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0), + ), + )); + + let pps = context.create_buffer(pps).unwrap(); + + let ref_pic_list_0: [PictureH264; 32] = (0..32) + .map(|_| { + PictureH264::new( + bindings::VA_INVALID_ID, + 0, + bindings::VA_INVALID_SURFACE, + 0, + 0, + ) + }) + .collect::>() + .try_into() + .unwrap_or_else(|_| { + panic!(); + }); + + let ref_pic_list_1: [PictureH264; 32] = (0..32) + .map(|_| { + PictureH264::new( + bindings::VA_INVALID_ID, + 0, + bindings::VA_INVALID_SURFACE, + 0, + 0, + ) + }) + .collect::>() + .try_into() + .unwrap_or_else(|_| { + panic!(); + }); + + let slice = BufferType::EncSliceParameter(EncSliceParameter::H264( + EncSliceParameterBufferH264::new( + 0, + ((width / 16) * (height / 16)) as u32, + bindings::VA_INVALID_ID, + 2, // I + 0, + 1, + 0, + 0, + [0, 0], + 1, + 0, + 0, + 0, + ref_pic_list_0, + ref_pic_list_1, + 0, + 0, + 0, + [0; 32], + [0; 32], + 0, + [[0; 2]; 32], + [[0; 2]; 32], + 0, + [0; 32], + [0; 32], + 0, + [[0; 2]; 32], + [[0; 2]; 32], + 0, + 0, + 0, + 2, + 2, + ), + )); + + let slice = context.create_buffer(slice).unwrap(); + + let mut picture = Picture::new(0, Rc::clone(&context), surface); + picture.add_buffer(pps); + picture.add_buffer(sps); + picture.add_buffer(slice); + + let picture = picture.begin().unwrap(); + let picture = picture.render().unwrap(); + let picture = picture.end().unwrap(); + let _ = picture.sync().map_err(|(e, _)| e).unwrap(); + + let coded_buf = MappedCodedBuffer::new(&coded_buffer).unwrap(); + assert_ne!(coded_buf.segments().len(), 0); + + for segment in coded_buf.iter() { + assert_ne!(segment.buf.len(), 0); + } + + const WRITE_TO_FILE: bool = false; + if WRITE_TO_FILE { + let raw_sps_bitstream: Vec = vec![ + 0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0xc0, 0x0a, 0xab, 0x42, 0x12, 0x7f, 0xe0, 0x00, + 0x20, 0x00, 0x22, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x03, 0x00, 0x79, 0x28, + ]; + + let raw_pps_bitstream: Vec = vec![0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x3c, 0x80]; + + let mut raw_file = std::fs::File::create("libva_utils_enc_h264_demo.h264").unwrap(); + raw_file.write_all(&raw_sps_bitstream).unwrap(); + raw_file.write_all(&raw_pps_bitstream).unwrap(); + + for segment in coded_buf.segments() { + raw_file.write_all(segment.buf).unwrap(); + } + + raw_file.flush().unwrap(); + } + } +} diff --git a/shims/cros-libva/src/picture.rs b/shims/cros-libva/src/picture.rs new file mode 100644 index 00000000..fd9f7090 --- /dev/null +++ b/shims/cros-libva/src/picture.rs @@ -0,0 +1,307 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::borrow::Borrow; +use std::marker::PhantomData; +use std::rc::Rc; + +use crate::bindings; +use crate::buffer::Buffer; +use crate::context::Context; +use crate::surface::Surface; +use crate::va_check; +use crate::Image; +use crate::SurfaceMemoryDescriptor; +use crate::VaError; + +// Use the sealed trait pattern to make sure that new states are not created in caller code. More +// information about the sealed trait pattern can be found at +// +mod private { + pub trait Sealed {} +} + +/// A `Picture` will only have valid YUV data after a sequence of operations are performed in a +/// particular order. This order correspond to the following VA-API calls: `vaBeginPicture`, +/// `vaRenderPicture`, `vaEndPicture` and `vaSyncSurface`. This trait enforces this ordering by +/// implementing the Typestate pattern to constrain what operations are available in what particular +/// states. +/// +/// The states for the state machine are: +/// +/// * PictureNew -> PictureBegin +/// * PictureBegin -> PictureRender +/// * PictureRender ->PictureEnd +/// * PictureEnd -> PictureSync +/// +/// Where the surface can be reclaimed in both `PictureNew` and `PictureSync`, as either no +/// operation took place (as in `PictureNew`), or it is guaranteed that the operation has already +/// completed (as in `PictureSync`). +/// +/// More information about the Typestate pattern can be found at +/// +pub trait PictureState: private::Sealed {} + +/// Represents a `Picture` that has just been created. +pub enum PictureNew {} +impl PictureState for PictureNew {} +impl private::Sealed for PictureNew {} + +/// Represents a `Picture` after `vaBeginPicture` has been called. +pub enum PictureBegin {} +impl PictureState for PictureBegin {} +impl private::Sealed for PictureBegin {} + +/// Represents a `Picture` after `vaRenderPicture` has been called. +pub enum PictureRender {} +impl PictureState for PictureRender {} +impl private::Sealed for PictureRender {} + +/// Represents a `Picture` after `vaEndPicture` has been called. +pub enum PictureEnd {} +impl PictureState for PictureEnd {} +impl private::Sealed for PictureEnd {} + +/// Represents a `Picture` after `vaSyncSurface` has been called on the underlying surface. +pub enum PictureSync {} +impl PictureState for PictureSync {} +impl private::Sealed for PictureSync {} + +/// Represents a state where one can reclaim the underlying `Surface` for this `Picture`. This is +/// true when either no decoding has been initiated or, alternatively, when the decoding operation +/// has completed for the underlying `vaSurface` +pub trait PictureReclaimableSurface: PictureState + private::Sealed {} +impl PictureReclaimableSurface for PictureNew {} +impl PictureReclaimableSurface for PictureSync {} + +/// Inner type for [`Picture`], that is, the part that exists in all states. +struct PictureInner { + /// Timestamp of the picture. + timestamp: u64, + /// A context associated with this picture. + context: Rc, + /// Contains the buffers used to decode the data. + buffers: Vec, + /// Contains the actual decoded data. Note that the surface may be shared in + /// interlaced decoding. + surface: Rc, +} + +/// A `Surface` that is being rendered into. +/// +/// This struct abstracts the decoding flow using `vaBeginPicture`, `vaRenderPicture`, +/// `vaEndPicture` and `vaSyncSurface` in a type-safe way. +/// +/// The surface will have valid picture data after all the stages of decoding are called. +/// +/// The `T` generic parameter must be `Borrow>`, i.e. it can be [`Surface`] directly or +/// some other type that contains one. +/// +/// No constraint on `T` is specified in this declaration because specifying it here would force us +/// to add the generic argument of [`Surface`] to this type as well, turning it into a type with 3 +/// generics, one of which is redundant. To avoid that we leave `T` unconstrained and instead +/// constrain the methods that require to act on it as a [`Surface`]. +pub struct Picture { + inner: Box>, + phantom: std::marker::PhantomData, +} + +impl Picture { + /// Creates a new Picture with a given `timestamp`. `surface` is the underlying surface that + /// libva will render to. + pub fn new(timestamp: u64, context: Rc, surface: T) -> Self + where + T: Borrow>, + { + Self { + inner: Box::new(PictureInner { + timestamp, + context, + buffers: Default::default(), + surface: Rc::new(surface), + }), + + phantom: PhantomData, + } + } + + /// Creates a new Picture with a given `timestamp` to identify it, + /// reusing the Surface from `picture`. This is useful for interlaced + /// decoding as one can render both fields to the same underlying surface. + pub fn new_from_same_surface(timestamp: u64, picture: &Picture) -> Self { + let context = Rc::clone(&picture.inner.context); + Picture { + inner: Box::new(PictureInner { + timestamp, + context, + buffers: Default::default(), + surface: Rc::clone(&picture.inner.surface), + }), + + phantom: PhantomData, + } + } + + /// Add `buffer` to the picture. + pub fn add_buffer(&mut self, buffer: Buffer) { + self.inner.buffers.push(buffer); + } + + /// Wrapper around `vaBeginPicture`. + pub fn begin(self) -> Result, VaError> + where + T: Borrow>, + { + // Safe because `self.inner.context` represents a valid VAContext and + // `self.inner.surface` represents a valid VASurface. + let res = va_check(unsafe { + bindings::vaBeginPicture( + self.inner.context.display().handle(), + self.inner.context.id(), + self.surface().id(), + ) + }); + + res.map(|()| Picture { + inner: self.inner, + phantom: PhantomData, + }) + } +} + +impl Picture { + /// Wrapper around `vaRenderPicture`. + pub fn render(self) -> Result, VaError> { + // Safe because `self.inner.context` represents a valid `VAContext` and `self.inner.surface` + // represents a valid `VASurface`. `buffers` point to a Rust struct and the vector length is + // passed to the C function, so it is impossible to write past the end of the vector's + // storage by mistake. + va_check(unsafe { + bindings::vaRenderPicture( + self.inner.context.display().handle(), + self.inner.context.id(), + Buffer::as_id_vec(&self.inner.buffers).as_mut_ptr(), + self.inner.buffers.len() as i32, + ) + }) + .map(|()| Picture { + inner: self.inner, + phantom: PhantomData, + }) + } +} + +impl Picture { + /// Wrapper around `vaEndPicture`. + pub fn end(self) -> Result, VaError> { + // Safe because `self.inner.context` represents a valid `VAContext`. + va_check(unsafe { + bindings::vaEndPicture( + self.inner.context.display().handle(), + self.inner.context.id(), + ) + }) + .map(|()| Picture { + inner: self.inner, + phantom: PhantomData, + }) + } +} + +impl Picture { + /// Syncs the picture, ensuring that all pending operations are complete when this call returns. + pub fn sync( + self, + ) -> Result, (VaError, Self)> + where + T: Borrow>, + { + let res = self.surface().sync(); + + match res { + Ok(()) => Ok(Picture { + inner: self.inner, + phantom: PhantomData, + }), + Err(e) => Err((e, self)), + } + } +} + +impl Picture { + /// Returns the timestamp of this picture. + pub fn timestamp(&self) -> u64 { + self.inner.timestamp + } + + /// Returns a reference to the underlying `Surface`. + /// + /// If you are interested in obtaining the container of the `Surface`, use `as_ref()` instead. + /// This is a convenience method to avoid having to call `borrow()` every time the surface is + /// needed. + pub fn surface(&self) -> &Surface + where + T: Borrow>, + { + self.as_ref().borrow() + } +} + +impl Picture { + /// Reclaim ownership of the Surface this picture has been created from, consuming the picture + /// in the process. Useful if the Surface is part of a pool. + /// + /// This will fail and return the passed object if there are more than one reference to the + /// underlying surface. + pub fn take_surface(self) -> Result { + let inner = self.inner; + match Rc::try_unwrap(inner.surface) { + Ok(surface) => Ok(surface), + Err(surface) => Err(Self { + inner: Box::new(PictureInner { + surface, + context: inner.context, + buffers: inner.buffers, + timestamp: inner.timestamp, + }), + phantom: PhantomData, + }), + } + } + + /// Create a new derived image from this `Picture` using `vaDeriveImage`. + /// + /// Derived images are a direct view (i.e. without any copy) on the buffer content of the + /// `Picture`. On the other hand, not all `Pictures` can be derived. + pub fn derive_image<'a, D: SurfaceMemoryDescriptor + 'a>( + &'a self, + visible_rect: (u32, u32), + ) -> Result, VaError> + where + T: Borrow>, + { + Image::derive_from(self.surface(), visible_rect) + } + + /// Create new image from the `Picture` using `vaCreateImage` and `vaGetImage`. + /// + /// The image will contain a copy of the `Picture` in the desired `format` and `coded_resolution`. + pub fn create_image<'a, D: SurfaceMemoryDescriptor + 'a>( + &'a self, + format: bindings::VAImageFormat, + coded_resolution: (u32, u32), + visible_rect: (u32, u32), + ) -> Result, VaError> + where + T: Borrow>, + { + Image::create_from(self.surface(), format, coded_resolution, visible_rect) + } +} + +impl AsRef for Picture { + fn as_ref(&self) -> &T { + (*self.inner.surface).borrow() + } +} diff --git a/shims/cros-libva/src/surface.rs b/shims/cros-libva/src/surface.rs new file mode 100644 index 00000000..35974091 --- /dev/null +++ b/shims/cros-libva/src/surface.rs @@ -0,0 +1,452 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::any::Any; +use std::os::fd::FromRawFd; +use std::os::fd::OwnedFd; +use std::os::raw::c_void; +use std::rc::Rc; + +use crate::bindings; +use crate::display::Display; +use crate::va_check; +use crate::UsageHint; +use crate::VASurfaceID; +use crate::VaError; + +/// Trait describing a memory backing for surfaces. +/// +/// Using external memory for backing a VA surface is done in two steps: +/// +/// 1. Build the descriptor specific to the memory type we want to use, +/// 2. Mention this descriptor as an attribute to be passed to `vaDeriveImage`. +/// +/// This trait allows to do that in a as-safe-as-possible way, by adding the required attributes +/// and returning a heap-allocated object containing the data pointed to by the attributes. That +/// way, the caller can keep that object alive until `vaCreateSurfaces` has returned. +pub trait SurfaceMemoryDescriptor { + /// Add the required attributes to `attr` in order to attach the memory of this descriptor to + /// the surface when it is created. + /// + /// The returned object, if any, is the descriptor pointed to by the attributes. The caller + /// must keep it around and unmoved until `vaCreateSurfaces` has returned. + fn add_attrs(&mut self, attrs: &mut Vec) -> Option>; +} + +/// VA memory types, aka `VA_SURFACE_ATTRIB_MEM_TYPE_*`. +#[repr(u32)] +pub enum MemoryType { + Va = bindings::VA_SURFACE_ATTRIB_MEM_TYPE_VA, + V4L2 = bindings::VA_SURFACE_ATTRIB_MEM_TYPE_V4L2, + UserPtr = bindings::VA_SURFACE_ATTRIB_MEM_TYPE_USER_PTR, + DrmPrime2 = bindings::VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2, +} + +/// Used when we want the VA driver to allocate surface memory for us. In this case we don't need +/// to add any specific attribute for surface creation. +impl SurfaceMemoryDescriptor for () { + fn add_attrs(&mut self, _: &mut Vec) -> Option> { + None + } +} + +/// Sealed trait pattern to avoid reimplementation of our local traits. +mod private { + pub trait Sealed {} +} + +/// Trait for types that can be used as a `VASurfaceAttribExternalBufferDescriptor`. +pub trait SurfaceExternalDescriptor: private::Sealed {} +impl private::Sealed for bindings::VASurfaceAttribExternalBuffers {} +impl SurfaceExternalDescriptor for bindings::VASurfaceAttribExternalBuffers {} +impl private::Sealed for bindings::VADRMPRIMESurfaceDescriptor {} +impl SurfaceExternalDescriptor for bindings::VADRMPRIMESurfaceDescriptor {} + +/// Trait allowing to import an external memory source to use with a surface by setting the +/// `VASurfaceAttribMemoryType` and `VASurfaceAttribExternalBuffers` attributes. +pub trait ExternalBufferDescriptor { + /// Memory type to set for `VASurfaceAttribMemoryType`. + const MEMORY_TYPE: MemoryType; + /// Type of the descriptor to be set with `VASurfaceAttribExternalBuffers`. + type DescriptorAttribute: SurfaceExternalDescriptor; + + /// Returns the `Self::DescriptorAttribute` instance allowing this memory to be imported + /// into VAAPI. + fn va_surface_attribute(&mut self) -> Self::DescriptorAttribute; +} + +impl SurfaceMemoryDescriptor for T +where + T: ExternalBufferDescriptor, + ::DescriptorAttribute: 'static, +{ + fn add_attrs(&mut self, attrs: &mut Vec) -> Option> { + let mut desc = Box::new(self.va_surface_attribute()); + + attrs.push(bindings::VASurfaceAttrib::new_memory_type( + Self::MEMORY_TYPE, + )); + attrs.push(bindings::VASurfaceAttrib::new_buffer_descriptor( + desc.as_mut(), + )); + + Some(desc) + } +} + +/// Decode error type aka `VADecodeErrorType` +#[repr(u32)] +#[derive(Debug)] +pub enum DecodeErrorType { + SliceMissing = bindings::VADecodeErrorType::VADecodeSliceMissing, + MBError = bindings::VADecodeErrorType::VADecodeMBError, + #[cfg(libva_1_20_or_higher)] + Reset = bindings::VADecodeErrorType::VADecodeReset, +} + +/// Decode error details extracted from `VASurfaceDecodeMBErrors`, result of vaQuerySurfaceError. +#[derive(Debug)] +pub struct SurfaceDecodeMBError { + /// Start mb address with errors + pub start_mb: u32, + + /// End mb address with errors + pub end_mb: u32, + + pub decode_error_type: DecodeErrorType, + + /// Number of mbs with errors + pub num_mb: u32, +} + +/// An owned VA surface that is tied to a particular `Display`. +pub struct Surface { + display: Rc, + id: bindings::VASurfaceID, + descriptor: D, + width: u32, + height: u32, +} + +impl From for bindings::VAGenericValue { + fn from(i: i32) -> Self { + Self { + type_: bindings::VAGenericValueType::VAGenericValueTypeInteger, + value: bindings::_VAGenericValue__bindgen_ty_1 { i }, + } + } +} + +impl From for bindings::VAGenericValue { + fn from(f: f32) -> Self { + Self { + type_: bindings::VAGenericValueType::VAGenericValueTypeFloat, + value: bindings::_VAGenericValue__bindgen_ty_1 { f }, + } + } +} + +impl From<*mut c_void> for bindings::VAGenericValue { + fn from(p: *mut c_void) -> Self { + Self { + type_: bindings::VAGenericValueType::VAGenericValueTypePointer, + value: bindings::_VAGenericValue__bindgen_ty_1 { p }, + } + } +} + +/// Helpers to build valid `VASurfaceAttrib`s. +impl bindings::VASurfaceAttrib { + pub fn new_pixel_format(fourcc: u32) -> Self { + Self { + type_: bindings::VASurfaceAttribType::VASurfaceAttribPixelFormat, + flags: bindings::VA_SURFACE_ATTRIB_SETTABLE, + value: bindings::VAGenericValue::from(fourcc as i32), + } + } + + pub fn new_usage_hint(usage_hint: UsageHint) -> Self { + Self { + type_: bindings::VASurfaceAttribType::VASurfaceAttribUsageHint, + flags: bindings::VA_SURFACE_ATTRIB_SETTABLE, + value: bindings::VAGenericValue::from(usage_hint.bits() as i32), + } + } + + pub fn new_memory_type(mem_type: MemoryType) -> Self { + Self { + type_: bindings::VASurfaceAttribType::VASurfaceAttribMemoryType, + flags: bindings::VA_SURFACE_ATTRIB_SETTABLE, + value: bindings::VAGenericValue::from(mem_type as i32), + } + } + + pub fn new_buffer_descriptor(desc: &mut T) -> Self { + Self { + type_: bindings::VASurfaceAttribType::VASurfaceAttribExternalBufferDescriptor, + flags: bindings::VA_SURFACE_ATTRIB_SETTABLE, + value: bindings::VAGenericValue::from(desc as *mut _ as *mut c_void), + } + } +} + +impl Surface { + /// Create `Surfaces` by wrapping around a `vaCreateSurfaces` call. This is just a helper for + /// [`Display::create_surfaces`]. + pub(crate) fn new( + display: Rc, + rt_format: u32, + va_fourcc: Option, + width: u32, + height: u32, + usage_hint: Option, + descriptors: Vec, + ) -> Result, VaError> { + let mut surfaces = vec![]; + + for mut descriptor in descriptors { + let mut attrs = vec![]; + + if let Some(usage_hint) = usage_hint { + attrs.push(bindings::VASurfaceAttrib::new_usage_hint(usage_hint)); + } + + if let Some(fourcc) = va_fourcc { + attrs.push(bindings::VASurfaceAttrib::new_pixel_format(fourcc)); + } + + // Just to be kept alive until we call `vaCreateSurfaces`... + let mut _va_desc = descriptor.add_attrs(&mut attrs); + let mut surface_id: VASurfaceID = 0; + + // Safe because `self` represents a valid VADisplay. The `surface` and `attrs` vectors are + // properly initialized and valid sizes are passed to the C function, so it is impossible to + // write past the end of their storage by mistake. + // + // Also all the pointers in `attrs` are pointing to valid objects that haven't been + // moved or destroyed. + match va_check(unsafe { + bindings::vaCreateSurfaces( + display.handle(), + rt_format, + width, + height, + &mut surface_id, + 1, + attrs.as_mut_ptr(), + attrs.len() as u32, + ) + }) { + Ok(()) => surfaces.push(Self { + display: Rc::clone(&display), + id: surface_id, + descriptor, + width, + height, + }), + Err(e) => return Err(e), + } + } + + Ok(surfaces) + } + + pub(crate) fn display(&self) -> &Rc { + &self.display + } + + /// Wrapper around `vaSyncSurface` that blocks until all pending operations on the render + /// target have been completed. + /// + /// Upon return it + /// is safe to use the render target for a different picture. + pub fn sync(&self) -> Result<(), VaError> { + // Safe because `self` represents a valid VASurface. + va_check(unsafe { bindings::vaSyncSurface(self.display.handle(), self.id) }) + } + + /// Convenience function to return a VASurfaceID vector. Useful to interface with the C API + /// where a surface array might be needed. + pub fn as_id_vec(surfaces: &[Self]) -> Vec { + surfaces.iter().map(|surface| surface.id).collect() + } + + /// Wrapper over `vaQuerySurfaceStatus` to find out any pending ops on the render target. + pub fn query_status(&self) -> Result { + let mut status: bindings::VASurfaceStatus::Type = 0; + // Safe because `self` represents a valid VASurface. + va_check(unsafe { + bindings::vaQuerySurfaceStatus(self.display.handle(), self.id, &mut status) + })?; + + Ok(status) + } + + pub fn query_error(&self) -> Result, VaError> { + let mut raw: *const bindings::VASurfaceDecodeMBErrors = std::ptr::null(); + + // Safe because `self` represents a valid VASurface. + va_check(unsafe { + bindings::vaQuerySurfaceError( + self.display.handle(), + self.id, + bindings::VA_STATUS_ERROR_DECODING_ERROR as i32, + (&mut raw) as *mut _ as *mut _, + ) + })?; + + let mut errors = vec![]; + + while !raw.is_null() { + // Safe because raw is a valid pointer + let error = unsafe { *raw }; + if error.status == -1 { + break; + } + + let type_ = match error.decode_error_type { + bindings::VADecodeErrorType::VADecodeSliceMissing => DecodeErrorType::SliceMissing, + bindings::VADecodeErrorType::VADecodeMBError => DecodeErrorType::MBError, + #[cfg(libva_1_20_or_higher)] + bindings::VADecodeErrorType::VADecodeReset => DecodeErrorType::Reset, + _ => { + log::warn!( + "Unrecognized `decode_error_type` value ({})", + error.decode_error_type + ); + + // Safe because status != -1 + raw = unsafe { raw.offset(1) }; + continue; + } + }; + + errors.push(SurfaceDecodeMBError { + start_mb: error.start_mb, + end_mb: error.end_mb, + decode_error_type: type_, + num_mb: error.num_mb, + }); + + // Safe because status != -1 + raw = unsafe { raw.offset(1) }; + } + + Ok(errors) + } + + /// Returns the ID of this surface. + pub fn id(&self) -> bindings::VASurfaceID { + self.id + } + + /// Returns the dimensions of this surface. + pub fn size(&self) -> (u32, u32) { + (self.width, self.height) + } + + /// Returns a PRIME descriptor for this surface. + pub fn export_prime(&self) -> Result { + let mut desc: bindings::VADRMPRIMESurfaceDescriptor = Default::default(); + + va_check(unsafe { + bindings::vaExportSurfaceHandle( + self.display.handle(), + self.id(), + bindings::VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2, + bindings::VA_EXPORT_SURFACE_READ_ONLY | bindings::VA_EXPORT_SURFACE_COMPOSED_LAYERS, + &mut desc as *mut _ as *mut c_void, + ) + })?; + + // We do not use a `From` implementation as this would allow + // to create "safe" descriptors outside of this method and thus from made up values, + // violating the safety guarantee that our FDs are legit. + + let objects = (0..desc.num_objects as usize) + // Make sure we don't go out of bounds. + .take(4) + .map(|i| desc.objects[i]) + .map(|o| { + DrmPrimeSurfaceDescriptorObject { + // Safe because `o.fd` is a valid file descriptor returned by + // `vaExportSurfaceHandle`. + fd: unsafe { OwnedFd::from_raw_fd(o.fd) }, + size: o.size, + drm_format_modifier: o.drm_format_modifier, + } + }) + .collect(); + + let layers = (0..desc.num_layers as usize) + // Make sure we don't go out of bounds. + .take(4) + .map(|i| desc.layers[i]) + .map(|l| DrmPrimeSurfaceDescriptorLayer { + drm_format: l.drm_format, + num_planes: l.num_planes, + object_index: [ + l.object_index[0] as u8, + l.object_index[1] as u8, + l.object_index[2] as u8, + l.object_index[3] as u8, + ], + offset: l.offset, + pitch: l.pitch, + }) + .collect(); + + Ok(DrmPrimeSurfaceDescriptor { + fourcc: desc.fourcc, + width: desc.width, + height: desc.height, + objects, + layers, + }) + } +} + +impl AsRef for Surface { + fn as_ref(&self) -> &D { + &self.descriptor + } +} + +impl AsMut for Surface { + fn as_mut(&mut self) -> &mut D { + &mut self.descriptor + } +} + +impl Drop for Surface { + fn drop(&mut self) { + // Safe because `self` represents a valid VASurface. + unsafe { bindings::vaDestroySurfaces(self.display.handle(), &mut self.id, 1) }; + } +} + +/// Safe wrapper for the `object` member of `VADRMPRIMESurfaceDescriptor`. +pub struct DrmPrimeSurfaceDescriptorObject { + pub fd: OwnedFd, + pub size: u32, + pub drm_format_modifier: u64, +} + +/// Safe wrapper for the `layers` member of `VADRMPRIMESurfaceDescriptor`. +pub struct DrmPrimeSurfaceDescriptorLayer { + pub drm_format: u32, + pub num_planes: u32, + pub object_index: [u8; 4], + pub offset: [u32; 4], + pub pitch: [u32; 4], +} + +/// Safe wrapper around `VADRMPRIMESurfaceDescriptor`. +pub struct DrmPrimeSurfaceDescriptor { + pub fourcc: u32, + pub width: u32, + pub height: u32, + pub objects: Vec, + pub layers: Vec, +} diff --git a/shims/cros-libva/src/test_frame.nv12 b/shims/cros-libva/src/test_frame.nv12 new file mode 100644 index 0000000000000000000000000000000000000000..c4e20156136e29109852b74653a43055505f6a57 GIT binary patch literal 6144 zcmaF;8VWAKz$zG+2m@I#5C{XBZ~)Ujsvibm!8aOyFaS$Fqv;0*;Mr$1|G)q&`;6uv z7=UG;(fk7guQC8K2r7jO<29Z%~<}m=$aIZ3og&>NY(!`pxtK-h5Q?xOwKSKEo?1@}$~- zTzcQCGNtTnr_2pqXG+9v>bv zUF51r)&HdYMD3-#r}DkVHGLEI$?qgpfAqoF`^S`3PpWPdj;ooRexFqRv-=Bom@LU& z=&++?_fl&IAyV~gi#VH2R(o+v>HMM04Hv35lB)lN)+F^QlG8U&Nzr76!Rwf|>_bl)punS3U=jo_6M(=xNi!t~JarEOCq0k)0D&L!U~p7F1dN8? zX!;q=KcEm8S>*?;9NbY3D+ytx<