Skip to main content

sew_call_client/
call.rs

1//! The public engine API: [`CallClient`] (one per app) and [`Call`] (one live
2//! call), their events, and the frame API the audio pipeline (kessel-audio, or a host's own)
3//! drives.
4//!
5//! Recording (Sew 0.7.3): the call's recording as Sew says it is
6//! [`Call::recording`] and [`CallEvent::Recording`]; the person answers its notice with
7//! [`Call::consent`] and withdraws with [`Call::withdraw_consent`] ("Stop recording me"), both
8//! through the host ([`JoinProvider::consent`]). A join into a recorded room that has no answer
9//! is held at [`CallState::ConsentRequired`] (no media, no keys, nothing captured) until the
10//! host answers or leaves. No answer is never consent: this device's key reaches the recorder
11//! only after Sew says `granted`.
12//!
13//! Record and Stop (Sew 0.9.0): [`Call::start_recording`] and [`Call::stop_recording`], the
14//! person's own acts, also through the host ([`JoinProvider::recording`]). The recording says
15//! what started it ([`CallRecording::trigger`]) and whether the room requires it
16//! ([`CallRecording::required`]).
17//!
18//! The person's Record and Stop: a Sew server that computes them sends them to the call
19//! ([`Call::recording_controls`], [`CallEvent::RecordingControls`],
20//! [`CallRecording::my_controls`]); [`Call::server_controls`] says whether this call's server
21//! does. Against an older server both stay empty, and the host works the buttons out itself.
22
23use std::sync::atomic::{AtomicBool, Ordering};
24use std::sync::{Arc, Mutex};
25use std::time::Instant;
26
27use bytes::Bytes;
28use serde::Serialize;
29use tokio::sync::{broadcast, mpsc, oneshot};
30
31use crate::config::ClientConfig;
32use crate::e2ee::E2eeProvider;
33use crate::engine;
34use crate::provider::{
35    ConsentRequired, JoinProvider, JoinRequest, ProviderError, RecordingControl,
36};
37use crate::stats::{CallStatsReport, PlayoutStats, StatsWindow};
38use sew_proto::recording::RecordingTrigger;
39
40/// Frames the send queue holds (20 ms each: one second).
41pub(crate) const SEND_QUEUE: usize = 50;
42/// Items the receive queue holds before it drops (and counts) new frames.
43pub(crate) const RECV_QUEUE: usize = 1024;
44/// Items the video receive queue holds before it drops (and counts) new frames.
45pub(crate) const VIDEO_RECV_QUEUE: usize = 256;
46
47/// Why a call ended (`ended.reason`).
48#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
49#[serde(rename_all = "snake_case")]
50#[non_exhaustive]
51pub enum EndReason {
52    /// The host left.
53    Left,
54    /// The host has no Sew session.
55    SigninRequired,
56    /// The network or the engine is gone for good (or relay-only had no `turns:`).
57    Network,
58    /// The keys refused the call.
59    E2eeRefused,
60    /// Sew no longer accepts the call credential (another device took over: `replaced`, or a
61    /// 4011 from a Sew older than 0.7.2 with no engine `Disconnect` before it).
62    CredentialLost,
63    /// The call credential expired: Sew refused its renewal as `expired`, or no renewal got
64    /// through (the network, a `5xx`) before it ran out (`credential_expired`).
65    CredentialExpired,
66    /// The engine removed this participant and Sew gave no reason within 1.5 s (`kicked`).
67    Kicked,
68    /// The engine closed or deleted the room and Sew gave no reason within 1.5 s
69    /// (`room_closed`).
70    RoomClosed,
71    /// Sew ended this join and said why (Sew 0.7.2): its voice leave reason as it arrived
72    /// (`perms_lost`, `removed_from_space`, `timed_out`, `channel_archived`,
73    /// `account_removed`, `removed_by_moderator`, `session_revoked`, `device_revoked`, …;
74    /// an open set). From the call socket's self copy of `voice_state_updated` or its `4011`
75    /// close; the key group's removal only when the call socket said nothing within 1.5 s of
76    /// it (it names `disconnected` for a reason the key protocol has no code for).
77    Removed(String),
78    /// Sew refused the (re-)join; the code is in the `errors` event.
79    Refused(String),
80}
81
82/// The call's state (`state` event).
83#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
84#[serde(tag = "state", rename_all = "snake_case")]
85#[non_exhaustive]
86pub enum CallState {
87    /// Getting media and keys up.
88    Connecting,
89    /// Media is up **and** a key epoch is active: you can hear and be heard.
90    Connected,
91    /// Resuming or reconnecting (attempt counts from 1).
92    Reconnecting {
93        /// The attempt.
94        attempt: u32,
95    },
96    /// Held (Sew 0.7.3): the room is recorded and Sew refused the join until the person
97    /// answers its notice (`409 recording_consent_required`). No media, no keys, nothing is
98    /// captured or sent. The notice is [`Call::recording`]'s `consent_prompt`; answer with
99    /// [`Call::consent`] (the engine re-joins with the answer) or give up with
100    /// [`Call::leave`]. Waits as long as the host does (a lock-screen answer may take a while).
101    ConsentRequired {
102        /// The recording (Sew's id, a decimal string), or `auto` for an auto-record channel's
103        /// first join.
104        recording_id: String,
105        /// The notice's version: what [`Call::consent`] echoes.
106        notice_version: u32,
107    },
108    /// Over.
109    Ended {
110        /// Why.
111        reason: EndReason,
112    },
113}
114
115/// One participant (`participants` event). Names are the host's.
116#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
117#[non_exhaustive]
118pub struct Participant {
119    /// The engine identity (`p_…`, one per join).
120    pub identity: String,
121    /// The Sew member, once the keys' roster or the call socket named it.
122    pub member_id: Option<String>,
123    /// This device.
124    pub is_self: bool,
125    /// Muted (self or by a moderator, the track is muted, or SPEAK denied).
126    pub muted: bool,
127    /// Deafened.
128    pub deafened: bool,
129    /// Muted by a moderator.
130    pub server_muted: bool,
131    /// Deafened by a moderator.
132    pub server_deafened: bool,
133    /// The member lacks SPEAK here (Sew's `VoiceState.speak_denied`; for this device also the
134    /// engine's permission): nothing is captured or published until it is granted again. Not a
135    /// moderator mute (`server_muted`).
136    pub speak_denied: bool,
137    /// The recorder (Sew Notes): the engine's recorder participant, which has no member.
138    pub recorder: bool,
139    /// The participant's camera track, if it publishes one (`video-core` builds).
140    #[serde(skip_serializing_if = "Option::is_none")]
141    pub camera: Option<crate::video::VideoTrackView>,
142    /// The participant's screen-share track, if it publishes one (`video-core` builds).
143    #[serde(skip_serializing_if = "Option::is_none")]
144    pub screen: Option<crate::video::VideoTrackView>,
145}
146
147/// A person's answer to a recording's notice, as Sew stores it.
148#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
149#[serde(rename_all = "snake_case")]
150#[non_exhaustive]
151pub enum RecordingConsent {
152    /// Not answered (never recorded).
153    Pending,
154    /// Agreed: recorded while captured.
155    Granted,
156    /// Declined (unrecorded, or not joined when declining means not joining).
157    Declined,
158    /// Agreed, then withdrew ("Stop recording me").
159    Withdrawn,
160}
161
162impl RecordingConsent {
163    /// From Sew's consent (`None`: not a participant yet, so `pending`; a value this engine
164    /// does not know is not a grant, so `declined`).
165    pub fn from_sew(c: Option<sew_proto::recording::Consent>) -> RecordingConsent {
166        use sew_proto::recording::Consent as C;
167        match c {
168            None | Some(C::Pending) => RecordingConsent::Pending,
169            Some(C::Granted) => RecordingConsent::Granted,
170            Some(C::Withdrawn) => RecordingConsent::Withdrawn,
171            Some(_) => RecordingConsent::Declined,
172        }
173    }
174}
175
176/// One participant of the recording, as everyone in the call sees it.
177#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
178#[non_exhaustive]
179pub struct RecordingMember {
180    /// The member (Sew's id, a decimal string).
181    pub member_id: String,
182    /// Their answer.
183    pub consent: RecordingConsent,
184    /// The recorder captures them now (granted and captured).
185    pub recorded: bool,
186}
187
188/// The call's recording as Sew says it (`recording` event, [`Call::recording`]).
189#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
190#[non_exhaustive]
191pub struct CallRecording {
192    /// The recording (Sew's id, a decimal string), or `auto` while a join into an auto-record
193    /// channel waits for an answer.
194    pub recording_id: String,
195    /// Started by an auto-record channel.
196    pub auto: bool,
197    /// Who started it (Sew's member id), when known.
198    pub started_by: Option<String>,
199    /// When it started, by Sew's clock: a person who joins a call already being recorded
200    /// shows the recording's real running time from it. `None` while a held join waits for an
201    /// answer and Sew has not sent the recording itself (an auto-record room's first join).
202    /// Left out of the serialised form when `None`.
203    #[serde(skip_serializing_if = "Option::is_none")]
204    pub started_at: Option<sew_proto::time::Timestamp>,
205    /// How many days Sew keeps the recording's audio, by the room's policy (0: the audio is
206    /// deleted once the transcript is final). From Sew's recording; while a held join waits
207    /// and Sew has not sent the recording itself (an auto-record room's first join), from the
208    /// notice the person answers, which carries the same policy. Always known, so a person who
209    /// already answered the notice can still show how long the audio is kept.
210    pub audio_keep_days: u16,
211    /// This person's answer.
212    pub my_consent: RecordingConsent,
213    /// The notice to show while this person has not answered (`pending`), with its
214    /// `notice_version`; `None` once answered.
215    pub consent_prompt: Option<sew_proto::recording::ConsentPrompt>,
216    /// Everyone in it.
217    pub participants: Vec<RecordingMember>,
218    /// What started it (Sew 0.9.0): a person pressing Record (`manual`), an auto-record
219    /// room's first join (`auto`), or the room reaching two people while it requires recording
220    /// (`required`). From `auto` against an older Sew.
221    pub trigger: RecordingTrigger,
222    /// The room requires its recording (Sew 0.9.0): it records every call with two or more
223    /// people in it, so Sew refuses a Stop (`recording_required`) while two or more are in the
224    /// room. "Stop recording me" ([`Call::withdraw_consent`]) always works. True when Sew
225    /// started it under that rule (`trigger: required`) or its notice says so
226    /// (`consent_prompt.required`).
227    pub required: bool,
228    /// This person's Record and Stop in the call's room as Sew computed them, carried in the
229    /// recording (`None` from a server that does not compute them, or outside the room).
230    #[serde(skip_serializing_if = "Option::is_none")]
231    pub my_controls: Option<ServerControls>,
232}
233
234/// A person's Record and Stop in the call's room, as Sew computes them
235/// ([`Call::recording_controls`], [`CallEvent::RecordingControls`],
236/// [`CallRecording::my_controls`]). Of two values, the larger `rev` is the newer. Sew still
237/// decides each Record and Stop; show its refusal if one comes.
238#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
239#[non_exhaustive]
240pub struct ServerControls {
241    /// Sew would take this person's Record now.
242    pub can_record: bool,
243    /// Sew would take this person's Stop now.
244    pub can_stop: bool,
245    /// The value's revision (server-wide, increasing).
246    pub rev: u64,
247    /// While the person may record: why a start would be refused for now (the install's
248    /// recording capacity is full, or the recorder does not answer). A hint only.
249    #[serde(skip_serializing_if = "Option::is_none")]
250    pub record_unavailable: Option<sew_proto::recording::RecordUnavailable>,
251}
252
253impl ServerControls {
254    /// The value Sew sent.
255    pub fn from_sew(c: &sew_proto::recording::RecordingControls) -> ServerControls {
256        ServerControls {
257            can_record: c.can_record,
258            can_stop: c.can_stop,
259            rev: c.rev,
260            record_unavailable: c.record_unavailable,
261        }
262    }
263
264    /// The pair, with `rev` 0 and no hint (for a host's own engine or a test).
265    pub fn new(can_record: bool, can_stop: bool) -> ServerControls {
266        ServerControls {
267            can_record,
268            can_stop,
269            rev: 0,
270            record_unavailable: None,
271        }
272    }
273}
274
275/// What started `r`: Sew's `trigger`. An older Sew sends none (read as `manual`), so an
276/// automatic start there shows only in `auto`: `auto` with `manual` reads as `auto` (Sew 0.9.0
277/// never sends that pair: a required start has `auto` and `required`).
278fn trigger_of(r: &sew_proto::recording::Recording) -> RecordingTrigger {
279    if r.auto && r.trigger == RecordingTrigger::Manual {
280        RecordingTrigger::Auto
281    } else {
282        r.trigger
283    }
284}
285
286/// The notice says the room requires recording (its `required` slot).
287fn prompt_required(p: &sew_proto::recording::ConsentPrompt) -> bool {
288    p.required
289}
290
291impl CallRecording {
292    /// The recording in Sew's shape (the member's own view).
293    pub fn from_sew(r: &sew_proto::recording::Recording) -> CallRecording {
294        use sew_proto::recording::Capture;
295        let trigger = trigger_of(r);
296        CallRecording {
297            recording_id: r.id.to_string(),
298            auto: r.auto,
299            started_by: Some(r.started_by.to_string()),
300            started_at: Some(r.started_at),
301            audio_keep_days: r.audio_keep_days,
302            my_consent: RecordingConsent::from_sew(r.my_consent),
303            consent_prompt: r.consent_prompt.clone(),
304            participants: r
305                .participants
306                .iter()
307                .map(|p| RecordingMember {
308                    member_id: p.member_id.to_string(),
309                    consent: RecordingConsent::from_sew(Some(p.consent)),
310                    recorded: p.capture == Some(Capture::Recorded),
311                })
312                .collect(),
313            trigger,
314            required: trigger == RecordingTrigger::Required
315                || r.consent_prompt.as_ref().is_some_and(prompt_required),
316            my_controls: r.my_controls.as_ref().map(ServerControls::from_sew),
317        }
318    }
319
320    /// The recording a held join shows: Sew's `409`'s recording with its prompt, or (an
321    /// auto-record channel's first join) the prompt alone.
322    pub fn from_consent_required(c: &ConsentRequired) -> CallRecording {
323        match &c.recording {
324            Some(r) => {
325                let mut out = CallRecording::from_sew(r);
326                out.consent_prompt = Some(c.consent_prompt.clone());
327                out.my_consent = RecordingConsent::Pending;
328                out.required |= prompt_required(&c.consent_prompt);
329                out
330            }
331            // No recording yet: the answer is held for the one the room starts (an
332            // auto-record room's first join, or a room that requires recording once a second
333            // person joins).
334            None => {
335                let required = prompt_required(&c.consent_prompt);
336                CallRecording {
337                    recording_id: c.consent_prompt.recording_id.to_string(),
338                    auto: c.auto,
339                    started_by: c
340                        .consent_prompt
341                        .started_by
342                        .as_ref()
343                        .map(|m| m.member_id.to_string()),
344                    started_at: None,
345                    audio_keep_days: c.consent_prompt.audio_keep_days,
346                    my_consent: RecordingConsent::Pending,
347                    consent_prompt: Some(c.consent_prompt.clone()),
348                    participants: Vec::new(),
349                    trigger: if required && !c.auto {
350                        RecordingTrigger::Required
351                    } else {
352                        RecordingTrigger::from_auto(c.auto)
353                    },
354                    required,
355                    my_controls: None,
356                }
357            }
358        }
359    }
360}
361
362/// A speaking level (`speaking` event).
363#[derive(Clone, Debug, PartialEq, Serialize)]
364#[non_exhaustive]
365pub struct Speaking {
366    /// The engine identity.
367    pub identity: String,
368    /// The member, when known.
369    pub member_id: Option<String>,
370    /// 0..1.
371    pub level: f32,
372}
373
374/// An error for the host (`errors` event): `{code, detail}`.
375#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
376#[non_exhaustive]
377pub struct CallErrorEvent {
378    /// `turn_unreachable`, `relay_only_no_turns`, `e2ee_refused`, a provider's code, …
379    pub code: String,
380    /// Details.
381    pub detail: String,
382}
383
384impl CallErrorEvent {
385    /// An error with its code and details (for a host's own engine or a test).
386    pub fn new(code: impl Into<String>, detail: impl Into<String>) -> CallErrorEvent {
387        CallErrorEvent {
388            code: code.into(),
389            detail: detail.into(),
390        }
391    }
392}
393
394/// Something that happened in the call.
395#[derive(Clone, Debug, PartialEq)]
396#[non_exhaustive]
397pub enum CallEvent {
398    /// The state changed.
399    State(CallState),
400    /// The participants changed.
401    Participants(Vec<Participant>),
402    /// Speaking levels (at most 10 Hz).
403    Speaking(Vec<Speaking>),
404    /// An error or warning.
405    Error(CallErrorEvent),
406    /// A moderator moved this member (Sew's `voice_server_updated`): the call goes on in the
407    /// destination. Sent before the engine reconnects there; a re-join after it asks the
408    /// provider for [`CallMoved::room`].
409    Moved(CallMoved),
410    /// A stats window ended: its numbers, the beacon sample sent (if any) and Sew's answer
411    /// (also in [`Call::stats`]).
412    Stats(Box<StatsWindow>),
413    /// The call's recording changed (Sew 0.7.3): started, someone answered, this person's
414    /// prompt, or `None` once no recording is active (also [`Call::recording`]).
415    Recording(Option<Box<CallRecording>>),
416    /// The person's Record and Stop in the call's room, from a Sew server that computes them
417    /// (also [`Call::recording_controls`]): a newer value, or `None` once a move took the call
418    /// to a room the server has sent none for yet. Never sent by an older server.
419    RecordingControls(Option<ServerControls>),
420    /// The call's key state or its security code changed (also [`CallSnapshot::security`]):
421    /// a new epoch, the keys securing or recovering, or a re-join's new key session.
422    Security(CallSecurity),
423    /// A remote camera or screen track appeared (`video-core` builds). It is disabled at the
424    /// media server until the host opens a sink for it ([`Call::video_sink`]).
425    VideoAdded(crate::video::VideoTrack),
426    /// A remote video track ended (unpublished, or its publisher left).
427    VideoRemoved {
428        /// Its id ([`crate::VideoTrack::id`]).
429        id: u64,
430        /// Its track sid.
431        track_sid: String,
432    },
433    /// A remote video track changed: muted, its size or layers, its codec (known from its
434    /// first packet), or paused by the server for congestion.
435    VideoChanged(crate::video::VideoTrack),
436    /// A local camera or screen share went on (the SFU confirmed it) or off (and why:
437    /// `unpublished`, `video_disabled`, `server_unpublished`, `lease_lost`, …).
438    LocalVideo(crate::video::LocalVideo),
439    /// The media policy changed (`media_policy_updated`, a move): the latest hints, with the
440    /// join's `camera_allowed` and `screen_allowed` (also [`Call::media_policy`]).
441    MediaPolicy(Box<sew_proto::voice::MediaPolicy>),
442}
443
444/// The call's end-to-end key state and its security code, as the keys report them
445/// ([`CallEvent::Security`], [`CallSnapshot::security`]). Ids, an epoch and a code only: no
446/// key material.
447#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
448#[non_exhaustive]
449pub struct CallSecurity {
450    /// The key state: `preparing`, `joining`, `active`, `securing`, `recovering`,
451    /// `device_not_enrolled`, `server_identity_changed`, `unsupported`, `failed` or `left`.
452    pub state: String,
453    /// The active epoch (with `active`).
454    #[serde(skip_serializing_if = "Option::is_none")]
455    pub epoch: Option<u64>,
456    /// Since when the keys are in this state (the key session's clock, ms).
457    #[serde(skip_serializing_if = "Option::is_none")]
458    pub since_ms: Option<u64>,
459    /// With `securing`: show "Securing…" only this long after `since_ms`.
460    #[serde(skip_serializing_if = "Option::is_none")]
461    pub show_after_ms: Option<u64>,
462    /// Why (`recovering`, `unsupported`, `failed`, `left`).
463    #[serde(skip_serializing_if = "Option::is_none")]
464    pub reason: Option<String>,
465    /// The active epoch's security code, six groups of five digits separated by spaces
466    /// (`"01234 56789 …"`), the same on every device in the epoch. `None` before an epoch is
467    /// active, or when Sew's policy hides it.
468    #[serde(skip_serializing_if = "Option::is_none")]
469    pub code: Option<String>,
470}
471
472impl CallSecurity {
473    /// A key state with nothing else (for a host's own engine or a test).
474    pub fn new(state: impl Into<String>) -> CallSecurity {
475        CallSecurity {
476            state: state.into(),
477            ..CallSecurity::default()
478        }
479    }
480
481    /// `active` in `epoch` with `code` (for a host's own engine or a test).
482    pub fn active(epoch: u64, code: Option<String>) -> CallSecurity {
483        CallSecurity {
484            state: "active".to_owned(),
485            epoch: Some(epoch),
486            code,
487            ..CallSecurity::default()
488        }
489    }
490}
491
492/// Where a moderator move took the call (Sew's `voice_server_updated`).
493#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
494#[non_exhaustive]
495pub struct CallMoved {
496    /// The destination channel (Sew's id, a decimal string): a voice channel, or the DM or
497    /// group DM of a DM call.
498    pub channel_id: String,
499    /// The destination DM call, when the destination is one (Sew's id, a decimal string).
500    pub call_id: Option<String>,
501    /// The destination's media room (`r_...`).
502    pub media_room: String,
503}
504
505impl CallMoved {
506    /// The move in Sew's `voice_server_updated`.
507    pub fn from_update(u: &sew_proto::voice::VoiceServerUpdated) -> CallMoved {
508        CallMoved {
509            channel_id: u.channel_id.to_string(),
510            call_id: u.call_id.map(|c| c.to_string()),
511            media_room: u.room.as_str().to_owned(),
512        }
513    }
514
515    /// The `room` a host joins for the destination: the channel's id, the voice channel's or,
516    /// for a DM call, the DM's (Sew's `call/join` takes the DM, never the call's id). The
517    /// engine's re-joins after the move ask for this room.
518    pub fn room(&self) -> &str {
519        &self.channel_id
520    }
521}
522
523/// Counters of one call.
524#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
525#[non_exhaustive]
526pub struct CallCounters {
527    /// Opus frames encrypted and sent.
528    pub frames_sent: u64,
529    /// Frames dropped before sending (no media path, no send key, muted).
530    pub frames_not_sent: u64,
531    /// Frames the send queue was too full for.
532    pub send_queue_drops: u64,
533    /// Remote frames decrypted and handed over.
534    pub frames_received: u64,
535    /// Remote frames that did not decrypt (never played): a tag that did not verify, a
536    /// malformed frame, or a key that stayed missing past the keys' grace.
537    pub decrypt_failures: u64,
538    /// Remote frames dropped because the sender's key at the frame's index was not installed
539    /// yet (never played): frames that crossed a join or a key switch. Not decrypt failures.
540    pub frames_before_key: u64,
541    /// Remote frames of tracks the keys do not allow (never played): before the subscription
542    /// check passes, or from a sender no longer verified.
543    pub refused_frames: u64,
544    /// Frames the receive queue was too full for.
545    pub recv_queue_drops: u64,
546    /// Packets reported lost.
547    pub lost_marks: u64,
548    /// Resumes completed.
549    pub resumes: u64,
550    /// Full reconnects completed.
551    pub full_reconnects: u64,
552    /// Re-joins through the provider.
553    pub rejoins: u64,
554    /// TURN allocations made.
555    pub turn_allocations: u64,
556    /// Call-credential renewals.
557    pub credential_renewals: u64,
558    /// Network changes the host reported ([`Call::network_changed`]).
559    pub network_changes: u64,
560    /// Remote video frames decrypted and handed over ([`Call::video_frames`]).
561    pub video_frames_received: u64,
562    /// Remote video frames that did not decrypt (never handed over); each breaks its track
563    /// until a keyframe.
564    pub video_decrypt_failures: u64,
565    /// Remote video frames dropped because the sender's key was not installed yet.
566    pub video_frames_before_key: u64,
567    /// Remote video frames lost (a gap the retransmissions did not fill) or dropped while
568    /// their track waited for a keyframe.
569    pub video_frames_dropped: u64,
570    /// Video packets of tracks with no open sink (not forwarded) or of no known track.
571    pub video_packets_unwanted: u64,
572    /// Video packets skipped over by the reorder buffer (never arrived in time).
573    pub video_packets_lost: u64,
574    /// Video packets that arrived after their gap was skipped (dropped).
575    pub video_packets_late: u64,
576    /// Video frames the video receive queue was too full for.
577    pub video_recv_queue_drops: u64,
578    /// Picture Loss Indications sent.
579    pub video_plis: u64,
580    /// Full Intra Requests sent.
581    pub video_firs: u64,
582}
583
584/// A point-in-time view of a call (`state` command).
585#[derive(Clone, Debug, PartialEq, Serialize)]
586#[non_exhaustive]
587pub struct CallSnapshot {
588    /// The state.
589    pub state: CallState,
590    /// The participants (this device first).
591    pub participants: Vec<Participant>,
592    /// The relay's transport in use (`udp`, `tcp`, `tls`), if any.
593    pub relay: Option<String>,
594    /// Whether this join is relay-only.
595    pub relay_only: bool,
596    /// Counters.
597    pub counters: CallCounters,
598    /// The last moderator move, if any ([`CallEvent::Moved`]).
599    #[serde(skip_serializing_if = "Option::is_none")]
600    pub moved: Option<CallMoved>,
601    /// The call's active recording, if any ([`CallEvent::Recording`]).
602    #[serde(skip_serializing_if = "Option::is_none")]
603    pub recording: Option<CallRecording>,
604    /// The call's key state and security code, once the keys reported one
605    /// ([`CallEvent::Security`]).
606    #[serde(skip_serializing_if = "Option::is_none")]
607    pub security: Option<CallSecurity>,
608    /// The person's Record and Stop in the call's room, as Sew computed them last
609    /// ([`Call::recording_controls`]).
610    #[serde(skip_serializing_if = "Option::is_none")]
611    pub recording_controls: Option<ServerControls>,
612    /// This call's server computes the person's Record and Stop ([`Call::server_controls`]).
613    #[serde(skip_serializing_if = "std::ops::Not::not")]
614    pub server_controls: bool,
615}
616
617impl Default for CallSnapshot {
618    fn default() -> CallSnapshot {
619        CallSnapshot {
620            state: CallState::Connecting,
621            participants: Vec::new(),
622            relay: None,
623            relay_only: false,
624            counters: CallCounters::default(),
625            moved: None,
626            recording: None,
627            security: None,
628            recording_controls: None,
629            server_controls: false,
630        }
631    }
632}
633
634/// One encoded 20 ms Opus frame to send (kessel-audio's `EncodedFrame`).
635#[derive(Clone, Debug, PartialEq)]
636pub struct OpusFrame {
637    /// The plaintext Opus packet (the engine encrypts it).
638    pub payload: Bytes,
639    /// Capture timestamp in 48 kHz units (the RTP timestamp; wraps).
640    pub ts48k: u32,
641    /// Voice activity after processing.
642    pub vad: bool,
643    /// Processed level, dBov (0 full scale … -127).
644    pub level_dbov: f32,
645}
646
647/// One decrypted, verified remote frame (kessel-audio's `RecvFrame`).
648#[derive(Clone, Debug, PartialEq)]
649#[non_exhaustive]
650pub struct RecvOpus {
651    /// The engine's stable id for the remote track.
652    pub participant: u64,
653    /// The publisher's engine identity.
654    pub identity: String,
655    /// The Opus packet (plaintext).
656    pub payload: Bytes,
657    /// RTP sequence number.
658    pub seq: u16,
659    /// RTP timestamp, 48 kHz units.
660    pub ts48k: u32,
661    /// When it arrived.
662    pub arrival: Instant,
663}
664
665/// What the receive side hands the audio pipeline, in order.
666#[derive(Clone, Debug, PartialEq)]
667#[non_exhaustive]
668pub enum RecvItem {
669    /// A remote track starts (call `add_participant` before its frames).
670    Added {
671        /// Its id.
672        participant: u64,
673        /// The publisher's engine identity.
674        identity: String,
675    },
676    /// A remote track ends.
677    Removed {
678        /// Its id.
679        participant: u64,
680    },
681    /// A frame.
682    Frame(RecvOpus),
683    /// A packet is known lost (a gap that did not fill, or a frame that failed decryption).
684    Lost {
685        /// The track.
686        participant: u64,
687        /// Its RTP sequence number.
688        seq: u16,
689    },
690    /// Capture on (`true`) or off (muted, by self or a moderator, or SPEAK denied).
691    Capture(bool),
692    /// Playout off (`true`, deafened) or on.
693    Deafened(bool),
694}
695
696/// The receive side's queue (one consumer).
697#[derive(Debug)]
698pub struct FrameStream(pub(crate) mpsc::Receiver<RecvItem>);
699
700impl FrameStream {
701    /// The next item; `None` once the call ended.
702    pub async fn recv(&mut self) -> Option<RecvItem> {
703        self.0.recv().await
704    }
705
706    /// The next item if one is waiting.
707    pub fn try_recv(&mut self) -> Option<RecvItem> {
708        self.0.try_recv().ok()
709    }
710}
711
712/// Why a call could not start or a command failed.
713#[derive(Clone, Debug, PartialEq, thiserror::Error)]
714#[non_exhaustive]
715pub enum CallError {
716    /// One call per app.
717    #[error("already_in_call")]
718    AlreadyInCall,
719    /// The provider refused.
720    #[error(transparent)]
721    Provider(#[from] ProviderError),
722    /// The call has ended.
723    #[error("the call has ended")]
724    Ended,
725    /// The engine could not set itself up (TLS roots or crypto provider, e.g.
726    /// `no_crypto_provider`; HTTP client).
727    #[error("setup: {0}")]
728    Setup(String),
729    /// No recording is active (or held) to answer.
730    #[error("no_recording")]
731    NoRecording,
732}
733
734pub(crate) enum Cmd {
735    Mute {
736        muted: Option<bool>,
737        deafened: Option<bool>,
738        reply: oneshot::Sender<()>,
739    },
740    Leave(oneshot::Sender<()>),
741    /// The [`Call`] handle was dropped without a leave: the engine leaves (whoever else still
742    /// holds its command queue: a video sink, a camera pipeline, a [`CallLeaver`]).
743    Dropped,
744    Consent {
745        granted: bool,
746        notice_version: Option<u32>,
747        reply: oneshot::Sender<Result<(), CallError>>,
748    },
749    /// The person's Record or Stop.
750    Recording {
751        control: RecordingControl,
752        reply: oneshot::Sender<Result<(), CallError>>,
753    },
754    NetworkChanged,
755    /// A video sink opened, changed, asked for a keyframe or closed.
756    Video(crate::video::subscribe::SinkCmd),
757    Publish(crate::video::publish::VideoCmd),
758}
759
760/// The engine of one app: at most one live call.
761///
762/// Two constructors; they differ in who builds the call keys:
763///
764/// - [`CallClient::with_mls`] is the one to use in an app. It builds Sew's MLS call keys
765///   ([`crate::e2ee::MlsKeys`]) from the [`ClientConfig`]: the device key where
766///   [`ClientConfig::device_store`] says (a 0600 file by default, the host's store with
767///   [`ClientConfig::with_device_key_store`], a hardware key with
768///   [`ClientConfig::with_hardware_device_key`]) and the platform the device enrols as.
769/// - [`CallClient::new`] takes any [`E2eeProvider`] the host built. Use it to configure
770///   [`crate::e2ee::MlsKeys`] yourself, for example the device name Sew shows in the person's
771///   device list ([`crate::e2ee::MlsKeys::with_label`]), or in tests with the `testing`
772///   feature's `StaticKeys`. No provider turns encryption off.
773///
774/// ```
775/// use std::path::PathBuf;
776/// use std::sync::Arc;
777///
778/// use sew_call_client::e2ee::MlsKeys;
779/// use sew_call_client::{CallClient, ClientConfig};
780///
781/// let data_dir = PathBuf::from("/var/lib/example-app/sew-voice");
782/// let config = ClientConfig::new("com.example.app", data_dir);
783/// // What an app needs: Sew's MLS call keys, from the config.
784/// let _client = CallClient::with_mls(config.clone());
785/// // The same keys built by hand, with the device name Sew shows.
786/// let keys = MlsKeys::new(config.device_store.clone())
787///     .with_platform(config.device_platform)
788///     .with_label("Example app on Linux");
789/// let _client = CallClient::new(config, Arc::new(keys));
790/// ```
791pub struct CallClient {
792    cfg: ClientConfig,
793    e2ee: Arc<dyn E2eeProvider>,
794    busy: Arc<AtomicBool>,
795    /// The video codec preference and the declared decoders, for every call of this engine.
796    codecs: Arc<crate::video::codec_pref::CodecSettings>,
797}
798
799impl std::fmt::Debug for CallClient {
800    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
801        f.debug_struct("CallClient")
802            .field("cfg", &self.cfg)
803            .finish_non_exhaustive()
804    }
805}
806
807impl CallClient {
808    /// An engine with `cfg` whose call keys come from `e2ee` (the `sew-e2ee` key session;
809    /// there is no plaintext alternative).
810    ///
811    /// For keys the host configured itself ([`crate::e2ee::MlsKeys`] with its own label, or
812    /// the `testing` feature's `StaticKeys`). An app that needs no such setting uses
813    /// [`CallClient::with_mls`], which builds the MLS keys from `cfg` (see [`CallClient`]).
814    pub fn new(cfg: ClientConfig, e2ee: Arc<dyn E2eeProvider>) -> CallClient {
815        CallClient {
816            cfg,
817            e2ee,
818            busy: Arc::new(AtomicBool::new(false)),
819            codecs: Arc::default(),
820        }
821    }
822
823    /// Sets this device's video codec preference ([`crate::VideoCodecPreference`], a user
824    /// setting) for every call of this engine, the live one included: a camera or screen
825    /// turned on after it publishes under it ([`crate::effective_publish_codec`]).
826    /// [`crate::VideoCodecPreference::PreferVp8`] also stops this device offering to receive
827    /// H.264, from its next join. The engine keeps it until the process ends; persisting it
828    /// across launches is the host's job (store [`CallClient::video_codec_preference`] with
829    /// the app's settings and set it again at start).
830    pub fn set_video_codec_preference(&self, pref: crate::VideoCodecPreference) {
831        self.codecs.set_preference(pref);
832    }
833
834    /// This device's video codec preference ([`CallClient::set_video_codec_preference`];
835    /// [`crate::VideoCodecPreference::Automatic`] until set).
836    pub fn video_codec_preference(&self) -> crate::VideoCodecPreference {
837        self.codecs.preference()
838    }
839
840    /// Declares the video codecs this host can decode, from the next join: the OS decoders its
841    /// kessel-video backend lists (its capabilities' decode entries, a run-time answer) and the
842    /// codecs its webview decodes (a WebCodecs probe). The media connection then offers to
843    /// receive VP8 always and H.264 only if `codecs` lists it, never on Linux and never under
844    /// [`crate::VideoCodecPreference::PreferVp8`]; the media server then sends this device a
845    /// sender's VP8 instead of H.264. Nothing is assumed: list only what was found.
846    ///
847    /// Until a host declares, [`ClientConfig::video_h264`] alone decides, as before.
848    pub fn set_video_decode(&self, codecs: &[crate::VideoCodec]) {
849        self.codecs.set_decode(codecs);
850    }
851
852    /// The codecs [`CallClient::set_video_decode`] declared (sorted, `None` until then).
853    pub fn video_decode(&self) -> Option<Vec<crate::VideoCodec>> {
854        self.codecs.decode()
855    }
856
857    /// An engine with `cfg` and Sew's MLS call keys ([`crate::e2ee::MlsKeys`]), the device key
858    /// where `cfg.device_store` says (by default a 0600 file; the host's own store with
859    /// [`ClientConfig::with_device_key_store`], a hardware key with
860    /// [`ClientConfig::with_hardware_device_key`]), enrolled as `cfg.device_platform`: the
861    /// production constructor, the one an app uses. [`CallClient::new`] is for keys the host
862    /// builds itself (see [`CallClient`]).
863    pub fn with_mls(cfg: ClientConfig) -> CallClient {
864        let keys =
865            crate::e2ee::MlsKeys::new(cfg.device_store.clone()).with_platform(cfg.device_platform);
866        CallClient::new(cfg, Arc::new(keys))
867    }
868
869    /// Every device key this engine's data directory holds a record of
870    /// ([`crate::device::known_device_keys`]), sorted: with a hardware key, one Keychain item
871    /// or Keystore alias each ([`crate::device::DeviceKeyId::account`]). A host store's
872    /// ([`ClientConfig::with_device_key_store`]) devices are the host's and not listed.
873    /// Blocking (it reads the directory).
874    pub fn known_device_keys(
875        &self,
876    ) -> Result<Vec<crate::device::DeviceKeyId>, crate::device::DeviceError> {
877        crate::device::known_device_keys(&self.cfg.data_dir)
878    }
879
880    /// The host's sign-out from one Sew install ([`crate::device::forget_install`] with
881    /// `cfg.device_store`): every device of `install_id` is reset (its key deleted, a hardware
882    /// key through `HardwareDeviceKey::delete`; the device and the pins cleared) and its files
883    /// removed. Answers the ids it removed. Refused with
884    /// [`crate::device::DeviceError::InCall`] while a call is live or joining; a join while it
885    /// runs is refused with [`CallError::AlreadyInCall`].
886    pub async fn forget_server(
887        &self,
888        install_id: u64,
889    ) -> Result<Vec<crate::device::DeviceKeyId>, crate::device::DeviceError> {
890        if self.busy.swap(true, Ordering::AcqRel) {
891            return Err(crate::device::DeviceError::InCall);
892        }
893        let _busy = BusyGuard(self.busy.clone());
894        let vault = crate::device::VaultConfig {
895            data_dir: self.cfg.data_dir.clone(),
896            app_id: self.cfg.app_id.clone(),
897            store: self.cfg.device_store.clone(),
898            label: String::new(),
899            platform: self.cfg.device_platform,
900        };
901        crate::device::forget_install(&vault, install_id).await
902    }
903
904    /// Joins through `provider` and starts the call.
905    ///
906    /// A room that is recorded (Sew's `409 recording_consent_required`, the provider's
907    /// [`ProviderError::ConsentRequired`]) is not an error: the call comes back held at
908    /// [`CallState::ConsentRequired`], with the notice in [`Call::recording`], until the host
909    /// answers ([`Call::consent`]) or leaves.
910    pub async fn join(
911        &self,
912        provider: Arc<dyn JoinProvider>,
913        req: JoinRequest,
914    ) -> Result<Call, CallError> {
915        if self.busy.swap(true, Ordering::AcqRel) {
916            return Err(CallError::AlreadyInCall);
917        }
918        let busy = BusyGuard(self.busy.clone());
919        let first = match provider.join(req.clone()).await {
920            Ok(answer) => engine::First::Answer(Box::new(answer)),
921            Err(ProviderError::ConsentRequired(c)) => engine::First::Held(c),
922            Err(e) => return Err(e.into()),
923        };
924        let (events, _) = broadcast::channel(256);
925        let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
926        let (push_tx, push_rx) = mpsc::channel(SEND_QUEUE);
927        let (frames_tx, frames_rx) = mpsc::channel(RECV_QUEUE);
928        let (video_tx, video_rx) = mpsc::channel(VIDEO_RECV_QUEUE);
929        let snapshot = Arc::new(Mutex::new(CallSnapshot::default()));
930        let shared = Arc::new(engine::Shared {
931            events: events.clone(),
932            snapshot: snapshot.clone(),
933            send_queue_drops: std::sync::atomic::AtomicU64::new(0),
934            stats: Mutex::new(CallStatsReport::default()),
935            playout: Mutex::new(None),
936            noise: Mutex::new(None),
937            beacon_stopped: AtomicBool::new(false),
938            policy: Mutex::new(None),
939            video_stats: Arc::new(Mutex::new(crate::video::VideoSendStats::default())),
940            video_codecs: self.codecs.negotiated(self.cfg.video_h264),
941            codec_settings: Arc::clone(&self.codecs),
942        });
943        if let engine::First::Held(c) = &first {
944            // Held before `join` returns: a host that reads the snapshot at once (to decide
945            // whether to open the microphone) sees `consent_required`, never `connecting`.
946            engine::preset_held(&snapshot, c);
947        }
948        engine::spawn(engine::Start {
949            cfg: self.cfg.clone(),
950            e2ee: self.e2ee.clone(),
951            provider,
952            req,
953            first,
954            shared: shared.clone(),
955            cmd_rx,
956            push_rx,
957            frames_tx,
958            video_tx,
959            busy,
960        })
961        .map_err(CallError::Setup)?;
962        Ok(Call {
963            cmd: cmd_tx,
964            push: push_tx,
965            shared,
966            frames: Mutex::new(Some(FrameStream(frames_rx))),
967            video: Mutex::new(Some(crate::video::VideoFrameStream(video_rx))),
968            next_sink: std::sync::atomic::AtomicU64::new(1),
969            id: NEXT_CALL.fetch_add(1, Ordering::Relaxed),
970        })
971    }
972}
973
974/// [`Call::local_id`]'s counter.
975static NEXT_CALL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
976
977/// Clears the app's call slot when the engine task ends.
978pub(crate) struct BusyGuard(Arc<AtomicBool>);
979
980impl Drop for BusyGuard {
981    fn drop(&mut self) {
982        self.0.store(false, Ordering::Release);
983    }
984}
985
986/// Leaves a call without its [`Call`] handle ([`Call::leaver`]). Cloneable; a leave of a call
987/// that is already over answers [`CallError::Ended`].
988#[derive(Clone)]
989pub struct CallLeaver {
990    cmd: mpsc::UnboundedSender<Cmd>,
991    id: u64,
992}
993
994impl std::fmt::Debug for CallLeaver {
995    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
996        f.debug_struct("CallLeaver").finish_non_exhaustive()
997    }
998}
999
1000impl CallLeaver {
1001    /// Leaves, as [`Call::leave`]: when it answers, the app's call slot is free.
1002    pub async fn leave(&self) -> Result<(), CallError> {
1003        let (reply, rx) = oneshot::channel();
1004        self.cmd
1005            .send(Cmd::Leave(reply))
1006            .map_err(|_| CallError::Ended)?;
1007        rx.await.map_err(|_| CallError::Ended)
1008    }
1009
1010    /// The call's [`Call::local_id`].
1011    pub fn local_id(&self) -> u64 {
1012        self.id
1013    }
1014}
1015
1016/// The send queue of a call, cloneable ([`Call::frame_sender`]).
1017#[derive(Clone)]
1018pub struct FrameSender {
1019    push: mpsc::Sender<OpusFrame>,
1020    shared: Arc<engine::Shared>,
1021}
1022
1023impl std::fmt::Debug for FrameSender {
1024    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1025        f.debug_struct("FrameSender").finish_non_exhaustive()
1026    }
1027}
1028
1029impl FrameSender {
1030    /// Queues one encoded frame (see [`Call::push_opus`]).
1031    pub fn push_opus(&self, f: OpusFrame) {
1032        if self.push.try_send(f).is_err() {
1033            self.shared.send_queue_drops.fetch_add(1, Ordering::Relaxed);
1034        }
1035    }
1036}
1037
1038/// One live call.
1039pub struct Call {
1040    cmd: mpsc::UnboundedSender<Cmd>,
1041    push: mpsc::Sender<OpusFrame>,
1042    shared: Arc<engine::Shared>,
1043    frames: Mutex<Option<FrameStream>>,
1044    video: Mutex<Option<crate::video::VideoFrameStream>>,
1045    next_sink: std::sync::atomic::AtomicU64,
1046    id: u64,
1047}
1048
1049impl Drop for Call {
1050    /// The handle is gone: the engine leaves now, even while a video sink, a camera pipeline
1051    /// or a [`CallLeaver`] still holds its command queue (after a leave, nothing happens).
1052    fn drop(&mut self) {
1053        let _ = self.cmd.send(Cmd::Dropped);
1054    }
1055}
1056
1057impl std::fmt::Debug for Call {
1058    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1059        f.debug_struct("Call").finish_non_exhaustive()
1060    }
1061}
1062
1063impl Call {
1064    /// The call's events (state, participants, speaking, errors).
1065    pub fn events(&self) -> broadcast::Receiver<CallEvent> {
1066        self.shared.events.subscribe()
1067    }
1068
1069    /// The current state and participants.
1070    pub fn snapshot(&self) -> CallSnapshot {
1071        let mut s = self
1072            .shared
1073            .snapshot
1074            .lock()
1075            .map(|s| s.clone())
1076            .unwrap_or_default();
1077        s.counters.send_queue_drops = self.shared.send_queue_drops.load(Ordering::Relaxed);
1078        s
1079    }
1080
1081    /// The stats windows so far (the latest 256) and the beacon's terms: the same numbers the
1082    /// beacon sends, measured whether or not it is on (see the `stats` module docs for how
1083    /// each is derived).
1084    pub fn stats(&self) -> CallStatsReport {
1085        self.shared
1086            .stats
1087            .lock()
1088            .map(|s| s.clone())
1089            .unwrap_or_default()
1090    }
1091
1092    /// Where the beacon's played and concealed audio come from: the host's own audio
1093    /// pipeline (one that does not use [`crate::AudioBridge`], which reports kessel-audio's).
1094    /// Without one, the engine reports what it handed the pipeline.
1095    pub fn set_playout_stats(&self, source: Arc<dyn PlayoutStats>) {
1096        if let Ok(mut p) = self.shared.playout.lock() {
1097            *p = Some(source);
1098        }
1099    }
1100
1101    /// The noise removal of this call's audio: `{mode, active, reason}`
1102    /// ([`crate::NoiseRemovalState`]), while audio started with
1103    /// [`crate::AudioBridge::start_with_noise`] runs; `None` otherwise.
1104    pub fn noise_removal(&self) -> Option<crate::NoiseRemovalState> {
1105        self.shared.noise_removal()
1106    }
1107
1108    /// The call's audio reports its noise removal here.
1109    #[cfg(feature = "audio-core")]
1110    pub(crate) fn set_noise_source(&self, source: Arc<dyn crate::noise::NoiseSource>) {
1111        if let Ok(mut n) = self.shared.noise.lock() {
1112            *n = Some(source);
1113        }
1114    }
1115
1116    /// The device is busy with something else for a moment (a camera starting): the call's
1117    /// noise removal stage opens a grace window. Nothing without a stage.
1118    #[cfg_attr(not(feature = "video-core"), allow(dead_code))]
1119    pub(crate) fn noise_grace(&self) {
1120        let src = self.shared.noise.lock().ok().and_then(|n| n.clone());
1121        if let Some(src) = src {
1122            src.grace();
1123        }
1124    }
1125
1126    /// Mute and deafen (`None` leaves it). Deafened implies muted; un-deafening returns
1127    /// `muted` to its value before the deafen.
1128    pub async fn mute(&self, muted: Option<bool>, deafened: Option<bool>) -> Result<(), CallError> {
1129        let (reply, rx) = oneshot::channel();
1130        self.cmd
1131            .send(Cmd::Mute {
1132                muted,
1133                deafened,
1134                reply,
1135            })
1136            .map_err(|_| CallError::Ended)?;
1137        rx.await.map_err(|_| CallError::Ended)
1138    }
1139
1140    /// The call's active recording as Sew says it (or the notice of a held join), if any.
1141    pub fn recording(&self) -> Option<CallRecording> {
1142        self.shared
1143            .snapshot
1144            .lock()
1145            .ok()
1146            .and_then(|s| s.recording.clone())
1147    }
1148
1149    /// The person's Record and Stop in the call's room as Sew computed them last (the newest
1150    /// by `rev` of its `recording_controls_updated`, the call socket's READY and the
1151    /// recording's `my_controls`). `None` from an older server, before the server's first
1152    /// value (Sew sends one once the call is connected), and after a move until the
1153    /// destination's arrives.
1154    pub fn recording_controls(&self) -> Option<ServerControls> {
1155        self.shared
1156            .snapshot
1157            .lock()
1158            .ok()
1159            .and_then(|s| s.recording_controls)
1160    }
1161
1162    /// This call's server computes the person's Record and Stop: its call socket's READY
1163    /// carried `recording_controls` (even `null`), or a value arrived. `false` against an
1164    /// older server: the host works the buttons out itself.
1165    pub fn server_controls(&self) -> bool {
1166        self.shared.snapshot.lock().is_ok_and(|s| s.server_controls)
1167    }
1168
1169    /// The person's answer to the recording's notice (`notice_version`: the version they saw,
1170    /// [`CallState::ConsentRequired`]'s or the prompt's). Held at `consent_required`, the
1171    /// engine re-joins with the answer (a decline joins unrecorded, or is refused when declining
1172    /// means not joining: the call ends). In a call, the host sends it
1173    /// ([`JoinProvider::consent`]). Either way this device's key reaches the recorder only
1174    /// once Sew says `granted`. A notice that changed meanwhile answers
1175    /// `Provider(ConsentRequired)` with the current one (the call stays as it was).
1176    pub async fn consent(&self, granted: bool, notice_version: u32) -> Result<(), CallError> {
1177        self.answer(granted, Some(notice_version)).await
1178    }
1179
1180    /// "Stop recording me": withdraws a granted consent through the host (Sew stops capturing
1181    /// this person at once and the keys rekey so the recorder gets no later key). Before an
1182    /// answer it is a decline.
1183    pub async fn withdraw_consent(&self) -> Result<(), CallError> {
1184        self.answer(false, None).await
1185    }
1186
1187    /// Record (Sew 0.9.0): the person starts recording the call's room through the host
1188    /// ([`JoinProvider::recording`], with the person's own session). Pressing Record is the
1189    /// person's own consent, so show the notice as a confirmation first; everyone else stays
1190    /// unrecorded until they answer. Sew's answer is the call's recording at once
1191    /// ([`Call::recording`], [`CallEvent::Recording`]). Refusals are Sew's, as
1192    /// `Provider(Refused { code, .. })` (`recording_active`, `recording_disabled`,
1193    /// `cap_ceiling`, …); while the join is held for a notice the person is not in the room
1194    /// yet, and it is refused `not_in_voice` without asking Sew.
1195    pub async fn start_recording(&self) -> Result<(), CallError> {
1196        self.control(RecordingControl::Start).await
1197    }
1198
1199    /// Stop (Sew 0.9.0): the person stops the room's active recording through the host
1200    /// ([`JoinProvider::recording`]). [`CallError::NoRecording`] when none is active. Sew
1201    /// refuses `recording_required` while the room requires its recording and two or more
1202    /// people are in it ([`CallRecording::required`]); "Stop recording me"
1203    /// ([`Call::withdraw_consent`]) still works then.
1204    pub async fn stop_recording(&self) -> Result<(), CallError> {
1205        self.control(RecordingControl::Stop).await
1206    }
1207
1208    async fn control(&self, control: RecordingControl) -> Result<(), CallError> {
1209        let (reply, rx) = oneshot::channel();
1210        self.cmd
1211            .send(Cmd::Recording { control, reply })
1212            .map_err(|_| CallError::Ended)?;
1213        rx.await.map_err(|_| CallError::Ended)?
1214    }
1215
1216    async fn answer(&self, granted: bool, notice_version: Option<u32>) -> Result<(), CallError> {
1217        let (reply, rx) = oneshot::channel();
1218        self.cmd
1219            .send(Cmd::Consent {
1220                granted,
1221                notice_version,
1222                reply,
1223            })
1224            .map_err(|_| CallError::Ended)?;
1225        rx.await.map_err(|_| CallError::Ended)?
1226    }
1227
1228    /// The device's network changed: the host calls this from its path monitor (iOS
1229    /// `NWPathMonitor`, Android `ConnectivityManager.NetworkCallback`) when the default route
1230    /// moves (Wi-Fi to cellular and back, a new Wi-Fi network, a VPN coming up). Never blocks;
1231    /// safe from any thread and to repeat.
1232    ///
1233    /// In a call it runs the resume path now instead of waiting for the old connections to time
1234    /// out: the signalling WebSocket is replaced and the session resumes (`JoinRequest.reconnect`,
1235    /// the PC kept), a fresh transport is opened on the new network (a new TURN allocation over a
1236    /// new TURN-TLS / TCP / UDP socket and new host candidates) and swapped into the PC, then an
1237    /// ICE restart moves the media onto it; the call socket of the keys reconnects and resumes
1238    /// too. The state shows `reconnecting` until the resume is done. If the new transport can't
1239    /// be opened, or the restart does not connect, the engine falls back to its full reconnect
1240    /// (and re-join) inside the usual window. Before the call is connected it retries the
1241    /// connect at once; while the join is held for a recording notice it does nothing (no
1242    /// connection is open).
1243    pub fn network_changed(&self) {
1244        let _ = self.cmd.send(Cmd::NetworkChanged);
1245    }
1246
1247    /// Leaves (Sew's leave with the credential, then the engine's). When it answers, the app's
1248    /// call slot is free: a [`CallClient::join`] right after it is never
1249    /// [`CallError::AlreadyInCall`]. Dropping the `Call` without it leaves too.
1250    pub async fn leave(self) -> Result<(), CallError> {
1251        self.leaver().leave().await
1252    }
1253
1254    /// A handle that leaves this call from anywhere, without the `Call` itself: for a host that
1255    /// keeps the `Call` behind a lock that its camera or screen commands hold while they wait
1256    /// on a device, so a leave never waits for them (they get [`CallError::Ended`] or
1257    /// [`crate::VideoError::Ended`] once the call is over).
1258    pub fn leaver(&self) -> CallLeaver {
1259        CallLeaver {
1260            cmd: self.cmd.clone(),
1261            id: self.id,
1262        }
1263    }
1264
1265    /// A number this call alone has in the process (never reused), to tell its video
1266    /// pipelines from a later call's (`VideoBridge::close_call`, with `video-core`).
1267    pub fn local_id(&self) -> u64 {
1268        self.id
1269    }
1270
1271    /// Queues one encoded frame to send. Never blocks: a full queue drops the frame (and
1272    /// counts it); the engine drops it too unless media is up and a send key is active.
1273    pub fn push_opus(&self, f: OpusFrame) {
1274        self.frame_sender().push_opus(f);
1275    }
1276
1277    /// A cloneable handle to the send queue (for an audio thread or task).
1278    pub fn frame_sender(&self) -> FrameSender {
1279        FrameSender {
1280            push: self.push.clone(),
1281            shared: self.shared.clone(),
1282        }
1283    }
1284
1285    /// The receive side (decrypted Opus per remote track, loss marks, mute and deafen), for the
1286    /// audio pipeline. The first call takes it; later calls get `None`.
1287    pub fn frames(&self) -> Option<FrameStream> {
1288        self.frames.lock().ok().and_then(|mut f| f.take())
1289    }
1290
1291    /// The video receive side: decrypted, verified **encoded** frames of the remote camera and
1292    /// screen tracks that have an open sink ([`Call::video_sink`]), with each track's `Added`,
1293    /// `Removed`, `Broken` and `KeyframeNeeded`. The first call takes it; later calls get
1294    /// `None`. Without `video-core` the engine negotiates no video and nothing arrives.
1295    pub fn video_frames(&self) -> Option<crate::video::VideoFrameStream> {
1296        self.video.lock().ok().and_then(|mut f| f.take())
1297    }
1298
1299    /// The video codecs this call's media connection offers to receive (VP8 first; H.264 only
1300    /// when the join's [`CallClient::set_video_decode`] and preference allowed it). Fixed at
1301    /// the join; the publish side can send only these too. Empty without `video-core`.
1302    pub fn video_codecs(&self) -> Vec<crate::VideoCodec> {
1303        if crate::pc::VIDEO {
1304            self.shared.video_codecs.codecs()
1305        } else {
1306            Vec::new()
1307        }
1308    }
1309
1310    /// This device's video codec preference now ([`CallClient::set_video_codec_preference`]),
1311    /// for the publish side when a camera or screen turns on.
1312    pub fn video_codec_preference(&self) -> crate::VideoCodecPreference {
1313        self.shared.codec_settings.preference()
1314    }
1315
1316    /// Opens a sink for the remote video track `track_sid` ([`CallEvent::VideoAdded`]): while
1317    /// at least one of a track's sinks is open and visible, the engine asks the media server
1318    /// for it (the largest visible sink's size, 30 fps for a large tile, 15 for a grid tile)
1319    /// and its frames flow through [`Call::video_frames`], starting at a keyframe. With none,
1320    /// the track is disabled at the server and nothing is forwarded. Dropping the sink closes
1321    /// it.
1322    pub fn video_sink(
1323        &self,
1324        track_sid: &str,
1325        spec: crate::video::VideoSinkSpec,
1326    ) -> crate::video::VideoSink {
1327        let id = self.next_sink.fetch_add(1, Ordering::Relaxed);
1328        let _ = self
1329            .cmd
1330            .send(Cmd::Video(crate::video::subscribe::SinkCmd::Open {
1331                id,
1332                track_sid: track_sid.to_owned(),
1333                spec,
1334            }));
1335        crate::video::VideoSink {
1336            id,
1337            cmd: self.cmd.clone(),
1338        }
1339    }
1340
1341    /// The client media policy of the join (its `camera_allowed` and `screen_allowed`) with
1342    /// the latest layer hints (`media_policy_updated`, a move), if the join answer had one.
1343    pub fn media_policy(&self) -> Option<sew_proto::voice::MediaPolicy> {
1344        self.shared.policy.lock().ok().and_then(|p| p.clone())
1345    }
1346
1347    /// Whether this call's media connection negotiates H.264 ([`crate::ClientConfig::video_h264`]):
1348    /// a sender publishes H.264 only then.
1349    #[cfg(feature = "video-core")]
1350    pub(crate) fn decodes_h264(&self) -> bool {
1351        self.shared.video_codecs.contains(crate::VideoCodec::H264)
1352    }
1353
1354    /// The send-side video counters.
1355    pub fn video_stats(&self) -> crate::video::VideoSendStats {
1356        self.shared
1357            .video_stats
1358            .lock()
1359            .map(|s| s.clone())
1360            .unwrap_or_default()
1361    }
1362
1363    async fn video(
1364        &self,
1365        cmd: impl FnOnce(
1366            oneshot::Sender<Result<(), crate::video::VideoError>>,
1367        ) -> crate::video::publish::VideoCmd,
1368    ) -> Result<(), crate::video::VideoError> {
1369        let (reply, rx) = oneshot::channel();
1370        self.cmd
1371            .send(Cmd::Publish(cmd(reply)))
1372            .map_err(|_| crate::video::VideoError::Ended)?;
1373        rx.await.map_err(|_| crate::video::VideoError::Ended)?
1374    }
1375
1376    /// Takes (`on`) or releases a video lease: Sew's `self_video` for the camera, `self_stream`
1377    /// for a screen share (`POST /api/v1/me/voice/state` with the call credential). Refused
1378    /// with `video_not_allowed` when the join's policy has video off or this session may not
1379    /// hold it, and with Sew's own refusals (`video_slots_full`, `media_busy` with its
1380    /// `Retry-After`, `media_capacity`, `video_disabled`). A publication needs the lease
1381    /// first; releasing it does not unpublish ([`Call::unpublish_video`] does both).
1382    pub async fn set_video_lease(
1383        &self,
1384        source: crate::video::VideoSource,
1385        on: bool,
1386    ) -> Result<(), crate::video::VideoError> {
1387        self.video(|reply| crate::video::publish::VideoCmd::Lease { source, on, reply })
1388            .await
1389    }
1390
1391    /// Publishes a camera or screen share under its lease: the `AddTrackRequest` with the
1392    /// layers that opened and the codec, the SFU's `TrackPublished` confirmed GCM by the keys,
1393    /// then the simulcast send section. The handle takes each layer's encoded frames and says
1394    /// what the engine needs ([`crate::video::VideoControl`]: keyframes, which layers run at
1395    /// what rates, a republish, the end). Refused with `no_lease` without the lease,
1396    /// `e2ee_downgraded` when the SFU drops GCM, `already_published` for a second publication
1397    /// of the source.
1398    pub async fn publish_video(
1399        &self,
1400        req: crate::video::VideoPublish,
1401    ) -> Result<crate::video::VideoPublication, crate::video::VideoError> {
1402        let (reply, rx) = oneshot::channel();
1403        self.cmd
1404            .send(Cmd::Publish(crate::video::publish::VideoCmd::Publish {
1405                req,
1406                reply,
1407            }))
1408            .map_err(|_| crate::video::VideoError::Ended)?;
1409        rx.await.map_err(|_| crate::video::VideoError::Ended)?
1410    }
1411
1412    /// Unpublishes the source's track (its send section goes inactive; the producer gets
1413    /// `Ended { reason: "unpublished" }`) and, with `release_lease`, releases its lease.
1414    pub async fn unpublish_video(
1415        &self,
1416        source: crate::video::VideoSource,
1417        release_lease: bool,
1418    ) -> Result<(), crate::video::VideoError> {
1419        self.unpublish_video_because(source, release_lease, crate::video::publish::UNPUBLISHED)
1420            .await
1421    }
1422
1423    /// [`Call::unpublish_video`] with `reason` as the producer's `Ended` and `local_video`'s
1424    /// reason (who turned it off: `camera_off`, `camera_switch`, `system_ui`, …).
1425    pub async fn unpublish_video_because(
1426        &self,
1427        source: crate::video::VideoSource,
1428        release_lease: bool,
1429        reason: &str,
1430    ) -> Result<(), crate::video::VideoError> {
1431        let reason = reason.to_owned();
1432        self.video(|reply| crate::video::publish::VideoCmd::Unpublish {
1433            source,
1434            release: release_lease,
1435            reason,
1436            reply,
1437        })
1438        .await
1439    }
1440
1441    /// A handle that ends this call's publications from another thread (the bridge's
1442    /// pipeline, when its source ends).
1443    #[cfg(feature = "video-core")]
1444    pub(crate) fn video_ctl(&self) -> crate::video::publish::VideoCtl {
1445        crate::video::publish::VideoCtl::new(self.cmd.clone())
1446    }
1447
1448    /// Mutes or unmutes the source's published track at the SFU (`MuteTrackRequest`) while
1449    /// keeping the publication and its lease: subscribers see the track muted (a phone app in
1450    /// the background, whose producer stops sending frames). Sent again after a republish or a
1451    /// reconnect. Nothing happens without a publication of the source.
1452    pub fn set_video_muted(&self, source: crate::video::VideoSource, muted: bool) {
1453        let _ = self
1454            .cmd
1455            .send(Cmd::Publish(crate::video::publish::VideoCmd::Mute {
1456                source,
1457                muted,
1458            }));
1459    }
1460
1461    /// Caps on top of the policy (thermal pressure, low power): each layer's bitrate, the
1462    /// number of layers and the frame rate, applied before the bandwidth split.
1463    pub fn set_video_caps(&self, caps: crate::video::VideoCaps) {
1464        let _ = self
1465            .cmd
1466            .send(Cmd::Publish(crate::video::publish::VideoCmd::Caps(caps)));
1467    }
1468}