sew-call-client 0.9.6

Sew's native voice engine: LiveKit-protocol signalling and reconnect against Sew's media server, str0m transport with TURN over UDP, TCP and TLS (relay-only when asked), MLS call keys with the mandatory E2EE checks over the call credential and the call socket, the device store, and the kessel-audio bridge.
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
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
//! The receive side of video, inside the engine: the roster's video tracks, their sinks and
//! settings, and per track the pipeline RTP → reorder → depacketise → decrypt → frame.
//!
//! [`Subscriptions`] holds no I/O. The engine feeds it (the roster, RTP, sink commands, time)
//! and carries out what it asks in [`Out`]: signal requests (`UpdateTrackSettings`),
//! keyframe requests on the PC, items for [`crate::Call::video_frames`] and call events.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};

use bytes::Bytes;
use sew_lkproto::livekit::{
    ParticipantInfo, SignalRequest, StreamState, StreamStateInfo, TrackInfo, TrackSource,
    TrackType, UpdateTrackSettings, signal_request,
};
use tokio::sync::mpsc;

use super::codec_pref::CodecSet;
use super::keyframe::{KeyframeAsk, KeyframeLimiter};
use super::reorder::{Pushed, Reorder};
use super::rtp::h264::H264Depacketizer;
use super::rtp::vp8::Vp8Depacketizer;
use super::rtp::{Frame, RtpIn};
use super::types::{
    VideoCodec, VideoFrame, VideoLayerInfo, VideoPause, VideoRecvItem, VideoSinkSpec, VideoSource,
    VideoTrack, VideoTrackView,
};
use crate::call::{CallCounters, CallEvent, Cmd};
use crate::e2ee::{CryptoError, KeySession};

/// Sink changes reach the server at most this often (the first sink of a track and the last
/// one closing go at once).
pub(crate) const SETTINGS_DEBOUNCE: Duration = Duration::from_millis(250);

/// The receive side's queue (one consumer), [`crate::Call::video_frames`].
#[derive(Debug)]
pub struct VideoFrameStream(pub(crate) mpsc::Receiver<VideoRecvItem>);

impl VideoFrameStream {
    /// The next item; `None` once the call ended.
    pub async fn recv(&mut self) -> Option<VideoRecvItem> {
        self.0.recv().await
    }

    /// The next item if one is waiting.
    pub fn try_recv(&mut self) -> Option<VideoRecvItem> {
        self.0.try_recv().ok()
    }
}

/// A sink command, from [`VideoSink`] to the engine.
#[derive(Debug)]
pub(crate) enum SinkCmd {
    Open {
        id: u64,
        track_sid: String,
        spec: VideoSinkSpec,
    },
    Update {
        id: u64,
        spec: VideoSinkSpec,
    },
    Keyframe {
        id: u64,
    },
    Close {
        id: u64,
    },
}

/// One open sink of a remote video track ([`crate::Call::video_sink`]): while it is open (and
/// visible) the track's frames flow; dropping it closes it.
///
/// This is the engine's own sink API, enough to drive the server's settings; the Tauri
/// plugin's sinks are built on it.
#[derive(Debug)]
pub struct VideoSink {
    pub(crate) id: u64,
    pub(crate) cmd: mpsc::UnboundedSender<Cmd>,
}

impl VideoSink {
    /// A new size, visibility or tile kind (debounced by 250 ms toward the server).
    pub fn update(&self, spec: VideoSinkSpec) {
        let _ = self
            .cmd
            .send(Cmd::Video(SinkCmd::Update { id: self.id, spec }));
    }

    /// The host's decoder needs a keyframe (a decode error): a PLI goes out, rate-limited.
    pub fn request_keyframe(&self) {
        let _ = self.cmd.send(Cmd::Video(SinkCmd::Keyframe { id: self.id }));
    }

    /// Closes the sink (as dropping it does).
    pub fn close(self) {}
}

impl Drop for VideoSink {
    fn drop(&mut self) {
        let _ = self.cmd.send(Cmd::Video(SinkCmd::Close { id: self.id }));
    }
}

/// What [`Subscriptions`] asks the engine to do.
#[derive(Debug, Default)]
pub(crate) struct Out {
    pub(crate) requests: Vec<SignalRequest>,
    /// `(ssrc, fir)`: a keyframe request on the PC.
    pub(crate) keyframes: Vec<(u32, bool)>,
    pub(crate) items: Vec<VideoRecvItem>,
    pub(crate) events: Vec<CallEvent>,
    /// Tracks that stalled (`video_stalled`): their sids.
    pub(crate) stalled: Vec<String>,
}

/// The settings one track asks of the server.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Settings {
    pub(crate) disabled: bool,
    pub(crate) width: u32,
    pub(crate) height: u32,
    pub(crate) fps: u32,
    pub(crate) priority: u32,
}

impl Settings {
    const DISABLED: Settings = Settings {
        disabled: true,
        width: 0,
        height: 0,
        fps: 0,
        priority: 0,
    };
}

/// The settings for a track's sinks: no visible sink → disabled; otherwise the largest
/// visible sink's size, 30 fps for a large tile and 15 for a grid tile, and a priority with
/// screens above cameras and the active speaker above the others.
pub(crate) fn settings_for<'a>(
    sinks: impl Iterator<Item = &'a VideoSinkSpec>,
    source: VideoSource,
    speaking: bool,
) -> Settings {
    let mut s = Settings::DISABLED;
    for k in sinks.filter(|k| k.visible) {
        s.disabled = false;
        s.width = s.width.max(k.width);
        s.height = s.height.max(k.height);
        s.fps = s.fps.max(if k.large { 30 } else { 15 });
    }
    if !s.disabled {
        let base = match source {
            VideoSource::ScreenShare => 2,
            VideoSource::Camera => 0,
        };
        s.priority = base + u32::from(speaking);
    }
    s
}

/// One received packet, held in the reorder buffer.
#[derive(Debug)]
struct Pkt {
    seq: u64,
    timestamp: u32,
    marker: bool,
    payload: Arc<[u8]>,
    at: Instant,
}

#[derive(Debug)]
enum Depack {
    Vp8(Vp8Depacketizer),
    H264(H264Depacketizer),
}

impl Depack {
    fn new(codec: VideoCodec) -> Depack {
        match codec {
            VideoCodec::Vp8 => Depack::Vp8(Vp8Depacketizer::new()),
            VideoCodec::H264 => Depack::H264(H264Depacketizer::new()),
        }
    }

    fn codec(&self) -> VideoCodec {
        match self {
            Depack::Vp8(_) => VideoCodec::Vp8,
            Depack::H264(_) => VideoCodec::H264,
        }
    }

    fn push(&mut self, p: RtpIn<'_>) -> Option<Frame> {
        match self {
            Depack::Vp8(d) => d.push(p),
            Depack::H264(d) => d.push(p),
        }
    }

    fn dropped(&self) -> u64 {
        match self {
            Depack::Vp8(d) => d.dropped(),
            Depack::H264(d) => d.dropped(),
        }
    }
}

/// One remote video track.
#[derive(Debug)]
struct Track {
    info: VideoTrack,
    participant_sid: String,
    ssrc: Option<u32>,
    reorder: Reorder<Pkt>,
    depack: Option<Depack>,
    /// Frames flow to the host (a sink is open and `Added` went out).
    flowing: bool,
    /// Frames are dropped until a keyframe (a loss, a decrypt failure, a new sink).
    need_key: bool,
    kf: KeyframeLimiter,
    sent: Option<Settings>,
    settings_due: Option<Instant>,
    /// A packet arrived: `info.codec` is its payload type's, no longer `TrackInfo`'s.
    codec_from_pt: bool,
}

impl Track {
    fn new(info: VideoTrack, participant_sid: String) -> Track {
        Track {
            info,
            participant_sid,
            ssrc: None,
            reorder: Reorder::new(),
            depack: None,
            flowing: false,
            need_key: true,
            kf: KeyframeLimiter::new(),
            sent: None,
            settings_due: None,
            codec_from_pt: false,
        }
    }

    /// Asks for a keyframe (and tells the host, once per wait).
    fn want_key(&mut self, out: &mut Out) {
        if !self.kf.waiting() && self.flowing {
            out.items.push(VideoRecvItem::KeyframeNeeded {
                track: self.info.id,
            });
        }
        self.kf.request();
    }

    /// Frames were lost or failed: the host resets, frames wait for a keyframe.
    fn broken(&mut self, out: &mut Out) {
        if !self.need_key && self.flowing {
            out.items.push(VideoRecvItem::Broken {
                track: self.info.id,
            });
        }
        self.need_key = true;
        self.want_key(out);
    }
}

fn source_of(t: &TrackInfo) -> Option<VideoSource> {
    if t.r#type != TrackType::Video as i32 {
        return None;
    }
    Some(if t.source == TrackSource::ScreenShare as i32 {
        VideoSource::ScreenShare
    } else {
        VideoSource::Camera
    })
}

/// The codecs a publisher's `TrackInfo` names, in its order: its mime type (the primary), then
/// each of its `codecs` (the primary and the backups), once each.
fn codecs_of(t: &TrackInfo) -> Vec<VideoCodec> {
    let mut v = Vec::new();
    let named =
        std::iter::once(t.mime_type.as_str()).chain(t.codecs.iter().map(|c| c.mime_type.as_str()));
    for c in named.filter_map(VideoCodec::from_mime) {
        if !v.contains(&c) {
            v.push(c);
        }
    }
    v
}

/// The codec a subscriber with the media connection's codecs `decode` sees before the first
/// packet, and whether it can receive none of them (`unsupported`): the first of the
/// publisher's codecs in `decode`, else (none of them) the primary, `unsupported`. `(None,
/// false)` when `TrackInfo` names no codec.
fn codec_for(t: &TrackInfo, decode: CodecSet) -> (Option<VideoCodec>, bool) {
    let named = codecs_of(t);
    match named.iter().find(|c| decode.contains(**c)) {
        Some(c) => (Some(*c), false),
        None => (named.first().copied(), !named.is_empty()),
    }
}

/// The publisher's layers: its codec's (`TrackInfo.codecs`), else the older `layers` field.
fn layers_of(t: &TrackInfo) -> Vec<VideoLayerInfo> {
    let layers = match t.codecs.iter().find(|c| !c.layers.is_empty()) {
        Some(c) => &c.layers,
        #[allow(deprecated)]
        None => &t.layers,
    };
    let mut v: Vec<VideoLayerInfo> = layers
        .iter()
        .map(|l| VideoLayerInfo {
            width: l.width,
            height: l.height,
            bitrate: l.bitrate,
        })
        .collect();
    v.sort_by_key(|l| (l.height, l.width));
    v
}

fn request(m: signal_request::Message) -> SignalRequest {
    SignalRequest { message: Some(m) }
}

fn settings_request(sid: &str, s: Settings) -> SignalRequest {
    request(signal_request::Message::TrackSetting(UpdateTrackSettings {
        track_sids: vec![sid.to_owned()],
        disabled: s.disabled,
        width: s.width,
        height: s.height,
        fps: s.fps,
        priority: s.priority,
        ..UpdateTrackSettings::default()
    }))
}

/// The receive side's state.
#[derive(Debug)]
pub(crate) struct Subscriptions {
    epoch: Instant,
    tracks: BTreeMap<String, Track>,
    next_id: u64,
    /// Sink id → (track sid, spec).
    sinks: HashMap<u64, (String, VideoSinkSpec)>,
    /// Participant sids speaking now (the server's speaker list).
    speaking: HashSet<String>,
    /// The codecs the media connection receives (`TrackInfo`'s codecs are matched to it).
    decode: CodecSet,
}

impl Subscriptions {
    pub(crate) fn new(epoch: Instant) -> Subscriptions {
        Subscriptions {
            epoch,
            tracks: BTreeMap::new(),
            next_id: 1,
            sinks: HashMap::new(),
            speaking: HashSet::new(),
            decode: CodecSet::ALL,
        }
    }

    /// The same, for a media connection that receives `decode` only.
    pub(crate) fn decoding(mut self, decode: CodecSet) -> Subscriptions {
        self.decode = decode;
        self
    }

    /// A participant's camera and screen for the snapshot.
    pub(crate) fn views(&self, identity: &str) -> (Option<VideoTrackView>, Option<VideoTrackView>) {
        let mut camera = None;
        let mut screen = None;
        for t in self.tracks.values().filter(|t| t.info.identity == identity) {
            match t.info.source {
                VideoSource::Camera => camera = camera.or(Some(t.info.view())),
                VideoSource::ScreenShare => screen = screen.or(Some(t.info.view())),
            }
        }
        (camera, screen)
    }

    /// The roster changed: new video tracks are announced (and disabled at the server until a
    /// sink opens), changed ones re-announced, gone ones removed.
    pub(crate) fn roster(
        &mut self,
        now: Instant,
        remotes: &BTreeMap<String, ParticipantInfo>,
        members: &HashMap<String, String>,
        out: &mut Out,
    ) {
        let mut live = HashSet::new();
        let decode = self.decode;
        for p in remotes.values() {
            for t in &p.tracks {
                let Some(source) = source_of(t) else {
                    continue;
                };
                live.insert(t.sid.clone());
                let member_id = members.get(&p.identity).cloned();
                match self.tracks.get_mut(&t.sid) {
                    None => {
                        let id = self.next_id;
                        self.next_id += 1;
                        let (codec, unsupported) = codec_for(t, decode);
                        let info = VideoTrack {
                            id,
                            identity: p.identity.clone(),
                            member_id,
                            source,
                            track_sid: t.sid.clone(),
                            codec,
                            width: t.width,
                            height: t.height,
                            muted: t.muted,
                            paused: None,
                            layers: layers_of(t),
                            unsupported,
                        };
                        out.events.push(CallEvent::VideoAdded(info.clone()));
                        // No video flows to a member who shows no tile.
                        out.requests
                            .push(settings_request(&t.sid, Settings::DISABLED));
                        let mut track = Track::new(info, p.sid.clone());
                        track.sent = Some(Settings::DISABLED);
                        self.tracks.insert(t.sid.clone(), track);
                        // Sinks opened before the roster named the track.
                        if self.sinks.values().any(|(s, _)| *s == t.sid) {
                            self.sinks_changed(now, &t.sid, out);
                        }
                    }
                    Some(track) => {
                        let mut info = track.info.clone();
                        info.member_id = member_id.or(info.member_id);
                        info.muted = t.muted;
                        info.width = t.width;
                        info.height = t.height;
                        info.layers = layers_of(t);
                        if !track.codec_from_pt {
                            // Before the first packet: the publisher's codecs may change (a
                            // backup added).
                            let (codec, unsupported) = codec_for(t, decode);
                            info.codec = codec.or(info.codec);
                            info.unsupported = unsupported;
                        }
                        track.participant_sid = p.sid.clone();
                        if info != track.info {
                            track.info = info.clone();
                            out.events.push(CallEvent::VideoChanged(info));
                        }
                    }
                }
            }
        }
        let gone: Vec<String> = self
            .tracks
            .keys()
            .filter(|k| !live.contains(*k))
            .cloned()
            .collect();
        for sid in gone {
            if let Some(t) = self.tracks.remove(&sid) {
                if t.flowing {
                    out.items.push(VideoRecvItem::Removed { track: t.info.id });
                }
                out.events.push(CallEvent::VideoRemoved {
                    id: t.info.id,
                    track_sid: sid,
                });
            }
        }
    }

    /// The server's speaker list (participant sids): priorities follow it.
    pub(crate) fn speakers(&mut self, now: Instant, speaking: HashSet<String>, out: &mut Out) {
        if speaking == self.speaking {
            return;
        }
        self.speaking = speaking;
        let sids: Vec<String> = self
            .tracks
            .iter()
            .filter(|(_, t)| t.enabled())
            .map(|(s, _)| s.clone())
            .collect();
        for sid in sids {
            self.schedule(now, &sid, false, out);
        }
    }

    /// The server's stream states: a paused track is shown paused (congestion).
    pub(crate) fn stream_states(&mut self, states: &[StreamStateInfo], out: &mut Out) {
        for s in states {
            let Some(t) = self.tracks.get_mut(&s.track_sid) else {
                continue;
            };
            let paused = (s.state == StreamState::Paused as i32).then_some(VideoPause::Congestion);
            if t.info.paused != paused {
                t.info.paused = paused;
                out.events.push(CallEvent::VideoChanged(t.info.clone()));
            }
        }
    }

    /// A sink command from the host.
    pub(crate) fn sink(&mut self, now: Instant, cmd: SinkCmd, out: &mut Out) {
        match cmd {
            SinkCmd::Open {
                id,
                track_sid,
                spec,
            } => {
                self.sinks.insert(id, (track_sid.clone(), spec));
                self.sinks_changed(now, &track_sid, out);
            }
            SinkCmd::Update { id, spec } => {
                let Some((sid, s)) = self.sinks.get_mut(&id) else {
                    return;
                };
                *s = spec;
                let sid = sid.clone();
                self.sinks_changed(now, &sid, out);
            }
            SinkCmd::Keyframe { id } => {
                let Some((sid, _)) = self.sinks.get(&id) else {
                    return;
                };
                if let Some(t) = self.tracks.get_mut(sid)
                    && t.flowing
                {
                    t.want_key(out);
                }
            }
            SinkCmd::Close { id } => {
                if let Some((sid, _)) = self.sinks.remove(&id) {
                    self.sinks_changed(now, &sid, out);
                }
            }
        }
    }

    fn sinks_of<'a>(&'a self, sid: &'a str) -> impl Iterator<Item = &'a VideoSinkSpec> + 'a {
        self.sinks
            .values()
            .filter(move |(s, _)| s == sid)
            .map(|(_, spec)| spec)
    }

    /// A track's sinks changed: frames start (the first visible sink) or stop (none left), and
    /// its settings follow.
    fn sinks_changed(&mut self, now: Instant, sid: &str, out: &mut Out) {
        let want = self.sinks_of(sid).any(|k| k.visible);
        let Some(t) = self.tracks.get_mut(sid) else {
            return;
        };
        match (t.flowing, want) {
            (false, true) => {
                t.flowing = true;
                t.need_key = true;
                out.items.push(VideoRecvItem::Added {
                    track: t.info.id,
                    codec: t
                        .depack
                        .as_ref()
                        .map_or(t.info.codec.unwrap_or(VideoCodec::Vp8), Depack::codec),
                });
                t.want_key(out);
                self.schedule(now, sid, true, out);
            }
            (true, false) => {
                t.flowing = false;
                t.kf.cancel();
                t.reorder.reset();
                t.depack = None;
                out.items.push(VideoRecvItem::Removed { track: t.info.id });
                self.schedule(now, sid, true, out);
            }
            _ => self.schedule(now, sid, false, out),
        }
    }

    /// Sends the track's settings now (`at_once`) or after the debounce.
    fn schedule(&mut self, now: Instant, sid: &str, at_once: bool, out: &mut Out) {
        if at_once {
            if let Some(t) = self.tracks.get_mut(sid) {
                t.settings_due = None;
            }
            self.send_settings(sid, out);
        } else if let Some(t) = self.tracks.get_mut(sid) {
            t.settings_due.get_or_insert(now + SETTINGS_DEBOUNCE);
        }
    }

    fn send_settings(&mut self, sid: &str, out: &mut Out) {
        let Some(t) = self.tracks.get(sid) else {
            return;
        };
        let speaking = self.speaking.contains(&t.participant_sid);
        let s = settings_for(self.sinks_of(sid), t.info.source, speaking);
        if let Some(t) = self.tracks.get_mut(sid)
            && t.sent != Some(s)
        {
            t.sent = Some(s);
            out.requests.push(settings_request(sid, s));
        }
    }

    /// Sends every track's settings again (after a reconnect the server may hold none).
    pub(crate) fn resend_settings(&mut self, out: &mut Out) {
        let sids: Vec<String> = self.tracks.keys().cloned().collect();
        for sid in sids {
            if let Some(t) = self.tracks.get_mut(&sid) {
                t.sent = None;
                t.settings_due = None;
            }
            self.send_settings(&sid, out);
        }
    }

    /// The round-trip time: each reorder window is the larger of 150 ms and twice it.
    pub(crate) fn set_rtt(&mut self, rtt: Duration) {
        for t in self.tracks.values_mut() {
            t.reorder.set_rtt(rtt);
        }
    }

    /// A new PC (a full reconnect): the streams start over; flowing tracks wait for a keyframe.
    pub(crate) fn media_reset(&mut self, out: &mut Out) {
        for t in self.tracks.values_mut() {
            t.ssrc = None;
            t.reorder.reset();
            t.depack = None;
            t.kf.cancel();
            if t.flowing {
                t.broken(out);
            }
        }
    }

    /// The media resumed (a resume from background or a network change): flowing tracks ask
    /// for a keyframe.
    pub(crate) fn resumed(&mut self, out: &mut Out) {
        for t in self.tracks.values_mut().filter(|t| t.flowing) {
            t.want_key(out);
        }
    }

    /// One RTP packet of `track_sid` (from `identity`, allowed by the keys).
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn on_rtp(
        &mut self,
        now: Instant,
        track_sid: &str,
        identity: &str,
        r: &crate::pc::RtpRx,
        codec: VideoCodec,
        keys: &dyn KeySession,
        counters: &mut CallCounters,
        out: &mut Out,
    ) {
        let Some(t) = self.tracks.get_mut(track_sid) else {
            counters.video_packets_unwanted += 1;
            return;
        };
        t.codec_from_pt = true;
        if t.info.codec != Some(codec) || t.info.unsupported {
            // The negotiated payload type says what the publisher sends (and that it arrives).
            t.info.codec = Some(codec);
            t.info.unsupported = false;
            out.events.push(CallEvent::VideoChanged(t.info.clone()));
        }
        if !t.flowing {
            // No sink: nothing is forwarded (the server was asked to disable the track).
            counters.video_packets_unwanted += 1;
            return;
        }
        if t.ssrc != Some(r.ssrc) || t.depack.as_ref().map(Depack::codec) != Some(codec) {
            // A new stream (a layer switch keeps the SSRC; a new publication or PC does not).
            if t.ssrc.is_some() {
                t.reorder.reset();
            }
            t.ssrc = Some(r.ssrc);
            t.depack = Some(Depack::new(codec));
        }
        let mut ready = Vec::new();
        let skipped = t.reorder.skipped;
        let pushed = t.reorder.push(
            r.seq,
            now,
            Pkt {
                seq: r.seq,
                timestamp: r.timestamp,
                marker: r.marker,
                payload: r.payload.clone(),
                at: now,
            },
            &mut ready,
        );
        if pushed == Pushed::Late {
            counters.video_packets_late += 1;
        }
        Self::gap_skipped(t, skipped, counters, out);
        let epoch = self.epoch;
        for p in ready {
            Self::depacketise(epoch, t, p, identity, keys, counters, out);
        }
    }

    /// The reorder buffer skipped packets (`skipped` was its count before): a gap the
    /// retransmissions did not fill. Whatever it held (part of a frame, or whole frames, which
    /// VP8's depacketiser cannot see when the gap ends on a frame boundary), the decoder's
    /// references are gone: the track breaks and waits for a keyframe.
    fn gap_skipped(t: &mut Track, skipped: u64, counters: &mut CallCounters, out: &mut Out) {
        if t.reorder.skipped > skipped {
            counters.video_packets_lost += t.reorder.skipped - skipped;
            t.broken(out);
        }
    }

    fn depacketise(
        epoch: Instant,
        t: &mut Track,
        p: Pkt,
        identity: &str,
        keys: &dyn KeySession,
        counters: &mut CallCounters,
        out: &mut Out,
    ) {
        let Some(d) = t.depack.as_mut() else {
            return;
        };
        let codec = d.codec();
        let before = d.dropped();
        let frame = d.push(RtpIn {
            seq: p.seq as u16,
            timestamp: p.timestamp,
            marker: p.marker,
            payload: &p.payload,
        });
        let lost = d.dropped() - before;
        if lost > 0 {
            // A gap the NACKs did not fill: the frame is gone, the decoder must wait for a
            // keyframe.
            counters.video_frames_dropped += lost;
            t.broken(out);
        }
        let Some(f) = frame else {
            return;
        };
        if t.need_key && !f.keyframe {
            counters.video_frames_dropped += 1;
            return;
        }
        let mut plain = Vec::with_capacity(f.data.len());
        match keys.decrypt_video(identity, codec, &f.data, &mut plain) {
            Ok(()) if !plain.is_empty() => {}
            Ok(()) => {
                counters.video_decrypt_failures += 1;
                t.broken(out);
                return;
            }
            Err(e) => {
                match e {
                    CryptoError::KeyPending => counters.video_frames_before_key += 1,
                    CryptoError::NoKey => counters.refused_frames += 1,
                    _ => counters.video_decrypt_failures += 1,
                }
                t.broken(out);
                return;
            }
        }
        let size = if f.keyframe {
            match codec {
                VideoCodec::Vp8 => super::size::vp8(&plain),
                VideoCodec::H264 => super::size::h264(&plain),
            }
        } else {
            None
        };
        if f.keyframe {
            t.need_key = false;
            t.kf.on_keyframe();
        }
        counters.video_frames_received += 1;
        out.items.push(VideoRecvItem::Frame(VideoFrame {
            track: t.info.id,
            codec,
            data: Bytes::from(plain),
            keyframe: f.keyframe,
            rtp_ts: f.timestamp,
            arrival_us: p.at.saturating_duration_since(epoch).as_micros() as u64,
            width: size.map(|s| s.0),
            height: size.map(|s| s.1),
        }));
    }

    /// The host's queue was full: the frame is gone, so the track waits for a keyframe.
    pub(crate) fn frame_not_delivered(&mut self, track: u64, out: &mut Out) {
        if let Some(t) = self.tracks.values_mut().find(|t| t.info.id == track) {
            t.broken(out);
        }
    }

    /// Time passed: gaps skipped, keyframe requests sent, settings flushed.
    pub(crate) fn tick(
        &mut self,
        now: Instant,
        keys: Option<&dyn KeySession>,
        counters: &mut CallCounters,
        out: &mut Out,
    ) {
        let epoch = self.epoch;
        let due: Vec<String> = self
            .tracks
            .iter()
            .filter(|(_, t)| t.settings_due.is_some_and(|d| d <= now))
            .map(|(s, _)| s.clone())
            .collect();
        for sid in due {
            if let Some(t) = self.tracks.get_mut(&sid) {
                t.settings_due = None;
            }
            self.send_settings(&sid, out);
        }
        for (sid, t) in self.tracks.iter_mut() {
            if !t.flowing {
                continue;
            }
            let mut ready = Vec::new();
            let skipped = t.reorder.skipped;
            t.reorder.poll(now, &mut ready);
            Self::gap_skipped(t, skipped, counters, out);
            if !ready.is_empty()
                && let Some(keys) = keys
            {
                // The track's publisher is the frames' sender.
                let identity = t.info.identity.clone();
                for p in ready {
                    Self::depacketise(epoch, t, p, &identity, keys, counters, out);
                }
            }
            let Some(ssrc) = t.ssrc else {
                continue;
            };
            let d = t.kf.poll(now);
            match d.ask {
                Some(KeyframeAsk::Pli) => {
                    counters.video_plis += 1;
                    out.keyframes.push((ssrc, false));
                }
                Some(KeyframeAsk::Fir) => {
                    counters.video_firs += 1;
                    out.keyframes.push((ssrc, true));
                }
                None => {}
            }
            if d.stalled {
                out.stalled.push(sid.clone());
            }
        }
    }

    /// When [`Subscriptions::tick`] next has something to do.
    pub(crate) fn deadline(&self) -> Option<Instant> {
        let mut d: Option<Instant> = None;
        for t in self.tracks.values() {
            let mut take = |x: Option<Instant>| {
                if let Some(x) = x {
                    d = Some(d.map_or(x, |y| y.min(x)));
                }
            };
            take(t.settings_due);
            if t.flowing {
                take(t.reorder.deadline());
                if t.ssrc.is_some() {
                    take(t.kf.deadline());
                }
            }
        }
        d
    }
}

impl Track {
    /// Whether the server was last asked to send the track (its priority can change).
    fn enabled(&self) -> bool {
        self.sent.is_some_and(|s| !s.disabled)
    }
}

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

    fn sink(w: u32, h: u32, large: bool, visible: bool) -> VideoSinkSpec {
        VideoSinkSpec::new(w, h, large).visible(visible)
    }

    #[test]
    fn no_visible_sink_disables_the_track() {
        assert_eq!(
            settings_for([].iter(), VideoSource::Camera, false),
            Settings::DISABLED
        );
        let hidden = [sink(640, 360, true, false)];
        assert!(settings_for(hidden.iter(), VideoSource::Camera, true).disabled);
    }

    #[test]
    fn the_largest_visible_sink_sets_the_size_and_a_large_tile_30_fps() {
        let sinks = [
            sink(320, 180, false, true),
            sink(1280, 720, true, false),
            sink(640, 400, false, true),
        ];
        let s = settings_for(sinks.iter(), VideoSource::Camera, false);
        assert_eq!(
            s,
            Settings {
                disabled: false,
                width: 640,
                height: 400,
                fps: 15,
                priority: 0
            }
        );
        let sinks = [sink(320, 180, false, true), sink(960, 540, true, true)];
        let s = settings_for(sinks.iter(), VideoSource::Camera, false);
        assert_eq!((s.width, s.height, s.fps), (960, 540, 30));
    }

    #[test]
    fn screens_rank_above_cameras_and_the_speaker_above_others() {
        let sinks = [sink(320, 180, false, true)];
        let cam = settings_for(sinks.iter(), VideoSource::Camera, false).priority;
        let cam_speaking = settings_for(sinks.iter(), VideoSource::Camera, true).priority;
        let screen = settings_for(sinks.iter(), VideoSource::ScreenShare, false).priority;
        assert!(cam_speaking > cam);
        assert!(screen > cam_speaking);
    }

    fn camera(sid: &str, muted: bool) -> TrackInfo {
        TrackInfo {
            sid: sid.to_owned(),
            r#type: TrackType::Video as i32,
            source: TrackSource::Camera as i32,
            mime_type: "video/VP8".to_owned(),
            width: 1280,
            height: 720,
            muted,
            ..TrackInfo::default()
        }
    }

    fn roster(tracks: Vec<TrackInfo>) -> BTreeMap<String, ParticipantInfo> {
        let mut m = BTreeMap::new();
        m.insert(
            "PA_a".to_owned(),
            ParticipantInfo {
                sid: "PA_a".to_owned(),
                identity: "p_a".to_owned(),
                tracks,
                ..ParticipantInfo::default()
            },
        );
        m
    }

    fn setting(r: &SignalRequest) -> Option<&UpdateTrackSettings> {
        match &r.message {
            Some(signal_request::Message::TrackSetting(s)) => Some(s),
            _ => None,
        }
    }

    #[test]
    fn a_new_track_is_announced_and_disabled_until_a_sink_opens() {
        let t0 = Instant::now();
        let mut s = Subscriptions::new(t0);
        let mut out = Out::default();
        s.roster(
            t0,
            &roster(vec![camera("TR_c", false)]),
            &HashMap::new(),
            &mut out,
        );
        assert!(
            matches!(&out.events[..], [CallEvent::VideoAdded(v)] if v.track_sid == "TR_c"
            && v.codec == Some(VideoCodec::Vp8) && v.source == VideoSource::Camera)
        );
        let u = setting(&out.requests[0]).unwrap();
        assert!(u.disabled);
        assert_eq!(u.track_sids, vec!["TR_c".to_owned()]);
        assert!(out.items.is_empty(), "nothing flows without a sink");
        // The first sink: frames start (Added, a keyframe asked) and the track is enabled now.
        let mut out = Out::default();
        s.sink(
            t0,
            SinkCmd::Open {
                id: 1,
                track_sid: "TR_c".to_owned(),
                spec: VideoSinkSpec::new(640, 360, false),
            },
            &mut out,
        );
        assert!(matches!(
            out.items[0],
            VideoRecvItem::Added {
                codec: VideoCodec::Vp8,
                ..
            }
        ));
        assert!(matches!(out.items[1], VideoRecvItem::KeyframeNeeded { .. }));
        let u = setting(&out.requests[0]).unwrap();
        assert!(!u.disabled);
        assert_eq!((u.width, u.height, u.fps), (640, 360, 15));
        // A resize is debounced 250 ms.
        let mut out = Out::default();
        s.sink(
            t0,
            SinkCmd::Update {
                id: 1,
                spec: VideoSinkSpec::new(1280, 720, true),
            },
            &mut out,
        );
        assert!(out.requests.is_empty());
        assert_eq!(s.deadline(), Some(t0 + SETTINGS_DEBOUNCE));
        let mut c = CallCounters::default();
        let mut out = Out::default();
        s.tick(t0 + SETTINGS_DEBOUNCE, None, &mut c, &mut out);
        let u = setting(&out.requests[0]).unwrap();
        assert_eq!((u.width, u.height, u.fps), (1280, 720, 30));
        // The last sink closes: frames stop and the track is disabled at once.
        let mut out = Out::default();
        s.sink(t0, SinkCmd::Close { id: 1 }, &mut out);
        assert!(matches!(out.items[..], [VideoRecvItem::Removed { .. }]));
        assert!(setting(&out.requests[0]).unwrap().disabled);
    }

    #[test]
    fn mute_size_and_congestion_are_changes_and_a_gone_track_is_removed() {
        let t0 = Instant::now();
        let mut s = Subscriptions::new(t0);
        let mut out = Out::default();
        s.roster(
            t0,
            &roster(vec![camera("TR_c", false)]),
            &HashMap::new(),
            &mut out,
        );
        let mut out = Out::default();
        s.roster(
            t0,
            &roster(vec![camera("TR_c", true)]),
            &HashMap::new(),
            &mut out,
        );
        assert!(matches!(&out.events[..], [CallEvent::VideoChanged(v)] if v.muted));
        let mut out = Out::default();
        s.stream_states(
            &[StreamStateInfo {
                participant_sid: "PA_a".to_owned(),
                track_sid: "TR_c".to_owned(),
                state: StreamState::Paused as i32,
            }],
            &mut out,
        );
        assert!(
            matches!(&out.events[..], [CallEvent::VideoChanged(v)] if v.paused == Some(VideoPause::Congestion))
        );
        assert_eq!(
            s.views("p_a").0.unwrap().paused,
            Some(VideoPause::Congestion)
        );
        let mut out = Out::default();
        s.roster(t0, &roster(vec![]), &HashMap::new(), &mut out);
        assert!(
            matches!(&out.events[..], [CallEvent::VideoRemoved { track_sid, .. }] if track_sid == "TR_c")
        );
        assert_eq!(s.views("p_a"), (None, None));
    }

    /// Keys that hand every frame back as it is (a unit test of the pipeline's bookkeeping;
    /// the engine's keys are never this).
    struct EchoKeys;

    impl KeySession for EchoKeys {
        fn encrypt(&self, _: &[u8], _: u32, _: u32, _: &mut Vec<u8>) -> Result<(), CryptoError> {
            Err(CryptoError::NoSendKey)
        }
        fn decrypt(&self, _: &str, _: &[u8], _: &mut Vec<u8>) -> Result<(), CryptoError> {
            Err(CryptoError::NoKey)
        }
        fn decrypt_video(
            &self,
            _: &str,
            _: VideoCodec,
            frame: &[u8],
            out: &mut Vec<u8>,
        ) -> Result<(), CryptoError> {
            out.extend_from_slice(frame);
            Ok(())
        }
        fn may_subscribe(&self, _: &str, _: &crate::e2ee::RemoteTrack) -> crate::e2ee::Subscribe {
            crate::e2ee::Subscribe::Yes
        }
        fn close(&self) -> crate::provider::BoxFuture<'_, ()> {
            Box::pin(async {})
        }
    }

    /// One single-packet VP8 frame: the descriptor (S, PID 0), then a keyframe or delta tag.
    fn vp8_packet(seq: u64, key: bool) -> crate::pc::RtpRx {
        let mut payload = vec![0x10, if key { 0x00 } else { 0x01 }];
        payload.extend_from_slice(&[0x9d, 0x01, 0x2a, 0x40, 0x01, 0xb4, 0x00, 0x55, 0x55]);
        crate::pc::RtpRx {
            mid: "1".to_owned(),
            ssrc: 7,
            seq,
            timestamp: seq as u32 * 3_000,
            marker: true,
            video: Some(VideoCodec::Vp8),
            payload: Arc::from(payload),
        }
    }

    #[test]
    fn whole_frames_lost_on_a_frame_boundary_break_the_track() {
        let t0 = Instant::now();
        let mut s = Subscriptions::new(t0);
        let mut out = Out::default();
        s.roster(
            t0,
            &roster(vec![camera("TR_c", false)]),
            &HashMap::new(),
            &mut out,
        );
        s.sink(
            t0,
            SinkCmd::Open {
                id: 1,
                track_sid: "TR_c".to_owned(),
                spec: VideoSinkSpec::new(640, 360, false),
            },
            &mut out,
        );
        let mut c = CallCounters::default();
        let rx = |s: &mut Subscriptions, seq, key, at, out: &mut Out, c: &mut CallCounters| {
            let r = vp8_packet(seq, key);
            s.on_rtp(at, "TR_c", "p_a", &r, VideoCodec::Vp8, &EchoKeys, c, out);
        };
        let mut out = Out::default();
        rx(&mut s, 10, true, t0, &mut out, &mut c);
        rx(&mut s, 11, false, t0, &mut out, &mut c);
        let frames = |o: &Out| {
            o.items
                .iter()
                .filter(|i| matches!(i, VideoRecvItem::Frame(_)))
                .count()
        };
        assert_eq!(frames(&out), 2);
        // Packets 12..=14 (three whole frames) never arrive; 15 waits the window, then the gap
        // is skipped: the track breaks, and the delta frames after it are not handed out.
        let mut out = Out::default();
        rx(&mut s, 15, false, t0, &mut out, &mut c);
        assert_eq!(frames(&out), 0, "held for the gap");
        s.tick(
            t0 + Duration::from_millis(200),
            Some(&EchoKeys),
            &mut c,
            &mut out,
        );
        assert!(
            out.items
                .iter()
                .any(|i| matches!(i, VideoRecvItem::Broken { .. })),
            "{:?}",
            out.items
        );
        assert_eq!(frames(&out), 0, "a delta frame after the loss");
        assert_eq!(c.video_packets_lost, 3);
        let mut out = Out::default();
        rx(
            &mut s,
            16,
            true,
            t0 + Duration::from_millis(210),
            &mut out,
            &mut c,
        );
        assert_eq!(frames(&out), 1, "the keyframe restarts the track");
    }

    /// A track with frames 10 (key) and 11 delivered, then packets 12..=14 lost and packet 15
    /// (`key15`) received, then one tick 200 ms later (the reorder window has passed): what that
    /// tick sent and handed out, with the counters.
    fn break_then(key15: bool) -> (Out, CallCounters) {
        let t0 = Instant::now();
        let mut s = Subscriptions::new(t0);
        let mut out = Out::default();
        s.roster(
            t0,
            &roster(vec![camera("TR_c", false)]),
            &HashMap::new(),
            &mut out,
        );
        s.sink(
            t0,
            SinkCmd::Open {
                id: 1,
                track_sid: "TR_c".to_owned(),
                spec: VideoSinkSpec::new(640, 360, false),
            },
            &mut out,
        );
        let mut c = CallCounters::default();
        let mut out = Out::default();
        for (seq, key) in [(10, true), (11, false), (15, key15)] {
            let r = vp8_packet(seq, key);
            s.on_rtp(
                t0,
                "TR_c",
                "p_a",
                &r,
                VideoCodec::Vp8,
                &EchoKeys,
                &mut c,
                &mut out,
            );
        }
        let plis_before = c.video_plis;
        let mut out = Out::default();
        s.tick(
            t0 + Duration::from_millis(200),
            Some(&EchoKeys),
            &mut c,
            &mut out,
        );
        assert!(
            out.items
                .iter()
                .any(|i| matches!(i, VideoRecvItem::Broken { .. })),
            "the loss breaks the track: {:?}",
            out.items
        );
        c.video_plis -= plis_before;
        (out, c)
    }

    /// The loss breaks the track and no keyframe follows: a PLI goes out in the same tick.
    #[test]
    fn a_break_without_a_keyframe_sends_a_pli() {
        let (out, c) = break_then(false);
        assert_eq!(c.video_plis, 1);
        assert_eq!(out.keyframes, vec![(7, false)]);
        assert!(
            !out.items
                .iter()
                .any(|i| matches!(i, VideoRecvItem::Frame(_))),
            "a delta frame after the loss is not handed out"
        );
    }

    /// The packet after the loss starts a keyframe: the track restarts on it in the same tick,
    /// and no PLI goes out (none is needed).
    #[test]
    fn a_keyframe_right_after_the_break_sends_no_pli() {
        let (out, c) = break_then(true);
        assert_eq!(c.video_plis, 0);
        assert!(out.keyframes.is_empty(), "{:?}", out.keyframes);
        assert!(
            out.items
                .iter()
                .any(|i| matches!(i, VideoRecvItem::Frame(f) if f.keyframe)),
            "the keyframe restarts the track: {:?}",
            out.items
        );
    }

    /// A camera whose `TrackInfo` names `primary`, then `codecs` (the simulcast codecs).
    fn camera_in(sid: &str, primary: &str, codecs: &[&str]) -> TrackInfo {
        let mut t = camera(sid, false);
        t.mime_type = primary.to_owned();
        t.codecs = codecs
            .iter()
            .map(|m| sew_lkproto::livekit::SimulcastCodecInfo {
                mime_type: (*m).to_owned(),
                ..Default::default()
            })
            .collect();
        t
    }

    #[test]
    fn the_codec_before_the_first_packet_is_the_first_one_this_device_receives() {
        let both = camera_in("TR_c", "video/H264", &["video/H264", "video/VP8"]);
        let h264_only = camera_in("TR_c", "video/H264", &["video/H264"]);
        let named_none = camera_in("TR_c", "", &[]);
        assert_eq!(
            codecs_of(&both),
            vec![VideoCodec::H264, VideoCodec::Vp8],
            "the primary first, each once"
        );
        assert_eq!(
            codec_for(&both, CodecSet::ALL),
            (Some(VideoCodec::H264), false)
        );
        assert_eq!(
            codec_for(&both, CodecSet::VP8_ONLY),
            (Some(VideoCodec::Vp8), false),
            "the VP8 backup"
        );
        assert_eq!(
            codec_for(&h264_only, CodecSet::VP8_ONLY),
            (Some(VideoCodec::H264), true),
            "nothing this device receives"
        );
        assert_eq!(
            codec_for(&h264_only, CodecSet::ALL),
            (Some(VideoCodec::H264), false)
        );
        assert_eq!(codec_for(&named_none, CodecSet::VP8_ONLY), (None, false));
    }

    #[test]
    fn a_track_this_device_cannot_receive_is_unsupported_until_a_packet_arrives() {
        let t0 = Instant::now();
        let mut s = Subscriptions::new(t0).decoding(CodecSet::VP8_ONLY);
        let mut out = Out::default();
        let h264_only = camera_in("TR_c", "video/H264", &["video/H264"]);
        s.roster(t0, &roster(vec![h264_only]), &HashMap::new(), &mut out);
        assert!(
            matches!(&out.events[..], [CallEvent::VideoAdded(v)]
                if v.codec == Some(VideoCodec::H264) && v.unsupported),
            "{:?}",
            out.events
        );
        assert!(s.views("p_a").0.is_some_and(|v| v.unsupported));
        // The publisher adds a VP8 backup: the track turns to VP8, no longer unsupported.
        let mut out = Out::default();
        let both = camera_in("TR_c", "video/H264", &["video/H264", "video/VP8"]);
        s.roster(t0, &roster(vec![both]), &HashMap::new(), &mut out);
        assert!(
            matches!(&out.events[..], [CallEvent::VideoChanged(v)]
                if v.codec == Some(VideoCodec::Vp8) && !v.unsupported),
            "{:?}",
            out.events
        );
        // And back: H.264 only again is unsupported again (no packet yet).
        let mut out = Out::default();
        let h264_only = camera_in("TR_c", "video/H264", &["video/H264"]);
        s.roster(
            t0,
            &roster(vec![h264_only.clone()]),
            &HashMap::new(),
            &mut out,
        );
        assert!(
            matches!(&out.events[..], [CallEvent::VideoChanged(v)] if v.unsupported),
            "{:?}",
            out.events
        );
        // A packet arrives (its payload type is one the connection negotiated): its codec,
        // supported, and later rosters no longer move it.
        let mut out = Out::default();
        let mut c = CallCounters::default();
        let r = vp8_packet(1, true);
        s.on_rtp(
            t0,
            "TR_c",
            "p_a",
            &r,
            VideoCodec::Vp8,
            &EchoKeys,
            &mut c,
            &mut out,
        );
        assert!(
            matches!(&out.events[..], [CallEvent::VideoChanged(v)]
                if v.codec == Some(VideoCodec::Vp8) && !v.unsupported),
            "{:?}",
            out.events
        );
        let mut out = Out::default();
        s.roster(t0, &roster(vec![h264_only]), &HashMap::new(), &mut out);
        assert!(out.events.is_empty(), "{:?}", out.events);
    }

    #[test]
    fn with_h264_received_an_h264_primary_is_shown_as_h264() {
        let t0 = Instant::now();
        let mut s = Subscriptions::new(t0).decoding(CodecSet::ALL);
        let mut out = Out::default();
        let both = camera_in("TR_c", "video/H264", &["video/H264", "video/VP8"]);
        s.roster(t0, &roster(vec![both]), &HashMap::new(), &mut out);
        assert!(
            matches!(&out.events[..], [CallEvent::VideoAdded(v)]
                if v.codec == Some(VideoCodec::H264) && !v.unsupported),
            "{:?}",
            out.events
        );
    }
}