1use 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
20type 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
27pub 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
35pub 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#[derive(Debug, Clone)]
42pub struct MicrophoneCompensation {
43 pub frequencies: Vec<f32>,
45 pub spl_db: Vec<f32>,
47}
48
49impl MicrophoneCompensation {
50 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 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 let freq = start_freq * ((t * (end_freq / start_freq).ln()) / duration).exp();
84
85 let comp_db = self.interpolate_at(freq);
87
88 let gain_db = if inverse { -comp_db } else { comp_db };
90
91 let gain = 10_f32.powf(gain_db / 20.0);
93
94 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 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 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 if line.is_empty() || line.starts_with('#') {
154 continue;
155 }
156
157 if !is_txt_file && line.starts_with("frequency") {
159 continue;
160 }
161
162 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 let parts: Vec<&str> = if is_txt_file {
177 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 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 line.split_whitespace().collect()
196 }
197 }
198 } else {
199 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 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 pub fn interpolate_at(&self, freq: f32) -> f32 {
269 if freq < self.frequencies[0] || freq > self.frequencies[self.frequencies.len() - 1] {
270 return 0.0;
272 }
273
274 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], 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 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#[derive(Debug, Clone)]
307pub struct WavAnalysisConfig {
308 pub num_points: usize,
310 pub min_freq: f32,
312 pub max_freq: f32,
314 pub fft_size: Option<usize>,
316 pub overlap: f32,
318 pub single_fft: bool,
320 pub pink_compensation: bool,
322 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 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 pub fn for_impulse_response() -> Self {
354 Self {
355 single_fft: true,
356 ..Default::default()
357 }
358 }
359
360 pub fn for_stationary() -> Self {
362 Self::default()
363 }
364}
365
366#[derive(Debug, Clone)]
368pub struct WavAnalysisOutput {
369 pub frequencies: Vec<f32>,
371 pub magnitude_db: Vec<f32>,
373 pub phase_deg: Vec<f32>,
375}
376
377pub 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 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 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 let log_freqs = generate_log_frequencies(config.num_points, config.min_freq, config.max_freq);
413
414 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 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
436pub 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
452fn 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 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
487pub 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
511fn 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 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 for i in 0..window_len {
554 windowed[i] = signal[start + i] * hann_window[i];
555 }
556 windowed[window_len..fft_size].fill(0.0);
558
559 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
599fn 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
662fn 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
671fn 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
682fn 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
708fn 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 let p0 = phase_deg[idx - 1];
731 let p1 = phase_deg[idx];
732 let mut diff = p1 - p0;
733 diff -= 360.0 * (diff / 360.0).round();
735 p0 + t * diff
736 })
737 .collect()
738}
739
740#[derive(Debug, Clone)]
746pub struct AnalysisResult {
747 pub frequencies: Vec<f32>,
749 pub spl_db: Vec<f32>,
751 pub phase_deg: Vec<f32>,
753 pub estimated_lag_samples: isize,
755 pub impulse_response: Vec<f32>,
757 pub impulse_time_ms: Vec<f32>,
759 pub excess_group_delay_ms: Vec<f32>,
761 pub thd_percent: Vec<f32>,
763 pub harmonic_distortion_db: Vec<Vec<f32>>,
765 pub rt60_ms: Vec<f32>,
767 pub clarity_c50_db: Vec<f32>,
769 pub clarity_c80_db: Vec<f32>,
771 pub spectrogram_db: Vec<Vec<f32>>,
773}
774
775pub 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 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 let recorded = &recorded[..];
812 let reference = reference_signal;
813
814 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 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 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 (reference, &recorded[lag_usize..])
883 } else {
884 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 (&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 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 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; 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 let ref_regularization_threshold = ref_peak_mag_sq * 1e-6;
928
929 let mut skipped_count = 0;
931 for i in 0..num_output_points {
932 let target_freq =
934 (log_start + (log_end - log_start) * i as f32 / (num_output_points - 1) as f32).exp();
935
936 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 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 frequencies.push(target_freq);
960 spl_db.push(-200.0);
961 phase_deg.push(0.0);
962 continue;
963 }
964
965 let mut sum_magnitude = 0.0;
967 let mut sum_sin = 0.0; 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 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 let cross_spectrum = ref_spectrum[k].conj() * rec_spectrum[k];
990 let phase_rad = cross_spectrum.arg();
991
992 sum_magnitude += magnitude;
994 sum_sin += phase_rad.sin();
995 sum_cos += phase_rad.cos();
996 bin_count += 1;
997 }
998
999 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 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 let mut transfer_function = vec![Complex::new(0.0, 0.0); fft_size];
1051 for k in 0..fft_size {
1052 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 let ifft = plan_fft_inverse(fft_size);
1062 ifft.process(&mut transfer_function);
1063
1064 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 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 let pre_ring_samples = (0.005 * sample_rate as f32) as usize; 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 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 let (thd_percent, harmonic_distortion_db) = if let Some((start, end)) = sweep_range {
1102 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 let excess_group_delay_ms = vec![0.0; frequencies.len()];
1121
1122 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 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 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
1180fn 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; let mut harmonics_db = vec![vec![-120.0; frequencies.len()]; num_harmonics];
1204
1205 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 for (k_idx, harmonic_db) in harmonics_db.iter_mut().enumerate().take(num_harmonics) {
1226 let harmonic_order = k_idx + 2; let dt = duration * (harmonic_order as f32).ln() / sweep_ratio.ln();
1231 let dn = (dt * sample_rate).round() as isize;
1232
1233 let center = peak_idx as isize - dn;
1235 let center_wrapped = center.rem_euclid(n as isize) as usize;
1236
1237 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 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 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 let fft_size = next_power_of_two(win_len);
1269 let nyquist_bin = fft_size / 2; 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 if bin < nyquist_bin && bin < spectrum.len() {
1277 let mag = spectrum[bin].norm();
1280 if mag > 1e-6 {
1282 harmonic_db[i] = 20.0 * mag.log10();
1283 }
1284 }
1285 }
1286 }
1287 }
1288
1289 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 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 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 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
1333pub 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 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 for i in 0..result.frequencies.len() {
1382 let freq = result.frequencies[i];
1383 let mut spl = result.spl_db[i];
1384
1385 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
1415pub 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 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 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#[derive(Debug, Clone, Copy)]
1499enum WindowType {
1500 Hann,
1501 Tukey(f32), }
1503
1504fn estimate_lag(reference: &[f32], recorded: &[f32]) -> Result<isize, String> {
1515 let len = reference.len().min(recorded.len());
1516
1517 let fft_size = next_power_of_two(len * 2);
1519
1520 let ref_fft = compute_fft(reference, fft_size, WindowType::Hann)?;
1522 let rec_fft = compute_fft(recorded, fft_size, WindowType::Hann)?;
1523
1524 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 let ifft = plan_fft_inverse(fft_size);
1533 ifft.process(&mut cross_corr_fft);
1534
1535 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 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
1555fn compute_fft(
1565 signal: &[f32],
1566 fft_size: usize,
1567 window_type: WindowType,
1568) -> Result<Vec<Complex<f32>>, String> {
1569 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
1578fn compute_fft_padded(signal: &[f32], fft_size: usize) -> Result<Vec<Complex<f32>>, String> {
1580 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 let fft = plan_fft_forward(fft_size);
1588 fft.process(&mut buffer);
1589
1590 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
1599fn 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
1615fn 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 0.5 * (1.0 - (PI * i as f32 / limit as f32).cos())
1639 } else if i >= len - limit {
1640 let n = len - 1 - i;
1642 0.5 * (1.0 - (PI * n as f32 / limit as f32).cos())
1643 } else {
1644 1.0
1646 };
1647 x * w
1648 })
1649 .collect()
1650}
1651
1652fn next_power_of_two(n: usize) -> usize {
1654 if n == 0 {
1655 return 1;
1656 }
1657 n.next_power_of_two()
1658}
1659
1660fn 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 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 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 if let Some(ch_idx) = channel_index {
1706 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 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
1735fn load_wav_mono(path: &Path) -> Result<Vec<f32>, String> {
1737 load_wav_mono_channel(path, None)
1738}
1739
1740pub 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 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, ¢er_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 while lo < n && frequencies[lo] < low_freq {
1778 lo += 1;
1779 }
1780 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
1796pub 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 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, ¢er_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 while lo < n && frequencies[lo] < low_freq {
1830 lo += 1;
1831 }
1832 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
1848pub 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 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 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 } else {
1871 0.0
1872 }
1873 } else if i == frequencies.len() - 1 {
1874 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 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
1898fn 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
1918pub 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; let freq_bin = sample_rate / fft_size as f32;
1934
1935 let unwrapped_phase = unwrap_phase_deg(phase_deg);
1937
1938 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 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 for k in 1..half {
1955 spectrum[fft_size - k] = spectrum[k].conj();
1956 }
1957
1958 let ifft = plan_fft_inverse(fft_size);
1960 ifft.process(&mut spectrum);
1961
1962 let scale = 1.0 / fft_size as f32;
1964 let mut impulse: Vec<f32> = spectrum.iter().map(|c| c.re * scale).collect();
1965
1966 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
1982fn 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 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, };
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
2019fn compute_schroeder_decay(impulse: &[f32]) -> Vec<f32> {
2021 let mut energy = 0.0;
2022 let mut decay = vec![0.0; impulse.len()];
2023
2024 for i in (0..impulse.len()).rev() {
2026 energy += impulse[i] * impulse[i];
2027 decay[i] = energy;
2028 }
2029
2030 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
2041pub 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 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; dt * 3.0 } else {
2057 0.0
2058 }
2059 }
2060 _ => 0.0,
2061 }
2062}
2063
2064pub 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 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 } else {
2101 -MAX_CLARITY_DB };
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 } else {
2110 -MAX_CLARITY_DB };
2112
2113 (c50, c80)
2114}
2115
2116pub 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 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 for &freq in ¢ers {
2131 if freq >= sample_rate / 2.0 {
2133 continue;
2134 }
2135
2136 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 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 let rt60 = compute_rt60_broadband(&filtered_f32, sample_rate);
2153
2154 band_rt60s.push(rt60);
2155 valid_centers.push(freq);
2156 }
2157
2158 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_log(&valid_centers, &band_rt60s, frequencies)
2174}
2175
2176pub 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 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 let samp_50ms = (0.050 * sample_rate) as usize;
2197 let samp_80ms = (0.080 * sample_rate) as usize;
2198
2199 for &freq in ¢ers {
2201 if freq >= sample_rate / 2.0 {
2202 continue;
2203 }
2204
2205 let mut biquad1 = Biquad::new(
2207 BiquadFilterType::Bandpass,
2208 freq as f64,
2209 sample_rate as f64,
2210 0.707, 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 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 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::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 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
2296pub 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 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 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 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 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
2362pub 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 if (m0 <= target_db && target_db <= m1) || (m1 <= target_db && target_db <= m0) {
2389 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 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
2418pub 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 if f1 < start_freq || f0 > end_freq {
2452 continue;
2453 }
2454
2455 let fa = f0.max(start_freq);
2457 let fb = f1.min(end_freq);
2458
2459 if fb <= fa {
2460 continue;
2461 }
2462
2463 let weight = (fb / fa).log2();
2466
2467 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 assert!(windowed[0].abs() < 0.01);
2507 assert!(windowed[99].abs() < 0.01);
2508
2509 assert!((windowed[50] - 1.0).abs() < 0.01);
2511 }
2512
2513 #[test]
2514 fn test_estimate_lag_zero() {
2515 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 let mut reference = vec![0.0; 100];
2526 let mut recorded = vec![0.0; 100];
2527
2528 for (j, val) in reference[10..20].iter_mut().enumerate() {
2530 *val = j as f32 / 10.0;
2531 }
2532 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 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 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 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 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 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 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 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 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 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 let noise_amplitude = 0.001;
2653 let num_samples = reference.len();
2654 let mut recorded = Vec::with_capacity(num_samples);
2655 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 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 let sample_rate = 48000;
2694 let duration = 1.0;
2695
2696 let ref_full = generate_test_sweep(20.0, 20000.0, duration, sample_rate, 0.5);
2698 let ref_lfe = generate_test_sweep(20.0, 500.0, duration, sample_rate, 0.5);
2700
2701 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 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 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}