vibox 0.2.2

a jukebox you exit with :q - a cli music player with vi motions, ex commands, and tmux manners
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
//! Lyrics from lrclib.net, fetched off the ui thread and cached on disk.
//!
//! lrclib needs no api key and matches on artist, title, album and duration,
//! which is exactly what a tagged file already carries. Synced lyrics come back
//! in lrc format, so the pane can follow the playback position.
//!
//! Nothing here ever blocks the ui: a miss queues a request and the pane says
//! so until the worker answers.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::time::Duration;

use crate::library::Track;

/// Stamped on every cache entry. Bump it when what gets cached changes
/// meaning: entries without the current marker are refetched rather than
/// trusted, since an old one cannot say whether its timings were believed.
const CACHE_MARK: &str = "[vibox:2]";

const AGENT: &str = concat!(
    "vibox/",
    env!("CARGO_PKG_VERSION"),
    " (https://gitlab.com/safteinzz/vibox)"
);

pub enum Lyrics {
    /// Timestamped lines, in order.
    Synced(Vec<(Duration, String)>),
    Plain(Vec<String>),
    /// Nothing to show, and the reason to put in the pane.
    Missing(String),
}

/// What the worker needs to ask lrclib for one track.
struct Request {
    path: PathBuf,
    artist: String,
    title: String,
    album: String,
    duration: u64,
}

pub struct Fetcher {
    tx: Sender<Request>,
    rx: Receiver<(PathBuf, Lyrics, i64)>,
    cache: HashMap<PathBuf, Lyrics>,
    /// Per file correction in milliseconds, positive meaning the words come
    /// later. A rip with a different lead-in needs this and no lookup can.
    offsets: HashMap<PathBuf, i64>,
    inflight: HashSet<PathBuf>,
}

impl Fetcher {
    pub fn new() -> Fetcher {
        let (tx, jobs) = channel::<Request>();
        let (results, rx) = channel();

        // One worker: lyrics are not urgent and a queue keeps lrclib happy.
        let _ = std::thread::Builder::new()
            .name("vibox-lyrics".into())
            .spawn(move || {
                while let Ok(job) = jobs.recv() {
                    let (found, offset) = load_cached(&job.path).unwrap_or_else(|| {
                        let fetched = fetch(&job);
                        store_cached(&job.path, &fetched, 0);
                        (fetched, 0)
                    });
                    if results.send((job.path, found, offset)).is_err() {
                        return;
                    }
                }
            });

        Fetcher {
            tx,
            rx,
            cache: HashMap::new(),
            offsets: HashMap::new(),
            inflight: HashSet::new(),
        }
    }

    /// Queues a fetch unless the track is already cached or already queued.
    pub fn request(&mut self, track: &Track) {
        if self.cache.contains_key(&track.path) || self.inflight.contains(&track.path) {
            return;
        }
        if track.title.trim().is_empty() && track.artist.trim().is_empty() {
            self.cache.insert(
                track.path.clone(),
                Lyrics::Missing("no artist or title tag to search with".into()),
            );
            return;
        }

        self.inflight.insert(track.path.clone());
        let _ = self.tx.send(Request {
            path: track.path.clone(),
            artist: track.artist.clone(),
            title: track.title.clone(),
            album: track.album.clone(),
            duration: track.duration.as_secs(),
        });
    }

    /// Moves whatever the worker finished into the cache. Called every tick.
    pub fn poll(&mut self) {
        while let Ok((path, lyrics, offset)) = self.rx.try_recv() {
            self.inflight.remove(&path);
            self.offsets.insert(path.clone(), offset);
            self.cache.insert(path, lyrics);
        }
    }

    pub fn offset(&self, path: &Path) -> i64 {
        self.offsets.get(path).copied().unwrap_or(0)
    }

    /// Shifts this file's lyrics and writes the correction into its cache
    /// entry, so the track stays in sync every time it is played.
    pub fn nudge(&mut self, path: &Path, delta_ms: i64) -> i64 {
        let offset = self.offset(path) + delta_ms;
        self.offsets.insert(path.to_path_buf(), offset);
        if let Some(lyrics) = self.cache.get(path) {
            store_cached(path, lyrics, offset);
        }
        offset
    }

    pub fn get(&self, path: &Path) -> Option<&Lyrics> {
        self.cache.get(path)
    }

    pub fn is_loading(&self, path: &Path) -> bool {
        self.inflight.contains(path)
    }
}

impl Default for Fetcher {
    fn default() -> Self {
        Fetcher::new()
    }
}

// ---- network ------------------------------------------------------------

fn fetch(job: &Request) -> Lyrics {
    let exact = format!(
        "https://lrclib.net/api/get?artist_name={}&track_name={}&album_name={}&duration={}",
        encode(&job.artist),
        encode(&job.title),
        encode(&job.album),
        job.duration
    );

    match get_json(&exact) {
        // lrclib matches duration loosely, so it will answer with a different
        // edit of the same song. Check the duration ourselves before believing
        // its timestamps.
        Ok(body) => {
            let trust = gap(&body, job.duration) <= SYNC_TOLERANCE;
            return from_json(&body, job.duration, trust);
        }
        // A miss on the exact match is normal: the duration or the album
        // rarely lines up with what someone else uploaded.
        Err(FetchError::NotFound) => {}
        Err(FetchError::Other(e)) => return Lyrics::Missing(e),
    }

    let search = format!(
        "https://lrclib.net/api/search?artist_name={}&track_name={}",
        encode(&job.artist),
        encode(&job.title)
    );
    match get_json(&search) {
        Ok(body) => match pick(&body, job.duration) {
            Some(hit) => {
                let trust = gap(&hit, job.duration) <= SYNC_TOLERANCE;
                from_json(&hit, job.duration, trust)
            }
            None => Lyrics::Missing("no lyrics on lrclib for this track".into()),
        },
        Err(FetchError::NotFound) => Lyrics::Missing("no lyrics on lrclib for this track".into()),
        Err(FetchError::Other(e)) => Lyrics::Missing(e),
    }
}

/// How far a hit's duration may be from ours before its timestamps belong to
/// another edit. Seconds of difference show up as seconds of lag.
const SYNC_TOLERANCE: f64 = 2.0;

/// True when the last line is timed past the end of the track, allowing a few
/// seconds for a fade or a sloppy final timestamp.
fn runs_over(lines: &[(Duration, String)], ours: u64) -> bool {
    if ours == 0 {
        return false;
    }
    lines
        .last()
        .is_some_and(|(at, _)| at.as_secs() > ours + 5)
}

/// Picks the hit closest in duration, which is the likeliest to be the same
/// recording.
fn pick(body: &serde_json::Value, ours: u64) -> Option<serde_json::Value> {
    let hits = body.as_array()?;
    hits.iter()
        .filter(|hit| has_lyrics(hit))
        .min_by(|a, b| gap(a, ours).total_cmp(&gap(b, ours)))
        .cloned()
}

fn gap(hit: &serde_json::Value, ours: u64) -> f64 {
    hit.get("duration")
        .and_then(serde_json::Value::as_f64)
        .map_or(f64::MAX, |theirs| (theirs - ours as f64).abs())
}

enum FetchError {
    NotFound,
    Other(String),
}

fn get_json(url: &str) -> Result<serde_json::Value, FetchError> {
    let response = ureq::get(url)
        .header("User-Agent", AGENT)
        .call()
        .map_err(|e| match e {
            ureq::Error::StatusCode(404) => FetchError::NotFound,
            other => FetchError::Other(format!("lrclib: {other}")),
        })?;

    response
        .into_body()
        .read_to_string()
        .map_err(|e| FetchError::Other(format!("lrclib: {e}")))
        .and_then(|text| {
            serde_json::from_str(&text).map_err(|e| FetchError::Other(format!("lrclib sent something unreadable: {e}")))
        })
}

fn has_lyrics(hit: &serde_json::Value) -> bool {
    !text_of(hit, "syncedLyrics").is_empty() || !text_of(hit, "plainLyrics").is_empty()
}

fn text_of(value: &serde_json::Value, key: &str) -> String {
    value
        .get(key)
        .and_then(serde_json::Value::as_str)
        .unwrap_or_default()
        .to_string()
}

/// `trust_timing` false means the words are right but the timestamps belong to
/// another release, so they are shown without a following highlight.
fn from_json(body: &serde_json::Value, ours: u64, trust_timing: bool) -> Lyrics {
    if body
        .get("instrumental")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false)
    {
        return Lyrics::Missing("instrumental".into());
    }

    let synced = text_of(body, "syncedLyrics");
    if !synced.trim().is_empty() {
        return match parse(&synced) {
            // Lyrics that run past the end of the track are from a longer
            // recording, whatever the entry claims its duration is: an lrclib
            // entry can say 2:44 and carry timings out to 3:10.
            Lyrics::Synced(lines) if !trust_timing || runs_over(&lines, ours) => {
                Lyrics::Plain(lines.into_iter().map(|(_, words)| words).collect())
            }
            other => other,
        };
    }
    let plain = text_of(body, "plainLyrics");
    if plain.trim().is_empty() {
        Lyrics::Missing("no lyrics on lrclib for this track".into())
    } else {
        parse(&plain)
    }
}

// ---- lrc ----------------------------------------------------------------

/// Parses lrc if the text is timestamped, and falls back to plain lines.
fn parse(text: &str) -> Lyrics {
    parse_with_offset(text).0
}

/// Also reads the `[offset:ms]` tag written by a nudge.
fn parse_with_offset(text: &str) -> (Lyrics, i64) {
    let mut timed: Vec<(Duration, String)> = Vec::new();
    let mut plain: Vec<String> = Vec::new();
    let mut offset = 0;

    for line in text.lines() {
        if let Some(rest) = line.trim().strip_prefix("[offset:")
            && let Some(value) = rest.strip_suffix(']')
        {
            offset = value.trim().trim_start_matches('+').parse().unwrap_or(0);
            continue;
        }
        match split_timestamp(line) {
            Some((at, words)) => timed.push((at, words.to_string())),
            None => plain.push(line.trim_end().to_string()),
        }
    }

    let lyrics = if timed.is_empty() {
        Lyrics::Plain(plain)
    } else {
        timed.sort_by_key(|(at, _)| *at);
        Lyrics::Synced(timed)
    };
    (lyrics, offset)
}

/// `[01:23.45] words` into the offset and the words.
fn split_timestamp(line: &str) -> Option<(Duration, &str)> {
    let rest = line.strip_prefix('[')?;
    let (stamp, words) = rest.split_once(']')?;
    let (minutes, seconds) = stamp.split_once(':')?;
    let minutes: u64 = minutes.trim().parse().ok()?;
    let seconds: f64 = seconds.trim().parse().ok()?;
    Some((
        Duration::from_secs_f64(minutes as f64 * 60.0 + seconds),
        words.trim(),
    ))
}

// ---- disk cache ---------------------------------------------------------

fn cache_path(track: &Path) -> Option<PathBuf> {
    let id = track.to_string_lossy().bytes().fold(0u64, |acc, b| {
        acc.wrapping_mul(31).wrapping_add(u64::from(b))
    });
    Some(dirs::data_dir()?.join("vibox/lyrics").join(format!("{id:016x}.lrc")))
}

/// An empty cache file means "asked lrclib, it has nothing", so a track with
/// no lyrics is not looked up again on every play.
fn load_cached(track: &Path) -> Option<(Lyrics, i64)> {
    let text = std::fs::read_to_string(cache_path(track)?).ok()?;
    // Written by an older vibox: refetch rather than believe its timestamps.
    let text = text.strip_prefix(CACHE_MARK)?;

    if text.trim().is_empty() {
        return Some((
            Lyrics::Missing("no lyrics on lrclib for this track".into()),
            0,
        ));
    }
    Some(parse_with_offset(text))
}

fn store_cached(track: &Path, lyrics: &Lyrics, offset: i64) {
    let Some(path) = cache_path(track) else {
        return;
    };
    if let Some(dir) = path.parent()
        && std::fs::create_dir_all(dir).is_err()
    {
        return;
    }

    let head = if offset == 0 {
        String::new()
    } else {
        format!("[offset:{offset}]\n")
    };
    let body = match lyrics {
        Lyrics::Synced(lines) => lines
            .iter()
            .map(|(at, words)| {
                let secs = at.as_secs_f64();
                format!("[{:02}:{:05.2}] {words}", secs as u64 / 60, secs % 60.0)
            })
            .collect::<Vec<_>>()
            .join("\n"),
        Lyrics::Plain(lines) => lines.join("\n"),
        Lyrics::Missing(_) => String::new(),
    };
    let _ = std::fs::write(path, format!("{CACHE_MARK}\n{head}{body}"));
}

/// Percent encodes everything a query string cannot carry literally.
fn encode(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    for byte in value.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(byte as char);
            }
            _ => out.push_str(&format!("%{byte:02X}")),
        }
    }
    out
}

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

    fn timed(seconds: &[u64]) -> Vec<(Duration, String)> {
        seconds
            .iter()
            .map(|s| (Duration::from_secs(*s), format!("line at {s}")))
            .collect()
    }

    /// The case this rule exists for: an lrclib entry claiming 2:44 whose
    /// timings run to 3:10, because they came from the original recording.
    #[test]
    fn lyrics_timed_past_the_end_of_the_track_are_not_trusted() {
        assert!(runs_over(&timed(&[14, 120, 190]), 164));
    }

    #[test]
    fn a_last_line_inside_the_track_is_fine() {
        assert!(!runs_over(&timed(&[14, 120, 160]), 164));
    }

    #[test]
    fn a_few_seconds_over_is_allowed_for_a_fade() {
        assert!(!runs_over(&timed(&[160, 166]), 164));
    }

    #[test]
    fn an_unknown_duration_never_rejects_anything() {
        assert!(!runs_over(&timed(&[190]), 0));
    }

    #[test]
    fn lrc_timestamps_parse_to_their_offsets() {
        let (lyrics, offset) = parse_with_offset("[offset:250]\n[01:30.50] words\n");
        assert_eq!(offset, 250);
        match lyrics {
            Lyrics::Synced(lines) => {
                assert_eq!(lines[0].0, Duration::from_secs_f64(90.5));
                assert_eq!(lines[0].1, "words");
            }
            _ => panic!("timestamped lines are synced lyrics"),
        }
    }
}