tauri_plugin_sew_voice/engine.rs
1//! The engine interface: what the plugin needs from a voice engine.
2//!
3//! The host's side is `sew-call-client`'s own: [`JoinProvider`], [`JoinRequest`],
4//! [`JoinAnswer`], [`ProviderError`] and [`RejoinReason`] are re-exported from it unchanged, so a
5//! host writes one provider for the engine and the plugin alike.
6//!
7//! The plugin's side is [`VoiceEngine`] and [`CallHandle`]: `crate::real::CallClientEngine`
8//! implements them over `sew_call_client::CallClient` and `Call` (the default engine), and
9//! [`crate::fake::FakeEngine`] in memory (tests, the example's offline mode).
10//!
11//! The JSON shapes the webview sees (`wire.rs`) are the same for both.
12
13use std::sync::Arc;
14
15use sew_call_client::device::DeviceKeyId;
16use tokio::sync::broadcast;
17
18use crate::details::{QualityInfo, RosterEntry, SecurityInfo};
19use crate::video::{
20 CameraRequest, DecoderSpec, DecoderWake, FrameDecoder, PreviewRequest, ScreenRequest,
21 TrackSettings, VideoFrames,
22};
23use crate::wire::{
24 CallState, CodecPreferenceInfo, DeviceChoice, DeviceList, ErrorInfo, LocalVideo, NoiseRemoval,
25 NoiseRemovalState, Participant, PermissionState, RecordingInfo, ScreenSource, SinkStats,
26 Speaking, VideoCaps, VideoCodec, VideoCodecPreference, VideoDevices, VideoTrack, video_code,
27};
28
29/// The answer of a video method an engine doesn't implement.
30fn no_video<T>() -> Result<T, EngineError> {
31 Err(EngineError::failed(video_code::VIDEO_UNSUPPORTED))
32}
33
34/// The person's Record and Stop as a Sew server that computes them sent them
35/// ([`CallEvent::RecordingControls`], [`CallHandle::recording_controls`]), from
36/// `sew-call-client`.
37pub use sew_call_client::ServerControls;
38/// The host's sign-in callback and its types, from `sew-call-client`.
39///
40/// One method, called to join and to re-join when Sew has dropped the join (`req.rejoin` says
41/// why: [`RejoinReason::AdmitLost`] or [`RejoinReason::CredentialExpired`]). The host calls
42/// Sew's voice or DM-call join with `call_credential: true` (and no `e2ee`) through its own
43/// session (K2: the daemon BFF `/cli/voice/join`; an App: its server) and returns the answer
44/// unchanged ([`JoinAnswer::from_json`]). The web UI never sees what it returns.
45///
46/// Recording (Sew 0.7.3): the provider forwards `req.recording_notice` as the voice join's
47/// `recording_notice`, returns Sew's `409 recording_consent_required` as
48/// [`ProviderError::ConsentRequired`] ([`ProviderError::from_sew_error`] reads Sew's error body,
49/// or an App server route's that passes it on unchanged), and sends the person's consent
50/// answers ([`JoinProvider::consent`], [`ConsentAnswer`]) with the person's own session. Sew
51/// 0.9.0: it also sends the person's Record and Stop ([`JoinProvider::recording`],
52/// [`RecordingRequest`]) the same way.
53pub use sew_call_client::{
54 AnswerError, BoxFuture, CONSENT_UNSUPPORTED, CallCredential, ConsentAnswer, ConsentRequired,
55 DmCall, JoinAnswer, JoinProvider, JoinRequest, ProviderError, RECORDING_UNSUPPORTED,
56 RecordingControl, RecordingRequest, RejoinReason,
57};
58
59/// Reads the App server route's `200` body, `{"join": <Sew's answer, unchanged>,
60/// "api_base": "https://…"}`, as a [`JoinAnswer`]: `join` is a voice join's
61/// `VoiceJoinResponse` or a DM call join's `CallJoinResponse` ([`JoinAnswer::from_json`]), and
62/// keeps its `call_credential`.
63///
64/// The error never quotes the body (it carries the media token and the call credential).
65pub fn app_server_answer(body: &[u8]) -> Result<JoinAnswer, ProviderError> {
66 let bad = |what: &str| ProviderError::Other(format!("the join answer did not parse ({what})"));
67 let mut v: serde_json::Value = serde_json::from_slice(body).map_err(|_| bad("not JSON"))?;
68 let api_base = v
69 .get("api_base")
70 .and_then(serde_json::Value::as_str)
71 .ok_or_else(|| bad("no api_base"))
72 .and_then(|s| url::Url::parse(s).map_err(|_| bad("api_base")))?;
73 let join = match v.get_mut("join").map(serde_json::Value::take) {
74 Some(j) if j.is_object() => serde_json::to_vec(&j).map_err(|_| bad("join"))?,
75 _ => return Err(bad("no join")),
76 };
77 JoinAnswer::from_json(&join, api_base).map_err(|_| bad("join"))
78}
79
80/// How an engine call fails.
81#[derive(Debug, Clone, PartialEq, thiserror::Error)]
82#[non_exhaustive]
83pub enum EngineError {
84 /// The provider failed (join or re-join).
85 #[error("provider: {0}")]
86 Provider(ProviderError),
87 /// The engine failed: `mic_denied`, `device_lost`, `turn_unreachable`, `e2ee_refused`, ...
88 #[error("{}", .0.code)]
89 Failed(ErrorInfo),
90}
91
92impl EngineError {
93 /// An engine failure with a code and no detail.
94 pub fn failed(code: impl Into<String>) -> EngineError {
95 EngineError::Failed(ErrorInfo::new(code))
96 }
97
98 /// The `{code, detail}` the webview gets.
99 pub fn to_info(&self) -> ErrorInfo {
100 use crate::wire::code;
101 match self {
102 EngineError::Provider(ProviderError::SigninRequired) => {
103 ErrorInfo::new(code::SIGNIN_REQUIRED)
104 }
105 EngineError::Provider(ProviderError::Refused { code, detail }) => ErrorInfo {
106 code: code.clone(),
107 detail: detail.clone(),
108 },
109 EngineError::Provider(ProviderError::Unavailable { retry_after_ms }) => {
110 ErrorInfo::with_detail(
111 code::UNAVAILABLE,
112 serde_json::json!({ "retry_after_ms": retry_after_ms }),
113 )
114 }
115 EngineError::Provider(ProviderError::Other(s)) => {
116 ErrorInfo::with_detail(code::PROVIDER_ERROR, s.clone())
117 }
118 // The notice changed: Sew's refusal details, for the app to show the new one.
119 EngineError::Provider(ProviderError::ConsentRequired(c)) => ErrorInfo::with_detail(
120 code::RECORDING_CONSENT_REQUIRED,
121 serde_json::to_value(c).unwrap_or_default(),
122 ),
123 // A provider error sew-call-client adds later.
124 EngineError::Provider(p) => ErrorInfo::with_detail(code::PROVIDER_ERROR, p.to_string()),
125 EngineError::Failed(info) => info.clone(),
126 }
127 }
128
129 /// The `ended` reason when a join fails this way.
130 pub fn end_reason(&self) -> String {
131 use crate::wire::reason;
132 match self {
133 EngineError::Provider(ProviderError::SigninRequired) => reason::SIGNIN_REQUIRED.into(),
134 EngineError::Provider(ProviderError::Refused { code, .. }) => code.clone(),
135 EngineError::Provider(ProviderError::Unavailable { .. }) => reason::UNAVAILABLE.into(),
136 EngineError::Provider(ProviderError::Other(_)) => reason::PROVIDER_ERROR.into(),
137 EngineError::Provider(ProviderError::ConsentRequired(_)) => {
138 crate::wire::code::RECORDING_CONSENT_REQUIRED.into()
139 }
140 // A provider error sew-call-client adds later.
141 EngineError::Provider(_) => reason::PROVIDER_ERROR.into(),
142 EngineError::Failed(info) => info.code.clone(),
143 }
144 }
145}
146
147/// What a live call reports (the engine's `CallEvent` in the plugin's shapes; devices are
148/// engine-wide here, see [`VoiceEngine::device_events`]).
149#[derive(Debug, Clone, PartialEq)]
150#[non_exhaustive]
151#[allow(clippy::large_enum_variant)]
152pub enum CallEvent {
153 /// A state change (`Idle` is never sent by an engine).
154 State(CallState),
155 /// The roster with mute and deaf flags.
156 Participants(Vec<Participant>),
157 /// Levels, this device included (the engine may send them faster than 10 Hz; the plugin
158 /// throttles).
159 Speaking(Vec<Speaking>),
160 /// A non-fatal error or warning (`device_lost`, `key_storage_file`, ...).
161 Error(ErrorInfo),
162 /// A moderator moved the call (Sew's `voice_server_updated`): `room` is the destination as
163 /// a host joins it (the channel's id: the voice channel's, or the DM's for a DM call).
164 Moved {
165 /// The destination room.
166 room: String,
167 },
168 /// The call's recording changed (Sew 0.7.3), or `None` once none is active.
169 Recording(Option<RecordingInfo>),
170 /// The call's key state or security code changed (0.4.1; [`CallHandle::security`]).
171 Security(Option<SecurityInfo>),
172 /// Every media participant with its engine identity and label (0.4.1;
173 /// [`CallHandle::roster`]).
174 Roster(Vec<RosterEntry>),
175 /// A stats window's connection quality (0.4.1; [`CallHandle::quality`]). The plugin shows
176 /// `lost` while the call is reconnecting, whatever the engine last said.
177 Quality(QualityInfo),
178 /// The call's video tracks changed (added, removed, muted, resized, paused): the whole
179 /// list.
180 Video(Vec<VideoTrack>),
181 /// This device's camera or screen changed state.
182 LocalVideo(LocalVideo),
183 /// The room's media policy changed (Sew's `media_policy_updated`; the engine also sends
184 /// the join answer's at the start).
185 Policy(serde_json::Value),
186 /// The person's Record and Stop from a Sew server that computes them (0.7.0): a new value,
187 /// or `None` when the server sends them but has none for the call's room (yet, or since a
188 /// move). Sending it at all says the server computes them
189 /// ([`CallHandle::server_controls`]); an engine against an older server never sends it.
190 RecordingControls(Option<ServerControls>),
191}
192
193/// A call's video now, for a late subscriber ([`CallHandle::video_snapshot`]).
194#[derive(Debug, Clone, Default, PartialEq, Eq)]
195pub struct VideoSnapshot {
196 /// The video tracks.
197 pub tracks: Vec<VideoTrack>,
198 /// This device's camera and screen.
199 pub local: LocalVideo,
200 /// The room's media policy (`None`: the engine has none).
201 pub policy: Option<serde_json::Value>,
202}
203
204/// A call's current state, for a late subscriber (the engine's `CallSnapshot`).
205#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct CallSnapshot {
207 /// The state now.
208 pub state: CallState,
209 /// The roster now.
210 pub participants: Vec<Participant>,
211 /// The active recording now (Sew 0.7.3).
212 pub recording: Option<RecordingInfo>,
213}
214
215/// One live call (the engine's `Call`).
216pub trait CallHandle: Send + Sync + 'static {
217 /// The call's id (Sew's call room).
218 fn call_id(&self) -> String;
219 /// Events from now on. The plugin subscribes once, right after `join`, then reads
220 /// [`CallHandle::snapshot`] so nothing sent in between is lost.
221 fn events(&self) -> broadcast::Receiver<CallEvent>;
222 /// The state and roster now.
223 fn snapshot(&self) -> CallSnapshot;
224 /// Self-mute and self-deafen (sending, `MuteTrackRequest` and Sew's self state).
225 fn mute(
226 &self,
227 muted: Option<bool>,
228 deafened: Option<bool>,
229 ) -> BoxFuture<'_, Result<(), EngineError>>;
230 /// Leave: Sew's leave with the credential, then the engine's.
231 fn leave(&self) -> BoxFuture<'_, Result<(), EngineError>>;
232 /// The room a moderator move took the call to (the last [`CallEvent::Moved`]); `None` when
233 /// there was no move (or the engine does not say).
234 fn moved_room(&self) -> Option<String> {
235 None
236 }
237 /// This call's server computes the person's Record and Stop (0.7.0): the plugin then takes
238 /// them from [`CallHandle::recording_controls`] and the [`CallEvent::RecordingControls`]
239 /// events instead of working them out from the host's rights. The default, `false`, is an
240 /// older server (or an engine that does not say).
241 fn server_controls(&self) -> bool {
242 false
243 }
244 /// The person's Record and Stop as the server sent them last for the call's room (0.7.0);
245 /// `None` when it sent none (yet). The default has none.
246 fn recording_controls(&self) -> Option<ServerControls> {
247 None
248 }
249 /// The person's answer to the recording notice (Sew 0.7.3): held at `consent_required`,
250 /// the engine joins with it; in a call, the host's provider sends it. The default answers
251 /// `consent_unsupported`.
252 fn consent(
253 &self,
254 granted: bool,
255 notice_version: u32,
256 ) -> BoxFuture<'_, Result<(), EngineError>> {
257 let _ = (granted, notice_version);
258 Box::pin(std::future::ready(Err(EngineError::failed(
259 crate::wire::code::CONSENT_UNSUPPORTED,
260 ))))
261 }
262 /// "Stop recording me": withdraws a granted consent through the host's provider. The
263 /// default answers `consent_unsupported`.
264 fn withdraw_consent(&self) -> BoxFuture<'_, Result<(), EngineError>> {
265 Box::pin(std::future::ready(Err(EngineError::failed(
266 crate::wire::code::CONSENT_UNSUPPORTED,
267 ))))
268 }
269 /// Record (Sew 0.9.0): the person starts recording the call's room through the host's
270 /// provider ([`JoinProvider::recording`]); Sew's answer becomes the `recording` event.
271 /// The default answers `recording_unsupported`.
272 fn start_recording(&self) -> BoxFuture<'_, Result<(), EngineError>> {
273 Box::pin(std::future::ready(Err(EngineError::failed(
274 crate::wire::code::RECORDING_UNSUPPORTED,
275 ))))
276 }
277 /// Stop (Sew 0.9.0): the person stops the room's active recording through the host's
278 /// provider. The default answers `recording_unsupported`.
279 fn stop_recording(&self) -> BoxFuture<'_, Result<(), EngineError>> {
280 Box::pin(std::future::ready(Err(EngineError::failed(
281 crate::wire::code::RECORDING_UNSUPPORTED,
282 ))))
283 }
284 /// The device's network changed (a phone's `NWPathMonitor` or `ConnectivityManager`): run
285 /// the resume path now (session resume, then an ICE restart) on a fresh TURN-TLS socket,
286 /// instead of waiting for the old one to die (`sew-call-client`'s `Call::network_changed`).
287 /// It must not block: an engine starts the work and returns. The default does nothing
288 /// (the engine notices the loss itself, later).
289 fn network_changed(&self) {}
290 /// The call's key state and security code now (0.4.1); then [`CallEvent::Security`]. The
291 /// default has none.
292 fn security(&self) -> Option<SecurityInfo> {
293 None
294 }
295 /// Every media participant now (0.4.1); then [`CallEvent::Roster`]. The default has none.
296 fn roster(&self) -> Vec<RosterEntry> {
297 Vec::new()
298 }
299 /// The last stats window's quality (0.4.1); then [`CallEvent::Quality`]. The default is
300 /// `unknown`.
301 fn quality(&self) -> QualityInfo {
302 QualityInfo::unknown()
303 }
304
305 // ── video (the defaults: an engine without video) ──
306
307 /// The call's frame channel: every subscribed track's encoded plaintext frames (decrypted
308 /// and checked; nothing that failed decryption) and this device's self-view frames, with
309 /// the tracks' `Added`, `Removed`, `Broken` and `KeyframeNeeded` items. The plugin takes it
310 /// once, right after `join`; a second call answers `None`. The default: `None` (no video).
311 fn video_frames(&self) -> Option<VideoFrames> {
312 None
313 }
314 /// The call's video tracks, this device's camera and screen and the media policy now
315 /// (read after `join` and after a missed event). The default: none.
316 fn video_snapshot(&self) -> VideoSnapshot {
317 VideoSnapshot::default()
318 }
319 /// What the sinks of remote track `track` want now (the union of its sinks, sent on every
320 /// change). The engine keeps every track disabled until told otherwise. It must not
321 /// block. The default does nothing.
322 fn set_video_settings(&self, track: &str, settings: TrackSettings) {
323 let _ = (track, settings);
324 }
325 /// A sink of `track` needs a keyframe (it opened, became visible, or its decoder failed or
326 /// fell behind): the engine asks the sender (rate-limited) or, for `local:*`, its own
327 /// encoder. It must not block. The default does nothing.
328 fn request_keyframe(&self, track: &str) {
329 let _ = track;
330 }
331 /// The webview's decoder counters of `track`'s sinks (every `video_sink_update` with
332 /// stats; summed over the track's sinks), for the stats beacon. The default drops them.
333 fn video_sink_stats(&self, track: &str, stats: SinkStats) {
334 let _ = (track, stats);
335 }
336 /// Camera on or off: the policy, the OS permission, the lease, the device, the encoders,
337 /// then publishing (`local_video` follows each step). Answers once publishing (or off).
338 /// The default: `video_unsupported`.
339 fn camera(&self, req: CameraRequest) -> BoxFuture<'_, Result<(), EngineError>> {
340 let _ = req;
341 Box::pin(std::future::ready(no_video()))
342 }
343 /// Camera off with `reason` as `local_video`'s reason (who turned it off: `system_ui` for
344 /// CallKit's or Telecom's video button), so a call log tells the offs apart. The default:
345 /// [`CallHandle::camera`] off.
346 fn camera_off_because(&self, reason: &'static str) -> BoxFuture<'_, Result<(), EngineError>> {
347 let _ = reason;
348 self.camera(CameraRequest {
349 on: false,
350 device: None,
351 })
352 }
353 /// Screen share on or off, as [`CallHandle::camera`] (the picker when `source` is
354 /// `None`). The default: `video_unsupported`.
355 fn screen(&self, req: ScreenRequest) -> BoxFuture<'_, Result<(), EngineError>> {
356 let _ = req;
357 Box::pin(std::future::ready(no_video()))
358 }
359 /// The iPhone screen share (`VoiceControl::screen_share_ring`): arm the broadcast
360 /// extension's ring in `container` (the App Group container) for the rest of the call; its
361 /// frames are published as the call's screen while the extension sends them. Arming again
362 /// replaces the ring. Answers once the ring's file is made. The default:
363 /// `screen_unsupported`.
364 fn screen_share_ring(
365 &self,
366 container: std::path::PathBuf,
367 ) -> BoxFuture<'_, Result<(), EngineError>> {
368 let _ = container;
369 Box::pin(std::future::ready(Err(EngineError::failed(
370 crate::wire::video_code::SCREEN_UNSUPPORTED,
371 ))))
372 }
373 /// The app went to the background or came back, as the plugin decides it: background when
374 /// the app says so ([`VoiceEngine::app_scene`]) **or** the video backend does (kessel-video's
375 /// `BackendEvent::Background`), foreground only when both say foreground. The plugin has
376 /// already hidden (or re-shown) the sinks; this is the engine's hook for its own sending
377 /// side (pausing and resuming the camera publish). It must not block. The default does
378 /// nothing.
379 fn app_scene(&self, scene: AppScene) {
380 let _ = scene;
381 }
382}
383
384/// Whether the app is on screen (phones): [`crate::VoiceControl::app_scene`].
385///
386/// It is not an audio interruption: `suspend` / `resume` ([`AudioSessionEvent`]) stay for
387/// those (Siri, a cellular call) and never touch video, and an app can go to the background
388/// with no audio interruption at all.
389#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
390pub enum AppScene {
391 /// On screen.
392 #[default]
393 Foreground,
394 /// In the background (iOS `sceneDidEnterBackground`, Android `onPause` / `onStop`).
395 Background,
396}
397
398impl AppScene {
399 /// Background or foreground from a flag.
400 pub fn background(background: bool) -> AppScene {
401 if background {
402 AppScene::Background
403 } else {
404 AppScene::Foreground
405 }
406 }
407
408 /// Is it the background?
409 pub fn is_background(self) -> bool {
410 self == AppScene::Background
411 }
412}
413
414/// The phone's audio session, as CallKit (iOS) or Telecom (Android) reports it, for the engine
415/// to pass to kessel-audio unchanged. The plugin never configures `AVAudioSession` or the
416/// Android audio mode itself: CallKit and Telecom own them.
417#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
418#[non_exhaustive]
419pub enum AudioSessionEvent {
420 /// The session is active (`CXProviderDelegate` `didActivate`; on Android, the Telecom
421 /// connection is active): kessel-audio's `start_when_session_active` opens the microphone
422 /// now.
423 Activated,
424 /// The session is no longer active (`didDeactivate`).
425 Deactivated,
426 /// An interruption began (kessel-audio's `suspend`).
427 Suspend,
428 /// The interruption ended (kessel-audio's `resume`).
429 Resume,
430 /// The OS audio route changed (speaker, earpiece, Bluetooth; kessel-audio's
431 /// `route_changed`).
432 RouteChanged,
433}
434
435/// The engine (`sew-call-client`'s `CallClient`): one per app.
436pub trait VoiceEngine: Send + Sync + 'static {
437 /// Join through the provider; the engine keeps the provider for re-joins.
438 fn join(
439 &self,
440 provider: Arc<dyn JoinProvider>,
441 req: JoinRequest,
442 ) -> BoxFuture<'_, Result<Arc<dyn CallHandle>, EngineError>>;
443 /// [`VoiceEngine::join`] from a host whose webview decodes `decode` (its WebCodecs probe;
444 /// `None`: the host didn't say, and nothing is assumed). The engine offers to receive only
445 /// the codecs it or the webview can decode (VP8 always; H.264 never on Linux), so the media
446 /// server sends it no codec it can't show. The default ignores `decode` and joins.
447 fn join_decoding(
448 &self,
449 provider: Arc<dyn JoinProvider>,
450 req: JoinRequest,
451 decode: Option<Vec<VideoCodec>>,
452 ) -> BoxFuture<'_, Result<Arc<dyn CallHandle>, EngineError>> {
453 let _ = decode;
454 self.join(provider, req)
455 }
456 /// The audio devices now.
457 fn devices(&self) -> Result<DeviceList, EngineError>;
458 /// Switch the input and/or output (`None`: unchanged; [`DeviceChoice::Default`]: the OS
459 /// default, followed when it changes); hot-swaps a live call's stream.
460 fn set_device(
461 &self,
462 input: Option<DeviceChoice>,
463 output: Option<DeviceChoice>,
464 ) -> Result<(), EngineError>;
465 /// Device list changes (hot-plug, a default change, a `set_device`).
466 fn device_events(&self) -> broadcast::Receiver<DeviceList>;
467 /// The phone's audio session changed ([`AudioSessionEvent`]): passed to kessel-audio
468 /// unchanged, for the live call and (an engine that keeps it) the next one, since CallKit
469 /// may activate the session before the join has a call. It must not block. The default
470 /// does nothing (a desktop engine).
471 fn audio_session(&self, event: AudioSessionEvent) {
472 let _ = event;
473 }
474 /// The app moved between the foreground and the background, came back to the front, or a
475 /// window gained or lost focus (Tauri's lifecycle, and [`crate::VoiceControl::app_scene`]):
476 /// a moment the device is busy with something else. The engine's noise removal holds its
477 /// timing rules back for a grace window, so the moment does not cost the call its model. It
478 /// must not block. The default does nothing.
479 fn app_scene_changed(&self) {}
480 /// A sign-out from one Sew install: delete every device of `install_id` the engine's device
481 /// store holds (a hardware key through `HardwareDeviceKey::delete`) and its pins; answer the
482 /// removed keys. The service refuses it while a call is live. The default holds no devices
483 /// and answers none.
484 fn forget_server(
485 &self,
486 install_id: u64,
487 ) -> BoxFuture<'_, Result<Vec<DeviceKeyId>, EngineError>> {
488 let _ = install_id;
489 Box::pin(std::future::ready(Ok(Vec::new())))
490 }
491 /// Every device key the engine's device store holds, sorted. The default holds none.
492 fn known_device_keys(&self) -> BoxFuture<'_, Result<Vec<DeviceKeyId>, EngineError>> {
493 Box::pin(std::future::ready(Ok(Vec::new())))
494 }
495 /// Leaves and releases every call of this engine the plugin no longer holds (the service
496 /// has no live call: a `leave` then, or a join refused `already_in_call`), so a host
497 /// recovers without a reload. It never blocks for long. The default has none.
498 fn release_calls(&self) -> BoxFuture<'_, ()> {
499 Box::pin(std::future::ready(()))
500 }
501
502 // ── noise removal (the defaults: an engine without it) ──
503
504 /// Sets the microphone's noise removal for this and later calls: in a call, from its next
505 /// 10 ms block, without a click. Answers the state now. Kept until the process ends
506 /// (persisting it is the host's job). The default: `Off` is taken (there is nothing to
507 /// remove), any other mode is refused with `noise_mode_unavailable`.
508 fn set_noise_removal(&self, mode: NoiseRemoval) -> Result<NoiseRemovalState, EngineError> {
509 if mode == NoiseRemoval::Off {
510 Ok(NoiseRemovalState::running(NoiseRemoval::Off))
511 } else {
512 Err(EngineError::failed(
513 crate::wire::code::NOISE_MODE_UNAVAILABLE,
514 ))
515 }
516 }
517 /// The noise removal setting and what runs (`{mode, active, reason?}`). The default:
518 /// `off`, running.
519 fn noise_removal(&self) -> NoiseRemovalState {
520 NoiseRemovalState::running(NoiseRemoval::Off)
521 }
522 /// Each change of [`VoiceEngine::noise_removal`] (the `noise_removal` event). The plugin
523 /// subscribes at start. The default: `None` (no events).
524 fn noise_removal_events(&self) -> Option<broadcast::Receiver<NoiseRemovalState>> {
525 None
526 }
527 /// Android: whether the device has the unprocessed audio source (the app reads
528 /// `AudioManager.PROPERTY_SUPPORT_AUDIO_SOURCE_UNPROCESSED`). With it, noise removal Off
529 /// captures from that source; without it (the default), from the voice recognition source.
530 /// It must not block. The default does nothing (an engine without a phone backend).
531 fn set_android_unprocessed_supported(&self, supported: bool) {
532 let _ = supported;
533 }
534 /// Where DeepFilterNet3's weights are (feature `dfn3`): the engine records the path and
535 /// checks the file's pinned sha256 (reading it through once), and loads the model when a
536 /// call first needs it, with RNNoise as its step-down. The check reads the whole file: the
537 /// plugin calls it on a thread of its own at start. The default: refused with
538 /// `noise_mode_unavailable` (Standard stays what the engine has).
539 fn set_dfn3_weights(&self, path: &std::path::Path) -> Result<(), EngineError> {
540 let _ = path;
541 Err(EngineError::failed(
542 crate::wire::code::NOISE_MODE_UNAVAILABLE,
543 ))
544 }
545 /// DEBUG ONLY (feature `noise-bench`): the noise removal stage on this device's microphone
546 /// for `duration`, with no call, as sew-call-client's `noise_bench::NoiseBenchReport` in
547 /// JSON. Blocks for `duration`. The default: refused with `noise_mode_unavailable`.
548 /// How long DeepFilterNet3's model stays in memory after the last call ends (feature
549 /// `dfn3`; the next call loads it again). The default does nothing.
550 fn set_dfn3_idle_unload(&self, after: std::time::Duration) {
551 let _ = after;
552 }
553 /// What the audio pipeline's processing thread asks the OS for in the calls that start
554 /// after this (sew-call-client's `NoiseRemovalControl::set_dsp_sched`); `None`: the
555 /// pipeline's default. The default: refused with `noise_mode_unavailable`.
556 fn set_dsp_sched(&self, sched: Option<crate::DspSched>) -> Result<(), EngineError> {
557 let _ = sched;
558 Err(EngineError::failed(
559 crate::wire::code::NOISE_MODE_UNAVAILABLE,
560 ))
561 }
562 /// The scheduling set with [`VoiceEngine::set_dsp_sched`]. The default: `None`.
563 fn dsp_sched(&self) -> Option<crate::DspSched> {
564 None
565 }
566 #[cfg(feature = "noise-bench")]
567 fn noise_bench(&self, duration: std::time::Duration) -> Result<serde_json::Value, EngineError> {
568 let _ = duration;
569 Err(EngineError::failed(
570 crate::wire::code::NOISE_MODE_UNAVAILABLE,
571 ))
572 }
573 /// MEASUREMENT ONLY (feature `noise-probe`): the next call's noise removal stage is
574 /// probed (sew-call-client's `noise_probe`). The default: refused with
575 /// `noise_mode_unavailable`.
576 #[cfg(feature = "noise-probe")]
577 fn arm_noise_probe(&self) -> Result<(), EngineError> {
578 Err(EngineError::failed(
579 crate::wire::code::NOISE_MODE_UNAVAILABLE,
580 ))
581 }
582 /// MEASUREMENT ONLY (feature `noise-probe`): labels the probed call's blocks from now on
583 /// as `phase` (it does not change the scheduling; see [`VoiceEngine::set_dsp_sched`]). The
584 /// default: refused with `noise_mode_unavailable`.
585 #[cfg(feature = "noise-probe")]
586 fn set_noise_probe_phase(
587 &self,
588 phase: crate::NoiseProbePhase,
589 deadline: Option<std::time::Duration>,
590 ) -> Result<(), EngineError> {
591 let _ = (phase, deadline);
592 Err(EngineError::failed(
593 crate::wire::code::NOISE_MODE_UNAVAILABLE,
594 ))
595 }
596 /// MEASUREMENT ONLY (feature `noise-probe`): the last probed call's figures as
597 /// sew-call-client's `noise_probe::NoiseProbeReport` in JSON, during the call or after it
598 /// (`None`: no call was probed). The default: `None`.
599 #[cfg(feature = "noise-probe")]
600 fn noise_probe_report(&self) -> Result<Option<serde_json::Value>, EngineError> {
601 Ok(None)
602 }
603
604 // ── video (the defaults: an engine without video) ──
605
606 /// What this device's video can do. The default: everything off (backend `null`).
607 fn video_caps(&self) -> VideoCaps {
608 VideoCaps::default()
609 }
610 /// Sets this device's video codec preference for this and later calls: a camera or screen
611 /// turned on after it publishes under it; `PreferVp8` also stops offering to receive H.264
612 /// from the next join. Kept until the process ends (persisting it is the host's job). The
613 /// default: `video_unsupported`.
614 fn set_video_codec_preference(&self, pref: VideoCodecPreference) -> Result<(), EngineError> {
615 let _ = pref;
616 no_video()
617 }
618 /// The video codec setting and what it gives here now (`video_caps.codec_preference`).
619 /// The default: `None`, an engine without video publish (`video_caps` leaves the readback
620 /// out).
621 fn video_codec_preference(&self) -> Option<CodecPreferenceInfo> {
622 None
623 }
624 /// The cameras, the chosen one and the OS permissions. The default: `video_unsupported`.
625 fn video_devices(&self) -> Result<VideoDevices, EngineError> {
626 no_video()
627 }
628 /// Choose the camera: switches a live camera without a republish, and is kept for the
629 /// next `camera` or `preview`. The default: `video_unsupported`.
630 fn set_video_device(&self, camera: DeviceChoice) -> Result<(), EngineError> {
631 let _ = camera;
632 no_video()
633 }
634 /// Camera list changes (hot-plug, a permission change, a `set_video_device`). The plugin
635 /// subscribes on the first use of video. The default: `None` (no events).
636 fn video_device_events(&self) -> Option<broadcast::Receiver<VideoDevices>> {
637 None
638 }
639 /// The displays and windows to share, for an App's own picker (`[]` where only the OS
640 /// picker exists). The default: `video_unsupported`.
641 fn screen_sources(&self) -> BoxFuture<'_, Result<Vec<ScreenSource>, EngineError>> {
642 Box::pin(std::future::ready(no_video()))
643 }
644 /// The camera outside a call (a pre-join check): on, it answers the preview's frame channel
645 /// (`local:camera` frames); off, `None`. The camera opens **only** on this explicit call.
646 /// The default: `video_unsupported`.
647 fn preview(
648 &self,
649 req: PreviewRequest,
650 ) -> BoxFuture<'_, Result<Option<VideoFrames>, EngineError>> {
651 let _ = req;
652 Box::pin(std::future::ready(no_video()))
653 }
654 /// A `local:camera` sink outside a call needs a keyframe: the preview's encoder makes one
655 /// now. It must not block. The default does nothing.
656 fn preview_keyframe(&self) {}
657
658 // ── phones (the defaults: a desktop engine, or one without video) ──
659
660 /// The camera permission now. Never prompts. The default: `unsupported`.
661 fn camera_permission(&self) -> PermissionState {
662 PermissionState::Unsupported
663 }
664 /// Asks for the camera: the OS prompt when the permission is `prompt` (iOS), else the state
665 /// at once. On Android the app asks for CAMERA itself (an Activity callback, in Tauri its
666 /// permission API); this then reports the state without a prompt. The default:
667 /// `unsupported`.
668 fn request_camera_permission(&self) -> BoxFuture<'_, PermissionState> {
669 Box::pin(std::future::ready(PermissionState::Unsupported))
670 }
671 /// The app went to the background or came back, as the app reports it (passed on before
672 /// the plugin hides or re-shows its sinks). The real engine tells kessel-video's Android
673 /// backend (`AndroidContext::set_background`). It must not block. The default does
674 /// nothing.
675 fn app_scene(&self, scene: AppScene) {
676 let _ = scene;
677 }
678 /// The device turned (degrees clockwise from its natural orientation, as Android's
679 /// `OrientationEventListener` reports it): kessel-video's Android backend turns camera
680 /// frames upright from the next one. It must not block. The default does nothing (iOS's
681 /// backend follows the device itself).
682 fn device_orientation(&self, degrees: u32) {
683 let _ = degrees;
684 }
685 /// The video backend's own background signal (kessel-video's `BackendEvent::Background`:
686 /// `true` in the background), the second signal next to [`VoiceEngine::app_scene`]. The
687 /// plugin subscribes on the first use of a sink or a scene. The default: `None`.
688 fn video_background_events(&self) -> Option<broadcast::Receiver<bool>> {
689 None
690 }
691 /// The video backend, for the plugin's native sinks (they decode VP8 with its decoder and
692 /// turn frames into OS buffers with its `convert`). The default: `None` (a native sink then
693 /// delivers H.264 only).
694 #[cfg(feature = "video-core")]
695 fn native_video_backend(&self) -> Option<Arc<dyn sew_call_client::kessel_video::VideoBackend>> {
696 None
697 }
698 /// A new tap on the camera's raw frames (sew-call-client's `CameraTap`), for a self-view
699 /// native sink: the frames of the camera the engine opens (the preview, a call's camera),
700 /// before any encoder. It must never open the camera. The default: `None` (the self-view
701 /// sink is refused with `video_unsupported`).
702 #[cfg(feature = "video-core")]
703 fn camera_tap(&self) -> Option<sew_call_client::CameraTap> {
704 None
705 }
706 /// A decoder for the decoded-frame fallback (a sink whose webview can't decode the track's
707 /// codec): `spec.codec` in, `spec.format` out at most `spec.fit`. `wake` is called (from
708 /// any thread) whenever an output or an error is queued. Only for a codec
709 /// [`VoiceEngine::video_caps`] lists in `decode_codecs`. The default:
710 /// `video_unsupported`.
711 fn video_decoder(
712 &self,
713 spec: DecoderSpec,
714 wake: DecoderWake,
715 ) -> Result<Box<dyn FrameDecoder>, EngineError> {
716 let _ = (spec, wake);
717 no_video()
718 }
719}