Skip to main content

avb_stream/
media.rs

1//! The ways a stream carries samples, AAF and AM824, and a media clock,
2//! CRF, behind one layout: building a talker's PDUs and reading a
3//! listener's.
4
5use atdecc::stream_format::StreamFormat;
6
7use crate::{aaf, am824, crf};
8
9/// How a stream format packs its samples, or its clock.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum Media {
12    Aaf(aaf::Layout),
13    Am824(am824::Layout),
14    Crf(crf::Layout),
15}
16
17impl Media {
18    /// The media of `format`, when this crate can send and receive it.
19    pub fn of(format: StreamFormat) -> Option<Self> {
20        aaf::Layout::of(format)
21            .map(Media::Aaf)
22            .or_else(|| am824::Layout::of(format).map(Media::Am824))
23            .or_else(|| crf::Layout::of(format).map(Media::Crf))
24    }
25
26    /// The AVTP subtype of its PDUs.
27    pub fn subtype(&self) -> u8 {
28        match self {
29            Media::Aaf(_) => aaf::SUBTYPE,
30            Media::Am824(_) => am824::SUBTYPE,
31            Media::Crf(_) => crf::SUBTYPE,
32        }
33    }
34
35    /// Its sampling rate; a media clock's base frequency.
36    pub fn sample_rate(&self) -> u32 {
37        match self {
38            Media::Aaf(layout) => layout.sample_rate,
39            Media::Am824(layout) => layout.sample_rate,
40            Media::Crf(layout) => layout.base_frequency,
41        }
42    }
43
44    /// Its audio channels, none for a media clock.
45    pub fn channels(&self) -> u16 {
46        match self {
47            Media::Aaf(layout) => layout.channels,
48            Media::Am824(layout) => layout.channels,
49            Media::Crf(_) => 0,
50        }
51    }
52
53    /// Whether it carries a media clock rather than audio.
54    pub fn is_clock(&self) -> bool {
55        matches!(self, Media::Crf(_))
56    }
57
58    /// The samples each frame carries; none for a media clock.
59    pub fn samples_per_frame(&self) -> u16 {
60        match self {
61            Media::Aaf(layout) => layout.samples_per_frame,
62            Media::Am824(layout) => layout.samples_per_frame,
63            Media::Crf(_) => 0,
64        }
65    }
66
67    /// How many samples at `rate` each frame spans: an audio stream's own
68    /// at its rate alone; a media clock's events counted at `rate`, where
69    /// they come to whole samples.
70    pub fn frame_samples_at(&self, rate: u32) -> Option<u64> {
71        match self {
72            Media::Crf(layout) => {
73                let spanned = layout.events_per_frame() * u64::from(rate);
74                let base = u64::from(layout.base_frequency);
75                (spanned.is_multiple_of(base) && spanned > 0).then(|| spanned / base)
76            }
77            _ => (self.sample_rate() == rate).then(|| u64::from(self.samples_per_frame().max(1))),
78        }
79    }
80
81    /// The AVTPDU's octets, as MSRP's MaxFrameSize counts them.
82    pub fn pdu_length(&self) -> usize {
83        match self {
84            Media::Aaf(layout) => layout.pdu_length(),
85            Media::Am824(layout) => layout.pdu_length(),
86            Media::Crf(layout) => layout.pdu_length(),
87        }
88    }
89
90    /// How often a frame goes out, in nanoseconds.
91    pub fn interval_nanos(&self) -> u64 {
92        match self {
93            Media::Aaf(layout) => layout.interval_nanos(),
94            Media::Am824(layout) => layout.interval_nanos(),
95            Media::Crf(layout) => layout.interval_nanos(),
96        }
97    }
98}
99
100/// Builds one stream's PDUs, counting what each carries on.
101#[derive(Debug, Clone)]
102pub struct Packetizer {
103    media: Media,
104    stream_id: u64,
105    sequence: u8,
106    /// AM824's count of data blocks sent.
107    dbc: u8,
108}
109
110impl Packetizer {
111    pub fn new(media: Media, stream_id: u64) -> Self {
112        Packetizer {
113            media,
114            stream_id,
115            sequence: 0,
116            dbc: 0,
117        }
118    }
119
120    /// Writes the next PDU into `out`, `media`'s PDU length: `samples`
121    /// interleaved, the first presented at `presentation` (gPTP
122    /// nanoseconds); for a media clock, its timestamps from
123    /// `presentation` on, without samples.
124    pub fn write(&mut self, presentation: i64, media_reset: bool, samples: &[f32], out: &mut [u8]) {
125        match self.media {
126            Media::Aaf(layout) => {
127                let header = aaf::Header {
128                    sequence: self.sequence,
129                    stream_id: self.stream_id,
130                    timestamp: Some(presentation as u32),
131                    media_reset,
132                    nsr: layout.nsr,
133                    sample_format: layout.sample_format,
134                    bit_depth: layout.bit_depth,
135                    channels: layout.channels,
136                    data_length: layout.data_length() as u16,
137                };
138                let mut encoded = [0; aaf::HEADER_LEN];
139                header.encode(&mut encoded);
140                out[..aaf::HEADER_LEN].copy_from_slice(&encoded);
141                aaf::write_samples(samples, &layout, &mut out[aaf::HEADER_LEN..]);
142            }
143            Media::Am824(layout) => {
144                // The timestamp is for the block at an SYT_INTERVAL
145                // boundary, and a frame without one has none.
146                let timestamp = layout.stamped_block(self.dbc).map(|block| {
147                    let offset = i64::from(block) * 1_000_000_000 / i64::from(layout.sample_rate);
148                    (presentation + offset) as u32
149                });
150                let header = am824::Header {
151                    sequence: self.sequence,
152                    stream_id: self.stream_id,
153                    timestamp,
154                    media_reset,
155                    dbs: layout.channels as u8,
156                    sfc: layout.sfc,
157                    dbc: self.dbc,
158                    data_length: layout.data_length() as u16,
159                };
160                let start = am824::HEADER_LEN + am824::CIP_LEN;
161                let mut encoded = [0; am824::HEADER_LEN + am824::CIP_LEN];
162                header.encode(&mut encoded);
163                out[..start].copy_from_slice(&encoded);
164                am824::write_samples(samples, &mut out[start..]);
165                self.dbc = self.dbc.wrapping_add(layout.samples_per_frame as u8);
166            }
167            Media::Crf(layout) => {
168                let mut encoded = [0; crf::HEADER_LEN];
169                crf::Header::of(&layout, self.sequence, self.stream_id, media_reset)
170                    .encode(&mut encoded);
171                out[..crf::HEADER_LEN].copy_from_slice(&encoded);
172                crf::write_timestamps(presentation, &layout, &mut out[crf::HEADER_LEN..]);
173            }
174        }
175        self.sequence = self.sequence.wrapping_add(1);
176    }
177}
178
179/// What a listener takes from one PDU.
180#[derive(Debug, Clone, Copy, PartialEq, Eq)]
181pub struct Received {
182    pub sequence: u8,
183    pub stream_id: u64,
184    /// A presentation time it carries: the low 32 bits of gPTP
185    /// nanoseconds.
186    pub timestamp: Option<u32>,
187    /// The presentation time of its first sample, where it carries one.
188    pub first_presented: Option<u32>,
189    /// Its media reset bit, which the talker toggles as its media clock
190    /// starts again.
191    pub media_reset: bool,
192    /// It carries what the media describes.
193    pub matches: bool,
194}
195
196/// Reads a PDU of `media`'s kind, its samples into `out` when it carries
197/// what `media` describes; a media clock's has none.
198pub fn read(pdu: &[u8], media: &Media, out: &mut Vec<f32>) -> Option<Received> {
199    match media {
200        Media::Aaf(layout) => {
201            let (header, data) = aaf::Header::decode(pdu)?;
202            let matches = header.matches(layout);
203            if matches {
204                aaf::read_samples(data, layout, out);
205            }
206            Some(Received {
207                sequence: header.sequence,
208                stream_id: header.stream_id,
209                timestamp: header.timestamp,
210                first_presented: header.timestamp,
211                media_reset: header.media_reset,
212                matches,
213            })
214        }
215        Media::Am824(layout) => {
216            let (header, data) = am824::Header::decode(pdu)?;
217            let matches = header.matches(layout);
218            if matches {
219                am824::read_samples(data, out);
220            }
221            // The timestamp is for the block at the SYT_INTERVAL boundary.
222            let block = layout.stamped_block(header.dbc).unwrap_or(0);
223            let before = u64::from(block) * 1_000_000_000 / u64::from(layout.sample_rate);
224            Some(Received {
225                sequence: header.sequence,
226                stream_id: header.stream_id,
227                timestamp: header.timestamp,
228                first_presented: header
229                    .timestamp
230                    .map(|timestamp| timestamp.wrapping_sub(before as u32)),
231                media_reset: header.media_reset,
232                matches,
233            })
234        }
235        Media::Crf(layout) => {
236            let (header, timestamps) = crf::Header::decode(pdu)?;
237            let first = crf::first_timestamp(timestamps).map(|time| time as u32);
238            Some(Received {
239                sequence: header.sequence,
240                stream_id: header.stream_id,
241                timestamp: first,
242                first_presented: first,
243                media_reset: header.media_reset,
244                matches: header.matches(layout),
245            })
246        }
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253
254    const AAF_48K_8CH_32: StreamFormat = StreamFormat(0x0205_0220_0200_6000);
255    const AM824_48K_8CH: StreamFormat = StreamFormat(0x00a0_0208_4000_0800);
256
257    #[test]
258    fn both_kinds_go_out_and_come_back() {
259        for format in [AAF_48K_8CH_32, AM824_48K_8CH] {
260            let media = Media::of(format).unwrap();
261            assert_eq!(media.interval_nanos(), 125_000);
262            let mut packetizer = Packetizer::new(media, 0x9c6b_0030_9a2b_0000);
263            let samples: Vec<f32> = (0..48).map(|place| place as f32 / 64.0 - 0.3).collect();
264            let mut stamps = Vec::new();
265            for frame in 0..4u8 {
266                let mut pdu = vec![0; media.pdu_length()];
267                let presentation = 1_000_000 + i64::from(frame) * 125_000;
268                packetizer.write(presentation, false, &samples, &mut pdu);
269                let mut back = Vec::new();
270                let received = read(&pdu, &media, &mut back).unwrap();
271                assert_eq!(received.sequence, frame);
272                assert!(received.matches);
273                assert_eq!(back.len(), 48);
274                stamps.push(received.timestamp);
275            }
276            match media {
277                Media::Aaf(_) => assert_eq!(
278                    stamps,
279                    [
280                        Some(1_000_000),
281                        Some(1_125_000),
282                        Some(1_250_000),
283                        Some(1_375_000)
284                    ]
285                ),
286                // Blocks 0, 8 and 16 are stamped, 2 and 4 blocks into their
287                // frames; the fourth frame has no boundary.
288                Media::Am824(_) => assert_eq!(
289                    stamps,
290                    [Some(1_000_000), Some(1_166_666), Some(1_333_333), None]
291                ),
292                Media::Crf(_) => unreachable!("audio formats only"),
293            }
294        }
295    }
296
297    /// A media clock's frame spans whole samples at the audio's rates:
298    /// 96 events at 48 kHz are 384 samples at 192 kHz; an audio stream
299    /// spans its own frame at its own rate alone.
300    #[test]
301    fn a_media_clock_spans_samples_at_any_audio_rate() {
302        let clock = Media::of(StreamFormat(0x0410_6001_0000_bb80)).unwrap();
303        assert!(clock.is_clock());
304        assert_eq!(clock.channels(), 0);
305        assert_eq!(clock.frame_samples_at(48_000), Some(96));
306        assert_eq!(clock.frame_samples_at(192_000), Some(384));
307        assert_eq!(clock.frame_samples_at(44_100), None);
308        let audio = Media::of(AAF_48K_8CH_32).unwrap();
309        assert_eq!(audio.frame_samples_at(48_000), Some(6));
310        assert_eq!(audio.frame_samples_at(96_000), None);
311        let mut pdu = vec![0; clock.pdu_length()];
312        Packetizer::new(clock, 1).write(3_000_000_000, false, &[], &mut pdu);
313        let received = read(&pdu, &clock, &mut Vec::new()).unwrap();
314        assert!(received.matches);
315        assert_eq!(received.timestamp, Some(3_000_000_000));
316    }
317
318    #[test]
319    fn a_listener_of_one_kind_ignores_the_other() {
320        let aaf = Media::of(AAF_48K_8CH_32).unwrap();
321        let am824 = Media::of(AM824_48K_8CH).unwrap();
322        let mut pdu = vec![0; aaf.pdu_length()];
323        Packetizer::new(aaf, 1).write(0, false, &[0.0; 48], &mut pdu);
324        assert!(read(&pdu, &am824, &mut Vec::new()).is_none());
325    }
326}