DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
AudioBuffer.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
23#include "SimdOps.h"
24
25#include <algorithm>
26#include <array>
27#include <bit>
28#include <cassert>
29#include <cstddef>
30#include <cstdint>
31#include <cstdlib>
32#include <cstring>
33#include <limits>
34#include <new>
35#include <type_traits>
36#include <utility>
37
38namespace dspark {
39
40// ============================================================================
41// AudioBufferView -- Non-owning view
42// ============================================================================
43
51template <typename T, int MaxViewChannels = 16>
53{
54public:
56 AudioBufferView() noexcept = default;
57
65 template <typename U>
66 requires std::is_convertible_v<U*, T*>
67 AudioBufferView(U* const* channelPtrs, int numChannels, int numSamples) noexcept
68 {
69 assert(numChannels >= 0 && numChannels <= MaxViewChannels);
70
71 // Release-safe clamp: an out-of-range channel count must never write
72 // past the fixed pointer array (assert-only protection vanishes in
73 // release builds).
74 numChannels_ = std::clamp(numChannels, 0, MaxViewChannels);
75 numSamples_ = numSamples >= 0 ? numSamples : 0;
76
77 for (int ch = 0; ch < numChannels_; ++ch)
78 channels_[ch] = channelPtrs[ch];
79 }
80
102 template <typename U, int OtherChannels>
103 requires (std::is_convertible_v<U*, T*> && OtherChannels <= MaxViewChannels)
105 : numChannels_(other.getNumChannels()), numSamples_(other.getNumSamples())
106 {
107 for (int ch = 0; ch < numChannels_; ++ch)
108 channels_[ch] = other.getChannel(ch);
109 }
110
111 // -- Accessors -----------------------------------------------------------
112
114 [[nodiscard]] T* getChannel(int ch) const noexcept
115 {
116 assert(ch >= 0 && ch < numChannels_);
117 return channels_[ch];
118 }
119
121 [[nodiscard]] int getNumChannels() const noexcept { return numChannels_; }
122
124 [[nodiscard]] int getNumSamples() const noexcept { return numSamples_; }
125
126 // -- Sub-views -----------------------------------------------------------
127
134 [[nodiscard]] AudioBufferView getSubView(int startSample, int length) const noexcept
135 {
136 assert(startSample >= 0);
137 assert(length >= 0);
138 assert(startSample + length <= numSamples_);
139
140 AudioBufferView sub;
141 sub.numChannels_ = numChannels_;
142 sub.numSamples_ = length;
143 for (int ch = 0; ch < numChannels_; ++ch)
144 sub.channels_[ch] = channels_[ch] + startSample;
145
146 return sub;
147 }
148
149 // -- Operations ----------------------------------------------------------
150
152 void clear() const noexcept
153 {
154 // A hard error, not a silent no-op: matching applyGain/copyFrom so a
155 // clear() on a read-only view can never be mistaken for a real one.
156 static_assert(!std::is_const_v<T>, "Cannot clear a const view");
157 const auto bytes = static_cast<std::size_t>(numSamples_) * sizeof(T);
158 // An empty view may hold null channel pointers (a zero-length host
159 // block, an empty AudioBuffer); memset on null is undefined even with
160 // a zero length.
161 if (bytes == 0) return;
162 for (int ch = 0; ch < numChannels_; ++ch)
163 std::memset(channels_[ch], 0, bytes);
164 }
165
177 template <typename U, int M>
178 void copyFrom(const AudioBufferView<U, M>& src) const noexcept
179 {
180 static_assert(!std::is_const_v<T>, "Cannot copy into a const view");
181
182 const int chCount = std::min(numChannels_, src.getNumChannels());
183 const int nSamples = std::min(numSamples_, src.getNumSamples());
184
185 for (int ch = 0; ch < chCount; ++ch)
186 {
187 T* dst = channels_[ch];
188 const U* s = src.getChannel(ch);
189
190 if constexpr (std::is_same_v<std::remove_const_t<U>, T>)
191 {
192 std::memmove(dst, s, static_cast<std::size_t>(nSamples) * sizeof(T));
193 }
194 else
195 {
196 for (int i = 0; i < nSamples; ++i)
197 dst[i] = static_cast<T>(s[i]);
198 }
199 }
200 }
201
214 template <typename U, int M>
215 void addFrom(const AudioBufferView<U, M>& src, T gain = T(1)) const noexcept
216 {
217 static_assert(!std::is_const_v<T>, "Cannot add into a const view");
218
219 const int chCount = std::min(numChannels_, src.getNumChannels());
220 const int nSamples = std::min(numSamples_, src.getNumSamples());
221
222 for (int ch = 0; ch < chCount; ++ch)
223 {
224 T* dst = channels_[ch];
225 const U* s = src.getChannel(ch);
226
227 if constexpr (std::is_same_v<std::remove_const_t<U>, T>)
228 {
229 simd::addWithGain(dst, s, gain, nSamples);
230 }
231 else
232 {
233 for (int i = 0; i < nSamples; ++i)
234 dst[i] += static_cast<T>(s[i]) * gain;
235 }
236 }
237 }
238
243 void applyGain(T gain) const noexcept
244 {
245 static_assert(!std::is_const_v<T>, "Cannot apply gain to a const view");
246 for (int ch = 0; ch < numChannels_; ++ch)
247 simd::applyGain(channels_[ch], gain, numSamples_);
248 }
249
254 [[nodiscard]] std::remove_const_t<T> getPeakLevel() const noexcept
255 {
256 // remove_const keeps the accumulator (and the returned value)
257 // assignable when T is a const sample type: this read-only query
258 // must work on read-only views.
259 using Value = std::remove_const_t<T>;
260 Value peak = Value(0);
261 for (int ch = 0; ch < numChannels_; ++ch)
262 {
263 const Value chPeak = simd::peakLevel(channels_[ch], numSamples_);
264 if (chPeak > peak) peak = chPeak;
265 }
266 return peak;
267 }
268
269private:
270 std::array<T*, MaxViewChannels> channels_ {};
271 int numChannels_ = 0;
272 int numSamples_ = 0;
273};
274
275// The view is part of the hot-path calling convention: it must stay cheap to
276// copy by value. Guard the promise made in the file header.
277static_assert(std::is_trivially_copyable_v<AudioBufferView<float>>,
278 "AudioBufferView must remain trivially copyable");
279static_assert(std::is_trivially_copyable_v<AudioBufferView<const float>>,
280 "AudioBufferView must remain trivially copyable");
281
282// ============================================================================
283// AudioBuffer -- Owning, SIMD-aligned buffer
284// ============================================================================
285
293template <typename T, int MaxChannels = 16>
295{
296 static constexpr std::size_t kAlignment = 32;
297 static_assert(std::has_single_bit(kAlignment), "Alignment must be a power of two");
298 static_assert(std::is_same_v<T, std::remove_cv_t<T>> && std::is_trivially_copyable_v<T>,
299 "AudioBuffer requires a non-const, trivially copyable sample type");
300
301public:
302 AudioBuffer() = default;
303
304 ~AudioBuffer() { deallocate(); }
305
306 AudioBuffer(const AudioBuffer&) = delete;
308
310 AudioBuffer(AudioBuffer&& other) noexcept
311 : rawData_(std::exchange(other.rawData_, nullptr))
312 , channelPtrs_(std::exchange(other.channelPtrs_, {}))
313 , numChannels_(std::exchange(other.numChannels_, 0))
314 , numSamples_(std::exchange(other.numSamples_, 0))
315 , allocatedBytes_(std::exchange(other.allocatedBytes_, 0))
316 , strideBytes_(std::exchange(other.strideBytes_, 0))
317 {}
318
321 {
322 if (this != &other)
323 {
324 deallocate();
325 rawData_ = std::exchange(other.rawData_, nullptr);
326 channelPtrs_ = std::exchange(other.channelPtrs_, {});
327 numChannels_ = std::exchange(other.numChannels_, 0);
328 numSamples_ = std::exchange(other.numSamples_, 0);
329 allocatedBytes_ = std::exchange(other.allocatedBytes_, 0);
330 strideBytes_ = std::exchange(other.strideBytes_, 0);
331 }
332 return *this;
333 }
334
335 // -- Allocation ----------------------------------------------------------
336
348 void resize(int numChannels, int numSamples)
349 {
350 assert(numChannels >= 0 && numChannels <= MaxChannels);
351 assert(numSamples >= 0);
352
353 // Release-safe clamps: out-of-range requests must never overflow the
354 // fixed channel-pointer array or produce a negative allocation size.
355 numChannels = std::clamp(numChannels, 0, MaxChannels);
356 if (numSamples < 0) numSamples = 0;
357
358 // Computed in 64 bits: with a 32-bit size_t (WebAssembly, x86) these
359 // products of in-range arguments can wrap into a small allocation that
360 // the channel pointers below would then overrun.
361 const auto samplesBytes = static_cast<std::uint64_t>(numSamples) * sizeof(T);
362 const auto stride64 = (samplesBytes + (kAlignment - 1)) & ~static_cast<std::uint64_t>(kAlignment - 1);
363 const auto totalBytes64 = stride64 * static_cast<std::uint64_t>(numChannels);
364 if (totalBytes64 > std::numeric_limits<std::size_t>::max())
365 failAllocation();
366 const auto stride = static_cast<std::size_t>(stride64);
367 const auto totalBytes = static_cast<std::size_t>(totalBytes64);
368
369 // Smart re-allocation: reuse memory if requested size fits in capacity
370 if (totalBytes > allocatedBytes_)
371 {
372 deallocate();
373 rawData_ = static_cast<T*>(::operator new(totalBytes, std::align_val_t(kAlignment)));
374 allocatedBytes_ = totalBytes;
375 }
376
377 numChannels_ = numChannels;
378 numSamples_ = numSamples;
379 strideBytes_ = stride;
380
381 auto* base = reinterpret_cast<char*>(rawData_);
382
383 // Map active channels
384 for (int ch = 0; ch < numChannels; ++ch)
385 channelPtrs_[ch] = reinterpret_cast<T*>(base + stride * static_cast<std::size_t>(ch));
386
387 // Nullify unused channels for safety
388 for (int ch = numChannels; ch < MaxChannels; ++ch)
389 channelPtrs_[ch] = nullptr;
390
391 clear(); // Guarantees padding zeroing for SIMD safety
392 }
393
394 // -- View creation -------------------------------------------------------
395
401 {
402 return { channelPtrs_.data(), numChannels_, numSamples_ };
403 }
404
406 [[nodiscard]] AudioBufferView<const T, MaxChannels> toView() const noexcept
407 {
408 return { channelPtrs_.data(), numChannels_, numSamples_ };
409 }
410
411 // -- Accessors -----------------------------------------------------------
412
414 [[nodiscard]] T* getChannel(int ch) noexcept
415 {
416 assert(ch >= 0 && ch < numChannels_);
417 return channelPtrs_[ch];
418 }
419
421 [[nodiscard]] const T* getChannel(int ch) const noexcept
422 {
423 assert(ch >= 0 && ch < numChannels_);
424 return channelPtrs_[ch];
425 }
426
428 [[nodiscard]] int getNumChannels() const noexcept { return numChannels_; }
429
431 [[nodiscard]] int getNumSamples() const noexcept { return numSamples_; }
432
433 // -- Operations ----------------------------------------------------------
434
439 void clear() noexcept
440 {
441 // Degenerate sizes (0 samples or 0 channels) own no storage at all;
442 // memset on a null pointer is undefined even with a zero length.
443 if (rawData_ == nullptr) return;
444 for (int ch = 0; ch < numChannels_; ++ch)
445 std::memset(channelPtrs_[ch], 0, strideBytes_);
446 }
447
448private:
450 [[noreturn]] static void failAllocation()
451 {
452#if defined(__cpp_exceptions) || defined(_CPPUNWIND)
453 throw std::bad_alloc();
454#else
455 std::abort();
456#endif
457 }
458
459 void deallocate() noexcept
460 {
461 if (rawData_)
462 {
463 ::operator delete(rawData_, std::align_val_t(kAlignment));
464 rawData_ = nullptr;
465 }
466 // Keep the capacity coherent with the (now absent) allocation. If
467 // resize()'s operator new throws after this call, a stale capacity
468 // would make a later, smaller resize() skip its allocation and build
469 // channel pointers over a null base.
470 allocatedBytes_ = 0;
471 // Drop dangling channel views too: if operator new throws in resize()
472 // right after this call, channelPtrs_/numChannels_ would otherwise
473 // still describe the just-freed block, so a caller catching bad_alloc
474 // and calling getChannel()/toView() would read freed memory. Leave the
475 // object as a safely-empty buffer. The success path re-establishes
476 // these fields after a successful allocation.
477 channelPtrs_.fill(nullptr);
478 numChannels_ = 0;
479 numSamples_ = 0;
480 strideBytes_ = 0;
481 }
482
483 T* rawData_ = nullptr;
484 std::array<T*, MaxChannels> channelPtrs_ {};
485 int numChannels_ = 0;
486 int numSamples_ = 0;
487 std::size_t allocatedBytes_ = 0;
488 std::size_t strideBytes_ = 0;
489};
490
491} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
void clear() const noexcept
Fills the valid sample range of all channels with zeros.
int getNumSamples() const noexcept
Returns the number of samples per channel.
int getNumChannels() const noexcept
Returns the number of channels in this view.
AudioBufferView() noexcept=default
Creates an empty view (0 channels, 0 samples).
void addFrom(const AudioBufferView< U, M > &src, T gain=T(1)) const noexcept
Adds samples from a source view into this view with optional gain.
T * getChannel(int ch) const noexcept
Returns a pointer to the sample data for the given channel.
AudioBufferView(const AudioBufferView< U, OtherChannels > &other) noexcept
Converts compatible sample types and widens pointer-array capacity.
void copyFrom(const AudioBufferView< U, M > &src) const noexcept
Safely copies samples from a source view into this view.
AudioBufferView getSubView(int startSample, int length) const noexcept
Returns a zero-copy sub-view starting at an offset.
std::remove_const_t< T > getPeakLevel() const noexcept
Returns the peak absolute sample value across all channels.
void applyGain(T gain) const noexcept
Multiplies all samples in all valid channels by a gain factor.
Owning audio buffer with contiguous, 32-byte aligned storage.
AudioBuffer & operator=(const AudioBuffer &)=delete
AudioBufferView< T, MaxChannels > toView() noexcept
Returns a non-owning mutable view of this buffer. The view's channel capacity is propagated from MaxC...
int getNumChannels() const noexcept
Returns the number of active channels.
AudioBuffer(const AudioBuffer &)=delete
T * getChannel(int ch) noexcept
Returns a pointer to the sample data.
int getNumSamples() const noexcept
Returns the number of samples per channel.
AudioBufferView< const T, MaxChannels > toView() const noexcept
Returns a non-owning const view of this buffer.
AudioBuffer(AudioBuffer &&other) noexcept
C++20 idiomatic move constructor.
void resize(int numChannels, int numSamples)
Allocates the buffer for the given dimensions.
const T * getChannel(int ch) const noexcept
Const overload.
void clear() noexcept
Clears all channels, including SIMD alignment padding. Ensures any SIMD over-read will consume pure z...
AudioBuffer & operator=(AudioBuffer &&other) noexcept
C++20 idiomatic move assignment.
void addWithGain(float *DSPARK_RESTRICT dst, const float *DSPARK_RESTRICT src, float gain, int count) noexcept
Adds source samples scaled by a gain factor into a destination buffer.
Definition SimdOps.h:302
float peakLevel(const float *DSPARK_RESTRICT data, int count) noexcept
Returns the peak absolute sample value in a buffer.
Definition SimdOps.h:489
void applyGain(float *DSPARK_RESTRICT data, float gain, int count) noexcept
Multiplies all samples in a buffer by a gain factor.
Definition SimdOps.h:411
Main namespace for the DSPark framework.