Skip to main content

avb_stream/
am824.rs

1//! IEC 61883-6 AM824 PDUs (IEEE 1722-2016, 6.4): the 61883 header, the
2//! CIP header and data blocks of one labeled quadlet per channel, each
3//! a 24-bit sample after the multi-bit linear audio label.
4
5use atdecc::stream_format::{FormatKind, Packing, StreamFormat};
6
7/// The IEC 61883/IIDC AVTP subtype.
8pub const SUBTYPE: u8 = 0x00;
9/// Octets of the AVTP header, then of the CIP header after it.
10pub const HEADER_LEN: usize = 24;
11pub const CIP_LEN: usize = 8;
12/// The CIP FMT of IEC 61883-6 audio and music.
13const FMT: u8 = 0x10;
14/// Multi-bit linear audio, 24 bits.
15const MBLA_24: u8 = 0x40;
16/// SYT when it carries nothing: the AVTP timestamp says when instead.
17const NO_SYT: u16 = 0xffff;
18
19/// What an AM824 stream carries, from its stream format.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub struct Layout {
22    pub sfc: u8,
23    pub sample_rate: u32,
24    pub channels: u16,
25    pub samples_per_frame: u16,
26}
27
28impl Layout {
29    /// The layout of an AM824 stream format, when this crate can send and
30    /// receive it: non-blocking, every quadlet multi-bit linear audio, at
31    /// a rate class A's 8000 frames a second divides.
32    pub fn of(format: StreamFormat) -> Option<Self> {
33        let FormatKind::Iec61883_6(iec) = format.kind() else {
34            return None;
35        };
36        let sample_rate = atdecc::stream_format::sfc_hertz(iec.sfc)?;
37        let usable = iec.packing == Packing::Am824
38            && iec.non_blocking
39            && iec.dbs > 0
40            && iec.labels == [0, iec.dbs, 0, 0]
41            && sample_rate % 8000 == 0;
42        usable.then_some(Layout {
43            sfc: iec.sfc,
44            sample_rate,
45            channels: u16::from(iec.dbs),
46            samples_per_frame: (sample_rate / 8000) as u16,
47        })
48    }
49
50    /// Octets of data blocks in each frame.
51    pub fn data_length(&self) -> usize {
52        usize::from(self.channels) * usize::from(self.samples_per_frame) * 4
53    }
54
55    /// The AVTPDU's octets, as MSRP's MaxFrameSize counts them.
56    pub fn pdu_length(&self) -> usize {
57        HEADER_LEN + CIP_LEN + self.data_length()
58    }
59
60    pub fn interval_nanos(&self) -> u64 {
61        125_000
62    }
63
64    /// Data blocks between the instants SYT, and so the AVTP timestamp,
65    /// can name (IEC 61883-6, Table 4).
66    pub fn syt_interval(&self) -> u8 {
67        match self.sample_rate {
68            ..=48_000 => 8,
69            48_001..=96_000 => 16,
70            _ => 32,
71        }
72    }
73
74    /// Which of a frame's data blocks its timestamp is for, when the
75    /// first is block `dbc`: the one at an SYT_INTERVAL boundary, if the
76    /// frame has one.
77    pub fn stamped_block(&self, dbc: u8) -> Option<u16> {
78        let interval = u16::from(self.syt_interval());
79        let block = (interval - u16::from(dbc) % interval) % interval;
80        (block < self.samples_per_frame).then_some(block)
81    }
82}
83
84/// An AM824 PDU's header fields, the CIP header's among them.
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub struct Header {
87    pub sequence: u8,
88    pub stream_id: u64,
89    /// The presentation time of the data block at the frame's SYT_INTERVAL
90    /// boundary, the low 32 bits of gPTP nanoseconds; none without one.
91    pub timestamp: Option<u32>,
92    pub media_reset: bool,
93    /// Quadlets in each data block.
94    pub dbs: u8,
95    pub sfc: u8,
96    /// The first data block's count.
97    pub dbc: u8,
98    /// Octets of data blocks.
99    pub data_length: u16,
100}
101
102impl Header {
103    pub fn encode(&self, out: &mut [u8; HEADER_LEN + CIP_LEN]) {
104        out[0] = SUBTYPE;
105        // sv, version 0, mr, gv 0, tv.
106        out[1] =
107            0x80 | if self.media_reset { 0x08 } else { 0 } | u8::from(self.timestamp.is_some());
108        out[2] = self.sequence;
109        out[3] = 0;
110        out[4..12].copy_from_slice(&self.stream_id.to_be_bytes());
111        out[12..16].copy_from_slice(&self.timestamp.unwrap_or(0).to_be_bytes());
112        // No gateway.
113        out[16..20].fill(0);
114        let length = CIP_LEN as u16 + self.data_length;
115        out[20..22].copy_from_slice(&length.to_be_bytes());
116        // Tag 1 (a CIP header follows), channel 31 (native AVTP), then
117        // tcode 0xA and sy 0.
118        out[22] = 0x40 | 31;
119        out[23] = 0xa0;
120        // SID 63, DBS, FN, QPC and SPH 0, DBC.
121        out[24] = 0x3f;
122        out[25] = self.dbs;
123        out[26] = 0;
124        out[27] = self.dbc;
125        // EOH, FMT, FDF (AM824 and the rate) and SYT.
126        out[28] = 0x80 | FMT;
127        out[29] = self.sfc & 0x07;
128        out[30..32].copy_from_slice(&NO_SYT.to_be_bytes());
129    }
130
131    /// Decodes an AM824 PDU, returning its header and data blocks.
132    pub fn decode(pdu: &[u8]) -> Option<(Header, &[u8])> {
133        let header: &[u8; HEADER_LEN + CIP_LEN] =
134            pdu.get(..HEADER_LEN + CIP_LEN)?.try_into().ok()?;
135        if header[0] != SUBTYPE || header[1] & 0x80 == 0 || header[22] & 0xc0 != 0x40 {
136            return None;
137        }
138        if header[28] & 0x3f != FMT {
139            return None;
140        }
141        let length = usize::from(u16::from_be_bytes([header[20], header[21]]));
142        let data = pdu.get(HEADER_LEN + CIP_LEN..HEADER_LEN + length.max(CIP_LEN))?;
143        let mut stream_id = [0; 8];
144        stream_id.copy_from_slice(&header[4..12]);
145        Some((
146            Header {
147                sequence: header[2],
148                stream_id: u64::from_be_bytes(stream_id),
149                timestamp: (header[1] & 0x01 != 0)
150                    .then(|| u32::from_be_bytes([header[12], header[13], header[14], header[15]])),
151                media_reset: header[1] & 0x08 != 0,
152                dbs: header[25],
153                sfc: header[29] & 0x07,
154                dbc: header[27],
155                data_length: data.len() as u16,
156            },
157            data,
158        ))
159    }
160
161    /// Whether the frame carries what `layout` describes.
162    pub fn matches(&self, layout: &Layout) -> bool {
163        self.sfc == layout.sfc && u16::from(self.dbs) == layout.channels
164    }
165}
166
167/// Writes `samples`, interleaved and from -1 to 1, as labeled 24-bit
168/// quadlets into `out`.
169pub fn write_samples(samples: &[f32], out: &mut [u8]) {
170    for (sample, quadlet) in samples.iter().zip(out.as_chunks_mut::<4>().0) {
171        let value = (f64::from(sample.clamp(-1.0, 1.0)) * 8_388_607.0) as i32;
172        quadlet[0] = MBLA_24;
173        quadlet[1..].copy_from_slice(&value.to_be_bytes()[1..]);
174    }
175}
176
177/// Reads the samples of `data`'s quadlets into `out`, from -1 to 1;
178/// quadlets of another kind than multi-bit linear audio read as silence.
179pub fn read_samples(data: &[u8], out: &mut Vec<f32>) {
180    out.extend(data.as_chunks::<4>().0.iter().map(|quadlet| {
181        if quadlet[0] & 0xfc != MBLA_24 {
182            return 0.0;
183        }
184        let value = i32::from_be_bytes([quadlet[1], quadlet[2], quadlet[3], 0]) >> 8;
185        value as f32 / 8_388_608.0
186    }));
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192
193    /// The Mac mini's AM824 input: 48 kHz, 8 channels, non-blocking.
194    const AM824_48K_8CH: StreamFormat = StreamFormat(0x00a0_0208_4000_0800);
195
196    #[test]
197    fn the_bench_format_is_six_blocks_of_eight_quadlets() {
198        let layout = Layout::of(AM824_48K_8CH).unwrap();
199        assert_eq!(layout.sample_rate, 48_000);
200        assert_eq!((layout.channels, layout.samples_per_frame), (8, 6));
201        assert_eq!(layout.data_length(), 192);
202        assert_eq!(layout.pdu_length(), 224);
203        assert_eq!(layout.syt_interval(), 8);
204        // Blocks 0, 6, 12 and 18 start the frames of 24 blocks: three of
205        // the four have an SYT_INTERVAL boundary.
206        let stamped: Vec<_> = [0, 6, 12, 18].map(|dbc| layout.stamped_block(dbc)).to_vec();
207        assert_eq!(stamped, [Some(0), Some(2), Some(4), None]);
208        // Blocking is not taken; synchronous beside non-blocking is.
209        assert!(Layout::of(StreamFormat(0x00a0_0208_8000_0800)).is_none());
210        assert!(Layout::of(StreamFormat(0x00a0_0208_5000_0800)).is_some());
211    }
212
213    #[test]
214    fn headers_and_samples_round_trip() {
215        let layout = Layout::of(AM824_48K_8CH).unwrap();
216        let header = Header {
217            sequence: 9,
218            stream_id: 0x9c6b_0030_9a2b_0000,
219            timestamp: Some(0x1234_5678),
220            media_reset: true,
221            dbs: 8,
222            sfc: layout.sfc,
223            dbc: 0xfa,
224            data_length: layout.data_length() as u16,
225        };
226        let mut pdu = vec![0; layout.pdu_length()];
227        let mut first = [0; HEADER_LEN + CIP_LEN];
228        header.encode(&mut first);
229        assert_eq!(
230            &first[22..32],
231            &[0x5f, 0xa0, 0x3f, 8, 0, 0xfa, 0x90, 2, 0xff, 0xff]
232        );
233        pdu[..HEADER_LEN + CIP_LEN].copy_from_slice(&first);
234        let samples: Vec<f32> = (0..48).map(|place| place as f32 / 64.0 - 0.3).collect();
235        write_samples(&samples, &mut pdu[HEADER_LEN + CIP_LEN..]);
236        assert_eq!(pdu[HEADER_LEN + CIP_LEN], 0x40);
237        let (decoded, data) = Header::decode(&pdu).unwrap();
238        assert_eq!(decoded, header);
239        assert!(decoded.matches(&layout));
240        let mut back = Vec::new();
241        read_samples(data, &mut back);
242        assert_eq!(back.len(), samples.len());
243        for (sent, received) in samples.iter().zip(&back) {
244            assert!((sent - received).abs() < 1e-6, "{sent} {received}");
245        }
246    }
247
248    #[test]
249    fn aaf_pdus_do_not_decode() {
250        assert!(Header::decode(&[0x02; 64]).is_none());
251        let mut no_cip = [0u8; 64];
252        no_cip[1] = 0x80;
253        assert!(Header::decode(&no_cip).is_none());
254    }
255}