Merge pull request #61 from jpcima/wavetable

Add the wavetable oscillator
This commit is contained in:
JP Cimalando 2020-03-16 00:55:16 +01:00 committed by GitHub
commit 31601bc1ff
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
19 changed files with 1871 additions and 22 deletions

View file

@ -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()

12
src/external/kiss_fft/CMakeLists.txt vendored Normal file
View file

@ -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")

11
src/external/kiss_fft/COPYING vendored Normal file
View file

@ -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.

164
src/external/kiss_fft/_kiss_fft_guts.h vendored Normal file
View file

@ -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 <limits.h>
#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 <alloca.h>
#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

408
src/external/kiss_fft/kiss_fft.c vendored Normal file
View file

@ -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; u<m; ++u ) {
C_FIXDIV( *Fout0,5); C_FIXDIV( *Fout1,5); C_FIXDIV( *Fout2,5); C_FIXDIV( *Fout3,5); C_FIXDIV( *Fout4,5);
scratch[0] = *Fout0;
C_MUL(scratch[1] ,*Fout1, tw[u*fstride]);
C_MUL(scratch[2] ,*Fout2, tw[2*u*fstride]);
C_MUL(scratch[3] ,*Fout3, tw[3*u*fstride]);
C_MUL(scratch[4] ,*Fout4, tw[4*u*fstride]);
C_ADD( scratch[7],scratch[1],scratch[4]);
C_SUB( scratch[10],scratch[1],scratch[4]);
C_ADD( scratch[8],scratch[2],scratch[3]);
C_SUB( scratch[9],scratch[2],scratch[3]);
Fout0->r += 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<m; ++u ) {
k=u;
for ( q1=0 ; q1<p ; ++q1 ) {
scratch[q1] = Fout[ k ];
C_FIXDIV(scratch[q1],p);
k += m;
}
k=u;
for ( q1=0 ; q1<p ; ++q1 ) {
int twidx=0;
Fout[ k ] = scratch[0];
for (q=1;q<p;++q ) {
twidx += fstride * k;
if (twidx>=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<p;++k)
kf_work( Fout +k*m, f+ fstride*in_stride*k,fstride*p,in_stride,factors,st);
// all threads have joined by this point
switch (p) {
case 2: kf_bfly2(Fout,fstride,st,m); break;
case 3: kf_bfly3(Fout,fstride,st,m); break;
case 4: kf_bfly4(Fout,fstride,st,m); break;
case 5: kf_bfly5(Fout,fstride,st,m); break;
default: kf_bfly_generic(Fout,fstride,st,m,p); break;
}
return;
}
#endif
if (m==1) {
do{
*Fout = *f;
f += fstride*in_stride;
}while(++Fout != Fout_end );
}else{
do{
// recursive call:
// DFT of size m*p performed by doing
// p instances of smaller DFTs of size m,
// each one takes a decimated version of the input
kf_work( Fout , f, fstride*p, in_stride, factors,st);
f += fstride*in_stride;
}while( (Fout += m) != Fout_end );
}
Fout=Fout_beg;
// recombine the p smaller DFTs
switch (p) {
case 2: kf_bfly2(Fout,fstride,st,m); break;
case 3: kf_bfly3(Fout,fstride,st,m); break;
case 4: kf_bfly4(Fout,fstride,st,m); break;
case 5: kf_bfly5(Fout,fstride,st,m); break;
default: kf_bfly_generic(Fout,fstride,st,m,p); break;
}
}
/* facbuf is populated by p1,m1,p2,m2, ...
where
p[i] * m[i] = m[i-1]
m0 = n */
static
void kf_factor(int n,int * facbuf)
{
int p=4;
double floor_sqrt;
floor_sqrt = floor( sqrt((double)n) );
/*factor out powers of 4, powers of 2, then any remaining primes */
do {
while (n % p) {
switch (p) {
case 4: p = 2; break;
case 2: p = 3; break;
default: p += 2; break;
}
if (p > 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;i<nfft;++i) {
const double pi=3.141592653589793238462643383279502884197169399375105820974944;
double phase = -2*pi*i / nfft;
if (st->inverse)
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;
}

124
src/external/kiss_fft/kiss_fft.h vendored Normal file
View file

@ -0,0 +1,124 @@
#ifndef KISS_FFT_H
#define KISS_FFT_H
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#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 <xmmintrin.h>
# 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 <sys/types.h>
# 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

159
src/external/kiss_fft/tools/kiss_fftr.c vendored Normal file
View file

@ -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);
}

46
src/external/kiss_fft/tools/kiss_fftr.h vendored Normal file
View file

@ -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

View file

@ -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

View file

@ -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;
};
}

View file

@ -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<float> 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<float>() / sampleRate;
fill<float>(jumps, step);
fill<float>(frequencies, baseFrequency);
if (region->bendStep > 1)
pitchBendEnvelope.getQuantizedBlock(bends, bendStepFactor);
else
pitchBendEnvelope.getBlock(bends);
applyGain<float>(bends, jumps);
jumps[0] += phase;
cumsum<float>(jumps, phases);
phase = phases.back();
applyGain<float>(bends, frequencies);
sin<float>(phases, leftSpan);
waveOscillator.processModulated(frequencies.data(), leftSpan.data(), buffer.getNumFrames());
copy<float>(leftSpan, rightSpan);
// Wrap the phase so we don't loose too much precision on longer notes
const auto numTwoPiWraps = static_cast<int>(phase / twoPi<float>());
phase -= twoPi<float>() * static_cast<float>(numTwoPiWraps);
}
}

View file

@ -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<float> volumeEnvelope;
float bendStepFactor { centsFactor(1) };
WavetableOscillator waveOscillator;
Duration dataDuration;
Duration amplitudeDuration;
Duration panningDuration;

310
src/sfizz/Wavetables.cpp Normal file
View file

@ -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 <kiss_fftr.h>
#include <memory>
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<const float> table = multi.getTableForFrequency(frequency);
for (unsigned i = 0; i < nframes; ++i) {
float position = phase * tableSize;
unsigned index = static_cast<unsigned>(position);
float frac = position - index;
output[i] = interpolate(&table[index], frac);
phase += phaseInc;
phase -= static_cast<int>(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<const float> table = multi.getTableForFrequency(frequency);
float position = phase * tableSize;
unsigned index = static_cast<unsigned>(position);
float frac = position - index;
output[i] = interpolate(&table[index], frac);
phase += phaseInc;
phase -= static_cast<int>(phase);
}
_phase = phase;
}
float WavetableOscillator::interpolate(const float* x, float delta)
{
return x[0] + delta * (x[1] - x[0]);
}
//------------------------------------------------------------------------------
void HarmonicProfile::generate(
absl::Span<float> table, double amplitude, double cutoff) const
{
size_t size = table.size();
typedef std::complex<kiss_fft_scalar> cpx;
// allocate a spectrum of size N/2+1
// bins are equispaced in frequency, with index N/2 being nyquist
std::unique_ptr<cpx[]> 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<double> 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<double> harmonic = getHarmonic(index);
spec[index] = k * harmonic;
}
kiss_fftri(cfg, reinterpret_cast<kiss_fft_cpx*>(spec.get()), table.data());
kiss_fftr_free(cfg);
}
class SineProfile : public HarmonicProfile {
public:
std::complex<double> getHarmonic(size_t index) const
{
return (index == 1) ? 1.0 : 0.0;
}
};
class TriangleProfile : public HarmonicProfile {
public:
std::complex<double> getHarmonic(size_t index) const
{
if ((index & 1) == 0)
return 0.0;
bool s = (index >> 1) & 1;
return std::polar<double>(
(8 / (M_PI * M_PI)) * (1.0 / (index * index)),
s ? 0.0 : M_PI);
}
};
class SawProfile : public HarmonicProfile {
public:
std::complex<double> 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<double> 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<int>(oct, 0, countOctaves - 1);
}
WavetableRange WavetableRange::getRangeForOctave(int o)
{
WavetableRange range;
Fraction<uint64_t> mant = fp_mantissa(0.0f);
float k = 1.0f / frequencyScaleFactor;
range.minFrequency = k * fp_from_parts<float>(0, o, 0);
range.maxFrequency = k * fp_from_parts<float>(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<float*>(wm.getTablePointer(m));
absl::Span<float> 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<float*>(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

194
src/sfizz/Wavetables.h Normal file
View file

@ -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 <absl/types/span.h>
#include <memory>
#include <complex>
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<double> 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<float> 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<const float> getTable(unsigned index) const
{
return { getTablePointer(index), _tableSize };
}
// get the table which is adequate for a given playback frequency
absl::Span<const float> 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<float> _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

View file

@ -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)

197
tests/DemoWavetables.cpp Normal file
View file

@ -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 <QApplication>
#include <QMainWindow>
#include <QMessageBox>
#include <QButtonGroup>
#include <QDebug>
#include <jack/jack.h>
#include <atomic>
#include <memory>
#include <cstring>
///
struct jack_delete {
void operator()(jack_client_t* x) const noexcept { jack_client_close(x); }
};
typedef std::unique_ptr<jack_client_t, jack_delete> 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<int> fNewWavePending { -1 };
std::atomic<bool> 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<float[]> 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<int>::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<DemoApp*>(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<float*>(
jack_port_get_buffer(self->fPorts[0], nframes));
float* right = reinterpret_cast<float*>(
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();
}

50
tests/DemoWavetables.ui Normal file
View file

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>DemoWavetablesWindow</class>
<widget class="QMainWindow" name="DemoWavetablesWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>170</width>
<height>103</height>
</rect>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>Select wave</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLabel" name="label_2">
<property name="text">
<string>Play sweep</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QComboBox" name="valWave"/>
</item>
<item row="1" column="1">
<widget class="QPushButton" name="btnPlaySweep">
<property name="minimumSize">
<size>
<width>64</width>
<height>64</height>
</size>
</property>
<property name="icon">
<iconset theme="media-playback-start"/>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>

96
tests/PlotWavetables.cpp Normal file
View file

@ -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 <absl/strings/numbers.h>
#include <absl/strings/string_view.h>
#include <iostream>
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], &amplitude))
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<const float> 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<const float> table = multi.getTable(m);
std::cout << ' ' << table[i];
}
std::cout << '\n';
}
}
}
return 0;
}

40
tests/WavetablesT.cpp Normal file
View file

@ -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 <algorithm>
TEST_CASE("[Wavetables] Frequency ranges")
{
int cur_oct = std::numeric_limits<int>::min();
int min_oct = std::numeric_limits<int>::max();
int max_oct = std::numeric_limits<int>::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);
}