Cotton code
953 lines · 43.1 KB · RustRaw
//! THE CALL, AS A PURE RULE. One call at a time on a device: what phase it//! is in, and — for every event (a tap, a route's answer, a room frame, the//! ICE state, a push, a timer) — the next phase and the effects the shell//! performs, in order. The shell decides nothing: it opens the socket it is//! told to with the credential it is handed, sends the frames it is handed,//! tells the system's call UI what it is told to tell it, and hands every//! frame, ICE change and tap back as an event.//!//! ```text//! idle ─dial─▶ dialling ─started─▶ ringing_out ─state connecting─▶ connecting ─media connected─▶ live ⇄ reconnecting//! idle ─incoming─▶ ringing_in ─accept─▶ connecting ─▶ …//! any ─▶ ended(reason)//! ```//!//! A call is peer to peer between two (`mode` p2p) or goes through the SFU//! (`mode` sfu: it rang several people, or a third joined; it never moves//! back). The room's roster is the call's `members`.//!//! **Platform-neutral.** Every effect is one a Swift shell (CallKit,//! AVAudioSession, the WebRTC framework) and a Kotlin shell (Telecom's//! ConnectionService, AudioManager, the WebRTC Android library) perform//! alike: the `system_call_*` effects are the system's call UI, and an end//! carries both CallKit's `CXCallEndedReason` and Android's `DisconnectCause`.//!//! The `ask_*` effects and `write_history` are the core's own (the phone//! methods perform them); every other effect is the shell's.use serde::{Deserialize, Serialize};use super::wire::{ClientFrame, EndReason, IceServer, Joined, MediaState, Member, MemberState, Mode, RoomFrame, RoomState, SfuOp, SignalKind, Started, Track, SOCKET_PATH};/// Waiting for the object to answer `POST /v1/calls`.pub const START_MS: i64 = 20_000;/// The room rings for 45 s; the device gives it a grace before it ends alone.pub const RING_OUT_MS: i64 = 60_000;/// A ring this device took that neither its person nor the room ended.pub const RING_IN_MS: i64 = 60_000;/// Accepted, and the media has not connected.pub const CONNECT_MS: i64 = 30_000;/// The media dropped; this long to come back.pub const RECONNECT_MS: i64 = 30_000;/// A socket that closed under a call is opened again after this.pub const REOPEN_MS: u64 = 1_000;/// What the system's call UI names an incoming call before the number is/// known: no number reaches Apple or Google in the push.pub const INCOMING_TITLE: &str = "Cotton";/// At most this many people are rung by one call (nine members with the caller).pub const MAX_INVITEES: usize = 8;#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum Phase {    Idle,    Dialling,    RingingOut,    RingingIn,    Connecting,    Live,    Reconnecting,    Ended,}#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum Direction {    In,    Out,}/// How the system's call UI is told a call ended. Each carries its CallKit/// `CXCallEndedReason` ([`SystemEnd::ios`], none meaning this person ended it:/// request a `CXEndCallAction`) and its Android `DisconnectCause` code/// ([`SystemEnd::android`], for `Connection.setDisconnected`).#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum SystemEnd {    /// This person hung up or cancelled.    Local,    /// This person declined a ring (or it was answered busy here).    Rejected,    /// The other side hung up.    Remote,    /// The person called declined.    RemoteDeclined,    /// The person called was in another call.    Busy,    /// The caller gave up before this device answered.    Cancelled,    /// The ring here ended unanswered.    Missed,    /// Nobody answered this person's call.    Unanswered,    AnsweredElsewhere,    DeclinedElsewhere,    Failed,}impl SystemEnd {    /// `CXCallEndedReason`'s raw value: failed 1, remoteEnded 2, unanswered 3,    /// answeredElsewhere 4, declinedElsewhere 5; none: a `CXEndCallAction`.    pub fn ios(self) -> Option<u8> {        match self {            SystemEnd::Local | SystemEnd::Rejected => None,            SystemEnd::Failed => Some(1),            SystemEnd::Remote | SystemEnd::RemoteDeclined | SystemEnd::Busy | SystemEnd::Cancelled => Some(2),            SystemEnd::Missed | SystemEnd::Unanswered => Some(3),            SystemEnd::AnsweredElsewhere => Some(4),            SystemEnd::DeclinedElsewhere => Some(5),        }    }    /// `android.telecom.DisconnectCause`: ERROR 1, LOCAL 2, REMOTE 3,    /// MISSED 5, REJECTED 6, BUSY 7, ANSWERED_ELSEWHERE 11.    pub fn android(self) -> u8 {        match self {            SystemEnd::Failed => 1,            SystemEnd::Local => 2,            SystemEnd::Remote | SystemEnd::RemoteDeclined | SystemEnd::Unanswered => 3,            SystemEnd::Missed | SystemEnd::Cancelled => 5,            SystemEnd::Rejected | SystemEnd::DeclinedElsewhere => 6,            SystemEnd::Busy => 7,            SystemEnd::AnsweredElsewhere => 11,        }    }}/// The tones the shell plays itself (an incoming call's ringtone is the system's).#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum Tone {    Ringback,}/// What the shell (or, for `ask_*` and `write_history`, the core's phone methods) does next.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(tag = "do", rename_all = "snake_case")]pub enum Effect {    /// The core: `POST /v1/calls { to, video, group? }` (one number, or several; `group`: a Cotton group's call).    AskStart {        to: Vec<String>,        video: bool,        #[serde(default, skip_serializing_if = "Option::is_none")]        group: Option<String>,    },    /// The core: `POST /v1/calls/<room>/join`.    AskJoin { room: String },    /// The core: `POST /v1/calls/<room>/enter` (a group's call, joined late or again).    AskEnter { room: String },    /// The core: `POST /v1/calls/<room>/decline { busy }`.    AskDecline { room: String, busy: bool },    /// The core: `POST /v1/calls/<room>/end`.    AskEnd { room: String },    /// The core: `POST /v1/calls/<room>/invite { to }`.    AskInvite { room: String, to: Vec<String> },    /// Open the room's socket at `path` with `Authorization: Bearer <credential>`, after `after_ms`.    /// Frames handed before it opens are sent, in order, once it does.    OpenSocket { path: String, credential: String, after_ms: u64 },    /// Send this frame on the socket.    Send { frame: ClientFrame },    CloseSocket,    /// Peer to peer: make the peer connection over these servers. The offerer makes its offer at once and hands it back (`calls.signal out offer`).    CreatePeer { offerer: bool, ice_servers: Vec<IceServer> },    /// Peer to peer: set the remote description. An `offer` or `restart` is answered: the shell makes the answer and hands it back (`calls.signal out answer`).    ApplyRemote { kind: SignalKind, sdp: String },    AddCandidate { candidate: String, mid: Option<String>, mline: Option<u32> },    /// Restart ICE: a restart offer handed back (`calls.signal out restart`, or `sfu renegotiate` on the SFU).    RestartIce,    /// Close the peer connection (peer to peer, or the SFU's).    ClosePeer,    /// Make the one peer connection to the SFU over these servers (any peer-to-peer one is already closed).    SwitchToSfu { ice_servers: Vec<IceServer> },    /// Add the local tracks to the SFU connection, make the offer and hand it back (`calls.signal out sfu push { sdp, tracks }`).    PushTracks { audio: bool, video: bool },    /// The SFU will offer `member`'s tracks by these names: draw them as theirs when they arrive.    PullTracks { member: String, names: Vec<String> },    /// `member` left: take their tracks and tiles away (and hand back `sfu close` for their mids).    CloseTracks { member: String },    /// The SFU's SDP: an `answer` to a push, or an `offer` to answer (`calls.signal out sfu renegotiate { sdp }`).    /// An offer's `tracks` say whose each new transceiver is, by its `mid`: draw and keep each person's apart.    ApplyRemoteSdp {        op: SfuOp,        sdp: String,        #[serde(default, skip_serializing_if = "Vec::is_empty")]        tracks: Vec<Track>,    },    /// Draw the roster: every member, their state, audio, video and who is speaking (and, on a change of    /// who takes notes, the call's `notes`: the screen is asked again).    ShowRoster { members: Vec<Member> },    /// Enable or disable the local microphone and camera tracks.    SetSending { audio: bool, video: bool },    /// Configure the audio for a call (voice or video chat).    StartAudio { video: bool },    StopAudio,    StartCamera,    StopCamera,    PlayTone { tone: Tone },    StopTone,    /// The system's call UI: an outgoing call starts.    SystemCallOutgoing { uuid: String, handle: String, name: Option<String>, video: bool },    /// The system's call UI: the outgoing call is connecting (answered).    SystemCallConnecting { uuid: String },    /// The system's call UI: the call is connected (`outgoing`: this person placed it).    SystemCallConnected { uuid: String, outgoing: bool },    /// The system's call UI: a call rings here. Inside the push handler, before it returns.    SystemCallIncoming { uuid: String, title: String, video: bool },    /// The system's call UI: who the call is with, once the object said.    SystemCallUpdate { uuid: String, handle: String, name: Option<String>, video: bool },    /// The system's call UI: the call is over, for `cause`; `ios` is CallKit's reason (none: request a    /// `CXEndCallAction`), `android` Telecom's `DisconnectCause` code.    SystemCallEnded { uuid: String, cause: SystemEnd, ios: Option<u8>, android: u8 },    /// Hand `calls.tick` back after this long.    Timer { after_ms: i64 },    /// The core: the call's row goes to the history.    WriteHistory,}/// Someone this person calls or invites.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Callee {    pub number: String,    pub person: Option<String>,    pub name: Option<String>,}/// What this device sends.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]pub struct Own {    pub audio: bool,    pub video: bool,    pub speaking: bool,}/// One call on this device.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct Call {    pub phase: Phase,    pub direction: Direction,    /// The call's kind: a video call (each member may still turn their camera off: `own`).    pub video: bool,    pub mode: Mode,    /// The system call UI's id for this call: minted at the dial, or made from the room for a ring.    pub uuid: String,    pub room: Option<String>,    /// The other side's number (a group: the first called, or the caller).    pub number: Option<String>,    /// The other side as a person in this copy, when they are one.    pub person: Option<String>,    pub name: Option<String>,    /// The room's roster (the called people as invited until the room says).    pub members: Vec<Member>,    /// This device's own member id in the roster.    pub me: Option<String>,    pub own: Own,    /// Milliseconds since the epoch.    pub started_at: i64,    /// When this phase began.    pub phase_at: i64,    pub live_at: Option<i64>,    pub ended_at: Option<i64>,    pub reason: Option<EndReason>,    /// The callee accepted before the object answered the join.    pub accepted: bool,    #[serde(default)]    pub ice_servers: Vec<IceServer>,    /// The room credential: never answered to the shell but on `open_socket`.    #[serde(skip)]    pub credential: Option<String>,    /// The socket is (being) held.    #[serde(skip)]    pub socket: bool,    /// The Cotton Chat conversation this call was placed from, when it was    /// (`chat.call`): its line goes there. None for a ring, whose line goes to    /// the caller's conversation when there is one.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub thread: Option<String>,    /// The Cotton group the call is of (its random id): its members may come in late.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub group: Option<String>,    /// The members taking notes now (Take notes), as their roster and member frames say.    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub notes: Vec<String>,    /// Who last stopped taking notes, while no one takes them: the screen says so (CONTRACT "Take notes").    #[serde(default, skip_serializing_if = "Option::is_none")]    pub notes_stopped: Option<String>,    /// This device came into a call already going (a group's, `enter`), rather than by its ring.    #[serde(default, skip_serializing_if = "std::ops::Not::not")]    pub entered: bool,    /// Take notes refused, or stopped, because someone in the call cannot show the mark (the room's `notes` frame,    /// said to the note-taker alone): kept for the screen until notes are asked again.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub notes_notice: Option<NotesNotice>,}/// Why Take notes did not start, or stopped: who in the call cannot show the mark (CONTRACT "Take notes").#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(tag = "kind", rename_all = "snake_case")]pub enum NotesNotice {    /// Refused before anything was recorded: these members' apps cannot show the mark.    Refused { members: Vec<String> },    /// Stopped: this member joined unable to show it; what was recorded is kept.    Stopped { member: String },}/// What happens.#[derive(Debug, Clone, PartialEq)]pub enum Event {    /// This person places a call to one or several. `uuid` is fresh (the methods mint it); `group`: a Cotton group's call.    Dial { uuid: String, callees: Vec<Callee>, video: bool, group: Option<String> },    /// This person joins a group's call already going (late, or again after leaving). `name`: the group's.    Enter { room: String, video: bool, group: Option<String>, name: Option<String> },    /// This device starts or stops taking notes.    Notes { on: bool },    Started(Started),    StartFailed { code: String },    /// A push rang this device.    Incoming { room: String, video: bool },    /// The object answered the join; `person`/`name` are who the number is in this copy.    Joined { answer: Joined, person: Option<String>, name: Option<String> },    JoinFailed { code: String },    Accept,    Decline,    Busy,    HangUp,    /// Leave a group call (a two-member call: hang up).    Leave,    /// Ring more people into this call.    Invite { callees: Vec<Callee> },    Mute { audio: bool, video: bool },    /// This device's own voice activity.    Speaking { on: bool },    Frame(RoomFrame),    Media(MediaState),    /// The shell's own offer, answer, candidate, restart offer or SFU op, to send.    Out(ClientFrame),    SocketClosed,    /// A stop push: the ring ended elsewhere.    Stop { reason: EndReason },    /// A timer the machine asked for fired.    Tick,}impl Call {    /// The phase before any call: what a fresh device holds.    pub fn idle() -> Call {        Call {            phase: Phase::Idle,            direction: Direction::Out,            video: false,            mode: Mode::P2p,            uuid: String::new(),            room: None,            number: None,            person: None,            name: None,            members: Vec::new(),            me: None,            own: Own { audio: true, video: false, speaking: false },            started_at: 0,            phase_at: 0,            live_at: None,            ended_at: None,            reason: None,            accepted: false,            ice_servers: Vec::new(),            credential: None,            socket: false,            thread: None,            group: None,            notes: Vec::new(),            notes_stopped: None,            entered: false,            notes_notice: None,        }    }    /// A call is under way (a new one is refused, a ring answered busy).    pub fn is_active(&self) -> bool {        !matches!(self.phase, Phase::Idle | Phase::Ended)    }    /// Seconds the call was live, so far or in all.    pub fn duration_s(&self, now: i64) -> i64 {        match self.live_at {            Some(live) => ((self.ended_at.unwrap_or(now) - live).max(0)) / 1000,            None => 0,        }    }    fn enter(&mut self, phase: Phase, now: i64) {        self.phase = phase;        self.phase_at = now;    }    /// A member the room said, keeping who this copy knows them as.    fn keep(&mut self, mut member: Member) {        let held = self.members.iter().position(|m| m.id == member.id).or_else(|| {            member.number.as_ref().and_then(|number| self.members.iter().position(|m| m.number.as_ref() == Some(number) && m.id.starts_with("invite:")))        });        match held {            Some(at) => {                let was = &self.members[at];                member.person = member.person.take().or_else(|| was.person.clone());                member.name = member.name.take().or_else(|| was.name.clone());                self.members[at] = member;            }            None => self.members.push(member),        }    }    fn invited(&mut self, callees: &[Callee]) {        for callee in callees {            if self.members.iter().any(|m| m.number.as_deref() == Some(callee.number.as_str())) {                continue;            }            self.members.push(Member {                id: format!("invite:{}", callee.number),                number: Some(callee.number.clone()),                state: MemberState::Invited,                audio: false,                video: false,                speaking: false,                notes: false,                can: Vec::new(),                person: callee.person.clone(),                name: callee.name.clone(),            });        }    }    fn in_call(&self) -> bool {        matches!(self.phase, Phase::RingingOut | Phase::Connecting | Phase::Live | Phase::Reconnecting)    }}/// The system call UI's id for a ring of `room`: the room's 32 hex as a UUID,/// so the push's report and every later one name the same call.pub fn uuid_of_room(room: &str) -> String {    let hex = if super::wire::is_room_id(room) {        room.to_string()    } else {        cotton_rules::ids::derived_id("cotton_call_uuid", &[room]).replace('-', "")    };    format!("{}-{}-{}-{}-{}", &hex[0..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..32]).to_uppercase()}/// The system call UI's id for coming into `room` at `now` (`enter`): its own each time. The room's/// [`uuid_of_room`] may already name a call the system ended on this phone (its ring, missed, or this/// phone's last time in), and iPhone's CallKit drops a new call under an id it has ended.pub fn uuid_of_entry(room: &str, now: i64) -> String {    let hex = cotton_rules::ids::derived_id("cotton_call_entry", &[room, &now.to_string()]).replace('-', "");    format!("{}-{}-{}-{}-{}", &hex[0..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..32]).to_uppercase()}/// How the system's call UI is told `reason` ended a call going `direction`.pub fn system_end(reason: EndReason, direction: Direction) -> SystemEnd {    use EndReason as R;    match (reason, direction) {        (R::HungUp, _) | (R::Cancelled, Direction::Out) => SystemEnd::Local,        (R::Declined | R::Busy, Direction::In) => SystemEnd::Rejected,        (R::Cancelled, Direction::In) => SystemEnd::Cancelled,        (R::Declined, Direction::Out) => SystemEnd::RemoteDeclined,        (R::Busy, Direction::Out) => SystemEnd::Busy,        (R::RemoteHungUp, _) => SystemEnd::Remote,        (R::NoAnswer, _) => SystemEnd::Unanswered,        (R::Missed, _) => SystemEnd::Missed,        (R::AnsweredElsewhere, _) => SystemEnd::AnsweredElsewhere,        (R::DeclinedElsewhere, _) => SystemEnd::DeclinedElsewhere,        (R::Failed | R::Lost | R::TooManyCalls | R::UnreachableNetwork, _) => SystemEnd::Failed,    }}fn ended_effect(uuid: String, cause: SystemEnd) -> Effect {    Effect::SystemCallEnded { uuid, cause, ios: cause.ios(), android: cause.android() }}/// The next phase of `call` on `event` at `now` (ms), and what to do.pub fn step(call: &Call, event: Event, now: i64) -> (Call, Vec<Effect>) {    let mut next = call.clone();    let mut out = Vec::new();    match event {        Event::Dial { uuid, callees, video, group } => {            if call.is_active() || callees.is_empty() || callees.len() > MAX_INVITEES {                return (next, out);            }            let first = callees[0].clone();            next = Call {                direction: Direction::Out,                video,                // A group's call is the SFU's from the start, whatever its size.                mode: if callees.len() > 1 || group.is_some() { Mode::Sfu } else { Mode::P2p },                group: group.clone(),                uuid: uuid.clone(),                number: Some(first.number.clone()),                person: first.person.clone(),                name: first.name.clone(),                own: Own { audio: true, video, speaking: false },                started_at: now,                ..Call::idle()            };            next.invited(&callees);            next.enter(Phase::Dialling, now);            let shown = if callees.len() > 1 || group.is_some() { None } else { first.name.clone() };            out.push(Effect::SystemCallOutgoing { uuid, handle: first.number.clone(), name: shown, video });            out.push(Effect::AskStart { to: callees.into_iter().map(|c| c.number).collect(), video, group });            out.push(Effect::StartAudio { video });            if video {                out.push(Effect::StartCamera);            }            out.push(Effect::Timer { after_ms: START_MS });        }        Event::Enter { room, video, group, name } => {            if call.is_active() {                return (next, out);            }            let uuid = uuid_of_entry(&room, now);            // Coming in is this person's own act: placed as an outgoing call, taken as soon as the room lets it in.            next = Call { direction: Direction::In, video, uuid: uuid.clone(), room: Some(room.clone()), group, name: name.clone(), own: Own { audio: true, video, speaking: false }, started_at: now, accepted: true, entered: true, mode: Mode::Sfu, ..Call::idle() };            next.enter(Phase::Dialling, now);            out.push(Effect::SystemCallOutgoing { uuid, handle: String::new(), name, video });            out.push(Effect::AskEnter { room });            out.push(Effect::Timer { after_ms: START_MS });        }        Event::Notes { on } => {            next.notes_notice = None;            if call.socket && matches!(call.phase, Phase::Live | Phase::Reconnecting | Phase::Connecting | Phase::RingingOut) {                out.push(Effect::Send { frame: ClientFrame::Notes { on } });            }        }        Event::Started(started) => match call.phase {            Phase::Dialling => {                next.room = Some(started.room);                next.credential = Some(started.credential.clone());                next.ice_servers = started.ice_servers.clone();                if started.mode == Mode::Sfu {                    next.mode = Mode::Sfu;                }                if started.group.is_some() {                    next.group = started.group.clone();                }                next.me = started.me.clone().or_else(|| Some("caller".into()));                next.socket = true;                next.enter(Phase::RingingOut, now);                out.push(Effect::OpenSocket { path: SOCKET_PATH.into(), credential: started.credential, after_ms: 0 });                if next.mode == Mode::Sfu {                    out.push(Effect::SwitchToSfu { ice_servers: started.ice_servers });                    out.push(Effect::PushTracks { audio: next.own.audio, video: next.own.video });                    out.push(Effect::ShowRoster { members: next.members.clone() });                } else {                    out.push(Effect::CreatePeer { offerer: true, ice_servers: started.ice_servers });                    // The camera asked again now the peer stands: asked at the dial, a shell whose camera feeds the                    // peer's video source had none yet (Android's started nothing, so the caller sent no video; lane                    // chat-open, 21 Nov 2026). Starting a camera already started does nothing.                    if next.video && next.own.video {                        out.push(Effect::StartCamera);                    }                }                out.push(Effect::PlayTone { tone: Tone::Ringback });                out.push(Effect::Timer { after_ms: RING_OUT_MS });            }            // Hung up while the object was making the room: the room is ended, and the call is history now.            Phase::Ended if call.direction == Direction::Out && call.room.is_none() && call.reason == Some(EndReason::Cancelled) => {                next.room = Some(started.room.clone());                out.push(Effect::AskEnd { room: started.room });                out.push(Effect::WriteHistory);            }            _ => {}        },        Event::StartFailed { code } => {            if call.phase == Phase::Dialling {                let reason = if code == "too_many_calls" { EndReason::TooManyCalls } else { EndReason::UnreachableNetwork };                end(&mut next, &mut out, reason, false, now);            }        }        Event::Incoming { room, video } => {            if call.is_active() {                // The same ring pushed twice is reported again (every VoIP push is); another is not this machine's (`ring_while_busy`).                if call.room.as_deref() == Some(room.as_str()) && call.phase == Phase::RingingIn {                    out.push(Effect::SystemCallIncoming { uuid: call.uuid.clone(), title: INCOMING_TITLE.into(), video: call.video });                }                return (next, out);            }            // The same ring again after it ended here (its frame and its push, or a socket that opened late): it rang            // once, and rings no more (CALLS FIX 1).            if call.phase == Phase::Ended && call.room.as_deref() == Some(room.as_str()) {                return (next, out);            }            next = Call { direction: Direction::In, video, uuid: uuid_of_room(&room), room: Some(room.clone()), own: Own { audio: true, video, speaking: false }, started_at: now, ..Call::idle() };            next.enter(Phase::RingingIn, now);            out.push(Effect::SystemCallIncoming { uuid: next.uuid.clone(), title: INCOMING_TITLE.into(), video });            out.push(Effect::AskJoin { room });            out.push(Effect::Timer { after_ms: RING_IN_MS });        }        Event::Joined { answer, person, name } => {            let entering = call.entered && call.phase == Phase::Dialling;            if (call.phase == Phase::RingingIn || entering) && call.room.as_deref() == Some(answer.room.as_str()) {                if entering {                    next.enter(Phase::RingingIn, now);                }                next.number = Some(answer.from.clone());                next.person = person;                // A group's call keeps the group's name (the shell named it by the group as it rang; the walk on dev                // saw it cleared here on answering, 23 Nov 2026); a one-to-one ring is named by its caller.                let group_call = entering || call.group.is_some() || answer.group.is_some();                next.name = if group_call { call.name.clone().or(name.clone()) } else { name.clone() };                next.mode = if call.group.is_some() || answer.group.is_some() { Mode::Sfu } else { answer.mode };                if answer.group.is_some() {                    next.group = answer.group.clone();                }                next.me = answer.me.clone();                next.credential = Some(answer.credential.clone());                next.ice_servers = answer.ice_servers.clone();                next.socket = true;                out.push(Effect::SystemCallUpdate { uuid: call.uuid.clone(), handle: answer.from, name, video: call.video });                out.push(Effect::OpenSocket { path: SOCKET_PATH.into(), credential: answer.credential, after_ms: 0 });                if call.accepted {                    accept(&mut next, &mut out, now);                }            }        }        Event::JoinFailed { .. } => {            if call.phase == Phase::RingingIn {                end(&mut next, &mut out, EndReason::Missed, false, now);            } else if call.entered && call.phase == Phase::Dialling {                // Not let in (over already, or here on another phone): nothing was joined, so nothing goes to the history.                next.room = None;                end(&mut next, &mut out, EndReason::Failed, false, now);            }        }        Event::Accept => {            if call.phase == Phase::RingingIn && !call.accepted {                next.accepted = true;                if call.credential.is_some() {                    accept(&mut next, &mut out, now);                }            }        }        Event::Decline | Event::Busy => {            if call.phase == Phase::RingingIn {                let busy = matches!(event, Event::Busy);                decline(&mut next, &mut out, busy, now);            }        }        Event::HangUp | Event::Leave => match call.phase {            Phase::Dialling if call.entered => {                // Given up before the room let this phone in: it stops ringing there, and leaves no history.                if let Some(room) = call.room.clone() {                    out.push(Effect::AskDecline { room, busy: false });                }                next.room = None;                end(&mut next, &mut out, EndReason::Cancelled, false, now);            }            Phase::Dialling => end(&mut next, &mut out, EndReason::Cancelled, false, now),            Phase::RingingOut => end(&mut next, &mut out, EndReason::Cancelled, true, now),            Phase::RingingIn => decline(&mut next, &mut out, false, now),            Phase::Connecting | Phase::Live | Phase::Reconnecting => end(&mut next, &mut out, EndReason::HungUp, true, now),            Phase::Idle | Phase::Ended => {}        },        Event::Invite { callees } => {            let fresh: Vec<Callee> = callees.into_iter().filter(|c| !call.members.iter().any(|m| m.number.as_deref() == Some(c.number.as_str()) && m.state == MemberState::Joined)).collect();            if call.in_call() && !fresh.is_empty() && call.members.len() + fresh.len() <= MAX_INVITEES + 1 {                if let Some(room) = &call.room {                    next.invited(&fresh);                    out.push(Effect::AskInvite { room: room.clone(), to: fresh.into_iter().map(|c| c.number).collect() });                    out.push(Effect::ShowRoster { members: next.members.clone() });                }            }        }        Event::Mute { audio, video } => {            if call.is_active() {                // A camera is turned on only in a video call.                let video = video && call.video;                next.own.audio = audio;                next.own.video = video;                out.push(Effect::SetSending { audio, video });                if call.socket {                    out.push(Effect::Send { frame: ClientFrame::Mute { audio, video } });                }            }        }        Event::Speaking { on } => {            if call.socket && call.own.speaking != on && matches!(call.phase, Phase::Live | Phase::Reconnecting) {                next.own.speaking = on;                out.push(Effect::Send { frame: ClientFrame::Speaking { on } });            }        }        Event::Frame(frame) => {            if !call.is_active() || !call.socket {                return (next, out);            }            room_frame(call, &mut next, &mut out, frame, now);        }        Event::Media(state) => {            if !call.is_active() || !call.socket {                return (next, out);            }            match (state, call.phase) {                (MediaState::Connected, Phase::Connecting | Phase::Reconnecting | Phase::Live) => {                    out.push(Effect::Send { frame: ClientFrame::Media { state } });                    live(&mut next, &mut out, now);                }                (MediaState::Failed, Phase::Connecting) => {                    out.push(Effect::Send { frame: ClientFrame::Media { state } });                    end(&mut next, &mut out, EndReason::Failed, false, now);                }                (MediaState::Disconnected | MediaState::Failed, Phase::Live) => {                    out.push(Effect::Send { frame: ClientFrame::Media { state } });                    next.enter(Phase::Reconnecting, now);                    // Peer to peer the caller restarts; on the SFU each member restarts its own connection.                    if call.direction == Direction::Out || call.mode == Mode::Sfu {                        out.push(Effect::RestartIce);                    }                    out.push(Effect::Timer { after_ms: RECONNECT_MS });                }                (_, _) => out.push(Effect::Send { frame: ClientFrame::Media { state } }),            }        }        Event::Out(frame) => {            if call.is_active() && call.socket {                out.push(Effect::Send { frame });            }        }        Event::SocketClosed => {            if call.is_active() && call.socket {                if call.phase == Phase::Live {                    next.enter(Phase::Reconnecting, now);                    out.push(Effect::Timer { after_ms: RECONNECT_MS });                }                if let Some(credential) = &call.credential {                    out.push(Effect::OpenSocket { path: SOCKET_PATH.into(), credential: credential.clone(), after_ms: REOPEN_MS });                }            }        }        Event::Stop { reason } => {            if call.phase == Phase::RingingIn {                end(&mut next, &mut out, reason, false, now);            }        }        Event::Tick => {            let waited = now - call.phase_at;            match call.phase {                Phase::Dialling if waited >= START_MS => end(&mut next, &mut out, EndReason::UnreachableNetwork, false, now),                Phase::RingingOut if waited >= RING_OUT_MS => end(&mut next, &mut out, EndReason::NoAnswer, true, now),                Phase::RingingIn if waited >= RING_IN_MS => end(&mut next, &mut out, EndReason::Missed, false, now),                Phase::Connecting if waited >= CONNECT_MS => end(&mut next, &mut out, EndReason::Failed, true, now),                Phase::Reconnecting if waited >= RECONNECT_MS => end(&mut next, &mut out, EndReason::Lost, true, now),                _ => {}            }        }    }    (next, out)}fn room_frame(call: &Call, next: &mut Call, out: &mut Vec<Effect>, frame: RoomFrame, now: i64) {    match frame {        RoomFrame::State { state, .. } => match state {            RoomState::Connecting if call.phase == Phase::RingingOut => {                next.enter(Phase::Connecting, now);                out.push(Effect::StopTone);                out.push(Effect::SystemCallConnecting { uuid: call.uuid.clone() });                out.push(Effect::Timer { after_ms: CONNECT_MS });            }            RoomState::Live => live(next, out, now),            RoomState::Reconnecting if call.phase == Phase::Live => {                next.enter(Phase::Reconnecting, now);                out.push(Effect::Timer { after_ms: RECONNECT_MS });            }            _ => {}        },        RoomFrame::Signal { kind, sdp, candidate, mid, mline, .. } => match kind {            SignalKind::Ice => {                if let Some(candidate) = candidate {                    out.push(Effect::AddCandidate { candidate, mid, mline });                }            }            SignalKind::Offer | SignalKind::Answer | SignalKind::Restart => {                if let Some(sdp) = sdp {                    out.push(Effect::ApplyRemote { kind, sdp });                }            }        },        RoomFrame::Ended { reason } => end(next, out, reason, false, now),        RoomFrame::Mode { mode } => {            if mode == Mode::Sfu && call.mode == Mode::P2p {                next.mode = Mode::Sfu;                // A ring not yet taken moves nothing: the accept makes the SFU connection.                if call.in_call() {                    out.push(Effect::ClosePeer);                    out.push(Effect::SwitchToSfu { ice_servers: call.ice_servers.clone() });                    out.push(Effect::PushTracks { audio: call.own.audio, video: call.own.video });                }            }        }        RoomFrame::Roster { members } => {            for member in members {                next.keep(member);            }            set_notes(next);            out.push(Effect::ShowRoster { members: next.members.clone() });        }        RoomFrame::Member { member } => {            let gone = matches!(member.state, MemberState::Left | MemberState::Declined | MemberState::NoAnswer | MemberState::Busy);            let id = member.id.clone();            next.keep(member);            set_notes(next);            if gone && call.mode == Mode::Sfu {                out.push(Effect::CloseTracks { member: id });            }            out.push(Effect::ShowRoster { members: next.members.clone() });        }        RoomFrame::Tracks { member, tracks } => {            if call.mode == Mode::Sfu && !tracks.is_empty() {                let names: Vec<String> = tracks.iter().map(|t| t.name.clone()).collect();                let wanted = names.iter().map(|name| Track { mid: None, member: Some(member.clone()), name: name.clone(), kind: None }).collect();                out.push(Effect::Send { frame: ClientFrame::Sfu { op: SfuOp::Pull, sdp: None, tracks: Some(wanted), mids: None } });                out.push(Effect::PullTracks { member, names });            }        }        RoomFrame::Speaking { member, on } => {            if let Some(held) = next.members.iter_mut().find(|m| m.id == member) {                if held.speaking != on {                    held.speaking = on;                    out.push(Effect::ShowRoster { members: next.members.clone() });                }            }        }        RoomFrame::Sfu { op, sdp, tracks } => {            if let (SfuOp::Answer | SfuOp::Offer, Some(sdp)) = (op, sdp) {                out.push(Effect::ApplyRemoteSdp { op, sdp, tracks });            }        }        // Said to the note-taker alone (refused, or stopped by someone who cannot show the mark): the screen asks again.        RoomFrame::Notes { refused, stopped, member, members } => {            if refused.is_some() {                next.notes_notice = Some(NotesNotice::Refused { members });            } else if stopped.is_some() {                next.notes_notice = Some(NotesNotice::Stopped { member: member.unwrap_or_default() });            }            out.push(Effect::ShowRoster { members: next.members.clone() });        }        // Frame encryption is not built: the frames are relayed and kept by nobody.        RoomFrame::E2ee { .. } | RoomFrame::Hello { .. } | RoomFrame::Pong | RoomFrame::Error { .. } => {}    }}/// Who takes notes now, from the members; whoever stopped, while no one takes them, is kept to be said.fn set_notes(next: &mut Call) {    let now: Vec<String> = next.members.iter().filter(|m| m.notes).map(|m| m.id.clone()).collect();    if let Some(gone) = next.notes.iter().find(|id| !now.contains(id)) {        next.notes_stopped = Some(gone.clone());    }    if !now.is_empty() {        next.notes_stopped = None;    }    next.notes = now;}/// A ring of another room while this device is in a call: reported (every/// VoIP push must be), answered busy, and ended at once.pub fn ring_while_busy(room: &str) -> Vec<Effect> {    let uuid = uuid_of_room(room);    vec![        Effect::SystemCallIncoming { uuid: uuid.clone(), title: INCOMING_TITLE.into(), video: false },        Effect::AskDecline { room: room.to_string(), busy: true },        ended_effect(uuid, SystemEnd::Missed),    ]}/// A stop push for a ring this device holds no call for (it came after the/// ring ended here, or before the ring did): reported and ended at once.pub fn stray_stop(room: &str, reason: EndReason) -> Vec<Effect> {    let uuid = uuid_of_room(room);    vec![        Effect::SystemCallIncoming { uuid: uuid.clone(), title: INCOMING_TITLE.into(), video: false },        ended_effect(uuid, system_end(reason, Direction::In)),    ]}fn accept(call: &mut Call, out: &mut Vec<Effect>, now: i64) {    call.enter(Phase::Connecting, now);    out.push(Effect::Send { frame: ClientFrame::Accept });    if call.mode == Mode::Sfu {        out.push(Effect::SwitchToSfu { ice_servers: call.ice_servers.clone() });        out.push(Effect::PushTracks { audio: call.own.audio, video: call.own.video });    } else {        out.push(Effect::CreatePeer { offerer: false, ice_servers: call.ice_servers.clone() });    }    out.push(Effect::StartAudio { video: call.video });    if call.video {        out.push(Effect::StartCamera);    }    out.push(Effect::Timer { after_ms: CONNECT_MS });}fn decline(call: &mut Call, out: &mut Vec<Effect>, busy: bool, now: i64) {    let room = call.room.clone().unwrap_or_default();    if call.socket {        out.push(Effect::Send { frame: if busy { ClientFrame::Busy } else { ClientFrame::Decline } });    } else {        out.push(Effect::AskDecline { room, busy });    }    end(call, out, if busy { EndReason::Busy } else { EndReason::Declined }, false, now);}fn live(call: &mut Call, out: &mut Vec<Effect>, now: i64) {    if call.phase == Phase::Live {        return;    }    let first = call.live_at.is_none();    call.enter(Phase::Live, now);    call.live_at.get_or_insert(now);    out.push(Effect::StopTone);    if first {        out.push(Effect::SystemCallConnected { uuid: call.uuid.clone(), outgoing: call.direction == Direction::Out });    }}/// The call ends for `reason`: `send_end` when the room has not said so and/// must be told (`leave` on the SFU, where the others go on).fn end(call: &mut Call, out: &mut Vec<Effect>, reason: EndReason, send_end: bool, now: i64) {    if send_end && call.socket {        out.push(Effect::Send { frame: if call.mode == Mode::Sfu { ClientFrame::Leave } else { ClientFrame::End } });    }    let was = call.phase;    call.enter(Phase::Ended, now);    call.reason = Some(reason);    call.ended_at = Some(now);    call.own.speaking = false;    if was == Phase::RingingOut {        out.push(Effect::StopTone);    }    // A ring nobody took started no peer, no camera and no audio.    if was != Phase::RingingIn || call.accepted {        out.push(Effect::ClosePeer);        if call.video {            out.push(Effect::StopCamera);        }        out.push(Effect::StopAudio);    }    if call.socket {        out.push(Effect::CloseSocket);        call.socket = false;    }    call.credential = None;    out.push(ended_effect(call.uuid.clone(), system_end(reason, call.direction)));    if call.room.is_some() && super::history::writes(call) {        out.push(Effect::WriteHistory);    }}#[cfg(test)]#[path = "machine_tests.rs"]mod tests;