Skip to main content

str0m/streams/
send.rs

1// Changed by Alakazam Labs for sew-str0m; the fork's patches are listed in its README.
2use std::collections::VecDeque;
3use std::sync::Arc;
4use std::time::Duration;
5use std::time::Instant;
6
7use crate::config_mod::RtcpReportIntervals;
8use crate::format::CodecConfig;
9use crate::format::PayloadParams;
10use crate::io::DATAGRAM_MAX_PACKET_SIZE;
11use crate::io::MAX_RTP_OVERHEAD;
12use crate::media::KeyframeRequestKind;
13use crate::media::Media;
14use crate::media::MediaKind;
15use crate::pacer::QueuePriority;
16use crate::pacer::QueueSnapshot;
17use crate::pacer::QueueState;
18use crate::packet::Vp8Patch;
19use crate::rtp_::MidRid;
20use crate::rtp_::{Bitrate, Descriptions, Extension, ExtensionMap, ExtensionValues, Frequency};
21use crate::rtp_::{MAX_BLANK_PADDING_PAYLOAD_SIZE, Sdes, SdesType};
22use crate::rtp_::{MediaTime, Mid, NackEntry, ReportList, Rtcp, RtpHeader};
23use crate::rtp_::{Pt, Rid, RtcpFb, SenderInfo, SenderReport, Ssrc};
24use crate::rtp_::{SRTP_BLOCK_SIZE, SeqNo};
25use crate::session::PacketReceipt;
26use crate::stats::StatsSnapshot;
27use crate::util::value_history::ValueHistory;
28use crate::util::{InstantExt, already_happened, not_happening};
29
30use super::RtpPacket;
31use super::rtx_cache::{RtxCache, SentWire};
32use super::send_queue::SendQueue;
33use super::send_stats::StreamTxStats;
34
35/// The smallest size of padding for which we attempt to use a spurious resend. For padding
36/// requests smaller than this we use blank packets instead.
37const MIN_SPURIOUS_PADDING_SIZE: usize = 50;
38
39pub const DEFAULT_RTX_CACHE_DURATION: Duration = Duration::from_secs(3);
40
41pub const DEFAULT_RTX_RATIO_CAP: Option<f32> = Some(0.15f32);
42
43/// A recently sampled view of an outgoing stream's send queue.
44///
45/// str0m refreshes this information as part of its regular pacer and bandwidth-estimation
46/// processing. Reading it does not cause a new value to be computed.
47pub trait StreamTxQueueInfo {
48    /// When this queue information was sampled.
49    ///
50    /// Compare this value between reads to determine whether str0m has computed a new sample.
51    fn created_at(&self) -> Instant;
52
53    /// Total number of bytes in the queue.
54    fn byte_size(&self) -> usize;
55
56    /// Total number of packets in the queue.
57    fn packet_count(&self) -> usize;
58
59    /// When the first packet still in the queue was enqueued.
60    fn first_unsent(&self) -> Option<Instant>;
61}
62
63impl StreamTxQueueInfo for QueueSnapshot {
64    fn created_at(&self) -> Instant {
65        self.created_at
66    }
67
68    fn byte_size(&self) -> usize {
69        self.byte_size
70    }
71
72    fn packet_count(&self) -> usize {
73        self.packet_count as usize
74    }
75
76    fn first_unsent(&self) -> Option<Instant> {
77        self.first_unsent
78    }
79}
80
81/// Outgoing encoded stream.
82///
83/// A stream is a primary SSRC + optional RTX SSRC.
84///
85/// This is RTP level API. For frame level API see [`Rtc::writer`][crate::Rtc::writer].
86#[derive(Debug)]
87pub struct StreamTx {
88    /// Unique identifier of the remote encoded stream.
89    ssrc: Ssrc,
90
91    /// Identifier of a resend (RTX) stream. If we are doing resends.
92    rtx: Option<Ssrc>,
93
94    /// The Media mid and rid this stream belongs to.
95    midrid: MidRid,
96
97    /// Set on first handle_timeout.
98    kind: Option<MediaKind>,
99
100    /// Set on first handle_timeout.
101    cname: Option<String>,
102
103    /// The last main payload clock rate that was sent.
104    clock_rate: Option<Frequency>,
105
106    /// If we are doing seq_no ourselves (frame mode or SSRC 0 probing).
107    seq_no: SeqNo,
108
109    /// If we are using RTX, this is the seq no counter.
110    seq_no_rtx: SeqNo,
111
112    /// The last seq_no that we sent, either by increasing seq_no ourselves (media API), or by
113    /// direct RTP mode writing.
114    last_sent_seq_no: SeqNo,
115
116    /// When we last sent something for this encoded stream, packet or RTCP.
117    last_used: Instant,
118
119    /// Last written media + wallclock time.
120    rtp_and_wallclock: Option<(u32, Instant)>,
121
122    /// Queue of packets to send.
123    ///
124    /// The packets here do not have correct sequence numbers, header extension values etc.
125    /// They must be updated when we are about to send.
126    send_queue: SendQueue,
127
128    /// The queue information sampled during the latest pacer update.
129    queue_info: Option<QueueSnapshot>,
130
131    /// Whether this sender is to be unpaced in BWE situations.
132    ///
133    /// Audio defaults to not being paced.
134    unpaced: Option<bool>,
135
136    /// Scheduled resends due to NACK or spurious padding.
137    resends: VecDeque<Resend>,
138
139    /// Requested padding, that has not been turned into packets yet.
140    padding: usize,
141
142    /// Dummy packet for resends. Used between poll_packet and poll_packet_padding
143    blank_packet: RtpPacket,
144
145    /// Cache of sent packets to be able to answer to NACKs as well as
146    /// sending spurious resends as padding.
147    rtx_cache: RtxCache,
148
149    /// Determines retransmitted bytes ratio value to clear queued resends.
150    rtx_ratio_cap: Option<f32>,
151
152    /// Optional per-packet limits on answering NACKs. `None` answers every NACK for a
153    /// cached packet (the default).
154    nack_policy: Option<NackPolicy>,
155
156    /// Last time we produced a SR.
157    last_sender_report: Instant,
158
159    /// If we have a pending incoming keyframe request.
160    pending_request_keyframe: Option<KeyframeRequestKind>,
161
162    /// If we have a pending incoming remb request.
163    pending_request_remb: Option<Bitrate>,
164
165    /// Statistics of outgoing data.
166    ///
167    /// Stats are use to calculate the rtx ratio also when statistics events are disabled.
168    stats: StreamTxStats,
169
170    // downsampled rtx ratio (value, last calculation)
171    rtx_ratio: (f32, Instant),
172
173    // The _main_ PT to use for padding. This is main PT, since the poll_packet() loop
174    // figures out the param.resend() RTX PT using main.
175    pt_for_padding: Option<Pt>,
176
177    /// Whether a receiver report has been received for this SSRC, thus acknowledging
178    /// that the receiver has bound the Mid/Rid tuple to the SSRC and no longer
179    /// needs to be sent on every packet
180    remote_acked_ssrc: bool,
181
182    // Same as `remote_acked_ssrc`, but for the RTX SSRC
183    remote_acked_rtx_ssrc: bool,
184
185    /// MTU warn threshold; used to cap spurious-padding RTX cache lookups.
186    mtu_warn: usize,
187}
188
189/// Per-packet limits on answering incoming NACKs, set with [`StreamTx::set_nack_policy`].
190///
191/// A NACKed packet is resent only if it has been resent fewer than `max_resends` times and
192/// more than `min(min_interval, rtt_factor × RTT)` has passed since its last resend (with
193/// `hold_after_send`, also since it was first sent). When the RTT is unknown, `min_interval`
194/// alone applies.
195///
196/// [`NackPolicy::default`] is 3 resends per packet, a 100 ms hold-off of at most 2 RTTs,
197/// held after the first send too, and at most 1000 queued resends. Build a policy with
198/// [`NackPolicy::new`], or start from the default and change it with the `with_*` setters,
199/// such as [`NackPolicy::with_max_resends`].
200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
201#[non_exhaustive]
202pub struct NackPolicy {
203    /// Upper bound of the hold-off between resends of one packet.
204    pub min_interval: Duration,
205    /// The hold-off is at most this many RTTs.
206    pub rtt_factor: u32,
207    /// Resends per packet.
208    pub max_resends: u8,
209    /// Hold NACKs that arrive within the hold-off of the packet's first send.
210    pub hold_after_send: bool,
211    /// Upper bound on resends waiting in the queue; more are dropped and counted.
212    pub max_queued_resends: usize,
213}
214
215impl NackPolicy {
216    /// A policy with these limits (see the fields).
217    pub fn new(
218        min_interval: Duration,
219        rtt_factor: u32,
220        max_resends: u8,
221        hold_after_send: bool,
222        max_queued_resends: usize,
223    ) -> Self {
224        NackPolicy {
225            min_interval,
226            rtt_factor,
227            max_resends,
228            hold_after_send,
229            max_queued_resends,
230        }
231    }
232}
233
234impl NackPolicy {
235    /// This policy with `min_interval` as the upper bound of the hold-off between resends.
236    pub fn with_min_interval(mut self, min_interval: Duration) -> Self {
237        self.min_interval = min_interval;
238        self
239    }
240
241    /// This policy with the hold-off at most `rtt_factor` RTTs.
242    pub fn with_rtt_factor(mut self, rtt_factor: u32) -> Self {
243        self.rtt_factor = rtt_factor;
244        self
245    }
246
247    /// This policy with at most `max_resends` resends per packet.
248    pub fn with_max_resends(mut self, max_resends: u8) -> Self {
249        self.max_resends = max_resends;
250        self
251    }
252
253    /// This policy holding NACKs within the hold-off of a packet's first send, or not.
254    pub fn with_hold_after_send(mut self, hold_after_send: bool) -> Self {
255        self.hold_after_send = hold_after_send;
256        self
257    }
258
259    /// This policy with at most `max_queued_resends` resends waiting in the queue.
260    pub fn with_max_queued_resends(mut self, max_queued_resends: usize) -> Self {
261        self.max_queued_resends = max_queued_resends;
262        self
263    }
264}
265
266impl Default for NackPolicy {
267    /// 3 resends per packet, a 100 ms hold-off of at most 2 RTTs (held after the first send
268    /// too), and at most 1000 queued resends. It also bounds in-band resends on a stream
269    /// without a policy (see [`StreamTx::set_nack_policy`]).
270    fn default() -> Self {
271        NackPolicy::new(Duration::from_millis(100), 2, 3, true, 1000)
272    }
273}
274
275/// RTP packet data to enqueue on a direct RTP send stream.
276///
277/// The payload is the RTP payload only, without the RTP header.
278///
279/// Optional RTP fields default to the common unmarked non-nackable packet with
280/// no header extension values, no CSRC entries and no VP8 rewrite.
281#[derive(Debug)]
282pub struct RtpWrite {
283    pt: Pt,
284    seq_no: SeqNo,
285    time: u32,
286    wallclock: Instant,
287    marker: bool,
288    ext_vals: ExtensionValues,
289    nackable: bool,
290    payload: Arc<[u8]>,
291    csrc_count: usize,
292    csrc: [u32; 15],
293    vp8_patch: Option<Vp8Patch>,
294}
295
296impl RtpWrite {
297    /// Create a direct RTP write command.
298    ///
299    /// The `payload` argument is expected to be only the RTP payload, not the
300    /// RTP packet header.
301    ///
302    /// * `pt` Payload type. Declared in the [`Media`][crate::media::Media] this
303    ///        encoded stream belongs to.
304    /// * `seq_no` Extended sequence number to use for this packet. Only the low
305    ///            16 bits are carried in the RTP header. The upper bits
306    ///            (`seq_no.roc()`) supply the SRTP rollover counter (ROC) used
307    ///            for the per-packet IV and authentication. See below for
308    ///            initializing a stream with a nonzero ROC.
309    /// * `time` Time in whatever the clock rate is for the media in question
310    ///          (normally 90_000 for video and 48_000 for audio).
311    /// * `wallclock` Real world time that corresponds to the media time in the
312    ///               RTP packet. For an SFU, this can be hard to know because
313    ///               RTP packets typically only contain the media time (RTP
314    ///               time). In the simplest SFU setup, the wallclock could
315    ///               simply be the arrival time of the incoming RTP data. For
316    ///               better synchronization the SFU probably needs to weigh in
317    ///               clock drifts and data provided via the statistics, receiver
318    ///               reports etc.
319    /// * `payload` RTP packet payload, without header.
320    ///
321    /// Optional fields default to an unmarked packet with no header extension
322    /// values, no CSRC entries, no VP8 patch and no NACK support.
323    /// [`RtpWrite::marker`] for video frame boundaries,
324    /// [`RtpWrite::ext_vals`] for RTP header extension values,
325    /// [`RtpWrite::nackable`] for packets that may answer incoming NACKs,
326    /// [`RtpWrite::csrc`] for contributing source identifiers,
327    /// [`RtpWrite::vp8_patch`] to apply a prevalidated VP8 payload descriptor patch during RTP serialization.
328    ///
329    /// # Initializing the rollover counter
330    ///
331    /// The ROC is not carried in the RTP header or transmitted by str0m in the
332    /// SRTP packet. A fresh receiver starts at ROC 0. To start a stream with a
333    /// higher ROC, the application must communicate that ROC and the stream's
334    /// SSRC to the receiver out of band, for example through its signaling
335    /// channel, and initialize the receiver before sending media. Otherwise,
336    /// sender and receiver use different packet indices and SRTP authentication
337    /// fails. See [RFC 3711 section 3.3.1][roc].
338    ///
339    /// On the sender, the extended sequence number determines the ROC:
340    ///
341    /// ```
342    /// # use std::time::Instant;
343    /// # use str0m::media::Pt;
344    /// # use str0m::rtp::{RtpWrite, SeqNo, StreamTx};
345    /// # fn send(stream: &mut StreamTx, pt: Pt, wallclock: Instant, payload: &[u8]) {
346    /// let seq_no: SeqNo = 100_000.into();
347    /// assert_eq!(seq_no.roc(), 1);
348    /// assert_eq!(seq_no.as_u16(), 34_464);
349    ///
350    /// // First communicate (stream.ssrc(), seq_no.roc()) out of band and
351    /// // arrange for the receiver to initialize its ROC as shown below.
352    /// stream.write_rtp(RtpWrite::new(pt, seq_no, 0, wallclock, payload));
353    /// # }
354    /// ```
355    ///
356    /// On a str0m receiver, use [`StreamRx::reset_roc`][crate::rtp::StreamRx::reset_roc]
357    /// with the signaled ROC before handling the first SRTP packet. This example
358    /// assumes the media identified by `mid` has already been declared:
359    ///
360    /// ```
361    /// # use str0m::Rtc;
362    /// # use str0m::media::Mid;
363    /// # use str0m::rtp::Ssrc;
364    /// # fn initialize_receiver(rtc: &mut Rtc, mid: Mid, ssrc: Ssrc, signaled_roc: u64) {
365    /// // `ssrc` and `signaled_roc` come from the application's signaling channel.
366    /// let mut direct = rtc.direct_api();
367    /// let stream = direct.expect_stream_rx(ssrc, None, mid, None);
368    /// stream.reset_roc(signaled_roc); // 1 for the sender example above.
369    /// # }
370    /// ```
371    ///
372    /// Continue supplying extended sequence numbers on the sender across
373    /// rollovers; the receiver tracks subsequent rollovers automatically.
374    /// Without out-of-band ROC initialization, start the outgoing stream with
375    /// `seq_no < 65_536`. In particular, forwarding a long-running source's
376    /// extended sequence numbers to a new receiver requires either signaling
377    /// its initial ROC or rebasing the outgoing sequence numbers for that receiver.
378    ///
379    /// [roc]: https://www.rfc-editor.org/rfc/rfc3711.html#section-3.3.1
380    pub fn new(
381        pt: Pt,
382        seq_no: SeqNo,
383        time: u32,
384        wallclock: Instant,
385        payload: impl Into<Arc<[u8]>>,
386    ) -> Self {
387        Self {
388            pt,
389            seq_no,
390            time,
391            wallclock,
392            marker: false,
393            ext_vals: ExtensionValues::default(),
394            nackable: false,
395            payload: payload.into(),
396            csrc_count: 0,
397            csrc: [0; 15],
398            vp8_patch: None,
399        }
400    }
401
402    /// Set the RTP marker bit.
403    pub fn marker(mut self, marker: bool) -> Self {
404        self.marker = marker;
405        self
406    }
407
408    /// Set RTP header extension values.
409    pub fn ext_vals(mut self, ext_vals: ExtensionValues) -> Self {
410        self.ext_vals = ext_vals;
411        self
412    }
413
414    /// Set whether this RTP packet should respond to incoming NACKs.
415    pub fn nackable(mut self, nackable: bool) -> Self {
416        self.nackable = nackable;
417        self
418    }
419
420    /// Set contributing source identifiers.
421    ///
422    /// # Panics
423    ///
424    /// Panics if more than 15 entries are supplied.
425    pub fn csrc(mut self, csrc: &[u32]) -> Self {
426        assert!(csrc.len() <= 15, "CSRC count must be <= 15");
427
428        self.csrc = [0; 15];
429        self.csrc[..csrc.len()].copy_from_slice(csrc);
430        self.csrc_count = csrc.len();
431        self
432    }
433
434    /// Apply a prevalidated VP8 payload descriptor patch during RTP serialization.
435    ///
436    /// Build the patch with [`Vp8Descriptor::patch`][crate::rtp::Vp8Descriptor::patch]
437    /// when the caller already parsed the VP8 payload descriptor before
438    /// constructing this write command.
439    pub fn vp8_patch(mut self, patch: Vp8Patch) -> Self {
440        self.vp8_patch = Some(patch);
441        self
442    }
443}
444
445impl StreamTx {
446    pub(crate) fn new(
447        ssrc: Ssrc,
448        rtx: Option<Ssrc>,
449        midrid: MidRid,
450        enable_stats: bool,
451        mtu_warn: usize,
452    ) -> Self {
453        debug!("Create StreamTx for SSRC: {}", ssrc);
454
455        StreamTx {
456            ssrc,
457            rtx,
458            midrid,
459            kind: None,
460            cname: None,
461            clock_rate: None,
462            seq_no: SeqNo::default(),
463            seq_no_rtx: SeqNo::default(),
464            last_sent_seq_no: SeqNo::default(),
465            last_used: already_happened(),
466            rtp_and_wallclock: None,
467            send_queue: SendQueue::new(),
468            queue_info: None,
469            unpaced: None,
470            resends: VecDeque::new(),
471            padding: 0,
472            blank_packet: RtpPacket::blank(),
473            rtx_cache: RtxCache::new(2000, DEFAULT_RTX_CACHE_DURATION),
474            rtx_ratio_cap: DEFAULT_RTX_RATIO_CAP,
475            nack_policy: None,
476            last_sender_report: already_happened(),
477            pending_request_keyframe: None,
478            pending_request_remb: None,
479            stats: StreamTxStats::new(enable_stats),
480            rtx_ratio: (0.0, already_happened()),
481            pt_for_padding: None,
482            remote_acked_ssrc: false,
483            remote_acked_rtx_ssrc: false,
484            mtu_warn,
485        }
486    }
487
488    pub(crate) fn new_probe(mtu_warn: usize) -> Self {
489        let mut stream = Self::new(
490            0.into(),
491            None,
492            MidRid(crate::media::MID_PROBE, None),
493            false,
494            mtu_warn,
495        );
496        stream.unpaced = Some(false);
497        stream
498    }
499
500    pub(crate) fn set_probe_media(&mut self, mid: Mid, pt: Pt) {
501        debug_assert!(self.ssrc.is_probe());
502        self.midrid = MidRid(mid, None);
503        self.pt_for_padding = Some(pt);
504    }
505
506    /// The (primary) SSRC of this encoded stream.
507    pub fn ssrc(&self) -> Ssrc {
508        self.ssrc
509    }
510
511    /// The resend (RTX) SSRC of this encoded stream.
512    pub fn rtx(&self) -> Option<Ssrc> {
513        self.rtx
514    }
515
516    /// Mid for this stream.
517    ///
518    /// In SDP this corresponds to m-line and "Media".
519    pub fn mid(&self) -> Mid {
520        self.midrid.mid()
521    }
522
523    /// Rid for this stream.
524    ///
525    /// This is used to separate streams with the same [`Mid`] when using simulcast.
526    pub fn rid(&self) -> Option<Rid> {
527        self.midrid.rid()
528    }
529
530    /// Information sampled during the latest pacer update for this stream's send queue.
531    ///
532    /// This is `None` until the pacer has observed the stream for the first time.
533    /// Calling this method does not refresh the information; use
534    /// [`StreamTxQueueInfo::created_at()`] to determine whether a new sample is available.
535    pub fn queue_info(&self) -> Option<&dyn StreamTxQueueInfo> {
536        self.queue_info
537            .as_ref()
538            .map(|info| info as &dyn StreamTxQueueInfo)
539    }
540
541    /// Configure the RTX (resend) cache.
542    ///
543    /// This determines how old incoming NACKs we can reply to.
544    ///
545    /// `rtx_ratio_cap` determines when to clear queued resends because of too many resends,
546    /// i.e. if `tx_sum / (rtx_sum + tx_sum) > rtx_ratio_cap`. `None` disables this functionality
547    /// so all queued resends will be sent.
548    ///
549    /// The default is 2000 packets over 3 seconds and RTX cache drop ratio of 0.15.
550    pub fn set_rtx_cache(
551        &mut self,
552        max_packets: usize,
553        max_age: Duration,
554        rtx_ratio_cap: Option<f32>,
555    ) {
556        // Dump old cache to avoid having to deal with resizing logic inside the cache impl.
557        self.rtx_cache = RtxCache::new(max_packets, max_age);
558        if rtx_ratio_cap.is_some() {
559            self.stats
560                .bytes_transmitted
561                .get_or_insert_with(ValueHistory::default);
562            self.stats
563                .bytes_retransmitted
564                .get_or_insert_with(ValueHistory::default);
565        } else {
566            self.stats.bytes_transmitted = None;
567            self.stats.bytes_retransmitted = None;
568        }
569        self.rtx_ratio_cap = rtx_ratio_cap;
570    }
571
572    /// Configure per-packet limits on answering incoming NACKs.
573    ///
574    /// Without a policy (the default) every NACK for a packet still in the RTX cache queues an
575    /// RTX resend, so a receiver repeating a NACK gets the packet again each time, and the
576    /// queue of resends is only bounded by the `rtx_ratio_cap` (see
577    /// [`StreamTx::set_rtx_cache`]). Resends without RTX (in-band on the main SSRC) are
578    /// bounded by [`NackPolicy::default`] even without a policy.
579    ///
580    /// With a policy, a NACKed packet is resent at most [`NackPolicy::max_resends`] times, and
581    /// not again within `min(min_interval, rtt_factor × RTT)` of its last resend (or of its
582    /// first send, with [`NackPolicy::hold_after_send`]). At most
583    /// [`NackPolicy::max_queued_resends`] resends wait in the queue; the rest are dropped and
584    /// counted in [`MediaEgressStats::resends_dropped`][crate::stats::MediaEgressStats]. The
585    /// policy applies to RTX and in-band resends alike.
586    pub fn set_nack_policy(&mut self, policy: Option<NackPolicy>) {
587        self.nack_policy = policy;
588    }
589
590    /// Set whether this stream is unpaced or not.
591    ///
592    /// This is only relevant when BWE (Bandwidth Estimation) is enabled. By default, audio is unpaced
593    /// thus not held to a steady send rate by the Pacer.
594    ///
595    /// This overrides the default behavior.
596    pub fn set_unpaced(&mut self, unpaced: bool) {
597        self.unpaced = Some(unpaced);
598    }
599
600    /// Write RTP packet to a send stream.
601    ///
602    /// The write command carries the RTP payload and optional RTP metadata.
603    pub fn write_rtp(&mut self, rtp: RtpWrite) {
604        let RtpWrite {
605            pt,
606            seq_no,
607            time,
608            wallclock,
609            marker,
610            ext_vals,
611            nackable,
612            payload,
613            csrc_count,
614            csrc,
615            vp8_patch,
616        } = rtp;
617
618        let first_call = self.rtp_and_wallclock.is_none();
619
620        if first_call && seq_no.roc() > 0 {
621            // TODO: make it possible to supress this.
622            warn!(
623                "First SeqNo has non-zero ROC ({}), which needs out-of-band signalling \
624                to remote peer",
625                seq_no.roc()
626            );
627        }
628
629        // This 1 in clock frequency will be fixed in poll_output.
630        let media_time = MediaTime::from_secs(time as u64);
631        self.rtp_and_wallclock = Some((time, wallclock));
632
633        let header = RtpHeader {
634            csrc_count,
635            sequence_number: *seq_no as u16,
636            marker,
637            payload_type: pt,
638            timestamp: time,
639            ssrc: self.ssrc,
640            csrc,
641            ext_vals,
642            ..Default::default()
643        };
644
645        let packet = RtpPacket {
646            seq_no,
647            time: media_time,
648            header,
649            payload,
650            vp8_patch,
651            nackable,
652            // The overall idea for str0m is to only drive time forward from handle_input. If we
653            // used a "now" argument to write_rtp(), we effectively get a second point that also need
654            // to move time forward _for all of Rtc_ – that's too complicated.
655            //
656            // Instead we set a future timestamp here. When time moves forward in the "regular way",
657            // in handle_timeout() we delegate to self.send_queue.handle_timeout() to mark the enqueued
658            // timestamp of all packets that are about to be sent.
659            timestamp: not_happening(),
660
661            // This is only relevant for incoming RTP packets.
662            last_sender_info: None,
663        };
664
665        self.send_queue.push(packet);
666    }
667
668    fn padding_enabled(&self) -> bool {
669        (self.ssrc.is_probe() || self.rtx.is_some()) && self.pt_for_padding.is_some()
670    }
671
672    pub(crate) fn poll_packet(
673        &mut self,
674        now: Instant,
675        exts: &ExtensionMap,
676        twcc: Option<&mut u64>,
677        params: &[PayloadParams],
678        buf: &mut Vec<u8>,
679    ) -> Option<PacketReceipt> {
680        let mid = self.midrid.mid();
681        let rid = self.midrid.rid();
682        let is_probe = self.ssrc.is_probe();
683        if is_probe && twcc.is_none() {
684            return None;
685        }
686        let ssrc_rtx = self.rtx;
687        let remote_acked_ssrc = self.remote_acked_ssrc;
688        let remote_acked_rtx_ssrc = self.remote_acked_rtx_ssrc;
689
690        let (next, is_padding) = if let Some(next) = self.poll_packet_resend(now) {
691            (next, false)
692        } else if let Some(next) = self.poll_packet_regular(now) {
693            (next, false)
694        } else {
695            let next = self.poll_packet_padding(now)?;
696            (next, true)
697        };
698
699        if next.kind == NextPacketKind::ResendInband {
700            let seq_no = next.seq_no;
701            return self.poll_packet_resend_inband(now, seq_no, buf);
702        }
703
704        let pop_send_queue = next.kind == NextPacketKind::Regular;
705
706        // Need the header for the receipt and modifications
707        // TODO: Can we remove this?
708        let header_ref = &mut next.pkt.header;
709
710        // <https://webrtc.googlesource.com/src/+/refs/heads/main/modules/rtp_rtcp/source/rtp_sender.cc#537>
711        // BUNDLE requires that the receiver "bind" the received SSRC to the values
712        // in the MID and/or (R)RID header extensions if present. Therefore, the
713        // sender can reduce overhead by omitting these header extensions once it
714        // knows that the receiver has "bound" the SSRC.
715        // <snip>
716        // The algorithm here is fairly simple: Always attach a MID and/or RID (if
717        // configured) to the outgoing packets until an RTCP receiver report comes
718        // back for this SSRC. That feedback indicates the receiver must have
719        // received a packet with the SSRC and header extension(s), so the sender
720        // then stops attaching the MID and RID.
721        if !remote_acked_ssrc {
722            header_ref.ext_vals.mid = Some(mid);
723            header_ref.ext_vals.rid = rid;
724        }
725
726        let pt_main = header_ref.payload_type;
727
728        // The pt in next.pkt is the "main" pt, or a RED PT folded onto its primary codec.
729        let Some(param) = params
730            .iter()
731            .find(|p| p.pt() == pt_main || p.red() == Some(pt_main))
732        else {
733            // PT does not exist in the connected media.
734            warn!("Media is missing PT ({}) used in RTP packet", pt_main);
735
736            // Get rid of this packet we can't send.
737            if pop_send_queue {
738                self.send_queue.pop(now);
739            }
740
741            return None;
742        };
743
744        let mut set_pt_for_padding = None;
745        let mut set_cr = None;
746        // A regular packet whose PT has no RTX PT can only be resent in-band.
747        let mut in_band_only = false;
748
749        let mut header = match next.kind {
750            NextPacketKind::Regular => {
751                // A RED-wrapped packet (pt_main is the RED PT) must not be nackable: an RTX
752                // resend carries the RTX PT with the primary codec's apt, so the peer would
753                // parse the RED bytes as raw primary codec. RED carries its own redundancy, so
754                // it does not need RTX anyway. Plain packets on this PT stay nackable.
755                let is_red_packet = param.red() == Some(pt_main);
756                let rtx_possible = param.resend().is_some() && !is_red_packet;
757
758                if rtx_possible {
759                    // Remember PT We want to set these directly on `self` here, but can't
760                    // because we already have a mutable borrow. We are using pt_main
761                    // since the above loop figuring out param needs to be correct also
762                    // for the NextPacketKind::Blank case.
763                    set_pt_for_padding = Some(pt_main);
764                } else if param.fb_nack() {
765                    in_band_only = true;
766                } else {
767                    // No RTX PT and no `fb_nack`: the packet cannot be resent (neither
768                    // via RTX nor in-band), so it is de-facto not nackable. This ensures
769                    // there are no entries in the rtx cache we can't resend.
770                    next.pkt.nackable = false;
771                }
772
773                let clock_rate = param.spec().rtp_clock_rate();
774                set_cr = Some(clock_rate);
775
776                // Modify the cached packet time. This is so write_rtp can use u32 media time without
777                // worrying about lengthening or the clock rate.
778                let time = MediaTime::new(next.pkt.time.numer(), clock_rate);
779                next.pkt.time = time;
780
781                // Modify the original (and also cached) header value.
782                header_ref.ext_vals.rid_repair = None;
783
784                header_ref.clone()
785            }
786            NextPacketKind::Blank(_) if is_probe => {
787                // Non-media probes use their negotiated main PT and own sequence
788                // counter, rather than rewriting the header for an RTX stream.
789                let mut header = header_ref.clone();
790                header.has_padding = true;
791                header.ssrc = 0.into();
792                header.sequence_number = *next.seq_no as u16;
793                header
794            }
795            NextPacketKind::ResendInband => {
796                unreachable!("in-band resends are sent by poll_packet_resend_inband")
797            }
798            NextPacketKind::Resend(_) | NextPacketKind::Blank(_) => {
799                // * For the Resend case, a packet is only resent over RTX when its PT has an
800                //   RTX PT and the stream has an RTX SSRC; every other cached packet (no RTX
801                //   PT, or no RTX SSRC) is resent in-band instead (see poll_packet_resend).
802                // * For the Blank case, we will only have produced blank packets if we
803                //   got a "real" PTX RT, either via set_pt_for_padding above, or via
804                //   the on_first_timeout() further down.
805                // Either way, unwrapping this optional _should_ be correct.
806                let pt_rtx = param.resend().expect("PT for resend or blank");
807
808                // Clone header to not change the original (cached) header.
809                let mut header = header_ref.clone();
810
811                // Update clone of header (to not change the cached value).
812                header.payload_type = pt_rtx;
813                header.ssrc = ssrc_rtx.expect("Should have RTX SSRC for resends");
814                header.sequence_number = *next.seq_no as u16;
815
816                header.ext_vals.rid = None;
817                header.ext_vals.rid_repair = rid;
818
819                if !remote_acked_rtx_ssrc {
820                    header.ext_vals.mid = Some(mid);
821                }
822
823                header
824            }
825        };
826
827        // These need to match `Extension::is_supported()` so we are sending what we are
828        // declaring we support.
829
830        // Absolute Send Time might not be enabled for this m-line.
831        if exts.id_of(Extension::AbsoluteSendTime).is_some() {
832            header.ext_vals.abs_send_time = Some(now);
833        }
834
835        // TWCC might not be enabled for this m-line.
836        if let Some(twcc) = twcc {
837            header.ext_vals.transport_cc = Some(*twcc as u16);
838            *twcc += 1;
839        }
840
841        buf.resize(DATAGRAM_MAX_PACKET_SIZE, 0);
842
843        let header_len = header.write_to(buf, exts);
844        assert!(header_len % 4 == 0, "RTP header must be multiple of 4");
845        header.header_len = header_len;
846
847        let mut body_out = &mut buf[header_len..];
848
849        // For resends, the original seq_no is inserted before the payload.
850        let mut original_seq_len = 0;
851        if let NextPacketKind::Resend(orig_seq_no) = next.kind {
852            original_seq_len = RtpHeader::write_original_sequence_number(body_out, orig_seq_no);
853            body_out = &mut body_out[original_seq_len..];
854        }
855
856        let pkt = &next.pkt;
857
858        let body_len = match next.kind {
859            NextPacketKind::Regular | NextPacketKind::Resend(_) | NextPacketKind::ResendInband => {
860                let body_len = pkt.payload.len();
861                if let Some(patch) = pkt.vp8_patch.as_ref() {
862                    patch.copy_to(pkt.payload.as_ref(), &mut body_out[..body_len]);
863                } else {
864                    body_out[..body_len].copy_from_slice(pkt.payload.as_ref());
865                }
866
867                // media packets are sent unpadded: the SRTP ciphers handle
868                // arbitrary body lengths (the CTR scratch alignment is internal
869                // to protect_rtp), and RTP-level padding breaks SFUs that
870                // re-marshal forwarded packets without it while keeping the P
871                // bit (observed with LiveKit -> Chrome, str0m issue #1014)
872                body_len + original_seq_len
873            }
874            NextPacketKind::Blank(len) => {
875                let len = RtpHeader::create_padding_packet(
876                    &mut buf[..],
877                    header_len,
878                    len,
879                    SRTP_BLOCK_SIZE,
880                );
881
882                if len == 0 {
883                    return None;
884                }
885
886                len
887            }
888        };
889
890        buf.truncate(header_len + body_len);
891
892        #[cfg(feature = "_internal_dont_use_log_stats")]
893        {
894            let queued_at = match next.kind {
895                NextPacketKind::Regular => Some(pkt.timestamp),
896                _ => {
897                    // TODO: We don't have queued at stats for Resends or blank padding.
898                    None
899                }
900            };
901
902            if let Some(delay) = queued_at.map(|i| now.duration_since(i)) {
903                crate::log_stat!("QUEUE_DELAY", header.ssrc, delay.as_secs_f64() * 1000.0);
904            }
905        }
906
907        let seq_no = next.seq_no;
908        if next.kind == NextPacketKind::Regular {
909            self.last_sent_seq_no = seq_no;
910        }
911
912        self.last_used = now;
913
914        // Padding comes in two forms, "spurious resends" of sent packets where
915        // the remote side didn't ask for a resend. The other variant are blank
916        // packets, containing nothing but zeroes. On media streams these use
917        // _some_ RTX PT. A good pick is the RTX for the PT last used to send
918        // regular media data.
919        //
920        // This is set here due to borrow checker.
921        if set_pt_for_padding.is_some() && self.pt_for_padding != set_pt_for_padding {
922            self.pt_for_padding = set_pt_for_padding;
923        }
924
925        if set_cr.is_some() && self.clock_rate != set_cr {
926            self.clock_rate = set_cr;
927        }
928
929        if pop_send_queue {
930            // poll_packet_regular leaves the packet in the head of the send_queue
931            let pkt = self
932                .send_queue
933                .pop(now)
934                .expect("head of send_queue to be there");
935            if pkt.nackable {
936                // A packet that may be resent in-band (no RTX PT, or no RTX SSRC) keeps the
937                // exact bytes it was sent with: an in-band resend repeats them verbatim.
938                let wire = (in_band_only || ssrc_rtx.is_none()).then(|| SentWire {
939                    bytes: buf[..].into(),
940                    header: header.clone(),
941                });
942                self.rtx_cache
943                    .cache_sent_packet_with_wire(pkt, now, in_band_only, wire);
944            }
945        }
946
947        Some(PacketReceipt {
948            header,
949            seq_no,
950            is_padding,
951            payload_size: body_len,
952            verbatim_resend: false,
953        })
954    }
955
956    /// Sends an in-band resend: the original packet's bytes, unchanged, header extensions
957    /// included.
958    fn poll_packet_resend_inband(
959        &mut self,
960        now: Instant,
961        seq_no: SeqNo,
962        buf: &mut Vec<u8>,
963    ) -> Option<PacketReceipt> {
964        // poll_packet_resend only hands out in-band resends whose bytes were kept.
965        let wire = self.rtx_cache.sent_wire(seq_no)?;
966
967        buf.clear();
968        buf.extend_from_slice(&wire.bytes);
969        let header = wire.header.clone();
970        let payload_size = wire.bytes.len() - header.header_len;
971
972        self.last_used = now;
973
974        Some(PacketReceipt {
975            header,
976            seq_no,
977            is_padding: false,
978            payload_size,
979            verbatim_resend: true,
980        })
981    }
982
983    fn rtx_ratio_downsampled(&mut self, now: Instant) -> f32 {
984        assert!(
985            self.stats.bytes_transmitted.is_some(),
986            "rtx_ratio_cap must be enabled"
987        );
988        assert!(
989            self.stats.bytes_retransmitted.is_some(),
990            "rtx_ratio_cap must be enabled"
991        );
992
993        let (value, ts) = self.rtx_ratio;
994        if now - ts < Duration::from_millis(50) {
995            // not worth re-evaluating, return the old value
996            return value;
997        }
998
999        // bytes stats refer to the last second by default
1000        self.stats
1001            .bytes_transmitted
1002            .as_mut()
1003            .unwrap()
1004            .purge_old(now);
1005        self.stats
1006            .bytes_retransmitted
1007            .as_mut()
1008            .unwrap()
1009            .purge_old(now);
1010
1011        let bytes_transmitted = self.stats.bytes_transmitted.as_mut().unwrap().sum();
1012        let bytes_retransmitted = self.stats.bytes_retransmitted.as_mut().unwrap().sum();
1013        let ratio = bytes_retransmitted as f32 / (bytes_retransmitted + bytes_transmitted) as f32;
1014        let ratio = if ratio.is_finite() { ratio } else { 0_f32 };
1015        self.rtx_ratio = (ratio, now);
1016        ratio
1017    }
1018
1019    fn poll_packet_resend(&mut self, now: Instant) -> Option<NextPacket<'_>> {
1020        if let Some(ratio_cap) = self.rtx_ratio_cap {
1021            let ratio = self.rtx_ratio_downsampled(now);
1022
1023            // If we hit the cap, stop doing resends by clearing those we have queued.
1024            if ratio > ratio_cap {
1025                self.resends.clear();
1026                return None;
1027            }
1028        }
1029
1030        let (seq_no, in_band) = loop {
1031            let resend = self.resends.pop_front()?;
1032
1033            let pkt = self.rtx_cache.get_cached_packet_by_seq_no(resend.seq_no);
1034
1035            // The seq_no could simply be too old to exist in the buffer, in which
1036            // case we will not do a resend.
1037            let Some(pkt) = pkt else {
1038                continue;
1039            };
1040
1041            // Cached packets must be nackable. This is ensured before adding the
1042            // entry to the self.rtx_cache.
1043            assert!(pkt.nackable);
1044
1045            let seq_no = pkt.seq_no;
1046
1047            // A packet whose PT has no RTX PT goes in-band even when the stream has an RTX SSRC.
1048            let in_band = self.rtx.is_none()
1049                || self
1050                    .rtx_cache
1051                    .nack_state_mut(seq_no)
1052                    .is_some_and(|(s, _)| s.in_band);
1053
1054            // An in-band resend repeats the original bytes exactly. Without them, the packet
1055            // is not resent.
1056            if in_band && self.rtx_cache.sent_wire(seq_no).is_none() {
1057                continue;
1058            }
1059
1060            break (seq_no, in_band);
1061        };
1062
1063        // Borrow checker gymnastics.
1064        let pkt = self.rtx_cache.get_cached_packet_by_seq_no(seq_no).unwrap();
1065
1066        let len = pkt.payload.len() as u64;
1067        self.stats.update_packet_counts(len, true);
1068        if let Some(h) = &mut self.stats.bytes_retransmitted {
1069            h.push(now, len);
1070        }
1071
1072        if in_band {
1073            let seq_no = pkt.seq_no;
1074            return Some(NextPacket {
1075                kind: NextPacketKind::ResendInband,
1076                seq_no,
1077                pkt,
1078            });
1079        }
1080
1081        let seq_no = self.seq_no_rtx.inc();
1082
1083        let orig_seq_no = pkt.seq_no;
1084
1085        Some(NextPacket {
1086            kind: NextPacketKind::Resend(orig_seq_no),
1087            seq_no,
1088            pkt,
1089        })
1090    }
1091
1092    fn poll_packet_regular(&mut self, now: Instant) -> Option<NextPacket<'_>> {
1093        // exit via ? here is ok since that means there is nothing to send.
1094        // The packet remains in the head of the send queue until we
1095        // finish poll_packet, at which point we move it to the cache.
1096        let pkt = self.send_queue.peek()?;
1097
1098        let len = pkt.payload.len() as u64;
1099        self.stats.update_packet_counts(len, false);
1100        if let Some(h) = &mut self.stats.bytes_transmitted {
1101            h.push(now, len)
1102        }
1103
1104        let seq_no = pkt.seq_no;
1105
1106        Some(NextPacket {
1107            kind: NextPacketKind::Regular,
1108            seq_no,
1109            pkt,
1110        })
1111    }
1112
1113    fn poll_packet_padding(&mut self, _now: Instant) -> Option<NextPacket> {
1114        if !self.padding_enabled() {
1115            self.padding = 0;
1116            return None;
1117        }
1118
1119        if self.padding == 0 {
1120            return None;
1121        }
1122
1123        #[allow(clippy::unnecessary_operation)]
1124        'outer: {
1125            if !self.ssrc.is_probe() && self.padding > MIN_SPURIOUS_PADDING_SIZE {
1126                // Find a historic packet that is smaller than this max size. The max size
1127                // is a headroom since we can accept slightly larger padding than asked for.
1128                let max_size = (self.padding * 2).min(self.mtu_warn - MAX_RTP_OVERHEAD);
1129
1130                let Some(pkt) = self.rtx_cache.get_cached_packet_smaller_than(max_size) else {
1131                    // Couldn't find spurious packet, try a blank packet instead.
1132                    break 'outer;
1133                };
1134
1135                let orig_seq_no = pkt.seq_no;
1136                let seq_no = self.seq_no_rtx.inc();
1137
1138                self.padding = self.padding.saturating_sub(pkt.payload.len());
1139
1140                return Some(NextPacket {
1141                    kind: NextPacketKind::Resend(orig_seq_no),
1142                    seq_no,
1143                    pkt,
1144                });
1145            }
1146        };
1147
1148        let seq_no = if self.ssrc.is_probe() {
1149            self.seq_no.inc()
1150        } else {
1151            self.seq_no_rtx.inc()
1152        };
1153
1154        let pkt = &mut self.blank_packet;
1155        pkt.seq_no = seq_no;
1156        // Unwrap here is correct because self.padding_enabled() above checks the we got the PT set.
1157        pkt.header.payload_type = self.pt_for_padding.unwrap();
1158
1159        let len = self
1160            .padding
1161            .clamp(SRTP_BLOCK_SIZE, MAX_BLANK_PADDING_PAYLOAD_SIZE);
1162        assert!(len <= 255); // should fit in a byte
1163
1164        let charged_len = if self.ssrc.is_probe() {
1165            len.div_ceil(SRTP_BLOCK_SIZE) * SRTP_BLOCK_SIZE
1166        } else {
1167            len
1168        };
1169        self.padding = self.padding.saturating_sub(charged_len);
1170
1171        Some(NextPacket {
1172            kind: NextPacketKind::Blank(len as u8),
1173            seq_no,
1174            pkt,
1175        })
1176    }
1177
1178    fn is_audio(&self) -> bool {
1179        self.kind.is_some_and(|kind| kind.is_audio())
1180    }
1181
1182    pub(crate) fn sender_report_at(&self, intervals: RtcpReportIntervals) -> Instant {
1183        if self.kind.is_none() {
1184            // First handle_timeout sets the kind. No sender report until then.
1185            return not_happening();
1186        }
1187        self.last_sender_report + intervals.for_audio(self.is_audio())
1188    }
1189
1190    pub(crate) fn poll_keyframe_request(&mut self) -> Option<KeyframeRequestKind> {
1191        self.pending_request_keyframe.take()
1192    }
1193
1194    pub(crate) fn poll_remb_request(&mut self) -> Option<Bitrate> {
1195        self.pending_request_remb.take()
1196    }
1197
1198    pub(crate) fn handle_rtcp(&mut self, now: Instant, fb: RtcpFb) {
1199        use RtcpFb::*;
1200        match fb {
1201            ReceptionReport(r) => {
1202                if let Some(rtx_ssrc) = self.rtx {
1203                    if rtx_ssrc == r.ssrc {
1204                        // Receiver has bound MidRid to RTX SSRC
1205                        self.remote_acked_rtx_ssrc = true;
1206                    }
1207                } else if r.ssrc == self.ssrc {
1208                    // Receiver has bound MidRid to SSRC
1209                    self.remote_acked_ssrc = true;
1210                }
1211
1212                self.stats.update_with_rr(now, self.last_sent_seq_no, r)
1213            }
1214            Nack(_, list) => {
1215                self.stats.increase_nacks();
1216                let entries = list.into_iter();
1217                self.handle_nack(entries, now);
1218            }
1219            Pli(_) => {
1220                self.stats.increase_plis();
1221                self.pending_request_keyframe = Some(KeyframeRequestKind::Pli);
1222            }
1223            Fir(_) => {
1224                self.stats.increase_firs();
1225                self.pending_request_keyframe = Some(KeyframeRequestKind::Fir);
1226            }
1227            Remb(r) => {
1228                self.pending_request_remb = Some(Bitrate::from(r.bitrate as f64));
1229            }
1230            Twcc(_) => unreachable!("TWCC should be handled on session level"),
1231            _ => {}
1232        }
1233    }
1234
1235    pub(crate) fn handle_nack(
1236        &mut self,
1237        entries: impl Iterator<Item = NackEntry>,
1238        now: Instant,
1239    ) -> Option<()> {
1240        // Turning NackEntry into SeqNo we need to know a SeqNo "close by" to lengthen the 16 bit
1241        // sequence number into the 64 bit we have in SeqNo.
1242        let seq_no = self.rtx_cache.last_cached_seq_no()?;
1243        let iter = entries.flat_map(|n| n.into_iter(seq_no));
1244
1245        let rtt = self.stats.rtt();
1246        let hold_of = |p: &NackPolicy| {
1247            let by_rtt = rtt.map(|rtt| rtt * p.rtt_factor);
1248            match by_rtt {
1249                Some(r) => r.min(p.min_interval),
1250                None => p.min_interval,
1251            }
1252        };
1253        let no_rtx = self.rtx.is_none();
1254
1255        // Schedule all resends. They will be handled on next poll_packet
1256        for seq_no in iter {
1257            let Some((state, payload_size)) = self.rtx_cache.nack_state_mut(seq_no) else {
1258                // Packet was not available in RTX cache, it has probably expired.
1259                continue;
1260            };
1261
1262            // Without a policy, a resend in-band (no RTX) still gets the default limits.
1263            let policy = self
1264                .nack_policy
1265                .or_else(|| (no_rtx || state.in_band).then(NackPolicy::default));
1266
1267            if let Some(p) = policy {
1268                let hold = hold_of(&p);
1269                if state.resends >= p.max_resends {
1270                    continue;
1271                }
1272                let check_interval = state.resends > 0 || p.hold_after_send;
1273                if check_interval && now.saturating_duration_since(state.last_at) <= hold {
1274                    continue;
1275                }
1276                if self.resends.len() >= p.max_queued_resends {
1277                    self.stats.increase_resends_dropped();
1278                    continue;
1279                }
1280                state.resends += 1;
1281                state.last_at = now;
1282                if state.resends > 1 {
1283                    self.stats.increase_nacks_repeated();
1284                }
1285            }
1286
1287            let resend = Resend {
1288                seq_no,
1289                queued_at: now,
1290                payload_size,
1291            };
1292            self.resends.push_back(resend);
1293        }
1294
1295        Some(())
1296    }
1297
1298    pub(crate) fn need_sr(&self, now: Instant, intervals: RtcpReportIntervals) -> bool {
1299        now >= self.sender_report_at(intervals)
1300    }
1301
1302    pub(crate) fn create_sr_and_update(&mut self, now: Instant, feedback: &mut VecDeque<Rtcp>) {
1303        let sr = self.create_sender_report(now);
1304
1305        trace!("Created feedback SR: {:?}", sr);
1306        feedback.push_back(Rtcp::SenderReport(sr));
1307
1308        if let Some(ds) = self.create_sdes() {
1309            feedback.push_back(Rtcp::SourceDescription(ds));
1310        }
1311
1312        // Update timestamp to move time when next is created.
1313        self.last_sender_report = now;
1314    }
1315
1316    fn create_sender_report(&self, now: Instant) -> SenderReport {
1317        SenderReport {
1318            sender_info: self.sender_info(now),
1319            reports: ReportList::new(),
1320        }
1321    }
1322
1323    fn create_sdes(&self) -> Option<Descriptions> {
1324        // CNAME is set on first handle_timeout. No SDES before that.
1325        let cname = self.cname.as_ref()?;
1326        let mut s = Sdes {
1327            ssrc: self.ssrc,
1328            values: ReportList::new(),
1329        };
1330        s.values.push((SdesType::CNAME, cname.to_string()));
1331
1332        let mut d = Descriptions {
1333            reports: Box::new(ReportList::new()),
1334        };
1335        d.reports.push(s);
1336
1337        Some(d)
1338    }
1339
1340    fn sender_info(&self, now: Instant) -> SenderInfo {
1341        let rtp_time = self.current_rtp_time(now).unwrap_or(MediaTime::ZERO);
1342
1343        SenderInfo {
1344            ssrc: self.ssrc,
1345            ntp_time: now.to_system_time(),
1346            rtp_time,
1347            sender_packet_count: self.stats.packets as u32,
1348            sender_octet_count: self.stats.bytes as u32,
1349        }
1350    }
1351
1352    fn current_rtp_time(&self, now: Instant) -> Option<MediaTime> {
1353        // This is the RTP time and the wallclock from the last written media.
1354        // We use that as an offset to current time (now), to calculate the
1355        // current RTP time.
1356        let (t_u32, w) = self.rtp_and_wallclock?;
1357
1358        let clock_rate = self.clock_rate?;
1359        let t = MediaTime::new(t_u32 as u64, clock_rate);
1360
1361        // Wallclock needs to be in the past.
1362        if w > now {
1363            let delta = w - now;
1364            debug!("write_rtp wallclock is in the future: {:?}", delta);
1365            return None;
1366        }
1367        let offset = now - w;
1368
1369        // This might be in the wrong base.
1370        let rtp_time = t + offset.into();
1371
1372        Some(rtp_time.rebase(clock_rate))
1373    }
1374
1375    pub(crate) fn next_seq_no(&mut self) -> SeqNo {
1376        self.seq_no.inc()
1377    }
1378
1379    pub(crate) fn last_packet(&self) -> Option<&[u8]> {
1380        if self.send_queue.is_empty() {
1381            self.rtx_cache.last_packet()
1382        } else {
1383            self.send_queue.last().map(|q| q.payload.as_ref())
1384        }
1385    }
1386
1387    pub(crate) fn visit_stats(&mut self, snapshot: &mut StatsSnapshot, now: Instant) {
1388        self.stats.fill(snapshot, self.midrid, now);
1389    }
1390
1391    pub(crate) fn queue_state(&mut self, now: Instant) -> QueueState {
1392        // The unpaced flag is set to a default value on first handle_timeout. The
1393        // default is to not pace audio. We unwrap default to "true" here to not
1394        // apply any pacing until we know what kind of content we are sending.
1395        let unpaced = self.unpaced.unwrap_or(true);
1396
1397        // Padding needs a known PT and either RTX or the non-media probe SSRC.
1398        let use_for_padding = self.padding_enabled();
1399
1400        let mut snapshot = self.send_queue.snapshot(now);
1401
1402        if let Some(snapshot_resend) = self.queue_state_resend(now) {
1403            snapshot.merge(&snapshot_resend);
1404        }
1405
1406        if let Some(snapshot_padding) = self.queue_state_padding(now) {
1407            snapshot.merge(&snapshot_padding);
1408        }
1409
1410        self.queue_info = Some(snapshot);
1411
1412        QueueState {
1413            midrid: self.midrid,
1414            unpaced,
1415            use_for_padding,
1416            snapshot,
1417        }
1418    }
1419
1420    fn queue_state_resend(&self, now: Instant) -> Option<QueueSnapshot> {
1421        if self.resends.is_empty() {
1422            return None;
1423        }
1424
1425        // Outstanding resends
1426        let mut snapshot = self
1427            .resends
1428            .iter()
1429            .fold(QueueSnapshot::default(), |mut snapshot, r| {
1430                snapshot.total_queue_time_origin += now.duration_since(r.queued_at);
1431                snapshot.byte_size += r.payload_size;
1432                snapshot.packet_count += 1;
1433                snapshot.first_unsent = snapshot
1434                    .first_unsent
1435                    .map(|i| i.min(r.queued_at))
1436                    .or(Some(r.queued_at));
1437
1438                snapshot
1439            });
1440        snapshot.created_at = now;
1441        snapshot.update_priority(QueuePriority::Media);
1442
1443        Some(snapshot)
1444    }
1445
1446    fn queue_state_padding(&self, now: Instant) -> Option<QueueSnapshot> {
1447        if self.padding == 0 {
1448            return None;
1449        }
1450
1451        if self.ssrc.is_probe() {
1452            return Some(QueueSnapshot {
1453                created_at: now,
1454                byte_size: self.padding,
1455                packet_count: self.padding.div_ceil(MAX_BLANK_PADDING_PAYLOAD_SIZE) as u32,
1456                first_unsent: Some(now),
1457                last_emitted: (self.last_used != already_happened()).then_some(self.last_used),
1458                priority: QueuePriority::Padding,
1459                ..Default::default()
1460            });
1461        }
1462
1463        // TODO: Be more scientific about these factors.
1464        const AVERAGE_PADDING_PACKET_SIZE: usize = 800;
1465        const FAKE_PADDING_DURATION_MILLIS: usize = 5;
1466
1467        let fake_packets = self.padding.div_ceil(AVERAGE_PADDING_PACKET_SIZE);
1468        let fake_millis = fake_packets * FAKE_PADDING_DURATION_MILLIS;
1469        let fake_duration = Duration::from_millis(fake_millis as u64);
1470
1471        Some(QueueSnapshot {
1472            created_at: now,
1473            byte_size: self.padding,
1474            packet_count: fake_packets as u32,
1475            total_queue_time_origin: fake_duration,
1476            priority: QueuePriority::Padding,
1477            ..Default::default()
1478        })
1479    }
1480
1481    pub(crate) fn padding_pt(&self) -> Option<Pt> {
1482        self.pt_for_padding
1483    }
1484
1485    pub(crate) fn generate_padding(&mut self, padding: usize) {
1486        if !self.padding_enabled() {
1487            return;
1488        }
1489        self.padding += padding;
1490    }
1491
1492    pub(crate) fn need_timeout(&self) -> bool {
1493        self.send_queue.need_timeout()
1494    }
1495
1496    pub(crate) fn handle_timeout<'a>(
1497        &mut self,
1498        now: Instant,
1499        get_media: impl FnOnce() -> (&'a Media, &'a CodecConfig),
1500    ) {
1501        // If kind is None, this is the first time we ever get a handle_timeout.
1502        if self.kind.is_none() {
1503            let (media, config) = get_media();
1504            self.on_first_timeout(media, config);
1505        }
1506
1507        self.send_queue.handle_timeout(now);
1508    }
1509
1510    fn on_first_timeout(&mut self, media: &Media, config: &CodecConfig) {
1511        // Always set on first timeout.
1512        self.kind = Some(media.kind());
1513        self.cname = Some(media.cname().to_string());
1514
1515        // Set on first timeout, if not set already by configuration.
1516        if self.unpaced.is_none() {
1517            // Default audio to be unpaced.
1518            self.unpaced = Some(media.kind().is_audio());
1519        }
1520
1521        // To allow for sending padding on a newly created StreamTx, before any regular
1522        // packet has been sent, we need any main PT that has associated RTX. This is
1523        // later be overwritten when we send the first regular packet.
1524        if self.rtx.is_some() && self.pt_for_padding.is_none() {
1525            if let Some(pt) = media.first_pt_with_rtx(config) {
1526                trace!(
1527                    "StreamTx {:?} PT {} before first regular packet",
1528                    self.midrid, pt
1529                );
1530                self.pt_for_padding = Some(pt);
1531
1532                // Setting the pt_for_rtx should enable RTX.
1533                assert!(self.padding_enabled());
1534            }
1535        }
1536    }
1537
1538    /// Stops this stream from being used for padding until it sends a regular packet
1539    /// again (which picks the padding PT anew).
1540    pub(crate) fn stop_padding(&mut self) {
1541        self.pt_for_padding = None;
1542        self.padding = 0;
1543    }
1544
1545    pub(crate) fn reset_buffers(&mut self) {
1546        self.send_queue.clear();
1547        self.queue_info = None;
1548        self.rtx_cache.clear();
1549        self.resends.clear();
1550        self.padding = 0;
1551    }
1552
1553    /// Reset this stream to use a new SSRC and optionally a new RTX SSRC.
1554    ///
1555    /// This updates the SSRCs and resets all relevant internal fields.
1556    pub(crate) fn reset_ssrc(&mut self, new_ssrc: Ssrc, new_rtx: Option<Ssrc>) {
1557        // Update the SSRC and RTX
1558        self.ssrc = new_ssrc;
1559        self.rtx = new_rtx;
1560
1561        // Reset sequence numbers
1562        self.seq_no = SeqNo::default();
1563        self.seq_no_rtx = SeqNo::default();
1564
1565        // Reset timing related fields
1566        self.last_used = already_happened();
1567        self.rtp_and_wallclock = None;
1568        self.last_sender_report = already_happened();
1569
1570        // Reset blank packet's SSRC
1571        self.blank_packet.header.ssrc = new_ssrc;
1572
1573        // Clear any pending requests
1574        self.pending_request_keyframe = None;
1575        self.pending_request_remb = None;
1576
1577        // Reset all statistics - preserve whether stats tracking is enabled
1578        let stats_enabled = self.stats.bytes_transmitted.is_some();
1579        self.stats = StreamTxStats::new(stats_enabled);
1580        self.rtx_ratio = (0.0, already_happened());
1581        self.remote_acked_ssrc = false;
1582
1583        // Clear all buffers
1584        self.reset_buffers();
1585    }
1586
1587    pub(crate) fn is_midrid(&self, midrid: MidRid) -> bool {
1588        midrid.special_equals(&self.midrid)
1589    }
1590}
1591
1592struct NextPacket<'a> {
1593    kind: NextPacketKind,
1594    seq_no: SeqNo,
1595    pkt: &'a mut RtpPacket,
1596}
1597
1598#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1599enum NextPacketKind {
1600    Regular,
1601    Resend(SeqNo),
1602    ResendInband,
1603    Blank(u8),
1604}
1605
1606#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1607struct Resend {
1608    seq_no: SeqNo,
1609    queued_at: Instant,
1610    payload_size: usize,
1611}
1612
1613#[cfg(test)]
1614mod test {
1615    use super::*;
1616
1617    fn nack_policy_stream(now: Instant) -> StreamTx {
1618        let mut stream = StreamTx::new(
1619            42.into(),
1620            Some(44.into()),
1621            MidRid(Mid::from("0"), None),
1622            false,
1623            1200,
1624        );
1625        for seq in 1..=10_u64 {
1626            let pkt = RtpPacket {
1627                header: RtpHeader::default(),
1628                seq_no: seq.into(),
1629                time: MediaTime::from_90khz(seq * 3000),
1630                payload: vec![seq as u8; 100].into(),
1631                vp8_patch: None,
1632                timestamp: now,
1633                last_sender_info: None,
1634                nackable: true,
1635            };
1636            stream.rtx_cache.cache_sent_packet(pkt, now, false);
1637        }
1638        stream
1639    }
1640
1641    fn nack(stream: &mut StreamTx, seqs: &[u16], now: Instant) -> usize {
1642        let before = stream.resends.len();
1643        let entries: Vec<NackEntry> = seqs.iter().map(|s| NackEntry { pid: *s, blp: 0 }).collect();
1644        stream.handle_nack(entries.into_iter(), now);
1645        let queued = stream.resends.len() - before;
1646        stream.resends.clear();
1647        queued
1648    }
1649
1650    fn bounded_policy() -> NackPolicy {
1651        NackPolicy::new(Duration::from_millis(100), 2, 3, true, 1000)
1652    }
1653
1654    #[test]
1655    fn in_band_packet_on_rtx_stream_resends_in_band_and_is_never_padding() {
1656        let now = Instant::now();
1657        let mut stream = StreamTx::new(
1658            42.into(),
1659            Some(44.into()),
1660            MidRid(Mid::from("0"), None),
1661            false,
1662            1200,
1663        );
1664        let pkt = RtpPacket {
1665            header: RtpHeader::default(),
1666            seq_no: 7.into(),
1667            time: MediaTime::from_90khz(0),
1668            payload: vec![7; 200].into(),
1669            vp8_patch: None,
1670            timestamp: now,
1671            last_sender_info: None,
1672            nackable: true,
1673        };
1674        let wire = SentWire {
1675            bytes: vec![7; 212].into(),
1676            header: RtpHeader {
1677                header_len: 12,
1678                ..RtpHeader::default()
1679            },
1680        };
1681        stream
1682            .rtx_cache
1683            .cache_sent_packet_with_wire(pkt, now, true, Some(wire));
1684        assert!(
1685            stream
1686                .rtx_cache
1687                .get_cached_packet_smaller_than(1000)
1688                .is_none()
1689        );
1690        // After the default hold-off that bounds in-band resends.
1691        let later = now + Duration::from_millis(200);
1692        let entries = vec![NackEntry { pid: 7, blp: 0 }];
1693        stream.handle_nack(entries.into_iter(), later);
1694        let next = stream.poll_packet_resend(later).expect("a resend");
1695        assert!(matches!(next.kind, NextPacketKind::ResendInband));
1696        assert_eq!(*next.seq_no, 7);
1697    }
1698
1699    #[test]
1700    fn in_band_packet_without_its_sent_bytes_is_not_resent() {
1701        let now = Instant::now();
1702        let mut stream = StreamTx::new(42.into(), None, MidRid(Mid::from("0"), None), false, 1200);
1703        let pkt = RtpPacket {
1704            header: RtpHeader::default(),
1705            seq_no: 7.into(),
1706            time: MediaTime::from_90khz(0),
1707            payload: vec![7; 200].into(),
1708            vp8_patch: None,
1709            timestamp: now,
1710            last_sender_info: None,
1711            nackable: true,
1712        };
1713        stream.rtx_cache.cache_sent_packet(pkt, now, false);
1714        let later = now + Duration::from_millis(200);
1715        let entries = vec![NackEntry { pid: 7, blp: 0 }];
1716        stream.handle_nack(entries.into_iter(), later);
1717        assert_eq!(stream.resends.len(), 1, "the NACK is accepted");
1718        assert!(stream.poll_packet_resend(later).is_none());
1719    }
1720
1721    #[test]
1722    fn in_band_resends_without_a_policy_get_the_default_bound() {
1723        let now = Instant::now();
1724        let ms = |n: u64| now + Duration::from_millis(n);
1725        let mut stream = StreamTx::new(42.into(), None, MidRid(Mid::from("0"), None), false, 1200);
1726        for seq in 1..=4_u64 {
1727            let pkt = RtpPacket {
1728                header: RtpHeader::default(),
1729                seq_no: seq.into(),
1730                time: MediaTime::from_90khz(seq * 3000),
1731                payload: vec![seq as u8; 100].into(),
1732                vp8_patch: None,
1733                timestamp: now,
1734                last_sender_info: None,
1735                nackable: true,
1736            };
1737            stream.rtx_cache.cache_sent_packet(pkt, now, false);
1738        }
1739        assert_eq!(stream.nack_policy, None);
1740        let d = NackPolicy::default();
1741        assert_eq!(
1742            d,
1743            NackPolicy::new(Duration::from_millis(100), 2, 3, true, 1000)
1744        );
1745        assert_eq!(
1746            NackPolicy::default()
1747                .with_min_interval(Duration::from_millis(50))
1748                .with_rtt_factor(4)
1749                .with_max_resends(1)
1750                .with_hold_after_send(false)
1751                .with_max_queued_resends(10),
1752            NackPolicy::new(Duration::from_millis(50), 4, 1, false, 10)
1753        );
1754
1755        // Within 100 ms of the send: held.
1756        assert_eq!(nack(&mut stream, &[3], ms(50)), 0);
1757        assert_eq!(nack(&mut stream, &[3], ms(200)), 1);
1758        assert_eq!(nack(&mut stream, &[3], ms(250)), 0);
1759        assert_eq!(nack(&mut stream, &[3], ms(400)), 1);
1760        assert_eq!(nack(&mut stream, &[3], ms(600)), 1);
1761        // 3 resends per packet: never again.
1762        assert_eq!(nack(&mut stream, &[3], ms(800)), 0);
1763        assert_eq!(nack(&mut stream, &[3], ms(2000)), 0);
1764        // An explicit policy replaces the default.
1765        let p = NackPolicy {
1766            max_resends: 5,
1767            ..NackPolicy::default()
1768        };
1769        stream.set_nack_policy(Some(p));
1770        assert_eq!(nack(&mut stream, &[3], ms(2200)), 1);
1771    }
1772
1773    #[test]
1774    fn stopped_stream_is_not_used_for_padding() {
1775        let mut streams = crate::streams::Streams::new(false, 1200, Duration::from_millis(1500));
1776        let mid = Mid::from("vid");
1777        let stream = streams.declare_stream_tx(42.into(), Some(44.into()), MidRid(mid, None));
1778        stream.pt_for_padding = Some(96.into());
1779        let now = Instant::now();
1780        assert!(
1781            streams
1782                .send_queue_states(now, |_, _| true)
1783                .any(|q| q.use_for_padding)
1784        );
1785        streams.reset_buffers_tx(mid);
1786        assert!(
1787            !streams
1788                .send_queue_states(now, |_, _| true)
1789                .any(|q| q.use_for_padding)
1790        );
1791    }
1792
1793    #[test]
1794    fn nack_without_policy_resends_every_time() {
1795        let now = Instant::now();
1796        let mut stream = nack_policy_stream(now);
1797        for _ in 0..5 {
1798            assert_eq!(nack(&mut stream, &[3, 4], now), 2);
1799        }
1800        assert_eq!(stream.stats.nack_policy_counts(), (0, 0));
1801    }
1802
1803    #[test]
1804    fn nack_policy_holds_repeats_and_caps_resends() {
1805        let now = Instant::now();
1806        let ms = |n: u64| now + Duration::from_millis(n);
1807        let mut stream = nack_policy_stream(now);
1808        stream.set_nack_policy(Some(bounded_policy()));
1809
1810        // Within 100 ms of the send: held (hold_after_send).
1811        assert_eq!(nack(&mut stream, &[3, 4], ms(50)), 0);
1812        // After the hold-off: answered.
1813        assert_eq!(nack(&mut stream, &[3, 4], ms(110)), 2);
1814        // A repeat right away: held.
1815        assert_eq!(nack(&mut stream, &[3, 4], ms(150)), 0);
1816        // Second and third resend.
1817        assert_eq!(nack(&mut stream, &[3, 4], ms(220)), 2);
1818        assert_eq!(nack(&mut stream, &[3, 4], ms(330)), 2);
1819        // max_resends = 3: never again.
1820        assert_eq!(nack(&mut stream, &[3, 4], ms(1000)), 0);
1821        // Resends 2 and 3 of two packets are "repeated".
1822        assert_eq!(stream.stats.nack_policy_counts(), (4, 0));
1823        // Other packets are unaffected; unknown SNs are ignored.
1824        assert_eq!(nack(&mut stream, &[5, 400], ms(1000)), 1);
1825    }
1826
1827    #[test]
1828    fn nack_policy_without_hold_after_send_answers_first_nack_at_once() {
1829        let now = Instant::now();
1830        let mut stream = nack_policy_stream(now);
1831        stream.set_nack_policy(Some(NackPolicy {
1832            hold_after_send: false,
1833            ..bounded_policy()
1834        }));
1835        assert_eq!(nack(&mut stream, &[3], now), 1);
1836        assert_eq!(nack(&mut stream, &[3], now + Duration::from_millis(50)), 0);
1837    }
1838
1839    #[test]
1840    fn nack_policy_interval_bounded_by_rtt() {
1841        let now = Instant::now();
1842        let ms = |n: u64| now + Duration::from_millis(n);
1843        let mut stream = nack_policy_stream(now);
1844        stream.set_nack_policy(Some(bounded_policy()));
1845        // RTT 20 ms: hold-off is min(100, 2 × 20) = 40 ms.
1846        stream
1847            .stats
1848            .set_rtt_for_test(Some(Duration::from_millis(20)));
1849        assert_eq!(nack(&mut stream, &[3], ms(30)), 0);
1850        assert_eq!(nack(&mut stream, &[3], ms(50)), 1);
1851        assert_eq!(nack(&mut stream, &[3], ms(80)), 0);
1852        assert_eq!(nack(&mut stream, &[3], ms(95)), 1);
1853        // RTT 200 ms: the 100 ms minimum interval wins.
1854        stream
1855            .stats
1856            .set_rtt_for_test(Some(Duration::from_millis(200)));
1857        assert_eq!(nack(&mut stream, &[4], ms(150)), 1);
1858        assert_eq!(nack(&mut stream, &[4], ms(240)), 0);
1859        assert_eq!(nack(&mut stream, &[4], ms(260)), 1);
1860    }
1861
1862    #[test]
1863    fn nack_policy_bounds_the_resend_queue() {
1864        let now = Instant::now();
1865        let mut stream = nack_policy_stream(now);
1866        stream.set_nack_policy(Some(NackPolicy {
1867            max_queued_resends: 3,
1868            ..bounded_policy()
1869        }));
1870        let t = now + Duration::from_millis(200);
1871        let entries: Vec<NackEntry> = (1..=8).map(|s| NackEntry { pid: s, blp: 0 }).collect();
1872        stream.handle_nack(entries.into_iter(), t);
1873        assert_eq!(stream.resends.len(), 3);
1874        assert_eq!(stream.stats.nack_policy_counts(), (0, 5));
1875        // Dropped packets were not counted as resent: once the queue drains they are answered.
1876        stream.resends.clear();
1877        assert_eq!(nack(&mut stream, &[8], t), 1);
1878    }
1879
1880    #[test]
1881    fn reset_buffers_forgets_nack_state() {
1882        let now = Instant::now();
1883        let mut stream = nack_policy_stream(now);
1884        stream.set_nack_policy(Some(bounded_policy()));
1885        stream.reset_buffers();
1886        assert_eq!(nack(&mut stream, &[3], now + Duration::from_millis(500)), 0);
1887    }
1888
1889    #[test]
1890    fn regular_padding_does_not_search_probe_negotiation() {
1891        let mut streams = crate::streams::Streams::new(false, 1200, Duration::from_millis(1500));
1892        let stream =
1893            streams.declare_stream_tx(42.into(), Some(44.into()), MidRid("vid".into(), None));
1894        stream.pt_for_padding = Some(96.into());
1895        let queues: Vec<_> = streams
1896            .send_queue_states(Instant::now(), |_, _| {
1897                panic!("ordinary padding must not check probe negotiation")
1898            })
1899            .collect();
1900        assert_eq!(queues.len(), 1);
1901        assert!(queues[0].use_for_padding);
1902    }
1903
1904    #[test]
1905    fn probe_absolute_send_time_follows_negotiated_extensions() {
1906        let now = Instant::now();
1907        let codecs = CodecConfig::new_with_defaults();
1908        for negotiated in [false, true] {
1909            let mut exts = ExtensionMap::empty();
1910            exts.set(1, Extension::RtpMid);
1911            exts.set(3, Extension::TransportSequenceNumber);
1912            if negotiated {
1913                exts.set(2, Extension::AbsoluteSendTime);
1914            }
1915            let mut stream = StreamTx::new_probe(1200);
1916            stream.set_probe_media("aud".into(), 111.into());
1917            stream.generate_padding(240);
1918            let mut twcc = 42;
1919            let mut buf = vec![];
1920            let receipt = stream
1921                .poll_packet(now, &exts, Some(&mut twcc), codecs.params(), &mut buf)
1922                .unwrap();
1923            assert_eq!(
1924                receipt.header.ext_vals.abs_send_time,
1925                negotiated.then_some(now)
1926            );
1927            let header = RtpHeader::parse(&buf, &exts).unwrap();
1928            assert_eq!(header.ext_vals.abs_send_time.is_some(), negotiated);
1929            assert_eq!(header.ext_vals.transport_cc, Some(42));
1930            assert!(header.ssrc.is_probe());
1931            assert!(header.has_padding);
1932        }
1933    }
1934
1935    #[test]
1936    fn queue_time_counts_only_unsent_packets_while_the_queue_never_empties() {
1937        let start = Instant::now();
1938        let codecs = CodecConfig::new_with_defaults();
1939        let pt = codecs.params()[0].pt();
1940        let exts = ExtensionMap::standard();
1941        let mut streams = crate::streams::Streams::new(false, 1200, Duration::from_millis(1500));
1942        let stream = streams.declare_stream_tx(42.into(), None, MidRid("vid".into(), None));
1943        let mut buf = vec![];
1944        let mut now = start;
1945        for i in 0..205_u64 {
1946            now = start + Duration::from_millis(i * 10);
1947            stream.write_rtp(RtpWrite::new(pt, i.into(), 0, now, vec![0_u8; 1000]));
1948            stream.send_queue.handle_timeout(now);
1949            if i >= 5 {
1950                stream
1951                    .poll_packet(now, &exts, None, codecs.params(), &mut buf)
1952                    .expect("a queued packet to send");
1953            }
1954        }
1955        let snapshot = stream.queue_state(now).snapshot;
1956        // The five queued packets are 0, 10, 20, 30 and 40 ms old.
1957        assert_eq!(snapshot.packet_count, 5);
1958        assert_eq!(snapshot.total_queue_time(now), Duration::from_millis(100));
1959    }
1960
1961    #[test]
1962    fn padding_accounting_and_sequence_rollover() {
1963        let now = Instant::now();
1964        let mut sender = StreamTx::new_probe(1200);
1965        sender.set_probe_media("aud".into(), 111.into());
1966        sender.seq_no = 65_535.into();
1967        let codecs = CodecConfig::new_with_defaults();
1968        let mut twcc = 131_071;
1969        let mut buf = vec![];
1970        let exts = ExtensionMap::standard();
1971        sender.generate_padding(241);
1972        let first = sender
1973            .poll_packet(now, &exts, Some(&mut twcc), codecs.params(), &mut buf)
1974            .unwrap();
1975        assert_eq!(first.payload_size, 240);
1976        assert!(first.header.has_padding);
1977        assert_eq!(first.header.ext_vals.abs_send_time, Some(now));
1978        assert_eq!(*first.seq_no, 65_535);
1979        let second = sender
1980            .poll_packet(now, &exts, Some(&mut twcc), codecs.params(), &mut buf)
1981            .unwrap();
1982        assert_eq!(*second.seq_no, 65_536);
1983        assert_eq!(second.header.sequence_number, 0);
1984        assert_eq!(second.header.ext_vals.transport_cc, Some(0));
1985        assert_eq!(second.payload_size, SRTP_BLOCK_SIZE);
1986        assert_eq!(buf.len(), second.header.header_len + second.payload_size);
1987        assert!(
1988            RtpHeader::unpad_payload(&buf[second.header.header_len..])
1989                .unwrap()
1990                .is_empty()
1991        );
1992        assert_eq!(sender.queue_state(now).snapshot.packet_count, 0);
1993        assert_eq!(twcc, 131_073);
1994    }
1995
1996    #[test]
1997    fn probe_stream_rebinding_preserves_srtp_sequence_and_discards_pending_padding() {
1998        use crate::media::MID_PROBE;
1999        use crate::rtp_::MidRid;
2000        use crate::streams::Streams;
2001
2002        let now = Instant::now();
2003        let mut streams = Streams::new(false, 1200, Duration::from_millis(1500));
2004        let queue = MidRid(MID_PROBE, None);
2005        let mut twcc = 0;
2006        let mut buf = vec![];
2007        let exts = ExtensionMap::standard();
2008        let codecs = CodecConfig::new_with_defaults();
2009        streams.set_probe_media(Some(("aud".into(), 111.into())));
2010        let stream = streams.stream_tx_by_midrid(queue).unwrap();
2011        stream.generate_padding(480);
2012        let first = stream
2013            .poll_packet(now, &exts, Some(&mut twcc), codecs.params(), &mut buf)
2014            .unwrap();
2015        assert_eq!(first.header.ext_vals.mid, Some("aud".into()));
2016
2017        // Ending a cluster must drop any unsent padding and remove its source
2018        // from selection, without resetting the SRTP index for the next cluster.
2019        streams.set_probe_media(None);
2020        assert!(streams.stream_tx_by_midrid(queue).is_none());
2021        assert_eq!(streams.send_queue_states(now, |_, _| true).count(), 0);
2022        streams.set_probe_media(Some(("vid".into(), 96.into())));
2023        assert_eq!(streams.streams_tx().count(), 0);
2024        let stream = streams.stream_tx_by_midrid(queue).unwrap();
2025        assert!(
2026            stream
2027                .poll_packet(now, &exts, Some(&mut twcc), codecs.params(), &mut buf)
2028                .is_none()
2029        );
2030        stream.generate_padding(240);
2031        let second = stream
2032            .poll_packet(now, &exts, Some(&mut twcc), codecs.params(), &mut buf)
2033            .unwrap();
2034        assert_eq!(*second.seq_no, *first.seq_no + 1);
2035        assert_eq!(second.header.ext_vals.transport_cc, Some(1));
2036        assert_eq!(second.header.ext_vals.mid, Some("vid".into()));
2037        assert_eq!(second.header.payload_type, 96.into());
2038    }
2039
2040    #[test]
2041    fn queue_info_is_cached_on_queue_state_update() {
2042        let mut stream = StreamTx::new(42.into(), None, MidRid(Mid::from("0"), None), false, 1200);
2043
2044        assert!(stream.queue_info().is_none());
2045
2046        let now = Instant::now();
2047        let first_unsent = now - Duration::from_millis(10);
2048        stream.resends.push_back(Resend {
2049            seq_no: 7.into(),
2050            queued_at: first_unsent,
2051            payload_size: 123,
2052        });
2053        stream.queue_state(now);
2054
2055        let info = stream.queue_info().expect("queue info after pacer update");
2056        assert_eq!(info.created_at(), now);
2057        assert_eq!(info.byte_size(), 123);
2058        assert_eq!(info.packet_count(), 1);
2059        assert_eq!(info.first_unsent(), Some(first_unsent));
2060
2061        stream.reset_buffers();
2062        assert!(stream.queue_info().is_none());
2063    }
2064
2065    #[test]
2066    fn sub_average_padding_is_visible_to_the_pacer() {
2067        let mut stream = StreamTx::new(42.into(), None, MidRid(Mid::from("0"), None), false, 1200);
2068        stream.padding = 240;
2069
2070        let snapshot = stream
2071            .queue_state_padding(Instant::now())
2072            .expect("nonzero padding must produce a queue snapshot");
2073
2074        assert_eq!(snapshot.byte_size, 240);
2075        assert_eq!(snapshot.packet_count, 1);
2076    }
2077
2078    #[test]
2079    fn sender_report_uses_supplied_intervals() {
2080        let mut stream = StreamTx::new(42.into(), None, MidRid(Mid::from("0"), None), false, 1200);
2081        let now = Instant::now();
2082        stream.kind = Some(MediaKind::Audio);
2083        stream.last_sender_report = now;
2084
2085        assert_eq!(
2086            stream.sender_report_at(RtcpReportIntervals {
2087                audio: Duration::from_millis(750),
2088                video: Duration::from_millis(500),
2089            }),
2090            now + Duration::from_millis(750)
2091        );
2092    }
2093}