Skip to main content

autoeq_core/
curve.rs

1use ndarray::Array1;
2use serde::{Deserialize, Serialize};
3use sha2::{Digest, Sha256};
4
5use crate::error::{AutoeqError, Result};
6
7/// A struct to hold frequency and SPL data.
8/// Re-exported from the main autoeq crate for compatibility.
9///
10/// Optional fields added for GD-Opt v2 (§2.3 of
11/// `docs/gd_opt_v2_plan.md`):
12/// - `coherence`, `noise_floor_db` come from the extended CSVs.
13/// - `min_phase`, `excess_phase`, `excess_delay_ms` are derived at
14///   load time and cached; never persisted.
15///
16/// Construct curves with struct-update syntax — the `Default` impl
17/// sets every optional field to `None`:
18///
19/// ```
20/// # use autoeq_core::Curve;
21/// # use ndarray::Array1;
22/// let freq = Array1::from_vec(vec![20.0, 200.0, 2000.0]);
23/// let spl = Array1::from_vec(vec![0.0, 0.0, 0.0]);
24/// let curve = Curve { freq, spl, ..Default::default() };
25/// ```
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct Curve {
28    /// Frequency points in Hz
29    pub freq: Array1<f64>,
30    /// Sound Pressure Level in dB
31    pub spl: Array1<f64>,
32    /// Phase in degrees (optional)
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub phase: Option<Array1<f64>>,
35    /// Magnitude-squared coherence γ²(f) from the multi-sweep average.
36    /// Persisted to CSV as `coherence`; consumed by the GD confidence
37    /// gate and the optimiser objective weight in GD-Opt v2.
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub coherence: Option<Array1<f64>>,
40    /// Per-bin noise-floor estimate in dB, derived from the
41    /// pre-silence window. Persisted to CSV as `noise_floor_db`.
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub noise_floor_db: Option<Array1<f64>>,
44    /// Minimum-phase component in degrees. Recomputed at load time
45    /// via Hilbert-on-log-magnitude; never persisted.
46    #[serde(default, skip_serializing)]
47    pub min_phase: Option<Array1<f64>>,
48    /// Excess-phase residual in degrees after removing the
49    /// minimum-phase component and the linear-delay term. Never
50    /// persisted.
51    #[serde(default, skip_serializing)]
52    pub excess_phase: Option<Array1<f64>>,
53    /// Linear-delay term extracted during decomposition, in
54    /// milliseconds. Never persisted.
55    #[serde(default, skip_serializing)]
56    pub excess_delay_ms: Option<f64>,
57}
58
59impl Default for Curve {
60    fn default() -> Self {
61        Self {
62            freq: Array1::from_vec(Vec::new()),
63            spl: Array1::from_vec(Vec::new()),
64            phase: None,
65            coherence: None,
66            noise_floor_db: None,
67            min_phase: None,
68            excess_phase: None,
69            excess_delay_ms: None,
70        }
71    }
72}
73
74impl Curve {
75    /// Return the versioned canonical byte representation used for content
76    /// identity. Derived cache fields are deliberately excluded: they are
77    /// implementation details which are recomputed when a measurement loads.
78    pub fn canonical_content_bytes(&self) -> Result<Vec<u8>> {
79        self.validate("curve content hash")?;
80
81        let mut bytes = b"autoeq.curve.content.v1\0".to_vec();
82        append_array(&mut bytes, b"freq", &self.freq);
83        append_array(&mut bytes, b"spl", &self.spl);
84        append_optional_array(&mut bytes, b"phase", self.phase.as_ref());
85        append_optional_array(&mut bytes, b"coherence", self.coherence.as_ref());
86        append_optional_array(&mut bytes, b"noise_floor_db", self.noise_floor_db.as_ref());
87        Ok(bytes)
88    }
89
90    /// SHA-256 fingerprint of the persisted numerical measurement content.
91    ///
92    /// `-0.0` is canonicalised to `0.0`, while invalid/non-finite values are
93    /// rejected by [`Self::validate`] before hashing.
94    pub fn content_hash(&self) -> Result<String> {
95        let digest = Sha256::digest(self.canonical_content_bytes()?);
96        Ok(digest.iter().map(|byte| format!("{byte:02x}")).collect())
97    }
98
99    /// Validate a frequency grid used by public DSP and optimization APIs.
100    pub fn validate_frequency_grid(freq: &Array1<f64>, context: &str) -> Result<()> {
101        if freq.len() < 2 {
102            return Err(AutoeqError::InvalidMeasurement {
103                message: format!("{context} needs at least two frequency points"),
104            });
105        }
106        if let Some((index, value)) = freq
107            .iter()
108            .copied()
109            .enumerate()
110            .find(|(_, value)| !value.is_finite() || *value <= 0.0)
111        {
112            return Err(AutoeqError::InvalidMeasurement {
113                message: format!(
114                    "{context} frequency at index {index} must be finite and positive, got {value}"
115                ),
116            });
117        }
118        if let Some((index, pair)) = freq
119            .windows(2)
120            .into_iter()
121            .enumerate()
122            .find(|(_, pair)| pair[0] >= pair[1])
123        {
124            return Err(AutoeqError::InvalidMeasurement {
125                message: format!(
126                    "{context} frequencies must be strictly increasing; indices {index} and {} contain {} then {}",
127                    index + 1,
128                    pair[0],
129                    pair[1]
130                ),
131            });
132        }
133        Ok(())
134    }
135
136    /// Validate the core and optional arrays of a measurement curve.
137    pub fn validate(&self, context: &str) -> Result<()> {
138        Self::validate_frequency_grid(&self.freq, context)?;
139        let expected = self.freq.len();
140        if self.spl.len() != expected {
141            return Err(AutoeqError::InvalidMeasurement {
142                message: format!(
143                    "{context} has mismatched frequency/SPL lengths: {expected} and {}",
144                    self.spl.len()
145                ),
146            });
147        }
148        if let Some((index, value)) = self
149            .spl
150            .iter()
151            .copied()
152            .enumerate()
153            .find(|(_, value)| !value.is_finite())
154        {
155            return Err(AutoeqError::InvalidMeasurement {
156                message: format!("{context} SPL at index {index} must be finite, got {value}"),
157            });
158        }
159
160        for (name, values) in [
161            ("phase", self.phase.as_ref()),
162            ("coherence", self.coherence.as_ref()),
163            ("noise_floor_db", self.noise_floor_db.as_ref()),
164            ("min_phase", self.min_phase.as_ref()),
165            ("excess_phase", self.excess_phase.as_ref()),
166        ] {
167            let Some(values) = values else {
168                continue;
169            };
170            if values.len() != expected {
171                return Err(AutoeqError::InvalidMeasurement {
172                    message: format!(
173                        "{context} {name} length {} does not match frequency length {expected}",
174                        values.len()
175                    ),
176                });
177            }
178            if let Some((index, value)) = values
179                .iter()
180                .copied()
181                .enumerate()
182                .find(|(_, value)| !value.is_finite())
183            {
184                return Err(AutoeqError::InvalidMeasurement {
185                    message: format!(
186                        "{context} {name} at index {index} must be finite, got {value}"
187                    ),
188                });
189            }
190        }
191
192        if self.excess_delay_ms.is_some_and(|value| !value.is_finite()) {
193            return Err(AutoeqError::InvalidMeasurement {
194                message: format!("{context} excess_delay_ms must be finite"),
195            });
196        }
197        Ok(())
198    }
199
200    /// Populate `min_phase`, `excess_phase`, and `excess_delay_ms` from the
201    /// measured magnitude + phase via Hilbert-on-log-magnitude decomposition
202    /// (§2.3 of `docs/gd_opt_v2_plan.md`).
203    ///
204    /// **Idempotent**: repeated calls are no-ops after the first success.
205    ///
206    /// **No-op guards** (all three cache fields stay `None`):
207    /// - `phase` is `None`
208    /// - `freq`, `spl`, and `phase` do not all share the same length
209    ///
210    /// The decomposition steps are:
211    /// 1. Unwrap the measured phase to remove ±180° discontinuities.
212    /// 2. Reconstruct minimum phase from magnitude via Hilbert transform of
213    ///    `ln|H|` (Hilbert-on-log-magnitude). Result is in degrees.
214    /// 3. `excess_phase = unwrapped_measured − min_phase` (degrees).
215    /// 4. Fit a linear slope `−2πfτ` to the excess phase via ordinary
216    ///    least-squares to yield `excess_delay_ms = τ × 1000`.
217    ///
218    /// Phase values are in **degrees** throughout, matching `Curve::phase`.
219    pub fn decompose_into_cache(&mut self) {
220        // Already computed — idempotent.
221        if self.min_phase.is_some() {
222            return;
223        }
224
225        // Guard: phase must be present.
226        let measured_phase = match self.phase.as_ref() {
227            Some(p) => p,
228            None => return,
229        };
230
231        // Guard: all three arrays must have the same length and be non-empty.
232        let n = self.freq.len();
233        if n != self.spl.len() || n != measured_phase.len() || n == 0 {
234            return;
235        }
236
237        use crate::phase_utils::{
238            compute_excess_phase, estimate_delay_from_excess_phase, reconstruct_minimum_phase,
239            unwrap_phase_degrees,
240        };
241
242        // Step 1: unwrap the measured phase to remove ±180° discontinuities.
243        let unwrapped = unwrap_phase_degrees(measured_phase);
244
245        // Step 2: reconstruct minimum phase from the magnitude via Hilbert
246        //         transform of ln|H|.
247        let min_phase = reconstruct_minimum_phase(&self.freq, &self.spl);
248
249        // Step 3: excess phase = unwrapped measured − minimum phase.
250        let excess_phase = compute_excess_phase(&unwrapped, &min_phase);
251
252        // Step 4: fit the linear delay term τ from the excess phase slope.
253        //         delay_ms is the propagation delay in milliseconds.
254        let (delay_ms, _residual) = estimate_delay_from_excess_phase(&self.freq, &excess_phase);
255
256        self.min_phase = Some(min_phase);
257        self.excess_phase = Some(excess_phase);
258        self.excess_delay_ms = Some(delay_ms);
259    }
260}
261
262fn append_array(bytes: &mut Vec<u8>, name: &[u8], values: &Array1<f64>) {
263    bytes.extend_from_slice(&(name.len() as u32).to_le_bytes());
264    bytes.extend_from_slice(name);
265    bytes.extend_from_slice(&(values.len() as u64).to_le_bytes());
266    for value in values {
267        let canonical = if *value == 0.0 { 0.0 } else { *value };
268        bytes.extend_from_slice(&canonical.to_bits().to_le_bytes());
269    }
270}
271
272fn append_optional_array(bytes: &mut Vec<u8>, name: &[u8], values: Option<&Array1<f64>>) {
273    bytes.push(values.is_some() as u8);
274    if let Some(values) = values {
275        append_array(bytes, name, values);
276    }
277}
278
279#[cfg(test)]
280mod validation_tests {
281    use super::*;
282
283    fn valid_curve() -> Curve {
284        Curve {
285            freq: Array1::from_vec(vec![20.0, 100.0, 1_000.0]),
286            spl: Array1::from_vec(vec![80.0, 81.0, 79.0]),
287            phase: Some(Array1::from_vec(vec![0.0, -5.0, -20.0])),
288            ..Default::default()
289        }
290    }
291
292    #[test]
293    fn curve_validation_accepts_finite_matching_data() {
294        valid_curve().validate("test curve").unwrap();
295    }
296
297    #[test]
298    fn curve_validation_rejects_empty_and_single_bin_curves() {
299        for curve in [
300            Curve::default(),
301            Curve {
302                freq: Array1::from_vec(vec![100.0]),
303                spl: Array1::from_vec(vec![80.0]),
304                ..Default::default()
305            },
306        ] {
307            assert!(matches!(
308                curve.validate("test curve"),
309                Err(AutoeqError::InvalidMeasurement { .. })
310            ));
311        }
312    }
313
314    #[test]
315    fn curve_validation_rejects_non_finite_or_unsorted_frequencies() {
316        for frequencies in [
317            vec![20.0, f64::NAN],
318            vec![20.0, f64::INFINITY],
319            vec![20.0, 0.0],
320            vec![100.0, 20.0],
321            vec![20.0, 20.0],
322        ] {
323            let mut curve = valid_curve();
324            curve.freq = Array1::from_vec(frequencies);
325            curve.spl = Array1::zeros(curve.freq.len());
326            curve.phase = None;
327            assert!(matches!(
328                curve.validate("test curve"),
329                Err(AutoeqError::InvalidMeasurement { .. })
330            ));
331        }
332    }
333
334    #[test]
335    fn curve_validation_rejects_non_finite_spl_and_mismatched_arrays() {
336        for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
337            let mut non_finite = valid_curve();
338            non_finite.spl[1] = value;
339            assert!(
340                non_finite.validate("test curve").is_err(),
341                "accepted non-finite SPL {value}"
342            );
343
344            let mut non_finite_phase = valid_curve();
345            non_finite_phase.phase = Some(Array1::from_vec(vec![0.0, value, 0.0]));
346            assert!(
347                non_finite_phase.validate("test curve").is_err(),
348                "accepted non-finite phase {value}"
349            );
350        }
351
352        let mut spl_mismatch = valid_curve();
353        spl_mismatch.spl = Array1::zeros(2);
354        assert!(spl_mismatch.validate("test curve").is_err());
355
356        let mut phase_mismatch = valid_curve();
357        phase_mismatch.phase = Some(Array1::zeros(2));
358        assert!(phase_mismatch.validate("test curve").is_err());
359    }
360
361    #[test]
362    fn content_hash_is_stable_and_excludes_derived_caches() {
363        let curve = valid_curve();
364        let expected = curve.content_hash().unwrap();
365
366        let mut cached = curve.clone();
367        cached.min_phase = Some(Array1::from_vec(vec![1.0, 2.0, 3.0]));
368        cached.excess_phase = Some(Array1::from_vec(vec![4.0, 5.0, 6.0]));
369        cached.excess_delay_ms = Some(1.5);
370        assert_eq!(cached.content_hash().unwrap(), expected);
371
372        let mut signed_zero = curve;
373        signed_zero.spl[0] = -0.0;
374        let mut zero = signed_zero.clone();
375        zero.spl[0] = 0.0;
376        assert_eq!(
377            signed_zero.content_hash().unwrap(),
378            zero.content_hash().unwrap()
379        );
380    }
381}
382
383#[cfg(test)]
384mod decompose_cache_tests {
385
386    use super::super::Curve;
387    use ndarray::Array1;
388    use std::f64::consts::PI;
389
390    fn log_freq_grid(n: usize, lo: f64, hi: f64) -> Array1<f64> {
391        Array1::from_vec(
392            (0..n)
393                .map(|i| lo * (hi / lo).powf(i as f64 / (n - 1) as f64))
394                .collect(),
395        )
396    }
397
398    // Test 1 — minimum-phase input (1st-order lowpass)
399    //
400    // H(jω) = ω₀ / (ω₀ + jω).  This is minimum phase.
401    // Magnitude: |H| = ω₀ / √(ω₀²+ω²)   → magnitude_db = 20·log₁₀|H|
402    // Analytical minimum phase: φ_min = −arctan(ω/ω₀) [degrees]
403    //
404    // Post GD-1d.1 the log-aware Hilbert reconstruction recovers the
405    // analytical minimum phase with mid80 max < 2.5° and low-mid
406    // (< 600 Hz) max < 1°. This test asserts those tolerances on the
407    // decomposition output — both that `min_phase` tracks the
408    // analytical target and that `excess_phase` (the residual) is
409    // small across the band.
410    #[test]
411    fn minimum_phase_input_is_recovered_accurately() {
412        let n = 256;
413        let freq = log_freq_grid(n, 20.0, 20000.0);
414        let fc = 1000.0_f64;
415        let omega_c = 2.0 * PI * fc;
416
417        let spl: Vec<f64> = freq
418            .iter()
419            .map(|&f| {
420                let omega = 2.0 * PI * f;
421                let mag = omega_c / (omega_c * omega_c + omega * omega).sqrt();
422                20.0 * mag.log10()
423            })
424            .collect();
425
426        let phase: Vec<f64> = freq
427            .iter()
428            .map(|&f| {
429                let omega = 2.0 * PI * f;
430                -((omega / omega_c).atan()).to_degrees()
431            })
432            .collect();
433
434        let mut curve = Curve {
435            freq: freq.clone(),
436            spl: Array1::from_vec(spl),
437            phase: Some(Array1::from_vec(phase.clone())),
438            ..Default::default()
439        };
440
441        curve.decompose_into_cache();
442
443        let min_ph = curve.min_phase.as_ref().expect("min_phase must be Some");
444        let excess = curve
445            .excess_phase
446            .as_ref()
447            .expect("excess_phase must be Some");
448        let _delay = curve.excess_delay_ms.expect("excess_delay_ms must be Some");
449
450        assert_eq!(min_ph.len(), n, "min_phase length must match freq length");
451        assert_eq!(
452            excess.len(),
453            n,
454            "excess_phase length must match freq length"
455        );
456        assert!(min_ph.iter().all(|v| v.is_finite()), "finite min_phase");
457        assert!(excess.iter().all(|v| v.is_finite()), "finite excess_phase");
458
459        // Residual vs analytical min phase.
460        let residuals: Vec<f64> = phase
461            .iter()
462            .zip(min_ph.iter())
463            .map(|(&exp, &got)| (exp - got).abs())
464            .collect();
465        let edge = n / 10;
466        let mid_max = residuals
467            .iter()
468            .skip(edge)
469            .take(n - 2 * edge)
470            .cloned()
471            .fold(0.0_f64, f64::max);
472        assert!(
473            mid_max < 2.5,
474            "mid80 max residual vs analytical min-phase should be < 2.5°, got {:.2}°",
475            mid_max
476        );
477        let low_mid_max = freq
478            .iter()
479            .zip(residuals.iter())
480            .filter(|&(f, _)| *f < 600.0)
481            .map(|(_, r)| *r)
482            .fold(0.0_f64, f64::max);
483        assert!(
484            low_mid_max < 1.0,
485            "low-mid (< 600 Hz) residual should be < 1°, got {:.3}°",
486            low_mid_max
487        );
488
489        // For a pure minimum-phase input the excess phase must be
490        // vanishingly small — everything the measurement carries is
491        // minimum-phase, so there's no "excess" to extract.
492        let max_abs_excess = excess.iter().map(|v| v.abs()).fold(0.0_f64, f64::max);
493        assert!(
494            max_abs_excess < 5.0,
495            "excess phase should be tiny for min-phase input, got max |excess| = {:.2}°",
496            max_abs_excess
497        );
498    }
499
500    // Test 2 — all-pass input (flat magnitude, 1st-order all-pass phase)
501    //
502    // H(jω) = (jω − ω₀) / (jω + ω₀)
503    // |H| = 1 (flat magnitude) → magnitude_db = 0 dB everywhere
504    // Phase φ = π − 2·arctan(ω/ω₀) [degrees]
505    //
506    // For flat magnitude the Hilbert of constant log-magnitude is zero,
507    // so minimum phase is zero everywhere. Post GD-1d.1 this holds to
508    // < 0.5° across the whole grid.
509    #[test]
510    fn allpass_flat_magnitude_has_near_zero_min_phase() {
511        let n = 256;
512        let freq = log_freq_grid(n, 20.0, 20000.0);
513        let fc = 1000.0;
514        let omega_c = 2.0 * PI * fc;
515
516        // Flat magnitude: 0 dB → Hilbert of constant ≈ 0
517        let spl = Array1::from_elem(n, 0.0_f64);
518
519        // All-pass phase: π − 2·arctan(ω/ω₀) in degrees
520        let phase: Vec<f64> = freq
521            .iter()
522            .map(|&f| {
523                let omega = 2.0 * PI * f;
524                (PI - 2.0 * (omega / omega_c).atan()).to_degrees()
525            })
526            .collect();
527
528        let mut curve = Curve {
529            freq,
530            spl,
531            phase: Some(Array1::from_vec(phase.clone())),
532            ..Default::default()
533        };
534
535        curve.decompose_into_cache();
536
537        let min_ph = curve.min_phase.as_ref().unwrap();
538        assert!(
539            min_ph.iter().all(|v| v.is_finite()),
540            "all min_phase values must be finite"
541        );
542
543        // Full-range max — must be near zero for flat magnitude.
544        let max_abs_min = min_ph.iter().map(|v| v.abs()).fold(0.0_f64, f64::max);
545        assert!(
546            max_abs_min < 0.5,
547            "max |min_phase| for flat-magnitude input should be < 0.5°, got {:.4}°",
548            max_abs_min
549        );
550
551        // Unused: `phase` is the analytical all-pass phase; since
552        // min_phase ≈ 0, excess_phase ≈ the analytical all-pass
553        // phase. We cross-check this implicitly via the
554        // `excess_phase.is_some()` guard + the residual constraint on
555        // min_phase.
556        let _ = phase;
557    }
558
559    // Test 3 — pure delay: flat magnitude, linear phase −360·f·τ
560    //
561    // With flat magnitude, min_phase ≈ 0, so excess ≈ −360·f·τ.
562    // The linear-fit step should recover τ within ±0.1 ms.
563    #[test]
564    fn pure_delay_recovers_excess_delay_ms() {
565        let n = 256;
566        let freq = log_freq_grid(n, 20.0, 20000.0);
567        let tau_ms = 1.0;
568        let tau_s = tau_ms / 1000.0;
569
570        let spl = Array1::from_elem(n, 0.0_f64);
571        let phase: Vec<f64> = freq.iter().map(|&f| -360.0 * f * tau_s).collect();
572
573        let mut curve = Curve {
574            freq,
575            spl,
576            phase: Some(Array1::from_vec(phase)),
577            ..Default::default()
578        };
579
580        curve.decompose_into_cache();
581
582        let delay = curve.excess_delay_ms.unwrap();
583        assert!(
584            (delay - tau_ms).abs() < 0.1,
585            "pure-delay should recover τ ≈ {:.1} ms, got {:.3} ms",
586            tau_ms,
587            delay
588        );
589    }
590
591    // Test 4 — guard: no phase → all cache fields stay None
592    #[test]
593    fn guard_no_phase_is_noop() {
594        let mut curve = Curve {
595            freq: Array1::from_vec(vec![100.0, 1000.0, 10000.0]),
596            spl: Array1::from_vec(vec![0.0, 0.0, 0.0]),
597            phase: None,
598            ..Default::default()
599        };
600        curve.decompose_into_cache();
601        assert!(curve.min_phase.is_none(), "min_phase must stay None");
602        assert!(curve.excess_phase.is_none(), "excess_phase must stay None");
603        assert!(
604            curve.excess_delay_ms.is_none(),
605            "excess_delay_ms must stay None"
606        );
607    }
608
609    // Test 5 — guard: phase shorter than spl → must not panic; cache stays None
610    #[test]
611    fn guard_length_mismatch_does_not_panic() {
612        let mut curve = Curve {
613            freq: Array1::from_vec(vec![100.0, 1000.0, 10000.0]),
614            spl: Array1::from_vec(vec![0.0, 0.0, 0.0]),
615            phase: Some(Array1::from_vec(vec![-10.0, -20.0])), // length 2 ≠ 3
616            ..Default::default()
617        };
618        curve.decompose_into_cache(); // must not panic
619        assert!(
620            curve.min_phase.is_none(),
621            "min_phase must stay None on mismatch"
622        );
623        assert!(
624            curve.excess_phase.is_none(),
625            "excess_phase must stay None on mismatch"
626        );
627        assert!(
628            curve.excess_delay_ms.is_none(),
629            "excess_delay_ms must stay None on mismatch"
630        );
631    }
632
633    // Test 6 — idempotence: second call must match first call exactly
634    #[test]
635    fn idempotent_second_call_matches_first() {
636        let n = 64;
637        let freq = log_freq_grid(n, 100.0, 10000.0);
638        let fc = 1000.0;
639        let omega_c = 2.0 * PI * fc;
640        let spl: Vec<f64> = freq
641            .iter()
642            .map(|&f| {
643                let omega = 2.0 * PI * f;
644                let mag = omega_c / (omega_c * omega_c + omega * omega).sqrt();
645                20.0 * mag.log10()
646            })
647            .collect();
648        let phase: Vec<f64> = freq
649            .iter()
650            .map(|&f| {
651                let omega = 2.0 * PI * f;
652                -((omega / omega_c).atan()).to_degrees()
653            })
654            .collect();
655
656        let mut curve = Curve {
657            freq: freq.clone(),
658            spl: Array1::from_vec(spl),
659            phase: Some(Array1::from_vec(phase)),
660            ..Default::default()
661        };
662
663        curve.decompose_into_cache(); // first call
664        let min1 = curve.min_phase.clone().unwrap();
665        let exc1 = curve.excess_phase.clone().unwrap();
666        let del1 = curve.excess_delay_ms.unwrap();
667
668        curve.decompose_into_cache(); // second call — must be no-op
669        let min2 = curve.min_phase.as_ref().unwrap();
670        let exc2 = curve.excess_phase.as_ref().unwrap();
671        let del2 = curve.excess_delay_ms.unwrap();
672
673        assert_eq!(min1, *min2, "min_phase must be identical on second call");
674        assert_eq!(exc1, *exc2, "excess_phase must be identical on second call");
675        assert_eq!(
676            del1, del2,
677            "excess_delay_ms must be identical on second call"
678        );
679    }
680}