DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
NoiseGenerator.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
38#include "../Core/AnalogRandom.h"
39#include "../Core/AudioBuffer.h"
40#include "../Core/AudioSpec.h"
41#include "../Core/DspMath.h"
42#include "../Core/StateBlob.h"
43
44#include <algorithm>
45#include <atomic>
46#include <cmath>
47#include <cstddef>
48#include <cstdint>
49#include <utility>
50#include <vector>
51
52namespace dspark {
53
64template <FloatType T>
66{
67public:
68 enum class Type
69 {
70 White,
71 Pink,
72 Brown
73 };
74
83 void prepare(const AudioSpec& spec)
84 {
85 if (!spec.isValid()) return; // release-safe: keep previous state
86
87 sampleRate_ = spec.sampleRate;
88 int targetChannels = spec.numChannels;
89
90 generators_.clear();
91 generators_.reserve(static_cast<size_t>(targetChannels));
92 brownState_.assign(static_cast<size_t>(targetChannels), T(0));
93
94 // Brown: y = (y + c * w) * a per sample. At 48 kHz a = 0.995 and
95 // c = 0.02 (the reference voicing: corner -ln(a) * fs / (2 pi) =
96 // 38.3 Hz); at other rates a keeps that corner in Hz and c keeps the
97 // output variance c^2 a^2 / (1 - a^2) unchanged.
98 constexpr double kLeak48k = 0.995;
99 const double a = std::pow(kLeak48k, 48000.0 / sampleRate_);
100 brownLeak_ = static_cast<T>(a);
101 brownGain_ = static_cast<T>(0.02 * (kLeak48k / a)
102 * std::sqrt((1.0 - a * a) / (1.0 - kLeak48k * kLeak48k)));
103
104 for (int ch = 0; ch < targetChannels; ++ch)
105 {
107 gen.prepare(sampleRate_);
108 gen.setRange(T(-1), T(1));
109 // A new value EVERY sample (rate == fs): full-bandwidth noise. A lower
110 // rate would sample-and-hold the source, giving a non-flat/imaged
111 // spectrum instead of true white/pink/brown.
112 gen.setRateHz(static_cast<T>(sampleRate_));
113 applyNoiseType(gen);
114
115 // Decorrelate output across channels
116 gen.reseed(static_cast<uint64_t>(ch + 1) * 0x9E3779B97F4A7C15ULL);
117 generators_.push_back(std::move(gen));
118 }
119
120 // Sync smoothing state to prevent ramp-up from zero on first block
121 currentGain_ = gain_.load(std::memory_order_relaxed);
122 }
123
132 void processBlock(AudioBufferView<T> buffer) noexcept
133 {
134 if (generators_.empty())
135 return;
136
137 if (typeDirty_.exchange(false, std::memory_order_acquire))
138 {
139 for (auto& gen : generators_)
140 applyNoiseType(gen);
141 }
142
143 const int numCh = std::min<int>(buffer.getNumChannels(), static_cast<int>(generators_.size()));
144 const int numSamples = buffer.getNumSamples();
145
146 if (numSamples <= 0 || numCh <= 0)
147 return;
148
149 const bool brown = type_.load(std::memory_order_relaxed) == Type::Brown;
150
151 // Block-level gain smoothing setup
152 const T targetGain = gain_.load(std::memory_order_relaxed);
153 const T startGain = currentGain_;
154 const bool needsSmoothing = std::abs(targetGain - startGain) > T(1e-6);
155 const T gainStep = needsSmoothing ? ((targetGain - startGain) / static_cast<T>(numSamples)) : T(0);
156
157 for (int ch = 0; ch < numCh; ++ch)
158 {
159 T* data = buffer.getChannel(ch);
160 auto& gen = generators_[static_cast<size_t>(ch)];
161
162 if (brown)
163 {
164 T y = brownState_[static_cast<size_t>(ch)];
165 T g = startGain;
166 for (int i = 0; i < numSamples; ++i)
167 {
168 y = std::clamp((y + gen.getNextSample() * brownGain_) * brownLeak_, T(-1), T(1));
169 g = needsSmoothing ? g + gainStep : targetGain;
170 data[i] = y * g;
171 }
172 brownState_[static_cast<size_t>(ch)] = y;
173 continue;
174 }
175
176 if (needsSmoothing)
177 {
178 T g = startGain;
179 for (int i = 0; i < numSamples; ++i)
180 {
181 g += gainStep;
182 data[i] = gen.getNextSample() * g;
183 }
184 }
185 else
186 {
187 for (int i = 0; i < numSamples; ++i)
188 {
189 data[i] = gen.getNextSample() * targetGain;
190 }
191 }
192 }
193
194 // Advance global smoothed state for the next block
195 currentGain_ = targetGain;
196 }
197
206 void reset() noexcept
207 {
208 int ch = 0;
209 for (auto& gen : generators_)
210 {
211 gen.reset();
212 gen.reseed(static_cast<uint64_t>(++ch) * 0x9E3779B97F4A7C15ULL);
213 }
214 std::fill(brownState_.begin(), brownState_.end(), T(0));
215
216 currentGain_ = gain_.load(std::memory_order_relaxed);
217 }
218
227 void setType(Type type) noexcept
228 {
229 // Wild enum values (a corrupted blob, a stray cast) clamp into range.
230 const int t = std::clamp(static_cast<int>(type), 0,
231 static_cast<int>(Type::Brown));
232 type_.store(static_cast<Type>(t), std::memory_order_relaxed);
233 typeDirty_.store(true, std::memory_order_release);
234 }
235
241 void setLevel(T levelDb) noexcept
242 {
243 if (std::isnan(levelDb) || levelDb > T(1e6)) return; // rejects +inf too
244 setGain(decibelsToGain(levelDb)); // -inf (<= -100 dB) maps to 0
245 }
246
252 void setGain(T gain) noexcept
253 {
254 if (!std::isfinite(gain)) return;
255 gain_.store(gain, std::memory_order_relaxed);
256 }
257
262 [[nodiscard]] Type getType() const noexcept
263 {
264 return type_.load(std::memory_order_relaxed);
265 }
266
271 [[nodiscard]] T getGain() const noexcept
272 {
273 return gain_.load(std::memory_order_relaxed);
274 }
275
276
278 [[nodiscard]] std::vector<uint8_t> getState() const
279 {
280 StateWriter w(stateId("NOIS"), 1);
281 // The blob stores float: the cast keeps NoiseGenerator<double> compiling.
282 w.write("gain", static_cast<float>(gain_.load(std::memory_order_relaxed)));
283 w.write("type", static_cast<int32_t>(type_.load(std::memory_order_relaxed)));
284 return w.blob();
285 }
286
288 bool setState(const uint8_t* data, size_t size)
289 {
290 StateReader r(data, size);
291 if (!r.isValid() || r.processorId() != stateId("NOIS")) return false;
292 setGain(static_cast<T>(r.read("gain", 1.0f)));
293 setType(static_cast<Type>(r.read("type", 0)));
294 return true;
295 }
296
297private:
298 void applyNoiseType(AnalogRandom::Generator<T>& gen) const noexcept
299 {
300 switch (type_.load(std::memory_order_relaxed))
301 {
302 case Type::White:
303 gen.setNoiseType(AnalogRandom::NoiseType::White);
304 break;
305 case Type::Pink:
306 gen.setNoiseType(AnalogRandom::NoiseType::Pink);
307 break;
308 case Type::Brown:
309 // The integration runs here, at a rate-independent corner.
310 gen.setNoiseType(AnalogRandom::NoiseType::White);
311 break;
312 }
313 }
314
315 double sampleRate_ = 44100.0;
316
317 // Core parameters (Thread-safe)
318 std::atomic<T> gain_ { T(1) };
319 std::atomic<Type> type_ { Type::White };
320 std::atomic<bool> typeDirty_ { false };
321
322 // Internal state (Audio thread only)
323 T currentGain_ { T(1) };
324
325 // Value semantics for memory locality. Avoids pointer chasing.
326 std::vector<AnalogRandom::Generator<T>> generators_;
327 std::vector<T> brownState_;
328 T brownLeak_ = T(0.995);
329 T brownGain_ = T(0.02);
330};
331
332} // namespace dspark
Main generator class for analog-style random modulation.
void setRateHz(Real rateInHz) noexcept
Free-running retrigger rate in Hz; non-finite values are ignored (a NaN or infinite rate froze the ph...
void reseed(std::uint64_t newSeed) noexcept
Request a lock-free reseed of the internal PRNG.
void prepare(double sampleRate) noexcept
Prepare the generator with the audio sample rate.
void setRange(T min, T max) noexcept
Set the output range for values. Safe from tearing.
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Generates decorellated noise (white, pink, brown) across multiple channels.
void setLevel(T levelDb) noexcept
Sets the output level in decibels. Thread-safe.
void reset() noexcept
Resets the internal PRNG and filter states.
void prepare(const AudioSpec &spec)
Prepares the noise generator and allocates internal state.
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
T getGain() const noexcept
Retrieves the current target gain in linear scale.
void setType(Type type) noexcept
Sets the noise spectrum type.
void setGain(T gain) noexcept
Sets the output level as linear gain. Thread-safe.
Type getType() const noexcept
Retrieves the currently requested noise type.
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
void processBlock(AudioBufferView< T > buffer) noexcept
Fills the buffer with generated noise.
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
Definition StateBlob.h:171
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
Definition StateBlob.h:214
bool isValid() const noexcept
Definition StateBlob.h:209
uint32_t processorId() const noexcept
Definition StateBlob.h:210
Serializes key/value parameters into a versioned blob.
Definition StateBlob.h:53
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
Definition StateBlob.h:112
void write(const char *key, float value)
Writes a float parameter.
Definition StateBlob.h:71
@ White
Uncorrelated noise for "sample-and-hold" effects.
@ Pink
1/f noise for organic drift.
Main namespace for the DSPark framework.
T decibelsToGain(T dB, T minusInfinityDb=T(-100)) noexcept
Converts a value in decibels to linear gain.
Definition DspMath.h:77
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Definition StateBlob.h:672
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
Definition AudioSpec.h:71
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
Definition AudioSpec.h:58
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45