Skip to main content

avb_stream/
listener.rs

1//! Listeners of AAF or AM824: the frames of a stream, their samples
2//! played on the sink, counted as Milan's stream input counters count
3//! them; and of a media clock, CRF, its frames counted alike.
4//!
5//! A group takes several streams on one thread, each with its own
6//! socket, sink and counters, waiting on all of their sockets at once. A
7//! [`Listener`] is a group of one.
8
9use std::io;
10use std::sync::Arc;
11use std::sync::atomic::{AtomicBool, AtomicI32, AtomicI64, AtomicU32, AtomicU64, Ordering};
12use std::thread::JoinHandle;
13use std::time::{Duration, Instant};
14
15use atdecc::stream_format::StreamFormat;
16use avb_net::MacAddress;
17use avb_net::stream::{FrameReceiver, avtp_payload};
18
19use crate::audio::{Arrived, BlockSink, Output, Presented, Sink};
20use crate::lock::Lock;
21use crate::media::{self, Media};
22use crate::meter::Peaks;
23use crate::{MediaClock, RecoveredClock, crf};
24
25/// How long without a frame before the stream counts as interrupted.
26const SILENCE: Duration = Duration::from_millis(100);
27/// Presentation times further ahead than this count as early.
28const EARLY: i64 = 50_000_000;
29/// The longest the thread waits for a frame at once, so that it notices
30/// streams that stopped and streams that came.
31const LONGEST_WAIT: Duration = Duration::from_millis(20);
32/// How often the sockets are asked what they dropped.
33const DROPS_EVERY: Duration = Duration::from_millis(250);
34
35/// What a listener receives, and where it goes.
36#[derive(Debug, Clone, PartialEq)]
37pub struct ListenerConfig {
38    pub interface: String,
39    pub stream_id: u64,
40    /// Where the stream comes to: its multicast address, and in AVB Lite
41    /// this computer's own as well.
42    pub destinations: Vec<MacAddress>,
43    pub format: StreamFormat,
44    pub sink: Sink,
45    /// The clock the stream carries, which it recovers for talkers to
46    /// follow: a media clock's from its timestamps, an audio stream's
47    /// from its presentation times.
48    pub recovered: Option<RecoveredClock>,
49    /// For each of the sink's channels, the stream channel it plays, none
50    /// for silence, as a controller mapped them or as a stream of other
51    /// channels than the sink's fills it; the stream's own channels, in
52    /// order, when left out.
53    pub channel_map: Option<Vec<Option<u16>>>,
54}
55
56/// A listener's counters (Milan 1.3, Table 5.10).
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
58pub struct ListenerStats {
59    pub frames_received: u64,
60    pub media_locked: u64,
61    pub media_unlocked: u64,
62    pub interrupted: u64,
63    pub sequence_mismatches: u64,
64    pub unsupported_formats: u64,
65    pub late: u64,
66    pub early: u64,
67    /// Frames the socket had no room for, its thread behind: not Milan's,
68    /// but what tells a stream's frames lost here from lost on the way.
69    pub socket_drops: u64,
70    /// Frames are arriving.
71    pub locked: bool,
72    /// The thread taking the frames runs real time.
73    pub realtime: bool,
74    /// How far the audio device's clock runs from gPTP's, in parts per
75    /// million.
76    pub drift_ppm: i32,
77    /// Times the audio device found nothing to play.
78    pub device_underruns: u64,
79    /// How long after its presentation time each sample plays, once the
80    /// device has said when it plays, and how far from that the last
81    /// chunk played, in nanoseconds.
82    pub playout: Option<(i64, i64)>,
83}
84
85struct Counters {
86    frames_received: AtomicU64,
87    media_locked: AtomicU64,
88    media_unlocked: AtomicU64,
89    interrupted: AtomicU64,
90    sequence_mismatches: AtomicU64,
91    unsupported_formats: AtomicU64,
92    late: AtomicU64,
93    early: AtomicU64,
94    socket_drops: AtomicU64,
95    locked: AtomicBool,
96    peak: AtomicU32,
97    peaks: Peaks,
98    drift_ppm: AtomicI32,
99    device_underruns: AtomicU64,
100    /// `i64::MIN` until chosen.
101    delay: AtomicI64,
102    playout_error: AtomicI64,
103}
104
105impl Default for Counters {
106    fn default() -> Self {
107        Counters {
108            frames_received: AtomicU64::new(0),
109            media_locked: AtomicU64::new(0),
110            media_unlocked: AtomicU64::new(0),
111            interrupted: AtomicU64::new(0),
112            sequence_mismatches: AtomicU64::new(0),
113            unsupported_formats: AtomicU64::new(0),
114            late: AtomicU64::new(0),
115            early: AtomicU64::new(0),
116            socket_drops: AtomicU64::new(0),
117            locked: AtomicBool::new(false),
118            peak: AtomicU32::new(0),
119            peaks: Peaks::default(),
120            drift_ppm: AtomicI32::new(0),
121            device_underruns: AtomicU64::new(0),
122            delay: AtomicI64::new(i64::MIN),
123            playout_error: AtomicI64::new(0),
124        }
125    }
126}
127
128/// A stream opened for the thread to take: its socket and its sink, none
129/// for a media clock.
130struct Opened {
131    config: ListenerConfig,
132    media: Media,
133    receiver: FrameReceiver,
134    output: Option<Output>,
135    /// A program's sink, which takes each frame's block as it comes.
136    blocks: Option<Arc<dyn BlockSink>>,
137}
138
139/// What the group's owner and its thread share.
140struct Shared {
141    /// Each place's stream opened, waiting for the thread, or `None` to
142    /// stop it; and how often they changed, which the thread compares
143    /// with what it last took.
144    waiting: Lock<Vec<Option<Option<Opened>>>>,
145    changes: AtomicU64,
146    /// Each place's counters, made anew for each stream.
147    counters: Lock<Vec<Arc<Counters>>>,
148    realtime: AtomicBool,
149}
150
151/// A running group of listeners. Dropping it stops them.
152pub struct ListenerGroup {
153    shared: Arc<Shared>,
154    stop: Arc<AtomicBool>,
155    handle: Option<JoinHandle<()>>,
156}
157
158impl ListenerGroup {
159    /// Starts the group's thread, with room for `places` streams, none
160    /// taken yet.
161    pub fn start(places: usize, clock: Arc<MediaClock>) -> io::Result<Self> {
162        let stop = Arc::new(AtomicBool::new(false));
163        let shared = Arc::new(Shared {
164            waiting: Lock::new((0..places).map(|_| None).collect()),
165            changes: AtomicU64::new(0),
166            counters: Lock::new((0..places).map(|_| Arc::default()).collect()),
167            realtime: AtomicBool::new(false),
168        });
169        let handle = {
170            let stop = stop.clone();
171            let shared = shared.clone();
172            std::thread::Builder::new()
173                .name("listener".into())
174                .spawn(move || run(&shared, &clock, &stop))?
175        };
176        Ok(ListenerGroup {
177            shared,
178            stop,
179            handle: Some(handle),
180        })
181    }
182
183    /// Starts taking `config`'s stream in `place`, in place of what was
184    /// there, opening its socket and sink, or stops what was there.
185    pub fn set_stream(&self, place: usize, config: Option<ListenerConfig>) -> io::Result<()> {
186        let opened = match config {
187            Some(config) => {
188                let media = Media::of(config.format).ok_or_else(|| {
189                    io::Error::new(
190                        io::ErrorKind::Unsupported,
191                        "not an AAF, AM824 or CRF format this listener takes",
192                    )
193                })?;
194                let receiver =
195                    FrameReceiver::open(&config.interface, media.subtype(), &config.destinations)?;
196                // The sink has the channels its map has, where it has one.
197                let channels = config
198                    .channel_map
199                    .as_ref()
200                    .map_or(media.channels(), |map| map.len() as u16);
201                let output = if media.is_clock() {
202                    None
203                } else {
204                    Some(Output::open(&config.sink, channels, media.sample_rate())?)
205                };
206                let blocks = match &config.sink {
207                    Sink::Blocks(blocks) if !media.is_clock() => Some(blocks.0.clone()),
208                    _ => None,
209                };
210                Some(Opened {
211                    config,
212                    media,
213                    receiver,
214                    output,
215                    blocks,
216                })
217            }
218            None => None,
219        };
220        let mut waiting = self.shared.waiting.lock();
221        let Some(slot) = waiting.get_mut(place) else {
222            return Err(io::Error::new(io::ErrorKind::InvalidInput, "no such place"));
223        };
224        if opened.is_some()
225            && let Some(counters) = self.shared.counters.lock().get_mut(place)
226        {
227            *counters = Arc::default();
228        }
229        *slot = Some(opened);
230        self.shared.changes.fetch_add(1, Ordering::Relaxed);
231        Ok(())
232    }
233
234    fn counters(&self, place: usize) -> Arc<Counters> {
235        self.shared
236            .counters
237            .lock()
238            .get(place)
239            .cloned()
240            .unwrap_or_default()
241    }
242
243    /// `place`'s counters.
244    pub fn stats(&self, place: usize) -> ListenerStats {
245        let counters = self.counters(place);
246        let read = |counter: &AtomicU64| counter.load(Ordering::Relaxed);
247        ListenerStats {
248            frames_received: read(&counters.frames_received),
249            media_locked: read(&counters.media_locked),
250            media_unlocked: read(&counters.media_unlocked),
251            interrupted: read(&counters.interrupted),
252            sequence_mismatches: read(&counters.sequence_mismatches),
253            unsupported_formats: read(&counters.unsupported_formats),
254            late: read(&counters.late),
255            early: read(&counters.early),
256            socket_drops: read(&counters.socket_drops),
257            locked: counters.locked.load(Ordering::Relaxed),
258            realtime: self.shared.realtime.load(Ordering::Relaxed),
259            drift_ppm: counters.drift_ppm.load(Ordering::Relaxed),
260            device_underruns: read(&counters.device_underruns),
261            playout: match counters.delay.load(Ordering::Relaxed) {
262                i64::MIN => None,
263                delay => Some((delay, counters.playout_error.load(Ordering::Relaxed))),
264            },
265        }
266    }
267
268    /// The loudest sample of `place`'s stream since the last time this was
269    /// asked, from 0 to 1.
270    pub fn take_peak(&self, place: usize) -> f32 {
271        f32::from_bits(self.counters(place).peak.swap(0, Ordering::Relaxed))
272    }
273
274    /// The loudest sample in each of the first two channels of `place`'s
275    /// stream since the last time this was asked, from 0 to 1, for a
276    /// meter.
277    pub fn take_peaks(&self, place: usize) -> [f32; 2] {
278        self.counters(place).peaks.take()
279    }
280}
281
282impl Drop for ListenerGroup {
283    fn drop(&mut self) {
284        self.stop.store(true, Ordering::Relaxed);
285        if let Some(handle) = self.handle.take() {
286            let _ = handle.join();
287        }
288    }
289}
290
291/// One of a group's streams, taken while it lives: dropping it stops
292/// that stream, and the group once none holds it.
293pub struct GroupListener {
294    group: Arc<ListenerGroup>,
295    place: usize,
296}
297
298impl GroupListener {
299    /// Starts taking `config`'s stream in `group`'s `place`.
300    pub fn start(
301        group: &Arc<ListenerGroup>,
302        place: usize,
303        config: ListenerConfig,
304    ) -> io::Result<Self> {
305        group.set_stream(place, Some(config))?;
306        Ok(GroupListener {
307            group: group.clone(),
308            place,
309        })
310    }
311
312    pub fn stats(&self) -> ListenerStats {
313        self.group.stats(self.place)
314    }
315
316    /// The loudest sample since the last time this was asked, from 0 to 1.
317    pub fn take_peak(&self) -> f32 {
318        self.group.take_peak(self.place)
319    }
320
321    /// The loudest sample in each of the first two channels since the
322    /// last time this was asked, from 0 to 1.
323    pub fn take_peaks(&self) -> [f32; 2] {
324        self.group.take_peaks(self.place)
325    }
326}
327
328impl Drop for GroupListener {
329    fn drop(&mut self) {
330        let _ = self.group.set_stream(self.place, None);
331    }
332}
333
334/// A running listener of one stream. Dropping it stops listening.
335pub struct Listener {
336    group: GroupListener,
337}
338
339impl Listener {
340    pub fn start(config: ListenerConfig, clock: Arc<MediaClock>) -> io::Result<Self> {
341        let group = Arc::new(ListenerGroup::start(1, clock)?);
342        Ok(Listener {
343            group: GroupListener::start(&group, 0, config)?,
344        })
345    }
346
347    pub fn stats(&self) -> ListenerStats {
348        self.group.stats()
349    }
350
351    /// The loudest sample since the last time this was asked, from 0 to 1.
352    pub fn take_peak(&self) -> f32 {
353        self.group.take_peak()
354    }
355}
356
357/// A stream the thread takes.
358struct Running {
359    opened: Opened,
360    counters: Arc<Counters>,
361    expected: Option<u8>,
362    last: Instant,
363    /// Its samples in the order its channel map plays them.
364    mapped: Vec<f32>,
365    /// A frame's samples as words, for a program's sink.
366    words: Vec<i32>,
367}
368
369impl Drop for Running {
370    /// The clock a stream recovered goes with it, however it stops: in
371    /// place of another, or with the group's thread.
372    fn drop(&mut self) {
373        if let Some(recovered) = &self.opened.config.recovered {
374            recovered.lose();
375        }
376    }
377}
378
379fn run(shared: &Shared, clock: &MediaClock, stop: &AtomicBool) {
380    shared
381        .realtime
382        .store(crate::realtime::raise(), Ordering::Relaxed);
383    let places = shared.waiting.lock().len();
384    let mut running: Vec<Option<Running>> = (0..places).map(|_| None).collect();
385    let mut seen = u64::MAX;
386    let mut frame = vec![0u8; 1522];
387    let mut samples = Vec::new();
388    let mut drops_read = Instant::now();
389    while !stop.load(Ordering::Relaxed) {
390        let changes = shared.changes.load(Ordering::Relaxed);
391        if changes != seen {
392            seen = changes;
393            take_changes(shared, &mut running);
394        }
395        let taking: Vec<usize> = (0..places)
396            .filter(|place| running[*place].is_some())
397            .collect();
398        if taking.is_empty() {
399            std::thread::sleep(LONGEST_WAIT);
400            continue;
401        }
402        let receivers: Vec<&FrameReceiver> = taking
403            .iter()
404            .filter_map(|place| running[*place].as_ref())
405            .map(|stream| &stream.opened.receiver)
406            .collect();
407        let ready = match FrameReceiver::ready(&receivers, Some(LONGEST_WAIT)) {
408            Ok(ready) => ready,
409            Err(_) => {
410                std::thread::sleep(Duration::from_millis(100));
411                continue;
412            }
413        };
414        for at in ready {
415            let Some(stream) = running[taking[at]].as_mut() else {
416                continue;
417            };
418            // Every frame the socket holds.
419            while let Ok(Some(length)) = stream
420                .opened
421                .receiver
422                .receive(&mut frame, Some(Duration::ZERO))
423            {
424                take_frame(stream, &frame[..length], &mut samples, clock);
425            }
426        }
427        // A stream gone quiet is interrupted.
428        for stream in running.iter_mut().flatten() {
429            let counters = &stream.counters;
430            if counters.locked.load(Ordering::Relaxed) && stream.last.elapsed() > SILENCE {
431                counters.locked.store(false, Ordering::Relaxed);
432                counters.media_unlocked.fetch_add(1, Ordering::Relaxed);
433                counters.interrupted.fetch_add(1, Ordering::Relaxed);
434                stream.expected = None;
435                if let Some(recovered) = &stream.opened.config.recovered {
436                    recovered.lose();
437                }
438            }
439        }
440        if drops_read.elapsed() >= DROPS_EVERY {
441            drops_read = Instant::now();
442            for stream in running.iter().flatten() {
443                let dropped = stream.opened.receiver.dropped();
444                if dropped > 0 {
445                    stream
446                        .counters
447                        .socket_drops
448                        .fetch_add(dropped, Ordering::Relaxed);
449                }
450            }
451        }
452    }
453}
454
455/// Takes the streams opened for it and stops those asked to stop.
456fn take_changes(shared: &Shared, running: &mut [Option<Running>]) {
457    let mut waiting = shared.waiting.lock();
458    let counters = shared.counters.lock();
459    for (place, slot) in waiting.iter_mut().enumerate() {
460        let Some(change) = slot.take() else {
461            continue;
462        };
463        if let Some(stream) = running.get_mut(place) {
464            *stream = change.map(|opened| {
465                // What the socket took while the sink opened and this
466                // thread slept is past its time: the stream starts with
467                // what comes next, rather than with frames counted late.
468                let mut frame = [0u8; 1522];
469                while let Ok(Some(_)) = opened.receiver.receive(&mut frame, Some(Duration::ZERO)) {}
470                Running {
471                    opened,
472                    counters: counters.get(place).cloned().unwrap_or_default(),
473                    expected: None,
474                    last: Instant::now(),
475                    mapped: Vec::new(),
476                    words: Vec::new(),
477                }
478            });
479        }
480    }
481}
482
483/// Whether an AVTPDU is of stream `stream_id`, whatever its format: the
484/// stream ID of AVTP's common stream header.
485fn of_stream(pdu: &[u8], stream_id: u64) -> bool {
486    pdu.get(4..12)
487        .and_then(|id| id.try_into().ok())
488        .map(u64::from_be_bytes)
489        == Some(stream_id)
490}
491
492/// Counts one frame of a stream and plays its samples.
493fn take_frame(stream: &mut Running, frame: &[u8], samples: &mut Vec<f32>, clock: &MediaClock) {
494    let Running {
495        opened,
496        counters,
497        expected,
498        last,
499        mapped,
500        words,
501    } = stream;
502    samples.clear();
503    let Some(pdu) = avtp_payload(frame) else {
504        return;
505    };
506    let Some(header) = media::read(pdu, &opened.media, samples) else {
507        // The stream it waits for, in a format it was not opened for, as
508        // when a controller binds a talker of another format: counted, so
509        // the controller sees why nothing plays.
510        if of_stream(pdu, opened.config.stream_id) {
511            counters.unsupported_formats.fetch_add(1, Ordering::Relaxed);
512        }
513        return;
514    };
515    if header.stream_id != opened.config.stream_id {
516        return;
517    }
518    if !header.matches {
519        counters.unsupported_formats.fetch_add(1, Ordering::Relaxed);
520        return;
521    }
522    let now = clock.now();
523    // How far ahead a presentation time is, from the low 32 bits of gPTP
524    // time.
525    let ahead = |timestamp: u32| i64::from(timestamp.wrapping_sub(now as u32) as i32);
526    // The clock the stream carries: a media clock's timestamps, or an
527    // audio stream's first sample's presentation time, each frame its
528    // samples on, made whole from gPTP time, which a hardware clock must
529    // give for its high bits to be right.
530    if let Some(recovered) = &opened.config.recovered {
531        match &opened.media {
532            Media::Crf(layout) => {
533                if let Some((crf, timestamps)) = crf::Header::decode(pdu) {
534                    let times = timestamps
535                        .as_chunks::<8>()
536                        .0
537                        .iter()
538                        .map(|time| u64::from_be_bytes(*time));
539                    recovered.take(
540                        times,
541                        layout.timestamp_interval,
542                        layout.base_frequency,
543                        crf.media_reset,
544                    );
545                }
546            }
547            media => {
548                if let Some(first) = header.first_presented.filter(|_| clock.locked()) {
549                    recovered.take(
550                        [(now + ahead(first)) as u64],
551                        media.samples_per_frame(),
552                        media.sample_rate(),
553                        header.media_reset,
554                    );
555                }
556            }
557        }
558    }
559    *last = Instant::now();
560    counters.frames_received.fetch_add(1, Ordering::Relaxed);
561    let missed = expected.map_or(0, |wanted| header.sequence.wrapping_sub(wanted));
562    if missed != 0 {
563        counters.sequence_mismatches.fetch_add(1, Ordering::Relaxed);
564    }
565    *expected = Some(header.sequence.wrapping_add(1));
566    if !counters.locked.load(Ordering::Relaxed) {
567        counters.locked.store(true, Ordering::Relaxed);
568        counters.media_locked.fetch_add(1, Ordering::Relaxed);
569    }
570    if let Some(timestamp) = header.timestamp {
571        let ahead = ahead(timestamp);
572        if ahead < 0 {
573            counters.late.fetch_add(1, Ordering::Relaxed);
574        } else if ahead > EARLY {
575            counters.early.fetch_add(1, Ordering::Relaxed);
576        }
577    }
578    let loudest = samples
579        .iter()
580        .fold(0.0f32, |most, sample| most.max(sample.abs()));
581    counters
582        .peak
583        .fetch_max(loudest.to_bits(), Ordering::Relaxed);
584    counters
585        .peaks
586        .raise(samples, usize::from(opened.media.channels()));
587    // Without gPTP time from a hardware clock the presentation times mean
588    // nothing here, and the device plays as frames come.
589    let presented = header
590        .first_presented
591        .filter(|_| clock.locked())
592        .map(|first| Presented {
593            first: now + ahead(first),
594            offset: clock.offset(),
595        });
596    if let Some(sink) = &opened.blocks {
597        words.clear();
598        if media::read_words(pdu, &opened.media, words) {
599            let channels = usize::from(opened.media.channels());
600            let arrived = Arrived {
601                presented: presented.map(|presented| presented.first),
602                margin: presented.map(|presented| presented.first - now),
603                samples: words.len() / channels.max(1),
604                channels,
605                missed,
606                media_reset: header.media_reset,
607            };
608            sink.take(&arrived, words);
609        }
610    }
611    let Some(output) = &opened.output else {
612        return;
613    };
614    let samples = match &opened.config.channel_map {
615        Some(map) => {
616            remap(samples, opened.media.channels(), map, mapped);
617            &*mapped
618        }
619        None => &*samples,
620    };
621    output.write(samples, presented);
622    if header.sequence == 0 {
623        counters
624            .drift_ppm
625            .store(output.drift_ppm(), Ordering::Relaxed);
626        counters
627            .device_underruns
628            .store(output.underruns(), Ordering::Relaxed);
629        if let Some((delay, error)) = output.playout() {
630            counters.delay.store(delay, Ordering::Relaxed);
631            counters.playout_error.store(error, Ordering::Relaxed);
632        }
633    }
634}
635
636/// `samples`, frames of `channels` interleaved, into `out` as `map` plays
637/// them: each of its channels the stream channel it names, silence where
638/// it names none or one the stream lacks.
639fn remap(samples: &[f32], channels: u16, map: &[Option<u16>], out: &mut Vec<f32>) {
640    let channels = usize::from(channels.max(1));
641    out.clear();
642    for frame in samples.chunks_exact(channels) {
643        out.extend(map.iter().map(|channel| {
644            channel
645                .and_then(|channel| frame.get(usize::from(channel)))
646                .copied()
647                .unwrap_or(0.0)
648        }));
649    }
650}
651
652#[cfg(test)]
653mod tests {
654    use super::*;
655
656    /// A channel map plays the stream's channels where it names them, and
657    /// silence elsewhere.
658    #[test]
659    fn a_channel_map_moves_and_silences_channels() {
660        let samples = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6];
661        let mut out = Vec::new();
662        remap(&samples, 3, &[Some(2), None, Some(0)], &mut out);
663        assert_eq!(out, [0.3, 0.0, 0.1, 0.6, 0.0, 0.4]);
664    }
665
666    /// A frame of the stream waited for is known by its stream ID alone,
667    /// so one in another format still counts as unsupported.
668    #[test]
669    fn a_frame_of_the_stream_is_known_by_its_id() {
670        let mut am824 = [0u8; 32];
671        am824[0] = 0x00; // IEC 61883
672        am824[4..12].copy_from_slice(&0x0001_f201_62e5_0000u64.to_be_bytes());
673        assert!(of_stream(&am824, 0x0001_f201_62e5_0000));
674        assert!(!of_stream(&am824, 0x0001_f201_62e5_0001));
675        assert!(!of_stream(&am824[..11], 0x0001_f201_62e5_0000));
676    }
677}