rtci 0.2.1

A sans-I/O WebRTC implementation: peer connections with ICE, DTLS-SRTP, SCTP data channels, RTP/RTCP and JSEP negotiation
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
use crate::peer_connection::event::{
    RTCEventInternal, RTCPeerConnectionEvent, TaggedRTCEventInternal,
};
use crate::peer_connection::message::internal::{
    RTCMessageInternal, RTPMessage, TaggedRTCMessageInternal,
};

use crate::peer_connection::cryptex::RTCRtpHeaderEncryptionPolicy;
use interceptor::Packet;
use log::{debug, warn};
use shared::error::{Error, Result};
use shared::marshal::{Marshal, Unmarshal};
use shared::util::is_rtcp;
use srtp::context::Context;
use srtp::cryptex::Cryptex;
use srtp::header_extension::EncryptedHeaderExtensions;
use std::collections::{HashSet, VecDeque};
use std::time::{Duration, Instant};

/// How long the inbound context of the association before a new one is kept, for packets
/// it protected that arrive late (RFC 5764 section 4.3).
pub(crate) const PREVIOUS_SRTP_KEYS_LINGER: Duration = Duration::from_secs(10);

/// How many inbound packets that fail authentication under the current keys are held while a
/// new DTLS association's keys are awaited (`SrtpHandlerContext::awaiting_new_keys`), and how
/// long each is held.
pub(crate) const MAX_HELD_INBOUND: usize = 256;
pub(crate) const HELD_INBOUND_FOR: Duration = Duration::from_secs(2);

/// An inbound SRTP or SRTCP packet held for the keys of the association being established.
pub(crate) struct HeldInbound {
    now: Instant,
    transport: shared::TransportContext,
    message: bytes::BytesMut,
    rtcp: bool,
}

#[derive(Default)]
pub(crate) struct SrtpHandlerContext {
    pub(crate) local_srtp_context: Option<Context>,
    pub(crate) remote_srtp_context: Option<Context>,
    /// RFC 5764 section 4.3: "DTLS-SRTP implementations SHOULD store multiple SRTP keys sets
    /// during a rekey in order to avoid the need for receivers to drop packets for which they
    /// lack a key." The inbound context a new handshake replaced, and until when it is kept.
    /// It only unprotects: nothing is sent with it.
    pub(crate) previous_remote_srtp_context: Option<(Context, Instant)>,
    /// The SSRCs whose packets the current inbound context has authenticated: from then on,
    /// their packets are not tried with the previous context (it has a later sender's key
    /// behind it, so an old-key packet now is a replay of the old association, not a late one).
    pub(crate) ssrcs_under_current_keys: HashSet<u32>,

    /// `RTCRtpHeaderEncryptionPolicy` (webrtc-extensions); see `peer_connection::cryptex`.
    pub(crate) rtp_header_encryption_policy: RTCRtpHeaderEncryptionPolicy,
    /// What the negotiated session says about Cryptex (RFC 9335), applied to the contexts
    /// now and to ones a DTLS handshake hands over later.
    pub(crate) cryptex: Cryptex,
    /// The header extension ids negotiated encrypted (RFC 6904), applied to the contexts now
    /// and to ones a DTLS handshake hands over later.
    pub(crate) encrypted_header_extensions: EncryptedHeaderExtensions,

    pub(crate) read_outs: VecDeque<TaggedRTCMessageInternal>,
    pub(crate) write_outs: VecDeque<TaggedRTCMessageInternal>,
    pub(crate) event_outs: VecDeque<TaggedRTCEventInternal>,
    /// The newest instant a read or write carried, for the events the contexts raise.
    pub(crate) now: Option<Instant>,
    /// Received RTCP is held to RFC 3550 Appendix A.2 and section 6.4.1
    /// (`SettingEngineBuilder::with_strict_rtcp_validity`).
    pub(crate) strict_rtcp_validity: bool,
    /// Reduced-size RTCP was negotiated (RFC 5506): under the strict form a datagram need
    /// not start with an SR or RR.
    pub(crate) rtcp_reduced_size: bool,
    /// [`RTCEventInternal::SrtpRekeyingDue`] was raised for the current keys.
    pub(crate) rekeying_due_reported: bool,
    /// When the current keys were installed (the handshake that exported them completed):
    /// with their usage, the packet rate the re-keying margin is measured against.
    pub(crate) keys_since: Option<Instant>,
    /// The time a re-keying needs, measured on the handshake that keyed the current
    /// contexts (`DtlsTransport::rekeying_handshake_time`), set by the peer connection when
    /// a handshake completes.
    pub(crate) rekeying_time: Option<Duration>,
    /// [`RTCEventInternal::SrtpRekeyingMarginReached`] was raised for the current keys.
    pub(crate) rekeying_margin_reported: bool,
    /// When the current keys first protected or unprotected a packet: the start of the span
    /// the re-keying margin's packet rate is measured over (media may begin well after the
    /// handshake).
    pub(crate) keys_first_used: Option<Instant>,
    /// A new DTLS association replaced the one that keyed the current contexts and its
    /// handshake has not completed: the peer may already protect with its keys.
    pub(crate) awaiting_new_keys: bool,
    /// Inbound packets that failed authentication while `awaiting_new_keys`, tried again with
    /// the new keys when the handshake completes (RFC 5764 section 4.3).
    pub(crate) held_inbound: VecDeque<HeldInbound>,
    /// Events of the inbound context read while deciding to hold a packet, not yet handed on.
    pub(crate) deferred_context_events: Vec<srtp::keying::ContextEvent>,
    /// RTP packets not sent because their SRTP index was already used for another packet
    /// (`RTCPeerConnection::unsent_media_packets`).
    pub(crate) unsent_index_reused: u64,
}

/// Parses a decrypted RTCP datagram for the chain.
///
/// RFC 8834 section 4.1 (RFC 3550 section 6.1): of a compound packet, the packets that can be
/// understood are processed. One of a known type that fails its own parse is passed on as a
/// raw packet; it does not cost the others. The framing (version, lengths) has to hold.
///
/// That is all the default asks. RFC 3550 Appendix A.2 also discards a datagram whose first
/// packet is not an SR or RR or has its padding bit set, and section 6.4.1 one with padding on
/// a packet that is not the last; libwebrtc pads a packet in the middle of a compound packet
/// (its TWCC feedback), so accepting those is the default and `strict` the RFC's form. Under
/// it the first-packet rule is RFC 5506's when reduced-size RTCP was negotiated: any RTCP
/// packet type may come first.
pub(crate) fn parse_received_rtcp(
    decrypted: &[u8],
    strict: bool,
    reduced_size: bool,
) -> Result<Vec<Box<dyn rtcp::packet::Packet>>> {
    if strict {
        if reduced_size {
            rtcp::compound_packet::validate_reduced_size(decrypted)?;
        } else {
            rtcp::compound_packet::validate_compound_headers(decrypted)?;
        }
    }
    let packets = rtcp::packet::unmarshal_lenient(&mut &decrypted[..])?;
    if packets.is_empty() {
        return Err(Error::Other("empty rtcp_packets".to_string()));
    }
    Ok(packets)
}

impl SrtpHandlerContext {
    /// Unprotects an inbound SRTP (`rtcp` false) or SRTCP packet with the current keys, or,
    /// for a packet of a stream the current keys have not authenticated yet, with the keys
    /// of the association before while they are kept (RFC 5764 section 4.3).
    fn unprotect(&mut self, now: Instant, message: &[u8], rtcp: bool) -> Result<bytes::BytesMut> {
        let ssrc_at = if rtcp { 4..8 } else { 8..12 };
        let ssrc = message
            .get(ssrc_at)
            .map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]));
        if self
            .previous_remote_srtp_context
            .as_ref()
            .is_some_and(|(_, until)| now >= *until)
        {
            self.previous_remote_srtp_context = None;
        }
        if let (Some((previous, _)), Some(ssrc)) =
            (self.previous_remote_srtp_context.as_mut(), ssrc)
            && !self.ssrcs_under_current_keys.contains(&ssrc)
        {
            let late = if rtcp {
                previous.decrypt_rtcp(message)
            } else {
                previous.decrypt_rtp(message)
            };
            // What the old context has to say is not the application's concern: a packet it
            // refuses is tried with the current keys, which report it.
            while previous.poll_event().is_some() {}
            if let Ok(plain) = late {
                return Ok(plain);
            }
        }
        let context = self
            .remote_srtp_context
            .as_mut()
            .ok_or_else(|| Error::Other("no inbound SRTP context".to_owned()))?;
        let plain = if rtcp {
            context.decrypt_rtcp(message)?
        } else {
            context.decrypt_rtp(message)?
        };
        if let Some(ssrc) = ssrc
            && self.previous_remote_srtp_context.is_some()
        {
            self.ssrcs_under_current_keys.insert(ssrc);
        }
        Ok(plain)
    }

    /// Records how the SRTP contexts use Cryptex and applies it to the ones in place.
    pub(crate) fn set_cryptex(&mut self, cryptex: Cryptex) {
        self.cryptex = cryptex;
        if let Some(context) = self.local_srtp_context.as_mut() {
            context.set_cryptex(cryptex);
        }
        if let Some(context) = self.remote_srtp_context.as_mut() {
            context.set_cryptex(cryptex);
        }
    }
}

impl SrtpHandlerContext {
    /// How long the current keys last at the rate they have been used: the packets left of the
    /// key nearest its lifetime (either direction, SRTP or SRTCP), at the rate that key's
    /// packets came since the keys were installed. `None` before any packet or without keys.
    pub(crate) fn key_time_left(&self, now: Instant) -> Option<Duration> {
        let elapsed = now
            .saturating_duration_since(self.keys_since?)
            .as_secs_f64();
        if elapsed <= 0.0 {
            return None;
        }
        [
            self.local_srtp_context.as_ref(),
            self.remote_srtp_context.as_ref(),
        ]
        .into_iter()
        .flatten()
        .flat_map(|context| {
            let usage = context.key_usage();
            [
                (usage.srtp_packets, usage.lifetime.srtp_packets),
                (usage.srtcp_packets, usage.lifetime.srtcp_packets),
            ]
        })
        .filter(|(used, _)| *used > 0)
        .map(|(used, limit)| {
            let rate = used as f64 / elapsed;
            Duration::from_secs_f64(limit.saturating_sub(used) as f64 / rate)
        })
        .min()
    }

    /// Whether the current keys have reached the re-keying margin measured in time: a key
    /// (either direction, SRTP or SRTCP) has no more packets left than it protects, at the
    /// rate it has been used since the keys were installed, in the time a re-keying needs
    /// ([`Self::rekeying_time`]), and that is more packets than the sixteenth of its lifetime
    /// the lifetime warning leaves (`ContextEvent::KeyLifetimeExpiring`): the margin is the
    /// larger of the two. The rate is measured from the keys' first packet, and taken once
    /// they have been in use for that time at least, so that a first burst does not stand
    /// for it.
    pub(crate) fn rekeying_margin_reached(&self, now: Instant) -> bool {
        let (Some(needed), Some(since)) = (self.rekeying_time, self.keys_first_used) else {
            return false;
        };
        let elapsed = now.saturating_duration_since(since);
        if elapsed.is_zero() || elapsed < needed {
            return false;
        }
        let share = needed.as_secs_f64() / elapsed.as_secs_f64();
        [
            self.local_srtp_context.as_ref(),
            self.remote_srtp_context.as_ref(),
        ]
        .into_iter()
        .flatten()
        .flat_map(|context| {
            let usage = context.key_usage();
            [
                (usage.srtp_packets, usage.lifetime.srtp_packets),
                (usage.srtcp_packets, usage.lifetime.srtcp_packets),
            ]
        })
        .any(|(used, limit)| {
            // Rounded down: at the very rate that makes it equal to the sixteenth, the
            // lifetime warning alone keeps its timing.
            let needed_packets = (used as f64 * share).floor() as u64;
            needed_packets > (limit / 16).max(1) && limit.saturating_sub(used) <= needed_packets
        })
    }

    /// Records the header extensions the session encrypts (RFC 6904) and applies them to the
    /// contexts in place, in both directions.
    pub(crate) fn set_encrypted_header_extensions(&mut self, ids: EncryptedHeaderExtensions) {
        self.encrypted_header_extensions = ids;
        for context in [
            self.local_srtp_context.as_mut(),
            self.remote_srtp_context.as_mut(),
        ]
        .into_iter()
        .flatten()
        {
            context.set_encrypted_header_extensions(ids);
        }
    }
}

/// SrtpHandler implements SRTP/RTP/RTCP Protocols handling
pub(crate) struct SrtpHandler<'a> {
    ctx: &'a mut SrtpHandlerContext,
}

impl<'a> SrtpHandler<'a> {
    pub(crate) fn new(ctx: &'a mut SrtpHandlerContext) -> Self {
        SrtpHandler { ctx }
    }

    pub(crate) fn name(&self) -> &'static str {
        "SrtpHandler"
    }

    /// Unprotects an inbound SRTP or SRTCP packet and hands the result on. While the keys of a
    /// new DTLS association are awaited (`awaiting_new_keys`), a packet that fails
    /// authentication under the current keys is held instead of dropped (`may_hold`), and tried
    /// again when the handshake completes: the peer may have completed its side first and
    /// already protects with the new keys (RFC 5764 section 4.3, "DTLS-SRTP implementations
    /// SHOULD store multiple SRTP keys sets during a rekey in order to avoid the need for
    /// receivers to drop packets for which they lack a key").
    fn read_protected(
        &mut self,
        now: Instant,
        transport: shared::TransportContext,
        message: bytes::BytesMut,
        rtcp: bool,
        may_hold: bool,
    ) -> Result<()> {
        let decrypted = match self.ctx.unprotect(now, &message, rtcp) {
            Ok(decrypted) => decrypted,
            Err(err) => {
                if may_hold && self.hold_for_new_keys(now, transport, &message, rtcp) {
                    return Ok(());
                }
                return Err(err);
            }
        };
        let message = if rtcp {
            RTPMessage::Packet(Packet::Rtcp(parse_received_rtcp(
                &decrypted,
                self.ctx.strict_rtcp_validity,
                self.ctx.rtcp_reduced_size,
            )?))
        } else {
            let mut decrypted = decrypted;
            RTPMessage::Packet(Packet::Rtp(rtp::Packet::unmarshal(&mut decrypted)?))
        };
        self.ctx.read_outs.push_back(TaggedRTCMessageInternal {
            now,
            transport,
            message: RTCMessageInternal::Rtp(message),
        });
        Ok(())
    }

    /// Holds `message`, which the current inbound context just refused, if a new
    /// association's keys are awaited, it failed authentication (not a replay), and there is
    /// room. The context's report of the failure is withdrawn for a held packet (it is not
    /// discarded yet); every other event it raised is handed on as usual.
    fn hold_for_new_keys(
        &mut self,
        now: Instant,
        transport: shared::TransportContext,
        message: &[u8],
        rtcp: bool,
    ) -> bool {
        use srtp::keying::{ContextEvent, DiscardReason, PacketKind};
        if !self.ctx.awaiting_new_keys {
            return false;
        }
        while self
            .ctx
            .held_inbound
            .front()
            .is_some_and(|held| now.saturating_duration_since(held.now) > HELD_INBOUND_FOR)
        {
            self.ctx.held_inbound.pop_front();
        }
        if self.ctx.held_inbound.len() >= MAX_HELD_INBOUND {
            return false;
        }
        let ssrc_at = if rtcp { 4..8 } else { 8..12 };
        let Some(ssrc) = message
            .get(ssrc_at)
            .map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
        else {
            return false;
        };
        let Some(context) = self.ctx.remote_srtp_context.as_mut() else {
            return false;
        };
        let mut authentication_failed = false;
        while let Some(event) = context.poll_event() {
            match event {
                ContextEvent::PacketDiscarded {
                    kind,
                    ssrc: of,
                    reason: DiscardReason::AuthenticationFailed,
                    ..
                } if !authentication_failed && of == ssrc && (kind == PacketKind::Rtcp) == rtcp => {
                    authentication_failed = true;
                }
                other => self.ctx.deferred_context_events.push(other),
            }
        }
        if authentication_failed {
            self.ctx.held_inbound.push_back(HeldInbound {
                now,
                transport,
                message: bytes::BytesMut::from(message),
                rtcp,
            });
        }
        authentication_failed
    }

    /// What the SRTP contexts have to say (`srtp::context::Context::poll_event`), as the
    /// connection's events: a key near the end of its lifetime, a key that reached it (the
    /// transport fails), a Cryptex violation.
    fn drain_context_events(&mut self) {
        use srtp::keying::{ContextEvent, PacketKind};
        // Contexts raise events only while protecting or unprotecting, which a read or a
        // write carrying an instant drives.
        let Some(now) = self.ctx.now else {
            return;
        };
        let mut events = Vec::new();
        let deferred = std::mem::take(&mut self.ctx.deferred_context_events);
        for (outbound, context) in [
            (true, self.ctx.local_srtp_context.as_mut()),
            (false, self.ctx.remote_srtp_context.as_mut()),
        ] {
            let Some(context) = context else { continue };
            let earlier = if outbound { vec![] } else { deferred.clone() };
            let mut later = std::iter::from_fn(|| context.poll_event());
            let mut queue = earlier.into_iter();
            while let Some(event) = queue.next().or_else(|| later.next()) {
                events.push(match event {
                    ContextEvent::KeyLifetimeExpiring {
                        kind, remaining, ..
                    } => RTCEventInternal::RTCPeerConnectionEvent(
                        RTCPeerConnectionEvent::OnSrtpKeyLifetimeExpiring {
                            outbound,
                            rtcp: kind == PacketKind::Rtcp,
                            remaining,
                        },
                    ),
                    ContextEvent::KeyExhausted { .. } => RTCEventInternal::SRTPKeyExhausted,
                    ContextEvent::CryptexRequiredViolation { ssrc } => {
                        RTCEventInternal::RTCPeerConnectionEvent(
                            RTCPeerConnectionEvent::OnCryptexRequiredViolation(ssrc),
                        )
                    }
                    ContextEvent::PacketDiscarded {
                        kind,
                        ssrc,
                        index,
                        reason,
                    } => {
                        // RFC 3711 section 3.3: logged, and told to the application.
                        warn!("{kind:?} packet discarded: SSRC {ssrc}, index {index}, {reason:?}");
                        RTCEventInternal::RTCPeerConnectionEvent(
                            RTCPeerConnectionEvent::OnSrtpPacketDiscarded {
                                rtcp: kind == PacketKind::Rtcp,
                                ssrc,
                                index,
                                replay: reason == srtp::keying::DiscardReason::Replay,
                            },
                        )
                    }
                    _ => continue,
                });
            }
        }
        // The DTLS server's re-keying threshold: a thirty-second of a key's lifetime left
        // (`SettingEngineBuilder::with_srtp_rekeying_dtls_client_first`), once per key set.
        if !self.ctx.rekeying_due_reported
            && [
                self.ctx.local_srtp_context.as_ref(),
                self.ctx.remote_srtp_context.as_ref(),
            ]
            .into_iter()
            .flatten()
            .any(|context| {
                let usage = context.key_usage();
                let near =
                    |used: u64, limit: u64| limit.saturating_sub(used) <= (limit / 32).max(1);
                near(usage.srtp_packets, usage.lifetime.srtp_packets)
                    || near(usage.srtcp_packets, usage.lifetime.srtcp_packets)
            })
        {
            self.ctx.rekeying_due_reported = true;
            events.push(RTCEventInternal::SrtpRekeyingDue);
        }
        if self.ctx.keys_first_used.is_none()
            && [
                self.ctx.local_srtp_context.as_ref(),
                self.ctx.remote_srtp_context.as_ref(),
            ]
            .into_iter()
            .flatten()
            .any(|context| {
                let usage = context.key_usage();
                usage.srtp_packets > 0 || usage.srtcp_packets > 0
            })
        {
            self.ctx.keys_first_used = Some(now);
        }
        // The re-keying margin measured in time, where it is larger than the lifetime
        // warning's sixteenth (a short lifetime on a slow path), once per key set.
        if !self.ctx.rekeying_margin_reported && self.ctx.rekeying_margin_reached(now) {
            self.ctx.rekeying_margin_reported = true;
            events.push(RTCEventInternal::SrtpRekeyingMarginReached);
        }
        for event in events {
            self.ctx
                .event_outs
                .push_back(TaggedRTCEventInternal { now, event });
        }
    }
}

impl<'a>
    sansio::Protocol<TaggedRTCMessageInternal, TaggedRTCMessageInternal, TaggedRTCEventInternal>
    for SrtpHandler<'a>
{
    type Rout = TaggedRTCMessageInternal;
    type Wout = TaggedRTCMessageInternal;
    type Eout = TaggedRTCEventInternal;
    type Error = Error;
    type Time = Instant;

    fn handle_read(&mut self, msg: TaggedRTCMessageInternal) -> Result<()> {
        self.ctx.now = Some(self.ctx.now.map_or(msg.now, |now| now.max(msg.now)));
        if let RTCMessageInternal::Rtp(RTPMessage::Raw(message)) = msg.message {
            debug!("srtp read {:?}", msg.transport.peer_addr);
            let rtcp = is_rtcp(&message);
            if self.ctx.remote_srtp_context.is_none() {
                return Err(Error::Other(format!(
                    "remote_srtp_context is not set yet for {} {:?}",
                    if rtcp { "rtcp_packet" } else { "rtp_packet" },
                    msg.transport.peer_addr
                )));
            }
            self.read_protected(msg.now, msg.transport, message, rtcp, true)
        } else {
            debug!("bypass srtp read {:?}", msg.transport.peer_addr);
            self.ctx.read_outs.push_back(msg);
            Ok(())
        }
    }

    fn poll_read(&mut self) -> Option<Self::Rout> {
        self.ctx.read_outs.pop_front()
    }

    fn handle_write(&mut self, msg: TaggedRTCMessageInternal) -> Result<()> {
        self.ctx.now = Some(self.ctx.now.map_or(msg.now, |now| now.max(msg.now)));
        if let RTCMessageInternal::Rtp(message) = msg.message {
            debug!("srtp write {:?}", msg.transport.peer_addr);

            let encrypted = match message {
                RTPMessage::Packet(Packet::Rtcp(rtcp_packets)) => {
                    if rtcp_packets.is_empty() {
                        return Err(Error::Other("empty rtcp_packets".to_string()));
                    };

                    if let Some(context) = self.ctx.local_srtp_context.as_mut() {
                        let packet = rtcp::packet::marshal(&rtcp_packets)?;
                        context.encrypt_rtcp(&packet)?
                    } else {
                        return Err(Error::Other(format!(
                            "local_srp_context is not set yet for rtcp_packet {:?}",
                            msg.transport.peer_addr
                        )));
                    }
                }
                RTPMessage::Packet(Packet::Rtp(rtp_message)) => {
                    if let Some(context) = self.ctx.local_srtp_context.as_mut() {
                        let packet = rtp_message.marshal()?;
                        match context.encrypt_rtp(&packet) {
                            Ok(encrypted) => encrypted,
                            // A packet index protects one packet only: a retransmission of
                            // the same packet is protected again, but a different packet with an
                            // already sent sequence number is dropped.
                            Err(Error::SrtpIndexReused(ssrc, seq)) => {
                                self.ctx.unsent_index_reused += 1;
                                debug!(
                                    "srtp write: dropped ssrc={ssrc} seq={seq}, index already used"
                                );
                                return Ok(());
                            }
                            Err(err) => return Err(err),
                        }
                    } else {
                        return Err(Error::Other(format!(
                            "local_srtp_context is not set yet for rtp_packet {:?}",
                            msg.transport.peer_addr
                        )));
                    }
                }
                // RFC 8827 section 6.5: no RTP or RTCP leaves unprotected. Nothing above this
                // handler writes serialized packets; one that did would pass the SRTP contexts
                // by, so it is refused instead of forwarded.
                RTPMessage::Raw(_) => {
                    return Err(Error::Other(
                        "serialized rtp/rtcp is never written past srtp unprotected".to_string(),
                    ));
                }
                RTPMessage::TrackPacket(_) | RTPMessage::SessionRtcp(..) => {
                    return Err(Error::Other(
                        "application level track message should never reach here".to_string(),
                    ));
                }
                RTPMessage::Packet(_) => {
                    return Err(Error::Other(
                        "unsupported packet kind for srtp write".to_string(),
                    ));
                }
            };

            self.ctx.write_outs.push_back(TaggedRTCMessageInternal {
                now: msg.now,
                transport: msg.transport,
                message: RTCMessageInternal::Rtp(RTPMessage::Raw(encrypted)),
            });
        } else {
            // Bypass
            debug!("Bypass srtp write {:?}", msg.transport.peer_addr);
            self.ctx.write_outs.push_back(msg);
        }
        Ok(())
    }

    fn poll_write(&mut self) -> Option<Self::Wout> {
        self.ctx.write_outs.pop_front()
    }

    fn handle_event(&mut self, mut evt: TaggedRTCEventInternal) -> Result<()> {
        if let RTCEventInternal::DTLSHandshakeComplete(local_srtp_context, remote_srtp_context) =
            &mut evt.event
        {
            debug!("srtp recv dtls handshake complete");
            // What the contexts being replaced still have to say is read first: a discarded
            // packet is reported, a lifetime warning of a key that is now retired is not
            // (it would ask for a renewal the handshake just gave).
            self.drain_context_events();
            self.ctx.event_outs.retain(|queued| {
                !matches!(
                    queued.event,
                    RTCEventInternal::SrtpRekeyingDue
                        | RTCEventInternal::SrtpRekeyingMarginReached
                        | RTCEventInternal::RTCPeerConnectionEvent(
                            RTCPeerConnectionEvent::OnSrtpKeyLifetimeExpiring { .. }
                        )
                )
            });
            self.ctx.rekeying_due_reported = false;
            self.ctx.rekeying_margin_reported = false;
            self.ctx.keys_first_used = None;
            self.ctx.keys_since = Some(evt.now);
            self.ctx.awaiting_new_keys = false;

            self.ctx.local_srtp_context = local_srtp_context.take();
            let previous = std::mem::replace(
                &mut self.ctx.remote_srtp_context,
                remote_srtp_context.take(),
            );
            // RFC 5764 section 4.3: the keys of the association before are kept a while for
            // its packets still on their way.
            self.ctx.previous_remote_srtp_context = previous
                .filter(|_| self.ctx.remote_srtp_context.is_some())
                .map(|context| (context, evt.now + PREVIOUS_SRTP_KEYS_LINGER));
            self.ctx.ssrcs_under_current_keys.clear();
            let cryptex = self.ctx.cryptex;
            self.ctx.set_cryptex(cryptex);
            let encrypted = self.ctx.encrypted_header_extensions;
            self.ctx.set_encrypted_header_extensions(encrypted);
        }

        let retry = matches!(evt.event, RTCEventInternal::DTLSHandshakeComplete(..));
        if matches!(evt.event, RTCEventInternal::DTLSClosed) {
            self.ctx.awaiting_new_keys = false;
            self.ctx.held_inbound.clear();
        }
        let now = evt.now;
        self.ctx.event_outs.push_back(evt);
        // The packets held for these keys, in the order they came (the contexts' own
        // reports cover any that still fail).
        if retry {
            for held in std::mem::take(&mut self.ctx.held_inbound) {
                if now.saturating_duration_since(held.now) <= HELD_INBOUND_FOR {
                    let _ = self.read_protected(
                        held.now,
                        held.transport,
                        held.message,
                        held.rtcp,
                        false,
                    );
                }
            }
        }

        Ok(())
    }

    fn poll_event(&mut self) -> Option<Self::Eout> {
        self.drain_context_events();
        self.ctx.event_outs.pop_front()
    }

    fn handle_timeout(&mut self, _now: Instant) -> Result<()> {
        Ok(())
    }

    fn poll_timeout(&mut self) -> Option<Instant> {
        None
    }

    fn close(&mut self) -> Result<()> {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bytes::BytesMut;
    use sansio::Protocol;
    use shared::TransportContext;

    /// An RR with no report blocks, its padding bit set and four octets of padding, then a
    /// PLI: padding on a packet that is not the last of the compound packet.
    fn padded_report_then_pli() -> Vec<u8> {
        let mut datagram = vec![0xA0, 201, 0, 2, 0, 0, 0, 1, 0, 0, 0, 4];
        datagram.extend_from_slice(&pli());
        datagram
    }

    fn pli() -> [u8; 12] {
        [0x81, 206, 0, 2, 0, 0, 0, 1, 0, 0, 0, 2]
    }

    /// RFC 8834 section 4.1 and libwebrtc's compound packets: by default padding on a packet
    /// in the middle costs nothing, both packets are processed.
    #[test]
    fn padding_on_a_packet_that_is_not_the_last_is_accepted_by_default() {
        let packets = parse_received_rtcp(&padded_report_then_pli(), false, false).unwrap();
        assert_eq!(2, packets.len());
    }

    /// RFC 3550 section 6.4.1 ("the padding bit MUST be set only on that packet", the last)
    /// and Appendix A.2 (the first packet's padding bit is zero), with the strict setting.
    #[test]
    fn the_strict_rtcp_validity_discards_padding_on_a_packet_that_is_not_the_last() {
        assert!(parse_received_rtcp(&padded_report_then_pli(), true, false).is_err());
        assert!(parse_received_rtcp(&padded_report_then_pli(), true, true).is_err());
    }

    /// RFC 3550 Appendix A.2: the first packet of a compound packet is an SR or RR; RFC 5506
    /// section 3.4.2 lifts that where reduced-size RTCP was negotiated. The default takes a
    /// lone feedback packet either way.
    #[test]
    fn the_strict_rtcp_validity_wants_a_report_first_unless_reduced_size_was_negotiated() {
        assert!(parse_received_rtcp(&pli(), true, false).is_err());
        assert_eq!(1, parse_received_rtcp(&pli(), true, true).unwrap().len());
        assert_eq!(1, parse_received_rtcp(&pli(), false, false).unwrap().len());
    }

    fn write(ctx: &mut SrtpHandlerContext, message: RTPMessage) -> Result<()> {
        SrtpHandler::new(ctx).handle_write(TaggedRTCMessageInternal {
            now: Instant::now(),
            transport: TransportContext::default(),
            message: RTCMessageInternal::Rtp(message),
        })
    }

    fn rtp_packet() -> rtp::Packet {
        rtp::Packet {
            header: rtp::header::Header {
                version: 2,
                payload_type: 96,
                sequence_number: 1,
                timestamp: 1,
                ssrc: 0x1234_5678,
                ..Default::default()
            },
            payload: bytes::Bytes::from_static(b"media"),
        }
    }

    /// RFC 8827 section 6.5 (and RFC 5764 section 5.1: no SRTP processing before the handshake
    /// has keyed the contexts): RTP and RTCP written before DTLS completes are refused, and
    /// nothing is queued for the wire.
    #[test]
    fn rtp_and_rtcp_are_not_sent_before_the_srtp_keys_exist() {
        let mut ctx = SrtpHandlerContext::default();
        assert!(write(&mut ctx, RTPMessage::Packet(Packet::Rtp(rtp_packet()))).is_err());
        let receiver_report: Box<dyn rtcp::packet::Packet> =
            Box::new(rtcp::receiver_report::ReceiverReport::default());
        assert!(
            write(
                &mut ctx,
                RTPMessage::Packet(Packet::Rtcp(vec![receiver_report]))
            )
            .is_err()
        );
        assert!(SrtpHandler::new(&mut ctx).poll_write().is_none());
    }

    /// RFC 8827 section 6.5: a serialized RTP packet handed to the SRTP handler is not passed
    /// on as it is, with or without SRTP contexts.
    #[test]
    fn serialized_rtp_is_never_forwarded_unprotected() {
        let mut ctx = SrtpHandlerContext::default();
        let raw = BytesMut::from(&rtp_packet().marshal().unwrap()[..]);
        assert!(write(&mut ctx, RTPMessage::Raw(raw)).is_err());
        assert!(SrtpHandler::new(&mut ctx).poll_write().is_none());
    }

    /// RFC 5764 section 5.1: inbound SRTP and SRTCP before the handshake completes are not
    /// processed: an error, and nothing reaches the handlers above.
    #[test]
    fn inbound_srtp_before_the_handshake_is_not_processed() {
        let mut ctx = SrtpHandlerContext::default();
        let rtp = BytesMut::from(&rtp_packet().marshal().unwrap()[..]);
        let mut rtcp = BytesMut::from(&[0u8; 12][..]);
        rtcp[0] = 0x80;
        rtcp[1] = 201;
        for raw in [rtp, rtcp] {
            let read = SrtpHandler::new(&mut ctx).handle_read(TaggedRTCMessageInternal {
                now: Instant::now(),
                transport: TransportContext::default(),
                message: RTCMessageInternal::Rtp(RTPMessage::Raw(raw)),
            });
            assert!(read.is_err());
        }
        assert!(SrtpHandler::new(&mut ctx).poll_read().is_none());
    }

    fn context(key_byte: u8) -> Context {
        let provider = crypto::default_provider().expect("a built-in crypto provider");
        Context::new(
            &[key_byte; 16],
            &[key_byte; 14],
            srtp::protection_profile::ProtectionProfile::Aes128CmHmacSha1_80,
            None,
            None,
            provider.crypto(),
        )
        .expect("an SRTP context")
    }

    fn handshake_complete(ctx: &mut SrtpHandlerContext, key_byte: u8) {
        SrtpHandler::new(ctx)
            .handle_event(TaggedRTCEventInternal {
                now: Instant::now(),
                event: RTCEventInternal::DTLSHandshakeComplete(
                    Some(context(key_byte)),
                    Some(context(key_byte)),
                ),
            })
            .unwrap();
    }

    fn protected(ctx: &mut SrtpHandlerContext, sequence_number: u16) -> BytesMut {
        let mut packet = rtp_packet();
        packet.header.sequence_number = sequence_number;
        write(ctx, RTPMessage::Packet(Packet::Rtp(packet))).unwrap();
        match SrtpHandler::new(ctx).poll_write().unwrap().message {
            RTCMessageInternal::Rtp(RTPMessage::Raw(protected)) => protected,
            other => panic!("unexpected {other:?}"),
        }
    }

    /// RFC 5764 section 4.1.3: "there MUST be only one SRTP master key in use at a time". The
    /// keys a DTLS handshake hands over replace the ones in place, in both directions: after a
    /// second handshake (a new association), packets are protected with the new key only.
    #[test]
    fn a_new_handshake_replaces_the_srtp_keys() {
        let mut ctx = SrtpHandlerContext::default();
        handshake_complete(&mut ctx, 1);
        let first = protected(&mut ctx, 1);
        assert!(context(1).decrypt_rtp(&first).is_ok());

        handshake_complete(&mut ctx, 2);
        let second = protected(&mut ctx, 2);
        assert!(context(2).decrypt_rtp(&second).is_ok());
        assert!(
            context(1).decrypt_rtp(&second).is_err(),
            "the first association's key no longer protects packets"
        );
        // Inbound, too: once the new key has carried a stream's packets, a packet of that
        // stream under the old key is refused.
        let mut sender = context(2);
        read_raw(
            &mut ctx,
            sender
                .encrypt_rtp(&rtp_packet().marshal().unwrap())
                .unwrap(),
        )
        .unwrap();
        let old = context(1)
            .encrypt_rtp(&rtp_packet().marshal().unwrap())
            .unwrap();
        assert!(read_raw(&mut ctx, old).is_err());
    }

    fn read_raw(ctx: &mut SrtpHandlerContext, raw: BytesMut) -> Result<()> {
        read_raw_at(ctx, raw, Instant::now())
    }

    fn read_raw_at(ctx: &mut SrtpHandlerContext, raw: BytesMut, now: Instant) -> Result<()> {
        SrtpHandler::new(ctx).handle_read(TaggedRTCMessageInternal {
            now,
            transport: TransportContext::default(),
            message: RTCMessageInternal::Rtp(RTPMessage::Raw(raw)),
        })?;
        SrtpHandler::new(ctx).poll_read();
        Ok(())
    }

    fn rtp_with_ssrc(ssrc: u32, sequence_number: u16) -> Vec<u8> {
        let mut packet = rtp_packet();
        packet.header.ssrc = ssrc;
        packet.header.sequence_number = sequence_number;
        packet.marshal().unwrap().to_vec()
    }

    /// RFC 5764 section 4.3: "DTLS-SRTP implementations SHOULD store multiple SRTP keys sets
    /// during a rekey in order to avoid the need for receivers to drop packets for which they
    /// lack a key." After a new handshake, a packet the peer protected with the old key and
    /// that arrives late is still read, for a stream the new key has not carried yet and for
    /// a while; nothing is sent with the old key.
    #[test]
    fn a_late_packet_under_the_previous_keys_is_still_read() {
        let start = Instant::now();
        let mut ctx = SrtpHandlerContext::default();
        handshake_complete(&mut ctx, 1);
        let mut old_sender = context(1);
        let late_a = old_sender.encrypt_rtp(&rtp_with_ssrc(0xa, 10)).unwrap();
        let late_b = old_sender.encrypt_rtp(&rtp_with_ssrc(0xb, 10)).unwrap();
        let late_c = old_sender.encrypt_rtp(&rtp_with_ssrc(0xc, 10)).unwrap();
        let late_rtcp = old_sender.encrypt_rtcp(&sender_report()).unwrap();

        SrtpHandler::new(&mut ctx)
            .handle_event(TaggedRTCEventInternal {
                now: start,
                event: RTCEventInternal::DTLSHandshakeComplete(Some(context(2)), Some(context(2))),
            })
            .unwrap();
        assert!(
            context(2).decrypt_rtp(&protected(&mut ctx, 3)).is_ok(),
            "sent with the new key only"
        );
        read_raw_at(&mut ctx, late_a, start).expect("a late packet under the old key");
        read_raw_at(&mut ctx, late_rtcp, start).expect("a late SRTCP packet under the old key");

        // Stream 0xb has a packet under the new key: an old-key one after it is refused.
        let mut new_sender = context(2);
        read_raw_at(
            &mut ctx,
            new_sender.encrypt_rtp(&rtp_with_ssrc(0xb, 11)).unwrap(),
            start,
        )
        .unwrap();
        assert!(read_raw_at(&mut ctx, late_b, start).is_err());

        // After the old keys' time, nothing under them is read.
        assert!(read_raw_at(&mut ctx, late_c, start + PREVIOUS_SRTP_KEYS_LINGER).is_err());
        assert!(ctx.previous_remote_srtp_context.is_none());
    }

    /// RFC 5764 section 7.3.1: a packet that fails SRTP authentication produces no DTLS alert
    /// (and nothing else on the wire): it is an error for the pipeline, and the contexts go
    /// on. RFC 3711 section 3.3 step 5: the failure is logged and reported to the
    /// application (`OnSrtpPacketDiscarded`).
    #[test]
    fn an_srtp_failure_sends_nothing() {
        let mut ctx = SrtpHandlerContext::default();
        handshake_complete(&mut ctx, 1);
        let mut forged = context(9)
            .encrypt_rtp(&rtp_packet().marshal().unwrap())
            .unwrap();
        let last = forged.len() - 1;
        forged[last] ^= 1;
        let read = SrtpHandler::new(&mut ctx).handle_read(TaggedRTCMessageInternal {
            now: Instant::now(),
            transport: TransportContext::default(),
            message: RTCMessageInternal::Rtp(RTPMessage::Raw(forged)),
        });
        assert!(read.is_err());
        let mut handler = SrtpHandler::new(&mut ctx);
        assert!(handler.poll_write().is_none());
        assert!(handler.poll_read().is_none());
        assert!(
            matches!(
                handler.poll_event().map(|e| e.event),
                Some(RTCEventInternal::DTLSHandshakeComplete(..))
            ),
            "the handshake event itself"
        );
        assert!(matches!(
            handler.poll_event().map(|e| e.event),
            Some(RTCEventInternal::RTCPeerConnectionEvent(
                RTCPeerConnectionEvent::OnSrtpPacketDiscarded {
                    rtcp: false,
                    ssrc: 0x1234_5678,
                    index: 1,
                    replay: false,
                }
            ))
        ));
        assert!(handler.poll_event().is_none());
        // A genuine packet is still read.
        let genuine = context(1)
            .encrypt_rtp(&rtp_packet().marshal().unwrap())
            .unwrap();
        SrtpHandler::new(&mut ctx)
            .handle_read(TaggedRTCMessageInternal {
                now: Instant::now(),
                transport: TransportContext::default(),
                message: RTCMessageInternal::Rtp(RTPMessage::Raw(genuine)),
            })
            .unwrap();
        assert!(SrtpHandler::new(&mut ctx).poll_read().is_some());
    }

    /// RFC 4585 section 8: senders and receivers "SHOULD behave conservatively" with feedback
    /// from sources they cannot authenticate. A compound packet of an RR and a PLI whose SRTCP
    /// authentication tag was forged (the payload decrypts, the tag does not verify) is not
    /// read: nothing reaches the interceptors or the application, the discard is reported;
    /// the same packet with its genuine tag is read, PLI and all.
    #[test]
    fn feedback_in_an_srtcp_packet_with_a_forged_tag_is_not_read() {
        let mut ctx = SrtpHandlerContext::default();
        handshake_complete(&mut ctx, 1);
        let mut plain = vec![0x80, 201, 0, 1, 0, 0, 0, 1];
        plain.extend_from_slice(&pli());
        let genuine = context(1).encrypt_rtcp(&plain).unwrap();
        let mut forged = genuine.clone();
        let last = forged.len() - 1;
        forged[last] ^= 0x40;

        let read = SrtpHandler::new(&mut ctx).handle_read(TaggedRTCMessageInternal {
            now: Instant::now(),
            transport: TransportContext::default(),
            message: RTCMessageInternal::Rtp(RTPMessage::Raw(forged)),
        });
        assert!(read.is_err(), "a forged tag fails authentication");
        let mut handler = SrtpHandler::new(&mut ctx);
        assert!(handler.poll_read().is_none(), "no feedback is read from it");
        let events: Vec<_> = std::iter::from_fn(|| handler.poll_event().map(|e| e.event)).collect();
        assert!(
            events.iter().any(|e| matches!(
                e,
                RTCEventInternal::RTCPeerConnectionEvent(
                    RTCPeerConnectionEvent::OnSrtpPacketDiscarded { rtcp: true, .. }
                )
            )),
            "the discard is reported: {} events",
            events.len()
        );

        let packets = read_rtcp_protected(&mut ctx, genuine);
        assert_eq!(2, packets.len());
        assert!(
            packets[1]
                .as_any()
                .is::<rtcp::payload_feedbacks::picture_loss_indication::PictureLossIndication>()
        );
    }

    /// The RTCP packets read from `protected`, one SRTCP datagram.
    fn read_rtcp_protected(
        ctx: &mut SrtpHandlerContext,
        protected: BytesMut,
    ) -> Vec<Box<dyn rtcp::Packet>> {
        SrtpHandler::new(ctx)
            .handle_read(TaggedRTCMessageInternal {
                now: Instant::now(),
                transport: TransportContext::default(),
                message: RTCMessageInternal::Rtp(RTPMessage::Raw(protected)),
            })
            .unwrap();
        match SrtpHandler::new(ctx).poll_read().map(|m| m.message) {
            Some(RTCMessageInternal::Rtp(RTPMessage::Packet(Packet::Rtcp(packets)))) => packets,
            other => panic!("unexpected {other:?}"),
        }
    }

    /// RFC 3711 section 3.3 step 2: a replayed packet is discarded, and the event is logged
    /// and reported to the application (`OnSrtpPacketDiscarded` with `replay`).
    #[test]
    fn a_replayed_srtp_packet_is_reported() {
        let provider = crypto::default_provider().expect("a built-in crypto provider");
        let replay_protected = || {
            Context::new(
                &[1; 16],
                &[1; 14],
                srtp::protection_profile::ProtectionProfile::Aes128CmHmacSha1_80,
                Some(srtp::option::srtp_replay_protection(64).unwrap()),
                None,
                provider.crypto(),
            )
            .expect("an SRTP context")
        };
        let mut ctx = SrtpHandlerContext::default();
        SrtpHandler::new(&mut ctx)
            .handle_event(TaggedRTCEventInternal {
                now: Instant::now(),
                event: RTCEventInternal::DTLSHandshakeComplete(
                    Some(replay_protected()),
                    Some(replay_protected()),
                ),
            })
            .unwrap();
        let packet = context(1)
            .encrypt_rtp(&rtp_packet().marshal().unwrap())
            .unwrap();
        for (i, raw) in [packet.clone(), packet].into_iter().enumerate() {
            let read = SrtpHandler::new(&mut ctx).handle_read(TaggedRTCMessageInternal {
                now: Instant::now(),
                transport: TransportContext::default(),
                message: RTCMessageInternal::Rtp(RTPMessage::Raw(raw)),
            });
            assert_eq!(read.is_ok(), i == 0);
        }
        let mut handler = SrtpHandler::new(&mut ctx);
        let events: Vec<_> = std::iter::from_fn(|| handler.poll_event().map(|e| e.event)).collect();
        assert!(
            events.iter().any(|e| matches!(
                e,
                RTCEventInternal::RTCPeerConnectionEvent(
                    RTCPeerConnectionEvent::OnSrtpPacketDiscarded {
                        rtcp: false,
                        ssrc: 0x1234_5678,
                        index: 1,
                        replay: true,
                    }
                )
            )),
            "{} events, none the replay",
            events.len()
        );
    }

    /// The RTCP packets read from one protected datagram.
    fn read_rtcp(ctx: &mut SrtpHandlerContext, plain: &[u8]) -> Vec<Box<dyn rtcp::Packet>> {
        let protected = context(1).encrypt_rtcp(plain).unwrap();
        SrtpHandler::new(ctx)
            .handle_read(TaggedRTCMessageInternal {
                now: Instant::now(),
                transport: TransportContext::default(),
                message: RTCMessageInternal::Rtp(RTPMessage::Raw(protected)),
            })
            .unwrap();
        match SrtpHandler::new(ctx).poll_read().map(|m| m.message) {
            Some(RTCMessageInternal::Rtp(RTPMessage::Packet(Packet::Rtcp(packets)))) => packets,
            other => panic!("unexpected {other:?}"),
        }
    }

    fn sender_report() -> Vec<u8> {
        rtcp::sender_report::SenderReport {
            ssrc: 0x0102_0304,
            ntp_time: 1,
            rtp_time: 2,
            packet_count: 3,
            octet_count: 4,
            ..Default::default()
        }
        .marshal()
        .unwrap()
        .to_vec()
    }

    /// RFC 8852 section 5 ("the identifiers ... need integrity protection and source
    /// authentication"), met by SRTP authenticating the whole RTP header (RFC 3711 section
    /// 4.2): a packet whose RtpStreamId element was changed on the way is not read, while the
    /// packet as sent is, with its RtpStreamId.
    #[test]
    fn a_changed_rtp_stream_id_fails_srtp_authentication() {
        let mut ctx = SrtpHandlerContext::default();
        handshake_complete(&mut ctx, 1);
        let mut packet = rtp_packet();
        packet
            .header
            .set_extension(10, bytes::Bytes::from_static(b"hi"))
            .unwrap();
        let plain = packet.marshal().unwrap();
        // 12 octets of fixed header, 4 of extension header, the element's own octet: the rid.
        assert_eq!(&plain[17..19], b"hi");
        let protected = context(1).encrypt_rtp(&plain).unwrap();
        for at in [17, 18] {
            let mut forged = protected.clone();
            forged[at] ^= 0x01;
            assert!(read_raw(&mut ctx, forged).is_err(), "octet {at} changed");
        }
        SrtpHandler::new(&mut ctx)
            .handle_read(TaggedRTCMessageInternal {
                now: Instant::now(),
                transport: TransportContext::default(),
                message: RTCMessageInternal::Rtp(RTPMessage::Raw(protected)),
            })
            .unwrap();
        match SrtpHandler::new(&mut ctx).poll_read().map(|m| m.message) {
            Some(RTCMessageInternal::Rtp(RTPMessage::Packet(Packet::Rtp(read)))) => {
                assert_eq!(read.header.get_extension(10).as_deref(), Some(&b"hi"[..]));
            }
            other => panic!("unexpected {other:?}"),
        }
    }

    /// RFC 5124 section 2: "the RTP/SAVPF profile ... does not use the RTCP encryption prefix"
    /// of RFC 3550 section 9.1 (a random 32-bit quantity before the compound packet). What the
    /// handler protects opens to exactly the compound packet written, so the first octets
    /// under SRTCP are the sender report's version-2 header (RFC 3711 section 3.4).
    #[test]
    fn srtcp_carries_no_rtcp_encryption_prefix() {
        let mut ctx = SrtpHandlerContext::default();
        handshake_complete(&mut ctx, 1);
        let report = || -> Box<dyn rtcp::Packet> {
            Box::new(rtcp::sender_report::SenderReport {
                ssrc: 0x0102_0304,
                ntp_time: 1,
                rtp_time: 2,
                packet_count: 3,
                octet_count: 4,
                ..Default::default()
            })
        };
        let plain = rtcp::packet::marshal(&[report()]).unwrap();
        write(&mut ctx, RTPMessage::Packet(Packet::Rtcp(vec![report()]))).unwrap();
        let protected = match SrtpHandler::new(&mut ctx).poll_write().unwrap().message {
            RTCMessageInternal::Rtp(RTPMessage::Raw(protected)) => protected,
            other => panic!("unexpected {other:?}"),
        };
        let opened = context(1).decrypt_rtcp(&protected).unwrap();
        assert_eq!(
            &plain[..],
            &opened[..],
            "nothing before the compound packet"
        );
        assert_eq!(
            opened[0] >> 6,
            2,
            "the first octet is a version-2 RTCP header"
        );
        assert_eq!(opened[1], 200, "and its packet type is SR");
    }

    fn source_description() -> Vec<u8> {
        rtcp::source_description::SourceDescription {
            chunks: vec![rtcp::source_description::SourceDescriptionChunk {
                source: 0x0102_0304,
                items: vec![rtcp::source_description::SourceDescriptionItem {
                    sdes_type: rtcp::source_description::SdesType::SdesCname,
                    text: bytes::Bytes::from_static(b"cname"),
                }],
            }],
        }
        .marshal()
        .unwrap()
        .to_vec()
    }

    /// RFC 8834 section 4.1 ("process the known packet types and ignore the unknown"), RFC
    /// 3550 section 6.1: a compound packet whose middle packet is a receiver report that does
    /// not parse (it says one report block, its length holds none) still delivers the sender
    /// report before it and the SDES after it; the broken one comes along as a raw packet.
    #[test]
    fn a_broken_packet_in_a_compound_packet_does_not_cost_the_others() {
        let mut ctx = SrtpHandlerContext::default();
        handshake_complete(&mut ctx, 1);
        // V=2, RC=1, PT=201 (RR), length 1: the reporter's SSRC and no room for its block.
        let broken_receiver_report = [0x81u8, 201, 0, 1, 0, 0, 0, 9];
        let mut plain = sender_report();
        plain.extend_from_slice(&broken_receiver_report);
        plain.extend_from_slice(&source_description());

        let packets = read_rtcp(&mut ctx, &plain);
        assert_eq!(3, packets.len(), "{packets:?}");
        assert!(
            packets[0]
                .as_any()
                .downcast_ref::<rtcp::sender_report::SenderReport>()
                .is_some()
        );
        let raw = packets[1]
            .as_any()
            .downcast_ref::<rtcp::raw_packet::RawPacket>()
            .expect("the broken packet as it came");
        assert_eq!(&raw.0[..], &broken_receiver_report[..]);
        assert!(
            packets[2]
                .as_any()
                .downcast_ref::<rtcp::source_description::SourceDescription>()
                .is_some()
        );
    }

    /// RFC 4588 section 12: the RTX stream gets at least the protection of the stream it
    /// repairs. A retransmission (its own SSRC and payload type) is protected under the same
    /// SRTP session as the media: it leaves encrypted and authenticated, and the receiving
    /// context opens it.
    #[test]
    fn a_retransmission_is_protected_like_the_media() {
        let mut ctx = SrtpHandlerContext::default();
        handshake_complete(&mut ctx, 1);
        let mut rtx = rtp_packet();
        rtx.header.ssrc = 0x0BAD_F00D;
        rtx.header.payload_type = 97;
        rtx.payload = bytes::Bytes::from_static(b"\x00\x2amedia");
        let plain = rtx.marshal().unwrap();
        write(&mut ctx, RTPMessage::Packet(Packet::Rtp(rtx))).unwrap();
        let protected = match SrtpHandler::new(&mut ctx).poll_write().unwrap().message {
            RTCMessageInternal::Rtp(RTPMessage::Raw(protected)) => protected,
            other => panic!("unexpected {other:?}"),
        };
        assert_ne!(
            &plain[12..],
            &protected[12..plain.len()],
            "the payload is encrypted"
        );
        assert!(
            protected.len() > plain.len(),
            "an authentication tag is added"
        );
        assert_eq!(&plain[..], &context(1).decrypt_rtp(&protected).unwrap()[..]);
    }

    /// RFC 8834 section 4.1, RFC 3550 section 6.1: a packet of a type this endpoint does not
    /// know (here 210) between known ones is skipped by its length; the known ones are read.
    #[test]
    fn a_packet_of_an_unknown_type_in_a_compound_packet_is_passed_over() {
        let mut ctx = SrtpHandlerContext::default();
        handshake_complete(&mut ctx, 1);
        let unknown = [0x80u8, 210, 0, 2, 1, 2, 3, 4, 5, 6, 7, 8];
        let mut plain = sender_report();
        plain.extend_from_slice(&unknown);
        plain.extend_from_slice(&source_description());

        let packets = read_rtcp(&mut ctx, &plain);
        assert_eq!(3, packets.len(), "{packets:?}");
        assert!(
            packets[0]
                .as_any()
                .downcast_ref::<rtcp::sender_report::SenderReport>()
                .is_some()
        );
        assert!(
            packets[2]
                .as_any()
                .downcast_ref::<rtcp::source_description::SourceDescription>()
                .is_some()
        );
    }
}