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