eqtune 0.4.0

A lightweight, system-wide audio equalizer for macOS, built on Core Audio process taps.
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
//! Persistent configuration: named presets (each an ordered set of EQ bands plus a
//! preamp) and global audio toggles. Serialized as TOML at
//! `~/Library/Application Support/eqtune/config.toml`.
//!
//! Ships a working preset library so a first run needs no config file.

use std::collections::BTreeMap;
use std::ffi::OsStr;
use std::io::Write;
use std::path::{Path, PathBuf};

use anyhow::Context;
use serde::{Deserialize, Serialize};

use crate::dsp::{self, Band};

/// A named tuning: the EQ bands plus the preamp make-up gain (dB).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Preset {
    pub bands: Vec<Band>,
    pub preamp_db: f32,
}

/// Top-level config: the active preset name, global audio toggles, and all presets.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Config {
    pub active_preset: String,
    /// The user's last explicit `on`/`off`. Restored at daemon startup so an enabled EQ
    /// survives a reboot or daemon restart. Absent in older config files, hence the
    /// serde default (off, matching the pre-field behavior).
    #[serde(default)]
    pub enabled: bool,
    pub limiter: bool,
    pub auto_follow_new_devices: bool,
    /// Automatically disable the EQ engine while macOS Low Power Mode is active (an
    /// explicit `eqtune on` still overrides it). Defaults on; absent in older config
    /// files, hence the serde default.
    #[serde(default = "default_true")]
    pub auto_off_low_power: bool,
    /// Automatically disable the EQ engine after sustained silence and resume when the
    /// default output device becomes active again.
    #[serde(default = "default_true")]
    pub auto_off_idle: bool,
    pub presets: BTreeMap<String, Preset>,
}

/// Serde default for boolean fields that should be enabled when absent from an older
/// config file.
fn default_true() -> bool {
    true
}

/// A sibling path with `suffix` appended to the file name (e.g. `config.toml` +
/// `.tmp` -> `config.toml.tmp`), so it lives in the same directory — and thus the same
/// filesystem — as `path`, which is required for an atomic `rename`.
fn with_suffix(path: &Path, suffix: &str) -> PathBuf {
    let mut name = path
        .file_name()
        .unwrap_or_else(|| OsStr::new("config"))
        .to_os_string();
    name.push(suffix);
    path.with_file_name(name)
}

/// A sibling backup path for an unusable config that does not already exist, so
/// quarantining a second bad config never overwrites the first one's backup. The common
/// case is `config.toml.corrupt`; a prior backup bumps it to `.corrupt.1`, `.corrupt.2`, …
fn quarantine_path(path: &Path) -> PathBuf {
    let base = with_suffix(path, ".corrupt");
    if !base.exists() {
        return base;
    }
    let mut n = 1;
    loop {
        let candidate = with_suffix(path, &format!(".corrupt.{n}"));
        if !candidate.exists() {
            return candidate;
        }
        n += 1;
    }
}

/// Build a graphic-EQ-style preset (peaking filters at ~octave Q) from (freq_hz,
/// gain_db) points.
fn graphic(points: &[(f32, f32)]) -> Vec<Band> {
    const Q: f32 = 1.41;
    points
        .iter()
        .map(|&(freq, gain_db)| Band {
            kind: dsp::BandKind::Peaking,
            freq,
            gain_db,
            q: Q,
        })
        .collect()
}

impl Default for Config {
    fn default() -> Self {
        let mut presets = BTreeMap::new();
        // Candidate tunings (peaking filters at ~octave Q).
        // NOTE: "bright" is all boosts; it ships with -8 dB preamp to tame the
        // loudness. Nudge the preamp toward 0 with `eqtune preamp` if you want it louder.
        presets.insert(
            "bright".to_string(),
            Preset {
                bands: graphic(&[
                    (32.0, 7.5),
                    (64.0, 9.0),
                    (125.0, 11.0),
                    (250.0, 7.5),
                    (500.0, 4.0),
                    (1000.0, 4.5),
                    (2000.0, 7.5),
                    (4000.0, 7.5),
                    (8000.0, 9.5),
                    (16000.0, 7.0),
                ]),
                preamp_db: -8.0,
            },
        );
        presets.insert(
            "mellow".to_string(),
            Preset {
                bands: graphic(&[
                    (32.0, 3.0),
                    (64.0, 2.0),
                    (125.0, 1.0),
                    (250.0, -2.0),
                    (500.0, -3.0),
                    (1000.0, -4.0),
                    (2000.0, -7.0),
                    (4000.0, -1.0),
                    (8000.0, 2.0),
                    (16000.0, 2.0),
                ]),
                preamp_db: 0.0,
            },
        );
        // "pro" — sound-engineer 31-band 1/3-octave curve (sub-bass lift + deep 125 Hz notch).
        // Best-effort parse of a hand-supplied spec; tweak by ear with `eqtune band`.
        presets.insert(
            "pro".to_string(),
            Preset {
                bands: graphic(&[
                    (20.0, 0.0),
                    (25.0, 1.0),
                    (31.5, 2.0),
                    (40.0, 1.5),
                    (50.0, 1.5),
                    (63.0, 1.5),
                    (80.0, -2.0),
                    (100.0, -6.0),
                    (125.0, -15.0),
                    (160.0, -7.0),
                    (200.0, -3.0),
                    (250.0, -2.0),
                    (315.0, -1.0),
                    (400.0, -1.0),
                    (500.0, 0.0),
                    (630.0, 0.0),
                    (800.0, 0.5),
                    (1000.0, 0.75),
                    (1250.0, 1.0),
                    (1600.0, 0.75),
                    (2000.0, 0.0),
                    (2500.0, 0.75),
                    (3150.0, 1.0),
                    (4000.0, 1.0),
                    (5000.0, 0.0),
                    (6300.0, -1.0),
                    (8000.0, 0.5),
                    (10000.0, 0.5),
                ]),
                preamp_db: 0.0,
            },
        );
        Self {
            active_preset: "bright".to_string(),
            enabled: false,
            limiter: true,
            auto_follow_new_devices: true,
            auto_off_low_power: true,
            auto_off_idle: true,
            presets,
        }
    }
}

impl Config {
    /// Standard config-file location.
    pub fn path() -> PathBuf {
        let home = std::env::var("HOME").unwrap_or_default();
        PathBuf::from(home).join("Library/Application Support/eqtune/config.toml")
    }

    /// Load from [`Config::path`], or return defaults if the file does not exist.
    pub fn load() -> anyhow::Result<Self> {
        Self::load_from(&Self::path())
    }

    pub fn load_from(path: &Path) -> anyhow::Result<Self> {
        let contents = match std::fs::read_to_string(path) {
            Ok(s) => s,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()),
            Err(e) => return Err(e.into()),
        };
        // A config that is unusable — malformed TOML, or parseable but with a preset the
        // real-time engine could not run (over dsp::MAX_BANDS, or a non-finite / out-of-range
        // value that would design NaN coefficients) — is quarantined rather than propagated:
        // under launchd KeepAlive a hard error would restart the daemon into the same failure
        // forever and lose every preset. Back the bad file up for manual recovery and continue
        // with defaults.
        let reason = match Self::parse_usable(&contents) {
            Ok(config) => return Ok(config),
            Err(reason) => reason,
        };
        // Move the bad file aside — both to preserve it for manual recovery and to get it
        // out of the way so the next save writes a fresh config. If the move fails we must
        // NOT continue: returning defaults here would let the next save overwrite the
        // user's only copy with defaults, so propagate instead and leave the file intact.
        let backup = quarantine_path(path);
        std::fs::rename(path, &backup).with_context(|| {
            format!(
                "config at {} is unusable ({reason}) but could not be moved aside to {}; \
                 refusing to continue and overwrite it with defaults",
                path.display(),
                backup.display(),
            )
        })?;
        eprintln!(
            "eqtune: config at {} is unusable ({reason}); backed up to {} and continuing with defaults",
            path.display(),
            backup.display()
        );
        Ok(Self::default())
    }

    /// Standard location of the session-draft file: the working (unsaved) tuning the
    /// daemon mirrors to disk while it differs from the saved config, so a reboot or
    /// daemon restart does not lose it.
    pub fn session_path() -> PathBuf {
        Self::path().with_file_name("session.toml")
    }

    /// Restore a session draft left behind by a previous daemon run (reboot, crash,
    /// reinstall). Returns the working config to continue from, or `None` when no usable
    /// draft exists.
    ///
    /// Only preset contents are taken from the draft, and only preset by preset, for
    /// names that exist in `saved`; `active_preset` and every global toggle (`enabled`,
    /// `limiter`, `auto_off_*`, …) come from `saved`. A legitimate draft only ever
    /// *modifies* presets of its saved base — session edits touch the active preset's
    /// contents, never the preset set — so a draft can neither delete a preset the
    /// saved config has (e.g. one committed by the very save that resolved the session,
    /// when a crash landed between the config write and the draft's removal) nor smuggle
    /// one in. Preset switches and toggle changes are committed to the saved config
    /// immediately by their handlers, so a stale draft must not revert them — or
    /// manufacture a phantom "unsaved changes" diff out of a switch or toggle alone.
    ///
    /// An unreadable or engine-unrunnable draft is moved aside like a bad config
    /// (`.corrupt` backup) and ignored. Unlike [`Config::load_from`], a failed move-aside
    /// is not an error: the committed config is untouched, and the draft file is
    /// overwritten by the next live edit anyway.
    pub fn load_session(path: &Path, saved: &Config) -> Option<Config> {
        let contents = match std::fs::read_to_string(path) {
            Ok(s) => s,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None,
            Err(e) => {
                eprintln!(
                    "eqtune: could not read session draft {}: {e}",
                    path.display()
                );
                return None;
            }
        };
        // The merged result needs no re-check: `saved` was validated by its own load and
        // the adopted contents by this parse (a draft carrying any unusable preset is
        // quarantined wholesale, adopted or not).
        let reason = match Self::parse_usable(&contents) {
            Ok(draft) => {
                let mut config = saved.clone();
                for (name, preset) in draft.presets {
                    if let Some(slot) = config.presets.get_mut(&name) {
                        *slot = preset;
                    }
                }
                return Some(config);
            }
            Err(reason) => reason,
        };
        let backup = quarantine_path(path);
        match std::fs::rename(path, &backup) {
            Ok(()) => eprintln!(
                "eqtune: session draft at {} is unusable ({reason}); backed up to {} and ignored",
                path.display(),
                backup.display()
            ),
            Err(e) => eprintln!(
                "eqtune: session draft at {} is unusable ({reason}) and could not be moved \
                 aside ({e}); ignored",
                path.display()
            ),
        }
        None
    }

    /// Persist to [`Config::path`], creating the parent directory if needed.
    pub fn save(&self) -> anyhow::Result<()> {
        self.save_to(&Self::path())
    }

    pub fn save_to(&self, path: &Path) -> anyhow::Result<()> {
        self.write_atomically(path, true)
    }

    /// Atomic like [`Config::save_to`] (readers never see a torn file) but without the
    /// fsyncs, for the best-effort session-draft mirror: it is rewritten as the working
    /// tuning changes inside the daemon's single-threaded accept/poll loop (rate-limited
    /// so a burst of edits coalesces), where two durability-grade flushes per write would
    /// stall request handling and the device/low-power/idle polling for nothing — the
    /// worst a power loss can cost is the most recent mirror write, and a file truncated
    /// by an ill-timed crash is quarantined (not trusted) by [`Config::load_session`].
    pub fn write_draft_to(&self, path: &Path) -> anyhow::Result<()> {
        self.write_atomically(path, false)
    }

    fn write_atomically(&self, path: &Path, durable: bool) -> anyhow::Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let contents = toml::to_string_pretty(self)?;
        // Write to a sibling temp file, then atomically rename it into place, so a crash
        // mid-write can only truncate the throwaway temp file, never the live file. When
        // `durable`, additionally fsync the file before the rename and the directory
        // after it: without those a power loss could apply the rename before the bytes
        // reach disk, leaving `path` pointing at an empty or partial file.
        let tmp = with_suffix(path, ".tmp");
        {
            let mut file = std::fs::File::create(&tmp)?;
            file.write_all(contents.as_bytes())?;
            if durable {
                file.sync_all()?;
            }
        }
        std::fs::rename(&tmp, path)?;
        if durable {
            if let Some(parent) = path.parent() {
                if let Ok(dir) = std::fs::File::open(parent) {
                    let _ = dir.sync_all();
                }
            }
        }
        Ok(())
    }

    /// Parse `contents` and check that every preset is runnable by the real-time
    /// engine. On failure returns the human-readable reason the quarantine paths log —
    /// one definition of "usable" and one reason format shared by the config file and
    /// the session draft, so their validation and diagnostics cannot drift apart.
    fn parse_usable(contents: &str) -> Result<Config, String> {
        match toml::from_str::<Config>(contents) {
            Ok(config) => match config.first_unusable_preset() {
                Some((name, err)) => Err(format!("preset {name:?} cannot be applied ({err})")),
                None => Ok(config),
            },
            Err(e) => Err(format!("invalid TOML ({e})")),
        }
    }

    /// The name and validation error of the first preset the real-time engine could not
    /// run — over [`dsp::MAX_BANDS`], or carrying a non-finite or out-of-range value that
    /// would design NaN/garbage coefficients — or `None` if every preset is usable.
    /// Presets are checked in name order (the map is a `BTreeMap`) so the result is stable.
    /// Applied at load time so a config that parses but cannot be run is quarantined
    /// instead of reaching the audio thread.
    fn first_unusable_preset(&self) -> Option<(&str, anyhow::Error)> {
        self.presets
            .iter()
            .find_map(|(name, preset)| validate_preset(preset).err().map(|e| (name.as_str(), e)))
    }

    /// The currently selected preset, or any remaining preset if the active name no longer
    /// resolves (e.g. right after the active preset was deleted).
    pub fn active(&self) -> Option<&Preset> {
        self.presets
            .get(&self.active_preset)
            .or_else(|| self.presets.values().next())
    }
}

// --- preset validation -------------------------------------------------------
// The single definition of what makes a preset runnable by the real-time engine.
// The config load path ([`Config::first_unusable_preset`]) and the daemon's IPC
// mutation handlers (set-band, preamp, import) both validate through these, so
// "parses from disk" and "the engine can run it" mean exactly the same thing —
// closing the gap where a hand-edited config with a NaN/out-of-range value would
// load cleanly and feed garbage coefficients to the audio thread.

const MIN_BAND_FREQ_HZ: f32 = 20.0;
const MAX_BAND_FREQ_HZ: f32 = 20_000.0;
const MIN_BAND_GAIN_DB: f32 = -24.0;
const MAX_BAND_GAIN_DB: f32 = 24.0;
const MIN_Q: f32 = 0.1;
const MAX_Q: f32 = 10.0;
const MIN_PREAMP_DB: f32 = -60.0;
const MAX_PREAMP_DB: f32 = 12.0;

pub(crate) fn validate_preset(preset: &Preset) -> anyhow::Result<()> {
    if preset.bands.len() > dsp::MAX_BANDS {
        return Err(anyhow::anyhow!(
            "preset has too many bands ({}); the maximum is {}",
            preset.bands.len(),
            dsp::MAX_BANDS
        ));
    }
    validate_preamp(preset.preamp_db)?;
    for band in &preset.bands {
        validate_band(band.freq, band.gain_db, band.q)?;
    }
    Ok(())
}

pub(crate) fn validate_band(freq: f32, gain_db: f32, q: f32) -> anyhow::Result<()> {
    validate_freq(freq)?;
    validate_range("gain", gain_db, MIN_BAND_GAIN_DB, MAX_BAND_GAIN_DB, "dB")?;
    validate_range("Q", q, MIN_Q, MAX_Q, "")?;
    Ok(())
}

pub(crate) fn validate_freq(freq: f32) -> anyhow::Result<()> {
    validate_range("frequency", freq, MIN_BAND_FREQ_HZ, MAX_BAND_FREQ_HZ, "Hz")
}

pub(crate) fn validate_preamp(db: f32) -> anyhow::Result<()> {
    validate_range("preamp", db, MIN_PREAMP_DB, MAX_PREAMP_DB, "dB")
}

fn validate_range(name: &str, value: f32, min: f32, max: f32, unit: &str) -> anyhow::Result<()> {
    if !value.is_finite() {
        return Err(anyhow::anyhow!("{name} must be a finite number"));
    }
    if !(min..=max).contains(&value) {
        return Err(anyhow::anyhow!(
            "{name} must be between {} and {}",
            format_bound(min, unit),
            format_bound(max, unit)
        ));
    }
    Ok(())
}

fn format_bound(value: f32, unit: &str) -> String {
    if unit.is_empty() {
        trim_number(value)
    } else {
        format!("{} {unit}", trim_number(value))
    }
}

fn trim_number(n: f32) -> String {
    let s = format!("{n:.3}");
    s.trim_end_matches('0').trim_end_matches('.').to_string()
}

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

    #[test]
    fn active_falls_back_to_a_remaining_preset_when_name_is_missing() {
        // No preset is named "default"; a stale active name must still resolve to some
        // preset (the first by name) rather than returning None.
        let c = Config {
            active_preset: "nonexistent".into(),
            ..Config::default()
        };
        assert!(!c.presets.contains_key("nonexistent"));
        assert!(c.active().is_some(), "must fall back to a remaining preset");
    }

    #[test]
    fn default_active_is_bright() {
        let c = Config::default();
        assert_eq!(c.active_preset, "bright");
        assert_eq!(c.active().unwrap().bands.len(), 10);
        assert!(
            !c.presets.contains_key("original"),
            "original should be removed"
        );
        assert!(!c.enabled);
        assert!(c.limiter);
        assert!(c.auto_follow_new_devices);
        assert!(c.auto_off_low_power);
        assert!(c.auto_off_idle);
    }

    #[test]
    fn library_has_expected_presets() {
        let c = Config::default();
        for name in ["bright", "mellow", "pro"] {
            assert!(c.presets.contains_key(name), "missing preset {name}");
        }
        for gone in [
            "flat",
            "macbook-pro",
            "original",
            "air-desk",
            "air-lap",
            "engineer",
        ] {
            assert!(!c.presets.contains_key(gone), "{gone} should be gone");
        }
        assert_eq!(c.presets["bright"].bands.len(), 10);
        assert_eq!(c.presets["bright"].preamp_db, -8.0);
        assert_eq!(c.presets["pro"].bands.len(), 28);
    }

    #[test]
    fn toml_round_trip() {
        let c = Config::default();
        let s = toml::to_string_pretty(&c).unwrap();
        let back: Config = toml::from_str(&s).unwrap();
        assert_eq!(c, back);
    }

    #[test]
    fn load_missing_returns_default() {
        let p = Path::new("/nonexistent/eqtune-xyz/config.toml");
        assert_eq!(Config::load_from(p).unwrap(), Config::default());
    }

    #[test]
    fn missing_auto_off_low_power_defaults_true() {
        // A config written before `auto_off_low_power`/`auto_off_idle` existed must still load.
        let toml = r#"
active_preset = "bright"
limiter = true
auto_follow_new_devices = true

[presets.bright]
preamp_db = -8.0
bands = []
"#;
        let c: Config = toml::from_str(toml).unwrap();
        assert!(c.auto_off_low_power, "absent field should default to true");
        assert!(c.auto_off_idle, "absent field should default to true");
        assert!(!c.enabled, "absent enabled field should default to off");
    }

    fn unique_dir(tag: &str) -> PathBuf {
        use std::sync::atomic::{AtomicU64, Ordering};
        // A process-wide counter guarantees uniqueness across parallel test threads even
        // when the clock is too coarse to distinguish two calls; the timestamp is kept only
        // to keep any leftover directory greppable/ordered if a test fails to clean up.
        static SEQ: AtomicU64 = AtomicU64::new(0);
        let seq = SEQ.fetch_add(1, Ordering::Relaxed);
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        std::env::temp_dir().join(format!(
            "eqtune-cfg-{}-{nanos}-{seq}-{tag}",
            std::process::id()
        ))
    }

    #[test]
    fn save_to_is_atomic_and_leaves_no_temp_file() {
        let dir = unique_dir("atomic");
        let path = dir.join("config.toml");
        let c = Config::default();
        c.save_to(&path).unwrap();

        assert!(path.exists(), "config must be written");
        assert!(
            !dir.join("config.toml.tmp").exists(),
            "the temp file must be renamed away, not left behind"
        );
        assert_eq!(Config::load_from(&path).unwrap(), c);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_from_recovers_from_corrupt_config() {
        let dir = unique_dir("corrupt");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");
        std::fs::write(&path, "not valid toml {{{").unwrap();

        // Must fall back to defaults instead of erroring (which would crash-loop the
        // daemon under launchd KeepAlive).
        let recovered = Config::load_from(&path).unwrap();
        assert_eq!(recovered, Config::default());
        // The bad file is preserved for manual recovery, and moved out of the way so the
        // next save writes a fresh, valid config.
        assert!(dir.join("config.toml.corrupt").exists());
        assert!(!path.exists());
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn second_quarantine_keeps_the_first_backup() {
        let dir = unique_dir("requarantine");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");

        std::fs::write(&path, "not valid toml {{{").unwrap();
        assert_eq!(Config::load_from(&path).unwrap(), Config::default());
        assert!(dir.join("config.toml.corrupt").exists());

        // A second unusable config must get its own backup, not overwrite the first.
        std::fs::write(&path, "also not valid }}}").unwrap();
        assert_eq!(Config::load_from(&path).unwrap(), Config::default());
        assert!(
            dir.join("config.toml.corrupt").exists(),
            "the first backup must survive a second quarantine"
        );
        assert!(
            dir.join("config.toml.corrupt.1").exists(),
            "the second bad config must be preserved under a distinct name"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_session_missing_returns_none() {
        let saved = Config::default();
        assert!(
            Config::load_session(Path::new("/nonexistent/eqtune-xyz/session.toml"), &saved)
                .is_none()
        );
    }

    #[test]
    fn load_session_takes_preset_contents_from_draft_and_the_rest_from_saved() {
        let dir = unique_dir("session-merge");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("session.toml");

        // The draft carries an edit, but also a stale active preset and toggle values
        // (switches and toggles commit immediately, so the saved config is their truth).
        let mut draft = Config {
            active_preset: "pro".into(),
            enabled: false,
            auto_off_idle: false,
            ..Config::default()
        };
        draft.presets.get_mut("mellow").unwrap().preamp_db = -3.0;
        std::fs::write(&path, toml::to_string_pretty(&draft).unwrap()).unwrap();

        let saved = Config {
            active_preset: "mellow".into(),
            enabled: true,
            ..Config::default()
        };
        let restored = Config::load_session(&path, &saved).unwrap();

        // Preset contents come from the draft…
        assert_eq!(restored.presets["mellow"].preamp_db, -3.0);
        // …and the active preset and every global toggle come from the saved config.
        assert_eq!(
            restored.active_preset, "mellow",
            "stale draft must not revert the committed preset switch"
        );
        assert!(restored.enabled, "stale draft must not revert `enabled`");
        assert!(
            restored.auto_off_idle,
            "stale draft must not revert toggles"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_session_keeps_presets_the_stale_draft_lacks() {
        // Crash window: `preset-save daily` committed config.toml (which gained "daily")
        // but the daemon died before the now-resolved draft was removed. The stale
        // draft's preset map must not shadow the committed one — "daily" survives.
        let dir = unique_dir("session-stale");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("session.toml");

        let mut draft = Config::default(); // no "daily"
        draft.presets.get_mut("bright").unwrap().preamp_db = -3.0;
        std::fs::write(&path, toml::to_string_pretty(&draft).unwrap()).unwrap();

        let mut saved = Config {
            active_preset: "daily".into(),
            ..Config::default()
        };
        saved.presets.insert(
            "daily".into(),
            Preset {
                bands: vec![],
                preamp_db: -6.0,
            },
        );
        let restored = Config::load_session(&path, &saved).unwrap();

        assert_eq!(
            restored.presets["daily"].preamp_db, -6.0,
            "a preset committed to the saved config must survive a stale draft"
        );
        assert_eq!(restored.active_preset, "daily");
        // Contents of presets both sides know still come from the draft.
        assert_eq!(restored.presets["bright"].preamp_db, -3.0);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_session_ignores_draft_presets_unknown_to_saved() {
        // A session can only modify existing presets, never add one — a draft key the
        // saved config does not know is stale garbage and must not be smuggled in.
        let dir = unique_dir("session-unknown");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("session.toml");

        let mut draft = Config::default();
        draft.presets.insert(
            "ghost".into(),
            Preset {
                bands: vec![],
                preamp_db: 0.0,
            },
        );
        std::fs::write(&path, toml::to_string_pretty(&draft).unwrap()).unwrap();

        let restored = Config::load_session(&path, &Config::default()).unwrap();
        assert!(!restored.presets.contains_key("ghost"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_session_quarantines_invalid_toml() {
        let dir = unique_dir("session-corrupt");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("session.toml");
        std::fs::write(&path, "not valid toml {{{").unwrap();

        assert!(Config::load_session(&path, &Config::default()).is_none());
        assert!(dir.join("session.toml.corrupt").exists());
        assert!(!path.exists());
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_session_quarantines_unrunnable_draft() {
        let dir = unique_dir("session-badpreset");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("session.toml");
        let mut draft = Config::default();
        draft.presets.get_mut("bright").unwrap().bands[0].q = 0.0;
        std::fs::write(&path, toml::to_string_pretty(&draft).unwrap()).unwrap();

        assert!(Config::load_session(&path, &Config::default()).is_none());
        assert!(dir.join("session.toml.corrupt").exists());
        assert!(!path.exists());
        let _ = std::fs::remove_dir_all(&dir);
    }

    fn wide_bands(n: usize) -> Vec<Band> {
        (0..n)
            .map(|i| Band {
                kind: dsp::BandKind::Peaking,
                freq: 20.0 + i as f32,
                gain_db: 1.0,
                q: 1.0,
            })
            .collect()
    }

    #[test]
    fn load_from_recovers_from_over_cap_preset() {
        let dir = unique_dir("overcap");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");
        // Valid TOML, but a preset exceeds the band cap — the RT engine could not run it
        // without allocating, so load must quarantine it and fall back to defaults.
        let mut c = Config::default();
        c.presets.insert(
            "big".into(),
            Preset {
                bands: wide_bands(dsp::MAX_BANDS + 1),
                preamp_db: 0.0,
            },
        );
        std::fs::write(&path, toml::to_string_pretty(&c).unwrap()).unwrap();

        let recovered = Config::load_from(&path).unwrap();
        assert_eq!(recovered, Config::default());
        assert!(dir.join("config.toml.corrupt").exists());
        assert!(!path.exists());
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_from_accepts_preset_at_the_band_cap() {
        let dir = unique_dir("atcap");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");
        let mut c = Config::default();
        c.presets.insert(
            "full".into(),
            Preset {
                bands: wide_bands(dsp::MAX_BANDS),
                preamp_db: 0.0,
            },
        );
        std::fs::write(&path, toml::to_string_pretty(&c).unwrap()).unwrap();

        let loaded = Config::load_from(&path).unwrap();
        assert_eq!(loaded.presets["full"].bands.len(), dsp::MAX_BANDS);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn save_then_load_roundtrips() {
        let dir = unique_dir("roundtrip");
        let path = dir.join("config.toml");
        let c = Config {
            active_preset: "flat".to_string(),
            ..Config::default()
        };
        c.save_to(&path).unwrap();
        let back = Config::load_from(&path).unwrap();
        let _ = std::fs::remove_dir_all(&dir);
        assert_eq!(c, back);
    }

    #[test]
    fn load_from_quarantines_a_preset_with_out_of_range_values() {
        // Valid TOML and a valid band count, but a value the RT engine can't design into
        // sane coefficients (q = 0 divides by zero; NaN/inf poison the biquad). The load
        // path must reject it exactly like the IPC mutation paths do, not pass it through
        // to the audio thread.
        for bad in [
            Band {
                kind: dsp::BandKind::Peaking,
                freq: 1000.0,
                gain_db: 0.0,
                q: 0.0,
            },
            Band {
                kind: dsp::BandKind::Peaking,
                freq: f32::NAN,
                gain_db: 0.0,
                q: 1.0,
            },
            Band {
                kind: dsp::BandKind::Peaking,
                freq: 1000.0,
                gain_db: f32::INFINITY,
                q: 1.0,
            },
        ] {
            let dir = unique_dir("badvalue");
            std::fs::create_dir_all(&dir).unwrap();
            let path = dir.join("config.toml");
            let mut c = Config::default();
            c.presets.insert(
                "poison".into(),
                Preset {
                    bands: vec![bad],
                    preamp_db: 0.0,
                },
            );
            std::fs::write(&path, toml::to_string_pretty(&c).unwrap()).unwrap();

            let recovered = Config::load_from(&path).unwrap();
            assert_eq!(recovered, Config::default());
            assert!(dir.join("config.toml.corrupt").exists());
            assert!(!path.exists());
            let _ = std::fs::remove_dir_all(&dir);
        }
    }

    #[test]
    fn band_validation_accepts_practical_values() {
        validate_band(20.0, -24.0, 0.1).unwrap();
        validate_band(20_000.0, 24.0, 10.0).unwrap();
        validate_band(1000.0, 0.0, 1.41).unwrap();
    }

    #[test]
    fn band_validation_rejects_invalid_values() {
        for (freq, gain, q) in [
            (0.0, 0.0, 1.0),
            (20_001.0, 0.0, 1.0),
            (1000.0, -24.1, 1.0),
            (1000.0, 24.1, 1.0),
            (1000.0, 0.0, 0.0),
            (1000.0, 0.0, 10.1),
            (f32::NAN, 0.0, 1.0),
            (1000.0, f32::INFINITY, 1.0),
            (1000.0, 0.0, f32::NEG_INFINITY),
        ] {
            assert!(validate_band(freq, gain, q).is_err());
        }
    }

    #[test]
    fn preamp_validation_accepts_safe_range() {
        validate_preamp(-60.0).unwrap();
        validate_preamp(0.0).unwrap();
        validate_preamp(12.0).unwrap();
    }

    #[test]
    fn preamp_validation_rejects_invalid_values() {
        for db in [-60.1, 12.1, f32::NAN, f32::INFINITY] {
            assert!(validate_preamp(db).is_err());
        }
    }
}