1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
// Additional strictness beyond default groups
// Intentional allowances
//! # AudioSamples
//!
//! A typed audio processing library for Rust that treats audio as a first-class,
//! invariant-preserving object rather than an unstructured numeric buffer. is this library?
//!
//! `audio_samples` provides a single central type, [`AudioSamples<T>`], that pairs raw
//! PCM data (backed by [`ndarray`](https://docs.rs/ndarray)) with essential metadata:
//! sample rate, channel count, and memory layout. Every audio processing operation in the
//! library is defined as a trait method on this type, ensuring that metadata travels with
//! the data throughout a processing pipeline. does this library exist?
//!
//! Low-level audio APIs in Rust typically expose bare slices or `Vec<f32>` buffers,
//! leaving metadata management to the caller. This encourages subtle bugs such as
//! mismatched sample rates after resampling, or interleaved/non-interleaved confusion
//! when passing buffers between components. `audio_samples` eliminates these error
//! classes by encoding invariants directly into the type. should it be used?
//!
//! Start by creating an [`AudioSamples<T>`] from an ndarray or from one of the
//! built-in signal generators (see [`utils::generation`]), then chain trait methods
//! for any further processing. Feature flags keep the dependency footprint small –
//! only enable what your application needs.
//!
//! ## Installation
//!
//! ```bash
//! cargo add audio_samples
//! ```
//!
//! ## Features
//!
//! The library uses a modular feature flag system. Only enable what you need.
//!
//! | Feature | Description |
//! |---|---|
//! | `statistics` | Peak, RMS, variance, zero-crossings, and other statistical measures |
//! | `processing` | Normalise, scale, clip, DC offset removal, and other sample-level operations (implies `statistics`) |
//! | `editing` | Time-domain editing: trim, pad, reverse, concatenate, fade (implies `statistics`, `random-generation`) |
//! | `channels` | Channel operations: mono↔stereo conversion, channel extraction, interleave/deinterleave |
//! | `transforms` | Spectrogram and frequency-domain transforms via the `spectrograms` crate |
//! | `iir-filtering` | IIR filter design and application (Butterworth, Chebyshev I) |
//! | `parametric-eq` | Multi-band parametric equaliser (implies `iir-filtering`) |
//! | `dynamic-range` | Compression, limiting, and expansion with side-chain support |
//! | `envelopes` | Amplitude, RMS, and analytical envelope followers (implies `dynamic-range`, `editing`, `random-generation`) |
//! | `peak-picking` | Onset strength curve peak picking |
//! | `onset-detection` | Onset detection (implies `transforms`, `peak-picking`, `processing`) |
//! | `beat-tracking` | Beat tracking and tempo estimation |
//! | `decomposition` | Audio source decomposition (implies `onset-detection`) |
//! | `pitch-analysis` | YIN and autocorrelation pitch detection (implies `transforms`) |
//! | `vad` | Voice activity detection |
//! | `resampling` | High-quality resampling via the `rubato` crate |
//! | `plotting` | Signal plotting via `plotly` |
//! | `fixed-size-audio` | Stack-allocated fixed-size audio buffers |
//! | `random-generation` | Noise generators and stochastic signal sources (implies `rand`) |
//! | `full` | Enables all of the above |
//!
//! See `Cargo.toml` for the complete dependency graph.
//!
//! ## Error Handling
//!
//! All fallible operations return [`AudioSampleResult<T>`], which is an alias for
//! `Result<T, AudioSampleError>`. Errors are structured so that the variant indicates
//! the category of failure and the inner type provides detail.
//!
//! ```rust
//! use audio_samples::{AudioSampleError, AudioSampleResult, ParameterError};
//!
//! let audio_result: AudioSampleResult<()> = Err(AudioSampleError::Parameter(
//! ParameterError::invalid_value("window_size", "must be > 0"),
//! ));
//!
//! match audio_result {
//! Ok(()) => {}
//! Err(AudioSampleError::Conversion(err)) => eprintln!("Conversion failed: {err}"),
//! Err(AudioSampleError::Parameter(err)) => eprintln!("Invalid parameter: {err}"),
//! Err(other_err) => eprintln!("Other error: {other_err}"),
//! }
//! ```
//!
//! ## Full Examples
//!
//! Examples live in the repository (see `examples/`) and in the crate-level docs on
//! <https://docs.rs/audio_samples>.
//!
//! ## Quick Start
//!
//! ### Creating Audio Data
//!
//! ```rust
//! use audio_samples::{AudioSamples, sample_rate};
//! use ndarray::array;
//!
//! // Create mono audio
//! let data = array![0.1f32, 0.5, -0.3, 0.8, -0.2];
//! let audio = AudioSamples::new_mono(data, sample_rate!(44100)).unwrap();
//!
//! // Create stereo audio (channels × samples)
//! let stereo_data = array![
//! [0.1f32, 0.5, -0.3], // Left channel
//! [0.8f32, -0.2, 0.4] // Right channel
//! ];
//! let stereo_audio = AudioSamples::new_multi_channel(stereo_data, sample_rate!(44100)).unwrap();
//! ```
//!
//! ### Basic Statistics
//!
//! Requires the `statistics` feature.
//!
//! ```rust,ignore
//! use audio_samples::{AudioStatistics, sine_wave, sample_rate};
//! use std::time::Duration;
//!
//! // Generate a 440 Hz sine wave at 44.1 kHz sample rate, amplitude 1.0
//! let audio = sine_wave::<f32>(440.0, Duration::from_secs_f32(1.0), sample_rate!(44100), 1.0);
//!
//! let peak = audio.peak();
//! let min = audio.min_sample();
//! let max = audio.max_sample();
//! let mean = audio.mean();
//! let rms = audio.rms().unwrap();
//! let variance = audio.variance().unwrap();
//! let zero_crossings = audio.zero_crossings();
//! ```
//!
//! ### Processing Operations
//!
//! Requires the `processing` feature.
//!
//! ```rust,ignore
//! use audio_samples::{AudioProcessing, NormalizationConfig, AudioSamples, sample_rate};
//! use ndarray::array;
//!
//! let data = array![0.1f32, 0.5, -0.3, 0.8, -0.2];
//! let audio = AudioSamples::new_mono(data, sample_rate!(44100)).unwrap();
//!
//! // Method chaining: each operation consumes and returns Self
//! let audio = audio
//! .normalize(NormalizationConfig::peak(1.0))
//! .unwrap()
//! .scale(0.5)
//! .remove_dc_offset()
//! .unwrap();
//! ```
//!
//! ### Type Conversions
//!
//! ```rust
//! use audio_samples::{AudioSamples, AudioTypeConversion, sample_rate};
//! use ndarray::array;
//!
//! let audio_f32 = AudioSamples::new_mono(array![1.0f32, 2.0, 3.0], sample_rate!(44100)).unwrap();
//! let audio_i16 = audio_f32.clone().to_type::<i16>();
//! let audio_f64 = audio_f32.to_type::<f64>();
//! ```
//!
//! ### Iterating Over Audio Data
//!
//! ```rust
//! use audio_samples::{AudioSampleIterators, AudioSamples, sample_rate};
//! use ndarray::array;
//!
//! let audio = AudioSamples::new_mono(
//! array![1.0f32, 2.0, 3.0, 4.0],
//! sample_rate!(44100),
//! ).unwrap();
//!
//! // Iterate by frames (one sample per channel per time step)
//! for frame in audio.frames() {
//! println!("Frame: {:?}", frame);
//! }
//!
//! // Iterate by channels
//! for channel in audio.channels() {
//! println!("Channel: {:?}", channel);
//! }
//! ```
//!
//! ## Core Type System
//!
//! ### Supported Sample Types
//!
//! | Type | Width | Notes |
//! |---|---|---|
//! | `u8` | 8-bit unsigned | Mid-scale (128) represents silence |
//! | `i16` | 16-bit signed | CD-quality audio |
//! | [`I24`](i24::I24) | 24-bit signed | From the `i24` crate |
//! | `i32` | 32-bit signed | High-dynamic-range integer audio |
//! | `f32` | 32-bit float | Most DSP operations use this type |
//! | `f64` | 64-bit float | High-precision processing |
//!
//! ### Type System Traits
//!
//! - **[`AudioSample`]** – Core trait all sample types implement. Provides constants
//! (`MAX`, `MIN`, `BITS`, `BYTES`, `LABEL`) and low-level byte operations.
//!
//! - **[`ConvertTo<T>`]** / **[`ConvertFrom<T>`]** – Audio-aware conversions with
//! correct scaling between bit depths (e.g. `i16 → f32` normalises to `[-1.0, 1.0]`).
//!
//! - **[`CastFrom<T>`]** / **[`CastInto<T>`]** – Raw numeric casts without scaling.
//! Use these when you need the raw integer value as a float for computation,
//! not as an audio amplitude.
//!
//! - **[`AudioTypeConversion`]** – High-level conversion methods on [`AudioSamples<T>`]
//! such as `as_f32()`, `as_i16()`, and `as_type::<U>()`.
//!
//! ## Signal Generation
//!
//! The [`utils::generation`] module provides functions for creating test and
//! reference signals: [`sine_wave`], [`cosine_wave`], [`square_wave`],
//! [`triangle_wave`], [`sawtooth_wave`], [`chirp`], [`impulse`], [`silence`],
//! [`compound_tone`], and [`am_signal`].
//!
//! ```rust
//! use audio_samples::{sine_wave, sample_rate};
//! use audio_samples::utils::comparison;
//! use std::time::Duration;
//!
//! let a = sine_wave::<f32>(440.0, Duration::from_secs(1), sample_rate!(44100), 1.0);
//! let b = sine_wave::<f32>(440.0, Duration::from_secs(1), sample_rate!(44100), 1.0);
//! let corr: f64 = comparison::correlation(&a, &b).unwrap();
//! assert!(corr > 0.99);
//! ```
//!
//! ## Documentation
//!
//! Full API documentation is available at [docs.rs/audio_samples](https://docs.rs/audio_samples).
//!
//! ## License
//!
//! MIT
//!
//! ## Contributing
//!
//! Contributions are welcome. Please open an issue or pull request on
//! [GitHub](https://github.com/jmg049/audio_samples).
// General todos in audio_samples:
// - Define / decide on a policy for parallel processing
// - Improve the error system, it has breadth currently, but not depth or aethetics. Rust set a new standard for error handling (i.e. nice errors that tell you exactly what went wrong, where and how to possible fix things.) which other libraries in other languages have tried to emulate.
// - Better constants and better use of them -- e.g. the LEFT, RIGHT and SUPPORTED_DTYPES are rarely used
/// Creates a `NonZeroUsize` from a compile-time constant with zero-check.
///
/// This macro creates a `NonZeroUsize` with a compile-time assertion that the value is
/// non-zero, making it safe to use `new_unchecked` internally. If the value is zero, the
/// code will fail to compile.
///
/// # Example
///
/// ```
/// # use audio_samples::nzu;
/// let size = nzu!(1024);
/// assert_eq!(size.get(), 1024);
/// ```
///
/// This will fail to compile:
/// ```compile_fail
/// # use audio_samples::nzu;
/// let invalid = nzu!(0); // Compile error: assertion failed
/// ```
/// Core trait definitions for audio sample types and operations.
pub use crate;
pub use crateAudioData;
pub use crateStereoAudioSamples;
pub use crate;
pub use crate;
pub use crate;
pub use crateWindowIterator;
pub use crate;
pub use crate;
pub use crateAudioStatistics;
pub use crateAudioProcessing;
pub use crate;
pub use crateAudioChannelOps;
pub use crateAudioEditing;
pub use crateAudioTransforms;
pub use crateFixedSizeAudioSamples;
pub use crateAudioOnsetDetection;
pub use crateAudioDecomposition;
pub use crateAudioDynamicRange;
pub use crateAudioIirFiltering;
pub use crateAudioParametricEq;
pub use crateAudioPitchAnalysis;
pub use crateAudioVoiceActivityDetection;
pub use crate;
pub use ; // Re-export I24 type that has the AudioSample implementation
use ;
pub use ;
/// A tagged result that is either a 1-D mono array or a 2-D multi-channel array.
///
/// ## Purpose
///
/// Several operations on [`AudioSamples<T>`] produce output whose dimensionality
/// mirrors the input: a mono input yields a 1-D result; a multi-channel input yields
/// a 2-D result. `NdResult` captures both possibilities in a single return type,
/// letting callers branch on the actual dimensionality at runtime rather than
/// discarding the channel structure.
///
/// ## Intended Usage
///
/// Pattern-match on the variants directly, or use [`into_array1`](NdResult::into_array1) /
/// [`into_array2`](NdResult::into_array2) when you already know the expected shape.
/// Prefer the safe helpers over the `_unchecked` variants unless performance is
/// critical and the shape has already been verified.
///
/// ## Invariants
///
/// - The [`Mono`](NdResult::Mono) variant always holds a 1-D array with at least one element.
/// - The [`MultiChannel`](NdResult::MultiChannel) variant always holds a 2-D array with at
/// least one channel and at least one sample per channel.
///
/// ## Assumptions
///
/// Callers must not construct `NdResult` directly with empty arrays.
/// All library functions that return `NdResult` uphold the non-empty invariants above.