Skip to main content

zaun_client/voice/
mod.rs

1//! Voice channels (specification ยง8.12, ADR-0018): join, leave, mute, moderate, and an
2//! end-to-end encrypted mesh of WebRTC connections, one per other participant.
3//!
4//! The host relays signalling and keys and never sees media. Every frame is sealed with
5//! SFrame under a key that only reaches the other participants inside X-Wing (post-quantum
6//! hybrid) wrappings, signed with this member's key; WebRTC's own DTLS-SRTP runs underneath.
7//!
8//! Media is relayed by default: the stay takes an allocation on the host's TURN server and
9//! offers only that relayed address, so other participants never learn this device's IP
10//! address. A direct (peer-to-peer) path is an option the application turns on
11//! ([`VoiceOptions::allow_direct`]); a host without a TURN server offers nothing else.
12//!
13//! The application brings the sound: it encodes Opus frames (20 ms, 48 kHz) and hands them
14//! to [`VoiceSession::send_audio`], and plays the frames [`VoiceEvent::Audio`] delivers.
15//!
16//! ```no_run
17//! # use zaun_client::{Community, VoiceEvent};
18//! # fn opus_frame() -> Vec<u8> { Vec::new() }
19//! # fn play(_: &[u8]) {}
20//! # fn demo(community: &Community) -> zaun_client::Result<()> {
21//! let lounge = community.channel_by_name("lounge").expect("a voice channel");
22//! let voice = lounge.join()?;
23//! voice.send_audio(&opus_frame());
24//! while let Some(event) = voice.next_event(std::time::Duration::from_millis(20)) {
25//!     if let VoiceEvent::Audio { frame, .. } = event {
26//!         play(&frame);
27//!     }
28//! }
29//! voice.leave()?;
30//! # Ok(()) }
31//! ```
32
33mod keys;
34mod media;
35mod ogg;
36mod pinning;
37mod player;
38mod policy;
39mod relay;
40mod signal;
41mod stay;
42mod worker;
43
44use std::collections::BTreeMap;
45use std::net::IpAddr;
46use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
47use std::sync::{Arc, Mutex, PoisonError};
48use std::thread::JoinHandle;
49use std::time::Duration;
50
51use crossbeam_channel::{Receiver, Sender, bounded, unbounded};
52use zaun_community_protocol::command::object::Opaque;
53use zaun_community_protocol::command::voice::{Join, Joined, Leave, Moderate, Update};
54use zaun_community_protocol::event::Event as Catalogue;
55use zaun_community_protocol::ids::{ChannelId, CommunityId, VoiceSessionId};
56
57use crate::client::Client;
58use crate::error::{Error, Result};
59use crate::store::Store;
60
61use keys::StayKeys;
62use media::Input;
63
64pub use player::{AudioPlayer, AudioPlayerEvent, AudioPlayerStatus, AudioResource, FfmpegOptions};
65
66/// Events a voice session keeps for an application that reads slowly; past this, audio is
67/// dropped first (it is stale anyway).
68const EVENT_QUEUE: usize = 512;
69
70/// The voice sessions' inputs, by community, shared with the driver, which hands them the
71/// host's voice events.
72pub(crate) type Routes = Arc<Mutex<BTreeMap<CommunityId, Sender<Input>>>>;
73
74/// Gives a voice event to the community's session. Returns whether the event is the session's
75/// alone (`voice.signal`, `voice.keys`), so the application does not see it.
76pub(crate) fn route(routes: &Routes, community: CommunityId, event: &Catalogue) -> bool {
77    let input = match event {
78        Catalogue::VoiceJoined(j) => Input::Joined(j.participant.clone()),
79        Catalogue::VoiceUpdated(u) => Input::Updated(u.participant.clone()),
80        Catalogue::VoiceLeft(l) => Input::Left(*l),
81        Catalogue::VoiceSignal(s) => Input::Signal(s.clone()),
82        Catalogue::VoiceKeys(k) => Input::Keys(k.clone()),
83        _ => return false,
84    };
85    let private = matches!(input, Input::Signal(_) | Input::Keys(_));
86    let map = routes.lock().unwrap_or_else(PoisonError::into_inner);
87    match map.get(&community) {
88        Some(tx) => {
89            let _ = tx.send(input);
90            private
91        }
92        None => false,
93    }
94}
95
96/// Ends the community's voice session: its host connection is gone or the member was removed.
97pub(crate) fn end(routes: &Routes, community: CommunityId) {
98    let tx = routes
99        .lock()
100        .unwrap_or_else(PoisonError::into_inner)
101        .remove(&community);
102    if let Some(tx) = tx {
103        let _ = tx.send(Input::HostGone);
104    }
105}
106
107/// How a voice session connects.
108///
109/// By default media goes through the host's TURN relay, and peers see only the relay's
110/// address. The relay sees this device's address and the encrypted frames. The relay is
111/// reached as the host lists it: `turn:` over UDP or TCP, or `turns:` over TLS 1.3 with the
112/// post-quantum X25519MLKEM768 key exchange (a relay without it is refused).
113#[derive(Debug, Clone, Default)]
114pub struct VoiceOptions {
115    /// Also offer peers a direct path to this device's own address, when the host allows it
116    /// (`ice_policy` `all` or `direct`). The other participants then learn this device's IP
117    /// address, so ask the user first. Off by default: media is relayed, and a join to a host
118    /// without a relay is refused.
119    pub allow_direct: bool,
120    /// The address the stay's socket binds to; `None` takes the address that reaches the
121    /// TURN server (or, without one, the default route). It is offered to peers only with
122    /// [`allow_direct`](Self::allow_direct).
123    pub host_ip: Option<IpAddr>,
124    /// Join muted.
125    pub self_mute: bool,
126    /// Join deafened.
127    pub self_deaf: bool,
128    /// Certificate authorities (DER) to trust for `turns:` relays besides the Mozilla roots,
129    /// for a host whose relay has a certificate from a private authority.
130    pub turn_tls_roots: Vec<Vec<u8>>,
131}
132
133pub use stay::VoiceEvent;
134
135/// One stay in a voice channel. Dropping it leaves the channel.
136pub struct VoiceSession {
137    community: CommunityId,
138    channel: ChannelId,
139    session: VoiceSessionId,
140    input: Sender<Input>,
141    events: Receiver<VoiceEvent>,
142    can_send: Arc<AtomicBool>,
143    /// Frames that arrived from a participant and did not open.
144    refused: Arc<AtomicU64>,
145    client: Client,
146    threads: Vec<JoinHandle<()>>,
147    left: bool,
148}
149
150impl VoiceSession {
151    /// The community.
152    #[must_use]
153    pub const fn community(&self) -> CommunityId {
154        self.community
155    }
156
157    /// The voice channel.
158    #[must_use]
159    pub const fn channel(&self) -> ChannelId {
160        self.channel
161    }
162
163    /// This stay's voice session, as the host named it.
164    #[must_use]
165    pub const fn voice_session(&self) -> VoiceSessionId {
166        self.session
167    }
168
169    /// Sends one Opus packet to every connected participant, sealed, now: the caller keeps
170    /// the time (one packet per 20 ms for 20 ms packets). Its duration comes from its TOC
171    /// byte. Frames are dropped while this member is muted (by itself or a moderator) or may
172    /// not speak. To play files or streams in real time, [`subscribe`](Self::subscribe) to an
173    /// [`AudioPlayer`] instead.
174    pub fn send_audio(&self, frame: &[u8]) {
175        if self.can_send.load(Ordering::Relaxed) {
176            let samples = ogg::packet_samples(frame).unwrap_or(960);
177            let _ = self.input.send(Input::Audio {
178                frame: frame.to_vec(),
179                samples,
180            });
181        }
182    }
183
184    /// Sends what `player` plays (discord.js's `connection.subscribe(player)`), instead of
185    /// any player subscribed before. The player does not keep this session alive.
186    pub fn subscribe(&self, player: &AudioPlayer) {
187        player.subscribe(player::Sink {
188            session: self.session,
189            input: self.input.clone(),
190            can_send: Arc::clone(&self.can_send),
191        });
192    }
193
194    /// Stops sending what `player` plays.
195    pub fn unsubscribe(&self, player: &AudioPlayer) {
196        player.unsubscribe(self.session);
197    }
198
199    /// How many frames arrived from participants and did not open (a wrong key, a damaged
200    /// frame, one that was never sealed, or one sealed under an epoch this stay never had or
201    /// no longer keeps, around joins and leaves); none are played.
202    #[must_use]
203    pub fn frames_refused(&self) -> u64 {
204        self.refused.load(Ordering::Relaxed)
205    }
206
207    /// Whether frames given to [`send_audio`](Self::send_audio) are sent now.
208    #[must_use]
209    pub fn can_send(&self) -> bool {
210        self.can_send.load(Ordering::Relaxed)
211    }
212
213    /// The next event, or `None` when none arrives within `timeout` or the session ended.
214    #[must_use]
215    pub fn next_event(&self, timeout: Duration) -> Option<VoiceEvent> {
216        self.events.recv_timeout(timeout).ok()
217    }
218
219    /// The events, blocking; ends with the session.
220    pub fn events(&self) -> impl Iterator<Item = VoiceEvent> + Send + 'static {
221        self.events.clone().into_iter()
222    }
223
224    /// Mutes or deafens this member (`voice.update`); deafened, incoming audio is dropped.
225    ///
226    /// # Errors
227    /// The host refused or did not answer.
228    pub fn set_self(&self, mute: Option<bool>, deaf: Option<bool>) -> Result<()> {
229        let body = Update {
230            self_mute: mute,
231            self_deaf: deaf,
232        };
233        self.client.command(self.community, None, body)?;
234        let _ = self.input.send(Input::SetSelf { mute, deaf });
235        Ok(())
236    }
237
238    /// Leaves the channel (`voice.leave`) and closes every media connection.
239    ///
240    /// # Errors
241    /// The host refused or did not answer; the media is closed either way.
242    pub fn leave(mut self) -> Result<()> {
243        self.left = true;
244        self.stop();
245        self.client
246            .command(self.community, None, Leave {})
247            .map(|_| ())
248    }
249
250    fn stop(&mut self) {
251        let routes = self.client.voice_routes();
252        let mut map = routes.lock().unwrap_or_else(PoisonError::into_inner);
253        if map
254            .get(&self.community)
255            .is_some_and(|tx| tx.same_channel(&self.input))
256        {
257            map.remove(&self.community);
258        }
259        drop(map);
260        let _ = self.input.send(Input::Stop);
261        for t in self.threads.drain(..) {
262            let _ = t.join();
263        }
264    }
265}
266
267impl Drop for VoiceSession {
268    fn drop(&mut self) {
269        if !self.left {
270            self.stop();
271            // Best effort: the host also ends the stay when this connection closes.
272            let (client, community) = (self.client.clone(), self.community);
273            let _ = std::thread::Builder::new()
274                .name("zaun-voice-leave".into())
275                .spawn(move || {
276                    let _ = client.command(community, None, Leave {});
277                });
278        }
279    }
280}
281
282impl Client {
283    /// Joins voice channel `channel` (`voice.join`) and connects to everyone in it. The media
284    /// is end-to-end encrypted (ADR-0018) and relayed through the host's TURN server; see
285    /// [`VoiceOptions`] for when a direct connection, which shows this device's IP address to
286    /// the other participants, is used. With a relay, this returns once the allocation is up
287    /// (a few round trips; at most about 8 s).
288    ///
289    /// # Errors
290    /// [`Error::UnknownCommunity`]; [`Error::Voice`] when already in voice in this community,
291    /// the host's media policy is not acceptable, or its TURN relay cannot be used (then this
292    /// client leaves again); the host's refusal (no `CONNECT`, full, timed out).
293    pub(crate) fn join_voice(
294        &self,
295        community: CommunityId,
296        channel: ChannelId,
297        options: VoiceOptions,
298    ) -> Result<VoiceSession> {
299        let me = self
300            .data(&community)
301            .map(|c| c.me)
302            .ok_or(Error::UnknownCommunity)?;
303        let member_key = Store::new(&self.inner_dir()).load_key(&community, "member.key")?;
304        let pins = Box::new(pinning::HostPins::new(self.clone(), community));
305        let keys = StayKeys::new(member_key, community, channel, me, self.now_ms(), pins)
306            .map_err(|e| Error::Voice(format!("voice keys: {e}")))?;
307        let (input, inbox) = unbounded();
308        {
309            let routes = self.voice_routes();
310            let mut map = routes.lock().unwrap_or_else(PoisonError::into_inner);
311            if map.contains_key(&community) {
312                return Err(Error::Voice(
313                    "already in a voice channel of this community; leave it first".into(),
314                ));
315            }
316            map.insert(community, input.clone());
317        }
318        let unroute = || {
319            self.voice_routes()
320                .lock()
321                .unwrap_or_else(PoisonError::into_inner)
322                .remove(&community);
323        };
324        let body = Join {
325            channel_id: Some(channel),
326            key_package: Opaque(keys.key_package()),
327            self_mute: options.self_mute,
328            self_deaf: options.self_deaf,
329        };
330        let joined: Joined = match self.command(community, Some(channel), body) {
331            Ok(j) => j,
332            Err(e) => {
333                unroute();
334                return Err(e);
335            }
336        };
337        let refuse = |text: &str| {
338            unroute();
339            let _ = self.command(community, None, Leave {});
340            Err(Error::Voice(text.into()))
341        };
342        let mut paths = match policy::decide(joined.ice_policy, options.allow_direct) {
343            Ok(p) => p,
344            Err(refusal) => return refuse(refusal.text()),
345        };
346        let mut notice = None;
347        let turn = if paths.relay {
348            match relay::servers(&joined.ice_servers) {
349                Ok(servers) => servers,
350                // The application accepted a direct path, and the host allows one.
351                Err(why) if paths.host => {
352                    paths = policy::Paths::DIRECT;
353                    notice = Some(format!("{}; using the direct path only", why.text()));
354                    Vec::new()
355                }
356                Err(why) => return refuse(why.text()),
357            }
358        } else {
359            Vec::new()
360        };
361        let tls = if turn.iter().any(|s| matches!(s.leg, relay::Leg::Tls(_))) {
362            match relay::tls_config(&options.turn_tls_roots) {
363                Ok(config) => Some(config),
364                Err(text) => return refuse(&text),
365            }
366        } else {
367            None
368        };
369        let (out, events) = bounded(EVENT_QUEUE);
370        let (cmds, cmd_rx) = unbounded();
371        let can_send = Arc::new(AtomicBool::new(false));
372        let (ready, started) = bounded(1);
373        let refused = Arc::new(AtomicU64::new(0));
374        let start = media::Start {
375            refused: Arc::clone(&refused),
376            me,
377            joined: joined.clone(),
378            keys,
379            paths,
380            turn,
381            tls,
382            notice,
383            host_ip: options.host_ip,
384            self_mute: options.self_mute,
385            self_deaf: options.self_deaf,
386            wall: {
387                let c = self.clone();
388                Box::new(move || c.now_ms())
389            },
390        };
391        let threads = match media::spawn(
392            start,
393            input.clone(),
394            inbox,
395            out.clone(),
396            cmds,
397            Arc::clone(&can_send),
398            ready,
399        ) {
400            Ok(mut t) => {
401                match worker::spawn(self.clone(), community, cmd_rx, out) {
402                    Ok(w) => t.push(w),
403                    Err(e) => {
404                        unroute();
405                        let _ = input.send(Input::Stop);
406                        let _ = self.command(community, None, Leave {});
407                        return Err(Error::Voice(format!("thread: {e}")));
408                    }
409                }
410                t
411            }
412            Err(e) => {
413                unroute();
414                let _ = self.command(community, None, Leave {});
415                return Err(Error::Voice(e));
416            }
417        };
418        let session = VoiceSession {
419            community,
420            channel: joined.channel_id,
421            session: joined.voice_session,
422            input,
423            events,
424            can_send,
425            refused,
426            client: self.clone(),
427            threads,
428            left: false,
429        };
430        let wait = media::ALLOCATE_WITHIN + Duration::from_secs(2);
431        match started.recv_timeout(wait) {
432            Ok(Ok(())) => Ok(session),
433            Ok(Err(text)) => {
434                let _ = session.leave();
435                Err(Error::Voice(text))
436            }
437            Err(_) => {
438                let _ = session.leave();
439                Err(Error::Voice("the media thread did not start".into()))
440            }
441        }
442    }
443
444    /// Server-mutes, server-deafens, moves or disconnects a member in voice
445    /// (`voice.moderate`; `MUTE_MEMBERS`, `DEAFEN_MEMBERS`, `MOVE_MEMBERS`).
446    ///
447    /// # Errors
448    /// The host refused (missing permission, rank) or did not answer.
449    pub fn moderate_voice(&self, community: CommunityId, action: Moderate) -> Result<()> {
450        self.command(community, None, action).map(|_| ())
451    }
452}