1use super::estimator::Gcc;
24use super::rate_calc::RateCalculator;
25use crate::cc::estimator::BandwidthEstimator;
26use crate::cc::feedback::negotiated_congestion_feedback;
27use crate::rtpfb::acknowledgement::PacketReport;
28use crate::stream_info::StreamInfo;
29use crate::twcc::flow_ssrcs;
30use crate::{Attribute, AttributedPacket, Interceptor, Packet, TaggedPacket};
31use rtcp::payload_feedbacks::receiver_estimated_maximum_bitrate::ReceiverEstimatedMaximumBitrate;
32use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
33use sansio::Protocol;
34use shared::TransportContext;
35use shared::error::Error;
36use shared::marshal::{MarshalSize, Unmarshal};
37use std::collections::{BTreeMap, HashMap, VecDeque};
38use std::time::{Duration, Instant};
39
40pub const ABS_SEND_TIME_URI: &str = "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time";
42
43pub const REMB_GENERATOR_SLOT: usize = 9_500;
47
48pub const ABS_SEND_TIME_SLOT: usize = 1_900;
53
54pub const GOOG_REMB: &str = "goog-remb";
56
57pub const REMB_UPDATE_INTERVAL: Duration = Duration::from_millis(100);
59
60pub const REMB_MAX_INTERVAL: Duration = Duration::from_secs(1);
62
63pub const REMB_DECREASE_TRIGGER: f64 = 0.97;
66
67pub const REMB_INITIALIZATION_TIME: Duration = Duration::from_secs(5);
73
74const REMB_MIN_BITRATE: f64 = 10_000.0;
76const REMB_MAX_BITRATE: f64 = 1_000_000_000.0;
78
79const ABS_SEND_TIME_HZ: f64 = (1u64 << 18) as f64;
81const ABS_SEND_TIME_MODULUS: u64 = 1 << 24;
82const RTP_TIMESTAMP_MODULUS: u64 = 1 << 32;
83
84#[derive(Debug, Clone, Copy)]
86struct SendClock {
87 hz: f64,
88 modulus: u64,
89 last: Option<u64>,
90 unwrapped: i64,
92}
93
94impl SendClock {
95 fn new(hz: f64, modulus: u64) -> Self {
96 Self {
97 hz,
98 modulus,
99 last: None,
100 unwrapped: 0,
101 }
102 }
103
104 fn seconds(&mut self, raw: u64) -> f64 {
106 let raw = raw % self.modulus;
107 if let Some(last) = self.last {
108 let forward = (raw + self.modulus - last) % self.modulus;
110 let delta = if forward <= self.modulus / 2 {
111 forward as i64
112 } else {
113 forward as i64 - self.modulus as i64
114 };
115 self.unwrapped += delta;
116 }
117 self.last = Some(raw);
118 self.unwrapped as f64 / self.hz
119 }
120}
121
122struct Estimate {
124 clock: SendClock,
125 anchor: Instant,
127 anchor_seconds: f64,
129 reports: Vec<PacketReport>,
131 incoming: RateCalculator,
133 first_arrival: Instant,
134 gcc: Option<Gcc>,
135 next_id: u64,
136}
137
138impl Estimate {
139 fn new(clock: SendClock, now: Instant) -> Self {
140 Self {
141 clock,
142 anchor: now,
143 anchor_seconds: f64::NAN,
144 reports: Vec::new(),
145 incoming: RateCalculator::new(Duration::from_secs(1)),
146 first_arrival: now,
147 gcc: None,
148 next_id: 0,
149 }
150 }
151
152 fn record(&mut self, now: Instant, epoch: Instant, ssrc: u32, raw_send_time: u64, size: usize) {
153 let seconds = self.clock.seconds(raw_send_time);
154 if self.anchor_seconds.is_nan() {
155 self.anchor_seconds = seconds;
156 }
157 let offset = seconds - self.anchor_seconds;
158 let departure = if offset >= 0.0 {
159 self.anchor + Duration::from_secs_f64(offset)
160 } else {
161 self.anchor
162 .checked_sub(Duration::from_secs_f64(-offset))
163 .unwrap_or(self.anchor)
164 };
165 self.incoming.add(now, size);
166 let id = self.next_id;
167 self.next_id += 1;
168 self.reports.push(PacketReport {
169 ssrc,
170 id,
171 rtp_sequence_number: 0,
172 is_twcc: false,
173 twcc_sequence_number: 0,
174 size,
175 arrived: true,
176 departure,
177 arrival: Some(now.saturating_duration_since(epoch)),
178 ecn: Ecn::default(),
179 });
180 }
181
182 fn update(&mut self, now: Instant) -> Option<f64> {
184 if self.gcc.is_none() {
185 if now.saturating_duration_since(self.first_arrival) < REMB_INITIALIZATION_TIME {
186 self.reports.clear();
187 return None;
188 }
189 let incoming = self.incoming.rate_bits_per_second(now)?;
190 self.gcc = Some(Gcc::new(incoming, REMB_MIN_BITRATE, REMB_MAX_BITRATE));
191 }
192 let gcc = self.gcc.as_mut()?;
193 let reports = std::mem::take(&mut self.reports);
194 gcc.on_reports(now, &reports);
195 Some(gcc.target_bitrate())
196 }
197}
198
199#[derive(Debug, Clone, Copy)]
201struct RembStream {
202 clock_rate: u32,
203 abs_send_time_id: Option<u8>,
204}
205
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
209enum EstimateKey {
210 AbsSendTime,
211 Stream(u32),
212}
213
214#[derive(Debug, Clone)]
216pub struct RembGeneratorBuilder {
217 interval: Duration,
218 sender_ssrc: Option<u32>,
219}
220
221impl Default for RembGeneratorBuilder {
222 fn default() -> Self {
223 Self {
224 interval: REMB_UPDATE_INTERVAL,
225 sender_ssrc: None,
226 }
227 }
228}
229
230impl RembGeneratorBuilder {
231 pub fn new() -> Self {
233 Self::default()
234 }
235
236 pub fn with_interval(mut self, interval: Duration) -> Self {
238 self.interval = interval;
239 self
240 }
241
242 pub fn with_sender_ssrc(mut self, sender_ssrc: u32) -> Self {
245 self.sender_ssrc = Some(sender_ssrc);
246 self
247 }
248
249 pub fn build(self) -> RembGeneratorInterceptor {
251 RembGeneratorInterceptor {
252 interval: self.interval,
253 sender_ssrc: self
254 .sender_ssrc
255 .unwrap_or_else(|| rand::random::<u32>().max(1)),
256 streams: HashMap::new(),
257 estimates: BTreeMap::new(),
258 epoch: None,
259 next_update: None,
260 last_sent: None,
261 read_queue: VecDeque::new(),
262 write_queue: VecDeque::new(),
263 }
264 }
265}
266
267pub struct RembGeneratorInterceptor {
270 interval: Duration,
271 sender_ssrc: u32,
272 streams: HashMap<u32, RembStream>,
273 estimates: BTreeMap<EstimateKey, Estimate>,
274 epoch: Option<Instant>,
276 next_update: Option<Instant>,
277 last_sent: Option<(f64, Instant)>,
279 read_queue: VecDeque<TaggedPacket>,
280 write_queue: VecDeque<TaggedPacket>,
281}
282
283impl RembGeneratorInterceptor {
284 fn record(&mut self, msg: &TaggedPacket) {
285 let Packet::Rtp(packet) = &msg.message.packet else {
286 return;
287 };
288 let Some(stream) = self.streams.get(&packet.header.ssrc).copied() else {
289 return;
290 };
291 if msg
292 .message
293 .attributes
294 .iter()
295 .any(|attribute| matches!(attribute, Attribute::Retransmitted { .. }))
296 {
297 return;
298 }
299 let abs_send_time = stream.abs_send_time_id.and_then(|id| {
300 let mut data = packet.header.get_extension(id)?;
301 rtp::extension::abs_send_time_extension::AbsSendTimeExtension::unmarshal(&mut data).ok()
302 });
303 let (key, raw, clock) = match abs_send_time {
304 Some(extension) => (
305 EstimateKey::AbsSendTime,
306 extension.timestamp,
307 SendClock::new(ABS_SEND_TIME_HZ, ABS_SEND_TIME_MODULUS),
308 ),
309 None if stream.clock_rate > 0 => (
310 EstimateKey::Stream(packet.header.ssrc),
311 u64::from(packet.header.timestamp),
312 SendClock::new(f64::from(stream.clock_rate), RTP_TIMESTAMP_MODULUS),
313 ),
314 None => return,
315 };
316 let now = msg.now;
317 let epoch = *self.epoch.get_or_insert(now);
318 self.next_update.get_or_insert(now + self.interval);
319 self.estimates
320 .entry(key)
321 .or_insert_with(|| Estimate::new(clock, now))
322 .record(now, epoch, packet.header.ssrc, raw, packet.marshal_size());
323 }
324
325 fn update(&mut self, now: Instant) {
326 let mut total = 0.0;
327 let mut any = false;
328 for estimate in self.estimates.values_mut() {
329 if let Some(bitrate) = estimate.update(now) {
330 total += bitrate;
331 any = true;
332 }
333 }
334 if !any {
335 return;
336 }
337 let due = match self.last_sent {
338 None => true,
339 Some((last, at)) => {
340 total < REMB_DECREASE_TRIGGER * last
341 || now.saturating_duration_since(at) >= REMB_MAX_INTERVAL
342 }
343 };
344 if !due {
345 return;
346 }
347 let mut ssrcs: Vec<u32> = self.streams.keys().copied().collect();
348 ssrcs.sort_unstable();
349 self.last_sent = Some((total, now));
350 self.write_queue.push_back(TaggedPacket {
351 now,
352 transport: TransportContext::default(),
353 message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
354 ReceiverEstimatedMaximumBitrate {
355 sender_ssrc: self.sender_ssrc,
356 bitrate: total as f32,
357 ssrcs,
358 },
359 )])),
360 });
361 }
362}
363
364impl Protocol<TaggedPacket, TaggedPacket, ()> for RembGeneratorInterceptor {
365 type Rout = TaggedPacket;
366 type Wout = TaggedPacket;
367 type Eout = ();
368 type Error = Error;
369 type Time = Instant;
370
371 fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
372 self.record(&msg);
373 self.read_queue.push_back(msg);
374 Ok(())
375 }
376
377 fn poll_read(&mut self) -> Option<Self::Rout> {
378 self.read_queue.pop_front()
379 }
380
381 fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
382 self.write_queue.push_back(msg);
383 Ok(())
384 }
385
386 fn poll_write(&mut self) -> Option<Self::Wout> {
387 self.write_queue.pop_front()
388 }
389
390 fn handle_timeout(&mut self, now: Instant) -> Result<(), Self::Error> {
391 if let Some(at) = self.next_update
392 && now >= at
393 {
394 self.update(now);
395 self.next_update = (!self.streams.is_empty()).then(|| now + self.interval);
396 }
397 Ok(())
398 }
399
400 fn poll_timeout(&mut self) -> Option<Self::Time> {
401 self.next_update
402 }
403}
404
405fn wants_remb(info: &StreamInfo) -> bool {
408 info.rtcp_feedback.iter().any(|fb| fb.typ == GOOG_REMB)
409 && negotiated_congestion_feedback(info).is_none()
410}
411
412fn abs_send_time_id(info: &StreamInfo) -> Option<u8> {
413 info.rtp_header_extensions
414 .iter()
415 .find(|ext| ext.uri == ABS_SEND_TIME_URI)
416 .and_then(|ext| u8::try_from(ext.id).ok())
417 .filter(|id| *id != 0)
418}
419
420impl Interceptor for RembGeneratorInterceptor {
421 fn bind_remote_stream(&mut self, info: &StreamInfo) {
422 if !wants_remb(info) {
423 self.streams.remove(&info.ssrc);
424 return;
425 }
426 self.streams.insert(
427 info.ssrc,
428 RembStream {
429 clock_rate: info.clock_rate,
430 abs_send_time_id: abs_send_time_id(info),
431 },
432 );
433 }
434
435 fn unbind_remote_stream(&mut self, info: &StreamInfo) {
436 self.streams.remove(&info.ssrc);
437 self.estimates.remove(&EstimateKey::Stream(info.ssrc));
438 if !self
439 .streams
440 .values()
441 .any(|stream| stream.abs_send_time_id.is_some())
442 {
443 self.estimates.remove(&EstimateKey::AbsSendTime);
444 }
445 if self.streams.is_empty() {
446 self.next_update = None;
447 }
448 }
449
450 fn bind_local_stream(&mut self, _info: &StreamInfo) {}
451
452 fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
453}
454
455#[derive(Default)]
460pub struct AbsSendTimeInterceptor {
461 ids: HashMap<u32, u8>,
463 epoch: Option<Instant>,
464 read_queue: VecDeque<TaggedPacket>,
465 write_queue: VecDeque<TaggedPacket>,
466}
467
468impl AbsSendTimeInterceptor {
469 pub fn new() -> Self {
471 Self::default()
472 }
473
474 fn stamp(&mut self, now: Instant) -> [u8; 3] {
477 let epoch = *self.epoch.get_or_insert(now);
478 let seconds = now.saturating_duration_since(epoch).as_secs_f64();
479 let ticks = ((seconds * ABS_SEND_TIME_HZ) as u64) % ABS_SEND_TIME_MODULUS;
480 [(ticks >> 16) as u8, (ticks >> 8) as u8, ticks as u8]
481 }
482}
483
484impl Protocol<TaggedPacket, TaggedPacket, ()> for AbsSendTimeInterceptor {
485 type Rout = TaggedPacket;
486 type Wout = TaggedPacket;
487 type Eout = ();
488 type Error = Error;
489 type Time = Instant;
490
491 fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
492 self.read_queue.push_back(msg);
493 Ok(())
494 }
495
496 fn poll_read(&mut self) -> Option<Self::Rout> {
497 self.read_queue.pop_front()
498 }
499
500 fn handle_write(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
501 if let Packet::Rtp(packet) = &mut msg.message.packet
502 && let Some(id) = self.ids.get(&packet.header.ssrc).copied()
503 {
504 let stamp = self.stamp(msg.now);
505 let _ = packet
506 .header
507 .set_extension_upgrading(id, bytes::Bytes::copy_from_slice(&stamp));
508 }
509 self.write_queue.push_back(msg);
510 Ok(())
511 }
512
513 fn poll_write(&mut self) -> Option<Self::Wout> {
514 self.write_queue.pop_front()
515 }
516
517 fn handle_timeout(&mut self, _now: Instant) -> Result<(), Self::Error> {
518 Ok(())
519 }
520
521 fn poll_timeout(&mut self) -> Option<Self::Time> {
522 None
523 }
524}
525
526impl Interceptor for AbsSendTimeInterceptor {
527 fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
528
529 fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
530
531 fn bind_local_stream(&mut self, info: &StreamInfo) {
532 if let Some(id) = abs_send_time_id(info) {
533 for ssrc in flow_ssrcs(info) {
534 self.ids.insert(ssrc, id);
535 }
536 }
537 }
538
539 fn unbind_local_stream(&mut self, info: &StreamInfo) {
540 for ssrc in flow_ssrcs(info) {
541 self.ids.remove(&ssrc);
542 }
543 }
544}
545
546#[cfg(test)]
547#[path = "remb_test.rs"]
548mod remb_test;