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