lyrx 0.2.2

A pure Rust implementation of LyRiCs which is a computer file format that synchronizes song lyrics with an audio file.
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
/*!
# lyrx

A pure Rust implementation of LyRiCs which is a computer file format that synchronizes song lyrics with an audio file.

## Examples

```rust
use lyrx::{Lyrics, IDTag, TimeTag};

let mut lyrics = Lyrics::new();

let metadata = &mut lyrics.metadata;
metadata.insert(IDTag::from_string("ti", "Let's Twist Again").unwrap());
metadata.insert(IDTag::from_string("al", "Hits Of The 60's - Vol. 2 – Oldies").unwrap());

lyrics.add_timed_line(TimeTag::from_str("00:12.00").unwrap(), "Naku Penda Piya-Naku Taka Piya-Mpenziwe").unwrap();
lyrics.add_timed_line(TimeTag::from_str("00:15.30").unwrap(), "Some more lyrics").unwrap();


assert_eq!(
    r"[al: Hits Of The 60's - Vol. 2 – Oldies]
[ti: Let's Twist Again]

[00:12.00]Naku Penda Piya-Naku Taka Piya-Mpenziwe
[00:15.30]Some more lyrics",
    lyrics.to_string()
);
```

```rust
use lyrx::{Lyrics, TimeTag};

let lyrics = Lyrics::from_str(r"[00:12.00][01:15.00]Naku Penda Piya-Naku Taka Piya-Mpenziwe
[00:15.30][01:18.00]Some more lyrics ...").unwrap();

if let Some(index) = lyrics.find_timed_line_index(TimeTag::from_str("00:13.00").unwrap()) {
    let timed_lines = lyrics.get_timed_lines();

    assert_eq!((TimeTag::from_str("00:12.00").unwrap(), "Naku Penda Piya-Naku Taka Piya-Mpenziwe".into()), timed_lines[index]);
} else {
    unreachable!();
}
```

```rust
use lyrx::Lyrics;

let lyrics = Lyrics::from_str(r"[00:53.44] This fire is out of control
[00:56.63] This fire is out of control
[00:59.96] This fire is out of control");
assert!(lyrics.is_ok());

// Here you need annotation because to_vec() support f64, Option<f64>, f32, Option<32>, u64, Option<u64>, u32, Option<u32>, i64
let vec: Vec<(f64, String)> = lyrics.unwrap().to_vec();

assert_eq!(vec.len(), 3);
assert_eq!(vec[0].0, 53.44);
assert_eq!(vec[0].1, "This fire is out of control");
```

```rust
use lyrx::Lyrics;

let lyrics = Lyrics::from_str(
    "[00:12.00] <00:12.04> This <00:12.16> fire <00:12.82> is"
);

let vec: Vec<(f64, String)> = lyrics.unwrap().to_vec();
assert_eq!(vec[0].0, 12.00);
assert_eq!(vec[0].1, "This fire is");
```
*/

#[macro_use]
extern crate educe;

mod error;
pub mod tags;
mod timestamp;

use std::{
    collections::BTreeSet,
    fmt::{self, Display, Formatter, Write},
    str::FromStr,
};

pub use error::*;
use regex::Regex;
use std::sync::LazyLock;
pub use tags::*;

static LYRICS_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new("^[^\x00-\x08\x0A-\x1F\x7F]*$").unwrap());
static TAG_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[.*:.*\]").unwrap());
static LINE_STARTS_WITH_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new("^\\[([^\x00-\x08\x0A-\x1F\x7F\\[\\]:]*):([^\x00-\x08\x0A-\x1F\x7F\\[\\]]*)\\]")
        .unwrap()
});

fn check_line<S: AsRef<str>>(line: S) -> Result<(), LyricsError> {
    let line = line.as_ref();

    if !LYRICS_RE.is_match(line) {
        return Err(LyricsError::FormatError("Incorrect lyrics."));
    }

    if TAG_RE.is_match(line) {
        return Err(LyricsError::FormatError("Lyrics contain tags."));
    }

    Ok(())
}

pub trait FromTime {
    fn from_timestamp(ms: i64) -> Self;
    fn none() -> Self;
}

impl FromTime for u32 {
    fn from_timestamp(ms: i64) -> Self {
        ms as u32
    }
    fn none() -> Self {
        0
    }
}

impl FromTime for Option<u32> {
    fn from_timestamp(ms: i64) -> Self {
        Some(ms as u32)
    }
    fn none() -> Self {
        None
    }
}

impl FromTime for u64 {
    fn from_timestamp(ms: i64) -> Self {
        ms as u64
    }
    fn none() -> Self {
        0
    }
}

impl FromTime for Option<u64> {
    fn from_timestamp(ms: i64) -> Self {
        Some(ms as u64)
    }
    fn none() -> Self {
        None
    }
}

impl FromTime for f64 {
    fn from_timestamp(ms: i64) -> Self {
        ms as f64 / 1000.0
    }
    fn none() -> Self {
        0.0
    }
}

impl FromTime for Option<f64> {
    fn from_timestamp(ms: i64) -> Self {
        Some(ms as f64 / 1000.0)
    }
    fn none() -> Self {
        None
    }
}

#[derive(Debug, Clone, Educe)]
#[educe(Default(new))]
pub struct Lyrics {
    /// Metadata about this lyrics.
    pub metadata: BTreeSet<IDTag>,
    timed_lines: Vec<(TimeTag, String)>,
    lines: Vec<String>,
}

impl Lyrics {
    /// Create a `Lyrics` instance with a string.
    #[allow(clippy::should_implement_trait)]
    pub fn from_str<S: AsRef<str>>(s: S) -> Result<Lyrics, LyricsError> {
        let mut lyrics: Lyrics = Lyrics::new();
        let s = s.as_ref();

        let lines: Vec<&str> = s.split('\n').collect();

        for line in lines {
            let mut time_tags: Vec<TimeTag> = Vec::new();
            let mut has_id_tag = false;

            let mut line = line.trim();

            while let Some(c) = LINE_STARTS_WITH_RE.captures(line) {
                let tag = c.get(0).unwrap().as_str();
                let tag_len = tag.len();

                match TimeTag::from_str(tag) {
                    Ok(time_tag) => {
                        time_tags.push(time_tag);
                    }
                    Err(_) => {
                        let label = c.get(1).unwrap().as_str().trim();

                        if label.is_empty() {
                            // A comment tag, usually in the format [:] ignores the characters after it.
                            line = "";
                            break;
                        }

                        let text = c.get(2).unwrap().as_str().trim();

                        has_id_tag = true;
                        lyrics
                            .metadata
                            .insert(IDTag::from_string_unchecked(label, text));
                    }
                }

                line = line[tag_len..].trim_start();
            }

            if !has_id_tag || !time_tags.is_empty() {
                // Remove all word-level timestamps (`<mm:ss.xx>`) from a text line,
                // keeping only the actual words joined by a single space.
                let mut clean_line = String::with_capacity(line.len());
                let mut inside_angle = false;

                for ch in line.chars() {
                    match ch {
                        '<' => inside_angle = true,
                        '>' => inside_angle = false,
                        _ if !inside_angle => clean_line.push(ch),
                        _ => {}
                    }
                }

                clean_line = clean_line.split_whitespace().collect::<Vec<_>>().join(" ");
                lyrics.add_line_with_multiple_time_tags(&time_tags, clean_line)?;
            }
        }

        Ok(lyrics)
    }
}

impl Lyrics {
    #[inline]
    /// Add line in Lyrics
    pub fn add_line<S: Into<String>>(&mut self, line: S) -> Result<(), LyricsError> {
        let line = line.into();

        check_line(&line)?;

        self.lines.push(line);

        Ok(())
    }

    #[inline]
    /// Add line with timetag in Lyrics
    pub fn add_timed_line<S: Into<String>>(
        &mut self,
        time_tag: TimeTag,
        line: S,
    ) -> Result<(), LyricsError> {
        let line = line.into();

        check_line(&line)?;

        self.add_timed_line_unchecked(time_tag, line);

        Ok(())
    }

    /// Add line with multiple timetag in Lyrics
    pub fn add_line_with_multiple_time_tags<S: Into<String>>(
        &mut self,
        time_tags: &[TimeTag],
        line: S,
    ) -> Result<(), LyricsError> {
        let line = line.into();

        check_line(&line)?;

        let len = time_tags.len();

        if len == 0 {
            self.lines.push(line);
        } else {
            let line: String = line;

            let len_dec = len - 1;

            for time_tag in time_tags.iter().copied().take(len_dec) {
                self.add_timed_line_unchecked(time_tag, line.clone());
            }

            self.add_timed_line_unchecked(time_tags[len_dec], line);
        }

        Ok(())
    }

    #[inline]
    fn add_timed_line_unchecked(&mut self, time_tag: TimeTag, line: String) {
        let mut insert_index = self.timed_lines.len();

        while insert_index > 0 {
            insert_index -= 1;

            let temp = &self.timed_lines[insert_index].0;

            if temp <= &time_tag {
                insert_index += 1;
                break;
            }
        }

        self.timed_lines.insert(insert_index, (time_tag, line));
    }
}

impl Lyrics {
    #[inline]
    /// Get lines without timeatg
    pub fn get_lines(&self) -> &[String] {
        &self.lines
    }

    #[inline]
    /// Get lines with timetag as [(TimeTag, String)]
    pub fn get_timed_lines(&self) -> &[(TimeTag, String)] {
        &self.timed_lines
    }

    #[inline]
    /// Delete line by index
    pub fn remove_line(&mut self, index: usize) -> String {
        self.lines.remove(index)
    }

    #[inline]
    /// Delete line with timetag by index
    pub fn remove_timed_line(&mut self, index: usize) -> (TimeTag, String) {
        self.timed_lines.remove(index)
    }

    #[inline]
    /// Find timed line by index
    pub fn find_timed_line_index<N: Into<i64>>(&self, timestamp: N) -> Option<usize> {
        let target_time_tag = TimeTag::new(timestamp);

        for (i, (time_tag, _)) in self.timed_lines.iter().enumerate().rev() {
            if target_time_tag >= *time_tag {
                return Some(i);
            }
        }

        None
    }

    #[inline]
    /// Convert lyrics to vec
    pub fn to_vec<T: FromTime>(&self) -> Vec<(T, String)> {
        let timed_lines = self.get_timed_lines();

        if !timed_lines.is_empty() {
            timed_lines
                .iter()
                .map(|(time, text)| (T::from_timestamp(time.get_timestamp()), text.clone()))
                .collect()
        } else {
            self.get_lines()
                .iter()
                .filter(|line| !line.is_empty())
                .map(|line| (T::none(), line.clone()))
                .collect()
        }
    }
}

impl Display for Lyrics {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
        let metadata_not_empty = !self.metadata.is_empty();
        let timed_lines_not_empty = !self.timed_lines.is_empty();
        let lines_not_empty = !self.lines.is_empty();

        if metadata_not_empty {
            let mut iter = self.metadata.iter();

            Display::fmt(iter.next().unwrap(), f)?;

            for id_tag in iter {
                f.write_char('\n')?;
                Display::fmt(id_tag, f)?;
            }
        }

        if timed_lines_not_empty {
            if metadata_not_empty {
                f.write_char('\n')?;
                f.write_char('\n')?;
            }

            let mut iter = self.timed_lines.iter();

            let (time_tag, line) = iter.next().unwrap();

            Display::fmt(time_tag, f)?;
            f.write_str(line)?;

            for (time_tag, line) in iter {
                f.write_char('\n')?;
                Display::fmt(time_tag, f)?;
                f.write_str(line)?;
            }
        }

        if lines_not_empty {
            let mut buffer = String::new();

            let mut iter = self.lines.iter();

            buffer.push_str(iter.next().unwrap());

            for line in iter {
                buffer.push('\n');
                buffer.push_str(line);
            }

            let s = buffer.trim();

            if !s.is_empty() {
                if metadata_not_empty || timed_lines_not_empty {
                    f.write_char('\n')?;
                    f.write_char('\n')?;
                }

                f.write_str(s)?;
            }
        }

        Ok(())
    }
}

impl FromStr for Lyrics {
    type Err = LyricsError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Lyrics::from_str(s)
    }
}