Skip to main content

avb_stream/
aaf.rs

1//! AAF PDUs (IEEE 1722-2016, 7.2): the header and interleaved PCM
2//! samples, big endian.
3
4use atdecc::stream_format::{FormatKind, StreamFormat};
5
6/// AAF's AVTP subtype.
7pub const SUBTYPE: u8 = 0x02;
8/// Octets of the AAF header.
9pub const HEADER_LEN: usize = 24;
10
11/// AAF sample formats (Table 9).
12pub mod sample_format {
13    pub const FLOAT_32: u8 = 1;
14    pub const INT_32: u8 = 2;
15    pub const INT_24: u8 = 3;
16    pub const INT_16: u8 = 4;
17}
18
19/// What an AAF stream carries, from its stream format.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub struct Layout {
22    pub nsr: u8,
23    pub sample_rate: u32,
24    pub sample_format: u8,
25    pub bit_depth: u8,
26    pub channels: u16,
27    pub samples_per_frame: u16,
28}
29
30impl Layout {
31    /// The layout of an AAF stream format, when it is one this crate can
32    /// send and receive: 16, 24 or 32-bit integers or 32-bit floats.
33    pub fn of(format: StreamFormat) -> Option<Self> {
34        let FormatKind::Aaf(aaf) = format.kind() else {
35            return None;
36        };
37        let sample_rate = atdecc::stream_format::nsr_hertz(aaf.nsr)?;
38        if aaf.channels == 0 || aaf.samples_per_frame == 0 {
39            return None;
40        }
41        matches!(
42            aaf.sample_format,
43            sample_format::FLOAT_32
44                | sample_format::INT_32
45                | sample_format::INT_24
46                | sample_format::INT_16
47        )
48        .then_some(Layout {
49            nsr: aaf.nsr,
50            sample_rate,
51            sample_format: aaf.sample_format,
52            bit_depth: aaf.bit_depth,
53            channels: aaf.channels,
54            samples_per_frame: aaf.samples_per_frame,
55        })
56    }
57
58    /// Octets of one sample.
59    pub fn sample_octets(&self) -> usize {
60        match self.sample_format {
61            sample_format::INT_24 => 3,
62            sample_format::INT_16 => 2,
63            _ => 4,
64        }
65    }
66
67    /// Octets of samples in each frame.
68    pub fn data_length(&self) -> usize {
69        usize::from(self.channels) * usize::from(self.samples_per_frame) * self.sample_octets()
70    }
71
72    /// The AVTPDU's octets: header and samples, as MSRP's MaxFrameSize
73    /// counts them.
74    pub fn pdu_length(&self) -> usize {
75        HEADER_LEN + self.data_length()
76    }
77
78    /// How often a frame goes out, in nanoseconds.
79    pub fn interval_nanos(&self) -> u64 {
80        1_000_000_000 * u64::from(self.samples_per_frame) / u64::from(self.sample_rate)
81    }
82}
83
84/// An AAF header's fields.
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub struct Header {
87    pub sequence: u8,
88    pub stream_id: u64,
89    /// The presentation time: the low 32 bits of gPTP nanoseconds, when
90    /// valid.
91    pub timestamp: Option<u32>,
92    pub media_reset: bool,
93    pub nsr: u8,
94    pub sample_format: u8,
95    pub bit_depth: u8,
96    pub channels: u16,
97    pub data_length: u16,
98}
99
100impl Header {
101    pub fn encode(&self, out: &mut [u8; HEADER_LEN]) {
102        out[0] = SUBTYPE;
103        // sv, version 0, mr, gv 0, tv.
104        out[1] =
105            0x80 | if self.media_reset { 0x08 } else { 0 } | u8::from(self.timestamp.is_some());
106        out[2] = self.sequence;
107        out[3] = 0;
108        out[4..12].copy_from_slice(&self.stream_id.to_be_bytes());
109        out[12..16].copy_from_slice(&self.timestamp.unwrap_or(0).to_be_bytes());
110        out[16] = self.sample_format;
111        out[17] = (self.nsr << 4) | ((self.channels >> 8) as u8 & 0x03);
112        out[18] = self.channels as u8;
113        out[19] = self.bit_depth;
114        out[20..22].copy_from_slice(&self.data_length.to_be_bytes());
115        out[22] = 0; // sp 0: normal packing; evt 0
116        out[23] = 0;
117    }
118
119    /// Decodes an AAF PDU, returning its header and samples.
120    pub fn decode(pdu: &[u8]) -> Option<(Header, &[u8])> {
121        let header: &[u8; HEADER_LEN] = pdu.get(..HEADER_LEN)?.try_into().ok()?;
122        if header[0] != SUBTYPE || header[1] & 0x80 == 0 {
123            return None;
124        }
125        let data_length = u16::from_be_bytes([header[20], header[21]]);
126        let samples = pdu.get(HEADER_LEN..HEADER_LEN + usize::from(data_length))?;
127        let mut stream_id = [0; 8];
128        stream_id.copy_from_slice(&header[4..12]);
129        Some((
130            Header {
131                sequence: header[2],
132                stream_id: u64::from_be_bytes(stream_id),
133                timestamp: (header[1] & 0x01 != 0)
134                    .then(|| u32::from_be_bytes([header[12], header[13], header[14], header[15]])),
135                media_reset: header[1] & 0x08 != 0,
136                nsr: header[17] >> 4,
137                sample_format: header[16],
138                bit_depth: header[19],
139                channels: (u16::from(header[17] & 0x03) << 8) | u16::from(header[18]),
140                data_length,
141            },
142            samples,
143        ))
144    }
145
146    /// Whether the frame carries what `layout` describes.
147    pub fn matches(&self, layout: &Layout) -> bool {
148        self.nsr == layout.nsr
149            && self.sample_format == layout.sample_format
150            && self.channels == layout.channels
151    }
152}
153
154/// Writes `samples`, interleaved and from -1 to 1, as `layout`'s sample
155/// format into `out`.
156pub fn write_samples(samples: &[f32], layout: &Layout, out: &mut [u8]) {
157    let octets = layout.sample_octets();
158    for (sample, slot) in samples.iter().zip(out.chunks_exact_mut(octets)) {
159        let clamped = sample.clamp(-1.0, 1.0);
160        match layout.sample_format {
161            sample_format::FLOAT_32 => slot.copy_from_slice(&clamped.to_be_bytes()),
162            sample_format::INT_16 => {
163                let value = (clamped * 32767.0) as i16;
164                slot.copy_from_slice(&value.to_be_bytes());
165            }
166            sample_format::INT_24 => {
167                let value = (f64::from(clamped) * 8_388_607.0) as i32;
168                slot.copy_from_slice(&value.to_be_bytes()[1..]);
169            }
170            _ => {
171                let value = (f64::from(clamped) * 2_147_483_647.0) as i32;
172                slot.copy_from_slice(&value.to_be_bytes());
173            }
174        }
175    }
176}
177
178/// Reads `layout`'s samples from `data` into `out`, from -1 to 1.
179pub fn read_samples(data: &[u8], layout: &Layout, out: &mut Vec<f32>) {
180    let octets = layout.sample_octets();
181    out.extend(
182        data.chunks_exact(octets)
183            .map(|slot| match layout.sample_format {
184                sample_format::FLOAT_32 => f32::from_be_bytes([slot[0], slot[1], slot[2], slot[3]]),
185                sample_format::INT_16 => {
186                    f32::from(i16::from_be_bytes([slot[0], slot[1]])) / 32768.0
187                }
188                sample_format::INT_24 => {
189                    let value = i32::from_be_bytes([slot[0], slot[1], slot[2], 0]) >> 8;
190                    value as f32 / 8_388_608.0
191                }
192                _ => {
193                    let value = i32::from_be_bytes([slot[0], slot[1], slot[2], slot[3]]);
194                    (f64::from(value) / 2_147_483_648.0) as f32
195                }
196            }),
197    );
198}
199
200/// Writes `words`, interleaved samples as 32-bit words, as `layout`'s
201/// sample format into `out`: a 32-bit integer format's exactly, a
202/// narrower one's from their high bits, a float's scaled from the full
203/// range.
204pub fn write_words(words: &[i32], layout: &Layout, out: &mut [u8]) {
205    let octets = layout.sample_octets();
206    for (word, slot) in words.iter().zip(out.chunks_exact_mut(octets)) {
207        match layout.sample_format {
208            sample_format::FLOAT_32 => {
209                let value = (f64::from(*word) / 2_147_483_648.0) as f32;
210                slot.copy_from_slice(&value.to_be_bytes());
211            }
212            _ => slot.copy_from_slice(&word.to_be_bytes()[..octets]),
213        }
214    }
215}
216
217/// Reads `layout`'s samples from `data` into `out` as 32-bit words, as
218/// [`write_words`] writes them.
219pub fn read_words(data: &[u8], layout: &Layout, out: &mut Vec<i32>) {
220    let octets = layout.sample_octets();
221    out.extend(
222        data.chunks_exact(octets)
223            .map(|slot| match layout.sample_format {
224                sample_format::FLOAT_32 => {
225                    let value = f32::from_be_bytes([slot[0], slot[1], slot[2], slot[3]]);
226                    (f64::from(value.clamp(-1.0, 1.0)) * 2_147_483_647.0) as i32
227                }
228                _ => {
229                    let mut word = [0; 4];
230                    word[..octets].copy_from_slice(slot);
231                    i32::from_be_bytes(word)
232                }
233            }),
234    );
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240
241    const AAF_48K_8CH_32: StreamFormat = StreamFormat(0x0205_0220_0200_6000);
242
243    #[test]
244    fn the_bench_format_is_six_frames_of_eight_channels() {
245        let layout = Layout::of(AAF_48K_8CH_32).unwrap();
246        assert_eq!(layout.sample_rate, 48_000);
247        assert_eq!((layout.channels, layout.samples_per_frame), (8, 6));
248        assert_eq!(layout.data_length(), 192);
249        assert_eq!(layout.pdu_length(), 216);
250        assert_eq!(layout.interval_nanos(), 125_000);
251    }
252
253    #[test]
254    fn headers_and_samples_round_trip() {
255        let layout = Layout::of(AAF_48K_8CH_32).unwrap();
256        let header = Header {
257            sequence: 7,
258            stream_id: 0x9c6b_0030_9a2b_0000,
259            timestamp: Some(0x1234_5678),
260            media_reset: false,
261            nsr: layout.nsr,
262            sample_format: layout.sample_format,
263            bit_depth: 32,
264            channels: 8,
265            data_length: layout.data_length() as u16,
266        };
267        let mut pdu = vec![0; layout.pdu_length()];
268        let mut first = [0; HEADER_LEN];
269        header.encode(&mut first);
270        pdu[..HEADER_LEN].copy_from_slice(&first);
271        let samples: Vec<f32> = (0..48).map(|place| place as f32 / 64.0 - 0.3).collect();
272        write_samples(&samples, &layout, &mut pdu[HEADER_LEN..]);
273        let (decoded, data) = Header::decode(&pdu).unwrap();
274        assert_eq!(decoded, header);
275        assert!(decoded.matches(&layout));
276        let mut back = Vec::new();
277        read_samples(data, &layout, &mut back);
278        for (sent, received) in samples.iter().zip(&back) {
279            assert!((sent - received).abs() < 1e-6, "{sent} {received}");
280        }
281    }
282
283    /// Words pass a 32-bit format exactly, every bit, and a 24 or 16-bit
284    /// one in their high bits.
285    #[test]
286    fn words_pass_as_they_are() {
287        let words = [
288            i32::MIN,
289            -1,
290            0,
291            1,
292            0x1234_5678,
293            i32::MAX,
294            0x0000_00ff,
295            -0x0100,
296        ];
297        let mut layout = Layout::of(AAF_48K_8CH_32).unwrap();
298        let mut data = vec![0; 32];
299        write_words(&words, &layout, &mut data);
300        let mut back = Vec::new();
301        read_words(&data, &layout, &mut back);
302        assert_eq!(back, words);
303
304        layout.sample_format = sample_format::INT_24;
305        let mut data = vec![0; 24];
306        write_words(&words, &layout, &mut data);
307        back.clear();
308        read_words(&data, &layout, &mut back);
309        let high: Vec<i32> = words.iter().map(|word| word & !0xff).collect();
310        assert_eq!(back, high);
311
312        layout.sample_format = sample_format::INT_16;
313        let mut data = vec![0; 16];
314        write_words(&words, &layout, &mut data);
315        back.clear();
316        read_words(&data, &layout, &mut back);
317        let high: Vec<i32> = words.iter().map(|word| word & !0xffff).collect();
318        assert_eq!(back, high);
319    }
320
321    #[test]
322    fn other_pdus_do_not_decode() {
323        assert!(Header::decode(&[0xfa; 40]).is_none());
324        assert!(Header::decode(&[SUBTYPE, 0x81]).is_none());
325        assert!(
326            Layout::of(StreamFormat(0x0410_6001_0000_bb80)).is_none(),
327            "CRF"
328        );
329    }
330}