Skip to main content

rtci_rtcp/extended_report/
vm.rs

1use super::*;
2
3const VM_REPORT_BLOCK_LENGTH: u16 = 4 + 4 + 2 * 4 + 10 + 2 * 3;
4
5/// VoIPMetricsReportBlock encodes a VoIP Metrics Report Block as described
6/// in RFC 3611, section 4.7.
7///
8///  0                   1                   2                   3
9///  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
10/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
11/// |     BT=7      |   reserved    |       block length = 8        |
12/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
13/// |                        ssrc of source                         |
14/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
15/// |   loss rate   | discard rate  | burst density |  gap density  |
16/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
17/// |       burst duration          |         gap duration          |
18/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
19/// |     round trip delay          |       end system delay        |
20/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
21/// | signal level  |  noise level  |     RERL      |     Gmin      |
22/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
23/// |   R factor    | ext. R factor |    MOS-LQ     |    MOS-CQ     |
24/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
25/// |   RX config   |   reserved    |          JB nominal           |
26/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
27/// |          JB maximum           |          JB abs max           |
28/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
29#[derive(Debug, PartialEq, Eq, Clone)]
30pub struct VoIPMetricsReportBlock {
31    /// The SSRC these metrics describe.
32    pub ssrc: u32,
33    /// Fraction of packets lost, as 256ths.
34    pub loss_rate: u8,
35    /// Fraction of packets discarded by the jitter buffer, as 256ths.
36    pub discard_rate: u8,
37    /// Fraction of packets lost or discarded during bursts, as 256ths.
38    pub burst_density: u8,
39    /// Fraction lost or discarded during gaps between bursts, as 256ths.
40    pub gap_density: u8,
41    /// Mean burst length in milliseconds.
42    pub burst_duration: u16,
43    /// Mean gap length in milliseconds.
44    pub gap_duration: u16,
45    /// Round-trip delay in milliseconds.
46    pub round_trip_delay: u16,
47    /// End-system delay in milliseconds, covering encode, buffer and decode.
48    pub end_system_delay: u16,
49    /// Signal level in dBm0.
50    pub signal_level: u8,
51    /// Noise level in dBm0.
52    pub noise_level: u8,
53    /// Residual echo return loss, in dB.
54    pub rerl: u8,
55    /// The gap threshold: consecutive received packets needed to end a burst.
56    pub gmin: u8,
57    /// The R factor, a 0–100 voice-quality estimate.
58    pub rfactor: u8,
59    /// An external-network R factor, for the segment beyond this one.
60    pub ext_rfactor: u8,
61    /// Listening-quality mean opinion score, in tenths.
62    pub mos_lq: u8,
63    /// Conversational-quality mean opinion score, in tenths.
64    pub mos_cq: u8,
65    /// Receiver configuration: packet-loss concealment and jitter-buffer flags.
66    pub rx_config: u8,
67    /// Reserved; sent as zero.
68    pub reserved: u8,
69    /// Nominal jitter-buffer delay in milliseconds.
70    pub jb_nominal: u16,
71    /// Maximum jitter-buffer delay in milliseconds.
72    pub jb_maximum: u16,
73    /// The absolute maximum the jitter buffer can grow to, in milliseconds.
74    pub jb_abs_max: u16,
75}
76
77/// The value of a metric that is not available (RFC 3611 §4.7.4, §4.7.5).
78pub const VOIP_METRIC_UNAVAILABLE: u8 = 127;
79/// The Gmin RFC 3611 §4.7.2 recommends.
80pub const VOIP_METRICS_DEFAULT_GMIN: u8 = 16;
81
82impl Default for VoIPMetricsReportBlock {
83    /// A block that reports nothing: every metric that has an "unavailable" value carries it
84    /// (127 for the signal, noise and echo levels, the R factors and the MOS scores), Gmin is
85    /// the recommended 16, and the rest is zero, which RFC 3611 §4.7 defines as "none" or
86    /// "unknown" for those fields. Fill in what is measured over `..Default::default()`.
87    fn default() -> Self {
88        VoIPMetricsReportBlock {
89            ssrc: 0,
90            loss_rate: 0,
91            discard_rate: 0,
92            burst_density: 0,
93            gap_density: 0,
94            burst_duration: 0,
95            gap_duration: 0,
96            round_trip_delay: 0,
97            end_system_delay: 0,
98            signal_level: VOIP_METRIC_UNAVAILABLE,
99            noise_level: VOIP_METRIC_UNAVAILABLE,
100            rerl: VOIP_METRIC_UNAVAILABLE,
101            gmin: VOIP_METRICS_DEFAULT_GMIN,
102            rfactor: VOIP_METRIC_UNAVAILABLE,
103            ext_rfactor: VOIP_METRIC_UNAVAILABLE,
104            mos_lq: VOIP_METRIC_UNAVAILABLE,
105            mos_cq: VOIP_METRIC_UNAVAILABLE,
106            rx_config: 0,
107            reserved: 0,
108            jb_nominal: 0,
109            jb_maximum: 0,
110            jb_abs_max: 0,
111        }
112    }
113}
114
115/// RFC 3611 4.7.5: an R factor is 0 to 100, or 127 when it is not available.
116fn valid_rfactor(value: u8) -> bool {
117    value <= 100 || value == VOIP_METRIC_UNAVAILABLE
118}
119
120/// RFC 3611 4.7.5: a MOS score is 10 to 50 (1.0 to 5.0), or 127 when it is not available.
121fn valid_mos(value: u8) -> bool {
122    (10..=50).contains(&value) || value == VOIP_METRIC_UNAVAILABLE
123}
124
125impl fmt::Display for VoIPMetricsReportBlock {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        write!(f, "{self:?}")
128    }
129}
130
131impl VoIPMetricsReportBlock {
132    /// The XR block header describing this block's type and length.
133    pub fn xr_header(&self) -> XRHeader {
134        XRHeader {
135            block_type: BlockType::VoIPMetrics,
136            type_specific: 0,
137            block_length: (self.raw_size() / 4 - 1) as u16,
138        }
139    }
140}
141
142impl Packet for VoIPMetricsReportBlock {
143    fn header(&self) -> Header {
144        Header::default()
145    }
146
147    /// destination_ssrc returns an array of ssrc values that this report block refers to.
148    fn destination_ssrc(&self) -> Vec<u32> {
149        vec![self.ssrc]
150    }
151
152    fn raw_size(&self) -> usize {
153        XR_HEADER_LENGTH + VM_REPORT_BLOCK_LENGTH as usize
154    }
155
156    fn as_any(&self) -> &dyn Any {
157        self
158    }
159    fn equal(&self, other: &dyn Packet) -> bool {
160        other.as_any().downcast_ref::<VoIPMetricsReportBlock>() == Some(self)
161    }
162    fn cloned(&self) -> Box<dyn Packet> {
163        Box::new(self.clone())
164    }
165}
166
167impl MarshalSize for VoIPMetricsReportBlock {
168    fn marshal_size(&self) -> usize {
169        self.raw_size()
170    }
171}
172
173impl Marshal for VoIPMetricsReportBlock {
174    /// marshal_to encodes the VoIPMetricsReportBlock in binary
175    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
176        // RFC 3611 4.7.5: values other than 127 and the valid range "MUST NOT be sent".
177        if !valid_rfactor(self.rfactor)
178            || !valid_rfactor(self.ext_rfactor)
179            || !valid_mos(self.mos_lq)
180            || !valid_mos(self.mos_cq)
181        {
182            return Err(Error::InvalidHeader);
183        }
184        // RFC 3611 4.7.6: "Gmin MUST not be zero".
185        if self.gmin == 0 {
186            return Err(Error::InvalidHeader);
187        }
188        if buf.remaining_mut() < self.marshal_size() {
189            return Err(Error::BufferTooShort);
190        }
191
192        let h = self.xr_header();
193        let n = h.marshal_to(buf)?;
194        buf = &mut buf[n..];
195
196        buf.put_u32(self.ssrc);
197        buf.put_u8(self.loss_rate);
198        buf.put_u8(self.discard_rate);
199        buf.put_u8(self.burst_density);
200        buf.put_u8(self.gap_density);
201        buf.put_u16(self.burst_duration);
202        buf.put_u16(self.gap_duration);
203        buf.put_u16(self.round_trip_delay);
204        buf.put_u16(self.end_system_delay);
205        buf.put_u8(self.signal_level);
206        buf.put_u8(self.noise_level);
207        buf.put_u8(self.rerl);
208        buf.put_u8(self.gmin);
209        buf.put_u8(self.rfactor);
210        buf.put_u8(self.ext_rfactor);
211        buf.put_u8(self.mos_lq);
212        buf.put_u8(self.mos_cq);
213        buf.put_u8(self.rx_config);
214        // "This field is reserved for future definition ... MUST be set to zero".
215        buf.put_u8(0);
216        buf.put_u16(self.jb_nominal);
217        buf.put_u16(self.jb_maximum);
218        buf.put_u16(self.jb_abs_max);
219
220        Ok(self.marshal_size())
221    }
222}
223
224impl Unmarshal for VoIPMetricsReportBlock {
225    /// Unmarshal decodes the VoIPMetricsReportBlock from binary
226    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
227    where
228        Self: Sized,
229        B: Buf,
230    {
231        if raw_packet.remaining() < XR_HEADER_LENGTH {
232            return Err(Error::PacketTooShort);
233        }
234
235        let xr_header = XRHeader::unmarshal(raw_packet)?;
236        if xr_header.block_type != BlockType::VoIPMetrics {
237            return Err(Error::WrongType);
238        }
239        let block_length = match xr_header.block_length.checked_mul(4) {
240            Some(length) => length,
241            None => return Err(Error::InvalidBlockSize),
242        };
243        if block_length != VM_REPORT_BLOCK_LENGTH || raw_packet.remaining() < block_length as usize
244        {
245            return Err(Error::PacketTooShort);
246        }
247
248        let ssrc = raw_packet.get_u32();
249        let loss_rate = raw_packet.get_u8();
250        let discard_rate = raw_packet.get_u8();
251        let burst_density = raw_packet.get_u8();
252        let gap_density = raw_packet.get_u8();
253        let burst_duration = raw_packet.get_u16();
254        let gap_duration = raw_packet.get_u16();
255        let round_trip_delay = raw_packet.get_u16();
256        let end_system_delay = raw_packet.get_u16();
257        let signal_level = raw_packet.get_u8();
258        let noise_level = raw_packet.get_u8();
259        let rerl = raw_packet.get_u8();
260        let gmin = raw_packet.get_u8();
261        // RFC 3611 4.7.5: values other than 127 and the valid range "MUST be ignored by the
262        // receiving system": such a value reads as not available.
263        let unless = |valid: fn(u8) -> bool, value: u8| {
264            if valid(value) {
265                value
266            } else {
267                VOIP_METRIC_UNAVAILABLE
268            }
269        };
270        let rfactor = unless(valid_rfactor, raw_packet.get_u8());
271        let ext_rfactor = unless(valid_rfactor, raw_packet.get_u8());
272        let mos_lq = unless(valid_mos, raw_packet.get_u8());
273        let mos_cq = unless(valid_mos, raw_packet.get_u8());
274        let rx_config = raw_packet.get_u8();
275        // The reserved octet is ignored.
276        raw_packet.advance(1);
277        let reserved = 0;
278        let jb_nominal = raw_packet.get_u16();
279        let jb_maximum = raw_packet.get_u16();
280        let jb_abs_max = raw_packet.get_u16();
281
282        Ok(VoIPMetricsReportBlock {
283            ssrc,
284            loss_rate,
285            discard_rate,
286            burst_density,
287            gap_density,
288            burst_duration,
289            gap_duration,
290            round_trip_delay,
291            end_system_delay,
292            signal_level,
293            noise_level,
294            rerl,
295            gmin,
296            rfactor,
297            ext_rfactor,
298            mos_lq,
299            mos_cq,
300            rx_config,
301            reserved,
302            jb_nominal,
303            jb_maximum,
304            jb_abs_max,
305        })
306    }
307}