mfe-player 0.3.8

Music For Everyone — a plugin-driven, terminal-native music player that tells subscriptions to get lost
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
use std::env;
use std::fs;
use std::path::PathBuf;

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

pub fn config_dir() -> PathBuf {
    dirs_config_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join("mfe-player")
}

fn legacy_config_dir() -> PathBuf {
    dirs_config_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join("nuclear-tui")
}

fn legacy_cache_dir() -> PathBuf {
    if let Ok(xdg) = env::var("XDG_CACHE_HOME") {
        if !xdg.trim().is_empty() {
            return PathBuf::from(xdg).join("nuclear-tui");
        }
    }
    env::var_os("HOME")
        .map(|home| PathBuf::from(home).join(".cache").join("nuclear-tui"))
        .unwrap_or_else(|| PathBuf::from(".cache").join("nuclear-tui"))
}

/// Move an old nuclear-tui install over to the mfe-player paths so nobody
/// loses their queue, playlists, downloads or hand-written config in the
/// rename. Safe to call on every launch.
pub fn migrate_legacy() {
    let new = config_dir();
    let old = legacy_config_dir();
    if !new.exists() && old.is_dir() && fs::rename(&old, &new).is_err() {
        let _ = copy_dir(&old, &new);
    }
    let new_cache = cache_dir();
    let old_cache = legacy_cache_dir();
    if !new_cache.exists() && old_cache.is_dir() && fs::rename(&old_cache, &new_cache).is_err() {
        let _ = copy_dir(&old_cache, &new_cache);
    }
}

fn copy_dir(from: &PathBuf, to: &PathBuf) -> std::io::Result<()> {
    fs::create_dir_all(to)?;
    for entry in fs::read_dir(from)? {
        let entry = entry?;
        let target = to.join(entry.file_name());
        if entry.file_type()?.is_dir() {
            copy_dir(&entry.path(), &target)?;
        } else {
            fs::copy(entry.path(), target)?;
        }
    }
    Ok(())
}

fn dirs_config_dir() -> Option<PathBuf> {
    #[cfg(windows)]
    if let Ok(appdata) = env::var("APPDATA") {
        if !appdata.trim().is_empty() {
            return Some(PathBuf::from(appdata));
        }
    }
    if let Ok(xdg) = env::var("XDG_CONFIG_HOME") {
        if !xdg.trim().is_empty() {
            return Some(PathBuf::from(xdg));
        }
    }
    env::var_os("HOME").map(|home| PathBuf::from(home).join(".config"))
}

pub fn plugins_dir() -> PathBuf {
    config_dir().join("plugins")
}

pub fn state_path() -> PathBuf {
    config_dir().join("state.json")
}

pub fn taste_path() -> PathBuf {
    config_dir().join("taste.json")
}

pub fn config_path() -> PathBuf {
    config_dir().join("config.toml")
}

pub fn mpv_log_path() -> PathBuf {
    config_dir().join("mpv.log")
}

pub fn cache_dir() -> PathBuf {
    #[cfg(windows)]
    if let Ok(local) = env::var("LOCALAPPDATA") {
        if !local.trim().is_empty() {
            return PathBuf::from(local).join("mfe-player");
        }
    }
    #[cfg(target_os = "macos")]
    if let Some(home) = env::var_os("HOME") {
        return PathBuf::from(home)
            .join("Library")
            .join("Caches")
            .join("mfe-player");
    }
    if let Ok(xdg) = env::var("XDG_CACHE_HOME") {
        if !xdg.trim().is_empty() {
            return PathBuf::from(xdg).join("mfe-player");
        }
    }
    env::var_os("HOME")
        .map(|home| PathBuf::from(home).join(".cache").join("mfe-player"))
        .unwrap_or_else(|| PathBuf::from(".cache").join("mfe-player"))
}

pub fn downloads_dir() -> PathBuf {
    cache_dir().join("downloads")
}

pub fn artwork_dir() -> PathBuf {
    cache_dir().join("artwork")
}

pub fn library_cache_path() -> PathBuf {
    config_dir().join("library.json")
}

pub fn runtime_dir() -> PathBuf {
    if let Ok(xdg) = env::var("XDG_RUNTIME_DIR") {
        if !xdg.trim().is_empty() {
            return PathBuf::from(xdg).join("mfe-player");
        }
    }
    let user = env::var("USER")
        .or_else(|_| env::var("USERNAME"))
        .unwrap_or_else(|_| "user".to_string());
    env::temp_dir().join(format!("mfe-player-{user}"))
}

#[cfg(windows)]
fn user_name() -> String {
    env::var("USER")
        .or_else(|_| env::var("USERNAME"))
        .unwrap_or_else(|_| "user".to_string())
}

/// mpv listens on a Unix socket everywhere except Windows, where it exposes
/// a named pipe instead.
pub fn mpv_socket_path() -> PathBuf {
    #[cfg(windows)]
    {
        PathBuf::from(format!(r"\\.\pipe\mfe-player-{}", user_name()))
    }
    #[cfg(not(windows))]
    {
        runtime_dir().join("mpv.sock")
    }
}

/// Records which TUI session owns the shared mpv instance. A second,
/// concurrently running session must not hijack it, so it gets its own
/// private socket instead.
pub fn session_lock_path() -> PathBuf {
    runtime_dir().join("session.pid")
}

/// Written by a UI that is handing playback to the daemon (Ctrl+B, window
/// closed). A UI or daemon that starts during that brief teardown waits for
/// the old session to let go of mpv instead of spawning a private player.
pub fn handoff_path() -> PathBuf {
    runtime_dir().join("handoff.pid")
}

/// PID of the headless background player, when one is running.
pub fn daemon_pid_path() -> PathBuf {
    runtime_dir().join("daemon.pid")
}

/// Heartbeat written by the daemon every second. Its pid must match the pid
/// file and stay fresh, which makes stale pid files and PID reuse harmless.
pub fn daemon_heartbeat_path() -> PathBuf {
    runtime_dir().join("daemon.heartbeat")
}

/// Presence of this file asks a running daemon to shut down gracefully. It
/// works on every platform, including Windows where signals are unreliable.
pub fn daemon_stop_path() -> PathBuf {
    runtime_dir().join("daemon.stop")
}

/// Command inbox for the background daemon. `mfe next` / `mfe pause` / ... append
/// one line here; the daemon drains it on its next tick and then empties it.
pub fn daemon_control_path() -> PathBuf {
    runtime_dir().join("daemon.control")
}

pub fn daemon_log_path() -> PathBuf {
    config_dir().join("daemon.log")
}

pub fn private_mpv_socket_path(pid: u32) -> PathBuf {
    #[cfg(windows)]
    {
        PathBuf::from(format!(r"\\.\pipe\mfe-player-{}-{pid}", user_name()))
    }
    #[cfg(not(windows))]
    {
        runtime_dir().join(format!("mpv-{pid}.sock"))
    }
}

fn default_true() -> bool {
    true
}

fn default_media() -> String {
    "auto".to_string()
}

fn default_seek() -> f64 {
    5.0
}

fn default_long_seek() -> f64 {
    30.0
}

fn default_volume_step() -> f64 {
    5.0
}

fn default_max_volume() -> f64 {
    130.0
}

fn default_speed_step() -> f64 {
    0.1
}

fn default_theme() -> String {
    "mfe".to_string()
}

fn default_view() -> String {
    "search".to_string()
}

fn default_cava_position() -> String {
    "right".to_string()
}

fn default_cava_bars() -> u16 {
    28
}

fn default_eq() -> String {
    "flat".to_string()
}

/// User-editable settings, loaded from `~/.config/mfe-player/config.toml`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AppConfig {
    pub theme: String,
    pub seek_step: f64,
    pub long_seek_step: f64,
    pub volume_step: f64,
    /// Upper bound for the volume slider and the +/- keys. mpv can amplify
    /// above 100%, so this is a taste decision, not a hardware limit.
    pub max_volume: f64,
    /// Playback-speed step for `[` / `]` (0.05–0.5).
    pub speed_step: f64,
    pub default_view: String,
    pub prefetch: bool,
    pub radio: bool,
    pub mouse: bool,
    pub cava: bool,
    pub cava_position: String,
    pub cava_bars: u16,
    /// Start with the spectrum panel hidden (Alt+S toggles it at runtime).
    /// cava keeps running so the theme still reacts to the music.
    pub cava_hidden: bool,
    pub normalize: bool,
    pub eq: String,
    /// Custom EQ curve in dB for the ten bands (only used when eq = "custom").
    pub eq_gains: Vec<f64>,
    pub audio_device: String,
    /// Media integration: auto (use the platform backend) or off.
    pub media: String,
    /// Legacy switch for the MPRIS card. `false` disables every backend.
    pub mpris: bool,
    /// Folders scanned for local audio (FLAC/MP3/Opus/...). `~` is expanded.
    pub library_paths: Vec<String>,
    /// ListenBrainz user token. Empty disables scrobbling entirely.
    pub listenbrainz_token: String,
    /// Seconds of fade at each end of a track (0 disables smart fade).
    pub fade_seconds: f64,
    /// ReplayGain gain applied to files that carry the tags: off | track | album.
    pub replaygain: String,
    /// Leave the base background unpainted so the terminal's transparency
    /// (and therefore the wallpaper) shows through.
    pub transparent: bool,
    /// Explicit wallpaper for `theme = "wallpaper"`. Empty = ask the desktop.
    pub wallpaper: String,
    /// Shift the accent colours to the dominant colour of the current cover.
    pub ambient_art: bool,
    /// Animate the interface. Off keeps every frame static for calm setups,
    /// screen readers and remote shells.
    pub motion: bool,
    /// Glyph set: nerd (default), ascii, or auto.
    pub icons: String,
    /// Desktop notification on track change.
    pub notifications: bool,
    /// What to do when the queue ends: off | similar | taste.
    pub autoplay: String,
    /// How much the autoplay batch may wander outside the profile (0-1).
    pub autoplay_explore: f64,
    /// Suggest one deliberate out-of-profile probe every N autoplay picks.
    pub autoplay_probe_every: u32,
    /// Allow the occasional mismatch probe.
    pub autoplay_probe: bool,
    /// Learn from plays/skips. Turning this off keeps radio-style autoplay.
    pub taste_enabled: bool,
    /// Screen slowed/sped-up/nightcore/AI-cover re-uploads and other slop out
    /// of autoplay. The catalogue is still searchable and playable by hand.
    pub taste_filter: bool,
    /// Show the current track on Discord Rich Presence.
    pub discord: bool,
    /// Discord application client id (Developer Portal → OAuth2).
    pub discord_client_id: String,
    /// Large image asset key uploaded to that Discord application.
    pub discord_asset: String,
    /// Keep the presence visible while playback is paused.
    pub discord_show_paused: bool,
    /// Show the "Get mfe-player" buttons on the presence card.
    pub discord_show_buttons: bool,
    /// Hide presence while running a private/headless session.
    pub discord_when_private: bool,
}

impl Default for AppConfig {
    fn default() -> Self {
        Self {
            theme: default_theme(),
            seek_step: default_seek(),
            long_seek_step: default_long_seek(),
            volume_step: default_volume_step(),
            max_volume: default_max_volume(),
            speed_step: default_speed_step(),
            default_view: default_view(),
            prefetch: default_true(),
            radio: false,
            mouse: default_true(),
            cava: default_true(),
            cava_position: default_cava_position(),
            cava_bars: default_cava_bars(),
            cava_hidden: false,
            normalize: false,
            eq: default_eq(),
            eq_gains: Vec::new(),
            audio_device: String::new(),
            media: default_media(),
            mpris: default_true(),
            library_paths: Vec::new(),
            listenbrainz_token: String::new(),
            fade_seconds: 0.0,
            replaygain: "off".to_string(),
            transparent: true,
            wallpaper: String::new(),
            ambient_art: false,
            motion: true,
            icons: "nerd".to_string(),
            notifications: false,
            autoplay: "taste".to_string(),
            autoplay_explore: 0.12,
            autoplay_probe_every: 10,
            autoplay_probe: true,
            taste_enabled: true,
            taste_filter: true,
            discord: false,
            discord_client_id: String::new(),
            discord_asset: "mfe".to_string(),
            discord_show_paused: false,
            discord_show_buttons: true,
            discord_when_private: false,
        }
    }
}

const DEFAULT_CONFIG: &str = r#"# mfe-player configuration
# Edit and restart the app. Every key is optional.

# Colour theme: mfe | gruvbox | nord | mono | matrix | rose |
#               catppuccin | dracula | tokyo-night | solarized | amber | ocean |
#               auto (your terminal's own 16 colours) | wallpaper
theme = "mfe"

# Playback steps (seconds / percent).
seek_step = 5
long_seek_step = 30
volume_step = 5
# Ceiling for the volume meter and +/- keys (mpv amplifies above 100%).
max_volume = 130
# Playback-speed step for [ and ] (0.05–0.5).
speed_step = 0.1

# View shown at startup: search | queue | favorites | playlists | downloads |
# plugins | library | history | browse
default_view = "search"

# Resolve the next track while the current one plays (no silence between songs).
prefetch = true

# When the queue ends, keep playing related tracks (Spotify-style radio).
radio = false

# Autoplay when the queue ends and repeat is off: off | similar | taste.
# "taste" learns from what you finish, repeat and skip and keeps the vibe.
autoplay = "taste"

# Learn a local taste profile from plays and skips (stored in taste.json).
taste_enabled = true

# Keep slowed/sped-up/nightcore/AI-cover re-uploads out of autoplay. They stay
# searchable and playable; they just do not get recommended.
taste_filter = true

# How far the batch may wander outside the profile, and how often to try one
# deliberate out-of-profile track (0 disables the mismatch probe).
autoplay_explore = 0.12
autoplay_probe = true
autoplay_probe_every = 10

# Mouse: wheel scrolls, click selects, double-click plays, click the progress bar to seek.
mouse = true

# Spectrum visualiser (needs `cava` installed).
cava = true
cava_position = "right"   # right | left
cava_bars = 28
# Remove the spectrum panel from the layout completely (Alt+S toggles it).
# cava keeps capturing, so borders and the theme still pulse with the music.
cava_hidden = false

# Audio polish.
normalize = false          # loudness normalisation via mpv dynaudnorm
eq = "flat"                # flat | bass | vocal | night | loud
audio_device = ""          # empty = system default (e.g. "alsa/hdmi:CARD=HDMI")

# Desktop media keys / playerctl integration.
# media = "auto" uses the native backend: MPRIS on Linux, SMTC on Windows,
# Now Playing on macOS. "off" hides the media card entirely.
media = "auto"
mpris = true                # legacy switch; false disables every backend

# Local music folders (FLAC, MP3, Opus, Ogg, M4A...). Scanned on launch.
# Example: library_paths = ["~/Music", "/mnt/archive/albums"]
library_paths = []

# Optional: scrobble to ListenBrainz (https://listenbrainz.org/profile/).
# Paste your user token here and every play is submitted from a background
# thread. Leave empty to keep everything local.
listenbrainz_token = ""

# Smart fade: seconds of fade at the start and the end of every track.
# 0 = off, 2-4 = gentle, 6 = long. Cycle with Alt+F.
fade_seconds = 0

# ReplayGain for your own files: off | track | album. Cycle with Alt+R.
replaygain = "off"

# Custom ten-band EQ curve in dB. Tune it with Ctrl+E in the app.
eq_gains = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

# Let the terminal's transparency show your wallpaper through the app.
# On by default; toggle at runtime with Alt+W.
transparent = true

# Optional explicit wallpaper for theme = "wallpaper". Empty means "ask the
# compositor" (swww, hyprpaper, GNOME, Plasma, macOS, Windows).
wallpaper = ""

# Ambient tint: pull a vivid accent from the current album cover and let the
# theme follow the music. Grey covers are ignored. Toggle with Alt+A.
ambient_art = false

# Motion: gradients, marquees and borders react to cava's energy. Turn off for
# a completely still interface (screen readers, remote shells, calm setups).
# Toggle with Alt+M.
motion = true

# Glyphs: nerd (default), ascii (plain TTYs/screen readers), or auto.
icons = "nerd"

# Desktop notification when a new track starts (Linux, macOS, Windows).
notifications = false

# Discord Rich Presence. Create an application at
# https://discord.com/developers/applications, copy its client id, upload an
# image asset (default key "mfe"), then enable this. Nothing leaves your
# machine: presence is sent over Discord's local IPC socket.
discord = false
discord_client_id = ""
discord_asset = "mfe"
# Keep the card visible when paused, and show project buttons (max two).
discord_show_paused = false
discord_show_buttons = true
# Hide presence for private sessions (headless daemon keeps showing it).
discord_when_private = false
"#;

fn write_atomic(path: &std::path::Path, raw: &str) {
    let tmp = path.with_extension("toml.tmp");
    if fs::write(&tmp, raw).is_ok() {
        let _ = crate::platform::fs_util::replace_file(&tmp, path);
    }
}

pub fn load_config() -> (AppConfig, Option<String>) {
    let path = config_path();
    if !path.exists() {
        // First run (or a CLI command before the TUI has ever started).
        if let Some(parent) = path.parent() {
            let _ = fs::create_dir_all(parent);
        }
        write_atomic(&path, DEFAULT_CONFIG);
        return (AppConfig::default(), None);
    }
    match fs::read_to_string(&path) {
        Ok(raw) => match toml::from_str::<AppConfig>(&raw) {
            Ok(mut config) => {
                config.seek_step = config.seek_step.clamp(1.0, 600.0);
                config.long_seek_step = config.long_seek_step.clamp(1.0, 600.0);
                config.volume_step = config.volume_step.clamp(1.0, 50.0);
                config.max_volume = config.max_volume.clamp(20.0, 300.0);
                config.speed_step = config.speed_step.clamp(0.05, 0.5);
                config.cava_bars = config.cava_bars.clamp(4, 96);
                config.fade_seconds = config.fade_seconds.clamp(0.0, 15.0);
                config.replaygain = config.replaygain.to_ascii_lowercase();
                if !["off", "track", "album"].contains(&config.replaygain.as_str()) {
                    config.replaygain = "off".to_string();
                }
                config.autoplay = config.autoplay.to_ascii_lowercase();
                if !["off", "similar", "taste"].contains(&config.autoplay.as_str()) {
                    config.autoplay = "taste".to_string();
                }
                config.autoplay_explore = config.autoplay_explore.clamp(0.0, 1.0);
                config.autoplay_probe_every = config.autoplay_probe_every.clamp(3, 100);
                config.discord_client_id = config.discord_client_id.trim().to_string();
                config.discord_asset = config.discord_asset.trim().to_string();
                if config.discord_asset.is_empty() {
                    config.discord_asset = "mfe".to_string();
                }
                (config, None)
            }
            Err(err) => (
                AppConfig::default(),
                Some(format!("config.toml is invalid, using defaults: {err}")),
            ),
        },
        Err(err) => (
            AppConfig::default(),
            Some(format!("could not read config.toml: {err}")),
        ),
    }
}

/// Rewrite one `key` line in the config so user comments survive.
fn set_key_in_file(key: &str, value: &str) {
    let path = config_path();
    if let Some(parent) = path.parent() {
        let _ = fs::create_dir_all(parent);
    }
    // Start from the defaults when nothing has been written yet, so CLI
    // commands like `mfe discord on` work on a fresh machine.
    let raw = fs::read_to_string(&path).unwrap_or_else(|_| DEFAULT_CONFIG.to_string());
    let mut replaced = false;
    let mut out = String::new();
    for line in raw.lines() {
        let starts = line
            .trim_start()
            .strip_prefix(key)
            .and_then(|rest| rest.trim_start().strip_prefix('='));
        if !replaced && starts.is_some() {
            out.push_str(&format!("{key} = {value}\n"));
            replaced = true;
        } else {
            out.push_str(line);
            out.push('\n');
        }
    }
    if !replaced {
        out.push_str(&format!("{key} = {value}\n"));
    }
    write_atomic(&path, &out);
}

/// Rewrite just the `theme` line so user comments in config.toml survive.
pub fn set_theme_in_file(name: &str) {
    set_key_in_file("theme", &format!("\"{name}\""));
}

/// Persist an audio setting that can be cycled from the keyboard.
pub fn set_line(key: &str, value: &str) {
    set_key_in_file(key, value);
}

pub fn ensure_dirs() -> Result<()> {
    fs::create_dir_all(config_dir())
        .with_context(|| format!("creating {}", config_dir().display()))?;
    fs::create_dir_all(plugins_dir())
        .with_context(|| format!("creating {}", plugins_dir().display()))?;
    fs::create_dir_all(runtime_dir())
        .with_context(|| format!("creating {}", runtime_dir().display()))?;
    fs::create_dir_all(downloads_dir())
        .with_context(|| format!("creating {}", downloads_dir().display()))?;
    Ok(())
}

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

    #[test]
    fn transparency_is_the_default() {
        assert!(AppConfig::default().transparent);
        assert!(!AppConfig::default().ambient_art);
    }

    #[test]
    fn shipped_config_parses_with_the_tuning_knobs() {
        let cfg: AppConfig = toml::from_str(DEFAULT_CONFIG).expect("shipped config parses");
        assert_eq!(cfg.max_volume, 130.0);
        assert_eq!(cfg.speed_step, 0.1);
        assert_eq!(cfg.default_view, "search");
    }
}