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