secs-types 0.14.1

Shared vocabulary of SECS 2R: domain types, error codes and the IPC request and response types (with generated TypeScript bindings).
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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
//! User-visible calibration settings and their mode-derived engine values.
//!
//! This is the typed form of `calibration.py::CalibrationSettings`. Ordered
//! pairs are used for Python dictionaries so insertion order survives a
//! `.secs` round trip; serde still exposes them as JSON objects.

use std::{collections::BTreeMap, fmt::Write as _};

use serde::{Deserialize, Serialize};
use ts_rs::TS;

use crate::rules::CALIBRATION_LIMITS;

/// The ultra mode's latency budget range (ms).
const ULTRA_MS: (f64, f64) = CALIBRATION_LIMITS.ultra_ms;

fn default_true() -> bool {
    true
}

fn is_true(value: &bool) -> bool {
    *value
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "lowercase")]
#[ts(export)]
pub enum Mode {
    Zero,
    Mixed,
    Linear,
    Ultra,
}

/// Evidence used to choose an automatic room-correction ceiling (ADR 0021).
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub enum RcHiBasis {
    #[default]
    Strict,
    Lenient,
    Agreement,
}

impl RcHiBasis {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Strict => "strict",
            Self::Lenient => "lenient",
            Self::Agreement => "agreement",
        }
    }
}

fn default_rc_hi_transition() -> u8 {
    1
}

/// One extra room-correction band beside `rc_lo..rc_hi`, both edges set by
/// hand (ADR 0024). `20 <= lo_hz < hi_hz <= 20000`.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct RcBand {
    pub lo_hz: f64,
    pub hi_hz: f64,
}

/// The extra bands a calculation may use: finite, inside
/// `CALIBRATION_LIMITS.rc_band` with `lo < hi`, sorted by `lo_hz`, at most
/// `rc_bands_max` (ADR 0024). Settings that did not pass the service's edit
/// checks (a request carrying its own settings) go through this.
pub fn valid_rc_bands(bands: &[RcBand]) -> Vec<RcBand> {
    let limits = crate::rules::CALIBRATION_LIMITS;
    let edge = limits.rc_band.0..=limits.rc_band.1;
    let mut kept: Vec<_> = bands
        .iter()
        .copied()
        .filter(|band| {
            band.lo_hz.is_finite()
                && band.hi_hz.is_finite()
                && edge.contains(&band.lo_hz)
                && edge.contains(&band.hi_hz)
                && band.lo_hz < band.hi_hz
        })
        .collect();
    kept.sort_by(|a, b| {
        a.lo_hz
            .total_cmp(&b.lo_hz)
            .then(a.hi_hz.total_cmp(&b.hi_hz))
    });
    kept.truncate(limits.rc_bands_max.1 as usize);
    kept
}

/// How non-48 kHz measurement responses are prepared for calculation.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub enum SampleRatePolicy {
    /// Preserve the existing validation error for mismatched measurements.
    #[default]
    Reject,
    /// Resample calculation copies to 48 kHz, leaving stored measurements intact.
    Resample,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct SubEntry {
    pub mode: String,
    pub bundle: String,
    pub gain_db: f64,
    pub delay_ms: f64,
    pub polarity: i8,
    pub allpass: Vec<(f64, f64)>,
    pub mimo_support: bool,
    pub hp_hz: f64,
    pub lp_hz: f64,
    pub peq: Vec<(f64, f64, f64)>,
    pub hp_type: String,
    pub lp_type: String,
    pub dba_row: String,
}

impl Default for SubEntry {
    fn default() -> Self {
        Self {
            mode: "auto".into(),
            bundle: "A".into(),
            gain_db: 0.0,
            delay_ms: 0.0,
            polarity: 1,
            allpass: Vec::new(),
            mimo_support: true,
            hp_hz: 0.0,
            lp_hz: 0.0,
            peq: Vec::new(),
            hp_type: "LR24".into(),
            lp_type: "LR24".into(),
            dba_row: "front".into(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct BundleLayoutEntry {
    pub kind: String,
    pub rear_trim_ms: f64,
}

impl Default for BundleLayoutEntry {
    fn default() -> Self {
        Self {
            kind: "values".into(),
            rear_trim_ms: 0.0,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct CalibrationSettings {
    pub mode: Mode,
    #[serde(default)]
    pub sample_rate_policy: SampleRatePolicy,
    #[serde(default)]
    pub low_protect: bool,
    /// Common LF arrival for the mains (ADR 0025); off keeps upstream phase.
    #[serde(default)]
    pub lf_align: bool,
    /// Shorter long-mode decay through pole-replacing cuts (ADR 0025).
    #[serde(default)]
    pub mode_decay: bool,
    /// Unwinds the RC FIR's constant phase above the band (ADR 0030).
    #[serde(default)]
    pub hf_phase: bool,
    pub rc_lo: f64,
    pub rc_hi: Option<f64>,
    #[serde(default)]
    pub rc_hi_basis: RcHiBasis,
    #[serde(default = "default_rc_hi_transition")]
    pub rc_hi_transition: u8,
    /// Extra correction bands, sorted by `lo_hz`, at most four (ADR 0024).
    #[serde(default)]
    pub rc_bands: Vec<RcBand>,
    pub room_volume_m3: Option<f64>,
    pub room_dims_m: Option<[f64; 3]>,
    pub mimo_on: bool,
    pub fsiso: f64,
    pub mimo_low: Option<f64>,
    #[ts(type = "number")]
    pub mimo_max_supports: i64,
    pub mimo_fir: bool,
    /// Experimental: PEQ fits use closed-form Jacobians (results leave SECS 2).
    #[serde(default)]
    pub peq_analytic_derivatives: bool,
    /// Experimental: MIMO IIR fits use closed-form derivatives (results leave SECS 2).
    #[serde(default)]
    pub mimo_iir_analytic_derivatives: bool,
    #[serde(with = "ordered_f64_map")]
    #[ts(as = "BTreeMap<String, f64>")]
    pub xo: Vec<(String, f64)>,
    #[serde(with = "ordered_f64_map")]
    #[ts(as = "BTreeMap<String, f64>")]
    pub xo_rec: Vec<(String, f64)>,
    /// Fingerprint of the inputs used for the stored XO recommendation.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    #[ts(as = "Option<String>", optional)]
    pub xo_rec_key: String,
    /// Recompute the XO recommendation before calibration (ADR 0028).
    #[serde(default = "default_true", skip_serializing_if = "is_true")]
    #[ts(as = "Option<bool>", optional)]
    pub xo_rec_include: bool,
    pub ultra_ms: f64,
    #[serde(with = "ordered_sub_map")]
    #[ts(as = "BTreeMap<String, SubEntry>")]
    pub subs_manual: Vec<(String, SubEntry)>,
    pub sub_main_delay_ms: f64,
    #[serde(with = "ordered_layout_map")]
    #[ts(as = "BTreeMap<String, BundleLayoutEntry>")]
    pub bundle_layouts: Vec<(String, BundleLayoutEntry)>,
    pub infra_boost_max_db: f64,
    pub xo_peq_on: bool,
    pub boost_max_db: f64,
    pub xo_peq_lo: f64,
    pub xo_peq_hi: f64,
}

impl Default for CalibrationSettings {
    fn default() -> Self {
        Self {
            mode: Mode::Mixed,
            sample_rate_policy: SampleRatePolicy::Reject,
            low_protect: false,
            lf_align: false,
            mode_decay: false,
            hf_phase: false,
            rc_lo: 20.0,
            rc_hi: None,
            rc_hi_basis: RcHiBasis::Strict,
            rc_hi_transition: 1,
            rc_bands: Vec::new(),
            room_volume_m3: None,
            room_dims_m: None,
            mimo_on: false,
            fsiso: 150.0,
            mimo_low: None,
            mimo_max_supports: 0,
            // Beta 1.3.0: MIMO supports start as FIR in a new project.
            mimo_fir: true,
            peq_analytic_derivatives: false,
            mimo_iir_analytic_derivatives: false,
            xo: Vec::new(),
            xo_rec: Vec::new(),
            xo_rec_key: String::new(),
            xo_rec_include: true,
            ultra_ms: 200.0,
            subs_manual: Vec::new(),
            sub_main_delay_ms: 0.0,
            bundle_layouts: Vec::new(),
            infra_boost_max_db: 24.0,
            xo_peq_on: true,
            boost_max_db: 10.0,
            xo_peq_lo: 0.0,
            xo_peq_hi: 0.0,
        }
    }
}

impl CalibrationSettings {
    /// Korean user-visible name of the selected calibration mode.
    pub fn label(&self) -> String {
        mode_label(self.mode, Some(self.ultra_ms))
    }

    /// Stable staleness fingerprint with the same inclusions and exclusions as upstream.
    pub fn engine_key(&self) -> String {
        let mut out = String::new();
        write!(&mut out, "{:?}|{}|", self.mode, number(self.rc_lo)).unwrap();
        optional_number(&mut out, self.rc_hi);
        out.push('|');
        optional_number(&mut out, self.room_volume_m3);
        out.push('|');
        sorted_f64_map(&mut out, &self.xo);
        out.push('|');
        if self.mode == Mode::Ultra {
            out.push_str(&number(self.ultra_ms));
        } else {
            out.push('-');
        }
        out.push('|');
        out.push_str(&self.manual_key());
        write!(
            &mut out,
            "|{}|{}|{}|{}|{}",
            number(self.infra_boost_max_db),
            self.xo_peq_on,
            number(self.xo_peq_lo),
            number(self.xo_peq_hi),
            number(self.boost_max_db)
        )
        .unwrap();
        // Preserve upstream keys for strict ×1, including existing caches.
        if self.rc_hi_basis != RcHiBasis::Strict {
            write!(&mut out, "|rc_hi_basis={}", self.rc_hi_basis.as_str()).unwrap();
        }
        if self.rc_hi_transition != 1 {
            write!(&mut out, "|rc_hi_transition={}", self.rc_hi_transition).unwrap();
        }
        // ADR 0024: only a project with extra bands gets a new key. Sorted, so
        // a list the service stored and the same list in another order match.
        if !self.rc_bands.is_empty() {
            let mut bands = self.rc_bands.clone();
            bands.sort_by(|a, b| {
                a.lo_hz
                    .total_cmp(&b.lo_hz)
                    .then(a.hi_hz.total_cmp(&b.hi_hz))
            });
            out.push_str("|rc_bands=");
            for (index, band) in bands.iter().enumerate() {
                if index > 0 {
                    out.push(',');
                }
                write!(&mut out, "{}-{}", number(band.lo_hz), number(band.hi_hz)).unwrap();
            }
        }
        // Keep existing cache fingerprints unchanged for the default policy.
        if self.sample_rate_policy == SampleRatePolicy::Resample {
            out.push_str("|sample_rate_policy=resample");
        }
        if self.low_protect {
            out.push_str("|low_protect");
        }
        if self.lf_align {
            out.push_str("|lf_align");
        }
        if self.mode_decay {
            out.push_str("|mode_decay");
        }
        if self.hf_phase {
            out.push_str("|hf_phase");
        }
        if self.peq_analytic_derivatives {
            out.push_str("|peq_analytic_derivatives");
        }
        out
    }

    /// Stable fingerprint of the sub settings which affect the correction engine.
    pub fn manual_key(&self) -> String {
        let mut entries: Vec<_> = self.subs_manual.iter().collect();
        entries.sort_by(|a, b| a.0.cmp(&b.0));
        let mut out = String::new();
        for (role, entry) in entries {
            let filters = filter_key(entry);
            if entry.mode == "auto" {
                if entry.hp_hz != 0.0 || entry.lp_hz != 0.0 || !entry.peq.is_empty() {
                    write!(&mut out, "{role}:auto:{filters};").unwrap();
                }
                continue;
            }
            let layout = if entry.mode == "bundle" {
                self.bundle_layouts
                    .iter()
                    .find(|(name, _)| name == &entry.bundle)
                    .map_or("values", |(_, layout)| layout.kind.as_str())
            } else {
                "values"
            };
            if layout != "values" {
                let row = if layout == "dba" {
                    entry.dba_row.as_str()
                } else {
                    ""
                };
                let trim = if layout == "dba" {
                    self.bundle_layouts
                        .iter()
                        .find(|(name, _)| name == &entry.bundle)
                        .map_or(0.0, |(_, value)| value.rear_trim_ms)
                } else {
                    0.0
                };
                write!(
                    &mut out,
                    "{role}:bundle:{}:{layout}:{row}:{}:{filters};",
                    entry.bundle,
                    number(trim)
                )
                .unwrap();
            } else {
                let bundle = if entry.mode == "bundle" {
                    entry.bundle.as_str()
                } else {
                    ""
                };
                write!(
                    &mut out,
                    "{role}:{}:{bundle}:{}:{}:{}:",
                    entry.mode,
                    number(entry.gain_db),
                    number(entry.delay_ms),
                    entry.polarity
                )
                .unwrap();
                for &(frequency, q) in &entry.allpass {
                    write!(&mut out, "{},{};", number(frequency), number(q)).unwrap();
                }
                write!(&mut out, ":{filters};").unwrap();
            }
        }
        let fixed = self.subs_manual.iter().any(|(_, e)| e.mode == "fixed");
        if fixed {
            write!(&mut out, "|{}", number(self.sub_main_delay_ms)).unwrap();
        } else {
            out.push_str("|-");
        }
        out
    }

    /// Stable fingerprint of settings used only by MIMO.
    pub fn mimo_key(&self) -> String {
        let mut excluded: Vec<_> = self
            .subs_manual
            .iter()
            .filter(|(_, entry)| !entry.mimo_support)
            .map(|(role, _)| role.as_str())
            .collect();
        excluded.sort_unstable();
        let mut out = format!("{}|", number(self.fsiso));
        optional_number(&mut out, self.mimo_low);
        write!(
            &mut out,
            "|{}|{}|{}",
            excluded.join(","),
            self.mimo_max_supports,
            self.mimo_fir
        )
        .unwrap();
        if self.mimo_iir_analytic_derivatives {
            out.push_str("|mimo_iir_analytic_derivatives");
        }
        out
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ModeParams {
    pub taps: usize,
    pub lift_ms: f64,
    pub peq_bands: Option<usize>,
    pub phase_frac: f64,
    pub max_latency_ms: f64,
}

/// Stable ASCII correction-mode tag used by export names and metadata.
pub fn mode_tag(mode: Mode) -> &'static str {
    match mode {
        Mode::Zero => "zero",
        Mode::Mixed => "mixed",
        Mode::Linear => "linear",
        Mode::Ultra => "ultra",
    }
}

/// Korean user-visible mode name, including the clamped ultra latency when supplied.
pub fn mode_label(mode: Mode, ultra_ms: Option<f64>) -> String {
    let name = match mode {
        Mode::Zero => "최소 지연 모드",
        Mode::Mixed => "저지연 모드",
        Mode::Linear => "표준 모드",
        Mode::Ultra => "초고지연 모드",
    };
    if mode == Mode::Ultra
        && let Some(ms) = ultra_ms
    {
        let (lo, hi) = ULTRA_MS;
        format!("{name} {} ms", python_g(ms.clamp(lo, hi)))
    } else {
        name.into()
    }
}

fn python_g(value: f64) -> String {
    if value == 0.0 {
        return if value.is_sign_negative() { "-0" } else { "0" }.into();
    }
    let mut exponent = value.abs().log10().floor() as i32;
    let places = 5 - exponent;
    let scale = 10_f64.powi(places);
    let rounded = if places >= 0 {
        (value * scale).round_ties_even() / scale
    } else {
        (value / scale.recip()).round_ties_even() * scale.recip()
    };
    if rounded != 0.0 {
        exponent = rounded.abs().log10().floor() as i32;
    }
    if !(-4..6).contains(&exponent) {
        let mut text = format!("{rounded:.5e}");
        let e = text.find('e').expect("scientific format");
        while text[..e].ends_with('0') {
            text.remove(e - 1);
        }
        if text[..text.find('e').unwrap()].ends_with('.') {
            text.remove(text.find('e').unwrap() - 1);
        }
        let e = text.find('e').unwrap();
        let power = text[e + 1..].parse::<i32>().expect("scientific exponent");
        format!(
            "{}e{}{:02}",
            &text[..e],
            if power >= 0 { '+' } else { '-' },
            power.abs()
        )
    } else {
        let places = (5 - exponent).max(0) as usize;
        let mut text = format!("{rounded:.places$}");
        while text.contains('.') && text.ends_with('0') {
            text.pop();
        }
        if text.ends_with('.') {
            text.pop();
        }
        text
    }
}

pub fn mode_params(mode: Mode, ultra_ms: f64) -> ModeParams {
    match mode {
        Mode::Zero => ModeParams {
            taps: 0,
            lift_ms: 0.0,
            peq_bands: Some(32),
            phase_frac: 6.0,
            max_latency_ms: 0.0,
        },
        Mode::Mixed => ModeParams {
            taps: 2048,
            lift_ms: 8.0,
            peq_bands: None,
            phase_frac: 6.0,
            max_latency_ms: 10.0,
        },
        Mode::Linear => ModeParams {
            taps: 2048,
            lift_ms: 28.0,
            peq_bands: None,
            phase_frac: 24.0,
            max_latency_ms: 30.0,
        },
        Mode::Ultra => {
            let ms = ultra_ms.clamp(ULTRA_MS.0, ULTRA_MS.1);
            let lift_ms = ms - 2.0;
            let mut taps = 2048;
            while taps < 16384 && 0.7 * taps as f64 / 48_000.0 * 1000.0 < lift_ms {
                taps *= 2;
            }
            ModeParams {
                taps,
                lift_ms,
                peq_bands: None,
                phase_frac: 24.0,
                max_latency_ms: ms,
            }
        }
    }
}

fn number(value: f64) -> String {
    if value == 0.0 {
        "0".into()
    } else {
        format!("{:016x}", value.to_bits())
    }
}

fn optional_number(out: &mut String, value: Option<f64>) {
    if let Some(value) = value {
        out.push_str(&number(value));
    } else {
        out.push('-');
    }
}

fn sorted_f64_map(out: &mut String, values: &[(String, f64)]) {
    let mut values: Vec<_> = values.iter().collect();
    values.sort_by(|a, b| a.0.cmp(&b.0));
    for (key, value) in values {
        write!(out, "{key}={};", number(*value)).unwrap();
    }
}

fn filter_key(entry: &SubEntry) -> String {
    let mut out = format!(
        "{}:{}:{}:{}:",
        number(entry.hp_hz),
        if entry.hp_hz != 0.0 {
            &entry.hp_type
        } else {
            ""
        },
        number(entry.lp_hz),
        if entry.lp_hz != 0.0 {
            &entry.lp_type
        } else {
            ""
        }
    );
    for &(frequency, q, gain) in &entry.peq {
        write!(
            &mut out,
            "{},{},{};",
            number(frequency),
            number(q),
            number(gain)
        )
        .unwrap();
    }
    out
}

macro_rules! ordered_map {
    ($module:ident, $value:ty) => {
        mod $module {
            use serde::{Deserialize, Deserializer, Serializer};
            use std::collections::BTreeMap;

            pub fn serialize<S>(
                values: &Vec<(String, $value)>,
                serializer: S,
            ) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                use serde::ser::SerializeMap as _;
                let mut map = serializer.serialize_map(Some(values.len()))?;
                for (key, value) in values {
                    map.serialize_entry(key, value)?;
                }
                map.end()
            }

            pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<(String, $value)>, D::Error>
            where
                D: Deserializer<'de>,
            {
                // Deserialization is for IPC values. `.secs` parsing uses PyJson
                // directly to retain insertion order.
                Ok(BTreeMap::<String, $value>::deserialize(deserializer)?
                    .into_iter()
                    .collect())
            }
        }
    };
}

ordered_map!(ordered_f64_map, f64);
ordered_map!(ordered_sub_map, super::SubEntry);
ordered_map!(ordered_layout_map, super::BundleLayoutEntry);

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

    fn band(lo_hz: f64, hi_hz: f64) -> RcBand {
        RcBand { lo_hz, hi_hz }
    }

    #[test]
    fn valid_rc_bands_drop_broken_bands_sort_and_keep_four() {
        let kept = valid_rc_bands(&[
            band(15_000.0, 20_000.0),
            band(10.0, 30.0),
            band(f64::NAN, 100.0),
            band(500.0, 400.0),
            band(300.0, 300.0),
            band(19_000.0, 21_000.0),
            band(1_000.0, 2_000.0),
            band(30.0, 60.0),
            band(5_000.0, 6_000.0),
            band(100.0, 200.0),
        ]);
        assert_eq!(
            kept,
            [
                band(30.0, 60.0),
                band(100.0, 200.0),
                band(1_000.0, 2_000.0),
                band(5_000.0, 6_000.0)
            ]
        );
        assert!(valid_rc_bands(&[]).is_empty());
    }

    #[test]
    fn engine_key_lists_extra_bands_sorted_and_only_when_present() {
        let baseline = CalibrationSettings::default();
        assert!(!baseline.engine_key().contains("rc_bands"));
        let forward = CalibrationSettings {
            rc_bands: vec![band(100.0, 200.0), band(15_000.0, 20_000.0)],
            ..baseline.clone()
        };
        let backward = CalibrationSettings {
            rc_bands: vec![band(15_000.0, 20_000.0), band(100.0, 200.0)],
            ..baseline
        };
        assert_eq!(forward.engine_key(), backward.engine_key());
        let expected = format!(
            "|rc_bands={}-{},{}-{}",
            number(100.0),
            number(200.0),
            number(15_000.0),
            number(20_000.0)
        );
        assert!(forward.engine_key().ends_with(&expected));
    }

    #[test]
    fn rc_upper_defaults_and_each_setting_change_engine_key() {
        let baseline = CalibrationSettings::default();
        let mut json = serde_json::to_value(&baseline).unwrap();
        json.as_object_mut().unwrap().remove("rc_hi_basis");
        json.as_object_mut().unwrap().remove("rc_hi_transition");
        let legacy: CalibrationSettings = serde_json::from_value(json).unwrap();
        assert_eq!(legacy, baseline);
        for basis in [RcHiBasis::Lenient, RcHiBasis::Agreement] {
            let settings = CalibrationSettings {
                rc_hi_basis: basis,
                ..baseline.clone()
            };
            assert_ne!(settings.engine_key(), baseline.engine_key());
            assert_eq!(settings.mimo_key(), baseline.mimo_key());
            assert_eq!(
                serde_json::to_value(&settings).unwrap()["rc_hi_basis"],
                basis.as_str()
            );
        }
        for factor in [2, 4] {
            let settings = CalibrationSettings {
                rc_hi_transition: factor,
                ..baseline.clone()
            };
            assert_ne!(settings.engine_key(), baseline.engine_key());
            assert_eq!(settings.mimo_key(), baseline.mimo_key());
        }
    }

    #[test]
    fn sample_rate_policy_defaults_for_legacy_settings_and_changes_engine_key() {
        let baseline = CalibrationSettings::default();
        let mut json = serde_json::to_value(&baseline).unwrap();
        assert_eq!(json["sample_rate_policy"], "reject");
        json.as_object_mut().unwrap().remove("sample_rate_policy");
        let legacy: CalibrationSettings = serde_json::from_value(json).unwrap();
        assert_eq!(legacy, baseline);
        let mut resampled = legacy.clone();
        resampled.sample_rate_policy = SampleRatePolicy::Resample;
        assert_ne!(resampled.engine_key(), legacy.engine_key());
        assert_eq!(
            serde_json::to_value(&resampled).unwrap()["sample_rate_policy"],
            "resample"
        );
        resampled.sample_rate_policy = SampleRatePolicy::Reject;
        assert_eq!(resampled.engine_key(), legacy.engine_key());
    }

    #[test]
    fn low_protect_defaults_off_and_preserves_legacy_engine_key() {
        let baseline = CalibrationSettings::default();
        assert!(!baseline.low_protect);
        let key = baseline.engine_key();
        assert!(!key.contains("low_protect"));
        let mut json = serde_json::to_value(&baseline).unwrap();
        json.as_object_mut().unwrap().remove("low_protect");
        let mut legacy: CalibrationSettings = serde_json::from_value(json).unwrap();
        assert_eq!(legacy, baseline);
        legacy.low_protect = true;
        assert_eq!(legacy.engine_key(), format!("{key}|low_protect"));
        legacy.low_protect = false;
        assert_eq!(legacy.engine_key(), key);
        let edit: crate::settings_edit::SettingEdit =
            serde_json::from_value(serde_json::json!({"kind":"low_protect","on":true})).unwrap();
        assert_eq!(
            edit,
            crate::settings_edit::SettingEdit::LowProtect { on: true }
        );
    }

    #[test]
    fn lf_align_and_mode_decay_default_off_and_extend_the_key_only_when_on() {
        let baseline = CalibrationSettings::default();
        assert!(!baseline.lf_align && !baseline.mode_decay);
        let key = baseline.engine_key();
        assert!(!key.contains("lf_align") && !key.contains("mode_decay"));
        let mut json = serde_json::to_value(&baseline).unwrap();
        json.as_object_mut().unwrap().remove("lf_align");
        json.as_object_mut().unwrap().remove("mode_decay");
        let mut legacy: CalibrationSettings = serde_json::from_value(json).unwrap();
        assert_eq!(legacy, baseline);
        legacy.lf_align = true;
        assert_eq!(legacy.engine_key(), format!("{key}|lf_align"));
        legacy.mode_decay = true;
        assert_eq!(legacy.engine_key(), format!("{key}|lf_align|mode_decay"));
        legacy.lf_align = false;
        assert_eq!(legacy.engine_key(), format!("{key}|mode_decay"));
        for (kind, expected) in [
            (
                "lf_align",
                crate::settings_edit::SettingEdit::LfAlign { on: true },
            ),
            (
                "mode_decay",
                crate::settings_edit::SettingEdit::ModeDecay { on: true },
            ),
        ] {
            let edit: crate::settings_edit::SettingEdit =
                serde_json::from_value(serde_json::json!({"kind": kind, "on": true})).unwrap();
            assert_eq!(edit, expected);
        }
    }

    #[test]
    fn hf_phase_defaults_off_and_extends_the_key_only_when_on() {
        let baseline = CalibrationSettings::default();
        assert!(!baseline.hf_phase);
        let key = baseline.engine_key();
        assert!(!key.contains("hf_phase"));
        let mut json = serde_json::to_value(&baseline).unwrap();
        json.as_object_mut().unwrap().remove("hf_phase");
        let mut legacy: CalibrationSettings = serde_json::from_value(json).unwrap();
        assert_eq!(legacy, baseline);
        legacy.hf_phase = true;
        assert_eq!(legacy.engine_key(), format!("{key}|hf_phase"));
        legacy.mode_decay = true;
        assert_eq!(legacy.engine_key(), format!("{key}|mode_decay|hf_phase"));
        let edit: crate::settings_edit::SettingEdit =
            serde_json::from_value(serde_json::json!({"kind": "hf_phase", "on": true})).unwrap();
        assert_eq!(
            edit,
            crate::settings_edit::SettingEdit::HfPhase { on: true }
        );
    }

    #[test]
    fn xo_recommendation_metadata_defaults_on_and_does_not_change_engine_key() {
        let baseline = CalibrationSettings::default();
        let key = baseline.engine_key();
        assert!(baseline.xo_rec_include);
        assert!(baseline.xo_rec_key.is_empty());
        let wire = serde_json::to_value(&baseline).unwrap();
        assert!(wire.get("xo_rec_include").is_none());
        assert!(wire.get("xo_rec_key").is_none());

        let legacy: CalibrationSettings = serde_json::from_value(wire).unwrap();
        assert!(legacy.xo_rec_include);
        let changed = CalibrationSettings {
            xo_rec_include: false,
            xo_rec_key: "recommendation".into(),
            ..legacy
        };
        assert_eq!(changed.engine_key(), key);
    }

    #[test]
    fn analytic_derivative_settings_default_off_and_change_only_their_keys() {
        let baseline = CalibrationSettings::default();
        let engine_key = baseline.engine_key();
        let mimo_key = baseline.mimo_key();
        let mut json = serde_json::to_value(&baseline).unwrap();
        let object = json.as_object_mut().unwrap();
        object.remove("peq_analytic_derivatives");
        object.remove("mimo_iir_analytic_derivatives");
        let legacy: CalibrationSettings = serde_json::from_value(json).unwrap();
        assert!(!legacy.peq_analytic_derivatives);
        assert!(!legacy.mimo_iir_analytic_derivatives);
        assert_eq!(legacy.engine_key(), engine_key);
        assert_eq!(legacy.mimo_key(), mimo_key);

        let mut peq = legacy.clone();
        peq.peq_analytic_derivatives = true;
        assert_eq!(
            peq.engine_key(),
            format!("{engine_key}|peq_analytic_derivatives")
        );
        assert_eq!(peq.mimo_key(), mimo_key);

        let mut mimo = legacy;
        mimo.mimo_iir_analytic_derivatives = true;
        assert_eq!(mimo.engine_key(), engine_key);
        assert_eq!(
            mimo.mimo_key(),
            format!("{mimo_key}|mimo_iir_analytic_derivatives")
        );
    }

    #[test]
    fn mode_labels_match_upstream() {
        assert_eq!(mode_label(Mode::Zero, None), "최소 지연 모드");
        assert_eq!(mode_label(Mode::Mixed, Some(120.0)), "저지연 모드");
        assert_eq!(mode_label(Mode::Linear, None), "표준 모드");
        assert_eq!(mode_label(Mode::Ultra, None), "초고지연 모드");
        assert_eq!(mode_label(Mode::Ultra, Some(20.0)), "초고지연 모드 30 ms");
        assert_eq!(
            mode_label(Mode::Ultra, Some(123.456_789)),
            "초고지연 모드 123.457 ms"
        );
        assert_eq!(mode_label(Mode::Ultra, Some(250.0)), "초고지연 모드 200 ms");

        let settings = CalibrationSettings {
            mode: Mode::Ultra,
            ultra_ms: 30.123_456_7,
            ..CalibrationSettings::default()
        };
        assert_eq!(settings.label(), "초고지연 모드 30.1235 ms");
    }

    #[test]
    fn mode_params_match_upstream() {
        let fixture: serde_json::Value = serde_json::from_str(include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../oracle/goldens/calibration/mode_params.json"
        )))
        .unwrap();
        for row in fixture["outputs"]["rows"].as_array().unwrap() {
            let mode = match row["mode"].as_str().unwrap() {
                "zero" => Mode::Zero,
                "mixed" => Mode::Mixed,
                "linear" => Mode::Linear,
                "ultra" => Mode::Ultra,
                _ => unreachable!(),
            };
            let actual = mode_params(mode, row["ultra_ms"].as_f64().unwrap());
            let expected = &row["params"];
            assert_eq!(actual.taps as u64, expected["taps"].as_u64().unwrap());
            assert_eq!(actual.lift_ms, expected["lift_ms"].as_f64().unwrap());
            assert_eq!(
                actual.peq_bands.map(|value| value as u64),
                expected
                    .get("peq_bands")
                    .and_then(serde_json::Value::as_u64)
            );
            assert_eq!(
                actual.phase_frac,
                expected
                    .get("phase_frac")
                    .and_then(serde_json::Value::as_f64)
                    .unwrap_or(6.0)
            );
            assert_eq!(
                actual.max_latency_ms,
                expected["max_latency_ms"].as_f64().unwrap()
            );
        }
    }

    #[test]
    fn keys_have_upstream_exclusions() {
        let fixture: serde_json::Value = serde_json::from_str(include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../oracle/goldens/calibration/keys.json"
        )))
        .unwrap();
        let settings: Vec<_> = fixture["inputs"]["settings"]
            .as_object()
            .unwrap()
            .iter()
            .map(|(name, value)| {
                (
                    name.as_str(),
                    serde_json::from_value::<CalibrationSettings>(value.clone()).unwrap(),
                )
            })
            .collect();

        for (kind, key) in [
            (
                "engine",
                CalibrationSettings::engine_key as fn(&CalibrationSettings) -> String,
            ),
            ("manual", CalibrationSettings::manual_key),
            ("mimo", CalibrationSettings::mimo_key),
        ] {
            let expected = fixture["outputs"][kind].as_object().unwrap();
            for (left_name, left) in &settings {
                for (right_name, right) in &settings {
                    assert_eq!(
                        key(left) == key(right),
                        expected[*left_name] == expected[*right_name],
                        "{kind} key equality differs for {left_name} and {right_name}"
                    );
                }
            }
        }
    }
}