fft.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. /*
  2. LICENSE
  3. -------
  4. Copyright 2005-2013 Nullsoft, Inc.
  5. All rights reserved.
  6. Redistribution and use in source and binary forms, with or without modification,
  7. are permitted provided that the following conditions are met:
  8. * Redistributions of source code must retain the above copyright notice,
  9. this list of conditions and the following disclaimer.
  10. * Redistributions in binary form must reproduce the above copyright notice,
  11. this list of conditions and the following disclaimer in the documentation
  12. and/or other materials provided with the distribution.
  13. * Neither the name of Nullsoft nor the names of its contributors may be used to
  14. endorse or promote products derived from this software without specific prior written permission.
  15. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
  16. IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  17. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  18. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  19. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  20. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
  21. IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  22. OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. */
  24. #include <math.h>
  25. #include <memory.h>
  26. #include "fft.h"
  27. #define PI 3.141592653589793238462643383279502884197169399f
  28. #define SafeDeleteArray(x) { if (x) { delete [] x; x = 0; } }
  29. /*****************************************************************************/
  30. FFT::FFT()
  31. {
  32. NFREQ = 0;
  33. envelope = 0;
  34. equalize = 0;
  35. bitrevtable = 0;
  36. cossintable = 0;
  37. temp1 = 0;
  38. temp2 = 0;
  39. }
  40. /*****************************************************************************/
  41. FFT::~FFT()
  42. {
  43. CleanUp();
  44. }
  45. /*****************************************************************************/
  46. void FFT::Init(int samples_in, int samples_out, int bEqualize, float envelope_power)
  47. {
  48. // samples_in: # of waveform samples you'll feed into the FFT
  49. // samples_out: # of frequency samples you want out; MUST BE A POWER OF 2.
  50. // bEqualize: set to 1 if you want the magnitude of the basses and trebles
  51. // to be roughly equalized; 0 to leave them untouched.
  52. // envelope_power: set to -1 to disable the envelope; otherwise, specify
  53. // the envelope power you want here. See InitEnvelopeTable for more info.
  54. CleanUp();
  55. m_samples_in = samples_in;
  56. NFREQ = samples_out*2;
  57. InitBitRevTable();
  58. InitCosSinTable();
  59. if (envelope_power > 0)
  60. InitEnvelopeTable(envelope_power);
  61. if (bEqualize)
  62. InitEqualizeTable();
  63. temp1 = new float[NFREQ];
  64. temp2 = new float[NFREQ];
  65. }
  66. /*****************************************************************************/
  67. void FFT::CleanUp()
  68. {
  69. SafeDeleteArray(envelope);
  70. SafeDeleteArray(equalize);
  71. SafeDeleteArray(bitrevtable);
  72. SafeDeleteArray(cossintable);
  73. SafeDeleteArray(temp1);
  74. SafeDeleteArray(temp2);
  75. }
  76. /*****************************************************************************/
  77. void FFT::InitEqualizeTable()
  78. {
  79. int i;
  80. float scaling = -0.02f;
  81. float inv_half_nfreq = 1.0f/(float)(NFREQ/2);
  82. equalize = new float[NFREQ/2];
  83. for (i=0; i<NFREQ/2; i++)
  84. equalize[i] = scaling * logf( (float)(NFREQ/2-i)*inv_half_nfreq );
  85. }
  86. /*****************************************************************************/
  87. void FFT::InitEnvelopeTable(float power)
  88. {
  89. // this precomputation is for multiplying the waveform sample
  90. // by a bell-curve-shaped envelope, so we don't see the ugly
  91. // frequency response (oscillations) of a square filter.
  92. // a power of 1.0 will compute the FFT with exactly one convolution.
  93. // a power of 2.0 is like doing it twice; the resulting frequency
  94. // output will be smoothed out and the peaks will be "fatter".
  95. // a power of 0.5 is closer to not using an envelope, and you start
  96. // to get the frequency response of the square filter as 'power'
  97. // approaches zero; the peaks get tighter and more precise, but
  98. // you also see small oscillations around their bases.
  99. int i;
  100. float mult = 1.0f/(float)m_samples_in * 6.2831853f;
  101. envelope = new float[m_samples_in];
  102. if (power==1.0f)
  103. for (i=0; i<m_samples_in; i++)
  104. envelope[i] = 0.5f + 0.5f*sinf(i*mult - 1.5707963268f);
  105. else
  106. for (i=0; i<m_samples_in; i++)
  107. envelope[i] = powf(0.5f + 0.5f*sinf(i*mult - 1.5707963268f), power);
  108. }
  109. /*****************************************************************************/
  110. void FFT::InitBitRevTable()
  111. {
  112. int i,j,m,temp;
  113. bitrevtable = new int[NFREQ];
  114. for (i=0; i<NFREQ; i++)
  115. bitrevtable[i] = i;
  116. for (i=0,j=0; i < NFREQ; i++)
  117. {
  118. if (j > i)
  119. {
  120. temp = bitrevtable[i];
  121. bitrevtable[i] = bitrevtable[j];
  122. bitrevtable[j] = temp;
  123. }
  124. m = NFREQ >> 1;
  125. while (m >= 1 && j >= m)
  126. {
  127. j -= m;
  128. m >>= 1;
  129. }
  130. j += m;
  131. }
  132. }
  133. /*****************************************************************************/
  134. void FFT::InitCosSinTable()
  135. {
  136. int i,dftsize,tabsize;
  137. float theta;
  138. dftsize = 2;
  139. tabsize = 0;
  140. while (dftsize <= NFREQ)
  141. {
  142. tabsize++;
  143. dftsize <<= 1;
  144. }
  145. cossintable = new float[tabsize][2];
  146. dftsize = 2;
  147. i = 0;
  148. while (dftsize <= NFREQ)
  149. {
  150. theta = (float)(-2.0f*PI/(float)dftsize);
  151. cossintable[i][0] = (float)cosf(theta);
  152. cossintable[i][1] = (float)sinf(theta);
  153. i++;
  154. dftsize <<= 1;
  155. }
  156. }
  157. /*****************************************************************************/
  158. void FFT::time_to_frequency_domain(float *in_wavedata, float *out_spectraldata)
  159. {
  160. // Converts time-domain samples from in_wavedata[]
  161. // into frequency-domain samples in out_spectraldata[].
  162. // The array lengths are the two parameters to Init().
  163. // The last sample of the output data will represent the frequency
  164. // that is 1/4th of the input sampling rate. For example,
  165. // if the input wave data is sampled at 44,100 Hz, then the last
  166. // sample of the spectral data output will represent the frequency
  167. // 11,025 Hz. The first sample will be 0 Hz; the frequencies of
  168. // the rest of the samples vary linearly in between.
  169. // Note that since human hearing is limited to the range 200 - 20,000
  170. // Hz. 200 is a low bass hum; 20,000 is an ear-piercing high shriek.
  171. // Each time the frequency doubles, that sounds like going up an octave.
  172. // That means that the difference between 200 and 300 Hz is FAR more
  173. // than the difference between 5000 and 5100, for example!
  174. // So, when trying to analyze bass, you'll want to look at (probably)
  175. // the 200-800 Hz range; whereas for treble, you'll want the 1,400 -
  176. // 11,025 Hz range.
  177. // If you want to get 3 bands, try it this way:
  178. // a) 11,025 / 200 = 55.125
  179. // b) to get the number of octaves between 200 and 11,025 Hz, solve for n:
  180. // 2^n = 55.125
  181. // n = log 55.125 / log 2
  182. // n = 5.785
  183. // c) so each band should represent 5.785/3 = 1.928 octaves; the ranges are:
  184. // 1) 200 - 200*2^1.928 or 200 - 761 Hz
  185. // 2) 200*2^1.928 - 200*2^(1.928*2) or 761 - 2897 Hz
  186. // 3) 200*2^(1.928*2) - 200*2^(1.928*3) or 2897 - 11025 Hz
  187. // A simple sine-wave-based envelope is convolved with the waveform
  188. // data before doing the FFT, to emeliorate the bad frequency response
  189. // of a square (i.e. nonexistent) filter.
  190. // You might want to slightly damp (blur) the input if your signal isn't
  191. // of a very high quality, to reduce high-frequency noise that would
  192. // otherwise show up in the output.
  193. int j, m, i, dftsize, hdftsize, t;
  194. float wr, wi, wpi, wpr, wtemp, tempr, tempi;
  195. if (!bitrevtable) return;
  196. //if (!envelope) return;
  197. //if (!equalize) return;
  198. if (!temp1) return;
  199. if (!temp2) return;
  200. if (!cossintable) return;
  201. // 1. set up input to the fft
  202. if (envelope)
  203. {
  204. for (i=0; i<NFREQ; i++)
  205. {
  206. int idx = bitrevtable[i];
  207. if (idx < m_samples_in)
  208. temp1[i] = in_wavedata[idx] * envelope[idx];
  209. else
  210. temp1[i] = 0;
  211. }
  212. }
  213. else
  214. {
  215. for (i=0; i<NFREQ; i++)
  216. {
  217. int idx = bitrevtable[i];
  218. if (idx < m_samples_in)
  219. temp1[i] = in_wavedata[idx];// * envelope[idx];
  220. else
  221. temp1[i] = 0;
  222. }
  223. }
  224. memset(temp2, 0, sizeof(float)*NFREQ);
  225. // 2. perform FFT
  226. float *real = temp1;
  227. float *imag = temp2;
  228. dftsize = 2;
  229. t = 0;
  230. while (dftsize <= NFREQ)
  231. {
  232. wpr = cossintable[t][0];
  233. wpi = cossintable[t][1];
  234. wr = 1.0f;
  235. wi = 0.0f;
  236. hdftsize = dftsize >> 1;
  237. for (m = 0; m < hdftsize; m+=1)
  238. {
  239. for (i = m; i < NFREQ; i+=dftsize)
  240. {
  241. j = i + hdftsize;
  242. tempr = wr*real[j] - wi*imag[j];
  243. tempi = wr*imag[j] + wi*real[j];
  244. real[j] = real[i] - tempr;
  245. imag[j] = imag[i] - tempi;
  246. real[i] += tempr;
  247. imag[i] += tempi;
  248. }
  249. wr = (wtemp=wr)*wpr - wi*wpi;
  250. wi = wi*wpr + wtemp*wpi;
  251. }
  252. dftsize <<= 1;
  253. t++;
  254. }
  255. // 3. take the magnitude & equalize it (on a log10 scale) for output
  256. if (equalize)
  257. for (i=0; i<NFREQ/2; i++)
  258. out_spectraldata[i] = equalize[i] * sqrtf(temp1[i]*temp1[i] + temp2[i]*temp2[i]);
  259. else
  260. for (i=0; i<NFREQ/2; i++)
  261. out_spectraldata[i] = sqrtf(temp1[i]*temp1[i] + temp2[i]*temp2[i]);
  262. }
  263. /*****************************************************************************/