1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
6 Centre for Digital Music, Queen Mary, University of London.
7 This file is based on Don Cross's public domain FFT implementation.
12 #include "maths/MathUtilities.h"
18 FFT::FFT(unsigned int n) :
22 if( !MathUtilities::isPowerOfTwo(m_n) )
24 std::cerr << "ERROR: FFT: Non-power-of-two FFT size "
25 << m_n << " not supported in this implementation"
36 FFTReal::FFTReal(unsigned int n) :
40 m_private_real = new FFT(m_n);
45 delete (FFT *)m_private_real;
49 FFTReal::process(bool inverse,
51 double *realOut, double *imagOut)
53 ((FFT *)m_private_real)->process(inverse, realIn, 0, realOut, imagOut);
56 static unsigned int numberOfBitsNeeded(unsigned int p_nSamples)
67 if( p_nSamples & (1 << i) ) return i;
71 static unsigned int reverseBits(unsigned int p_nIndex, unsigned int p_nBits)
75 for(i=rev=0; i < p_nBits; i++)
77 rev = (rev << 1) | (p_nIndex & 1);
85 FFT::process(bool p_bInverseTransform,
86 const double *p_lpRealIn, const double *p_lpImagIn,
87 double *p_lpRealOut, double *p_lpImagOut)
89 if (!p_lpRealIn || !p_lpRealOut || !p_lpImagOut) return;
91 // std::cerr << "FFT::process(" << m_n << "," << p_bInverseTransform << ")" << std::endl;
94 unsigned int i, j, k, n;
95 unsigned int BlockSize, BlockEnd;
97 double angle_numerator = 2.0 * M_PI;
100 if( !MathUtilities::isPowerOfTwo(m_n) )
102 std::cerr << "ERROR: FFT::process: Non-power-of-two FFT size "
103 << m_n << " not supported in this implementation"
108 if( p_bInverseTransform ) angle_numerator = -angle_numerator;
110 NumBits = numberOfBitsNeeded ( m_n );
113 for( i=0; i < m_n; i++ )
115 j = reverseBits ( i, NumBits );
116 p_lpRealOut[j] = p_lpRealIn[i];
117 p_lpImagOut[j] = (p_lpImagIn == 0) ? 0.0 : p_lpImagIn[i];
122 for( BlockSize = 2; BlockSize <= m_n; BlockSize <<= 1 )
124 double delta_angle = angle_numerator / (double)BlockSize;
125 double sm2 = -sin ( -2 * delta_angle );
126 double sm1 = -sin ( -delta_angle );
127 double cm2 = cos ( -2 * delta_angle );
128 double cm1 = cos ( -delta_angle );
132 for( i=0; i < m_n; i += BlockSize )
141 for ( j=i, n=0; n < BlockEnd; j++, n++ )
144 ar[0] = w*ar[1] - ar[2];
148 ai[0] = w*ai[1] - ai[2];
153 tr = ar[0]*p_lpRealOut[k] - ai[0]*p_lpImagOut[k];
154 ti = ar[0]*p_lpImagOut[k] + ai[0]*p_lpRealOut[k];
156 p_lpRealOut[k] = p_lpRealOut[j] - tr;
157 p_lpImagOut[k] = p_lpImagOut[j] - ti;
159 p_lpRealOut[j] += tr;
160 p_lpImagOut[j] += ti;
165 BlockEnd = BlockSize;
170 if( p_bInverseTransform )
172 double denom = (double)m_n;
174 for ( i=0; i < m_n; i++ )
176 p_lpRealOut[i] /= denom;
177 p_lpImagOut[i] /= denom;