Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ Schedules the `AudioBufferSourceNode` to start playback of audio data contained
| :---: | :---: | :---- |
| `when` <Optional /> | `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. <br /> Default: `0.0`. |
| `offset` <Optional /> | `number` | The position, in seconds, within the audio buffer where playback begins. <br /> 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. <br /> 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` <Optional /> | `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). <br /> Equivalent to calling `start(when, offset)` followed by `stop(when + duration)`. |
| `duration` <Optional /> | `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). <br /> 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. <br /> When [`loop`](./audio-buffer-source-node.mdx#properties) is enabled, the content played across all loop iterations counts toward it. |


#### Errors:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,8 @@ AudioBufferSourceNodeHostObject::NodeBuffers AudioBufferSourceNodeHostObject::pr

if (pitchCorrection_) {
initStretch(
static_cast<int>(acquiredContent->getNumberOfChannels()), acquiredContent->getSampleRate());
static_cast<int>(acquiredContent->getNumberOfChannels()),
audioBufferSourceNode_->getContextSampleRate());
}

buffers.nodeBuffer = acquiredContent;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,9 +144,9 @@ void AudioBufferBaseSourceNode::processWithPitchCorrection(
2.0f, // NOLINT(cppcoreguidelines-avoid-magic-numbers, readability-magic-numbers)
detune / static_cast<float>(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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

#include <audioapi/core/utils/buffer/SingleBufferProcessor.h>
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <memory>
#include <utility>
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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) {
Expand All @@ -153,7 +166,12 @@ void AudioBufferSourceNode::runBufferProcessor(
processor_->setPosition(vReadIndex_);
processor_->setEndFrame(static_cast<size_t>(endFrame));
processor_->setStartFrame(static_cast<size_t>(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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include <audioapi/core/utils/buffer/SingleBufferProcessor.h>
#include <cstddef>
#include <memory>
#include <optional>

namespace audioapi {

Expand Down Expand Up @@ -68,6 +69,14 @@ class AudioBufferSourceNode : public AudioBufferBaseSourceNode {

// User provided buffer
std::shared_ptr<AudioBuffer> buffer_;
/// start() arguments in seconds, which only become frames at the buffer's own sample rate.
struct StartArguments {
double offset;
std::optional<double> duration;
};
std::optional<StartArguments> startAwaitingBuffer_;

void applyStartToBuffer();

EventCaller<AudioEvent::LOOP_ENDED> onLoopEndedEvent_;
void sendOnLoopEndedEvent();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
#include <audioapi/core/utils/buffer/SingleBufferProcessor.h>

#include <algorithm>
#include <cmath>
#include <cstddef>
#include <memory>

namespace audioapi {

CursorState SingleBufferProcessor::advance(double rate) {
if (isFrameBudgetSpent()) {
return {.atEndOfBuffer = true};
}

const double currentPosition = position_;
const auto index = static_cast<size_t>(currentPosition);
const auto factor = static_cast<float>(currentPosition - static_cast<double>(index));
Expand All @@ -31,18 +36,23 @@ CursorState SingleBufferProcessor::advance(double rate) {
(currentPosition >= static_cast<double>(endFrame_) ||
currentPosition < static_cast<double>(startFrame_));

spendFrameBudget(std::fabs(rate));

return {.index = index, .nextIndex = nextIndex, .factor = factor, .atEndOfBuffer = atEnd};
}

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<size_t>(std::ceil(*frameBudget_)));
}

void SingleBufferProcessor::consume(size_t frames) {
Expand All @@ -51,6 +61,7 @@ void SingleBufferProcessor::consume(size_t frames) {
} else {
position_ += static_cast<double>(frames);
}
spendFrameBudget(static_cast<double>(frames));
}

size_t SingleBufferProcessor::currentIndex() const {
Expand All @@ -66,12 +77,12 @@ std::shared_ptr<const AudioBuffer> SingleBufferProcessor::getNextBuffer() const
}

bool SingleBufferProcessor::atBoundary() const {
return position_ < static_cast<double>(startFrame_) ||
return isFrameBudgetSpent() || position_ < static_cast<double>(startFrame_) ||
position_ >= static_cast<double>(endFrame_);
}

bool SingleBufferProcessor::shouldStop() const {
return !loop_;
return !loop_ || isFrameBudgetSpent();
}

void SingleBufferProcessor::handleBoundary() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <audioapi/utils/FatFunction.hpp>
#include <cstddef>
#include <memory>
#include <optional>
#include <utility>

namespace audioapi {
Expand Down Expand Up @@ -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;
Expand All @@ -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<double> frameBudget_;

[[nodiscard]] bool isFrameBudgetSpent() const {
return frameBudget_ && *frameBudget_ <= 0.0;
}

void spendFrameBudget(double frames) {
if (frameBudget_) {
*frameBudget_ -= frames;
}
}
};

} // namespace audioapi
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ namespace audioapi::dsp {
return static_cast<size_t>(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<double>(sampleFrame) / sampleRate;
}
Expand Down
Loading
Loading