koan-core 0.17.0

Core library for koan — bit-perfect music player. Audio engine, player, database, format strings.
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
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use thiserror::Error;

#[derive(Debug, Error)]
pub enum ConfigError {
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
    #[error("parse error: {0}")]
    Parse(#[from] toml::de::Error),
    #[error("serialize error: {0}")]
    Serialize(#[from] toml::ser::Error),
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
    pub library: LibraryConfig,
    pub playback: PlaybackConfig,
    pub remote: RemoteConfig,
    pub organize: OrganizeConfig,
    #[serde(alias = "visualiser")]
    pub visualizer: VisualizerConfig,
    pub radio: RadioConfig,
    pub graphql: GraphqlConfig,
    pub discovery: DiscoveryConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct LibraryConfig {
    pub folders: Vec<PathBuf>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct PlaybackConfig {
    pub software_volume: bool,
    pub replaygain: ReplayGainMode,
    /// Ticker scroll speed in frames-per-second (default: 8).
    /// The title scrolls one character per frame. Higher = faster scroll.
    pub ticker_fps: u8,
    /// UI render rate in frames-per-second (default: 60).
    /// Controls how often the TUI redraws. 30, 60, or 120 are typical values.
    pub target_fps: u8,
    /// Show an FPS counter overlay in the top-right corner.
    pub show_fps: bool,
    /// ReplayGain pre-amplification in dB. Applied on top of track/album gain.
    /// Positive values boost, negative values attenuate. Default: 0.0.
    pub pre_amp_db: f64,
    /// Output audio device name. None = system default.
    /// Persisted by name (not ID) since IDs can change across reboots.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output_device: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ReplayGainMode {
    Off,
    Track,
    Album,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct RemoteConfig {
    pub enabled: bool,
    pub url: String,
    pub username: String,
    /// Password — stored in config.local.toml (gitignored), not Keychain.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub password: String,
    /// original | opus-128 | mp3-320
    pub transcode_quality: String,
    /// Defaults to config_dir()/cache if empty.
    pub cache_dir: Option<PathBuf>,
    /// Parallel download workers for remote tracks (default: 5).
    pub download_workers: usize,
}

impl Default for LibraryConfig {
    fn default() -> Self {
        let music_dir = dirs::audio_dir().unwrap_or_else(|| {
            dirs::home_dir()
                .map(|h| h.join("Music"))
                .unwrap_or_else(|| PathBuf::from("/Music"))
        });
        Self {
            folders: vec![music_dir],
        }
    }
}

impl Default for PlaybackConfig {
    fn default() -> Self {
        Self {
            software_volume: false,
            replaygain: ReplayGainMode::Album,
            ticker_fps: 8,
            target_fps: 60,
            show_fps: false,
            pre_amp_db: 0.0,
            output_device: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct VisualizerConfig {
    pub enabled: bool,
    pub fps: u8,
    /// Frequency scale: "bark" (default), "mel", "log", "linear".
    pub scale: String,
    /// Amplitude scale: "aweight" (default, A-weighted), "perceptual" (A-weighted + gamma), "sqrt", "linear".
    pub amplitude_scale: String,
    /// Bar decay half-life in milliseconds (how fast bars drop).
    pub bar_decay_ms: u32,
    /// Peak decay half-life in milliseconds (how long peaks linger).
    pub peak_decay_ms: u32,
}

impl Default for VisualizerConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            fps: 60,
            scale: "bark".into(),
            amplitude_scale: "aweight".into(),
            bar_decay_ms: 50,
            peak_decay_ms: 180,
        }
    }
}

impl Default for RemoteConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            url: String::new(),
            username: String::new(),
            password: String::new(),
            transcode_quality: "original".into(),
            cache_dir: None,
            download_workers: 5,
        }
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct OrganizeConfig {
    /// Default named pattern to use when --pattern is omitted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,
    /// Named patterns — keys are names, values are format strings.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub patterns: HashMap<String, String>,
}

impl OrganizeConfig {
    /// Resolve a pattern argument: if it matches a named pattern, return the stored
    /// format string. Otherwise return it as-is (raw format string).
    pub fn resolve_pattern<'a>(&'a self, name_or_raw: &'a str) -> &'a str {
        self.patterns
            .get(name_or_raw)
            .map(|s| s.as_str())
            .unwrap_or(name_or_raw)
    }

    /// Get the default pattern's format string, if configured.
    pub fn default_pattern(&self) -> Option<&str> {
        self.default
            .as_ref()
            .and_then(|name| self.patterns.get(name))
            .map(|s| s.as_str())
    }
}

/// GraphQL API server configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct GraphqlConfig {
    /// Enable the GraphQL API server alongside the TUI (default: true).
    /// Set to false for TUI-only mode (equivalent to --no-api).
    pub enabled: bool,
    /// GraphQL API port (default: 4000).
    pub port: u16,
    /// Enable GraphiQL web IDE at GET /graphql.
    pub playground: bool,
    /// Enable Subsonic REST API on this port. Omit or null to disable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subsonic_port: Option<u16>,
}

impl Default for GraphqlConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            port: 4000,
            playground: false,
            subsonic_port: None,
        }
    }
}

/// Radio / infinite play mode configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct RadioConfig {
    /// Number of tracks to keep queued ahead of the cursor.
    pub lookahead: usize,
    /// Number of tracks to add each time the queue runs low.
    pub batch_size: usize,
    /// Use Subsonic getSimilarSongs2 when a remote server is configured.
    pub use_subsonic: bool,
    /// Don't repeat any of the last N tracks (play history exclusion window).
    pub history_window: usize,
    /// Number of recently played tracks to use as seed (drifting seed window).
    pub seed_window: usize,
    /// Discovery weight: 0.0 = only familiar tracks, 1.0 = maximise discovery.
    /// Controls the recency bonus — higher values boost never-played/long-forgotten tracks.
    pub discovery_weight: f64,
}

impl Default for RadioConfig {
    fn default() -> Self {
        Self {
            lookahead: 5,
            batch_size: 5,
            use_subsonic: true,
            history_window: 200,
            seed_window: 5,
            discovery_weight: 0.3,
        }
    }
}

/// Acoustic analysis / discovery configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct DiscoveryConfig {
    /// Run acoustic analysis automatically after library scan (default: false).
    pub analysis_on_scan: bool,
    /// Weight for acoustic similarity signal in radio mode scoring (0.0..1.0).
    pub acoustic_weight: f64,
}

impl Default for DiscoveryConfig {
    fn default() -> Self {
        Self {
            analysis_on_scan: false,
            acoustic_weight: 0.5,
        }
    }
}

impl Config {
    /// Load config.toml then deep-merge config.local.toml on top.
    /// Only keys actually present in config.local.toml override — missing keys
    /// keep their values from config.toml (not serde defaults).
    pub fn load() -> Result<Self, ConfigError> {
        let base_path = config_file_path();
        let local_path = config_local_file_path();

        let mut base_val: toml::Value = if base_path.exists() {
            let contents = fs::read_to_string(&base_path)?;
            toml::from_str(&contents)?
        } else {
            toml::Value::Table(toml::map::Map::new())
        };

        if local_path.exists() {
            let local_contents = fs::read_to_string(&local_path)?;
            let local_val: toml::Value = toml::from_str(&local_contents)?;
            deep_merge(&mut base_val, local_val);
        }

        let config: Config = base_val.try_into()?;
        Ok(config)
    }

    /// Load config, logging and falling back to defaults on error.
    pub fn load_or_default() -> Self {
        Self::load().unwrap_or_else(|e| {
            log::warn!("failed to load config, using defaults: {}", e);
            Self::default()
        })
    }

    /// Load from a specific path.
    pub fn load_from(path: &Path) -> Result<Self, ConfigError> {
        let contents = fs::read_to_string(path)?;
        let config: Config = toml::from_str(&contents)?;
        Ok(config)
    }

    /// Write config to the base config.toml.
    pub fn save(&self) -> Result<(), ConfigError> {
        let path = config_file_path();
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        let contents = toml::to_string_pretty(self)?;
        fs::write(&path, contents)?;
        Ok(())
    }

    /// Write config to config.local.toml (for machine-specific / sensitive values).
    pub fn save_local(&self) -> Result<(), ConfigError> {
        let path = config_local_file_path();
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        let contents = toml::to_string_pretty(self)?;
        fs::write(&path, contents)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?;
        }
        Ok(())
    }

    /// Resolved cache directory — uses explicit setting or defaults to config_dir/cache.
    pub fn cache_dir(&self) -> PathBuf {
        self.remote
            .cache_dir
            .clone()
            .unwrap_or_else(|| config_dir().join("cache"))
    }
}

/// Recursively merge `overlay` into `base`. Only keys present in `overlay`
/// are touched — everything else in `base` is preserved.
fn deep_merge(base: &mut toml::Value, overlay: toml::Value) {
    match (base, overlay) {
        (toml::Value::Table(base_map), toml::Value::Table(overlay_map)) => {
            for (key, overlay_val) in overlay_map {
                let entry = base_map
                    .entry(key)
                    .or_insert(toml::Value::Table(toml::map::Map::new()));
                deep_merge(entry, overlay_val);
            }
        }
        (base, overlay) => {
            *base = overlay;
        }
    }
}

/// `~/.config/koan/`
pub fn config_dir() -> PathBuf {
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".config")
        .join("koan")
}

/// Path to the base config TOML file (committable to dotfiles).
pub fn config_file_path() -> PathBuf {
    config_dir().join("config.toml")
}

/// Path to the local override config (gitignored, machine-specific).
pub fn config_local_file_path() -> PathBuf {
    config_dir().join("config.local.toml")
}

/// Path to the database file.
pub fn db_path() -> PathBuf {
    config_dir().join("koan.db")
}

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

    fn tmp_dir() -> PathBuf {
        let dir = std::env::temp_dir().join(format!("koan-test-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn test_defaults() {
        let cfg = Config::default();
        assert_eq!(cfg.playback.replaygain, ReplayGainMode::Album);
        assert!(!cfg.remote.enabled);
        assert_eq!(cfg.remote.transcode_quality, "original");
    }

    #[test]
    fn test_roundtrip_toml() {
        let cfg = Config::default();
        let serialized = toml::to_string_pretty(&cfg).unwrap();
        let deserialized: Config = toml::from_str(&serialized).unwrap();
        assert_eq!(deserialized.playback.replaygain, cfg.playback.replaygain);
        assert_eq!(
            deserialized.remote.transcode_quality,
            cfg.remote.transcode_quality
        );
    }

    #[test]
    fn test_load_from_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        fs::write(
            &path,
            r#"
[library]
folders = ["/tmp/music"]

[playback]
replaygain = "track"
"#,
        )
        .unwrap();

        let cfg = Config::load_from(&path).unwrap();
        assert_eq!(cfg.library.folders, vec![PathBuf::from("/tmp/music")]);
        assert_eq!(cfg.playback.replaygain, ReplayGainMode::Track);
        assert!(!cfg.remote.enabled);
    }

    #[test]
    fn test_partial_toml_uses_defaults() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("partial.toml");
        fs::write(&path, "[playback]\nsoftware_volume = true\n").unwrap();

        let cfg = Config::load_from(&path).unwrap();
        assert!(cfg.playback.software_volume);
    }

    #[test]
    fn test_deep_merge_local_overrides_base() {
        // Test deep_merge directly on TOML values (no temp files needed).
        let base_toml = r#"
[library]
folders = ["/base/music"]

[remote]
url = "https://base.example.com"
"#;
        let local_toml = r#"
[library]
folders = ["/local/music"]

[remote]
enabled = true
url = "https://local.example.com"
username = "admin"
"#;

        let mut base_val: toml::Value = toml::from_str(base_toml).unwrap();
        let local_val: toml::Value = toml::from_str(local_toml).unwrap();
        deep_merge(&mut base_val, local_val);

        let cfg: Config = base_val.try_into().unwrap();
        assert_eq!(cfg.library.folders, vec![PathBuf::from("/local/music")]);
        assert!(cfg.remote.enabled);
        assert_eq!(cfg.remote.url, "https://local.example.com");
        assert_eq!(cfg.remote.username, "admin");
    }

    #[test]
    fn test_deep_merge_missing_keys_preserved() {
        let base_toml = r#"
[remote]
url = "https://keep.me"
username = "keepuser"
"#;
        // Local only sets password — url and username should survive.
        let local_toml = r#"
[remote]
password = "secret"
"#;

        let mut base_val: toml::Value = toml::from_str(base_toml).unwrap();
        let local_val: toml::Value = toml::from_str(local_toml).unwrap();
        deep_merge(&mut base_val, local_val);

        let cfg: Config = base_val.try_into().unwrap();
        assert_eq!(cfg.remote.url, "https://keep.me");
        assert_eq!(cfg.remote.username, "keepuser");
        assert_eq!(cfg.remote.password, "secret");
    }

    #[test]
    fn test_cache_dir_default() {
        let cfg = Config::default();
        assert!(cfg.cache_dir().ends_with("cache"));
    }

    #[test]
    fn test_cache_dir_explicit() {
        let mut cfg = Config::default();
        cfg.remote.cache_dir = Some(PathBuf::from("/custom/cache"));
        assert_eq!(cfg.cache_dir(), PathBuf::from("/custom/cache"));
    }

    #[test]
    fn test_organize_config_defaults() {
        let cfg = Config::default();
        assert!(cfg.organize.default.is_none());
        assert!(cfg.organize.patterns.is_empty());
    }

    #[test]
    fn test_organize_config_from_toml() {
        let dir = tmp_dir();
        let path = dir.join("organize.toml");
        fs::write(
            &path,
            r#"
[organize]
default = "standard"

[organize.patterns]
standard = "%album artist%/(%date%) %album%/%tracknumber%. %title%"
va-aware = "%album artist%/$if($stricmp(%album artist%,Various Artists),,%album%)"
"#,
        )
        .unwrap();

        let cfg = Config::load_from(&path).unwrap();
        assert_eq!(cfg.organize.default.as_deref(), Some("standard"));
        assert_eq!(cfg.organize.patterns.len(), 2);
        assert!(cfg.organize.patterns.contains_key("standard"));
        assert!(cfg.organize.patterns.contains_key("va-aware"));

        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn test_organize_resolve_named_pattern() {
        let mut cfg = OrganizeConfig::default();
        cfg.patterns
            .insert("standard".into(), "%artist%/%title%".into());

        assert_eq!(cfg.resolve_pattern("standard"), "%artist%/%title%");
        // Unknown name falls through as raw pattern
        assert_eq!(cfg.resolve_pattern("%raw%pattern%"), "%raw%pattern%");
    }

    #[test]
    fn test_organize_default_pattern() {
        let mut cfg = OrganizeConfig {
            default: Some("standard".into()),
            ..OrganizeConfig::default()
        };
        cfg.patterns
            .insert("standard".into(), "%artist%/%title%".into());

        assert_eq!(cfg.default_pattern(), Some("%artist%/%title%"));
    }

    #[test]
    fn test_organize_default_pattern_missing_name() {
        let cfg = OrganizeConfig {
            default: Some("nonexistent".into()),
            ..OrganizeConfig::default()
        };
        // Name doesn't match any pattern → None
        assert_eq!(cfg.default_pattern(), None);
    }

    #[test]
    fn test_deep_merge_organize_patterns() {
        let base_toml = r#"
[organize]
default = "standard"

[organize.patterns]
standard = "base-pattern"
"#;
        let local_toml = r#"
[organize]
default = "custom"

[organize.patterns]
custom = "local-pattern"
"#;

        let mut base_val: toml::Value = toml::from_str(base_toml).unwrap();
        let local_val: toml::Value = toml::from_str(local_toml).unwrap();
        deep_merge(&mut base_val, local_val);

        let cfg: Config = base_val.try_into().unwrap();
        // Local default wins
        assert_eq!(cfg.organize.default.as_deref(), Some("custom"));
        // Both patterns present (deep merge into [organize.patterns] table)
        assert_eq!(cfg.organize.patterns.len(), 2);
        assert_eq!(cfg.organize.patterns["standard"], "base-pattern");
        assert_eq!(cfg.organize.patterns["custom"], "local-pattern");
    }

    #[test]
    fn test_output_device_config_roundtrip() {
        let mut cfg = Config::default();
        cfg.playback.output_device = Some("My DAC".into());

        let serialized = toml::to_string_pretty(&cfg).unwrap();
        let deserialized: Config = toml::from_str(&serialized).unwrap();
        assert_eq!(
            deserialized.playback.output_device.as_deref(),
            Some("My DAC")
        );
    }

    #[test]
    fn test_output_device_config_default_is_none() {
        let cfg = Config::default();
        assert!(cfg.playback.output_device.is_none());

        // Roundtrip: None should not appear in serialized output.
        let serialized = toml::to_string_pretty(&cfg).unwrap();
        assert!(!serialized.contains("output_device"));
        let deserialized: Config = toml::from_str(&serialized).unwrap();
        assert!(deserialized.playback.output_device.is_none());
    }

    #[test]
    fn test_output_device_config_from_toml() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        fs::write(
            &path,
            r#"
[playback]
output_device = "External Speakers"
"#,
        )
        .unwrap();

        let cfg = Config::load_from(&path).unwrap();
        assert_eq!(
            cfg.playback.output_device.as_deref(),
            Some("External Speakers")
        );
    }

    #[test]
    fn test_organize_config_roundtrip() {
        let mut cfg = Config::default();
        cfg.organize.default = Some("standard".into());
        cfg.organize
            .patterns
            .insert("standard".into(), "%artist%/%title%".into());

        let serialized = toml::to_string_pretty(&cfg).unwrap();
        let deserialized: Config = toml::from_str(&serialized).unwrap();
        assert_eq!(deserialized.organize.default.as_deref(), Some("standard"));
        assert_eq!(
            deserialized.organize.patterns["standard"],
            "%artist%/%title%"
        );
    }
}