rtci_rtcp/payload_feedbacks/receiver_estimated_maximum_bitrate/mod.rs
1#[cfg(test)]
2mod receiver_estimated_maximum_bitrate_test;
3
4use crate::{header::*, packet::*, util::*};
5use shared::{
6 error::{Error, Result},
7 marshal::{Marshal, MarshalSize, Unmarshal},
8};
9
10use bytes::{Buf, BufMut};
11use std::any::Any;
12use std::fmt;
13
14/// ReceiverEstimatedMaximumBitrate contains the receiver's estimated maximum bitrate.
15///
16/// ## Specifications
17///
18/// * [draft-alvestrand-rmcat-remb-03]
19///
20/// [draft-alvestrand-rmcat-remb-03]: https://tools.ietf.org/html/draft-alvestrand-rmcat-remb-03
21#[derive(Debug, PartialEq, Default, Clone)]
22pub struct ReceiverEstimatedMaximumBitrate {
23 /// SSRC of sender
24 pub sender_ssrc: u32,
25
26 /// Estimated maximum bitrate
27 pub bitrate: f32,
28
29 /// SSRC entries which this packet applies to
30 pub ssrcs: Vec<u32>,
31}
32
33const REMB_OFFSET: usize = 16;
34const SSRC_ENTRY_OFFSET: usize = 20;
35
36/// Keep a table of powers to units for fast conversion.
37const BIT_UNITS: [&str; 7] = ["b", "Kb", "Mb", "Gb", "Tb", "Pb", "Eb"];
38const UNIQUE_IDENTIFIER: [u8; 4] = *b"REMB";
39
40/// String prints the REMB packet in a human-readable format.
41impl fmt::Display for ReceiverEstimatedMaximumBitrate {
42 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43 // Do some unit conversions because b/s is far too difficult to read.
44 let mut bitrate = self.bitrate;
45 let mut powers = 0;
46
47 // Keep dividing the bitrate until it's under 1000
48 // (and stop at the last unit: a peer can state a bit rate far beyond exabits, and the
49 // table must not be indexed past its end)
50 while bitrate >= 1000.0 && powers < BIT_UNITS.len() - 1 {
51 bitrate /= 1000.0;
52 powers += 1;
53 }
54
55 let unit = BIT_UNITS[powers];
56
57 write!(
58 f,
59 "ReceiverEstimatedMaximumBitrate {:x} {:.2} {}/s",
60 self.sender_ssrc, bitrate, unit,
61 )
62 }
63}
64
65impl Packet for ReceiverEstimatedMaximumBitrate {
66 /// Header returns the Header associated with this packet.
67 fn header(&self) -> Header {
68 Header {
69 padding: get_padding_size(self.raw_size()) != 0,
70 count: FORMAT_REMB,
71 packet_type: PacketType::PayloadSpecificFeedback,
72 length: ((self.marshal_size() / 4) - 1) as u16,
73 }
74 }
75
76 /// destination_ssrc returns an array of SSRC values that this packet refers to.
77 fn destination_ssrc(&self) -> Vec<u32> {
78 self.ssrcs.clone()
79 }
80
81 fn raw_size(&self) -> usize {
82 HEADER_LENGTH + REMB_OFFSET + self.ssrcs.len() * 4
83 }
84
85 fn as_any(&self) -> &dyn Any {
86 self
87 }
88
89 fn equal(&self, other: &dyn Packet) -> bool {
90 other
91 .as_any()
92 .downcast_ref::<ReceiverEstimatedMaximumBitrate>()
93 == Some(self)
94 }
95
96 fn cloned(&self) -> Box<dyn Packet> {
97 Box::new(self.clone())
98 }
99}
100
101impl MarshalSize for ReceiverEstimatedMaximumBitrate {
102 fn marshal_size(&self) -> usize {
103 let l = self.raw_size();
104 // align to 32-bit boundary
105 l + get_padding_size(l)
106 }
107}
108
109impl Marshal for ReceiverEstimatedMaximumBitrate {
110 /// Marshal serializes the packet and returns a byte slice.
111 fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
112 const BITRATE_MAX: f32 = 2.417_842_4e24; //0x3FFFFp+63;
113
114 /*
115 0 1 2 3
116 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
117 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
118 |V=2|P| FMT=15 | PT=206 | length |
119 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
120 | SSRC of packet sender |
121 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
122 | SSRC of media source |
123 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
124 | Unique identifier 'R' 'E' 'M' 'B' |
125 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
126 | Num SSRC | BR Exp | BR Mantissa |
127 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
128 | SSRC feedback |
129 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
130 | ... |
131 */
132
133 // Num SSRC is one octet.
134 if self.ssrcs.len() > u8::MAX as usize {
135 return Err(Error::TooManySources);
136 }
137 if buf.remaining_mut() < self.marshal_size() {
138 return Err(Error::BufferTooShort);
139 }
140
141 let h = self.header();
142 let n = h.marshal_to(buf)?;
143 buf = &mut buf[n..];
144
145 buf.put_u32(self.sender_ssrc);
146 buf.put_u32(0); // always zero
147
148 buf.put_slice(&UNIQUE_IDENTIFIER);
149
150 // Write the length of the ssrcs to follow at the end
151 buf.put_u8(self.ssrcs.len() as u8);
152
153 let mut exp = 0;
154 let mut bitrate = self.bitrate;
155 if bitrate >= BITRATE_MAX {
156 bitrate = BITRATE_MAX
157 }
158
159 if bitrate < 0.0 {
160 return Err(Error::InvalidBitrate);
161 }
162
163 while bitrate >= (1 << 18) as f32 {
164 bitrate /= 2.0;
165 exp += 1;
166 }
167
168 if exp >= (1 << 6) {
169 return Err(Error::InvalidBitrate);
170 }
171
172 let mantissa = bitrate.floor() as u32;
173
174 // We can't quite use the binary package because
175 // a) it's a uint24 and b) the exponent is only 6-bits
176 // Just trust me; this is big-endian encoding.
177 buf.put_u8((exp << 2) as u8 | (mantissa >> 16) as u8);
178 buf.put_u8((mantissa >> 8) as u8);
179 buf.put_u8(mantissa as u8);
180
181 // Write the SSRCs at the very end.
182 for ssrc in &self.ssrcs {
183 buf.put_u32(*ssrc);
184 }
185
186 if h.padding {
187 put_padding(buf, self.raw_size());
188 }
189
190 Ok(self.marshal_size())
191 }
192}
193
194/// Whether `body`, what follows the header of a PSFB FMT=15 packet, is a REMB: after the two
195/// SSRCs its FCI opens with `REMB`.
196pub(crate) fn is_remb(body: &[u8]) -> bool {
197 body.get(FEEDBACK_SSRCS_LENGTH..FEEDBACK_SSRCS_LENGTH + UNIQUE_IDENTIFIER.len())
198 == Some(&UNIQUE_IDENTIFIER[..])
199}
200
201impl Unmarshal for ReceiverEstimatedMaximumBitrate {
202 /// Unmarshal reads a REMB packet from the given byte slice.
203 fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
204 where
205 Self: Sized,
206 B: Buf,
207 {
208 const MANTISSA_MAX: u32 = 0x7FFFFF;
209 /*
210 0 1 2 3
211 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
212 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
213 |V=2|P| FMT=15 | PT=206 | length |
214 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
215 | SSRC of packet sender |
216 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
217 | SSRC of media source |
218 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
219 | Unique identifier 'R' 'E' 'M' 'B' |
220 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
221 | Num SSRC | BR Exp | BR Mantissa |
222 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
223 | SSRC feedback |
224 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
225 | ... |
226 */
227 let (sender_ssrc, media_ssrc, mut fci) =
228 read_feedback(raw_packet, PacketType::PayloadSpecificFeedback, FORMAT_REMB)?;
229 // The identifier and the word with the SSRC count and the bit rate.
230 if fci.len() < SSRC_ENTRY_OFFSET - HEADER_LENGTH - FEEDBACK_SSRCS_LENGTH {
231 return Err(Error::PacketTooShort);
232 }
233 if media_ssrc != 0 {
234 return Err(Error::SsrcMustBeZero);
235 }
236
237 let mut unique_identifier = [0; 4];
238 fci.copy_to_slice(&mut unique_identifier);
239 if unique_identifier != UNIQUE_IDENTIFIER {
240 return Err(Error::MissingRembIdentifier);
241 }
242
243 let ssrcs_len = fci.get_u8() as usize;
244
245 let b17 = fci.get_u8();
246 let mut exp = (b17 as u64) >> 2;
247 exp += 127; // bias for IEEE754
248 exp += 23; // IEEE754 biases the decimal to the left, abs-send-time biases it to the right
249
250 let b18 = fci.get_u8();
251 let b19 = fci.get_u8();
252 let mut mantissa = ((b17 & 3) as u32) << 16 | (b18 as u32) << 8 | b19 as u32;
253
254 if mantissa != 0 {
255 // ieee754 requires an implicit leading bit
256 while (mantissa & (MANTISSA_MAX + 1)) == 0 {
257 exp -= 1;
258 mantissa *= 2;
259 }
260 }
261
262 // bitrate = mantissa * 2^exp. A mantissa of zero is a bit rate of zero whatever the
263 // exponent: it has no leading bit to normalise, and the bits below would read as
264 // 2^(exp + 23).
265 let bitrate = if mantissa == 0 {
266 0.0
267 } else {
268 f32::from_bits(((exp as u32) << 23) | (mantissa & MANTISSA_MAX))
269 };
270
271 // draft-alvestrand-rmcat-remb-03 2.2: Num SSRC entries follow, and nothing else.
272 if fci.len() != ssrcs_len * SSRC_LENGTH {
273 return Err(Error::SsrcNumAndLengthMismatch);
274 }
275 let mut ssrcs = Vec::with_capacity(ssrcs_len);
276 for _ in 0..ssrcs_len {
277 ssrcs.push(fci.get_u32());
278 }
279
280 Ok(ReceiverEstimatedMaximumBitrate {
281 sender_ssrc,
282 bitrate,
283 ssrcs,
284 })
285 }
286}