audio-clock-bsd 0.1.0

PTP/NTP clock synchronization and sample-index to timestamp conversion for real-time audio
Documentation
//! Example: read the NTP-backed clock and timestamp a few sample windows.
//!
//! ```sh
//! cargo run --example ntp_clock
//! ```

use audio_clock_bsd::{ClockSource, NtpClock};
use audio_core_bsd::AudioFrame;

/// Frames per audio buffer.
const PERIOD_FRAMES: usize = 256;
const SAMPLE_RATE: u32 = 48_000;

fn main() -> audio_clock_bsd::Result<()> {
    let clock = NtpClock::new(SAMPLE_RATE)?;

    println!("clock anchored: {:?}", clock.anchor());
    println!("now (ptp_now_ns): {} ns", clock.ptp_now_ns()?);

    // Timestamp the start of each of a few consecutive periods, as an audio
    // engine would when labelling outgoing buffers.
    for i in 0i64..5 {
        let frame = AudioFrame::silence(2, PERIOD_FRAMES, SAMPLE_RATE);
        let sample_offset = i * i64::try_from(PERIOD_FRAMES).unwrap();
        let start_ns = clock.sample_to_ptp(sample_offset);
        let end_ns =
            clock.sample_to_ptp(sample_offset + i64::try_from(frame.num_frames()).unwrap());
        println!(
            "period {i}: samples {sample_offset}..{} -> ptp [{start_ns}, {end_ns}] ns ({:.3} ms)",
            sample_offset + i64::try_from(frame.num_frames()).unwrap(),
            (end_ns - start_ns) as f64 / 1_000_000.0
        );
    }
    Ok(())
}