aura_dsp/lib.rs
1//! # aura-dsp — Audio DSP primitives
2//!
3//! JUCE analogue: **`juce_dsp`** (processors, filters, oscillators, FX, maths).
4//! MIDI messages/buffers live in **`aura-midi`** (not here).
5//!
6//! Core synthesis/FX stack forked from **naad** (Sanskrit: primordial sound)
7//! and now maintained as part of AURA:
8//! oscillators, filters, envelopes, wavetables, modulation, delay, effects,
9//! noise, tuning. Product-grade LX FX / analysis modules land under this crate
10//! over time (`fx/`, `analysis/`) — not as separate product-only silos in the
11//! framework tree.
12//!
13//! Historical: this crate was forked from naad v1.2.5 (GPL-3.0-only,
14//! part of the AGNOS ecosystem — dhvani / svara).
15//!
16//! ## Architecture
17//!
18//! All processing methods work on contiguous `&mut [f32]` slices. Hot-path
19//! methods (`next_sample`, `process_sample`) are `#[inline]` for cross-crate
20//! optimization. Buffer methods (`fill_buffer`, `process_buffer`) iterate
21//! over slices, enabling SIMD auto-vectorization when compiled with
22//! appropriate target features (`-C target-cpu=native`).
23//!
24//! dhvani (the sound engine) handles buffer alignment and SIMD dispatch.
25//! aura-dsp provides the scalar reference implementations.
26//!
27//! ## Quick Start
28//!
29//! ```rust
30//! use aura_dsp::oscillator::{Oscillator, Waveform};
31//! use aura_dsp::envelope::Adsr;
32//! use aura_dsp::filter::{BiquadFilter, FilterType};
33//!
34//! // Create a 440 Hz sine oscillator
35//! let mut osc = Oscillator::new(Waveform::Sine, 440.0, 44100.0).unwrap();
36//!
37//! // Create an ADSR envelope
38//! let mut env = Adsr::new(0.01, 0.1, 0.7, 0.3).unwrap();
39//!
40//! // Create a low-pass filter at 2kHz
41//! let mut filter = BiquadFilter::new(FilterType::LowPass, 44100.0, 2000.0, 0.707).unwrap();
42//!
43//! // Generate a sample
44//! env.gate_on();
45//! let sample = osc.next_sample() * env.next_value();
46//! let filtered = filter.process_sample(sample);
47//! ```
48//!
49//! ## Feature Flags
50//!
51//! - `default` — All core primitives (oscillators, filters, envelopes, effects, dynamics, EQ, reverb, voice, mod matrix, panning, smoothing, tuning, noise, delay, wavetable, `dsp_util`)
52//! - `synthesis` — Synthesis algorithm modules (subtractive, FM, drum, formant, additive, vocoder, granular, physical modeling)
53//! - `acoustics` — Room simulation, convolution reverb, binaural, FDN, analysis, ambisonics (via goonj)
54//! - `logging` — Enable tracing-subscriber for structured logging output
55//! - `full` — All features enabled
56//!
57//! ## API Conventions
58//!
59//! These conventions apply uniformly across the crate. Knowing them up front
60//! avoids surprises when wiring aura-dsp into a host (dhvani, svara, etc.).
61//!
62//! ### Encapsulation
63//!
64//! - **Stateful types with non-trivial invariants** (e.g. [`oscillator::Oscillator`],
65//! [`filter::BiquadFilter`], [`wavetable::Wavetable`]) keep their fields **private**
66//! and expose validated setters. Modifying state requires a constructor or a
67//! typed mutator — there is no way to silently break the invariant.
68//! - **Parameter structs** that are pure value-bags read directly by their owning
69//! type (e.g. [`dynamics::Compressor::threshold_db`], [`envelope::Adsr::sustain_level`])
70//! keep `pub` fields. They are documented when modifying them bypasses
71//! constructor-time clamping; callers may set arbitrary `f32` values and
72//! accept whatever output the algorithm produces.
73//!
74//! Rule of thumb: if changing a field requires recomputing cached coefficients
75//! or affects internal state coupling, it is private. If it only feeds a
76//! direct read in the next-sample loop, it may be `pub`.
77//!
78//! ### Constructor return types
79//!
80//! - **Constructors that validate `sample_rate`, `frequency`, or other
81//! range-restricted inputs return [`Result`]**. Examples:
82//! [`oscillator::Oscillator::new`], [`filter::BiquadFilter::new`],
83//! [`envelope::Adsr::new`].
84//! - **Constructors that only clamp inputs (e.g. amplitude to `0..=1`) are
85//! infallible** — they take any `f32` and store the clamped result.
86//! Examples: [`dynamics::LevelDetector::new`], [`smoothing::ParamSmoother::new`].
87//! - **Index-based mutators (`set_operator_freq`, `set_band_gain`)** that may
88//! receive an out-of-range index return `Option<()>` or `Result<()>` so
89//! callers can detect — and not silently ignore — bad indices.
90
91// DSP code intentionally uses float/int conversions where precision loss,
92// truncation or sign loss are harmless by construction (array indices,
93// sample counts, normalized parameters). Allow these lints crate-wide so
94// real logic issues remain visible.
95#![allow(
96 clippy::cast_precision_loss,
97 clippy::cast_possible_truncation,
98 clippy::cast_sign_loss,
99 clippy::cast_possible_wrap,
100 clippy::must_use_candidate,
101 // Tests compare exact float results and DSP benchmarks allocate large stack buffers.
102 clippy::float_cmp,
103 clippy::large_stack_arrays
104)]
105
106/// Portable analysis: FFT/SNAP maths, spectrum, meter blocks (no vault/MD/*Shared).
107pub mod analysis;
108pub mod dc_blocker;
109pub mod delay;
110pub mod dsp_util;
111pub mod dynamics;
112pub mod effects;
113pub mod envelope;
114pub mod eq;
115pub mod error;
116pub mod filter;
117/// LX product-grade FX (from `lx-dsp`): TDF-II biquad, mastering, meters, …
118pub mod fx;
119pub mod mod_matrix;
120pub mod mod_route_table;
121pub mod modulation;
122pub mod noise;
123pub mod oscillator;
124pub mod panning;
125pub mod reverb;
126pub mod smoothing;
127pub mod tempo;
128pub mod tuning;
129pub mod voice;
130pub mod wavetable;
131
132#[cfg(feature = "synthesis")]
133pub mod synth;
134
135#[cfg(feature = "acoustics")]
136pub mod acoustics;
137
138pub use error::{DspError, Result};
139
140/// Flush denormal floating-point values to zero.
141///
142/// Denormal (subnormal) floats cause 10-100x slowdowns on x86 processors.
143/// Call this on filter state variables and feedback paths to prevent
144/// performance degradation when signals decay to near-zero.
145#[inline]
146#[must_use]
147pub fn flush_denormal(x: f32) -> f32 {
148 // A float is denormal if its exponent bits are all zero but mantissa is non-zero.
149 // Threshold: f32::MIN_POSITIVE (1.175e-38) is the smallest normal f32.
150 if x.abs() < f32::MIN_POSITIVE { 0.0 } else { x }
151}