Skip to main content

rtci_rtp/codec/vp8/
mod.rs

1#[cfg(test)]
2mod vp8_descriptor_test;
3#[cfg(test)]
4mod vp8_layers_test;
5#[cfg(test)]
6mod vp8_partitions_test;
7#[cfg(test)]
8mod vp8_test;
9
10mod partitions;
11
12use crate::packetizer::{Depacketizer, Payloader};
13use shared::error::{Error, Result};
14
15use bytes::{BufMut, Bytes, BytesMut};
16
17/// Bytes of mandatory VP8 payload descriptor prefixed to each payload.
18pub const VP8_HEADER_SIZE: usize = 1;
19
20/// The highest temporal layer id the two-bit `TID` field carries (RFC 7741 section 4.2).
21pub const VP8_MAX_TEMPORAL_ID: u8 = 3;
22/// The highest `KEYIDX` the five-bit field carries (RFC 7741 section 4.2).
23pub const VP8_MAX_KEY_IDX: u8 = 31;
24
25/// The temporal layer of one VP8 frame, as the encoder reports it (RFC 7741 section 4.2).
26#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
27pub struct Vp8TemporalLayer {
28    /// `TID`: the temporal layer the frame belongs to; 0 is the base layer.
29    pub tid: u8,
30    /// `Y`, the layer sync bit: the frame depends only on the base layer frame with the same
31    /// `TL0PICIDX`, so a receiver can start decoding this layer here. Leave it `false` when
32    /// the dependency is not known (always safe).
33    pub layer_sync: bool,
34}
35
36/// What the encoder knows about one VP8 frame and the payload descriptor carries (RFC 7741
37/// section 4.2). The default describes a frame of a stream without temporal layers.
38#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
39pub struct Vp8FrameInfo {
40    /// `N`: the frame is not a reference for any other frame and can be discarded without
41    /// affecting later frames. Leave it `false` when the reference status is not known.
42    pub non_reference: bool,
43    /// The frame's temporal layer. When set, the descriptor carries `TID`, `Y` and
44    /// `TL0PICIDX` (which the payloader counts).
45    pub temporal: Option<Vp8TemporalLayer>,
46    /// `KEYIDX`, the encoder's running index of key frames (0 to 31). When set, the descriptor
47    /// carries it; a sender that uses it sets it on key frames and interframes alike.
48    pub key_idx: Option<u8>,
49}
50
51/// Vp8Payloader payloads VP8 packets
52///
53/// [`Payloader::payload`] sends a frame of a stream without temporal layers.
54/// [`Vp8Payloader::payload_frame`] takes the frame's layer information from the encoder and
55/// writes `N`, `TID`, `Y`, `TL0PICIDX` and `KEYIDX` (RFC 7741 section 4.2), which is what lets
56/// a forwarder drop temporal layers.
57#[derive(Default, Debug, Copy, Clone)]
58pub struct Vp8Payloader {
59    /// Whether to include the optional picture id in the payload descriptor.
60    ///
61    /// Lets a receiver detect loss within a frame, at one or two bytes per packet.
62    pub enable_picture_id: bool,
63    /// Cut each frame at MTU boundaries without regard to its partitions, with `PID` 0 on
64    /// every packet and `S` on the first only (RFC 7741 section 4.4 allows it; libwebrtc's
65    /// packetizer does this). By default each partition starts a packet of its own, labelled
66    /// with its `PID` and `S` (sections 3, 4.2 and 4.4).
67    pub ignore_partitions: bool,
68    picture_id: u16,
69    /// `TL0PICIDX` of the last base layer frame sent.
70    tl0_pic_idx: u8,
71}
72
73impl Vp8Payloader {
74    /// Sets the PictureID of the next frame (15 bits). RFC 7741 section 4.2 lets it start at a
75    /// random value; the default is 0.
76    pub fn set_initial_picture_id(&mut self, picture_id: u16) {
77        self.picture_id = picture_id & 0x7FFF;
78    }
79
80    /// Sets `TL0PICIDX` so that the next base layer frame carries `tl0_pic_idx`. RFC 7741
81    /// section 4.2 lets it start at a random value; by default the first base layer frame
82    /// carries 1.
83    pub fn set_initial_tl0_pic_idx(&mut self, tl0_pic_idx: u8) {
84        self.tl0_pic_idx = tl0_pic_idx.wrapping_sub(1);
85    }
86
87    /// The PictureID the next frame is sent with.
88    pub fn picture_id(&self) -> u16 {
89        self.picture_id
90    }
91
92    /// Fragments one VP8 frame, describing it with `info`.
93    ///
94    /// The descriptor carries the PictureID when [`enable_picture_id`](Self::enable_picture_id)
95    /// is set, `TL0PICIDX`, `TID` and `Y` when `info.temporal` is, `KEYIDX` when
96    /// `info.key_idx` is, and `N` from `info.non_reference`. `TL0PICIDX` is incremented for
97    /// every frame with `TID` 0 and repeated on the frames above it.
98    ///
99    /// Each partition of the frame (the first partition with the frame header and the token
100    /// partition sizes, then each DCT token partition: RFC 6386 section 9) starts a packet of
101    /// its own, as RFC 7741 section 3 recommends: the packet's `PID` is the partition's index
102    /// (the eighth and ninth of a frame with eight token partitions share `PID` 7, the field's
103    /// largest value) and `S` is set on the first packet of each partition (sections 4.2,
104    /// 4.4). A partition larger than the MTU allows is cut over several packets. A frame
105    /// whose partition sizes cannot be read, or every frame with
106    /// [`ignore_partitions`](Self::ignore_partitions), is cut at MTU boundaries without
107    /// regard to its partitions, `S` on the first packet only and `PID` 0 (section 4.4).
108    ///
109    /// # Errors
110    ///
111    /// `TID` above 3 or `KEYIDX` above 31, which the fields cannot carry.
112    pub fn payload_frame(
113        &mut self,
114        mtu: usize,
115        payload: &Bytes,
116        info: &Vp8FrameInfo,
117    ) -> Result<Vec<Bytes>> {
118        if let Some(temporal) = &info.temporal
119            && temporal.tid > VP8_MAX_TEMPORAL_ID
120        {
121            return Err(Error::Other(format!(
122                "VP8 TID {} does not fit two bits",
123                temporal.tid
124            )));
125        }
126        if let Some(key_idx) = info.key_idx
127            && key_idx > VP8_MAX_KEY_IDX
128        {
129            return Err(Error::Other(format!(
130                "VP8 KEYIDX {key_idx} does not fit five bits"
131            )));
132        }
133        if payload.is_empty() || mtu == 0 {
134            return Ok(vec![]);
135        }
136
137        /*
138         * https://tools.ietf.org/html/rfc7741#section-4.2
139         *
140         *       0 1 2 3 4 5 6 7
141         *      +-+-+-+-+-+-+-+-+
142         *      |X|R|N|S|R| PID | (REQUIRED)
143         *      +-+-+-+-+-+-+-+-+
144         * X:   |I|L|T|K| RSV   | (OPTIONAL)
145         *      +-+-+-+-+-+-+-+-+
146         * I:   |M| PictureID   | (OPTIONAL)
147         *      +-+-+-+-+-+-+-+-+
148         * L:   |   tl0picidx   | (OPTIONAL)
149         *      +-+-+-+-+-+-+-+-+
150         * T/K: |tid|Y| KEYIDX  | (OPTIONAL)
151         *      +-+-+-+-+-+-+-+-+
152         *  S: Start of VP8 partition.  SHOULD be set to 1 when the first payload
153         *     octet of the RTP packet is the beginning of a new VP8 partition,
154         *     and MUST NOT be 1 otherwise.  The S bit MUST be set to 1 for the
155         *     first packet of each encoded frame.
156         */
157        // The descriptor after its first octet: the same on every packet of the frame.
158        let mut extension = [0u8; 5];
159        let mut extension_len = 0;
160        let has_extension =
161            self.enable_picture_id || info.temporal.is_some() || info.key_idx.is_some();
162        // TL0PICIDX counts base layer frames: a frame with TID 0 takes the next value, a frame
163        // above it repeats the value of the base layer frame it depends on.
164        let tl0_pic_idx = match &info.temporal {
165            Some(temporal) if temporal.tid == 0 => self.tl0_pic_idx.wrapping_add(1),
166            _ => self.tl0_pic_idx,
167        };
168        if has_extension {
169            let mut flags = 0u8;
170            extension_len = 1;
171            if self.enable_picture_id {
172                flags |= 0x80; // I
173                if self.picture_id < 128 {
174                    extension[extension_len] = self.picture_id as u8;
175                    extension_len += 1;
176                } else {
177                    extension[extension_len] = 0x80 | (self.picture_id >> 8) as u8; // M
178                    extension[extension_len + 1] = (self.picture_id & 0xFF) as u8;
179                    extension_len += 2;
180                }
181            }
182            if info.temporal.is_some() {
183                // L is only sent with T (RFC 7741 4.2: "L=1 requires T=1").
184                flags |= 0x40 | 0x20;
185                extension[extension_len] = tl0_pic_idx;
186                extension_len += 1;
187            }
188            if info.temporal.is_some() || info.key_idx.is_some() {
189                let mut b = 0u8;
190                if let Some(temporal) = &info.temporal {
191                    b |= temporal.tid << 6;
192                    if temporal.layer_sync {
193                        b |= 0x20;
194                    }
195                }
196                if let Some(key_idx) = info.key_idx {
197                    flags |= 0x10; // K
198                    b |= key_idx;
199                }
200                extension[extension_len] = b;
201                extension_len += 1;
202            }
203            extension[0] = flags;
204        }
205
206        let using_header_size = VP8_HEADER_SIZE + extension_len;
207        if mtu <= using_header_size {
208            return Ok(vec![]);
209        }
210        let max_fragment_size = mtu - using_header_size;
211
212        // The byte ranges that each start a packet, with their PID.
213        let mut regions: Vec<(std::ops::Range<usize>, u8)> = Vec::new();
214        match (!self.ignore_partitions)
215            .then(|| partitions::vp8_partitions(payload))
216            .flatten()
217        {
218            Some(parts) => {
219                for (index, part) in parts.into_iter().enumerate() {
220                    // PID cannot be larger than 7: a ninth partition continues the eighth's.
221                    let pid = index.min(7) as u8;
222                    match regions.last_mut() {
223                        Some((last, last_pid)) if *last_pid == pid => last.end = part.end,
224                        _ if part.is_empty() => {}
225                        _ => regions.push((part, pid)),
226                    }
227                }
228            }
229            None => regions.push((0..payload.len(), 0)),
230        }
231
232        let mut payloads = Vec::with_capacity(
233            regions
234                .iter()
235                .map(|(r, _)| r.len().div_ceil(max_fragment_size))
236                .sum(),
237        );
238        for (region, pid) in regions {
239            let mut payload_data_index = region.start;
240            while payload_data_index < region.end {
241                let current_fragment_size =
242                    std::cmp::min(max_fragment_size, region.end - payload_data_index);
243                let mut out = BytesMut::with_capacity(using_header_size + current_fragment_size);
244                let mut first = pid;
245                if has_extension {
246                    first |= 0x80; // X
247                }
248                if info.non_reference {
249                    first |= 0x20; // N
250                }
251                if payload_data_index == region.start {
252                    first |= 0x10; // S: the first packet of a partition
253                }
254                out.put_u8(first);
255                out.put(&extension[..extension_len]);
256                out.put(
257                    &*payload.slice(payload_data_index..payload_data_index + current_fragment_size),
258                );
259                payloads.push(out.freeze());
260
261                payload_data_index += current_fragment_size;
262            }
263        }
264
265        self.picture_id += 1;
266        self.picture_id &= 0x7FFF;
267        self.tl0_pic_idx = tl0_pic_idx;
268
269        Ok(payloads)
270    }
271}
272
273impl Payloader for Vp8Payloader {
274    /// Payload fragments a VP8 packet across one or more byte arrays
275    fn payload(&mut self, mtu: usize, payload: &Bytes) -> Result<Vec<Bytes>> {
276        self.payload_frame(mtu, payload, &Vp8FrameInfo::default())
277    }
278
279    fn clone_to(&self) -> Box<dyn Payloader> {
280        Box::new(*self)
281    }
282}
283
284/// Vp8Packet represents the VP8 header that is stored in the payload of an RTP Packet
285///
286/// Every field describes the packet last given to [`Depacketizer::depacketize`]: a field the
287/// packet did not carry reads 0.
288#[derive(PartialEq, Eq, Debug, Default, Clone)]
289pub struct Vp8Packet {
290    /// Required Header
291    /// extended controlbits present
292    pub x: u8,
293    /// when set to 1 this frame can be discarded
294    pub n: u8,
295    /// start of VP8 partition
296    pub s: u8,
297    /// partition index
298    pub pid: u8,
299
300    /// Extended control bits
301    /// 1 if PictureID is present
302    pub i: u8,
303    /// 1 if tl0picidx is present
304    pub l: u8,
305    /// 1 if tid is present
306    pub t: u8,
307    /// 1 if KEYIDX is present
308    pub k: u8,
309
310    /// Optional extension
311    /// 7 or 15 bits, picture ID
312    pub picture_id: u16,
313    /// Whether the picture ID was sent in 15 bits (`M`=1) rather than 7. The width can change
314    /// during a session (RFC 7741 section 4.2); a PictureID wraps at the width it was sent in.
315    pub picture_id_15_bits: bool,
316    /// 8 bits temporal level zero index
317    pub tl0_pic_idx: u8,
318    /// 2 bits temporal layer index
319    pub tid: u8,
320    /// 1 bit layer sync bit
321    pub y: u8,
322    /// 5 bits temporal key frame index
323    pub key_idx: u8,
324}
325
326impl Vp8Packet {
327    /// Parses the payload descriptor at the start of `packet` and returns its length.
328    fn parse_descriptor(&mut self, packet: &[u8]) -> Result<usize> {
329        //    0 1 2 3 4 5 6 7                      0 1 2 3 4 5 6 7
330        //    +-+-+-+-+-+-+-+-+                   +-+-+-+-+-+-+-+-+
331        //    |X|R|N|S|R| PID | (REQUIRED)        |X|R|N|S|R| PID | (REQUIRED)
332        //    +-+-+-+-+-+-+-+-+                   +-+-+-+-+-+-+-+-+
333        // X: |I|L|T|K| RSV   | (OPTIONAL)   X:   |I|L|T|K| RSV   | (OPTIONAL)
334        //    +-+-+-+-+-+-+-+-+                   +-+-+-+-+-+-+-+-+
335        // I: |M| PictureID   | (OPTIONAL)   I:   |M| PictureID   | (OPTIONAL)
336        //    +-+-+-+-+-+-+-+-+                   +-+-+-+-+-+-+-+-+
337        // L: |   tl0picidx   | (OPTIONAL)        |   PictureID   |
338        //    +-+-+-+-+-+-+-+-+                   +-+-+-+-+-+-+-+-+
339        //T/K:|tid|Y| KEYIDX  | (OPTIONAL)   L:   |   tl0picidx   | (OPTIONAL)
340        //    +-+-+-+-+-+-+-+-+                   +-+-+-+-+-+-+-+-+
341        //T/K:|tid|Y| KEYIDX  | (OPTIONAL)
342        //    +-+-+-+-+-+-+-+-+
343        // One depacketizer reads a whole stream: nothing of the previous packet's descriptor
344        // may be left for this one (RFC 7741 4.2: with X=0 there are no extensions).
345        *self = Self::default();
346
347        let mut index = 0;
348        let mut next = || -> Result<u8> {
349            let b = *packet.get(index).ok_or(Error::ErrShortPacket)?;
350            index += 1;
351            Ok(b)
352        };
353
354        // The R bits (0x40, 0x08) are ignored.
355        let b = next()?;
356        self.x = (b & 0x80) >> 7;
357        self.n = (b & 0x20) >> 5;
358        self.s = (b & 0x10) >> 4;
359        self.pid = b & 0x07;
360
361        if self.x == 1 {
362            // The four RSV bits are ignored.
363            let b = next()?;
364            self.i = (b & 0x80) >> 7;
365            self.l = (b & 0x40) >> 6;
366            self.t = (b & 0x20) >> 5;
367            self.k = (b & 0x10) >> 4;
368        }
369
370        if self.i == 1 {
371            let b = next()?;
372            if b & 0x80 > 0 {
373                // M == 1, PID is 15 bits
374                self.picture_id = (((b & 0x7f) as u16) << 8) | (next()? as u16);
375                self.picture_id_15_bits = true;
376            } else {
377                self.picture_id = b as u16;
378            }
379        }
380
381        if self.l == 1 {
382            self.tl0_pic_idx = next()?;
383        }
384
385        if self.t == 1 || self.k == 1 {
386            let b = next()?;
387            // TID and Y are ignored without T, KEYIDX without K.
388            if self.t == 1 {
389                self.tid = b >> 6;
390                self.y = (b >> 5) & 0x1;
391            }
392            if self.k == 1 {
393                self.key_idx = b & 0x1F;
394            }
395        }
396
397        Ok(index)
398    }
399
400    /// Whether this packet is the first of a frame: `S`=1 and `PID`=0 (RFC 7741 section 4.5.1).
401    pub fn is_frame_start(&self) -> bool {
402        self.s == 1 && self.pid == 0
403    }
404}
405
406impl Depacketizer for Vp8Packet {
407    /// depacketize parses the passed byte slice and stores the result in the VP8Packet this method is called upon
408    ///
409    /// A packet is its descriptor and at least one octet of VP8 data (RFC 7741 section 4.2);
410    /// anything shorter is an error.
411    fn depacketize(&mut self, packet: &Bytes) -> Result<Bytes> {
412        let descriptor_len = self.parse_descriptor(packet)?;
413        if descriptor_len >= packet.len() {
414            return Err(Error::ErrShortPacket);
415        }
416        Ok(packet.slice(descriptor_len..))
417    }
418
419    /// Whether the packet starts a frame: `S`=1 and `PID`=0 (RFC 7741 section 4.5.1). `S`=1
420    /// with another `PID` starts a later partition of a frame.
421    fn is_partition_head(&self, payload: &Bytes) -> bool {
422        if payload.is_empty() {
423            false
424        } else {
425            (payload[0] & 0x10) != 0 && (payload[0] & 0x07) == 0
426        }
427    }
428
429    fn is_partition_tail(&self, marker: bool, _payload: &Bytes) -> bool {
430        marker
431    }
432
433    fn has_key_frames(&self) -> bool {
434        true
435    }
436
437    /// The first packet of a frame (`S`=1, `PID`=0) whose payload header has `P`=0 (RFC 7741
438    /// section 4.3: "P: Inverse key frame flag. When set to 0, the current frame is a key
439    /// frame"; the payload header is in the first packet of each frame only, and key frames
440    /// "are decoded without reference to any other frame", section 3).
441    fn is_key_frame_start(&self, payload: &Bytes) -> bool {
442        if !self.is_partition_head(payload) {
443            return false;
444        }
445        // The descriptor (RFC 7741 section 4.2): the first octet, with X the extension octet,
446        // then the picture ID (one or two octets), TL0PICIDX and the TID/KEYIDX octet.
447        let mut index = 1;
448        if payload[0] & 0x80 != 0 {
449            let Some(&extension) = payload.get(1) else {
450                return false;
451            };
452            index += 1;
453            if extension & 0x80 != 0 {
454                index += match payload.get(index) {
455                    Some(m) if m & 0x80 != 0 => 2,
456                    Some(_) => 1,
457                    None => return false,
458                };
459            }
460            if extension & 0x40 != 0 {
461                index += 1;
462            }
463            if extension & 0x30 != 0 {
464                index += 1;
465            }
466        }
467        payload.get(index).is_some_and(|header| header & 0x01 == 0)
468    }
469}
470
471/// Decides which packets of a VP8 stream with temporal layers to forward for a target frame
472/// rate (RFC 7741 sections 4.2 and 8: discarding by `TID`).
473///
474/// A middlebox keeps one per receiver. Layers at or below the target are forwarded. Going down
475/// takes effect at once. Going up waits for a switch point: a key frame, or a frame with the
476/// layer sync bit `Y` (it depends on the base layer only, and no later frame depends on
477/// anything older than that base layer frame). A stream without `TID` is forwarded whole.
478#[derive(Debug, Clone, PartialEq, Eq)]
479pub struct Vp8TemporalLayerFilter {
480    target_tid: u8,
481    /// The highest layer forwarded at the moment.
482    current_tid: u8,
483    /// The lowest layer, at or below the target, of which a packet was withheld since the last
484    /// base layer frame. A layer sync frame vouches for what is older than that base layer
485    /// frame, not for what was withheld after it.
486    withheld_tid: Option<u8>,
487}
488
489impl Default for Vp8TemporalLayerFilter {
490    fn default() -> Self {
491        Self::new(VP8_MAX_TEMPORAL_ID)
492    }
493}
494
495impl Vp8TemporalLayerFilter {
496    /// A filter that forwards the layers up to `target_tid`. It starts at the base layer and
497    /// adds the layers above it at a switch point.
498    pub fn new(target_tid: u8) -> Self {
499        Self {
500            target_tid: target_tid.min(VP8_MAX_TEMPORAL_ID),
501            current_tid: 0,
502            withheld_tid: None,
503        }
504    }
505
506    /// Changes the target layer. A lower one applies to the next packet; a higher one at the
507    /// next switch point.
508    pub fn set_target(&mut self, target_tid: u8) {
509        self.target_tid = target_tid.min(VP8_MAX_TEMPORAL_ID);
510        self.current_tid = self.current_tid.min(self.target_tid);
511    }
512
513    /// The target layer.
514    pub fn target(&self) -> u8 {
515        self.target_tid
516    }
517
518    /// The highest layer forwarded at the moment.
519    pub fn current(&self) -> u8 {
520        self.current_tid
521    }
522
523    /// Whether to forward a packet: `descriptor` is its parsed payload descriptor (a
524    /// [`Vp8Packet`] after [`Depacketizer::depacketize`]) and `vp8_data` the VP8 data that
525    /// follows the descriptor. Call it for every packet of the stream, in order.
526    pub fn forward(&mut self, descriptor: &Vp8Packet, vp8_data: &[u8]) -> bool {
527        if descriptor.t == 0 {
528            // No temporal layer information: nothing to select on.
529            return true;
530        }
531        let tid = descriptor.tid;
532        if descriptor.is_frame_start() {
533            // The first octet of a frame is the VP8 frame tag; its low bit is 0 on a key frame
534            // (RFC 6386 section 9.1). A key frame restarts every layer.
535            if vp8_data.first().is_some_and(|b| b & 0x01 == 0) {
536                self.current_tid = self.target_tid;
537                self.withheld_tid = None;
538            } else if tid == 0 {
539                self.withheld_tid = None;
540            }
541        }
542        if tid > self.target_tid {
543            return false;
544        }
545        if tid <= self.current_tid {
546            return true;
547        }
548        // A layer above the ones forwarded so far. A layer sync frame opens every layer of
549        // which nothing was withheld since the base layer frame it depends on. The frame's
550        // first packet decides; its other packets follow because the layer is then current.
551        if descriptor.y == 1 && descriptor.is_frame_start() {
552            let open = match self.withheld_tid {
553                Some(withheld) => withheld.saturating_sub(1).min(self.target_tid),
554                None => self.target_tid,
555            };
556            if tid <= open {
557                self.current_tid = open;
558                return true;
559            }
560        }
561        self.withheld_tid = Some(self.withheld_tid.map_or(tid, |w| w.min(tid)));
562        false
563    }
564}