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
use super::audibility_deadband_config::AudibilityDeadbandConfig;
use super::auto_optimizer_config::AutoOptimizerConfig;
use super::cea2034_correction_config::Cea2034CorrectionConfig;
use super::channel_matching_config::ChannelMatchingConfig;
use super::decomposed_correction_serde_config::DecomposedCorrectionSerdeConfig;
use super::decomposed_correction_serde_config::decomposed_correction_is_default;
use super::default::default_algorithm;
use super::default::default_asymmetric_loss;
use super::default::default_atolerance;
use super::default::default_elimination_threshold;
use super::default::default_local_algo;
use super::default::default_loss_type;
use super::default::default_max_db;
use super::default::default_max_freq;
use super::default::default_max_iter;
use super::default::default_max_q;
use super::default::default_min_db;
use super::default::default_min_filter_improvement;
use super::default::default_min_freq;
use super::default::default_min_q;
use super::default::default_num_filters;
use super::default::default_peq_model;
use super::default::default_population;
use super::default::default_psychoacoustic;
use super::default::default_refine;
use super::default::default_smooth_n;
use super::default::default_strategy;
use super::default::default_tolerance;
use super::early_late_correction_config::EarlyLateCorrectionConfig;
use super::excursion_protection_config::ExcursionProtectionConfig;
use super::group_delay_optimization_config::GroupDelayOptimizationConfig;
use super::high_frequency_correction_config::HighFrequencyCorrectionConfig;
use super::mixed_mode_config::MixedModeConfig;
use super::multi_measurement_config::MultiMeasurementConfig;
use super::multi_seat_config::MultiSeatConfig;
use super::perceptual_policy_config::PerceptualPolicyConfig;
use super::phase_alignment_config::PhaseAlignmentConfig;
use super::policy::policy_asymmetric_loss;
use super::policy::policy_audibility_deadband;
use super::policy::policy_decomposed_correction;
use super::policy::policy_early_late_correction;
use super::policy::policy_high_frequency_guard;
use super::policy::policy_multi_measurement;
use super::policy::policy_psychoacoustic_smoothing;
use super::policy::policy_smoothness_penalty;
use super::policy::policy_target_response;
use super::schroeder_split_config::SchroederSplitConfig;
use super::sub_optimizer_config::SubOptimizerConfig;
use super::target_response_config::TargetResponseConfig;
use super::types::FirConfig;
use super::types::MixedPhaseSerdeConfig;
use super::types::PerceptualPolicyPreset;
use super::types::ProcessingMode;
use super::types::SmoothnessPenaltyConfigSerde;
use super::types::{HeightChannelAlignmentConfig, InterChannelTimbreMatchingConfig};
use super::validation_bundle_config::ValidationBundleConfig;
use crate::{AsymmetricLossConfig, EpaConfig, PsychoacousticSmoothingConfig};
use schemars::JsonSchema;
use serde::{Deserialize, Deserializer, Serialize, de};

fn reject_removed_vog_alias<'de, D>(_: D) -> Result<Option<()>, D::Error>
where
    D: Deserializer<'de>,
{
    Err(de::Error::custom(
        "optimizer.vog was removed; use optimizer.inter_channel_timbre_matching",
    ))
}

/// Optimizer configuration
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct OptimizerConfig {
    /// Processing mode — selects the filter class used for correction.
    #[serde(default, alias = "mode")]
    pub processing_mode: ProcessingMode,
    /// FIR configuration (used when `processing_mode` requires FIR filters)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fir: Option<FirConfig>,
    /// Mixed mode configuration (frequency-based crossover)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mixed_config: Option<MixedModeConfig>,
    /// Mixed-phase correction configuration
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mixed_phase: Option<MixedPhaseSerdeConfig>,
    /// Standalone phase correction (rePhase-style)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub phase_correction: Option<MixedPhaseSerdeConfig>,
    /// Loss function type. Supported values:
    /// - `"flat"` — minimize deviation from target (default)
    /// - `"score"` — maximize Harman/Olive preference score
    /// - `"epa"` — EPA (Evaluation/Potency/Activity) psychoacoustic
    ///   loss combining spectral flatness with sharpness, roughness,
    ///   and loudness-balance penalties derived from Zwicker metrics.
    ///   When selected, the EPA penalty weights can be customized via
    ///   the [`epa_config`](Self::epa_config) field; otherwise the
    ///   defaults from [`EpaConfig::default`](crate::loss::epa::score::EpaConfig::default)
    ///   are used.
    #[serde(default = "default_loss_type")]
    pub loss_type: String,
    /// EPA diagnostic settings and spectral-flatness blend; optimizer use is
    /// limited to the active flatness term when `loss_type == "epa"`.
    /// When `None`, the optimizer falls back to
    /// [`EpaConfig::default`](crate::loss::epa::score::EpaConfig::default).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub epa_config: Option<EpaConfig>,
    /// Optimization algorithm
    #[serde(default = "default_algorithm")]
    pub algorithm: String,
    /// DE mutation strategy (e.g. "currenttobest1bin", "lshade", "best1bin")
    #[serde(default = "default_strategy")]
    pub strategy: String,
    /// Maximum number of PEQ filters per channel
    #[serde(default = "default_num_filters")]
    pub num_filters: usize,
    /// Minimum loss improvement to justify adding another filter
    #[serde(default = "default_min_filter_improvement")]
    pub min_filter_improvement: f64,
    /// Backward elimination threshold
    #[serde(default = "default_elimination_threshold")]
    pub elimination_threshold: f64,
    /// Minimum Q factor
    #[serde(default = "default_min_q")]
    pub min_q: f64,
    /// Maximum Q factor
    #[serde(default = "default_max_q")]
    pub max_q: f64,
    /// Minimum gain in dB
    #[serde(default = "default_min_db")]
    pub min_db: f64,
    /// Maximum gain in dB
    #[serde(default = "default_max_db")]
    pub max_db: f64,
    /// Minimum frequency in Hz
    #[serde(default = "default_min_freq")]
    pub min_freq: f64,
    /// Maximum frequency in Hz
    #[serde(default = "default_max_freq")]
    pub max_freq: f64,
    /// Maximum number of iterations
    #[serde(default = "default_max_iter")]
    pub max_iter: usize,
    /// Population size for population-based optimizers
    #[serde(default = "default_population")]
    pub population: usize,
    /// PEQ model (e.g. "pk", "ls-pk-hs", "free")
    #[serde(default = "default_peq_model")]
    pub peq_model: String,
    /// Random seed for reproducible results (None for random)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seed: Option<u64>,
    /// Number of threads for parallel objective evaluation. `None` uses all
    /// available cores. Note that a fixed seed only gives bit-reproducible
    /// results when this is pinned (1 = fully deterministic): parallel
    /// evaluation order otherwise depends on machine load.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parallel_threads: Option<usize>,
    /// Whether to run local refinement after global optimization
    #[serde(default = "default_refine")]
    pub refine: bool,
    /// Local optimizer algorithm for refinement stage
    #[serde(default = "default_local_algo")]
    pub local_algo: String,
    /// Bayesian optimization Sobol hot-start samples. `None` uses an automatic default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bo_initial_samples: Option<usize>,
    /// Bayesian optimization batch size. `None` uses the backend default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bo_batch_size: Option<usize>,
    /// Posterior standard-deviation threshold for BO local-refiner handoff.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bo_posterior_std_threshold: Option<f64>,
    /// Bayesian optimization acquisition: `"ei"`, `"qei"`, or `"thompson"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bo_acquisition: Option<String>,
    /// Use Monte-Carlo qEHVI Bayesian optimization for multi-objective data.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bo_ehvi: Option<bool>,
    /// Enable psychoacoustic preprocessing
    #[serde(default = "default_psychoacoustic")]
    pub psychoacoustic: bool,
    /// Psychoacoustic variable-smoothing settings. `None` preserves the built-in default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub psychoacoustic_smoothing: Option<PsychoacousticSmoothingConfig>,
    /// Loss function smoothing resolution as 1/N octave
    #[serde(default = "default_smooth_n")]
    pub smooth_n: usize,
    /// Enable asymmetric loss (peaks penalized 2x more than dips)
    #[serde(default = "default_asymmetric_loss")]
    pub asymmetric_loss: bool,
    /// Asymmetric loss weights. `None` preserves the built-in default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub asymmetric_loss_config: Option<AsymmetricLossConfig>,
    /// Product-level perceptual policy preset. When omitted, legacy optimizer
    /// defaults are preserved.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub perceptual_policy: Option<PerceptualPolicyConfig>,
    /// Heuristic deadband for spectral residual objectives. Thresholds are
    /// optimizer tuning values rather than literal psychoacoustic JNDs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub audibility_deadband: Option<AudibilityDeadbandConfig>,
    /// Safeguards for high-frequency correction above the conservative range.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub high_frequency_correction: Option<HighFrequencyCorrectionConfig>,
    /// Direct/early/late correction-energy report settings.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub early_late_correction: Option<EarlyLateCorrectionConfig>,
    /// Validation/listening-test descriptor generation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub validation_bundle: Option<ValidationBundleConfig>,
    /// Optimization convergence tolerance (relative)
    #[serde(default = "default_tolerance")]
    pub tolerance: f64,
    /// Optimization convergence tolerance (absolute)
    #[serde(default = "default_atolerance")]
    pub atolerance: f64,
    /// Allow inter-speaker delay optimization
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub allow_delay: Option<bool>,
    /// Unified target response configuration (shape + preference shelves + broadband pre-correction)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_response: Option<TargetResponseConfig>,
    /// Excursion protection configuration
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub excursion_protection: Option<ExcursionProtectionConfig>,
    /// Schroeder frequency split configuration
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schroeder_split: Option<SchroederSplitConfig>,
    /// Automatic selection of filter count and optimizer bounds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auto_optimizer: Option<AutoOptimizerConfig>,
    /// Smoothness regularizer on the correction curve.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub smoothness_penalty: Option<SmoothnessPenaltyConfigSerde>,
    /// Phase alignment configuration for subwoofer integration
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub phase_alignment: Option<PhaseAlignmentConfig>,
    /// Group-delay optimization configuration. Disabled by default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub group_delay: Option<GroupDelayOptimizationConfig>,
    /// Multi-seat optimization configuration
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub multi_seat: Option<MultiSeatConfig>,
    /// Inter-channel timbre matching configuration.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub inter_channel_timbre_matching: Option<InterChannelTimbreMatchingConfig>,
    /// Role-aware overhead/height-channel alignment.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub height_channel_alignment: Option<HeightChannelAlignmentConfig>,
    /// Deserialization tombstone for the removed `optimizer.vog` alias.
    #[doc(hidden)]
    #[serde(
        default,
        rename = "vog",
        skip_serializing,
        deserialize_with = "reject_removed_vog_alias"
    )]
    #[schemars(skip)]
    pub removed_vog_alias: Option<()>,
    /// Multi-measurement optimization configuration
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub multi_measurement: Option<MultiMeasurementConfig>,
    /// Decomposed correction configuration
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub decomposed_correction: Option<DecomposedCorrectionSerdeConfig>,
    /// CEA2034 speaker pre-correction configuration
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cea2034_correction: Option<Cea2034CorrectionConfig>,
    /// Subwoofer-specific optimizer overrides
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sub_config: Option<SubOptimizerConfig>,
    /// Inter-channel consistency correction configuration
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub channel_matching: Option<ChannelMatchingConfig>,
    /// Runtime-only: path to a measured room impulse response WAV file
    #[serde(skip)]
    pub ssir_wav_path: Option<std::path::PathBuf>,
    /// Frequency-dependent maximum boost envelope.
    /// Each entry is (frequency_hz, max_boost_db).
    /// Between points, linear interpolation in log-frequency.
    /// Default: None (use the existing flat `max_db` limit).
    /// When set, overrides `max_db` on a per-frequency basis.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_boost_envelope: Option<Vec<(f64, f64)>>,

    /// Optional frequency-dependent minimum-cut safety envelope.
    /// Each entry is (frequency_hz, max_cut_db), where max_cut_db is negative.
    /// Default: None (use the existing flat `min_db` limit).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_cut_envelope: Option<Vec<(f64, f64)>>,

    /// Runtime-only: system-wide slope (dB/octave) resolved once for
    /// `TargetShape::FromMeasurement`. When `Some`, every channel reuses
    /// this slope instead of re-running the regression on its own curve.
    /// Lifted to room level so that band-limited channels (LFE, sub) do
    /// not derive a junk slope from their own rolled-off skirts.
    #[serde(skip)]
    pub from_measurement_slope_override: Option<f64>,
}

impl Default for OptimizerConfig {
    fn default() -> Self {
        Self {
            loss_type: default_loss_type(),
            algorithm: default_algorithm(),
            strategy: default_strategy(),
            num_filters: default_num_filters(),
            min_filter_improvement: default_min_filter_improvement(),
            elimination_threshold: default_elimination_threshold(),
            min_q: default_min_q(),
            max_q: default_max_q(),
            min_db: default_min_db(),
            max_db: default_max_db(),
            min_freq: default_min_freq(),
            max_freq: default_max_freq(),
            max_iter: default_max_iter(),
            population: default_population(),
            peq_model: default_peq_model(),
            processing_mode: ProcessingMode::LowLatency,
            fir: None,
            mixed_config: None,
            mixed_phase: None,
            phase_correction: None,
            seed: None,
            parallel_threads: None,
            refine: default_refine(),
            local_algo: default_local_algo(),
            bo_initial_samples: None,
            bo_batch_size: None,
            bo_posterior_std_threshold: None,
            bo_acquisition: None,
            bo_ehvi: None,
            psychoacoustic: default_psychoacoustic(),
            psychoacoustic_smoothing: None,
            smooth_n: default_smooth_n(),
            asymmetric_loss: default_asymmetric_loss(),
            asymmetric_loss_config: None,
            perceptual_policy: None,
            audibility_deadband: None,
            high_frequency_correction: None,
            early_late_correction: None,
            validation_bundle: None,
            tolerance: default_tolerance(),
            atolerance: default_atolerance(),
            allow_delay: None,
            target_response: None,
            excursion_protection: None,
            schroeder_split: None,
            auto_optimizer: None,
            smoothness_penalty: None,
            phase_alignment: None,
            group_delay: None,
            multi_seat: None,
            inter_channel_timbre_matching: None,
            height_channel_alignment: None,
            removed_vog_alias: None,
            multi_measurement: None,
            decomposed_correction: None,
            cea2034_correction: None,
            sub_config: None,
            channel_matching: None,
            ssir_wav_path: None,
            max_boost_envelope: None,
            min_cut_envelope: None,
            epa_config: None,
            from_measurement_slope_override: None,
        }
    }
}

impl OptimizerConfig {
    /// Resolve psychoacoustic smoothing settings, falling back to the historical
    /// 1/48 octave below 100 Hz through 1/6 octave above 1 kHz curve.
    pub fn psychoacoustic_smoothing_config(&self) -> PsychoacousticSmoothingConfig {
        self.psychoacoustic_smoothing.unwrap_or_default()
    }

    /// Resolve asymmetric loss weights, falling back to the historical peak/dip
    /// weighting.
    pub fn asymmetric_loss_config(&self) -> AsymmetricLossConfig {
        self.asymmetric_loss_config.unwrap_or_default()
    }

    /// Resolve the active audibility deadband, including the extra treble
    /// threshold requested by the high-frequency guard when correction extends
    /// above its start frequency.
    pub fn audibility_deadband_config(&self) -> Option<AudibilityDeadbandConfig> {
        let mut cfg = self.audibility_deadband?;
        if let Some(hf) = self.high_frequency_correction
            && hf.enabled
            && self.max_freq > hf.start_hz
        {
            cfg.treble_db = cfg.treble_db.max(cfg.mid_db + hf.extra_deadband_db);
        }
        cfg.enabled.then_some(cfg)
    }

    /// Resolve direct/early/late correction-report settings. Policies enable
    /// this by default; absent config keeps legacy output compact.
    pub fn early_late_correction_config(&self) -> Option<EarlyLateCorrectionConfig> {
        self.early_late_correction.filter(|cfg| cfg.enabled)
    }

    /// Resolve validation bundle generation settings.
    pub fn validation_bundle_config(&self) -> Option<ValidationBundleConfig> {
        self.validation_bundle.filter(|cfg| cfg.enabled)
    }

    /// Apply product-level perceptual policy defaults to this optimizer config.
    ///
    /// The overlay fills optional lower-level knobs and primitive values that
    /// are still at historical defaults. Explicit user overrides are preserved
    /// unless `perceptual_policy.override_existing` is true.
    pub fn apply_perceptual_policy_defaults(&mut self) {
        let Some(policy) = self.perceptual_policy else {
            return;
        };
        if !policy.apply_defaults {
            return;
        }

        let preset = policy.preset;
        let override_existing = policy.override_existing;
        let smoothing_was_missing = self.psychoacoustic_smoothing.is_none();

        if override_existing || self.loss_type == default_loss_type() {
            self.loss_type = match preset {
                PerceptualPolicyPreset::Reference => "flat",
                PerceptualPolicyPreset::Music
                | PerceptualPolicyPreset::Cinema
                | PerceptualPolicyPreset::Night
                | PerceptualPolicyPreset::Speech => "epa",
            }
            .to_string();
        }

        if override_existing || self.target_response.is_none() {
            self.target_response = Some(policy_target_response(preset));
        }
        if override_existing || self.multi_measurement.is_none() {
            self.multi_measurement = Some(policy_multi_measurement(preset));
        }
        if override_existing
            || self
                .decomposed_correction
                .as_ref()
                .map(decomposed_correction_is_default)
                .unwrap_or(true)
        {
            self.decomposed_correction = Some(policy_decomposed_correction(preset));
        }
        if override_existing || self.psychoacoustic_smoothing.is_none() {
            self.psychoacoustic_smoothing = Some(policy_psychoacoustic_smoothing(preset));
        }
        if override_existing || self.asymmetric_loss_config.is_none() {
            self.asymmetric_loss_config = Some(policy_asymmetric_loss(preset));
        }
        if override_existing || self.smoothness_penalty.is_none() {
            self.smoothness_penalty = Some(policy_smoothness_penalty(preset));
        }
        if override_existing || self.audibility_deadband.is_none() {
            self.audibility_deadband = Some(policy_audibility_deadband(preset));
        }
        if override_existing || self.high_frequency_correction.is_none() {
            self.high_frequency_correction = Some(policy_high_frequency_guard(preset));
        }
        if override_existing || self.early_late_correction.is_none() {
            self.early_late_correction = Some(policy_early_late_correction(preset));
        }
        if override_existing || self.validation_bundle.is_none() {
            self.validation_bundle = Some(ValidationBundleConfig::default());
        }

        if smoothing_was_missing {
            self.apply_high_frequency_smoothing_guard();
        }
        self.apply_high_frequency_correction_defaults(override_existing);
    }

    /// Apply high-frequency guard defaults when correction extends above the
    /// conservative RoomEQ range. Explicit Q/smoothing overrides are preserved
    /// unless requested by the policy layer.
    pub fn apply_high_frequency_correction_defaults(&mut self, override_existing: bool) {
        let Some(hf) = self.high_frequency_correction else {
            return;
        };
        if !hf.enabled || self.max_freq <= hf.start_hz {
            return;
        }

        if (override_existing || (self.max_q - default_max_q()).abs() < 1e-9)
            && self.max_q > hf.max_q
        {
            self.max_q = hf.max_q.max(self.min_q);
        }

        if override_existing || self.psychoacoustic_smoothing.is_none() {
            self.apply_high_frequency_smoothing_guard();
        }
    }

    pub(super) fn apply_high_frequency_smoothing_guard(&mut self) {
        let Some(hf) = self.high_frequency_correction else {
            return;
        };
        if !hf.enabled || self.max_freq <= hf.start_hz {
            return;
        }

        let mut smoothing = self.psychoacoustic_smoothing_config();
        smoothing.high_freq_n = smoothing.high_freq_n.min(hf.smoothing_n.max(1));
        smoothing.high_freq = smoothing.high_freq.min(hf.start_hz);
        if smoothing.high_freq <= smoothing.low_freq {
            smoothing.low_freq = smoothing.high_freq * 0.5;
        }
        self.psychoacoustic_smoothing = Some(smoothing);
    }

    /// Resolve the effective `allow_delay` value.
    ///
    /// Defaults to `true` whenever `processing_mode` introduces any non-zero
    /// base latency (everything except `LowLatency`). Callers can override
    /// explicitly via the `allow_delay` field.
    pub fn allow_delay(&self) -> bool {
        self.allow_delay.unwrap_or_else(|| {
            self.processing_mode != ProcessingMode::LowLatency
                || self
                    .phase_alignment
                    .as_ref()
                    .is_some_and(|config| config.enabled)
        })
    }

    /// Get the maximum allowed boost at a given frequency.
    /// If `max_boost_envelope` is set, interpolate it in log-frequency space.
    /// Otherwise fall back to `self.max_db`.
    pub fn max_boost_at_freq(&self, freq_hz: f64) -> f64 {
        let envelope = match &self.max_boost_envelope {
            Some(env) if !env.is_empty() => env,
            _ => return self.max_db,
        };

        if freq_hz <= envelope[0].0 {
            return envelope[0].1;
        }
        let last = envelope.len() - 1;
        if freq_hz >= envelope[last].0 {
            return envelope[last].1;
        }

        for i in 0..last {
            let (f0, db0) = envelope[i];
            let (f1, db1) = envelope[i + 1];
            if freq_hz >= f0 && freq_hz <= f1 {
                let t = (freq_hz.ln() - f0.ln()) / (f1.ln() - f0.ln());
                return db0 + t * (db1 - db0);
            }
        }

        self.max_db
    }

    /// Return structural errors for the frequency-dependent gain envelopes.
    ///
    /// Interpolation requires finite positive frequencies in strict ascending
    /// order; validating this in the model keeps every engine caller from
    /// reaching a zero/invalid log-frequency denominator.
    pub fn gain_envelope_errors(&self) -> Vec<String> {
        [
            ("max_boost_envelope", self.max_boost_envelope.as_deref()),
            ("min_cut_envelope", self.min_cut_envelope.as_deref()),
        ]
        .into_iter()
        .filter_map(|(name, envelope)| gain_envelope_error(name, envelope))
        .collect()
    }
}

fn gain_envelope_error(name: &str, envelope: Option<&[(f64, f64)]>) -> Option<String> {
    let envelope = envelope?;
    for &(frequency, gain) in envelope {
        if !frequency.is_finite() || frequency <= 0.0 {
            return Some(format!(
                "{name} frequencies must be finite and positive, got {frequency}"
            ));
        }
        if !gain.is_finite() {
            return Some(format!("{name} gains must be finite, got {gain}"));
        }
    }
    if envelope.windows(2).any(|points| points[0].0 >= points[1].0) {
        return Some(format!(
            "{name} frequencies must be strictly increasing without duplicates"
        ));
    }
    None
}

#[cfg(test)]
mod legacy_alias_tests {
    use super::OptimizerConfig;

    #[test]
    fn removed_vog_alias_is_rejected() {
        let error = serde_json::from_value::<OptimizerConfig>(serde_json::json!({
            "vog": {
                "enabled": true,
                "reference_channel": "left",
                "min_improvement_db": 0.05
            }
        }))
        .unwrap_err();

        assert!(error.to_string().contains("optimizer.vog was removed"));
    }

    #[test]
    fn unrelated_legacy_fields_remain_tolerated() {
        let config = serde_json::from_value::<OptimizerConfig>(serde_json::json!({
            "mode": "iir"
        }))
        .unwrap();

        assert_eq!(
            config.processing_mode,
            OptimizerConfig::default().processing_mode
        );
    }
}