this repo has no description
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

initial commit of kiss_fft130.tar.gz contents

Ian 7d001836

+4748
+123
CHANGELOG
··· 1 + 1.3.0 2012-07-18 2 + removed non-standard malloc.h from kiss_fft.h 3 + 4 + moved -lm to end of link line 5 + 6 + checked various return values 7 + 8 + converted python Numeric code to NumPy 9 + 10 + fixed test of int32_t on 64 bit OS 11 + 12 + added padding in a couple of places to allow SIMD alignment of structs 13 + 14 + 1.2.9 2010-05-27 15 + threadsafe ( including OpenMP ) 16 + 17 + first edition of kissfft.hh the C++ template fft engine 18 + 19 + 1.2.8 20 + Changed memory.h to string.h -- apparently more standard 21 + 22 + Added openmp extensions. This can have fairly linear speedups for larger FFT sizes. 23 + 24 + 1.2.7 25 + Shrank the real-fft memory footprint. Thanks to Galen Seitz. 26 + 27 + 1.2.6 (Nov 14, 2006) The "thanks to GenArts" release. 28 + Added multi-dimensional real-optimized FFT, see tools/kiss_fftndr 29 + Thanks go to GenArts, Inc. for sponsoring the development. 30 + 31 + 1.2.5 (June 27, 2006) The "release for no good reason" release. 32 + Changed some harmless code to make some compilers' warnings go away. 33 + Added some more digits to pi -- why not. 34 + Added kiss_fft_next_fast_size() function to help people decide how much to pad. 35 + Changed multidimensional test from 8 dimensions to only 3 to avoid testing 36 + problems with fixed point (sorry Buckaroo Banzai). 37 + 38 + 1.2.4 (Oct 27, 2005) The "oops, inverse fixed point real fft was borked" release. 39 + Fixed scaling bug for inverse fixed point real fft -- also fixed test code that should've been failing. 40 + Thanks to Jean-Marc Valin for bug report. 41 + 42 + Use sys/types.h for more portable types than short,int,long => int16_t,int32_t,int64_t 43 + If your system does not have these, you may need to define them -- but at least it breaks in a 44 + loud and easily fixable way -- unlike silently using the wrong size type. 45 + 46 + Hopefully tools/psdpng.c is fixed -- thanks to Steve Kellog for pointing out the weirdness. 47 + 48 + 1.2.3 (June 25, 2005) The "you want to use WHAT as a sample" release. 49 + Added ability to use 32 bit fixed point samples -- requires a 64 bit intermediate result, a la 'long long' 50 + 51 + Added ability to do 4 FFTs in parallel by using SSE SIMD instructions. This is accomplished by 52 + using the __m128 (vector of 4 floats) as kiss_fft_scalar. Define USE_SIMD to use this. 53 + 54 + I know, I know ... this is drifting a bit from the "kiss" principle, but the speed advantages 55 + make it worth it for some. Also recent gcc makes it SOO easy to use vectors of 4 floats like a POD type. 56 + 57 + 1.2.2 (May 6, 2005) The Matthew release 58 + Replaced fixed point division with multiply&shift. Thanks to Jean-Marc Valin for 59 + discussions regarding. Considerable speedup for fixed-point. 60 + 61 + Corrected overflow protection in real fft routines when using fixed point. 62 + Finder's Credit goes to Robert Oschler of robodance for pointing me at the bug. 63 + This also led to the CHECK_OVERFLOW_OP macro. 64 + 65 + 1.2.1 (April 4, 2004) 66 + compiles cleanly with just about every -W warning flag under the sun 67 + 68 + reorganized kiss_fft_state so it could be read-only/const. This may be useful for embedded systems 69 + that are willing to predeclare twiddle factors, factorization. 70 + 71 + Fixed C_MUL,S_MUL on 16-bit platforms. 72 + 73 + tmpbuf will only be allocated if input & output buffers are same 74 + scratchbuf will only be allocated for ffts that are not multiples of 2,3,5 75 + 76 + NOTE: The tmpbuf,scratchbuf changes may require synchronization code for multi-threaded apps. 77 + 78 + 79 + 1.2 (Feb 23, 2004) 80 + interface change -- cfg object is forward declaration of struct instead of void* 81 + This maintains type saftey and lets the compiler warn/error about stupid mistakes. 82 + (prompted by suggestion from Erik de Castro Lopo) 83 + 84 + small speed improvements 85 + 86 + added psdpng.c -- sample utility that will create png spectrum "waterfalls" from an input file 87 + ( not terribly useful yet) 88 + 89 + 1.1.1 (Feb 1, 2004 ) 90 + minor bug fix -- only affects odd rank, in-place, multi-dimensional FFTs 91 + 92 + 1.1 : (Jan 30,2004) 93 + split sample_code/ into test/ and tools/ 94 + 95 + Removed 2-D fft and added N-D fft (arbitrary) 96 + 97 + modified fftutil.c to allow multi-d FFTs 98 + 99 + Modified core fft routine to allow an input stride via kiss_fft_stride() 100 + (eased support of multi-D ffts) 101 + 102 + Added fast convolution filtering (FIR filtering using overlap-scrap method, with tail scrap) 103 + 104 + Add kfc.[ch]: the KISS FFT Cache. It takes care of allocs for you ( suggested by Oscar Lesta ). 105 + 106 + 1.0.1 (Dec 15, 2003) 107 + fixed bug that occurred when nfft==1. Thanks to Steven Johnson. 108 + 109 + 1.0 : (Dec 14, 2003) 110 + changed kiss_fft function from using a single buffer, to two buffers. 111 + If the same buffer pointer is supplied for both in and out, kiss will 112 + manage the buffer copies. 113 + 114 + added kiss_fft2d and kiss_fftr as separate source files (declarations in kiss_fft.h ) 115 + 116 + 0.4 :(Nov 4,2003) optimized for radix 2,3,4,5 117 + 118 + 0.3 :(Oct 28, 2003) woops, version 2 didn't actually factor out any radices other than 2. 119 + Thanks to Steven Johnson for finding this one. 120 + 121 + 0.2 :(Oct 27, 2003) added mixed radix, only radix 2,4 optimized versions 122 + 123 + 0.1 :(May 19 2003) initial release, radix 2 only
+11
COPYING
··· 1 + Copyright (c) 2003-2010 Mark Borgerding 2 + 3 + All rights reserved. 4 + 5 + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 + 7 + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 9 + * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. 10 + 11 + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+33
Makefile
··· 1 + KFVER=130 2 + 3 + doc: 4 + @echo "Start by reading the README file. If you want to build and test lots of stuff, do a 'make testall'" 5 + @echo "but be aware that 'make testall' has dependencies that the basic kissfft software does not." 6 + @echo "It is generally unneeded to run these tests yourself, unless you plan on changing the inner workings" 7 + @echo "of kissfft and would like to make use of its regression tests." 8 + 9 + testall: 10 + # The simd and int32_t types may or may not work on your machine 11 + make -C test DATATYPE=simd CFLAGADD="$(CFLAGADD)" test 12 + make -C test DATATYPE=int32_t CFLAGADD="$(CFLAGADD)" test 13 + make -C test DATATYPE=int16_t CFLAGADD="$(CFLAGADD)" test 14 + make -C test DATATYPE=float CFLAGADD="$(CFLAGADD)" test 15 + make -C test DATATYPE=double CFLAGADD="$(CFLAGADD)" test 16 + echo "all tests passed" 17 + 18 + tarball: clean 19 + hg archive -r v$(KFVER) -t tgz kiss_fft$(KFVER).tar.gz 20 + hg archive -r v$(KFVER) -t zip kiss_fft$(KFVER).zip 21 + 22 + clean: 23 + cd test && make clean 24 + cd tools && make clean 25 + rm -f kiss_fft*.tar.gz *~ *.pyc kiss_fft*.zip 26 + 27 + asm: kiss_fft.s 28 + 29 + kiss_fft.s: kiss_fft.c kiss_fft.h _kiss_fft_guts.h 30 + [ -e kiss_fft.s ] && mv kiss_fft.s kiss_fft.s~ || true 31 + gcc -S kiss_fft.c -O3 -mtune=native -ffast-math -fomit-frame-pointer -unroll-loops -dA -fverbose-asm 32 + gcc -o kiss_fft_short.s -S kiss_fft.c -O3 -mtune=native -ffast-math -fomit-frame-pointer -dA -fverbose-asm -DFIXED_POINT 33 + [ -e kiss_fft.s~ ] && diff kiss_fft.s~ kiss_fft.s || true
+134
README
··· 1 + KISS FFT - A mixed-radix Fast Fourier Transform based up on the principle, 2 + "Keep It Simple, Stupid." 3 + 4 + There are many great fft libraries already around. Kiss FFT is not trying 5 + to be better than any of them. It only attempts to be a reasonably efficient, 6 + moderately useful FFT that can use fixed or floating data types and can be 7 + incorporated into someone's C program in a few minutes with trivial licensing. 8 + 9 + USAGE: 10 + 11 + The basic usage for 1-d complex FFT is: 12 + 13 + #include "kiss_fft.h" 14 + 15 + kiss_fft_cfg cfg = kiss_fft_alloc( nfft ,is_inverse_fft ,0,0 ); 16 + 17 + while ... 18 + 19 + ... // put kth sample in cx_in[k].r and cx_in[k].i 20 + 21 + kiss_fft( cfg , cx_in , cx_out ); 22 + 23 + ... // transformed. DC is in cx_out[0].r and cx_out[0].i 24 + 25 + free(cfg); 26 + 27 + Note: frequency-domain data is stored from dc up to 2pi. 28 + so cx_out[0] is the dc bin of the FFT 29 + and cx_out[nfft/2] is the Nyquist bin (if exists) 30 + 31 + Declarations are in "kiss_fft.h", along with a brief description of the 32 + functions you'll need to use. 33 + 34 + Code definitions for 1d complex FFTs are in kiss_fft.c. 35 + 36 + You can do other cool stuff with the extras you'll find in tools/ 37 + 38 + * multi-dimensional FFTs 39 + * real-optimized FFTs (returns the positive half-spectrum: (nfft/2+1) complex frequency bins) 40 + * fast convolution FIR filtering (not available for fixed point) 41 + * spectrum image creation 42 + 43 + The core fft and most tools/ code can be compiled to use float, double, 44 + Q15 short or Q31 samples. The default is float. 45 + 46 + 47 + BACKGROUND: 48 + 49 + I started coding this because I couldn't find a fixed point FFT that didn't 50 + use assembly code. I started with floating point numbers so I could get the 51 + theory straight before working on fixed point issues. In the end, I had a 52 + little bit of code that could be recompiled easily to do ffts with short, float 53 + or double (other types should be easy too). 54 + 55 + Once I got my FFT working, I was curious about the speed compared to 56 + a well respected and highly optimized fft library. I don't want to criticize 57 + this great library, so let's call it FFT_BRANDX. 58 + During this process, I learned: 59 + 60 + 1. FFT_BRANDX has more than 100K lines of code. The core of kiss_fft is about 500 lines (cpx 1-d). 61 + 2. It took me an embarrassingly long time to get FFT_BRANDX working. 62 + 3. A simple program using FFT_BRANDX is 522KB. A similar program using kiss_fft is 18KB (without optimizing for size). 63 + 4. FFT_BRANDX is roughly twice as fast as KISS FFT in default mode. 64 + 65 + It is wonderful that free, highly optimized libraries like FFT_BRANDX exist. 66 + But such libraries carry a huge burden of complexity necessary to extract every 67 + last bit of performance. 68 + 69 + Sometimes simpler is better, even if it's not better. 70 + 71 + FREQUENTLY ASKED QUESTIONS: 72 + Q: Can I use kissfft in a project with a ___ license? 73 + A: Yes. See LICENSE below. 74 + 75 + Q: Why don't I get the output I expect? 76 + A: The two most common causes of this are 77 + 1) scaling : is there a constant multiplier between what you got and what you want? 78 + 2) mixed build environment -- all code must be compiled with same preprocessor 79 + definitions for FIXED_POINT and kiss_fft_scalar 80 + 81 + Q: Will you write/debug my code for me? 82 + A: Probably not unless you pay me. I am happy to answer pointed and topical questions, but 83 + I may refer you to a book, a forum, or some other resource. 84 + 85 + 86 + PERFORMANCE: 87 + (on Athlon XP 2100+, with gcc 2.96, float data type) 88 + 89 + Kiss performed 10000 1024-pt cpx ffts in .63 s of cpu time. 90 + For comparison, it took md5sum twice as long to process the same amount of data. 91 + 92 + Transforming 5 minutes of CD quality audio takes less than a second (nfft=1024). 93 + 94 + DO NOT: 95 + ... use Kiss if you need the Fastest Fourier Transform in the World 96 + ... ask me to add features that will bloat the code 97 + 98 + UNDER THE HOOD: 99 + 100 + Kiss FFT uses a time decimation, mixed-radix, out-of-place FFT. If you give it an input buffer 101 + and output buffer that are the same, a temporary buffer will be created to hold the data. 102 + 103 + No static data is used. The core routines of kiss_fft are thread-safe (but not all of the tools directory). 104 + 105 + No scaling is done for the floating point version (for speed). 106 + Scaling is done both ways for the fixed-point version (for overflow prevention). 107 + 108 + Optimized butterflies are used for factors 2,3,4, and 5. 109 + 110 + The real (i.e. not complex) optimization code only works for even length ffts. It does two half-length 111 + FFTs in parallel (packed into real&imag), and then combines them via twiddling. The result is 112 + nfft/2+1 complex frequency bins from DC to Nyquist. If you don't know what this means, search the web. 113 + 114 + The fast convolution filtering uses the overlap-scrap method, slightly 115 + modified to put the scrap at the tail. 116 + 117 + LICENSE: 118 + Revised BSD License, see COPYING for verbiage. 119 + Basically, "free to use&change, give credit where due, no guarantees" 120 + Note this license is compatible with GPL at one end of the spectrum and closed, commercial software at 121 + the other end. See http://www.fsf.org/licensing/licenses 122 + 123 + A commercial license is available which removes the requirement for attribution. Contact me for details. 124 + 125 + 126 + TODO: 127 + *) Add real optimization for odd length FFTs 128 + *) Document/revisit the input/output fft scaling 129 + *) Make doc describing the overlap (tail) scrap fast convolution filtering in kiss_fastfir.c 130 + *) Test all the ./tools/ code with fixed point (kiss_fastfir.c doesn't work, maybe others) 131 + 132 + AUTHOR: 133 + Mark Borgerding 134 + Mark@Borgerding.net
+78
README.simd
··· 1 + If you are reading this, it means you think you may be interested in using the SIMD extensions in kissfft 2 + to do 4 *separate* FFTs at once. 3 + 4 + Beware! Beyond here there be dragons! 5 + 6 + This API is not easy to use, is not well documented, and breaks the KISS principle. 7 + 8 + 9 + Still reading? Okay, you may get rewarded for your patience with a considerable speedup 10 + (2-3x) on intel x86 machines with SSE if you are willing to jump through some hoops. 11 + 12 + The basic idea is to use the packed 4 float __m128 data type as a scalar element. 13 + This means that the format is pretty convoluted. It performs 4 FFTs per fft call on signals A,B,C,D. 14 + 15 + For complex data, the data is interlaced as follows: 16 + rA0,rB0,rC0,rD0, iA0,iB0,iC0,iD0, rA1,rB1,rC1,rD1, iA1,iB1,iC1,iD1 ... 17 + where "rA0" is the real part of the zeroth sample for signal A 18 + 19 + Real-only data is laid out: 20 + rA0,rB0,rC0,rD0, rA1,rB1,rC1,rD1, ... 21 + 22 + Compile with gcc flags something like 23 + -O3 -mpreferred-stack-boundary=4 -DUSE_SIMD=1 -msse 24 + 25 + Be aware of SIMD alignment. This is the most likely cause of segfaults. 26 + The code within kissfft uses scratch variables on the stack. 27 + With SIMD, these must have addresses on 16 byte boundaries. 28 + Search on "SIMD alignment" for more info. 29 + 30 + 31 + 32 + Robin at Divide Concept was kind enough to share his code for formatting to/from the SIMD kissfft. 33 + I have not run it -- use it at your own risk. It appears to do 4xN and Nx4 transpositions 34 + (out of place). 35 + 36 + void SSETools::pack128(float* target, float* source, unsigned long size128) 37 + { 38 + __m128* pDest = (__m128*)target; 39 + __m128* pDestEnd = pDest+size128; 40 + float* source0=source; 41 + float* source1=source0+size128; 42 + float* source2=source1+size128; 43 + float* source3=source2+size128; 44 + 45 + while(pDest<pDestEnd) 46 + { 47 + *pDest=_mm_set_ps(*source3,*source2,*source1,*source0); 48 + source0++; 49 + source1++; 50 + source2++; 51 + source3++; 52 + pDest++; 53 + } 54 + } 55 + 56 + void SSETools::unpack128(float* target, float* source, unsigned long size128) 57 + { 58 + 59 + float* pSrc = source; 60 + float* pSrcEnd = pSrc+size128*4; 61 + float* target0=target; 62 + float* target1=target0+size128; 63 + float* target2=target1+size128; 64 + float* target3=target2+size128; 65 + 66 + while(pSrc<pSrcEnd) 67 + { 68 + *target0=pSrc[0]; 69 + *target1=pSrc[1]; 70 + *target2=pSrc[2]; 71 + *target3=pSrc[3]; 72 + target0++; 73 + target1++; 74 + target2++; 75 + target3++; 76 + pSrc+=4; 77 + } 78 + }
+39
TIPS
··· 1 + Speed: 2 + * If you want to use multiple cores, then compile with -openmp or -fopenmp (see your compiler docs). 3 + Realize that larger FFTs will reap more benefit than smaller FFTs. This generally uses more CPU time, but 4 + less wall time. 5 + 6 + * experiment with compiler flags 7 + Special thanks to Oscar Lesta. He suggested some compiler flags 8 + for gcc that make a big difference. They shave 10-15% off 9 + execution time on some systems. Try some combination of: 10 + -march=pentiumpro 11 + -ffast-math 12 + -fomit-frame-pointer 13 + 14 + * If the input data has no imaginary component, use the kiss_fftr code under tools/. 15 + Real ffts are roughly twice as fast as complex. 16 + 17 + * If you can rearrange your code to do 4 FFTs in parallel and you are on a recent Intel or AMD machine, 18 + then you might want to experiment with the USE_SIMD code. See README.simd 19 + 20 + 21 + Reducing code size: 22 + * remove some of the butterflies. There are currently butterflies optimized for radices 23 + 2,3,4,5. It is worth mentioning that you can still use FFT sizes that contain 24 + other factors, they just won't be quite as fast. You can decide for yourself 25 + whether to keep radix 2 or 4. If you do some work in this area, let me 26 + know what you find. 27 + 28 + * For platforms where ROM/code space is more plentiful than RAM, 29 + consider creating a hardcoded kiss_fft_state. In other words, decide which 30 + FFT size(s) you want and make a structure with the correct factors and twiddles. 31 + 32 + * Frank van der Hulst offered numerous suggestions for smaller code size and correct operation 33 + on embedded targets. "I'm happy to help anyone who is trying to implement KISSFFT on a micro" 34 + 35 + Some of these were rolled into the mainline code base: 36 + - using long casts to promote intermediate results of short*short multiplication 37 + - delaying allocation of buffers that are sometimes unused. 38 + In some cases, it may be desirable to limit capability in order to better suit the target: 39 + - predefining the twiddle tables for the desired fft size.
+164
_kiss_fft_guts.h
··· 1 + /* 2 + Copyright (c) 2003-2010, Mark Borgerding 3 + 4 + All rights reserved. 5 + 6 + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 7 + 8 + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 9 + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 10 + * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 + 12 + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 13 + */ 14 + 15 + /* kiss_fft.h 16 + defines kiss_fft_scalar as either short or a float type 17 + and defines 18 + typedef struct { kiss_fft_scalar r; kiss_fft_scalar i; }kiss_fft_cpx; */ 19 + #include "kiss_fft.h" 20 + #include <limits.h> 21 + 22 + #define MAXFACTORS 32 23 + /* e.g. an fft of length 128 has 4 factors 24 + as far as kissfft is concerned 25 + 4*4*4*2 26 + */ 27 + 28 + struct kiss_fft_state{ 29 + int nfft; 30 + int inverse; 31 + int factors[2*MAXFACTORS]; 32 + kiss_fft_cpx twiddles[1]; 33 + }; 34 + 35 + /* 36 + Explanation of macros dealing with complex math: 37 + 38 + C_MUL(m,a,b) : m = a*b 39 + C_FIXDIV( c , div ) : if a fixed point impl., c /= div. noop otherwise 40 + C_SUB( res, a,b) : res = a - b 41 + C_SUBFROM( res , a) : res -= a 42 + C_ADDTO( res , a) : res += a 43 + * */ 44 + #ifdef FIXED_POINT 45 + #if (FIXED_POINT==32) 46 + # define FRACBITS 31 47 + # define SAMPPROD int64_t 48 + #define SAMP_MAX 2147483647 49 + #else 50 + # define FRACBITS 15 51 + # define SAMPPROD int32_t 52 + #define SAMP_MAX 32767 53 + #endif 54 + 55 + #define SAMP_MIN -SAMP_MAX 56 + 57 + #if defined(CHECK_OVERFLOW) 58 + # define CHECK_OVERFLOW_OP(a,op,b) \ 59 + if ( (SAMPPROD)(a) op (SAMPPROD)(b) > SAMP_MAX || (SAMPPROD)(a) op (SAMPPROD)(b) < SAMP_MIN ) { \ 60 + fprintf(stderr,"WARNING:overflow @ " __FILE__ "(%d): (%d " #op" %d) = %ld\n",__LINE__,(a),(b),(SAMPPROD)(a) op (SAMPPROD)(b) ); } 61 + #endif 62 + 63 + 64 + # define smul(a,b) ( (SAMPPROD)(a)*(b) ) 65 + # define sround( x ) (kiss_fft_scalar)( ( (x) + (1<<(FRACBITS-1)) ) >> FRACBITS ) 66 + 67 + # define S_MUL(a,b) sround( smul(a,b) ) 68 + 69 + # define C_MUL(m,a,b) \ 70 + do{ (m).r = sround( smul((a).r,(b).r) - smul((a).i,(b).i) ); \ 71 + (m).i = sround( smul((a).r,(b).i) + smul((a).i,(b).r) ); }while(0) 72 + 73 + # define DIVSCALAR(x,k) \ 74 + (x) = sround( smul( x, SAMP_MAX/k ) ) 75 + 76 + # define C_FIXDIV(c,div) \ 77 + do { DIVSCALAR( (c).r , div); \ 78 + DIVSCALAR( (c).i , div); }while (0) 79 + 80 + # define C_MULBYSCALAR( c, s ) \ 81 + do{ (c).r = sround( smul( (c).r , s ) ) ;\ 82 + (c).i = sround( smul( (c).i , s ) ) ; }while(0) 83 + 84 + #else /* not FIXED_POINT*/ 85 + 86 + # define S_MUL(a,b) ( (a)*(b) ) 87 + #define C_MUL(m,a,b) \ 88 + do{ (m).r = (a).r*(b).r - (a).i*(b).i;\ 89 + (m).i = (a).r*(b).i + (a).i*(b).r; }while(0) 90 + # define C_FIXDIV(c,div) /* NOOP */ 91 + # define C_MULBYSCALAR( c, s ) \ 92 + do{ (c).r *= (s);\ 93 + (c).i *= (s); }while(0) 94 + #endif 95 + 96 + #ifndef CHECK_OVERFLOW_OP 97 + # define CHECK_OVERFLOW_OP(a,op,b) /* noop */ 98 + #endif 99 + 100 + #define C_ADD( res, a,b)\ 101 + do { \ 102 + CHECK_OVERFLOW_OP((a).r,+,(b).r)\ 103 + CHECK_OVERFLOW_OP((a).i,+,(b).i)\ 104 + (res).r=(a).r+(b).r; (res).i=(a).i+(b).i; \ 105 + }while(0) 106 + #define C_SUB( res, a,b)\ 107 + do { \ 108 + CHECK_OVERFLOW_OP((a).r,-,(b).r)\ 109 + CHECK_OVERFLOW_OP((a).i,-,(b).i)\ 110 + (res).r=(a).r-(b).r; (res).i=(a).i-(b).i; \ 111 + }while(0) 112 + #define C_ADDTO( res , a)\ 113 + do { \ 114 + CHECK_OVERFLOW_OP((res).r,+,(a).r)\ 115 + CHECK_OVERFLOW_OP((res).i,+,(a).i)\ 116 + (res).r += (a).r; (res).i += (a).i;\ 117 + }while(0) 118 + 119 + #define C_SUBFROM( res , a)\ 120 + do {\ 121 + CHECK_OVERFLOW_OP((res).r,-,(a).r)\ 122 + CHECK_OVERFLOW_OP((res).i,-,(a).i)\ 123 + (res).r -= (a).r; (res).i -= (a).i; \ 124 + }while(0) 125 + 126 + 127 + #ifdef FIXED_POINT 128 + # define KISS_FFT_COS(phase) floor(.5+SAMP_MAX * cos (phase)) 129 + # define KISS_FFT_SIN(phase) floor(.5+SAMP_MAX * sin (phase)) 130 + # define HALF_OF(x) ((x)>>1) 131 + #elif defined(USE_SIMD) 132 + # define KISS_FFT_COS(phase) _mm_set1_ps( cos(phase) ) 133 + # define KISS_FFT_SIN(phase) _mm_set1_ps( sin(phase) ) 134 + # define HALF_OF(x) ((x)*_mm_set1_ps(.5)) 135 + #else 136 + # define KISS_FFT_COS(phase) (kiss_fft_scalar) cos(phase) 137 + # define KISS_FFT_SIN(phase) (kiss_fft_scalar) sin(phase) 138 + # define HALF_OF(x) ((x)*.5) 139 + #endif 140 + 141 + #define kf_cexp(x,phase) \ 142 + do{ \ 143 + (x)->r = KISS_FFT_COS(phase);\ 144 + (x)->i = KISS_FFT_SIN(phase);\ 145 + }while(0) 146 + 147 + 148 + /* a debugging function */ 149 + #define pcpx(c)\ 150 + fprintf(stderr,"%g + %gi\n",(double)((c)->r),(double)((c)->i) ) 151 + 152 + 153 + #ifdef KISS_FFT_USE_ALLOCA 154 + // define this to allow use of alloca instead of malloc for temporary buffers 155 + // Temporary buffers are used in two case: 156 + // 1. FFT sizes that have "bad" factors. i.e. not 2,3 and 5 157 + // 2. "in-place" FFTs. Notice the quotes, since kissfft does not really do an in-place transform. 158 + #include <alloca.h> 159 + #define KISS_FFT_TMP_ALLOC(nbytes) alloca(nbytes) 160 + #define KISS_FFT_TMP_FREE(ptr) 161 + #else 162 + #define KISS_FFT_TMP_ALLOC(nbytes) KISS_FFT_MALLOC(nbytes) 163 + #define KISS_FFT_TMP_FREE(ptr) KISS_FFT_FREE(ptr) 164 + #endif
+408
kiss_fft.c
··· 1 + /* 2 + Copyright (c) 2003-2010, Mark Borgerding 3 + 4 + All rights reserved. 5 + 6 + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 7 + 8 + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 9 + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 10 + * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 + 12 + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 13 + */ 14 + 15 + 16 + #include "_kiss_fft_guts.h" 17 + /* The guts header contains all the multiplication and addition macros that are defined for 18 + fixed or floating point complex numbers. It also delares the kf_ internal functions. 19 + */ 20 + 21 + static void kf_bfly2( 22 + kiss_fft_cpx * Fout, 23 + const size_t fstride, 24 + const kiss_fft_cfg st, 25 + int m 26 + ) 27 + { 28 + kiss_fft_cpx * Fout2; 29 + kiss_fft_cpx * tw1 = st->twiddles; 30 + kiss_fft_cpx t; 31 + Fout2 = Fout + m; 32 + do{ 33 + C_FIXDIV(*Fout,2); C_FIXDIV(*Fout2,2); 34 + 35 + C_MUL (t, *Fout2 , *tw1); 36 + tw1 += fstride; 37 + C_SUB( *Fout2 , *Fout , t ); 38 + C_ADDTO( *Fout , t ); 39 + ++Fout2; 40 + ++Fout; 41 + }while (--m); 42 + } 43 + 44 + static void kf_bfly4( 45 + kiss_fft_cpx * Fout, 46 + const size_t fstride, 47 + const kiss_fft_cfg st, 48 + const size_t m 49 + ) 50 + { 51 + kiss_fft_cpx *tw1,*tw2,*tw3; 52 + kiss_fft_cpx scratch[6]; 53 + size_t k=m; 54 + const size_t m2=2*m; 55 + const size_t m3=3*m; 56 + 57 + 58 + tw3 = tw2 = tw1 = st->twiddles; 59 + 60 + do { 61 + C_FIXDIV(*Fout,4); C_FIXDIV(Fout[m],4); C_FIXDIV(Fout[m2],4); C_FIXDIV(Fout[m3],4); 62 + 63 + C_MUL(scratch[0],Fout[m] , *tw1 ); 64 + C_MUL(scratch[1],Fout[m2] , *tw2 ); 65 + C_MUL(scratch[2],Fout[m3] , *tw3 ); 66 + 67 + C_SUB( scratch[5] , *Fout, scratch[1] ); 68 + C_ADDTO(*Fout, scratch[1]); 69 + C_ADD( scratch[3] , scratch[0] , scratch[2] ); 70 + C_SUB( scratch[4] , scratch[0] , scratch[2] ); 71 + C_SUB( Fout[m2], *Fout, scratch[3] ); 72 + tw1 += fstride; 73 + tw2 += fstride*2; 74 + tw3 += fstride*3; 75 + C_ADDTO( *Fout , scratch[3] ); 76 + 77 + if(st->inverse) { 78 + Fout[m].r = scratch[5].r - scratch[4].i; 79 + Fout[m].i = scratch[5].i + scratch[4].r; 80 + Fout[m3].r = scratch[5].r + scratch[4].i; 81 + Fout[m3].i = scratch[5].i - scratch[4].r; 82 + }else{ 83 + Fout[m].r = scratch[5].r + scratch[4].i; 84 + Fout[m].i = scratch[5].i - scratch[4].r; 85 + Fout[m3].r = scratch[5].r - scratch[4].i; 86 + Fout[m3].i = scratch[5].i + scratch[4].r; 87 + } 88 + ++Fout; 89 + }while(--k); 90 + } 91 + 92 + static void kf_bfly3( 93 + kiss_fft_cpx * Fout, 94 + const size_t fstride, 95 + const kiss_fft_cfg st, 96 + size_t m 97 + ) 98 + { 99 + size_t k=m; 100 + const size_t m2 = 2*m; 101 + kiss_fft_cpx *tw1,*tw2; 102 + kiss_fft_cpx scratch[5]; 103 + kiss_fft_cpx epi3; 104 + epi3 = st->twiddles[fstride*m]; 105 + 106 + tw1=tw2=st->twiddles; 107 + 108 + do{ 109 + C_FIXDIV(*Fout,3); C_FIXDIV(Fout[m],3); C_FIXDIV(Fout[m2],3); 110 + 111 + C_MUL(scratch[1],Fout[m] , *tw1); 112 + C_MUL(scratch[2],Fout[m2] , *tw2); 113 + 114 + C_ADD(scratch[3],scratch[1],scratch[2]); 115 + C_SUB(scratch[0],scratch[1],scratch[2]); 116 + tw1 += fstride; 117 + tw2 += fstride*2; 118 + 119 + Fout[m].r = Fout->r - HALF_OF(scratch[3].r); 120 + Fout[m].i = Fout->i - HALF_OF(scratch[3].i); 121 + 122 + C_MULBYSCALAR( scratch[0] , epi3.i ); 123 + 124 + C_ADDTO(*Fout,scratch[3]); 125 + 126 + Fout[m2].r = Fout[m].r + scratch[0].i; 127 + Fout[m2].i = Fout[m].i - scratch[0].r; 128 + 129 + Fout[m].r -= scratch[0].i; 130 + Fout[m].i += scratch[0].r; 131 + 132 + ++Fout; 133 + }while(--k); 134 + } 135 + 136 + static void kf_bfly5( 137 + kiss_fft_cpx * Fout, 138 + const size_t fstride, 139 + const kiss_fft_cfg st, 140 + int m 141 + ) 142 + { 143 + kiss_fft_cpx *Fout0,*Fout1,*Fout2,*Fout3,*Fout4; 144 + int u; 145 + kiss_fft_cpx scratch[13]; 146 + kiss_fft_cpx * twiddles = st->twiddles; 147 + kiss_fft_cpx *tw; 148 + kiss_fft_cpx ya,yb; 149 + ya = twiddles[fstride*m]; 150 + yb = twiddles[fstride*2*m]; 151 + 152 + Fout0=Fout; 153 + Fout1=Fout0+m; 154 + Fout2=Fout0+2*m; 155 + Fout3=Fout0+3*m; 156 + Fout4=Fout0+4*m; 157 + 158 + tw=st->twiddles; 159 + for ( u=0; u<m; ++u ) { 160 + C_FIXDIV( *Fout0,5); C_FIXDIV( *Fout1,5); C_FIXDIV( *Fout2,5); C_FIXDIV( *Fout3,5); C_FIXDIV( *Fout4,5); 161 + scratch[0] = *Fout0; 162 + 163 + C_MUL(scratch[1] ,*Fout1, tw[u*fstride]); 164 + C_MUL(scratch[2] ,*Fout2, tw[2*u*fstride]); 165 + C_MUL(scratch[3] ,*Fout3, tw[3*u*fstride]); 166 + C_MUL(scratch[4] ,*Fout4, tw[4*u*fstride]); 167 + 168 + C_ADD( scratch[7],scratch[1],scratch[4]); 169 + C_SUB( scratch[10],scratch[1],scratch[4]); 170 + C_ADD( scratch[8],scratch[2],scratch[3]); 171 + C_SUB( scratch[9],scratch[2],scratch[3]); 172 + 173 + Fout0->r += scratch[7].r + scratch[8].r; 174 + Fout0->i += scratch[7].i + scratch[8].i; 175 + 176 + scratch[5].r = scratch[0].r + S_MUL(scratch[7].r,ya.r) + S_MUL(scratch[8].r,yb.r); 177 + scratch[5].i = scratch[0].i + S_MUL(scratch[7].i,ya.r) + S_MUL(scratch[8].i,yb.r); 178 + 179 + scratch[6].r = S_MUL(scratch[10].i,ya.i) + S_MUL(scratch[9].i,yb.i); 180 + scratch[6].i = -S_MUL(scratch[10].r,ya.i) - S_MUL(scratch[9].r,yb.i); 181 + 182 + C_SUB(*Fout1,scratch[5],scratch[6]); 183 + C_ADD(*Fout4,scratch[5],scratch[6]); 184 + 185 + scratch[11].r = scratch[0].r + S_MUL(scratch[7].r,yb.r) + S_MUL(scratch[8].r,ya.r); 186 + scratch[11].i = scratch[0].i + S_MUL(scratch[7].i,yb.r) + S_MUL(scratch[8].i,ya.r); 187 + scratch[12].r = - S_MUL(scratch[10].i,yb.i) + S_MUL(scratch[9].i,ya.i); 188 + scratch[12].i = S_MUL(scratch[10].r,yb.i) - S_MUL(scratch[9].r,ya.i); 189 + 190 + C_ADD(*Fout2,scratch[11],scratch[12]); 191 + C_SUB(*Fout3,scratch[11],scratch[12]); 192 + 193 + ++Fout0;++Fout1;++Fout2;++Fout3;++Fout4; 194 + } 195 + } 196 + 197 + /* perform the butterfly for one stage of a mixed radix FFT */ 198 + static void kf_bfly_generic( 199 + kiss_fft_cpx * Fout, 200 + const size_t fstride, 201 + const kiss_fft_cfg st, 202 + int m, 203 + int p 204 + ) 205 + { 206 + int u,k,q1,q; 207 + kiss_fft_cpx * twiddles = st->twiddles; 208 + kiss_fft_cpx t; 209 + int Norig = st->nfft; 210 + 211 + kiss_fft_cpx * scratch = (kiss_fft_cpx*)KISS_FFT_TMP_ALLOC(sizeof(kiss_fft_cpx)*p); 212 + 213 + for ( u=0; u<m; ++u ) { 214 + k=u; 215 + for ( q1=0 ; q1<p ; ++q1 ) { 216 + scratch[q1] = Fout[ k ]; 217 + C_FIXDIV(scratch[q1],p); 218 + k += m; 219 + } 220 + 221 + k=u; 222 + for ( q1=0 ; q1<p ; ++q1 ) { 223 + int twidx=0; 224 + Fout[ k ] = scratch[0]; 225 + for (q=1;q<p;++q ) { 226 + twidx += fstride * k; 227 + if (twidx>=Norig) twidx-=Norig; 228 + C_MUL(t,scratch[q] , twiddles[twidx] ); 229 + C_ADDTO( Fout[ k ] ,t); 230 + } 231 + k += m; 232 + } 233 + } 234 + KISS_FFT_TMP_FREE(scratch); 235 + } 236 + 237 + static 238 + void kf_work( 239 + kiss_fft_cpx * Fout, 240 + const kiss_fft_cpx * f, 241 + const size_t fstride, 242 + int in_stride, 243 + int * factors, 244 + const kiss_fft_cfg st 245 + ) 246 + { 247 + kiss_fft_cpx * Fout_beg=Fout; 248 + const int p=*factors++; /* the radix */ 249 + const int m=*factors++; /* stage's fft length/p */ 250 + const kiss_fft_cpx * Fout_end = Fout + p*m; 251 + 252 + #ifdef _OPENMP 253 + // use openmp extensions at the 254 + // top-level (not recursive) 255 + if (fstride==1 && p<=5) 256 + { 257 + int k; 258 + 259 + // execute the p different work units in different threads 260 + # pragma omp parallel for 261 + for (k=0;k<p;++k) 262 + kf_work( Fout +k*m, f+ fstride*in_stride*k,fstride*p,in_stride,factors,st); 263 + // all threads have joined by this point 264 + 265 + switch (p) { 266 + case 2: kf_bfly2(Fout,fstride,st,m); break; 267 + case 3: kf_bfly3(Fout,fstride,st,m); break; 268 + case 4: kf_bfly4(Fout,fstride,st,m); break; 269 + case 5: kf_bfly5(Fout,fstride,st,m); break; 270 + default: kf_bfly_generic(Fout,fstride,st,m,p); break; 271 + } 272 + return; 273 + } 274 + #endif 275 + 276 + if (m==1) { 277 + do{ 278 + *Fout = *f; 279 + f += fstride*in_stride; 280 + }while(++Fout != Fout_end ); 281 + }else{ 282 + do{ 283 + // recursive call: 284 + // DFT of size m*p performed by doing 285 + // p instances of smaller DFTs of size m, 286 + // each one takes a decimated version of the input 287 + kf_work( Fout , f, fstride*p, in_stride, factors,st); 288 + f += fstride*in_stride; 289 + }while( (Fout += m) != Fout_end ); 290 + } 291 + 292 + Fout=Fout_beg; 293 + 294 + // recombine the p smaller DFTs 295 + switch (p) { 296 + case 2: kf_bfly2(Fout,fstride,st,m); break; 297 + case 3: kf_bfly3(Fout,fstride,st,m); break; 298 + case 4: kf_bfly4(Fout,fstride,st,m); break; 299 + case 5: kf_bfly5(Fout,fstride,st,m); break; 300 + default: kf_bfly_generic(Fout,fstride,st,m,p); break; 301 + } 302 + } 303 + 304 + /* facbuf is populated by p1,m1,p2,m2, ... 305 + where 306 + p[i] * m[i] = m[i-1] 307 + m0 = n */ 308 + static 309 + void kf_factor(int n,int * facbuf) 310 + { 311 + int p=4; 312 + double floor_sqrt; 313 + floor_sqrt = floor( sqrt((double)n) ); 314 + 315 + /*factor out powers of 4, powers of 2, then any remaining primes */ 316 + do { 317 + while (n % p) { 318 + switch (p) { 319 + case 4: p = 2; break; 320 + case 2: p = 3; break; 321 + default: p += 2; break; 322 + } 323 + if (p > floor_sqrt) 324 + p = n; /* no more factors, skip to end */ 325 + } 326 + n /= p; 327 + *facbuf++ = p; 328 + *facbuf++ = n; 329 + } while (n > 1); 330 + } 331 + 332 + /* 333 + * 334 + * User-callable function to allocate all necessary storage space for the fft. 335 + * 336 + * The return value is a contiguous block of memory, allocated with malloc. As such, 337 + * It can be freed with free(), rather than a kiss_fft-specific function. 338 + * */ 339 + kiss_fft_cfg kiss_fft_alloc(int nfft,int inverse_fft,void * mem,size_t * lenmem ) 340 + { 341 + kiss_fft_cfg st=NULL; 342 + size_t memneeded = sizeof(struct kiss_fft_state) 343 + + sizeof(kiss_fft_cpx)*(nfft-1); /* twiddle factors*/ 344 + 345 + if ( lenmem==NULL ) { 346 + st = ( kiss_fft_cfg)KISS_FFT_MALLOC( memneeded ); 347 + }else{ 348 + if (mem != NULL && *lenmem >= memneeded) 349 + st = (kiss_fft_cfg)mem; 350 + *lenmem = memneeded; 351 + } 352 + if (st) { 353 + int i; 354 + st->nfft=nfft; 355 + st->inverse = inverse_fft; 356 + 357 + for (i=0;i<nfft;++i) { 358 + const double pi=3.141592653589793238462643383279502884197169399375105820974944; 359 + double phase = -2*pi*i / nfft; 360 + if (st->inverse) 361 + phase *= -1; 362 + kf_cexp(st->twiddles+i, phase ); 363 + } 364 + 365 + kf_factor(nfft,st->factors); 366 + } 367 + return st; 368 + } 369 + 370 + 371 + void kiss_fft_stride(kiss_fft_cfg st,const kiss_fft_cpx *fin,kiss_fft_cpx *fout,int in_stride) 372 + { 373 + if (fin == fout) { 374 + //NOTE: this is not really an in-place FFT algorithm. 375 + //It just performs an out-of-place FFT into a temp buffer 376 + kiss_fft_cpx * tmpbuf = (kiss_fft_cpx*)KISS_FFT_TMP_ALLOC( sizeof(kiss_fft_cpx)*st->nfft); 377 + kf_work(tmpbuf,fin,1,in_stride, st->factors,st); 378 + memcpy(fout,tmpbuf,sizeof(kiss_fft_cpx)*st->nfft); 379 + KISS_FFT_TMP_FREE(tmpbuf); 380 + }else{ 381 + kf_work( fout, fin, 1,in_stride, st->factors,st ); 382 + } 383 + } 384 + 385 + void kiss_fft(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout) 386 + { 387 + kiss_fft_stride(cfg,fin,fout,1); 388 + } 389 + 390 + 391 + void kiss_fft_cleanup(void) 392 + { 393 + // nothing needed any more 394 + } 395 + 396 + int kiss_fft_next_fast_size(int n) 397 + { 398 + while(1) { 399 + int m=n; 400 + while ( (m%2) == 0 ) m/=2; 401 + while ( (m%3) == 0 ) m/=3; 402 + while ( (m%5) == 0 ) m/=5; 403 + if (m<=1) 404 + break; /* n is completely factorable by twos, threes, and fives */ 405 + n++; 406 + } 407 + return n; 408 + }
+124
kiss_fft.h
··· 1 + #ifndef KISS_FFT_H 2 + #define KISS_FFT_H 3 + 4 + #include <stdlib.h> 5 + #include <stdio.h> 6 + #include <math.h> 7 + #include <string.h> 8 + 9 + #ifdef __cplusplus 10 + extern "C" { 11 + #endif 12 + 13 + /* 14 + ATTENTION! 15 + If you would like a : 16 + -- a utility that will handle the caching of fft objects 17 + -- real-only (no imaginary time component ) FFT 18 + -- a multi-dimensional FFT 19 + -- a command-line utility to perform ffts 20 + -- a command-line utility to perform fast-convolution filtering 21 + 22 + Then see kfc.h kiss_fftr.h kiss_fftnd.h fftutil.c kiss_fastfir.c 23 + in the tools/ directory. 24 + */ 25 + 26 + #ifdef USE_SIMD 27 + # include <xmmintrin.h> 28 + # define kiss_fft_scalar __m128 29 + #define KISS_FFT_MALLOC(nbytes) _mm_malloc(nbytes,16) 30 + #define KISS_FFT_FREE _mm_free 31 + #else 32 + #define KISS_FFT_MALLOC malloc 33 + #define KISS_FFT_FREE free 34 + #endif 35 + 36 + 37 + #ifdef FIXED_POINT 38 + #include <sys/types.h> 39 + # if (FIXED_POINT == 32) 40 + # define kiss_fft_scalar int32_t 41 + # else 42 + # define kiss_fft_scalar int16_t 43 + # endif 44 + #else 45 + # ifndef kiss_fft_scalar 46 + /* default is float */ 47 + # define kiss_fft_scalar float 48 + # endif 49 + #endif 50 + 51 + typedef struct { 52 + kiss_fft_scalar r; 53 + kiss_fft_scalar i; 54 + }kiss_fft_cpx; 55 + 56 + typedef struct kiss_fft_state* kiss_fft_cfg; 57 + 58 + /* 59 + * kiss_fft_alloc 60 + * 61 + * Initialize a FFT (or IFFT) algorithm's cfg/state buffer. 62 + * 63 + * typical usage: kiss_fft_cfg mycfg=kiss_fft_alloc(1024,0,NULL,NULL); 64 + * 65 + * The return value from fft_alloc is a cfg buffer used internally 66 + * by the fft routine or NULL. 67 + * 68 + * If lenmem is NULL, then kiss_fft_alloc will allocate a cfg buffer using malloc. 69 + * The returned value should be free()d when done to avoid memory leaks. 70 + * 71 + * The state can be placed in a user supplied buffer 'mem': 72 + * If lenmem is not NULL and mem is not NULL and *lenmem is large enough, 73 + * then the function places the cfg in mem and the size used in *lenmem 74 + * and returns mem. 75 + * 76 + * If lenmem is not NULL and ( mem is NULL or *lenmem is not large enough), 77 + * then the function returns NULL and places the minimum cfg 78 + * buffer size in *lenmem. 79 + * */ 80 + 81 + kiss_fft_cfg kiss_fft_alloc(int nfft,int inverse_fft,void * mem,size_t * lenmem); 82 + 83 + /* 84 + * kiss_fft(cfg,in_out_buf) 85 + * 86 + * Perform an FFT on a complex input buffer. 87 + * for a forward FFT, 88 + * fin should be f[0] , f[1] , ... ,f[nfft-1] 89 + * fout will be F[0] , F[1] , ... ,F[nfft-1] 90 + * Note that each element is complex and can be accessed like 91 + f[k].r and f[k].i 92 + * */ 93 + void kiss_fft(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout); 94 + 95 + /* 96 + A more generic version of the above function. It reads its input from every Nth sample. 97 + * */ 98 + void kiss_fft_stride(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout,int fin_stride); 99 + 100 + /* If kiss_fft_alloc allocated a buffer, it is one contiguous 101 + buffer and can be simply free()d when no longer needed*/ 102 + #define kiss_fft_free free 103 + 104 + /* 105 + Cleans up some memory that gets managed internally. Not necessary to call, but it might clean up 106 + your compiler output to call this before you exit. 107 + */ 108 + void kiss_fft_cleanup(void); 109 + 110 + 111 + /* 112 + * Returns the smallest integer k, such that k>=n and k has only "fast" factors (2,3,5) 113 + */ 114 + int kiss_fft_next_fast_size(int n); 115 + 116 + /* for real ffts, we need an even size */ 117 + #define kiss_fftr_next_fast_size_real(n) \ 118 + (kiss_fft_next_fast_size( ((n)+1)>>1)<<1) 119 + 120 + #ifdef __cplusplus 121 + } 122 + #endif 123 + 124 + #endif
+299
kissfft.hh
··· 1 + #ifndef KISSFFT_CLASS_HH 2 + #include <complex> 3 + #include <vector> 4 + 5 + namespace kissfft_utils { 6 + 7 + template <typename T_scalar> 8 + struct traits 9 + { 10 + typedef T_scalar scalar_type; 11 + typedef std::complex<scalar_type> cpx_type; 12 + void fill_twiddles( std::complex<T_scalar> * dst ,int nfft,bool inverse) 13 + { 14 + T_scalar phinc = (inverse?2:-2)* acos( (T_scalar) -1) / nfft; 15 + for (int i=0;i<nfft;++i) 16 + dst[i] = exp( std::complex<T_scalar>(0,i*phinc) ); 17 + } 18 + 19 + void prepare( 20 + std::vector< std::complex<T_scalar> > & dst, 21 + int nfft,bool inverse, 22 + std::vector<int> & stageRadix, 23 + std::vector<int> & stageRemainder ) 24 + { 25 + _twiddles.resize(nfft); 26 + fill_twiddles( &_twiddles[0],nfft,inverse); 27 + dst = _twiddles; 28 + 29 + //factorize 30 + //start factoring out 4's, then 2's, then 3,5,7,9,... 31 + int n= nfft; 32 + int p=4; 33 + do { 34 + while (n % p) { 35 + switch (p) { 36 + case 4: p = 2; break; 37 + case 2: p = 3; break; 38 + default: p += 2; break; 39 + } 40 + if (p*p>n) 41 + p=n;// no more factors 42 + } 43 + n /= p; 44 + stageRadix.push_back(p); 45 + stageRemainder.push_back(n); 46 + }while(n>1); 47 + } 48 + std::vector<cpx_type> _twiddles; 49 + 50 + 51 + const cpx_type twiddle(int i) { return _twiddles[i]; } 52 + }; 53 + 54 + } 55 + 56 + template <typename T_Scalar, 57 + typename T_traits=kissfft_utils::traits<T_Scalar> 58 + > 59 + class kissfft 60 + { 61 + public: 62 + typedef T_traits traits_type; 63 + typedef typename traits_type::scalar_type scalar_type; 64 + typedef typename traits_type::cpx_type cpx_type; 65 + 66 + kissfft(int nfft,bool inverse,const traits_type & traits=traits_type() ) 67 + :_nfft(nfft),_inverse(inverse),_traits(traits) 68 + { 69 + _traits.prepare(_twiddles, _nfft,_inverse ,_stageRadix, _stageRemainder); 70 + } 71 + 72 + void transform(const cpx_type * src , cpx_type * dst) 73 + { 74 + kf_work(0, dst, src, 1,1); 75 + } 76 + 77 + private: 78 + void kf_work( int stage,cpx_type * Fout, const cpx_type * f, size_t fstride,size_t in_stride) 79 + { 80 + int p = _stageRadix[stage]; 81 + int m = _stageRemainder[stage]; 82 + cpx_type * Fout_beg = Fout; 83 + cpx_type * Fout_end = Fout + p*m; 84 + 85 + if (m==1) { 86 + do{ 87 + *Fout = *f; 88 + f += fstride*in_stride; 89 + }while(++Fout != Fout_end ); 90 + }else{ 91 + do{ 92 + // recursive call: 93 + // DFT of size m*p performed by doing 94 + // p instances of smaller DFTs of size m, 95 + // each one takes a decimated version of the input 96 + kf_work(stage+1, Fout , f, fstride*p,in_stride); 97 + f += fstride*in_stride; 98 + }while( (Fout += m) != Fout_end ); 99 + } 100 + 101 + Fout=Fout_beg; 102 + 103 + // recombine the p smaller DFTs 104 + switch (p) { 105 + case 2: kf_bfly2(Fout,fstride,m); break; 106 + case 3: kf_bfly3(Fout,fstride,m); break; 107 + case 4: kf_bfly4(Fout,fstride,m); break; 108 + case 5: kf_bfly5(Fout,fstride,m); break; 109 + default: kf_bfly_generic(Fout,fstride,m,p); break; 110 + } 111 + } 112 + 113 + // these were #define macros in the original kiss_fft 114 + void C_ADD( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a+b;} 115 + void C_MUL( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a*b;} 116 + void C_SUB( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a-b;} 117 + void C_ADDTO( cpx_type & c,const cpx_type & a) { c+=a;} 118 + void C_FIXDIV( cpx_type & ,int ) {} // NO-OP for float types 119 + scalar_type S_MUL( const scalar_type & a,const scalar_type & b) { return a*b;} 120 + scalar_type HALF_OF( const scalar_type & a) { return a*.5;} 121 + void C_MULBYSCALAR(cpx_type & c,const scalar_type & a) {c*=a;} 122 + 123 + void kf_bfly2( cpx_type * Fout, const size_t fstride, int m) 124 + { 125 + for (int k=0;k<m;++k) { 126 + cpx_type t = Fout[m+k] * _traits.twiddle(k*fstride); 127 + Fout[m+k] = Fout[k] - t; 128 + Fout[k] += t; 129 + } 130 + } 131 + 132 + void kf_bfly4( cpx_type * Fout, const size_t fstride, const size_t m) 133 + { 134 + cpx_type scratch[7]; 135 + int negative_if_inverse = _inverse * -2 +1; 136 + for (size_t k=0;k<m;++k) { 137 + scratch[0] = Fout[k+m] * _traits.twiddle(k*fstride); 138 + scratch[1] = Fout[k+2*m] * _traits.twiddle(k*fstride*2); 139 + scratch[2] = Fout[k+3*m] * _traits.twiddle(k*fstride*3); 140 + scratch[5] = Fout[k] - scratch[1]; 141 + 142 + Fout[k] += scratch[1]; 143 + scratch[3] = scratch[0] + scratch[2]; 144 + scratch[4] = scratch[0] - scratch[2]; 145 + scratch[4] = cpx_type( scratch[4].imag()*negative_if_inverse , -scratch[4].real()* negative_if_inverse ); 146 + 147 + Fout[k+2*m] = Fout[k] - scratch[3]; 148 + Fout[k] += scratch[3]; 149 + Fout[k+m] = scratch[5] + scratch[4]; 150 + Fout[k+3*m] = scratch[5] - scratch[4]; 151 + } 152 + } 153 + 154 + void kf_bfly3( cpx_type * Fout, const size_t fstride, const size_t m) 155 + { 156 + size_t k=m; 157 + const size_t m2 = 2*m; 158 + cpx_type *tw1,*tw2; 159 + cpx_type scratch[5]; 160 + cpx_type epi3; 161 + epi3 = _twiddles[fstride*m]; 162 + 163 + tw1=tw2=&_twiddles[0]; 164 + 165 + do{ 166 + C_FIXDIV(*Fout,3); C_FIXDIV(Fout[m],3); C_FIXDIV(Fout[m2],3); 167 + 168 + C_MUL(scratch[1],Fout[m] , *tw1); 169 + C_MUL(scratch[2],Fout[m2] , *tw2); 170 + 171 + C_ADD(scratch[3],scratch[1],scratch[2]); 172 + C_SUB(scratch[0],scratch[1],scratch[2]); 173 + tw1 += fstride; 174 + tw2 += fstride*2; 175 + 176 + Fout[m] = cpx_type( Fout->real() - HALF_OF(scratch[3].real() ) , Fout->imag() - HALF_OF(scratch[3].imag() ) ); 177 + 178 + C_MULBYSCALAR( scratch[0] , epi3.imag() ); 179 + 180 + C_ADDTO(*Fout,scratch[3]); 181 + 182 + Fout[m2] = cpx_type( Fout[m].real() + scratch[0].imag() , Fout[m].imag() - scratch[0].real() ); 183 + 184 + C_ADDTO( Fout[m] , cpx_type( -scratch[0].imag(),scratch[0].real() ) ); 185 + ++Fout; 186 + }while(--k); 187 + } 188 + 189 + void kf_bfly5( cpx_type * Fout, const size_t fstride, const size_t m) 190 + { 191 + cpx_type *Fout0,*Fout1,*Fout2,*Fout3,*Fout4; 192 + size_t u; 193 + cpx_type scratch[13]; 194 + cpx_type * twiddles = &_twiddles[0]; 195 + cpx_type *tw; 196 + cpx_type ya,yb; 197 + ya = twiddles[fstride*m]; 198 + yb = twiddles[fstride*2*m]; 199 + 200 + Fout0=Fout; 201 + Fout1=Fout0+m; 202 + Fout2=Fout0+2*m; 203 + Fout3=Fout0+3*m; 204 + Fout4=Fout0+4*m; 205 + 206 + tw=twiddles; 207 + for ( u=0; u<m; ++u ) { 208 + C_FIXDIV( *Fout0,5); C_FIXDIV( *Fout1,5); C_FIXDIV( *Fout2,5); C_FIXDIV( *Fout3,5); C_FIXDIV( *Fout4,5); 209 + scratch[0] = *Fout0; 210 + 211 + C_MUL(scratch[1] ,*Fout1, tw[u*fstride]); 212 + C_MUL(scratch[2] ,*Fout2, tw[2*u*fstride]); 213 + C_MUL(scratch[3] ,*Fout3, tw[3*u*fstride]); 214 + C_MUL(scratch[4] ,*Fout4, tw[4*u*fstride]); 215 + 216 + C_ADD( scratch[7],scratch[1],scratch[4]); 217 + C_SUB( scratch[10],scratch[1],scratch[4]); 218 + C_ADD( scratch[8],scratch[2],scratch[3]); 219 + C_SUB( scratch[9],scratch[2],scratch[3]); 220 + 221 + C_ADDTO( *Fout0, scratch[7]); 222 + C_ADDTO( *Fout0, scratch[8]); 223 + 224 + scratch[5] = scratch[0] + cpx_type( 225 + S_MUL(scratch[7].real(),ya.real() ) + S_MUL(scratch[8].real() ,yb.real() ), 226 + S_MUL(scratch[7].imag(),ya.real()) + S_MUL(scratch[8].imag(),yb.real()) 227 + ); 228 + 229 + scratch[6] = cpx_type( 230 + S_MUL(scratch[10].imag(),ya.imag()) + S_MUL(scratch[9].imag(),yb.imag()), 231 + -S_MUL(scratch[10].real(),ya.imag()) - S_MUL(scratch[9].real(),yb.imag()) 232 + ); 233 + 234 + C_SUB(*Fout1,scratch[5],scratch[6]); 235 + C_ADD(*Fout4,scratch[5],scratch[6]); 236 + 237 + scratch[11] = scratch[0] + 238 + cpx_type( 239 + S_MUL(scratch[7].real(),yb.real()) + S_MUL(scratch[8].real(),ya.real()), 240 + S_MUL(scratch[7].imag(),yb.real()) + S_MUL(scratch[8].imag(),ya.real()) 241 + ); 242 + 243 + scratch[12] = cpx_type( 244 + -S_MUL(scratch[10].imag(),yb.imag()) + S_MUL(scratch[9].imag(),ya.imag()), 245 + S_MUL(scratch[10].real(),yb.imag()) - S_MUL(scratch[9].real(),ya.imag()) 246 + ); 247 + 248 + C_ADD(*Fout2,scratch[11],scratch[12]); 249 + C_SUB(*Fout3,scratch[11],scratch[12]); 250 + 251 + ++Fout0;++Fout1;++Fout2;++Fout3;++Fout4; 252 + } 253 + } 254 + 255 + /* perform the butterfly for one stage of a mixed radix FFT */ 256 + void kf_bfly_generic( 257 + cpx_type * Fout, 258 + const size_t fstride, 259 + int m, 260 + int p 261 + ) 262 + { 263 + int u,k,q1,q; 264 + cpx_type * twiddles = &_twiddles[0]; 265 + cpx_type t; 266 + int Norig = _nfft; 267 + cpx_type scratchbuf[p]; 268 + 269 + for ( u=0; u<m; ++u ) { 270 + k=u; 271 + for ( q1=0 ; q1<p ; ++q1 ) { 272 + scratchbuf[q1] = Fout[ k ]; 273 + C_FIXDIV(scratchbuf[q1],p); 274 + k += m; 275 + } 276 + 277 + k=u; 278 + for ( q1=0 ; q1<p ; ++q1 ) { 279 + int twidx=0; 280 + Fout[ k ] = scratchbuf[0]; 281 + for (q=1;q<p;++q ) { 282 + twidx += fstride * k; 283 + if (twidx>=Norig) twidx-=Norig; 284 + C_MUL(t,scratchbuf[q] , twiddles[twidx] ); 285 + C_ADDTO( Fout[ k ] ,t); 286 + } 287 + k += m; 288 + } 289 + } 290 + } 291 + 292 + int _nfft; 293 + bool _inverse; 294 + std::vector<cpx_type> _twiddles; 295 + std::vector<int> _stageRadix; 296 + std::vector<int> _stageRemainder; 297 + traits_type _traits; 298 + }; 299 + #endif
+108
test/Makefile
··· 1 + 2 + WARNINGS=-W -Wall -Wstrict-prototypes -Wmissing-prototypes -Waggregate-return \ 3 + -Wcast-align -Wcast-qual -Wnested-externs -Wshadow -Wbad-function-cast \ 4 + -Wwrite-strings 5 + 6 + CFLAGS=-O3 -I.. -I../tools $(WARNINGS) 7 + CFLAGS+=-ffast-math -fomit-frame-pointer 8 + #CFLAGS+=-funroll-loops 9 + #CFLAGS+=-march=prescott 10 + #CFLAGS+= -mtune=native 11 + # TIP: try adding -openmp or -fopenmp to enable OPENMP directives and use of multiple cores 12 + #CFLAGS+=-fopenmp 13 + CFLAGS+= $(CFLAGADD) 14 + 15 + 16 + ifeq "$(NFFT)" "" 17 + NFFT=1800 18 + endif 19 + ifeq "$(NUMFFTS)" "" 20 + NUMFFTS=10000 21 + endif 22 + 23 + ifeq "$(DATATYPE)" "" 24 + DATATYPE=float 25 + endif 26 + 27 + BENCHKISS=bm_kiss_$(DATATYPE) 28 + BENCHFFTW=bm_fftw_$(DATATYPE) 29 + SELFTEST=st_$(DATATYPE) 30 + TESTREAL=tr_$(DATATYPE) 31 + TESTKFC=tkfc_$(DATATYPE) 32 + FASTFILTREAL=ffr_$(DATATYPE) 33 + SELFTESTSRC=twotonetest.c 34 + 35 + 36 + TYPEFLAGS=-Dkiss_fft_scalar=$(DATATYPE) 37 + 38 + ifeq "$(DATATYPE)" "int16_t" 39 + TYPEFLAGS=-DFIXED_POINT=16 40 + endif 41 + 42 + ifeq "$(DATATYPE)" "int32_t" 43 + TYPEFLAGS=-DFIXED_POINT=32 44 + endif 45 + 46 + ifeq "$(DATATYPE)" "simd" 47 + TYPEFLAGS=-DUSE_SIMD=1 -msse 48 + endif 49 + 50 + 51 + ifeq "$(DATATYPE)" "float" 52 + # fftw needs to be built with --enable-float to build this lib 53 + FFTWLIB=-lfftw3f 54 + else 55 + FFTWLIB=-lfftw3 56 + endif 57 + 58 + FFTWLIBDIR=-L/usr/local/lib/ 59 + 60 + SRCFILES=../kiss_fft.c ../tools/kiss_fftnd.c ../tools/kiss_fftr.c pstats.c ../tools/kfc.c ../tools/kiss_fftndr.c 61 + 62 + all: tools $(BENCHKISS) $(SELFTEST) $(BENCHFFTW) $(TESTREAL) $(TESTKFC) 63 + 64 + tools: 65 + cd ../tools && make all 66 + 67 + 68 + $(SELFTEST): $(SELFTESTSRC) $(SRCFILES) 69 + $(CC) -o $@ $(CFLAGS) $(TYPEFLAGS) $+ -lm 70 + 71 + $(TESTKFC): $(SRCFILES) 72 + $(CC) -o $@ $(CFLAGS) -DKFC_TEST $(TYPEFLAGS) $+ -lm 73 + 74 + $(TESTREAL): test_real.c $(SRCFILES) 75 + $(CC) -o $@ $(CFLAGS) $(TYPEFLAGS) $+ -lm 76 + 77 + $(BENCHKISS): benchkiss.c $(SRCFILES) 78 + $(CC) -o $@ $(CFLAGS) $(TYPEFLAGS) $+ -lm 79 + 80 + $(BENCHFFTW): benchfftw.c pstats.c 81 + @echo "======attempting to build FFTW benchmark" 82 + @$(CC) -o $@ $(CFLAGS) -DDATATYPE$(DATATYPE) $+ $(FFTWLIB) $(FFTWLIBDIR) -lm || echo "FFTW not available for comparison" 83 + 84 + test: all 85 + @./$(TESTKFC) 86 + @echo "======1d & 2-d complex fft self test (type= $(DATATYPE) )" 87 + @./$(SELFTEST) 88 + @echo "======real FFT (type= $(DATATYPE) )" 89 + @./$(TESTREAL) 90 + @echo "======timing test (type=$(DATATYPE))" 91 + @./$(BENCHKISS) -x $(NUMFFTS) -n $(NFFT) 92 + @[ -x ./$(BENCHFFTW) ] && ./$(BENCHFFTW) -x $(NUMFFTS) -n $(NFFT) ||true 93 + @echo "======higher dimensions type=$(DATATYPE))" 94 + @./testkiss.py 95 + 96 + selftest.c: 97 + ./mk_test.py 10 12 14 > selftest.c 98 + selftest_short.c: 99 + ./mk_test.py -s 10 12 14 > selftest_short.c 100 + 101 + 102 + CXXFLAGS=-O3 -ffast-math -fomit-frame-pointer -I.. -I../tools -W -Wall 103 + testcpp: testcpp.cc ../kissfft.hh 104 + $(CXX) -o $@ $(CXXFLAGS) testcpp.cc -lm 105 + 106 + 107 + clean: 108 + rm -f *~ bm_* st_* tr_* kf_* tkfc_* ff_* ffr_* *.pyc *.pyo *.dat testcpp
+94
test/benchfftw.c
··· 1 + #include <stdio.h> 2 + #include <stdlib.h> 3 + #include <fftw3.h> 4 + #include <unistd.h> 5 + #include "pstats.h" 6 + 7 + #ifdef DATATYPEdouble 8 + 9 + #define CPXTYPE fftw_complex 10 + #define PLAN fftw_plan 11 + #define FFTMALLOC fftw_malloc 12 + #define MAKEPLAN fftw_plan_dft_1d 13 + #define DOFFT fftw_execute 14 + #define DESTROYPLAN fftw_destroy_plan 15 + #define FFTFREE fftw_free 16 + 17 + #elif defined(DATATYPEfloat) 18 + 19 + #define CPXTYPE fftwf_complex 20 + #define PLAN fftwf_plan 21 + #define FFTMALLOC fftwf_malloc 22 + #define MAKEPLAN fftwf_plan_dft_1d 23 + #define DOFFT fftwf_execute 24 + #define DESTROYPLAN fftwf_destroy_plan 25 + #define FFTFREE fftwf_free 26 + 27 + #endif 28 + 29 + #ifndef CPXTYPE 30 + int main(void) 31 + { 32 + fprintf(stderr,"Datatype not available in FFTW\n" ); 33 + return 0; 34 + } 35 + #else 36 + int main(int argc,char ** argv) 37 + { 38 + int nfft=1024; 39 + int isinverse=0; 40 + int numffts=1000,i; 41 + 42 + CPXTYPE * in=NULL; 43 + CPXTYPE * out=NULL; 44 + PLAN p; 45 + 46 + pstats_init(); 47 + 48 + while (1) { 49 + int c = getopt (argc, argv, "n:ix:h"); 50 + if (c == -1) 51 + break; 52 + switch (c) { 53 + case 'n': 54 + nfft = atoi (optarg); 55 + break; 56 + case 'x': 57 + numffts = atoi (optarg); 58 + break; 59 + case 'i': 60 + isinverse = 1; 61 + break; 62 + case 'h': 63 + case '?': 64 + default: 65 + fprintf(stderr,"options:\n-n N: complex fft length\n-i: inverse\n-x N: number of ffts to compute\n" 66 + ""); 67 + } 68 + } 69 + 70 + in=FFTMALLOC(sizeof(CPXTYPE) * nfft); 71 + out=FFTMALLOC(sizeof(CPXTYPE) * nfft); 72 + for (i=0;i<nfft;++i ) { 73 + in[i][0] = rand() - RAND_MAX/2; 74 + in[i][1] = rand() - RAND_MAX/2; 75 + } 76 + 77 + if ( isinverse ) 78 + p = MAKEPLAN(nfft, in, out, FFTW_BACKWARD, FFTW_ESTIMATE); 79 + else 80 + p = MAKEPLAN(nfft, in, out, FFTW_FORWARD, FFTW_ESTIMATE); 81 + 82 + for (i=0;i<numffts;++i) 83 + DOFFT(p); 84 + 85 + DESTROYPLAN(p); 86 + 87 + FFTFREE(in); FFTFREE(out); 88 + 89 + fprintf(stderr,"fftw\tnfft=%d\tnumffts=%d\n", nfft,numffts); 90 + pstats_report(); 91 + 92 + return 0; 93 + } 94 + #endif
+122
test/benchkiss.c
··· 1 + #include <stdio.h> 2 + #include <stdlib.h> 3 + #include <sys/times.h> 4 + #include <unistd.h> 5 + #include "kiss_fft.h" 6 + #include "kiss_fftr.h" 7 + #include "kiss_fftnd.h" 8 + #include "kiss_fftndr.h" 9 + 10 + #include "pstats.h" 11 + 12 + static 13 + int getdims(int * dims, char * arg) 14 + { 15 + char *s; 16 + int ndims=0; 17 + while ( (s=strtok( arg , ",") ) ) { 18 + dims[ndims++] = atoi(s); 19 + //printf("%s=%d\n",s,dims[ndims-1]); 20 + arg=NULL; 21 + } 22 + return ndims; 23 + } 24 + 25 + int main(int argc,char ** argv) 26 + { 27 + int k; 28 + int nfft[32]; 29 + int ndims = 1; 30 + int isinverse=0; 31 + int numffts=1000,i; 32 + kiss_fft_cpx * buf; 33 + kiss_fft_cpx * bufout; 34 + int real = 0; 35 + 36 + nfft[0] = 1024;// default 37 + 38 + while (1) { 39 + int c = getopt (argc, argv, "n:ix:r"); 40 + if (c == -1) 41 + break; 42 + switch (c) { 43 + case 'r': 44 + real = 1; 45 + break; 46 + case 'n': 47 + ndims = getdims(nfft, optarg ); 48 + if (nfft[0] != kiss_fft_next_fast_size(nfft[0]) ) { 49 + int ng = kiss_fft_next_fast_size(nfft[0]); 50 + fprintf(stderr,"warning: %d might be a better choice for speed than %d\n",ng,nfft[0]); 51 + } 52 + break; 53 + case 'x': 54 + numffts = atoi (optarg); 55 + break; 56 + case 'i': 57 + isinverse = 1; 58 + break; 59 + } 60 + } 61 + int nbytes = sizeof(kiss_fft_cpx); 62 + for (k=0;k<ndims;++k) 63 + nbytes *= nfft[k]; 64 + 65 + #ifdef USE_SIMD 66 + numffts /= 4; 67 + fprintf(stderr,"since SIMD implementation does 4 ffts at a time, numffts is being reduced to %d\n",numffts); 68 + #endif 69 + 70 + buf=(kiss_fft_cpx*)KISS_FFT_MALLOC(nbytes); 71 + bufout=(kiss_fft_cpx*)KISS_FFT_MALLOC(nbytes); 72 + memset(buf,0,nbytes); 73 + 74 + pstats_init(); 75 + 76 + if (ndims==1) { 77 + if (real) { 78 + kiss_fftr_cfg st = kiss_fftr_alloc( nfft[0] ,isinverse ,0,0); 79 + if (isinverse) 80 + for (i=0;i<numffts;++i) 81 + kiss_fftri( st ,(kiss_fft_cpx*)buf,(kiss_fft_scalar*)bufout ); 82 + else 83 + for (i=0;i<numffts;++i) 84 + kiss_fftr( st ,(kiss_fft_scalar*)buf,(kiss_fft_cpx*)bufout ); 85 + free(st); 86 + }else{ 87 + kiss_fft_cfg st = kiss_fft_alloc( nfft[0] ,isinverse ,0,0); 88 + for (i=0;i<numffts;++i) 89 + kiss_fft( st ,buf,bufout ); 90 + free(st); 91 + } 92 + }else{ 93 + if (real) { 94 + kiss_fftndr_cfg st = kiss_fftndr_alloc( nfft,ndims ,isinverse ,0,0); 95 + if (isinverse) 96 + for (i=0;i<numffts;++i) 97 + kiss_fftndri( st ,(kiss_fft_cpx*)buf,(kiss_fft_scalar*)bufout ); 98 + else 99 + for (i=0;i<numffts;++i) 100 + kiss_fftndr( st ,(kiss_fft_scalar*)buf,(kiss_fft_cpx*)bufout ); 101 + free(st); 102 + }else{ 103 + kiss_fftnd_cfg st= kiss_fftnd_alloc(nfft,ndims,isinverse ,0,0); 104 + for (i=0;i<numffts;++i) 105 + kiss_fftnd( st ,buf,bufout ); 106 + free(st); 107 + } 108 + } 109 + 110 + free(buf); free(bufout); 111 + 112 + fprintf(stderr,"KISS\tnfft="); 113 + for (k=0;k<ndims;++k) 114 + fprintf(stderr, "%d,",nfft[k]); 115 + fprintf(stderr,"\tnumffts=%d\n" ,numffts); 116 + pstats_report(); 117 + 118 + kiss_fft_cleanup(); 119 + 120 + return 0; 121 + } 122 +
+92
test/compfft.py
··· 1 + #!/usr/bin/env python 2 + 3 + # use FFTPACK as a baseline 4 + import FFT 5 + from Numeric import * 6 + import math 7 + import random 8 + import sys 9 + import struct 10 + import fft 11 + 12 + pi=math.pi 13 + e=math.e 14 + j=complex(0,1) 15 + lims=(-32768,32767) 16 + 17 + def randbuf(n,cpx=1): 18 + res = array( [ random.uniform( lims[0],lims[1] ) for i in range(n) ] ) 19 + if cpx: 20 + res = res + j*randbuf(n,0) 21 + return res 22 + 23 + def main(): 24 + from getopt import getopt 25 + import popen2 26 + opts,args = getopt( sys.argv[1:],'u:n:Rt:' ) 27 + opts=dict(opts) 28 + exitcode=0 29 + 30 + util = opts.get('-u','./kf_float') 31 + 32 + try: 33 + dims = [ int(d) for d in opts['-n'].split(',')] 34 + cpx = opts.get('-R') is None 35 + fmt=opts.get('-t','f') 36 + except KeyError: 37 + sys.stderr.write(""" 38 + usage: compfft.py 39 + -n d1[,d2,d3...] : FFT dimension(s) 40 + -u utilname : see sample_code/fftutil.c, default = ./kf_float 41 + -R : real-optimized version\n""") 42 + sys.exit(1) 43 + 44 + x = fft.make_random( dims ) 45 + 46 + cmd = '%s -n %s ' % ( util, ','.join([ str(d) for d in dims]) ) 47 + if cpx: 48 + xout = FFT.fftnd(x) 49 + xout = reshape(xout,(size(xout),)) 50 + else: 51 + cmd += '-R ' 52 + xout = FFT.real_fft(x) 53 + 54 + proc = popen2.Popen3( cmd , bufsize=len(x) ) 55 + 56 + proc.tochild.write( dopack( x , fmt ,cpx ) ) 57 + proc.tochild.close() 58 + xoutcomp = dounpack( proc.fromchild.read( ) , fmt ,1 ) 59 + #xoutcomp = reshape( xoutcomp , dims ) 60 + 61 + sig = xout * conjugate(xout) 62 + sigpow = sum( sig ) 63 + 64 + diff = xout-xoutcomp 65 + noisepow = sum( diff * conjugate(diff) ) 66 + 67 + snr = 10 * math.log10(abs( sigpow / noisepow ) ) 68 + if snr<100: 69 + print xout 70 + print xoutcomp 71 + exitcode=1 72 + print 'NFFT=%s,SNR = %f dB' % (str(dims),snr) 73 + sys.exit(exitcode) 74 + 75 + def dopack(x,fmt,cpx): 76 + x = reshape( x, ( size(x),) ) 77 + if cpx: 78 + s = ''.join( [ struct.pack('ff',c.real,c.imag) for c in x ] ) 79 + else: 80 + s = ''.join( [ struct.pack('f',c) for c in x ] ) 81 + return s 82 + 83 + def dounpack(x,fmt,cpx): 84 + uf = fmt * ( len(x) / 4 ) 85 + s = struct.unpack(uf,x) 86 + if cpx: 87 + return array(s[::2]) + array( s[1::2] )*j 88 + else: 89 + return array(s ) 90 + 91 + if __name__ == "__main__": 92 + main()
+129
test/doit.c
··· 1 + /* this program is in the public domain 2 + A program that helps the authors of the fine fftw library benchmark kiss 3 + */ 4 + 5 + #include "bench-user.h" 6 + #include <math.h> 7 + 8 + #include "kiss_fft.h" 9 + #include "kiss_fftnd.h" 10 + #include "kiss_fftr.h" 11 + 12 + BEGIN_BENCH_DOC 13 + BENCH_DOC("name", "kissfft") 14 + BENCH_DOC("version", "1.0.1") 15 + BENCH_DOC("year", "2004") 16 + BENCH_DOC("author", "Mark Borgerding") 17 + BENCH_DOC("language", "C") 18 + BENCH_DOC("url", "http://sourceforge.net/projects/kissfft/") 19 + BENCH_DOC("copyright", 20 + "Copyright (c) 2003,4 Mark Borgerding\n" 21 + "\n" 22 + "All rights reserved.\n" 23 + "\n" 24 + "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n" 25 + "\n" 26 + " * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n" 27 + " * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n" 28 + " * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n" 29 + "\n" 30 + "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n") 31 + END_BENCH_DOC 32 + 33 + int can_do(struct problem *p) 34 + { 35 + if (p->rank == 1) { 36 + if (p->kind == PROBLEM_REAL) { 37 + return (p->n[0] & 1) == 0; /* only even real is okay */ 38 + } else { 39 + return 1; 40 + } 41 + } else { 42 + return p->kind == PROBLEM_COMPLEX; 43 + } 44 + } 45 + 46 + static kiss_fft_cfg cfg=NULL; 47 + static kiss_fftr_cfg cfgr=NULL; 48 + static kiss_fftnd_cfg cfgnd=NULL; 49 + 50 + #define FAILIF( c ) \ 51 + if ( c ) do {\ 52 + fprintf(stderr,\ 53 + "kissfft: " #c " (file=%s:%d errno=%d %s)\n",\ 54 + __FILE__,__LINE__ , errno,strerror( errno ) ) ;\ 55 + exit(1);\ 56 + }while(0) 57 + 58 + 59 + 60 + void setup(struct problem *p) 61 + { 62 + size_t i; 63 + 64 + /* 65 + fprintf(stderr,"%s %s %d-d ", 66 + (p->sign == 1)?"Inverse":"Forward", 67 + p->kind == PROBLEM_COMPLEX?"Complex":"Real", 68 + p->rank); 69 + */ 70 + if (p->rank == 1) { 71 + if (p->kind == PROBLEM_COMPLEX) { 72 + cfg = kiss_fft_alloc (p->n[0], (p->sign == 1), 0, 0); 73 + FAILIF(cfg==NULL); 74 + }else{ 75 + cfgr = kiss_fftr_alloc (p->n[0], (p->sign == 1), 0, 0); 76 + FAILIF(cfgr==NULL); 77 + } 78 + }else{ 79 + int dims[5]; 80 + for (i=0;i<p->rank;++i){ 81 + dims[i] = p->n[i]; 82 + } 83 + /* multi-dimensional */ 84 + if (p->kind == PROBLEM_COMPLEX) { 85 + cfgnd = kiss_fftnd_alloc( dims , p->rank, (p->sign == 1), 0, 0 ); 86 + FAILIF(cfgnd==NULL); 87 + } 88 + } 89 + } 90 + 91 + void doit(int iter, struct problem *p) 92 + { 93 + int i; 94 + void *in = p->in; 95 + void *out = p->out; 96 + 97 + if (p->in_place) 98 + out = p->in; 99 + 100 + if (p->rank == 1) { 101 + if (p->kind == PROBLEM_COMPLEX){ 102 + for (i = 0; i < iter; ++i) 103 + kiss_fft (cfg, in, out); 104 + } else { 105 + /* PROBLEM_REAL */ 106 + if (p->sign == -1) /* FORWARD */ 107 + for (i = 0; i < iter; ++i) 108 + kiss_fftr (cfgr, in, out); 109 + else 110 + for (i = 0; i < iter; ++i) 111 + kiss_fftri (cfgr, in, out); 112 + } 113 + }else{ 114 + /* multi-dimensional */ 115 + for (i = 0; i < iter; ++i) 116 + kiss_fftnd(cfgnd,in,out); 117 + } 118 + } 119 + 120 + void done(struct problem *p) 121 + { 122 + free(cfg); 123 + cfg=NULL; 124 + free(cfgr); 125 + cfgr=NULL; 126 + free(cfgnd); 127 + cfgnd=NULL; 128 + UNUSED(p); 129 + }
+102
test/fastfir.py
··· 1 + #!/usr/bin/env python 2 + 3 + from Numeric import * 4 + from FFT import * 5 + 6 + def make_random(len): 7 + import random 8 + res=[] 9 + for i in range(int(len)): 10 + r=random.uniform(-1,1) 11 + i=random.uniform(-1,1) 12 + res.append( complex(r,i) ) 13 + return res 14 + 15 + def slowfilter(sig,h): 16 + translen = len(h)-1 17 + return convolve(sig,h)[translen:-translen] 18 + 19 + def nextpow2(x): 20 + return 2 ** math.ceil(math.log(x)/math.log(2)) 21 + 22 + def fastfilter(sig,h,nfft=None): 23 + if nfft is None: 24 + nfft = int( nextpow2( 2*len(h) ) ) 25 + H = fft( h , nfft ) 26 + scraplen = len(h)-1 27 + keeplen = nfft-scraplen 28 + res=[] 29 + isdone = 0 30 + lastidx = nfft 31 + idx0 = 0 32 + while not isdone: 33 + idx1 = idx0 + nfft 34 + if idx1 >= len(sig): 35 + idx1 = len(sig) 36 + lastidx = idx1-idx0 37 + if lastidx <= scraplen: 38 + break 39 + isdone = 1 40 + Fss = fft(sig[idx0:idx1],nfft) 41 + fm = Fss * H 42 + m = inverse_fft(fm) 43 + res.append( m[scraplen:lastidx] ) 44 + idx0 += keeplen 45 + return concatenate( res ) 46 + 47 + def main(): 48 + import sys 49 + from getopt import getopt 50 + opts,args = getopt(sys.argv[1:],'rn:l:') 51 + opts=dict(opts) 52 + 53 + siglen = int(opts.get('-l',1e4 ) ) 54 + hlen =50 55 + 56 + nfft = int(opts.get('-n',128) ) 57 + usereal = opts.has_key('-r') 58 + 59 + print 'nfft=%d'%nfft 60 + # make a signal 61 + sig = make_random( siglen ) 62 + # make an impulse response 63 + h = make_random( hlen ) 64 + #h=[1]*2+[0]*3 65 + if usereal: 66 + sig=[c.real for c in sig] 67 + h=[c.real for c in h] 68 + 69 + # perform MAC filtering 70 + yslow = slowfilter(sig,h) 71 + #print '<YSLOW>',yslow,'</YSLOW>' 72 + #yfast = fastfilter(sig,h,nfft) 73 + yfast = utilfastfilter(sig,h,nfft,usereal) 74 + #print yfast 75 + print 'len(yslow)=%d'%len(yslow) 76 + print 'len(yfast)=%d'%len(yfast) 77 + diff = yslow-yfast 78 + snr = 10*log10( abs( vdot(yslow,yslow) / vdot(diff,diff) ) ) 79 + print 'snr=%s' % snr 80 + if snr < 10.0: 81 + print 'h=',h 82 + print 'sig=',sig[:5],'...' 83 + print 'yslow=',yslow[:5],'...' 84 + print 'yfast=',yfast[:5],'...' 85 + 86 + def utilfastfilter(sig,h,nfft,usereal): 87 + import compfft 88 + import os 89 + open( 'sig.dat','w').write( compfft.dopack(sig,'f',not usereal) ) 90 + open( 'h.dat','w').write( compfft.dopack(h,'f',not usereal) ) 91 + if usereal: 92 + util = './fastconvr' 93 + else: 94 + util = './fastconv' 95 + cmd = 'time %s -n %d -i sig.dat -h h.dat -o out.dat' % (util, nfft) 96 + print cmd 97 + ec = os.system(cmd) 98 + print 'exited->',ec 99 + return compfft.dounpack(open('out.dat').read(),'f',not usereal) 100 + 101 + if __name__ == "__main__": 102 + main()
+196
test/fft.py
··· 1 + #!/usr/bin/env python 2 + 3 + import math 4 + import sys 5 + import random 6 + 7 + pi=math.pi 8 + e=math.e 9 + j=complex(0,1) 10 + 11 + def fft(f,inv): 12 + n=len(f) 13 + if n==1: 14 + return f 15 + 16 + for p in 2,3,5: 17 + if n%p==0: 18 + break 19 + else: 20 + raise Exception('%s not factorable ' % n) 21 + 22 + m = n/p 23 + Fout=[] 24 + for q in range(p): # 0,1 25 + fp = f[q::p] # every p'th time sample 26 + Fp = fft( fp ,inv) 27 + Fout.extend( Fp ) 28 + 29 + for u in range(m): 30 + scratch = Fout[u::m] # u to end in strides of m 31 + for q1 in range(p): 32 + k = q1*m + u # indices to Fout above that became scratch 33 + Fout[ k ] = scratch[0] # cuz e**0==1 in loop below 34 + for q in range(1,p): 35 + if inv: 36 + t = e ** ( j*2*pi*k*q/n ) 37 + else: 38 + t = e ** ( -j*2*pi*k*q/n ) 39 + Fout[ k ] += scratch[q] * t 40 + 41 + return Fout 42 + 43 + def rifft(F): 44 + N = len(F) - 1 45 + Z = [0] * (N) 46 + for k in range(N): 47 + Fek = ( F[k] + F[-k-1].conjugate() ) 48 + Fok = ( F[k] - F[-k-1].conjugate() ) * e ** (j*pi*k/N) 49 + Z[k] = Fek + j*Fok 50 + 51 + fp = fft(Z , 1) 52 + 53 + f = [] 54 + for c in fp: 55 + f.append(c.real) 56 + f.append(c.imag) 57 + return f 58 + 59 + def real_fft( f,inv ): 60 + if inv: 61 + return rifft(f) 62 + 63 + N = len(f) / 2 64 + 65 + res = f[::2] 66 + ims = f[1::2] 67 + 68 + fp = [ complex(r,i) for r,i in zip(res,ims) ] 69 + print 'fft input ', fp 70 + Fp = fft( fp ,0 ) 71 + print 'fft output ', Fp 72 + 73 + F = [ complex(0,0) ] * ( N+1 ) 74 + 75 + F[0] = complex( Fp[0].real + Fp[0].imag , 0 ) 76 + 77 + for k in range(1,N/2+1): 78 + tw = e ** ( -j*pi*(.5+float(k)/N ) ) 79 + 80 + F1k = Fp[k] + Fp[N-k].conjugate() 81 + F2k = Fp[k] - Fp[N-k].conjugate() 82 + F2k *= tw 83 + F[k] = ( F1k + F2k ) * .5 84 + F[N-k] = ( F1k - F2k ).conjugate() * .5 85 + #F[N-k] = ( F1kp + e ** ( -j*pi*(.5+float(N-k)/N ) ) * F2kp ) * .5 86 + #F[N-k] = ( F1k.conjugate() - tw.conjugate() * F2k.conjugate() ) * .5 87 + 88 + F[N] = complex( Fp[0].real - Fp[0].imag , 0 ) 89 + return F 90 + 91 + def main(): 92 + #fft_func = fft 93 + fft_func = real_fft 94 + 95 + tvec = [0.309655,0.815653,0.768570,0.591841,0.404767,0.637617,0.007803,0.012665] 96 + Ftvec = [ complex(r,i) for r,i in zip( 97 + [3.548571,-0.378761,-0.061950,0.188537,-0.566981,0.188537,-0.061950,-0.378761], 98 + [0.000000,-1.296198,-0.848764,0.225337,0.000000,-0.225337,0.848764,1.296198] ) ] 99 + 100 + F = fft_func( tvec,0 ) 101 + 102 + nerrs= 0 103 + for i in range(len(Ftvec)/2 + 1): 104 + if abs( F[i] - Ftvec[i] )> 1e-5: 105 + print 'F[%d]: %s != %s' % (i,F[i],Ftvec[i]) 106 + nerrs += 1 107 + 108 + print '%d errors in forward fft' % nerrs 109 + if nerrs: 110 + return 111 + 112 + trec = fft_func( F , 1 ) 113 + 114 + for i in range(len(trec) ): 115 + trec[i] /= len(trec) 116 + 117 + for i in range(len(tvec) ): 118 + if abs( trec[i] - tvec[i] )> 1e-5: 119 + print 't[%d]: %s != %s' % (i,tvec[i],trec[i]) 120 + nerrs += 1 121 + 122 + print '%d errors in reverse fft' % nerrs 123 + 124 + 125 + def make_random(dims=[1]): 126 + import Numeric 127 + res = [] 128 + for i in range(dims[0]): 129 + if len(dims)==1: 130 + r=random.uniform(-1,1) 131 + i=random.uniform(-1,1) 132 + res.append( complex(r,i) ) 133 + else: 134 + res.append( make_random( dims[1:] ) ) 135 + return Numeric.array(res) 136 + 137 + def flatten(x): 138 + import Numeric 139 + ntotal = Numeric.product(Numeric.shape(x)) 140 + return Numeric.reshape(x,(ntotal,)) 141 + 142 + def randmat( ndims ): 143 + dims=[] 144 + for i in range( ndims ): 145 + curdim = int( random.uniform(2,4) ) 146 + dims.append( curdim ) 147 + return make_random(dims ) 148 + 149 + def test_fftnd(ndims=3): 150 + import FFT 151 + import Numeric 152 + 153 + x=randmat( ndims ) 154 + print 'dimensions=%s' % str( Numeric.shape(x) ) 155 + #print 'x=%s' %str(x) 156 + xver = FFT.fftnd(x) 157 + x2=myfftnd(x) 158 + err = xver - x2 159 + errf = flatten(err) 160 + xverf = flatten(xver) 161 + errpow = Numeric.vdot(errf,errf)+1e-10 162 + sigpow = Numeric.vdot(xverf,xverf)+1e-10 163 + snr = 10*math.log10(abs(sigpow/errpow) ) 164 + if snr<80: 165 + print xver 166 + print x2 167 + print 'SNR=%sdB' % str( snr ) 168 + 169 + def myfftnd(x): 170 + import Numeric 171 + xf = flatten(x) 172 + Xf = fftndwork( xf , Numeric.shape(x) ) 173 + return Numeric.reshape(Xf,Numeric.shape(x) ) 174 + 175 + def fftndwork(x,dims): 176 + import Numeric 177 + dimprod=Numeric.product( dims ) 178 + 179 + for k in range( len(dims) ): 180 + cur_dim=dims[ k ] 181 + stride=dimprod/cur_dim 182 + next_x = [complex(0,0)]*len(x) 183 + for i in range(stride): 184 + next_x[i*cur_dim:(i+1)*cur_dim] = fft(x[i:(i+cur_dim)*stride:stride],0) 185 + x = next_x 186 + return x 187 + 188 + if __name__ == "__main__": 189 + try: 190 + nd = int(sys.argv[1]) 191 + except: 192 + nd=None 193 + if nd: 194 + test_fftnd( nd ) 195 + else: 196 + sys.exit(0)
+117
test/mk_test.py
··· 1 + #!/usr/bin/env python 2 + 3 + import FFT 4 + import sys 5 + import random 6 + import re 7 + j=complex(0,1) 8 + 9 + def randvec(n,iscomplex): 10 + if iscomplex: 11 + return [ 12 + int(random.uniform(-32768,32767) ) + j*int(random.uniform(-32768,32767) ) 13 + for i in range(n) ] 14 + else: 15 + return [ int(random.uniform(-32768,32767) ) for i in range(n) ] 16 + 17 + def c_format(v,round=0): 18 + if round: 19 + return ','.join( [ '{%d,%d}' %(int(c.real),int(c.imag) ) for c in v ] ) 20 + else: 21 + s= ','.join( [ '{%.60f ,%.60f }' %(c.real,c.imag) for c in v ] ) 22 + return re.sub(r'\.?0+ ',' ',s) 23 + 24 + def test_cpx( n,inverse ,short): 25 + v = randvec(n,1) 26 + scale = 1 27 + if short: 28 + minsnr=30 29 + else: 30 + minsnr=100 31 + 32 + if inverse: 33 + tvecout = FFT.inverse_fft(v) 34 + if short: 35 + scale = 1 36 + else: 37 + scale = len(v) 38 + else: 39 + tvecout = FFT.fft(v) 40 + if short: 41 + scale = 1.0/len(v) 42 + 43 + tvecout = [ c * scale for c in tvecout ] 44 + 45 + 46 + s="""#define NFFT %d""" % len(v) + """ 47 + { 48 + double snr; 49 + kiss_fft_cpx test_vec_in[NFFT] = { """ + c_format(v) + """}; 50 + kiss_fft_cpx test_vec_out[NFFT] = {""" + c_format( tvecout ) + """}; 51 + kiss_fft_cpx testbuf[NFFT]; 52 + void * cfg = kiss_fft_alloc(NFFT,%d,0,0);""" % inverse + """ 53 + 54 + kiss_fft(cfg,test_vec_in,testbuf); 55 + snr = snr_compare(test_vec_out,testbuf,NFFT); 56 + printf("DATATYPE=" xstr(kiss_fft_scalar) ", FFT n=%d, inverse=%d, snr = %g dB\\n",NFFT,""" + str(inverse) + """,snr); 57 + if (snr<""" + str(minsnr) + """) 58 + exit_code++; 59 + free(cfg); 60 + } 61 + #undef NFFT 62 + """ 63 + return s 64 + 65 + def compare_func(): 66 + s=""" 67 + #define xstr(s) str(s) 68 + #define str(s) #s 69 + double snr_compare( kiss_fft_cpx * test_vec_out,kiss_fft_cpx * testbuf, int n) 70 + { 71 + int k; 72 + double sigpow,noisepow,err,snr,scale=0; 73 + kiss_fft_cpx err; 74 + sigpow = noisepow = .000000000000000000000000000001; 75 + 76 + for (k=0;k<n;++k) { 77 + sigpow += test_vec_out[k].r * test_vec_out[k].r + 78 + test_vec_out[k].i * test_vec_out[k].i; 79 + C_SUB(err,test_vec_out[k],testbuf[k].r); 80 + noisepow += err.r * err.r + err.i + err.i; 81 + 82 + if (test_vec_out[k].r) 83 + scale += testbuf[k].r / test_vec_out[k].r; 84 + } 85 + snr = 10*log10( sigpow / noisepow ); 86 + scale /= n; 87 + if (snr<10) 88 + printf( "\\npoor snr, try a scaling factor %f\\n" , scale ); 89 + return snr; 90 + } 91 + """ 92 + return s 93 + 94 + def main(): 95 + 96 + from getopt import getopt 97 + opts,args = getopt(sys.argv[1:],'s') 98 + opts = dict(opts) 99 + short = int( opts.has_key('-s') ) 100 + 101 + fftsizes = args 102 + if not fftsizes: 103 + fftsizes = [ 1800 ] 104 + print '#include "kiss_fft.h"' 105 + print compare_func() 106 + print "int main() { int exit_code=0;\n" 107 + for n in fftsizes: 108 + n = int(n) 109 + print test_cpx(n,0,short) 110 + print test_cpx(n,1,short) 111 + print """ 112 + return exit_code; 113 + } 114 + """ 115 + 116 + if __name__ == "__main__": 117 + main()
+49
test/pstats.c
··· 1 + #include <stdio.h> 2 + #include <stdlib.h> 3 + #include <sys/times.h> 4 + #include <sys/types.h> 5 + #include <unistd.h> 6 + 7 + #include "pstats.h" 8 + 9 + static struct tms tms_beg; 10 + static struct tms tms_end; 11 + static int has_times = 0; 12 + 13 + 14 + void pstats_init(void) 15 + { 16 + has_times = times(&tms_beg) != -1; 17 + } 18 + 19 + static void tms_report(void) 20 + { 21 + double cputime; 22 + if (! has_times ) 23 + return; 24 + times(&tms_end); 25 + cputime = ( ((float)tms_end.tms_utime + tms_end.tms_stime + tms_end.tms_cutime + tms_end.tms_cstime ) - 26 + ((float)tms_beg.tms_utime + tms_beg.tms_stime + tms_beg.tms_cutime + tms_beg.tms_cstime ) ) 27 + / sysconf(_SC_CLK_TCK); 28 + fprintf(stderr,"\tcputime=%.3f\n" , cputime); 29 + } 30 + 31 + static void ps_report(void) 32 + { 33 + char buf[1024]; 34 + #ifdef __APPLE__ /* MAC OS X */ 35 + sprintf(buf,"ps -o command,majflt,minflt,rss,pagein,vsz -p %d 1>&2",getpid() ); 36 + #else /* GNU/Linux */ 37 + sprintf(buf,"ps -o comm,majflt,minflt,rss,drs,pagein,sz,trs,vsz %d 1>&2",getpid() ); 38 + #endif 39 + if (system( buf )==-1) { 40 + perror("system call to ps failed"); 41 + } 42 + } 43 + 44 + void pstats_report() 45 + { 46 + ps_report(); 47 + tms_report(); 48 + } 49 +
+7
test/pstats.h
··· 1 + #ifndef PSTATS_H 2 + #define PSTATS_H 3 + 4 + void pstats_init(void); 5 + void pstats_report(void); 6 + 7 + #endif
+26
test/tailscrap.m
··· 1 + function maxabsdiff=tailscrap() 2 + % test code for circular convolution with the scrapped portion 3 + % at the tail of the buffer, rather than the front 4 + % 5 + % The idea is to rotate the zero-padded h (impulse response) buffer 6 + % to the left nh-1 samples, rotating the junk samples as well. 7 + % This could be very handy in avoiding buffer copies during fast filtering. 8 + nh=10; 9 + nfft=256; 10 + 11 + h=rand(1,nh); 12 + x=rand(1,nfft); 13 + 14 + hpad=[ h(nh) zeros(1,nfft-nh) h(1:nh-1) ]; 15 + 16 + % baseline comparison 17 + y1 = filter(h,1,x); 18 + y1_notrans = y1(nh:nfft); 19 + 20 + % fast convolution 21 + y2 = ifft( fft(hpad) .* fft(x) ); 22 + y2_notrans=y2(1:nfft-nh+1); 23 + 24 + maxabsdiff = max(abs(y2_notrans - y1_notrans)) 25 + 26 + end
+172
test/test_real.c
··· 1 + #include "kiss_fftr.h" 2 + #include "_kiss_fft_guts.h" 3 + #include <sys/times.h> 4 + #include <time.h> 5 + #include <unistd.h> 6 + 7 + static double cputime(void) 8 + { 9 + struct tms t; 10 + times(&t); 11 + return (double)(t.tms_utime + t.tms_stime)/ sysconf(_SC_CLK_TCK) ; 12 + } 13 + 14 + static 15 + kiss_fft_scalar rand_scalar(void) 16 + { 17 + #ifdef USE_SIMD 18 + return _mm_set1_ps(rand()-RAND_MAX/2); 19 + #else 20 + kiss_fft_scalar s = (kiss_fft_scalar)(rand() -RAND_MAX/2); 21 + return s/2; 22 + #endif 23 + } 24 + 25 + static 26 + double snr_compare( kiss_fft_cpx * vec1,kiss_fft_cpx * vec2, int n) 27 + { 28 + int k; 29 + double sigpow=1e-10,noisepow=1e-10,err,snr,scale=0; 30 + 31 + #ifdef USE_SIMD 32 + float *fv1 = (float*)vec1; 33 + float *fv2 = (float*)vec2; 34 + for (k=0;k<8*n;++k) { 35 + sigpow += *fv1 * *fv1; 36 + err = *fv1 - *fv2; 37 + noisepow += err*err; 38 + ++fv1; 39 + ++fv2; 40 + } 41 + #else 42 + for (k=0;k<n;++k) { 43 + sigpow += (double)vec1[k].r * (double)vec1[k].r + 44 + (double)vec1[k].i * (double)vec1[k].i; 45 + err = (double)vec1[k].r - (double)vec2[k].r; 46 + noisepow += err * err; 47 + err = (double)vec1[k].i - (double)vec2[k].i; 48 + noisepow += err * err; 49 + 50 + if (vec1[k].r) 51 + scale +=(double) vec2[k].r / (double)vec1[k].r; 52 + } 53 + #endif 54 + snr = 10*log10( sigpow / noisepow ); 55 + scale /= n; 56 + if (snr<10) { 57 + printf( "\npoor snr, try a scaling factor %f\n" , scale ); 58 + exit(1); 59 + } 60 + return snr; 61 + } 62 + 63 + #ifndef NUMFFTS 64 + #define NUMFFTS 10000 65 + #endif 66 + 67 + 68 + int main(int argc,char ** argv) 69 + { 70 + int nfft = 8*3*5; 71 + double ts,tfft,trfft; 72 + int i; 73 + if (argc>1) 74 + nfft = atoi(argv[1]); 75 + kiss_fft_cpx cin[nfft]; 76 + kiss_fft_cpx cout[nfft]; 77 + kiss_fft_cpx sout[nfft]; 78 + kiss_fft_cfg kiss_fft_state; 79 + kiss_fftr_cfg kiss_fftr_state; 80 + 81 + kiss_fft_scalar rin[nfft+2]; 82 + kiss_fft_scalar rout[nfft+2]; 83 + kiss_fft_scalar zero; 84 + memset(&zero,0,sizeof(zero) ); // ugly way of setting short,int,float,double, or __m128 to zero 85 + 86 + srand(time(0)); 87 + 88 + for (i=0;i<nfft;++i) { 89 + rin[i] = rand_scalar(); 90 + cin[i].r = rin[i]; 91 + cin[i].i = zero; 92 + } 93 + 94 + kiss_fft_state = kiss_fft_alloc(nfft,0,0,0); 95 + kiss_fftr_state = kiss_fftr_alloc(nfft,0,0,0); 96 + kiss_fft(kiss_fft_state,cin,cout); 97 + kiss_fftr(kiss_fftr_state,rin,sout); 98 + /* 99 + printf(" results from kiss_fft : (%f,%f), (%f,%f), (%f,%f) ...\n " 100 + , (float)cout[0].r , (float)cout[0].i 101 + , (float)cout[1].r , (float)cout[1].i 102 + , (float)cout[2].r , (float)cout[2].i); 103 + printf(" results from kiss_fftr: (%f,%f), (%f,%f), (%f,%f) ...\n " 104 + , (float)sout[0].r , (float)sout[0].i 105 + , (float)sout[1].r , (float)sout[1].i 106 + , (float)sout[2].r , (float)sout[2].i); 107 + */ 108 + 109 + printf( "nfft=%d, inverse=%d, snr=%g\n", 110 + nfft,0, snr_compare(cout,sout,(nfft/2)+1) ); 111 + ts = cputime(); 112 + for (i=0;i<NUMFFTS;++i) { 113 + kiss_fft(kiss_fft_state,cin,cout); 114 + } 115 + tfft = cputime() - ts; 116 + 117 + ts = cputime(); 118 + for (i=0;i<NUMFFTS;++i) { 119 + kiss_fftr( kiss_fftr_state, rin, cout ); 120 + /* kiss_fftri(kiss_fftr_state,cout,rin); */ 121 + } 122 + trfft = cputime() - ts; 123 + 124 + printf("%d complex ffts took %gs, real took %gs\n",NUMFFTS,tfft,trfft); 125 + 126 + free(kiss_fft_state); 127 + free(kiss_fftr_state); 128 + 129 + kiss_fft_state = kiss_fft_alloc(nfft,1,0,0); 130 + kiss_fftr_state = kiss_fftr_alloc(nfft,1,0,0); 131 + 132 + memset(cin,0,sizeof(cin)); 133 + #if 1 134 + for (i=1;i< nfft/2;++i) { 135 + //cin[i].r = (kiss_fft_scalar)(rand()-RAND_MAX/2); 136 + cin[i].r = rand_scalar(); 137 + cin[i].i = rand_scalar(); 138 + } 139 + #else 140 + cin[0].r = 12000; 141 + cin[3].r = 12000; 142 + cin[nfft/2].r = 12000; 143 + #endif 144 + 145 + // conjugate symmetry of real signal 146 + for (i=1;i< nfft/2;++i) { 147 + cin[nfft-i].r = cin[i].r; 148 + cin[nfft-i].i = - cin[i].i; 149 + } 150 + 151 + kiss_fft(kiss_fft_state,cin,cout); 152 + kiss_fftri(kiss_fftr_state,cin,rout); 153 + /* 154 + printf(" results from inverse kiss_fft : (%f,%f), (%f,%f), (%f,%f), (%f,%f), (%f,%f) ...\n " 155 + , (float)cout[0].r , (float)cout[0].i , (float)cout[1].r , (float)cout[1].i , (float)cout[2].r , (float)cout[2].i , (float)cout[3].r , (float)cout[3].i , (float)cout[4].r , (float)cout[4].i 156 + ); 157 + 158 + printf(" results from inverse kiss_fftr: %f,%f,%f,%f,%f ... \n" 159 + ,(float)rout[0] ,(float)rout[1] ,(float)rout[2] ,(float)rout[3] ,(float)rout[4]); 160 + */ 161 + for (i=0;i<nfft;++i) { 162 + sout[i].r = rout[i]; 163 + sout[i].i = zero; 164 + } 165 + 166 + printf( "nfft=%d, inverse=%d, snr=%g\n", 167 + nfft,1, snr_compare(cout,sout,nfft/2) ); 168 + free(kiss_fft_state); 169 + free(kiss_fftr_state); 170 + 171 + return 0; 172 + }
+74
test/test_vs_dft.c
··· 1 + #include "kiss_fft.h" 2 + 3 + 4 + void check(kiss_fft_cpx * in,kiss_fft_cpx * out,int nfft,int isinverse) 5 + { 6 + int bin,k; 7 + double errpow=0,sigpow=0; 8 + 9 + for (bin=0;bin<nfft;++bin) { 10 + double ansr = 0; 11 + double ansi = 0; 12 + double difr; 13 + double difi; 14 + 15 + for (k=0;k<nfft;++k) { 16 + double phase = -2*M_PI*bin*k/nfft; 17 + double re = cos(phase); 18 + double im = sin(phase); 19 + if (isinverse) 20 + im = -im; 21 + 22 + #ifdef FIXED_POINT 23 + re /= nfft; 24 + im /= nfft; 25 + #endif 26 + 27 + ansr += in[k].r * re - in[k].i * im; 28 + ansi += in[k].r * im + in[k].i * re; 29 + } 30 + difr = ansr - out[bin].r; 31 + difi = ansi - out[bin].i; 32 + errpow += difr*difr + difi*difi; 33 + sigpow += ansr*ansr+ansi*ansi; 34 + } 35 + printf("nfft=%d inverse=%d,snr = %f\n",nfft,isinverse,10*log10(sigpow/errpow) ); 36 + } 37 + 38 + void test1d(int nfft,int isinverse) 39 + { 40 + size_t buflen = sizeof(kiss_fft_cpx)*nfft; 41 + 42 + kiss_fft_cpx * in = (kiss_fft_cpx*)malloc(buflen); 43 + kiss_fft_cpx * out= (kiss_fft_cpx*)malloc(buflen); 44 + kiss_fft_cfg cfg = kiss_fft_alloc(nfft,isinverse,0,0); 45 + int k; 46 + 47 + for (k=0;k<nfft;++k) { 48 + in[k].r = (rand() % 65536) - 32768; 49 + in[k].i = (rand() % 65536) - 32768; 50 + } 51 + 52 + kiss_fft(cfg,in,out); 53 + 54 + check(in,out,nfft,isinverse); 55 + 56 + free(in); 57 + free(out); 58 + free(cfg); 59 + } 60 + 61 + int main(int argc,char ** argv) 62 + { 63 + if (argc>1) { 64 + int k; 65 + for (k=1;k<argc;++k) { 66 + test1d(atoi(argv[k]),0); 67 + test1d(atoi(argv[k]),1); 68 + } 69 + }else{ 70 + test1d(32,0); 71 + test1d(32,1); 72 + } 73 + return 0; 74 + }
+73
test/testcpp.cc
··· 1 + #include "kissfft.hh" 2 + #include <iostream> 3 + #include <cstdlib> 4 + #include <typeinfo> 5 + 6 + #include <sys/time.h> 7 + static inline 8 + double curtime(void) 9 + { 10 + struct timeval tv; 11 + gettimeofday(&tv, NULL); 12 + return (double)tv.tv_sec + (double)tv.tv_usec*.000001; 13 + } 14 + 15 + using namespace std; 16 + 17 + template <class T> 18 + void dotest(int nfft) 19 + { 20 + typedef kissfft<T> FFT; 21 + typedef std::complex<T> cpx_type; 22 + 23 + cout << "type:" << typeid(T).name() << " nfft:" << nfft; 24 + 25 + FFT fft(nfft,false); 26 + 27 + vector<cpx_type> inbuf(nfft); 28 + vector<cpx_type> outbuf(nfft); 29 + for (int k=0;k<nfft;++k) 30 + inbuf[k]= cpx_type( 31 + (T)(rand()/(double)RAND_MAX - .5), 32 + (T)(rand()/(double)RAND_MAX - .5) ); 33 + fft.transform( &inbuf[0] , &outbuf[0] ); 34 + 35 + long double totalpower=0; 36 + long double difpower=0; 37 + for (int k0=0;k0<nfft;++k0) { 38 + complex<long double> acc = 0; 39 + long double phinc = 2*k0* M_PIl / nfft; 40 + for (int k1=0;k1<nfft;++k1) { 41 + complex<long double> x(inbuf[k1].real(),inbuf[k1].imag()); 42 + acc += x * exp( complex<long double>(0,-k1*phinc) ); 43 + } 44 + totalpower += norm(acc); 45 + complex<long double> x(outbuf[k0].real(),outbuf[k0].imag()); 46 + complex<long double> dif = acc - x; 47 + difpower += norm(dif); 48 + } 49 + cout << " RMSE:" << sqrt(difpower/totalpower) << "\t"; 50 + 51 + double t0 = curtime(); 52 + int nits=20e6/nfft; 53 + for (int k=0;k<nits;++k) { 54 + fft.transform( &inbuf[0] , &outbuf[0] ); 55 + } 56 + double t1 = curtime(); 57 + cout << " MSPS:" << ( (nits*nfft)*1e-6/ (t1-t0) ) << endl; 58 + } 59 + 60 + int main(int argc,char ** argv) 61 + { 62 + if (argc>1) { 63 + for (int k=1;k<argc;++k) { 64 + int nfft = atoi(argv[k]); 65 + dotest<float>(nfft); dotest<double>(nfft); dotest<long double>(nfft); 66 + } 67 + }else{ 68 + dotest<float>(32); dotest<double>(32); dotest<long double>(32); 69 + dotest<float>(1024); dotest<double>(1024); dotest<long double>(1024); 70 + dotest<float>(840); dotest<double>(840); dotest<long double>(840); 71 + } 72 + return 0; 73 + }
+162
test/testkiss.py
··· 1 + #!/usr/bin/env python 2 + 3 + import math 4 + import sys 5 + import os 6 + import random 7 + import struct 8 + import popen2 9 + import getopt 10 + import numpy 11 + 12 + pi=math.pi 13 + e=math.e 14 + j=complex(0,1) 15 + 16 + doreal=0 17 + 18 + datatype = os.environ.get('DATATYPE','float') 19 + 20 + util = '../tools/fft_' + datatype 21 + minsnr=90 22 + if datatype == 'double': 23 + fmt='d' 24 + elif datatype=='int16_t': 25 + fmt='h' 26 + minsnr=10 27 + elif datatype=='int32_t': 28 + fmt='i' 29 + elif datatype=='simd': 30 + fmt='4f' 31 + sys.stderr.write('testkiss.py does not yet test simd') 32 + sys.exit(0) 33 + elif datatype=='float': 34 + fmt='f' 35 + else: 36 + sys.stderr.write('unrecognized datatype %s\n' % datatype) 37 + sys.exit(1) 38 + 39 + 40 + def dopack(x,cpx=1): 41 + x = numpy.reshape( x, ( numpy.size(x),) ) 42 + 43 + if cpx: 44 + s = ''.join( [ struct.pack(fmt*2,c.real,c.imag) for c in x ] ) 45 + else: 46 + s = ''.join( [ struct.pack(fmt,c.real) for c in x ] ) 47 + return s 48 + 49 + def dounpack(x,cpx): 50 + uf = fmt * ( len(x) / struct.calcsize(fmt) ) 51 + s = struct.unpack(uf,x) 52 + if cpx: 53 + return numpy.array(s[::2]) + numpy.array( s[1::2] )*j 54 + else: 55 + return numpy.array(s ) 56 + 57 + def make_random(dims=[1]): 58 + res = [] 59 + for i in range(dims[0]): 60 + if len(dims)==1: 61 + r=random.uniform(-1,1) 62 + if doreal: 63 + res.append( r ) 64 + else: 65 + i=random.uniform(-1,1) 66 + res.append( complex(r,i) ) 67 + else: 68 + res.append( make_random( dims[1:] ) ) 69 + return numpy.array(res) 70 + 71 + def flatten(x): 72 + ntotal = numpy.size(x) 73 + return numpy.reshape(x,(ntotal,)) 74 + 75 + def randmat( ndims ): 76 + dims=[] 77 + for i in range( ndims ): 78 + curdim = int( random.uniform(2,5) ) 79 + if doreal and i==(ndims-1): 80 + curdim = int(curdim/2)*2 # force even last dimension if real 81 + dims.append( curdim ) 82 + return make_random(dims ) 83 + 84 + def test_fft(ndims): 85 + x=randmat( ndims ) 86 + 87 + 88 + if doreal: 89 + xver = numpy.fft.rfftn(x) 90 + else: 91 + xver = numpy.fft.fftn(x) 92 + 93 + open('/tmp/fftexp.dat','w').write(dopack( flatten(xver) , True ) ) 94 + 95 + x2=dofft(x,doreal) 96 + err = xver - x2 97 + errf = flatten(err) 98 + xverf = flatten(xver) 99 + errpow = numpy.vdot(errf,errf)+1e-10 100 + sigpow = numpy.vdot(xverf,xverf)+1e-10 101 + snr = 10*math.log10(abs(sigpow/errpow) ) 102 + print 'SNR (compared to NumPy) : %.1fdB' % float(snr) 103 + 104 + if snr<minsnr: 105 + print 'xver=',xver 106 + print 'x2=',x2 107 + print 'err',err 108 + sys.exit(1) 109 + 110 + def dofft(x,isreal): 111 + dims=list( numpy.shape(x) ) 112 + x = flatten(x) 113 + 114 + scale=1 115 + if datatype=='int16_t': 116 + x = 32767 * x 117 + scale = len(x) / 32767.0 118 + elif datatype=='int32_t': 119 + x = 2147483647.0 * x 120 + scale = len(x) / 2147483647.0 121 + 122 + cmd='%s -n ' % util 123 + cmd += ','.join([str(d) for d in dims]) 124 + if doreal: 125 + cmd += ' -R ' 126 + 127 + print cmd 128 + p = popen2.Popen3(cmd ) 129 + 130 + open('/tmp/fftin.dat','w').write(dopack( x , isreal==False ) ) 131 + 132 + p.tochild.write( dopack( x , isreal==False ) ) 133 + p.tochild.close() 134 + 135 + res = dounpack( p.fromchild.read() , 1 ) 136 + open('/tmp/fftout.dat','w').write(dopack( flatten(res) , True ) ) 137 + if doreal: 138 + dims[-1] = int( dims[-1]/2 ) + 1 139 + 140 + res = scale * res 141 + 142 + p.wait() 143 + return numpy.reshape(res,dims) 144 + 145 + def main(): 146 + opts,args = getopt.getopt(sys.argv[1:],'r') 147 + opts=dict(opts) 148 + 149 + global doreal 150 + doreal = opts.has_key('-r') 151 + 152 + if doreal: 153 + print 'Testing multi-dimensional real FFTs' 154 + else: 155 + print 'Testing multi-dimensional FFTs' 156 + 157 + for dim in range(1,4): 158 + test_fft( dim ) 159 + 160 + if __name__ == "__main__": 161 + main() 162 +
+94
test/twotonetest.c
··· 1 + #include <stdlib.h> 2 + #include <string.h> 3 + #include <stdio.h> 4 + #include "kiss_fft.h" 5 + #include "kiss_fftr.h" 6 + #include <limits.h> 7 + 8 + 9 + static 10 + double two_tone_test( int nfft, int bin1,int bin2) 11 + { 12 + kiss_fftr_cfg cfg = NULL; 13 + kiss_fft_cpx *kout = NULL; 14 + kiss_fft_scalar *tbuf = NULL; 15 + 16 + int i; 17 + double f1 = bin1*2*M_PI/nfft; 18 + double f2 = bin2*2*M_PI/nfft; 19 + double sigpow=0; 20 + double noisepow=0; 21 + #if FIXED_POINT==32 22 + long maxrange = LONG_MAX; 23 + #else 24 + long maxrange = SHRT_MAX;/* works fine for float too*/ 25 + #endif 26 + 27 + cfg = kiss_fftr_alloc(nfft , 0, NULL, NULL); 28 + tbuf = KISS_FFT_MALLOC(nfft * sizeof(kiss_fft_scalar)); 29 + kout = KISS_FFT_MALLOC(nfft * sizeof(kiss_fft_cpx)); 30 + 31 + /* generate a signal with two tones*/ 32 + for (i = 0; i < nfft; i++) { 33 + #ifdef USE_SIMD 34 + tbuf[i] = _mm_set1_ps( (maxrange>>1)*cos(f1*i) 35 + + (maxrange>>1)*cos(f2*i) ); 36 + #else 37 + tbuf[i] = (maxrange>>1)*cos(f1*i) 38 + + (maxrange>>1)*cos(f2*i); 39 + #endif 40 + } 41 + 42 + kiss_fftr(cfg, tbuf, kout); 43 + 44 + for (i=0;i < (nfft/2+1);++i) { 45 + #ifdef USE_SIMD 46 + double tmpr = (double)*(float*)&kout[i].r / (double)maxrange; 47 + double tmpi = (double)*(float*)&kout[i].i / (double)maxrange; 48 + #else 49 + double tmpr = (double)kout[i].r / (double)maxrange; 50 + double tmpi = (double)kout[i].i / (double)maxrange; 51 + #endif 52 + double mag2 = tmpr*tmpr + tmpi*tmpi; 53 + if (i!=0 && i!= nfft/2) 54 + mag2 *= 2; /* all bins except DC and Nyquist have symmetric counterparts implied*/ 55 + 56 + /* if there is power in one of the expected bins, it is signal, otherwise noise*/ 57 + if ( i!=bin1 && i != bin2 ) 58 + noisepow += mag2; 59 + else 60 + sigpow += mag2; 61 + } 62 + kiss_fft_cleanup(); 63 + /*printf("TEST %d,%d,%d noise @ %fdB\n",nfft,bin1,bin2,10*log10(noisepow/sigpow +1e-30) );*/ 64 + return 10*log10(sigpow/(noisepow+1e-50) ); 65 + } 66 + 67 + int main(int argc,char ** argv) 68 + { 69 + int nfft = 4*2*2*3*5; 70 + if (argc>1) nfft = atoi(argv[1]); 71 + 72 + int i,j; 73 + double minsnr = 500; 74 + double maxsnr = -500; 75 + double snr; 76 + for (i=0;i<nfft/2;i+= (nfft>>4)+1) { 77 + for (j=i;j<nfft/2;j+=(nfft>>4)+7) { 78 + snr = two_tone_test(nfft,i,j); 79 + if (snr<minsnr) { 80 + minsnr=snr; 81 + } 82 + if (snr>maxsnr) { 83 + maxsnr=snr; 84 + } 85 + } 86 + } 87 + snr = two_tone_test(nfft,nfft/2,nfft/2); 88 + if (snr<minsnr) minsnr=snr; 89 + if (snr>maxsnr) maxsnr=snr; 90 + 91 + printf("TwoToneTest: snr ranges from %ddB to %ddB\n",(int)minsnr,(int)maxsnr); 92 + printf("sizeof(kiss_fft_scalar) = %d\n",(int)sizeof(kiss_fft_scalar) ); 93 + return 0; 94 + }
+62
tools/Makefile
··· 1 + WARNINGS=-W -Wall -Wstrict-prototypes -Wmissing-prototypes -Waggregate-return \ 2 + -Wcast-align -Wcast-qual -Wnested-externs -Wshadow -Wbad-function-cast \ 3 + -Wwrite-strings 4 + 5 + ifeq "$(DATATYPE)" "" 6 + DATATYPE=float 7 + endif 8 + 9 + ifeq "$(DATATYPE)" "int32_t" 10 + TYPEFLAGS=-DFIXED_POINT=32 11 + endif 12 + 13 + ifeq "$(DATATYPE)" "int16_t" 14 + TYPEFLAGS=-DFIXED_POINT=16 15 + endif 16 + 17 + ifeq "$(DATATYPE)" "simd" 18 + TYPEFLAGS=-DUSE_SIMD=1 -msse 19 + endif 20 + 21 + ifeq "$(TYPEFLAGS)" "" 22 + TYPEFLAGS=-Dkiss_fft_scalar=$(DATATYPE) 23 + endif 24 + 25 + ifneq ("$(KISS_FFT_USE_ALLOCA)","") 26 + CFLAGS+= -DKISS_FFT_USE_ALLOCA=1 27 + endif 28 + CFLAGS+= $(CFLAGADD) 29 + 30 + 31 + FFTUTIL=fft_$(DATATYPE) 32 + FASTFILT=fastconv_$(DATATYPE) 33 + FASTFILTREAL=fastconvr_$(DATATYPE) 34 + PSDPNG=psdpng_$(DATATYPE) 35 + DUMPHDR=dumphdr_$(DATATYPE) 36 + 37 + all: $(FFTUTIL) $(FASTFILT) $(FASTFILTREAL) 38 + # $(PSDPNG) 39 + # $(DUMPHDR) 40 + 41 + #CFLAGS=-Wall -O3 -pedantic -march=pentiumpro -ffast-math -fomit-frame-pointer $(WARNINGS) 42 + # If the above flags do not work, try the following 43 + CFLAGS=-Wall -O3 $(WARNINGS) 44 + # tip: try -openmp or -fopenmp to use multiple cores 45 + 46 + $(FASTFILTREAL): ../kiss_fft.c kiss_fastfir.c kiss_fftr.c 47 + $(CC) -o $@ $(CFLAGS) -I.. $(TYPEFLAGS) -DREAL_FASTFIR $+ -DFAST_FILT_UTIL -lm 48 + 49 + $(FASTFILT): ../kiss_fft.c kiss_fastfir.c 50 + $(CC) -o $@ $(CFLAGS) -I.. $(TYPEFLAGS) $+ -DFAST_FILT_UTIL -lm 51 + 52 + $(FFTUTIL): ../kiss_fft.c fftutil.c kiss_fftnd.c kiss_fftr.c kiss_fftndr.c 53 + $(CC) -o $@ $(CFLAGS) -I.. $(TYPEFLAGS) $+ -lm 54 + 55 + $(PSDPNG): ../kiss_fft.c psdpng.c kiss_fftr.c 56 + $(CC) -o $@ $(CFLAGS) -I.. $(TYPEFLAGS) $+ -lpng -lm 57 + 58 + $(DUMPHDR): ../kiss_fft.c dumphdr.c 59 + $(CC) -o $@ $(CFLAGS) -I.. $(TYPEFLAGS) $+ -lm 60 + 61 + clean: 62 + rm -f *~ fft fft_* fastconv fastconv_* fastconvr fastconvr_* psdpng psdpng_*
+208
tools/fftutil.c
··· 1 + /* 2 + Copyright (c) 2003-2004, Mark Borgerding 3 + 4 + All rights reserved. 5 + 6 + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 7 + 8 + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 9 + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 10 + * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 + 12 + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 13 + */ 14 + 15 + #include <stdlib.h> 16 + #include <math.h> 17 + #include <stdio.h> 18 + #include <string.h> 19 + #include <unistd.h> 20 + 21 + #include "kiss_fft.h" 22 + #include "kiss_fftndr.h" 23 + 24 + static 25 + void fft_file(FILE * fin,FILE * fout,int nfft,int isinverse) 26 + { 27 + kiss_fft_cfg st; 28 + kiss_fft_cpx * buf; 29 + kiss_fft_cpx * bufout; 30 + 31 + buf = (kiss_fft_cpx*)malloc(sizeof(kiss_fft_cpx) * nfft ); 32 + bufout = (kiss_fft_cpx*)malloc(sizeof(kiss_fft_cpx) * nfft ); 33 + st = kiss_fft_alloc( nfft ,isinverse ,0,0); 34 + 35 + while ( fread( buf , sizeof(kiss_fft_cpx) * nfft ,1, fin ) > 0 ) { 36 + kiss_fft( st , buf ,bufout); 37 + fwrite( bufout , sizeof(kiss_fft_cpx) , nfft , fout ); 38 + } 39 + free(st); 40 + free(buf); 41 + free(bufout); 42 + } 43 + 44 + static 45 + void fft_filend(FILE * fin,FILE * fout,int *dims,int ndims,int isinverse) 46 + { 47 + kiss_fftnd_cfg st; 48 + kiss_fft_cpx *buf; 49 + int dimprod=1,i; 50 + for (i=0;i<ndims;++i) 51 + dimprod *= dims[i]; 52 + 53 + buf = (kiss_fft_cpx *) malloc (sizeof (kiss_fft_cpx) * dimprod); 54 + st = kiss_fftnd_alloc (dims, ndims, isinverse, 0, 0); 55 + 56 + while (fread (buf, sizeof (kiss_fft_cpx) * dimprod, 1, fin) > 0) { 57 + kiss_fftnd (st, buf, buf); 58 + fwrite (buf, sizeof (kiss_fft_cpx), dimprod, fout); 59 + } 60 + free (st); 61 + free (buf); 62 + } 63 + 64 + 65 + 66 + static 67 + void fft_filend_real(FILE * fin,FILE * fout,int *dims,int ndims,int isinverse) 68 + { 69 + int dimprod=1,i; 70 + kiss_fftndr_cfg st; 71 + void *ibuf; 72 + void *obuf; 73 + int insize,outsize; // size in bytes 74 + 75 + for (i=0;i<ndims;++i) 76 + dimprod *= dims[i]; 77 + insize = outsize = dimprod; 78 + int rdim = dims[ndims-1]; 79 + 80 + if (isinverse) 81 + insize = insize*2*(rdim/2+1)/rdim; 82 + else 83 + outsize = outsize*2*(rdim/2+1)/rdim; 84 + 85 + ibuf = malloc(insize*sizeof(kiss_fft_scalar)); 86 + obuf = malloc(outsize*sizeof(kiss_fft_scalar)); 87 + 88 + st = kiss_fftndr_alloc(dims, ndims, isinverse, 0, 0); 89 + 90 + while ( fread (ibuf, sizeof(kiss_fft_scalar), insize, fin) > 0) { 91 + if (isinverse) { 92 + kiss_fftndri(st, 93 + (kiss_fft_cpx*)ibuf, 94 + (kiss_fft_scalar*)obuf); 95 + }else{ 96 + kiss_fftndr(st, 97 + (kiss_fft_scalar*)ibuf, 98 + (kiss_fft_cpx*)obuf); 99 + } 100 + fwrite (obuf, sizeof(kiss_fft_scalar), outsize,fout); 101 + } 102 + free(st); 103 + free(ibuf); 104 + free(obuf); 105 + } 106 + 107 + static 108 + void fft_file_real(FILE * fin,FILE * fout,int nfft,int isinverse) 109 + { 110 + kiss_fftr_cfg st; 111 + kiss_fft_scalar * rbuf; 112 + kiss_fft_cpx * cbuf; 113 + 114 + rbuf = (kiss_fft_scalar*)malloc(sizeof(kiss_fft_scalar) * nfft ); 115 + cbuf = (kiss_fft_cpx*)malloc(sizeof(kiss_fft_cpx) * (nfft/2+1) ); 116 + st = kiss_fftr_alloc( nfft ,isinverse ,0,0); 117 + 118 + if (isinverse==0) { 119 + while ( fread( rbuf , sizeof(kiss_fft_scalar) * nfft ,1, fin ) > 0 ) { 120 + kiss_fftr( st , rbuf ,cbuf); 121 + fwrite( cbuf , sizeof(kiss_fft_cpx) , (nfft/2 + 1) , fout ); 122 + } 123 + }else{ 124 + while ( fread( cbuf , sizeof(kiss_fft_cpx) * (nfft/2+1) ,1, fin ) > 0 ) { 125 + kiss_fftri( st , cbuf ,rbuf); 126 + fwrite( rbuf , sizeof(kiss_fft_scalar) , nfft , fout ); 127 + } 128 + } 129 + free(st); 130 + free(rbuf); 131 + free(cbuf); 132 + } 133 + 134 + static 135 + int get_dims(char * arg,int * dims) 136 + { 137 + char *p0; 138 + int ndims=0; 139 + 140 + do{ 141 + p0 = strchr(arg,','); 142 + if (p0) 143 + *p0++ = '\0'; 144 + dims[ndims++] = atoi(arg); 145 + // fprintf(stderr,"dims[%d] = %d\n",ndims-1,dims[ndims-1]); 146 + arg = p0; 147 + }while (p0); 148 + return ndims; 149 + } 150 + 151 + int main(int argc,char ** argv) 152 + { 153 + int isinverse=0; 154 + int isreal=0; 155 + FILE *fin=stdin; 156 + FILE *fout=stdout; 157 + int ndims=1; 158 + int dims[32]; 159 + dims[0] = 1024; /*default fft size*/ 160 + 161 + while (1) { 162 + int c=getopt(argc,argv,"n:iR"); 163 + if (c==-1) break; 164 + switch (c) { 165 + case 'n': 166 + ndims = get_dims(optarg,dims); 167 + break; 168 + case 'i':isinverse=1;break; 169 + case 'R':isreal=1;break; 170 + case '?': 171 + fprintf(stderr,"usage options:\n" 172 + "\t-n d1[,d2,d3...]: fft dimension(s)\n" 173 + "\t-i : inverse\n" 174 + "\t-R : real input samples, not complex\n"); 175 + exit (1); 176 + default:fprintf(stderr,"bad %c\n",c);break; 177 + } 178 + } 179 + 180 + if ( optind < argc ) { 181 + if (strcmp("-",argv[optind]) !=0) 182 + fin = fopen(argv[optind],"rb"); 183 + ++optind; 184 + } 185 + 186 + if ( optind < argc ) { 187 + if ( strcmp("-",argv[optind]) !=0 ) 188 + fout = fopen(argv[optind],"wb"); 189 + ++optind; 190 + } 191 + 192 + if (ndims==1) { 193 + if (isreal) 194 + fft_file_real(fin,fout,dims[0],isinverse); 195 + else 196 + fft_file(fin,fout,dims[0],isinverse); 197 + }else{ 198 + if (isreal) 199 + fft_filend_real(fin,fout,dims,ndims,isinverse); 200 + else 201 + fft_filend(fin,fout,dims,ndims,isinverse); 202 + } 203 + 204 + if (fout!=stdout) fclose(fout); 205 + if (fin!=stdin) fclose(fin); 206 + 207 + return 0; 208 + }
+116
tools/kfc.c
··· 1 + #include "kfc.h" 2 + 3 + /* 4 + Copyright (c) 2003-2004, Mark Borgerding 5 + 6 + All rights reserved. 7 + 8 + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 9 + 10 + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 11 + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 12 + * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. 13 + 14 + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 15 + */ 16 + 17 + 18 + typedef struct cached_fft *kfc_cfg; 19 + 20 + struct cached_fft 21 + { 22 + int nfft; 23 + int inverse; 24 + kiss_fft_cfg cfg; 25 + kfc_cfg next; 26 + }; 27 + 28 + static kfc_cfg cache_root=NULL; 29 + static int ncached=0; 30 + 31 + static kiss_fft_cfg find_cached_fft(int nfft,int inverse) 32 + { 33 + size_t len; 34 + kfc_cfg cur=cache_root; 35 + kfc_cfg prev=NULL; 36 + while ( cur ) { 37 + if ( cur->nfft == nfft && inverse == cur->inverse ) 38 + break;/*found the right node*/ 39 + prev = cur; 40 + cur = prev->next; 41 + } 42 + if (cur== NULL) { 43 + /* no cached node found, need to create a new one*/ 44 + kiss_fft_alloc(nfft,inverse,0,&len); 45 + #ifdef USE_SIMD 46 + int padding = (16-sizeof(struct cached_fft)) & 15; 47 + // make sure the cfg aligns on a 16 byte boundary 48 + len += padding; 49 + #endif 50 + cur = (kfc_cfg)KISS_FFT_MALLOC((sizeof(struct cached_fft) + len )); 51 + if (cur == NULL) 52 + return NULL; 53 + cur->cfg = (kiss_fft_cfg)(cur+1); 54 + #ifdef USE_SIMD 55 + cur->cfg = (kiss_fft_cfg) ((char*)(cur+1)+padding); 56 + #endif 57 + kiss_fft_alloc(nfft,inverse,cur->cfg,&len); 58 + cur->nfft=nfft; 59 + cur->inverse=inverse; 60 + cur->next = NULL; 61 + if ( prev ) 62 + prev->next = cur; 63 + else 64 + cache_root = cur; 65 + ++ncached; 66 + } 67 + return cur->cfg; 68 + } 69 + 70 + void kfc_cleanup(void) 71 + { 72 + kfc_cfg cur=cache_root; 73 + kfc_cfg next=NULL; 74 + while (cur){ 75 + next = cur->next; 76 + free(cur); 77 + cur=next; 78 + } 79 + ncached=0; 80 + cache_root = NULL; 81 + } 82 + void kfc_fft(int nfft, const kiss_fft_cpx * fin,kiss_fft_cpx * fout) 83 + { 84 + kiss_fft( find_cached_fft(nfft,0),fin,fout ); 85 + } 86 + 87 + void kfc_ifft(int nfft, const kiss_fft_cpx * fin,kiss_fft_cpx * fout) 88 + { 89 + kiss_fft( find_cached_fft(nfft,1),fin,fout ); 90 + } 91 + 92 + #ifdef KFC_TEST 93 + static void check(int nc) 94 + { 95 + if (ncached != nc) { 96 + fprintf(stderr,"ncached should be %d,but it is %d\n",nc,ncached); 97 + exit(1); 98 + } 99 + } 100 + 101 + int main(void) 102 + { 103 + kiss_fft_cpx buf1[1024],buf2[1024]; 104 + memset(buf1,0,sizeof(buf1)); 105 + check(0); 106 + kfc_fft(512,buf1,buf2); 107 + check(1); 108 + kfc_fft(512,buf1,buf2); 109 + check(1); 110 + kfc_ifft(512,buf1,buf2); 111 + check(2); 112 + kfc_cleanup(); 113 + check(0); 114 + return 0; 115 + } 116 + #endif
+46
tools/kfc.h
··· 1 + #ifndef KFC_H 2 + #define KFC_H 3 + #include "kiss_fft.h" 4 + 5 + #ifdef __cplusplus 6 + extern "C" { 7 + #endif 8 + 9 + /* 10 + KFC -- Kiss FFT Cache 11 + 12 + Not needing to deal with kiss_fft_alloc and a config 13 + object may be handy for a lot of programs. 14 + 15 + KFC uses the underlying KISS FFT functions, but caches the config object. 16 + The first time kfc_fft or kfc_ifft for a given FFT size, the cfg 17 + object is created for it. All subsequent calls use the cached 18 + configuration object. 19 + 20 + NOTE: 21 + You should probably not use this if your program will be using a lot 22 + of various sizes of FFTs. There is a linear search through the 23 + cached objects. If you are only using one or two FFT sizes, this 24 + will be negligible. Otherwise, you may want to use another method 25 + of managing the cfg objects. 26 + 27 + There is no automated cleanup of the cached objects. This could lead 28 + to large memory usage in a program that uses a lot of *DIFFERENT* 29 + sized FFTs. If you want to force all cached cfg objects to be freed, 30 + call kfc_cleanup. 31 + 32 + */ 33 + 34 + /*forward complex FFT */ 35 + void kfc_fft(int nfft, const kiss_fft_cpx * fin,kiss_fft_cpx * fout); 36 + /*reverse complex FFT */ 37 + void kfc_ifft(int nfft, const kiss_fft_cpx * fin,kiss_fft_cpx * fout); 38 + 39 + /*free all cached objects*/ 40 + void kfc_cleanup(void); 41 + 42 + #ifdef __cplusplus 43 + } 44 + #endif 45 + 46 + #endif
+470
tools/kiss_fastfir.c
··· 1 + /* 2 + Copyright (c) 2003-2004, Mark Borgerding 3 + 4 + All rights reserved. 5 + 6 + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 7 + 8 + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 9 + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 10 + * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 + 12 + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 13 + */ 14 + 15 + #include "_kiss_fft_guts.h" 16 + 17 + 18 + /* 19 + Some definitions that allow real or complex filtering 20 + */ 21 + #ifdef REAL_FASTFIR 22 + #define MIN_FFT_LEN 2048 23 + #include "kiss_fftr.h" 24 + typedef kiss_fft_scalar kffsamp_t; 25 + typedef kiss_fftr_cfg kfcfg_t; 26 + #define FFT_ALLOC kiss_fftr_alloc 27 + #define FFTFWD kiss_fftr 28 + #define FFTINV kiss_fftri 29 + #else 30 + #define MIN_FFT_LEN 1024 31 + typedef kiss_fft_cpx kffsamp_t; 32 + typedef kiss_fft_cfg kfcfg_t; 33 + #define FFT_ALLOC kiss_fft_alloc 34 + #define FFTFWD kiss_fft 35 + #define FFTINV kiss_fft 36 + #endif 37 + 38 + typedef struct kiss_fastfir_state *kiss_fastfir_cfg; 39 + 40 + 41 + 42 + kiss_fastfir_cfg kiss_fastfir_alloc(const kffsamp_t * imp_resp,size_t n_imp_resp, 43 + size_t * nfft,void * mem,size_t*lenmem); 44 + 45 + /* see do_file_filter for usage */ 46 + size_t kiss_fastfir( kiss_fastfir_cfg cfg, kffsamp_t * inbuf, kffsamp_t * outbuf, size_t n, size_t *offset); 47 + 48 + 49 + 50 + static int verbose=0; 51 + 52 + 53 + struct kiss_fastfir_state{ 54 + size_t nfft; 55 + size_t ngood; 56 + kfcfg_t fftcfg; 57 + kfcfg_t ifftcfg; 58 + kiss_fft_cpx * fir_freq_resp; 59 + kiss_fft_cpx * freqbuf; 60 + size_t n_freq_bins; 61 + kffsamp_t * tmpbuf; 62 + }; 63 + 64 + 65 + kiss_fastfir_cfg kiss_fastfir_alloc( 66 + const kffsamp_t * imp_resp,size_t n_imp_resp, 67 + size_t *pnfft, /* if <= 0, an appropriate size will be chosen */ 68 + void * mem,size_t*lenmem) 69 + { 70 + kiss_fastfir_cfg st = NULL; 71 + size_t len_fftcfg,len_ifftcfg; 72 + size_t memneeded = sizeof(struct kiss_fastfir_state); 73 + char * ptr; 74 + size_t i; 75 + size_t nfft=0; 76 + float scale; 77 + int n_freq_bins; 78 + if (pnfft) 79 + nfft=*pnfft; 80 + 81 + if (nfft<=0) { 82 + /* determine fft size as next power of two at least 2x 83 + the impulse response length*/ 84 + i=n_imp_resp-1; 85 + nfft=2; 86 + do{ 87 + nfft<<=1; 88 + }while (i>>=1); 89 + #ifdef MIN_FFT_LEN 90 + if ( nfft < MIN_FFT_LEN ) 91 + nfft=MIN_FFT_LEN; 92 + #endif 93 + } 94 + if (pnfft) 95 + *pnfft = nfft; 96 + 97 + #ifdef REAL_FASTFIR 98 + n_freq_bins = nfft/2 + 1; 99 + #else 100 + n_freq_bins = nfft; 101 + #endif 102 + /*fftcfg*/ 103 + FFT_ALLOC (nfft, 0, NULL, &len_fftcfg); 104 + memneeded += len_fftcfg; 105 + /*ifftcfg*/ 106 + FFT_ALLOC (nfft, 1, NULL, &len_ifftcfg); 107 + memneeded += len_ifftcfg; 108 + /* tmpbuf */ 109 + memneeded += sizeof(kffsamp_t) * nfft; 110 + /* fir_freq_resp */ 111 + memneeded += sizeof(kiss_fft_cpx) * n_freq_bins; 112 + /* freqbuf */ 113 + memneeded += sizeof(kiss_fft_cpx) * n_freq_bins; 114 + 115 + if (lenmem == NULL) { 116 + st = (kiss_fastfir_cfg) malloc (memneeded); 117 + } else { 118 + if (*lenmem >= memneeded) 119 + st = (kiss_fastfir_cfg) mem; 120 + *lenmem = memneeded; 121 + } 122 + if (!st) 123 + return NULL; 124 + 125 + st->nfft = nfft; 126 + st->ngood = nfft - n_imp_resp + 1; 127 + st->n_freq_bins = n_freq_bins; 128 + ptr=(char*)(st+1); 129 + 130 + st->fftcfg = (kfcfg_t)ptr; 131 + ptr += len_fftcfg; 132 + 133 + st->ifftcfg = (kfcfg_t)ptr; 134 + ptr += len_ifftcfg; 135 + 136 + st->tmpbuf = (kffsamp_t*)ptr; 137 + ptr += sizeof(kffsamp_t) * nfft; 138 + 139 + st->freqbuf = (kiss_fft_cpx*)ptr; 140 + ptr += sizeof(kiss_fft_cpx) * n_freq_bins; 141 + 142 + st->fir_freq_resp = (kiss_fft_cpx*)ptr; 143 + ptr += sizeof(kiss_fft_cpx) * n_freq_bins; 144 + 145 + FFT_ALLOC (nfft,0,st->fftcfg , &len_fftcfg); 146 + FFT_ALLOC (nfft,1,st->ifftcfg , &len_ifftcfg); 147 + 148 + memset(st->tmpbuf,0,sizeof(kffsamp_t)*nfft); 149 + /*zero pad in the middle to left-rotate the impulse response 150 + This puts the scrap samples at the end of the inverse fft'd buffer */ 151 + st->tmpbuf[0] = imp_resp[ n_imp_resp - 1 ]; 152 + for (i=0;i<n_imp_resp - 1; ++i) { 153 + st->tmpbuf[ nfft - n_imp_resp + 1 + i ] = imp_resp[ i ]; 154 + } 155 + 156 + FFTFWD(st->fftcfg,st->tmpbuf,st->fir_freq_resp); 157 + 158 + /* TODO: this won't work for fixed point */ 159 + scale = 1.0 / st->nfft; 160 + 161 + for ( i=0; i < st->n_freq_bins; ++i ) { 162 + #ifdef USE_SIMD 163 + st->fir_freq_resp[i].r *= _mm_set1_ps(scale); 164 + st->fir_freq_resp[i].i *= _mm_set1_ps(scale); 165 + #else 166 + st->fir_freq_resp[i].r *= scale; 167 + st->fir_freq_resp[i].i *= scale; 168 + #endif 169 + } 170 + return st; 171 + } 172 + 173 + static void fastconv1buf(const kiss_fastfir_cfg st,const kffsamp_t * in,kffsamp_t * out) 174 + { 175 + size_t i; 176 + /* multiply the frequency response of the input signal by 177 + that of the fir filter*/ 178 + FFTFWD( st->fftcfg, in , st->freqbuf ); 179 + for ( i=0; i<st->n_freq_bins; ++i ) { 180 + kiss_fft_cpx tmpsamp; 181 + C_MUL(tmpsamp,st->freqbuf[i],st->fir_freq_resp[i]); 182 + st->freqbuf[i] = tmpsamp; 183 + } 184 + 185 + /* perform the inverse fft*/ 186 + FFTINV(st->ifftcfg,st->freqbuf,out); 187 + } 188 + 189 + /* n : the size of inbuf and outbuf in samples 190 + return value: the number of samples completely processed 191 + n-retval samples should be copied to the front of the next input buffer */ 192 + static size_t kff_nocopy( 193 + kiss_fastfir_cfg st, 194 + const kffsamp_t * inbuf, 195 + kffsamp_t * outbuf, 196 + size_t n) 197 + { 198 + size_t norig=n; 199 + while (n >= st->nfft ) { 200 + fastconv1buf(st,inbuf,outbuf); 201 + inbuf += st->ngood; 202 + outbuf += st->ngood; 203 + n -= st->ngood; 204 + } 205 + return norig - n; 206 + } 207 + 208 + static 209 + size_t kff_flush(kiss_fastfir_cfg st,const kffsamp_t * inbuf,kffsamp_t * outbuf,size_t n) 210 + { 211 + size_t zpad=0,ntmp; 212 + 213 + ntmp = kff_nocopy(st,inbuf,outbuf,n); 214 + n -= ntmp; 215 + inbuf += ntmp; 216 + outbuf += ntmp; 217 + 218 + zpad = st->nfft - n; 219 + memset(st->tmpbuf,0,sizeof(kffsamp_t)*st->nfft ); 220 + memcpy(st->tmpbuf,inbuf,sizeof(kffsamp_t)*n ); 221 + 222 + fastconv1buf(st,st->tmpbuf,st->tmpbuf); 223 + 224 + memcpy(outbuf,st->tmpbuf,sizeof(kffsamp_t)*( st->ngood - zpad )); 225 + return ntmp + st->ngood - zpad; 226 + } 227 + 228 + size_t kiss_fastfir( 229 + kiss_fastfir_cfg vst, 230 + kffsamp_t * inbuf, 231 + kffsamp_t * outbuf, 232 + size_t n_new, 233 + size_t *offset) 234 + { 235 + size_t ntot = n_new + *offset; 236 + if (n_new==0) { 237 + return kff_flush(vst,inbuf,outbuf,ntot); 238 + }else{ 239 + size_t nwritten = kff_nocopy(vst,inbuf,outbuf,ntot); 240 + *offset = ntot - nwritten; 241 + /*save the unused or underused samples at the front of the input buffer */ 242 + memcpy( inbuf , inbuf+nwritten , *offset * sizeof(kffsamp_t) ); 243 + return nwritten; 244 + } 245 + } 246 + 247 + #ifdef FAST_FILT_UTIL 248 + #include <unistd.h> 249 + #include <sys/types.h> 250 + #include <sys/mman.h> 251 + #include <assert.h> 252 + 253 + static 254 + void direct_file_filter( 255 + FILE * fin, 256 + FILE * fout, 257 + const kffsamp_t * imp_resp, 258 + size_t n_imp_resp) 259 + { 260 + size_t nlag = n_imp_resp - 1; 261 + 262 + const kffsamp_t *tmph; 263 + kffsamp_t *buf, *circbuf; 264 + kffsamp_t outval; 265 + size_t nread; 266 + size_t nbuf; 267 + size_t oldestlag = 0; 268 + size_t k, tap; 269 + #ifndef REAL_FASTFIR 270 + kffsamp_t tmp; 271 + #endif 272 + 273 + nbuf = 4096; 274 + buf = (kffsamp_t *) malloc ( sizeof (kffsamp_t) * nbuf); 275 + circbuf = (kffsamp_t *) malloc (sizeof (kffsamp_t) * nlag); 276 + if (!circbuf || !buf) { 277 + perror("circbuf allocation"); 278 + exit(1); 279 + } 280 + 281 + if ( fread (circbuf, sizeof (kffsamp_t), nlag, fin) != nlag ) { 282 + perror ("insufficient data to overcome transient"); 283 + exit (1); 284 + } 285 + 286 + do { 287 + nread = fread (buf, sizeof (kffsamp_t), nbuf, fin); 288 + if (nread <= 0) 289 + break; 290 + 291 + for (k = 0; k < nread; ++k) { 292 + tmph = imp_resp+nlag; 293 + #ifdef REAL_FASTFIR 294 + # ifdef USE_SIMD 295 + outval = _mm_set1_ps(0); 296 + #else 297 + outval = 0; 298 + #endif 299 + for (tap = oldestlag; tap < nlag; ++tap) 300 + outval += circbuf[tap] * *tmph--; 301 + for (tap = 0; tap < oldestlag; ++tap) 302 + outval += circbuf[tap] * *tmph--; 303 + outval += buf[k] * *tmph; 304 + #else 305 + # ifdef USE_SIMD 306 + outval.r = outval.i = _mm_set1_ps(0); 307 + #else 308 + outval.r = outval.i = 0; 309 + #endif 310 + for (tap = oldestlag; tap < nlag; ++tap){ 311 + C_MUL(tmp,circbuf[tap],*tmph); 312 + --tmph; 313 + C_ADDTO(outval,tmp); 314 + } 315 + 316 + for (tap = 0; tap < oldestlag; ++tap) { 317 + C_MUL(tmp,circbuf[tap],*tmph); 318 + --tmph; 319 + C_ADDTO(outval,tmp); 320 + } 321 + C_MUL(tmp,buf[k],*tmph); 322 + C_ADDTO(outval,tmp); 323 + #endif 324 + 325 + circbuf[oldestlag++] = buf[k]; 326 + buf[k] = outval; 327 + 328 + if (oldestlag == nlag) 329 + oldestlag = 0; 330 + } 331 + 332 + if (fwrite (buf, sizeof (buf[0]), nread, fout) != nread) { 333 + perror ("short write"); 334 + exit (1); 335 + } 336 + } while (nread); 337 + free (buf); 338 + free (circbuf); 339 + } 340 + 341 + static 342 + void do_file_filter( 343 + FILE * fin, 344 + FILE * fout, 345 + const kffsamp_t * imp_resp, 346 + size_t n_imp_resp, 347 + size_t nfft ) 348 + { 349 + int fdout; 350 + size_t n_samps_buf; 351 + 352 + kiss_fastfir_cfg cfg; 353 + kffsamp_t *inbuf,*outbuf; 354 + int nread,nwrite; 355 + size_t idx_inbuf; 356 + 357 + fdout = fileno(fout); 358 + 359 + cfg=kiss_fastfir_alloc(imp_resp,n_imp_resp,&nfft,0,0); 360 + 361 + /* use length to minimize buffer shift*/ 362 + n_samps_buf = 8*4096/sizeof(kffsamp_t); 363 + n_samps_buf = nfft + 4*(nfft-n_imp_resp+1); 364 + 365 + if (verbose) fprintf(stderr,"bufsize=%d\n",(int)(sizeof(kffsamp_t)*n_samps_buf) ); 366 + 367 + 368 + /*allocate space and initialize pointers */ 369 + inbuf = (kffsamp_t*)malloc(sizeof(kffsamp_t)*n_samps_buf); 370 + outbuf = (kffsamp_t*)malloc(sizeof(kffsamp_t)*n_samps_buf); 371 + 372 + idx_inbuf=0; 373 + do{ 374 + /* start reading at inbuf[idx_inbuf] */ 375 + nread = fread( inbuf + idx_inbuf, sizeof(kffsamp_t), n_samps_buf - idx_inbuf,fin ); 376 + 377 + /* If nread==0, then this is a flush. 378 + The total number of samples in input is idx_inbuf + nread . */ 379 + nwrite = kiss_fastfir(cfg, inbuf, outbuf,nread,&idx_inbuf) * sizeof(kffsamp_t); 380 + /* kiss_fastfir moved any unused samples to the front of inbuf and updated idx_inbuf */ 381 + 382 + if ( write(fdout, outbuf, nwrite) != nwrite ) { 383 + perror("short write"); 384 + exit(1); 385 + } 386 + }while ( nread ); 387 + free(cfg); 388 + free(inbuf); 389 + free(outbuf); 390 + } 391 + 392 + int main(int argc,char**argv) 393 + { 394 + kffsamp_t * h; 395 + int use_direct=0; 396 + size_t nh,nfft=0; 397 + FILE *fin=stdin; 398 + FILE *fout=stdout; 399 + FILE *filtfile=NULL; 400 + while (1) { 401 + int c=getopt(argc,argv,"n:h:i:o:vd"); 402 + if (c==-1) break; 403 + switch (c) { 404 + case 'v': 405 + verbose=1; 406 + break; 407 + case 'n': 408 + nfft=atoi(optarg); 409 + break; 410 + case 'i': 411 + fin = fopen(optarg,"rb"); 412 + if (fin==NULL) { 413 + perror(optarg); 414 + exit(1); 415 + } 416 + break; 417 + case 'o': 418 + fout = fopen(optarg,"w+b"); 419 + if (fout==NULL) { 420 + perror(optarg); 421 + exit(1); 422 + } 423 + break; 424 + case 'h': 425 + filtfile = fopen(optarg,"rb"); 426 + if (filtfile==NULL) { 427 + perror(optarg); 428 + exit(1); 429 + } 430 + break; 431 + case 'd': 432 + use_direct=1; 433 + break; 434 + case '?': 435 + fprintf(stderr,"usage options:\n" 436 + "\t-n nfft: fft size to use\n" 437 + "\t-d : use direct FIR filtering, not fast convolution\n" 438 + "\t-i filename: input file\n" 439 + "\t-o filename: output(filtered) file\n" 440 + "\t-n nfft: fft size to use\n" 441 + "\t-h filename: impulse response\n"); 442 + exit (1); 443 + default:fprintf(stderr,"bad %c\n",c);break; 444 + } 445 + } 446 + if (filtfile==NULL) { 447 + fprintf(stderr,"You must supply the FIR coeffs via -h\n"); 448 + exit(1); 449 + } 450 + fseek(filtfile,0,SEEK_END); 451 + nh = ftell(filtfile) / sizeof(kffsamp_t); 452 + if (verbose) fprintf(stderr,"%d samples in FIR filter\n",(int)nh); 453 + h = (kffsamp_t*)malloc(sizeof(kffsamp_t)*nh); 454 + fseek(filtfile,0,SEEK_SET); 455 + if (fread(h,sizeof(kffsamp_t),nh,filtfile) != nh) 456 + fprintf(stderr,"short read on filter file\n"); 457 + 458 + fclose(filtfile); 459 + 460 + if (use_direct) 461 + direct_file_filter( fin, fout, h,nh); 462 + else 463 + do_file_filter( fin, fout, h,nh,nfft); 464 + 465 + if (fout!=stdout) fclose(fout); 466 + if (fin!=stdin) fclose(fin); 467 + 468 + return 0; 469 + } 470 + #endif
+193
tools/kiss_fftnd.c
··· 1 + 2 + 3 + /* 4 + Copyright (c) 2003-2004, Mark Borgerding 5 + 6 + All rights reserved. 7 + 8 + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 9 + 10 + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 11 + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 12 + * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. 13 + 14 + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 15 + */ 16 + 17 + #include "kiss_fftnd.h" 18 + #include "_kiss_fft_guts.h" 19 + 20 + struct kiss_fftnd_state{ 21 + int dimprod; /* dimsum would be mighty tasty right now */ 22 + int ndims; 23 + int *dims; 24 + kiss_fft_cfg *states; /* cfg states for each dimension */ 25 + kiss_fft_cpx * tmpbuf; /*buffer capable of hold the entire input */ 26 + }; 27 + 28 + kiss_fftnd_cfg kiss_fftnd_alloc(const int *dims,int ndims,int inverse_fft,void*mem,size_t*lenmem) 29 + { 30 + kiss_fftnd_cfg st = NULL; 31 + int i; 32 + int dimprod=1; 33 + size_t memneeded = sizeof(struct kiss_fftnd_state); 34 + char * ptr; 35 + 36 + for (i=0;i<ndims;++i) { 37 + size_t sublen=0; 38 + kiss_fft_alloc (dims[i], inverse_fft, NULL, &sublen); 39 + memneeded += sublen; /* st->states[i] */ 40 + dimprod *= dims[i]; 41 + } 42 + memneeded += sizeof(int) * ndims;/* st->dims */ 43 + memneeded += sizeof(void*) * ndims;/* st->states */ 44 + memneeded += sizeof(kiss_fft_cpx) * dimprod; /* st->tmpbuf */ 45 + 46 + if (lenmem == NULL) {/* allocate for the caller*/ 47 + st = (kiss_fftnd_cfg) malloc (memneeded); 48 + } else { /* initialize supplied buffer if big enough */ 49 + if (*lenmem >= memneeded) 50 + st = (kiss_fftnd_cfg) mem; 51 + *lenmem = memneeded; /*tell caller how big struct is (or would be) */ 52 + } 53 + if (!st) 54 + return NULL; /*malloc failed or buffer too small */ 55 + 56 + st->dimprod = dimprod; 57 + st->ndims = ndims; 58 + ptr=(char*)(st+1); 59 + 60 + st->states = (kiss_fft_cfg *)ptr; 61 + ptr += sizeof(void*) * ndims; 62 + 63 + st->dims = (int*)ptr; 64 + ptr += sizeof(int) * ndims; 65 + 66 + st->tmpbuf = (kiss_fft_cpx*)ptr; 67 + ptr += sizeof(kiss_fft_cpx) * dimprod; 68 + 69 + for (i=0;i<ndims;++i) { 70 + size_t len; 71 + st->dims[i] = dims[i]; 72 + kiss_fft_alloc (st->dims[i], inverse_fft, NULL, &len); 73 + st->states[i] = kiss_fft_alloc (st->dims[i], inverse_fft, ptr,&len); 74 + ptr += len; 75 + } 76 + /* 77 + Hi there! 78 + 79 + If you're looking at this particular code, it probably means you've got a brain-dead bounds checker 80 + that thinks the above code overwrites the end of the array. 81 + 82 + It doesn't. 83 + 84 + -- Mark 85 + 86 + P.S. 87 + The below code might give you some warm fuzzies and help convince you. 88 + */ 89 + if ( ptr - (char*)st != (int)memneeded ) { 90 + fprintf(stderr, 91 + "################################################################################\n" 92 + "Internal error! Memory allocation miscalculation\n" 93 + "################################################################################\n" 94 + ); 95 + } 96 + return st; 97 + } 98 + 99 + /* 100 + This works by tackling one dimension at a time. 101 + 102 + In effect, 103 + Each stage starts out by reshaping the matrix into a DixSi 2d matrix. 104 + A Di-sized fft is taken of each column, transposing the matrix as it goes. 105 + 106 + Here's a 3-d example: 107 + Take a 2x3x4 matrix, laid out in memory as a contiguous buffer 108 + [ [ [ a b c d ] [ e f g h ] [ i j k l ] ] 109 + [ [ m n o p ] [ q r s t ] [ u v w x ] ] ] 110 + 111 + Stage 0 ( D=2): treat the buffer as a 2x12 matrix 112 + [ [a b ... k l] 113 + [m n ... w x] ] 114 + 115 + FFT each column with size 2. 116 + Transpose the matrix at the same time using kiss_fft_stride. 117 + 118 + [ [ a+m a-m ] 119 + [ b+n b-n] 120 + ... 121 + [ k+w k-w ] 122 + [ l+x l-x ] ] 123 + 124 + Note fft([x y]) == [x+y x-y] 125 + 126 + Stage 1 ( D=3) treats the buffer (the output of stage D=2) as an 3x8 matrix, 127 + [ [ a+m a-m b+n b-n c+o c-o d+p d-p ] 128 + [ e+q e-q f+r f-r g+s g-s h+t h-t ] 129 + [ i+u i-u j+v j-v k+w k-w l+x l-x ] ] 130 + 131 + And perform FFTs (size=3) on each of the columns as above, transposing 132 + the matrix as it goes. The output of stage 1 is 133 + (Legend: ap = [ a+m e+q i+u ] 134 + am = [ a-m e-q i-u ] ) 135 + 136 + [ [ sum(ap) fft(ap)[0] fft(ap)[1] ] 137 + [ sum(am) fft(am)[0] fft(am)[1] ] 138 + [ sum(bp) fft(bp)[0] fft(bp)[1] ] 139 + [ sum(bm) fft(bm)[0] fft(bm)[1] ] 140 + [ sum(cp) fft(cp)[0] fft(cp)[1] ] 141 + [ sum(cm) fft(cm)[0] fft(cm)[1] ] 142 + [ sum(dp) fft(dp)[0] fft(dp)[1] ] 143 + [ sum(dm) fft(dm)[0] fft(dm)[1] ] ] 144 + 145 + Stage 2 ( D=4) treats this buffer as a 4*6 matrix, 146 + [ [ sum(ap) fft(ap)[0] fft(ap)[1] sum(am) fft(am)[0] fft(am)[1] ] 147 + [ sum(bp) fft(bp)[0] fft(bp)[1] sum(bm) fft(bm)[0] fft(bm)[1] ] 148 + [ sum(cp) fft(cp)[0] fft(cp)[1] sum(cm) fft(cm)[0] fft(cm)[1] ] 149 + [ sum(dp) fft(dp)[0] fft(dp)[1] sum(dm) fft(dm)[0] fft(dm)[1] ] ] 150 + 151 + Then FFTs each column, transposing as it goes. 152 + 153 + The resulting matrix is the 3d FFT of the 2x3x4 input matrix. 154 + 155 + Note as a sanity check that the first element of the final 156 + stage's output (DC term) is 157 + sum( [ sum(ap) sum(bp) sum(cp) sum(dp) ] ) 158 + , i.e. the summation of all 24 input elements. 159 + 160 + */ 161 + void kiss_fftnd(kiss_fftnd_cfg st,const kiss_fft_cpx *fin,kiss_fft_cpx *fout) 162 + { 163 + int i,k; 164 + const kiss_fft_cpx * bufin=fin; 165 + kiss_fft_cpx * bufout; 166 + 167 + /*arrange it so the last bufout == fout*/ 168 + if ( st->ndims & 1 ) { 169 + bufout = fout; 170 + if (fin==fout) { 171 + memcpy( st->tmpbuf, fin, sizeof(kiss_fft_cpx) * st->dimprod ); 172 + bufin = st->tmpbuf; 173 + } 174 + }else 175 + bufout = st->tmpbuf; 176 + 177 + for ( k=0; k < st->ndims; ++k) { 178 + int curdim = st->dims[k]; 179 + int stride = st->dimprod / curdim; 180 + 181 + for ( i=0 ; i<stride ; ++i ) 182 + kiss_fft_stride( st->states[k], bufin+i , bufout+i*curdim, stride ); 183 + 184 + /*toggle back and forth between the two buffers*/ 185 + if (bufout == st->tmpbuf){ 186 + bufout = fout; 187 + bufin = st->tmpbuf; 188 + }else{ 189 + bufout = st->tmpbuf; 190 + bufin = fout; 191 + } 192 + } 193 + }
+18
tools/kiss_fftnd.h
··· 1 + #ifndef KISS_FFTND_H 2 + #define KISS_FFTND_H 3 + 4 + #include "kiss_fft.h" 5 + 6 + #ifdef __cplusplus 7 + extern "C" { 8 + #endif 9 + 10 + typedef struct kiss_fftnd_state * kiss_fftnd_cfg; 11 + 12 + kiss_fftnd_cfg kiss_fftnd_alloc(const int *dims,int ndims,int inverse_fft,void*mem,size_t*lenmem); 13 + void kiss_fftnd(kiss_fftnd_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout); 14 + 15 + #ifdef __cplusplus 16 + } 17 + #endif 18 + #endif
+118
tools/kiss_fftndr.c
··· 1 + /* 2 + Copyright (c) 2003-2004, Mark Borgerding 3 + 4 + All rights reserved. 5 + 6 + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 7 + 8 + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 9 + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 10 + * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 + 12 + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 13 + */ 14 + 15 + #include "kiss_fftndr.h" 16 + #include "_kiss_fft_guts.h" 17 + #define MAX(x,y) ( ( (x)<(y) )?(y):(x) ) 18 + 19 + struct kiss_fftndr_state 20 + { 21 + int dimReal; 22 + int dimOther; 23 + kiss_fftr_cfg cfg_r; 24 + kiss_fftnd_cfg cfg_nd; 25 + void * tmpbuf; 26 + }; 27 + 28 + static int prod(const int *dims, int ndims) 29 + { 30 + int x=1; 31 + while (ndims--) 32 + x *= *dims++; 33 + return x; 34 + } 35 + 36 + kiss_fftndr_cfg kiss_fftndr_alloc(const int *dims,int ndims,int inverse_fft,void*mem,size_t*lenmem) 37 + { 38 + kiss_fftndr_cfg st = NULL; 39 + size_t nr=0 , nd=0,ntmp=0; 40 + int dimReal = dims[ndims-1]; 41 + int dimOther = prod(dims,ndims-1); 42 + size_t memneeded; 43 + 44 + (void)kiss_fftr_alloc(dimReal,inverse_fft,NULL,&nr); 45 + (void)kiss_fftnd_alloc(dims,ndims-1,inverse_fft,NULL,&nd); 46 + ntmp = 47 + MAX( 2*dimOther , dimReal+2) * sizeof(kiss_fft_scalar) // freq buffer for one pass 48 + + dimOther*(dimReal+2) * sizeof(kiss_fft_scalar); // large enough to hold entire input in case of in-place 49 + 50 + memneeded = sizeof( struct kiss_fftndr_state ) + nr + nd + ntmp; 51 + 52 + if (lenmem==NULL) { 53 + st = (kiss_fftndr_cfg) malloc(memneeded); 54 + }else{ 55 + if (*lenmem >= memneeded) 56 + st = (kiss_fftndr_cfg)mem; 57 + *lenmem = memneeded; 58 + } 59 + if (st==NULL) 60 + return NULL; 61 + memset( st , 0 , memneeded); 62 + 63 + st->dimReal = dimReal; 64 + st->dimOther = dimOther; 65 + st->cfg_r = kiss_fftr_alloc( dimReal,inverse_fft,st+1,&nr); 66 + st->cfg_nd = kiss_fftnd_alloc(dims,ndims-1,inverse_fft, ((char*) st->cfg_r)+nr,&nd); 67 + st->tmpbuf = (char*)st->cfg_nd + nd; 68 + 69 + return st; 70 + } 71 + 72 + void kiss_fftndr(kiss_fftndr_cfg st,const kiss_fft_scalar *timedata,kiss_fft_cpx *freqdata) 73 + { 74 + int k1,k2; 75 + int dimReal = st->dimReal; 76 + int dimOther = st->dimOther; 77 + int nrbins = dimReal/2+1; 78 + 79 + kiss_fft_cpx * tmp1 = (kiss_fft_cpx*)st->tmpbuf; 80 + kiss_fft_cpx * tmp2 = tmp1 + MAX(nrbins,dimOther); 81 + 82 + // timedata is N0 x N1 x ... x Nk real 83 + 84 + // take a real chunk of data, fft it and place the output at correct intervals 85 + for (k1=0;k1<dimOther;++k1) { 86 + kiss_fftr( st->cfg_r, timedata + k1*dimReal , tmp1 ); // tmp1 now holds nrbins complex points 87 + for (k2=0;k2<nrbins;++k2) 88 + tmp2[ k2*dimOther+k1 ] = tmp1[k2]; 89 + } 90 + 91 + for (k2=0;k2<nrbins;++k2) { 92 + kiss_fftnd(st->cfg_nd, tmp2+k2*dimOther, tmp1); // tmp1 now holds dimOther complex points 93 + for (k1=0;k1<dimOther;++k1) 94 + freqdata[ k1*(nrbins) + k2] = tmp1[k1]; 95 + } 96 + } 97 + 98 + void kiss_fftndri(kiss_fftndr_cfg st,const kiss_fft_cpx *freqdata,kiss_fft_scalar *timedata) 99 + { 100 + int k1,k2; 101 + int dimReal = st->dimReal; 102 + int dimOther = st->dimOther; 103 + int nrbins = dimReal/2+1; 104 + kiss_fft_cpx * tmp1 = (kiss_fft_cpx*)st->tmpbuf; 105 + kiss_fft_cpx * tmp2 = tmp1 + MAX(nrbins,dimOther); 106 + 107 + for (k2=0;k2<nrbins;++k2) { 108 + for (k1=0;k1<dimOther;++k1) 109 + tmp1[k1] = freqdata[ k1*(nrbins) + k2 ]; 110 + kiss_fftnd(st->cfg_nd, tmp1, tmp2+k2*dimOther); 111 + } 112 + 113 + for (k1=0;k1<dimOther;++k1) { 114 + for (k2=0;k2<nrbins;++k2) 115 + tmp1[k2] = tmp2[ k2*dimOther+k1 ]; 116 + kiss_fftri( st->cfg_r,tmp1,timedata + k1*dimReal); 117 + } 118 + }
+47
tools/kiss_fftndr.h
··· 1 + #ifndef KISS_NDR_H 2 + #define KISS_NDR_H 3 + 4 + #include "kiss_fft.h" 5 + #include "kiss_fftr.h" 6 + #include "kiss_fftnd.h" 7 + 8 + #ifdef __cplusplus 9 + extern "C" { 10 + #endif 11 + 12 + typedef struct kiss_fftndr_state *kiss_fftndr_cfg; 13 + 14 + 15 + kiss_fftndr_cfg kiss_fftndr_alloc(const int *dims,int ndims,int inverse_fft,void*mem,size_t*lenmem); 16 + /* 17 + dims[0] must be even 18 + 19 + If you don't care to allocate space, use mem = lenmem = NULL 20 + */ 21 + 22 + 23 + void kiss_fftndr( 24 + kiss_fftndr_cfg cfg, 25 + const kiss_fft_scalar *timedata, 26 + kiss_fft_cpx *freqdata); 27 + /* 28 + input timedata has dims[0] X dims[1] X ... X dims[ndims-1] scalar points 29 + output freqdata has dims[0] X dims[1] X ... X dims[ndims-1]/2+1 complex points 30 + */ 31 + 32 + void kiss_fftndri( 33 + kiss_fftndr_cfg cfg, 34 + const kiss_fft_cpx *freqdata, 35 + kiss_fft_scalar *timedata); 36 + /* 37 + input and output dimensions are the exact opposite of kiss_fftndr 38 + */ 39 + 40 + 41 + #define kiss_fftr_free free 42 + 43 + #ifdef __cplusplus 44 + } 45 + #endif 46 + 47 + #endif
+159
tools/kiss_fftr.c
··· 1 + /* 2 + Copyright (c) 2003-2004, Mark Borgerding 3 + 4 + All rights reserved. 5 + 6 + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 7 + 8 + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 9 + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 10 + * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 + 12 + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 13 + */ 14 + 15 + #include "kiss_fftr.h" 16 + #include "_kiss_fft_guts.h" 17 + 18 + struct kiss_fftr_state{ 19 + kiss_fft_cfg substate; 20 + kiss_fft_cpx * tmpbuf; 21 + kiss_fft_cpx * super_twiddles; 22 + #ifdef USE_SIMD 23 + void * pad; 24 + #endif 25 + }; 26 + 27 + kiss_fftr_cfg kiss_fftr_alloc(int nfft,int inverse_fft,void * mem,size_t * lenmem) 28 + { 29 + int i; 30 + kiss_fftr_cfg st = NULL; 31 + size_t subsize, memneeded; 32 + 33 + if (nfft & 1) { 34 + fprintf(stderr,"Real FFT optimization must be even.\n"); 35 + return NULL; 36 + } 37 + nfft >>= 1; 38 + 39 + kiss_fft_alloc (nfft, inverse_fft, NULL, &subsize); 40 + memneeded = sizeof(struct kiss_fftr_state) + subsize + sizeof(kiss_fft_cpx) * ( nfft * 3 / 2); 41 + 42 + if (lenmem == NULL) { 43 + st = (kiss_fftr_cfg) KISS_FFT_MALLOC (memneeded); 44 + } else { 45 + if (*lenmem >= memneeded) 46 + st = (kiss_fftr_cfg) mem; 47 + *lenmem = memneeded; 48 + } 49 + if (!st) 50 + return NULL; 51 + 52 + st->substate = (kiss_fft_cfg) (st + 1); /*just beyond kiss_fftr_state struct */ 53 + st->tmpbuf = (kiss_fft_cpx *) (((char *) st->substate) + subsize); 54 + st->super_twiddles = st->tmpbuf + nfft; 55 + kiss_fft_alloc(nfft, inverse_fft, st->substate, &subsize); 56 + 57 + for (i = 0; i < nfft/2; ++i) { 58 + double phase = 59 + -3.14159265358979323846264338327 * ((double) (i+1) / nfft + .5); 60 + if (inverse_fft) 61 + phase *= -1; 62 + kf_cexp (st->super_twiddles+i,phase); 63 + } 64 + return st; 65 + } 66 + 67 + void kiss_fftr(kiss_fftr_cfg st,const kiss_fft_scalar *timedata,kiss_fft_cpx *freqdata) 68 + { 69 + /* input buffer timedata is stored row-wise */ 70 + int k,ncfft; 71 + kiss_fft_cpx fpnk,fpk,f1k,f2k,tw,tdc; 72 + 73 + if ( st->substate->inverse) { 74 + fprintf(stderr,"kiss fft usage error: improper alloc\n"); 75 + exit(1); 76 + } 77 + 78 + ncfft = st->substate->nfft; 79 + 80 + /*perform the parallel fft of two real signals packed in real,imag*/ 81 + kiss_fft( st->substate , (const kiss_fft_cpx*)timedata, st->tmpbuf ); 82 + /* The real part of the DC element of the frequency spectrum in st->tmpbuf 83 + * contains the sum of the even-numbered elements of the input time sequence 84 + * The imag part is the sum of the odd-numbered elements 85 + * 86 + * The sum of tdc.r and tdc.i is the sum of the input time sequence. 87 + * yielding DC of input time sequence 88 + * The difference of tdc.r - tdc.i is the sum of the input (dot product) [1,-1,1,-1... 89 + * yielding Nyquist bin of input time sequence 90 + */ 91 + 92 + tdc.r = st->tmpbuf[0].r; 93 + tdc.i = st->tmpbuf[0].i; 94 + C_FIXDIV(tdc,2); 95 + CHECK_OVERFLOW_OP(tdc.r ,+, tdc.i); 96 + CHECK_OVERFLOW_OP(tdc.r ,-, tdc.i); 97 + freqdata[0].r = tdc.r + tdc.i; 98 + freqdata[ncfft].r = tdc.r - tdc.i; 99 + #ifdef USE_SIMD 100 + freqdata[ncfft].i = freqdata[0].i = _mm_set1_ps(0); 101 + #else 102 + freqdata[ncfft].i = freqdata[0].i = 0; 103 + #endif 104 + 105 + for ( k=1;k <= ncfft/2 ; ++k ) { 106 + fpk = st->tmpbuf[k]; 107 + fpnk.r = st->tmpbuf[ncfft-k].r; 108 + fpnk.i = - st->tmpbuf[ncfft-k].i; 109 + C_FIXDIV(fpk,2); 110 + C_FIXDIV(fpnk,2); 111 + 112 + C_ADD( f1k, fpk , fpnk ); 113 + C_SUB( f2k, fpk , fpnk ); 114 + C_MUL( tw , f2k , st->super_twiddles[k-1]); 115 + 116 + freqdata[k].r = HALF_OF(f1k.r + tw.r); 117 + freqdata[k].i = HALF_OF(f1k.i + tw.i); 118 + freqdata[ncfft-k].r = HALF_OF(f1k.r - tw.r); 119 + freqdata[ncfft-k].i = HALF_OF(tw.i - f1k.i); 120 + } 121 + } 122 + 123 + void kiss_fftri(kiss_fftr_cfg st,const kiss_fft_cpx *freqdata,kiss_fft_scalar *timedata) 124 + { 125 + /* input buffer timedata is stored row-wise */ 126 + int k, ncfft; 127 + 128 + if (st->substate->inverse == 0) { 129 + fprintf (stderr, "kiss fft usage error: improper alloc\n"); 130 + exit (1); 131 + } 132 + 133 + ncfft = st->substate->nfft; 134 + 135 + st->tmpbuf[0].r = freqdata[0].r + freqdata[ncfft].r; 136 + st->tmpbuf[0].i = freqdata[0].r - freqdata[ncfft].r; 137 + C_FIXDIV(st->tmpbuf[0],2); 138 + 139 + for (k = 1; k <= ncfft / 2; ++k) { 140 + kiss_fft_cpx fk, fnkc, fek, fok, tmp; 141 + fk = freqdata[k]; 142 + fnkc.r = freqdata[ncfft - k].r; 143 + fnkc.i = -freqdata[ncfft - k].i; 144 + C_FIXDIV( fk , 2 ); 145 + C_FIXDIV( fnkc , 2 ); 146 + 147 + C_ADD (fek, fk, fnkc); 148 + C_SUB (tmp, fk, fnkc); 149 + C_MUL (fok, tmp, st->super_twiddles[k-1]); 150 + C_ADD (st->tmpbuf[k], fek, fok); 151 + C_SUB (st->tmpbuf[ncfft - k], fek, fok); 152 + #ifdef USE_SIMD 153 + st->tmpbuf[ncfft - k].i *= _mm_set1_ps(-1.0); 154 + #else 155 + st->tmpbuf[ncfft - k].i *= -1; 156 + #endif 157 + } 158 + kiss_fft (st->substate, st->tmpbuf, (kiss_fft_cpx *) timedata); 159 + }
+46
tools/kiss_fftr.h
··· 1 + #ifndef KISS_FTR_H 2 + #define KISS_FTR_H 3 + 4 + #include "kiss_fft.h" 5 + #ifdef __cplusplus 6 + extern "C" { 7 + #endif 8 + 9 + 10 + /* 11 + 12 + Real optimized version can save about 45% cpu time vs. complex fft of a real seq. 13 + 14 + 15 + 16 + */ 17 + 18 + typedef struct kiss_fftr_state *kiss_fftr_cfg; 19 + 20 + 21 + kiss_fftr_cfg kiss_fftr_alloc(int nfft,int inverse_fft,void * mem, size_t * lenmem); 22 + /* 23 + nfft must be even 24 + 25 + If you don't care to allocate space, use mem = lenmem = NULL 26 + */ 27 + 28 + 29 + void kiss_fftr(kiss_fftr_cfg cfg,const kiss_fft_scalar *timedata,kiss_fft_cpx *freqdata); 30 + /* 31 + input timedata has nfft scalar points 32 + output freqdata has nfft/2+1 complex points 33 + */ 34 + 35 + void kiss_fftri(kiss_fftr_cfg cfg,const kiss_fft_cpx *freqdata,kiss_fft_scalar *timedata); 36 + /* 37 + input freqdata has nfft/2+1 complex points 38 + output timedata has nfft scalar points 39 + */ 40 + 41 + #define kiss_fftr_free free 42 + 43 + #ifdef __cplusplus 44 + } 45 + #endif 46 + #endif
+235
tools/psdpng.c
··· 1 + /* 2 + Copyright (c) 2003-2004, Mark Borgerding 3 + 4 + All rights reserved. 5 + 6 + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 7 + 8 + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 9 + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 10 + * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 + 12 + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 13 + */ 14 + 15 + #include <stdlib.h> 16 + #include <math.h> 17 + #include <stdio.h> 18 + #include <string.h> 19 + #include <unistd.h> 20 + #include <png.h> 21 + 22 + #include "kiss_fft.h" 23 + #include "kiss_fftr.h" 24 + 25 + int nfft=1024; 26 + FILE * fin=NULL; 27 + FILE * fout=NULL; 28 + 29 + int navg=20; 30 + int remove_dc=0; 31 + int nrows=0; 32 + float * vals=NULL; 33 + int stereo=0; 34 + 35 + static 36 + void config(int argc,char** argv) 37 + { 38 + while (1) { 39 + int c = getopt (argc, argv, "n:r:as"); 40 + if (c == -1) 41 + break; 42 + switch (c) { 43 + case 'n': nfft=(int)atoi(optarg);break; 44 + case 'r': navg=(int)atoi(optarg);break; 45 + case 'a': remove_dc=1;break; 46 + case 's': stereo=1;break; 47 + case '?': 48 + fprintf (stderr, "usage options:\n" 49 + "\t-n d: fft dimension(s) [1024]\n" 50 + "\t-r d: number of rows to average [20]\n" 51 + "\t-a : remove average from each fft buffer\n" 52 + "\t-s : input is stereo, channels will be combined before fft\n" 53 + "16 bit machine format real input is assumed\n" 54 + ); 55 + default: 56 + fprintf (stderr, "bad %c\n", c); 57 + exit (1); 58 + break; 59 + } 60 + } 61 + if ( optind < argc ) { 62 + if (strcmp("-",argv[optind]) !=0) 63 + fin = fopen(argv[optind],"rb"); 64 + ++optind; 65 + } 66 + 67 + if ( optind < argc ) { 68 + if ( strcmp("-",argv[optind]) !=0 ) 69 + fout = fopen(argv[optind],"wb"); 70 + ++optind; 71 + } 72 + if (fin==NULL) 73 + fin=stdin; 74 + if (fout==NULL) 75 + fout=stdout; 76 + } 77 + 78 + #define CHECKNULL(p) if ( (p)==NULL ) do { fprintf(stderr,"CHECKNULL failed @ %s(%d): %s\n",__FILE__,__LINE__,#p );exit(1);} while(0) 79 + 80 + typedef struct 81 + { 82 + png_byte r; 83 + png_byte g; 84 + png_byte b; 85 + } rgb_t; 86 + 87 + static 88 + void val2rgb(float x,rgb_t *p) 89 + { 90 + const double pi = 3.14159265358979; 91 + p->g = (int)(255*sin(x*pi)); 92 + p->r = (int)(255*abs(sin(x*pi*3/2))); 93 + p->b = (int)(255*abs(sin(x*pi*5/2))); 94 + //fprintf(stderr,"%.2f : %d,%d,%d\n",x,(int)p->r,(int)p->g,(int)p->b); 95 + } 96 + 97 + static 98 + void cpx2pixels(rgb_t * res,const float * fbuf,size_t n) 99 + { 100 + size_t i; 101 + float minval,maxval,valrange; 102 + minval=maxval=fbuf[0]; 103 + 104 + for (i = 0; i < n; ++i) { 105 + if (fbuf[i] > maxval) maxval = fbuf[i]; 106 + if (fbuf[i] < minval) minval = fbuf[i]; 107 + } 108 + 109 + fprintf(stderr,"min ==%f,max=%f\n",minval,maxval); 110 + valrange = maxval-minval; 111 + if (valrange == 0) { 112 + fprintf(stderr,"min == max == %f\n",minval); 113 + exit (1); 114 + } 115 + 116 + for (i = 0; i < n; ++i) 117 + val2rgb( (fbuf[i] - minval)/valrange , res+i ); 118 + } 119 + 120 + static 121 + void transform_signal(void) 122 + { 123 + short *inbuf; 124 + kiss_fftr_cfg cfg=NULL; 125 + kiss_fft_scalar *tbuf; 126 + kiss_fft_cpx *fbuf; 127 + float *mag2buf; 128 + int i; 129 + int n; 130 + int avgctr=0; 131 + 132 + int nfreqs=nfft/2+1; 133 + 134 + CHECKNULL( cfg=kiss_fftr_alloc(nfft,0,0,0) ); 135 + CHECKNULL( inbuf=(short*)malloc(sizeof(short)*2*nfft ) ); 136 + CHECKNULL( tbuf=(kiss_fft_scalar*)malloc(sizeof(kiss_fft_scalar)*nfft ) ); 137 + CHECKNULL( fbuf=(kiss_fft_cpx*)malloc(sizeof(kiss_fft_cpx)*nfreqs ) ); 138 + CHECKNULL( mag2buf=(float*)malloc(sizeof(float)*nfreqs ) ); 139 + 140 + memset(mag2buf,0,sizeof(mag2buf)*nfreqs); 141 + 142 + while (1) { 143 + if (stereo) { 144 + n = fread(inbuf,sizeof(short)*2,nfft,fin); 145 + if (n != nfft ) 146 + break; 147 + for (i=0;i<nfft;++i) 148 + tbuf[i] = inbuf[2*i] + inbuf[2*i+1]; 149 + }else{ 150 + n = fread(inbuf,sizeof(short),nfft,fin); 151 + if (n != nfft ) 152 + break; 153 + for (i=0;i<nfft;++i) 154 + tbuf[i] = inbuf[i]; 155 + } 156 + 157 + if (remove_dc) { 158 + float avg = 0; 159 + for (i=0;i<nfft;++i) avg += tbuf[i]; 160 + avg /= nfft; 161 + for (i=0;i<nfft;++i) tbuf[i] -= (kiss_fft_scalar)avg; 162 + } 163 + 164 + /* do FFT */ 165 + kiss_fftr(cfg,tbuf,fbuf); 166 + 167 + for (i=0;i<nfreqs;++i) 168 + mag2buf[i] += fbuf[i].r * fbuf[i].r + fbuf[i].i * fbuf[i].i; 169 + 170 + if (++avgctr == navg) { 171 + avgctr=0; 172 + ++nrows; 173 + vals = (float*)realloc(vals,sizeof(float)*nrows*nfreqs); 174 + float eps = 1; 175 + for (i=0;i<nfreqs;++i) 176 + vals[(nrows - 1) * nfreqs + i] = 10 * log10 ( mag2buf[i] / navg + eps ); 177 + memset(mag2buf,0,sizeof(mag2buf[0])*nfreqs); 178 + } 179 + } 180 + 181 + free(cfg); 182 + free(inbuf); 183 + free(tbuf); 184 + free(fbuf); 185 + free(mag2buf); 186 + } 187 + 188 + static 189 + void make_png(void) 190 + { 191 + png_bytepp row_pointers=NULL; 192 + rgb_t * row_data=NULL; 193 + int i; 194 + int nfreqs = nfft/2+1; 195 + 196 + png_structp png_ptr=NULL; 197 + png_infop info_ptr=NULL; 198 + 199 + CHECKNULL( png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING,0,0,0) ); 200 + CHECKNULL( info_ptr = png_create_info_struct(png_ptr) ); 201 + 202 + 203 + png_init_io(png_ptr, fout ); 204 + png_set_IHDR(png_ptr, info_ptr ,nfreqs,nrows,8,PNG_COLOR_TYPE_RGB,PNG_INTERLACE_NONE,PNG_COMPRESSION_TYPE_DEFAULT,PNG_FILTER_TYPE_DEFAULT ); 205 + 206 + 207 + row_data = (rgb_t*)malloc(sizeof(rgb_t) * nrows * nfreqs) ; 208 + cpx2pixels(row_data, vals, nfreqs*nrows ); 209 + 210 + row_pointers = realloc(row_pointers, nrows*sizeof(png_bytep)); 211 + for (i=0;i<nrows;++i) { 212 + row_pointers[i] = (png_bytep)(row_data + i*nfreqs); 213 + } 214 + png_set_rows(png_ptr, info_ptr, row_pointers); 215 + 216 + 217 + fprintf(stderr,"creating %dx%d png\n",nfreqs,nrows); 218 + fprintf(stderr,"bitdepth %d \n",png_get_bit_depth(png_ptr,info_ptr ) ); 219 + 220 + png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY , NULL); 221 + 222 + } 223 + 224 + int main(int argc,char ** argv) 225 + { 226 + config(argc,argv); 227 + 228 + transform_signal(); 229 + 230 + make_png(); 231 + 232 + if (fout!=stdout) fclose(fout); 233 + if (fin!=stdin) fclose(fin); 234 + return 0; 235 + }