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