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 media_resets: u64,
100 pub adjustments: u64,
103 pub underruns: u64,
104 pub send_errors: u64,
106 pub realtime: bool,
108 pub drift_ppm: i32,
111}
112
113#[derive(Default)]
115struct StreamCounters {
116 frames_sent: AtomicU64,
117 send_errors: AtomicU64,
118 peaks: Peaks,
119}
120
121#[derive(Default)]
123struct GroupCounters {
124 media_resets: AtomicU64,
125 adjustments: AtomicU64,
126 underruns: AtomicU64,
127 realtime: AtomicBool,
128 drift_ppm: AtomicI32,
129}
130
131struct Shared {
133 streams: Mutex<Vec<Option<GroupStream>>>,
136 changes: AtomicU64,
137 inputs: Mutex<Vec<Option<Input>>>,
140 follow: Mutex<Option<RecoveredClock>>,
142 counters: Vec<StreamCounters>,
143 group: GroupCounters,
144}
145
146impl Shared {
147 fn lock(&self) -> std::sync::MutexGuard<'_, Vec<Option<GroupStream>>> {
148 self.streams.lock().unwrap_or_else(PoisonError::into_inner)
149 }
150}
151
152pub struct TalkerGroup {
154 shared: Arc<Shared>,
155 stop: Arc<AtomicBool>,
156 handle: Option<JoinHandle<()>>,
157 rate: u32,
158}
159
160impl TalkerGroup {
161 pub fn start(config: GroupConfig, places: usize, clock: Arc<MediaClock>) -> io::Result<Self> {
164 let sender = FrameSender::open(&config.interface)?;
165 let stop = Arc::new(AtomicBool::new(false));
166 let shared = Arc::new(Shared {
167 streams: Mutex::new(vec![None; places]),
168 changes: AtomicU64::new(0),
169 inputs: Mutex::new((0..places).map(|_| None).collect()),
170 follow: Mutex::new(None),
171 counters: (0..places).map(|_| StreamCounters::default()).collect(),
172 group: GroupCounters::default(),
173 });
174 let rate = config.rate;
175 let handle = {
176 let stop = stop.clone();
177 let shared = shared.clone();
178 std::thread::Builder::new()
179 .name("talker".into())
180 .spawn(move || run(&config, &shared, &sender, &clock, &stop))?
181 };
182 Ok(TalkerGroup {
183 shared,
184 stop,
185 handle: Some(handle),
186 rate,
187 })
188 }
189
190 pub fn rate(&self) -> u32 {
192 self.rate
193 }
194
195 pub fn set_stream(&self, place: usize, stream: Option<GroupStream>) -> io::Result<()> {
198 let input = match &stream {
199 Some(stream) => {
200 let media = Media::of(stream.format).ok_or_else(|| {
201 io::Error::new(
202 io::ErrorKind::Unsupported,
203 "not an AAF, AM824 or CRF format this talker sends",
204 )
205 })?;
206 if media.frame_samples_at(self.rate).is_none() {
207 return Err(io::Error::new(
208 io::ErrorKind::InvalidInput,
209 "a stream at another rate than its group's",
210 ));
211 }
212 if media.is_clock() {
213 None
214 } else {
215 Some(Input::open(&stream.source, stream.channels, self.rate)?)
216 }
217 }
218 None => None,
219 };
220 let mut streams = self.shared.lock();
221 let Some(slot) = streams.get_mut(place) else {
222 return Err(io::Error::new(io::ErrorKind::InvalidInput, "no such place"));
223 };
224 if let Some(waiting) = self
225 .shared
226 .inputs
227 .lock()
228 .unwrap_or_else(PoisonError::into_inner)
229 .get_mut(place)
230 {
231 *waiting = input;
232 }
233 *slot = stream;
234 self.shared.changes.fetch_add(1, Ordering::Relaxed);
235 Ok(())
236 }
237
238 pub fn set_destinations(&self, place: usize, destinations: Vec<MacAddress>) {
241 let mut streams = self.shared.lock();
242 if let Some(Some(stream)) = streams.get_mut(place) {
243 stream.destinations = destinations;
244 self.shared.changes.fetch_add(1, Ordering::Relaxed);
245 }
246 }
247
248 pub fn follow(&self, clock: Option<RecoveredClock>) {
253 let mut follow = self
254 .shared
255 .follow
256 .lock()
257 .unwrap_or_else(PoisonError::into_inner);
258 if *follow != clock {
259 *follow = clock;
260 self.shared.changes.fetch_add(1, Ordering::Relaxed);
261 }
262 }
263
264 pub fn sending(&self) -> bool {
266 self.shared.lock().iter().any(Option::is_some)
267 }
268
269 pub fn sends(&self, place: usize) -> bool {
271 self.shared.lock().get(place).is_some_and(Option::is_some)
272 }
273
274 pub fn stats(&self, place: usize) -> TalkerStats {
276 let read = |counter: &AtomicU64| counter.load(Ordering::Relaxed);
277 let group = &self.shared.group;
278 let (frames_sent, send_errors) =
279 self.shared.counters.get(place).map_or((0, 0), |counters| {
280 (read(&counters.frames_sent), read(&counters.send_errors))
281 });
282 TalkerStats {
283 frames_sent,
284 media_resets: read(&group.media_resets),
285 adjustments: read(&group.adjustments),
286 underruns: read(&group.underruns),
287 send_errors,
288 realtime: group.realtime.load(Ordering::Relaxed),
289 drift_ppm: group.drift_ppm.load(Ordering::Relaxed),
290 }
291 }
292
293 pub fn take_peaks(&self, place: usize) -> [f32; 2] {
297 self.shared
298 .counters
299 .get(place)
300 .map_or([0.0; 2], |counters| counters.peaks.take())
301 }
302}
303
304impl Drop for TalkerGroup {
305 fn drop(&mut self) {
306 self.stop.store(true, Ordering::Relaxed);
307 if let Some(handle) = self.handle.take() {
308 let _ = handle.join();
309 }
310 }
311}
312
313pub struct GroupTalker {
316 group: Arc<TalkerGroup>,
317 place: usize,
318}
319
320impl GroupTalker {
321 pub fn start(group: &Arc<TalkerGroup>, place: usize, stream: GroupStream) -> io::Result<Self> {
323 group.set_stream(place, Some(stream))?;
324 Ok(GroupTalker {
325 group: group.clone(),
326 place,
327 })
328 }
329
330 pub fn set_destinations(&self, destinations: Vec<MacAddress>) {
333 self.group.set_destinations(self.place, destinations);
334 }
335
336 pub fn stats(&self) -> TalkerStats {
337 self.group.stats(self.place)
338 }
339
340 pub fn take_peaks(&self) -> [f32; 2] {
343 self.group.take_peaks(self.place)
344 }
345}
346
347impl Drop for GroupTalker {
348 fn drop(&mut self) {
349 let _ = self.group.set_stream(self.place, None);
350 }
351}
352
353pub struct Talker {
355 group: TalkerGroup,
356}
357
358impl Talker {
359 pub fn start(config: TalkerConfig, clock: Arc<MediaClock>) -> io::Result<Self> {
361 let media = Media::of(config.format).ok_or_else(|| {
362 io::Error::new(
363 io::ErrorKind::Unsupported,
364 "not an AAF, AM824 or CRF format this talker sends",
365 )
366 })?;
367 let group = TalkerGroup::start(
368 GroupConfig {
369 interface: config.interface,
370 mac: config.mac,
371 rate: media.sample_rate(),
372 },
373 1,
374 clock,
375 )?;
376 group.set_stream(
377 0,
378 Some(GroupStream {
379 stream_id: config.stream_id,
380 destinations: config.destinations,
381 vlan_id: config.vlan_id,
382 priority: config.priority,
383 format: config.format,
384 max_transit_time: config.max_transit_time,
385 source: config.source,
386 channels: media.channels(),
387 }),
388 )?;
389 Ok(Talker { group })
390 }
391
392 pub fn set_destinations(&self, destinations: Vec<MacAddress>) {
395 self.group.set_destinations(0, destinations);
396 }
397
398 pub fn stats(&self) -> TalkerStats {
399 self.group.stats(0)
400 }
401}
402
403fn ethernet_header(mac: MacAddress, stream: &GroupStream) -> [u8; ETHERNET_LEN] {
405 let mut header = [0; ETHERNET_LEN];
406 header[..6].copy_from_slice(&stream.destinations.first().map_or([0; 6], |mac| mac.0));
407 header[6..12].copy_from_slice(&mac.0);
408 header[12..14].copy_from_slice(ÐERTYPE_VLAN.to_be_bytes());
409 let tag = (u16::from(stream.priority & 0x7) << 13) | (stream.vlan_id & 0x0fff);
410 header[14..16].copy_from_slice(&tag.to_be_bytes());
411 header[16..18].copy_from_slice(ÐERTYPE_AVTP.to_be_bytes());
412 header
413}
414
415struct Running {
417 stream: GroupStream,
418 input: Option<Input>,
420 packetizer: Packetizer,
421 frame: Vec<u8>,
422 samples: Vec<f32>,
423 channels: usize,
425 frame_samples: u64,
427 next: u64,
429}
430
431impl Running {
432 fn new(
433 mac: MacAddress,
434 stream: GroupStream,
435 media: Media,
436 input: Option<Input>,
437 frame_samples: u64,
438 ) -> Self {
439 let mut frame = vec![0u8; ETHERNET_LEN + media.pdu_length()];
440 frame[..ETHERNET_LEN].copy_from_slice(ðernet_header(mac, &stream));
441 let samples =
442 vec![0.0f32; usize::from(media.channels()) * usize::from(media.samples_per_frame())];
443 Running {
444 packetizer: Packetizer::new(media, stream.stream_id),
445 stream,
446 input,
447 frame,
448 samples,
449 channels: usize::from(media.channels()),
450 frame_samples: frame_samples.max(1),
451 next: 0,
452 }
453 }
454
455 fn frame_samples(&self) -> u64 {
456 self.frame_samples
457 }
458
459 fn first_from(&self, from: u64) -> u64 {
461 from.div_ceil(self.frame_samples()) * self.frame_samples()
462 }
463}
464
465struct Timeline {
468 rate: u64,
469 origin: i64,
470 follow: Option<Following>,
472 wanted: Option<Fit>,
475}
476
477#[derive(Debug, Clone, Copy)]
480struct Following {
481 fit: Fit,
482 sample: u64,
483 sub: i128,
484 base: i128,
485}
486
487impl Timeline {
488 fn at(&self, sample: u64) -> i64 {
489 match &self.follow {
490 Some(following) => {
491 let samples = i128::from(sample) - i128::from(following.sample);
492 following
493 .fit
494 .time_at(following.sub + samples * following.base, self.rate)
495 }
496 None => self.origin + (u128::from(sample) * NANOS / u128::from(self.rate)) as i64,
497 }
498 }
499
500 fn sample_at(&self, time: i64) -> u64 {
502 match &self.follow {
503 Some(following) => {
504 let sub = following.fit.sub_at(time, self.rate);
505 let samples = div_ceil(sub - following.sub, following.base);
506 (i128::from(following.sample) + samples).max(0) as u64
507 }
508 None => {
509 let since = (time - self.origin).max(0);
510 (since as u128 * u128::from(self.rate)).div_ceil(NANOS) as u64
511 }
512 }
513 }
514
515 fn take(&mut self, fit: Option<Fit>) -> bool {
519 self.wanted = fit;
520 match (fit, self.follow.as_mut()) {
521 (Some(fit), Some(following)) if following.fit.generation == fit.generation => {
522 following.fit = fit;
523 false
524 }
525 (None, None) => false,
526 _ => true,
527 }
528 }
529
530 fn restart(&mut self, from: u64, now: i64) -> u64 {
535 let first = from.div_ceil(ALIGN) * ALIGN;
536 let boundary = (now / 1_000_000 + 2) * 1_000_000;
537 match self.wanted {
538 Some(fit) => {
539 let rate = i128::from(self.rate);
540 let edge = div_ceil(fit.sub_at(boundary, self.rate), rate) * rate;
541 self.follow = Some(Following {
542 fit,
543 sample: first,
544 sub: edge,
545 base: i128::from(fit.base_frequency),
546 });
547 }
548 None => {
549 self.follow = None;
550 self.origin = boundary - (u128::from(first) * NANOS / u128::from(self.rate)) as i64;
551 }
552 }
553 first
554 }
555}
556
557fn take_changes(
561 config: &GroupConfig,
562 shared: &Shared,
563 running: &mut [Option<Running>],
564 timeline: &mut Timeline,
565 clock: &MediaClock,
566) {
567 let wanted = shared.lock().clone();
568 let mut inputs = shared.inputs.lock().unwrap_or_else(PoisonError::into_inner);
569 let idle = running.iter().all(Option::is_none);
570 let mut from = None;
571 for (place, wanted) in wanted.into_iter().enumerate() {
572 let Some(slot) = running.get_mut(place) else {
573 continue;
574 };
575 match (wanted, slot.as_mut()) {
576 (None, _) => *slot = None,
577 (Some(stream), Some(now)) if same_but_destinations(&stream, &now.stream) => {
578 if stream.destinations != now.stream.destinations {
579 now.frame[..ETHERNET_LEN]
580 .copy_from_slice(ðernet_header(config.mac, &stream));
581 now.stream.destinations = stream.destinations;
582 }
583 }
584 (Some(stream), _) => {
585 let input = inputs.get_mut(place).and_then(Option::take);
586 let Some((media, frame_samples)) = Media::of(stream.format)
587 .and_then(|media| Some((media, media.frame_samples_at(config.rate)?)))
588 else {
589 *slot = None;
590 continue;
591 };
592 if input.is_none() && !media.is_clock() {
594 *slot = None;
595 continue;
596 }
597 let start = *from.get_or_insert_with(|| {
599 let now = clock.now();
600 if idle {
601 timeline.restart(timeline.sample_at(now), now)
602 } else {
603 timeline.sample_at(now + 1_000_000)
604 }
605 });
606 let mut made = Running::new(config.mac, stream, media, input, frame_samples);
607 made.next = made.first_from(start);
608 *slot = Some(made);
609 }
610 }
611 }
612}
613
614fn same_but_destinations(one: &GroupStream, other: &GroupStream) -> bool {
616 GroupStream {
617 destinations: Vec::new(),
618 ..one.clone()
619 } == GroupStream {
620 destinations: Vec::new(),
621 ..other.clone()
622 }
623}
624
625fn run(
626 config: &GroupConfig,
627 shared: &Shared,
628 sender: &FrameSender,
629 clock: &MediaClock,
630 stop: &AtomicBool,
631) {
632 precise_sleeps();
633 shared
634 .group
635 .realtime
636 .store(crate::realtime::raise(), Ordering::Relaxed);
637 let mut running: Vec<Option<Running>> = (0..shared.counters.len()).map(|_| None).collect();
638 let mut timeline = Timeline {
639 rate: u64::from(config.rate.max(1)),
640 origin: 0,
641 follow: None,
642 wanted: None,
643 };
644 let mut seen = u64::MAX;
645 let mut media_reset = false;
646 let mut frames: u64 = 0;
647 let mut follow: Option<RecoveredClock> = None;
648 let mut switched = false;
649 while !stop.load(Ordering::Relaxed) {
650 let changes = shared.changes.load(Ordering::Relaxed);
651 if changes != seen {
652 seen = changes;
653 let wanted = shared
654 .follow
655 .lock()
656 .unwrap_or_else(PoisonError::into_inner)
657 .clone();
658 if wanted != follow {
661 follow = wanted;
662 switched = timeline.follow.take().is_some();
663 }
664 timeline.take(follow.as_ref().and_then(RecoveredClock::fit));
665 take_changes(config, shared, &mut running, &mut timeline, clock);
666 }
667 let retime = timeline.take(follow.as_ref().and_then(RecoveredClock::fit));
671 if (retime || std::mem::take(&mut switched)) && running.iter().any(Option::is_some) {
672 restart(&mut running, &mut timeline, clock);
673 media_reset = !media_reset;
674 shared.group.media_resets.fetch_add(1, Ordering::Relaxed);
675 }
676 let Some((place, due)) = running
678 .iter()
679 .enumerate()
680 .filter_map(|(place, stream)| {
681 stream
682 .as_ref()
683 .map(|stream| (place, timeline.at(stream.next)))
684 })
685 .min_by_key(|(_, due)| *due)
686 else {
687 std::thread::sleep(LONGEST_SLEEP);
688 continue;
689 };
690 let wake = clock.monotonic_at(due);
691 let now = monotonic_now();
692 if wake > now {
693 let wait = wake - now;
694 std::thread::sleep(wait.min(LONGEST_SLEEP));
695 if wait > LONGEST_SLEEP {
696 if due - clock.now() > 2 * LONGEST_SLEEP.as_nanos() as i64 {
699 restart(&mut running, &mut timeline, clock);
700 media_reset = !media_reset;
701 shared.group.media_resets.fetch_add(1, Ordering::Relaxed);
702 }
703 continue;
704 }
705 }
706 let Some(stream) = running[place].as_mut() else {
707 continue;
708 };
709 let transit = stream.stream.max_transit_time.as_nanos() as i64;
712 let late = clock.now() - due;
713 if late > (transit - CROSSING).max(transit / 2) {
714 restart(&mut running, &mut timeline, clock);
717 media_reset = !media_reset;
718 shared.group.media_resets.fetch_add(1, Ordering::Relaxed);
719 continue;
720 }
721 if let Some(input) = &mut stream.input {
722 input.read_as(&mut stream.samples, stream.channels);
723 }
724 let counters = &shared.counters[place];
725 counters.peaks.raise(&stream.samples, stream.channels);
726 stream.packetizer.write(
727 due + transit,
728 media_reset,
729 &stream.samples,
730 &mut stream.frame[ETHERNET_LEN..],
731 );
732 for destination in &stream.stream.destinations {
733 stream.frame[..6].copy_from_slice(&destination.0);
734 match sender.send(&stream.frame) {
735 Ok(()) => counters.frames_sent.fetch_add(1, Ordering::Relaxed),
736 Err(_) => counters.send_errors.fetch_add(1, Ordering::Relaxed),
737 };
738 }
739 stream.next += stream.frame_samples();
740 frames += 1;
741 if frames.is_multiple_of(800) {
742 let (mut made, mut empty, mut drift) = (0, 0, 0);
745 for input in running
746 .iter()
747 .flatten()
748 .filter_map(|stream| stream.input.as_ref())
749 {
750 let (adjusted, short) = input.counts();
751 made += adjusted;
752 empty += short;
753 if drift == 0 {
754 drift = input.drift_ppm();
755 }
756 }
757 shared.group.adjustments.store(made, Ordering::Relaxed);
758 shared.group.drift_ppm.store(drift, Ordering::Relaxed);
759 shared.group.underruns.store(empty, Ordering::Relaxed);
760 }
761 }
762}
763
764fn restart(running: &mut [Option<Running>], timeline: &mut Timeline, clock: &MediaClock) {
766 let now = clock.now();
767 let first = timeline.restart(timeline.sample_at(now), now);
768 for stream in running.iter_mut().flatten() {
769 stream.next = stream.first_from(first);
770 }
771}
772
773#[cfg(test)]
774mod tests {
775 use super::*;
776
777 #[test]
780 fn the_timeline_counts_samples_on_gptp_time() {
781 let mut timeline = Timeline {
782 rate: 48_000,
783 origin: 0,
784 follow: None,
785 wanted: None,
786 };
787 let first = timeline.restart(5, 7_400_000);
788 assert_eq!(first, 48);
789 assert_eq!(timeline.at(first), 9_000_000);
790 assert_eq!(timeline.at(first + 6) - timeline.at(first), 125_000);
791 assert_eq!(timeline.at(first + 12) - timeline.at(first), 250_000);
792 assert_eq!(timeline.sample_at(timeline.at(first + 6)), first + 6);
793 assert_eq!(timeline.sample_at(timeline.at(first) + 1), first + 1);
795 }
796
797 #[test]
802 fn the_timeline_follows_a_media_clock() {
803 let period = (1e9 / 48_000.0 / (1.0 + 50e-6) * 4_294_967_296.0) as u64;
805 let fit = Fit {
806 generation: 3,
807 event: 960_000,
808 time: 21_000_000_000,
809 period,
810 base_frequency: 48_000,
811 };
812 let mut timeline = Timeline {
813 rate: 192_000,
814 origin: 0,
815 follow: None,
816 wanted: None,
817 };
818 assert!(timeline.take(Some(fit)), "a clock to follow starts again");
819 let first = timeline.restart(1000, 21_000_000_000);
820 assert_eq!(first, 1008);
821 let start = timeline.at(first);
822 assert!(start >= 21_002_000_000, "{start}");
823 let events = fit.sub_at(start, 1) - i128::from(fit.event);
825 assert_eq!(fit.time_at(i128::from(fit.event) + events, 1), start);
826 let second = timeline.at(first + 192_000) - start;
828 assert!((second - 999_950_002).abs() <= 2, "{second}");
829 assert_eq!(
830 timeline.at(first + 4) - start,
831 fit.time_at(i128::from(fit.event) + events + 1, 1) - start
832 );
833 assert_eq!(timeline.sample_at(timeline.at(first + 7)), first + 7);
834 let later = Fit {
836 event: fit.event + 96,
837 time: fit.time_at(i128::from(fit.event) + 96, 1),
838 ..fit
839 };
840 assert!(!timeline.take(Some(later)));
841 assert_eq!(timeline.at(first + 192_000) - start, second);
842 assert!(timeline.take(Some(Fit {
844 generation: 4,
845 ..later
846 })));
847 assert!(timeline.take(None));
848 timeline.restart(first + 192_000, 22_500_000_000);
849 assert!(timeline.follow.is_none());
850 assert!(!timeline.take(None));
851 }
852}