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