spectrograms 1.1.0

High-performance FFT-based computations for audio and image processing
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
//! Python bindings for binaural audio spectrograms.
//!
//! Credit to @barrydn for the original implementation of all the spectrograms in this file.
//! Taken from https://github.com/QxLabIreland/Binaspect/

use std::num::NonZeroUsize;

use non_empty_slice::NonEmptySlice;
use numpy::{PyArray1, PyArray2, PyArrayMethods};
use pyo3::prelude::*;

use crate::binaural::{
    ILDSpectrogramParams, ILRSpectrogramParams, IPDSpectrogramParams,
    ITDSpectrogramParams,
    compute_ild_spectrogram, compute_ilr_spectrogram, compute_ilr_spectrogram_diff,
    compute_ipd_spectrogram, compute_itd_spectrogram, compute_itd_spectrogram_diff,
};
use crate::{StftPlan, python::PySpectrogramParams};

/// Parameters for computing the Interaural Time Difference (ITD) spectrogram.
///
/// ITD represents the time difference between when a sound reaches the left and right ears,
/// which is a primary cue for sound localization, especially at low frequencies.
///
/// The ITD spectrogram captures how this time difference varies across frequency and time,
/// providing insight into the spatial properties of binaural audio signals.
#[pyclass(name = "ITDSpectrogramParams", from_py_object)]
#[derive(Debug, Clone)]
pub struct PyITDSpectrogramParams {
    pub(crate) inner: ITDSpectrogramParams,
}

#[pymethods]
impl PyITDSpectrogramParams {
    /// Create new ITD spectrogram parameters.
    ///
    /// Parameters
    /// ----------
    /// spectrogram_params : SpectrogramParams
    ///     Base spectrogram parameters (FFT size, hop length, window, etc.)
    /// start_freq : float, optional
    ///     Lower frequency bound in Hz for ITD analysis (default: 50.0)
    /// end_freq : float, optional
    ///     Upper frequency bound in Hz for ITD analysis (default: 620.0)
    /// magphase_power : int, optional
    ///     Power to raise magnitude-phase product to (default: 1)
    ///
    /// Returns
    /// -------
    /// ITDSpectrogramParams
    ///     Configured ITD spectrogram parameters
    #[new]
    #[pyo3(signature = (spectrogram_params: "SpectrogramParams", start_freq: "float" = 50.0, end_freq: "float" = 620.0, magphase_power: "Optional[int]" = 1), text_signature = "(spectrogram_params: SpectrogramParams, start_freq: float = 50.0, end_freq: float = 620.0, magphase_power: Optional[int] = 1) -> ITDSpectrogramParams")]
    fn new(
        spectrogram_params: PySpectrogramParams,
        start_freq: Option<f64>,
        end_freq: Option<f64>,
        magphase_power: Option<usize>,
    ) -> Self {
        let inner = ITDSpectrogramParams {
            spectrogram_params: spectrogram_params.into(),
            start_freq: start_freq.unwrap_or(50.0),
            end_freq: end_freq.unwrap_or(620.0),
            magphase_power: magphase_power
                .and_then(|p| NonZeroUsize::new(p))
                .unwrap_or_else(|| crate::nzu!(1)),
        };
        Self { inner }
    }

    /// Get the base spectrogram parameters.
    ///
    /// Returns
    /// -------
    /// SpectrogramParams
    ///     Base spectrogram configuration
    #[getter]
    fn spectrogram_params(&self) -> PySpectrogramParams {
        PySpectrogramParams::from(self.inner.spectrogram_params.clone())
    }

    /// Get the lower frequency bound.
    ///
    /// Returns
    /// -------
    /// float
    ///     Lower frequency bound in Hz
    #[getter]
    fn start_freq(&self) -> f64 {
        self.inner.start_freq
    }

    /// Get the upper frequency bound.
    ///
    /// Returns
    /// -------
    /// float
    ///     Upper frequency bound in Hz
    #[getter]
    fn end_freq(&self) -> f64 {
        self.inner.end_freq
    }

    /// Get the magnitude-phase power parameter.
    ///
    /// Returns
    /// -------
    /// int
    ///     Power to raise magnitude-phase product to
    #[getter]
    fn magphase_power(&self) -> NonZeroUsize {
        self.inner.magphase_power
    }
}

impl From<ITDSpectrogramParams> for PyITDSpectrogramParams {
    #[inline]
    fn from(inner: ITDSpectrogramParams) -> Self {
        Self { inner }
    }
}

impl From<PyITDSpectrogramParams> for ITDSpectrogramParams {
    #[inline]
    fn from(val: PyITDSpectrogramParams) -> Self {
        val.inner
    }
}

/// Compute the Interaural Time Difference (ITD) spectrogram for a stereo audio signal.
///
/// Parameters
/// ----------
/// audio : list[numpy.typing.NDArray[numpy.float64]]
///     List containing two 1D arrays [left_channel, right_channel]
/// params : ITDSpectrogramParams
///     ITD spectrogram parameters
///
/// Returns
/// -------
/// numpy.typing.NDArray[numpy.float64]
///     2D array containing the ITD spectrogram
///
/// Raises
/// ------
/// RuntimeError
///     If STFT plan creation or ITD computation fails
/// ValueError
///     If audio arrays are not contiguous or not of type float64
#[pyfunction(name = "compute_itd_spectrogram")]
#[pyo3(signature = (audio: "list[numpy.typing.NDArray[numpy.float64]]", params: "ITDSpectrogramParams"), text_signature = "(audio: list[numpy.typing.NDArray[numpy.float64]], params: ITDSpectrogramParams) -> numpy.typing.NDArray[numpy.float64]")]
fn py_compute_itd_spectrogram<'py>(
    py: Python<'py>,
    audio: [Bound<'py, PyArray1<f64>>; 2],
    params: &'py PyITDSpectrogramParams,
) -> PyResult<Bound<'py, PyArray2<f64>>> {
    let mut plan: StftPlan = StftPlan::new(&params.inner.spectrogram_params).map_err(|e| {
        PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!(
            "Failed to create STFT plan: {}",
            e
        ))
    })?;

    let left_slice = unsafe {
        NonEmptySlice::new_unchecked(audio[0].as_slice().map_err(|_| {
            PyErr::new::<pyo3::exceptions::PyValueError, _>(
                "Left audio array must be contiguous and of type float64.",
            )
        })?)
    };

    let right_slice = unsafe {
        NonEmptySlice::new_unchecked(audio[1].as_slice().map_err(|_| {
            PyErr::new::<pyo3::exceptions::PyValueError, _>(
                "Right audio array must be contiguous and of type float64.",
            )
        })?)
    };
    let audio_slices = [left_slice, right_slice];

    let itd_spectrogram =
        compute_itd_spectrogram(audio_slices, &params.inner, &mut plan).map_err(|e| {
            PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!(
                "Failed to compute ITD spectrogram: {}",
                e
            ))
        })?;

    let py_array = PyArray2::from_owned_array(py, itd_spectrogram.data);
    Ok(py_array.into())
}

/// Parameters for computing the Interaural Phase Difference (IPD) spectrogram.
///
/// IPD represents the phase difference between the left and right ear signals,
/// which provides spatial cues, particularly at higher frequencies where ITD becomes ambiguous.
#[pyclass(name = "IPDSpectrogramParams", from_py_object)]
#[derive(Debug, Clone)]
pub struct PyIPDSpectrogramParams {
    pub(crate) inner: IPDSpectrogramParams,
}

#[pymethods]
impl PyIPDSpectrogramParams {
    /// Create new IPD spectrogram parameters.
    ///
    /// Parameters
    /// ----------
    /// spectrogram_params : SpectrogramParams
    ///     Base spectrogram parameters (FFT size, hop length, window, etc.)
    /// start_freq : float, optional
    ///     Lower frequency bound in Hz for IPD analysis (default: 50.0)
    /// end_freq : float, optional
    ///     Upper frequency bound in Hz for IPD analysis (default: 620.0)
    /// wrapped : bool, optional
    ///     If True, return wrapped phase difference in [-π, π], otherwise unwrapped (default: False)
    ///
    /// Returns
    /// -------
    /// IPDSpectrogramParams
    ///     Configured IPD spectrogram parameters
    ///
    /// Raises
    /// ------
    /// ValueError
    ///     If parameters are invalid
    #[new]
    #[pyo3(signature = (spectrogram_params, start_freq = 50.0, end_freq = 620.0, wrapped = false), text_signature = "(spectrogram_params: SpectrogramParams, start_freq: float = 50.0, end_freq: float = 620.0, wrapped: bool = False) -> IPDSpectrogramParams")]
    fn new(
        spectrogram_params: PySpectrogramParams,
        start_freq: Option<f64>,
        end_freq: Option<f64>,
        wrapped: Option<bool>,
    ) -> PyResult<Self> {
        let inner = IPDSpectrogramParams::new(
            spectrogram_params.into(),
            start_freq.unwrap_or(50.0),
            end_freq.unwrap_or(620.0),
            wrapped.unwrap_or(false),
        ).map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("{}", e)))?;
        Ok(Self { inner })
    }

    /// Get the base spectrogram parameters.
    ///
    /// Returns
    /// -------
    /// SpectrogramParams
    ///     Base spectrogram configuration
    #[getter]
    fn spectrogram_params(&self) -> PySpectrogramParams {
        PySpectrogramParams::from(self.inner.spectrogram_params.clone())
    }

    /// Get the lower frequency bound.
    ///
    /// Returns
    /// -------
    /// float
    ///     Lower frequency bound in Hz
    #[getter]
    fn start_freq(&self) -> f64 {
        self.inner.start_freq
    }

    /// Get the upper frequency bound.
    ///
    /// Returns
    /// -------
    /// float
    ///     Upper frequency bound in Hz
    #[getter]
    fn end_freq(&self) -> f64 {
        self.inner.end_freq
    }

    /// Get whether phase difference is wrapped.
    ///
    /// Returns
    /// -------
    /// bool
    ///     True if wrapped to [-π, π], False if unwrapped
    #[getter]
    fn wrapped(&self) -> bool {
        self.inner.wrapped
    }
}

/// Compute the Interaural Phase Difference (IPD) spectrogram for a stereo audio signal.
///
/// Parameters
/// ----------
/// audio : list[numpy.typing.NDArray[numpy.float64]]
///     List containing two 1D arrays [left_channel, right_channel]
/// params : IPDSpectrogramParams
///     IPD spectrogram parameters
///
/// Returns
/// -------
/// numpy.typing.NDArray[numpy.float64]
///     2D array containing the IPD spectrogram
///
/// Raises
/// ------
/// RuntimeError
///     If STFT plan creation or IPD computation fails
/// ValueError
///     If audio arrays are not contiguous or not of type float64
#[pyfunction(name = "compute_ipd_spectrogram")]
#[pyo3(signature = (audio: "list[numpy.typing.NDArray[numpy.float64]]", params: "IPDSpectrogramParams"), text_signature = "(audio: list[numpy.typing.NDArray[numpy.float64]], params: IPDSpectrogramParams) -> numpy.typing.NDArray[numpy.float64]")]
fn py_compute_ipd_spectrogram<'py>(
    py: Python<'py>,
    audio: [Bound<'py, PyArray1<f64>>; 2],
    params: &'py PyIPDSpectrogramParams,
) -> PyResult<Bound<'py, PyArray2<f64>>> {
    let mut plan = StftPlan::new(&params.inner.spectrogram_params).map_err(|e| {
        PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Failed to create STFT plan: {}", e))
    })?;

    let left_slice = unsafe {
        NonEmptySlice::new_unchecked(audio[0].as_slice().map_err(|_| {
            PyErr::new::<pyo3::exceptions::PyValueError, _>("Left audio array must be contiguous and of type float64.")
        })?)
    };

    let right_slice = unsafe {
        NonEmptySlice::new_unchecked(audio[1].as_slice().map_err(|_| {
            PyErr::new::<pyo3::exceptions::PyValueError, _>("Right audio array must be contiguous and of type float64.")
        })?)
    };

    let ipd_spectrogram = compute_ipd_spectrogram([left_slice, right_slice], &params.inner, &mut plan)
        .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Failed to compute IPD spectrogram: {}", e)))?;

    Ok(PyArray2::from_owned_array(py, ipd_spectrogram.data).into())
}

/// Parameters for computing the Interaural Level Difference (ILD) spectrogram.
///
/// ILD represents the difference in sound intensity between the left and right ears,
/// which is an important cue for sound localization, especially at higher frequencies.
#[pyclass(name = "ILDSpectrogramParams", from_py_object)]
#[derive(Debug, Clone)]
pub struct PyILDSpectrogramParams {
    pub(crate) inner: ILDSpectrogramParams,
}

#[pymethods]
impl PyILDSpectrogramParams {
    /// Create new ILD spectrogram parameters.
    ///
    /// Parameters
    /// ----------
    /// spectrogram_params : SpectrogramParams
    ///     Base spectrogram parameters (FFT size, hop length, window, etc.)
    /// start_freq : float, optional
    ///     Lower frequency bound in Hz for ILD analysis (default: 1700.0)
    /// end_freq : float, optional
    ///     Upper frequency bound in Hz for ILD analysis (default: 4600.0)
    ///
    /// Returns
    /// -------
    /// ILDSpectrogramParams
    ///     Configured ILD spectrogram parameters
    ///
    /// Raises
    /// ------
    /// ValueError
    ///     If parameters are invalid
    #[new]
    #[pyo3(signature = (spectrogram_params: "SpectrogramParams", start_freq: "float" = 1700.0, end_freq: "float" = 4600.0), text_signature = "(spectrogram_params: SpectrogramParams, start_freq: float = 1700.0, end_freq: float = 4600.0) -> ILDSpectrogramParams")]
    fn new(
        spectrogram_params: PySpectrogramParams,
        start_freq: Option<f64>,
        end_freq: Option<f64>,
    ) -> PyResult<Self> {
        let inner = ILDSpectrogramParams::new(
            spectrogram_params.into(),
            start_freq.unwrap_or(1700.0),
            end_freq.unwrap_or(4600.0),
        ).map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("{}", e)))?;
        Ok(Self { inner })
    }

    /// Get the base spectrogram parameters.
    ///
    /// Returns
    /// -------
    /// SpectrogramParams
    ///     Base spectrogram configuration
    #[getter]
    fn spectrogram_params(&self) -> PySpectrogramParams {
        PySpectrogramParams::from(self.inner.spectrogram_params.clone())
    }

    /// Get the lower frequency bound.
    ///
    /// Returns
    /// -------
    /// float
    ///     Lower frequency bound in Hz
    #[getter]
    fn start_freq(&self) -> f64 {
        self.inner.start_freq
    }

    /// Get the upper frequency bound.
    ///
    /// Returns
    /// -------
    /// float
    ///     Upper frequency bound in Hz
    #[getter]
    fn end_freq(&self) -> f64 {
        self.inner.end_freq
    }
}

/// Compute the Interaural Level Difference (ILD) spectrogram for a stereo audio signal.
///
/// Parameters
/// ----------
/// audio : list[numpy.typing.NDArray[numpy.float64]]
///     List containing two 1D arrays [left_channel, right_channel]
/// params : ILDSpectrogramParams
///     ILD spectrogram parameters
///
/// Returns
/// -------
/// numpy.typing.NDArray[numpy.float64]
///     2D array containing the ILD spectrogram
///
/// Raises
/// ------
/// RuntimeError
///     If STFT plan creation or ILD computation fails
/// ValueError
///     If audio arrays are not contiguous or not of type float64
#[pyfunction(name = "compute_ild_spectrogram")]
#[pyo3(signature = (audio: "list[numpy.typing.NDArray[numpy.float64]]", params: "ILDSpectrogramParams"), text_signature = "(audio: list[numpy.typing.NDArray[numpy.float64]], params: ILDSpectrogramParams) -> numpy.typing.NDArray[numpy.float64]")]
fn py_compute_ild_spectrogram<'py>(
    py: Python<'py>,
    audio: [Bound<'py, PyArray1<f64>>; 2],
    params: &'py PyILDSpectrogramParams,
) -> PyResult<Bound<'py, PyArray2<f64>>> {
    let mut plan = StftPlan::new(&params.inner.spectrogram_params).map_err(|e| {
        PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Failed to create STFT plan: {}", e))
    })?;

    let left_slice = unsafe {
        NonEmptySlice::new_unchecked(audio[0].as_slice().map_err(|_| {
            PyErr::new::<pyo3::exceptions::PyValueError, _>("Left audio array must be contiguous and of type float64.")
        })?)
    };

    let right_slice = unsafe {
        NonEmptySlice::new_unchecked(audio[1].as_slice().map_err(|_| {
            PyErr::new::<pyo3::exceptions::PyValueError, _>("Right audio array must be contiguous and of type float64.")
        })?)
    };

    let ild_spectrogram = compute_ild_spectrogram([left_slice, right_slice], &params.inner, &mut plan)
        .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Failed to compute ILD spectrogram: {}", e)))?;

    Ok(PyArray2::from_owned_array(py, ild_spectrogram.data).into())
}


/// Parameters for computing the Interaural Level Ratio (ILR) spectrogram.
///
/// ILR represents the ratio of sound levels between the left and right ears,
/// providing a normalized measure of level differences for spatial analysis.
#[pyclass(name = "ILRSpectrogramParams", from_py_object)]
#[derive(Debug, Clone)]
pub struct PyILRSpectrogramParams {
    pub(crate) inner: ILRSpectrogramParams,
}

#[pymethods]
impl PyILRSpectrogramParams {
    /// Create new ILR spectrogram parameters.
    ///
    /// Parameters
    /// ----------
    /// spectrogram_params : SpectrogramParams
    ///     Base spectrogram parameters (FFT size, hop length, window, etc.)
    /// start_freq : float, optional
    ///     Lower frequency bound in Hz for ILR analysis (default: 1700.0)
    /// end_freq : float, optional
    ///     Upper frequency bound in Hz for ILR analysis (default: 4600.0)
    ///
    /// Returns
    /// -------
    /// ILRSpectrogramParams
    ///     Configured ILR spectrogram parameters
    ///
    /// Raises
    /// ------
    /// ValueError
    ///     If parameters are invalid
    #[new]
    #[pyo3(signature = (spectrogram_params: "SpectrogramParams", start_freq: "float" = 1700.0, end_freq: "float" = 4600.0), text_signature = "(spectrogram_params: SpectrogramParams, start_freq: float = 1700.0, end_freq: float = 4600.0) -> ILRSpectrogramParams")]
    fn new(
        spectrogram_params: PySpectrogramParams,
        start_freq: Option<f64>,
        end_freq: Option<f64>,
    ) -> PyResult<Self> {
        let inner = ILRSpectrogramParams::new(
            spectrogram_params.into(),
            start_freq.unwrap_or(1700.0),
            end_freq.unwrap_or(4600.0),
        ).map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("{}", e)))?;
        Ok(Self { inner })
    }

    /// Get the base spectrogram parameters.
    ///
    /// Returns
    /// -------
    /// SpectrogramParams
    ///     Base spectrogram configuration
    #[getter]
    fn spectrogram_params(&self) -> PySpectrogramParams {
        PySpectrogramParams::from(self.inner.spectrogram_params.clone())
    }

    /// Get the lower frequency bound.
    ///
    /// Returns
    /// -------
    /// float
    ///     Lower frequency bound in Hz
    #[getter]
    fn start_freq(&self) -> f64 {
        self.inner.start_freq
    }

    /// Get the upper frequency bound.
    ///
    /// Returns
    /// -------
    /// float
    ///     Upper frequency bound in Hz
    #[getter]
    fn end_freq(&self) -> f64 {
        self.inner.end_freq
    }
}

/// Compute the Interaural Level Ratio (ILR) spectrogram for a stereo audio signal.
///
/// Parameters
/// ----------
/// audio : list[numpy.typing.NDArray[numpy.float64]]
///     List containing two 1D arrays [left_channel, right_channel]
/// params : ILRSpectrogramParams
///     ILR spectrogram parameters
///
/// Returns
/// -------
/// numpy.typing.NDArray[numpy.float64]
///     2D array containing the ILR spectrogram
///
/// Raises
/// ------
/// RuntimeError
///     If STFT plan creation or ILR computation fails
/// ValueError
///     If audio arrays are not contiguous or not of type float64
#[pyfunction(name = "compute_ilr_spectrogram")]
#[pyo3(signature = (audio, params), text_signature = "(audio: list[numpy.typing.NDArray[numpy.float64]], params: ILRSpectrogramParams) -> numpy.typing.NDArray[numpy.float64]")]
fn py_compute_ilr_spectrogram<'py>(
    py: Python<'py>,
    audio: [Bound<'py, PyArray1<f64>>; 2],
    params: &'py PyILRSpectrogramParams,
) -> PyResult<Bound<'py, PyArray2<f64>>> {
    let mut plan = StftPlan::new(&params.inner.spectrogram_params).map_err(|e| {
        PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Failed to create STFT plan: {}", e))
    })?;

    let left_slice = unsafe {
        NonEmptySlice::new_unchecked(audio[0].as_slice().map_err(|_| {
            PyErr::new::<pyo3::exceptions::PyValueError, _>("Left audio array must be contiguous and of type float64.")
        })?)
    };

    let right_slice = unsafe {
        NonEmptySlice::new_unchecked(audio[1].as_slice().map_err(|_| {
            PyErr::new::<pyo3::exceptions::PyValueError, _>("Right audio array must be contiguous and of type float64.")
        })?)
    };

    let ilr_spectrogram = compute_ilr_spectrogram([left_slice, right_slice], &params.inner, &mut plan)
        .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Failed to compute ILR spectrogram: {}", e)))?;

    Ok(PyArray2::from_owned_array(py, ilr_spectrogram.data).into())
}

/// Compute the difference between two ITD spectrograms.
///
/// Parameters
/// ----------
/// reference : list[numpy.typing.NDArray[numpy.float64]]
///     List containing two 1D arrays [left_channel, right_channel] for the reference signal
/// test : list[numpy.typing.NDArray[numpy.float64]]
///     List containing two 1D arrays [left_channel, right_channel] for the test signal
/// params : ITDSpectrogramParams
///     ITD spectrogram parameters
///
/// Returns
/// -------
/// tuple[numpy.typing.NDArray[numpy.float64], float, float]
///     Tuple of (itd_time_diff, mean_diff_degrees, mean_diff_itd)
#[pyfunction(name = "compute_itd_spectrogram_diff")]
#[pyo3(signature = (reference, test, params), text_signature = "(reference: list[numpy.typing.NDArray[numpy.float64]], test: list[numpy.typing.NDArray[numpy.float64]], params: ITDSpectrogramParams) -> tuple[numpy.typing.NDArray[numpy.float64], float, float]")]
fn py_compute_itd_spectrogram_diff<'py>(
    py: Python<'py>,
    reference: [Bound<'py, PyArray1<f64>>; 2],
    test: [Bound<'py, PyArray1<f64>>; 2],
    params: &'py PyITDSpectrogramParams,
) -> PyResult<(Bound<'py, PyArray1<f64>>, f64, f64)> {
    let mut plan = StftPlan::new(&params.inner.spectrogram_params).map_err(|e| {
        PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Failed to create STFT plan: {}", e))
    })?;

    let left_ref = unsafe { NonEmptySlice::new_unchecked(reference[0].as_slice().map_err(|_| PyErr::new::<pyo3::exceptions::PyValueError, _>("Left reference array must be contiguous float64."))?) };
    let right_ref = unsafe { NonEmptySlice::new_unchecked(reference[1].as_slice().map_err(|_| PyErr::new::<pyo3::exceptions::PyValueError, _>("Right reference array must be contiguous float64."))?) };
    let left_test = unsafe { NonEmptySlice::new_unchecked(test[0].as_slice().map_err(|_| PyErr::new::<pyo3::exceptions::PyValueError, _>("Left test array must be contiguous float64."))?) };
    let right_test = unsafe { NonEmptySlice::new_unchecked(test[1].as_slice().map_err(|_| PyErr::new::<pyo3::exceptions::PyValueError, _>("Right test array must be contiguous float64."))?) };

    let (time_diff, mean_deg, mean_itd) = compute_itd_spectrogram_diff(
        [left_ref, right_ref], [left_test, right_test], &params.inner, &mut plan
    ).map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Failed to compute ITD diff: {}", e)))?;

    Ok((PyArray1::from_owned_array(py, time_diff).into(), mean_deg, mean_itd))
}

/// Compute the difference between two ILR spectrograms.
///
/// Parameters
/// ----------
/// reference : list[numpy.typing.NDArray[numpy.float64]]
///     List containing two 1D arrays [left_channel, right_channel] for the reference signal
/// test : list[numpy.typing.NDArray[numpy.float64]]
///     List containing two 1D arrays [left_channel, right_channel] for the test signal
/// params : ILRSpectrogramParams
///     ILR spectrogram parameters
///
/// Returns
/// -------
/// tuple[numpy.typing.NDArray[numpy.float64], float]
///     Tuple of (ilr_time_diff, mean_diff)
#[pyfunction(name = "compute_ilr_spectrogram_diff")]
#[pyo3(signature = (reference, test, params), text_signature = "(reference: list[numpy.typing.NDArray[numpy.float64]], test: list[numpy.typing.NDArray[numpy.float64]], params: ILRSpectrogramParams) -> tuple[numpy.typing.NDArray[numpy.float64], float]")]
fn py_compute_ilr_spectrogram_diff<'py>(
    py: Python<'py>,
    reference: [Bound<'py, PyArray1<f64>>; 2],
    test: [Bound<'py, PyArray1<f64>>; 2],
    params: &'py PyILRSpectrogramParams,
) -> PyResult<(Bound<'py, PyArray1<f64>>, f64)> {
    let mut plan = StftPlan::new(&params.inner.spectrogram_params).map_err(|e| {
        PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Failed to create STFT plan: {}", e))
    })?;

    let left_ref = unsafe { NonEmptySlice::new_unchecked(reference[0].as_slice().map_err(|_| PyErr::new::<pyo3::exceptions::PyValueError, _>("Left reference array must be contiguous float64."))?) };
    let right_ref = unsafe { NonEmptySlice::new_unchecked(reference[1].as_slice().map_err(|_| PyErr::new::<pyo3::exceptions::PyValueError, _>("Right reference array must be contiguous float64."))?) };
    let left_test = unsafe { NonEmptySlice::new_unchecked(test[0].as_slice().map_err(|_| PyErr::new::<pyo3::exceptions::PyValueError, _>("Left test array must be contiguous float64."))?) };
    let right_test = unsafe { NonEmptySlice::new_unchecked(test[1].as_slice().map_err(|_| PyErr::new::<pyo3::exceptions::PyValueError, _>("Right test array must be contiguous float64."))?) };

    let (time_diff, mean_diff) = compute_ilr_spectrogram_diff(
        [left_ref, right_ref], [left_test, right_test], &params.inner, &mut plan
    ).map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Failed to compute ILR diff: {}", e)))?;

    Ok((PyArray1::from_owned_array(py, time_diff).into(), mean_diff))
}

pub fn register(_py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
    // ITD
    m.add_function(wrap_pyfunction!(py_compute_itd_spectrogram, m)?)?;
    m.add_function(wrap_pyfunction!(py_compute_itd_spectrogram_diff, m)?)?;
    m.add_class::<PyITDSpectrogramParams>()?;

    // IPD
    m.add_function(wrap_pyfunction!(py_compute_ipd_spectrogram, m)?)?;
    m.add_class::<PyIPDSpectrogramParams>()?;

    // ILD
    m.add_function(wrap_pyfunction!(py_compute_ild_spectrogram, m)?)?;
    m.add_class::<PyILDSpectrogramParams>()?;

    // ILR
    m.add_function(wrap_pyfunction!(py_compute_ilr_spectrogram, m)?)?;
    m.add_function(wrap_pyfunction!(py_compute_ilr_spectrogram_diff, m)?)?;
    m.add_class::<PyILRSpectrogramParams>()?;

    Ok(())
}