├── .gitignore ├── .hgignore ├── CHANGELOG ├── COPYING ├── LICENSES ├── BSD-3-Clause └── Unlicense ├── Makefile ├── README ├── README.simd ├── TIPS ├── _kiss_fft_guts.h ├── kiss_fft.c ├── kiss_fft.h ├── kissfft.hh ├── kissfft_i32.hh ├── test ├── Makefile ├── benchfftw.c ├── benchkiss.c ├── compfft.py ├── doit.c ├── fastfir.py ├── fft.py ├── mk_test.py ├── pstats.c ├── pstats.h ├── tailscrap.m ├── test_real.c ├── test_vs_dft.c ├── testcpp.cc ├── testkiss.py └── twotonetest.c └── tools ├── Makefile ├── fftutil.c ├── kfc.c ├── kfc.h ├── kiss_fastfir.c ├── kiss_fftnd.c ├── kiss_fftnd.h ├── kiss_fftndr.c ├── kiss_fftndr.h ├── kiss_fftr.c ├── kiss_fftr.h └── psdpng.c /.gitignore: -------------------------------------------------------------------------------- 1 | *.o 2 | *.swp 3 | *.so 4 | *.a 5 | *.dylib 6 | test/bm_fftw_double 7 | test/bm_fftw_float 8 | test/bm_fftw_int16_t 9 | test/bm_fftw_int32_t 10 | test/bm_fftw_simd 11 | test/bm_kiss_double 12 | test/bm_kiss_float 13 | test/bm_kiss_int16_t 14 | test/bm_kiss_int32_t 15 | test/bm_kiss_simd 16 | test/st_double 17 | test/st_float 18 | test/st_int16_t 19 | test/st_int32_t 20 | test/st_simd 21 | test/tkfc_double 22 | test/tkfc_float 23 | test/tkfc_int16_t 24 | test/tkfc_int32_t 25 | test/tkfc_simd 26 | test/tr_double 27 | test/tr_float 28 | test/tr_int16_t 29 | test/tr_int32_t 30 | test/tr_simd 31 | tools/fastconv_double 32 | tools/fastconv_float 33 | tools/fastconv_int16_t 34 | tools/fastconv_int32_t 35 | tools/fastconv_simd 36 | tools/fastconvr_double 37 | tools/fastconvr_float 38 | tools/fastconvr_int16_t 39 | tools/fastconvr_int32_t 40 | tools/fastconvr_simd 41 | tools/fft_double 42 | tools/fft_float 43 | tools/fft_int16_t 44 | tools/fft_int32_t 45 | tools/fft_simd 46 | -------------------------------------------------------------------------------- /.hgignore: -------------------------------------------------------------------------------- 1 | syntax:glob 2 | test/bm_* 3 | test/st_* 4 | test/tkfc_* 5 | test/tr_* 6 | tools/fastconv_* 7 | tools/fastconvr_* 8 | tools/fft_* 9 | *.swp 10 | *~ 11 | -------------------------------------------------------------------------------- /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 124 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | Copyright (c) 2003-2010 Mark Borgerding . All rights reserved. 2 | 3 | KISS FFT is provided under: 4 | 5 | SPDX-License-Identifier: BSD-3-Clause 6 | 7 | Being under the terms of the BSD 3-clause "New" or "Revised" License, 8 | according with: 9 | 10 | LICENSES/BSD-3-Clause 11 | 12 | -------------------------------------------------------------------------------- /LICENSES/BSD-3-Clause: -------------------------------------------------------------------------------- 1 | Valid-License-Identifier: BSD-3-Clause 2 | SPDX-URL: https://spdx.org/licenses/BSD-3-Clause.html 3 | Usage-Guide: 4 | To use the BSD 3-clause "New" or "Revised" License put the following SPDX 5 | tag/value pair into a comment according to the placement guidelines in 6 | the licensing rules documentation: 7 | SPDX-License-Identifier: BSD-3-Clause 8 | License-Text: 9 | 10 | Copyright (c) . All rights reserved. 11 | 12 | Redistribution and use in source and binary forms, with or without modification, 13 | are permitted provided that the following conditions are met: 14 | 15 | 1. Redistributions of source code must retain the above copyright notice, 16 | this list of conditions and the following disclaimer. 17 | 18 | 2. Redistributions in binary form must reproduce the above copyright notice, 19 | this list of conditions and the following disclaimer in the documentation 20 | and/or other materials provided with the distribution. 21 | 22 | 3. Neither the name of the copyright holder nor the names of its contributors 23 | may be used to endorse or promote products derived from this software without 24 | specific prior written permission. 25 | 26 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 27 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 28 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 29 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 30 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 31 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 32 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 33 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 34 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 35 | USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 36 | -------------------------------------------------------------------------------- /LICENSES/Unlicense: -------------------------------------------------------------------------------- 1 | Valid-License-Identifier: Unlicense 2 | SPDX-URL: https://spdx.org/licenses/Unlicense.html 3 | Usage-Guide: 4 | To use the Unlicense put the following SPDX tag/value pair into a 5 | comment according to the placement guidelines in the licensing rules 6 | documentation: 7 | SPDX-License-Identifier: Unlicense 8 | License-Text: 9 | 10 | This is free and unencumbered software released into the public domain. 11 | 12 | Anyone is free to copy, modify, publish, use, compile, sell, or distribute 13 | this software, either in source code form or as a compiled binary, for any 14 | purpose, commercial or non-commercial, and by any means. 15 | 16 | In jurisdictions that recognize copyright laws, the author or authors of this 17 | software dedicate any and all copyright interest in the software to the public 18 | domain. We make this dedication for the benefit of the public at large and 19 | to the detriment of our heirs and successors. We intend this dedication to be 20 | an overt act of relinquishment in perpetuity of all present and future rights 21 | to this software under copyright law. 22 | 23 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 24 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 25 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 26 | BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 27 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH 28 | THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 29 | 30 | For more information, please refer to 31 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | KFVER=130 2 | 3 | ifeq ($(shell uname -s),Darwin) 4 | SHARED := -Wl,-install_name,libkissfft.dylib -o libkissfft.dylib 5 | else 6 | SHARED := -Wl,-soname,libkissfft.so -o libkissfft.so 7 | endif 8 | 9 | all: 10 | gcc -Wall -fPIC -c *.c -Dkiss_fft_scalar=float -o kiss_fft.o 11 | ar crus libkissfft.a kiss_fft.o 12 | gcc -shared $(SHARED) kiss_fft.o 13 | 14 | install: all 15 | cp libkissfft.so /usr/local/lib/ 16 | 17 | doc: 18 | @echo "Start by reading the README file. If you want to build and test lots of stuff, do a 'make testall'" 19 | @echo "but be aware that 'make testall' has dependencies that the basic kissfft software does not." 20 | @echo "It is generally unneeded to run these tests yourself, unless you plan on changing the inner workings" 21 | @echo "of kissfft and would like to make use of its regression tests." 22 | 23 | testall: 24 | # The simd and int32_t types may or may not work on your machine 25 | make -C test DATATYPE=simd CFLAGADD="$(CFLAGADD)" test 26 | make -C test DATATYPE=int32_t CFLAGADD="$(CFLAGADD)" test 27 | make -C test DATATYPE=int16_t CFLAGADD="$(CFLAGADD)" test 28 | make -C test DATATYPE=float CFLAGADD="$(CFLAGADD)" test 29 | make -C test DATATYPE=double CFLAGADD="$(CFLAGADD)" test 30 | echo "all tests passed" 31 | 32 | tarball: clean 33 | hg archive -r v$(KFVER) -t tgz kiss_fft$(KFVER).tar.gz 34 | hg archive -r v$(KFVER) -t zip kiss_fft$(KFVER).zip 35 | 36 | clean: 37 | cd test && make clean 38 | cd tools && make clean 39 | rm -f kiss_fft*.tar.gz *~ *.pyc kiss_fft*.zip 40 | 41 | asm: kiss_fft.s 42 | 43 | kiss_fft.s: kiss_fft.c kiss_fft.h _kiss_fft_guts.h 44 | [ -e kiss_fft.s ] && mv kiss_fft.s kiss_fft.s~ || true 45 | gcc -S kiss_fft.c -O3 -mtune=native -ffast-math -fomit-frame-pointer -unroll-loops -dA -fverbose-asm 46 | gcc -o kiss_fft_short.s -S kiss_fft.c -O3 -mtune=native -ffast-math -fomit-frame-pointer -dA -fverbose-asm -DFIXED_POINT 47 | [ -e kiss_fft.s~ ] && diff kiss_fft.s~ kiss_fft.s || true 48 | -------------------------------------------------------------------------------- /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 | kiss_fft_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 135 | -------------------------------------------------------------------------------- /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 15 | 16 | #define MAXFACTORS 32 17 | /* e.g. an fft of length 128 has 4 factors 18 | as far as kissfft is concerned 19 | 4*4*4*2 20 | */ 21 | 22 | struct kiss_fft_state{ 23 | int nfft; 24 | int inverse; 25 | int factors[2*MAXFACTORS]; 26 | kiss_fft_cpx twiddles[1]; 27 | }; 28 | 29 | /* 30 | Explanation of macros dealing with complex math: 31 | 32 | C_MUL(m,a,b) : m = a*b 33 | C_FIXDIV( c , div ) : if a fixed point impl., c /= div. noop otherwise 34 | C_SUB( res, a,b) : res = a - b 35 | C_SUBFROM( res , a) : res -= a 36 | C_ADDTO( res , a) : res += a 37 | * */ 38 | #ifdef FIXED_POINT 39 | #if (FIXED_POINT==32) 40 | # define FRACBITS 31 41 | # define SAMPPROD int64_t 42 | #define SAMP_MAX 2147483647 43 | #else 44 | # define FRACBITS 15 45 | # define SAMPPROD int32_t 46 | #define SAMP_MAX 32767 47 | #endif 48 | 49 | #define SAMP_MIN -SAMP_MAX 50 | 51 | #if defined(CHECK_OVERFLOW) 52 | # define CHECK_OVERFLOW_OP(a,op,b) \ 53 | if ( (SAMPPROD)(a) op (SAMPPROD)(b) > SAMP_MAX || (SAMPPROD)(a) op (SAMPPROD)(b) < SAMP_MIN ) { \ 54 | fprintf(stderr,"WARNING:overflow @ " __FILE__ "(%d): (%d " #op" %d) = %ld\n",__LINE__,(a),(b),(SAMPPROD)(a) op (SAMPPROD)(b) ); } 55 | #endif 56 | 57 | 58 | # define smul(a,b) ( (SAMPPROD)(a)*(b) ) 59 | # define sround( x ) (kiss_fft_scalar)( ( (x) + (1<<(FRACBITS-1)) ) >> FRACBITS ) 60 | 61 | # define S_MUL(a,b) sround( smul(a,b) ) 62 | 63 | # define C_MUL(m,a,b) \ 64 | do{ (m).r = sround( smul((a).r,(b).r) - smul((a).i,(b).i) ); \ 65 | (m).i = sround( smul((a).r,(b).i) + smul((a).i,(b).r) ); }while(0) 66 | 67 | # define DIVSCALAR(x,k) \ 68 | (x) = sround( smul( x, SAMP_MAX/k ) ) 69 | 70 | # define C_FIXDIV(c,div) \ 71 | do { DIVSCALAR( (c).r , div); \ 72 | DIVSCALAR( (c).i , div); }while (0) 73 | 74 | # define C_MULBYSCALAR( c, s ) \ 75 | do{ (c).r = sround( smul( (c).r , s ) ) ;\ 76 | (c).i = sround( smul( (c).i , s ) ) ; }while(0) 77 | 78 | #else /* not FIXED_POINT*/ 79 | 80 | # define S_MUL(a,b) ( (a)*(b) ) 81 | #define C_MUL(m,a,b) \ 82 | do{ (m).r = (a).r*(b).r - (a).i*(b).i;\ 83 | (m).i = (a).r*(b).i + (a).i*(b).r; }while(0) 84 | # define C_FIXDIV(c,div) /* NOOP */ 85 | # define C_MULBYSCALAR( c, s ) \ 86 | do{ (c).r *= (s);\ 87 | (c).i *= (s); }while(0) 88 | #endif 89 | 90 | #ifndef CHECK_OVERFLOW_OP 91 | # define CHECK_OVERFLOW_OP(a,op,b) /* noop */ 92 | #endif 93 | 94 | #define C_ADD( res, a,b)\ 95 | do { \ 96 | CHECK_OVERFLOW_OP((a).r,+,(b).r)\ 97 | CHECK_OVERFLOW_OP((a).i,+,(b).i)\ 98 | (res).r=(a).r+(b).r; (res).i=(a).i+(b).i; \ 99 | }while(0) 100 | #define C_SUB( 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_ADDTO( res , a)\ 107 | do { \ 108 | CHECK_OVERFLOW_OP((res).r,+,(a).r)\ 109 | CHECK_OVERFLOW_OP((res).i,+,(a).i)\ 110 | (res).r += (a).r; (res).i += (a).i;\ 111 | }while(0) 112 | 113 | #define C_SUBFROM( res , a)\ 114 | do {\ 115 | CHECK_OVERFLOW_OP((res).r,-,(a).r)\ 116 | CHECK_OVERFLOW_OP((res).i,-,(a).i)\ 117 | (res).r -= (a).r; (res).i -= (a).i; \ 118 | }while(0) 119 | 120 | 121 | #ifdef FIXED_POINT 122 | # define KISS_FFT_COS(phase) floor(.5+SAMP_MAX * cos (phase)) 123 | # define KISS_FFT_SIN(phase) floor(.5+SAMP_MAX * sin (phase)) 124 | # define HALF_OF(x) ((x)>>1) 125 | #elif defined(USE_SIMD) 126 | # define KISS_FFT_COS(phase) _mm_set1_ps( cos(phase) ) 127 | # define KISS_FFT_SIN(phase) _mm_set1_ps( sin(phase) ) 128 | # define HALF_OF(x) ((x)*_mm_set1_ps(.5)) 129 | #else 130 | # define KISS_FFT_COS(phase) (kiss_fft_scalar) cos(phase) 131 | # define KISS_FFT_SIN(phase) (kiss_fft_scalar) sin(phase) 132 | # define HALF_OF(x) ((x)*.5) 133 | #endif 134 | 135 | #define kf_cexp(x,phase) \ 136 | do{ \ 137 | (x)->r = KISS_FFT_COS(phase);\ 138 | (x)->i = KISS_FFT_SIN(phase);\ 139 | }while(0) 140 | 141 | 142 | /* a debugging function */ 143 | #define pcpx(c)\ 144 | fprintf(stderr,"%g + %gi\n",(double)((c)->r),(double)((c)->i) ) 145 | 146 | 147 | #ifdef KISS_FFT_USE_ALLOCA 148 | // define this to allow use of alloca instead of malloc for temporary buffers 149 | // Temporary buffers are used in two case: 150 | // 1. FFT sizes that have "bad" factors. i.e. not 2,3 and 5 151 | // 2. "in-place" FFTs. Notice the quotes, since kissfft does not really do an in-place transform. 152 | #include 153 | #define KISS_FFT_TMP_ALLOC(nbytes) alloca(nbytes) 154 | #define KISS_FFT_TMP_FREE(ptr) 155 | #else 156 | #define KISS_FFT_TMP_ALLOC(nbytes) KISS_FFT_MALLOC(nbytes) 157 | #define KISS_FFT_TMP_FREE(ptr) KISS_FFT_FREE(ptr) 158 | #endif 159 | -------------------------------------------------------------------------------- /kiss_fft.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003-2010, Mark Borgerding. All rights reserved. 3 | * This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | * 5 | * SPDX-License-Identifier: BSD-3-Clause 6 | * See COPYING file for more information. 7 | */ 8 | 9 | 10 | #include "_kiss_fft_guts.h" 11 | /* The guts header contains all the multiplication and addition macros that are defined for 12 | fixed or floating point complex numbers. It also delares the kf_ internal functions. 13 | */ 14 | 15 | static void kf_bfly2( 16 | kiss_fft_cpx * Fout, 17 | const size_t fstride, 18 | const kiss_fft_cfg st, 19 | int m 20 | ) 21 | { 22 | kiss_fft_cpx * Fout2; 23 | kiss_fft_cpx * tw1 = st->twiddles; 24 | kiss_fft_cpx t; 25 | Fout2 = Fout + m; 26 | do{ 27 | C_FIXDIV(*Fout,2); C_FIXDIV(*Fout2,2); 28 | 29 | C_MUL (t, *Fout2 , *tw1); 30 | tw1 += fstride; 31 | C_SUB( *Fout2 , *Fout , t ); 32 | C_ADDTO( *Fout , t ); 33 | ++Fout2; 34 | ++Fout; 35 | }while (--m); 36 | } 37 | 38 | static void kf_bfly4( 39 | kiss_fft_cpx * Fout, 40 | const size_t fstride, 41 | const kiss_fft_cfg st, 42 | const size_t m 43 | ) 44 | { 45 | kiss_fft_cpx *tw1,*tw2,*tw3; 46 | kiss_fft_cpx scratch[6]; 47 | size_t k=m; 48 | const size_t m2=2*m; 49 | const size_t m3=3*m; 50 | 51 | 52 | tw3 = tw2 = tw1 = st->twiddles; 53 | 54 | do { 55 | C_FIXDIV(*Fout,4); C_FIXDIV(Fout[m],4); C_FIXDIV(Fout[m2],4); C_FIXDIV(Fout[m3],4); 56 | 57 | C_MUL(scratch[0],Fout[m] , *tw1 ); 58 | C_MUL(scratch[1],Fout[m2] , *tw2 ); 59 | C_MUL(scratch[2],Fout[m3] , *tw3 ); 60 | 61 | C_SUB( scratch[5] , *Fout, scratch[1] ); 62 | C_ADDTO(*Fout, scratch[1]); 63 | C_ADD( scratch[3] , scratch[0] , scratch[2] ); 64 | C_SUB( scratch[4] , scratch[0] , scratch[2] ); 65 | C_SUB( Fout[m2], *Fout, scratch[3] ); 66 | tw1 += fstride; 67 | tw2 += fstride*2; 68 | tw3 += fstride*3; 69 | C_ADDTO( *Fout , scratch[3] ); 70 | 71 | if(st->inverse) { 72 | Fout[m].r = scratch[5].r - scratch[4].i; 73 | Fout[m].i = scratch[5].i + scratch[4].r; 74 | Fout[m3].r = scratch[5].r + scratch[4].i; 75 | Fout[m3].i = scratch[5].i - scratch[4].r; 76 | }else{ 77 | Fout[m].r = scratch[5].r + scratch[4].i; 78 | Fout[m].i = scratch[5].i - scratch[4].r; 79 | Fout[m3].r = scratch[5].r - scratch[4].i; 80 | Fout[m3].i = scratch[5].i + scratch[4].r; 81 | } 82 | ++Fout; 83 | }while(--k); 84 | } 85 | 86 | static void kf_bfly3( 87 | kiss_fft_cpx * Fout, 88 | const size_t fstride, 89 | const kiss_fft_cfg st, 90 | size_t m 91 | ) 92 | { 93 | size_t k=m; 94 | const size_t m2 = 2*m; 95 | kiss_fft_cpx *tw1,*tw2; 96 | kiss_fft_cpx scratch[5]; 97 | kiss_fft_cpx epi3; 98 | epi3 = st->twiddles[fstride*m]; 99 | 100 | tw1=tw2=st->twiddles; 101 | 102 | do{ 103 | C_FIXDIV(*Fout,3); C_FIXDIV(Fout[m],3); C_FIXDIV(Fout[m2],3); 104 | 105 | C_MUL(scratch[1],Fout[m] , *tw1); 106 | C_MUL(scratch[2],Fout[m2] , *tw2); 107 | 108 | C_ADD(scratch[3],scratch[1],scratch[2]); 109 | C_SUB(scratch[0],scratch[1],scratch[2]); 110 | tw1 += fstride; 111 | tw2 += fstride*2; 112 | 113 | Fout[m].r = Fout->r - HALF_OF(scratch[3].r); 114 | Fout[m].i = Fout->i - HALF_OF(scratch[3].i); 115 | 116 | C_MULBYSCALAR( scratch[0] , epi3.i ); 117 | 118 | C_ADDTO(*Fout,scratch[3]); 119 | 120 | Fout[m2].r = Fout[m].r + scratch[0].i; 121 | Fout[m2].i = Fout[m].i - scratch[0].r; 122 | 123 | Fout[m].r -= scratch[0].i; 124 | Fout[m].i += scratch[0].r; 125 | 126 | ++Fout; 127 | }while(--k); 128 | } 129 | 130 | static void kf_bfly5( 131 | kiss_fft_cpx * Fout, 132 | const size_t fstride, 133 | const kiss_fft_cfg st, 134 | int m 135 | ) 136 | { 137 | kiss_fft_cpx *Fout0,*Fout1,*Fout2,*Fout3,*Fout4; 138 | int u; 139 | kiss_fft_cpx scratch[13]; 140 | kiss_fft_cpx * twiddles = st->twiddles; 141 | kiss_fft_cpx *tw; 142 | kiss_fft_cpx ya,yb; 143 | ya = twiddles[fstride*m]; 144 | yb = twiddles[fstride*2*m]; 145 | 146 | Fout0=Fout; 147 | Fout1=Fout0+m; 148 | Fout2=Fout0+2*m; 149 | Fout3=Fout0+3*m; 150 | Fout4=Fout0+4*m; 151 | 152 | tw=st->twiddles; 153 | for ( u=0; ur += scratch[7].r + scratch[8].r; 168 | Fout0->i += scratch[7].i + scratch[8].i; 169 | 170 | scratch[5].r = scratch[0].r + S_MUL(scratch[7].r,ya.r) + S_MUL(scratch[8].r,yb.r); 171 | scratch[5].i = scratch[0].i + S_MUL(scratch[7].i,ya.r) + S_MUL(scratch[8].i,yb.r); 172 | 173 | scratch[6].r = S_MUL(scratch[10].i,ya.i) + S_MUL(scratch[9].i,yb.i); 174 | scratch[6].i = -S_MUL(scratch[10].r,ya.i) - S_MUL(scratch[9].r,yb.i); 175 | 176 | C_SUB(*Fout1,scratch[5],scratch[6]); 177 | C_ADD(*Fout4,scratch[5],scratch[6]); 178 | 179 | scratch[11].r = scratch[0].r + S_MUL(scratch[7].r,yb.r) + S_MUL(scratch[8].r,ya.r); 180 | scratch[11].i = scratch[0].i + S_MUL(scratch[7].i,yb.r) + S_MUL(scratch[8].i,ya.r); 181 | scratch[12].r = - S_MUL(scratch[10].i,yb.i) + S_MUL(scratch[9].i,ya.i); 182 | scratch[12].i = S_MUL(scratch[10].r,yb.i) - S_MUL(scratch[9].r,ya.i); 183 | 184 | C_ADD(*Fout2,scratch[11],scratch[12]); 185 | C_SUB(*Fout3,scratch[11],scratch[12]); 186 | 187 | ++Fout0;++Fout1;++Fout2;++Fout3;++Fout4; 188 | } 189 | } 190 | 191 | /* perform the butterfly for one stage of a mixed radix FFT */ 192 | static void kf_bfly_generic( 193 | kiss_fft_cpx * Fout, 194 | const size_t fstride, 195 | const kiss_fft_cfg st, 196 | int m, 197 | int p 198 | ) 199 | { 200 | int u,k,q1,q; 201 | kiss_fft_cpx * twiddles = st->twiddles; 202 | kiss_fft_cpx t; 203 | int Norig = st->nfft; 204 | 205 | kiss_fft_cpx * scratch = (kiss_fft_cpx*)KISS_FFT_TMP_ALLOC(sizeof(kiss_fft_cpx)*p); 206 | 207 | for ( u=0; u=Norig) twidx-=Norig; 222 | C_MUL(t,scratch[q] , twiddles[twidx] ); 223 | C_ADDTO( Fout[ k ] ,t); 224 | } 225 | k += m; 226 | } 227 | } 228 | KISS_FFT_TMP_FREE(scratch); 229 | } 230 | 231 | static 232 | void kf_work( 233 | kiss_fft_cpx * Fout, 234 | const kiss_fft_cpx * f, 235 | const size_t fstride, 236 | int in_stride, 237 | int * factors, 238 | const kiss_fft_cfg st 239 | ) 240 | { 241 | kiss_fft_cpx * Fout_beg=Fout; 242 | const int p=*factors++; /* the radix */ 243 | const int m=*factors++; /* stage's fft length/p */ 244 | const kiss_fft_cpx * Fout_end = Fout + p*m; 245 | 246 | #ifdef _OPENMP 247 | // use openmp extensions at the 248 | // top-level (not recursive) 249 | if (fstride==1 && p<=5) 250 | { 251 | int k; 252 | 253 | // execute the p different work units in different threads 254 | # pragma omp parallel for 255 | for (k=0;k floor_sqrt) 318 | p = n; /* no more factors, skip to end */ 319 | } 320 | n /= p; 321 | *facbuf++ = p; 322 | *facbuf++ = n; 323 | } while (n > 1); 324 | } 325 | 326 | /* 327 | * 328 | * User-callable function to allocate all necessary storage space for the fft. 329 | * 330 | * The return value is a contiguous block of memory, allocated with malloc. As such, 331 | * It can be freed with free(), rather than a kiss_fft-specific function. 332 | * */ 333 | kiss_fft_cfg kiss_fft_alloc(int nfft,int inverse_fft,void * mem,size_t * lenmem ) 334 | { 335 | kiss_fft_cfg st=NULL; 336 | size_t memneeded = sizeof(struct kiss_fft_state) 337 | + sizeof(kiss_fft_cpx)*(nfft-1); /* twiddle factors*/ 338 | 339 | if ( lenmem==NULL ) { 340 | st = ( kiss_fft_cfg)KISS_FFT_MALLOC( memneeded ); 341 | }else{ 342 | if (mem != NULL && *lenmem >= memneeded) 343 | st = (kiss_fft_cfg)mem; 344 | *lenmem = memneeded; 345 | } 346 | if (st) { 347 | int i; 348 | st->nfft=nfft; 349 | st->inverse = inverse_fft; 350 | 351 | for (i=0;iinverse) 355 | phase *= -1; 356 | kf_cexp(st->twiddles+i, phase ); 357 | } 358 | 359 | kf_factor(nfft,st->factors); 360 | } 361 | return st; 362 | } 363 | 364 | 365 | void kiss_fft_stride(kiss_fft_cfg st,const kiss_fft_cpx *fin,kiss_fft_cpx *fout,int in_stride) 366 | { 367 | if (fin == fout) { 368 | //NOTE: this is not really an in-place FFT algorithm. 369 | //It just performs an out-of-place FFT into a temp buffer 370 | kiss_fft_cpx * tmpbuf = (kiss_fft_cpx*)KISS_FFT_TMP_ALLOC( sizeof(kiss_fft_cpx)*st->nfft); 371 | kf_work(tmpbuf,fin,1,in_stride, st->factors,st); 372 | memcpy(fout,tmpbuf,sizeof(kiss_fft_cpx)*st->nfft); 373 | KISS_FFT_TMP_FREE(tmpbuf); 374 | }else{ 375 | kf_work( fout, fin, 1,in_stride, st->factors,st ); 376 | } 377 | } 378 | 379 | void kiss_fft(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout) 380 | { 381 | kiss_fft_stride(cfg,fin,fout,1); 382 | } 383 | 384 | 385 | void kiss_fft_cleanup(void) 386 | { 387 | // nothing needed any more 388 | } 389 | 390 | int kiss_fft_next_fast_size(int n) 391 | { 392 | while(1) { 393 | int m=n; 394 | while ( (m%2) == 0 ) m/=2; 395 | while ( (m%3) == 0 ) m/=3; 396 | while ( (m%5) == 0 ) m/=5; 397 | if (m<=1) 398 | break; /* n is completely factorable by twos, threes, and fives */ 399 | n++; 400 | } 401 | return n; 402 | } 403 | -------------------------------------------------------------------------------- /kiss_fft.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003-2010, Mark Borgerding. All rights reserved. 3 | * This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | * 5 | * SPDX-License-Identifier: BSD-3-Clause 6 | * See COPYING file for more information. 7 | */ 8 | 9 | #ifndef KISS_FFT_H 10 | #define KISS_FFT_H 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | #ifdef __cplusplus 18 | extern "C" { 19 | #endif 20 | 21 | /* 22 | ATTENTION! 23 | If you would like a : 24 | -- a utility that will handle the caching of fft objects 25 | -- real-only (no imaginary time component ) FFT 26 | -- a multi-dimensional FFT 27 | -- a command-line utility to perform ffts 28 | -- a command-line utility to perform fast-convolution filtering 29 | 30 | Then see kfc.h kiss_fftr.h kiss_fftnd.h fftutil.c kiss_fastfir.c 31 | in the tools/ directory. 32 | */ 33 | 34 | #ifdef USE_SIMD 35 | # include 36 | # define kiss_fft_scalar __m128 37 | #define KISS_FFT_MALLOC(nbytes) _mm_malloc(nbytes,16) 38 | #define KISS_FFT_FREE _mm_free 39 | #else 40 | #define KISS_FFT_MALLOC malloc 41 | #define KISS_FFT_FREE free 42 | #endif 43 | 44 | 45 | #ifdef FIXED_POINT 46 | #include 47 | # if (FIXED_POINT == 32) 48 | # define kiss_fft_scalar int32_t 49 | # else 50 | # define kiss_fft_scalar int16_t 51 | # endif 52 | #else 53 | # ifndef kiss_fft_scalar 54 | /* default is float */ 55 | # define kiss_fft_scalar float 56 | # endif 57 | #endif 58 | 59 | typedef struct { 60 | kiss_fft_scalar r; 61 | kiss_fft_scalar i; 62 | }kiss_fft_cpx; 63 | 64 | typedef struct kiss_fft_state* kiss_fft_cfg; 65 | 66 | /* 67 | * kiss_fft_alloc 68 | * 69 | * Initialize a FFT (or IFFT) algorithm's cfg/state buffer. 70 | * 71 | * typical usage: kiss_fft_cfg mycfg=kiss_fft_alloc(1024,0,NULL,NULL); 72 | * 73 | * The return value from fft_alloc is a cfg buffer used internally 74 | * by the fft routine or NULL. 75 | * 76 | * If lenmem is NULL, then kiss_fft_alloc will allocate a cfg buffer using malloc. 77 | * The returned value should be free()d when done to avoid memory leaks. 78 | * 79 | * The state can be placed in a user supplied buffer 'mem': 80 | * If lenmem is not NULL and mem is not NULL and *lenmem is large enough, 81 | * then the function places the cfg in mem and the size used in *lenmem 82 | * and returns mem. 83 | * 84 | * If lenmem is not NULL and ( mem is NULL or *lenmem is not large enough), 85 | * then the function returns NULL and places the minimum cfg 86 | * buffer size in *lenmem. 87 | * */ 88 | 89 | kiss_fft_cfg kiss_fft_alloc(int nfft,int inverse_fft,void * mem,size_t * lenmem); 90 | 91 | /* 92 | * kiss_fft(cfg,in_out_buf) 93 | * 94 | * Perform an FFT on a complex input buffer. 95 | * for a forward FFT, 96 | * fin should be f[0] , f[1] , ... ,f[nfft-1] 97 | * fout will be F[0] , F[1] , ... ,F[nfft-1] 98 | * Note that each element is complex and can be accessed like 99 | f[k].r and f[k].i 100 | * */ 101 | void kiss_fft(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout); 102 | 103 | /* 104 | A more generic version of the above function. It reads its input from every Nth sample. 105 | * */ 106 | void kiss_fft_stride(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout,int fin_stride); 107 | 108 | /* If kiss_fft_alloc allocated a buffer, it is one contiguous 109 | buffer and can be simply free()d when no longer needed*/ 110 | #define kiss_fft_free KISS_FFT_FREE 111 | 112 | /* 113 | Cleans up some memory that gets managed internally. Not necessary to call, but it might clean up 114 | your compiler output to call this before you exit. 115 | */ 116 | void kiss_fft_cleanup(void); 117 | 118 | 119 | /* 120 | * Returns the smallest integer k, such that k>=n and k has only "fast" factors (2,3,5) 121 | */ 122 | int kiss_fft_next_fast_size(int n); 123 | 124 | /* for real ffts, we need an even size */ 125 | #define kiss_fftr_next_fast_size_real(n) \ 126 | (kiss_fft_next_fast_size( ((n)+1)>>1)<<1) 127 | 128 | #ifdef __cplusplus 129 | } 130 | #endif 131 | 132 | #endif 133 | -------------------------------------------------------------------------------- /kissfft.hh: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003-2010, Mark Borgerding. All rights reserved. 3 | * This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | * 5 | * SPDX-License-Identifier: BSD-3-Clause 6 | * See COPYING file for more information. 7 | */ 8 | 9 | #ifndef KISSFFT_CLASS_HH 10 | #define KISSFFT_CLASS_HH 11 | #include 12 | #include 13 | #include 14 | 15 | 16 | template 17 | class kissfft 18 | { 19 | public: 20 | 21 | using cpx_t = std::complex; 22 | 23 | kissfft( const std::size_t nfft, 24 | const bool inverse ) 25 | :_nfft(nfft) 26 | ,_inverse(inverse) 27 | { 28 | // fill twiddle factors 29 | _twiddles.resize(_nfft); 30 | const scalar_t phinc = (_inverse?2:-2)* acos( (scalar_t) -1) / _nfft; 31 | for (std::size_t i=0;i<_nfft;++i) 32 | _twiddles[i] = exp( cpx_t(0,i*phinc) ); 33 | 34 | //factorize 35 | //start factoring out 4's, then 2's, then 3,5,7,9,... 36 | std::size_t n= _nfft; 37 | std::size_t p=4; 38 | do { 39 | while (n % p) { 40 | switch (p) { 41 | case 4: p = 2; break; 42 | case 2: p = 3; break; 43 | default: p += 2; break; 44 | } 45 | if (p*p>n) 46 | p = n;// no more factors 47 | } 48 | n /= p; 49 | _stageRadix.push_back(p); 50 | _stageRemainder.push_back(n); 51 | }while(n>1); 52 | } 53 | 54 | 55 | /// Changes the FFT-length and/or the transform direction. 56 | /// 57 | /// @post The @c kissfft object will be in the same state as if it 58 | /// had been newly constructed with the passed arguments. 59 | /// However, the implementation may be faster than constructing a 60 | /// new fft object. 61 | void assign( const std::size_t nfft, 62 | const bool inverse ) 63 | { 64 | if ( nfft != _nfft ) 65 | { 66 | kissfft tmp( nfft, inverse ); // O(n) time. 67 | std::swap( tmp, *this ); // this is O(1) in C++11, O(n) otherwise. 68 | } 69 | else if ( inverse != _inverse ) 70 | { 71 | // conjugate the twiddle factors. 72 | for ( typename std::vector::iterator it = _twiddles.begin(); 73 | it != _twiddles.end(); ++it ) 74 | it->imag( -it->imag() ); 75 | } 76 | } 77 | 78 | /// Calculates the complex Discrete Fourier Transform. 79 | /// 80 | /// The size of the passed arrays must be passed in the constructor. 81 | /// The sum of the squares of the absolute values in the @c dst 82 | /// array will be @c N times the sum of the squares of the absolute 83 | /// values in the @c src array, where @c N is the size of the array. 84 | /// In other words, the l_2 norm of the resulting array will be 85 | /// @c sqrt(N) times as big as the l_2 norm of the input array. 86 | /// This is also the case when the inverse flag is set in the 87 | /// constructor. Hence when applying the same transform twice, but with 88 | /// the inverse flag changed the second time, then the result will 89 | /// be equal to the original input times @c N. 90 | void transform(const cpx_t * fft_in, cpx_t * fft_out, const std::size_t stage = 0, const std::size_t fstride = 1, const std::size_t in_stride = 1) const 91 | { 92 | const std::size_t p = _stageRadix[stage]; 93 | const std::size_t m = _stageRemainder[stage]; 94 | cpx_t * const Fout_beg = fft_out; 95 | cpx_t * const Fout_end = fft_out + p*m; 96 | 97 | if (m==1) { 98 | do{ 99 | *fft_out = *fft_in; 100 | fft_in += fstride*in_stride; 101 | }while(++fft_out != Fout_end ); 102 | }else{ 103 | do{ 104 | // recursive call: 105 | // DFT of size m*p performed by doing 106 | // p instances of smaller DFTs of size m, 107 | // each one takes a decimated version of the input 108 | transform(fft_in, fft_out, stage+1, fstride*p,in_stride); 109 | fft_in += fstride*in_stride; 110 | }while( (fft_out += m) != Fout_end ); 111 | } 112 | 113 | fft_out=Fout_beg; 114 | 115 | // recombine the p smaller DFTs 116 | switch (p) { 117 | case 2: kf_bfly2(fft_out,fstride,m); break; 118 | case 3: kf_bfly3(fft_out,fstride,m); break; 119 | case 4: kf_bfly4(fft_out,fstride,m); break; 120 | case 5: kf_bfly5(fft_out,fstride,m); break; 121 | default: kf_bfly_generic(fft_out,fstride,m,p); break; 122 | } 123 | } 124 | 125 | /// Calculates the Discrete Fourier Transform (DFT) of a real input 126 | /// of size @c 2*N. 127 | /// 128 | /// The 0-th and N-th value of the DFT are real numbers. These are 129 | /// stored in @c dst[0].real() and @c dst[1].imag() respectively. 130 | /// The remaining DFT values up to the index N-1 are stored in 131 | /// @c dst[1] to @c dst[N-1]. 132 | /// The other half of the DFT values can be calculated from the 133 | /// symmetry relation 134 | /// @code 135 | /// DFT(src)[2*N-k] == conj( DFT(src)[k] ); 136 | /// @endcode 137 | /// The same scaling factors as in @c transform() apply. 138 | /// 139 | /// @note For this to work, the types @c scalar_t and @c cpx_t 140 | /// must fulfill the following requirements: 141 | /// 142 | /// For any object @c z of type @c cpx_t, 143 | /// @c reinterpret_cast(z)[0] is the real part of @c z and 144 | /// @c reinterpret_cast(z)[1] is the imaginary part of @c z. 145 | /// For any pointer to an element of an array of @c cpx_t named @c p 146 | /// and any valid array index @c i, @c reinterpret_cast(p)[2*i] 147 | /// is the real part of the complex number @c p[i], and 148 | /// @c reinterpret_cast(p)[2*i+1] is the imaginary part of the 149 | /// complex number @c p[i]. 150 | /// 151 | /// Since C++11, these requirements are guaranteed to be satisfied for 152 | /// @c scalar_ts being @c float, @c double or @c long @c double 153 | /// together with @c cpx_t being @c std::complex. 154 | void transform_real( const scalar_t * const src, 155 | cpx_t * const dst ) const 156 | { 157 | const std::size_t N = _nfft; 158 | if ( N == 0 ) 159 | return; 160 | 161 | // perform complex FFT 162 | transform( reinterpret_cast(src), dst ); 163 | 164 | // post processing for k = 0 and k = N 165 | dst[0] = cpx_t( dst[0].real() + dst[0].imag(), 166 | dst[0].real() - dst[0].imag() ); 167 | 168 | // post processing for all the other k = 1, 2, ..., N-1 169 | const scalar_t pi = acos( (scalar_t) -1); 170 | const scalar_t half_phi_inc = ( _inverse ? pi : -pi ) / N; 171 | const cpx_t twiddle_mul = exp( cpx_t(0, half_phi_inc) ); 172 | for ( std::size_t k = 1; 2*k < N; ++k ) 173 | { 174 | const cpx_t w = (scalar_t)0.5 * cpx_t( 175 | dst[k].real() + dst[N-k].real(), 176 | dst[k].imag() - dst[N-k].imag() ); 177 | const cpx_t z = (scalar_t)0.5 * cpx_t( 178 | dst[k].imag() + dst[N-k].imag(), 179 | -dst[k].real() + dst[N-k].real() ); 180 | const cpx_t twiddle = 181 | k % 2 == 0 ? 182 | _twiddles[k/2] : 183 | _twiddles[k/2] * twiddle_mul; 184 | dst[ k] = w + twiddle * z; 185 | dst[N-k] = conj( w - twiddle * z ); 186 | } 187 | if ( N % 2 == 0 ) 188 | dst[N/2] = conj( dst[N/2] ); 189 | } 190 | 191 | private: 192 | 193 | void kf_bfly2( cpx_t * Fout, const size_t fstride, const std::size_t m) const 194 | { 195 | for (std::size_t k=0;k=_nfft) 345 | twidx-=_nfft; 346 | Fout[ k ] += scratchbuf[q] * twiddles[twidx]; 347 | } 348 | k += m; 349 | } 350 | } 351 | } 352 | 353 | std::size_t _nfft; 354 | bool _inverse; 355 | std::vector _twiddles; 356 | std::vector _stageRadix; 357 | std::vector _stageRemainder; 358 | }; 359 | #endif 360 | -------------------------------------------------------------------------------- /kissfft_i32.hh: -------------------------------------------------------------------------------- 1 | #ifndef KISSFFT_I32_CLASS_HH 2 | #define KISSFFT_I32_CLASS_HH 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | // TODO1: substitute complex (behaviour not defined for nonfloats), should be faster 9 | // TODO2: use std:: namespace 10 | // TODO3: make unittests for all ffts (c, cpp, i32) 11 | 12 | template 13 | struct complex_s 14 | { 15 | DType real; 16 | DType imag; 17 | }; 18 | 19 | class kissfft_i32 20 | { 21 | private: 22 | 23 | using scalar_type = int32_t; 24 | using cpx_type = complex; 25 | 26 | scalar_type _scale_factor; 27 | std::size_t _nfft; 28 | bool _inverse; 29 | std::vector _twiddles; 30 | std::vector _stageRadix; 31 | std::vector _stageRemainder; 32 | 33 | public: 34 | 35 | // scale_factor: upscale twiddle-factors otherwise they lie between 0..1 (out of range for integer) --> fixed point math 36 | kissfft_i32(const std::size_t nfft, const bool inverse, const double scale_factor = 1024.0) 37 | : _scale_factor(scalar_type(scale_factor)), _nfft(nfft), _inverse(inverse) 38 | { 39 | // fill twiddle factors 40 | _twiddles.resize(_nfft); 41 | const double phinc = (_inverse ? 2 : -2) * acos(-1.0) / _nfft; 42 | for (std::size_t i = 0; i < _nfft; ++i) 43 | { 44 | _twiddles[i] = scale_factor * exp(complex(0, i * phinc)); 45 | } 46 | //factorize 47 | //start factoring out 4's, then 2's, then 3,5,7,9,... 48 | std::size_t n = _nfft; 49 | std::size_t p = 4; 50 | do 51 | { 52 | while (n % p) 53 | { 54 | switch (p) 55 | { 56 | case 4: 57 | p = 2; 58 | break; 59 | case 2: 60 | p = 3; 61 | break; 62 | default: 63 | p += 2; 64 | break; 65 | } 66 | if (p * p > n) p = n;// no more factors 67 | } 68 | n /= p; 69 | _stageRadix.push_back(p); 70 | _stageRemainder.push_back(n); 71 | } while (n > 1); 72 | } 73 | 74 | /// Calculates the complex Discrete Fourier Transform. 75 | /// 76 | /// The size of the passed arrays must be passed in the constructor. 77 | /// The sum of the squares of the absolute values in the @c dst 78 | /// array will be @c N times the sum of the squares of the absolute 79 | /// values in the @c src array, where @c N is the size of the array. 80 | /// In other words, the l_2 norm of the resulting array will be 81 | /// @c sqrt(N) times as big as the l_2 norm of the input array. 82 | /// This is also the case when the inverse flag is set in the 83 | /// constructor. Hence when applying the same transform twice, but with 84 | /// the inverse flag changed the second time, then the result will 85 | /// be equal to the original input times @c N. 86 | void transform(const cpx_type * FSrc, 87 | cpx_type * FDst, 88 | const std::size_t stage = 0, 89 | const std::size_t fstride = 1, 90 | const std::size_t in_stride = 1) const 91 | { 92 | const std::size_t p = _stageRadix[stage]; 93 | const std::size_t m = _stageRemainder[stage]; 94 | cpx_type *const Fout_beg = FDst; 95 | cpx_type *const Fout_end = FDst + p * m; 96 | 97 | if (m == 1) 98 | { 99 | do 100 | { 101 | *FDst = *FSrc; 102 | FSrc += fstride * in_stride; 103 | } while (++FDst != Fout_end); 104 | } 105 | else 106 | { 107 | do 108 | { 109 | // recursive call: 110 | // DFT of size m*p performed by doing 111 | // p instances of smaller DFTs of size m, 112 | // each one takes a decimated version of the input 113 | transform(FSrc, FDst, stage + 1, fstride * p, in_stride); 114 | FSrc += fstride * in_stride; 115 | } while ((FDst += m) != Fout_end); 116 | } 117 | 118 | FDst = Fout_beg; 119 | 120 | // recombine the p smaller DFTs 121 | switch (p) 122 | { 123 | case 2: 124 | kf_bfly2(FDst, fstride, m); 125 | break; 126 | case 3: 127 | kf_bfly3(FDst, fstride, m); 128 | break; 129 | case 4: 130 | kf_bfly4(FDst, fstride, m); 131 | break; 132 | case 5: 133 | kf_bfly5(FDst, fstride, m); 134 | break; 135 | default: 136 | kf_bfly_generic(FDst, fstride, m, p); 137 | break; 138 | } 139 | } 140 | 141 | private: 142 | 143 | void kf_bfly2(cpx_type *const Fout, const size_t fstride, const std::size_t m) const 144 | { 145 | for (std::size_t k = 0; k < m; ++k) 146 | { 147 | const cpx_type t = (Fout[m + k] * _twiddles[k * fstride]) / _scale_factor; 148 | Fout[m + k] = Fout[k] - t; 149 | Fout[k] += t; 150 | } 151 | } 152 | 153 | void kf_bfly3(cpx_type *Fout, const std::size_t fstride, const std::size_t m) const 154 | { 155 | std::size_t k = m; 156 | const std::size_t m2 = 2 * m; 157 | const cpx_type *tw1, *tw2; 158 | cpx_type scratch[5]; 159 | const cpx_type epi3 = _twiddles[fstride * m]; 160 | 161 | tw1 = tw2 = &_twiddles[0]; 162 | 163 | do 164 | { 165 | scratch[1] = (Fout[m] * *tw1) / _scale_factor; 166 | scratch[2] = (Fout[m2] * *tw2) / _scale_factor; 167 | 168 | scratch[3] = scratch[1] + scratch[2]; 169 | scratch[0] = scratch[1] - scratch[2]; 170 | tw1 += fstride; 171 | tw2 += fstride * 2; 172 | 173 | Fout[m] = Fout[0] - (scratch[3] / 2); 174 | scratch[0] *= epi3.imag(); 175 | scratch[0] /= _scale_factor; 176 | 177 | Fout[0] += scratch[3]; 178 | 179 | Fout[m2] = cpx_type(Fout[m].real() + scratch[0].imag(), Fout[m].imag() - scratch[0].real()); 180 | 181 | Fout[m] += cpx_type(-scratch[0].imag(), scratch[0].real()); 182 | ++Fout; 183 | } while (--k); 184 | } 185 | 186 | void kf_bfly4(cpx_type *const Fout, const std::size_t fstride, const std::size_t m) const 187 | { 188 | cpx_type scratch[7]; 189 | const scalar_type negative_if_inverse = _inverse ? -1 : +1; 190 | 191 | for (std::size_t k = 0; k < m; ++k) 192 | { 193 | scratch[0] = (Fout[k + m] * _twiddles[k * fstride]) / _scale_factor; 194 | scratch[1] = (Fout[k + 2 * m] * _twiddles[k * fstride * 2]) / _scale_factor; 195 | scratch[2] = (Fout[k + 3 * m] * _twiddles[k * fstride * 3]) / _scale_factor; 196 | scratch[5] = Fout[k] - scratch[1]; 197 | 198 | Fout[k] += scratch[1]; 199 | scratch[3] = scratch[0] + scratch[2]; 200 | scratch[4] = scratch[0] - scratch[2]; 201 | scratch[4] = cpx_type(scratch[4].imag() * negative_if_inverse, 202 | -scratch[4].real() * negative_if_inverse); 203 | 204 | Fout[k + 2 * m] = Fout[k] - scratch[3]; 205 | Fout[k] += scratch[3]; 206 | Fout[k + m] = scratch[5] + scratch[4]; 207 | Fout[k + 3 * m] = scratch[5] - scratch[4]; 208 | } 209 | } 210 | 211 | void kf_bfly5(cpx_type *const Fout, const std::size_t fstride, const std::size_t m) const 212 | { 213 | cpx_type *Fout0, *Fout1, *Fout2, *Fout3, *Fout4; 214 | cpx_type scratch[13]; 215 | const cpx_type ya = _twiddles[fstride * m]; 216 | const cpx_type yb = _twiddles[fstride * 2 * m]; 217 | 218 | Fout0 = Fout; 219 | Fout1 = Fout0 + m; 220 | Fout2 = Fout0 + 2 * m; 221 | Fout3 = Fout0 + 3 * m; 222 | Fout4 = Fout0 + 4 * m; 223 | 224 | for (std::size_t u = 0; u < m; ++u) 225 | { 226 | scratch[0] = *Fout0; 227 | 228 | scratch[1] = (*Fout1 * _twiddles[u * fstride]) / _scale_factor; 229 | scratch[2] = (*Fout2 * _twiddles[2 * u * fstride]) / _scale_factor; 230 | scratch[3] = (*Fout3 * _twiddles[3 * u * fstride]) / _scale_factor; 231 | scratch[4] = (*Fout4 * _twiddles[4 * u * fstride]) / _scale_factor; 232 | 233 | scratch[7] = scratch[1] + scratch[4]; 234 | scratch[10] = scratch[1] - scratch[4]; 235 | scratch[8] = scratch[2] + scratch[3]; 236 | scratch[9] = scratch[2] - scratch[3]; 237 | 238 | *Fout0 += scratch[7]; 239 | *Fout0 += scratch[8]; 240 | 241 | scratch[5] = scratch[0] + (cpx_type( 242 | scratch[7].real() * ya.real() + scratch[8].real() * yb.real(), 243 | scratch[7].imag() * ya.real() + scratch[8].imag() * yb.real() ) / _scale_factor); 244 | 245 | scratch[6] = cpx_type( 246 | scratch[10].imag() * ya.imag() + scratch[9].imag() * yb.imag(), 247 | -scratch[10].real() * ya.imag() - scratch[9].real() * yb.imag() ) / _scale_factor; 248 | 249 | *Fout1 = scratch[5] - scratch[6]; 250 | *Fout4 = scratch[5] + scratch[6]; 251 | 252 | scratch[11] = scratch[0] + (cpx_type( 253 | scratch[7].real() * yb.real() + scratch[8].real() * ya.real(), 254 | scratch[7].imag() * yb.real() + scratch[8].imag() * ya.real() ) / _scale_factor); 255 | 256 | scratch[12] = cpx_type( 257 | -scratch[10].imag() * yb.imag() + scratch[9].imag() * ya.imag(), 258 | scratch[10].real() * yb.imag() - scratch[9].real() * ya.imag() ) / _scale_factor; 259 | 260 | *Fout2 = scratch[11] + scratch[12]; 261 | *Fout3 = scratch[11] - scratch[12]; 262 | 263 | ++Fout0; 264 | ++Fout1; 265 | ++Fout2; 266 | ++Fout3; 267 | ++Fout4; 268 | } 269 | } 270 | 271 | /* perform the butterfly for one stage of a mixed radix FFT */ 272 | void kf_bfly_generic(cpx_type * const Fout, const size_t fstride, const std::size_t m, const std::size_t p) const 273 | { 274 | const cpx_type *twiddles = &_twiddles[0]; 275 | cpx_type scratchbuf[p]; 276 | 277 | for (std::size_t u = 0; u < m; ++u) 278 | { 279 | std::size_t k = u; 280 | for (std::size_t q1 = 0; q1 < p; ++q1) 281 | { 282 | scratchbuf[q1] = Fout[k]; 283 | k += m; 284 | } 285 | 286 | k = u; 287 | for (std::size_t q1 = 0; q1 < p; ++q1) 288 | { 289 | std::size_t twidx = 0; 290 | Fout[k] = scratchbuf[0]; 291 | for (std::size_t q = 1; q < p; ++q) 292 | { 293 | twidx += fstride * k; 294 | if (twidx >= _nfft) 295 | twidx -= _nfft; 296 | Fout[k] += (scratchbuf[q] * twiddles[twidx]) / _scale_factor; 297 | } 298 | k += m; 299 | } 300 | } 301 | } 302 | }; 303 | 304 | #endif 305 | -------------------------------------------------------------------------------- /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 109 | -------------------------------------------------------------------------------- /test/benchfftw.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003-2010, Mark Borgerding. All rights reserved. 3 | * This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | * 5 | * SPDX-License-Identifier: BSD-3-Clause 6 | * See COPYING file for more information. 7 | */ 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "pstats.h" 13 | 14 | #ifdef DATATYPEdouble 15 | 16 | #define CPXTYPE fftw_complex 17 | #define PLAN fftw_plan 18 | #define FFTMALLOC fftw_malloc 19 | #define MAKEPLAN fftw_plan_dft_1d 20 | #define DOFFT fftw_execute 21 | #define DESTROYPLAN fftw_destroy_plan 22 | #define FFTFREE fftw_free 23 | 24 | #elif defined(DATATYPEfloat) 25 | 26 | #define CPXTYPE fftwf_complex 27 | #define PLAN fftwf_plan 28 | #define FFTMALLOC fftwf_malloc 29 | #define MAKEPLAN fftwf_plan_dft_1d 30 | #define DOFFT fftwf_execute 31 | #define DESTROYPLAN fftwf_destroy_plan 32 | #define FFTFREE fftwf_free 33 | 34 | #endif 35 | 36 | #ifndef CPXTYPE 37 | int main(void) 38 | { 39 | fprintf(stderr,"Datatype not available in FFTW\n" ); 40 | return 0; 41 | } 42 | #else 43 | int main(int argc,char ** argv) 44 | { 45 | int nfft=1024; 46 | int isinverse=0; 47 | int numffts=1000,i; 48 | 49 | CPXTYPE * in=NULL; 50 | CPXTYPE * out=NULL; 51 | PLAN p; 52 | 53 | pstats_init(); 54 | 55 | while (1) { 56 | int c = getopt (argc, argv, "n:ix:h"); 57 | if (c == -1) 58 | break; 59 | switch (c) { 60 | case 'n': 61 | nfft = atoi (optarg); 62 | break; 63 | case 'x': 64 | numffts = atoi (optarg); 65 | break; 66 | case 'i': 67 | isinverse = 1; 68 | break; 69 | case 'h': 70 | case '?': 71 | default: 72 | fprintf(stderr,"options:\n-n N: complex fft length\n-i: inverse\n-x N: number of ffts to compute\n" 73 | ""); 74 | } 75 | } 76 | 77 | in=FFTMALLOC(sizeof(CPXTYPE) * nfft); 78 | out=FFTMALLOC(sizeof(CPXTYPE) * nfft); 79 | for (i=0;i 9 | #include 10 | #include 11 | #include 12 | #include "kiss_fft.h" 13 | #include "kiss_fftr.h" 14 | #include "kiss_fftnd.h" 15 | #include "kiss_fftndr.h" 16 | 17 | #include "pstats.h" 18 | 19 | static 20 | int getdims(int * dims, char * arg) 21 | { 22 | char *s; 23 | int ndims=0; 24 | while ( (s=strtok( arg , ",") ) ) { 25 | dims[ndims++] = atoi(s); 26 | //printf("%s=%d\n",s,dims[ndims-1]); 27 | arg=NULL; 28 | } 29 | return ndims; 30 | } 31 | 32 | int main(int argc,char ** argv) 33 | { 34 | int k; 35 | int nfft[32]; 36 | int ndims = 1; 37 | int isinverse=0; 38 | int numffts=1000,i; 39 | kiss_fft_cpx * buf; 40 | kiss_fft_cpx * bufout; 41 | int real = 0; 42 | 43 | nfft[0] = 1024;// default 44 | 45 | while (1) { 46 | int c = getopt (argc, argv, "n:ix:r"); 47 | if (c == -1) 48 | break; 49 | switch (c) { 50 | case 'r': 51 | real = 1; 52 | break; 53 | case 'n': 54 | ndims = getdims(nfft, optarg ); 55 | if (nfft[0] != kiss_fft_next_fast_size(nfft[0]) ) { 56 | int ng = kiss_fft_next_fast_size(nfft[0]); 57 | fprintf(stderr,"warning: %d might be a better choice for speed than %d\n",ng,nfft[0]); 58 | } 59 | break; 60 | case 'x': 61 | numffts = atoi (optarg); 62 | break; 63 | case 'i': 64 | isinverse = 1; 65 | break; 66 | } 67 | } 68 | int nbytes = sizeof(kiss_fft_cpx); 69 | for (k=0;k 12 | 13 | #include "kiss_fft.h" 14 | #include "kiss_fftnd.h" 15 | #include "kiss_fftr.h" 16 | 17 | BEGIN_BENCH_DOC 18 | BENCH_DOC("name", "kissfft") 19 | BENCH_DOC("version", "1.0.1") 20 | BENCH_DOC("year", "2004") 21 | BENCH_DOC("author", "Mark Borgerding") 22 | BENCH_DOC("language", "C") 23 | BENCH_DOC("url", "http://sourceforge.net/projects/kissfft/") 24 | BENCH_DOC("copyright", 25 | "Copyright (c) 2003,4 Mark Borgerding\n" 26 | "\n" 27 | "All rights reserved.\n" 28 | "\n" 29 | "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n" 30 | "\n" 31 | " * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n" 32 | " * 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" 33 | " * 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" 34 | "\n" 35 | "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") 36 | END_BENCH_DOC 37 | 38 | int can_do(struct problem *p) 39 | { 40 | if (p->rank == 1) { 41 | if (p->kind == PROBLEM_REAL) { 42 | return (p->n[0] & 1) == 0; /* only even real is okay */ 43 | } else { 44 | return 1; 45 | } 46 | } else { 47 | return p->kind == PROBLEM_COMPLEX; 48 | } 49 | } 50 | 51 | static kiss_fft_cfg cfg=NULL; 52 | static kiss_fftr_cfg cfgr=NULL; 53 | static kiss_fftnd_cfg cfgnd=NULL; 54 | 55 | #define FAILIF( c ) \ 56 | if ( c ) do {\ 57 | fprintf(stderr,\ 58 | "kissfft: " #c " (file=%s:%d errno=%d %s)\n",\ 59 | __FILE__,__LINE__ , errno,strerror( errno ) ) ;\ 60 | exit(1);\ 61 | }while(0) 62 | 63 | 64 | 65 | void setup(struct problem *p) 66 | { 67 | size_t i; 68 | 69 | /* 70 | fprintf(stderr,"%s %s %d-d ", 71 | (p->sign == 1)?"Inverse":"Forward", 72 | p->kind == PROBLEM_COMPLEX?"Complex":"Real", 73 | p->rank); 74 | */ 75 | if (p->rank == 1) { 76 | if (p->kind == PROBLEM_COMPLEX) { 77 | cfg = kiss_fft_alloc (p->n[0], (p->sign == 1), 0, 0); 78 | FAILIF(cfg==NULL); 79 | }else{ 80 | cfgr = kiss_fftr_alloc (p->n[0], (p->sign == 1), 0, 0); 81 | FAILIF(cfgr==NULL); 82 | } 83 | }else{ 84 | int dims[5]; 85 | for (i=0;irank;++i){ 86 | dims[i] = p->n[i]; 87 | } 88 | /* multi-dimensional */ 89 | if (p->kind == PROBLEM_COMPLEX) { 90 | cfgnd = kiss_fftnd_alloc( dims , p->rank, (p->sign == 1), 0, 0 ); 91 | FAILIF(cfgnd==NULL); 92 | } 93 | } 94 | } 95 | 96 | void doit(int iter, struct problem *p) 97 | { 98 | int i; 99 | void *in = p->in; 100 | void *out = p->out; 101 | 102 | if (p->in_place) 103 | out = p->in; 104 | 105 | if (p->rank == 1) { 106 | if (p->kind == PROBLEM_COMPLEX){ 107 | for (i = 0; i < iter; ++i) 108 | kiss_fft (cfg, in, out); 109 | } else { 110 | /* PROBLEM_REAL */ 111 | if (p->sign == -1) /* FORWARD */ 112 | for (i = 0; i < iter; ++i) 113 | kiss_fftr (cfgr, in, out); 114 | else 115 | for (i = 0; i < iter; ++i) 116 | kiss_fftri (cfgr, in, out); 117 | } 118 | }else{ 119 | /* multi-dimensional */ 120 | for (i = 0; i < iter; ++i) 121 | kiss_fftnd(cfgnd,in,out); 122 | } 123 | } 124 | 125 | void done(struct problem *p) 126 | { 127 | free(cfg); 128 | cfg=NULL; 129 | free(cfgr); 130 | cfgr=NULL; 131 | free(cfgnd); 132 | cfgnd=NULL; 133 | UNUSED(p); 134 | } 135 | -------------------------------------------------------------------------------- /test/fastfir.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright (c) 2003-2010, Mark Borgerding. All rights reserved. 3 | # This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | # 5 | # SPDX-License-Identifier: BSD-3-Clause 6 | # See COPYING file for more information. 7 | 8 | from Numeric import * 9 | from FFT import * 10 | 11 | def make_random(len): 12 | import random 13 | res=[] 14 | for i in range(int(len)): 15 | r=random.uniform(-1,1) 16 | i=random.uniform(-1,1) 17 | res.append( complex(r,i) ) 18 | return res 19 | 20 | def slowfilter(sig,h): 21 | translen = len(h)-1 22 | return convolve(sig,h)[translen:-translen] 23 | 24 | def nextpow2(x): 25 | return 2 ** math.ceil(math.log(x)/math.log(2)) 26 | 27 | def fastfilter(sig,h,nfft=None): 28 | if nfft is None: 29 | nfft = int( nextpow2( 2*len(h) ) ) 30 | H = fft( h , nfft ) 31 | scraplen = len(h)-1 32 | keeplen = nfft-scraplen 33 | res=[] 34 | isdone = 0 35 | lastidx = nfft 36 | idx0 = 0 37 | while not isdone: 38 | idx1 = idx0 + nfft 39 | if idx1 >= len(sig): 40 | idx1 = len(sig) 41 | lastidx = idx1-idx0 42 | if lastidx <= scraplen: 43 | break 44 | isdone = 1 45 | Fss = fft(sig[idx0:idx1],nfft) 46 | fm = Fss * H 47 | m = inverse_fft(fm) 48 | res.append( m[scraplen:lastidx] ) 49 | idx0 += keeplen 50 | return concatenate( res ) 51 | 52 | def main(): 53 | import sys 54 | from getopt import getopt 55 | opts,args = getopt(sys.argv[1:],'rn:l:') 56 | opts=dict(opts) 57 | 58 | siglen = int(opts.get('-l',1e4 ) ) 59 | hlen =50 60 | 61 | nfft = int(opts.get('-n',128) ) 62 | usereal = opts.has_key('-r') 63 | 64 | print 'nfft=%d'%nfft 65 | # make a signal 66 | sig = make_random( siglen ) 67 | # make an impulse response 68 | h = make_random( hlen ) 69 | #h=[1]*2+[0]*3 70 | if usereal: 71 | sig=[c.real for c in sig] 72 | h=[c.real for c in h] 73 | 74 | # perform MAC filtering 75 | yslow = slowfilter(sig,h) 76 | #print '',yslow,'' 77 | #yfast = fastfilter(sig,h,nfft) 78 | yfast = utilfastfilter(sig,h,nfft,usereal) 79 | #print yfast 80 | print 'len(yslow)=%d'%len(yslow) 81 | print 'len(yfast)=%d'%len(yfast) 82 | diff = yslow-yfast 83 | snr = 10*log10( abs( vdot(yslow,yslow) / vdot(diff,diff) ) ) 84 | print 'snr=%s' % snr 85 | if snr < 10.0: 86 | print 'h=',h 87 | print 'sig=',sig[:5],'...' 88 | print 'yslow=',yslow[:5],'...' 89 | print 'yfast=',yfast[:5],'...' 90 | 91 | def utilfastfilter(sig,h,nfft,usereal): 92 | import compfft 93 | import os 94 | open( 'sig.dat','w').write( compfft.dopack(sig,'f',not usereal) ) 95 | open( 'h.dat','w').write( compfft.dopack(h,'f',not usereal) ) 96 | if usereal: 97 | util = './fastconvr' 98 | else: 99 | util = './fastconv' 100 | cmd = 'time %s -n %d -i sig.dat -h h.dat -o out.dat' % (util, nfft) 101 | print cmd 102 | ec = os.system(cmd) 103 | print 'exited->',ec 104 | return compfft.dounpack(open('out.dat').read(),'f',not usereal) 105 | 106 | if __name__ == "__main__": 107 | main() 108 | -------------------------------------------------------------------------------- /test/fft.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright (c) 2003-2010, Mark Borgerding. All rights reserved. 3 | # This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | # 5 | # SPDX-License-Identifier: BSD-3-Clause 6 | # See COPYING file for more information. 7 | 8 | import math 9 | import sys 10 | import random 11 | 12 | pi=math.pi 13 | e=math.e 14 | j=complex(0,1) 15 | 16 | def fft(f,inv): 17 | n=len(f) 18 | if n==1: 19 | return f 20 | 21 | for p in 2,3,5: 22 | if n%p==0: 23 | break 24 | else: 25 | raise Exception('%s not factorable ' % n) 26 | 27 | m = n/p 28 | Fout=[] 29 | for q in range(p): # 0,1 30 | fp = f[q::p] # every p'th time sample 31 | Fp = fft( fp ,inv) 32 | Fout.extend( Fp ) 33 | 34 | for u in range(m): 35 | scratch = Fout[u::m] # u to end in strides of m 36 | for q1 in range(p): 37 | k = q1*m + u # indices to Fout above that became scratch 38 | Fout[ k ] = scratch[0] # cuz e**0==1 in loop below 39 | for q in range(1,p): 40 | if inv: 41 | t = e ** ( j*2*pi*k*q/n ) 42 | else: 43 | t = e ** ( -j*2*pi*k*q/n ) 44 | Fout[ k ] += scratch[q] * t 45 | 46 | return Fout 47 | 48 | def rifft(F): 49 | N = len(F) - 1 50 | Z = [0] * (N) 51 | for k in range(N): 52 | Fek = ( F[k] + F[-k-1].conjugate() ) 53 | Fok = ( F[k] - F[-k-1].conjugate() ) * e ** (j*pi*k/N) 54 | Z[k] = Fek + j*Fok 55 | 56 | fp = fft(Z , 1) 57 | 58 | f = [] 59 | for c in fp: 60 | f.append(c.real) 61 | f.append(c.imag) 62 | return f 63 | 64 | def real_fft( f,inv ): 65 | if inv: 66 | return rifft(f) 67 | 68 | N = len(f) / 2 69 | 70 | res = f[::2] 71 | ims = f[1::2] 72 | 73 | fp = [ complex(r,i) for r,i in zip(res,ims) ] 74 | print 'fft input ', fp 75 | Fp = fft( fp ,0 ) 76 | print 'fft output ', Fp 77 | 78 | F = [ complex(0,0) ] * ( N+1 ) 79 | 80 | F[0] = complex( Fp[0].real + Fp[0].imag , 0 ) 81 | 82 | for k in range(1,N/2+1): 83 | tw = e ** ( -j*pi*(.5+float(k)/N ) ) 84 | 85 | F1k = Fp[k] + Fp[N-k].conjugate() 86 | F2k = Fp[k] - Fp[N-k].conjugate() 87 | F2k *= tw 88 | F[k] = ( F1k + F2k ) * .5 89 | F[N-k] = ( F1k - F2k ).conjugate() * .5 90 | #F[N-k] = ( F1kp + e ** ( -j*pi*(.5+float(N-k)/N ) ) * F2kp ) * .5 91 | #F[N-k] = ( F1k.conjugate() - tw.conjugate() * F2k.conjugate() ) * .5 92 | 93 | F[N] = complex( Fp[0].real - Fp[0].imag , 0 ) 94 | return F 95 | 96 | def main(): 97 | #fft_func = fft 98 | fft_func = real_fft 99 | 100 | tvec = [0.309655,0.815653,0.768570,0.591841,0.404767,0.637617,0.007803,0.012665] 101 | Ftvec = [ complex(r,i) for r,i in zip( 102 | [3.548571,-0.378761,-0.061950,0.188537,-0.566981,0.188537,-0.061950,-0.378761], 103 | [0.000000,-1.296198,-0.848764,0.225337,0.000000,-0.225337,0.848764,1.296198] ) ] 104 | 105 | F = fft_func( tvec,0 ) 106 | 107 | nerrs= 0 108 | for i in range(len(Ftvec)/2 + 1): 109 | if abs( F[i] - Ftvec[i] )> 1e-5: 110 | print 'F[%d]: %s != %s' % (i,F[i],Ftvec[i]) 111 | nerrs += 1 112 | 113 | print '%d errors in forward fft' % nerrs 114 | if nerrs: 115 | return 116 | 117 | trec = fft_func( F , 1 ) 118 | 119 | for i in range(len(trec) ): 120 | trec[i] /= len(trec) 121 | 122 | for i in range(len(tvec) ): 123 | if abs( trec[i] - tvec[i] )> 1e-5: 124 | print 't[%d]: %s != %s' % (i,tvec[i],trec[i]) 125 | nerrs += 1 126 | 127 | print '%d errors in reverse fft' % nerrs 128 | 129 | 130 | def make_random(dims=[1]): 131 | import Numeric 132 | res = [] 133 | for i in range(dims[0]): 134 | if len(dims)==1: 135 | r=random.uniform(-1,1) 136 | i=random.uniform(-1,1) 137 | res.append( complex(r,i) ) 138 | else: 139 | res.append( make_random( dims[1:] ) ) 140 | return Numeric.array(res) 141 | 142 | def flatten(x): 143 | import Numeric 144 | ntotal = Numeric.product(Numeric.shape(x)) 145 | return Numeric.reshape(x,(ntotal,)) 146 | 147 | def randmat( ndims ): 148 | dims=[] 149 | for i in range( ndims ): 150 | curdim = int( random.uniform(2,4) ) 151 | dims.append( curdim ) 152 | return make_random(dims ) 153 | 154 | def test_fftnd(ndims=3): 155 | import FFT 156 | import Numeric 157 | 158 | x=randmat( ndims ) 159 | print 'dimensions=%s' % str( Numeric.shape(x) ) 160 | #print 'x=%s' %str(x) 161 | xver = FFT.fftnd(x) 162 | x2=myfftnd(x) 163 | err = xver - x2 164 | errf = flatten(err) 165 | xverf = flatten(xver) 166 | errpow = Numeric.vdot(errf,errf)+1e-10 167 | sigpow = Numeric.vdot(xverf,xverf)+1e-10 168 | snr = 10*math.log10(abs(sigpow/errpow) ) 169 | if snr<80: 170 | print xver 171 | print x2 172 | print 'SNR=%sdB' % str( snr ) 173 | 174 | def myfftnd(x): 175 | import Numeric 176 | xf = flatten(x) 177 | Xf = fftndwork( xf , Numeric.shape(x) ) 178 | return Numeric.reshape(Xf,Numeric.shape(x) ) 179 | 180 | def fftndwork(x,dims): 181 | import Numeric 182 | dimprod=Numeric.product( dims ) 183 | 184 | for k in range( len(dims) ): 185 | cur_dim=dims[ k ] 186 | stride=dimprod/cur_dim 187 | next_x = [complex(0,0)]*len(x) 188 | for i in range(stride): 189 | next_x[i*cur_dim:(i+1)*cur_dim] = fft(x[i:(i+cur_dim)*stride:stride],0) 190 | x = next_x 191 | return x 192 | 193 | if __name__ == "__main__": 194 | try: 195 | nd = int(sys.argv[1]) 196 | except: 197 | nd=None 198 | if nd: 199 | test_fftnd( nd ) 200 | else: 201 | sys.exit(0) 202 | -------------------------------------------------------------------------------- /test/mk_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright (c) 2003-2010, Mark Borgerding. All rights reserved. 3 | # This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | # 5 | # SPDX-License-Identifier: BSD-3-Clause 6 | # See COPYING file for more information. 7 | 8 | import FFT 9 | import sys 10 | import random 11 | import re 12 | j=complex(0,1) 13 | 14 | def randvec(n,iscomplex): 15 | if iscomplex: 16 | return [ 17 | int(random.uniform(-32768,32767) ) + j*int(random.uniform(-32768,32767) ) 18 | for i in range(n) ] 19 | else: 20 | return [ int(random.uniform(-32768,32767) ) for i in range(n) ] 21 | 22 | def c_format(v,round=0): 23 | if round: 24 | return ','.join( [ '{%d,%d}' %(int(c.real),int(c.imag) ) for c in v ] ) 25 | else: 26 | s= ','.join( [ '{%.60f ,%.60f }' %(c.real,c.imag) for c in v ] ) 27 | return re.sub(r'\.?0+ ',' ',s) 28 | 29 | def test_cpx( n,inverse ,short): 30 | v = randvec(n,1) 31 | scale = 1 32 | if short: 33 | minsnr=30 34 | else: 35 | minsnr=100 36 | 37 | if inverse: 38 | tvecout = FFT.inverse_fft(v) 39 | if short: 40 | scale = 1 41 | else: 42 | scale = len(v) 43 | else: 44 | tvecout = FFT.fft(v) 45 | if short: 46 | scale = 1.0/len(v) 47 | 48 | tvecout = [ c * scale for c in tvecout ] 49 | 50 | 51 | s="""#define NFFT %d""" % len(v) + """ 52 | { 53 | double snr; 54 | kiss_fft_cpx test_vec_in[NFFT] = { """ + c_format(v) + """}; 55 | kiss_fft_cpx test_vec_out[NFFT] = {""" + c_format( tvecout ) + """}; 56 | kiss_fft_cpx testbuf[NFFT]; 57 | void * cfg = kiss_fft_alloc(NFFT,%d,0,0);""" % inverse + """ 58 | 59 | kiss_fft(cfg,test_vec_in,testbuf); 60 | snr = snr_compare(test_vec_out,testbuf,NFFT); 61 | printf("DATATYPE=" xstr(kiss_fft_scalar) ", FFT n=%d, inverse=%d, snr = %g dB\\n",NFFT,""" + str(inverse) + """,snr); 62 | if (snr<""" + str(minsnr) + """) 63 | exit_code++; 64 | free(cfg); 65 | } 66 | #undef NFFT 67 | """ 68 | return s 69 | 70 | def compare_func(): 71 | s=""" 72 | #define xstr(s) str(s) 73 | #define str(s) #s 74 | double snr_compare( kiss_fft_cpx * test_vec_out,kiss_fft_cpx * testbuf, int n) 75 | { 76 | int k; 77 | double sigpow,noisepow,err,snr,scale=0; 78 | kiss_fft_cpx err; 79 | sigpow = noisepow = .000000000000000000000000000001; 80 | 81 | for (k=0;k 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include "pstats.h" 15 | 16 | static struct tms tms_beg; 17 | static struct tms tms_end; 18 | static int has_times = 0; 19 | 20 | 21 | void pstats_init(void) 22 | { 23 | has_times = times(&tms_beg) != -1; 24 | } 25 | 26 | static void tms_report(void) 27 | { 28 | double cputime; 29 | if (! has_times ) 30 | return; 31 | times(&tms_end); 32 | cputime = ( ((float)tms_end.tms_utime + tms_end.tms_stime + tms_end.tms_cutime + tms_end.tms_cstime ) - 33 | ((float)tms_beg.tms_utime + tms_beg.tms_stime + tms_beg.tms_cutime + tms_beg.tms_cstime ) ) 34 | / sysconf(_SC_CLK_TCK); 35 | fprintf(stderr,"\tcputime=%.3f\n" , cputime); 36 | } 37 | 38 | static void ps_report(void) 39 | { 40 | char buf[1024]; 41 | #ifdef __APPLE__ /* MAC OS X */ 42 | sprintf(buf,"ps -o command,majflt,minflt,rss,pagein,vsz -p %d 1>&2",getpid() ); 43 | #else /* GNU/Linux */ 44 | sprintf(buf,"ps -o comm,majflt,minflt,rss,drs,pagein,sz,trs,vsz %d 1>&2",getpid() ); 45 | #endif 46 | if (system( buf )==-1) { 47 | perror("system call to ps failed"); 48 | } 49 | } 50 | 51 | void pstats_report() 52 | { 53 | ps_report(); 54 | tms_report(); 55 | } 56 | 57 | -------------------------------------------------------------------------------- /test/pstats.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003-2010, Mark Borgerding. All rights reserved. 3 | * This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | * 5 | * SPDX-License-Identifier: BSD-3-Clause 6 | * See COPYING file for more information. 7 | */ 8 | #ifndef PSTATS_H 9 | #define PSTATS_H 10 | 11 | void pstats_init(void); 12 | void pstats_report(void); 13 | 14 | #endif 15 | -------------------------------------------------------------------------------- /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 27 | -------------------------------------------------------------------------------- /test/test_real.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003-2010, Mark Borgerding. All rights reserved. 3 | * This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | * 5 | * SPDX-License-Identifier: BSD-3-Clause 6 | * See COPYING file for more information. 7 | */ 8 | #include "kiss_fftr.h" 9 | #include "_kiss_fft_guts.h" 10 | #include 11 | #include 12 | #include 13 | 14 | static double cputime(void) 15 | { 16 | struct tms t; 17 | times(&t); 18 | return (double)(t.tms_utime + t.tms_stime)/ sysconf(_SC_CLK_TCK) ; 19 | } 20 | 21 | static 22 | kiss_fft_scalar rand_scalar(void) 23 | { 24 | #ifdef USE_SIMD 25 | return _mm_set1_ps(rand()-RAND_MAX/2); 26 | #else 27 | kiss_fft_scalar s = (kiss_fft_scalar)(rand() -RAND_MAX/2); 28 | return s/2; 29 | #endif 30 | } 31 | 32 | static 33 | double snr_compare( kiss_fft_cpx * vec1,kiss_fft_cpx * vec2, int n) 34 | { 35 | int k; 36 | double sigpow=1e-10,noisepow=1e-10,err,snr,scale=0; 37 | 38 | #ifdef USE_SIMD 39 | float *fv1 = (float*)vec1; 40 | float *fv2 = (float*)vec2; 41 | for (k=0;k<8*n;++k) { 42 | sigpow += *fv1 * *fv1; 43 | err = *fv1 - *fv2; 44 | noisepow += err*err; 45 | ++fv1; 46 | ++fv2; 47 | } 48 | #else 49 | for (k=0;k1) 81 | nfft = atoi(argv[1]); 82 | kiss_fft_cpx cin[nfft]; 83 | kiss_fft_cpx cout[nfft]; 84 | kiss_fft_cpx sout[nfft]; 85 | kiss_fft_cfg kiss_fft_state; 86 | kiss_fftr_cfg kiss_fftr_state; 87 | 88 | kiss_fft_scalar rin[nfft+2]; 89 | kiss_fft_scalar rout[nfft+2]; 90 | kiss_fft_scalar zero; 91 | memset(&zero,0,sizeof(zero) ); // ugly way of setting short,int,float,double, or __m128 to zero 92 | 93 | srand(time(0)); 94 | 95 | for (i=0;i1) { 71 | int k; 72 | for (k=1;k 10 | #include 11 | #include 12 | 13 | #include 14 | static inline 15 | double curtime(void) 16 | { 17 | struct timeval tv; 18 | gettimeofday(&tv, NULL); 19 | return (double)tv.tv_sec + (double)tv.tv_usec*.000001; 20 | } 21 | 22 | using namespace std; 23 | 24 | template 25 | void dotest(int nfft) 26 | { 27 | typedef kissfft FFT; 28 | typedef std::complex cpx_type; 29 | 30 | cout << "type:" << typeid(T).name() << " nfft:" << nfft; 31 | 32 | FFT fft(nfft,false); 33 | 34 | vector inbuf(nfft); 35 | vector outbuf(nfft); 36 | for (int k=0;k acc = 0; 46 | long double phinc = 2*k0* M_PIl / nfft; 47 | for (int k1=0;k1 x(inbuf[k1].real(),inbuf[k1].imag()); 49 | acc += x * exp( complex(0,-k1*phinc) ); 50 | } 51 | totalpower += norm(acc); 52 | complex x(outbuf[k0].real(),outbuf[k0].imag()); 53 | complex dif = acc - x; 54 | difpower += norm(dif); 55 | } 56 | cout << " RMSE:" << sqrt(difpower/totalpower) << "\t"; 57 | 58 | double t0 = curtime(); 59 | int nits=20e6/nfft; 60 | for (int k=0;k1) { 70 | for (int k=1;k(nfft); dotest(nfft); dotest(nfft); 73 | } 74 | }else{ 75 | dotest(32); dotest(32); dotest(32); 76 | dotest(1024); dotest(1024); dotest(1024); 77 | dotest(840); dotest(840); dotest(840); 78 | } 79 | return 0; 80 | } 81 | -------------------------------------------------------------------------------- /test/testkiss.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright (c) 2003-2010, Mark Borgerding. All rights reserved. 3 | # This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | # 5 | # SPDX-License-Identifier: BSD-3-Clause 6 | # See COPYING file for more information. 7 | 8 | import math 9 | import sys 10 | import os 11 | import random 12 | import struct 13 | import popen2 14 | import getopt 15 | import numpy 16 | 17 | pi=math.pi 18 | e=math.e 19 | j=complex(0,1) 20 | 21 | doreal=0 22 | 23 | datatype = os.environ.get('DATATYPE','float') 24 | 25 | util = '../tools/fft_' + datatype 26 | minsnr=90 27 | if datatype == 'double': 28 | fmt='d' 29 | elif datatype=='int16_t': 30 | fmt='h' 31 | minsnr=10 32 | elif datatype=='int32_t': 33 | fmt='i' 34 | elif datatype=='simd': 35 | fmt='4f' 36 | sys.stderr.write('testkiss.py does not yet test simd') 37 | sys.exit(0) 38 | elif datatype=='float': 39 | fmt='f' 40 | else: 41 | sys.stderr.write('unrecognized datatype %s\n' % datatype) 42 | sys.exit(1) 43 | 44 | 45 | def dopack(x,cpx=1): 46 | x = numpy.reshape( x, ( numpy.size(x),) ) 47 | 48 | if cpx: 49 | s = ''.join( [ struct.pack(fmt*2,c.real,c.imag) for c in x ] ) 50 | else: 51 | s = ''.join( [ struct.pack(fmt,c.real) for c in x ] ) 52 | return s 53 | 54 | def dounpack(x,cpx): 55 | uf = fmt * ( len(x) / struct.calcsize(fmt) ) 56 | s = struct.unpack(uf,x) 57 | if cpx: 58 | return numpy.array(s[::2]) + numpy.array( s[1::2] )*j 59 | else: 60 | return numpy.array(s ) 61 | 62 | def make_random(dims=[1]): 63 | res = [] 64 | for i in range(dims[0]): 65 | if len(dims)==1: 66 | r=random.uniform(-1,1) 67 | if doreal: 68 | res.append( r ) 69 | else: 70 | i=random.uniform(-1,1) 71 | res.append( complex(r,i) ) 72 | else: 73 | res.append( make_random( dims[1:] ) ) 74 | return numpy.array(res) 75 | 76 | def flatten(x): 77 | ntotal = numpy.size(x) 78 | return numpy.reshape(x,(ntotal,)) 79 | 80 | def randmat( ndims ): 81 | dims=[] 82 | for i in range( ndims ): 83 | curdim = int( random.uniform(2,5) ) 84 | if doreal and i==(ndims-1): 85 | curdim = int(curdim/2)*2 # force even last dimension if real 86 | dims.append( curdim ) 87 | return make_random(dims ) 88 | 89 | def test_fft(ndims): 90 | x=randmat( ndims ) 91 | 92 | 93 | if doreal: 94 | xver = numpy.fft.rfftn(x) 95 | else: 96 | xver = numpy.fft.fftn(x) 97 | 98 | open('/tmp/fftexp.dat','w').write(dopack( flatten(xver) , True ) ) 99 | 100 | x2=dofft(x,doreal) 101 | err = xver - x2 102 | errf = flatten(err) 103 | xverf = flatten(xver) 104 | errpow = numpy.vdot(errf,errf)+1e-10 105 | sigpow = numpy.vdot(xverf,xverf)+1e-10 106 | snr = 10*math.log10(abs(sigpow/errpow) ) 107 | print 'SNR (compared to NumPy) : %.1fdB' % float(snr) 108 | 109 | if snr 9 | #include 10 | #include 11 | #include "kiss_fft.h" 12 | #include "kiss_fftr.h" 13 | #include 14 | 15 | 16 | static 17 | double two_tone_test( int nfft, int bin1,int bin2) 18 | { 19 | kiss_fftr_cfg cfg = NULL; 20 | kiss_fft_cpx *kout = NULL; 21 | kiss_fft_scalar *tbuf = NULL; 22 | 23 | int i; 24 | double f1 = bin1*2*M_PI/nfft; 25 | double f2 = bin2*2*M_PI/nfft; 26 | double sigpow=0; 27 | double noisepow=0; 28 | #if FIXED_POINT==32 29 | long maxrange = LONG_MAX; 30 | #else 31 | long maxrange = SHRT_MAX;/* works fine for float too*/ 32 | #endif 33 | 34 | cfg = kiss_fftr_alloc(nfft , 0, NULL, NULL); 35 | tbuf = KISS_FFT_MALLOC(nfft * sizeof(kiss_fft_scalar)); 36 | kout = KISS_FFT_MALLOC(nfft * sizeof(kiss_fft_cpx)); 37 | 38 | /* generate a signal with two tones*/ 39 | for (i = 0; i < nfft; i++) { 40 | #ifdef USE_SIMD 41 | tbuf[i] = _mm_set1_ps( (maxrange>>1)*cos(f1*i) 42 | + (maxrange>>1)*cos(f2*i) ); 43 | #else 44 | tbuf[i] = (maxrange>>1)*cos(f1*i) 45 | + (maxrange>>1)*cos(f2*i); 46 | #endif 47 | } 48 | 49 | kiss_fftr(cfg, tbuf, kout); 50 | 51 | for (i=0;i < (nfft/2+1);++i) { 52 | #ifdef USE_SIMD 53 | double tmpr = (double)*(float*)&kout[i].r / (double)maxrange; 54 | double tmpi = (double)*(float*)&kout[i].i / (double)maxrange; 55 | #else 56 | double tmpr = (double)kout[i].r / (double)maxrange; 57 | double tmpi = (double)kout[i].i / (double)maxrange; 58 | #endif 59 | double mag2 = tmpr*tmpr + tmpi*tmpi; 60 | if (i!=0 && i!= nfft/2) 61 | mag2 *= 2; /* all bins except DC and Nyquist have symmetric counterparts implied*/ 62 | 63 | /* if there is power in one of the expected bins, it is signal, otherwise noise*/ 64 | if ( i!=bin1 && i != bin2 ) 65 | noisepow += mag2; 66 | else 67 | sigpow += mag2; 68 | } 69 | kiss_fft_cleanup(); 70 | /*printf("TEST %d,%d,%d noise @ %fdB\n",nfft,bin1,bin2,10*log10(noisepow/sigpow +1e-30) );*/ 71 | return 10*log10(sigpow/(noisepow+1e-50) ); 72 | } 73 | 74 | int main(int argc,char ** argv) 75 | { 76 | int nfft = 4*2*2*3*5; 77 | if (argc>1) nfft = atoi(argv[1]); 78 | 79 | int i,j; 80 | double minsnr = 500; 81 | double maxsnr = -500; 82 | double snr; 83 | for (i=0;i>4)+1) { 84 | for (j=i;j>4)+7) { 85 | snr = two_tone_test(nfft,i,j); 86 | if (snrmaxsnr) { 90 | maxsnr=snr; 91 | } 92 | } 93 | } 94 | snr = two_tone_test(nfft,nfft/2,nfft/2); 95 | if (snrmaxsnr) maxsnr=snr; 97 | 98 | printf("TwoToneTest: snr ranges from %ddB to %ddB\n",(int)minsnr,(int)maxsnr); 99 | printf("sizeof(kiss_fft_scalar) = %d\n",(int)sizeof(kiss_fft_scalar) ); 100 | return 0; 101 | } 102 | -------------------------------------------------------------------------------- /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_* 63 | -------------------------------------------------------------------------------- /tools/fftutil.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003-2004, Mark Borgerding. All rights reserved. 3 | * This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | * 5 | * SPDX-License-Identifier: BSD-3-Clause 6 | * See COPYING file for more information. 7 | */ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | #include "kiss_fft.h" 16 | #include "kiss_fftndr.h" 17 | 18 | static 19 | void fft_file(FILE * fin,FILE * fout,int nfft,int isinverse) 20 | { 21 | kiss_fft_cfg st; 22 | kiss_fft_cpx * buf; 23 | kiss_fft_cpx * bufout; 24 | 25 | buf = (kiss_fft_cpx*)malloc(sizeof(kiss_fft_cpx) * nfft ); 26 | bufout = (kiss_fft_cpx*)malloc(sizeof(kiss_fft_cpx) * nfft ); 27 | st = kiss_fft_alloc( nfft ,isinverse ,0,0); 28 | 29 | while ( fread( buf , sizeof(kiss_fft_cpx) * nfft ,1, fin ) > 0 ) { 30 | kiss_fft( st , buf ,bufout); 31 | fwrite( bufout , sizeof(kiss_fft_cpx) , nfft , fout ); 32 | } 33 | free(st); 34 | free(buf); 35 | free(bufout); 36 | } 37 | 38 | static 39 | void fft_filend(FILE * fin,FILE * fout,int *dims,int ndims,int isinverse) 40 | { 41 | kiss_fftnd_cfg st; 42 | kiss_fft_cpx *buf; 43 | int dimprod=1,i; 44 | for (i=0;i 0) { 51 | kiss_fftnd (st, buf, buf); 52 | fwrite (buf, sizeof (kiss_fft_cpx), dimprod, fout); 53 | } 54 | free (st); 55 | free (buf); 56 | } 57 | 58 | 59 | 60 | static 61 | void fft_filend_real(FILE * fin,FILE * fout,int *dims,int ndims,int isinverse) 62 | { 63 | int dimprod=1,i; 64 | kiss_fftndr_cfg st; 65 | void *ibuf; 66 | void *obuf; 67 | int insize,outsize; // size in bytes 68 | 69 | for (i=0;i 0) { 85 | if (isinverse) { 86 | kiss_fftndri(st, 87 | (kiss_fft_cpx*)ibuf, 88 | (kiss_fft_scalar*)obuf); 89 | }else{ 90 | kiss_fftndr(st, 91 | (kiss_fft_scalar*)ibuf, 92 | (kiss_fft_cpx*)obuf); 93 | } 94 | fwrite (obuf, sizeof(kiss_fft_scalar), outsize,fout); 95 | } 96 | free(st); 97 | free(ibuf); 98 | free(obuf); 99 | } 100 | 101 | static 102 | void fft_file_real(FILE * fin,FILE * fout,int nfft,int isinverse) 103 | { 104 | kiss_fftr_cfg st; 105 | kiss_fft_scalar * rbuf; 106 | kiss_fft_cpx * cbuf; 107 | 108 | rbuf = (kiss_fft_scalar*)malloc(sizeof(kiss_fft_scalar) * nfft ); 109 | cbuf = (kiss_fft_cpx*)malloc(sizeof(kiss_fft_cpx) * (nfft/2+1) ); 110 | st = kiss_fftr_alloc( nfft ,isinverse ,0,0); 111 | 112 | if (isinverse==0) { 113 | while ( fread( rbuf , sizeof(kiss_fft_scalar) * nfft ,1, fin ) > 0 ) { 114 | kiss_fftr( st , rbuf ,cbuf); 115 | fwrite( cbuf , sizeof(kiss_fft_cpx) , (nfft/2 + 1) , fout ); 116 | } 117 | }else{ 118 | while ( fread( cbuf , sizeof(kiss_fft_cpx) * (nfft/2+1) ,1, fin ) > 0 ) { 119 | kiss_fftri( st , cbuf ,rbuf); 120 | fwrite( rbuf , sizeof(kiss_fft_scalar) , nfft , fout ); 121 | } 122 | } 123 | free(st); 124 | free(rbuf); 125 | free(cbuf); 126 | } 127 | 128 | static 129 | int get_dims(char * arg,int * dims) 130 | { 131 | char *p0; 132 | int ndims=0; 133 | 134 | do{ 135 | p0 = strchr(arg,','); 136 | if (p0) 137 | *p0++ = '\0'; 138 | dims[ndims++] = atoi(arg); 139 | // fprintf(stderr,"dims[%d] = %d\n",ndims-1,dims[ndims-1]); 140 | arg = p0; 141 | }while (p0); 142 | return ndims; 143 | } 144 | 145 | int main(int argc,char ** argv) 146 | { 147 | int isinverse=0; 148 | int isreal=0; 149 | FILE *fin=stdin; 150 | FILE *fout=stdout; 151 | int ndims=1; 152 | int dims[32]; 153 | dims[0] = 1024; /*default fft size*/ 154 | 155 | while (1) { 156 | int c=getopt(argc,argv,"n:iR"); 157 | if (c==-1) break; 158 | switch (c) { 159 | case 'n': 160 | ndims = get_dims(optarg,dims); 161 | break; 162 | case 'i':isinverse=1;break; 163 | case 'R':isreal=1;break; 164 | case '?': 165 | fprintf(stderr,"usage options:\n" 166 | "\t-n d1[,d2,d3...]: fft dimension(s)\n" 167 | "\t-i : inverse\n" 168 | "\t-R : real input samples, not complex\n"); 169 | exit (1); 170 | default:fprintf(stderr,"bad %c\n",c);break; 171 | } 172 | } 173 | 174 | if ( optind < argc ) { 175 | if (strcmp("-",argv[optind]) !=0) 176 | fin = fopen(argv[optind],"rb"); 177 | ++optind; 178 | } 179 | 180 | if ( optind < argc ) { 181 | if ( strcmp("-",argv[optind]) !=0 ) 182 | fout = fopen(argv[optind],"wb"); 183 | ++optind; 184 | } 185 | 186 | if (ndims==1) { 187 | if (isreal) 188 | fft_file_real(fin,fout,dims[0],isinverse); 189 | else 190 | fft_file(fin,fout,dims[0],isinverse); 191 | }else{ 192 | if (isreal) 193 | fft_filend_real(fin,fout,dims,ndims,isinverse); 194 | else 195 | fft_filend(fin,fout,dims,ndims,isinverse); 196 | } 197 | 198 | if (fout!=stdout) fclose(fout); 199 | if (fin!=stdin) fclose(fin); 200 | 201 | return 0; 202 | } 203 | -------------------------------------------------------------------------------- /tools/kfc.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003-2004, Mark Borgerding. All rights reserved. 3 | * This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | * 5 | * SPDX-License-Identifier: BSD-3-Clause 6 | * See COPYING file for more information. 7 | */ 8 | 9 | #include "kfc.h" 10 | 11 | typedef struct cached_fft *kfc_cfg; 12 | 13 | struct cached_fft 14 | { 15 | int nfft; 16 | int inverse; 17 | kiss_fft_cfg cfg; 18 | kfc_cfg next; 19 | }; 20 | 21 | static kfc_cfg cache_root=NULL; 22 | static int ncached=0; 23 | 24 | static kiss_fft_cfg find_cached_fft(int nfft,int inverse) 25 | { 26 | size_t len; 27 | kfc_cfg cur=cache_root; 28 | kfc_cfg prev=NULL; 29 | while ( cur ) { 30 | if ( cur->nfft == nfft && inverse == cur->inverse ) 31 | break;/*found the right node*/ 32 | prev = cur; 33 | cur = prev->next; 34 | } 35 | if (cur== NULL) { 36 | /* no cached node found, need to create a new one*/ 37 | kiss_fft_alloc(nfft,inverse,0,&len); 38 | #ifdef USE_SIMD 39 | int padding = (16-sizeof(struct cached_fft)) & 15; 40 | // make sure the cfg aligns on a 16 byte boundary 41 | len += padding; 42 | #endif 43 | cur = (kfc_cfg)KISS_FFT_MALLOC((sizeof(struct cached_fft) + len )); 44 | if (cur == NULL) 45 | return NULL; 46 | cur->cfg = (kiss_fft_cfg)(cur+1); 47 | #ifdef USE_SIMD 48 | cur->cfg = (kiss_fft_cfg) ((char*)(cur+1)+padding); 49 | #endif 50 | kiss_fft_alloc(nfft,inverse,cur->cfg,&len); 51 | cur->nfft=nfft; 52 | cur->inverse=inverse; 53 | cur->next = NULL; 54 | if ( prev ) 55 | prev->next = cur; 56 | else 57 | cache_root = cur; 58 | ++ncached; 59 | } 60 | return cur->cfg; 61 | } 62 | 63 | void kfc_cleanup(void) 64 | { 65 | kfc_cfg cur=cache_root; 66 | kfc_cfg next=NULL; 67 | while (cur){ 68 | next = cur->next; 69 | free(cur); 70 | cur=next; 71 | } 72 | ncached=0; 73 | cache_root = NULL; 74 | } 75 | void kfc_fft(int nfft, const kiss_fft_cpx * fin,kiss_fft_cpx * fout) 76 | { 77 | kiss_fft( find_cached_fft(nfft,0),fin,fout ); 78 | } 79 | 80 | void kfc_ifft(int nfft, const kiss_fft_cpx * fin,kiss_fft_cpx * fout) 81 | { 82 | kiss_fft( find_cached_fft(nfft,1),fin,fout ); 83 | } 84 | 85 | #ifdef KFC_TEST 86 | static void check(int nc) 87 | { 88 | if (ncached != nc) { 89 | fprintf(stderr,"ncached should be %d,but it is %d\n",nc,ncached); 90 | exit(1); 91 | } 92 | } 93 | 94 | int main(void) 95 | { 96 | kiss_fft_cpx buf1[1024],buf2[1024]; 97 | memset(buf1,0,sizeof(buf1)); 98 | check(0); 99 | kfc_fft(512,buf1,buf2); 100 | check(1); 101 | kfc_fft(512,buf1,buf2); 102 | check(1); 103 | kfc_ifft(512,buf1,buf2); 104 | check(2); 105 | kfc_cleanup(); 106 | check(0); 107 | return 0; 108 | } 109 | #endif 110 | -------------------------------------------------------------------------------- /tools/kfc.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003-2004, Mark Borgerding. All rights reserved. 3 | * This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | * 5 | * SPDX-License-Identifier: BSD-3-Clause 6 | * See COPYING file for more information. 7 | */ 8 | 9 | #ifndef KFC_H 10 | #define KFC_H 11 | #include "kiss_fft.h" 12 | 13 | #ifdef __cplusplus 14 | extern "C" { 15 | #endif 16 | 17 | /* 18 | KFC -- Kiss FFT Cache 19 | 20 | Not needing to deal with kiss_fft_alloc and a config 21 | object may be handy for a lot of programs. 22 | 23 | KFC uses the underlying KISS FFT functions, but caches the config object. 24 | The first time kfc_fft or kfc_ifft for a given FFT size, the cfg 25 | object is created for it. All subsequent calls use the cached 26 | configuration object. 27 | 28 | NOTE: 29 | You should probably not use this if your program will be using a lot 30 | of various sizes of FFTs. There is a linear search through the 31 | cached objects. If you are only using one or two FFT sizes, this 32 | will be negligible. Otherwise, you may want to use another method 33 | of managing the cfg objects. 34 | 35 | There is no automated cleanup of the cached objects. This could lead 36 | to large memory usage in a program that uses a lot of *DIFFERENT* 37 | sized FFTs. If you want to force all cached cfg objects to be freed, 38 | call kfc_cleanup. 39 | 40 | */ 41 | 42 | /*forward complex FFT */ 43 | void kfc_fft(int nfft, const kiss_fft_cpx * fin,kiss_fft_cpx * fout); 44 | /*reverse complex FFT */ 45 | void kfc_ifft(int nfft, const kiss_fft_cpx * fin,kiss_fft_cpx * fout); 46 | 47 | /*free all cached objects*/ 48 | void kfc_cleanup(void); 49 | 50 | #ifdef __cplusplus 51 | } 52 | #endif 53 | 54 | #endif 55 | -------------------------------------------------------------------------------- /tools/kiss_fastfir.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003-2004, Mark Borgerding. All rights reserved. 3 | * This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | * 5 | * SPDX-License-Identifier: BSD-3-Clause 6 | * See COPYING file for more information. 7 | */ 8 | 9 | #include "_kiss_fft_guts.h" 10 | 11 | 12 | /* 13 | Some definitions that allow real or complex filtering 14 | */ 15 | #ifdef REAL_FASTFIR 16 | #define MIN_FFT_LEN 2048 17 | #include "kiss_fftr.h" 18 | typedef kiss_fft_scalar kffsamp_t; 19 | typedef kiss_fftr_cfg kfcfg_t; 20 | #define FFT_ALLOC kiss_fftr_alloc 21 | #define FFTFWD kiss_fftr 22 | #define FFTINV kiss_fftri 23 | #else 24 | #define MIN_FFT_LEN 1024 25 | typedef kiss_fft_cpx kffsamp_t; 26 | typedef kiss_fft_cfg kfcfg_t; 27 | #define FFT_ALLOC kiss_fft_alloc 28 | #define FFTFWD kiss_fft 29 | #define FFTINV kiss_fft 30 | #endif 31 | 32 | typedef struct kiss_fastfir_state *kiss_fastfir_cfg; 33 | 34 | 35 | 36 | kiss_fastfir_cfg kiss_fastfir_alloc(const kffsamp_t * imp_resp,size_t n_imp_resp, 37 | size_t * nfft,void * mem,size_t*lenmem); 38 | 39 | /* see do_file_filter for usage */ 40 | size_t kiss_fastfir( kiss_fastfir_cfg cfg, kffsamp_t * inbuf, kffsamp_t * outbuf, size_t n, size_t *offset); 41 | 42 | 43 | 44 | static int verbose=0; 45 | 46 | 47 | struct kiss_fastfir_state{ 48 | size_t nfft; 49 | size_t ngood; 50 | kfcfg_t fftcfg; 51 | kfcfg_t ifftcfg; 52 | kiss_fft_cpx * fir_freq_resp; 53 | kiss_fft_cpx * freqbuf; 54 | size_t n_freq_bins; 55 | kffsamp_t * tmpbuf; 56 | }; 57 | 58 | 59 | kiss_fastfir_cfg kiss_fastfir_alloc( 60 | const kffsamp_t * imp_resp,size_t n_imp_resp, 61 | size_t *pnfft, /* if <= 0, an appropriate size will be chosen */ 62 | void * mem,size_t*lenmem) 63 | { 64 | kiss_fastfir_cfg st = NULL; 65 | size_t len_fftcfg,len_ifftcfg; 66 | size_t memneeded = sizeof(struct kiss_fastfir_state); 67 | char * ptr; 68 | size_t i; 69 | size_t nfft=0; 70 | float scale; 71 | int n_freq_bins; 72 | if (pnfft) 73 | nfft=*pnfft; 74 | 75 | if (nfft<=0) { 76 | /* determine fft size as next power of two at least 2x 77 | the impulse response length*/ 78 | i=n_imp_resp-1; 79 | nfft=2; 80 | do{ 81 | nfft<<=1; 82 | }while (i>>=1); 83 | #ifdef MIN_FFT_LEN 84 | if ( nfft < MIN_FFT_LEN ) 85 | nfft=MIN_FFT_LEN; 86 | #endif 87 | } 88 | if (pnfft) 89 | *pnfft = nfft; 90 | 91 | #ifdef REAL_FASTFIR 92 | n_freq_bins = nfft/2 + 1; 93 | #else 94 | n_freq_bins = nfft; 95 | #endif 96 | /*fftcfg*/ 97 | FFT_ALLOC (nfft, 0, NULL, &len_fftcfg); 98 | memneeded += len_fftcfg; 99 | /*ifftcfg*/ 100 | FFT_ALLOC (nfft, 1, NULL, &len_ifftcfg); 101 | memneeded += len_ifftcfg; 102 | /* tmpbuf */ 103 | memneeded += sizeof(kffsamp_t) * nfft; 104 | /* fir_freq_resp */ 105 | memneeded += sizeof(kiss_fft_cpx) * n_freq_bins; 106 | /* freqbuf */ 107 | memneeded += sizeof(kiss_fft_cpx) * n_freq_bins; 108 | 109 | if (lenmem == NULL) { 110 | st = (kiss_fastfir_cfg) malloc (memneeded); 111 | } else { 112 | if (*lenmem >= memneeded) 113 | st = (kiss_fastfir_cfg) mem; 114 | *lenmem = memneeded; 115 | } 116 | if (!st) 117 | return NULL; 118 | 119 | st->nfft = nfft; 120 | st->ngood = nfft - n_imp_resp + 1; 121 | st->n_freq_bins = n_freq_bins; 122 | ptr=(char*)(st+1); 123 | 124 | st->fftcfg = (kfcfg_t)ptr; 125 | ptr += len_fftcfg; 126 | 127 | st->ifftcfg = (kfcfg_t)ptr; 128 | ptr += len_ifftcfg; 129 | 130 | st->tmpbuf = (kffsamp_t*)ptr; 131 | ptr += sizeof(kffsamp_t) * nfft; 132 | 133 | st->freqbuf = (kiss_fft_cpx*)ptr; 134 | ptr += sizeof(kiss_fft_cpx) * n_freq_bins; 135 | 136 | st->fir_freq_resp = (kiss_fft_cpx*)ptr; 137 | ptr += sizeof(kiss_fft_cpx) * n_freq_bins; 138 | 139 | FFT_ALLOC (nfft,0,st->fftcfg , &len_fftcfg); 140 | FFT_ALLOC (nfft,1,st->ifftcfg , &len_ifftcfg); 141 | 142 | memset(st->tmpbuf,0,sizeof(kffsamp_t)*nfft); 143 | /*zero pad in the middle to left-rotate the impulse response 144 | This puts the scrap samples at the end of the inverse fft'd buffer */ 145 | st->tmpbuf[0] = imp_resp[ n_imp_resp - 1 ]; 146 | for (i=0;itmpbuf[ nfft - n_imp_resp + 1 + i ] = imp_resp[ i ]; 148 | } 149 | 150 | FFTFWD(st->fftcfg,st->tmpbuf,st->fir_freq_resp); 151 | 152 | /* TODO: this won't work for fixed point */ 153 | scale = 1.0 / st->nfft; 154 | 155 | for ( i=0; i < st->n_freq_bins; ++i ) { 156 | #ifdef USE_SIMD 157 | st->fir_freq_resp[i].r *= _mm_set1_ps(scale); 158 | st->fir_freq_resp[i].i *= _mm_set1_ps(scale); 159 | #else 160 | st->fir_freq_resp[i].r *= scale; 161 | st->fir_freq_resp[i].i *= scale; 162 | #endif 163 | } 164 | return st; 165 | } 166 | 167 | static void fastconv1buf(const kiss_fastfir_cfg st,const kffsamp_t * in,kffsamp_t * out) 168 | { 169 | size_t i; 170 | /* multiply the frequency response of the input signal by 171 | that of the fir filter*/ 172 | FFTFWD( st->fftcfg, in , st->freqbuf ); 173 | for ( i=0; in_freq_bins; ++i ) { 174 | kiss_fft_cpx tmpsamp; 175 | C_MUL(tmpsamp,st->freqbuf[i],st->fir_freq_resp[i]); 176 | st->freqbuf[i] = tmpsamp; 177 | } 178 | 179 | /* perform the inverse fft*/ 180 | FFTINV(st->ifftcfg,st->freqbuf,out); 181 | } 182 | 183 | /* n : the size of inbuf and outbuf in samples 184 | return value: the number of samples completely processed 185 | n-retval samples should be copied to the front of the next input buffer */ 186 | static size_t kff_nocopy( 187 | kiss_fastfir_cfg st, 188 | const kffsamp_t * inbuf, 189 | kffsamp_t * outbuf, 190 | size_t n) 191 | { 192 | size_t norig=n; 193 | while (n >= st->nfft ) { 194 | fastconv1buf(st,inbuf,outbuf); 195 | inbuf += st->ngood; 196 | outbuf += st->ngood; 197 | n -= st->ngood; 198 | } 199 | return norig - n; 200 | } 201 | 202 | static 203 | size_t kff_flush(kiss_fastfir_cfg st,const kffsamp_t * inbuf,kffsamp_t * outbuf,size_t n) 204 | { 205 | size_t zpad=0,ntmp; 206 | 207 | ntmp = kff_nocopy(st,inbuf,outbuf,n); 208 | n -= ntmp; 209 | inbuf += ntmp; 210 | outbuf += ntmp; 211 | 212 | zpad = st->nfft - n; 213 | memset(st->tmpbuf,0,sizeof(kffsamp_t)*st->nfft ); 214 | memcpy(st->tmpbuf,inbuf,sizeof(kffsamp_t)*n ); 215 | 216 | fastconv1buf(st,st->tmpbuf,st->tmpbuf); 217 | 218 | memcpy(outbuf,st->tmpbuf,sizeof(kffsamp_t)*( st->ngood - zpad )); 219 | return ntmp + st->ngood - zpad; 220 | } 221 | 222 | size_t kiss_fastfir( 223 | kiss_fastfir_cfg vst, 224 | kffsamp_t * inbuf, 225 | kffsamp_t * outbuf, 226 | size_t n_new, 227 | size_t *offset) 228 | { 229 | size_t ntot = n_new + *offset; 230 | if (n_new==0) { 231 | return kff_flush(vst,inbuf,outbuf,ntot); 232 | }else{ 233 | size_t nwritten = kff_nocopy(vst,inbuf,outbuf,ntot); 234 | *offset = ntot - nwritten; 235 | /*save the unused or underused samples at the front of the input buffer */ 236 | memcpy( inbuf , inbuf+nwritten , *offset * sizeof(kffsamp_t) ); 237 | return nwritten; 238 | } 239 | } 240 | 241 | #ifdef FAST_FILT_UTIL 242 | #include 243 | #include 244 | #include 245 | #include 246 | 247 | static 248 | void direct_file_filter( 249 | FILE * fin, 250 | FILE * fout, 251 | const kffsamp_t * imp_resp, 252 | size_t n_imp_resp) 253 | { 254 | size_t nlag = n_imp_resp - 1; 255 | 256 | const kffsamp_t *tmph; 257 | kffsamp_t *buf, *circbuf; 258 | kffsamp_t outval; 259 | size_t nread; 260 | size_t nbuf; 261 | size_t oldestlag = 0; 262 | size_t k, tap; 263 | #ifndef REAL_FASTFIR 264 | kffsamp_t tmp; 265 | #endif 266 | 267 | nbuf = 4096; 268 | buf = (kffsamp_t *) malloc ( sizeof (kffsamp_t) * nbuf); 269 | circbuf = (kffsamp_t *) malloc (sizeof (kffsamp_t) * nlag); 270 | if (!circbuf || !buf) { 271 | perror("circbuf allocation"); 272 | exit(1); 273 | } 274 | 275 | if ( fread (circbuf, sizeof (kffsamp_t), nlag, fin) != nlag ) { 276 | perror ("insufficient data to overcome transient"); 277 | exit (1); 278 | } 279 | 280 | do { 281 | nread = fread (buf, sizeof (kffsamp_t), nbuf, fin); 282 | if (nread <= 0) 283 | break; 284 | 285 | for (k = 0; k < nread; ++k) { 286 | tmph = imp_resp+nlag; 287 | #ifdef REAL_FASTFIR 288 | # ifdef USE_SIMD 289 | outval = _mm_set1_ps(0); 290 | #else 291 | outval = 0; 292 | #endif 293 | for (tap = oldestlag; tap < nlag; ++tap) 294 | outval += circbuf[tap] * *tmph--; 295 | for (tap = 0; tap < oldestlag; ++tap) 296 | outval += circbuf[tap] * *tmph--; 297 | outval += buf[k] * *tmph; 298 | #else 299 | # ifdef USE_SIMD 300 | outval.r = outval.i = _mm_set1_ps(0); 301 | #else 302 | outval.r = outval.i = 0; 303 | #endif 304 | for (tap = oldestlag; tap < nlag; ++tap){ 305 | C_MUL(tmp,circbuf[tap],*tmph); 306 | --tmph; 307 | C_ADDTO(outval,tmp); 308 | } 309 | 310 | for (tap = 0; tap < oldestlag; ++tap) { 311 | C_MUL(tmp,circbuf[tap],*tmph); 312 | --tmph; 313 | C_ADDTO(outval,tmp); 314 | } 315 | C_MUL(tmp,buf[k],*tmph); 316 | C_ADDTO(outval,tmp); 317 | #endif 318 | 319 | circbuf[oldestlag++] = buf[k]; 320 | buf[k] = outval; 321 | 322 | if (oldestlag == nlag) 323 | oldestlag = 0; 324 | } 325 | 326 | if (fwrite (buf, sizeof (buf[0]), nread, fout) != nread) { 327 | perror ("short write"); 328 | exit (1); 329 | } 330 | } while (nread); 331 | free (buf); 332 | free (circbuf); 333 | } 334 | 335 | static 336 | void do_file_filter( 337 | FILE * fin, 338 | FILE * fout, 339 | const kffsamp_t * imp_resp, 340 | size_t n_imp_resp, 341 | size_t nfft ) 342 | { 343 | int fdout; 344 | size_t n_samps_buf; 345 | 346 | kiss_fastfir_cfg cfg; 347 | kffsamp_t *inbuf,*outbuf; 348 | int nread,nwrite; 349 | size_t idx_inbuf; 350 | 351 | fdout = fileno(fout); 352 | 353 | cfg=kiss_fastfir_alloc(imp_resp,n_imp_resp,&nfft,0,0); 354 | 355 | /* use length to minimize buffer shift*/ 356 | n_samps_buf = 8*4096/sizeof(kffsamp_t); 357 | n_samps_buf = nfft + 4*(nfft-n_imp_resp+1); 358 | 359 | if (verbose) fprintf(stderr,"bufsize=%d\n",(int)(sizeof(kffsamp_t)*n_samps_buf) ); 360 | 361 | 362 | /*allocate space and initialize pointers */ 363 | inbuf = (kffsamp_t*)malloc(sizeof(kffsamp_t)*n_samps_buf); 364 | outbuf = (kffsamp_t*)malloc(sizeof(kffsamp_t)*n_samps_buf); 365 | 366 | idx_inbuf=0; 367 | do{ 368 | /* start reading at inbuf[idx_inbuf] */ 369 | nread = fread( inbuf + idx_inbuf, sizeof(kffsamp_t), n_samps_buf - idx_inbuf,fin ); 370 | 371 | /* If nread==0, then this is a flush. 372 | The total number of samples in input is idx_inbuf + nread . */ 373 | nwrite = kiss_fastfir(cfg, inbuf, outbuf,nread,&idx_inbuf) * sizeof(kffsamp_t); 374 | /* kiss_fastfir moved any unused samples to the front of inbuf and updated idx_inbuf */ 375 | 376 | if ( write(fdout, outbuf, nwrite) != nwrite ) { 377 | perror("short write"); 378 | exit(1); 379 | } 380 | }while ( nread ); 381 | free(cfg); 382 | free(inbuf); 383 | free(outbuf); 384 | } 385 | 386 | int main(int argc,char**argv) 387 | { 388 | kffsamp_t * h; 389 | int use_direct=0; 390 | size_t nh,nfft=0; 391 | FILE *fin=stdin; 392 | FILE *fout=stdout; 393 | FILE *filtfile=NULL; 394 | while (1) { 395 | int c=getopt(argc,argv,"n:h:i:o:vd"); 396 | if (c==-1) break; 397 | switch (c) { 398 | case 'v': 399 | verbose=1; 400 | break; 401 | case 'n': 402 | nfft=atoi(optarg); 403 | break; 404 | case 'i': 405 | fin = fopen(optarg,"rb"); 406 | if (fin==NULL) { 407 | perror(optarg); 408 | exit(1); 409 | } 410 | break; 411 | case 'o': 412 | fout = fopen(optarg,"w+b"); 413 | if (fout==NULL) { 414 | perror(optarg); 415 | exit(1); 416 | } 417 | break; 418 | case 'h': 419 | filtfile = fopen(optarg,"rb"); 420 | if (filtfile==NULL) { 421 | perror(optarg); 422 | exit(1); 423 | } 424 | break; 425 | case 'd': 426 | use_direct=1; 427 | break; 428 | case '?': 429 | fprintf(stderr,"usage options:\n" 430 | "\t-n nfft: fft size to use\n" 431 | "\t-d : use direct FIR filtering, not fast convolution\n" 432 | "\t-i filename: input file\n" 433 | "\t-o filename: output(filtered) file\n" 434 | "\t-n nfft: fft size to use\n" 435 | "\t-h filename: impulse response\n"); 436 | exit (1); 437 | default:fprintf(stderr,"bad %c\n",c);break; 438 | } 439 | } 440 | if (filtfile==NULL) { 441 | fprintf(stderr,"You must supply the FIR coeffs via -h\n"); 442 | exit(1); 443 | } 444 | fseek(filtfile,0,SEEK_END); 445 | nh = ftell(filtfile) / sizeof(kffsamp_t); 446 | if (verbose) fprintf(stderr,"%d samples in FIR filter\n",(int)nh); 447 | h = (kffsamp_t*)malloc(sizeof(kffsamp_t)*nh); 448 | fseek(filtfile,0,SEEK_SET); 449 | if (fread(h,sizeof(kffsamp_t),nh,filtfile) != nh) 450 | fprintf(stderr,"short read on filter file\n"); 451 | 452 | fclose(filtfile); 453 | 454 | if (use_direct) 455 | direct_file_filter( fin, fout, h,nh); 456 | else 457 | do_file_filter( fin, fout, h,nh,nfft); 458 | 459 | if (fout!=stdout) fclose(fout); 460 | if (fin!=stdin) fclose(fin); 461 | 462 | return 0; 463 | } 464 | #endif 465 | -------------------------------------------------------------------------------- /tools/kiss_fftnd.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003-2004, Mark Borgerding. All rights reserved. 3 | * This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | * 5 | * SPDX-License-Identifier: BSD-3-Clause 6 | * See COPYING file for more information. 7 | */ 8 | 9 | #include "kiss_fftnd.h" 10 | #include "_kiss_fft_guts.h" 11 | 12 | struct kiss_fftnd_state{ 13 | int dimprod; /* dimsum would be mighty tasty right now */ 14 | int ndims; 15 | int *dims; 16 | kiss_fft_cfg *states; /* cfg states for each dimension */ 17 | kiss_fft_cpx * tmpbuf; /*buffer capable of hold the entire input */ 18 | }; 19 | 20 | kiss_fftnd_cfg kiss_fftnd_alloc(const int *dims,int ndims,int inverse_fft,void*mem,size_t*lenmem) 21 | { 22 | kiss_fftnd_cfg st = NULL; 23 | int i; 24 | int dimprod=1; 25 | size_t memneeded = sizeof(struct kiss_fftnd_state); 26 | char * ptr; 27 | 28 | for (i=0;istates[i] */ 32 | dimprod *= dims[i]; 33 | } 34 | memneeded += sizeof(int) * ndims;/* st->dims */ 35 | memneeded += sizeof(void*) * ndims;/* st->states */ 36 | memneeded += sizeof(kiss_fft_cpx) * dimprod; /* st->tmpbuf */ 37 | 38 | if (lenmem == NULL) {/* allocate for the caller*/ 39 | st = (kiss_fftnd_cfg) malloc (memneeded); 40 | } else { /* initialize supplied buffer if big enough */ 41 | if (*lenmem >= memneeded) 42 | st = (kiss_fftnd_cfg) mem; 43 | *lenmem = memneeded; /*tell caller how big struct is (or would be) */ 44 | } 45 | if (!st) 46 | return NULL; /*malloc failed or buffer too small */ 47 | 48 | st->dimprod = dimprod; 49 | st->ndims = ndims; 50 | ptr=(char*)(st+1); 51 | 52 | st->states = (kiss_fft_cfg *)ptr; 53 | ptr += sizeof(void*) * ndims; 54 | 55 | st->dims = (int*)ptr; 56 | ptr += sizeof(int) * ndims; 57 | 58 | st->tmpbuf = (kiss_fft_cpx*)ptr; 59 | ptr += sizeof(kiss_fft_cpx) * dimprod; 60 | 61 | for (i=0;idims[i] = dims[i]; 64 | kiss_fft_alloc (st->dims[i], inverse_fft, NULL, &len); 65 | st->states[i] = kiss_fft_alloc (st->dims[i], inverse_fft, ptr,&len); 66 | ptr += len; 67 | } 68 | /* 69 | Hi there! 70 | 71 | If you're looking at this particular code, it probably means you've got a brain-dead bounds checker 72 | that thinks the above code overwrites the end of the array. 73 | 74 | It doesn't. 75 | 76 | -- Mark 77 | 78 | P.S. 79 | The below code might give you some warm fuzzies and help convince you. 80 | */ 81 | if ( ptr - (char*)st != (int)memneeded ) { 82 | fprintf(stderr, 83 | "################################################################################\n" 84 | "Internal error! Memory allocation miscalculation\n" 85 | "################################################################################\n" 86 | ); 87 | } 88 | return st; 89 | } 90 | 91 | /* 92 | This works by tackling one dimension at a time. 93 | 94 | In effect, 95 | Each stage starts out by reshaping the matrix into a DixSi 2d matrix. 96 | A Di-sized fft is taken of each column, transposing the matrix as it goes. 97 | 98 | Here's a 3-d example: 99 | Take a 2x3x4 matrix, laid out in memory as a contiguous buffer 100 | [ [ [ a b c d ] [ e f g h ] [ i j k l ] ] 101 | [ [ m n o p ] [ q r s t ] [ u v w x ] ] ] 102 | 103 | Stage 0 ( D=2): treat the buffer as a 2x12 matrix 104 | [ [a b ... k l] 105 | [m n ... w x] ] 106 | 107 | FFT each column with size 2. 108 | Transpose the matrix at the same time using kiss_fft_stride. 109 | 110 | [ [ a+m a-m ] 111 | [ b+n b-n] 112 | ... 113 | [ k+w k-w ] 114 | [ l+x l-x ] ] 115 | 116 | Note fft([x y]) == [x+y x-y] 117 | 118 | Stage 1 ( D=3) treats the buffer (the output of stage D=2) as an 3x8 matrix, 119 | [ [ a+m a-m b+n b-n c+o c-o d+p d-p ] 120 | [ e+q e-q f+r f-r g+s g-s h+t h-t ] 121 | [ i+u i-u j+v j-v k+w k-w l+x l-x ] ] 122 | 123 | And perform FFTs (size=3) on each of the columns as above, transposing 124 | the matrix as it goes. The output of stage 1 is 125 | (Legend: ap = [ a+m e+q i+u ] 126 | am = [ a-m e-q i-u ] ) 127 | 128 | [ [ sum(ap) fft(ap)[0] fft(ap)[1] ] 129 | [ sum(am) fft(am)[0] fft(am)[1] ] 130 | [ sum(bp) fft(bp)[0] fft(bp)[1] ] 131 | [ sum(bm) fft(bm)[0] fft(bm)[1] ] 132 | [ sum(cp) fft(cp)[0] fft(cp)[1] ] 133 | [ sum(cm) fft(cm)[0] fft(cm)[1] ] 134 | [ sum(dp) fft(dp)[0] fft(dp)[1] ] 135 | [ sum(dm) fft(dm)[0] fft(dm)[1] ] ] 136 | 137 | Stage 2 ( D=4) treats this buffer as a 4*6 matrix, 138 | [ [ sum(ap) fft(ap)[0] fft(ap)[1] sum(am) fft(am)[0] fft(am)[1] ] 139 | [ sum(bp) fft(bp)[0] fft(bp)[1] sum(bm) fft(bm)[0] fft(bm)[1] ] 140 | [ sum(cp) fft(cp)[0] fft(cp)[1] sum(cm) fft(cm)[0] fft(cm)[1] ] 141 | [ sum(dp) fft(dp)[0] fft(dp)[1] sum(dm) fft(dm)[0] fft(dm)[1] ] ] 142 | 143 | Then FFTs each column, transposing as it goes. 144 | 145 | The resulting matrix is the 3d FFT of the 2x3x4 input matrix. 146 | 147 | Note as a sanity check that the first element of the final 148 | stage's output (DC term) is 149 | sum( [ sum(ap) sum(bp) sum(cp) sum(dp) ] ) 150 | , i.e. the summation of all 24 input elements. 151 | 152 | */ 153 | void kiss_fftnd(kiss_fftnd_cfg st,const kiss_fft_cpx *fin,kiss_fft_cpx *fout) 154 | { 155 | int i,k; 156 | const kiss_fft_cpx * bufin=fin; 157 | kiss_fft_cpx * bufout; 158 | 159 | /*arrange it so the last bufout == fout*/ 160 | if ( st->ndims & 1 ) { 161 | bufout = fout; 162 | if (fin==fout) { 163 | memcpy( st->tmpbuf, fin, sizeof(kiss_fft_cpx) * st->dimprod ); 164 | bufin = st->tmpbuf; 165 | } 166 | }else 167 | bufout = st->tmpbuf; 168 | 169 | for ( k=0; k < st->ndims; ++k) { 170 | int curdim = st->dims[k]; 171 | int stride = st->dimprod / curdim; 172 | 173 | for ( i=0 ; istates[k], bufin+i , bufout+i*curdim, stride ); 175 | 176 | /*toggle back and forth between the two buffers*/ 177 | if (bufout == st->tmpbuf){ 178 | bufout = fout; 179 | bufin = st->tmpbuf; 180 | }else{ 181 | bufout = st->tmpbuf; 182 | bufin = fout; 183 | } 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /tools/kiss_fftnd.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003-2004, Mark Borgerding. All rights reserved. 3 | * This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | * 5 | * SPDX-License-Identifier: BSD-3-Clause 6 | * See COPYING file for more information. 7 | */ 8 | 9 | #ifndef KISS_FFTND_H 10 | #define KISS_FFTND_H 11 | 12 | #include "kiss_fft.h" 13 | 14 | #ifdef __cplusplus 15 | extern "C" { 16 | #endif 17 | 18 | typedef struct kiss_fftnd_state * kiss_fftnd_cfg; 19 | 20 | kiss_fftnd_cfg kiss_fftnd_alloc(const int *dims,int ndims,int inverse_fft,void*mem,size_t*lenmem); 21 | void kiss_fftnd(kiss_fftnd_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout); 22 | 23 | #ifdef __cplusplus 24 | } 25 | #endif 26 | #endif 27 | -------------------------------------------------------------------------------- /tools/kiss_fftndr.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003-2004, Mark Borgerding. All rights reserved. 3 | * This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | * 5 | * SPDX-License-Identifier: BSD-3-Clause 6 | * See COPYING file for more information. 7 | */ 8 | 9 | #include "kiss_fftndr.h" 10 | #include "_kiss_fft_guts.h" 11 | #define MAX(x,y) ( ( (x)<(y) )?(y):(x) ) 12 | 13 | struct kiss_fftndr_state 14 | { 15 | int dimReal; 16 | int dimOther; 17 | kiss_fftr_cfg cfg_r; 18 | kiss_fftnd_cfg cfg_nd; 19 | void * tmpbuf; 20 | }; 21 | 22 | static int prod(const int *dims, int ndims) 23 | { 24 | int x=1; 25 | while (ndims--) 26 | x *= *dims++; 27 | return x; 28 | } 29 | 30 | kiss_fftndr_cfg kiss_fftndr_alloc(const int *dims,int ndims,int inverse_fft,void*mem,size_t*lenmem) 31 | { 32 | kiss_fftndr_cfg st = NULL; 33 | size_t nr=0 , nd=0,ntmp=0; 34 | int dimReal = dims[ndims-1]; 35 | int dimOther = prod(dims,ndims-1); 36 | size_t memneeded; 37 | 38 | (void)kiss_fftr_alloc(dimReal,inverse_fft,NULL,&nr); 39 | (void)kiss_fftnd_alloc(dims,ndims-1,inverse_fft,NULL,&nd); 40 | ntmp = 41 | MAX( 2*dimOther , dimReal+2) * sizeof(kiss_fft_scalar) // freq buffer for one pass 42 | + dimOther*(dimReal+2) * sizeof(kiss_fft_scalar); // large enough to hold entire input in case of in-place 43 | 44 | memneeded = sizeof( struct kiss_fftndr_state ) + nr + nd + ntmp; 45 | 46 | if (lenmem==NULL) { 47 | st = (kiss_fftndr_cfg) malloc(memneeded); 48 | }else{ 49 | if (*lenmem >= memneeded) 50 | st = (kiss_fftndr_cfg)mem; 51 | *lenmem = memneeded; 52 | } 53 | if (st==NULL) 54 | return NULL; 55 | memset( st , 0 , memneeded); 56 | 57 | st->dimReal = dimReal; 58 | st->dimOther = dimOther; 59 | st->cfg_r = kiss_fftr_alloc( dimReal,inverse_fft,st+1,&nr); 60 | st->cfg_nd = kiss_fftnd_alloc(dims,ndims-1,inverse_fft, ((char*) st->cfg_r)+nr,&nd); 61 | st->tmpbuf = (char*)st->cfg_nd + nd; 62 | 63 | return st; 64 | } 65 | 66 | void kiss_fftndr(kiss_fftndr_cfg st,const kiss_fft_scalar *timedata,kiss_fft_cpx *freqdata) 67 | { 68 | int k1,k2; 69 | int dimReal = st->dimReal; 70 | int dimOther = st->dimOther; 71 | int nrbins = dimReal/2+1; 72 | 73 | kiss_fft_cpx * tmp1 = (kiss_fft_cpx*)st->tmpbuf; 74 | kiss_fft_cpx * tmp2 = tmp1 + MAX(nrbins,dimOther); 75 | 76 | // timedata is N0 x N1 x ... x Nk real 77 | 78 | // take a real chunk of data, fft it and place the output at correct intervals 79 | for (k1=0;k1cfg_r, timedata + k1*dimReal , tmp1 ); // tmp1 now holds nrbins complex points 81 | for (k2=0;k2cfg_nd, tmp2+k2*dimOther, tmp1); // tmp1 now holds dimOther complex points 87 | for (k1=0;k1dimReal; 96 | int dimOther = st->dimOther; 97 | int nrbins = dimReal/2+1; 98 | kiss_fft_cpx * tmp1 = (kiss_fft_cpx*)st->tmpbuf; 99 | kiss_fft_cpx * tmp2 = tmp1 + MAX(nrbins,dimOther); 100 | 101 | for (k2=0;k2cfg_nd, tmp1, tmp2+k2*dimOther); 105 | } 106 | 107 | for (k1=0;k1cfg_r,tmp1,timedata + k1*dimReal); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /tools/kiss_fftndr.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003-2004, Mark Borgerding. All rights reserved. 3 | * This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | * 5 | * SPDX-License-Identifier: BSD-3-Clause 6 | * See COPYING file for more information. 7 | */ 8 | 9 | #ifndef KISS_NDR_H 10 | #define KISS_NDR_H 11 | 12 | #include "kiss_fft.h" 13 | #include "kiss_fftr.h" 14 | #include "kiss_fftnd.h" 15 | 16 | #ifdef __cplusplus 17 | extern "C" { 18 | #endif 19 | 20 | typedef struct kiss_fftndr_state *kiss_fftndr_cfg; 21 | 22 | 23 | kiss_fftndr_cfg kiss_fftndr_alloc(const int *dims,int ndims,int inverse_fft,void*mem,size_t*lenmem); 24 | /* 25 | dims[0] must be even 26 | 27 | If you don't care to allocate space, use mem = lenmem = NULL 28 | */ 29 | 30 | 31 | void kiss_fftndr( 32 | kiss_fftndr_cfg cfg, 33 | const kiss_fft_scalar *timedata, 34 | kiss_fft_cpx *freqdata); 35 | /* 36 | input timedata has dims[0] X dims[1] X ... X dims[ndims-1] scalar points 37 | output freqdata has dims[0] X dims[1] X ... X dims[ndims-1]/2+1 complex points 38 | */ 39 | 40 | void kiss_fftndri( 41 | kiss_fftndr_cfg cfg, 42 | const kiss_fft_cpx *freqdata, 43 | kiss_fft_scalar *timedata); 44 | /* 45 | input and output dimensions are the exact opposite of kiss_fftndr 46 | */ 47 | 48 | 49 | #define kiss_fftndr_free free 50 | 51 | #ifdef __cplusplus 52 | } 53 | #endif 54 | 55 | #endif 56 | -------------------------------------------------------------------------------- /tools/kiss_fftr.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003-2004, Mark Borgerding. All rights reserved. 3 | * This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | * 5 | * SPDX-License-Identifier: BSD-3-Clause 6 | * See COPYING file for more information. 7 | */ 8 | 9 | #include "kiss_fftr.h" 10 | #include "_kiss_fft_guts.h" 11 | 12 | struct kiss_fftr_state{ 13 | kiss_fft_cfg substate; 14 | kiss_fft_cpx * tmpbuf; 15 | kiss_fft_cpx * super_twiddles; 16 | #ifdef USE_SIMD 17 | void * pad; 18 | #endif 19 | }; 20 | 21 | kiss_fftr_cfg kiss_fftr_alloc(int nfft,int inverse_fft,void * mem,size_t * lenmem) 22 | { 23 | int i; 24 | kiss_fftr_cfg st = NULL; 25 | size_t subsize, memneeded; 26 | 27 | if (nfft & 1) { 28 | fprintf(stderr,"Real FFT optimization must be even.\n"); 29 | return NULL; 30 | } 31 | nfft >>= 1; 32 | 33 | kiss_fft_alloc (nfft, inverse_fft, NULL, &subsize); 34 | memneeded = sizeof(struct kiss_fftr_state) + subsize + sizeof(kiss_fft_cpx) * ( nfft * 3 / 2); 35 | 36 | if (lenmem == NULL) { 37 | st = (kiss_fftr_cfg) KISS_FFT_MALLOC (memneeded); 38 | } else { 39 | if (*lenmem >= memneeded) 40 | st = (kiss_fftr_cfg) mem; 41 | *lenmem = memneeded; 42 | } 43 | if (!st) 44 | return NULL; 45 | 46 | st->substate = (kiss_fft_cfg) (st + 1); /*just beyond kiss_fftr_state struct */ 47 | st->tmpbuf = (kiss_fft_cpx *) (((char *) st->substate) + subsize); 48 | st->super_twiddles = st->tmpbuf + nfft; 49 | kiss_fft_alloc(nfft, inverse_fft, st->substate, &subsize); 50 | 51 | for (i = 0; i < nfft/2; ++i) { 52 | double phase = 53 | -3.14159265358979323846264338327 * ((double) (i+1) / nfft + .5); 54 | if (inverse_fft) 55 | phase *= -1; 56 | kf_cexp (st->super_twiddles+i,phase); 57 | } 58 | return st; 59 | } 60 | 61 | void kiss_fftr(kiss_fftr_cfg st,const kiss_fft_scalar *timedata,kiss_fft_cpx *freqdata) 62 | { 63 | /* input buffer timedata is stored row-wise */ 64 | int k,ncfft; 65 | kiss_fft_cpx fpnk,fpk,f1k,f2k,tw,tdc; 66 | 67 | if ( st->substate->inverse) { 68 | fprintf(stderr,"kiss fft usage error: improper alloc\n"); 69 | exit(1); 70 | } 71 | 72 | ncfft = st->substate->nfft; 73 | 74 | /*perform the parallel fft of two real signals packed in real,imag*/ 75 | kiss_fft( st->substate , (const kiss_fft_cpx*)timedata, st->tmpbuf ); 76 | /* The real part of the DC element of the frequency spectrum in st->tmpbuf 77 | * contains the sum of the even-numbered elements of the input time sequence 78 | * The imag part is the sum of the odd-numbered elements 79 | * 80 | * The sum of tdc.r and tdc.i is the sum of the input time sequence. 81 | * yielding DC of input time sequence 82 | * The difference of tdc.r - tdc.i is the sum of the input (dot product) [1,-1,1,-1... 83 | * yielding Nyquist bin of input time sequence 84 | */ 85 | 86 | tdc.r = st->tmpbuf[0].r; 87 | tdc.i = st->tmpbuf[0].i; 88 | C_FIXDIV(tdc,2); 89 | CHECK_OVERFLOW_OP(tdc.r ,+, tdc.i); 90 | CHECK_OVERFLOW_OP(tdc.r ,-, tdc.i); 91 | freqdata[0].r = tdc.r + tdc.i; 92 | freqdata[ncfft].r = tdc.r - tdc.i; 93 | #ifdef USE_SIMD 94 | freqdata[ncfft].i = freqdata[0].i = _mm_set1_ps(0); 95 | #else 96 | freqdata[ncfft].i = freqdata[0].i = 0; 97 | #endif 98 | 99 | for ( k=1;k <= ncfft/2 ; ++k ) { 100 | fpk = st->tmpbuf[k]; 101 | fpnk.r = st->tmpbuf[ncfft-k].r; 102 | fpnk.i = - st->tmpbuf[ncfft-k].i; 103 | C_FIXDIV(fpk,2); 104 | C_FIXDIV(fpnk,2); 105 | 106 | C_ADD( f1k, fpk , fpnk ); 107 | C_SUB( f2k, fpk , fpnk ); 108 | C_MUL( tw , f2k , st->super_twiddles[k-1]); 109 | 110 | freqdata[k].r = HALF_OF(f1k.r + tw.r); 111 | freqdata[k].i = HALF_OF(f1k.i + tw.i); 112 | freqdata[ncfft-k].r = HALF_OF(f1k.r - tw.r); 113 | freqdata[ncfft-k].i = HALF_OF(tw.i - f1k.i); 114 | } 115 | } 116 | 117 | void kiss_fftri(kiss_fftr_cfg st,const kiss_fft_cpx *freqdata,kiss_fft_scalar *timedata) 118 | { 119 | /* input buffer timedata is stored row-wise */ 120 | int k, ncfft; 121 | 122 | if (st->substate->inverse == 0) { 123 | fprintf (stderr, "kiss fft usage error: improper alloc\n"); 124 | exit (1); 125 | } 126 | 127 | ncfft = st->substate->nfft; 128 | 129 | st->tmpbuf[0].r = freqdata[0].r + freqdata[ncfft].r; 130 | st->tmpbuf[0].i = freqdata[0].r - freqdata[ncfft].r; 131 | C_FIXDIV(st->tmpbuf[0],2); 132 | 133 | for (k = 1; k <= ncfft / 2; ++k) { 134 | kiss_fft_cpx fk, fnkc, fek, fok, tmp; 135 | fk = freqdata[k]; 136 | fnkc.r = freqdata[ncfft - k].r; 137 | fnkc.i = -freqdata[ncfft - k].i; 138 | C_FIXDIV( fk , 2 ); 139 | C_FIXDIV( fnkc , 2 ); 140 | 141 | C_ADD (fek, fk, fnkc); 142 | C_SUB (tmp, fk, fnkc); 143 | C_MUL (fok, tmp, st->super_twiddles[k-1]); 144 | C_ADD (st->tmpbuf[k], fek, fok); 145 | C_SUB (st->tmpbuf[ncfft - k], fek, fok); 146 | #ifdef USE_SIMD 147 | st->tmpbuf[ncfft - k].i *= _mm_set1_ps(-1.0); 148 | #else 149 | st->tmpbuf[ncfft - k].i *= -1; 150 | #endif 151 | } 152 | kiss_fft (st->substate, st->tmpbuf, (kiss_fft_cpx *) timedata); 153 | } 154 | -------------------------------------------------------------------------------- /tools/kiss_fftr.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003-2004, Mark Borgerding. All rights reserved. 3 | * This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | * 5 | * SPDX-License-Identifier: BSD-3-Clause 6 | * See COPYING file for more information. 7 | */ 8 | 9 | #ifndef KISS_FTR_H 10 | #define KISS_FTR_H 11 | 12 | #include "kiss_fft.h" 13 | #ifdef __cplusplus 14 | extern "C" { 15 | #endif 16 | 17 | 18 | /* 19 | 20 | Real optimized version can save about 45% cpu time vs. complex fft of a real seq. 21 | 22 | 23 | 24 | */ 25 | 26 | typedef struct kiss_fftr_state *kiss_fftr_cfg; 27 | 28 | 29 | kiss_fftr_cfg kiss_fftr_alloc(int nfft,int inverse_fft,void * mem, size_t * lenmem); 30 | /* 31 | nfft must be even 32 | 33 | If you don't care to allocate space, use mem = lenmem = NULL 34 | */ 35 | 36 | 37 | void kiss_fftr(kiss_fftr_cfg cfg,const kiss_fft_scalar *timedata,kiss_fft_cpx *freqdata); 38 | /* 39 | input timedata has nfft scalar points 40 | output freqdata has nfft/2+1 complex points 41 | */ 42 | 43 | void kiss_fftri(kiss_fftr_cfg cfg,const kiss_fft_cpx *freqdata,kiss_fft_scalar *timedata); 44 | /* 45 | input freqdata has nfft/2+1 complex points 46 | output timedata has nfft scalar points 47 | */ 48 | 49 | #define kiss_fftr_free KISS_FFT_FREE 50 | 51 | #ifdef __cplusplus 52 | } 53 | #endif 54 | #endif 55 | -------------------------------------------------------------------------------- /tools/psdpng.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003-2004, Mark Borgerding. All rights reserved. 3 | * This file is part of KISS FFT - https://github.com/mborgerding/kissfft 4 | * 5 | * SPDX-License-Identifier: BSD-3-Clause 6 | * See COPYING file for more information. 7 | */ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | #include "kiss_fft.h" 17 | #include "kiss_fftr.h" 18 | 19 | int nfft=1024; 20 | FILE * fin=NULL; 21 | FILE * fout=NULL; 22 | 23 | int navg=20; 24 | int remove_dc=0; 25 | int nrows=0; 26 | float * vals=NULL; 27 | int stereo=0; 28 | 29 | static 30 | void config(int argc,char** argv) 31 | { 32 | while (1) { 33 | int c = getopt (argc, argv, "n:r:as"); 34 | if (c == -1) 35 | break; 36 | switch (c) { 37 | case 'n': nfft=(int)atoi(optarg);break; 38 | case 'r': navg=(int)atoi(optarg);break; 39 | case 'a': remove_dc=1;break; 40 | case 's': stereo=1;break; 41 | case '?': 42 | fprintf (stderr, "usage options:\n" 43 | "\t-n d: fft dimension(s) [1024]\n" 44 | "\t-r d: number of rows to average [20]\n" 45 | "\t-a : remove average from each fft buffer\n" 46 | "\t-s : input is stereo, channels will be combined before fft\n" 47 | "16 bit machine format real input is assumed\n" 48 | ); 49 | default: 50 | fprintf (stderr, "bad %c\n", c); 51 | exit (1); 52 | break; 53 | } 54 | } 55 | if ( optind < argc ) { 56 | if (strcmp("-",argv[optind]) !=0) 57 | fin = fopen(argv[optind],"rb"); 58 | ++optind; 59 | } 60 | 61 | if ( optind < argc ) { 62 | if ( strcmp("-",argv[optind]) !=0 ) 63 | fout = fopen(argv[optind],"wb"); 64 | ++optind; 65 | } 66 | if (fin==NULL) 67 | fin=stdin; 68 | if (fout==NULL) 69 | fout=stdout; 70 | } 71 | 72 | #define CHECKNULL(p) if ( (p)==NULL ) do { fprintf(stderr,"CHECKNULL failed @ %s(%d): %s\n",__FILE__,__LINE__,#p );exit(1);} while(0) 73 | 74 | typedef struct 75 | { 76 | png_byte r; 77 | png_byte g; 78 | png_byte b; 79 | } rgb_t; 80 | 81 | static 82 | void val2rgb(float x,rgb_t *p) 83 | { 84 | const double pi = 3.14159265358979; 85 | p->g = (int)(255*sin(x*pi)); 86 | p->r = (int)(255*abs(sin(x*pi*3/2))); 87 | p->b = (int)(255*abs(sin(x*pi*5/2))); 88 | //fprintf(stderr,"%.2f : %d,%d,%d\n",x,(int)p->r,(int)p->g,(int)p->b); 89 | } 90 | 91 | static 92 | void cpx2pixels(rgb_t * res,const float * fbuf,size_t n) 93 | { 94 | size_t i; 95 | float minval,maxval,valrange; 96 | minval=maxval=fbuf[0]; 97 | 98 | for (i = 0; i < n; ++i) { 99 | if (fbuf[i] > maxval) maxval = fbuf[i]; 100 | if (fbuf[i] < minval) minval = fbuf[i]; 101 | } 102 | 103 | fprintf(stderr,"min ==%f,max=%f\n",minval,maxval); 104 | valrange = maxval-minval; 105 | if (valrange == 0) { 106 | fprintf(stderr,"min == max == %f\n",minval); 107 | exit (1); 108 | } 109 | 110 | for (i = 0; i < n; ++i) 111 | val2rgb( (fbuf[i] - minval)/valrange , res+i ); 112 | } 113 | 114 | static 115 | void transform_signal(void) 116 | { 117 | short *inbuf; 118 | kiss_fftr_cfg cfg=NULL; 119 | kiss_fft_scalar *tbuf; 120 | kiss_fft_cpx *fbuf; 121 | float *mag2buf; 122 | int i; 123 | int n; 124 | int avgctr=0; 125 | 126 | int nfreqs=nfft/2+1; 127 | 128 | CHECKNULL( cfg=kiss_fftr_alloc(nfft,0,0,0) ); 129 | CHECKNULL( inbuf=(short*)malloc(sizeof(short)*2*nfft ) ); 130 | CHECKNULL( tbuf=(kiss_fft_scalar*)malloc(sizeof(kiss_fft_scalar)*nfft ) ); 131 | CHECKNULL( fbuf=(kiss_fft_cpx*)malloc(sizeof(kiss_fft_cpx)*nfreqs ) ); 132 | CHECKNULL( mag2buf=(float*)malloc(sizeof(float)*nfreqs ) ); 133 | 134 | memset(mag2buf,0,sizeof(mag2buf)*nfreqs); 135 | 136 | while (1) { 137 | if (stereo) { 138 | n = fread(inbuf,sizeof(short)*2,nfft,fin); 139 | if (n != nfft ) 140 | break; 141 | for (i=0;i