moq_mux/clock.rs
1//! A shared clock for aligning concurrently-produced tracks.
2
3use std::time::Instant;
4
5/// A monotonic clock for stamping media frames so that tracks produced
6/// concurrently, e.g. an audio and a video capture running on separate
7/// threads, land on a single timeline.
8///
9/// Create one [`Clock`] and sample it ([`micros`](Self::micros)) from each
10/// producer: because they share an epoch, frames captured at the same instant
11/// get the same timestamp, keeping the tracks in sync. It is `Copy`, so it's
12/// cheap to hand to several producers.
13#[derive(Clone, Copy, Debug)]
14pub struct Clock {
15 epoch: Instant,
16}
17
18impl Clock {
19 /// Start a clock anchored at the current instant.
20 pub fn new() -> Self {
21 Self { epoch: Instant::now() }
22 }
23
24 /// Microseconds elapsed since the clock's epoch.
25 pub fn micros(&self) -> u64 {
26 // u128 -> u64 truncation is unreachable: u64 microseconds is ~584,000 years.
27 self.epoch.elapsed().as_micros() as u64
28 }
29}
30
31impl Default for Clock {
32 fn default() -> Self {
33 Self::new()
34 }
35}