94 lines
2.3 KiB
C++
94 lines
2.3 KiB
C++
#pragma once
|
|
|
|
#include <algorithm>
|
|
#include <cstddef>
|
|
#include <span>
|
|
#include <vector>
|
|
|
|
namespace Echoion::Core
|
|
{
|
|
|
|
// Fixed-capacity ring buffer of audio samples for the playback thread.
|
|
//
|
|
// A std::vector<short> drained with erase(begin(), begin()+n) every 20ms
|
|
// is an O(n) shift of the whole remaining buffer on the real-time audio
|
|
// path. This ring buffer drains by advancing a head index (O(1)) and
|
|
// reuses one contiguous allocation, so steady-state playback performs
|
|
// zero per-frame allocations and no element shuffling. Capacity grows
|
|
// only if a decoder hands back an unusually large chunk (rare); steady
|
|
// state never reallocates.
|
|
//
|
|
// Single-threaded by design: owned and touched only by the playback
|
|
// engine thread.
|
|
class AudioRingBuffer
|
|
{
|
|
public:
|
|
|
|
void reserve(std::size_t capacity)
|
|
{
|
|
if (capacity > storage_.size()) {
|
|
grow(capacity);
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] std::size_t size() const { return count_; }
|
|
[[nodiscard]] bool empty() const { return count_ == 0; }
|
|
|
|
// Read the i-th sample counting from the current head.
|
|
short operator[](std::size_t i) const
|
|
{
|
|
return storage_[(head_ + i) % storage_.size()];
|
|
}
|
|
|
|
void append(std::span<const short> data)
|
|
{
|
|
if (count_ + data.size() > storage_.size()) {
|
|
grow(count_ + data.size());
|
|
}
|
|
const std::size_t cap = storage_.size();
|
|
std::size_t tail = (head_ + count_) % cap;
|
|
for (short sample : data) {
|
|
storage_[tail] = sample;
|
|
tail = (tail + 1) % cap;
|
|
}
|
|
count_ += data.size();
|
|
}
|
|
|
|
// Drop the first n samples (advance head). O(1).
|
|
void popFront(std::size_t n)
|
|
{
|
|
n = std::min(n, count_);
|
|
head_ = (head_ + n) % storage_.size();
|
|
count_ -= n;
|
|
}
|
|
|
|
void clear()
|
|
{
|
|
head_ = 0;
|
|
count_ = 0;
|
|
}
|
|
|
|
private:
|
|
|
|
void grow(std::size_t needed)
|
|
{
|
|
// Linearise existing samples into a fresh, larger buffer.
|
|
std::size_t newCap = storage_.empty() ? 1 : storage_.size();
|
|
while (newCap < needed) {
|
|
newCap *= 2;
|
|
}
|
|
std::vector<short> next(newCap);
|
|
for (std::size_t i = 0; i < count_; ++i) {
|
|
next[i] = storage_[(head_ + i) % storage_.size()];
|
|
}
|
|
storage_ = std::move(next);
|
|
head_ = 0;
|
|
}
|
|
|
|
std::vector<short> storage_;
|
|
std::size_t head_ = 0;
|
|
std::size_t count_ = 0;
|
|
};
|
|
|
|
} // namespace Echoion::Core
|