diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 7b37e907..d5c8882f 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,5 +1,7 @@ include (GNUInstallDirs) +add_subdirectory(external/kiss_fft) + set (SFIZZ_SOURCES sfizz/Synth.cpp sfizz/FilePool.cpp @@ -15,6 +17,7 @@ set (SFIZZ_SOURCES sfizz/Logger.cpp sfizz/SfzFilter.cpp sfizz/Curve.cpp + sfizz/Wavetables.cpp sfizz/Effects.cpp sfizz/effects/Nothing.cpp sfizz/effects/Filter.cpp @@ -37,7 +40,7 @@ target_sources(sfizz_static PRIVATE ${SFIZZ_SOURCES} sfizz/sfizz_wrapper.cpp sfi target_include_directories (sfizz_static PUBLIC .) target_include_directories (sfizz_static PUBLIC external) target_link_libraries (sfizz_static PUBLIC absl::strings absl::span) -target_link_libraries (sfizz_static PRIVATE sfizz_parser absl::flat_hash_map Threads::Threads sfizz-sndfile sfizz-pugixml sfizz-spline) +target_link_libraries (sfizz_static PRIVATE sfizz_parser absl::flat_hash_map Threads::Threads sfizz-sndfile sfizz-pugixml sfizz-spline sfizz-kissfft) set_target_properties (sfizz_static PROPERTIES OUTPUT_NAME sfizz PUBLIC_HEADER "sfizz.h;sfizz.hpp") if (WIN32) target_compile_definitions (sfizz_static PRIVATE _USE_MATH_DEFINES) @@ -70,7 +73,7 @@ if (SFIZZ_SHARED) target_sources(sfizz_shared PRIVATE ${SFIZZ_SOURCES} sfizz/sfizz_wrapper.cpp sfizz/sfizz.cpp) target_include_directories (sfizz_shared PRIVATE .) target_include_directories (sfizz_shared PRIVATE external) - target_link_libraries (sfizz_shared PRIVATE absl::strings absl::span sfizz_parser absl::flat_hash_map Threads::Threads sfizz-sndfile sfizz-pugixml sfizz-spline) + target_link_libraries (sfizz_shared PRIVATE absl::strings absl::span sfizz_parser absl::flat_hash_map Threads::Threads sfizz-sndfile sfizz-pugixml sfizz-spline sfizz-kissfft) if (WIN32) target_compile_definitions (sfizz_shared PRIVATE _USE_MATH_DEFINES) endif() diff --git a/src/external/kiss_fft/CMakeLists.txt b/src/external/kiss_fft/CMakeLists.txt new file mode 100644 index 00000000..dc5c22e9 --- /dev/null +++ b/src/external/kiss_fft/CMakeLists.txt @@ -0,0 +1,12 @@ +# This CMake build file is part of sfizz + +cmake_minimum_required(VERSION 3.5) + +project(sfizz-kissfft VERSION "1.3.0" LANGUAGES C) + +add_library(sfizz-kissfft STATIC + kiss_fft.c + tools/kiss_fftr.c) +target_include_directories(sfizz-kissfft + PUBLIC "." + PUBLIC "tools") diff --git a/src/external/kiss_fft/COPYING b/src/external/kiss_fft/COPYING new file mode 100644 index 00000000..2fc6685a --- /dev/null +++ b/src/external/kiss_fft/COPYING @@ -0,0 +1,11 @@ +Copyright (c) 2003-2010 Mark Borgerding + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * 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. + +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. diff --git a/src/external/kiss_fft/_kiss_fft_guts.h b/src/external/kiss_fft/_kiss_fft_guts.h new file mode 100644 index 00000000..ba661444 --- /dev/null +++ b/src/external/kiss_fft/_kiss_fft_guts.h @@ -0,0 +1,164 @@ +/* +Copyright (c) 2003-2010, Mark Borgerding + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * 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. + +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. +*/ + +/* kiss_fft.h + defines kiss_fft_scalar as either short or a float type + and defines + typedef struct { kiss_fft_scalar r; kiss_fft_scalar i; }kiss_fft_cpx; */ +#include "kiss_fft.h" +#include + +#define MAXFACTORS 32 +/* e.g. an fft of length 128 has 4 factors + as far as kissfft is concerned + 4*4*4*2 + */ + +struct kiss_fft_state{ + int nfft; + int inverse; + int factors[2*MAXFACTORS]; + kiss_fft_cpx twiddles[1]; +}; + +/* + Explanation of macros dealing with complex math: + + C_MUL(m,a,b) : m = a*b + C_FIXDIV( c , div ) : if a fixed point impl., c /= div. noop otherwise + C_SUB( res, a,b) : res = a - b + C_SUBFROM( res , a) : res -= a + C_ADDTO( res , a) : res += a + * */ +#ifdef FIXED_POINT +#if (FIXED_POINT==32) +# define FRACBITS 31 +# define SAMPPROD int64_t +#define SAMP_MAX 2147483647 +#else +# define FRACBITS 15 +# define SAMPPROD int32_t +#define SAMP_MAX 32767 +#endif + +#define SAMP_MIN -SAMP_MAX + +#if defined(CHECK_OVERFLOW) +# define CHECK_OVERFLOW_OP(a,op,b) \ + if ( (SAMPPROD)(a) op (SAMPPROD)(b) > SAMP_MAX || (SAMPPROD)(a) op (SAMPPROD)(b) < SAMP_MIN ) { \ + fprintf(stderr,"WARNING:overflow @ " __FILE__ "(%d): (%d " #op" %d) = %ld\n",__LINE__,(a),(b),(SAMPPROD)(a) op (SAMPPROD)(b) ); } +#endif + + +# define smul(a,b) ( (SAMPPROD)(a)*(b) ) +# define sround( x ) (kiss_fft_scalar)( ( (x) + (1<<(FRACBITS-1)) ) >> FRACBITS ) + +# define S_MUL(a,b) sround( smul(a,b) ) + +# define C_MUL(m,a,b) \ + do{ (m).r = sround( smul((a).r,(b).r) - smul((a).i,(b).i) ); \ + (m).i = sround( smul((a).r,(b).i) + smul((a).i,(b).r) ); }while(0) + +# define DIVSCALAR(x,k) \ + (x) = sround( smul( x, SAMP_MAX/k ) ) + +# define C_FIXDIV(c,div) \ + do { DIVSCALAR( (c).r , div); \ + DIVSCALAR( (c).i , div); }while (0) + +# define C_MULBYSCALAR( c, s ) \ + do{ (c).r = sround( smul( (c).r , s ) ) ;\ + (c).i = sround( smul( (c).i , s ) ) ; }while(0) + +#else /* not FIXED_POINT*/ + +# define S_MUL(a,b) ( (a)*(b) ) +#define C_MUL(m,a,b) \ + do{ (m).r = (a).r*(b).r - (a).i*(b).i;\ + (m).i = (a).r*(b).i + (a).i*(b).r; }while(0) +# define C_FIXDIV(c,div) /* NOOP */ +# define C_MULBYSCALAR( c, s ) \ + do{ (c).r *= (s);\ + (c).i *= (s); }while(0) +#endif + +#ifndef CHECK_OVERFLOW_OP +# define CHECK_OVERFLOW_OP(a,op,b) /* noop */ +#endif + +#define C_ADD( res, a,b)\ + do { \ + CHECK_OVERFLOW_OP((a).r,+,(b).r)\ + CHECK_OVERFLOW_OP((a).i,+,(b).i)\ + (res).r=(a).r+(b).r; (res).i=(a).i+(b).i; \ + }while(0) +#define C_SUB( res, a,b)\ + do { \ + CHECK_OVERFLOW_OP((a).r,-,(b).r)\ + CHECK_OVERFLOW_OP((a).i,-,(b).i)\ + (res).r=(a).r-(b).r; (res).i=(a).i-(b).i; \ + }while(0) +#define C_ADDTO( res , a)\ + do { \ + CHECK_OVERFLOW_OP((res).r,+,(a).r)\ + CHECK_OVERFLOW_OP((res).i,+,(a).i)\ + (res).r += (a).r; (res).i += (a).i;\ + }while(0) + +#define C_SUBFROM( res , a)\ + do {\ + CHECK_OVERFLOW_OP((res).r,-,(a).r)\ + CHECK_OVERFLOW_OP((res).i,-,(a).i)\ + (res).r -= (a).r; (res).i -= (a).i; \ + }while(0) + + +#ifdef FIXED_POINT +# define KISS_FFT_COS(phase) floor(.5+SAMP_MAX * cos (phase)) +# define KISS_FFT_SIN(phase) floor(.5+SAMP_MAX * sin (phase)) +# define HALF_OF(x) ((x)>>1) +#elif defined(USE_SIMD) +# define KISS_FFT_COS(phase) _mm_set1_ps( cos(phase) ) +# define KISS_FFT_SIN(phase) _mm_set1_ps( sin(phase) ) +# define HALF_OF(x) ((x)*_mm_set1_ps(.5)) +#else +# define KISS_FFT_COS(phase) (kiss_fft_scalar) cos(phase) +# define KISS_FFT_SIN(phase) (kiss_fft_scalar) sin(phase) +# define HALF_OF(x) ((x)*.5) +#endif + +#define kf_cexp(x,phase) \ + do{ \ + (x)->r = KISS_FFT_COS(phase);\ + (x)->i = KISS_FFT_SIN(phase);\ + }while(0) + + +/* a debugging function */ +#define pcpx(c)\ + fprintf(stderr,"%g + %gi\n",(double)((c)->r),(double)((c)->i) ) + + +#ifdef KISS_FFT_USE_ALLOCA +// define this to allow use of alloca instead of malloc for temporary buffers +// Temporary buffers are used in two case: +// 1. FFT sizes that have "bad" factors. i.e. not 2,3 and 5 +// 2. "in-place" FFTs. Notice the quotes, since kissfft does not really do an in-place transform. +#include +#define KISS_FFT_TMP_ALLOC(nbytes) alloca(nbytes) +#define KISS_FFT_TMP_FREE(ptr) +#else +#define KISS_FFT_TMP_ALLOC(nbytes) KISS_FFT_MALLOC(nbytes) +#define KISS_FFT_TMP_FREE(ptr) KISS_FFT_FREE(ptr) +#endif diff --git a/src/external/kiss_fft/kiss_fft.c b/src/external/kiss_fft/kiss_fft.c new file mode 100644 index 00000000..465d6c97 --- /dev/null +++ b/src/external/kiss_fft/kiss_fft.c @@ -0,0 +1,408 @@ +/* +Copyright (c) 2003-2010, Mark Borgerding + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * 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. + +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. +*/ + + +#include "_kiss_fft_guts.h" +/* The guts header contains all the multiplication and addition macros that are defined for + fixed or floating point complex numbers. It also delares the kf_ internal functions. + */ + +static void kf_bfly2( + kiss_fft_cpx * Fout, + const size_t fstride, + const kiss_fft_cfg st, + int m + ) +{ + kiss_fft_cpx * Fout2; + kiss_fft_cpx * tw1 = st->twiddles; + kiss_fft_cpx t; + Fout2 = Fout + m; + do{ + C_FIXDIV(*Fout,2); C_FIXDIV(*Fout2,2); + + C_MUL (t, *Fout2 , *tw1); + tw1 += fstride; + C_SUB( *Fout2 , *Fout , t ); + C_ADDTO( *Fout , t ); + ++Fout2; + ++Fout; + }while (--m); +} + +static void kf_bfly4( + kiss_fft_cpx * Fout, + const size_t fstride, + const kiss_fft_cfg st, + const size_t m + ) +{ + kiss_fft_cpx *tw1,*tw2,*tw3; + kiss_fft_cpx scratch[6]; + size_t k=m; + const size_t m2=2*m; + const size_t m3=3*m; + + + tw3 = tw2 = tw1 = st->twiddles; + + do { + C_FIXDIV(*Fout,4); C_FIXDIV(Fout[m],4); C_FIXDIV(Fout[m2],4); C_FIXDIV(Fout[m3],4); + + C_MUL(scratch[0],Fout[m] , *tw1 ); + C_MUL(scratch[1],Fout[m2] , *tw2 ); + C_MUL(scratch[2],Fout[m3] , *tw3 ); + + C_SUB( scratch[5] , *Fout, scratch[1] ); + C_ADDTO(*Fout, scratch[1]); + C_ADD( scratch[3] , scratch[0] , scratch[2] ); + C_SUB( scratch[4] , scratch[0] , scratch[2] ); + C_SUB( Fout[m2], *Fout, scratch[3] ); + tw1 += fstride; + tw2 += fstride*2; + tw3 += fstride*3; + C_ADDTO( *Fout , scratch[3] ); + + if(st->inverse) { + Fout[m].r = scratch[5].r - scratch[4].i; + Fout[m].i = scratch[5].i + scratch[4].r; + Fout[m3].r = scratch[5].r + scratch[4].i; + Fout[m3].i = scratch[5].i - scratch[4].r; + }else{ + Fout[m].r = scratch[5].r + scratch[4].i; + Fout[m].i = scratch[5].i - scratch[4].r; + Fout[m3].r = scratch[5].r - scratch[4].i; + Fout[m3].i = scratch[5].i + scratch[4].r; + } + ++Fout; + }while(--k); +} + +static void kf_bfly3( + kiss_fft_cpx * Fout, + const size_t fstride, + const kiss_fft_cfg st, + size_t m + ) +{ + size_t k=m; + const size_t m2 = 2*m; + kiss_fft_cpx *tw1,*tw2; + kiss_fft_cpx scratch[5]; + kiss_fft_cpx epi3; + epi3 = st->twiddles[fstride*m]; + + tw1=tw2=st->twiddles; + + do{ + C_FIXDIV(*Fout,3); C_FIXDIV(Fout[m],3); C_FIXDIV(Fout[m2],3); + + C_MUL(scratch[1],Fout[m] , *tw1); + C_MUL(scratch[2],Fout[m2] , *tw2); + + C_ADD(scratch[3],scratch[1],scratch[2]); + C_SUB(scratch[0],scratch[1],scratch[2]); + tw1 += fstride; + tw2 += fstride*2; + + Fout[m].r = Fout->r - HALF_OF(scratch[3].r); + Fout[m].i = Fout->i - HALF_OF(scratch[3].i); + + C_MULBYSCALAR( scratch[0] , epi3.i ); + + C_ADDTO(*Fout,scratch[3]); + + Fout[m2].r = Fout[m].r + scratch[0].i; + Fout[m2].i = Fout[m].i - scratch[0].r; + + Fout[m].r -= scratch[0].i; + Fout[m].i += scratch[0].r; + + ++Fout; + }while(--k); +} + +static void kf_bfly5( + kiss_fft_cpx * Fout, + const size_t fstride, + const kiss_fft_cfg st, + int m + ) +{ + kiss_fft_cpx *Fout0,*Fout1,*Fout2,*Fout3,*Fout4; + int u; + kiss_fft_cpx scratch[13]; + kiss_fft_cpx * twiddles = st->twiddles; + kiss_fft_cpx *tw; + kiss_fft_cpx ya,yb; + ya = twiddles[fstride*m]; + yb = twiddles[fstride*2*m]; + + Fout0=Fout; + Fout1=Fout0+m; + Fout2=Fout0+2*m; + Fout3=Fout0+3*m; + Fout4=Fout0+4*m; + + tw=st->twiddles; + for ( u=0; ur += scratch[7].r + scratch[8].r; + Fout0->i += scratch[7].i + scratch[8].i; + + scratch[5].r = scratch[0].r + S_MUL(scratch[7].r,ya.r) + S_MUL(scratch[8].r,yb.r); + scratch[5].i = scratch[0].i + S_MUL(scratch[7].i,ya.r) + S_MUL(scratch[8].i,yb.r); + + scratch[6].r = S_MUL(scratch[10].i,ya.i) + S_MUL(scratch[9].i,yb.i); + scratch[6].i = -S_MUL(scratch[10].r,ya.i) - S_MUL(scratch[9].r,yb.i); + + C_SUB(*Fout1,scratch[5],scratch[6]); + C_ADD(*Fout4,scratch[5],scratch[6]); + + scratch[11].r = scratch[0].r + S_MUL(scratch[7].r,yb.r) + S_MUL(scratch[8].r,ya.r); + scratch[11].i = scratch[0].i + S_MUL(scratch[7].i,yb.r) + S_MUL(scratch[8].i,ya.r); + scratch[12].r = - S_MUL(scratch[10].i,yb.i) + S_MUL(scratch[9].i,ya.i); + scratch[12].i = S_MUL(scratch[10].r,yb.i) - S_MUL(scratch[9].r,ya.i); + + C_ADD(*Fout2,scratch[11],scratch[12]); + C_SUB(*Fout3,scratch[11],scratch[12]); + + ++Fout0;++Fout1;++Fout2;++Fout3;++Fout4; + } +} + +/* perform the butterfly for one stage of a mixed radix FFT */ +static void kf_bfly_generic( + kiss_fft_cpx * Fout, + const size_t fstride, + const kiss_fft_cfg st, + int m, + int p + ) +{ + int u,k,q1,q; + kiss_fft_cpx * twiddles = st->twiddles; + kiss_fft_cpx t; + int Norig = st->nfft; + + kiss_fft_cpx * scratch = (kiss_fft_cpx*)KISS_FFT_TMP_ALLOC(sizeof(kiss_fft_cpx)*p); + + for ( u=0; u=Norig) twidx-=Norig; + C_MUL(t,scratch[q] , twiddles[twidx] ); + C_ADDTO( Fout[ k ] ,t); + } + k += m; + } + } + KISS_FFT_TMP_FREE(scratch); +} + +static +void kf_work( + kiss_fft_cpx * Fout, + const kiss_fft_cpx * f, + const size_t fstride, + int in_stride, + int * factors, + const kiss_fft_cfg st + ) +{ + kiss_fft_cpx * Fout_beg=Fout; + const int p=*factors++; /* the radix */ + const int m=*factors++; /* stage's fft length/p */ + const kiss_fft_cpx * Fout_end = Fout + p*m; + +#ifdef _OPENMP + // use openmp extensions at the + // top-level (not recursive) + if (fstride==1 && p<=5) + { + int k; + + // execute the p different work units in different threads +# pragma omp parallel for + for (k=0;k floor_sqrt) + p = n; /* no more factors, skip to end */ + } + n /= p; + *facbuf++ = p; + *facbuf++ = n; + } while (n > 1); +} + +/* + * + * User-callable function to allocate all necessary storage space for the fft. + * + * The return value is a contiguous block of memory, allocated with malloc. As such, + * It can be freed with free(), rather than a kiss_fft-specific function. + * */ +kiss_fft_cfg kiss_fft_alloc(int nfft,int inverse_fft,void * mem,size_t * lenmem ) +{ + kiss_fft_cfg st=NULL; + size_t memneeded = sizeof(struct kiss_fft_state) + + sizeof(kiss_fft_cpx)*(nfft-1); /* twiddle factors*/ + + if ( lenmem==NULL ) { + st = ( kiss_fft_cfg)KISS_FFT_MALLOC( memneeded ); + }else{ + if (mem != NULL && *lenmem >= memneeded) + st = (kiss_fft_cfg)mem; + *lenmem = memneeded; + } + if (st) { + int i; + st->nfft=nfft; + st->inverse = inverse_fft; + + for (i=0;iinverse) + phase *= -1; + kf_cexp(st->twiddles+i, phase ); + } + + kf_factor(nfft,st->factors); + } + return st; +} + + +void kiss_fft_stride(kiss_fft_cfg st,const kiss_fft_cpx *fin,kiss_fft_cpx *fout,int in_stride) +{ + if (fin == fout) { + //NOTE: this is not really an in-place FFT algorithm. + //It just performs an out-of-place FFT into a temp buffer + kiss_fft_cpx * tmpbuf = (kiss_fft_cpx*)KISS_FFT_TMP_ALLOC( sizeof(kiss_fft_cpx)*st->nfft); + kf_work(tmpbuf,fin,1,in_stride, st->factors,st); + memcpy(fout,tmpbuf,sizeof(kiss_fft_cpx)*st->nfft); + KISS_FFT_TMP_FREE(tmpbuf); + }else{ + kf_work( fout, fin, 1,in_stride, st->factors,st ); + } +} + +void kiss_fft(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout) +{ + kiss_fft_stride(cfg,fin,fout,1); +} + + +void kiss_fft_cleanup(void) +{ + // nothing needed any more +} + +int kiss_fft_next_fast_size(int n) +{ + while(1) { + int m=n; + while ( (m%2) == 0 ) m/=2; + while ( (m%3) == 0 ) m/=3; + while ( (m%5) == 0 ) m/=5; + if (m<=1) + break; /* n is completely factorable by twos, threes, and fives */ + n++; + } + return n; +} diff --git a/src/external/kiss_fft/kiss_fft.h b/src/external/kiss_fft/kiss_fft.h new file mode 100644 index 00000000..64c50f4a --- /dev/null +++ b/src/external/kiss_fft/kiss_fft.h @@ -0,0 +1,124 @@ +#ifndef KISS_FFT_H +#define KISS_FFT_H + +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + ATTENTION! + If you would like a : + -- a utility that will handle the caching of fft objects + -- real-only (no imaginary time component ) FFT + -- a multi-dimensional FFT + -- a command-line utility to perform ffts + -- a command-line utility to perform fast-convolution filtering + + Then see kfc.h kiss_fftr.h kiss_fftnd.h fftutil.c kiss_fastfir.c + in the tools/ directory. +*/ + +#ifdef USE_SIMD +# include +# define kiss_fft_scalar __m128 +#define KISS_FFT_MALLOC(nbytes) _mm_malloc(nbytes,16) +#define KISS_FFT_FREE _mm_free +#else +#define KISS_FFT_MALLOC malloc +#define KISS_FFT_FREE free +#endif + + +#ifdef FIXED_POINT +#include +# if (FIXED_POINT == 32) +# define kiss_fft_scalar int32_t +# else +# define kiss_fft_scalar int16_t +# endif +#else +# ifndef kiss_fft_scalar +/* default is float */ +# define kiss_fft_scalar float +# endif +#endif + +typedef struct { + kiss_fft_scalar r; + kiss_fft_scalar i; +}kiss_fft_cpx; + +typedef struct kiss_fft_state* kiss_fft_cfg; + +/* + * kiss_fft_alloc + * + * Initialize a FFT (or IFFT) algorithm's cfg/state buffer. + * + * typical usage: kiss_fft_cfg mycfg=kiss_fft_alloc(1024,0,NULL,NULL); + * + * The return value from fft_alloc is a cfg buffer used internally + * by the fft routine or NULL. + * + * If lenmem is NULL, then kiss_fft_alloc will allocate a cfg buffer using malloc. + * The returned value should be free()d when done to avoid memory leaks. + * + * The state can be placed in a user supplied buffer 'mem': + * If lenmem is not NULL and mem is not NULL and *lenmem is large enough, + * then the function places the cfg in mem and the size used in *lenmem + * and returns mem. + * + * If lenmem is not NULL and ( mem is NULL or *lenmem is not large enough), + * then the function returns NULL and places the minimum cfg + * buffer size in *lenmem. + * */ + +kiss_fft_cfg kiss_fft_alloc(int nfft,int inverse_fft,void * mem,size_t * lenmem); + +/* + * kiss_fft(cfg,in_out_buf) + * + * Perform an FFT on a complex input buffer. + * for a forward FFT, + * fin should be f[0] , f[1] , ... ,f[nfft-1] + * fout will be F[0] , F[1] , ... ,F[nfft-1] + * Note that each element is complex and can be accessed like + f[k].r and f[k].i + * */ +void kiss_fft(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout); + +/* + A more generic version of the above function. It reads its input from every Nth sample. + * */ +void kiss_fft_stride(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout,int fin_stride); + +/* If kiss_fft_alloc allocated a buffer, it is one contiguous + buffer and can be simply free()d when no longer needed*/ +#define kiss_fft_free free + +/* + Cleans up some memory that gets managed internally. Not necessary to call, but it might clean up + your compiler output to call this before you exit. +*/ +void kiss_fft_cleanup(void); + + +/* + * Returns the smallest integer k, such that k>=n and k has only "fast" factors (2,3,5) + */ +int kiss_fft_next_fast_size(int n); + +/* for real ffts, we need an even size */ +#define kiss_fftr_next_fast_size_real(n) \ + (kiss_fft_next_fast_size( ((n)+1)>>1)<<1) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/external/kiss_fft/tools/kiss_fftr.c b/src/external/kiss_fft/tools/kiss_fftr.c new file mode 100644 index 00000000..b8e238b1 --- /dev/null +++ b/src/external/kiss_fft/tools/kiss_fftr.c @@ -0,0 +1,159 @@ +/* +Copyright (c) 2003-2004, Mark Borgerding + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * 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. + +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. +*/ + +#include "kiss_fftr.h" +#include "_kiss_fft_guts.h" + +struct kiss_fftr_state{ + kiss_fft_cfg substate; + kiss_fft_cpx * tmpbuf; + kiss_fft_cpx * super_twiddles; +#ifdef USE_SIMD + void * pad; +#endif +}; + +kiss_fftr_cfg kiss_fftr_alloc(int nfft,int inverse_fft,void * mem,size_t * lenmem) +{ + int i; + kiss_fftr_cfg st = NULL; + size_t subsize, memneeded; + + if (nfft & 1) { + fprintf(stderr,"Real FFT optimization must be even.\n"); + return NULL; + } + nfft >>= 1; + + kiss_fft_alloc (nfft, inverse_fft, NULL, &subsize); + memneeded = sizeof(struct kiss_fftr_state) + subsize + sizeof(kiss_fft_cpx) * ( nfft * 3 / 2); + + if (lenmem == NULL) { + st = (kiss_fftr_cfg) KISS_FFT_MALLOC (memneeded); + } else { + if (*lenmem >= memneeded) + st = (kiss_fftr_cfg) mem; + *lenmem = memneeded; + } + if (!st) + return NULL; + + st->substate = (kiss_fft_cfg) (st + 1); /*just beyond kiss_fftr_state struct */ + st->tmpbuf = (kiss_fft_cpx *) (((char *) st->substate) + subsize); + st->super_twiddles = st->tmpbuf + nfft; + kiss_fft_alloc(nfft, inverse_fft, st->substate, &subsize); + + for (i = 0; i < nfft/2; ++i) { + double phase = + -3.14159265358979323846264338327 * ((double) (i+1) / nfft + .5); + if (inverse_fft) + phase *= -1; + kf_cexp (st->super_twiddles+i,phase); + } + return st; +} + +void kiss_fftr(kiss_fftr_cfg st,const kiss_fft_scalar *timedata,kiss_fft_cpx *freqdata) +{ + /* input buffer timedata is stored row-wise */ + int k,ncfft; + kiss_fft_cpx fpnk,fpk,f1k,f2k,tw,tdc; + + if ( st->substate->inverse) { + fprintf(stderr,"kiss fft usage error: improper alloc\n"); + exit(1); + } + + ncfft = st->substate->nfft; + + /*perform the parallel fft of two real signals packed in real,imag*/ + kiss_fft( st->substate , (const kiss_fft_cpx*)timedata, st->tmpbuf ); + /* The real part of the DC element of the frequency spectrum in st->tmpbuf + * contains the sum of the even-numbered elements of the input time sequence + * The imag part is the sum of the odd-numbered elements + * + * The sum of tdc.r and tdc.i is the sum of the input time sequence. + * yielding DC of input time sequence + * The difference of tdc.r - tdc.i is the sum of the input (dot product) [1,-1,1,-1... + * yielding Nyquist bin of input time sequence + */ + + tdc.r = st->tmpbuf[0].r; + tdc.i = st->tmpbuf[0].i; + C_FIXDIV(tdc,2); + CHECK_OVERFLOW_OP(tdc.r ,+, tdc.i); + CHECK_OVERFLOW_OP(tdc.r ,-, tdc.i); + freqdata[0].r = tdc.r + tdc.i; + freqdata[ncfft].r = tdc.r - tdc.i; +#ifdef USE_SIMD + freqdata[ncfft].i = freqdata[0].i = _mm_set1_ps(0); +#else + freqdata[ncfft].i = freqdata[0].i = 0; +#endif + + for ( k=1;k <= ncfft/2 ; ++k ) { + fpk = st->tmpbuf[k]; + fpnk.r = st->tmpbuf[ncfft-k].r; + fpnk.i = - st->tmpbuf[ncfft-k].i; + C_FIXDIV(fpk,2); + C_FIXDIV(fpnk,2); + + C_ADD( f1k, fpk , fpnk ); + C_SUB( f2k, fpk , fpnk ); + C_MUL( tw , f2k , st->super_twiddles[k-1]); + + freqdata[k].r = HALF_OF(f1k.r + tw.r); + freqdata[k].i = HALF_OF(f1k.i + tw.i); + freqdata[ncfft-k].r = HALF_OF(f1k.r - tw.r); + freqdata[ncfft-k].i = HALF_OF(tw.i - f1k.i); + } +} + +void kiss_fftri(kiss_fftr_cfg st,const kiss_fft_cpx *freqdata,kiss_fft_scalar *timedata) +{ + /* input buffer timedata is stored row-wise */ + int k, ncfft; + + if (st->substate->inverse == 0) { + fprintf (stderr, "kiss fft usage error: improper alloc\n"); + exit (1); + } + + ncfft = st->substate->nfft; + + st->tmpbuf[0].r = freqdata[0].r + freqdata[ncfft].r; + st->tmpbuf[0].i = freqdata[0].r - freqdata[ncfft].r; + C_FIXDIV(st->tmpbuf[0],2); + + for (k = 1; k <= ncfft / 2; ++k) { + kiss_fft_cpx fk, fnkc, fek, fok, tmp; + fk = freqdata[k]; + fnkc.r = freqdata[ncfft - k].r; + fnkc.i = -freqdata[ncfft - k].i; + C_FIXDIV( fk , 2 ); + C_FIXDIV( fnkc , 2 ); + + C_ADD (fek, fk, fnkc); + C_SUB (tmp, fk, fnkc); + C_MUL (fok, tmp, st->super_twiddles[k-1]); + C_ADD (st->tmpbuf[k], fek, fok); + C_SUB (st->tmpbuf[ncfft - k], fek, fok); +#ifdef USE_SIMD + st->tmpbuf[ncfft - k].i *= _mm_set1_ps(-1.0); +#else + st->tmpbuf[ncfft - k].i *= -1; +#endif + } + kiss_fft (st->substate, st->tmpbuf, (kiss_fft_cpx *) timedata); +} diff --git a/src/external/kiss_fft/tools/kiss_fftr.h b/src/external/kiss_fft/tools/kiss_fftr.h new file mode 100644 index 00000000..72e5a577 --- /dev/null +++ b/src/external/kiss_fft/tools/kiss_fftr.h @@ -0,0 +1,46 @@ +#ifndef KISS_FTR_H +#define KISS_FTR_H + +#include "kiss_fft.h" +#ifdef __cplusplus +extern "C" { +#endif + + +/* + + Real optimized version can save about 45% cpu time vs. complex fft of a real seq. + + + + */ + +typedef struct kiss_fftr_state *kiss_fftr_cfg; + + +kiss_fftr_cfg kiss_fftr_alloc(int nfft,int inverse_fft,void * mem, size_t * lenmem); +/* + nfft must be even + + If you don't care to allocate space, use mem = lenmem = NULL +*/ + + +void kiss_fftr(kiss_fftr_cfg cfg,const kiss_fft_scalar *timedata,kiss_fft_cpx *freqdata); +/* + input timedata has nfft scalar points + output freqdata has nfft/2+1 complex points +*/ + +void kiss_fftri(kiss_fftr_cfg cfg,const kiss_fft_cpx *freqdata,kiss_fft_scalar *timedata); +/* + input freqdata has nfft/2+1 complex points + output timedata has nfft scalar points +*/ + +#define kiss_fftr_free free + +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/sfizz/Config.h b/src/sfizz/Config.h index b2a6f8a2..e1bab309 100644 --- a/src/sfizz/Config.h +++ b/src/sfizz/Config.h @@ -73,6 +73,12 @@ namespace config { Limit of how many "fxN" buses are accepted (in SFZv2, maximum is 4) */ constexpr int maxEffectBuses { 256 }; + // Wavetable constants; amplitude values are matched to reference + static constexpr unsigned tableSize = 1024; + static constexpr double amplitudeSine = 0.625; + static constexpr double amplitudeTriangle = 0.625; + static constexpr double amplitudeSaw = 0.515; + static constexpr double amplitudeSquare = 0.515; } // namespace config // Enable or disable SIMD accelerators by default diff --git a/src/sfizz/Resources.h b/src/sfizz/Resources.h index 616e2cac..99bc9dac 100644 --- a/src/sfizz/Resources.h +++ b/src/sfizz/Resources.h @@ -9,9 +9,12 @@ #include "FilterPool.h" #include "EQPool.h" #include "Logger.h" +#include "Wavetables.h" namespace sfz { +class WavetableMulti; + struct Resources { MidiState midiState; @@ -19,5 +22,6 @@ struct Resources FilePool filePool { logger }; FilterPool filterPool { midiState }; EQPool eqPool { midiState }; + WavetablePool wavePool; }; } diff --git a/src/sfizz/Voice.cpp b/src/sfizz/Voice.cpp index e6bb2f94..659f3a80 100644 --- a/src/sfizz/Voice.cpp +++ b/src/sfizz/Voice.cpp @@ -20,6 +20,8 @@ sfz::Voice::Voice(sfz::Resources& resources) { filters.reserve(config::filtersPerVoice); equalizers.reserve(config::eqsPerVoice); + + waveOscillator.init(sampleRate); } void sfz::Voice::startVoice(Region* region, int delay, int number, uint8_t value, sfz::Voice::TriggerType triggerType) noexcept @@ -35,7 +37,28 @@ void sfz::Voice::startVoice(Region* region, int delay, int number, uint8_t value if (delay < 0) delay = 0; - if (!region->isGenerator()) { + if (region->isGenerator()) { + const WavetableMulti* wave = nullptr; + switch (hash(region->sample)) { + default: + case hash("*silence"): + break; + case hash("*sine"): + wave = resources.wavePool.getWaveSin(); + break; + case hash("*triangle"): // fallthrough + case hash("*tri"): + wave = resources.wavePool.getWaveTriangle(); + break; + case hash("*square"): + wave = resources.wavePool.getWaveSquare(); + break; + case hash("*saw"): + wave = resources.wavePool.getWaveSaw(); + break; + } + waveOscillator.setWavetable(wave); + } else { currentPromise = resources.filePool.getFilePromise(region->sample); if (currentPromise == nullptr) { reset(); @@ -226,6 +249,8 @@ void sfz::Voice::registerTempo(int delay, float secondsPerQuarter) noexcept void sfz::Voice::setSampleRate(float sampleRate) noexcept { this->sampleRate = sampleRate; + + waveOscillator.init(sampleRate); } void sfz::Voice::setSamplesPerBlock(int samplesPerBlock) noexcept @@ -472,38 +497,26 @@ void sfz::Voice::fillWithGenerator(AudioSpan buffer) noexcept { const auto leftSpan = buffer.getSpan(0); const auto rightSpan = buffer.getSpan(1); + if (region->sample == "*noise") { absl::c_generate(leftSpan, [&](){ return noiseDist(Random::randomGenerator); }); absl::c_generate(rightSpan, [&](){ return noiseDist(Random::randomGenerator); }); - } - else if (region->sample == "*sine") { - // TODO: wavetables for sine and other generators - if (buffer.getNumFrames() == 0) - return; - - auto jumps = tempSpan1.first(buffer.getNumFrames()); + } else { + // wavetables for sine and other generators + auto frequencies = tempSpan1.first(buffer.getNumFrames()); auto bends = tempSpan2.first(buffer.getNumFrames()); - auto phases = tempSpan2.first(buffer.getNumFrames()); - const float step = baseFrequency * twoPi() / sampleRate; - fill(jumps, step); + fill(frequencies, baseFrequency); if (region->bendStep > 1) pitchBendEnvelope.getQuantizedBlock(bends, bendStepFactor); else pitchBendEnvelope.getBlock(bends); - applyGain(bends, jumps); - jumps[0] += phase; - cumsum(jumps, phases); - phase = phases.back(); + applyGain(bends, frequencies); - sin(phases, leftSpan); + waveOscillator.processModulated(frequencies.data(), leftSpan.data(), buffer.getNumFrames()); copy(leftSpan, rightSpan); - - // Wrap the phase so we don't loose too much precision on longer notes - const auto numTwoPiWraps = static_cast(phase / twoPi()); - phase -= twoPi() * static_cast(numTwoPiWraps); } } diff --git a/src/sfizz/Voice.h b/src/sfizz/Voice.h index d46c23fa..291b1a38 100644 --- a/src/sfizz/Voice.h +++ b/src/sfizz/Voice.h @@ -12,6 +12,7 @@ #include "Region.h" #include "AudioBuffer.h" #include "MidiState.h" +#include "Wavetables.h" #include "Resources.h" #include "AudioSpan.h" #include "LeakDetector.h" @@ -307,6 +308,8 @@ private: MultiplicativeEnvelope volumeEnvelope; float bendStepFactor { centsFactor(1) }; + WavetableOscillator waveOscillator; + Duration dataDuration; Duration amplitudeDuration; Duration panningDuration; diff --git a/src/sfizz/Wavetables.cpp b/src/sfizz/Wavetables.cpp new file mode 100644 index 00000000..1e27853b --- /dev/null +++ b/src/sfizz/Wavetables.cpp @@ -0,0 +1,310 @@ +// SPDX-License-Identifier: BSD-2-Clause + +// This code is part of the sfizz library and is licensed under a BSD 2-clause +// license. You should have receive a LICENSE.md file along with the code. +// If not, contact the sfizz maintainers at https://github.com/sfztools/sfizz + +#include "Wavetables.h" +#include "MathHelpers.h" +#include +#include + +namespace sfz { + +static WavetableMulti silenceMulti = WavetableMulti::createSilence(); + +void WavetableOscillator::init(double sampleRate) +{ + _sampleInterval = 1.0 / sampleRate; + _multi = &silenceMulti; + clear(); +} + +void WavetableOscillator::clear() +{ + _phase = 0.0f; +} + +void WavetableOscillator::setWavetable(const WavetableMulti* wave) +{ + _multi = wave ? wave : &silenceMulti; +} + +void WavetableOscillator::process(float frequency, float* output, unsigned nframes) +{ + float phase = _phase; + float phaseInc = frequency * _sampleInterval; + + const WavetableMulti& multi = *_multi; + unsigned tableSize = multi.tableSize(); + absl::Span table = multi.getTableForFrequency(frequency); + + for (unsigned i = 0; i < nframes; ++i) { + float position = phase * tableSize; + unsigned index = static_cast(position); + float frac = position - index; + output[i] = interpolate(&table[index], frac); + + phase += phaseInc; + phase -= static_cast(phase); + } + + _phase = phase; +} + +void WavetableOscillator::processModulated(const float* frequencies, float* output, unsigned nframes) +{ + float phase = _phase; + float sampleInterval = _sampleInterval; + + const WavetableMulti& multi = *_multi; + unsigned tableSize = multi.tableSize(); + + for (unsigned i = 0; i < nframes; ++i) { + float frequency = frequencies[i]; + float phaseInc = frequency * sampleInterval; + absl::Span table = multi.getTableForFrequency(frequency); + + float position = phase * tableSize; + unsigned index = static_cast(position); + float frac = position - index; + output[i] = interpolate(&table[index], frac); + + phase += phaseInc; + phase -= static_cast(phase); + } + + _phase = phase; +} + +float WavetableOscillator::interpolate(const float* x, float delta) +{ + return x[0] + delta * (x[1] - x[0]); +} + +//------------------------------------------------------------------------------ +void HarmonicProfile::generate( + absl::Span table, double amplitude, double cutoff) const +{ + size_t size = table.size(); + + typedef std::complex cpx; + + // allocate a spectrum of size N/2+1 + // bins are equispaced in frequency, with index N/2 being nyquist + std::unique_ptr spec(new cpx[size / 2 + 1]()); + + kiss_fftr_cfg cfg = kiss_fftr_alloc(size, true, nullptr, nullptr); + if (!cfg) + throw std::bad_alloc(); + + // bins need scaling and phase offset; this IFFT is a sum of cosines + const std::complex k = std::polar(amplitude * 0.5, M_PI / 2); + + // start filling at bin index 1; 1 is fundamental, 0 is DC + for (size_t index = 1; index < size / 2 + 1; ++index) { + if (index * (1.0 / size) > cutoff) + break; + + std::complex harmonic = getHarmonic(index); + spec[index] = k * harmonic; + } + + kiss_fftri(cfg, reinterpret_cast(spec.get()), table.data()); + kiss_fftr_free(cfg); +} + +class SineProfile : public HarmonicProfile { +public: + std::complex getHarmonic(size_t index) const + { + return (index == 1) ? 1.0 : 0.0; + } +}; + +class TriangleProfile : public HarmonicProfile { +public: + std::complex getHarmonic(size_t index) const + { + if ((index & 1) == 0) + return 0.0; + + bool s = (index >> 1) & 1; + return std::polar( + (8 / (M_PI * M_PI)) * (1.0 / (index * index)), + s ? 0.0 : M_PI); + } +}; + +class SawProfile : public HarmonicProfile { +public: + std::complex getHarmonic(size_t index) const + { + if (index < 1) + return 0.0; + + return std::polar( + (2.0 / M_PI) / index, + (index & 1) ? 0.0 : M_PI); + } +}; + +class SquareProfile : public HarmonicProfile { +public: + std::complex getHarmonic(size_t index) const + { + if ((index & 1) == 0) + return 0.0; + + return std::polar((4.0 / M_PI) / index, M_PI); + } +}; + +static const SineProfile sineProfile; +static const TriangleProfile triangleProfile; +static const SawProfile sawProfile; +static const SquareProfile squareProfile; + +const HarmonicProfile& HarmonicProfile::getSine() +{ + return sineProfile; +} + +const HarmonicProfile& HarmonicProfile::getTriangle() +{ + return triangleProfile; +} + +const HarmonicProfile& HarmonicProfile::getSaw() +{ + return sawProfile; +} + +const HarmonicProfile& HarmonicProfile::getSquare() +{ + return squareProfile; +} + +//------------------------------------------------------------------------------ +constexpr unsigned WavetableRange::countOctaves; +constexpr float WavetableRange::frequencyScaleFactor; + +unsigned WavetableRange::getOctaveForFrequency(float f) +{ + int oct = fp_exponent(frequencyScaleFactor * f); + return clamp(oct, 0, countOctaves - 1); +} + +WavetableRange WavetableRange::getRangeForOctave(int o) +{ + WavetableRange range; + + Fraction mant = fp_mantissa(0.0f); + float k = 1.0f / frequencyScaleFactor; + + range.minFrequency = k * fp_from_parts(0, o, 0); + range.maxFrequency = k * fp_from_parts(0, o, mant.den - 1); + + return range; +} + +WavetableRange WavetableRange::getRangeForFrequency(float f) +{ + int oct = getOctaveForFrequency(f); + return getRangeForOctave(oct); +} + +//------------------------------------------------------------------------------ +constexpr unsigned WavetableMulti::_tableExtra; + +WavetableMulti WavetableMulti::createForHarmonicProfile( + const HarmonicProfile& hp, double amplitude, unsigned tableSize, double refSampleRate) +{ + WavetableMulti wm; + constexpr unsigned numTables = WavetableMulti::numTables(); + + wm.allocateStorage(tableSize); + + for (unsigned m = 0; m < numTables; ++m) { + WavetableRange range = WavetableRange::getRangeForOctave(m); + + double freq = range.maxFrequency; + + // A spectrum S of fundamental F has: S[1]=F and S[N/2]=Fs'/2 + // which lets it generate frequency up to Fs'/2=F*N/2. + // Therefore it's desired to cut harmonics at C=0.5*Fs/Fs'=0.5*Fs/(F*N). + double cutoff = (0.5 * refSampleRate / tableSize) / freq; + + float* ptr = const_cast(wm.getTablePointer(m)); + absl::Span table(ptr, tableSize); + + hp.generate(table, amplitude, cutoff); + } + + wm.fillExtra(); + + return wm; +} + +WavetableMulti WavetableMulti::createSilence() +{ + WavetableMulti wm; + wm.allocateStorage(1); + wm.fillExtra(); + return wm; +} + +void WavetableMulti::allocateStorage(unsigned tableSize) +{ + _multiData.resize((tableSize + _tableExtra) * numTables()); + _tableSize = tableSize; +} + +void WavetableMulti::fillExtra() +{ + unsigned tableSize = _tableSize; + constexpr unsigned tableExtra = _tableExtra; + constexpr unsigned numTables = WavetableMulti::numTables(); + + for (unsigned m = 0; m < numTables; ++m) { + float* ptr = const_cast(getTablePointer(m)); + for (unsigned i = 0; i < tableExtra; ++i) + ptr[tableSize + i] = ptr[i % tableSize]; + } +} + + +WavetablePool::WavetablePool() +{ + getWaveSin(); + getWaveTriangle(); + getWaveSaw(); + getWaveSquare(); +} + +const WavetableMulti* WavetablePool::getWaveSin() +{ + static auto wave = WavetableMulti::createForHarmonicProfile( + HarmonicProfile::getSine(), config::amplitudeSine); + return &wave; +} +const WavetableMulti* WavetablePool::getWaveTriangle() +{ + static auto wave = WavetableMulti::createForHarmonicProfile( + HarmonicProfile::getTriangle(), config::amplitudeTriangle); + return &wave; +} +const WavetableMulti* WavetablePool::getWaveSaw() +{ + static auto wave = WavetableMulti::createForHarmonicProfile( + HarmonicProfile::getSaw(), config::amplitudeSaw); + return &wave; +} +const WavetableMulti* WavetablePool::getWaveSquare() +{ + static auto wave = WavetableMulti::createForHarmonicProfile( + HarmonicProfile::getSquare(), config::amplitudeSquare); + return &wave; +} + +} // namespace sfz diff --git a/src/sfizz/Wavetables.h b/src/sfizz/Wavetables.h new file mode 100644 index 00000000..6ec7fe12 --- /dev/null +++ b/src/sfizz/Wavetables.h @@ -0,0 +1,194 @@ +// SPDX-License-Identifier: BSD-2-Clause + +// This code is part of the sfizz library and is licensed under a BSD 2-clause +// license. You should have receive a LICENSE.md file along with the code. +// If not, contact the sfizz maintainers at https://github.com/sfztools/sfizz + +#pragma once +#include "Config.h" +#include "LeakDetector.h" +#include "Buffer.h" +#include +#include +#include + +namespace sfz { + +class WavetableMulti; + +/** + An oscillator based on wavetables + */ +class WavetableOscillator { +public: + /** + Initialize with the given sample rate. + Run it once after instantiating. + */ + void init(double sampleRate); + + /** + Reset the oscillation to the initial phase. + */ + void clear(); + + /** + Set the wavetable to generate with this oscillator. + */ + void setWavetable(const WavetableMulti* wave); + + /** + Compute a cycle of the oscillator, with constant frequency. + */ + void process(float frequency, float* output, unsigned nframes); + + /** + Compute a cycle of the oscillator, with varying frequency. + */ + void processModulated(const float* frequencies, float* output, unsigned nframes); + +private: + /** + Interpolate a value from a part of table, with delta in 0 to 1 excluded. + There are `TableExtra` elements available for reading. + (cf. WavetableMulti) + */ + static float interpolate(const float* x, float delta); + +private: + float _phase = 0.0f; + float _sampleInterval = 0.0f; + const WavetableMulti* _multi = nullptr; + LEAK_DETECTOR(WavetableOscillator); +}; + +/** + A description of the harmonics of a particular wave form + */ +class HarmonicProfile { +public: + virtual ~HarmonicProfile() {} + + static const HarmonicProfile& getSine(); + static const HarmonicProfile& getTriangle(); + static const HarmonicProfile& getSaw(); + static const HarmonicProfile& getSquare(); + + /** + @brief Get the value at the given index of the frequency spectrum. + + The modulus and the argument of the complex number are equal to the + amplitude and the phase of the harmonic component. + */ + virtual std::complex getHarmonic(size_t index) const = 0; + + /** + @brief Generate a period of the waveform and store it in the table. + + Do not generate harmonics above cutoff, which is expressed as Fc/Fs. + */ + void generate(absl::Span table, double amplitude, double cutoff) const; +}; + +/** + A helper to select ranges of a multi-sampled oscillator, according to the + frequency of an oscillator. + + The ranges are identified by octave numbers; not octaves in a musical sense, + but as logarithmic divisions of the frequency range. + */ +class WavetableRange { +public: + float minFrequency = 0; + float maxFrequency = 0; + + static constexpr unsigned countOctaves = 10; + static constexpr float frequencyScaleFactor = 0.05; + + static unsigned getOctaveForFrequency(float f); + static WavetableRange getRangeForOctave(int o); + static WavetableRange getRangeForFrequency(float f); + + // Note: using the frequency factor 0.05, octaves are as follows: + // octave 0: 20 Hz - 40 Hz + // octave 1: 40 Hz - 80 Hz + // octave 2: 80 Hz - 160 Hz + // octave 3: 160 Hz - 320 Hz + // octave 4: 320 Hz - 640 Hz + // octave 5: 640 Hz - 1280 Hz + // octave 6: 1280 Hz - 2560 Hz + // octave 7: 2560 Hz - 5120 Hz + // octave 8: 5120 Hz - 10240 Hz + // octave 9: 10240 Hz - 20480 Hz +}; + +/** + Multisample of a wavetable, which is a collection of FFT-filtered mipmaps + adapted for various playback frequencies. + */ +class WavetableMulti { +public: + // number of tables in the multisample + unsigned tableSize() const { return _tableSize; } + + // number of tables in the multisample + static constexpr unsigned numTables() { return WavetableRange::countOctaves; } + + // get the N-th table in the multisample + absl::Span getTable(unsigned index) const + { + return { getTablePointer(index), _tableSize }; + } + + // get the table which is adequate for a given playback frequency + absl::Span getTableForFrequency(float freq) const + { + return getTable(WavetableRange::getOctaveForFrequency(freq)); + } + + // create a multisample according to a given harmonic profile + // the reference sample rate is the minimum value accepted by the DSP + // system (most defavorable wrt. aliasing) + static WavetableMulti createForHarmonicProfile( + const HarmonicProfile& hp, double amplitude, unsigned tableSize = config::tableSize, double refSampleRate = 44100.0); + + // create the tiniest wavetable with null content for use with oscillators + static WavetableMulti createSilence(); + +private: + // get a pointer to the beginning of the N-th table + const float* getTablePointer(unsigned index) const + { + return _multiData.data() + index * (_tableSize + _tableExtra); + } + + // allocate the internal data for tables of the given size + void allocateStorage(unsigned tableSize); + + // fill extra data at table ends with repetitions of the first samples + void fillExtra(); + + // length of each individual table of the multisample + unsigned _tableSize = 0; + + // number X of extra elements, for safe interpolations up to X-th order. + static constexpr unsigned _tableExtra = 4; + + // internal storage, having `multiSize` rows and `tableSize` columns. + sfz::Buffer _multiData; + LEAK_DETECTOR(WavetableMulti); +}; + +/** + * @brief Holds predefined wavetables. + * + */ +struct WavetablePool { + WavetablePool(); + static const WavetableMulti* getWaveSin(); + static const WavetableMulti* getWaveTriangle(); + static const WavetableMulti* getWaveSaw(); + static const WavetableMulti* getWaveSquare(); +}; + +} // namespace sfz diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index eb28bb5c..598e58ea 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -26,6 +26,7 @@ set(SFIZZ_TEST_SOURCES CurveT.cpp RegionTriggersT.cpp FloatHelpersT.cpp + WavetablesT.cpp ) add_executable(sfizz_tests ${SFIZZ_TEST_SOURCES}) @@ -49,6 +50,11 @@ if(JACK_FOUND AND TARGET Qt5::Widgets) target_include_directories(sfizz_demo_stereo PRIVATE ${JACK_INCLUDE_DIRS}) target_link_libraries(sfizz_demo_stereo PRIVATE sfizz::sfizz Qt5::Widgets ${JACK_LIBRARIES}) set_target_properties(sfizz_demo_stereo PROPERTIES AUTOUIC ON) + + add_executable(sfizz_demo_wavetables DemoWavetables.cpp) + target_include_directories(sfizz_demo_wavetables PRIVATE ${JACK_INCLUDE_DIRS}) + target_link_libraries(sfizz_demo_wavetables PRIVATE sfizz::sfizz Qt5::Widgets ${JACK_LIBRARIES}) + set_target_properties(sfizz_demo_wavetables PROPERTIES AUTOUIC ON) endif() add_executable(eq_apply EQ.cpp) @@ -60,4 +66,7 @@ target_link_libraries(filter_apply PRIVATE sfizz::sfizz) add_executable(sfizz_plot_curve PlotCurve.cpp) target_link_libraries(sfizz_plot_curve PRIVATE sfizz::sfizz) +add_executable(sfizz_plot_wavetables PlotWavetables.cpp) +target_link_libraries(sfizz_plot_wavetables PRIVATE sfizz::sfizz) + file(COPY "." DESTINATION ${CMAKE_BINARY_DIR}/tests) diff --git a/tests/DemoWavetables.cpp b/tests/DemoWavetables.cpp new file mode 100644 index 00000000..aaaea98b --- /dev/null +++ b/tests/DemoWavetables.cpp @@ -0,0 +1,197 @@ +// SPDX-License-Identifier: BSD-2-Clause + +// This code is part of the sfizz library and is licensed under a BSD 2-clause +// license. You should have receive a LICENSE.md file along with the code. +// If not, contact the sfizz maintainers at https://github.com/sfztools/sfizz + +#include "sfizz/Wavetables.h" +#include "sfizz/MathHelpers.h" +#include "ui_DemoWavetables.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/// +struct jack_delete { + void operator()(jack_client_t* x) const noexcept { jack_client_close(x); } +}; + +typedef std::unique_ptr jack_client_u; + +/// +class DemoApp : public QApplication { +public: + DemoApp(int& argc, char** argv); + bool initSound(); + void initWindow(); + +private: + static int processAudio(jack_nframes_t nframes, void* cbdata); + +private: + void valueChangedWave(int value); + void buttonClickedPlaySweep(); + +private: + QMainWindow* fWindow = nullptr; + Ui::DemoWavetablesWindow fUi; + + sfz::WavetableMulti fMulti[4]; + sfz::WavetableOscillator fOsc; + unsigned fWavePlaying = 0; + std::atomic fNewWavePending { -1 }; + std::atomic fStartNewSweep { false }; + + static constexpr float sweepMin = 0.0; + static constexpr float sweepMax = 136.0; + static constexpr float sweepDuration = 3.0; + + float fSweepCurrent = sweepMax; + float fSweepIncrement = 0.0; + + std::unique_ptr fTmpFrequency; + + jack_client_u fClient; + jack_port_t* fPorts[2] = {}; +}; + +DemoApp::DemoApp(int& argc, char** argv) + : QApplication(argc, argv) +{ + setApplicationName(tr("Sfizz Wavetables")); +} + +bool DemoApp::initSound() +{ + jack_client_t* client = jack_client_open( + applicationName().toUtf8().data(), JackNoStartServer, nullptr); + if (!client) { + QMessageBox::critical(nullptr, tr("Error"), tr("Cannot open JACK audio.")); + return false; + } + + double sampleRate = jack_get_sample_rate(client); + fOsc.init(sampleRate); + fSweepIncrement = ((sweepMax - sweepMin) / (sweepDuration * sampleRate)); + + unsigned bufferSize = jack_get_buffer_size(client); + fTmpFrequency.reset(new float[bufferSize]); + + fMulti[0] = sfz::WavetableMulti::createForHarmonicProfile( + sfz::HarmonicProfile::getSine(), 1.0, 2048); + fMulti[1] = sfz::WavetableMulti::createForHarmonicProfile( + sfz::HarmonicProfile::getTriangle(), 1.0, 2048); + fMulti[2] = sfz::WavetableMulti::createForHarmonicProfile( + sfz::HarmonicProfile::getSaw(), 1.0, 2048); + fMulti[3] = sfz::WavetableMulti::createForHarmonicProfile( + sfz::HarmonicProfile::getSquare(), 1.0, 2048); + + fClient.reset(client); + + fPorts[0] = jack_port_register(client, "out_left", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0); + fPorts[1] = jack_port_register(client, "out_right", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0); + + if (!(fPorts[0] && fPorts[1])) { + QMessageBox::critical(nullptr, tr("Error"), tr("Cannot register JACK ports.")); + return false; + } + + jack_set_process_callback(client, &processAudio, this); + + if (jack_activate(client) != 0) { + QMessageBox::critical(nullptr, tr("Error"), tr("Cannot activate JACK client.")); + return false; + } + + return true; +} + +void DemoApp::initWindow() +{ + QMainWindow* window = new QMainWindow; + fWindow = window; + fUi.setupUi(window); + window->setWindowTitle(applicationDisplayName()); + + fUi.valWave->addItem(tr("1 - Sine")); + fUi.valWave->addItem(tr("2 - Triangle")); + fUi.valWave->addItem(tr("3 - Saw")); + fUi.valWave->addItem(tr("4 - Square")); + + connect( + fUi.valWave, QOverload::of(&QComboBox::currentIndexChanged), + this, [this](int index) { valueChangedWave(index); }); + + connect( + fUi.btnPlaySweep, &QPushButton::clicked, + this, [this]() { buttonClickedPlaySweep(); }); + + window->adjustSize(); + window->setFixedSize(window->size()); + + window->show(); +} + +int DemoApp::processAudio(jack_nframes_t nframes, void* cbdata) +{ + DemoApp* self = reinterpret_cast(cbdata); + + sfz::WavetableOscillator& osc = self->fOsc; + + int newWave = self->fNewWavePending.exchange(-1); + if (newWave != -1) + self->fWavePlaying = newWave; + + osc.setWavetable(&self->fMulti[self->fWavePlaying]); + + float* left = reinterpret_cast( + jack_port_get_buffer(self->fPorts[0], nframes)); + float* right = reinterpret_cast( + jack_port_get_buffer(self->fPorts[1], nframes)); + + // sweep the pitch of the oscillator + float* frequency = self->fTmpFrequency.get(); + float sweepCurrent = self->fSweepCurrent; + if (self->fStartNewSweep.exchange(false)) + sweepCurrent = sweepMin; + float sweepIncrement = self->fSweepIncrement; + for (unsigned i = 0; i < nframes; ++i) { + frequency[i] = 440.0f * std::pow(2.0f, (sweepCurrent - 69.0f) * (1.0f / 12.0f)); + sweepCurrent = std::min(sweepMax, sweepCurrent + sweepIncrement); + } + self->fSweepCurrent = sweepCurrent; + + // compute oscillator + osc.processModulated(frequency, left, nframes); + std::memcpy(right, left, nframes * sizeof(float)); + + return 0; +} + +void DemoApp::valueChangedWave(int value) +{ + fNewWavePending.store(value); +} + +void DemoApp::buttonClickedPlaySweep() +{ + fStartNewSweep.store(true); +} + +int main(int argc, char* argv[]) +{ + DemoApp app(argc, argv); + + if (!app.initSound()) + return 1; + + app.initWindow(); + + return app.exec(); +} diff --git a/tests/DemoWavetables.ui b/tests/DemoWavetables.ui new file mode 100644 index 00000000..6a5f5def --- /dev/null +++ b/tests/DemoWavetables.ui @@ -0,0 +1,50 @@ + + + DemoWavetablesWindow + + + + 0 + 0 + 170 + 103 + + + + + + + + Select wave + + + + + + + Play sweep + + + + + + + + + + + 64 + 64 + + + + + + + + + + + + + diff --git a/tests/PlotWavetables.cpp b/tests/PlotWavetables.cpp new file mode 100644 index 00000000..1ce71f49 --- /dev/null +++ b/tests/PlotWavetables.cpp @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: BSD-2-Clause + +// This code is part of the sfizz library and is licensed under a BSD 2-clause +// license. You should have receive a LICENSE.md file along with the code. +// If not, contact the sfizz maintainers at https://github.com/sfztools/sfizz + +#include "sfizz/Wavetables.h" +#include +#include +#include + +static void usage() +{ + std::cerr << "Usage: sfizz_plot_wavetables [-w wave] [-a amplitude] [-c cutoff] [-m]\n"; +} + +int main(int argc, char* argv[]) +{ + absl::string_view waveName; + double amplitude = 1.0; + double cutoff = 0.5; + bool generateMulti = false; + + for (int i = 1; i < argc; ++i) { + absl::string_view arg = argv[i]; + + if (arg == "-w") { + if (i + 1 >= argc) + return usage(), 1; + waveName = argv[++i]; + } else if (arg == "-a") { + if (i + 1 >= argc || !absl::SimpleAtod(argv[++i], &litude)) + return usage(), 1; + } else if (arg == "-c") { + if (i + 1 >= argc || !absl::SimpleAtod(argv[++i], &cutoff)) + return usage(), 1; + } else if (arg == "-m") + generateMulti = true; + else + return usage(), 1; + } + + if (waveName.empty()) + waveName = "saw"; + + const sfz::HarmonicProfile* hp = nullptr; + if (waveName == "sine") + hp = &sfz::HarmonicProfile::getSine(); + else if (waveName == "square") + hp = &sfz::HarmonicProfile::getSquare(); + else if (waveName == "triangle") + hp = &sfz::HarmonicProfile::getTriangle(); + else if (waveName == "saw") + hp = &sfz::HarmonicProfile::getSaw(); + else { + std::cerr << "Unknown wave: " << waveName << '\n'; + return 1; + } + + constexpr size_t tableSize = 2048; + float table[tableSize]; + + if (!generateMulti) { + hp->generate(table, amplitude, cutoff); + + for (size_t i = 0; i < tableSize; ++i) + std::cout << (i * (1.0 / tableSize)) << ' ' << table[i] << '\n'; + } else { + sfz::WavetableMulti multi = sfz::WavetableMulti::createForHarmonicProfile( + *hp, 1.0, tableSize); + unsigned numTables = multi.numTables(); + + if (true) { + // print all tables one after another + for (unsigned m = 0; m < numTables; ++m) { + absl::Span table = multi.getTable(m); + for (size_t i = 0; i < tableSize; ++i) { + std::cout << ((i + m * tableSize) * (1.0 / tableSize)) + << ' ' << table[i] << '\n'; + } + } + } else { + // print all tables separately + for (size_t i = 0; i < tableSize; ++i) { + std::cout << (i * (1.0 / tableSize)); + for (unsigned m = 0; m < numTables; ++m) { + absl::Span table = multi.getTable(m); + std::cout << ' ' << table[i]; + } + std::cout << '\n'; + } + } + } + + return 0; +} diff --git a/tests/WavetablesT.cpp b/tests/WavetablesT.cpp new file mode 100644 index 00000000..51231614 --- /dev/null +++ b/tests/WavetablesT.cpp @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: BSD-2-Clause + +// This code is part of the sfizz library and is licensed under a BSD 2-clause +// license. You should have receive a LICENSE.md file along with the code. +// If not, contact the sfizz maintainers at https://github.com/sfztools/sfizz + +#include "sfizz/Wavetables.h" +#include "sfizz/MathHelpers.h" +#include "catch2/catch.hpp" +#include + +TEST_CASE("[Wavetables] Frequency ranges") +{ + int cur_oct = std::numeric_limits::min(); + int min_oct = std::numeric_limits::max(); + int max_oct = std::numeric_limits::min(); + + for (int note = 0; note < 128; ++note) { + double f = midiNoteFrequency(note); + + int oct = sfz::WavetableRange::getOctaveForFrequency(f); + + REQUIRE(oct >= 0); + REQUIRE(oct < sfz::WavetableRange::countOctaves); + + REQUIRE(oct >= cur_oct); + cur_oct = oct; + + min_oct = std::min(min_oct, oct); + max_oct = std::max(max_oct, oct); + + sfz::WavetableRange range = sfz::WavetableRange::getRangeForOctave(oct); + REQUIRE((f >= range.minFrequency || oct == 0)); + REQUIRE((f <= range.maxFrequency || oct == sfz::WavetableRange::countOctaves - 1)); + } + + // check ranges to be decently adjusted to the MIDI frequency range + REQUIRE(min_oct == 0); + REQUIRE(max_oct == sfz::WavetableRange::countOctaves - 1); +}