### DecodeRequest Creation Example Source: https://docs.rs/zenwebp/latest/src/zenwebp/decoder/api.rs.html Demonstrates how to create a new `DecodeRequest` with a default configuration and WebP data. This is the starting point for decoding. ```rust let config = DecodeConfig::default(); let webp_data: &[u8] = &[]; // your WebP data let (pixels, w, h) = DecodeRequest::new(&config, webp_data).decode_rgba()?; # Ok::<(), whereat::At>(()) ``` -------------------------------- ### Assemble a WebP file with WebPMux Source: https://docs.rs/zenwebp/latest/src/zenwebp/mux/assemble.rs.html Demonstrates initializing a new WebPMux instance, configuring animation settings, and adding frames to generate a WebP file. ```rust use zenwebp::mux::{WebPMux, MuxFrame, BlendMethod, DisposeMethod}; use zenwebp::decoder::LoopCount; let mut mux = WebPMux::new(320, 240); mux.set_animation([0, 0, 0, 0], LoopCount::Forever); // Add pre-encoded frames mux.push_frame(MuxFrame { x_offset: 0, y_offset: 0, width: 320, height: 240, duration_ms: 100, dispose: DisposeMethod::Background, blend: BlendMethod::Overwrite, bitstream: vec![], // VP8L data here alpha_data: None, is_lossless: true, })?; let webp_bytes = mux.assemble()?; # Ok::<(), whereat::At>(()) ``` -------------------------------- ### Create New EncoderConfig Source: https://docs.rs/zenwebp/latest/src/zenwebp/encoder/api.rs.html Creates a new encoder configuration with default settings. This is a convenient way to get a starting configuration. ```rust /// Create a new encoder configuration with default settings. /// /// Default: lossy encoding at quality 75, method 4, no preset. #[must_use] pub fn new() -> Self { Self::default() } ``` -------------------------------- ### Configure and Encode with Metadata Source: https://docs.rs/zenwebp/latest/src/zenwebp/encoder/api.rs.html Demonstrates how to initialize a lossy configuration, create image metadata with an ICC profile, and perform an encoding request. ```rust use zenwebp::{EncodeRequest, LossyConfig, PixelLayout, ImageMetadata}; let config = LossyConfig::new(); let pixels = vec![255u8; 4 * 4 * 4]; let icc_data = vec![/* ICC data */]; let metadata = ImageMetadata::new() .with_icc_profile(&icc_data); let webp = EncodeRequest::lossy(&config, &pixels, PixelLayout::Rgba8, 4, 4) .with_metadata(metadata) .encode()?; # Ok::<(), whereat::At>(()) ``` -------------------------------- ### Get Err Value with unwrap_err Source: https://docs.rs/zenwebp/latest/zenwebp/encoder/type.EncodeResult.html Use `unwrap_err()` to get the contained Err value. Panics with the Ok value if the Result is Ok. ```rust let x: Result = Ok(2); x.unwrap_err(); // panics with `2` ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### Start Accumulated Result - Rust Source: https://docs.rs/zenwebp/latest/src/zenwebp/decoder/arithmetic.rs.html Starts an accumulated result for bit reading operations. Each call must be followed by a `check` on the same decoder. ```rust pub(crate) fn start_accumulated_result(&mut self) -> BitResultAccumulator { BitResultAccumulator } ``` -------------------------------- ### Initialize Token Partitions Source: https://docs.rs/zenwebp/latest/src/zenwebp/decoder/vp8v2/header.rs.html Reads partition sizes and prepares data buffers for token decoding. ```rust 234 fn init_partitions( 235 &mut self, 236 r: &mut SliceReader<'_>, 237 n: usize, 238 ) -> Result<(), whereat::At> { 239 use byteorder_lite::{ByteOrder, LittleEndian}; 240 241 let remaining = r.remaining(); 242 let mut all_data = Vec::new(); 243 let mut boundaries = Vec::with_capacity(n); 244 245 if n > 1 { 246 // Partition size table: 3 bytes per partition for n-1 partitions 247 let size_table_bytes = 3 * (n - 1); 248 if size_table_bytes > remaining { 249 return Err(at!(DecodeError::BitStreamError)); 250 } 251 let mut sizes = vec![0u8; size_table_bytes]; 252 r.read_exact(sizes.as_mut_slice())?; 253 254 for s in sizes.chunks(3) { 255 // u24 max is 16_777_215, always fits usize. 256 let size = LittleEndian::read_u24(s) as usize; 257 // Validate partition size against remaining data 258 if size > r.remaining() { 259 return Err(at!(DecodeError::BitStreamError)); 260 } 261 let start = all_data.len(); ``` -------------------------------- ### Get Frame Count (Alias) Source: https://docs.rs/zenwebp/latest/src/zenwebp/mux/demux.rs.html An alias for the `num_frames()` method, providing an alternative way to get the total number of frames in a WebP image. ```rust pub fn frame_count(&self) -> u32 { self.num_frames() } ``` -------------------------------- ### WebPMux - Initialization Source: https://docs.rs/zenwebp/latest/zenwebp/mux/struct.WebPMux.html Methods for creating a new WebPMux instance or parsing an existing WebP file. ```APIDOC ## WebPMux - Initialization ### `new(width: u32, height: u32) -> Self` **Description**: Creates a new mux assembler with the given canvas dimensions. ### `from_data(data: &[u8]) -> MuxResult` **Description**: Parses an existing WebP file into a mux assembler. This allows modifying an existing file (e.g., adding metadata, replacing frames). ``` -------------------------------- ### Create WebPDecoder and Get Image Info Source: https://docs.rs/zenwebp/latest/zenwebp/decoder/struct.WebPDecoder.html Instantiate a WebPDecoder and retrieve image metadata like format, dimensions, and alpha channel presence. The `webp_data` slice is required. This is a zero-cost operation. ```rust use zenwebp::WebPDecoder; let webp_data: &[u8] = &[]; // your WebP data let decoder = WebPDecoder::new(webp_data)?; let info = decoder.info(); println!("Format: {:?}, {}x{}", info.format, info.width, info.height); ``` -------------------------------- ### Internal API Example for Animation Decoding Source: https://docs.rs/zenwebp/latest/src/zenwebp/decoder/vp8v2/animation.rs.html An example demonstrating how to use the `decode_animation` method with an internal API. This snippet is marked with `ignore` and is intended for internal testing or illustration. ```rust let mut ctx = DecoderContext::new(); ctx.decode_animation(webp_data, |frame| { println!("frame {} at {}ms", frame.frame_num, frame.timestamp_ms); true // continue }).unwrap(); ``` -------------------------------- ### Get Ok Value or Default with unwrap_or_default Source: https://docs.rs/zenwebp/latest/zenwebp/encoder/type.EncodeResult.html Use `unwrap_or_default()` to get the contained Ok value or the default value for the type if it's an Err. This is useful for converting strings to numbers, providing 0 for invalid inputs. ```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); ``` -------------------------------- ### Configure and Initialize Decoding Limits Source: https://docs.rs/zenwebp/latest/src/zenwebp/decoder/limits.rs.html Demonstrates how to customize default limits or create an unrestricted configuration for trusted inputs. ```rust use zenwebp::Limits; // Start with defaults and customize let limits = Limits::default() .max_dimensions(4096, 4096) .max_memory(256 * 1024 * 1024); // 256 MB // Or start with no limits for trusted inputs let unlimited = Limits::none(); ``` -------------------------------- ### Get Boundary Data Source: https://docs.rs/zenwebp/latest/src/zenwebp/encoder/analysis/iterator.rs.html Retrieves boundary information for YUV components. ```rust /// Get left boundary for Y with corner at index 0 /// Returns full y_left array: [0]=corner, [1..17]=left pixels #[allow(dead_code)] fn get_y_left_with_corner(&self) -> Option<&[u8]> { if self.x > 0 { Some(&self.y_left[..]) } else { None } } ``` ```rust /// Get top boundary for Y #[allow(dead_code)] fn get_y_top(&self) -> Option<&[u8]> { if self.y > 0 { Some(&self.y_top[self.x * 16..self.x * 16 + 16]) ``` -------------------------------- ### Assemble WebP Source: https://docs.rs/zenwebp/latest/src/zenwebp/mux/assemble.rs.html Finalizes the configuration and generates the binary WebP file. ```APIDOC ## assemble() ### Description Assembles the final WebP file based on the current configuration (animated or single image). ### Returns - **Vec** - The binary representation of the WebP file. ### Errors - **MuxError::NoFrames** - If no frames are provided for a single image assembly. ``` -------------------------------- ### WebPDemuxer Initialization Source: https://docs.rs/zenwebp/latest/zenwebp/mux/struct.WebPDemuxer.html Initializes a new WebPDemuxer instance from a byte slice containing WebP data. ```APIDOC ## POST /WebPDemuxer/new ### Description Parses a WebP file from a byte slice. This only parses the container structure and records byte ranges; no pixel decoding is performed. ### Method POST ### Parameters #### Request Body - **data** ([u8]) - Required - A byte slice containing the raw WebP file data. ### Response #### Success Response (200) - **WebPDemuxer** (Object) - A new instance of the WebPDemuxer. ``` -------------------------------- ### Set Iterator Row Source: https://docs.rs/zenwebp/latest/src/zenwebp/encoder/analysis/iterator.rs.html Resets the iterator to the start of a specific row. ```rust /// Set iterator to start of row y pub fn set_row(&mut self, y: usize) { self.x = 0; self.y = y; self.init_left(); } ``` -------------------------------- ### is_err_and Example Source: https://docs.rs/zenwebp/latest/zenwebp/decoder/type.DecodeResult.html Demonstrates the usage of the is_err_and method on Result types. ```APIDOC ## is_err_and Example ### Description Checks if the result is an error and if the error satisfies a given predicate. ### Method `is_err_and` (called on a Result) ### Endpoint N/A (method on Result type) ### Parameters #### Predicate Function - `predicate` (FnOnce(&E) -> bool) - A closure that takes a reference to the error value and returns true if the error matches the condition. ### Request Body N/A ### Response #### Success Response - `bool`: `true` if the Result is `Err` and the predicate returns `true` for the error value, `false` otherwise. ### Response Example ```rust use std::io::{Error, ErrorKind}; // Case 1: Error matches the kind let x: Result = Err(Error::new(ErrorKind::NotFound, "!")); assert_eq!(x.is_err_and(|e| e.kind() == ErrorKind::NotFound), true); // Case 2: Error does not match the kind let x: Result = Err(Error::new(ErrorKind::PermissionDenied, "!")); assert_eq!(x.is_err_and(|e| e.kind() == ErrorKind::NotFound), false); // Case 3: Result is Ok let x: Result = Ok(123); assert_eq!(x.is_err_and(|e| e.kind() == ErrorKind::NotFound), false); // Case 4: Using a different error type (String) let x: Result = Err("ownership".to_string()); assert_eq!(x.as_ref().is_err_and(|e| e.len() > 1), true); println!("still alive {:?}", x); ``` ``` -------------------------------- ### Choose Encoder Configuration at Runtime Source: https://docs.rs/zenwebp/latest/src/zenwebp/encoder/config.rs.html Demonstrates how to select between lossy and lossless encoder configurations based on runtime conditions, such as image transparency. ```rust use zenwebp::{EncoderConfig, LossyConfig, LosslessConfig}; fn choose_config(has_transparency: bool) -> EncoderConfig { if has_transparency { EncoderConfig::Lossless(LosslessConfig::new()) } else { EncoderConfig::Lossy(LossyConfig::new().with_quality(80.0)) } } ``` -------------------------------- ### Get Result Reference with as_ref Source: https://docs.rs/zenwebp/latest/zenwebp/encoder/type.EncodeResult.html Converts from &Result to Result<&T, &E>. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### Initialize WebPEncoder Source: https://docs.rs/zenwebp/latest/src/zenwebp/encoder/api.rs.html Creates a new `WebPEncoder` instance, initializing it with a writer and default settings. Supports only 'VP8L' lossless encoding. ```rust pub fn new(w: &'a mut Vec) -> Self { Self { writer: w, icc_profile: Vec::new(), exif_metadata: Vec::new(), xmp_metadata: Vec::new(), params: EncoderParams::default(), stop: &enough::Unstoppable, progress: &NO_PROGRESS, } } ``` -------------------------------- ### Configure WebP Lambda and Psy Parameters Source: https://docs.rs/zenwebp/latest/src/zenwebp/common/types.rs.html Calculates trellis and mode selection lambda values based on quantization parameters and initializes perceptual configuration. ```rust self.lambda_trellis_i4 = ((7 * q_i4 * q_i4) >> 3).max(1); self.lambda_trellis_i16 = ((q_i16 * q_i16) >> 2).max(1); self.lambda_trellis_uv = ((q_uv * q_uv) << 1).max(1); // Compute RD mode selection lambda values (from libwebp SetSegmentProbas) // lambda_i4 = (3 * q^2) >> 7 // lambda_i16 = 3 * q^2 // lambda_uv = (3 * q^2) >> 6 // lambda_mode = (1 * q^2) >> 7 self.lambda_i4 = ((3 * q_i4 * q_i4) >> 7).max(1); self.lambda_i16 = (3 * q_i16 * q_i16).max(1); self.lambda_uv = ((3 * q_uv * q_uv) >> 6).max(1); self.lambda_mode = ((q_i4 * q_i4) >> 7).max(1); // Compute tlambda for spectral distortion weight // tlambda = (sns_strength * q) >> 5 // This enables TDisto in mode selection self.tlambda = (u32::from(sns_strength) * q_i4) >> 5; // Initialize perceptual config self.psy_config = PsyConfig::new(method, self.quant_index, sns_strength); } } ``` -------------------------------- ### Get Canvas Height Source: https://docs.rs/zenwebp/latest/src/zenwebp/mux/demux.rs.html Returns the canvas height of the WebP image in pixels. ```rust pub fn canvas_height(&self) -> u32 { self.canvas_height } ``` -------------------------------- ### Get Canvas Width Source: https://docs.rs/zenwebp/latest/src/zenwebp/mux/demux.rs.html Returns the canvas width of the WebP image in pixels. ```rust pub fn canvas_width(&self) -> u32 { self.canvas_width } ``` -------------------------------- ### Initialize VP8Partitions Source: https://docs.rs/zenwebp/latest/src/zenwebp/decoder/bit_reader.rs.html Creates a new `VP8Partitions` instance with default empty values. Used when no partitions are present or before initialization. ```rust pub fn new() -> Self { Self { data: Box::new([]), boundaries: [(0, 0); 8], states: [VP8BitReaderState::default(); 8], num_partitions: 0, } } ``` -------------------------------- ### Result::is_ok_and Implementation Source: https://docs.rs/zenwebp/latest/zenwebp/mux/type.MuxResult.html Example of checking if a Result is Ok and matches a predicate. ```rust let x: Result = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Initialize VP8Partitions with Data Source: https://docs.rs/zenwebp/latest/src/zenwebp/decoder/bit_reader.rs.html Initializes the `VP8Partitions` with provided data and partition boundaries. It sets up the data slice, number of partitions, and initializes the state for each partition. ```rust pub fn init(&mut self, data: Vec, boundaries: &[(usize, usize)]) { self.data = data.into_boxed_slice(); self.num_partitions = boundaries.len().min(8); for (i, &(start, len)) in boundaries.iter().take(8).enumerate() { self.boundaries[i] = (start, len); self.states[i] = VP8BitReaderState::init_from_slice(&self.data[start..start + len]); } } ``` -------------------------------- ### Create Lossy EncodeRequest with Method Source: https://docs.rs/zenwebp/latest/zenwebp/encoder/struct.EncodeRequest.html This example demonstrates creating a lossy encoding request and specifying the compression method. The `with_method` option can fine-tune the compression algorithm. ```rust use zenwebp::{EncodeRequest, LossyConfig, PixelLayout}; let config = LossyConfig::new().with_quality(85.0).with_method(4); let rgba = vec![0u8; 640 * 480 * 4]; let webp = EncodeRequest::lossy(&config, &rgba, PixelLayout::Rgba8, 640, 480) .encode()?; ``` -------------------------------- ### Get ICC Profile Source: https://docs.rs/zenwebp/latest/zenwebp/mux/struct.WebPDemuxer.html Retrieves the ICC profile data from the WebP container, if it is present. ```rust pub fn icc_profile(&self) -> Option<&'a [u8]> ``` -------------------------------- ### WebPMux::new Source: https://docs.rs/zenwebp/latest/src/zenwebp/mux/assemble.rs.html Initializes a new WebP mux assembler with specified canvas dimensions. ```APIDOC ## WebPMux::new ### Description Creates a new mux assembler instance with the given canvas width and height. ### Parameters #### Request Body - **width** (u32) - Required - Canvas width in pixels - **height** (u32) - Required - Canvas height in pixels ### Response - **WebPMux** (Object) - A new instance of the WebP mux assembler. ``` -------------------------------- ### GET /image/frame/{n} Source: https://docs.rs/zenwebp/latest/src/zenwebp/mux/demux.rs.html Retrieves a specific frame from the WebP image by its 1-based index. ```APIDOC ## GET /image/frame/{n} ### Description Fetches a specific frame by its 1-based index. Returns null if the index is out of range. ### Parameters #### Path Parameters - **n** (u32) - Required - The 1-based index of the frame to retrieve. ### Response #### Success Response (200) - **frame** (DemuxFrame) - The requested frame object containing dimensions, offsets, and bitstream data. ``` -------------------------------- ### unwrap_err() - Get Err value Source: https://docs.rs/zenwebp/latest/zenwebp/mux/type.MuxResult.html Retrieves the value from an Err variant. Panics if the Result is an Ok. ```APIDOC ## POST /api/users ### Description Retrieves the value from an Err variant. Panics if the Result is an Ok. ### Method POST ### Endpoint /api/users ### Parameters #### Path Parameters - **user_id** (string) - Required - The ID of the user to retrieve. #### Query Parameters - **include_details** (boolean) - Optional - Whether to include detailed user information. ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **user_id** (string) - The unique identifier for the user. - **username** (string) - The user's chosen username. - **email** (string) - The user's email address. #### Response Example ```json { "user_id": "123e4567-e89b-12d3-a456-426614174000", "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Setup Encoding Parameters Source: https://docs.rs/zenwebp/latest/src/zenwebp/encoder/vp8/mod.rs.html Configures encoder parameters based on lossy quality, image dimensions, and input buffers. It determines the quantization index and macroblock dimensions, and computes the optimal filter level. ```rust if lossy_quality > 100 { panic!("lossy quality must be between 0 and 100"); } // Use libwebp-style quality curve to match expected behavior at Q75 // This emulates jpeg-like behavior where Q75 is "good quality" let quant_index: u8 = quality_to_quant_index(lossy_quality); let quant_index_usize: usize = quant_index as usize; let mb_width = width.div_ceil(16); let mb_height = height.div_ceil(16); self.macroblock_width = mb_width; self.macroblock_height = mb_height; // Compute optimal filter level based on quantization and preset tuning params let filter_level = super::cost::compute_filter_level( quant_index, self.filter_sharpness, self.filter_strength, ); self.frame = Frame { width, height, ybuf: y_buf, ubuf: u_buf, vbuf: v_buf, ``` -------------------------------- ### Get TypeId of ImageInfo Source: https://docs.rs/zenwebp/latest/zenwebp/decoder/struct.ImageInfo.html Retrieves the `TypeId` of the `ImageInfo` struct, useful for runtime type identification. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### WebPDecoder::new Source: https://docs.rs/zenwebp/latest/src/zenwebp/decoder/api.rs.html Creates a new `WebPDecoder` from the data slice with default options. ```APIDOC ## POST /websites/rs_zenwebp/WebPDecoder/new ### Description Creates a new `WebPDecoder` from the data slice using default decoding options. ### Method POST ### Endpoint /websites/rs_zenwebp/WebPDecoder/new ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (slice of u8) - Required - The WebP data to decode. ### Request Example ```json { "data": "your_webp_data_here" } ``` ### Response #### Success Response (200) - **WebPDecoder** (object) - A new WebPDecoder instance. #### Response Example ```json { "decoder_instance": "..." } ``` ``` -------------------------------- ### Configure and Use WebP Encoder Source: https://docs.rs/zenwebp/latest/src/zenwebp/encoder/api.rs.html Demonstrates creating a reusable EncoderConfig and using it to encode multiple images with different dimensions. ```rust use zenwebp::{EncoderConfig, EncodeRequest, PixelLayout, Preset}; let config = EncoderConfig::with_preset(Preset::Photo, 85.0) .with_method(4); // Reuse config for multiple images let image1 = vec![0u8; 4 * 4 * 4]; // 4x4 RGBA let image2 = vec![0u8; 8 * 6 * 4]; // 8x6 RGBA let webp1 = EncodeRequest::new(&config, &image1, PixelLayout::Rgba8, 4, 4).encode()?; let webp2 = EncodeRequest::new(&config, &image2, PixelLayout::Rgba8, 8, 6).encode()?; # Ok::<(), whereat::At>(()) ``` -------------------------------- ### GET /image/metadata Source: https://docs.rs/zenwebp/latest/src/zenwebp/mux/demux.rs.html Retrieves embedded metadata chunks such as ICC profiles, EXIF, or XMP data. ```APIDOC ## GET /image/metadata ### Description Retrieves optional metadata chunks present in the WebP file. ### Response #### Success Response (200) - **icc_profile** (Option<[u8]>) - ICC profile data if present. - **exif** (Option<[u8]>) - EXIF metadata if present. - **xmp** (Option<[u8]>) - XMP metadata if present. ``` -------------------------------- ### Build WebPDecoder with Two-Phase Decoding Source: https://docs.rs/zenwebp/latest/zenwebp/decoder/struct.WebPDecoder.html Use this method to parse WebP headers and prepare for decoding. Inspect metadata using `info()` before decoding. Requires the webp_data slice. ```rust use zenwebp::WebPDecoder; // Phase 1: Parse headers let mut decoder = WebPDecoder::build(webp_data)?; // Phase 2: Inspect metadata let info = decoder.info(); println!("{}x{}, alpha={}", info.width, info.height, info.has_alpha); // Phase 3: Decode (no re-parsing) let mut output = vec![0u8; decoder.output_buffer_size().unwrap()]; decoder.read_image(&mut output)?; ``` -------------------------------- ### Get Extra Bits Source: https://docs.rs/zenwebp/latest/src/zenwebp/encoder/vp8l/histogram.rs.html Retrieves the number of extra bits required for a given prefix code. ```APIDOC ## length_code_extra_bits / distance_code_extra_bits ### Description Calculates the number of extra bits associated with a specific prefix code. ### Parameters - **code** (u8) - Required - The prefix code. ### Response - **u8** - The number of extra bits. ``` -------------------------------- ### Get Bytes Buffered Source: https://docs.rs/zenwebp/latest/src/zenwebp/decoder/streaming.rs.html Returns the number of bytes that have been accumulated in the decoder's buffer so far. ```rust #[must_use] pub fn bytes_buffered(&self) -> usize { self.buf.len() } ``` -------------------------------- ### Initialize Luma Block Transformation Source: https://docs.rs/zenwebp/latest/src/zenwebp/encoder/vp8/prediction.rs.html Sets up the environment for 4x4 luma block transformation, including border creation and non-zero context initialization. ```rust // this is for transforming the luma blocks for each subblock independently // meaning the luma mode is B #[allow(clippy::needless_range_loop)] // sbx,sby indices used for multiple arrays and coordinate computation fn transform_luma_blocks_4x4( &mut self, bpred_modes: [IntraMode; 16], mbx: usize, mby: usize, ) -> LumaBlockResult { let mut luma_blocks = [0i32; 16 * 16]; let stride = LUMA_STRIDE; let mbw = self.macroblock_width; let width = usize::from(mbw * 16); let mut y_with_border = create_border_luma( mbx, mby, mbw.into(), &self.top_border_y, &self.left_border_y, ); let segment = self.get_segment_for_mb(mbx, mby); let trellis_lambda = if self.do_trellis { Some(segment.lambda_trellis_i4) } else { None }; // Track non-zero context for trellis (I4 uses ctype=3) // IMPORTANT: Initialize from global state to match encode_residual let mut top_nz = [ self.top_complexity[mbx].y[0] != 0, self.top_complexity[mbx].y[1] != 0, self.top_complexity[mbx].y[2] != 0, self.top_complexity[mbx].y[3] != 0, ]; let mut left_nz = [ self.left_complexity.y[0] != 0, self.left_complexity.y[1] != 0, self.left_complexity.y[2] != 0, self.left_complexity.y[3] != 0, ]; for sby in 0usize..4 { for sbx in 0usize..4 { let i = sby * 4 + sbx; let y0 = sby * 4 + 1; let x0 = sbx * 4 + 1; match bpred_modes[i] { IntraMode::TM => predict_tmpred(&mut y_with_border, 4, x0, y0, stride), ``` -------------------------------- ### WebPMux - Metadata Operations Source: https://docs.rs/zenwebp/latest/zenwebp/mux/struct.WebPMux.html Methods for setting, getting, and clearing ICC profile, EXIF, and XMP metadata. ```APIDOC ## WebPMux - Metadata Operations ### `set_icc_profile(&mut self, data: Vec)` **Description**: Sets the ICC profile metadata. ### `icc_profile(&self) -> Option<&[u8]>` **Description**: Gets the ICC profile metadata. ### `set_exif(&mut self, data: Vec)` **Description**: Sets the EXIF metadata. ### `exif(&self) -> Option<&[u8]>` **Description**: Gets the EXIF metadata. ### `set_xmp(&mut self, data: Vec)` **Description**: Sets the XMP metadata. ### `xmp(&self) -> Option<&[u8]>` **Description**: Gets the XMP metadata. ### `clear_icc_profile(&mut self)` **Description**: Removes the ICC profile metadata. ### `clear_exif(&mut self)` **Description**: Removes the EXIF metadata. ### `clear_xmp(&mut self)` **Description**: Removes the XMP metadata. ``` -------------------------------- ### Initialize WebPDemuxer Source: https://docs.rs/zenwebp/latest/zenwebp/mux/struct.WebPDemuxer.html Parses a WebP file from a byte slice to create a WebPDemuxer. This operation only parses the container structure and records byte ranges; no pixel decoding is performed. ```rust pub fn new(data: &'a [u8]) -> MuxResult ``` -------------------------------- ### Get Quality from EncoderConfig Source: https://docs.rs/zenwebp/latest/src/zenwebp/encoder/config.rs.html Retrieves the quality value from an `EncoderConfig`, whether it's a `Lossy` or `Lossless` variant. ```rust /// Get the quality value from either variant. pub(crate) fn get_quality(&self) -> f32 { match self { Self::Lossy(cfg) => cfg.quality, Self::Lossless(cfg) => cfg.quality, } } ``` -------------------------------- ### Test Arithmetic Decoder Initialization and Decoding Source: https://docs.rs/zenwebp/latest/src/zenwebp/decoder/arithmetic.rs.html Demonstrates initializing the decoder with a buffer and performing sequential reads of flags, booleans, and literals. ```rust let mut buf = vec![[0u8; 4]; size.div_ceil(4)]; buf.as_mut_slice().as_flattened_mut()[..size].copy_from_slice(&data[..]); decoder.init(buf, size).unwrap(); let mut res = decoder.start_accumulated_result(); assert!(!decoder.read_flag().or_accumulate(&mut res)); assert!(decoder.read_bool(10).or_accumulate(&mut res)); assert!(!decoder.read_bool(250).or_accumulate(&mut res)); assert_eq!(1, decoder.read_literal(1).or_accumulate(&mut res)); assert_eq!(5, decoder.read_literal(3).or_accumulate(&mut res)); assert_eq!(64, decoder.read_literal(8).or_accumulate(&mut res)); assert_eq!(185, decoder.read_literal(8).or_accumulate(&mut res)); assert_eq!(31, decoder.read_literal(8).or_accumulate(&mut res)); decoder.check(res, ()).unwrap(); } ``` -------------------------------- ### Flush and Get Buffer Source: https://docs.rs/zenwebp/latest/src/zenwebp/encoder/arithmetic.rs.html Flushes remaining bits by padding with zeros and returns the final output buffer. ```rust pub(crate) fn flush_and_get_buffer(mut self) -> Vec { // Flush remaining bits by writing enough zero-padding. // VP8BitWriterFinish calls VP8PutBits(bw, 0, 9 - bw->nb_bits) let pad_bits = 9 - self.nb_bits; for _ in 0..pad_bits { self.write_bool(false, 128); } self.nb_bits = 0; self.flush(); self.buf } ``` -------------------------------- ### WebPDecoder::build Source: https://docs.rs/zenwebp/latest/src/zenwebp/decoder/api.rs.html Parses WebP headers and prepares for decoding. Use `info()` to inspect metadata before calling decode methods. ```APIDOC ## POST /websites/rs_zenwebp/WebPDecoder/build ### Description Parses the WebP headers and prepares for decoding. Use [`info()`](Self::info) to inspect metadata before calling decode methods. ### Method POST ### Endpoint /websites/rs_zenwebp/WebPDecoder/build ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (slice of u8) - Required - The WebP data to decode. ### Request Example ```json { "data": "your_webp_data_here" } ``` ### Response #### Success Response (200) - **WebPDecoder** (object) - A WebPDecoder instance ready for further operations. #### Response Example ```json { "decoder_instance": "..." } ``` ``` -------------------------------- ### Initialize BitWriter Source: https://docs.rs/zenwebp/latest/src/zenwebp/encoder/vp8l/bitwriter.rs.html Creates a new `BitWriter` instance. Use `with_capacity` for pre-allocation. ```rust pub fn new() -> Self { Self { buffer: Vec::new(), bits: 0, used: 0, } } ``` ```rust pub fn with_capacity(cap: usize) -> Self { Self { buffer: Vec::with_capacity(cap), bits: 0, used: 0, } } ``` -------------------------------- ### D4 Group Operations Source: https://docs.rs/zenwebp/latest/zenwebp/enum.Orientation.html Demonstrates D4 group operations like composition and inversion with code examples. ```APIDOC ## §D4 group operations `compose` implements group multiplication (verified against a full Cayley table). `inverse` returns the element that undoes the transformation. ```rust use zenpixels::Orientation; let combined = Orientation::Rotate90.then(Orientation::FlipH); assert_eq!(combined, Orientation::Transpose); let roundtrip = Orientation::Rotate90.compose(Orientation::Rotate90.inverse()); assert_eq!(roundtrip, Orientation::Identity); ``` ``` -------------------------------- ### Get Mutable Result Reference with as_mut Source: https://docs.rs/zenwebp/latest/zenwebp/encoder/type.EncodeResult.html Converts from &mut Result to Result<&mut T, &mut E>. ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### WebPDecoder::new_with_options Source: https://docs.rs/zenwebp/latest/src/zenwebp/decoder/api.rs.html Creates a new `WebPDecoder` from the data slice with the given options. ```APIDOC ## POST /websites/rs_zenwebp/WebPDecoder/new_with_options ### Description Creates a new `WebPDecoder` from the data slice with the specified decoding options. ### Method POST ### Endpoint /websites/rs_zenwebp/WebPDecoder/new_with_options ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (slice of u8) - Required - The WebP data to decode. - **webp_decode_options** (object) - Required - Options for decoding. - **use_scaling** (boolean) - Whether to use scaling. - **scaling_width** (integer) - The target width for scaling. - **scaling_height** (integer) - The target height for scaling. - **use_crop** (boolean) - Whether to use cropping. - **crop_x** (integer) - The x-coordinate for cropping. - **crop_y** (integer) - The y-coordinate for cropping. - **crop_width** (integer) - The width for cropping. - **crop_height** (integer) - The height for cropping. - **use_alpha_crop** (boolean) - Whether to use alpha cropping. - **alpha_crop_x** (integer) - The x-coordinate for alpha cropping. - **alpha_crop_y** (integer) - The y-coordinate for alpha cropping. - **alpha_crop_width** (integer) - The width for alpha cropping. - **alpha_crop_height** (integer) - The height for alpha cropping. - **use_icc_profile** (boolean) - Whether to use ICC profile. - **use_exif** (boolean) - Whether to use EXIF data. - **use_xmp** (boolean) - Whether to use XMP data. - **use_animation** (boolean) - Whether to decode animation frames. - **loop_count** (integer) - The number of times to loop the animation. - **loop_duration** (integer) - The duration of each loop. ### Request Example ```json { "data": "your_webp_data_here", "webp_decode_options": { "use_scaling": true, "scaling_width": 800, "scaling_height": 600, "use_crop": false, "use_alpha_crop": false, "use_icc_profile": true, "use_exif": true, "use_xmp": true, "use_animation": false, "loop_count": 0, "loop_duration": 0 } } ``` ### Response #### Success Response (200) - **WebPDecoder** (object) - A new WebPDecoder instance configured with the provided options. #### Response Example ```json { "decoder_instance": "..." } ``` ``` -------------------------------- ### Create New WebPMux Instance Source: https://docs.rs/zenwebp/latest/zenwebp/mux/struct.WebPMux.html Initializes a new WebPMux assembler with specified canvas dimensions. Use this when creating a WebP file from scratch. ```rust pub fn new(width: u32, height: u32) -> Self ``` -------------------------------- ### Get Number of Animation Frames Source: https://docs.rs/zenwebp/latest/zenwebp/mux/struct.WebPMux.html Returns the total number of animation frames currently stored in the mux assembler. ```rust pub fn num_frames(&self) -> u32 ``` -------------------------------- ### Compare Palette Sorting Methods Source: https://docs.rs/zenwebp/latest/src/zenwebp/encoder/vp8l/encode.rs.html Compares the output of VP8L encoding using Palette mode with MinimizeDelta and Lexicographic palette sorting. Asserts that both methods produce valid VP8L output. ```rust let colors: [[u8; 3]; 4] = [[10, 20, 30], [40, 50, 60], [70, 80, 90], [100, 110, 120]]; let w = 8usize; let h = 8usize; let mut pixels = Vec::with_capacity(w * h * 3); for i in 0..(w * h) { let c = colors[i % 4]; pixels.extend_from_slice(&c); } let mut argb: Vec = pixels .chunks_exact(3) .map(|p| make_argb(255, p[0], p[1], p[2])) .collect(); let config = Vp8lConfig::default(); // MinimizeDelta sorting let mut argb_md = argb.clone(); let crunch_md = CrunchConfig { mode: CrunchMode::Palette, palette_sorting: PaletteSorting::MinimizeDelta, }; let result_md = encode_argb_single_config( &mut argb_md, w, h, false, &config, &crunch_md, &enough::Unstoppable, ) .unwrap(); // Lexicographic sorting let crunch_lex = CrunchConfig { mode: CrunchMode::Palette, palette_sorting: PaletteSorting::Lexicographic, }; let result_lex = encode_argb_single_config( &mut argb, w, h, false, &config, &crunch_lex, &enough::Unstoppable, ) .unwrap(); // Both should be valid VP8L assert_eq!(result_md[0], 0x2f); assert_eq!(result_lex[0], 0x2f); ```