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/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 bb9f34c050..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
@@ -10,6 +10,7 @@
#include
#include
+#include
#include
#include
#include
@@ -44,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;
}
@@ -77,29 +79,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) {
- AudioScheduledSourceNode::stop(when + 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::timeToFractionalFrames(*duration, sampleRate));
+ }
}
void AudioBufferSourceNode::disable() {
@@ -141,9 +153,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) {
@@ -153,7 +166,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/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 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..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
@@ -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(double frames) {
+ frameBudget_ = 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
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;
}
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 0b2ea1dfd4..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
@@ -411,6 +411,232 @@ 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);
+}
+
+/// 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;
+ }
+ }
+
+ // 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;
+ 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()};