1use std::io;
29use std::sync::Arc;
30use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering};
31use std::thread::JoinHandle;
32use std::time::Duration;
33
34use atdecc::stream_format::StreamFormat;
35use avb_net::MacAddress;
36use avb_net::clock::{monotonic_now, precise_sleeps};
37use avb_net::stream::FrameSender;
38
39use crate::MediaClock;
40use crate::audio::{Block, BlockSource, Input, Source};
41use crate::lock::{Guard, Lock};
42use crate::media::{Media, Packetizer};
43use crate::meter::Peaks;
44use crate::recovered::{Fit, RecoveredClock, div_ceil};
45use crate::timing::Timing;
46
47const ETHERTYPE_VLAN: u16 = 0x8100;
49const ETHERTYPE_AVTP: u16 = 0x22f0;
50const ETHERNET_LEN: usize = 18;
52const CROSSING: i64 = 500_000;
56pub const LAUNCH_AHEAD: Duration = Duration::from_millis(2);
59const LATE_STAMP: Duration = Duration::from_micros(20);
64pub const CARD_AHEAD: Duration = Duration::from_millis(1);
69const CARD_LATE: u64 = 200_000;
73const LONGEST_SLEEP: Duration = Duration::from_millis(20);
76const ALIGN: u64 = 48;
80const NANOS: u128 = 1_000_000_000;
81
82#[derive(Debug, Clone, PartialEq)]
84pub struct TalkerConfig {
85 pub interface: String,
86 pub mac: MacAddress,
88 pub stream_id: u64,
89 pub destinations: Vec<MacAddress>,
93 pub vlan_id: u16,
94 pub priority: u8,
95 pub format: StreamFormat,
96 pub max_transit_time: Duration,
98 pub source: Source,
99}
100
101#[derive(Debug, Clone, PartialEq)]
103pub struct GroupConfig {
104 pub interface: String,
105 pub mac: MacAddress,
107 pub rate: u32,
108}
109
110#[derive(Debug, Clone, PartialEq)]
112pub struct GroupStream {
113 pub stream_id: u64,
114 pub destinations: Vec<MacAddress>,
117 pub vlan_id: u16,
118 pub priority: u8,
119 pub format: StreamFormat,
121 pub max_transit_time: Duration,
123 pub source: Source,
125 pub channels: u16,
128}
129
130#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
132pub struct TalkerStats {
133 pub frames_sent: u64,
134 pub frames_late: u64,
137 pub media_resets: u64,
139 pub clock_resets: u64,
142 pub adjustments: u64,
145 pub underruns: u64,
146 pub send_errors: u64,
148 pub realtime: bool,
150 pub drift_ppm: i32,
153 pub launching: bool,
156 pub launches_missed: u64,
159}
160
161#[derive(Default)]
163struct StreamCounters {
164 frames_sent: AtomicU64,
165 frames_late: AtomicU64,
166 send_errors: AtomicU64,
167 peaks: Peaks,
168}
169
170#[derive(Default)]
172struct GroupCounters {
173 media_resets: AtomicU64,
174 clock_resets: AtomicU64,
175 adjustments: AtomicU64,
176 underruns: AtomicU64,
177 realtime: AtomicBool,
178 drift_ppm: AtomicI32,
179 launching: AtomicBool,
180 launches_missed: AtomicU64,
181}
182
183struct Shared {
185 streams: Lock<Vec<Option<GroupStream>>>,
188 changes: AtomicU64,
189 inputs: Lock<Vec<Option<Input>>>,
192 follow: Lock<Option<RecoveredClock>>,
194 counters: Vec<StreamCounters>,
195 group: GroupCounters,
196}
197
198impl Shared {
199 fn lock(&self) -> Guard<'_, Vec<Option<GroupStream>>> {
200 self.streams.lock()
201 }
202}
203
204pub struct TalkerGroup {
206 shared: Arc<Shared>,
207 stop: Arc<AtomicBool>,
208 handle: Option<JoinHandle<()>>,
209 rate: u32,
210 ahead: Option<Duration>,
211 card: bool,
212}
213
214impl TalkerGroup {
215 pub fn start(config: GroupConfig, places: usize, clock: Arc<MediaClock>) -> io::Result<Self> {
218 Self::start_ahead(config, places, clock, None)
219 }
220
221 pub fn start_ahead(
224 config: GroupConfig,
225 places: usize,
226 clock: Arc<MediaClock>,
227 ahead: Option<Duration>,
228 ) -> io::Result<Self> {
229 let sender = FrameSender::open(&config.interface)?;
230 Self::start_with(config, places, clock, sender, ahead, false)
231 }
232
233 pub fn start_on_card(
239 config: GroupConfig,
240 places: usize,
241 clock: Arc<MediaClock>,
242 ) -> io::Result<Self> {
243 match FrameSender::open_for_card(&config.interface) {
244 Ok(sender) => Self::start_with(config, places, clock, sender, None, true),
245 Err(_) => Self::start(config, places, clock),
246 }
247 }
248
249 fn start_with(
250 config: GroupConfig,
251 places: usize,
252 clock: Arc<MediaClock>,
253 sender: FrameSender,
254 ahead: Option<Duration>,
255 card: bool,
256 ) -> io::Result<Self> {
257 let room = ahead.and_then(|_| avb_net::stream::paced_frames(&config.interface));
260 let ahead = ahead.filter(|_| room.is_some() && sender.time_departures().is_ok());
261 let launch = ahead.map(|ahead| (ahead, room.unwrap_or(u32::MAX)));
262 let stop = Arc::new(AtomicBool::new(false));
263 let shared = Arc::new(Shared {
264 streams: Lock::new(vec![None; places]),
265 changes: AtomicU64::new(0),
266 inputs: Lock::new((0..places).map(|_| None).collect()),
267 follow: Lock::new(None),
268 counters: (0..places).map(|_| StreamCounters::default()).collect(),
269 group: GroupCounters::default(),
270 });
271 let rate = config.rate;
272 let handle = {
273 let stop = stop.clone();
274 let shared = shared.clone();
275 std::thread::Builder::new()
276 .name("talker".into())
277 .spawn(move || run(&config, &shared, &sender, &clock, launch, card, &stop))?
278 };
279 Ok(TalkerGroup {
280 shared,
281 stop,
282 handle: Some(handle),
283 rate,
284 ahead,
285 card,
286 })
287 }
288
289 pub fn rate(&self) -> u32 {
291 self.rate
292 }
293
294 pub fn launch_ahead(&self) -> Option<Duration> {
297 self.ahead
298 }
299
300 pub fn on_card(&self) -> bool {
304 self.card
305 }
306
307 pub fn set_stream(&self, place: usize, stream: Option<GroupStream>) -> io::Result<()> {
310 let input = match &stream {
311 Some(stream) => {
312 let media = Media::of(stream.format).ok_or_else(|| {
313 io::Error::new(
314 io::ErrorKind::Unsupported,
315 "not an AAF, AM824 or CRF format this talker sends",
316 )
317 })?;
318 if media.frame_samples_at(self.rate).is_none() {
319 return Err(io::Error::new(
320 io::ErrorKind::InvalidInput,
321 "a stream at another rate than its group's",
322 ));
323 }
324 if media.is_clock() {
325 None
326 } else {
327 Some(Input::open(&stream.source, stream.channels, self.rate)?)
328 }
329 }
330 None => None,
331 };
332 let mut streams = self.shared.lock();
333 let Some(slot) = streams.get_mut(place) else {
334 return Err(io::Error::new(io::ErrorKind::InvalidInput, "no such place"));
335 };
336 if let Some(waiting) = self.shared.inputs.lock().get_mut(place) {
337 *waiting = input;
338 }
339 *slot = stream;
340 self.shared.changes.fetch_add(1, Ordering::Relaxed);
341 Ok(())
342 }
343
344 pub fn set_destinations(&self, place: usize, destinations: Vec<MacAddress>) {
347 let mut streams = self.shared.lock();
348 if let Some(Some(stream)) = streams.get_mut(place) {
349 stream.destinations = destinations;
350 self.shared.changes.fetch_add(1, Ordering::Relaxed);
351 }
352 }
353
354 pub fn follow(&self, clock: Option<RecoveredClock>) {
359 let mut follow = self.shared.follow.lock();
360 if *follow != clock {
361 *follow = clock;
362 self.shared.changes.fetch_add(1, Ordering::Relaxed);
363 }
364 }
365
366 pub fn sending(&self) -> bool {
368 self.shared.lock().iter().any(Option::is_some)
369 }
370
371 pub fn sends(&self, place: usize) -> bool {
373 self.shared.lock().get(place).is_some_and(Option::is_some)
374 }
375
376 pub fn stats(&self, place: usize) -> TalkerStats {
378 let read = |counter: &AtomicU64| counter.load(Ordering::Relaxed);
379 let group = &self.shared.group;
380 let (frames_sent, frames_late, send_errors) =
381 self.shared
382 .counters
383 .get(place)
384 .map_or((0, 0, 0), |counters| {
385 (
386 read(&counters.frames_sent),
387 read(&counters.frames_late),
388 read(&counters.send_errors),
389 )
390 });
391 TalkerStats {
392 frames_sent,
393 frames_late,
394 media_resets: read(&group.media_resets),
395 clock_resets: read(&group.clock_resets),
396 adjustments: read(&group.adjustments),
397 underruns: read(&group.underruns),
398 send_errors,
399 realtime: group.realtime.load(Ordering::Relaxed),
400 drift_ppm: group.drift_ppm.load(Ordering::Relaxed),
401 launching: group.launching.load(Ordering::Relaxed),
402 launches_missed: read(&group.launches_missed),
403 }
404 }
405
406 pub fn take_peaks(&self, place: usize) -> [f32; 2] {
410 self.shared
411 .counters
412 .get(place)
413 .map_or([0.0; 2], |counters| counters.peaks.take())
414 }
415}
416
417impl Drop for TalkerGroup {
418 fn drop(&mut self) {
419 self.stop.store(true, Ordering::Relaxed);
420 if let Some(handle) = self.handle.take() {
421 let _ = handle.join();
422 }
423 }
424}
425
426pub struct GroupTalker {
429 group: Arc<TalkerGroup>,
430 place: usize,
431}
432
433impl GroupTalker {
434 pub fn start(group: &Arc<TalkerGroup>, place: usize, stream: GroupStream) -> io::Result<Self> {
436 group.set_stream(place, Some(stream))?;
437 Ok(GroupTalker {
438 group: group.clone(),
439 place,
440 })
441 }
442
443 pub fn set_destinations(&self, destinations: Vec<MacAddress>) {
446 self.group.set_destinations(self.place, destinations);
447 }
448
449 pub fn stats(&self) -> TalkerStats {
450 self.group.stats(self.place)
451 }
452
453 pub fn take_peaks(&self) -> [f32; 2] {
456 self.group.take_peaks(self.place)
457 }
458}
459
460impl Drop for GroupTalker {
461 fn drop(&mut self) {
462 let _ = self.group.set_stream(self.place, None);
463 }
464}
465
466pub struct Talker {
468 group: TalkerGroup,
469}
470
471impl Talker {
472 pub fn start(config: TalkerConfig, clock: Arc<MediaClock>) -> io::Result<Self> {
475 Self::start_ahead(config, clock, None)
476 }
477
478 pub fn start_ahead(
481 config: TalkerConfig,
482 clock: Arc<MediaClock>,
483 ahead: Option<Duration>,
484 ) -> io::Result<Self> {
485 Self::start_as(config, clock, Departures::Ahead(ahead))
486 }
487
488 pub fn start_on_card(config: TalkerConfig, clock: Arc<MediaClock>) -> io::Result<Self> {
491 Self::start_as(config, clock, Departures::Card)
492 }
493
494 fn start_as(
495 config: TalkerConfig,
496 clock: Arc<MediaClock>,
497 departures: Departures,
498 ) -> io::Result<Self> {
499 let media = Media::of(config.format).ok_or_else(|| {
500 io::Error::new(
501 io::ErrorKind::Unsupported,
502 "not an AAF, AM824 or CRF format this talker sends",
503 )
504 })?;
505 let group_config = GroupConfig {
506 interface: config.interface,
507 mac: config.mac,
508 rate: media.sample_rate(),
509 };
510 let group = match departures {
511 Departures::Ahead(ahead) => TalkerGroup::start_ahead(group_config, 1, clock, ahead)?,
512 Departures::Card => TalkerGroup::start_on_card(group_config, 1, clock)?,
513 };
514 group.set_stream(
515 0,
516 Some(GroupStream {
517 stream_id: config.stream_id,
518 destinations: config.destinations,
519 vlan_id: config.vlan_id,
520 priority: config.priority,
521 format: config.format,
522 max_transit_time: config.max_transit_time,
523 source: config.source,
524 channels: media.channels(),
525 }),
526 )?;
527 Ok(Talker { group })
528 }
529
530 pub fn set_destinations(&self, destinations: Vec<MacAddress>) {
533 self.group.set_destinations(0, destinations);
534 }
535
536 pub fn stats(&self) -> TalkerStats {
537 self.group.stats(0)
538 }
539
540 pub fn launch_ahead(&self) -> Option<Duration> {
543 self.group.launch_ahead()
544 }
545
546 pub fn on_card(&self) -> bool {
549 self.group.on_card()
550 }
551}
552
553enum Departures {
556 Ahead(Option<Duration>),
557 Card,
558}
559
560fn ethernet_header(mac: MacAddress, stream: &GroupStream) -> [u8; ETHERNET_LEN] {
562 let mut header = [0; ETHERNET_LEN];
563 header[..6].copy_from_slice(&stream.destinations.first().map_or([0; 6], |mac| mac.0));
564 header[6..12].copy_from_slice(&mac.0);
565 header[12..14].copy_from_slice(ÐERTYPE_VLAN.to_be_bytes());
566 let tag = (u16::from(stream.priority & 0x7) << 13) | (stream.vlan_id & 0x0fff);
567 header[14..16].copy_from_slice(&tag.to_be_bytes());
568 header[16..18].copy_from_slice(ÐERTYPE_AVTP.to_be_bytes());
569 header
570}
571
572struct Running {
574 stream: GroupStream,
575 input: Option<Input>,
577 blocks: Option<Arc<dyn BlockSource>>,
580 words: Vec<i32>,
581 packetizer: Packetizer,
582 frame: Vec<u8>,
583 samples: Vec<f32>,
584 channels: usize,
586 frame_samples: u64,
588 next: u64,
590 media_reset: MediaReset,
592}
593
594#[derive(Debug, Default)]
599struct MediaReset {
600 bit: bool,
601 carried: bool,
603}
604
605impl MediaReset {
606 fn restart(&mut self) {
608 if self.carried {
609 self.bit = !self.bit;
610 self.carried = false;
611 }
612 }
613
614 fn sent(&mut self) {
616 self.carried = true;
617 }
618}
619
620impl Running {
621 fn new(
622 mac: MacAddress,
623 stream: GroupStream,
624 media: Media,
625 input: Option<Input>,
626 frame_samples: u64,
627 ) -> Self {
628 let mut frame = vec![0u8; ETHERNET_LEN + media.pdu_length()];
629 frame[..ETHERNET_LEN].copy_from_slice(ðernet_header(mac, &stream));
630 let samples =
631 vec![0.0f32; usize::from(media.channels()) * usize::from(media.samples_per_frame())];
632 let blocks = match (&stream.source, &input) {
633 (Source::Blocks(blocks), Some(_)) => Some(blocks.0.clone()),
634 _ => None,
635 };
636 Running {
637 packetizer: Packetizer::new(media, stream.stream_id),
638 words: vec![0; samples.len()],
639 stream,
640 input,
641 blocks,
642 frame,
643 samples,
644 channels: usize::from(media.channels()),
645 frame_samples: frame_samples.max(1),
646 next: 0,
647 media_reset: MediaReset::default(),
648 }
649 }
650
651 fn frame_samples(&self) -> u64 {
652 self.frame_samples
653 }
654
655 fn first_from(&self, from: u64) -> u64 {
657 from.div_ceil(self.frame_samples()) * self.frame_samples()
658 }
659
660 fn skip_to(&mut self, from: u64) -> u64 {
665 let frames = self.first_from(from).saturating_sub(self.next) / self.frame_samples();
666 let samples = frames as usize * self.block_samples();
667 if let Some(input) = &mut self.input {
668 input.skip(samples);
669 }
670 if let Some(blocks) = &self.blocks
671 && frames > 0
672 {
673 blocks.left_out(samples as u64);
674 }
675 self.packetizer.skip(frames);
676 self.next += frames * self.frame_samples();
677 frames
678 }
679
680 fn block_samples(&self) -> usize {
682 self.samples.len() / self.channels.max(1)
683 }
684
685 fn build(&mut self, presented: i64, peaks: &Peaks) -> Option<Block> {
689 let (samples, channels) = (self.block_samples(), self.channels);
690 let media_reset = self.media_reset.bit;
691 let block = self.blocks.as_ref().map(|blocks| {
692 let block = Block {
693 presented,
694 samples,
695 channels,
696 media_reset,
697 };
698 blocks.fill(&block, &mut self.words);
699 for (level, word) in self.samples.iter_mut().zip(&self.words) {
700 *level = (f64::from(*word) / 2_147_483_648.0) as f32;
701 }
702 block
703 });
704 if block.is_none()
705 && let Some(input) = &mut self.input
706 {
707 input.read_as(&mut self.samples, self.channels);
708 }
709 peaks.raise(&self.samples, self.channels);
710 let frame = &mut self.frame[ETHERNET_LEN..];
711 match block {
712 Some(_) => {
713 self.packetizer
714 .write_words(presented, self.media_reset.bit, &self.words, frame)
715 }
716 None => self
717 .packetizer
718 .write(presented, self.media_reset.bit, &self.samples, frame),
719 }
720 block
721 }
722}
723
724struct Timeline {
727 rate: u64,
728 origin: i64,
729 follow: Option<Following>,
731 wanted: Option<Fit>,
734}
735
736#[derive(Debug, Clone, Copy)]
739struct Following {
740 fit: Fit,
741 sample: u64,
742 sub: i128,
743 base: i128,
744}
745
746impl Timeline {
747 fn at(&self, sample: u64) -> i64 {
748 match &self.follow {
749 Some(following) => {
750 let samples = i128::from(sample) - i128::from(following.sample);
751 following
752 .fit
753 .time_at(following.sub + samples * following.base, self.rate)
754 }
755 None => self.origin + (u128::from(sample) * NANOS / u128::from(self.rate)) as i64,
756 }
757 }
758
759 fn sample_at(&self, time: i64) -> u64 {
761 match &self.follow {
762 Some(following) => {
763 let sub = following.fit.sub_at(time, self.rate);
764 let samples = div_ceil(sub - following.sub, following.base);
765 (i128::from(following.sample) + samples).max(0) as u64
766 }
767 None => {
768 let since = (time - self.origin).max(0);
769 (since as u128 * u128::from(self.rate)).div_ceil(NANOS) as u64
770 }
771 }
772 }
773
774 fn take(&mut self, fit: Option<Fit>) -> bool {
778 self.wanted = fit;
779 match (fit, self.follow.as_mut()) {
780 (Some(fit), Some(following)) if following.fit.generation == fit.generation => {
781 following.fit = fit;
782 false
783 }
784 (None, None) => false,
785 _ => true,
786 }
787 }
788
789 fn restart(&mut self, from: u64, now: i64) -> u64 {
794 let first = from.div_ceil(ALIGN) * ALIGN;
795 let boundary = (now / 1_000_000 + 2) * 1_000_000;
796 match self.wanted {
797 Some(fit) => {
798 let rate = i128::from(self.rate);
799 let edge = div_ceil(fit.sub_at(boundary, self.rate), rate) * rate;
800 self.follow = Some(Following {
801 fit,
802 sample: first,
803 sub: edge,
804 base: i128::from(fit.base_frequency),
805 });
806 }
807 None => {
808 self.follow = None;
809 self.origin = boundary - (u128::from(first) * NANOS / u128::from(self.rate)) as i64;
810 }
811 }
812 first
813 }
814}
815
816fn take_changes(
820 config: &GroupConfig,
821 shared: &Shared,
822 running: &mut [Option<Running>],
823 timeline: &mut Timeline,
824 clock: &MediaClock,
825) {
826 let wanted = shared.lock().clone();
827 let mut inputs = shared.inputs.lock();
828 let idle = running.iter().all(Option::is_none);
829 let mut from = None;
830 for (place, wanted) in wanted.into_iter().enumerate() {
831 let Some(slot) = running.get_mut(place) else {
832 continue;
833 };
834 match (wanted, slot.as_mut()) {
835 (None, _) => *slot = None,
836 (Some(stream), Some(now)) if same_but_destinations(&stream, &now.stream) => {
837 if stream.destinations != now.stream.destinations {
838 now.frame[..ETHERNET_LEN]
839 .copy_from_slice(ðernet_header(config.mac, &stream));
840 now.stream.destinations = stream.destinations;
841 }
842 }
843 (Some(stream), _) => {
844 let input = inputs.get_mut(place).and_then(Option::take);
845 let Some((media, frame_samples)) = Media::of(stream.format)
846 .and_then(|media| Some((media, media.frame_samples_at(config.rate)?)))
847 else {
848 *slot = None;
849 continue;
850 };
851 if input.is_none() && !media.is_clock() {
853 *slot = None;
854 continue;
855 }
856 let start = *from.get_or_insert_with(|| {
858 let now = clock.now();
859 if idle {
860 timeline.restart(timeline.sample_at(now), now)
861 } else {
862 timeline.sample_at(now + 1_000_000)
863 }
864 });
865 let mut made = Running::new(config.mac, stream, media, input, frame_samples);
866 made.next = made.first_from(start);
867 *slot = Some(made);
868 }
869 }
870 }
871}
872
873fn same_but_destinations(one: &GroupStream, other: &GroupStream) -> bool {
875 GroupStream {
876 destinations: Vec::new(),
877 ..one.clone()
878 } == GroupStream {
879 destinations: Vec::new(),
880 ..other.clone()
881 }
882}
883
884fn run(
885 config: &GroupConfig,
886 shared: &Shared,
887 sender: &FrameSender,
888 clock: &MediaClock,
889 launch: Option<(Duration, u32)>,
890 card: bool,
891 stop: &AtomicBool,
892) {
893 precise_sleeps();
894 shared
895 .group
896 .realtime
897 .store(crate::realtime::raise(), Ordering::Relaxed);
898 let mut running: Vec<Option<Running>> = (0..shared.counters.len()).map(|_| None).collect();
899 let mut timeline = Timeline {
900 rate: u64::from(config.rate.max(1)),
901 origin: 0,
902 follow: None,
903 wanted: None,
904 };
905 let mut seen = u64::MAX;
906 let mut frames: u64 = 0;
907 let mut follow: Option<RecoveredClock> = None;
908 let mut switched = false;
909 let mut generation = clock.generation();
910 let mut ahead = launch.map(|(ahead, _)| ahead);
911 let mut timing = Timing::start(monotonic_now());
912 let mut launching = false;
915 let mut last_launch = 0u64;
916 while !stop.load(Ordering::Relaxed) {
917 let changes = shared.changes.load(Ordering::Relaxed);
918 if changes != seen {
919 seen = changes;
920 let wanted = shared.follow.lock().clone();
921 if wanted != follow {
924 follow = wanted;
925 switched = timeline.follow.take().is_some();
926 }
927 timeline.take(follow.as_ref().and_then(RecoveredClock::fit));
928 take_changes(config, shared, &mut running, &mut timeline, clock);
929 ahead = fitting(launch, &running, timeline.rate);
930 }
931 let retime = timeline.take(follow.as_ref().and_then(RecoveredClock::fit));
935 let jumped = clock.generation() != generation;
938 generation = clock.generation();
939 if (retime || jumped || std::mem::take(&mut switched))
940 && running.iter().any(Option::is_some)
941 {
942 restart(&mut running, &mut timeline, clock);
943 shared.group.media_resets.fetch_add(1, Ordering::Relaxed);
944 if jumped {
945 shared.group.clock_resets.fetch_add(1, Ordering::Relaxed);
946 }
947 }
948 let Some((place, due)) = running
950 .iter()
951 .enumerate()
952 .filter_map(|(place, stream)| {
953 stream
954 .as_ref()
955 .map(|stream| (place, timeline.at(stream.next)))
956 })
957 .min_by_key(|(_, due)| *due)
958 else {
959 std::thread::sleep(LONGEST_SLEEP);
960 continue;
961 };
962 let departure = clock.monotonic_at(due);
967 let mut launch_at = if card { clock.card_at(due) } else { None };
968 if launch_at.is_some() != launching && sender.launch_on_card(launch_at.is_some()).is_ok() {
969 launching = launch_at.is_some();
970 shared.group.launching.store(launching, Ordering::Relaxed);
971 }
972 if !launching {
973 launch_at = None;
974 }
975 let lead = match launch_at {
976 Some(_) => CARD_AHEAD,
977 None => ahead.unwrap_or_default(),
978 };
979 let wake = departure.saturating_sub(lead);
980 let now = monotonic_now();
981 let mut woke = None;
984 if wake > now {
985 let wait = wake - now;
986 std::thread::sleep(wait.min(LONGEST_SLEEP));
987 if wait > LONGEST_SLEEP {
988 if due - clock.now() > 2 * LONGEST_SLEEP.as_nanos() as i64 {
991 restart(&mut running, &mut timeline, clock);
992 shared.group.media_resets.fetch_add(1, Ordering::Relaxed);
993 shared.group.clock_resets.fetch_add(1, Ordering::Relaxed);
994 }
995 continue;
996 }
997 if timing.on() {
998 woke = Some(monotonic_now().saturating_sub(wake));
999 }
1000 }
1001 let handover = timing.on().then(monotonic_now);
1004 if let Some(handover) = handover {
1005 timing.handed(handover, departure, woke);
1006 }
1007 let Some(stream) = running[place].as_mut() else {
1008 continue;
1009 };
1010 let transit = stream.stream.max_transit_time.as_nanos() as i64;
1013 let allowed = (transit - CROSSING).max(transit / 2);
1014 let now = clock.now();
1015 let counters = &shared.counters[place];
1016 if now - due > allowed {
1017 let from = timeline.sample_at(now - allowed / 2).max(stream.next + 1);
1023 let skipped = stream.skip_to(from);
1024 counters.frames_late.fetch_add(skipped, Ordering::Relaxed);
1025 timing.skipped(skipped);
1026 continue;
1027 }
1028 let block = stream.build(due + transit, &counters.peaks);
1029 if clock.now() - due > allowed {
1033 stream.next += stream.frame_samples();
1034 if let Some(blocks) = &stream.blocks {
1035 blocks.left_out(stream.block_samples() as u64);
1036 }
1037 counters.frames_late.fetch_add(1, Ordering::Relaxed);
1038 timing.skipped(1);
1039 continue;
1040 }
1041 let stamp = match launch_at {
1042 Some(at) => {
1046 let soonest = clock.card_at(clock.now()).map_or(at, |now| now + CARD_LATE);
1047 at.max(soonest).max(last_launch)
1048 }
1049 None => departure.max(monotonic_now() + LATE_STAMP).as_nanos() as u64,
1050 };
1051 if let Some(at) = launch_at {
1052 if stamp.saturating_sub(at) > allowed as u64 {
1055 stream.next += stream.frame_samples();
1056 if let Some(blocks) = &stream.blocks {
1057 blocks.left_out(stream.block_samples() as u64);
1058 }
1059 counters.frames_late.fetch_add(1, Ordering::Relaxed);
1060 timing.skipped(1);
1061 continue;
1062 }
1063 last_launch = stamp;
1064 }
1065 let built = timing.on().then(monotonic_now);
1066 let mut went_out = false;
1067 for destination in &stream.stream.destinations {
1068 stream.frame[..6].copy_from_slice(&destination.0);
1069 let sent = match (launch_at, ahead) {
1070 (Some(_), _) | (None, Some(_)) => sender.send_at(&stream.frame, stamp),
1071 (None, None) => sender.send(&stream.frame),
1072 };
1073 match sent {
1074 Ok(()) => {
1075 counters.frames_sent.fetch_add(1, Ordering::Relaxed);
1076 stream.media_reset.sent();
1077 went_out = true;
1078 }
1079 #[cfg(target_os = "linux")]
1083 Err(error)
1084 if launch_at.is_some() && error.raw_os_error() == Some(libc::ENOBUFS) => {}
1085 Err(_) => {
1086 counters.send_errors.fetch_add(1, Ordering::Relaxed);
1087 }
1088 }
1089 }
1090 if let (Some(blocks), Some(block)) = (&stream.blocks, &block) {
1091 blocks.sent(block, went_out);
1092 }
1093 if let (Some(handover), Some(built)) = (handover, built) {
1094 let sent = monotonic_now();
1095 timing.sent(built - handover, sent - built);
1096 }
1097 stream.next += stream.frame_samples();
1098 frames += 1;
1099 if frames.is_multiple_of(800) {
1100 let (mut made, mut empty, mut drift) = (0, 0, 0);
1103 for input in running
1104 .iter()
1105 .flatten()
1106 .filter_map(|stream| stream.input.as_ref())
1107 {
1108 let (adjusted, short) = input.counts();
1109 made += adjusted;
1110 empty += short;
1111 if drift == 0 {
1112 drift = input.drift_ppm();
1113 }
1114 }
1115 shared.group.adjustments.store(made, Ordering::Relaxed);
1116 shared.group.drift_ppm.store(drift, Ordering::Relaxed);
1117 shared.group.underruns.store(empty, Ordering::Relaxed);
1118 if card {
1121 let missed = sender.missed_launches();
1122 if missed > 0 {
1123 shared
1124 .group
1125 .launches_missed
1126 .fetch_add(missed, Ordering::Relaxed);
1127 timing.skipped(missed);
1128 }
1129 }
1130 }
1131 }
1132}
1133
1134fn fitting(
1139 launch: Option<(Duration, u32)>,
1140 running: &[Option<Running>],
1141 rate: u64,
1142) -> Option<Duration> {
1143 let (ahead, room) = launch?;
1144 let per_second: f64 = running
1145 .iter()
1146 .flatten()
1147 .map(|stream| {
1148 stream.stream.destinations.len() as f64 * rate as f64
1149 / stream.frame_samples().max(1) as f64
1150 })
1151 .sum();
1152 if per_second <= 0.0 {
1153 return Some(ahead);
1154 }
1155 Some(ahead.min(Duration::from_secs_f64(f64::from(room) / 2.0 / per_second)))
1156}
1157
1158fn restart(running: &mut [Option<Running>], timeline: &mut Timeline, clock: &MediaClock) {
1161 let now = clock.now();
1162 let first = timeline.restart(timeline.sample_at(now), now);
1163 for stream in running.iter_mut().flatten() {
1164 stream.next = stream.first_from(first);
1165 stream.media_reset.restart();
1166 }
1167}
1168
1169#[cfg(test)]
1170mod tests {
1171 use super::*;
1172
1173 #[test]
1176 fn the_timeline_counts_samples_on_gptp_time() {
1177 let mut timeline = Timeline {
1178 rate: 48_000,
1179 origin: 0,
1180 follow: None,
1181 wanted: None,
1182 };
1183 let first = timeline.restart(5, 7_400_000);
1184 assert_eq!(first, 48);
1185 assert_eq!(timeline.at(first), 9_000_000);
1186 assert_eq!(timeline.at(first + 6) - timeline.at(first), 125_000);
1187 assert_eq!(timeline.at(first + 12) - timeline.at(first), 250_000);
1188 assert_eq!(timeline.sample_at(timeline.at(first + 6)), first + 6);
1189 assert_eq!(timeline.sample_at(timeline.at(first) + 1), first + 1);
1191 }
1192
1193 #[test]
1198 fn the_timeline_follows_a_media_clock() {
1199 let period = (1e9 / 48_000.0 / (1.0 + 50e-6) * 4_294_967_296.0) as u64;
1201 let fit = Fit {
1202 generation: 3,
1203 event: 960_000,
1204 time: 21_000_000_000,
1205 period,
1206 base_frequency: 48_000,
1207 };
1208 let mut timeline = Timeline {
1209 rate: 192_000,
1210 origin: 0,
1211 follow: None,
1212 wanted: None,
1213 };
1214 assert!(timeline.take(Some(fit)), "a clock to follow starts again");
1215 let first = timeline.restart(1000, 21_000_000_000);
1216 assert_eq!(first, 1008);
1217 let start = timeline.at(first);
1218 assert!(start >= 21_002_000_000, "{start}");
1219 let events = fit.sub_at(start, 1) - i128::from(fit.event);
1221 assert_eq!(fit.time_at(i128::from(fit.event) + events, 1), start);
1222 let second = timeline.at(first + 192_000) - start;
1224 assert!((second - 999_950_002).abs() <= 2, "{second}");
1225 assert_eq!(
1226 timeline.at(first + 4) - start,
1227 fit.time_at(i128::from(fit.event) + events + 1, 1) - start
1228 );
1229 assert_eq!(timeline.sample_at(timeline.at(first + 7)), first + 7);
1230 let later = Fit {
1232 event: fit.event + 96,
1233 time: fit.time_at(i128::from(fit.event) + 96, 1),
1234 ..fit
1235 };
1236 assert!(!timeline.take(Some(later)));
1237 assert_eq!(timeline.at(first + 192_000) - start, second);
1238 assert!(timeline.take(Some(Fit {
1240 generation: 4,
1241 ..later
1242 })));
1243 assert!(timeline.take(None));
1244 timeline.restart(first + 192_000, 22_500_000_000);
1245 assert!(timeline.follow.is_none());
1246 assert!(!timeline.take(None));
1247 }
1248
1249 #[test]
1253 fn late_frames_are_left_out() {
1254 let format = StreamFormat(0x0205_0220_0200_6000);
1255 let media = Media::of(format).unwrap();
1256 let source = Source::Tone {
1257 hertz: 1000.0,
1258 level: 0.5,
1259 };
1260 let stream = GroupStream {
1261 stream_id: 1,
1262 destinations: Vec::new(),
1263 vlan_id: 2,
1264 priority: 3,
1265 format,
1266 max_transit_time: Duration::from_millis(2),
1267 source: source.clone(),
1268 channels: 8,
1269 };
1270 let start = || {
1271 let input = Input::open(&source, 8, 48_000).unwrap();
1272 let mut made = Running::new(MacAddress([0; 6]), stream.clone(), media, Some(input), 6);
1273 made.next = 480;
1274 made
1275 };
1276 let send = |running: &mut Running| {
1277 let input = running.input.as_mut().unwrap();
1278 input.read_as(&mut running.samples, running.channels);
1279 let presentation = 9_000_000 + running.next as i64 * 1_000_000_000 / 48_000;
1280 running.packetizer.write(
1281 presentation,
1282 running.media_reset.bit,
1283 &running.samples,
1284 &mut running.frame[ETHERNET_LEN..],
1285 );
1286 running.next += running.frame_samples();
1287 let mut samples = Vec::new();
1288 let received =
1289 crate::media::read(&running.frame[ETHERNET_LEN..], &media, &mut samples).unwrap();
1290 (received, samples)
1291 };
1292 let (mut every, mut late) = (start(), start());
1293 for _ in 0..4 {
1294 send(&mut every);
1295 }
1296 assert_eq!(late.skip_to(500), 4);
1298 assert_eq!(late.next, every.next);
1299 let (wanted, wanted_samples) = send(&mut every);
1300 let (got, samples) = send(&mut late);
1301 assert_eq!(got, wanted);
1302 assert_eq!(got.sequence, 4);
1303 assert!(!got.media_reset);
1304 assert!(
1305 samples
1306 .iter()
1307 .zip(&wanted_samples)
1308 .all(|(sample, wanted)| (sample - wanted).abs() < 1e-4),
1309 "the tone goes on where it would have"
1310 );
1311 assert_eq!(late.skip_to(late.next), 0);
1313 }
1314
1315 #[test]
1319 fn a_programs_blocks_go_out_as_filled() {
1320 use crate::audio::{Block, BlockSource, Blocks};
1321 use std::sync::Mutex;
1322
1323 #[derive(Default)]
1324 struct Counting {
1325 filled: Mutex<Vec<Block>>,
1326 sent: Mutex<Vec<(i64, bool)>>,
1327 left_out: Mutex<Vec<u64>>,
1328 }
1329 impl BlockSource for Counting {
1330 fn fill(&self, block: &Block, words: &mut [i32]) {
1331 let mut filled = self.filled.lock().unwrap();
1332 let first = filled.len() as i32 * 1000;
1333 for (place, word) in words.iter_mut().enumerate() {
1334 *word = (first + place as i32).wrapping_mul(0x0101_0101);
1335 }
1336 filled.push(*block);
1337 }
1338 fn sent(&self, block: &Block, sent: bool) {
1339 self.sent.lock().unwrap().push((block.presented, sent));
1340 }
1341 fn left_out(&self, samples: u64) {
1342 self.left_out.lock().unwrap().push(samples);
1343 }
1344 }
1345
1346 let format = StreamFormat(0x0205_0220_0080_6000);
1348 let media = Media::of(format).unwrap();
1349 assert_eq!((media.channels(), media.samples_per_frame()), (2, 6));
1350 let counting = Arc::new(Counting::default());
1351 let source = Source::Blocks(Blocks(counting.clone()));
1352 let stream = GroupStream {
1353 stream_id: 1,
1354 destinations: Vec::new(),
1355 vlan_id: 2,
1356 priority: 3,
1357 format,
1358 max_transit_time: Duration::from_millis(2),
1359 source: source.clone(),
1360 channels: 2,
1361 };
1362 let input = Input::open(&source, 2, 48_000).unwrap();
1363 let mut running = Running::new(MacAddress([0; 6]), stream, media, Some(input), 6);
1364 let peaks = Peaks::default();
1365 let block = running.build(5_000_000, &peaks).unwrap();
1366 assert_eq!(
1367 block,
1368 Block {
1369 presented: 5_000_000,
1370 samples: 6,
1371 channels: 2,
1372 media_reset: false,
1373 }
1374 );
1375 let mut words = Vec::new();
1376 assert!(crate::media::read_words(
1377 &running.frame[ETHERNET_LEN..],
1378 &media,
1379 &mut words
1380 ));
1381 let wanted: Vec<i32> = (0..12)
1382 .map(|place: i32| place.wrapping_mul(0x0101_0101))
1383 .collect();
1384 assert_eq!(words, wanted, "every bit of every word");
1385 let mut levels = Vec::new();
1386 let received =
1387 crate::media::read(&running.frame[ETHERNET_LEN..], &media, &mut levels).unwrap();
1388 assert_eq!(received.timestamp, Some(5_000_000));
1389
1390 running.next = 6;
1392 assert_eq!(running.skip_to(20), 3);
1393 assert_eq!(*counting.left_out.lock().unwrap(), [18]);
1394 assert!(counting.sent.lock().unwrap().is_empty());
1395 }
1396
1397 #[test]
1402 fn the_mr_bit_tells_each_start() {
1403 let mut media_reset = MediaReset::default();
1404 media_reset.restart();
1405 assert!(!media_reset.bit, "nothing to tell before the first frame");
1406 media_reset.sent();
1407 media_reset.restart();
1408 media_reset.restart();
1409 assert!(media_reset.bit, "two starts change the bit once");
1410 media_reset.restart();
1412 assert!(media_reset.bit);
1413 media_reset.sent();
1414 media_reset.restart();
1415 assert!(!media_reset.bit);
1416 }
1417}