diff --git a/Cargo.lock b/Cargo.lock index c3f09064..252b0a60 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -308,7 +308,6 @@ version = "0.0.13" dependencies = [ "bindgen", "bitflags 2.13.1", - "crc32fast", "log", "pkg-config", "regex", @@ -1908,9 +1907,6 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" name = "vk-video-ffi" version = "0.1.0" dependencies = [ - "ec-av1-syntax", - "ec-h264-syntax", - "ec-h265-syntax", "vulkanalia", "windows", ] diff --git a/crates/ec-va/abi-probe.c b/crates/ec-va/abi-probe.c deleted file mode 100644 index 951fea88..00000000 --- a/crates/ec-va/abi-probe.c +++ /dev/null @@ -1,90 +0,0 @@ -/* - * ABI probe for the hand-written libva FFI in src/sys.rs. - * - * src/sys.rs transcribes libva struct layouts by hand (no bindgen, family rule). - * This probe is the evidence for that transcription: it prints the sizes, - * alignments and field offsets that the *system* headers produce, so the - * `const _: () = assert!(...)` block in sys.rs can be checked against a real - * compiler instead of against a reading of the header. - * - * Run: - * cc -o /tmp/ec-va-abi-probe crates/ec-va/abi-probe.c $(pkg-config --cflags --libs libva) \ - * && /tmp/ec-va-abi-probe - * - * Recorded output (libva 1.23.0, x86_64-unknown-linux-gnu, gcc 15) is pasted - * into the assertion block in sys.rs. Any mismatch after a libva upgrade means - * the transcription drifted — the exact failure mode that broke cros-libva at - * libva >= 1.23. - */ -#include -#include -#include -#include - -#define SA(T) printf("%-32s size=%-5zu align=%zu\n", #T, sizeof(T), _Alignof(T)) -#define OF(T, F) printf(" %-30s offset=%zu\n", #T "." #F, offsetof(T, F)) - -int main(void) -{ - printf("libva headers: %s\n", VA_VERSION_S); - - SA(VAStatus); - SA(VAGenericID); - SA(VAProfile); - SA(VAEntrypoint); - SA(VAConfigAttribType); - SA(VAConfigAttrib); - OF(VAConfigAttrib, type); - OF(VAConfigAttrib, value); - - SA(VAGenericValue); - OF(VAGenericValue, type); - OF(VAGenericValue, value); - - SA(VASurfaceAttrib); - OF(VASurfaceAttrib, type); - OF(VASurfaceAttrib, flags); - OF(VASurfaceAttrib, value); - - SA(VAImageFormat); - OF(VAImageFormat, fourcc); - OF(VAImageFormat, byte_order); - OF(VAImageFormat, bits_per_pixel); - OF(VAImageFormat, depth); - OF(VAImageFormat, red_mask); - OF(VAImageFormat, alpha_mask); - OF(VAImageFormat, va_reserved); - - SA(VAImage); - OF(VAImage, image_id); - OF(VAImage, format); - OF(VAImage, buf); - OF(VAImage, width); - OF(VAImage, height); - OF(VAImage, data_size); - OF(VAImage, num_planes); - OF(VAImage, pitches); - OF(VAImage, offsets); - OF(VAImage, num_palette_entries); - OF(VAImage, entry_bytes); - OF(VAImage, component_order); - OF(VAImage, va_reserved); - - SA(VADRMPRIMESurfaceDescriptor); - OF(VADRMPRIMESurfaceDescriptor, fourcc); - OF(VADRMPRIMESurfaceDescriptor, width); - OF(VADRMPRIMESurfaceDescriptor, height); - OF(VADRMPRIMESurfaceDescriptor, num_objects); - OF(VADRMPRIMESurfaceDescriptor, objects); - OF(VADRMPRIMESurfaceDescriptor, num_layers); - OF(VADRMPRIMESurfaceDescriptor, layers); - printf(" object elem size=%zu align=%zu\n", - sizeof(((VADRMPRIMESurfaceDescriptor *)0)->objects[0]), - _Alignof(((VADRMPRIMESurfaceDescriptor *)0)->objects[0])); - printf(" layer elem size=%zu align=%zu\n", - sizeof(((VADRMPRIMESurfaceDescriptor *)0)->layers[0]), - _Alignof(((VADRMPRIMESurfaceDescriptor *)0)->layers[0])); - - SA(VARectangle); - return 0; -} diff --git a/crates/ec-va/src/cacheline.rs b/crates/ec-va/src/cacheline.rs deleted file mode 100644 index adfb03ca..00000000 --- a/crates/ec-va/src/cacheline.rs +++ /dev/null @@ -1,78 +0,0 @@ -//! Which cache lines a CPU write-back of a mapped DMA-BUF has to visit. -//! -//! `CLFLUSH` takes an address and writes back the whole cache line holding it, -//! so a buffer needs one flush per line, not one per byte. The incumbent -//! stack flushed every byte (64 instructions per line, 6.2 ms per 1080p -//! picture on radeonsi). The base of a mapping is not guaranteed to be cache -//! aligned, so the last byte's line is flushed too: a range that starts -//! mid-line can straddle one more line than its length suggests. - -/// Bytes per cache line on every x86-64 part this crate targets. -pub const CACHE_LINE: usize = 64; - -/// Offsets from a mapping's base at which to issue a flush for a buffer of -/// `len` bytes: one per [`CACHE_LINE`], plus the last byte when the stride -/// does not land on it. Empty for `len == 0`, which has no line to flush. -pub fn flush_offsets(len: usize) -> Vec { - if len == 0 { - return Vec::new(); - } - let last = len - 1; - let mut offsets: Vec = (0..len).step_by(CACHE_LINE).collect(); - if offsets.last() != Some(&last) { - offsets.push(last); - } - offsets -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The absolute cache-line indices a flush at `offsets` writes back, for a - /// mapping whose base sits `base_mod` bytes into a line. - fn lines_flushed(base_mod: usize, offsets: &[usize]) -> Vec { - let base = 1000 * CACHE_LINE + base_mod; - let mut lines: Vec = offsets.iter().map(|o| (base + o) / CACHE_LINE).collect(); - lines.sort_unstable(); - lines.dedup(); - lines - } - - #[test] - fn empty_buffer_has_nothing_to_flush() { - assert!(flush_offsets(0).is_empty()); - } - - #[test] - fn one_flush_per_line_not_per_byte() { - assert_eq!(flush_offsets(1), vec![0]); - // 64 bytes from an unaligned base can still straddle two lines: the last byte too. - assert_eq!(flush_offsets(64), vec![0, 63]); - assert_eq!(flush_offsets(65), vec![0, 64]); - assert_eq!(flush_offsets(128), vec![0, 64, 127]); - // A 1080p NV12 picture (~3.1 MB) is ~48K flushes, not ~3.1M. - assert!(flush_offsets(1920 * 1620).len() <= 1920 * 1620 / CACHE_LINE + 2); - } - - // Regression for the straddle: with an unaligned base, the bytes of a - // range can sit in one more line than a stride from the base reaches, so - // every byte's line must be among the flushed lines for every alignment. - #[test] - fn every_byte_is_covered_for_every_base_alignment() { - for base_mod in 0..CACHE_LINE { - for len in 0..=300 { - let offsets = flush_offsets(len); - let flushed = lines_flushed(base_mod, &offsets); - let base = 1000 * CACHE_LINE + base_mod; - for i in 0..len { - let line = (base + i) / CACHE_LINE; - assert!( - flushed.contains(&line), - "base_mod {base_mod} len {len}: byte {i} (line {line}) not flushed" - ); - } - } - } - } -} diff --git a/crates/ec-va/src/caps.rs b/crates/ec-va/src/caps.rs index c37583e8..d879e39e 100644 --- a/crates/ec-va/src/caps.rs +++ b/crates/ec-va/src/caps.rs @@ -127,25 +127,6 @@ va_enum! { } } -impl Profile { - /// True for the profiles the family decodes or encodes in hardware. - pub fn is_family_codec(self) -> bool { - matches!( - self, - Profile::H264ConstrainedBaseline - | Profile::H264Main - | Profile::H264High - | Profile::H264High10 - | Profile::HEVCMain - | Profile::HEVCMain10 - | Profile::VP9Profile0 - | Profile::VP9Profile2 - | Profile::AV1Profile0 - | Profile::AV1Profile2 - ) - } -} - /// What one (profile, entrypoint) pair supports. /// One supported (profile, entrypoint) pair and what the driver says about it. #[derive(Debug, Clone)] diff --git a/crates/ec-va/src/config.rs b/crates/ec-va/src/config.rs index e8591a6c..77cf20b2 100644 --- a/crates/ec-va/src/config.rs +++ b/crates/ec-va/src/config.rs @@ -64,11 +64,9 @@ impl SurfaceCaps { } } -/// A live `VAConfigID`, remembering the profile and entrypoint it was made for. +/// A live `VAConfigID`. pub struct Config { inner: cros_libva::Config, - profile: Profile, - entrypoint: Entrypoint, } impl Config { @@ -90,21 +88,7 @@ impl Config { "vaCreateConfig", display.create_config(attrs, profile.as_raw(), entrypoint.as_raw()), )?; - Ok(Config { - inner, - profile, - entrypoint, - }) - } - - /// The profile this config decodes or encodes. - pub fn profile(&self) -> Profile { - self.profile - } - - /// The entrypoint this config was created for. - pub fn entrypoint(&self) -> Entrypoint { - self.entrypoint + Ok(Config { inner }) } /// The cros-libva handle, for the calls that take one. diff --git a/crates/ec-va/src/display.rs b/crates/ec-va/src/display.rs index 972d439a..3978fb60 100644 --- a/crates/ec-va/src/display.rs +++ b/crates/ec-va/src/display.rs @@ -1,6 +1,5 @@ //! Opening a VA display on a DRM render node. -use std::path::Path; use std::rc::Rc; use crate::error::{Error, Result}; @@ -14,14 +13,6 @@ pub fn open() -> Result> { Display::open().ok_or(Error::NoDevice) } -/// Open a specific DRM render node. -pub fn open_path(path: &Path) -> Result> { - Display::open_drm_display(path).map_err(|e| Error::Drm { - path: path.display().to_string(), - message: format!("{e:?}"), - }) -} - /// The driver's vendor string (`vaQueryVendorString`). pub fn vendor(display: &Display) -> Result { display diff --git a/crates/ec-va/src/error.rs b/crates/ec-va/src/error.rs index 89d46b6d..d51379ed 100644 --- a/crates/ec-va/src/error.rs +++ b/crates/ec-va/src/error.rs @@ -21,13 +21,6 @@ pub enum Error { /// libva's description of `status`. message: String, }, - /// A DRM render node could not be opened as a VA display. - Drm { - /// The node that was tried. - path: String, - /// Why it failed. - message: String, - }, /// No usable `/dev/dri/renderD*` VA display exists. NoDevice, /// libva returned a value this crate cannot interpret. @@ -66,7 +59,6 @@ impl fmt::Display for Error { status, message, } => write!(f, "{op} failed: {message} (VAStatus 0x{status:08x})"), - Error::Drm { path, message } => write!(f, "opening DRM node {path}: {message}"), Error::NoDevice => write!(f, "no usable /dev/dri/renderD* VA display"), Error::Protocol(what) => write!(f, "libva returned an uninterpretable value: {what}"), } diff --git a/crates/ec-va/src/lib.rs b/crates/ec-va/src/lib.rs index d9a3b6ef..889857e7 100644 --- a/crates/ec-va/src/lib.rs +++ b/crates/ec-va/src/lib.rs @@ -34,7 +34,6 @@ #![forbid(unsafe_code)] #![deny(missing_docs)] -pub mod cacheline; pub mod caps; pub mod config; pub mod display; @@ -47,7 +46,7 @@ pub use cros_libva as va; pub use caps::{CapEntry, CapReport, Entrypoint, Profile, fourcc_str}; pub use config::{Config, ConfigAttrib, SurfaceCaps, caps_of}; -pub use display::{Display, open, open_path}; +pub use display::{Display, open}; pub use error::{Error, Result}; pub use picture::{Buffer, Context, Picture, create_context}; pub use surface::{ diff --git a/crates/ec-va/tests/gpu.rs b/crates/ec-va/tests/gpu.rs index c5ebc99c..c91e677b 100644 --- a/crates/ec-va/tests/gpu.rs +++ b/crates/ec-va/tests/gpu.rs @@ -9,14 +9,12 @@ //! //! Reference: `vainfo` on this box (Mesa 26.1.6, radeonsi gfx1200, RX 9060 XT). -use std::os::fd::AsRawFd; use std::rc::Rc; use std::sync::{Mutex, MutexGuard, OnceLock}; -use std::time::Duration; use ec_va::caps::{Entrypoint, Profile}; use ec_va::va; -use ec_va::{CapReport, Config, Display, Image, Surface, SurfaceExt, SurfaceSpec, create_pool}; +use ec_va::{CapReport, Display, Image, Surface, SurfaceExt, SurfaceSpec, create_pool}; /// Runs the tests in this binary one at a time. /// @@ -57,28 +55,6 @@ fn one(display: &Rc, spec: &SurfaceSpec) -> Surface { // -------------------------------------------------------------------------- // Display -// -------------------------------------------------------------------------- - -// The raw `Display::version` / `device_path` / `is_valid` checks no longer -// exist in cros-libva; what remains observable is that the open succeeded and -// the driver answers real queries. -#[test] -fn display_opens_on_a_render_node() { - let _serial = serial(); - let display = display(); - let vendor = ec_va::display::vendor(&display).expect("vendor string"); - assert!(!vendor.is_empty(), "driver reported an empty vendor string"); - assert!( - !display - .query_config_profiles() - .expect("profiles") - .is_empty() - ); -} - -// -------------------------------------------------------------------------- -// Capabilities — the table must match `vainfo` on this GPU -// -------------------------------------------------------------------------- #[test] fn caps_match_vainfo_on_this_gpu() { @@ -170,351 +146,6 @@ fn caps_match_vainfo_on_this_gpu() { ); } -#[test] -fn caps_report_driver_legal_surface_sizes() { - let _serial = serial(); - let display = display(); - let caps = CapReport::probe(&display).expect("probe"); - let entry = caps - .entry(Profile::H264Main, Entrypoint::VLD) - .expect("H264 Main VLD"); - let surfaces = entry.surfaces.as_ref().expect("surface caps"); - - // radeonsi rejects decode surfaces below 64x64. Probing with a hardcoded - // 16x16 config is what used to panic here, so the minimum is reported - // rather than assumed. - assert_eq!(surfaces.min_width, Some(64)); - assert_eq!(surfaces.min_height, Some(64)); - assert!(surfaces.max_width.unwrap() >= 4096); - assert!( - !surfaces.allows(16, 16), - "16x16 must be refused by the caps" - ); - assert!(surfaces.allows(1920, 1088)); - - // DRM PRIME 2 export must be advertised: that is how frames leave the GPU. - assert!( - surfaces.memory_types & va::VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2 != 0, - "memory types 0x{:08x} lack DRM_PRIME_2", - surfaces.memory_types - ); -} - -#[test] -fn unsupported_pair_is_refused_by_the_driver() { - let _serial = serial(); - // A refusal is a claim: prove the capability is genuinely absent rather - // than assumed absent. - let display = display(); - let caps = CapReport::probe(&display).expect("probe"); - assert!(!caps.supports(Profile::VP9Profile1, Entrypoint::VLD)); - - let err = Config::new(&display, Profile::VP9Profile1, Entrypoint::VLD, &[]) - .err() - .expect("VP9 Profile1 decode does not exist on this GPU"); - let status = err.status().expect("a VAStatus-carrying error"); - assert!( - status == va::VA_STATUS_ERROR_UNSUPPORTED_PROFILE as i32 - || status == va::VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT as i32, - "unexpected refusal: {err}" - ); - assert!(err.to_string().contains("vaCreateConfig"), "{err}"); -} - -// -------------------------------------------------------------------------- -// Surfaces -// -------------------------------------------------------------------------- - -#[test] -fn surface_pool_create_and_destroy_is_leak_free() { - let _serial = serial(); - let display = display(); - let spec = SurfaceSpec::nv12(64, 64); - - // Warm up so first-touch allocations are not counted as a leak. - for _ in 0..4 { - let p = pool(&display, &spec, 16); - assert_eq!(p.len(), 16); - drop(p); - } - - let before = vm_rss_kb(); - for _ in 0..100 { - let p = pool(&display, &spec, 16); - // Every id must be distinct and valid, or the pool is aliasing memory. - let mut ids: Vec<_> = p.iter().map(|s| s.id()).collect(); - ids.sort_unstable(); - ids.dedup(); - assert_eq!(ids.len(), 16, "vaCreateSurfaces returned duplicate ids"); - assert!(ids.iter().all(|&id| id != va::VA_INVALID_SURFACE)); - drop(p); - } - let after = vm_rss_kb(); - - // 1600 surfaces created and destroyed. A per-surface leak would be obvious - // at this scale; the incumbent's unmatched map leaked ~3MB per frame. - let delta_kb = after.saturating_sub(before); - assert!( - delta_kb < 50 * 1024, - "VmRSS grew {delta_kb} kB over 100 create/destroy cycles" - ); -} - -#[test] -fn derive_image_maps_and_reads_back() { - let _serial = serial(); - let display = display(); - let surface = one(&display, &SurfaceSpec::nv12(64, 64)); - let mut image = Image::derive_from(&surface, (64, 64)).expect("vaDeriveImage"); - - let va_image = *image.image(); - assert_eq!(va_image.format.fourcc, va::VA_FOURCC_NV12); - assert_eq!(image.display_resolution(), (64, 64)); - assert!(image.is_derived()); - assert_eq!(va_image.num_planes, 2, "NV12 is luma + interleaved chroma"); - let pitch = va_image.pitches[0] as usize; - assert!(pitch >= 64, "luma pitch {pitch} is narrower than the image"); - assert!(va_image.pitches[1] > 0, "chroma pitch missing"); - let luma_off = va_image.offsets[0] as usize; - let chroma_off = va_image.offsets[1] as usize; - assert!( - chroma_off >= luma_off + pitch * 64, - "luma plane must be at least pitch * height" - ); - - { - let bytes: &mut [u8] = image.as_mut(); - assert!( - bytes.len() > chroma_off, - "mapping shorter than chroma plane" - ); - for (i, byte) in bytes[luma_off..luma_off + pitch * 64] - .iter_mut() - .enumerate() - { - *byte = (i % 251) as u8; - } - let luma = &bytes[luma_off..]; - assert_eq!(luma[0], 0); - assert_eq!(luma[250], 250); - assert_eq!(luma[251], 0, "write did not survive within the mapping"); - } - drop(image); - - // Re-deriving after the drop proves the unmap/destroy actually happened. - // - // What is deliberately *not* asserted: that the bytes written above are - // readable through this second mapping. On radeonsi 26.1 a derived-image - // mapping is write-oriented staging — the write reaches the surface (see - // `created_image_reads_a_surface_back`), but a fresh map reads back zeros. - let again = Image::derive_from(&surface, (64, 64)).expect("second vaDeriveImage"); - assert_eq!( - again.image().pitches[0] as usize, - pitch, - "second mapping has a different geometry" - ); - assert!(!AsRef::<[u8]>::as_ref(&again).is_empty()); -} - -#[test] -fn created_image_reads_a_surface_back() { - let _serial = serial(); - let display = display(); - let surface = one(&display, &SurfaceSpec::nv12(64, 64)); - // Paint through the derived image so there is something known to read back. - { - let mut derived = Image::derive_from(&surface, (64, 64)).expect("derive"); - let luma_off = derived.image().offsets[0] as usize; - let pitch = derived.image().pitches[0] as usize; - let bytes: &mut [u8] = derived.as_mut(); - for byte in &mut bytes[luma_off..luma_off + pitch * 64] { - *byte = 0x5a; - } - } - surface.sync().expect("sync"); - - let fmt = image_format(&display, va::VA_FOURCC_NV12); - let image = Image::create_from(&surface, fmt, (64, 64), (64, 64)).expect("vaGetImage"); - let luma_off = image.image().offsets[0] as usize; - let bytes: &[u8] = image.as_ref(); - assert!( - bytes[luma_off..luma_off + 64].iter().all(|&b| b == 0x5a), - "vaGetImage did not return the painted luma" - ); - drop(image); - - // A region larger than the surface must be refused, not read out of bounds. - let fmt = image_format(&display, va::VA_FOURCC_NV12); - let refused = Image::create_from(&surface, fmt, (128, 128), (128, 128)); - assert!( - refused.is_err(), - "region larger than the surface must be refused" - ); -} - -#[test] -fn prime_export_owns_and_releases_its_descriptors() { - let _serial = serial(); - let display = display(); - let surface = one(&display, &SurfaceSpec::nv12(64, 64)); - surface - .sync_timeout(Duration::from_secs(5)) - .expect("sync before export"); - - let baseline = open_fd_count(); - let exported = surface.export().expect("vaExportSurfaceHandle"); - - assert_eq!(exported.fourcc, va::VA_FOURCC_NV12); - assert_eq!((exported.width, exported.height), (64, 64)); - assert!(!exported.objects.is_empty(), "no DRM objects exported"); - assert!(!exported.layers.is_empty(), "no layers exported"); - for object in &exported.objects { - assert!(object.fd.as_raw_fd() >= 0); - assert!(object.size > 0); - } - for layer in &exported.layers { - assert!(!layer.planes.is_empty()); - for &(object_index, _offset, pitch) in &layer.planes { - assert!((object_index as usize) < exported.objects.len()); - assert!(pitch > 0); - } - } - - let with_export = open_fd_count(); - assert_eq!( - with_export - baseline, - exported.objects.len(), - "exported fd count does not match the descriptor" - ); - drop(exported); - assert_eq!( - open_fd_count(), - baseline, - "dropping the export leaked file descriptors" - ); -} - -// -------------------------------------------------------------------------- -// Context / picture protocol -// -------------------------------------------------------------------------- - -#[test] -fn picture_typestate_walks_the_va_protocol() { - let _serial = serial(); - let display = display(); - let config = Config::new(&display, Profile::H264Main, Entrypoint::VLD, &[]).expect("config"); - let targets = pool(&display, &SurfaceSpec::nv12(1920, 1088), 2); - let context = ec_va::create_context(&display, &config, 1920, 1088, Some(&targets), true) - .expect("context"); - let targets: Vec> = targets.into_iter().map(Rc::new).collect(); - - // New -> Begin. Each transition consumes the picture, so nothing can call - // `begin` twice or reach `sync` without `end`. - let picture = ec_va::Picture::new(0, Rc::clone(&context), Rc::clone(&targets[0])); - let picture = picture.begin::<()>().expect("vaBeginPicture"); - assert_eq!(picture.surface::<()>().id(), targets[0].id()); - - // Begin -> Render -> End. Submitting a picture with no parameter buffers - // is a driver-level error here (mesa creates the decoder lazily from the - // picture parameters); what matters is that it surfaces as a typed error - // instead of a panic, an abort or a GPU hang. Real submissions carry - // parameter/slice buffers and are `ec-hw`'s job. - let failed = picture.render().and_then(|p| p.end()); - let err = failed - .err() - .expect("empty submission is rejected by radeonsi"); - assert_eq!( - err.va_status(), - va::VA_STATUS_ERROR_INVALID_CONTEXT as i32, - "{err}" - ); - - // The display is still usable afterwards: an abandoned picture must not - // wedge the context. - let picture = ec_va::Picture::new(0, Rc::clone(&context), Rc::clone(&targets[1])) - .begin::<()>() - .expect("second vaBeginPicture after a failed end"); - drop(picture); - assert!(display.query_vendor_string().is_ok()); -} - -#[test] -fn buffers_map_unmap_and_destroy() { - let _serial = serial(); - let display = display(); - let config = - Config::new(&display, Profile::H264Main, Entrypoint::EncSlice, &[]).expect("config"); - let targets = pool(&display, &SurfaceSpec::nv12(1920, 1088), 1); - let context = ec_va::create_context(&display, &config, 1920, 1088, Some(&targets), true) - .expect("context"); - - // Coded-output buffer: allocated empty, mapped, unmapped, dropped. - const CODED_SIZE: usize = 1 << 20; - let coded = context - .create_enc_coded(CODED_SIZE) - .expect("vaCreateBuffer"); - assert_ne!(coded.id(), va::VA_INVALID_ID); - { - let mapped = va::MappedCodedBuffer::new(&coded).expect("vaMapBuffer"); - // Never filled by an encode: no segment carries payload bytes. - assert!(mapped.iter().all(|s| s.buf.is_empty())); - } - // Mapping again proves the guard released the mapping. - drop(va::MappedCodedBuffer::new(&coded).expect("second vaMapBuffer after unmap")); - - // Parameter buffer: data is copied into driver memory during the call. - let buffer = ec_va::picture::buffer( - &context, - va::BufferType::EncMiscParameter(va::EncMiscParameter::FrameRate( - va::EncMiscParameterFrameRate::new(30, 0), - )), - ) - .expect("vaCreateBuffer from a typed parameter"); - drop(buffer); - drop(coded); -} - -#[test] -fn context_keeps_its_dependencies_alive() { - let _serial = serial(); - // Dropping the config and the surfaces while the context lives must be - // safe: the context holds `Rc`s, so libva's destruction order (buffers -> - // context -> surfaces -> config -> display) cannot be violated. - let display = display(); - let config = Config::new(&display, Profile::H264Main, Entrypoint::VLD, &[]).expect("config"); - let targets = pool(&display, &SurfaceSpec::nv12(1920, 1088), 2); - let context = ec_va::create_context(&display, &config, 1920, 1088, Some(&targets), true) - .expect("context"); - let target = Rc::new(targets.into_iter().next().expect("target")); - drop(config); - - let picture = ec_va::Picture::new(0, Rc::clone(&context), target) - .begin::<()>() - .expect("begin"); - drop(picture); - drop(context); - assert!(display.query_vendor_string().is_ok()); -} - -// -------------------------------------------------------------------------- -// VPP -// -------------------------------------------------------------------------- - -// `vaQueryVideoProcFilters` is no longer wrapped (cros-libva has no such -// call), so the filter list cannot be printed. The equivalent: a pipeline -// still opens on the real display and runs a whole-surface NV12 pass. -#[test] -fn vpp_filters_probe() { - let _serial = serial(); - let display = display(); - let targets = pool(&display, &SurfaceSpec::nv12(1920, 1080), 2); - let vpp = ec_va::Vpp::new(&display, va::VA_RT_FORMAT_YUV420, 1920, 1080).expect("vpp opens"); - let mut it = targets.into_iter(); - let src = it.next().expect("src"); - let dst = Rc::new(it.next().expect("dst")); - vpp.convert(&src, dst).expect("vpp pipeline runs"); -} - /// `Vpp::convert` end to end: a P010 source surface into an NV12 destination, /// no readback — the conversion `ec-hw`'s `encode_frame` relies on for a /// 10-bit source. @@ -537,21 +168,6 @@ fn vpp_converts_p010_to_nv12() { // -------------------------------------------------------------------------- // helpers -// -------------------------------------------------------------------------- - -fn vm_rss_kb() -> u64 { - let status = std::fs::read_to_string("/proc/self/status").expect("/proc/self/status"); - for line in status.lines() { - if let Some(rest) = line.strip_prefix("VmRSS:") { - return rest - .split_whitespace() - .next() - .and_then(|v| v.parse().ok()) - .expect("VmRSS value"); - } - } - panic!("VmRSS not found in /proc/self/status"); -} fn open_fd_count() -> usize { std::fs::read_dir("/proc/self/fd") diff --git a/shims/cros-libva/Android.bp b/shims/cros-libva/Android.bp deleted file mode 100644 index e1ae101c..00000000 --- a/shims/cros-libva/Android.bp +++ /dev/null @@ -1,63 +0,0 @@ -// 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 index c2d9e978..84d4fb65 100644 --- a/shims/cros-libva/Cargo.toml +++ b/shims/cros-libva/Cargo.toml @@ -21,6 +21,3 @@ log = { version = "0", features = ["release_max_level_debug"] } 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/src/buffer.rs b/shims/cros-libva/src/buffer.rs index c5f2686d..b6a62dc5 100644 --- a/shims/cros-libva/src/buffer.rs +++ b/shims/cros-libva/src/buffer.rs @@ -5,25 +5,17 @@ //! 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; @@ -61,14 +53,6 @@ impl Buffer { 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()), @@ -93,25 +77,9 @@ impl Buffer { 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()), @@ -132,25 +100,9 @@ impl Buffer { 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()), @@ -159,23 +111,9 @@ impl Buffer { 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()) @@ -190,10 +128,6 @@ impl Buffer { 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()), @@ -213,10 +147,6 @@ impl Buffer { 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()), @@ -289,12 +219,6 @@ impl Buffer { 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()), @@ -419,34 +343,28 @@ impl Drop for Buffer { /// Abstraction over `VABufferType`s. pub enum BufferType { - /// Abstraction over `VAPictureParameterBufferType`. Needed for MPEG2, VP8, VP9, H264, JPEGBaseline. + /// Abstraction over `VAPictureParameterBufferType`. Needed for VP9, H264. PictureParameter(PictureParameter), - /// Abstraction over `VASliceParameterBufferType`. Needed for MPEG2, VP8, VP9, H264, JPEGBaseline. + /// Abstraction over `VASliceParameterBufferType`. Needed for VP9, H264. SliceParameter(SliceParameter), - /// Abstraction over `VAIQMatrixBufferType`. Needed for VP8, H264, JPEGBaseline. + /// Abstraction over `VAIQMatrixBufferType`. Needed for H264. 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. + /// Abstraction over `VAEncSequenceParameterBufferType`. Needed for VP9, H264, HEVC. EncSequenceParameter(EncSequenceParameter), - /// Abstraction over `VAEncPictureParameterBufferType`. Needed for MPEG2, VP8, VP9, H264, HEVC. + /// Abstraction over `VAEncPictureParameterBufferType`. Needed for VP9, H264, HEVC. EncPictureParameter(EncPictureParameter), - /// Abstraction over `VAEncSliceParameterBufferType`. Needed for MPEG2, VP8, VP9, H264, HEVC. + /// Abstraction over `VAEncSliceParameterBufferType`. Needed for VP9, H264, HEVC. EncSliceParameter(EncSliceParameter), /// Abstraction over `VAEncMacroblockMapBufferType`. Needed for H264. EncMacroblockParameterBuffer(EncMacroblockParameterBuffer), - /// Abstraction over `VAEncCodedBufferType`. Needed for MPEG2, VP8, VP9, H264, HEVC. + /// Abstraction over `VAEncCodedBufferType`. Needed for 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`. @@ -460,8 +378,6 @@ impl BufferType { 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(_) => { @@ -488,7 +404,6 @@ impl BufferType { bindings::VABufferType::VAProcPipelineParameterBufferType } - BufferType::QMatrix(_) => bindings::VABufferType::VAQMatrixBufferType, BufferType::EncPackedHeaderParameter(_) => { bindings::VABufferType::VAEncPackedHeaderParameterBufferType @@ -503,10 +418,6 @@ impl BufferType { /// 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. @@ -519,18 +430,10 @@ pub enum PictureParameter { 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 @@ -541,37 +444,16 @@ pub enum SliceParameter { 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 { @@ -579,8 +461,6 @@ pub enum EncSequenceParameter { H264(h264::EncSequenceParameterBufferH264), /// Abstraction over `VAEncSequenceParameterBufferHEVC` HEVC(hevc::EncSequenceParameterBufferHEVC), - /// Abstraction over `VAEncSequenceParameterBufferVP8` - VP8(vp8::EncSequenceParameterBufferVP8), /// Abstraction over `VAEncSequenceParameterBufferVP9` VP9(vp9::EncSequenceParameterBufferVP9), /// Abstraction over `VAEncSequenceParameterBufferAV1` @@ -593,8 +473,6 @@ pub enum EncPictureParameter { H264(h264::EncPictureParameterBufferH264), /// Abstraction over `VAEncPictureParameterBufferHEVC` HEVC(hevc::EncPictureParameterBufferHEVC), - /// Abstraction over `VAEncPictureParameterBufferVP8` - VP8(vp8::EncPictureParameterBufferVP8), /// Abstraction over `VAEncPictureParameterBufferVP9` VP9(vp9::EncPictureParameterBufferVP9), /// Abstraction over `VAEncPictureParameterBufferAV1` diff --git a/shims/cros-libva/src/buffer/enc_jpeg.rs b/shims/cros-libva/src/buffer/enc_jpeg.rs deleted file mode 100644 index 3b656ed4..00000000 --- a/shims/cros-libva/src/buffer/enc_jpeg.rs +++ /dev/null @@ -1,159 +0,0 @@ -// 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/jpeg_baseline.rs b/shims/cros-libva/src/buffer/jpeg_baseline.rs deleted file mode 100644 index 92d962f4..00000000 --- a/shims/cros-libva/src/buffer/jpeg_baseline.rs +++ /dev/null @@ -1,220 +0,0 @@ -// 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 deleted file mode 100644 index 22df3141..00000000 --- a/shims/cros-libva/src/buffer/mpeg2.rs +++ /dev/null @@ -1,172 +0,0 @@ -// 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 index 2c2ea936..9a03ecb0 100644 --- a/shims/cros-libva/src/buffer/proc_pipeline.rs +++ b/shims/cros-libva/src/buffer/proc_pipeline.rs @@ -5,7 +5,7 @@ //! Wrappers around `VAProcPipeline` types. use crate::bindings; -use std::{marker::PhantomData, ptr}; +use std::ptr; /// Wrapper over the `VABlendState` ffi type. pub struct BlendState(bindings::VABlendState); diff --git a/shims/cros-libva/src/buffer/vp8.rs b/shims/cros-libva/src/buffer/vp8.rs deleted file mode 100644 index 70989e1c..00000000 --- a/shims/cros-libva/src/buffer/vp8.rs +++ /dev/null @@ -1,397 +0,0 @@ -// 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/lib.rs b/shims/cros-libva/src/lib.rs index c7111f34..70792843 100644 --- a/shims/cros-libva/src/lib.rs +++ b/shims/cros-libva/src/lib.rs @@ -69,468 +69,3 @@ fn va_check(code: VAStatus) -> Result<(), VaError> { _ => 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/test_frame.nv12 b/shims/cros-libva/src/test_frame.nv12 deleted file mode 100644 index c4e20156136e29109852b74653a43055505f6a57..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 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< Av1ColorConfig { - Av1ColorConfig { - bit_depth: c.bit_depth, - mono_chrome: c.mono_chrome, - color_range: c.color_range, - separate_uv_delta_q: c.separate_uv_delta_q, - subsampling_x: c.subsampling_x, - subsampling_y: c.subsampling_y, - color_primaries: c.color_primaries, - transfer_characteristics: c.transfer_characteristics, - matrix_coefficients: c.matrix_coefficients, - chroma_sample_position: match c.chroma_sample_position { - ChromaSamplePosition::Unknown => 0, - ChromaSamplePosition::Vertical => 1, - ChromaSamplePosition::Colocated => 2, - ChromaSamplePosition::Reserved => 3, - }, - } -} - -fn sequence(s: &SequenceHeader) -> Av1SequenceHeader { - Av1SequenceHeader { - seq_profile: s.seq_profile, - still_picture: s.still_picture, - reduced_still_picture_header: s.reduced_still_picture_header, - timing_info: s.timing_info.map(|t| Av1TimingInfo { - equal_picture_interval: t.equal_picture_interval, - num_units_in_display_tick: t.num_units_in_display_tick, - time_scale: t.time_scale, - num_ticks_per_picture_minus_1: t.num_ticks_per_picture.saturating_sub(1), - }), - initial_display_delay_present: s.initial_display_delay_present_flag, - frame_width_bits_minus_1: (s.frame_width_bits - 1) as u8, - frame_height_bits_minus_1: (s.frame_height_bits - 1) as u8, - max_frame_width_minus_1: (s.max_frame_width - 1) as u16, - max_frame_height_minus_1: (s.max_frame_height - 1) as u16, - frame_id_numbers_present: s.frame_id_numbers_present_flag, - delta_frame_id_length_minus_2: s.delta_frame_id_length.saturating_sub(2) as u8, - additional_frame_id_length_minus_1: s.additional_frame_id_length.saturating_sub(1) as u8, - order_hint_bits_minus_1: s.order_hint_bits.saturating_sub(1) as u8, - seq_force_integer_mv: s.seq_force_integer_mv, - seq_force_screen_content_tools: s.seq_force_screen_content_tools, - use_128x128_superblock: s.use_128x128_superblock, - enable_filter_intra: s.enable_filter_intra, - enable_intra_edge_filter: s.enable_intra_edge_filter, - enable_interintra_compound: s.enable_interintra_compound, - enable_masked_compound: s.enable_masked_compound, - enable_warped_motion: s.enable_warped_motion, - enable_dual_filter: s.enable_dual_filter, - enable_order_hint: s.enable_order_hint, - enable_jnt_comp: s.enable_jnt_comp, - enable_ref_frame_mvs: s.enable_ref_frame_mvs, - enable_superres: s.enable_superres, - enable_cdef: s.enable_cdef, - enable_restoration: s.enable_restoration, - color_config: color(&s.color_config), - film_grain_params_present: s.film_grain_params_present, - } -} - -fn restoration(r: RestorationType) -> Av1Restoration { - match r { - RestorationType::None => Av1Restoration::None, - RestorationType::Wiener => Av1Restoration::Wiener, - RestorationType::Sgrproj => Av1Restoration::Sgrproj, - RestorationType::Switchable => Av1Restoration::Switchable, - } -} - -fn frame(h: &FrameHeader, s: &SequenceHeader) -> Av1FrameHeader { - let sb_shift = s.sb_shift(); - let mut global_motion = [Av1GlobalMotion::default(); 8]; - let mut order_hints = [0u8; 8]; - for i in 0..7 { - global_motion[i + 1] = Av1GlobalMotion { - model: match h.global_motion[i].model { - WarpModel::Identity => Av1WarpModel::Identity, - WarpModel::Translation => Av1WarpModel::Translation, - WarpModel::Rotzoom => Av1WarpModel::Rotzoom, - WarpModel::Affine => Av1WarpModel::Affine, - }, - params: h.global_motion[i].params, - }; - order_hints[i + 1] = h.order_hints[i] as u8; - } - Av1FrameHeader { - frame_type: match h.frame_type { - FrameType::Key => Av1FrameType::Key, - FrameType::Inter => Av1FrameType::Inter, - FrameType::IntraOnly => Av1FrameType::IntraOnly, - FrameType::Switch => Av1FrameType::Switch, - }, - show_frame: h.show_frame, - showable_frame: h.showable_frame, - error_resilient_mode: h.error_resilient_mode, - disable_cdf_update: h.disable_cdf_update, - allow_screen_content_tools: h.allow_screen_content_tools, - force_integer_mv: h.force_integer_mv, - current_frame_id: h.current_frame_id, - frame_size_override_flag: h.frame_size_override_flag, - order_hint: h.order_hint as u8, - primary_ref_frame: h.primary_ref_frame, - refresh_frame_flags: h.refresh_frame_flags, - frame_width: h.frame_width, - frame_height: h.frame_height, - upscaled_width: h.upscaled_width, - render_width: h.render_width, - render_height: h.render_height, - use_superres: h.use_superres, - superres_denom: h.superres_denom, - allow_intrabc: h.allow_intrabc, - allow_high_precision_mv: h.allow_high_precision_mv, - is_motion_mode_switchable: h.is_motion_mode_switchable, - use_ref_frame_mvs: h.use_ref_frame_mvs, - frame_refs_short_signaling: h.frame_refs_short_signaling, - disable_frame_end_update_cdf: h.disable_frame_end_update_cdf, - reference_select: h.reference_select, - skip_mode_present: h.skip_mode_present, - allow_warped_motion: h.allow_warped_motion, - reduced_tx_set: h.reduced_tx_set, - interpolation_filter: match h.interpolation_filter { - InterpolationFilter::Eighttap => Av1InterpolationFilter::EightTap, - InterpolationFilter::EighttapSmooth => Av1InterpolationFilter::EightTapSmooth, - InterpolationFilter::EighttapSharp => Av1InterpolationFilter::EightTapSharp, - InterpolationFilter::Bilinear => Av1InterpolationFilter::Bilinear, - InterpolationFilter::Switchable => Av1InterpolationFilter::Switchable, - }, - tx_mode: match h.tx_mode { - TxMode::Only4x4 => Av1TxMode::Only4x4, - TxMode::Largest => Av1TxMode::Largest, - TxMode::Select => Av1TxMode::Select, - }, - tile_info: Av1TileInfo { - uniform_spacing: h.tile_info.uniform_spacing, - cols: h.tile_info.cols as u8, - rows: h.tile_info.rows as u8, - mi_col_starts: h - .tile_info - .mi_col_starts - .iter() - .map(|&v| v as u16) - .collect(), - mi_row_starts: h - .tile_info - .mi_row_starts - .iter() - .map(|&v| v as u16) - .collect(), - width_in_sbs_minus_1: h.tile_info.width_in_sbs_minus_1(sb_shift), - height_in_sbs_minus_1: h.tile_info.height_in_sbs_minus_1(sb_shift), - context_update_tile_id: h.tile_info.context_update_tile_id as u16, - tile_size_bytes_minus_1: h.tile_info.tile_size_bytes.saturating_sub(1) as u8, - }, - quantization: Av1Quantization { - base_q_idx: h.quantization.base_q_idx, - delta_q_y_dc: h.quantization.delta_q_y_dc, - delta_q_u_dc: h.quantization.delta_q_u_dc, - delta_q_u_ac: h.quantization.delta_q_u_ac, - delta_q_v_dc: h.quantization.delta_q_v_dc, - delta_q_v_ac: h.quantization.delta_q_v_ac, - using_qmatrix: h.quantization.using_qmatrix, - qm_y: h.quantization.qm_y, - qm_u: h.quantization.qm_u, - qm_v: h.quantization.qm_v, - }, - segmentation: Av1Segmentation { - enabled: h.segmentation.enabled, - update_map: h.segmentation.update_map, - temporal_update: h.segmentation.temporal_update, - update_data: h.segmentation.update_data, - feature_enabled: h.segmentation.feature_enabled, - feature_data: h.segmentation.feature_data, - }, - delta: Av1DeltaParams { - q_present: h.delta.q_present, - q_res: h.delta.q_res, - lf_present: h.delta.lf_present, - lf_res: h.delta.lf_res, - lf_multi: h.delta.lf_multi, - }, - loop_filter: Av1LoopFilter { - level: h.loop_filter.level, - sharpness: h.loop_filter.sharpness, - delta_enabled: h.loop_filter.delta_enabled, - delta_update: h.loop_filter.delta_update, - ref_deltas: h.loop_filter.ref_deltas, - mode_deltas: h.loop_filter.mode_deltas, - }, - cdef: Av1Cdef { - damping_minus_3: h.cdef.damping.saturating_sub(3), - bits: h.cdef.bits, - y_pri: h.cdef.y_pri_strength, - y_sec: h.cdef.y_sec_strength, - uv_pri: h.cdef.uv_pri_strength, - uv_sec: h.cdef.uv_sec_strength, - }, - loop_restoration: Av1LoopRestoration { - frame_restoration_type: h.loop_restoration.frame_restoration_type.map(restoration), - loop_restoration_size: h.loop_restoration.loop_restoration_size.map(|v| v as u16), - }, - global_motion, - order_hints, - skip_mode_frame: h.skip_mode_frame, - expected_frame_id: [0; 8], - apply_grain: h.film_grain.apply_grain, - } -} - -fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 { - a.iter() - .zip(b) - .map(|(&x, &y)| (f64::from(x) - f64::from(y)).abs()) - .sum::() - / a.len() as f64 -} - -fn main() { - let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); - let stream = dir.join("key.ivf"); - let reference = dir.join("av1_ref.yuv"); - let status = Command::new("ffmpeg") - .args(["-y", "-loglevel", "error", "-f", "lavfi", "-i"]) - .arg("testsrc2=size=320x240:rate=30") - .args(["-frames:v", "1", "-c:v", "libsvtav1", "-f", "ivf"]) - .arg(&stream) - .status() - .expect("run ffmpeg"); - assert!(status.success()); - let status = Command::new("ffmpeg") - .args(["-y", "-loglevel", "error", "-i"]) - .arg(&stream) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .arg(&reference) - .status() - .expect("run ffmpeg"); - assert!(status.success()); - - let ivf = fs::read(&stream).expect("read ivf"); - let header_len = u16::from_le_bytes([ivf[6], ivf[7]]) as usize; - let frame_len = - u32::from_le_bytes(ivf[header_len..header_len + 4].try_into().unwrap()) as usize; - let data = &ivf[header_len + 12..header_len + 12 + frame_len]; - - let mut parser = Av1Parser::new(); - let obus = parser - .parse_temporal_unit(data) - .expect("parse temporal unit"); - let mut seq = None; - let mut frame_obu = None; - for obu in obus { - match obu.kind { - ObuKind::SequenceHeader(s) => seq = Some(*s), - ObuKind::Frame(h, tiles) => frame_obu = Some((*h, tiles)), - _ => {} - } - } - let seq = seq.expect("sequence header"); - let (header, tiles) = frame_obu.expect("frame OBU"); - assert_eq!(header.frame_type, FrameType::Key); - - let offsets: Vec = tiles.iter().map(|t| t.offset as u32).collect(); - let sizes: Vec = tiles.iter().map(|t| t.size as u32).collect(); - let plain_seq = sequence(&seq); - let plain_frame = frame(&header, &seq); - let (w, h) = (header.upscaled_width, header.frame_height); - - let gpu = Gpu::open().expect("open GPU"); - println!("device: {}", gpu.device_name()); - let cfg = Av1DecodeConfig { - max_width: w, - max_height: h, - max_dpb_slots: 9, - bit_depth: 8, - }; - let mut session = Av1DecodeSession::new(&gpu, &cfg).expect("decode session"); - session - .set_sequence_header(&plain_seq) - .expect("sequence header"); - let pic = Av1DecodePicture { - header: &plain_frame, - setup_slot: 0, - ref_frame_slot: [-1; 7], - refs: &[], - tile_data: data, - tile_offsets: &offsets, - tile_sizes: &sizes, - }; - session.decode(&pic).expect("decode"); - session.store_output(0, (0, 0, w, h)).expect("store"); - let (y, uv) = session.read_output(0, w, h).expect("read slot"); - - let reference = fs::read(&reference).expect("read reference"); - let luma = (w * h) as usize; - let chroma = luma / 4; - let ref_uv: Vec = reference[luma..luma + chroma] - .iter() - .zip(&reference[luma + chroma..luma + 2 * chroma]) - .flat_map(|(&u, &v)| [u, v]) - .collect(); - println!( - "mean abs diff Y: {:.6}", - mean_abs_diff(&y, &reference[..luma]) - ); - println!("mean abs diff UV: {:.6}", mean_abs_diff(&uv, &ref_uv)); -} diff --git a/shims/vk-video-ffi/examples/d3d11_pool.rs b/shims/vk-video-ffi/examples/d3d11_pool.rs deleted file mode 100644 index 102b0523..00000000 --- a/shims/vk-video-ffi/examples/d3d11_pool.rs +++ /dev/null @@ -1,111 +0,0 @@ -#[cfg(windows)] -fn main() { - use std::os::windows::io::AsRawHandle; - - use vk_video_ffi::D3d11Pool; - use windows::Win32::Foundation::{HANDLE, HMODULE}; - use windows::Win32::Graphics::Direct3D::D3D_DRIVER_TYPE_WARP; - use windows::Win32::Graphics::Direct3D11::{ - D3D11_CPU_ACCESS_READ, D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_MAP_READ, - D3D11_MAPPED_SUBRESOURCE, D3D11_SDK_VERSION, D3D11_SUBRESOURCE_DATA, D3D11_TEXTURE2D_DESC, - D3D11_USAGE_DEFAULT, D3D11_USAGE_STAGING, D3D11CreateDevice, ID3D11Device, ID3D11Device1, - ID3D11Texture2D, - }; - use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_SAMPLE_DESC}; - use windows::core::Interface; - - let (w, h) = (256u32, 144u32); - let mut device: Option = None; - unsafe { - D3D11CreateDevice( - None, - D3D_DRIVER_TYPE_WARP, - HMODULE::default(), - D3D11_CREATE_DEVICE_BGRA_SUPPORT, - None, - D3D11_SDK_VERSION, - Some(&mut device), - None, - None, - ) - .expect("WARP device"); - } - let device = device.expect("device"); - let context = unsafe { device.GetImmediateContext() }.expect("context"); - let desc = |usage, cpu: u32, bind: u32| D3D11_TEXTURE2D_DESC { - Width: w, - Height: h, - MipLevels: 1, - ArraySize: 1, - Format: DXGI_FORMAT_B8G8R8A8_UNORM, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Usage: usage, - BindFlags: bind, - CPUAccessFlags: cpu, - MiscFlags: 0, - }; - let mut pool = D3d11Pool::new(&device).expect("pool"); - let mut ids = Vec::new(); - for round in 0..6u32 { - let pixels: Vec = (0..w * h * 4).map(|i| (i * 7 + round * 13) as u8).collect(); - let init = D3D11_SUBRESOURCE_DATA { - pSysMem: pixels.as_ptr().cast(), - SysMemPitch: w * 4, - SysMemSlicePitch: 0, - }; - let mut src: Option = None; - unsafe { - device - .CreateTexture2D(&desc(D3D11_USAGE_DEFAULT, 0, 8), Some(&init), Some(&mut src)) - .expect("source texture"); - } - let src = src.expect("source"); - let frame = pool.submit(&src).expect("submit"); - ids.push(frame.id); - let dev1: ID3D11Device1 = device.cast().expect("ID3D11Device1"); - let opened: ID3D11Texture2D = - unsafe { dev1.OpenSharedResource1(HANDLE(frame.handle.as_raw_handle())) } - .expect("OpenSharedResource1"); - let mut staging: Option = None; - unsafe { - device - .CreateTexture2D( - &desc(D3D11_USAGE_STAGING, D3D11_CPU_ACCESS_READ.0 as u32, 0), - None, - Some(&mut staging), - ) - .expect("staging"); - } - let staging = staging.expect("staging"); - let mut got = vec![0u8; pixels.len()]; - unsafe { - context.CopyResource(&staging, &opened); - let mut map = D3D11_MAPPED_SUBRESOURCE::default(); - context.Map(&staging, 0, D3D11_MAP_READ, 0, Some(&mut map)).expect("map"); - for y in 0..h as usize { - let row = std::slice::from_raw_parts( - map.pData.cast::().add(y * map.RowPitch as usize), - w as usize * 4, - ); - got[y * w as usize * 4..][..w as usize * 4].copy_from_slice(row); - } - context.Unmap(&staging, 0); - } - println!( - "round {round} id {} {}x{} bgr {} {}", - frame.id, - frame.width, - frame.height, - frame.bgr, - if got == pixels { "identical" } else { "DIFFERS" } - ); - } - println!("ids {ids:?}"); - match vk_video_ffi::Gpu::open() { - Ok(gpu) => println!("vulkan: importable bgr {}", vk_video_ffi::d3d11_importable(&gpu, true)), - Err(e) => println!("vulkan: {e}"), - } -} - -#[cfg(not(windows))] -fn main() {} diff --git a/shims/vk-video-ffi/examples/dmabuf_smoke.rs b/shims/vk-video-ffi/examples/dmabuf_smoke.rs deleted file mode 100644 index 1f303cc0..00000000 --- a/shims/vk-video-ffi/examples/dmabuf_smoke.rs +++ /dev/null @@ -1,767 +0,0 @@ -use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd}; - -use vk_video_ffi::{ - Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref, DmaBuf, DmaBufFormat, DmaBufPlane, - Error, Gpu, H264EncodeConfig, H264EncodeSession, H264Picture, H264Ref, H265EncodeConfig, - H265EncodeSession, H265Picture, H265Ref, H264Profile, RateControl, -}; -use vulkanalia::prelude::v1_3::*; -use vulkanalia::vk::KhrExternalMemoryFdExtensionDeviceCommands; - -const W: u32 = 1280; -const H: u32 = 720; -const FRAMES: usize = 10; -const FPS: (u32, u32) = (30, 1); -const RATE: RateControl = RateControl::ConstantQp { qp: 28 }; -const FORMAT: vk::Format = vk::Format::B8G8R8A8_UNORM; -const NV12: vk::Format = vk::Format::G8_B8R8_2PLANE_420_UNORM; -const P010: vk::Format = vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16; - -struct Export { - image: vk::Image, - memory: vk::DeviceMemory, - fd: OwnedFd, - modifier: u64, - planes: Vec, -} - -impl Export { - fn destroy(&self, d: &Device) { - unsafe { - d.destroy_image(self.image, None); - d.free_memory(self.memory, None); - } - } -} - -struct Pattern { - bits: u8, - y: Vec, - uv: Vec, -} - -impl Pattern { - fn new(bits: u8) -> Self { - let max = (1u32 << bits) - 1; - let y = (0..W * H) - .map(|i| { - let (x, row) = (i % W, i / W); - ((x * max / (W - 1) + row * max / (H - 1)) / 2) as u16 - }) - .collect(); - let uv = (0..W * H / 2) - .map(|i| ((i * 7) % (max + 1)) as u16) - .collect(); - Pattern { bits, y, uv } - } - - fn y8(&self) -> Vec { - self.y.iter().map(|&v| v as u8).collect() - } - - fn uv8(&self) -> Vec { - self.uv.iter().map(|&v| v as u8).collect() - } - - fn device(&self) -> Vec { - let samples = self.y.iter().chain(&self.uv); - if self.bits == 8 { - samples.map(|&v| v as u8).collect() - } else { - samples.flat_map(|&v| (v << 6).to_le_bytes()).collect() - } - } -} - -trait Encode: Sized { - fn open(gpu: &Gpu, size: (u32, u32), bits: u8) -> Result; - fn rgb(&mut self, host: &[u8], frame: usize) -> Result, Error>; - fn planar(&mut self, pattern: &Pattern, frame: usize) -> Result, Error>; - fn dma(&mut self, src: &DmaBuf, frame: usize) -> Result, Error>; -} - -impl Encode for H264EncodeSession { - fn open(gpu: &Gpu, size: (u32, u32), _bits: u8) -> Result { - let cfg = H264EncodeConfig { - width: size.0, - height: size.1, - fps: FPS, - rate: RATE, - profile: H264Profile::High, - level: 62, - colour: None, - quality: 0, - }; - H264EncodeSession::new(gpu, &cfg) - } - - fn rgb(&mut self, host: &[u8], i: usize) -> Result, Error> { - let pic = h264_picture(i); - self.encode_rgb(host, W, H, W * 4, true, &pic) - } - - fn planar(&mut self, pattern: &Pattern, i: usize) -> Result, Error> { - self.encode(&pattern.y8(), &pattern.uv8(), &h264_picture(i)) - } - - fn dma(&mut self, src: &DmaBuf, i: usize) -> Result, Error> { - self.encode_dmabuf(src, &h264_picture(i)) - } -} - -fn h264_picture(i: usize) -> H264Picture { - H264Picture { - idr: i == 0, - idr_pic_id: 0, - frame_num: i as u32, - poc: 2 * i as i32, - slot: (i % 2) as u32, - reference: (i > 0).then(|| H264Ref { - slot: ((i - 1) % 2) as u32, - frame_num: (i - 1) as u32, - poc: 2 * (i - 1) as i32, - }), - } -} - -impl Encode for H265EncodeSession { - fn open(gpu: &Gpu, size: (u32, u32), bits: u8) -> Result { - let cfg = H265EncodeConfig { - width: size.0, - height: size.1, - fps: FPS, - rate: RATE, - bit_depth: bits, - level: 186, - colour: None, - quality: 0, - }; - H265EncodeSession::new(gpu, &cfg) - } - - fn rgb(&mut self, host: &[u8], i: usize) -> Result, Error> { - let pic = h265_picture(i); - self.encode_rgb(host, W, H, W * 4, true, &pic) - } - - fn planar(&mut self, p: &Pattern, i: usize) -> Result, Error> { - let pic = h265_picture(i); - if p.bits == 8 { - self.encode(&p.y8(), &p.uv8(), &pic) - } else { - self.encode_16(&p.y, &p.uv, &pic) - } - } - - fn dma(&mut self, src: &DmaBuf, i: usize) -> Result, Error> { - self.encode_dmabuf(src, &h265_picture(i)) - } -} - -fn h265_picture(i: usize) -> H265Picture { - H265Picture { - idr: i == 0, - poc: 2 * i as i32, - slot: (i % 2) as u32, - reference: (i > 0).then(|| H265Ref { - slot: ((i - 1) % 2) as u32, - poc: 2 * (i - 1) as i32, - }), - keep: [None; vk_video_ffi::DPB_SLOTS], - } -} - -impl Encode for Av1EncodeSession { - fn open(gpu: &Gpu, size: (u32, u32), bits: u8) -> Result { - let cfg = Av1EncodeConfig { - width: size.0, - height: size.1, - fps: FPS, - rate: RATE, - bit_depth: bits, - level: 23, - colour: None, - quality: 0, - }; - Av1EncodeSession::new(gpu, &cfg) - } - - fn rgb(&mut self, host: &[u8], i: usize) -> Result, Error> { - let pic = av1_picture(i); - self.encode_rgb(host, W, H, W * 4, true, &pic) - } - - fn planar(&mut self, p: &Pattern, i: usize) -> Result, Error> { - let pic = av1_picture(i); - if p.bits == 8 { - self.encode(&p.y8(), &p.uv8(), &pic) - } else { - self.encode_16(&p.y, &p.uv, &pic) - } - } - - fn dma(&mut self, src: &DmaBuf, i: usize) -> Result, Error> { - self.encode_dmabuf(src, &av1_picture(i)) - } -} - -fn av1_picture(i: usize) -> Av1Picture { - Av1Picture { - key: i == 0, - order_hint: i as u8, - slot: (i % 2) as u32, - reference: (i > 0).then(|| Av1Ref { - slot: ((i - 1) % 2) as u32, - order_hint: (i - 1) as u8, - }), - } -} - -fn gradient() -> Vec { - let mut out = Vec::with_capacity((W * H * 4) as usize); - for y in 0..H { - for x in 0..W { - out.extend([ - (x * 255 / (W - 1)) as u8, - (y * 255 / (H - 1)) as u8, - (x ^ y) as u8, - 255, - ]); - } - } - out -} - -fn memory_index( - instance: &Instance, - physical: vk::PhysicalDevice, - bits: u32, - flags: vk::MemoryPropertyFlags, -) -> u32 { - let props = unsafe { instance.get_physical_device_memory_properties(physical) }; - (0..props.memory_type_count) - .find(|&i| { - bits & (1 << i) != 0 - && props.memory_types[i as usize] - .property_flags - .contains(flags) - }) - .expect("memory type") -} - -fn pick_modifier( - instance: &Instance, - physical: vk::PhysicalDevice, - format: vk::Format, - planes: u32, -) -> Option { - let mut list = vk::DrmFormatModifierPropertiesListEXT::builder().build(); - let mut props = vk::FormatProperties2::builder() - .push_next(&mut list) - .build(); - unsafe { instance.get_physical_device_format_properties2(physical, format, &mut props) }; - let count = list.drm_format_modifier_count as usize; - - let mut entries: Vec = (0..count) - .map(|_| vk::DrmFormatModifierPropertiesEXT::builder().build()) - .collect(); - let mut list = vk::DrmFormatModifierPropertiesListEXT::builder() - .drm_format_modifier_properties(&mut entries) - .build(); - let mut props = vk::FormatProperties2::builder() - .push_next(&mut list) - .build(); - unsafe { instance.get_physical_device_format_properties2(physical, format, &mut props) }; - - let want = vk::FormatFeatureFlags::TRANSFER_SRC | vk::FormatFeatureFlags::TRANSFER_DST; - entries - .iter() - .find(|e| { - e.drm_format_modifier != 0 - && e.drm_format_modifier_plane_count == planes - && e.drm_format_modifier_tiling_features.contains(want) - }) - .map(|e| e.drm_format_modifier) -} - -fn export( - instance: &Instance, - physical: vk::PhysicalDevice, - d: &Device, - queue: vk::Queue, - family: u32, - format: vk::Format, - modifier: u64, - host: &[u8], - regions: &[(vk::ImageAspectFlags, u64, u32, u32)], - memory_planes: usize, -) -> Export { - let modifiers = [modifier]; - let mut list = vk::ImageDrmFormatModifierListCreateInfoEXT::builder() - .drm_format_modifiers(&modifiers) - .build(); - let mut external = vk::ExternalMemoryImageCreateInfo::builder() - .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT) - .build(); - let info = vk::ImageCreateInfo::builder() - .image_type(vk::ImageType::_2D) - .format(format) - .extent(vk::Extent3D { - width: W, - height: H, - depth: 1, - }) - .mip_levels(1) - .array_layers(1) - .samples(vk::SampleCountFlags::_1) - .tiling(vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT) - .usage(vk::ImageUsageFlags::TRANSFER_SRC | vk::ImageUsageFlags::TRANSFER_DST) - .sharing_mode(vk::SharingMode::EXCLUSIVE) - .initial_layout(vk::ImageLayout::UNDEFINED) - .push_next(&mut external) - .push_next(&mut list) - .build(); - let image = unsafe { d.create_image(&info, None) }.expect("export image"); - - let req = unsafe { d.get_image_memory_requirements(image) }; - let index = memory_index( - instance, - physical, - req.memory_type_bits, - vk::MemoryPropertyFlags::DEVICE_LOCAL, - ); - let mut export_info = vk::ExportMemoryAllocateInfo::builder() - .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT) - .build(); - let mut dedicated = vk::MemoryDedicatedAllocateInfo::builder() - .image(image) - .build(); - let alloc = vk::MemoryAllocateInfo::builder() - .allocation_size(req.size) - .memory_type_index(index) - .push_next(&mut dedicated) - .push_next(&mut export_info) - .build(); - let memory = unsafe { d.allocate_memory(&alloc, None) }.expect("export memory"); - unsafe { d.bind_image_memory(image, memory, 0) }.expect("bind export memory"); - - let fd_info = vk::MemoryGetFdInfoKHR::builder() - .memory(memory) - .handle_type(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT) - .build(); - let fd = unsafe { d.get_memory_fd_khr(&fd_info) }.expect("export fd"); - let fd = unsafe { OwnedFd::from_raw_fd(fd) }; - let memory_aspects = [ - vk::ImageAspectFlags::MEMORY_PLANE_0_EXT, - vk::ImageAspectFlags::MEMORY_PLANE_1_EXT, - ]; - let planes = memory_aspects[..memory_planes] - .iter() - .map(|&aspect_mask| { - let sub = vk::ImageSubresource { - aspect_mask, - mip_level: 0, - array_layer: 0, - }; - let layout = unsafe { d.get_image_subresource_layout(image, &sub) }; - DmaBufPlane { - fd: 0, - offset: layout.offset as u32, - pitch: layout.row_pitch as u32, - } - }) - .collect(); - - let bytes = host.len() as u64; - let buf_info = vk::BufferCreateInfo::builder() - .size(bytes) - .usage(vk::BufferUsageFlags::TRANSFER_SRC) - .sharing_mode(vk::SharingMode::EXCLUSIVE); - let staging = unsafe { d.create_buffer(&buf_info, None) }.expect("staging buffer"); - let breq = unsafe { d.get_buffer_memory_requirements(staging) }; - let bindex = memory_index( - instance, - physical, - breq.memory_type_bits, - vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, - ); - let balloc = vk::MemoryAllocateInfo::builder() - .allocation_size(breq.size) - .memory_type_index(bindex) - .build(); - let bmem = unsafe { d.allocate_memory(&balloc, None) }.expect("staging memory"); - unsafe { - d.bind_buffer_memory(staging, bmem, 0) - .expect("bind staging"); - let ptr = d - .map_memory(bmem, 0, bytes, vk::MemoryMapFlags::empty()) - .expect("map staging") as *mut u8; - std::ptr::copy_nonoverlapping(host.as_ptr(), ptr, host.len()); - d.unmap_memory(bmem); - } - - let pool_info = vk::CommandPoolCreateInfo::builder().queue_family_index(family); - let pool = unsafe { d.create_command_pool(&pool_info, None) }.expect("pool"); - let alloc = vk::CommandBufferAllocateInfo::builder() - .command_pool(pool) - .level(vk::CommandBufferLevel::PRIMARY) - .command_buffer_count(1); - let cb = unsafe { d.allocate_command_buffers(&alloc) }.expect("command buffer")[0]; - let to_dst: Vec = regions - .iter() - .map(|&(aspect, ..)| { - vk::ImageMemoryBarrier::builder() - .old_layout(vk::ImageLayout::UNDEFINED) - .new_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL) - .src_access_mask(vk::AccessFlags::empty()) - .dst_access_mask(vk::AccessFlags::TRANSFER_WRITE) - .image(image) - .subresource_range(vk::ImageSubresourceRange { - aspect_mask: aspect, - base_mip_level: 0, - level_count: 1, - base_array_layer: 0, - layer_count: 1, - }) - .build() - }) - .collect(); - let copies: Vec = regions - .iter() - .map(|&(aspect, offset, width, height)| { - vk::BufferImageCopy::builder() - .buffer_offset(offset) - .image_subresource(vk::ImageSubresourceLayers { - aspect_mask: aspect, - mip_level: 0, - base_array_layer: 0, - layer_count: 1, - }) - .image_extent(vk::Extent3D { - width, - height, - depth: 1, - }) - .build() - }) - .collect(); - let begin = - vk::CommandBufferBeginInfo::builder().flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); - unsafe { - d.begin_command_buffer(cb, &begin).expect("begin"); - d.cmd_pipeline_barrier( - cb, - vk::PipelineStageFlags::TOP_OF_PIPE, - vk::PipelineStageFlags::TRANSFER, - vk::DependencyFlags::empty(), - &[] as &[vk::MemoryBarrier], - &[] as &[vk::BufferMemoryBarrier], - &to_dst, - ); - d.cmd_copy_buffer_to_image( - cb, - staging, - image, - vk::ImageLayout::TRANSFER_DST_OPTIMAL, - &copies, - ); - d.end_command_buffer(cb).expect("end"); - let cbs = [cb]; - let submit = vk::SubmitInfo::builder().command_buffers(&cbs).build(); - d.queue_submit(queue, &[submit], vk::Fence::null()) - .expect("submit"); - d.queue_wait_idle(queue).expect("wait"); - d.destroy_command_pool(pool, None); - d.destroy_buffer(staging, None); - d.free_memory(bmem, None); - } - - Export { - image, - memory, - fd, - modifier, - planes, - } -} - -fn export_planar( - instance: &Instance, - physical: vk::PhysicalDevice, - d: &Device, - queue: vk::Queue, - family: u32, - format: vk::Format, - modifier: u64, - pattern: &Pattern, -) -> Export { - let bps = if pattern.bits == 8 { 1 } else { 2 }; - let luma = (W * H * bps) as u64; - let regions = [ - (vk::ImageAspectFlags::PLANE_0, 0, W, H), - (vk::ImageAspectFlags::PLANE_1, luma, W / 2, H / 2), - ]; - export( - instance, - physical, - d, - queue, - family, - format, - modifier, - &pattern.device(), - ®ions, - 2, - ) -} - -fn run(gpu: &Gpu, name: &str, host: &[u8], linear: &Export, tiled: &Export) { - let modifiers = vk_video_ffi::rgb_import_modifiers(gpu, true); - println!( - "{name} bgrx import modifiers {modifiers:x?}, linear {} tiled {}", - modifiers.contains(&linear.modifier), - modifiers.contains(&tiled.modifier) - ); - let cases = [(linear, (W, H)), (tiled, (W, H)), (linear, (W / 2, H / 2))]; - for (export, size) in cases { - let mut a = S::open(gpu, size, 8).expect("encoder"); - let mut b = S::open(gpu, size, 8).expect("encoder"); - let owned = vk_video_ffi::dup_raw_fd(export.fd.as_raw_fd()).expect("dup"); - let fds = [owned.as_fd()]; - let src = DmaBuf { - fds: &fds, - planes: &export.planes, - width: W, - height: H, - modifier: export.modifier, - format: DmaBufFormat::Bgrx, - }; - let mut left = Vec::new(); - let mut right = Vec::new(); - for i in 0..FRAMES { - left.extend(a.rgb(host, i).expect("encode_rgb")); - right.extend(b.dma(&src, i).expect("encode_dmabuf")); - } - let verdict = if left == right { - "identical" - } else { - "DIFFERENT" - }; - println!( - "{name} {:#x} {}x{} {verdict}", - export.modifier, size.0, size.1 - ); - } -} - -fn planar_format(pattern: &Pattern) -> DmaBufFormat { - if pattern.bits == 8 { - DmaBufFormat::Nv12 - } else { - DmaBufFormat::P010 - } -} - -fn split_planes(a: &Export, b: &Export) -> [DmaBufPlane; 2] { - [ - DmaBufPlane { fd: 0, ..a.planes[0] }, - DmaBufPlane { fd: 1, ..b.planes[1] }, - ] -} - -fn run_split(gpu: &Gpu, name: &str, pattern: &Pattern, pairs: &[(Export, Export)]) { - let format = planar_format(pattern); - for (a_export, b_export) in pairs { - let mut a = S::open(gpu, (W, H), pattern.bits).expect("encoder"); - let mut b = S::open(gpu, (W, H), pattern.bits).expect("encoder"); - let fds = [a_export.fd.as_fd(), b_export.fd.as_fd()]; - let planes = split_planes(a_export, b_export); - let src = DmaBuf { - fds: &fds, - planes: &planes, - width: W, - height: H, - modifier: a_export.modifier, - format, - }; - let mut left = Vec::new(); - let mut right = Vec::new(); - for i in 0..FRAMES { - left.extend(a.planar(pattern, i).expect("encode")); - right.extend(b.dma(&src, i).expect("encode_dmabuf")); - } - let verdict = if left == right { - "identical" - } else { - "DIFFERENT" - }; - println!("{name} split {:#x} {W}x{H} {verdict}", a_export.modifier); - } -} - -fn run_planar(gpu: &Gpu, name: &str, pattern: &Pattern, exports: &[&Export]) { - let format = planar_format(pattern); - for export in exports { - let mut a = S::open(gpu, (W, H), pattern.bits).expect("encoder"); - let mut b = S::open(gpu, (W, H), pattern.bits).expect("encoder"); - let fds = [export.fd.as_fd()]; - let src = DmaBuf { - fds: &fds, - planes: &export.planes, - width: W, - height: H, - modifier: export.modifier, - format, - }; - let mut left = Vec::new(); - let mut right = Vec::new(); - for i in 0..FRAMES { - left.extend(a.planar(pattern, i).expect("encode")); - right.extend(b.dma(&src, i).expect("encode_dmabuf")); - } - let verdict = if left == right { - "identical" - } else { - "DIFFERENT" - }; - println!("{name} {:#x} {W}x{H} {verdict}", export.modifier); - } -} - -fn main() { - let gpu = Gpu::open().expect("open GPU"); - let (instance, physical, d) = gpu.vulkan(); - let family = unsafe { instance.get_physical_device_queue_family_properties(physical) } - .iter() - .position(|f| f.queue_flags.contains(vk::QueueFlags::GRAPHICS)) - .expect("graphics family") as u32; - let queue = unsafe { d.get_device_queue(family, 0) }; - let host = gradient(); - let rgb_regions = [(vk::ImageAspectFlags::COLOR, 0, W, H)]; - let linear = export( - instance, - physical, - d, - queue, - family, - FORMAT, - 0, - &host, - &rgb_regions, - 1, - ); - let modifier = - pick_modifier(instance, physical, FORMAT, 1).expect("tiled single-plane modifier"); - let tiled = export( - instance, - physical, - d, - queue, - family, - FORMAT, - modifier, - &host, - &rgb_regions, - 1, - ); - run::(&gpu, "h264", &host, &linear, &tiled); - run::(&gpu, "h265", &host, &linear, &tiled); - run::(&gpu, "av1", &host, &linear, &tiled); - - let nv12 = Pattern::new(8); - let p010 = Pattern::new(10); - let mut exports = vec![linear, tiled]; - let nv12_linear = export_planar(instance, physical, d, queue, family, NV12, 0, &nv12); - let nv12_tiled = pick_modifier(instance, physical, NV12, 2) - .map(|m| export_planar(instance, physical, d, queue, family, NV12, m, &nv12)); - let p010_linear = export_planar(instance, physical, d, queue, family, P010, 0, &p010); - let p010_tiled = pick_modifier(instance, physical, P010, 2) - .map(|m| export_planar(instance, physical, d, queue, family, P010, m, &p010)); - let nv12_set: Vec<&Export> = [Some(&nv12_linear), nv12_tiled.as_ref()] - .into_iter() - .flatten() - .collect(); - let p010_set: Vec<&Export> = [Some(&p010_linear), p010_tiled.as_ref()] - .into_iter() - .flatten() - .collect(); - run_planar::(&gpu, "h264 nv12", &nv12, &nv12_set); - run_planar::(&gpu, "h265 nv12", &nv12, &nv12_set); - run_planar::(&gpu, "h265 p010", &p010, &p010_set); - run_planar::(&gpu, "av1 nv12", &nv12, &nv12_set); - run_planar::(&gpu, "av1 p010", &p010, &p010_set); - - let pair = |format, pattern: &Pattern, modifier| { - ( - export_planar(instance, physical, d, queue, family, format, modifier, pattern), - export_planar(instance, physical, d, queue, family, format, modifier, pattern), - ) - }; - let nv12_pairs: Vec<(Export, Export)> = [Some(0), pick_modifier(instance, physical, NV12, 2)] - .into_iter() - .flatten() - .map(|m| pair(NV12, &nv12, m)) - .collect(); - let p010_pairs: Vec<(Export, Export)> = [Some(0), pick_modifier(instance, physical, P010, 2)] - .into_iter() - .flatten() - .map(|m| pair(P010, &p010, m)) - .collect(); - run_split::(&gpu, "h264 nv12", &nv12, &nv12_pairs); - run_split::(&gpu, "h265 nv12", &nv12, &nv12_pairs); - run_split::(&gpu, "h265 p010", &p010, &p010_pairs); - run_split::(&gpu, "av1 nv12", &nv12, &nv12_pairs); - run_split::(&gpu, "av1 p010", &p010, &p010_pairs); - - let mut split_cache = ::open(&gpu, (W, H), 8).expect("encoder"); - let (sa, sb) = &nv12_pairs[0]; - let fds = [sa.fd.as_fd(), sb.fd.as_fd()]; - let planes = split_planes(sa, sb); - let src = DmaBuf { - fds: &fds, - planes: &planes, - width: W, - height: H, - modifier: sa.modifier, - format: DmaBufFormat::Nv12, - }; - for pass in 1..=2 { - for i in 0..FRAMES { - split_cache.dma(&src, i).expect("encode_dmabuf"); - } - println!( - "cache h265 nv12 split pass {pass} {FRAMES} frames same fds imports {}", - split_cache.dmabuf_imports() - ); - } - - let mut cache = ::open(&gpu, (W, H), 8).expect("encoder"); - let fds = [nv12_linear.fd.as_fd()]; - let src = DmaBuf { - fds: &fds, - planes: &nv12_linear.planes, - width: W, - height: H, - modifier: nv12_linear.modifier, - format: DmaBufFormat::Nv12, - }; - for i in 0..FRAMES { - cache.dma(&src, i).expect("encode_dmabuf"); - } - println!( - "cache h265 nv12 {FRAMES} frames same fd imports {}", - cache.dmabuf_imports() - ); - - exports.extend(nv12_tiled); - exports.push(nv12_linear); - exports.extend(p010_tiled); - exports.push(p010_linear); - for e in &exports { - e.destroy(d); - } - for (a, b) in nv12_pairs.iter().chain(&p010_pairs) { - a.destroy(d); - b.destroy(d); - } -} diff --git a/shims/vk-video-ffi/examples/h264_decode_smoke.rs b/shims/vk-video-ffi/examples/h264_decode_smoke.rs deleted file mode 100644 index 939b1805..00000000 --- a/shims/vk-video-ffi/examples/h264_decode_smoke.rs +++ /dev/null @@ -1,182 +0,0 @@ -use std::fs; -use std::path::PathBuf; -use std::process::Command; - -use ec_h264_syntax::sps::{ZIGZAG_4X4, ZIGZAG_8X8}; -use ec_h264_syntax::{ - AnnexBIter, NalHeader, NalUnitType, Pps, SliceHeader, Sps, unescape_rbsp, -}; -use vk_video_ffi::{ - Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264Sps, ScalingLists, -}; - -fn zigzag(raster: &[u8], scan: &[u8]) -> Vec { - scan.iter().map(|&r| raster[r as usize]).collect() -} - -fn lists(l: &ec_h264_syntax::ScalingLists) -> ScalingLists { - let mut out = ScalingLists { - l4x4: [[0; 16]; 6], - l8x8: [[0; 64]; 6], - }; - for i in 0..6 { - out.l4x4[i].copy_from_slice(&zigzag(&l.list_4x4[i], &ZIGZAG_4X4)); - out.l8x8[i].copy_from_slice(&zigzag(&l.list_8x8[i], &ZIGZAG_8X8)); - } - out -} - -fn main() { - let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); - let stream = dir.join("idr.h264"); - let reference = dir.join("ref.yuv"); - let status = Command::new("ffmpeg") - .args(["-y", "-loglevel", "error", "-f", "lavfi", "-i"]) - .arg("testsrc2=size=320x240:rate=30") - .args(["-frames:v", "1", "-c:v", "libx264", "-profile:v", "main"]) - .args(["-bsf:v", "h264_mp4toannexb", "-f", "h264"]) - .arg(&stream) - .status() - .expect("run ffmpeg"); - assert!(status.success()); - let status = Command::new("ffmpeg") - .args(["-y", "-loglevel", "error", "-i"]) - .arg(&stream) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .arg(&reference) - .status() - .expect("run ffmpeg"); - assert!(status.success()); - - let data = fs::read(&stream).expect("read stream"); - let mut sps_list: Vec = Vec::new(); - let mut pps_list: Vec = Vec::new(); - let mut slices: Vec<&[u8]> = Vec::new(); - let mut slice_header = None; - let mut rbsp = Vec::new(); - for nal in AnnexBIter::new(&data) { - let header = NalHeader::parse(nal[0]).expect("NAL header"); - unescape_rbsp(&nal[1..], &mut rbsp); - match header.unit_type { - NalUnitType::Sps => sps_list.push(Sps::parse(&rbsp).expect("SPS")), - NalUnitType::Pps => { - let pps = Pps::parse(&rbsp, |id| sps_list.iter().find(|s| s.id == id)) - .expect("PPS"); - pps_list.push(pps); - } - NalUnitType::SliceIdr => { - let sps = &sps_list[0]; - let pps = &pps_list[0]; - let sh = SliceHeader::parse(&rbsp, header, sps, pps).expect("slice header"); - slice_header = Some(sh); - slices.push(nal); - } - _ => {} - } - } - let sps = &sps_list[0]; - let pps = &pps_list[0]; - let sh = slice_header.expect("IDR slice"); - - let unit_y = if sps.frame_mbs_only { 2 } else { 4 }; - let (left, right, top, bottom) = sps.crop; - let h264_sps = H264Sps { - id: sps.id, - profile_idc: sps.profile_idc, - level_idc: sps.level_idc, - chroma_format_idc: sps.chroma_format_idc, - bit_depth_luma_minus8: sps.bit_depth_luma - 8, - bit_depth_chroma_minus8: sps.bit_depth_chroma - 8, - log2_max_frame_num_minus4: sps.log2_max_frame_num - 4, - pic_order_cnt_type: sps.pic_order_cnt_type, - log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_pic_order_cnt_lsb - 4, - offset_for_non_ref_pic: sps.offset_for_non_ref_pic, - offset_for_top_to_bottom_field: sps.offset_for_top_to_bottom_field, - offset_for_ref_frame: sps.offsets_for_ref_frame.clone(), - max_num_ref_frames: sps.max_num_ref_frames as u8, - pic_width_in_mbs_minus1: sps.mb_width - 1, - pic_height_in_map_units_minus1: (if sps.frame_mbs_only { - sps.mb_height - } else { - sps.mb_height / 2 - }) - 1, - frame_mbs_only: sps.frame_mbs_only, - mb_adaptive_frame_field: sps.mb_adaptive_frame_field, - direct_8x8_inference: sps.direct_8x8_inference, - delta_pic_order_always_zero: sps.delta_pic_order_always_zero, - frame_crop_offsets: [left / 2, right / 2, top / unit_y, bottom / unit_y], - qpprime_y_zero_transform_bypass: sps.transform_bypass, - seq_scaling_matrix: sps.scaling_lists.as_ref().map(lists), - }; - let h264_pps = H264Pps { - id: pps.id as u8, - sps_id: pps.sps_id, - entropy_coding_mode: pps.entropy_coding_mode, - bottom_field_pic_order_in_frame_present: pps.bottom_field_pic_order_in_frame_present, - num_ref_idx_l0_default_active_minus1: (pps.num_ref_idx_l0_default_active - 1) as u8, - num_ref_idx_l1_default_active_minus1: (pps.num_ref_idx_l1_default_active - 1) as u8, - weighted_pred: pps.weighted_pred, - weighted_bipred_idc: pps.weighted_bipred_idc, - pic_init_qp_minus26: (pps.pic_init_qp - 26) as i8, - pic_init_qs_minus26: (pps.pic_init_qs - 26) as i8, - chroma_qp_index_offset: pps.chroma_qp_index_offset as i8, - second_chroma_qp_index_offset: pps.second_chroma_qp_index_offset as i8, - deblocking_filter_control_present: pps.deblocking_filter_control_present, - constrained_intra_pred: pps.constrained_intra_pred, - redundant_pic_cnt_present: pps.redundant_pic_cnt_present, - transform_8x8_mode: pps.transform_8x8_mode, - pic_scaling_matrix: pps.scaling_lists.as_ref().map(lists), - }; - - let (w, h) = (sps.width, sps.height); - let gpu = Gpu::open().expect("open GPU"); - println!("device: {}", gpu.device_name()); - let cfg = H264DecodeConfig { - max_width: sps.coded_width, - max_height: sps.coded_height, - max_dpb_slots: 2, - profile_idc: sps.profile_idc, - chroma_format_idc: sps.chroma_format_idc, - }; - let mut session = H264DecodeSession::new(&gpu, &cfg).expect("decode session"); - session - .set_parameters(std::slice::from_ref(&h264_sps), std::slice::from_ref(&h264_pps)) - .expect("parameters"); - let poc = if sps.pic_order_cnt_type == 0 { - sh.pic_order_cnt_lsb as i32 - } else { - 0 - }; - let pic = H264DecodePicture { - sps_id: sps.id, - pps_id: pps.id as u8, - idr: true, - reference: true, - frame_num: sh.frame_num as u16, - idr_pic_id: sh.idr_pic_id.unwrap_or(0) as u16, - poc: [poc, poc + sh.delta_pic_order_cnt_bottom], - setup_slot: 0, - refs: &[], - slices: &slices, - }; - session.decode(&pic).expect("decode"); - session.store_output(0, (0, 0, w, h)).expect("store"); - let (y, uv) = session.read_output(0, w, h).expect("read slot"); - - let mut pgm = format!("P5\n{w} {h}\n255\n").into_bytes(); - pgm.extend_from_slice(&y); - fs::write(dir.join("out.pgm"), &pgm).expect("write pgm"); - - let ref_data = fs::read(&reference).expect("read reference"); - let luma = (w * h) as usize; - let chroma = luma / 4; - let ref_y = &ref_data[..luma]; - let ref_u = &ref_data[luma..luma + chroma]; - let ref_v = &ref_data[luma + chroma..luma + 2 * chroma]; - let mad = |a: &[u8], b: &[u8]| { - a.iter().zip(b).map(|(&x, &y)| (x as f64 - y as f64).abs()).sum::() / a.len() as f64 - }; - let ref_uv: Vec = ref_u.iter().zip(ref_v).flat_map(|(&u, &v)| [u, v]).collect(); - println!("mean abs diff Y: {:.6}", mad(&y, ref_y)); - println!("mean abs diff UV: {:.6}", mad(&uv, &ref_uv)); -} diff --git a/shims/vk-video-ffi/examples/h265_decode_smoke.rs b/shims/vk-video-ffi/examples/h265_decode_smoke.rs deleted file mode 100644 index 53c7ff78..00000000 --- a/shims/vk-video-ffi/examples/h265_decode_smoke.rs +++ /dev/null @@ -1,284 +0,0 @@ -use std::fs; -use std::path::PathBuf; -use std::process::Command; - -use ec_h265_syntax::{ - NalUnitType, Pps, ProfileTierLevel, ScalingList, ShortTermRefPicSet, SliceHeader, Sps, Vps, - split_annex_b, -}; -use vk_video_ffi::{ - Gpu, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession, - H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265ScalingLists, - H265ShortTermRefPicSet, H265Sps, H265Vps, -}; - -fn ptl(p: &ProfileTierLevel) -> H265ProfileTierLevel { - H265ProfileTierLevel { - tier_flag: p.tier_flag, - progressive_source: p.progressive_source, - interlaced_source: p.interlaced_source, - non_packed_constraint: p.non_packed_constraint, - frame_only_constraint: p.frame_only_constraint, - profile_idc: p.profile_idc, - level_idc: p.level_idc, - } -} - -fn dpbm( - max_latency_increase_plus1: u32, - max_dec_pic_buffering_minus1: u32, - reorder: u32, -) -> H265DecPicBufMgr { - H265DecPicBufMgr { - max_latency_increase_plus1: [max_latency_increase_plus1; 7], - max_dec_pic_buffering_minus1: [max_dec_pic_buffering_minus1 as u8; 7], - max_num_reorder_pics: [reorder as u8; 7], - } -} - -fn lists(l: &ScalingList) -> H265ScalingLists { - let c = &l.coefficients; - H265ScalingLists { - list_4x4: std::array::from_fn(|i| c[0][i][..16].try_into().unwrap()), - list_8x8: std::array::from_fn(|i| c[1][i]), - list_16x16: std::array::from_fn(|i| c[2][i]), - list_32x32: std::array::from_fn(|i| c[3][3 * i]), - dc_16x16: std::array::from_fn(|i| l.dc[2][i]), - dc_32x32: std::array::from_fn(|i| l.dc[3][3 * i]), - } -} - -fn rps(r: &ShortTermRefPicSet) -> H265ShortTermRefPicSet { - let (n0, n1) = (r.num_negative as usize, r.num_positive as usize); - H265ShortTermRefPicSet { - delta_poc_s0: r.delta_poc_s0[..n0].to_vec(), - used_by_curr_pic_s0: r.used_s0[..n0].to_vec(), - delta_poc_s1: r.delta_poc_s1[..n1].to_vec(), - used_by_curr_pic_s1: r.used_s1[..n1].to_vec(), - } -} - -fn main() { - let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); - let stream = dir.join("idr.hevc"); - let reference = dir.join("ref.yuv"); - let status = Command::new("ffmpeg") - .args(["-y", "-loglevel", "error", "-f", "lavfi", "-i"]) - .arg("testsrc2=size=320x240:rate=30") - .args([ - "-frames:v", - "1", - "-c:v", - "libx265", - "-x265-params", - "log-level=error", - ]) - .args(["-f", "hevc"]) - .arg(&stream) - .status() - .expect("run ffmpeg"); - assert!(status.success()); - let status = Command::new("ffmpeg") - .args(["-y", "-loglevel", "error", "-i"]) - .arg(&stream) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .arg(&reference) - .status() - .expect("run ffmpeg"); - assert!(status.success()); - - let data = fs::read(&stream).expect("read stream"); - let nals = split_annex_b(&data); - let mut vps_list: Vec = Vec::new(); - let mut sps_list: Vec = Vec::new(); - let mut pps_list: Vec = Vec::new(); - let mut slice_nals: Vec> = Vec::new(); - for nal in &nals { - match nal.header.nal_type { - NalUnitType::Vps => vps_list.push(Vps::parse(&nal.rbsp()).expect("VPS")), - NalUnitType::Sps => sps_list.push(Sps::parse(&nal.rbsp()).expect("SPS")), - NalUnitType::Pps => pps_list.push(Pps::parse(&nal.rbsp()).expect("PPS")), - t if t.is_vcl() => { - let mut raw = nal.header.to_bytes().to_vec(); - raw.extend_from_slice(nal.payload); - slice_nals.push(raw); - } - _ => {} - } - } - let first = nals - .iter() - .find(|n| n.header.nal_type.is_vcl()) - .expect("slice"); - let vps = &vps_list[0]; - let pps = &pps_list[0]; - let sps = sps_list - .iter() - .find(|s| s.id == pps.sps_id) - .expect("SPS for PPS"); - let (sh, pos) = - SliceHeader::parse(&first.rbsp(), sps, pps, first.header.nal_type).expect("slice header"); - - let h265_vps = H265Vps { - id: vps.id, - max_sub_layers_minus1: 0, - profile_tier_level: ptl(&vps.ptl), - dec_pic_buf_mgr: dpbm( - 0, - vps.max_dec_pic_buffering_minus1, - vps.max_num_reorder_pics, - ), - }; - let c = &sps.conf_win; - let h265_sps = H265Sps { - id: sps.id as u8, - vps_id: sps.vps_id, - max_sub_layers_minus1: 0, - profile_tier_level: ptl(&sps.ptl), - chroma_format_idc: sps.chroma_format_idc as u8, - pic_width_in_luma_samples: sps.pic_width_in_luma_samples, - pic_height_in_luma_samples: sps.pic_height_in_luma_samples, - conformance_window: [c.left, c.right, c.top, c.bottom], - bit_depth_luma_minus8: sps.bit_depth_luma_minus8 as u8, - bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8 as u8, - log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_poc_lsb_minus4 as u8, - log2_min_luma_coding_block_size_minus3: sps.log2_min_cb_size_minus3 as u8, - log2_diff_max_min_luma_coding_block_size: sps.log2_diff_max_min_cb_size as u8, - log2_min_luma_transform_block_size_minus2: sps.log2_min_tb_size_minus2 as u8, - log2_diff_max_min_luma_transform_block_size: sps.log2_diff_max_min_tb_size as u8, - max_transform_hierarchy_depth_inter: sps.max_transform_hierarchy_depth_inter as u8, - max_transform_hierarchy_depth_intra: sps.max_transform_hierarchy_depth_intra as u8, - pcm: sps.pcm.map(|(a, b, c, d, e)| H265Pcm { - bit_depth_luma_minus1: a as u8, - bit_depth_chroma_minus1: b as u8, - log2_min_luma_coding_block_size_minus3: c as u8, - log2_diff_max_min_luma_coding_block_size: d as u8, - loop_filter_disabled: e, - }), - dec_pic_buf_mgr: dpbm( - sps.max_latency_increase_plus1, - sps.max_dec_pic_buffering_minus1, - sps.max_num_reorder_pics, - ), - scaling_list_enabled: sps.scaling_list_enabled, - scaling_lists: sps.scaling_list.as_ref().map(lists), - amp_enabled: sps.amp_enabled, - sample_adaptive_offset_enabled: sps.sao_enabled, - long_term_ref_pics_present: sps.long_term_ref_pics_present, - long_term_ref_pics_sps: sps - .long_term_ref_pics_sps - .iter() - .map(|&(poc_lsb, used_by_curr_pic)| H265LongTermRefPicSps { - poc_lsb, - used_by_curr_pic, - }) - .collect(), - temporal_mvp_enabled: sps.temporal_mvp_enabled, - strong_intra_smoothing_enabled: sps.strong_intra_smoothing, - short_term_ref_pic_sets: sps.short_term_ref_pic_sets.iter().map(rps).collect(), - }; - let h265_pps = H265Pps { - id: pps.id as u8, - sps_id: pps.sps_id as u8, - dependent_slice_segments_enabled: pps.dependent_slice_segments_enabled, - output_flag_present: pps.output_flag_present, - num_extra_slice_header_bits: pps.num_extra_slice_header_bits as u8, - sign_data_hiding_enabled: pps.sign_data_hiding_enabled, - cabac_init_present: pps.cabac_init_present, - num_ref_idx_l0_default_active_minus1: pps.num_ref_idx_l0_default_active_minus1 as u8, - num_ref_idx_l1_default_active_minus1: pps.num_ref_idx_l1_default_active_minus1 as u8, - init_qp_minus26: pps.init_qp_minus26 as i8, - constrained_intra_pred: pps.constrained_intra_pred, - transform_skip_enabled: pps.transform_skip_enabled, - cu_qp_delta_enabled: pps.cu_qp_delta_enabled, - diff_cu_qp_delta_depth: pps.diff_cu_qp_delta_depth as u8, - cb_qp_offset: pps.cb_qp_offset as i8, - cr_qp_offset: pps.cr_qp_offset as i8, - slice_chroma_qp_offsets_present: pps.slice_chroma_qp_offsets_present, - weighted_pred: pps.weighted_pred, - weighted_bipred: pps.weighted_bipred, - transquant_bypass_enabled: pps.transquant_bypass_enabled, - tiles_enabled: pps.tiles_enabled, - entropy_coding_sync_enabled: pps.entropy_coding_sync_enabled, - num_tile_columns_minus1: pps.num_tile_columns_minus1 as u8, - num_tile_rows_minus1: pps.num_tile_rows_minus1 as u8, - uniform_spacing: pps.uniform_spacing, - column_width_minus1: pps.column_width_minus1.iter().map(|&w| w as u16).collect(), - row_height_minus1: pps.row_height_minus1.iter().map(|&h| h as u16).collect(), - loop_filter_across_tiles_enabled: pps.loop_filter_across_tiles_enabled, - loop_filter_across_slices_enabled: pps.loop_filter_across_slices_enabled, - deblocking_filter_control_present: pps.deblocking_filter_control_present, - deblocking_filter_override_enabled: pps.deblocking_filter_override_enabled, - deblocking_filter_disabled: pps.deblocking_filter_disabled, - beta_offset_div2: pps.beta_offset_div2 as i8, - tc_offset_div2: pps.tc_offset_div2 as i8, - scaling_lists: pps.scaling_list.as_ref().map(lists), - lists_modification_present: pps.lists_modification_present, - log2_parallel_merge_level_minus2: pps.log2_parallel_merge_level_minus2 as u8, - slice_segment_header_extension_present: pps.slice_segment_header_extension_present, - }; - - let (w, h) = ( - h265_sps.pic_width_in_luma_samples, - h265_sps.pic_height_in_luma_samples, - ); - let gpu = Gpu::open().expect("open GPU"); - println!("device: {}", gpu.device_name()); - let cfg = H265DecodeConfig { - max_width: w, - max_height: h, - max_dpb_slots: 2, - bit_depth: 8, - }; - let mut session = H265DecodeSession::new(&gpu, &cfg).expect("decode session"); - session - .set_parameters( - std::slice::from_ref(&h265_vps), - std::slice::from_ref(&h265_sps), - std::slice::from_ref(&h265_pps), - ) - .expect("parameters"); - let slices: Vec<&[u8]> = slice_nals.iter().map(|v| v.as_slice()).collect(); - let pic = H265DecodePicture { - vps_id: sps.vps_id, - sps_id: sps.id as u8, - pps_id: pps.id as u8, - irap: first.header.nal_type.is_irap(), - idr: first.header.nal_type.is_idr(), - reference: true, - poc: 0, - setup_slot: 0, - short_term_ref_pic_set_sps: sh.short_term_ref_pic_set_sps_flag, - num_delta_pocs_of_ref_rps_idx: 0, - st_rps_bits: pos.st_rps_bits, - st_curr_before: &[], - st_curr_after: &[], - lt_curr: &[], - refs: &[], - slices: &slices, - }; - session.decode(&pic).expect("decode"); - session.store_output(0, (0, 0, w, h)).expect("store"); - let (y, uv) = session.read_output(0, w, h).expect("read slot"); - - let ref_data = fs::read(&reference).expect("read reference"); - let luma = (w * h) as usize; - let chroma = luma / 4; - let ref_y = &ref_data[..luma]; - let ref_u = &ref_data[luma..luma + chroma]; - let ref_v = &ref_data[luma + chroma..luma + 2 * chroma]; - let mad = |a: &[u8], b: &[u8]| { - a.iter() - .zip(b) - .map(|(&x, &y)| (x as f64 - y as f64).abs()) - .sum::() - / a.len() as f64 - }; - let ref_uv: Vec = ref_u - .iter() - .zip(ref_v) - .flat_map(|(&u, &v)| [u, v]) - .collect(); - println!("mean abs diff Y: {:.6}", mad(&y, ref_y)); - println!("mean abs diff UV: {:.6}", mad(&uv, &ref_uv)); -} diff --git a/shims/vk-video-ffi/src/av1_encode.rs b/shims/vk-video-ffi/src/av1_encode.rs index 297d0eb7..395db36a 100644 --- a/shims/vk-video-ffi/src/av1_encode.rs +++ b/shims/vk-video-ffi/src/av1_encode.rs @@ -302,25 +302,6 @@ impl Av1EncodeSession { self.encode_uploaded(pic) } - /// Encodes one picture from a shared D3D11 texture synchronously and returns its coded bytes. - #[cfg(windows)] - pub fn encode_d3d11(&mut self, src: &crate::D3d11Texture<'_>, pic: &Av1Picture) -> Result, Error> { - self.submit_d3d11(src, pic)?; - self.enc.flush_last() - } - - /// Number of D3D11 texture imports made so far; a texture re-used by id is imported once. - #[cfg(windows)] - pub fn d3d11_imports(&self) -> usize { - self.enc.import_count() - } - - /// Number of DMA-BUF imports made so far; a buffer re-used by fd is imported once. - #[cfg(target_os = "linux")] - pub fn dmabuf_imports(&self) -> usize { - self.enc.import_count() - } - fn encode_uploaded(&mut self, pic: &Av1Picture) -> Result>, Error> { let extent = self.enc.extent; @@ -460,39 +441,6 @@ impl Av1EncodeSession { Ok(out) } - /// Encodes one picture synchronously and returns its coded bytes. - pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &Av1Picture) -> Result, Error> { - self.submit(y, uv, pic)?; - self.enc.flush_last() - } - - /// Encodes one picture synchronously and returns its coded bytes. - pub fn encode_16(&mut self, y: &[u16], uv: &[u16], pic: &Av1Picture) -> Result, Error> { - self.submit_16(y, uv, pic)?; - self.enc.flush_last() - } - - /// Encodes one picture synchronously and returns its coded bytes. - pub fn encode_rgb( - &mut self, - rgb: &[u8], - src_width: u32, - src_height: u32, - stride_bytes: u32, - bgr: bool, - pic: &Av1Picture, - ) -> Result, Error> { - self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?; - self.enc.flush_last() - } - - #[cfg(target_os = "linux")] - /// Encodes one picture synchronously and returns its coded bytes. - pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &Av1Picture) -> Result, Error> { - self.submit_dmabuf(src, pic)?; - self.enc.flush_last() - } - /// Waits for queued pictures and returns their coded bytes in order. pub fn flush(&mut self) -> Result>, Error> { self.enc.flush() diff --git a/shims/vk-video-ffi/src/d3d11.rs b/shims/vk-video-ffi/src/d3d11.rs index 10a5ae41..c43d55fa 100644 --- a/shims/vk-video-ffi/src/d3d11.rs +++ b/shims/vk-video-ffi/src/d3d11.rs @@ -194,7 +194,6 @@ fn import_memory( pub(crate) struct ImportCache { entries: Vec<(Key, Import)>, next_id: u64, - pub(crate) count: usize, } impl ImportCache { @@ -224,7 +223,6 @@ impl ImportCache { } self.next_id += 1; let import = Import::new(gpu, src, self.next_id)?; - self.count += 1; self.entries.push((key, import)); } } diff --git a/shims/vk-video-ffi/src/dmabuf.rs b/shims/vk-video-ffi/src/dmabuf.rs index 94238866..016b64d7 100644 --- a/shims/vk-video-ffi/src/dmabuf.rs +++ b/shims/vk-video-ffi/src/dmabuf.rs @@ -388,7 +388,6 @@ fn device_memory(gpu: &Gpu, image: vk::Image) -> Result pub(crate) struct ImportCache { entries: Vec<(Key, Import)>, next_id: u64, - pub(crate) count: usize, } impl ImportCache { @@ -417,7 +416,6 @@ impl ImportCache { } self.next_id += 1; let import = Import::new(gpu, src, self.next_id)?; - self.count += 1; self.entries.push((key, import)); } } diff --git a/shims/vk-video-ffi/src/h264_encode.rs b/shims/vk-video-ffi/src/h264_encode.rs index 32247751..c89f08a9 100644 --- a/shims/vk-video-ffi/src/h264_encode.rs +++ b/shims/vk-video-ffi/src/h264_encode.rs @@ -399,25 +399,6 @@ impl H264EncodeSession { self.encode_uploaded(pic) } - /// Encodes one picture from a shared D3D11 texture synchronously and returns its coded bytes. - #[cfg(windows)] - pub fn encode_d3d11(&mut self, src: &crate::D3d11Texture<'_>, pic: &H264Picture) -> Result, Error> { - self.submit_d3d11(src, pic)?; - self.enc.flush_last() - } - - /// Number of D3D11 texture imports made so far; a texture re-used by id is imported once. - #[cfg(windows)] - pub fn d3d11_imports(&self) -> usize { - self.enc.import_count() - } - - /// Number of DMA-BUF imports made so far; a buffer re-used by fd is imported once. - #[cfg(target_os = "linux")] - pub fn dmabuf_imports(&self) -> usize { - self.enc.import_count() - } - fn encode_uploaded(&mut self, pic: &H264Picture) -> Result>, Error> { let extent = self.enc.extent; @@ -550,33 +531,6 @@ impl H264EncodeSession { .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode) } - /// Encodes one picture synchronously and returns its coded bytes. - pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &H264Picture) -> Result, Error> { - self.submit(y, uv, pic)?; - self.enc.flush_last() - } - - /// Encodes one picture synchronously and returns its coded bytes. - pub fn encode_rgb( - &mut self, - rgb: &[u8], - src_width: u32, - src_height: u32, - stride_bytes: u32, - bgr: bool, - pic: &H264Picture, - ) -> Result, Error> { - self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?; - self.enc.flush_last() - } - - #[cfg(target_os = "linux")] - /// Encodes one picture synchronously and returns its coded bytes. - pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H264Picture) -> Result, Error> { - self.submit_dmabuf(src, pic)?; - self.enc.flush_last() - } - /// Waits for queued pictures and returns their coded bytes in order. pub fn flush(&mut self) -> Result>, Error> { self.enc.flush() diff --git a/shims/vk-video-ffi/src/h265_encode.rs b/shims/vk-video-ffi/src/h265_encode.rs index ff2b34de..4a9e1b96 100644 --- a/shims/vk-video-ffi/src/h265_encode.rs +++ b/shims/vk-video-ffi/src/h265_encode.rs @@ -344,25 +344,6 @@ impl H265EncodeSession { self.encode_uploaded(pic) } - /// Encodes one picture from a shared D3D11 texture synchronously and returns its coded bytes. - #[cfg(windows)] - pub fn encode_d3d11(&mut self, src: &crate::D3d11Texture<'_>, pic: &H265Picture) -> Result, Error> { - self.submit_d3d11(src, pic)?; - self.enc.flush_last() - } - - /// Number of D3D11 texture imports made so far; a texture re-used by id is imported once. - #[cfg(windows)] - pub fn d3d11_imports(&self) -> usize { - self.enc.import_count() - } - - /// Number of DMA-BUF imports made so far; a buffer re-used by fd is imported once. - #[cfg(target_os = "linux")] - pub fn dmabuf_imports(&self) -> usize { - self.enc.import_count() - } - fn encode_uploaded(&mut self, pic: &H265Picture) -> Result>, Error> { let extent = self.enc.extent; @@ -474,39 +455,6 @@ impl H265EncodeSession { .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode) } - /// Encodes one picture synchronously and returns its coded bytes. - pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &H265Picture) -> Result, Error> { - self.submit(y, uv, pic)?; - self.enc.flush_last() - } - - /// Encodes one picture synchronously and returns its coded bytes. - pub fn encode_16(&mut self, y: &[u16], uv: &[u16], pic: &H265Picture) -> Result, Error> { - self.submit_16(y, uv, pic)?; - self.enc.flush_last() - } - - /// Encodes one picture synchronously and returns its coded bytes. - pub fn encode_rgb( - &mut self, - rgb: &[u8], - src_width: u32, - src_height: u32, - stride_bytes: u32, - bgr: bool, - pic: &H265Picture, - ) -> Result, Error> { - self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?; - self.enc.flush_last() - } - - #[cfg(target_os = "linux")] - /// Encodes one picture synchronously and returns its coded bytes. - pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H265Picture) -> Result, Error> { - self.submit_dmabuf(src, pic)?; - self.enc.flush_last() - } - /// Waits for queued pictures and returns their coded bytes in order. pub fn flush(&mut self) -> Result>, Error> { self.enc.flush() diff --git a/shims/vk-video-ffi/src/session.rs b/shims/vk-video-ffi/src/session.rs index a3693bc2..5b12ad48 100644 --- a/shims/vk-video-ffi/src/session.rs +++ b/shims/vk-video-ffi/src/session.rs @@ -1356,11 +1356,6 @@ impl Encoder { slot.upload.submit_with(&[], &[slot.ready]) } - #[cfg(any(target_os = "linux", windows))] - pub(crate) fn import_count(&self) -> usize { - self.imports.count - } - /// Records the encode of the uploaded slot and submits it without waiting. Returns the oldest picture once FLIGHT are queued. pub(crate) fn submit( &mut self, @@ -1449,13 +1444,6 @@ impl Encoder { Ok(out) } - /// Flushes and returns the last picture, for synchronous use where one picture is queued per call. - pub(crate) fn flush_last(&mut self) -> Result, Error> { - self.flush()? - .pop() - .ok_or_else(|| Error::Invalid("no picture encoded".into())) - } - fn finish(&mut self, k: usize) -> Result, Error> { let slot = &self.slots[k]; slot.main.wait()?;