1use std::io;
12use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering};
13use std::sync::{Arc, Mutex, PoisonError};
14use std::thread::JoinHandle;
15use std::time::Duration;
16
17use atdecc::stream_format::StreamFormat;
18use avb_net::MacAddress;
19use avb_net::clock::{monotonic_now, precise_sleeps};
20use avb_net::stream::FrameSender;
21
22use crate::MediaClock;
23use crate::audio::{Input, Source};
24use crate::media::{Media, Packetizer};
25use crate::meter::Peaks;
26use crate::recovered::{Fit, RecoveredClock, div_ceil};
27
28const ETHERTYPE_VLAN: u16 = 0x8100;
30const ETHERTYPE_AVTP: u16 = 0x22f0;
31const ETHERNET_LEN: usize = 18;
33const CROSSING: i64 = 500_000;
37const LONGEST_SLEEP: Duration = Duration::from_millis(20);
40const ALIGN: u64 = 48;
44const NANOS: u128 = 1_000_000_000;
45
46#[derive(Debug, Clone, PartialEq)]
48pub struct TalkerConfig {
49 pub interface: String,
50 pub mac: MacAddress,
52 pub stream_id: u64,
53 pub destinations: Vec<MacAddress>,
57 pub vlan_id: u16,
58 pub priority: u8,
59 pub format: StreamFormat,
60 pub max_transit_time: Duration,
62 pub source: Source,
63}
64
65#[derive(Debug, Clone, PartialEq)]
67pub struct GroupConfig {
68 pub interface: String,
69 pub mac: MacAddress,
71 pub rate: u32,
72}
73
74#[derive(Debug, Clone, PartialEq)]
76pub struct GroupStream {
77 pub stream_id: u64,
78 pub destinations: Vec<MacAddress>,
81 pub vlan_id: u16,
82 pub priority: u8,
83 pub format: StreamFormat,
85 pub max_transit_time: Duration,
87 pub source: Source,
89 pub channels: u16,
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
96pub struct TalkerStats {
97 pub frames_sent: u64,
98 pub frames_late: u64,
101 pub media_resets: u64,
103 pub clock_resets: u64,
106 pub adjustments: u64,
109 pub underruns: u64,
110 pub send_errors: u64,
112 pub realtime: bool,
114 pub drift_ppm: i32,
117}
118
119#[derive(Default)]
121struct StreamCounters {
122 frames_sent: AtomicU64,
123 frames_late: AtomicU64,
124 send_errors: AtomicU64,
125 peaks: Peaks,
126}
127
128#[derive(Default)]
130struct GroupCounters {
131 media_resets: AtomicU64,
132 clock_resets: AtomicU64,
133 adjustments: AtomicU64,
134 underruns: AtomicU64,
135 realtime: AtomicBool,
136 drift_ppm: AtomicI32,
137}
138
139struct Shared {
141 streams: Mutex<Vec<Option<GroupStream>>>,
144 changes: AtomicU64,
145 inputs: Mutex<Vec<Option<Input>>>,
148 follow: Mutex<Option<RecoveredClock>>,
150 counters: Vec<StreamCounters>,
151 group: GroupCounters,
152}
153
154impl Shared {
155 fn lock(&self) -> std::sync::MutexGuard<'_, Vec<Option<GroupStream>>> {
156 self.streams.lock().unwrap_or_else(PoisonError::into_inner)
157 }
158}
159
160pub struct TalkerGroup {
162 shared: Arc<Shared>,
163 stop: Arc<AtomicBool>,
164 handle: Option<JoinHandle<()>>,
165 rate: u32,
166}
167
168impl TalkerGroup {
169 pub fn start(config: GroupConfig, places: usize, clock: Arc<MediaClock>) -> io::Result<Self> {
172 let sender = FrameSender::open(&config.interface)?;
173 let stop = Arc::new(AtomicBool::new(false));
174 let shared = Arc::new(Shared {
175 streams: Mutex::new(vec![None; places]),
176 changes: AtomicU64::new(0),
177 inputs: Mutex::new((0..places).map(|_| None).collect()),
178 follow: Mutex::new(None),
179 counters: (0..places).map(|_| StreamCounters::default()).collect(),
180 group: GroupCounters::default(),
181 });
182 let rate = config.rate;
183 let handle = {
184 let stop = stop.clone();
185 let shared = shared.clone();
186 std::thread::Builder::new()
187 .name("talker".into())
188 .spawn(move || run(&config, &shared, &sender, &clock, &stop))?
189 };
190 Ok(TalkerGroup {
191 shared,
192 stop,
193 handle: Some(handle),
194 rate,
195 })
196 }
197
198 pub fn rate(&self) -> u32 {
200 self.rate
201 }
202
203 pub fn set_stream(&self, place: usize, stream: Option<GroupStream>) -> io::Result<()> {
206 let input = match &stream {
207 Some(stream) => {
208 let media = Media::of(stream.format).ok_or_else(|| {
209 io::Error::new(
210 io::ErrorKind::Unsupported,
211 "not an AAF, AM824 or CRF format this talker sends",
212 )
213 })?;
214 if media.frame_samples_at(self.rate).is_none() {
215 return Err(io::Error::new(
216 io::ErrorKind::InvalidInput,
217 "a stream at another rate than its group's",
218 ));
219 }
220 if media.is_clock() {
221 None
222 } else {
223 Some(Input::open(&stream.source, stream.channels, self.rate)?)
224 }
225 }
226 None => None,
227 };
228 let mut streams = self.shared.lock();
229 let Some(slot) = streams.get_mut(place) else {
230 return Err(io::Error::new(io::ErrorKind::InvalidInput, "no such place"));
231 };
232 if let Some(waiting) = self
233 .shared
234 .inputs
235 .lock()
236 .unwrap_or_else(PoisonError::into_inner)
237 .get_mut(place)
238 {
239 *waiting = input;
240 }
241 *slot = stream;
242 self.shared.changes.fetch_add(1, Ordering::Relaxed);
243 Ok(())
244 }
245
246 pub fn set_destinations(&self, place: usize, destinations: Vec<MacAddress>) {
249 let mut streams = self.shared.lock();
250 if let Some(Some(stream)) = streams.get_mut(place) {
251 stream.destinations = destinations;
252 self.shared.changes.fetch_add(1, Ordering::Relaxed);
253 }
254 }
255
256 pub fn follow(&self, clock: Option<RecoveredClock>) {
261 let mut follow = self
262 .shared
263 .follow
264 .lock()
265 .unwrap_or_else(PoisonError::into_inner);
266 if *follow != clock {
267 *follow = clock;
268 self.shared.changes.fetch_add(1, Ordering::Relaxed);
269 }
270 }
271
272 pub fn sending(&self) -> bool {
274 self.shared.lock().iter().any(Option::is_some)
275 }
276
277 pub fn sends(&self, place: usize) -> bool {
279 self.shared.lock().get(place).is_some_and(Option::is_some)
280 }
281
282 pub fn stats(&self, place: usize) -> TalkerStats {
284 let read = |counter: &AtomicU64| counter.load(Ordering::Relaxed);
285 let group = &self.shared.group;
286 let (frames_sent, frames_late, send_errors) =
287 self.shared
288 .counters
289 .get(place)
290 .map_or((0, 0, 0), |counters| {
291 (
292 read(&counters.frames_sent),
293 read(&counters.frames_late),
294 read(&counters.send_errors),
295 )
296 });
297 TalkerStats {
298 frames_sent,
299 frames_late,
300 media_resets: read(&group.media_resets),
301 clock_resets: read(&group.clock_resets),
302 adjustments: read(&group.adjustments),
303 underruns: read(&group.underruns),
304 send_errors,
305 realtime: group.realtime.load(Ordering::Relaxed),
306 drift_ppm: group.drift_ppm.load(Ordering::Relaxed),
307 }
308 }
309
310 pub fn take_peaks(&self, place: usize) -> [f32; 2] {
314 self.shared
315 .counters
316 .get(place)
317 .map_or([0.0; 2], |counters| counters.peaks.take())
318 }
319}
320
321impl Drop for TalkerGroup {
322 fn drop(&mut self) {
323 self.stop.store(true, Ordering::Relaxed);
324 if let Some(handle) = self.handle.take() {
325 let _ = handle.join();
326 }
327 }
328}
329
330pub struct GroupTalker {
333 group: Arc<TalkerGroup>,
334 place: usize,
335}
336
337impl GroupTalker {
338 pub fn start(group: &Arc<TalkerGroup>, place: usize, stream: GroupStream) -> io::Result<Self> {
340 group.set_stream(place, Some(stream))?;
341 Ok(GroupTalker {
342 group: group.clone(),
343 place,
344 })
345 }
346
347 pub fn set_destinations(&self, destinations: Vec<MacAddress>) {
350 self.group.set_destinations(self.place, destinations);
351 }
352
353 pub fn stats(&self) -> TalkerStats {
354 self.group.stats(self.place)
355 }
356
357 pub fn take_peaks(&self) -> [f32; 2] {
360 self.group.take_peaks(self.place)
361 }
362}
363
364impl Drop for GroupTalker {
365 fn drop(&mut self) {
366 let _ = self.group.set_stream(self.place, None);
367 }
368}
369
370pub struct Talker {
372 group: TalkerGroup,
373}
374
375impl Talker {
376 pub fn start(config: TalkerConfig, clock: Arc<MediaClock>) -> io::Result<Self> {
378 let media = Media::of(config.format).ok_or_else(|| {
379 io::Error::new(
380 io::ErrorKind::Unsupported,
381 "not an AAF, AM824 or CRF format this talker sends",
382 )
383 })?;
384 let group = TalkerGroup::start(
385 GroupConfig {
386 interface: config.interface,
387 mac: config.mac,
388 rate: media.sample_rate(),
389 },
390 1,
391 clock,
392 )?;
393 group.set_stream(
394 0,
395 Some(GroupStream {
396 stream_id: config.stream_id,
397 destinations: config.destinations,
398 vlan_id: config.vlan_id,
399 priority: config.priority,
400 format: config.format,
401 max_transit_time: config.max_transit_time,
402 source: config.source,
403 channels: media.channels(),
404 }),
405 )?;
406 Ok(Talker { group })
407 }
408
409 pub fn set_destinations(&self, destinations: Vec<MacAddress>) {
412 self.group.set_destinations(0, destinations);
413 }
414
415 pub fn stats(&self) -> TalkerStats {
416 self.group.stats(0)
417 }
418}
419
420fn ethernet_header(mac: MacAddress, stream: &GroupStream) -> [u8; ETHERNET_LEN] {
422 let mut header = [0; ETHERNET_LEN];
423 header[..6].copy_from_slice(&stream.destinations.first().map_or([0; 6], |mac| mac.0));
424 header[6..12].copy_from_slice(&mac.0);
425 header[12..14].copy_from_slice(ÐERTYPE_VLAN.to_be_bytes());
426 let tag = (u16::from(stream.priority & 0x7) << 13) | (stream.vlan_id & 0x0fff);
427 header[14..16].copy_from_slice(&tag.to_be_bytes());
428 header[16..18].copy_from_slice(ÐERTYPE_AVTP.to_be_bytes());
429 header
430}
431
432struct Running {
434 stream: GroupStream,
435 input: Option<Input>,
437 packetizer: Packetizer,
438 frame: Vec<u8>,
439 samples: Vec<f32>,
440 channels: usize,
442 frame_samples: u64,
444 next: u64,
446 media_reset: MediaReset,
448}
449
450#[derive(Debug, Default)]
455struct MediaReset {
456 bit: bool,
457 carried: bool,
459}
460
461impl MediaReset {
462 fn restart(&mut self) {
464 if self.carried {
465 self.bit = !self.bit;
466 self.carried = false;
467 }
468 }
469
470 fn sent(&mut self) {
472 self.carried = true;
473 }
474}
475
476impl Running {
477 fn new(
478 mac: MacAddress,
479 stream: GroupStream,
480 media: Media,
481 input: Option<Input>,
482 frame_samples: u64,
483 ) -> Self {
484 let mut frame = vec![0u8; ETHERNET_LEN + media.pdu_length()];
485 frame[..ETHERNET_LEN].copy_from_slice(ðernet_header(mac, &stream));
486 let samples =
487 vec![0.0f32; usize::from(media.channels()) * usize::from(media.samples_per_frame())];
488 Running {
489 packetizer: Packetizer::new(media, stream.stream_id),
490 stream,
491 input,
492 frame,
493 samples,
494 channels: usize::from(media.channels()),
495 frame_samples: frame_samples.max(1),
496 next: 0,
497 media_reset: MediaReset::default(),
498 }
499 }
500
501 fn frame_samples(&self) -> u64 {
502 self.frame_samples
503 }
504
505 fn first_from(&self, from: u64) -> u64 {
507 from.div_ceil(self.frame_samples()) * self.frame_samples()
508 }
509
510 fn skip_to(&mut self, from: u64) -> u64 {
515 let frames = self.first_from(from).saturating_sub(self.next) / self.frame_samples();
516 if let Some(input) = &mut self.input {
517 input.skip(frames as usize * self.samples.len() / self.channels.max(1));
518 }
519 self.packetizer.skip(frames);
520 self.next += frames * self.frame_samples();
521 frames
522 }
523}
524
525struct Timeline {
528 rate: u64,
529 origin: i64,
530 follow: Option<Following>,
532 wanted: Option<Fit>,
535}
536
537#[derive(Debug, Clone, Copy)]
540struct Following {
541 fit: Fit,
542 sample: u64,
543 sub: i128,
544 base: i128,
545}
546
547impl Timeline {
548 fn at(&self, sample: u64) -> i64 {
549 match &self.follow {
550 Some(following) => {
551 let samples = i128::from(sample) - i128::from(following.sample);
552 following
553 .fit
554 .time_at(following.sub + samples * following.base, self.rate)
555 }
556 None => self.origin + (u128::from(sample) * NANOS / u128::from(self.rate)) as i64,
557 }
558 }
559
560 fn sample_at(&self, time: i64) -> u64 {
562 match &self.follow {
563 Some(following) => {
564 let sub = following.fit.sub_at(time, self.rate);
565 let samples = div_ceil(sub - following.sub, following.base);
566 (i128::from(following.sample) + samples).max(0) as u64
567 }
568 None => {
569 let since = (time - self.origin).max(0);
570 (since as u128 * u128::from(self.rate)).div_ceil(NANOS) as u64
571 }
572 }
573 }
574
575 fn take(&mut self, fit: Option<Fit>) -> bool {
579 self.wanted = fit;
580 match (fit, self.follow.as_mut()) {
581 (Some(fit), Some(following)) if following.fit.generation == fit.generation => {
582 following.fit = fit;
583 false
584 }
585 (None, None) => false,
586 _ => true,
587 }
588 }
589
590 fn restart(&mut self, from: u64, now: i64) -> u64 {
595 let first = from.div_ceil(ALIGN) * ALIGN;
596 let boundary = (now / 1_000_000 + 2) * 1_000_000;
597 match self.wanted {
598 Some(fit) => {
599 let rate = i128::from(self.rate);
600 let edge = div_ceil(fit.sub_at(boundary, self.rate), rate) * rate;
601 self.follow = Some(Following {
602 fit,
603 sample: first,
604 sub: edge,
605 base: i128::from(fit.base_frequency),
606 });
607 }
608 None => {
609 self.follow = None;
610 self.origin = boundary - (u128::from(first) * NANOS / u128::from(self.rate)) as i64;
611 }
612 }
613 first
614 }
615}
616
617fn take_changes(
621 config: &GroupConfig,
622 shared: &Shared,
623 running: &mut [Option<Running>],
624 timeline: &mut Timeline,
625 clock: &MediaClock,
626) {
627 let wanted = shared.lock().clone();
628 let mut inputs = shared.inputs.lock().unwrap_or_else(PoisonError::into_inner);
629 let idle = running.iter().all(Option::is_none);
630 let mut from = None;
631 for (place, wanted) in wanted.into_iter().enumerate() {
632 let Some(slot) = running.get_mut(place) else {
633 continue;
634 };
635 match (wanted, slot.as_mut()) {
636 (None, _) => *slot = None,
637 (Some(stream), Some(now)) if same_but_destinations(&stream, &now.stream) => {
638 if stream.destinations != now.stream.destinations {
639 now.frame[..ETHERNET_LEN]
640 .copy_from_slice(ðernet_header(config.mac, &stream));
641 now.stream.destinations = stream.destinations;
642 }
643 }
644 (Some(stream), _) => {
645 let input = inputs.get_mut(place).and_then(Option::take);
646 let Some((media, frame_samples)) = Media::of(stream.format)
647 .and_then(|media| Some((media, media.frame_samples_at(config.rate)?)))
648 else {
649 *slot = None;
650 continue;
651 };
652 if input.is_none() && !media.is_clock() {
654 *slot = None;
655 continue;
656 }
657 let start = *from.get_or_insert_with(|| {
659 let now = clock.now();
660 if idle {
661 timeline.restart(timeline.sample_at(now), now)
662 } else {
663 timeline.sample_at(now + 1_000_000)
664 }
665 });
666 let mut made = Running::new(config.mac, stream, media, input, frame_samples);
667 made.next = made.first_from(start);
668 *slot = Some(made);
669 }
670 }
671 }
672}
673
674fn same_but_destinations(one: &GroupStream, other: &GroupStream) -> bool {
676 GroupStream {
677 destinations: Vec::new(),
678 ..one.clone()
679 } == GroupStream {
680 destinations: Vec::new(),
681 ..other.clone()
682 }
683}
684
685fn run(
686 config: &GroupConfig,
687 shared: &Shared,
688 sender: &FrameSender,
689 clock: &MediaClock,
690 stop: &AtomicBool,
691) {
692 precise_sleeps();
693 shared
694 .group
695 .realtime
696 .store(crate::realtime::raise(), Ordering::Relaxed);
697 let mut running: Vec<Option<Running>> = (0..shared.counters.len()).map(|_| None).collect();
698 let mut timeline = Timeline {
699 rate: u64::from(config.rate.max(1)),
700 origin: 0,
701 follow: None,
702 wanted: None,
703 };
704 let mut seen = u64::MAX;
705 let mut frames: u64 = 0;
706 let mut follow: Option<RecoveredClock> = None;
707 let mut switched = false;
708 let mut generation = clock.generation();
709 while !stop.load(Ordering::Relaxed) {
710 let changes = shared.changes.load(Ordering::Relaxed);
711 if changes != seen {
712 seen = changes;
713 let wanted = shared
714 .follow
715 .lock()
716 .unwrap_or_else(PoisonError::into_inner)
717 .clone();
718 if wanted != follow {
721 follow = wanted;
722 switched = timeline.follow.take().is_some();
723 }
724 timeline.take(follow.as_ref().and_then(RecoveredClock::fit));
725 take_changes(config, shared, &mut running, &mut timeline, clock);
726 }
727 let retime = timeline.take(follow.as_ref().and_then(RecoveredClock::fit));
731 let jumped = clock.generation() != generation;
734 generation = clock.generation();
735 if (retime || jumped || std::mem::take(&mut switched))
736 && running.iter().any(Option::is_some)
737 {
738 restart(&mut running, &mut timeline, clock);
739 shared.group.media_resets.fetch_add(1, Ordering::Relaxed);
740 if jumped {
741 shared.group.clock_resets.fetch_add(1, Ordering::Relaxed);
742 }
743 }
744 let Some((place, due)) = running
746 .iter()
747 .enumerate()
748 .filter_map(|(place, stream)| {
749 stream
750 .as_ref()
751 .map(|stream| (place, timeline.at(stream.next)))
752 })
753 .min_by_key(|(_, due)| *due)
754 else {
755 std::thread::sleep(LONGEST_SLEEP);
756 continue;
757 };
758 let wake = clock.monotonic_at(due);
759 let now = monotonic_now();
760 if wake > now {
761 let wait = wake - now;
762 std::thread::sleep(wait.min(LONGEST_SLEEP));
763 if wait > LONGEST_SLEEP {
764 if due - clock.now() > 2 * LONGEST_SLEEP.as_nanos() as i64 {
767 restart(&mut running, &mut timeline, clock);
768 shared.group.media_resets.fetch_add(1, Ordering::Relaxed);
769 shared.group.clock_resets.fetch_add(1, Ordering::Relaxed);
770 }
771 continue;
772 }
773 }
774 let Some(stream) = running[place].as_mut() else {
775 continue;
776 };
777 let transit = stream.stream.max_transit_time.as_nanos() as i64;
780 let allowed = (transit - CROSSING).max(transit / 2);
781 let now = clock.now();
782 let counters = &shared.counters[place];
783 if now - due > allowed {
784 let from = timeline.sample_at(now - allowed).max(stream.next + 1);
788 let skipped = stream.skip_to(from);
789 counters.frames_late.fetch_add(skipped, Ordering::Relaxed);
790 continue;
791 }
792 if let Some(input) = &mut stream.input {
793 input.read_as(&mut stream.samples, stream.channels);
794 }
795 counters.peaks.raise(&stream.samples, stream.channels);
796 stream.packetizer.write(
797 due + transit,
798 stream.media_reset.bit,
799 &stream.samples,
800 &mut stream.frame[ETHERNET_LEN..],
801 );
802 if clock.now() - due > allowed {
806 stream.next += stream.frame_samples();
807 counters.frames_late.fetch_add(1, Ordering::Relaxed);
808 continue;
809 }
810 for destination in &stream.stream.destinations {
811 stream.frame[..6].copy_from_slice(&destination.0);
812 match sender.send(&stream.frame) {
813 Ok(()) => {
814 counters.frames_sent.fetch_add(1, Ordering::Relaxed);
815 stream.media_reset.sent();
816 }
817 Err(_) => {
818 counters.send_errors.fetch_add(1, Ordering::Relaxed);
819 }
820 }
821 }
822 stream.next += stream.frame_samples();
823 frames += 1;
824 if frames.is_multiple_of(800) {
825 let (mut made, mut empty, mut drift) = (0, 0, 0);
828 for input in running
829 .iter()
830 .flatten()
831 .filter_map(|stream| stream.input.as_ref())
832 {
833 let (adjusted, short) = input.counts();
834 made += adjusted;
835 empty += short;
836 if drift == 0 {
837 drift = input.drift_ppm();
838 }
839 }
840 shared.group.adjustments.store(made, Ordering::Relaxed);
841 shared.group.drift_ppm.store(drift, Ordering::Relaxed);
842 shared.group.underruns.store(empty, Ordering::Relaxed);
843 }
844 }
845}
846
847fn restart(running: &mut [Option<Running>], timeline: &mut Timeline, clock: &MediaClock) {
850 let now = clock.now();
851 let first = timeline.restart(timeline.sample_at(now), now);
852 for stream in running.iter_mut().flatten() {
853 stream.next = stream.first_from(first);
854 stream.media_reset.restart();
855 }
856}
857
858#[cfg(test)]
859mod tests {
860 use super::*;
861
862 #[test]
865 fn the_timeline_counts_samples_on_gptp_time() {
866 let mut timeline = Timeline {
867 rate: 48_000,
868 origin: 0,
869 follow: None,
870 wanted: None,
871 };
872 let first = timeline.restart(5, 7_400_000);
873 assert_eq!(first, 48);
874 assert_eq!(timeline.at(first), 9_000_000);
875 assert_eq!(timeline.at(first + 6) - timeline.at(first), 125_000);
876 assert_eq!(timeline.at(first + 12) - timeline.at(first), 250_000);
877 assert_eq!(timeline.sample_at(timeline.at(first + 6)), first + 6);
878 assert_eq!(timeline.sample_at(timeline.at(first) + 1), first + 1);
880 }
881
882 #[test]
887 fn the_timeline_follows_a_media_clock() {
888 let period = (1e9 / 48_000.0 / (1.0 + 50e-6) * 4_294_967_296.0) as u64;
890 let fit = Fit {
891 generation: 3,
892 event: 960_000,
893 time: 21_000_000_000,
894 period,
895 base_frequency: 48_000,
896 };
897 let mut timeline = Timeline {
898 rate: 192_000,
899 origin: 0,
900 follow: None,
901 wanted: None,
902 };
903 assert!(timeline.take(Some(fit)), "a clock to follow starts again");
904 let first = timeline.restart(1000, 21_000_000_000);
905 assert_eq!(first, 1008);
906 let start = timeline.at(first);
907 assert!(start >= 21_002_000_000, "{start}");
908 let events = fit.sub_at(start, 1) - i128::from(fit.event);
910 assert_eq!(fit.time_at(i128::from(fit.event) + events, 1), start);
911 let second = timeline.at(first + 192_000) - start;
913 assert!((second - 999_950_002).abs() <= 2, "{second}");
914 assert_eq!(
915 timeline.at(first + 4) - start,
916 fit.time_at(i128::from(fit.event) + events + 1, 1) - start
917 );
918 assert_eq!(timeline.sample_at(timeline.at(first + 7)), first + 7);
919 let later = Fit {
921 event: fit.event + 96,
922 time: fit.time_at(i128::from(fit.event) + 96, 1),
923 ..fit
924 };
925 assert!(!timeline.take(Some(later)));
926 assert_eq!(timeline.at(first + 192_000) - start, second);
927 assert!(timeline.take(Some(Fit {
929 generation: 4,
930 ..later
931 })));
932 assert!(timeline.take(None));
933 timeline.restart(first + 192_000, 22_500_000_000);
934 assert!(timeline.follow.is_none());
935 assert!(!timeline.take(None));
936 }
937
938 #[test]
942 fn late_frames_are_left_out() {
943 let format = StreamFormat(0x0205_0220_0200_6000);
944 let media = Media::of(format).unwrap();
945 let source = Source::Tone {
946 hertz: 1000.0,
947 level: 0.5,
948 };
949 let stream = GroupStream {
950 stream_id: 1,
951 destinations: Vec::new(),
952 vlan_id: 2,
953 priority: 3,
954 format,
955 max_transit_time: Duration::from_millis(2),
956 source: source.clone(),
957 channels: 8,
958 };
959 let start = || {
960 let input = Input::open(&source, 8, 48_000).unwrap();
961 let mut made = Running::new(MacAddress([0; 6]), stream.clone(), media, Some(input), 6);
962 made.next = 480;
963 made
964 };
965 let send = |running: &mut Running| {
966 let input = running.input.as_mut().unwrap();
967 input.read_as(&mut running.samples, running.channels);
968 let presentation = 9_000_000 + running.next as i64 * 1_000_000_000 / 48_000;
969 running.packetizer.write(
970 presentation,
971 running.media_reset.bit,
972 &running.samples,
973 &mut running.frame[ETHERNET_LEN..],
974 );
975 running.next += running.frame_samples();
976 let mut samples = Vec::new();
977 let received =
978 crate::media::read(&running.frame[ETHERNET_LEN..], &media, &mut samples).unwrap();
979 (received, samples)
980 };
981 let (mut every, mut late) = (start(), start());
982 for _ in 0..4 {
983 send(&mut every);
984 }
985 assert_eq!(late.skip_to(500), 4);
987 assert_eq!(late.next, every.next);
988 let (wanted, wanted_samples) = send(&mut every);
989 let (got, samples) = send(&mut late);
990 assert_eq!(got, wanted);
991 assert_eq!(got.sequence, 4);
992 assert!(!got.media_reset);
993 assert!(
994 samples
995 .iter()
996 .zip(&wanted_samples)
997 .all(|(sample, wanted)| (sample - wanted).abs() < 1e-4),
998 "the tone goes on where it would have"
999 );
1000 assert_eq!(late.skip_to(late.next), 0);
1002 }
1003
1004 #[test]
1009 fn the_mr_bit_tells_each_start() {
1010 let mut media_reset = MediaReset::default();
1011 media_reset.restart();
1012 assert!(!media_reset.bit, "nothing to tell before the first frame");
1013 media_reset.sent();
1014 media_reset.restart();
1015 media_reset.restart();
1016 assert!(media_reset.bit, "two starts change the bit once");
1017 media_reset.restart();
1019 assert!(media_reset.bit);
1020 media_reset.sent();
1021 media_reset.restart();
1022 assert!(!media_reset.bit);
1023 }
1024}