Skip to main content

rtci_host/
media.rs

1// Copyright 2026 Brainwires. MIT OR Apache-2.0.
2
3//! Media: transceivers, senders and receivers over the engine's RTP stack
4//! (SRTP, RTCP reports, NACK, TWCC), and the codec capabilities.
5//!
6//! There is no capture device and no codec here. The standard surface
7//! (`addTransceiver`, `addTrack`, `getTransceivers`, `ontrack`, parameters,
8//! capabilities, codec preferences, per-sender / per-receiver stats) works
9//! without one; what goes out on a sender is what the program writes through
10//! the `Deno.webrtc` extension (encoded frames, packetized here, or finished
11//! RTP packets), and what a receiver gets is delivered as RTP packets to a
12//! `Deno.webrtc.readRtp()` reader.
13//!
14//! The engine names transceivers by their index, which a removal (a rollback,
15//! or an answer rejecting a stopped transceiver's section) shifts;
16//! [`Core::keys`](crate::peer::Core) maps each index to a stable key that
17//! JavaScript uses instead.
18
19use std::collections::HashMap;
20use std::collections::VecDeque;
21use std::sync::Arc;
22use std::sync::atomic::AtomicU64;
23use std::sync::atomic::Ordering;
24use std::time::Instant;
25
26use bytes::Bytes;
27use rtci::interceptor::Attribute;
28use rtci::interceptor::AttributedPacket;
29use rtci::interceptor::CONGESTION_CONTROL_DEFAULT_PRUNE_HORIZON;
30use rtci::interceptor::GCC_INITIAL_BITRATE;
31use rtci::interceptor::Gcc;
32use rtci::interceptor::Interceptor;
33use rtci::interceptor::PacerBuilder;
34use rtci::interceptor::PacerInterceptor;
35use rtci::interceptor::Packet;
36use rtci::interceptor::Registry;
37use rtci::interceptor::Slot;
38use rtci::interceptor::StreamInfo;
39use rtci::interceptor::TaggedPacket;
40use rtci::media_stream::MediaStreamTrack;
41use rtci::peer_connection::RTCPeerConnectionBuilder;
42use rtci::peer_connection::configuration::interceptor_registry::CongestionFeedback;
43use rtci::peer_connection::configuration::interceptor_registry::DefaultInterceptorOptions;
44use rtci::peer_connection::configuration::interceptor_registry::configure_congestion_control;
45use rtci::peer_connection::configuration::interceptor_registry::configure_congestion_control_feedback;
46use rtci::peer_connection::configuration::interceptor_registry::register_default_interceptors_with_options;
47use rtci::peer_connection::configuration::media_engine::MediaEngine;
48use rtci::peer_connection::cryptex::RTCRtpHeaderEncryptionPolicy;
49use rtci::rtcp::payload_feedbacks::full_intra_request::FullIntraRequest;
50use rtci::rtcp::payload_feedbacks::picture_loss_indication::PictureLossIndication;
51use rtci::rtcp::transport_feedbacks::cc_feedback_report::CcFeedbackReport;
52use rtci::rtcp::transport_feedbacks::transport_layer_cc::TransportLayerCc;
53use rtci::rtp::packetizer::Packetizer;
54use rtci::rtp_transceiver::RTCRtpTransceiverDirection;
55use rtci::rtp_transceiver::RTCRtpTransceiverInit;
56use rtci::rtp_transceiver::rtp_sender::RTCP_FB_ACK_CCFB;
57use rtci::rtp_transceiver::rtp_sender::RTCRtpCodec;
58use rtci::rtp_transceiver::rtp_sender::RTCRtpCodecParameters;
59use rtci::rtp_transceiver::rtp_sender::RTCRtpCodingParameters;
60use rtci::rtp_transceiver::rtp_sender::RTCRtpEncodingParameters;
61use rtci::rtp_transceiver::rtp_sender::RTCRtpHeaderExtensionCapability;
62use rtci::rtp_transceiver::rtp_sender::RTCRtpHeaderExtensionEncryption;
63use rtci::rtp_transceiver::rtp_sender::RTCRtpHeaderExtensionToNegotiate;
64use rtci::rtp_transceiver::rtp_sender::RTCRtpSendParameters;
65use rtci::rtp_transceiver::rtp_sender::RtpCodecKind;
66use rtci::rtp_transceiver::rtp_sender::TYPE_RTCP_FB_ACK;
67use rtci::sansio::Protocol;
68use rtci::shared::marshal::MarshalSize;
69use rtci::shared::marshal::Unmarshal;
70use serde::Deserialize;
71use serde::Serialize;
72
73use crate::error::Error;
74use crate::error::ErrorKind;
75use crate::peer::Core;
76
77/// The MTU RTP packets are cut to (what browsers use; leaves room for SRTP,
78/// UDP, IP and a TURN header), header extensions included: a sender's
79/// payloads are smaller by the octets the engine adds
80/// (`RTCRtpSender::max_packet_expansion`, RFC 7941 section 4.2.2), and by
81/// more once a path reported a smaller MTU ([`rtp_mtu`]).
82const RTP_MTU: usize = 1200;
83
84/// The most an SRTP packet adds to the RTP packet it protects: the
85/// authentication tag of the largest profile browsers negotiate
86/// (AEAD_AES_128_GCM / AEAD_AES_256_GCM, 16 octets; RFC 7714 section 15).
87const SRTP_MAX_OVERHEAD: usize = 16;
88
89/// The smallest MTU [`rtp_mtu`] cuts to: a payload of a few hundred octets
90/// still packetizes every codec, where a path report below the IPv4 minimum
91/// would leave none.
92const RTP_MTU_FLOOR: usize = 256;
93
94/// The size a sender's RTP packets are cut to by its packetizer, header
95/// included and the engine's extensions left out: [`RTP_MTU`], or what a
96/// datagram of `datagram_limit` octets (the path's, once reported) carries
97/// once SRTP has its tag, less `expansion`
98/// (`RTCRtpSender::max_packet_expansion`), so the RTP packet on the wire,
99/// extensions included, stays within both.
100fn rtp_mtu(datagram_limit: Option<usize>, expansion: usize) -> usize {
101  let mtu = datagram_limit.map_or(RTP_MTU, |limit| {
102    RTP_MTU.min(limit.saturating_sub(SRTP_MAX_OVERHEAD))
103  });
104  mtu.saturating_sub(expansion).max(RTP_MTU_FLOOR)
105}
106
107/// The engine's media configuration: every codec browsers negotiate (Opus,
108/// G.722, PCMU/PCMA, VP8, VP9, H.264, AV1, H.265, RTX), the default
109/// interceptors (NACK, RTCP sender/receiver reports, TWCC feedback,
110/// simulcast header extensions), send-side congestion control (GCC over
111/// TWCC, with a pacer) and RFC 8888 congestion control feedback (`ack
112/// ccfb`), which carries ECN.
113pub fn media_stack() -> Result<(MediaEngine, Registry), Error> {
114  media_stack_counting(Arc::default())
115}
116
117/// [`media_stack`], with the pacer counting the packets its full queue
118/// refuses into `refusals` (a connection's `getStats()` reports them).
119pub(crate) fn media_stack_counting(
120  refusals: Arc<PacerRefusals>,
121) -> Result<(MediaEngine, Registry), Error> {
122  let mut media_engine = MediaEngine::default();
123  media_engine
124    .register_default_codecs()
125    .map_err(crate::peer::rtc_err)?;
126  // The defaults register RFC 4733 telephone events (RFC 7874 section 3),
127  // at Opus' clock and at 8 kHz, for RTCDTMFSender: a second registration
128  // here would put another format on a payload type the video RTX formats
129  // use (RFC 9143 section 9.1.1 refuses one payload type with two
130  // configurations in a BUNDLE group).
131  // The defaults include the fork's key-frame request interceptor, which
132  // delivers inbound PLI and FIR to the application (here, an
133  // `EncodedMediaTrack`'s `keyframerequest`): upstream ends them at the
134  // chain's terminus.
135  // The audio level extensions (RFC 6464, RFC 6465) are offered in the
136  // clear only, as Chromium, WebKit and Firefox offer them (and as the 0.22
137  // engine did; rtci's `Chrome` profile value of
138  // `audio_level_encryption`). The default, best effort, offers each also in
139  // its RFC 6904 encrypted form and answers an offer that has both with the
140  // encrypted one and the clear one `a=extmap:<id>/inactive`: that answer's
141  // first "inactive" is then an extmap line's, not the section's direction
142  // (WPT `protocol/direction.html` changes the first one to make an invalid
143  // answer), and every audio section carries two mappings per extension.
144  // Answering, the engine still takes the encrypted form an offer has (RFC
145  // 6904 section 4.1). RFC 9335 cryptex (`rtpHeaderEncryptionPolicy`)
146  // encrypts every extension and is not affected.
147  let mut options =
148    DefaultInterceptorOptions::for_profile(media_engine.behaviour_profile());
149  options.audio_level_encryption = RTCRtpHeaderExtensionEncryption::Clear;
150  let (registry, _handles) = register_default_interceptors_with_options(
151    Registry::new(),
152    &mut media_engine,
153    &options,
154  )
155  .map_err(crate::peer::rtc_err)?;
156  // Send-side congestion control: transport-wide sequence numbers on what
157  // leaves, GCC over the TWCC feedback that comes back, and a pacer at its
158  // estimate. The defaults already negotiate TWCC (`transport-cc` feedback and
159  // the header extension, deduplicated here) and record arrivals for the
160  // remote side; this takes the receiver's slot with the same recorder. The
161  // pacer only queues (bounded), and the driver releases from it at the
162  // engine's `poll_timeout`, so writes never wait on it. It paces at
163  // PACING_FACTOR times the estimate, and only while the remote's congestion
164  // feedback is in use: see [`FactorPacer`] for when it lets packets straight
165  // through instead, what the stats report then, and how a packet its full
166  // queue refuses is counted.
167  let registry = configure_congestion_control(
168    registry,
169    Gcc::default(),
170    CongestionFeedback::Twcc,
171    &mut media_engine,
172  )
173  .map_err(crate::peer::rtc_err)?
174  .with(Slot::Pacer, FactorPacer::new(refusals));
175  // RFC 8888 feedback beside TWCC: `a=rtcp-fb:<pt> ack ccfb` on every codec
176  // and the recorder that reports each received packet with the ECN
177  // codepoint it arrived with. A stream sends ECT(1) (L4S) only once `ack
178  // ccfb` is negotiated, since an L4S sender needs CE reported back; a peer
179  // that doesn't answer it (browsers, unless Chrome's field trial is on)
180  // negotiates without it and keeps TWCC alone. Where both are negotiated
181  // the send history keeps one record per packet, so a packet both report
182  // reaches the estimator once.
183  let registry =
184    configure_congestion_control_feedback(registry, &mut media_engine);
185  register_header_extensions(&mut media_engine)?;
186  Ok((media_engine, registry))
187}
188
189/// How much faster than the congestion controller's estimate the pacer lets
190/// packets out: libwebrtc's pacing factor (`kDefaultPaceMultiplier`, 2.5).
191/// The pacer smooths bursts (a key frame's packets); it is not what holds a
192/// sender to the estimate, which is the encoder's job in a browser.
193pub const PACING_FACTOR: f64 = 2.5;
194
195/// How long the pacer keeps pacing without congestion feedback: from the
196/// first packet of a stream that negotiated it, and from each report after
197/// that. It is the congestion controller's own horizon
198/// (`DEFAULT_PRUNE_HORIZON`, 2 s): past it the send history has written off
199/// every packet the remote had not reported, so no report can still bring
200/// the estimate up to date, and holding packets at it would cap the
201/// connection at a number nothing measures. Remotes send TWCC every 50 to
202/// 250 ms (libwebrtc) and RFC 8888 reports about once per round trip, so
203/// this is eight reports or more: a few lost ones never trip it.
204pub const FEEDBACK_TIMEOUT: std::time::Duration =
205  CONGESTION_CONTROL_DEFAULT_PRUNE_HORIZON;
206
207/// The longest the pacer lets its queue grow, in the time it takes to drain:
208/// past it the pacer releases faster than the estimate, at what drains the
209/// queue in this time (libwebrtc's pacer queue time limit,
210/// `kMaxExpectedQueueLength`, 2 s). A source steadily above the estimate is
211/// then delayed by this much at most, rather than by however long its
212/// backlog takes at the estimate (minutes, at a low one).
213pub const QUEUE_TIME_LIMIT: std::time::Duration =
214  std::time::Duration::from_secs(2);
215
216/// The engine pacer's rate while [`FactorPacer`] is not pacing: high enough
217/// that what it still holds from before (packets queued while it was) goes
218/// at the next wake-up.
219const UNPACED_BITRATE: f64 = 1e9;
220
221/// The packets (and their bytes) a connection's pacer refused because its
222/// queue was full. Shared with the connection (`MediaState`), whose
223/// `getStats()` adds them to the selected candidate pair's
224/// `packetsDiscardedOnSend` / `bytesDiscardedOnSend`.
225#[derive(Default, Debug)]
226pub struct PacerRefusals {
227  packets: AtomicU64,
228  bytes: AtomicU64,
229}
230
231impl PacerRefusals {
232  /// The packets refused so far, and their bytes.
233  pub fn get(&self) -> (u64, u64) {
234    (
235      self.packets.load(Ordering::Relaxed),
236      self.bytes.load(Ordering::Relaxed),
237    )
238  }
239
240  pub(crate) fn add(&self, bytes: usize) {
241    self.packets.fetch_add(1, Ordering::Relaxed);
242    self.bytes.fetch_add(bytes as u64, Ordering::Relaxed);
243  }
244}
245
246/// The pacer slot: the engine's pacer at [`PACING_FACTOR`] times the
247/// congestion controller's estimate, while the remote's congestion feedback
248/// is in use, and a pass-through otherwise.
249///
250/// - **Which packets.** Those of a local video stream (its RTX and FEC
251///   SSRCs included) that negotiated feedback: the transport-wide sequence
252///   number extension (TWCC) or `ack ccfb` (RFC 8888). A stream that
253///   negotiated neither is never paced: the remote will not report on it, so
254///   the estimate never moves and pacing would hold it at the initial rate
255///   (GCC's 300 kb/s, so 750 kb/s here) for the life of the connection.
256///   Audio is never paced either: its rate is small and steady, and behind a
257///   video key frame in one queue it would arrive late (libwebrtc sends it
258///   ahead of video). The congestion controller still counts it.
259/// - **How fast.** At [`PACING_FACTOR`] times the estimate, or faster when
260///   the queue would take longer than [`QUEUE_TIME_LIMIT`] to drain at that:
261///   then at what drains it in that time.
262/// - **When.** While reports keep coming: TWCC or RFC 8888 feedback (or an
263///   estimate the controller made from one) went past within
264///   [`FEEDBACK_TIMEOUT`]. Before the first report the window runs from
265///   the first packet of a negotiated stream, at the initial rate, as a
266///   browser starts; a remote that negotiated feedback but sends none, or
267///   whose reports stop, gets pass-through once it passes, and pacing at the
268///   estimate again with its next report. What was queued then goes at
269///   once, and later packets of a stream wait behind it, so a stream's
270///   packets keep their order.
271/// - **Stats.** The estimate reaches `availableOutgoingBitrate` and
272///   `targetBitrate` only while it paces: from the first report (the
273///   initial rate until the controller moves it) to when reports stop, and
274///   again from the next one. Without feedback `availableOutgoingBitrate` is
275///   absent and `targetBitrate` is 0, as before any estimate: nothing is
276///   estimated, and nothing but the source and the path limits the rate.
277/// - **A full queue.** The engine pacer refuses a packet past its limit, as
278///   a congested path would drop it, without an error to its caller (the
279///   write reaches it later, from the driver). Each refusal is counted
280///   ([`PacerRefusals`]) and logged once per run of them.
281///
282/// The engine paces at the estimate itself (it adds no headroom of its own)
283/// and hands the same number to the stats, so the estimate stays what the
284/// stats report; only the rate this pacer releases at is scaled.
285pub(crate) struct FactorPacer {
286  pacer: PacerInterceptor,
287  /// The SSRCs (primary, RTX, FEC) of each bound local stream it paces
288  /// ([`paces`](Self::paces)), by its primary SSRC.
289  negotiated: HashMap<u32, Vec<u32>>,
290  /// The controller's latest estimate (GCC's initial one before any).
291  estimate: f64,
292  /// When the last report (or estimate) came by.
293  last_feedback: Option<Instant>,
294  /// Before any report: when a negotiated stream's first packet went out.
295  waiting_since: Option<Instant>,
296  /// Whether packets of negotiated streams are paced now.
297  paced: bool,
298  /// What the engine pacer holds, per SSRC in the order written: each
299  /// packet's sequence number, when it was written, and its bits. Per SSRC
300  /// because the engine pacer (rtci 0.4) shares its queue among the streams
301  /// by priority (RFC 8835 section 4.1): packets of different streams leave
302  /// interleaved, not in the order written, while each stream's leave in
303  /// its own order (a retransmission without RTX goes ahead of new media,
304  /// so a released packet is looked up by its sequence number).
305  held: HashMap<u32, VecDeque<(u16, Instant, f64)>>,
306  /// The bits in `held`.
307  held_bits: f64,
308  /// The latest instant handed in.
309  now: Option<Instant>,
310  /// Whether the stats hold an estimate this pacer let through.
311  estimate_reported: bool,
312  /// Packets let straight through, behind what the engine pacer releases.
313  passed: VecDeque<TaggedPacket>,
314  /// Attribute carriers for the stats (an estimate withdrawn).
315  carriers: VecDeque<TaggedPacket>,
316  refusals: Arc<PacerRefusals>,
317  /// In a run of refusals (logged at its first).
318  refusing: bool,
319}
320
321impl FactorPacer {
322  pub(crate) fn new(refusals: Arc<PacerRefusals>) -> Self {
323    Self::with_pacer(
324      PacerBuilder::new()
325        .with_target_bitrate(GCC_INITIAL_BITRATE * PACING_FACTOR)
326        // The queue's time limit is this pacer's (`rate`: drained faster
327        // past QUEUE_TIME_LIMIT, never discarded for its age), not the
328        // engine pacer's default, which drops what waited 2 s.
329        .with_queue_time_limit(None)
330        .build(),
331      refusals,
332    )
333  }
334
335  pub(crate) fn with_pacer(
336    pacer: PacerInterceptor,
337    refusals: Arc<PacerRefusals>,
338  ) -> Self {
339    Self {
340      pacer,
341      negotiated: HashMap::new(),
342      estimate: GCC_INITIAL_BITRATE,
343      last_feedback: None,
344      waiting_since: None,
345      paced: true,
346      held: HashMap::new(),
347      held_bits: 0.0,
348      now: None,
349      estimate_reported: false,
350      passed: VecDeque::new(),
351      carriers: VecDeque::new(),
352      refusals,
353      refusing: false,
354    }
355  }
356
357  /// The estimate a packet on the read leg carries (the congestion
358  /// controller attaches it to the feedback that produced it).
359  fn estimate(msg: &TaggedPacket) -> Option<f64> {
360    match msg.message.get(&Attribute::TargetBitrateChanged {
361      bits_per_second: 0.0,
362    }) {
363      Some(Attribute::TargetBitrateChanged { bits_per_second }) => {
364        Some(*bits_per_second)
365      }
366      _ => None,
367    }
368  }
369
370  /// Whether an inbound packet is congestion feedback: a TWCC or an RFC
371  /// 8888 report.
372  fn is_feedback(msg: &TaggedPacket) -> bool {
373    let Packet::Rtcp(packets) = &msg.message.packet else {
374      return false;
375    };
376    packets.iter().any(|p| {
377      let p = p.as_any();
378      p.is::<TransportLayerCc>() || p.is::<CcFeedbackReport>()
379    })
380  }
381
382  /// Whether a stream is paced: video that negotiated feedback the remote
383  /// reports it with.
384  fn paces(info: &StreamInfo) -> bool {
385    !info.mime_type.to_ascii_lowercase().starts_with("audio/")
386      && Self::negotiates_feedback(info)
387  }
388
389  /// Whether a stream negotiated feedback the remote reports it with.
390  fn negotiates_feedback(info: &StreamInfo) -> bool {
391    info
392      .rtp_header_extensions
393      .iter()
394      .any(|e| e.uri == rtci::sdp::extmap::TRANSPORT_CC_URI)
395      || info
396        .rtcp_feedback
397        .iter()
398        .any(|f| f.typ == TYPE_RTCP_FB_ACK && f.parameter == RTCP_FB_ACK_CCFB)
399  }
400
401  fn is_negotiated(&self, ssrc: u32) -> bool {
402    self.negotiated.values().any(|ssrcs| ssrcs.contains(&ssrc))
403  }
404
405  /// Whether negotiated streams are to be paced at `now`.
406  fn pacing(&self, now: Instant) -> bool {
407    if self.negotiated.is_empty() {
408      return false;
409    }
410    match self.last_feedback.or(self.waiting_since) {
411      Some(since) => now.saturating_duration_since(since) < FEEDBACK_TIMEOUT,
412      None => true,
413    }
414  }
415
416  /// The rate the engine pacer releases at now: the scaled estimate, or,
417  /// when that is slower, what lets the queue out by the time its oldest
418  /// packet has waited [`QUEUE_TIME_LIMIT`] (libwebrtc's rule: the time left
419  /// is the limit less that wait, and at least a millisecond).
420  fn rate(&self) -> f64 {
421    if !self.paced {
422      return UNPACED_BITRATE;
423    }
424    let paced = self.estimate * PACING_FACTOR;
425    let oldest = self
426      .held
427      .values()
428      .filter_map(|queue| queue.front().map(|&(_, written, _)| written))
429      .min();
430    let (Some(oldest), Some(now)) = (oldest, self.now) else {
431      return paced;
432    };
433    let left = QUEUE_TIME_LIMIT
434      .saturating_sub(now.saturating_duration_since(oldest))
435      .max(std::time::Duration::from_millis(1));
436    paced.max(self.held_bits / left.as_secs_f64())
437  }
438
439  /// Records the latest instant handed in.
440  fn observe(&mut self, now: Instant) {
441    if self.now.is_none_or(|last| now > last) {
442      self.now = Some(now);
443    }
444  }
445
446  /// Hands the engine pacer [`rate`](Self::rate).
447  fn apply_rate(&mut self) {
448    let rate = self.rate();
449    self.pacer.pacer_mut().set_target_bitrate(rate);
450  }
451
452  /// Starts or stops pacing as feedback came or stopped.
453  fn update(&mut self, now: Instant) {
454    self.observe(now);
455    let paced = self.pacing(now);
456    if paced == self.paced {
457      return;
458    }
459    self.paced = paced;
460    self.apply_rate();
461    if !paced && self.estimate_reported {
462      // The stats stop reporting an estimate nothing is paced at.
463      self.estimate_reported = false;
464      let mut message = AttributedPacket::new(Packet::Rtcp(Vec::new()));
465      message.add(Attribute::TargetBitrateChanged {
466        bits_per_second: 0.0,
467      });
468      self.carriers.push_back(TaggedPacket {
469        now,
470        transport: Default::default(),
471        message,
472      });
473    }
474  }
475
476  /// A packet the engine pacer released: its entry leaves `held`. One that
477  /// was never held (padding the pacer made) changes nothing.
478  fn released(&mut self, ssrc: u32, sequence_number: u16) {
479    let Some(queue) = self.held.get_mut(&ssrc) else {
480      return;
481    };
482    let Some(at) = queue.iter().position(|&(seq, _, _)| seq == sequence_number)
483    else {
484      return;
485    };
486    let Some((_, _, bits)) = queue.remove(at) else {
487      return;
488    };
489    if queue.is_empty() {
490      self.held.remove(&ssrc);
491    }
492    self.held_bits = if self.held.is_empty() {
493      0.0
494    } else {
495      (self.held_bits - bits).max(0.0)
496    };
497  }
498
499  /// The engine pacer's target rate.
500  #[cfg(test)]
501  pub(crate) fn target_bitrate(&self) -> f64 {
502    self.pacer.pacer().target_bitrate()
503  }
504
505  /// The bits [`held`](Self::held) counts.
506  #[cfg(test)]
507  pub(crate) fn held_bits(&self) -> f64 {
508    self.held_bits
509  }
510}
511
512impl rtci::sansio::Protocol<TaggedPacket, TaggedPacket, ()> for FactorPacer {
513  type Rout = TaggedPacket;
514  type Wout = TaggedPacket;
515  type Eout = ();
516  type Error = rtci::shared::error::Error;
517  type Time = Instant;
518
519  fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
520    let estimate = Self::estimate(&msg);
521    let feedback = estimate.is_some() || Self::is_feedback(&msg);
522    if let Some(bits_per_second) = estimate {
523      self.estimate = bits_per_second;
524    }
525    if feedback {
526      self.last_feedback = Some(msg.now);
527    }
528    self.update(msg.now);
529    if feedback && self.paced {
530      if estimate.is_none() && !self.estimate_reported {
531        // Pacing (again) at an estimate the stats don't hold: the first
532        // report, or the first since reports stopped.
533        msg.message.add(Attribute::TargetBitrateChanged {
534          bits_per_second: self.estimate,
535        });
536      }
537      self.estimate_reported = true;
538    }
539    if estimate.is_some() && !self.paced {
540      // Not pacing (no congestion feedback negotiated, or none for
541      // FEEDBACK_TIMEOUT): the stats report no estimate, even one the
542      // controller attached without congestion feedback (rtci 0.2 does, on a
543      // connection that negotiated none).
544      msg
545        .message
546        .attributes
547        .retain(|a| !matches!(a, Attribute::TargetBitrateChanged { .. }));
548    }
549    // The engine's pacer follows an estimate going past; the scaled rate
550    // (or the pass-through's) replaces what it set.
551    self.pacer.handle_read(msg)?;
552    self.apply_rate();
553    Ok(())
554  }
555
556  fn poll_read(&mut self) -> Option<TaggedPacket> {
557    self.pacer.poll_read().or_else(|| self.carriers.pop_front())
558  }
559
560  fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
561    let Packet::Rtp(rtp) = &msg.message.packet else {
562      // RTCP: the engine's pacer passes it straight on (and takes the
563      // carriers meant for it, the streams' priorities among them).
564      return self.pacer.handle_write(msg);
565    };
566    let bytes = rtp.marshal_size();
567    let (ssrc, sequence_number) = (rtp.header.ssrc, rtp.header.sequence_number);
568    if !self.is_negotiated(rtp.header.ssrc) {
569      self.passed.push_back(msg);
570      return Ok(());
571    }
572    if self.last_feedback.is_none() && self.waiting_since.is_none() {
573      self.waiting_since = Some(msg.now);
574    }
575    self.update(msg.now);
576    if !self.paced && self.pacer.queued() == 0 {
577      self.passed.push_back(msg);
578      return Ok(());
579    }
580    let refused = self.pacer.dropped();
581    self.pacer.handle_write(msg)?;
582    if self.pacer.dropped() > refused {
583      self.refusals.add(bytes);
584      if !self.refusing {
585        self.refusing = true;
586        log::warn!(
587          "webrtc: the pacer's queue is full ({} packets); refusing RTP until it drains",
588          self.pacer.queued()
589        );
590      }
591    } else {
592      self.refusing = false;
593      let bits = (bytes * 8) as f64;
594      self.held.entry(ssrc).or_default().push_back((
595        sequence_number,
596        self.now.unwrap_or_else(Instant::now),
597        bits,
598      ));
599      self.held_bits += bits;
600      self.apply_rate();
601    }
602    Ok(())
603  }
604
605  fn poll_write(&mut self) -> Option<TaggedPacket> {
606    // What the engine pacer releases was written before anything still let
607    // through here.
608    if let Some(out) = self.pacer.poll_write() {
609      if let Packet::Rtp(rtp) = &out.message.packet {
610        self.released(rtp.header.ssrc, rtp.header.sequence_number);
611        self.apply_rate();
612      }
613      return Some(out);
614    }
615    self.passed.pop_front()
616  }
617
618  fn handle_event(&mut self, evt: ()) -> Result<(), Self::Error> {
619    self.pacer.handle_event(evt)
620  }
621
622  fn poll_event(&mut self) -> Option<()> {
623    self.pacer.poll_event()
624  }
625
626  fn handle_timeout(&mut self, now: Instant) -> Result<(), Self::Error> {
627    self.update(now);
628    self.apply_rate();
629    self.pacer.handle_timeout(now)
630  }
631
632  fn poll_timeout(&mut self) -> Option<Instant> {
633    self.pacer.poll_timeout()
634  }
635
636  fn close(&mut self) -> Result<(), Self::Error> {
637    self.pacer.close()
638  }
639}
640
641impl Interceptor for FactorPacer {
642  fn bind_local_stream(&mut self, info: &StreamInfo) {
643    if Self::paces(info) {
644      let ssrcs = std::iter::once(info.ssrc)
645        .chain(info.ssrc_rtx)
646        .chain(info.ssrc_fec)
647        .collect();
648      self.negotiated.insert(info.ssrc, ssrcs);
649    }
650    self.pacer.bind_local_stream(info);
651  }
652
653  fn unbind_local_stream(&mut self, info: &StreamInfo) {
654    self.negotiated.remove(&info.ssrc);
655    self.pacer.unbind_local_stream(info);
656  }
657
658  fn bind_remote_stream(&mut self, info: &StreamInfo) {
659    self.pacer.bind_remote_stream(info);
660  }
661
662  fn unbind_remote_stream(&mut self, info: &StreamInfo) {
663    self.pacer.unbind_remote_stream(info);
664  }
665}
666
667/// The RTP header extensions RFC 8834 section 5.2 has a WebRTC endpoint
668/// support, on top of the ones the default interceptors register (the
669/// simulcast `mid` / `rid` / `repaired-rid` for video, transport-wide
670/// congestion control for both): `mid` for audio too (5.2.4, mandatory with
671/// BUNDLE), the client-to-mixer audio level (5.2.2, RFC 6464) and the
672/// coordination of video orientation (5.2.5), and absolute capture time
673/// (abs-capture-time; RTCRtpTransceiver's header extension list starts it
674/// "stopped", so an offer carries it only once the application asks, while an
675/// answer takes it when offered). Registered after the defaults, so the ids
676/// those have stay as they were. A sender writes the audio level and the
677/// capture time (`header_extensions.rs`); the engine reads them from
678/// received packets as any other extension.
679fn register_header_extensions(
680  media_engine: &mut MediaEngine,
681) -> Result<(), Error> {
682  for (uri, kind) in [
683    (rtci::sdp::extmap::SDES_MID_URI, RtpCodecKind::Audio),
684    (rtci::sdp::extmap::AUDIO_LEVEL_URI, RtpCodecKind::Audio),
685    (
686      rtci::sdp::extmap::VIDEO_ORIENTATION_URI,
687      RtpCodecKind::Video,
688    ),
689    (
690      crate::header_extensions::ABS_CAPTURE_TIME_URI,
691      RtpCodecKind::Audio,
692    ),
693    (
694      crate::header_extensions::ABS_CAPTURE_TIME_URI,
695      RtpCodecKind::Video,
696    ),
697  ] {
698    media_engine
699      .register_header_extension(
700        RTCRtpHeaderExtensionCapability {
701          uri: uri.to_string(),
702        },
703        kind,
704        None,
705      )
706      .map_err(crate::peer::rtc_err)?;
707  }
708  Ok(())
709}
710
711pub fn parse_kind(kind: &str) -> Result<RtpCodecKind, Error> {
712  match kind {
713    "audio" => Ok(RtpCodecKind::Audio),
714    "video" => Ok(RtpCodecKind::Video),
715    other => Err(Error::new(
716      ErrorKind::Type,
717      format!("'{other}' is not a valid media kind"),
718    )),
719  }
720}
721
722fn kind_str(kind: RtpCodecKind) -> &'static str {
723  match kind {
724    RtpCodecKind::Audio => "audio",
725    RtpCodecKind::Video => "video",
726    _ => "",
727  }
728}
729
730pub fn parse_direction(
731  direction: &str,
732) -> Result<RTCRtpTransceiverDirection, Error> {
733  match RTCRtpTransceiverDirection::from(direction) {
734    RTCRtpTransceiverDirection::Unspecified => Err(Error::new(
735      ErrorKind::Type,
736      format!("'{direction}' is not a valid RTCRtpTransceiverDirection"),
737    )),
738    d => Ok(d),
739  }
740}
741
742fn direction_str(direction: RTCRtpTransceiverDirection) -> Option<String> {
743  match direction {
744    RTCRtpTransceiverDirection::Unspecified => None,
745    d => Some(d.to_string()),
746  }
747}
748
749/// `RTCRtpCodec` as JavaScript sees it: a dictionary, so a member the codec
750/// doesn't have (a video codec's `channels`, an absent fmtp line) is left
751/// out rather than `null`.
752#[derive(Serialize, Deserialize, Clone, Debug)]
753#[serde(rename_all = "camelCase")]
754pub struct CodecArg {
755  pub mime_type: String,
756  pub clock_rate: u32,
757  #[serde(default, skip_serializing_if = "Option::is_none")]
758  pub channels: Option<u16>,
759  #[serde(default, skip_serializing_if = "Option::is_none")]
760  pub sdp_fmtp_line: Option<String>,
761}
762
763impl CodecArg {
764  fn from_codec(codec: &RTCRtpCodec) -> Self {
765    let audio = codec.mime_type.to_ascii_lowercase().starts_with("audio/");
766    Self {
767      mime_type: codec.mime_type.clone(),
768      clock_rate: codec.clock_rate,
769      // An audio codec without a channel count is mono (RFC 4566's
770      // default for the rtpmap encoding parameters).
771      channels: if codec.channels > 0 {
772        Some(codec.channels)
773      } else {
774        audio.then_some(1)
775      },
776      sdp_fmtp_line: (!codec.sdp_fmtp_line.is_empty())
777        .then(|| codec.sdp_fmtp_line.clone()),
778    }
779  }
780
781  fn to_codec(&self) -> RTCRtpCodec {
782    let audio = self.mime_type.to_ascii_lowercase().starts_with("audio/");
783    RTCRtpCodec {
784      mime_type: self.mime_type.clone(),
785      clock_rate: self.clock_rate,
786      // A mono audio codec is the engine's 0 (no encoding parameter in its
787      // rtpmap), the reverse of `from_codec`: the engine matches a codec
788      // dictionary's channels exactly (W3C webrtc "codec dictionary
789      // match"), so `channels: 1`, which getCapabilities() and
790      // getParameters() report for PCMU, PCMA, G722, CN and
791      // telephone-event, would match none of its codecs.
792      channels: match self.channels {
793        Some(1) if audio => 0,
794        channels => channels.unwrap_or(0),
795      },
796      sdp_fmtp_line: self.sdp_fmtp_line.clone().unwrap_or_default(),
797      rtcp_feedback: vec![],
798    }
799  }
800}
801
802#[derive(Serialize)]
803#[serde(rename_all = "camelCase")]
804pub struct Capabilities {
805  pub(crate) codecs: Vec<CodecArg>,
806  header_extensions: Vec<HeaderExtensionCapability>,
807}
808
809#[derive(Serialize)]
810pub struct HeaderExtensionCapability {
811  uri: String,
812}
813
814/// `RTCRtpSender.getCapabilities(kind)` / `RTCRtpReceiver.getCapabilities`:
815/// what the media stack offers, read from the offer of a connection that is
816/// never used for anything else (the engine's codec lists are internal).
817/// RTX is listed once, without the `apt` that ties each RTX payload type to
818/// its primary, as browsers list it.
819pub fn capabilities(
820  kind: &str,
821  _sender: bool,
822) -> Result<Option<Capabilities>, Error> {
823  let Ok(kind_enum) = parse_kind(kind) else {
824    return Ok(None);
825  };
826  let (media_engine, registry) = media_stack()?;
827  let mut pc = RTCPeerConnectionBuilder::new()
828    .with_media_engine(media_engine)
829    .with_interceptor_registry(registry)
830    .build(Instant::now())
831    .map_err(crate::peer::rtc_err)?;
832  let index = pc
833    .add_transceiver_from_kind(
834      kind_enum,
835      Some(RTCRtpTransceiverInit {
836        direction: RTCRtpTransceiverDirection::Sendrecv,
837        streams: vec![],
838        send_encodings: vec![RTCRtpEncodingParameters::default()],
839      }),
840    )
841    .map_err(crate::peer::rtc_err)?;
842  let offer = pc.create_offer(None).map_err(crate::peer::rtc_err)?;
843  // The codecs come from the engine's registry (its own
844  // `RTCRtpSender.getCapabilities`, W3C webrtc-pc 5.2: what this side can
845  // send and receive), not read back from an offer. rtci 0.2.0 wrote every
846  // H.264 High format of an offer with level 5.0's fmtp line, so an offer
847  // read back merged them (WPT `protocol/codecs-filtered-by-direction`);
848  // since 0.2.1 each payload type carries its own fmtp (rtci jsep-83), and
849  // the registry stays the direct source. The offer gives the header
850  // extensions.
851  let registered = pc
852    .rtp_sender(index.into())
853    .and_then(|sender| sender.get_capabilities(kind_enum));
854  let _ = pc.close();
855  let mut caps = capabilities_from_sdp(kind, &offer.sdp);
856  if let Some(registered) = registered {
857    caps.codecs = codecs_from_registry(&registered.codecs);
858  }
859  Ok(Some(caps))
860}
861
862/// The engine's registered codecs as `getCapabilities()` lists them, each
863/// once: RTX without the `apt` that ties it to one primary (the engine's
864/// list already has none), every other format with its parameters, as
865/// [`capabilities_from_sdp`] lists them.
866fn codecs_from_registry(codecs: &[RTCRtpCodec]) -> Vec<CodecArg> {
867  let mut out: Vec<CodecArg> = Vec::new();
868  for codec in codecs {
869    let mut arg = CodecArg::from_codec(codec);
870    if arg.mime_type.to_ascii_lowercase().ends_with("/rtx") {
871      arg.sdp_fmtp_line = None;
872    }
873    let duplicate = out.iter().any(|c| {
874      c.mime_type.eq_ignore_ascii_case(&arg.mime_type)
875        && c.clock_rate == arg.clock_rate
876        && c.channels == arg.channels
877        && c.sdp_fmtp_line == arg.sdp_fmtp_line
878    });
879    if !duplicate {
880      out.push(arg);
881    }
882  }
883  out
884}
885
886/// The codecs (`a=rtpmap` + `a=fmtp`) and header extensions (`a=extmap`)
887/// of an SDP's media sections of `kind`.
888pub fn capabilities_from_sdp(kind: &str, sdp: &str) -> Capabilities {
889  let mut codecs: Vec<(String, CodecArg)> = Vec::new();
890  let mut fmtp: HashMap<String, String> = HashMap::new();
891  let mut header_extensions: Vec<(u16, HeaderExtensionCapability)> = Vec::new();
892  let mut in_kind = false;
893  for line in sdp.lines() {
894    let line = line.trim_end();
895    if let Some(m) = line.strip_prefix("m=") {
896      in_kind = m.split_ascii_whitespace().next() == Some(kind);
897      continue;
898    }
899    if !in_kind {
900      continue;
901    }
902    if let Some(value) = line.strip_prefix("a=rtpmap:") {
903      let Some((pt, rest)) = value.split_once(' ') else {
904        continue;
905      };
906      let mut parts = rest.split('/');
907      let name = parts.next().unwrap_or_default();
908      let clock_rate = parts.next().and_then(|c| c.parse().ok()).unwrap_or(0);
909      let channels = parts
910        .next()
911        .and_then(|c| c.parse().ok())
912        .or((kind == "audio").then_some(1));
913      codecs.push((
914        pt.to_string(),
915        CodecArg {
916          mime_type: format!("{kind}/{name}"),
917          clock_rate,
918          channels,
919          sdp_fmtp_line: None,
920        },
921      ));
922    } else if let Some(value) = line.strip_prefix("a=fmtp:") {
923      if let Some((pt, params)) = value.split_once(' ') {
924        fmtp.insert(pt.to_string(), params.to_string());
925      }
926    } else if let Some(value) = line.strip_prefix("a=extmap:")
927      && let Some(uri) = extmap_uri(value)
928    {
929      // By id: the engine writes the lines in no particular order.
930      let id = value
931        .split(|c: char| c == '/' || c.is_ascii_whitespace())
932        .next()
933        .and_then(|id| id.parse::<u16>().ok())
934        .unwrap_or(u16::MAX);
935      header_extensions.push((
936        id,
937        HeaderExtensionCapability {
938          uri: uri.to_string(),
939        },
940      ));
941    }
942  }
943  header_extensions.sort_by_key(|(id, _)| *id);
944  // An extension offered both in the clear and encrypted (RFC 6904) is one
945  // capability.
946  let mut unique: Vec<HeaderExtensionCapability> = Vec::new();
947  for (_, h) in header_extensions {
948    if !unique.iter().any(|u| u.uri == h.uri) {
949      unique.push(h);
950    }
951  }
952  let header_extensions = unique;
953  let mut out: Vec<CodecArg> = Vec::new();
954  for (pt, mut codec) in codecs {
955    // RTX is listed without the `apt` that ties its payload type to one
956    // primary. Every other format keeps its parameters, an audio RED's
957    // redundancy list (`111/111`) included, as browsers list it and as the
958    // engine registered it: setCodecPreferences() matches them exactly.
959    if !codec.mime_type.to_ascii_lowercase().ends_with("/rtx") {
960      codec.sdp_fmtp_line = fmtp.get(&pt).cloned();
961    }
962    let duplicate = out.iter().any(|c| {
963      c.mime_type.eq_ignore_ascii_case(&codec.mime_type)
964        && c.clock_rate == codec.clock_rate
965        && c.channels == codec.channels
966        && c.sdp_fmtp_line == codec.sdp_fmtp_line
967    });
968    if !duplicate {
969      out.push(codec);
970    }
971  }
972  Capabilities {
973    codecs: out,
974    header_extensions,
975  }
976}
977
978/// The RFC 6904 URI that marks an `a=extmap` line as the encrypted form of
979/// the extension it names next.
980const ENCRYPT_URI: &str = "urn:ietf:params:rtp-hdrext:encrypt";
981
982/// The extension URI of an `a=extmap` value (`<id>[/<direction>] <uri>
983/// [attributes]`); of the encrypted form (`<id>
984/// urn:ietf:params:rtp-hdrext:encrypt <uri> [attributes]`, RFC 6904 section
985/// 4, which rtci 0.2 offers for the audio level extensions beside the clear
986/// one), the URI it encrypts.
987pub(crate) fn extmap_uri(value: &str) -> Option<&str> {
988  let mut tokens = value.split_ascii_whitespace().skip(1);
989  match tokens.next()? {
990    ENCRYPT_URI => tokens.next(),
991    uri => Some(uri),
992  }
993}
994
995#[derive(Deserialize)]
996#[serde(rename_all = "camelCase")]
997pub struct TrackArg {
998  pub id: String,
999  pub label: String,
1000}
1001
1002#[derive(Deserialize, Default)]
1003#[serde(rename_all = "camelCase")]
1004pub struct EncodingArg {
1005  #[serde(default)]
1006  pub rid: Option<String>,
1007  #[serde(default = "yes")]
1008  pub active: bool,
1009}
1010
1011fn yes() -> bool {
1012  true
1013}
1014
1015#[derive(Deserialize)]
1016#[serde(rename_all = "camelCase")]
1017pub struct TransceiverArg {
1018  pub kind: String,
1019  pub track: Option<TrackArg>,
1020  pub direction: String,
1021  pub streams: Vec<String>,
1022  pub send_encodings: Vec<EncodingArg>,
1023  /// The `Deno.webrtc.EncodedMediaTrack` codec, which becomes the sender's
1024  /// preferred codec.
1025  pub codec: Option<CodecArg>,
1026  /// `addTrack` made the transceiver (not `addTransceiver`): a remote
1027  /// offer's new media section of the same kind may take it.
1028  #[serde(default)]
1029  pub add_track: bool,
1030}
1031
1032/// The stream ids of a sender's `a=msid` lines: the `MediaStream`s it is in,
1033/// or `-` for none (RFC 9429 section 5.2.1).
1034fn msid_streams(streams: Vec<String>) -> Vec<String> {
1035  if streams.is_empty() {
1036    vec!["-".to_string()]
1037  } else {
1038    streams
1039  }
1040}
1041
1042/// One m-section of the remote description, by mid.
1043#[derive(Serialize, Clone, Debug, Default)]
1044#[serde(rename_all = "camelCase")]
1045pub struct RemoteSection {
1046  /// The remote side's direction attribute (`sendrecv` / `sendonly` /
1047  /// `recvonly` / `inactive`).
1048  pub direction: String,
1049  /// The `a=msid` stream ids (`-` dropped).
1050  pub streams: Vec<String>,
1051  /// Port 0 without `a=bundle-only`: the section was rejected.
1052  pub rejected: bool,
1053  pub kind: String,
1054  /// The layers of the section's `a=simulcast` `recv` list (RFC 8853): the
1055  /// first of each layer's alternatives, without the paused marker `~`,
1056  /// each once, in the list's order.
1057  pub simulcast_recv: Vec<String>,
1058}
1059
1060/// A transceiver as JavaScript reconciles it after every operation.
1061#[derive(Serialize)]
1062#[serde(rename_all = "camelCase")]
1063pub struct TransceiverInfo {
1064  pub key: u32,
1065  pub kind: String,
1066  pub mid: Option<String>,
1067  pub direction: Option<String>,
1068  pub current_direction: Option<String>,
1069  pub remote: Option<RemoteSection>,
1070}
1071
1072/// The id of the stream a remote track with no `a=msid` is in.
1073const DEFAULT_STREAM_ID: &str = "default";
1074
1075/// The m-sections of an SDP, keyed by mid.
1076pub fn sections(sdp: &str) -> HashMap<String, RemoteSection> {
1077  let mut out = HashMap::new();
1078  let mut current: Option<(Option<String>, RemoteSection)> = None;
1079  // Whether the current section has an `a=msid` line at all.
1080  let mut has_msid = false;
1081  let mut flush = |current: &mut Option<(Option<String>, RemoteSection)>,
1082                   has_msid: bool| {
1083    if let Some((Some(mid), mut section)) = current.take() {
1084      // A media section with no `a=msid` at all (an endpoint that predates
1085      // it): its track is in one default stream (RFC 9429 section 5.10; the
1086      // id `-` means "no stream" and stays none).
1087      if !has_msid && (section.kind == "audio" || section.kind == "video") {
1088        section.streams.push(DEFAULT_STREAM_ID.to_string());
1089      }
1090      out.insert(mid, section);
1091    }
1092  };
1093  for line in sdp.lines() {
1094    let line = line.trim_end();
1095    if let Some(m) = line.strip_prefix("m=") {
1096      flush(&mut current, has_msid);
1097      has_msid = false;
1098      let mut fields = m.split_ascii_whitespace();
1099      let kind = fields.next().unwrap_or_default().to_string();
1100      let port = fields.next().unwrap_or_default();
1101      current = Some((
1102        None,
1103        RemoteSection {
1104          direction: "sendrecv".to_string(),
1105          streams: vec![],
1106          rejected: port == "0",
1107          kind,
1108          simulcast_recv: vec![],
1109        },
1110      ));
1111      continue;
1112    }
1113    let Some((mid, section)) = current.as_mut() else {
1114      continue;
1115    };
1116    let Some(attr) = line.strip_prefix("a=") else {
1117      continue;
1118    };
1119    if let Some(value) = attr.strip_prefix("mid:") {
1120      *mid = Some(value.trim().to_string());
1121    } else if let Some(value) = attr.strip_prefix("msid:") {
1122      has_msid = true;
1123      if let Some(stream) = value.split_ascii_whitespace().next()
1124        && stream != "-"
1125        && !section.streams.iter().any(|s| s == stream)
1126      {
1127        section.streams.push(stream.to_string());
1128      }
1129    } else if let Some(value) = attr.strip_prefix("simulcast:") {
1130      section.simulcast_recv = simulcast_recv_layers(value);
1131    } else if matches!(attr, "sendrecv" | "sendonly" | "recvonly" | "inactive")
1132    {
1133      section.direction = attr.to_string();
1134    } else if attr == "bundle-only" {
1135      // RFC 8843 section 6 / RFC 9429 section 5.10: port zero with
1136      // `a=bundle-only` is a section reached through its BUNDLE group, not a
1137      // rejected one.
1138      section.rejected = false;
1139    }
1140  }
1141  flush(&mut current, has_msid);
1142  out
1143}
1144
1145/// The layers of an `a=simulcast` value's `recv` list (`send 1;2 recv
1146/// a,b;~c`): the first alternative of each, `~` dropped, each once.
1147fn simulcast_recv_layers(value: &str) -> Vec<String> {
1148  let mut out: Vec<String> = Vec::new();
1149  let mut fields = value.split_ascii_whitespace();
1150  while let (Some(direction), Some(list)) = (fields.next(), fields.next()) {
1151    if !direction.eq_ignore_ascii_case("recv") {
1152      continue;
1153    }
1154    for layer in list.split(';') {
1155      let first = layer.split(',').next().unwrap_or_default();
1156      let rid = first.strip_prefix('~').unwrap_or(first);
1157      if !rid.is_empty() && !out.iter().any(|r| r == rid) {
1158        out.push(rid.to_string());
1159      }
1160    }
1161  }
1162  out
1163}
1164
1165/// The codec preferences an `EncodedMediaTrack` gives its transceiver: its
1166/// codec, then (for audio) the telephone-event formats `RTCDTMFSender`
1167/// needs, and (for video) retransmission, which a preference list leaves out
1168/// unless it lists it (W3C `setCodecPreferences`). The engine offers no FEC
1169/// format by default, and a preference it doesn't offer is refused.
1170pub fn track_preferences(codec: &CodecArg) -> Vec<CodecArg> {
1171  let mut out = vec![codec.clone()];
1172  if codec.mime_type.to_ascii_lowercase().starts_with("video/") {
1173    out.push(CodecArg {
1174      mime_type: "video/rtx".to_string(),
1175      clock_rate: 90000,
1176      channels: None,
1177      sdp_fmtp_line: None,
1178    });
1179  }
1180  if codec.mime_type.to_ascii_lowercase().starts_with("audio/") {
1181    for clock_rate in [48000, 8000] {
1182      out.push(CodecArg {
1183        mime_type: "audio/telephone-event".to_string(),
1184        clock_rate,
1185        channels: None,
1186        sdp_fmtp_line: Some("0-15".to_string()),
1187      });
1188    }
1189  }
1190  out
1191}
1192
1193/// What a sender's frames are cut into RTP packets with, per SSRC.
1194pub struct SenderPacketizer {
1195  ssrc: u32,
1196  payload_type: u8,
1197  mime_type: String,
1198  clock_rate: u32,
1199  /// The next frame's RTP timestamp.
1200  timestamp: u32,
1201  /// The size the packetizer cuts to ([`rtp_mtu`]).
1202  mtu: usize,
1203  /// The packetizer's sequence numbers, kept when only the size changes,
1204  /// so the SSRC's sequence goes on.
1205  sequencer: Box<dyn rtci::rtp::sequence::Sequencer>,
1206  packetizer: Box<dyn Packetizer>,
1207}
1208
1209/// What an encoded frame's metadata names about its sender.
1210#[derive(Serialize, Debug)]
1211#[serde(rename_all = "camelCase")]
1212pub struct SenderFrameInfo {
1213  pub synchronization_source: u32,
1214  pub payload_type: u8,
1215  pub mime_type: String,
1216  pub rtp_timestamp: u32,
1217}
1218
1219/// A fake capture device's frame, for an encoded transform.
1220///
1221/// `P` is how the frame's bytes are held ([`crate::Payload`] from the
1222/// engine); see [`FakeFrame::map_payload`].
1223#[derive(Serialize)]
1224#[serde(rename_all = "camelCase")]
1225pub struct FakeFrame<P = crate::peer::Payload> {
1226  pub data: P,
1227  pub duration_ms: f64,
1228  pub key_frame: bool,
1229  pub width_height: Option<(u16, u16)>,
1230  pub info: SenderFrameInfo,
1231  /// The RFC 6464 level (-dBov) measured from the frame's PCM, as the sender
1232  /// writes it in the audio level header extension
1233  /// (`header_extensions::audio_level`); `None` where the PCM isn't at hand
1234  /// (and for video).
1235  pub audio_level: Option<u8>,
1236}
1237
1238impl<P> FakeFrame<P> {
1239  /// The same frame with its bytes converted by `f`.
1240  pub fn map_payload<Q>(self, f: impl FnOnce(P) -> Q) -> FakeFrame<Q> {
1241    FakeFrame {
1242      data: f(self.data),
1243      duration_ms: self.duration_ms,
1244      key_frame: self.key_frame,
1245      width_height: self.width_height,
1246      info: self.info,
1247      audio_level: self.audio_level,
1248    }
1249  }
1250}
1251
1252/// Whether an encoded video frame is a key frame (audio frames are not
1253/// typed): from its bitstream.
1254pub fn is_key_frame(mime_type: &str, data: &[u8]) -> bool {
1255  match mime_type.to_ascii_lowercase().as_str() {
1256    // RFC 6386 9.1: bit 0 of the frame tag is 0 on a key frame.
1257    "video/vp8" => data.first().is_some_and(|b| b & 1 == 0),
1258    // VP9 uncompressed header: frame_marker (2), profile (2, a reserved
1259    // zero bit for profile 3), show_existing_frame, then frame_type (0 =
1260    // key).
1261    "video/vp9" => data.first().is_some_and(|b| {
1262      let profile = ((b >> 5) & 1) | (((b >> 4) & 1) << 1);
1263      let shift = if profile == 3 { 1 } else { 0 };
1264      (b >> (3 - shift)) & 1 == 0 && (b >> (2 - shift)) & 1 == 0
1265    }),
1266    "video/h264" => {
1267      nal_units(data).any(|n| n.first().is_some_and(|b| b & 0x1f == 5))
1268    }
1269    "video/h265" => nal_units(data).any(|n| {
1270      n.first()
1271        .is_some_and(|b| (16..=23).contains(&((b >> 1) & 0x3f)))
1272    }),
1273    "video/av1" => {
1274      // A sequence header OBU (type 1) starts every key frame's temporal
1275      // unit.
1276      data.iter().take(16).any(|b| (b >> 3) & 0xf == 1)
1277    }
1278    _ => false,
1279  }
1280}
1281
1282/// The NAL units of an Annex B stream.
1283fn nal_units(data: &[u8]) -> impl Iterator<Item = &[u8]> {
1284  let mut starts = Vec::new();
1285  let mut i = 0;
1286  while i + 3 <= data.len() {
1287    if data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1 {
1288      starts.push(i + 3);
1289      i += 3;
1290    } else {
1291      i += 1;
1292    }
1293  }
1294  let ends: Vec<usize> = starts
1295    .iter()
1296    .skip(1)
1297    .map(|s| s - 3)
1298    .chain(std::iter::once(data.len()))
1299    .collect();
1300  starts
1301    .into_iter()
1302    .zip(ends)
1303    .map(move |(a, b)| &data[a..b.max(a)])
1304}
1305
1306/// A key frame's size, where its bitstream says it simply (VP8).
1307pub fn frame_size(mime_type: &str, data: &[u8]) -> Option<(u16, u16)> {
1308  if !mime_type.eq_ignore_ascii_case("video/vp8")
1309    || data.len() < 10
1310    || data[0] & 1 != 0
1311    || data[3..6] != [0x9d, 0x01, 0x2a]
1312  {
1313    return None;
1314  }
1315  let w = u16::from_le_bytes([data[6], data[7]]) & 0x3fff;
1316  let h = u16::from_le_bytes([data[8], data[9]]) & 0x3fff;
1317  Some((w, h))
1318}
1319
1320/// A format no encoder produces frames in: one that repairs or protects
1321/// another's packets (RTX, RED, ULPFEC, FlexFEC; the engine's
1322/// `is_repair_codec`), comfort noise or telephone events.
1323fn is_auxiliary_mime(mime: &str) -> bool {
1324  let mime = mime.to_ascii_lowercase();
1325  let subtype = mime.split_once('/').map_or(mime.as_str(), |(_, s)| s);
1326  matches!(subtype, "rtx" | "ulpfec" | "red" | "cn" | "telephone-event")
1327    || subtype.starts_with("flexfec")
1328}
1329
1330/// One parameter of an `a=fmtp` line (`name=value;...`), lowercased.
1331fn fmtp_param(fmtp: &str, name: &str) -> Option<String> {
1332  fmtp.split(';').find_map(|p| {
1333    let (k, v) = p.split_once('=')?;
1334    k.trim()
1335      .eq_ignore_ascii_case(name)
1336      .then(|| v.trim().to_ascii_lowercase())
1337  })
1338}
1339
1340/// The negotiated format that is `wanted`: same name, clock rate and
1341/// channels, the one with the same `a=fmtp` first, else any whose
1342/// parameters describe the same bitstream (H.264's packetization mode,
1343/// VP9's profile; the rest, such as a level, the receiver's limit).
1344fn negotiated_format<'a>(
1345  codecs: &'a [RTCRtpCodecParameters],
1346  wanted: &RTCRtpCodec,
1347) -> Option<&'a RTCRtpCodecParameters> {
1348  let same = |c: &&RTCRtpCodecParameters| {
1349    c.rtp_codec
1350      .mime_type
1351      .eq_ignore_ascii_case(&wanted.mime_type)
1352      && c.rtp_codec.clock_rate == wanted.clock_rate
1353      && c.rtp_codec.channels == wanted.channels
1354  };
1355  let mime = wanted.mime_type.to_ascii_lowercase();
1356  let bitstream: &[(&str, &str)] = match mime.as_str() {
1357    "video/h264" | "video/h265" => &[("packetization-mode", "0")],
1358    "video/vp9" => &[("profile-id", "0")],
1359    "video/av1" => &[("profile", "0")],
1360    _ => &[],
1361  };
1362  codecs
1363    .iter()
1364    .filter(same)
1365    .find(|c| c.rtp_codec.sdp_fmtp_line.trim() == wanted.sdp_fmtp_line.trim())
1366    .or_else(|| {
1367      codecs.iter().filter(same).find(|c| {
1368        bitstream.iter().all(|(name, default)| {
1369          fmtp_param(&c.rtp_codec.sdp_fmtp_line, name)
1370            .unwrap_or_else(|| default.to_string())
1371            == fmtp_param(&wanted.sdp_fmtp_line, name)
1372              .unwrap_or_else(|| default.to_string())
1373        })
1374      })
1375    })
1376}
1377
1378/// The negotiated format a sender's frames go out in, with the payload type
1379/// the remote description gave it, from the engine sender's parameters as
1380/// the last applied description left them (W3C webrtc-pc 5.2: the codecs
1381/// negotiated for sending, in the remote m= line's order of preference):
1382/// - a sender fed by an `EncodedMediaTrack` sends its codec, the one its
1383///   bytes are already in: the negotiated format that is it, or none, and
1384///   then nothing is sent (another format's payload type on its bytes
1385///   would have the receiver decode them as that format);
1386/// - else the codec the first encoding names (`RTCRtpEncodingParameters`
1387///   `codec`, which the engine removes when an answer does not negotiate
1388///   it, webrtc-pc 4.4.1.6);
1389/// - else the first media format of the list (not a repair format, comfort
1390///   noise or telephone events): an answer that leads with H.264 has H.264
1391///   sent, whatever the local preferences or offer led with.
1392///
1393/// The engine's `write_rtp` rewrites a packet whose payload type is not
1394/// negotiated to its encoding's format, so a packet cut for the wrong format
1395/// would leave labelled as another: what is cut is chosen here, and always
1396/// carries a negotiated payload type.
1397pub(crate) fn sending_codec(
1398  params: &RTCRtpSendParameters,
1399  track_codec: Option<&CodecArg>,
1400) -> Option<RTCRtpCodecParameters> {
1401  let codecs: Vec<RTCRtpCodecParameters> = params
1402    .rtp_parameters
1403    .codecs
1404    .iter()
1405    .filter(|c| !is_auxiliary_mime(&c.rtp_codec.mime_type))
1406    .cloned()
1407    .collect();
1408  if let Some(track) = track_codec {
1409    return negotiated_format(&codecs, &track.to_codec()).cloned();
1410  }
1411  let named = params
1412    .encodings
1413    .first()
1414    .map(|e| &e.codec)
1415    .filter(|c| !c.mime_type.is_empty());
1416  match named {
1417    Some(codec) => negotiated_format(&codecs, codec).cloned(),
1418    None => codecs.into_iter().next(),
1419  }
1420}
1421
1422fn payloader_for(
1423  mime: &str,
1424) -> Option<Box<dyn rtci::rtp::packetizer::Payloader>> {
1425  use rtci::rtp::codec;
1426  let mime = mime.to_ascii_lowercase();
1427  Some(match mime.as_str() {
1428    "audio/opus" => Box::<codec::opus::OpusPayloader>::default(),
1429    "audio/g722" | "audio/pcmu" | "audio/pcma" => {
1430      Box::<codec::g7xx::G7xxPayloader>::default()
1431    }
1432    "video/vp8" => Box::<codec::vp8::Vp8Payloader>::default(),
1433    "video/vp9" => Box::<codec::vp9::Vp9Payloader>::default(),
1434    "video/h264" => Box::<codec::h264::H264Payloader>::default(),
1435    "video/h265" => Box::<codec::h265::HevcPayloader>::default(),
1436    "video/av1" => Box::<codec::av1::Av1Payloader>::default(),
1437    _ => return None,
1438  })
1439}
1440
1441/// RTP packets in, per transceiver key, while a reader wants them.
1442#[derive(Default)]
1443pub struct MediaState {
1444  /// Engine transceiver index -> stable key.
1445  pub keys: Vec<u32>,
1446  pub next_key: u32,
1447  /// Kinds of the transceivers, by key.
1448  pub kinds: HashMap<u32, RtpCodecKind>,
1449  /// Engine track id -> transceiver key (receivers' and senders' tracks).
1450  pub track_keys: HashMap<String, u32>,
1451  /// Keys whose receiver's RTP is read from JavaScript.
1452  pub reading: std::collections::HashSet<u32>,
1453  /// Keys whose sender's track is `null` or that a `setParameters` made
1454  /// inactive: what is written to them is dropped.
1455  pub paused: std::collections::HashSet<u32>,
1456  pub packetizers: HashMap<u32, SenderPacketizer>,
1457  /// The codec of the `EncodedMediaTrack` each sender is fed by, which the
1458  /// bytes of its `writeFrame` / `writeRtp` are in ([`sending_codec`]).
1459  pub track_codecs: HashMap<u32, CodecArg>,
1460  /// Keys whose receiver delivered its first packet (`unmute` was sent).
1461  pub flowing: std::collections::HashSet<u32>,
1462  /// The generation JavaScript gave each receiver's last mute
1463  /// (`op_webrtc_receiver_muted`); a `trackunmute` carries it, so one
1464  /// queued before a newer mute is told apart.
1465  pub unmute_generation: HashMap<u32, u32>,
1466  /// RFC 4733 state per sender: the next sequence number and timestamp.
1467  pub dtmf: HashMap<u32, (u16, u32)>,
1468  /// The SSRCs and CSRCs each receiver got packets from, for
1469  /// `getSynchronizationSources()` / `getContributingSources()`.
1470  pub sources: HashMap<u32, Vec<Source>>,
1471  /// Where each sender fed by a fake capture device is in its clip.
1472  pub fake: HashMap<u32, crate::fake_media::Cursor>,
1473  /// The encoded video frames each outbound RTP stream (by SSRC) took and
1474  /// sent, which the engine counts only when told (webrtc-stats encoder
1475  /// members: the encoder is upstream of the sender here).
1476  pub sent_video: HashMap<u32, SentVideo>,
1477  /// The complete video frames each inbound RTP stream (by SSRC) brought.
1478  pub received_video: HashMap<u32, ReceivedVideo>,
1479  /// What this connection's pacer refused ([`FactorPacer`]).
1480  pub pacer_refusals: Arc<PacerRefusals>,
1481  /// When each inbound stream (by SSRC) last asked its sender for a key
1482  /// frame after a loss ([`KEY_FRAME_REQUEST_INTERVAL`]).
1483  pub loss_key_frame_requests: HashMap<u32, Instant>,
1484  /// The largest datagram (UDP payload) the connection's path carries, the
1485  /// smallest the engine reported (`OnPathMtuExceeded`); `None` until a
1486  /// report. Senders' packets are cut for it ([`rtp_mtu`]).
1487  pub path_datagram_limit: Option<usize>,
1488}
1489
1490impl MediaState {
1491  /// A path carries datagrams of at most `max_datagram` octets: never
1492  /// raised (RFC 8201 section 4), as the engine's own estimate.
1493  pub(crate) fn limit_datagrams(&mut self, max_datagram: usize) {
1494    self.path_datagram_limit = Some(
1495      self
1496        .path_datagram_limit
1497        .map_or(max_datagram, |limit| limit.min(max_datagram)),
1498    );
1499  }
1500}
1501
1502/// How often a receiver whose stream lost a frame asks the sender for a key
1503/// frame again while no key frame came: once per SSRC per this interval, as
1504/// libwebrtc paces its repeated requests. Each delta frame after the loss
1505/// would otherwise send one.
1506pub const KEY_FRAME_REQUEST_INTERVAL: std::time::Duration =
1507  std::time::Duration::from_millis(500);
1508
1509/// What an outbound video stream's frames were, as they reached its sender:
1510/// encoded frames, from a fake capture device's clip, an
1511/// `EncodedMediaTrack` or an encoded transform. Only what the frames
1512/// themselves show is counted (their number, key frames from the bitstream,
1513/// their coded size, their byte size); the encoder's own measures (QP,
1514/// encode time, quality limitation) are not known here and stay absent.
1515#[derive(Debug, Default)]
1516pub struct SentVideo {
1517  pub frames_encoded: u32,
1518  pub key_frames_encoded: u32,
1519  pub frames_sent: u32,
1520  pub huge_frames_sent: u32,
1521  /// Bytes of the frames sent, for their average size.
1522  pub bytes_sent: u64,
1523  /// The coded size of the last frame that named one.
1524  pub size: Option<(u32, u32)>,
1525  /// When each frame of the last second reached the sender.
1526  pub recent: std::collections::VecDeque<Instant>,
1527}
1528
1529/// webrtc-stats `hugeFramesSent`: a frame at least 2.5 times the average
1530/// size of the frames sent before it.
1531const HUGE_FRAME_FACTOR: f64 = 2.5;
1532
1533impl SentVideo {
1534  /// Frames that reached the sender in the second up to `now`
1535  /// (`framesPerSecond`).
1536  pub fn frames_per_second(&mut self, now: Instant) -> f64 {
1537    while self.recent.front().is_some_and(|t| {
1538      now.saturating_duration_since(*t) > std::time::Duration::from_secs(1)
1539    }) {
1540      self.recent.pop_front();
1541    }
1542    self.recent.len() as f64
1543  }
1544
1545  /// One encoded frame reached the sender at `now`; `sent` when its packets
1546  /// went out.
1547  pub(crate) fn frame(
1548    &mut self,
1549    mime_type: &str,
1550    data: &[u8],
1551    sent: bool,
1552    now: Instant,
1553  ) {
1554    self.frames_encoded = self.frames_encoded.saturating_add(1);
1555    if is_key_frame(mime_type, data) {
1556      self.key_frames_encoded = self.key_frames_encoded.saturating_add(1);
1557    }
1558    if let Some(size) = crate::media_sink::frame_coded_size(mime_type, data) {
1559      self.size = Some(size);
1560    }
1561    self.recent.push_back(now);
1562    self.frames_per_second(now);
1563    if !sent {
1564      return;
1565    }
1566    if self.frames_sent > 0 {
1567      let average = self.bytes_sent as f64 / self.frames_sent as f64;
1568      if data.len() as f64 >= HUGE_FRAME_FACTOR * average {
1569        self.huge_frames_sent = self.huge_frames_sent.saturating_add(1);
1570      }
1571    }
1572    self.frames_sent = self.frames_sent.saturating_add(1);
1573    self.bytes_sent = self.bytes_sent.saturating_add(data.len() as u64);
1574  }
1575
1576  fn update(&mut self, now: Instant) -> rtci::statistics::EncoderStatsUpdate {
1577    rtci::statistics::EncoderStatsUpdate {
1578      frames_encoded: Some(self.frames_encoded),
1579      key_frames_encoded: Some(self.key_frames_encoded),
1580      frames_sent: Some(self.frames_sent),
1581      huge_frames_sent: Some(self.huge_frames_sent),
1582      frame_width: self.size.map(|(w, _)| w),
1583      frame_height: self.size.map(|(_, h)| h),
1584      frames_per_second: Some(self.frames_per_second(now)),
1585      ..Default::default()
1586    }
1587  }
1588}
1589
1590/// The frames of an inbound video stream as its packets arrive: a frame is
1591/// complete (webrtc-stats `framesReceived`) when its packets, from the one
1592/// after the previous frame's last (RTP marker) packet through its own
1593/// marker packet, all arrived in sequence. There is no jitter buffer, so a
1594/// frame with a packet missing or out of order is not counted, as the frame
1595/// assemblers (`encoded_frames.rs`) drop it; the first frame, whose start
1596/// can't be told, is not counted either.
1597#[derive(Debug, Default)]
1598pub struct ReceivedVideo {
1599  pub frames_received: u32,
1600  /// The RTP timestamp of the frame in the making.
1601  timestamp: Option<u32>,
1602  /// The sequence number the next packet should have.
1603  next: Option<u16>,
1604  /// Whether the frame in the making lost a packet (or its start).
1605  broken: bool,
1606  /// Whether the last packet ended a frame.
1607  ended: bool,
1608}
1609
1610impl ReceivedVideo {
1611  /// A received packet without a payload: padding, or a ULPFEC packet of a
1612  /// RED stream (the engine delivers it emptied). It carries no frame but
1613  /// takes a sequence number of the stream, so the next packet is still in
1614  /// sequence after it; one that comes after a gap leaves the next frame
1615  /// uncounted, as its start may be what was lost.
1616  pub fn empty(&mut self, header: &rtci::rtp::Header) {
1617    if self.next != Some(header.sequence_number) {
1618      self.broken = true;
1619      self.ended = false;
1620    }
1621    self.next = Some(header.sequence_number.wrapping_add(1));
1622  }
1623
1624  /// A received packet with a payload; returns whether it completed a frame.
1625  pub fn packet(&mut self, header: &rtci::rtp::Header) -> bool {
1626    let in_sequence = self.next == Some(header.sequence_number);
1627    if self.timestamp != Some(header.timestamp) {
1628      // A new frame starts whole only right after a frame's last packet.
1629      self.timestamp = Some(header.timestamp);
1630      self.broken = !(self.ended && in_sequence);
1631    } else if !in_sequence {
1632      self.broken = true;
1633    }
1634    self.next = Some(header.sequence_number.wrapping_add(1));
1635    self.ended = header.marker;
1636    if !header.marker {
1637      return false;
1638    }
1639    self.timestamp = None;
1640    if self.broken {
1641      return false;
1642    }
1643    self.frames_received = self.frames_received.saturating_add(1);
1644    true
1645  }
1646}
1647
1648/// At most this many inbound video streams are followed per connection.
1649const MAX_RECEIVED_VIDEO_STREAMS: usize = 64;
1650
1651/// A synchronization or contributing source a receiver heard from.
1652#[derive(Clone, Debug)]
1653pub struct Source {
1654  pub source: u32,
1655  pub contributing: bool,
1656  /// When its last packet arrived, in ms since the epoch.
1657  pub timestamp: f64,
1658  pub rtp_timestamp: u32,
1659}
1660
1661/// Sources older than this are not reported (the spec's 10 seconds).
1662const SOURCE_LIFETIME_MS: f64 = 10_000.0;
1663
1664fn epoch_ms() -> f64 {
1665  std::time::SystemTime::now()
1666    .duration_since(std::time::UNIX_EPOCH)
1667    .map(|d| d.as_secs_f64() * 1000.0)
1668    .unwrap_or(0.0)
1669}
1670
1671impl MediaState {
1672  /// Records the sources of a received RTP packet.
1673  pub fn saw_rtp(&mut self, key: u32, header: &rtci::rtp::Header) {
1674    let now = epoch_ms();
1675    let list = self.sources.entry(key).or_default();
1676    let mut upsert = |source: u32, contributing: bool| {
1677      match list
1678        .iter_mut()
1679        .find(|s| s.source == source && s.contributing == contributing)
1680      {
1681        Some(s) => {
1682          s.timestamp = now;
1683          s.rtp_timestamp = header.timestamp;
1684        }
1685        None => {
1686          // Bounded: a stream can't carry more than 15 CSRCs a packet,
1687          // and stale ones are dropped below.
1688          list.push(Source {
1689            source,
1690            contributing,
1691            timestamp: now,
1692            rtp_timestamp: header.timestamp,
1693          });
1694        }
1695      }
1696    };
1697    upsert(header.ssrc, false);
1698    for csrc in &header.csrc {
1699      upsert(*csrc, true);
1700    }
1701    list.retain(|s| now - s.timestamp <= SOURCE_LIFETIME_MS);
1702  }
1703}
1704
1705impl Core {
1706  /// A received RTP packet of a video receiver, for its stream's
1707  /// `framesReceived` (padding-only packets carry no frame).
1708  pub(crate) fn count_received_frame(
1709    &mut self,
1710    key: u32,
1711    packet: &rtci::rtp::Packet,
1712  ) {
1713    if self.media.kinds.get(&key) != Some(&RtpCodecKind::Video) {
1714      return;
1715    }
1716    let ssrc = packet.header.ssrc;
1717    let streams = &mut self.media.received_video;
1718    if !streams.contains_key(&ssrc)
1719      && streams.len() >= MAX_RECEIVED_VIDEO_STREAMS
1720    {
1721      return;
1722    }
1723    let video = streams.entry(ssrc).or_default();
1724    if packet.payload.is_empty() {
1725      video.empty(&packet.header);
1726      return;
1727    }
1728    if video.packet(&packet.header) {
1729      let frames_received = video.frames_received;
1730      self.pc.update_decoder_stats(
1731        ssrc,
1732        rtci::statistics::DecoderStatsUpdate {
1733          frames_received: Some(frames_received),
1734          ..Default::default()
1735        },
1736      );
1737    }
1738  }
1739
1740  /// Brings the members measured over a window (`framesPerSecond`) up to
1741  /// `now` before a report.
1742  pub(crate) fn refresh_media_stats(&mut self, now: Instant) {
1743    for (ssrc, video) in &mut self.media.sent_video {
1744      let frames_per_second = video.frames_per_second(now);
1745      self.pc.update_encoder_stats(
1746        *ssrc,
1747        rtci::statistics::EncoderStatsUpdate {
1748          frames_per_second: Some(frames_per_second),
1749          ..Default::default()
1750        },
1751      );
1752    }
1753  }
1754}
1755
1756impl MediaState {
1757  fn new_key(&mut self) -> u32 {
1758    self.next_key += 1;
1759    self.next_key
1760  }
1761}
1762
1763impl Core {
1764  /// Gives every engine transceiver a key (new ones are appended by the
1765  /// engine).
1766  pub(crate) fn sync_transceiver_keys(&mut self) {
1767    let count = self.pc.get_transceivers().count();
1768    while self.media.keys.len() < count {
1769      let key = self.media.new_key();
1770      let index = self.media.keys.len();
1771      self.media.keys.push(key);
1772      let kind = self
1773        .pc
1774        .rtp_receiver(index.into())
1775        .map(|r| r.track().kind())
1776        .filter(|k| *k != RtpCodecKind::Unspecified)
1777        .or_else(|| {
1778          self
1779            .pc
1780            .rtp_sender(index.into())
1781            .and_then(|s| s.track().map(|t| t.kind()))
1782        });
1783      if let Some(kind) = kind.filter(|k| *k != RtpCodecKind::Unspecified) {
1784        self.media.kinds.insert(key, kind);
1785      }
1786    }
1787  }
1788
1789  /// After a description (or a rollback): drops the keys of the transceivers
1790  /// the engine removed from its set, which moves the later ones down (a
1791  /// rollback undoing the remote offer that created them, RFC 9429 section
1792  /// 5.7; an answer leaving a stopped transceiver's m= section rejected, W3C
1793  /// webrtc-pc 4.4.1.6), then keys the ones it added. The engine reports
1794  /// each removal by the index the transceiver had then, in removal order,
1795  /// so removing them in that order keeps the keys in step. An index past
1796  /// the keys is a transceiver the same call added and removed again.
1797  pub(crate) fn sync_removed_transceivers(&mut self) {
1798    for index in self.pc.take_removed_transceivers() {
1799      if index >= self.media.keys.len() {
1800        continue;
1801      }
1802      let key = self.media.keys.remove(index);
1803      self.forget_transceiver(key);
1804    }
1805    self.sync_transceiver_keys();
1806  }
1807
1808  /// Per-key state of a transceiver that left the set.
1809  fn forget_transceiver(&mut self, key: u32) {
1810    let media = &mut self.media;
1811    media.kinds.remove(&key);
1812    media.track_keys.retain(|_, k| *k != key);
1813    media.reading.remove(&key);
1814    media.paused.remove(&key);
1815    media.packetizers.remove(&key);
1816    media.track_codecs.remove(&key);
1817    media.flowing.remove(&key);
1818    media.dtmf.remove(&key);
1819    media.sources.remove(&key);
1820    media.fake.remove(&key);
1821  }
1822
1823  pub(crate) fn index_of(&self, key: u32) -> Result<usize, Error> {
1824    self
1825      .media
1826      .keys
1827      .iter()
1828      .position(|k| *k == key)
1829      .ok_or_else(|| {
1830        Error::new(
1831          ErrorKind::InvalidState,
1832          "The transceiver is gone".to_string(),
1833        )
1834      })
1835  }
1836
1837  pub(crate) fn add_transceiver(
1838    &mut self,
1839    arg: TransceiverArg,
1840  ) -> Result<u32, Error> {
1841    let kind = parse_kind(&arg.kind)?;
1842    let direction = parse_direction(&arg.direction)?;
1843    // Every W3C transceiver has a sender and a receiver: the engine's are
1844    // made by creating it sendrecv (a sender needs an encoding there), then
1845    // the asked-for direction is set.
1846    let mut encodings: Vec<RTCRtpEncodingParameters> = arg
1847      .send_encodings
1848      .iter()
1849      .map(|e| RTCRtpEncodingParameters {
1850        rtp_coding_parameters: RTCRtpCodingParameters {
1851          rid: e.rid.clone().unwrap_or_default(),
1852          ..Default::default()
1853        },
1854        active: e.active,
1855        codec: arg
1856          .codec
1857          .as_ref()
1858          .map(CodecArg::to_codec)
1859          .unwrap_or_default(),
1860        ..Default::default()
1861      })
1862      .collect();
1863    if encodings.is_empty() {
1864      encodings.push(RTCRtpEncodingParameters {
1865        active: true,
1866        codec: arg
1867          .codec
1868          .as_ref()
1869          .map(CodecArg::to_codec)
1870          .unwrap_or_default(),
1871        ..Default::default()
1872      });
1873    }
1874    let init = RTCRtpTransceiverInit {
1875      direction: RTCRtpTransceiverDirection::Sendrecv,
1876      streams: arg.streams.clone(),
1877      send_encodings: encodings.clone(),
1878    };
1879    let index = match &arg.track {
1880      Some(track) => {
1881        let stream = msid_streams(arg.streams.clone()).remove(0);
1882        let engine_track = MediaStreamTrack::new(
1883          stream,
1884          track.id.clone(),
1885          track.label.clone(),
1886          kind,
1887          encodings,
1888        );
1889        self
1890          .pc
1891          .add_transceiver_from_track(engine_track, Some(init))
1892          .map_err(crate::peer::rtc_err)?
1893      }
1894      None => self
1895        .pc
1896        .add_transceiver_from_kind(kind, Some(init))
1897        .map_err(crate::peer::rtc_err)?,
1898    };
1899    self.sync_transceiver_keys();
1900    let key = self.media.keys[index];
1901    self.media.kinds.insert(key, kind);
1902    if let Some(mut sender) = self.pc.rtp_sender(index.into()) {
1903      sender
1904        .set_streams(msid_streams(arg.streams))
1905        .map_err(crate::peer::rtc_err)?;
1906      // A transceiver made from a kind has no engine track (W3C null).
1907      if let Some(track) = sender.track() {
1908        let id = track.track_id().to_string();
1909        self.media.track_keys.insert(id, key);
1910      }
1911    }
1912    // RFC 9429 section 5.10: a remote offer's new media section takes a
1913    // transceiver `addTrack` created, never one `addTransceiver` did.
1914    if !arg.add_track
1915      && let Some(mut t) = self.pc.rtp_transceiver(index)
1916    {
1917      t.set_associable_with_remote_offer(false);
1918    }
1919    if arg.track.is_none() {
1920      self.media.paused.insert(key);
1921    }
1922    if let Some(codec) = &arg.codec {
1923      self.media.track_codecs.insert(key, codec.clone());
1924      let _ =
1925        self.set_codec_preferences_inner(index, &track_preferences(codec));
1926    }
1927    if direction != RTCRtpTransceiverDirection::Sendrecv
1928      && let Some(mut t) = self.pc.rtp_transceiver(index)
1929    {
1930      t.set_direction(direction).map_err(crate::peer::rtc_err)?;
1931    }
1932    Ok(key)
1933  }
1934
1935  /// `addTrack` onto a transceiver JavaScript chose for reuse: the sender
1936  /// takes the track (its id and streams go in the msid) and starts sending.
1937  /// A transceiver a remote offer created has no engine sender until now; the
1938  /// engine hands out a sender only while the direction sends, so the
1939  /// direction gains `send` first. One `addTransceiver` created stays out of a
1940  /// remote offer's new m-sections (WPT checkAddTransceiverThenAddTrackPairs:
1941  /// browsers keep it unassociable), and `addTrack` keeps a transceiver a
1942  /// rolled-back remote offer created (W3C 4.4.1.6).
1943  pub(crate) fn attach_track(
1944    &mut self,
1945    key: u32,
1946    track: TrackArg,
1947    streams: Vec<String>,
1948  ) -> Result<(), Error> {
1949    let index = self.index_of(key)?;
1950    let kind = self.media.kinds.get(&key).copied().unwrap_or_default();
1951    let streams = msid_streams(streams);
1952    let stream = streams[0].clone();
1953    if let Some(mut t) = self.pc.rtp_transceiver(index) {
1954      let has_recv = t.direction().has_recv();
1955      t.set_direction(RTCRtpTransceiverDirection::from_send_recv(
1956        true, has_recv,
1957      ))
1958      .map_err(crate::peer::rtc_err)?;
1959      t.keep_on_rollback();
1960    }
1961    let has_sender = self
1962      .pc
1963      .rtp_transceiver(index)
1964      .is_some_and(|t| t.sender().is_some());
1965    if !has_sender {
1966      self
1967        .pc
1968        .add_track_to_transceiver(
1969          index,
1970          MediaStreamTrack::new(
1971            stream,
1972            track.id.clone(),
1973            track.label,
1974            kind,
1975            vec![RTCRtpEncodingParameters {
1976              active: true,
1977              ..Default::default()
1978            }],
1979          ),
1980        )
1981        .map_err(crate::peer::rtc_err)?;
1982      if let Some(mut sender) = self.pc.rtp_sender(index.into()) {
1983        sender.set_streams(streams).map_err(crate::peer::rtc_err)?;
1984      }
1985      self.media.track_keys.insert(track.id, key);
1986      self.media.paused.remove(&key);
1987      return Ok(());
1988    }
1989    let Some(mut sender) = self.pc.rtp_sender(index.into()) else {
1990      return Err(Error::new(
1991        ErrorKind::InvalidState,
1992        "The transceiver has no sender".to_string(),
1993      ));
1994    };
1995    // A sender made from a kind has no engine track: the new one takes one
1996    // active encoding, unless the sender has encodings of its own (which
1997    // the engine keeps, with their SSRCs).
1998    let codings = sender.track().map_or_else(
1999      || {
2000        vec![RTCRtpEncodingParameters {
2001          active: true,
2002          ..Default::default()
2003        }]
2004      },
2005      |t| t.codings().to_vec(),
2006    );
2007    let old = sender.track().map(|t| t.track_id().to_string());
2008    sender
2009      .replace_track(Some(MediaStreamTrack::new(
2010        stream,
2011        track.id.clone(),
2012        track.label,
2013        kind,
2014        codings,
2015      )))
2016      .map_err(crate::peer::rtc_err)?;
2017    sender.set_streams(streams).map_err(crate::peer::rtc_err)?;
2018    if let Some(old) = old {
2019      self.media.track_keys.remove(&old);
2020    }
2021    self.media.track_keys.insert(track.id, key);
2022    self.media.paused.remove(&key);
2023    Ok(())
2024  }
2025
2026  /// A transceiver a remote offer created has no engine sender. Made to send
2027  /// (a sending direction, or `replaceTrack` with a track) without `addTrack`,
2028  /// it gets one: SSRCs in the answer, an outbound stream. A rollback still
2029  /// removes it (only `addTrack` keeps it).
2030  fn ensure_sender(&mut self, key: u32) {
2031    if let Ok(index) = self.index_of(key) {
2032      let _ = self.pc.ensure_transceiver_sender(index);
2033    }
2034  }
2035
2036  pub(crate) fn set_sender_paused(&mut self, key: u32, paused: bool) {
2037    if paused {
2038      self.media.paused.insert(key);
2039    } else {
2040      self.ensure_sender(key);
2041      self.media.paused.remove(&key);
2042    }
2043  }
2044
2045  /// The sender's track changed: `codec` is the new track's when it is an
2046  /// `EncodedMediaTrack` (what its frames are in), `None` for any other
2047  /// track or none.
2048  pub(crate) fn set_sender_track_codec(
2049    &mut self,
2050    key: u32,
2051    codec: Option<CodecArg>,
2052  ) {
2053    match codec {
2054      Some(codec) => {
2055        self.media.track_codecs.insert(key, codec);
2056      }
2057      None => {
2058        self.media.track_codecs.remove(&key);
2059      }
2060    }
2061  }
2062
2063  pub(crate) fn set_streams(
2064    &mut self,
2065    key: u32,
2066    streams: Vec<String>,
2067  ) -> Result<(), Error> {
2068    let index = self.index_of(key)?;
2069    if let Some(mut sender) = self.pc.rtp_sender(index.into()) {
2070      sender
2071        .set_streams(msid_streams(streams))
2072        .map_err(crate::peer::rtc_err)?;
2073    }
2074    Ok(())
2075  }
2076
2077  pub(crate) fn set_direction(
2078    &mut self,
2079    key: u32,
2080    direction: &str,
2081  ) -> Result<(), Error> {
2082    let direction = parse_direction(direction)?;
2083    let index = self.index_of(key)?;
2084    if direction.has_send() {
2085      self.ensure_sender(key);
2086    }
2087    if let Some(mut t) = self.pc.rtp_transceiver(index) {
2088      t.set_direction(direction).map_err(crate::peer::rtc_err)?;
2089    }
2090    Ok(())
2091  }
2092
2093  pub(crate) fn stop_transceiver(&mut self, key: u32) -> Result<(), Error> {
2094    let index = self.index_of(key)?;
2095    self.media.paused.insert(key);
2096    self.media.reading.remove(&key);
2097    if let Some(mut t) = self.pc.rtp_transceiver(index) {
2098      t.stop().map_err(crate::peer::rtc_err)?;
2099    }
2100    Ok(())
2101  }
2102
2103  fn set_codec_preferences_inner(
2104    &mut self,
2105    index: usize,
2106    codecs: &[CodecArg],
2107  ) -> Result<(), Error> {
2108    let kind = self
2109      .media
2110      .kinds
2111      .get(&self.media.keys[index])
2112      .copied()
2113      .unwrap_or_default();
2114    let params: Vec<RTCRtpCodecParameters> = codecs
2115      .iter()
2116      .map(|c| RTCRtpCodecParameters {
2117        rtp_codec: c.to_codec(),
2118        payload_type: 0,
2119      })
2120      .collect();
2121    if let Some(mut t) = self.pc.rtp_transceiver(index) {
2122      t.set_codec_preferences(params).map_err(|e| {
2123        Error::new(
2124          ErrorKind::InvalidModification,
2125          format!("setCodecPreferences: {e} ({} codec)", kind_str(kind)),
2126        )
2127      })?;
2128    }
2129    Ok(())
2130  }
2131
2132  pub(crate) fn set_codec_preferences(
2133    &mut self,
2134    key: u32,
2135    codecs: Vec<CodecArg>,
2136  ) -> Result<(), Error> {
2137    let index = self.index_of(key)?;
2138    self.set_codec_preferences_inner(index, &codecs)
2139  }
2140
2141  /// `setHeaderExtensionsToNegotiate()` and its effect on the next offer or
2142  /// answer (webrtc-extensions): the URIs this transceiver's media section
2143  /// may carry. JavaScript hands the list over before each offer and answer.
2144  pub(crate) fn set_header_extensions_to_negotiate(
2145    &mut self,
2146    key: u32,
2147    uris: Vec<String>,
2148  ) -> Result<(), Error> {
2149    let index = self.index_of(key)?;
2150    let Some(mut t) = self.pc.rtp_transceiver(index) else {
2151      return Ok(());
2152    };
2153    // The engine takes the whole list with a direction per extension: the
2154    // ones JavaScript names are negotiated (an extension stopped before
2155    // comes back "sendrecv"), the others "stopped".
2156    let list: Vec<RTCRtpHeaderExtensionToNegotiate> = t
2157      .get_header_extensions_to_negotiate()
2158      .into_iter()
2159      .map(|mut e| {
2160        if !uris.contains(&e.uri) {
2161          e.direction = RTCRtpTransceiverDirection::Stopped;
2162        } else if e.direction == RTCRtpTransceiverDirection::Stopped {
2163          e.direction = RTCRtpTransceiverDirection::Sendrecv;
2164        }
2165        e
2166      })
2167      .collect();
2168    // JavaScript refuses to stop an extension every WebRTC endpoint must
2169    // implement (webrtc-extensions; RFC 8834 section 5.2), as the engine
2170    // does: what reaches here is what the engine takes.
2171    t.set_header_extensions_to_negotiate(list)
2172      .map_err(|e| Error::new(ErrorKind::InvalidModification, e.to_string()))?;
2173    Ok(())
2174  }
2175
2176  /// `RTCConfiguration.rtpHeaderEncryptionPolicy` and
2177  /// `alwaysNegotiateDataChannels` (webrtc-extensions).
2178  pub(crate) fn set_negotiation_options(
2179    &mut self,
2180    rtp_header_encryption_policy: &str,
2181    always_negotiate_data_channels: bool,
2182  ) -> Result<(), Error> {
2183    let policy = match rtp_header_encryption_policy {
2184      "disable" => RTCRtpHeaderEncryptionPolicy::Disable,
2185      "negotiate" => RTCRtpHeaderEncryptionPolicy::Negotiate,
2186      "require" => RTCRtpHeaderEncryptionPolicy::Require,
2187      other => {
2188        return Err(Error::new(
2189          ErrorKind::Type,
2190          format!("'{other}' is not a valid RTCRtpHeaderEncryptionPolicy"),
2191        ));
2192      }
2193    };
2194    self
2195      .pc
2196      .set_rtp_header_encryption_policy(policy)
2197      .map_err(crate::peer::rtc_err)?;
2198    self
2199      .pc
2200      .set_always_negotiate_data_channels(always_negotiate_data_channels)
2201      .map_err(crate::peer::rtc_err)?;
2202    Ok(())
2203  }
2204
2205  pub(crate) fn transceivers(&mut self) -> Vec<TransceiverInfo> {
2206    self.sync_transceiver_keys();
2207    let remote = self
2208      .pc
2209      .remote_description()
2210      .map(|d| sections(&d.sdp))
2211      .unwrap_or_default();
2212    let mut out = Vec::with_capacity(self.media.keys.len());
2213    for (index, key) in self.media.keys.clone().into_iter().enumerate() {
2214      let Some(t) = self.pc.rtp_transceiver(index) else {
2215        continue;
2216      };
2217      let mid = t.mid().clone();
2218      let direction = direction_str(t.direction());
2219      let current_direction = t.current_direction().and_then(direction_str);
2220      let section = mid.as_ref().and_then(|m| remote.get(m)).cloned();
2221      // The remote side doesn't send on this section (now): its track is
2222      // muted, and the next RTP that arrives unmutes it again.
2223      if section.as_ref().is_some_and(|s| {
2224        s.rejected || !matches!(s.direction.as_str(), "sendrecv" | "sendonly")
2225      }) {
2226        self.media.flowing.remove(&key);
2227      }
2228      let kind = match self.media.kinds.get(&key) {
2229        Some(kind) => kind_str(*kind).to_string(),
2230        None => {
2231          let kind = section
2232            .as_ref()
2233            .and_then(|s| parse_kind(&s.kind).ok())
2234            .unwrap_or_default();
2235          if kind != RtpCodecKind::Unspecified {
2236            self.media.kinds.insert(key, kind);
2237          }
2238          kind_str(kind).to_string()
2239        }
2240      };
2241      // A receiver's engine track id reaches the RTP it delivers.
2242      if let Some(r) = self.pc.rtp_receiver(index.into()) {
2243        let id = r.track().track_id().to_string();
2244        if !id.is_empty() {
2245          self.media.track_keys.insert(id, key);
2246        }
2247      }
2248      out.push(TransceiverInfo {
2249        key,
2250        kind,
2251        mid,
2252        direction,
2253        current_direction,
2254        remote: section,
2255      });
2256    }
2257    out
2258  }
2259
2260  /// The codecs of the transceiver's m-section in the current local
2261  /// (`local`) or remote description, in the section's order.
2262  fn negotiated_section_codecs(
2263    &mut self,
2264    index: usize,
2265    local: bool,
2266  ) -> Option<(String, Vec<(u8, CodecArg)>)> {
2267    let mid = self.pc.rtp_transceiver(index)?.mid().clone()?;
2268    let sdp = if local {
2269      self
2270        .pc
2271        .current_local_description()
2272        .or(self.pc.pending_local_description())
2273        .map(|d| d.sdp)
2274    } else {
2275      self
2276        .pc
2277        .current_remote_description()
2278        .or(self.pc.remote_description())
2279        .map(|d| d.sdp.clone())
2280    }?;
2281    section_codecs(&sdp, &mid)
2282  }
2283
2284  pub(crate) fn sender_parameters(
2285    &mut self,
2286    key: u32,
2287  ) -> Result<serde_json::Value, Error> {
2288    let index = self.index_of(key)?;
2289    // webrtc-pc 5.2 getParameters(): the codecs negotiated for sending. The
2290    // set is the engine's own (its sender's codecs: the formats of the
2291    // remote description this side can send, since rtci 0.3 also those a
2292    // remote answer added beyond the offer, RFC 9429 5.11, DENEXT.md item
2293    // 572); each is written as the remote description has it (its payload
2294    // type and fmtp line, RFC 9429 5.3.1), in the remote m= line's order of
2295    // preference.
2296    let remote_section = self.negotiated_section_codecs(index, false);
2297    let remote_codecs = remote_section
2298      .clone()
2299      .map(|(kind, codecs)| sendable_codecs(&kind, codecs));
2300    let Some(mut sender) = self.pc.rtp_sender(index.into()) else {
2301      // A transceiver a remote offer made has no engine sender until it
2302      // sends; what it may send is negotiated all the same.
2303      return Ok(match remote_codecs {
2304        Some(codecs) => serde_json::json!({
2305          "codecs": codecs
2306            .iter()
2307            .map(|(pt, c)| section_codec_json(*pt, c))
2308            .collect::<Vec<_>>(),
2309          "headerExtensions": [],
2310          "encodings": [],
2311        }),
2312        None => serde_json::Value::Null,
2313      });
2314    };
2315    let params = sender.get_parameters().clone();
2316    let codecs = match remote_codecs {
2317      // The engine holds no send codecs for a transceiver negotiated not
2318      // to send; getParameters() lists what the remote side would take all
2319      // the same (WPT RTCRtpParameters-codecs "should have codecs after
2320      // negotiation", a recvonly answerer).
2321      Some(codecs) if params.rtp_parameters.codecs.is_empty() => codecs
2322        .iter()
2323        .map(|(pt, c)| section_codec_json(*pt, c))
2324        .collect(),
2325      Some(_) => negotiated_send_codecs(
2326        &params.rtp_parameters.codecs,
2327        remote_section
2328          .as_ref()
2329          .map_or(&[][..], |(_, c)| c.as_slice()),
2330      ),
2331      None => params
2332        .rtp_parameters
2333        .codecs
2334        .iter()
2335        .map(codec_params_json)
2336        .collect(),
2337    };
2338    Ok(serde_json::json!({
2339      "codecs": codecs,
2340      "headerExtensions": params.rtp_parameters.header_extensions.iter().map(|h| serde_json::json!({
2341        "uri": h.uri, "id": h.id, "encrypted": h.encrypted,
2342      })).collect::<Vec<_>>(),
2343      "encodings": params.encodings.iter().map(|e| serde_json::json!({
2344        "rid": e.rtp_coding_parameters.rid,
2345        "ssrc": e.rtp_coding_parameters.ssrc,
2346      })).collect::<Vec<_>>(),
2347    }))
2348  }
2349
2350  pub(crate) fn receiver_parameters(
2351    &mut self,
2352    key: u32,
2353  ) -> Result<serde_json::Value, Error> {
2354    let index = self.index_of(key)?;
2355    // webrtc-pc 5.3 getParameters(): the codecs the receiver is prepared to
2356    // receive, which are the local description's for its m-section.
2357    let local_codecs = self.negotiated_section_codecs(index, true);
2358    let Some(mut receiver) = self.pc.rtp_receiver(index.into()) else {
2359      return Ok(serde_json::Value::Null);
2360    };
2361    let params = receiver.get_parameters().clone();
2362    let codecs: Vec<serde_json::Value> = match local_codecs {
2363      Some((_, codecs)) => codecs
2364        .iter()
2365        .map(|(pt, c)| section_codec_json(*pt, c))
2366        .collect(),
2367      None => params
2368        .rtp_parameters
2369        .codecs
2370        .iter()
2371        .map(codec_params_json)
2372        .collect(),
2373    };
2374    Ok(serde_json::json!({
2375      "codecs": codecs,
2376      "headerExtensions": params.rtp_parameters.header_extensions.iter().map(|h| serde_json::json!({
2377        "uri": h.uri, "id": h.id, "encrypted": h.encrypted,
2378      })).collect::<Vec<_>>(),
2379    }))
2380  }
2381
2382  /// `getSynchronizationSources()` / `getContributingSources()`: the
2383  /// sources heard in the last 10 seconds, most recent first, with
2384  /// timestamps on the wall clock as the spec has them (ms since the epoch).
2385  pub(crate) fn receiver_sources(
2386    &mut self,
2387    key: u32,
2388    contributing: bool,
2389  ) -> Result<Vec<serde_json::Value>, Error> {
2390    self.index_of(key)?;
2391    let now = epoch_ms();
2392    let mut list: Vec<Source> = self
2393      .media
2394      .sources
2395      .get(&key)
2396      .map(|l| {
2397        l.iter()
2398          .filter(|s| {
2399            s.contributing == contributing
2400              && now - s.timestamp <= SOURCE_LIFETIME_MS
2401          })
2402          .cloned()
2403          .collect()
2404      })
2405      .unwrap_or_default();
2406    list.sort_by(|a, b| b.timestamp.total_cmp(&a.timestamp));
2407    Ok(
2408      list
2409        .into_iter()
2410        .map(|s| {
2411          serde_json::json!({
2412            "timestamp": s.timestamp,
2413            "source": s.source,
2414            "rtpTimestamp": s.rtp_timestamp,
2415          })
2416        })
2417        .collect(),
2418    )
2419  }
2420
2421  /// `Deno.webrtc` `writeRtp`: a finished RTP packet; the SSRC becomes the
2422  /// sender's (its first encoding's) and an unknown payload type the
2423  /// negotiated one.
2424  pub(crate) fn write_rtp(
2425    &mut self,
2426    key: u32,
2427    data: &[u8],
2428  ) -> Result<bool, Error> {
2429    if self.media.paused.contains(&key) {
2430      return Ok(false);
2431    }
2432    let index = self.index_of(key)?;
2433    let mut buf = data;
2434    let mut packet =
2435      rtci::rtp::packet::Packet::unmarshal(&mut buf).map_err(|e| {
2436        Error::new(ErrorKind::Type, format!("Not an RTP packet: {e}"))
2437      })?;
2438    let Some(mut sender) = self.pc.rtp_sender(index.into()) else {
2439      return Ok(false);
2440    };
2441    let Some(ssrc) = sender.ssrcs().next() else {
2442      return Ok(false);
2443    };
2444    packet.header.ssrc = ssrc;
2445    // The packet's payload is in the track's codec: one with a payload type
2446    // that isn't negotiated goes out on that codec's, and none goes out
2447    // while it isn't negotiated (the engine would rewrite the payload type
2448    // to another format's, [`sending_codec`]).
2449    let params = sender.get_parameters();
2450    let negotiated = params
2451      .rtp_parameters
2452      .codecs
2453      .iter()
2454      .any(|c| c.payload_type == packet.header.payload_type);
2455    if !negotiated {
2456      match sending_codec(params, self.media.track_codecs.get(&key)) {
2457        Some(codec) => packet.header.payload_type = codec.payload_type,
2458        None => return Ok(false),
2459      }
2460    }
2461    match sender.write_rtp(Instant::now(), packet) {
2462      Ok(()) => Ok(true),
2463      // Not negotiated (yet): dropped, as a sender that isn't sending
2464      // drops what its track produces.
2465      Err(_) => Ok(false),
2466    }
2467  }
2468
2469  /// `Deno.webrtc` `writeFrame`: one encoded frame, cut into RTP packets
2470  /// for the negotiated codec; `samples` advances the RTP timestamp.
2471  pub(crate) fn write_frame(
2472    &mut self,
2473    key: u32,
2474    data: &[u8],
2475    duration_ms: f64,
2476  ) -> Result<bool, Error> {
2477    self.write_frame_at(key, data, duration_ms, None)
2478  }
2479
2480  /// The packetizer of the format the sender sends ([`sending_codec`]),
2481  /// read from the engine sender for every frame, so each applied
2482  /// description that changes it (an answer that leads with another codec, a
2483  /// renegotiation) switches it, and made anew when the format, its payload
2484  /// type or the SSRC changed; `None` before negotiation, while the sender
2485  /// is paused, or for an `EncodedMediaTrack` whose codec was not
2486  /// negotiated.
2487  fn sender_packetizer(
2488    &mut self,
2489    key: u32,
2490  ) -> Result<Option<&mut SenderPacketizer>, Error> {
2491    if self.media.paused.contains(&key) {
2492      return Ok(None);
2493    }
2494    let index = self.index_of(key)?;
2495    let now = Instant::now();
2496    let Some(mut sender) = self.pc.rtp_sender(index.into()) else {
2497      return Ok(None);
2498    };
2499    let Some(ssrc) = sender.ssrcs().next() else {
2500      return Ok(None);
2501    };
2502    let Some(codec) =
2503      sending_codec(sender.get_parameters(), self.media.track_codecs.get(&key))
2504    else {
2505      // Nothing that was cut for an earlier format is kept.
2506      self.media.packetizers.remove(&key);
2507      return Ok(None);
2508    };
2509    // What the engine adds to each packet changes with a negotiation (the
2510    // extensions, the mid, the rids, RTX), and the size with a path report.
2511    let mtu = rtp_mtu(
2512      self.media.path_datagram_limit,
2513      sender.max_packet_expansion(),
2514    );
2515    // `Some(kept)`: a new packetizer is needed; `kept` is the sequence and
2516    // timestamp to go on with when only the size changed.
2517    let renew = match self.media.packetizers.get(&key) {
2518      Some(p)
2519        if p.ssrc == ssrc
2520          && p.payload_type == codec.payload_type
2521          && p.mime_type.eq_ignore_ascii_case(&codec.rtp_codec.mime_type) =>
2522      {
2523        (p.mtu != mtu).then(|| Some((p.sequencer.clone_to(), p.timestamp)))
2524      }
2525      _ => Some(None),
2526    };
2527    if let Some(kept) = renew {
2528      let Some(payloader) = payloader_for(&codec.rtp_codec.mime_type) else {
2529        return Err(Error::new(
2530          ErrorKind::NotSupported,
2531          format!(
2532            "writeFrame can't packetize {}; write RTP packets instead",
2533            codec.rtp_codec.mime_type
2534          ),
2535        ));
2536      };
2537      let (sequencer, timestamp) = kept.unwrap_or_else(|| {
2538        let mut start = [0u8; 4];
2539        let _ = aws_lc_rs::rand::fill(&mut start);
2540        (
2541          Box::new(rtci::rtp::sequence::new_random_sequencer()),
2542          u32::from_le_bytes(start),
2543        )
2544      });
2545      let packetizer = rtci::rtp::packetizer::new_packetizer(
2546        now,
2547        mtu,
2548        codec.payload_type,
2549        ssrc,
2550        payloader,
2551        sequencer.clone_to(),
2552        codec.rtp_codec.clock_rate,
2553      );
2554      self.media.packetizers.insert(
2555        key,
2556        SenderPacketizer {
2557          ssrc,
2558          payload_type: codec.payload_type,
2559          mime_type: codec.rtp_codec.mime_type.clone(),
2560          clock_rate: codec.rtp_codec.clock_rate,
2561          timestamp,
2562          mtu,
2563          sequencer,
2564          packetizer: Box::new(packetizer),
2565        },
2566      );
2567    }
2568    Ok(self.media.packetizers.get_mut(&key))
2569  }
2570
2571  /// Takes the RTP timestamp of a sender's next frame of `duration_ms`
2572  /// (an encoded transform's frame, written later with
2573  /// [`write_frame_at`](Self::write_frame_at)), with what its metadata
2574  /// names: `None` before negotiation.
2575  pub(crate) fn reserve_frame(
2576    &mut self,
2577    key: u32,
2578    duration_ms: f64,
2579  ) -> Result<Option<SenderFrameInfo>, Error> {
2580    let Some(p) = self.sender_packetizer(key)? else {
2581      return Ok(None);
2582    };
2583    let samples = ((duration_ms / 1000.0) * p.clock_rate as f64).round() as u32;
2584    let rtp_timestamp = p.timestamp;
2585    p.timestamp = p.timestamp.wrapping_add(samples);
2586    Ok(Some(SenderFrameInfo {
2587      synchronization_source: p.ssrc,
2588      payload_type: p.payload_type,
2589      mime_type: p.mime_type.clone(),
2590      rtp_timestamp,
2591    }))
2592  }
2593
2594  /// Writes one encoded frame on a sender, cut into RTP packets: at the next
2595  /// timestamp, or at `rtp_timestamp` (one [`reserve_frame`](Self::reserve_frame)
2596  /// took). Returns whether it went out.
2597  pub(crate) fn write_frame_at(
2598    &mut self,
2599    key: u32,
2600    data: &[u8],
2601    duration_ms: f64,
2602    rtp_timestamp: Option<u32>,
2603  ) -> Result<bool, Error> {
2604    let index = self.index_of(key)?;
2605    let now = Instant::now();
2606    let Some(p) = self.sender_packetizer(key)? else {
2607      return Ok(false);
2608    };
2609    let samples = ((duration_ms / 1000.0) * p.clock_rate as f64).round() as u32;
2610    let timestamp = match rtp_timestamp {
2611      Some(t) => t,
2612      None => {
2613        let t = p.timestamp;
2614        p.timestamp = p.timestamp.wrapping_add(samples);
2615        t
2616      }
2617    };
2618    let mime_type = p.mime_type.clone();
2619    let ssrc = p.ssrc;
2620    let mut packets = p
2621      .packetizer
2622      .packetize(now, &Bytes::copy_from_slice(data), samples)
2623      .map_err(|e| {
2624        Error::new(ErrorKind::Type, format!("Could not packetize: {e}"))
2625      })?;
2626    // The timestamps are ours, so a frame's metadata can name its own.
2627    for packet in &mut packets {
2628      packet.header.timestamp = timestamp;
2629    }
2630    let Some(mut sender) = self.pc.rtp_sender(index.into()) else {
2631      return Ok(false);
2632    };
2633    // wpt100:hdrext — the negotiated audio level (RFC 6464) on each packet
2634    // and the absolute capture time on the frame's first one.
2635    let mut extension_id = |uri: &str| {
2636      sender
2637        .get_parameters()
2638        .rtp_parameters
2639        .header_extensions
2640        .iter()
2641        .find(|h| h.uri == uri)
2642        .and_then(|h| u8::try_from(h.id).ok())
2643    };
2644    let level_id = extension_id(rtci::sdp::extmap::AUDIO_LEVEL_URI);
2645    let capture_id =
2646      extension_id(crate::header_extensions::ABS_CAPTURE_TIME_URI);
2647    if let Some(id) = level_id
2648      && let Some(level) =
2649        crate::header_extensions::audio_level(&mime_type, data)
2650    {
2651      let payload = crate::header_extensions::audio_level_payload(level);
2652      for packet in &mut packets {
2653        let _ = packet.header.set_extension(id, payload.clone());
2654      }
2655    }
2656    if let Some(id) = capture_id
2657      && let Some(first) = packets.first_mut()
2658      && let Some(payload) = crate::header_extensions::abs_capture_time_payload(
2659        std::time::SystemTime::now(),
2660      )
2661    {
2662      let _ = first.header.set_extension(id, payload);
2663    }
2664    let mut sent = false;
2665    for packet in packets {
2666      sent |= sender.write_rtp(now, packet).is_ok();
2667    }
2668    // A video frame that reached the sender counts in its stream's encoder
2669    // stats, and in `framesSent` when it went out.
2670    if mime_type.to_ascii_lowercase().starts_with("video/") {
2671      let video = self.media.sent_video.entry(ssrc).or_default();
2672      video.frame(&mime_type, data, sent, now);
2673      let update = video.update(now);
2674      self.pc.update_encoder_stats(ssrc, update);
2675    }
2676    Ok(sent)
2677  }
2678
2679  /// A fake capture device's next frame for a sender (one with an encoded
2680  /// transform, which writes it later), in the codec it negotiated: its
2681  /// bytes, duration and whether it is a key frame, and the frame's
2682  /// metadata. `None` before negotiation or for a codec there is no clip of.
2683  pub(crate) fn fake_frame(
2684    &mut self,
2685    key: u32,
2686    stereo: bool,
2687  ) -> Result<Option<FakeFrame>, Error> {
2688    let Some(mime) = self.sender_packetizer(key)?.map(|p| p.mime_type.clone())
2689    else {
2690      return Ok(None);
2691    };
2692    let cursor = self.media.fake.entry(key).or_default();
2693    let Some((data, duration_ms)) = cursor.advance(&mime, stereo) else {
2694      return Ok(None);
2695    };
2696    let Some(info) = self.reserve_frame(key, duration_ms)? else {
2697      return Ok(None);
2698    };
2699    Ok(Some(FakeFrame {
2700      data: crate::peer::Payload::new(data.to_vec()),
2701      duration_ms,
2702      key_frame: is_key_frame(&mime, data),
2703      width_height: frame_size(&mime, data),
2704      info,
2705      audio_level: crate::header_extensions::audio_level(&mime, data),
2706    }))
2707  }
2708
2709  /// A fake capture device's next frame (`fake_media.rs`) on a sender, in
2710  /// the codec it negotiated; `stereo` takes Opus' two-channel clip.
2711  /// Returns whether it went out (false before negotiation, or for a codec
2712  /// there is no clip of).
2713  pub(crate) fn write_fake(
2714    &mut self,
2715    key: u32,
2716    stereo: bool,
2717  ) -> Result<bool, Error> {
2718    if self.media.paused.contains(&key) {
2719      return Ok(false);
2720    }
2721    let index = self.index_of(key)?;
2722    let Some(mut sender) = self.pc.rtp_sender(index.into()) else {
2723      return Ok(false);
2724    };
2725    // The device encodes in the format the sender sends.
2726    let Some(mime) =
2727      sending_codec(sender.get_parameters(), self.media.track_codecs.get(&key))
2728        .map(|c| c.rtp_codec.mime_type)
2729    else {
2730      return Ok(false);
2731    };
2732    let cursor = self.media.fake.entry(key).or_default();
2733    let Some((frame, duration)) = cursor.advance(&mime, stereo) else {
2734      return Ok(false);
2735    };
2736    self.write_frame(key, frame, duration)
2737  }
2738
2739  /// `RTCDTMFSender`: one RFC 4733 event (0-9 → 0-9, `*` 10, `#` 11, A-D
2740  /// 12-15) lasting `duration_ms`: a start packet (marker set) and the end
2741  /// packet three times, on the negotiated telephone-event payload type at
2742  /// the clock of the sender's audio codec. Returns whether it went out.
2743  pub(crate) fn send_dtmf(
2744    &mut self,
2745    key: u32,
2746    event: u8,
2747    duration_ms: u32,
2748  ) -> Result<bool, Error> {
2749    let index = self.index_of(key)?;
2750    let Some(mut sender) = self.pc.rtp_sender(index.into()) else {
2751      return Ok(false);
2752    };
2753    let Some(ssrc) = sender.ssrcs().next() else {
2754      return Ok(false);
2755    };
2756    let params = sender.get_parameters().clone();
2757    let codecs = &params.rtp_parameters.codecs;
2758    let primary_rate = codecs
2759      .iter()
2760      .find(|c| {
2761        let m = c.rtp_codec.mime_type.to_ascii_lowercase();
2762        !m.ends_with("/telephone-event")
2763          && !m.ends_with("/cn")
2764          && !m.ends_with("/red")
2765          && !m.ends_with("/rtx")
2766      })
2767      .map(|c| c.rtp_codec.clock_rate);
2768    let events: Vec<&RTCRtpCodecParameters> = codecs
2769      .iter()
2770      .filter(|c| {
2771        c.rtp_codec
2772          .mime_type
2773          .eq_ignore_ascii_case("audio/telephone-event")
2774      })
2775      .collect();
2776    let Some(codec) = events
2777      .iter()
2778      .find(|c| Some(c.rtp_codec.clock_rate) == primary_rate)
2779      .or_else(|| events.first())
2780    else {
2781      return Ok(false);
2782    };
2783    let (payload_type, clock_rate) =
2784      (codec.payload_type, codec.rtp_codec.clock_rate);
2785    let entry = self.media.dtmf.entry(key).or_insert_with(|| {
2786      let mut seed = [0u8; 6];
2787      let _ = aws_lc_rs::rand::fill(&mut seed);
2788      (
2789        u16::from_le_bytes([seed[0], seed[1]]),
2790        u32::from_le_bytes([seed[2], seed[3], seed[4], seed[5]]),
2791      )
2792    });
2793    let (mut seq, timestamp) = *entry;
2794    let samples = (u64::from(duration_ms) * u64::from(clock_rate) / 1000)
2795      .min(u64::from(u16::MAX)) as u16;
2796    let now = Instant::now();
2797    let packet = |seq: u16, end: bool, marker: bool, duration: u16| {
2798      let flags = if end { 0x80 } else { 0x00 } | 10; // volume -10 dBm0
2799      let d = duration.to_be_bytes();
2800      rtci::rtp::packet::Packet {
2801        header: rtci::rtp::Header {
2802          version: 2,
2803          marker,
2804          payload_type,
2805          sequence_number: seq,
2806          timestamp,
2807          ssrc,
2808          ..Default::default()
2809        },
2810        payload: Bytes::copy_from_slice(&[event, flags, d[0], d[1]]),
2811      }
2812    };
2813    let mut sent = false;
2814    let Some(mut sender) = self.pc.rtp_sender(index.into()) else {
2815      return Ok(false);
2816    };
2817    sent |= sender.write_rtp(now, packet(seq, false, true, 0)).is_ok();
2818    for _ in 0..3 {
2819      seq = seq.wrapping_add(1);
2820      sent |= sender
2821        .write_rtp(now, packet(seq, true, false, samples))
2822        .is_ok();
2823    }
2824    *self.media.dtmf.get_mut(&key).unwrap() = (
2825      seq.wrapping_add(1),
2826      timestamp.wrapping_add(u32::from(samples)),
2827    );
2828    Ok(sent)
2829  }
2830
2831  /// `Deno.webrtc` `requestKeyFrame`: a PLI to the remote sender.
2832  pub(crate) fn request_key_frame(&mut self, key: u32) -> Result<bool, Error> {
2833    let index = self.index_of(key)?;
2834    let Some(mut receiver) = self.pc.rtp_receiver(index.into()) else {
2835      return Ok(false);
2836    };
2837    let ssrcs: Vec<u32> = receiver.track().ssrcs().collect();
2838    let mut sent = false;
2839    for media_ssrc in ssrcs {
2840      sent |= write_pli(&mut receiver, media_ssrc, Instant::now());
2841    }
2842    Ok(sent)
2843  }
2844
2845  /// A receiver's frame assembler lost a frame of the stream `media_ssrc`
2846  /// and has seen no key frame since: a PLI to the remote sender (RFC 4585
2847  /// section 6.3.1), at most once per [`KEY_FRAME_REQUEST_INTERVAL`] per
2848  /// stream. Returns whether one was sent.
2849  pub(crate) fn request_key_frame_after_loss(
2850    &mut self,
2851    key: u32,
2852    media_ssrc: u32,
2853    now: Instant,
2854  ) -> bool {
2855    let requests = &mut self.media.loss_key_frame_requests;
2856    if requests.get(&media_ssrc).is_some_and(|last| {
2857      now.saturating_duration_since(*last) < KEY_FRAME_REQUEST_INTERVAL
2858    }) {
2859      return false;
2860    }
2861    // Bounded: only streams that asked within the interval are kept.
2862    requests.retain(|_, last| {
2863      now.saturating_duration_since(*last) < KEY_FRAME_REQUEST_INTERVAL
2864    });
2865    let Ok(index) = self.index_of(key) else {
2866      return false;
2867    };
2868    let Some(mut receiver) = self.pc.rtp_receiver(index.into()) else {
2869      return false;
2870    };
2871    let sent = write_pli(&mut receiver, media_ssrc, now);
2872    if sent {
2873      self.media.loss_key_frame_requests.insert(media_ssrc, now);
2874      self.wrote_rtcp = true;
2875    }
2876    sent
2877  }
2878
2879  pub(crate) fn key_for_track(&mut self, track_id: &str) -> Option<u32> {
2880    if let Some(key) = self.media.track_keys.get(track_id) {
2881      return Some(*key);
2882    }
2883    for (index, key) in self.media.keys.clone().into_iter().enumerate() {
2884      if let Some(r) = self.pc.rtp_receiver(index.into())
2885        && r.track().track_id() == track_id
2886      {
2887        self.media.track_keys.insert(track_id.to_string(), key);
2888        return Some(key);
2889      }
2890    }
2891    None
2892  }
2893
2894  pub(crate) fn key_for_receiver_index(&self, index: usize) -> Option<u32> {
2895    self.media.keys.get(index).copied()
2896  }
2897}
2898
2899/// A PLI for the stream `media_ssrc`, written by its receiver. The sender
2900/// SSRC is 0, as the engine's own requests have it.
2901fn write_pli(
2902  receiver: &mut rtci::rtp_transceiver::rtp_receiver::RTCRtpReceiver<'_>,
2903  media_ssrc: u32,
2904  now: Instant,
2905) -> bool {
2906  receiver
2907    .write_rtcp(
2908      now,
2909      vec![Box::new(PictureLossIndication {
2910        sender_ssrc: 0,
2911        media_ssrc,
2912      })],
2913    )
2914    .is_ok()
2915}
2916
2917/// Whether an RTCP compound asks for a key frame (PLI or FIR).
2918pub fn wants_key_frame(packets: &[Box<dyn rtci::rtcp::Packet>]) -> bool {
2919  packets.iter().any(|p| {
2920    p.as_any().downcast_ref::<PictureLossIndication>().is_some()
2921      || p.as_any().downcast_ref::<FullIntraRequest>().is_some()
2922  })
2923}
2924
2925fn section_codec_json(payload_type: u8, c: &CodecArg) -> serde_json::Value {
2926  let mut v = serde_json::to_value(c).unwrap_or(serde_json::Value::Null);
2927  if let Some(obj) = v.as_object_mut() {
2928    obj.insert("payloadType".to_string(), payload_type.into());
2929  }
2930  v
2931}
2932
2933/// RFC 3551's static audio payload types, which may come without an
2934/// `a=rtpmap` line.
2935fn static_audio_codec(payload_type: u8) -> Option<(&'static str, u32)> {
2936  match payload_type {
2937    0 => Some(("PCMU", 8000)),
2938    3 => Some(("GSM", 8000)),
2939    4 => Some(("G723", 8000)),
2940    8 => Some(("PCMA", 8000)),
2941    9 => Some(("G722", 8000)),
2942    13 => Some(("CN", 8000)),
2943    18 => Some(("G729", 8000)),
2944    _ => None,
2945  }
2946}
2947
2948/// The media kind and codecs (payload type, `a=rtpmap`, `a=fmtp`) of the
2949/// m-section of `sdp` whose mid is `mid`, in the m= line's format order. A
2950/// dynamic payload type with no `a=rtpmap` is left out.
2951pub fn section_codecs(
2952  sdp: &str,
2953  mid: &str,
2954) -> Option<(String, Vec<(u8, CodecArg)>)> {
2955  struct Section {
2956    kind: String,
2957    formats: Vec<String>,
2958    rtpmap: HashMap<String, String>,
2959    fmtp: HashMap<String, String>,
2960    mid: Option<String>,
2961  }
2962  let mut sections: Vec<Section> = Vec::new();
2963  for line in sdp.lines() {
2964    let line = line.trim_end();
2965    if let Some(m) = line.strip_prefix("m=") {
2966      let mut fields = m.split_ascii_whitespace();
2967      let kind = fields.next().unwrap_or_default().to_string();
2968      let formats = fields.skip(2).map(str::to_string).collect();
2969      sections.push(Section {
2970        kind,
2971        formats,
2972        rtpmap: HashMap::new(),
2973        fmtp: HashMap::new(),
2974        mid: None,
2975      });
2976      continue;
2977    }
2978    let Some(section) = sections.last_mut() else {
2979      continue;
2980    };
2981    if let Some(value) = line.strip_prefix("a=mid:") {
2982      section.mid = Some(value.trim().to_string());
2983    } else if let Some(value) = line.strip_prefix("a=rtpmap:") {
2984      if let Some((pt, rest)) = value.split_once(' ') {
2985        section
2986          .rtpmap
2987          .entry(pt.to_string())
2988          .or_insert_with(|| rest.trim().to_string());
2989      }
2990    } else if let Some(value) = line.strip_prefix("a=fmtp:")
2991      && let Some((pt, params)) = value.split_once(' ')
2992    {
2993      section
2994        .fmtp
2995        .entry(pt.to_string())
2996        .or_insert_with(|| params.trim().to_string());
2997    }
2998  }
2999  let section = sections
3000    .into_iter()
3001    .find(|s| s.mid.as_deref() == Some(mid))?;
3002  let audio = section.kind == "audio";
3003  let mut out: Vec<(u8, CodecArg)> = Vec::new();
3004  for format in &section.formats {
3005    let Ok(pt) = format.parse::<u8>() else {
3006      continue;
3007    };
3008    if out.iter().any(|(p, _)| *p == pt) {
3009      continue;
3010    }
3011    let (name, clock_rate, channels) = match section.rtpmap.get(format) {
3012      Some(map) => {
3013        let mut parts = map.split('/');
3014        let name = parts.next().unwrap_or_default().to_string();
3015        let clock_rate = parts.next().and_then(|c| c.parse().ok()).unwrap_or(0);
3016        let channels = parts.next().and_then(|c| c.parse().ok());
3017        (name, clock_rate, channels)
3018      }
3019      None => match static_audio_codec(pt).filter(|_| audio) {
3020        Some((name, clock_rate)) => (name.to_string(), clock_rate, None),
3021        None => continue,
3022      },
3023    };
3024    out.push((
3025      pt,
3026      CodecArg {
3027        mime_type: format!("{}/{name}", section.kind),
3028        clock_rate,
3029        // An audio codec without a channel count is mono (RFC 4566).
3030        channels: if audio { channels.or(Some(1)) } else { None },
3031        sdp_fmtp_line: section.fmtp.get(format).cloned(),
3032      },
3033    ));
3034  }
3035  Some((section.kind, out))
3036}
3037
3038/// The send codecs this stack implements for `kind` (computed once).
3039fn supported_codecs(kind: &str) -> &'static [CodecArg] {
3040  static AUDIO: std::sync::OnceLock<Vec<CodecArg>> = std::sync::OnceLock::new();
3041  static VIDEO: std::sync::OnceLock<Vec<CodecArg>> = std::sync::OnceLock::new();
3042  let cell = match kind {
3043    "audio" => &AUDIO,
3044    "video" => &VIDEO,
3045    _ => return &[],
3046  };
3047  cell.get_or_init(|| {
3048    capabilities(kind, true)
3049      .ok()
3050      .flatten()
3051      .map(|c| c.codecs)
3052      .unwrap_or_default()
3053  })
3054}
3055
3056fn is_rtx(c: &CodecArg) -> bool {
3057  c.mime_type.to_ascii_lowercase().ends_with("/rtx")
3058}
3059
3060/// The `apt` (RFC 4588) of a retransmission format's fmtp line.
3061fn rtx_apt(c: &CodecArg) -> Option<u8> {
3062  c.sdp_fmtp_line.as_deref()?.split(';').find_map(|p| {
3063    p.trim()
3064      .strip_prefix("apt=")
3065      .and_then(|v| v.trim().parse().ok())
3066  })
3067}
3068
3069/// Of a remote m-section's codecs, those this stack can send (same name,
3070/// clock rate and, for audio, channels as one it implements); a
3071/// retransmission format only with the primary it repairs.
3072fn sendable_codecs(
3073  kind: &str,
3074  codecs: Vec<(u8, CodecArg)>,
3075) -> Vec<(u8, CodecArg)> {
3076  let supported = supported_codecs(kind);
3077  let known = |c: &CodecArg| {
3078    supported.iter().any(|s| {
3079      s.mime_type.eq_ignore_ascii_case(&c.mime_type)
3080        && s.clock_rate == c.clock_rate
3081        && (kind != "audio" || s.channels == c.channels)
3082    })
3083  };
3084  let primaries: Vec<u8> = codecs
3085    .iter()
3086    .filter(|(_, c)| !is_rtx(c) && known(c))
3087    .map(|(pt, _)| *pt)
3088    .collect();
3089  codecs
3090    .into_iter()
3091    .filter(|(pt, c)| {
3092      if is_rtx(c) {
3093        known(c) && rtx_apt(c).is_some_and(|apt| primaries.contains(&apt))
3094      } else {
3095        primaries.contains(pt)
3096      }
3097    })
3098    .collect()
3099}
3100
3101/// The engine sender's codecs (`engine`, in the remote description's
3102/// payload types) as `getParameters()` lists them: each written as the
3103/// remote m-section (`section`) has it, in that section's order, and any the
3104/// section does not name after them as the engine holds them.
3105fn negotiated_send_codecs(
3106  engine: &[RTCRtpCodecParameters],
3107  section: &[(u8, CodecArg)],
3108) -> Vec<serde_json::Value> {
3109  let in_engine = |pt: u8, c: &CodecArg| {
3110    engine.iter().any(|e| {
3111      e.payload_type == pt
3112        && e.rtp_codec.mime_type.eq_ignore_ascii_case(&c.mime_type)
3113    })
3114  };
3115  let mut out: Vec<serde_json::Value> = section
3116    .iter()
3117    .filter(|(pt, c)| in_engine(*pt, c))
3118    .map(|(pt, c)| section_codec_json(*pt, c))
3119    .collect();
3120  for e in engine {
3121    let listed = section.iter().any(|(pt, c)| {
3122      *pt == e.payload_type
3123        && e.rtp_codec.mime_type.eq_ignore_ascii_case(&c.mime_type)
3124    });
3125    if !listed {
3126      out.push(codec_params_json(e));
3127    }
3128  }
3129  out
3130}
3131
3132fn codec_params_json(c: &RTCRtpCodecParameters) -> serde_json::Value {
3133  let mut v = serde_json::to_value(CodecArg::from_codec(&c.rtp_codec))
3134    .unwrap_or(serde_json::Value::Null);
3135  if let Some(obj) = v.as_object_mut() {
3136    obj.insert("payloadType".to_string(), c.payload_type.into());
3137  }
3138  v
3139}
3140
3141#[cfg(test)]
3142mod rtp_mtu_tests {
3143  use super::*;
3144
3145  // RFC 7941 section 4.2.2: payloads are cut so that the RTP packet, with
3146  // the extensions the engine adds, stays within the MTU; and within what
3147  // a reported path carries once SRTP has its tag.
3148  #[test]
3149  fn packets_are_cut_for_the_extensions_and_the_path() {
3150    assert_eq!(rtp_mtu(None, 0), RTP_MTU);
3151    assert_eq!(rtp_mtu(None, 18), RTP_MTU - 18);
3152    // A path larger than the default changes nothing.
3153    assert_eq!(rtp_mtu(Some(1452), 18), RTP_MTU - 18);
3154    // IPv6's minimum (1280 less IPv6 and UDP: 1232-byte datagrams) still
3155    // carries the default once SRTP has its tag (1216 >= 1200).
3156    assert_eq!(rtp_mtu(Some(1232), 18), RTP_MTU - 18);
3157    // A path just under the default plus the tag cuts below it.
3158    assert_eq!(rtp_mtu(Some(1200), 18), 1200 - SRTP_MAX_OVERHEAD - 18);
3159    // IPv4's minimum (576 less IPv4 and UDP).
3160    assert_eq!(rtp_mtu(Some(548), 18), 548 - SRTP_MAX_OVERHEAD - 18);
3161    // Never below the floor.
3162    assert_eq!(rtp_mtu(Some(200), 18), RTP_MTU_FLOOR);
3163  }
3164
3165  // A path's estimate only ever goes down (RFC 8201 section 4).
3166  #[test]
3167  fn a_path_report_never_raises_the_limit() {
3168    let mut media = MediaState::default();
3169    assert_eq!(media.path_datagram_limit, None);
3170    media.limit_datagrams(1232);
3171    assert_eq!(media.path_datagram_limit, Some(1232));
3172    media.limit_datagrams(1400);
3173    assert_eq!(media.path_datagram_limit, Some(1232));
3174    media.limit_datagrams(548);
3175    assert_eq!(media.path_datagram_limit, Some(548));
3176  }
3177}
3178
3179#[cfg(test)]
3180mod factor_pacer_tests {
3181  use std::sync::Arc;
3182  use std::time::Duration;
3183  use std::time::Instant;
3184
3185  use bytes::Bytes;
3186  use rtci::interceptor::Attribute;
3187  use rtci::interceptor::AttributedPacket;
3188  use rtci::interceptor::GCC_INITIAL_BITRATE;
3189  use rtci::interceptor::Interceptor;
3190  use rtci::interceptor::PacerBuilder;
3191  use rtci::interceptor::Packet;
3192  use rtci::interceptor::RTCPFeedback;
3193  use rtci::interceptor::RTPHeaderExtension;
3194  use rtci::interceptor::StreamInfo;
3195  use rtci::interceptor::TaggedPacket;
3196  use rtci::rtcp::transport_feedbacks::cc_feedback_report::CcFeedbackReport;
3197  use rtci::rtcp::transport_feedbacks::transport_layer_cc::TransportLayerCc;
3198  use rtci::sansio::Protocol;
3199  use rtci::shared::TransportContext;
3200  use rtci::shared::marshal::MarshalSize;
3201
3202  use super::FEEDBACK_TIMEOUT;
3203  use super::FactorPacer;
3204  use super::PACING_FACTOR;
3205  use super::PacerRefusals;
3206  use super::QUEUE_TIME_LIMIT;
3207
3208  const SSRC: u32 = 1234;
3209
3210  fn rtcp(
3211    now: Instant,
3212    packet: Box<dyn rtci::rtcp::Packet>,
3213    estimate: Option<f64>,
3214  ) -> TaggedPacket {
3215    let mut message = AttributedPacket::new(Packet::Rtcp(vec![packet]));
3216    if let Some(bits_per_second) = estimate {
3217      message.add(Attribute::TargetBitrateChanged { bits_per_second });
3218    }
3219    TaggedPacket {
3220      now,
3221      transport: TransportContext::default(),
3222      message,
3223    }
3224  }
3225
3226  /// A receiver report: not congestion feedback, but the estimate the
3227  /// controller attaches makes it one.
3228  fn feedback(estimate: Option<f64>) -> TaggedPacket {
3229    rtcp(
3230      Instant::now(),
3231      Box::new(rtci::rtcp::receiver_report::ReceiverReport::default()),
3232      estimate,
3233    )
3234  }
3235
3236  fn twcc(now: Instant, estimate: Option<f64>) -> TaggedPacket {
3237    rtcp(now, Box::new(TransportLayerCc::default()), estimate)
3238  }
3239
3240  fn ccfb(now: Instant) -> TaggedPacket {
3241    rtcp(now, Box::new(CcFeedbackReport::default()), None)
3242  }
3243
3244  fn rtp(now: Instant, ssrc: u32, seq: u16) -> TaggedPacket {
3245    TaggedPacket {
3246      now,
3247      transport: TransportContext::default(),
3248      message: AttributedPacket::new(Packet::Rtp(rtci::rtp::packet::Packet {
3249        header: rtci::rtp::Header {
3250          version: 2,
3251          sequence_number: seq,
3252          ssrc,
3253          ..Default::default()
3254        },
3255        payload: Bytes::from(vec![0u8; 1000]),
3256      })),
3257    }
3258  }
3259
3260  /// A stream that negotiated the transport-wide sequence number (TWCC).
3261  fn twcc_stream(ssrc: u32) -> StreamInfo {
3262    StreamInfo {
3263      ssrc,
3264      rtp_header_extensions: vec![RTPHeaderExtension {
3265        uri: rtci::sdp::extmap::TRANSPORT_CC_URI.to_string(),
3266        id: 5,
3267      }],
3268      ..Default::default()
3269    }
3270  }
3271
3272  /// A stream that negotiated RFC 8888 feedback (`ack ccfb`) only.
3273  fn ccfb_stream(ssrc: u32) -> StreamInfo {
3274    StreamInfo {
3275      ssrc,
3276      rtcp_feedback: vec![RTCPFeedback {
3277        typ: "ack".to_string(),
3278        parameter: "ccfb".to_string(),
3279      }],
3280      ..Default::default()
3281    }
3282  }
3283
3284  /// What leaves a paced stream at once: the engine pacer starts with one
3285  /// burst in its bucket and refills it to one burst (draft-ietf-rmcat-gcc-02
3286  /// section 4: the rate times 5 ms, at least one full-sized packet), which
3287  /// at the initial rate is one of these packets.
3288  const BURST: usize = 1;
3289
3290  fn pacer() -> FactorPacer {
3291    FactorPacer::new(Arc::default())
3292  }
3293
3294  /// Writes `count` RTP packets at `now` and returns how many came straight
3295  /// out (unpaced), without a timeout releasing them.
3296  fn write(p: &mut FactorPacer, now: Instant, ssrc: u32, count: u16) -> usize {
3297    for seq in 0..count {
3298      p.handle_write(rtp(now, ssrc, seq)).unwrap();
3299    }
3300    drain(p)
3301  }
3302
3303  fn drain(p: &mut FactorPacer) -> usize {
3304    std::iter::from_fn(|| p.poll_write()).count()
3305  }
3306
3307  /// The estimates the packets read through it carry to the stats.
3308  fn reported(p: &mut FactorPacer) -> Vec<f64> {
3309    std::iter::from_fn(|| p.poll_read())
3310      .filter_map(|out| FactorPacer::estimate(&out))
3311      .collect()
3312  }
3313
3314  // A congestion controller estimate paces at PACING_FACTOR times it, and the
3315  // feedback that carried it goes on with the estimate itself (what the stats
3316  // report).
3317  #[test]
3318  fn paces_at_the_factor_times_the_estimate() {
3319    let mut p = pacer();
3320    p.bind_local_stream(&twcc_stream(SSRC));
3321    assert_eq!(p.target_bitrate(), GCC_INITIAL_BITRATE * PACING_FACTOR);
3322    p.handle_read(feedback(Some(400_000.0))).unwrap();
3323    assert_eq!(p.target_bitrate(), 400_000.0 * PACING_FACTOR);
3324    assert_eq!(reported(&mut p), vec![400_000.0]);
3325  }
3326
3327  // Feedback without an estimate leaves the rate alone.
3328  #[test]
3329  fn keeps_the_rate_without_an_estimate() {
3330    let mut p = pacer();
3331    p.bind_local_stream(&twcc_stream(SSRC));
3332    p.handle_read(feedback(Some(500_000.0))).unwrap();
3333    p.handle_read(feedback(None)).unwrap();
3334    assert_eq!(p.target_bitrate(), 500_000.0 * PACING_FACTOR);
3335  }
3336
3337  // A stream that negotiated neither TWCC nor `ack ccfb` is not paced: the
3338  // remote never reports on it, so the estimate would never leave its
3339  // initial value (PR-02: every such connection was held near 750 kb/s).
3340  // Its packets come straight out, however fast they are written.
3341  #[test]
3342  fn passes_a_stream_without_feedback_through() {
3343    let mut p = pacer();
3344    p.bind_local_stream(&StreamInfo {
3345      ssrc: SSRC,
3346      ..Default::default()
3347    });
3348    let now = Instant::now();
3349    assert_eq!(write(&mut p, now, SSRC, 500), 500);
3350    // Seconds later, still nothing held.
3351    assert_eq!(write(&mut p, now + Duration::from_secs(10), SSRC, 500), 500);
3352    assert_eq!(p.refusals.get(), (0, 0));
3353    // No estimate reaches the stats.
3354    assert!(reported(&mut p).is_empty());
3355  }
3356
3357  // An unbound SSRC (no stream negotiated anything) passes through too.
3358  #[test]
3359  fn passes_an_unbound_stream_through() {
3360    let mut p = pacer();
3361    assert_eq!(write(&mut p, Instant::now(), SSRC, 100), 100);
3362  }
3363
3364  // A stream that negotiated TWCC is paced from its first packet, at the
3365  // initial rate: the packets wait for the pacer's budget.
3366  #[test]
3367  fn paces_a_stream_that_negotiated_twcc() {
3368    let mut p = pacer();
3369    p.bind_local_stream(&twcc_stream(SSRC));
3370    let now = Instant::now();
3371    assert!(write(&mut p, now, SSRC, 100) <= BURST);
3372    p.handle_timeout(now).unwrap();
3373    let released = drain(&mut p);
3374    assert!(released < 100, "released {released}");
3375  }
3376
3377  // RFC 8888 feedback (`ack ccfb`) counts as congestion feedback too.
3378  #[test]
3379  fn paces_a_stream_that_negotiated_ccfb() {
3380    let mut p = pacer();
3381    p.bind_local_stream(&ccfb_stream(SSRC));
3382    let now = Instant::now();
3383    assert!(write(&mut p, now, SSRC, 10) <= BURST);
3384    // An RFC 8888 report keeps it paced past the feedback timeout.
3385    let later = now + FEEDBACK_TIMEOUT - Duration::from_millis(100);
3386    p.handle_read(ccfb(later)).unwrap();
3387    assert!(
3388      write(&mut p, later + Duration::from_millis(500), SSRC, 10) <= BURST
3389    );
3390  }
3391
3392  // Only the negotiated stream is paced: another stream of the same
3393  // connection that negotiated nothing passes beside it.
3394  #[test]
3395  fn paces_only_the_negotiated_streams() {
3396    let mut p = pacer();
3397    p.bind_local_stream(&twcc_stream(SSRC));
3398    p.bind_local_stream(&StreamInfo {
3399      ssrc: SSRC + 1,
3400      ..Default::default()
3401    });
3402    let now = Instant::now();
3403    assert!(write(&mut p, now, SSRC, 10) <= BURST);
3404    assert_eq!(write(&mut p, now, SSRC + 1, 10), 10);
3405  }
3406
3407  // While reports keep coming, it keeps pacing, however long the call.
3408  #[test]
3409  fn keeps_pacing_while_feedback_arrives() {
3410    let mut p = pacer();
3411    p.bind_local_stream(&twcc_stream(SSRC));
3412    let start = Instant::now();
3413    for i in 0..20 {
3414      let now = start + Duration::from_millis(250) * i;
3415      p.handle_read(twcc(now, None)).unwrap();
3416      assert!(write(&mut p, now, SSRC, 5) <= BURST, "at {i}");
3417      p.handle_timeout(now).unwrap();
3418      drain(&mut p);
3419    }
3420  }
3421
3422  // Negotiated, but no report within FEEDBACK_TIMEOUT of the first packet:
3423  // what was held goes at the next wake-up and later packets pass straight
3424  // through; the next report resumes pacing at its estimate.
3425  #[test]
3426  fn falls_back_without_feedback_then_resumes() {
3427    let mut p = pacer();
3428    p.bind_local_stream(&twcc_stream(SSRC));
3429    let start = Instant::now();
3430    let first = write(&mut p, start, SSRC, 100);
3431    assert!(first <= BURST);
3432    let before = start + FEEDBACK_TIMEOUT - Duration::from_millis(1);
3433    let second = write(&mut p, before, SSRC, 1);
3434    assert!(second <= BURST, "still paced");
3435    let after = start + FEEDBACK_TIMEOUT;
3436    p.handle_timeout(after).unwrap();
3437    assert_eq!(
3438      drain(&mut p),
3439      101 - first - second,
3440      "the held packets all go"
3441    );
3442    assert_eq!(write(&mut p, after, SSRC, 200), 200);
3443    // A report: paced again, at its estimate.
3444    let resumed = after + Duration::from_secs(5);
3445    p.handle_read(twcc(resumed, Some(400_000.0))).unwrap();
3446    assert_eq!(p.target_bitrate(), 400_000.0 * PACING_FACTOR);
3447    let third = write(&mut p, resumed, SSRC, 10);
3448    assert!(third <= BURST);
3449    // And reports that stop after that fall back the same way.
3450    let stopped = resumed + FEEDBACK_TIMEOUT;
3451    p.handle_timeout(stopped).unwrap();
3452    assert_eq!(drain(&mut p), 10 - third);
3453    assert_eq!(write(&mut p, stopped, SSRC, 10), 10);
3454  }
3455
3456  // rtci 0.4's pacer interleaves the streams waiting in it (by priority,
3457  // RFC 8835 section 4.1) instead of releasing them in the order written:
3458  // what this pacer counts as held stays the bits of the packets still in
3459  // it, whichever stream's leave first, so the backlog rate is right.
3460  #[test]
3461  fn counts_what_it_holds_when_streams_interleave() {
3462    const OTHER: u32 = 5678;
3463    fn sized(now: Instant, ssrc: u32, seq: u16, len: usize) -> TaggedPacket {
3464      let mut packet = rtp(now, ssrc, seq);
3465      if let Packet::Rtp(rtp) = &mut packet.message.packet {
3466        rtp.payload = Bytes::from(vec![0u8; len]);
3467      }
3468      packet
3469    }
3470    let bits = |ssrc: u32, seq: u16| {
3471      let len = if ssrc == SSRC { 1000 } else { 300 };
3472      match &sized(Instant::now(), ssrc, seq, len).message.packet {
3473        Packet::Rtp(rtp) => (rtp.marshal_size() * 8) as f64,
3474        _ => unreachable!("an RTP packet"),
3475      }
3476    };
3477    let mut p = pacer();
3478    p.bind_local_stream(&twcc_stream(SSRC));
3479    p.bind_local_stream(&twcc_stream(OTHER));
3480    let start = Instant::now();
3481    let mut waiting: Vec<(u32, u16)> = Vec::new();
3482    for seq in 0..40 {
3483      p.handle_write(sized(start, SSRC, seq, 1000)).unwrap();
3484      waiting.push((SSRC, seq));
3485    }
3486    for seq in 0..40 {
3487      p.handle_write(sized(start, OTHER, seq, 300)).unwrap();
3488      waiting.push((OTHER, seq));
3489    }
3490    let mut now = start;
3491    let mut order = Vec::new();
3492    while !waiting.is_empty() {
3493      p.handle_read(twcc(now, None)).unwrap();
3494      p.handle_timeout(now).unwrap();
3495      while let Some(out) = p.poll_write() {
3496        if let Packet::Rtp(rtp) = out.message.packet {
3497          let id = (rtp.header.ssrc, rtp.header.sequence_number);
3498          waiting.retain(|w| *w != id);
3499          order.push(rtp.header.ssrc);
3500        }
3501      }
3502      let expected: f64 = waiting.iter().map(|&(s, q)| bits(s, q)).sum();
3503      assert!(
3504        (p.held_bits() - expected).abs() < 1.0,
3505        "holds {} bits, {} wait",
3506        p.held_bits(),
3507        expected
3508      );
3509      if waiting.is_empty() {
3510        break;
3511      }
3512      now = p.poll_timeout().expect("a release is due").max(now);
3513    }
3514    assert_eq!(p.held_bits(), 0.0);
3515    // Each stream left in its own order; the other stream started before
3516    // the first had gone (they shared the path).
3517    let first_other = order.iter().position(|s| *s == OTHER).unwrap();
3518    let last_first = order.iter().rposition(|s| *s == SSRC).unwrap();
3519    assert!(first_other < last_first, "interleaved: {order:?}");
3520  }
3521
3522  // A packet written while the held ones haven't gone yet waits behind them,
3523  // so the stream keeps its order.
3524  #[test]
3525  fn keeps_a_streams_order_when_falling_back() {
3526    let mut p = pacer();
3527    p.bind_local_stream(&twcc_stream(SSRC));
3528    let start = Instant::now();
3529    let first = write(&mut p, start, SSRC, 50);
3530    assert!(first <= BURST);
3531    let after = start + FEEDBACK_TIMEOUT;
3532    p.handle_write(rtp(after, SSRC, 50)).unwrap();
3533    p.handle_timeout(after).unwrap();
3534    let order: Vec<u16> = std::iter::from_fn(|| p.poll_write())
3535      .map(|out| match out.message.packet {
3536        Packet::Rtp(rtp) => rtp.header.sequence_number,
3537        _ => unreachable!("only RTP was written"),
3538      })
3539      .collect();
3540    assert_eq!(order, (first as u16..=50).collect::<Vec<_>>());
3541  }
3542
3543  // The stats hold an estimate only while it paces at one: the initial
3544  // estimate with the first report, the controller's after that, none once
3545  // reports stop (`availableOutgoingBitrate` absent, `targetBitrate` 0), and
3546  // the last one again with the next report.
3547  #[test]
3548  fn reports_an_estimate_only_while_pacing() {
3549    let mut p = pacer();
3550    p.bind_local_stream(&twcc_stream(SSRC));
3551    let start = Instant::now();
3552    write(&mut p, start, SSRC, 1);
3553    assert!(reported(&mut p).is_empty(), "nothing before a report");
3554    let first = start + Duration::from_millis(100);
3555    p.handle_read(twcc(first, None)).unwrap();
3556    assert_eq!(reported(&mut p), vec![GCC_INITIAL_BITRATE]);
3557    p.handle_read(twcc(first, Some(500_000.0))).unwrap();
3558    assert_eq!(reported(&mut p), vec![500_000.0]);
3559    p.handle_read(twcc(first, None)).unwrap();
3560    assert!(reported(&mut p).is_empty(), "unchanged: nothing new");
3561    p.handle_timeout(first + FEEDBACK_TIMEOUT).unwrap();
3562    let carrier = p.poll_read().expect("the estimate is withdrawn");
3563    assert!(
3564      matches!(&carrier.message.packet, Packet::Rtcp(packets) if packets.is_empty())
3565    );
3566    assert_eq!(FactorPacer::estimate(&carrier), Some(0.0));
3567    assert!(p.poll_read().is_none());
3568    let back = first + FEEDBACK_TIMEOUT * 2;
3569    p.handle_read(twcc(back, None)).unwrap();
3570    assert_eq!(reported(&mut p), vec![500_000.0]);
3571  }
3572
3573  // A packet the full queue refuses is counted, with its bytes, for the
3574  // candidate pair's `packetsDiscardedOnSend` / `bytesDiscardedOnSend`.
3575  #[test]
3576  fn counts_what_a_full_queue_refuses() {
3577    let refusals = Arc::new(PacerRefusals::default());
3578    let mut p = FactorPacer::with_pacer(
3579      PacerBuilder::new()
3580        .with_target_bitrate(GCC_INITIAL_BITRATE * PACING_FACTOR)
3581        .with_queue_time_limit(None)
3582        .with_queue_limit(4)
3583        .build(),
3584      refusals.clone(),
3585    );
3586    p.bind_local_stream(&twcc_stream(SSRC));
3587    let now = Instant::now();
3588    let released = write(&mut p, now, SSRC, 10);
3589    assert!(released <= BURST);
3590    let size = match &rtp(now, SSRC, 0).message.packet {
3591      Packet::Rtp(rtp) => rtp.marshal_size() as u64,
3592      _ => unreachable!("an RTP packet"),
3593    };
3594    // Ten written: what left at once, four queued, the rest refused.
3595    let refused = (10 - released - 4) as u64;
3596    assert_eq!(refusals.get(), (refused, refused * size));
3597  }
3598
3599  // A backlog drains within QUEUE_TIME_LIMIT whatever the estimate: 1,000
3600  // packets (about 8 Mb) at the initial 750 kb/s would take over 10 s; the
3601  // pacer releases them faster instead, while feedback keeps it pacing.
3602  #[test]
3603  fn drains_a_backlog_within_the_queue_time_limit() {
3604    let mut p = pacer();
3605    p.bind_local_stream(&twcc_stream(SSRC));
3606    let start = Instant::now();
3607    let mut released = write(&mut p, start, SSRC, 1000);
3608    assert!(released <= BURST);
3609    let mut now = start;
3610    while released < 1000 {
3611      p.handle_read(twcc(now, None)).unwrap();
3612      p.handle_timeout(now).unwrap();
3613      released += drain(&mut p);
3614      if released == 1000 {
3615        break;
3616      }
3617      now = p.poll_timeout().expect("a release is due").max(now);
3618      assert!(
3619        now <= start + QUEUE_TIME_LIMIT + Duration::from_millis(100),
3620        "{released} of 1000 released after {:?}",
3621        now - start
3622      );
3623    }
3624    // Drained, it paces at the estimate again.
3625    assert_eq!(p.target_bitrate(), GCC_INITIAL_BITRATE * PACING_FACTOR);
3626  }
3627
3628  // Audio is never paced, even where it negotiated feedback: it doesn't wait
3629  // behind video in the queue.
3630  #[test]
3631  fn does_not_pace_audio() {
3632    let mut p = pacer();
3633    p.bind_local_stream(&StreamInfo {
3634      mime_type: "audio/opus".to_string(),
3635      ..twcc_stream(SSRC)
3636    });
3637    p.bind_local_stream(&twcc_stream(SSRC + 1));
3638    let now = Instant::now();
3639    assert!(write(&mut p, now, SSRC + 1, 100) <= BURST);
3640    assert_eq!(write(&mut p, now, SSRC, 50), 50);
3641  }
3642}