-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSpectralGen.cpp
343 lines (300 loc) · 9.16 KB
/
SpectralGen.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//
// SpectralGen.cpp
// SpectralHarp
//
// Created by Damien Di Fede on 5/6/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#include "SpectralGen.h"
#include "FourierTransform.h"
#include <stdio.h>
#include <string> // for memset
#include <random>
SpectralGen::SpectralGen()
: UGen()
, decay( *this, CONTROL, 0 )
, brightness( *this, CONTROL, 0 )
, spread( *this, CONTROL, 0 )
, inverseSize(0)
, specSize(0)
, outputSize(0)
, outIndex(0)
, overlapSize(0)
, fft(nullptr)
, bands(nullptr)
, specSpread(nullptr)
, specMag(nullptr)
, specReal(nullptr)
, specImag(nullptr)
, inverse(nullptr)
, output(nullptr)
, phaseIdx(0)
{
}
SpectralGen::~SpectralGen()
{
cleanup();
}
void SpectralGen::reset()
{
// pick a buffer size based on sample rate.
// lower sample rate means shorter buffer, otherwise short decays will never be heard.
const int bufferSizeNP2 = (int)(sampleRate()*0.09f);
// find the nearest power of two greater than or equal to bufferSizeNP2
// so that our spectrum and overlap behave nicely.
int bufferSize = 32;
while (bufferSize < bufferSizeNP2) bufferSize <<= 1;
if (inverseSize != bufferSize)
{
cleanup();
inverseSize = bufferSize;
specSize = inverseSize / 2;
outputSize = inverseSize * 2;
overlapSize = inverseSize / 2;
fft = new Minim::FFT(inverseSize, sampleRate());
bands = new band[specSize];
specSpread = new float[specSize];
specMag = new float[specSize];
inverse = new float[inverseSize];
specReal = new float[inverseSize];
specImag = new float[inverseSize];
output = new float[outputSize];
}
// have to set the sample rate always
// because we may not have resized the buffers even though the sample rate changed.
fft->setSampleRate(sampleRate());
memset(specMag, 0, sizeof(float)*specSize);
memset(specSpread, 0, sizeof(float)*specSize);
memset(specReal, 0, sizeof(float)*inverseSize);
memset(specImag, 0, sizeof(float)*inverseSize);
memset(inverse, 0, sizeof(float)*inverseSize);
memset(output, 0, sizeof(float)*outputSize);
// we give each band a random phase to minimize interference
// when there are lots of active bands.
// ie this sounds nicer than if all bands start with a phase of 0.
std::random_device rd; //Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_real_distribution<> dis(0, M_PI*2);
for(int i = 0; i < specSize; ++i)
{
bands[i].amplitude = 0;
bands[i].phase = dis(gen);
bands[i].real[0] = cosf(bands[i].phase);
bands[i].imag[0] = sinf(bands[i].phase);
// ODD bands need to be 180 out of phase every other buffer generation
// because our overlap is half the size of the buffer generated.
// this ensure that phase lines up for those sinusoids in every buffer.
if (i % 2 == 1)
{
bands[i].real[1] = cosf(bands[i].phase + M_PI);
bands[i].imag[1] = sinf(bands[i].phase + M_PI);
}
else
{
bands[i].real[1] = bands[i].real[0];
bands[i].imag[1] = bands[i].imag[0];
}
}
outIndex = 0;
phaseIdx = 0;
// spectral magnitude is relative to the fft size because shorter ffts make louder output (and vice-versa),
// so this helps maintain similar volume across all sample rates.
#if SA_API
// spectral magnitude needs to be louder for standalone to balance this APP_MULT constant in app_resource.h
// adjust volume here gives better results than setting APP_MULT to 1 and using the same spectral amplitude.
spectralMagnitude = inverseSize / 8;
#else
spectralMagnitude = inverseSize / 32;
#endif
}
void SpectralGen::sampleRateChanged()
{
reset();
}
void SpectralGen::pluck(const float freq, const float amp)
{
const int bidx = freqToIndex(freq);
if (bidx > 0 && bidx < specSize)
{
bands[bidx].amplitude = amp;
bands[bidx].decay = 1;
}
}
float SpectralGen::getBandPhase(const float freq) const
{
if (fft != nullptr)
{
const int b = fft->freqToIndex(freq);
return b >= 0 && b < specSize ? bands[b].phase : 0;
}
return 0;
}
float SpectralGen::getBandMagnitude(const float freq) const
{
if (fft != nullptr)
{
const int b = fft->freqToIndex(freq);
return b >= 0 && b < specSize ? specMag[b]/spectralMagnitude : 0;
}
return 0;
}
void SpectralGen::uGenerate(float* out, const int numChannels)
{
if (output == nullptr)
{
UGen::fill(out, 0, numChannels);
return;
}
if ( outIndex % overlapSize == 0 )
{
// DQ (2/20/18)
// now pull the decay from a UGenInput and pass it in to the band struct instead of using a static var.
// this is in seconds, we need to convert to a fixed amount we can subtract from each band's amplitude,
// which depends on sample rate and overlap size.
const float decaySeconds = decay.getLastValue();
// amplitude needs to decrease by 1 / (decaySeconds * sampleRate()) every sample.
// eg decaySeconds == 1 -> 1 / sampleRate()
// decaySeconds == 0.5 -> 1 / (0.5 * sampleRate), which is twice as fast, equivalent to 2 / sampleRate()
// since we generate a new buffer every overlapSize samples, we multiply that rate by overlapSize, giving:
const float decayDec = overlapSize / (decaySeconds * sampleRate());
const float falloff = brightness.getLastValue();
const float halfSpread = spread.getLastValue() * 0.5f;
// we *do not* memset specMag because it will be directly set once we accumulate all amplitudes.
// this keeps it more consistent for rendering the strings in the UI
memset(specSpread, 0, specSize * sizeof(float));
memset(specReal, 0, inverseSize * sizeof(float));
memset(specImag, 0, inverseSize * sizeof(float));
for( int i = 1; i < specSize; ++i )
{
band& b = bands[i];
b.decay = b.decay > decayDec ? b.decay - decayDec : 0;
if (b.decay > 0)
{
const float a = b.decay*b.amplitude;
const float bandFreq = fft->indexToFreq(i);
// get low and high frequencies for spread
const int lidx = freqToIndex(bandFreq - halfSpread);
const int hidx = freqToIndex(bandFreq + halfSpread);
addSinusoidWithSpread(i, a, lidx, hidx);
}
}
// apply brightness to the spectrum
for(int i = 1; i < specSize; ++i)
{
// grab the magnitude as set by our pluck with spread pass
float a = specSpread[i];
// copy into the complex spectrum where we will accumulate brightness.
// it's += because we may have already accumulated some brightness here from a previous band.
specReal[i] += a;
// add brightness if we have a decent signal to work with
static const float epsilon = 0.0001f;
if ( a > epsilon )
{
const float bandFreq = fft->indexToFreq(i);
int partial = 2;
float partialFreq = bandFreq*partial;
int pidx = freqToIndex(bandFreq*partial);
a *= falloff;
while (pidx < specSize && a > epsilon)
{
// accumulate into the complex spectrum
specReal[pidx] += a / partial;
++partial;
partialFreq = bandFreq*partial;
pidx = freqToIndex(bandFreq*partial);
a *= falloff;
}
}
// copy accumulated result into the magnitude array, scaling by our max amplitude
specMag[i] = fmin(specReal[i] * spectralMagnitude, spectralMagnitude);
// done with this band, we can construct the complex representation.
specReal[i] = specMag[i] * bands[i].real[phaseIdx];
specImag[i] = specMag[i] * bands[i].imag[phaseIdx];
}
fft->Minim::FourierTransform::inverse(specReal, specImag, inverse);
Minim::FourierTransform::TRIANGULAR.apply( inverse, inverseSize );
for( int s = 0; s < inverseSize; ++s )
{
int ind = (s + outIndex) % outputSize;
output[ind] += inverse[s];
}
if (phaseIdx == 0) phaseIdx = 1;
else phaseIdx = 0;
}
UGen::fill(out, output[outIndex], numChannels);
output[outIndex] = 0;
outIndex = (outIndex+1)%outputSize;
}
int SpectralGen::freqToIndex(const float freq)
{
// special case: freq is lower than the bandwidth of spectrum[0] but not negative
if (freq > 0 && freq < fft->getBandWidth() / 2) return 0;
// all other cases
const float fraction = freq / sampleRate();
// roundf is not available in windows, so we do this
const int i = (int)floorf((float)fft->timeSize() * fraction + 0.5f);
return i;
}
void SpectralGen::addSinusoidWithSpread(const int idx, const float amp, const int lidx, const int hidx)
{
const int range = idx - lidx;
for (int bidx = lidx; bidx <= hidx; ++bidx)
{
if (bidx > 0 && bidx < specSize)
{
if (bidx == idx)
{
specSpread[bidx] += amp;
}
else
{
const float fn = fabs(bidx - idx) / range;
// exponential fall off from the center, see: https://www.desmos.com/calculator/gzqrz4isyb
specSpread[bidx] += amp * exp(-10 * fn);
}
}
}
}
void SpectralGen::cleanup()
{
if (fft != nullptr)
{
delete fft;
fft = nullptr;
}
if (bands != nullptr)
{
delete[] bands;
bands = nullptr;
}
if (specSpread != nullptr)
{
delete[] specSpread;
specSpread = nullptr;
}
if (specMag != nullptr)
{
delete[] specMag;
specMag = nullptr;
}
if (specReal != nullptr)
{
delete[] specReal;
specReal = nullptr;
}
if (specImag != nullptr)
{
delete[] specImag;
specImag = nullptr;
}
if (inverse != nullptr)
{
delete[] inverse;
inverse = nullptr;
}
if (output != nullptr)
{
delete[] output;
output = nullptr;
}
}