### decode_with Example Usage Source: https://docs.rs/zenavif/latest/zenavif/fn.decode_with.html Example of how to use the decode_with function to decode an AVIF image. ```APIDOC ```rust use zenavif::{decode_with, DecoderConfig}; use enough::Unstoppable; let config = DecoderConfig::new().threads(4); let avif_data = std::fs::read("image.avif").unwrap(); let image = decode_with(&avif_data, &config, &Unstoppable).unwrap(); ``` ``` -------------------------------- ### Error Integration Example Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/enum.StopReason.html Example demonstrating how to integrate StopReason with custom error types using `From`. ```APIDOC ## §Error Integration Implement `From` for your error type to use `?` naturally: ```rust use enough::StopReason; #[derive(Debug)] enum MyError { Stopped(StopReason), Io(std::io::Error), } impl From for MyError { fn from(r: StopReason) -> Self { MyError::Stopped(r) } } ``` ``` -------------------------------- ### Unstoppable Usage Example Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.Unstoppable.html Demonstrates how to use the Unstoppable struct when cancellation is not needed. ```APIDOC ```rust use enough::{Stop, Unstoppable}; fn process(data: &[u8], stop: impl Stop) -> Vec { // ... implementation details ... unimplemented!("process function not fully implemented"); } // Example of calling process with Unstoppable let data = [1u8, 2, 3]; let result = process(&data, Unstoppable); ``` ``` -------------------------------- ### Example Implementation of Stop Trait Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/trait.Stop.html An example demonstrating how to implement the Stop trait for a custom cancellation source. ```APIDOC ## §Example Implementation ```rust use enough::{Stop, StopReason}; use core::sync::atomic::{AtomicBool, Ordering}; pub struct MyStop<'a> { cancelled: &'a AtomicBool, } impl Stop for MyStop<'_> { fn check(&self) -> Result<(), StopReason> { if self.cancelled.load(Ordering::Relaxed) { Err(StopReason::Cancelled) } else { Ok(()) } } } ``` ``` -------------------------------- ### Example Usage Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifDepthMap.html Demonstrates how to parse an AVIF file and extract the depth map using the zenavif_parse library. ```APIDOC ## §Example ```rust let bytes = std::fs::read("portrait.avif").unwrap(); let parser = zenavif_parse::AvifParser::from_bytes(&bytes).unwrap(); if let Some(Ok(dm)) = parser.depth_map() { println!("Depth map: {}x{}, {} bytes AV1 data", dm.width, dm.height, dm.data.len()); } ``` ``` -------------------------------- ### Get grid configuration Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Retrieves the grid configuration if the AVIF file is a grid image. ```rust pub fn grid_config(&self) -> Option<&GridConfig> ``` -------------------------------- ### Example Usage of Unstoppable Source: https://docs.rs/zenavif/latest/zenavif/struct.Unstoppable.html Demonstrates how to use the Unstoppable struct as a Stop implementation when cancellation is not needed. ```APIDOC ```rust use enough::{Stop, Unstoppable}; fn process(data: &[u8], stop: impl Stop) -> Vec { // ... } // Caller doesn't need cancellation let data = [1u8, 2, 3]; let result = process(&data, Unstoppable); ``` ``` -------------------------------- ### Premultiplied Alpha Calculation Example Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/c_api/struct.avif_data_t.html Illustrates how to adjust RGB values when the alpha channel is premultiplied. This calculation is necessary when premultiplied_alpha is set to 1. ```c if (a != 0) {r = r * 255 / a} ``` -------------------------------- ### Create a new DecoderConfig with default settings Source: https://docs.rs/zenavif/latest/zenavif/struct.DecoderConfig.html Use this function to initialize a DecoderConfig with all default values. This is the starting point for customizing decoding parameters. ```rust pub fn new() -> Self ``` -------------------------------- ### Example: Accessing Depth Map Information Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Demonstrates how to read an AVIF file, parse it using AvifParser, and access depth map information if available. It prints the dimensions and data size of the depth map. ```rust let bytes = std::fs::read("portrait.avif").unwrap(); let parser = zenavif_parse::AvifParser::from_bytes(&bytes).unwrap(); if let Some(Ok(dm)) = parser.depth_map() { println!("Depth: {}x{}, {} bytes", dm.width, dm.height, dm.data.len()); } ``` -------------------------------- ### AvifParser::compatible_brands Source: https://docs.rs/zenavif-parse/0.6.2/src/zenavif_parse/lib.rs.html Gets the compatible brands from the 'ftyp' box of the AVIF file. ```APIDOC ## AvifParser::compatible_brands ### Description Gets the compatible brands from the 'ftyp' box of the AVIF file. These indicate other formats the file can be compatible with. ### Method Signature `pub fn compatible_brands(&self) -> &[[u8; 4]]` ### Returns A slice of 4-byte arrays, each representing a compatible brand. ``` -------------------------------- ### Example Usage of Unstoppable Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.Unstoppable.html Demonstrates how to use the Unstoppable struct with a function that accepts a Stop trait object when cancellation is not needed. ```rust use enough::{Stop, Unstoppable}; fn process(data: &[u8], stop: impl Stop) -> Vec { // ... } // Caller doesn't need cancellation let data = [1u8, 2, 3]; let result = process(&data, Unstoppable); ``` -------------------------------- ### Get Compatible Brands - AvifParser Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Retrieves the compatible brands from the `ftyp` box of the AVIF file. These indicate other formats or specifications that the file is compatible with. ```rust pub fn compatible_brands(&self) -> &[[u8; 4]] ``` -------------------------------- ### Get Matrix Coefficients Source: https://docs.rs/zenavif/latest/src/zenavif/yuv_convert.rs.html Retrieves the Kr and Kb coefficients for YUV to RGB conversion based on the specified YuvMatrix standard (Bt601, Bt709, Bt2020). These coefficients are used in the color transformation calculations. ```rust pub(crate) fn matrix_coefficients(matrix: YuvMatrix) -> (f32, f32) { match matrix { YuvMatrix::Bt601 => (0.299, 0.114), YuvMatrix::Bt709 => (0.2126, 0.0722), YuvMatrix::Bt2020 => (0.2627, 0.0593), } } ``` -------------------------------- ### Using may_stop() with dyn Stop for Optimization Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/trait.Stop.html Demonstrates how to use the `may_stop()` method with `dyn Stop` to optimize checks in hot loops. If `may_stop()` returns `false`, checks can be skipped. This example shows how `Option` implements `Stop` where `None` is a no-op. ```rust use enough::{Stop, StopReason, Unstoppable}; fn process(stop: &dyn Stop) -> Result<(), StopReason> { let stop = stop.may_stop().then_some(stop); // stop is Option<&dyn Stop>, which impl Stop: // None → check() always returns Ok(()), Some → delegates for i in 0..100 { stop.check()?; } Ok(()) } // Unstoppable: may_stop() returns false, so stop is None assert!(process(&Unstoppable).is_ok()); ``` -------------------------------- ### Get AVIF Compatible Brands Source: https://docs.rs/zenavif-parse/0.6.2/src/zenavif_parse/lib.rs.html Retrieves a list of compatible brand identifiers from the AVIF file's `ftyp` box. These indicate other formats the file can be compatible with. ```rust pub fn compatible_brands(&self) -> &[[u8; 4]] { &self.compatible_brands } ``` -------------------------------- ### Handling File Metadata with and_then Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/type.Result.html Demonstrates using `and_then` to chain fallible operations like getting file metadata and its modification time. This is useful for sequential operations that can fail. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Creating DecodeConfig Instances Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.DecodeConfig.html Demonstrates how to create DecodeConfig instances using default settings, with specific limits, or with no limits. ```rust use zenavif_parse::DecodeConfig; // Default limits (suitable for most apps) let config = DecodeConfig::default(); // Strict limits for untrusted input let config = DecodeConfig::default() .with_peak_memory_limit(100_000_000) // 100MB .with_total_megapixels_limit(64) // 64MP max .with_max_animation_frames(100); // 100 frames // No limits (backwards compatible with read_avif) let config = DecodeConfig::unlimited(); ``` -------------------------------- ### Test AVIF Quantizer to Quality Mapping Boundaries Source: https://docs.rs/zenavif/latest/src/zenavif/detect.rs.html Verifies the `qp_to_quality` function at its boundary conditions: QP 0 should map to 100.0 quality, and QP 255 should map to a quality between 1.0 and 5.0. ```rust assert_eq!(qp_to_quality(0), 100.0); let worst = qp_to_quality(255); assert!((1.0..=5.0).contains(&worst), "QP 255 → {worst}"); ``` -------------------------------- ### Get Recommended Re-encoding Quality Source: https://docs.rs/zenavif/latest/src/zenavif/detect.rs.html Calculates a recommended quality setting for re-encoding the AVIF image to minimize generation loss. It returns a value slightly higher than the estimated source quality, capped at 100.0. Returns `None` if the quality couldn't be estimated. ```rust pub fn recommended_quality(&self) -> Option { self.quality.as_ref().map(|q| { // Slightly higher than detected to avoid generation loss (q.estimated_quality + 2.0).min(100.0) }) } ``` -------------------------------- ### Example Stop Trait Implementation Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/trait.Stop.html Implement the Stop trait for custom cancellation sources. The `check` method should return `Ok(())` to continue or `Err(StopReason)` to stop. This example uses an `AtomicBool` for thread-safe cancellation signaling. ```rust use enough::{Stop, StopReason}; use core::sync::atomic::{AtomicBool, Ordering}; pub struct MyStop<'a> { cancelled: &'a AtomicBool, } impl Stop for MyStop<'_> { fn check(&self) -> Result<(), StopReason> { if self.cancelled.load(Ordering::Relaxed) { Err(StopReason::Cancelled) } else { Ok(()) } } } ``` -------------------------------- ### AvifParser::major_brand Source: https://docs.rs/zenavif-parse/0.6.2/src/zenavif_parse/lib.rs.html Gets the major brand from the 'ftyp' box of the AVIF file. ```APIDOC ## AvifParser::major_brand ### Description Gets the major brand from the 'ftyp' box of the AVIF file. This identifies the primary format. ### Method Signature `pub fn major_brand(&self) -> &[u8; 4]` ### Returns A 4-byte array representing the major brand (e.g., `*b"avif"`). ``` -------------------------------- ### Configure AVIF Parsing with Limits - Rust Source: https://docs.rs/zenavif-parse/0.6.2/src/zenavif_parse/lib.rs.html Shows how to set up AVIF parsing with custom resource limits for memory and megapixels. Useful for untrusted input. ```rust use zenavif_parse::DecodeConfig; // Default limits (suitable for most apps) let config = DecodeConfig::default(); // Strict limits for untrusted input let config = DecodeConfig::default() .with_peak_memory_limit(100_000_000) // 100MB .with_total_megapixels_limit(64); // 64MP max ``` -------------------------------- ### Get image rotation Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Retrieves the rotation information for the primary item, if present. ```rust pub fn rotation(&self) -> Option<&ImageRotation> ``` -------------------------------- ### DecoderConfig::new Source: https://docs.rs/zenavif/latest/src/zenavif/config.rs.html Creates a new `DecoderConfig` with default settings. ```APIDOC ## fn new() -> DecoderConfig ### Description Creates a new decoder configuration with default settings. ### Returns A new `DecoderConfig` instance. ``` -------------------------------- ### Get animation frame by index Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Retrieves a single animation frame by its index. ```rust pub fn frame(&self, index: usize) -> Result> ``` -------------------------------- ### Get image mirror information Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Retrieves the mirror information for the primary item, if present. ```rust pub fn mirror(&self) -> Option<&ImageMirror> ``` -------------------------------- ### into_ok Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/type.Result.html Returns the contained Ok value, never panics. This is a nightly-only experimental API. ```APIDOC ## into_ok ### Description Returns the contained `Ok` value, but never panics. This is a nightly-only experimental API. Unlike `unwrap`, this method is known to never panic on the result types it is implemented for. Therefore, it can be used instead of `unwrap` as a maintainability safeguard that will fail to compile if the error type of the `Result` is later changed to an error that can actually occur. ### Type Parameters - `T`: The type of the contained `Ok` value. ### Examples ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` ``` -------------------------------- ### AvifData::alpha_item_metadata Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifData.html Parses AV1 data to get basic properties about the alpha channel, if any. ```APIDOC ## AvifData::alpha_item_metadata ### Description Parses AV1 data to get basic properties about the alpha channel, if any. ### Method `alpha_item_metadata(&self) -> Result>` ``` -------------------------------- ### New decoder configuration Source: https://docs.rs/zenavif/latest/src/zenavif/config.rs.html Creates a new `DecoderConfig` instance with default settings. ```rust pub fn new() -> Self { Self::default() } ``` -------------------------------- ### AvifData::primary_item_metadata Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifData.html Parses AV1 data to get basic properties of the opaque channel. ```APIDOC ## AvifData::primary_item_metadata ### Description Parses AV1 data to get basic properties of the opaque channel. ### Method `primary_item_metadata(&self) -> Result` ``` -------------------------------- ### PartialEq Implementation for ImageMirror Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.ImageMirror.html Allows comparison of two ImageMirror instances for equality. This is used when checking if two mirror configurations are the same. ```rust fn eq(&self, other: &ImageMirror) -> bool ``` -------------------------------- ### Get the default DecoderConfig Source: https://docs.rs/zenavif/latest/zenavif/struct.DecoderConfig.html Provides the default configuration for the decoder, equivalent to calling `DecoderConfig::new()`. ```rust fn default() -> Self ``` -------------------------------- ### Read AVIF File and Access Grid Data Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifData.html Demonstrates how to read an AVIF file and access its grid configuration if present. Note that the `read_avif` function is deprecated. ```rust #[allow(deprecated)] use std::fs::File; #[allow(deprecated)] let data = zenavif_parse::read_avif(&mut File::open("image.avif")?)?; if let Some(grid) = data.grid_config { println!("Grid: {}×{} tiles", grid.rows, grid.columns); println!("Output: {}×{}", grid.output_width, grid.output_height); println!("Tile count: {}", data.grid_tiles.len()); } ``` -------------------------------- ### Get pixel aspect ratio Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Retrieves the pixel aspect ratio for the primary item, if present. ```rust pub fn pixel_aspect_ratio(&self) -> Option<&PixelAspectRatio> ``` -------------------------------- ### AvifProbe Recommended Quality Source: https://docs.rs/zenavif/latest/zenavif/detect/struct.AvifProbe.html Provides a recommended quality setting for re-encoding the AVIF image to match the source quality. Returns None if the quality could not be estimated. ```rust pub fn recommended_quality(&self) -> Option ``` -------------------------------- ### Get number of grid tiles Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Returns the total count of grid tiles in the AVIF image. ```rust pub fn grid_tile_count(&self) -> usize ``` -------------------------------- ### Get animation metadata Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Retrieves animation metadata if the AVIF file contains animation information. ```rust pub fn animation_info(&self) -> Option ``` -------------------------------- ### Get grid tile data by index Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Retrieves the data for a specific grid tile by its index. ```rust pub fn tile_data(&self, index: usize) -> Result> ``` -------------------------------- ### Get alpha item data Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Retrieves the alpha item data, if it is present in the AVIF file. ```rust pub fn alpha_data(&self) -> Option>> ``` -------------------------------- ### YUV Planar Image Initialization Source: https://docs.rs/zenavif/latest/src/zenavif/decoder_managed.rs.html Initializes a YuvPlanarImage structure from provided plane views. This is used when the image contains U and V planes in addition to the Y plane. It checks for the presence of U and V planes, returning an error if they are missing. ```rust 1309 let planar = YuvPlanarImage { y_plane: y_view.as_slice(), y_stride: y_view.stride() as u32, u_plane: u_view.as_slice(), ``` -------------------------------- ### Zenvif File Probing and Detection Assertions Source: https://docs.rs/zenavif/latest/src/zenavif/detect.rs.html This code block iterates through files, probes them, and collects statistics on files with QP and lossless detection. It concludes with assertions to ensure a minimum number of files meet these criteria, indicating successful detection. ```rust probed += 1; } Err(e) => { eprintln!(" {name}: probe failed: {e}"); } } } } eprintln!( "\n Probed {probed} files, {with_qp} with QP, {with_lossless} with lossless detection" ); assert!(probed > 30, "Expected to probe >30 files, got {probed}"); assert!(with_qp > 20, "Expected >20 files with QP, got {with_qp}"); assert!( with_lossless > 20, "Expected >20 files with lossless detection, got {with_lossless}" ); ``` -------------------------------- ### Get Primary Metadata - AvifParser Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Parses and returns the AV1 metadata from the primary item of the AVIF image. ```rust pub fn primary_metadata(&self) -> Result ``` -------------------------------- ### AvifProbe::recommended_quality Source: https://docs.rs/zenavif/latest/src/zenavif/detect.rs.html Provides a recommended quality setting (0-100) for re-encoding the AVIF image using ZenAVIF, aiming to match the source quality. It adds a small buffer to prevent generation loss. Returns `None` if the quality couldn't be estimated. ```APIDOC ## AvifProbe::recommended_quality ### Description Provides a recommended quality setting (0-100) for re-encoding the AVIF image using ZenAVIF, aiming to match the source quality. It adds a small buffer to prevent generation loss. Returns `None` if the quality couldn't be estimated. ### Method Signature `pub fn recommended_quality(&self) -> Option` ### Returns - `Option` - The recommended quality setting (0-100) or `None`. ``` -------------------------------- ### Get ambient viewing environment Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Retrieves ambient viewing environment information for the primary item, if present. ```rust pub fn ambient_viewing(&self) -> Option<&AmbientViewingEnvironment> ``` -------------------------------- ### take Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.FrameIterator.html Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ```APIDOC ## fn take(self, n: usize) -> Take ### Description Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ### Parameters - `n`: The maximum number of elements to yield. ### Returns A new iterator of type `Take`. ``` -------------------------------- ### Get content colour volume Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Retrieves content colour volume information for the primary item, if present. ```rust pub fn content_colour_volume(&self) -> Option<&ContentColourVolume> ``` -------------------------------- ### AvifProbe Methods Source: https://docs.rs/zenavif/latest/zenavif/detect/struct.AvifProbe.html Methods available on the AvifProbe struct for estimating and recommending quality. ```APIDOC ## impl AvifProbe ### pub fn estimated_quality(&self) -> Option Estimated source quality (0-100), or `None` if not extractable. ### pub fn recommended_quality(&self) -> Option Recommended zenavif quality for re-encoding that matches the source. Returns `None` if the quality couldn’t be estimated. ``` -------------------------------- ### CloneToUninit Trait Implementation (Nightly) Source: https://docs.rs/zenavif/latest/zenavif/struct.ImageInfo.html Nightly-only experimental API for copying ImageInfo to uninitialized memory. ```rust impl CloneToUninit for T where T: Clone, Source unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Get clean aperture (crop) Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Retrieves the clean aperture (crop) information for the primary item, if present. ```rust pub fn clean_aperture(&self) -> Option<&CleanAperture> ``` -------------------------------- ### unwrap_or_default for Result Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/type.Result.html Uses `unwrap_or_default` to get the contained value or a default if the `Result` is `Err`. This is useful for fallible parsing. ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### YUV420 to RGB8 Conversion (SIMD Optimized) Source: https://docs.rs/zenavif/latest/src/zenavif/yuv_convert_libyuv.rs.html Converts YUV420 format to RGB8 using libyuv, prioritizing SIMD acceleration for x86_64 and aarch64 architectures when BT.709 Full Range is specified. Falls back to scalar implementation if SIMD is not available or applicable. ```rust pub fn yuv420_to_rgb8( y_plane: &[u8], y_stride: usize, u_plane: &[u8], u_stride: usize, v_plane: &[u8], v_stride: usize, width: usize, height: usize, range: YuvRange, matrix: YuvMatrix, ) -> Option> { // Try SIMD first for BT.709 Full Range (most common) #[cfg(target_arch = "x86_64")] #[allow(clippy::collapsible_if)] if matches!((range, matrix), (YuvRange::Full, YuvMatrix::Bt709)) { if let Some(token) = Desktop64::summon() { return yuv_convert_libyuv_simd::yuv420_to_rgb8_simd( token, y_plane, y_stride, u_plane, u_stride, v_plane, v_stride, width, height, range, matrix, ); } } #[cfg(target_arch = "aarch64")] #[allow(clippy::collapsible_if)] if matches!((range, matrix), (YuvRange::Full, YuvMatrix::Bt709)) { if let Some(token) = NeonToken::summon() { return yuv_convert_libyuv_simd::yuv420_to_rgb8_simd_neon( token, y_plane, y_stride, u_plane, u_stride, v_plane, v_stride, width, height, range, matrix, ); } } // Fallback to scalar implementation would go here if SIMD is not used or available None } ``` -------------------------------- ### ok Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/type.Result.html Converts from `Result` to `Option`. ```APIDOC ## ok ### Description Converts `self` into an `Option`, consuming `self`, and converting the error to `None`, if any. ### Method `ok` ### Response - `Option`: `Some(T)` if the result is `Ok`, `None` otherwise. ### Request Example ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` ``` -------------------------------- ### Get content light level info Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Retrieves content light level information for the primary item, if present. ```rust pub fn content_light_level(&self) -> Option<&ContentLightLevel> ``` -------------------------------- ### Initialize AvifData Structure Source: https://docs.rs/zenavif-parse/0.6.2/src/zenavif_parse/lib.rs.html Initializes the AvifData structure, populating it with extracted properties and default values. It also checks for premultiplied alpha based on item references. ```rust let mut context = AvifData { premultiplied_alpha: alpha_item_id.is_some_and(|alpha_item_id| { meta.item_references.iter().any(|iref| { iref.from_item_id == meta.primary_item_id && iref.to_item_id == alpha_item_id && iref.item_type == b"prem" }) }), av1_config, color_info, rotation, mirror, clean_aperture, pixel_aspect_ratio, content_light_level, mastering_display, content_colour_volume, ambient_viewing, operating_point, layer_selector, layered_image_indexing, major_brand, compatible_brands, ..Default::default() }; ``` -------------------------------- ### Cloning into Existing Data Source: https://docs.rs/zenavif/latest/zenavif/enum.StopReason.html Explains how to use borrowed data to replace existing owned data with the `clone_into` method. ```APIDOC ## fn clone_into(&self, target: &mut T) ### Description Uses borrowed data to replace owned data, usually by cloning. ### Method `clone_into` ``` -------------------------------- ### Get XMP Metadata - AvifParser Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Retrieves the XMP metadata for the primary item, if present. Returns raw XMP/XML data. ```rust pub fn xmp(&self) -> Option>> ``` -------------------------------- ### Get mastering display colour volume Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Retrieves mastering display colour volume information for the primary item, if present. ```rust pub fn mastering_display(&self) -> Option<&MasteringDisplayColourVolume> ``` -------------------------------- ### Hot Loop Optimization with Option Stop Implementation Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/trait.Stop.html Illustrates optimizing hot loops by leveraging the `Stop` implementation for `Option`. When `stop.may_stop()` is false, `stop` becomes `None`, and `stop.check()` effectively becomes a no-op, avoiding unnecessary checks. ```rust use enough::{Stop, StopReason, Unstoppable}; fn hot_loop(stop: &dyn Stop) -> Result<(), StopReason> { let stop = stop.may_stop().then_some(stop); for i in 0..1000 { stop.check()?; } Ok(()) } assert!(hot_loop(&Unstoppable).is_ok()); ``` -------------------------------- ### Clone DecoderConfig Source: https://docs.rs/zenavif/latest/zenavif/struct.DecoderConfig.html Creates a duplicate of the existing DecoderConfig. This allows for creating multiple configurations based on a common starting point. ```rust fn clone(&self) -> DecoderConfig ``` -------------------------------- ### Decode Image to StripConverter for Streaming Source: https://docs.rs/zenavif/latest/src/zenavif/decoder_managed.rs.html Prepares a StripConverter for cache-optimal streaming of AVIF images. Falls back to full-frame conversion for 16-bit or monochrome images. Returns the StripConverter and image information. This is intended as a streaming decode entry point. ```rust pub(crate) fn decode_to_strip_converter( &mut self, stop: &(impl Stop + ?Sized), ) -> Result<(crate::strip_convert::StripConverter, ImageInfo)> { stop.check().map_err(|e| at!(Error::Cancelled(e)))?; let primary_data = self .parser .primary_data() .map_err(|e| at!(Error::from(e)))?; let primary_frame = Self::decode_frame( &mut self.decoder, &primary_data, "Failed to decode primary frame", )?; stop.check().map_err(|e| at!(Error::Cancelled(e)))?; let alpha_frame = if let Some(alpha_result) = self.parser.alpha_data() { let alpha_data = alpha_result.map_err(|e| at!(Error::from(e)))?; Some(Self::decode_frame( &mut self.decoder, &alpha_data, "Failed to decode alpha frame", )?) } else { None }; stop.check().map_err(|e| at!(Error::Cancelled(e)))?; let info = self.build_image_info(&primary_frame, alpha_frame.is_some())?; let bit_depth = primary_frame.bit_depth(); let layout = primary_frame.pixel_layout(); let chroma_sampling = convert_chroma_sampling(layout); let buffer_width = primary_frame.width() as usize; let buffer_height = primary_frame.height() as usize; let display_width = info.width as usize; let display_height = info.height as usize; let can_strip = bit_depth == 8 && !matches!(chroma_sampling, ChromaSampling::Monochrome) && buffer_width == display_width && buffer_height == display_height; let converter = if can_strip { let alpha_range = alpha_frame .as_ref() .map(|f| convert_color_range(f.color_info().color_range)) .unwrap_or(ColorRange::Full); ``` -------------------------------- ### Get Item Extents from Metadata Source: https://docs.rs/zenavif-parse/0.6.2/src/zenavif_parse/lib.rs.html Retrieves item extents (construction method and ranges) from AvifInternalMeta. Used when an item is not found in the iloc. ```rust /// Get item extents (construction method + ranges) from metadata. fn get_item_extents(meta: &AvifInternalMeta, item_id: u32) -> Result { let item = meta .iloc_items .iter() .find(|item| item.item_id == item_id) .ok_or(Error::InvalidData("item not found in iloc"))?; let mut extents = TryVec::new(); for extent in &item.extents { extents.push(extent.extent_range.clone())?; } Ok(ItemExtents { construction_method: item.construction_method, extents, }) } ``` -------------------------------- ### Implement SourceEncodingDetails for AvifProbe Source: https://docs.rs/zenavif/latest/src/zenavif/detect.rs.html Implements the `SourceEncodingDetails` trait for the `AvifProbe` struct, providing methods to retrieve estimated quality and check for lossless encoding. Requires the `zencodec` feature to be enabled. ```rust impl zencodec::SourceEncodingDetails for AvifProbe { fn source_generic_quality(&self) -> Option { self.quality.as_ref().map(|q| q.estimated_quality) } fn is_lossless(&self) -> bool { self.lossless.unwrap_or(false) } } ``` -------------------------------- ### Get AV1 codec configuration Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Retrieves the AV1 codec configuration for the primary item, if available. This is parsed from the `av1C` property box. ```rust pub fn av1_config(&self) -> Option<&AV1Config> ``` -------------------------------- ### To and TryTo Implementations Source: https://docs.rs/zenavif/latest/zenavif/detect/struct.QualityEstimate.html Provides methods for converting owned data to other types, with fallible conversion support. ```rust fn to(self) -> T where Self: Into, ``` ```rust fn try_to(self) -> Result where Self: TryInto, ``` -------------------------------- ### clone_to_uninit Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.GainMapMetadata.html Performs copy-assignment from `self` to `dest`. This is a nightly-only experimental API. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from `self` to `dest`. ### Method `clone_to_uninit` ### Parameters #### Path Parameters - **self** (*mut T*) - Required - Reference to the source data. - **dest** (**mut u8*) - Required - Pointer to the destination buffer. ### Note This is a nightly-only experimental API. ``` -------------------------------- ### Get Alpha Metadata - AvifParser Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AvifParser.html Parses and returns the AV1 metadata from the alpha item, if present. Returns None if no alpha item exists. ```rust pub fn alpha_metadata(&self) -> Option> ``` -------------------------------- ### Parse AVIF file for Gain Map Source: https://docs.rs/zenavif-parse/0.6.2/src/zenavif_parse/lib.rs.html Demonstrates how to read an AVIF file, parse it using `AvifParser`, and extract the gain map information if present. The gain map data is an AV1 bitstream. ```rust let bytes = std::fs::read("hdr.avif").unwrap(); let parser = zenavif_parse::AvifParser::from_bytes(&bytes).unwrap(); if let Some(Ok(gm)) = parser.gain_map() { ``` -------------------------------- ### CloneToUninit Trait Implementation (Nightly) Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.AnimationInfo.html An experimental nightly-only API for copying values to uninitialized memory. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Get AVIF Major Brand Source: https://docs.rs/zenavif-parse/0.6.2/src/zenavif_parse/lib.rs.html Retrieves the major brand identifier from the AVIF file's `ftyp` box. This indicates the primary format of the file. ```rust pub fn major_brand(&self) -> &[u8; 4] { &self.major_brand } ``` -------------------------------- ### Clone Implementation for ImageMirror Source: https://docs.rs/zenavif-parse/0.6.2/zenavif_parse/struct.ImageMirror.html Provides the ability to create a duplicate of an ImageMirror instance. This is useful for copying mirror settings. ```rust fn clone(&self) -> ImageMirror ``` -------------------------------- ### Get Gain Map Bundle Source: https://docs.rs/zenavif-parse/0.6.2/src/zenavif_parse/lib.rs.html Retrieves the complete gain map bundle, combining metadata and image data. Returns `None` if either is missing. ```rust pub fn gain_map(&self) -> Option { let metadata = self.gain_map_metadata.as_ref()?.clone(); let gain_map_data = self.gain_map_item.as_ref()?.to_vec(); Some(AvifGainMap { metadata, gain_map_data, alt_color_info: self.gain_map_color_info.clone(), }) } ``` -------------------------------- ### ManagedAvifDecoder::probe_info Source: https://docs.rs/zenavif/latest/zenavif/struct.ManagedAvifDecoder.html Probes and extracts image metadata without decoding the actual pixel data. This is efficient for quickly getting image dimensions and other information. ```APIDOC ## ManagedAvifDecoder::probe_info ### Description Probe image metadata without decoding pixels. Uses the AVIF container parser and AV1 sequence header to extract dimensions, color info, ICC profile, EXIF, XMP, orientation, and HDR metadata. Does NOT do full AV1 frame decoding. ### Signature ```rust pub fn probe_info(&self) -> Result ``` ### Returns An `ImageInfo` struct containing the extracted metadata. ``` -------------------------------- ### yuv420_to_rgb8 Source: https://docs.rs/zenavif/latest/src/zenavif/yuv_convert.rs.html Converts YUV420 to RGB8 with bilinear chroma upsampling. It automatically dispatches to the most efficient SIMD path available for the target architecture (x86-64 AVX2/FMA, aarch64 NEON, wasm32 SIMD, or a scalar fallback). ```APIDOC ## yuv420_to_rgb8 ### Description Converts YUV420 to RGB8 with bilinear chroma upsampling. Automatically dispatches to the best SIMD path available: AVX2/FMA on x86-64, NEON on aarch64, wasm SIMD on wasm32, or scalar fallback. ### Arguments * `y_plane` - Luma plane (full resolution) * `y_stride` - Y plane stride in bytes * `u_plane` - U chroma plane (half resolution) * `u_stride` - U plane stride in bytes * `v_plane` - V chroma plane (half resolution) * `v_stride` - V plane stride in bytes * `width` - Image width * `height` - Image height * `range` - Color range (Limited or Full) * `matrix` - Matrix coefficients (BT.601, BT.709, or BT.2020) ``` -------------------------------- ### Get YUV Conversion Constants Source: https://docs.rs/zenavif/latest/src/zenavif/yuv_convert_libyuv.rs.html Retrieves the appropriate `YuvConstants` based on the specified `YuvMatrix` and `YuvRange`. Returns `None` if the combination is not supported (e.g., BT.2020). ```rust fn get_constants(matrix: YuvMatrix, range: YuvRange) -> Option<&'static YuvConstants> { match (matrix, range) { (YuvMatrix::Bt709, YuvRange::Full) => Some(&YuvConstants::BT709_FULL), (YuvMatrix::Bt709, YuvRange::Limited) => Some(&YuvConstants::BT709_LIMITED), (YuvMatrix::Bt601, YuvRange::Full) => Some(&YuvConstants::BT601_FULL), (YuvMatrix::Bt601, YuvRange::Limited) => Some(&YuvConstants::BT601_LIMITED), _ => None, // BT.2020 not yet implemented } } ```