Skip to main content

rtci_interceptor/
rtp_session.rs

1//! One interceptor instance per RTP session.
2//!
3//! A peer connection whose m= sections are not all in one BUNDLE group runs several RTP
4//! sessions, each on a transport of its own (RFC 8834 section 4.4, RFC 9429 section 5.2.1).
5//! What is kept per session must then be kept per transport: the RTCP session's members,
6//! bandwidth and reduced-size use (RFC 3550 section 6, RFC 5506), the transport-wide sequence
7//! numbers and the feedback about them, the congestion controller's estimate and the pacer's
8//! budget (each path has its own capacity, RFC 8836 section 2).
9//!
10//! [`PerRtpSession`] holds one instance of an interceptor per session and routes to it:
11//!
12//! - a stream (bind / unbind) goes to the session its SSRCs were assigned to
13//!   ([`RtpSessionAssignment`]), or to the first session while none is known;
14//! - a packet carrying [`RtpSession`] goes to that session (the peer connection tags what
15//!   it reads with the transport it arrived on), an RTP packet without one to the session of
16//!   its SSRC, an RTCP packet to that of the first SSRC it names that has one;
17//! - an empty RTCP packet without a tag (a control message for the chain) goes to every
18//!   session, and leaves the wrapper once; a session started later is given the ones it
19//!   missed.
20//!
21//! What an instance writes or reads out is tagged with its session, so the interceptors
22//! further along and the peer connection route it to that session's transport. With one
23//! session (every section bundled) the wrapper holds one instance and changes nothing.
24
25use crate::stream_info::StreamInfo;
26use crate::{Attribute, AttributedPacket, Interceptor, Packet, TaggedPacket};
27use sansio::Protocol;
28use shared::TransportContext;
29use shared::error::Error;
30use std::collections::{BTreeMap, HashMap, VecDeque};
31use std::sync::Arc;
32use std::time::Instant;
33
34/// Names the RTP session (the transport) a packet belongs to. Carried as an
35/// [`Attribute::Custom`]; read it with [`RtpSession::of`].
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
37pub struct RtpSession(pub usize);
38
39impl RtpSession {
40    /// The session `packet` is tagged with.
41    pub fn of(packet: &AttributedPacket) -> Option<usize> {
42        packet.custom::<RtpSession>().map(|session| session.0)
43    }
44
45    /// The attribute that tags a packet with this session.
46    pub fn attribute(self) -> Attribute {
47        Attribute::Custom(Arc::new(self))
48    }
49}
50
51/// A control message: the SSRCs (local and remote, media and repair) of the m= sections that
52/// run in RTP session `session`. Written into the chain as an empty RTCP packet
53/// ([`RtpSessionAssignment::into_packet`]); every [`PerRtpSession`] on the way takes note and
54/// moves a stream it holds in another session.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct RtpSessionAssignment {
57    /// The session.
58    pub session: usize,
59    /// The SSRCs that belong to it.
60    pub ssrcs: Vec<u32>,
61}
62
63impl RtpSessionAssignment {
64    /// The packet that carries this into the chain at `now`.
65    pub fn into_packet(self, now: Instant) -> TaggedPacket {
66        TaggedPacket {
67            now,
68            transport: TransportContext::default(),
69            message: AttributedPacket::new(Packet::Rtcp(vec![]))
70                .with(Attribute::Custom(Arc::new(self))),
71        }
72    }
73}
74
75/// A control message: the transport moved to another selected candidate pair (an ICE restart,
76/// a switch to another pair, a move to another network), after its first one. The peer
77/// connection reads it into the chain on the read leg, as an empty RTCP packet
78/// ([`PathChanged::into_packet`]), so it passes the congestion controllers first: they sit
79/// wire-most. Each starts its estimate over and forgets what it sent before (RFC 8836
80/// section 2, requirement 1: a congestion controller reacts to a change of the path; as
81/// libwebrtc's `RtpTransportControllerSend::OnNetworkRouteChanged` restarts the bandwidth
82/// estimate and has its feedback adapter report only the packets sent on the new route).
83///
84/// The congestion controllers also follow the addresses inbound packets arrive between, which
85/// shows most changes; this one is told also when the addresses do not change (a TURN relay
86/// that keeps them, or an application that hands every datagram over with one placeholder
87/// address pair). With several transports it is tagged with the session ([`RtpSession`]) of
88/// the transport whose pair changed, and reaches only that session's instances.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub struct PathChanged;
91
92impl PathChanged {
93    /// The packet that carries this into the chain's read leg at `now`, tagged with
94    /// `session` when the peer connection runs several transports.
95    pub fn into_packet(self, now: Instant, session: Option<usize>) -> TaggedPacket {
96        let mut message =
97            AttributedPacket::new(Packet::Rtcp(vec![])).with(Attribute::Custom(Arc::new(self)));
98        if let Some(session) = session {
99            message.add(RtpSession(session).attribute());
100        }
101        TaggedPacket {
102            now,
103            transport: TransportContext::default(),
104            message,
105        }
106    }
107}
108
109/// Marks a copy of a broadcast control message given to a session other than the first:
110/// whatever of it comes out again is dropped, so the message leaves the wrapper once. The
111/// mark goes on last: what an instance attaches after it is its own and leaves on a carrier
112/// tagged with its session.
113#[derive(Debug)]
114struct BroadcastCopy;
115
116/// Marks the copy of a broadcast control message given to the first session: it leaves the
117/// wrapper as it came, untagged; what an instance attaches to it leaves as for
118/// [`BroadcastCopy`].
119#[derive(Debug)]
120struct Passthrough;
121
122/// The most broadcast control messages kept for a session that starts later.
123const MAX_REPLAYED_CONTROLS: usize = 512;
124
125/// The most SSRCs whose session is learned from the reports they send.
126const MAX_LEARNED_SSRCS: usize = 4096;
127
128/// The SSRC that sent a sender or receiver report.
129fn rtcp_sender_ssrc(packet: &dyn rtcp::Packet) -> Option<u32> {
130    let any = packet.as_any();
131    any.downcast_ref::<rtcp::receiver_report::ReceiverReport>()
132        .map(|rr| rr.ssrc)
133        .or_else(|| {
134            any.downcast_ref::<rtcp::sender_report::SenderReport>()
135                .map(|sr| sr.ssrc)
136        })
137}
138
139fn duplicate(msg: &TaggedPacket) -> TaggedPacket {
140    TaggedPacket {
141        now: msg.now,
142        transport: msg.transport,
143        message: msg.message.clone(),
144    }
145}
146
147type Factory<T> = Box<dyn FnMut(usize) -> T + Send + Sync>;
148
149/// An interceptor instance per RTP session; see the `rtp_session` module's source documentation.
150pub struct PerRtpSession<T: Interceptor> {
151    factory: Factory<T>,
152    instances: BTreeMap<usize, T>,
153    /// The session of each SSRC, from assignments and tagged reads.
154    sessions: HashMap<u32, usize>,
155    /// The streams bound, by media SSRC and direction (`true`: local), with the session
156    /// each is bound in.
157    streams: HashMap<(bool, u32), (StreamInfo, usize)>,
158    /// Broadcast control messages, for a session that starts later.
159    controls: VecDeque<TaggedPacket>,
160    read_queue: VecDeque<TaggedPacket>,
161    write_queue: VecDeque<TaggedPacket>,
162}
163
164impl<T: Interceptor> PerRtpSession<T> {
165    /// A wrapper whose sessions are each given an instance `factory` makes. The first is
166    /// made now, for session 0.
167    pub fn new(mut factory: impl FnMut() -> T + Send + Sync + 'static) -> Self {
168        let first = factory();
169        Self::with_first(first, factory)
170    }
171
172    /// A wrapper whose session 0 is `first` and whose other sessions each get an instance
173    /// `factory` makes.
174    pub fn with_first(first: T, mut factory: impl FnMut() -> T + Send + Sync + 'static) -> Self {
175        Self::with_first_for_sessions(first, move |_| factory())
176    }
177
178    /// A wrapper whose session 0 is `first` and whose other sessions each get the instance
179    /// `factory` makes for the session's number (to hand out a per-session handle).
180    pub fn with_first_for_sessions(
181        first: T,
182        factory: impl FnMut(usize) -> T + Send + Sync + 'static,
183    ) -> Self {
184        Self {
185            factory: Box::new(factory),
186            instances: BTreeMap::from([(0, first)]),
187            sessions: HashMap::new(),
188            streams: HashMap::new(),
189            controls: VecDeque::new(),
190            read_queue: VecDeque::new(),
191            write_queue: VecDeque::new(),
192        }
193    }
194
195    /// The sessions that have an instance, in order.
196    pub fn sessions(&self) -> Vec<usize> {
197        self.instances.keys().copied().collect()
198    }
199
200    /// The instance of `session`, if it has one.
201    pub fn instance(&self, session: usize) -> Option<&T> {
202        self.instances.get(&session)
203    }
204
205    /// The first session's instance (the only one while every section is bundled).
206    pub fn first(&self) -> &T {
207        self.instances
208            .values()
209            .next()
210            .expect("a wrapper always holds an instance")
211    }
212
213    fn home(&self) -> usize {
214        *self
215            .instances
216            .keys()
217            .next()
218            .expect("a wrapper always holds an instance")
219    }
220
221    /// The instance of `session`, made (and given the control messages it missed) when it
222    /// has none yet.
223    fn ensure(&mut self, session: usize) -> &mut T {
224        if !self.instances.contains_key(&session) {
225            let mut instance = (self.factory)(session);
226            for control in &self.controls {
227                let mut copy = duplicate(control);
228                copy.message.add(Attribute::Custom(Arc::new(BroadcastCopy)));
229                let _ = instance.handle_write(copy);
230            }
231            self.instances.insert(session, instance);
232        }
233        self.instances
234            .get_mut(&session)
235            .expect("the instance was just made")
236    }
237
238    fn session_of_info(&self, info: &StreamInfo) -> usize {
239        std::iter::once(info.ssrc)
240            .chain(info.ssrc_rtx)
241            .chain(info.ssrc_fec)
242            .find_map(|ssrc| self.sessions.get(&ssrc).copied())
243            .unwrap_or_else(|| self.home())
244    }
245
246    fn bind(&mut self, local: bool, info: &StreamInfo, session: usize) {
247        let instance = self.ensure(session);
248        if local {
249            instance.bind_local_stream(info);
250        } else {
251            instance.bind_remote_stream(info);
252        }
253        self.streams
254            .insert((local, info.ssrc), (info.clone(), session));
255    }
256
257    fn unbind(&mut self, local: bool, ssrc: u32) -> Option<StreamInfo> {
258        let (info, session) = self.streams.remove(&(local, ssrc))?;
259        if let Some(instance) = self.instances.get_mut(&session) {
260            if local {
261                instance.unbind_local_stream(&info);
262            } else {
263                instance.unbind_remote_stream(&info);
264            }
265        }
266        self.drop_if_empty(session);
267        Some(info)
268    }
269
270    /// A session left with no stream goes, unless it is the only one: its transport is gone
271    /// or its sections moved to another.
272    fn drop_if_empty(&mut self, session: usize) {
273        if self.instances.len() > 1
274            && !self.streams.values().any(|(_, s)| *s == session)
275            && let Some(mut instance) = self.instances.remove(&session)
276        {
277            self.drain_instance(session, &mut instance);
278        }
279    }
280
281    /// Moves every stream with an SSRC in `ssrcs` that is bound in another session to
282    /// `session`.
283    fn reassign(&mut self, session: usize, ssrcs: &[u32]) {
284        for ssrc in ssrcs {
285            self.sessions.insert(*ssrc, session);
286        }
287        let moving: Vec<(bool, u32)> = self
288            .streams
289            .iter()
290            .filter(|(_, (info, bound))| {
291                *bound != session
292                    && std::iter::once(info.ssrc)
293                        .chain(info.ssrc_rtx)
294                        .chain(info.ssrc_fec)
295                        .any(|ssrc| ssrcs.contains(&ssrc))
296            })
297            .map(|(key, _)| *key)
298            .collect();
299        // Bound in the new session first, so the old one is not the last and kept.
300        for (local, ssrc) in moving {
301            if let Some((info, from)) = self.streams.get(&(local, ssrc)).cloned() {
302                let instance = self.ensure(session);
303                if local {
304                    instance.bind_local_stream(&info);
305                } else {
306                    instance.bind_remote_stream(&info);
307                }
308                self.streams.insert((local, ssrc), (info.clone(), session));
309                if let Some(old) = self.instances.get_mut(&from) {
310                    if local {
311                        // The stream goes on in the other session: it moves, it does not
312                        // leave (no BYE on the old transport, RFC 3550 6.6).
313                        old.move_local_stream_out(&info);
314                    } else {
315                        old.unbind_remote_stream(&info);
316                    }
317                }
318                self.drop_if_empty(from);
319            }
320        }
321    }
322
323    /// The session a packet without a tag belongs to; `None` for a broadcast control message.
324    fn session_of_packet(&self, packet: &Packet) -> Option<usize> {
325        match packet {
326            Packet::Rtp(rtp) => Some(
327                self.sessions
328                    .get(&rtp.header.ssrc)
329                    .copied()
330                    .or_else(|| self.stream_session(rtp.header.ssrc))
331                    .unwrap_or_else(|| self.home()),
332            ),
333            Packet::Rtcp(packets) if packets.is_empty() => None,
334            // The session of the first SSRC the compound packet is about, else that of its
335            // sender (a receiver report without blocks names no stream, only who sent it), else
336            // the first session.
337            Packet::Rtcp(packets) => Some(
338                packets
339                    .iter()
340                    .flat_map(|packet| packet.destination_ssrc())
341                    .chain(
342                        packets
343                            .iter()
344                            .filter_map(|packet| rtcp_sender_ssrc(packet.as_ref())),
345                    )
346                    .find_map(|ssrc| {
347                        self.sessions
348                            .get(&ssrc)
349                            .copied()
350                            .or_else(|| self.stream_session(ssrc))
351                    })
352                    .unwrap_or_else(|| self.home()),
353            ),
354            #[allow(unreachable_patterns)]
355            _ => Some(self.home()),
356        }
357    }
358
359    fn stream_session(&self, ssrc: u32) -> Option<usize> {
360        self.streams.values().find_map(|(info, session)| {
361            std::iter::once(info.ssrc)
362                .chain(info.ssrc_rtx)
363                .chain(info.ssrc_fec)
364                .any(|s| s == ssrc)
365                .then_some(*session)
366        })
367    }
368
369    /// What an instance hands on, tagged with its session (or, for a broadcast control
370    /// message, as it came, once).
371    fn emit(session: usize, mut packet: TaggedPacket, queue: &mut VecDeque<TaggedPacket>) {
372        // What an instance attached to a broadcast copy (an estimate riding on a carrier
373        // that every session was given) is that session's: it leaves on a carrier of its own,
374        // tagged with the session, whatever becomes of the copy.
375        // The mark goes on last, so what follows it was attached by the instance.
376        let mark = packet.message.attributes.iter().position(|a| {
377            matches!(a, Attribute::Custom(value)
378                if value.is::<BroadcastCopy>() || value.is::<Passthrough>())
379        });
380        if let Some(mark) = mark
381            && packet.message.attributes.len() > mark + 1
382        {
383            let added = packet.message.attributes.split_off(mark + 1);
384            let mut carrier = AttributedPacket::new(Packet::Rtcp(vec![]));
385            for attribute in added {
386                carrier.add(attribute);
387            }
388            carrier.add(RtpSession(session).attribute());
389            queue.push_back(TaggedPacket {
390                now: packet.now,
391                transport: packet.transport,
392                message: carrier,
393            });
394        }
395        let tagged = RtpSession::of(&packet.message).is_some();
396        let attributes = &mut packet.message.attributes;
397        let marked = |attribute: &Attribute, copy: bool| match attribute {
398            Attribute::Custom(value) => {
399                if copy {
400                    value.downcast_ref::<BroadcastCopy>().is_some()
401                } else {
402                    value.downcast_ref::<Passthrough>().is_some()
403                }
404            }
405            _ => false,
406        };
407        if attributes.iter().any(|a| marked(a, true)) {
408            return;
409        }
410        if attributes.iter().any(|a| marked(a, false)) {
411            attributes.retain(|a| !marked(a, false));
412        } else if !tagged {
413            attributes.push(RtpSession(session).attribute());
414        }
415        queue.push_back(packet);
416    }
417
418    fn drain_instance(&mut self, session: usize, instance: &mut T) {
419        while let Some(packet) = instance.poll_read() {
420            Self::emit(session, packet, &mut self.read_queue);
421        }
422        while let Some(packet) = instance.poll_write() {
423            Self::emit(session, packet, &mut self.write_queue);
424        }
425    }
426
427    fn drain(&mut self) {
428        for (session, instance) in self.instances.iter_mut() {
429            while let Some(packet) = instance.poll_read() {
430                Self::emit(*session, packet, &mut self.read_queue);
431            }
432            while let Some(packet) = instance.poll_write() {
433                Self::emit(*session, packet, &mut self.write_queue);
434            }
435        }
436    }
437
438    /// Hands `msg` to its session, or to all of them.
439    fn dispatch(&mut self, msg: TaggedPacket, write: bool) -> Result<(), Error> {
440        if let Some(assignment) = msg.message.custom::<RtpSessionAssignment>() {
441            let assignment = assignment.clone();
442            self.reassign(assignment.session, &assignment.ssrcs);
443            // Every wrapper on the way takes note: it goes on as it came.
444            if write {
445                self.write_queue.push_back(msg);
446            } else {
447                self.read_queue.push_back(msg);
448            }
449            return Ok(());
450        }
451        let session =
452            RtpSession::of(&msg.message).or_else(|| self.session_of_packet(&msg.message.packet));
453        let handle = |instance: &mut T, msg: TaggedPacket| {
454            if write {
455                instance.handle_write(msg)
456            } else {
457                instance.handle_read(msg)
458            }
459        };
460        match session {
461            Some(session) => {
462                // A read names the transport it arrived on: its media SSRC belongs to that
463                // session from now on.
464                if !write
465                    && RtpSession::of(&msg.message).is_some()
466                    && let Packet::Rtp(rtp) = &msg.message.packet
467                    && self.sessions.get(&rtp.header.ssrc) != Some(&session)
468                {
469                    let ssrc = rtp.header.ssrc;
470                    self.reassign(session, &[ssrc]);
471                }
472                // The sender of a report read on a transport is in that transport's session,
473                // so a later report from it routes there without a tag.
474                if !write
475                    && RtpSession::of(&msg.message).is_some()
476                    && let Packet::Rtcp(packets) = &msg.message.packet
477                {
478                    for ssrc in packets.iter().filter_map(|p| rtcp_sender_ssrc(p.as_ref())) {
479                        if !self.sessions.contains_key(&ssrc)
480                            && self.sessions.len() < MAX_LEARNED_SSRCS
481                        {
482                            self.sessions.insert(ssrc, session);
483                        }
484                    }
485                }
486                handle(self.ensure(session), msg)?;
487            }
488            None => {
489                if write {
490                    if self.controls.len() == MAX_REPLAYED_CONTROLS {
491                        self.controls.pop_front();
492                    }
493                    self.controls.push_back(duplicate(&msg));
494                }
495                let home = self.home();
496                for (session, instance) in self.instances.iter_mut() {
497                    let mut copy = duplicate(&msg);
498                    copy.message.add(Attribute::Custom(if *session == home {
499                        Arc::new(Passthrough) as Arc<dyn std::any::Any + Send + Sync>
500                    } else {
501                        Arc::new(BroadcastCopy)
502                    }));
503                    handle(instance, copy)?;
504                }
505            }
506        }
507        self.drain();
508        Ok(())
509    }
510}
511
512impl<T: Interceptor> Protocol<TaggedPacket, TaggedPacket, ()> for PerRtpSession<T> {
513    type Rout = TaggedPacket;
514    type Wout = TaggedPacket;
515    type Eout = ();
516    type Error = Error;
517    type Time = Instant;
518
519    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
520        self.dispatch(msg, false)
521    }
522
523    fn poll_read(&mut self) -> Option<Self::Rout> {
524        if self.read_queue.is_empty() {
525            self.drain();
526        }
527        self.read_queue.pop_front()
528    }
529
530    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
531        self.dispatch(msg, true)
532    }
533
534    fn poll_write(&mut self) -> Option<Self::Wout> {
535        if self.write_queue.is_empty() {
536            self.drain();
537        }
538        self.write_queue.pop_front()
539    }
540
541    fn handle_timeout(&mut self, now: Self::Time) -> Result<(), Self::Error> {
542        for instance in self.instances.values_mut() {
543            instance.handle_timeout(now)?;
544        }
545        self.drain();
546        Ok(())
547    }
548
549    fn poll_timeout(&mut self) -> Option<Self::Time> {
550        self.instances
551            .values_mut()
552            .filter_map(|instance| instance.poll_timeout())
553            .min()
554    }
555
556    fn close(&mut self) -> Result<(), Self::Error> {
557        for instance in self.instances.values_mut() {
558            instance.close()?;
559        }
560        self.drain();
561        Ok(())
562    }
563}
564
565impl<T: Interceptor> Interceptor for PerRtpSession<T> {
566    fn bind_local_stream(&mut self, info: &StreamInfo) {
567        let session = match self.streams.get(&(true, info.ssrc)) {
568            Some((_, bound)) => *bound,
569            None => self.session_of_info(info),
570        };
571        self.bind(true, info, session);
572    }
573
574    fn unbind_local_stream(&mut self, info: &StreamInfo) {
575        self.unbind(true, info.ssrc);
576    }
577
578    fn bind_remote_stream(&mut self, info: &StreamInfo) {
579        let session = match self.streams.get(&(false, info.ssrc)) {
580            Some((_, bound)) => *bound,
581            None => self.session_of_info(info),
582        };
583        self.bind(false, info, session);
584    }
585
586    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
587        self.unbind(false, info.ssrc);
588    }
589}
590
591#[cfg(test)]
592mod tests {
593    use super::*;
594    use crate::{RtcpSessionBuilder, RtcpSessionControl};
595    use std::collections::HashSet;
596    use std::sync::Mutex;
597    use std::time::Duration;
598
599    /// What each instance was given: (instance number, SSRC or `None` for a control).
600    type Log = Arc<Mutex<Vec<(usize, Option<u32>)>>>;
601
602    struct Recorder {
603        number: usize,
604        log: Log,
605        queue: VecDeque<TaggedPacket>,
606        read: VecDeque<TaggedPacket>,
607    }
608
609    impl Protocol<TaggedPacket, TaggedPacket, ()> for Recorder {
610        type Rout = TaggedPacket;
611        type Wout = TaggedPacket;
612        type Eout = ();
613        type Error = Error;
614        type Time = Instant;
615        fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Error> {
616            // An estimate riding on a carrier, as a congestion controller attaches one.
617            if matches!(&msg.message.packet, Packet::Rtcp(packets) if packets.is_empty()) {
618                msg.message.add(Attribute::TargetBitrateChanged {
619                    bits_per_second: self.number as f64,
620                });
621            }
622            self.read.push_back(msg);
623            Ok(())
624        }
625        fn poll_read(&mut self) -> Option<TaggedPacket> {
626            self.read.pop_front()
627        }
628        fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Error> {
629            let ssrc = match &msg.message.packet {
630                Packet::Rtp(rtp) => Some(rtp.header.ssrc),
631                _ => None,
632            };
633            self.log.lock().unwrap().push((self.number, ssrc));
634            self.queue.push_back(msg);
635            Ok(())
636        }
637        fn poll_write(&mut self) -> Option<TaggedPacket> {
638            self.queue.pop_front()
639        }
640    }
641
642    impl Interceptor for Recorder {
643        fn bind_local_stream(&mut self, _: &StreamInfo) {}
644        fn unbind_local_stream(&mut self, _: &StreamInfo) {}
645        fn bind_remote_stream(&mut self, _: &StreamInfo) {}
646        fn unbind_remote_stream(&mut self, _: &StreamInfo) {}
647    }
648
649    fn recorders(log: &Log) -> PerRtpSession<Recorder> {
650        let log = log.clone();
651        let mut number = 0;
652        PerRtpSession::new(move || {
653            number += 1;
654            Recorder {
655                number,
656                log: log.clone(),
657                queue: VecDeque::new(),
658                read: VecDeque::new(),
659            }
660        })
661    }
662
663    fn rtp(now: Instant, ssrc: u32, sequence_number: u16) -> TaggedPacket {
664        TaggedPacket {
665            now,
666            transport: TransportContext::default(),
667            message: AttributedPacket::new(Packet::Rtp(rtp::Packet {
668                header: rtp::header::Header {
669                    version: 2,
670                    ssrc,
671                    sequence_number,
672                    payload_type: 111,
673                    ..Default::default()
674                },
675                payload: vec![0u8; 100].into(),
676            })),
677        }
678    }
679
680    fn stream(ssrc: u32) -> StreamInfo {
681        StreamInfo {
682            ssrc,
683            clock_rate: 48_000,
684            mime_type: "audio/opus".to_owned(),
685            payload_type: 111,
686            ..Default::default()
687        }
688    }
689
690    #[test]
691    fn packets_reach_the_instance_of_their_session_and_leave_tagged_with_it() {
692        let log = Log::default();
693        let mut wrapper = recorders(&log);
694        let now = Instant::now();
695        for (session, ssrc) in [(0, 1), (1, 2)] {
696            wrapper
697                .handle_write(
698                    RtpSessionAssignment {
699                        session,
700                        ssrcs: vec![ssrc],
701                    }
702                    .into_packet(now),
703                )
704                .unwrap();
705        }
706        wrapper.bind_local_stream(&stream(1));
707        wrapper.bind_local_stream(&stream(2));
708        for n in 0..3 {
709            wrapper.handle_write(rtp(now, 1, n)).unwrap();
710            wrapper.handle_write(rtp(now, 2, n)).unwrap();
711        }
712        assert_eq!(wrapper.sessions(), vec![0, 1]);
713        let got = log.lock().unwrap().clone();
714        assert!(
715            got.iter()
716                .filter(|(_, s)| s.is_some())
717                .all(|(n, s)| *s == Some(*n as u32)),
718            "{got:?}"
719        );
720        let mut out = vec![];
721        while let Some(packet) = wrapper.poll_write() {
722            if let Packet::Rtp(rtp) = &packet.message.packet {
723                out.push((rtp.header.ssrc, RtpSession::of(&packet.message)));
724            }
725        }
726        assert_eq!(out.len(), 6);
727        assert!(
728            out.iter()
729                .all(|(ssrc, session)| *session == Some(*ssrc as usize - 1)),
730            "{out:?}"
731        );
732    }
733
734    #[test]
735    fn a_control_message_reaches_every_session_and_leaves_once() {
736        let log = Log::default();
737        let mut wrapper = recorders(&log);
738        let now = Instant::now();
739        wrapper
740            .handle_write(
741                RtpSessionAssignment {
742                    session: 1,
743                    ssrcs: vec![2],
744                }
745                .into_packet(now),
746            )
747            .unwrap();
748        wrapper.bind_local_stream(&stream(1));
749        wrapper.bind_local_stream(&stream(2));
750        while wrapper.poll_write().is_some() {}
751        log.lock().unwrap().clear();
752        wrapper
753            .handle_write(RtcpSessionControl::Start.into_packet(now))
754            .unwrap();
755        let got = log.lock().unwrap().clone();
756        assert_eq!(got, vec![(1, None), (2, None)]);
757        let out: Vec<_> = std::iter::from_fn(|| wrapper.poll_write()).collect();
758        assert_eq!(out.len(), 1, "the control leaves the wrapper once");
759        assert_eq!(
760            RtpSession::of(&out[0].message),
761            None,
762            "as it came, untagged"
763        );
764        assert!(out[0].message.custom::<RtcpSessionControl>().is_some());
765        assert!(out[0].message.custom::<Passthrough>().is_none());
766    }
767
768    #[test]
769    fn a_session_made_later_is_given_the_control_messages_it_missed() {
770        let log = Log::default();
771        let mut wrapper = recorders(&log);
772        let now = Instant::now();
773        wrapper
774            .handle_write(RtcpSessionControl::Start.into_packet(now))
775            .unwrap();
776        while wrapper.poll_write().is_some() {}
777        wrapper
778            .handle_write(
779                RtpSessionAssignment {
780                    session: 4,
781                    ssrcs: vec![9],
782                }
783                .into_packet(now),
784            )
785            .unwrap();
786        wrapper.bind_local_stream(&stream(9));
787        let got = log.lock().unwrap().clone();
788        assert_eq!(
789            got,
790            vec![(1, None), (2, None)],
791            "the new instance got the Start it missed"
792        );
793        let out: Vec<_> = std::iter::from_fn(|| wrapper.poll_write()).collect();
794        assert!(
795            out.iter()
796                .all(|p| p.message.custom::<RtcpSessionControl>().is_none()),
797            "a replayed control does not leave the wrapper again"
798        );
799        // The first session lost its last stream to none: it stays while it is not empty.
800        assert_eq!(wrapper.sessions(), vec![0, 4]);
801    }
802
803    #[test]
804    fn a_read_moves_a_remote_stream_to_the_transport_it_arrived_on() {
805        let log = Log::default();
806        let mut wrapper = recorders(&log);
807        let now = Instant::now();
808        wrapper.bind_remote_stream(&stream(7));
809        wrapper.bind_local_stream(&stream(1));
810        let mut packet = rtp(now, 7, 0);
811        packet.message.add(RtpSession(3).attribute());
812        wrapper.handle_read(packet).unwrap();
813        assert_eq!(wrapper.sessions(), vec![0, 3]);
814        assert_eq!(wrapper.stream_session(7), Some(3));
815        let out = wrapper.poll_read().expect("the packet goes on");
816        assert_eq!(RtpSession::of(&out.message), Some(3));
817    }
818
819    /// RFC 3550 section 6 and RFC 8834 section 4.4: each RTP session has its own RTCP
820    /// session. With the sections of two transports, each compound packet reports on the
821    /// streams of one transport only and is tagged with it.
822    #[test]
823    fn each_rtcp_session_reports_on_the_streams_of_its_own_transport() {
824        let mut wrapper = RtcpSessionBuilder::new()
825            .with_t_rr_interval(Duration::ZERO)
826            .build_per_rtp_session();
827        let mut now = Instant::now();
828        // Session 0: local 0x10, remote 0x20; session 1: local 0x11, remote 0x21.
829        let sessions = [(0usize, [0x10u32, 0x20u32]), (1, [0x11, 0x21])];
830        for (session, ssrcs) in sessions {
831            wrapper
832                .handle_write(
833                    RtpSessionAssignment {
834                        session,
835                        ssrcs: ssrcs.to_vec(),
836                    }
837                    .into_packet(now),
838                )
839                .unwrap();
840            wrapper.bind_local_stream(&stream(ssrcs[0]));
841            wrapper.bind_remote_stream(&stream(ssrcs[1]));
842        }
843        wrapper
844            .handle_write(RtcpSessionControl::Start.into_packet(now))
845            .unwrap();
846        let mut reports = vec![];
847        for step in 0..400u16 {
848            now += Duration::from_millis(20);
849            for (session, ssrcs) in sessions {
850                wrapper.handle_write(rtp(now, ssrcs[0], step)).unwrap();
851                let mut arrival = rtp(now, ssrcs[1], step);
852                arrival.message.add(RtpSession(session).attribute());
853                wrapper.handle_read(arrival).unwrap();
854            }
855            wrapper.handle_timeout(now).unwrap();
856            while wrapper.poll_read().is_some() {}
857            while let Some(packet) = wrapper.poll_write() {
858                if let Packet::Rtcp(packets) = &packet.message.packet
859                    && !packets.is_empty()
860                {
861                    let named: HashSet<u32> =
862                        packets.iter().flat_map(|p| p.destination_ssrc()).collect();
863                    reports.push((RtpSession::of(&packet.message), named));
864                }
865            }
866        }
867        assert!(reports.len() > 10, "{}", reports.len());
868        for (tag, named) in &reports {
869            let session = tag.expect("tagged with its session");
870            let own: HashSet<u32> = sessions[session].1.into_iter().collect();
871            assert!(named.is_subset(&own), "session {session} named {named:x?}");
872        }
873        for session in [0, 1] {
874            assert!(reports.iter().any(|(tag, _)| *tag == Some(session)));
875        }
876    }
877
878    /// A receiver report without report blocks names no stream: it is routed by its sender,
879    /// to the session the sender's stream is bound in (not to the first session).
880    #[test]
881    fn a_receiver_report_without_blocks_goes_to_its_senders_session() {
882        let log = Log::default();
883        let mut wrapper = recorders(&log);
884        let now = Instant::now();
885        wrapper
886            .handle_write(
887                RtpSessionAssignment {
888                    session: 1,
889                    ssrcs: vec![0x21],
890                }
891                .into_packet(now),
892            )
893            .unwrap();
894        wrapper.bind_remote_stream(&stream(0x21));
895        wrapper.bind_local_stream(&stream(0x10));
896        while wrapper.poll_write().is_some() {}
897        while wrapper.poll_read().is_some() {}
898        let report = TaggedPacket {
899            now,
900            transport: TransportContext::default(),
901            message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
902                rtcp::receiver_report::ReceiverReport {
903                    ssrc: 0x21,
904                    ..Default::default()
905                },
906            )])),
907        };
908        wrapper.handle_read(report).unwrap();
909        let out = wrapper.poll_read().expect("the report goes on");
910        assert_eq!(RtpSession::of(&out.message), Some(1));
911    }
912
913    /// RFC 3550 section 6.6: BYE is for a source leaving the session. A stream whose section
914    /// moves to another transport (a bundling answer) carries on in that session: the session
915    /// it leaves, which keeps another section, says no BYE for it, and the session it joins
916    /// reports on it.
917    #[test]
918    fn a_stream_moving_to_another_session_says_no_goodbye() {
919        let mut wrapper = RtcpSessionBuilder::new()
920            .with_t_rr_interval(Duration::ZERO)
921            .build_per_rtp_session();
922        let mut now = Instant::now();
923        let sections = [(0usize, 0x10u32, 0x20u32), (1, 0x11, 0x21), (1, 0x12, 0x22)];
924        for (session, local, remote) in sections {
925            wrapper
926                .handle_write(
927                    RtpSessionAssignment {
928                        session,
929                        ssrcs: vec![local, remote],
930                    }
931                    .into_packet(now),
932                )
933                .unwrap();
934            wrapper.bind_local_stream(&stream(local));
935            wrapper.bind_remote_stream(&stream(remote));
936        }
937        wrapper
938            .handle_write(RtcpSessionControl::Start.into_packet(now))
939            .unwrap();
940        let mut goodbyes = vec![];
941        let mut reported_in_zero = false;
942        for step in 0..600u16 {
943            now += Duration::from_millis(20);
944            if step == 200 {
945                // The section of 0x11 moves to the first transport; 0x12's stays.
946                wrapper
947                    .handle_write(
948                        RtpSessionAssignment {
949                            session: 0,
950                            ssrcs: vec![0x10, 0x20, 0x11, 0x21],
951                        }
952                        .into_packet(now),
953                    )
954                    .unwrap();
955            }
956            for (_, local, remote) in sections {
957                wrapper.handle_write(rtp(now, local, step)).unwrap();
958                wrapper.handle_read(rtp(now, remote, step)).unwrap();
959            }
960            wrapper.handle_timeout(now).unwrap();
961            while wrapper.poll_read().is_some() {}
962            while let Some(packet) = wrapper.poll_write() {
963                if let Packet::Rtcp(packets) = &packet.message.packet {
964                    for p in packets {
965                        if let Some(bye) = p.as_any().downcast_ref::<rtcp::goodbye::Goodbye>() {
966                            goodbyes.extend(bye.sources.iter().copied());
967                        }
968                        if step > 300
969                            && RtpSession::of(&packet.message) == Some(0)
970                            && p.as_any()
971                                .downcast_ref::<rtcp::sender_report::SenderReport>()
972                                .is_some_and(|sr| sr.ssrc == 0x11)
973                        {
974                            reported_in_zero = true;
975                        }
976                    }
977                }
978            }
979        }
980        assert!(
981            !goodbyes.contains(&0x11),
982            "no BYE for the stream that moved: {goodbyes:x?}"
983        );
984        assert!(
985            reported_in_zero,
986            "the session it moved to sends its sender report"
987        );
988        assert_eq!(
989            wrapper.sessions(),
990            vec![0, 1],
991            "the second session keeps its section"
992        );
993    }
994
995    /// A carrier read without a tag goes to every session. What each session's instance
996    /// attaches to it (a congestion controller's estimate) leaves tagged with that session, the
997    /// first session's included: it is that transport's, not the transport the connection
998    /// happens to be working on.
999    #[test]
1000    fn what_a_session_attaches_to_a_broadcast_leaves_tagged_with_it() {
1001        let log = Log::default();
1002        let mut wrapper = recorders(&log);
1003        let now = Instant::now();
1004        wrapper
1005            .handle_write(
1006                RtpSessionAssignment {
1007                    session: 1,
1008                    ssrcs: vec![2],
1009                }
1010                .into_packet(now),
1011            )
1012            .unwrap();
1013        wrapper.bind_local_stream(&stream(1));
1014        wrapper.bind_local_stream(&stream(2));
1015        while wrapper.poll_read().is_some() {}
1016        let carrier = TaggedPacket {
1017            now,
1018            transport: TransportContext::default(),
1019            message: AttributedPacket::new(Packet::Rtcp(vec![])),
1020        };
1021        wrapper.handle_read(carrier).unwrap();
1022        let mut estimates = vec![];
1023        while let Some(packet) = wrapper.poll_read() {
1024            for attribute in &packet.message.attributes {
1025                if let Attribute::TargetBitrateChanged { bits_per_second } = attribute {
1026                    estimates.push((RtpSession::of(&packet.message), *bits_per_second));
1027                }
1028            }
1029        }
1030        estimates.sort_by(|a, b| a.partial_cmp(b).unwrap());
1031        // Instance 1 serves session 0, instance 2 session 1.
1032        assert_eq!(estimates, vec![(Some(0), 1.0), (Some(1), 2.0)]);
1033    }
1034}