Skip to main content

avb_stream/
talker.rs

1//! Talkers of AAF or AM824: one frame each class interval, paced on gPTP
2//! time, its presentation time the max transit time ahead.
3//!
4//! A group sends several streams on one thread, each from its own source.
5//! Their samples are counted on one clock, sample `s` going out at the
6//! group's origin plus `s` sample periods, so the streams present
7//! together, sample for sample. A media clock stream, CRF, is counted on
8//! the same clock, its timestamps the presentation times of the samples
9//! they fall on. A [`Talker`] is a group of one.
10
11use std::io;
12use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering};
13use std::sync::{Arc, Mutex, PoisonError};
14use std::thread::JoinHandle;
15use std::time::Duration;
16
17use atdecc::stream_format::StreamFormat;
18use avb_net::MacAddress;
19use avb_net::clock::{monotonic_now, precise_sleeps};
20use avb_net::stream::FrameSender;
21
22use crate::MediaClock;
23use crate::audio::{Input, Source};
24use crate::media::{Media, Packetizer};
25use crate::meter::Peaks;
26use crate::recovered::{Fit, RecoveredClock, div_ceil};
27
28/// The VLAN tag's ethertype, and AVTP's.
29const ETHERTYPE_VLAN: u16 = 0x8100;
30const ETHERTYPE_AVTP: u16 = 0x22f0;
31/// The Ethernet header with its VLAN tag.
32const ETHERNET_LEN: usize = 18;
33/// How long a frame may take to cross the network to its listeners, in
34/// nanoseconds: a frame sent later than this before its presentation time
35/// would be late.
36const CROSSING: i64 = 500_000;
37/// The longest the pacing thread sleeps at once, so that it follows a
38/// clock that moved.
39const LONGEST_SLEEP: Duration = Duration::from_millis(20);
40/// Streams start on a sample a multiple of this, sent on a millisecond:
41/// every frame size of 6 to 48 samples divides it, so each stream's
42/// frames go out on its class interval's boundaries.
43const ALIGN: u64 = 48;
44const NANOS: u128 = 1_000_000_000;
45
46/// What a talker sends, and from where.
47#[derive(Debug, Clone, PartialEq)]
48pub struct TalkerConfig {
49    pub interface: String,
50    /// The interface's address, the frames' source.
51    pub mac: MacAddress,
52    pub stream_id: u64,
53    /// Where the stream goes: its multicast address, or in AVB Lite a
54    /// unicast copy to each listener. [`Talker::set_destinations`] moves
55    /// it while it runs.
56    pub destinations: Vec<MacAddress>,
57    pub vlan_id: u16,
58    pub priority: u8,
59    pub format: StreamFormat,
60    /// How far ahead of sending the presentation times are.
61    pub max_transit_time: Duration,
62    pub source: Source,
63}
64
65/// Where a group's streams go out, and the rate they all run at.
66#[derive(Debug, Clone, PartialEq)]
67pub struct GroupConfig {
68    pub interface: String,
69    /// The interface's address, the frames' source.
70    pub mac: MacAddress,
71    pub rate: u32,
72}
73
74/// One of a group's streams.
75#[derive(Debug, Clone, PartialEq)]
76pub struct GroupStream {
77    pub stream_id: u64,
78    /// Where the stream goes: its multicast address, or in AVB Lite a
79    /// unicast copy to each listener.
80    pub destinations: Vec<MacAddress>,
81    pub vlan_id: u16,
82    pub priority: u8,
83    /// Its format, at the group's rate.
84    pub format: StreamFormat,
85    /// How far ahead of sending the presentation times are.
86    pub max_transit_time: Duration,
87    /// Where its samples come from.
88    pub source: Source,
89    /// The channels its source gives, which go out as the format's first,
90    /// with silence in the rest, and those past the format's not at all.
91    pub channels: u16,
92}
93
94/// A talker's counters.
95#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
96pub struct TalkerStats {
97    pub frames_sent: u64,
98    /// Frames that went out too late and started the media clock again.
99    pub media_resets: u64,
100    /// Times the input dropped frames as its device ran far ahead, and
101    /// reads that found it empty.
102    pub adjustments: u64,
103    pub underruns: u64,
104    /// Frames the interface would not take.
105    pub send_errors: u64,
106    /// The thread pacing the frames runs real time.
107    pub realtime: bool,
108    /// How far the audio device's clock runs from gPTP's, in parts per
109    /// million.
110    pub drift_ppm: i32,
111}
112
113/// A stream's own counters, and its audio's peaks.
114#[derive(Default)]
115struct StreamCounters {
116    frames_sent: AtomicU64,
117    send_errors: AtomicU64,
118    peaks: Peaks,
119}
120
121/// The group's counters, which its streams share.
122#[derive(Default)]
123struct GroupCounters {
124    media_resets: AtomicU64,
125    adjustments: AtomicU64,
126    underruns: AtomicU64,
127    realtime: AtomicBool,
128    drift_ppm: AtomicI32,
129}
130
131/// What the group's owner and its thread share.
132struct Shared {
133    /// The streams wanted, by place, and how often they changed, which
134    /// the thread compares with what it last took.
135    streams: Mutex<Vec<Option<GroupStream>>>,
136    changes: AtomicU64,
137    /// Each new stream's source, opened for the thread to take; none for
138    /// a media clock.
139    inputs: Mutex<Vec<Option<Input>>>,
140    /// The media clock the streams follow, none for gPTP time itself.
141    follow: Mutex<Option<RecoveredClock>>,
142    counters: Vec<StreamCounters>,
143    group: GroupCounters,
144}
145
146impl Shared {
147    fn lock(&self) -> std::sync::MutexGuard<'_, Vec<Option<GroupStream>>> {
148        self.streams.lock().unwrap_or_else(PoisonError::into_inner)
149    }
150}
151
152/// A running group of streams. Dropping it stops them.
153pub struct TalkerGroup {
154    shared: Arc<Shared>,
155    stop: Arc<AtomicBool>,
156    handle: Option<JoinHandle<()>>,
157    rate: u32,
158}
159
160impl TalkerGroup {
161    /// Starts the group's thread, with room for `places` streams, none
162    /// sending yet.
163    pub fn start(config: GroupConfig, places: usize, clock: Arc<MediaClock>) -> io::Result<Self> {
164        let sender = FrameSender::open(&config.interface)?;
165        let stop = Arc::new(AtomicBool::new(false));
166        let shared = Arc::new(Shared {
167            streams: Mutex::new(vec![None; places]),
168            changes: AtomicU64::new(0),
169            inputs: Mutex::new((0..places).map(|_| None).collect()),
170            follow: Mutex::new(None),
171            counters: (0..places).map(|_| StreamCounters::default()).collect(),
172            group: GroupCounters::default(),
173        });
174        let rate = config.rate;
175        let handle = {
176            let stop = stop.clone();
177            let shared = shared.clone();
178            std::thread::Builder::new()
179                .name("talker".into())
180                .spawn(move || run(&config, &shared, &sender, &clock, &stop))?
181        };
182        Ok(TalkerGroup {
183            shared,
184            stop,
185            handle: Some(handle),
186            rate,
187        })
188    }
189
190    /// The sampling rate its source runs at.
191    pub fn rate(&self) -> u32 {
192        self.rate
193    }
194
195    /// Starts sending `stream` in `place`, in place of what went there,
196    /// opening its source, or stops what went there.
197    pub fn set_stream(&self, place: usize, stream: Option<GroupStream>) -> io::Result<()> {
198        let input = match &stream {
199            Some(stream) => {
200                let media = Media::of(stream.format).ok_or_else(|| {
201                    io::Error::new(
202                        io::ErrorKind::Unsupported,
203                        "not an AAF, AM824 or CRF format this talker sends",
204                    )
205                })?;
206                if media.frame_samples_at(self.rate).is_none() {
207                    return Err(io::Error::new(
208                        io::ErrorKind::InvalidInput,
209                        "a stream at another rate than its group's",
210                    ));
211                }
212                if media.is_clock() {
213                    None
214                } else {
215                    Some(Input::open(&stream.source, stream.channels, self.rate)?)
216                }
217            }
218            None => None,
219        };
220        let mut streams = self.shared.lock();
221        let Some(slot) = streams.get_mut(place) else {
222            return Err(io::Error::new(io::ErrorKind::InvalidInput, "no such place"));
223        };
224        if let Some(waiting) = self
225            .shared
226            .inputs
227            .lock()
228            .unwrap_or_else(PoisonError::into_inner)
229            .get_mut(place)
230        {
231            *waiting = input;
232        }
233        *slot = stream;
234        self.shared.changes.fetch_add(1, Ordering::Relaxed);
235        Ok(())
236    }
237
238    /// Sends `place`'s stream to `destinations` from its next frame on,
239    /// none pausing it.
240    pub fn set_destinations(&self, place: usize, destinations: Vec<MacAddress>) {
241        let mut streams = self.shared.lock();
242        if let Some(Some(stream)) = streams.get_mut(place) {
243            stream.destinations = destinations;
244            self.shared.changes.fetch_add(1, Ordering::Relaxed);
245        }
246    }
247
248    /// Times the streams on `clock`, a media clock recovered from a CRF
249    /// stream, while it is recovered, and on gPTP time otherwise; `None`
250    /// on gPTP time alone. The streams start again on each change of
251    /// clock, as a media reset tells their listeners.
252    pub fn follow(&self, clock: Option<RecoveredClock>) {
253        let mut follow = self
254            .shared
255            .follow
256            .lock()
257            .unwrap_or_else(PoisonError::into_inner);
258        if *follow != clock {
259            *follow = clock;
260            self.shared.changes.fetch_add(1, Ordering::Relaxed);
261        }
262    }
263
264    /// Whether any of its streams sends.
265    pub fn sending(&self) -> bool {
266        self.shared.lock().iter().any(Option::is_some)
267    }
268
269    /// Whether `place`'s stream sends.
270    pub fn sends(&self, place: usize) -> bool {
271        self.shared.lock().get(place).is_some_and(Option::is_some)
272    }
273
274    /// `place`'s counters, with the group's it shares.
275    pub fn stats(&self, place: usize) -> TalkerStats {
276        let read = |counter: &AtomicU64| counter.load(Ordering::Relaxed);
277        let group = &self.shared.group;
278        let (frames_sent, send_errors) =
279            self.shared.counters.get(place).map_or((0, 0), |counters| {
280                (read(&counters.frames_sent), read(&counters.send_errors))
281            });
282        TalkerStats {
283            frames_sent,
284            media_resets: read(&group.media_resets),
285            adjustments: read(&group.adjustments),
286            underruns: read(&group.underruns),
287            send_errors,
288            realtime: group.realtime.load(Ordering::Relaxed),
289            drift_ppm: group.drift_ppm.load(Ordering::Relaxed),
290        }
291    }
292
293    /// The loudest sample in each of the first two channels `place`'s
294    /// stream sent since the last time this was asked, from 0 to 1, for a
295    /// meter.
296    pub fn take_peaks(&self, place: usize) -> [f32; 2] {
297        self.shared
298            .counters
299            .get(place)
300            .map_or([0.0; 2], |counters| counters.peaks.take())
301    }
302}
303
304impl Drop for TalkerGroup {
305    fn drop(&mut self) {
306        self.stop.store(true, Ordering::Relaxed);
307        if let Some(handle) = self.handle.take() {
308            let _ = handle.join();
309        }
310    }
311}
312
313/// One of a group's streams, sending while it lives: dropping it stops
314/// that stream, and the group once none holds it.
315pub struct GroupTalker {
316    group: Arc<TalkerGroup>,
317    place: usize,
318}
319
320impl GroupTalker {
321    /// Starts `stream` in `group`'s `place`.
322    pub fn start(group: &Arc<TalkerGroup>, place: usize, stream: GroupStream) -> io::Result<Self> {
323        group.set_stream(place, Some(stream))?;
324        Ok(GroupTalker {
325            group: group.clone(),
326            place,
327        })
328    }
329
330    /// Sends the stream to `destinations` from its next frame on, none
331    /// pausing it.
332    pub fn set_destinations(&self, destinations: Vec<MacAddress>) {
333        self.group.set_destinations(self.place, destinations);
334    }
335
336    pub fn stats(&self) -> TalkerStats {
337        self.group.stats(self.place)
338    }
339
340    /// The loudest sample in each of the first two channels sent since the
341    /// last time this was asked, from 0 to 1.
342    pub fn take_peaks(&self) -> [f32; 2] {
343        self.group.take_peaks(self.place)
344    }
345}
346
347impl Drop for GroupTalker {
348    fn drop(&mut self) {
349        let _ = self.group.set_stream(self.place, None);
350    }
351}
352
353/// A running talker of one stream. Dropping it stops the stream.
354pub struct Talker {
355    group: TalkerGroup,
356}
357
358impl Talker {
359    /// Starts sending `config`'s stream on `clock`'s time.
360    pub fn start(config: TalkerConfig, clock: Arc<MediaClock>) -> io::Result<Self> {
361        let media = Media::of(config.format).ok_or_else(|| {
362            io::Error::new(
363                io::ErrorKind::Unsupported,
364                "not an AAF, AM824 or CRF format this talker sends",
365            )
366        })?;
367        let group = TalkerGroup::start(
368            GroupConfig {
369                interface: config.interface,
370                mac: config.mac,
371                rate: media.sample_rate(),
372            },
373            1,
374            clock,
375        )?;
376        group.set_stream(
377            0,
378            Some(GroupStream {
379                stream_id: config.stream_id,
380                destinations: config.destinations,
381                vlan_id: config.vlan_id,
382                priority: config.priority,
383                format: config.format,
384                max_transit_time: config.max_transit_time,
385                source: config.source,
386                channels: media.channels(),
387            }),
388        )?;
389        Ok(Talker { group })
390    }
391
392    /// Sends the stream to `destinations` from the next frame on, none
393    /// pausing it.
394    pub fn set_destinations(&self, destinations: Vec<MacAddress>) {
395        self.group.set_destinations(0, destinations);
396    }
397
398    pub fn stats(&self) -> TalkerStats {
399        self.group.stats(0)
400    }
401}
402
403/// The frame's Ethernet header: destination, source, VLAN tag, ethertype.
404fn ethernet_header(mac: MacAddress, stream: &GroupStream) -> [u8; ETHERNET_LEN] {
405    let mut header = [0; ETHERNET_LEN];
406    header[..6].copy_from_slice(&stream.destinations.first().map_or([0; 6], |mac| mac.0));
407    header[6..12].copy_from_slice(&mac.0);
408    header[12..14].copy_from_slice(&ETHERTYPE_VLAN.to_be_bytes());
409    let tag = (u16::from(stream.priority & 0x7) << 13) | (stream.vlan_id & 0x0fff);
410    header[14..16].copy_from_slice(&tag.to_be_bytes());
411    header[16..18].copy_from_slice(&ETHERTYPE_AVTP.to_be_bytes());
412    header
413}
414
415/// A stream the thread sends.
416struct Running {
417    stream: GroupStream,
418    /// Where its samples come from; none for a media clock.
419    input: Option<Input>,
420    packetizer: Packetizer,
421    frame: Vec<u8>,
422    samples: Vec<f32>,
423    /// The format's channels, which its samples' frames have.
424    channels: usize,
425    /// The group's samples each of its frames spans.
426    frame_samples: u64,
427    /// The first sample of its next frame.
428    next: u64,
429}
430
431impl Running {
432    fn new(
433        mac: MacAddress,
434        stream: GroupStream,
435        media: Media,
436        input: Option<Input>,
437        frame_samples: u64,
438    ) -> Self {
439        let mut frame = vec![0u8; ETHERNET_LEN + media.pdu_length()];
440        frame[..ETHERNET_LEN].copy_from_slice(&ethernet_header(mac, &stream));
441        let samples =
442            vec![0.0f32; usize::from(media.channels()) * usize::from(media.samples_per_frame())];
443        Running {
444            packetizer: Packetizer::new(media, stream.stream_id),
445            stream,
446            input,
447            frame,
448            samples,
449            channels: usize::from(media.channels()),
450            frame_samples: frame_samples.max(1),
451            next: 0,
452        }
453    }
454
455    fn frame_samples(&self) -> u64 {
456        self.frame_samples
457    }
458
459    /// Its next frame's first sample at or after sample `from`.
460    fn first_from(&self, from: u64) -> u64 {
461        from.div_ceil(self.frame_samples()) * self.frame_samples()
462    }
463}
464
465/// The group's clock: sample `s` goes out at gPTP time `origin` plus `s`
466/// sample periods, or, following a media clock, where that clock puts it.
467struct Timeline {
468    rate: u64,
469    origin: i64,
470    /// The media clock followed, and where the samples fall on it.
471    follow: Option<Following>,
472    /// The latest line of the media clock to follow, which a restart
473    /// takes up.
474    wanted: Option<Fit>,
475}
476
477/// Samples on a recovered media clock: sample `sample` falls on its event
478/// `sub / rate`, and each sample takes `base` of those `1 / rate` events.
479#[derive(Debug, Clone, Copy)]
480struct Following {
481    fit: Fit,
482    sample: u64,
483    sub: i128,
484    base: i128,
485}
486
487impl Timeline {
488    fn at(&self, sample: u64) -> i64 {
489        match &self.follow {
490            Some(following) => {
491                let samples = i128::from(sample) - i128::from(following.sample);
492                following
493                    .fit
494                    .time_at(following.sub + samples * following.base, self.rate)
495            }
496            None => self.origin + (u128::from(sample) * NANOS / u128::from(self.rate)) as i64,
497        }
498    }
499
500    /// The first sample sent at or after gPTP time `time`.
501    fn sample_at(&self, time: i64) -> u64 {
502        match &self.follow {
503            Some(following) => {
504                let sub = following.fit.sub_at(time, self.rate);
505                let samples = div_ceil(sub - following.sub, following.base);
506                (i128::from(following.sample) + samples).max(0) as u64
507            }
508            None => {
509                let since = (time - self.origin).max(0);
510                (since as u128 * u128::from(self.rate)).div_ceil(NANOS) as u64
511            }
512        }
513    }
514
515    /// Takes the followed clock's latest line, none while it is not
516    /// recovered: the same clock moves the samples with it; whether the
517    /// samples must start again on another, or on gPTP time, it tells.
518    fn take(&mut self, fit: Option<Fit>) -> bool {
519        self.wanted = fit;
520        match (fit, self.follow.as_mut()) {
521            (Some(fit), Some(following)) if following.fit.generation == fit.generation => {
522                following.fit = fit;
523                false
524            }
525            (None, None) => false,
526            _ => true,
527        }
528    }
529
530    /// Starts again so that sample `from`, rounded up to the alignment,
531    /// goes out at least a millisecond after `now`: on a millisecond of
532    /// gPTP time, or on an event of the media clock followed; gives that
533    /// sample.
534    fn restart(&mut self, from: u64, now: i64) -> u64 {
535        let first = from.div_ceil(ALIGN) * ALIGN;
536        let boundary = (now / 1_000_000 + 2) * 1_000_000;
537        match self.wanted {
538            Some(fit) => {
539                let rate = i128::from(self.rate);
540                let edge = div_ceil(fit.sub_at(boundary, self.rate), rate) * rate;
541                self.follow = Some(Following {
542                    fit,
543                    sample: first,
544                    sub: edge,
545                    base: i128::from(fit.base_frequency),
546                });
547            }
548            None => {
549                self.follow = None;
550                self.origin = boundary - (u128::from(first) * NANOS / u128::from(self.rate)) as i64;
551            }
552        }
553        first
554    }
555}
556
557/// Takes the streams wanted: those gone stop, new ones start on their
558/// next frame a millisecond on, changed ones start again, and those whose
559/// destinations moved send there.
560fn take_changes(
561    config: &GroupConfig,
562    shared: &Shared,
563    running: &mut [Option<Running>],
564    timeline: &mut Timeline,
565    clock: &MediaClock,
566) {
567    let wanted = shared.lock().clone();
568    let mut inputs = shared.inputs.lock().unwrap_or_else(PoisonError::into_inner);
569    let idle = running.iter().all(Option::is_none);
570    let mut from = None;
571    for (place, wanted) in wanted.into_iter().enumerate() {
572        let Some(slot) = running.get_mut(place) else {
573            continue;
574        };
575        match (wanted, slot.as_mut()) {
576            (None, _) => *slot = None,
577            (Some(stream), Some(now)) if same_but_destinations(&stream, &now.stream) => {
578                if stream.destinations != now.stream.destinations {
579                    now.frame[..ETHERNET_LEN]
580                        .copy_from_slice(&ethernet_header(config.mac, &stream));
581                    now.stream.destinations = stream.destinations;
582                }
583            }
584            (Some(stream), _) => {
585                let input = inputs.get_mut(place).and_then(Option::take);
586                let Some((media, frame_samples)) = Media::of(stream.format)
587                    .and_then(|media| Some((media, media.frame_samples_at(config.rate)?)))
588                else {
589                    *slot = None;
590                    continue;
591                };
592                // An audio stream needs its source; a media clock has none.
593                if input.is_none() && !media.is_clock() {
594                    *slot = None;
595                    continue;
596                }
597                // The first stream after none starts the clock again.
598                let start = *from.get_or_insert_with(|| {
599                    let now = clock.now();
600                    if idle {
601                        timeline.restart(timeline.sample_at(now), now)
602                    } else {
603                        timeline.sample_at(now + 1_000_000)
604                    }
605                });
606                let mut made = Running::new(config.mac, stream, media, input, frame_samples);
607                made.next = made.first_from(start);
608                *slot = Some(made);
609            }
610        }
611    }
612}
613
614/// Whether two streams differ in their destinations alone.
615fn same_but_destinations(one: &GroupStream, other: &GroupStream) -> bool {
616    GroupStream {
617        destinations: Vec::new(),
618        ..one.clone()
619    } == GroupStream {
620        destinations: Vec::new(),
621        ..other.clone()
622    }
623}
624
625fn run(
626    config: &GroupConfig,
627    shared: &Shared,
628    sender: &FrameSender,
629    clock: &MediaClock,
630    stop: &AtomicBool,
631) {
632    precise_sleeps();
633    shared
634        .group
635        .realtime
636        .store(crate::realtime::raise(), Ordering::Relaxed);
637    let mut running: Vec<Option<Running>> = (0..shared.counters.len()).map(|_| None).collect();
638    let mut timeline = Timeline {
639        rate: u64::from(config.rate.max(1)),
640        origin: 0,
641        follow: None,
642        wanted: None,
643    };
644    let mut seen = u64::MAX;
645    let mut media_reset = false;
646    let mut frames: u64 = 0;
647    let mut follow: Option<RecoveredClock> = None;
648    let mut switched = false;
649    while !stop.load(Ordering::Relaxed) {
650        let changes = shared.changes.load(Ordering::Relaxed);
651        if changes != seen {
652            seen = changes;
653            let wanted = shared
654                .follow
655                .lock()
656                .unwrap_or_else(PoisonError::into_inner)
657                .clone();
658            // Leaving a clock followed starts again; samples on gPTP time
659            // start again once the new clock is recovered.
660            if wanted != follow {
661                follow = wanted;
662                switched = timeline.follow.take().is_some();
663            }
664            timeline.take(follow.as_ref().and_then(RecoveredClock::fit));
665            take_changes(config, shared, &mut running, &mut timeline, clock);
666        }
667        // The media clock followed moves the samples with it; one that
668        // comes, goes or starts again starts them again on it, or on gPTP
669        // time.
670        let retime = timeline.take(follow.as_ref().and_then(RecoveredClock::fit));
671        if (retime || std::mem::take(&mut switched)) && running.iter().any(Option::is_some) {
672            restart(&mut running, &mut timeline, clock);
673            media_reset = !media_reset;
674            shared.group.media_resets.fetch_add(1, Ordering::Relaxed);
675        }
676        // The stream whose frame is due first.
677        let Some((place, due)) = running
678            .iter()
679            .enumerate()
680            .filter_map(|(place, stream)| {
681                stream
682                    .as_ref()
683                    .map(|stream| (place, timeline.at(stream.next)))
684            })
685            .min_by_key(|(_, due)| *due)
686        else {
687            std::thread::sleep(LONGEST_SLEEP);
688            continue;
689        };
690        let wake = clock.monotonic_at(due);
691        let now = monotonic_now();
692        if wake > now {
693            let wait = wake - now;
694            std::thread::sleep(wait.min(LONGEST_SLEEP));
695            if wait > LONGEST_SLEEP {
696                // Too far ahead for the clock to have only drifted: it
697                // went back, and the streams start again from it.
698                if due - clock.now() > 2 * LONGEST_SLEEP.as_nanos() as i64 {
699                    restart(&mut running, &mut timeline, clock);
700                    media_reset = !media_reset;
701                    shared.group.media_resets.fetch_add(1, Ordering::Relaxed);
702                }
703                continue;
704            }
705        }
706        let Some(stream) = running[place].as_mut() else {
707            continue;
708        };
709        // A frame sent late still arrives in time while its presentation
710        // time is far enough ahead.
711        let transit = stream.stream.max_transit_time.as_nanos() as i64;
712        let late = clock.now() - due;
713        if late > (transit - CROSSING).max(transit / 2) {
714            // Too late for the presentation time to mean anything: the
715            // media clock starts again, which the mr bit tells.
716            restart(&mut running, &mut timeline, clock);
717            media_reset = !media_reset;
718            shared.group.media_resets.fetch_add(1, Ordering::Relaxed);
719            continue;
720        }
721        if let Some(input) = &mut stream.input {
722            input.read_as(&mut stream.samples, stream.channels);
723        }
724        let counters = &shared.counters[place];
725        counters.peaks.raise(&stream.samples, stream.channels);
726        stream.packetizer.write(
727            due + transit,
728            media_reset,
729            &stream.samples,
730            &mut stream.frame[ETHERNET_LEN..],
731        );
732        for destination in &stream.stream.destinations {
733            stream.frame[..6].copy_from_slice(&destination.0);
734            match sender.send(&stream.frame) {
735                Ok(()) => counters.frames_sent.fetch_add(1, Ordering::Relaxed),
736                Err(_) => counters.send_errors.fetch_add(1, Ordering::Relaxed),
737            };
738        }
739        stream.next += stream.frame_samples();
740        frames += 1;
741        if frames.is_multiple_of(800) {
742            // Each tenth of a second at 8000 frames a second, the sources'
743            // own counts.
744            let (mut made, mut empty, mut drift) = (0, 0, 0);
745            for input in running
746                .iter()
747                .flatten()
748                .filter_map(|stream| stream.input.as_ref())
749            {
750                let (adjusted, short) = input.counts();
751                made += adjusted;
752                empty += short;
753                if drift == 0 {
754                    drift = input.drift_ppm();
755                }
756            }
757            shared.group.adjustments.store(made, Ordering::Relaxed);
758            shared.group.drift_ppm.store(drift, Ordering::Relaxed);
759            shared.group.underruns.store(empty, Ordering::Relaxed);
760        }
761    }
762}
763
764/// Starts every stream again on the clock as it is now.
765fn restart(running: &mut [Option<Running>], timeline: &mut Timeline, clock: &MediaClock) {
766    let now = clock.now();
767    let first = timeline.restart(timeline.sample_at(now), now);
768    for stream in running.iter_mut().flatten() {
769        stream.next = stream.first_from(first);
770    }
771}
772
773#[cfg(test)]
774mod tests {
775    use super::*;
776
777    /// Samples map to gPTP time exactly, every stream's frames on its
778    /// interval: 6 samples at 48 kHz each 125 µs, 12 each 250 µs.
779    #[test]
780    fn the_timeline_counts_samples_on_gptp_time() {
781        let mut timeline = Timeline {
782            rate: 48_000,
783            origin: 0,
784            follow: None,
785            wanted: None,
786        };
787        let first = timeline.restart(5, 7_400_000);
788        assert_eq!(first, 48);
789        assert_eq!(timeline.at(first), 9_000_000);
790        assert_eq!(timeline.at(first + 6) - timeline.at(first), 125_000);
791        assert_eq!(timeline.at(first + 12) - timeline.at(first), 250_000);
792        assert_eq!(timeline.sample_at(timeline.at(first + 6)), first + 6);
793        // A time between samples gives the next sample.
794        assert_eq!(timeline.sample_at(timeline.at(first) + 1), first + 1);
795    }
796
797    /// Following a media clock 50 ppm fast at 48 kHz, a 192 kHz group's
798    /// samples start on one of its events and run 50 ppm fast with it,
799    /// four to an event; another start of the clock, or its loss, starts
800    /// them again.
801    #[test]
802    fn the_timeline_follows_a_media_clock() {
803        // Events 20833.33 ns apart, less 50 ppm, 32.32.
804        let period = (1e9 / 48_000.0 / (1.0 + 50e-6) * 4_294_967_296.0) as u64;
805        let fit = Fit {
806            generation: 3,
807            event: 960_000,
808            time: 21_000_000_000,
809            period,
810            base_frequency: 48_000,
811        };
812        let mut timeline = Timeline {
813            rate: 192_000,
814            origin: 0,
815            follow: None,
816            wanted: None,
817        };
818        assert!(timeline.take(Some(fit)), "a clock to follow starts again");
819        let first = timeline.restart(1000, 21_000_000_000);
820        assert_eq!(first, 1008);
821        let start = timeline.at(first);
822        assert!(start >= 21_002_000_000, "{start}");
823        // On an event: a whole number of periods from the line's.
824        let events = fit.sub_at(start, 1) - i128::from(fit.event);
825        assert_eq!(fit.time_at(i128::from(fit.event) + events, 1), start);
826        // A second of samples is 50 ppm short of a second.
827        let second = timeline.at(first + 192_000) - start;
828        assert!((second - 999_950_002).abs() <= 2, "{second}");
829        assert_eq!(
830            timeline.at(first + 4) - start,
831            fit.time_at(i128::from(fit.event) + events + 1, 1) - start
832        );
833        assert_eq!(timeline.sample_at(timeline.at(first + 7)), first + 7);
834        // The same clock's next line moves the samples on.
835        let later = Fit {
836            event: fit.event + 96,
837            time: fit.time_at(i128::from(fit.event) + 96, 1),
838            ..fit
839        };
840        assert!(!timeline.take(Some(later)));
841        assert_eq!(timeline.at(first + 192_000) - start, second);
842        // A new start of the clock, or none, starts again.
843        assert!(timeline.take(Some(Fit {
844            generation: 4,
845            ..later
846        })));
847        assert!(timeline.take(None));
848        timeline.restart(first + 192_000, 22_500_000_000);
849        assert!(timeline.follow.is_none());
850        assert!(!timeline.take(None));
851    }
852}