DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
AnalogRandom.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
47#include <algorithm>
48#include <array>
49#include <atomic>
50#include <chrono>
51#include <cmath>
52#include <cstdint>
53#include <span>
54#include <type_traits>
55#include <utility>
56
57#include "AnalogConstants.h"
58
63namespace dspark
64{
69 namespace AnalogRandom
70 {
71 //==============================================================================
72 // PRNG and Internal Details
73 // (Reference constants live in Core/AnalogConstants.h, included above.)
74 //==============================================================================
75 namespace Detail
76 {
82 {
83 std::uint64_t s[4];
84
85 explicit Xoshiro256pp(std::uint64_t seed = 1) noexcept
86 {
87 reseed(seed);
88 }
89
90 void reseed(std::uint64_t seed) noexcept
91 {
92 if (seed == 0) seed = 1;
93 s[0] = splitmix64(seed + 0x9E3779B97F4A7C15ull);
94 s[1] = splitmix64(s[0]);
95 s[2] = splitmix64(s[1]);
96 s[3] = splitmix64(s[2]);
97 }
98
99 [[nodiscard]] std::uint64_t next() noexcept
100 {
101 const std::uint64_t result = rotl(s[0] + s[3], 23) + s[0];
102 const std::uint64_t t = s[1] << 17;
103 s[2] ^= s[0];
104 s[3] ^= s[1];
105 s[1] ^= s[2];
106 s[0] ^= s[3];
107 s[2] ^= t;
108 s[3] = rotl(s[3], 45);
109 return result;
110 }
111
112 [[nodiscard]] double next_double() noexcept
113 {
114 const std::uint64_t x = next();
115 constexpr double inv2pow53 = 1.0 / 9007199254740992.0;
116 return static_cast<double>(x >> 11) * inv2pow53;
117 }
118
119 private:
120 static std::uint64_t rotl(std::uint64_t x, int k) noexcept
121 {
122 return (x << k) | (x >> (64 - k));
123 }
124
125 static std::uint64_t splitmix64(std::uint64_t x) noexcept
126 {
127 x += 0x9E3779B97F4A7C15ull;
128 x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ull;
129 x = (x ^ (x >> 27)) * 0x94D049BB133111EBull;
130 return x ^ (x >> 31);
131 }
132 };
133
134 // NOTE: lock-free safety is checked at runtime per Generator instance
135 // (checkLockFree() -> isSafeToRun_). A preprocessor #warning here would
136 // fire on every translation unit unconditionally (the directive ignores
137 // the runtime `if`), so it is intentionally omitted.
138 }
139
140 //==============================================================================
141 // Public API
142 //==============================================================================
143
148 enum class NoiseType
149 {
150 Pink,
151 Brown,
152 White
153 };
154
161
166
172 template <typename Real = float>
174 {
175 static_assert(std::is_floating_point_v<Real>,
176 "AnalogRandom::Generator requires a floating-point Real type.");
177
178 public:
179 Generator() noexcept : prng_(generateUniqueSeed())
180 {
181 checkLockFree();
182 }
183
184 explicit Generator(std::uint64_t seed) noexcept : prng_(seed)
185 {
186 checkLockFree();
187 }
188
189 // std::atomic members are not move-constructible by default, but we
190 // own this Generator's state and need it to be storable in standard
191 // containers (e.g. std::vector). The atomic loads/stores below are
192 // safe because the source object is being moved-from; by contract
193 // it is not concurrently observed by any other thread.
194 Generator(Generator&& other) noexcept
195 : isSafeToRun_(other.isSafeToRun_),
196 prng_(other.prng_),
197 sampleRate_(other.sampleRate_),
198 phaseAccumulator_(other.phaseAccumulator_),
199 triggerNext_(other.triggerNext_),
200 currentValue_(other.currentValue_),
201 targetValue_(other.targetValue_),
202 noiseType_(other.noiseType_.load(std::memory_order_relaxed)),
203 useBpmSync_(other.useBpmSync_.load(std::memory_order_relaxed)),
204 rateHz_(other.rateHz_.load(std::memory_order_relaxed)),
205 bpm_(other.bpm_.load(std::memory_order_relaxed)),
206 bpmDivision_(other.bpmDivision_.load(std::memory_order_relaxed)),
207 min_(other.min_.load(std::memory_order_relaxed)),
208 max_(other.max_.load(std::memory_order_relaxed)),
209 smoothingEnabled_(other.smoothingEnabled_.load(std::memory_order_relaxed)),
210 smoothingCoeff_(other.smoothingCoeff_.load(std::memory_order_relaxed)),
211 smoothingTimeMs_(other.smoothingTimeMs_.load(std::memory_order_relaxed)),
212 quantizationStep_(other.quantizationStep_.load(std::memory_order_relaxed)),
213 pendingSeed_(other.pendingSeed_.load(std::memory_order_relaxed)),
214 publishedValue_(other.publishedValue_.load(std::memory_order_relaxed)),
215 publishedPhase_(other.publishedPhase_.load(std::memory_order_relaxed)),
216 brownNoiseState_(other.brownNoiseState_),
217 pinkNoiseOctaves_(other.pinkNoiseOctaves_),
218 denormalFlip_(other.denormalFlip_)
219 {
220 }
221
222 Generator& operator=(Generator&& other) noexcept
223 {
224 if (this == &other) return *this;
225 isSafeToRun_ = other.isSafeToRun_;
226 prng_ = other.prng_;
227 sampleRate_ = other.sampleRate_;
228 phaseAccumulator_ = other.phaseAccumulator_;
229 triggerNext_ = other.triggerNext_;
230 currentValue_ = other.currentValue_;
231 targetValue_ = other.targetValue_;
232 noiseType_.store (other.noiseType_.load(std::memory_order_relaxed), std::memory_order_relaxed);
233 useBpmSync_.store (other.useBpmSync_.load(std::memory_order_relaxed), std::memory_order_relaxed);
234 rateHz_.store (other.rateHz_.load(std::memory_order_relaxed), std::memory_order_relaxed);
235 bpm_.store (other.bpm_.load(std::memory_order_relaxed), std::memory_order_relaxed);
236 bpmDivision_.store(other.bpmDivision_.load(std::memory_order_relaxed), std::memory_order_relaxed);
237 min_.store (other.min_.load(std::memory_order_relaxed), std::memory_order_relaxed);
238 max_.store (other.max_.load(std::memory_order_relaxed), std::memory_order_relaxed);
239 smoothingEnabled_.store(other.smoothingEnabled_.load(std::memory_order_relaxed), std::memory_order_relaxed);
240 smoothingCoeff_.store (other.smoothingCoeff_.load(std::memory_order_relaxed), std::memory_order_relaxed);
241 smoothingTimeMs_.store (other.smoothingTimeMs_.load(std::memory_order_relaxed), std::memory_order_relaxed);
242 quantizationStep_.store(other.quantizationStep_.load(std::memory_order_relaxed), std::memory_order_relaxed);
243 pendingSeed_.store(other.pendingSeed_.load(std::memory_order_relaxed), std::memory_order_relaxed);
244 publishedValue_.store(other.publishedValue_.load(std::memory_order_relaxed), std::memory_order_relaxed);
245 publishedPhase_.store(other.publishedPhase_.load(std::memory_order_relaxed), std::memory_order_relaxed);
246 brownNoiseState_ = other.brownNoiseState_;
247 pinkNoiseOctaves_ = other.pinkNoiseOctaves_;
248 denormalFlip_ = other.denormalFlip_;
249 return *this;
250 }
251
252 // Copy operations stay deleted: the atomics make a meaningful copy
253 // semantically ambiguous (concurrent observers of the source) and
254 // we don't need them.
255 Generator(const Generator&) = delete;
256 Generator& operator=(const Generator&) = delete;
257
262 void prepare(double sampleRate) noexcept
263 {
264 if (sampleRate > 0.0 && std::isfinite(sampleRate)) sampleRate_ = sampleRate;
265 // The smoothing time is a time: re-derive its per-sample
266 // coefficient for this rate (setSmoothing() is usually called
267 // before prepare(), e.g. through setAnalogDefault()).
268 updateSmoothingCoeff();
269 reset();
270 }
271
275 void reset() noexcept
276 {
277 phaseAccumulator_ = 0.0;
278 triggerNext_ = true;
279 currentValue_ = static_cast<Real>(0);
280 targetValue_ = static_cast<Real>(0);
281 brownNoiseState_ = static_cast<Real>(0);
282 pinkNoiseOctaves_.fill(static_cast<Real>(0));
283 publishedValue_.store(static_cast<Real>(0), std::memory_order_relaxed);
284 publishedPhase_.store(static_cast<Real>(0), std::memory_order_relaxed);
285 }
286
291 void reseed(std::uint64_t newSeed) noexcept
292 {
293 if (newSeed == 0) newSeed = 1;
294 pendingSeed_.store(newSeed, std::memory_order_release);
295 }
296
297 //----------------------------------------------------------------------
298 // Main audio API
299 //----------------------------------------------------------------------
300
306 [[nodiscard]] Real getNextSample() noexcept
307 {
308 if (!isSafeToRun_) [[unlikely]] return static_cast<Real>(0);
309
310 // Relaxed load first: the exchange (a locked read-modify-write)
311 // only runs when a reseed was actually published.
312 const auto pending = pendingSeed_.load(std::memory_order_relaxed) != 0
313 ? pendingSeed_.exchange(0, std::memory_order_acq_rel) : std::uint64_t { 0 };
314 if (pending != 0)
315 {
316 prng_.reseed(pending);
317 reset();
318 }
319
320 updatePhase();
321
322 if (std::exchange(triggerNext_, false))
323 {
324 generateNewTarget(tickColoredNoise(noiseType_.load(std::memory_order_relaxed)));
325 }
326
327 if (smoothingEnabled_.load(std::memory_order_relaxed))
328 {
329 const Real coeff = smoothingCoeff_.load(std::memory_order_relaxed);
330 currentValue_ += coeff * (targetValue_ - currentValue_);
331 }
332 else
333 {
334 currentValue_ = targetValue_;
335 }
336
337 // Professional DC-free denormal mitigation
338 denormalFlip_ = -denormalFlip_;
339 currentValue_ += denormalFlip_;
340
341 // Publish the readout words for getCurrentValue()/getPhase()
342 // (relaxed atomic stores: a plain MOV on x86/ARM64; the
343 // cross-thread read of the previous plain members was a data
344 // race -- undefined behaviour, not merely a stale read).
345 publishedValue_.store(currentValue_, std::memory_order_relaxed);
346 publishedPhase_.store(static_cast<Real>(phaseAccumulator_),
347 std::memory_order_relaxed);
348
349 return currentValue_;
350 }
351
357 void getNextBlock(std::span<Real> outputBuffer) noexcept
358 {
359 if (!isSafeToRun_ || outputBuffer.empty()) [[unlikely]] return;
360
361 const auto pending = pendingSeed_.load(std::memory_order_relaxed) != 0
362 ? pendingSeed_.exchange(0, std::memory_order_acq_rel) : std::uint64_t { 0 };
363 if (pending != 0)
364 {
365 prng_.reseed(pending);
366 reset();
367 }
368
369 // Cache atomics to local registers for the block duration
370 const bool smoothing = smoothingEnabled_.load(std::memory_order_relaxed);
371 const Real coeff = smoothingCoeff_.load(std::memory_order_relaxed);
372 const NoiseType noiseType = noiseType_.load(std::memory_order_relaxed);
373 const Real quantStep = quantizationStep_.load(std::memory_order_relaxed);
374 Real currentMin = min_.load(std::memory_order_relaxed);
375 Real currentMax = max_.load(std::memory_order_relaxed);
376
377 if (currentMin > currentMax) std::swap(currentMin, currentMax);
378
379 for (Real& sample : outputBuffer)
380 {
381 updatePhase();
382
383 if (std::exchange(triggerNext_, false))
384 {
385 // Clamp to [-1,1] before mapping, matching generateNewTarget()
386 // (pink noise can momentarily exceed unity).
387 const Real cn = std::clamp(tickColoredNoise(noiseType),
388 static_cast<Real>(-1), static_cast<Real>(1));
389 targetValue_ = currentMin + ((cn * static_cast<Real>(0.5)) + static_cast<Real>(0.5)) * (currentMax - currentMin);
390 if (quantStep > static_cast<Real>(0)) targetValue_ = std::round(targetValue_ / quantStep) * quantStep;
391 }
392
393 if (smoothing)
394 {
395 currentValue_ += coeff * (targetValue_ - currentValue_);
396 }
397 else
398 {
399 currentValue_ = targetValue_;
400 }
401
402 denormalFlip_ = -denormalFlip_;
403 currentValue_ += denormalFlip_;
404
405 sample = currentValue_;
406 }
407
408 // Publish the readout words once per block (block-boundary
409 // granularity is the documented readout resolution here; the
410 // per-sample loop above stays free of atomic stores).
411 publishedValue_.store(currentValue_, std::memory_order_relaxed);
412 publishedPhase_.store(static_cast<Real>(phaseAccumulator_),
413 std::memory_order_relaxed);
414 }
415
419 [[nodiscard]] Real getCurrentValue() const noexcept
420 {
421 return publishedValue_.load(std::memory_order_relaxed);
422 }
423
428 [[nodiscard]] Real getPhase() const noexcept
429 {
430 return publishedPhase_.load(std::memory_order_relaxed);
431 }
432
433 //----------------------------------------------------------------------
434 // Configuration API
435 //----------------------------------------------------------------------
436
437 void setNoiseType(NoiseType type) noexcept
438 {
439 noiseType_.store(type, std::memory_order_relaxed);
440 }
441
445 void setRateHz(Real rateInHz) noexcept
446 {
447 if (!std::isfinite(rateInHz)) return;
448 useBpmSync_.store(false, std::memory_order_relaxed);
449 rateHz_.store(static_cast<float>(rateInHz), std::memory_order_relaxed);
450 }
451
452 void setRateBPM(double bpm, BpmDivision division) noexcept
453 {
454 if (!std::isfinite(bpm)) return;
455 bpm_.store(static_cast<float>(bpm), std::memory_order_relaxed);
456 bpmDivision_.store(division, std::memory_order_relaxed);
457 useBpmSync_.store(true, std::memory_order_relaxed);
458 }
459
460 void updateBPM(double newBpm) noexcept
461 {
462 if (!std::isfinite(newBpm)) return;
463 bpm_.store(static_cast<float>(newBpm), std::memory_order_relaxed);
464 }
465
469 template <typename T>
470 void setRange(T min, T max) noexcept
471 {
472 static_assert(std::is_floating_point_v<T>, "setRange only accepts floating-point types.");
473 // A NaN bound reached the smoothed output and stayed there.
474 if (!std::isfinite(min) || !std::isfinite(max)) return;
475 if (min > max) std::swap(min, max);
476 min_.store(static_cast<Real>(min), std::memory_order_relaxed);
477 max_.store(static_cast<Real>(max), std::memory_order_relaxed);
478 }
479
487 void setSmoothing(bool shouldBeEnabled, Real timeInMs = static_cast<Real>(50.0)) noexcept
488 {
489 smoothingEnabled_.store(shouldBeEnabled, std::memory_order_relaxed);
490 smoothingTimeMs_.store(timeInMs > static_cast<Real>(0) ? static_cast<double>(timeInMs) : 0.0,
491 std::memory_order_relaxed);
492 updateSmoothingCoeff();
493 }
494
495 void setQuantization(Real step) noexcept
496 {
497 // An infinite step made every target 0 * inf = NaN.
498 if (!std::isfinite(step) || step < static_cast<Real>(0)) step = static_cast<Real>(0);
499 quantizationStep_.store(step, std::memory_order_relaxed);
500 }
501
502 void setAnalogDefault(AnalogComponent component) noexcept
503 {
504 switch (component)
505 {
509 setRateHz(0.5f);
510 setSmoothing(true, 100.0f);
511 break;
515 setRateHz(2.0f);
516 setSmoothing(true, 50.0f);
517 break;
521 setRateHz(1.0f);
522 setSmoothing(true, 75.0f);
523 break;
527 setRateHz(1.5f);
528 setSmoothing(true, 80.0f);
529 break;
533 setRateHz(0.8f);
534 setSmoothing(true, 120.0f);
535 break;
536 }
537 }
538
539 template <typename Int>
540 [[nodiscard]] Int getNextDiscrete(Int imin, Int imax) noexcept
541 {
542 static_assert(std::is_integral_v<Int>, "getNextDiscrete requires an integral type.");
543 if (imax <= imin) return imin;
544 const Real value = getNextSample();
545
546 Real minVal = min_.load(std::memory_order_relaxed);
547 Real maxVal = max_.load(std::memory_order_relaxed);
548 if (minVal > maxVal) std::swap(minVal, maxVal);
549 if (maxVal == minVal) return imin;
550
551 const double t = static_cast<double>((value - minVal) / (maxVal - minVal));
552 // The span in double: imax - imin overflowed Int (undefined)
553 // for full-range requests and returned imin every time.
554 const double span = static_cast<double>(imax) - static_cast<double>(imin);
555 const double mapped = t * span + static_cast<double>(imin);
556 // llround/long long, not lround/long: on LLP64 platforms
557 // (Windows) long is 32-bit and would truncate 64-bit Int.
558 return static_cast<Int>(std::clamp(std::llround(mapped),
559 static_cast<long long>(imin),
560 static_cast<long long>(imax)));
561 }
562
563 [[nodiscard]] int getNextDiscreteInt(int imin, int imax) noexcept
564 {
565 return static_cast<int>(getNextDiscrete<int>(imin, imax));
566 }
567
568 private:
569 void checkLockFree() noexcept
570 {
571 // Guard against the atomics this class actually uses. On every
572 // supported platform these are all lock-free; a hypothetical
573 // platform where they are not degrades to silence instead of
574 // risking a blocking atomic on the audio thread.
575 isSafeToRun_ = std::atomic<Real>::is_always_lock_free
576 && std::atomic<float>::is_always_lock_free
577 && std::atomic<std::uint64_t>::is_always_lock_free
578 && std::atomic<double>::is_always_lock_free
579 && std::atomic<NoiseType>::is_always_lock_free
580 && std::atomic<BpmDivision>::is_always_lock_free
581 && std::atomic<bool>::is_always_lock_free;
582 }
583
585 void updateSmoothingCoeff() noexcept
586 {
587 const double timeMs = smoothingTimeMs_.load(std::memory_order_relaxed);
588 // A zero smoothing time means instantaneous. Keeping a previous
589 // coefficient here (possibly 0) would silently freeze the output
590 // short of every new target while smoothing is enabled.
591 const double coeff = (timeMs > 0.0)
592 ? 1.0 - std::exp(-1.0 / (sampleRate_ * timeMs / 1000.0))
593 : 1.0;
594 smoothingCoeff_.store(static_cast<Real>(coeff), std::memory_order_relaxed);
595 }
596
602 [[nodiscard]] Real tickColoredNoise(NoiseType type) noexcept
603 {
604 const Real white = static_cast<Real>(prng_.next_double() * 2.0 - 1.0);
605 switch (type)
606 {
607 case NoiseType::White: return white;
608 case NoiseType::Pink: return tickPinkNoise(white);
609 case NoiseType::Brown: return tickBrownNoise(white);
610 default: return white;
611 }
612 }
613
617 void generateNewTarget(Real sampledNoise) noexcept
618 {
619 sampledNoise = std::clamp(sampledNoise, static_cast<Real>(-1), static_cast<Real>(1));
620
621 Real currentMin = min_.load(std::memory_order_relaxed);
622 Real currentMax = max_.load(std::memory_order_relaxed);
623 if (currentMin > currentMax) std::swap(currentMin, currentMax);
624
625 targetValue_ = currentMin + ((sampledNoise * static_cast<Real>(0.5)) + static_cast<Real>(0.5)) * (currentMax - currentMin);
626
627 const Real quantStep = quantizationStep_.load(std::memory_order_relaxed);
628 if (quantStep > static_cast<Real>(0))
629 {
630 targetValue_ = std::round(targetValue_ / quantStep) * quantStep;
631 }
632 }
633
634 void updatePhase() noexcept
635 {
636 Real rate = static_cast<Real>(0);
637 if (useBpmSync_.load(std::memory_order_relaxed))
638 {
639 const float bpm = bpm_.load(std::memory_order_relaxed);
640 if (bpm > 0.0f)
641 {
642 const double noteLengthInBeats = 4.0 / getBpmDivisionMultiplier(bpmDivision_.load(std::memory_order_relaxed));
643 const double periodInSeconds = (60.0 / static_cast<double>(bpm)) * noteLengthInBeats;
644 if (periodInSeconds > 0.0) rate = static_cast<Real>(1.0 / periodInSeconds);
645 }
646 }
647 else
648 {
649 rate = static_cast<Real>(rateHz_.load(std::memory_order_relaxed));
650 }
651
652 if (rate <= static_cast<Real>(0)) return;
653
654 phaseAccumulator_ += static_cast<double>(rate) / sampleRate_;
655 if (phaseAccumulator_ >= 1.0)
656 {
657 // floor(), not a single -1.0: with rates at or above the
658 // sample rate the fixed decrement would let the
659 // accumulator grow without bound.
660 phaseAccumulator_ -= std::floor(phaseAccumulator_);
661 triggerNext_ = true;
662 }
663 }
664
665 [[nodiscard]] Real tickPinkNoise(Real white) noexcept
666 {
667 // Paul Kellett's refined 7-state pink-noise filter (public-domain
668 // "instrumentation-grade" variant): parallel one-pole bank whose
669 // summed response tracks -3 dB/oct across the audio band to
670 // within ~0.5 dB. The previous 3-pole truncation measured ~-5
671 // dB/oct, violating the documented pink slope.
672 Real b0 = pinkNoiseOctaves_[0];
673 Real b1 = pinkNoiseOctaves_[1];
674 Real b2 = pinkNoiseOctaves_[2];
675 Real b3 = pinkNoiseOctaves_[3];
676 Real b4 = pinkNoiseOctaves_[4];
677 Real b5 = pinkNoiseOctaves_[5];
678 Real b6 = pinkNoiseOctaves_[6];
679
680 b0 = static_cast<Real>(0.99886) * b0 + white * static_cast<Real>(0.0555179);
681 b1 = static_cast<Real>(0.99332) * b1 + white * static_cast<Real>(0.0750759);
682 b2 = static_cast<Real>(0.96900) * b2 + white * static_cast<Real>(0.1538520);
683 b3 = static_cast<Real>(0.86650) * b3 + white * static_cast<Real>(0.3104856);
684 b4 = static_cast<Real>(0.55000) * b4 + white * static_cast<Real>(0.5329522);
685 b5 = static_cast<Real>(-0.7616) * b5 - white * static_cast<Real>(0.0168980);
686
687 const Real pink = b0 + b1 + b2 + b3 + b4 + b5 + b6
688 + white * static_cast<Real>(0.5362);
689
690 pinkNoiseOctaves_[0] = b0;
691 pinkNoiseOctaves_[1] = b1;
692 pinkNoiseOctaves_[2] = b2;
693 pinkNoiseOctaves_[3] = b3;
694 pinkNoiseOctaves_[4] = b4;
695 pinkNoiseOctaves_[5] = b5;
696 pinkNoiseOctaves_[6] = white * static_cast<Real>(0.115926);
697
698 // Normalisation keeps the peak below unity for white in [-1,1].
699 // The peak grows with run length; measured worst case ~0.90 over
700 // 2^21 samples (RMS ~0.19), leaving headroom to full scale.
701 return pink * static_cast<Real>(0.11);
702 }
703
704 [[nodiscard]] Real tickBrownNoise(Real white) noexcept
705 {
706 brownNoiseState_ += white * static_cast<Real>(0.02);
707 brownNoiseState_ *= static_cast<Real>(0.995);
708 brownNoiseState_ = std::clamp(brownNoiseState_, static_cast<Real>(-1.0), static_cast<Real>(1.0));
709 return brownNoiseState_;
710 }
711
712 [[nodiscard]] static constexpr double getBpmDivisionMultiplier(BpmDivision division) noexcept
713 {
714 switch (division)
715 {
716 case BpmDivision::One: return 4.0;
717 case BpmDivision::Half: return 2.0;
718 case BpmDivision::Quarter: return 1.0;
719 case BpmDivision::Eighth: return 0.5;
720 case BpmDivision::Sixteenth: return 0.25;
721 case BpmDivision::ThirtySecond: return 0.125;
722 case BpmDivision::HalfTriplet: return 4.0 / 3.0;
723 case BpmDivision::QuarterTriplet: return 2.0 / 3.0;
724 case BpmDivision::EighthTriplet: return 1.0 / 3.0;
725 case BpmDivision::SixteenthTriplet: return 1.0 / 6.0;
726 case BpmDivision::DottedHalf: return 3.0;
727 case BpmDivision::DottedQuarter: return 1.5;
728 case BpmDivision::DottedEighth: return 0.75;
729 default: return 1.0;
730 }
731 }
732
733 [[nodiscard]] static std::uint64_t generateUniqueSeed() noexcept
734 {
735 static std::atomic_uint64_t instanceCounter{ 0 };
736 const auto instanceId = instanceCounter.fetch_add(1, std::memory_order_relaxed);
737 const auto thisPtrAddress = reinterpret_cast<std::uintptr_t>(&instanceCounter);
738 const auto now = static_cast<std::uint64_t>(std::chrono::steady_clock::now().time_since_epoch().count());
739 std::uint64_t seed = instanceId ^ (thisPtrAddress << 1) ^ (now + 0x9E3779B97F4A7C15ull);
740 return seed == 0 ? 1 : seed;
741 }
742
743 bool isSafeToRun_{ false };
744 Detail::Xoshiro256pp prng_;
745 double sampleRate_{ 44100.0 };
746 double phaseAccumulator_{ 0.0 };
747 // Written and read only by the stream owner (updatePhase(),
748 // reset(), the generation calls): a plain flag. It used to be an
749 // atomic exchanged on every sample, a locked read-modify-write
750 // that cost more than the generation itself.
751 bool triggerNext_{ true };
752 Real currentValue_{ static_cast<Real>(0) };
753 Real targetValue_{ static_cast<Real>(0) };
754 std::atomic<NoiseType> noiseType_{ NoiseType::Pink };
755 std::atomic<bool> useBpmSync_{ false };
756 std::atomic<float> rateHz_{ 1.0f };
757 std::atomic<float> bpm_{ 120.0f };
758 std::atomic<BpmDivision> bpmDivision_{ BpmDivision::Quarter };
759 // Value-domain atomics use Real: with Real = double, storing them
760 // as float would silently round the user's range/quantization.
761 // Time-domain ones (rateHz_, bpm_) stay float on purpose.
762 std::atomic<Real> min_{ static_cast<Real>(-1) };
763 std::atomic<Real> max_{ static_cast<Real>(1) };
764 std::atomic<bool> smoothingEnabled_{ false };
765 std::atomic<Real> smoothingCoeff_{ static_cast<Real>(1) };
766 std::atomic<double> smoothingTimeMs_{ 0.0 };
767 std::atomic<Real> quantizationStep_{ static_cast<Real>(0) };
768 std::atomic<std::uint64_t> pendingSeed_{ 0 };
769 // Cross-thread READOUT words (each a single independent
770 // word): the generator thread publishes them with relaxed
771 // stores (once per getNextSample() call, and once per
772 // block in getNextBlock()); getCurrentValue()/getPhase() load
773 // them relaxed from any thread. The plain working members
774 // (currentValue_, phaseAccumulator_) stay audio-thread-private,
775 // so the hot recursion is untouched. No invariant couples the
776 // two words, so no seqlock is required.
777 std::atomic<Real> publishedValue_{ static_cast<Real>(0) };
778 std::atomic<Real> publishedPhase_{ static_cast<Real>(0) };
779 Real brownNoiseState_{ static_cast<Real>(0) };
780 std::array<Real, 7> pinkNoiseOctaves_{};
781 Real denormalFlip_{ static_cast<Real>(1e-18) }; // DC-Free denormal mitigation state
782 };
783 } // namespace AnalogRandom
784} // namespace dspark
Main generator class for analog-style random modulation.
void reset() noexcept
Reset internal state (phase, smoothing, noise states).
void setRateBPM(double bpm, BpmDivision division) noexcept
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 setNoiseType(NoiseType type) noexcept
int getNextDiscreteInt(int imin, int imax) noexcept
void setSmoothing(bool shouldBeEnabled, Real timeInMs=static_cast< Real >(50.0)) noexcept
Enables one-pole smoothing of the held targets.
void reseed(std::uint64_t newSeed) noexcept
Request a lock-free reseed of the internal PRNG.
Int getNextDiscrete(Int imin, Int imax) noexcept
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.
Generator(const Generator &)=delete
Generator & operator=(const Generator &)=delete
Generator(Generator &&other) noexcept
void getNextBlock(std::span< Real > outputBuffer) noexcept
Generate a block of modulation samples.
Real getCurrentValue() const noexcept
Last published output value. Lock-free readout, any thread (relaxed atomic; updated once per getNextS...
Real getPhase() const noexcept
Last published LFO phase in [0, 1). Lock-free readout, any thread (relaxed atomic; same publication p...
void setQuantization(Real step) noexcept
void setAnalogDefault(AnalogComponent component) noexcept
Real getNextSample() noexcept
Generate and return the next modulation sample.
Generator(std::uint64_t seed) noexcept
Generator & operator=(Generator &&other) noexcept
void updateBPM(double newBpm) noexcept
Parametric multi-band EQ using cascaded biquads or FFT overlap-save convolution.
Definition Equalizer.h:145
Main namespace for the analog random generation library.
NoiseType
Defines the spectral distribution of the random fluctuations.
@ White
Uncorrelated noise for "sample-and-hold" effects.
@ Pink
1/f noise for organic drift.
@ Brown
1/f^2 noise for slow "wow/flutter".
Main namespace for the DSPark framework.
A compact xoshiro256++ PRNG implementation (non-threadsafe).
void reseed(std::uint64_t seed) noexcept
Xoshiro256pp(std::uint64_t seed=1) noexcept