spectrograms/sample.rs
1//! Sealed scalar trait abstracting the float precision used by the FFT backend.
2//!
3//! [`Sample`] is implemented for `f32` and `f64` only. It ties a concrete scalar
4//! type to the associated FFT plan types and constructors provided by the active
5//! backend (realfft or fftw), allowing the rest of the crate to be written
6//! generically over precision.
7
8use num_traits::{Float, FloatConst, NumAssign};
9
10use crate::SpectrogramResult;
11use crate::fft_backend::{C2cPlan, C2rPlan, C2rPlan2d, R2cPlan, R2cPlan2d};
12
13mod sealed {
14 pub trait Sealed {}
15 impl Sealed for f32 {}
16 impl Sealed for f64 {}
17}
18
19/// Sealed trait describing a float scalar the FFT backend can operate on.
20///
21/// Implemented for `f32` and `f64`. Each implementor exposes the backend's
22/// concrete plan types and constructors for those plans.
23pub trait Sample:
24 sealed::Sealed
25 + Float
26 + FloatConst
27 + NumAssign
28 + Copy
29 + Send
30 + Sync
31 + 'static
32 + core::fmt::Debug
33 + Default
34{
35 /// Real-to-complex 1D plan type for this scalar.
36 type R2cPlan: R2cPlan<Self>;
37 /// Complex-to-real 1D plan type for this scalar.
38 type C2rPlan: C2rPlan<Self>;
39 /// Complex-to-complex 1D plan type for this scalar.
40 type C2cPlan: C2cPlan<Self>;
41 /// Real-to-complex 2D plan type for this scalar.
42 type R2cPlan2d: R2cPlan2d<Self>;
43 /// Complex-to-real 2D plan type for this scalar.
44 type C2rPlan2d: C2rPlan2d<Self>;
45
46 /// Build a real-to-complex 1D FFT plan of length `n_fft`.
47 ///
48 /// # Errors
49 ///
50 /// Returns an error if the backend fails to construct the plan.
51 fn plan_r2c(n_fft: usize) -> SpectrogramResult<Self::R2cPlan>;
52
53 /// Build a complex-to-real 1D inverse FFT plan of length `n_fft`.
54 ///
55 /// # Errors
56 ///
57 /// Returns an error if the backend fails to construct the plan.
58 fn plan_c2r(n_fft: usize) -> SpectrogramResult<Self::C2rPlan>;
59
60 /// Build a complex-to-complex 1D FFT plan of length `n_fft`.
61 ///
62 /// # Errors
63 ///
64 /// Returns an error if the backend fails to construct the plan.
65 fn plan_c2c(n_fft: usize) -> SpectrogramResult<Self::C2cPlan>;
66
67 /// Build a real-to-complex 2D FFT plan of dimensions `nrows` x `ncols`.
68 ///
69 /// # Errors
70 ///
71 /// Returns an error if the backend fails to construct the plan.
72 fn plan_r2c_2d(nrows: usize, ncols: usize) -> SpectrogramResult<Self::R2cPlan2d>;
73
74 /// Build a complex-to-real 2D inverse FFT plan of dimensions `nrows` x `ncols`.
75 ///
76 /// # Errors
77 ///
78 /// Returns an error if the backend fails to construct the plan.
79 fn plan_c2r_2d(nrows: usize, ncols: usize) -> SpectrogramResult<Self::C2rPlan2d>;
80
81 /// Convert an `f64` constant/literal to this scalar (for PI-derived consts, casts).
82 fn from_f64(x: f64) -> Self;
83
84 /// Convert a `usize` (e.g. an index or length) to this scalar.
85 fn from_usize(n: usize) -> Self;
86}