1use std::io;
21use std::sync::Arc;
22use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering};
23use std::thread::JoinHandle;
24use std::time::Duration;
25
26use atdecc::stream_format::StreamFormat;
27use avb_net::MacAddress;
28use avb_net::clock::{monotonic_now, precise_sleeps};
29use avb_net::stream::FrameSender;
30
31use crate::MediaClock;
32use crate::audio::{Input, Source};
33use crate::lock::{Guard, Lock};
34use crate::media::{Media, Packetizer};
35use crate::meter::Peaks;
36use crate::recovered::{Fit, RecoveredClock, div_ceil};
37use crate::timing::Timing;
38
39const ETHERTYPE_VLAN: u16 = 0x8100;
41const ETHERTYPE_AVTP: u16 = 0x22f0;
42const ETHERNET_LEN: usize = 18;
44const CROSSING: i64 = 500_000;
48pub const LAUNCH_AHEAD: Duration = Duration::from_millis(2);
51const LATE_STAMP: Duration = Duration::from_micros(20);
56const LONGEST_SLEEP: Duration = Duration::from_millis(20);
59const ALIGN: u64 = 48;
63const NANOS: u128 = 1_000_000_000;
64
65#[derive(Debug, Clone, PartialEq)]
67pub struct TalkerConfig {
68 pub interface: String,
69 pub mac: MacAddress,
71 pub stream_id: u64,
72 pub destinations: Vec<MacAddress>,
76 pub vlan_id: u16,
77 pub priority: u8,
78 pub format: StreamFormat,
79 pub max_transit_time: Duration,
81 pub source: Source,
82}
83
84#[derive(Debug, Clone, PartialEq)]
86pub struct GroupConfig {
87 pub interface: String,
88 pub mac: MacAddress,
90 pub rate: u32,
91}
92
93#[derive(Debug, Clone, PartialEq)]
95pub struct GroupStream {
96 pub stream_id: u64,
97 pub destinations: Vec<MacAddress>,
100 pub vlan_id: u16,
101 pub priority: u8,
102 pub format: StreamFormat,
104 pub max_transit_time: Duration,
106 pub source: Source,
108 pub channels: u16,
111}
112
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
115pub struct TalkerStats {
116 pub frames_sent: u64,
117 pub frames_late: u64,
120 pub media_resets: u64,
122 pub clock_resets: u64,
125 pub adjustments: u64,
128 pub underruns: u64,
129 pub send_errors: u64,
131 pub realtime: bool,
133 pub drift_ppm: i32,
136}
137
138#[derive(Default)]
140struct StreamCounters {
141 frames_sent: AtomicU64,
142 frames_late: AtomicU64,
143 send_errors: AtomicU64,
144 peaks: Peaks,
145}
146
147#[derive(Default)]
149struct GroupCounters {
150 media_resets: AtomicU64,
151 clock_resets: AtomicU64,
152 adjustments: AtomicU64,
153 underruns: AtomicU64,
154 realtime: AtomicBool,
155 drift_ppm: AtomicI32,
156}
157
158struct Shared {
160 streams: Lock<Vec<Option<GroupStream>>>,
163 changes: AtomicU64,
164 inputs: Lock<Vec<Option<Input>>>,
167 follow: Lock<Option<RecoveredClock>>,
169 counters: Vec<StreamCounters>,
170 group: GroupCounters,
171}
172
173impl Shared {
174 fn lock(&self) -> Guard<'_, Vec<Option<GroupStream>>> {
175 self.streams.lock()
176 }
177}
178
179pub struct TalkerGroup {
181 shared: Arc<Shared>,
182 stop: Arc<AtomicBool>,
183 handle: Option<JoinHandle<()>>,
184 rate: u32,
185 ahead: Option<Duration>,
186}
187
188impl TalkerGroup {
189 pub fn start(config: GroupConfig, places: usize, clock: Arc<MediaClock>) -> io::Result<Self> {
192 Self::start_ahead(config, places, clock, None)
193 }
194
195 pub fn start_ahead(
198 config: GroupConfig,
199 places: usize,
200 clock: Arc<MediaClock>,
201 ahead: Option<Duration>,
202 ) -> io::Result<Self> {
203 let sender = FrameSender::open(&config.interface)?;
204 let room = avb_net::stream::paced_frames(&config.interface);
207 let ahead = ahead.filter(|_| room.is_some() && sender.time_departures().is_ok());
208 let launch = ahead.map(|ahead| (ahead, room.unwrap_or(u32::MAX)));
209 let stop = Arc::new(AtomicBool::new(false));
210 let shared = Arc::new(Shared {
211 streams: Lock::new(vec![None; places]),
212 changes: AtomicU64::new(0),
213 inputs: Lock::new((0..places).map(|_| None).collect()),
214 follow: Lock::new(None),
215 counters: (0..places).map(|_| StreamCounters::default()).collect(),
216 group: GroupCounters::default(),
217 });
218 let rate = config.rate;
219 let handle = {
220 let stop = stop.clone();
221 let shared = shared.clone();
222 std::thread::Builder::new()
223 .name("talker".into())
224 .spawn(move || run(&config, &shared, &sender, &clock, launch, &stop))?
225 };
226 Ok(TalkerGroup {
227 shared,
228 stop,
229 handle: Some(handle),
230 rate,
231 ahead,
232 })
233 }
234
235 pub fn rate(&self) -> u32 {
237 self.rate
238 }
239
240 pub fn launch_ahead(&self) -> Option<Duration> {
243 self.ahead
244 }
245
246 pub fn set_stream(&self, place: usize, stream: Option<GroupStream>) -> io::Result<()> {
249 let input = match &stream {
250 Some(stream) => {
251 let media = Media::of(stream.format).ok_or_else(|| {
252 io::Error::new(
253 io::ErrorKind::Unsupported,
254 "not an AAF, AM824 or CRF format this talker sends",
255 )
256 })?;
257 if media.frame_samples_at(self.rate).is_none() {
258 return Err(io::Error::new(
259 io::ErrorKind::InvalidInput,
260 "a stream at another rate than its group's",
261 ));
262 }
263 if media.is_clock() {
264 None
265 } else {
266 Some(Input::open(&stream.source, stream.channels, self.rate)?)
267 }
268 }
269 None => None,
270 };
271 let mut streams = self.shared.lock();
272 let Some(slot) = streams.get_mut(place) else {
273 return Err(io::Error::new(io::ErrorKind::InvalidInput, "no such place"));
274 };
275 if let Some(waiting) = self.shared.inputs.lock().get_mut(place) {
276 *waiting = input;
277 }
278 *slot = stream;
279 self.shared.changes.fetch_add(1, Ordering::Relaxed);
280 Ok(())
281 }
282
283 pub fn set_destinations(&self, place: usize, destinations: Vec<MacAddress>) {
286 let mut streams = self.shared.lock();
287 if let Some(Some(stream)) = streams.get_mut(place) {
288 stream.destinations = destinations;
289 self.shared.changes.fetch_add(1, Ordering::Relaxed);
290 }
291 }
292
293 pub fn follow(&self, clock: Option<RecoveredClock>) {
298 let mut follow = self.shared.follow.lock();
299 if *follow != clock {
300 *follow = clock;
301 self.shared.changes.fetch_add(1, Ordering::Relaxed);
302 }
303 }
304
305 pub fn sending(&self) -> bool {
307 self.shared.lock().iter().any(Option::is_some)
308 }
309
310 pub fn sends(&self, place: usize) -> bool {
312 self.shared.lock().get(place).is_some_and(Option::is_some)
313 }
314
315 pub fn stats(&self, place: usize) -> TalkerStats {
317 let read = |counter: &AtomicU64| counter.load(Ordering::Relaxed);
318 let group = &self.shared.group;
319 let (frames_sent, frames_late, send_errors) =
320 self.shared
321 .counters
322 .get(place)
323 .map_or((0, 0, 0), |counters| {
324 (
325 read(&counters.frames_sent),
326 read(&counters.frames_late),
327 read(&counters.send_errors),
328 )
329 });
330 TalkerStats {
331 frames_sent,
332 frames_late,
333 media_resets: read(&group.media_resets),
334 clock_resets: read(&group.clock_resets),
335 adjustments: read(&group.adjustments),
336 underruns: read(&group.underruns),
337 send_errors,
338 realtime: group.realtime.load(Ordering::Relaxed),
339 drift_ppm: group.drift_ppm.load(Ordering::Relaxed),
340 }
341 }
342
343 pub fn take_peaks(&self, place: usize) -> [f32; 2] {
347 self.shared
348 .counters
349 .get(place)
350 .map_or([0.0; 2], |counters| counters.peaks.take())
351 }
352}
353
354impl Drop for TalkerGroup {
355 fn drop(&mut self) {
356 self.stop.store(true, Ordering::Relaxed);
357 if let Some(handle) = self.handle.take() {
358 let _ = handle.join();
359 }
360 }
361}
362
363pub struct GroupTalker {
366 group: Arc<TalkerGroup>,
367 place: usize,
368}
369
370impl GroupTalker {
371 pub fn start(group: &Arc<TalkerGroup>, place: usize, stream: GroupStream) -> io::Result<Self> {
373 group.set_stream(place, Some(stream))?;
374 Ok(GroupTalker {
375 group: group.clone(),
376 place,
377 })
378 }
379
380 pub fn set_destinations(&self, destinations: Vec<MacAddress>) {
383 self.group.set_destinations(self.place, destinations);
384 }
385
386 pub fn stats(&self) -> TalkerStats {
387 self.group.stats(self.place)
388 }
389
390 pub fn take_peaks(&self) -> [f32; 2] {
393 self.group.take_peaks(self.place)
394 }
395}
396
397impl Drop for GroupTalker {
398 fn drop(&mut self) {
399 let _ = self.group.set_stream(self.place, None);
400 }
401}
402
403pub struct Talker {
405 group: TalkerGroup,
406}
407
408impl Talker {
409 pub fn start(config: TalkerConfig, clock: Arc<MediaClock>) -> io::Result<Self> {
412 Self::start_ahead(config, clock, None)
413 }
414
415 pub fn start_ahead(
418 config: TalkerConfig,
419 clock: Arc<MediaClock>,
420 ahead: Option<Duration>,
421 ) -> io::Result<Self> {
422 let media = Media::of(config.format).ok_or_else(|| {
423 io::Error::new(
424 io::ErrorKind::Unsupported,
425 "not an AAF, AM824 or CRF format this talker sends",
426 )
427 })?;
428 let group = TalkerGroup::start_ahead(
429 GroupConfig {
430 interface: config.interface,
431 mac: config.mac,
432 rate: media.sample_rate(),
433 },
434 1,
435 clock,
436 ahead,
437 )?;
438 group.set_stream(
439 0,
440 Some(GroupStream {
441 stream_id: config.stream_id,
442 destinations: config.destinations,
443 vlan_id: config.vlan_id,
444 priority: config.priority,
445 format: config.format,
446 max_transit_time: config.max_transit_time,
447 source: config.source,
448 channels: media.channels(),
449 }),
450 )?;
451 Ok(Talker { group })
452 }
453
454 pub fn set_destinations(&self, destinations: Vec<MacAddress>) {
457 self.group.set_destinations(0, destinations);
458 }
459
460 pub fn stats(&self) -> TalkerStats {
461 self.group.stats(0)
462 }
463
464 pub fn launch_ahead(&self) -> Option<Duration> {
467 self.group.launch_ahead()
468 }
469}
470
471fn ethernet_header(mac: MacAddress, stream: &GroupStream) -> [u8; ETHERNET_LEN] {
473 let mut header = [0; ETHERNET_LEN];
474 header[..6].copy_from_slice(&stream.destinations.first().map_or([0; 6], |mac| mac.0));
475 header[6..12].copy_from_slice(&mac.0);
476 header[12..14].copy_from_slice(ÐERTYPE_VLAN.to_be_bytes());
477 let tag = (u16::from(stream.priority & 0x7) << 13) | (stream.vlan_id & 0x0fff);
478 header[14..16].copy_from_slice(&tag.to_be_bytes());
479 header[16..18].copy_from_slice(ÐERTYPE_AVTP.to_be_bytes());
480 header
481}
482
483struct Running {
485 stream: GroupStream,
486 input: Option<Input>,
488 packetizer: Packetizer,
489 frame: Vec<u8>,
490 samples: Vec<f32>,
491 channels: usize,
493 frame_samples: u64,
495 next: u64,
497 media_reset: MediaReset,
499}
500
501#[derive(Debug, Default)]
506struct MediaReset {
507 bit: bool,
508 carried: bool,
510}
511
512impl MediaReset {
513 fn restart(&mut self) {
515 if self.carried {
516 self.bit = !self.bit;
517 self.carried = false;
518 }
519 }
520
521 fn sent(&mut self) {
523 self.carried = true;
524 }
525}
526
527impl Running {
528 fn new(
529 mac: MacAddress,
530 stream: GroupStream,
531 media: Media,
532 input: Option<Input>,
533 frame_samples: u64,
534 ) -> Self {
535 let mut frame = vec![0u8; ETHERNET_LEN + media.pdu_length()];
536 frame[..ETHERNET_LEN].copy_from_slice(ðernet_header(mac, &stream));
537 let samples =
538 vec![0.0f32; usize::from(media.channels()) * usize::from(media.samples_per_frame())];
539 Running {
540 packetizer: Packetizer::new(media, stream.stream_id),
541 stream,
542 input,
543 frame,
544 samples,
545 channels: usize::from(media.channels()),
546 frame_samples: frame_samples.max(1),
547 next: 0,
548 media_reset: MediaReset::default(),
549 }
550 }
551
552 fn frame_samples(&self) -> u64 {
553 self.frame_samples
554 }
555
556 fn first_from(&self, from: u64) -> u64 {
558 from.div_ceil(self.frame_samples()) * self.frame_samples()
559 }
560
561 fn skip_to(&mut self, from: u64) -> u64 {
566 let frames = self.first_from(from).saturating_sub(self.next) / self.frame_samples();
567 if let Some(input) = &mut self.input {
568 input.skip(frames as usize * self.samples.len() / self.channels.max(1));
569 }
570 self.packetizer.skip(frames);
571 self.next += frames * self.frame_samples();
572 frames
573 }
574}
575
576struct Timeline {
579 rate: u64,
580 origin: i64,
581 follow: Option<Following>,
583 wanted: Option<Fit>,
586}
587
588#[derive(Debug, Clone, Copy)]
591struct Following {
592 fit: Fit,
593 sample: u64,
594 sub: i128,
595 base: i128,
596}
597
598impl Timeline {
599 fn at(&self, sample: u64) -> i64 {
600 match &self.follow {
601 Some(following) => {
602 let samples = i128::from(sample) - i128::from(following.sample);
603 following
604 .fit
605 .time_at(following.sub + samples * following.base, self.rate)
606 }
607 None => self.origin + (u128::from(sample) * NANOS / u128::from(self.rate)) as i64,
608 }
609 }
610
611 fn sample_at(&self, time: i64) -> u64 {
613 match &self.follow {
614 Some(following) => {
615 let sub = following.fit.sub_at(time, self.rate);
616 let samples = div_ceil(sub - following.sub, following.base);
617 (i128::from(following.sample) + samples).max(0) as u64
618 }
619 None => {
620 let since = (time - self.origin).max(0);
621 (since as u128 * u128::from(self.rate)).div_ceil(NANOS) as u64
622 }
623 }
624 }
625
626 fn take(&mut self, fit: Option<Fit>) -> bool {
630 self.wanted = fit;
631 match (fit, self.follow.as_mut()) {
632 (Some(fit), Some(following)) if following.fit.generation == fit.generation => {
633 following.fit = fit;
634 false
635 }
636 (None, None) => false,
637 _ => true,
638 }
639 }
640
641 fn restart(&mut self, from: u64, now: i64) -> u64 {
646 let first = from.div_ceil(ALIGN) * ALIGN;
647 let boundary = (now / 1_000_000 + 2) * 1_000_000;
648 match self.wanted {
649 Some(fit) => {
650 let rate = i128::from(self.rate);
651 let edge = div_ceil(fit.sub_at(boundary, self.rate), rate) * rate;
652 self.follow = Some(Following {
653 fit,
654 sample: first,
655 sub: edge,
656 base: i128::from(fit.base_frequency),
657 });
658 }
659 None => {
660 self.follow = None;
661 self.origin = boundary - (u128::from(first) * NANOS / u128::from(self.rate)) as i64;
662 }
663 }
664 first
665 }
666}
667
668fn take_changes(
672 config: &GroupConfig,
673 shared: &Shared,
674 running: &mut [Option<Running>],
675 timeline: &mut Timeline,
676 clock: &MediaClock,
677) {
678 let wanted = shared.lock().clone();
679 let mut inputs = shared.inputs.lock();
680 let idle = running.iter().all(Option::is_none);
681 let mut from = None;
682 for (place, wanted) in wanted.into_iter().enumerate() {
683 let Some(slot) = running.get_mut(place) else {
684 continue;
685 };
686 match (wanted, slot.as_mut()) {
687 (None, _) => *slot = None,
688 (Some(stream), Some(now)) if same_but_destinations(&stream, &now.stream) => {
689 if stream.destinations != now.stream.destinations {
690 now.frame[..ETHERNET_LEN]
691 .copy_from_slice(ðernet_header(config.mac, &stream));
692 now.stream.destinations = stream.destinations;
693 }
694 }
695 (Some(stream), _) => {
696 let input = inputs.get_mut(place).and_then(Option::take);
697 let Some((media, frame_samples)) = Media::of(stream.format)
698 .and_then(|media| Some((media, media.frame_samples_at(config.rate)?)))
699 else {
700 *slot = None;
701 continue;
702 };
703 if input.is_none() && !media.is_clock() {
705 *slot = None;
706 continue;
707 }
708 let start = *from.get_or_insert_with(|| {
710 let now = clock.now();
711 if idle {
712 timeline.restart(timeline.sample_at(now), now)
713 } else {
714 timeline.sample_at(now + 1_000_000)
715 }
716 });
717 let mut made = Running::new(config.mac, stream, media, input, frame_samples);
718 made.next = made.first_from(start);
719 *slot = Some(made);
720 }
721 }
722 }
723}
724
725fn same_but_destinations(one: &GroupStream, other: &GroupStream) -> bool {
727 GroupStream {
728 destinations: Vec::new(),
729 ..one.clone()
730 } == GroupStream {
731 destinations: Vec::new(),
732 ..other.clone()
733 }
734}
735
736fn run(
737 config: &GroupConfig,
738 shared: &Shared,
739 sender: &FrameSender,
740 clock: &MediaClock,
741 launch: Option<(Duration, u32)>,
742 stop: &AtomicBool,
743) {
744 precise_sleeps();
745 shared
746 .group
747 .realtime
748 .store(crate::realtime::raise(), Ordering::Relaxed);
749 let mut running: Vec<Option<Running>> = (0..shared.counters.len()).map(|_| None).collect();
750 let mut timeline = Timeline {
751 rate: u64::from(config.rate.max(1)),
752 origin: 0,
753 follow: None,
754 wanted: None,
755 };
756 let mut seen = u64::MAX;
757 let mut frames: u64 = 0;
758 let mut follow: Option<RecoveredClock> = None;
759 let mut switched = false;
760 let mut generation = clock.generation();
761 let mut ahead = launch.map(|(ahead, _)| ahead);
762 let mut timing = Timing::start(monotonic_now());
763 while !stop.load(Ordering::Relaxed) {
764 let changes = shared.changes.load(Ordering::Relaxed);
765 if changes != seen {
766 seen = changes;
767 let wanted = shared.follow.lock().clone();
768 if wanted != follow {
771 follow = wanted;
772 switched = timeline.follow.take().is_some();
773 }
774 timeline.take(follow.as_ref().and_then(RecoveredClock::fit));
775 take_changes(config, shared, &mut running, &mut timeline, clock);
776 ahead = fitting(launch, &running, timeline.rate);
777 }
778 let retime = timeline.take(follow.as_ref().and_then(RecoveredClock::fit));
782 let jumped = clock.generation() != generation;
785 generation = clock.generation();
786 if (retime || jumped || std::mem::take(&mut switched))
787 && running.iter().any(Option::is_some)
788 {
789 restart(&mut running, &mut timeline, clock);
790 shared.group.media_resets.fetch_add(1, Ordering::Relaxed);
791 if jumped {
792 shared.group.clock_resets.fetch_add(1, Ordering::Relaxed);
793 }
794 }
795 let Some((place, due)) = running
797 .iter()
798 .enumerate()
799 .filter_map(|(place, stream)| {
800 stream
801 .as_ref()
802 .map(|stream| (place, timeline.at(stream.next)))
803 })
804 .min_by_key(|(_, due)| *due)
805 else {
806 std::thread::sleep(LONGEST_SLEEP);
807 continue;
808 };
809 let departure = clock.monotonic_at(due);
811 let wake = departure.saturating_sub(ahead.unwrap_or_default());
812 let now = monotonic_now();
813 let mut woke = None;
816 if wake > now {
817 let wait = wake - now;
818 std::thread::sleep(wait.min(LONGEST_SLEEP));
819 if wait > LONGEST_SLEEP {
820 if due - clock.now() > 2 * LONGEST_SLEEP.as_nanos() as i64 {
823 restart(&mut running, &mut timeline, clock);
824 shared.group.media_resets.fetch_add(1, Ordering::Relaxed);
825 shared.group.clock_resets.fetch_add(1, Ordering::Relaxed);
826 }
827 continue;
828 }
829 if timing.on() {
830 woke = Some(monotonic_now().saturating_sub(wake));
831 }
832 }
833 let handover = timing.on().then(monotonic_now);
834 let Some(stream) = running[place].as_mut() else {
835 continue;
836 };
837 let transit = stream.stream.max_transit_time.as_nanos() as i64;
840 let allowed = (transit - CROSSING).max(transit / 2);
841 let now = clock.now();
842 let counters = &shared.counters[place];
843 if now - due > allowed {
844 let from = timeline.sample_at(now - allowed / 2).max(stream.next + 1);
850 let skipped = stream.skip_to(from);
851 counters.frames_late.fetch_add(skipped, Ordering::Relaxed);
852 continue;
853 }
854 if let Some(input) = &mut stream.input {
855 input.read_as(&mut stream.samples, stream.channels);
856 }
857 counters.peaks.raise(&stream.samples, stream.channels);
858 stream.packetizer.write(
859 due + transit,
860 stream.media_reset.bit,
861 &stream.samples,
862 &mut stream.frame[ETHERNET_LEN..],
863 );
864 if clock.now() - due > allowed {
868 stream.next += stream.frame_samples();
869 counters.frames_late.fetch_add(1, Ordering::Relaxed);
870 continue;
871 }
872 let stamp = departure.max(monotonic_now() + LATE_STAMP).as_nanos() as u64;
873 let built = timing.on().then(monotonic_now);
874 for destination in &stream.stream.destinations {
875 stream.frame[..6].copy_from_slice(&destination.0);
876 let sent = match ahead {
877 Some(_) => sender.send_at(&stream.frame, stamp),
878 None => sender.send(&stream.frame),
879 };
880 match sent {
881 Ok(()) => {
882 counters.frames_sent.fetch_add(1, Ordering::Relaxed);
883 stream.media_reset.sent();
884 }
885 Err(_) => {
886 counters.send_errors.fetch_add(1, Ordering::Relaxed);
887 }
888 }
889 }
890 if let (Some(handover), Some(built)) = (handover, built) {
891 let sent = monotonic_now();
892 timing.frame(sent, woke, built - handover, sent - built);
893 }
894 stream.next += stream.frame_samples();
895 frames += 1;
896 if frames.is_multiple_of(800) {
897 let (mut made, mut empty, mut drift) = (0, 0, 0);
900 for input in running
901 .iter()
902 .flatten()
903 .filter_map(|stream| stream.input.as_ref())
904 {
905 let (adjusted, short) = input.counts();
906 made += adjusted;
907 empty += short;
908 if drift == 0 {
909 drift = input.drift_ppm();
910 }
911 }
912 shared.group.adjustments.store(made, Ordering::Relaxed);
913 shared.group.drift_ppm.store(drift, Ordering::Relaxed);
914 shared.group.underruns.store(empty, Ordering::Relaxed);
915 }
916 }
917}
918
919fn fitting(
924 launch: Option<(Duration, u32)>,
925 running: &[Option<Running>],
926 rate: u64,
927) -> Option<Duration> {
928 let (ahead, room) = launch?;
929 let per_second: f64 = running
930 .iter()
931 .flatten()
932 .map(|stream| {
933 stream.stream.destinations.len() as f64 * rate as f64
934 / stream.frame_samples().max(1) as f64
935 })
936 .sum();
937 if per_second <= 0.0 {
938 return Some(ahead);
939 }
940 Some(ahead.min(Duration::from_secs_f64(f64::from(room) / 2.0 / per_second)))
941}
942
943fn restart(running: &mut [Option<Running>], timeline: &mut Timeline, clock: &MediaClock) {
946 let now = clock.now();
947 let first = timeline.restart(timeline.sample_at(now), now);
948 for stream in running.iter_mut().flatten() {
949 stream.next = stream.first_from(first);
950 stream.media_reset.restart();
951 }
952}
953
954#[cfg(test)]
955mod tests {
956 use super::*;
957
958 #[test]
961 fn the_timeline_counts_samples_on_gptp_time() {
962 let mut timeline = Timeline {
963 rate: 48_000,
964 origin: 0,
965 follow: None,
966 wanted: None,
967 };
968 let first = timeline.restart(5, 7_400_000);
969 assert_eq!(first, 48);
970 assert_eq!(timeline.at(first), 9_000_000);
971 assert_eq!(timeline.at(first + 6) - timeline.at(first), 125_000);
972 assert_eq!(timeline.at(first + 12) - timeline.at(first), 250_000);
973 assert_eq!(timeline.sample_at(timeline.at(first + 6)), first + 6);
974 assert_eq!(timeline.sample_at(timeline.at(first) + 1), first + 1);
976 }
977
978 #[test]
983 fn the_timeline_follows_a_media_clock() {
984 let period = (1e9 / 48_000.0 / (1.0 + 50e-6) * 4_294_967_296.0) as u64;
986 let fit = Fit {
987 generation: 3,
988 event: 960_000,
989 time: 21_000_000_000,
990 period,
991 base_frequency: 48_000,
992 };
993 let mut timeline = Timeline {
994 rate: 192_000,
995 origin: 0,
996 follow: None,
997 wanted: None,
998 };
999 assert!(timeline.take(Some(fit)), "a clock to follow starts again");
1000 let first = timeline.restart(1000, 21_000_000_000);
1001 assert_eq!(first, 1008);
1002 let start = timeline.at(first);
1003 assert!(start >= 21_002_000_000, "{start}");
1004 let events = fit.sub_at(start, 1) - i128::from(fit.event);
1006 assert_eq!(fit.time_at(i128::from(fit.event) + events, 1), start);
1007 let second = timeline.at(first + 192_000) - start;
1009 assert!((second - 999_950_002).abs() <= 2, "{second}");
1010 assert_eq!(
1011 timeline.at(first + 4) - start,
1012 fit.time_at(i128::from(fit.event) + events + 1, 1) - start
1013 );
1014 assert_eq!(timeline.sample_at(timeline.at(first + 7)), first + 7);
1015 let later = Fit {
1017 event: fit.event + 96,
1018 time: fit.time_at(i128::from(fit.event) + 96, 1),
1019 ..fit
1020 };
1021 assert!(!timeline.take(Some(later)));
1022 assert_eq!(timeline.at(first + 192_000) - start, second);
1023 assert!(timeline.take(Some(Fit {
1025 generation: 4,
1026 ..later
1027 })));
1028 assert!(timeline.take(None));
1029 timeline.restart(first + 192_000, 22_500_000_000);
1030 assert!(timeline.follow.is_none());
1031 assert!(!timeline.take(None));
1032 }
1033
1034 #[test]
1038 fn late_frames_are_left_out() {
1039 let format = StreamFormat(0x0205_0220_0200_6000);
1040 let media = Media::of(format).unwrap();
1041 let source = Source::Tone {
1042 hertz: 1000.0,
1043 level: 0.5,
1044 };
1045 let stream = GroupStream {
1046 stream_id: 1,
1047 destinations: Vec::new(),
1048 vlan_id: 2,
1049 priority: 3,
1050 format,
1051 max_transit_time: Duration::from_millis(2),
1052 source: source.clone(),
1053 channels: 8,
1054 };
1055 let start = || {
1056 let input = Input::open(&source, 8, 48_000).unwrap();
1057 let mut made = Running::new(MacAddress([0; 6]), stream.clone(), media, Some(input), 6);
1058 made.next = 480;
1059 made
1060 };
1061 let send = |running: &mut Running| {
1062 let input = running.input.as_mut().unwrap();
1063 input.read_as(&mut running.samples, running.channels);
1064 let presentation = 9_000_000 + running.next as i64 * 1_000_000_000 / 48_000;
1065 running.packetizer.write(
1066 presentation,
1067 running.media_reset.bit,
1068 &running.samples,
1069 &mut running.frame[ETHERNET_LEN..],
1070 );
1071 running.next += running.frame_samples();
1072 let mut samples = Vec::new();
1073 let received =
1074 crate::media::read(&running.frame[ETHERNET_LEN..], &media, &mut samples).unwrap();
1075 (received, samples)
1076 };
1077 let (mut every, mut late) = (start(), start());
1078 for _ in 0..4 {
1079 send(&mut every);
1080 }
1081 assert_eq!(late.skip_to(500), 4);
1083 assert_eq!(late.next, every.next);
1084 let (wanted, wanted_samples) = send(&mut every);
1085 let (got, samples) = send(&mut late);
1086 assert_eq!(got, wanted);
1087 assert_eq!(got.sequence, 4);
1088 assert!(!got.media_reset);
1089 assert!(
1090 samples
1091 .iter()
1092 .zip(&wanted_samples)
1093 .all(|(sample, wanted)| (sample - wanted).abs() < 1e-4),
1094 "the tone goes on where it would have"
1095 );
1096 assert_eq!(late.skip_to(late.next), 0);
1098 }
1099
1100 #[test]
1105 fn the_mr_bit_tells_each_start() {
1106 let mut media_reset = MediaReset::default();
1107 media_reset.restart();
1108 assert!(!media_reset.bit, "nothing to tell before the first frame");
1109 media_reset.sent();
1110 media_reset.restart();
1111 media_reset.restart();
1112 assert!(media_reset.bit, "two starts change the bit once");
1113 media_reset.restart();
1115 assert!(media_reset.bit);
1116 media_reset.sent();
1117 media_reset.restart();
1118 assert!(!media_reset.bit);
1119 }
1120}