Skip to main content

rtci_interceptor/pause_resume/
mod.rs

1//! RTP stream pause and resume (RFC 7728).
2//!
3//! [`PauseResumeInterceptor`] runs both roles of the PAUSE-RESUME message
4//! ([`rtcp::transport_feedbacks::pause_resume`]) for the streams that negotiated
5//! `a=rtcp-fb:<pt> ccm pause` (section 9):
6//!
7//! - as RTP stream **sender** it keeps the state machine of section 6 per local SSRC (playing,
8//!   pausing, paused, local paused) and the current PauseID: a PAUSE with the current PauseID
9//!   starts the hold-off period (section 6.2; none when `nowait` was negotiated), after which
10//!   the stream is paused and a PAUSED indication is sent at once and with the next two
11//!   reports (section 6.3); a RESUME with the current PauseID plays it again with the next
12//!   PauseID (section 6.1); a request it cannot honour, or one with a PauseID that is not
13//!   current, is answered with REFUSED (section 8.4), one REFUSED per PauseID and compound
14//!   packet. While paused, the RTP the application still writes is not sent, and the stream
15//!   goes on afterwards with the sequence number after the last one sent (section 6.1). The
16//!   requester's BYE or time-out resumes the stream (sections 6.3.1, 6.3.2).
17//! - as RTP stream **receiver** it sends the PAUSE and RESUME the application asks for through
18//!   [`PauseResumeHandle`], with the current PauseID it learned from PAUSED, REFUSED and its
19//!   own requests (section 8.1), retransmits them after `2 * RTT + T_dither_max` (sections
20//!   8.1, 8.3) and refrains for a while after a REFUSED for its own PauseID.
21//!
22//! The messages a peer did not declare it can receive (its `config`, section 9) are not sent
23//! to it. Every PAUSE-RESUME message read is also delivered to the application.
24
25#[cfg(test)]
26mod pause_resume_test;
27
28use crate::rtcp_session::{RepeatInRegularReports, RtcpSessionControl, RtcpSessionEvent};
29use crate::stream_info::StreamInfo;
30use crate::{Attribute, AttributedPacket, Interceptor, Packet, TaggedPacket};
31use rtcp::goodbye::Goodbye;
32use rtcp::receiver_report::ReceiverReport;
33use rtcp::reception_report::ReceptionReport;
34use rtcp::sender_report::SenderReport;
35use rtcp::transport_feedbacks::pause_resume::{PauseResume, PauseResumeEntry, PauseResumeType};
36use sansio::Protocol;
37use shared::TransportContext;
38use shared::error::Error;
39use std::collections::{HashMap, HashSet, VecDeque};
40use std::sync::{Arc, Mutex, MutexGuard};
41use std::time::{Duration, Instant};
42
43/// The `ccm` parameter of `a=rtcp-fb` that negotiates the messages (RFC 7728 section 9).
44pub const RTCP_FB_CCM_PAUSE: &str = "pause";
45
46/// The round trip a sender or receiver assumes while it knows none (RFC 7728 section 8.1:
47/// "RTP stream receivers that lack an RTT estimate to the sender SHOULD use 500 ms as the
48/// default value").
49pub const PAUSE_DEFAULT_ROUND_TRIP_TIME: Duration = Duration::from_millis(500);
50
51/// How often PAUSED is repeated after the first one: "PAUSED MUST also be included in (at
52/// least) the next two regular RTCP reports" (section 8.2).
53pub const PAUSED_REPETITIONS: u8 = 2;
54
55/// The fewest times a local-pause PAUSED is repeated after the first one (RFC 7728 section
56/// 6.4: "a sufficient number of times to reach a high probability that the message is
57/// correctly delivered"); more when the receivers report loss
58/// ([`local_pause_repetitions`]).
59pub const LOCAL_PAUSED_MIN_REPETITIONS: u8 = PAUSED_REPETITIONS + 1;
60
61/// The most times a local-pause PAUSED is repeated after the first one, whatever the loss.
62pub const LOCAL_PAUSED_MAX_REPETITIONS: u8 = 10;
63
64/// The probability that every copy of a local-pause PAUSED is lost, which the repetitions
65/// are chosen to stay under (section 6.4's "high probability" of delivery: 99.9 %).
66pub const LOCAL_PAUSED_LOSS_TARGET: f64 = 1e-3;
67
68/// How many times a local-pause PAUSED is repeated after the first one when the receivers
69/// report `fraction_lost` (the RFC 3550 report block's fraction, out of 256) on the stream:
70/// the fewest repetitions `n` for which all `n + 1` copies are lost with a probability of at
71/// most [`LOCAL_PAUSED_LOSS_TARGET`], between [`LOCAL_PAUSED_MIN_REPETITIONS`] and
72/// [`LOCAL_PAUSED_MAX_REPETITIONS`] (RFC 7728 section 6.4).
73pub fn local_pause_repetitions(fraction_lost: u8) -> u8 {
74    let loss = f64::from(fraction_lost) / 256.0;
75    let mut repetitions = LOCAL_PAUSED_MIN_REPETITIONS;
76    while repetitions < LOCAL_PAUSED_MAX_REPETITIONS
77        && loss.powi(i32::from(repetitions) + 1) > LOCAL_PAUSED_LOSS_TARGET
78    {
79        repetitions += 1;
80    }
81    repetitions
82}
83
84/// The interval at which PAUSED is repeated and after which a participant that sent nothing
85/// for five of them has timed out (RFC 3550 section 6.3.5), unless the builder says otherwise:
86/// the RTCP report interval of a session at the minimum RTCP rate (RFC 3550 section 6.2).
87pub const PAUSE_DEFAULT_REPORT_INTERVAL: Duration = Duration::from_secs(5);
88
89/// The `config` values of RFC 7728 section 9 (Figure 7): what an endpoint sends and receives.
90/// `1` is the full implementation, the default when the attribute is left out.
91fn supports(config: u8, sending: bool, typ: PauseResumeType) -> bool {
92    use PauseResumeType::*;
93    // (send PAUSE, RESUME, PAUSED, REFUSED), (receive PAUSE, RESUME, PAUSED, REFUSED).
94    let (send, receive): ([bool; 4], [bool; 4]) = match config {
95        1 => ([true; 4], [true; 4]),
96        2 => ([true, true, true, false], [false, false, true, true]),
97        3 => ([false, false, true, true], [true, true, true, false]),
98        4 => ([true, true, false, false], [false, false, true, true]),
99        5 => ([false, false, true, true], [true, true, false, false]),
100        6 => ([false, false, true, false], [false, false, true, false]),
101        7 => ([false; 4], [false, false, true, false]),
102        8 => ([false, false, true, false], [false; 4]),
103        _ => ([false; 4], [false; 4]),
104    };
105    let row = if sending { send } else { receive };
106    match typ {
107        Pause => row[0],
108        Resume => row[1],
109        Paused => row[2],
110        Refused => row[3],
111        Reserved(_) => false,
112    }
113}
114
115/// The `config` an answerer that implements everything answers to an offered one (RFC 7728
116/// section 9.1, Figure 9): the complementary subset, so that what one side sends the other
117/// receives. `None` for a value the section does not define: "MUST remove the "pause" CCM
118/// line in the answer when receiving an offer with a "config" value it does not understand".
119/// The mapping is its own inverse, so it also gives the peer's `config` from this endpoint's.
120pub fn pause_config_answer(offered: u8) -> Option<u8> {
121    Some(match offered {
122        1 => 1,
123        2 => 3,
124        3 => 2,
125        4 => 5,
126        5 => 4,
127        6 => 6,
128        7 => 8,
129        8 => 7,
130        _ => return None,
131    })
132}
133
134/// What a negotiated `ccm pause` line says (RFC 7728 section 9, Figure 8): `pause`, then
135/// `nowait` and `config=<n>` in any order; unknown attributes are ignored ("Unknown pause
136/// attributes MUST be ignored").
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub struct PauseCapability {
139    /// `nowait`: the hold-off period is 0.
140    pub nowait: bool,
141    /// `config`, 1 when left out.
142    pub config: u8,
143}
144
145impl PauseCapability {
146    /// Parses the parameter of a `ccm` feedback line (`pause nowait config=3`); `None` when it
147    /// is not `pause`, or names `config` or `nowait` more than once ("MUST NOT appear more
148    /// than once"), or `config` is not a number.
149    pub fn parse(parameter: &str) -> Option<Self> {
150        let mut words = parameter.split_whitespace();
151        if !words.next()?.eq_ignore_ascii_case(RTCP_FB_CCM_PAUSE) {
152            return None;
153        }
154        let (mut nowait, mut config) = (false, None);
155        for word in words {
156            if word.eq_ignore_ascii_case("nowait") {
157                if nowait {
158                    return None;
159                }
160                nowait = true;
161            } else if let Some(value) = word
162                .split_once('=')
163                .filter(|(key, _)| key.eq_ignore_ascii_case("config"))
164                .map(|(_, value)| value)
165            {
166                if config.is_some() || value.is_empty() || value.len() > 2 {
167                    return None;
168                }
169                config = Some(value.parse().ok()?);
170            }
171        }
172        Some(Self {
173            nowait,
174            config: config.unwrap_or(1),
175        })
176    }
177
178    /// The line's parameter: `pause`, `nowait` when set, `config` when not 1.
179    pub fn parameter(&self) -> String {
180        let mut parameter = RTCP_FB_CCM_PAUSE.to_owned();
181        if self.nowait {
182            parameter.push_str(" nowait");
183        }
184        if self.config != 1 {
185            parameter.push_str(&format!(" config={}", self.config));
186        }
187        parameter
188    }
189
190    /// The negotiated capability of this endpoint from its own line (`local`) and the peer's
191    /// (`remote`), as an answer states it (section 9.1): this endpoint implements every
192    /// message, so its `config` is the one complementary to the peer's, and `nowait` holds
193    /// only when both lines have it. `None` when the peer's `config` is not one the section
194    /// defines.
195    pub fn negotiate(local: &Self, remote: &Self) -> Option<Self> {
196        Some(Self {
197            nowait: local.nowait && remote.nowait,
198            config: pause_config_answer(remote.config)?,
199        })
200    }
201
202    /// Whether the peer receives `typ`: its `config` is the complement of this endpoint's.
203    fn peer_receives(&self, typ: PauseResumeType) -> bool {
204        pause_config_answer(self.config).is_some_and(|peer| supports(peer, false, typ))
205    }
206
207    /// Whether this endpoint acts on a received `typ`.
208    fn receives(&self, typ: PauseResumeType) -> bool {
209        supports(self.config, false, typ)
210    }
211}
212
213/// The negotiated `ccm pause` of a stream, if it has one.
214fn negotiated_pause(info: &StreamInfo) -> Option<PauseCapability> {
215    info.rtcp_feedback
216        .iter()
217        .filter(|feedback| feedback.typ == "ccm")
218        .find_map(|feedback| PauseCapability::parse(&feedback.parameter))
219}
220
221/// Where a local RTP stream is in the state machine of RFC 7728 section 6 (Figure 4).
222#[derive(Debug, Clone, Copy, PartialEq, Eq)]
223pub enum PauseState {
224    /// Sending (section 6.1).
225    Playing,
226    /// A PAUSE was received; the hold-off period runs (section 6.2).
227    Pausing,
228    /// Paused at a receiver's request (section 6.3).
229    Paused,
230    /// Paused by this endpoint's own decision (section 6.4).
231    LocalPaused,
232}
233
234/// What a receiver knows of a remote RTP stream it can pause.
235#[derive(Debug, Clone, Copy, PartialEq, Eq)]
236pub enum RemotePauseState {
237    /// The stream is played as far as the receiver knows.
238    Playing,
239    /// A PAUSE was sent and neither PAUSED nor REFUSED has come back.
240    PauseRequested,
241    /// A PAUSED indication arrived.
242    Paused,
243    /// A RESUME was sent and neither the stream's RTP nor REFUSED has come back.
244    ResumeRequested,
245}
246
247enum Command {
248    Pause(u32),
249    Resume(u32),
250    LocalPause(u32),
251    LocalResume(u32),
252    /// The stream was bound initially paused (`StreamInfo::initially_paused`).
253    InitialPause(u32),
254}
255
256#[derive(Default)]
257struct Shared {
258    commands: Vec<Command>,
259    local: HashMap<u32, PauseState>,
260    remote: HashMap<u32, RemotePauseState>,
261    /// The PauseID each remote stream's sender uses now, as far as known.
262    remote_pause_ids: HashMap<u32, u16>,
263}
264
265fn lock(shared: &Arc<Mutex<Shared>>) -> MutexGuard<'_, Shared> {
266    shared
267        .lock()
268        .unwrap_or_else(|poisoned| poisoned.into_inner())
269}
270
271/// What the peer connection tells the [`PauseResumeInterceptor`] while it runs: a local
272/// stream it sends made inactive or active again (W3C webrtc-pc `RTCRtpEncodingParameters`
273/// `active`), which RFC 8853 section 5.2 has treated as an RFC 7728 local pause (section 6.4,
274/// announced with PAUSED) and resume. A stream that did not negotiate pause and resume is
275/// not affected.
276///
277/// It travels as an [`Attribute::Custom`] on an empty RTCP packet written into the chain
278/// ([`PauseResumeControl::into_packet`]), which the interceptor hands on.
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280#[non_exhaustive]
281pub enum PauseResumeControl {
282    /// The local stream of this SSRC is paused by local decision.
283    LocalPause(u32),
284    /// The local stream of this SSRC, paused by local decision, plays again.
285    LocalResume(u32),
286}
287
288impl PauseResumeControl {
289    /// The packet that carries this to the pause-resume interceptor when written into the
290    /// chain at `now`.
291    pub fn into_packet(self, now: Instant) -> TaggedPacket {
292        TaggedPacket {
293            now,
294            transport: TransportContext::default(),
295            message: AttributedPacket::new(Packet::Rtcp(vec![]))
296                .with(Attribute::Custom(Arc::new(self))),
297        }
298    }
299}
300
301/// The application's side of [`PauseResumeInterceptor`]: asks a remote stream to pause or
302/// resume, pauses its own streams by local decision, and reads where each stream is. A
303/// request takes effect at the interceptor's next timeout, which the interceptor asks for at
304/// once.
305#[derive(Clone)]
306pub struct PauseResumeHandle {
307    shared: Arc<Mutex<Shared>>,
308}
309
310impl PauseResumeHandle {
311    /// Asks the sender of the remote stream `ssrc` to pause it (RFC 7728 section 8.1).
312    pub fn pause(&self, ssrc: u32) {
313        lock(&self.shared).commands.push(Command::Pause(ssrc));
314    }
315
316    /// Asks the sender of the remote stream `ssrc` to resume it (section 8.3).
317    pub fn resume(&self, ssrc: u32) {
318        lock(&self.shared).commands.push(Command::Resume(ssrc));
319    }
320
321    /// Pauses the local stream `ssrc` by local decision (section 6.4).
322    pub fn local_pause(&self, ssrc: u32) {
323        lock(&self.shared).commands.push(Command::LocalPause(ssrc));
324    }
325
326    /// Ends a local pause of the local stream `ssrc`: it plays (section 6.4, "When leaving the
327    /// local paused state, the stream state SHALL become Playing").
328    pub fn local_resume(&self, ssrc: u32) {
329        lock(&self.shared).commands.push(Command::LocalResume(ssrc));
330    }
331
332    /// The state of the local stream `ssrc`, if it negotiated pause.
333    pub fn state(&self, ssrc: u32) -> Option<PauseState> {
334        lock(&self.shared).local.get(&ssrc).copied()
335    }
336
337    /// What is known of the remote stream `ssrc`, if it negotiated pause.
338    pub fn remote_state(&self, ssrc: u32) -> Option<RemotePauseState> {
339        lock(&self.shared).remote.get(&ssrc).copied()
340    }
341
342    /// The PauseID the sender of the remote stream `ssrc` uses now, as far as known.
343    pub fn remote_pause_id(&self, ssrc: u32) -> Option<u16> {
344        lock(&self.shared).remote_pause_ids.get(&ssrc).copied()
345    }
346}
347
348/// Builder for [`PauseResumeInterceptor`].
349#[derive(Debug, Clone)]
350pub struct PauseResumeBuilder {
351    round_trip_time: Duration,
352    report_interval: Duration,
353    dither_max: Duration,
354    repeat_in_regular_reports: bool,
355}
356
357impl Default for PauseResumeBuilder {
358    fn default() -> Self {
359        Self {
360            round_trip_time: PAUSE_DEFAULT_ROUND_TRIP_TIME,
361            report_interval: PAUSE_DEFAULT_REPORT_INTERVAL,
362            dither_max: Duration::ZERO,
363            repeat_in_regular_reports: true,
364        }
365    }
366}
367
368impl PauseResumeBuilder {
369    /// The defaults: a 500 ms round trip, a 5 s report interval, `T_dither_max` 0 (RFC 4585
370    /// section 3.4 for a point-to-point session).
371    pub fn new() -> Self {
372        Self::default()
373    }
374
375    /// The round trip to the peer assumed until one is measured, used for the hold-off period
376    /// and the retransmission of requests (`2 * RTT + T_dither_max`). Once the RTCP session
377    /// reports round trips ([`RtcpSessionEvent::RoundTripTime`]), the longest one measured is
378    /// used instead (RFC 7728 section 6.2: "RTT is the longest round trip known to the RTP
379    /// stream sender").
380    pub fn with_round_trip_time(mut self, round_trip_time: Duration) -> Self {
381        self.round_trip_time = round_trip_time;
382        self
383    }
384
385    /// The RTCP report interval: PAUSED is repeated once per interval, twice (section 8.2),
386    /// a participant silent for five intervals has timed out (section 6.3.2), and a refused
387    /// request is not repeated for two intervals (PAUSE) or one (RESUME).
388    pub fn with_report_interval(mut self, report_interval: Duration) -> Self {
389        self.report_interval = report_interval;
390        self
391    }
392
393    /// `T_dither_max` (RFC 4585 section 3.4): 0 in a point-to-point session.
394    pub fn with_dither_max(mut self, dither_max: Duration) -> Self {
395        self.dither_max = dither_max;
396        self
397    }
398
399    /// How PAUSED is repeated (RFC 7728 sections 6.3, 6.4, 8.2). `true`, the default: the
400    /// first PAUSED is written with a [`RepeatInRegularReports`], so the RTCP session
401    /// ([`Slot::RtcpSession`](crate::Slot::RtcpSession)) carries it again in the next Regular
402    /// compound packets, "the next two regular RTCP reports" (section 8.2), and drops what is
403    /// still owed when the stream leaves the state. `false`: the interceptor writes each
404    /// repetition itself, one [`Self::with_report_interval`] apart, for a chain without the
405    /// RTCP session.
406    pub fn with_repeats_in_regular_reports(mut self, repeat_in_regular_reports: bool) -> Self {
407        self.repeat_in_regular_reports = repeat_in_regular_reports;
408        self
409    }
410
411    /// The interceptor and its handle.
412    pub fn build(self) -> (PauseResumeInterceptor, PauseResumeHandle) {
413        let shared = Arc::new(Mutex::new(Shared::default()));
414        (
415            PauseResumeInterceptor {
416                config: self,
417                shared: shared.clone(),
418                senders: HashMap::new(),
419                receivers: HashMap::new(),
420                initially_paused: HashSet::new(),
421                local_ssrcs: Vec::new(),
422                last_heard: HashMap::new(),
423                round_trips: HashMap::new(),
424                cnames: HashMap::new(),
425                fraction_lost: HashMap::new(),
426                stop_repeating: Vec::new(),
427                fallback_ssrc: rand::random(),
428                now: None,
429                read_queue: VecDeque::new(),
430                write_queue: VecDeque::new(),
431            },
432            PauseResumeHandle { shared },
433        )
434    }
435}
436
437#[derive(Debug, Clone, Copy, PartialEq, Eq)]
438enum SenderState {
439    Playing,
440    Pausing {
441        until: Instant,
442        requester: u32,
443    },
444    Paused {
445        requester: u32,
446    },
447    LocalPaused {
448        requester: Option<u32>,
449    },
450    /// Paused from the start by the session description (RFC 8853 section 5.2): an
451    /// unsolicited local pause that, unlike [`SenderState::LocalPaused`], a RESUME ends
452    /// ("Initially paused simulcast streams are resumed as described by the RTP pause/resume
453    /// specification").
454    InitiallyPaused,
455}
456
457impl SenderState {
458    fn view(self) -> PauseState {
459        match self {
460            Self::Playing => PauseState::Playing,
461            Self::Pausing { .. } => PauseState::Pausing,
462            Self::Paused { .. } => PauseState::Paused,
463            Self::LocalPaused { .. } | Self::InitiallyPaused => PauseState::LocalPaused,
464        }
465    }
466}
467
468struct SenderStream {
469    capability: PauseCapability,
470    state: SenderState,
471    pause_id: u16,
472    /// The packets not sent while paused: later sequence numbers are lowered by this many,
473    /// so that the first packet after a pause follows the last one sent (section 6.1).
474    dropped: u16,
475    /// The extended sequence number of the last packet sent.
476    highest: Option<u32>,
477    /// PAUSED indications still owed, and when the next one is (without the RTCP session's
478    /// repetitions, [`PauseResumeBuilder::with_repeats_in_regular_reports`]).
479    paused_left: u8,
480    next_paused: Option<Instant>,
481    /// The RTCP session repeats this stream's PAUSED.
482    repeating: bool,
483    /// The repetitions are to stop: the stream left the paused states.
484    stop_repeating: bool,
485    ssrc: u32,
486}
487
488impl SenderStream {
489    fn on_sent(&mut self, sequence_number: u16) {
490        self.highest = Some(match self.highest {
491            None => u32::from(sequence_number),
492            Some(highest) => {
493                let cycles = highest & 0xffff_0000;
494                let last = highest as u16;
495                let ahead = sequence_number.wrapping_sub(last);
496                if ahead == 0 || ahead >= 0x8000 {
497                    highest
498                } else if sequence_number < last {
499                    (cycles + 0x1_0000) | u32::from(sequence_number)
500                } else {
501                    cycles | u32::from(sequence_number)
502                }
503            }
504        });
505    }
506
507    fn sending(&self) -> bool {
508        matches!(
509            self.state,
510            SenderState::Playing | SenderState::Pausing { .. }
511        )
512    }
513}
514
515#[derive(Debug, Clone, Copy)]
516struct Request {
517    typ: PauseResumeType,
518    pause_id: u16,
519    next_at: Instant,
520    tries: u8,
521}
522
523struct ReceiverStream {
524    capability: PauseCapability,
525    state: RemotePauseState,
526    pause_id: Option<u16>,
527    request: Option<Request>,
528    /// No new request of this type before then (a REFUSED for this endpoint's PauseID).
529    hold: Option<(PauseResumeType, Instant)>,
530    /// The sender said BYE for this SSRC: no further PAUSE or RESUME goes to it (section
531    /// 6.3.1).
532    left: bool,
533}
534
535/// How often a request is retransmitted before the receiver gives up.
536const MAX_REQUEST_TRIES: u8 = 5;
537
538/// RFC 7728 pause and resume for the streams that negotiated `ccm pause`; see the module
539/// documentation.
540pub struct PauseResumeInterceptor {
541    config: PauseResumeBuilder,
542    shared: Arc<Mutex<Shared>>,
543    senders: HashMap<u32, SenderStream>,
544    receivers: HashMap<u32, ReceiverStream>,
545    /// The local SSRCs that were bound initially paused once: a later binding (after a
546    /// renegotiation) does not pause them again; RFC 7728 signalling decides from then on
547    /// (RFC 8853 section 5.3.4).
548    initially_paused: HashSet<u32>,
549    /// Every bound local SSRC: a request is sent from one of them (section 7: "any of its
550    /// SSRCs MAY be used").
551    local_ssrcs: Vec<u32>,
552    /// When each remote SSRC was last heard from (RTP or RTCP), for the time-out of a
553    /// requester (section 6.3.2).
554    last_heard: HashMap<u32, Instant>,
555    /// The round trip the RTCP session measured to the receiver of each local SSRC.
556    round_trips: HashMap<u32, Duration>,
557    /// The CNAME of each remote SSRC, from the RTCP session (section 6.2: one CNAME across
558    /// the received SSRCs is a single receiver).
559    cnames: HashMap<u32, String>,
560    /// The latest fraction lost the receivers reported on each local SSRC.
561    fraction_lost: HashMap<u32, u8>,
562    /// Keys whose repetitions the RTCP session is to stop (a stream left the paused states).
563    stop_repeating: Vec<u32>,
564    fallback_ssrc: u32,
565    now: Option<Instant>,
566    read_queue: VecDeque<TaggedPacket>,
567    write_queue: VecDeque<TaggedPacket>,
568}
569
570impl PauseResumeInterceptor {
571    fn send(&mut self, now: Instant, sender_ssrc: u32, entries: Vec<PauseResumeEntry>) {
572        if entries.is_empty() {
573            return;
574        }
575        self.write_queue.push_back(TaggedPacket {
576            now,
577            transport: TransportContext::default(),
578            message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(PauseResume {
579                sender_ssrc,
580                entries,
581            })])),
582        });
583    }
584
585    /// RTT for `2 * RTT + T_dither_max` (sections 6.2, 8.1): "the longest round trip known",
586    /// the configured one until one is measured.
587    fn round_trip_time(&self) -> Duration {
588        self.round_trips
589            .values()
590            .copied()
591            .max()
592            .unwrap_or(self.config.round_trip_time)
593    }
594
595    /// Section 6.2: whether the received SSRCs show more than one CNAME, i.e. several
596    /// receivers.
597    fn several_receivers(&self) -> bool {
598        let mut cnames = self.cnames.values();
599        cnames
600            .next()
601            .is_some_and(|first| cnames.any(|other| other != first))
602    }
603
604    fn request_ssrc(&self) -> u32 {
605        self.local_ssrcs
606            .first()
607            .copied()
608            .unwrap_or(self.fallback_ssrc)
609    }
610
611    fn publish(&self) {
612        let mut shared = lock(&self.shared);
613        shared.local = self
614            .senders
615            .iter()
616            .map(|(ssrc, stream)| (*ssrc, stream.state.view()))
617            .collect();
618        shared.remote = self
619            .receivers
620            .iter()
621            .map(|(ssrc, stream)| (*ssrc, stream.state))
622            .collect();
623        shared.remote_pause_ids = self
624            .receivers
625            .iter()
626            .filter_map(|(ssrc, stream)| stream.pause_id.map(|id| (*ssrc, id)))
627            .collect();
628    }
629
630    /// Section 6.1: "When entering the state, the current PauseID MUST be incremented".
631    /// Repetitions of PAUSED still owed stop (sections 6.3: "as long as it is then still in
632    /// paused state", 6.4: "stopping such repetition whenever leaving the state").
633    fn enter_playing(stream: &mut SenderStream) {
634        stream.state = SenderState::Playing;
635        stream.pause_id = stream.pause_id.wrapping_add(1);
636        stream.paused_left = 0;
637        stream.next_paused = None;
638        stream.stop_repeating |= std::mem::take(&mut stream.repeating);
639    }
640
641    /// Tells the RTCP session to stop the repetitions of the streams that left the paused
642    /// states.
643    fn flush_stop_repeating(&mut self, now: Instant) {
644        for stream in self.senders.values_mut() {
645            if std::mem::take(&mut stream.stop_repeating) {
646                self.stop_repeating.push(stream.ssrc);
647            }
648        }
649        for key in std::mem::take(&mut self.stop_repeating) {
650            self.write_queue
651                .push_back(RtcpSessionControl::StopRepeating { key }.into_packet(now));
652        }
653    }
654
655    /// Paused (section 6.3) or local paused (6.4): PAUSED now, and `repeats` more, in the
656    /// next Regular RTCP packets of the session (or, without it, one report interval apart).
657    fn enter_paused(&mut self, now: Instant, ssrc: u32, state: SenderState, repeats: u8) {
658        let interval = self.config.report_interval;
659        let in_regular = self.config.repeat_in_regular_reports;
660        let Some(stream) = self.senders.get_mut(&ssrc) else {
661            return;
662        };
663        stream.state = state;
664        let entry = PauseResumeEntry::paused(ssrc, stream.pause_id, stream.highest.unwrap_or(0));
665        if !stream.capability.peer_receives(PauseResumeType::Paused) {
666            return;
667        }
668        if in_regular {
669            stream.paused_left = 0;
670            stream.next_paused = None;
671            stream.repeating = repeats > 0;
672            stream.stop_repeating = false;
673            self.write_queue.push_back(TaggedPacket {
674                now,
675                transport: TransportContext::default(),
676                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(PauseResume {
677                    sender_ssrc: ssrc,
678                    entries: vec![entry],
679                })]))
680                .with(Attribute::Custom(Arc::new(RepeatInRegularReports {
681                    key: ssrc,
682                    count: repeats,
683                }))),
684            });
685        } else {
686            stream.paused_left = repeats;
687            stream.next_paused = (repeats > 0).then(|| now + interval);
688            self.send(now, ssrc, vec![entry]);
689        }
690    }
691
692    /// The sender's side of the requests of one compound packet (sections 8.1, 8.3, 8.4).
693    fn on_requests(&mut self, now: Instant, requester: u32, entries: &[PauseResumeEntry]) {
694        let several_receivers = self.several_receivers();
695        let round_trip_time = self.round_trip_time();
696        let dither_max = self.config.dither_max;
697        let mut refused: Vec<(u32, u16)> = vec![];
698        let mut paused_now: Vec<u32> = vec![];
699        for entry in entries {
700            let Some(stream) = self.senders.get_mut(&entry.target_ssrc) else {
701                continue;
702            };
703            if !stream.capability.receives(entry.typ) {
704                continue;
705            }
706            let current = stream.pause_id;
707            let is_current = entry.pause_id == current;
708            match (entry.typ, stream.state) {
709                (PauseResumeType::Pause, SenderState::Playing) if is_current => {
710                    // Section 6.2: 0 with `nowait`, unless the sender learned that there are
711                    // several receivers after all: then "it MUST change the hold-off period
712                    // to be based on the above formula instead".
713                    let hold_off = if stream.capability.nowait && !several_receivers {
714                        Duration::ZERO
715                    } else {
716                        round_trip_time * 2 + dither_max
717                    };
718                    if hold_off.is_zero() {
719                        paused_now.push(entry.target_ssrc);
720                        stream.state = SenderState::Paused { requester };
721                    } else {
722                        stream.state = SenderState::Pausing {
723                            until: now + hold_off,
724                            requester,
725                        };
726                    }
727                }
728                // "the received PAUSE SHALL be ignored".
729                (PauseResumeType::Pause, _) if is_current => {}
730                (PauseResumeType::Resume, SenderState::Pausing { .. })
731                | (PauseResumeType::Resume, SenderState::Paused { .. })
732                | (PauseResumeType::Resume, SenderState::InitiallyPaused)
733                    if is_current =>
734                {
735                    Self::enter_playing(stream);
736                }
737                (PauseResumeType::Resume, SenderState::Playing)
738                    if is_current || past(entry.pause_id, current) =>
739                {
740                    // "the received RESUME SHALL be ignored".
741                }
742                (PauseResumeType::Pause, _) | (PauseResumeType::Resume, _) => {
743                    // Not the current PauseID, or (local paused) a RESUME local considerations
744                    // make it impossible to honour: REFUSED with the current PauseID.
745                    refused.push((entry.target_ssrc, current));
746                }
747                _ => {}
748            }
749        }
750        for ssrc in paused_now {
751            if let Some(stream) = self.senders.get(&ssrc) {
752                let state = stream.state;
753                self.enter_paused(now, ssrc, state, PAUSED_REPETITIONS);
754            }
755        }
756        // "duplicate REFUSED notifications MUST NOT be scheduled".
757        let mut seen: HashSet<(u32, u16)> = HashSet::new();
758        for (ssrc, pause_id) in refused {
759            let receives = self
760                .senders
761                .get(&ssrc)
762                .is_some_and(|s| s.capability.peer_receives(PauseResumeType::Refused));
763            if seen.insert((ssrc, pause_id)) && receives {
764                self.send(now, ssrc, vec![PauseResumeEntry::refused(ssrc, pause_id)]);
765            }
766        }
767    }
768
769    /// The receiver's side of PAUSED and REFUSED (sections 8.2, 8.4).
770    fn on_answers(&mut self, now: Instant, entries: &[PauseResumeEntry]) {
771        let (pause_hold, resume_hold) =
772            (self.config.report_interval * 2, self.config.report_interval);
773        for entry in entries {
774            let Some(stream) = self.receivers.get_mut(&entry.target_ssrc) else {
775                continue;
776            };
777            if !stream.capability.receives(entry.typ) {
778                continue;
779            }
780            match entry.typ {
781                PauseResumeType::Paused => {
782                    stream.pause_id = Some(entry.pause_id);
783                    stream.state = RemotePauseState::Paused;
784                    if stream
785                        .request
786                        .is_some_and(|r| r.typ == PauseResumeType::Pause)
787                    {
788                        stream.request = None;
789                    }
790                }
791                PauseResumeType::Refused => {
792                    let Some(request) = stream.request else {
793                        stream.pause_id = Some(entry.pause_id);
794                        continue;
795                    };
796                    stream.request = None;
797                    if request.pause_id == entry.pause_id {
798                        // Section 8.4: "SHOULD refrain from sending an identical request for
799                        // some appropriate time".
800                        let hold = if request.typ == PauseResumeType::Pause {
801                            pause_hold
802                        } else {
803                            resume_hold
804                        };
805                        stream.hold = Some((request.typ, now + hold));
806                        stream.state = if request.typ == PauseResumeType::Pause {
807                            RemotePauseState::Playing
808                        } else {
809                            RemotePauseState::Paused
810                        };
811                    } else {
812                        // "MAY schedule another request using the PauseID from the REFUSED".
813                        stream.pause_id = Some(entry.pause_id);
814                        stream.request = Some(Request {
815                            typ: request.typ,
816                            pause_id: entry.pause_id,
817                            next_at: now,
818                            tries: 0,
819                        });
820                    }
821                }
822                _ => {}
823            }
824        }
825    }
826
827    /// Section 6.4 for the local stream `ssrc`, from the loss its receivers last reported.
828    fn local_pause_repetitions(&self, ssrc: u32) -> u8 {
829        local_pause_repetitions(self.fraction_lost.get(&ssrc).copied().unwrap_or(0))
830    }
831
832    /// The report blocks a remote SR or RR carries about the local streams.
833    fn observe_report_blocks(&mut self, reports: &[ReceptionReport]) {
834        for report in reports {
835            if self.senders.contains_key(&report.ssrc) {
836                self.fraction_lost.insert(report.ssrc, report.fraction_lost);
837            }
838        }
839    }
840
841    fn run_commands(&mut self, now: Instant) {
842        let commands = std::mem::take(&mut lock(&self.shared).commands);
843        for command in commands {
844            match command {
845                Command::Pause(ssrc) | Command::Resume(ssrc) => {
846                    let typ = if matches!(command, Command::Pause(_)) {
847                        PauseResumeType::Pause
848                    } else {
849                        PauseResumeType::Resume
850                    };
851                    let Some(stream) = self.receivers.get_mut(&ssrc) else {
852                        continue;
853                    };
854                    if stream.left
855                        || !stream.capability.peer_receives(typ)
856                        || stream
857                            .hold
858                            .is_some_and(|(held, until)| held == typ && now < until)
859                    {
860                        continue;
861                    }
862                    // Section 8.1: "The initial value SHOULD be 0".
863                    let pause_id = stream.pause_id.unwrap_or(0);
864                    stream.state = if typ == PauseResumeType::Pause {
865                        RemotePauseState::PauseRequested
866                    } else {
867                        RemotePauseState::ResumeRequested
868                    };
869                    stream.request = Some(Request {
870                        typ,
871                        pause_id,
872                        next_at: now,
873                        tries: 0,
874                    });
875                }
876                Command::LocalPause(ssrc) => {
877                    let Some(stream) = self.senders.get(&ssrc) else {
878                        continue;
879                    };
880                    match stream.state {
881                        SenderState::LocalPaused { .. } => {}
882                        SenderState::InitiallyPaused => {
883                            if let Some(stream) = self.senders.get_mut(&ssrc) {
884                                stream.state = SenderState::LocalPaused { requester: None };
885                            }
886                        }
887                        // "unless the stream was already in paused state".
888                        SenderState::Paused { requester } => {
889                            if let Some(stream) = self.senders.get_mut(&ssrc) {
890                                stream.state = SenderState::LocalPaused {
891                                    requester: Some(requester),
892                                };
893                            }
894                        }
895                        SenderState::Playing | SenderState::Pausing { .. } => {
896                            // "SHALL be repeated a sufficient number of times to reach a high
897                            // probability that the message is correctly delivered": as many
898                            // as the loss the receivers report on the stream needs.
899                            let repetitions = self.local_pause_repetitions(ssrc);
900                            self.enter_paused(
901                                now,
902                                ssrc,
903                                SenderState::LocalPaused { requester: None },
904                                repetitions,
905                            );
906                        }
907                    }
908                }
909                Command::LocalResume(ssrc) => {
910                    if let Some(stream) = self.senders.get_mut(&ssrc)
911                        && matches!(
912                            stream.state,
913                            SenderState::LocalPaused { .. } | SenderState::InitiallyPaused
914                        )
915                    {
916                        Self::enter_playing(stream);
917                    }
918                }
919                Command::InitialPause(ssrc) => {
920                    if self
921                        .senders
922                        .get(&ssrc)
923                        .is_some_and(|stream| matches!(stream.state, SenderState::Playing))
924                    {
925                        // Announced as a local pause is (section 6.4).
926                        let repetitions = self.local_pause_repetitions(ssrc);
927                        self.enter_paused(now, ssrc, SenderState::InitiallyPaused, repetitions);
928                    }
929                }
930            }
931        }
932    }
933
934    fn run_timers(&mut self, now: Instant) {
935        let interval = self.config.report_interval;
936        let timeout = interval * 5;
937        let retransmit = self.round_trip_time() * 2 + self.config.dither_max;
938        let last_heard = self.last_heard.clone();
939        let mut pause_now = vec![];
940        let mut paused_due = vec![];
941        for (ssrc, stream) in &mut self.senders {
942            match stream.state {
943                SenderState::Pausing { until, requester } if until <= now => {
944                    stream.state = SenderState::Paused { requester };
945                    pause_now.push(*ssrc);
946                }
947                SenderState::Paused { requester } | SenderState::Pausing { requester, .. }
948                    if last_heard
949                        .get(&requester)
950                        .is_some_and(|heard| *heard + timeout <= now) =>
951                {
952                    // Section 6.3.2: the requester timed out; the stream is resumed.
953                    Self::enter_playing(stream);
954                }
955                _ => {}
956            }
957            if !stream.sending()
958                && stream.paused_left > 0
959                && stream.next_paused.is_some_and(|at| at <= now)
960            {
961                stream.paused_left -= 1;
962                stream.next_paused = (stream.paused_left > 0).then(|| now + interval);
963                if stream.capability.peer_receives(PauseResumeType::Paused) {
964                    paused_due.push(PauseResumeEntry::paused(
965                        *ssrc,
966                        stream.pause_id,
967                        stream.highest.unwrap_or(0),
968                    ));
969                }
970            }
971        }
972        for ssrc in pause_now {
973            if let Some(stream) = self.senders.get(&ssrc) {
974                let state = stream.state;
975                self.enter_paused(now, ssrc, state, PAUSED_REPETITIONS);
976            }
977        }
978        for entry in paused_due {
979            let ssrc = entry.target_ssrc;
980            self.send(now, ssrc, vec![entry]);
981        }
982
983        let request_ssrc = self.request_ssrc();
984        let mut requests = vec![];
985        for (ssrc, stream) in &mut self.receivers {
986            let Some(request) = stream.request.as_mut() else {
987                continue;
988            };
989            if request.next_at > now {
990                continue;
991            }
992            if request.tries >= MAX_REQUEST_TRIES {
993                stream.request = None;
994                continue;
995            }
996            request.tries += 1;
997            request.next_at = now + retransmit;
998            requests.push(match request.typ {
999                PauseResumeType::Pause => PauseResumeEntry::pause(*ssrc, request.pause_id),
1000                _ => PauseResumeEntry::resume(*ssrc, request.pause_id),
1001            });
1002        }
1003        self.send(now, request_ssrc, requests);
1004    }
1005
1006    fn next_timer(&self) -> Option<Instant> {
1007        let timeout = self.config.report_interval * 5;
1008        let mut next: Option<Instant> = None;
1009        let mut consider = |at: Instant| {
1010            next = Some(next.map_or(at, |n| n.min(at)));
1011        };
1012        for stream in self.senders.values() {
1013            match stream.state {
1014                SenderState::Pausing { until, requester } => {
1015                    consider(until);
1016                    if let Some(heard) = self.last_heard.get(&requester) {
1017                        consider(*heard + timeout);
1018                    }
1019                }
1020                SenderState::Paused { requester } => {
1021                    if let Some(heard) = self.last_heard.get(&requester) {
1022                        consider(*heard + timeout);
1023                    }
1024                }
1025                _ => {}
1026            }
1027            if let Some(at) = stream.next_paused {
1028                consider(at);
1029            }
1030        }
1031        for stream in self.receivers.values() {
1032            if let Some(request) = stream.request {
1033                consider(request.next_at);
1034            }
1035        }
1036        next
1037    }
1038}
1039
1040/// Whether `pause_id` is a past PauseID of `current` (RFC 7728 section 8: between
1041/// `current - 2^15` and `current - 1`, modulo 2^16).
1042fn past(pause_id: u16, current: u16) -> bool {
1043    let behind = current.wrapping_sub(pause_id);
1044    (1..=0x8000).contains(&behind)
1045}
1046
1047impl Protocol<TaggedPacket, TaggedPacket, ()> for PauseResumeInterceptor {
1048    type Rout = TaggedPacket;
1049    type Wout = TaggedPacket;
1050    type Eout = ();
1051    type Error = Error;
1052    type Time = Instant;
1053
1054    fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
1055        let now = msg.now;
1056        self.now = Some(self.now.map_or(now, |n| n.max(now)));
1057        self.run_commands(now);
1058        match &msg.message.packet {
1059            Packet::Rtp(packet) => {
1060                let ssrc = packet.header.ssrc;
1061                self.last_heard.insert(ssrc, now);
1062                // Section 8.3: a RESUME is retransmitted until RTP of the stream arrives.
1063                if let Some(stream) = self.receivers.get_mut(&ssrc)
1064                    && matches!(
1065                        stream.state,
1066                        RemotePauseState::Paused | RemotePauseState::ResumeRequested
1067                    )
1068                {
1069                    // The sender plays again, with the next PauseID (section 6.1).
1070                    stream.pause_id = stream.pause_id.map(|id| id.wrapping_add(1));
1071                    stream.state = RemotePauseState::Playing;
1072                    stream.request = None;
1073                }
1074            }
1075            Packet::Rtcp(packets) => {
1076                let mut deliver = false;
1077                for packet in packets {
1078                    if let Some(message) = packet.as_any().downcast_ref::<PauseResume>() {
1079                        deliver = true;
1080                        self.last_heard.insert(message.sender_ssrc, now);
1081                        let message = message.clone();
1082                        self.on_requests(now, message.sender_ssrc, &message.entries);
1083                        self.on_answers(now, &message.entries);
1084                    } else if let Some(bye) = packet.as_any().downcast_ref::<Goodbye>() {
1085                        // Section 6.3.1: the requester left; the stream is resumed.
1086                        for left in &bye.sources {
1087                            self.last_heard.remove(left);
1088                            self.cnames.remove(left);
1089                            for stream in self.senders.values_mut() {
1090                                if matches!(
1091                                    stream.state,
1092                                    SenderState::Paused { requester }
1093                                        | SenderState::Pausing { requester, .. }
1094                                        if requester == *left
1095                                ) {
1096                                    Self::enter_playing(stream);
1097                                }
1098                            }
1099                            // "receivers observing this SHALL NOT send further PAUSE or
1100                            // RESUME requests to it".
1101                            if let Some(stream) = self.receivers.get_mut(left) {
1102                                stream.request = None;
1103                                stream.left = true;
1104                            }
1105                        }
1106                    } else if let Some(report) = packet.as_any().downcast_ref::<ReceiverReport>() {
1107                        self.last_heard.insert(report.ssrc, now);
1108                        self.observe_report_blocks(&report.reports);
1109                    } else if let Some(report) = packet.as_any().downcast_ref::<SenderReport>() {
1110                        self.last_heard.insert(report.ssrc, now);
1111                        self.observe_report_blocks(&report.reports);
1112                    }
1113                }
1114                // What the RTCP session learned: round trips (section 6.2: "the longest
1115                // round trip known") and the CNAMEs of the remote sources (section 6.2: one
1116                // CNAME across the received SSRCs is a single receiver).
1117                match msg.message.custom::<RtcpSessionEvent>() {
1118                    Some(RtcpSessionEvent::RoundTripTime { ssrc, rtt }) => {
1119                        self.round_trips.insert(*ssrc, *rtt);
1120                    }
1121                    Some(RtcpSessionEvent::RemoteCname { ssrc, cname }) => {
1122                        self.cnames.insert(*ssrc, cname.clone());
1123                    }
1124                    Some(RtcpSessionEvent::SourceTimedOut { ssrc }) => {
1125                        self.cnames.remove(ssrc);
1126                    }
1127                    _ => {}
1128                }
1129                if deliver && !msg.message.has(&Attribute::DeliverToApplication) {
1130                    msg.message.attributes.push(Attribute::DeliverToApplication);
1131                }
1132            }
1133        }
1134        self.publish();
1135        self.read_queue.push_back(msg);
1136        self.flush_stop_repeating(now);
1137        Ok(())
1138    }
1139
1140    fn poll_read(&mut self) -> Option<Self::Rout> {
1141        self.read_queue.pop_front()
1142    }
1143
1144    fn handle_write(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
1145        self.now = Some(self.now.map_or(msg.now, |n| n.max(msg.now)));
1146        if let Some(control) = msg.message.custom::<PauseResumeControl>() {
1147            lock(&self.shared).commands.push(match *control {
1148                PauseResumeControl::LocalPause(ssrc) => Command::LocalPause(ssrc),
1149                PauseResumeControl::LocalResume(ssrc) => Command::LocalResume(ssrc),
1150            });
1151        }
1152        // A local pause asked for before this packet applies to it.
1153        self.run_commands(msg.now);
1154        self.flush_stop_repeating(msg.now);
1155        if let Packet::Rtp(packet) = &mut msg.message.packet
1156            && let Some(stream) = self.senders.get_mut(&packet.header.ssrc)
1157        {
1158            if !stream.sending() {
1159                // Paused: nothing is sent (sections 6.3, 6.4). Keepalives are ICE's.
1160                stream.dropped = stream.dropped.wrapping_add(1);
1161                return Ok(());
1162            }
1163            packet.header.sequence_number =
1164                packet.header.sequence_number.wrapping_sub(stream.dropped);
1165            stream.on_sent(packet.header.sequence_number);
1166        }
1167        self.write_queue.push_back(msg);
1168        Ok(())
1169    }
1170
1171    fn poll_write(&mut self) -> Option<Self::Wout> {
1172        self.write_queue.pop_front()
1173    }
1174
1175    fn handle_timeout(&mut self, now: Instant) -> Result<(), Self::Error> {
1176        self.now = Some(self.now.map_or(now, |n| n.max(now)));
1177        self.run_commands(now);
1178        self.run_timers(now);
1179        self.flush_stop_repeating(now);
1180        self.publish();
1181        Ok(())
1182    }
1183
1184    fn poll_timeout(&mut self) -> Option<Self::Time> {
1185        // Commands run at the next timeout (or packet): the interceptor has no clock of its
1186        // own, so it asks for the latest time it was given.
1187        let commands = !lock(&self.shared).commands.is_empty();
1188        match (commands.then_some(self.now).flatten(), self.next_timer()) {
1189            (Some(now), Some(timer)) => Some(now.min(timer)),
1190            (now, timer) => now.or(timer),
1191        }
1192    }
1193}
1194
1195impl Interceptor for PauseResumeInterceptor {
1196    fn bind_remote_stream(&mut self, info: &StreamInfo) {
1197        if let Some(capability) = negotiated_pause(info) {
1198            self.receivers
1199                .entry(info.ssrc)
1200                .or_insert(ReceiverStream {
1201                    capability,
1202                    state: RemotePauseState::Playing,
1203                    pause_id: None,
1204                    request: None,
1205                    hold: None,
1206                    left: false,
1207                })
1208                .capability = capability;
1209            self.publish();
1210        }
1211    }
1212
1213    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
1214        self.receivers.remove(&info.ssrc);
1215        self.publish();
1216    }
1217
1218    fn bind_local_stream(&mut self, info: &StreamInfo) {
1219        if !self.local_ssrcs.contains(&info.ssrc) {
1220            self.local_ssrcs.push(info.ssrc);
1221        }
1222        if let Some(capability) = negotiated_pause(info) {
1223            // RFC 8853 section 5.2: an initially paused stream is "an unsolicited locally
1224            // paused stream", from the start; it can be paused only with pause and resume
1225            // negotiated for it (section 5.3.3), which is when this interceptor binds it.
1226            if info.initially_paused
1227                && !self.senders.contains_key(&info.ssrc)
1228                && self.initially_paused.insert(info.ssrc)
1229            {
1230                lock(&self.shared)
1231                    .commands
1232                    .push(Command::InitialPause(info.ssrc));
1233            }
1234            self.senders
1235                .entry(info.ssrc)
1236                .or_insert(SenderStream {
1237                    capability,
1238                    state: SenderState::Playing,
1239                    pause_id: 0,
1240                    dropped: 0,
1241                    highest: None,
1242                    paused_left: 0,
1243                    next_paused: None,
1244                    repeating: false,
1245                    stop_repeating: false,
1246                    ssrc: info.ssrc,
1247                })
1248                .capability = capability;
1249            self.publish();
1250        }
1251    }
1252
1253    fn unbind_local_stream(&mut self, info: &StreamInfo) {
1254        self.local_ssrcs.retain(|ssrc| *ssrc != info.ssrc);
1255        if self
1256            .senders
1257            .remove(&info.ssrc)
1258            .is_some_and(|stream| stream.repeating)
1259        {
1260            self.stop_repeating.push(info.ssrc);
1261        }
1262        self.fraction_lost.remove(&info.ssrc);
1263        self.round_trips.remove(&info.ssrc);
1264        self.publish();
1265    }
1266}