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