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