Files
Liber-public/crates/liber-audio/src/player.rs
T

159 lines
5.3 KiB
Rust

//! What a player knows, without a device or a clock: chapters, the queue, skips, the sleep timer and when to save
//! the position. The app drives it with the time it measures; every rule here is a pure function of that.
use serde::{Deserialize, Serialize};
/// Most chapters an item may have (hostile metadata).
pub const MAX_CHAPTERS: usize = 10_000;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Chapter {
pub title: String,
pub start_ms: u64,
pub end_ms: u64,
}
/// Chapters as found, made sane: sorted, inside the duration, no zero-length or overlapping ones, at most
/// [`MAX_CHAPTERS`]; each ends where the next starts. `None` when there is nothing usable.
pub fn tidy(mut chapters: Vec<Chapter>, duration_ms: u64) -> Option<Vec<Chapter>> {
chapters.retain(|c| c.start_ms < duration_ms);
chapters.sort_by_key(|c| c.start_ms);
chapters.dedup_by_key(|c| c.start_ms);
chapters.truncate(MAX_CHAPTERS);
if chapters.is_empty() {
return None;
}
let n = chapters.len();
for i in 0..n {
let end = if i + 1 < n { chapters[i + 1].start_ms } else { duration_ms };
chapters[i].end_ms = end;
chapters[i].title = chapters[i].title.chars().take(200).collect::<String>().trim().to_owned();
if chapters[i].title.is_empty() {
chapters[i].title = format!("Chapter {}", i + 1);
}
}
Some(chapters)
}
/// The chapter that holds a position.
pub fn chapter_at(chapters: &[Chapter], ms: u64) -> Option<usize> {
chapters.iter().rposition(|c| c.start_ms <= ms)
}
/// The position after a skip, inside `0..=duration`.
pub fn skip(ms: u64, by_ms: i64, duration_ms: u64) -> u64 {
(ms as i64 + by_ms).clamp(0, duration_ms as i64) as u64
}
/// Previous chapter: back to this chapter's start, or to the one before when within the first 3 s of it.
pub fn previous_chapter(chapters: &[Chapter], ms: u64) -> u64 {
match chapter_at(chapters, ms) {
Some(i) if ms.saturating_sub(chapters[i].start_ms) < 3_000 && i > 0 => chapters[i - 1].start_ms,
Some(i) => chapters[i].start_ms,
None => 0,
}
}
pub fn next_chapter(chapters: &[Chapter], ms: u64) -> Option<u64> {
let i = chapter_at(chapters, ms).map_or(0, |i| i + 1);
chapters.get(i).map(|c| c.start_ms)
}
/// The sleep timer.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Sleep {
Off,
/// Stop when the device's monotonic clock reaches this.
At {
until_ms: u64,
},
/// Stop at the end of the chapter playing when it was set.
EndOfChapter {
chapter_end_ms: u64,
},
}
impl Sleep {
pub fn minutes(now_ms: u64, minutes: u32) -> Sleep {
Sleep::At { until_ms: now_ms + u64::from(minutes.min(24 * 60)) * 60_000 }
}
pub fn end_of_chapter(chapters: &[Chapter], position_ms: u64, duration_ms: u64) -> Sleep {
let end = chapter_at(chapters, position_ms).map_or(duration_ms, |i| chapters[i].end_ms);
Sleep::EndOfChapter { chapter_end_ms: end }
}
/// Whether playback should stop now.
pub fn due(&self, now_ms: u64, position_ms: u64) -> bool {
match *self {
Sleep::Off => false,
Sleep::At { until_ms } => now_ms >= until_ms,
Sleep::EndOfChapter { chapter_end_ms } => position_ms >= chapter_end_ms,
}
}
}
/// When to write the position: every 900 ms while playing (locally; the app syncs it on pause, chapter change and
/// every 30 s), and at once on pause, seek, chapter change or stop.
#[derive(Clone, Copy, Debug, Default)]
pub struct Saver {
last_ms: Option<u64>,
}
/// With playback blocks of at most 100 ms, a saved position is never more than a second behind.
pub const SAVE_EVERY_MS: u64 = 900;
pub const MAX_BLOCK_MS: u64 = 100;
impl Saver {
pub fn tick(&mut self, now_ms: u64) -> bool {
let due = self.last_ms.is_none_or(|l| now_ms.saturating_sub(l) >= SAVE_EVERY_MS);
if due {
self.last_ms = Some(now_ms);
}
due
}
/// Pause, seek, chapter change, stop: save now.
pub fn now(&mut self, now_ms: u64) -> bool {
self.last_ms = Some(now_ms);
true
}
}
/// A queue of things to play (an audiobook, a book read aloud, texts other apps sent).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Queue<T> {
pub items: Vec<T>,
pub current: Option<usize>,
}
impl<T> Queue<T> {
pub fn push(&mut self, item: T) -> usize {
self.items.push(item);
if self.current.is_none() {
self.current = Some(self.items.len() - 1);
}
self.items.len() - 1
}
pub fn current(&self) -> Option<&T> {
self.current.and_then(|i| self.items.get(i))
}
pub fn advance(&mut self) -> Option<&T> {
let next = self.current.map_or(0, |i| i + 1);
self.current = (next < self.items.len()).then_some(next);
self.current()
}
pub fn remove(&mut self, i: usize) {
if i >= self.items.len() {
return;
}
self.items.remove(i);
self.current = match self.current {
Some(c) if c == i => (c < self.items.len()).then_some(c),
Some(c) if c > i => Some(c - 1),
c => c,
};
}
}