audio_samples 1.0.5

A typed audio processing library for Rust that treats audio as a first-class, invariant-preserving object rather than an unstructured numeric buffer.
Documentation
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
//! Audio signal comparison and similarity metrics.
//!
//! This module provides a small collection of signal-level comparison operators for
//! analysing similarity, error, and alignment between audio signals. The exposed functions
//! operate on [`AudioSamples`] and return scalar metrics or derived signals that are suitable
//! for validation, evaluation, diagnostics, and lightweight analysis workflows.
//!
//! The primary purpose of this module is to centralise common comparison semantics.
//!
//! # Usage
//!
//! Typical usage consists of passing two compatible audio signals into a metric function
//! and interpreting the returned scalar or aligned signal. All comparison functions require
//! matching dimensionality and compatible channel layouts unless explicitly documented
//! otherwise.
//!
//! ```rust
//! use audio_samples::utils::comparison::{correlation, mse};
//! use audio_samples::utils::generation::sine_wave;
//! use audio_samples::sample_rate;
//! use std::time::Duration;
//!
//! let sr = sample_rate!(44100);
//! let a = sine_wave::<f32>(440.0, Duration::from_millis(100), sr, 1.0);
//! let b = sine_wave::<f32>(440.0, Duration::from_millis(100), sr, 1.0);
//!
//! let corr: f64 = correlation(&a, &b).unwrap();
//! let error: f64 = mse(&a, &b).unwrap();
//!
//! assert!((corr - 1.0).abs() < 1e-6);
//! assert!(error < 1e-10);
//! ```
use crate::{
    AudioSampleError, AudioSampleResult, AudioSamples, AudioTypeConversion, LayoutError,
    ParameterError, traits::StandardSample,
};
use ndarray::{Array1, ArrayView1};

/// Computes the Pearson correlation coefficient between two audio signals.
///
/// This function measures linear similarity between two signals on a per-sample basis and
/// returns a scalar correlation coefficient in the range `[-1, 1]`. Positive values indicate
/// positive correlation, negative values indicate inverse correlation, and values near zero
/// indicate weak linear relationship.
///
/// For mono signals, the correlation is computed directly over the single channel.\
/// For multi-channel signals, the correlation is computed independently for each channel and
/// the results are averaged to produce a single scalar score.
///
/// # Arguments
///
/// * `a`\
///   The first audio signal.
///
/// * `b`\
///   The second audio signal.
///
/// Both signals must have identical channel counts and the same number of samples per
/// channel.
///
/// # Returns
///
/// A scalar correlation coefficient in the range `[-1, 1]`, expressed in the requested
/// floating-point type.
///
/// # Errors
///
/// Returns an error in the following cases:
///
/// * The two signals have different channel counts.
/// * The two signals have different numbers of samples per channel.
/// * The underlying sample layout is non-contiguous and cannot be viewed as a slice.
/// * The channel configuration of the two signals does not match (mono vs multi-channel).
///
/// # Behavioural Guarantees
///
/// * The returned value lies in the closed interval `[-1, 1]` for all finite inputs.
/// * For identical signals, the returned value is `1.0` (up to floating-point rounding).
/// * For multi-channel inputs, the result is the arithmetic mean of per-channel correlations.
/// * If either signal has zero variance over a channel, the correlation for that channel is
///   defined as `0.0`.
///
/// # Examples
///
/// ```rust
/// use audio_samples::utils::comparison::correlation;
/// use audio_samples::utils::generation::sine_wave;
/// use audio_samples::sample_rate;
/// use std::time::Duration;
///
/// let sr = sample_rate!(44100);
/// let a = sine_wave::<f32>(440.0, Duration::from_millis(100), sr, 1.0);
/// let b = sine_wave::<f32>(440.0, Duration::from_millis(100), sr, 1.0);
///
/// let corr = correlation(&a, &b).unwrap();
/// assert!((corr - 1.0).abs() < 1e-6); // identical signals → correlation 1.0
/// ```
#[inline]
pub fn correlation<T>(a: &AudioSamples<T>, b: &AudioSamples<T>) -> AudioSampleResult<f64>
where
    T: StandardSample,
{
    if a.num_channels() != b.num_channels() || a.samples_per_channel() != b.samples_per_channel() {
        return Err(AudioSampleError::Parameter(ParameterError::invalid_value(
            "audio_signals",
            "Signals must have the same dimensions for correlation",
        )));
    }

    let a_f = a.as_float();
    let b_f = b.as_float();

    match (a_f.as_mono(), b_f.as_mono()) {
        (Some(a_mono), Some(b_mono)) => {
            let corr = correlation_1d(&a_mono.view(), &b_mono.view())?;
            Ok(corr)
        }
        (Some(_), None) | (None, Some(_)) => {
            Err(AudioSampleError::Parameter(ParameterError::invalid_value(
                "audio_format",
                "Signals must have the same channel configuration",
            )))
        }
        (None, None) => {
            // Multi-channel correlation - compute average correlation across channels
            let a_multi = a_f.as_multi_channel().ok_or_else(|| {
                AudioSampleError::Parameter(ParameterError::invalid_value(
                    "audio_format",
                    "Must be multi-channel audio",
                ))
            })?;
            let b_multi = b_f.as_multi_channel().ok_or_else(|| {
                AudioSampleError::Parameter(ParameterError::invalid_value(
                    "audio_format",
                    "Must be multi-channel audio",
                ))
            })?;

            let mut correlations = Vec::new();
            for i in 0..a_multi.nrows().get() {
                let a_channel = a_multi.row(i);
                let b_channel = b_multi.row(i);
                let corr = correlation_1d_slice(
                    a_channel.as_slice().ok_or_else(|| {
                        AudioSampleError::Layout(LayoutError::NonContiguous {
                            operation: "signal processing".to_string(),
                            layout_type: "non-contiguous multi-channel samples".to_string(),
                        })
                    })?,
                    b_channel.as_slice().ok_or_else(|| {
                        AudioSampleError::Layout(LayoutError::NonContiguous {
                            operation: "signal processing".to_string(),
                            layout_type: "non-contiguous multi-channel samples".to_string(),
                        })
                    })?,
                )?;
                correlations.push(corr);
            }

            Ok(correlations.iter().fold(0.0, |acc, x| acc + *x) / correlations.len() as f64)
        }
    }
}

/// Computes the mean squared error (MSE) between two audio signals.
///
/// This function measures the average squared per-sample difference between two signals.
/// Lower values indicate higher similarity, with a value of `0.0` indicating identical
/// signals under exact arithmetic. The metric is unnormalised and scales quadratically with
/// signal amplitude.
///
/// For mono signals, the MSE is computed directly over the single channel.\
/// For multi-channel signals, the MSE is computed independently for each channel and the
/// results are averaged to produce a single scalar value.
///
/// # Arguments
///
/// * `a`\
///   The first audio signal.
///
/// * `b`\
///   The second audio signal.
///
/// Both signals must have identical channel counts and the same number of samples per
/// channel.
///
/// # Returns
///
/// The mean squared error as a non-negative scalar value expressed in the requested
/// floating-point type.
///
/// # Errors
///
/// Returns an error in the following cases:
///
/// * The two signals have different channel counts.
/// * The two signals have different numbers of samples per channel.
/// * The underlying sample layout is non-contiguous and cannot be viewed as a slice.
/// * The channel configuration of the two signals does not match (mono vs multi-channel).
///
/// # Behavioural Guarantees
///
/// * The returned value is always greater than or equal to `0.0` for all finite inputs.
/// * For identical signals, the returned value is `0.0` up to floating-point rounding.
/// * For multi-channel inputs, the result is the arithmetic mean of per-channel MSE values.
///
/// # Examples
///
/// ```rust
/// use audio_samples::utils::comparison::mse;
/// use audio_samples::utils::generation::sine_wave;
/// use audio_samples::sample_rate;
/// use std::time::Duration;
///
/// let sr = sample_rate!(44100);
/// let a = sine_wave::<f32>(440.0, Duration::from_millis(100), sr, 1.0);
/// let b = sine_wave::<f32>(440.0, Duration::from_millis(100), sr, 1.0);
///
/// let error = mse(&a, &b).unwrap();
/// assert!(error < 1e-10); // identical signals → zero MSE
/// ```
#[inline]
pub fn mse<T>(a: &AudioSamples<T>, b: &AudioSamples<T>) -> AudioSampleResult<f64>
where
    T: StandardSample,
{
    if a.num_channels() != b.num_channels() || a.samples_per_channel() != b.samples_per_channel() {
        return Err(AudioSampleError::Parameter(ParameterError::invalid_value(
            "audio_signals",
            "Signals must have the same dimensions for MSE",
        )));
    }

    let a_f = a.as_float();
    let b_f = b.as_float();

    match (a_f.as_mono(), b_f.as_mono()) {
        (Some(a_mono), Some(b_mono)) => mse_1d(&a_mono.view(), &b_mono.view()),
        (Some(_), None) | (None, Some(_)) => {
            Err(AudioSampleError::Parameter(ParameterError::invalid_value(
                "audio_format",
                "Signals must have the same channel configuration",
            )))
        }
        (None, None) => {
            // Multi-channel MSE - compute average MSE across channels
            let a_multi = a_f.as_multi_channel().ok_or_else(|| {
                AudioSampleError::Parameter(ParameterError::invalid_value(
                    "audio_format",
                    "Must be multi-channel audio",
                ))
            })?;
            let b_multi = b_f.as_multi_channel().ok_or_else(|| {
                AudioSampleError::Parameter(ParameterError::invalid_value(
                    "audio_format",
                    "Must be multi-channel audio",
                ))
            })?;

            let mut mses = Vec::new();
            for i in 0..a_multi.nrows().get() {
                let a_channel = a_multi.row(i);
                let b_channel = b_multi.row(i);
                let mse = mse_1d_slice(
                    a_channel.as_slice().ok_or_else(|| {
                        AudioSampleError::Layout(LayoutError::NonContiguous {
                            operation: "signal processing".to_string(),
                            layout_type: "non-contiguous multi-channel samples".to_string(),
                        })
                    })?,
                    b_channel.as_slice().ok_or_else(|| {
                        AudioSampleError::Layout(LayoutError::NonContiguous {
                            operation: "signal processing".to_string(),
                            layout_type: "non-contiguous multi-channel samples".to_string(),
                        })
                    })?,
                )?;
                mses.push(mse);
            }

            Ok(mses.iter().fold(0.0, |acc, x| acc + *x) / mses.len() as f64)
        }
    }
}

/// Computes the signal-to-noise ratio (SNR) between a signal and a noise signal.
///
/// This function measures the ratio between the average power of a signal and the average
/// power of a corresponding noise signal, expressed in decibels. Higher values indicate
/// greater dominance of the signal relative to noise.
///
/// The function assumes that `signal` and `noise` are already aligned and represent
/// compatible components. No validation is performed to determine whether the inputs
/// actually correspond to a signal–noise decomposition.
///
/// For mono inputs, power is computed over the single channel.\
/// For multi-channel inputs, power is computed over all samples across all channels and
/// aggregated into a single scalar value. No per-channel SNR values are returned.
///
/// # Arguments
///
/// * `signal`\
///   The signal component.
///
/// * `noise`\
///   The noise component.
///
/// Both inputs must have identical channel counts and the same number of samples per
/// channel.
///
/// # Returns
///
/// The signal-to-noise ratio in decibels. Larger values indicate higher signal quality.
///
/// If the estimated noise power is zero, the function returns positive infinity.
///
/// # Errors
///
/// Returns an error in the following cases:
///
/// * The two inputs have different channel counts.
/// * The two inputs have different numbers of samples per channel.
/// * The underlying sample layout is non-contiguous and cannot be viewed as a slice.
/// * The channel configuration of the two signals does not match (mono vs multi-channel).
///
/// # Behavioural Guarantees
///
/// * For finite non-zero noise power, the returned value is finite.
/// * If the noise power is exactly zero, the returned value is positive infinity.
/// * The returned value increases monotonically with increasing signal power for fixed
///   noise power.
///
/// # Examples
///
/// ```rust
/// use audio_samples::utils::comparison::snr;
/// use audio_samples::utils::generation::sine_wave;
/// use audio_samples::sample_rate;
/// use std::time::Duration;
///
/// let sr = sample_rate!(44100);
/// // Signal with amplitude 1.0, noise with amplitude 0.01.
/// let signal = sine_wave::<f32>(440.0, Duration::from_millis(100), sr, 1.0);
/// let noise  = sine_wave::<f32>(880.0, Duration::from_millis(100), sr, 0.01);
///
/// let db = snr(&signal, &noise).unwrap();
/// assert!(db > 30.0); // high-power signal relative to low-power noise → high SNR
/// ```
#[inline]
pub fn snr<T>(signal: &AudioSamples<T>, noise: &AudioSamples<T>) -> AudioSampleResult<f64>
where
    T: StandardSample,
{
    if signal.num_channels() != noise.num_channels()
        || signal.samples_per_channel() != noise.samples_per_channel()
    {
        return Err(AudioSampleError::Parameter(ParameterError::invalid_value(
            "audio_signals",
            "Signal and noise must have the same dimensions for SNR",
        )));
    }

    let signal_f = signal.as_float();
    let noise_f = noise.as_float();

    // Calculate signal power
    let signal_power = if let Some(mono) = signal_f.as_mono() {
        mono.iter().map(|&x| x * x).fold(0.0, |acc, x| acc + x) / mono.len().get() as f64
    } else {
        let multi = signal_f.as_multi_channel().ok_or_else(|| {
            AudioSampleError::Parameter(ParameterError::invalid_value(
                "audio_format",
                "Must be multi-channel audio",
            ))
        })?;
        multi.iter().map(|&x| x * x).fold(0.0, |acc, x| acc + x) / multi.len().get() as f64
    };

    // Calculate noise power
    let noise_power = if let Some(mono) = noise_f.as_mono() {
        mono.iter().map(|x| *x * *x).fold(0.0, |acc, x| acc + x) / mono.len().get() as f64
    } else {
        let multi = noise_f.as_multi_channel().ok_or_else(|| {
            AudioSampleError::Parameter(ParameterError::invalid_value(
                "audio_format",
                "Must be multi-channel audio",
            ))
        })?;
        multi.iter().map(|&x| x * x).fold(0.0, |acc, x| acc + x) / multi.len().get() as f64
    };

    if noise_power == 0.0 {
        return Ok(f64::INFINITY);
    }

    let snr_db = 10.0 * (signal_power / noise_power).log10();
    Ok(snr_db)
}
/// Aligns two audio signals by estimating a time offset that maximises correlation.
///
/// This function attempts to temporally align `signal` to `reference` by searching for a
/// non-negative sample offset that maximises cross-correlation between the two signals. The
/// returned signal is a shifted version of the input signal padded at the start, together
/// with the estimated offset in samples.
///
/// This is a heuristic alignment utility intended for coarse synchronisation, diagnostics,
/// and preprocessing. It does not guarantee globally optimal alignment, sub-sample accuracy,
/// or robustness under heavy noise, reverberation, or non-linear distortion.
///
/// # Channel Handling
///
/// * For mono signals, alignment is computed directly on the single channel.
/// * For multi-channel signals, all channels are averaged to a single derived signal before
///   alignment. The estimated offset is then applied uniformly to all channels.
///
/// No per-channel alignment is performed. Channel-specific delays are not detected.
///
/// # Search Behaviour
///
/// * Only non-negative offsets are considered. The signal is shifted forward in time only.
/// * The maximum offset searched is half of the shorter signal length.
/// * For each candidate offset, correlation is computed over the overlapping region only.
///
/// These limits are part of the public contract and constrain the class of alignments that
/// can be detected.
///
/// # Padding Semantics
///
/// When a positive offset is selected, the aligned signal is padded at the start using the
/// default value of the sample type. This is a structural padding operation rather than an
/// explicit silence model.
///
/// # Arguments
///
/// * `reference`\
///   The reference signal that defines the target alignment.
///
/// * `signal`\
///   The signal to be aligned to the reference.
///
/// Both signals must have identical channel counts.
///
/// # Returns
///
/// A tuple `(aligned_signal, offset_samples)` where:
///
/// * `aligned_signal` is a newly allocated signal shifted by the estimated offset.
/// * `offset_samples` is the number of samples by which the signal was shifted.
///
/// # Errors
///
/// Returns an error in the following cases:
///
/// * The two signals have different channel counts.
/// * The channel configuration of the two signals does not match (mono vs multi-channel).
/// * The underlying sample layout is non-contiguous and cannot be viewed as a slice.
/// * Internal array construction fails due to invalid shape assumptions.
///
/// # Behavioural Guarantees
///
/// * The returned offset is always greater than or equal to zero.
/// * If no offset improves correlation, the returned offset is zero and the original signal
///   is returned unchanged (cloned).
/// * The alignment decision is deterministic for fixed inputs.
/// * The function allocates a new signal when a non-zero offset is applied.
///
/// # Limitations
///
/// This function does not:
///
/// * Search negative offsets or bidirectional shifts.
/// * Perform sub-sample alignment or interpolation.
/// * Account for phase offsets, time stretching, or sample-rate mismatch.
/// * Preserve original sample padding semantics beyond default value initialisation.
///
/// # Examples
///
/// ```rust
/// use audio_samples::utils::comparison::align_signals;
/// use audio_samples::AudioSamples;
///
/// fn example<T: audio_samples::traits::StandardSample>(
///     reference: AudioSamples<'static, T>,
///      signal: AudioSamples<'static, T>,
///  ) {
/// let (aligned, offset) = align_signals::<T>(&reference, &signal).unwrap();
///
/// println!("Estimated offset: {offset} samples");
/// assert!(offset >= 0);
///  }
/// ```
#[inline]
pub fn align_signals<T>(
    reference: &AudioSamples<'_, T>,
    signal: &AudioSamples<'_, T>,
) -> AudioSampleResult<(AudioSamples<'static, T>, usize)>
where
    T: StandardSample,
{
    if reference.num_channels() != signal.num_channels() {
        return Err(AudioSampleError::Parameter(ParameterError::invalid_value(
            "audio_channels",
            "Signals must have the same number of channels for alignment",
        )));
    }

    let sample_rate = signal.sample_rate();
    let ref_f = reference.as_float();
    let sig_f = signal.as_float();

    // For simplicity, we'll work with the first channel for mono or the average for multi-channel
    let (ref_data, sig_data) = match (ref_f.as_mono(), sig_f.as_mono()) {
        (Some(ref_mono), Some(sig_mono)) => (ref_mono.to_vec(), sig_mono.to_vec()),
        (None, None) => {
            // Average across channels for multi-channel signals
            let ref_multi = ref_f.as_multi_channel().ok_or_else(|| {
                AudioSampleError::Parameter(ParameterError::invalid_value(
                    "audio_format",
                    "Must be multi-channel audio",
                ))
            })?;
            let sig_multi = sig_f.as_multi_channel().ok_or_else(|| {
                AudioSampleError::Parameter(ParameterError::invalid_value(
                    "audio_format",
                    "Must be multi-channel audio",
                ))
            })?;

            let ref_avg: Vec<f64> = (0..ref_multi.ncols().get())
                .map(|i| {
                    ref_multi.column(i).iter().fold(0.0, |acc, x| acc + *x)
                        / ref_multi.nrows().get() as f64
                })
                .collect();

            let sig_avg: Vec<f64> = (0..sig_multi.ncols().get())
                .map(|i| {
                    sig_multi.column(i).iter().fold(0.0, |acc, x| acc + *x)
                        / sig_multi.nrows().get() as f64
                })
                .collect();

            (ref_avg, sig_avg)
        }
        _ => {
            return Err(AudioSampleError::Parameter(ParameterError::invalid_value(
                "audio_format",
                "Signals must have the same channel configuration",
            )));
        }
    };

    // Find the best alignment using cross-correlation
    let max_offset = ref_data.len().min(sig_data.len()) / 2;
    let mut best_offset = 0;
    let mut best_correlation = f64::NEG_INFINITY;

    for offset in 0..max_offset {
        let correlation = if offset < sig_data.len() {
            let end = (ref_data.len() - offset).min(sig_data.len() - offset);
            correlation_1d_slice(
                &ref_data[offset..offset + end],
                &sig_data[offset..offset + end],
            )?
        } else {
            0.0
        };

        if correlation > best_correlation {
            best_correlation = correlation;
            best_offset = offset;
        }
    }

    // Create aligned signal by shifting
    let aligned_signal = if best_offset > 0 {
        if let Some(mono) = signal.as_mono() {
            let mut aligned_data = vec![T::default(); best_offset];
            aligned_data.extend_from_slice(
                &mono.as_slice().ok_or_else(|| {
                    AudioSampleError::Layout(LayoutError::NonContiguous {
                        operation: "signal alignment".to_string(),
                        layout_type: "non-contiguous mono samples".to_string(),
                    })
                })?[..mono.len().get() - best_offset],
            );
            let aligned_array = Array1::from_vec(aligned_data);
            AudioSamples::new_mono(aligned_array, sample_rate)?
        } else {
            let multi = signal.as_multi_channel().ok_or_else(|| {
                AudioSampleError::Parameter(ParameterError::invalid_value(
                    "audio_format",
                    "Must be multi-channel audio",
                ))
            })?;
            let mut aligned_data = Vec::new();
            for i in 0..multi.nrows().get() {
                let mut row = vec![T::default(); best_offset];
                row.extend_from_slice(
                    &multi.row(i).as_slice().ok_or_else(|| {
                        AudioSampleError::Layout(LayoutError::NonContiguous {
                            operation: "signal alignment".to_string(),
                            layout_type: "non-contiguous multi-channel samples".to_string(),
                        })
                    })?[..multi.ncols().get() - best_offset],
                );
                aligned_data.push(row);
            }
            let aligned_array = ndarray::Array2::from_shape_vec(
                (aligned_data.len(), aligned_data[0].len()),
                aligned_data.into_iter().flatten().collect(),
            )
            .map_err(|e| {
                AudioSampleError::Parameter(ParameterError::invalid_value(
                    "array_shape",
                    format!("Array shape error: {e}"),
                ))
            })?;
            AudioSamples::new_multi_channel(aligned_array, sample_rate)?
        }
    } else {
        signal.clone().into_owned()
    };

    Ok((aligned_signal, best_offset))
}

// Helper functions for 1D correlation and MSE
fn correlation_1d(a: &ArrayView1<f64>, b: &ArrayView1<f64>) -> AudioSampleResult<f64> {
    correlation_1d_slice(
        a.as_slice().ok_or_else(|| {
            AudioSampleError::Layout(LayoutError::NonContiguous {
                operation: "correlation calculation".to_string(),
                layout_type: "non-contiguous mono samples".to_string(),
            })
        })?,
        b.as_slice().ok_or_else(|| {
            AudioSampleError::Layout(LayoutError::NonContiguous {
                operation: "correlation calculation".to_string(),
                layout_type: "non-contiguous mono samples".to_string(),
            })
        })?,
    )
}

fn correlation_1d_slice(a: &[f64], b: &[f64]) -> AudioSampleResult<f64> {
    if a.len() != b.len() {
        return Err(AudioSampleError::Parameter(ParameterError::invalid_value(
            "array_length",
            "Arrays must have the same length for correlation",
        )));
    }

    let n = a.len();
    let mean_a = a.iter().fold(0.0, |acc, x| acc + *x) / n as f64;
    let mean_b = b.iter().fold(0.0, |acc, x| acc + *x) / n as f64;

    let mut num = 0.0;
    let mut den_a = 0.0;
    let mut den_b = 0.0;

    for (&x, &y) in a.iter().zip(b.iter()) {
        let dx = x - mean_a;
        let dy = y - mean_b;
        num += dx * dy;
        den_a += dx * dx;
        den_b += dy * dy;
    }

    let denominator = (den_a * den_b).sqrt();
    if denominator == 0.0 {
        Ok(0.0)
    } else {
        Ok(num / denominator)
    }
}

fn mse_1d(a: &ArrayView1<f64>, b: &ArrayView1<f64>) -> AudioSampleResult<f64> {
    if a.len() != b.len() {
        return Err(AudioSampleError::Parameter(ParameterError::invalid_value(
            "array_length",
            "Arrays must have the same length for MSE",
        )));
    }

    let n = a.len();
    let sum_squared_diff: f64 = a
        .iter()
        .zip(b.iter())
        .map(|(&x, &y)| (x - y) * (x - y))
        .fold(0.0, |acc, val| acc + val);

    Ok(sum_squared_diff / n as f64)
}

fn mse_1d_slice(a: &[f64], b: &[f64]) -> AudioSampleResult<f64> {
    if a.len() != b.len() {
        return Err(AudioSampleError::Parameter(ParameterError::invalid_value(
            "array_length",
            "Arrays must have the same length for MSE",
        )));
    }
    let n = a.len();

    let sum_squared_diff: f64 = a
        .iter()
        .zip(b.iter())
        .map(|(&x, &y)| (x - y) * (x - y))
        .fold(0.0, |acc, val| acc + val)
        / n as f64;

    Ok(sum_squared_diff)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sample_rate;
    use approx_eq::assert_approx_eq;
    use non_empty_slice::non_empty_vec;

    #[test]
    fn test_correlation_identical_signals() {
        let data: non_empty_slice::NonEmptyVec<f64> = non_empty_vec![1.0f64, 2.0, 3.0, 4.0, 5.0];
        let audio1: AudioSamples<'static, f64> =
            AudioSamples::from_mono_vec::<f64>(data.clone(), sample_rate!(44100));
        let audio2: AudioSamples<'static, f64> =
            AudioSamples::from_mono_vec::<f64>(data, sample_rate!(44100));

        let corr: f64 = correlation(&audio1, &audio2).unwrap();
        assert_approx_eq!(corr, 1.0, 1e-10);
    }

    #[test]
    fn test_correlation_opposite_signals() {
        let audio1: AudioSamples<'static, f64> = AudioSamples::from_mono_vec::<f64>(
            non_empty_vec![1.0f64, 2.0, 3.0, 4.0, 5.0],
            sample_rate!(44100),
        );
        let audio2 = AudioSamples::from_mono_vec::<f64>(
            non_empty_vec![-1.0f64, -2.0, -3.0, -4.0, -5.0],
            sample_rate!(44100),
        );

        let corr: f64 = correlation(&audio1, &audio2).unwrap();
        assert_approx_eq!(corr, -1.0, 1e-10);
    }

    #[test]
    fn test_mse_identical_signals() {
        let audio1: AudioSamples<'static, f64> = AudioSamples::from_mono_vec::<f64>(
            non_empty_vec![1.0f64, 2.0, 3.0, 4.0, 5.0],
            sample_rate!(44100),
        );
        let audio2 = AudioSamples::from_mono_vec::<f64>(
            non_empty_vec![1.0f64, 2.0, 3.0, 4.0, 5.0],
            sample_rate!(44100),
        );

        let mse_val = mse(&audio1, &audio2).unwrap();
        assert_approx_eq!(mse_val, 0.0_f64, 1e-10);
    }

    #[test]
    fn test_snr_calculation() {
        let signal: AudioSamples<'static, f64> = AudioSamples::from_mono_vec::<f64>(
            non_empty_vec![1.0f64, 2.0, 3.0, 4.0, 5.0],
            sample_rate!(44100),
        );
        let noise = AudioSamples::from_mono_vec::<f64>(
            non_empty_vec![0.1f64, 0.2, 0.1, 0.2, 0.1],
            sample_rate!(44100),
        );

        let snr_val: f64 = snr(&signal, &noise).unwrap();
        assert!(snr_val > 0.0_f64); // Signal should have higher power than noise
    }

    #[test]
    fn test_align_signals_no_offset() {
        let data = non_empty_vec![1.0f64, 2.0, 3.0, 4.0, 5.0];
        let reference = AudioSamples::from_mono_vec::<f64>(data.clone(), sample_rate!(44100));
        let signal = AudioSamples::from_mono_vec::<f64>(data, sample_rate!(44100));

        let (aligned, offset) = align_signals::<f64>(&reference, &signal).unwrap();
        assert_eq!(offset, 0);
        assert_eq!(aligned.samples_per_channel(), signal.samples_per_channel());
    }
}