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 late_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 send_errors: AtomicU64,
124 peaks: Peaks,
125}
126
127#[derive(Default)]
129struct GroupCounters {
130 media_resets: AtomicU64,
131 late_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, send_errors) =
287 self.shared.counters.get(place).map_or((0, 0), |counters| {
288 (read(&counters.frames_sent), read(&counters.send_errors))
289 });
290 TalkerStats {
291 frames_sent,
292 media_resets: read(&group.media_resets),
293 late_resets: read(&group.late_resets),
294 clock_resets: read(&group.clock_resets),
295 adjustments: read(&group.adjustments),
296 underruns: read(&group.underruns),
297 send_errors,
298 realtime: group.realtime.load(Ordering::Relaxed),
299 drift_ppm: group.drift_ppm.load(Ordering::Relaxed),
300 }
301 }
302
303 pub fn take_peaks(&self, place: usize) -> [f32; 2] {
307 self.shared
308 .counters
309 .get(place)
310 .map_or([0.0; 2], |counters| counters.peaks.take())
311 }
312}
313
314impl Drop for TalkerGroup {
315 fn drop(&mut self) {
316 self.stop.store(true, Ordering::Relaxed);
317 if let Some(handle) = self.handle.take() {
318 let _ = handle.join();
319 }
320 }
321}
322
323pub struct GroupTalker {
326 group: Arc<TalkerGroup>,
327 place: usize,
328}
329
330impl GroupTalker {
331 pub fn start(group: &Arc<TalkerGroup>, place: usize, stream: GroupStream) -> io::Result<Self> {
333 group.set_stream(place, Some(stream))?;
334 Ok(GroupTalker {
335 group: group.clone(),
336 place,
337 })
338 }
339
340 pub fn set_destinations(&self, destinations: Vec<MacAddress>) {
343 self.group.set_destinations(self.place, destinations);
344 }
345
346 pub fn stats(&self) -> TalkerStats {
347 self.group.stats(self.place)
348 }
349
350 pub fn take_peaks(&self) -> [f32; 2] {
353 self.group.take_peaks(self.place)
354 }
355}
356
357impl Drop for GroupTalker {
358 fn drop(&mut self) {
359 let _ = self.group.set_stream(self.place, None);
360 }
361}
362
363pub struct Talker {
365 group: TalkerGroup,
366}
367
368impl Talker {
369 pub fn start(config: TalkerConfig, clock: Arc<MediaClock>) -> io::Result<Self> {
371 let media = Media::of(config.format).ok_or_else(|| {
372 io::Error::new(
373 io::ErrorKind::Unsupported,
374 "not an AAF, AM824 or CRF format this talker sends",
375 )
376 })?;
377 let group = TalkerGroup::start(
378 GroupConfig {
379 interface: config.interface,
380 mac: config.mac,
381 rate: media.sample_rate(),
382 },
383 1,
384 clock,
385 )?;
386 group.set_stream(
387 0,
388 Some(GroupStream {
389 stream_id: config.stream_id,
390 destinations: config.destinations,
391 vlan_id: config.vlan_id,
392 priority: config.priority,
393 format: config.format,
394 max_transit_time: config.max_transit_time,
395 source: config.source,
396 channels: media.channels(),
397 }),
398 )?;
399 Ok(Talker { group })
400 }
401
402 pub fn set_destinations(&self, destinations: Vec<MacAddress>) {
405 self.group.set_destinations(0, destinations);
406 }
407
408 pub fn stats(&self) -> TalkerStats {
409 self.group.stats(0)
410 }
411}
412
413fn ethernet_header(mac: MacAddress, stream: &GroupStream) -> [u8; ETHERNET_LEN] {
415 let mut header = [0; ETHERNET_LEN];
416 header[..6].copy_from_slice(&stream.destinations.first().map_or([0; 6], |mac| mac.0));
417 header[6..12].copy_from_slice(&mac.0);
418 header[12..14].copy_from_slice(ÐERTYPE_VLAN.to_be_bytes());
419 let tag = (u16::from(stream.priority & 0x7) << 13) | (stream.vlan_id & 0x0fff);
420 header[14..16].copy_from_slice(&tag.to_be_bytes());
421 header[16..18].copy_from_slice(ÐERTYPE_AVTP.to_be_bytes());
422 header
423}
424
425struct Running {
427 stream: GroupStream,
428 input: Option<Input>,
430 packetizer: Packetizer,
431 frame: Vec<u8>,
432 samples: Vec<f32>,
433 channels: usize,
435 frame_samples: u64,
437 next: u64,
439}
440
441impl Running {
442 fn new(
443 mac: MacAddress,
444 stream: GroupStream,
445 media: Media,
446 input: Option<Input>,
447 frame_samples: u64,
448 ) -> Self {
449 let mut frame = vec![0u8; ETHERNET_LEN + media.pdu_length()];
450 frame[..ETHERNET_LEN].copy_from_slice(ðernet_header(mac, &stream));
451 let samples =
452 vec![0.0f32; usize::from(media.channels()) * usize::from(media.samples_per_frame())];
453 Running {
454 packetizer: Packetizer::new(media, stream.stream_id),
455 stream,
456 input,
457 frame,
458 samples,
459 channels: usize::from(media.channels()),
460 frame_samples: frame_samples.max(1),
461 next: 0,
462 }
463 }
464
465 fn frame_samples(&self) -> u64 {
466 self.frame_samples
467 }
468
469 fn first_from(&self, from: u64) -> u64 {
471 from.div_ceil(self.frame_samples()) * self.frame_samples()
472 }
473}
474
475struct Timeline {
478 rate: u64,
479 origin: i64,
480 follow: Option<Following>,
482 wanted: Option<Fit>,
485}
486
487#[derive(Debug, Clone, Copy)]
490struct Following {
491 fit: Fit,
492 sample: u64,
493 sub: i128,
494 base: i128,
495}
496
497impl Timeline {
498 fn at(&self, sample: u64) -> i64 {
499 match &self.follow {
500 Some(following) => {
501 let samples = i128::from(sample) - i128::from(following.sample);
502 following
503 .fit
504 .time_at(following.sub + samples * following.base, self.rate)
505 }
506 None => self.origin + (u128::from(sample) * NANOS / u128::from(self.rate)) as i64,
507 }
508 }
509
510 fn sample_at(&self, time: i64) -> u64 {
512 match &self.follow {
513 Some(following) => {
514 let sub = following.fit.sub_at(time, self.rate);
515 let samples = div_ceil(sub - following.sub, following.base);
516 (i128::from(following.sample) + samples).max(0) as u64
517 }
518 None => {
519 let since = (time - self.origin).max(0);
520 (since as u128 * u128::from(self.rate)).div_ceil(NANOS) as u64
521 }
522 }
523 }
524
525 fn take(&mut self, fit: Option<Fit>) -> bool {
529 self.wanted = fit;
530 match (fit, self.follow.as_mut()) {
531 (Some(fit), Some(following)) if following.fit.generation == fit.generation => {
532 following.fit = fit;
533 false
534 }
535 (None, None) => false,
536 _ => true,
537 }
538 }
539
540 fn restart(&mut self, from: u64, now: i64) -> u64 {
545 let first = from.div_ceil(ALIGN) * ALIGN;
546 let boundary = (now / 1_000_000 + 2) * 1_000_000;
547 match self.wanted {
548 Some(fit) => {
549 let rate = i128::from(self.rate);
550 let edge = div_ceil(fit.sub_at(boundary, self.rate), rate) * rate;
551 self.follow = Some(Following {
552 fit,
553 sample: first,
554 sub: edge,
555 base: i128::from(fit.base_frequency),
556 });
557 }
558 None => {
559 self.follow = None;
560 self.origin = boundary - (u128::from(first) * NANOS / u128::from(self.rate)) as i64;
561 }
562 }
563 first
564 }
565}
566
567fn take_changes(
571 config: &GroupConfig,
572 shared: &Shared,
573 running: &mut [Option<Running>],
574 timeline: &mut Timeline,
575 clock: &MediaClock,
576) {
577 let wanted = shared.lock().clone();
578 let mut inputs = shared.inputs.lock().unwrap_or_else(PoisonError::into_inner);
579 let idle = running.iter().all(Option::is_none);
580 let mut from = None;
581 for (place, wanted) in wanted.into_iter().enumerate() {
582 let Some(slot) = running.get_mut(place) else {
583 continue;
584 };
585 match (wanted, slot.as_mut()) {
586 (None, _) => *slot = None,
587 (Some(stream), Some(now)) if same_but_destinations(&stream, &now.stream) => {
588 if stream.destinations != now.stream.destinations {
589 now.frame[..ETHERNET_LEN]
590 .copy_from_slice(ðernet_header(config.mac, &stream));
591 now.stream.destinations = stream.destinations;
592 }
593 }
594 (Some(stream), _) => {
595 let input = inputs.get_mut(place).and_then(Option::take);
596 let Some((media, frame_samples)) = Media::of(stream.format)
597 .and_then(|media| Some((media, media.frame_samples_at(config.rate)?)))
598 else {
599 *slot = None;
600 continue;
601 };
602 if input.is_none() && !media.is_clock() {
604 *slot = None;
605 continue;
606 }
607 let start = *from.get_or_insert_with(|| {
609 let now = clock.now();
610 if idle {
611 timeline.restart(timeline.sample_at(now), now)
612 } else {
613 timeline.sample_at(now + 1_000_000)
614 }
615 });
616 let mut made = Running::new(config.mac, stream, media, input, frame_samples);
617 made.next = made.first_from(start);
618 *slot = Some(made);
619 }
620 }
621 }
622}
623
624fn same_but_destinations(one: &GroupStream, other: &GroupStream) -> bool {
626 GroupStream {
627 destinations: Vec::new(),
628 ..one.clone()
629 } == GroupStream {
630 destinations: Vec::new(),
631 ..other.clone()
632 }
633}
634
635fn run(
636 config: &GroupConfig,
637 shared: &Shared,
638 sender: &FrameSender,
639 clock: &MediaClock,
640 stop: &AtomicBool,
641) {
642 precise_sleeps();
643 shared
644 .group
645 .realtime
646 .store(crate::realtime::raise(), Ordering::Relaxed);
647 let mut running: Vec<Option<Running>> = (0..shared.counters.len()).map(|_| None).collect();
648 let mut timeline = Timeline {
649 rate: u64::from(config.rate.max(1)),
650 origin: 0,
651 follow: None,
652 wanted: None,
653 };
654 let mut seen = u64::MAX;
655 let mut media_reset = false;
656 let mut frames: u64 = 0;
657 let mut follow: Option<RecoveredClock> = None;
658 let mut switched = false;
659 let mut generation = clock.generation();
660 while !stop.load(Ordering::Relaxed) {
661 let changes = shared.changes.load(Ordering::Relaxed);
662 if changes != seen {
663 seen = changes;
664 let wanted = shared
665 .follow
666 .lock()
667 .unwrap_or_else(PoisonError::into_inner)
668 .clone();
669 if wanted != follow {
672 follow = wanted;
673 switched = timeline.follow.take().is_some();
674 }
675 timeline.take(follow.as_ref().and_then(RecoveredClock::fit));
676 take_changes(config, shared, &mut running, &mut timeline, clock);
677 }
678 let retime = timeline.take(follow.as_ref().and_then(RecoveredClock::fit));
682 let jumped = clock.generation() != generation;
685 generation = clock.generation();
686 if (retime || jumped || std::mem::take(&mut switched))
687 && running.iter().any(Option::is_some)
688 {
689 restart(&mut running, &mut timeline, clock);
690 media_reset = !media_reset;
691 shared.group.media_resets.fetch_add(1, Ordering::Relaxed);
692 if jumped {
693 shared.group.clock_resets.fetch_add(1, Ordering::Relaxed);
694 }
695 }
696 let Some((place, due)) = running
698 .iter()
699 .enumerate()
700 .filter_map(|(place, stream)| {
701 stream
702 .as_ref()
703 .map(|stream| (place, timeline.at(stream.next)))
704 })
705 .min_by_key(|(_, due)| *due)
706 else {
707 std::thread::sleep(LONGEST_SLEEP);
708 continue;
709 };
710 let wake = clock.monotonic_at(due);
711 let now = monotonic_now();
712 if wake > now {
713 let wait = wake - now;
714 std::thread::sleep(wait.min(LONGEST_SLEEP));
715 if wait > LONGEST_SLEEP {
716 if due - clock.now() > 2 * LONGEST_SLEEP.as_nanos() as i64 {
719 restart(&mut running, &mut timeline, clock);
720 media_reset = !media_reset;
721 shared.group.media_resets.fetch_add(1, Ordering::Relaxed);
722 shared.group.clock_resets.fetch_add(1, Ordering::Relaxed);
723 }
724 continue;
725 }
726 }
727 let Some(stream) = running[place].as_mut() else {
728 continue;
729 };
730 let transit = stream.stream.max_transit_time.as_nanos() as i64;
733 let late = clock.now() - due;
734 if late > (transit - CROSSING).max(transit / 2) {
735 restart(&mut running, &mut timeline, clock);
738 media_reset = !media_reset;
739 shared.group.media_resets.fetch_add(1, Ordering::Relaxed);
740 shared.group.late_resets.fetch_add(1, Ordering::Relaxed);
741 continue;
742 }
743 if let Some(input) = &mut stream.input {
744 input.read_as(&mut stream.samples, stream.channels);
745 }
746 let counters = &shared.counters[place];
747 counters.peaks.raise(&stream.samples, stream.channels);
748 stream.packetizer.write(
749 due + transit,
750 media_reset,
751 &stream.samples,
752 &mut stream.frame[ETHERNET_LEN..],
753 );
754 for destination in &stream.stream.destinations {
755 stream.frame[..6].copy_from_slice(&destination.0);
756 match sender.send(&stream.frame) {
757 Ok(()) => counters.frames_sent.fetch_add(1, Ordering::Relaxed),
758 Err(_) => counters.send_errors.fetch_add(1, Ordering::Relaxed),
759 };
760 }
761 stream.next += stream.frame_samples();
762 frames += 1;
763 if frames.is_multiple_of(800) {
764 let (mut made, mut empty, mut drift) = (0, 0, 0);
767 for input in running
768 .iter()
769 .flatten()
770 .filter_map(|stream| stream.input.as_ref())
771 {
772 let (adjusted, short) = input.counts();
773 made += adjusted;
774 empty += short;
775 if drift == 0 {
776 drift = input.drift_ppm();
777 }
778 }
779 shared.group.adjustments.store(made, Ordering::Relaxed);
780 shared.group.drift_ppm.store(drift, Ordering::Relaxed);
781 shared.group.underruns.store(empty, Ordering::Relaxed);
782 }
783 }
784}
785
786fn restart(running: &mut [Option<Running>], timeline: &mut Timeline, clock: &MediaClock) {
788 let now = clock.now();
789 let first = timeline.restart(timeline.sample_at(now), now);
790 for stream in running.iter_mut().flatten() {
791 stream.next = stream.first_from(first);
792 }
793}
794
795#[cfg(test)]
796mod tests {
797 use super::*;
798
799 #[test]
802 fn the_timeline_counts_samples_on_gptp_time() {
803 let mut timeline = Timeline {
804 rate: 48_000,
805 origin: 0,
806 follow: None,
807 wanted: None,
808 };
809 let first = timeline.restart(5, 7_400_000);
810 assert_eq!(first, 48);
811 assert_eq!(timeline.at(first), 9_000_000);
812 assert_eq!(timeline.at(first + 6) - timeline.at(first), 125_000);
813 assert_eq!(timeline.at(first + 12) - timeline.at(first), 250_000);
814 assert_eq!(timeline.sample_at(timeline.at(first + 6)), first + 6);
815 assert_eq!(timeline.sample_at(timeline.at(first) + 1), first + 1);
817 }
818
819 #[test]
824 fn the_timeline_follows_a_media_clock() {
825 let period = (1e9 / 48_000.0 / (1.0 + 50e-6) * 4_294_967_296.0) as u64;
827 let fit = Fit {
828 generation: 3,
829 event: 960_000,
830 time: 21_000_000_000,
831 period,
832 base_frequency: 48_000,
833 };
834 let mut timeline = Timeline {
835 rate: 192_000,
836 origin: 0,
837 follow: None,
838 wanted: None,
839 };
840 assert!(timeline.take(Some(fit)), "a clock to follow starts again");
841 let first = timeline.restart(1000, 21_000_000_000);
842 assert_eq!(first, 1008);
843 let start = timeline.at(first);
844 assert!(start >= 21_002_000_000, "{start}");
845 let events = fit.sub_at(start, 1) - i128::from(fit.event);
847 assert_eq!(fit.time_at(i128::from(fit.event) + events, 1), start);
848 let second = timeline.at(first + 192_000) - start;
850 assert!((second - 999_950_002).abs() <= 2, "{second}");
851 assert_eq!(
852 timeline.at(first + 4) - start,
853 fit.time_at(i128::from(fit.event) + events + 1, 1) - start
854 );
855 assert_eq!(timeline.sample_at(timeline.at(first + 7)), first + 7);
856 let later = Fit {
858 event: fit.event + 96,
859 time: fit.time_at(i128::from(fit.event) + 96, 1),
860 ..fit
861 };
862 assert!(!timeline.take(Some(later)));
863 assert_eq!(timeline.at(first + 192_000) - start, second);
864 assert!(timeline.take(Some(Fit {
866 generation: 4,
867 ..later
868 })));
869 assert!(timeline.take(None));
870 timeline.restart(first + 192_000, 22_500_000_000);
871 assert!(timeline.follow.is_none());
872 assert!(!timeline.take(None));
873 }
874}