noise.hpp (2339B)
1 #pragma once 2 3 #include <random> 4 5 #include "base.hpp" 6 #include "filters/filter.hpp" 7 8 namespace bogaudio { 9 namespace dsp { 10 11 class Seeds { 12 private: 13 std::mt19937 _generator; 14 Seeds(); 15 unsigned int _next(); 16 17 public: 18 Seeds(const Seeds&) = delete; 19 void operator=(const Seeds&) = delete; 20 static Seeds& getInstance(); 21 22 static unsigned int next(); 23 }; 24 25 struct NoiseGenerator : Generator { 26 std::minstd_rand _generator; // one of the faster options. 27 28 NoiseGenerator() : _generator(Seeds::next()) {} 29 }; 30 31 struct WhiteNoiseGenerator : NoiseGenerator { 32 std::uniform_real_distribution<float> _uniform; 33 34 WhiteNoiseGenerator() : _uniform(-1.0, 1.0) {} 35 36 float _next() override { 37 return _uniform(_generator); 38 } 39 }; 40 41 template<typename G> 42 struct BasePinkNoiseGenerator : NoiseGenerator { 43 static const int _n = 7; 44 G _g; 45 G _gs[_n]; 46 uint32_t _count = _g.next(); 47 48 float _next() override { 49 // See: http://www.firstpr.com.au/dsp/pink-noise/ 50 float sum = _g.next(); 51 for (int i = 0, bit = 1; i < _n; ++i, bit <<= 1) { 52 if (_count & bit) { 53 sum += _gs[i].next(); 54 } 55 else { 56 sum += _gs[i].current(); 57 } 58 } 59 ++_count; 60 return sum / (float)(_n + 1); 61 } 62 }; 63 64 struct PinkNoiseGenerator : BasePinkNoiseGenerator<WhiteNoiseGenerator> {}; 65 66 struct RedNoiseGenerator : BasePinkNoiseGenerator<PinkNoiseGenerator> {}; 67 68 struct BlueNoiseGenerator : NoiseGenerator { 69 PinkNoiseGenerator _pink; 70 float _last = 0.0f; 71 72 float _next() override { 73 float t = _last; 74 _last = _pink.next(); 75 return _last - t; 76 } 77 }; 78 79 struct GaussianNoiseGenerator : NoiseGenerator { 80 std::normal_distribution<float> _normal; 81 82 GaussianNoiseGenerator(float mean = 0.0f, float stdDev = 1.0f) : _normal(mean, stdDev) {} 83 84 float _next() override { 85 return _normal(_generator); 86 } 87 }; 88 89 struct RandomWalk : Generator { 90 float _min; 91 float _max; 92 float _last = 0.0f; 93 float _lastOut = 0.0f; 94 float _damp; 95 float _bias = 0.0f; 96 float _biasDamp = 1.0f; 97 WhiteNoiseGenerator _noise; 98 LowPassFilter _filter; 99 100 RandomWalk( 101 float min = -5.0f, 102 float max = 5.0f, 103 float sampleRate = 1000.0f, 104 float change = 0.5f 105 ) 106 : _min(min) 107 , _max(max) 108 { 109 assert(_min < _max); 110 setParams(sampleRate, change); 111 } 112 113 void setParams(float sampleRate = 1000.0f, float change = 0.5f); 114 void jump(); 115 void tell(float v); 116 float _next() override; 117 }; 118 119 } // namespace dsp 120 } // namespace bogaudio