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
//! Simple Wizard preset types for Room EQ.
//!
//! These types encode the guided "Simple Wizard" choices that map to sane
//! optimizer defaults.  They live in autoeq (not the player crate) because
//! the knowledge of what constitutes a good default is optimizer domain
//! knowledge.

use super::config::{
    DecomposedCorrectionSerdeConfig, OptimizerConfig, ProcessingMode, TargetResponseConfig,
    TargetShape,
};

fn canonical_multi_measurement_strategy(strategy: &str) -> Option<&'static str> {
    let normalized = strategy
        .trim()
        .to_ascii_lowercase()
        .replace([' ', '-'], "_")
        .replace(['(', ')'], "");
    match normalized.as_str() {
        "average" | "average_rms" => Some("average"),
        "weighted_sum" => Some("weighted_sum"),
        "minimax" | "minmax" | "minimax_worst_case" => Some("minimax"),
        "variance_penalized" | "minimize_variance" | "variance" => Some("variance_penalized"),
        "spatial_robustness" => Some("spatial_robustness"),
        "minimax_uncertainty" | "minimax_bootstrap_uncertainty" => Some("minimax_uncertainty"),
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// Enums
// ---------------------------------------------------------------------------

/// Listening distance tier used by the Simple Wizard to set the target
/// curve family.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub enum SpeakerTier {
    NearField,
    #[default]
    MidField,
    FarField,
}

impl SpeakerTier {
    pub fn label(&self) -> &'static str {
        match self {
            Self::NearField => "Near-field (<1.5m)",
            Self::MidField => "Mid-field (1.5–3m)",
            Self::FarField => "Far-field (>3m)",
        }
    }

    pub fn all() -> &'static [SpeakerTier] {
        &[Self::NearField, Self::MidField, Self::FarField]
    }
}

/// Simple-mode loss function choice.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub enum SimpleLossChoice {
    #[default]
    Flat,
    Epa,
}

impl SimpleLossChoice {
    pub fn label(&self) -> &'static str {
        match self {
            Self::Flat => "Flat (minimize deviation)",
            Self::Epa => "EPA (perceptual quality)",
        }
    }
}

/// Simple-mode processing capability choice.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub enum SimpleProcessingChoice {
    #[default]
    Iir,
    MixedPhase,
}

impl SimpleProcessingChoice {
    pub fn label(&self) -> &'static str {
        match self {
            Self::Iir => "IIR (low latency)",
            Self::MixedPhase => "Mixed Phase (best quality)",
        }
    }
}

/// Simple-mode crossover choice (shown for 2.1+ configs).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub enum SimpleCrossoverChoice {
    #[default]
    Lr24,
    Lr48,
}

impl SimpleCrossoverChoice {
    pub fn label(&self) -> &'static str {
        match self {
            Self::Lr24 => "Linkwitz-Riley 24 dB/oct",
            Self::Lr48 => "Linkwitz-Riley 48 dB/oct",
        }
    }
}

// ---------------------------------------------------------------------------
// SimplePresetConfig
// ---------------------------------------------------------------------------

/// Collected choices from the Simple Wizard's Configure step.
///
/// [`to_optimizer_config`](Self::to_optimizer_config) translates these
/// directly into an [`OptimizerConfig`] so the optimizer sees a fully
/// populated configuration regardless of which wizard path the user took.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct SimplePresetConfig {
    pub target: SpeakerTier,
    pub loss: SimpleLossChoice,
    pub processing: SimpleProcessingChoice,
    /// Only meaningful for 2.1+ configs.
    pub crossover: SimpleCrossoverChoice,
    /// Only meaningful for 5.0+ or >2 subs.
    pub bass_management: String,
    /// Multi-position strategy (only when multi-position data detected).
    pub multi_position_strategy: String,
}

impl SimplePresetConfig {
    /// Produce a backend [`OptimizerConfig`] directly from the Simple
    /// Wizard choices.
    ///
    /// The returned config uses sensible defaults for every field the
    /// Simple Wizard doesn't expose (num_filters, population, tolerances,
    /// etc.).  Callers can further mutate the result before passing it to
    /// [`optimize_room`](crate::roomeq::optimize_room).
    pub fn to_optimizer_config(&self) -> OptimizerConfig {
        let processing_mode = match self.processing {
            SimpleProcessingChoice::Iir => ProcessingMode::LowLatency,
            SimpleProcessingChoice::MixedPhase => ProcessingMode::MixedPhase,
        };

        let loss_type = match self.loss {
            SimpleLossChoice::Flat => "flat".to_string(),
            SimpleLossChoice::Epa => "epa".to_string(),
        };

        // Target response: use measurement's own broadband slope.
        let target_response = Some(TargetResponseConfig {
            shape: TargetShape::FromMeasurement,
            slope_db_per_octave: 0.0,
            broadband_precorrection: true,
            ..Default::default()
        });

        // Schroeder split: enable when bass management is configured or
        // LR48 crossover is selected.
        let schroeder_split =
            if !self.bass_management.is_empty() || self.crossover == SimpleCrossoverChoice::Lr48 {
                Some(super::config::SchroederSplitConfig {
                    enabled: true,
                    ..Default::default()
                })
            } else {
                None
            };

        // Multi-position measurement strategy
        let multi_measurement = if !self.multi_position_strategy.is_empty() {
            let strategy_key = canonical_multi_measurement_strategy(&self.multi_position_strategy)
                .unwrap_or_else(|| {
                    log::warn!(
                        "Unknown multi_position_strategy '{}'; falling back to average",
                        self.multi_position_strategy
                    );
                    "average"
                });
            let strategy = match strategy_key {
                "average" => super::config::MultiMeasurementStrategy::Average,
                "weighted_sum" => super::config::MultiMeasurementStrategy::WeightedSum,
                "minimax" => super::config::MultiMeasurementStrategy::Minimax,
                "variance_penalized" => super::config::MultiMeasurementStrategy::VariancePenalized,
                "spatial_robustness" => super::config::MultiMeasurementStrategy::SpatialRobustness,
                "minimax_uncertainty" => {
                    super::config::MultiMeasurementStrategy::MinimaxUncertainty
                }
                _ => super::config::MultiMeasurementStrategy::Average,
            };
            Some(super::config::MultiMeasurementConfig {
                strategy,
                weights: None,
                variance_lambda: 0.5,
                spatial_robustness: None,
                bootstrap_uncertainty: None,
                rir_prototype: None,
            })
        } else {
            None
        };

        OptimizerConfig {
            processing_mode,
            loss_type,
            target_response,
            schroeder_split,
            multi_measurement,
            // Sane defaults for fields not exposed in Simple mode
            num_filters: 7,
            algorithm: "autoeq:cmaes".to_string(),
            population: 300,
            max_iter: 50_000,
            min_freq: 20.0,
            max_freq: 1600.0,
            min_db: -12.0,
            max_db: 4.0,
            min_q: 0.5,
            max_q: 6.0,
            peq_model: "pk".to_string(),
            tolerance: 1e-5,
            atolerance: 1e-5,
            psychoacoustic: true,
            asymmetric_loss: true,
            refine: true,
            local_algo: "cobyla".to_string(),
            decomposed_correction: Some(DecomposedCorrectionSerdeConfig::default()),
            ..OptimizerConfig::default()
        }
    }
}

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

    #[test]
    fn test_simple_preset_default_produces_valid_config() {
        let preset = SimplePresetConfig::default();
        let config = preset.to_optimizer_config();
        assert_eq!(config.processing_mode, ProcessingMode::LowLatency);
        assert_eq!(config.loss_type, "flat");
        assert_eq!(config.algorithm, "autoeq:cmaes");
        assert_eq!(config.num_filters, 7);
        assert!(config.target_response.is_some());
        assert!(config.schroeder_split.is_none());
        assert!(config.multi_measurement.is_none());
    }

    #[test]
    fn test_simple_preset_mixed_phase_epa() {
        let preset = SimplePresetConfig {
            processing: SimpleProcessingChoice::MixedPhase,
            loss: SimpleLossChoice::Epa,
            ..Default::default()
        };
        let config = preset.to_optimizer_config();
        assert_eq!(config.processing_mode, ProcessingMode::MixedPhase);
        assert_eq!(config.loss_type, "epa");
    }

    #[test]
    fn test_simple_preset_with_crossover_enables_schroeder() {
        let preset = SimplePresetConfig {
            crossover: SimpleCrossoverChoice::Lr48,
            ..Default::default()
        };
        let config = preset.to_optimizer_config();
        assert!(config.schroeder_split.is_some());
    }

    #[test]
    fn test_simple_preset_with_bass_management_enables_schroeder() {
        let preset = SimplePresetConfig {
            bass_management: "some_config".to_string(),
            ..Default::default()
        };
        let config = preset.to_optimizer_config();
        assert!(config.schroeder_split.is_some());
    }

    #[test]
    fn test_simple_preset_with_multi_position() {
        let preset = SimplePresetConfig {
            multi_position_strategy: "average".to_string(),
            ..Default::default()
        };
        let config = preset.to_optimizer_config();
        assert!(config.multi_measurement.is_some());
    }

    #[test]
    fn test_simple_preset_accepts_multi_position_display_label() {
        let preset = SimplePresetConfig {
            multi_position_strategy: "Minimize Variance".to_string(),
            ..Default::default()
        };
        let config = preset.to_optimizer_config();
        assert_eq!(
            config.multi_measurement.unwrap().strategy,
            super::super::config::MultiMeasurementStrategy::VariancePenalized
        );
    }

    #[test]
    fn test_simple_preset_multi_position_strategies() {
        let strategies = [
            (
                "weighted_sum",
                super::super::config::MultiMeasurementStrategy::WeightedSum,
            ),
            (
                "minimax",
                super::super::config::MultiMeasurementStrategy::Minimax,
            ),
            (
                "minmax",
                super::super::config::MultiMeasurementStrategy::Minimax,
            ),
            (
                "variance_penalized",
                super::super::config::MultiMeasurementStrategy::VariancePenalized,
            ),
            (
                "minimize_variance",
                super::super::config::MultiMeasurementStrategy::VariancePenalized,
            ),
            (
                "spatial_robustness",
                super::super::config::MultiMeasurementStrategy::SpatialRobustness,
            ),
            (
                "minimax_uncertainty",
                super::super::config::MultiMeasurementStrategy::MinimaxUncertainty,
            ),
            (
                "minimax_bootstrap_uncertainty",
                super::super::config::MultiMeasurementStrategy::MinimaxUncertainty,
            ),
        ];
        for (name, expected) in strategies {
            let preset = SimplePresetConfig {
                multi_position_strategy: name.to_string(),
                ..Default::default()
            };
            let config = preset.to_optimizer_config();
            assert_eq!(
                config.multi_measurement.unwrap().strategy,
                expected,
                "strategy '{}' should map to {:?}",
                name,
                expected
            );
        }
    }

    #[test]
    fn test_simple_preset_unknown_multi_position_falls_back() {
        let preset = SimplePresetConfig {
            multi_position_strategy: "not_a_strategy".to_string(),
            ..Default::default()
        };
        let config = preset.to_optimizer_config();
        assert_eq!(
            config.multi_measurement.unwrap().strategy,
            super::super::config::MultiMeasurementStrategy::Average
        );
    }

    #[test]
    fn test_speaker_tier_labels_and_all() {
        assert_eq!(SpeakerTier::NearField.label(), "Near-field (<1.5m)");
        assert_eq!(SpeakerTier::MidField.label(), "Mid-field (1.5–3m)");
        assert_eq!(SpeakerTier::FarField.label(), "Far-field (>3m)");
        assert_eq!(SpeakerTier::all().len(), 3);
    }

    #[test]
    fn test_simple_loss_choice_labels() {
        assert_eq!(SimpleLossChoice::Flat.label(), "Flat (minimize deviation)");
        assert_eq!(SimpleLossChoice::Epa.label(), "EPA (perceptual quality)");
    }

    #[test]
    fn test_simple_processing_choice_labels() {
        assert_eq!(SimpleProcessingChoice::Iir.label(), "IIR (low latency)");
        assert_eq!(
            SimpleProcessingChoice::MixedPhase.label(),
            "Mixed Phase (best quality)"
        );
    }

    #[test]
    fn test_simple_crossover_choice_labels() {
        assert_eq!(
            SimpleCrossoverChoice::Lr24.label(),
            "Linkwitz-Riley 24 dB/oct"
        );
        assert_eq!(
            SimpleCrossoverChoice::Lr48.label(),
            "Linkwitz-Riley 48 dB/oct"
        );
    }
}