1use super::platform::{self, AudioStart, AwakeLevel, CallAudio};
8use super::share::ShareInput;
9use super::video::{Hooks, Prefs, VideoSnapshot, VideoTrack};
10use super::wire::{read_control, write_control, Control, Tracks, VideoCodec, VideoKind, CALL_ALPN};
11use crate::event_ext::FinalizeUnsignedWithId;
12use crate::rt::time::{sleep, timeout};
13use crate::rt::JoinHandle;
14use crate::state::{active_trusted_relays, my_public_key, nostr_client};
15use iroh::endpoint::{Connection, RecvStream, SendStream, VarInt};
16use iroh::EndpointAddr;
17use nostr_sdk::prelude::*;
18use serde::Serialize;
19use std::sync::atomic::Ordering;
20use std::sync::{Arc, Mutex, OnceLock};
21use std::time::Duration;
22use web_time::Instant;
23
24const OFFER_TTL_SECS: u64 = 75;
26const RING_TIMEOUT: Duration = Duration::from_secs(60);
28const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
29const PEER_SILENCE_SECS: u32 = 30;
32const AWAY_SILENCE_SECS: u32 = 90;
33const STALL_SECS: u32 = 3;
34
35#[derive(Serialize, Clone, Copy, PartialEq, Debug)]
36#[serde(rename_all = "snake_case")]
37pub enum Phase {
38 Ringing,
39 Connecting,
40 Active,
41 Ended,
42}
43
44#[derive(Serialize, Clone, Debug)]
45pub struct CallState {
46 pub id: String,
47 pub peer: String,
48 pub outgoing: bool,
49 pub phase: Phase,
50 pub reason: Option<String>,
51 pub muted: bool,
52 pub peer_muted: bool,
53 pub mic_off: bool,
55 pub volume: f32,
57 pub active_ms: u64,
59 pub video_mine: Tracks,
61 pub video_peer: Tracks,
62 pub peer_decodes: Vec<String>,
64 pub video_offered: bool,
66 pub paused_by_peer: bool,
68 pub peer_away: bool,
70 pub stalled: bool,
72 pub share_audio_mine: bool,
74 pub share_audio_peer: bool,
75 pub share_volume: f32,
77 pub share_audio_native: bool,
79 pub share_audio_denied: bool,
81 #[serde(skip)]
83 pub name: String,
84 #[serde(skip)]
85 pub avatar: Option<String>,
86}
87
88#[derive(Serialize, Clone, Debug)]
89pub struct LevelPayload {
90 pub id: String,
91 pub mic: f32,
92 pub peer: f32,
93}
94
95#[derive(Serialize, Clone, Debug)]
96pub struct CallStats {
97 pub id: String,
98 pub rtt_ms: u32,
99 pub path: &'static str,
100 pub sent: u64,
101 pub send_dropped: u64,
102 pub received: u64,
103 pub lost: u64,
104 pub shed: u64,
105 pub rebuilt: u64,
106 pub concealed: u64,
107 pub late: u64,
108 pub depth_ms: u32,
109 pub jitter_ms: u32,
110 pub clicks_cut: u64,
111 pub bitrate_kbps: u32,
112 pub net_loss: f32,
114 pub video: VideoSnapshot,
115 pub share_sent: u64,
116 pub share_received: u64,
117}
118
119struct Call {
120 id: String,
121 peer: String,
122 outgoing: bool,
123 phase: Phase,
124 conn: Option<Connection>,
125 media: Option<Box<dyn CallAudio>>,
126 control: Option<Arc<tokio::sync::Mutex<SendStream>>>,
127 tasks: Vec<JoinHandle<()>>,
128 active_since: Option<Instant>,
129 muted: bool,
130 peer_muted: bool,
131 mic_off: bool,
132 volume: f32,
133 video: Option<VideoTrack>,
134 video_mine: Tracks,
135 video_peer: Tracks,
136 peer_decodes: Vec<String>,
137 video_offered: bool,
138 paused_by_peer: bool,
139 peer_away: bool,
140 stalled: bool,
141 awake: Option<Box<dyn std::any::Any + Send>>,
143 call_audio: Option<(bool, Box<dyn std::any::Any + Send>)>,
145 shown: (String, Option<String>),
147 share: Arc<ShareInput>,
149 share_audio_mine: bool,
150 share_audio_peer: bool,
151 share_volume: f32,
152 share_audio_denied: bool,
153}
154
155fn call_audio_wanted(phase: Phase, outgoing: bool, video: bool, held: Option<bool>) -> Option<bool> {
158 match phase {
159 Phase::Ringing if !outgoing => None,
160 Phase::Ended => None,
161 _ => Some(video || held == Some(true)),
162 }
163}
164
165impl Call {
166 fn refresh_holds(&mut self) {
169 let video = self.video_mine.any() || self.video_peer.any();
170 let level = if self.phase != Phase::Active {
171 None
172 } else if video {
173 Some(AwakeLevel::Display)
174 } else {
175 Some(AwakeLevel::System)
176 };
177 let next = level.and_then(|l| platform::get().ok()?.hold_awake(l));
178 self.awake = next;
179 let held = self.call_audio.as_ref().map(|(loud, _)| *loud);
180 let audio = call_audio_wanted(self.phase, self.outgoing, self.video_offered || video, held);
181 if held != audio {
182 self.call_audio = audio.and_then(|loud| Some((loud, platform::get().ok()?.hold_call_audio(loud)?)));
183 }
184 }
185
186 fn state(&self, reason: Option<String>) -> CallState {
187 CallState {
188 id: self.id.clone(),
189 peer: self.peer.clone(),
190 outgoing: self.outgoing,
191 phase: self.phase,
192 reason,
193 muted: self.muted,
194 peer_muted: self.peer_muted,
195 mic_off: self.mic_off,
196 volume: self.volume,
197 active_ms: self.active_since.map_or(0, |t| t.elapsed().as_millis() as u64),
198 video_mine: self.video_mine,
199 video_peer: self.video_peer,
200 peer_decodes: self.peer_decodes.clone(),
201 video_offered: self.video_offered,
202 paused_by_peer: self.paused_by_peer,
203 peer_away: self.peer_away,
204 stalled: self.stalled,
205 share_audio_mine: self.share_audio_mine,
206 share_audio_peer: self.share_audio_peer,
207 share_volume: self.share_volume,
208 share_audio_native: platform::get().is_ok_and(|p| p.share_audio_native()),
209 share_audio_denied: self.share_audio_denied,
210 name: self.shown.0.clone(),
211 avatar: self.shown.1.clone(),
212 }
213 }
214}
215
216static VIDEO_CAPS: Mutex<(Vec<String>, Vec<String>)> = Mutex::new((Vec::new(), Vec::new()));
219
220pub fn set_video_caps(encode: Vec<String>, decode: Vec<String>) {
221 *VIDEO_CAPS.lock().unwrap_or_else(|e| e.into_inner()) = (encode, decode);
222}
223
224fn my_decodes() -> Vec<String> {
225 VIDEO_CAPS.lock().unwrap_or_else(|e| e.into_inner()).1.clone()
226}
227
228fn pick_codec(peer_decodes: &[String]) -> Option<VideoCodec> {
230 let mine = VIDEO_CAPS.lock().unwrap_or_else(|e| e.into_inner()).0.clone();
231 [VideoCodec::H264, VideoCodec::Vp8]
232 .into_iter()
233 .find(|c| mine.iter().any(|m| m == c.name()) && peer_decodes.iter().any(|p| p == c.name()))
234}
235
236fn parse_decodes(tag: Option<&str>) -> Vec<String> {
237 tag.unwrap_or("")
238 .split(',')
239 .filter_map(|c| VideoCodec::from_name(c.trim()).map(|c| c.name().to_string()))
240 .collect()
241}
242
243static CALL: OnceLock<Mutex<Option<Call>>> = OnceLock::new();
244
245fn slot() -> &'static Mutex<Option<Call>> {
246 CALL.get_or_init(|| Mutex::new(None))
247}
248
249static SEEN_OFFERS: Mutex<Vec<(String, u64)>> = Mutex::new(Vec::new());
252
253fn first_offer(call_id: &str, now: u64) -> bool {
255 let mut seen = SEEN_OFFERS.lock().unwrap_or_else(|e| e.into_inner());
256 seen.retain(|(_, at)| at + OFFER_TTL_SECS >= now);
257 if seen.iter().any(|(id, _)| id == call_id) {
258 return false;
259 }
260 seen.push((call_id.to_string(), now));
261 true
262}
263
264fn with_call<R>(f: impl FnOnce(&mut Call) -> R) -> Option<R> {
265 let mut guard = slot().lock().unwrap_or_else(|e| e.into_inner());
266 guard.as_mut().map(f)
267}
268
269fn with_call_id<R>(id: &str, f: impl FnOnce(&mut Call) -> R) -> Option<R> {
270 let mut guard = slot().lock().unwrap_or_else(|e| e.into_inner());
271 match guard.as_mut() {
272 Some(call) if call.id == id => Some(f(call)),
273 _ => None,
274 }
275}
276
277fn emit_state(state: &CallState) {
278 crate::traits::emit_event("call_state", state);
279 if let Some(ringer) = RINGER.get() {
280 ringer.ongoing(state);
281 }
282}
283
284pub fn snapshot() -> Option<CallState> {
285 with_call(|c| c.state(None))
286}
287
288async fn send_signal(peer: &str, call_id: &str, signal: &str, addr: Option<&str>, offer_video: bool) -> bool {
291 let Some(client) = nostr_client() else { return false };
292 let Some(me) = my_public_key() else { return false };
293 let Ok(pubkey) = PublicKey::from_bech32(peer) else { return false };
294
295 let mut builder = EventBuilder::new(Kind::ApplicationSpecificData, "call")
296 .tag(Tag::public_key(pubkey))
297 .tag(Tag::custom("d", vec!["vector-call"]))
298 .tag(Tag::custom("call-id", vec![call_id]))
299 .tag(Tag::custom("call-signal", vec![signal]));
300 if let Some(addr) = addr {
301 builder = builder.tag(Tag::custom("call-node-addr", vec![addr]));
302 }
303 if signal == "offer" {
304 builder = builder.tag(Tag::expiration(crate::clock::timestamp() + OFFER_TTL_SECS));
305 builder = builder.tag(Tag::custom("call-media", vec![if offer_video { "video" } else { "audio" }]));
306 }
307 if signal == "offer" || signal == "answer" {
308 let decodes = my_decodes();
309 if !decodes.is_empty() {
310 builder = builder.tag(Tag::custom("call-video", vec![decodes.join(",")]));
311 }
312 }
313 let rumor = builder.finalize_unsigned_with_id(me);
314 let relays = active_trusted_relays().await;
315 let (ours, inbox) = if signal == "offer" || signal == "hangup" {
318 futures_util::join!(
319 crate::send_gift_wrap(&client, relays, &pubkey, rumor.clone(), []),
320 async { crate::inbox_relays::send_gift_wrap(&client, &pubkey, rumor, []).await.map(|_| ()) },
321 )
322 } else {
323 (crate::send_gift_wrap(&client, relays, &pubkey, rumor, []).await, Err(String::new()))
324 };
325 match (ours, inbox) {
326 (Ok(_), _) | (_, Ok(())) => true,
327 (Err(e), _) => {
328 log_warn!("[CALLS] Failed to send {signal} to {peer}: {e}");
329 false
330 }
331 }
332}
333
334pub fn end(id: &str, reason: &str) {
336 if take_down(id, reason) {
337 if let Ok(p) = platform::get() {
338 p.ended();
339 }
340 }
341}
342
343pub fn end_all(reason: &str) {
345 if let Some(id) = with_call(|c| c.id.clone()) {
346 take_down(&id, reason);
347 }
348}
349
350pub trait Ringer: Send + Sync {
354 fn ring(&self, call_id: &str, peer: &str, name: &str, avatar: Option<&str>, video: bool);
356 fn over(&self, call_id: &str, missed: bool);
358 fn ongoing(&self, _state: &CallState) {}
360 fn voice(&self, _call: Option<&VoiceShown>) {}
362}
363
364pub struct VoiceShown<'a> {
366 pub channel_id: &'a str,
367 pub channel: &'a str,
368 pub community: &'a str,
369 pub muted: bool,
370 pub since_ms: u64,
371}
372
373static RINGER: std::sync::OnceLock<Box<dyn Ringer>> = std::sync::OnceLock::new();
374
375pub(super) fn ringer() -> Option<&'static dyn Ringer> {
376 RINGER.get().map(|r| &**r)
377}
378
379pub fn set_ringer(ringer: Box<dyn Ringer>) {
380 let _ = RINGER.set(ringer);
381}
382
383async fn ring(call_id: &str, peer: &str, video: bool) {
384 let Some(ringer) = RINGER.get() else { return };
385 let (name, avatar) = shown_as(peer).await;
386 ringer.ring(call_id, peer, &name, avatar.as_deref(), video);
387}
388
389async fn shown_as(peer: &str) -> (String, Option<String>) {
391 let (name, avatar) = {
392 let state = crate::STATE.lock().await;
393 match state.get_profile(peer) {
394 Some(p) => {
395 let name = [p.nickname(), p.display_name(), p.name()].into_iter().find(|n| !n.is_empty()).map(str::to_string);
396 (name, p.has_avatar_cached().then(|| p.avatar_cached().into_owned()))
397 }
398 None => (None, None),
399 }
400 };
401 (name.unwrap_or_else(|| format!("{}…", &peer[..peer.len().min(14)])), avatar)
402}
403
404fn ring_over(call_id: &str, missed: bool) {
405 if let Some(ringer) = RINGER.get() {
406 ringer.over(call_id, missed);
407 }
408}
409
410fn take_down(id: &str, reason: &str) -> bool {
411 let call = {
412 let mut guard = slot().lock().unwrap_or_else(|e| e.into_inner());
413 match guard.as_ref() {
414 Some(c) if c.id == id => guard.take(),
415 _ => None,
416 }
417 };
418 let Some(mut call) = call else { return false };
419 log_info!("[CALLS] Call {} ended: {reason}", call.id);
420 ring_over(&call.id, !call.outgoing && call.phase == Phase::Ringing && matches!(reason, "missed" | "hangup"));
422 for t in call.tasks.drain(..) {
423 t.abort();
424 }
425 stop_share_audio();
428 drop(call.video.take());
429 drop(call.media.take());
430 if let Some(conn) = call.conn.take() {
431 conn.close(VarInt::from_u32(0), b"bye");
432 }
433 call.phase = Phase::Ended;
434 emit_state(&call.state(Some(reason.to_string())));
435 true
436}
437
438pub async fn start(peer: String, video: bool) -> Result<CallState, String> {
439 if PublicKey::from_bech32(&peer).is_err() {
440 return Err("Not a valid npub".into());
441 }
442 crate::transport::realtime::check()?;
443 if super::voice::snapshot().is_some() {
444 return Err("Leave the voice channel first".into());
445 }
446 let platform = platform::get()?;
447 let id = format!("{:032x}", rand::random::<u128>());
448
449 let shown = shown_as(&peer).await;
450 let state = {
453 let mut guard = slot().lock().unwrap_or_else(|e| e.into_inner());
454 if guard.is_some() {
455 return Err("Already in a call".into());
456 }
457 let mut call = Call {
458 id: id.clone(),
459 peer: peer.clone(),
460 outgoing: true,
461 phase: Phase::Ringing,
462 conn: None,
463 media: None,
464 control: None,
465 tasks: Vec::new(),
466 active_since: None,
467 muted: { let mic = super::settings::mic_state(); mic.muted || mic.deafened },
468 peer_muted: false,
469 mic_off: false,
470 volume: 1.0,
471 video: None,
472 video_mine: Tracks::default(),
473 video_peer: Tracks::default(),
474 peer_decodes: Vec::new(),
475 video_offered: video,
476 paused_by_peer: false,
477 peer_away: false,
478 stalled: false,
479 awake: None,
480 call_audio: None,
481 shown,
482 share: Arc::new(ShareInput::new()),
483 share_audio_mine: false,
484 share_audio_peer: false,
485 share_volume: 1.0,
486 share_audio_denied: false,
487 };
488 call.refresh_holds();
489 let state = call.state(None);
490 *guard = Some(call);
491 state
492 };
493 let addr = match platform.local_addr().await {
494 Ok(a) => a,
495 Err(e) => {
496 let mut guard = slot().lock().unwrap_or_else(|e| e.into_inner());
497 if guard.as_ref().is_some_and(|c| c.id == id) {
498 *guard = None;
499 }
500 return Err(e);
501 }
502 };
503 emit_state(&state);
504
505 if !send_signal(&peer, &id, "offer", Some(&addr), video).await {
506 end(&id, "send_failed");
507 return Err("Could not reach the relays".into());
508 }
509 crate::push::call_ringing(&peer, &id, video);
510 spawn_ring_timeout(id.clone(), peer, true);
511 Ok(state)
512}
513
514fn spawn_ring_timeout(id: String, peer: String, outgoing: bool) {
515 let task = crate::db::spawn_bound(async move {
516 sleep(RING_TIMEOUT).await;
517 let still_ringing = with_call_id(&id, |c| c.phase == Phase::Ringing).unwrap_or(false);
518 if !still_ringing {
519 return;
520 }
521 if outgoing {
522 send_signal(&peer, &id, "hangup", None, false).await;
523 crate::push::call_missed(&peer, &id);
524 end(&id, "no_answer");
525 } else {
526 end(&id, "missed");
527 }
528 });
529 with_call_id_push_task(task);
530}
531
532fn with_call_id_push_task(task: JoinHandle<()>) {
533 if with_call(|c| c.tasks.push(task)).is_none() {
534 }
536}
537
538pub async fn accept() -> Result<(), String> {
539 crate::transport::realtime::check()?;
540 let (id, peer) = with_call(|c| {
541 if c.outgoing || c.phase != Phase::Ringing {
542 return Err("No incoming call to accept".to_string());
543 }
544 c.phase = Phase::Connecting;
545 c.refresh_holds();
546 Ok((c.id.clone(), c.peer.clone()))
547 })
548 .unwrap_or(Err("No call".into()))?;
549 ring_over(&id, false);
550 if let Some(s) = snapshot() {
551 emit_state(&s);
552 }
553
554 let addr = match platform::get() {
555 Ok(p) => p.local_addr().await,
556 Err(e) => Err(e),
557 };
558 let addr = match addr {
559 Ok(a) => a,
560 Err(e) => {
561 end(&id, "connect_failed");
562 return Err(e);
563 }
564 };
565 if !send_signal(&peer, &id, "answer", Some(&addr), false).await {
566 end(&id, "send_failed");
567 return Err("Could not reach the relays".into());
568 }
569 let timeout_id = id.clone();
570 let task = crate::db::spawn_bound(async move {
571 sleep(CONNECT_TIMEOUT).await;
572 if with_call_id(&timeout_id, |c| c.phase == Phase::Connecting).unwrap_or(false) {
573 end(&timeout_id, "connect_failed");
574 }
575 });
576 with_call_id_push_task(task);
577 Ok(())
578}
579
580pub async fn reject() -> Result<(), String> {
581 let (id, peer) = with_call(|c| (c.id.clone(), c.peer.clone())).ok_or("No call")?;
582 send_signal(&peer, &id, "reject", None, false).await;
583 end(&id, "rejected");
584 Ok(())
585}
586
587pub async fn decline(call_id: &str, peer: &str) {
590 ring_over(call_id, false);
591 if with_call(|c| c.id == call_id).unwrap_or(false) {
592 let _ = reject().await;
593 } else {
594 send_signal(peer, call_id, "reject", None, false).await;
595 }
596}
597
598pub async fn hangup() -> Result<(), String> {
599 let (id, peer, control, unanswered) =
600 with_call(|c| (c.id.clone(), c.peer.clone(), c.control.clone(), c.outgoing && c.phase == Phase::Ringing)).ok_or("No call")?;
601 if let Some(control) = control {
602 let mut send = control.lock().await;
603 let _ = timeout(Duration::from_secs(1), write_control(&mut *send, &Control::Bye)).await;
604 }
605 end(&id, "hangup");
607 send_signal(&peer, &id, "hangup", None, false).await;
609 if unanswered {
610 crate::push::call_missed(&peer, &id);
611 }
612 Ok(())
613}
614
615pub async fn set_muted(on: bool) -> Result<(), String> {
617 let mic = super::settings::mic_state();
618 if !on && mic.deafened {
619 hear(true)?;
620 }
621 super::settings::remember_mic(super::settings::MicState { muted: on, deafened: mic.deafened && on });
622 send_muted(on).await
623}
624
625pub async fn set_deafened(on: bool) -> Result<(), String> {
627 let mic = super::settings::mic_state();
628 super::settings::remember_mic(super::settings::MicState { muted: mic.muted, deafened: on });
629 hear(!on)?;
630 send_muted(on || mic.muted).await
631}
632
633fn hear(on: bool) -> Result<(), String> {
635 with_call(|c| {
636 if let Some(m) = c.media.as_ref() {
637 m.set_volume(if on { c.volume } else { 0.0 });
638 }
639 })
640 .ok_or_else(|| "No call".to_string())
641}
642
643async fn send_muted(on: bool) -> Result<(), String> {
644 let control = with_call(|c| {
645 c.muted = on;
646 if let Some(m) = c.media.as_ref() {
647 m.set_muted(on);
648 }
649 c.control.clone()
650 })
651 .ok_or("No call")?;
652 if let Some(s) = snapshot() {
653 emit_state(&s);
654 }
655 if let Some(control) = control {
656 let mut send = control.lock().await;
657 let _ = timeout(Duration::from_secs(1), write_control(&mut *send, &Control::Mute { on })).await;
658 }
659 Ok(())
660}
661
662pub async fn set_away(on: bool) -> Result<(), String> {
664 let control = with_call(|c| c.control.clone()).ok_or("No call")?;
665 if let Some(control) = control {
666 let mut send = control.lock().await;
667 let _ = timeout(Duration::from_secs(1), write_control(&mut *send, &Control::Away { on })).await;
668 }
669 Ok(())
670}
671
672pub async fn set_volume(volume: f32) -> Result<(), String> {
674 let volume = volume.clamp(0.0, 4.0);
675 with_call(|c| {
676 c.volume = volume;
677 if let Some(m) = c.media.as_ref() {
678 m.set_volume(super::settings::heard(volume));
679 }
680 })
681 .ok_or("No call")?;
682 if let Some(s) = snapshot() {
683 emit_state(&s);
684 }
685 Ok(())
686}
687
688pub async fn set_video(kind: VideoKind, on: bool) -> Result<(), String> {
691 let tracks = with_call(|c| {
692 if c.phase != Phase::Active {
693 return Err("Not in a call".to_string());
694 }
695 let Some(track) = c.video.as_ref() else { return Err("No video track".to_string()) };
696 let tracks = c.video_mine.with(kind, on);
697 if tracks.any() {
698 let codec = pick_codec(&c.peer_decodes).ok_or("They cannot receive video")?;
699 track.set_codec(codec);
700 }
701 track.set_sending(tracks);
702 c.video_mine = tracks;
703 if !tracks.screen {
704 c.share_audio_mine = false;
705 c.share.active.store(false, Ordering::Relaxed);
706 stop_share_audio();
707 }
708 c.refresh_holds();
709 Ok((tracks, c.control.clone()))
710 })
711 .unwrap_or(Err("No call".into()))?;
712 tell_tracks(tracks).await;
713 Ok(())
714}
715
716async fn tell_tracks((tracks, control): (Tracks, Option<Arc<tokio::sync::Mutex<SendStream>>>)) {
718 let audio = with_call(|c| c.share_audio_mine).unwrap_or(false);
719 if let Some(s) = snapshot() {
720 emit_state(&s);
721 }
722 if let Some(control) = control {
723 let mut send = control.lock().await;
724 let _ = timeout(Duration::from_secs(1), write_control(&mut *send, &Control::Video { camera: tracks.camera, screen: tracks.screen, audio })).await;
725 }
726}
727
728pub async fn set_share_audio(on: bool, native: bool) -> Result<(), String> {
731 let (on, share) = with_call(|c| {
732 if c.phase != Phase::Active {
733 return Err("Not in a call".to_string());
734 }
735 Ok((on && c.video_mine.screen, Arc::clone(&c.share)))
736 })
737 .unwrap_or(Err("No call".into()))?;
738 let platform = platform::get()?;
739 if on && native {
740 if let Err(e) = platform.start_share_audio(share).await {
741 let denied = !platform.share_audio_permitted();
743 with_call(|c| c.share_audio_denied = denied);
744 if let Some(s) = snapshot() {
745 emit_state(&s);
746 }
747 return Err(if denied { "Screen recording is off for Vector in System Settings".to_string() } else { e });
748 }
749 with_call(|c| c.share_audio_denied = false);
750 } else {
751 platform.stop_share_audio().await;
752 }
753 let tracks = with_call(|c| {
754 c.share_audio_mine = on;
755 c.share.active.store(on, Ordering::Relaxed);
756 (c.video_mine, c.control.clone())
757 })
758 .ok_or("No call")?;
759 tell_tracks(tracks).await;
760 Ok(())
761}
762
763pub async fn set_share_volume(volume: f32) -> Result<(), String> {
765 let volume = volume.clamp(0.0, 4.0);
766 with_call(|c| {
767 c.share_volume = volume;
768 if let Some(m) = c.media.as_ref() {
769 m.set_share_volume(volume);
770 }
771 })
772 .ok_or("No call")?;
773 if let Some(s) = snapshot() {
774 emit_state(&s);
775 }
776 Ok(())
777}
778
779pub fn set_video_prefs(kind: VideoKind, rung: Option<usize>, fps: Option<u32>) -> Result<(), String> {
781 with_call(|c| {
782 let Some(track) = c.video.as_ref() else { return Err("No video track".to_string()) };
783 track.set_prefs(kind, Prefs { rung, fps });
784 Ok(())
785 })
786 .unwrap_or(Err("No call".into()))
787}
788
789pub async fn set_video_pause(on: bool) -> Result<(), String> {
791 let control = with_call(|c| c.control.clone()).ok_or("No call")?;
792 if let Some(control) = control {
793 let mut send = control.lock().await;
794 let _ = timeout(Duration::from_secs(1), write_control(&mut *send, &Control::VideoPause { on })).await;
795 }
796 Ok(())
797}
798
799async fn on_link_closed(id: &str) {
801 let tracks = with_call_id(id, |c| {
802 if !c.video_mine.any() {
803 return None;
804 }
805 c.video_mine = Tracks::default();
806 c.share_audio_mine = false;
807 c.share.active.store(false, Ordering::Relaxed);
808 if let Some(v) = c.video.as_ref() {
809 v.set_sending(Tracks::default());
810 }
811 c.refresh_holds();
812 Some((Tracks::default(), c.control.clone()))
813 })
814 .flatten();
815 if let Some(t) = tracks {
816 tell_tracks(t).await;
817 }
818}
819
820pub async fn restart_audio() {
824 static RESTART: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
825 let _turn = RESTART.lock().await;
826 let mut stats = None;
829 for wait in [0u64, 500, 1500, 3000] {
830 crate::rt::time::sleep(Duration::from_millis(wait)).await;
831 match reopen_audio(&mut stats).await {
832 Reopen::Done => return,
833 Reopen::Failed(e) => log_warn!("[CALLS] Could not reopen audio after a device change: {e}"),
834 }
835 }
836 if let Some(id) = with_call(|c| c.media.is_none().then(|| c.id.clone())).flatten() {
837 end(&id, "audio_failed");
838 }
839}
840
841enum Reopen {
842 Done,
843 Failed(String),
844}
845
846async fn reopen_audio(stats: &mut Option<Arc<super::stats::MediaStats>>) -> Reopen {
848 let Some((id, Some(conn))) = with_call(|c| (c.id.clone(), c.conn.clone())) else { return Reopen::Done };
849 let Ok(platform) = platform::get() else { return Reopen::Done };
850 let Some((old, muted, volume, share, share_volume)) =
852 with_call_id(&id, |c| (c.media.take(), c.muted, c.volume, Arc::clone(&c.share), c.share_volume))
853 else {
854 return Reopen::Done;
855 };
856 if let Some(m) = old.as_ref() {
859 *stats = Some(m.stats());
860 }
861 drop(old);
862 let volume = super::settings::heard(volume);
863 match platform.start_audio(conn, AudioStart { volume, share_volume, stats: stats.clone(), share }).await {
864 Ok(m) => {
865 m.set_muted(muted);
866 let mic_off = !m.has_mic();
867 if with_call_id(&id, |c| {
868 c.mic_off = mic_off;
869 c.media = Some(m);
870 })
871 .is_some()
872 {
873 log_info!("[CALLS] Audio reopened on the new default devices");
874 if let Some(s) = snapshot() {
875 emit_state(&s);
876 }
877 }
878 Reopen::Done
879 }
880 Err(e) => Reopen::Failed(e),
881 }
882}
883
884fn stop_share_audio() {
886 if let Ok(p) = platform::get() {
887 crate::db::spawn_bound(async move { p.stop_share_audio().await });
888 }
889}
890
891pub async fn on_signal(sender: &str, call_id: &str, signal: &str, node_addr: Option<&str>, created_at: u64, video: Option<&str>, media: Option<&str>) {
893 log_info!("[CALLS] {signal} from {sender} for call {call_id}");
894 let Ok(platform) = platform::get() else {
895 match signal {
897 "offer" if created_at + OFFER_TTL_SECS >= crate::clock::timestamp().as_secs() => ring(call_id, sender, media == Some("video")).await,
898 "hangup" => ring_over(call_id, true),
899 "taken" => ring_over(call_id, false),
900 _ => {}
901 }
902 return;
903 };
904 match signal {
905 "offer" => {
906 let now = crate::clock::timestamp().as_secs();
907 if created_at + OFFER_TTL_SECS < now {
908 log_info!("[CALLS] Ignoring an offer {}s old", now.saturating_sub(created_at));
909 return;
910 }
911 if node_addr.and_then(|a| platform.decode_addr(a)).is_none() {
912 log_warn!("[CALLS] Offer without a usable address");
913 return;
914 }
915 if !first_offer(call_id, now) {
916 return;
917 }
918 let shown = shown_as(sender).await;
919 let state = {
920 let mut guard = slot().lock().unwrap_or_else(|e| e.into_inner());
921 match guard.as_ref() {
922 Some(c) if c.id == call_id => return,
923 Some(_) => None,
924 None if super::voice::snapshot().is_some() => None,
926 None => {
927 let call = Call {
928 id: call_id.to_string(),
929 peer: sender.to_string(),
930 outgoing: false,
931 phase: Phase::Ringing,
932 conn: None,
933 media: None,
934 control: None,
935 tasks: Vec::new(),
936 active_since: None,
937 muted: { let mic = super::settings::mic_state(); mic.muted || mic.deafened },
938 peer_muted: false,
939 mic_off: false,
940 volume: 1.0,
941 video: None,
942 video_mine: Tracks::default(),
943 video_peer: Tracks::default(),
944 peer_decodes: parse_decodes(video),
945 video_offered: media == Some("video"),
946 paused_by_peer: false,
947 peer_away: false,
948 stalled: false,
949 awake: None,
950 call_audio: None,
951 shown,
952 share: Arc::new(ShareInput::new()),
953 share_audio_mine: false,
954 share_audio_peer: false,
955 share_volume: 1.0,
956 share_audio_denied: false,
957 };
958 let state = call.state(None);
959 *guard = Some(call);
960 Some(state)
961 }
962 }
963 };
964 match state {
965 Some(state) => {
966 emit_state(&state);
967 spawn_ring_timeout(call_id.to_string(), sender.to_string(), false);
968 ring(call_id, sender, media == Some("video")).await;
969 }
970 None => {
971 send_signal(sender, call_id, "busy", None, false).await;
972 }
973 }
974 }
975 "answer" => {
976 let Some(addr) = node_addr.and_then(|a| platform.decode_addr(a)) else {
977 log_warn!("[CALLS] Answer without a usable address");
978 return;
979 };
980 let accepted = with_call_id(call_id, |c| {
981 if c.outgoing && c.peer == sender && c.phase == Phase::Ringing {
982 c.phase = Phase::Connecting;
983 c.peer_decodes = parse_decodes(video);
984 c.refresh_holds();
985 true
986 } else {
987 false
988 }
989 })
990 .unwrap_or(false);
991 if !accepted {
992 return;
993 }
994 if let Some(s) = snapshot() {
995 emit_state(&s);
996 }
997 send_signal(sender, call_id, "taken", node_addr, false).await;
999 let id = call_id.to_string();
1000 let peer = sender.to_string();
1001 let task = crate::db::spawn_bound(async move {
1002 match connect(addr, &id).await {
1003 Ok((conn, send, recv)) => attach(&id, conn, send, recv).await,
1004 Err(e) => {
1005 log_warn!("[CALLS] Connect failed: {e}");
1006 send_signal(&peer, &id, "hangup", None, false).await;
1007 end(&id, "connect_failed");
1008 }
1009 }
1010 });
1011 with_call_id_push_task(task);
1012 }
1013 "reject" | "busy" | "hangup" => {
1014 if with_call_id(call_id, |c| c.peer == sender).unwrap_or(false) {
1015 end(call_id, signal);
1016 }
1017 }
1018 "taken" => {
1020 let ringing = with_call_id(call_id, |c| c.peer == sender && !c.outgoing && c.phase == Phase::Ringing).unwrap_or(false);
1021 if ringing {
1022 end(call_id, "answered_elsewhere");
1023 }
1024 }
1025 other => log_warn!("[CALLS] Unknown signal {other}"),
1026 }
1027}
1028
1029async fn connect(addr: EndpointAddr, call_id: &str) -> Result<(Connection, SendStream, RecvStream), String> {
1030 let endpoint = platform::get()?.endpoint().await?;
1031 let conn = timeout(CONNECT_TIMEOUT, endpoint.connect(addr, CALL_ALPN))
1032 .await
1033 .map_err(|_| "connect timed out".to_string())?
1034 .map_err(|e| e.to_string())?;
1035 let (mut send, recv) = conn.open_bi().await.map_err(|e| e.to_string())?;
1036 write_control(&mut send, &Control::Hello { call_id: call_id.to_string() }).await?;
1037 Ok((conn, send, recv))
1038}
1039
1040pub async fn on_incoming(conn: Connection) {
1043 let handshake = timeout(Duration::from_secs(10), async {
1044 let (send, mut recv) = conn.accept_bi().await.map_err(|e| e.to_string())?;
1045 let hello = read_control(&mut recv).await?;
1046 Ok::<_, String>((send, recv, hello))
1047 })
1048 .await;
1049 let (send, recv, hello) = match handshake {
1050 Ok(Ok(v)) => v,
1051 Ok(Err(e)) => {
1052 log_warn!("[CALLS] Incoming connection without a Hello: {e}");
1053 conn.close(VarInt::from_u32(1), b"no hello");
1054 return;
1055 }
1056 Err(_) => {
1057 conn.close(VarInt::from_u32(1), b"hello timeout");
1058 return;
1059 }
1060 };
1061 let Control::Hello { call_id } = hello else {
1062 conn.close(VarInt::from_u32(1), b"expected hello");
1063 return;
1064 };
1065 let waiting = with_call_id(&call_id, |c| !c.outgoing && c.phase == Phase::Connecting).unwrap_or(false);
1066 if !waiting {
1067 log_warn!("[CALLS] Connection for call {call_id} that is not waiting");
1068 conn.close(VarInt::from_u32(2), b"not expected");
1069 return;
1070 }
1071 attach(&call_id, conn, send, recv).await;
1072}
1073
1074async fn attach(id: &str, conn: Connection, send: SendStream, mut recv: RecvStream) {
1076 let platform = match platform::get() {
1077 Ok(p) => p,
1078 Err(_) => {
1079 conn.close(VarInt::from_u32(3), b"no audio");
1080 end(id, "audio_failed");
1081 return;
1082 }
1083 };
1084 let (volume, share, share_volume) = with_call_id(id, |c| (c.volume, Arc::clone(&c.share), c.share_volume)).unwrap_or((1.0, Arc::new(ShareInput::new()), 1.0));
1085 let start = AudioStart { volume: super::settings::heard(volume), share_volume, stats: None, share: Arc::clone(&share) };
1086 let media = match platform.start_audio(conn.clone(), start).await {
1087 Ok(m) => m,
1088 Err(e) => {
1089 log_warn!("[CALLS] Media failed: {e}");
1090 let peer = with_call_id(id, |c| c.peer.clone());
1091 if let Some(peer) = peer {
1092 send_signal(&peer, id, "hangup", None, false).await;
1093 }
1094 conn.close(VarInt::from_u32(3), b"no audio");
1095 end(id, "audio_failed");
1096 return;
1097 }
1098 };
1099 let muted = with_call_id(id, |c| c.muted).unwrap_or(false);
1100 media.set_muted(muted);
1101 let control = Arc::new(tokio::sync::Mutex::new(send));
1102 let stats = media.stats();
1103
1104 let peer_video = with_call_id(id, |c| !c.peer_decodes.is_empty()).unwrap_or(false);
1105 let video = VideoTrack::start(
1106 conn.clone(),
1107 Hooks {
1108 call_id: id.to_string(),
1109 control: Arc::clone(&control),
1110 on_link_closed: Arc::new(|id: &str| {
1111 let id = id.to_string();
1112 crate::db::spawn_bound(async move { on_link_closed(&id).await });
1113 }),
1114 on_caps: Arc::new(set_video_caps),
1115 audio: Arc::clone(&stats),
1116 peer_video,
1117 share,
1118 },
1119 platform,
1120 );
1121 let mic_off = !media.has_mic();
1122 let installed = with_call_id(id, |c| {
1123 c.conn = Some(conn.clone());
1124 c.mic_off = mic_off;
1125 c.media = Some(media);
1126 c.control = Some(Arc::clone(&control));
1127 c.video = Some(video);
1128 c.phase = Phase::Active;
1129 c.active_since = Some(Instant::now());
1130 c.refresh_holds();
1131 })
1132 .is_some();
1133 if !installed {
1134 conn.close(VarInt::from_u32(0), b"gone");
1135 return;
1136 }
1137 if let Some(s) = snapshot() {
1138 emit_state(&s);
1139 }
1140
1141 let ctl_id = id.to_string();
1143 let ctl = crate::db::spawn_bound(async move {
1144 loop {
1145 match read_control(&mut recv).await {
1146 Ok(Control::Mute { on }) => {
1147 with_call_id(&ctl_id, |c| c.peer_muted = on);
1148 if let Some(s) = snapshot() {
1149 emit_state(&s);
1150 }
1151 }
1152 Ok(Control::Bye) => {
1153 end(&ctl_id, "hangup");
1154 break;
1155 }
1156 Ok(Control::Video { camera, screen, audio }) => {
1157 let tracks = Tracks { camera, screen };
1158 with_call_id(&ctl_id, |c| {
1159 c.video_peer = tracks;
1160 c.share_audio_peer = audio && screen;
1161 if let Some(v) = c.video.as_ref() {
1162 v.set_peer(tracks);
1163 }
1164 c.refresh_holds();
1165 });
1166 if let Some(s) = snapshot() {
1167 emit_state(&s);
1168 }
1169 }
1170 Ok(Control::KeyframeRequest { kind }) => {
1171 with_call_id(&ctl_id, |c| {
1172 if let Some(v) = c.video.as_ref() {
1173 v.force_keyframe(kind);
1174 }
1175 });
1176 }
1177 Ok(Control::Away { on }) => {
1178 with_call_id(&ctl_id, |c| c.peer_away = on);
1179 if let Some(s) = snapshot() {
1180 emit_state(&s);
1181 }
1182 }
1183 Ok(Control::VideoPause { on }) => {
1184 with_call_id(&ctl_id, |c| {
1185 c.paused_by_peer = on;
1186 if let Some(v) = c.video.as_ref() {
1187 v.set_paused(on);
1188 }
1189 });
1190 if let Some(s) = snapshot() {
1191 emit_state(&s);
1192 }
1193 }
1194 Ok(Control::VideoUnsupported { codec }) => {
1195 let repick = with_call_id(&ctl_id, |c| {
1197 c.peer_decodes.retain(|d| d != codec.name());
1198 if !c.video_mine.any() {
1199 return None;
1200 }
1201 match (pick_codec(&c.peer_decodes), c.video.as_ref()) {
1202 (Some(next), Some(track)) => {
1203 track.set_codec(next);
1204 Some(true)
1205 }
1206 _ => Some(false),
1207 }
1208 })
1209 .flatten();
1210 if repick == Some(false) {
1211 log_warn!("[CALLS] Peer cannot decode any codec we encode");
1212 let _ = set_video(VideoKind::Camera, false).await;
1213 let _ = set_video(VideoKind::Screen, false).await;
1214 crate::traits::emit_event("call_video_refused", &serde_json::json!({ "id": ctl_id }));
1215 }
1216 }
1217 Ok(Control::Hello { .. }) | Ok(Control::Unknown) => {}
1218 Err(_) => break,
1219 }
1220 }
1221 });
1222 let closed_id = id.to_string();
1224 let closed_conn = conn.clone();
1225 let closed = crate::db::spawn_bound(async move {
1226 let reason = match closed_conn.closed().await {
1229 iroh::endpoint::ConnectionError::ApplicationClosed(ac) if ac.reason.as_ref() == b"bye" => "hangup",
1230 _ => "disconnected",
1231 };
1232 end(&closed_id, reason);
1233 });
1234 let stats_id = id.to_string();
1237 let stats_conn = conn.clone();
1238 let stats_task = crate::db::spawn_bound(async move {
1239 let mut last_received = 0u64;
1240 let mut silent_secs = 0u32;
1241 let mut tick = 0u32;
1242 loop {
1243 sleep(Duration::from_millis(100)).await;
1244 crate::traits::emit_event("call_level", &LevelPayload {
1246 id: stats_id.clone(),
1247 mic: stats.mic_level(),
1248 peer: stats.peer_level(),
1249 });
1250 tick += 1;
1251 if !tick.is_multiple_of(10) {
1252 continue;
1253 }
1254 let received = stats.received.load(Ordering::Relaxed);
1255 silent_secs = if received == last_received { silent_secs + 1 } else { 0 };
1256 last_received = received;
1257 let away = with_call_id(&stats_id, |c| c.peer_away).unwrap_or(false);
1258 if silent_secs >= if away { AWAY_SILENCE_SECS } else { PEER_SILENCE_SECS } {
1259 end(&stats_id, "disconnected");
1260 return;
1261 }
1262 let stalled = silent_secs >= STALL_SECS;
1263 if with_call_id(&stats_id, |c| std::mem::replace(&mut c.stalled, stalled) != stalled).unwrap_or(false) {
1264 if let Some(s) = snapshot() {
1265 emit_state(&s);
1266 }
1267 }
1268 let (rtt_ms, path) = {
1269 let paths = stats_conn.paths();
1270 match paths.iter().find(|p| p.is_selected()).or_else(|| paths.iter().next()) {
1271 Some(p) => (p.rtt().as_millis() as u32, if p.is_relay() { "relay" } else { "direct" }),
1272 None => (0, "none"),
1273 }
1274 };
1275 let payload = CallStats {
1276 id: stats_id.clone(),
1277 rtt_ms,
1278 path,
1279 sent: stats.sent.load(Ordering::Relaxed),
1280 send_dropped: stats.send_dropped.load(Ordering::Relaxed),
1281 received: stats.received.load(Ordering::Relaxed),
1282 lost: stats.lost.load(Ordering::Relaxed),
1283 shed: stats.shed.load(Ordering::Relaxed),
1284 rebuilt: stats.rebuilt.load(Ordering::Relaxed),
1285 concealed: stats.concealed.load(Ordering::Relaxed),
1286 late: stats.late.load(Ordering::Relaxed),
1287 clicks_cut: stats.clicks_cut.load(Ordering::Relaxed),
1288 depth_ms: stats.depth_ms.load(Ordering::Relaxed),
1289 jitter_ms: stats.jitter_ms.load(Ordering::Relaxed),
1290 bitrate_kbps: stats.bitrate_kbps.load(Ordering::Relaxed),
1291 net_loss: stats.net_loss(),
1292 video: with_call_id(&stats_id, |c| c.video.as_ref().map(|v| v.snapshot())).flatten().unwrap_or_default(),
1293 share_sent: stats.share_sent.load(Ordering::Relaxed),
1294 share_received: stats.share_received.load(Ordering::Relaxed),
1295 };
1296 crate::traits::emit_event("call_stats", &payload);
1297 }
1298 });
1299 let mut tasks = Some(vec![ctl, closed, stats_task]);
1300 with_call_id(id, |c| c.tasks.extend(tasks.take().unwrap_or_default()));
1301 if let Some(orphans) = tasks {
1302 for t in orphans {
1303 t.abort();
1304 }
1305 end(id, "hangup");
1306 }
1307}
1308
1309#[cfg(test)]
1310mod tests {
1311 use super::*;
1312
1313 #[test]
1314 fn a_call_plays_to_the_ear_from_our_ring_and_out_loud_once_there_is_video() {
1315 assert_eq!(call_audio_wanted(Phase::Ringing, false, false, None), None);
1316 assert_eq!(call_audio_wanted(Phase::Ringing, true, false, None), Some(false));
1317 assert_eq!(call_audio_wanted(Phase::Connecting, false, false, None), Some(false));
1318 assert_eq!(call_audio_wanted(Phase::Ringing, true, true, None), Some(true));
1319 assert_eq!(call_audio_wanted(Phase::Active, false, true, Some(false)), Some(true));
1320 assert_eq!(call_audio_wanted(Phase::Active, false, false, Some(true)), Some(true));
1322 assert_eq!(call_audio_wanted(Phase::Active, false, false, Some(false)), Some(false));
1323 assert_eq!(call_audio_wanted(Phase::Ended, true, true, Some(true)), None);
1324 }
1325
1326 #[test]
1327 fn an_offer_rings_once_until_its_ttl_passes() {
1328 let id = format!("{:032x}", rand::random::<u128>());
1329 assert!(first_offer(&id, 1_000));
1330 assert!(!first_offer(&id, 1_000 + OFFER_TTL_SECS));
1331 assert!(first_offer(&format!("{id}x"), 1_000));
1332 assert!(first_offer(&id, 1_001 + OFFER_TTL_SECS));
1333 }
1334}