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 left out as due too late to arrive in time, as when the
99    /// thread woke late: the stream goes on past them on its timeline.
100    pub frames_late: u64,
101    /// Times the media clock started again, which the mr bit tells.
102    pub media_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    frames_late: AtomicU64,
124    send_errors: AtomicU64,
125    peaks: Peaks,
126}
127
128/// The group's counters, which its streams share.
129#[derive(Default)]
130struct GroupCounters {
131    media_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, frames_late, send_errors) =
287            self.shared
288                .counters
289                .get(place)
290                .map_or((0, 0, 0), |counters| {
291                    (
292                        read(&counters.frames_sent),
293                        read(&counters.frames_late),
294                        read(&counters.send_errors),
295                    )
296                });
297        TalkerStats {
298            frames_sent,
299            frames_late,
300            media_resets: read(&group.media_resets),
301            clock_resets: read(&group.clock_resets),
302            adjustments: read(&group.adjustments),
303            underruns: read(&group.underruns),
304            send_errors,
305            realtime: group.realtime.load(Ordering::Relaxed),
306            drift_ppm: group.drift_ppm.load(Ordering::Relaxed),
307        }
308    }
309
310    /// The loudest sample in each of the first two channels `place`'s
311    /// stream sent since the last time this was asked, from 0 to 1, for a
312    /// meter.
313    pub fn take_peaks(&self, place: usize) -> [f32; 2] {
314        self.shared
315            .counters
316            .get(place)
317            .map_or([0.0; 2], |counters| counters.peaks.take())
318    }
319}
320
321impl Drop for TalkerGroup {
322    fn drop(&mut self) {
323        self.stop.store(true, Ordering::Relaxed);
324        if let Some(handle) = self.handle.take() {
325            let _ = handle.join();
326        }
327    }
328}
329
330/// One of a group's streams, sending while it lives: dropping it stops
331/// that stream, and the group once none holds it.
332pub struct GroupTalker {
333    group: Arc<TalkerGroup>,
334    place: usize,
335}
336
337impl GroupTalker {
338    /// Starts `stream` in `group`'s `place`.
339    pub fn start(group: &Arc<TalkerGroup>, place: usize, stream: GroupStream) -> io::Result<Self> {
340        group.set_stream(place, Some(stream))?;
341        Ok(GroupTalker {
342            group: group.clone(),
343            place,
344        })
345    }
346
347    /// Sends the stream to `destinations` from its next frame on, none
348    /// pausing it.
349    pub fn set_destinations(&self, destinations: Vec<MacAddress>) {
350        self.group.set_destinations(self.place, destinations);
351    }
352
353    pub fn stats(&self) -> TalkerStats {
354        self.group.stats(self.place)
355    }
356
357    /// The loudest sample in each of the first two channels sent since the
358    /// last time this was asked, from 0 to 1.
359    pub fn take_peaks(&self) -> [f32; 2] {
360        self.group.take_peaks(self.place)
361    }
362}
363
364impl Drop for GroupTalker {
365    fn drop(&mut self) {
366        let _ = self.group.set_stream(self.place, None);
367    }
368}
369
370/// A running talker of one stream. Dropping it stops the stream.
371pub struct Talker {
372    group: TalkerGroup,
373}
374
375impl Talker {
376    /// Starts sending `config`'s stream on `clock`'s time.
377    pub fn start(config: TalkerConfig, clock: Arc<MediaClock>) -> io::Result<Self> {
378        let media = Media::of(config.format).ok_or_else(|| {
379            io::Error::new(
380                io::ErrorKind::Unsupported,
381                "not an AAF, AM824 or CRF format this talker sends",
382            )
383        })?;
384        let group = TalkerGroup::start(
385            GroupConfig {
386                interface: config.interface,
387                mac: config.mac,
388                rate: media.sample_rate(),
389            },
390            1,
391            clock,
392        )?;
393        group.set_stream(
394            0,
395            Some(GroupStream {
396                stream_id: config.stream_id,
397                destinations: config.destinations,
398                vlan_id: config.vlan_id,
399                priority: config.priority,
400                format: config.format,
401                max_transit_time: config.max_transit_time,
402                source: config.source,
403                channels: media.channels(),
404            }),
405        )?;
406        Ok(Talker { group })
407    }
408
409    /// Sends the stream to `destinations` from the next frame on, none
410    /// pausing it.
411    pub fn set_destinations(&self, destinations: Vec<MacAddress>) {
412        self.group.set_destinations(0, destinations);
413    }
414
415    pub fn stats(&self) -> TalkerStats {
416        self.group.stats(0)
417    }
418}
419
420/// The frame's Ethernet header: destination, source, VLAN tag, ethertype.
421fn ethernet_header(mac: MacAddress, stream: &GroupStream) -> [u8; ETHERNET_LEN] {
422    let mut header = [0; ETHERNET_LEN];
423    header[..6].copy_from_slice(&stream.destinations.first().map_or([0; 6], |mac| mac.0));
424    header[6..12].copy_from_slice(&mac.0);
425    header[12..14].copy_from_slice(&ETHERTYPE_VLAN.to_be_bytes());
426    let tag = (u16::from(stream.priority & 0x7) << 13) | (stream.vlan_id & 0x0fff);
427    header[14..16].copy_from_slice(&tag.to_be_bytes());
428    header[16..18].copy_from_slice(&ETHERTYPE_AVTP.to_be_bytes());
429    header
430}
431
432/// A stream the thread sends.
433struct Running {
434    stream: GroupStream,
435    /// Where its samples come from; none for a media clock.
436    input: Option<Input>,
437    packetizer: Packetizer,
438    frame: Vec<u8>,
439    samples: Vec<f32>,
440    /// The format's channels, which its samples' frames have.
441    channels: usize,
442    /// The group's samples each of its frames spans.
443    frame_samples: u64,
444    /// The first sample of its next frame.
445    next: u64,
446    /// The mr bit its frames carry.
447    media_reset: MediaReset,
448}
449
450/// A stream's mr bit, which changes as its media clock starts again. A
451/// start no frame has carried yet goes out with the one before it: two
452/// changes with no frame between would cancel, and a listener would see
453/// the timeline jump with the bit as it was.
454#[derive(Debug, Default)]
455struct MediaReset {
456    bit: bool,
457    /// Whether a frame sent has carried the bit since it last changed.
458    carried: bool,
459}
460
461impl MediaReset {
462    /// The media clock starts again.
463    fn restart(&mut self) {
464        if self.carried {
465            self.bit = !self.bit;
466            self.carried = false;
467        }
468    }
469
470    /// A frame with the bit went out, to at least one destination.
471    fn sent(&mut self) {
472        self.carried = true;
473    }
474}
475
476impl Running {
477    fn new(
478        mac: MacAddress,
479        stream: GroupStream,
480        media: Media,
481        input: Option<Input>,
482        frame_samples: u64,
483    ) -> Self {
484        let mut frame = vec![0u8; ETHERNET_LEN + media.pdu_length()];
485        frame[..ETHERNET_LEN].copy_from_slice(&ethernet_header(mac, &stream));
486        let samples =
487            vec![0.0f32; usize::from(media.channels()) * usize::from(media.samples_per_frame())];
488        Running {
489            packetizer: Packetizer::new(media, stream.stream_id),
490            stream,
491            input,
492            frame,
493            samples,
494            channels: usize::from(media.channels()),
495            frame_samples: frame_samples.max(1),
496            next: 0,
497            media_reset: MediaReset::default(),
498        }
499    }
500
501    fn frame_samples(&self) -> u64 {
502        self.frame_samples
503    }
504
505    /// Its next frame's first sample at or after sample `from`.
506    fn first_from(&self, from: u64) -> u64 {
507        from.div_ceil(self.frame_samples()) * self.frame_samples()
508    }
509
510    /// Leaves out its frames before sample `from`, as too late to send,
511    /// and gives how many: what comes after stays on the timeline, so a
512    /// listener misses those frames alone, where a restart would have it
513    /// lock again.
514    fn skip_to(&mut self, from: u64) -> u64 {
515        let frames = self.first_from(from).saturating_sub(self.next) / self.frame_samples();
516        if let Some(input) = &mut self.input {
517            input.skip(frames as usize * self.samples.len() / self.channels.max(1));
518        }
519        self.packetizer.skip(frames);
520        self.next += frames * self.frame_samples();
521        frames
522    }
523}
524
525/// The group's clock: sample `s` goes out at gPTP time `origin` plus `s`
526/// sample periods, or, following a media clock, where that clock puts it.
527struct Timeline {
528    rate: u64,
529    origin: i64,
530    /// The media clock followed, and where the samples fall on it.
531    follow: Option<Following>,
532    /// The latest line of the media clock to follow, which a restart
533    /// takes up.
534    wanted: Option<Fit>,
535}
536
537/// Samples on a recovered media clock: sample `sample` falls on its event
538/// `sub / rate`, and each sample takes `base` of those `1 / rate` events.
539#[derive(Debug, Clone, Copy)]
540struct Following {
541    fit: Fit,
542    sample: u64,
543    sub: i128,
544    base: i128,
545}
546
547impl Timeline {
548    fn at(&self, sample: u64) -> i64 {
549        match &self.follow {
550            Some(following) => {
551                let samples = i128::from(sample) - i128::from(following.sample);
552                following
553                    .fit
554                    .time_at(following.sub + samples * following.base, self.rate)
555            }
556            None => self.origin + (u128::from(sample) * NANOS / u128::from(self.rate)) as i64,
557        }
558    }
559
560    /// The first sample sent at or after gPTP time `time`.
561    fn sample_at(&self, time: i64) -> u64 {
562        match &self.follow {
563            Some(following) => {
564                let sub = following.fit.sub_at(time, self.rate);
565                let samples = div_ceil(sub - following.sub, following.base);
566                (i128::from(following.sample) + samples).max(0) as u64
567            }
568            None => {
569                let since = (time - self.origin).max(0);
570                (since as u128 * u128::from(self.rate)).div_ceil(NANOS) as u64
571            }
572        }
573    }
574
575    /// Takes the followed clock's latest line, none while it is not
576    /// recovered: the same clock moves the samples with it; whether the
577    /// samples must start again on another, or on gPTP time, it tells.
578    fn take(&mut self, fit: Option<Fit>) -> bool {
579        self.wanted = fit;
580        match (fit, self.follow.as_mut()) {
581            (Some(fit), Some(following)) if following.fit.generation == fit.generation => {
582                following.fit = fit;
583                false
584            }
585            (None, None) => false,
586            _ => true,
587        }
588    }
589
590    /// Starts again so that sample `from`, rounded up to the alignment,
591    /// goes out at least a millisecond after `now`: on a millisecond of
592    /// gPTP time, or on an event of the media clock followed; gives that
593    /// sample.
594    fn restart(&mut self, from: u64, now: i64) -> u64 {
595        let first = from.div_ceil(ALIGN) * ALIGN;
596        let boundary = (now / 1_000_000 + 2) * 1_000_000;
597        match self.wanted {
598            Some(fit) => {
599                let rate = i128::from(self.rate);
600                let edge = div_ceil(fit.sub_at(boundary, self.rate), rate) * rate;
601                self.follow = Some(Following {
602                    fit,
603                    sample: first,
604                    sub: edge,
605                    base: i128::from(fit.base_frequency),
606                });
607            }
608            None => {
609                self.follow = None;
610                self.origin = boundary - (u128::from(first) * NANOS / u128::from(self.rate)) as i64;
611            }
612        }
613        first
614    }
615}
616
617/// Takes the streams wanted: those gone stop, new ones start on their
618/// next frame a millisecond on, changed ones start again, and those whose
619/// destinations moved send there.
620fn take_changes(
621    config: &GroupConfig,
622    shared: &Shared,
623    running: &mut [Option<Running>],
624    timeline: &mut Timeline,
625    clock: &MediaClock,
626) {
627    let wanted = shared.lock().clone();
628    let mut inputs = shared.inputs.lock().unwrap_or_else(PoisonError::into_inner);
629    let idle = running.iter().all(Option::is_none);
630    let mut from = None;
631    for (place, wanted) in wanted.into_iter().enumerate() {
632        let Some(slot) = running.get_mut(place) else {
633            continue;
634        };
635        match (wanted, slot.as_mut()) {
636            (None, _) => *slot = None,
637            (Some(stream), Some(now)) if same_but_destinations(&stream, &now.stream) => {
638                if stream.destinations != now.stream.destinations {
639                    now.frame[..ETHERNET_LEN]
640                        .copy_from_slice(&ethernet_header(config.mac, &stream));
641                    now.stream.destinations = stream.destinations;
642                }
643            }
644            (Some(stream), _) => {
645                let input = inputs.get_mut(place).and_then(Option::take);
646                let Some((media, frame_samples)) = Media::of(stream.format)
647                    .and_then(|media| Some((media, media.frame_samples_at(config.rate)?)))
648                else {
649                    *slot = None;
650                    continue;
651                };
652                // An audio stream needs its source; a media clock has none.
653                if input.is_none() && !media.is_clock() {
654                    *slot = None;
655                    continue;
656                }
657                // The first stream after none starts the clock again.
658                let start = *from.get_or_insert_with(|| {
659                    let now = clock.now();
660                    if idle {
661                        timeline.restart(timeline.sample_at(now), now)
662                    } else {
663                        timeline.sample_at(now + 1_000_000)
664                    }
665                });
666                let mut made = Running::new(config.mac, stream, media, input, frame_samples);
667                made.next = made.first_from(start);
668                *slot = Some(made);
669            }
670        }
671    }
672}
673
674/// Whether two streams differ in their destinations alone.
675fn same_but_destinations(one: &GroupStream, other: &GroupStream) -> bool {
676    GroupStream {
677        destinations: Vec::new(),
678        ..one.clone()
679    } == GroupStream {
680        destinations: Vec::new(),
681        ..other.clone()
682    }
683}
684
685fn run(
686    config: &GroupConfig,
687    shared: &Shared,
688    sender: &FrameSender,
689    clock: &MediaClock,
690    stop: &AtomicBool,
691) {
692    precise_sleeps();
693    shared
694        .group
695        .realtime
696        .store(crate::realtime::raise(), Ordering::Relaxed);
697    let mut running: Vec<Option<Running>> = (0..shared.counters.len()).map(|_| None).collect();
698    let mut timeline = Timeline {
699        rate: u64::from(config.rate.max(1)),
700        origin: 0,
701        follow: None,
702        wanted: None,
703    };
704    let mut seen = u64::MAX;
705    let mut frames: u64 = 0;
706    let mut follow: Option<RecoveredClock> = None;
707    let mut switched = false;
708    let mut generation = clock.generation();
709    while !stop.load(Ordering::Relaxed) {
710        let changes = shared.changes.load(Ordering::Relaxed);
711        if changes != seen {
712            seen = changes;
713            let wanted = shared
714                .follow
715                .lock()
716                .unwrap_or_else(PoisonError::into_inner)
717                .clone();
718            // Leaving a clock followed starts again; samples on gPTP time
719            // start again once the new clock is recovered.
720            if wanted != follow {
721                follow = wanted;
722                switched = timeline.follow.take().is_some();
723            }
724            timeline.take(follow.as_ref().and_then(RecoveredClock::fit));
725            take_changes(config, shared, &mut running, &mut timeline, clock);
726        }
727        // The media clock followed moves the samples with it; one that
728        // comes, goes or starts again starts them again on it, or on gPTP
729        // time.
730        let retime = timeline.take(follow.as_ref().and_then(RecoveredClock::fit));
731        // gPTP time jumped, as to a new grandmaster: the timeline built on
732        // the old one is no good, and the streams start again on the new.
733        let jumped = clock.generation() != generation;
734        generation = clock.generation();
735        if (retime || jumped || std::mem::take(&mut switched))
736            && running.iter().any(Option::is_some)
737        {
738            restart(&mut running, &mut timeline, clock);
739            shared.group.media_resets.fetch_add(1, Ordering::Relaxed);
740            if jumped {
741                shared.group.clock_resets.fetch_add(1, Ordering::Relaxed);
742            }
743        }
744        // The stream whose frame is due first.
745        let Some((place, due)) = running
746            .iter()
747            .enumerate()
748            .filter_map(|(place, stream)| {
749                stream
750                    .as_ref()
751                    .map(|stream| (place, timeline.at(stream.next)))
752            })
753            .min_by_key(|(_, due)| *due)
754        else {
755            std::thread::sleep(LONGEST_SLEEP);
756            continue;
757        };
758        let wake = clock.monotonic_at(due);
759        let now = monotonic_now();
760        if wake > now {
761            let wait = wake - now;
762            std::thread::sleep(wait.min(LONGEST_SLEEP));
763            if wait > LONGEST_SLEEP {
764                // Too far ahead for the clock to have only drifted: it
765                // went back, and the streams start again from it.
766                if due - clock.now() > 2 * LONGEST_SLEEP.as_nanos() as i64 {
767                    restart(&mut running, &mut timeline, clock);
768                    shared.group.media_resets.fetch_add(1, Ordering::Relaxed);
769                    shared.group.clock_resets.fetch_add(1, Ordering::Relaxed);
770                }
771                continue;
772            }
773        }
774        let Some(stream) = running[place].as_mut() else {
775            continue;
776        };
777        // A frame sent late still arrives in time while its presentation
778        // time is far enough ahead.
779        let transit = stream.stream.max_transit_time.as_nanos() as i64;
780        let allowed = (transit - CROSSING).max(transit / 2);
781        let now = clock.now();
782        let counters = &shared.counters[place];
783        if now - due > allowed {
784            // Too late to arrive in time, as when the thread woke late:
785            // the stream goes on from its first frame that still would,
786            // past one at least.
787            let from = timeline.sample_at(now - allowed).max(stream.next + 1);
788            let skipped = stream.skip_to(from);
789            counters.frames_late.fetch_add(skipped, Ordering::Relaxed);
790            continue;
791        }
792        if let Some(input) = &mut stream.input {
793            input.read_as(&mut stream.samples, stream.channels);
794        }
795        counters.peaks.raise(&stream.samples, stream.channels);
796        stream.packetizer.write(
797            due + transit,
798            stream.media_reset.bit,
799            &stream.samples,
800            &mut stream.frame[ETHERNET_LEN..],
801        );
802        for destination in &stream.stream.destinations {
803            stream.frame[..6].copy_from_slice(&destination.0);
804            match sender.send(&stream.frame) {
805                Ok(()) => {
806                    counters.frames_sent.fetch_add(1, Ordering::Relaxed);
807                    stream.media_reset.sent();
808                }
809                Err(_) => {
810                    counters.send_errors.fetch_add(1, Ordering::Relaxed);
811                }
812            }
813        }
814        stream.next += stream.frame_samples();
815        frames += 1;
816        if frames.is_multiple_of(800) {
817            // Each tenth of a second at 8000 frames a second, the sources'
818            // own counts.
819            let (mut made, mut empty, mut drift) = (0, 0, 0);
820            for input in running
821                .iter()
822                .flatten()
823                .filter_map(|stream| stream.input.as_ref())
824            {
825                let (adjusted, short) = input.counts();
826                made += adjusted;
827                empty += short;
828                if drift == 0 {
829                    drift = input.drift_ppm();
830                }
831            }
832            shared.group.adjustments.store(made, Ordering::Relaxed);
833            shared.group.drift_ppm.store(drift, Ordering::Relaxed);
834            shared.group.underruns.store(empty, Ordering::Relaxed);
835        }
836    }
837}
838
839/// Starts every stream again on the clock as it is now, which the mr
840/// bit tells.
841fn restart(running: &mut [Option<Running>], timeline: &mut Timeline, clock: &MediaClock) {
842    let now = clock.now();
843    let first = timeline.restart(timeline.sample_at(now), now);
844    for stream in running.iter_mut().flatten() {
845        stream.next = stream.first_from(first);
846        stream.media_reset.restart();
847    }
848}
849
850#[cfg(test)]
851mod tests {
852    use super::*;
853
854    /// Samples map to gPTP time exactly, every stream's frames on its
855    /// interval: 6 samples at 48 kHz each 125 µs, 12 each 250 µs.
856    #[test]
857    fn the_timeline_counts_samples_on_gptp_time() {
858        let mut timeline = Timeline {
859            rate: 48_000,
860            origin: 0,
861            follow: None,
862            wanted: None,
863        };
864        let first = timeline.restart(5, 7_400_000);
865        assert_eq!(first, 48);
866        assert_eq!(timeline.at(first), 9_000_000);
867        assert_eq!(timeline.at(first + 6) - timeline.at(first), 125_000);
868        assert_eq!(timeline.at(first + 12) - timeline.at(first), 250_000);
869        assert_eq!(timeline.sample_at(timeline.at(first + 6)), first + 6);
870        // A time between samples gives the next sample.
871        assert_eq!(timeline.sample_at(timeline.at(first) + 1), first + 1);
872    }
873
874    /// Following a media clock 50 ppm fast at 48 kHz, a 192 kHz group's
875    /// samples start on one of its events and run 50 ppm fast with it,
876    /// four to an event; another start of the clock, or its loss, starts
877    /// them again.
878    #[test]
879    fn the_timeline_follows_a_media_clock() {
880        // Events 20833.33 ns apart, less 50 ppm, 32.32.
881        let period = (1e9 / 48_000.0 / (1.0 + 50e-6) * 4_294_967_296.0) as u64;
882        let fit = Fit {
883            generation: 3,
884            event: 960_000,
885            time: 21_000_000_000,
886            period,
887            base_frequency: 48_000,
888        };
889        let mut timeline = Timeline {
890            rate: 192_000,
891            origin: 0,
892            follow: None,
893            wanted: None,
894        };
895        assert!(timeline.take(Some(fit)), "a clock to follow starts again");
896        let first = timeline.restart(1000, 21_000_000_000);
897        assert_eq!(first, 1008);
898        let start = timeline.at(first);
899        assert!(start >= 21_002_000_000, "{start}");
900        // On an event: a whole number of periods from the line's.
901        let events = fit.sub_at(start, 1) - i128::from(fit.event);
902        assert_eq!(fit.time_at(i128::from(fit.event) + events, 1), start);
903        // A second of samples is 50 ppm short of a second.
904        let second = timeline.at(first + 192_000) - start;
905        assert!((second - 999_950_002).abs() <= 2, "{second}");
906        assert_eq!(
907            timeline.at(first + 4) - start,
908            fit.time_at(i128::from(fit.event) + events + 1, 1) - start
909        );
910        assert_eq!(timeline.sample_at(timeline.at(first + 7)), first + 7);
911        // The same clock's next line moves the samples on.
912        let later = Fit {
913            event: fit.event + 96,
914            time: fit.time_at(i128::from(fit.event) + 96, 1),
915            ..fit
916        };
917        assert!(!timeline.take(Some(later)));
918        assert_eq!(timeline.at(first + 192_000) - start, second);
919        // A new start of the clock, or none, starts again.
920        assert!(timeline.take(Some(Fit {
921            generation: 4,
922            ..later
923        })));
924        assert!(timeline.take(None));
925        timeline.restart(first + 192_000, 22_500_000_000);
926        assert!(timeline.follow.is_none());
927        assert!(!timeline.take(None));
928    }
929
930    /// Frames too late to send are left out on the stream's timeline: the
931    /// next goes out as it would have, its sequence number, presentation
932    /// time, samples and mr bit, with only those between missing.
933    #[test]
934    fn late_frames_are_left_out() {
935        let format = StreamFormat(0x0205_0220_0200_6000);
936        let media = Media::of(format).unwrap();
937        let source = Source::Tone {
938            hertz: 1000.0,
939            level: 0.5,
940        };
941        let stream = GroupStream {
942            stream_id: 1,
943            destinations: Vec::new(),
944            vlan_id: 2,
945            priority: 3,
946            format,
947            max_transit_time: Duration::from_millis(2),
948            source: source.clone(),
949            channels: 8,
950        };
951        let start = || {
952            let input = Input::open(&source, 8, 48_000).unwrap();
953            let mut made = Running::new(MacAddress([0; 6]), stream.clone(), media, Some(input), 6);
954            made.next = 480;
955            made
956        };
957        let send = |running: &mut Running| {
958            let input = running.input.as_mut().unwrap();
959            input.read_as(&mut running.samples, running.channels);
960            let presentation = 9_000_000 + running.next as i64 * 1_000_000_000 / 48_000;
961            running.packetizer.write(
962                presentation,
963                running.media_reset.bit,
964                &running.samples,
965                &mut running.frame[ETHERNET_LEN..],
966            );
967            running.next += running.frame_samples();
968            let mut samples = Vec::new();
969            let received =
970                crate::media::read(&running.frame[ETHERNET_LEN..], &media, &mut samples).unwrap();
971            (received, samples)
972        };
973        let (mut every, mut late) = (start(), start());
974        for _ in 0..4 {
975            send(&mut every);
976        }
977        // Sample 500 falls in the fourth frame, so the fifth is next.
978        assert_eq!(late.skip_to(500), 4);
979        assert_eq!(late.next, every.next);
980        let (wanted, wanted_samples) = send(&mut every);
981        let (got, samples) = send(&mut late);
982        assert_eq!(got, wanted);
983        assert_eq!(got.sequence, 4);
984        assert!(!got.media_reset);
985        assert!(
986            samples
987                .iter()
988                .zip(&wanted_samples)
989                .all(|(sample, wanted)| (sample - wanted).abs() < 1e-4),
990            "the tone goes on where it would have"
991        );
992        // A sample the stream is past leaves nothing out.
993        assert_eq!(late.skip_to(late.next), 0);
994    }
995
996    /// The mr bit changes for a start of the media clock once a frame sent
997    /// has carried it as it was: two starts with no frame sent between, as
998    /// a late send and then a jump of gPTP time, or a frame no destination
999    /// took, change it once, and a start before the first frame not at all.
1000    #[test]
1001    fn the_mr_bit_tells_each_start() {
1002        let mut media_reset = MediaReset::default();
1003        media_reset.restart();
1004        assert!(!media_reset.bit, "nothing to tell before the first frame");
1005        media_reset.sent();
1006        media_reset.restart();
1007        media_reset.restart();
1008        assert!(media_reset.bit, "two starts change the bit once");
1009        // A frame that went nowhere tells nothing.
1010        media_reset.restart();
1011        assert!(media_reset.bit);
1012        media_reset.sent();
1013        media_reset.restart();
1014        assert!(!media_reset.bit);
1015    }
1016}