rtci-interceptor 0.1.0

Sans-I/O RTP/RTCP interceptor pipeline for WebRTC: RTCP reports, NACK, TWCC, congestion control, pacing, FEC
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
//! Feedback through the RTCP session: compound packets (RFC 4585 3.1), the packet sender
//! SSRC (RFC 4585 6.1, RFC 8108 5.4.1), early RTCP and its allowance (RFC 4585 3.5.2) and
//! reduced-size RTCP (RFC 5506).

mod rtcp_session_common;

use rtci_interceptor::{Interceptor, RtcpBandwidth, RtcpSessionControl};
use rtcp::payload_feedbacks::picture_loss_indication::PictureLossIndication;
use rtcp::payload_feedbacks::receiver_estimated_maximum_bitrate::ReceiverEstimatedMaximumBitrate;
use rtcp::receiver_report::ReceiverReport;
use rtcp::sender_report::SenderReport;
use rtcp::source_description::{
    SdesType, SourceDescription, SourceDescriptionChunk, SourceDescriptionItem,
};
use rtcp::transport_feedbacks::transport_layer_nack::{NackPair, TransportLayerNack};
use rtcp_session_common::*;
use sansio::Protocol;
use std::time::Instant;

fn pli(media_ssrc: u32) -> Vec<Box<dyn rtcp::Packet>> {
    vec![Box::new(PictureLossIndication {
        // What an application or an interceptor that knows no better fills in.
        sender_ssrc: 0,
        media_ssrc,
    })]
}

fn nack(media_ssrc: u32, sequence_number: u16) -> Vec<Box<dyn rtcp::Packet>> {
    vec![Box::new(TransportLayerNack {
        sender_ssrc: 0xDEAD_BEEF,
        media_ssrc,
        nacks: vec![NackPair {
            packet_id: sequence_number,
            lost_packets: 0,
        }],
    })]
}

fn remb(media_ssrc: u32) -> Vec<Box<dyn rtcp::Packet>> {
    vec![Box::new(ReceiverEstimatedMaximumBitrate {
        sender_ssrc: 0,
        bitrate: 1_000_000.0,
        ssrcs: vec![media_ssrc],
    })]
}

fn sdes(source: u32, cname: &str) -> Box<dyn rtcp::Packet> {
    Box::new(SourceDescription {
        chunks: vec![SourceDescriptionChunk {
            source,
            items: vec![SourceDescriptionItem {
                sdes_type: SdesType::SdesCname,
                text: cname.to_string().into(),
            }],
        }],
    })
}

/// RFC 4585 3.1 (and RFC 3550 6.1): feedback leaves in a compound packet: RR, SDES with the
/// CNAME, then the feedback message, whose packet sender is the endpoint's own SSRC. Between
/// two parties it leaves at once (RFC 4585 3.5.2: no dither).
#[test]
fn feedback_leaves_at_once_in_a_minimal_compound_packet_from_the_endpoints_ssrc() {
    let mut chain = chain(builder());
    let base = Instant::now();
    control(&mut chain, base, RtcpSessionControl::Start);

    let now = base + secs(0.01);
    chain.handle_write(rtcp(now, pli(200))).unwrap();
    let sent = written(&mut chain);
    assert_eq!(1, sent.len());
    assert_eq!(now, sent[0].at);
    assert_eq!(3, sent[0].packets.len());
    let report = sent[0].packets[0]
        .as_any()
        .downcast_ref::<ReceiverReport>()
        .expect("a receiver report first");
    assert_eq!(REPORTER, report.ssrc);
    assert!(report.reports.is_empty(), "the minimal compound packet");
    assert_eq!(
        vec![REPORTER],
        sent[0].cnames().iter().map(|c| c.0).collect::<Vec<_>>()
    );
    assert!(sent[0].packets[1].as_any().is::<SourceDescription>());
    let pli = sent[0].packets[2]
        .as_any()
        .downcast_ref::<PictureLossIndication>()
        .expect("then the feedback");
    assert_eq!(REPORTER, pli.sender_ssrc);
    assert_eq!(200, pli.media_ssrc);
}

/// RFC 4585 3.5.2: after an Early packet no other is allowed until the next regular one is
/// due (put off by one interval). Feedback detected meanwhile is stored and goes with it,
/// merged into as few messages as possible.
#[test]
fn a_second_feedback_waits_for_the_regular_packet_and_is_merged() {
    let mut chain = chain(builder().with_bandwidth(RtcpBandwidth {
        session: Some(64_000),
        ..Default::default()
    }));
    let base = Instant::now();
    chain.bind_remote_stream(&video(200));
    control(&mut chain, base, RtcpSessionControl::Start);

    chain
        .handle_write(rtcp(base + secs(0.01), nack(200, 10)))
        .unwrap();
    assert_eq!(1, written(&mut chain).len());

    // No early packet is allowed now.
    chain
        .handle_write(rtcp(base + secs(0.02), nack(200, 12)))
        .unwrap();
    chain
        .handle_write(rtcp(base + secs(0.03), nack(200, 11)))
        .unwrap();
    chain
        .handle_write(rtcp(base + secs(0.03), pli(200)))
        .unwrap();
    chain
        .handle_write(rtcp(base + secs(0.04), pli(200)))
        .unwrap();
    assert!(written(&mut chain).is_empty());

    let sent = run(&mut chain, base + secs(0.9));
    assert_eq!(1, sent.len(), "one packet carries what was stored");
    assert!(sent[0].at > base + secs(0.04));
    assert!(sent[0].is_compound());
    let nacks = sent[0].get::<TransportLayerNack>();
    assert_eq!(1, nacks.len(), "the two NACKs are one message");
    let mut requested: Vec<u16> = nacks[0]
        .nacks
        .iter()
        .flat_map(|p| p.packet_list())
        .collect();
    requested.sort_unstable();
    assert_eq!(vec![11, 12], requested);
    assert_eq!(REPORTER, nacks[0].sender_ssrc);
    assert_eq!(1, sent[0].get::<PictureLossIndication>().len());

    // The regular packet went: early feedback is allowed again.
    let now = base + secs(0.91);
    chain.handle_write(rtcp(now, pli(200))).unwrap();
    let sent = written(&mut chain);
    assert_eq!(1, sent.len());
    assert_eq!(now, sent[0].at);

    // And not again right after. The next regular packet is not due yet (`T_rr_interval`),
    // so what is stored leaves with a packet of its own when the timer expires (RFC 4585
    // 3.5.3, case 2b): the minimal compound packet, no report blocks.
    chain
        .handle_write(rtcp(now + secs(0.001), nack(200, 30)))
        .unwrap();
    assert!(written(&mut chain).is_empty());
    let sent = run(&mut chain, now + secs(0.6));
    assert_eq!(1, sent.len());
    assert!(sent[0].is_compound());
    assert_eq!(1, sent[0].get::<TransportLayerNack>().len());
    assert!(sent[0].reported().is_empty());
}

/// RFC 5506 4.2.2: a large feedback packet goes out compound even when reduced-size RTCP was
/// negotiated.
#[test]
fn a_large_feedback_packet_is_sent_compound() {
    let mut chain = chain(builder().with_reduced_size(true));
    let base = Instant::now();
    chain.bind_remote_stream(&video(200));
    control(&mut chain, base, RtcpSessionControl::Start);
    chain
        .handle_write(rtcp(base + secs(0.01), pli(200)))
        .unwrap();
    written(&mut chain);
    run(&mut chain, base + secs(2.0));

    // 150 separate losses: 150 PID/BLP pairs, 600 octets of FCI.
    let large: Vec<Box<dyn rtcp::Packet>> = vec![Box::new(TransportLayerNack {
        sender_ssrc: 0,
        media_ssrc: 200,
        nacks: (0..150u16)
            .map(|n| NackPair {
                packet_id: n * 20,
                lost_packets: 0,
            })
            .collect(),
    })];
    chain.handle_write(rtcp(base + secs(2.0), large)).unwrap();
    let sent = written(&mut chain);
    assert_eq!(1, sent.len());
    assert!(sent[0].is_compound());
}

/// RFC 4585 3.5.2 step 3: when the next regular packet is due within the dither of an Early
/// one, no Early packet is scheduled; the feedback goes with the regular packet.
#[test]
fn feedback_close_to_the_regular_packet_waits_for_it() {
    let mut chain = chain(builder());
    let base = Instant::now();
    control(&mut chain, base, RtcpSessionControl::Start);
    // Two CNAMEs: a multiparty session, so an Early packet would be dithered by up to half
    // the regular interval (about 88 ms here; the first regular packet is due at 175 ms).
    chain
        .handle_read(rtcp(base, vec![sdes(200, "alice"), sdes(201, "bob")]))
        .unwrap();
    read(&mut chain);

    chain
        .handle_write(rtcp(base + secs(0.12), pli(200)))
        .unwrap();
    assert!(written(&mut chain).is_empty());
    let sent = run(&mut chain, base + secs(3.0));
    let carrier = sent
        .iter()
        .find(|sent| sent.has::<PictureLossIndication>())
        .expect("the PLI is sent");
    // Not as an Early packet (that would have left by 208 ms): with the first regular one.
    assert!(carrier.at > base + secs(0.25), "{:?}", carrier.at - base);
    assert_eq!(carrier.at, sent[0].at);
}

/// RFC 8108 5.4.1: feedback about a media type comes from an SSRC of that media type when
/// the endpoint sends one; RFC 3550 6.4: a sending SSRC leads with its sender report.
#[test]
fn feedback_about_video_comes_from_the_video_ssrc() {
    let mut chain = chain(builder());
    let base = Instant::now();
    chain.bind_local_stream(&audio(10));
    chain.bind_local_stream(&video(20));
    chain.bind_remote_stream(&video(200));
    chain.bind_remote_stream(&audio(300));
    control(&mut chain, base, RtcpSessionControl::Start);
    chain.handle_write(rtp(base, 20, 1, 0)).unwrap();

    chain
        .handle_write(rtcp(base + secs(0.01), pli(200)))
        .unwrap();
    let sent = written(&mut chain);
    assert_eq!(20, sent[0].get::<PictureLossIndication>()[0].sender_ssrc);
    let report = sent[0].packets[0]
        .as_any()
        .downcast_ref::<SenderReport>()
        .expect("the video SSRC is sending: a sender report");
    assert_eq!(20, report.ssrc);
    assert!(report.reports.is_empty());

    // Feedback about audio, and about a stream the session does not know, from the first
    // media SSRC.
    let mut chain = self::chain(builder());
    chain.bind_local_stream(&audio(10));
    chain.bind_local_stream(&video(20));
    chain.bind_remote_stream(&audio(300));
    control(&mut chain, base, RtcpSessionControl::Start);
    chain
        .handle_write(rtcp(base + secs(0.01), nack(300, 1)))
        .unwrap();
    let sent = written(&mut chain);
    assert_eq!(10, sent[0].get::<TransportLayerNack>()[0].sender_ssrc);
}

/// RFC 5506: reduced-size RTCP only when negotiated, never before a compound packet was
/// sent, and not for feedback whose delivery cannot be seen.
#[test]
fn reduced_size_feedback_needs_negotiation_and_a_first_compound_packet() {
    let mut chain = chain(builder().with_reduced_size(true));
    let base = Instant::now();
    chain.bind_remote_stream(&video(200));
    control(&mut chain, base, RtcpSessionControl::Start);

    // The first RTCP packet of the session: compound.
    chain
        .handle_write(rtcp(base + secs(0.01), pli(200)))
        .unwrap();
    let sent = written(&mut chain);
    assert!(sent[0].is_compound());

    // Later, with early feedback allowed again: the PLI alone.
    run(&mut chain, base + secs(2.0));
    chain
        .handle_write(rtcp(base + secs(2.0), pli(200)))
        .unwrap();
    let sent = written(&mut chain);
    assert_eq!(1, sent.len());
    assert_eq!(1, sent[0].packets.len());
    assert_eq!(
        REPORTER,
        sent[0].get::<PictureLossIndication>()[0].sender_ssrc
    );

    // A bitrate estimate gets no visible answer: it travels compound (RFC 5506 4.2.1).
    run(&mut chain, base + secs(4.0));
    chain
        .handle_write(rtcp(base + secs(4.0), remb(200)))
        .unwrap();
    let sent = written(&mut chain);
    assert_eq!(1, sent.len());
    assert!(sent[0].is_compound());
    assert_eq!(
        REPORTER,
        sent[0].get::<ReceiverEstimatedMaximumBitrate>()[0].sender_ssrc
    );
}

#[test]
fn without_negotiation_feedback_is_always_compound() {
    let mut chain = chain(builder());
    let base = Instant::now();
    control(&mut chain, base, RtcpSessionControl::Start);
    for step in 1..=5u32 {
        let now = base + secs(2.0) * step;
        run(&mut chain, now);
        chain.handle_write(rtcp(now, pli(200))).unwrap();
        let sent = written(&mut chain);
        assert_eq!(1, sent.len());
        assert!(sent[0].is_compound());
    }

    // Negotiated while running.
    control(
        &mut chain,
        base + secs(11.0),
        RtcpSessionControl::ReducedSize(true),
    );
    run(&mut chain, base + secs(12.0));
    chain
        .handle_write(rtcp(base + secs(12.0), pli(200)))
        .unwrap();
    assert_eq!(1, written(&mut chain)[0].packets.len());
}

/// RFC 5506 4.2.1: when reduced-size NACKs consistently get no answer, the session goes back
/// to compound packets; an answer (a requested packet arriving) shows they get through.
#[test]
fn reduced_size_is_given_up_when_nacks_get_no_answer() {
    let mut chain = chain(builder().with_reduced_size(true));
    let base = Instant::now();
    chain.bind_remote_stream(&video(200));
    control(&mut chain, base, RtcpSessionControl::Start);
    chain
        .handle_write(rtcp(base + secs(0.01), pli(200)))
        .unwrap();
    written(&mut chain);

    let mut shapes = vec![];
    for step in 1..=12u32 {
        let now = base + secs(2.0) * step;
        run(&mut chain, now);
        chain
            .handle_write(rtcp(now, nack(200, step as u16)))
            .unwrap();
        let sent = written(&mut chain);
        assert_eq!(1, sent.len());
        shapes.push(sent[0].is_compound());
    }
    // Nine reduced-size NACKs, eight of them sent while the one before was unanswered.
    assert_eq!(
        vec![
            false, false, false, false, false, false, false, false, false, true, true, true
        ],
        shapes
    );

    // With answers arriving, it stays reduced-size.
    let mut chain = self::chain(builder().with_reduced_size(true));
    chain.bind_remote_stream(&video(200));
    control(&mut chain, base, RtcpSessionControl::Start);
    chain
        .handle_write(rtcp(base + secs(0.01), pli(200)))
        .unwrap();
    written(&mut chain);
    for step in 1..=12u32 {
        let now = base + secs(2.0) * step;
        run(&mut chain, now);
        chain
            .handle_write(rtcp(now, nack(200, step as u16)))
            .unwrap();
        let sent = written(&mut chain);
        assert!(!sent[0].is_compound(), "step {step}");
        // The retransmission.
        chain
            .handle_read(rtp(now + secs(0.05), 200, step as u16, 0))
            .unwrap();
        read(&mut chain);
    }
}

/// RFC 8108 5.4.2 and RFC 4585 3.5.2: with remote sources under more than one CNAME the
/// session is multiparty, and an Early packet is dithered instead of leaving at once.
#[test]
fn early_feedback_is_dithered_in_a_multiparty_session() {
    let mut chain = chain(builder());
    let base = Instant::now();
    control(&mut chain, base, RtcpSessionControl::Start);
    chain
        .handle_read(rtcp(base, vec![sdes(200, "alice"), sdes(201, "bob")]))
        .unwrap();
    read(&mut chain);

    let now = base + secs(0.01);
    chain.handle_write(rtcp(now, pli(200))).unwrap();
    assert!(written(&mut chain).is_empty(), "not at once");
    // Feedback detected while that packet is scheduled joins it (step 2a).
    chain
        .handle_write(rtcp(now + secs(0.005), nack(201, 4)))
        .unwrap();
    assert!(written(&mut chain).is_empty());
    let sent = run(&mut chain, base + secs(2.0));
    let early = sent
        .iter()
        .find(|sent| sent.has::<PictureLossIndication>())
        .expect("the PLI is sent");
    assert!(early.at > now);
    assert!(early.at < now + secs(0.1), "{:?}", early.at - now);
    assert!(early.has::<TransportLayerNack>(), "one packet carries both");

    // Said to be point to point (RFC 8108 5.4.2: "unless signaling indicates"), it is not.
    let mut chain = self::chain(builder().with_point_to_point(true));
    control(&mut chain, base, RtcpSessionControl::Start);
    chain
        .handle_read(rtcp(base, vec![sdes(200, "alice"), sdes(201, "bob")]))
        .unwrap();
    read(&mut chain);
    chain.handle_write(rtcp(now, pli(200))).unwrap();
    assert_eq!(1, written(&mut chain).len());
}

/// Reports written by anything but the session are not sent beside its own: one voice.
#[test]
fn reports_written_from_above_are_replaced_by_the_sessions_own() {
    let mut chain = chain(builder());
    let base = Instant::now();
    control(&mut chain, base, RtcpSessionControl::Start);
    chain
        .handle_write(rtcp(
            base + secs(0.01),
            vec![
                Box::new(ReceiverReport {
                    ssrc: 0x7777,
                    ..Default::default()
                }),
                sdes(0x7777, "someone-else"),
            ],
        ))
        .unwrap();

    let sent = run(&mut chain, base + secs(3.0));
    assert!(!sent.is_empty());
    for sent in &sent {
        assert_eq!(Some(REPORTER), sent.leader());
        assert!(sent.cnames().iter().all(|c| c.0 == REPORTER));
    }
}

/// RTP passes the session untouched in both directions, and inbound RTCP goes on to the
/// interceptors behind it.
#[test]
fn media_and_inbound_rtcp_pass_through() {
    let mut chain = rtci_interceptor::Registry::new()
        .with(rtci_interceptor::Slot::RtcpSession, builder().build())
        .with(
            rtci_interceptor::Slot::KeyFrameRequests,
            rtci_interceptor::KeyFrameRequestInterceptor::new(),
        )
        .build();
    let base = Instant::now();
    chain.bind_local_stream(&video(100));
    chain.handle_write(rtp(base, 100, 5, 0)).unwrap();
    let out = chain.poll_write().expect("the packet");
    assert!(
        matches!(out.message.packet, rtci_interceptor::Packet::Rtp(p) if p.header.sequence_number == 5)
    );

    chain.handle_read(rtcp(base, pli(100))).unwrap();
    let (packets, _) = read(&mut chain);
    assert_eq!(
        1,
        packets.len(),
        "the key-frame request reaches the application"
    );
}

fn sender_report_request(media_ssrc: u32) -> Vec<Box<dyn rtcp::Packet>> {
    vec![Box::new(
        rtcp::transport_feedbacks::rapid_resynchronization_request::RapidResynchronizationRequest {
            sender_ssrc: 200,
            media_ssrc,
        },
    )]
}

/// RFC 6051 section 3.2: "a media source that understands the RTCP-SR-REQ packet SHOULD
/// generate an RTCP SR packet as soon as possible while complying with the RTCP early feedback
/// rules". Between two parties (no dither) the SR of the SSRC the request names leaves at
/// once, in an Early compound packet, long before the first regular one; a request for an
/// SSRC this side does not send gets nothing early.
#[test]
fn an_rtcp_sr_req_is_answered_with_a_sender_report_at_once() {
    let mut chain = chain(builder().with_bandwidth(RtcpBandwidth {
        session: Some(64_000),
        ..Default::default()
    }));
    let base = Instant::now();
    chain.bind_local_stream(&video(100));
    chain.bind_remote_stream(&video(200));
    control(&mut chain, base, RtcpSessionControl::Start);
    chain.handle_write(rtp(base, 100, 1, 3000)).unwrap();
    assert!(
        written(&mut chain)
            .iter()
            .all(|sent| !sent.has::<SenderReport>())
    );

    let other = base + secs(0.02);
    chain
        .handle_read(rtcp(other, sender_report_request(4242)))
        .unwrap();
    read(&mut chain);
    assert!(written(&mut chain).is_empty(), "not an SSRC of ours");

    let now = base + secs(0.05);
    chain
        .handle_read(rtcp(now, sender_report_request(100)))
        .unwrap();
    read(&mut chain);
    let sent = written(&mut chain);
    assert_eq!(1, sent.len(), "an Early packet");
    assert_eq!(now, sent[0].at);
    let reports = sent[0].get::<SenderReport>();
    assert_eq!(1, reports.len());
    assert_eq!(100, reports[0].ssrc);
}

/// RFC 5104 sections 4.3.2.3 and 4.3.3.3: a TSTR "is not time critical and SHOULD be sent
/// using regular RTCP timing", and so does the TSTN that acknowledges it. Written where a PLI
/// would leave at once in an Early packet, each waits for the next regular compound packet.
#[test]
fn a_tstr_and_a_tstn_wait_for_the_regular_packet() {
    use rtcp::payload_feedbacks::temporal_spatial_tradeoff::{
        TemporalSpatialTradeoffNotification, TemporalSpatialTradeoffRequest, TstEntry,
    };
    for request in [true, false] {
        let mut chain = chain(builder());
        let base = Instant::now();
        chain.bind_remote_stream(&video(200));
        control(&mut chain, base, RtcpSessionControl::Start);
        let entries = vec![TstEntry {
            ssrc: 200,
            sequence_number: 0,
            index: 7,
        }];
        let packet: Box<dyn rtcp::Packet> = if request {
            Box::new(TemporalSpatialTradeoffRequest {
                sender_ssrc: 0,
                entries,
            })
        } else {
            Box::new(TemporalSpatialTradeoffNotification {
                sender_ssrc: 0,
                entries,
            })
        };
        let now = base + secs(0.01);
        chain.handle_write(rtcp(now, vec![packet])).unwrap();
        assert!(
            written(&mut chain).is_empty(),
            "no Early packet (TSTR: {request})"
        );

        let sent = run(&mut chain, base + secs(10.0));
        let first = sent.first().expect("a regular packet");
        assert!(first.is_compound());
        let carried = if request {
            first.has::<TemporalSpatialTradeoffRequest>()
        } else {
            first.has::<TemporalSpatialTradeoffNotification>()
        };
        assert!(carried, "the regular packet carries it (TSTR: {request})");
    }
}

/// RFC 7728 sections 6.3 and 8.2 (PAUSED "SHALL also [be repeated] in the next two regular
/// RTCP reports"), through [`RepeatInRegularReports`]: the packet leaves as feedback (an Early
/// packet: the minimal compound packet, no report blocks) and a copy of it rides each of the
/// next two Regular compound packets, the ones with the report blocks, and no packet after
/// them. [`RtcpSessionControl::StopRepeating`] ends what is still owed.
#[test]
fn a_packet_to_repeat_rides_the_next_two_regular_packets() {
    use rtci_interceptor::{Attribute, RepeatInRegularReports};
    use rtcp::transport_feedbacks::pause_resume::{PauseResume, PauseResumeEntry};
    use std::sync::Arc;

    let paused = |now: Instant, count: u8| {
        let mut packet = rtcp(
            now,
            vec![Box::new(PauseResume {
                sender_ssrc: 300,
                entries: vec![PauseResumeEntry::paused(300, 7, 1000)],
            })],
        );
        packet
            .message
            .attributes
            .push(Attribute::Custom(Arc::new(RepeatInRegularReports {
                key: 300,
                count,
            })));
        packet
    };
    for stop in [false, true] {
        let mut chain = chain(builder());
        let base = Instant::now();
        chain.bind_local_stream(&video(300));
        chain.bind_remote_stream(&video(200));
        control(&mut chain, base, RtcpSessionControl::Start);
        // The remote stream is received, so a Regular packet reports on it.
        let mut sent = vec![];
        let mut seq = 0u16;
        let mut t = base;
        let until = base + secs(40.0);
        let mut pause_at = None;
        while t < until {
            chain
                .handle_read(rtp(t, 200, seq, u32::from(seq) * 3000))
                .unwrap();
            let _ = read(&mut chain);
            seq = seq.wrapping_add(1);
            if pause_at.is_none() && t >= base + secs(8.0) {
                chain.handle_write(paused(t, 2)).unwrap();
                pause_at = Some(t);
            }
            if stop && pause_at == Some(t) {
                sent.extend(written(&mut chain));
                control(
                    &mut chain,
                    t,
                    RtcpSessionControl::StopRepeating { key: 300 },
                );
            }
            t += secs(0.1);
            sent.extend(run(&mut chain, t));
        }
        let pause_at = pause_at.expect("written");
        let after: Vec<&Sent> = sent.iter().filter(|s| s.at >= pause_at).collect();
        let carrying: Vec<usize> = after
            .iter()
            .enumerate()
            .filter(|(_, sent)| sent.has::<PauseResume>())
            .map(|(i, _)| i)
            .collect();
        assert_eq!(after[0].at, pause_at, "the first copy leaves at once");
        assert!(after[0].reported().is_empty(), "in an Early packet");
        assert_eq!(carrying[0], 0);
        let regular: Vec<usize> = after
            .iter()
            .enumerate()
            .skip(1)
            .filter(|(_, sent)| !sent.reported().is_empty())
            .map(|(i, _)| i)
            .collect();
        assert!(
            regular.len() >= 4,
            "regular packets follow: {}",
            regular.len()
        );
        if stop {
            assert_eq!(carrying, vec![0], "stopped before the next regular packet");
        } else {
            assert_eq!(
                carrying,
                vec![0, regular[0], regular[1]],
                "the next two regular packets carry it, and no other"
            );
        }
    }
}

fn twcc(media_ssrc: u32, count: u8) -> Vec<Box<dyn rtcp::Packet>> {
    use rtcp::transport_feedbacks::transport_layer_cc::TransportLayerCc;
    vec![Box::new(TransportLayerCc {
        sender_ssrc: 0,
        media_ssrc,
        fb_pkt_count: count,
        ..Default::default()
    })]
}

/// RFC 4585 section 3.5.2, as written, for congestion control feedback too
/// (`with_immediate_congestion_feedback(false)`): after an Early packet a second transport-wide
/// feedback message is held for the next regular packet ("allow_early == FALSE"), not sent
/// at once. With the default (`true`) each leaves as it is built.
#[test]
fn with_rfc_4585_timing_a_second_congestion_feedback_waits_for_the_regular_packet() {
    use rtcp::transport_feedbacks::transport_layer_cc::TransportLayerCc;
    for immediate in [false, true] {
        let mut chain = chain(
            builder()
                .with_bandwidth(RtcpBandwidth {
                    session: Some(64_000),
                    ..Default::default()
                })
                .with_immediate_congestion_feedback(immediate),
        );
        let base = Instant::now();
        chain.bind_remote_stream(&video(200));
        control(&mut chain, base, RtcpSessionControl::Start);

        chain
            .handle_write(rtcp(base + secs(0.01), twcc(200, 1)))
            .unwrap();
        assert_eq!(1, written(&mut chain).len(), "immediate {immediate}");
        chain
            .handle_write(rtcp(base + secs(0.02), twcc(200, 2)))
            .unwrap();
        let second = written(&mut chain);
        if immediate {
            assert_eq!(1, second.len(), "leaves as it is built");
            assert_eq!(1, second[0].get::<TransportLayerCc>().len());
        } else {
            assert!(second.is_empty(), "no second Early packet");
            let sent = run(&mut chain, base + secs(0.9));
            assert!(!sent.is_empty());
            assert!(sent[0].at > base + secs(0.02));
            assert!(sent[0].is_compound(), "with the regular packet");
            assert_eq!(1, sent[0].get::<TransportLayerCc>().len());
        }
    }
}