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