From 6c159669bd1a5375820194d8e3832c281d332186 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benoi=CC=82t=20Rouleau?= Date: Wed, 5 Aug 2026 18:03:23 -0400 Subject: [PATCH 01/10] resampler: don't let span chunking change the output MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `fill_input_buffer` treats `current_span_len()` as the samples left in the span, but it's the span's total length, so it stops reading at the end of every span. Vorbis packets are smaller than a resampler chunk, so every chunk ends up short, gets marked `partial_len`, and rubato pads it with zeros. The same audio comes out different depending on how the decoder split it. Stop only where the rate or channel count actually changes, and check that before reading anything from the next span. When reading stops there, rebuild the resampler. That fixes a second bug: a span that changed the sample rate was still being resampled at the old one. 441 frames at 44.1k then 441 at 22.05k, converted to 48k, gave 962 samples instead of 1440. Drop the counter the boundary detection was using — reading stops at the change itself now, so there's nothing left to count. Only the passthrough still needs it. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 1 + src/conversions/sample_rate/mod.rs | 167 +++++++++++--------------- src/conversions/sample_rate/rubato.rs | 76 +++++++++--- src/conversions/sample_rate/tests.rs | 106 ++++++++++++++++ 4 files changed, 237 insertions(+), 113 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e0f149de..8bcc53bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fixed sources to detect parameter updates after mid-span seeks. - Fixed `Stoppable` and `Skippable` not signaling exhaustion. - Fixed `SpatialAudio` left and write channel swapping +- Fixed resampled output depending on how the input is split into spans. ## Version [0.22.2] (2026-03-05) diff --git a/src/conversions/sample_rate/mod.rs b/src/conversions/sample_rate/mod.rs index 7df49d64..0d932ca8 100644 --- a/src/conversions/sample_rate/mod.rs +++ b/src/conversions/sample_rate/mod.rs @@ -167,6 +167,28 @@ where } } + /// Rebuild for the format the input has moved on to. + fn recreate(&mut self) { + let source = self.inner.take().expect("always set").into_inner(); + self.inner = Some(Self::create_resampler( + source, + self.target_rate, + &self.config, + )); + self.pending_recreate = false; + self.cached_input_span_len = self.resampler().input().current_span_len(); + } + + fn next_resampled(&mut self) -> Option { + match self.resampler_mut() { + ResampleInner::Passthrough { source, .. } => source.next(), + ResampleInner::Poly(resampler) => resampler.next_sample(), + ResampleInner::Sinc(resampler) => resampler.next_sample(), + #[cfg(feature = "rubato-fft")] + ResampleInner::Fft(resampler) => resampler.next_sample(), + } + } + /// Helper method to create a resampler from a source using the stored config and target rate. fn create_resampler( source: I, @@ -330,35 +352,17 @@ where self.pending_recreate = false; let input_span_len = self.resampler().input().current_span_len(); - match self.inner.as_mut().unwrap() { - ResampleInner::Passthrough { - input_span_pos: input_samples_consumed, - .. - } => { - reset_seek_span_tracking( - input_samples_consumed.raw_mut(), - &mut self.cached_input_span_len, - position, - input_span_len, - ); - } - ResampleInner::Poly(r) | ResampleInner::Sinc(r) => { - reset_seek_span_tracking( - r.pos_in_current_span.raw_mut(), - &mut self.cached_input_span_len, - position, - input_span_len, - ); - } - #[cfg(feature = "rubato-fft")] - ResampleInner::Fft(r) => { - reset_seek_span_tracking( - r.pos_in_current_span.raw_mut(), - &mut self.cached_input_span_len, - position, - input_span_len, - ); - } + // Only the passthrough counts samples against the span length; + // `reset` already cleared the resamplers' own tracking. + if let ResampleInner::Passthrough { input_span_pos, .. } = + self.inner.as_mut().expect("always set") + { + reset_seek_span_tracking( + input_span_pos.raw_mut(), + &mut self.cached_input_span_len, + position, + input_span_len, + ); } Ok(()) @@ -376,60 +380,46 @@ where // If a format change was detected at the previous span boundary, wait until the // output buffer is fully drained before recreating the resampler. This guarantees // that fill_input_buffer only ever reads from the current span. - if self.pending_recreate { - let output_empty = match self.resampler() { - ResampleInner::Passthrough { .. } => true, - ResampleInner::Poly(r) | ResampleInner::Sinc(r) => !r.output_has_samples(), - #[cfg(feature = "rubato-fft")] - ResampleInner::Fft(r) => !r.output_has_samples(), - }; - if output_empty { - let source = self.inner.take().unwrap().into_inner(); - self.inner = Some(Self::create_resampler( - source, - self.target_rate, - &self.config, - )); - self.pending_recreate = false; + let sample = loop { + if self.pending_recreate { + let output_empty = match self.resampler() { + ResampleInner::Passthrough { .. } => true, + ResampleInner::Poly(r) | ResampleInner::Sinc(r) => !r.output_has_samples(), + #[cfg(feature = "rubato-fft")] + ResampleInner::Fft(r) => !r.output_has_samples(), + }; + if output_empty { + self.recreate(); + } } - } - let sample = match self.resampler_mut() { - ResampleInner::Passthrough { source, .. } => source.next()?, - ResampleInner::Poly(resampler) => resampler.next_sample()?, - ResampleInner::Sinc(resampler) => resampler.next_sample()?, - #[cfg(feature = "rubato-fft")] - ResampleInner::Fft(resampler) => resampler.next_sample()?, + match self.next_resampled() { + Some(sample) => break sample, + // Built for one format, a resampler stops where its input + // changes rate or channels. Rebuilding matches the format + // it stopped at, so this retries at most once. + None if self.resampler().built_for_input() => return None, + None => self.recreate(), + } }; - // If input reports no span length, parameters are stable by contract - let input_span_len = self.resampler().input().current_span_len(); - if input_span_len.is_none() { + // Only the passthrough tracks spans here; a resampler stops at a + // format change itself while filling, and the loop above rebuilds it. + let ResampleInner::Passthrough { + input_span_pos, + channels, + source_rate, + source, + } = self.resampler_mut() + else { return Some(sample); - } - - let (expected_channels, expected_rate, samples_consumed) = match self.resampler_mut() { - ResampleInner::Passthrough { - input_span_pos: input_samples_consumed, - channels, - source_rate, - .. - } => { - *input_samples_consumed += 1usize; - (*channels, *source_rate, *input_samples_consumed) - } - ResampleInner::Poly(r) | ResampleInner::Sinc(r) => ( - r.output.channels, - r.input.sample_rate(), - r.pos_in_current_span, - ), - #[cfg(feature = "rubato-fft")] - ResampleInner::Fft(r) => ( - r.output.channels, - r.input.sample_rate(), - r.pos_in_current_span, - ), }; + let input_span_len = source.current_span_len(); + // No span length means the format is stable by contract. + input_span_len?; + *input_span_pos += 1usize; + let (expected_channels, expected_rate, samples_consumed) = + (*channels, *source_rate, *input_span_pos); let input = self.resampler().input(); let (at_boundary, parameters_changed) = Self::detect_boundary( @@ -442,30 +432,11 @@ where ); if at_boundary { - // Update cached span length (exits detection mode if we were in it) self.cached_input_span_len = input_span_len; - if parameters_changed { - // Defer recreation until the output buffer is drained (handled above at the - // top of the next next() call) so no cross-span reads occur. self.pending_recreate = true; - } else { - // Just crossed boundary without parameter change, reset counter - match self.resampler_mut() { - ResampleInner::Passthrough { - input_span_pos: input_samples_consumed, - .. - } => { - *input_samples_consumed = InSamples::ZERO; - } - ResampleInner::Poly(r) | ResampleInner::Sinc(r) => { - r.pos_in_current_span = InSamples::ZERO; - } - #[cfg(feature = "rubato-fft")] - ResampleInner::Fft(r) => { - r.pos_in_current_span = InSamples::ZERO; - } - } + } else if let ResampleInner::Passthrough { input_span_pos, .. } = self.resampler_mut() { + *input_span_pos = InSamples::ZERO; } } diff --git a/src/conversions/sample_rate/rubato.rs b/src/conversions/sample_rate/rubato.rs index df1ee016..c2bc3d04 100644 --- a/src/conversions/sample_rate/rubato.rs +++ b/src/conversions/sample_rate/rubato.rs @@ -57,6 +57,26 @@ impl ResampleInner { } } + /// Whether the input still has the format this was built for. + #[inline] + pub fn built_for_input(&self) -> bool { + let (channels, source_rate) = match self { + ResampleInner::Passthrough { + channels, + source_rate, + .. + } => (*channels, *source_rate), + ResampleInner::Poly(resampler) | ResampleInner::Sinc(resampler) => { + (resampler.output.channels, resampler.output.source_rate) + } + #[cfg(feature = "rubato-fft")] + ResampleInner::Fft(resampler) => { + (resampler.output.channels, resampler.output.source_rate) + } + }; + self.input().channels() == channels && self.input().sample_rate() == source_rate + } + /// Extract the inner input source, consuming the resampler #[inline] pub fn into_inner(self) -> I { @@ -83,7 +103,11 @@ pub struct RubatoResample> { pub resample_ratio: Float, pub output_delay_remaining: OutFrameCount, - pub pos_in_current_span: InSamples, + + /// How much of the span being read is left. Tracked because + /// `Source::current_span_len` reports the span's total length, + /// not its remainder. + span_remaining: InSamples, pub frames_being_resampled: OutFrameCount, } @@ -118,7 +142,7 @@ impl> RubatoResample { pub fn reset(&mut self) { self.resampler.reset(); self.output.reset(); - self.pos_in_current_span = InSamples::ZERO; + self.span_remaining = InSamples::ZERO; self.output_delay_remaining = Self::output_delay(&self.resampler); } @@ -147,7 +171,6 @@ impl> RubatoResample { } self.frames_being_resampled += frames_in.resampled_by(self.resample_ratio); - self.pos_in_current_span += frames_in.samples(self.output.channels); let indexing = Some(&rubato::Indexing { input_offset: 0, @@ -192,23 +215,46 @@ impl> RubatoResample { Some(()) } + /// Reads across spans, since the resampler is built for one format + /// and only a span that changes it has to end the chunk. A short + /// read then means end of stream or a format change, which is when + /// rubato should treat the chunk as partial. fn fill_input_buffer(&mut self, needed_by_resampler: InFrameCount) -> InFrameCount { - let current_span_length = self.input.current_span_len().map(InSamples); - let frames_to_take = needed_by_resampler - .samples(self.output.channels) - .min(current_span_length.unwrap_or(InSamples::MAX)); - + let wanted = needed_by_resampler.samples(self.output.channels); self.input_buffer.clear(); - for _ in 0..frames_to_take.raw() { - if let Some(sample) = self.input.next() { - self.input_buffer.push(sample); - } else { + + while self.input_buffer.len() < wanted { + if self.span_remaining == InSamples::ZERO && !self.start_of_span() { break; } + let Some(sample) = self.input.next() else { + break; + }; + self.input_buffer.push(sample); + self.span_remaining -= InSamples(1); } + self.input_buffer.len().frames(self.output.channels) } + /// Whether reading may continue into the next span, recording its + /// length. `false` once the stream ends or the format changes. + fn start_of_span(&mut self) -> bool { + let Some(span_len) = self.input.current_span_len() else { + // Without spans the format never changes. + self.span_remaining = InSamples::MAX; + return true; + }; + if span_len == 0 + || self.input.channels() != self.output.channels + || self.input.sample_rate() != self.output.source_rate + { + return false; + } + self.span_remaining = InSamples(span_len); + true + } + fn resampler_empty(&self) -> bool { self.frames_being_resampled == OutFrameCount::ZERO } @@ -247,7 +293,7 @@ impl RubatoAsyncResample { resampler, input_buffer: Input::new(input_buf_size.samples(channels)), output: Output::new(source_rate, channels, output_buf_size), - pos_in_current_span: InSamples::ZERO, + span_remaining: InSamples::ZERO, output_delay_remaining: initial_output_delay, resample_ratio, frames_being_resampled: OutFrameCount::ZERO, @@ -298,7 +344,7 @@ impl RubatoAsyncResample { resampler, input_buffer: Input::new(input_buf_size.samples(channels)), output: Output::new(source_rate, channels, output_buf_size), - pos_in_current_span: InSamples::ZERO, + span_remaining: InSamples::ZERO, output_delay_remaining: initial_output_delay, resample_ratio, frames_being_resampled: OutFrameCount::ZERO, @@ -348,7 +394,7 @@ impl RubatoFftResample { resampler, input_buffer: Input::new(input_buf_size.samples(channels)), output: Output::new(source_rate, channels, output_buf_size), - pos_in_current_span: InSamples::ZERO, + span_remaining: InSamples::ZERO, output_delay_remaining, resample_ratio, frames_being_resampled: OutFrameCount::ZERO, diff --git a/src/conversions/sample_rate/tests.rs b/src/conversions/sample_rate/tests.rs index c2ea52cc..6ca08cea 100644 --- a/src/conversions/sample_rate/tests.rs +++ b/src/conversions/sample_rate/tests.rs @@ -338,3 +338,109 @@ fn test_span_boundary_same_format() { output.len() ); } + +/// Split `input` into spans of `span_samples`, all with the same format. +fn chunked_into_spans( + input: &[Sample], + span_samples: usize, + rate: SampleRate, + channels: ChannelCount, +) -> TestSource { + let mut spans = input.chunks(span_samples); + let first = spans.next().expect("input is not empty").to_vec(); + spans.fold(TestSource::new(first, rate, channels), |source, span| { + source.chain(span.to_vec(), rate, channels) + }) +} + +/// Same samples, same format, different span lengths must resample to +/// the same output: a span boundary without a format change is not a +/// discontinuity. Reproduces #907, where Vorbis-sized spans made every +/// chunk look like end-of-stream and get zero-padded. +#[test] +fn output_is_independent_of_span_chunking() { + let channels = ChannelCount::new(2).unwrap(); + let rate = SampleRate::new(44100).unwrap(); + let target = SampleRate::new(48000).unwrap(); + let input = create_test_input(InFrameCount(4410), channels); + let config = || ResampleConfig::poly().build(); + + let whole: Vec = SampleRateConverter::new( + TestSource::new(input.clone(), rate, channels), + target, + config(), + ) + .collect(); + + // 128 frames is a typical Vorbis short block. + let source = chunked_into_spans(&input, 128 * channels.get() as usize, rate, channels); + let chunked: Vec = SampleRateConverter::new(source, target, config()).collect(); + + assert_eq!(whole.len(), chunked.len(), "output length changed"); + let worst = whole + .iter() + .zip(&chunked) + .map(|(a, b)| (a - b).abs()) + .fold(0.0, Sample::max); + assert!(worst < 1e-4, "output differs by up to {worst}"); +} + +/// A span that changes the sample rate must be resampled at its own +/// rate. It used to be resampled at the previous span's rate, so a +/// span that halved the rate came out half as long as it should. +#[test] +fn span_boundary_may_change_sample_rate() { + let channels = ChannelCount::new(1).unwrap(); + let target = SampleRate::new(48000).unwrap(); + let (fast, slow) = ( + SampleRate::new(44100).unwrap(), + SampleRate::new(22050).unwrap(), + ); + let frames = InFrameCount(441); + + let source = TestSource::new(create_test_input(frames, channels), fast, channels).chain( + create_test_input(frames, channels), + slow, + channels, + ); + let output: Vec = + SampleRateConverter::new(source, target, ResampleConfig::poly().build()).collect(); + + let expected = resampled_len(frames, fast, target) + resampled_len(frames, slow, target); + assert_close(output.len(), expected, "sample rate change"); +} + +/// The same for a span that changes the channel count. +#[test] +fn span_boundary_may_change_channel_count() { + let (stereo, mono) = (ChannelCount::new(2).unwrap(), ChannelCount::new(1).unwrap()); + let rate = SampleRate::new(44100).unwrap(); + let target = SampleRate::new(48000).unwrap(); + let frames = InFrameCount(441); + + let source = TestSource::new(create_test_input(frames, stereo), rate, stereo).chain( + create_test_input(frames, mono), + rate, + mono, + ); + let output: Vec = + SampleRateConverter::new(source, target, ResampleConfig::poly().build()).collect(); + + let expected = resampled_len(frames, rate, target) * 2 + resampled_len(frames, rate, target); + assert_close(output.len(), expected, "channel count change"); +} + +/// Samples one span of `frames` becomes at `target`, one channel. +fn resampled_len(frames: InFrameCount, from: SampleRate, target: SampleRate) -> usize { + (frames.raw() as f64 * target.get() as f64 / from.get() as f64).round() as usize +} + +/// Resampler delay and rounding move the total by a few samples, so +/// compare with room for that rather than exactly. +fn assert_close(got: usize, expected: usize, what: &str) { + let slack = 16; + assert!( + got.abs_diff(expected) <= slack, + "{what}: got {got} samples, expected {expected} ± {slack}", + ); +} From 2f4c14ea4ce1a7661c3b76cb0334ea50adf42a86 Mon Sep 17 00:00:00 2001 From: Patrick Hayes Date: Thu, 6 Aug 2026 06:36:19 -0700 Subject: [PATCH 02/10] Fixing up confusion between None meaning end-of-stream and None meaning no-spans (stable stream format) --- src/conversions/sample_rate/mod.rs | 4 +++- src/conversions/sample_rate/tests.rs | 13 +++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/conversions/sample_rate/mod.rs b/src/conversions/sample_rate/mod.rs index 0d932ca8..2f81a11f 100644 --- a/src/conversions/sample_rate/mod.rs +++ b/src/conversions/sample_rate/mod.rs @@ -416,7 +416,9 @@ where }; let input_span_len = source.current_span_len(); // No span length means the format is stable by contract. - input_span_len?; + if input_span_len.is_none() { + return Some(sample); + } *input_span_pos += 1usize; let (expected_channels, expected_rate, samples_consumed) = (*channels, *source_rate, *input_span_pos); diff --git a/src/conversions/sample_rate/tests.rs b/src/conversions/sample_rate/tests.rs index 6ca08cea..4aa47bcc 100644 --- a/src/conversions/sample_rate/tests.rs +++ b/src/conversions/sample_rate/tests.rs @@ -444,3 +444,16 @@ fn assert_close(got: usize, expected: usize, what: &str) { "{what}: got {got} samples, expected {expected} ± {slack}", ); } + +/// Passthrough must keep yielding when the input reports no span length. +#[test] +fn passthrough_none_span_len_yields_samples() { + let rate = crate::DEFAULT_SAMPLE_RATE; + let mut out = + SampleRateConverter::new(SineWave::new(440.0), rate, ResampleConfig::poly().build()); + let n = (&mut out).take(32).count(); + assert_eq!( + n, 32, + "Passthrough with current_span_len() == None stopped early (got {n})" + ); +} From 6e4b0bf9a4a01d33c4862f3b3014051cd32a9b80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benoi=CC=82t=20Rouleau?= Date: Wed, 25 Nov 2026 15:41:53 -0500 Subject: [PATCH 03/10] chain: move on as soon as a source ends Until the next call to `next`, a finished source stayed current, so the chain reported its `Some(0)`: the end of the whole stream, per the `Source` contract. A resampler reading across spans takes it at its word, so resampling a chain of a 600-frame buffer and a 64-frame one at 24 kHz to 48 kHz stopped at 1200 samples instead of 1328. Advance right after the last sample instead, as `Repeat` does, so the span length, channel count and sample rate always describe the next sample. That also fixes the FIXME in the `basic` test. Co-Authored-By: Claude Opus 5.5 Co-authored-by: multica-agent --- CHANGELOG.md | 1 + src/source/chain.rs | 44 +++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8bcc53bd..c6f0532b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fixed `Stoppable` and `Skippable` not signaling exhaustion. - Fixed `SpatialAudio` left and write channel swapping - Fixed resampled output depending on how the input is split into spans. +- Fixed `chain` reporting the end of the stream between two of its sources. ## Version [0.22.2] (2026-03-05) diff --git a/src/source/chain.rs b/src/source/chain.rs index e64ab88c..070a690f 100644 --- a/src/source/chain.rs +++ b/src/source/chain.rs @@ -37,6 +37,25 @@ where current_source: Option, } +impl Chain +where + I: Iterator, + I::Item: Source, +{ + fn skip_finished_sources(&mut self) { + while self + .current_source + .as_ref() + .is_some_and(Source::is_exhausted) + { + let Some(next) = self.iterator.next() else { + return; + }; + self.current_source = Some(next); + } + } +} + impl Iterator for Chain where I: Iterator, @@ -49,6 +68,12 @@ where loop { if let Some(src) = &mut self.current_source { if let Some(value) = src.next() { + // Move on as soon as a source reports its end, so + // `current_span_len`, `channels` and `sample_rate` + // describe the next sample rather than a finished + // source. Its `Some(0)` would otherwise read as the + // end of the whole chain. + self.skip_finished_sources(); return Some(value); } } @@ -145,6 +170,20 @@ mod tests { assert_eq!(c.current_span_len(), Some(0)); } + #[test] + fn reports_next_source_once_one_ends() { + let mut c = chain([ + SamplesBuffer::new(nz!(1), nz!(24000), vec![1.0, 2.0]), + SamplesBuffer::new(nz!(1), nz!(24000), vec![]), + SamplesBuffer::new(nz!(1), nz!(24000), vec![3.0]), + ]); + c.next(); + c.next(); + assert!(!c.is_exhausted(), "a finished source isn't the chain's end"); + assert_eq!(c.current_span_len(), Some(1)); + assert_eq!(c.collect::>(), [3.0]); + } + #[test] fn basic() { let mut rx = chain((0..2).map(|n| { @@ -163,9 +202,8 @@ mod tests { assert_eq!(rx.next(), Some(-10.0)); assert_eq!(rx.next(), Some(10.0)); assert_eq!(rx.next(), Some(-10.0)); - /*assert_eq!(rx.channels(), 2); - assert_eq!(rx.sample_rate().get(), 96000);*/ - // FIXME: not working + assert_eq!(rx.channels(), nz!(2)); + assert_eq!(rx.sample_rate().get(), 96000); assert_eq!(rx.next(), Some(5.0)); assert_eq!(rx.next(), Some(5.0)); assert_eq!(rx.next(), Some(5.0)); From e0804290c08d8770d2ee14a503e88cd116c30dcf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benoi=CC=82t=20Rouleau?= Date: Wed, 25 Nov 2026 15:41:53 -0500 Subject: [PATCH 04/10] resampler: report the format of the samples still to come Reading across spans means the input is often further along than the samples being yielded, but `channels()`, `is_exhausted()` and the format checks in `UniformSourceIterator` all looked at the input: - `channels()` turned stereo while mono samples were still buffered. - `is_exhausted()` was true once the input ran out, with rubato still holding the tail of a sinc filter. - `UniformSourceIterator` saw the next span's rate on the input and rebuilt, dropping what the resampler had buffered. Through `Mixer::add` at 48 kHz, 128 and 64 frames at 24 kHz then 96 at 48 kHz played 224 samples instead of 480. The resampler now reports the format it was built for while it holds samples of it, and the input's after. `UniformSourceIterator` asks it before every sample while resampling, since counting spans can't tell where its format changes, and resamples before remixing channels, so a resampler always reads its raw input and sees where a span changes format. Its span count starts from what it yields, and it checks the format on the first pull, as a queue added while empty has moved on. `size_hint()` applied the current ratio to every span after the one being read, whose rate may differ, and the passthrough counted them one to one. Only the span being read is counted now, with room for each chunk rounding up, and the upper bound is unknown past it. Co-Authored-By: Claude Opus 5.5 Co-authored-by: multica-agent --- src/conversions/sample_rate/mod.rs | 61 +++++++------ src/conversions/sample_rate/rubato.rs | 85 ++++++++++++++++-- src/conversions/sample_rate/tests.rs | 119 +++++++++++++++++++++++++ src/mixer/tests.rs | 42 +++++++++ src/source/uniform.rs | 121 ++++++++++++++------------ 5 files changed, 343 insertions(+), 85 deletions(-) diff --git a/src/conversions/sample_rate/mod.rs b/src/conversions/sample_rate/mod.rs index 2f81a11f..1d2c501b 100644 --- a/src/conversions/sample_rate/mod.rs +++ b/src/conversions/sample_rate/mod.rs @@ -269,6 +269,13 @@ where } } + /// The channel count and sample rate of the input the next sample + /// comes from. The input itself may already be further along. + #[inline] + pub(crate) fn next_input_format(&self) -> (ChannelCount, SampleRate) { + self.resampler().next_format() + } + /// Returns the inner source. #[inline] pub fn into_inner(self) -> I { @@ -324,9 +331,11 @@ where self.target_rate } + /// The channel count of the samples `next` yields, which lags the + /// input's while samples read from before a change are still buffered. #[inline] fn channels(&self) -> ChannelCount { - self.resampler().input().channels() + self.resampler().next_format().0 } #[inline] @@ -448,34 +457,34 @@ where #[inline] fn size_hint(&self) -> (usize, Option) { match self.resampler() { - ResampleInner::Passthrough { source, .. } => source.size_hint(), - ResampleInner::Poly(resampler) | ResampleInner::Sinc(resampler) => { - let adjusted_for_resampling = |samples| { - InSamples(samples).resampled_by(resampler.resample_ratio) - + resampler.output.len() - + resampler - .frames_being_resampled - .samples(resampler.output.channels) + ResampleInner::Passthrough { + source, + input_span_pos, + channels, + source_rate, + } => { + let (lower, upper) = source.size_hint(); + if source.current_span_len().is_none() { + return (lower, upper); + } + // Past this span the rate may change and need resampling, + // so only the rest of it passes through one to one. + let in_span = if self.pending_recreate + || source.channels() != *channels + || source.sample_rate() != *source_rate + { + 0 + } else { + self.cached_input_span_len + .map_or(0, |len| len.saturating_sub(input_span_pos.raw())) }; - let (lower, upper) = resampler.input.size_hint(); - let lower = adjusted_for_resampling(lower); - let upper = upper.map(adjusted_for_resampling); - (lower.raw(), upper.as_ref().map(OutSamples::raw)) + (lower.min(in_span), upper.filter(|&upper| upper <= in_span)) } - #[cfg(feature = "rubato-fft")] - ResampleInner::Fft(resampler) => { - let adjusted_for_resampling = |samples| { - InSamples(samples).resampled_by(resampler.resample_ratio) - + resampler.output.len() - + resampler - .frames_being_resampled - .samples(resampler.output.channels) - }; - let (lower, upper) = resampler.input.size_hint(); - let lower = adjusted_for_resampling(lower); - let upper = upper.map(adjusted_for_resampling); - (lower.raw(), upper.as_ref().map(OutSamples::raw)) + ResampleInner::Poly(resampler) | ResampleInner::Sinc(resampler) => { + resampler.size_hint() } + #[cfg(feature = "rubato-fft")] + ResampleInner::Fft(resampler) => resampler.size_hint(), } } } diff --git a/src/conversions/sample_rate/rubato.rs b/src/conversions/sample_rate/rubato.rs index c2bc3d04..c5a29085 100644 --- a/src/conversions/sample_rate/rubato.rs +++ b/src/conversions/sample_rate/rubato.rs @@ -77,6 +77,20 @@ impl ResampleInner { self.input().channels() == channels && self.input().sample_rate() == source_rate } + /// The format of the samples `next` yields: what a resampler was + /// built for while it still holds samples of it, then the input's. + #[inline] + pub fn next_format(&self) -> (ChannelCount, SampleRate) { + match self { + ResampleInner::Passthrough { source, .. } => (source.channels(), source.sample_rate()), + ResampleInner::Poly(resampler) | ResampleInner::Sinc(resampler) => { + resampler.next_format() + } + #[cfg(feature = "rubato-fft")] + ResampleInner::Fft(resampler) => resampler.next_format(), + } + } + /// Extract the inner input source, consuming the resampler #[inline] pub fn into_inner(self) -> I { @@ -125,12 +139,12 @@ impl> RubatoResample { if !self.output.is_empty() { // rest of the output buffer is rest of span Some(self.output.current_span_len()) - } else if self.input.is_exhausted() { + } else if self.input.is_exhausted() && self.resampler_empty() { Some(0) } else { // True span length unknown, return the smallest possible span since that is // always correct - Some(self.input.channels().get() as usize) + Some(self.next_format().0.get() as usize) } } @@ -139,6 +153,59 @@ impl> RubatoResample { !self.output.is_empty() } + /// Whether samples of the format this was built for are still to + /// come, buffered or inside rubato. + pub fn holds_samples(&self) -> bool { + self.output_has_samples() || !self.resampler_empty() + } + + /// See [`ResampleInner::next_format`]. + pub fn next_format(&self) -> (ChannelCount, SampleRate) { + if self.holds_samples() { + (self.output.channels, self.output.source_rate) + } else { + (self.input.channels(), self.input.sample_rate()) + } + } + + /// Bounds on the samples left, as `Iterator::size_hint`. The rate + /// may change after the span being read, so only input up to there + /// can be counted, and past it there's no upper bound. + pub fn size_hint(&self) -> (usize, Option) { + let buffered = + self.output.len() + self.frames_being_resampled.samples(self.output.channels); + let resampled = + |samples: usize| buffered + InSamples(samples).resampled_by(self.resample_ratio); + + // Input left in the format being resampled. + let in_format = if self.input.current_span_len().is_none() { + usize::MAX + } else if self.input.channels() != self.output.channels + || self.input.sample_rate() != self.output.source_rate + { + 0 + } else if self.span_remaining == InSamples::ZERO { + // Read up to a span boundary: the next span starts here. + self.input.current_span_len().unwrap_or(0) + } else { + self.span_remaining.raw() + }; + + // Each chunk rounds its output up, by less than a frame. + let channels = self.output.channels.get() as usize; + let per_chunk = self.resampler.input_frames_next().max(1); + let rounding = |samples: usize| ((samples / channels).div_ceil(per_chunk) + 1) * channels; + + let (lower, upper) = self.input.size_hint(); + let upper = upper + .filter(|&upper| upper <= in_format) + .map(|upper| resampled(upper) + rounding(upper)); + ( + resampled(lower.min(in_format)).raw(), + upper.map(|upper| upper.raw()), + ) + } + pub fn reset(&mut self) { self.resampler.reset(); self.output.reset(); @@ -255,6 +322,11 @@ impl> RubatoResample { true } + /// A resampler is built at the start of a span, so all of it is left. + fn first_span(input: &I) -> InSamples { + input.current_span_len().map_or(InSamples::MAX, InSamples) + } + fn resampler_empty(&self) -> bool { self.frames_being_resampled == OutFrameCount::ZERO } @@ -288,12 +360,13 @@ impl RubatoAsyncResample { let initial_output_delay = RubatoResample::>::output_delay(&resampler); + let span_remaining = Self::first_span(&input); Ok(Self { input, resampler, input_buffer: Input::new(input_buf_size.samples(channels)), output: Output::new(source_rate, channels, output_buf_size), - span_remaining: InSamples::ZERO, + span_remaining, output_delay_remaining: initial_output_delay, resample_ratio, frames_being_resampled: OutFrameCount::ZERO, @@ -339,12 +412,13 @@ impl RubatoAsyncResample { let initial_output_delay = RubatoResample::>::output_delay(&resampler); + let span_remaining = Self::first_span(&input); Ok(Self { input, resampler, input_buffer: Input::new(input_buf_size.samples(channels)), output: Output::new(source_rate, channels, output_buf_size), - span_remaining: InSamples::ZERO, + span_remaining, output_delay_remaining: initial_output_delay, resample_ratio, frames_being_resampled: OutFrameCount::ZERO, @@ -389,12 +463,13 @@ impl RubatoFftResample { let output_delay_remaining = RubatoFftResample::::output_delay(&resampler); + let span_remaining = Self::first_span(&input); Ok(Self { input, resampler, input_buffer: Input::new(input_buf_size.samples(channels)), output: Output::new(source_rate, channels, output_buf_size), - span_remaining: InSamples::ZERO, + span_remaining, output_delay_remaining, resample_ratio, frames_being_resampled: OutFrameCount::ZERO, diff --git a/src/conversions/sample_rate/tests.rs b/src/conversions/sample_rate/tests.rs index 4aa47bcc..107f549b 100644 --- a/src/conversions/sample_rate/tests.rs +++ b/src/conversions/sample_rate/tests.rs @@ -102,6 +102,12 @@ impl Iterator for TestSource { } Some(s) } + + fn size_hint(&self) -> (usize, Option) { + let left = self.spans.iter().skip(self.span).map(|s| s.samples.len()); + let left = left.sum::() - self.offset; + (left, Some(left)) + } } impl Source for TestSource { @@ -457,3 +463,116 @@ fn passthrough_none_span_len_yields_samples() { "Passthrough with current_span_len() == None stopped early (got {n})" ); } + +/// Spans of `(frames, rate, channels)`, one after the other. +fn spans_of(spans: &[(usize, u32, u16)]) -> TestSource { + let span = |&(frames, rate, channels): &(usize, u32, u16)| { + let channels = ChannelCount::new(channels).unwrap(); + let input = create_test_input(InFrameCount(frames), channels); + (input, SampleRate::new(rate).unwrap(), channels) + }; + let mut spans = spans.iter().map(span); + let (input, rate, channels) = spans.next().expect("at least one span"); + spans.fold(TestSource::new(input, rate, channels), |source, span| { + source.chain(span.0, span.1, span.2) + }) +} + +/// A resampler reads ahead of the samples it yields, so what it reports +/// must describe the next sample, not where its input has got to. +#[test] +fn channels_follow_the_samples_still_buffered() { + let target = SampleRate::new(48000).unwrap(); + let mut resampler = SampleRateConverter::new( + spans_of(&[(100, 24000, 1), (100, 24000, 2)]), + target, + ResampleConfig::poly().build(), + ); + + let mut mono = 0; + while resampler.channels().get() == 1 { + resampler.next().expect("the stereo span is still to come"); + mono += 1; + } + assert_close(mono, 200, "mono samples before channels() turned stereo"); + let stereo = resampler.count(); + assert_close(stereo, 400, "stereo samples after"); +} + +#[test] +fn is_exhausted_only_once_nothing_is_left() { + let target = SampleRate::new(44100).unwrap(); + // A sinc filter still holds samples after its input runs out. + let config = ResampleConfig::sinc() + .sinc_len(NonZero::new(16).unwrap()) + .build(); + let mut resampler = SampleRateConverter::new( + spans_of(&[(429, 22050, 2), (262, 12000, 2)]), + target, + config, + ); + + let mut emitted = 0; + loop { + let exhausted = resampler.is_exhausted(); + let Some(_) = resampler.next() else { + break; + }; + assert!(!exhausted, "is_exhausted() before sample {emitted}"); + emitted += 1; + } + assert!(resampler.is_exhausted()); +} + +/// Later spans may be at another rate, so the current ratio can't bound +/// them: past the span being read, only the lower bound may count on it. +#[test] +fn size_hint_holds_across_rate_changes() { + let target = SampleRate::new(48000).unwrap(); + for spans in [ + &[(64, 48000, 1), (128, 24000, 1)][..], + &[(64, 24000, 1), (256, 96000, 1)], + &[(128, 24000, 1), (128, 12000, 1)], + &[(128, 24000, 1), (256, 48000, 1)], + &[(441, 44100, 2), (441, 44100, 2)], + ] { + let mut resampler = + SampleRateConverter::new(spans_of(spans), target, ResampleConfig::poly().build()); + let mut hints = vec![resampler.size_hint()]; + while resampler.next().is_some() { + hints.push(resampler.size_hint()); + } + + let total = hints.len() - 1; + for (emitted, (lower, upper)) in hints.into_iter().enumerate() { + let left = total - emitted; + assert!( + lower <= left, + "{spans:?}: lower bound {lower} with {left} left" + ); + assert!( + upper.is_none_or(|upper| upper >= left), + "{spans:?}: upper bound {upper:?} with {left} left" + ); + } + } +} + +/// A finished buffer in a `chain` isn't the end of the stream. +#[test] +fn chain_is_resampled_to_its_end() { + use crate::buffer::SamplesBuffer; + use crate::source::chain; + + let (mono, rate) = ( + ChannelCount::new(1).unwrap(), + SampleRate::new(24000).unwrap(), + ); + let source = chain([ + SamplesBuffer::new(mono, rate, vec![0.5; 600]), + SamplesBuffer::new(mono, rate, vec![0.5; 64]), + ]); + let target = SampleRate::new(48000).unwrap(); + let output = SampleRateConverter::new(source, target, ResampleConfig::poly().build()).count(); + assert_close(output, 1328, "chain of two buffers"); +} diff --git a/src/mixer/tests.rs b/src/mixer/tests.rs index b55b5c65..4a60e046 100644 --- a/src/mixer/tests.rs +++ b/src/mixer/tests.rs @@ -138,3 +138,45 @@ fn added_taking_phase_into_account() { assert_eq!(rx.next(), Some(-10.0)); // not yet mixed (out of phase) assert_eq!(rx.next(), Some(15.0)); // mixing starts } + +/// Buffers played one after the other, as `(frames, rate, channels)`. +fn spans(spans: &[(usize, u32, u16)]) -> impl Source + Send { + let buffers: Vec<_> = spans + .iter() + .map(|&(frames, rate, channels)| { + let samples = vec![0.25; frames * channels as usize]; + SamplesBuffer::new( + channels.try_into().unwrap(), + rate.try_into().unwrap(), + samples, + ) + }) + .collect(); + crate::source::chain(buffers) +} + +/// A resampler reads ahead, so it has moved on to the next format while +/// samples of the last one are still to come. Those must still play. +#[test] +fn format_change_keeps_resampled_samples() { + for (spans_in, mixer_channels, expected) in [ + // Read up to the 48 kHz span with 24 kHz samples still buffered. + ( + &[(128, 24000, 1), (64, 24000, 1), (96, 48000, 1)][..], + 1, + 480, + ), + // Same, when the next span also changes the channel count. + (&[(300, 24000, 1), (200, 44100, 2)], 2, 1200 + 2 * 218), + // Downmixing as well as resampling. + (&[(300, 24000, 2), (200, 24000, 1)], 1, 600 + 400), + ] { + let (tx, rx) = mixer::mixer(mixer_channels.try_into().unwrap(), nz!(48000)); + tx.add(spans(spans_in)); + let played = rx.count(); + assert!( + played.abs_diff(expected) <= 16, + "{spans_in:?}: played {played} samples, expected {expected}" + ); + } +} diff --git a/src/source/uniform.rs b/src/source/uniform.rs index e3f7c1be..af7b59f7 100644 --- a/src/source/uniform.rs +++ b/src/source/uniform.rs @@ -11,8 +11,9 @@ enum UniformInner { Passthrough(I), SampleRate(SampleRateConverter), ChannelCount(ChannelCountConverter), - BothUpmix(ChannelCountConverter>), - BothDownmix(SampleRateConverter>), + // Resampled first even when downmixing: a resampler reads ahead, + // and only on its raw input can it see where a span changes format. + Both(ChannelCountConverter>), } impl Iterator for UniformInner { @@ -24,8 +25,7 @@ impl Iterator for UniformInner { UniformInner::Passthrough(take) => take.next(), UniformInner::SampleRate(converter) => converter.next(), UniformInner::ChannelCount(converter) => converter.next(), - UniformInner::BothUpmix(converter) => converter.next(), - UniformInner::BothDownmix(converter) => converter.next(), + UniformInner::Both(converter) => converter.next(), } } @@ -35,8 +35,7 @@ impl Iterator for UniformInner { UniformInner::Passthrough(take) => take.size_hint(), UniformInner::SampleRate(converter) => converter.size_hint(), UniformInner::ChannelCount(converter) => converter.size_hint(), - UniformInner::BothUpmix(converter) => converter.size_hint(), - UniformInner::BothDownmix(converter) => converter.size_hint(), + UniformInner::Both(converter) => converter.size_hint(), } } } @@ -48,8 +47,7 @@ impl UniformInner { UniformInner::Passthrough(source) => source, UniformInner::SampleRate(converter) => converter.into_inner(), UniformInner::ChannelCount(converter) => converter.into_inner(), - UniformInner::BothUpmix(converter) => converter.into_inner().into_inner(), - UniformInner::BothDownmix(converter) => converter.into_inner().into_inner(), + UniformInner::Both(converter) => converter.into_inner().into_inner(), } } @@ -59,8 +57,22 @@ impl UniformInner { UniformInner::Passthrough(source) => source, UniformInner::SampleRate(converter) => converter.inner(), UniformInner::ChannelCount(converter) => converter.inner(), - UniformInner::BothUpmix(converter) => converter.inner().inner(), - UniformInner::BothDownmix(converter) => converter.inner().inner(), + UniformInner::Both(converter) => converter.inner().inner(), + } + } + + /// The format of the input the next sample comes from. A resampler + /// has read ahead of it, so its input may already be further along. + #[inline] + fn next_input_format(&self) -> (ChannelCount, SampleRate) { + match self { + UniformInner::Passthrough(source) => (source.channels(), source.sample_rate()), + UniformInner::ChannelCount(converter) => ( + converter.inner().channels(), + converter.inner().sample_rate(), + ), + UniformInner::SampleRate(converter) => converter.next_input_format(), + UniformInner::Both(converter) => converter.inner().next_input_format(), } } @@ -70,16 +82,21 @@ impl UniformInner { UniformInner::Passthrough(source) => source, UniformInner::SampleRate(converter) => converter.inner_mut(), UniformInner::ChannelCount(converter) => converter.inner_mut(), - UniformInner::BothUpmix(converter) => converter.inner_mut().inner_mut(), - UniformInner::BothDownmix(converter) => converter.inner_mut().inner_mut(), + UniformInner::Both(converter) => converter.inner_mut().inner_mut(), } } } impl Source for UniformInner { + /// The span of the converted output, which is what gets counted. #[inline] fn current_span_len(&self) -> Option { - self.inner().current_span_len() + match self { + UniformInner::Passthrough(source) => source.current_span_len(), + UniformInner::SampleRate(converter) => converter.current_span_len(), + UniformInner::ChannelCount(converter) => converter.current_span_len(), + UniformInner::Both(converter) => converter.current_span_len(), + } } #[inline] @@ -136,7 +153,6 @@ where let current_channels = input.channels(); let current_sample_rate = input.sample_rate(); let inner = UniformSourceIterator::bootstrap(input, target_channels, target_sample_rate); - let cached_span_len = inner.current_span_len(); Self { inner: Some(inner), @@ -145,7 +161,9 @@ where current_channels, current_sample_rate, current_span_pos: 0, - cached_span_len, + // Check on the first pull too: the format may have changed + // since, like a queue that was empty when added to a mixer. + cached_span_len: Some(0), } } @@ -172,18 +190,11 @@ where ChannelCountConverter::new(input, from_channels, target_channels); UniformInner::ChannelCount(channel_converted) } - (true, true) if target_channels > from_channels => { + (true, true) => { let rate_converted = SampleRateConverter::new(input, target_sample_rate, config); let channel_converted = ChannelCountConverter::new(rate_converted, from_channels, target_channels); - UniformInner::BothUpmix(channel_converted) - } - (true, true) => { - let channel_converted = - ChannelCountConverter::new(input, from_channels, target_channels); - let rate_converted = - SampleRateConverter::new(channel_converted, target_sample_rate, config); - UniformInner::BothDownmix(rate_converted) + UniformInner::Both(channel_converted) } } } @@ -197,36 +208,38 @@ where #[inline] fn next(&mut self) -> Option { - if let Some(span_len) = self.cached_span_len { - if self.current_span_pos >= span_len { - // At span boundary - check if parameters changed - let source = self.inner.as_mut().unwrap().inner_mut(); - let new_channels = source.channels(); - let new_sample_rate = source.sample_rate(); - - let parameters_changed = new_channels != self.current_channels - || new_sample_rate != self.current_sample_rate; - - if parameters_changed { - let source = self.inner.take().unwrap().into_inner(); - self.current_channels = new_channels; - self.current_sample_rate = new_sample_rate; - let new_inner = UniformSourceIterator::bootstrap( - source, - self.target_channels, - self.target_sample_rate, - ); - self.inner = Some(new_inner); - } - - // Calculate new output span length based on the conversion type - let new_span_len = match self.inner.as_ref().unwrap() { - UniformInner::Passthrough(source) => source.current_span_len(), - UniformInner::SampleRate(resample) => resample.current_span_len(), - UniformInner::ChannelCount(converter) => converter.current_span_len(), - UniformInner::BothUpmix(converter) => converter.current_span_len(), - UniformInner::BothDownmix(converter) => converter.current_span_len(), - }; + let mut at_boundary = self + .cached_span_len + .is_some_and(|span_len| self.current_span_pos >= span_len); + // A resampler reads ahead of its input, so neither the input's + // format nor counting spans tells where the format of what it + // yields changes. It knows, cheaply, so ask before every sample. + let resamples = matches!( + self.inner, + Some(UniformInner::SampleRate(_) | UniformInner::Both(_)) + ); + + if at_boundary || resamples { + let (new_channels, new_sample_rate) = self.inner.as_ref().unwrap().next_input_format(); + + let parameters_changed = new_channels != self.current_channels + || new_sample_rate != self.current_sample_rate; + + if parameters_changed { + let source = self.inner.take().unwrap().into_inner(); + self.current_channels = new_channels; + self.current_sample_rate = new_sample_rate; + let new_inner = UniformSourceIterator::bootstrap( + source, + self.target_channels, + self.target_sample_rate, + ); + self.inner = Some(new_inner); + at_boundary = true; + } + + if at_boundary { + let new_span_len = self.inner.as_ref().unwrap().current_span_len(); self.current_span_pos = 0; self.cached_span_len = new_span_len; From 2ba89bce2c078c2994c4afe9af6af11daf5273b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benoi=CC=82t=20Rouleau?= Date: Wed, 25 Nov 2026 16:02:00 -0500 Subject: [PATCH 05/10] resampler: end a format's samples on the input, not on silence Keeping what a resampler buffered past a format change, rather than dropping it, brought out two things wrong with its last frames: - Output was counted by rounding up each chunk on its own, which can count a frame more than the input gives, once per chunk. At the end of a stream that's a little silence; before a format change it's a gap in the middle: 44.1 kHz music sped up to 2.5x, as a player's `set_speed` does, came out with 19 frames of silence at the change. Count from the totals in and out instead, in integers, which is also what `size_hint` now counts with. - The chunk that stops at a format change was marked partial, so rubato padded it with silence and the last frames were interpolated towards it, ending in a click. Pad it with the last frame read instead: the frames taken out only cover real input, so the padding only stands in for the input that would have followed. A reset now also forgets what was being resampled before it. Co-Authored-By: Claude Opus 5.5 Co-authored-by: multica-agent --- src/conversions/sample_rate/rubato.rs | 104 +++++++++++++++++++------- src/conversions/sample_rate/tests.rs | 38 ++++++++++ 2 files changed, 117 insertions(+), 25 deletions(-) diff --git a/src/conversions/sample_rate/rubato.rs b/src/conversions/sample_rate/rubato.rs index c5a29085..6f63fefe 100644 --- a/src/conversions/sample_rate/rubato.rs +++ b/src/conversions/sample_rate/rubato.rs @@ -113,9 +113,6 @@ pub struct RubatoResample> { pub input_buffer: super::buffer::Input, pub(crate) output: super::buffer::Output, - /// The following are cached at construction for parameter-change detection. - pub resample_ratio: Float, - pub output_delay_remaining: OutFrameCount, /// How much of the span being read is left. Tracked because @@ -123,7 +120,19 @@ pub struct RubatoResample> { /// not its remainder. span_remaining: InSamples, + /// Output frames still to come from what rubato has been given. pub frames_being_resampled: OutFrameCount, + target_rate: SampleRate, + /// Input frames given to rubato and frames taken out, since it was + /// built or reset. Its output is counted from these totals: rounding + /// each chunk on its own would count up to a frame too many per + /// chunk, which came out as silence before a format change. + frames_in_total: u64, + frames_out_total: u64, + /// The last frame read, which pads the chunk that ends at a format + /// change: rubato would pad it with silence, and the last frames + /// would fall towards it. + last_frame: Box<[Sample]>, } impl> RubatoResample { @@ -172,10 +181,14 @@ impl> RubatoResample { /// may change after the span being read, so only input up to there /// can be counted, and past it there's no upper bound. pub fn size_hint(&self) -> (usize, Option) { - let buffered = - self.output.len() + self.frames_being_resampled.samples(self.output.channels); - let resampled = - |samples: usize| buffered + InSamples(samples).resampled_by(self.resample_ratio); + let channels = self.output.channels.get() as usize; + let buffered = self.output.len().raw() + self.frames_being_resampled.raw() * channels; + // Samples out for `frames` more frames in, counted as rubato is. + let resampled = |frames: usize| { + let total = self.frames_in_total + frames as u64; + let frames = self.frames_out_for(total) - self.frames_out_for(self.frames_in_total); + buffered + frames as usize * channels + }; // Input left in the format being resampled. let in_format = if self.input.current_span_len().is_none() { @@ -191,19 +204,11 @@ impl> RubatoResample { self.span_remaining.raw() }; - // Each chunk rounds its output up, by less than a frame. - let channels = self.output.channels.get() as usize; - let per_chunk = self.resampler.input_frames_next().max(1); - let rounding = |samples: usize| ((samples / channels).div_ceil(per_chunk) + 1) * channels; - let (lower, upper) = self.input.size_hint(); let upper = upper .filter(|&upper| upper <= in_format) - .map(|upper| resampled(upper) + rounding(upper)); - ( - resampled(lower.min(in_format)).raw(), - upper.map(|upper| upper.raw()), - ) + .map(|upper| resampled(upper.div_ceil(channels))); + (resampled(lower.min(in_format) / channels), upper) } pub fn reset(&mut self) { @@ -211,6 +216,25 @@ impl> RubatoResample { self.output.reset(); self.span_remaining = InSamples::ZERO; self.output_delay_remaining = Self::output_delay(&self.resampler); + self.frames_being_resampled = OutFrameCount::ZERO; + self.frames_in_total = 0; + self.frames_out_total = 0; + } + + /// Output frames for `frames_in` input frames: one for each output + /// instant before the end of the input. + fn frames_out_for(&self, frames_in: u64) -> u64 { + let target = u128::from(self.target_rate.get()); + let source = u128::from(self.output.source_rate.get()); + (u128::from(frames_in) * target).div_ceil(source) as u64 + } + + /// Whether reading stopped at a span in another format, rather than + /// at the end of the stream. + fn stopped_at_format_change(&self) -> bool { + self.input.current_span_len() != Some(0) + && (self.input.channels() != self.output.channels + || self.input.sample_rate() != self.output.source_rate) } pub fn next_sample(&mut self) -> Option { @@ -237,12 +261,27 @@ impl> RubatoResample { return None; } - self.frames_being_resampled += frames_in.resampled_by(self.resample_ratio); + self.frames_in_total += frames_in.raw() as u64; + self.frames_being_resampled = OutFrameCount( + (self.frames_out_for(self.frames_in_total) - self.frames_out_total) as usize, + ); + + let mut partial_len = (frames_in < needed_by_resampler).then_some(frames_in.raw()); + if partial_len.is_some() && self.stopped_at_format_change() { + // Hold the last frame instead, so the frames before the change + // don't fall towards silence. They're all that's taken out. + while self.input_buffer.len().frames(self.output.channels) < needed_by_resampler { + for &sample in &self.last_frame { + self.input_buffer.push(sample); + } + } + partial_len = None; + } let indexing = Some(&rubato::Indexing { input_offset: 0, output_offset: 0, - partial_len: (frames_in < needed_by_resampler).then_some(frames_in.raw()), + partial_len, active_channels_mask: None, }); @@ -277,7 +316,9 @@ impl> RubatoResample { self.output.set_end(frames_out); self.output.set_len(resampled_frames); - self.frames_being_resampled -= self.output.len().frames(self.output.channels); + let taken = self.output.len().frames(self.output.channels); + self.frames_being_resampled -= taken; + self.frames_out_total += taken.raw() as u64; Some(()) } @@ -301,6 +342,12 @@ impl> RubatoResample { self.span_remaining -= InSamples(1); } + let read = self.input_buffer.len().raw(); + let channels = self.last_frame.len(); + if read >= channels { + self.last_frame + .copy_from_slice(&self.input_buffer.samples[read - channels..read]); + } self.input_buffer.len().frames(self.output.channels) } @@ -368,8 +415,11 @@ impl RubatoAsyncResample { output: Output::new(source_rate, channels, output_buf_size), span_remaining, output_delay_remaining: initial_output_delay, - resample_ratio, frames_being_resampled: OutFrameCount::ZERO, + target_rate, + frames_in_total: 0, + frames_out_total: 0, + last_frame: vec![0.0; channels.get().into()].into_boxed_slice(), }) } @@ -420,8 +470,11 @@ impl RubatoAsyncResample { output: Output::new(source_rate, channels, output_buf_size), span_remaining, output_delay_remaining: initial_output_delay, - resample_ratio, frames_being_resampled: OutFrameCount::ZERO, + target_rate, + frames_in_total: 0, + frames_out_total: 0, + last_frame: vec![0.0; channels.get().into()].into_boxed_slice(), }) } } @@ -459,8 +512,6 @@ impl RubatoFftResample { let input_buf_size = InFrameCount(resampler.input_frames_max()); let output_buf_size = OutFrameCount(resampler.output_frames_max()); - let resample_ratio = target_rate.get() as Float / source_rate.get() as Float; - let output_delay_remaining = RubatoFftResample::::output_delay(&resampler); let span_remaining = Self::first_span(&input); @@ -471,8 +522,11 @@ impl RubatoFftResample { output: Output::new(source_rate, channels, output_buf_size), span_remaining, output_delay_remaining, - resample_ratio, frames_being_resampled: OutFrameCount::ZERO, + target_rate, + frames_in_total: 0, + frames_out_total: 0, + last_frame: vec![0.0; channels.get().into()].into_boxed_slice(), }) } } diff --git a/src/conversions/sample_rate/tests.rs b/src/conversions/sample_rate/tests.rs index 107f549b..6035af38 100644 --- a/src/conversions/sample_rate/tests.rs +++ b/src/conversions/sample_rate/tests.rs @@ -576,3 +576,41 @@ fn chain_is_resampled_to_its_end() { let output = SampleRateConverter::new(source, target, ResampleConfig::poly().build()).count(); assert_close(output, 1328, "chain of two buffers"); } + +/// The last frames before a format change are interpolated like any +/// others: not towards silence, nor with silence counted in after them. +#[test] +fn frames_before_a_format_change_follow_the_input() { + let mono = ChannelCount::new(1).unwrap(); + let (rate, next_rate) = ( + SampleRate::new(44100).unwrap(), + SampleRate::new(110250).unwrap(), + ); + let frames = 20_000; + // Many chunks, so rounding each one's output would add up. + let ramp: Vec = (0..frames) + .map(|i| i as Sample / frames as Sample) + .collect(); + let source = TestSource::new(ramp, rate, mono).chain(vec![1.0; 4410], next_rate, mono); + let target = SampleRate::new(48000).unwrap(); + let config = ResampleConfig::poly().degree(Poly::Linear).build(); + let output: Vec = SampleRateConverter::new(source, target, config).collect(); + + let before_change = resampled_len(InFrameCount(frames), rate, target); + let tail = &output[..before_change]; + for (i, pair) in tail.windows(2).enumerate() { + assert!( + pair[1] >= pair[0], + "frame {} falls from {} to {}", + i + 1, + pair[0], + pair[1] + ); + } + let step = 1.0 / frames as Sample; + let last = tail.last().copied().unwrap_or_default(); + assert!( + last >= 1.0 - 3.0 * step, + "the last frame before the change is {last}, not the input's end" + ); +} From 8da1e2a36cb57047acaabfdd712f8e4f6e4b20fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benoi=CC=82t=20Rouleau?= Date: Wed, 25 Nov 2026 16:27:48 -0500 Subject: [PATCH 06/10] uniform: finish an upmixed frame before the format changes The channel converter repeats a mono sample into the next channel after reading it. Once the resampler has moved on to the next span, UniformSourceIterator saw the new format between those two samples and rebuilt there, dropping the repeat and swapping every channel after it. Only switch formats between output frames. Co-authored-by: multica-agent --- src/conversions/channels.rs | 7 ++++ src/mixer/tests.rs | 20 +++++++++ src/source/uniform.rs | 83 ++++++++++++++++++++++++++++++++++++- 3 files changed, 109 insertions(+), 1 deletion(-) diff --git a/src/conversions/channels.rs b/src/conversions/channels.rs index 94bcf442..4c065da4 100644 --- a/src/conversions/channels.rs +++ b/src/conversions/channels.rs @@ -51,6 +51,13 @@ where pub fn inner_mut(&mut self) -> &mut I { &mut self.input } + + /// Whether the next sample starts an output frame. Mid-frame, the + /// rest of the frame may still come from input already read. + #[inline] + pub(crate) fn at_frame_start(&self) -> bool { + self.next_output_sample_pos == 0 + } } impl Iterator for ChannelCountConverter diff --git a/src/mixer/tests.rs b/src/mixer/tests.rs index 4a60e046..59e43a0b 100644 --- a/src/mixer/tests.rs +++ b/src/mixer/tests.rs @@ -178,5 +178,25 @@ fn format_change_keeps_resampled_samples() { played.abs_diff(expected) <= 16, "{spans_in:?}: played {played} samples, expected {expected}" ); + assert_eq!( + played % mixer_channels as usize, + 0, + "{spans_in:?}: played {played} samples, not whole frames" + ); } } + +/// Upmixed to stereo, the frame being played is finished in the format +/// it started in, so the next span's channels stay in place. +#[test] +fn format_change_keeps_channels_in_place() { + let (tx, rx) = mixer::mixer(nz!(2), nz!(48000)); + tx.add(crate::source::chain([ + SamplesBuffer::new(nz!(1), nz!(24000), vec![0.25; 300]), + SamplesBuffer::new(nz!(2), nz!(48000), [0.5, 0.75].repeat(200)), + ])); + let played: Vec<_> = rx.collect(); + assert_eq!(played.len(), 1600); + assert!(played[..1200].chunks(2).all(|frame| frame[0] == frame[1])); + assert!(played[1200..].chunks(2).all(|frame| frame == [0.5, 0.75])); +} diff --git a/src/source/uniform.rs b/src/source/uniform.rs index af7b59f7..c595f299 100644 --- a/src/source/uniform.rs +++ b/src/source/uniform.rs @@ -76,6 +76,18 @@ impl UniformInner { } } + /// Whether the next sample starts an output frame. Mid-frame, the + /// channel converter still owes samples of input it has read, so + /// rebuilding there would drop them and shift every later channel. + #[inline] + fn at_frame_start(&self) -> bool { + match self { + UniformInner::Passthrough(_) | UniformInner::SampleRate(_) => true, + UniformInner::ChannelCount(converter) => converter.at_frame_start(), + UniformInner::Both(converter) => converter.at_frame_start(), + } + } + #[inline] fn inner_mut(&mut self) -> &mut I { match self { @@ -219,7 +231,9 @@ where Some(UniformInner::SampleRate(_) | UniformInner::Both(_)) ); - if at_boundary || resamples { + // Only between output frames: a frame is finished in the format + // it started in. + if (at_boundary || resamples) && self.inner.as_ref().unwrap().at_frame_start() { let (new_channels, new_sample_rate) = self.inner.as_ref().unwrap().next_input_format(); let parameters_changed = new_channels != self.current_channels @@ -296,3 +310,70 @@ where } } } + +#[cfg(test)] +mod tests { + use super::UniformSourceIterator; + use crate::buffer::SamplesBuffer; + use crate::math::nz; + use crate::source::chain; + use crate::{Sample, Source}; + + /// A mono span, then a stereo one whose channels differ, so a sample + /// lost or added at the switch swaps every channel after it. + fn mono_then_stereo(mono_rate: u32, stereo_rate: u32) -> impl Source { + chain([ + SamplesBuffer::new(nz!(1), mono_rate.try_into().unwrap(), vec![0.25; 300]), + SamplesBuffer::new( + nz!(2), + stereo_rate.try_into().unwrap(), + [0.5, 0.75].repeat(200), + ), + ]) + } + + fn assert_frames_aligned(out: &[Sample], stereo_from: usize) { + assert_eq!(out.len(), stereo_from + 400, "length"); + for (i, frame) in out[..stereo_from].chunks(2).enumerate() { + assert_eq!(frame[0], frame[1], "upmixed mono frame {i}"); + } + for (i, frame) in out[stereo_from..].chunks(2).enumerate() { + assert_eq!(frame, [0.5, 0.75], "stereo frame {i}"); + } + } + + /// An upmixed frame is finished before the format changes, even + /// once the resampler has already moved on to the next span. + #[test] + fn upmixed_frame_ends_before_a_resampled_format_change() { + let out: Vec<_> = + UniformSourceIterator::new(mono_then_stereo(24000, 48000), nz!(2), nz!(48000)) + .collect(); + assert_frames_aligned(&out, 1200); + } + + #[test] + fn upmixed_frame_ends_before_a_format_change() { + let out: Vec<_> = + UniformSourceIterator::new(mono_then_stereo(48000, 48000), nz!(2), nz!(48000)) + .collect(); + assert_frames_aligned(&out, 600); + } + + #[test] + fn upmixed_frame_ends_before_a_rate_change() { + let out: Vec<_> = + UniformSourceIterator::new(mono_then_stereo(24000, 24000), nz!(2), nz!(48000)) + .collect(); + // Both spans resampled: the stereo one doubles to 400 frames. + // Its first frame blends in the mono span's last sample, and its + // last one the silence after the end. + assert_eq!(out.len(), 1200 + 800, "length"); + for (i, frame) in out[..1200].chunks(2).enumerate() { + assert_eq!(frame[0], frame[1], "upmixed mono frame {i}"); + } + for (i, frame) in out[1202..out.len() - 2].chunks(2).enumerate() { + assert_eq!(frame, [0.5, 0.75], "stereo frame {i}"); + } + } +} From bd375e71556d9294dea1b5a96d50b39439a6b151 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benoi=CC=82t=20Rouleau?= Date: Wed, 25 Nov 2026 17:19:32 -0500 Subject: [PATCH 07/10] resampler: start on the input's first frame, not on silence Rubato's history starts as silence, and the first frames out land just before the input's start, so they were interpolated partly from it. At the start of a sound that's a soft first frame. But UniformSourceIterator builds a new resampler at every format change, which `Player::set_speed` makes, and a seek resets one: there, the first frame dipped. A linear resampler from 44.1 to 48 kHz gave 92% of the first frame; the balanced sinc resampler as little as 3% at 110.25 kHz, and 56% at 44.1 kHz. Feed rubato copies of the first frame ahead of it, as far back as its filter reaches, and skip their output along with the delay. Where the rates allow it within 1024 frames, the lead-in is a whole number of output frames, so the output keeps its timing exactly. Otherwise it moves by less than half a frame. Co-Authored-By: Claude Opus 5.5 Co-authored-by: multica-agent --- src/conversions/sample_rate/rubato.rs | 173 ++++++++++++++++++++++---- src/conversions/sample_rate/tests.rs | 122 ++++++++++++++++++ src/source/uniform.rs | 23 ++++ 3 files changed, 296 insertions(+), 22 deletions(-) diff --git a/src/conversions/sample_rate/rubato.rs b/src/conversions/sample_rate/rubato.rs index 6f63fefe..8bef5433 100644 --- a/src/conversions/sample_rate/rubato.rs +++ b/src/conversions/sample_rate/rubato.rs @@ -133,15 +133,62 @@ pub struct RubatoResample> { /// change: rubato would pad it with silence, and the last frames /// would fall towards it. last_frame: Box<[Sample]>, + /// Copies of the first frame still to feed rubato ahead of it. Its + /// history starts as silence, and the first frames out, which land + /// just before the input's start, would be interpolated partly from + /// it: a soft start, and a dip where a resampler is built mid-stream + /// or after a seek. + lead_in: usize, + /// Whether the first frame has been read into `last_frame` for the + /// lead-in, and is still to be fed after it. + lead_in_read: bool, } impl> RubatoResample { - /// Calculate the number of output samples to skip for delay compensation. - pub fn output_delay(resampler: &R) -> OutFrameCount { + /// Frames of lead-in: as far back as the filter reaches from the + /// first frame out, which can land up to two frames before the + /// input's start, with a frame to spare. Rounded up to a whole + /// number of output frames where that's not many more, so skipping + /// them keeps the output's timing exactly. + fn lead_in_frames(resampler: &R, source_rate: SampleRate, target_rate: SampleRate) -> usize { + const MAX_PERIOD: u32 = 1024; + let (source, target) = (source_rate.get(), target_rate.get()); + let reach = resampler.output_delay() as u64 + 3; + let frames = (reach * u64::from(source)).div_ceil(u64::from(target)) as usize + 1; + let period = source / crate::math::gcd(source, target); + if period <= MAX_PERIOD { + frames.next_multiple_of(period as usize) + } else { + frames + } + } + + /// Calculate the number of output frames to skip for delay compensation. + pub fn output_delay( + resampler: &R, + lead_in: usize, + source_rate: SampleRate, + target_rate: SampleRate, + ) -> OutFrameCount { // Skip delay-1 frames to align the first output frame with input position 0. let delay_frames = resampler.output_delay(); let delay_frames = delay_frames.saturating_sub(1); - OutFrameCount(delay_frames) + // And the frames out for the lead-in, to the nearest: the output + // moves by less than half a frame, if at all. + let (target, source) = (u64::from(target_rate.get()), u64::from(source_rate.get())); + let lead_in = (2 * lead_in as u64 * target + source) / (2 * source); + OutFrameCount(delay_frames + lead_in as usize) + } + + /// The lead-in and output delay of a new or reset resampler. + fn start_state( + resampler: &R, + source_rate: SampleRate, + target_rate: SampleRate, + ) -> (usize, OutFrameCount) { + let lead_in = Self::lead_in_frames(resampler, source_rate, target_rate); + let delay = Self::output_delay(resampler, lead_in, source_rate, target_rate); + (lead_in, delay) } pub fn span_length(&self) -> Option { @@ -215,7 +262,9 @@ impl> RubatoResample { self.resampler.reset(); self.output.reset(); self.span_remaining = InSamples::ZERO; - self.output_delay_remaining = Self::output_delay(&self.resampler); + (self.lead_in, self.output_delay_remaining) = + Self::start_state(&self.resampler, self.output.source_rate, self.target_rate); + self.lead_in_read = false; self.frames_being_resampled = OutFrameCount::ZERO; self.frames_in_total = 0; self.frames_out_total = 0; @@ -256,8 +305,8 @@ impl> RubatoResample { #[inline(never)] fn resample_chunk(&mut self) -> Option<()> { let needed_by_resampler = InFrameCount(self.resampler.input_frames_next()); - let frames_in = self.fill_input_buffer(needed_by_resampler); - if frames_in == InFrameCount::ZERO && self.resampler_empty() { + let (frames_buffered, frames_in) = self.fill_input_buffer(needed_by_resampler); + if frames_buffered == InFrameCount::ZERO && self.resampler_empty() { return None; } @@ -266,7 +315,8 @@ impl> RubatoResample { (self.frames_out_for(self.frames_in_total) - self.frames_out_total) as usize, ); - let mut partial_len = (frames_in < needed_by_resampler).then_some(frames_in.raw()); + let mut partial_len = + (frames_buffered < needed_by_resampler).then_some(frames_buffered.raw()); if partial_len.is_some() && self.stopped_at_format_change() { // Hold the last frame instead, so the frames before the change // don't fall towards silence. They're all that's taken out. @@ -327,10 +377,81 @@ impl> RubatoResample { /// and only a span that changes it has to end the chunk. A short /// read then means end of stream or a format change, which is when /// rubato should treat the chunk as partial. - fn fill_input_buffer(&mut self, needed_by_resampler: InFrameCount) -> InFrameCount { - let wanted = needed_by_resampler.samples(self.output.channels); + /// + /// Returns the frames buffered, lead-in included, and the frames + /// read from the input. + fn fill_input_buffer( + &mut self, + needed_by_resampler: InFrameCount, + ) -> (InFrameCount, InFrameCount) { + let channels = self.output.channels; + let wanted = needed_by_resampler.samples(channels); self.input_buffer.clear(); + let mut read = InSamples::ZERO; + if self.lead_in > 0 { + read = self.lead_in_with_first_frame(wanted); + } + if self.lead_in > 0 { + // The lead-in fills this chunk, and goes on into the next. + return ( + self.input_buffer.len().frames(channels), + read.frames(channels), + ); + } + read += self.read_input(wanted); + + let len = self.input_buffer.len().raw(); + let frame = self.last_frame.len(); + if len >= frame { + self.last_frame + .copy_from_slice(&self.input_buffer.samples[len - frame..len]); + } + ( + self.input_buffer.len().frames(channels), + read.frames(channels), + ) + } + + /// Reads the first frame and buffers the lead-in ahead of it, as + /// much of both as fits before `wanted`. Returns the samples read. + fn lead_in_with_first_frame(&mut self, wanted: InSamples) -> InSamples { + let mut read = InSamples::ZERO; + if !self.lead_in_read { + read = self.read_input(InSamples(self.last_frame.len())); + if read.raw() < self.last_frame.len() { + // No whole frame to lead in with: leave what was read + // as it is. + self.lead_in = 0; + return read; + } + self.last_frame + .copy_from_slice(&self.input_buffer.samples[..read.raw()]); + self.input_buffer.clear(); + self.lead_in_read = true; + } + + // Then the first frame itself, once the lead-in is all in. + let copies = self.lead_in + 1; + let room = (wanted - self.input_buffer.len()).raw() / self.last_frame.len(); + for _ in 0..copies.min(room) { + for &sample in &self.last_frame { + self.input_buffer.push(sample); + } + } + if room >= copies { + self.lead_in = 0; + self.lead_in_read = false; + } else { + self.lead_in -= room; + } + read + } + + /// Reads up to `wanted` samples in all into the input buffer, as far + /// as the format this was built for goes. Returns the samples read. + fn read_input(&mut self, wanted: InSamples) -> InSamples { + let start = self.input_buffer.len(); while self.input_buffer.len() < wanted { if self.span_remaining == InSamples::ZERO && !self.start_of_span() { break; @@ -341,14 +462,7 @@ impl> RubatoResample { self.input_buffer.push(sample); self.span_remaining -= InSamples(1); } - - let read = self.input_buffer.len().raw(); - let channels = self.last_frame.len(); - if read >= channels { - self.last_frame - .copy_from_slice(&self.input_buffer.samples[read - channels..read]); - } - self.input_buffer.len().frames(self.output.channels) + self.input_buffer.len() - start } /// Whether reading may continue into the next span, recording its @@ -404,8 +518,12 @@ impl RubatoAsyncResample { let input_buf_size = InFrameCount(resampler.input_frames_max()); let output_buf_size = OutFrameCount(resampler.output_frames_max()); - let initial_output_delay = - RubatoResample::>::output_delay(&resampler); + let (lead_in, initial_output_delay) = + RubatoResample::>::start_state( + &resampler, + source_rate, + target_rate, + ); let span_remaining = Self::first_span(&input); Ok(Self { @@ -420,6 +538,8 @@ impl RubatoAsyncResample { frames_in_total: 0, frames_out_total: 0, last_frame: vec![0.0; channels.get().into()].into_boxed_slice(), + lead_in, + lead_in_read: false, }) } @@ -459,8 +579,12 @@ impl RubatoAsyncResample { let input_buf_size = InFrameCount(resampler.input_frames_max()); let output_buf_size = OutFrameCount(resampler.output_frames_max()); - let initial_output_delay = - RubatoResample::>::output_delay(&resampler); + let (lead_in, initial_output_delay) = + RubatoResample::>::start_state( + &resampler, + source_rate, + target_rate, + ); let span_remaining = Self::first_span(&input); Ok(Self { @@ -475,6 +599,8 @@ impl RubatoAsyncResample { frames_in_total: 0, frames_out_total: 0, last_frame: vec![0.0; channels.get().into()].into_boxed_slice(), + lead_in, + lead_in_read: false, }) } } @@ -512,7 +638,8 @@ impl RubatoFftResample { let input_buf_size = InFrameCount(resampler.input_frames_max()); let output_buf_size = OutFrameCount(resampler.output_frames_max()); - let output_delay_remaining = RubatoFftResample::::output_delay(&resampler); + let (lead_in, output_delay_remaining) = + RubatoFftResample::::start_state(&resampler, source_rate, target_rate); let span_remaining = Self::first_span(&input); Ok(Self { @@ -527,6 +654,8 @@ impl RubatoFftResample { frames_in_total: 0, frames_out_total: 0, last_frame: vec![0.0; channels.get().into()].into_boxed_slice(), + lead_in, + lead_in_read: false, }) } } diff --git a/src/conversions/sample_rate/tests.rs b/src/conversions/sample_rate/tests.rs index 6035af38..94251184 100644 --- a/src/conversions/sample_rate/tests.rs +++ b/src/conversions/sample_rate/tests.rs @@ -614,3 +614,125 @@ fn frames_before_a_format_change_follow_the_input() { "the last frame before the change is {last}, not the input's end" ); } + +/// The resamplers to check a start with, each with how close to the +/// input its output has to stay: a sinc filter's gain isn't exactly one. +/// With `rubato-fft`, the sinc one is the FFT resampler at fixed ratios. +fn start_configs() -> [(&'static str, ResampleConfig, Sample); 3] { + [ + ( + "linear", + ResampleConfig::poly().degree(Poly::Linear).build(), + 1e-6, + ), + ( + "cubic", + ResampleConfig::poly().degree(Poly::Cubic).build(), + 1e-6, + ), + ("balanced sinc", ResampleConfig::balanced(), 1e-3), + ] +} + +/// The first frames a resampler yields are at the input's start, so they +/// follow its first frame, not the silence rubato's history starts with. +#[test] +fn first_frames_follow_the_input() { + let stereo = ChannelCount::new(2).unwrap(); + let target = SampleRate::new(48000).unwrap(); + for (name, config, tolerance) in start_configs() { + for rate in [44100, 32000, 22050, 110250, 96000] { + let rate = SampleRate::new(rate).unwrap(); + let input = [0.8, -0.6].repeat(2000); + let source = TestSource::new(input, rate, stereo); + let output: Vec = + SampleRateConverter::new(source, target, config.clone()).collect(); + for (i, frame) in output.chunks(2).take(64).enumerate() { + assert!( + (frame[0] - 0.8).abs() <= tolerance && (frame[1] + 0.6).abs() <= tolerance, + "{name}, {rate} Hz: frame {i} is {frame:?}, not [0.8, -0.6]" + ); + } + } + } +} + +/// A seek starts the resampler over in the middle of the input, which +/// mustn't dip towards silence either. +#[test] +fn first_frames_after_a_seek_follow_the_input() { + let mono = ChannelCount::new(1).unwrap(); + let rate = SampleRate::new(44100).unwrap(); + let target = SampleRate::new(48000).unwrap(); + for (name, config, tolerance) in start_configs() { + let source = TestSource::new(vec![0.8; 44100], rate, mono); + let mut resampler = SampleRateConverter::new(source, target, config); + resampler.try_seek(Duration::from_millis(500)).unwrap(); + for (i, sample) in resampler.take(64).enumerate() { + assert!( + (sample - 0.8).abs() <= tolerance, + "{name}: sample {i} after the seek is {sample}, not 0.8" + ); + } + } +} + +/// With small chunks, the lead-in takes several of them, while the +/// first frame waits: it still counts as left, and comes out in place. +#[test] +fn lead_in_longer_than_a_chunk() { + let mono = ChannelCount::new(1).unwrap(); + let (rate, target) = ( + SampleRate::new(8000).unwrap(), + SampleRate::new(48000).unwrap(), + ); + let config = ResampleConfig::sinc() + .chunk_size(NonZero::new(32).unwrap()) + .build(); + let source = TestSource::new(vec![0.8; 800], rate, mono); + let mut resampler = SampleRateConverter::new(source, target, config); + + let mut hints = vec![resampler.size_hint()]; + let mut output = Vec::new(); + loop { + let exhausted = resampler.is_exhausted(); + let Some(sample) = resampler.next() else { + break; + }; + assert!(!exhausted, "is_exhausted() before sample {}", output.len()); + output.push(sample); + hints.push(resampler.size_hint()); + } + + assert_eq!(output.len(), resampled_len(InFrameCount(800), rate, target)); + for (i, sample) in output.iter().take(256).enumerate() { + assert!( + (sample - 0.8).abs() <= 1e-3, + "sample {i} is {sample}, not 0.8" + ); + } + for (emitted, (lower, upper)) in hints.into_iter().enumerate() { + let left = output.len() - emitted; + assert!(lower <= left, "lower bound {lower} with {left} left"); + assert!( + upper.is_none_or(|upper| upper >= left), + "upper bound {upper:?} with {left} left" + ); + } +} + +/// A single frame is still resampled, alone or before a format change. +#[test] +fn a_single_frame_is_resampled() { + let target = SampleRate::new(48000).unwrap(); + for (name, config, _) in start_configs() { + let alone = spans_of(&[(1, 24000, 2)]); + let alone = SampleRateConverter::new(alone, target, config.clone()).count(); + assert_eq!(alone, 4, "{name}: one stereo frame at half the rate"); + + let before_a_change = spans_of(&[(1, 24000, 2), (100, 12000, 2)]); + let output: Vec = + SampleRateConverter::new(before_a_change, target, config.clone()).collect(); + assert_close(output.len(), 4 + 800, &format!("{name}: then a span")); + } +} diff --git a/src/source/uniform.rs b/src/source/uniform.rs index c595f299..573318e3 100644 --- a/src/source/uniform.rs +++ b/src/source/uniform.rs @@ -360,6 +360,29 @@ mod tests { assert_frames_aligned(&out, 600); } + /// A resampler rebuilt at a rate change, as `Player::set_speed` makes + /// one, starts on the new span's first frame rather than dipping + /// towards silence. + #[test] + fn rate_change_starts_on_the_input() { + let source = chain([ + SamplesBuffer::new(nz!(2), nz!(110250), [0.5, -0.5].repeat(2205)), + SamplesBuffer::new(nz!(2), nz!(44100), [0.8, -0.6].repeat(4410)), + ]); + let out: Vec = UniformSourceIterator::new(source, nz!(2), nz!(48000)).collect(); + // The end of the stream falls to silence: leave it out. + let frames = out.chunks(2).take(out.len() / 2 - 4); + let first_after = 960; + for (i, frame) in frames.enumerate() { + let expected = if i < first_after { + [0.5, -0.5] + } else { + [0.8, -0.6] + }; + assert_eq!(frame, expected, "frame {i}"); + } + } + #[test] fn upmixed_frame_ends_before_a_rate_change() { let out: Vec<_> = From f4b6d7dccc94d6be2e8f10d3819a0706daa568f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benoi=CC=82t=20Rouleau?= Date: Wed, 25 Nov 2026 17:43:41 -0500 Subject: [PATCH 08/10] resampler: keep the first frame when its lead-in fills a chunk The lead-in counted only the copies ahead of the first frame, so when they filled a chunk exactly, it reached zero with the frame itself still to feed, and the next chunk read on from the second frame. The output ran a frame ahead, with silence at its end. Count the frame as the lead-in's last copy instead. Co-Authored-By: Claude Opus 5.5 Co-authored-by: multica-agent --- src/conversions/sample_rate/rubato.rs | 53 ++++++++++++++------------- src/conversions/sample_rate/tests.rs | 53 +++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 26 deletions(-) diff --git a/src/conversions/sample_rate/rubato.rs b/src/conversions/sample_rate/rubato.rs index 8bef5433..17a83f2e 100644 --- a/src/conversions/sample_rate/rubato.rs +++ b/src/conversions/sample_rate/rubato.rs @@ -133,14 +133,14 @@ pub struct RubatoResample> { /// change: rubato would pad it with silence, and the last frames /// would fall towards it. last_frame: Box<[Sample]>, - /// Copies of the first frame still to feed rubato ahead of it. Its - /// history starts as silence, and the first frames out, which land - /// just before the input's start, would be interpolated partly from - /// it: a soft start, and a dip where a resampler is built mid-stream - /// or after a seek. - lead_in: usize, + /// Copies of the first frame still to feed rubato: the lead-in ahead + /// of it, then the frame itself. Its history starts as silence, and + /// the first frames out, which land just before the input's start, + /// would be interpolated partly from it: a soft start, and a dip + /// where a resampler is built mid-stream or after a seek. + lead_in_copies: usize, /// Whether the first frame has been read into `last_frame` for the - /// lead-in, and is still to be fed after it. + /// lead-in. lead_in_read: bool, } @@ -180,7 +180,8 @@ impl> RubatoResample { OutFrameCount(delay_frames + lead_in as usize) } - /// The lead-in and output delay of a new or reset resampler. + /// The copies of the first frame to feed rubato, lead-in and frame + /// itself, and the output delay of a new or reset resampler. fn start_state( resampler: &R, source_rate: SampleRate, @@ -188,7 +189,7 @@ impl> RubatoResample { ) -> (usize, OutFrameCount) { let lead_in = Self::lead_in_frames(resampler, source_rate, target_rate); let delay = Self::output_delay(resampler, lead_in, source_rate, target_rate); - (lead_in, delay) + (lead_in + 1, delay) } pub fn span_length(&self) -> Option { @@ -262,7 +263,7 @@ impl> RubatoResample { self.resampler.reset(); self.output.reset(); self.span_remaining = InSamples::ZERO; - (self.lead_in, self.output_delay_remaining) = + (self.lead_in_copies, self.output_delay_remaining) = Self::start_state(&self.resampler, self.output.source_rate, self.target_rate); self.lead_in_read = false; self.frames_being_resampled = OutFrameCount::ZERO; @@ -389,10 +390,10 @@ impl> RubatoResample { self.input_buffer.clear(); let mut read = InSamples::ZERO; - if self.lead_in > 0 { + if self.lead_in_copies > 0 { read = self.lead_in_with_first_frame(wanted); } - if self.lead_in > 0 { + if self.lead_in_copies > 0 { // The lead-in fills this chunk, and goes on into the next. return ( self.input_buffer.len().frames(channels), @@ -422,7 +423,7 @@ impl> RubatoResample { if read.raw() < self.last_frame.len() { // No whole frame to lead in with: leave what was read // as it is. - self.lead_in = 0; + self.lead_in_copies = 0; return read; } self.last_frame @@ -431,19 +432,19 @@ impl> RubatoResample { self.lead_in_read = true; } - // Then the first frame itself, once the lead-in is all in. - let copies = self.lead_in + 1; + // The first frame itself is the last copy, so it stays pending + // until every copy ahead of it is in, even when they fill a + // chunk exactly. let room = (wanted - self.input_buffer.len()).raw() / self.last_frame.len(); - for _ in 0..copies.min(room) { + let copies = self.lead_in_copies.min(room); + for _ in 0..copies { for &sample in &self.last_frame { self.input_buffer.push(sample); } } - if room >= copies { - self.lead_in = 0; + self.lead_in_copies -= copies; + if self.lead_in_copies == 0 { self.lead_in_read = false; - } else { - self.lead_in -= room; } read } @@ -518,7 +519,7 @@ impl RubatoAsyncResample { let input_buf_size = InFrameCount(resampler.input_frames_max()); let output_buf_size = OutFrameCount(resampler.output_frames_max()); - let (lead_in, initial_output_delay) = + let (lead_in_copies, initial_output_delay) = RubatoResample::>::start_state( &resampler, source_rate, @@ -538,7 +539,7 @@ impl RubatoAsyncResample { frames_in_total: 0, frames_out_total: 0, last_frame: vec![0.0; channels.get().into()].into_boxed_slice(), - lead_in, + lead_in_copies, lead_in_read: false, }) } @@ -579,7 +580,7 @@ impl RubatoAsyncResample { let input_buf_size = InFrameCount(resampler.input_frames_max()); let output_buf_size = OutFrameCount(resampler.output_frames_max()); - let (lead_in, initial_output_delay) = + let (lead_in_copies, initial_output_delay) = RubatoResample::>::start_state( &resampler, source_rate, @@ -599,7 +600,7 @@ impl RubatoAsyncResample { frames_in_total: 0, frames_out_total: 0, last_frame: vec![0.0; channels.get().into()].into_boxed_slice(), - lead_in, + lead_in_copies, lead_in_read: false, }) } @@ -638,7 +639,7 @@ impl RubatoFftResample { let input_buf_size = InFrameCount(resampler.input_frames_max()); let output_buf_size = OutFrameCount(resampler.output_frames_max()); - let (lead_in, output_delay_remaining) = + let (lead_in_copies, output_delay_remaining) = RubatoFftResample::::start_state(&resampler, source_rate, target_rate); let span_remaining = Self::first_span(&input); @@ -654,7 +655,7 @@ impl RubatoFftResample { frames_in_total: 0, frames_out_total: 0, last_frame: vec![0.0; channels.get().into()].into_boxed_slice(), - lead_in, + lead_in_copies, lead_in_read: false, }) } diff --git a/src/conversions/sample_rate/tests.rs b/src/conversions/sample_rate/tests.rs index 94251184..a7657863 100644 --- a/src/conversions/sample_rate/tests.rs +++ b/src/conversions/sample_rate/tests.rs @@ -721,6 +721,59 @@ fn lead_in_longer_than_a_chunk() { } } +/// The copies of the first frame can fill a chunk exactly, which leaves +/// the frame itself for the next one: it still comes out first, and the +/// rest in place. A ramp through a linear resampler comes out the same at +/// every chunk size around the ones the lead-in fills exactly, from the +/// start and after a seek, as with one chunk for the whole input. +#[test] +fn first_frame_after_a_lead_in_that_fills_a_chunk() { + let mono = ChannelCount::new(1).unwrap(); + let ramp = |frame: usize| 0.2 + frame as Sample * 1e-4; + let input: Vec = (0..2000).map(ramp).collect(); + // 1/64 s, a whole number of frames at 48 kHz, rounded down at 44.1. + let seek = Duration::from_secs_f64(1.0 / 64.0); + let resample = |rate, target, chunk, seeked| { + let source = TestSource::new(input.clone(), rate, mono); + let config = ResampleConfig::poly() + .degree(Poly::Linear) + .chunk_size(NonZero::new(chunk).unwrap()) + .build(); + let mut resampler = SampleRateConverter::new(source, target, config); + if seeked { + resampler.try_seek(seek).unwrap(); + } + resampler.collect::>() + }; + let cases = [ + // The lead-in fills the chunk of 158 exactly. + (44100, 48000, 140..=170), + // And those of 144 and 145. + (48000, 88200, 130..=160), + // And the default chunk. + (48000, 131456, 1024..=1024), + ]; + for (from, to, chunks) in cases { + let (rate, target) = (SampleRate::new(from).unwrap(), SampleRate::new(to).unwrap()); + for seeked in [false, true] { + let first = ramp(if seeked { from as usize / 64 } else { 0 }); + let whole = resample(rate, target, 8192, seeked); + assert!((whole[0] - first).abs() <= 1e-5, "{from} → {to} Hz"); + for chunk in chunks.clone() { + let output = resample(rate, target, chunk, seeked); + let what = format!("{from} → {to} Hz, chunks of {chunk}, seeked: {seeked}"); + assert_eq!(output.len(), whole.len(), "{what}"); + for (i, (&got, &expected)) in output.iter().zip(&whole).enumerate() { + assert!( + (got - expected).abs() <= 1e-5, + "{what}: frame {i} is {got}, not {expected}" + ); + } + } + } + } +} + /// A single frame is still resampled, alone or before a format change. #[test] fn a_single_frame_is_resampled() { From a17ba692a1f6e2ed77078944e2a370873dfc88c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benoi=CC=82t=20Rouleau?= Date: Wed, 25 Nov 2026 17:46:47 -0500 Subject: [PATCH 09/10] uniform: check the format once per resampled chunk, not per sample UniformSourceIterator asked a resampler for the format of every sample it yielded, since neither the input's spans nor the resampler's own tell where the format of its output changes. But what the resampler has buffered is all in the format it was built for, so count that like a span, and check again once it runs out. The check now happens once or twice per chunk instead of once per sample. Downmixing also goes before resampling again, so the channels dropped aren't resampled. It sits behind a small wrapper that reports another channel count once the input's changes, which stops the resampler there as its raw input would have. Instructions retired converting 10 s of audio 10 times, previous head to this one: stereo 48 kHz passthrough 484M to 358M, stereo 44.1 to 48 kHz 1,676M to 1,293M, mono 24 kHz to stereo 48 kHz 1,323M to 1,080M, stereo 44.1 kHz to mono 48 kHz 1,886M to 811M. All four are back to where they were before this PR's fixes, or a little under. The output is the same, bit for bit, over 30,000 random span layouts. Co-Authored-By: Claude Opus 5.5 Co-authored-by: multica-agent --- src/conversions/channels.rs | 12 ++ src/conversions/sample_rate/mod.rs | 29 ++++ src/conversions/sample_rate/rubato.rs | 6 + src/source/uniform.rs | 237 ++++++++++++++++++++------ 4 files changed, 232 insertions(+), 52 deletions(-) diff --git a/src/conversions/channels.rs b/src/conversions/channels.rs index 4c065da4..95f84208 100644 --- a/src/conversions/channels.rs +++ b/src/conversions/channels.rs @@ -58,6 +58,18 @@ where pub(crate) fn at_frame_start(&self) -> bool { self.next_output_sample_pos == 0 } + + /// The channel count converted from. + #[inline] + pub(crate) fn channels_from(&self) -> ChannelCount { + self.from + } + + /// How many samples `input_len` whole input frames convert to. + #[inline] + pub(crate) fn converted_len(&self, input_len: usize) -> usize { + input_len / self.from.get() as usize * self.to.get() as usize + } } impl Iterator for ChannelCountConverter diff --git a/src/conversions/sample_rate/mod.rs b/src/conversions/sample_rate/mod.rs index 1d2c501b..927b380e 100644 --- a/src/conversions/sample_rate/mod.rs +++ b/src/conversions/sample_rate/mod.rs @@ -276,6 +276,35 @@ where self.resampler().next_format() } + /// Whether samples of the format it was built for are still to come, + /// buffered or inside the resampler. + #[inline] + pub(crate) fn holds_samples(&self) -> bool { + match self.resampler() { + ResampleInner::Passthrough { .. } => false, + ResampleInner::Poly(resampler) | ResampleInner::Sinc(resampler) => { + resampler.holds_samples() + } + #[cfg(feature = "rubato-fft")] + ResampleInner::Fft(resampler) => resampler.holds_samples(), + } + } + + /// How many samples `next` yields before the format may change: the + /// resampled samples buffered, all in the format it was built for. + /// Zero once they run out, or when passing through. + #[inline] + pub(crate) fn samples_in_format(&self) -> usize { + match self.resampler() { + ResampleInner::Passthrough { .. } => 0, + ResampleInner::Poly(resampler) | ResampleInner::Sinc(resampler) => { + resampler.buffered_len() + } + #[cfg(feature = "rubato-fft")] + ResampleInner::Fft(resampler) => resampler.buffered_len(), + } + } + /// Returns the inner source. #[inline] pub fn into_inner(self) -> I { diff --git a/src/conversions/sample_rate/rubato.rs b/src/conversions/sample_rate/rubato.rs index 6f63fefe..9ab88af0 100644 --- a/src/conversions/sample_rate/rubato.rs +++ b/src/conversions/sample_rate/rubato.rs @@ -162,6 +162,12 @@ impl> RubatoResample { !self.output.is_empty() } + /// Resampled samples buffered, not yet yielded. + #[inline] + pub fn buffered_len(&self) -> usize { + self.output.len().raw() + } + /// Whether samples of the format this was built for are still to /// come, buffered or inside rubato. pub fn holds_samples(&self) -> bool { diff --git a/src/source/uniform.rs b/src/source/uniform.rs index c595f299..dd59c57e 100644 --- a/src/source/uniform.rs +++ b/src/source/uniform.rs @@ -4,16 +4,92 @@ use super::SeekError; use crate::common::{ChannelCount, SampleRate}; use crate::conversions::ChannelCountConverter; use crate::conversions::{Poly, ResampleConfig, SampleRateConverter}; -use crate::Source; +use crate::{Sample, Source}; #[derive(Clone)] enum UniformInner { Passthrough(I), SampleRate(SampleRateConverter), ChannelCount(ChannelCountConverter), - // Resampled first even when downmixing: a resampler reads ahead, - // and only on its raw input can it see where a span changes format. - Both(ChannelCountConverter>), + BothUpmix(ChannelCountConverter>), + // Downmixed first, so only the channels kept are resampled. + BothDownmix(SampleRateConverter>), +} + +/// Drops channels ahead of a resampler. A resampler reads ahead across +/// spans, and stops where its input's format changes. So once the +/// input's channel count is no longer the one converted from, this +/// reports another count than the one it converts to, which stops the +/// resampler there as the raw input would have. +#[derive(Clone)] +struct Downmix(ChannelCountConverter); + +impl Downmix { + #[inline] + fn new(input: I, from: ChannelCount, to: ChannelCount) -> Self { + Self(ChannelCountConverter::new(input, from, to)) + } + + /// Whether the input is still in the channel count converted from. + #[inline] + fn input_unchanged(&self) -> bool { + self.0.inner().channels() == self.0.channels_from() + } +} + +impl Iterator for Downmix { + type Item = Sample; + + #[inline] + fn next(&mut self) -> Option { + self.0.next() + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.0.size_hint() + } +} + +impl Source for Downmix { + #[inline] + fn current_span_len(&self) -> Option { + if self.input_unchanged() { + self.0.current_span_len() + } else { + // Converted, a span shorter than a frame of the old format + // would count as `Some(0)`: the end of the stream. + self.0.inner().current_span_len() + } + } + + #[inline] + fn channels(&self) -> ChannelCount { + let input = self.0.inner().channels(); + if self.input_unchanged() { + self.0.channels() + } else if input != self.0.channels() { + input + } else { + // Any count but the converted one stops the resampler. + self.0.channels_from() + } + } + + #[inline] + fn sample_rate(&self) -> SampleRate { + self.0.sample_rate() + } + + #[inline] + fn total_duration(&self) -> Option { + self.0.total_duration() + } + + #[inline] + fn try_seek(&mut self, pos: Duration) -> Result<(), SeekError> { + self.0.try_seek(pos) + } } impl Iterator for UniformInner { @@ -25,7 +101,8 @@ impl Iterator for UniformInner { UniformInner::Passthrough(take) => take.next(), UniformInner::SampleRate(converter) => converter.next(), UniformInner::ChannelCount(converter) => converter.next(), - UniformInner::Both(converter) => converter.next(), + UniformInner::BothUpmix(converter) => converter.next(), + UniformInner::BothDownmix(converter) => converter.next(), } } @@ -35,7 +112,8 @@ impl Iterator for UniformInner { UniformInner::Passthrough(take) => take.size_hint(), UniformInner::SampleRate(converter) => converter.size_hint(), UniformInner::ChannelCount(converter) => converter.size_hint(), - UniformInner::Both(converter) => converter.size_hint(), + UniformInner::BothUpmix(converter) => converter.size_hint(), + UniformInner::BothDownmix(converter) => converter.size_hint(), } } } @@ -47,7 +125,8 @@ impl UniformInner { UniformInner::Passthrough(source) => source, UniformInner::SampleRate(converter) => converter.into_inner(), UniformInner::ChannelCount(converter) => converter.into_inner(), - UniformInner::Both(converter) => converter.into_inner().into_inner(), + UniformInner::BothUpmix(converter) => converter.into_inner().into_inner(), + UniformInner::BothDownmix(converter) => converter.into_inner().0.into_inner(), } } @@ -57,7 +136,8 @@ impl UniformInner { UniformInner::Passthrough(source) => source, UniformInner::SampleRate(converter) => converter.inner(), UniformInner::ChannelCount(converter) => converter.inner(), - UniformInner::Both(converter) => converter.inner().inner(), + UniformInner::BothUpmix(converter) => converter.inner().inner(), + UniformInner::BothDownmix(converter) => converter.inner().0.inner(), } } @@ -72,7 +152,16 @@ impl UniformInner { converter.inner().sample_rate(), ), UniformInner::SampleRate(converter) => converter.next_input_format(), - UniformInner::Both(converter) => converter.inner().next_input_format(), + UniformInner::BothUpmix(converter) => converter.inner().next_input_format(), + UniformInner::BothDownmix(converter) => { + let downmix = &converter.inner().0; + if converter.holds_samples() { + (downmix.channels_from(), converter.next_input_format().1) + } else { + let input = downmix.inner(); + (input.channels(), input.sample_rate()) + } + } } } @@ -82,9 +171,12 @@ impl UniformInner { #[inline] fn at_frame_start(&self) -> bool { match self { - UniformInner::Passthrough(_) | UniformInner::SampleRate(_) => true, + // A resampler yields whole frames from its buffer. + UniformInner::Passthrough(_) + | UniformInner::SampleRate(_) + | UniformInner::BothDownmix(_) => true, UniformInner::ChannelCount(converter) => converter.at_frame_start(), - UniformInner::Both(converter) => converter.at_frame_start(), + UniformInner::BothUpmix(converter) => converter.at_frame_start(), } } @@ -94,20 +186,28 @@ impl UniformInner { UniformInner::Passthrough(source) => source, UniformInner::SampleRate(converter) => converter.inner_mut(), UniformInner::ChannelCount(converter) => converter.inner_mut(), - UniformInner::Both(converter) => converter.inner_mut().inner_mut(), + UniformInner::BothUpmix(converter) => converter.inner_mut().inner_mut(), + UniformInner::BothDownmix(converter) => converter.inner_mut().0.inner_mut(), } } } impl Source for UniformInner { - /// The span of the converted output, which is what gets counted. + /// How many samples to count before checking the format again. A + /// resampler reads ahead of its input, so neither the input's spans + /// nor its own tell where the format of what it yields changes. What + /// it has buffered is all in one format, though, so that's counted. + /// Only called at the start of an output frame. #[inline] fn current_span_len(&self) -> Option { match self { UniformInner::Passthrough(source) => source.current_span_len(), - UniformInner::SampleRate(converter) => converter.current_span_len(), + UniformInner::SampleRate(converter) => Some(converter.samples_in_format()), UniformInner::ChannelCount(converter) => converter.current_span_len(), - UniformInner::Both(converter) => converter.current_span_len(), + UniformInner::BothUpmix(converter) => { + Some(converter.converted_len(converter.inner().samples_in_format())) + } + UniformInner::BothDownmix(converter) => Some(converter.samples_in_format()), } } @@ -202,11 +302,17 @@ where ChannelCountConverter::new(input, from_channels, target_channels); UniformInner::ChannelCount(channel_converted) } - (true, true) => { + (true, true) if target_channels > from_channels => { let rate_converted = SampleRateConverter::new(input, target_sample_rate, config); let channel_converted = ChannelCountConverter::new(rate_converted, from_channels, target_channels); - UniformInner::Both(channel_converted) + UniformInner::BothUpmix(channel_converted) + } + (true, true) => { + let channel_converted = Downmix::new(input, from_channels, target_channels); + let rate_converted = + SampleRateConverter::new(channel_converted, target_sample_rate, config); + UniformInner::BothDownmix(rate_converted) } } } @@ -220,43 +326,30 @@ where #[inline] fn next(&mut self) -> Option { - let mut at_boundary = self - .cached_span_len - .is_some_and(|span_len| self.current_span_pos >= span_len); - // A resampler reads ahead of its input, so neither the input's - // format nor counting spans tells where the format of what it - // yields changes. It knows, cheaply, so ask before every sample. - let resamples = matches!( - self.inner, - Some(UniformInner::SampleRate(_) | UniformInner::Both(_)) - ); - - // Only between output frames: a frame is finished in the format - // it started in. - if (at_boundary || resamples) && self.inner.as_ref().unwrap().at_frame_start() { - let (new_channels, new_sample_rate) = self.inner.as_ref().unwrap().next_input_format(); - - let parameters_changed = new_channels != self.current_channels - || new_sample_rate != self.current_sample_rate; - - if parameters_changed { - let source = self.inner.take().unwrap().into_inner(); - self.current_channels = new_channels; - self.current_sample_rate = new_sample_rate; - let new_inner = UniformSourceIterator::bootstrap( - source, - self.target_channels, - self.target_sample_rate, - ); - self.inner = Some(new_inner); - at_boundary = true; - } - - if at_boundary { - let new_span_len = self.inner.as_ref().unwrap().current_span_len(); + if let Some(span_len) = self.cached_span_len { + // Only between output frames: a frame is finished in the + // format it started in. + if self.current_span_pos >= span_len && self.inner.as_ref().unwrap().at_frame_start() { + let (new_channels, new_sample_rate) = + self.inner.as_ref().unwrap().next_input_format(); + + let parameters_changed = new_channels != self.current_channels + || new_sample_rate != self.current_sample_rate; + + if parameters_changed { + let source = self.inner.take().unwrap().into_inner(); + self.current_channels = new_channels; + self.current_sample_rate = new_sample_rate; + let new_inner = UniformSourceIterator::bootstrap( + source, + self.target_channels, + self.target_sample_rate, + ); + self.inner = Some(new_inner); + } self.current_span_pos = 0; - self.cached_span_len = new_span_len; + self.cached_span_len = self.inner.as_ref().unwrap().current_span_len(); } } @@ -360,6 +453,46 @@ mod tests { assert_frames_aligned(&out, 600); } + /// Downmixed ahead of the resampler, a span still ends on its last + /// frame when the next one, in another format, is shorter than a + /// frame of it. + #[test] + fn downmixed_span_ends_on_its_input_before_a_short_span() { + let source = chain([ + SamplesBuffer::new(nz!(2), nz!(24000), [0.5, -0.25].repeat(300)), + SamplesBuffer::new(nz!(1), nz!(48000), vec![0.75]), + ]); + let out: Vec<_> = UniformSourceIterator::new(source, nz!(1), nz!(48000)).collect(); + assert_eq!(out.len(), 600 + 1, "length"); + for (i, sample) in out[..600].iter().enumerate() { + assert!((sample - 0.5).abs() < 1e-6, "sample {i} is {sample}"); + } + assert_eq!(out[600], 0.75); + } + + /// A resampler reading downmixed input stops where the input's + /// channel count changes, even to the one downmixed to. + #[test] + fn downmixed_input_changing_to_the_target_channel_count() { + let source = chain([ + SamplesBuffer::new(nz!(2), nz!(24000), [0.5, -0.25].repeat(300)), + SamplesBuffer::new(nz!(1), nz!(24000), vec![0.75; 300]), + ]); + let out: Vec<_> = UniformSourceIterator::new(source, nz!(1), nz!(48000)).collect(); + assert_eq!(out.len(), 600 + 600, "length"); + for (i, sample) in out[..600].iter().enumerate() { + assert!((sample - 0.5).abs() < 1e-6, "sample {i} is {sample}"); + } + // Past the resampler's first frame, and before the end's silence. + for (i, sample) in out[602..1198].iter().enumerate() { + assert!( + (sample - 0.75).abs() < 1e-6, + "sample {} is {sample}", + 602 + i + ); + } + } + #[test] fn upmixed_frame_ends_before_a_rate_change() { let out: Vec<_> = From a64317720d6084d371cee7e2a63cb6e69edc86de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benoi=CC=82t=20Rouleau?= Date: Wed, 25 Nov 2026 22:11:34 -0500 Subject: [PATCH 10/10] chain: let a finished source see its last `next()` Moving on as soon as a source reports its end skipped any source that starts out exhausted, without calling its `next()`. So an `EmptyCallback` between two sources never ran, and a `Done` wrapping a source in the middle of a chain never signalled. Chain now calls `next()` on each source it leaves until it returns `None`, and never calls it again after that, so a trailing `EmptyCallback` runs once even if the chain is asked again. A source that still yields a sample after reporting its end keeps it: the chain plays it next instead of dropping it. Co-Authored-By: Claude Opus 5.5 Co-authored-by: multica-agent --- src/source/chain.rs | 165 +++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 155 insertions(+), 10 deletions(-) diff --git a/src/source/chain.rs b/src/source/chain.rs index 070a690f..e71488df 100644 --- a/src/source/chain.rs +++ b/src/source/chain.rs @@ -3,7 +3,7 @@ use std::time::Duration; use super::SeekError; use crate::common::{ChannelCount, SampleRate}; use crate::math::nz; -use crate::Source; +use crate::{Sample, Source}; /// Builds a source that chains sources provided by an iterator. /// @@ -22,6 +22,8 @@ where Chain { iterator, current_source: first_source, + current_ended: false, + pending: None, } } @@ -35,6 +37,11 @@ where iterator: I, // Is only ever `None` if the first element of the iterator is `None`. current_source: Option, + // Whether `current_source`'s `next()` has returned `None`. A source + // is never asked for a sample again once it has. + current_ended: bool, + // A sample from a source that reported its end but still had one. + pending: Option, } impl Chain @@ -43,15 +50,22 @@ where I::Item: Source, { fn skip_finished_sources(&mut self) { - while self - .current_source - .as_ref() - .is_some_and(Source::is_exhausted) - { + while let Some(src) = &mut self.current_source { + if !src.is_exhausted() { + return; + } + // Leave a source only once its `next()` has returned `None`: + // sources like `EmptyCallback` and `Done` act on that call. + if let Some(value) = src.next() { + self.pending = Some(value); + return; + } + self.current_ended = true; let Some(next) = self.iterator.next() else { return; }; self.current_source = Some(next); + self.current_ended = false; } } } @@ -65,8 +79,12 @@ where #[inline] fn next(&mut self) -> Option { + if let Some(value) = self.pending.take() { + self.skip_finished_sources(); + return Some(value); + } loop { - if let Some(src) = &mut self.current_source { + if let Some(src) = self.current_source.as_mut().filter(|_| !self.current_ended) { if let Some(value) = src.next() { // Move on as soon as a source reports its end, so // `current_span_len`, `channels` and `sample_rate` @@ -76,17 +94,22 @@ where self.skip_finished_sources(); return Some(value); } + self.current_ended = true; } let source = self.iterator.next()?; self.current_source = Some(source); + self.current_ended = false; } } #[inline] fn size_hint(&self) -> (usize, Option) { if let Some(cur) = &self.current_source { - (cur.size_hint().0, None) + ( + cur.size_hint().0 + usize::from(self.pending.is_some()), + None, + ) } else { (0, Some(0)) } @@ -138,7 +161,11 @@ where #[inline] fn try_seek(&mut self, pos: Duration) -> Result<(), SeekError> { if let Some(source) = self.current_source.as_mut() { - source.try_seek(pos) + source.try_seek(pos)?; + self.current_ended = false; + self.pending = None; + self.skip_finished_sources(); + Ok(()) } else { Ok(()) } @@ -147,9 +174,127 @@ where #[cfg(test)] mod tests { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Arc; + use std::time::Duration; + use crate::buffer::SamplesBuffer; + use crate::common::{ChannelCount, SampleRate}; use crate::math::nz; - use crate::source::{chain, Source}; + use crate::source::{chain, Done, EmptyCallback, SeekError, Source}; + use crate::Sample; + + fn counting_callback(count: &Arc) -> EmptyCallback { + let count = count.clone(); + EmptyCallback::new(Box::new(move || { + count.fetch_add(1, Ordering::SeqCst); + })) + } + + #[test] + fn calls_an_empty_callback_between_sources_once() { + let count = Arc::new(AtomicUsize::new(0)); + let sources: Vec> = vec![ + Box::new(SamplesBuffer::new(nz!(1), nz!(48000), vec![1.0, 2.0])), + Box::new(counting_callback(&count)), + Box::new(SamplesBuffer::new(nz!(1), nz!(48000), vec![3.0])), + ]; + let mut c = chain(sources); + assert_eq!(c.next(), Some(1.0)); + assert_eq!(count.load(Ordering::SeqCst), 0); + assert_eq!(c.next(), Some(2.0)); + assert_eq!( + count.load(Ordering::SeqCst), + 1, + "the first source has ended" + ); + assert_eq!(c.next(), Some(3.0)); + assert_eq!(c.next(), None); + assert_eq!(c.next(), None); + assert_eq!(count.load(Ordering::SeqCst), 1); + } + + #[test] + fn calls_a_trailing_empty_callback_once() { + let count = Arc::new(AtomicUsize::new(0)); + let sources: Vec> = vec![ + Box::new(SamplesBuffer::new(nz!(1), nz!(48000), vec![1.0])), + Box::new(counting_callback(&count)), + ]; + let mut c = chain(sources); + assert_eq!(c.next(), Some(1.0)); + assert_eq!(c.next(), None); + assert_eq!(c.next(), None); + assert_eq!(count.load(Ordering::SeqCst), 1); + } + + #[test] + fn tells_a_source_it_ended_before_moving_on() { + let count = Arc::new(AtomicUsize::new(0)); + let ended = count.clone(); + let done = Done::new( + SamplesBuffer::new(nz!(1), nz!(48000), vec![1.0, 2.0]), + move |_: &mut SamplesBuffer| { + ended.fetch_add(1, Ordering::SeqCst); + }, + ); + let mut c = chain([ + Box::new(done) as Box, + Box::new(SamplesBuffer::new(nz!(1), nz!(48000), vec![3.0])), + ]); + assert_eq!(c.by_ref().take(2).collect::>(), [1.0, 2.0]); + assert_eq!( + count.load(Ordering::SeqCst), + 1, + "the first source has ended" + ); + assert_eq!(c.collect::>(), [3.0]); + } + + #[test] + fn plays_the_last_source_again_after_seeking_back() { + let mut c = chain([SamplesBuffer::new(nz!(1), nz!(48000), vec![1.0, 2.0])]); + assert_eq!(c.by_ref().collect::>(), [1.0, 2.0]); + c.try_seek(Duration::ZERO).unwrap(); + assert_eq!(c.collect::>(), [1.0, 2.0]); + } + + /// Reports its end one sample early. + struct EndsEarly(Vec); + + impl Iterator for EndsEarly { + type Item = Sample; + fn next(&mut self) -> Option { + (!self.0.is_empty()).then(|| self.0.remove(0)) + } + } + + impl Source for EndsEarly { + fn current_span_len(&self) -> Option { + Some(self.0.len().saturating_sub(1)) + } + fn channels(&self) -> ChannelCount { + nz!(1) + } + fn sample_rate(&self) -> SampleRate { + nz!(48000) + } + fn total_duration(&self) -> Option { + None + } + fn try_seek(&mut self, _: Duration) -> Result<(), SeekError> { + Ok(()) + } + } + + #[test] + fn keeps_samples_a_source_has_after_reporting_its_end() { + let c = chain([ + Box::new(EndsEarly(vec![1.0, 2.0, 3.0])) as Box, + Box::new(SamplesBuffer::new(nz!(1), nz!(48000), vec![4.0])), + ]); + assert_eq!(c.collect::>(), [1.0, 2.0, 3.0, 4.0]); + } #[test] fn empty_chain_reports_end_of_span() {