msf-rtp 0.4.1

Real-time Transport Protocol (RTP) for Rust.
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
use std::{
    collections::VecDeque,
    future::Future,
    pin::Pin,
    task::{Context, Poll},
    time::{Duration, Instant},
};

use futures::{channel::mpsc, ready, FutureExt, Sink, SinkExt, Stream, StreamExt};
use tokio::{
    task::JoinHandle,
    time::{Interval, MissedTickBehavior},
};

use crate::{
    rtcp::{ByePacket, ReceiverReport, RtcpContextHandle, RtcpPacketType, SenderReport},
    transceiver::RtpTransceiver,
    utils::PacketMux,
    CompoundRtcpPacket, InvalidInput, RtpPacket,
};

/// RTCP handler options.
#[derive(Copy, Clone)]
pub struct RtcpHandlerOptions {
    rtcp_report_interval: Duration,
    ignore_decoding_errors: bool,
}

impl RtcpHandlerOptions {
    /// Create new RTCP handler options with default values.
    #[inline]
    pub const fn new() -> Self {
        Self {
            rtcp_report_interval: Duration::from_secs(5),
            ignore_decoding_errors: true,
        }
    }

    /// Get the RTCP report interval.
    #[inline]
    pub const fn rtcp_report_interval(&self) -> Duration {
        self.rtcp_report_interval
    }

    /// Set the RTCP report interval.
    ///
    /// RTCP reports will be generated every `interval` seconds. The default
    /// value is 5 seconds.
    #[inline]
    pub const fn with_rtcp_report_interval(mut self, interval: Duration) -> Self {
        self.rtcp_report_interval = interval;
        self
    }

    /// Check if RTCP decoding errors should be ignored.
    #[inline]
    pub const fn ignore_decoding_errors(&self) -> bool {
        self.ignore_decoding_errors
    }

    /// Set whether RTCP decoding errors should be ignored.
    ///
    /// If true, decoding errors will be ignored and the invalid packets
    /// will be silently dropped. If false, the RTCP handler will stop
    /// processing incoming RTCP packets on the first decoding error. The
    /// default value is true.
    #[inline]
    pub const fn with_ignore_decoding_errors(mut self, ignore: bool) -> Self {
        self.ignore_decoding_errors = ignore;
        self
    }
}

impl Default for RtcpHandlerOptions {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

pin_project_lite::pin_project! {
    /// RTCP protocol handler.
    ///
    /// The handler consumes a given RTP-RTCP stream pair and handles all the
    /// necessary RTCP communication. The resulting object can be used as an RTP
    /// stream/sink while the corresponding RTCP communication is handled
    /// automatically by a background task.
    pub struct RtcpHandler<T> {
        #[pin]
        stream: T,
        context: RtcpHandlerContext,
    }
}

impl<T> RtcpHandler<T> {
    /// Create a new RTCP handler.
    ///
    /// The handler will use the RTCP context provided by the RTP transceiver.
    pub fn new<U, E>(rtp: T, rtcp: U, options: RtcpHandlerOptions) -> Self
    where
        T: RtpTransceiver,
        U: Send + 'static,
        U: Stream<Item = Result<CompoundRtcpPacket, E>>,
        U: Sink<CompoundRtcpPacket>,
    {
        let rtcp_context = rtp.rtcp_context();

        Self::new_with_rtcp_context(rtp, rtcp, rtcp_context, options)
    }

    /// Create a new RTCP handler with a given RTCP context.
    pub fn new_with_rtcp_context<U, E>(
        rtp: T,
        rtcp: U,
        rtcp_context: RtcpContextHandle,
        options: RtcpHandlerOptions,
    ) -> Self
    where
        U: Send + 'static,
        U: Stream<Item = Result<CompoundRtcpPacket, E>>,
        U: Sink<CompoundRtcpPacket>,
    {
        let (rtcp_tx, rtcp_rx) = rtcp.split();

        let sender = send_rtcp_reports(
            rtcp_tx,
            rtcp_context.clone(),
            options.rtcp_report_interval(),
        );

        // NOTE: This task will run as long as the RtcpContext is generating
        //   RTCP reports. It stops when the context is closed. Therefore, we
        //   close the context when the handler is dropped.
        tokio::spawn(async move {
            let _ = sender.await;
        });

        let receiver = RtcpReceiver::new(
            rtcp_rx,
            rtcp_context.clone(),
            options.ignore_decoding_errors(),
        );

        // NOTE: This task will be terminated when the handler is dropped.
        let receiver = tokio::spawn(async move {
            let _ = receiver.await;
        });

        Self {
            stream: rtp,
            context: RtcpHandlerContext {
                context: rtcp_context,
                receiver,
            },
        }
    }
}

impl<T, P, E> Stream for RtcpHandler<T>
where
    T: Stream<Item = Result<P, E>>,
{
    type Item = Result<P, E>;

    #[inline]
    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.project();

        this.stream.poll_next(cx)
    }
}

impl<T, P, E> Sink<P> for RtcpHandler<T>
where
    T: Sink<P, Error = E>,
{
    type Error = E;

    #[inline]
    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let this = self.project();

        this.stream.poll_ready(cx)
    }

    #[inline]
    fn start_send(self: Pin<&mut Self>, packet: P) -> Result<(), Self::Error> {
        let this = self.project();

        this.stream.start_send(packet)
    }

    #[inline]
    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let this = self.project();

        this.stream.poll_flush(cx)
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let this = self.project();

        ready!(this.stream.poll_close(cx))?;

        // close the RTCP context here just in case the stream itself did not
        // do it
        this.context.context.close();

        Poll::Ready(Ok(()))
    }
}

/// RTCP handler context.
struct RtcpHandlerContext {
    context: RtcpContextHandle,
    receiver: JoinHandle<()>,
}

impl Drop for RtcpHandlerContext {
    fn drop(&mut self) {
        // close the RTCP context here just in case the RTCP handler sink was
        // not closed
        self.context.close();

        // stop the RTCP receiver
        self.receiver.abort();
    }
}

/// Type alias.
type DemuxingRtpStream<P, E> = mpsc::Receiver<Result<P, E>>;

/// Type alias.
type MuxingRtpSink = PacketMuxer<mpsc::Sender<PacketMux>>;

/// Type alias.
type RtpComponent<P, E> = StreamSink<DemuxingRtpStream<P, E>, MuxingRtpSink>;

/// RTCP protocol handler for muxed RTP-RTCP streams.
///
/// The handler consumes a given muxed RTP-RTCP stream and handles all the
/// necessary RTCP communication. The resulting object can be used as an RTP
/// stream/sink while the corresponding RTCP communication is handled
/// automatically by a background task.
pub struct MuxedRtcpHandler<P, E> {
    inner: RtcpHandler<RtpComponent<P, E>>,
    reader: JoinHandle<()>,
    writer: JoinHandle<Result<(), E>>,
    sink_error: bool,
}

impl<P, E> MuxedRtcpHandler<P, E> {
    /// Create a new RTCP handler.
    pub fn new<T>(stream: T, options: RtcpHandlerOptions) -> Self
    where
        T: Send + 'static,
        T: Stream<Item = Result<PacketMux<P>, E>>,
        T: Sink<PacketMux, Error = E>,
        T: RtpTransceiver,
        P: Send + 'static,
        E: Send + 'static,
    {
        let rtcp_context = stream.rtcp_context();

        let (muxed_tx, mut muxed_rx) = stream.split();

        let (mut input_rtp_tx, input_rtp_rx) = mpsc::channel::<Result<_, E>>(4);
        let (output_rtp_tx, output_rtp_rx) = mpsc::channel(4);
        let (mut input_rtcp_tx, input_rtcp_rx) = mpsc::channel::<Result<_, E>>(4);
        let (output_rtcp_tx, output_rtcp_rx) = mpsc::channel(4);

        let output_rtp_tx = PacketMuxer::new(output_rtp_tx);
        let output_rtcp_tx = PacketMuxer::new(output_rtcp_tx);

        let rtp = StreamSink::new(input_rtp_rx, output_rtp_tx);
        let rtcp = StreamSink::new(input_rtcp_rx, output_rtcp_tx);

        // NOTE: This task will be terminated when the handler is dropped.
        let reader = tokio::spawn(async move {
            let mut run = true;

            while run {
                let next = muxed_rx.next().await;

                run = matches!(next, Some(Ok(_)));

                let _ = match next {
                    Some(Ok(PacketMux::Rtp(packet))) => input_rtp_tx.send(Ok(packet)).await,
                    Some(Ok(PacketMux::Rtcp(packet))) => input_rtcp_tx.send(Ok(packet)).await,
                    Some(Err(err)) => input_rtp_tx.send(Err(err)).await,
                    _ => Ok(()),
                };
            }
        });

        // NOTE: This task will run as long as the `output_rtp_rx` and
        //   `output_rtcp_rx` are open. These channels will be closed when the
        //   inner handler is dropped.
        let writer = tokio::spawn(async move {
            futures::stream::select(output_rtp_rx, output_rtcp_rx)
                .map(Ok)
                .forward(muxed_tx)
                .await
        });

        Self {
            inner: RtcpHandler::new_with_rtcp_context(rtp, rtcp, rtcp_context, options),
            reader,
            writer,
            sink_error: false,
        }
    }

    /// Poll the writer result.
    fn poll_writer_result(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), E>> {
        match ready!(self.writer.poll_unpin(cx)) {
            Ok(Ok(_)) => Poll::Ready(Ok(())),
            Ok(Err(err)) => Poll::Ready(Err(err)),
            Err(_) => Poll::Ready(Ok(())),
        }
    }
}

impl<P, E> Drop for MuxedRtcpHandler<P, E> {
    #[inline]
    fn drop(&mut self) {
        self.reader.abort();
    }
}

impl<P, E> Stream for MuxedRtcpHandler<P, E> {
    type Item = Result<P, E>;

    #[inline]
    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.inner.poll_next_unpin(cx)
    }
}

impl<P, E> Sink<RtpPacket> for MuxedRtcpHandler<P, E> {
    type Error = E;

    fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        loop {
            if self.sink_error {
                return self.poll_writer_result(cx);
            }

            let res = ready!(SinkExt::<RtpPacket>::poll_ready_unpin(&mut self.inner, cx));

            if res.is_ok() {
                return Poll::Ready(Ok(()));
            } else {
                self.sink_error = true;
            }
        }
    }

    fn start_send(mut self: Pin<&mut Self>, item: RtpPacket) -> Result<(), Self::Error> {
        let res = SinkExt::<RtpPacket>::start_send_unpin(&mut self.inner, item);

        // we cannot get the actual error here, it needs to be polled out from
        // the writer
        if res.is_err() {
            self.sink_error = true;
        }

        Ok(())
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        loop {
            if self.sink_error {
                return self.poll_writer_result(cx);
            }

            let res = ready!(SinkExt::<RtpPacket>::poll_flush_unpin(&mut self.inner, cx));

            if res.is_ok() {
                return Poll::Ready(Ok(()));
            } else {
                self.sink_error = true;
            }
        }
    }

    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        loop {
            if self.sink_error {
                return self.poll_writer_result(cx);
            }

            let res = ready!(SinkExt::<RtpPacket>::poll_close_unpin(&mut self.inner, cx));

            if res.is_ok() {
                return Poll::Ready(Ok(()));
            } else {
                self.sink_error = true;
            }
        }
    }
}

pin_project_lite::pin_project! {
    /// Helper struct.
    struct StreamSink<T, U> {
        #[pin]
        stream: T,
        #[pin]
        sink: U,
    }
}

impl<T, U> StreamSink<T, U> {
    /// Create a new stream-sink.
    fn new(stream: T, sink: U) -> Self {
        Self { stream, sink }
    }
}

impl<T, U> Stream for StreamSink<T, U>
where
    T: Stream,
{
    type Item = T::Item;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.project();

        this.stream.poll_next(cx)
    }
}

impl<T, U, I> Sink<I> for StreamSink<T, U>
where
    U: Sink<I>,
{
    type Error = U::Error;

    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let this = self.project();

        this.sink.poll_ready(cx)
    }

    fn start_send(self: Pin<&mut Self>, item: I) -> Result<(), Self::Error> {
        let this = self.project();

        this.sink.start_send(item)
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let this = self.project();

        this.sink.poll_flush(cx)
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let this = self.project();

        this.sink.poll_close(cx)
    }
}

pin_project_lite::pin_project! {
    /// Helper struct.
    struct PacketMuxer<T> {
        #[pin]
        inner: T,
    }
}

impl<T> PacketMuxer<T> {
    /// Create a new packet muxer.
    fn new(sink: T) -> Self {
        Self { inner: sink }
    }
}

impl<T, I> Sink<I> for PacketMuxer<T>
where
    T: Sink<PacketMux>,
    I: Into<PacketMux>,
{
    type Error = T::Error;

    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let this = self.project();

        this.inner.poll_ready(cx)
    }

    fn start_send(self: Pin<&mut Self>, item: I) -> Result<(), Self::Error> {
        let this = self.project();

        this.inner.start_send(item.into())
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let this = self.project();

        this.inner.poll_flush(cx)
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let this = self.project();

        this.inner.poll_close(cx)
    }
}

pin_project_lite::pin_project! {
    /// Future that will read and process all incoming RTCP packets.
    struct RtcpReceiver<T> {
        #[pin]
        stream: T,
        context: RtcpReceiverContext,
        ignore_decoding_errors: bool,
    }
}

impl<T> RtcpReceiver<T> {
    /// Create a new RTCP receiver.
    fn new(stream: T, context: RtcpContextHandle, ignore_decoding_errors: bool) -> Self {
        Self {
            stream,
            context: RtcpReceiverContext::new(context),
            ignore_decoding_errors,
        }
    }
}

impl<T, E> Future for RtcpReceiver<T>
where
    T: Stream<Item = Result<CompoundRtcpPacket, E>>,
{
    type Output = Result<(), RtcpReceiverError<E>>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut this = self.project();

        loop {
            let stream = this.stream.as_mut();

            match ready!(stream.poll_next(cx)) {
                Some(Ok(packet)) => {
                    if let Err(err) = this.context.process_incoming_rtcp_packet(&packet) {
                        if !*this.ignore_decoding_errors {
                            return Poll::Ready(Err(err.into()));
                        }
                    }
                }
                Some(Err(err)) => return Poll::Ready(Err(RtcpReceiverError::Other(err))),
                None => return Poll::Ready(Ok(())),
            }
        }
    }
}

/// RTCP receiver context.
struct RtcpReceiverContext {
    context: RtcpContextHandle,
}

impl RtcpReceiverContext {
    /// Create a new RTCP receiver context.
    fn new(context: RtcpContextHandle) -> Self {
        Self { context }
    }

    /// Process a given incoming RTCP packet.
    fn process_incoming_rtcp_packet(
        &mut self,
        packet: &CompoundRtcpPacket,
    ) -> Result<(), InvalidInput> {
        for packet in packet.iter() {
            match packet.packet_type() {
                RtcpPacketType::SR => {
                    self.context
                        .process_incoming_sender_report(&SenderReport::decode(packet)?);
                }
                RtcpPacketType::RR => {
                    self.context
                        .process_incoming_receiver_report(&ReceiverReport::decode(packet)?);
                }
                RtcpPacketType::BYE => {
                    self.context
                        .process_incoming_bye_packet(&ByePacket::decode(packet)?);
                }
                _ => (),
            }
        }

        Ok(())
    }
}

/// Internal RTCP receiver error.
enum RtcpReceiverError<E> {
    InvalidInput,
    Other(E),
}

impl<E> From<InvalidInput> for RtcpReceiverError<E> {
    fn from(_: InvalidInput) -> Self {
        Self::InvalidInput
    }
}

/// Generate and send RTCP reports at regular intervals.
///
/// The returned future completes once there are no more RTCP reports to send
/// and the sink has been flushed and closed.
async fn send_rtcp_reports<T>(
    sink: T,
    context: RtcpContextHandle,
    rtcp_report_interval: Duration,
) -> Result<(), T::Error>
where
    T: Sink<CompoundRtcpPacket>,
{
    RtcpOutputStream::new(context, rtcp_report_interval)
        .map(Ok)
        .forward(sink)
        .await
}

/// Stream of outgoing RTCP packets.
struct RtcpOutputStream {
    interval: Interval,
    context: RtcpContextHandle,
    output: VecDeque<CompoundRtcpPacket>,
}

impl RtcpOutputStream {
    /// Create a new stream that will generate RTCP reports at regular
    /// intervals.
    fn new(context: RtcpContextHandle, rtcp_report_interval: Duration) -> Self {
        let start = Instant::now() + (rtcp_report_interval / 2);

        let mut interval = tokio::time::interval_at(start.into(), rtcp_report_interval);

        interval.set_missed_tick_behavior(MissedTickBehavior::Skip);

        Self {
            interval,
            context,
            output: VecDeque::new(),
        }
    }
}

impl Stream for RtcpOutputStream {
    type Item = CompoundRtcpPacket;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        loop {
            if let Some(packet) = self.output.pop_front() {
                return Poll::Ready(Some(packet));
            }

            let closed = self.context.poll_closed(cx);

            if closed.is_pending() {
                ready!(self.interval.poll_tick(cx));
            }

            let packets = self.context.create_rtcp_reports();

            if packets.is_empty() {
                return Poll::Ready(None);
            }

            self.output.extend(packets);
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{
        collections::VecDeque,
        convert::Infallible,
        pin::Pin,
        sync::{Arc, Mutex},
        task::{Context, Poll},
        time::{Duration, Instant},
    };

    use futures::{channel::mpsc, Sink, SinkExt, Stream, StreamExt};

    use super::{MuxedRtcpHandler, RtcpHandler, RtcpHandlerOptions, StreamSink};

    use crate::{
        rtcp::{RtcpContext, RtcpPacketType},
        rtp::{IncomingRtpPacket, OrderedRtpPacket, RtpPacket},
        transceiver::{DefaultRtpTransceiver, RtpTransceiver, RtpTransceiverOptions, SSRCMode},
        utils::PacketMux,
    };

    fn make_rtp_packet(ssrc: u32, seq: u16, timestamp: u32) -> RtpPacket {
        RtpPacket::new()
            .with_ssrc(ssrc)
            .with_sequence_number(seq)
            .with_timestamp(timestamp)
    }

    /// Helper stream-sink for testing.
    #[derive(Clone)]
    struct RtcpTestChannel<I, O> {
        inner: Arc<Mutex<InnerRtcpTestChannel<I, O>>>,
    }

    impl<I, O> RtcpTestChannel<I, O> {
        /// Create a new RTCP test channel.
        fn new<T>(input: T) -> Self
        where
            T: IntoIterator<Item = I>,
        {
            Self {
                inner: Arc::new(Mutex::new(InnerRtcpTestChannel::new(input))),
            }
        }
    }

    impl<I, O> Stream for RtcpTestChannel<I, O> {
        type Item = Result<I, Infallible>;

        fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
            let mut inner = self.inner.lock().unwrap();

            if let Some(packet) = inner.input.pop_front() {
                Poll::Ready(Some(Ok(packet)))
            } else {
                Poll::Pending
            }
        }
    }

    impl<I, O> Sink<O> for RtcpTestChannel<I, O> {
        type Error = Infallible;

        fn poll_ready(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn start_send(self: Pin<&mut Self>, packet: O) -> Result<(), Self::Error> {
            let mut inner = self.inner.lock().unwrap();
            inner.output.push(packet);

            Ok(())
        }

        fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
            self.inner.lock().unwrap().closed = true;

            Poll::Ready(Ok(()))
        }
    }

    /// Inner RTCP test channel.
    struct InnerRtcpTestChannel<I, O> {
        input: VecDeque<I>,
        output: Vec<O>,
        closed: bool,
    }

    impl<I, O> InnerRtcpTestChannel<I, O> {
        /// Create a new inner RTCP test channel.
        fn new<T>(input: T) -> Self
        where
            T: IntoIterator<Item = I>,
        {
            Self {
                input: VecDeque::from_iter(input),
                output: Vec::new(),
                closed: false,
            }
        }
    }

    /// Test transceiver for muxed RTP-RTCP streams.
    #[derive(Clone)]
    struct MuxedTestTransceiver {
        inner: Arc<Mutex<InnerMuxedTestTransceiver>>,
    }

    impl MuxedTestTransceiver {
        /// Create a new muxed RTP-RTCP test transceiver.
        fn new<T>(input: T, options: RtpTransceiverOptions) -> Self
        where
            T: IntoIterator<Item = PacketMux>,
        {
            let inner = InnerMuxedTestTransceiver::new(input, options);

            Self {
                inner: Arc::new(Mutex::new(inner)),
            }
        }
    }

    impl Stream for MuxedTestTransceiver {
        type Item = Result<PacketMux, Infallible>;

        fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
            let mut inner = self.inner.lock().unwrap();

            if let Some(packet) = inner.inner.input.pop_front() {
                let packet = if let PacketMux::Rtp(packet) = packet {
                    let index = packet.sequence_number() as u64;

                    let now = Instant::now();
                    let incoming = IncomingRtpPacket::new(packet, now);
                    let ordered = OrderedRtpPacket::new(incoming, index);

                    inner.context.process_incoming_rtp_packet(&ordered);
                    inner.context.process_ordered_rtp_packet(&ordered);

                    PacketMux::Rtp(ordered.into())
                } else {
                    packet
                };

                Poll::Ready(Some(Ok(packet)))
            } else {
                Poll::Ready(None)
            }
        }
    }

    impl Sink<PacketMux> for MuxedTestTransceiver {
        type Error = Infallible;

        fn poll_ready(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn start_send(self: Pin<&mut Self>, packet: PacketMux) -> Result<(), Self::Error> {
            let mut inner = self.inner.lock().unwrap();

            if let PacketMux::Rtp(packet) = &packet {
                inner.context.process_outgoing_rtp_packet(packet);
            }

            inner.inner.output.push(packet);

            Ok(())
        }

        fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
            let mut inner = self.inner.lock().unwrap();

            inner.inner.closed = true;

            Poll::Ready(Ok(()))
        }
    }

    impl RtpTransceiver for MuxedTestTransceiver {
        fn rtcp_context(&self) -> crate::rtcp::RtcpContextHandle {
            let inner = self.inner.lock().unwrap();

            inner.context.handle()
        }
    }

    /// Inner muxed RTP-RTCP test transceiver.
    struct InnerMuxedTestTransceiver {
        inner: InnerRtcpTestChannel<PacketMux, PacketMux>,
        context: RtcpContext,
    }

    impl InnerMuxedTestTransceiver {
        /// Create a new inner muxed RTP-RTCP test transceiver.
        fn new<T>(input: T, options: RtpTransceiverOptions) -> Self
        where
            T: IntoIterator<Item = PacketMux>,
        {
            Self {
                inner: InnerRtcpTestChannel::new(input),
                context: RtcpContext::new(options),
            }
        }
    }

    #[tokio::test]
    async fn test_handler_task_termination() {
        let (mut incoming_rtp_tx, incoming_rtp_rx) =
            mpsc::unbounded::<Result<RtpPacket, Infallible>>();
        let (outgoing_rtp_tx, outgoing_rtp_rx) = mpsc::unbounded::<RtpPacket>();

        let rtp = StreamSink::new(incoming_rtp_rx, outgoing_rtp_tx);

        let options = RtpTransceiverOptions::new()
            .with_default_clock_rate(1000)
            .with_primary_sender_ssrc(0)
            .with_input_ssrc_mode(SSRCMode::Any);

        let rtp = DefaultRtpTransceiver::<_, Infallible>::new(rtp, options);

        let rtcp = RtcpTestChannel::new([]);

        let options = RtcpHandlerOptions::new()
            .with_ignore_decoding_errors(true)
            .with_rtcp_report_interval(Duration::from_millis(100));

        let handler = RtcpHandler::new(rtp, rtcp.clone(), options);

        let handler = tokio::spawn(async move { handler.collect::<Vec<_>>().await });

        incoming_rtp_tx
            .send(Ok(make_rtp_packet(1, 1, 100)))
            .await
            .unwrap();
        incoming_rtp_tx.close().await.unwrap();

        let incoming_rtp_packets = handler.await.unwrap();

        std::mem::drop(outgoing_rtp_rx);

        assert_eq!(incoming_rtp_packets.len(), 1);

        let packet = incoming_rtp_packets.into_iter().next().unwrap().unwrap();

        assert_eq!(packet.ssrc(), 1);
        assert_eq!(packet.sequence_number(), 1);
        assert_eq!(packet.timestamp(), 100);

        let wait_for_close = async {
            while Arc::strong_count(&rtcp.inner) > 1 {
                tokio::time::sleep(Duration::from_millis(100)).await;
            }
        };

        tokio::time::timeout(Duration::from_secs(1), wait_for_close)
            .await
            .expect("RTCP handler tasks have not terminated");

        // once we reach here, both RTCP handler tasks are already terminated
        let rtcp = Arc::try_unwrap(rtcp.inner)
            .ok()
            .unwrap()
            .into_inner()
            .ok()
            .unwrap();

        assert!(rtcp.closed);

        assert_eq!(rtcp.output.len(), 1);

        let report = &rtcp.output[0];

        assert_eq!(report.len(), 3);

        let rr = &report[0];
        let sdes = &report[1];
        let bye = &report[2];

        assert_eq!(rr.packet_type(), RtcpPacketType::RR);
        assert_eq!(sdes.packet_type(), RtcpPacketType::SDES);
        assert_eq!(bye.packet_type(), RtcpPacketType::BYE);
    }

    #[tokio::test]
    async fn test_muxed_handler_task_termination() {
        let options = RtpTransceiverOptions::new()
            .with_default_clock_rate(1000)
            .with_primary_sender_ssrc(0)
            .with_input_ssrc_mode(SSRCMode::Any);

        let packet = PacketMux::Rtp(make_rtp_packet(1, 1, 100));

        let muxed = MuxedTestTransceiver::new([packet], options);

        let options = RtcpHandlerOptions::new()
            .with_ignore_decoding_errors(true)
            .with_rtcp_report_interval(Duration::from_millis(100));

        let handler = MuxedRtcpHandler::new(muxed.clone(), options);

        let handler = tokio::spawn(async move { handler.collect::<Vec<_>>().await });

        let incoming_rtp_packets = handler.await.unwrap();

        assert_eq!(incoming_rtp_packets.len(), 1);

        let packet = incoming_rtp_packets.into_iter().next().unwrap().unwrap();

        assert_eq!(packet.ssrc(), 1);
        assert_eq!(packet.sequence_number(), 1);
        assert_eq!(packet.timestamp(), 100);

        let wait_for_close = async {
            while Arc::strong_count(&muxed.inner) > 1 {
                tokio::time::sleep(Duration::from_millis(100)).await;
            }
        };

        tokio::time::timeout(Duration::from_secs(1), wait_for_close)
            .await
            .expect("RTCP handler tasks have not terminated");

        // once we reach here, all RTCP handler tasks are already terminated
        let muxed = Arc::try_unwrap(muxed.inner)
            .ok()
            .unwrap()
            .into_inner()
            .ok()
            .unwrap();

        assert!(muxed.inner.closed);

        assert_eq!(muxed.inner.output.len(), 1);

        let PacketMux::Rtcp(report) = &muxed.inner.output[0] else {
            panic!("expected RTCP packet");
        };

        assert_eq!(report.len(), 3);

        let rr = &report[0];
        let sdes = &report[1];
        let bye = &report[2];

        assert_eq!(rr.packet_type(), RtcpPacketType::RR);
        assert_eq!(sdes.packet_type(), RtcpPacketType::SDES);
        assert_eq!(bye.packet_type(), RtcpPacketType::BYE);
    }
}