Skip to main content

avb_stream/
crf.rs

1//! CRF PDUs (IEEE 1722-2016, 10): a media clock as the gPTP times of
2//! every so many of its events, 64 bits each, after a header.
3
4use atdecc::stream_format::{FormatKind, StreamFormat};
5
6/// CRF's AVTP subtype.
7pub const SUBTYPE: u8 = 0x04;
8/// Octets of the CRF header.
9pub const HEADER_LEN: usize = 20;
10/// The CRF type of an audio sample clock (Table 26).
11pub const AUDIO_SAMPLE: u8 = 1;
12
13/// What a CRF stream carries, from its stream format.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct Layout {
16    /// Clock events from one timestamp to the next.
17    pub timestamp_interval: u16,
18    pub timestamps_per_pdu: u8,
19    pub base_frequency: u32,
20}
21
22impl Layout {
23    /// The layout of a CRF stream format, when it is one this crate can
24    /// send and receive: an audio sample clock at its nominal rate.
25    pub fn of(format: StreamFormat) -> Option<Self> {
26        let FormatKind::Crf(crf) = format.kind() else {
27            return None;
28        };
29        (crf.crf_type == AUDIO_SAMPLE
30            && crf.pull == 0
31            && crf.timestamp_interval > 0
32            && crf.timestamps_per_pdu > 0
33            && crf.base_frequency > 0)
34            .then_some(Layout {
35                timestamp_interval: crf.timestamp_interval,
36                timestamps_per_pdu: crf.timestamps_per_pdu,
37                base_frequency: crf.base_frequency,
38            })
39    }
40
41    /// Octets of timestamps in each frame.
42    pub fn data_length(&self) -> usize {
43        8 * usize::from(self.timestamps_per_pdu)
44    }
45
46    /// The AVTPDU's octets: header and timestamps, as MSRP's MaxFrameSize
47    /// counts them.
48    pub fn pdu_length(&self) -> usize {
49        HEADER_LEN + self.data_length()
50    }
51
52    /// Clock events each frame covers.
53    pub fn events_per_frame(&self) -> u64 {
54        u64::from(self.timestamp_interval) * u64::from(self.timestamps_per_pdu)
55    }
56
57    /// How often a frame goes out, in nanoseconds.
58    pub fn interval_nanos(&self) -> u64 {
59        1_000_000_000 * self.events_per_frame() / u64::from(self.base_frequency)
60    }
61
62    /// The nanoseconds from a frame's first timestamp to its `index`th.
63    fn after_first(&self, index: u8) -> i64 {
64        let events = u128::from(self.timestamp_interval) * u128::from(index);
65        (events * 1_000_000_000 / u128::from(self.base_frequency)) as i64
66    }
67}
68
69/// A CRF header's fields.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub struct Header {
72    pub sequence: u8,
73    pub stream_id: u64,
74    pub media_reset: bool,
75    /// The timestamps may be off, as while the clock settles (tu).
76    pub uncertain: bool,
77    pub crf_type: u8,
78    pub pull: u8,
79    pub base_frequency: u32,
80    pub timestamp_interval: u16,
81    pub data_length: u16,
82}
83
84impl Header {
85    /// The header of a frame of `layout`.
86    pub fn of(layout: &Layout, sequence: u8, stream_id: u64, media_reset: bool) -> Self {
87        Header {
88            sequence,
89            stream_id,
90            media_reset,
91            uncertain: false,
92            crf_type: AUDIO_SAMPLE,
93            pull: 0,
94            base_frequency: layout.base_frequency,
95            timestamp_interval: layout.timestamp_interval,
96            data_length: layout.data_length() as u16,
97        }
98    }
99
100    pub fn encode(&self, out: &mut [u8; HEADER_LEN]) {
101        out[0] = SUBTYPE;
102        // sv, version 0, mr, fs 0, tu.
103        out[1] = 0x80 | if self.media_reset { 0x08 } else { 0 } | u8::from(self.uncertain);
104        out[2] = self.sequence;
105        out[3] = self.crf_type;
106        out[4..12].copy_from_slice(&self.stream_id.to_be_bytes());
107        let frequency = (u32::from(self.pull) << 29) | (self.base_frequency & 0x1fff_ffff);
108        out[12..16].copy_from_slice(&frequency.to_be_bytes());
109        out[16..18].copy_from_slice(&self.data_length.to_be_bytes());
110        out[18..20].copy_from_slice(&self.timestamp_interval.to_be_bytes());
111    }
112
113    /// Decodes a CRF PDU, returning its header and timestamps.
114    pub fn decode(pdu: &[u8]) -> Option<(Header, &[u8])> {
115        let header: &[u8; HEADER_LEN] = pdu.get(..HEADER_LEN)?.try_into().ok()?;
116        if header[0] != SUBTYPE || header[1] & 0x80 == 0 {
117            return None;
118        }
119        let data_length = u16::from_be_bytes([header[16], header[17]]);
120        let timestamps = pdu.get(HEADER_LEN..HEADER_LEN + usize::from(data_length))?;
121        let mut stream_id = [0; 8];
122        stream_id.copy_from_slice(&header[4..12]);
123        let frequency = u32::from_be_bytes([header[12], header[13], header[14], header[15]]);
124        Some((
125            Header {
126                sequence: header[2],
127                stream_id: u64::from_be_bytes(stream_id),
128                media_reset: header[1] & 0x08 != 0,
129                uncertain: header[1] & 0x01 != 0,
130                crf_type: header[3],
131                pull: (frequency >> 29) as u8,
132                base_frequency: frequency & 0x1fff_ffff,
133                timestamp_interval: u16::from_be_bytes([header[18], header[19]]),
134                data_length,
135            },
136            timestamps,
137        ))
138    }
139
140    /// Whether the frame carries the clock `layout` describes.
141    pub fn matches(&self, layout: &Layout) -> bool {
142        self.crf_type == AUDIO_SAMPLE
143            && self.pull == 0
144            && self.base_frequency == layout.base_frequency
145            && self.timestamp_interval == layout.timestamp_interval
146            && usize::from(self.data_length) == layout.data_length()
147    }
148}
149
150/// Writes a frame's timestamps, the first `first` (gPTP nanoseconds) and
151/// each next one a timestamp interval on.
152pub fn write_timestamps(first: i64, layout: &Layout, out: &mut [u8]) {
153    for index in 0..layout.timestamps_per_pdu {
154        let at = 8 * usize::from(index);
155        let time = (first + layout.after_first(index)) as u64;
156        out[at..at + 8].copy_from_slice(&time.to_be_bytes());
157    }
158}
159
160/// A frame's first timestamp, in gPTP nanoseconds.
161pub fn first_timestamp(timestamps: &[u8]) -> Option<u64> {
162    Some(u64::from_be_bytes(timestamps.get(..8)?.try_into().ok()?))
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    /// Milan's media clock: 48 kHz, a timestamp every 96 samples, one a
170    /// frame, 500 frames a second.
171    const MILAN: StreamFormat = StreamFormat(0x0410_6001_0000_bb80);
172
173    #[test]
174    fn milans_media_clock_goes_out_and_comes_back() {
175        let layout = Layout::of(MILAN).unwrap();
176        assert_eq!(layout.pdu_length(), 28);
177        assert_eq!(layout.interval_nanos(), 2_000_000);
178        let mut pdu = vec![0; layout.pdu_length()];
179        let mut header = [0; HEADER_LEN];
180        Header::of(&layout, 7, 0x9c6b_0030_9a2b_0001, false).encode(&mut header);
181        pdu[..HEADER_LEN].copy_from_slice(&header);
182        write_timestamps(5_000_000_123, &layout, &mut pdu[HEADER_LEN..]);
183        let (back, timestamps) = Header::decode(&pdu).unwrap();
184        assert_eq!(back.sequence, 7);
185        assert_eq!(back.stream_id, 0x9c6b_0030_9a2b_0001);
186        assert!(back.matches(&layout));
187        assert_eq!(first_timestamp(timestamps), Some(5_000_000_123));
188        // Its octets as 1722 lays them out.
189        assert_eq!(
190            &pdu[..4],
191            [SUBTYPE, 0x80, 7, AUDIO_SAMPLE],
192            "subtype, sv, sequence, type"
193        );
194        assert_eq!(&pdu[12..20], [0, 0, 0xbb, 0x80, 0, 8, 0, 96]);
195    }
196
197    /// Several timestamps a frame are a timestamp interval apart, to the
198    /// nanosecond.
199    #[test]
200    fn timestamps_a_frame_are_an_interval_apart() {
201        let layout = Layout {
202            timestamp_interval: 160,
203            timestamps_per_pdu: 6,
204            base_frequency: 48_000,
205        };
206        let mut data = vec![0; layout.data_length()];
207        write_timestamps(1_000_000, &layout, &mut data);
208        let times: Vec<u64> = data
209            .chunks(8)
210            .map(|chunk| u64::from_be_bytes(chunk.try_into().unwrap()))
211            .collect();
212        assert_eq!(
213            times,
214            [
215                1_000_000, 4_333_333, 7_666_666, 11_000_000, 14_333_333, 17_666_666
216            ]
217        );
218        assert_eq!(layout.interval_nanos(), 20_000_000);
219    }
220
221    /// Video frame clocks, and pulled ones, are not sent.
222    #[test]
223    fn only_audio_sample_clocks_are_taken() {
224        assert!(Layout::of(StreamFormat(0x0420_0101_0000_0018)).is_none());
225        assert!(Layout::of(StreamFormat(0x0410_6001_2000_bb80)).is_none());
226        assert!(Layout::of(StreamFormat(0x0205_0220_0200_6000)).is_none());
227    }
228}