roomeq-model 0.5.5

RoomEQ configuration, pipeline, and DSP-chain contracts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
use super::area_quadrature_kind::AreaQuadratureKind;
use super::bass_anchor_results_legacy::BassAnchorResultsLegacy;
use super::bass_management_config::BassManagementConfig;
use super::default::default_area_cvar_alpha;
use super::default::default_area_inner_maxiter;
use super::default::default_ctc_hrtf_distance_m;
use super::default::default_fir_phase;
use super::default::default_fir_taps;
use super::default::default_gaussian_truncation_sigmas;
use super::default::default_idw_power;
use super::default::default_mask_smoothing;
use super::default::default_mask_smoothing_octaves;
use super::default::default_min_correction_depth;
use super::default::default_mixed_phase_fir_length;
use super::default::default_mixed_phase_spatial_depth;
use super::default::default_modal_weight_scale;
use super::default::default_phase_smoothing;
use super::default::default_pre_ringing_threshold;
use super::default::default_pre_ringing_time;
use super::default::default_smoothness_exponent;
use super::default::default_transition_width;
use super::default::default_variance_threshold;
use super::room_dimensions::RoomDimensions;
use super::spl_calibration::SplCalibration;
use crate::MeasurementSource;
pub use crate::optimizer_settings::MultiMeasurementStrategy;
use schemars::JsonSchema;
use serde::{Deserialize, Deserializer, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

/// Recording configuration stored with measurements
/// Contains device settings and signal parameters used during measurement capture
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct RecordingConfiguration {
    /// Playback device name
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub playback_device_name: Option<String>,
    /// Playback device ID
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub playback_device_id: Option<String>,
    /// Playback sample rate in Hz
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub playback_sample_rate: Option<u32>,
    /// Playback channel count
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub playback_channels: Option<usize>,
    /// Speaker configuration (e.g. "5.1", "7.1.4", "Stereo")
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub speaker_configuration: Option<String>,
    /// Channel names in order (e.g. ["L", "R", "C", "LFE", "SL", "SR"])
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub channel_names: Option<Vec<String>>,
    /// Recording device name
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recording_device_name: Option<String>,
    /// Recording device ID
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recording_device_id: Option<String>,
    /// Recording sample rate in Hz
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recording_sample_rate: Option<u32>,
    /// Recording channel count
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recording_channels: Option<usize>,
    /// Microphone calibration file path (if used)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mic_calibration_path: Option<String>,
    /// Per-channel microphone calibration file paths
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mic_calibration_paths: Option<Vec<Option<String>>>,
    /// Recording output directory
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recording_directory: Option<String>,
    /// Signal type used for measurements (e.g. "Sweep", "Pink Noise")
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signal_type: Option<String>,
    /// Signal duration in seconds
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signal_duration_secs: Option<f32>,
    /// Signal level in dB
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signal_level_db: Option<f32>,
    /// Sweep start frequency in Hz (only applicable when signal_type is "Sweep")
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sweep_start_freq: Option<f32>,
    /// Sweep end frequency in Hz (only applicable when signal_type is "Sweep")
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sweep_end_freq: Option<f32>,
    /// Physical room dimensions (metric — length/width/height in meters)
    /// collected from the user at save time. When present these are
    /// reused by the optimizer's Schroeder-frequency auto-detection; see
    /// [`RoomDimensions::schroeder_frequency_with_rt60`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub room_dimensions: Option<RoomDimensions>,
    /// Free-form description of the listening setup (treatment,
    /// seating, notes about speaker placement, etc.). Not consumed by
    /// the optimizer — stored purely for session reproducibility.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub setup_description: Option<String>,
    /// Per-channel speaker identity (brand + model) as free-form
    /// strings, ideally autocompleted from the spinorama.org catalog.
    /// Keyed by channel name so it round-trips through reorder/rename.
    /// Not consumed by the optimizer — metadata only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub channel_speakers: Option<HashMap<String, String>>,
    /// Tone-burst delay probe results captured during the Recording
    /// wizard's Probe step. Stored here so the `autoeq::roomeq`
    /// pipeline can pick them up at config-load time without requiring
    /// a live measurement. Mirrors the shape of the engine's
    /// `ProbeDelayResults` for cross-crate serde compatibility.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub probe_results: Option<ProbeResultsLegacy>,
    /// Relative path (within the recording directory) of the raw
    /// probe WAV persisted by `probe_channel_delays_with_recording`.
    /// `None` for sessions that skipped the Probe step.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub probe_wav_relative: Option<String>,

    /// Bass anchor results captured during the GD-1e BassAnchor
    /// wizard step — per-channel phase of a low-frequency tone burst
    /// at `bass_probe_freq_hz`. Populated after the wizard finishes;
    /// absent when the user skipped the step.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bass_anchor_results: Option<BassAnchorResultsLegacy>,

    /// Relative path (within the recording directory) of the raw
    /// bass-anchor WAV. `None` when the BassAnchor step was skipped
    /// or when recording persistence was disabled.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bass_anchor_wav_relative: Option<String>,

    // ------------------------------------------------------------------
    // GD-Opt v2 recording extensions (see `docs/gd_opt_v2_plan.md` §2).
    // All optional; absent values degrade the GD confidence gate but
    // do not break the wider recording pipeline.
    // ------------------------------------------------------------------
    /// Per-octave bass sweep duration in seconds. Defaults to 3.0; the
    /// sweep generator scales total duration so that the band below
    /// 100 Hz receives `bass_octave_duration_s` seconds per octave.
    /// Clamped to `[1.0 .. 10.0]` at load time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bass_octave_duration_s: Option<f32>,
    /// Pre-sweep silence window in seconds. Used by the coherence
    /// averager to estimate the noise-floor. Default 2.0.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pre_silence_s: Option<f32>,
    /// Post-sweep silence window in seconds. Default
    /// `schroeder_rt60 + 1.0`; falls back to `2.0` if no RT60 estimate
    /// is available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub post_silence_s: Option<f32>,
    /// Target sweep level at the listening position in dBSPL. Requires
    /// [`spl_calibration`](Self::spl_calibration) to be populated.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sweep_level_db_spl: Option<f32>,
    /// Number of sweeps recorded back-to-back for coherence averaging.
    /// Default 4. Clamped to `[1 .. 8]` at load time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub num_sweeps: Option<u8>,
    /// Coherence threshold below which the GD confidence gate declares
    /// bass phase untrustworthy. Default 0.9. Clamped to `[0.5 .. 0.99]`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub coherence_threshold: Option<f32>,
    /// Centre frequency of the bass tone burst captured by the
    /// BassAnchor wizard step. Default 20.0 Hz (or
    /// `1.25 * min_freq`, whichever is higher).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bass_probe_freq_hz: Option<f32>,
    /// Total length of the steady-state bass-anchor tone in seconds
    /// (steady portion + fades). Default 2.0.
    ///
    /// The pre-v2 schema stored `bass_probe_cycles: u16` here — it's
    /// dropped silently at load (the units differ and converting
    /// requires `bass_probe_freq_hz` which serde sees per-field). The
    /// per-result `BassAnchorResultsLegacy::bass_duration_s` migration
    /// handles legacy run-output files (where the conversion is well
    /// defined).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bass_probe_duration_s: Option<f32>,
    /// Path to the microphone phase calibration CSV (4 columns:
    /// `freq, mag_db, phase_deg, coherence`). Magnitude calibration
    /// already lives under [`mic_calibration_path`](Self::mic_calibration_path).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mic_phase_calibration_path: Option<String>,
    /// Per-channel mic phase calibration files, aligned with
    /// [`mic_calibration_paths`](Self::mic_calibration_paths).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mic_phase_calibration_paths: Option<Vec<Option<String>>>,
    /// SPL calibration anchor captured from a pre-sweep reference tone.
    /// Required on new recordings by the SplCalibration wizard step;
    /// stored here so that replayed recordings can re-derive
    /// `sweep_level_db_spl`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spl_calibration: Option<SplCalibration>,
    /// Deterministic seed for the sweep / probe generators. QA sets it;
    /// the UI hides it. When `None`, the generators use their internal
    /// fixed seed constants.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recording_seed: Option<u64>,
    /// Number of measurement positions (seats) the user captured. `None`
    /// or `Some(1)` means a single-position session; `Some(n)` with
    /// `n >= 2` means each `ChannelMeasurement.multi_mic_measurements`
    /// holds `n * num_mics - 1` entries in `(position, mic)` order
    /// (primary measurement is `(0, 0)`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub num_positions: Option<usize>,
}

/// Serializable mirror of the engine's `ProbeDelayResults`. Kept
/// in-crate (rather than depending on `sotf-engine` or `sotf-player`)
/// so the autoeq crate remains lean. Fields match the engine type
/// 1:1 so round-trip through serde is lossless.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct ProbeResultsLegacy {
    pub channels: Vec<ProbeChannelResultLegacy>,
    pub sample_rate: u32,
    pub alignment_delays_ms: Vec<f64>,
}

/// Per-channel probe result (mirror of `ProbeDelayChannelResult`).
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct ProbeChannelResultLegacy {
    pub channel_name: String,
    pub channel_index: usize,
    pub arrival_ms: f64,
    pub gain_db: f64,
    pub snr_db: f64,
}

/// Per-channel bass-anchor result (mirror of `BassAnchorChannelResult`).
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct BassAnchorChannelResultLegacy {
    /// Channel name (e.g. "L", "R", "Sub").
    pub channel_name: String,
    /// Channel output index used during playback.
    pub channel_index: usize,
    /// Reported phase of the bass tone at the listening position,
    /// degrees in `(−180°, 180°]`, sin-referenced. When a loopback
    /// reference channel was recorded this is the loopback-corrected
    /// acoustic phase (`phase_mic − phase_loopback`); see
    /// `bass_anchor_loopback_phase_deg` for the raw loopback value.
    pub bass_anchor_phase_deg: f64,
    /// Linear magnitude of the lock-in I/Q estimator at
    /// `bass_freq_hz` on the mic. SNR proxy.
    pub bass_anchor_magnitude: f64,
    /// Circular standard deviation of phase across the sub-window
    /// lock-in estimates, in degrees. Values above the
    /// `"bass_anchor_unreliable"` advisory threshold (§2.8, 20°) mean
    /// the GD confidence gate should discard this channel's anchor.
    pub bass_anchor_stability_deg: f64,
    /// Raw loopback reference phase in degrees (sin-referenced).
    /// `None` when no loopback channel was recorded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bass_anchor_loopback_phase_deg: Option<f64>,
    /// Magnitude-squared coherence γ² ∈ [0, 1] between the mic and the
    /// loopback per-window phasors at `bass_freq_hz`. Conventional QA
    /// threshold is γ² > 0.9. `None` when no loopback channel was
    /// recorded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bass_anchor_coherence: Option<f64>,
}

/// Processing mode for the optimization engine
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ProcessingMode {
    /// Low-latency mode (IIR filters only) - < 5ms latency
    #[default]
    #[serde(alias = "iir")]
    LowLatency,
    /// Phase-linear mode (FIR filters only) - High latency allowed
    #[serde(alias = "fir")]
    PhaseLinear,
    /// Hybrid mode (IIR for bass, FIR for mids/highs) - Variable latency
    #[serde(alias = "mixed")]
    Hybrid,
    /// Mixed-phase mode (IIR for minimum-phase + excess phase FIR)
    /// Requires phase data in measurements. Low latency (~10ms).
    MixedPhase,
    /// Warped IIR mode — exports RoomEQ filters as warped biquads using a
    /// Bark-scale lambda. The optimizer currently uses the same biquad
    /// placement/scoring path as low_latency, then serializes the runtime
    /// topology as `warped_biquad`.
    WarpedIir,
    /// Kautz modal mode — pole-tuned filter targeting detected room modes.
    /// Uses room mode analysis to place filter poles at resonance frequencies.
    /// Gain optimization via linear least-squares (very fast, no DE needed).
    /// Exports the runtime topology as `kautz_filter` with modal sections.
    /// Best for small, highly resonant rooms with clear modal problems.
    /// Returns an error if no room modes are detected.
    KautzModal,
}

/// Strategy for subwoofer optimization
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum SubwooferStrategy {
    /// Single subwoofer optimization (default)
    #[default]
    Single,
    /// Multi-Sub Optimizer (minimize seat-to-seat variance)
    Mso,
    /// Double Bass Array (active cancellation)
    Dba,
}

/// System topology model
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Default)]
#[serde(rename_all = "snake_case")]
pub enum SystemModel {
    Stereo,
    HomeCinema,
    #[default]
    Custom,
}

/// Target response shape preset
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum TargetShape {
    /// Flat in-room response (no tilt)
    #[default]
    Flat,
    /// Harman preferred in-room curve (-0.8 dB/octave from 1 kHz reference)
    Harman,
    /// Custom slope specified by `slope_db_per_octave`
    Custom,
    /// Load target curve from external CSV file (`curve_path` must be set)
    File,
    /// Derive slope from the input measurement curve at optimization time
    FromMeasurement,
}

/// Highpass filter type for excursion protection
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum HighpassType {
    /// Linkwitz-Riley (4th order = 24dB/oct)
    #[default]
    LinkwitzRiley,
    /// Butterworth
    Butterworth,
}

/// Strategy for multi-seat optimization
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum MultiSeatStrategy {
    /// Minimize standard deviation across all seats (default)
    #[default]
    MinimizeVariance,
    /// Optimize for primary seat with constraints on others
    PrimaryWithConstraints,
    /// Optimize for average response across all seats
    Average,
    /// Complex modal-basis sound-field management across seats
    ModalBasis,
    /// Continuous listening-area prior: integrate the variance / mean / worst-case
    /// objective over a probability density over positions, instead of the
    /// discrete seat slots. Requires `MultiSeatConfig::continuous_area` to be set.
    ContinuousArea,
}

/// Correction mode for CEA2034 speaker pre-correction
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Cea2034CorrectionMode {
    /// Correct Listening Window toward flat (best for nearfield <2m)
    Flat,
    /// Unsupported in roomeq; Harman speaker score is anechoic-only
    Score,
    /// Auto-select the supported roomeq pre-correction from listening distance
    #[default]
    Auto,
}

/// Subwoofer system configuration (part of SystemConfig)
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SubwooferSystemConfig {
    /// Strategy for subwoofer optimization
    #[serde(default)]
    pub config: SubwooferStrategy,
    /// Crossover reference key (points to entry in `crossovers` map)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub crossover: Option<String>,
    /// Mapping of subwoofer measurement key to main speaker logical role
    #[serde(flatten)]
    pub mapping: HashMap<String, String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum BassHeadroomModelKind {
    CinemaCorrelated,
}

/// Naming convention for supporting-source physical outputs.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SupportingSourceOutputNaming {
    /// Suffix appended to the logical role for the supporting output.
    /// Default: "_support".
    #[serde(default = "default_supporting_source_suffix")]
    pub suffix: String,
}

impl Default for SupportingSourceOutputNaming {
    fn default() -> Self {
        Self {
            suffix: default_supporting_source_suffix(),
        }
    }
}

fn default_supporting_source_suffix() -> String {
    "_support".to_string()
}

/// Explicit system configuration mapping logical roles to measurements
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
pub struct SystemConfig {
    /// System topology model
    #[serde(default)]
    pub model: SystemModel,
    /// Map of logical role to measurement key
    pub speakers: HashMap<String, String>,
    /// Subwoofer configuration and mapping
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subwoofers: Option<SubwooferSystemConfig>,
    /// Home-cinema bass-management policy.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bass_management: Option<BassManagementConfig>,
    /// Naming convention for supporting-source physical outputs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supporting_source_outputs: Option<SupportingSourceOutputNaming>,
}

/// Crossover configuration
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CrossoverConfig {
    /// Crossover type (e.g. "LR24", "LR48", "Butterworth24", "LinearPhase")
    #[serde(rename = "type")]
    pub crossover_type: String,
    /// Crossover frequency in Hz (for 2-way speakers)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub frequency: Option<f64>,
    /// Crossover frequencies in Hz (for 3-way and above)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub frequencies: Option<Vec<f64>>,
    /// Frequency range for automatic optimization
    #[serde(skip_serializing_if = "Option::is_none")]
    pub frequency_range: Option<(f64, f64)>,
}

/// Target curve configuration
#[derive(Debug, Clone, JsonSchema)]
#[schemars(with = "String")]
pub enum TargetCurveConfig {
    /// Predefined target (e.g. "flat", "harman")
    Predefined(String),
    /// Path to CSV file (freq, spl columns)
    Path(PathBuf),
}

impl Serialize for TargetCurveConfig {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Self::Predefined(name) => serializer.serialize_str(name),
            Self::Path(path) => serializer.serialize_str(&path.to_string_lossy()),
        }
    }
}

impl<'de> Deserialize<'de> for TargetCurveConfig {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        match value.as_str() {
            // These names are deliberate public RoomEQ targets. Every other
            // string is a CSV path, so a typo cannot silently select flat.
            "flat"
            | "harman"
            | "Listening Window"
            | "Sound Power"
            | "Early Reflections"
            | "Estimated In-Room Response" => Ok(Self::Predefined(value)),
            _ => Ok(Self::Path(PathBuf::from(value))),
        }
    }
}

/// FIR filter configuration
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct FirConfig {
    /// Number of taps (coefficients)
    #[serde(default = "default_fir_taps")]
    pub taps: usize,
    /// Phase response type: "linear", "minimum", or "kirkeby"
    #[serde(default = "default_fir_phase")]
    pub phase: String,
    /// Whether to correct excess phase (only applies to kirkeby mode)
    #[serde(default)]
    pub correct_excess_phase: bool,
    /// Phase smoothing width in octaves (default: 0.167 = 1/6 octave)
    #[serde(default = "default_phase_smoothing")]
    pub phase_smoothing: f64,
    /// Maximum per-frequency correction boost in dB. When set, the
    /// target-vs-measurement delta is clamped to at most this many dB of
    /// boost before the FIR is designed, mirroring the runtime acceptance
    /// policy's `max_boost_db` guard. `None` keeps the uncapped behavior.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_boost_db: Option<f64>,
    /// Pre-ringing suppression configuration
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pre_ringing: Option<PreRingingSerdeConfig>,
}

impl Default for FirConfig {
    fn default() -> Self {
        Self {
            taps: default_fir_taps(),
            phase: default_fir_phase(),
            correct_excess_phase: false,
            phase_smoothing: default_phase_smoothing(),
            pre_ringing: None,
            max_boost_db: None,
        }
    }
}

/// Serializable pre-ringing configuration for JSON config files
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PreRingingSerdeConfig {
    /// Maximum pre-ringing level in dB relative to main tap. Default: -30.0
    #[serde(default = "default_pre_ringing_threshold")]
    pub threshold_db: f64,
    /// Maximum pre-ringing time in seconds. Default: 0.005 (5 ms)
    #[serde(default = "default_pre_ringing_time")]
    pub max_time_s: f64,
}

/// Serializable mixed-phase correction configuration for JSON config files
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct MixedPhaseSerdeConfig {
    /// Maximum FIR length in milliseconds for excess phase correction. Default: 10.0
    #[serde(default = "default_mixed_phase_fir_length")]
    pub max_fir_length_ms: f64,
    /// Pre-ringing threshold in dB. Default: -30.0
    #[serde(default = "default_pre_ringing_threshold")]
    pub pre_ringing_threshold_db: f64,
    /// Minimum spatial correction depth for excess phase correction. Default: 0.5
    #[serde(default = "default_mixed_phase_spatial_depth")]
    pub min_spatial_depth: f64,
    /// Phase smoothing width in octaves. Default: 1/6 octave
    #[serde(default = "default_mask_smoothing")]
    pub phase_smoothing_octaves: f64,
}

/// Multi-seat measurement configuration
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct MultiSeatMeasurement {
    /// Name of this multi-seat configuration
    pub name: String,
    /// Measurements at each seat position
    pub seat_measurements: Vec<MeasurementSource>,
}

/// Serializable smoothness-penalty configuration for JSON config files.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SmoothnessPenaltyConfigSerde {
    /// Penalty weight in loss units per (dB/decade^2)^exponent.
    #[serde(default)]
    pub tv2_weight: f64,
    /// Optional Schroeder cutoff in Hz for reduced modal-region penalty.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schroeder_hz: Option<f64>,
    /// Multiplier below `schroeder_hz` (0 = modal region exempt).
    #[serde(default = "default_modal_weight_scale")]
    pub modal_weight_scale: f64,
    /// L_p exponent. 1.0 = TV^2-like sparse curvature, 2.0 = L2 smoothing.
    #[serde(default = "default_smoothness_exponent")]
    pub exponent: f64,
}

/// Measurement of inter-channel SPL consistency after optimization
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct InterChannelDeviation {
    /// Per-frequency max deviation (freq_hz, spread_db)
    pub deviation_per_freq: Vec<(f64, f64)>,
    /// RMS of deviation in the midrange (200-4000 Hz)
    pub midrange_rms_db: f64,
    /// RMS of deviation from F3 to 10 kHz
    pub passband_rms_db: f64,
    /// Maximum single-point deviation in midrange
    pub midrange_peak_db: f64,
    /// Frequency of maximum midrange deviation
    pub midrange_peak_freq: f64,
}

/// Serializable spatial robustness configuration for JSON config files
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SpatialRobustnessSerdeConfig {
    /// Threshold (dB) below which full correction is allowed. Despite the field
    /// name, this is compared against the per-frequency *standard deviation*
    /// across positions, not the variance. Default: 3.0
    #[serde(default = "default_variance_threshold")]
    pub variance_threshold_db: f64,
    /// Transition width (dB) for sigmoid blending. Default: 2.0
    #[serde(default = "default_transition_width")]
    pub transition_width_db: f64,
    /// Minimum correction depth (0.0-1.0). Default: 0.1
    #[serde(default = "default_min_correction_depth")]
    pub min_correction_depth: f64,
    /// Smoothing width in octaves for the correction depth mask. Default: 1/6 octave.
    #[serde(default = "default_mask_smoothing_octaves")]
    pub mask_smoothing_octaves: f64,
}

/// How to scalarise the per-bootstrap-resample losses into one outer-loop loss.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum BootstrapScalarisation {
    /// Pure worst-case: max loss across the B resamples. Most conservative; can be
    /// driven by a single outlier resample.
    #[default]
    WorstCase,
    /// Mean of the worst α-fraction of resamples (CVaR). Smoother, less sensitive
    /// to a single freak resample than `WorstCase`.
    Cvar,
}

/// Probability density shape over positions, JSON-serialisable.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Default)]
#[serde(rename_all = "snake_case", tag = "kind")]
pub enum AreaPriorKind {
    /// Uniform density over the configured `bounds`.
    #[default]
    Uniform,
    /// Axis-aligned Gaussian density. `mean` and `cov_diag` must each have
    /// length equal to the number of dimensions; truncated at ±k·σ.
    Gaussian {
        /// Per-axis means.
        mean: Vec<f64>,
        /// Per-axis variances (must be > 0).
        cov_diag: Vec<f64>,
        /// Truncation in standard deviations. Default 4.0.
        #[serde(default = "default_gaussian_truncation_sigmas")]
        truncation_sigmas: f64,
    },
}

/// How to scalarise per-quadrature-point losses, JSON-serialisable.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Default)]
#[serde(rename_all = "snake_case", tag = "kind")]
pub enum AreaScalarisationKind {
    /// Probability-weighted mean (expected loss over the listening area).
    #[default]
    ExpectedValue,
    /// Worst-case (max) over the area's bounding box. Inner DE search.
    WorstCase {
        /// Inner-search budget. Default 50.
        #[serde(default = "default_area_inner_maxiter")]
        inner_maxiter: usize,
        /// Inner-search seed.
        #[serde(default)]
        inner_seed: u64,
    },
    /// CVaR at level α — mean of the worst α-fraction of points.
    Cvar {
        /// Tail fraction in (0, 1].
        #[serde(default = "default_area_cvar_alpha")]
        alpha: f64,
    },
}

/// Serializable continuous listening-area configuration for JSON config files.
///
/// Drives `MultiSeatStrategy::ContinuousArea`. The optimizer integrates the
/// per-position objective over a continuous prior π(p) defined over a
/// `dimensions`-dimensional axis-aligned box, replacing the discrete seats
/// array with a continuous probability density.
///
/// `bounds.len()` must equal `dimensions`. For Gaussian priors,
/// `mean.len()` and `cov_diag.len()` must also equal `dimensions`.
/// `seat_positions.len()` must equal the number of discrete seats in the
/// calibration `MultiSeatMeasurements` and each row's length must equal
/// `dimensions`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ContinuousListeningAreaConfig {
    /// Number of spatial dimensions (typical: 1 for a couch line, 2 for an
    /// MLP rectangle, 3 for a head-volume sweep). Currently 1, 2, and 3 are
    /// supported by the runtime dispatcher.
    pub dimensions: usize,
    /// Per-axis bounding-box bounds `(lo, hi)`. Always required; even for
    /// Gaussian priors the bounds determine the truncation rectangle.
    pub bounds: Vec<(f64, f64)>,
    /// Spatial coordinates of each calibration seat in
    /// `MultiSeatMeasurements`. Outer length = number of seats, inner length =
    /// `dimensions`. Order must match the seat index in the measurements.
    pub seat_positions: Vec<Vec<f64>>,
    /// Probability density shape.
    #[serde(default)]
    pub prior: AreaPriorKind,
    /// Quadrature scheme.
    #[serde(default)]
    pub quadrature: AreaQuadratureKind,
    /// How to scalarise the Q per-point losses.
    #[serde(default)]
    pub scalarisation: AreaScalarisationKind,
    /// IDW power exponent for spatial interpolation (default 2.0).
    #[serde(default = "default_idw_power")]
    pub idw_power: f64,
}

/// Product-level perceptual policy preset.
///
/// Policies fill in coherent defaults for the lower-level RoomEQ knobs. Omitted
/// policies preserve the historical optimizer defaults.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum PerceptualPolicyPreset {
    /// Conservative reference correction with strong early-cue preservation.
    #[default]
    Reference,
    /// Music listening target with broad in-room tilt and robust LF correction.
    Music,
    /// Home-cinema target policy with role-aware dialog and X-curve shaping.
    Cinema,
    /// Quiet-listening policy with headroom/bass restraint and dialog emphasis.
    Night,
    /// Speech-intelligibility policy with stronger dialog-band correction.
    Speech,
}

fn default_timbre_improvement_db() -> f64 {
    0.05
}

fn default_height_match_timbre() -> bool {
    true
}

fn default_height_match_level() -> bool {
    true
}

fn default_height_match_arrival() -> bool {
    true
}

fn default_height_max_delay_ms() -> f64 {
    20.0
}

/// Broadband timbre matching between corrected channels.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct InterChannelTimbreMatchingConfig {
    /// Enable inter-channel timbre matching.
    #[serde(default)]
    pub enabled: bool,
    /// Reference channel name (e.g. "Center" or "Left").
    pub reference_channel: String,
    /// Minimum reduction in normalized timbre spread required before applying DSP.
    #[serde(default = "default_timbre_improvement_db")]
    pub min_improvement_db: f64,
}

impl Default for InterChannelTimbreMatchingConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            reference_channel: String::new(),
            min_improvement_db: default_timbre_improvement_db(),
        }
    }
}

/// Role-aware alignment policy for overhead/height channels.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct HeightChannelAlignmentConfig {
    #[serde(default)]
    pub enabled: bool,
    /// Optional reference overrides keyed by height channel name or role group
    /// (`top_front`, `top_middle`, or `top_rear`).
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub reference_channels: HashMap<String, String>,
    #[serde(default = "default_height_match_timbre")]
    pub match_timbre: bool,
    #[serde(default = "default_height_match_level")]
    pub match_level: bool,
    #[serde(default = "default_height_match_arrival")]
    pub match_arrival_time: bool,
    /// Require candidate DSP not to worsen phase consistency when trustworthy
    /// phase and coherence are available. This is an optional safety gate, not
    /// a standalone correction objective.
    #[serde(default)]
    pub match_phase: bool,
    #[serde(default = "default_timbre_improvement_db")]
    pub min_timbre_improvement_db: f64,
    #[serde(default = "default_height_max_delay_ms")]
    pub max_delay_ms: f64,
}

impl Default for HeightChannelAlignmentConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            reference_channels: HashMap::new(),
            match_timbre: true,
            match_level: true,
            match_arrival_time: true,
            match_phase: false,
            min_timbre_improvement_db: default_timbre_improvement_db(),
            max_delay_ms: default_height_max_delay_ms(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CtcHeadPositionConfig {
    pub id: String,
    #[serde(default)]
    pub x: f64,
    #[serde(default)]
    pub y: f64,
    #[serde(default)]
    pub z: f64,
    #[serde(default)]
    pub yaw_deg: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CtcMeasurementFileConfig {
    pub head_position: String,
    pub speaker: String,
    /// Processed/deconvolved two-channel ear IR WAV.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ir: Option<PathBuf>,
    /// Raw recorded two-ear sweep WAV. Channel 1 = left ear, channel 2 = right ear.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub raw_sweep: Option<PathBuf>,
    /// Raw loopback/reference recording WAV used to align the take.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub loopback: Option<PathBuf>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CtcHrtfSpeakerConfig {
    pub speaker: String,
    pub azimuth_deg: f64,
    #[serde(default)]
    pub elevation_deg: f64,
    #[serde(default = "default_ctc_hrtf_distance_m")]
    pub distance_m: f64,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn supporting_source_output_naming_default_suffix() {
        let naming = SupportingSourceOutputNaming::default();
        assert_eq!(naming.suffix, "_support");
    }

    #[test]
    fn supporting_source_output_naming_json_roundtrip() {
        let naming = SupportingSourceOutputNaming {
            suffix: "_room".to_string(),
        };
        let json = serde_json::to_string(&naming).unwrap();
        assert!(json.contains("_room"));
        let back: SupportingSourceOutputNaming = serde_json::from_str(&json).unwrap();
        assert_eq!(back.suffix, "_room");
    }

    #[test]
    fn supporting_source_output_naming_deserializes_default() {
        let back: SupportingSourceOutputNaming = serde_json::from_str("{}").unwrap();
        assert_eq!(back.suffix, "_support");
    }
}