rtci 0.5.0

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
//! WebRTC Priority Control (W3C webrtc-priority) and the DSCP values of RFC 8837: the
//! `RTCPriorityType` of encodings and data channels, and the Differentiated Services codepoint
//! each outgoing datagram is to be marked with.
//!
//! The engine performs no I/O, so it does not mark anything itself:
//! [`RTCPeerConnection::dscp`](crate::peer_connection::RTCPeerConnection::dscp) tells the
//! socket layer which codepoint to set (`IP_TOS` / `IPV6_TCLASS`, the upper six bits) on a
//! datagram `poll_write` returned.

use serde::{Deserialize, Serialize};
use std::fmt;

/// W3C webrtc-priority `RTCPriorityType`: the relative priority of a flow.
#[derive(
    Default, Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
)]
pub enum RTCPriorityType {
    /// `very-low` (DCEP "below normal", 128).
    #[serde(rename = "very-low")]
    VeryLow,
    /// `low`, the default (DCEP "normal", 256).
    #[default]
    #[serde(rename = "low")]
    Low,
    /// `medium` (DCEP "high", 512).
    #[serde(rename = "medium")]
    Medium,
    /// `high` (DCEP "extra high", 1024).
    #[serde(rename = "high")]
    High,
}

impl RTCPriorityType {
    /// The DCEP priority value of this class (W3C webrtc-priority 4.3; RFC 8832 section 5.1).
    pub fn dcep_priority(self) -> u16 {
        match self {
            Self::VeryLow => 128,
            Self::Low => 256,
            Self::Medium => 512,
            Self::High => 1024,
        }
    }

    /// The class of a DCEP priority value (W3C webrtc-priority 4.3: 0 to 128 is very-low, 129
    /// to 256 low, 257 to 512 medium, above that high).
    pub fn from_dcep_priority(priority: u16) -> Self {
        match priority {
            0..=128 => Self::VeryLow,
            129..=256 => Self::Low,
            257..=512 => Self::Medium,
            _ => Self::High,
        }
    }
}

impl fmt::Display for RTCPriorityType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::VeryLow => "very-low",
            Self::Low => "low",
            Self::Medium => "medium",
            Self::High => "high",
        })
    }
}

/// The flow types of RFC 8837 Table 1.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum RTCFlowType {
    /// Audio.
    Audio,
    /// Interactive video, with or without audio: all WebRTC video (RFC 8837 section 5).
    InteractiveVideo,
    /// Non-interactive video: video known not to be interactive (a playback application).
    /// RFC 8837 section 5: "Browsers MUST NOT use the AF3x DSCP values ... Non-browser
    /// implementations of WebRTC MAY use \[them\]".
    NonInteractiveVideo,
    /// Data channels.
    Data,
}

/// How a connection marks its datagrams
/// ([`SettingEngineBuilder::with_dscp_marking`](crate::peer_connection::configuration::setting_engine::SettingEngineBuilder::with_dscp_marking)).
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RTCDscpMarking {
    /// RFC 8837 Table 1, and a media flow whose marked packets do not get through goes back to
    /// Default Forwarding (RFC 8835 section 4.2 MAY): a flow that was sent with a codepoint
    /// other than DF and that the peer never reported on in its receiver reports on that
    /// transport ([`DSCP_BLOCKED_REPORTS`] of them, at least [`DSCP_BLOCKED_AFTER`] after the
    /// flow began) is marked DSCP 0 from then on, its retransmission and FEC streams with it.
    /// The other flows keep their codepoints ("Other flows on the same transport, using
    /// different DSCPs, don't need to change"). Only the start of a flow is watched: a flow
    /// reported on once is not watched again (later failures are the transport's, RFC 8835
    /// section 4.2). The default.
    #[default]
    Rfc8837,
    /// RFC 8837 Table 1, never turned back.
    WithoutFallback,
    /// Nothing is marked: DSCP 0 (Default Forwarding) for every datagram and connection.
    Off,
}

/// How long a marked media flow is sent before the DSCP fallback may judge it blocked.
pub const DSCP_BLOCKED_AFTER: std::time::Duration = std::time::Duration::from_secs(2);

/// How many sender or receiver reports from the peer, on the flow's transport and none about
/// the flow, judge it blocked (the first may have been sent before the flow's first packet
/// arrived).
pub const DSCP_BLOCKED_REPORTS: u64 = 3;

/// The DSCP fallback's state (RFC 8835 section 4.2).
#[derive(Debug, Default)]
pub(crate) struct DscpFallback {
    /// Marked flows not yet reported on, by SSRC: when they were first seen sent, and the
    /// transport's report count then.
    watched: std::collections::HashMap<u32, (std::time::Instant, u64)>,
    /// Flows reported on: never watched again.
    delivered: std::collections::HashSet<u32>,
    /// Flows turned back to Default Forwarding, by their encoding's SSRC.
    blocked: std::collections::HashSet<u32>,
}

/// Lower Effort (RFC 8622): DSCP 1. RFC 8837 section 5: used for very-low priority, not CS1.
pub const DSCP_LE: u8 = 1;
/// Default Forwarding: DSCP 0.
pub const DSCP_DF: u8 = 0;
/// Expedited Forwarding: DSCP 46.
pub const DSCP_EF: u8 = 46;

/// RFC 8837 Table 1: the DSCP of a flow of `flow` type at `priority`. Where the table gives two
/// codepoints (video at medium and high priority), the first: the lower drop precedence.
pub fn dscp_for(flow: RTCFlowType, priority: RTCPriorityType) -> u8 {
    match (priority, flow) {
        (RTCPriorityType::VeryLow, _) => DSCP_LE,
        (RTCPriorityType::Low, _) => DSCP_DF,
        (_, RTCFlowType::Audio) => DSCP_EF,
        (RTCPriorityType::Medium, RTCFlowType::InteractiveVideo) => 36, // AF42
        (RTCPriorityType::High, RTCFlowType::InteractiveVideo) => 34,   // AF41
        (RTCPriorityType::Medium, RTCFlowType::NonInteractiveVideo) => 28, // AF32
        (RTCPriorityType::High, RTCFlowType::NonInteractiveVideo) => 26, // AF31
        (RTCPriorityType::Medium, RTCFlowType::Data) => 10,             // AF11
        (RTCPriorityType::High, RTCFlowType::Data) => 18,               // AF21
    }
}

/// The share of a flow at `priority` against the other flows under the same congestion
/// control (RFC 8835 section 4.1, W3C webrtc-priority 3.2): each level gets "approximately
/// twice the transmission capacity" of the level below, so very-low : low : medium : high
/// is 1 : 2 : 4 : 8.
pub fn bandwidth_weight(priority: RTCPriorityType) -> f64 {
    match priority {
        RTCPriorityType::VeryLow => 1.0,
        RTCPriorityType::Low => 2.0,
        RTCPriorityType::Medium => 4.0,
        RTCPriorityType::High => 8.0,
    }
}

/// Divides `total` bits per second among flows by their weights (`bandwidth_weight`), none
/// above its cap (an encoding's `maxBitrate`): a capped flow gets its cap, and what it leaves
/// goes to the others in proportion to their weights (weighted max-min fairness). Returns
/// one share per flow, in order; with every flow capped below its share, the rest of
/// `total` is left unallocated.
pub fn allocate_bandwidth(total: f64, flows: &[(f64, Option<f64>)]) -> Vec<f64> {
    let mut shares = vec![0.0; flows.len()];
    let mut open: Vec<usize> = (0..flows.len()).filter(|&i| flows[i].0 > 0.0).collect();
    let mut remaining = total.max(0.0);
    while !open.is_empty() {
        let weights: f64 = open.iter().map(|&i| flows[i].0).sum();
        let capped: Vec<usize> = open
            .iter()
            .copied()
            .filter(|&i| {
                flows[i]
                    .1
                    .is_some_and(|cap| cap <= remaining * flows[i].0 / weights)
            })
            .collect();
        if capped.is_empty() {
            for &i in &open {
                shares[i] = remaining * flows[i].0 / weights;
            }
            break;
        }
        for &i in &capped {
            let cap = flows[i].1.unwrap_or_default().max(0.0);
            shares[i] = cap;
            remaining -= cap;
        }
        open.retain(|i| !capped.contains(i));
    }
    shares
}

/// Divides the congestion controller's target among the encodings the connection sends
/// (W3C webrtc-priority 3.2: "the priority ... influences the bandwidth allocation among
/// RTCRtpSenders"; webrtc 5.2.5 `maxBitrate` caps an encoding): every active encoding with
/// an SSRC of a transceiver that is not stopped and has a sending direction takes a share by
/// its `priority` (`bandwidth_weight`), capped at its `maxBitrate`. Each sender keeps its
/// encodings' shares (`RTCRtpSender::target_bitrates`); returns them by SSRC.
#[cfg(test)]
pub(crate) fn allocate_target_bitrate(
    transceivers: &mut [crate::rtp_transceiver::internal::RTCRtpTransceiverInternal],
    total: f64,
) -> std::collections::HashMap<u32, f64> {
    allocate_target_bitrate_on(
        transceivers,
        total,
        |_| true,
        &std::collections::BTreeSet::new(),
        None,
    )
}

/// [`allocate_target_bitrate`] among the encodings of the m= sections `on_transport` accepts
/// (by MID): one transport's congestion controller's target is divided among the senders that
/// transport carries (RFC 8836 section 2: each path has its own capacity).
///
/// An encoding whose media SSRC is in `ceased` takes no share: the RTP circuit breaker
/// stopped it (RFC 8083 section 4.5), nothing of it leaves, and what it would have had goes to
/// the encodings that still send. It has its share again when it is restarted.
///
/// `data`, when the data channels share the transport's congestion control (RFC 8836 section 2,
/// requirement 6a; [`DataChannelCoupling`]): their weight and what they may take, a flow of the
/// division like an encoding capped at its `maxBitrate`. The encodings get what it leaves.
pub(crate) fn allocate_target_bitrate_on(
    transceivers: &mut [crate::rtp_transceiver::internal::RTCRtpTransceiverInternal],
    total: f64,
    on_transport: impl Fn(&str) -> bool,
    ceased: &std::collections::BTreeSet<u32>,
    data: Option<(f64, f64)>,
) -> std::collections::HashMap<u32, f64> {
    let (mut flows, owners) = media_flows_on(transceivers, on_transport, ceased);
    if let Some((weight, demand)) = data {
        flows.push((weight, Some(demand.max(0.0))));
    }
    let mut shares = allocate_bandwidth(total, &flows);
    keep_simulcast_streams_usable(&mut shares, &flows, &owners);
    let mut by_ssrc = std::collections::HashMap::new();
    for transceiver in transceivers.iter_mut() {
        if let Some(sender) = transceiver.sender_mut() {
            sender.set_allocated_bitrates(vec![]);
        }
    }
    // The data channels' flow, last, has no owner: the zip ends before it.
    for ((index, ssrc), share) in owners.into_iter().zip(shares) {
        by_ssrc.insert(ssrc, share);
        if let Some(sender) = transceivers[index].sender_mut() {
            let mut current = sender.allocated_bitrates().to_vec();
            current.push((ssrc, share));
            sender.set_allocated_bitrates(current);
        }
    }
    by_ssrc
}

/// The least an encoding of a simulcast sender is given while it is sent: 30 kbps, the minimum
/// libwebrtc sets for any simulcast layer (`video/config/simulcast.cc` @ a222406d,
/// `kSimulcastFormatsVP8`: "The min bitrate is still limited at 30 kbps"), or the encoding's
/// `maxBitrate` when that is lower.
pub const MIN_SIMULCAST_STREAM_BITRATE: f64 = 30_000.0;

/// Within each sender with more than one encoding (simulcast), the shares
/// [`allocate_bandwidth`] gave are made usable stream by stream. RFC 8853 section 7.1: "What
/// simulcast streams to prioritize when allocating available bitrate among the simulcast
/// streams in such adaptation SHOULD be taken from the simulcast stream order on the
/// 'a=simulcast' line"; W3C webrtc-pc 5.4.1: "allocate bandwidth between encodings in such a
/// way that all simulcast streams are usable on their own ... If bandwidth does not permit all
/// simulcast streams to be sent in an usable form, the user agent is expected to stop sending
/// some of the simulcast streams." The sender's total is divided again among the first
/// encodings in the order of its encodings (the order of the `a=simulcast` line), as many as
/// can each have at least [`MIN_SIMULCAST_STREAM_BITRATE`] (or their `maxBitrate`, when lower);
/// the others get nothing. With enough for every one, nothing changes.
fn keep_simulcast_streams_usable(
    shares: &mut [f64],
    flows: &[(f64, Option<f64>)],
    owners: &[(usize, u32)],
) {
    let mut senders: Vec<usize> = owners.iter().map(|&(index, _)| index).collect();
    senders.dedup();
    for sender in senders {
        // The sender's encodings, in its encodings' order (`media_flows_on`).
        let members: Vec<usize> = (0..owners.len())
            .filter(|&i| owners[i].0 == sender)
            .collect();
        if members.len() < 2 {
            continue;
        }
        let total: f64 = members.iter().map(|&i| shares[i]).sum();
        let floor = |i: usize| {
            flows[i].1.map_or(MIN_SIMULCAST_STREAM_BITRATE, |cap| {
                cap.min(MIN_SIMULCAST_STREAM_BITRATE)
            })
        };
        if members.iter().all(|&i| shares[i] + 1e-6 >= floor(i)) {
            continue;
        }
        // The fewest streams dropped, from the end of the order; the first is always kept
        // (with all there is, when that is under its floor too).
        let mut kept = members.len() - 1;
        let divided = loop {
            let sub: Vec<(f64, Option<f64>)> = members[..kept].iter().map(|&i| flows[i]).collect();
            let divided = allocate_bandwidth(total, &sub);
            let usable = members[..kept]
                .iter()
                .zip(&divided)
                .all(|(&i, &share)| share + 1e-6 >= floor(i));
            if usable || kept == 1 {
                break divided;
            }
            kept -= 1;
        };
        for (n, &i) in members.iter().enumerate() {
            shares[i] = divided.get(n).copied().unwrap_or(0.0);
        }
    }
}

/// The flows of [`allocate_target_bitrate_on`]'s division: each active, not ceased encoding
/// with an SSRC of a sending transceiver on the transport, as (weight, `maxBitrate` cap), with
/// (transceiver index, SSRC).
#[allow(clippy::type_complexity)]
fn media_flows_on(
    transceivers: &[crate::rtp_transceiver::internal::RTCRtpTransceiverInternal],
    on_transport: impl Fn(&str) -> bool,
    ceased: &std::collections::BTreeSet<u32>,
) -> (Vec<(f64, Option<f64>)>, Vec<(usize, u32)>) {
    let mut flows = Vec::new();
    let mut owners = Vec::new();
    for (index, transceiver) in transceivers.iter().enumerate() {
        if !on_transport(transceiver.mid().as_deref().unwrap_or_default()) {
            continue;
        }
        if transceiver.stopped() || !transceiver.direction().has_send() {
            continue;
        }
        let Some(sender) = transceiver.sender() else {
            continue;
        };
        for encoding in sender.send_encodings() {
            let Some(ssrc) = encoding.rtp_coding_parameters.ssrc else {
                continue;
            };
            if !encoding.active || ceased.contains(&ssrc) {
                continue;
            }
            flows.push((
                bandwidth_weight(encoding.priority),
                (encoding.max_bitrate > 0).then_some(f64::from(encoding.max_bitrate)),
            ));
            owners.push((index, ssrc));
        }
    }
    (flows, owners)
}

/// How long the data channels' send rate is measured over (RFC 8836 section 2, requirement
/// 6a; [`DataChannelCoupling`]).
pub const DATA_CHANNEL_RATE_WINDOW: std::time::Duration = std::time::Duration::from_secs(1);

/// What the data channels may take of the target beyond what they sent in the last
/// [`DATA_CHANNEL_RATE_WINDOW`]: a quarter more, so a channel that sends more than it did can
/// grow into its share (it may always send up to its share: the bound on the association is
/// the whole share).
pub const DATA_CHANNEL_DEMAND_HEADROOM: f64 = 1.25;

/// How often the data channels' octets sent are sampled for their rate.
const DATA_CHANNEL_SAMPLE_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50);

/// The data channels' part in the connection's congestion control (RFC 8836 section 2,
/// requirement 6a; RFC 8835 section 4.1;
/// [`SettingEngineBuilder::with_data_channel_congestion_coupling`](crate::peer_connection::configuration::setting_engine::SettingEngineBuilder::with_data_channel_congestion_coupling)).
#[derive(Debug, Default)]
pub(crate) struct DataChannelCoupling {
    /// What the associations had sent in all, sampled at each timeout: (when, octets).
    samples: std::collections::VecDeque<(std::time::Instant, usize)>,
    /// Whether a bound is set on the associations.
    bounded: bool,
}

impl DataChannelCoupling {
    /// The data channels' send rate over the last [`DATA_CHANNEL_RATE_WINDOW`], bits per
    /// second, from the associations' octets sent (`sent`) at `now`.
    fn rate(&mut self, now: std::time::Instant, sent: usize) -> f64 {
        if self.samples.back().is_some_and(|(_, last)| sent < *last) {
            // A new association: its count starts again.
            self.samples.clear();
        }
        // One sample per [`DATA_CHANNEL_SAMPLE_INTERVAL`] at most: the rate is read from the
        // oldest sample of the window to `now` whatever the spacing.
        if self.samples.back().is_none_or(|(at, _)| {
            now.saturating_duration_since(*at) >= DATA_CHANNEL_SAMPLE_INTERVAL
        }) {
            self.samples.push_back((now, sent));
        }
        while self.samples.len() > 2 && self.samples[1].0 + DATA_CHANNEL_RATE_WINDOW <= now {
            self.samples.pop_front();
        }
        let (first_at, first) = self.samples[0];
        let sent = sent.max(first);
        let elapsed = now.saturating_duration_since(first_at).as_secs_f64();
        if elapsed <= 0.0 {
            return 0.0;
        }
        (sent - first) as f64 * 8.0 / elapsed.max(DATA_CHANNEL_RATE_WINDOW.as_secs_f64() / 10.0)
    }
}

/// The weights the pacer shares the rate by among the streams waiting in it (RFC 8835 section
/// 4.1, `interceptor::PacerPriorities`): each encoding with an SSRC, by its media SSRC, with
/// the weight of its `priority` ([`bandwidth_weight`]), the weight the target is divided by
/// too. The pacer weighs a stream's RTX and FEC streams with it.
pub(crate) fn pacer_priorities(
    transceivers: &[crate::rtp_transceiver::internal::RTCRtpTransceiverInternal],
) -> Vec<(u32, f64)> {
    let mut weights: Vec<(u32, f64)> = transceivers
        .iter()
        .filter_map(|transceiver| transceiver.sender().as_ref())
        .flat_map(|sender| sender.send_encodings())
        .filter_map(|encoding| {
            encoding
                .rtp_coding_parameters
                .ssrc
                .map(|ssrc| (ssrc, bandwidth_weight(encoding.priority)))
        })
        .collect();
    weights.sort_by_key(|(ssrc, _)| *ssrc);
    weights
}

impl crate::peer_connection::RTCPeerConnection {
    /// Writes the encodings' priorities to the pacer ([`pacer_priorities`]), and the codepoints
    /// their packets are marked with to the congestion controller
    /// ([`Self::flow_codepoints`]).
    pub(crate) fn write_pacer_priorities(&mut self) -> shared::error::Result<()> {
        let weights = pacer_priorities(&self.rtp_transceivers);
        let now = self.pipeline_context.now;
        self.interceptor
            .handle_write(interceptor::PacerPriorities::new(weights).into_packet(now))?;
        self.write_flow_codepoints()
    }

    /// Writes the codepoints of the streams sent ([`Self::flow_codepoints`]) to the congestion
    /// controller (`interceptor::FlowCodepoints`).
    pub(crate) fn write_flow_codepoints(&mut self) -> shared::error::Result<()> {
        let codepoints = self.flow_codepoints();
        let now = self.pipeline_context.now;
        self.interceptor
            .handle_write(interceptor::FlowCodepoints::new(codepoints).into_packet(now))
    }

    /// The DSCP each stream the connection sends is marked with, by SSRC: each encoding's
    /// media, RTX and FEC streams with the encoding's codepoint ([`Self::dscp`]: RFC 8837
    /// Table 1, 0 once the DSCP fallback turned the flow back, 0 for everything under
    /// [`RTCDscpMarking::Off`]). For the congestion controller, which reads the delay of each
    /// codepoint's packets on its own (RFC 8836 section 2, requirement 9: "The algorithm
    /// SHOULD attempt to leverage DSCP markings when they're available"). Sorted by SSRC.
    pub(crate) fn flow_codepoints(&self) -> Vec<(u32, u8)> {
        let off = self.setting_engine.dscp_marking == RTCDscpMarking::Off;
        let mut codepoints: Vec<(u32, u8)> = self
            .rtp_transceivers
            .iter()
            .filter_map(|transceiver| transceiver.sender().as_ref())
            .flat_map(|sender| sender.send_encodings())
            .flat_map(|encoding| {
                let coding = &encoding.rtp_coding_parameters;
                [
                    coding.ssrc,
                    coding.rtx.as_ref().map(|rtx| rtx.ssrc),
                    coding.fec.as_ref().map(|fec| fec.ssrc),
                ]
            })
            .flatten()
            .map(|ssrc| {
                let dscp = if off {
                    DSCP_DF
                } else {
                    self.rtp_dscp(ssrc).unwrap_or(DSCP_DF)
                };
                (ssrc, dscp)
            })
            .collect();
        codepoints.sort_unstable();
        codepoints.dedup();
        codepoints
    }

    /// RFC 8836 section 2, requirement 6a: the data channels "share information and adaptation"
    /// with the media's congestion control
    /// ([`SettingEngineBuilder::with_data_channel_congestion_coupling`](crate::peer_connection::configuration::setting_engine::SettingEngineBuilder::with_data_channel_congestion_coupling)).
    /// Run at each timeout: their send rate (the associations' octets sent, over the last
    /// [`DATA_CHANNEL_RATE_WINDOW`]) becomes a flow of the transport's division of the target,
    /// weighted by the highest priority of the open channels and capped at
    /// [`DATA_CHANNEL_DEMAND_HEADROOM`] times the rate (the encodings' next shares are lowered
    /// by it), and each association sends new DATA at no more than the channels' whole share
    /// of the target (`sctp::Association::set_max_send_rate`). Only while the connection has one transport,
    /// a congestion controller's target for it, media flows that send and open channels; the
    /// bound is lifted otherwise.
    pub(crate) fn couple_data_channels(&mut self, now: std::time::Instant) {
        if self.data_channels.is_empty() && !self.data_channel_coupling.bounded {
            self.data_channel_coupling.samples.clear();
            if !self
                .pipeline_context
                .interceptor_handler_context
                .data_channel_flows
                .is_empty()
            {
                self.pipeline_context
                    .interceptor_handler_context
                    .data_channel_flows
                    .clear();
            }
            return;
        }
        let sent: usize = self
            .sctp_transport()
            .sctp_associations
            .values()
            .map(|association| association.bytes_sent())
            .sum();
        let rate = self.data_channel_coupling.rate(now, sent);
        let context = &self.pipeline_context.interceptor_handler_context;
        let weight = self
            .data_channels
            .values()
            .map(|dc| RTCPriorityType::from_dcep_priority(dc.priority))
            .max()
            .map(bandwidth_weight);
        let coupled = match (
            self.setting_engine.data_channel_congestion_coupling,
            weight,
            context.transport_targets.len(),
            self.pipeline_context.transports.len() <= 1,
        ) {
            (true, Some(weight), 1, true) => context
                .transport_targets
                .iter()
                .next()
                .map(|(key, total)| (*key, *total, weight)),
            _ => None,
        };
        let share = coupled.and_then(|(key, total, weight)| {
            let stats = &self.pipeline_context.stats;
            let (mut flows, _) = media_flows_on(
                &self.rtp_transceivers,
                |mid| stats.section_transport_key(mid) == key,
                &context.ceased_flows,
            );
            if flows.is_empty() {
                return None;
            }
            flows.push((weight, None));
            let whole = allocate_bandwidth(total, &flows).last().copied()?;
            Some((key, weight, whole))
        });
        let context = &mut self.pipeline_context.interceptor_handler_context;
        context.data_channel_flows.clear();
        if let Some((key, weight, _)) = share {
            context
                .data_channel_flows
                .insert(key, (weight, rate * DATA_CHANNEL_DEMAND_HEADROOM));
        }
        let bounded = share.is_some();
        if !bounded && !self.data_channel_coupling.bounded {
            return;
        }
        self.data_channel_coupling.bounded = bounded;
        let bound = share.map(|(_, _, whole)| whole);
        for association in self.sctp_transport_mut().sctp_associations.values_mut() {
            association.set_max_send_rate(bound);
        }
    }

    /// While the data channels' association is held to their share
    /// ([`Self::couple_data_channels`]) and has DATA waiting, the next instant to let more of
    /// it out: the association sets no timer for its bound on the send rate.
    pub(crate) fn data_channel_coupling_timeout(&self) -> Option<std::time::Instant> {
        if !self.data_channel_coupling.bounded {
            return None;
        }
        self.sctp_transport()
            .sctp_associations
            .values()
            .any(|association| association.status().pending_data_chunks > 0)
            .then(|| self.pipeline_context.now + DATA_CHANNEL_SAMPLE_INTERVAL / 5)
    }

    /// Divides the congestion controller's last target among the encodings again
    /// (`allocate_target_bitrate`), after a change of their parameters. Nothing before the
    /// first target.
    pub(crate) fn reallocate_target_bitrate(&mut self) {
        let targets = self
            .pipeline_context
            .interceptor_handler_context
            .transport_targets
            .clone();
        let ceased = self
            .pipeline_context
            .interceptor_handler_context
            .ceased_flows
            .clone();
        for (key, total) in targets {
            let data = self
                .pipeline_context
                .interceptor_handler_context
                .data_channel_flows
                .get(&key)
                .copied();
            let stats = &self.pipeline_context.stats;
            let shares = allocate_target_bitrate_on(
                &mut self.rtp_transceivers,
                total,
                |mid| stats.section_transport_key(mid) == key,
                &ceased,
                data,
            );
            // The shares only: `total` is the target the streams were last given (zero while
            // the pacer has the source paused), not a new estimate from the congestion
            // controller, and `availableOutgoingBitrate` is left as it said.
            self.pipeline_context
                .stats
                .on_target_shares(key, total, &shares);
        }
    }

    /// The DSCP (RFC 8837 Table 1) a datagram [`poll_write`](sansio::Protocol::poll_write)
    /// returned is to be marked with: the socket layer sets it in the upper six bits of
    /// `IP_TOS` / `IPV6_TCLASS`, beside the ECN bits the datagram's transport context gives.
    ///
    /// The flow is told by the datagram (RFC 7983): an RTP packet is its sender's encoding's
    /// (`network_priority`, else `priority`; audio or interactive video), DTLS records carry
    /// the SCTP association, whose data channels share the codepoint of the highest-priority
    /// one (RFC 8837 section 5: "All data channel packets of an SCTP association carry one
    /// DSCP", RECOMMENDED the highest priority's). Over TCP (ICE-TCP, TURN over TCP) every
    /// flow of the connection shares one codepoint, the highest of them (RFC 8837 section 5,
    /// a MUST). STUN (connectivity checks, their responses, consent checks, and the engine's
    /// requests to STUN and TURN servers) carries the codepoint of the highest-priority flow
    /// whose marking is not blocked ([`Self::check_dscp`]; RFC 8445 sections 7.2.3 and 7.3:
    /// "the agent SHOULD apply the same markings to Binding requests and responses", and "If
    /// multiple DSCP markings are used on the data packets, the agent SHOULD choose one of
    /// them"). RTCP and what the engine cannot place go with Default Forwarding.
    ///
    /// Video is interactive video unless
    /// [`SettingEngineBuilder::with_non_interactive_video`] says otherwise (the AF3x values
    /// RFC 8837 section 5 lets a non-browser use for playback).
    ///
    /// Under [`RTCDscpMarking::Rfc8837`] (the default) a media flow whose marked packets the
    /// network blocks goes back to DSCP 0 ([`dscp_blocked_flows`](Self::dscp_blocked_flows));
    /// under [`RTCDscpMarking::Off`] every datagram is DSCP 0
    /// ([`SettingEngineBuilder::with_dscp_marking`]).
    ///
    /// [`SettingEngineBuilder::with_non_interactive_video`]: crate::peer_connection::configuration::setting_engine::SettingEngineBuilder::with_non_interactive_video
    /// [`SettingEngineBuilder::with_dscp_marking`]: crate::peer_connection::configuration::setting_engine::SettingEngineBuilder::with_dscp_marking
    pub fn dscp(&self, datagram: &shared::TaggedBytesMut) -> u8 {
        if self.setting_engine.dscp_marking == RTCDscpMarking::Off {
            return DSCP_DF;
        }
        if datagram.transport.transport_protocol == shared::TransportProtocol::TCP {
            return self.highest_dscp();
        }
        let mut bytes: &[u8] = &datagram.message;
        // TURN ChannelData (RFC 8656 section 12.4): the payload follows a four-byte header.
        if bytes.first().is_some_and(|b| (64..=79).contains(b)) && bytes.len() > 4 {
            bytes = &bytes[4..];
        }
        match bytes.first() {
            // RTP or RTCP (RFC 7983); RTCP packet types are 192 to 223 (RFC 5761 section 4).
            Some(128..=191) if bytes.len() >= 12 && !(192..=223).contains(&bytes[1]) => {
                let ssrc = u32::from_be_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
                self.rtp_dscp(ssrc).unwrap_or(DSCP_DF)
            }
            // DTLS: the SCTP association, under DTLS 1.2 or 1.3 records.
            Some(20..=63) => self.data_dscp().unwrap_or(DSCP_DF),
            // STUN (RFC 7983: 0 to 3).
            Some(0..=3) => self.check_dscp(),
            _ => DSCP_DF,
        }
    }

    /// The codepoint STUN goes with: one of the markings the data packets use (RFC 8445
    /// section 7.2.3), that of the highest-priority flow (audio first among equals, as over
    /// TCP: [`Self::highest_dscp`]), leaving out a media flow whose marking the network
    /// blocks (it is sent with DF, [`Self::dscp_blocked_flows`]); DF while nothing is sent.
    /// libwebrtc does the same where it marks: `Connection::OnSendStunPacket` and
    /// `Port::SendBindingResponse` send with `StunDscpValue()`, the DSCP the media channel set
    /// on the port's socket (`UDPPort::SetOption(OPT_DSCP)`, `p2p/base/stun_port.cc`).
    fn check_dscp(&self) -> u8 {
        use crate::rtp_transceiver::rtp_sender::RtpCodecKind;
        let media = self
            .rtp_transceivers
            .iter()
            .filter_map(|t| t.sender().as_ref())
            .flat_map(|sender| {
                let flow = if sender.kind() == RtpCodecKind::Audio {
                    RTCFlowType::Audio
                } else {
                    self.video_flow()
                };
                sender
                    .send_encodings()
                    .iter()
                    .filter(|e| {
                        !coding_ssrc(e)
                            .is_some_and(|ssrc| self.dscp_fallback.blocked.contains(&ssrc))
                    })
                    .map(move |e| (e.network_priority.unwrap_or(e.priority), flow))
                    .collect::<Vec<_>>()
            });
        let data = self.data_channels.values().map(|dc| {
            (
                RTCPriorityType::from_dcep_priority(dc.priority),
                RTCFlowType::Data,
            )
        });
        media
            .chain(data)
            .max_by_key(|(priority, flow)| (*priority, *flow == RTCFlowType::Audio))
            .map_or(DSCP_DF, |(priority, flow)| dscp_for(flow, priority))
    }

    /// The whole IPv4 TOS / IPv6 Traffic Class byte to send `datagram` with: its
    /// [`dscp`](Self::dscp) in the upper six bits (RFC 2474 section 3) and the ECN codepoint
    /// of its transport context in the lower two (RFC 3168 section 5). What a driver sets with
    /// `IP_TOS` / `IPV6_TCLASS` on the socket before sending the datagram.
    pub fn traffic_class(&self, datagram: &shared::TaggedBytesMut) -> u8 {
        (self.dscp(datagram) << 2) | datagram.transport.ecn.map_or(0, |ecn| ecn as u8)
    }

    /// Whether a datagram [`poll_write`](sansio::Protocol::poll_write) returned is to be sent
    /// unfragmented: with the Don't Fragment bit set over IPv4 (`IP_DONTFRAG`, or
    /// `IP_MTU_DISCOVER` = `IP_PMTUDISC_PROBE` on Linux) and with local fragmentation
    /// prohibited over IPv6 (`IPV6_DONTFRAG`). The socket layer, which this sans-I/O engine
    /// does not own, sets it per datagram as it sets the [`traffic_class`](Self::traffic_class).
    ///
    /// `true` for the DTLS records of a UDP path (also inside TURN ChannelData) while SCTP
    /// discovers the path MTU
    /// ([`SettingEngineBuilder::with_sctp_path_mtu_discovery`], on by default): the
    /// association's probes and packets travel in them, and a probe the network fragmented
    /// would tell SCTP the path carries a size it does not. RFC 8261 section 5: "If path MTU
    /// discovery is performed by the SCTP layer and IPv4 is used as the network-layer
    /// protocol, the DTLS implementation SHOULD allow the DTLS user to enforce that the
    /// corresponding IPv4 packet is sent with the Don't Fragment (DF) bit set"; RFC 6347
    /// section 4.1.1.1 and RFC 9147 section 4.4: the upper layer "SHOULD be allowed to set
    /// the state of the DF bit (in IPv4) or prohibit local fragmentation (in IPv6)".
    ///
    /// `false` for every other datagram (STUN, RTP, RTCP, anything over TCP), and for all of
    /// them when discovery is off or a fixed [`SettingEngineBuilder::with_sctp_mtu`] is set:
    /// the packet size then stays within the safe initial path MTU (RFC 8261 section 5,
    /// RFC 8831 section 5), and the operating system's default applies.
    ///
    /// `false` also for the DTLS datagram of an SCTP packet with DATA that is larger than its
    /// association's path MTU now allows: a fragment of a message cut before the path MTU was
    /// reduced. RFC 9260 section 6.9: "Once a user message is fragmented, it cannot be
    /// re-fragmented. Instead, if the PMTU has been reduced, then IP fragmentation MUST be
    /// used." Over IPv4 the routers on the path or the sender's stack fragment it; over IPv6
    /// only the sender's stack can (RFC 8200 section 4.5), so the socket layer is to allow
    /// source fragmentation for it (`IPV6_DONTFRAG` off). New fragments are cut to the new
    /// size and go with DF.
    ///
    /// [`SettingEngineBuilder::with_sctp_path_mtu_discovery`]: crate::peer_connection::configuration::setting_engine::SettingEngineBuilder::with_sctp_path_mtu_discovery
    /// [`SettingEngineBuilder::with_sctp_mtu`]: crate::peer_connection::configuration::setting_engine::SettingEngineBuilder::with_sctp_mtu
    pub fn dont_fragment(&self, datagram: &shared::TaggedBytesMut) -> bool {
        if datagram.transport.transport_protocol != shared::TransportProtocol::UDP
            || !self.sctp_transport().discovers_path_mtu()
        {
            return false;
        }
        let mut bytes: &[u8] = &datagram.message;
        // TURN ChannelData (RFC 8656 section 12.4): the payload, of the length the four-byte
        // header gives, follows it.
        if bytes.first().is_some_and(|b| (64..=79).contains(b)) && bytes.len() > 4 {
            let length = u16::from_be_bytes([bytes[2], bytes[3]]) as usize;
            bytes = &bytes[4..(4 + length).min(bytes.len())];
        }
        // DTLS (RFC 7983): content types 20 to 63.
        matches!(bytes.first(), Some(20..=63))
            && !self
                .pipeline_context
                .fragmentable_datagrams
                .contains(&crate::peer_connection::handler::PipelineContext::datagram_hash(bytes))
    }

    fn video_flow(&self) -> RTCFlowType {
        if self.setting_engine.non_interactive_video {
            RTCFlowType::NonInteractiveVideo
        } else {
            RTCFlowType::InteractiveVideo
        }
    }

    /// The SSRCs whose media flows the DSCP fallback turned back to Default Forwarding
    /// (RFC 8835 section 4.2; [`RTCDscpMarking::Rfc8837`]): each the SSRC of an encoding whose
    /// marked packets the peer never reported receiving. Its retransmission and FEC streams
    /// are unmarked with it.
    pub fn dscp_blocked_flows(&self) -> Vec<u32> {
        let mut ssrcs: Vec<u32> = self.dscp_fallback.blocked.iter().copied().collect();
        ssrcs.sort_unstable();
        ssrcs
    }

    /// The DSCP of the encoding that sends (or repairs) `ssrc`: its RFC 8837 codepoint, or DF
    /// once the fallback turned the flow back.
    fn rtp_dscp(&self, ssrc: u32) -> Option<u8> {
        let (primary, dscp) = self.flow_dscp(ssrc)?;
        Some(if self.dscp_fallback.blocked.contains(&primary) {
            DSCP_DF
        } else {
            dscp
        })
    }

    /// The SSRC of the encoding that sends (or repairs) `ssrc`, and its RFC 8837 codepoint.
    fn flow_dscp(&self, ssrc: u32) -> Option<(u32, u8)> {
        use crate::rtp_transceiver::rtp_sender::RtpCodecKind;
        self.rtp_transceivers.iter().find_map(|transceiver| {
            let sender = transceiver.sender().as_ref()?;
            let encoding = sender.send_encodings().iter().find(|encoding| {
                let coding = &encoding.rtp_coding_parameters;
                coding.ssrc == Some(ssrc)
                    || coding.rtx.as_ref().is_some_and(|rtx| rtx.ssrc == ssrc)
                    || coding.fec.as_ref().is_some_and(|fec| fec.ssrc == ssrc)
            })?;
            let flow = if sender.kind() == RtpCodecKind::Audio {
                RTCFlowType::Audio
            } else {
                self.video_flow()
            };
            Some((
                coding_ssrc(encoding).unwrap_or(ssrc),
                dscp_for(flow, encoding.network_priority.unwrap_or(encoding.priority)),
            ))
        })
    }

    /// RFC 8835 section 4.2: "The implementation MAY turn off use of DSCP markings if it
    /// detects symptoms of unexpected behavior such as ... blocking of packets with certain
    /// DSCP markings." Under [`RTCDscpMarking::Rfc8837`], each media flow sent with a
    /// codepoint other than DF is watched from its first packet until the peer reports on it
    /// (a report block about its SSRC, RFC 3550 6.4); a flow the peer's sender and receiver
    /// reports on its transport keep leaving out ([`DSCP_BLOCKED_REPORTS`] of them, at least
    /// [`DSCP_BLOCKED_AFTER`] after the flow began) is blocked by its marking, and goes with
    /// DSCP 0 from then on, the whole flow (its retransmission and FEC streams too: "one has
    /// to switch the whole media flow to DSCP 0, since all traffic for a single media flow
    /// needs to be on the same queue").
    pub(crate) fn detect_blocked_dscp(&mut self, now: std::time::Instant) {
        if self.setting_engine.dscp_marking != RTCDscpMarking::Rfc8837 {
            return;
        }
        let mut flows = Vec::new();
        for transceiver in &self.rtp_transceivers {
            let Some(sender) = transceiver.sender().as_ref() else {
                continue;
            };
            let mid = transceiver.mid().clone().unwrap_or_default();
            for encoding in sender.send_encodings() {
                if let Some(ssrc) = coding_ssrc(encoding) {
                    flows.push((ssrc, mid.clone()));
                }
            }
        }
        for (ssrc, mid) in flows {
            let fallback = &self.dscp_fallback;
            if fallback.blocked.contains(&ssrc) || fallback.delivered.contains(&ssrc) {
                continue;
            }
            if self.flow_dscp(ssrc).is_none_or(|(_, dscp)| dscp == DSCP_DF) {
                self.dscp_fallback.watched.remove(&ssrc);
                continue;
            }
            let stats = &self.pipeline_context.stats;
            let Some(stream) = stats.outbound_rtp_streams.get(&ssrc) else {
                continue;
            };
            if stream.packets_sent == 0 {
                continue;
            }
            if stream.remote_reports_received > 0 {
                self.dscp_fallback.watched.remove(&ssrc);
                self.dscp_fallback.delivered.insert(ssrc);
                continue;
            }
            let reports = stats
                .reception_report_packets
                .get(&stats.section_transport_key(&mid))
                .copied()
                .unwrap_or(0);
            let (since, at) = *self
                .dscp_fallback
                .watched
                .entry(ssrc)
                .or_insert((now, reports));
            if now >= since + DSCP_BLOCKED_AFTER && reports >= at + DSCP_BLOCKED_REPORTS {
                log::warn!(
                    "RFC 8835 4.2: the peer reported none of SSRC {ssrc}'s marked packets in {} reports; the flow goes with DSCP 0",
                    reports - at
                );
                self.dscp_fallback.watched.remove(&ssrc);
                self.dscp_fallback.blocked.insert(ssrc);
                // The flow's packets go with DSCP 0 from now on: so does its delay signal
                // (RFC 8836 section 2, requirement 9).
                if let Err(err) = self.write_flow_codepoints() {
                    log::warn!("flow codepoints after ssrc {ssrc} went back to DSCP 0: {err}");
                }
            }
        }
    }

    /// The codepoint of the connection's stream transmits: every TCP connection carries one
    /// (RFC 8837 section 5 MUST), the highest-priority flow's.
    pub(crate) fn stream_dscp(&self) -> u8 {
        if self.setting_engine.dscp_marking == RTCDscpMarking::Off {
            DSCP_DF
        } else {
            self.highest_dscp()
        }
    }

    /// The DSCP of the SCTP association: that of its highest-priority data channel.
    fn data_dscp(&self) -> Option<u8> {
        if self.setting_engine.dscp_marking == RTCDscpMarking::Off {
            return None;
        }
        self.data_channels
            .values()
            .map(|dc| RTCPriorityType::from_dcep_priority(dc.priority))
            .max()
            .map(|priority| dscp_for(RTCFlowType::Data, priority))
    }

    /// RFC 8837 section 5: "if the DSCP of an SCTP association is changed, the congestion
    /// controller MUST be reset" (an association whose packets carry another codepoint may
    /// take another queue, another path in effect). The data channels' codepoint
    /// ([`Self::data_dscp`]) is compared with the one last seen; when it changed, each live
    /// association's congestion control and RTO start over, as on a path change (RFC 9260
    /// section 7.2.5).
    pub(crate) fn restart_sctp_congestion_control_on_dscp_change(
        &mut self,
        now: std::time::Instant,
    ) {
        let dscp = self.data_dscp();
        let previous = std::mem::replace(&mut self.last_data_dscp, dscp);
        if previous.is_none() || previous == dscp {
            return;
        }
        for association in self.sctp_transport_mut().sctp_associations.values_mut() {
            if !association.is_ended() {
                association.on_path_change(now);
            }
        }
    }

    /// The codepoint every flow over one TCP connection shares: the highest-priority flow's.
    fn highest_dscp(&self) -> u8 {
        use crate::rtp_transceiver::rtp_sender::RtpCodecKind;
        let media = self
            .rtp_transceivers
            .iter()
            .filter_map(|t| t.sender().as_ref())
            .flat_map(|sender| {
                let flow = if sender.kind() == RtpCodecKind::Audio {
                    RTCFlowType::Audio
                } else {
                    self.video_flow()
                };
                sender
                    .send_encodings()
                    .iter()
                    .map(move |e| (e.network_priority.unwrap_or(e.priority), flow))
                    .collect::<Vec<_>>()
            });
        let data = self.data_channels.values().map(|dc| {
            (
                RTCPriorityType::from_dcep_priority(dc.priority),
                RTCFlowType::Data,
            )
        });
        media
            .chain(data)
            .max_by_key(|(priority, flow)| (*priority, *flow == RTCFlowType::Audio))
            .map_or(DSCP_DF, |(priority, flow)| dscp_for(flow, priority))
    }
}

/// The SSRC of an encoding's media.
fn coding_ssrc(
    encoding: &crate::rtp_transceiver::rtp_sender::RTCRtpEncodingParameters,
) -> Option<u32> {
    encoding.rtp_coding_parameters.ssrc
}

#[cfg(test)]
mod tests {
    use super::{allocate_bandwidth, bandwidth_weight};

    /// RFC 8835 4.1: each level twice the one below; high gets eight times very-low.
    #[test]
    fn each_priority_level_gets_twice_the_share_of_the_level_below() {
        let flows: Vec<(f64, Option<f64>)> = [
            RTCPriorityType::VeryLow,
            RTCPriorityType::Low,
            RTCPriorityType::Medium,
            RTCPriorityType::High,
        ]
        .into_iter()
        .map(|p| (bandwidth_weight(p), None))
        .collect();
        let shares = allocate_bandwidth(1_500_000.0, &flows);
        assert_eq!(shares, vec![100_000.0, 200_000.0, 400_000.0, 800_000.0]);
    }

    /// W3C webrtc 5.2.5 maxBitrate: a flow never gets more than its cap; what it leaves is
    /// shared among the others by weight; all capped leaves the rest unallocated.
    #[test]
    fn a_capped_flow_gets_its_cap_and_the_rest_goes_to_the_others() {
        let shares = allocate_bandwidth(
            1_000_000.0,
            &[(8.0, Some(100_000.0)), (2.0, None), (2.0, None)],
        );
        assert_eq!(shares, vec![100_000.0, 450_000.0, 450_000.0]);
        let shares = allocate_bandwidth(
            1_000_000.0,
            &[(2.0, Some(300_000.0)), (2.0, Some(200_000.0))],
        );
        assert_eq!(shares, vec![300_000.0, 200_000.0]);
        // A cap above the fair share does not bind.
        let shares = allocate_bandwidth(600_000.0, &[(2.0, Some(500_000.0)), (2.0, None)]);
        assert_eq!(shares, vec![300_000.0, 300_000.0]);
        assert!(allocate_bandwidth(1.0, &[]).is_empty());
    }

    use super::*;

    /// RFC 8837 Table 1, cell by cell; LE, not CS1, for very-low.
    #[test]
    fn dscp_values_follow_rfc_8837_table_1() {
        use RTCFlowType::*;
        use RTCPriorityType::*;
        let rows = [
            (Audio, [1, 0, 46, 46]),
            (InteractiveVideo, [1, 0, 36, 34]),
            (NonInteractiveVideo, [1, 0, 28, 26]),
            (Data, [1, 0, 10, 18]),
        ];
        for (flow, values) in rows {
            for (priority, value) in [VeryLow, Low, Medium, High].into_iter().zip(values) {
                assert_eq!(dscp_for(flow, priority), value, "{flow:?} {priority}");
            }
        }
    }

    /// W3C webrtc-priority 4.3: the DCEP integer of each class, and the class of any integer.
    #[test]
    fn priority_classes_map_to_and_from_dcep_values() {
        use RTCPriorityType::*;
        for class in [VeryLow, Low, Medium, High] {
            assert_eq!(
                RTCPriorityType::from_dcep_priority(class.dcep_priority()),
                class
            );
        }
        for (value, class) in [
            (0, VeryLow),
            (128, VeryLow),
            (129, Low),
            (256, Low),
            (257, Medium),
            (512, Medium),
            (513, High),
            (u16::MAX, High),
        ] {
            assert_eq!(RTCPriorityType::from_dcep_priority(value), class, "{value}");
        }
        assert_eq!(RTCPriorityType::default(), Low);
    }

    /// W3C webrtc-priority 3.2 and webrtc 5.2.5, through the senders: the connection's target
    /// is divided among the sending encodings by priority, each capped at its maxBitrate; a
    /// setParameters that changes a priority or a maxBitrate divides it again; a recvonly
    /// transceiver's sender gets nothing.
    #[test]
    fn the_target_is_divided_among_the_senders_by_priority_and_max_bitrate() {
        use crate::peer_connection::RTCPeerConnectionBuilder;
        use crate::peer_connection::configuration::media_engine::MediaEngine;
        use crate::rtp_transceiver::rtp_sender::{RTCRtpEncodingParameters, RtpCodecKind};
        use crate::rtp_transceiver::{
            RTCRtpSenderId, RTCRtpTransceiverDirection, RTCRtpTransceiverInit,
        };
        let mut media_engine = MediaEngine::default();
        media_engine.register_default_codecs().unwrap();
        let mut pc = RTCPeerConnectionBuilder::new()
            .with_media_engine(media_engine)
            .build(std::time::Instant::now())
            .unwrap();
        let add = |pc: &mut crate::peer_connection::RTCPeerConnection,
                   priority: RTCPriorityType,
                   direction: RTCRtpTransceiverDirection| {
            RTCRtpSenderId::from(
                pc.add_transceiver_from_kind(
                    RtpCodecKind::Video,
                    Some(RTCRtpTransceiverInit {
                        direction,
                        streams: vec![],
                        send_encodings: vec![RTCRtpEncodingParameters {
                            active: true,
                            priority,
                            ..Default::default()
                        }],
                    }),
                )
                .unwrap(),
            )
        };
        let high = add(
            &mut pc,
            RTCPriorityType::High,
            RTCRtpTransceiverDirection::Sendonly,
        );
        let low = add(
            &mut pc,
            RTCPriorityType::Low,
            RTCRtpTransceiverDirection::Sendonly,
        );
        let receiving = add(
            &mut pc,
            RTCPriorityType::High,
            RTCRtpTransceiverDirection::Recvonly,
        );
        let shares = |pc: &mut crate::peer_connection::RTCPeerConnection, id| {
            pc.rtp_sender(id)
                .unwrap()
                .target_bitrates()
                .iter()
                .map(|&(_, bps)| bps)
                .collect::<Vec<f64>>()
        };
        assert!(shares(&mut pc, high).is_empty(), "no target yet");

        pc.pipeline_context
            .interceptor_handler_context
            .transport_targets
            .insert(0, 1_000_000.0);
        pc.reallocate_target_bitrate();
        assert_eq!(shares(&mut pc, high), vec![800_000.0], "8 : 2");
        assert_eq!(shares(&mut pc, low), vec![200_000.0]);
        assert!(
            shares(&mut pc, receiving).is_empty(),
            "a recvonly transceiver sends nothing"
        );

        // maxBitrate on the high one: capped, the rest to the other.
        let mut sender = pc.rtp_sender(high).unwrap();
        let mut parameters = sender.get_parameters().clone();
        parameters.encodings[0].max_bitrate = 300_000;
        sender.set_parameters(parameters, None).unwrap();
        assert_eq!(shares(&mut pc, high), vec![300_000.0]);
        assert_eq!(shares(&mut pc, low), vec![700_000.0]);

        // The low one raised to high and capped too: both at their caps.
        let mut sender = pc.rtp_sender(low).unwrap();
        let mut parameters = sender.get_parameters().clone();
        parameters.encodings[0].priority = RTCPriorityType::High;
        parameters.encodings[0].max_bitrate = 100_000;
        sender.set_parameters(parameters, None).unwrap();
        assert_eq!(shares(&mut pc, high), vec![300_000.0]);
        assert_eq!(shares(&mut pc, low), vec![100_000.0]);
    }

    /// RFC 8853 section 7.1 (the a=simulcast order says which streams come first when the
    /// rate is short) and W3C webrtc-pc 5.4.1 (every simulcast stream usable on its own; when
    /// the rate does not allow it, some stop): three encodings h, m, l of one sender share the
    /// target equally while each gets at least 30 kbps; below that the last ones in the order
    /// get nothing and the first ones share the rate; the first is always sent.
    #[test]
    fn simulcast_streams_are_kept_usable_in_the_order_of_the_simulcast_line() {
        use crate::peer_connection::RTCPeerConnectionBuilder;
        use crate::peer_connection::configuration::media_engine::MediaEngine;
        use crate::rtp_transceiver::rtp_sender::{
            RTCRtpCodingParameters, RTCRtpEncodingParameters, RtpCodecKind,
        };
        use crate::rtp_transceiver::{
            RTCRtpSenderId, RTCRtpTransceiverDirection, RTCRtpTransceiverInit,
        };
        let mut media_engine = MediaEngine::default();
        media_engine.register_default_codecs().unwrap();
        let mut pc = RTCPeerConnectionBuilder::new()
            .with_media_engine(media_engine)
            .build(std::time::Instant::now())
            .unwrap();
        let encoding = |rid: &str| RTCRtpEncodingParameters {
            rtp_coding_parameters: RTCRtpCodingParameters {
                rid: rid.to_owned(),
                ..Default::default()
            },
            active: true,
            ..Default::default()
        };
        let sender = RTCRtpSenderId::from(
            pc.add_transceiver_from_kind(
                RtpCodecKind::Video,
                Some(RTCRtpTransceiverInit {
                    direction: RTCRtpTransceiverDirection::Sendonly,
                    streams: vec![],
                    send_encodings: vec![encoding("h"), encoding("m"), encoding("l")],
                }),
            )
            .unwrap(),
        );
        let shares = |pc: &mut crate::peer_connection::RTCPeerConnection, target: f64| {
            pc.pipeline_context
                .interceptor_handler_context
                .transport_targets
                .insert(0, target);
            pc.reallocate_target_bitrate();
            let mut sender = pc.rtp_sender(sender).unwrap();
            let ssrcs: Vec<u32> = sender
                .get_parameters()
                .encodings
                .iter()
                .map(|e| e.rtp_coding_parameters.ssrc.expect("an SSRC"))
                .collect();
            let targets = sender.target_bitrates().to_vec();
            ssrcs
                .iter()
                .map(|ssrc| {
                    targets
                        .iter()
                        .find(|(s, _)| s == ssrc)
                        .map_or(0.0, |&(_, bps)| bps.round())
                })
                .collect::<Vec<f64>>()
        };
        assert_eq!(
            shares(&mut pc, 900_000.0),
            vec![300_000.0; 3],
            "enough for all"
        );
        assert_eq!(shares(&mut pc, 90_000.0), vec![30_000.0; 3], "just enough");
        assert_eq!(
            shares(&mut pc, 60_000.0),
            vec![30_000.0, 30_000.0, 0.0],
            "l, last on the line, stops"
        );
        assert_eq!(
            shares(&mut pc, 50_000.0),
            vec![50_000.0, 0.0, 0.0],
            "only h, first on the line"
        );
        assert_eq!(shares(&mut pc, 20_000.0), vec![20_000.0, 0.0, 0.0]);
    }

    /// RFC 8836 section 2, requirement 6a, and RFC 8835 section 4.1 ("configure each codec and
    /// each data channel with a target send rate that is appropriate to its share"): the data
    /// channels coupled to the transport's congestion control are a flow of the division. What
    /// they send (with the headroom) is taken from the encodings' targets, up to their share
    /// by priority; idle, they take nothing.
    #[test]
    fn the_data_channels_take_what_they_send_of_the_target_up_to_their_share() {
        use crate::peer_connection::RTCPeerConnectionBuilder;
        use crate::peer_connection::configuration::media_engine::MediaEngine;
        use crate::rtp_transceiver::rtp_sender::{RTCRtpEncodingParameters, RtpCodecKind};
        use crate::rtp_transceiver::{
            RTCRtpSenderId, RTCRtpTransceiverDirection, RTCRtpTransceiverInit,
        };
        let mut media_engine = MediaEngine::default();
        media_engine.register_default_codecs().unwrap();
        let mut pc = RTCPeerConnectionBuilder::new()
            .with_media_engine(media_engine)
            .build(std::time::Instant::now())
            .unwrap();
        let video = RTCRtpSenderId::from(
            pc.add_transceiver_from_kind(
                RtpCodecKind::Video,
                Some(RTCRtpTransceiverInit {
                    direction: RTCRtpTransceiverDirection::Sendonly,
                    streams: vec![],
                    send_encodings: vec![RTCRtpEncodingParameters {
                        active: true,
                        priority: RTCPriorityType::High,
                        ..Default::default()
                    }],
                }),
            )
            .unwrap(),
        );
        let share = |pc: &mut crate::peer_connection::RTCPeerConnection,
                     data: Option<(f64, f64)>| {
            let context = &mut pc.pipeline_context.interceptor_handler_context;
            context.transport_targets.insert(0, 900_000.0);
            context.data_channel_flows.clear();
            context.data_channel_flows.extend(data.map(|d| (0, d)));
            pc.reallocate_target_bitrate();
            pc.rtp_sender(video).unwrap().target_bitrates()[0].1
        };
        let very_low = bandwidth_weight(RTCPriorityType::VeryLow);
        assert_eq!(share(&mut pc, None), 900_000.0, "no data channels coupled");
        assert_eq!(share(&mut pc, Some((very_low, 0.0))), 900_000.0, "idle");
        assert_eq!(
            share(&mut pc, Some((very_low, 50_000.0))),
            850_000.0,
            "what they send, under their share"
        );
        assert_eq!(
            share(&mut pc, Some((very_low, 500_000.0))),
            800_000.0,
            "their share at most: 1 : 8"
        );
    }
}