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