Skip to main content

vector_core/calls/
voice.rs

1//! A voice Channel's call (CORD-07 §8). Each join binds a fresh iroh endpoint, unlinkable across
2//! calls and relayed unless the account chose Direct, names it in presence every 30 s, and keeps a
3//! full mesh in which the lower EndpointId dials. Only an endpoint that fresh presence binds to a
4//! member who may connect is dialled or accepted, so the QUIC handshake says whose each stream is.
5
6use std::collections::{HashMap, HashSet};
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::sync::{Arc, Mutex};
9use std::time::Duration;
10
11use iroh::endpoint::{Connection, VarInt};
12use iroh::{Endpoint, EndpointAddr, RelayMode, RelayUrl, TransportAddr};
13use nostr_sdk::prelude::{PublicKey, ToBech32};
14use serde::Serialize;
15
16use super::platform::AwakeLevel;
17use crate::community::roles::Permissions;
18use crate::community::transport::LiveTransport;
19use crate::community::v2::{community::CommunityV2, voice as presence};
20use crate::community::{ChannelId, CommunityId};
21
22mod video;
23
24pub const VOICE_ALPN: &[u8] = b"concord/voice/1";
25/// Others in a call besides us: a full mesh carries voice to about fifteen (CORD-07 §8).
26pub const MAX_PEERS: usize = 14;
27const DIAL_EVERY: Duration = Duration::from_secs(3);
28const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
29/// How long an incoming connection waits for the presence that names it: whoever dials us
30/// saw our presence first, and theirs can still be crossing the relays to us.
31const PRESENCE_GRACE: Duration = Duration::from_secs(15);
32/// The spread of a room's answers to a newcomer.
33const GREET_JITTER_MS: u64 = 1500;
34const JOIN_TRIES: u32 = 3;
35
36/// A cue the call plays: who came and went, and our own mute.
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum Chime {
39    Joined,
40    Left,
41    PeerJoined,
42    PeerLeft,
43    Muted,
44    Unmuted,
45}
46
47/// What a client's media engine does with a call's peers: one capture sent to every connection,
48/// and every connection's audio mixed for playout.
49pub trait VoiceMedia: Send + Sync {
50    fn chime(&self, _cue: Chime) {}
51    fn add_peer(&self, endpoint: [u8; 32], conn: Connection);
52    fn remove_peer(&self, endpoint: &[u8; 32]);
53    fn set_muted(&self, on: bool);
54    fn set_deafened(&self, on: bool);
55    /// Whether a peer's audio plays: a member without SPEAK, or timed out, isn't heard.
56    fn set_audible(&self, _endpoint: &[u8; 32], _on: bool) {}
57    /// How loud a peer plays here, 1.0 as sent, up to 2.0.
58    fn set_volume(&self, _endpoint: &[u8; 32], _gain: f32) {}
59    /// A peer with Priority Speaker: while they talk, everyone else plays quieter.
60    fn set_priority(&self, _endpoint: &[u8; 32], _on: bool) {}
61    /// Let go of the devices now, though other holders of the engine may outlive this call.
62    fn stop(&self) {}
63    /// False when the call went ahead without a microphone: muted, whatever the switch says.
64    fn has_mic(&self) -> bool {
65        true
66    }
67    /// How loud each peer is now, 0 to 1, and our own microphone under `None`.
68    fn levels(&self) -> Vec<(Option<[u8; 32]>, f32)> {
69        Vec::new()
70    }
71    /// The engine itself, for a platform that hands its own engines back out.
72    fn as_any(&self) -> Option<&dyn std::any::Any> {
73        None
74    }
75}
76
77#[derive(Clone, Debug, Serialize, PartialEq)]
78pub struct VoicePeer {
79    pub npub: String,
80    /// Their key, hex: what their screen's frames are tagged with on the video link.
81    pub pubkey: String,
82    /// How loud they play here, as this account set it.
83    pub volume: f32,
84    pub connected: bool,
85    /// The selected path is direct, not through a relay.
86    pub direct: bool,
87    /// The selected path's round trip, 0 until there is one.
88    pub rtt_ms: u32,
89    /// How loud they are now, 0 to 1.
90    pub level: f32,
91    pub muted: bool,
92    pub deafened: bool,
93    /// A moderator muted or deafened them for this call.
94    pub server_muted: bool,
95    pub server_deafened: bool,
96    /// They are sharing their screen, or their camera.
97    pub screen: bool,
98    pub camera: bool,
99}
100
101#[derive(Clone, Debug, Serialize, PartialEq)]
102pub struct VoiceState {
103    pub community_id: String,
104    pub channel_id: String,
105    pub peers: Vec<VoicePeer>,
106    pub muted: bool,
107    pub deafened: bool,
108    /// False when no media engine runs here: in the call, but neither heard nor hearing.
109    pub audio: bool,
110    /// How loud our microphone is now, 0 to 1.
111    pub mic_level: f32,
112    /// False when there's no microphone to hear: refused access, or none there.
113    pub mic: bool,
114    /// A moderator muted or deafened us for this call.
115    pub server_muted: bool,
116    pub server_deafened: bool,
117    /// We are sharing our screen, and to how many; our camera is on.
118    pub sharing: bool,
119    pub viewers: u32,
120    pub camera: bool,
121    /// We may send a camera or a screen in this Channel.
122    pub can_video: bool,
123}
124
125struct Link {
126    author: PublicKey,
127    conn: Connection,
128}
129
130struct Voice {
131    owner: u64,
132    community: CommunityId,
133    channel: ChannelId,
134    channel_hex: String,
135    endpoint: Endpoint,
136    me: PublicKey,
137    links: Mutex<HashMap<[u8; 32], Link>>,
138    dialing: Mutex<HashSet<[u8; 32]>>,
139    /// Swapped whole when the devices change.
140    media: Mutex<Option<Arc<dyn VoiceMedia>>>,
141    muted: AtomicBool,
142    deafened: AtomicBool,
143    /// Our app is paused by its system (a locked phone): shown muted until it's back.
144    away: AtomicBool,
145    nudge: tokio::sync::Notify,
146    /// An answer to a newcomer is pending; more arrivals ride it.
147    greeting: AtomicBool,
148    /// Whether we hold Video here, as the mesh upkeep last judged it.
149    can_video: AtomicBool,
150    video: video::Video,
151    /// The machine stays awake for the call, and the display too while video shows.
152    awake: Mutex<Option<(AwakeLevel, Box<dyn std::any::Any + Send>)>>,
153    /// The sound routed as a phone call's, out loud.
154    call_audio: Mutex<Option<Box<dyn std::any::Any + Send>>>,
155    /// The channel's and community's names, and when we joined, for a phone's call notification.
156    shown: (String, String, u64),
157    tasks: Mutex<Vec<crate::rt::JoinHandle<()>>>,
158    /// The app's one call (`join`), rather than one of a bot's many (`join_also`): it follows a
159    /// move, and its mute is the account's.
160    exclusive: bool,
161}
162
163/// Every call this process is in, one per Channel. The app holds one at a time (`join` leaves the
164/// rest); a bot may hold many (`join_also`).
165static VOICE: Mutex<Vec<Arc<Voice>>> = Mutex::new(Vec::new());
166
167impl Voice {
168    fn engine(&self) -> Option<Arc<dyn VoiceMedia>> {
169        self.media.lock().unwrap_or_else(|e| e.into_inner()).clone()
170    }
171}
172
173/// This account's calls.
174fn calls() -> Vec<Arc<Voice>> {
175    let owner = crate::db::current_session().id();
176    VOICE.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|v| v.owner == owner).cloned().collect()
177}
178
179/// The call: the app is in one at most, so this is it.
180fn live() -> Option<Arc<Voice>> {
181    calls().into_iter().next()
182}
183
184/// Who an iroh endpoint in our call in `channel_hex` belongs to.
185pub fn peer_author(channel_hex: &str, endpoint: &[u8; 32]) -> Option<PublicKey> {
186    live_in(channel_hex)?.links.lock().unwrap_or_else(|e| e.into_inner()).get(endpoint).map(|l| l.author)
187}
188
189/// This account's call in `channel_hex`.
190fn live_in(channel_hex: &str) -> Option<Arc<Voice>> {
191    calls().into_iter().find(|v| v.channel_hex == channel_hex)
192}
193
194/// The media engine of this account's call in `channel_hex`, if it is in one with audio.
195pub fn media_in(channel_hex: &str) -> Option<Arc<dyn VoiceMedia>> {
196    live_in(channel_hex)?.engine()
197}
198
199/// Where a moderator moved each of a bot's calls: `from` → `to`, both channel ids.
200struct Moves;
201
202fn moves() -> Arc<Mutex<HashMap<String, String>>> {
203    crate::db::current_session().scoped::<Moves, Mutex<HashMap<String, String>>>()
204}
205
206/// Where a moderator moved the bot's call in `channel_hex`, which ended it: the channel to join
207/// to follow. Taken once.
208pub fn moved_to(channel_hex: &str) -> Option<String> {
209    moves().lock().unwrap_or_else(|e| e.into_inner()).remove(channel_hex)
210}
211
212/// Whether `v` is still a call in progress, not one taken down meanwhile.
213fn is_live(v: &Voice) -> bool {
214    VOICE.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|now| std::ptr::eq(Arc::as_ptr(now), v))
215}
216
217fn now_ms() -> u64 {
218    crate::clock::now_ms()
219}
220
221/// The lower EndpointId dials, so a pair never opens two connections.
222pub fn dials(me: &[u8; 32], them: &[u8; 32]) -> bool {
223    me < them
224}
225
226/// A relay a peer may be dialled through: iroh's defaults, or one the Community lists.
227pub fn allowed_relay(url: &RelayUrl, community: &CommunityV2) -> bool {
228    let host = |u: &RelayUrl| u.host_str().map(|h| h.trim_end_matches('.').to_ascii_lowercase());
229    let theirs = host(url);
230    theirs.is_some()
231        && iroh::defaults::prod::default_relay_map()
232            .urls::<Vec<RelayUrl>>()
233            .into_iter()
234            .chain(voice_relays(community))
235            .any(|d| host(&d) == theirs)
236}
237
238/// Whether `member` may be in this Channel's call now: not banned, and the Channel resolves
239/// View and Connect for them (CORD-07 §1: Connect is holding its key).
240pub fn may_connect(community: &CommunityV2, channel: &ChannelId, member: &PublicKey) -> bool {
241    let cid = crate::simd::hex::bytes_to_hex_32(&community.id().0);
242    let chan = crate::simd::hex::bytes_to_hex_32(&channel.0);
243    let hex = member.to_hex();
244    if crate::db::community::get_community_banlist(&cid).unwrap_or_default().contains(&hex) {
245        return false;
246    }
247    let Some(ch) = community.channel(channel) else { return false };
248    let owner = community.owner().ok().map(|o| o.to_hex());
249    let roster = crate::db::community::get_community_roles(&cid).unwrap_or_default();
250    if roster.everyone.is_none() {
251        return !ch.private || roster.is_entitled(owner.as_deref(), &hex, &chan, &[], &[]);
252    }
253    roster.channel_permissions(owner.as_deref(), &hex, &chan, ch.private).contains(Permissions::VIEW_CHANNEL | Permissions::CONNECT)
254}
255
256/// Whether `member` is heard: Speak, not under a Timeout, and not muted or deafened by a moderator.
257/// The original roles carry no voice bits, but a Timeout and a moderator's mute hold there too.
258pub fn may_speak(community: &CommunityV2, channel: &ChannelId, member: &PublicKey) -> bool {
259    let cid = crate::simd::hex::bytes_to_hex_32(&community.id().0);
260    let chan = crate::simd::hex::bytes_to_hex_32(&channel.0);
261    let hex = member.to_hex();
262    let timed_out = crate::community::v2::service::community_timeouts(community).is_ok_and(|t| t.contains_key(member));
263    let (server_muted, server_deafened) = presence::server_state(&chan, member);
264    if timed_out || server_muted || server_deafened {
265        return false;
266    }
267    let owner = community.owner().ok().map(|o| o.to_hex());
268    let roster = crate::db::community::get_community_roles(&cid).unwrap_or_default();
269    roster.everyone.is_none() || roster.channel_permissions(owner.as_deref(), &hex, &chan, community.channel(channel).is_some_and(|c| c.private)).contains(Permissions::SPEAK)
270}
271
272/// Whether `member` holds `bit` in this Channel; on the original roles, nobody holds the voice bits.
273fn has_bit(community: &CommunityV2, channel: &ChannelId, member: &PublicKey, bit: u64) -> bool {
274    let cid = crate::simd::hex::bytes_to_hex_32(&community.id().0);
275    let chan = crate::simd::hex::bytes_to_hex_32(&channel.0);
276    let owner = community.owner().ok().map(|o| o.to_hex());
277    let roster = crate::db::community::get_community_roles(&cid).unwrap_or_default();
278    roster.everyone.is_some() && roster.channel_permissions(owner.as_deref(), &member.to_hex(), &chan, community.channel(channel).is_some_and(|c| c.private)).contains(bit)
279}
280
281/// Whether `member`'s camera or screen is shown: Video, and not under a Timeout (CORD-07 §7).
282pub fn may_video(community: &CommunityV2, channel: &ChannelId, member: &PublicKey) -> bool {
283    if crate::community::v2::service::community_timeouts(community).is_ok_and(|t| t.contains_key(member)) {
284        return false;
285    }
286    let cid = crate::simd::hex::bytes_to_hex_32(&community.id().0);
287    let chan = crate::simd::hex::bytes_to_hex_32(&channel.0);
288    let owner = community.owner().ok().map(|o| o.to_hex());
289    let roster = crate::db::community::get_community_roles(&cid).unwrap_or_default();
290    roster.everyone.is_none() || roster.channel_permissions(owner.as_deref(), &member.to_hex(), &chan, community.channel(channel).is_some_and(|c| c.private)).contains(Permissions::VIDEO)
291}
292
293fn voice_relays(community: &CommunityV2) -> Vec<RelayUrl> {
294    community.voice_relays().iter().filter_map(|u| u.parse().ok()).collect()
295}
296
297async fn bind(community: &CommunityV2) -> Result<Endpoint, String> {
298    struct Voice(RelayMode);
299    impl iroh::endpoint::presets::Preset for Voice {
300        fn apply(self, builder: iroh::endpoint::Builder) -> iroh::endpoint::Builder {
301            builder.relay_mode(self.0).crypto_provider(Arc::new(rustls::crypto::ring::default_provider()))
302        }
303    }
304    let relays = voice_relays(community);
305    #[cfg(not(target_arch = "wasm32"))]
306    let mode = if relays.is_empty() { RelayMode::Default } else { RelayMode::Custom(relays.into_iter().collect()) };
307    #[cfg(target_arch = "wasm32")]
308    let mode = {
309        let urls = if relays.is_empty() { iroh::defaults::prod::default_relay_map().urls::<Vec<RelayUrl>>() } else { relays };
310        RelayMode::Custom(urls.iter().map(browser_relay).collect())
311    };
312    let transport = iroh::endpoint::QuicTransportConfig::builder()
313        .keep_alive_interval(Duration::from_secs(5))
314        .max_idle_timeout(Some(Duration::from_secs(30).try_into().map_err(|e| format!("{e}"))?))
315        .send_observed_address_reports(false)
316        .receive_observed_address_reports(false)
317        .stream_receive_window(VarInt::from_u32(512 * 1024))
318        .receive_window(VarInt::from_u32(2 * 1024 * 1024))
319        .max_concurrent_uni_streams(VarInt::from_u32(256))
320        .build();
321    let builder = Endpoint::builder(Voice(mode)).alpns(vec![VOICE_ALPN.to_vec()]).transport_config(transport);
322    #[cfg(not(target_arch = "wasm32"))]
323    let builder = if crate::transport::realtime::direct() { builder } else { builder.clear_ip_transports() };
324    let endpoint = builder.bind().await.map_err(|e| format!("Voice unavailable: {e}"))?;
325    let _ = crate::rt::time::timeout(Duration::from_secs(8), endpoint.online()).await;
326    Ok(endpoint)
327}
328
329/// A relay as a browser can dial it: WebKit refuses a WebSocket to a fully qualified host, and
330/// iroh spells its relays with the trailing dot. `xdc::wire::browser_relay` is the mesh's twin.
331#[cfg(target_arch = "wasm32")]
332fn browser_relay(url: &RelayUrl) -> RelayUrl {
333    let mut u = (**url).clone();
334    if let Some(host) = u.host_str().and_then(|h| h.strip_suffix('.')).map(str::to_string) {
335        let _ = u.set_host(Some(&host));
336    }
337    RelayUrl::from(u)
338}
339
340fn relay_of(endpoint: &Endpoint) -> Option<String> {
341    endpoint.addr().addrs.iter().find_map(|a| match a {
342        TransportAddr::Relay(u) => Some(u.to_string()),
343        _ => None,
344    })
345}
346
347fn held(community: &CommunityId) -> Result<CommunityV2, String> {
348    crate::db::community::load_community_v2(community)?.ok_or_else(|| "Community not found".to_string())
349}
350
351async fn announce(v: &Voice, joined: bool) -> Result<(), String> {
352    let community = held(&v.community)?;
353    let transport = LiveTransport::with_timeout(Duration::from_secs(12));
354    let endpoint = joined.then(|| (*v.endpoint.id().as_bytes(), relay_of(&v.endpoint)));
355    crate::community::v2::service::send_voice_presence(&transport, &community, &v.channel, endpoint, showing(v)).await
356}
357
358/// What our presence shows of us now.
359fn showing(v: &Voice) -> presence::Showing {
360    let sending = v.video.sending();
361    presence::Showing {
362        muted: v.muted.load(Ordering::SeqCst) || v.away.load(Ordering::SeqCst) || v.engine().is_none_or(|m| !m.has_mic()),
363        deafened: v.deafened.load(Ordering::SeqCst),
364        screen: sending.screen,
365        camera: sending.camera,
366    }
367}
368
369/// Join a voice Channel's call, leaving any other first.
370pub async fn join(community_id: &str, channel_id: &str) -> Result<VoiceState, String> {
371    join_with(community_id, channel_id, true).await
372}
373
374/// Join a voice Channel's call and stay in every other: a bot can be in many at once. Only a
375/// call already in this Channel is left first.
376pub async fn join_also(community_id: &str, channel_id: &str) -> Result<VoiceState, String> {
377    join_with(community_id, channel_id, false).await
378}
379
380async fn join_with(community_id: &str, channel_id: &str, alone: bool) -> Result<VoiceState, String> {
381    crate::transport::realtime::check()?;
382    if super::session::snapshot().is_some() {
383        return Err("End your call first".into());
384    }
385    if alone {
386        leave().await;
387    } else {
388        leave_channel(&channel_id.to_ascii_lowercase()).await;
389    }
390    let me = crate::state::my_public_key().ok_or("Not signed in")?;
391    let cid = CommunityId(crate::community::id32_from_hex(community_id).ok_or("bad community id")?);
392    let channel = ChannelId(crate::community::id32_from_hex(channel_id).ok_or("bad channel id")?);
393    let community = held(&cid)?;
394    let ch = community.channel(&channel).ok_or("No such channel")?;
395    if ch.view() != crate::community::v2::community::ChannelView::Voice {
396        return Err("That isn't a voice channel".into());
397    }
398    if ch.private && ch.key.is_none() {
399        return Err("This channel's key hasn't arrived yet".into());
400    }
401    if !may_connect(&community, &channel, &me) {
402        return Err("You can't connect to this channel".into());
403    }
404    let endpoint = bind(&community).await?;
405    crate::log_info!("[voice] joined via {}", relay_of(&endpoint).as_deref().unwrap_or("no relay yet"));
406    let call_audio = super::platform::get().ok().and_then(|p| p.hold_call_audio(true));
407    let media = match super::platform::get() {
408        Ok(p) => match p.start_voice().await {
409            Ok(m) => Some(m),
410            Err(e) => {
411                crate::log_warn!("[voice] in the call without audio: {e}");
412                None
413            }
414        },
415        Err(_) => None,
416    };
417    // As the app's member left them, so a muted member never sends a moment on arrival; a bot's
418    // calls each start open.
419    let mic = if alone { super::settings::mic_state() } else { super::settings::MicState::default() };
420    let v = Arc::new(Voice {
421        owner: crate::db::current_session().id(),
422        community: cid,
423        channel,
424        channel_hex: crate::simd::hex::bytes_to_hex_32(&channel.0),
425        endpoint,
426        me,
427        links: Mutex::new(HashMap::new()),
428        dialing: Mutex::new(HashSet::new()),
429        media: Mutex::new(media.map(Arc::from)),
430        muted: AtomicBool::new(mic.muted),
431        deafened: AtomicBool::new(mic.deafened),
432        away: AtomicBool::new(false),
433        nudge: tokio::sync::Notify::new(),
434        greeting: AtomicBool::new(false),
435        can_video: AtomicBool::new(may_video(&community, &channel, &me)),
436        video: video::Video::default(),
437        awake: Mutex::new(None),
438        call_audio: Mutex::new(call_audio),
439        shown: (ch.name.clone(), community.name.clone(), now_ms()),
440        tasks: Mutex::new(Vec::new()),
441        exclusive: alone,
442    });
443    // Just after launch the relays may still be connecting: a refused first presence is retried.
444    let mut tries = 0;
445    while let Err(e) = announce(&v, true).await {
446        tries += 1;
447        if tries >= JOIN_TRIES {
448            v.endpoint.close().await;
449            return Err(e);
450        }
451        crate::rt::time::sleep(Duration::from_millis(1500)).await;
452    }
453    // A join that raced this one installed its call meanwhile: that call goes, not just its slot.
454    let raced: Vec<Arc<Voice>> = {
455        let mut all = VOICE.lock().unwrap_or_else(|e| e.into_inner());
456        let (gone, kept): (Vec<_>, Vec<_>) = all.drain(..).partition(|o| alone || o.channel_hex == v.channel_hex);
457        *all = kept;
458        all.push(v.clone());
459        gone
460    };
461    for old in raced {
462        crate::db::spawn_bound(shutdown(old));
463    }
464    if let Some(m) = v.engine() {
465        apply_to(&v, &*m);
466        m.chime(Chime::Joined);
467    }
468    let mut tasks = vec![
469        crate::db::spawn_bound(levels(v.clone())),
470        crate::db::spawn_bound(heartbeat(v.clone())),
471        crate::db::spawn_bound(dialer(v.clone())),
472        crate::db::spawn_bound(acceptor(v.clone())),
473    ];
474    tasks.extend(video::start(&v));
475    *v.tasks.lock().unwrap_or_else(|e| e.into_inner()) = tasks;
476    changed(&v);
477    Ok(state(&v))
478}
479
480/// Leave every call: a `left` is best-effort, staleness heals a missed one.
481pub async fn leave() {
482    let all: Vec<Arc<Voice>> = VOICE.lock().unwrap_or_else(|e| e.into_inner()).drain(..).collect();
483    if all.is_empty() {
484        return;
485    }
486    if let Some(ringer) = super::session::ringer() {
487        ringer.voice(None);
488    }
489    for v in all {
490        shutdown(v).await;
491    }
492    crate::emit_event("voice_state", &serde_json::Value::Null);
493}
494
495/// Leave the call in `channel_hex`, if in one, and stay in any other.
496pub async fn leave_channel(channel_hex: &str) {
497    let owner = crate::db::current_session().id();
498    let gone: Vec<Arc<Voice>> = {
499        let mut all = VOICE.lock().unwrap_or_else(|e| e.into_inner());
500        let (gone, kept): (Vec<_>, Vec<_>) = all.drain(..).partition(|v| v.channel_hex == channel_hex && v.owner == owner);
501        *all = kept;
502        gone
503    };
504    if gone.is_empty() {
505        return;
506    }
507    for v in gone {
508        shutdown(v).await;
509    }
510    // Read after: a join that installed during the shutdown keeps its notification.
511    if VOICE.lock().unwrap_or_else(|e| e.into_inner()).is_empty() {
512        if let Some(ringer) = super::session::ringer() {
513            ringer.voice(None);
514        }
515        crate::emit_event("voice_state", &serde_json::Value::Null);
516    }
517}
518
519/// Take a call down: its tasks, its links, its devices, a `left`, its endpoint.
520async fn shutdown(v: Arc<Voice>) {
521    if let Some(m) = v.engine() {
522        m.chime(Chime::Left);
523    }
524    for t in v.tasks.lock().unwrap_or_else(|e| e.into_inner()).drain(..) {
525        t.abort();
526    }
527    video::stop(&v);
528    for (id, link) in v.links.lock().unwrap_or_else(|e| e.into_inner()).drain() {
529        link.conn.close(0u32.into(), b"left");
530        if let Some(m) = v.engine() {
531            m.remove_peer(&id);
532        }
533    }
534    // The microphone closes now, not when the last task holding the session lets go.
535    let engine = v.media.lock().unwrap_or_else(|e| e.into_inner()).take();
536    if let Some(engine) = engine {
537        engine.stop();
538    }
539    v.call_audio.lock().unwrap_or_else(|e| e.into_inner()).take();
540    let _ = announce(&v, false).await;
541    v.endpoint.close().await;
542    v.awake.lock().unwrap_or_else(|e| e.into_inner()).take();
543}
544
545/// Start or stop sending our camera or screen to whoever watches (CORD-07 §6). Video is judged
546/// by every receiver; we refuse here too, so a member without it isn't left sending to no one.
547pub fn set_video(kind: crate::calls::wire::VideoKind, on: bool) -> Result<(), String> {
548    let v = live().ok_or("Not in a call")?;
549    if on && !may_video(&held(&v.community)?, &v.channel, &v.me) {
550        return Err("You can't share video in this channel".into());
551    }
552    video::set_sending(&v, kind, on)?;
553    reannounce(&v);
554    changed(&v);
555    Ok(())
556}
557
558/// Which of a member's pictures we show in our call; neither stops them coming.
559pub fn watch(member: &PublicKey, want: crate::calls::wire::Tracks) -> Result<(), String> {
560    let v = live().ok_or("Not in a call")?;
561    video::watch(&v, member, want)?;
562    refresh_awake(&v);
563    Ok(())
564}
565
566/// A moderator's directive, already judged: one aimed at us is obeyed, and anyone else's mute
567/// changes who is heard.
568pub fn on_directive(channel_hex: &str, target: &PublicKey, directive: presence::Directive, to: Option<[u8; 32]>) {
569    use presence::Directive;
570    let Some(v) = live_in(channel_hex) else { return };
571    if *target != v.me {
572        v.nudge.notify_one();
573        changed(&v);
574        return;
575    }
576    match directive {
577        Directive::Mute | Directive::Unmute | Directive::Deafen | Directive::Undeafen => {
578            if let Some(m) = v.engine() {
579                apply_to(&v, &*m);
580                match directive {
581                    Directive::Mute | Directive::Deafen => m.chime(Chime::Muted),
582                    _ if !effective(&v).0 => m.chime(Chime::Unmuted),
583                    _ => {}
584                }
585            }
586        }
587        Directive::Disconnect => {
588            let channel = v.channel_hex.clone();
589            crate::db::spawn_bound(async move { leave_channel(&channel).await });
590            return;
591        }
592        // The app follows; a bot's call ends and says where to, so the bot decides.
593        Directive::Move => {
594            let Some(to) = to else { return };
595            let community = crate::simd::hex::bytes_to_hex_32(&v.community.0);
596            let to = crate::simd::hex::bytes_to_hex_32(&to);
597            let from = v.channel_hex.clone();
598            if !v.exclusive {
599                moves().lock().unwrap_or_else(|e| e.into_inner()).insert(from.clone(), to);
600                crate::db::spawn_bound(async move { leave_channel(&from).await });
601                return;
602            }
603            crate::db::spawn_bound(async move {
604                if let Err(e) = join(&community, &to).await {
605                    crate::log_warn!("[voice] couldn't follow a move: {e}");
606                }
607            });
608            return;
609        }
610    }
611    changed(&v);
612}
613
614/// Someone is newly reachable in our call: answer with our presence now rather than at our next
615/// heartbeat, since whichever of us has the lower id can't dial until it has our endpoint.
616pub fn greet(channel_hex: &str, author: &PublicKey) {
617    let Some(v) = live_in(channel_hex).filter(|v| v.me != *author) else { return };
618    if !crate::rt::can_spawn() || v.greeting.swap(true, Ordering::SeqCst) {
619        return;
620    }
621    crate::db::spawn_bound(async move {
622        crate::rt::time::sleep(Duration::from_millis(rand::random::<u64>() % GREET_JITTER_MS)).await;
623        v.greeting.store(false, Ordering::SeqCst);
624        if !is_live(&v) {
625            return;
626        }
627        if let Err(e) = announce(&v, true).await {
628            crate::log_warn!("[voice] answering a newcomer failed: {e}");
629        }
630    });
631}
632
633/// Someone's presence changed in a Channel: re-check the mesh if it is ours.
634pub fn nudge(channel_hex: &str) {
635    if let Some(v) = live_in(channel_hex) {
636        v.nudge.notify_one();
637    }
638}
639
640/// A member in a voice Channel's call, as every client lists them.
641#[derive(Clone, Debug, Serialize)]
642pub struct InCall {
643    pub npub: String,
644    /// Their own mute or deafen, or a moderator's.
645    pub muted: bool,
646    pub deafened: bool,
647    pub server_muted: bool,
648    pub server_deafened: bool,
649    pub screen: bool,
650    pub camera: bool,
651    /// In the call on another transport: out of reach of ours.
652    pub elsewhere: bool,
653}
654
655/// Who is in a voice Channel's call now, whether or not we are, earliest first.
656pub fn in_call(channel_hex: &str) -> Vec<InCall> {
657    presence::present(channel_hex, now_ms())
658        .into_iter()
659        .filter_map(|p| {
660            let elsewhere = p.transport.as_deref() != Some(crate::community::v2::chat::TRANSPORT_IROH);
661            Some(InCall {
662                npub: p.author.to_bech32().ok()?,
663                muted: p.muted || p.server_muted,
664                deafened: p.deafened || p.server_deafened,
665                server_muted: p.server_muted,
666                server_deafened: p.server_deafened,
667                screen: p.screen,
668                camera: p.camera,
669                elsewhere,
670            })
671        })
672        .collect()
673}
674
675/// What this account may do to a member in a voice call.
676#[derive(Clone, Copy, Debug, Default, Serialize)]
677pub struct Powers {
678    pub mute: bool,
679    pub deafen: bool,
680    #[serde(rename = "move")]
681    pub move_: bool,
682}
683
684/// Our moderation powers over `target` in `community`: never over ourselves or the owner.
685pub fn powers(community_id: &str, target: &PublicKey) -> Powers {
686    let Some(me) = crate::state::my_public_key() else { return Powers::default() };
687    let Some(id) = crate::simd::hex::hex_to_bytes_32_checked(community_id) else { return Powers::default() };
688    let Ok(Some(community)) = crate::db::community::load_community_v2(&CommunityId(id)) else { return Powers::default() };
689    let owner = community.owner().ok().map(|o| o.to_hex());
690    let roles = crate::db::community::get_community_roles(community_id).unwrap_or_default();
691    let (me, them) = (me.to_hex(), target.to_hex());
692    let can = |bit: u64| me != them && owner.as_deref() != Some(them.as_str()) && (owner.as_deref() == Some(me.as_str()) || roles.can_act_on_member(&me, owner.as_deref(), &them, bit));
693    Powers { mute: can(Permissions::MUTE_MEMBERS), deafen: can(Permissions::DEAFEN_MEMBERS), move_: can(Permissions::MOVE_MEMBERS) }
694}
695
696/// Mute, deafen, move or disconnect `target` in a voice Channel's call, as a moderator
697/// (CORD-07 §7). `to` names the Channel a move sends them to.
698pub async fn moderate(community_id: &str, channel_id: &str, target: &PublicKey, action: &str, to: Option<&str>) -> Result<(), String> {
699    let directive = presence::Directive::parse(action).ok_or("unknown action")?;
700    let id = CommunityId(crate::simd::hex::hex_to_bytes_32_checked(community_id).ok_or("bad community id")?);
701    let channel = ChannelId(crate::simd::hex::hex_to_bytes_32_checked(channel_id).ok_or("bad channel id")?);
702    let to = to.map(|t| crate::simd::hex::hex_to_bytes_32_checked(t).ok_or("bad channel id")).transpose()?;
703    let community = held(&id)?;
704    let transport = LiveTransport::with_timeout(Duration::from_secs(12));
705    crate::community::v2::service::send_voice_directive(&transport, &community, &channel, target, directive, to).await
706}
707
708pub fn snapshot() -> Option<VoiceState> {
709    live().map(|v| state(&v))
710}
711
712/// The call in `channel_hex`, if this account is in it.
713pub fn snapshot_in(channel_hex: &str) -> Option<VoiceState> {
714    live_in(channel_hex).map(|v| state(&v))
715}
716
717/// Every call this account is in.
718pub fn snapshots() -> Vec<VoiceState> {
719    calls().iter().map(|v| state(v)).collect()
720}
721
722pub fn set_muted(on: bool) -> Result<(), String> {
723    mute(&live().ok_or("Not in a call")?, on)
724}
725
726/// [`set_muted`] for the call in `channel_hex`.
727pub fn set_muted_in(channel_hex: &str, on: bool) -> Result<(), String> {
728    mute(&live_in(channel_hex).ok_or("Not in that call")?, on)
729}
730
731fn mute(v: &Arc<Voice>, on: bool) -> Result<(), String> {
732    let v = v.clone();
733    let (server_muted, server_deafened) = presence::server_state(&v.channel_hex, &v.me);
734    if !on && server_muted {
735        return Err("A moderator muted you in this call".into());
736    }
737    if !on && server_deafened {
738        return Err("A moderator deafened you in this call".into());
739    }
740    v.muted.store(on, Ordering::SeqCst);
741    if let Some(m) = v.engine() {
742        apply_to(&v, &*m);
743        m.chime(if on { Chime::Muted } else { Chime::Unmuted });
744    }
745    reannounce(&v);
746    changed(&v);
747    if v.exclusive {
748        super::settings::remember_mic(super::settings::MicState { muted: on, deafened: v.deafened.load(Ordering::SeqCst) });
749    }
750    Ok(())
751}
752
753pub fn set_deafened(on: bool) -> Result<(), String> {
754    deafen(&live().ok_or("Not in a call")?, on)
755}
756
757/// [`set_deafened`] for the call in `channel_hex`.
758pub fn set_deafened_in(channel_hex: &str, on: bool) -> Result<(), String> {
759    deafen(&live_in(channel_hex).ok_or("Not in that call")?, on)
760}
761
762fn deafen(v: &Arc<Voice>, on: bool) -> Result<(), String> {
763    let v = v.clone();
764    if !on && presence::server_state(&v.channel_hex, &v.me).1 {
765        return Err("A moderator deafened you in this call".into());
766    }
767    v.deafened.store(on, Ordering::SeqCst);
768    if let Some(m) = v.engine() {
769        apply_to(&v, &*m);
770        m.chime(if on { Chime::Muted } else { Chime::Unmuted });
771    }
772    reannounce(&v);
773    changed(&v);
774    if v.exclusive {
775        super::settings::remember_mic(super::settings::MicState { muted: v.muted.load(Ordering::SeqCst), deafened: on });
776    }
777    Ok(())
778}
779
780/// Our app is paused by its system or back: shown muted meanwhile, since nothing we say is
781/// sent; back, we announce at once and dial, as a long pause aged our presence out.
782pub fn set_away(on: bool) {
783    for v in calls() {
784        if v.away.swap(on, Ordering::SeqCst) == on && on {
785            continue;
786        }
787        reannounce(&v);
788        if !on {
789            v.nudge.notify_one();
790        }
791        changed(&v);
792    }
793}
794
795const VOLUMES_KEY: &str = "voice_volumes";
796
797struct Volumes;
798
799/// Read once per account, then kept: the state repaints five times a second.
800fn volumes() -> HashMap<String, f32> {
801    let cache = crate::db::current_session().scoped::<Volumes, Mutex<Option<HashMap<String, f32>>>>();
802    let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
803    held.get_or_insert_with(|| crate::db::get_sql_setting(VOLUMES_KEY.to_string()).ok().flatten().and_then(|j| serde_json::from_str(&j).ok()).unwrap_or_default()).clone()
804}
805
806fn store_volumes(all: HashMap<String, f32>) -> Result<(), String> {
807    crate::db::set_sql_setting(VOLUMES_KEY.to_string(), serde_json::to_string(&all).map_err(|e| e.to_string())?)?;
808    *crate::db::current_session().scoped::<Volumes, Mutex<Option<HashMap<String, f32>>>>().lock().unwrap_or_else(|e| e.into_inner()) = Some(all);
809    Ok(())
810}
811
812/// How loud `member` plays in this account's calls: 1.0 unless set.
813pub fn peer_volume(member: &PublicKey) -> f32 {
814    volumes().get(&member.to_hex()).copied().unwrap_or(1.0)
815}
816
817/// Remember how loud `member` plays, 0 to 2, and apply it to the call in progress.
818pub fn set_peer_volume(member: &PublicKey, gain: f32) -> Result<(), String> {
819    let gain = if gain.is_finite() { gain.clamp(0.0, 2.0) } else { 1.0 };
820    let mut all = volumes();
821    if (gain - 1.0).abs() < 0.01 {
822        all.remove(&member.to_hex());
823    } else {
824        all.insert(member.to_hex(), gain);
825    }
826    store_volumes(all)?;
827    for v in calls() {
828        if let Some(m) = v.engine() {
829            let ids: Vec<[u8; 32]> = v.links.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|(_, l)| l.author == *member).map(|(id, _)| *id).collect();
830            for id in ids {
831                m.set_volume(&id, gain);
832            }
833        }
834        changed(&v);
835    }
836    Ok(())
837}
838
839/// Everyone sees a mute or deafen now, not at the next heartbeat.
840fn reannounce(v: &Arc<Voice>) {
841    // Ours applies the moment it's set, so the list shows it before any relay has the announcement.
842    let at = now_ms();
843    let heard = presence::Heard::announcing(Some((*v.endpoint.id().as_bytes(), relay_of(&v.endpoint))), showing(v));
844    presence::note(&v.channel_hex, v.me, at, heard, at);
845    let v = v.clone();
846    crate::db::spawn_bound(async move {
847        // A call left meanwhile must not announce itself joined after its `left`.
848        if !is_live(&v) {
849            return;
850        }
851        if let Err(e) = announce(&v, true).await {
852            crate::log_warn!("[voice] presence update failed: {e}");
853        }
854    });
855}
856
857fn state(v: &Voice) -> VoiceState {
858    let levels = v.engine().map(|m| m.levels()).unwrap_or_default();
859    let level_of = |ep: Option<[u8; 32]>| levels.iter().find(|(e, _)| *e == ep).map_or(0.0, |(_, l)| *l);
860    // Read before the links are held: the video side takes its locks one at a time too.
861    let (sending, viewers) = (v.video.sending(), v.video.viewers());
862    let links = v.links.lock().unwrap_or_else(|e| e.into_inner());
863    let mut peers: Vec<VoicePeer> = presence::present(&v.channel_hex, now_ms())
864        .into_iter()
865        .filter(|p| p.author != v.me)
866        .map(|p| {
867            let link = p.endpoint.and_then(|ep| links.get(&ep));
868            let path = link.and_then(|l| {
869                let paths = l.conn.paths();
870                paths.iter().find(|path| path.is_selected()).map(|path| (path.is_ip(), path.rtt().as_millis() as u32))
871            });
872            VoicePeer {
873                volume: peer_volume(&p.author),
874                npub: p.author.to_bech32().unwrap_or_default(),
875                pubkey: p.author.to_hex(),
876                screen: p.screen,
877                camera: p.camera,
878                connected: link.is_some(),
879                direct: path.is_some_and(|(ip, _)| ip),
880                rtt_ms: path.map_or(0, |(_, rtt)| rtt),
881                level: if link.is_some() { level_of(p.endpoint) } else { 0.0 },
882                muted: p.muted,
883                deafened: p.deafened,
884                server_muted: p.server_muted,
885                server_deafened: p.server_deafened,
886            }
887        })
888        .collect();
889    peers.sort_by(|a, b| a.npub.cmp(&b.npub));
890    VoiceState {
891        community_id: crate::simd::hex::bytes_to_hex_32(&v.community.0),
892        channel_id: v.channel_hex.clone(),
893        peers,
894        muted: v.muted.load(Ordering::SeqCst),
895        deafened: v.deafened.load(Ordering::SeqCst),
896        audio: v.engine().is_some(),
897        mic_level: level_of(None),
898        mic: v.engine().is_some_and(|m| m.has_mic()),
899        server_muted: presence::server_state(&v.channel_hex, &v.me).0,
900        server_deafened: presence::server_state(&v.channel_hex, &v.me).1,
901        sharing: sending.screen,
902        viewers,
903        camera: sending.camera,
904        can_video: v.can_video.load(Ordering::SeqCst),
905    }
906}
907
908/// What the engine does, (mute, deafen): our own choices, or a moderator's, whichever is
909/// stricter. Deafened also means muted, as it does everywhere voice chat is.
910fn effective(v: &Voice) -> (bool, bool) {
911    stricter((v.muted.load(Ordering::SeqCst), v.deafened.load(Ordering::SeqCst)), presence::server_state(&v.channel_hex, &v.me))
912}
913
914fn stricter((muted, deafened): (bool, bool), (server_muted, server_deafened): (bool, bool)) -> (bool, bool) {
915    let deafened = deafened || server_deafened;
916    (muted || server_muted || deafened, deafened)
917}
918
919fn apply_to(v: &Voice, m: &dyn VoiceMedia) {
920    let (muted, deafened) = effective(v);
921    m.set_muted(muted);
922    m.set_deafened(deafened);
923}
924
925/// Repaint, if this is still the live call: one taken down meanwhile paints nothing.
926fn changed(v: &Voice) {
927    let state = state(v);
928    if is_live(v) {
929        refresh_awake(v);
930        crate::emit_event("voice_state", &state);
931        if let Some(ringer) = super::session::ringer() {
932            let (channel, community, since_ms) = &v.shown;
933            ringer.voice(Some(&super::session::VoiceShown { channel_id: &v.channel_hex, channel, community, muted: effective(v).0, since_ms: *since_ms }));
934        }
935    }
936}
937
938/// The hold the call needs now; the new one is taken before the old goes, so the machine is
939/// covered in between.
940fn refresh_awake(v: &Voice) {
941    let level = if v.video.any() { AwakeLevel::Display } else { AwakeLevel::System };
942    let mut slot = v.awake.lock().unwrap_or_else(|e| e.into_inner());
943    if slot.as_ref().is_some_and(|(held, _)| *held == level) {
944        return;
945    }
946    let Some(hold) = super::platform::get().ok().and_then(|p| p.hold_awake(level)) else { return };
947    *slot = Some((level, hold));
948}
949
950/// Who is speaking, five times a second while there is audio to show it.
951async fn levels(v: Arc<Voice>) {
952    loop {
953        crate::rt::time::sleep(Duration::from_millis(200)).await;
954        if v.engine().is_some() {
955            crate::emit_event("voice_levels", &state(&v));
956        }
957    }
958}
959
960/// The microphone or speaker changed: a fresh engine on the new devices, carrying every peer,
961/// their volume and whether they're heard, and our mute and deafen.
962pub async fn restart_audio() {
963    let Some(v) = live() else { return };
964    let Ok(platform) = super::platform::get() else { return };
965    // The old engine lets go of the devices before the new one opens them, though a task may
966    // still hold it for a moment.
967    let old = v.media.lock().unwrap_or_else(|e| e.into_inner()).take();
968    if let Some(old) = old {
969        old.stop();
970    }
971    let fresh: Arc<dyn VoiceMedia> = match platform.start_voice().await {
972        Ok(m) => Arc::from(m),
973        Err(e) => {
974            crate::log_warn!("[voice] audio didn't restart: {e}");
975            changed(&v);
976            return;
977        }
978    };
979    apply_to(&v, &*fresh);
980    // Installed before the peers are added: a link landing meanwhile adds itself to it too.
981    *v.media.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::clone(&fresh));
982    let community = held(&v.community).ok();
983    let links: Vec<([u8; 32], PublicKey, Connection)> = v.links.lock().unwrap_or_else(|e| e.into_inner()).iter().map(|(id, l)| (*id, l.author, l.conn.clone())).collect();
984    for (id, author, conn) in links {
985        fresh.add_peer(id, conn);
986        fresh.set_volume(&id, peer_volume(&author));
987        if let Some(c) = &community {
988            fresh.set_audible(&id, may_speak(c, &v.channel, &author));
989            fresh.set_priority(&id, has_bit(c, &v.channel, &author, Permissions::PRIORITY_SPEAKER));
990        }
991    }
992    changed(&v);
993}
994
995/// Presence every heartbeat, and at once when our home relay changes: peers dial us through it.
996async fn heartbeat(v: Arc<Voice>) {
997    use iroh::Watcher;
998    let mut addr = v.endpoint.watch_addr();
999    let mut relay = relay_of(&v.endpoint);
1000    loop {
1001        let due = web_time::Instant::now() + Duration::from_millis(presence::HEARTBEAT_MS);
1002        loop {
1003            let left = due.saturating_duration_since(web_time::Instant::now());
1004            tokio::select! {
1005                _ = crate::rt::time::sleep(left) => break,
1006                moved = addr.updated() => {
1007                    if moved.is_err() {
1008                        return;
1009                    }
1010                    if relay_of(&v.endpoint) != relay {
1011                        break;
1012                    }
1013                }
1014            }
1015        }
1016        relay = relay_of(&v.endpoint);
1017        if let Err(e) = announce(&v, true).await {
1018            crate::log_warn!("[voice] presence heartbeat failed: {e}");
1019        }
1020    }
1021}
1022
1023/// Keep the mesh what presence says: drop who left or may no longer connect, dial who we should.
1024async fn dialer(v: Arc<Voice>) {
1025    let my_id = *v.endpoint.id().as_bytes();
1026    loop {
1027        // Gone ends the upkeep; a failed read only skips this pass.
1028        let community = match crate::db::community::load_community_v2(&v.community) {
1029            Ok(Some(c)) => c,
1030            Ok(None) => return,
1031            Err(e) => {
1032                crate::log_warn!("[voice] mesh upkeep skipped a pass: {e}");
1033                crate::rt::time::sleep(DIAL_EVERY).await;
1034                continue;
1035            }
1036        };
1037        let present = presence::present(&v.channel_hex, now_ms());
1038        let linked: Vec<([u8; 32], PublicKey)> = v.links.lock().unwrap_or_else(|e| e.into_inner()).iter().map(|(id, l)| (*id, l.author)).collect();
1039        let gone: Vec<[u8; 32]> = linked
1040            .into_iter()
1041            .filter(|(id, author)| !present.iter().any(|p| p.endpoint.as_ref() == Some(id) && p.author == *author) || !may_connect(&community, &v.channel, author))
1042            .map(|(id, _)| id)
1043            .collect();
1044        for id in gone {
1045            unlink(&v, &id, b"not in this call");
1046        }
1047        if let Some(m) = v.engine() {
1048            // Judged outside the lock: every frame we send waits on it.
1049            let linked: Vec<([u8; 32], PublicKey)> = v.links.lock().unwrap_or_else(|e| e.into_inner()).iter().map(|(id, l)| (*id, l.author)).collect();
1050            for (id, author) in linked {
1051                m.set_audible(&id, may_speak(&community, &v.channel, &author));
1052                m.set_priority(&id, has_bit(&community, &v.channel, &author, Permissions::PRIORITY_SPEAKER));
1053            }
1054        }
1055        video::revalidate(&v, |author| may_video(&community, &v.channel, author));
1056        // Video lost while sending: stop, as every receiver already has.
1057        let can_video = may_video(&community, &v.channel, &v.me);
1058        if v.can_video.swap(can_video, Ordering::SeqCst) != can_video {
1059            changed(&v);
1060        }
1061        let sending = v.video.sending();
1062        if sending.any() && !can_video {
1063            for kind in [crate::calls::wire::VideoKind::Camera, crate::calls::wire::VideoKind::Screen] {
1064                let _ = video::set_sending(&v, kind, false);
1065            }
1066            reannounce(&v);
1067            changed(&v);
1068        }
1069        for p in present.iter().filter(|p| p.author != v.me) {
1070            let (Some(ep), Some(relay)) = (p.endpoint, p.relay.as_deref().and_then(|r| r.parse::<RelayUrl>().ok())) else { continue };
1071            let busy = v.links.lock().unwrap_or_else(|e| e.into_inner()).contains_key(&ep) || v.dialing.lock().unwrap_or_else(|e| e.into_inner()).contains(&ep);
1072            let full = v.links.lock().unwrap_or_else(|e| e.into_inner()).len() >= MAX_PEERS;
1073            if busy || full || !dials(&my_id, &ep) || !allowed_relay(&relay, &community) || !may_connect(&community, &v.channel, &p.author) {
1074                continue;
1075            }
1076            let Ok(id) = iroh::EndpointId::from_bytes(&ep) else { continue };
1077            v.dialing.lock().unwrap_or_else(|e| e.into_inner()).insert(ep);
1078            let (v2, author) = (v.clone(), p.author);
1079            #[cfg(target_arch = "wasm32")]
1080            let relay = browser_relay(&relay);
1081            crate::db::spawn_bound(async move {
1082                let addr = EndpointAddr { id, addrs: [TransportAddr::Relay(relay)].into_iter().collect() };
1083                match crate::rt::time::timeout(CONNECT_TIMEOUT, v2.endpoint.connect(addr, VOICE_ALPN)).await {
1084                    Ok(Ok(conn)) => link(&v2, ep, author, conn),
1085                    Ok(Err(e)) => crate::log_debug!("[voice] dial failed: {e}"),
1086                    Err(_) => crate::log_debug!("[voice] dial timed out"),
1087                }
1088                v2.dialing.lock().unwrap_or_else(|e| e.into_inner()).remove(&ep);
1089            });
1090        }
1091        changed(&v);
1092        tokio::select! {
1093            _ = crate::rt::time::sleep(DIAL_EVERY) => {}
1094            _ = v.nudge.notified() => {}
1095        }
1096    }
1097}
1098
1099async fn acceptor(v: Arc<Voice>) {
1100    let my_id = *v.endpoint.id().as_bytes();
1101    while let Some(incoming) = v.endpoint.accept().await {
1102        let v = v.clone();
1103        crate::db::spawn_bound(async move {
1104            let Ok(conn) = incoming.await else { return };
1105            let id = *conn.remote_id().as_bytes();
1106            if !dials(&id, &my_id) {
1107                conn.close(0u32.into(), b"not in this call");
1108                return;
1109            }
1110            let named = || presence::author_of(&v.channel_hex, &id, now_ms()).filter(|a| *a != v.me);
1111            let waited = crate::rt::time::timeout(PRESENCE_GRACE, async {
1112                loop {
1113                    if let Some(a) = named() {
1114                        return a;
1115                    }
1116                    crate::rt::time::sleep(Duration::from_millis(250)).await;
1117                }
1118            });
1119            let author = tokio::select! {
1120                a = waited => a.ok(),
1121                _ = conn.closed() => return,
1122            };
1123            let allowed = author.is_some_and(|a| held(&v.community).is_ok_and(|c| may_connect(&c, &v.channel, &a)));
1124            match author {
1125                Some(a) if allowed && dials(&id, &my_id) => link(&v, id, a, conn),
1126                _ => conn.close(0u32.into(), b"not in this call"),
1127            }
1128        });
1129    }
1130}
1131
1132fn link(v: &Arc<Voice>, id: [u8; 32], author: PublicKey, conn: Connection) {
1133    {
1134        let mut links = v.links.lock().unwrap_or_else(|e| e.into_inner());
1135        if links.contains_key(&id) || links.len() >= MAX_PEERS {
1136            conn.close(0u32.into(), b"already connected");
1137            return;
1138        }
1139        links.insert(id, Link { author, conn: conn.clone() });
1140    }
1141    video::on_link(v, id, author, conn.clone());
1142    if let Some(m) = v.engine() {
1143        m.add_peer(id, conn.clone());
1144        m.set_volume(&id, peer_volume(&author));
1145        m.chime(Chime::PeerJoined);
1146        if let Ok(c) = held(&v.community) {
1147            m.set_audible(&id, may_speak(&c, &v.channel, &author));
1148            m.set_priority(&id, has_bit(&c, &v.channel, &author, Permissions::PRIORITY_SPEAKER));
1149        }
1150    }
1151    let watch = v.clone();
1152    crate::db::spawn_bound(async move {
1153        conn.closed().await;
1154        let same = watch.links.lock().unwrap_or_else(|e| e.into_inner()).get(&id).is_some_and(|l| l.conn.stable_id() == conn.stable_id());
1155        if same {
1156            unlink(&watch, &id, b"closed");
1157        }
1158    });
1159    changed(v);
1160}
1161
1162fn unlink(v: &Voice, id: &[u8; 32], why: &[u8]) {
1163    // Out of the lock first: `changed` reads the links again.
1164    let removed = v.links.lock().unwrap_or_else(|e| e.into_inner()).remove(id);
1165    video::on_unlink(v, id);
1166    if let Some(l) = removed {
1167        l.conn.close(0u32.into(), why);
1168        if let Some(m) = v.engine() {
1169            m.remove_peer(id);
1170            m.chime(Chime::PeerLeft);
1171        }
1172        changed(v);
1173    }
1174}
1175
1176#[cfg(test)]
1177mod tests {
1178    use super::*;
1179
1180    #[test]
1181    fn a_moderator_lifting_their_mute_hands_back_our_own_choice() {
1182        assert_eq!(stricter((false, false), (true, false)), (true, false));
1183        assert_eq!(stricter((false, false), (false, false)), (false, false), "unmuted again once lifted");
1184        assert_eq!(stricter((true, false), (false, false)), (true, false), "our own mute outlives theirs");
1185        assert_eq!(stricter((false, true), (false, false)), (true, true), "deafened is muted too");
1186        assert_eq!(stricter((false, false), (false, true)), (true, true));
1187    }
1188
1189    #[tokio::test]
1190    async fn a_peer_dropped_from_the_call_never_blocks_on_its_own_state() {
1191        struct Offline;
1192        impl iroh::endpoint::presets::Preset for Offline {
1193            fn apply(self, b: iroh::endpoint::Builder) -> iroh::endpoint::Builder {
1194                b.relay_mode(RelayMode::Disabled).crypto_provider(Arc::new(rustls::crypto::ring::default_provider()))
1195            }
1196        }
1197        let bind = || async { Endpoint::builder(Offline).alpns(vec![VOICE_ALPN.to_vec()]).bind().await.unwrap() };
1198        let (a, b) = (bind().await, bind().await);
1199        let server = b.clone();
1200        let accepted = tokio::spawn(async move { server.accept().await.unwrap().await.unwrap() });
1201        let conn = a.connect(b.addr(), VOICE_ALPN).await.unwrap();
1202        let _held = accepted.await.unwrap();
1203        let v = Arc::new(Voice {
1204            owner: 0,
1205            community: CommunityId([0; 32]),
1206            channel: ChannelId([1; 32]),
1207            channel_hex: crate::simd::hex::bytes_to_hex_32(&[1; 32]),
1208            endpoint: a.clone(),
1209            me: nostr_sdk::prelude::Keys::generate().public_key(),
1210            links: Mutex::new(HashMap::new()),
1211            dialing: Mutex::new(HashSet::new()),
1212            media: Mutex::new(None),
1213            muted: AtomicBool::new(false),
1214            deafened: AtomicBool::new(false),
1215            away: AtomicBool::new(false),
1216            nudge: tokio::sync::Notify::new(),
1217            greeting: AtomicBool::new(false),
1218            can_video: AtomicBool::new(false),
1219            video: video::Video::default(),
1220            awake: Mutex::new(None),
1221            call_audio: Mutex::new(None),
1222            shown: Default::default(),
1223            tasks: Mutex::new(Vec::new()),
1224            exclusive: true,
1225        });
1226        let id = *b.id().as_bytes();
1227        link(&v, id, nostr_sdk::prelude::Keys::generate().public_key(), conn);
1228        assert_eq!(v.links.lock().unwrap().len(), 1);
1229        let (gone, (tx, rx)) = (v.clone(), std::sync::mpsc::channel());
1230        std::thread::spawn(move || {
1231            unlink(&gone, &id, b"left");
1232            let _ = tx.send(());
1233        });
1234        assert!(rx.recv_timeout(Duration::from_secs(5)).is_ok(), "unlinking repaints the state, which reads the links: it must not hold them");
1235        assert!(v.links.lock().unwrap().is_empty());
1236    }
1237
1238    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1239    async fn the_state_and_the_screen_fan_out_never_wait_on_each_other() {
1240        let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1241        struct Offline;
1242        impl iroh::endpoint::presets::Preset for Offline {
1243            fn apply(self, b: iroh::endpoint::Builder) -> iroh::endpoint::Builder {
1244                b.relay_mode(RelayMode::Disabled).crypto_provider(Arc::new(rustls::crypto::ring::default_provider()))
1245            }
1246        }
1247        let bind = || async { Endpoint::builder(Offline).alpns(vec![VOICE_ALPN.to_vec()]).bind().await.unwrap() };
1248        let (a, b) = (bind().await, bind().await);
1249        let server = b.clone();
1250        let accepted = tokio::spawn(async move { server.accept().await.unwrap().await.unwrap() });
1251        let conn = a.connect(b.addr(), VOICE_ALPN).await.unwrap();
1252        let _held = accepted.await.unwrap();
1253        let v = Arc::new(Voice {
1254            owner: 0,
1255            community: CommunityId([0; 32]),
1256            channel: ChannelId([2; 32]),
1257            channel_hex: crate::simd::hex::bytes_to_hex_32(&[2; 32]),
1258            endpoint: a.clone(),
1259            me: nostr_sdk::prelude::Keys::generate().public_key(),
1260            links: Mutex::new(HashMap::new()),
1261            dialing: Mutex::new(HashSet::new()),
1262            media: Mutex::new(None),
1263            muted: AtomicBool::new(false),
1264            deafened: AtomicBool::new(false),
1265            away: AtomicBool::new(false),
1266            nudge: tokio::sync::Notify::new(),
1267            greeting: AtomicBool::new(false),
1268            can_video: AtomicBool::new(false),
1269            video: video::Video::default(),
1270            awake: Mutex::new(None),
1271            call_audio: Mutex::new(None),
1272            shown: Default::default(),
1273            tasks: Mutex::new(Vec::new()),
1274            exclusive: true,
1275        });
1276        let id = *b.id().as_bytes();
1277        v.links.lock().unwrap().insert(id, Link { author: nostr_sdk::prelude::Keys::generate().public_key(), conn });
1278        v.video.add_watcher(id);
1279        v.video.set_sending_for_test(crate::calls::wire::Tracks { camera: true, screen: true });
1280        let run = |f: Box<dyn Fn() + Send>| {
1281            let (tx, rx) = std::sync::mpsc::channel();
1282            std::thread::spawn(move || {
1283                for _ in 0..20_000 {
1284                    f();
1285                }
1286                let _ = tx.send(());
1287            });
1288            rx
1289        };
1290        let (s, f) = (v.clone(), v.clone());
1291        let painted = run(Box::new(move || drop(state(&s))));
1292        let fanned = run(Box::new(move || drop(video::targets(&f, crate::calls::wire::VideoKind::Screen))));
1293        let done = painted.recv_timeout(Duration::from_secs(20)).is_ok() && fanned.recv_timeout(Duration::from_secs(20)).is_ok();
1294        assert!(done, "the state read and a frame's fan-out each take the links and the viewers: never both at once");
1295    }
1296
1297    /// A call in `channel`, as `owner`'s, with nobody linked.
1298    async fn call_in(channel: u8, owner: u64, exclusive: bool) -> Arc<Voice> {
1299        struct Offline;
1300        impl iroh::endpoint::presets::Preset for Offline {
1301            fn apply(self, b: iroh::endpoint::Builder) -> iroh::endpoint::Builder {
1302                b.relay_mode(RelayMode::Disabled).crypto_provider(Arc::new(rustls::crypto::ring::default_provider()))
1303            }
1304        }
1305        let endpoint = Endpoint::builder(Offline).alpns(vec![VOICE_ALPN.to_vec()]).bind().await.unwrap();
1306        Arc::new(Voice {
1307            owner,
1308            community: CommunityId([0; 32]),
1309            channel: ChannelId([channel; 32]),
1310            channel_hex: crate::simd::hex::bytes_to_hex_32(&[channel; 32]),
1311            endpoint,
1312            me: nostr_sdk::prelude::Keys::generate().public_key(),
1313            links: Mutex::new(HashMap::new()),
1314            dialing: Mutex::new(HashSet::new()),
1315            media: Mutex::new(None),
1316            muted: AtomicBool::new(false),
1317            deafened: AtomicBool::new(false),
1318            away: AtomicBool::new(false),
1319            nudge: tokio::sync::Notify::new(),
1320            greeting: AtomicBool::new(false),
1321            can_video: AtomicBool::new(false),
1322            video: video::Video::default(),
1323            awake: Mutex::new(None),
1324            call_audio: Mutex::new(None),
1325            shown: Default::default(),
1326            tasks: Mutex::new(Vec::new()),
1327            exclusive,
1328        })
1329    }
1330
1331    #[tokio::test]
1332    async fn a_bot_leaving_one_call_stays_in_the_rest_and_another_accounts() {
1333        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1334        let me = crate::db::current_session().id();
1335        let (a, b, theirs) = (call_in(0xA1, me, false).await, call_in(0xB2, me, false).await, call_in(0xA1, me + 1, false).await);
1336        VOICE.lock().unwrap().extend([a.clone(), b.clone(), theirs.clone()]);
1337        leave_channel(&a.channel_hex).await;
1338        let left: Vec<String> = VOICE.lock().unwrap().iter().map(|v| format!("{}:{}", &v.channel_hex[..2], v.owner - me)).collect();
1339        assert_eq!(left, vec!["b2:0", "a1:1"], "only this account's call in that channel");
1340        VOICE.lock().unwrap().clear();
1341    }
1342
1343    #[tokio::test]
1344    async fn a_bots_moved_call_ends_and_says_where_to() {
1345        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1346        let me = crate::db::current_session().id();
1347        let call = call_in(0xC3, me, false).await;
1348        VOICE.lock().unwrap().push(call.clone());
1349        on_directive(&call.channel_hex, &call.me, presence::Directive::Move, Some([0xD4; 32]));
1350        for _ in 0..100 {
1351            if live_in(&call.channel_hex).is_none() {
1352                break;
1353            }
1354            tokio::time::sleep(Duration::from_millis(20)).await;
1355        }
1356        assert!(live_in(&call.channel_hex).is_none(), "the call ended");
1357        assert!(calls().is_empty(), "and the bot joined nothing it has no handle for");
1358        assert_eq!(moved_to(&call.channel_hex), Some(crate::simd::hex::bytes_to_hex_32(&[0xD4; 32])));
1359        assert_eq!(moved_to(&call.channel_hex), None, "read once");
1360    }
1361
1362    #[test]
1363    fn of_a_pair_exactly_one_dials() {
1364        let (a, b) = ([1u8; 32], [2u8; 32]);
1365        assert!(dials(&a, &b) ^ dials(&b, &a));
1366        assert!(!dials(&a, &a), "never itself");
1367    }
1368}