Skip to main content

rtci_rtcp/application_defined/
mod.rs

1//! The APP packet ([RFC 3550] §6.7): application-defined data under a four-character name.
2//!
3//! [RFC 3550]: https://datatracker.ietf.org/doc/html/rfc3550#section-6.7
4#[cfg(test)]
5mod application_defined_test;
6
7use crate::{header::*, packet::*, util::*};
8use shared::{
9    error::{Error, Result},
10    marshal::{Marshal, MarshalSize, Unmarshal},
11};
12
13use bytes::{Buf, BufMut, Bytes};
14use std::fmt;
15
16const APP_NAME_LENGTH: usize = 4;
17
18/// An APP packet: experimental or application-specific data that needs no registered packet
19/// type.
20///
21/// ```text
22///  0                   1                   2                   3
23///  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
24/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
25/// |V=2|P| subtype |   PT=APP=204  |             length            |
26/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
27/// |                           SSRC/CSRC                           |
28/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
29/// |                          name (ASCII)                         |
30/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
31/// |                   application-dependent data                ...
32/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
33/// ```
34///
35/// A receiver that does not recognise the name ignores the packet (RFC 3550 §6.7); this type
36/// is the parsed form either way, so the application can look at `name` and decide.
37#[derive(Debug, PartialEq, Eq, Default, Clone)]
38pub struct ApplicationDefined {
39    /// Five bits the application may use to tell its own packets apart.
40    pub subtype: u8,
41    /// The source the packet comes from.
42    pub ssrc: u32,
43    /// The name the application chose, four ASCII characters, case significant.
44    pub name: [u8; 4],
45    /// The application's data. Its length is a multiple of four octets.
46    pub data: Bytes,
47}
48
49impl ApplicationDefined {
50    /// The name as text, when it is the four ASCII characters RFC 3550 asks for.
51    pub fn name_str(&self) -> Option<&str> {
52        if self.name.is_ascii() {
53            std::str::from_utf8(&self.name).ok()
54        } else {
55            None
56        }
57    }
58}
59
60impl fmt::Display for ApplicationDefined {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        write!(
63            f,
64            "ApplicationDefined {:x} subtype={} name={:?} data={} octets",
65            self.ssrc,
66            self.subtype,
67            self.name_str().unwrap_or("?"),
68            self.data.len()
69        )
70    }
71}
72
73impl Packet for ApplicationDefined {
74    fn header(&self) -> Header {
75        Header {
76            padding: false,
77            count: self.subtype,
78            packet_type: PacketType::ApplicationDefined,
79            length: ((self.marshal_size() / 4) - 1) as u16,
80        }
81    }
82
83    fn destination_ssrc(&self) -> Vec<u32> {
84        vec![self.ssrc]
85    }
86
87    fn raw_size(&self) -> usize {
88        HEADER_LENGTH + SSRC_LENGTH + APP_NAME_LENGTH + self.data.len()
89    }
90
91    packet_any!(ApplicationDefined);
92}
93
94impl MarshalSize for ApplicationDefined {
95    fn marshal_size(&self) -> usize {
96        let l = self.raw_size();
97        l + get_padding_size(l)
98    }
99}
100
101impl Marshal for ApplicationDefined {
102    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
103        // The subtype shares the first octet with the version and the P bit.
104        if self.subtype as usize > COUNT_MAX || !self.name.is_ascii() {
105            return Err(Error::InvalidHeader);
106        }
107        // RFC 3550 6.7: the data "must be a multiple of 32 bits long". How to fill a shorter
108        // value up is the application's format, so it is not padded here.
109        if !self.data.len().is_multiple_of(4) {
110            return Err(Error::WrongMarshalSize);
111        }
112        let size = self.raw_size();
113        if buf.remaining_mut() < size {
114            return Err(Error::BufferTooShort);
115        }
116
117        let h = header_for(PacketType::ApplicationDefined, self.subtype, size)?;
118        let n = h.marshal_to(buf)?;
119        buf = &mut buf[n..];
120
121        buf.put_u32(self.ssrc);
122        buf.put_slice(&self.name);
123        buf.put_slice(&self.data);
124
125        Ok(size)
126    }
127}
128
129impl Unmarshal for ApplicationDefined {
130    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
131    where
132        Self: Sized,
133        B: Buf,
134    {
135        let (header, mut body) = read_packet(raw_packet)?;
136        if header.packet_type != PacketType::ApplicationDefined {
137            return Err(Error::WrongType);
138        }
139        if body.len() < SSRC_LENGTH + APP_NAME_LENGTH {
140            return Err(Error::PacketTooShort);
141        }
142
143        let ssrc = body.get_u32();
144        let mut name = [0u8; APP_NAME_LENGTH];
145        body.copy_to_slice(&mut name);
146        // Padding that was not a whole number of words leaves data that is not one either.
147        if !body.len().is_multiple_of(4) {
148            return Err(Error::WrongPadding);
149        }
150
151        Ok(ApplicationDefined {
152            subtype: header.count,
153            ssrc,
154            name,
155            data: body,
156        })
157    }
158}