Skip to main content

weirdnet_streaming/
listen.rs

1//! Listen-along: the host streams its master out as raw PCM (32-bit float) over weirdnet-streaming; members of the session subscribe
2//! and hear it mixed into their own output. Each frame carries the sender's wall-clock time (frame metadata, 8 bytes, microseconds since
3//! the Unix epoch) so a listener can measure the one-way delay when the clocks agree (same machine, or synced clocks). The take is kept
4//! and offered as a recorded stream that can be played from any position.
5
6use crate::bus::Ends;
7use crate::{Frame, Hub, Publisher, Recording, StreamEvent, StreamId, StreamInfo};
8use serde::{Deserialize, Serialize};
9use std::sync::atomic::Ordering;
10use std::sync::{Arc, Mutex};
11use std::time::{Duration, SystemTime, UNIX_EPOCH};
12
13/// The live master out stream.
14pub const MASTER: &str = "master";
15/// The last take of the master out, recorded and seekable.
16pub const TAKE: &str = "master-take";
17/// Samples per channel in one frame: 10 ms at 48 kHz.
18pub const FRAME_MS: u32 = 10;
19/// The longest take kept, in seconds.
20pub const TAKE_SECONDS: u32 = 120;
21
22/// Stream metadata: what the stream is.
23#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
24pub struct StreamMeta {
25    /// The app that made the stream.
26    pub app: String,
27    /// The kind of stream (for example [`MASTER`] or [`TAKE`]).
28    pub class: String,
29    /// The project the stream belongs to.
30    pub project: String,
31}
32
33/// The wall-clock time now, microseconds since the Unix epoch.
34pub fn wall_us() -> u64 {
35    SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_micros() as u64).unwrap_or(0)
36}
37
38/// The send time carried in a frame's metadata.
39pub fn sent_us(f: &Frame) -> Option<u64> {
40    let m = f.meta.as_ref()?;
41    Some(u64::from_le_bytes(m.get(..8)?.try_into().ok()?))
42}
43
44/// What a listener measured.
45#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
46pub struct ListenStats {
47    /// Frames received.
48    pub frames: u64,
49    /// Gaps seen in the sequence.
50    pub gaps: u64,
51    /// Frames missed in all.
52    pub missed: u64,
53    /// One-way delay from the sender's tap to arrival (needs agreeing clocks), milliseconds.
54    pub delay_ms_mean: f64,
55    /// Smallest one-way delay, milliseconds.
56    pub delay_ms_min: f64,
57    /// Largest one-way delay, milliseconds.
58    pub delay_ms_max: f64,
59    /// Interarrival jitter, milliseconds (weirdnet-streaming's estimate).
60    pub jitter_ms: f64,
61    /// Times playback ran dry.
62    pub underruns: u64,
63    /// Whether the connection is relayed.
64    pub relayed: bool,
65}
66
67impl ListenStats {
68    /// The statistics as one log line.
69    pub fn line(&self) -> String {
70        format!(
71            "frames={} gaps={} missed={} delay_ms mean={:.2} min={:.2} max={:.2} jitter_ms={:.2} underruns={} path={}",
72            self.frames,
73            self.gaps,
74            self.missed,
75            self.delay_ms_mean,
76            self.delay_ms_min,
77            self.delay_ms_max,
78            self.jitter_ms,
79            self.underruns,
80            if self.relayed { "relayed" } else { "direct" }
81        )
82    }
83}
84
85/// Moves the tap into frames on a publisher, and the take into a recording. Runs until `stop`.
86pub async fn pump(ends: Arc<Mutex<Ends>>, publisher: Publisher, hub: Arc<Hub>, stop: Arc<std::sync::atomic::AtomicBool>) {
87    let (rate, ch) = {
88        let e = crate::lock(&ends);
89        e.shared.tap_on.store(true, Ordering::Relaxed);
90        (e.sample_rate, e.channels)
91    };
92    let per = (rate * FRAME_MS / 1000) as usize * ch as usize;
93    let mut take = Recording::new(StreamInfo { id: StreamId::new(TAKE), ..publisher.info() });
94    let max_take = (TAKE_SECONDS * 1000 / FRAME_MS) as usize;
95    let (mut seq, mut pts) = (0u64, 0u64);
96    let mut buf = Vec::with_capacity(per);
97    while !stop.load(Ordering::Relaxed) {
98        tokio::time::sleep(Duration::from_millis(2)).await;
99        let mut e = crate::lock(&ends);
100        loop {
101            let n = (per - buf.len()).min(e.tap.slots());
102            if n == 0 {
103                break;
104            }
105            if let Ok(c) = e.tap.read_chunk(n) {
106                let (a, b) = c.as_slices();
107                buf.extend_from_slice(a);
108                buf.extend_from_slice(b);
109                c.commit_all();
110            }
111            if buf.len() == per {
112                let mut f = Frame::pcm_f32(seq, pts, ch, &buf);
113                f.meta = Some(wall_us().to_le_bytes().to_vec());
114                pts += f.duration as u64;
115                seq += 1;
116                if take.len() < max_take {
117                    take.push(f.clone());
118                }
119                let _ = publisher.send(f);
120                buf.clear();
121            }
122        }
123    }
124    crate::lock(&ends).shared.tap_on.store(false, Ordering::Relaxed);
125    publisher.finish();
126    hub.remove(&StreamId::new(MASTER));
127    if !take.is_empty() {
128        hub.remove(&StreamId::new(TAKE));
129        hub.add_recorded(take.finish());
130    }
131}
132
133/// Plays a subscription into the mix until it ends or `stop`.
134pub async fn play(mut sub: crate::net::Subscriber, ends: Arc<Mutex<Ends>>, stats: Arc<Mutex<ListenStats>>, stop: Arc<std::sync::atomic::AtomicBool>) {
135    crate::lock(&ends).shared.listening.store(true, Ordering::Relaxed);
136    let (mut sum, mut n) = (0.0f64, 0u64);
137    while !stop.load(Ordering::Relaxed) {
138        let ev = match tokio::time::timeout(Duration::from_millis(200), sub.next()).await {
139            Ok(Some(ev)) => ev,
140            Ok(None) => break,
141            Err(_) => continue,
142        };
143        match ev {
144            StreamEvent::Frame(f) => {
145                let now = wall_us();
146                {
147                    let mut e = crate::lock(&ends);
148                    let samples = f.f32_samples();
149                    let k = samples.len().min(e.mix.slots());
150                    if let Ok(c) = e.mix.write_chunk_uninit(k) {
151                        c.fill_from_iter(samples);
152                    }
153                }
154                let mut s = crate::lock(&stats);
155                if let Some(t) = sent_us(&f) {
156                    let d = now.saturating_sub(t) as f64 / 1000.0;
157                    sum += d;
158                    n += 1;
159                    s.delay_ms_mean = sum / n as f64;
160                    s.delay_ms_min = if n == 1 { d } else { s.delay_ms_min.min(d) };
161                    s.delay_ms_max = s.delay_ms_max.max(d);
162                }
163                let st = sub.stats();
164                s.frames = st.frames;
165                s.gaps = st.gaps;
166                s.missed = st.missed;
167                s.jitter_ms = st.jitter_ms;
168                s.underruns = crate::lock(&ends).shared.underruns.load(Ordering::Relaxed);
169            }
170            StreamEvent::Ended => break,
171            _ => {}
172        }
173    }
174    crate::lock(&ends).shared.listening.store(false, Ordering::Relaxed);
175}