diff --git a/quest/m2/README.md b/quest/m2/README.md index 5955c29d242..23ea57eb235 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -205,7 +205,6 @@ quests that require them. - [Small API fixes before the cut](/quest/m2/api-shape/README.md) - one path and one spelling per item, names by role, and no dead or wrong-role public surface across net, transport, media, native, apps, JS, and bindings - [Public constructors spawn nothing, or say why](/quest/m2/spawn-constructors.md) - each public library entry point that spawns returns a driver its caller polls, or is listed as kept - [moq-audio codecs return zero or more outputs](/quest/m2/audio-codec-seam.md) - `encode` and `decode` return any number of outputs and gain `flush`, as moq-video's do -- [Bus writes land at a bus position](/quest/m2/bus-positioned-write.md) - callers sync audio to video without copying the bus's private latency, before the cut first publishes `bus` - [A mix-minus removes several sources](/quest/m2/bus-minus-several.md) - a guest's return feed drops every copy of their own sound - [Drop moq-auth's iroh transport](/quest/m2/auth-drop-iroh.md) - this breaking moq-auth release drops `Transport::Iroh` and the JS `"iroh"` value - [Plan: recovery boundaries](/quest/m2/intra-refresh-boundary.md) - the catalog's new `warmup` contract is settled before the cut publishes it diff --git a/quest/m2/bus-positioned-write.md b/quest/m2/bus-positioned-write.md deleted file mode 100644 index 7419e725599..00000000000 --- a/quest/m2/bus-positioned-write.md +++ /dev/null @@ -1,32 +0,0 @@ -# [M] Bus writes land at a bus position - -## Goal - -A `bus::Channel` write can say which bus position its samples belong at, and -the bus places them there, so a caller lines sound up with video without -copying the bus's private latency and padding rules. - -## Plan - -Decided 2026-11-05 (maintainer, on moq-dev/studio's /quest-plan): m3, since the studio is a named consumer that is not urgent. Moved to m2: Decided 2026-11-07 (maintainer, /quest-plan from the API sweep of open PRs and remaining quests). `moq_audio::bus` is new since `release`, so the cut publishes `Channel::write` for the first time, and this break after it would cost another moq-audio major. If the positioned-write semantics can't settle in time, land `write(Write { position: Option, data })` so positioning is additive. - -- ✅ **Positioned writes**, a breaking change to `Channel::write`. - Rejected: exposing a channel's buffered depth and latency, which leaves the - caller doing the placement and keeps the dry-channel error below. - -Today `Channel::write` (`rs/moq-audio/src/bus.rs`) takes no position, and -`LATENCY` (50 ms) and `HEADROOM` are private; positions exist only on the -output side (`Block::position`, `Driver::position`). Studio broadcast sync -([moq-dev/studio#38](https://github.com/moq-dev/studio/pull/38)) copies those constants, and sound can trail -video by up to 37.5 ms after a channel runs dry. Decide what a write for a -position already mixed or beyond the headroom does, and fail loudly rather -than silently shifting it. - -[moq-dev/studio#93](https://github.com/moq-dev/studio/pull/93) adds a second -case: after a silence the studio's `playout::Writer` can't tell how much its -channel holds, so a first write lands up to one block (10 ms) early. Broadcast -and media sources both hit it. A positioned write fixes this too; test that a -first write after silence is mixed at the sample it was meant for. - -- ✅ **Fold studio#93 in here**, decided 2026-11-07 (maintainer, /quest-complete). - Rejected: an interim bus-position accessor quest, and dropping the plan. diff --git a/rs/moq-audio/CHANGELOG.md b/rs/moq-audio/CHANGELOG.md index 6be0942208f..188f7e9c5d0 100644 --- a/rs/moq-audio/CHANGELOG.md +++ b/rs/moq-audio/CHANGELOG.md @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- **Breaking:** `Bus::channel` and `bus::Channel` are renamed `Bus::live` and + `bus::Live`, pairing with `Bus::positioned` and `bus::Positioned`. See + `MIGRATE.md`. +- `Bus::positioned` adds a bus source whose every write names the bus position + its first frame plays at, for audio scheduled against video on the bus's + clock. A write that would land where the bus already mixed, overlap the + channel's own audio, or end past `bus::REACH` (200 ms) fails whole instead of + moving. It takes the bus's sample rate. - A bus `Strip` has a pan, `set_pan` and `pan`, that places its source between left and right in every mix: constant power for a mono source, at -3 dB per side when centered (so a mono source now plays 3 dB quieter by default), and diff --git a/rs/moq-audio/MIGRATE.md b/rs/moq-audio/MIGRATE.md index 94376708a9f..9d12aa62f7f 100644 --- a/rs/moq-audio/MIGRATE.md +++ b/rs/moq-audio/MIGRATE.md @@ -4,6 +4,14 @@ How to update your code for each breaking change, newest first. ## Unreleased +### `Bus::channel` is `Bus::live` + +The bus has two kinds of source: a live one on its own clock, whose ring +absorbs jitter and drift, and a positioned one on the bus's clock, whose every +write names its bus position. `Bus::channel` and `bus::Channel` are renamed +`Bus::live` and `bus::Live` to pair with `Bus::positioned` and +`bus::Positioned`. Their behavior is unchanged: rename the calls and the type. + ### Playback fills a declared silence with comfort noise `Sink::end()` declares that the audio written so far is followed by a silence @@ -88,7 +96,7 @@ Device channel counts above stereo are now consistently `Layout::Discrete`: a microphone array does not declare surround-speaker positions. A stereo bus refuses those inputs instead of guessing a surround downmix. Request mono or stereo through `capture::Config::channels` when the device supports it, or map -the known channels explicitly before writing a `Bus::channel`. The encoder refuses +the known channels explicitly before writing a `Bus::live`. The encoder refuses them too: `encode::Control::new` fails for such a consumer, since its default stereo config (and Opus in any config) cannot take a discrete layout. Publish a microphone array only when it delivers mono or stereo, or with an diff --git a/rs/moq-audio/benches/bus.rs b/rs/moq-audio/benches/bus.rs index b0438c7d506..8de0272f26b 100644 --- a/rs/moq-audio/benches/bus.rs +++ b/rs/moq-audio/benches/bus.rs @@ -14,7 +14,7 @@ use std::hint::black_box; use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main}; -use moq_audio::bus::{Bus, Channel, Config, Driver, Strip}; +use moq_audio::bus::{Bus, Config, Driver, Live, Strip}; use moq_audio::encode::Input; use moq_audio::{Format, Layout}; @@ -23,7 +23,7 @@ const BLOCK: usize = 480; /// A bus with `count` stereo sources at `rate`, opened by a first advance, and /// one block of PCM for each. -fn sources(count: usize, rate: u32) -> (Bus, Driver, Vec<(Channel, Strip)>, Vec) { +fn sources(count: usize, rate: u32) -> (Bus, Driver, Vec<(Live, Strip)>, Vec) { let (bus, mut driver) = Bus::new(Config::default()).unwrap(); let frames = BLOCK * rate as usize / 48_000; let block: Vec = std::iter::repeat_n(0.25f32, frames * 2) @@ -34,7 +34,7 @@ fn sources(count: usize, rate: u32) -> (Bus, Driver, Vec<(Channel, Strip)>, Vec< let mut input = Input::new(rate, Layout::Stereo); input.format = Format::F32; let strip = Strip::default(); - (bus.channel(input, strip.clone()).unwrap(), strip) + (bus.live(input, strip.clone()).unwrap(), strip) }) .collect(); // Writes before the first advance are dropped, so open the channels first. @@ -42,7 +42,7 @@ fn sources(count: usize, rate: u32) -> (Bus, Driver, Vec<(Channel, Strip)>, Vec< (bus, driver, sources, block) } -fn run(driver: &mut Driver, sources: &mut [(Channel, Strip)], block: &[u8]) { +fn run(driver: &mut Driver, sources: &mut [(Live, Strip)], block: &[u8]) { for (channel, _) in sources.iter_mut() { channel.write(black_box(block)).unwrap(); } diff --git a/rs/moq-audio/src/bus.rs b/rs/moq-audio/src/bus.rs index a93e277aeb0..a804e8079a5 100644 --- a/rs/moq-audio/src/bus.rs +++ b/rs/moq-audio/src/bus.rs @@ -1,9 +1,10 @@ //! Route PCM sources into several mixes, advanced on the caller's clock. //! -//! A [`Bus`] holds sources, each a [`Channel`] fed with PCM and controlled by a -//! [`Strip`] of gain, mute, pan, sync delay, and level meter, and [`Mix`]es, each -//! the sum of the sources routed into it. A [`Minus`] is a mix-minus: one mix -//! with one of its sources taken out, for a guest's return feed. Every mix +//! A [`Bus`] holds sources, each a [`Live`] or [`Positioned`] channel fed with +//! PCM and controlled by a [`Strip`] of gain, mute, pan, sync delay, and level +//! meter, and [`Mix`]es, each the sum of the sources routed into it. A +//! [`Minus`] is a mix-minus: one mix with one of its sources taken out, for a +//! guest's return feed. Every mix //! publishes interleaved `f32` at the bus's [`Config`] to any number of //! independent [`Reader`]s. //! @@ -18,7 +19,10 @@ //! //! Each channel is resampled from its own rate to the bus's, and a source that //! runs slightly fast or slow against the clock is corrected by the same ring -//! that absorbs its jitter, so it never drifts out of the mix. +//! that absorbs its jitter, so it never drifts out of the mix. A source that +//! already runs on the bus's clock, such as decoded media scheduled against +//! video, opens a [`Positioned`] channel instead, and says where on the clock +//! each write belongs. //! //! ``` //! # async fn example() -> Result<(), moq_audio::Error> { @@ -26,7 +30,7 @@ //! //! let (bus, mut driver) = bus::Bus::new(bus::Config::default())?; //! let strip = bus::Strip::default(); -//! let mut mic = bus.channel(encode::Input::new(44_100, moq_audio::Layout::Mono), strip.clone())?; +//! let mut mic = bus.live(encode::Input::new(44_100, moq_audio::Layout::Mono), strip.clone())?; //! strip.set_gain(0.5); //! //! let program = bus.mix(); @@ -44,6 +48,7 @@ //! //! Enabled by the default-on `bus` feature; `Bus::capture` also needs `capture`. +use std::borrow::Cow; use std::collections::{HashMap, HashSet, VecDeque}; use std::f32::consts::FRAC_PI_4; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; @@ -56,7 +61,7 @@ use crate::resample::Remix; use crate::ring; use crate::{Error, Layout, Level}; -/// Audio held between a [`Channel::write`] and the [`Driver::advance`] that mixes it. +/// Audio held between a [`Live::write`] and the [`Driver::advance`] that mixes it. /// /// The jitter a late write absorbs without a dropout, and the delay every /// source carries into the mix. Matches the playback sink's default, which @@ -77,6 +82,10 @@ const RETENTION: Duration = Duration::from_millis(200); /// The longest [`Strip::set_delay`] accepts, which bounds a source's delay line. pub const MAX_DELAY: Duration = Duration::from_secs(2); +/// How far past the next frame the bus mixes a [`Positioned::write`] may end: +/// the audio a positioned channel holds, as much as a live channel can. +pub const REACH: Duration = LATENCY.saturating_add(HEADROOM); + /// What every mix is mixed to. /// /// `#[non_exhaustive]`: construct via [`Config::default`] and set fields, so new @@ -137,11 +146,39 @@ type StripKey = usize; /// One open channel of a source, as the mixer reads it. struct Feed { id: u64, - ring: ring::Consumer, + queue: Queue, /// Panned with constant power rather than balanced. mono: bool, } +/// Where a channel's audio waits to be mixed. +enum Queue { + /// A [`Live`]'s jitter buffer, filled without the mixer's lock. + Live(ring::Consumer), + /// A [`Positioned`] channel's interleaved samples, the first of which is + /// mixed at the bus's next position. Filled under the mixer's lock, so a + /// write sees exactly where the mix is. + Positioned(VecDeque), +} + +impl Feed { + /// Fill `output` with this channel's next samples, and silence past them. + fn read(&mut self, output: &mut [f32]) { + match &mut self.queue { + Queue::Live(ring) => { + ring.read(output); + } + Queue::Positioned(queue) => { + let queued = queue.len().min(output.len()); + for (out, sample) in output.iter_mut().zip(queue.drain(..queued)) { + *out = sample; + } + output[queued..].fill(0.0); + } + } + } +} + /// The channels sharing one strip, as the mixer sees them. struct Source { strip: Strip, @@ -265,6 +302,11 @@ fn key(strip: &Strip) -> StripKey { Arc::as_ptr(&strip.shared) as StripKey } +/// `duration` in frames at `sample_rate`, rounded down. +fn frames(sample_rate: u32, duration: Duration) -> usize { + (u128::from(sample_rate) * duration.as_nanos() / 1_000_000_000) as usize +} + impl Bus { /// An empty bus producing PCM in `config`'s format, and the one driver /// that advances it. @@ -279,7 +321,7 @@ impl Bus { ))); } - let retention = (u128::from(config.sample_rate) * RETENTION.as_nanos() / 1_000_000_000) as usize; + let retention = frames(config.sample_rate, RETENTION); let inner = Arc::new(Inner { config, mixer: Mutex::new(Mixer { @@ -316,26 +358,12 @@ impl Bus { /// /// Refuses a strip panned off center unless the bus is stereo, and holds /// the strip at center while this channel is open on such a bus. - pub fn channel(&self, input: Input, strip: Strip) -> Result { + pub fn live(&self, input: Input, strip: Strip) -> Result { if input.sample_rate == 0 { return Err(Error::Unsupported("channel sample rate must be > 0".into())); } - let output = self.inner.config.layout; - let remix = if input.layout == output { - None - } else { - Some(Remix::new(input.layout, output)?) - }; - // Only a stereo bus pans, so any other holds the strip at center for - // as long as this channel is open. Nothing below fails, so the hold - // is always released by the channel's drop. - let centered = output != Layout::Stereo; - if centered { - strip.hold_center(output)?; - } - let (prod, cons) = ring::channel( - output.channels() as usize, + self.inner.config.layout.channels() as usize, input.sample_rate, self.inner.config.sample_rate, ring::Config { @@ -347,6 +375,48 @@ impl Bus { trim: true, }, ); + let port = self.open(input, strip, Queue::Live(cons))?; + Ok(Live { prod, port }) + } + + /// Add a source on the bus's own clock, whose every write says the bus + /// position its first frame is mixed at, as [`live`](Self::live) adds + /// one running on a clock of its own. + /// + /// For audio scheduled against something else on the bus's clock, such as + /// the video of the same media: there is no jitter buffer between a write + /// and its position, and no drift correction to move it. + /// + /// Refuses `input` at another rate than the bus's, which positions count + /// frames of, and a strip as [`live`](Self::live) does. + pub fn positioned(&self, input: Input, strip: Strip) -> Result { + let sample_rate = self.inner.config.sample_rate; + if input.sample_rate != sample_rate { + return Err(Error::Unsupported(format!( + "a positioned channel takes the bus rate, {sample_rate} Hz (got {} Hz)", + input.sample_rate + ))); + } + let samples = frames(sample_rate, REACH) * self.inner.config.layout.channels() as usize; + let port = self.open(input, strip, Queue::Positioned(VecDeque::with_capacity(samples)))?; + Ok(Positioned { port }) + } + + /// Add a channel reading `queue` to `strip`'s source. + fn open(&self, input: Input, strip: Strip, queue: Queue) -> Result { + let output = self.inner.config.layout; + let remix = if input.layout == output { + None + } else { + Some(Remix::new(input.layout, output)?) + }; + // Only a stereo bus pans, so any other holds the strip at center for + // as long as this channel is open. Nothing below fails, so the hold + // is always released by the port's drop. + let centered = output != Layout::Stereo; + if centered { + strip.hold_center(output)?; + } let id = self.inner.next.fetch_add(1, Ordering::Relaxed); let mut mixer = self.inner.mixer.lock().unwrap(); @@ -364,14 +434,13 @@ impl Bus { .channels .push(Feed { id, - ring: cons, + queue, mono: input.layout == Layout::Mono, }); drop(mixer); - Ok(Channel { + Ok(Port { id, - prod, remix, input, strip, @@ -424,7 +493,7 @@ impl Bus { /// Requires the `capture` feature. #[cfg(feature = "capture")] pub fn capture(&self, capture: crate::capture::Consumer, strip: Strip) -> Result { - let channel = self.channel(capture.input().clone(), strip)?; + let channel = self.live(capture.input().clone(), strip)?; Ok(Capture { capture, channel }) } } @@ -532,14 +601,14 @@ impl Source { let lane = &mut self.lanes[usize::from(stereo && feed.mono)]; if lane.fed { scratch.resize(samples, 0.0); - feed.ring.read(scratch); + feed.read(scratch); for (out, sample) in lane.block.iter_mut().zip(scratch.iter()) { *out += *sample; } } else { lane.block.clear(); lane.block.resize(samples, 0.0); - feed.ring.read(&mut lane.block); + feed.read(&mut lane.block); lane.fed = true; } } @@ -859,21 +928,15 @@ impl Reader { } } -/// One source's PCM on its way into a [`Bus`]. +/// One source's PCM on its way into a [`Bus`], on a clock of its own. /// /// Dropping it takes this channel out of the bus. -pub struct Channel { - id: u64, +pub struct Live { prod: ring::Producer, - remix: Option, - input: Input, - strip: Strip, - /// Holds the strip at center, since the bus cannot pan. - centered: bool, - bus: Weak, + port: Port, } -impl Channel { +impl Live { /// Push PCM in the format, rate, and layout this channel was created with. /// /// Never blocks. Audio that arrives before the bus first advances, or that @@ -882,19 +945,13 @@ impl Channel { /// Refuses a NaN or infinite sample, which would reach every mix and /// survive any gain, mute included. pub fn write(&mut self, data: &[u8]) -> Result<(), Error> { - let pcm = self - .input - .format - .as_interleaved_f32(data, self.input.layout.channels())?; - if pcm.iter().any(|sample| !sample.is_finite()) { - return Err(Error::Unsupported("a non-finite PCM sample".into())); - } + let pcm = self.port.pcm(data)?; self.push(&pcm); Ok(()) } fn push(&mut self, pcm: &[f32]) { - match &self.remix { + match &self.port.remix { Some(remix) => { let _ = self.prod.push(&remix.process(pcm)); } @@ -906,11 +963,118 @@ impl Channel { /// This source's gain, mute, pan, delay, and meter. pub fn strip(&self) -> &Strip { - &self.strip + &self.port.strip + } +} + +/// One source's PCM on its way into a [`Bus`], placed on the bus's clock. +/// +/// Built by [`Bus::positioned`]. Dropping it takes this channel out of the bus. +pub struct Positioned { + port: Port, +} + +impl Positioned { + /// Mix PCM in this channel's format and layout so its first frame plays at + /// bus `position`, on the clock [`Driver::position`] counts, then delayed + /// by the strip's sync delay. + /// + /// Writes only move forward: whatever lies between the end of the previous + /// write and `position` is silence. A write fails, and nothing of it is + /// mixed, if any of it would land where the bus has already mixed or where + /// this channel already holds audio, or would end more than [`REACH`] past + /// the next frame the bus mixes. The bus never shifts a write to fit. + /// + /// Waits only for a [`Driver::advance`] in progress. Once the driver is + /// gone nothing mixes, so writes are dropped. + /// + /// Refuses a NaN or infinite sample, as [`Live::write`] does. + pub fn write(&mut self, position: u64, data: &[u8]) -> Result<(), Error> { + let pcm = self.port.pcm(data)?; + let pcm = match &self.port.remix { + Some(remix) => remix.process(&pcm).into(), + None => pcm, + }; + if pcm.is_empty() { + return Ok(()); + } + let Some(bus) = self.port.bus.upgrade() else { + return Ok(()); + }; + let channels = bus.config.layout.channels() as usize; + let reach = frames(bus.config.sample_rate, REACH) as u64; + + let mut mixer = bus.mixer.lock().unwrap(); + if mixer.closed { + return Ok(()); + } + let next = mixer.position; + let feed = mixer + .sources + .get_mut(&key(&self.port.strip)) + .and_then(|source| source.channels.iter_mut().find(|feed| feed.id == self.port.id)) + .expect("an open channel keeps its feed"); + let Queue::Positioned(queue) = &mut feed.queue else { + unreachable!("a positioned channel feeds a positioned queue"); + }; + + let end = next + (queue.len() / channels) as u64; + let frames = (pcm.len() / channels) as u64; + if position < next { + return Err(Error::Unsupported(format!( + "bus position {position} is already mixed, up to {next}" + ))); + } + if position < end { + return Err(Error::Unsupported(format!( + "bus position {position} overlaps this channel's audio, which runs to {end}" + ))); + } + if (position - next).saturating_add(frames) > reach { + return Err(Error::Unsupported(format!( + "a write of {frames} frames at bus position {position} ends past {}, the reach from {next}", + next + reach + ))); + } + queue.extend(std::iter::repeat_n(0.0, (position - end) as usize * channels)); + queue.extend(pcm.iter().copied()); + Ok(()) + } + + /// This source's gain, mute, pan, delay, and meter. + pub fn strip(&self) -> &Strip { + &self.port.strip } } -impl Drop for Channel { +/// What every channel shares: its place in the mixer, and the conversion of +/// its input to the bus layout. +struct Port { + id: u64, + remix: Option, + input: Input, + strip: Strip, + /// Holds the strip at center, since the bus cannot pan. + centered: bool, + bus: Weak, +} + +impl Port { + /// `data` as interleaved `f32` in the input's layout, refusing a NaN or + /// infinite sample, which would reach every mix and survive any gain. + fn pcm<'a>(&self, data: &'a [u8]) -> Result, Error> { + let pcm = self + .input + .format + .as_interleaved_f32(data, self.input.layout.channels())?; + if pcm.iter().any(|sample| !sample.is_finite()) { + return Err(Error::Unsupported("a non-finite PCM sample".into())); + } + Ok(pcm) + } +} + +impl Drop for Port { fn drop(&mut self) { if self.centered { self.strip.release_center(); @@ -930,7 +1094,7 @@ impl Drop for Channel { /// The gain, mute, pan, sync delay, and meter of one source in a [`Bus`]. /// /// Cheap to clone and `Send + Sync`: clones control the same source, so a UI -/// can hold one while a task owns the [`Channel`]. Its settings apply to every +/// can hold one while a task owns the [`Live`]. Its settings apply to every /// mix the source is routed into, from the next [`Driver::advance`], with gain /// and pan ramped across it. #[derive(Clone, Debug, Default)] @@ -1101,7 +1265,7 @@ impl Meter { #[cfg(feature = "capture")] pub struct Capture { capture: crate::capture::Consumer, - channel: Channel, + channel: Live, } #[cfg(feature = "capture")] @@ -1157,9 +1321,9 @@ mod tests { /// A stereo 48 kHz source the test feeds one block per advance, the way a /// live source keeps pace with the clock. - fn source(bus: &Bus) -> (Channel, Strip) { + fn source(bus: &Bus) -> (Live, Strip) { let strip = Strip::default(); - let channel = bus.channel(input(48_000, Layout::Stereo), strip.clone()).unwrap(); + let channel = bus.live(input(48_000, Layout::Stereo), strip.clone()).unwrap(); (channel, strip) } @@ -1168,7 +1332,7 @@ mod tests { /// each reader's last block. fn feed( driver: &mut Driver, - sources: &mut [(&mut Channel, f32)], + sources: &mut [(&mut Live, f32)], readers: &mut [&mut Reader], blocks: usize, ) -> Vec { @@ -1179,8 +1343,8 @@ mod tests { } for _ in 0..blocks { for (channel, value) in sources.iter_mut() { - let frames = BLOCK * channel.input.sample_rate as usize / 48_000; - let channels = channel.input.layout.channels() as usize; + let frames = BLOCK * channel.port.input.sample_rate as usize / 48_000; + let channels = channel.port.input.layout.channels() as usize; channel.write(&constant(*value, frames, channels)).unwrap(); } driver.advance(BLOCK); @@ -1199,7 +1363,7 @@ mod tests { for sample_rate in [44_100, 96_000, 4_000_000_000] { let (bus, _driver) = Bus::new(Config::default()).unwrap(); let (_, stats) = crate::allocation::measure(|| { - bus.channel(input(sample_rate, Layout::SevenPointOne), Strip::default()) + bus.live(input(sample_rate, Layout::SevenPointOne), Strip::default()) .unwrap() }); let baseline = *baseline.get_or_insert(stats.bytes); @@ -1402,7 +1566,7 @@ mod tests { fn converts_layout_and_rate() { let (bus, mut driver) = Bus::new(Config::default()).unwrap(); let strip = Strip::default(); - let mut channel = bus.channel(input(16_000, Layout::Mono), strip.clone()).unwrap(); + let mut channel = bus.live(input(16_000, Layout::Mono), strip.clone()).unwrap(); let program = bus.mix(); program.route(&strip); let mut reader = program.reader(); @@ -1474,9 +1638,9 @@ mod tests { let program = bus.mix(); program.route(&strip); let mut reader = program.reader(); - drop(bus.channel(input(48_000, Layout::Stereo), strip.clone()).unwrap()); + drop(bus.live(input(48_000, Layout::Stereo), strip.clone()).unwrap()); - let mut second = bus.channel(input(16_000, Layout::Mono), strip.clone()).unwrap(); + let mut second = bus.live(input(16_000, Layout::Mono), strip.clone()).unwrap(); let last = feed(&mut driver, &mut [(&mut second, 0.5)], &mut [&mut reader], 40); let sample = *last[0].data.last().unwrap(); assert!((sample - 0.25 * CENTER).abs() < 1e-2, "{sample}"); @@ -1624,7 +1788,7 @@ mod tests { fn pans_a_mono_source() { let (bus, mut driver) = Bus::new(Config::default()).unwrap(); let strip = Strip::default(); - let mut channel = bus.channel(input(48_000, Layout::Mono), strip.clone()).unwrap(); + let mut channel = bus.live(input(48_000, Layout::Mono), strip.clone()).unwrap(); let program = bus.mix(); program.route(&strip); let mut reader = program.reader(); @@ -1681,7 +1845,7 @@ mod tests { fn pan_changes_ramp_at_constant_power() { let (bus, mut driver) = Bus::new(Config::default()).unwrap(); let strip = Strip::default(); - let mut channel = bus.channel(input(48_000, Layout::Mono), strip.clone()).unwrap(); + let mut channel = bus.live(input(48_000, Layout::Mono), strip.clone()).unwrap(); strip.set_pan(-1.0).unwrap(); let program = bus.mix(); program.route(&strip); @@ -1724,8 +1888,8 @@ mod tests { let (bus, mut driver) = Bus::new(Config::default()).unwrap(); let strip = Strip::default(); - let mut mono = bus.channel(input(48_000, Layout::Mono), strip.clone()).unwrap(); - let mut stereo = bus.channel(input(48_000, Layout::Stereo), strip.clone()).unwrap(); + let mut mono = bus.live(input(48_000, Layout::Mono), strip.clone()).unwrap(); + let mut stereo = bus.live(input(48_000, Layout::Stereo), strip.clone()).unwrap(); strip.set_pan(0.5).unwrap(); strip.set_delay(Duration::from_millis(20)); let program = bus.mix(); @@ -1780,7 +1944,7 @@ mod tests { fn pan_applies_after_the_sync_delay() { let (bus, mut driver) = Bus::new(Config::default()).unwrap(); let strip = Strip::default(); - let mut channel = bus.channel(input(48_000, Layout::Mono), strip.clone()).unwrap(); + let mut channel = bus.live(input(48_000, Layout::Mono), strip.clone()).unwrap(); strip.set_delay(Duration::from_millis(100)); strip.set_pan(-1.0).unwrap(); let program = bus.mix(); @@ -1813,11 +1977,11 @@ mod tests { let (bus, mut driver) = Bus::new(config).unwrap(); let strip = Strip::default(); strip.set_pan(0.5).unwrap(); - assert!(bus.channel(input(48_000, Layout::Mono), strip.clone()).is_err()); + assert!(bus.live(input(48_000, Layout::Mono), strip.clone()).is_err()); strip.set_pan(0.0).unwrap(); - let mut first = bus.channel(input(48_000, Layout::Mono), strip.clone()).unwrap(); - let second = bus.channel(input(48_000, Layout::Stereo), strip.clone()).unwrap(); + let mut first = bus.live(input(48_000, Layout::Mono), strip.clone()).unwrap(); + let second = bus.live(input(48_000, Layout::Stereo), strip.clone()).unwrap(); assert!(strip.set_pan(-0.5).is_err()); assert_eq!(strip.pan(), 0.0); strip.set_pan(0.0).unwrap(); @@ -1844,10 +2008,7 @@ mod tests { assert!(Bus::new(config).is_err()); let (bus, _driver) = Bus::new(Config::default()).unwrap(); - assert!( - bus.channel(input(48_000, Layout::Discrete(3)), Strip::default()) - .is_err() - ); + assert!(bus.live(input(48_000, Layout::Discrete(3)), Strip::default()).is_err()); } /// A NaN survives every gain, mute included, so it is refused before it can @@ -1861,6 +2022,140 @@ mod tests { } } + /// A bus-rate source at `layout` placing its writes on the bus clock. + fn positioned(bus: &Bus, layout: Layout) -> (Positioned, Strip) { + let strip = Strip::default(); + let channel = bus.positioned(input(48_000, layout), strip.clone()).unwrap(); + (channel, strip) + } + + /// Advance `frames` in blocks of `sizes`, returning the left channel of + /// every frame mixed, indexed from the driver's position at the call. + fn mixed(driver: &mut Driver, reader: &mut Reader, sizes: &[usize], frames: usize) -> Vec { + let start = driver.position(); + let mut left = Vec::with_capacity(frames); + for size in sizes.iter().cycle() { + if left.len() >= frames { + break; + } + driver.advance((*size).min(frames - left.len())); + let block = ready(reader).unwrap(); + assert_eq!(block.position, start + left.len() as u64, "contiguous"); + left.extend(block.data.as_chunks::<2>().0.iter().map(|frame| frame[0])); + } + left + } + + /// Each write plays from the sample it names, wherever that falls in a + /// block, however the clock's blocks are sized, and whatever the channel + /// held before: a first write after silence included. + #[test] + fn a_positioned_write_plays_at_its_position() { + let (bus, mut driver) = Bus::new(Config::default()).unwrap(); + let (mut channel, strip) = positioned(&bus, Layout::Stereo); + let program = bus.mix(); + program.route(&strip); + let mut reader = program.reader(); + let sizes = [441, 512, 256, 480, 1024]; + + // Before the first advance, then contiguous with it. + channel.write(100, &constant(0.25, 300, 2)).unwrap(); + channel.write(400, &constant(0.5, 100, 2)).unwrap(); + // A gap of exactly 7 frames. + channel.write(507, &constant(0.25, 93, 2)).unwrap(); + let left = mixed(&mut driver, &mut reader, &sizes, 3_000); + let mut want = vec![0.0; 3_000]; + want[100..400].fill(0.25); + want[400..500].fill(0.5); + want[507..600].fill(0.25); + assert_eq!(left, want); + + // The channel has long run dry: a write after the silence plays at the + // sample it names, not where the bus happens to be. + let next = driver.position(); + channel.write(next + 333, &constant(0.25, 10, 2)).unwrap(); + let left = mixed(&mut driver, &mut reader, &sizes, 1_000); + let onset = left.iter().position(|sample| *sample != 0.0); + assert_eq!(onset, Some(333)); + assert_eq!(left.iter().filter(|sample| **sample != 0.0).count(), 10); + + // The strip's sync delay moves it on from there, by exactly that much. + strip.set_delay(Duration::from_millis(10)); + let next = driver.position(); + channel.write(next + 1_200, &constant(0.25, 10, 2)).unwrap(); + let left = mixed(&mut driver, &mut reader, &sizes, 3_000); + let onset = left.iter().position(|sample| *sample != 0.0); + assert_eq!(onset, Some(1_200 + BLOCK)); + } + + /// A write the bus cannot place where it names fails whole, rather than + /// being shifted or cut to fit, and leaves the channel as it was. + #[test] + fn a_positioned_write_fails_rather_than_moves() { + let (bus, mut driver) = Bus::new(Config::default()).unwrap(); + let (mut channel, strip) = positioned(&bus, Layout::Stereo); + let program = bus.mix(); + program.route(&strip); + let mut reader = program.reader(); + let block = constant(0.25, BLOCK, 2); + let reach = 48_000 / 5; + + driver.advance(BLOCK); + ready(&mut reader); + let next = BLOCK as u64; + assert!(channel.write(next - 1, &block).is_err(), "already mixed"); + assert!(channel.write(0, &block).is_err(), "already mixed"); + channel.write(next + 100, &block).unwrap(); + assert!(channel.write(next + 100, &block).is_err(), "overlaps the last write"); + assert!(channel.write(next + 579, &block).is_err(), "overlaps by one frame"); + assert!( + channel.write(next + 99, &constant(0.25, 1, 2)).is_err(), + "before the last write" + ); + let at_reach = next + reach as u64 - BLOCK as u64; + assert!(channel.write(at_reach + 1, &block).is_err(), "ends past the reach"); + assert!(channel.write(u64::MAX - 1, &block).is_err(), "ends past the reach"); + channel.write(at_reach, &block).unwrap(); + + // Only the two writes that fit play, each where it said. + let left = mixed(&mut driver, &mut reader, &[BLOCK], reach + BLOCK); + let heard: Vec<_> = (0..left.len()).filter(|&index| left[index] != 0.0).collect(); + let mut want: Vec<_> = (100..580).collect(); + want.extend(reach - BLOCK..reach); + assert_eq!(heard, want); + + // The position it fails on moves with the clock. + let next = driver.position(); + assert!(channel.write(next - 1, &block).is_err()); + channel.write(next, &block).unwrap(); + + // Once the driver is gone, nothing mixes, and writes are dropped. + drop(driver); + channel.write(0, &block).unwrap(); + } + + /// A positioned channel takes another layout, remixed and panned as any + /// channel is, but only the bus's rate, which its positions count. + #[test] + fn a_positioned_channel_takes_the_bus_rate() { + let (bus, mut driver) = Bus::new(Config::default()).unwrap(); + assert!(bus.positioned(input(44_100, Layout::Stereo), Strip::default()).is_err()); + assert!( + bus.positioned(input(48_000, Layout::Discrete(3)), Strip::default()) + .is_err() + ); + + let (mut channel, strip) = positioned(&bus, Layout::Mono); + let program = bus.mix(); + program.route(&strip); + let mut reader = program.reader(); + channel.write(0, &constant(0.5, BLOCK, 1)).unwrap(); + assert!(channel.write(BLOCK as u64, &constant(f32::NAN, 1, 1)).is_err()); + let block = step(&mut driver, &mut reader); + assert!(all_near(&block, 0.5 * CENTER), "{:?}", &block.data[..4]); + assert!(all_near(&step(&mut driver, &mut reader), 0.0)); + } + #[test] #[should_panic(expected = "exceeds")] fn refuses_a_delay_past_the_limit() {