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