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::{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}
136
137/// What the group's owner and its thread share.
138struct Shared {
139    /// Each place's stream opened, waiting for the thread, or `None` to
140    /// stop it; and how often they changed, which the thread compares
141    /// with what it last took.
142    waiting: Lock<Vec<Option<Option<Opened>>>>,
143    changes: AtomicU64,
144    /// Each place's counters, made anew for each stream.
145    counters: Lock<Vec<Arc<Counters>>>,
146    realtime: AtomicBool,
147}
148
149/// A running group of listeners. Dropping it stops them.
150pub struct ListenerGroup {
151    shared: Arc<Shared>,
152    stop: Arc<AtomicBool>,
153    handle: Option<JoinHandle<()>>,
154}
155
156impl ListenerGroup {
157    /// Starts the group's thread, with room for `places` streams, none
158    /// taken yet.
159    pub fn start(places: usize, clock: Arc<MediaClock>) -> io::Result<Self> {
160        let stop = Arc::new(AtomicBool::new(false));
161        let shared = Arc::new(Shared {
162            waiting: Lock::new((0..places).map(|_| None).collect()),
163            changes: AtomicU64::new(0),
164            counters: Lock::new((0..places).map(|_| Arc::default()).collect()),
165            realtime: AtomicBool::new(false),
166        });
167        let handle = {
168            let stop = stop.clone();
169            let shared = shared.clone();
170            std::thread::Builder::new()
171                .name("listener".into())
172                .spawn(move || run(&shared, &clock, &stop))?
173        };
174        Ok(ListenerGroup {
175            shared,
176            stop,
177            handle: Some(handle),
178        })
179    }
180
181    /// Starts taking `config`'s stream in `place`, in place of what was
182    /// there, opening its socket and sink, or stops what was there.
183    pub fn set_stream(&self, place: usize, config: Option<ListenerConfig>) -> io::Result<()> {
184        let opened = match config {
185            Some(config) => {
186                let media = Media::of(config.format).ok_or_else(|| {
187                    io::Error::new(
188                        io::ErrorKind::Unsupported,
189                        "not an AAF, AM824 or CRF format this listener takes",
190                    )
191                })?;
192                let receiver =
193                    FrameReceiver::open(&config.interface, media.subtype(), &config.destinations)?;
194                // The sink has the channels its map has, where it has one.
195                let channels = config
196                    .channel_map
197                    .as_ref()
198                    .map_or(media.channels(), |map| map.len() as u16);
199                let output = if media.is_clock() {
200                    None
201                } else {
202                    Some(Output::open(&config.sink, channels, media.sample_rate())?)
203                };
204                Some(Opened {
205                    config,
206                    media,
207                    receiver,
208                    output,
209                })
210            }
211            None => None,
212        };
213        let mut waiting = self.shared.waiting.lock();
214        let Some(slot) = waiting.get_mut(place) else {
215            return Err(io::Error::new(io::ErrorKind::InvalidInput, "no such place"));
216        };
217        if opened.is_some()
218            && let Some(counters) = self.shared.counters.lock().get_mut(place)
219        {
220            *counters = Arc::default();
221        }
222        *slot = Some(opened);
223        self.shared.changes.fetch_add(1, Ordering::Relaxed);
224        Ok(())
225    }
226
227    fn counters(&self, place: usize) -> Arc<Counters> {
228        self.shared
229            .counters
230            .lock()
231            .get(place)
232            .cloned()
233            .unwrap_or_default()
234    }
235
236    /// `place`'s counters.
237    pub fn stats(&self, place: usize) -> ListenerStats {
238        let counters = self.counters(place);
239        let read = |counter: &AtomicU64| counter.load(Ordering::Relaxed);
240        ListenerStats {
241            frames_received: read(&counters.frames_received),
242            media_locked: read(&counters.media_locked),
243            media_unlocked: read(&counters.media_unlocked),
244            interrupted: read(&counters.interrupted),
245            sequence_mismatches: read(&counters.sequence_mismatches),
246            unsupported_formats: read(&counters.unsupported_formats),
247            late: read(&counters.late),
248            early: read(&counters.early),
249            socket_drops: read(&counters.socket_drops),
250            locked: counters.locked.load(Ordering::Relaxed),
251            realtime: self.shared.realtime.load(Ordering::Relaxed),
252            drift_ppm: counters.drift_ppm.load(Ordering::Relaxed),
253            device_underruns: read(&counters.device_underruns),
254            playout: match counters.delay.load(Ordering::Relaxed) {
255                i64::MIN => None,
256                delay => Some((delay, counters.playout_error.load(Ordering::Relaxed))),
257            },
258        }
259    }
260
261    /// The loudest sample of `place`'s stream since the last time this was
262    /// asked, from 0 to 1.
263    pub fn take_peak(&self, place: usize) -> f32 {
264        f32::from_bits(self.counters(place).peak.swap(0, Ordering::Relaxed))
265    }
266
267    /// The loudest sample in each of the first two channels of `place`'s
268    /// stream since the last time this was asked, from 0 to 1, for a
269    /// meter.
270    pub fn take_peaks(&self, place: usize) -> [f32; 2] {
271        self.counters(place).peaks.take()
272    }
273}
274
275impl Drop for ListenerGroup {
276    fn drop(&mut self) {
277        self.stop.store(true, Ordering::Relaxed);
278        if let Some(handle) = self.handle.take() {
279            let _ = handle.join();
280        }
281    }
282}
283
284/// One of a group's streams, taken while it lives: dropping it stops
285/// that stream, and the group once none holds it.
286pub struct GroupListener {
287    group: Arc<ListenerGroup>,
288    place: usize,
289}
290
291impl GroupListener {
292    /// Starts taking `config`'s stream in `group`'s `place`.
293    pub fn start(
294        group: &Arc<ListenerGroup>,
295        place: usize,
296        config: ListenerConfig,
297    ) -> io::Result<Self> {
298        group.set_stream(place, Some(config))?;
299        Ok(GroupListener {
300            group: group.clone(),
301            place,
302        })
303    }
304
305    pub fn stats(&self) -> ListenerStats {
306        self.group.stats(self.place)
307    }
308
309    /// The loudest sample since the last time this was asked, from 0 to 1.
310    pub fn take_peak(&self) -> f32 {
311        self.group.take_peak(self.place)
312    }
313
314    /// The loudest sample in each of the first two channels since the
315    /// last time this was asked, from 0 to 1.
316    pub fn take_peaks(&self) -> [f32; 2] {
317        self.group.take_peaks(self.place)
318    }
319}
320
321impl Drop for GroupListener {
322    fn drop(&mut self) {
323        let _ = self.group.set_stream(self.place, None);
324    }
325}
326
327/// A running listener of one stream. Dropping it stops listening.
328pub struct Listener {
329    group: GroupListener,
330}
331
332impl Listener {
333    pub fn start(config: ListenerConfig, clock: Arc<MediaClock>) -> io::Result<Self> {
334        let group = Arc::new(ListenerGroup::start(1, clock)?);
335        Ok(Listener {
336            group: GroupListener::start(&group, 0, config)?,
337        })
338    }
339
340    pub fn stats(&self) -> ListenerStats {
341        self.group.stats()
342    }
343
344    /// The loudest sample since the last time this was asked, from 0 to 1.
345    pub fn take_peak(&self) -> f32 {
346        self.group.take_peak()
347    }
348}
349
350/// A stream the thread takes.
351struct Running {
352    opened: Opened,
353    counters: Arc<Counters>,
354    expected: Option<u8>,
355    last: Instant,
356    /// Its samples in the order its channel map plays them.
357    mapped: Vec<f32>,
358}
359
360impl Drop for Running {
361    /// The clock a stream recovered goes with it, however it stops: in
362    /// place of another, or with the group's thread.
363    fn drop(&mut self) {
364        if let Some(recovered) = &self.opened.config.recovered {
365            recovered.lose();
366        }
367    }
368}
369
370fn run(shared: &Shared, clock: &MediaClock, stop: &AtomicBool) {
371    shared
372        .realtime
373        .store(crate::realtime::raise(), Ordering::Relaxed);
374    let places = shared.waiting.lock().len();
375    let mut running: Vec<Option<Running>> = (0..places).map(|_| None).collect();
376    let mut seen = u64::MAX;
377    let mut frame = vec![0u8; 1522];
378    let mut samples = Vec::new();
379    let mut drops_read = Instant::now();
380    while !stop.load(Ordering::Relaxed) {
381        let changes = shared.changes.load(Ordering::Relaxed);
382        if changes != seen {
383            seen = changes;
384            take_changes(shared, &mut running);
385        }
386        let taking: Vec<usize> = (0..places)
387            .filter(|place| running[*place].is_some())
388            .collect();
389        if taking.is_empty() {
390            std::thread::sleep(LONGEST_WAIT);
391            continue;
392        }
393        let receivers: Vec<&FrameReceiver> = taking
394            .iter()
395            .filter_map(|place| running[*place].as_ref())
396            .map(|stream| &stream.opened.receiver)
397            .collect();
398        let ready = match FrameReceiver::ready(&receivers, Some(LONGEST_WAIT)) {
399            Ok(ready) => ready,
400            Err(_) => {
401                std::thread::sleep(Duration::from_millis(100));
402                continue;
403            }
404        };
405        for at in ready {
406            let Some(stream) = running[taking[at]].as_mut() else {
407                continue;
408            };
409            // Every frame the socket holds.
410            while let Ok(Some(length)) = stream
411                .opened
412                .receiver
413                .receive(&mut frame, Some(Duration::ZERO))
414            {
415                take_frame(stream, &frame[..length], &mut samples, clock);
416            }
417        }
418        // A stream gone quiet is interrupted.
419        for stream in running.iter_mut().flatten() {
420            let counters = &stream.counters;
421            if counters.locked.load(Ordering::Relaxed) && stream.last.elapsed() > SILENCE {
422                counters.locked.store(false, Ordering::Relaxed);
423                counters.media_unlocked.fetch_add(1, Ordering::Relaxed);
424                counters.interrupted.fetch_add(1, Ordering::Relaxed);
425                stream.expected = None;
426                if let Some(recovered) = &stream.opened.config.recovered {
427                    recovered.lose();
428                }
429            }
430        }
431        if drops_read.elapsed() >= DROPS_EVERY {
432            drops_read = Instant::now();
433            for stream in running.iter().flatten() {
434                let dropped = stream.opened.receiver.dropped();
435                if dropped > 0 {
436                    stream
437                        .counters
438                        .socket_drops
439                        .fetch_add(dropped, Ordering::Relaxed);
440                }
441            }
442        }
443    }
444}
445
446/// Takes the streams opened for it and stops those asked to stop.
447fn take_changes(shared: &Shared, running: &mut [Option<Running>]) {
448    let mut waiting = shared.waiting.lock();
449    let counters = shared.counters.lock();
450    for (place, slot) in waiting.iter_mut().enumerate() {
451        let Some(change) = slot.take() else {
452            continue;
453        };
454        if let Some(stream) = running.get_mut(place) {
455            *stream = change.map(|opened| {
456                // What the socket took while the sink opened and this
457                // thread slept is past its time: the stream starts with
458                // what comes next, rather than with frames counted late.
459                let mut frame = [0u8; 1522];
460                while let Ok(Some(_)) = opened.receiver.receive(&mut frame, Some(Duration::ZERO)) {}
461                Running {
462                    opened,
463                    counters: counters.get(place).cloned().unwrap_or_default(),
464                    expected: None,
465                    last: Instant::now(),
466                    mapped: Vec::new(),
467                }
468            });
469        }
470    }
471}
472
473/// Whether an AVTPDU is of stream `stream_id`, whatever its format: the
474/// stream ID of AVTP's common stream header.
475fn of_stream(pdu: &[u8], stream_id: u64) -> bool {
476    pdu.get(4..12)
477        .and_then(|id| id.try_into().ok())
478        .map(u64::from_be_bytes)
479        == Some(stream_id)
480}
481
482/// Counts one frame of a stream and plays its samples.
483fn take_frame(stream: &mut Running, frame: &[u8], samples: &mut Vec<f32>, clock: &MediaClock) {
484    let Running {
485        opened,
486        counters,
487        expected,
488        last,
489        mapped,
490    } = stream;
491    samples.clear();
492    let Some(pdu) = avtp_payload(frame) else {
493        return;
494    };
495    let Some(header) = media::read(pdu, &opened.media, samples) else {
496        // The stream it waits for, in a format it was not opened for, as
497        // when a controller binds a talker of another format: counted, so
498        // the controller sees why nothing plays.
499        if of_stream(pdu, opened.config.stream_id) {
500            counters.unsupported_formats.fetch_add(1, Ordering::Relaxed);
501        }
502        return;
503    };
504    if header.stream_id != opened.config.stream_id {
505        return;
506    }
507    if !header.matches {
508        counters.unsupported_formats.fetch_add(1, Ordering::Relaxed);
509        return;
510    }
511    let now = clock.now();
512    // How far ahead a presentation time is, from the low 32 bits of gPTP
513    // time.
514    let ahead = |timestamp: u32| i64::from(timestamp.wrapping_sub(now as u32) as i32);
515    // The clock the stream carries: a media clock's timestamps, or an
516    // audio stream's first sample's presentation time, each frame its
517    // samples on, made whole from gPTP time, which a hardware clock must
518    // give for its high bits to be right.
519    if let Some(recovered) = &opened.config.recovered {
520        match &opened.media {
521            Media::Crf(layout) => {
522                if let Some((crf, timestamps)) = crf::Header::decode(pdu) {
523                    let times = timestamps
524                        .as_chunks::<8>()
525                        .0
526                        .iter()
527                        .map(|time| u64::from_be_bytes(*time));
528                    recovered.take(
529                        times,
530                        layout.timestamp_interval,
531                        layout.base_frequency,
532                        crf.media_reset,
533                    );
534                }
535            }
536            media => {
537                if let Some(first) = header.first_presented.filter(|_| clock.locked()) {
538                    recovered.take(
539                        [(now + ahead(first)) as u64],
540                        media.samples_per_frame(),
541                        media.sample_rate(),
542                        header.media_reset,
543                    );
544                }
545            }
546        }
547    }
548    *last = Instant::now();
549    counters.frames_received.fetch_add(1, Ordering::Relaxed);
550    if expected.is_some_and(|wanted| wanted != header.sequence) {
551        counters.sequence_mismatches.fetch_add(1, Ordering::Relaxed);
552    }
553    *expected = Some(header.sequence.wrapping_add(1));
554    if !counters.locked.load(Ordering::Relaxed) {
555        counters.locked.store(true, Ordering::Relaxed);
556        counters.media_locked.fetch_add(1, Ordering::Relaxed);
557    }
558    if let Some(timestamp) = header.timestamp {
559        let ahead = ahead(timestamp);
560        if ahead < 0 {
561            counters.late.fetch_add(1, Ordering::Relaxed);
562        } else if ahead > EARLY {
563            counters.early.fetch_add(1, Ordering::Relaxed);
564        }
565    }
566    let loudest = samples
567        .iter()
568        .fold(0.0f32, |most, sample| most.max(sample.abs()));
569    counters
570        .peak
571        .fetch_max(loudest.to_bits(), Ordering::Relaxed);
572    counters
573        .peaks
574        .raise(samples, usize::from(opened.media.channels()));
575    // Without gPTP time from a hardware clock the presentation times mean
576    // nothing here, and the device plays as frames come.
577    let presented = header
578        .first_presented
579        .filter(|_| clock.locked())
580        .map(|first| Presented {
581            first: now + ahead(first),
582            offset: clock.offset(),
583        });
584    let Some(output) = &opened.output else {
585        return;
586    };
587    let samples = match &opened.config.channel_map {
588        Some(map) => {
589            remap(samples, opened.media.channels(), map, mapped);
590            &*mapped
591        }
592        None => &*samples,
593    };
594    output.write(samples, presented);
595    if header.sequence == 0 {
596        counters
597            .drift_ppm
598            .store(output.drift_ppm(), Ordering::Relaxed);
599        counters
600            .device_underruns
601            .store(output.underruns(), Ordering::Relaxed);
602        if let Some((delay, error)) = output.playout() {
603            counters.delay.store(delay, Ordering::Relaxed);
604            counters.playout_error.store(error, Ordering::Relaxed);
605        }
606    }
607}
608
609/// `samples`, frames of `channels` interleaved, into `out` as `map` plays
610/// them: each of its channels the stream channel it names, silence where
611/// it names none or one the stream lacks.
612fn remap(samples: &[f32], channels: u16, map: &[Option<u16>], out: &mut Vec<f32>) {
613    let channels = usize::from(channels.max(1));
614    out.clear();
615    for frame in samples.chunks_exact(channels) {
616        out.extend(map.iter().map(|channel| {
617            channel
618                .and_then(|channel| frame.get(usize::from(channel)))
619                .copied()
620                .unwrap_or(0.0)
621        }));
622    }
623}
624
625#[cfg(test)]
626mod tests {
627    use super::*;
628
629    /// A channel map plays the stream's channels where it names them, and
630    /// silence elsewhere.
631    #[test]
632    fn a_channel_map_moves_and_silences_channels() {
633        let samples = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6];
634        let mut out = Vec::new();
635        remap(&samples, 3, &[Some(2), None, Some(0)], &mut out);
636        assert_eq!(out, [0.3, 0.0, 0.1, 0.6, 0.0, 0.4]);
637    }
638
639    /// A frame of the stream waited for is known by its stream ID alone,
640    /// so one in another format still counts as unsupported.
641    #[test]
642    fn a_frame_of_the_stream_is_known_by_its_id() {
643        let mut am824 = [0u8; 32];
644        am824[0] = 0x00; // IEC 61883
645        am824[4..12].copy_from_slice(&0x0001_f201_62e5_0000u64.to_be_bytes());
646        assert!(of_stream(&am824, 0x0001_f201_62e5_0000));
647        assert!(!of_stream(&am824, 0x0001_f201_62e5_0001));
648        assert!(!of_stream(&am824[..11], 0x0001_f201_62e5_0000));
649    }
650}