vector-core 0.13.0

Core library for Vector: the single source of truth for all Vector clients, SDKs and interfaces.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
//! One call at a time: the state machine, its signalling over gift-wrapped rumors,
//! and the Iroh connection that carries the media once both sides have agreed.
//!
//! Every deferred step (a ring timeout, a connect, a closed watcher) carries the
//! call id it was started for and does nothing if the call it finds is another.

use super::platform::{self, AudioStart, AwakeLevel, CallAudio};
use super::share::ShareInput;
use super::video::{Hooks, Prefs, VideoSnapshot, VideoTrack};
use super::wire::{read_control, write_control, Control, Tracks, VideoCodec, VideoKind, CALL_ALPN};
use crate::event_ext::FinalizeUnsignedWithId;
use crate::rt::time::{sleep, timeout};
use crate::rt::JoinHandle;
use crate::state::{active_trusted_relays, my_public_key, nostr_client};
use iroh::endpoint::{Connection, RecvStream, SendStream, VarInt};
use iroh::EndpointAddr;
use nostr_sdk::prelude::*;
use serde::Serialize;
use std::sync::atomic::Ordering;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
use web_time::Instant;

/// An offer older than this never rings: it was a call that already ended.
const OFFER_TTL_SECS: u64 = 75;
/// Long enough to answer from a notification on a phone the call woke.
const RING_TIMEOUT: Duration = Duration::from_secs(60);
const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
/// A peer silent this long is gone; one that said it went away gets [`AWAY_SILENCE_SECS`],
/// under the transport's own idle timeout. Past [`STALL_SECS`] the call shows as reconnecting.
const PEER_SILENCE_SECS: u32 = 30;
const AWAY_SILENCE_SECS: u32 = 90;
const STALL_SECS: u32 = 3;

#[derive(Serialize, Clone, Copy, PartialEq, Debug)]
#[serde(rename_all = "snake_case")]
pub enum Phase {
    Ringing,
    Connecting,
    Active,
    Ended,
}

#[derive(Serialize, Clone, Debug)]
pub struct CallState {
    pub id: String,
    pub peer: String,
    pub outgoing: bool,
    pub phase: Phase,
    pub reason: Option<String>,
    pub muted: bool,
    pub peer_muted: bool,
    /// The call has no microphone (access refused, or none there): it stays muted.
    pub mic_off: bool,
    /// Listener-side volume, 1.0 is unity.
    pub volume: f32,
    /// Milliseconds since the call went active; 0 before that.
    pub active_ms: u64,
    /// What I am sending on video, and what the peer is: either, both or neither.
    pub video_mine: Tracks,
    pub video_peer: Tracks,
    /// Codecs the peer can decode, from their offer or answer; empty means no video.
    pub peer_decodes: Vec<String>,
    /// The offer asked for a video call.
    pub video_offered: bool,
    /// The peer has hidden our picture; the camera can rest.
    pub paused_by_peer: bool,
    /// The peer's app is paused by their system; the call waits for it.
    pub peer_away: bool,
    /// Nothing has arrived from the peer for a few seconds.
    pub stalled: bool,
    /// The shared screen's sound travels with it, each way.
    pub share_audio_mine: bool,
    pub share_audio_peer: bool,
    /// Listener-side volume for their screen's sound, 1.0 is unity.
    pub share_volume: f32,
    /// This platform can capture the screen's sound itself, without the webview.
    pub share_audio_native: bool,
    /// The system has refused screen recording and will not ask again.
    pub share_audio_denied: bool,
    /// The peer as this account shows them, for a phone's own call notification.
    #[serde(skip)]
    pub name: String,
    #[serde(skip)]
    pub avatar: Option<String>,
}

#[derive(Serialize, Clone, Debug)]
pub struct LevelPayload {
    pub id: String,
    pub mic: f32,
    pub peer: f32,
}

#[derive(Serialize, Clone, Debug)]
pub struct CallStats {
    pub id: String,
    pub rtt_ms: u32,
    pub path: &'static str,
    pub sent: u64,
    pub send_dropped: u64,
    pub received: u64,
    pub lost: u64,
    pub shed: u64,
    pub rebuilt: u64,
    pub concealed: u64,
    pub late: u64,
    pub depth_ms: u32,
    pub jitter_ms: u32,
    pub clicks_cut: u64,
    pub bitrate_kbps: u32,
    /// Percent of our packets the network dropped in the last second.
    pub net_loss: f32,
    pub video: VideoSnapshot,
    pub share_sent: u64,
    pub share_received: u64,
}

struct Call {
    id: String,
    peer: String,
    outgoing: bool,
    phase: Phase,
    conn: Option<Connection>,
    media: Option<Box<dyn CallAudio>>,
    control: Option<Arc<tokio::sync::Mutex<SendStream>>>,
    tasks: Vec<JoinHandle<()>>,
    active_since: Option<Instant>,
    muted: bool,
    peer_muted: bool,
    mic_off: bool,
    volume: f32,
    video: Option<VideoTrack>,
    video_mine: Tracks,
    video_peer: Tracks,
    peer_decodes: Vec<String>,
    video_offered: bool,
    paused_by_peer: bool,
    peer_away: bool,
    stalled: bool,
    /// The machine stays awake for the call, and the display too once there is video.
    awake: Option<Box<dyn std::any::Any + Send>>,
    /// The sound routed as a phone call's, and whether out loud.
    call_audio: Option<(bool, Box<dyn std::any::Any + Send>)>,
    /// The peer's name and cached avatar, as this account knows them.
    shown: (String, Option<String>),
    /// The shared screen's sound from the webview, for the engine's share thread.
    share: Arc<ShareInput>,
    share_audio_mine: bool,
    share_audio_peer: bool,
    share_volume: f32,
    share_audio_denied: bool,
}

/// Whether a call's sound is held as a phone call's, and out loud: from our own ring on (theirs
/// rings out loud by itself), to the ear until there is video, which keeps it out loud.
fn call_audio_wanted(phase: Phase, outgoing: bool, video: bool, held: Option<bool>) -> Option<bool> {
    match phase {
        Phase::Ringing if !outgoing => None,
        Phase::Ended => None,
        _ => Some(video || held == Some(true)),
    }
}

impl Call {
    /// The holds the call needs right now; dropping the old one after taking the new
    /// keeps the machine covered in between.
    fn refresh_holds(&mut self) {
        let video = self.video_mine.any() || self.video_peer.any();
        let level = if self.phase != Phase::Active {
            None
        } else if video {
            Some(AwakeLevel::Display)
        } else {
            Some(AwakeLevel::System)
        };
        let next = level.and_then(|l| platform::get().ok()?.hold_awake(l));
        self.awake = next;
        let held = self.call_audio.as_ref().map(|(loud, _)| *loud);
        let audio = call_audio_wanted(self.phase, self.outgoing, self.video_offered || video, held);
        if held != audio {
            self.call_audio = audio.and_then(|loud| Some((loud, platform::get().ok()?.hold_call_audio(loud)?)));
        }
    }

    fn state(&self, reason: Option<String>) -> CallState {
        CallState {
            id: self.id.clone(),
            peer: self.peer.clone(),
            outgoing: self.outgoing,
            phase: self.phase,
            reason,
            muted: self.muted,
            peer_muted: self.peer_muted,
            mic_off: self.mic_off,
            volume: self.volume,
            active_ms: self.active_since.map_or(0, |t| t.elapsed().as_millis() as u64),
            video_mine: self.video_mine,
            video_peer: self.video_peer,
            peer_decodes: self.peer_decodes.clone(),
            video_offered: self.video_offered,
            paused_by_peer: self.paused_by_peer,
            peer_away: self.peer_away,
            stalled: self.stalled,
            share_audio_mine: self.share_audio_mine,
            share_audio_peer: self.share_audio_peer,
            share_volume: self.share_volume,
            share_audio_native: platform::get().is_ok_and(|p| p.share_audio_native()),
            share_audio_denied: self.share_audio_denied,
            name: self.shown.0.clone(),
            avatar: self.shown.1.clone(),
        }
    }
}

/// What this device's webview can encode and decode, from its boot probe. Sent on
/// every offer and answer so the other side knows whether to offer video at all.
static VIDEO_CAPS: Mutex<(Vec<String>, Vec<String>)> = Mutex::new((Vec::new(), Vec::new()));

pub fn set_video_caps(encode: Vec<String>, decode: Vec<String>) {
    *VIDEO_CAPS.lock().unwrap_or_else(|e| e.into_inner()) = (encode, decode);
}

fn my_decodes() -> Vec<String> {
    VIDEO_CAPS.lock().unwrap_or_else(|e| e.into_inner()).1.clone()
}

/// The codec to send with: the first of ours the peer decodes, H.264 first.
fn pick_codec(peer_decodes: &[String]) -> Option<VideoCodec> {
    let mine = VIDEO_CAPS.lock().unwrap_or_else(|e| e.into_inner()).0.clone();
    [VideoCodec::H264, VideoCodec::Vp8]
        .into_iter()
        .find(|c| mine.iter().any(|m| m == c.name()) && peer_decodes.iter().any(|p| p == c.name()))
}

fn parse_decodes(tag: Option<&str>) -> Vec<String> {
    tag.unwrap_or("")
        .split(',')
        .filter_map(|c| VideoCodec::from_name(c.trim()).map(|c| c.name().to_string()))
        .collect()
}

static CALL: OnceLock<Mutex<Option<Call>>> = OnceLock::new();

fn slot() -> &'static Mutex<Option<Call>> {
    CALL.get_or_init(|| Mutex::new(None))
}

/// Offers seen within `OFFER_TTL_SECS`: a relay can re-serve one under a new wrapper id, and
/// it must not ring again once its call ended. Call ids are random, so no per-account scope.
static SEEN_OFFERS: Mutex<Vec<(String, u64)>> = Mutex::new(Vec::new());

/// True the first time `call_id` is offered within the TTL window.
fn first_offer(call_id: &str, now: u64) -> bool {
    let mut seen = SEEN_OFFERS.lock().unwrap_or_else(|e| e.into_inner());
    seen.retain(|(_, at)| at + OFFER_TTL_SECS >= now);
    if seen.iter().any(|(id, _)| id == call_id) {
        return false;
    }
    seen.push((call_id.to_string(), now));
    true
}

fn with_call<R>(f: impl FnOnce(&mut Call) -> R) -> Option<R> {
    let mut guard = slot().lock().unwrap_or_else(|e| e.into_inner());
    guard.as_mut().map(f)
}

fn with_call_id<R>(id: &str, f: impl FnOnce(&mut Call) -> R) -> Option<R> {
    let mut guard = slot().lock().unwrap_or_else(|e| e.into_inner());
    match guard.as_mut() {
        Some(call) if call.id == id => Some(f(call)),
        _ => None,
    }
}

fn emit_state(state: &CallState) {
    crate::traits::emit_event("call_state", state);
    if let Some(ringer) = RINGER.get() {
        ringer.ongoing(state);
    }
}

pub fn snapshot() -> Option<CallState> {
    with_call(|c| c.state(None))
}

/// Gift-wraps one signal to the peer. The relay-only address rides along on offers and
/// answers; an offer also carries an expiration so a stale one is dropped by relays too.
async fn send_signal(peer: &str, call_id: &str, signal: &str, addr: Option<&str>, offer_video: bool) -> bool {
    let Some(client) = nostr_client() else { return false };
    let Some(me) = my_public_key() else { return false };
    let Ok(pubkey) = PublicKey::from_bech32(peer) else { return false };

    let mut builder = EventBuilder::new(Kind::ApplicationSpecificData, "call")
        .tag(Tag::public_key(pubkey))
        .tag(Tag::custom("d", vec!["vector-call"]))
        .tag(Tag::custom("call-id", vec![call_id]))
        .tag(Tag::custom("call-signal", vec![signal]));
    if let Some(addr) = addr {
        builder = builder.tag(Tag::custom("call-node-addr", vec![addr]));
    }
    if signal == "offer" {
        builder = builder.tag(Tag::expiration(crate::clock::timestamp() + OFFER_TTL_SECS));
        builder = builder.tag(Tag::custom("call-media", vec![if offer_video { "video" } else { "audio" }]));
    }
    if signal == "offer" || signal == "answer" {
        let decodes = my_decodes();
        if !decodes.is_empty() {
            builder = builder.tag(Tag::custom("call-video", vec![decodes.join(",")]));
        }
    }
    let rumor = builder.finalize_unsigned_with_id(me);
    let relays = active_trusted_relays().await;
    // An offer and its withdrawal also go to their inbox relays: a phone the ring's push just
    // woke reads those first, and may not share ours.
    let (ours, inbox) = if signal == "offer" || signal == "hangup" {
        futures_util::join!(
            crate::send_gift_wrap(&client, relays, &pubkey, rumor.clone(), []),
            async { crate::inbox_relays::send_gift_wrap(&client, &pubkey, rumor, []).await.map(|_| ()) },
        )
    } else {
        (crate::send_gift_wrap(&client, relays, &pubkey, rumor, []).await, Err(String::new()))
    };
    match (ours, inbox) {
        (Ok(_), _) | (_, Ok(())) => true,
        (Err(e), _) => {
            log_warn!("[CALLS] Failed to send {signal} to {peer}: {e}");
            false
        }
    }
}

/// Tears the call down and tells the UI why. Idempotent: a second end is a no-op.
pub fn end(id: &str, reason: &str) {
    if take_down(id, reason) {
        if let Ok(p) = platform::get() {
            p.ended();
        }
    }
}

/// Account swap or shutdown: whatever is up comes down without a signal.
pub fn end_all(reason: &str) {
    if let Some(id) = with_call(|c| c.id.clone()) {
        take_down(&id, reason);
    }
}

/// A phone's own call surfaces: the ring where the app's window can't show one (the lock
/// screen), and the notification of a call under way. Installed once per process, so it rings
/// even in one that runs no call engine (a phone's background service).
pub trait Ringer: Send + Sync {
    /// `name` and `avatar` are the caller's, as this account knows them.
    fn ring(&self, call_id: &str, peer: &str, name: &str, avatar: Option<&str>, video: bool);
    /// The ring stopped: taken up here, or `missed`.
    fn over(&self, call_id: &str, missed: bool);
    /// Every change to the call, for the phone's ongoing-call notification.
    fn ongoing(&self, _state: &CallState) {}
    /// The voice Channel's call, for the same notification; None once left.
    fn voice(&self, _call: Option<&VoiceShown>) {}
}

/// A voice Channel's call as a phone's notification shows it.
pub struct VoiceShown<'a> {
    pub channel_id: &'a str,
    pub channel: &'a str,
    pub community: &'a str,
    pub muted: bool,
    pub since_ms: u64,
}

static RINGER: std::sync::OnceLock<Box<dyn Ringer>> = std::sync::OnceLock::new();

pub(super) fn ringer() -> Option<&'static dyn Ringer> {
    RINGER.get().map(|r| &**r)
}

pub fn set_ringer(ringer: Box<dyn Ringer>) {
    let _ = RINGER.set(ringer);
}

async fn ring(call_id: &str, peer: &str, video: bool) {
    let Some(ringer) = RINGER.get() else { return };
    let (name, avatar) = shown_as(peer).await;
    ringer.ring(call_id, peer, &name, avatar.as_deref(), video);
}

/// A peer's name and cached avatar, as this account knows them.
async fn shown_as(peer: &str) -> (String, Option<String>) {
    let (name, avatar) = {
        let state = crate::STATE.lock().await;
        match state.get_profile(peer) {
            Some(p) => {
                let name = [p.nickname(), p.display_name(), p.name()].into_iter().find(|n| !n.is_empty()).map(str::to_string);
                (name, p.has_avatar_cached().then(|| p.avatar_cached().into_owned()))
            }
            None => (None, None),
        }
    };
    (name.unwrap_or_else(|| format!("{}…", &peer[..peer.len().min(14)])), avatar)
}

fn ring_over(call_id: &str, missed: bool) {
    if let Some(ringer) = RINGER.get() {
        ringer.over(call_id, missed);
    }
}

fn take_down(id: &str, reason: &str) -> bool {
    let call = {
        let mut guard = slot().lock().unwrap_or_else(|e| e.into_inner());
        match guard.as_ref() {
            Some(c) if c.id == id => guard.take(),
            _ => None,
        }
    };
    let Some(mut call) = call else { return false };
    log_info!("[CALLS] Call {} ended: {reason}", call.id);
    // An incoming ring that timed out, or that the caller withdrew, was missed.
    ring_over(&call.id, !call.outgoing && call.phase == Phase::Ringing && matches!(reason, "missed" | "hangup"));
    for t in call.tasks.drain(..) {
        t.abort();
    }
    // Media first: its threads hold the connection and the mixer slot. The video
    // track's drop closes the link, which stops the camera.
    stop_share_audio();
    drop(call.video.take());
    drop(call.media.take());
    if let Some(conn) = call.conn.take() {
        conn.close(VarInt::from_u32(0), b"bye");
    }
    call.phase = Phase::Ended;
    emit_state(&call.state(Some(reason.to_string())));
    true
}

pub async fn start(peer: String, video: bool) -> Result<CallState, String> {
    if PublicKey::from_bech32(&peer).is_err() {
        return Err("Not a valid npub".into());
    }
    crate::transport::realtime::check()?;
    if super::voice::snapshot().is_some() {
        return Err("Leave the voice channel first".into());
    }
    let platform = platform::get()?;
    let id = format!("{:032x}", rand::random::<u128>());

    let shown = shown_as(&peer).await;
    // In the slot before the node is read: a client that closes an idle node
    // must see this call, or the offer could name a node already gone.
    let state = {
        let mut guard = slot().lock().unwrap_or_else(|e| e.into_inner());
        if guard.is_some() {
            return Err("Already in a call".into());
        }
        let mut call = Call {
            id: id.clone(),
            peer: peer.clone(),
            outgoing: true,
            phase: Phase::Ringing,
            conn: None,
            media: None,
            control: None,
            tasks: Vec::new(),
            active_since: None,
            muted: { let mic = super::settings::mic_state(); mic.muted || mic.deafened },
            peer_muted: false,
            mic_off: false,
            volume: 1.0,
            video: None,
            video_mine: Tracks::default(),
            video_peer: Tracks::default(),
            peer_decodes: Vec::new(),
            video_offered: video,
            paused_by_peer: false,
            peer_away: false,
            stalled: false,
            awake: None,
            call_audio: None,
            shown,
            share: Arc::new(ShareInput::new()),
            share_audio_mine: false,
            share_audio_peer: false,
            share_volume: 1.0,
            share_audio_denied: false,
        };
        call.refresh_holds();
        let state = call.state(None);
        *guard = Some(call);
        state
    };
    let addr = match platform.local_addr().await {
        Ok(a) => a,
        Err(e) => {
            let mut guard = slot().lock().unwrap_or_else(|e| e.into_inner());
            if guard.as_ref().is_some_and(|c| c.id == id) {
                *guard = None;
            }
            return Err(e);
        }
    };
    emit_state(&state);

    if !send_signal(&peer, &id, "offer", Some(&addr), video).await {
        end(&id, "send_failed");
        return Err("Could not reach the relays".into());
    }
    crate::push::call_ringing(&peer, &id, video);
    spawn_ring_timeout(id.clone(), peer, true);
    Ok(state)
}

fn spawn_ring_timeout(id: String, peer: String, outgoing: bool) {
    let task = crate::db::spawn_bound(async move {
        sleep(RING_TIMEOUT).await;
        let still_ringing = with_call_id(&id, |c| c.phase == Phase::Ringing).unwrap_or(false);
        if !still_ringing {
            return;
        }
        if outgoing {
            send_signal(&peer, &id, "hangup", None, false).await;
            crate::push::call_missed(&peer, &id);
            end(&id, "no_answer");
        } else {
            end(&id, "missed");
        }
    });
    with_call_id_push_task(task);
}

fn with_call_id_push_task(task: JoinHandle<()>) {
    if with_call(|c| c.tasks.push(task)).is_none() {
        // The call ended between spawn and registration; nothing to keep.
    }
}

pub async fn accept() -> Result<(), String> {
    crate::transport::realtime::check()?;
    let (id, peer) = with_call(|c| {
        if c.outgoing || c.phase != Phase::Ringing {
            return Err("No incoming call to accept".to_string());
        }
        c.phase = Phase::Connecting;
        c.refresh_holds();
        Ok((c.id.clone(), c.peer.clone()))
    })
    .unwrap_or(Err("No call".into()))?;
    ring_over(&id, false);
    if let Some(s) = snapshot() {
        emit_state(&s);
    }

    let addr = match platform::get() {
        Ok(p) => p.local_addr().await,
        Err(e) => Err(e),
    };
    let addr = match addr {
        Ok(a) => a,
        Err(e) => {
            end(&id, "connect_failed");
            return Err(e);
        }
    };
    if !send_signal(&peer, &id, "answer", Some(&addr), false).await {
        end(&id, "send_failed");
        return Err("Could not reach the relays".into());
    }
    let timeout_id = id.clone();
    let task = crate::db::spawn_bound(async move {
        sleep(CONNECT_TIMEOUT).await;
        if with_call_id(&timeout_id, |c| c.phase == Phase::Connecting).unwrap_or(false) {
            end(&timeout_id, "connect_failed");
        }
    });
    with_call_id_push_task(task);
    Ok(())
}

pub async fn reject() -> Result<(), String> {
    let (id, peer) = with_call(|c| (c.id.clone(), c.peer.clone())).ok_or("No call")?;
    send_signal(&peer, &id, "reject", None, false).await;
    end(&id, "rejected");
    Ok(())
}

/// Decline a ringing call from a notification, whether or not this process holds it: a
/// background service only rang it.
pub async fn decline(call_id: &str, peer: &str) {
    ring_over(call_id, false);
    if with_call(|c| c.id == call_id).unwrap_or(false) {
        let _ = reject().await;
    } else {
        send_signal(peer, call_id, "reject", None, false).await;
    }
}

pub async fn hangup() -> Result<(), String> {
    let (id, peer, control, unanswered) =
        with_call(|c| (c.id.clone(), c.peer.clone(), c.control.clone(), c.outgoing && c.phase == Phase::Ringing)).ok_or("No call")?;
    if let Some(control) = control {
        let mut send = control.lock().await;
        let _ = timeout(Duration::from_secs(1), write_control(&mut *send, &Control::Bye)).await;
    }
    // Local teardown first: the peer's close must not be what ends our side.
    end(&id, "hangup");
    // The signal reaches a peer whose connection never came up, or one still ringing.
    send_signal(&peer, &id, "hangup", None, false).await;
    if unanswered {
        crate::push::call_missed(&peer, &id);
    }
    Ok(())
}

/// Mute or unmute, and remember it for the next call. Unmuting while deafened hears again too.
pub async fn set_muted(on: bool) -> Result<(), String> {
    let mic = super::settings::mic_state();
    if !on && mic.deafened {
        hear(true)?;
    }
    super::settings::remember_mic(super::settings::MicState { muted: on, deafened: mic.deafened && on });
    send_muted(on).await
}

/// Deafen: nothing the call plays is heard, and the microphone goes off with it.
pub async fn set_deafened(on: bool) -> Result<(), String> {
    let mic = super::settings::mic_state();
    super::settings::remember_mic(super::settings::MicState { muted: mic.muted, deafened: on });
    hear(!on)?;
    send_muted(on || mic.muted).await
}

/// Play the call at its volume, or at nothing.
fn hear(on: bool) -> Result<(), String> {
    with_call(|c| {
        if let Some(m) = c.media.as_ref() {
            m.set_volume(if on { c.volume } else { 0.0 });
        }
    })
    .ok_or_else(|| "No call".to_string())
}

async fn send_muted(on: bool) -> Result<(), String> {
    let control = with_call(|c| {
        c.muted = on;
        if let Some(m) = c.media.as_ref() {
            m.set_muted(on);
        }
        c.control.clone()
    })
    .ok_or("No call")?;
    if let Some(s) = snapshot() {
        emit_state(&s);
    }
    if let Some(control) = control {
        let mut send = control.lock().await;
        let _ = timeout(Duration::from_secs(1), write_control(&mut *send, &Control::Mute { on })).await;
    }
    Ok(())
}

/// Tell the peer this app is going where the system pauses it, or is back.
pub async fn set_away(on: bool) -> Result<(), String> {
    let control = with_call(|c| c.control.clone()).ok_or("No call")?;
    if let Some(control) = control {
        let mut send = control.lock().await;
        let _ = timeout(Duration::from_secs(1), write_control(&mut *send, &Control::Away { on })).await;
    }
    Ok(())
}

/// Listener-side volume for the call in progress.
pub async fn set_volume(volume: f32) -> Result<(), String> {
    let volume = volume.clamp(0.0, 4.0);
    with_call(|c| {
        c.volume = volume;
        if let Some(m) = c.media.as_ref() {
            m.set_volume(super::settings::heard(volume));
        }
    })
    .ok_or("No call")?;
    if let Some(s) = snapshot() {
        emit_state(&s);
    }
    Ok(())
}

/// Start or stop sending one of our pictures. The codec is the first of ours the
/// peer decodes.
pub async fn set_video(kind: VideoKind, on: bool) -> Result<(), String> {
    let tracks = with_call(|c| {
        if c.phase != Phase::Active {
            return Err("Not in a call".to_string());
        }
        let Some(track) = c.video.as_ref() else { return Err("No video track".to_string()) };
        let tracks = c.video_mine.with(kind, on);
        if tracks.any() {
            let codec = pick_codec(&c.peer_decodes).ok_or("They cannot receive video")?;
            track.set_codec(codec);
        }
        track.set_sending(tracks);
        c.video_mine = tracks;
        if !tracks.screen {
            c.share_audio_mine = false;
            c.share.active.store(false, Ordering::Relaxed);
            stop_share_audio();
        }
        c.refresh_holds();
        Ok((tracks, c.control.clone()))
    })
    .unwrap_or(Err("No call".into()))?;
    tell_tracks(tracks).await;
    Ok(())
}

/// Every send of what we are sending goes through here: the UI and the peer both hear.
async fn tell_tracks((tracks, control): (Tracks, Option<Arc<tokio::sync::Mutex<SendStream>>>)) {
    let audio = with_call(|c| c.share_audio_mine).unwrap_or(false);
    if let Some(s) = snapshot() {
        emit_state(&s);
    }
    if let Some(control) = control {
        let mut send = control.lock().await;
        let _ = timeout(Duration::from_secs(1), write_control(&mut *send, &Control::Video { camera: tracks.camera, screen: tracks.screen, audio })).await;
    }
}

/// The shared screen's sound goes with it, or stops; it cannot outlive the screen.
/// `native` asks this platform to capture it itself, for a picker that gave none.
pub async fn set_share_audio(on: bool, native: bool) -> Result<(), String> {
    let (on, share) = with_call(|c| {
        if c.phase != Phase::Active {
            return Err("Not in a call".to_string());
        }
        Ok((on && c.video_mine.screen, Arc::clone(&c.share)))
    })
    .unwrap_or(Err("No call".into()))?;
    let platform = platform::get()?;
    if on && native {
        if let Err(e) = platform.start_share_audio(share).await {
            // A declined prompt is a plain no; a standing refusal is for the panel to show.
            let denied = !platform.share_audio_permitted();
            with_call(|c| c.share_audio_denied = denied);
            if let Some(s) = snapshot() {
                emit_state(&s);
            }
            return Err(if denied { "Screen recording is off for Vector in System Settings".to_string() } else { e });
        }
        with_call(|c| c.share_audio_denied = false);
    } else {
        platform.stop_share_audio().await;
    }
    let tracks = with_call(|c| {
        c.share_audio_mine = on;
        c.share.active.store(on, Ordering::Relaxed);
        (c.video_mine, c.control.clone())
    })
    .ok_or("No call")?;
    tell_tracks(tracks).await;
    Ok(())
}

/// Listener-side volume for their screen's sound.
pub async fn set_share_volume(volume: f32) -> Result<(), String> {
    let volume = volume.clamp(0.0, 4.0);
    with_call(|c| {
        c.share_volume = volume;
        if let Some(m) = c.media.as_ref() {
            m.set_share_volume(volume);
        }
    })
    .ok_or("No call")?;
    if let Some(s) = snapshot() {
        emit_state(&s);
    }
    Ok(())
}

/// The user's quality and frame rate for one of our pictures; None means the ladder decides.
pub fn set_video_prefs(kind: VideoKind, rung: Option<usize>, fps: Option<u32>) -> Result<(), String> {
    with_call(|c| {
        let Some(track) = c.video.as_ref() else { return Err("No video track".to_string()) };
        track.set_prefs(kind, Prefs { rung, fps });
        Ok(())
    })
    .unwrap_or(Err("No call".into()))
}

/// Our view of their picture is hidden (or shown again): they may stop sending.
pub async fn set_video_pause(on: bool) -> Result<(), String> {
    let control = with_call(|c| c.control.clone()).ok_or("No call")?;
    if let Some(control) = control {
        let mut send = control.lock().await;
        let _ = timeout(Duration::from_secs(1), write_control(&mut *send, &Control::VideoPause { on })).await;
    }
    Ok(())
}

/// The webview's socket closed under a call: whatever it was sending has stopped.
async fn on_link_closed(id: &str) {
    let tracks = with_call_id(id, |c| {
        if !c.video_mine.any() {
            return None;
        }
        c.video_mine = Tracks::default();
        c.share_audio_mine = false;
        c.share.active.store(false, Ordering::Relaxed);
        if let Some(v) = c.video.as_ref() {
            v.set_sending(Tracks::default());
        }
        c.refresh_holds();
        Some((Tracks::default(), c.control.clone()))
    })
    .flatten();
    if let Some(t) = tracks {
        tell_tracks(t).await;
    }
}

/// Reopens the call's audio, on whatever devices are now the defaults. One at a time: an
/// unplugged headset changes the default input and output together, and two overlapping
/// reopens fight over the devices and the mixer.
pub async fn restart_audio() {
    static RESTART: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
    let _turn = RESTART.lock().await;
    // Devices settle over a few seconds after a change; a reopen that fails meanwhile is
    // retried rather than ending the call, inside the peer's silence window.
    let mut stats = None;
    for wait in [0u64, 500, 1500, 3000] {
        crate::rt::time::sleep(Duration::from_millis(wait)).await;
        match reopen_audio(&mut stats).await {
            Reopen::Done => return,
            Reopen::Failed(e) => log_warn!("[CALLS] Could not reopen audio after a device change: {e}"),
        }
    }
    if let Some(id) = with_call(|c| c.media.is_none().then(|| c.id.clone())).flatten() {
        end(&id, "audio_failed");
    }
}

enum Reopen {
    Done,
    Failed(String),
}

/// `stats` carries the counters from the engine the first attempt dropped to every retry.
async fn reopen_audio(stats: &mut Option<Arc<super::stats::MediaStats>>) -> Reopen {
    let Some((id, Some(conn))) = with_call(|c| (c.id.clone(), c.conn.clone())) else { return Reopen::Done };
    let Ok(platform) = platform::get() else { return Reopen::Done };
    // Drop the old engine first: it holds the devices.
    let Some((old, muted, volume, share, share_volume)) =
        with_call_id(&id, |c| (c.media.take(), c.muted, c.volume, Arc::clone(&c.share), c.share_volume))
    else {
        return Reopen::Done;
    };
    // The counters outlive the engine: the liveness check reads them for the
    // call's life, and a reset reads as the peer having gone quiet.
    if let Some(m) = old.as_ref() {
        *stats = Some(m.stats());
    }
    drop(old);
    let volume = super::settings::heard(volume);
    match platform.start_audio(conn, AudioStart { volume, share_volume, stats: stats.clone(), share }).await {
        Ok(m) => {
            m.set_muted(muted);
            let mic_off = !m.has_mic();
            if with_call_id(&id, |c| {
                c.mic_off = mic_off;
                c.media = Some(m);
            })
            .is_some()
            {
                log_info!("[CALLS] Audio reopened on the new default devices");
                if let Some(s) = snapshot() {
                    emit_state(&s);
                }
            }
            Reopen::Done
        }
        Err(e) => Reopen::Failed(e),
    }
}

/// Stops the platform's own capture of the screen's sound, if it had one going.
fn stop_share_audio() {
    if let Ok(p) = platform::get() {
        crate::db::spawn_bound(async move { p.stop_share_audio().await });
    }
}

/// A signal from the peer, already validated as coming from `sender`.
pub async fn on_signal(sender: &str, call_id: &str, signal: &str, node_addr: Option<&str>, created_at: u64, video: Option<&str>, media: Option<&str>) {
    log_info!("[CALLS] {signal} from {sender} for call {call_id}");
    let Ok(platform) = platform::get() else {
        // No call engine in this process: the ring is all it can do, and the app takes the call.
        match signal {
            "offer" if created_at + OFFER_TTL_SECS >= crate::clock::timestamp().as_secs() => ring(call_id, sender, media == Some("video")).await,
            "hangup" => ring_over(call_id, true),
            "taken" => ring_over(call_id, false),
            _ => {}
        }
        return;
    };
    match signal {
        "offer" => {
            let now = crate::clock::timestamp().as_secs();
            if created_at + OFFER_TTL_SECS < now {
                log_info!("[CALLS] Ignoring an offer {}s old", now.saturating_sub(created_at));
                return;
            }
            if node_addr.and_then(|a| platform.decode_addr(a)).is_none() {
                log_warn!("[CALLS] Offer without a usable address");
                return;
            }
            if !first_offer(call_id, now) {
                return;
            }
            let shown = shown_as(sender).await;
            let state = {
                let mut guard = slot().lock().unwrap_or_else(|e| e.into_inner());
                match guard.as_ref() {
                    Some(c) if c.id == call_id => return,
                    Some(_) => None,
                    // In a voice channel's call: busy, as in any other.
                    None if super::voice::snapshot().is_some() => None,
                    None => {
                        let call = Call {
                            id: call_id.to_string(),
                            peer: sender.to_string(),
                            outgoing: false,
                            phase: Phase::Ringing,
                            conn: None,
                            media: None,
                            control: None,
                            tasks: Vec::new(),
                            active_since: None,
                            muted: { let mic = super::settings::mic_state(); mic.muted || mic.deafened },
                            peer_muted: false,
                            mic_off: false,
                            volume: 1.0,
                            video: None,
                            video_mine: Tracks::default(),
                            video_peer: Tracks::default(),
                            peer_decodes: parse_decodes(video),
                            video_offered: media == Some("video"),
                            paused_by_peer: false,
                            peer_away: false,
                            stalled: false,
                            awake: None,
                            call_audio: None,
                            shown,
                            share: Arc::new(ShareInput::new()),
                            share_audio_mine: false,
                            share_audio_peer: false,
                            share_volume: 1.0,
                            share_audio_denied: false,
                        };
                        let state = call.state(None);
                        *guard = Some(call);
                        Some(state)
                    }
                }
            };
            match state {
                Some(state) => {
                    emit_state(&state);
                    spawn_ring_timeout(call_id.to_string(), sender.to_string(), false);
                    ring(call_id, sender, media == Some("video")).await;
                }
                None => {
                    send_signal(sender, call_id, "busy", None, false).await;
                }
            }
        }
        "answer" => {
            let Some(addr) = node_addr.and_then(|a| platform.decode_addr(a)) else {
                log_warn!("[CALLS] Answer without a usable address");
                return;
            };
            let accepted = with_call_id(call_id, |c| {
                if c.outgoing && c.peer == sender && c.phase == Phase::Ringing {
                    c.phase = Phase::Connecting;
                    c.peer_decodes = parse_decodes(video);
                    c.refresh_holds();
                    true
                } else {
                    false
                }
            })
            .unwrap_or(false);
            if !accepted {
                return;
            }
            if let Some(s) = snapshot() {
                emit_state(&s);
            }
            // The peer's other devices are still ringing; tell them which one answered.
            send_signal(sender, call_id, "taken", node_addr, false).await;
            let id = call_id.to_string();
            let peer = sender.to_string();
            let task = crate::db::spawn_bound(async move {
                match connect(addr, &id).await {
                    Ok((conn, send, recv)) => attach(&id, conn, send, recv).await,
                    Err(e) => {
                        log_warn!("[CALLS] Connect failed: {e}");
                        send_signal(&peer, &id, "hangup", None, false).await;
                        end(&id, "connect_failed");
                    }
                }
            });
            with_call_id_push_task(task);
        }
        "reject" | "busy" | "hangup" => {
            if with_call_id(call_id, |c| c.peer == sender).unwrap_or(false) {
                end(call_id, signal);
            }
        }
        // Another of our devices answered: only a device still ringing stands down.
        "taken" => {
            let ringing = with_call_id(call_id, |c| c.peer == sender && !c.outgoing && c.phase == Phase::Ringing).unwrap_or(false);
            if ringing {
                end(call_id, "answered_elsewhere");
            }
        }
        other => log_warn!("[CALLS] Unknown signal {other}"),
    }
}

async fn connect(addr: EndpointAddr, call_id: &str) -> Result<(Connection, SendStream, RecvStream), String> {
    let endpoint = platform::get()?.endpoint().await?;
    let conn = timeout(CONNECT_TIMEOUT, endpoint.connect(addr, CALL_ALPN))
        .await
        .map_err(|_| "connect timed out".to_string())?
        .map_err(|e| e.to_string())?;
    let (mut send, recv) = conn.open_bi().await.map_err(|e| e.to_string())?;
    write_control(&mut send, &Control::Hello { call_id: call_id.to_string() }).await?;
    Ok((conn, send, recv))
}

/// The accept loop hands over a connection with our ALPN. It belongs to the call
/// whose id its Hello names, if that call is waiting for one.
pub async fn on_incoming(conn: Connection) {
    let handshake = timeout(Duration::from_secs(10), async {
        let (send, mut recv) = conn.accept_bi().await.map_err(|e| e.to_string())?;
        let hello = read_control(&mut recv).await?;
        Ok::<_, String>((send, recv, hello))
    })
    .await;
    let (send, recv, hello) = match handshake {
        Ok(Ok(v)) => v,
        Ok(Err(e)) => {
            log_warn!("[CALLS] Incoming connection without a Hello: {e}");
            conn.close(VarInt::from_u32(1), b"no hello");
            return;
        }
        Err(_) => {
            conn.close(VarInt::from_u32(1), b"hello timeout");
            return;
        }
    };
    let Control::Hello { call_id } = hello else {
        conn.close(VarInt::from_u32(1), b"expected hello");
        return;
    };
    let waiting = with_call_id(&call_id, |c| !c.outgoing && c.phase == Phase::Connecting).unwrap_or(false);
    if !waiting {
        log_warn!("[CALLS] Connection for call {call_id} that is not waiting");
        conn.close(VarInt::from_u32(2), b"not expected");
        return;
    }
    attach(&call_id, conn, send, recv).await;
}

/// Media up, watchers on, Active.
async fn attach(id: &str, conn: Connection, send: SendStream, mut recv: RecvStream) {
    let platform = match platform::get() {
        Ok(p) => p,
        Err(_) => {
            conn.close(VarInt::from_u32(3), b"no audio");
            end(id, "audio_failed");
            return;
        }
    };
    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));
    let start = AudioStart { volume: super::settings::heard(volume), share_volume, stats: None, share: Arc::clone(&share) };
    let media = match platform.start_audio(conn.clone(), start).await {
        Ok(m) => m,
        Err(e) => {
            log_warn!("[CALLS] Media failed: {e}");
            let peer = with_call_id(id, |c| c.peer.clone());
            if let Some(peer) = peer {
                send_signal(&peer, id, "hangup", None, false).await;
            }
            conn.close(VarInt::from_u32(3), b"no audio");
            end(id, "audio_failed");
            return;
        }
    };
    let muted = with_call_id(id, |c| c.muted).unwrap_or(false);
    media.set_muted(muted);
    let control = Arc::new(tokio::sync::Mutex::new(send));
    let stats = media.stats();

    let peer_video = with_call_id(id, |c| !c.peer_decodes.is_empty()).unwrap_or(false);
    let video = VideoTrack::start(
        conn.clone(),
        Hooks {
            call_id: id.to_string(),
            control: Arc::clone(&control),
            on_link_closed: Arc::new(|id: &str| {
                let id = id.to_string();
                crate::db::spawn_bound(async move { on_link_closed(&id).await });
            }),
            on_caps: Arc::new(set_video_caps),
            audio: Arc::clone(&stats),
            peer_video,
            share,
        },
        platform,
    );
    let mic_off = !media.has_mic();
    let installed = with_call_id(id, |c| {
        c.conn = Some(conn.clone());
        c.mic_off = mic_off;
        c.media = Some(media);
        c.control = Some(Arc::clone(&control));
        c.video = Some(video);
        c.phase = Phase::Active;
        c.active_since = Some(Instant::now());
        c.refresh_holds();
    })
    .is_some();
    if !installed {
        conn.close(VarInt::from_u32(0), b"gone");
        return;
    }
    if let Some(s) = snapshot() {
        emit_state(&s);
    }

    // Peer's control messages.
    let ctl_id = id.to_string();
    let ctl = crate::db::spawn_bound(async move {
        loop {
            match read_control(&mut recv).await {
                Ok(Control::Mute { on }) => {
                    with_call_id(&ctl_id, |c| c.peer_muted = on);
                    if let Some(s) = snapshot() {
                        emit_state(&s);
                    }
                }
                Ok(Control::Bye) => {
                    end(&ctl_id, "hangup");
                    break;
                }
                Ok(Control::Video { camera, screen, audio }) => {
                    let tracks = Tracks { camera, screen };
                    with_call_id(&ctl_id, |c| {
                        c.video_peer = tracks;
                        c.share_audio_peer = audio && screen;
                        if let Some(v) = c.video.as_ref() {
                            v.set_peer(tracks);
                        }
                        c.refresh_holds();
                    });
                    if let Some(s) = snapshot() {
                        emit_state(&s);
                    }
                }
                Ok(Control::KeyframeRequest { kind }) => {
                    with_call_id(&ctl_id, |c| {
                        if let Some(v) = c.video.as_ref() {
                            v.force_keyframe(kind);
                        }
                    });
                }
                Ok(Control::Away { on }) => {
                    with_call_id(&ctl_id, |c| c.peer_away = on);
                    if let Some(s) = snapshot() {
                        emit_state(&s);
                    }
                }
                Ok(Control::VideoPause { on }) => {
                    with_call_id(&ctl_id, |c| {
                        c.paused_by_peer = on;
                        if let Some(v) = c.video.as_ref() {
                            v.set_paused(on);
                        }
                    });
                    if let Some(s) = snapshot() {
                        emit_state(&s);
                    }
                }
                Ok(Control::VideoUnsupported { codec }) => {
                    // Send with what is left; with nothing left, video stops and the UI says so.
                    let repick = with_call_id(&ctl_id, |c| {
                        c.peer_decodes.retain(|d| d != codec.name());
                        if !c.video_mine.any() {
                            return None;
                        }
                        match (pick_codec(&c.peer_decodes), c.video.as_ref()) {
                            (Some(next), Some(track)) => {
                                track.set_codec(next);
                                Some(true)
                            }
                            _ => Some(false),
                        }
                    })
                    .flatten();
                    if repick == Some(false) {
                        log_warn!("[CALLS] Peer cannot decode any codec we encode");
                        let _ = set_video(VideoKind::Camera, false).await;
                        let _ = set_video(VideoKind::Screen, false).await;
                        crate::traits::emit_event("call_video_refused", &serde_json::json!({ "id": ctl_id }));
                    }
                }
                Ok(Control::Hello { .. }) | Ok(Control::Unknown) => {}
                Err(_) => break,
            }
        }
    });
    // The transport going away under us.
    let closed_id = id.to_string();
    let closed_conn = conn.clone();
    let closed = crate::db::spawn_bound(async move {
        // A close carrying our own "bye" is a hangup; the Bye on the control stream can
        // still be in flight when the close lands.
        let reason = match closed_conn.closed().await {
            iroh::endpoint::ConnectionError::ApplicationClosed(ac) if ac.reason.as_ref() == b"bye" => "hangup",
            _ => "disconnected",
        };
        end(&closed_id, reason);
    });
    // A stats line every second, and the liveness check: the peer sends fifty frames
    // a second even muted, so a silent stretch means they are stalled, and a long one gone.
    let stats_id = id.to_string();
    let stats_conn = conn.clone();
    let stats_task = crate::db::spawn_bound(async move {
        let mut last_received = 0u64;
        let mut silent_secs = 0u32;
        let mut tick = 0u32;
        loop {
            sleep(Duration::from_millis(100)).await;
            // Meters ten times a second; the rest once a second.
            crate::traits::emit_event("call_level", &LevelPayload {
                id: stats_id.clone(),
                mic: stats.mic_level(),
                peer: stats.peer_level(),
            });
            tick += 1;
            if !tick.is_multiple_of(10) {
                continue;
            }
            let received = stats.received.load(Ordering::Relaxed);
            silent_secs = if received == last_received { silent_secs + 1 } else { 0 };
            last_received = received;
            let away = with_call_id(&stats_id, |c| c.peer_away).unwrap_or(false);
            if silent_secs >= if away { AWAY_SILENCE_SECS } else { PEER_SILENCE_SECS } {
                end(&stats_id, "disconnected");
                return;
            }
            let stalled = silent_secs >= STALL_SECS;
            if with_call_id(&stats_id, |c| std::mem::replace(&mut c.stalled, stalled) != stalled).unwrap_or(false) {
                if let Some(s) = snapshot() {
                    emit_state(&s);
                }
            }
            let (rtt_ms, path) = {
                let paths = stats_conn.paths();
                match paths.iter().find(|p| p.is_selected()).or_else(|| paths.iter().next()) {
                    Some(p) => (p.rtt().as_millis() as u32, if p.is_relay() { "relay" } else { "direct" }),
                    None => (0, "none"),
                }
            };
            let payload = CallStats {
                id: stats_id.clone(),
                rtt_ms,
                path,
                sent: stats.sent.load(Ordering::Relaxed),
                send_dropped: stats.send_dropped.load(Ordering::Relaxed),
                received: stats.received.load(Ordering::Relaxed),
                lost: stats.lost.load(Ordering::Relaxed),
                shed: stats.shed.load(Ordering::Relaxed),
                rebuilt: stats.rebuilt.load(Ordering::Relaxed),
                concealed: stats.concealed.load(Ordering::Relaxed),
                late: stats.late.load(Ordering::Relaxed),
                clicks_cut: stats.clicks_cut.load(Ordering::Relaxed),
                depth_ms: stats.depth_ms.load(Ordering::Relaxed),
                jitter_ms: stats.jitter_ms.load(Ordering::Relaxed),
                bitrate_kbps: stats.bitrate_kbps.load(Ordering::Relaxed),
                net_loss: stats.net_loss(),
                video: with_call_id(&stats_id, |c| c.video.as_ref().map(|v| v.snapshot())).flatten().unwrap_or_default(),
                share_sent: stats.share_sent.load(Ordering::Relaxed),
                share_received: stats.share_received.load(Ordering::Relaxed),
            };
            crate::traits::emit_event("call_stats", &payload);
        }
    });
    let mut tasks = Some(vec![ctl, closed, stats_task]);
    with_call_id(id, |c| c.tasks.extend(tasks.take().unwrap_or_default()));
    if let Some(orphans) = tasks {
        for t in orphans {
            t.abort();
        }
        end(id, "hangup");
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_call_plays_to_the_ear_from_our_ring_and_out_loud_once_there_is_video() {
        assert_eq!(call_audio_wanted(Phase::Ringing, false, false, None), None);
        assert_eq!(call_audio_wanted(Phase::Ringing, true, false, None), Some(false));
        assert_eq!(call_audio_wanted(Phase::Connecting, false, false, None), Some(false));
        assert_eq!(call_audio_wanted(Phase::Ringing, true, true, None), Some(true));
        assert_eq!(call_audio_wanted(Phase::Active, false, true, Some(false)), Some(true));
        // The camera going off leaves a video call out loud.
        assert_eq!(call_audio_wanted(Phase::Active, false, false, Some(true)), Some(true));
        assert_eq!(call_audio_wanted(Phase::Active, false, false, Some(false)), Some(false));
        assert_eq!(call_audio_wanted(Phase::Ended, true, true, Some(true)), None);
    }

    #[test]
    fn an_offer_rings_once_until_its_ttl_passes() {
        let id = format!("{:032x}", rand::random::<u128>());
        assert!(first_offer(&id, 1_000));
        assert!(!first_offer(&id, 1_000 + OFFER_TTL_SECS));
        assert!(first_offer(&format!("{id}x"), 1_000));
        assert!(first_offer(&id, 1_001 + OFFER_TTL_SECS));
    }
}