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    /// Leaves out the next `frames` PDUs: those after count on past them,
179    /// so a listener sees them missing.
180    pub fn skip(&mut self, frames: u64) {
181        // Both counts wrap at 256, so only the frames past whole wraps
182        // move them.
183        let frames = frames as u8;
184        self.sequence = self.sequence.wrapping_add(frames);
185        if let Media::Am824(layout) = self.media {
186            self.dbc = self
187                .dbc
188                .wrapping_add(frames.wrapping_mul(layout.samples_per_frame as u8));
189        }
190    }
191}
192
193/// What a listener takes from one PDU.
194#[derive(Debug, Clone, Copy, PartialEq, Eq)]
195pub struct Received {
196    pub sequence: u8,
197    pub stream_id: u64,
198    /// A presentation time it carries: the low 32 bits of gPTP
199    /// nanoseconds.
200    pub timestamp: Option<u32>,
201    /// The presentation time of its first sample, where it carries one.
202    pub first_presented: Option<u32>,
203    /// Its media reset bit, which the talker toggles as its media clock
204    /// starts again.
205    pub media_reset: bool,
206    /// It carries what the media describes.
207    pub matches: bool,
208}
209
210/// Reads a PDU of `media`'s kind, its samples into `out` when it carries
211/// what `media` describes; a media clock's has none.
212pub fn read(pdu: &[u8], media: &Media, out: &mut Vec<f32>) -> Option<Received> {
213    match media {
214        Media::Aaf(layout) => {
215            let (header, data) = aaf::Header::decode(pdu)?;
216            let matches = header.matches(layout);
217            if matches {
218                aaf::read_samples(data, layout, out);
219            }
220            Some(Received {
221                sequence: header.sequence,
222                stream_id: header.stream_id,
223                timestamp: header.timestamp,
224                first_presented: header.timestamp,
225                media_reset: header.media_reset,
226                matches,
227            })
228        }
229        Media::Am824(layout) => {
230            let (header, data) = am824::Header::decode(pdu)?;
231            let matches = header.matches(layout);
232            if matches {
233                am824::read_samples(data, out);
234            }
235            // The timestamp is for the block at the SYT_INTERVAL boundary.
236            let block = layout.stamped_block(header.dbc).unwrap_or(0);
237            let before = u64::from(block) * 1_000_000_000 / u64::from(layout.sample_rate);
238            Some(Received {
239                sequence: header.sequence,
240                stream_id: header.stream_id,
241                timestamp: header.timestamp,
242                first_presented: header
243                    .timestamp
244                    .map(|timestamp| timestamp.wrapping_sub(before as u32)),
245                media_reset: header.media_reset,
246                matches,
247            })
248        }
249        Media::Crf(layout) => {
250            let (header, timestamps) = crf::Header::decode(pdu)?;
251            let first = crf::first_timestamp(timestamps).map(|time| time as u32);
252            Some(Received {
253                sequence: header.sequence,
254                stream_id: header.stream_id,
255                timestamp: first,
256                first_presented: first,
257                media_reset: header.media_reset,
258                matches: header.matches(layout),
259            })
260        }
261    }
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267
268    const AAF_48K_8CH_32: StreamFormat = StreamFormat(0x0205_0220_0200_6000);
269    const AM824_48K_8CH: StreamFormat = StreamFormat(0x00a0_0208_4000_0800);
270
271    #[test]
272    fn both_kinds_go_out_and_come_back() {
273        for format in [AAF_48K_8CH_32, AM824_48K_8CH] {
274            let media = Media::of(format).unwrap();
275            assert_eq!(media.interval_nanos(), 125_000);
276            let mut packetizer = Packetizer::new(media, 0x9c6b_0030_9a2b_0000);
277            let samples: Vec<f32> = (0..48).map(|place| place as f32 / 64.0 - 0.3).collect();
278            let mut stamps = Vec::new();
279            for frame in 0..4u8 {
280                let mut pdu = vec![0; media.pdu_length()];
281                let presentation = 1_000_000 + i64::from(frame) * 125_000;
282                packetizer.write(presentation, false, &samples, &mut pdu);
283                let mut back = Vec::new();
284                let received = read(&pdu, &media, &mut back).unwrap();
285                assert_eq!(received.sequence, frame);
286                assert!(received.matches);
287                assert_eq!(back.len(), 48);
288                stamps.push(received.timestamp);
289            }
290            match media {
291                Media::Aaf(_) => assert_eq!(
292                    stamps,
293                    [
294                        Some(1_000_000),
295                        Some(1_125_000),
296                        Some(1_250_000),
297                        Some(1_375_000)
298                    ]
299                ),
300                // Blocks 0, 8 and 16 are stamped, 2 and 4 blocks into their
301                // frames; the fourth frame has no boundary.
302                Media::Am824(_) => assert_eq!(
303                    stamps,
304                    [Some(1_000_000), Some(1_166_666), Some(1_333_333), None]
305                ),
306                Media::Crf(_) => unreachable!("audio formats only"),
307            }
308        }
309    }
310
311    /// A media clock's frame spans whole samples at the audio's rates:
312    /// 96 events at 48 kHz are 384 samples at 192 kHz; an audio stream
313    /// spans its own frame at its own rate alone.
314    #[test]
315    fn a_media_clock_spans_samples_at_any_audio_rate() {
316        let clock = Media::of(StreamFormat(0x0410_6001_0000_bb80)).unwrap();
317        assert!(clock.is_clock());
318        assert_eq!(clock.channels(), 0);
319        assert_eq!(clock.frame_samples_at(48_000), Some(96));
320        assert_eq!(clock.frame_samples_at(192_000), Some(384));
321        assert_eq!(clock.frame_samples_at(44_100), None);
322        let audio = Media::of(AAF_48K_8CH_32).unwrap();
323        assert_eq!(audio.frame_samples_at(48_000), Some(6));
324        assert_eq!(audio.frame_samples_at(96_000), None);
325        let mut pdu = vec![0; clock.pdu_length()];
326        Packetizer::new(clock, 1).write(3_000_000_000, false, &[], &mut pdu);
327        let received = read(&pdu, &clock, &mut Vec::new()).unwrap();
328        assert!(received.matches);
329        assert_eq!(received.timestamp, Some(3_000_000_000));
330    }
331
332    /// Frames left out count on in the sequence number and, in AM824, the
333    /// data blocks, past a wrap too: the next PDU is the one that would
334    /// have gone.
335    #[test]
336    fn frames_left_out_count_on() {
337        for format in [AAF_48K_8CH_32, AM824_48K_8CH] {
338            let media = Media::of(format).unwrap();
339            let samples = [0.25; 48];
340            let mut every = Packetizer::new(media, 1);
341            let mut pdu = vec![0; media.pdu_length()];
342            for _ in 0..259 {
343                every.write(0, false, &samples, &mut pdu);
344            }
345            let mut skipping = Packetizer::new(media, 1);
346            skipping.skip(259);
347            let mut next = vec![0; media.pdu_length()];
348            every.write(7_000_000, false, &samples, &mut pdu);
349            skipping.write(7_000_000, false, &samples, &mut next);
350            assert_eq!(pdu, next);
351        }
352    }
353
354    #[test]
355    fn a_listener_of_one_kind_ignores_the_other() {
356        let aaf = Media::of(AAF_48K_8CH_32).unwrap();
357        let am824 = Media::of(AM824_48K_8CH).unwrap();
358        let mut pdu = vec![0; aaf.pdu_length()];
359        Packetizer::new(aaf, 1).write(0, false, &[0.0; 48], &mut pdu);
360        assert!(read(&pdu, &am824, &mut Vec::new()).is_none());
361    }
362}