weirdnet-audio-stream 0.3.0

General-purpose audio streaming for Weirdnet: publish and subscribe to live or recorded streams of codec-agnostic frames, many listeners with their own bounded queues, seeking, arrival statistics and per-subscription authorisation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//! A remote executor (feature `route`): the connections of a `weirdnet_audio_route` graph between this node's
//! `weirdnet_audio_engine` router and other nodes.
//!
//! 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
//! 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
//! received: a subscription to that port's stream on the node that has it goes through a resampler into a router input, routed
//! to the port with the connection's gain. Connections with both ends here are left to the router's own executor, and the
//! router's own wiring is never touched.
//!
//! Receiving keeps about [`RemoteOptions::playout_ms`] of audio queued, which absorbs network jitter, and trims the resampler's
//! ratio to hold that level, which follows the sender's audio clock running a little fast or slow. The sender's clock is measured
//! with [`crate::clock`], and every link reports its transit time, buffer, total delay and drift in a [`LinkReport`]; an app
//! writes the delay into the graph with `Graph::set_measured_delay`.
//!
//! Who may subscribe is decided by the [`StreamAuth`] the executor serves its hub with, so a connection the sender's
//! permissions refuse is reported as [`LinkState::Denied`] and carries nothing.

use crate::Publisher;
use crate::clock::{self, ClockFn, DriftFit};
use crate::net::{Hub, Server, StreamAuth, Subscriber, serve};
use crate::types::{Frame, StreamError, StreamEvent, StreamId, StreamInfo, SubscribeOptions};
use std::collections::{BTreeMap, BTreeSet};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Duration;
use weirdnet_audio_engine::router::{Route, RouterControl, RouterInput, RouterTap};
use weirdnet_audio_route::{ConnectionId, Executor, Graph, NodeId, PortId, RouteError};
use weirdnet_dsp::resample::{MAX_TRIM, Resampler};
use weirdnet_net::{Message, Multiaddr, Node, PeerId};

/// The stream parameter carrying the sender's clock reading, in nanoseconds, at the stream's first sample.
pub const EPOCH_PARAM: &str = "epoch_ns";

/// Where other nodes are.
pub trait Peers: Send + Sync {
    /// The peer serving `node`'s streams and its addresses, or `None` while it cannot be reached.
    fn locate(&self, node: &NodeId) -> Option<(PeerId, Vec<Multiaddr>)>;
}

impl<F: Fn(&NodeId) -> Option<(PeerId, Vec<Multiaddr>)> + Send + Sync> Peers for F {
    fn locate(&self, node: &NodeId) -> Option<(PeerId, Vec<Multiaddr>)> {
        self(node)
    }
}

/// Tuning.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RemoteOptions {
    /// Audio kept queued on the receiving side, milliseconds.
    pub playout_ms: f64,
    /// Frames per sent stream frame.
    pub frame_frames: usize,
    /// How often the sender's clock is measured.
    pub clock_every: Duration,
    /// How long to wait before trying a link again.
    pub retry: Duration,
    /// Align every received link to this whole delay, milliseconds: each link's buffer becomes this minus its transit (at least
    /// [`MIN_BUFFER_MS`]), so audio made at the same moment on different nodes leaves this router's inputs together. `None` keeps
    /// [`RemoteOptions::playout_ms`] of buffer on every link.
    pub align_ms: Option<f64>,
    /// Holds every sent frame this long before sending it, milliseconds: a longer network path, for tests and demonstrations.
    pub send_hold_ms: f64,
}

/// The least buffer a link keeps when aligning, milliseconds.
pub const MIN_BUFFER_MS: f64 = 10.0;

impl Default for RemoteOptions {
    fn default() -> Self {
        RemoteOptions {
            playout_ms: 40.0,
            frame_frames: 240,
            clock_every: Duration::from_secs(2),
            retry: Duration::from_millis(250),
            align_ms: None,
            send_hold_ms: 0.0,
        }
    }
}

/// Which way a link carries audio.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LinkDir {
    /// From a port here to another node.
    Send,
    /// From another node to a port here.
    Receive,
}

/// How a link is doing.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LinkState {
    /// Not carrying audio yet, and why.
    Waiting(String),
    /// Carrying audio.
    Live,
    /// The sender refused the subscription, with its reason.
    Denied(String),
}

/// One link's numbers.
#[derive(Clone, Debug, PartialEq)]
pub struct LinkReport {
    /// The graph connection.
    pub connection: ConnectionId,
    /// Its output.
    pub from: PortId,
    /// Its input.
    pub to: PortId,
    /// Send or receive.
    pub dir: LinkDir,
    /// The state. A send is live while anyone listens to its port.
    pub state: LinkState,
    /// Receive: how long a sample takes from the sender's router to arrival here (clock offset removed), milliseconds.
    pub transit_ms: Option<f64>,
    /// Receive: frames queued for playout, at this router's rate.
    pub buffer_frames: usize,
    /// Receive: the whole delay from the sender's router to this router's input, frames at this router's rate.
    pub delay_frames: Option<u32>,
    /// Receive: the sender's clock minus this one, nanoseconds.
    pub clock_offset_ns: Option<i64>,
    /// Receive: how much faster the sender's clock runs, parts per million.
    pub clock_drift_ppm: Option<f64>,
    /// Receive: how much faster the sender's audio runs than this router's, as the resampler trim holding the buffer level
    /// shows it averaged over about four seconds, parts per million.
    pub trim_ppm: f64,
    /// Frames carried.
    pub frames: u64,
    /// Samples lost: dropped or missing at the router.
    pub lost: u64,
    /// Receive: stream frames missing on arrival.
    pub gaps: u64,
    /// Receive: the buffer the link aims at, frames at this router's rate.
    pub target_frames: usize,
    /// Receive: whether the link meets [`RemoteOptions::align_ms`] (false when its transit leaves less than [`MIN_BUFFER_MS`]).
    pub aligned: Option<bool>,
    /// Receive: the sender's clock at its stream's first sample, nanoseconds of the sender's clock.
    pub sender_epoch_ns: Option<u64>,
}

impl LinkReport {
    fn new(connection: ConnectionId, from: PortId, to: PortId, dir: LinkDir) -> LinkReport {
        LinkReport {
            connection,
            from,
            to,
            dir,
            state: LinkState::Waiting("starting".into()),
            transit_ms: None,
            buffer_frames: 0,
            delay_frames: None,
            clock_offset_ns: None,
            clock_drift_ppm: None,
            trim_ppm: 0.0,
            frames: 0,
            lost: 0,
            gaps: 0,
            target_frames: 0,
            aligned: None,
            sender_epoch_ns: None,
        }
    }
}

fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
    m.lock().unwrap_or_else(|e| e.into_inner())
}

struct Send_ {
    tap: String,
    publisher: Arc<Mutex<Option<Publisher>>>,
    sent: Arc<AtomicU64>,
    tap_handle: RouterTap,
    task: tokio::task::JoinHandle<()>,
}

struct Receive {
    input: String,
    to: PortId,
    gain_db: f32,
    report: Arc<Mutex<LinkReport>>,
    task: tokio::task::JoinHandle<()>,
}

/// Carries a graph's connections between this node's router and other nodes.
pub struct RemoteExecutor<Q: Message, R: Message> {
    node: Arc<Node<Q, R>>,
    router: Arc<Mutex<RouterControl>>,
    hub: Arc<Hub>,
    peers: Arc<dyn Peers>,
    clock: ClockFn,
    rt: tokio::runtime::Handle,
    opts: RemoteOptions,
    sends: BTreeMap<PortId, Send_>,
    send_links: Vec<(ConnectionId, PortId, PortId)>,
    receives: BTreeMap<ConnectionId, Receive>,
    _server: Server,
    _clock_server: clock::ClockServer,
}

impl<Q: Message, R: Message> RemoteExecutor<Q, R> {
    /// Serves this node's sent ports (asking `auth` about each subscriber) and its clock on `node`, and receives through
    /// `router`. `clock` should be the clock the audio runs on, or [`clock::monotonic`].
    pub fn start(
        node: Arc<Node<Q, R>>,
        router: Arc<Mutex<RouterControl>>,
        peers: Arc<dyn Peers>,
        auth: Arc<dyn StreamAuth>,
        clock: ClockFn,
        rt: tokio::runtime::Handle,
        opts: RemoteOptions,
    ) -> Result<Self, StreamError> {
        let _g = rt.enter();
        let hub = Arc::new(Hub::new());
        let server = serve(&node, hub.clone(), auth)?;
        let clock_server = clock::serve_clock(&node, clock.clone())?;
        Ok(RemoteExecutor {
            node,
            router,
            hub,
            peers,
            clock,
            rt,
            opts,
            sends: BTreeMap::new(),
            send_links: Vec::new(),
            receives: BTreeMap::new(),
            _server: server,
            _clock_server: clock_server,
        })
    }

    /// Every link's numbers, sends first, in connection order.
    pub fn reports(&self) -> Vec<LinkReport> {
        let mut v = Vec::new();
        for (c, from, to) in &self.send_links {
            let mut r = LinkReport::new(c.clone(), from.clone(), to.clone(), LinkDir::Send);
            if let Some(s) = self.sends.get(from) {
                let listeners = lock(&s.publisher).as_ref().map(|p| p.listeners().len()).unwrap_or(0);
                r.state = if listeners > 0 { LinkState::Live } else { LinkState::Waiting("no listener".into()) };
                r.frames = s.sent.load(Ordering::Relaxed);
                r.lost = s.tap_handle.lost();
            }
            v.push(r);
        }
        v.extend(self.receives.values().map(|r| lock(&r.report).clone()));
        v
    }

    fn stop_send(&mut self, port: &PortId) {
        if let Some(s) = self.sends.remove(port) {
            s.task.abort();
            if let Some(p) = lock(&s.publisher).take() {
                p.finish();
            }
            self.hub.remove(&StreamId::new(port.as_str()));
            let _ = lock(&self.router).remove(&s.tap);
        }
    }

    fn stop_receive(&mut self, id: &ConnectionId) {
        if let Some(r) = self.receives.remove(id) {
            r.task.abort();
            let _ = lock(&self.router).remove(&r.input);
        }
    }

    fn start_send(&mut self, port: &PortId) -> Result<(), RouteError> {
        let tap = format!("{}>net", port.as_str());
        let config = lock(&self.router).config();
        let handle = {
            let mut router = lock(&self.router);
            let handle = router.add_tap(&tap, config.sample_rate as usize).map_err(|e| RouteError::Denied(e.to_string()))?;
            if let Err(e) = router.connect(Route::new(port.as_str(), &tap)) {
                let _ = router.remove(&tap);
                return Err(RouteError::Denied(e.to_string()));
            }
            handle
        };
        let publisher = Arc::new(Mutex::new(None));
        let sent = Arc::new(AtomicU64::new(0));
        let task = self.rt.spawn(pump_send(
            handle.clone(),
            port.clone(),
            config.sample_rate,
            config.channels,
            self.opts.frame_frames,
            Duration::from_secs_f64(self.opts.send_hold_ms.max(0.0) / 1000.0),
            self.clock.clone(),
            self.hub.clone(),
            publisher.clone(),
            sent.clone(),
        ));
        self.sends.insert(port.clone(), Send_ { tap, publisher, sent, tap_handle: handle, task });
        Ok(())
    }

    fn start_receive(&mut self, c: &weirdnet_audio_route::Connection, node: NodeId) -> Result<(), RouteError> {
        let input = format!("{}<net", c.id.0);
        let config = lock(&self.router).config();
        let handle = {
            let mut router = lock(&self.router);
            let handle = router.add_input(&input, config.sample_rate as usize).map_err(|e| RouteError::Denied(e.to_string()))?;
            if let Err(e) = router.connect(Route::new(&input, c.to.as_str()).gain_db(c.gain_db)) {
                let _ = router.remove(&input);
                return Err(RouteError::Denied(e.to_string()));
            }
            handle
        };
        let report = Arc::new(Mutex::new(LinkReport::new(c.id.clone(), c.from.clone(), c.to.clone(), LinkDir::Receive)));
        let link = ReceiveLink {
            node: self.node.clone(),
            peers: self.peers.clone(),
            remote: node,
            stream: StreamId::new(c.from.as_str()),
            input: handle,
            rate: config.sample_rate,
            channels: config.channels,
            clock: self.clock.clone(),
            opts: self.opts,
            report: report.clone(),
        };
        let task = self.rt.spawn(link.run());
        self.receives.insert(c.id.clone(), Receive { input, to: c.to.clone(), gain_db: c.gain_db, report, task });
        Ok(())
    }
}

impl<Q: Message, R: Message> Executor for RemoteExecutor<Q, R> {
    /// Starts and stops sends and receives to match the enabled connections with one end here and one elsewhere, and updates
    /// gains. A link that cannot reach its other end keeps trying, with its state in [`RemoteExecutor::reports`]; an error means
    /// this router refused an endpoint or route.
    fn apply(&mut self, graph: &Graph) -> Result<(), RouteError> {
        let here = |p: &PortId| lock(&self.router).kind(p.as_str()).is_some();
        let mut sends = BTreeSet::new();
        let mut send_links = Vec::new();
        let mut receives = BTreeMap::new();
        for c in graph.connections().filter(|c| c.enabled) {
            match (here(&c.from), here(&c.to)) {
                (true, false) => {
                    sends.insert(c.from.clone());
                    send_links.push((c.id.clone(), c.from.clone(), c.to.clone()));
                }
                (false, true) => {
                    let node = graph.port(&c.from).map(|p| p.node.clone()).ok_or_else(|| RouteError::UnknownPort(c.from.clone()))?;
                    receives.insert(c.id.clone(), (c.clone(), node));
                }
                _ => {}
            }
        }
        for p in self.sends.keys().filter(|p| !sends.contains(*p)).cloned().collect::<Vec<_>>() {
            self.stop_send(&p);
        }
        for p in sends.iter().filter(|p| !self.sends.contains_key(*p)).cloned().collect::<Vec<_>>() {
            self.start_send(&p)?;
        }
        self.send_links = send_links;
        let gone: Vec<ConnectionId> =
            self.receives.iter().filter(|(id, r)| receives.get(*id).is_none_or(|(c, _)| c.to != r.to)).map(|(id, _)| id.clone()).collect();
        for id in gone {
            self.stop_receive(&id);
        }
        for (id, (c, node)) in receives {
            match self.receives.get_mut(&id) {
                Some(r) if r.gain_db != c.gain_db => {
                    lock(&self.router)
                        .connect(Route::new(&r.input, c.to.as_str()).gain_db(c.gain_db))
                        .map_err(|e| RouteError::Denied(e.to_string()))?;
                    r.gain_db = c.gain_db;
                }
                Some(_) => {}
                None => self.start_receive(&c, node)?,
            }
        }
        Ok(())
    }
}

impl<Q: Message, R: Message> Drop for RemoteExecutor<Q, R> {
    fn drop(&mut self) {
        for p in self.sends.keys().cloned().collect::<Vec<_>>() {
            self.stop_send(&p);
        }
        for id in self.receives.keys().cloned().collect::<Vec<_>>() {
            self.stop_receive(&id);
        }
    }
}

#[allow(clippy::too_many_arguments)]
async fn pump_send(
    tap: RouterTap,
    port: PortId,
    rate: u32,
    channels: u16,
    frame_frames: usize,
    hold: Duration,
    clock: ClockFn,
    hub: Arc<Hub>,
    slot: Arc<Mutex<Option<Publisher>>>,
    sent: Arc<AtomicU64>,
) {
    let ch = usize::from(channels.max(1));
    let per = frame_frames.max(1) * ch;
    let mut scratch = vec![0.0f32; 8192 * ch];
    let mut acc: Vec<f32> = Vec::with_capacity(per * 4);
    let (mut seq, mut pts) = (0u64, 0u64);
    // The clock at the first sample, as now minus what has been read so far; the smallest reading of each second is the one
    // least delayed by this pump, and is sent again every second so receivers follow this side's audio clock.
    let mut read = 0u64;
    let mut best = u64::MAX;
    let mut resend = tokio::time::Instant::now() + Duration::from_secs(1);
    let mut tick = tokio::time::interval(Duration::from_millis(2));
    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
    let mut held: std::collections::VecDeque<(tokio::time::Instant, Frame)> = std::collections::VecDeque::new();
    loop {
        tick.tick().await;
        let now = tokio::time::Instant::now();
        while held.front().is_some_and(|(at, _)| *at <= now) {
            let (_, f) = held.pop_front().expect("a held frame");
            if let Some(p) = lock(&slot).as_ref() {
                let _ = p.send(f);
            }
        }
        let n = tap.read(&mut scratch);
        if n == 0 {
            continue;
        }
        read += (n / ch) as u64;
        let epoch = clock().saturating_sub(read * 1_000_000_000 / u64::from(rate));
        best = best.min(epoch);
        let info = |epoch: u64| {
            let mut info = StreamInfo::pcm_f32(port.as_str(), port.as_str(), rate, channels);
            info.params.push((EPOCH_PARAM.into(), epoch.to_string()));
            info
        };
        if lock(&slot).is_none() {
            let p = Publisher::new(info(epoch));
            hub.publish(&p);
            *lock(&slot) = Some(p);
        } else if tokio::time::Instant::now() >= resend {
            if let Some(p) = lock(&slot).as_ref() {
                p.set_info(info(best));
            }
            best = u64::MAX;
            resend += Duration::from_secs(1);
        }
        acc.extend_from_slice(&scratch[..n]);
        let p = lock(&slot).clone().expect("published");
        while acc.len() >= per {
            let f = Frame::pcm_f32(seq, pts, channels, &acc[..per]);
            if hold.is_zero() {
                let _ = p.send(f);
            } else {
                held.push_back((now + hold, f));
            }
            acc.drain(..per);
            seq += 1;
            pts += frame_frames as u64;
            sent.fetch_add(frame_frames as u64, Ordering::Relaxed);
        }
    }
}

struct ReceiveLink<Q: Message, R: Message> {
    node: Arc<Node<Q, R>>,
    peers: Arc<dyn Peers>,
    remote: NodeId,
    stream: StreamId,
    input: RouterInput,
    rate: u32,
    channels: u16,
    clock: ClockFn,
    opts: RemoteOptions,
    report: Arc<Mutex<LinkReport>>,
}

/// Converts interleaved `input` with `from` channels into `out` with `to` channels: mono is copied to every channel, many to
/// mono is averaged, otherwise channels are matched in order and the rest are silent.
fn map_channels(input: &[f32], from: usize, to: usize, out: &mut Vec<f32>) {
    out.clear();
    for f in input.chunks_exact(from) {
        for c in 0..to {
            out.push(if from == to {
                f[c]
            } else if from == 1 {
                f[0]
            } else if to == 1 {
                f.iter().sum::<f32>() / from as f32
            } else {
                f.get(c).copied().unwrap_or(0.0)
            });
        }
    }
}

impl<Q: Message, R: Message> ReceiveLink<Q, R> {
    fn set_state(&self, s: LinkState) {
        lock(&self.report).state = s;
    }

    async fn run(self) {
        loop {
            let Some((peer, addrs)) = self.peers.locate(&self.remote) else {
                self.set_state(LinkState::Waiting(format!("{} is not reachable", self.remote)));
                tokio::time::sleep(self.opts.retry).await;
                continue;
            };
            // measured before subscribing, so frames do not pile up behind the first measurement
            let first = clock::measure(&self.node, peer, &addrs, &self.clock, 5).await.ok();
            match Subscriber::connect(&self.node, peer, &addrs, &self.stream, SubscribeOptions::default()).await {
                Ok(sub) => {
                    let why = self.carry(sub, peer, &addrs, first).await;
                    self.set_state(LinkState::Waiting(why));
                }
                Err(StreamError::Refused(r)) => {
                    self.set_state(LinkState::Denied(r));
                    tokio::time::sleep(self.opts.retry * 8).await;
                    continue;
                }
                Err(e) => self.set_state(LinkState::Waiting(e.to_string())),
            }
            tokio::time::sleep(self.opts.retry).await;
        }
    }

    /// Carries one subscription until it ends; returns why it stopped.
    async fn carry(&self, mut sub: Subscriber, peer: PeerId, addrs: &[Multiaddr], first: Option<clock::ClockSample>) -> String {
        let info = sub.info().clone();
        let param = |k: &str| info.param(k).and_then(|v| v.parse::<u64>().ok());
        let (Some(from_rate), Some(from_ch)) = (param("sample_rate"), param("channels")) else { return "the stream is not raw PCM".into() };
        let mut epoch = param(EPOCH_PARAM);
        let (from_rate, from_ch) = (from_rate as u32, (from_ch as usize).max(1));
        let ch = usize::from(self.channels.max(1));
        let Ok(mut rs) = Resampler::new(from_rate, self.rate, self.channels) else { return "bad sample rates".into() };
        let per_ms = f64::from(self.rate) / 1000.0;
        // the buffer to aim at, and whether that meets the alignment asked for
        let aim = |transit: Option<f64>| -> (f64, Option<bool>) {
            match (self.opts.align_ms, transit) {
                (Some(a), Some(t)) => {
                    let want = a - t;
                    (want.max(MIN_BUFFER_MS) * per_ms, Some(want >= MIN_BUFFER_MS))
                }
                (Some(a), None) => ((a.max(MIN_BUFFER_MS)) * per_ms, None),
                (None, _) => ((self.opts.playout_ms * per_ms).max(1.0), None),
            }
        };
        let (mut target, mut aligned) = aim(None);
        // frames still to drop after a hard correction down
        let mut drop_owed = 0usize;
        let mut fit = DriftFit::new(16);
        fit.extend(first);
        let mut mapped = Vec::new();
        let mut out = vec![0.0f32; 4096 * ch];
        let mut prime: Vec<f32> = Vec::new();
        let mut primed = false;
        let (mut level, mut integral) = (target, 0.0f64);
        // the queue's low and high marks over a window: their middle is the level whatever the arrival bursts look like
        let (mut low, mut high, mut window) = (f64::MAX, 0.0f64, 0.0f64);
        // the trim averaged over about four seconds
        let mut mean_trim: Option<f64> = None;
        let mut transit: Option<f64> = None;
        let mut next_clock = tokio::time::Instant::now() + self.opts.clock_every;
        let mut gaps = 0u64;
        let mut frames = 0u64;
        self.set_state(LinkState::Live);
        loop {
            if tokio::time::Instant::now() >= next_clock {
                if let Ok(s) = clock::measure(&self.node, peer, addrs, &self.clock, 5).await {
                    fit.push(s);
                }
                next_clock = tokio::time::Instant::now() + self.opts.clock_every;
            }
            let ev = match tokio::time::timeout(self.opts.clock_every, sub.next()).await {
                Ok(Some(ev)) => ev,
                Ok(None) => return "the stream stopped".into(),
                Err(_) => continue,
            };
            let f = match ev {
                StreamEvent::Frame(f) => f,
                StreamEvent::Gap { missed } => {
                    gaps += missed;
                    continue;
                }
                StreamEvent::InfoChanged(i) => {
                    let same = |k: &str| i.param(k) == info.param(k);
                    if !(same("sample_rate") && same("channels") && i.codec == info.codec) {
                        return "the stream's format changed".into();
                    }
                    epoch = i.param(EPOCH_PARAM).and_then(|v| v.parse().ok());
                    continue;
                }
                StreamEvent::Ended => return "the stream ended".into(),
            };
            let now = (self.clock)();
            if let (Some(epoch), Some(offset)) = (epoch, fit.offset_at(now)) {
                let sent_remote = epoch as f64 + f.pts as f64 * 1e9 / f64::from(from_rate) + f64::from(f.duration) * 1e9 / f64::from(from_rate);
                let ms = (now as f64 - (sent_remote - offset as f64)) / 1e6;
                transit = Some(match transit {
                    Some(t) => t + 0.1 * (ms - t),
                    None => ms,
                });
            }
            map_channels(&f.f32_samples(), from_ch, ch, &mut mapped);
            let mut rest = &mapped[..];
            let mut produced: Vec<f32> = Vec::with_capacity(rest.len() * 2 + 64);
            loop {
                let (used, written) = rs.process(rest, &mut out);
                produced.extend_from_slice(&out[..written * ch]);
                rest = &rest[used * ch..];
                if written == out.len() / ch {
                    continue;
                }
                if rest.is_empty() || used == 0 {
                    break;
                }
            }
            frames += u64::from(f.duration);
            if drop_owed > 0 {
                let n = drop_owed.min(produced.len() / ch);
                produced.drain(..n * ch);
                drop_owed -= n;
            }
            let queued = self.input.queued() / ch;
            if !primed {
                prime.extend_from_slice(&produced);
                if prime.len() / ch >= target as usize {
                    self.input.push(&prime);
                    prime.clear();
                    primed = true;
                    level = target;
                    integral = 0.0;
                    (low, high, window) = (f64::MAX, 0.0, 0.0);
                }
            } else if queued == 0 {
                // ran dry: build the buffer up again
                primed = false;
                prime.extend_from_slice(&produced);
            } else if queued as f64 > target * 2.0 {
                // far too much (a backlog arrived at once, or this side stalled): drop this frame rather than add delay
            } else {
                self.input.push(&produced);
                low = low.min(queued as f64);
                high = high.max((queued + produced.len() / ch) as f64);
                window += f64::from(f.duration) / f64::from(from_rate);
                if window >= 0.25 {
                    level += 0.5 * ((low + high) / 2.0 - level);
                    (target, aligned) = aim(transit);
                    // far off (the start, or a new alignment): correct at once, by dropping or by adding silence
                    let dev = level - target;
                    if dev.abs() > 10.0 * per_ms {
                        if dev > 0.0 {
                            drop_owed += dev as usize;
                        } else {
                            self.input.push(&vec![0.0; (-dev) as usize * ch]);
                        }
                        level = target;
                    }
                    let err = (level - target) / target;
                    // proportional and integral, the integral held while the trim is at its limit and the error would push it further
                    let limit = MAX_TRIM / 10.0;
                    let raw = 1.0 - 2e-2 * err - 2.5e-3 * integral;
                    if (raw - 1.0).abs() < limit || (raw > 1.0) == (err > 0.0) {
                        integral = (integral + err * window).clamp(-1.0, 1.0);
                    }
                    let trim = (1.0 - 2e-2 * err - 2.5e-3 * integral).clamp(1.0 - limit, 1.0 + limit);
                    rs.set_trim(trim);
                    let ppm = (1.0 / trim - 1.0) * 1e6;
                    mean_trim = Some(mean_trim.map_or(ppm, |m| m + 0.0625 * (ppm - m)));
                    (low, high, window) = (f64::MAX, 0.0, 0.0);
                }
            }
            let mut r = lock(&self.report);
            r.state = LinkState::Live;
            r.transit_ms = transit;
            r.buffer_frames = queued;
            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);
            r.clock_offset_ns = fit.offset_at(now);
            r.clock_drift_ppm = fit.drift_ppm();
            r.trim_ppm = mean_trim.unwrap_or(0.0);
            r.frames = frames;
            r.lost = self.input.lost();
            r.gaps = gaps;
            r.target_frames = target as usize;
            r.aligned = aligned;
            r.sender_epoch_ns = epoch;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::map_channels;

    #[test]
    fn channels_map_mono_to_stereo_and_stereo_to_mono() {
        let mut out = Vec::new();
        map_channels(&[1.0, 2.0], 1, 2, &mut out);
        assert_eq!(out, [1.0, 1.0, 2.0, 2.0]);
        map_channels(&[1.0, 3.0], 2, 1, &mut out);
        assert_eq!(out, [2.0]);
        map_channels(&[1.0, 2.0, 3.0], 3, 2, &mut out);
        assert_eq!(out, [1.0, 2.0]);
    }
}