Skip to main content

str0m/streams/
receive.rs

1use std::collections::VecDeque;
2use std::sync::Arc;
3use std::time::{Duration, Instant};
4
5use crate::config_mod::RtcpReportIntervals;
6use crate::media::KeyframeRequestKind;
7use crate::packet::MAX_RED_RECOVERY_DEPTH;
8use crate::rtp_::MidRid;
9use crate::rtp_::SeqNoWindow;
10use crate::rtp_::{Bitrate, DlrrItem, ExtendedReport, extend_u32};
11use crate::rtp_::{Fir, FirEntry, Frequency, MediaTime, Remb};
12use crate::rtp_::{Mid, Pli, Pt, ReceiverReport};
13use crate::rtp_::{ReportBlock, ReportList, Rid, Rrtr, Rtcp};
14use crate::rtp_::{RtcpFb, RtpHeader, SenderInfo, SeqNo};
15use crate::rtp_::{SdesType, Ssrc};
16use crate::stats::{MediaIngressStats, RemoteEgressStats, StatsSnapshot};
17use crate::util::{InstantExt, SystemTimeExt};
18use crate::util::{already_happened, calculate_rtt};
19
20use super::RtpPacket;
21use super::StreamPaused;
22use super::register::ReceiverRegister;
23
24/// How many recent packets to remember for placing RED redundant blocks. Must cover the
25/// recovery depth plus some reordering slack.
26const RED_RECENT_PACKETS: usize = 32;
27
28/// Incoming encoded stream.
29///
30/// A stream is a primary SSRC + optional RTX SSRC.
31///
32/// This is RTP level API. For frame level API see [`Rtc::writer`][crate::Rtc::writer].
33#[derive(Debug)]
34pub struct StreamRx {
35    /// Unique idenfier of the remote stream.
36    ///
37    /// If the remote changes the SSRC, we will create a new stream, not change this id.
38    ssrc: Ssrc,
39
40    /// Identifier of a resend (RTX) stream. This can be set later, once we discover it.
41    rtx: Option<Ssrc>,
42
43    /// Previous main SSRC. This is to ensure we never go "backwards" in terms
44    /// of changing SSRC (for FF).
45    previous_ssrc: Option<Ssrc>,
46
47    /// The Media mid/rid this stream belongs to.
48    midrid: MidRid,
49
50    /// Incoming CNAME in Sdes reports.
51    cname: Option<String>,
52
53    /// Whether we explicitly want to supress NACK sending. This is normally done by not
54    /// setting an RTX, however this can be toggled off manually despite RTX being there.
55    ///
56    /// This is also set to true if the SDP negotiation disables RTX.
57    ///
58    /// Defaults to false.
59    suppress_nack: bool,
60
61    /// Timestamp when we got some indication of remote using this stream.
62    last_used: Instant,
63
64    /// Last seen pt and clock_rate in
65    last_clock_rate: Option<(Pt, Frequency)>,
66
67    /// Last received sender info.
68    sender_info: Option<LastSenderInfo>,
69
70    /// ROC to reset with on next incoming packet.
71    reset_roc: Option<u64>,
72
73    /// Register of received packets. For NACK handling.
74    ///
75    /// Set on first ever packet.
76    register: Option<ReceiverRegister>,
77
78    /// Sequence and replay tracking for RTX. NACKs and reception reports use the main register.
79    ///
80    /// Set on the first authenticated RTX packet or restored from remembered sequence history.
81    register_rtx: Option<SeqNoWindow>,
82
83    /// The most recent main-stream packets as `(seq_no, extended rtp time)`, used to place
84    /// RFC 2198 RED redundant blocks (which carry a timestamp, not a seq no) at the right
85    /// sequence number. Bounded by `RED_RECENT_PACKETS`.
86    red_recent: VecDeque<(SeqNo, u64)>,
87
88    /// Last observed media time in an RTP packet.
89    last_time: Option<MediaTime>,
90
91    /// If we have a pending keyframe request to send.
92    pending_request_keyframe: Option<KeyframeRequestKind>,
93
94    /// If we have a pending REMB request to send.
95    pending_request_remb: Option<Bitrate>,
96
97    /// Sequence number of the next FIR.
98    fir_seq_no: u8,
99
100    /// Last time we produced regular feedback RR.
101    last_receiver_report: Instant,
102
103    /// Statistics of incoming data.
104    stats: StreamRxStats,
105
106    /// When we need to evaluate the paused state.
107    ///
108    /// now + pause_threshold
109    check_paused_at: Option<Instant>,
110
111    /// Whether we consider this StreamRx paused.
112    ///
113    /// A stream is considered paused if it has received no packets for some (configurable) duration.
114    /// This defaults to 1.5s.
115    paused: bool,
116
117    /// Whether we need to emit a paused event for the current paused state.
118    need_paused_event: bool,
119
120    /// The configured threshold before considering the lack of packets as going into paused.
121    pause_threshold: Duration,
122}
123
124/// The last sender info we recieved.
125#[derive(Debug)]
126pub(crate) struct LastSenderInfo {
127    /// When this SenderInfo was received.
128    received_at: Instant,
129    /// The sender info itself.
130    info: SenderInfo,
131    /// Whether we have emitted it yet via `poll_sender_info`
132    emitted: bool,
133}
134
135/// Holder of stats.
136#[derive(Debug, Default)]
137pub(crate) struct StreamRxStats {
138    /// count of bytes received, including retransmissions
139    bytes: u64,
140    /// count of packets received, including retransmissions
141    packets: u64,
142    /// count of FIR requests sent
143    firs: u64,
144    /// count of PLI requests sent
145    plis: u64,
146    /// count of NACKs sent
147    nacks: u64,
148    /// interarrival jitter (RTP timestamp units) from the last RR we sent
149    jitter: u32,
150    /// round trip time from the last DLRR, if any
151    rtt: Option<Duration>,
152    /// fraction of packets lost from the last RR, if any
153    loss: Option<f32>,
154}
155
156impl StreamRx {
157    pub(crate) fn new(
158        ssrc: Ssrc,
159        midrid: MidRid,
160        suppress_nack: bool,
161        pause_threshold: Duration,
162    ) -> Self {
163        debug!("Create StreamRx for SSRC: {}", ssrc);
164
165        StreamRx {
166            ssrc,
167            rtx: None,
168            previous_ssrc: None,
169            midrid,
170            cname: None,
171            suppress_nack,
172            last_used: already_happened(),
173            last_clock_rate: None,
174            sender_info: None,
175            reset_roc: None,
176            register: None,
177            register_rtx: None,
178            red_recent: VecDeque::new(),
179            last_time: None,
180            pending_request_keyframe: None,
181            pending_request_remb: None,
182            fir_seq_no: 0,
183            last_receiver_report: already_happened(),
184            stats: StreamRxStats::default(),
185            check_paused_at: None,
186            paused: true,
187            need_paused_event: false,
188            pause_threshold,
189        }
190    }
191
192    /// The (primary) SSRC of this encoded stream.
193    pub fn ssrc(&self) -> Ssrc {
194        self.ssrc
195    }
196
197    /// The resend (RTX) SSRC of this encoded stream.
198    pub fn rtx(&self) -> Option<Ssrc> {
199        self.rtx
200    }
201
202    /// Mid for this stream.
203    ///
204    /// In SDP this corresponds to m-line and "Media".
205    pub fn mid(&self) -> Mid {
206        self.midrid.mid()
207    }
208
209    /// Rid for this stream.
210    ///
211    /// This is used to separate streams with the same [`Mid`] when using simulcast.
212    pub fn rid(&self) -> Option<Rid> {
213        self.midrid.rid()
214    }
215
216    /// CNAME as sent by remote peer in a Sdes.
217    ///
218    /// The value is None until we receive a first report with the value set.
219    pub fn cname(&self) -> Option<&str> {
220        self.cname.as_deref()
221    }
222
223    /// Set threshold duration for emitting the paused event.
224    ///
225    /// This event is emitted when no packet have received for this duration.
226    pub fn set_pause_threshold(&mut self, t: Duration) {
227        self.pause_threshold = t;
228    }
229
230    /// The last time we received a packet.
231    ///
232    /// Resets if the SSRC changes.
233    pub fn last_time(&self) -> Option<MediaTime> {
234        self.last_time
235    }
236
237    /// Request a keyframe for an incoming encoded stream.
238    ///
239    /// * SSRC the identifier of the remote encoded stream to request a keyframe for.
240    /// * kind PLI or FIR.
241    pub fn request_keyframe(&mut self, kind: KeyframeRequestKind) {
242        self.pending_request_keyframe = Some(kind);
243    }
244
245    /// Request max recv bitrate for an incoming encoded stream.
246    ///
247    /// * bitrate Bitrate.
248    pub fn request_remb(&mut self, bitrate: Bitrate) {
249        self.pending_request_remb = Some(bitrate);
250    }
251
252    /// Suppress NACK sending.
253    ///
254    /// Normally NACK is disabled by not having an RTX SSRC set. In some situations it might be
255    /// desirable to manually suppress NACK sending regardless of RTX setting.
256    pub fn suppress_nack(&mut self, suppress: bool) {
257        self.suppress_nack = suppress;
258    }
259
260    fn is_audio(&self) -> bool {
261        self.rtx.is_none() // this is maybe not correct, but it's all we got.
262    }
263
264    pub(crate) fn receiver_report_at(&self, intervals: RtcpReportIntervals) -> Instant {
265        self.last_receiver_report + intervals.for_audio(self.is_audio())
266    }
267
268    pub(crate) fn handle_rtcp(&mut self, now: Instant, fb: RtcpFb) {
269        use RtcpFb::*;
270        match fb {
271            SenderInfo(v) => {
272                self.set_sender_info(now, v);
273            }
274            SourceDescription(v) => {
275                for (sdes, st) in v.values {
276                    if sdes == SdesType::CNAME {
277                        if st.is_empty() {
278                            // In simulcast, chrome doesn't send the SSRC lines, but
279                            // expects us to infer that from rtp headers. It does
280                            // however send the SourceDescription RTCP with an empty
281                            // string CNAME. ¯\_(ツ)_/¯
282                            return;
283                        }
284
285                        // Here we _could_ check CNAME here matches something. But
286                        // CNAMEs are a bit unfashionable.
287                        self.cname = Some(st);
288                        return;
289                    }
290                }
291            }
292            DlrrItem(v) => {
293                self.set_dlrr_item(now, v);
294            }
295            Goodbye(_v) => {
296                // We get Goodbye at weird times, like SDP renegotiation, which makes
297                // pausing on the BYE not a good idea. Chrome also reuses the SSRC it
298                // just sent BYE on. Very not helpful.
299            }
300            _ => {}
301        }
302    }
303
304    fn set_sender_info(&mut self, now: Instant, mut info: SenderInfo) {
305        // Extend the incoming time given our knowledge of last time.
306        let extended = {
307            let prev = self
308                .sender_info
309                .as_ref()
310                .map(|last| last.info.rtp_time.numer());
311            let r_u32 = info.rtp_time.numer() as u32;
312            extend_u32(prev, r_u32)
313        };
314
315        // The MediaTime has a base 1 after being parsed. At this point
316        // we know whether it's audio or video and set the base accordingly.
317        let clock_rate = self
318            .last_clock_rate
319            .map(|(_, r)| r)
320            .unwrap_or(Frequency::SECONDS);
321
322        // Clock rate is that of the last received packet.
323        info.rtp_time = MediaTime::new(extended, clock_rate);
324
325        self.sender_info = Some(LastSenderInfo {
326            received_at: now,
327            info,
328            emitted: false,
329        });
330    }
331
332    fn set_dlrr_item(&mut self, now: Instant, dlrr: DlrrItem) {
333        let ntp_time = now.to_ntp_duration();
334        let rtt = calculate_rtt(ntp_time, dlrr.last_rr_delay, dlrr.last_rr_time);
335        self.stats.rtt = rtt;
336    }
337
338    pub(crate) fn paused_at(&self) -> Option<Instant> {
339        self.check_paused_at
340    }
341
342    pub(crate) fn has_pending_request(&self) -> bool {
343        self.pending_request_keyframe.is_some() || self.pending_request_remb.is_some()
344    }
345
346    pub(crate) fn handle_timeout(&mut self, now: Instant) {
347        // No scheduled paused check?
348        if self.check_paused_at.is_none() {
349            return;
350        }
351
352        // Not reached scheduled paused check?
353        if Some(now) < self.check_paused_at {
354            return;
355        }
356
357        // Every update() schedules a paused check in the future. If we have reached that
358        // future we have implicitly also paused.
359        self.check_paused_at = None;
360
361        self.paused = true;
362        self.need_paused_event = true;
363    }
364
365    pub(crate) fn extend_seq(
366        &mut self,
367        header: &RtpHeader,
368        is_repair: bool,
369        max_seq_lookup: impl Fn(Ssrc) -> Option<SeqNo>,
370    ) -> SeqNo {
371        // RTX has its own sequence series and only needs a replay window.
372        if is_repair {
373            if self.register_rtx.is_none() {
374                self.register_rtx = max_seq_lookup(header.ssrc).map(SeqNoWindow::new_after);
375            }
376            return header.sequence_number(self.register_rtx.as_ref().map(|r| r.max_seq()));
377        }
378
379        let register = self
380            .register
381            .get_or_insert_with(|| ReceiverRegister::new(max_seq_lookup(header.ssrc)));
382
383        // If the user has called `reset_seq_no`, this is the time to handle it, but only
384        // if the incoming packet is for main (not repair).
385        let mut reset_seq_no = None;
386        if let Some(reset_roc) = self.reset_roc.take() {
387            let s: SeqNo = (reset_roc << 16 | header.sequence_number as u64).into();
388            reset_seq_no = Some(s);
389        }
390
391        if let Some(reset_seq_no) = reset_seq_no {
392            reset_seq_no
393        } else {
394            header.sequence_number(register.max_seq())
395        }
396    }
397
398    pub(crate) fn is_new_packet(&self, is_repair: bool, seq_no: SeqNo) -> bool {
399        if is_repair {
400            self.register_rtx.as_ref().is_none_or(|r| r.accepts(seq_no))
401        } else {
402            // extend_seq() initializes the main register before this check.
403            self.register.as_ref().unwrap().accepts(seq_no)
404        }
405    }
406
407    fn remember_recent(&mut self, seq_no: SeqNo, time: u64) {
408        self.red_recent.push_back((seq_no, time));
409        while self.red_recent.len() > RED_RECENT_PACKETS {
410            self.red_recent.pop_front();
411        }
412    }
413
414    /// Work out which (still missing) sequence number a RED redundant block belongs to.
415    ///
416    /// RFC 2198 blocks carry a timestamp offset, not a sequence number, and the frame duration
417    /// is neither signalled nor constant (Opus 10/20/40/60 ms, DTX, CN interleaved on the same
418    /// SSRC). Rather than guess a duration from the offsets, bracket the block's time between the
419    /// nearest received packets `L` (latest with time before) and `U` (earliest with time after)
420    /// and look at the missing sequence numbers between them:
421    ///
422    /// * exactly one missing: that is the block, whatever the durations were — this case is
423    ///   exact;
424    /// * several missing: only if `L..U` is uniformly spaced and the block time lands exactly on
425    ///   one of the missing slots; otherwise give up. This case *assumes* a constant frame
426    ///   duration across the gap, which holds for the fixed-ptime senders seen in practice
427    ///   (WebRTC uses 20 ms). Under variable Opus ptime the derived slot can be a neighbouring
428    ///   lost sequence number rather than the block's true one, so recovered audio may land one
429    ///   or two frames off.
430    ///
431    /// The bound this always keeps is that a candidate must be a currently *missing* sequence
432    /// number (`register.accepts`): recovery only ever fills a hole, and never overwrites a
433    /// correctly received frame — the worst case above only reorders audio among frames that
434    /// were all lost anyway. `carrier` is the packet the block arrived in; recovery is limited
435    /// to `MAX_RED_RECOVERY_DEPTH` packets behind it.
436    pub(crate) fn red_locate_seq(&self, carrier: SeqNo, block_time: u64) -> Option<SeqNo> {
437        let register = self.register.as_ref()?;
438
439        // A packet (received or already recovered) at exactly this time: nothing to recover.
440        if self.red_recent.iter().any(|(_, t)| *t == block_time) {
441            return None;
442        }
443
444        let below = self
445            .red_recent
446            .iter()
447            .filter(|(_, t)| *t < block_time)
448            .max_by_key(|(s, _)| *s)?;
449        let above = self
450            .red_recent
451            .iter()
452            .filter(|(_, t)| *t > block_time)
453            .min_by_key(|(s, _)| *s)?;
454
455        let (l_seq, l_time) = (*below.0, below.1);
456        let (u_seq, u_time) = (*above.0, above.1);
457
458        // Bound the scan: the block must be within recovery depth of the carrier, which also
459        // keeps `l_seq..u_seq` small. `checked_sub` guards a stream whose timestamps don't
460        // follow its sequence numbers.
461        let depth_ok = (*carrier)
462            .checked_sub(l_seq)
463            .is_some_and(|d| d <= MAX_RED_RECOVERY_DEPTH + 1);
464        if u_seq <= l_seq + 1 || !depth_ok {
465            return None;
466        }
467
468        let mut missing = (l_seq + 1..u_seq)
469            .map(SeqNo::from)
470            .filter(|s| register.accepts(*s));
471
472        let first = missing.next()?;
473        let candidate = if missing.next().is_none() {
474            // Exactly one hole between two received packets that bracket the block in time.
475            first
476        } else {
477            // Several holes: only a uniformly spaced span lets us tell which one.
478            let span_seq = u_seq - l_seq;
479            let span_time = u_time - l_time;
480            if span_time % span_seq != 0 {
481                return None;
482            }
483            let d = span_time / span_seq;
484            let back = block_time - l_time;
485            if !back.is_multiple_of(d) {
486                return None;
487            }
488            let seq: SeqNo = (l_seq + back / d).into();
489            if !register.accepts(seq) {
490                return None;
491            }
492            seq
493        };
494
495        (*carrier)
496            .checked_sub(*candidate)
497            .is_some_and(|d| d <= MAX_RED_RECOVERY_DEPTH)
498            .then_some(candidate)
499    }
500
501    /// Record that `seq_no` was rebuilt from RED redundancy. It was never on the wire, so it is
502    /// not counted as received (reception reports still show the loss), but it must neither be
503    /// NACKed nor recovered again.
504    pub(crate) fn mark_red_recovered(&mut self, seq_no: SeqNo, time: u64) {
505        if let Some(register) = &mut self.register {
506            register.mark_recovered(seq_no);
507        }
508        self.remember_recent(seq_no, time);
509    }
510
511    pub(crate) fn update_register(
512        &mut self,
513        now: Instant,
514        header: &RtpHeader,
515        clock_rate: Frequency,
516        is_repair: bool,
517        seq_no: SeqNo,
518    ) -> RegisterUpdateReceipt {
519        self.last_used = now;
520
521        let was_paused = self.paused;
522        if was_paused {
523            self.paused = false;
524            self.need_paused_event = true;
525        }
526        self.check_paused_at = Some(now + self.pause_threshold);
527
528        let is_new_packet = if is_repair {
529            let is_new = self.is_new_packet(true, seq_no);
530            self.register_rtx
531                .get_or_insert_with(|| SeqNoWindow::new(seq_no))
532                .update(seq_no);
533            is_new
534        } else {
535            // extend_seq() initializes the main register before this update.
536            self.register
537                .as_mut()
538                .unwrap()
539                .update(seq_no, now, header.timestamp, clock_rate.get())
540        };
541
542        // Get the previous time for comparison
543        let previous_time = self.last_time.map(|t| t.numer());
544
545        // Calculate the extended timestamp
546        let mut time_u32 = extend_u32(previous_time, header.timestamp);
547
548        if was_paused && Some(time_u32) < previous_time {
549            // In 32-bit RTP timestamps, adding 2^31 (MAX/2) flips to the other half of timestamp space
550            // This forces extend_u32 to produce a value in the next cycle
551            const HALF_CYCLE: u32 = 1u32 << 31;
552            let adjusted_ts = header.timestamp.wrapping_add(HALF_CYCLE);
553
554            // Recalculate extended timestamp with adjusted value
555            let adjusted_time_u32 = extend_u32(previous_time, adjusted_ts);
556
557            // If this adjusted timestamp moves time forward, use it
558            if adjusted_time_u32 > previous_time.unwrap() {
559                time_u32 = adjusted_time_u32;
560            } else {
561                // Fallback
562                time_u32 = header.timestamp as u64;
563            }
564        }
565
566        let time = MediaTime::new(time_u32, clock_rate);
567
568        if !is_repair {
569            self.last_time = Some(time);
570            if is_new_packet {
571                self.remember_recent(seq_no, time.numer());
572            }
573        }
574
575        RegisterUpdateReceipt {
576            time,
577            is_new_packet,
578        }
579    }
580
581    #[allow(clippy::too_many_arguments)]
582    pub(crate) fn handle_rtp(
583        &mut self,
584        now: Instant,
585        header: RtpHeader,
586        payload: Arc<[u8]>,
587        seq_no: SeqNo,
588        time: MediaTime,
589        wire_payload_len: usize,
590    ) -> RtpPacket {
591        let packet = self.make_rtp_packet(now, header, payload, seq_no, time);
592
593        // `payload` may be narrower than what was on the wire (RED unwrapped to its primary
594        // block); count what was received, matching the sender's egress accounting.
595        self.stats.bytes += wire_payload_len as u64;
596        self.stats.packets += 1;
597
598        packet
599    }
600
601    /// Build an [`RtpPacket`] WITHOUT counting it in receive stats. Used for RFC 2198
602    /// FEC-recovered packets, which were never received on the wire (the carrying packet's
603    /// bytes are already counted by `handle_rtp`).
604    pub(crate) fn make_rtp_packet(
605        &mut self,
606        now: Instant,
607        header: RtpHeader,
608        payload: Arc<[u8]>,
609        seq_no: SeqNo,
610        time: MediaTime,
611    ) -> RtpPacket {
612        trace!("Handle RTP: {:?}", header);
613
614        let need_clock_rate = self.last_clock_rate.map(|(pt, _)| pt) != Some(header.payload_type);
615        if need_clock_rate {
616            self.last_clock_rate = Some((header.payload_type, time.frequency()));
617
618            // If we get an SR before the first packet, we update the potential clock rate.
619            if let Some(i) = &mut self.sender_info {
620                i.info.rtp_time = MediaTime::new(i.info.rtp_time.numer(), time.frequency());
621            }
622        }
623
624        RtpPacket {
625            seq_no,
626            time,
627            header,
628            payload,
629            vp8_patch: None,
630            nackable: false,
631            last_sender_info: self.sender_info.as_ref().map(|l| l.info),
632            timestamp: now,
633        }
634    }
635
636    /// Rewrites the header to be the un-RTX'd original packet, and returns
637    /// `data` with the original sequence number prefix stripped.
638    pub(crate) fn un_rtx<'a>(&self, header: &mut RtpHeader, data: &'a [u8], pt: Pt) -> &'a [u8] {
639        let mut orig_seq_no_16 = 0;
640
641        let n = RtpHeader::read_original_sequence_number(data, &mut orig_seq_no_16);
642
643        trace!(
644            "Repaired seq no {} -> {}",
645            header.sequence_number, orig_seq_no_16
646        );
647
648        header.sequence_number = orig_seq_no_16;
649
650        header.ssrc = self.ssrc;
651        header.payload_type = pt;
652        header.ext_vals.rid = header.ext_vals.rid_repair.take();
653
654        &data[n..]
655    }
656
657    pub(crate) fn maybe_create_keyframe_request(
658        &mut self,
659        sender_ssrc: Ssrc,
660        feedback: &mut VecDeque<Rtcp>,
661    ) {
662        let Some(kind) = self.pending_request_keyframe.take() else {
663            return;
664        };
665
666        let ssrc = self.ssrc;
667
668        match kind {
669            KeyframeRequestKind::Pli => {
670                self.stats.plis += 1;
671                feedback.push_back(Rtcp::Pli(Pli { sender_ssrc, ssrc }))
672            }
673            KeyframeRequestKind::Fir => {
674                self.stats.firs += 1;
675                feedback.push_back(Rtcp::Fir(Fir {
676                    sender_ssrc,
677                    reports: FirEntry {
678                        ssrc,
679                        seq_no: self.next_fir_seq_no(),
680                    }
681                    .into(),
682                }))
683            }
684        }
685    }
686
687    pub(crate) fn maybe_create_remb_request(
688        &mut self,
689        sender_ssrc: Ssrc,
690        feedback: &mut VecDeque<Rtcp>,
691    ) {
692        let Some(bitrate) = self.pending_request_remb.take() else {
693            return;
694        };
695
696        feedback.push_back(Rtcp::Remb(Remb {
697            sender_ssrc,
698            ssrc: 0.into(),
699            bitrate: bitrate.as_f64() as f32,
700            ssrcs: vec![*self.ssrc],
701        }))
702    }
703
704    fn next_fir_seq_no(&mut self) -> u8 {
705        let x = self.fir_seq_no;
706        self.fir_seq_no = self.fir_seq_no.wrapping_add(1);
707        x
708    }
709
710    pub(crate) fn need_rr(&self, now: Instant, intervals: RtcpReportIntervals) -> bool {
711        if self.ssrc.is_probe() {
712            return false;
713        }
714
715        now >= self.receiver_report_at(intervals)
716    }
717
718    pub(crate) fn create_rr_and_update(
719        &mut self,
720        now: Instant,
721        sender_ssrc: Ssrc,
722        feedback: &mut VecDeque<Rtcp>,
723    ) {
724        let mut rr = self.create_receiver_report(now);
725        rr.sender_ssrc = sender_ssrc;
726
727        if !rr.reports.is_empty() {
728            let report = &rr.reports[rr.reports.len() - 1];
729            self.stats.update_loss(report.fraction_lost);
730            self.stats.jitter = report.jitter;
731        }
732
733        let xr = self.create_extended_receiver_report(now, sender_ssrc);
734
735        trace!(
736            "Created feedback RR/XR ({:?}): {:?} {:?}",
737            self.midrid, rr, xr
738        );
739        feedback.push_back(Rtcp::ReceiverReport(rr));
740        feedback.push_back(Rtcp::ExtendedReport(xr));
741
742        self.last_receiver_report = now;
743    }
744
745    fn create_receiver_report(&mut self, now: Instant) -> ReceiverReport {
746        let Some(mut report) = self.register.as_mut().and_then(|r| r.reception_report()) else {
747            return ReceiverReport {
748                sender_ssrc: 0.into(), // set one level up
749                reports: ReportList::new(),
750            };
751        };
752        report.ssrc = self.ssrc;
753
754        // The middle 32 bits out of 64 in the NTP timestamp (as explained in
755        // Section 4) received as part of the most recent RTCP sender report
756        // (SR) packet from source SSRC_n.  If no SR has been received yet,
757        // the field is set to zero.
758        report.last_sr_time = {
759            let t64 = self
760                .sender_info
761                .as_ref()
762                .map_or(0u64, |l| l.info.ntp_time.as_ntp_64());
763
764            (t64 >> 16) as u32
765        };
766
767        // The delay, expressed in units of 1/65_536 seconds, between
768        // receiving the last SR packet from source SSRC_n and sending this
769        // reception report block.  If no SR packet has been received yet
770        // from SSRC_n, the DLSR field is set to zero.
771        report.last_sr_delay = if let Some(l) = self.sender_info.as_ref() {
772            let t = l.received_at;
773            let delay = now - t;
774            ((delay.as_micros() * 65_536) / 1_000_000) as u32
775        } else {
776            0
777        };
778
779        ReceiverReport {
780            sender_ssrc: 0.into(), // set one level up
781            reports: report.into(),
782        }
783    }
784
785    fn create_extended_receiver_report(&self, now: Instant, sender_ssrc: Ssrc) -> ExtendedReport {
786        // we only want to report our time to measure RTT,
787        // the source will answer with Dlrr feedback, allowing us to calculate RTT
788        let block = ReportBlock::Rrtr(Rrtr {
789            ntp_time: now.to_system_time(),
790        });
791        ExtendedReport {
792            ssrc: sender_ssrc,
793            blocks: vec![block],
794        }
795    }
796
797    pub(crate) fn recovery_deadline(
798        &self,
799        range: std::ops::Range<SeqNo>,
800        received: Instant,
801    ) -> Option<Instant> {
802        if !self.suppress_nack {
803            if let Some(register) = &self.register {
804                return register.recovery_deadline(range, received, self.stats.rtt);
805            }
806        }
807        let rtt = self.stats.rtt.unwrap_or(super::register_nack::DEFAULT_RTT);
808        received.checked_add(rtt.saturating_mul(3))
809    }
810
811    /// Whether this stream should keep its NACK timer active.
812    ///
813    /// Paused streams finish pending retries before disabling NACK reports.
814    pub(crate) fn nack_enabled(&self) -> bool {
815        // Deliberately don't look at RTX is_some() here, since when using dynamic SSRC, we might need
816        // to send NACK before discovering the remote RTX.
817        if self.suppress_nack {
818            return false;
819        }
820
821        if !self.paused {
822            return true;
823        }
824
825        let Some(register) = &self.register else {
826            return false;
827        };
828
829        register.has_pending_nacks()
830    }
831
832    pub(crate) fn maybe_create_nack(
833        &mut self,
834        now: Instant,
835        sender_ssrc: Ssrc,
836        feedback: &mut VecDeque<Rtcp>,
837    ) -> Option<()> {
838        if !self.nack_enabled() {
839            return None;
840        }
841
842        let nacks = self
843            .register
844            .as_mut()
845            .and_then(|r| r.nack_report(now, self.stats.rtt))?;
846
847        for mut nack in nacks {
848            nack.sender_ssrc = sender_ssrc;
849            nack.ssrc = self.ssrc;
850
851            trace!("Created feedback NACK: {:?}", nack);
852            feedback.push_back(Rtcp::Nack(nack));
853            self.stats.nacks += 1;
854        }
855
856        Some(())
857    }
858
859    pub(crate) fn visit_stats(&self, snapshot: &mut StatsSnapshot, now: Instant) {
860        if self.ssrc.is_probe() {
861            return;
862        }
863
864        self.stats
865            .fill(snapshot, self.midrid, self.sender_info.as_ref(), now);
866    }
867
868    pub(crate) fn poll_paused(&mut self) -> Option<StreamPaused> {
869        if self.ssrc.is_probe() {
870            return None;
871        }
872
873        if !self.need_paused_event {
874            return None;
875        }
876
877        self.need_paused_event = false;
878
879        debug!(
880            "{} StreamRx with {:?} and SSRC: {}",
881            if self.paused { "Paused" } else { "Unpaused" },
882            self.midrid,
883            self.ssrc
884        );
885
886        Some(StreamPaused {
887            ssrc: self.ssrc,
888            mid: self.midrid.mid(),
889            rid: self.midrid.rid(),
890            paused: self.paused,
891        })
892    }
893
894    /// Poll the most recent sender info and when it was received
895    pub(crate) fn poll_sender_info(&mut self) -> Option<(SenderInfo, Instant)> {
896        let i = self.sender_info.as_mut()?;
897        if i.emitted {
898            return None;
899        }
900
901        i.emitted = true;
902
903        Some((i.info, i.received_at))
904    }
905
906    pub(crate) fn reset_buffers(&mut self, max_seq_lookup: impl Fn(Ssrc) -> Option<SeqNo>) {
907        if let Some(r) = &mut self.register {
908            r.clear(max_seq_lookup(self.ssrc));
909        }
910
911        if self.register_rtx.is_some() {
912            self.register_rtx = self
913                .rtx
914                .and_then(max_seq_lookup)
915                .map(SeqNoWindow::new_after);
916        }
917        self.pending_request_keyframe = None;
918    }
919
920    #[must_use]
921    pub(crate) fn change_ssrc(&mut self, ssrc: Ssrc) -> bool {
922        // Avoid flapping
923        if ssrc == self.ssrc || Some(ssrc) == self.previous_ssrc {
924            return false;
925        }
926
927        debug!(
928            "Change main SSRC: {} -> {} {:?}",
929            self.ssrc, ssrc, self.midrid
930        );
931
932        // Remember which was the previous in case a stray packet turns up
933        // so do we don't go "backwards".
934        self.previous_ssrc = Some(self.ssrc);
935        self.ssrc = ssrc;
936
937        // Reset all SSRC-specific state
938        self.register = None;
939        self.red_recent.clear();
940        self.last_time = None;
941        self.last_clock_rate = None;
942        self.sender_info = None;
943        self.last_receiver_report = already_happened();
944        self.fir_seq_no = 0;
945        self.pending_request_keyframe = None;
946        self.pending_request_remb = None;
947        self.reset_roc = None;
948
949        // Note: We don't reset the RTX register here, as the RTX SSRC is managed separately
950        // via maybe_reset_rtx() and is not directly tied to the main SSRC change.
951
952        true
953    }
954
955    pub(crate) fn maybe_reset_rtx(&mut self, rtx: Ssrc) {
956        if let Some(current) = self.rtx {
957            if current == rtx {
958                return;
959            }
960
961            debug!(
962                "Change RTX SSRC {} -> {} for main SSRC: {} {:?}",
963                current, rtx, self.ssrc, self.midrid
964            );
965        } else {
966            debug!("SSRC {} associated with RTX: {}", self.ssrc, rtx);
967        }
968
969        self.rtx = Some(rtx);
970        self.register_rtx = None;
971    }
972
973    /// Reset the current rollover counter (ROC).
974    ///
975    /// This is used in scenarios where we use a single sequence number across all
976    /// receivers of the same stream (as opposed to a sequence number unique per peer).
977    ///
978    /// The ROC is not carried in the RTP header. Obtain it through out-of-band
979    /// signaling and call this before handling the first SRTP packet for the stream.
980    /// See [`RtpWrite::new`][crate::rtp::RtpWrite::new] for sender and receiver examples.
981    ///
982    /// [RFC3711](https://datatracker.ietf.org/doc/html/rfc3711#section-3.3.1):
983    ///
984    /// > Receivers joining an on-going session MUST be given the
985    /// > current ROC value using out-of-band signaling such as key-management
986    /// > signaling.  Furthermore, the receiver SHALL initialize s_l to the RTP
987    /// > sequence number (SEQ) of the first observed SRTP packet (unless the
988    /// > initial value is provided by out of band signaling such as key
989    /// > management).
990    pub fn reset_roc(&mut self, roc: u64) {
991        self.register = None;
992        self.register_rtx = None;
993        self.red_recent.clear();
994        self.reset_roc = Some(roc);
995    }
996
997    pub(crate) fn is_midrid(&self, midrid: MidRid) -> bool {
998        midrid.special_equals(&self.midrid)
999    }
1000}
1001
1002impl StreamRxStats {
1003    fn update_loss(&mut self, fraction_lost: u8) {
1004        self.loss = Some(fraction_lost as f32 / u8::MAX as f32)
1005    }
1006
1007    pub(crate) fn fill(
1008        &self,
1009        snapshot: &mut StatsSnapshot,
1010        midrid: MidRid,
1011        sender_info: Option<&LastSenderInfo>,
1012        now: Instant,
1013    ) {
1014        if self.bytes == 0 {
1015            return;
1016        }
1017
1018        let stats = MediaIngressStats {
1019            mid: midrid.mid(),
1020            rid: midrid.rid(),
1021            bytes: self.bytes,
1022            packets: self.packets,
1023            firs: self.firs,
1024            plis: self.plis,
1025            nacks: self.nacks,
1026            jitter: self.jitter,
1027            rtt: self.rtt,
1028            loss: self.loss,
1029            timestamp: now,
1030            remote: sender_info.map(|l| RemoteEgressStats {
1031                bytes: l.info.sender_octet_count as u64,
1032                packets: l.info.sender_packet_count as u64,
1033            }),
1034        };
1035
1036        // Several SSRCs can back a given (mid, rid) tuple. For example, Firefox creates new SSRCs
1037        // when a Transceiver transitions from send -> inactive -> send. In order to continue
1038        // correctly reporting stats for this (mid, rid) pair we need to merge the stats across all
1039        // the SSRCs that have been used.
1040        snapshot
1041            .ingress
1042            .entry(midrid)
1043            .and_modify(|s| s.merge_by_mid_rid(&stats))
1044            .or_insert(stats);
1045    }
1046}
1047
1048#[derive(Debug, Clone, Copy)]
1049pub(crate) struct RegisterUpdateReceipt {
1050    pub time: MediaTime,
1051    pub is_new_packet: bool,
1052}
1053
1054#[cfg(test)]
1055mod tests {
1056    use super::*;
1057
1058    #[test]
1059    fn paused_timestamp_repair_moves_time_forward() {
1060        let now = already_happened();
1061        let mut stream = StreamRx::new(
1062            7.into(),
1063            MidRid("mid".into(), None),
1064            false,
1065            Duration::from_millis(1500),
1066        );
1067        let previous_time = 1;
1068        stream.last_time = Some(MediaTime::new(previous_time, Frequency::NINETY_KHZ));
1069        stream.paused = true;
1070
1071        let header = RtpHeader {
1072            payload_type: Pt::new_with_value(96),
1073            sequence_number: 42,
1074            timestamp: 0,
1075            ssrc: 7.into(),
1076            ..Default::default()
1077        };
1078
1079        let seq_no = stream.extend_seq(&header, false, |_| None);
1080        let receipt = stream.update_register(now, &header, Frequency::NINETY_KHZ, false, seq_no);
1081
1082        assert!(
1083            receipt.time.numer() > previous_time,
1084            "expected repaired media time to move forward"
1085        );
1086        assert!(!stream.paused);
1087    }
1088
1089    /// Feed packets `(seq, rtp_time)` into a fresh stream, as received on the wire.
1090    fn stream_with(packets: &[(u16, u32)]) -> StreamRx {
1091        let now = already_happened();
1092        let mut stream = StreamRx::new(
1093            7.into(),
1094            MidRid("mid".into(), None),
1095            false,
1096            Duration::from_millis(1500),
1097        );
1098        for (seq, ts) in packets {
1099            let header = RtpHeader {
1100                payload_type: Pt::new_with_value(111),
1101                sequence_number: *seq,
1102                timestamp: *ts,
1103                ssrc: 7.into(),
1104                ..Default::default()
1105            };
1106            let seq_no = stream.extend_seq(&header, false, |_| None);
1107            stream.update_register(now, &header, Frequency::FORTY_EIGHT_KHZ, false, seq_no);
1108        }
1109        stream
1110    }
1111
1112    #[test]
1113    fn dlrr_for_local_ssrc_updates_receive_streams() {
1114        let mut streams = crate::streams::Streams::new(false, 1200, Duration::from_millis(1500));
1115        for (ssrc, mid) in [(7, "video"), (8, "audio")] {
1116            streams.expect_stream_rx(ssrc.into(), None, MidRid(mid.into(), None), false);
1117        }
1118        let default_ssrc = streams.first_ssrc_local();
1119        streams.declare_stream_tx(9.into(), None, MidRid("send".into(), None));
1120        let now = Instant::now();
1121        let last_rr_time = ((now - Duration::from_millis(250))
1122            .to_system_time()
1123            .as_ntp_64()
1124            >> 16) as u32;
1125
1126        // Ignore a sub-block addressed to the remote media source instead of us.
1127        streams.handle_dlrr(
1128            now,
1129            DlrrItem {
1130                ssrc: 7.into(),
1131                last_rr_time,
1132                last_rr_delay: 3276,
1133            },
1134        );
1135        assert_eq!(streams.stream_rx(&7.into()).unwrap().stats.rtt, None);
1136
1137        // Accept both an active sender and the fallback SSRC used before it existed.
1138        for local_ssrc in [9.into(), default_ssrc] {
1139            for ssrc in [7, 8] {
1140                streams.stream_rx(&ssrc.into()).unwrap().stats.rtt = None;
1141            }
1142            streams.handle_dlrr(
1143                now,
1144                DlrrItem {
1145                    ssrc: local_ssrc,
1146                    last_rr_time,
1147                    last_rr_delay: 3276,
1148                },
1149            );
1150            for ssrc in [7, 8] {
1151                let rtt = streams.stream_rx(&ssrc.into()).unwrap().stats.rtt.unwrap();
1152                assert!((Duration::from_millis(199)..=Duration::from_millis(201)).contains(&rtt));
1153            }
1154        }
1155    }
1156
1157    #[test]
1158    fn nack_retries_use_receive_stream_rtt() {
1159        for rtt in [Duration::from_millis(20), Duration::from_millis(250)] {
1160            let mut stream = stream_with(&[(10, 0), (12, 1920)]);
1161            stream.stats.rtt = Some(rtt);
1162            let now = Instant::now();
1163            let mut feedback = VecDeque::new();
1164            assert!(
1165                stream
1166                    .maybe_create_nack(now, 1.into(), &mut feedback)
1167                    .is_some()
1168            );
1169            let due = now + rtt + Duration::from_millis(5);
1170            assert!(
1171                stream
1172                    .maybe_create_nack(due - Duration::from_nanos(1), 1.into(), &mut feedback)
1173                    .is_none()
1174            );
1175            assert_eq!(feedback.len(), 1);
1176            assert!(
1177                stream
1178                    .maybe_create_nack(due, 1.into(), &mut feedback)
1179                    .is_some()
1180            );
1181            assert_eq!(feedback.len(), 2);
1182        }
1183    }
1184
1185    #[test]
1186    fn paused_stream_finishes_pending_nack_retries() {
1187        let mut stream = stream_with(&[(10, 0), (12, 1920)]);
1188        let mut now = stream.paused_at().unwrap();
1189        stream.handle_timeout(now);
1190        assert!(stream.paused);
1191
1192        let mut feedback = VecDeque::new();
1193        for _ in 0..5 {
1194            assert!(stream.nack_enabled());
1195            assert!(
1196                stream
1197                    .maybe_create_nack(now, 1.into(), &mut feedback)
1198                    .is_some()
1199            );
1200            assert!(
1201                stream
1202                    .maybe_create_nack(now, 1.into(), &mut feedback)
1203                    .is_none()
1204            );
1205            now += Duration::from_millis(105);
1206        }
1207        assert_eq!(feedback.len(), 5);
1208        assert!(feedback.iter().all(|rtcp| {
1209            matches!(rtcp, Rtcp::Nack(nack) if nack.reports.len() == 1 && nack.reports[0].pid == 11)
1210        }));
1211
1212        assert!(!stream.nack_enabled());
1213        assert!(
1214            stream
1215                .maybe_create_nack(now, 1.into(), &mut feedback)
1216                .is_none()
1217        );
1218        assert_eq!(feedback.len(), 5);
1219    }
1220
1221    #[test]
1222    fn red_locate_seq_single_hole_regardless_of_frame_duration() {
1223        // 20 ms frames, then a 40 ms frame at seq 12, then 20 ms again. Seq 13 lost.
1224        let stream = stream_with(&[(10, 0), (11, 960), (12, 1920), (14, 4800)]);
1225
1226        // Block at the time of seq 13 (1920 + 1920): the only hole between 12 and 14.
1227        assert_eq!(stream.red_locate_seq(14.into(), 3840), Some(13.into()));
1228    }
1229
1230    #[test]
1231    fn red_locate_seq_several_holes_need_uniform_spacing() {
1232        // Seq 11, 12, 13 lost; 10 and 14 bracket them 4 frames apart: unambiguous.
1233        let stream = stream_with(&[(10, 0), (14, 3840)]);
1234        assert_eq!(stream.red_locate_seq(14.into(), 960), Some(11.into()));
1235        assert_eq!(stream.red_locate_seq(14.into(), 1920), Some(12.into()));
1236        assert_eq!(stream.red_locate_seq(14.into(), 2880), Some(13.into()));
1237        // Not on a slot: skip rather than guess.
1238        assert_eq!(stream.red_locate_seq(14.into(), 1000), None);
1239
1240        // Same holes, but one of the lost frames was longer (span not a multiple): every block
1241        // is skipped, none is misplaced.
1242        let stream = stream_with(&[(10, 0), (14, 4800)]);
1243        for t in [960, 1920, 2880, 3840] {
1244            assert_eq!(stream.red_locate_seq(14.into(), t), None, "time {t}");
1245        }
1246    }
1247
1248    #[test]
1249    fn red_locate_seq_rejects_known_and_recovered_frames() {
1250        let mut stream = stream_with(&[(10, 0), (14, 3840)]);
1251        let now = Instant::now();
1252        let mut feedback = VecDeque::new();
1253        assert!(
1254            stream
1255                .maybe_create_nack(now, 1.into(), &mut feedback)
1256                .is_some()
1257        );
1258
1259        // A block for a frame we already have is not a recovery.
1260        assert_eq!(stream.red_locate_seq(14.into(), 0), None);
1261
1262        // Once recovered, the seq is neither a hole nor NACKed, and a later block for the same
1263        // frame is rejected instead of being pushed into a neighbouring hole.
1264        stream.mark_red_recovered(12.into(), 1920);
1265        assert_eq!(stream.red_locate_seq(14.into(), 1920), None);
1266        assert!(!stream.is_new_packet(false, 12.into()));
1267        let nacked: Vec<SeqNo> = stream
1268            .register
1269            .as_mut()
1270            .unwrap()
1271            .nack_report(now + Duration::from_millis(105), None)
1272            .into_iter()
1273            .flatten()
1274            .flat_map(|n| {
1275                n.reports
1276                    .iter()
1277                    .flat_map(|r| r.into_iter(10.into()))
1278                    .collect::<Vec<_>>()
1279            })
1280            .collect();
1281        assert_eq!(nacked, vec![11.into(), 13.into()]);
1282
1283        // The remaining holes are still found (11 and 13 are single-hole brackets now).
1284        assert_eq!(stream.red_locate_seq(14.into(), 960), Some(11.into()));
1285        assert_eq!(stream.red_locate_seq(14.into(), 2880), Some(13.into()));
1286    }
1287
1288    #[test]
1289    fn red_locate_seq_limits_recovery_depth() {
1290        let mut packets = vec![(10u16, 0u32)];
1291        // Seq 11 lost, then 12..=30 received at 20 ms.
1292        packets.extend((12..=30u16).map(|s| (s, (s as u32 - 10) * 960)));
1293        let stream = stream_with(&packets);
1294        assert_eq!(stream.red_locate_seq(30.into(), 960), None);
1295        assert_eq!(stream.red_locate_seq(19.into(), 960), Some(11.into()));
1296    }
1297
1298    #[test]
1299    fn receiver_report_uses_supplied_intervals() {
1300        let mut stream = StreamRx::new(
1301            7.into(),
1302            MidRid("mid".into(), None),
1303            false,
1304            Duration::from_millis(1500),
1305        );
1306        let now = Instant::now();
1307        stream.last_receiver_report = now;
1308
1309        assert_eq!(
1310            stream.receiver_report_at(RtcpReportIntervals {
1311                audio: Duration::from_millis(750),
1312                video: Duration::from_millis(500),
1313            }),
1314            now + Duration::from_millis(750)
1315        );
1316    }
1317
1318    #[test]
1319    fn rtx_tracks_rollover_and_reordering_only_after_receipt() {
1320        let mut stream = rtx_stream();
1321        let header = rtx_header(8, 50000);
1322        stream.extend_seq(&header, true, |_| None);
1323        assert!(
1324            stream.register_rtx.is_none(),
1325            "unverified headers must not advance the window"
1326        );
1327
1328        for seq in [65535, 65536, 65538, 65537] {
1329            record_rtx(&mut stream, seq);
1330            assert!(!stream.is_new_packet(true, seq.into()));
1331        }
1332        assert!(
1333            stream.register.is_none(),
1334            "RTX must not update primary reception reports"
1335        );
1336        let mut feedback = VecDeque::new();
1337        assert!(
1338            stream
1339                .maybe_create_nack(Instant::now(), 1.into(), &mut feedback)
1340                .is_none()
1341        );
1342        assert!(feedback.is_empty());
1343    }
1344
1345    #[test]
1346    fn rtx_uses_the_full_128_position_window() {
1347        let mut stream = rtx_stream();
1348        record_rtx(&mut stream, 0);
1349        record_rtx(&mut stream, 200);
1350        assert!(!stream.is_new_packet(true, 72.into()));
1351        assert!(stream.is_new_packet(true, 73.into()));
1352        record_rtx(&mut stream, 73);
1353        assert!(!stream.is_new_packet(true, 73.into()));
1354    }
1355
1356    #[test]
1357    fn rtx_buffer_and_roc_resets_preserve_remembered_replay_floor() {
1358        let mut stream = rtx_stream();
1359        record_rtx(&mut stream, 65535);
1360        record_rtx(&mut stream, 65537);
1361        assert!(stream.is_new_packet(true, 65536.into()));
1362        let history = |ssrc| (ssrc == 8.into()).then_some(65537.into());
1363        stream.reset_buffers(history);
1364        assert!(!stream.is_new_packet(true, 65536.into()));
1365        assert!(!stream.is_new_packet(true, 65537.into()));
1366
1367        stream.reset_roc(5);
1368        let header = rtx_header(8, 2);
1369        assert_eq!(stream.extend_seq(&header, true, history), 65538.into());
1370        assert!(!stream.is_new_packet(true, 65536.into()));
1371        assert!(stream.is_new_packet(true, 65538.into()));
1372        // The requested ROC applies to the main stream, not the RTX sequence series.
1373        let main = RtpHeader {
1374            ssrc: 7.into(),
1375            sequence_number: 10,
1376            ..Default::default()
1377        };
1378        assert_eq!(
1379            stream.extend_seq(&main, false, history),
1380            ((5u64 << 16) + 10).into()
1381        );
1382    }
1383
1384    #[test]
1385    fn rtx_ssrc_changes_restore_history_and_main_changes_preserve_it() {
1386        let mut stream = rtx_stream();
1387        record_rtx(&mut stream, 65535);
1388        assert!(stream.change_ssrc(9.into()));
1389        assert!(!stream.is_new_packet(true, 65535.into()));
1390        stream.maybe_reset_rtx(8.into());
1391        assert!(!stream.is_new_packet(true, 65535.into()));
1392
1393        stream.maybe_reset_rtx(10.into());
1394        assert!(stream.register_rtx.is_none());
1395        record_rtx(&mut stream, 0);
1396        stream.maybe_reset_rtx(8.into());
1397        let header = rtx_header(8, 0);
1398        let seq = stream.extend_seq(&header, true, |ssrc| {
1399            (ssrc == 8.into()).then_some(65535.into())
1400        });
1401        assert_eq!(seq, 65536.into());
1402        assert!(!stream.is_new_packet(true, 65534.into()));
1403        assert!(!stream.is_new_packet(true, 65535.into()));
1404        assert!(stream.is_new_packet(true, seq));
1405        record_rtx(&mut stream, 65536);
1406    }
1407
1408    fn rtx_stream() -> StreamRx {
1409        let mut stream = StreamRx::new(
1410            7.into(),
1411            MidRid("mid".into(), None),
1412            false,
1413            Duration::from_millis(1500),
1414        );
1415        stream.maybe_reset_rtx(8.into());
1416        stream
1417    }
1418
1419    fn record_rtx(stream: &mut StreamRx, seq: u64) {
1420        let header = rtx_header(*stream.rtx().unwrap(), seq as u16);
1421        let extended = stream.extend_seq(&header, true, |_| None);
1422        assert_eq!(extended, seq.into());
1423        assert!(stream.is_new_packet(true, extended));
1424        let receipt = stream.update_register(
1425            already_happened(),
1426            &header,
1427            Frequency::NINETY_KHZ,
1428            true,
1429            extended,
1430        );
1431        assert!(receipt.is_new_packet);
1432    }
1433
1434    fn rtx_header(ssrc: u32, seq: u16) -> RtpHeader {
1435        RtpHeader {
1436            ssrc: ssrc.into(),
1437            sequence_number: seq,
1438            payload_type: 97.into(),
1439            ..Default::default()
1440        }
1441    }
1442}