### Example: Basic Resampling with libsoxr-rs Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/libsoxr/soxr/struct.Soxr.html Demonstrates a basic audio resampling operation using libsoxr-rs. It shows how to create a Soxr resampler, define source and target buffers, and process the audio data. The example highlights the use of `process` for both data conversion and end-of-input signaling. ```rust // upscale factor 2, one channel with all the defaults let soxr = Soxr::create(1.0, 2.0, 1, None, None, None).unwrap(); // source data, taken from 1-single-block.c of libsoxr examples. let source: [f32; 48] = [0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0]; // create room for 2*48 = 96 samples let mut target: [f32; 96] = [0.0; 96]; // Two runs. First run will convert the source data into target. // Last run with None is to inform resampler of end-of-input so it can clean up soxr.process(Some(&source), &mut target).unwrap(); soxr.process::(None, &mut target[0..]).unwrap(); ``` -------------------------------- ### Complete Stereo Downsampling Example with libsoxr-rs Source: https://context7.com/lrbalt/libsoxr-rs/llms.txt Provides a full example of downsampling stereo audio from 96kHz to 44.1kHz using libsoxr-rs. It configures input/output specifications, quality settings, and runtime parameters before processing audio data and flushing remaining samples. Error handling and final state checks are included. ```rust use libsoxr::{Soxr, Datatype, IOSpec, QualitySpec, QualityRecipe, QualityFlags, RuntimeSpec}; // Configure all specifications let io_spec = IOSpec::new(Datatype::Float32I, Datatype::Float32I); let quality_spec = QualitySpec::new(&QualityRecipe::VeryHigh, QualityFlags::ROLLOFF_SMALL); let runtime_spec = RuntimeSpec::new(4); // Create high-quality downsampler let soxr = Soxr::create( 96000.0, // Input rate 44100.0, // Output rate 2, // Stereo Some(&io_spec), Some(&quality_spec), Some(&runtime_spec) ).unwrap(); // Input: 1 second of 96kHz stereo = 192000 samples let input: Vec = vec![0.5; 192000]; // Output: ~1 second of 44.1kHz stereo = 88200 samples (calculated: 192000 * 44100 / 96000) let mut output: Vec = vec![0.0; 90000]; // Slightly larger for safety // Process audio let (input_used, output_generated) = soxr.process(Some(&input), &mut output).unwrap(); println!("Processed {} samples, generated {} samples", input_used, output_generated); // Finalize and flush any remaining samples let (_, final_samples) = soxr.process::(None, &mut output).unwrap(); println!("Final flush generated {} samples", final_samples); // Check final state if let Some(error) = soxr.error() { eprintln!("Resampling error: {}", error); } else { println!("Resampling completed successfully"); println!("Total clips: {}", soxr.num_clips()); } ``` -------------------------------- ### Create libsoxr Resampler and Get Version/Engine (Rust) Source: https://context7.com/lrbalt/libsoxr-rs/llms.txt Demonstrates how to create a basic libsoxr resampler instance by specifying input and output sample rates, and the number of channels. It also shows how to retrieve the library version and the name of the resampling engine being used. ```rust use libsoxr::Soxr; // Create a resampler: 44.1kHz to 48kHz, stereo (2 channels) let soxr = Soxr::create(44100.0, 48000.0, 2, None, None, None).unwrap(); // Get library version let version = Soxr::version(); println!("Using libsoxr version: {}", version); // Query the resampling engine being used let engine = soxr.engine(); println!("Resampler engine: {}", engine); ``` -------------------------------- ### Configure Data Types with IOSpec (Rust) Source: https://context7.com/lrbalt/libsoxr-rs/llms.txt Shows how to specify custom input and output data types for the resampler using `IOSpec`. This example configures a resampler to accept `f32` input and produce `f64` output with interleaved channels. ```rust use libsoxr::{Soxr, Datatype, IOSpec}; // Configure f32 input and f64 output with interleaved channels let io_spec = IOSpec::new(Datatype::Float32I, Datatype::Float64I); // Create resampler with custom IO specification let soxr = Soxr::create(44100.0, 48000.0, 2, Some(&io_spec), None, None).unwrap(); // Input data as f32 let input: [f32; 8] = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]; // Output buffer as f64 let mut output: [f64; 10] = [0.0; 10]; // Process with different types let (in_used, out_generated) = soxr.process(Some(&input), &mut output).unwrap(); soxr.process::(None, &mut output).unwrap(); println!("Converted {} f32 samples to {} f64 samples", in_used, out_generated); ``` -------------------------------- ### Basic Audio Resampling with Process Method (Rust) Source: https://context7.com/lrbalt/libsoxr-rs/llms.txt Illustrates basic audio resampling using the `process` method. This example upsamples mono audio from 1Hz to 2Hz and demonstrates the use of source and target buffers, including finalizing the process to flush remaining data. ```rust use libsoxr::Soxr; // Upsample by factor of 2: 1Hz to 2Hz, mono let soxr = Soxr::create(1.0, 2.0, 1, None, None, None).unwrap(); // Source audio data (48 samples) let source: [f32; 48] = [ 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, ]; // Allocate output buffer (2x size for 2x upsampling) let mut target: [f32; 96] = [0.0; 96]; // Process the audio data let (input_used, output_generated) = soxr.process(Some(&source), &mut target).unwrap(); println!("Processed {} input samples, generated {} output samples", input_used, output_generated); // Always finalize with None to flush remaining data soxr.process::(None, &mut target[0..]).unwrap(); // target now contains resampled audio ``` -------------------------------- ### Split Channel Processing with IOSpec (Rust) Source: https://context7.com/lrbalt/libsoxr-rs/llms.txt Demonstrates processing audio with a split (non-interleaved) channel layout. This example uses `Float32S` for input and `Float64S` for output to handle stereo audio where each channel's data is in a separate contiguous block. ```rust use libsoxr::{Soxr, Datatype, IOSpec}; // Use Float32S and Float64S for split channels let io_spec = IOSpec::new(Datatype::Float32S, Datatype::Float64S); // Create stereo resampler with split channels let soxr = Soxr::create(1.0, 2.0, 2, Some(&io_spec), None, None).unwrap(); // Input: 48 samples per channel, 96 total (first 48 = left, next 48 = right) let source: [f32; 96] = [0.0; 96]; // Initialize with your audio data // Output: 96 samples per channel, 192 total let mut target: [f64; 192] = [0.0; 192]; // Process split channel audio soxr.process(Some(&source), &mut target).unwrap(); soxr.process::(None, &mut target).unwrap(); // target now contains resampled split-channel audio ``` -------------------------------- ### Implementing and Using SoxrFunction in Rust Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/libsoxr/soxr/type.SoxrFunction.html Demonstrates how to create a custom input function (`input_fn`) that supplies data to the SOXR library. It shows how to define a state struct, implement the function logic, and register it with the `Soxr` instance using `set_input`. This example highlights error handling and end-of-input conditions. ```rust use libsoxr::{Error, ErrorType, Soxr, SoxrFunction}; struct State { // data for input function to supply Soxr with source samples. // In this case just a value, but you could put a handle to a FLAC file into this. value: f32 } let input_fn = |state: &mut State, buffer: &mut [f32], samples: usize| { for sample in buffer.iter_mut().take(samples) { *sample = state.value; } // if end-of-input: return Ok(0); // if error: Err(Error::new(Some("input_fn".into()), ErrorType::ProcessError("Unexpected end of input".into()))) Ok(samples) }; let mut soxr = Soxr::create(1.0, 2.0, 1, None, None, None).unwrap(); let mut state = State { value: 1.0 }; assert!(soxr.set_input(input_fn, Some(&mut state), 100).is_ok()); ``` -------------------------------- ### Error Handling in Streaming Input Functions with libsoxr-rs Source: https://context7.com/lrbalt/libsoxr-rs/llms.txt Gracefully handle errors within streaming input callbacks using libsoxr's Error and ErrorType. This example demonstrates how to simulate an error condition and check for it after resampling. Dependencies include the libsoxr crate. ```rust use libsoxr::{Soxr, SoxrFunction, Error, ErrorType, Result}; struct AudioState { error_occurred: bool, sample_count: usize, } let input_fn: SoxrFunction = |state: &mut AudioState, buffer: &mut [f32], samples: usize| { // Simulate an error condition if state.sample_count > 1000 { state.error_occurred = true; return Err(Error::new( Some("input_fn".into()), ErrorType::ProcessError("Sample limit exceeded".into()) )); } // Fill buffer with test data for sample in buffer.iter_mut().take(samples) { *sample = 0.5; } state.sample_count += samples; Ok(samples) }; let mut soxr = Soxr::create(1.0, 2.0, 1, None, None, None).unwrap(); let mut state = AudioState { error_occurred: false, sample_count: 0 }; soxr.set_input(input_fn, Some(&mut state), 100).unwrap(); let mut output: [f32; 200] = [0.0; 200]; let result = soxr.output(&mut output, 200); // Check for errors if let Some(error_msg) = soxr.error() { println!("Resampling error: {}", error_msg); } // Check custom state for additional error information if state.error_occurred { println!("Custom error flag was set"); } ``` -------------------------------- ### Rust: Implement Any trait Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/libsoxr/spec/struct.QualityFlags.html This Rust code shows a blanket implementation of the `Any` trait for any type `T` that is `'static` and sized. The `Any` trait provides a way to get the `TypeId` of a value, enabling runtime type reflection. This is a common pattern in Rust for dynamic dispatch and type checking. ```rust impl Any for T where T: 'static + ?Sized, { fn type_id(&self) -> TypeId { // Implementation details for getting TypeId unimplemented!() } } ``` -------------------------------- ### Soxr Utility Functions API Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/src/libsoxr/soxr.rs.html Provides utility functions for interacting with the SoXR library, such as getting the version, setting errors, and querying status. ```APIDOC ## GET /soxr/version ### Description Retrieves the version string of the underlying libsoxr library. ### Method GET ### Endpoint /soxr/version ### Parameters (None) ### Response #### Success Response (200) - **version** (string) - The version string of the libsoxr library. #### Response Example ```json { "version": "0.1.3" } ``` ## POST /soxr/{handle}/set_error ### Description Sets an error message for the specified SoXR instance. This is typically used internally to report errors during operations. ### Method POST ### Endpoint /soxr/{handle}/set_error ### Parameters #### Path Parameters - **handle** (pointer) - Required - The internal handle of the SoXR instance. #### Request Body - **msg** (string) - Required - The error message string to set. ### Response #### Success Response (200) - **status** (string) - Indicates success, typically "OK" or similar. #### Response Example ```json { "status": "OK" } ``` #### Error Response (500) - **Error** (object) - An error occurred while setting the error message. - **error_type** (string) - The type of error (e.g., ChangeError). - **message** (string) - A descriptive error message. #### Error Response Example ```json { "error_type": "ChangeError", "message": "Failed to set error message: invalid handle" } ``` ## POST /soxr/{handle}/set_num_channels ### Description Changes the number of audio channels for an existing SoXR instance. This operation might not be supported by all configurations or might require reinitialization. ### Method POST ### Endpoint /soxr/{handle}/set_num_channels ### Parameters #### Path Parameters - **handle** (pointer) - Required - The internal handle of the SoXR instance. #### Request Body - **num_channels** (u32) - Required - The new number of audio channels. ### Response #### Success Response (200) - **status** (string) - Indicates success, typically "OK" or similar. #### Response Example ```json { "status": "OK" } ``` #### Error Response (500) - **Error** (object) - An error occurred while changing the number of channels. - **error_type** (string) - The type of error (e.g., ChangeError). - **message** (string) - A descriptive error message. #### Error Response Example ```json { "error_type": "ChangeError", "message": "Failed to set number of channels: operation not supported" } ``` ## GET /soxr/{handle}/error ### Description Retrieves the last recorded error message for a specific SoXR instance, if any. ### Method GET ### Endpoint /soxr/{handle}/error ### Parameters #### Path Parameters - **handle** (pointer) - Required - The internal handle of the SoXR instance. ### Response #### Success Response (200) - **error_message** (string or null) - The error message string, or null if no error is present. #### Response Example ```json { "error_message": "Input buffer underrun" } ``` Or: ```json { "error_message": null } ``` ## GET /soxr/{handle}/num_clips ### Description Queries the clip counter for the SoXR instance. This counter indicates the number of times the output signal has been clipped. ### Method GET ### Endpoint /soxr/{handle}/num_clips ### Parameters #### Path Parameters - **handle** (pointer) - Required - The internal handle of the SoXR instance. ### Response #### Success Response (200) - **count** (usize) - The number of clipping occurrences. #### Response Example ```json { "count": 5 } ``` ## GET /soxr/{handle}/delay ### Description Queries the current delay in output samples for the SoXR instance. This is useful for synchronization purposes. ### Method GET ### Endpoint /soxr/{handle}/delay ### Parameters #### Path Parameters - **handle** (pointer) - Required - The internal handle of the SoXR instance. ### Response #### Success Response (200) - **delay** (f64) - The current delay in output samples. #### Response Example ```json { "delay": 128.0 } ``` ## GET /soxr/{handle}/engine ### Description Retrieves the name of the resampling engine currently being used by the SoXR instance. ### Method GET ### Endpoint /soxr/{handle}/engine ### Parameters #### Path Parameters - **handle** (pointer) - Required - The internal handle of the SoXR instance. ### Response #### Success Response (200) - **engine_name** (string) - The name of the resampling engine. #### Response Example ```json { "engine_name": "sox-hq-float" } ``` ## POST /soxr/{handle}/clear ### Description Resets the SoXR instance to its initial state, allowing it to process a new signal with the same configuration. ### Method POST ### Endpoint /soxr/{handle}/clear ### Parameters #### Path Parameters - **handle** (pointer) - Required - The internal handle of the SoXR instance. ### Response #### Success Response (200) - **status** (string) - Indicates success, typically "OK" or similar. #### Response Example ```json { "status": "OK" } ``` #### Error Response (500) - **Error** (object) - An error occurred during the clear operation. - **error_type** (string) - The type of error (e.g., ChangeError). - **message** (string) - A descriptive error message. #### Error Response Example ```json { "error_type": "ChangeError", "message": "Failed to clear SoXR state: invalid handle" } ``` ## POST /soxr/{handle}/set_io_ratio ### Description Configures the SoXR instance for variable-rate resampling by setting the I/O ratio and slew length. This is used for dynamic rate changes during processing. ### Method POST ### Endpoint /soxr/{handle}/set_io_ratio ### Parameters #### Path Parameters - **handle** (pointer) - Required - The internal handle of the SoXR instance. #### Request Body - **io_ratio** (f64) - Required - The ratio of output samples to input samples. - **slew_len** (usize) - Required - The length of the slew filter in samples. ### Response #### Success Response (200) - **status** (string) - Indicates success, typically "OK" or similar. #### Response Example ```json { "status": "OK" } ``` #### Error Response (500) - **Error** (object) - An error occurred while setting the I/O ratio. - **error_type** (string) - The type of error (e.g., ChangeError). - **message** (string) - A descriptive error message. #### Error Response Example ```json { "error_type": "ChangeError", "message": "Failed to set I/O ratio: slew length too large" } ``` ``` -------------------------------- ### Query Resampling Engine Name Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/src/libsoxr/soxr.rs.html Gets the name of the currently active resampling engine used by SoX-R. Different engines may offer varying performance and quality characteristics. ```rust /// Query resampling engine name. pub fn engine(&self) -> String { from_const("Soxr::engine", unsafe { soxr::soxr_engine(self.soxr) }) .unwrap() .to_string() } ``` -------------------------------- ### Get libsoxr Library Version - Rust Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/libsoxr/soxr/struct.Soxr.html Retrieves the version string of the linked libsoxr library. This function returns a static string slice representing the library version. ```rust pub fn version() -> &'static str ``` -------------------------------- ### Get inner soxr_runtime_spec_t from RuntimeSpec in Rust Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/libsoxr/spec/struct.RuntimeSpec.html Returns a reference to the inner `soxr_runtime_spec_t` struct from a RuntimeSpec instance. This method is useful for interacting with the underlying C API of SoX Resampler. ```rust pub fn soxr_spec(&self) -> &soxr_runtime_spec_t ``` -------------------------------- ### Create and Use Soxr Instance in Rust Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/src/libsoxr/lib.rs.html This Rust code demonstrates how to create an instance of the `Soxr` struct, perform sample-rate conversion, and process audio data. It initializes the `Soxr` with a specified upscale factor, then converts source data to a target buffer, and handles the end-of-input signal. It showcases the core functionality of the libsoxr wrapper. ```rust #[macro_use] extern crate bitflags; pub mod datatype; pub mod soxr; pub mod spec; mod error_handling; mod wrapper_helpers; pub use crate::{ datatype::Datatype, error_handling::{Error, ErrorType, Result}, soxr::{Soxr, SoxrFunction}, spec::{IOSpec, QualityFlags, QualityRecipe, QualitySpec, RuntimeSpec}, }; //! # libsoxr-rs //! //! This library is a thin wrapper for \[libsoxr\](https://sourceforge.net/projects/soxr/) which is //! a "High quality, one-dimensional sample-rate conversion library". //! //! For direct access to the libsoxr functions, you can use the \[libsoxr-sys\](https://github.com/lrbalt/libsoxr-sys) crate. //! //! This wrapper library is licensed the same as libsoxr itself: LGPLv2. //! //! The documentation can be found \[here\](https://lrbalt.github.io/libsoxr-rs/libsoxr/). //! //! # Install //! //! add the following to your Cargo.toml: //! ```toml //! [dependencies] //! libsoxr = "0.2" //! ``` //! //! # Example //! //! ```rust //! # use libsoxr::Soxr; //! // upscale factor 2, one channel with all the defaults //! let soxr = Soxr::create(1.0, 2.0, 1, None, None, None).unwrap(); //! //! // source data, taken from 1-single-block.c of libsoxr examples. //! let source: [f32; 48] = [0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, //! 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, //! 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, //! -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0]; //! //! // create room for 2*48 = 96 samples //! let mut target: [f32; 96] = [0.0; 96]; //! //! // Two runs. First run will convert the source data into target. //! // Last run with None is to inform resampler of end-of-input so it can clean up //! soxr.process(Some(&source), &mut target).unwrap(); //! soxr.process::(None, &mut target[0..]).unwrap(); //! //! // just print the values in target //! for s in target.iter() { //! print!("{:?}\t", s) //! } //! ``` ``` -------------------------------- ### Rust: Get Type ID with Any trait Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/libsoxr/spec/struct.QualitySpec.html Retrieves the unique `TypeId` of a given type using the `Any` trait. This is useful for runtime type checking and downcasting. It requires the type to implement the `Any` trait. ```rust trait Any { fn type_id(&self) -> TypeId; } ``` -------------------------------- ### Get underlying soxr_io_spec_t in Rust Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/libsoxr/spec/struct.IOSpec.html This method returns a reference to the inner `soxr_io_spec_t` struct. This can be useful for advanced usage or when interacting with C APIs that expect this type. It's a reference, so it borrows the IOSpec immutably. ```rust pub fn soxr_spec(&self) -> &soxr_io_spec_t ``` -------------------------------- ### Variable Rate Resampling with libsoxr-rs Source: https://context7.com/lrbalt/libsoxr-rs/llms.txt Demonstrates how to create a resampler that can dynamically adjust its input-to-output ratio during processing using libsoxr-rs. This is useful for scenarios where the resampling rate needs to change mid-stream. It utilizes the `QualityFlags::VR` for variable rate operations. ```rust use libsoxr::{Soxr, QualitySpec, QualityRecipe, QualityFlags}; // Create quality spec with VR (Variable Rate) flag let quality_spec = QualitySpec::new( &QualityRecipe::High, QualityFlags::VR ); // Create variable-rate resampler let mut soxr = Soxr::create(44100.0, 48000.0, 2, None, Some(&quality_spec), None).unwrap(); // Change the I/O ratio dynamically // New ratio: 2.0, slew length: 100 samples let result = soxr.set_io_ratio(2.0, 100); match result { Ok(_) => println!("I/O ratio changed successfully"), Err(e) => println!("Failed to change ratio: {}", e), } // Continue processing with new ratio ``` -------------------------------- ### Set Variable I/O Ratio Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/src/libsoxr/soxr.rs.html Configures the SoX-R engine for variable-rate resampling. This function allows dynamic adjustment of the input-to-output sample rate ratio and specifies a slew length for smooth transitions. Refer to the libsoxr examples for detailed usage. ```rust /// For variable-rate resampling. /// See [example # 5](https://sourceforge.net/p/soxr/code/ci/master/tree/examples/5-variable-rate.c) /// of libsoxr repository for how to create a /// variable-rate resampler and how to use this function. pub fn set_io_ratio(&mut self, io_ratio: f64, slew_len: usize) -> Result<()>{ let error = unsafe { soxr::soxr_set_io_ratio(self.soxr, io_ratio, slew_len) }; if error.is_null() { Ok(()) } else { Err(Error::new( Some("Soxr::set_io_ratio".into()), ErrorType::ChangeError( from_const("Soxr::set_io_ratio", error).unwrap().to_string(), ), )) } } ``` -------------------------------- ### QualityFlags Formatting and Ordering API Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/libsoxr/spec/struct.QualityFlags.html This section details the implementation of traits related to formatting, ordering, and equality for the QualityFlags struct. It includes methods for displaying QualityFlags in octal format, comparing QualityFlags for ordering, and checking for equality. ```APIDOC ## QualityFlags Formatting and Ordering ### Description This API documentation covers the `QualityFlags` struct and its implementations of standard Rust traits for formatting, ordering, and equality checks. ### Methods #### `fmt` (Octal Formatting) * **Description**: Formats the `QualityFlags` value using the given formatter in octal representation. * **Method**: (Implicitly called by `Octal` trait) * **Endpoint**: N/A (Method of a struct) #### `cmp` (Comparison) * **Description**: Compares `self` with `other` `QualityFlags` and returns an `Ordering` (Less, Equal, Greater). * **Method**: `cmp` (Part of `Ord` trait) * **Endpoint**: N/A #### `max` (Maximum Value) * **Description**: Compares two `QualityFlags` values and returns the maximum. * **Method**: `max` (Part of `Ord` trait) * **Endpoint**: N/A #### `min` (Minimum Value) * **Description**: Compares two `QualityFlags` values and returns the minimum. * **Method**: `min` (Part of `Ord` trait) * **Endpoint**: N/A #### `clamp` (Restrict Value) * **Description**: Restricts a `QualityFlags` value to be within a specified interval [min, max]. Note: This is a nightly-only experimental API. * **Method**: `clamp` (Part of `Ord` trait) * **Endpoint**: N/A #### `eq` (Equality Check) * **Description**: Tests if `self` and `other` `QualityFlags` are equal. Used by the `==` operator. * **Method**: `eq` (Part of `PartialEq` trait) * **Endpoint**: N/A #### `ne` (Inequality Check) * **Description**: Tests if `self` and `other` `QualityFlags` are not equal. Used by the `!=` operator. * **Method**: `ne` (Part of `PartialEq` trait) * **Endpoint**: N/A ### Parameters * **`self`**: Reference to the `QualityFlags` instance. * **`other`**: Reference to another `QualityFlags` instance for comparison or equality checks. * **`f`**: A mutable reference to a `Formatter` for output. * **`min`**: The minimum bound for the `clamp` method. * **`max`**: The maximum bound for the `clamp` method. ### Request Example (No direct request examples as these are method implementations within Rust code) ### Response * **`fmt`**: Returns a `Result` indicating success or failure of the formatting operation. * **`cmp`**: Returns an `Ordering` enum (`Less`, `Equal`, `Greater`). * **`max`, `min`, `clamp`**: Returns a `QualityFlags` instance. * **`eq`, `ne`**: Returns a `bool` (`true` if equal/not equal, `false` otherwise). ### Response Example (No direct response examples as these are method implementations within Rust code) ``` -------------------------------- ### Managing Resampler State with libsoxr-rs Source: https://context7.com/lrbalt/libsoxr-rs/llms.txt Illustrates how to query and modify the state of a libsoxr-rs resampler during operation. This includes checking for audio delay, counting clipping events, retrieving error messages, clearing the resampler's internal state, and dynamically changing the number of audio channels. ```rust use libsoxr::Soxr; let mut soxr = Soxr::create(44100.0, 48000.0, 2, None, None, None).unwrap(); // Query current delay in output samples let delay = soxr.delay(); println!("Current delay: {} samples", delay); // Query clipping counter let clips = soxr.num_clips(); println!("Number of clips: {}", clips); // Check for errors if let Some(error_msg) = soxr.error() { println!("Error occurred: {}", error_msg); } else { println!("No errors"); } // Clear resampler state (ready for fresh signal, same config) soxr.clear().unwrap(); // Change number of channels dynamically soxr.set_num_channels(1).unwrap(); // Change from stereo to mono ``` -------------------------------- ### Configure Resampling Quality with libsoxr-rs Source: https://context7.com/lrbalt/libsoxr-rs/llms.txt Configure the resampling quality using QualitySpec, QualityRecipe, and QualityFlags. This allows for fine-tuning the precision and characteristics of the audio resampling algorithm. Dependencies include the libsoxr crate. ```rust use libsoxr::{Soxr, QualitySpec, QualityRecipe, QualityFlags}; // Create high-quality spec with precise clock let quality_spec = QualitySpec::new( &QualityRecipe::VeryHigh, QualityFlags::HI_PREC_CLOCK | QualityFlags::DOUBLE_PRECISION ); // Create resampler with custom quality let soxr = Soxr::create(96000.0, 44100.0, 2, None, Some(&quality_spec), None).unwrap(); // Available quality recipes: // - QualityRecipe::Quick - Fast cubic interpolation // - QualityRecipe::Low - 16-bit with larger rolloff // - QualityRecipe::Medium - 16-bit with medium rolloff // - QualityRecipe::High - High quality (default) // - QualityRecipe::VeryHigh - Very high quality // Available quality flags: // - QualityFlags::ROLLOFF_SMALL - <= 0.01 dB // - QualityFlags::ROLLOFF_MEDIUM - <= 0.35 dB // - QualityFlags::ROLLOFF_NONE - Chebyshev bandwidth // - QualityFlags::HI_PREC_CLOCK - Increase irrational ratio accuracy // - QualityFlags::DOUBLE_PRECISION - Use double precision calculations // - QualityFlags::VR - Variable-rate resampling ``` -------------------------------- ### Rust: Implement PartialOrd for QualityFlags Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/libsoxr/spec/struct.QualityFlags.html Implements partial ordering comparisons for QualityFlags, allowing for less than, greater than, less than or equal to, and greater than or equal to checks. These methods are used by the relational operators (<, >, <=, >=). ```rust impl PartialOrd for QualityFlags { fn partial_cmp(&self, other: &QualityFlags) -> Option { // Implementation details for comparison unimplemented!("partial_cmp not fully implemented"); } fn lt(&self, other: &QualityFlags) -> bool { // Implementation for less than self.partial_cmp(other) == Some(Ordering::Less) } fn le(&self, other: &QualityFlags) -> bool { // Implementation for less than or equal to match self.partial_cmp(other) { Some(Ordering::Less) | Some(Ordering::Equal) => true, _ => false, } } fn gt(&self, other: &QualityFlags) -> bool { // Implementation for greater than self.partial_cmp(other) == Some(Ordering::Greater) } fn ge(&self, other: &QualityFlags) -> bool { // Implementation for greater than or equal to match self.partial_cmp(other) { Some(Ordering::Greater) | Some(Ordering::Equal) => true, _ => false, } } } ``` -------------------------------- ### QualityFlags Conversion Methods Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/libsoxr/spec/struct.QualityFlags.html Methods for converting raw bit representations into QualityFlags, with different behaviors for handling unknown bits. ```APIDOC ## QualityFlags Conversion Methods ### `from_bits(bits: c_ulong) -> Option` Converts from underlying bit representation, returning `None` if the representation contains bits that do not correspond to a flag. ### `from_bits_truncate(bits: c_ulong) -> QualityFlags` Converts from underlying bit representation, dropping any bits that do not correspond to flags. ### `from_bits_unchecked(bits: c_ulong) -> QualityFlags` Converts from underlying bit representation, preserving all bits (even those not corresponding to a defined flag). This is an unsafe operation. ``` -------------------------------- ### Soxr Input Trampoline Function Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/src/libsoxr/soxr.rs.html An external C-callable function used internally by Soxr to get input samples. It acts as a bridge between the C API and the Rust closure provided via `set_input`. This function manages the unsafe pointer conversions and calls the user-supplied input function. ```rust extern "C" fn input_trampoline( input_fn_state: *mut ::std::os::raw::c_void, data: *mut soxr::soxr_in_t, requested_len: usize, ) -> usize { let trampoline_data = input_fn_state as *mut TrampolineData; unsafe { assert_eq!((*trampoline_data).check, "trampoline"); let input_fn = (*trampoline_data).input_fn; let input_data: &mut [T] = std::slice::from_raw_parts_mut( (*trampoline_data).input_buffer.as_mut_slice().as_ptr() as *mut T, requested_len, ); let result = input_fn((*trampoline_data).input_state, input_data, requested_len); match result { Ok(samples_or_zero) => { *data = (*trampoline_data).input_buffer.as_mut_slice().as_ptr() as soxr::soxr_in_t; samples_or_zero } Err(Error(_, e)) => { (*trampoline_data).last_error = Some(e); 0 } } } } ``` -------------------------------- ### Implement PartialEq for QualityFlags in Rust Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/libsoxr/spec/struct.QualityFlags.html This code implements the PartialEq trait for QualityFlags, enabling the comparison of two QualityFlags instances for equality. It provides the eq method for checking equality (==) and the ne method for checking inequality (!=). ```Rust impl PartialEq for QualityFlags { fn eq(&self, other: &QualityFlags) -> bool { // Implementation details for equality check } fn ne(&self, other: &QualityFlags) -> bool { // Implementation details for inequality check } } ``` -------------------------------- ### Create SoX-R Resampler Instance Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/src/libsoxr/soxr.rs.html Creates a new SoX-R resampler instance with specified audio parameters. It takes input and output rates, number of channels, and optional I/O, quality, and runtime specifications. Returns a Result containing the Soxr object on success or an Error on failure. ```rust /// let quality_spec = QualitySpec::new(&QualityRecipe::VeryHigh, QualityFlags::HI_PREC_CLOCK); /// let runtime_spec = RuntimeSpec::new(4); /// let mut soxr = Soxr::create(1.0, 2.0, 1, Some(&io_spec), Some(&quality_spec), Some(&runtime_spec)); /// assert!(soxr.is_ok()); ///``` pub fn create( input_rate: f64, output_rate: f64, num_channels: u32, io_spec: Option<&IOSpec>, quality_spec: Option<&QualitySpec>, runtime_spec: Option<&RuntimeSpec>, ) -> Result { let error: *mut *const c_char = ::std::ptr::null_mut(); let q = quality_spec.map_or(ptr::null(), |spec| spec.soxr_spec()); let io = io_spec.map_or(ptr::null(), |spec| spec.soxr_spec()); let rt = runtime_spec.map_or(ptr::null(), |spec| spec.soxr_spec()); let soxr = unsafe { soxr::soxr_create(input_rate, output_rate, num_channels, error, io, q, rt) }; if error.is_null() { Ok(Soxr { soxr, channels: num_channels, error: CString::new("").unwrap(), }) } else { let error = unsafe { *error }; Err(Error::new( Some("Soxr::new".into()), ErrorType::CreateError(from_const("Soxr::new", error).unwrap().to_string()), )) } } ``` -------------------------------- ### QualityFlags Trait Implementations Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/libsoxr/spec/struct.QualityFlags.html Implementation of standard traits for QualityFlags, such as Binary formatting. ```APIDOC ## QualityFlags Trait Implementations ### `impl Binary for QualityFlags` #### `fmt(&self, f: &mut Formatter<'_>) -> Result` Formats the value using the given formatter for binary representation. ``` -------------------------------- ### FromIterator for QualityFlags Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/libsoxr/spec/struct.QualityFlags.html Implementation of FromIterator for QualityFlags, allowing creation from an iterator of QualityFlags. ```APIDOC ## FromIterator for QualityFlags ### Description Creates a `QualityFlags` value from an iterator of `QualityFlags`. ### Method `from_iter` ### Endpoint N/A (Method on a struct) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "iterator": "T where T: IntoIterator" } ``` ### Response #### Success Response (200) - **QualityFlags** (struct) - The newly created QualityFlags value. #### Response Example ```json { "QualityFlags": "{ ... }" } ``` ``` -------------------------------- ### Create Soxr Resampler Instance - Rust Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/libsoxr/soxr/struct.Soxr.html Creates a new Soxr resampler instance with specified input and output rates, number of channels, and optional I/O, quality, and runtime specifications. If optional specifications are not provided, default values are used. This method returns a Result, indicating success or potential failure during creation. ```rust use libsoxr::{Datatype, IOSpec, QualitySpec, RuntimeSpec, Soxr, QualityRecipe, QualityFlags}; let io_spec = IOSpec::new(Datatype::Float32I, Datatype::Float64I); let quality_spec = QualitySpec::new(&QualityRecipe::VeryHigh, QualityFlags::HI_PREC_CLOCK); let runtime_spec = RuntimeSpec::new(4); let mut soxr = Soxr::create(1.0, 2.0, 1, Some(&io_spec), Some(&quality_spec), Some(&runtime_spec)); assert!(soxr.is_ok()); ``` -------------------------------- ### From Trait Implementation Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/libsoxr/struct.Error.html Enables conversion from one type to another. ```APIDOC ## `from` Method ### Description Performs the conversion from type `T` to type `T`. ### Method `pub fn from(t: T) -> T` ### Endpoint N/A (Rust method) ### Parameters * `t` (T) - The value to convert. ### Request Example ```rust let value = 10; let converted_value = i32::from(value); println!("{}", converted_value); ``` ### Response #### Success Response * `T` - The converted value. ``` -------------------------------- ### QualitySpec Struct API Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/libsoxr/spec/struct.QualitySpec.html Documentation for the QualitySpec struct, its constructor, and methods. ```APIDOC ## Struct QualitySpec ### Description Wrapper for `soxr_quality_spec_t`. ### Methods #### `new` - **Method:** `new` - **Description:** Creates a new `QualitySpec` with the specified quality and flags. - **Parameters:** - `quality` (QualityRecipe) - Required - The desired quality recipe for resampling. - `flags` (QualityFlags) - Required - Flags to modify the quality specification. - **Returns:** `QualitySpec` - A new instance of `QualitySpec`. #### `soxr_spec` - **Method:** `soxr_spec` - **Description:** Returns a reference to the inner `soxr_quality_spec_t` struct. - **Returns:** `&soxr_quality_spec_t` - A reference to the underlying C struct. ### Trait Implementations #### `Debug` - **Description:** Implements the `Debug` trait for `QualitySpec`, allowing it to be formatted for debugging purposes. - **Method:** `fmt` - **Parameters:** - `f` (Formatter) - A mutable reference to a formatter. - **Returns:** `Result` - The result of the formatting operation. #### `RefUnwindSafe` - **Description:** Implements the `RefUnwindSafe` trait. #### `Send` - **Description:** Implements the `Send` trait. #### `Sync` - **Description:** Implements the `Sync` trait. #### `Unpin` - **Description:** Implements the `Unpin` trait. #### `UnwindSafe` - **Description:** Implements the `UnwindSafe` trait. ``` -------------------------------- ### Into Trait Implementation Source: https://github.com/lrbalt/libsoxr-rs/blob/master/docs/libsoxr/struct.Error.html Enables conversion into another type, provided the target type implements `From`. ```APIDOC ## `into` Method ### Description Performs the conversion from type `T` to type `U`. ### Method `pub fn into(self) -> U` ### Endpoint N/A (Rust method) ### Parameters * `self` (T) - The value to convert. ### Request Example ```rust let value = String::from("hello"); let converted_value: Vec = value.into(); // Requires Vec to implement From println!("{:?}", converted_value); ``` ### Response #### Success Response * `U` - The converted value. ```