Skip to main content

weirdnet_streaming/
remote.rs

1//! A remote executor (feature `route`): the connections of a `weirdnet_audio_route` graph between this node's
2//! `weirdnet_audio_engine` router and other nodes.
3//!
4//! A connection from a port of this router to a port elsewhere is sent: the port feeds a router tap, and a pump sends what the
5//! tap holds as a live raw PCM stream whose id is the port id. A connection from a port elsewhere to a port of this router is
6//! received: a subscription to that port's stream on the node that has it goes through a resampler into a router input, routed
7//! to the port with the connection's gain. Connections with both ends here are left to the router's own executor, and the
8//! router's own wiring is never touched.
9//!
10//! Receiving keeps about [`RemoteOptions::playout_ms`] of audio queued, which absorbs network jitter, and trims the resampler's
11//! ratio to hold that level, which follows the sender's audio clock running a little fast or slow. The sender's clock is measured
12//! with [`crate::clock`], and every link reports its transit time, buffer, total delay and drift in a [`LinkReport`]; an app
13//! writes the delay into the graph with `Graph::set_measured_delay`.
14//!
15//! Who may subscribe is decided by the [`StreamAuth`] the executor serves its hub with, so a connection the sender's
16//! permissions refuse is reported as [`LinkState::Denied`] and carries nothing.
17
18use crate::Publisher;
19use crate::clock::{self, ClockFn, DriftFit};
20use crate::net::{Hub, Server, StreamAuth, Subscriber, serve};
21use crate::types::{Frame, StreamError, StreamEvent, StreamId, StreamInfo, SubscribeOptions};
22use std::collections::{BTreeMap, BTreeSet};
23use std::sync::atomic::{AtomicU64, Ordering};
24use std::sync::{Arc, Mutex, MutexGuard};
25use std::time::Duration;
26use weirdnet_audio_engine::router::{Route, RouterControl, RouterInput, RouterTap};
27use weirdnet_audio_route::{ConnectionId, Executor, Graph, NodeId, PortId, RouteError};
28use weirdnet_dsp::resample::{MAX_TRIM, Resampler};
29use weirdnet_net::{Message, Multiaddr, Node, PeerId};
30
31/// The stream parameter carrying the sender's clock reading, in nanoseconds, at the stream's first sample.
32pub const EPOCH_PARAM: &str = "epoch_ns";
33
34/// Where other nodes are.
35pub trait Peers: Send + Sync {
36    /// The peer serving `node`'s streams and its addresses, or `None` while it cannot be reached.
37    fn locate(&self, node: &NodeId) -> Option<(PeerId, Vec<Multiaddr>)>;
38}
39
40impl<F: Fn(&NodeId) -> Option<(PeerId, Vec<Multiaddr>)> + Send + Sync> Peers for F {
41    fn locate(&self, node: &NodeId) -> Option<(PeerId, Vec<Multiaddr>)> {
42        self(node)
43    }
44}
45
46/// A [`Peers`] table an app fills as it learns where nodes are (from a registry, a session or a discovery message), shared between
47/// the app and the [`RemoteExecutor`].
48#[derive(Default)]
49pub struct PeerTable(Mutex<BTreeMap<NodeId, (PeerId, Vec<Multiaddr>)>>);
50
51impl PeerTable {
52    /// Learns or updates where `node` is.
53    pub fn set(&self, node: NodeId, peer: PeerId, addrs: Vec<Multiaddr>) {
54        self.0.lock().unwrap_or_else(|e| e.into_inner()).insert(node, (peer, addrs));
55    }
56
57    /// Forgets `node`.
58    pub fn remove(&self, node: &NodeId) {
59        self.0.lock().unwrap_or_else(|e| e.into_inner()).remove(node);
60    }
61}
62
63impl Peers for PeerTable {
64    fn locate(&self, node: &NodeId) -> Option<(PeerId, Vec<Multiaddr>)> {
65        self.0.lock().unwrap_or_else(|e| e.into_inner()).get(node).cloned()
66    }
67}
68
69/// Tuning.
70#[derive(Clone, Copy, Debug, PartialEq)]
71pub struct RemoteOptions {
72    /// Audio kept queued on the receiving side, milliseconds.
73    pub playout_ms: f64,
74    /// Frames per sent stream frame.
75    pub frame_frames: usize,
76    /// How often the sender's clock is measured.
77    pub clock_every: Duration,
78    /// How long to wait before trying a link again.
79    pub retry: Duration,
80    /// Align every received link to this whole delay, milliseconds: each link's buffer becomes this minus its transit (at least
81    /// [`MIN_BUFFER_MS`]), so audio made at the same moment on different nodes leaves this router's inputs together. `None` keeps
82    /// [`RemoteOptions::playout_ms`] of buffer on every link.
83    pub align_ms: Option<f64>,
84    /// Holds every sent frame this long before sending it, milliseconds: a longer network path, for tests and demonstrations.
85    pub send_hold_ms: f64,
86}
87
88/// The least buffer a link keeps when aligning, milliseconds.
89pub const MIN_BUFFER_MS: f64 = 10.0;
90
91impl Default for RemoteOptions {
92    fn default() -> Self {
93        RemoteOptions {
94            playout_ms: 40.0,
95            frame_frames: 240,
96            clock_every: Duration::from_secs(2),
97            retry: Duration::from_millis(250),
98            align_ms: None,
99            send_hold_ms: 0.0,
100        }
101    }
102}
103
104/// Which way a link carries audio.
105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106pub enum LinkDir {
107    /// From a port here to another node.
108    Send,
109    /// From another node to a port here.
110    Receive,
111}
112
113/// How a link is doing.
114#[derive(Clone, Debug, PartialEq, Eq)]
115pub enum LinkState {
116    /// Not carrying audio yet, and why.
117    Waiting(String),
118    /// Carrying audio.
119    Live,
120    /// The sender refused the subscription, with its reason.
121    Denied(String),
122}
123
124/// One link's numbers.
125#[derive(Clone, Debug, PartialEq)]
126pub struct LinkReport {
127    /// The graph connection.
128    pub connection: ConnectionId,
129    /// Its output.
130    pub from: PortId,
131    /// Its input.
132    pub to: PortId,
133    /// Send or receive.
134    pub dir: LinkDir,
135    /// The state. A send is live while anyone listens to its port.
136    pub state: LinkState,
137    /// Receive: how long a sample takes from the sender's router to arrival here (clock offset removed), milliseconds. A sample
138    /// stands for the moment its block started plus its place in the block, and blocks are rendered ahead, so a fast path can
139    /// show slightly below zero.
140    pub transit_ms: Option<f64>,
141    /// Receive: frames queued for playout, at this router's rate.
142    pub buffer_frames: usize,
143    /// Receive: the whole delay from the sender's router to this router's input, frames at this router's rate.
144    pub delay_frames: Option<u32>,
145    /// Receive: the sender's clock minus this one, nanoseconds.
146    pub clock_offset_ns: Option<i64>,
147    /// Receive: how much faster the sender's clock runs, parts per million.
148    pub clock_drift_ppm: Option<f64>,
149    /// Receive: how much faster the sender's audio runs than this router's, as the resampler trim holding the buffer level
150    /// shows it averaged over about four seconds, parts per million.
151    pub trim_ppm: f64,
152    /// Frames carried.
153    pub frames: u64,
154    /// Samples lost: dropped or missing at the router.
155    pub lost: u64,
156    /// Receive: stream frames missing on arrival.
157    pub gaps: u64,
158    /// Receive: the buffer the link aims at, frames at this router's rate.
159    pub target_frames: usize,
160    /// Receive: whether the link meets [`RemoteOptions::align_ms`] (false when its transit leaves less than [`MIN_BUFFER_MS`]).
161    pub aligned: Option<bool>,
162    /// Receive: the sender's clock at its stream's first sample, nanoseconds of the sender's clock.
163    pub sender_epoch_ns: Option<u64>,
164}
165
166impl LinkReport {
167    fn new(connection: ConnectionId, from: PortId, to: PortId, dir: LinkDir) -> LinkReport {
168        LinkReport {
169            connection,
170            from,
171            to,
172            dir,
173            state: LinkState::Waiting("starting".into()),
174            transit_ms: None,
175            buffer_frames: 0,
176            delay_frames: None,
177            clock_offset_ns: None,
178            clock_drift_ppm: None,
179            trim_ppm: 0.0,
180            frames: 0,
181            lost: 0,
182            gaps: 0,
183            target_frames: 0,
184            aligned: None,
185            sender_epoch_ns: None,
186        }
187    }
188}
189
190fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
191    m.lock().unwrap_or_else(|e| e.into_inner())
192}
193
194struct Send_ {
195    tap: String,
196    publisher: Arc<Mutex<Option<Publisher>>>,
197    sent: Arc<AtomicU64>,
198    tap_handle: RouterTap,
199    task: tokio::task::JoinHandle<()>,
200}
201
202struct Receive {
203    input: String,
204    to: PortId,
205    gain_db: f32,
206    report: Arc<Mutex<LinkReport>>,
207    task: tokio::task::JoinHandle<()>,
208}
209
210/// Carries a graph's connections between this node's router and other nodes.
211pub struct RemoteExecutor<Q: Message, R: Message> {
212    node: Arc<Node<Q, R>>,
213    router: Arc<Mutex<RouterControl>>,
214    hub: Arc<Hub>,
215    peers: Arc<dyn Peers>,
216    clock: ClockFn,
217    rt: tokio::runtime::Handle,
218    opts: RemoteOptions,
219    sends: BTreeMap<PortId, Send_>,
220    send_links: Vec<(ConnectionId, PortId, PortId)>,
221    receives: BTreeMap<ConnectionId, Receive>,
222    _server: Server,
223    _clock_server: clock::ClockServer,
224}
225
226impl<Q: Message, R: Message> RemoteExecutor<Q, R> {
227    /// Serves this node's sent ports (asking `auth` about each subscriber) and its clock on `node`, and receives through
228    /// `router`. `clock` should be the clock the audio runs on, or [`clock::monotonic`].
229    pub fn start(
230        node: Arc<Node<Q, R>>,
231        router: Arc<Mutex<RouterControl>>,
232        peers: Arc<dyn Peers>,
233        auth: Arc<dyn StreamAuth>,
234        clock: ClockFn,
235        rt: tokio::runtime::Handle,
236        opts: RemoteOptions,
237    ) -> Result<Self, StreamError> {
238        let _g = rt.enter();
239        let hub = Arc::new(Hub::new());
240        let server = serve(&node, hub.clone(), auth)?;
241        let clock_server = clock::serve_clock(&node, clock.clone())?;
242        Ok(RemoteExecutor {
243            node,
244            router,
245            hub,
246            peers,
247            clock,
248            rt,
249            opts,
250            sends: BTreeMap::new(),
251            send_links: Vec::new(),
252            receives: BTreeMap::new(),
253            _server: server,
254            _clock_server: clock_server,
255        })
256    }
257
258    /// Every link's numbers, sends first, in connection order.
259    pub fn reports(&self) -> Vec<LinkReport> {
260        let mut v = Vec::new();
261        for (c, from, to) in &self.send_links {
262            let mut r = LinkReport::new(c.clone(), from.clone(), to.clone(), LinkDir::Send);
263            if let Some(s) = self.sends.get(from) {
264                let listeners = lock(&s.publisher).as_ref().map(|p| p.listeners().len()).unwrap_or(0);
265                r.state = if listeners > 0 { LinkState::Live } else { LinkState::Waiting("no listener".into()) };
266                r.frames = s.sent.load(Ordering::Relaxed);
267                r.lost = s.tap_handle.lost();
268            }
269            v.push(r);
270        }
271        v.extend(self.receives.values().map(|r| lock(&r.report).clone()));
272        v
273    }
274
275    fn stop_send(&mut self, port: &PortId) {
276        if let Some(s) = self.sends.remove(port) {
277            s.task.abort();
278            if let Some(p) = lock(&s.publisher).take() {
279                p.finish();
280            }
281            self.hub.remove(&StreamId::new(port.as_str()));
282            let _ = lock(&self.router).remove(&s.tap);
283        }
284    }
285
286    fn stop_receive(&mut self, id: &ConnectionId) {
287        if let Some(r) = self.receives.remove(id) {
288            r.task.abort();
289            let _ = lock(&self.router).remove(&r.input);
290        }
291    }
292
293    fn start_send(&mut self, port: &PortId) -> Result<(), RouteError> {
294        let tap = format!("{}>net", port.as_str());
295        let config = lock(&self.router).config();
296        let handle = {
297            let mut router = lock(&self.router);
298            let handle = router.add_tap(&tap, config.sample_rate as usize).map_err(|e| RouteError::Denied(e.to_string()))?;
299            if let Err(e) = router.connect(Route::new(port.as_str(), &tap)) {
300                let _ = router.remove(&tap);
301                return Err(RouteError::Denied(e.to_string()));
302            }
303            handle
304        };
305        let publisher = Arc::new(Mutex::new(None));
306        let sent = Arc::new(AtomicU64::new(0));
307        let task = self.rt.spawn(pump_send(
308            handle.clone(),
309            port.clone(),
310            config.sample_rate,
311            config.channels,
312            self.opts.frame_frames,
313            Duration::from_secs_f64(self.opts.send_hold_ms.max(0.0) / 1000.0),
314            self.clock.clone(),
315            self.hub.clone(),
316            publisher.clone(),
317            sent.clone(),
318        ));
319        self.sends.insert(port.clone(), Send_ { tap, publisher, sent, tap_handle: handle, task });
320        Ok(())
321    }
322
323    fn start_receive(&mut self, c: &weirdnet_audio_route::Connection, node: NodeId) -> Result<(), RouteError> {
324        let input = format!("{}<net", c.id.0);
325        let config = lock(&self.router).config();
326        let handle = {
327            let mut router = lock(&self.router);
328            let handle = router.add_input(&input, config.sample_rate as usize).map_err(|e| RouteError::Denied(e.to_string()))?;
329            if let Err(e) = router.connect(Route::new(&input, c.to.as_str()).gain_db(c.gain_db)) {
330                let _ = router.remove(&input);
331                return Err(RouteError::Denied(e.to_string()));
332            }
333            handle
334        };
335        let report = Arc::new(Mutex::new(LinkReport::new(c.id.clone(), c.from.clone(), c.to.clone(), LinkDir::Receive)));
336        let link = ReceiveLink {
337            node: self.node.clone(),
338            peers: self.peers.clone(),
339            remote: node,
340            stream: StreamId::new(c.from.as_str()),
341            input: handle,
342            rate: config.sample_rate,
343            channels: config.channels,
344            clock: self.clock.clone(),
345            opts: self.opts,
346            report: report.clone(),
347        };
348        let task = self.rt.spawn(link.run());
349        self.receives.insert(c.id.clone(), Receive { input, to: c.to.clone(), gain_db: c.gain_db, report, task });
350        Ok(())
351    }
352}
353
354impl<Q: Message, R: Message> Executor for RemoteExecutor<Q, R> {
355    /// Starts and stops sends and receives to match the enabled connections with one end here and one elsewhere, and updates
356    /// gains. A link that cannot reach its other end keeps trying, with its state in [`RemoteExecutor::reports`]; an error means
357    /// this router refused an endpoint or route.
358    fn apply(&mut self, graph: &Graph) -> Result<(), RouteError> {
359        let here = |p: &PortId| lock(&self.router).kind(p.as_str()).is_some();
360        let mut sends = BTreeSet::new();
361        let mut send_links = Vec::new();
362        let mut receives = BTreeMap::new();
363        for c in graph.connections().filter(|c| c.enabled) {
364            match (here(&c.from), here(&c.to)) {
365                (true, false) => {
366                    sends.insert(c.from.clone());
367                    send_links.push((c.id.clone(), c.from.clone(), c.to.clone()));
368                }
369                (false, true) => {
370                    let node = graph.port(&c.from).map(|p| p.node.clone()).ok_or_else(|| RouteError::UnknownPort(c.from.clone()))?;
371                    receives.insert(c.id.clone(), (c.clone(), node));
372                }
373                _ => {}
374            }
375        }
376        for p in self.sends.keys().filter(|p| !sends.contains(*p)).cloned().collect::<Vec<_>>() {
377            self.stop_send(&p);
378        }
379        for p in sends.iter().filter(|p| !self.sends.contains_key(*p)).cloned().collect::<Vec<_>>() {
380            self.start_send(&p)?;
381        }
382        self.send_links = send_links;
383        let gone: Vec<ConnectionId> =
384            self.receives.iter().filter(|(id, r)| receives.get(*id).is_none_or(|(c, _)| c.to != r.to)).map(|(id, _)| id.clone()).collect();
385        for id in gone {
386            self.stop_receive(&id);
387        }
388        for (id, (c, node)) in receives {
389            match self.receives.get_mut(&id) {
390                Some(r) if r.gain_db != c.gain_db => {
391                    lock(&self.router)
392                        .connect(Route::new(&r.input, c.to.as_str()).gain_db(c.gain_db))
393                        .map_err(|e| RouteError::Denied(e.to_string()))?;
394                    r.gain_db = c.gain_db;
395                }
396                Some(_) => {}
397                None => self.start_receive(&c, node)?,
398            }
399        }
400        Ok(())
401    }
402}
403
404impl<Q: Message, R: Message> Drop for RemoteExecutor<Q, R> {
405    fn drop(&mut self) {
406        for p in self.sends.keys().cloned().collect::<Vec<_>>() {
407            self.stop_send(&p);
408        }
409        for id in self.receives.keys().cloned().collect::<Vec<_>>() {
410            self.stop_receive(&id);
411        }
412    }
413}
414
415#[allow(clippy::too_many_arguments)]
416async fn pump_send(
417    tap: RouterTap,
418    port: PortId,
419    rate: u32,
420    channels: u16,
421    frame_frames: usize,
422    hold: Duration,
423    clock: ClockFn,
424    hub: Arc<Hub>,
425    slot: Arc<Mutex<Option<Publisher>>>,
426    sent: Arc<AtomicU64>,
427) {
428    let ch = usize::from(channels.max(1));
429    let per = frame_frames.max(1) * ch;
430    let mut scratch = vec![0.0f32; 8192 * ch];
431    let mut acc: Vec<f32> = Vec::with_capacity(per * 4);
432    let (mut seq, mut pts) = (0u64, 0u64);
433    // The clock at the first sample: a block's samples are all made when the block is rendered, so the newest block read now
434    // was made about now, and the first sample as long before as everything read earlier lasts. The smallest reading of each
435    // second is the one least delayed by this pump (one block read right after it was rendered), and is sent again every
436    // second so receivers follow this side's audio clock.
437    let mut read = 0u64;
438    let mut best = u64::MAX;
439    let mut resend = tokio::time::Instant::now() + Duration::from_secs(1);
440    let mut tick = tokio::time::interval(Duration::from_millis(2));
441    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
442    let mut held: std::collections::VecDeque<(tokio::time::Instant, Frame)> = std::collections::VecDeque::new();
443    loop {
444        tick.tick().await;
445        let now = tokio::time::Instant::now();
446        while held.front().is_some_and(|(at, _)| *at <= now) {
447            let (_, f) = held.pop_front().expect("a held frame");
448            if let Some(p) = lock(&slot).as_ref() {
449                let _ = p.send(f);
450            }
451        }
452        let n = tap.read(&mut scratch);
453        if n == 0 {
454            continue;
455        }
456        let epoch = clock().saturating_sub(read * 1_000_000_000 / u64::from(rate));
457        read += (n / ch) as u64;
458        best = best.min(epoch);
459        let info = |epoch: u64| {
460            let mut info = StreamInfo::pcm_f32(port.as_str(), port.as_str(), rate, channels);
461            info.params.push((EPOCH_PARAM.into(), epoch.to_string()));
462            info
463        };
464        if lock(&slot).is_none() {
465            let p = Publisher::new(info(epoch));
466            hub.publish(&p);
467            *lock(&slot) = Some(p);
468        } else if tokio::time::Instant::now() >= resend {
469            if let Some(p) = lock(&slot).as_ref() {
470                p.set_info(info(best));
471            }
472            best = u64::MAX;
473            resend += Duration::from_secs(1);
474        }
475        acc.extend_from_slice(&scratch[..n]);
476        let p = lock(&slot).clone().expect("published");
477        while acc.len() >= per {
478            let f = Frame::pcm_f32(seq, pts, channels, &acc[..per]);
479            if hold.is_zero() {
480                let _ = p.send(f);
481            } else {
482                held.push_back((now + hold, f));
483            }
484            acc.drain(..per);
485            seq += 1;
486            pts += frame_frames as u64;
487            sent.fetch_add(frame_frames as u64, Ordering::Relaxed);
488        }
489    }
490}
491
492struct ReceiveLink<Q: Message, R: Message> {
493    node: Arc<Node<Q, R>>,
494    peers: Arc<dyn Peers>,
495    remote: NodeId,
496    stream: StreamId,
497    input: RouterInput,
498    rate: u32,
499    channels: u16,
500    clock: ClockFn,
501    opts: RemoteOptions,
502    report: Arc<Mutex<LinkReport>>,
503}
504
505/// Converts interleaved `input` with `from` channels into `out` with `to` channels: mono is copied to every channel, many to
506/// mono is averaged, otherwise channels are matched in order and the rest are silent.
507fn map_channels(input: &[f32], from: usize, to: usize, out: &mut Vec<f32>) {
508    out.clear();
509    for f in input.chunks_exact(from) {
510        for c in 0..to {
511            out.push(if from == to {
512                f[c]
513            } else if from == 1 {
514                f[0]
515            } else if to == 1 {
516                f.iter().sum::<f32>() / from as f32
517            } else {
518                f.get(c).copied().unwrap_or(0.0)
519            });
520        }
521    }
522}
523
524impl<Q: Message, R: Message> ReceiveLink<Q, R> {
525    fn set_state(&self, s: LinkState) {
526        lock(&self.report).state = s;
527    }
528
529    async fn run(self) {
530        loop {
531            let Some((peer, addrs)) = self.peers.locate(&self.remote) else {
532                self.set_state(LinkState::Waiting(format!("{} is not reachable", self.remote)));
533                tokio::time::sleep(self.opts.retry).await;
534                continue;
535            };
536            // measured before subscribing, so frames do not pile up behind the first measurement
537            let first = clock::measure(&self.node, peer, &addrs, &self.clock, 5).await.ok();
538            match Subscriber::connect(&self.node, peer, &addrs, &self.stream, SubscribeOptions::default()).await {
539                Ok(sub) => {
540                    let why = self.carry(sub, peer, &addrs, first).await;
541                    self.set_state(LinkState::Waiting(why));
542                }
543                Err(StreamError::Refused(r)) => {
544                    self.set_state(LinkState::Denied(r));
545                    tokio::time::sleep(self.opts.retry * 8).await;
546                    continue;
547                }
548                Err(e) => self.set_state(LinkState::Waiting(e.to_string())),
549            }
550            tokio::time::sleep(self.opts.retry).await;
551        }
552    }
553
554    /// Carries one subscription until it ends; returns why it stopped.
555    async fn carry(&self, mut sub: Subscriber, peer: PeerId, addrs: &[Multiaddr], first: Option<clock::ClockSample>) -> String {
556        let info = sub.info().clone();
557        let param = |k: &str| info.param(k).and_then(|v| v.parse::<u64>().ok());
558        let (Some(from_rate), Some(from_ch)) = (param("sample_rate"), param("channels")) else { return "the stream is not raw PCM".into() };
559        let mut epoch = param(EPOCH_PARAM);
560        let (from_rate, from_ch) = (from_rate as u32, (from_ch as usize).max(1));
561        let ch = usize::from(self.channels.max(1));
562        let Ok(mut rs) = Resampler::new(from_rate, self.rate, self.channels) else { return "bad sample rates".into() };
563        let per_ms = f64::from(self.rate) / 1000.0;
564        // the buffer to aim at, and whether that meets the alignment asked for
565        let aim = |transit: Option<f64>| -> (f64, Option<bool>) {
566            match (self.opts.align_ms, transit) {
567                (Some(a), Some(t)) => {
568                    let want = a - t;
569                    (want.max(MIN_BUFFER_MS) * per_ms, Some(want >= MIN_BUFFER_MS))
570                }
571                (Some(a), None) => ((a.max(MIN_BUFFER_MS)) * per_ms, None),
572                (None, _) => ((self.opts.playout_ms * per_ms).max(1.0), None),
573            }
574        };
575        let (mut target, mut aligned) = aim(None);
576        // frames still to drop after a hard correction down
577        let mut drop_owed = 0usize;
578        let mut fit = DriftFit::new(16);
579        fit.extend(first);
580        let mut mapped = Vec::new();
581        let mut out = vec![0.0f32; 4096 * ch];
582        let mut prime: Vec<f32> = Vec::new();
583        let mut primed = false;
584        let (mut level, mut integral) = (target, 0.0f64);
585        // the queue's low and high marks over a window: their middle is the level whatever the arrival bursts look like
586        let (mut low, mut high, mut window) = (f64::MAX, 0.0f64, 0.0f64);
587        // the trim averaged over about four seconds
588        let mut mean_trim: Option<f64> = None;
589        let mut transit: Option<f64> = None;
590        let mut next_clock = tokio::time::Instant::now() + self.opts.clock_every;
591        let mut gaps = 0u64;
592        let mut frames = 0u64;
593        self.set_state(LinkState::Live);
594        loop {
595            if tokio::time::Instant::now() >= next_clock {
596                if let Ok(s) = clock::measure(&self.node, peer, addrs, &self.clock, 5).await {
597                    fit.push(s);
598                }
599                next_clock = tokio::time::Instant::now() + self.opts.clock_every;
600            }
601            let ev = match tokio::time::timeout(self.opts.clock_every, sub.next()).await {
602                Ok(Some(ev)) => ev,
603                Ok(None) => return "the stream stopped".into(),
604                Err(_) => continue,
605            };
606            let f = match ev {
607                StreamEvent::Frame(f) => f,
608                StreamEvent::Gap { missed } => {
609                    gaps += missed;
610                    continue;
611                }
612                StreamEvent::InfoChanged(i) => {
613                    let same = |k: &str| i.param(k) == info.param(k);
614                    if !(same("sample_rate") && same("channels") && i.codec == info.codec) {
615                        return "the stream's format changed".into();
616                    }
617                    epoch = i.param(EPOCH_PARAM).and_then(|v| v.parse().ok());
618                    continue;
619                }
620                StreamEvent::Ended => return "the stream ended".into(),
621            };
622            let now = (self.clock)();
623            if let (Some(epoch), Some(offset)) = (epoch, fit.offset_at(now)) {
624                let sent_remote = epoch as f64 + f.pts as f64 * 1e9 / f64::from(from_rate) + f64::from(f.duration) * 1e9 / f64::from(from_rate);
625                let ms = (now as f64 - (sent_remote - offset as f64)) / 1e6;
626                transit = Some(match transit {
627                    Some(t) => t + 0.1 * (ms - t),
628                    None => ms,
629                });
630            }
631            map_channels(&f.f32_samples(), from_ch, ch, &mut mapped);
632            let mut rest = &mapped[..];
633            let mut produced: Vec<f32> = Vec::with_capacity(rest.len() * 2 + 64);
634            loop {
635                let (used, written) = rs.process(rest, &mut out);
636                produced.extend_from_slice(&out[..written * ch]);
637                rest = &rest[used * ch..];
638                if written == out.len() / ch {
639                    continue;
640                }
641                if rest.is_empty() || used == 0 {
642                    break;
643                }
644            }
645            frames += u64::from(f.duration);
646            if drop_owed > 0 {
647                let n = drop_owed.min(produced.len() / ch);
648                produced.drain(..n * ch);
649                drop_owed -= n;
650            }
651            let queued = self.input.queued() / ch;
652            if !primed {
653                prime.extend_from_slice(&produced);
654                if prime.len() / ch >= target as usize {
655                    self.input.push(&prime);
656                    prime.clear();
657                    primed = true;
658                    level = target;
659                    integral = 0.0;
660                    (low, high, window) = (f64::MAX, 0.0, 0.0);
661                }
662            } else if queued == 0 {
663                // ran dry: build the buffer up again
664                primed = false;
665                prime.extend_from_slice(&produced);
666            } else if queued as f64 > target * 2.0 {
667                // far too much (a backlog arrived at once, or this side stalled): drop this frame rather than add delay
668            } else {
669                self.input.push(&produced);
670                low = low.min(queued as f64);
671                high = high.max((queued + produced.len() / ch) as f64);
672                window += f64::from(f.duration) / f64::from(from_rate);
673                if window >= 0.25 {
674                    level += 0.5 * ((low + high) / 2.0 - level);
675                    (target, aligned) = aim(transit);
676                    // far off (the start, or a new alignment): correct at once, by dropping or by adding silence
677                    let dev = level - target;
678                    if dev.abs() > 10.0 * per_ms {
679                        if dev > 0.0 {
680                            drop_owed += dev as usize;
681                        } else {
682                            self.input.push(&vec![0.0; (-dev) as usize * ch]);
683                        }
684                        level = target;
685                    }
686                    let err = (level - target) / target;
687                    // proportional and integral, the integral held while the trim is at its limit and the error would push it further
688                    let limit = MAX_TRIM / 10.0;
689                    let raw = 1.0 - 2e-2 * err - 2.5e-3 * integral;
690                    if (raw - 1.0).abs() < limit || (raw > 1.0) == (err > 0.0) {
691                        integral = (integral + err * window).clamp(-1.0, 1.0);
692                    }
693                    let trim = (1.0 - 2e-2 * err - 2.5e-3 * integral).clamp(1.0 - limit, 1.0 + limit);
694                    rs.set_trim(trim);
695                    let ppm = (1.0 / trim - 1.0) * 1e6;
696                    mean_trim = Some(mean_trim.map_or(ppm, |m| m + 0.0625 * (ppm - m)));
697                    (low, high, window) = (f64::MAX, 0.0, 0.0);
698                }
699            }
700            let mut r = lock(&self.report);
701            r.state = LinkState::Live;
702            r.transit_ms = transit;
703            r.buffer_frames = queued;
704            r.delay_frames = transit.map(|t| (t / 1000.0 * f64::from(self.rate) + queued as f64 + rs.pending() * rs.ratio()).max(0.0).round() as u32);
705            r.clock_offset_ns = fit.offset_at(now);
706            r.clock_drift_ppm = fit.drift_ppm();
707            r.trim_ppm = mean_trim.unwrap_or(0.0);
708            r.frames = frames;
709            r.lost = self.input.lost();
710            r.gaps = gaps;
711            r.target_frames = target as usize;
712            r.aligned = aligned;
713            r.sender_epoch_ns = epoch;
714        }
715    }
716}
717
718#[cfg(test)]
719mod tests {
720    use super::map_channels;
721
722    #[test]
723    fn channels_map_mono_to_stereo_and_stereo_to_mono() {
724        let mut out = Vec::new();
725        map_channels(&[1.0, 2.0], 1, 2, &mut out);
726        assert_eq!(out, [1.0, 1.0, 2.0, 2.0]);
727        map_channels(&[1.0, 3.0], 2, 1, &mut out);
728        assert_eq!(out, [2.0]);
729        map_channels(&[1.0, 2.0, 3.0], 3, 2, &mut out);
730        assert_eq!(out, [1.0, 2.0]);
731    }
732}