From ff997f368c1bf7bed99c1383fe899fbe84fe026f Mon Sep 17 00:00:00 2001 From: Abboskhon Sobirov Date: Sat, 14 Nov 2026 20:45:28 +0900 Subject: [PATCH 1/7] fix: count start() duration in buffer time --- .../core/sources/AudioBufferSourceNode.cpp | 32 ++++++- .../core/sources/AudioBufferSourceNode.h | 4 + .../sources/AudioBufferSourceNodeTest.cpp | 88 +++++++++++++++++++ 3 files changed, 120 insertions(+), 4 deletions(-) diff --git a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp index 0484ccc6fb..9ec58b69c3 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp +++ b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -81,9 +82,8 @@ void AudioBufferSourceNode::setBuffer( void AudioBufferSourceNode::start(double when, double offset, double duration) { AudioScheduledSourceNode::start(when); - if (duration > 0) { - AudioScheduledSourceNode::stop(when + duration); - } + // Spec: `duration` counts buffer content, not context time. + remainingDuration_ = duration > 0 ? std::optional(duration) : std::nullopt; if (buffer_ == nullptr) { return; @@ -152,7 +152,31 @@ void AudioBufferSourceNode::runBufferProcessor( processor_->setPosition(vReadIndex_); processor_->setEndFrame(static_cast(endFrame)); processor_->setStartFrame(static_cast(startFrame)); - processor_->process(processingBuffer, startOffset, offsetLength, playbackRate, interpolate); + // renderBlock() copies one buffer frame per output frame whatever the rate. + const double bufferFramesPerFrame = interpolate ? std::fabs(playbackRate) : 1.0; + const double bufferSampleRate = buffer_->getSampleRate(); + size_t framesToPlay = offsetLength; + if (remainingDuration_) { + const double framesLeft = + std::round(*remainingDuration_ * bufferSampleRate / bufferFramesPerFrame); + if (framesLeft < static_cast(offsetLength)) { + framesToPlay = static_cast(framesLeft); + } + } + + processor_->process(processingBuffer, startOffset, framesToPlay, playbackRate, interpolate); + + if (remainingDuration_) { + if (framesToPlay < offsetLength) { + processingBuffer->zero(startOffset + framesToPlay, offsetLength - framesToPlay); + remainingDuration_ = 0.0; + playbackState_ = PlaybackState::STOP_SCHEDULED; + } else { + const double spent = + static_cast(framesToPlay) * bufferFramesPerFrame / bufferSampleRate; + remainingDuration_ = std::max(0.0, *remainingDuration_ - spent); + } + } if (processor_->atBoundary() && processor_->shouldStop()) { playbackState_ = PlaybackState::STOP_SCHEDULED; diff --git a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.h b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.h index 4541bd9cce..b077d90556 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.h +++ b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.h @@ -6,6 +6,7 @@ #include #include #include +#include namespace audioapi { @@ -66,6 +67,9 @@ class AudioBufferSourceNode : public AudioBufferBaseSourceNode { double loopStart_; double loopEnd_; + /// Buffer seconds `start()`'s `duration` still allows, across loop iterations. + std::optional remainingDuration_; + // User provided buffer std::shared_ptr buffer_; diff --git a/packages/react-native-audio-api/common/cpp/test/src/core/sources/AudioBufferSourceNodeTest.cpp b/packages/react-native-audio-api/common/cpp/test/src/core/sources/AudioBufferSourceNodeTest.cpp index 424d2f7452..56f484f518 100644 --- a/packages/react-native-audio-api/common/cpp/test/src/core/sources/AudioBufferSourceNodeTest.cpp +++ b/packages/react-native-audio-api/common/cpp/test/src/core/sources/AudioBufferSourceNodeTest.cpp @@ -411,4 +411,92 @@ TEST_F(AudioBufferSourceNodeTest, ConnectedSourceStillEndsThroughRenderPath) { processGraph(); // `ended` must not fire a second time } +/// Spec: `duration` in start(when, offset, duration) counts buffer content, not context time. +TEST_F(AudioBufferSourceNodeTest, StartDurationCountsBufferTimeAtPlaybackRate) { + BaseAudioBufferSourceOptions baseOptions; + baseOptions.playbackRate = 2.0f; + auto *node = addNode( + std::make_unique( + context, AudioBufferSourceOptions(baseOptions))); + + auto buffer = makeSilentBuffer(8 * QUANTUM); + for (auto &sample : buffer->getChannel(0)->span()) { + sample = 1.0f; + } + node->setBuffer(buffer, makeOutputBuffer()); + + // 3.5 quanta of buffer content: 1.75 quanta of output at 2x. + constexpr size_t DURATION_FRAMES = 3 * QUANTUM + QUANTUM / 2; + node->start(0.0, 0.0, static_cast(DURATION_FRAMES) / SAMPLE_RATE); + + auto out = std::make_shared(QUANTUM, 1, static_cast(SAMPLE_RATE)); + size_t played = 0; + for (int q = 0; q < 3; ++q) { + context->processGraph(out.get(), QUANTUM); + for (float sample : out->getChannel(0)->span()) { + played += sample != 0.0f ? 1 : 0; + } + } + + EXPECT_EQ(played, DURATION_FRAMES / 2); + EXPECT_TRUE(node->isFinished()); +} + +/// Spec: with loop on, `duration` still counts buffer content, across loop iterations. +TEST_F(AudioBufferSourceNodeTest, StartDurationCountsBufferTimeAcrossLoops) { + BaseAudioBufferSourceOptions baseOptions; + baseOptions.playbackRate = 2.0f; + auto *node = addNode( + std::make_unique( + context, AudioBufferSourceOptions(baseOptions))); + node->setLoop(true); + + auto buffer = makeSilentBuffer(QUANTUM); + for (auto &sample : buffer->getChannel(0)->span()) { + sample = 1.0f; + } + node->setBuffer(buffer, makeOutputBuffer()); + + // Three and a half passes over the one-quantum buffer: 1.75 quanta of output at 2x. + constexpr size_t DURATION_FRAMES = 3 * QUANTUM + QUANTUM / 2; + node->start(0.0, 0.0, static_cast(DURATION_FRAMES) / SAMPLE_RATE); + + auto out = std::make_shared(QUANTUM, 1, static_cast(SAMPLE_RATE)); + size_t played = 0; + for (int q = 0; q < 3; ++q) { + context->processGraph(out.get(), QUANTUM); + for (float sample : out->getChannel(0)->span()) { + played += sample != 0.0f ? 1 : 0; + } + } + + EXPECT_EQ(played, DURATION_FRAMES / 2); + EXPECT_TRUE(node->isFinished()); +} + +/// Spec: with pitch correction on, `duration` still counts buffer content. +TEST_F(AudioBufferSourceNodeTest, StartDurationCountsBufferTimeWithPitchCorrection) { + BaseAudioBufferSourceOptions baseOptions; + baseOptions.pitchCorrection = true; + baseOptions.playbackRate = 2.0f; + auto *node = addNode( + std::make_unique( + context, AudioBufferSourceOptions(baseOptions))); + auto playbackRateBuffer = std::make_shared( + static_cast(WsolaTimeStretcher::MAX_PLAYBACK_RATE * QUANTUM), + 1, + static_cast(SAMPLE_RATE)); + node->initStretch(1, static_cast(SAMPLE_RATE), playbackRateBuffer); + node->setBuffer(makeSilentBuffer(8 * QUANTUM), makeOutputBuffer()); + + constexpr size_t DURATION_FRAMES = 3 * QUANTUM + QUANTUM / 2; + node->start(0.0, 0.0, static_cast(DURATION_FRAMES) / SAMPLE_RATE); + + for (int q = 0; q < 3; ++q) { + processGraph(); + } + + EXPECT_DOUBLE_EQ(node->getCurrentPosition(), static_cast(DURATION_FRAMES) / SAMPLE_RATE); +} + // NOLINTEND From 952533bdcae60d62e49ea8bc2e47082595b3c7ec Mon Sep 17 00:00:00 2001 From: Abboskhon Sobirov Date: Tue, 17 Nov 2026 23:42:15 +0900 Subject: [PATCH 2/7] refactor: move start() duration into processor --- .../docs/sources/audio-buffer-source-node.mdx | 2 +- .../core/sources/AudioBufferSourceNode.cpp | 35 ++++--------------- .../core/sources/AudioBufferSourceNode.h | 4 --- .../utils/buffer/SingleBufferProcessor.cpp | 23 ++++++++---- .../core/utils/buffer/SingleBufferProcessor.h | 19 ++++++++++ 5 files changed, 44 insertions(+), 39 deletions(-) diff --git a/packages/audiodocs/docs/sources/audio-buffer-source-node.mdx b/packages/audiodocs/docs/sources/audio-buffer-source-node.mdx index e2d16eb7bb..bf5ac33363 100644 --- a/packages/audiodocs/docs/sources/audio-buffer-source-node.mdx +++ b/packages/audiodocs/docs/sources/audio-buffer-source-node.mdx @@ -134,7 +134,7 @@ Schedules the `AudioBufferSourceNode` to start playback of audio data contained | :---: | :---: | :---- | | `when` | `number` | The time, in seconds, at which playback is scheduled to start. If `when` is less than [`AudioContext.currentTime`](../core/base-audio-context.mdx#properties) or set to `0.0`, the node starts playing immediately.
Default: `0.0`. | | `offset` | `number` | The position, in seconds, within the audio buffer where playback begins.
The default value is `0.0`, which starts playback from the beginning of the buffer. If the offset exceeds the buffer’s [`duration`](./audio-buffer.mdx#properties) (or the defined [`loopEnd`](./audio-buffer-source-node.mdx#properties) value), it’s automatically clamped to the valid range.
Offsets are calculated using the buffer’s natural sample rate rather than the current playback rate — so even if the sound is played at double speed, halfway through a `10`-second buffer is still `5` seconds. | -| `duration` | `number` | The playback duration, in seconds. If not provided, playback continues until the sound ends naturally or is manually stopped with [`stop() method`](./audio-scheduled-source-node.mdx#stop).
Equivalent to calling `start(when, offset)` followed by `stop(when + duration)`. | +| `duration` | `number` | The amount of buffer content to play, in seconds. If not provided, playback continues until the sound ends naturally or is manually stopped with [`stop() method`](./audio-scheduled-source-node.mdx#stop).
Like `offset`, it is measured in the buffer's own time rather than at the current playback rate, so at double speed a `duration` of `4` seconds plays for `2` seconds.
When [`loop`](./audio-buffer-source-node.mdx#properties) is enabled, the content played across all loop iterations counts toward it. | #### Errors: diff --git a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp index 6e8dded43a..202244364f 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp +++ b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp @@ -10,7 +10,6 @@ #include #include -#include #include #include #include @@ -83,8 +82,12 @@ void AudioBufferSourceNode::setBuffer( void AudioBufferSourceNode::start(double when, double offset, double duration) { AudioScheduledSourceNode::start(when); - // Spec: `duration` counts buffer content, not context time. - remainingDuration_ = duration > 0 ? std::optional(duration) : std::nullopt; + if (duration > 0) { + // A buffer assigned after start() is taken to run at the context rate. + const float sampleRate = buffer_ != nullptr ? buffer_->getSampleRate() : getContextSampleRate(); + // Spec: `duration` counts buffer content, not context time. + processor_->setFrameBudget(dsp::timeToSampleFrame(duration, sampleRate)); + } if (buffer_ == nullptr) { return; @@ -153,31 +156,7 @@ void AudioBufferSourceNode::runBufferProcessor( processor_->setPosition(vReadIndex_); processor_->setEndFrame(static_cast(endFrame)); processor_->setStartFrame(static_cast(startFrame)); - // renderBlock() copies one buffer frame per output frame whatever the rate. - const double bufferFramesPerFrame = interpolate ? std::fabs(playbackRate) : 1.0; - const double bufferSampleRate = buffer_->getSampleRate(); - size_t framesToPlay = offsetLength; - if (remainingDuration_) { - const double framesLeft = - std::round(*remainingDuration_ * bufferSampleRate / bufferFramesPerFrame); - if (framesLeft < static_cast(offsetLength)) { - framesToPlay = static_cast(framesLeft); - } - } - - processor_->process(processingBuffer, startOffset, framesToPlay, playbackRate, interpolate); - - if (remainingDuration_) { - if (framesToPlay < offsetLength) { - processingBuffer->zero(startOffset + framesToPlay, offsetLength - framesToPlay); - remainingDuration_ = 0.0; - playbackState_ = PlaybackState::STOP_SCHEDULED; - } else { - const double spent = - static_cast(framesToPlay) * bufferFramesPerFrame / bufferSampleRate; - remainingDuration_ = std::max(0.0, *remainingDuration_ - spent); - } - } + processor_->process(processingBuffer, startOffset, offsetLength, playbackRate, interpolate); if (processor_->atBoundary() && processor_->shouldStop()) { playbackState_ = PlaybackState::STOP_SCHEDULED; diff --git a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.h b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.h index b077d90556..4541bd9cce 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.h +++ b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.h @@ -6,7 +6,6 @@ #include #include #include -#include namespace audioapi { @@ -67,9 +66,6 @@ class AudioBufferSourceNode : public AudioBufferBaseSourceNode { double loopStart_; double loopEnd_; - /// Buffer seconds `start()`'s `duration` still allows, across loop iterations. - std::optional remainingDuration_; - // User provided buffer std::shared_ptr buffer_; diff --git a/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.cpp b/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.cpp index c081998eb4..4fb2ae8d66 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.cpp +++ b/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.cpp @@ -1,5 +1,6 @@ #include +#include #include #include #include @@ -7,6 +8,10 @@ namespace audioapi { CursorState SingleBufferProcessor::advance(double rate) { + if (isFrameBudgetSpent()) { + return {.atEndOfBuffer = true}; + } + const double currentPosition = position_; const auto index = static_cast(currentPosition); const auto factor = static_cast(currentPosition - static_cast(index)); @@ -31,6 +36,8 @@ CursorState SingleBufferProcessor::advance(double rate) { (currentPosition >= static_cast(endFrame_) || currentPosition < static_cast(startFrame_)); + spendFrameBudget(std::fabs(rate)); + return {.index = index, .nextIndex = nextIndex, .factor = factor, .atEndOfBuffer = atEnd}; } @@ -38,11 +45,14 @@ size_t SingleBufferProcessor::remainingInContiguousBlock() const { if (atBoundary()) { return 0; } - if (direction_ == BufferProcessingDirection::REVERSE) { - // +1 because we read down to and including startFrame_ - return currentIndex() - startFrame_ + 1; + // +1 in reverse because we read down to and including startFrame_ + const size_t framesToEdge = direction_ == BufferProcessingDirection::REVERSE + ? currentIndex() - startFrame_ + 1 + : endFrame_ - currentIndex(); + if (!frameBudget_) { + return framesToEdge; } - return endFrame_ - currentIndex(); + return std::min(framesToEdge, static_cast(std::ceil(*frameBudget_))); } void SingleBufferProcessor::consume(size_t frames) { @@ -51,6 +61,7 @@ void SingleBufferProcessor::consume(size_t frames) { } else { position_ += static_cast(frames); } + spendFrameBudget(static_cast(frames)); } size_t SingleBufferProcessor::currentIndex() const { @@ -66,12 +77,12 @@ std::shared_ptr SingleBufferProcessor::getNextBuffer() const } bool SingleBufferProcessor::atBoundary() const { - return position_ < static_cast(startFrame_) || + return isFrameBudgetSpent() || position_ < static_cast(startFrame_) || position_ >= static_cast(endFrame_); } bool SingleBufferProcessor::shouldStop() const { - return !loop_; + return !loop_ || isFrameBudgetSpent(); } void SingleBufferProcessor::handleBoundary() { diff --git a/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.h b/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.h index 81305203cd..7251e3d373 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.h +++ b/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.h @@ -7,6 +7,7 @@ #include #include #include +#include #include namespace audioapi { @@ -45,6 +46,12 @@ class SingleBufferProcessor : public BufferProcessorBase { buffer_ = std::move(buffer); } + /// @brief Limit playback to this many buffer frames, counted across loop iterations. + /// @note A spent budget is a boundary the processor stops at, even when looping. + void setFrameBudget(size_t frames) { + frameBudget_ = static_cast(frames); + } + protected: CursorState advance(double rate) override; void consume(size_t frames) override; @@ -60,6 +67,18 @@ class SingleBufferProcessor : public BufferProcessorBase { bool loop_ = false; size_t startFrame_ = 0; size_t endFrame_ = 0; + /// Fractional, because interpolated playback spends `|rate|` buffer frames per output frame. + std::optional frameBudget_; + + [[nodiscard]] bool isFrameBudgetSpent() const { + return frameBudget_ && *frameBudget_ <= 0.0; + } + + void spendFrameBudget(double frames) { + if (frameBudget_) { + *frameBudget_ -= frames; + } + } }; } // namespace audioapi From 4985efac6e3cb8e6823d6b9b17a3f83d129cdef1 Mon Sep 17 00:00:00 2001 From: Abboskhon Sobirov Date: Tue, 17 Nov 2026 23:48:06 +0900 Subject: [PATCH 3/7] fix: ignore non-finite start() duration --- .../common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp index 202244364f..cbdc7f4c59 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp +++ b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -82,7 +83,7 @@ void AudioBufferSourceNode::setBuffer( void AudioBufferSourceNode::start(double when, double offset, double duration) { AudioScheduledSourceNode::start(when); - if (duration > 0) { + if (duration > 0 && std::isfinite(duration)) { // A buffer assigned after start() is taken to run at the context rate. const float sampleRate = buffer_ != nullptr ? buffer_->getSampleRate() : getContextSampleRate(); // Spec: `duration` counts buffer content, not context time. From 692cf0941b97573b6622da20661b80f222b5d300 Mon Sep 17 00:00:00 2001 From: Abboskhon Sobirov Date: Wed, 18 Nov 2026 07:12:52 +0900 Subject: [PATCH 4/7] fix: size start() duration by the late buffer --- .../core/sources/AudioBufferSourceNode.cpp | 4 +-- .../utils/buffer/SingleBufferProcessor.cpp | 21 ++++++++++++++ .../core/utils/buffer/SingleBufferProcessor.h | 14 +++++----- .../sources/AudioBufferSourceNodeTest.cpp | 28 +++++++++++++++++++ 4 files changed, 57 insertions(+), 10 deletions(-) diff --git a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp index cbdc7f4c59..42c415d581 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp +++ b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp @@ -84,10 +84,8 @@ void AudioBufferSourceNode::start(double when, double offset, double duration) { AudioScheduledSourceNode::start(when); if (duration > 0 && std::isfinite(duration)) { - // A buffer assigned after start() is taken to run at the context rate. - const float sampleRate = buffer_ != nullptr ? buffer_->getSampleRate() : getContextSampleRate(); // Spec: `duration` counts buffer content, not context time. - processor_->setFrameBudget(dsp::timeToSampleFrame(duration, sampleRate)); + processor_->setDurationBudget(duration); } if (buffer_ == nullptr) { diff --git a/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.cpp b/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.cpp index 4fb2ae8d66..31d02f7db9 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.cpp +++ b/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.cpp @@ -1,12 +1,33 @@ #include +#include #include #include #include #include +#include namespace audioapi { +void SingleBufferProcessor::setBuffer(std::shared_ptr buffer) { + buffer_ = std::move(buffer); + startFrameBudgetOnceBufferIsSet(); +} + +void SingleBufferProcessor::setDurationBudget(double seconds) { + durationAwaitingBuffer_ = seconds; + startFrameBudgetOnceBufferIsSet(); +} + +void SingleBufferProcessor::startFrameBudgetOnceBufferIsSet() { + if (!durationAwaitingBuffer_ || buffer_ == nullptr) { + return; + } + frameBudget_ = static_cast( + dsp::timeToSampleFrame(*durationAwaitingBuffer_, buffer_->getSampleRate())); + durationAwaitingBuffer_.reset(); +} + CursorState SingleBufferProcessor::advance(double rate) { if (isFrameBudgetSpent()) { return {.atEndOfBuffer = true}; diff --git a/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.h b/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.h index 7251e3d373..5e4f736608 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.h +++ b/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.h @@ -42,15 +42,11 @@ class SingleBufferProcessor : public BufferProcessorBase { } /// @brief Set the audio buffer to process. - void setBuffer(std::shared_ptr buffer) { - buffer_ = std::move(buffer); - } + void setBuffer(std::shared_ptr buffer); - /// @brief Limit playback to this many buffer frames, counted across loop iterations. + /// @brief Limit playback to this many seconds of buffer content, counted across loop iterations. /// @note A spent budget is a boundary the processor stops at, even when looping. - void setFrameBudget(size_t frames) { - frameBudget_ = static_cast(frames); - } + void setDurationBudget(double seconds); protected: CursorState advance(double rate) override; @@ -67,9 +63,13 @@ class SingleBufferProcessor : public BufferProcessorBase { bool loop_ = false; size_t startFrame_ = 0; size_t endFrame_ = 0; + /// Seconds only become frames at the buffer's own sample rate. + std::optional durationAwaitingBuffer_; /// Fractional, because interpolated playback spends `|rate|` buffer frames per output frame. std::optional frameBudget_; + void startFrameBudgetOnceBufferIsSet(); + [[nodiscard]] bool isFrameBudgetSpent() const { return frameBudget_ && *frameBudget_ <= 0.0; } diff --git a/packages/react-native-audio-api/common/cpp/test/src/core/sources/AudioBufferSourceNodeTest.cpp b/packages/react-native-audio-api/common/cpp/test/src/core/sources/AudioBufferSourceNodeTest.cpp index 70bb0a6832..5e4a447f44 100644 --- a/packages/react-native-audio-api/common/cpp/test/src/core/sources/AudioBufferSourceNodeTest.cpp +++ b/packages/react-native-audio-api/common/cpp/test/src/core/sources/AudioBufferSourceNodeTest.cpp @@ -499,6 +499,34 @@ TEST_F(AudioBufferSourceNodeTest, StartDurationCountsBufferTimeWithPitchCorrecti EXPECT_DOUBLE_EQ(node->getCurrentPosition(), static_cast(DURATION_FRAMES) / SAMPLE_RATE); } +/// Spec: start() keeps `duration` for a buffer assigned later, and counts that buffer's content. +TEST_F(AudioBufferSourceNodeTest, StartDurationCountsContentOfBufferAssignedAfterStart) { + static constexpr int BUFFER_SAMPLE_RATE = SAMPLE_RATE / 2; + auto *node = addNode(makeNodeWithoutBuffer()); + + constexpr size_t DURATION_FRAMES = QUANTUM + QUANTUM / 2; + node->start(0.0, 0.0, static_cast(DURATION_FRAMES) / BUFFER_SAMPLE_RATE); + + auto buffer = + std::make_shared(8 * QUANTUM, 1, static_cast(BUFFER_SAMPLE_RATE)); + for (auto &sample : buffer->getChannel(0)->span()) { + sample = 1.0f; + } + node->setBuffer(buffer, makeOutputBuffer()); + + auto out = std::make_shared(QUANTUM, 1, static_cast(SAMPLE_RATE)); + size_t played = 0; + for (int q = 0; q < 4; ++q) { + context->processGraph(out.get(), QUANTUM); + for (float sample : out->getChannel(0)->span()) { + played += sample != 0.0f ? 1 : 0; + } + } + + EXPECT_EQ(played, DURATION_FRAMES); + EXPECT_TRUE(node->isFinished()); +} + /// `loop` passed to the constructor must loop like the setter does. TEST_F(AudioBufferSourceNodeTest, LoopFromConstructorOptionsKeepsPlayingPastBufferEnd) { AudioBufferSourceOptions options{BaseAudioBufferSourceOptions()}; From 4793c9ce2d3ddb051d91528d3487e019757b7223 Mon Sep 17 00:00:00 2001 From: Abboskhon Sobirov Date: Wed, 18 Nov 2026 19:08:14 +0900 Subject: [PATCH 5/7] fix: keep start() offset for a late buffer --- .../core/sources/AudioBufferSourceNode.cpp | 29 ++++++++++------ .../core/sources/AudioBufferSourceNode.h | 9 +++++ .../utils/buffer/SingleBufferProcessor.cpp | 21 ------------ .../core/utils/buffer/SingleBufferProcessor.h | 14 ++++---- .../sources/AudioBufferSourceNodeTest.cpp | 33 +++++++++++++++++++ 5 files changed, 68 insertions(+), 38 deletions(-) diff --git a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp index 42c415d581..781cc1f411 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp +++ b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp @@ -78,30 +78,39 @@ void AudioBufferSourceNode::setBuffer( buffer_ = buffer; audioBuffer_ = audioBuffer; processor_->setBuffer(buffer_); + applyStartToBuffer(); } void AudioBufferSourceNode::start(double when, double offset, double duration) { AudioScheduledSourceNode::start(when); - if (duration > 0 && std::isfinite(duration)) { - // Spec: `duration` counts buffer content, not context time. - processor_->setDurationBudget(duration); - } + // Spec: both wait for a buffer assigned after start(). + startAwaitingBuffer_ = StartArguments{ + .offset = offset, + .duration = + duration >= 0 && std::isfinite(duration) ? std::optional(duration) : std::nullopt}; + applyStartToBuffer(); +} - if (buffer_ == nullptr) { +void AudioBufferSourceNode::applyStartToBuffer() { + if (buffer_ == nullptr || !startAwaitingBuffer_) { return; } + const auto [offset, duration] = *std::exchange(startAwaitingBuffer_, std::nullopt); + const auto sampleRate = buffer_->getSampleRate(); // Past the (effective) loop end, or past the buffer when not looping, playback starts // at that boundary instead. - const auto sampleRate = buffer_->getSampleRate(); - offset = std::min(offset, getVirtualEndFrame(sampleRate) / sampleRate); - + double startOffset = std::min(offset, getVirtualEndFrame(sampleRate) / sampleRate); if (loop_) { - offset = std::min(offset, loopEnd_); + startOffset = std::min(startOffset, loopEnd_); } + vReadIndex_ = sampleRate * startOffset; - vReadIndex_ = sampleRate * offset; + if (duration) { + // Spec: `duration` counts buffer content, not context time. + processor_->setFrameBudget(dsp::timeToSampleFrame(*duration, sampleRate)); + } } void AudioBufferSourceNode::disable() { diff --git a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.h b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.h index 4541bd9cce..6d1f8915b8 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.h +++ b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.h @@ -6,6 +6,7 @@ #include #include #include +#include namespace audioapi { @@ -68,6 +69,14 @@ class AudioBufferSourceNode : public AudioBufferBaseSourceNode { // User provided buffer std::shared_ptr buffer_; + /// start() arguments in seconds, which only become frames at the buffer's own sample rate. + struct StartArguments { + double offset; + std::optional duration; + }; + std::optional startAwaitingBuffer_; + + void applyStartToBuffer(); EventCaller onLoopEndedEvent_; void sendOnLoopEndedEvent(); diff --git a/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.cpp b/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.cpp index 31d02f7db9..4fb2ae8d66 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.cpp +++ b/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.cpp @@ -1,33 +1,12 @@ #include -#include #include #include #include #include -#include namespace audioapi { -void SingleBufferProcessor::setBuffer(std::shared_ptr buffer) { - buffer_ = std::move(buffer); - startFrameBudgetOnceBufferIsSet(); -} - -void SingleBufferProcessor::setDurationBudget(double seconds) { - durationAwaitingBuffer_ = seconds; - startFrameBudgetOnceBufferIsSet(); -} - -void SingleBufferProcessor::startFrameBudgetOnceBufferIsSet() { - if (!durationAwaitingBuffer_ || buffer_ == nullptr) { - return; - } - frameBudget_ = static_cast( - dsp::timeToSampleFrame(*durationAwaitingBuffer_, buffer_->getSampleRate())); - durationAwaitingBuffer_.reset(); -} - CursorState SingleBufferProcessor::advance(double rate) { if (isFrameBudgetSpent()) { return {.atEndOfBuffer = true}; diff --git a/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.h b/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.h index 5e4f736608..7251e3d373 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.h +++ b/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.h @@ -42,11 +42,15 @@ class SingleBufferProcessor : public BufferProcessorBase { } /// @brief Set the audio buffer to process. - void setBuffer(std::shared_ptr buffer); + void setBuffer(std::shared_ptr buffer) { + buffer_ = std::move(buffer); + } - /// @brief Limit playback to this many seconds of buffer content, counted across loop iterations. + /// @brief Limit playback to this many buffer frames, counted across loop iterations. /// @note A spent budget is a boundary the processor stops at, even when looping. - void setDurationBudget(double seconds); + void setFrameBudget(size_t frames) { + frameBudget_ = static_cast(frames); + } protected: CursorState advance(double rate) override; @@ -63,13 +67,9 @@ class SingleBufferProcessor : public BufferProcessorBase { bool loop_ = false; size_t startFrame_ = 0; size_t endFrame_ = 0; - /// Seconds only become frames at the buffer's own sample rate. - std::optional durationAwaitingBuffer_; /// Fractional, because interpolated playback spends `|rate|` buffer frames per output frame. std::optional frameBudget_; - void startFrameBudgetOnceBufferIsSet(); - [[nodiscard]] bool isFrameBudgetSpent() const { return frameBudget_ && *frameBudget_ <= 0.0; } diff --git a/packages/react-native-audio-api/common/cpp/test/src/core/sources/AudioBufferSourceNodeTest.cpp b/packages/react-native-audio-api/common/cpp/test/src/core/sources/AudioBufferSourceNodeTest.cpp index 5e4a447f44..612ac22514 100644 --- a/packages/react-native-audio-api/common/cpp/test/src/core/sources/AudioBufferSourceNodeTest.cpp +++ b/packages/react-native-audio-api/common/cpp/test/src/core/sources/AudioBufferSourceNodeTest.cpp @@ -527,6 +527,39 @@ TEST_F(AudioBufferSourceNodeTest, StartDurationCountsContentOfBufferAssignedAfte EXPECT_TRUE(node->isFinished()); } +/// Spec: start() keeps `offset` for a buffer assigned later, and counts it in that buffer's time. +TEST_F(AudioBufferSourceNodeTest, StartOffsetAppliesToBufferAssignedAfterStart) { + static constexpr int BUFFER_SAMPLE_RATE = SAMPLE_RATE / 2; + auto *node = addNode(makeNodeWithoutBuffer()); + + constexpr size_t OFFSET_FRAMES = 2 * QUANTUM; + node->start(0.0, static_cast(OFFSET_FRAMES) / BUFFER_SAMPLE_RATE); + node->setBuffer( + std::make_shared(8 * QUANTUM, 1, static_cast(BUFFER_SAMPLE_RATE)), + makeOutputBuffer()); + + EXPECT_DOUBLE_EQ( + node->getCurrentPosition(), static_cast(OFFSET_FRAMES) / BUFFER_SAMPLE_RATE); +} + +/// Spec: a `duration` of zero plays no buffer content. +TEST_F(AudioBufferSourceNodeTest, StartWithZeroDurationPlaysNothing) { + auto *node = addNode(makeNodeWithoutBuffer()); + auto buffer = makeSilentBuffer(8 * QUANTUM); + for (auto &sample : buffer->getChannel(0)->span()) { + sample = 1.0f; + } + node->setBuffer(buffer, makeOutputBuffer()); + node->start(0.0, 0.0, 0.0); + + auto out = std::make_shared(QUANTUM, 1, static_cast(SAMPLE_RATE)); + context->processGraph(out.get(), QUANTUM); + for (float sample : out->getChannel(0)->span()) { + EXPECT_EQ(sample, 0.0f); + } + EXPECT_TRUE(node->isFinished()); +} + /// `loop` passed to the constructor must loop like the setter does. TEST_F(AudioBufferSourceNodeTest, LoopFromConstructorOptionsKeepsPlayingPastBufferEnd) { AudioBufferSourceOptions options{BaseAudioBufferSourceOptions()}; From bf480e7cc9816c92879187490e254d1ba78b5a24 Mon Sep 17 00:00:00 2001 From: Abboskhon Sobirov Date: Thu, 19 Nov 2026 15:45:32 +0900 Subject: [PATCH 6/7] fix: read buffer at its own sample rate --- .../AudioBufferSourceNodeHostObject.cpp | 3 +- .../sources/AudioBufferBaseSourceNode.cpp | 4 +- .../core/sources/AudioBufferSourceNode.cpp | 24 ++++-- .../core/utils/buffer/SingleBufferProcessor.h | 4 +- .../sources/AudioBufferSourceNodeTest.cpp | 79 ++++++++++++++++++- 5 files changed, 102 insertions(+), 12 deletions(-) diff --git a/packages/react-native-audio-api/common/cpp/audioapi/HostObjects/sources/AudioBufferSourceNodeHostObject.cpp b/packages/react-native-audio-api/common/cpp/audioapi/HostObjects/sources/AudioBufferSourceNodeHostObject.cpp index d08d0f618c..351b651649 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/HostObjects/sources/AudioBufferSourceNodeHostObject.cpp +++ b/packages/react-native-audio-api/common/cpp/audioapi/HostObjects/sources/AudioBufferSourceNodeHostObject.cpp @@ -175,7 +175,8 @@ AudioBufferSourceNodeHostObject::NodeBuffers AudioBufferSourceNodeHostObject::pr if (pitchCorrection_) { initStretch( - static_cast(acquiredContent->getNumberOfChannels()), acquiredContent->getSampleRate()); + static_cast(acquiredContent->getNumberOfChannels()), + audioBufferSourceNode_->getContextSampleRate()); } buffers.nodeBuffer = acquiredContent; diff --git a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferBaseSourceNode.cpp b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferBaseSourceNode.cpp index c19249574f..adaedfda62 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferBaseSourceNode.cpp +++ b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferBaseSourceNode.cpp @@ -144,9 +144,9 @@ void AudioBufferBaseSourceNode::processWithPitchCorrection( 2.0f, // NOLINT(cppcoreguidelines-avoid-magic-numbers, readability-magic-numbers) detune / static_cast(SEMITONES_PER_OCTAVE)); - const float bufferPlaybackRate = rate >= 0.0f ? rate : -rate; const bool stopTimeReached = isStopScheduled(); - runBufferProcessor(playbackRateBuffer_, startOffset, offsetLength, bufferPlaybackRate, false); + // WSOLA applies the speed, so the source reads forward at its natural rate. + runBufferProcessor(playbackRateBuffer_, startOffset, offsetLength, 1.0f, false); // The source ran dry (as opposed to stop() time arriving), but the stretcher still // holds audio. The processor has already zero-filled the rest of the input, so keep diff --git a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp index 781cc1f411..bcfd0ab4b7 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp +++ b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp @@ -45,7 +45,8 @@ void AudioBufferSourceNode::setLoopSkip(bool loopSkip) { void AudioBufferSourceNode::setLoopStart(double loopStart) { if (loopSkip_) { - vReadIndex_ = loopStart * getContextSampleRate(); + vReadIndex_ = + loopStart * (buffer_ != nullptr ? buffer_->getSampleRate() : getContextSampleRate()); } loopStart_ = loopStart; } @@ -109,7 +110,12 @@ void AudioBufferSourceNode::applyStartToBuffer() { if (duration) { // Spec: `duration` counts buffer content, not context time. - processor_->setFrameBudget(dsp::timeToSampleFrame(*duration, sampleRate)); + // Seconds-to-frames conversion leaves float noise that would otherwise add a whole frame. + constexpr double kWholeFrameTolerance = 1e-6; + const double frames = *duration * sampleRate; + const double wholeFrames = std::round(frames); + processor_->setFrameBudget( + std::fabs(frames - wholeFrames) < kWholeFrameTolerance ? wholeFrames : frames); } } @@ -152,9 +158,10 @@ void AudioBufferSourceNode::runBufferProcessor( return; } - const float sampleRate = getContextSampleRate(); - const double startFrame = getVirtualStartFrame(sampleRate); - const double endFrame = getVirtualEndFrame(sampleRate); + const float bufferSampleRate = buffer_->getSampleRate(); + const double startFrame = getVirtualStartFrame(bufferSampleRate); + const double endFrame = getVirtualEndFrame(bufferSampleRate); + const double resampleRatio = bufferSampleRate / getContextSampleRate(); // start(when, offset=duration) sets vReadIndex_ to endFrame, so clamp it if (playbackRate < 0 && vReadIndex_ >= endFrame && endFrame > startFrame) { @@ -164,7 +171,12 @@ void AudioBufferSourceNode::runBufferProcessor( processor_->setPosition(vReadIndex_); processor_->setEndFrame(static_cast(endFrame)); processor_->setStartFrame(static_cast(startFrame)); - processor_->process(processingBuffer, startOffset, offsetLength, playbackRate, interpolate); + processor_->process( + processingBuffer, + startOffset, + offsetLength, + playbackRate * resampleRatio, + interpolate || resampleRatio != 1.0); if (processor_->atBoundary() && processor_->shouldStop()) { playbackState_ = PlaybackState::STOP_SCHEDULED; diff --git a/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.h b/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.h index 7251e3d373..f678e22155 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.h +++ b/packages/react-native-audio-api/common/cpp/audioapi/core/utils/buffer/SingleBufferProcessor.h @@ -48,8 +48,8 @@ class SingleBufferProcessor : public BufferProcessorBase { /// @brief Limit playback to this many buffer frames, counted across loop iterations. /// @note A spent budget is a boundary the processor stops at, even when looping. - void setFrameBudget(size_t frames) { - frameBudget_ = static_cast(frames); + void setFrameBudget(double frames) { + frameBudget_ = frames; } protected: diff --git a/packages/react-native-audio-api/common/cpp/test/src/core/sources/AudioBufferSourceNodeTest.cpp b/packages/react-native-audio-api/common/cpp/test/src/core/sources/AudioBufferSourceNodeTest.cpp index 612ac22514..ad6ca9279e 100644 --- a/packages/react-native-audio-api/common/cpp/test/src/core/sources/AudioBufferSourceNodeTest.cpp +++ b/packages/react-native-audio-api/common/cpp/test/src/core/sources/AudioBufferSourceNodeTest.cpp @@ -523,10 +523,87 @@ TEST_F(AudioBufferSourceNodeTest, StartDurationCountsContentOfBufferAssignedAfte } } - EXPECT_EQ(played, DURATION_FRAMES); + // The buffer runs at half the context rate, so each buffer frame lasts two output frames. + EXPECT_EQ(played, 2 * DURATION_FRAMES); EXPECT_TRUE(node->isFinished()); } +/// Spec: `duration` is compared against unrounded buffer time, so a fractional frame counts. +TEST_F(AudioBufferSourceNodeTest, StartDurationKeepsFractionalBufferFrames) { + BaseAudioBufferSourceOptions baseOptions; + baseOptions.playbackRate = 0.25f; + auto *node = addNode( + std::make_unique( + context, AudioBufferSourceOptions(baseOptions))); + + auto buffer = makeSilentBuffer(8 * QUANTUM); + for (auto &sample : buffer->getChannel(0)->span()) { + sample = 1.0f; + } + node->setBuffer(buffer, makeOutputBuffer()); + + constexpr double DURATION_FRAMES = 1.5; + node->start(0.0, 0.0, DURATION_FRAMES / SAMPLE_RATE); + + auto out = std::make_shared(QUANTUM, 1, static_cast(SAMPLE_RATE)); + context->processGraph(out.get(), QUANTUM); + size_t played = 0; + for (float sample : out->getChannel(0)->span()) { + played += sample != 0.0f ? 1 : 0; + } + + EXPECT_EQ(played, 6U); +} + +/// A buffer at half the context rate feeds WSOLA one buffer frame per two output frames. +TEST_F(AudioBufferSourceNodeTest, PitchCorrectionReadsBufferAtItsOwnSampleRate) { + static constexpr int BUFFER_SAMPLE_RATE = SAMPLE_RATE / 2; + BaseAudioBufferSourceOptions baseOptions; + baseOptions.pitchCorrection = true; + baseOptions.playbackRate = 2.0f; + auto *node = addNode( + std::make_unique( + context, AudioBufferSourceOptions(baseOptions))); + auto playbackRateBuffer = std::make_shared( + static_cast(WsolaTimeStretcher::MAX_PLAYBACK_RATE * QUANTUM), + 1, + static_cast(SAMPLE_RATE)); + node->initStretch(1, static_cast(SAMPLE_RATE), playbackRateBuffer); + node->setBuffer( + std::make_shared(8 * QUANTUM, 1, static_cast(BUFFER_SAMPLE_RATE)), + makeOutputBuffer()); + node->start(0.0); + + constexpr int QUANTA = 3; + for (int q = 0; q < QUANTA; ++q) { + processGraph(); + } + + // Each quantum stretches 2 * QUANTUM output-rate frames, which is QUANTUM buffer frames. + EXPECT_DOUBLE_EQ( + node->getCurrentPosition(), static_cast(QUANTA * QUANTUM) / BUFFER_SAMPLE_RATE); +} + +/// Spec: loop points are buffer time, so they become frames at the buffer's sample rate. +TEST_F(AudioBufferSourceNodeTest, LoopPointsUseBufferSampleRate) { + static constexpr int BUFFER_SAMPLE_RATE = SAMPLE_RATE / 2; + auto *node = addNode(makeNodeWithoutBuffer()); + node->setLoop(true); + constexpr size_t LOOP_END_FRAMES = 3 * QUANTUM / 8; + node->setLoopEnd(static_cast(LOOP_END_FRAMES) / BUFFER_SAMPLE_RATE); + node->setBuffer( + std::make_shared(8 * QUANTUM, 1, static_cast(BUFFER_SAMPLE_RATE)), + makeOutputBuffer()); + node->start(0.0); + + processGraph(); + + // One quantum reads QUANTUM / 2 buffer frames, wrapping once past the loop end. + constexpr size_t EXPECTED_FRAMES = QUANTUM / 2 - LOOP_END_FRAMES; + EXPECT_DOUBLE_EQ( + node->getCurrentPosition(), static_cast(EXPECTED_FRAMES) / BUFFER_SAMPLE_RATE); +} + /// Spec: start() keeps `offset` for a buffer assigned later, and counts it in that buffer's time. TEST_F(AudioBufferSourceNodeTest, StartOffsetAppliesToBufferAssignedAfterStart) { static constexpr int BUFFER_SAMPLE_RATE = SAMPLE_RATE / 2; From 26a1b76ddb0929809178f48b81e298933004857b Mon Sep 17 00:00:00 2001 From: Abboskhon Sobirov Date: Thu, 19 Nov 2026 18:48:47 +0900 Subject: [PATCH 7/7] refactor: move frame snap to AudioUtils --- .../cpp/audioapi/core/sources/AudioBufferSourceNode.cpp | 7 +------ .../common/cpp/audioapi/dsp/AudioUtils.h | 8 ++++++++ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp index bcfd0ab4b7..8e7d3105f7 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp +++ b/packages/react-native-audio-api/common/cpp/audioapi/core/sources/AudioBufferSourceNode.cpp @@ -110,12 +110,7 @@ void AudioBufferSourceNode::applyStartToBuffer() { if (duration) { // Spec: `duration` counts buffer content, not context time. - // Seconds-to-frames conversion leaves float noise that would otherwise add a whole frame. - constexpr double kWholeFrameTolerance = 1e-6; - const double frames = *duration * sampleRate; - const double wholeFrames = std::round(frames); - processor_->setFrameBudget( - std::fabs(frames - wholeFrames) < kWholeFrameTolerance ? wholeFrames : frames); + processor_->setFrameBudget(dsp::timeToFractionalFrames(*duration, sampleRate)); } } diff --git a/packages/react-native-audio-api/common/cpp/audioapi/dsp/AudioUtils.h b/packages/react-native-audio-api/common/cpp/audioapi/dsp/AudioUtils.h index 9626afc82c..4b09475a9c 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/dsp/AudioUtils.h +++ b/packages/react-native-audio-api/common/cpp/audioapi/dsp/AudioUtils.h @@ -12,6 +12,14 @@ namespace audioapi::dsp { return static_cast(0.5 + time * sampleRate); } +/// Fractional frames, with float noise near a whole frame snapped away. +[[nodiscard]] inline double timeToFractionalFrames(double time, float sampleRate) { + constexpr double kWholeFrameTolerance = 1e-6; + const double frames = time * sampleRate; + const double wholeFrames = std::round(frames); + return std::fabs(frames - wholeFrames) < kWholeFrameTolerance ? wholeFrames : frames; +} + [[nodiscard]] inline double sampleFrameToTime(int sampleFrame, float sampleRate) { return static_cast(sampleFrame) / sampleRate; }