Skip to content

Don't let span chunking change the resampler's output - #915

Open
benface wants to merge 8 commits into
RustAudio:masterfrom
benface:fix/resampler-span-boundaries
Open

benface wants to merge 8 commits into
RustAudio:masterfrom
benface:fix/resampler-span-boundaries

Conversation

@benface

@benface benface commented Aug 6, 2026 •

Copy link
Copy Markdown

Resampler output changes depending on how the input happens to be split into spans, which it shouldn't.

fill_input_buffer stops at every span boundary and marks the read partial, so rubato zero-pads it as if the stream had ended. Decoders report a span per packet, so this happens constantly — a 48 kHz file on a 44.1 kHz device hisses the whole way through. It now reads across spans and only stops at a real end or a format change.

The resamplers were also tracking input position against span length to spot boundaries, but they read ahead into their own buffer, so that count never matched where the input actually was. Filling already stops at a format change, so the tracking is gone — the passthrough keeps its own, where it's accurate.

Tests cover the chunking, plus a sample rate change and a channel count change at a boundary. The chunking one fails on master.

Reading across spans also means the input runs ahead of the samples coming out. So the resampler now reports the format of those samples in channels(), is_exhausted() and size_hint(), and UniformSourceIterator asks it rather than the input, so a rate change through Mixer::add no longer drops what it holds. It asks once the resampler's buffered output runs out, since that's all in one format, rather than before every sample. Downmixing still goes before resampling, behind a small wrapper that stops the resampler where the input's channel count changes. The last frames before a format change end on the input rather than falling to silence. An upmixed frame is finished in the format it started in, so a change from mono to stereo no longer swaps the channels after it. chain moves on as soon as a source ends, rather than reporting Some(0) in between, still calling next() on each source it leaves, so an EmptyCallback or Done between two sources runs.

`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) <noreply@anthropic.com>
@benface
benface force-pushed the fix/resampler-span-boundaries branch from 1623f94 to 6c15966 Compare August 6, 2026 01:17
@phayes

phayes commented Aug 6, 2026

Copy link
Copy Markdown

I found one issue on this:

in next(), you're returning None (end-of-stream) when source.current_span_len() is None (No span length means the format is stable by contract). So there's some confusion between end-of-stream signalling and stable-format signalling.

I've opened a PR to your PR with a simple fix.

The fix boils down to this:

        // No span length means the format is stable by contract.
        // input_span_len?; // replace this with this:
        let Some(input_span_len) = input_span_len else {
            return Some(sample);
        };

@phayes

phayes commented Aug 6, 2026 •

Copy link
Copy Markdown

PR to your PR is here: benface#1

@benface

benface commented Aug 6, 2026

Copy link
Copy Markdown
Author

Thank you so much @phayes! When I rewrote next() I turned if input_span_len.is_none() { return Some(sample); } into input_span_len?; and kept the comment saying "format is stable by contract", without noticing that the operator does the opposite. 😅 Good test too; it fails on the pre-fix commit. Merged your PR 🙏

@kapok-4o kapok-4o left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I verified the Vorbis fix by comparing packetized input with the same decoded PCM in a single buffer. The samples now match in each resampler I tested.

  • Through Mixer::add at 48 kHz, mono spans of 128 and 64 frames at 24 kHz followed by 96 frames at 48 kHz yield 224 samples instead of 480. UniformSourceIterator sees the new rate on the read-ahead input and drops the buffered tail of the old format.
  • Resampling a chain() of two 24 kHz mono buffers (600 and 64 frames) to 48 kHz produces 1,200 of 1,328 samples. The first buffer's Some(0) cuts off the second buffer.
  • channels() can report stereo while mono samples are still buffered, and is_exhausted() can become true with a sample pending. size_hint() also applies the current rate to later spans. One case advertises an upper bound of 384 and emits 512 samples. Another advertises a lower bound of 384 and emits 320.

benface and others added 3 commits November 25, 2026 15:41
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 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>
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 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>
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 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>
@benface

benface commented Nov 25, 2026

Copy link
Copy Markdown
Author

Thanks a lot @kapok-4o, and for checking the Vorbis fix against the decoded PCM! I could reproduce all three with your numbers:

  • Mixer::add dropping the old format's tail. Right: UniformSourceIterator checked the input, which the resampler had already read past. It now asks the resampler for the format of the next sample it yields. While resampling it asks before every sample, since counting spans can't tell where that format changes. It also resamples before downmixing now, because a channel converter between the resampler and its input hid where the channel count changes. That costs a little more CPU when downmixing, so I'm happy to find another way if you'd rather keep the order. Your case plays 480 samples. (e080429)
    Keeping that tail also showed that its last frames fell towards silence, from rubato's zero padding. Rounding each chunk's output up also added up to a short gap before the change. Those frames now end on the input. (2ba89bc)
  • chain() cut off. A finished source stayed current until the next next(), so the chain reported Some(0). It now moves on right after the last sample, as Repeat does, which also fixed the FIXME in its basic test. Your case gives 1,328 samples. (6e4b0bf)
  • Metadata running ahead. channels() reports the format of the buffered samples, is_exhausted() waits for rubato's tail, and size_hint() only counts the span being read, with no upper bound past it, in the passthrough too. These were already off on master, but reading across spans made them matter more. (e080429)

Each has a test that fails on the previous head. I also fuzzed random span layouts through the resampler and the mixer: lengths, both bounds at every step, is_exhausted(), and channel changes landing on frame boundaries. All clean now. One thing I left out: a resampler rebuilt mid-stream starts from silence, so its first frame dips a little. That's on master too, so I'd rather fix it separately.

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 <github@multica.ai>
@benface

benface commented Nov 25, 2026

Copy link
Copy Markdown
Author

One more, found while testing the above: when a resampled mono source changed to stereo, UniformSourceIterator could switch formats halfway through an upmixed frame, dropping the repeated right sample and swapping every channel after it (1,599 samples instead of 1,600 for 300 mono frames at 24 kHz then 200 stereo at 48 kHz, into stereo at 48 kHz). It now waits for the frame to end: 8da1e2a, with tests that check every frame's channels, and the mixer test now also checks for whole frames.

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 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>
@benface

benface commented Nov 25, 2026

Copy link
Copy Markdown
Author

Following up on the extra CPU I mentioned: it's gone now (a17ba69). UniformSourceIterator was asking the resampler for the format before every sample, and resampling channels it then dropped. It now counts what the resampler has buffered, which is all in one format, and checks again once that runs out. And it downmixes before resampling again, behind a small wrapper that stops the resampler where the input's channel count changes, so the order is back to what it was.

Instructions retired converting 10 s of audio 10 times:

Case Before this PR Previous head Now
Stereo 48 kHz, no conversion 359M 484M 358M
Stereo 44.1 → 48 kHz 1,295M 1,676M 1,293M
Mono 24 → stereo 48 kHz 1,083M 1,323M 1,080M
Stereo 44.1 kHz → mono 48 kHz 818M 1,886M 811M

The output is the same as the previous head, bit for bit, over 30,000 random span layouts, and two new tests cover the wrapper.

@kapok-4o kapok-4o left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the quick and thorough follow-up, and for the CPU table.

I re-ran my three earlier cases on a17ba69. The Mixer::add case now plays 480 samples, the resampled chain() gives 1,328, and size_hint() stayed within bounds at every step over 3,000 random span layouts through the resampling path. I also fuzzed 3,000 layouts through UniformSourceIterator (1-3 channels, four rates, into mono or stereo): lengths match the per-format sums, and no stereo frame came out with swapped channels. CI's fmt, clippy, test and check commands all pass here (stable 1.99, not the MSRV).

One regression from 6e4b0bf: Chain::skip_finished_sources (src/source/chain.rs:45-56, called at :76) steps past any source whose is_exhausted() is already true without calling its next(). An EmptyCallback in the middle of a chain never fires, although its docs describe exactly this use:

let sources: Vec<Box<dyn Source + Send>> = vec![
    Box::new(SamplesBuffer::new(nz!(1), nz!(48000), vec![1.0, 2.0])),
    Box::new(EmptyCallback::new(Box::new(move || { h.fetch_add(1, SeqCst); }))),
    Box::new(SamplesBuffer::new(nz!(1), nz!(48000), vec![3.0])),
];
// samples are [1, 2, 3], but the callback ran 0 times (1 on 2f4c14e and master)

A test for this would be good with the fix.

Minor, and older than this PR: the Passthrough and ChannelCount arms of UniformInner::size_hint (src/source/uniform.rs:112,114) still count past a format change. Mono 48 kHz ×2 then 3-channel 48 kHz ×64, into mono 48 kHz, reports a lower bound of 192 with 64 left. I see #940 already fixes exactly these two arms, so nothing to do here.

On CPU I only timed wall clock on one Apple-silicon machine: versus master, 44.1 → 48 kHz is ~14% faster, mono → stereo level, passthrough and stereo → mono 8-17% slower. Possibly layout noise, so no change requested.

Otherwise this looks good to me.

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 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>
@benface

benface commented Nov 26, 2026

Copy link
Copy Markdown
Author

Thanks again @kapok-4o, and good catch on EmptyCallback!

Fixed in a643177: chain now calls next() on each source it moves past until it returns None, so an EmptyCallback in the middle runs once, as does a Done wrapping a source in the middle (its callback had the same problem). Your example now gives [1, 2, 3] with the callback run once.

A few details:

  • The callback runs as the source before it hands out its last sample, rather than when the next sample is asked for. That's one sample earlier than on master.
  • A source is never asked again once it has returned None, so a trailing EmptyCallback runs once even if the chain is polled past its end (master ran it again on each call).
  • If a source still yields a sample after is_exhausted() said it was done, the chain plays it next instead of dropping it.

New tests in chain.rs cover the callback in the middle and at the end, Done, a source that reports its end early, and seeking back after the end. The first four fail on a17ba69. I also merged this into #939 and #940, which build on this branch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants