Skip to main content

str0m/streams/
mod.rs

1// Changed by Alakazam Labs for sew-str0m; the fork's patches are listed in its README.
2use std::collections::{HashMap, VecDeque};
3use std::fmt::{self};
4use std::sync::Arc;
5use std::time::Duration;
6use std::time::Instant;
7
8use crate::config_mod::RtcpReportIntervals;
9use crate::format::CodecConfig;
10use crate::format::PayloadParams;
11use crate::media::{KeyframeRequest, MID_PROBE, Media, SenderFeedback};
12use crate::pacer::QueueState;
13use crate::packet::Vp8Patch;
14use crate::rtp_::MidRid;
15use crate::rtp_::Ssrc;
16use crate::rtp_::{Bitrate, Pt};
17use crate::rtp_::{DlrrItem, Rtcp, RtcpFb, RtpHeader};
18use crate::rtp_::{MediaTime, SenderInfo};
19use crate::rtp_::{Mid, Rid, SeqNo};
20use crate::util::already_happened;
21
22pub use self::receive::StreamRx;
23pub use self::send::{NackPolicy, RtpWrite, StreamTx, StreamTxQueueInfo};
24
25mod receive;
26pub(crate) mod register;
27pub(crate) mod register_nack;
28mod rtx_cache;
29pub(crate) mod rtx_cache_buf;
30mod send;
31mod send_queue;
32mod send_stats;
33
34pub(crate) use send::{DEFAULT_RTX_CACHE_DURATION, DEFAULT_RTX_RATIO_CAP};
35
36pub(crate) struct StreamTimeoutConfig<'a> {
37    pub(crate) codecs: &'a CodecConfig,
38    pub(crate) intervals: RtcpReportIntervals,
39}
40
41/// Packet of RTP data.
42///
43/// As emitted by [`Event::RtpPacket`][crate::Event::RtpPacket] when using rtp mode.
44#[derive(PartialEq, Eq)]
45pub struct RtpPacket {
46    /// Extended sequence number to avoid having to deal with ROC.
47    pub seq_no: SeqNo,
48
49    /// Extended RTP time in the clock frequency of the codec. To avoid dealing with ROC.
50    ///
51    /// For a newly scheduled outgoing packet, the clock_rate is not correctly set until
52    /// we do the poll_output().
53    pub time: MediaTime,
54
55    /// Parsed RTP header.
56    pub header: RtpHeader,
57
58    /// RTP payload. This contains no header.
59    pub payload: Arc<[u8]>,
60
61    vp8_patch: Option<Vp8Patch>,
62
63    /// str0m server timestamp.
64    ///
65    /// This timestamp has nothing to do with RTP itself. For outgoing packets, this is when
66    /// the packet was first handed over to str0m and enqueued in the outgoing send buffers.
67    /// For incoming packets it's the time we received the network packet.
68    pub timestamp: Instant,
69
70    /// Sender information from the most recent Sender Report(SR).
71    ///
72    /// If no Sender Report(SR) has been received or this packet is being sent by str0m this is [`None`].
73    pub last_sender_info: Option<SenderInfo>,
74
75    /// Whether this packet can be nacked.
76    ///
77    /// This is often false for audio, but might also be false for discardable frames when
78    /// using temporal encoding as in a VP8 simulcast situation.
79    pub(crate) nackable: bool,
80}
81
82/// Event when an encoded stream is considered paused/unpaused.
83///
84/// This means the stream has not received any data for some time (default 1.5 seconds).
85#[derive(Debug)]
86pub struct StreamPaused {
87    /// The main SSRC of the encoded stream that paused.
88    pub ssrc: Ssrc,
89
90    /// The mid the encoded stream belongs to.
91    pub mid: Mid,
92
93    /// The rid, if the encoded stream has a rid.
94    pub rid: Option<Rid>,
95
96    /// Whether the stream is paused or not.
97    pub paused: bool,
98}
99
100/// 255 is out of range for a real PT, which is 7 bit.
101const BLANK_PACKET_DEFAULT_PT: Pt = Pt::new_with_value(255);
102
103impl RtpPacket {
104    fn blank() -> RtpPacket {
105        RtpPacket {
106            seq_no: 0.into(),
107            time: MediaTime::from_90khz(0),
108            header: RtpHeader {
109                payload_type: BLANK_PACKET_DEFAULT_PT,
110                ..Default::default()
111            },
112            payload: Arc::default(), // This payload is never used. See RtpHeader::create_padding_packet
113            vp8_patch: None,
114            nackable: false,
115            last_sender_info: None,
116            timestamp: already_happened(),
117        }
118    }
119}
120
121/// Holder of incoming/outgoing encoded streams.
122///
123/// Each encoded stream is uniquely identified by an SSRC. The concept of mid/rid sits on the Media
124/// level together with the ability to translate a mid/rid to an encoded stream.
125#[derive(Debug)]
126pub(crate) struct Streams {
127    /// All incoming encoded streams.
128    streams_rx: HashMap<Ssrc, StreamRx>,
129
130    /// Each incoming SSRC is mapped to a Mid/Ssrc. The Ssrc in the value is for the case
131    /// where the incoming SSRC is for an RTX and we want the "main".
132    rx_lookup: HashMap<Ssrc, RxLookup>,
133
134    /// Time we last cleaned up unused entries from source_keys_rx.
135    last_rx_lookup_cleanup: Instant,
136
137    /// All outgoing encoded streams.
138    streams_tx: HashMap<Ssrc, StreamTx>,
139
140    /// Non-media padding source. Its sequence counter survives media changes.
141    probe_tx: StreamTx,
142    probe_media: Option<(Mid, Pt)>,
143
144    /// Local SSRC used before we got any StreamTx. This is used for RTCP if we don't
145    /// have any reasonable value to use.
146    default_ssrc_tx: Ssrc,
147
148    /// We need to report all RR/SR for a Mid together in one RTCP. This is a dynamic
149    /// list that we don't want to allocate on every handle_timeout.
150    mids_to_report: Vec<Mid>,
151
152    /// Whether periodic statistics reports are expected to be generated. This informs us on
153    /// whether we should be holding onto data needed for those reports or not.
154    enable_stats: bool,
155
156    /// Threshold above which an outgoing RTP packet triggers an MTU warning. Used as a
157    /// hard cap when selecting RTX cache entries for spurious padding.
158    mtu_warn: usize,
159    pause_threshold: Duration,
160}
161
162/// Delay between cleaning up the RxLookup.
163const RX_LOOKUP_CLEANUP_INTERVAL: Duration = Duration::from_millis(10_000);
164
165/// How old an RxLookup entry may be.
166const RX_LOOKUP_EXPIRY: Duration = Duration::from_millis(30_000);
167
168#[derive(Debug)]
169struct RxLookup {
170    mid: Mid,
171    main: Ssrc,
172    last_used: Instant,
173}
174
175impl Streams {
176    pub(crate) fn new(enable_stats: bool, mtu_warn: usize, pause_threshold: Duration) -> Self {
177        Self {
178            streams_rx: Default::default(),
179            rx_lookup: Default::default(),
180            last_rx_lookup_cleanup: already_happened(),
181            streams_tx: Default::default(),
182            probe_tx: StreamTx::new_probe(mtu_warn),
183            probe_media: None,
184            default_ssrc_tx: 0.into(), // this will be changed
185            mids_to_report: Vec::with_capacity(10),
186            enable_stats,
187            mtu_warn,
188            pause_threshold,
189        }
190    }
191
192    pub(crate) fn map_dynamic_by_rid(
193        &mut self,
194        ssrc: Ssrc,
195        midrid: MidRid,
196        media: &mut Media,
197        payload: PayloadParams,
198        is_main: bool,
199    ) {
200        // This is the point of the function.
201        let rid = midrid
202            .rid()
203            .expect("map_dynamic_by_rid to be called with Rid");
204
205        // Check if the mid/rid combo is not expected
206        if !media.rids_rx().contains(rid) {
207            trace!("Mid does not expect rid: {} {}", midrid.mid(), rid);
208            return;
209        }
210
211        let maybe_stream = self.stream_rx_by_midrid(midrid);
212
213        let (ssrc_main, rtx) = if is_main {
214            let maybe_rtx = maybe_stream.and_then(|s| s.rtx());
215            (ssrc, maybe_rtx)
216        } else {
217            // This can bail if the main SSRC has not been discovered yet.
218            let Some(stream) = maybe_stream else {
219                return;
220            };
221            (stream.ssrc(), Some(ssrc))
222        };
223
224        self.map_dynamic_finish(midrid, ssrc_main, rtx, media, payload);
225    }
226
227    pub(crate) fn map_dynamic_by_pt(
228        &mut self,
229        ssrc: Ssrc,
230        midrid: MidRid,
231        media: &mut Media,
232        payload: PayloadParams,
233        is_main: bool,
234    ) {
235        if media.rids_rx().is_specific() {
236            trace!(
237                "Media expects rid and RTP packet has only mid: {:?}",
238                media.rids_rx()
239            );
240            return;
241        }
242
243        let maybe_stream = self.stream_rx_by_midrid(midrid);
244
245        let (ssrc_main, rtx) = if is_main {
246            let maybe_rtx = maybe_stream.and_then(|s| s.rtx());
247            (ssrc, maybe_rtx)
248        } else {
249            // This can bail if the main SSRC has not been discovered yet.
250            let Some(stream) = maybe_stream else {
251                return;
252            };
253            // The main is the SSRC in the stream already. The incoming is RTX.
254            let ssrc_main = stream.ssrc();
255            (ssrc_main, Some(ssrc))
256        };
257
258        self.map_dynamic_finish(midrid, ssrc_main, rtx, media, payload);
259    }
260
261    #[allow(clippy::too_many_arguments)]
262    fn map_dynamic_finish(
263        &mut self,
264        midrid: MidRid,
265        ssrc_main: Ssrc,
266        rtx: Option<Ssrc>,
267        media: &mut Media,
268        payload: PayloadParams,
269    ) {
270        let maybe_stream = self.stream_rx_by_midrid(midrid);
271
272        if let Some(stream) = maybe_stream {
273            let ssrc_from = stream.ssrc();
274            let rtx_from = stream.rtx();
275
276            // Handle changes in SSRC.
277            if ssrc_from != ssrc_main {
278                // We got a change in main SSRC for this stream.
279                let did_change = self.change_stream_rx_ssrc(ssrc_from, ssrc_main);
280
281                // When the SSRC changes, any payload type on this RID can start with
282                // a new sequence number. Reset all depayloaders for the RID.
283                if did_change {
284                    media.reset_depayloaders_for_rid(midrid.rid());
285                }
286            }
287
288            // Handle changes in RTX
289            if let (Some(rtx_from), Some(rtx_to)) = (rtx_from, rtx) {
290                if rtx_from != rtx_to {
291                    self.change_stream_rx_rtx(rtx_from, rtx_to);
292                }
293            }
294        }
295
296        // NACK gated on negotiated `nack` feedback; RTX is just the transport (as in libwebrtc).
297        let suppress_nack = !payload.fb_nack;
298
299        // If stream already exists, this might only "fill in" the RTX.
300        self.expect_stream_rx(ssrc_main, rtx, midrid, suppress_nack);
301    }
302
303    pub fn expect_stream_rx(
304        &mut self,
305        ssrc: Ssrc,
306        rtx: Option<Ssrc>,
307        midrid: MidRid,
308        suppress_nack: bool,
309    ) -> &mut StreamRx {
310        let stream = self
311            .streams_rx
312            .entry(ssrc)
313            .or_insert_with(|| StreamRx::new(ssrc, midrid, suppress_nack, self.pause_threshold));
314
315        if let Some(rtx) = rtx {
316            stream.maybe_reset_rtx(rtx);
317        }
318
319        stream
320    }
321
322    pub fn remove_stream_rx(&mut self, ssrc: Ssrc) -> bool {
323        let stream = self.streams_rx.remove(&ssrc);
324        let existed = stream.is_some();
325
326        self.rx_lookup.retain(|k, l| *k != ssrc && l.main != ssrc);
327
328        existed
329    }
330
331    pub fn declare_stream_tx(
332        &mut self,
333        ssrc: Ssrc,
334        rtx: Option<Ssrc>,
335        midrid: MidRid,
336    ) -> &mut StreamTx {
337        self.streams_tx
338            .entry(ssrc)
339            .or_insert_with(|| StreamTx::new(ssrc, rtx, midrid, self.enable_stats, self.mtu_warn))
340    }
341
342    pub fn remove_stream_tx(&mut self, ssrc: Ssrc) -> bool {
343        self.streams_tx.remove(&ssrc).is_some()
344    }
345
346    /// Re-keys a send stream whose SSRC changed from `old` (`reset_stream_tx`): `streams_tx`
347    /// is keyed by SSRC, and incoming RTCP (receiver reports, NACK, PLI, FIR) finds its send
348    /// stream by the SSRC it names.
349    pub(crate) fn rekey_stream_tx(&mut self, old: Ssrc) {
350        if let Some(s) = self.streams_tx.remove(&old) {
351            self.streams_tx.insert(s.ssrc(), s);
352        }
353    }
354
355    pub(crate) fn local_sender_ssrcs(&self) -> Vec<Ssrc> {
356        self.streams_tx
357            .values()
358            .flat_map(|s| std::iter::once(s.ssrc()).chain(s.rtx()))
359            .collect()
360    }
361
362    pub(crate) fn reset_send_buffers(&mut self) {
363        for stream in self.streams_tx.values_mut() {
364            stream.reset_buffers();
365        }
366    }
367
368    pub fn stream_rx(&mut self, ssrc: &Ssrc) -> Option<&mut StreamRx> {
369        self.streams_rx.get_mut(ssrc)
370    }
371
372    pub fn stream_tx(&mut self, ssrc: &Ssrc) -> Option<&mut StreamTx> {
373        self.streams_tx.get_mut(ssrc)
374    }
375
376    /// Lookup the "main" SSRC and mid for a given SSRC(main or RTX).
377    pub(crate) fn mid_ssrc_rx_by_ssrc_or_rtx(
378        &mut self,
379        now: Instant,
380        ssrc: Ssrc,
381    ) -> Option<(Mid, Ssrc)> {
382        // A direct hit on SSRC is to prefer. The idea is that mid/rid are only sent
383        // for the initial x seconds and then we start using SSRC only instead.
384        if let Some(r) = self.rx_lookup.get_mut(&ssrc) {
385            r.last_used = now;
386            return Some((r.mid, r.main));
387        }
388
389        let maybe_stream = self.stream_rx_by_ssrc_or_rtx(ssrc);
390        if let Some(stream) = maybe_stream {
391            let mid = stream.mid();
392            let ssrc_main = stream.ssrc();
393
394            self.rx_lookup.insert(
395                ssrc,
396                RxLookup {
397                    mid,
398                    main: ssrc_main,
399                    last_used: now,
400                },
401            );
402
403            return Some((mid, ssrc_main));
404        }
405
406        None
407    }
408
409    pub(crate) fn regular_feedback_at(&self, i: RtcpReportIntervals) -> Option<Instant> {
410        let r = self
411            .streams_rx
412            .values()
413            .filter(|s| !s.ssrc().is_probe())
414            .map(|s| s.receiver_report_at(i));
415        let s = self.streams_tx.values().map(|s| s.sender_report_at(i));
416        r.chain(s).min()
417    }
418
419    pub(crate) fn paused_at(&self) -> Option<Instant> {
420        self.streams_rx.values().find_map(|s| s.paused_at())
421    }
422
423    pub(crate) fn send_stream(&self) -> Option<Instant> {
424        if self.streams_tx.values().any(|s| s.need_timeout()) {
425            Some(already_happened())
426        } else {
427            None
428        }
429    }
430
431    pub(crate) fn pending_request(&self) -> Option<Instant> {
432        if self.streams_rx.values().any(|s| s.has_pending_request()) {
433            Some(already_happened())
434        } else {
435            None
436        }
437    }
438
439    pub(crate) fn handle_timeout(
440        &mut self,
441        now: Instant,
442        sender_ssrc: Ssrc,
443        do_nack: bool,
444        medias: &[Media],
445        config: StreamTimeoutConfig<'_>,
446        feedback: &mut VecDeque<Rtcp>,
447    ) {
448        let StreamTimeoutConfig { codecs, intervals } = config;
449
450        self.mids_to_report.clear(); // Clear for checking StreamRx.
451        for stream in self.streams_rx.values() {
452            if stream.need_rr(now, intervals) {
453                self.mids_to_report.push(stream.mid());
454            }
455        }
456
457        for stream in self.streams_rx.values_mut() {
458            stream.maybe_create_keyframe_request(sender_ssrc, feedback);
459            stream.maybe_create_remb_request(sender_ssrc, feedback);
460
461            // All StreamRx belonging to the same Mid are reported together.
462            if self.mids_to_report.contains(&stream.mid()) {
463                stream.create_rr_and_update(now, sender_ssrc, feedback);
464            }
465
466            if do_nack {
467                stream.maybe_create_nack(now, sender_ssrc, feedback);
468            }
469
470            stream.handle_timeout(now);
471        }
472
473        self.mids_to_report.clear(); // start over for StreamTx.
474        for stream in self.streams_tx.values() {
475            if stream.need_sr(now, intervals) {
476                self.mids_to_report.push(stream.mid());
477            }
478        }
479
480        for stream in self.streams_tx.values_mut() {
481            let mid = stream.mid();
482
483            // All StreamTx belonging to the same Mid are reported together.
484            if self.mids_to_report.contains(&mid) {
485                stream.create_sr_and_update(now, feedback);
486            }
487
488            // Finding the first (main) PT that also has RTX for the Media is expensive,
489            // this closure is run only when needed.
490            // The unwrap is okay because we cannot have StreamTx with a Mid without the corresponding Media.
491            let get_media = move || (medias.iter().find(|m| m.mid() == mid).unwrap(), codecs);
492
493            stream.handle_timeout(now, get_media);
494        }
495
496        if now > self.rx_lookup_at() {
497            self.rx_lookup
498                .retain(|_, l| now - l.last_used <= RX_LOOKUP_EXPIRY);
499            self.last_rx_lookup_cleanup = now;
500        }
501    }
502
503    pub(crate) fn poll_keyframe_request(&mut self) -> Option<KeyframeRequest> {
504        self.streams_tx.values_mut().find_map(|s| {
505            let kind = s.poll_keyframe_request()?;
506            Some(KeyframeRequest {
507                mid: s.mid(),
508                rid: s.rid(),
509                kind,
510            })
511        })
512    }
513
514    pub(crate) fn poll_sender_feedback(&mut self) -> Option<SenderFeedback> {
515        self.streams_rx.values_mut().find_map(|s| {
516            let (sender_info, at) = s.poll_sender_info()?;
517
518            Some(SenderFeedback {
519                mid: s.mid(),
520                rid: s.rid(),
521                received_at: at,
522                sender_info,
523            })
524        })
525    }
526
527    pub(crate) fn poll_remb_request(&mut self) -> Option<(Mid, Bitrate)> {
528        self.streams_tx
529            .values_mut()
530            .find_map(|s| s.poll_remb_request().map(|b| (s.mid(), b)))
531    }
532
533    pub(crate) fn poll_stream_paused(&mut self) -> Option<StreamPaused> {
534        self.streams_rx.values_mut().find_map(|s| s.poll_paused())
535    }
536
537    pub(crate) fn has_stream_rx(&self, ssrc: Ssrc) -> bool {
538        self.streams_rx.contains_key(&ssrc)
539    }
540
541    pub(crate) fn has_stream_tx(&self, ssrc: Ssrc) -> bool {
542        self.streams_tx.contains_key(&ssrc)
543    }
544
545    pub(crate) fn handle_dlrr(&mut self, now: Instant, dlrr: DlrrItem) {
546        let is_default_ssrc = !self.default_ssrc_tx.is_probe() && dlrr.ssrc == self.default_ssrc_tx;
547        if !is_default_ssrc && !self.has_stream_tx(dlrr.ssrc) {
548            trace!("Ignoring DLRR for unknown local SSRC: {}", dlrr.ssrc);
549            return;
550        }
551
552        // DLRR identifies our RRTR sender, not a remote media SSRC. The measured
553        // round trip is shared by receive streams on this peer's transport.
554        for stream in self.streams_rx.values_mut() {
555            stream.handle_rtcp(now, RtcpFb::DlrrItem(dlrr));
556        }
557    }
558
559    pub(crate) fn streams_rx(&mut self) -> impl Iterator<Item = &mut StreamRx> {
560        self.streams_rx.values_mut()
561    }
562
563    pub(crate) fn streams_tx(&mut self) -> impl Iterator<Item = &mut StreamTx> {
564        self.streams_tx.values_mut()
565    }
566
567    pub(crate) fn ssrcs_tx(&self, mid: Mid) -> Vec<(Ssrc, Option<Ssrc>)> {
568        self.streams_tx
569            .values()
570            .filter(|s| s.mid() == mid)
571            .map(|s| (s.ssrc(), s.rtx()))
572            .collect()
573    }
574
575    pub(crate) fn new_ssrc(&self) -> Ssrc {
576        loop {
577            // This new guarantees we never get SSRC 0 (reserved for BWE probes)
578            let ssrc = Ssrc::new();
579
580            let has_ssrc = self.has_stream_rx(ssrc) || self.has_stream_tx(ssrc);
581
582            if has_ssrc {
583                continue;
584            }
585
586            // Need to check RTX as well.
587            let has_rtx_rx = self.streams_rx.values().any(|s| s.rtx() == Some(ssrc));
588            if has_rtx_rx {
589                continue;
590            }
591
592            let has_rtx_tx = self.streams_tx.values().any(|s| s.rtx() == Some(ssrc));
593            if has_rtx_tx {
594                continue;
595            }
596
597            // Not used
598            break ssrc;
599        }
600    }
601
602    pub fn new_ssrc_pair(&self) -> (Ssrc, Ssrc) {
603        let ssrc = self.new_ssrc();
604
605        let rtx = loop {
606            let proposed = self.new_ssrc();
607            // Avoid clashing with just allocated main SSRC.
608            if proposed != ssrc {
609                break proposed;
610            }
611        };
612
613        (ssrc, rtx)
614    }
615
616    pub(crate) fn first_ssrc_remote(&self) -> Ssrc {
617        *self.streams_rx.keys().next().unwrap_or(&0.into())
618    }
619
620    pub(crate) fn first_ssrc_local(&mut self) -> Ssrc {
621        if let Some(ssrc) = self.streams_tx.keys().next() {
622            // If there is some local Tx SSRC, use that.
623            *ssrc
624        } else {
625            // Fallback in case we don't have any Tx SSRC.
626            if *self.default_ssrc_tx == 0 {
627                // Do not use 0, allocate one that is not in session already.
628                self.default_ssrc_tx = self.new_ssrc();
629            }
630            self.default_ssrc_tx
631        }
632    }
633
634    /// Bind the probe source only while a cluster is authorized. Changing the
635    /// binding drops queued padding but preserves the SSRC's SRTP sequence.
636    pub(crate) fn set_probe_media(&mut self, media: Option<(Mid, Pt)>) {
637        if media == self.probe_media {
638            return;
639        }
640        self.probe_tx.reset_buffers();
641        if let Some((mid, pt)) = media {
642            self.probe_tx.set_probe_media(mid, pt);
643        }
644        self.probe_media = media;
645    }
646
647    pub(crate) fn send_queue_states(
648        &mut self,
649        now: Instant,
650        mut can_probe: impl FnMut(Mid, Pt) -> bool,
651    ) -> impl Iterator<Item = QueueState> {
652        // Snapshot each stream once, preferring media/RTX padding over the
653        // fallback. No extra stream or retransmission-queue scan is needed.
654        let mut media_padding = false;
655        let mut probe_queue = self.probe_media.map(|_| {
656            let mut queue = self.probe_tx.queue_state(now);
657            queue.midrid = MidRid(MID_PROBE, None);
658            queue
659        });
660        let mut streams = self.streams_tx.values_mut();
661        std::iter::from_fn(move || {
662            if let Some(stream) = streams.next() {
663                let mut queue = stream.queue_state(now);
664                if probe_queue.is_some() && queue.use_for_padding {
665                    // Only negotiated feedback sources can provide probe padding.
666                    // Ordinary padding keeps its existing eligibility.
667                    queue.use_for_padding = stream
668                        .padding_pt()
669                        .is_some_and(|pt| can_probe(stream.mid(), pt));
670                }
671                media_padding |= queue.use_for_padding;
672                return Some(queue);
673            }
674            let mut queue = probe_queue.take()?;
675            queue.use_for_padding = !media_padding;
676            Some(queue)
677        })
678    }
679
680    pub(crate) fn stream_tx_by_midrid(&mut self, midrid: MidRid) -> Option<&mut StreamTx> {
681        if midrid == MidRid(MID_PROBE, None) {
682            self.probe_media?;
683            return Some(&mut self.probe_tx);
684        }
685        self.streams_tx.values_mut().find(|s| s.is_midrid(midrid))
686    }
687
688    pub(crate) fn stream_rx_by_midrid(&mut self, midrid: MidRid) -> Option<&mut StreamRx> {
689        self.streams_rx.values_mut().find(|s| s.is_midrid(midrid))
690    }
691
692    pub(crate) fn remove_streams_by_mid(&mut self, mid: Mid) {
693        self.streams_tx.retain(|_, s| s.mid() != mid);
694        self.streams_rx.retain(|_, s| s.mid() != mid);
695        self.rx_lookup.retain(|_, v| v.mid != mid);
696    }
697
698    /// An iterator over all the tx streams for a given mid.
699    pub(crate) fn streams_tx_by_mid(&mut self, mid: Mid) -> impl Iterator<Item = &mut StreamTx> {
700        self.streams_tx.values_mut().filter(move |s| s.mid() == mid)
701    }
702
703    /// An iterator over all the rx streams for a given mid.
704    pub(crate) fn streams_rx_by_mid(&mut self, mid: Mid) -> impl Iterator<Item = &mut StreamRx> {
705        self.streams_rx.values_mut().filter(move |s| s.mid() == mid)
706    }
707
708    pub(crate) fn reset_buffers_tx(&mut self, mid: Mid) {
709        for s in self.streams_tx_by_mid(mid) {
710            s.reset_buffers();
711            // A stream that stopped sending must not be picked for padding either.
712            s.stop_padding();
713        }
714    }
715
716    pub(crate) fn reset_buffers_rx(
717        &mut self,
718        mid: Mid,
719        max_seq_lookup: impl Fn(Ssrc) -> Option<SeqNo>,
720    ) {
721        for s in self.streams_rx_by_mid(mid) {
722            s.reset_buffers(&max_seq_lookup);
723        }
724    }
725
726    pub(crate) fn change_stream_rx_ssrc(&mut self, ssrc_from: Ssrc, ssrc_to: Ssrc) -> bool {
727        // This unwrap is OK, because we can't call change_stream_rx_ssrc without first
728        // knowing there is such a StreamRx.
729        let maybe_change = self.streams_rx.get_mut(&ssrc_from).unwrap();
730
731        // The StreamRx is allowed to not change the SSRC in case it is switching back
732        // to the previous SSRC. This is to avoid flapping in case RTP packets arrive
733        // out of order.
734        let did_change = maybe_change.change_ssrc(ssrc_to);
735
736        if did_change {
737            // Unwrap is OK, see above.
738            let to_change = self.streams_rx.remove(&ssrc_from).unwrap();
739
740            // Reinsert under new SSRC key.
741            self.streams_rx.insert(ssrc_to, to_change);
742
743            // Remove previous mappings for the SSRC
744            self.rx_lookup
745                .retain(|k, l| *k != ssrc_from && l.main != ssrc_from);
746        }
747
748        did_change
749    }
750
751    fn change_stream_rx_rtx(&mut self, rtx_from: Ssrc, rtx_to: Ssrc) {
752        // Remove the SSRC mapping
753        self.rx_lookup.remove(&rtx_from);
754
755        let Some(to_change) = self
756            .streams_rx
757            .values_mut()
758            .find(|s| s.rtx() == Some(rtx_from))
759        else {
760            // If there's no main stream associated with the RTX our job is done.
761            return;
762        };
763
764        to_change.maybe_reset_rtx(rtx_to);
765    }
766
767    fn stream_rx_by_ssrc_or_rtx(&self, ssrc: Ssrc) -> Option<&StreamRx> {
768        self.streams_rx
769            .values()
770            .find(|s| s.ssrc() == ssrc || s.rtx() == Some(ssrc))
771    }
772
773    /// Whether any receive stream currently needs NACK reports (see [`StreamRx::nack_enabled`]).
774    ///
775    /// Not cached: the answer changes with pause state and pending NACK retries.
776    pub(crate) fn any_nack_enabled(&self) -> bool {
777        self.streams_rx.values().any(|s| s.nack_enabled())
778    }
779
780    fn rx_lookup_at(&self) -> Instant {
781        self.last_rx_lookup_cleanup + RX_LOOKUP_CLEANUP_INTERVAL
782    }
783}
784
785impl fmt::Debug for RtpPacket {
786    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
787        f.debug_struct("RtpPacket")
788            .field("seq_no", &self.seq_no)
789            .field("time", &self.time)
790            .field("header", &self.header)
791            .field("payload", &self.payload.len())
792            .field("nackable", &self.nackable)
793            .field("timestamp", &self.timestamp)
794            .finish()
795    }
796}