Skip to main content

atdecc/
lite.rs

1//! AVB Lite's ATDECC messages (AVB Lite profile, 2.4 and 6): the status
2//! query an endpoint reports its mode with, and the CVU SRP messages that
3//! carry MSRP declarations where bridges do not. Both are AECP vendor
4//! unique messages under the AVB Lite MA-S OUI `8C-1F-64-36-C`.
5
6use crate::aecp::{AecpHeader, AecpMessageType, VendorUniquePdu};
7use crate::avtp::{read_u16, read_u32, read_u64};
8use crate::error::{DecodeError, EncodeError};
9use crate::id::{ClockIdentity, EntityId};
10use crate::macros::{code, flags};
11
12/// CVU SRP, sub-protocol `0x002`.
13pub const CVU_PROTOCOL_ID: [u8; 6] = [0x8c, 0x1f, 0x64, 0x36, 0xc0, 0x02];
14/// The status query, sub-protocol `0x003`.
15pub const STATUS_PROTOCOL_ID: [u8; 6] = [0x8c, 0x1f, 0x64, 0x36, 0xc0, 0x03];
16
17code! {
18    /// The status query's command_type.
19    pub struct LiteCommandType(u16) {
20        const GET_LITE_STATUS = 0x0000;
21        const SET_LITE_CONFIG = 0x0001;
22    }
23}
24
25flags! {
26    /// GET_LITE_STATUS flags.
27    pub struct LiteFlags(u8) {
28        /// The endpoint supports AVB Lite.
29        const CAPABLE = 0x01;
30        /// The interface operates in AVB Lite.
31        const ACTIVE = 0x02;
32        const OFFSET_VALID = 0x04;
33        const EGRESS_VALID = 0x08;
34        /// Talkers on the interface may escalate streams to multicast.
35        const ESCALATION_ALLOWED = 0x10;
36    }
37}
38
39flags! {
40    /// SET_LITE_CONFIG's config_flags (profile 2.4).
41    pub struct LiteConfigFlags(u8) {
42        /// Talkers on the interface may escalate streams to multicast.
43        const ESCALATION_ALLOWED = 0x01;
44    }
45}
46
47code! {
48    /// Why an interface operates in AVB Lite (profile 2.2).
49    pub struct FallbackReason(u8) {
50        /// It operates in standard AVB.
51        const NONE = 0;
52        const ENDPOINT_TLV = 1;
53        const PDELAY_UNANSWERED = 2;
54        const MULTIPLE_RESPONDERS = 3;
55        /// The operator or a controller set it.
56        const CONFIGURED = 4;
57    }
58}
59
60code! {
61    pub struct PtpProfile(u8) {
62        const GPTP = 0;
63        const AVB_LITE_PTP = 1;
64    }
65}
66
67/// The status query part of a vendor unique PDU: the u flag, the command
68/// type and the command specific data after them.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub struct LiteMessage<'a> {
71    pub unsolicited: bool,
72    pub command_type: LiteCommandType,
73    pub data: &'a [u8],
74}
75
76impl<'a> LiteMessage<'a> {
77    /// The status query message in a vendor unique PDU, if it is one.
78    pub fn from_pdu(pdu: &VendorUniquePdu<'a>) -> Result<Self, DecodeError> {
79        if pdu.protocol_id != STATUS_PROTOCOL_ID {
80            return Err(DecodeError::WrongProtocol);
81        }
82        let Some(word) = pdu.payload.get(..2) else {
83            return Err(DecodeError::Truncated {
84                needed: 2,
85                available: pdu.payload.len(),
86            });
87        };
88        let word = read_u16(word, 0);
89        Ok(Self {
90            unsolicited: word & 0x8000 != 0,
91            command_type: LiteCommandType(word & 0x7fff),
92            data: &pdu.payload[2..],
93        })
94    }
95}
96
97/// Encodes a GET_LITE_STATUS command for an AVB_INTERFACE.
98pub fn encode_get_lite_status(
99    target: EntityId,
100    controller: EntityId,
101    sequence_id: u16,
102    interface: u16,
103    out: &mut [u8],
104) -> Result<usize, EncodeError> {
105    let header = AecpHeader {
106        message_type: AecpMessageType::VENDOR_UNIQUE_COMMAND,
107        status: 0,
108        target_entity_id: target,
109        controller_entity_id: controller,
110        sequence_id,
111    };
112    let command = LiteCommandType::GET_LITE_STATUS.0.to_be_bytes();
113    header.encode(
114        &[&STATUS_PROTOCOL_ID, &command, &interface.to_be_bytes()],
115        out,
116    )
117}
118
119/// Encodes a SET_LITE_CONFIG command for an AVB_INTERFACE.
120pub fn encode_set_lite_config(
121    target: EntityId,
122    controller: EntityId,
123    sequence_id: u16,
124    interface: u16,
125    flags: LiteConfigFlags,
126    out: &mut [u8],
127) -> Result<usize, EncodeError> {
128    let header = AecpHeader {
129        message_type: AecpMessageType::VENDOR_UNIQUE_COMMAND,
130        status: 0,
131        target_entity_id: target,
132        controller_entity_id: controller,
133        sequence_id,
134    };
135    let command = LiteCommandType::SET_LITE_CONFIG.0.to_be_bytes();
136    header.encode(
137        &[
138            &STATUS_PROTOCOL_ID,
139            &command,
140            &interface.to_be_bytes(),
141            &[flags.0, 0, 0, 0],
142        ],
143        out,
144    )
145}
146
147/// What an endpoint reports of an interface in a GET_LITE_STATUS
148/// response.
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150pub struct LiteStatus {
151    pub interface: u16,
152    pub flags: LiteFlags,
153    pub fallback_reason: FallbackReason,
154    pub ptp_profile: PtpProfile,
155    pub ptp_domain: u8,
156    /// 0 when streams are untagged.
157    pub media_vlan_id: u16,
158    pub unicast_fanout_limit: u8,
159    /// Mb/s, 0 when not known.
160    pub link_speed: u32,
161    /// kb/s of admitted streams sent, each unicast copy counted.
162    pub committed_egress: u32,
163    pub grandmaster: ClockIdentity,
164    /// Nanoseconds.
165    pub offset_from_grandmaster: i32,
166}
167
168impl LiteStatus {
169    /// The response's octets after the command_type.
170    const LEN: usize = 30;
171
172    /// Decodes the data after the command_type of a response.
173    pub fn decode(data: &[u8]) -> Result<Self, DecodeError> {
174        if data.len() < Self::LEN {
175            return Err(DecodeError::Truncated {
176                needed: Self::LEN,
177                available: data.len(),
178            });
179        }
180        Ok(Self {
181            interface: read_u16(data, 0),
182            flags: LiteFlags(data[2]),
183            fallback_reason: FallbackReason(data[3]),
184            ptp_profile: PtpProfile(data[4]),
185            ptp_domain: data[5],
186            media_vlan_id: read_u16(data, 6),
187            unicast_fanout_limit: data[8],
188            link_speed: read_u32(data, 10),
189            committed_egress: read_u32(data, 14),
190            grandmaster: ClockIdentity(read_u64(data, 18)),
191            offset_from_grandmaster: read_u32(data, 26) as i32,
192        })
193    }
194
195    /// The data after the command_type, as a response carries it.
196    pub fn to_bytes(&self) -> [u8; Self::LEN] {
197        let mut out = [0; Self::LEN];
198        out[0..2].copy_from_slice(&self.interface.to_be_bytes());
199        out[2] = self.flags.0;
200        out[3] = self.fallback_reason.0;
201        out[4] = self.ptp_profile.0;
202        out[5] = self.ptp_domain;
203        out[6..8].copy_from_slice(&self.media_vlan_id.to_be_bytes());
204        out[8] = self.unicast_fanout_limit;
205        out[10..14].copy_from_slice(&self.link_speed.to_be_bytes());
206        out[14..18].copy_from_slice(&self.committed_egress.to_be_bytes());
207        out[18..26].copy_from_slice(&self.grandmaster.0.to_be_bytes());
208        out[26..30].copy_from_slice(&self.offset_from_grandmaster.to_be_bytes());
209        out
210    }
211
212    /// The offset from the grandmaster, when the endpoint measured it.
213    pub fn offset(&self) -> Option<i32> {
214        self.flags
215            .contains(LiteFlags::OFFSET_VALID)
216            .then_some(self.offset_from_grandmaster)
217    }
218
219    /// The committed egress, when the endpoint keeps it.
220    pub fn egress(&self) -> Option<u32> {
221        self.flags
222            .contains(LiteFlags::EGRESS_VALID)
223            .then_some(self.committed_egress)
224    }
225}
226
227/// A CVU SRP message: an MSRP message carried in a vendor unique command,
228/// from the endpoint the PDU's controller_entity_id names.
229#[derive(Debug, Clone, Copy, PartialEq, Eq)]
230pub struct CvuMessage<'a> {
231    pub sender: EntityId,
232    /// The MSRP attribute type of the message.
233    pub command_type: u8,
234    /// The MSRP message, from its AttributeType through its EndMark.
235    pub msrp: &'a [u8],
236}
237
238impl<'a> CvuMessage<'a> {
239    pub fn from_pdu(pdu: &VendorUniquePdu<'a>) -> Result<Self, DecodeError> {
240        if pdu.protocol_id != CVU_PROTOCOL_ID {
241            return Err(DecodeError::WrongProtocol);
242        }
243        let Some((&command_type, msrp)) = pdu.payload.split_first() else {
244            return Err(DecodeError::Truncated {
245                needed: 1,
246                available: 0,
247            });
248        };
249        Ok(Self {
250            sender: pdu.header.controller_entity_id,
251            command_type,
252            msrp,
253        })
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260
261    fn status() -> LiteStatus {
262        LiteStatus {
263            interface: 0,
264            flags: LiteFlags::CAPABLE | LiteFlags::ACTIVE | LiteFlags::OFFSET_VALID,
265            fallback_reason: FallbackReason::MULTIPLE_RESPONDERS,
266            ptp_profile: PtpProfile::AVB_LITE_PTP,
267            ptp_domain: 0,
268            media_vlan_id: 2,
269            unicast_fanout_limit: 2,
270            link_speed: 1000,
271            committed_egress: 6_336,
272            grandmaster: ClockIdentity(0x0011_22ff_fe33_4455),
273            offset_from_grandmaster: -320,
274        }
275    }
276
277    #[test]
278    fn status_round_trips_and_says_what_is_valid() {
279        let status = status();
280        let decoded = LiteStatus::decode(&status.to_bytes()).unwrap();
281        assert_eq!(decoded, status);
282        assert_eq!(decoded.offset(), Some(-320));
283        assert_eq!(decoded.egress(), None);
284        assert!(LiteStatus::decode(&status.to_bytes()[..29]).is_err());
285    }
286
287    #[test]
288    fn queries_carry_the_status_protocol() {
289        let mut out = [0; 64];
290        let length = encode_get_lite_status(
291            EntityId(0xe8f6_0ae0_9220_0000),
292            EntityId(0x9c6b_00ff_fe30_9a2b),
293            7,
294            0,
295            &mut out,
296        )
297        .unwrap();
298        let pdu = VendorUniquePdu::decode(&out[..length]).unwrap();
299        let message = LiteMessage::from_pdu(&pdu).unwrap();
300        assert_eq!(message.command_type, LiteCommandType::GET_LITE_STATUS);
301        assert!(!message.unsolicited);
302        assert_eq!(message.data, [0, 0]);
303        assert!(CvuMessage::from_pdu(&pdu).is_err());
304    }
305}