mecomp_tui/state/
audio.rs

1//! This module contains the implementation of audio state store.
2//! which is updated every tick and used by views to render the audio playback and queue state.
3//!
4//! The audio state store is responsible for maintaining the audio state, and for handling audio related actions.
5
6use std::{sync::Arc, time::Duration};
7
8use tokio::sync::{
9    broadcast,
10    mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel},
11};
12
13use mecomp_core::state::{Percent, StateAudio};
14use mecomp_core::{rpc::MusicPlayerClient, udp::StateChange};
15
16use crate::termination::Interrupted;
17
18use super::action::{AudioAction, PlaybackAction, QueueAction, VolumeAction};
19
20pub const TICK_RATE: Duration = Duration::from_millis(100);
21
22/// The audio state store.
23#[derive(Debug, Clone)]
24#[allow(clippy::module_name_repetitions)]
25pub struct AudioState {
26    state_tx: UnboundedSender<StateAudio>,
27}
28
29impl AudioState {
30    /// create a new audio state store, and return the receiver for listening to state updates.
31    #[must_use]
32    pub fn new() -> (Self, UnboundedReceiver<StateAudio>) {
33        let (state_tx, state_rx) = unbounded_channel::<StateAudio>();
34
35        (Self { state_tx }, state_rx)
36    }
37
38    /// a loop that updates the audio state every tick.
39    ///
40    /// # Errors
41    ///
42    /// Fails if the state cannot be sent
43    pub async fn main_loop(
44        &self,
45        daemon: Arc<MusicPlayerClient>,
46        mut action_rx: UnboundedReceiver<AudioAction>,
47        mut interrupt_rx: broadcast::Receiver<Interrupted>,
48    ) -> anyhow::Result<Interrupted> {
49        let mut state = get_state(daemon.clone()).await?;
50        let mut update_needed = false;
51
52        // the initial state once
53        self.state_tx.send(state.clone())?;
54
55        // the ticker
56        let mut ticker = tokio::time::interval(TICK_RATE);
57        ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
58
59        let mut time_last = tokio::time::Instant::now();
60
61        let result = loop {
62            tokio::select! {
63                // Handle the actions coming from the UI
64                // and process them to do async operations
65                Some(action) = action_rx.recv() => {
66                    match action {
67                        AudioAction::Playback(action) => handle_playback(&daemon, action).await?,
68                        AudioAction::Queue(action) => handle_queue(&daemon, action).await?,
69                        AudioAction::StateChange(state_change) => {
70                            match state_change {
71                                StateChange::Muted => state.muted = true,
72                                StateChange::Unmuted => state.muted = false,
73                                StateChange::VolumeChanged(volume) => state.volume = volume,
74                                StateChange::TrackChanged(_) => {
75                                    // force an update when the track changes, "just in case"
76                                    update_needed = true;
77                                },
78                                StateChange::RepeatModeChanged(repeat_mode) => state.repeat_mode = repeat_mode,
79                                StateChange::Seeked(seek_position) => if let Some(runtime) = &mut state.runtime {
80                                    runtime.seek_percent =
81                                        Percent::new(seek_position.as_secs_f32() / runtime.duration.as_secs_f32() * 100.0);
82                                    runtime.seek_position = seek_position;
83                                },
84                                StateChange::StatusChanged(status) => state.status = status,
85                            }
86                        }
87                    }
88                },
89                // Tick to terminate the select every N milliseconds
90                _ = ticker.tick() => {
91                    if state.paused() {
92                        continue;
93                    }
94                    if let Some(runtime) = &mut state.runtime {
95                        // push the seek position forward by how much time has passed since the last tick
96                        runtime.seek_position+= time_last.elapsed();
97                        runtime.seek_percent =
98                            Percent::new(runtime.seek_position.as_secs_f32() / runtime.duration.as_secs_f32() * 100.0);
99                    }
100                },
101                // Catch and handle interrupt signal to gracefully shutdown
102                Ok(interrupted) = interrupt_rx.recv() => {
103                    break interrupted;
104                }
105            }
106            if update_needed {
107                state = get_state(daemon.clone()).await?;
108                update_needed = false;
109            }
110            self.state_tx.send(state.clone())?;
111            time_last = tokio::time::Instant::now();
112        };
113
114        Ok(result)
115    }
116}
117
118/// get the audio state from the daemon.
119async fn get_state(daemon: Arc<MusicPlayerClient>) -> anyhow::Result<StateAudio> {
120    let ctx = tarpc::context::current();
121    Ok(daemon.state_audio(ctx).await?.unwrap_or_default())
122}
123
124/// handle a playback action
125async fn handle_playback(daemon: &MusicPlayerClient, action: PlaybackAction) -> anyhow::Result<()> {
126    let ctx = tarpc::context::current();
127
128    match action {
129        PlaybackAction::Toggle => daemon.playback_toggle(ctx).await?,
130        PlaybackAction::Next => daemon.playback_skip_forward(ctx, 1).await?,
131        PlaybackAction::Previous => daemon.playback_skip_backward(ctx, 1).await?,
132        PlaybackAction::Seek(seek_type, duration) => {
133            daemon.playback_seek(ctx, seek_type, duration).await?;
134        }
135        PlaybackAction::Volume(VolumeAction::Increase(amount)) => {
136            daemon.playback_volume_up(ctx, amount).await?;
137        }
138        PlaybackAction::Volume(VolumeAction::Decrease(amount)) => {
139            daemon.playback_volume_down(ctx, amount).await?;
140        }
141        PlaybackAction::ToggleMute => daemon.playback_volume_toggle_mute(ctx).await?,
142    }
143
144    Ok(())
145}
146
147/// handle a queue action
148async fn handle_queue(daemon: &MusicPlayerClient, action: QueueAction) -> anyhow::Result<()> {
149    let ctx = tarpc::context::current();
150
151    match action {
152        QueueAction::Add(ids) => daemon.queue_add_list(ctx, ids).await??,
153        QueueAction::Remove(index) => {
154            #[allow(clippy::range_plus_one)]
155            daemon.queue_remove_range(ctx, index..index + 1).await?;
156        }
157        QueueAction::SetPosition(index) => daemon.queue_set_index(ctx, index).await?,
158        QueueAction::Shuffle => daemon.playback_shuffle(ctx).await?,
159        QueueAction::Clear => daemon.playback_clear(ctx).await?,
160        QueueAction::SetRepeatMode(mode) => daemon.playback_repeat(ctx, mode).await?,
161    }
162
163    Ok(())
164}