//! Client-side completion of personal-device controls. Only a fresh output //! report can finish a request. Nothing here is serialized to another device. use std::time::{Duration, Instant}; use furumi_control_protocol::{RemoteCommand, RemoteCommandState}; use music_dht::playback::Claim; use super::state::{AppState, DevicePlaybackRole, PlayerBar}; use crate::config::settings::LibrarySourceMode; use crate::devices::{PlaybackSnapshot, PlaybackStateWire, PlaybackTrack}; pub(super) const WAITING: &str = "Waiting for the active device"; const TIMEOUT: Duration = Duration::from_secs(15); #[derive(Debug, Clone, Copy)] pub(super) enum Change { Transport, Start, Seek, Volume, Options, Queue, } #[derive(Debug)] struct Pending { owner: String, claim: Option, heartbeat: u64, written: bool, started: Instant, change: Change, desired: PlaybackStateWire, same_item: bool, } #[derive(Debug, Default)] pub(crate) struct RemotePlayback { pub(crate) status: RemoteCommand, pending: Option, // The resolved UI projection preserves local cover paths and podcast // identities when discarding a speculative edit. No DB access on input. confirmed: Option, source_mode: Option, } impl RemotePlayback { pub(crate) fn busy(&self) -> bool { self.pending.is_some() } fn finish(&mut self, error: Option) { self.pending = None; self.status.state = if error.is_some() { RemoteCommandState::Failed } else { RemoteCommandState::Confirmed }; self.status.error = error; } } // A heartbeat normally changes only the position. Keep the resolved queue // across those reports instead of copying every track on every heartbeat. pub(super) fn remember(state: &mut AppState, report: &PlaybackSnapshot) { let device = &mut state.device_playback; let remote = &mut device.control; let unchanged = device.last_remote_snapshot.as_ref().is_some_and(|old| { let (a, b) = (&old.state, &report.state); old.device_id == report.device_id && a.queue == b.queue && a.queue_pos == b.queue_pos && a.playing == b.playing && a.paused == b.paused && a.volume == b.volume && a.shuffle == b.shuffle && a.repeat == b.repeat }); if unchanged && remote.source_mode == Some(state.global.filters.source_mode) && let Some(confirmed) = &mut remote.confirmed { confirmed.position_secs = state.player.position_secs; } else { remote.confirmed = Some(state.player.clone()); remote.source_mode = Some(state.global.filters.source_mode); } } pub(super) fn restore(state: &mut AppState) { if let Some(last) = &state.device_playback.last_remote_snapshot && state.device_playback.active_device_id.as_ref() == Some(&last.device_id) && let Some(confirmed) = &state.device_playback.control.confirmed { state.player.clone_from(confirmed); state.device_playback.local_idle_since_ms = last.state.idle_since_ms; state.queue_tab.cursor = state .queue_tab .cursor .min(state.player.queue.len().saturating_sub(1)); super::extrapolate_control_position(state); } } pub(super) fn available(state: &AppState) -> Result<(), &'static str> { let device = &state.device_playback; if device.role != DevicePlaybackRole::Control { return Ok(()); } if device.control.busy() { return Err(WAITING); } device .active_device_id .as_ref() .map(|_| ()) .ok_or("No active playback device") } pub(super) fn begin( state: &mut AppState, change: Change, desired: PlaybackStateWire, now: Instant, ) -> Result { // update() may already have edited the queue, modes or pause flag to // build the outgoing SetState. Restore the screen before it can repaint. restore(state); let device = &mut state.device_playback; if device.control.busy() { return Err(WAITING); } let owner = device .active_device_id .as_ref() .ok_or("No active playback device")?; let last = device .last_remote_snapshot .as_ref() .filter(|s| s.device_id == *owner); let same_item = last.is_some_and(|s| same_current(&s.state, &desired)); let announcement = last.and_then(|s| s.coordination.as_ref()); let generation = device.control.status.id.wrapping_add(1); device.control.pending = Some(Pending { owner: owner.clone(), claim: announcement.and_then(|a| a.claim.clone()), heartbeat: announcement.map_or(0, |a| a.heartbeat), written: false, started: now, change, desired, same_item, }); device.control.status = RemoteCommand { id: generation, state: RemoteCommandState::Pending, error: None, }; Ok(generation) } pub(super) fn recorded(state: &mut AppState, id: u64, result: Result<(), String>) { let control = &mut state.device_playback.control; if id != control.status.id { return; } let Some(pending) = &mut control.pending else { return; }; match result { Ok(()) => pending.written = true, Err(error) => { state.status_message = Some(error.clone()); control.finish(Some(error)); } } } // IDs and file paths belong to the originating library. Older music entries // without a content ID can still be compared by portable display metadata. fn same_item(a: &PlaybackTrack, b: &PlaybackTrack) -> bool { use music_dht::device_sync::PlaybackSource; match (&a.source, &b.source) { (Some(PlaybackSource::PodcastEpisode(a)), Some(PlaybackSource::PodcastEpisode(b))) => { return a.episode_id == b.episode_id; } (Some(PlaybackSource::Private), Some(PlaybackSource::Private)) => return true, (None | Some(PlaybackSource::Music), None | Some(PlaybackSource::Music)) => {} _ => return false, } let content = |t: &PlaybackTrack| { t.content_id .as_deref() .or_else(|| t.fed.as_ref().map(|f| f.content_id.as_str())) .and_then(music_dht::normalize_content_id) }; if let (Some(a), Some(b)) = (content(a), content(b)) { return a == b; } if let (Some(a), Some(b)) = (&a.fed, &b.fed) { return a.owner == b.owner && a.item_id == b.item_id; } a.title == b.title && a.release_title == b.release_title && a.artist_names == b.artist_names && a.track_number == b.track_number && a.disc_number == b.disc_number } fn same_current(a: &PlaybackStateWire, b: &PlaybackStateWire) -> bool { a.queue_pos == b.queue_pos && match (a.queue.get(a.queue_pos), b.queue.get(b.queue_pos)) { (Some(a), Some(b)) => same_item(a, b), (None, None) => true, _ => false, } } impl Pending { fn matches(&self, actual: &PlaybackStateWire, output_playing: bool, age: Duration) -> bool { let want = &self.desired; let transport = actual.playing == want.playing && actual.paused == want.paused && output_playing == (want.playing && !want.paused); let position_matches = || { let elapsed = if output_playing { age.as_secs_f64() } else { 0.0 }; actual.position_secs >= want.position_secs - 0.75 && actual.position_secs <= want.position_secs + elapsed + 0.75 }; let queue_matches = || { want.queue.len() == actual.queue.len() && want .queue .iter() .zip(&actual.queue) .all(|(a, b)| same_item(a, b)) }; match self.change { Change::Transport => transport && (!want.playing || same_current(want, actual)), Change::Start => { transport && same_current(want, actual) && queue_matches() && (!self.same_item || position_matches()) } Change::Seek => transport && same_current(want, actual) && position_matches(), Change::Volume => actual.volume == want.volume, Change::Options => actual.repeat == want.repeat && actual.shuffle == want.shuffle, Change::Queue => same_current(want, actual) && queue_matches(), } } } pub(super) fn observe(state: &mut AppState, report: &PlaybackSnapshot, now: Instant) { tick(state, now); let device = &mut state.device_playback; let Some(pending) = &mut device.control.pending else { return; }; if device.role != DevicePlaybackRole::Control || pending.owner != report.device_id { return; } let Some(announcement) = &report.coordination else { return; }; let Some(claim) = &announcement.claim else { return; }; if let Some(baseline) = &pending.claim { if claim < baseline { return; } if claim > baseline { device .control .finish(Some("Playback ownership changed".into())); state.status_message = device.control.status.error.clone(); return; } } if !report.active || !announcement.available || claim.owner != pending.owner || announcement.heartbeat <= pending.heartbeat { return; } pending.heartbeat = announcement.heartbeat; pending.claim.get_or_insert_with(|| claim.clone()); if pending.written && pending.matches( &report.state, announcement.playing, now.saturating_duration_since(pending.started), ) { device.control.finish(None); } } pub(super) fn tick(state: &mut AppState, now: Instant) { let device = &mut state.device_playback; if device.role != DevicePlaybackRole::Control { device.control.confirmed = None; } let Some(pending) = &device.control.pending else { return; }; let reason = if device.role != DevicePlaybackRole::Control || device.active_device_id.as_ref() != Some(&pending.owner) { "Playback ownership changed" } else if now.saturating_duration_since(pending.started) >= TIMEOUT { "Active device did not confirm the command" } else { return; }; state.status_message = Some(reason.into()); device.control.finish(Some(reason.into())); }