sew_call_client/lib.rs
1//! `sew-call-client`: Sew's native voice engine. Everything below the UI for one call:
2//!
3//! - LiveKit-protocol signalling against Sew's media server (the `/rtc/v1` single-PC session from
4//! `sew-lk-compat`) with resume, full reconnect inside a 20 s window and re-join through the
5//! host's [`JoinProvider`];
6//! - str0m transport with TURN over UDP, TCP and TLS, relay-only when the join answer or the
7//! engine asks (`media.relay_only` / `force_relay`), production TLS trust (the platform's);
8//! - the frame path: kessel-audio's encoded Opus frames are encrypted through the call's keys
9//! ([`e2ee::KeySession`]) and sent; remote frames are decrypted and verified before kessel-audio
10//! ever sees them (no plaintext mode exists);
11//! - mute and deafen, participants, speaking levels, and the call credential's renewal;
12//! - the call-stats beacon (Sew's `POST /api/v1/me/voice/stats`, when the join answer carries
13//! its terms) and the same per-window numbers for the host ([`stats`], [`Call::stats`]);
14//! - recording consent (Sew 0.7.3): a join into a recorded room is held at
15//! [`CallState::ConsentRequired`] until the host answers the notice ([`Call::consent`]); the
16//! call's recording ([`Call::recording`], [`CallEvent::Recording`]) feeds the keys, which
17//! release this device's key to the recorder only once Sew says `granted`;
18//! [`Call::withdraw_consent`] is "Stop recording me". Consent travels through the host's
19//! [`JoinProvider`] with the person's own session.
20//!
21//! Sew is a self-hosted chat and calls server from Alakazam Labs; this crate is its native call
22//! client. It needs a Sew server to join calls on.
23//!
24//! ```text
25//! let client = CallClient::with_mls(ClientConfig::new("com.example.app", data_dir));
26//! let call = client.join(provider, JoinRequest::new(target, room)).await?;
27//! let audio = AudioBridge::start(&call, kessel_audio::EngineConfig::default())?; // feature `audio`
28//! let mut events = call.events();
29//! ```
30//!
31//! The host implements [`JoinProvider`] (its documentation says which crates that needs and has
32//! a complete example). The engine runs on Tokio: call [`CallClient::join`] from inside a Tokio
33//! runtime.
34//!
35//! The E2EE layer plugs in through [`e2ee::E2eeProvider`]; `CallClient` cannot be built without
36//! one. The real one, and the default ([`CallClient::with_mls`]), is [`e2ee::MlsKeys`]: MLS
37//! through `sew-e2ee`, the call socket ([`gateway`]), the device store ([`device`]), the
38//! mandatory checks and sew-lk-compat's LkGcm. The only other provider is the test-only
39//! `StaticKeys` (feature `testing`). [`CallClient`] says when to use `with_mls` and when
40//! [`CallClient::new`].
41//!
42//! Two labels in these docs: **K2** is Alakazam Labs' platform, which can host Sew
43//! (`kessel-audio` and `kessel-video`, the audio and video pipelines used here, are K2's crates;
44//! nothing here needs K2). A **Sew version** ("Sew 0.7.3") is a version of the Sew server: next
45//! to a feature, the first server version that has it; in the CHANGELOG's headings, the server
46//! version that release of this crate is tested against.
47//!
48//! The [README](https://github.com/Alakazam-211/sew-crates/tree/main/sew-call-client#features)
49//! has the cargo features and the platforms each one builds on.
50// Test code may unwrap and expect: the packaged crate has no clippy.toml (whose
51// allow-unwrap-in-tests and allow-expect-in-tests say so in this repository).
52#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
53
54mod api;
55#[cfg(feature = "audio-core")]
56mod audio;
57mod call;
58mod config;
59pub mod device;
60pub mod e2ee;
61mod engine;
62pub mod gateway;
63mod noise;
64mod pc;
65mod provider;
66#[cfg(feature = "rust-crypto")]
67mod rust_crypto;
68mod signal;
69pub mod stats;
70mod transport;
71mod video;
72
73#[cfg(feature = "audio")]
74pub use audio::platform_audio_config;
75#[cfg(feature = "audio-core")]
76pub use audio::{
77 AUDIO_BACKEND, AudioBridge, AudioBridgeError, AudioSession, BridgeLevels, SessionEvent,
78};
79pub use call::{
80 Call, CallClient, CallCounters, CallError, CallErrorEvent, CallEvent, CallLeaver, CallMoved,
81 CallRecording, CallSecurity, CallSnapshot, CallState, EndReason, FrameSender, FrameStream,
82 OpusFrame, Participant, RecordingConsent, RecordingMember, RecvItem, RecvOpus, ServerControls,
83 Speaking,
84};
85#[cfg(feature = "testing")]
86pub use config::TestingOverrides;
87pub use config::{ClientConfig, default_video_h264};
88/// kessel-audio, re-exported for hosts that configure the audio engine.
89#[cfg(feature = "audio-core")]
90pub use kessel_audio;
91/// kessel-video, re-exported for hosts that pick or configure the video backend.
92#[cfg(feature = "video-core")]
93pub use kessel_video;
94/// The noise removal setting of the capture path and what runs; with `audio-core`, the control
95/// that builds the capture stage ([`AudioBridge::start_with_noise`]).
96#[cfg(feature = "audio-core")]
97pub use noise::NoiseRemovalControl;
98/// The device bench of the noise removal stage (feature `noise-bench`; debug builds only).
99#[cfg(feature = "noise-bench")]
100pub use noise::bench as noise_bench;
101/// The probe of the noise removal stage (feature `noise-probe`; measurement builds only).
102#[cfg(feature = "noise-probe")]
103pub use noise::probe as noise_probe;
104pub use noise::{
105 CaptureDspSched, CaptureDspSchedError, CaptureDspSchedFallback, CaptureDspSchedMode,
106 CaptureDspScheduling, CaptureStageClock, CaptureTransient, NoiseDfn3State, NoiseModel,
107 NoiseRemoval, NoiseRemovalReason, NoiseRemovalState, NoiseStepDownReason, PhoneAudioMode,
108};
109/// What loading DeepFilterNet3's weights cost, and how long the model stays after the last
110/// call by default (feature `dfn3`).
111#[cfg(feature = "dfn3")]
112pub use noise::{DFN3_IDLE_UNLOAD, Dfn3LoadInfo};
113pub use provider::{
114 AnswerError, BoxFuture, CONSENT_UNSUPPORTED, CallCredential, ConsentAnswer, ConsentRequired,
115 DmCall, JoinAnswer, JoinProvider, JoinRequest, ProviderError, RECORDING_UNSUPPORTED,
116 RecordingControl, RecordingRequest, RejoinReason,
117};
118/// rustls, re-exported for hosts that pass their own crypto provider
119/// ([`ClientConfig::with_crypto_provider`]).
120pub use rustls;
121/// Why DeepFilterNet3's weights were refused (feature `dfn3`).
122#[cfg(feature = "dfn3")]
123pub use sew_noise::dfn3::LoadError as Dfn3LoadError;
124/// The DeepFilterNet3 weights file's name, as an app ships it (feature `dfn3`).
125#[cfg(feature = "dfn3")]
126pub use sew_noise::dfn3::WEIGHTS_FILE as DFN3_WEIGHTS_FILE;
127/// Sew's recording types the engine's recording API carries (from `sew-proto`).
128pub use sew_proto::recording::{
129 ConsentPrompt, RecordUnavailable, Recording, RecordingNotice, RecordingRef, RecordingTrigger,
130};
131pub use stats::{
132 BeaconOutcome, BeforeFirstWindow, CallStatsReport, PlayoutSource, PlayoutStats, PlayoutTotals,
133 StatsWindow,
134};
135/// The per-device video codec preference and the run-time H.264 check it rests on.
136#[cfg(feature = "video-core")]
137pub use video::h264_encode_detection;
138/// Video publishing: the engine's frame API ([`Call::publish_video`]) and its types.
139pub use video::{
140 BackupSpec, EncodedVideo, LayerRate, LayerSpec, LocalVideo, VideoCaps, VideoControl,
141 VideoError, VideoPublication, VideoPublish, VideoSendStats, VideoSender, plan_layers,
142 plan_screen_layers,
143};
144/// Raw camera frames for a native self-view (`video-core`): [`VideoCapture::camera_tap`].
145#[cfg(feature = "video-core")]
146pub use video::{CameraFeed, CameraFrame, CameraTap, CameraTapItem, CameraTapSender};
147/// The video bridge: a kessel-video backend's cameras, screens and encoders into a call, with
148/// the in-call self-view.
149#[cfg(feature = "video-core")]
150#[allow(deprecated)]
151pub use video::{
152 CameraRequest, CameraState, CodecPlan, PlannedCodec, SelfViewFrames, SelfViewItem, SourceFeed,
153 SourceNote, VideoBridge, choose_codec, choose_codecs,
154};
155/// Video capture (`video-core`): cameras, screens, the OS picker, screen thumbnails and the
156/// pre-join preview over a kessel-video backend, as the sources the publish side takes.
157#[cfg(feature = "video-core")]
158pub use video::{
159 CameraSource, Capture, CaptureEnd, CaptureError, CaptureEvent, CaptureKind, CapturePause,
160 LocalFrame, PREVIEW_BITRATE_BPS, PREVIEW_FPS, PREVIEW_HEIGHT, PREVIEW_QUEUE, PREVIEW_WIDTH,
161 Preview, PreviewFrames, PreviewItem, ScreenChoice, ScreenPick, ScreenSource,
162 THUMBNAIL_MAX_WIDTH, VideoCapture, preview_codec, screen_constraints, thumbnail_png,
163};
164pub use video::{
165 CodecPreferenceReason, H264Detection, VideoCodecPreference, effective_publish_codec,
166 effective_publish_codec_under_policy,
167};
168/// A kessel-video backend replaying pre-encoded VP8 and H.264 simulcast streams (test only).
169#[cfg(all(feature = "testing", feature = "video-core"))]
170pub use video::{FixtureBackend, FixtureError, FixtureH264, FixtureOptions};
171pub use video::{
172 VideoCodec, VideoFrame, VideoFrameStream, VideoLayerInfo, VideoPause, VideoRecvItem, VideoSink,
173 VideoSinkSpec, VideoSource, VideoTrack, VideoTrackView,
174};
175
176// aws-lc-rs is never built for the phones; their DTLS/SRTP is the pure-Rust provider.
177#[cfg(all(
178 any(target_os = "ios", target_os = "android"),
179 not(feature = "rust-crypto")
180))]
181compile_error!(
182 "sew-call-client on iOS and Android needs the `mobile` feature (or `rust-crypto`): aws-lc-rs is not built for phones"
183);
184
185/// The call peer connection's DTLS/SRTP provider in this build: `"rust-crypto"` (features
186/// `rust-crypto`, `mobile`: dimpl's RustCrypto backend and RustCrypto SRTP) or `"aws-lc-rs"`.
187pub const CRYPTO_BACKEND: &str = if cfg!(feature = "rust-crypto") {
188 "rust-crypto"
189} else {
190 "aws-lc-rs"
191};
192
193/// Android only: hands the app's JNI env and `android.content.Context` to the platform TLS
194/// verifier (rustls-platform-verifier), which needs the JVM to reach Android's trust store.
195///
196/// **Call it once, before the first [`CallClient::join`]** (from `JNI_OnLoad` or the
197/// `Application.onCreate` bridge), with the application Context. Without it the first TLS
198/// connection (signalling, TURN-TLS, the key routes) panics inside the verifier. Later calls are
199/// no-ops. The Android build side is the host's: the app must include the verifier's Kotlin
200/// component (the `rustls-platform-verifier-android` package, as that crate's README
201/// describes) and keep its classes from the Android code shrinker (ProGuard rules).
202///
203/// [`jni`] is re-exported so the host passes the version the verifier takes.
204#[cfg(target_os = "android")]
205pub fn android_init(
206 env: &mut jni::JNIEnv<'_>,
207 context: jni::objects::JObject<'_>,
208) -> Result<(), jni::errors::Error> {
209 rustls_platform_verifier::android::init_with_env(env, context)
210}
211
212/// The `jni` crate [`android_init`] takes (Android only).
213#[cfg(target_os = "android")]
214pub use jni;
215
216/// The engine's name and version as Sew sees it (`ClientInfo`, the caps' `sdk_version`).
217pub const ENGINE_VERSION: &str = concat!("sew-call-client/", env!("CARGO_PKG_VERSION"));
218
219/// The user agent of the key routes and the call socket (no personal data).
220pub const USER_AGENT: &str = concat!(
221 "sew-call-client/",
222 env!("CARGO_PKG_VERSION"),
223 " (+https://github.com/Alakazam-211)"
224);
225
226/// Wall-clock unix milliseconds, or a test clock.
227pub type Clock = std::sync::Arc<dyn Fn() -> u64 + Send + Sync>;
228
229/// The system clock.
230pub fn system_clock() -> Clock {
231 use sew_proto::clock::Clock as _;
232 std::sync::Arc::new(|| sew_proto::clock::SystemClock.now_unix_ms())
233}
234
235/// README.md's examples, compiled and run as doc tests (with the `audio-core` feature: the example starts the audio bridge).
236#[cfg(all(doctest, feature = "audio-core"))]
237#[doc = include_str!("../README.md")]
238struct ReadmeExamples;