use std::future::Future; use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel}; use crate::devices::{DeviceChoice, DeviceLists}; use crate::error::{Error, Result}; use crate::mute::MuteCommand; use crate::roster::RosterEntry; use crate::state::CallState; #[derive(Debug, Clone, PartialEq, Eq)] pub enum CallCommand { Mute(MuteCommand), SelectInput(DeviceChoice), SelectOutput(DeviceChoice), RefreshDevices, Hangup, EndMeeting, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Progress { Calling, Ringing, } #[derive(Debug, Clone, PartialEq)] pub enum CallUpdate { State(CallState), Muted(bool), Levels { local: f32, remote: f32 }, Devices(DeviceLists), Selected { input: DeviceChoice, output: DeviceChoice }, ListenOnly(bool), Stats { inbound_packets: u64, outbound_packets: u64 }, Progress(Progress), Roster(Vec), Speakers(Vec), Lobby(bool), OwnIdentity { mri: String }, } pub struct CallHandle { pub commands: UnboundedSender, pub updates: UnboundedReceiver, } pub struct CallControl { commands: UnboundedReceiver, updates: UnboundedSender, deferred: Vec, } pub fn call_channel() -> (CallHandle, CallControl) { let (command_sender, command_receiver) = unbounded_channel(); let (update_sender, update_receiver) = unbounded_channel(); ( CallHandle { commands: command_sender, updates: update_receiver, }, CallControl { commands: command_receiver, updates: update_sender, deferred: Vec::new(), }, ) } impl CallControl { pub fn send(&self, update: CallUpdate) { let _ = self.updates.send(update); } pub async fn recv(&mut self) -> Option { if !self.deferred.is_empty() { return Some(self.deferred.remove(0)); } self.commands.recv().await } /// Runs a setup step; a hangup while it is pending cancels it, other commands wait for the call loop. pub async fn until_hangup(&mut self, step: impl Future) -> Result { let CallControl { commands, deferred, .. } = self; let hangup = async { loop { match commands.recv().await { Some(CallCommand::Hangup) | None => return, Some(other) => deferred.push(other), } } }; tokio::select! { output = step => Ok(output), _ = hangup => Err(Error::Cancelled), } } } #[cfg(test)] mod tests { use super::*; #[tokio::test] async fn hangup_cancels_a_pending_step_and_keeps_other_commands() { let (handle, mut control) = call_channel(); handle.commands.send(CallCommand::Mute(MuteCommand::Mute)).unwrap(); handle.commands.send(CallCommand::Hangup).unwrap(); let outcome = control.until_hangup(std::future::pending::<()>()).await; assert!(matches!(outcome, Err(Error::Cancelled))); assert_eq!(control.recv().await, Some(CallCommand::Mute(MuteCommand::Mute))); } #[tokio::test] async fn a_finished_step_returns_its_value() { let (_handle, mut control) = call_channel(); assert_eq!(control.until_hangup(async { 7 }).await.unwrap(), 7); } }