1mod 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
66const EVENT_QUEUE: usize = 512;
69
70pub(crate) type Routes = Arc<Mutex<BTreeMap<CommunityId, Sender<Input>>>>;
73
74pub(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
96pub(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#[derive(Debug, Clone, Default)]
114pub struct VoiceOptions {
115 pub allow_direct: bool,
120 pub host_ip: Option<IpAddr>,
124 pub self_mute: bool,
126 pub self_deaf: bool,
128 pub turn_tls_roots: Vec<Vec<u8>>,
131}
132
133pub use stay::VoiceEvent;
134
135pub 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 refused: Arc<AtomicU64>,
145 client: Client,
146 threads: Vec<JoinHandle<()>>,
147 left: bool,
148}
149
150impl VoiceSession {
151 #[must_use]
153 pub const fn community(&self) -> CommunityId {
154 self.community
155 }
156
157 #[must_use]
159 pub const fn channel(&self) -> ChannelId {
160 self.channel
161 }
162
163 #[must_use]
165 pub const fn voice_session(&self) -> VoiceSessionId {
166 self.session
167 }
168
169 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 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 pub fn unsubscribe(&self, player: &AudioPlayer) {
196 player.unsubscribe(self.session);
197 }
198
199 #[must_use]
203 pub fn frames_refused(&self) -> u64 {
204 self.refused.load(Ordering::Relaxed)
205 }
206
207 #[must_use]
209 pub fn can_send(&self) -> bool {
210 self.can_send.load(Ordering::Relaxed)
211 }
212
213 #[must_use]
215 pub fn next_event(&self, timeout: Duration) -> Option<VoiceEvent> {
216 self.events.recv_timeout(timeout).ok()
217 }
218
219 pub fn events(&self) -> impl Iterator<Item = VoiceEvent> + Send + 'static {
221 self.events.clone().into_iter()
222 }
223
224 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 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 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 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 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 pub fn moderate_voice(&self, community: CommunityId, action: Moderate) -> Result<()> {
450 self.command(community, None, action).map(|_| ())
451 }
452}