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