Skip to main content

rtci_rtcp/payload_feedbacks/slice_loss_indication/
mod.rs

1#[cfg(test)]
2mod slice_loss_indication_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
14const SLI_LENGTH: usize = 2;
15const SLI_OFFSET: usize = 8;
16
17/// SLIEntry represents a single entry to the SLI packet's
18/// list of lost slices.
19#[derive(Debug, PartialEq, Eq, Default, Clone)]
20pub struct SliEntry {
21    /// ID of first lost slice
22    pub first: u16,
23    /// Number of lost slices
24    pub number: u16,
25    /// ID of related picture
26    pub picture: u8,
27}
28
29/// The SliceLossIndication packet informs the encoder about the loss of a picture slice
30#[derive(Debug, PartialEq, Eq, Default, Clone)]
31pub struct SliceLossIndication {
32    /// SSRC of sender
33    pub sender_ssrc: u32,
34    /// SSRC of the media source
35    pub media_ssrc: u32,
36
37    /// The lost slices being reported.
38    pub sli_entries: Vec<SliEntry>,
39}
40
41impl SliceLossIndication {
42    /// An SLI for a VP8 frame (RFC 7741 section 5.2) that the receiver cannot say more of: the
43    /// whole frame lost ("First ... 0, and the Number parameter to the total number of
44    /// macroblocks per frame", for a frame of `width` by `height` pixels in 16 by 16
45    /// macroblocks), in the picture whose VP8 PictureID is `picture_id`; a receiver whose
46    /// current frame had none passes the last PictureID received plus one. The entry carries
47    /// the six least significant bits. Number is cut to its 13 bits.
48    pub fn vp8_frame(
49        sender_ssrc: u32,
50        media_ssrc: u32,
51        picture_id: u16,
52        width: u16,
53        height: u16,
54    ) -> Self {
55        let macroblocks = u32::from(width).div_ceil(16) * u32::from(height).div_ceil(16);
56        Self {
57            sender_ssrc,
58            media_ssrc,
59            sli_entries: vec![SliEntry {
60                first: 0,
61                number: macroblocks.min(0x1fff) as u16,
62                picture: (picture_id & 0x3f) as u8,
63            }],
64        }
65    }
66}
67
68impl fmt::Display for SliceLossIndication {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        write!(
71            f,
72            "SliceLossIndication {:x} {:x} {:?}",
73            self.sender_ssrc, self.media_ssrc, self.sli_entries,
74        )
75    }
76}
77
78impl Packet for SliceLossIndication {
79    /// Header returns the Header associated with this packet.
80    fn header(&self) -> Header {
81        Header {
82            padding: get_padding_size(self.raw_size()) != 0,
83            count: FORMAT_SLI,
84            // RFC 4585 ยง6.3.2: SLI is payload-specific feedback (PT=PSFB, FMT=2).
85            packet_type: PacketType::PayloadSpecificFeedback,
86            length: ((self.marshal_size() / 4) - 1) as u16,
87        }
88    }
89
90    /// destination_ssrc returns an array of SSRC values that this packet refers to.
91    fn destination_ssrc(&self) -> Vec<u32> {
92        vec![self.media_ssrc]
93    }
94
95    fn raw_size(&self) -> usize {
96        HEADER_LENGTH + SLI_OFFSET + self.sli_entries.len() * 4
97    }
98
99    fn as_any(&self) -> &dyn Any {
100        self
101    }
102
103    fn equal(&self, other: &dyn Packet) -> bool {
104        other.as_any().downcast_ref::<SliceLossIndication>() == Some(self)
105    }
106
107    fn cloned(&self) -> Box<dyn Packet> {
108        Box::new(self.clone())
109    }
110}
111
112impl MarshalSize for SliceLossIndication {
113    fn marshal_size(&self) -> usize {
114        let l = self.raw_size();
115        // align to 32-bit boundary
116        l + get_padding_size(l)
117    }
118}
119
120impl Marshal for SliceLossIndication {
121    /// Marshal encodes the SliceLossIndication in binary
122    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
123        // RFC 4585 6.3.2: "The FCI field MUST contain at least one SLI."
124        if self.sli_entries.is_empty() {
125            return Err(Error::PacketTooShort);
126        }
127        // The length field counts 32-bit words in 16 bits.
128        if self.sli_entries.len() + SLI_LENGTH > u16::MAX as usize {
129            return Err(Error::TooManyReports);
130        }
131        if buf.remaining_mut() < self.marshal_size() {
132            return Err(Error::BufferTooShort);
133        }
134
135        let h = self.header();
136        let n = h.marshal_to(buf)?;
137        buf = &mut buf[n..];
138
139        buf.put_u32(self.sender_ssrc);
140        buf.put_u32(self.media_ssrc);
141
142        for s in &self.sli_entries {
143            let sli = ((s.first as u32 & 0x1FFF) << 19)
144                | ((s.number as u32 & 0x1FFF) << 6)
145                | (s.picture as u32 & 0x3F);
146
147            buf.put_u32(sli);
148        }
149
150        if h.padding {
151            put_padding(buf, self.raw_size());
152        }
153
154        Ok(self.marshal_size())
155    }
156}
157
158impl Unmarshal for SliceLossIndication {
159    /// Unmarshal decodes the SliceLossIndication from binary
160    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
161    where
162        Self: Sized,
163        B: Buf,
164    {
165        let (sender_ssrc, media_ssrc, mut fci) =
166            read_feedback(raw_packet, PacketType::PayloadSpecificFeedback, FORMAT_SLI)?;
167        // RFC 4585 6.3.2: "The FCI field MUST contain at least one SLI."
168        if fci.is_empty() {
169            return Err(Error::PacketTooShort);
170        }
171        if !fci.len().is_multiple_of(4) {
172            return Err(Error::WrongPadding);
173        }
174
175        let mut sli_entries = Vec::with_capacity(fci.len() / 4);
176        while fci.has_remaining() {
177            let sli = fci.get_u32();
178            sli_entries.push(SliEntry {
179                first: ((sli >> 19) & 0x1FFF) as u16,
180                number: ((sli >> 6) & 0x1FFF) as u16,
181                picture: (sli & 0x3F) as u8,
182            });
183        }
184
185        Ok(SliceLossIndication {
186            sender_ssrc,
187            media_ssrc,
188            sli_entries,
189        })
190    }
191}