trill 0.7.3

Lean terminal Spotify client: Spotify's own player, small and quiet when idle
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
//! trill — a lean terminal Spotify player.
//!
//! Design notes (why it's light):
//! - single-threaded tokio runtime for UI + network
//! - one blocking thread for terminal input (zero CPU while idle)
//! - redraws only on input / player events / 1 Hz while playing; nothing polls Spotify
//! - browsing uses librespot's session (batched metadata), not the rate-limited Web API
//! - playback: Spotify's official Soloist daemon (works where librespot keys are refused),
//!   or in-process librespot (1-worker runtime, PulseAudio protocol straight to PipeWire)

mod api;
mod app;
mod audio;
mod auth;
mod config;
mod discover;
mod engine;
mod library;
mod theme;
mod mpris;
#[cfg(target_os = "linux")]
mod relay;
mod ui;
mod update;

use std::{env, fs, process::Command, sync::Arc, time::Duration};

use crossterm::event::{DisableMouseCapture, EnableMouseCapture, Event};
use librespot_core::{Session, SessionConfig, cache::Cache};
use librespot_playback::{
    audio_backend,
    config::{AudioFormat, PlayerConfig},
    mixer::{self, MixerConfig},
    player::Player,
};
use tokio::{
    sync::{Mutex, mpsc},
    time::{MissedTickBehavior, interval, timeout},
};

use crate::{
    app::App,
    auth::WebToken,
    config::Config,
    engine::{Engine, EngineEvent, LibrespotEvents, SoloistOpts},
};

// Spotify publishes Linux x86_64/arm64, Apple Silicon and Windows x86_64 builds (no Intel Mac one).
const SOLOIST_URL: &str = if cfg!(windows) {
    "https://soloist-builds.spotifycdn.com/soloist_release_windows_x86_64.zip"
} else if cfg!(target_os = "macos") {
    "https://soloist-builds.spotifycdn.com/soloist_release_osx_arm64.tar.gz"
} else if cfg!(target_arch = "aarch64") {
    "https://soloist-builds.spotifycdn.com/soloist_release_arm64.tar.gz"
} else {
    "https://soloist-builds.spotifycdn.com/soloist_release_x86_64.tar.gz"
};

/// Hands freed heap pages back to the OS (glibc only).
pub fn trim_heap() {
    // SAFETY: malloc_trim only releases free heap memory.
    #[cfg(target_os = "linux")]
    unsafe {
        libc::malloc_trim(0);
    }
}

fn main() {
    // SAFETY: no other threads exist yet.
    unsafe {
        for (k, v) in [
            ("TOKIO_WORKER_THREADS", "1"),
            ("PULSE_PROP_application.name", "trill"),
            ("PULSE_PROP_stream.description", "Music"),
            ("PULSE_PROP_media.role", "music"),
            ("PULSE_PROP_application.icon_name", "audio-x-generic"),
        ] {
            if env::var_os(k).is_none() {
                env::set_var(k, v);
            }
        }
    }

    // after set_var: AppKit may start threads of its own
    #[cfg(target_os = "macos")]
    let mac_app = mpris::prepare();

    let has = |flag: &str| env::args().any(|a| a == flag);
    if has("-V") || has("--version") {
        println!("trill {}", env!("CARGO_PKG_VERSION"));
        return;
    }
    if has("-h") || has("--help") {
        println!("trill — lean terminal Spotify player (Premium required)\n");
        println!("  trill                   start (first run opens a browser to log in)");
        println!("  trill --update          update trill to the latest release");
        println!("  trill --update-soloist  download/refresh Spotify's Soloist player (every <90 days)");
        println!("  trill --pair            pair Soloist once via the Spotify app on your phone");
        println!("  trill --logout          forget saved logins");
        println!("  trill --version         which version this is\n");
        println!("Config: ~/.config/trill/config   Logs: TRILL_LOG=debug trill");
        return;
    }

    let cfg = Config::load();
    config::init_logger(&cfg.cache_dir);

    if has("--logout") {
        let _ = fs::remove_file(cfg.cache_dir.join("credentials.json"));
        let _ = fs::remove_file(cfg.cache_dir.join("webapi_refresh_token"));
        println!("Logged out of trill. (Soloist pairing kept; re-pair with --pair.)");
        return;
    }
    if has("--update") {
        std::process::exit(update::run(&cfg.cache_dir));
    }
    if has("--update-soloist") {
        std::process::exit(update_soloist(&cfg));
    }
    if has("--pair") {
        std::process::exit(pair_soloist(&cfg));
    }
    // Hidden diagnostics: which image protocol / font size this terminal reports.
    if has("--debug-term") {
        let t0 = std::time::Instant::now();
        match query_terminal_images(&cfg.cache_dir) {
            Some(p) => eprintln!("{:?} font {:?} in {} ms", p.protocol_type(), p.font_size(), t0.elapsed().as_millis()),
            None => eprintln!("no picker in {} ms", t0.elapsed().as_millis()),
        }
        return;
    }

    // Every helper thread gets its own malloc arena that is never handed back; with a few
    // short-lived DNS/file threads that's megabytes of RSS for nothing. Two arenas is plenty.
    // A fixed mmap threshold also stops glibc raising it (and the trim threshold with it) after
    // each decoded cover is freed, which left ~7 MB of free heap resident in the second arena.
    // SAFETY: called before any other threads exist.
    #[cfg(target_os = "linux")]
    unsafe {
        libc::mallopt(libc::M_ARENA_MAX, 2);
        libc::mallopt(libc::M_MMAP_THRESHOLD, 256 * 1024);
    }
    let go = move || {
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            // DNS lookups and file I/O run here; parallel requests shouldn't mean a thread each.
            .max_blocking_threads(4)
            .build()
            .expect("tokio runtime");
        // LocalSet: the MPRIS server is single-threaded (!Send), like the rest of the app.
        let local = tokio::task::LocalSet::new();
        let code = local.block_on(&rt, run(cfg));
        std::process::exit(code);
    };
    // macOS delivers media keys on the main thread's event loop, so trill moves off it.
    #[cfg(target_os = "macos")]
    if mac_app {
        std::thread::Builder::new().name("trill".into()).stack_size(8 << 20).spawn(go).expect("thread");
        mpris::run_main();
    }
    go();
}

fn soloist_opts(cfg: &Config) -> Result<SoloistOpts, String> {
    let api_key = cfg.soloist_api_key().ok_or_else(|| {
        format!(
            "No Soloist API key. Create one at https://developer.spotify.com/dashboard (Soloist API Key page)\n\
             and save it to {}  (chmod 600)",
            cfg.config_dir.join("soloist_api_key").display()
        )
    })?;
    let bin = cfg
        .soloist_bin()
        .ok_or("Soloist isn't installed. Run: trill --update-soloist")?;
    Ok(SoloistOpts {
        bin,
        api_key,
        device_name: cfg.device_name.clone(),
        data_dir: cfg.data_dir.join("soloist-data"),
        cache_dir: cfg.cache_dir.join("soloist"),
        cache_mb: cfg.soloist_cache_mb,
        ws: cfg.soloist_ws.clone(),
        pipewire_device: None,
        initial_volume: None,
        env: Vec::new(),
    })
}

fn update_soloist(cfg: &Config) -> i32 {
    let dir = cfg.soloist_install_dir();
    let staging = dir.join("staging");
    println!("Downloading Soloist from Spotify ({SOLOIST_URL})…");
    if let Err(e) = fetch_and_unpack(SOLOIST_URL, &staging) {
        eprintln!("{e}");
        return 1;
    }
    let found = walk_find(&staging, config::SOLOIST_EXE);
    let Some(bin) = found else {
        eprintln!("No `soloist` executable in the archive; contents left in {}", staging.display());
        return 1;
    };
    let target = dir.join(config::SOLOIST_EXE);
    if let Err(e) = fs::rename(&bin, &target) {
        eprintln!("install to {}: {e}", target.display());
        return 1;
    }
    // keep bundled licence notices next to the binary, drop the rest
    let _ = fs::remove_dir_all(&staging);
    let _ = Command::new(&target).arg("--version").status();
    println!("Installed {}", target.display());
    0
}

/// Download `url` into `staging` (emptied first) and unpack it there.
pub(crate) fn fetch_and_unpack(url: &str, staging: &std::path::Path) -> Result<(), String> {
    let _ = fs::remove_dir_all(staging);
    fs::create_dir_all(staging).map_err(|e| format!("{}: {e}", staging.display()))?;
    let archive = staging.join(url.rsplit('/').next().unwrap_or("download"));
    let ok = Command::new("curl").args(["-fL", "--progress-bar", "-o"]).arg(&archive).arg(url).status().is_ok_and(|s| s.success())
        // tar detects gzip or zip itself (GNU tar, macOS bsdtar and Windows' tar.exe alike)
        && Command::new("tar").arg("-xf").arg(&archive).arg("-C").arg(staging).status().is_ok_and(|s| s.success());
    if ok { Ok(()) } else { Err(format!("Download or extract of {url} failed.")) }
}

pub(crate) fn walk_find(dir: &std::path::Path, name: &str) -> Option<std::path::PathBuf> {
    for e in fs::read_dir(dir).ok()?.flatten() {
        let p = e.path();
        if p.is_dir() {
            if let Some(f) = walk_find(&p, name) {
                return Some(f);
            }
        } else if p.file_name().is_some_and(|n| n == name) {
            return Some(p);
        }
    }
    None
}

fn pair_soloist(cfg: &Config) -> i32 {
    let opts = match soloist_opts(cfg) {
        Ok(o) => o,
        Err(e) => {
            eprintln!("{e}");
            return 1;
        }
    };
    let _ = fs::create_dir_all(&opts.data_dir);
    let _ = fs::create_dir_all(&opts.cache_dir);
    println!("Pairing: open Spotify on your phone (same Wi-Fi), tap the devices icon,");
    println!("and pick “{}”. This window finishes by itself once paired.\n", opts.device_name);
    match opts.base_command().arg("-p").status() {
        Ok(s) if s.success() => {
            println!("\nPaired. Run `trill`.");
            0
        }
        Ok(s) => {
            eprintln!("Soloist exited with {s}");
            s.code().unwrap_or(1)
        }
        Err(e) => {
            eprintln!("can't run {}: {e}", opts.bin.display());
            1
        }
    }
}

/// Which terminal this is, as far as the environment tells: the key under which a terminal that
/// didn't answer the image query is remembered.
fn terminal_id() -> String {
    let get = |k: &str| env::var(k).unwrap_or_default();
    let has = |k: &'static str| if env::var_os(k).is_some_and(|v| !v.is_empty()) { k } else { "" };
    [get("TERM"), get("TERM_PROGRAM"), get("TERM_PROGRAM_VERSION"), get("LC_TERMINAL"), get("KONSOLE_VERSION"), get("VTE_VERSION")]
        .into_iter()
        .chain(["TMUX", "WT_SESSION", "KITTY_WINDOW_ID", "WEZTERM_EXECUTABLE", "ITERM_SESSION_ID", "GHOSTTY_RESOURCES_DIR"].map(|k| has(k).to_string()))
        .collect::<Vec<_>>()
        .join("|")
}

/// Terminals that didn't answer the image query, one `terminal_id` per line. Re-asked after a
/// week, in case one learns to answer (or tmux gets attached from a terminal that does).
fn silent_terminals(cache: &std::path::Path) -> (std::path::PathBuf, String) {
    let file = cache.join("silent_terminals");
    let fresh = fs::metadata(&file).and_then(|m| m.modified()).is_ok_and(|t| t.elapsed().is_ok_and(|d| d < Duration::from_secs(7 * 86400)));
    let text = if fresh { fs::read_to_string(&file).unwrap_or_default() } else { String::new() };
    (file, text)
}

/// Which image protocol the terminal supports. Terminals answer in a few ms; if one doesn't,
/// ratatui-image gives up but leaves a thread blocked reading stdin, which would eat the
/// first keypresses. A Device Status Report query (which every terminal, and tmux itself,
/// answers) completes that read so the thread exits before we start reading keys.
/// A terminal that didn't answer is remembered, so the next start skips the ~0.5 s wait and
/// goes straight to what the timeout would have given.
fn query_terminal_images(cache: &std::path::Path) -> Option<ratatui_image::picker::Picker> {
    use ratatui_image::picker::{Picker, ProtocolType, cap_parser::QueryStdioOptions};
    use std::io::Write;
    const TIMEOUT: Duration = Duration::from_millis(400);
    let t0 = std::time::Instant::now();
    let id = terminal_id();
    let (file, silent) = silent_terminals(cache);
    let mut picker = if silent.lines().any(|l| l == id) {
        // ratatui-image's own fallback: the font size from the window's pixel size, if known
        #[allow(deprecated)]
        Some(match crossterm::terminal::window_size() {
            Ok(w) if w.width > 0 && w.height > 0 && w.columns > 0 && w.rows > 0 => {
                Picker::from_fontsize(ratatui_image::FontSize::new(w.width / w.columns, w.height / w.rows))
            }
            _ => Picker::halfblocks(),
        })
    } else {
        let p = Picker::from_query_stdio_with_options(QueryStdioOptions { timeout: TIMEOUT, ..Default::default() }).ok();
        if t0.elapsed() >= TIMEOUT {
            let mut out = std::io::stdout();
            let _ = out.write_all(b"\x1b[5n");
            let _ = out.flush();
            std::thread::sleep(Duration::from_millis(100));
            let _ = fs::create_dir_all(cache);
            let _ = fs::write(&file, format!("{silent}{id}\n"));
        }
        p
    };
    // Konsole draws iTerm2 inline images (its sixel/kitty support is buggy, so ratatui-image
    // rules those out) but has no env var announcing it, so ratatui-image falls back to
    // half-blocks. Use iTerm2 there (not through tmux, which would need passthrough).
    if let Some(p) = picker.as_mut()
        && env::var_os("KONSOLE_VERSION").is_some()
        && !p.tmux_detected()
        && p.protocol_type() == ProtocolType::Halfblocks
    {
        p.set_protocol_type(ProtocolType::Iterm2);
    }
    // VS Code is guessed to be iTerm2 from TERM_PROGRAM alone, but it only draws images with
    // `terminal.integrated.enableImages` on, and then it also answers the query with sixel.
    // A guess that the query didn't back up would draw nothing, so use half-blocks there.
    if let Some(p) = picker.as_mut()
        && env::var("TERM_PROGRAM").is_ok_and(|t| t == "vscode")
        && p.protocol_type() == ProtocolType::Iterm2
    {
        p.set_protocol_type(ProtocolType::Halfblocks);
    }
    picker
}

async fn run(cfg: Config) -> i32 {
    let audio_dir = (cfg.audio_cache_mb > 0).then(|| cfg.cache_dir.join("audio"));
    let limit = (cfg.audio_cache_mb > 0).then(|| cfg.audio_cache_mb * 1024 * 1024);
    let cache = match Cache::new(Some(&cfg.cache_dir), Some(&cfg.cache_dir), audio_dir.as_ref(), limit) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("cache dir {}: {e}", cfg.cache_dir.display());
            return 1;
        }
    };

    // Stream buffers go to disk; clear leftovers from a previous crash.
    let tmp_dir = cfg.cache_dir.join("tmp");
    let _ = fs::remove_dir_all(&tmp_dir);
    let _ = fs::create_dir_all(&tmp_dir);
    let session_cfg = SessionConfig { tmp_dir, ..SessionConfig::default() };

    let (eng_tx, mut eng_rx) = mpsc::unbounded_channel::<EngineEvent>();
    let saved_vol = cache.volume().map(|v| (v as u32 * 100 + 32767) / 65535).unwrap_or(50);

    let audio_settings = audio::AudioSettings::load(&cfg.data_dir);
    // The EQ only runs when it would change the sound (Flat = no extra process at all).
    let eq = if cfg.eq && !audio_settings.is_flat() {
        match audio::Eq::start(&cfg.cache_dir, &audio_settings.gains()) {
            Ok(eq) => Some(eq),
            Err(e) => {
                log::warn!("EQ disabled: {e}");
                None
            }
        }
    } else {
        None
    };
    let eq_sink = eq.as_ref().map(|_| audio::EQ_NODE.to_string());

    // Soloist doesn't need our librespot session, so start it while we log in (~0.4 s saved).
    let mut soloist_cfg = None;
    // Hidden: `trill --preview <track uri> [<list uri> <title>]` shows the UI with that song as "now playing" but
    // plays nothing, starts no Soloist and claims no MPRIS name, so it can run beside a real
    // trill (for screenshots and layout checks).
    let preview = env::args().position(|a| a == "--preview").map(|i| env::args().nth(i + 1).unwrap_or_default());
    if cfg.use_soloist() && preview.is_none() {
        match soloist_opts(&cfg) {
            Ok(mut o) => {
                o.pipewire_device = eq_sink.clone();
                o.initial_volume = Some(saved_vol);
                soloist_cfg = Some(o);
            }
            Err(e) => {
                eprintln!("{e}");
                return 1;
            }
        }
    }
    // Private mode: a session still running from last time starts Soloist through the relay.
    let private_until = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(audio_settings.private_until));
    #[cfg(target_os = "linux")]
    let mut relay = None;
    #[cfg(target_os = "linux")]
    if let Some(o) = soloist_cfg.as_mut()
        && audio_settings.private_until > app::unix_now()
    {
        match relay::Relay::start(&cfg.data_dir, private_until.clone()).await {
            Ok(r) => {
                o.env = r.env();
                relay = Some(r);
            }
            Err(e) => log::warn!("private-mode relay: {e}"),
        }
    }
    // Ask the terminal which image protocol it speaks (kitty / sixel / iTerm2, else
    // half-block characters) while we log in. Must finish before we read key events.
    let mut picker_query = (cfg.art && std::io::IsTerminal::is_terminal(&std::io::stdout())).then(|| {
        let dir = cfg.cache_dir.clone();
        std::thread::Builder::new().name("term-query".into()).spawn(move || query_terminal_images(&dir))
    });
    let session = Session::new(session_cfg.clone(), Some(cache.clone()));
    let cached_user = cache.credentials().and_then(|c| c.username);
    let early = soloist_cfg.clone().zip(cached_user).map(|(o, user)| {
        audio::write_soloist_prefs(&o.data_dir, &user, audio_settings.crossfade_s, cfg.bitrate);
        let tx = eng_tx.clone();
        async move { engine::start_soloist(&o, tx).await }
    });
    // With a saved login nothing prompts, so draw the library at once instead of after the
    // ~0.4 s login. The image query must finish first: both talk to the terminal.
    let mut img_picker = None;
    let mut term = None;
    let (login, early) = match early {
        Some(start) => {
            if std::io::IsTerminal::is_terminal(&std::io::stdout()) && !env::args().any(|a| a.starts_with("--debug")) {
                img_picker = picker_query.take().and_then(|t| t.ok()).and_then(|t| t.join().ok()).flatten();
                theme::set(theme::colors(audio_settings.theme, audio_settings.tint));
                let mut t = ratatui::init();
                let names: Vec<String> = api::read_playlist_cache(&cfg.cache_dir).unwrap_or_default().into_iter().map(|p| p.1).collect();
                let _ = t.draw(|f| ui::draw_splash(f, &names));
                term = Some(t);
            } else {
                eprintln!("Connecting and starting Soloist…");
            }
            let (l, e) = tokio::join!(auth::connect(&session, &cache), start);
            (l, Some(e))
        }
        None => (auth::connect(&session, &cache).await, None),
    };
    if let Err(e) = login {
        if term.take().is_some() {
            ratatui::restore();
        }
        if let Some(Ok(e)) = early {
            e.shutdown();
        }
        eprintln!("Login failed: {e}");
        return 1;
    }

    let web = match &cfg.client_id {
        Some(id) => match WebToken::load(id, &cfg.cache_dir).await {
            Ok(t) => Some(Arc::new(Mutex::new(t))),
            Err(e) => {
                log::warn!("own client_id auth failed: {e}");
                if term.is_none() {
                    eprintln!("Own client_id auth failed ({e}); search will use the fallback.");
                }
                None
            }
        },
        None => None,
    };

    let mut soloist = None;
    let engine = if let Some(opts) = soloist_cfg {
        let started = match early {
            Some(r) => r,
            None => {
                audio::write_soloist_prefs(&opts.data_dir, &session.username(), audio_settings.crossfade_s, cfg.bitrate);
                eprintln!("Starting Soloist…");
                engine::start_soloist(&opts, eng_tx.clone()).await
            }
        };
        let e = match started {
            Ok(e) => e,
            Err(e) => {
                if term.take().is_some() {
                    ratatui::restore();
                }
                eprintln!("{e}");
                return 1;
            }
        };
        soloist = Some(opts);
        e
    } else {
        let mixer = match mixer::find(None).map(|m| m(MixerConfig::default())) {
            Some(Ok(m)) => m,
            _ => {
                eprintln!("couldn't create volume mixer");
                return 1;
            }
        };
        mixer.set_volume((saved_vol * u16::MAX as u32 / 100) as u16);
        // The one backend in the build: PulseAudio on Linux, CoreAudio (rodio) on macOS.
        let Some(backend) = audio_backend::find(None) else {
            eprintln!("no audio backend in this build");
            return 1;
        };
        let player_cfg = PlayerConfig {
            bitrate: cfg.bitrate,
            normalisation: cfg.normalise,
            ..PlayerConfig::default()
        };
        let sink = eq_sink.clone();
        let player = Player::new(player_cfg, session.clone(), mixer.get_soft_volume(), move || {
            backend(sink, AudioFormat::default())
        });
        let mut rx = player.get_player_event_channel();
        let tx = eng_tx.clone();
        tokio::spawn(async move {
            let mut map = LibrespotEvents::default();
            while let Some(ev) = rx.recv().await {
                if let Some(ev) = map.map(ev)
                    && tx.send(ev).is_err()
                {
                    break;
                }
            }
        });
        Engine::Librespot { player, mixer }
    };

    // Hidden diagnostics: `trill --debug-lib <action> <args…>` exercises library writes.
    if let Some(i) = env::args().position(|a| a == "--debug-lib") {
        let a: Vec<String> = env::args().skip(i + 1).collect();
        let t0 = std::time::Instant::now();
        let res = match a.first().map(String::as_str) {
            Some("like") => library::set_liked(&session, &a[1], true).await,
            Some("unlike") => library::set_liked(&session, &a[1], false).await,
            Some("add") => library::playlist_add(&session, &a[1], &a[2]).await,
            Some("rm") => library::playlist_remove(&session, &a[1], &a[2]).await,
            Some("isliked") => {
                let liked = format!("spotify:user:{}:collection", session.username());
                api::context_tracks(&session, &liked).await.map(|t| {
                    let n = t.iter().filter(|t| a[1..].contains(&t.uri)).count();
                    eprintln!("{} liked; {n} of {} given are liked", t.len(), a.len() - 1);
                })
            }
            Some("recs") => {
                let rows = api::recommendations(&session, &a[1], a.get(2).map_or("", String::as_str)).await;
                eprintln!("{} recs; first: {:?}", rows.len(), rows.iter().take(6).map(|r| format!("{} — {}", r.title, r.artist)).collect::<Vec<_>>());
                Ok(())
            }
            Some("pins") => library::pins(&session).await.map(|p| p.iter().for_each(|u| eprintln!("{u}"))),
            Some("all") => match api::context_rows(&session, &a[1], &[]).await {
                Ok(rows) => {
                    let all = api::expand(&session, &rows).await.unwrap_or_default();
                    eprintln!("{} tracks; first: {:?}", all.len(), all.iter().take(12).map(|r| r.title.as_str()).collect::<Vec<_>>());
                    Ok(())
                }
                Err(e) => Err(e),
            },
            Some("rows") => api::context_rows(&session, &a[1], &[]).await.map(|rows| {
                eprintln!("{} rows", rows.len());
                rows.iter().take(40).for_each(|r| eprintln!("{:?} {} | {} | {} | {}", r.kind, r.title, r.artist, r.album, r.uri));
            }),
            Some("set") => library::collection(&session, &a[1]).await.map(|p| {
                let mut kinds = std::collections::BTreeMap::<&str, usize>::new();
                p.iter().for_each(|u| *kinds.entry(u.split(':').nth(1).unwrap_or("?")).or_default() += 1);
                eprintln!("{} items {kinds:?}; first: {:?}", p.len(), p.iter().filter(|u| !u.contains(":track:")).take(4).collect::<Vec<_>>());
            }),
            Some("lyrics") => library::lyrics(&session, &a[1]).await.map(|l| match l {
                Some(l) => eprintln!("synced={} lines={} provider={}", l.synced, l.lines.len(), l.provider),
                None => eprintln!("no lyrics"),
            }),
            _ => match api::playlists(&session).await {
                Ok(p) => {
                    for (uri, name, editable, pinned) in &p {
                        eprintln!("{} {} {uri} {name}", if *editable { "EDIT" } else { "    " }, if *pinned { "PIN" } else { "   " });
                    }
                    Ok(())
                }
                Err(e) => Err(e),
            },
        };
        eprintln!("{res:?} in {} ms", t0.elapsed().as_millis());
        engine.shutdown();
        return 0;
    }

    // Hidden diagnostics: `trill --debug-tint <search>` prints the cover-theme colour per result.
    if let Some(i) = env::args().position(|a| a == "--debug-tint") {
        let q = env::args().skip(i + 1).collect::<Vec<_>>().join(" ");
        let rows = api::search(&session, None, &q).await.map(|r| r.0).unwrap_or_default();
        let mut seen = std::collections::HashSet::new();
        for r in rows.iter().filter(|r| r.art.as_ref().is_some_and(|u| seen.insert(u.clone()))).take(6) {
            let url = r.art.clone().unwrap_or_default();
            let Ok(bytes) = session.spclient().request_url(&url).await else { continue };
            let t0 = std::time::Instant::now();
            let Ok(img) = image::load_from_memory(&bytes) else { continue };
            let t1 = t0.elapsed();
            let c = theme::cover_tint(&img);
            let t2 = t0.elapsed() - t1;
            let (a, b) = theme::colors(theme::COVER, Some(c));
            println!(
                "\x1b[48;2;{};{};{}m      \x1b[48;2;{};{};{}m   \x1b[0m {:?} decode {:?} tint {:?}  {} — {}  {url}",
                a[0], a[1], a[2], b[0], b[1], b[2], c, t1, t2, r.title, r.artist
            );
        }
        engine.shutdown();
        return 0;
    }

    // Hidden diagnostics: `trill --debug-get <spclient endpoint | url>` prints a raw response.
    if let Some(i) = env::args().position(|a| a == "--debug-get") {
        let target = env::args().nth(i + 1).unwrap_or_default();
        let t0 = std::time::Instant::now();
        let res = if target.starts_with("http") {
            session.spclient().request_url(&target).await
        } else {
            session.spclient().request_as_json(&http::Method::GET, &target, None, None).await
        };
        match res {
            Ok(b) => {
                eprintln!("ok in {} ms, {} bytes", t0.elapsed().as_millis(), b.len());
                println!("{}", String::from_utf8_lossy(&b));
            }
            Err(e) => eprintln!("error in {} ms: {e}", t0.elapsed().as_millis()),
        }
        engine.shutdown();
        return 0;
    }

    // Hidden diagnostics: `trill --debug-context <uri>` prints raw context-resolve track metadata.
    if let Some(i) = env::args().position(|a| a == "--debug-context") {
        let mut uri = env::args()
            .nth(i + 1)
            .unwrap_or_else(|| format!("spotify:user:{}:collection", session.username()));
        if uri == "playlist" {
            let lists = api::playlists(&session).await.unwrap_or_default();
            eprintln!("first playlists: {:?}", lists.iter().take(3).collect::<Vec<_>>());
            uri = lists.first().map(|l| l.0.clone()).unwrap_or_default();
        }
        match session.spclient().get_context(&uri).await {
            Ok(ctx) => {
                eprintln!("context metadata: {:?}", ctx.metadata);
                for (pi, page) in ctx.pages.iter().enumerate().take(3) {
                    eprintln!("page {pi}: {} tracks, page_url={:?} next={:?} meta={:?}", page.tracks.len(), page.page_url(), page.next_page_url(), page.metadata);
                    for t in page.tracks.iter().take(3) {
                        eprintln!("  {} uid={} meta={:?}", t.uri(), t.uid(), t.metadata);
                    }
                    if let Some(t) = page.tracks.last() {
                        eprintln!("  … last: {} meta={:?}", t.uri(), t.metadata);
                    }
                }
            }
            Err(e) => eprintln!("error: {e}"),
        }
        engine.shutdown();
        return 0;
    }

    // Hidden diagnostics: `trill --debug-play [uri]` plays one track headless and prints events.
    if let Some(i) = env::args().position(|a| a == "--debug-play") {
        let uri = match env::args().nth(i + 1) {
            Some(u) => u,
            None => {
                let liked = format!("spotify:user:{}:collection", session.username());
                match api::context_track_uris(&session, &liked).await {
                    Ok(u) if !u.is_empty() => u[0].clone(),
                    other => {
                        eprintln!("couldn't resolve liked songs: {other:?}");
                        return 1;
                    }
                }
            }
        };
        let secs: u64 = env::var("TRILL_DEBUG_SECS").ok().and_then(|s| s.parse().ok()).unwrap_or(12);
        eprintln!("loading {uri}");
        engine.load(&uri);
        // TRILL_DEBUG_SEEK_END=1: jump to 6 s before the end to observe end-of-track events.
        let seek_lead: Option<u32> = env::var("TRILL_DEBUG_SEEK_END").ok().map(|v| v.parse().unwrap_or(6000));
        let mut seek_end = seek_lead.is_some();
        let end = tokio::time::Instant::now() + Duration::from_secs(secs);
        let t0 = std::time::Instant::now();
        while let Ok(Some(ev)) = tokio::time::timeout_at(end, eng_rx.recv()).await {
            eprintln!("[{:>6} ms] event: {ev:?}", t0.elapsed().as_millis());
            if seek_end
                && let EngineEvent::Position { playing: Some(true), .. } = ev
            {
                seek_end = false;
                // duration comes from our own metadata so it works on both engines
                let rows = api::track_rows(&session, vec![uri.clone()]).await.unwrap_or_default();
                if let Some(r) = rows.first() {
                    tokio::time::sleep(Duration::from_secs(2)).await;
                    let lead = seek_lead.unwrap_or(6000);
                    eprintln!("debug: seeking to {} of {}", r.duration_ms.saturating_sub(lead), r.duration_ms);
                    engine.seek(r.duration_ms.saturating_sub(lead));
                }
            }
        }
        engine.stop();
        tokio::time::sleep(Duration::from_millis(300)).await;
        engine.shutdown();
        return 0;
    }

    // Terminal input on one blocking thread: sleeps in read() until a key arrives.
    let img_picker = img_picker.or_else(|| picker_query.and_then(|t| t.ok()).and_then(|t| t.join().ok()).flatten());
    let (key_tx, mut key_rx) = mpsc::unbounded_channel();
    let _ = std::thread::Builder::new().name("input".into()).spawn(move || {
        while let Ok(ev) = crossterm::event::read() {
            if key_tx.send(ev).is_err() {
                break;
            }
        }
    });

    // reuse the startup frame's terminal unless the login fallback had to put it away
    let mut term = term.filter(|_| crossterm::terminal::is_raw_mode_enabled().unwrap_or(false)).unwrap_or_else(ratatui::init);
    if cfg.mouse {
        let _ = crossterm::execute!(std::io::stdout(), EnableMouseCapture);
        // ratatui's panic hook restores the terminal but not mouse reporting, which would leak into the shell
        let hook = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |p| {
            let _ = crossterm::execute!(std::io::stdout(), DisableMouseCapture);
            hook(p)
        }));
    }
    let (tx, mut rx) = mpsc::unbounded_channel();
    let mut app = App::new(session, engine, saved_vol, web, tx, audio_settings, eq);
    app.eq_allowed = cfg.eq;
    app.remap = cfg.remap.clone();
    app.private_shared = private_until;
    #[cfg(target_os = "linux")]
    {
        app.relay_on = relay.is_some();
    }
    app.soloist_missing = cfg.soloist_missing();
    app.cache_dir = Some(cfg.cache_dir.clone());
    app.not_interested = discover::not_interested(&cfg.data_dir);
    app.data_dir = Some(cfg.data_dir.clone());
    app.art_on = img_picker.is_some() && app.audio.art;
    app.img_picker = img_picker;
    app.load_playlists();
    app.load_liked();
    app.check_update();
    let (remote_tx, mut remote_rx) = mpsc::unbounded_channel();
    let mut desktop = None;
    match &preview {
        Some(uri) => {
            app.now = api::track_rows(&app.session, vec![uri.clone()]).await.ok().and_then(|r| r.into_iter().next());
            // optional: a list to open, and its title (`--preview <track> <list uri> <title>`)
            let mut rest = env::args().skip_while(|a| a != "--preview").skip(2);
            if let (Some(list), Some(title)) = (rest.next(), rest.next()) {
                app.open(list, title, false, false);
            }
        }
        None => desktop = mpris::Mpris::new(remote_tx).await,
    }

    // Closing the terminal window (SIGHUP), `kill` (SIGTERM) or closing the Windows console
    // quits like `q`: playback stops first, so Spotify (and Discord) don't think it's still playing.
    let (quit_tx, mut quit_rx) = mpsc::unbounded_channel::<&str>();
    tokio::spawn(async move {
        #[cfg(unix)]
        {
            use tokio::signal::unix::{SignalKind, signal};
            if let (Ok(mut hup), Ok(mut term)) = (signal(SignalKind::hangup()), signal(SignalKind::terminate())) {
                let why = tokio::select! {
                    _ = hup.recv() => "terminal closed",
                    _ = term.recv() => "terminated",
                };
                let _ = quit_tx.send(why);
            }
        }
        #[cfg(windows)]
        if let Ok(mut close) = tokio::signal::windows::ctrl_close() {
            close.recv().await;
            let _ = quit_tx.send("console closed");
        }
    });

    let mut tick = interval(Duration::from_secs(1));
    tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
    // When the last reconnect was tried (one try per 15 s at most).
    let mut reconnect_at: Option<std::time::Instant> = None;
    let mut dirty = true;

    loop {
        if dirty {
            let _ = term.draw(|f| ui::draw(f, &mut app));
            // after drawing: the UI has said how much room the cover gets
            app.refresh_media();
            if let Some(d) = desktop.as_mut() {
                d.sync(&app).await;
            }
            dirty = false;
        }
        if app.quit {
            app.save_prefs(); // keeps the last cover colour for the next start
            break;
        }
        // Private mode turned on: start the relay and restart Soloist through it (once).
        #[cfg(target_os = "linux")]
        if std::mem::take(&mut app.want_relay)
            && relay.is_none()
            && let Some(opts) = soloist.as_mut()
        {
            match relay::Relay::start(&cfg.data_dir, app.private_shared.clone()).await {
                Ok(r) => {
                    opts.env = r.env();
                    relay = Some(r);
                    app.relay_on = true;
                    app.restart_at = Some(std::time::Instant::now());
                }
                Err(e) => app.status = format!("Private session on, but Discord can still see Soloist: {e}"),
            }
            dirty = true;
        }
        if app.restart_due() {
            if let Some(opts) = soloist.as_mut() {
                if app.eq_wanted() {
                    match audio::Eq::start(&cfg.cache_dir, &app.audio.gains()) {
                        Ok(eq) => {
                            app.eq = Some(eq);
                            opts.pipewire_device = Some(audio::EQ_NODE.into());
                        }
                        Err(e) => app.status = format!("EQ failed to start: {e}"),
                    }
                }
                let _ = term.draw(|f| ui::draw(f, &mut app));
                restart_soloist(&mut app, opts, &cfg, &eng_tx, &mut eng_rx).await;
            }
            dirty = true;
        }
        let deadline = [app.end_deadline(), app.restart_at, app.lyrics_deadline(), app.sleep_deadline()].into_iter().flatten().min();
        tokio::select! {
            _ = async {
                match deadline {
                    Some(d) => tokio::time::sleep_until(d.into()).await,
                    None => std::future::pending().await,
                }
            }, if deadline.is_some() => { app.on_end_deadline(); app.on_sleep_deadline(); dirty = true; }
            Some(why) = quit_rx.recv() => {
                log::info!("quitting: {why}");
                app.quit = true;
                dirty = true;
            }
            Some(ev) = key_rx.recv() => match ev {
                Event::Key(k) => { app.on_key(k); dirty = true; }
                Event::Resize(..) => { app.on_resize(); dirty = true; }
                Event::Mouse(m) => dirty |= app.on_mouse(m),
                _ => {}
            },
            Some(ev) = eng_rx.recv() => dirty |= app.on_engine(ev),
            Some(msg) = rx.recv() => { app.on_msg(msg); dirty = true; }
            Some(cmd) = remote_rx.recv() => { app.on_remote(cmd); dirty = true; }
            _ = tick.tick(), if app.playing => {
                app.check_resume();
                app.note_play();
                dirty = true;
            }
        }
        // A lost connection is noticed on the next key, event or second of playback rather
        // than by a timer, so an idle trill never wakes up just to check.
        if !app.quit && app.session.is_invalid() && reconnect_at.is_none_or(|t| t.elapsed() >= Duration::from_secs(15)) {
            reconnect_at = Some(std::time::Instant::now());
            app.status = "Connection lost, reconnecting…".into();
            let _ = term.draw(|f| ui::draw(f, &mut app));
            let s = Session::new(session_cfg.clone(), Some(cache.clone()));
            match timeout(Duration::from_secs(10), auth::reconnect(&s, &cache)).await {
                Ok(Ok(())) => {
                    if let Engine::Librespot { player, .. } = &app.engine {
                        player.set_session(s.clone());
                    }
                    app.session = s;
                    app.status = "Reconnected.".into();
                }
                Ok(Err(e)) => app.status = format!("Reconnect failed: {e} (retrying)"),
                Err(_) => app.status = "Reconnect timed out (retrying)".into(),
            }
            dirty = true;
        }
    }

    // Pause and give up the Connect device before stopping Soloist, and wait for its reply
    // (at most 1.5 s): stopped straight away, Spotify and Discord kept showing the song playing.
    app.engine.stop();
    if app.engine.is_soloist() {
        app.engine.deactivate();
        let _ = timeout(Duration::from_millis(1500), async {
            while let Some(ev) = eng_rx.recv().await {
                if matches!(ev, EngineEvent::Deactivated) {
                    break;
                }
            }
        })
        .await;
    }
    app.engine.shutdown();
    if let Some(eq) = &app.eq {
        eq.stop();
    }
    app.session.shutdown();
    if cfg.mouse {
        let _ = crossterm::execute!(std::io::stdout(), DisableMouseCapture);
    }
    ratatui::restore();
    0
}

/// Crossfade lives in Soloist's prefs, read at startup: stop it, rewrite prefs, start it
/// again and resume the current track where it was.
async fn restart_soloist(
    app: &mut App,
    opts: &mut SoloistOpts,
    cfg: &Config,
    eng_tx: &mpsc::UnboundedSender<EngineEvent>,
    eng_rx: &mut mpsc::UnboundedReceiver<EngineEvent>,
) {
    let resume = app.begin_restart();
    if let Some(pid) = app.engine.pid() {
        app.engine.shutdown();
        let deadline = std::time::Instant::now() + Duration::from_secs(5);
        while engine::process_alive(pid) && std::time::Instant::now() < deadline {
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
    }
    opts.initial_volume = Some(app.volume_pct());
    audio::write_soloist_prefs(&opts.data_dir, &app.session.username(), app.audio.crossfade_s, cfg.bitrate);
    match engine::start_soloist(opts, eng_tx.clone()).await {
        Ok(e) => {
            // The old process's last words and the new one's snapshot of the old session:
            // stale, and they'd make the resume think our track had already started.
            while eng_rx.try_recv().is_ok() {}
            app.finish_restart(e, resume)
        }
        Err(e) => {
            app.playing = false;
            app.status = format!("Couldn't restart Soloist: {e}");
        }
    }
}