DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
RingBuffer.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
27#include "DspMath.h"
28#include "Interpolation.h"
29
30#include <algorithm>
31#include <cassert>
32#include <cstddef>
33#include <cstdint>
34#include <cstdlib>
35#include <cstring>
36#include <limits>
37#include <memory>
38
39#if defined(_WIN32)
40 #include <malloc.h> // _aligned_malloc / _aligned_free (MSVC and MinGW CRTs)
41#endif
42
43namespace dspark {
44
48enum class InterpMethod
49{
50 Linear,
51 Cubic,
52 Hermite,
54};
55
62template <FloatType T>
64{
65public:
71 RingBuffer() noexcept = default;
72
86 void prepare(int maxSamples) noexcept
87 {
88 assert(maxSamples > 0);
89
90 // Clamp before the round-up loop: growing the signed capacity past
91 // 2^30 would overflow the shift (undefined) and never terminate.
92 constexpr int kMaxCapacity = 1 << 30;
93 if (maxSamples > kMaxCapacity) maxSamples = kMaxCapacity;
94
95 capacity_ = 1;
96 while (capacity_ < maxSamples)
97 capacity_ <<= 1;
98
99 mask_ = capacity_ - 1;
100
101 // Ensure 32-byte alignment for SIMD operations. std::aligned_alloc
102 // additionally requires the size to be an integral multiple of the
103 // alignment (UB / nullptr otherwise on POSIX), so round bytes up to 32.
104 // The byte count is formed in 64 bits: with a 32-bit size_t (x86,
105 // WebAssembly) 2^30 floats wrap to 0 bytes, and the allocator then
106 // hands back a valid zero-size block that the ring would overrun.
107 const std::uint64_t bytes64 =
108 (static_cast<std::uint64_t>(capacity_) * sizeof(T) + 31u) & ~static_cast<std::uint64_t>(31u);
109 if (bytes64 > static_cast<std::uint64_t>(std::numeric_limits<size_t>::max()))
110 {
111 buffer_.reset();
112 capacity_ = 0; mask_ = 0; writePos_ = 0;
113 return;
114 }
115 const size_t bytes = static_cast<size_t>(bytes64);
116
117 // Custom deleter for aligned allocation
118 buffer_.reset(static_cast<T*>(
119 // The Windows CRT has no std::aligned_alloc, whatever the compiler
120 // (MSVC, clang-cl, MinGW GCC/Clang): it has _aligned_malloc.
121 #if defined(_WIN32)
122 _aligned_malloc(bytes, 32)
123 #else
124 std::aligned_alloc(32, bytes)
125 #endif
126 ));
127
128 // On allocation failure leave the buffer in a safe unprepared state.
129 if (!buffer_) { capacity_ = 0; mask_ = 0; writePos_ = 0; return; }
130
131 reset();
132 }
133
138 void reset() noexcept
139 {
140 if (buffer_)
141 std::fill_n(buffer_.get(), capacity_, T(0));
142 writePos_ = 0;
143 }
144
149 inline void push(T sample) noexcept
150 {
151 if (capacity_ == 0) [[unlikely]] return; // not prepared
152 buffer_[writePos_] = sample;
153 writePos_ = (writePos_ + 1) & mask_;
154 }
155
166 void pushBlock(const T* samples, int numSamples) noexcept
167 {
168 if (capacity_ == 0 || numSamples <= 0) [[unlikely]] return;
169
170 if (numSamples >= capacity_)
171 {
172 // Only the trailing capacity_ samples survive a full overwrite.
173 samples += numSamples - capacity_;
174 std::memcpy(buffer_.get(), samples, static_cast<size_t>(capacity_) * sizeof(T));
175 writePos_ = 0;
176 return;
177 }
178
179 const int firstSpan = std::min(numSamples, capacity_ - writePos_);
180 std::memcpy(buffer_.get() + writePos_, samples,
181 static_cast<size_t>(firstSpan) * sizeof(T));
182
183 const int remaining = numSamples - firstSpan;
184 if (remaining > 0)
185 std::memcpy(buffer_.get(), samples + firstSpan,
186 static_cast<size_t>(remaining) * sizeof(T));
187
188 writePos_ = (writePos_ + numSamples) & mask_;
189 }
190
199 [[nodiscard]] inline T read(int delaySamples) const noexcept
200 {
201 if (capacity_ == 0) [[unlikely]] return T(0); // not prepared
202 assert(delaySamples >= 0 && delaySamples < capacity_
203 && "RingBuffer::read: delay out of range");
204
205 int idx = (writePos_ - 1 - delaySamples) & mask_;
206 return buffer_[idx];
207 }
208
229 template <InterpMethod Method = InterpMethod::Cubic>
230 [[nodiscard]] inline T readInterpolated(T delaySamples) const noexcept
231 {
232 if (capacity_ == 0) [[unlikely]] return T(0); // not prepared
233
234 int intDelay = static_cast<int>(delaySamples);
235 T frac = delaySamples - static_cast<T>(intDelay);
236
237 assert(delaySamples >= T(0) && intDelay + 2 < capacity_);
238
239 if constexpr (Method == InterpMethod::Linear)
240 {
241 T s0 = read(intDelay);
242 T s1 = read(intDelay + 1);
243 return s0 + frac * (s1 - s0);
244 }
245 else
246 {
247 assert(delaySamples >= T(1) && "4-point interpolators require delay >= 1.0");
248
249 T s[4];
250 // Optimized contiguous logical read
251 s[0] = read(intDelay - 1);
252 s[1] = read(intDelay);
253 s[2] = read(intDelay + 1);
254 s[3] = read(intDelay + 2);
255
256 // Interpolate within the s[1]..s[2] interval, so an integer delay
257 // (frac == 0) returns exactly read(intDelay) == s[1]. The 4-point
258 // (y0,y1,y2,y3,frac) overloads do precisely that. (Calling the
259 // buffer+position overloads with `frac` would misread it as an
260 // absolute index and interpolate s[0]..s[1] with a wrapped neighbour,
261 // i.e. a 1-sample delay error.)
262 if constexpr (Method == InterpMethod::Cubic || Method == InterpMethod::Hermite)
263 return interpolateHermite(s[0], s[1], s[2], s[3], frac);
264 else if constexpr (Method == InterpMethod::Lagrange)
265 return interpolateLagrange(s[0], s[1], s[2], s[3], frac);
266 }
267 }
268
269 [[nodiscard]] int getCapacity() const noexcept { return capacity_; }
270 [[nodiscard]] const T* data() const noexcept { return buffer_.get(); }
271 [[nodiscard]] int getWritePosition() const noexcept { return writePos_; }
272
273private:
274 struct AlignedDeleter {
275 void operator()(T* ptr) const {
276 #if defined(_WIN32)
277 _aligned_free(ptr);
278 #else
279 std::free(ptr);
280 #endif
281 }
282 };
283
284 std::unique_ptr<T[], AlignedDeleter> buffer_;
285 int capacity_ = 0;
286 int mask_ = 0;
287 int writePos_ = 0;
288};
289
290} // namespace dspark
Power-of-two circular buffer with compile-time interpolated read access.
Definition RingBuffer.h:64
T read(int delaySamples) const noexcept
Reads a sample at an integer delay.
Definition RingBuffer.h:199
void prepare(int maxSamples) noexcept
Allocates the ring buffer with the given capacity.
Definition RingBuffer.h:86
const T * data() const noexcept
Definition RingBuffer.h:270
void pushBlock(const T *samples, int numSamples) noexcept
Pushes a block of samples into the buffer.
Definition RingBuffer.h:166
void push(T sample) noexcept
Pushes a single sample into the buffer.
Definition RingBuffer.h:149
int getCapacity() const noexcept
Definition RingBuffer.h:269
RingBuffer() noexcept=default
Constructs an empty ring buffer. No allocation happens until prepare() is called, honouring the frame...
void reset() noexcept
Clears the buffer to zero without deallocating. Safe to call from the audio thread.
Definition RingBuffer.h:138
T readInterpolated(T delaySamples) const noexcept
Reads a sample at a fractional delay using the specified interpolation.
Definition RingBuffer.h:230
int getWritePosition() const noexcept
Definition RingBuffer.h:271
Main namespace for the DSPark framework.
T interpolateHermite(T y0, T y1, T y2, T y3, T frac) noexcept
4-point, 3rd-order Hermite interpolation (optimized x-form).
T interpolateLagrange(T y0, T y1, T y2, T y3, T frac) noexcept
4-point Lagrange interpolation from discrete samples.
InterpMethod
Interpolation method for fractional-sample reads.
Definition RingBuffer.h:49
@ Lagrange
4-point Lagrange (highest accuracy, static delay)
@ Linear
2-point linear (fast, lower quality)
@ Hermite
4-point Hermite (smooth transients, best for modulated delay)
@ Cubic
4-point Catmull-Rom (good balance)