diff --git a/CHANGELOG.md b/CHANGELOG.md index e0f149de..b413691b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,9 @@ 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. +- Fixed `chain` reporting the end of the stream between two of its sources. +- Fixed `UniformSourceIterator`'s lower size hint counting input past a format change. ## Version [0.22.2] (2026-03-05) diff --git a/src/conversions/channels.rs b/src/conversions/channels.rs index 94bcf442..95f84208 100644 --- a/src/conversions/channels.rs +++ b/src/conversions/channels.rs @@ -51,6 +51,25 @@ 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 + } + + /// 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 7df49d64..927b380e 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, @@ -247,6 +269,42 @@ 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() + } + + /// 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 { @@ -302,9 +360,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] @@ -330,35 +390,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 +418,48 @@ 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(); + // 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 input_span_len = source.current_span_len(); + // No span length means the format is stable by contract. if input_span_len.is_none() { 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, - ), - }; + *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 +472,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; } } @@ -475,34 +486,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 df1ee016..9ab88af0 100644 --- a/src/conversions/sample_rate/rubato.rs +++ b/src/conversions/sample_rate/rubato.rs @@ -57,6 +57,40 @@ 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 + } + + /// 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 { @@ -79,13 +113,26 @@ 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, - 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, + + /// 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 { @@ -101,12 +148,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) } } @@ -115,11 +162,85 @@ 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 { + 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 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() { + 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() + }; + + let (lower, upper) = self.input.size_hint(); + let upper = upper + .filter(|&upper| upper <= in_format) + .map(|upper| resampled(upper.div_ceil(channels))); + (resampled(lower.min(in_format) / channels), upper) + } + 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); + 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 { @@ -146,13 +267,27 @@ impl> RubatoResample { return None; } - self.frames_being_resampled += frames_in.resampled_by(self.resample_ratio); - self.pos_in_current_span += frames_in.samples(self.output.channels); + 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, }); @@ -187,28 +322,64 @@ 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(()) } + /// 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); + } + + 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) } + /// 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 + } + + /// 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 } @@ -242,15 +413,19 @@ 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), - pos_in_current_span: InSamples::ZERO, + 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(), }) } @@ -293,15 +468,19 @@ 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), - pos_in_current_span: InSamples::ZERO, + 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(), }) } } @@ -339,19 +518,21 @@ 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); Ok(Self { input, 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, 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 c2ea52cc..6035af38 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 { @@ -338,3 +344,273 @@ 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}", + ); +} + +/// 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})" + ); +} + +/// 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"); +} + +/// 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" + ); +} diff --git a/src/mixer/tests.rs b/src/mixer/tests.rs index b55b5c65..59e43a0b 100644 --- a/src/mixer/tests.rs +++ b/src/mixer/tests.rs @@ -138,3 +138,65 @@ 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}" + ); + 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/chain.rs b/src/source/chain.rs index e64ab88c..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,37 @@ 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 +where + I: Iterator, + I::Item: Source, +{ + fn skip_finished_sources(&mut self) { + 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; + } + } } impl Iterator for Chain @@ -46,22 +79,37 @@ 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` + // 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); } + 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)) } @@ -113,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(()) } @@ -122,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() { @@ -145,6 +315,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 +347,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)); diff --git a/src/source/uniform.rs b/src/source/uniform.rs index e3f7c1be..364a034b 100644 --- a/src/source/uniform.rs +++ b/src/source/uniform.rs @@ -4,7 +4,7 @@ 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 { @@ -12,7 +12,84 @@ enum UniformInner { SampleRate(SampleRateConverter), ChannelCount(ChannelCountConverter), BothUpmix(ChannelCountConverter>), - BothDownmix(SampleRateConverter>), + // 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 { @@ -49,7 +126,7 @@ impl UniformInner { 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::BothDownmix(converter) => converter.into_inner().0.into_inner(), } } @@ -60,7 +137,46 @@ impl UniformInner { UniformInner::SampleRate(converter) => converter.inner(), UniformInner::ChannelCount(converter) => converter.inner(), UniformInner::BothUpmix(converter) => converter.inner().inner(), - UniformInner::BothDownmix(converter) => converter.inner().inner(), + UniformInner::BothDownmix(converter) => converter.inner().0.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::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()) + } + } + } + } + + /// 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 { + // A resampler yields whole frames from its buffer. + UniformInner::Passthrough(_) + | UniformInner::SampleRate(_) + | UniformInner::BothDownmix(_) => true, + UniformInner::ChannelCount(converter) => converter.at_frame_start(), + UniformInner::BothUpmix(converter) => converter.at_frame_start(), } } @@ -71,15 +187,28 @@ impl UniformInner { 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::BothDownmix(converter) => converter.inner_mut().0.inner_mut(), } } } impl Source for UniformInner { + /// 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 { - self.inner().current_span_len() + match self { + UniformInner::Passthrough(source) => source.current_span_len(), + UniformInner::SampleRate(converter) => Some(converter.samples_in_format()), + UniformInner::ChannelCount(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()), + } } #[inline] @@ -136,7 +265,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 +273,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), } } @@ -179,8 +309,7 @@ where UniformInner::BothUpmix(channel_converted) } (true, true) => { - let channel_converted = - ChannelCountConverter::new(input, from_channels, target_channels); + 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) @@ -198,11 +327,11 @@ 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(); + // 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; @@ -219,17 +348,8 @@ where 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(), - }; - self.current_span_pos = 0; - self.cached_span_len = new_span_len; + self.cached_span_len = self.inner.as_ref().unwrap().current_span_len(); } } @@ -246,7 +366,43 @@ where #[inline] fn size_hint(&self) -> (usize, Option) { - (self.inner.as_ref().unwrap().size_hint().0, None) + let lower = self.inner.as_ref().unwrap().size_hint().0; + (lower.min(self.max_left_in_format()), None) + } +} + +impl UniformSourceIterator +where + I: Source, +{ + /// At most how many samples come before the input's format may + /// change. Past that, another conversion may yield fewer samples for + /// the same input, so a lower bound can't count them. A resampler's + /// own bound already stops at its format; the other conversions' + /// count the whole input in the current one. + fn max_left_in_format(&self) -> usize { + let inner = self.inner.as_ref().unwrap(); + if !matches!( + inner, + UniformInner::Passthrough(_) | UniformInner::ChannelCount(_) + ) { + return usize::MAX; + } + let Some(span_len) = self.cached_span_len else { + // The input's format never changes. + return usize::MAX; + }; + if self.current_span_pos < span_len { + return span_len - self.current_span_pos; + } + // The next sample checks the format first, and starts a span + // in it if it holds. + let format = (self.current_channels, self.current_sample_rate); + if inner.at_frame_start() && inner.next_input_format() == format { + inner.current_span_len().unwrap_or(usize::MAX) + } else { + 0 + } } } @@ -283,3 +439,165 @@ 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); + } + + /// 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 + ); + } + } + + /// The lower bound holds once a later span converts to fewer + /// samples, with or without resampling. + #[test] + fn size_hint_holds_across_format_changes() { + // (channels, rate, frames) per span, into mono or stereo 48 kHz. + for (spans, to_channels) in [ + // Passed through, then downmixed. + (&[(1, 48000, 2), (2, 48000, 400)][..], 1), + // Downmixed, then more so. + (&[(2, 48000, 64), (4, 48000, 200)], 1), + // Upmixed, then passed through. + (&[(1, 48000, 64), (2, 48000, 200)], 2), + // Resampled, passed through, then downmixed. + (&[(1, 24000, 64), (1, 48000, 2), (2, 48000, 400)], 1), + ] { + let source = chain(spans.iter().map( + |&(channels, rate, frames): &(u16, u32, usize)| { + let samples = vec![0.5; frames * channels as usize]; + SamplesBuffer::new( + channels.try_into().unwrap(), + rate.try_into().unwrap(), + samples, + ) + }, + )); + let mut uniform = + UniformSourceIterator::new(source, to_channels.try_into().unwrap(), nz!(48000)); + let mut lower_bounds = vec![uniform.size_hint().0]; + while uniform.next().is_some() { + lower_bounds.push(uniform.size_hint().0); + } + + let total = lower_bounds.len() - 1; + for (emitted, lower) in lower_bounds.into_iter().enumerate() { + let left = total - emitted; + assert!( + lower <= left, + "{spans:?}: lower bound {lower} with {left} left" + ); + } + } + } + + /// Until the format can change, the lower bound is still exact. + #[test] + fn size_hint_is_exact_in_one_format() { + for to_channels in [nz!(1), nz!(2)] { + let source = SamplesBuffer::new(nz!(1), nz!(48000), vec![0.5; 300]); + let uniform = UniformSourceIterator::new(source, to_channels, nz!(48000)); + let len = 300 * to_channels.get() as usize; + assert_eq!(uniform.size_hint().0, len, "into {to_channels} channels"); + assert_eq!(uniform.count(), len, "into {to_channels} channels"); + } + } + + #[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}"); + } + } +}