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
58        let mut update_ticker = tokio::time::interval(Duration::from_secs(1));
59
60        let result = loop {
61            tokio::select! {
62                // Handle the actions coming from the UI
63                // and process them to do async operations
64                Some(action) = action_rx.recv() => {
65                    match action {
66                        AudioAction::Playback(action) => handle_playback(&daemon, action).await?,
67                        AudioAction::Queue(action) => handle_queue(&daemon, action).await?,
68                        AudioAction::StateChange(state_change) => {
69                            match state_change {
70                                StateChange::Muted => state.muted = true,
71                                StateChange::Unmuted => state.muted = false,
72                                StateChange::VolumeChanged(volume) => state.volume = volume,
73                                StateChange::TrackChanged(_) => {
74                                    // force an update when the track changes, "just in case"
75                                    update_needed = true;
76                                },
77                                StateChange::RepeatModeChanged(repeat_mode) => state.repeat_mode = repeat_mode,
78                                StateChange::Seeked(seek_position) => if let Some(runtime) = &mut state.runtime {
79                                    runtime.seek_percent =
80                                        Percent::new(seek_position.as_secs_f32() / runtime.duration.as_secs_f32() * 100.0);
81                                    runtime.seek_position = seek_position;
82                                },
83                                StateChange::StatusChanged(status) => state.status = status,
84                            }
85                        }
86                    }
87                },
88                // Tick to terminate the select every N milliseconds
89                _ = ticker.tick() => {
90                    if state.paused() {
91                        continue;
92                    }
93                    if let Some(runtime) = &mut state.runtime {
94                        runtime.seek_position+= TICK_RATE;
95                        runtime.seek_percent =
96                            Percent::new(runtime.seek_position.as_secs_f32() / runtime.duration.as_secs_f32() * 100.0);
97                    }
98                },
99                // force a state update every second
100                _ = update_ticker.tick() => {
101                    update_needed = true;
102                },
103                // Catch and handle interrupt signal to gracefully shutdown
104                Ok(interrupted) = interrupt_rx.recv() => {
105                    break interrupted;
106                }
107            }
108            if update_needed {
109                state = get_state(daemon.clone()).await?;
110                update_needed = false;
111            }
112            self.state_tx.send(state.clone())?;
113        };
114
115        Ok(result)
116    }
117}
118
119/// get the audio state from the daemon.
120async fn get_state(daemon: Arc<MusicPlayerClient>) -> anyhow::Result<StateAudio> {
121    let ctx = tarpc::context::current();
122    Ok(daemon.state_audio(ctx).await?.unwrap_or_default())
123}
124
125/// handle a playback action
126async fn handle_playback(daemon: &MusicPlayerClient, action: PlaybackAction) -> anyhow::Result<()> {
127    let ctx = tarpc::context::current();
128
129    match action {
130        PlaybackAction::Toggle => daemon.playback_toggle(ctx).await?,
131        PlaybackAction::Next => daemon.playback_skip_forward(ctx, 1).await?,
132        PlaybackAction::Previous => daemon.playback_skip_backward(ctx, 1).await?,
133        PlaybackAction::Seek(seek_type, duration) => {
134            daemon.playback_seek(ctx, seek_type, duration).await?;
135        }
136        PlaybackAction::Volume(VolumeAction::Increase(amount)) => {
137            daemon.playback_volume_up(ctx, amount).await?;
138        }
139        PlaybackAction::Volume(VolumeAction::Decrease(amount)) => {
140            daemon.playback_volume_down(ctx, amount).await?;
141        }
142        PlaybackAction::ToggleMute => daemon.playback_volume_toggle_mute(ctx).await?,
143    }
144
145    Ok(())
146}
147
148/// handle a queue action
149async fn handle_queue(daemon: &MusicPlayerClient, action: QueueAction) -> anyhow::Result<()> {
150    let ctx = tarpc::context::current();
151
152    match action {
153        QueueAction::Add(ids) => daemon.queue_add_list(ctx, ids).await??,
154        QueueAction::Remove(index) => {
155            #[allow(clippy::range_plus_one)]
156            daemon.queue_remove_range(ctx, index..index + 1).await?;
157        }
158        QueueAction::SetPosition(index) => daemon.queue_set_index(ctx, index).await?,
159        QueueAction::Shuffle => daemon.playback_shuffle(ctx).await?,
160        QueueAction::Clear => daemon.playback_clear(ctx).await?,
161        QueueAction::SetRepeatMode(mode) => daemon.playback_repeat(ctx, mode).await?,
162    }
163
164    Ok(())
165}