rtci_rtcp/application_defined/
mod.rs1#[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#[derive(Debug, PartialEq, Eq, Default, Clone)]
38pub struct ApplicationDefined {
39 pub subtype: u8,
41 pub ssrc: u32,
43 pub name: [u8; 4],
45 pub data: Bytes,
47}
48
49impl ApplicationDefined {
50 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 if self.subtype as usize > COUNT_MAX || !self.name.is_ascii() {
105 return Err(Error::InvalidHeader);
106 }
107 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 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}