Skip to main content

math_audio_dsp/
analysis.rs

1//! FFT-based frequency analysis for recorded signals
2//!
3//! This module provides functions to analyze recorded audio signals and extract:
4//! - Frequency spectrum (magnitude in dBFS)
5//! - Phase spectrum (compensated for latency)
6//! - Latency estimation via cross-correlation
7//! - Microphone compensation for calibrated measurements
8//! - Standalone WAV buffer analysis (wav2csv functionality)
9
10use hound::WavReader;
11use math_audio_iir_fir::{Biquad, BiquadFilterType};
12use rustfft::FftPlanner;
13use rustfft::num_complex::Complex;
14use std::cell::RefCell;
15use std::f32::consts::PI;
16use std::io::Write;
17use std::path::Path;
18use std::sync::Arc;
19
20/// Spectrum result: (frequencies, magnitudes_db, phases_deg)
21type SpectrumResult = Result<(Vec<f32>, Vec<f32>, Vec<f32>), String>;
22
23thread_local! {
24    static FFT_PLANNER: RefCell<FftPlanner<f32>> = RefCell::new(FftPlanner::new());
25}
26
27/// Get a cached forward FFT plan for the given size (f32).
28///
29/// Uses a thread-local planner so repeated calls with the same size
30/// return the same plan without recomputing twiddle factors.
31pub fn plan_fft_forward(size: usize) -> Arc<dyn rustfft::Fft<f32>> {
32    FFT_PLANNER.with(|p| p.borrow_mut().plan_fft_forward(size))
33}
34
35/// Get a cached inverse FFT plan for the given size (f32).
36pub fn plan_fft_inverse(size: usize) -> Arc<dyn rustfft::Fft<f32>> {
37    FFT_PLANNER.with(|p| p.borrow_mut().plan_fft_inverse(size))
38}
39
40/// Microphone compensation data (frequency response correction)
41#[derive(Debug, Clone)]
42pub struct MicrophoneCompensation {
43    /// Frequency points in Hz
44    pub frequencies: Vec<f32>,
45    /// SPL deviation in dB (positive = mic is louder, negative = mic is quieter)
46    pub spl_db: Vec<f32>,
47}
48
49impl MicrophoneCompensation {
50    /// Apply pre-compensation to a sweep signal
51    ///
52    /// For log sweeps, this modulates the amplitude based on the instantaneous frequency
53    /// to pre-compensate for the microphone's response.
54    ///
55    /// # Arguments
56    /// * `signal` - The sweep signal to compensate
57    /// * `start_freq` - Start frequency of the sweep in Hz
58    /// * `end_freq` - End frequency of the sweep in Hz
59    /// * `sample_rate` - Sample rate in Hz
60    /// * `inverse` - If true, applies inverse compensation (boost where mic is weak)
61    ///
62    /// # Returns
63    /// Pre-compensated signal
64    pub fn apply_to_sweep(
65        &self,
66        signal: &[f32],
67        start_freq: f32,
68        end_freq: f32,
69        sample_rate: u32,
70        inverse: bool,
71    ) -> Vec<f32> {
72        let duration = signal.len() as f32 / sample_rate as f32;
73        let mut compensated = Vec::with_capacity(signal.len());
74
75        // Debug: print some sample points
76        let debug_points = [0, signal.len() / 4, signal.len() / 2, 3 * signal.len() / 4];
77
78        for (i, &sample) in signal.iter().enumerate() {
79            let t = i as f32 / sample_rate as f32;
80
81            // Compute instantaneous frequency for log sweep
82            // f(t) = f0 * exp(t * ln(f1/f0) / T)
83            let freq = start_freq * ((t * (end_freq / start_freq).ln()) / duration).exp();
84
85            // Get compensation at this frequency (in dB)
86            let comp_db = self.interpolate_at(freq);
87
88            // Apply inverse or direct compensation
89            let gain_db = if inverse { -comp_db } else { comp_db };
90
91            // Convert dB to linear gain
92            let gain = 10_f32.powf(gain_db / 20.0);
93
94            // Debug output for sample points
95            if debug_points.contains(&i) {
96                log::debug!(
97                    "[apply_to_sweep] t={:.3}s, freq={:.1}Hz, comp_db={:.2}dB, gain_db={:.2}dB, gain={:.3}x",
98                    t,
99                    freq,
100                    comp_db,
101                    gain_db,
102                    gain
103                );
104            }
105
106            compensated.push(sample * gain);
107        }
108
109        log::debug!(
110            "[apply_to_sweep] Processed {} samples, duration={:.2}s",
111            signal.len(),
112            duration
113        );
114        compensated
115    }
116
117    /// Load microphone compensation from a CSV or TXT file
118    ///
119    /// File format:
120    /// - CSV: frequency_hz,spl_db (with or without header, comma-separated)
121    /// - TXT: freq spl (space/tab-separated, no header assumed)
122    pub fn from_file(path: &Path) -> Result<Self, String> {
123        use std::fs::File;
124        use std::io::{BufRead, BufReader};
125
126        log::debug!("[MicrophoneCompensation] Loading from {:?}", path);
127
128        let file = File::open(path)
129            .map_err(|e| format!("Failed to open compensation file {:?}: {}", path, e))?;
130        let reader = BufReader::new(file);
131
132        // Determine if this is a .txt file (no header expected)
133        let is_txt_file = path
134            .extension()
135            .and_then(|e| e.to_str())
136            .map(|e| e.to_lowercase() == "txt")
137            .unwrap_or(false);
138
139        if is_txt_file {
140            log::info!(
141                "[MicrophoneCompensation] Detected .txt file - assuming space/tab-separated without header"
142            );
143        }
144
145        let mut frequencies = Vec::new();
146        let mut spl_db = Vec::new();
147
148        for (line_num, line) in reader.lines().enumerate() {
149            let line = line.map_err(|e| format!("Failed to read line {}: {}", line_num + 1, e))?;
150            let line = line.trim();
151
152            // Skip empty lines and comments
153            if line.is_empty() || line.starts_with('#') {
154                continue;
155            }
156
157            // For CSV files, skip header line
158            if !is_txt_file && line.starts_with("frequency") {
159                continue;
160            }
161
162            // For TXT files, skip lines that don't start with a number
163            if is_txt_file {
164                let first_char = line.chars().next().unwrap_or(' ');
165                if !first_char.is_ascii_digit() && first_char != '-' && first_char != '+' {
166                    log::info!(
167                        "[MicrophoneCompensation] Skipping non-numeric line {}: '{}'",
168                        line_num + 1,
169                        line
170                    );
171                    continue;
172                }
173            }
174
175            // Parse based on file type with auto-detection for TXT
176            let parts: Vec<&str> = if is_txt_file {
177                // TXT: Try to auto-detect separator
178                // First, try comma (in case it's mislabeled CSV)
179                let comma_parts: Vec<&str> = line.split(',').map(|s| s.trim()).collect();
180                if comma_parts.len() >= 2
181                    && comma_parts[0].parse::<f32>().is_ok()
182                    && comma_parts[1].parse::<f32>().is_ok()
183                {
184                    comma_parts
185                } else {
186                    // Try tab
187                    let tab_parts: Vec<&str> = line.split('\t').map(|s| s.trim()).collect();
188                    if tab_parts.len() >= 2
189                        && tab_parts[0].parse::<f32>().is_ok()
190                        && tab_parts[1].parse::<f32>().is_ok()
191                    {
192                        tab_parts
193                    } else {
194                        // Fall back to whitespace
195                        line.split_whitespace().collect()
196                    }
197                }
198            } else {
199                // CSV: comma separated
200                line.split(',').collect()
201            };
202
203            if parts.len() < 2 {
204                let separator = if is_txt_file {
205                    "separator (comma/tab/space)"
206                } else {
207                    "comma"
208                };
209                return Err(format!(
210                    "Invalid format at line {}: expected {} with 2+ values but got '{}'",
211                    line_num + 1,
212                    separator,
213                    line
214                ));
215            }
216
217            let freq: f32 = parts[0]
218                .trim()
219                .parse()
220                .map_err(|e| format!("Invalid frequency at line {}: {}", line_num + 1, e))?;
221            let spl: f32 = parts[1]
222                .trim()
223                .parse()
224                .map_err(|e| format!("Invalid SPL at line {}: {}", line_num + 1, e))?;
225
226            frequencies.push(freq);
227            spl_db.push(spl);
228        }
229
230        if frequencies.is_empty() {
231            return Err(format!("No compensation data found in {:?}", path));
232        }
233
234        // Validate that frequencies are sorted
235        for i in 1..frequencies.len() {
236            if frequencies[i] <= frequencies[i - 1] {
237                return Err(format!(
238                    "Frequencies must be strictly increasing: found {} after {} at line {}",
239                    frequencies[i],
240                    frequencies[i - 1],
241                    i + 1
242                ));
243            }
244        }
245
246        log::info!(
247            "[MicrophoneCompensation] Loaded {} calibration points: {:.1} Hz - {:.1} Hz",
248            frequencies.len(),
249            frequencies[0],
250            frequencies[frequencies.len() - 1]
251        );
252        log::info!(
253            "[MicrophoneCompensation] SPL range: {:.2} dB to {:.2} dB",
254            spl_db.iter().fold(f32::INFINITY, |a, &b| a.min(b)),
255            spl_db.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b))
256        );
257
258        Ok(Self {
259            frequencies,
260            spl_db,
261        })
262    }
263
264    /// Interpolate compensation value at a given frequency
265    ///
266    /// Uses linear interpolation in dB domain.
267    /// Returns 0.0 for frequencies outside the calibration range.
268    pub fn interpolate_at(&self, freq: f32) -> f32 {
269        if freq < self.frequencies[0] || freq > self.frequencies[self.frequencies.len() - 1] {
270            // Outside calibration range - no compensation
271            return 0.0;
272        }
273
274        // Find the two nearest points
275        let idx = match self
276            .frequencies
277            .binary_search_by(|f| f.partial_cmp(&freq).unwrap_or(std::cmp::Ordering::Equal))
278        {
279            Ok(i) => return self.spl_db[i], // Exact match
280            Err(i) => i,
281        };
282
283        if idx == 0 {
284            return self.spl_db[0];
285        }
286        if idx >= self.frequencies.len() {
287            return self.spl_db[self.frequencies.len() - 1];
288        }
289
290        // Linear interpolation
291        let f0 = self.frequencies[idx - 1];
292        let f1 = self.frequencies[idx];
293        let s0 = self.spl_db[idx - 1];
294        let s1 = self.spl_db[idx];
295
296        let t = (freq - f0) / (f1 - f0);
297        s0 + t * (s1 - s0)
298    }
299}
300
301// ============================================================================
302// WAV Buffer Analysis (wav2csv functionality)
303// ============================================================================
304
305/// Configuration for standalone WAV buffer analysis
306#[derive(Debug, Clone)]
307pub struct WavAnalysisConfig {
308    /// Number of output frequency points (default: 2000)
309    pub num_points: usize,
310    /// Minimum frequency in Hz (default: 20)
311    pub min_freq: f32,
312    /// Maximum frequency in Hz (default: 20000)
313    pub max_freq: f32,
314    /// FFT size (if None, auto-computed based on signal length and mode)
315    pub fft_size: Option<usize>,
316    /// Window overlap ratio for Welch's method (0.0-1.0, default: 0.5)
317    pub overlap: f32,
318    /// Use single FFT instead of Welch's method (better for sweeps and impulse responses)
319    pub single_fft: bool,
320    /// Apply pink compensation (-3dB/octave) for log sweeps
321    pub pink_compensation: bool,
322    /// Use rectangular window instead of Hann
323    pub no_window: bool,
324}
325
326impl Default for WavAnalysisConfig {
327    fn default() -> Self {
328        Self {
329            num_points: 2000,
330            min_freq: 20.0,
331            max_freq: 20000.0,
332            fft_size: None,
333            overlap: 0.5,
334            single_fft: false,
335            pink_compensation: false,
336            no_window: false,
337        }
338    }
339}
340
341impl WavAnalysisConfig {
342    /// Create config optimized for log sweep analysis
343    pub fn for_log_sweep() -> Self {
344        Self {
345            single_fft: true,
346            pink_compensation: true,
347            no_window: true,
348            ..Default::default()
349        }
350    }
351
352    /// Create config optimized for impulse response analysis
353    pub fn for_impulse_response() -> Self {
354        Self {
355            single_fft: true,
356            ..Default::default()
357        }
358    }
359
360    /// Create config for stationary signals (music, noise)
361    pub fn for_stationary() -> Self {
362        Self::default()
363    }
364}
365
366/// Result of standalone WAV buffer analysis
367#[derive(Debug, Clone)]
368pub struct WavAnalysisOutput {
369    /// Frequency points in Hz (log-spaced)
370    pub frequencies: Vec<f32>,
371    /// Magnitude in dB
372    pub magnitude_db: Vec<f32>,
373    /// Phase in degrees
374    pub phase_deg: Vec<f32>,
375}
376
377/// Analyze a buffer of audio samples and return frequency response
378///
379/// # Arguments
380/// * `samples` - Mono audio samples (f32, -1.0 to 1.0)
381/// * `sample_rate` - Sample rate in Hz
382/// * `config` - Analysis configuration
383///
384/// # Returns
385/// Analysis result with frequency, magnitude, and phase data
386pub fn analyze_wav_buffer(
387    samples: &[f32],
388    sample_rate: u32,
389    config: &WavAnalysisConfig,
390) -> Result<WavAnalysisOutput, String> {
391    if samples.is_empty() {
392        return Err("Signal is empty".to_string());
393    }
394
395    // Determine FFT size
396    let fft_size = if config.single_fft {
397        config
398            .fft_size
399            .unwrap_or_else(|| wav_next_power_of_two(samples.len()))
400    } else {
401        config.fft_size.unwrap_or(16384)
402    };
403
404    // Compute spectrum
405    let (freqs, magnitudes_db, phases_deg) = if config.single_fft {
406        compute_single_fft_spectrum_internal(samples, sample_rate, fft_size, config.no_window)?
407    } else {
408        compute_welch_spectrum_internal(samples, sample_rate, fft_size, config.overlap)?
409    };
410
411    // Generate logarithmically spaced frequency points
412    let log_freqs = generate_log_frequencies(config.num_points, config.min_freq, config.max_freq);
413
414    // Interpolate magnitude and phase at log frequencies
415    let mut interp_mag = interpolate_log(&freqs, &magnitudes_db, &log_freqs);
416    let interp_phase = interpolate_log_phase(&freqs, &phases_deg, &log_freqs);
417
418    // Apply pink compensation if requested (for log sweeps)
419    if config.pink_compensation {
420        let ref_freq = 1000.0;
421        for (i, freq) in log_freqs.iter().enumerate() {
422            if *freq > 0.0 {
423                let correction = 10.0 * (freq / ref_freq).log10();
424                interp_mag[i] += correction;
425            }
426        }
427    }
428
429    Ok(WavAnalysisOutput {
430        frequencies: log_freqs,
431        magnitude_db: interp_mag,
432        phase_deg: interp_phase,
433    })
434}
435
436/// Analyze a WAV file and return frequency response
437///
438/// # Arguments
439/// * `path` - Path to WAV file
440/// * `config` - Analysis configuration
441///
442/// # Returns
443/// Analysis result with frequency, magnitude, and phase data
444pub fn analyze_wav_file(
445    path: &Path,
446    config: &WavAnalysisConfig,
447) -> Result<WavAnalysisOutput, String> {
448    let (samples, sample_rate) = load_wav_mono_with_rate(path)?;
449    analyze_wav_buffer(&samples, sample_rate, config)
450}
451
452/// Load WAV file as mono and return samples with sample rate
453fn load_wav_mono_with_rate(path: &Path) -> Result<(Vec<f32>, u32), String> {
454    let mut reader =
455        WavReader::open(path).map_err(|e| format!("Failed to open WAV file: {}", e))?;
456
457    let spec = reader.spec();
458    let sample_rate = spec.sample_rate;
459    let channels = spec.channels as usize;
460
461    let samples: Result<Vec<f32>, _> = match spec.sample_format {
462        hound::SampleFormat::Float => reader.samples::<f32>().collect(),
463        hound::SampleFormat::Int => {
464            let max_val = (1_i64 << (spec.bits_per_sample - 1)) as f32;
465            reader
466                .samples::<i32>()
467                .map(|s| s.map(|v| v as f32 / max_val))
468                .collect()
469        }
470    };
471
472    let samples = samples.map_err(|e| format!("Failed to read samples: {}", e))?;
473
474    // Convert to mono by averaging channels
475    let mono = if channels == 1 {
476        samples
477    } else {
478        samples
479            .chunks(channels)
480            .map(|chunk| chunk.iter().sum::<f32>() / channels as f32)
481            .collect()
482    };
483
484    Ok((mono, sample_rate))
485}
486
487/// Write WAV analysis result to CSV file
488///
489/// # Arguments
490/// * `result` - Analysis output
491/// * `path` - Path to output CSV file
492pub fn write_wav_analysis_csv(result: &WavAnalysisOutput, path: &Path) -> Result<(), String> {
493    let mut file =
494        std::fs::File::create(path).map_err(|e| format!("Failed to create CSV: {}", e))?;
495
496    writeln!(file, "frequency_hz,spl_db,phase_deg")
497        .map_err(|e| format!("Failed to write CSV header: {}", e))?;
498
499    for i in 0..result.frequencies.len() {
500        writeln!(
501            file,
502            "{:.2},{:.2},{:.2}",
503            result.frequencies[i], result.magnitude_db[i], result.phase_deg[i]
504        )
505        .map_err(|e| format!("Failed to write CSV row: {}", e))?;
506    }
507
508    Ok(())
509}
510
511/// Compute spectrum using Welch's method (averaged periodograms) - internal version
512fn compute_welch_spectrum_internal(
513    signal: &[f32],
514    sample_rate: u32,
515    fft_size: usize,
516    overlap: f32,
517) -> SpectrumResult {
518    if signal.is_empty() {
519        return Err("Signal is empty".to_string());
520    }
521
522    let overlap_samples = (fft_size as f32 * overlap.clamp(0.0, 0.95)) as usize;
523    let hop_size = fft_size - overlap_samples;
524
525    let num_windows = if signal.len() >= fft_size {
526        1 + (signal.len() - fft_size) / hop_size
527    } else {
528        1
529    };
530
531    let num_bins = fft_size / 2;
532    let mut magnitude_sum = vec![0.0_f32; num_bins];
533    let mut phase_real_sum = vec![0.0_f32; num_bins];
534    let mut phase_imag_sum = vec![0.0_f32; num_bins];
535
536    // Precompute symmetric Hann window (N-1 divisor for spectral analysis)
537    let hann_window = crate::stft::generate_hann_window_symmetric(fft_size);
538
539    let window_power: f32 = hann_window.iter().map(|&w| w * w).sum();
540    let scale_factor = 2.0 / window_power;
541
542    let fft = plan_fft_forward(fft_size);
543
544    let mut windowed = vec![0.0_f32; fft_size];
545    let mut buffer = vec![Complex::new(0.0, 0.0); fft_size];
546
547    for window_idx in 0..num_windows {
548        let start = window_idx * hop_size;
549        let end = (start + fft_size).min(signal.len());
550        let window_len = end - start;
551
552        // Apply window
553        for i in 0..window_len {
554            windowed[i] = signal[start + i] * hann_window[i];
555        }
556        // Zero-pad the rest if necessary
557        windowed[window_len..fft_size].fill(0.0);
558
559        // Convert to complex
560        for (i, &val) in windowed.iter().enumerate() {
561            buffer[i] = Complex::new(val, 0.0);
562        }
563
564        fft.process(&mut buffer);
565
566        for i in 0..num_bins {
567            let mag = buffer[i].norm() * scale_factor.sqrt();
568            magnitude_sum[i] += mag * mag;
569            phase_real_sum[i] += buffer[i].re;
570            phase_imag_sum[i] += buffer[i].im;
571        }
572    }
573
574    let magnitudes_db: Vec<f32> = magnitude_sum
575        .iter()
576        .map(|&mag_sq| {
577            let mag = (mag_sq / num_windows as f32).sqrt();
578            if mag > 1e-10 {
579                20.0 * mag.log10()
580            } else {
581                -200.0
582            }
583        })
584        .collect();
585
586    let phases_deg: Vec<f32> = phase_real_sum
587        .iter()
588        .zip(phase_imag_sum.iter())
589        .map(|(&re, &im)| (im / num_windows as f32).atan2(re / num_windows as f32) * 180.0 / PI)
590        .collect();
591
592    let freqs: Vec<f32> = (0..num_bins)
593        .map(|i| i as f32 * sample_rate as f32 / fft_size as f32)
594        .collect();
595
596    Ok((freqs, magnitudes_db, phases_deg))
597}
598
599/// Compute spectrum using a single FFT - internal version
600fn compute_single_fft_spectrum_internal(
601    signal: &[f32],
602    sample_rate: u32,
603    fft_size: usize,
604    no_window: bool,
605) -> SpectrumResult {
606    if signal.is_empty() {
607        return Err("Signal is empty".to_string());
608    }
609
610    let mut windowed = vec![0.0_f32; fft_size];
611    let copy_len = signal.len().min(fft_size);
612    windowed[..copy_len].copy_from_slice(&signal[..copy_len]);
613
614    let window_scale_factor = if no_window {
615        1.0
616    } else {
617        let hann_window = crate::stft::generate_hann_window_symmetric(fft_size);
618
619        for (i, sample) in windowed.iter_mut().enumerate() {
620            *sample *= hann_window[i];
621        }
622
623        hann_window.iter().map(|&w| w * w).sum::<f32>()
624    };
625
626    let mut buffer: Vec<Complex<f32>> = windowed.iter().map(|&x| Complex::new(x, 0.0)).collect();
627
628    let fft = plan_fft_forward(fft_size);
629    fft.process(&mut buffer);
630
631    let scale_factor = if no_window {
632        (2.0 / fft_size as f32).sqrt()
633    } else {
634        (2.0 / window_scale_factor).sqrt()
635    };
636
637    let num_bins = fft_size / 2;
638    let magnitudes_db: Vec<f32> = buffer[..num_bins]
639        .iter()
640        .map(|c| {
641            let mag = c.norm() * scale_factor;
642            if mag > 1e-10 {
643                20.0 * mag.log10()
644            } else {
645                -200.0
646            }
647        })
648        .collect();
649
650    let phases_deg: Vec<f32> = buffer[..num_bins]
651        .iter()
652        .map(|c| c.arg() * 180.0 / PI)
653        .collect();
654
655    let freqs: Vec<f32> = (0..num_bins)
656        .map(|i| i as f32 * sample_rate as f32 / fft_size as f32)
657        .collect();
658
659    Ok((freqs, magnitudes_db, phases_deg))
660}
661
662/// Next power of two for wav analysis (capped at 1M)
663fn wav_next_power_of_two(n: usize) -> usize {
664    let mut p = 1;
665    while p < n {
666        p *= 2;
667    }
668    p.min(1048576)
669}
670
671/// Generate logarithmically spaced frequencies
672fn generate_log_frequencies(num_points: usize, min_freq: f32, max_freq: f32) -> Vec<f32> {
673    let log_min = min_freq.ln();
674    let log_max = max_freq.ln();
675    let step = (log_max - log_min) / (num_points - 1) as f32;
676
677    (0..num_points)
678        .map(|i| (log_min + i as f32 * step).exp())
679        .collect()
680}
681
682/// Logarithmic interpolation
683fn interpolate_log(x: &[f32], y: &[f32], x_new: &[f32]) -> Vec<f32> {
684    x_new
685        .iter()
686        .map(|&freq| {
687            let idx = x.partition_point(|&f| f < freq).min(x.len() - 1);
688
689            if idx == 0 {
690                return y[0];
691            }
692
693            let x0 = x[idx - 1];
694            let x1 = x[idx];
695            let y0 = y[idx - 1];
696            let y1 = y[idx];
697
698            if x1 <= x0 {
699                return y0;
700            }
701
702            let t = (freq - x0) / (x1 - x0);
703            y0 + t * (y1 - y0)
704        })
705        .collect()
706}
707
708/// Logarithmic interpolation for phase data (degrees).
709/// Uses circular interpolation to correctly handle ±180° wrap boundaries.
710fn interpolate_log_phase(x: &[f32], phase_deg: &[f32], x_new: &[f32]) -> Vec<f32> {
711    x_new
712        .iter()
713        .map(|&freq| {
714            let idx = x.partition_point(|&f| f < freq).min(x.len() - 1);
715
716            if idx == 0 {
717                return phase_deg[0];
718            }
719
720            let x0 = x[idx - 1];
721            let x1 = x[idx];
722
723            if x1 <= x0 {
724                return phase_deg[idx - 1];
725            }
726
727            let t = (freq - x0) / (x1 - x0);
728
729            // Circular interpolation: find shortest arc between the two angles
730            let p0 = phase_deg[idx - 1];
731            let p1 = phase_deg[idx];
732            let mut diff = p1 - p0;
733            // Wrap diff to [-180, 180]
734            diff -= 360.0 * (diff / 360.0).round();
735            p0 + t * diff
736        })
737        .collect()
738}
739
740// ============================================================================
741// Recording Analysis (reference vs recorded comparison)
742// ============================================================================
743
744/// Result of FFT analysis
745#[derive(Debug, Clone)]
746pub struct AnalysisResult {
747    /// Frequency bins in Hz
748    pub frequencies: Vec<f32>,
749    /// Magnitude in dBFS
750    pub spl_db: Vec<f32>,
751    /// Phase in degrees (compensated for latency)
752    pub phase_deg: Vec<f32>,
753    /// Estimated latency in samples
754    pub estimated_lag_samples: isize,
755    /// Impulse response (time domain)
756    pub impulse_response: Vec<f32>,
757    /// Time vector for impulse response in ms
758    pub impulse_time_ms: Vec<f32>,
759    /// Excess group delay in ms
760    pub excess_group_delay_ms: Vec<f32>,
761    /// Total Harmonic Distortion + Noise (%)
762    pub thd_percent: Vec<f32>,
763    /// Harmonic distortion curves (2nd, 3rd, etc) in dB
764    pub harmonic_distortion_db: Vec<Vec<f32>>,
765    /// RT60 decay time in ms
766    pub rt60_ms: Vec<f32>,
767    /// Clarity C50 in dB
768    pub clarity_c50_db: Vec<f32>,
769    /// Clarity C80 in dB
770    pub clarity_c80_db: Vec<f32>,
771    /// Spectrogram (Time x Freq magnitude in dB)
772    pub spectrogram_db: Vec<Vec<f32>>,
773}
774
775/// Analyze a recorded WAV file against a reference signal
776///
777/// # Arguments
778/// * `recorded_path` - Path to the recorded WAV file
779/// * `reference_signal` - Reference signal (should match the signal used for playback)
780/// * `sample_rate` - Sample rate in Hz
781/// * `sweep_range` - Optional (start_freq, end_freq) if the signal is a log sweep
782///
783/// # Returns
784/// Analysis result with frequency, SPL, and phase data
785pub fn analyze_recording(
786    recorded_path: &Path,
787    reference_signal: &[f32],
788    sample_rate: u32,
789    sweep_range: Option<(f32, f32)>,
790) -> Result<AnalysisResult, String> {
791    // Load recorded WAV
792    log::debug!("[FFT Analysis] Loading recorded file: {:?}", recorded_path);
793    let recorded = load_wav_mono(recorded_path)?;
794    log::debug!(
795        "[FFT Analysis] Loaded {} samples from recording",
796        recorded.len()
797    );
798    log::debug!(
799        "[FFT Analysis] Reference has {} samples",
800        reference_signal.len()
801    );
802
803    if recorded.is_empty() {
804        return Err("Recorded signal is empty!".to_string());
805    }
806    if reference_signal.is_empty() {
807        return Err("Reference signal is empty!".to_string());
808    }
809
810    // Don't truncate yet - we need full signals for lag estimation
811    let recorded = &recorded[..];
812    let reference = reference_signal;
813
814    // Debug: Check signal statistics (guarded to skip O(n) computation when disabled)
815    if log::log_enabled!(log::Level::Debug) {
816        let ref_max = reference
817            .iter()
818            .map(|&x| x.abs())
819            .fold(0.0_f32, |a, b| a.max(b));
820        let rec_max = recorded
821            .iter()
822            .map(|&x| x.abs())
823            .fold(0.0_f32, |a, b| a.max(b));
824        let ref_rms =
825            (reference.iter().map(|&x| x * x).sum::<f32>() / reference.len() as f32).sqrt();
826        let rec_rms = (recorded.iter().map(|&x| x * x).sum::<f32>() / recorded.len() as f32).sqrt();
827
828        log::debug!(
829            "[FFT Analysis] Reference: max={:.4}, RMS={:.4}",
830            ref_max,
831            ref_rms
832        );
833        log::debug!(
834            "[FFT Analysis] Recorded:  max={:.4}, RMS={:.4}",
835            rec_max,
836            rec_rms
837        );
838        log::debug!(
839            "[FFT Analysis] First 5 reference samples: {:?}",
840            &reference[..5.min(reference.len())]
841        );
842        log::debug!(
843            "[FFT Analysis] First 5 recorded samples:  {:?}",
844            &recorded[..5.min(recorded.len())]
845        );
846
847        let check_len = reference.len().min(recorded.len());
848        let mut identical_count = 0;
849        for (r, c) in reference[..check_len]
850            .iter()
851            .zip(recorded[..check_len].iter())
852        {
853            if (r - c).abs() < 1e-6 {
854                identical_count += 1;
855            }
856        }
857        log::debug!(
858            "[FFT Analysis] Identical samples: {}/{} ({:.1}%)",
859            identical_count,
860            check_len,
861            identical_count as f32 * 100.0 / check_len as f32
862        );
863    }
864
865    // Estimate lag using cross-correlation
866    let lag = estimate_lag(reference, recorded)?;
867
868    log::debug!(
869        "[FFT Analysis] Estimated lag: {} samples ({:.2} ms)",
870        lag,
871        lag as f32 * 1000.0 / sample_rate as f32
872    );
873
874    // Time-align the signals before FFT
875    // If recorded is delayed (positive lag), skip the lag samples in recorded
876    let (aligned_ref, aligned_rec) = if lag >= 0 {
877        let lag_usize = lag as usize;
878        if lag_usize >= recorded.len() {
879            return Err("Lag is larger than recorded signal length".to_string());
880        }
881        // Capture full tail
882        (reference, &recorded[lag_usize..])
883    } else {
884        // Recorded leads reference - rare
885        let lag_usize = (-lag) as usize;
886        if lag_usize >= reference.len() {
887            return Err("Negative lag is larger than reference signal length".to_string());
888        }
889        // Pad reference start? No, just slice reference
890        (&reference[lag_usize..], recorded)
891    };
892
893    log::debug!(
894        "[FFT Analysis] Aligned lengths: ref={}, rec={} (tail included)",
895        aligned_ref.len(),
896        aligned_rec.len()
897    );
898
899    // Compute FFT size to include the longer of the two (usually rec with tail)
900    let fft_size = next_power_of_two(aligned_ref.len().max(aligned_rec.len()));
901
902    let ref_spectrum = compute_fft(aligned_ref, fft_size, WindowType::Tukey(0.1))?;
903    let rec_spectrum = compute_fft(aligned_rec, fft_size, WindowType::Tukey(0.1))?;
904
905    // Generate 2000 log-spaced frequency points between 20 Hz and 20 kHz
906    let num_output_points = 2000;
907    let log_start = 20.0_f32.ln();
908    let log_end = 20000.0_f32.ln();
909
910    let mut frequencies = Vec::with_capacity(num_output_points);
911    let mut spl_db = Vec::with_capacity(num_output_points);
912    let mut phase_deg = Vec::with_capacity(num_output_points);
913
914    let freq_resolution = sample_rate as f32 / fft_size as f32;
915    let num_bins = fft_size / 2; // Single-sided spectrum
916
917    // Compute regularization threshold relative to the peak reference energy.
918    // Bins where the reference has very little energy (e.g., disconnected speaker
919    // with a misaligned sweep) produce unreliable transfer functions — division by
920    // near-zero gives spurious high-dB peaks. We skip bins where the reference
921    // energy is more than 60 dB below the peak.
922    let ref_peak_mag_sq = ref_spectrum[1..num_bins.min(ref_spectrum.len())]
923        .iter()
924        .map(|c| c.norm_sqr())
925        .fold(0.0_f32, |a, b| a.max(b));
926    // 60 dB below peak = 10^(-6) in power
927    let ref_regularization_threshold = ref_peak_mag_sq * 1e-6;
928
929    // Apply 1/24 octave smoothing for each target frequency
930    let mut skipped_count = 0;
931    for i in 0..num_output_points {
932        // Log-spaced target frequency
933        let target_freq =
934            (log_start + (log_end - log_start) * i as f32 / (num_output_points - 1) as f32).exp();
935
936        // 1/24 octave bandwidth: +/- 1/48 octave around target frequency
937        // Lower and upper frequency bounds: f * 2^(+/- 1/48)
938        let octave_fraction = 1.0 / 48.0;
939        let freq_lower = target_freq * 2.0_f32.powf(-octave_fraction);
940        let freq_upper = target_freq * 2.0_f32.powf(octave_fraction);
941
942        // Find FFT bins within this frequency range
943        let bin_lower = ((freq_lower / freq_resolution).floor() as usize).max(1);
944        let bin_upper = ((freq_upper / freq_resolution).ceil() as usize).min(num_bins);
945
946        if bin_lower > bin_upper || bin_upper >= ref_spectrum.len() {
947            if skipped_count < 5 {
948                log::debug!(
949                    "[FFT Analysis] Skipping freq {:.1} Hz: bin_lower={}, bin_upper={}, ref_spectrum.len()={}",
950                    target_freq,
951                    bin_lower,
952                    bin_upper,
953                    ref_spectrum.len()
954                );
955            }
956            skipped_count += 1;
957            // Output noise-floor placeholder so all channels produce the same
958            // number of frequency points (prevents ndarray shape mismatches).
959            frequencies.push(target_freq);
960            spl_db.push(-200.0);
961            phase_deg.push(0.0);
962            continue;
963        }
964
965        // Average transfer function magnitude and phase across bins in the smoothing range
966        let mut sum_magnitude = 0.0;
967        let mut sum_sin = 0.0; // For circular averaging of phase
968        let mut sum_cos = 0.0;
969        let mut bin_count = 0;
970
971        for k in bin_lower..=bin_upper {
972            if k >= ref_spectrum.len() {
973                break;
974            }
975
976            // Compute transfer function: H(f) = recorded / reference
977            // This gives the system response (for loopback, should be ~1.0 or 0 dB)
978            // Skip bins where the reference energy is too low (>60 dB below peak):
979            // dividing by near-zero produces unreliable, spuriously high values
980            // (e.g., disconnected speaker where the recording is just noise).
981            let ref_mag_sq = ref_spectrum[k].norm_sqr();
982            if ref_mag_sq <= ref_regularization_threshold {
983                continue;
984            }
985            let transfer_function = rec_spectrum[k] / ref_spectrum[k];
986            let magnitude = transfer_function.norm();
987
988            // Phase from cross-spectrum (signals are already time-aligned)
989            let cross_spectrum = ref_spectrum[k].conj() * rec_spectrum[k];
990            let phase_rad = cross_spectrum.arg();
991
992            // Accumulate for averaging
993            sum_magnitude += magnitude;
994            sum_sin += phase_rad.sin();
995            sum_cos += phase_rad.cos();
996            bin_count += 1;
997        }
998
999        // When no valid bins contribute (reference energy too low at this frequency,
1000        // e.g., LFE sweep above 500 Hz), output a noise-floor value instead of skipping.
1001        // Skipping would produce fewer output points than other channels, causing
1002        // ndarray shape mismatches when curves are combined downstream.
1003        let (avg_magnitude, db) = if bin_count == 0 {
1004            (0.0, -200.0)
1005        } else {
1006            let avg = sum_magnitude / bin_count as f32;
1007            (avg, 20.0 * avg.max(1e-10).log10())
1008        };
1009
1010        if frequencies.len() < 5 {
1011            log::debug!(
1012                "[FFT Analysis] freq={:.1} Hz: avg_magnitude={:.6}, dB={:.2}",
1013                target_freq,
1014                avg_magnitude,
1015                db
1016            );
1017        }
1018
1019        // Average phase using circular mean
1020        let avg_phase_rad = sum_sin.atan2(sum_cos);
1021        let phase = avg_phase_rad * 180.0 / PI;
1022
1023        frequencies.push(target_freq);
1024        spl_db.push(db);
1025        phase_deg.push(phase);
1026    }
1027
1028    log::debug!(
1029        "[FFT Analysis] Generated {} frequency points for CSV output",
1030        frequencies.len()
1031    );
1032    log::debug!(
1033        "[FFT Analysis] Skipped {} frequency points (out of {})",
1034        skipped_count,
1035        num_output_points
1036    );
1037
1038    if log::log_enabled!(log::Level::Debug) && !spl_db.is_empty() {
1039        let min_spl = spl_db.iter().fold(f32::INFINITY, |a, &b| a.min(b));
1040        let max_spl = spl_db.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
1041        log::debug!(
1042            "[FFT Analysis] SPL range: {:.2} dB to {:.2} dB",
1043            min_spl,
1044            max_spl
1045        );
1046    }
1047
1048    // --- Compute Impulse Response ---
1049    // H(f) = Recorded(f) / Reference(f)
1050    let mut transfer_function = vec![Complex::new(0.0, 0.0); fft_size];
1051    for k in 0..fft_size {
1052        // Handle DC and Nyquist specially if needed, but for complex FFT it's just bins
1053        // Avoid division by zero
1054        let ref_mag_sq = ref_spectrum[k].norm_sqr();
1055        if ref_mag_sq > 1e-20 {
1056            transfer_function[k] = rec_spectrum[k] / ref_spectrum[k];
1057        }
1058    }
1059
1060    // IFFT to get Impulse Response
1061    let ifft = plan_fft_inverse(fft_size);
1062    ifft.process(&mut transfer_function);
1063
1064    // Normalize and take real part (input was real, so output should be real-ish)
1065    // Scale by 1.0/N is done by IFFT? rustfft typically does NOT scale.
1066    // Standard IFFT definition: sum(X[k] * exp(...)) / N?
1067    // RustFFT inverse is unnormalized sum. So we divide by N.
1068    let norm = 1.0 / fft_size as f32;
1069    let mut impulse_response: Vec<f32> = transfer_function.iter().map(|c| c.re * norm).collect();
1070
1071    // Find the peak and shift the IR so the peak is near the beginning
1072    // This is necessary because the IFFT result has the peak at an arbitrary position
1073    // due to the phase of the transfer function (system latency)
1074    let peak_idx = impulse_response
1075        .iter()
1076        .enumerate()
1077        .max_by(|(_, a), (_, b)| a.abs().partial_cmp(&b.abs()).unwrap())
1078        .map(|(i, _)| i)
1079        .unwrap_or(0);
1080
1081    // Shift the IR so peak is at a small offset (e.g., 5ms for pre-ringing visibility)
1082    let pre_ring_samples = (0.005 * sample_rate as f32) as usize; // 5ms pre-ring buffer
1083    let shift_amount = peak_idx.saturating_sub(pre_ring_samples);
1084
1085    if shift_amount > 0 {
1086        impulse_response.rotate_left(shift_amount);
1087        log::info!(
1088            "[FFT Analysis] IR peak was at index {}, shifted by {} samples to put peak near beginning",
1089            peak_idx,
1090            shift_amount
1091        );
1092    }
1093
1094    // Generate time vector for IR (0 to duration)
1095    let _ir_duration_sec = fft_size as f32 / sample_rate as f32;
1096    let impulse_time_ms: Vec<f32> = (0..fft_size)
1097        .map(|i| i as f32 / sample_rate as f32 * 1000.0)
1098        .collect();
1099
1100    // --- Compute THD if sweep range is provided ---
1101    let (thd_percent, harmonic_distortion_db) = if let Some((start, end)) = sweep_range {
1102        // Assume sweep duration is same as impulse length (circular convolution)
1103        // or derived from reference signal length
1104        let duration = reference_signal.len() as f32 / sample_rate as f32;
1105        compute_thd_from_ir(
1106            &impulse_response,
1107            sample_rate as f32,
1108            &frequencies,
1109            &spl_db,
1110            start,
1111            end,
1112            duration,
1113        )
1114    } else {
1115        (vec![0.0; frequencies.len()], Vec::new())
1116    };
1117
1118    // --- Compute Excess Group Delay ---
1119    // (Placeholder)
1120    let excess_group_delay_ms = vec![0.0; frequencies.len()];
1121
1122    // --- Compute Acoustic Metrics ---
1123    // Debug: Log impulse response stats
1124    let ir_max = impulse_response.iter().fold(0.0f32, |a, &b| a.max(b.abs()));
1125    let ir_len = impulse_response.len();
1126    log::info!(
1127        "[Analysis] Impulse response: len={}, max_abs={:.6}, sample_rate={}",
1128        ir_len,
1129        ir_max,
1130        sample_rate
1131    );
1132
1133    let rt60_ms = compute_rt60_spectrum(&impulse_response, sample_rate as f32, &frequencies);
1134    let (clarity_c50_db, clarity_c80_db) =
1135        compute_clarity_spectrum(&impulse_response, sample_rate as f32, &frequencies);
1136
1137    // Debug: Log computed metrics
1138    if !rt60_ms.is_empty() {
1139        let rt60_min = rt60_ms.iter().fold(f32::INFINITY, |a, &b| a.min(b));
1140        let rt60_max = rt60_ms.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
1141        log::info!(
1142            "[Analysis] RT60 range: {:.1} - {:.1} ms",
1143            rt60_min,
1144            rt60_max
1145        );
1146    }
1147    if !clarity_c50_db.is_empty() {
1148        let c50_min = clarity_c50_db.iter().fold(f32::INFINITY, |a, &b| a.min(b));
1149        let c50_max = clarity_c50_db
1150            .iter()
1151            .fold(f32::NEG_INFINITY, |a, &b| a.max(b));
1152        log::info!(
1153            "[Analysis] Clarity C50 range: {:.1} - {:.1} dB",
1154            c50_min,
1155            c50_max
1156        );
1157    }
1158
1159    // Compute Spectrogram
1160    let (spectrogram_db, _, _) =
1161        compute_spectrogram(&impulse_response, sample_rate as f32, 512, 128);
1162
1163    Ok(AnalysisResult {
1164        frequencies,
1165        spl_db,
1166        phase_deg,
1167        estimated_lag_samples: lag,
1168        impulse_response,
1169        impulse_time_ms,
1170        excess_group_delay_ms,
1171        thd_percent,
1172        harmonic_distortion_db,
1173        rt60_ms,
1174        clarity_c50_db,
1175        clarity_c80_db,
1176        spectrogram_db,
1177    })
1178}
1179
1180/// Compute Total Harmonic Distortion (THD) from Impulse Response
1181///
1182/// Uses Farina's method to extract harmonics from the impulse response of a log sweep.
1183fn compute_thd_from_ir(
1184    impulse: &[f32],
1185    sample_rate: f32,
1186    frequencies: &[f32],
1187    fundamental_db: &[f32],
1188    start_freq: f32,
1189    end_freq: f32,
1190    duration: f32,
1191) -> (Vec<f32>, Vec<Vec<f32>>) {
1192    if frequencies.is_empty() {
1193        return (Vec::new(), Vec::new());
1194    }
1195
1196    let n = impulse.len();
1197    if n == 0 {
1198        return (vec![0.0; frequencies.len()], Vec::new());
1199    }
1200
1201    let num_harmonics = 4; // Compute 2nd, 3rd, 4th, 5th
1202    // Initialize to -120 dB (very low but not absurdly so)
1203    let mut harmonics_db = vec![vec![-120.0; frequencies.len()]; num_harmonics];
1204
1205    // Find main peak index (t=0)
1206    let peak_idx = impulse
1207        .iter()
1208        .enumerate()
1209        .max_by(|(_, a), (_, b)| a.abs().partial_cmp(&b.abs()).unwrap())
1210        .map(|(i, _)| i)
1211        .unwrap_or(0);
1212
1213    let sweep_ratio = end_freq / start_freq;
1214    log::debug!(
1215        "[THD] Impulse len={}, peak_idx={}, duration={:.3}s, sweep {:.0}-{:.0} Hz (ratio {:.1})",
1216        n,
1217        peak_idx,
1218        duration,
1219        start_freq,
1220        end_freq,
1221        sweep_ratio
1222    );
1223
1224    // Compute harmonics
1225    for (k_idx, harmonic_db) in harmonics_db.iter_mut().enumerate().take(num_harmonics) {
1226        let harmonic_order = k_idx + 2; // 2nd harmonic is k=2
1227
1228        // Calculate delay for this harmonic
1229        // dt = T * ln(k) / ln(f2/f1)
1230        let dt = duration * (harmonic_order as f32).ln() / sweep_ratio.ln();
1231        let dn = (dt * sample_rate).round() as isize;
1232
1233        // Center of harmonic impulse (negative time wraps to end of array)
1234        let center = peak_idx as isize - dn;
1235        let center_wrapped = center.rem_euclid(n as isize) as usize;
1236
1237        // Window size logic: distance to next harmonic * 0.8 to avoid overlap
1238        let dt_next_rel = duration
1239            * ((harmonic_order as f32 + 1.0).ln() - (harmonic_order as f32).ln())
1240            / sweep_ratio.ln();
1241        let win_len = ((dt_next_rel * sample_rate * 0.8).max(256.0) as usize).min(n / 2);
1242
1243        // Extract windowed harmonic IR
1244        let mut harmonic_ir = vec![0.0f32; win_len];
1245        let mut max_harmonic_sample = 0.0f32;
1246        for (i, harmonic_ir_val) in harmonic_ir.iter_mut().enumerate() {
1247            let src_idx =
1248                (center - (win_len as isize / 2) + i as isize).rem_euclid(n as isize) as usize;
1249            // Apply Hann window
1250            let w = 0.5 * (1.0 - (2.0 * PI * i as f32 / (win_len as f32 - 1.0)).cos());
1251            *harmonic_ir_val = impulse[src_idx] * w;
1252            max_harmonic_sample = max_harmonic_sample.max(harmonic_ir_val.abs());
1253        }
1254
1255        if k_idx == 0 {
1256            log::debug!(
1257                "[THD] H{}: dt={:.3}s, dn={}, center_wrapped={}, win_len={}, max_sample={:.2e}",
1258                harmonic_order,
1259                dt,
1260                dn,
1261                center_wrapped,
1262                win_len,
1263                max_harmonic_sample
1264            );
1265        }
1266
1267        // Compute spectrum
1268        let fft_size = next_power_of_two(win_len);
1269        let nyquist_bin = fft_size / 2; // Only use positive frequency bins
1270        if let Ok(spectrum) = compute_fft_padded(&harmonic_ir, fft_size) {
1271            let freq_resolution = sample_rate / fft_size as f32;
1272
1273            for (i, &f) in frequencies.iter().enumerate() {
1274                let bin = (f / freq_resolution).round() as usize;
1275                // Only access positive frequency bins (0 to nyquist)
1276                if bin < nyquist_bin && bin < spectrum.len() {
1277                    // compute_fft_padded already applies 1/N normalization, matching
1278                    // the scale of fundamental_db (derived from transfer function ratios)
1279                    let mag = spectrum[bin].norm();
1280                    // Convert to dB (threshold at -120 dB to avoid log of tiny values)
1281                    if mag > 1e-6 {
1282                        harmonic_db[i] = 20.0 * mag.log10();
1283                    }
1284                }
1285            }
1286        }
1287    }
1288
1289    // Log a summary of detected harmonic levels
1290    if !frequencies.is_empty() {
1291        let mid_idx = frequencies.len() / 2;
1292        log::debug!(
1293            "[THD] Harmonic levels at {:.0} Hz: H2={:.1}dB, H3={:.1}dB, H4={:.1}dB, H5={:.1}dB, fundamental={:.1}dB",
1294            frequencies[mid_idx],
1295            harmonics_db[0][mid_idx],
1296            harmonics_db[1][mid_idx],
1297            harmonics_db[2][mid_idx],
1298            harmonics_db[3][mid_idx],
1299            fundamental_db[mid_idx]
1300        );
1301    }
1302
1303    // Compute THD %
1304    let mut thd_percent = Vec::with_capacity(frequencies.len());
1305    for i in 0..frequencies.len() {
1306        let fundamental = 10.0f32.powf(fundamental_db[i] / 20.0);
1307        let mut harmonic_sum_sq = 0.0;
1308
1309        for harmonic_db in harmonics_db.iter().take(num_harmonics) {
1310            let h_mag = 10.0f32.powf(harmonic_db[i] / 20.0);
1311            harmonic_sum_sq += h_mag * h_mag;
1312        }
1313
1314        // THD = sqrt(sum(harmonics^2)) / fundamental
1315        let thd = if fundamental > 1e-9 {
1316            (harmonic_sum_sq.sqrt() / fundamental) * 100.0
1317        } else {
1318            0.0
1319        };
1320        thd_percent.push(thd);
1321    }
1322
1323    // Log THD summary
1324    if !thd_percent.is_empty() {
1325        let max_thd = thd_percent.iter().fold(0.0f32, |a, &b| a.max(b));
1326        let min_thd = thd_percent.iter().fold(f32::INFINITY, |a, &b| a.min(b));
1327        log::debug!("[THD] THD range: {:.4}% to {:.4}%", min_thd, max_thd);
1328    }
1329
1330    (thd_percent, harmonics_db)
1331}
1332
1333/// Write analysis results to CSV file with optional microphone compensation
1334///
1335/// # Arguments
1336/// * `result` - Analysis result
1337/// * `output_path` - Path to output CSV file
1338/// * `compensation` - Optional microphone compensation to apply (inverse)
1339///
1340/// When compensation is provided, the inverse is applied: the microphone's
1341/// SPL deviation is subtracted from the measured SPL to get the true SPL.
1342///
1343/// CSV format includes all analysis metrics:
1344/// frequency_hz, spl_db, phase_deg, thd_percent, rt60_ms, c50_db, c80_db, group_delay_ms
1345pub fn write_analysis_csv(
1346    result: &AnalysisResult,
1347    output_path: &Path,
1348    compensation: Option<&MicrophoneCompensation>,
1349) -> Result<(), String> {
1350    use std::fs::File;
1351    use std::io::Write;
1352
1353    log::info!(
1354        "[write_analysis_csv] Writing {} frequency points to {:?}",
1355        result.frequencies.len(),
1356        output_path
1357    );
1358
1359    if let Some(comp) = compensation {
1360        log::info!(
1361            "[write_analysis_csv] Applying inverse microphone compensation ({} calibration points)",
1362            comp.frequencies.len()
1363        );
1364    }
1365
1366    if result.frequencies.is_empty() {
1367        return Err("Cannot write CSV: Analysis result has no frequency points!".to_string());
1368    }
1369
1370    let mut file =
1371        File::create(output_path).map_err(|e| format!("Failed to create CSV file: {}", e))?;
1372
1373    // Write header with all metrics
1374    writeln!(
1375        file,
1376        "frequency_hz,spl_db,phase_deg,thd_percent,rt60_ms,c50_db,c80_db,group_delay_ms"
1377    )
1378    .map_err(|e| format!("Failed to write header: {}", e))?;
1379
1380    // Write data with compensation applied
1381    for i in 0..result.frequencies.len() {
1382        let freq = result.frequencies[i];
1383        let mut spl = result.spl_db[i];
1384
1385        // Apply inverse compensation: subtract microphone deviation
1386        // If mic reads +2dB at this frequency, the true level is 2dB lower
1387        if let Some(comp) = compensation {
1388            let mic_deviation = comp.interpolate_at(freq);
1389            spl -= mic_deviation;
1390        }
1391
1392        let phase = result.phase_deg[i];
1393        let thd = result.thd_percent.get(i).copied().unwrap_or(0.0);
1394        let rt60 = result.rt60_ms.get(i).copied().unwrap_or(0.0);
1395        let c50 = result.clarity_c50_db.get(i).copied().unwrap_or(0.0);
1396        let c80 = result.clarity_c80_db.get(i).copied().unwrap_or(0.0);
1397        let gd = result.excess_group_delay_ms.get(i).copied().unwrap_or(0.0);
1398
1399        writeln!(
1400            file,
1401            "{:.6},{:.3},{:.6},{:.6},{:.3},{:.3},{:.3},{:.6}",
1402            freq, spl, phase, thd, rt60, c50, c80, gd
1403        )
1404        .map_err(|e| format!("Failed to write data: {}", e))?;
1405    }
1406
1407    log::info!(
1408        "[write_analysis_csv] Successfully wrote {} data rows to CSV",
1409        result.frequencies.len()
1410    );
1411
1412    Ok(())
1413}
1414
1415/// Read analysis results from CSV file
1416///
1417/// Parses CSV with columns: frequency_hz, spl_db, phase_deg, thd_percent, rt60_ms, c50_db, c80_db, group_delay_ms
1418/// Also supports legacy format with just: frequency_hz, spl_db, phase_deg
1419pub fn read_analysis_csv(csv_path: &Path) -> Result<AnalysisResult, String> {
1420    use std::fs::File;
1421    use std::io::{BufRead, BufReader};
1422
1423    let file = File::open(csv_path).map_err(|e| format!("Failed to open CSV: {}", e))?;
1424    let reader = BufReader::new(file);
1425    let mut lines = reader.lines();
1426
1427    // Read header
1428    let header = lines
1429        .next()
1430        .ok_or("Empty CSV file")?
1431        .map_err(|e| format!("Failed to read header: {}", e))?;
1432
1433    let columns: Vec<&str> = header.split(',').map(|s| s.trim()).collect();
1434    let has_extended_format = columns.len() >= 8;
1435
1436    let mut frequencies = Vec::new();
1437    let mut spl_db = Vec::new();
1438    let mut phase_deg = Vec::new();
1439    let mut thd_percent = Vec::new();
1440    let mut rt60_ms = Vec::new();
1441    let mut clarity_c50_db = Vec::new();
1442    let mut clarity_c80_db = Vec::new();
1443    let mut excess_group_delay_ms = Vec::new();
1444
1445    for line in lines {
1446        let line = line.map_err(|e| format!("Failed to read line: {}", e))?;
1447        let parts: Vec<&str> = line.split(',').map(|s| s.trim()).collect();
1448
1449        if parts.len() < 3 {
1450            continue;
1451        }
1452
1453        let freq: f32 = parts[0].parse().unwrap_or(0.0);
1454        let spl: f32 = parts[1].parse().unwrap_or(0.0);
1455        let phase: f32 = parts[2].parse().unwrap_or(0.0);
1456
1457        frequencies.push(freq);
1458        spl_db.push(spl);
1459        phase_deg.push(phase);
1460
1461        if has_extended_format && parts.len() >= 8 {
1462            thd_percent.push(parts[3].parse().unwrap_or(0.0));
1463            rt60_ms.push(parts[4].parse().unwrap_or(0.0));
1464            clarity_c50_db.push(parts[5].parse().unwrap_or(0.0));
1465            clarity_c80_db.push(parts[6].parse().unwrap_or(0.0));
1466            excess_group_delay_ms.push(parts[7].parse().unwrap_or(0.0));
1467        }
1468    }
1469
1470    // If legacy format, fill with zeros
1471    let n = frequencies.len();
1472    if thd_percent.is_empty() {
1473        thd_percent = vec![0.0; n];
1474        rt60_ms = vec![0.0; n];
1475        clarity_c50_db = vec![0.0; n];
1476        clarity_c80_db = vec![0.0; n];
1477        excess_group_delay_ms = vec![0.0; n];
1478    }
1479
1480    Ok(AnalysisResult {
1481        frequencies,
1482        spl_db,
1483        phase_deg,
1484        estimated_lag_samples: 0,
1485        impulse_response: Vec::new(),
1486        impulse_time_ms: Vec::new(),
1487        thd_percent,
1488        harmonic_distortion_db: Vec::new(),
1489        rt60_ms,
1490        clarity_c50_db,
1491        clarity_c80_db,
1492        excess_group_delay_ms,
1493        spectrogram_db: Vec::new(),
1494    })
1495}
1496
1497/// Window function type for FFT
1498#[derive(Debug, Clone, Copy)]
1499enum WindowType {
1500    Hann,
1501    Tukey(f32), // alpha parameter (0.0-1.0)
1502}
1503
1504/// Estimate lag between reference and recorded signals using cross-correlation
1505///
1506/// Uses FFT-based cross-correlation for efficiency
1507///
1508/// # Arguments
1509/// * `reference` - Reference signal
1510/// * `recorded` - Recorded signal
1511///
1512/// # Returns
1513/// Estimated lag in samples (negative means recorded leads)
1514fn estimate_lag(reference: &[f32], recorded: &[f32]) -> Result<isize, String> {
1515    let len = reference.len().min(recorded.len());
1516
1517    // Zero-pad to avoid circular correlation artifacts
1518    let fft_size = next_power_of_two(len * 2);
1519
1520    // Use Hann window for correlation to suppress edge effects
1521    let ref_fft = compute_fft(reference, fft_size, WindowType::Hann)?;
1522    let rec_fft = compute_fft(recorded, fft_size, WindowType::Hann)?;
1523
1524    // Cross-correlation in frequency domain: conj(X) * Y
1525    let mut cross_corr_fft: Vec<Complex<f32>> = ref_fft
1526        .iter()
1527        .zip(rec_fft.iter())
1528        .map(|(x, y)| x.conj() * y)
1529        .collect();
1530
1531    // IFFT to get cross-correlation in time domain
1532    let ifft = plan_fft_inverse(fft_size);
1533    ifft.process(&mut cross_corr_fft);
1534
1535    // Find peak
1536    let mut max_val = 0.0;
1537    let mut max_idx = 0;
1538
1539    for (i, &val) in cross_corr_fft.iter().enumerate() {
1540        let magnitude = val.norm();
1541        if magnitude > max_val {
1542            max_val = magnitude;
1543            max_idx = i;
1544        }
1545    }
1546
1547    // Convert index to lag (handle wrap-around)
1548    Ok(if max_idx <= fft_size / 2 {
1549        max_idx as isize
1550    } else {
1551        max_idx as isize - fft_size as isize
1552    })
1553}
1554
1555/// Compute FFT of a signal with specified windowing
1556///
1557/// # Arguments
1558/// * `signal` - Input signal
1559/// * `fft_size` - FFT size (should be power of 2)
1560/// * `window_type` - Type of window to apply
1561///
1562/// # Returns
1563/// Complex FFT spectrum
1564fn compute_fft(
1565    signal: &[f32],
1566    fft_size: usize,
1567    window_type: WindowType,
1568) -> Result<Vec<Complex<f32>>, String> {
1569    // Apply window
1570    let windowed = match window_type {
1571        WindowType::Hann => apply_hann_window(signal),
1572        WindowType::Tukey(alpha) => apply_tukey_window(signal, alpha),
1573    };
1574
1575    compute_fft_padded(&windowed, fft_size)
1576}
1577
1578/// Compute FFT with zero-padding
1579fn compute_fft_padded(signal: &[f32], fft_size: usize) -> Result<Vec<Complex<f32>>, String> {
1580    // Single allocation at final size; trailing elements are already zero-padded
1581    let mut buffer = vec![Complex::new(0.0, 0.0); fft_size];
1582    for (dst, &src) in buffer.iter_mut().zip(signal.iter()) {
1583        dst.re = src;
1584    }
1585
1586    // Compute FFT
1587    let fft = plan_fft_forward(fft_size);
1588    fft.process(&mut buffer);
1589
1590    // Normalize by FFT size (standard FFT normalization)
1591    let norm_factor = 1.0 / fft_size as f32;
1592    for val in buffer.iter_mut() {
1593        *val *= norm_factor;
1594    }
1595
1596    Ok(buffer)
1597}
1598
1599/// Apply Hann window to a signal
1600fn apply_hann_window(signal: &[f32]) -> Vec<f32> {
1601    let len = signal.len();
1602    if len < 2 {
1603        return signal.to_vec();
1604    }
1605    signal
1606        .iter()
1607        .enumerate()
1608        .map(|(i, &x)| {
1609            let window = 0.5 * (1.0 - (2.0 * PI * i as f32 / (len - 1) as f32).cos());
1610            x * window
1611        })
1612        .collect()
1613}
1614
1615/// Apply Tukey window to a signal
1616///
1617/// Tukey window is a "tapered cosine" window.
1618/// alpha=0.0 is rectangular, alpha=1.0 is Hann.
1619fn apply_tukey_window(signal: &[f32], alpha: f32) -> Vec<f32> {
1620    let len = signal.len();
1621    if len < 2 {
1622        return signal.to_vec();
1623    }
1624
1625    let alpha = alpha.clamp(0.0, 1.0);
1626    let limit = (alpha * (len as f32 - 1.0) / 2.0).round() as usize;
1627
1628    if limit == 0 {
1629        return signal.to_vec();
1630    }
1631
1632    signal
1633        .iter()
1634        .enumerate()
1635        .map(|(i, &x)| {
1636            let w = if i < limit {
1637                // Fade in (Half-Hann)
1638                0.5 * (1.0 - (PI * i as f32 / limit as f32).cos())
1639            } else if i >= len - limit {
1640                // Fade out (Half-Hann)
1641                let n = len - 1 - i;
1642                0.5 * (1.0 - (PI * n as f32 / limit as f32).cos())
1643            } else {
1644                // Flat top
1645                1.0
1646            };
1647            x * w
1648        })
1649        .collect()
1650}
1651
1652/// Find the next power of two greater than or equal to n
1653fn next_power_of_two(n: usize) -> usize {
1654    if n == 0 {
1655        return 1;
1656    }
1657    n.next_power_of_two()
1658}
1659
1660/// Load a mono WAV file and convert to f32 samples
1661/// Load a WAV file and extract a specific channel or convert to mono
1662///
1663/// # Arguments
1664/// * `path` - Path to WAV file
1665/// * `channel_index` - Optional channel index to extract (0-based). If None, will average all channels for mono
1666fn load_wav_mono_channel(path: &Path, channel_index: Option<usize>) -> Result<Vec<f32>, String> {
1667    let mut reader =
1668        WavReader::open(path).map_err(|e| format!("Failed to open WAV file: {}", e))?;
1669
1670    let spec = reader.spec();
1671    let channels = spec.channels as usize;
1672
1673    log::info!(
1674        "[load_wav_mono_channel] WAV file: {} channels, {} Hz, {:?} format",
1675        channels,
1676        spec.sample_rate,
1677        spec.sample_format
1678    );
1679
1680    // Read all samples and convert to f32
1681    let samples: Result<Vec<f32>, _> = match spec.sample_format {
1682        hound::SampleFormat::Float => reader.samples::<f32>().collect(),
1683        hound::SampleFormat::Int => reader
1684            .samples::<i32>()
1685            .map(|s| s.map(|v| v as f32 / i32::MAX as f32))
1686            .collect(),
1687    };
1688
1689    let samples = samples.map_err(|e| format!("Failed to read samples: {}", e))?;
1690    log::info!(
1691        "[load_wav_mono_channel] Read {} total samples",
1692        samples.len()
1693    );
1694
1695    // Handle mono file - return as-is
1696    if channels == 1 {
1697        log::info!(
1698            "[load_wav_mono_channel] File is already mono, returning {} samples",
1699            samples.len()
1700        );
1701        return Ok(samples);
1702    }
1703
1704    // Handle multi-channel file
1705    if let Some(ch_idx) = channel_index {
1706        // Extract specific channel
1707        if ch_idx >= channels {
1708            return Err(format!(
1709                "Channel index {} out of range (file has {} channels)",
1710                ch_idx, channels
1711            ));
1712        }
1713        log::info!(
1714            "[load_wav_mono_channel] Extracting channel {} from {} channels",
1715            ch_idx,
1716            channels
1717        );
1718        Ok(samples
1719            .chunks(channels)
1720            .map(|chunk| chunk[ch_idx])
1721            .collect())
1722    } else {
1723        // Average all channels to mono
1724        log::info!(
1725            "[load_wav_mono_channel] Averaging {} channels to mono",
1726            channels
1727        );
1728        Ok(samples
1729            .chunks(channels)
1730            .map(|chunk| chunk.iter().sum::<f32>() / channels as f32)
1731            .collect())
1732    }
1733}
1734
1735/// Load a WAV file as mono (averages channels if multi-channel)
1736fn load_wav_mono(path: &Path) -> Result<Vec<f32>, String> {
1737    load_wav_mono_channel(path, None)
1738}
1739
1740// ============================================================================
1741// DSP Utilities (Moved from frontend dsp.rs)
1742// ============================================================================
1743
1744/// Apply octave smoothing to frequency response data (f64 version)
1745///
1746/// Frequencies must be sorted in ascending order (as from FFT or log-spaced grids).
1747/// Uses a prefix sum with two-pointer sliding window for O(n) complexity.
1748pub fn smooth_response_f64(frequencies: &[f64], values: &[f64], octaves: f64) -> Vec<f64> {
1749    if octaves <= 0.0 || frequencies.is_empty() || values.is_empty() {
1750        return values.to_vec();
1751    }
1752
1753    let n = values.len();
1754
1755    // Prefix sum for O(1) range averages
1756    let mut prefix = Vec::with_capacity(n + 1);
1757    prefix.push(0.0);
1758    for &v in values {
1759        prefix.push(prefix.last().unwrap() + v);
1760    }
1761
1762    let ratio = 2.0_f64.powf(octaves / 2.0);
1763    let mut smoothed = Vec::with_capacity(n);
1764    let mut lo = 0usize;
1765    let mut hi = 0usize;
1766
1767    for (i, &center_freq) in frequencies.iter().enumerate() {
1768        if center_freq <= 0.0 {
1769            smoothed.push(values[i]);
1770            continue;
1771        }
1772
1773        let low_freq = center_freq / ratio;
1774        let high_freq = center_freq * ratio;
1775
1776        // Advance lo past frequencies below the window
1777        while lo < n && frequencies[lo] < low_freq {
1778            lo += 1;
1779        }
1780        // Advance hi to include frequencies within the window
1781        while hi < n && frequencies[hi] <= high_freq {
1782            hi += 1;
1783        }
1784
1785        let count = hi - lo;
1786        if count > 0 {
1787            smoothed.push((prefix[hi] - prefix[lo]) / count as f64);
1788        } else {
1789            smoothed.push(values[i]);
1790        }
1791    }
1792
1793    smoothed
1794}
1795
1796/// Apply octave smoothing to frequency response data (f32 version)
1797///
1798/// Frequencies must be sorted in ascending order (as from FFT or log-spaced grids).
1799/// Uses a prefix sum with two-pointer sliding window for O(n) complexity.
1800pub fn smooth_response_f32(frequencies: &[f32], values: &[f32], octaves: f32) -> Vec<f32> {
1801    if octaves <= 0.0 || frequencies.is_empty() || values.is_empty() {
1802        return values.to_vec();
1803    }
1804
1805    let n = values.len();
1806
1807    // Prefix sum for O(1) range averages (accumulate in f64 to avoid precision loss)
1808    let mut prefix = Vec::with_capacity(n + 1);
1809    prefix.push(0.0_f64);
1810    for &v in values {
1811        prefix.push(prefix.last().unwrap() + v as f64);
1812    }
1813
1814    let ratio = 2.0_f32.powf(octaves / 2.0);
1815    let mut smoothed = Vec::with_capacity(n);
1816    let mut lo = 0usize;
1817    let mut hi = 0usize;
1818
1819    for (i, &center_freq) in frequencies.iter().enumerate() {
1820        if center_freq <= 0.0 {
1821            smoothed.push(values[i]);
1822            continue;
1823        }
1824
1825        let low_freq = center_freq / ratio;
1826        let high_freq = center_freq * ratio;
1827
1828        // Advance lo past frequencies below the window
1829        while lo < n && frequencies[lo] < low_freq {
1830            lo += 1;
1831        }
1832        // Advance hi to include frequencies within the window
1833        while hi < n && frequencies[hi] <= high_freq {
1834            hi += 1;
1835        }
1836
1837        let count = hi - lo;
1838        if count > 0 {
1839            smoothed.push(((prefix[hi] - prefix[lo]) / count as f64) as f32);
1840        } else {
1841            smoothed.push(values[i]);
1842        }
1843    }
1844
1845    smoothed
1846}
1847
1848/// Compute group delay from phase data
1849/// Group delay = -d(phase)/d(frequency) / (2*pi)
1850///
1851/// Phase is unwrapped before differentiation to avoid spurious spikes
1852/// at ±180° wrap boundaries.
1853pub fn compute_group_delay(frequencies: &[f32], phase_deg: &[f32]) -> Vec<f32> {
1854    if frequencies.len() < 2 {
1855        return vec![0.0; frequencies.len()];
1856    }
1857
1858    // Unwrap phase to remove ±180° discontinuities before differentiation
1859    let unwrapped = unwrap_phase_deg(phase_deg);
1860
1861    let mut group_delay_ms = Vec::with_capacity(frequencies.len());
1862
1863    for i in 0..frequencies.len() {
1864        let delay = if i == 0 {
1865            // Forward difference at start
1866            let df = frequencies[1] - frequencies[0];
1867            let dp = unwrapped[1] - unwrapped[0];
1868            if df.abs() > 1e-6 {
1869                -dp / df / 360.0 * 1000.0 // Convert to ms
1870            } else {
1871                0.0
1872            }
1873        } else if i == frequencies.len() - 1 {
1874            // Backward difference at end
1875            let df = frequencies[i] - frequencies[i - 1];
1876            let dp = unwrapped[i] - unwrapped[i - 1];
1877            if df.abs() > 1e-6 {
1878                -dp / df / 360.0 * 1000.0
1879            } else {
1880                0.0
1881            }
1882        } else {
1883            // Central difference
1884            let df = frequencies[i + 1] - frequencies[i - 1];
1885            let dp = unwrapped[i + 1] - unwrapped[i - 1];
1886            if df.abs() > 1e-6 {
1887                -dp / df / 360.0 * 1000.0
1888            } else {
1889                0.0
1890            }
1891        };
1892        group_delay_ms.push(delay);
1893    }
1894
1895    group_delay_ms
1896}
1897
1898/// Unwrap phase in degrees to produce a continuous phase curve.
1899/// Wraps each inter-sample difference to [-180, 180] and accumulates,
1900/// handling arbitrarily large jumps (not just single ±360° wraps).
1901fn unwrap_phase_deg(phase_deg: &[f32]) -> Vec<f32> {
1902    if phase_deg.is_empty() {
1903        return Vec::new();
1904    }
1905
1906    let mut unwrapped = Vec::with_capacity(phase_deg.len());
1907    unwrapped.push(phase_deg[0]);
1908
1909    for i in 1..phase_deg.len() {
1910        let diff = phase_deg[i] - phase_deg[i - 1];
1911        let wrapped_diff = diff - 360.0 * (diff / 360.0).round();
1912        unwrapped.push(unwrapped[i - 1] + wrapped_diff);
1913    }
1914
1915    unwrapped
1916}
1917
1918/// Compute impulse response from frequency response via inverse FFT.
1919///
1920/// The input frequency/magnitude/phase data (possibly irregularly spaced) is
1921/// interpolated onto a uniform FFT frequency grid, assembled into a complex
1922/// spectrum with Hermitian symmetry, and transformed with an inverse FFT.
1923///
1924/// Returns (times_ms, impulse) where impulse is peak-normalized to [-1, 1].
1925pub fn compute_impulse_response_from_fr(
1926    frequencies: &[f32],
1927    magnitude_db: &[f32],
1928    phase_deg: &[f32],
1929    sample_rate: f32,
1930) -> (Vec<f32>, Vec<f32>) {
1931    let fft_size = 1024;
1932    let half = fft_size / 2; // Number of positive-frequency bins (excluding DC)
1933    let freq_bin = sample_rate / fft_size as f32;
1934
1935    // Unwrap phase before interpolation to avoid discontinuities
1936    let unwrapped_phase = unwrap_phase_deg(phase_deg);
1937
1938    // Build complex spectrum on uniform FFT grid via linear interpolation
1939    let mut spectrum = vec![Complex::new(0.0_f32, 0.0); fft_size];
1940
1941    for (k, spectrum_bin) in spectrum.iter_mut().enumerate().take(half + 1) {
1942        let f = k as f32 * freq_bin;
1943
1944        // Interpolate magnitude (dB) and phase (deg) at this bin frequency
1945        let (mag_db, phase_d) = interpolate_fr(frequencies, magnitude_db, &unwrapped_phase, f);
1946
1947        let mag_linear = 10.0_f32.powf(mag_db / 20.0);
1948        let phase_rad = phase_d * PI / 180.0;
1949
1950        *spectrum_bin = Complex::new(mag_linear * phase_rad.cos(), mag_linear * phase_rad.sin());
1951    }
1952
1953    // Enforce Hermitian symmetry: X[N-k] = conj(X[k])
1954    for k in 1..half {
1955        spectrum[fft_size - k] = spectrum[k].conj();
1956    }
1957
1958    // Inverse FFT (uses thread-local cached planner)
1959    let ifft = plan_fft_inverse(fft_size);
1960    ifft.process(&mut spectrum);
1961
1962    // Extract real part and scale by 1/N (rustfft doesn't normalize)
1963    let scale = 1.0 / fft_size as f32;
1964    let mut impulse: Vec<f32> = spectrum.iter().map(|c| c.re * scale).collect();
1965
1966    // Normalize to [-1, 1]
1967    let max_val = impulse.iter().map(|v| v.abs()).fold(0.0_f32, f32::max);
1968    if max_val > 0.0 {
1969        for v in &mut impulse {
1970            *v /= max_val;
1971        }
1972    }
1973
1974    let time_step = 1.0 / sample_rate;
1975    let times: Vec<f32> = (0..fft_size)
1976        .map(|i| i as f32 * time_step * 1000.0)
1977        .collect();
1978
1979    (times, impulse)
1980}
1981
1982/// Linearly interpolate magnitude and phase at a target frequency.
1983/// Clamps to the nearest endpoint if `target_freq` is outside the data range.
1984///
1985/// Phase must be pre-unwrapped (continuous) for correct interpolation.
1986fn interpolate_fr(
1987    frequencies: &[f32],
1988    magnitude_db: &[f32],
1989    unwrapped_phase_deg: &[f32],
1990    target_freq: f32,
1991) -> (f32, f32) {
1992    if frequencies.is_empty() {
1993        return (0.0, 0.0);
1994    }
1995    if target_freq <= frequencies[0] {
1996        return (magnitude_db[0], unwrapped_phase_deg[0]);
1997    }
1998    let last = frequencies.len() - 1;
1999    if target_freq >= frequencies[last] {
2000        return (magnitude_db[last], unwrapped_phase_deg[last]);
2001    }
2002
2003    // Binary search for the interval containing target_freq
2004    let idx = match frequencies.binary_search_by(|f| f.partial_cmp(&target_freq).unwrap()) {
2005        Ok(i) => return (magnitude_db[i], unwrapped_phase_deg[i]),
2006        Err(i) => i, // target_freq is between frequencies[i-1] and frequencies[i]
2007    };
2008
2009    let f0 = frequencies[idx - 1];
2010    let f1 = frequencies[idx];
2011    let t = (target_freq - f0) / (f1 - f0);
2012
2013    let mag = magnitude_db[idx - 1] + t * (magnitude_db[idx] - magnitude_db[idx - 1]);
2014    let phase = unwrapped_phase_deg[idx - 1]
2015        + t * (unwrapped_phase_deg[idx] - unwrapped_phase_deg[idx - 1]);
2016    (mag, phase)
2017}
2018
2019/// Compute Schroeder energy decay curve
2020fn compute_schroeder_decay(impulse: &[f32]) -> Vec<f32> {
2021    let mut energy = 0.0;
2022    let mut decay = vec![0.0; impulse.len()];
2023
2024    // Backward integration
2025    for i in (0..impulse.len()).rev() {
2026        energy += impulse[i] * impulse[i];
2027        decay[i] = energy;
2028    }
2029
2030    // Normalize to 0dB max (1.0 linear)
2031    let max_energy = decay.first().copied().unwrap_or(1.0);
2032    if max_energy > 0.0 {
2033        for v in &mut decay {
2034            *v /= max_energy;
2035        }
2036    }
2037
2038    decay
2039}
2040
2041/// Compute RT60 from Impulse Response (Broadband)
2042/// Uses T20 (-5dB to -25dB) extrapolation
2043pub fn compute_rt60_broadband(impulse: &[f32], sample_rate: f32) -> f32 {
2044    let decay = compute_schroeder_decay(impulse);
2045    let decay_db: Vec<f32> = decay.iter().map(|&v| 10.0 * v.max(1e-9).log10()).collect();
2046
2047    // Find -5dB and -25dB points
2048    let t_minus_5 = decay_db.iter().position(|&v| v < -5.0);
2049    let t_minus_25 = decay_db.iter().position(|&v| v < -25.0);
2050
2051    match (t_minus_5, t_minus_25) {
2052        (Some(start), Some(end)) => {
2053            if end > start {
2054                let dt = (end - start) as f32 / sample_rate; // Time for 20dB decay
2055                dt * 3.0 // Extrapolate to 60dB (T20 * 3)
2056            } else {
2057                0.0
2058            }
2059        }
2060        _ => 0.0,
2061    }
2062}
2063
2064/// Compute Clarity (C50, C80) from Impulse Response (Broadband)
2065/// Returns (C50_dB, C80_dB)
2066pub fn compute_clarity_broadband(impulse: &[f32], sample_rate: f32) -> (f32, f32) {
2067    let mut energy_0_50 = 0.0;
2068    let mut energy_50_inf = 0.0;
2069    let mut energy_0_80 = 0.0;
2070    let mut energy_80_inf = 0.0;
2071
2072    let samp_50ms = (0.050 * sample_rate) as usize;
2073    let samp_80ms = (0.080 * sample_rate) as usize;
2074
2075    for (i, &samp) in impulse.iter().enumerate() {
2076        let sq = samp * samp;
2077
2078        if i < samp_50ms {
2079            energy_0_50 += sq;
2080        } else {
2081            energy_50_inf += sq;
2082        }
2083
2084        if i < samp_80ms {
2085            energy_0_80 += sq;
2086        } else {
2087            energy_80_inf += sq;
2088        }
2089    }
2090
2091    // When late energy is negligible, clarity is very high (capped at 60 dB)
2092    // When early energy is negligible, clarity is very low (capped at -60 dB)
2093    const MAX_CLARITY_DB: f32 = 60.0;
2094
2095    let c50 = if energy_50_inf > 1e-12 && energy_0_50 > 1e-12 {
2096        let ratio = energy_0_50 / energy_50_inf;
2097        (10.0 * ratio.log10()).clamp(-MAX_CLARITY_DB, MAX_CLARITY_DB)
2098    } else if energy_0_50 > energy_50_inf {
2099        MAX_CLARITY_DB // Early energy dominates - excellent clarity
2100    } else {
2101        -MAX_CLARITY_DB // Late energy dominates - poor clarity
2102    };
2103
2104    let c80 = if energy_80_inf > 1e-12 && energy_0_80 > 1e-12 {
2105        let ratio = energy_0_80 / energy_80_inf;
2106        (10.0 * ratio.log10()).clamp(-MAX_CLARITY_DB, MAX_CLARITY_DB)
2107    } else if energy_80_inf > energy_0_80 {
2108        MAX_CLARITY_DB // Early energy dominates - excellent clarity
2109    } else {
2110        -MAX_CLARITY_DB // Late energy dominates - poor clarity
2111    };
2112
2113    (c50, c80)
2114}
2115
2116/// Compute RT60 spectrum using octave band filtering
2117pub fn compute_rt60_spectrum(impulse: &[f32], sample_rate: f32, frequencies: &[f32]) -> Vec<f32> {
2118    if impulse.is_empty() {
2119        return vec![0.0; frequencies.len()];
2120    }
2121
2122    // Octave band center frequencies
2123    let centers = [
2124        63.0f32, 125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 16000.0,
2125    ];
2126    let mut band_rt60s = Vec::with_capacity(centers.len());
2127    let mut valid_centers = Vec::with_capacity(centers.len());
2128
2129    // Compute RT60 for each band
2130    for &freq in &centers {
2131        // Skip if frequency is too high for sample rate
2132        if freq >= sample_rate / 2.0 {
2133            continue;
2134        }
2135
2136        // Apply bandpass filter
2137        // Q=1.414 (sqrt(2)) gives approx 1 octave bandwidth
2138        let mut biquad = Biquad::new(
2139            BiquadFilterType::Bandpass,
2140            freq as f64,
2141            sample_rate as f64,
2142            1.414,
2143            0.0,
2144        );
2145
2146        // Process in f64
2147        let mut filtered: Vec<f64> = impulse.iter().map(|&x| x as f64).collect();
2148        biquad.process_block(&mut filtered);
2149        let filtered_f32: Vec<f32> = filtered.iter().map(|&x| x as f32).collect();
2150
2151        // Compute RT60 for this band
2152        let rt60 = compute_rt60_broadband(&filtered_f32, sample_rate);
2153
2154        band_rt60s.push(rt60);
2155        valid_centers.push(freq);
2156    }
2157
2158    // Log per-band values
2159    log::info!(
2160        "[RT60] Per-band values: {:?}",
2161        valid_centers
2162            .iter()
2163            .zip(band_rt60s.iter())
2164            .map(|(f, v)| format!("{:.0}Hz:{:.1}ms", f, v))
2165            .collect::<Vec<_>>()
2166    );
2167
2168    if valid_centers.is_empty() {
2169        return vec![0.0; frequencies.len()];
2170    }
2171
2172    // Interpolate to output frequencies
2173    interpolate_log(&valid_centers, &band_rt60s, frequencies)
2174}
2175
2176/// Compute Clarity spectrum (C50, C80) using octave band filtering
2177/// Returns (C50_vec, C80_vec)
2178pub fn compute_clarity_spectrum(
2179    impulse: &[f32],
2180    sample_rate: f32,
2181    frequencies: &[f32],
2182) -> (Vec<f32>, Vec<f32>) {
2183    if impulse.is_empty() || frequencies.is_empty() {
2184        return (vec![0.0; frequencies.len()], vec![0.0; frequencies.len()]);
2185    }
2186
2187    // Octave band center frequencies
2188    let centers = [
2189        63.0f32, 125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 16000.0,
2190    ];
2191    let mut band_c50s = Vec::with_capacity(centers.len());
2192    let mut band_c80s = Vec::with_capacity(centers.len());
2193    let mut valid_centers = Vec::with_capacity(centers.len());
2194
2195    // Time boundaries for clarity calculation
2196    let samp_50ms = (0.050 * sample_rate) as usize;
2197    let samp_80ms = (0.080 * sample_rate) as usize;
2198
2199    // Compute Clarity for each band using cascaded bandpass for better selectivity
2200    for &freq in &centers {
2201        if freq >= sample_rate / 2.0 {
2202            continue;
2203        }
2204
2205        // Use cascaded biquads for sharper filter response (reduces filter ringing effects)
2206        let mut biquad1 = Biquad::new(
2207            BiquadFilterType::Bandpass,
2208            freq as f64,
2209            sample_rate as f64,
2210            0.707, // Lower Q per stage, cascaded gives Q ~ 1.0
2211            0.0,
2212        );
2213        let mut biquad2 = Biquad::new(
2214            BiquadFilterType::Bandpass,
2215            freq as f64,
2216            sample_rate as f64,
2217            0.707,
2218            0.0,
2219        );
2220
2221        let mut filtered: Vec<f64> = impulse.iter().map(|&x| x as f64).collect();
2222        biquad1.process_block(&mut filtered);
2223        biquad2.process_block(&mut filtered);
2224
2225        // Compute energy in early and late windows directly
2226        let mut energy_0_50 = 0.0f64;
2227        let mut energy_50_inf = 0.0f64;
2228        let mut energy_0_80 = 0.0f64;
2229        let mut energy_80_inf = 0.0f64;
2230
2231        for (i, &samp) in filtered.iter().enumerate() {
2232            let sq = samp * samp;
2233
2234            if i < samp_50ms {
2235                energy_0_50 += sq;
2236            } else {
2237                energy_50_inf += sq;
2238            }
2239
2240            if i < samp_80ms {
2241                energy_0_80 += sq;
2242            } else {
2243                energy_80_inf += sq;
2244            }
2245        }
2246
2247        // Compute C50 and C80 with proper handling
2248        // When late energy is very small, clarity is high (capped at 40 dB for display)
2249        const MAX_CLARITY_DB: f32 = 40.0;
2250        const MIN_ENERGY: f64 = 1e-20;
2251
2252        let c50 = if energy_50_inf > MIN_ENERGY && energy_0_50 > MIN_ENERGY {
2253            let ratio = energy_0_50 / energy_50_inf;
2254            (10.0 * ratio.log10() as f32).clamp(-MAX_CLARITY_DB, MAX_CLARITY_DB)
2255        } else if energy_0_50 > energy_50_inf {
2256            MAX_CLARITY_DB
2257        } else {
2258            -MAX_CLARITY_DB
2259        };
2260
2261        let c80 = if energy_80_inf > MIN_ENERGY && energy_0_80 > MIN_ENERGY {
2262            let ratio = energy_0_80 / energy_80_inf;
2263            (10.0 * ratio.log10() as f32).clamp(-MAX_CLARITY_DB, MAX_CLARITY_DB)
2264        } else if energy_0_80 > energy_80_inf {
2265            MAX_CLARITY_DB
2266        } else {
2267            -MAX_CLARITY_DB
2268        };
2269
2270        band_c50s.push(c50);
2271        band_c80s.push(c80);
2272        valid_centers.push(freq);
2273    }
2274
2275    // Log per-band values
2276    log::info!(
2277        "[Clarity] Per-band C50: {:?}",
2278        valid_centers
2279            .iter()
2280            .zip(band_c50s.iter())
2281            .map(|(f, v)| format!("{:.0}Hz:{:.1}dB", f, v))
2282            .collect::<Vec<_>>()
2283    );
2284
2285    if valid_centers.is_empty() {
2286        return (vec![0.0; frequencies.len()], vec![0.0; frequencies.len()]);
2287    }
2288
2289    // Interpolate to output frequency grid
2290    let c50_interp = interpolate_log(&valid_centers, &band_c50s, frequencies);
2291    let c80_interp = interpolate_log(&valid_centers, &band_c80s, frequencies);
2292
2293    (c50_interp, c80_interp)
2294}
2295
2296/// Compute Spectrogram from Impulse Response
2297/// Returns (spectrogram_matrix_db, frequency_bins, time_bins)
2298/// `window_size` samples (e.g. 512), `hop_size` samples (e.g. 128).
2299pub fn compute_spectrogram(
2300    impulse: &[f32],
2301    sample_rate: f32,
2302    window_size: usize,
2303    hop_size: usize,
2304) -> (Vec<Vec<f32>>, Vec<f32>, Vec<f32>) {
2305    use rustfft::num_complex::Complex;
2306
2307    if impulse.len() < window_size {
2308        return (Vec::new(), Vec::new(), Vec::new());
2309    }
2310
2311    let num_frames = (impulse.len() - window_size) / hop_size;
2312    let mut spectrogram = Vec::with_capacity(num_frames);
2313    let mut times = Vec::with_capacity(num_frames);
2314
2315    // Precompute Hann window
2316    let window: Vec<f32> = (0..window_size)
2317        .map(|i| 0.5 * (1.0 - (2.0 * PI * i as f32 / (window_size as f32 - 1.0)).cos()))
2318        .collect();
2319
2320    // Setup FFT
2321    let fft = plan_fft_forward(window_size);
2322
2323    for i in 0..num_frames {
2324        let start = i * hop_size;
2325        let time_ms = (start as f32 / sample_rate) * 1000.0;
2326        times.push(time_ms);
2327
2328        let mut buffer: Vec<Complex<f32>> = (0..window_size)
2329            .map(|j| {
2330                let sample = impulse.get(start + j).copied().unwrap_or(0.0);
2331                Complex::new(sample * window[j], 0.0)
2332            })
2333            .collect();
2334
2335        fft.process(&mut buffer);
2336
2337        // Take magnitude of first half (up to Nyquist)
2338        // Store as dB
2339        let magnitude_db: Vec<f32> = buffer[..window_size / 2]
2340            .iter()
2341            .map(|c| {
2342                let mag = c.norm();
2343                if mag > 1e-9 {
2344                    20.0 * mag.log10()
2345                } else {
2346                    -180.0
2347                }
2348            })
2349            .collect();
2350
2351        spectrogram.push(magnitude_db);
2352    }
2353
2354    // Generate frequency bins
2355    let num_bins = window_size / 2;
2356    let freq_step = sample_rate / window_size as f32;
2357    let freqs: Vec<f32> = (0..num_bins).map(|i| i as f32 * freq_step).collect();
2358
2359    (spectrogram, freqs, times)
2360}
2361
2362/// Find a frequency point where the magnitude reaches a specific dB level
2363///
2364/// # Arguments
2365/// * `frequencies` - Frequency points in Hz
2366/// * `magnitude_db` - Magnitude in dB
2367/// * `target_db` - The target level to find (e.g., -3.0)
2368/// * `from_start` - If true, search from the beginning of the curve. If false, search from the end.
2369///
2370/// # Returns
2371/// The interpolated frequency where the target dB is reached, or None if not found.
2372pub fn find_db_point(
2373    frequencies: &[f32],
2374    magnitude_db: &[f32],
2375    target_db: f32,
2376    from_start: bool,
2377) -> Option<f32> {
2378    if frequencies.len() < 2 || frequencies.len() != magnitude_db.len() {
2379        return None;
2380    }
2381
2382    if from_start {
2383        for i in 0..magnitude_db.len() - 1 {
2384            let m0 = magnitude_db[i];
2385            let m1 = magnitude_db[i + 1];
2386
2387            // Check if target_db is between m0 and m1
2388            if (m0 <= target_db && target_db <= m1) || (m1 <= target_db && target_db <= m0) {
2389                // Linear interpolation: m0 + t * (m1 - m0) = target_db
2390                let denominator = m1 - m0;
2391                if denominator.abs() < 1e-9 {
2392                    return Some(frequencies[i]);
2393                }
2394                let t = (target_db - m0) / denominator;
2395                return Some(frequencies[i] + t * (frequencies[i + 1] - frequencies[i]));
2396            }
2397        }
2398    } else {
2399        for i in (1..magnitude_db.len()).rev() {
2400            let m0 = magnitude_db[i];
2401            let m1 = magnitude_db[i - 1];
2402
2403            // Check if target_db is between m0 and m1
2404            if (m0 <= target_db && target_db <= m1) || (m1 <= target_db && target_db <= m0) {
2405                let denominator = m1 - m0;
2406                if denominator.abs() < 1e-9 {
2407                    return Some(frequencies[i]);
2408                }
2409                let t = (target_db - m0) / denominator;
2410                return Some(frequencies[i] + t * (frequencies[i - 1] - frequencies[i]));
2411            }
2412        }
2413    }
2414
2415    None
2416}
2417
2418/// Compute a log-frequency weighted reference response level in dB.
2419///
2420/// # Arguments
2421/// * `frequencies` - Frequency points in Hz
2422/// * `magnitude_db` - Magnitude in dB
2423/// * `freq_range` - Optional (start_freq, end_freq) to limit the averaging range.
2424///   If None, averages over the full bandwidth.
2425///
2426/// # Returns
2427/// The log-frequency weighted average in the dB domain.
2428///
2429/// This is intended as a stable acoustic reference level for comparison and
2430/// normalization. It is not a pressure- or energy-domain average.
2431pub fn compute_average_response(
2432    frequencies: &[f32],
2433    magnitude_db: &[f32],
2434    freq_range: Option<(f32, f32)>,
2435) -> f32 {
2436    if frequencies.len() < 2 || frequencies.len() != magnitude_db.len() {
2437        return magnitude_db.first().copied().unwrap_or(0.0);
2438    }
2439
2440    let (start_freq, end_freq) =
2441        freq_range.unwrap_or((frequencies[0], frequencies[frequencies.len() - 1]));
2442
2443    let mut sum_weighted_db = 0.0;
2444    let mut sum_weights = 0.0;
2445
2446    for i in 0..frequencies.len() - 1 {
2447        let f0 = frequencies[i];
2448        let f1 = frequencies[i + 1];
2449
2450        // Check if this segment overlaps with the target range
2451        if f1 < start_freq || f0 > end_freq {
2452            continue;
2453        }
2454
2455        // Clamp segment to target range
2456        let fa = f0.max(start_freq);
2457        let fb = f1.min(end_freq);
2458
2459        if fb <= fa {
2460            continue;
2461        }
2462
2463        // For acoustic data, we weight by log frequency (octaves)
2464        // weight = log2(fb/fa)
2465        let weight = (fb / fa).log2();
2466
2467        // Average magnitude in this segment
2468        // We'll use the midpoint value of the segment (or average of endpoints)
2469        // If the segment is partially outside start_freq/end_freq, we should interpolate
2470        // but for many points simple average of endpoints in the segment is fine.
2471        let m0 = magnitude_db[i];
2472        let m1 = magnitude_db[i + 1];
2473        let avg_m = (m0 + m1) / 2.0;
2474
2475        sum_weighted_db += avg_m * weight;
2476        sum_weights += weight;
2477    }
2478
2479    if sum_weights > 0.0 {
2480        sum_weighted_db / sum_weights
2481    } else {
2482        magnitude_db.first().copied().unwrap_or(0.0)
2483    }
2484}
2485
2486#[cfg(test)]
2487mod tests {
2488    use super::*;
2489
2490    #[test]
2491    fn test_next_power_of_two() {
2492        assert_eq!(next_power_of_two(1), 1);
2493        assert_eq!(next_power_of_two(2), 2);
2494        assert_eq!(next_power_of_two(3), 4);
2495        assert_eq!(next_power_of_two(1000), 1024);
2496        assert_eq!(next_power_of_two(1024), 1024);
2497        assert_eq!(next_power_of_two(1025), 2048);
2498    }
2499
2500    #[test]
2501    fn test_hann_window() {
2502        let signal = vec![1.0; 100];
2503        let windowed = apply_hann_window(&signal);
2504
2505        // First and last samples should be near zero
2506        assert!(windowed[0].abs() < 0.01);
2507        assert!(windowed[99].abs() < 0.01);
2508
2509        // Middle sample should be near 1.0
2510        assert!((windowed[50] - 1.0).abs() < 0.01);
2511    }
2512
2513    #[test]
2514    fn test_estimate_lag_zero() {
2515        // Identical signals should have zero lag
2516        let signal = vec![1.0, 2.0, 3.0, 4.0, 5.0];
2517        let lag = estimate_lag(&signal, &signal).unwrap();
2518        assert_eq!(lag, 0);
2519    }
2520
2521    #[test]
2522    fn test_estimate_lag_positive() {
2523        // Reference leads recorded (recorded is delayed)
2524        // Use longer signals for reliable FFT-based cross-correlation
2525        let mut reference = vec![0.0; 100];
2526        let mut recorded = vec![0.0; 100];
2527
2528        // Create a pulse pattern that will correlate well
2529        for (j, val) in reference[10..20].iter_mut().enumerate() {
2530            *val = j as f32 / 10.0;
2531        }
2532        // Same pattern but delayed by 5 samples
2533        for (j, val) in recorded[15..25].iter_mut().enumerate() {
2534            *val = j as f32 / 10.0;
2535        }
2536
2537        let lag = estimate_lag(&reference, &recorded).unwrap();
2538        assert_eq!(lag, 5, "Recorded signal is delayed by 5 samples");
2539    }
2540
2541    #[test]
2542    fn test_identical_signals_have_zero_lag() {
2543        // When signals are truly identical (like in the bug case),
2544        // lag should be exactly zero
2545        let signal = vec![1.0, 2.0, 3.0, 4.0, 5.0];
2546        let lag = estimate_lag(&signal, &signal).unwrap();
2547        assert_eq!(lag, 0, "Identical signals should have zero lag");
2548    }
2549
2550    /// Write a mono f32 WAV file for testing
2551    fn write_test_wav(path: &std::path::Path, samples: &[f32], sample_rate: u32) {
2552        let spec = hound::WavSpec {
2553            channels: 1,
2554            sample_rate,
2555            bits_per_sample: 32,
2556            sample_format: hound::SampleFormat::Float,
2557        };
2558        let mut writer = hound::WavWriter::create(path, spec).unwrap();
2559        for &s in samples {
2560            writer.write_sample(s).unwrap();
2561        }
2562        writer.finalize().unwrap();
2563    }
2564
2565    /// Generate a log sweep signal (same as the recording system uses)
2566    fn generate_test_sweep(
2567        start_freq: f32,
2568        end_freq: f32,
2569        duration_secs: f32,
2570        sample_rate: u32,
2571        amplitude: f32,
2572    ) -> Vec<f32> {
2573        let num_samples = (duration_secs * sample_rate as f32) as usize;
2574        let mut signal = Vec::with_capacity(num_samples);
2575        let ln_ratio = (end_freq / start_freq).ln();
2576        for i in 0..num_samples {
2577            let t = i as f32 / sample_rate as f32;
2578            let phase = 2.0 * PI * start_freq * duration_secs / ln_ratio
2579                * ((t / duration_secs * ln_ratio).exp() - 1.0);
2580            signal.push(amplitude * phase.sin());
2581        }
2582        signal
2583    }
2584
2585    #[test]
2586    fn test_analyze_recording_normal_channel() {
2587        // Simulate a normal speaker: reference sweep played back and recorded
2588        // with some attenuation and small delay
2589        let sample_rate = 48000;
2590        let duration = 1.0;
2591        let reference = generate_test_sweep(20.0, 20000.0, duration, sample_rate, 0.5);
2592
2593        // Simulate recording: attenuate by ~-6dB (factor 0.5) and delay by 100 samples
2594        let delay = 100;
2595        let attenuation = 0.5;
2596        let mut recorded = vec![0.0_f32; reference.len() + delay];
2597        for (i, &s) in reference.iter().enumerate() {
2598            recorded[i + delay] = s * attenuation;
2599        }
2600
2601        let dir = std::env::temp_dir().join(format!("sotf_test_normal_{}", std::process::id()));
2602        std::fs::create_dir_all(&dir).unwrap();
2603        let wav_path = dir.join("test_normal.wav");
2604        write_test_wav(&wav_path, &recorded, sample_rate);
2605
2606        let result = analyze_recording(&wav_path, &reference, sample_rate, None).unwrap();
2607        std::fs::remove_dir_all(&dir).ok();
2608
2609        // Compute average SPL in the passband (200 Hz - 10 kHz)
2610        let mut sum = 0.0_f32;
2611        let mut count = 0;
2612        for (&freq, &db) in result.frequencies.iter().zip(result.spl_db.iter()) {
2613            if (200.0..=10000.0).contains(&freq) {
2614                sum += db;
2615                count += 1;
2616            }
2617        }
2618        let avg_db = sum / count as f32;
2619
2620        // Expected: ~-6 dB (attenuation factor 0.5)
2621        // Allow generous tolerance for windowing/FFT artifacts
2622        assert!(
2623            avg_db > -12.0 && avg_db < 0.0,
2624            "Normal channel avg SPL should be near -6 dB, got {:.1} dB",
2625            avg_db
2626        );
2627
2628        // No bin should exceed +6 dB (physically implausible for passive attenuation)
2629        let max_db = result
2630            .spl_db
2631            .iter()
2632            .zip(result.frequencies.iter())
2633            .filter(|&(_, &f)| (200.0..=10000.0).contains(&f))
2634            .map(|(&db, _)| db)
2635            .fold(f32::NEG_INFINITY, f32::max);
2636        assert!(
2637            max_db < 6.0,
2638            "Normal channel should not have bins above +6 dB, got {:.1} dB",
2639            max_db
2640        );
2641    }
2642
2643    #[test]
2644    fn test_analyze_recording_silent_channel() {
2645        // Simulate a disconnected speaker: reference sweep played but recording
2646        // is just low-level noise (no speaker output)
2647        let sample_rate = 48000;
2648        let duration = 1.0;
2649        let reference = generate_test_sweep(20.0, 20000.0, duration, sample_rate, 0.5);
2650
2651        // Recording is pure noise at -60 dBFS (amplitude 0.001)
2652        let noise_amplitude = 0.001;
2653        let num_samples = reference.len();
2654        let mut recorded = Vec::with_capacity(num_samples);
2655        // Use deterministic "noise" (alternating small values)
2656        for i in 0..num_samples {
2657            let pseudo_noise =
2658                noise_amplitude * (((i as f32 * 0.1).sin() + (i as f32 * 0.37).cos()) * 0.5);
2659            recorded.push(pseudo_noise);
2660        }
2661
2662        let dir = std::env::temp_dir().join(format!("sotf_test_silent_{}", std::process::id()));
2663        std::fs::create_dir_all(&dir).unwrap();
2664        let wav_path = dir.join("test_silent.wav");
2665        write_test_wav(&wav_path, &recorded, sample_rate);
2666
2667        let result = analyze_recording(&wav_path, &reference, sample_rate, None).unwrap();
2668        std::fs::remove_dir_all(&dir).ok();
2669
2670        // For a disconnected channel, the transfer function should be very low
2671        // (noise / sweep ≈ noise floor). It must NOT show spurious high-dB peaks.
2672        let max_db = result
2673            .spl_db
2674            .iter()
2675            .zip(result.frequencies.iter())
2676            .filter(|&(_, &f)| (100.0..=10000.0).contains(&f))
2677            .map(|(&db, _)| db)
2678            .fold(f32::NEG_INFINITY, f32::max);
2679
2680        assert!(
2681            max_db < 0.0,
2682            "Silent/disconnected channel should not have positive dB values, got max {:.1} dB",
2683            max_db
2684        );
2685    }
2686
2687    #[test]
2688    fn test_analyze_recording_lfe_narrow_sweep_same_point_count() {
2689        // Simulate a 5.1 scenario: LFE uses a narrow sweep (20-500 Hz) while
2690        // main channels use the full range (20-20000 Hz). Both must produce
2691        // the same number of output frequency points to avoid ndarray shape
2692        // mismatches when curves are combined in the optimizer.
2693        let sample_rate = 48000;
2694        let duration = 1.0;
2695
2696        // Full-range reference (main channel)
2697        let ref_full = generate_test_sweep(20.0, 20000.0, duration, sample_rate, 0.5);
2698        // Narrow reference (LFE)
2699        let ref_lfe = generate_test_sweep(20.0, 500.0, duration, sample_rate, 0.5);
2700
2701        // Simulate recordings: attenuated copies with delay
2702        let delay = 50;
2703        let atten = 0.3;
2704
2705        let mut rec_full = vec![0.0_f32; ref_full.len() + delay];
2706        for (i, &s) in ref_full.iter().enumerate() {
2707            rec_full[i + delay] = s * atten;
2708        }
2709
2710        let mut rec_lfe = vec![0.0_f32; ref_lfe.len() + delay];
2711        for (i, &s) in ref_lfe.iter().enumerate() {
2712            rec_lfe[i + delay] = s * atten;
2713        }
2714
2715        let dir = std::env::temp_dir().join(format!("sotf_test_lfe_points_{}", std::process::id()));
2716        std::fs::create_dir_all(&dir).unwrap();
2717
2718        let wav_full = dir.join("main.wav");
2719        let wav_lfe = dir.join("lfe.wav");
2720        write_test_wav(&wav_full, &rec_full, sample_rate);
2721        write_test_wav(&wav_lfe, &rec_lfe, sample_rate);
2722
2723        let result_full = analyze_recording(&wav_full, &ref_full, sample_rate, None).unwrap();
2724        let result_lfe = analyze_recording(&wav_lfe, &ref_lfe, sample_rate, None).unwrap();
2725        std::fs::remove_dir_all(&dir).ok();
2726
2727        // Both must produce the same number of frequency points
2728        assert_eq!(
2729            result_full.frequencies.len(),
2730            result_lfe.frequencies.len(),
2731            "Main ({}) and LFE ({}) must have the same number of frequency points",
2732            result_full.frequencies.len(),
2733            result_lfe.frequencies.len()
2734        );
2735        assert_eq!(
2736            result_full.spl_db.len(),
2737            result_lfe.spl_db.len(),
2738            "SPL arrays must match in length"
2739        );
2740
2741        // LFE should have valid data below ~500 Hz and noise floor above
2742        let lfe_valid_count = result_lfe
2743            .spl_db
2744            .iter()
2745            .zip(result_lfe.frequencies.iter())
2746            .filter(|&(&db, &f)| f <= 500.0 && db > -100.0)
2747            .count();
2748        assert!(
2749            lfe_valid_count > 100,
2750            "LFE should have valid data below 500 Hz, got {} points",
2751            lfe_valid_count
2752        );
2753
2754        let lfe_above_500_max = result_lfe
2755            .spl_db
2756            .iter()
2757            .zip(result_lfe.frequencies.iter())
2758            .filter(|&(_, &f)| f > 1000.0)
2759            .map(|(&db, _)| db)
2760            .fold(f32::NEG_INFINITY, f32::max);
2761        assert!(
2762            lfe_above_500_max <= -100.0,
2763            "LFE above 1 kHz should be at noise floor, got {:.1} dB",
2764            lfe_above_500_max
2765        );
2766    }
2767}