audio_samples 0.10.2

A typed audio processing library for Rust that treats audio as a first-class, invariant-preserving object rather than an unstructured numeric buffer.
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Development Commands

### Build Commands

- `cargo build` - Build with core features only
- `cargo build --features full` - Build with all features enabled
- `cargo build --features "fft plotting"` - Build with specific features
- `cargo check` - Fast syntax/type checking
- `cargo clippy` - Comprehensive linting
- `cargo fmt` - Code formatting

### Testing

- `cargo test` - Run core tests
- `cargo test --features full` - Run all tests with all features
- `cargo test <test_name>` - Run specific test
- `cargo test --lib` - Run library unit tests only
- `cargo test --doc` - Run documentation tests

### Running Examples

- `cargo run --example iterators_demo` - Basic iteration patterns
- `cargo run --example processing_builder_demo --features full` - Processing pipeline demo
- `cargo run --example beat_tracking_with_progress --features full` - Advanced analysis with progress tracking

## Architecture Overview

### Core Design Philosophy
This is a modular audio processing library built around trait-based operations on `AudioSamples<T>` containers. The library follows a zero-allocation approach where possible, using views for efficient data access.

### Key Components

#### `AudioSamples<T>` - Main Container

- Central data structure wrapping `AudioData<T>` enum
- Supports borrowed and owned data through lifetime parameter `'a`
- Channels as rows, samples as columns in multi-channel case
- Supports multiple sample types: `i16`, `I24`, `i32`, `f32`, `f64`
- Sample rate stored alongside data

#### Data Storage System

- `AudioData<'a, T>` - Enum with `Mono(MonoData<'a, T>)` and `Multi(MultiData<'a, T>)` variants
- `MonoData<'a, T>` - Wraps `Array1<T>` for single-channel audio
- `MultiData<'a, T>` - Wraps `Array2<T>` for multi-channel audio
- Each data type supports both borrowed (`ArrayView`) and owned (`Array`) representations

#### Trait Organization
Operations are organized into focused traits in `src/operations/traits.rs`:

**Core Traits:**

- `AudioStatistics` - Peak, RMS, variance, zero-crossings, spectral analysis
- `AudioProcessing` - Normalize, scale, clip, DC removal, gain operations
- `AudioChannelOps` - Mono/stereo conversion, channel manipulation
- `AudioEditing` - Trim, pad, reverse, fade, mix, concatenation

**Advanced Traits (feature-gated):**

- `AudioTransforms` - FFT, STFT, spectral analysis (requires `fft`)
- `AudioPitchAnalysis` - Fundamental frequency analysis (requires `spectral-analysis`)
- `AudioPlottingUtils` - Visualization (requires `plotting`)
- `AudioIirFiltering` - IIR filters, biquads
- `AudioParametricEq` - Multi-band equalizer
- `AudioDynamicRange` - Compression, limiting, expansion

**Utility Traits:**

- `AudioOperationApply` - Apply functions to samples
- `AudioRealtimeOps` - Real-time processing operations
- `AudioSamplesOperations` - Umbrella trait combining all operations

### Type System

#### Sample Types and Conversions

- **`ConvertTo<T>`** - Audio-aware conversions with proper scaling (i16 → f32 normalizes to -1.0..1.0)
- **`CastFrom<T>/CastInto<T>`** - Raw numeric casting without audio scaling
- All sample types implement `AudioSample` trait for common operations

#### Error Handling

- Simple operations return values directly (e.g., `peak()` returns `T`)
- Complex operations return `Result<T, AudioError>`
- Chainable result pattern available for functional composition

### Feature System
The library uses cargo features for modular dependencies:

- `default` - Includes `full` (all features enabled by default)
- `core-ops` - Basic operations
- `fft` - Spectral analysis via RustFFT/RealFFT
- `plotting` - Visualization via Plotly
- `resampling` - Quality resampling via Rubato
- `parallel-processing` - Multi-threading via Rayon
- `simd` - SIMD acceleration
- `beat-detection` - Tempo analysis (requires `fft`)
- `spectral-analysis` - Advanced spectral operations (requires `fft`)
- `static-plots` - Static plot generation
- `mkl` - Intel MKL backend for FFT
- `progress-tracking` - Progress reporting for long operations
- `full` - All features enabled

### Module Structure

- `src/repr.rs` - Core data structures (`AudioSamples`, `AudioData`, etc.)
- `src/operations/traits.rs` - All trait definitions
- `src/operations/` - Trait implementations organized by functionality:
  - `statistics.rs` - Statistical operations
  - `processing.rs` - Signal processing + ProcessingBuilder
  - `transforms.rs` - FFT and spectral analysis
  - `editing.rs` - Time-domain editing
  - `channels.rs` - Channel operations
  - `iir_filtering.rs` - IIR filter implementations
  - `parametric_eq.rs` - Equalizer operations
  - `dynamic_range.rs` - Compression/limiting
  - `pitch_analysis.rs` - Pitch detection
  - `plotting/` - Visualization components
  - `beats.rs` - Beat detection and tracking
- `src/utils/` - Utility functions (generation, detection, comparison)
- `src/iterators.rs` - Iterator patterns (frames, channels, windows)
- `src/realtime.rs` - Real-time processing utilities
- `src/conversions.rs` - Type conversion implementations
- `src/traits.rs` - Core type system traits

## Code Conventions

### Error Handling

- Use `AudioSampleError` for audio-specific errors
- Simple getters return values directly, complex operations return `Result`
- Prefer `?` operator over `.unwrap()` or `.expect()`

### Performance

- Use views for zero-allocation access patterns
- Prefer in-place operations when possible
- SIMD acceleration available via `simd` feature
- Parallel processing available via `parallel-processing` feature

### Type Safety

- Leverage the type system for sample format safety
- Use appropriate conversion traits (`ConvertTo` vs `CastInto`)
- Maintain sample rate information with audio data

## Builder Pattern Usage

The library provides a fluent ProcessingBuilder API:

```rust
audio.processing()
    .normalize(-1.0, 1.0, NormalizationMethod::Peak)
    .scale(0.8)
    .clip(-0.5, 0.5)
    .remove_dc_offset()
    .apply()?;
```

## Iterator Patterns

The library supports several iteration patterns:

- `audio.frames()` - Iterate by frames (one sample from each channel)
- `audio.channels()` - Iterate by complete channels
- `audio.windows(size, hop)` - Windowed iteration with overlap
- Support for different padding modes: Zero, None, Skip

## Important Implementation Details

1. **Lifetime Management**: `AudioSamples<'a, T>` uses lifetime parameter to support both borrowed and owned data
2. **Memory Layout**: Mono audio uses 1D arrays, multi-channel uses 2D arrays with channels as rows
3. **Feature Gates**: Many operations are feature-gated to keep dependencies minimal
4. **Type Conversions**: Two conversion systems - `ConvertTo` for audio-aware scaling, `CastFrom/Into` for raw numeric casting
5. **Error Propagation**: Complex operations return `Result` types and support chainable error handling