Skip to content
File

Blob: firmware/crates/radio-core/src/now_playing.rs

rust72 lines
1//! A song instance within one publisher generation; independent of the RTP clock.
2use crate::{
3 music::{Catalog, Error, FRAME_MS, Track},
4 playback::Due,
5};
6use serde::Serialize;
7 
8#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
9#[serde(rename_all = "camelCase")]
10pub struct NowPlaying {
11 pub revision: u32,
12 pub track_index: u32,
13 pub track_count: u32,
14 pub track: Option<Track>,
15}
16 
17/// Published state describes the most recent frame returned by
18/// [`Playback::due`](crate::playback::Playback::due).
19/// Use the same immutable catalog for construction and subsequent updates.
20#[derive(Debug)]
21pub struct Snapshot {
22 pub now_playing: NowPlaying,
23 pub position_ms: u32,
24 pub duration_ms: u32,
25}
26 
27impl Snapshot {
28 pub fn new(catalog: &Catalog) -> Self {
29 let first = &catalog.songs()[0];
30 Self {
31 now_playing: NowPlaying {
32 revision: 0,
33 track_index: 0,
34 track_count: catalog.songs().len() as u32,
35 track: first.metadata.clone(),
36 },
37 position_ms: 0,
38 duration_ms: first.frames.get() * FRAME_MS,
39 }
40 }
41 
42 /// Records a due frame and reports whether its playback revision changed.
43 pub fn record(&mut self, catalog: &Catalog, due: Due) -> Result<bool, Error> {
44 let song = catalog
45 .songs()
46 .get(due.track_index as usize)
47 .ok_or(Error::TrackCount)?;
48 if due.index >= song.frames.get() {
49 return Err(Error::FrameCount);
50 }
51 let changed = due.revision != self.now_playing.revision;
52 if changed {
53 self.now_playing = NowPlaying {
54 revision: due.revision,
55 track_index: due.track_index,
56 track_count: catalog.songs().len() as u32,
57 track: song.metadata.clone(),
58 };
59 }
60 self.position_ms = due.index * FRAME_MS;
61 self.duration_ms = song.frames.get() * FRAME_MS;
62 Ok(changed)
63 }
64}
65 
66#[derive(Debug, Serialize)]
67#[serde(rename_all = "camelCase")]
68pub struct Message<'a> {
69 pub event: &'static str,
70 pub now_playing: &'a NowPlaying,
71}