├── libs ├── .DS_Store ├── Gist │ └── src │ │ ├── .DS_Store │ │ ├── core │ │ ├── CoreTimeDomainFeatures.h │ │ ├── CoreFrequencyDomainFeatures.h │ │ ├── CoreTimeDomainFeatures.cpp │ │ └── CoreFrequencyDomainFeatures.cpp │ │ ├── mfcc │ │ ├── MFCC.h │ │ └── MFCC.cpp │ │ ├── pitch │ │ ├── Yin.h │ │ └── Yin.cpp │ │ ├── onset-detection-functions │ │ ├── OnsetDetectionFunction.h │ │ └── OnsetDetectionFunction.cpp │ │ └── Gist.h ├── kiss_fft130 │ ├── COPYING │ ├── kiss_fft.h │ ├── README │ ├── _kiss_fft_guts.h │ ├── kissfft.hh │ └── kiss_fft.c └── Stark-Plumbley │ ├── ChordDetector.h │ ├── Chromagram.h │ ├── ChordDetector.cpp │ ├── Chromagram.cpp │ └── LICENSE.txt ├── ofxaddons_thumbnail.png ├── example └── src │ ├── main.cpp │ ├── ofApp.h │ └── ofApp.cpp ├── README.md └── src ├── ofxGist.h └── ofxGist.cpp /libs/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/borg/ofxGist/HEAD/libs/.DS_Store -------------------------------------------------------------------------------- /libs/Gist/src/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/borg/ofxGist/HEAD/libs/Gist/src/.DS_Store -------------------------------------------------------------------------------- /ofxaddons_thumbnail.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/borg/ofxGist/HEAD/ofxaddons_thumbnail.png -------------------------------------------------------------------------------- /example/src/main.cpp: -------------------------------------------------------------------------------- 1 | #include "ofMain.h" 2 | #include "ofApp.h" 3 | 4 | //======================================================================== 5 | int main( ){ 6 | ofSetupOpenGL(1024,768,OF_WINDOW); // <-------- setup the GL context 7 | 8 | // this kicks off the running of my app 9 | // can be OF_WINDOW or OF_FULLSCREEN 10 | // pass in width and height too: 11 | ofRunApp(new ofApp()); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ofxGist 2 | openFrameworks implementation of GIST real-time sound analysis library 3 | 4 | ![ofxGist](ofxaddons_thumbnail.png) 5 | 6 | An openFrameworks implementation of Adam Stark's real-time sound analysis library Gist 7 | 8 | https://github.com/adamstark/Gist 9 | 10 | 11 | NOTE UPDATE May 25, 2015 12 | 13 | ofxGist has no dependencies, but the example makes use of a modified 14 | [ofxOpenALSoundPlayer](https://github.com/borg/ofxOpenALSoundPlayer). It is included only as a way of getting the soundbuffer out of loaded sound. There are other ways you can do that. This player includes a version of kissFFT. You can remove the one included in Gist. 15 | 16 | 17 | It is also using a slightly modified [ofxHistoryPlot](https://github.com/local-projects/ofxHistoryPlot) from @armadillu to add a dynamic getVariable method to be able to plot based on gist feature list 18 | 19 | 20 | by 21 | /Andreas Borg 22 | 23 | 24 | From [Gist page](http://www.adamstark.co.uk/gist/) 25 | 26 | Gist 27 | 28 | Gist is a C++ audio analysis library intended for use in real-time applications. It contains a range of audio analysis algorithms, including: 29 | 30 | * Simple Time Domain Features (e.g. RMS, Zero Crossing Rate) 31 | * Simple Frequency Domain Features (e.g. Spectral Centroid, Spectral Flatness) 32 | * Onset Detection Functions (e.g. Energy Difference, Complex Spectral Difference) 33 | * Pitch Detection 34 | * Mel-frequency Representations (e.g. Mel-frequency Spectrum, MFCCs) 35 | 36 | -------------------------------------------------------------------------------- /libs/kiss_fft130/COPYING: -------------------------------------------------------------------------------- 1 | Copyright (c) 2003-2010 Mark Borgerding 2 | 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 9 | * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. 10 | 11 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 12 | -------------------------------------------------------------------------------- /example/src/ofApp.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "ofMain.h" 4 | 5 | //This is included only as a way of getting buffer out of loaded sound. 6 | //There are many other ways you can do that. 7 | //This player includes a version of kissFFT. You can remove the one included in Gist. 8 | //https://github.com/borg/ofxOpenALSoundPlayer 9 | #include "ofxOpenALSoundPlayer.h" 10 | 11 | 12 | //Slightly modified to add a dynamic getVariable method to be able to plot based on 13 | //gist feature list 14 | //https://github.com/local-projects/ofxHistoryPlot 15 | #include "ofxHistoryPlot.h" 16 | #include "ofxGist.h" 17 | 18 | class ofApp : public ofBaseApp{ 19 | 20 | public: 21 | void setup(); 22 | void update(); 23 | void draw(); 24 | 25 | void keyPressed(int key); 26 | void keyReleased(int key); 27 | void mouseMoved(int x, int y ); 28 | void mouseDragged(int x, int y, int button); 29 | void mousePressed(int x, int y, int button); 30 | void mouseReleased(int x, int y, int button); 31 | void windowResized(int w, int h); 32 | void dragEvent(ofDragInfo dragInfo); 33 | void gotMessage(ofMessage msg); 34 | 35 | ofSoundStream soundStream; 36 | ofxOpenALSoundPlayer player; 37 | void processAudio(float * input, int bufferSize, int nChannels); 38 | 39 | void audioIn(float * input, int bufferSize, int nChannels); 40 | 41 | vectorfftSmoothed; 42 | 43 | vectormfccSmoothed; 44 | float mfccMax; 45 | 46 | 47 | int bufferSize; 48 | int sampleRate; 49 | bool useMic; 50 | 51 | bool isPaused; 52 | 53 | void clear(); 54 | void loadSong(string str); 55 | 56 | 57 | vectorplots; 58 | mapplotMap; 59 | 60 | ofxHistoryPlot* addGraph(string varName,float max,ofColor color); 61 | 62 | 63 | ofxGist gist; 64 | void onNoteOn(GistEvent &e); 65 | void onNoteOff(GistEvent &e); 66 | 67 | int noteOnRadius; 68 | 69 | 70 | bool showMFCC; 71 | vectormfccPlots; 72 | 73 | }; 74 | -------------------------------------------------------------------------------- /libs/Gist/src/core/CoreTimeDomainFeatures.h: -------------------------------------------------------------------------------- 1 | //======================================================================= 2 | /** @file CoreTimeDomainFeatures.h 3 | * @brief Implementations of common time domain audio features 4 | * @author Adam Stark 5 | * @copyright Copyright (C) 2013 Adam Stark 6 | * 7 | * This file is part of the 'Gist' audio analysis library 8 | * 9 | * This program is free software: you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as published by 11 | * the Free Software Foundation, either version 3 of the License, or 12 | * (at your option) any later version. 13 | * 14 | * This program is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | * GNU General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public License 20 | * along with this program. If not, see . 21 | */ 22 | //======================================================================= 23 | 24 | #ifndef __GIST__CORETIMEDOMAINFEATURES__ 25 | #define __GIST__CORETIMEDOMAINFEATURES__ 26 | 27 | #include 28 | #include 29 | 30 | /** template class for calculating common time domain 31 | * audio features. Instantiations of the class should be 32 | * of either 'float' or 'double' types and no others */ 33 | template 34 | class CoreTimeDomainFeatures 35 | { 36 | public: 37 | 38 | /** constructor */ 39 | CoreTimeDomainFeatures(); 40 | 41 | //=========================================================== 42 | /** calculates the Root Mean Square (RMS) of an audio buffer 43 | * in vector format 44 | * @param buffer a time domain buffer containing audio samples 45 | * @returns the RMS value 46 | */ 47 | T rootMeanSquare(std::vector buffer); 48 | 49 | //=========================================================== 50 | /** calculates the peak energy (max absolute value) in a time 51 | * domain audio signal buffer in vector format 52 | * @param buffer a time domain buffer containing audio samples 53 | * @returns the peak energy value 54 | */ 55 | T peakEnergy(std::vector buffer); 56 | 57 | //=========================================================== 58 | /** calculates the zero crossing rate of a time domain audio signal buffer 59 | * @param buffer a time domain buffer containing audio samples 60 | * @returns the zero crossing rate 61 | */ 62 | T zeroCrossingRate(std::vector buffer); 63 | }; 64 | 65 | #endif -------------------------------------------------------------------------------- /libs/Stark-Plumbley/ChordDetector.h: -------------------------------------------------------------------------------- 1 | //======================================================================= 2 | /** @file ChordDetector.h 3 | * @brief ChordDetector - a class for estimating chord labels from chromagram input 4 | * @author Adam Stark 5 | * @copyright Copyright (C) 2008-2014 Queen Mary University of London 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | //======================================================================= 21 | 22 | #ifndef CHORDDETECT_H 23 | #define CHORDDETECT_H 24 | 25 | #include 26 | 27 | //======================================================================= 28 | /** A class for estimating chord labels from chromagram input */ 29 | class ChordDetector 30 | { 31 | public: 32 | 33 | /** An enum describing the chord qualities used in the algorithm */ 34 | enum ChordQuality 35 | { 36 | Minor, 37 | Major, 38 | Suspended, 39 | Dominant, 40 | Dimished5th, 41 | Augmented5th, 42 | }; 43 | 44 | /** Constructor */ 45 | ChordDetector(); 46 | 47 | /** Detects the chord from a chromagram. This is the vector interface 48 | * @param chroma a vector of length 12 containing the chromagram 49 | */ 50 | void detectChord(std::vector chroma); 51 | 52 | /** Detects the chord from a chromagram. This is the array interface 53 | * @param chroma an array of length 12 containing the chromagram 54 | */ 55 | void detectChord(double *chroma); 56 | 57 | /** The root note of the detected chord */ 58 | int rootNote; 59 | 60 | /** The quality of the detected chord (Major, Minor, etc) */ 61 | int quality; 62 | 63 | /** Any other intervals that describe the chord, e.g. 7th */ 64 | int intervals; 65 | 66 | private: 67 | void makeChordProfiles(); 68 | 69 | void classifyChromagram(); 70 | 71 | double calculateChordScore(double *chroma,double *chordProfile,double biasToUse, double N); 72 | 73 | int minimumIndex(double *array,int length); 74 | 75 | double chromagram[12]; 76 | double chordProfiles[108][12]; 77 | 78 | double chord[108]; 79 | 80 | double bias; 81 | }; 82 | 83 | #endif 84 | -------------------------------------------------------------------------------- /libs/Gist/src/core/CoreFrequencyDomainFeatures.h: -------------------------------------------------------------------------------- 1 | //======================================================================= 2 | /** @file CoreFrequencyDomainFeatures.h 3 | * @brief Implementations of common frequency domain audio features 4 | * @author Adam Stark 5 | * @copyright Copyright (C) 2013 Adam Stark 6 | * 7 | * This file is part of the 'Gist' audio analysis library 8 | * 9 | * This program is free software: you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as published by 11 | * the Free Software Foundation, either version 3 of the License, or 12 | * (at your option) any later version. 13 | * 14 | * This program is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | * GNU General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public License 20 | * along with this program. If not, see . 21 | */ 22 | //======================================================================= 23 | 24 | 25 | #ifndef __GIST__COREFREQUENCYDOMAINFEATURES__ 26 | #define __GIST__COREFREQUENCYDOMAINFEATURES__ 27 | 28 | #include 29 | #include 30 | 31 | /** template class for calculating common frequency domain 32 | * audio features. Instantiations of the class should be 33 | * of either 'float' or 'double' types and no others */ 34 | template 35 | class CoreFrequencyDomainFeatures 36 | { 37 | 38 | public: 39 | /** constructor */ 40 | CoreFrequencyDomainFeatures(); 41 | 42 | //=========================================================== 43 | /** calculates the spectral centroid given the first half of the magnitude spectrum 44 | of an audio signal. Do not pass the whole (i.e. mirrored) magnitude spectrum into 45 | this function or you will always get the middle index as the spectral centroid 46 | @param magnitudeSpectrum the first half of the magnitude spectrum (i.e. not mirrored) 47 | @returns the spectral centroid as an index value 48 | */ 49 | T spectralCentroid(std::vector magnitudeSpectrum); 50 | 51 | //=========================================================== 52 | /** calculates the spectral flatness given the first half of the magnitude spectrum 53 | of an audio signal. 54 | @param magnitudeSpectrum the first half of the magnitude spectrum (i.e. not mirrored) 55 | @returns the spectral flatness 56 | */ 57 | T spectralFlatness(std::vector magnitudeSpectrum); 58 | 59 | //=========================================================== 60 | /** calculates the spectral crest given the first half of the magnitude spectrum 61 | of an audio signal. 62 | @param magnitudeSpectrum the first half of the magnitude spectrum (i.e. not mirrored) 63 | @returns the spectral crest 64 | */ 65 | T spectralCrest(std::vector magnitudeSpectrum); 66 | 67 | 68 | }; 69 | 70 | #endif -------------------------------------------------------------------------------- /libs/Gist/src/core/CoreTimeDomainFeatures.cpp: -------------------------------------------------------------------------------- 1 | //======================================================================= 2 | /** @file CoreTimeDomainFeatures.cpp 3 | * @brief Implementations of common time domain audio features 4 | * @author Adam Stark 5 | * @copyright Copyright (C) 2013 Adam Stark 6 | * 7 | * This file is part of the 'Gist' audio analysis library 8 | * 9 | * This program is free software: you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as published by 11 | * the Free Software Foundation, either version 3 of the License, or 12 | * (at your option) any later version. 13 | * 14 | * This program is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | * GNU General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public License 20 | * along with this program. If not, see . 21 | */ 22 | //======================================================================= 23 | 24 | #include "CoreTimeDomainFeatures.h" 25 | 26 | 27 | //=========================================================== 28 | template 29 | CoreTimeDomainFeatures::CoreTimeDomainFeatures() 30 | { 31 | 32 | 33 | } 34 | 35 | //=========================================================== 36 | template 37 | T CoreTimeDomainFeatures::rootMeanSquare(std::vector buffer) 38 | { 39 | // create variable to hold the sum 40 | T sum = 0; 41 | 42 | // sum the squared samples 43 | for (int i = 0;i < buffer.size();i++) 44 | { 45 | sum += pow(buffer[i],2); 46 | } 47 | 48 | // return the square root of the mean of squared samples 49 | return sqrt(sum / ((T) buffer.size())); 50 | } 51 | 52 | //=========================================================== 53 | template 54 | T CoreTimeDomainFeatures::peakEnergy(std::vector buffer) 55 | { 56 | // create variable with very small value to hold the peak value 57 | T peak = -10000.0; 58 | 59 | // for each audio sample 60 | for (int i = 0;i < buffer.size();i++) 61 | { 62 | // store the absolute value of the sample 63 | T absSample = fabs(buffer[i]); 64 | 65 | // if the absolute value is larger than the peak 66 | if (absSample > peak) 67 | { 68 | // the peak takes on the sample value 69 | peak = absSample; 70 | } 71 | } 72 | 73 | // return the peak value 74 | return peak; 75 | } 76 | 77 | //=========================================================== 78 | template 79 | T CoreTimeDomainFeatures::zeroCrossingRate(std::vector buffer) 80 | { 81 | // create a variable to hold the zero crossing rate 82 | T zcr = 0; 83 | 84 | // for each audio sample, starting from the second one 85 | for (int i = 1;i < buffer.size();i++) 86 | { 87 | // initialise two booleans indicating whether or not 88 | // the current and previous sample are positive 89 | bool current = (buffer[i] > 0); 90 | bool previous = (buffer[i-1] > 0); 91 | 92 | // if the sign is different 93 | if (current != previous) 94 | { 95 | // add one to the zero crossing rate 96 | zcr = zcr + 1.0; 97 | } 98 | } 99 | 100 | // return the zero crossing rate 101 | return zcr; 102 | } 103 | 104 | //=========================================================== 105 | template class CoreTimeDomainFeatures; 106 | template class CoreTimeDomainFeatures; -------------------------------------------------------------------------------- /libs/kiss_fft130/kiss_fft.h: -------------------------------------------------------------------------------- 1 | #ifndef KISS_FFT_H 2 | #define KISS_FFT_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #ifdef __cplusplus 10 | extern "C" { 11 | #endif 12 | 13 | /* 14 | ATTENTION! 15 | If you would like a : 16 | -- a utility that will handle the caching of fft objects 17 | -- real-only (no imaginary time component ) FFT 18 | -- a multi-dimensional FFT 19 | -- a command-line utility to perform ffts 20 | -- a command-line utility to perform fast-convolution filtering 21 | 22 | Then see kfc.h kiss_fftr.h kiss_fftnd.h fftutil.c kiss_fastfir.c 23 | in the tools/ directory. 24 | */ 25 | 26 | #ifdef USE_SIMD 27 | # include 28 | # define kiss_fft_scalar __m128 29 | #define KISS_FFT_MALLOC(nbytes) _mm_malloc(nbytes,16) 30 | #define KISS_FFT_FREE _mm_free 31 | #else 32 | #define KISS_FFT_MALLOC malloc 33 | #define KISS_FFT_FREE free 34 | #endif 35 | 36 | 37 | #ifdef FIXED_POINT 38 | #include 39 | # if (FIXED_POINT == 32) 40 | # define kiss_fft_scalar int32_t 41 | # else 42 | # define kiss_fft_scalar int16_t 43 | # endif 44 | #else 45 | # ifndef kiss_fft_scalar 46 | /* default is float */ 47 | # define kiss_fft_scalar float 48 | # endif 49 | #endif 50 | 51 | typedef struct { 52 | kiss_fft_scalar r; 53 | kiss_fft_scalar i; 54 | }kiss_fft_cpx; 55 | 56 | typedef struct kiss_fft_state* kiss_fft_cfg; 57 | 58 | /* 59 | * kiss_fft_alloc 60 | * 61 | * Initialize a FFT (or IFFT) algorithm's cfg/state buffer. 62 | * 63 | * typical usage: kiss_fft_cfg mycfg=kiss_fft_alloc(1024,0,NULL,NULL); 64 | * 65 | * The return value from fft_alloc is a cfg buffer used internally 66 | * by the fft routine or NULL. 67 | * 68 | * If lenmem is NULL, then kiss_fft_alloc will allocate a cfg buffer using malloc. 69 | * The returned value should be free()d when done to avoid memory leaks. 70 | * 71 | * The state can be placed in a user supplied buffer 'mem': 72 | * If lenmem is not NULL and mem is not NULL and *lenmem is large enough, 73 | * then the function places the cfg in mem and the size used in *lenmem 74 | * and returns mem. 75 | * 76 | * If lenmem is not NULL and ( mem is NULL or *lenmem is not large enough), 77 | * then the function returns NULL and places the minimum cfg 78 | * buffer size in *lenmem. 79 | * */ 80 | 81 | kiss_fft_cfg kiss_fft_alloc(int nfft,int inverse_fft,void * mem,size_t * lenmem); 82 | 83 | /* 84 | * kiss_fft(cfg,in_out_buf) 85 | * 86 | * Perform an FFT on a complex input buffer. 87 | * for a forward FFT, 88 | * fin should be f[0] , f[1] , ... ,f[nfft-1] 89 | * fout will be F[0] , F[1] , ... ,F[nfft-1] 90 | * Note that each element is complex and can be accessed like 91 | f[k].r and f[k].i 92 | * */ 93 | void kiss_fft(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout); 94 | 95 | /* 96 | A more generic version of the above function. It reads its input from every Nth sample. 97 | * */ 98 | void kiss_fft_stride(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout,int fin_stride); 99 | 100 | /* If kiss_fft_alloc allocated a buffer, it is one contiguous 101 | buffer and can be simply free()d when no longer needed*/ 102 | #define kiss_fft_free free 103 | 104 | /* 105 | Cleans up some memory that gets managed internally. Not necessary to call, but it might clean up 106 | your compiler output to call this before you exit. 107 | */ 108 | void kiss_fft_cleanup(void); 109 | 110 | 111 | /* 112 | * Returns the smallest integer k, such that k>=n and k has only "fast" factors (2,3,5) 113 | */ 114 | int kiss_fft_next_fast_size(int n); 115 | 116 | /* for real ffts, we need an even size */ 117 | #define kiss_fftr_next_fast_size_real(n) \ 118 | (kiss_fft_next_fast_size( ((n)+1)>>1)<<1) 119 | 120 | #ifdef __cplusplus 121 | } 122 | #endif 123 | 124 | #endif 125 | -------------------------------------------------------------------------------- /libs/Gist/src/core/CoreFrequencyDomainFeatures.cpp: -------------------------------------------------------------------------------- 1 | //======================================================================= 2 | /** @file CoreFrequencyDomainFeatures.cpp 3 | * @brief Implementations of common frequency domain audio features 4 | * @author Adam Stark 5 | * @copyright Copyright (C) 2013 Adam Stark 6 | * 7 | * This file is part of the 'Gist' audio analysis library 8 | * 9 | * This program is free software: you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as published by 11 | * the Free Software Foundation, either version 3 of the License, or 12 | * (at your option) any later version. 13 | * 14 | * This program is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | * GNU General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public License 20 | * along with this program. If not, see . 21 | */ 22 | //======================================================================= 23 | 24 | 25 | #include "CoreFrequencyDomainFeatures.h" 26 | 27 | //=========================================================== 28 | template 29 | CoreFrequencyDomainFeatures::CoreFrequencyDomainFeatures() 30 | { 31 | 32 | } 33 | 34 | //=========================================================== 35 | template 36 | T CoreFrequencyDomainFeatures::spectralCentroid(std::vector magnitudeSpectrum) 37 | { 38 | // to hold sum of amplitudes 39 | T sumAmplitudes = 0.0; 40 | 41 | // to hold sum of weighted amplitudes 42 | T sumWeightedAmplitudes = 0.0; 43 | 44 | // for each bin in the first half of the magnitude spectrum 45 | for (int i = 0;i < magnitudeSpectrum.size();i++) 46 | { 47 | // sum amplitudes 48 | sumAmplitudes += magnitudeSpectrum[i]; 49 | 50 | // sum amplitudes weighted by the bin number 51 | sumWeightedAmplitudes += magnitudeSpectrum[i]*i; 52 | } 53 | 54 | // if the sum of amplitudes is larger than zero (it should be if the buffer wasn't 55 | // all zeros) 56 | if (sumAmplitudes > 0) 57 | { 58 | // the spectral centroid is the sum of weighted amplitudes divided by the sum of amplitdues 59 | return sumWeightedAmplitudes / sumAmplitudes; 60 | } 61 | else // to be safe just return zero 62 | { 63 | return 0.0; 64 | } 65 | } 66 | 67 | //=========================================================== 68 | template 69 | T CoreFrequencyDomainFeatures::spectralFlatness(std::vector magnitudeSpectrum) 70 | { 71 | double sumVal = 0.0; 72 | double logSumVal = 0.0; 73 | double N = (double) magnitudeSpectrum.size(); 74 | 75 | T flatness; 76 | 77 | for (int i = 0;i < magnitudeSpectrum.size();i++) 78 | { 79 | // add one to stop zero values making it always zero 80 | double v = (double) (1+magnitudeSpectrum[i]); 81 | 82 | sumVal += v; 83 | logSumVal += log(v); 84 | } 85 | 86 | sumVal = sumVal / N; 87 | logSumVal = logSumVal / N; 88 | 89 | if (sumVal > 0) 90 | { 91 | flatness = (T) (exp(logSumVal) / sumVal); 92 | } 93 | else 94 | { 95 | flatness = 0.0; 96 | } 97 | 98 | return flatness; 99 | } 100 | 101 | //=========================================================== 102 | template 103 | T CoreFrequencyDomainFeatures::spectralCrest(std::vector magnitudeSpectrum) 104 | { 105 | T sumVal = 0.0; 106 | T maxVal = 0.0; 107 | T N = (T) magnitudeSpectrum.size(); 108 | 109 | for (int i = 0;i < magnitudeSpectrum.size();i++) 110 | { 111 | T v = magnitudeSpectrum[i]*magnitudeSpectrum[i]; 112 | sumVal += v; 113 | 114 | if (v > maxVal) 115 | { 116 | maxVal = v; 117 | } 118 | } 119 | 120 | T spectralCrest; 121 | 122 | if (sumVal > 0) 123 | { 124 | T meanVal = sumVal / N; 125 | 126 | spectralCrest = maxVal / meanVal; 127 | } 128 | else 129 | { 130 | // this is a ratio so we return 1.0 if the buffer is just zeros 131 | spectralCrest = 1.0; 132 | } 133 | 134 | return spectralCrest; 135 | } 136 | 137 | //=========================================================== 138 | template class CoreFrequencyDomainFeatures; 139 | template class CoreFrequencyDomainFeatures; 140 | -------------------------------------------------------------------------------- /libs/Gist/src/mfcc/MFCC.h: -------------------------------------------------------------------------------- 1 | //======================================================================= 2 | /** @file MFCC.h 3 | * @brief Calculates Mel Frequency Cepstral Coefficients 4 | * @author Adam Stark 5 | * @copyright Copyright (C) 2014 Adam Stark 6 | * 7 | * This file is part of the 'Gist' audio analysis library 8 | * 9 | * This program is free software: you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as published by 11 | * the Free Software Foundation, either version 3 of the License, or 12 | * (at your option) any later version. 13 | * 14 | * This program is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | * GNU General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public License 20 | * along with this program. If not, see . 21 | */ 22 | //======================================================================= 23 | 24 | #ifndef __GIST__MFCC__ 25 | #define __GIST__MFCC__ 26 | 27 | #define _USE_MATH_DEFINES 28 | #include 29 | #include 30 | 31 | /** Template class for calculating Mel Frequency Cepstral Coefficients 32 | * Instantiations of the class should be of either 'float' or 33 | * 'double' types and no others */ 34 | template 35 | class MFCC 36 | { 37 | public: 38 | /** Constructor */ 39 | MFCC(int frameSize_,int samplingFrequency_); 40 | 41 | /** Set the number of coefficients to calculate 42 | * @param numCoefficients_ the number of coefficients to calculate 43 | */ 44 | void setNumCoefficients(int numCoefficients_); 45 | 46 | /** Set the frame size - N.B. this will be twice the length of the magnitude spectrum passed to calculateMFCC() 47 | * @param frameSize_ the frame size 48 | */ 49 | void setFrameSize(int frameSize_); 50 | 51 | /** Set the sampling frequency 52 | * @param samplingFrequency_ the sampling frequency in hz 53 | */ 54 | void setSamplingFrequency(int samplingFrequency_); 55 | 56 | /** Calculates the Mel Frequency Cepstral Coefficients from the magnitude spectrum of a signal. Note that 57 | * the magnitude spectrum passed to the function is not the full mirrored magnitude spectrum, but only the 58 | * first half. The frame size passed to the constructor should be twice the length of the magnitude spectrum. 59 | * @param magnitudeSpectrum the magnitude spectrum in vector format 60 | * @returns a vector containing the MFCCs 61 | */ 62 | std::vector melFrequencyCepstralCoefficients(std::vector magnitudeSpectrum); 63 | 64 | /** Calculates the magnitude spectrum on a Mel scale 65 | * @returns a vector containing the Mel spectrum 66 | */ 67 | std::vector melFrequencySpectrum(std::vector magnitudeSpectrum); 68 | 69 | private: 70 | /** Initialises the parts of the algorithm dependent on frame size, sampling frequency 71 | * and the number of coefficients 72 | */ 73 | void initialise(); 74 | 75 | /** Calculates the discrete cosine transform (version 2) of an input signal 76 | * @param inputSignal a vector containing the input signal 77 | * @returns a vector containing the DCT of the input signal 78 | */ 79 | std::vector discreteCosineTransform(std::vector inputSignal); 80 | 81 | /** Calculates the triangular filters used in the algorithm. These will be different depending 82 | * upon the frame size, sampling frequency and number of coefficients and so should be re-calculated 83 | * should any of those parameters change. 84 | */ 85 | void calculateMelFilterBank(); 86 | 87 | /** Calculates mel from frequency 88 | * @param frequency the frequency in Hz 89 | * @returns the equivalent mel value 90 | */ 91 | T frequencyToMel(T frequency); 92 | 93 | /** the sampling frequency in Hz */ 94 | int samplingFrequency; 95 | 96 | /** the number of MFCCs to calculate */ 97 | int numCoefficents; 98 | 99 | /** the audio frame size */ 100 | int frameSize; 101 | 102 | /** the magnitude spectrum size (this will be half the frame size) */ 103 | int magnitudeSpectrumSize; 104 | 105 | /** the minimum frequency to be used in the calculation of MFCCs */ 106 | T minFrequency; 107 | 108 | /** the maximum frequency to be used in the calculation of MFCCs */ 109 | T maxFrequency; 110 | 111 | /** a vector of vectors to hold the values of the triangular filters */ 112 | std::vector > filterBank; 113 | 114 | }; 115 | 116 | #endif /* defined(__GIST__MFCC__) */ 117 | -------------------------------------------------------------------------------- /libs/Gist/src/pitch/Yin.h: -------------------------------------------------------------------------------- 1 | //======================================================================= 2 | /** @file Yin.h 3 | * @brief Implementation of the YIN pitch detection algorithm (de Cheveigné and Kawahara,2002) 4 | * @author Adam Stark 5 | * @copyright Copyright (C) 2013 Adam Stark 6 | * 7 | * This file is part of the 'Gist' audio analysis library 8 | * 9 | * This program is free software: you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as published by 11 | * the Free Software Foundation, either version 3 of the License, or 12 | * (at your option) any later version. 13 | * 14 | * This program is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | * GNU General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public License 20 | * along with this program. If not, see . 21 | */ 22 | //======================================================================= 23 | 24 | #ifndef __GIST__YIN__ 25 | #define __GIST__YIN__ 26 | 27 | #include 28 | #include 29 | 30 | /** template class for the pitch detection algorithm Yin. 31 | * Instantiations of the class should be of either 'float' or 32 | * 'double' types and no others */ 33 | template 34 | class Yin 35 | { 36 | 37 | public: 38 | /** constructor 39 | * @param samplingFrequency the sampling frequency 40 | */ 41 | Yin(int samplingFrequency); 42 | 43 | /** sets the sampling frequency used to calculate pitch values 44 | * @param samplingFrequency the sampling frequency 45 | */ 46 | void setSamplingFrequency(int samplingFrequency); 47 | 48 | /** sets the maximum frequency that the algorithm will return 49 | * @param maxFreq the maximum frequency 50 | */ 51 | void setMaxFrequency(T maxFreq); 52 | 53 | /** @returns the maximum frequency that the algorithm will return */ 54 | T getMaxFrequency() 55 | { 56 | return ((T) fs) / ((T) minPeriod); 57 | } 58 | 59 | /** calculates the pitch of the audio frame passed to it 60 | * @param frame an audio frame stored in a vector 61 | * @returns the estimated pitch in Hz 62 | */ 63 | T pitchYin(std::vector frame); 64 | 65 | private: 66 | 67 | /** converts periods to pitch in Hz 68 | * @param period the period in audio samples 69 | * @returns the pitch in Hz 70 | */ 71 | T periodToPitch(T period); 72 | 73 | /** this method searches the previous period estimate for a 74 | * minimum and if it finds one, it is used, for the sake of consistency, 75 | * even if it is not the optimal choice 76 | * @param delta the cumulative mean normalised difference function 77 | * @returns the period found if a minimum is found, or -1 if not 78 | */ 79 | long searchForOtherRecentMinima(std::vector delta); 80 | 81 | /** interpolates a period estimate using parabolic interpolation 82 | * @param period the period estimate 83 | * @param y1 the value of the cumulative mean normalised difference function at (period-1) 84 | * @param y2 the value of the cumulative mean normalised difference function at (period) 85 | * @param y3 the value of the cumulative mean normalised difference function at (period+1) 86 | * @returns the interpolated period 87 | */ 88 | T parabolicInterpolation(unsigned long period,T y1,T y2,T y3); 89 | 90 | /** calculates the period candidate from the cumulative mean normalised difference function 91 | * @param delta the cumulative mean normalised difference function 92 | * @returns the period estimate 93 | */ 94 | unsigned long getPeriodCandidate(std::vector delta); 95 | 96 | /** this calculates steps 1, 2 and 3 of the Yin algorithm as set out in 97 | * the paper (de Cheveigné and Kawahara,2002). 98 | * @param frame a pointer to the audio frame to be procesed 99 | * @param numSamples the number of audio samples in the frame 100 | * @returns the cumulative mean normalised difference function ("delta") 101 | */ 102 | void cumulativeMeanNormalisedDifferenceFunction(T *frame,unsigned long numSamples); 103 | 104 | T round(T val) 105 | { 106 | return floor(val + 0.5); 107 | } 108 | 109 | /** the previous period estimate found by the algorithm last time it was called - initially set to 1.0 */ 110 | T prevPeriodEstimate; 111 | 112 | /** the sampling frequency */ 113 | int fs; 114 | 115 | /** the minimum period the algorithm will look for. this is set indirectly by setMaxFrequency() */ 116 | int minPeriod; 117 | 118 | std::vector delta; 119 | }; 120 | 121 | #endif 122 | -------------------------------------------------------------------------------- /libs/Stark-Plumbley/Chromagram.h: -------------------------------------------------------------------------------- 1 | //======================================================================= 2 | /** @file Chromagram.h 3 | * @brief Chromagram - a class for calculating the chromagram in real-time 4 | * @author Adam Stark 5 | * @copyright Copyright (C) 2008-2014 Queen Mary University of London 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | //======================================================================= 21 | 22 | #ifndef __CHROMAGRAM_H 23 | #define __CHROMAGRAM_H 24 | 25 | #define _USE_MATH_DEFINES 26 | #include 27 | #include 28 | 29 | #ifdef USE_FFTW 30 | #include "fftw3.h" 31 | #endif 32 | 33 | #ifdef USE_KISS_FFT 34 | #include "../kiss_fft130/kiss_fft.h" 35 | #endif 36 | 37 | //======================================================================= 38 | /** A class for calculating a Chromagram from input audio 39 | * in a real-time context */ 40 | class Chromagram 41 | { 42 | 43 | public: 44 | /** Constructor 45 | * @param frameSize the input audio frame size 46 | * @param fs the sampling frequency 47 | */ 48 | Chromagram(int frameSize,int fs); 49 | 50 | /** Destructor */ 51 | ~Chromagram(); 52 | 53 | /** Process a single audio frame. This will determine whether enough samples 54 | * have been accumulated and if so, will calculate the chromagram 55 | * @param inputAudioFrame an array containing the input audio frame. This should be 56 | * the length indicated by the input audio frame size passed to the constructor 57 | * @see setInputAudioFrameSize 58 | */ 59 | void processAudioFrame(double *inputAudioFrame); 60 | 61 | /** Process a single audio frame. This will determine whether enough samples 62 | * have been accumulated and if so, will calculate the chromagram 63 | * @param inputAudioFrame a vector containing the input audio frame. This should be 64 | * the length indicated by the input audio frame size passed to the constructor 65 | * @see setInputAudioFrameSize 66 | */ 67 | void processAudioFrame(std::vector inputAudioFrame); 68 | 69 | /** Sets the input audio frame size 70 | * @param frameSize the input audio frame size 71 | */ 72 | void setInputAudioFrameSize(int frameSize); 73 | 74 | /** Set the sampling frequency of the input audio 75 | * @param fs the sampling frequency in Hz 76 | */ 77 | void setSamplingFrequency(int fs); 78 | 79 | /** Set the interval at which the chromagram is calculated. As the algorithm requires 80 | * a significant amount of audio to be accumulated, it may be desirable to have the algorithm 81 | * not calculate the chromagram at every new audio frame. This function allows you to set the 82 | * interval at which the chromagram will be calculated, specified in the number of samples at 83 | * the audio sampling frequency 84 | * @param numSamples the number of samples that the algorithm will receive before calculating a new chromagram 85 | */ 86 | void setChromaCalculationInterval(int numSamples); 87 | 88 | /** @returns the chromagram vector */ 89 | std::vector getChromagram(); 90 | 91 | /** @returns true if a new chromagram vector has been calculated at the current iteration. This should 92 | * be called after processAudioFrame 93 | */ 94 | bool isReady(); 95 | 96 | private: 97 | 98 | void setupFFT(); 99 | 100 | void calculateChromagram(); 101 | 102 | void calculateMagnitudeSpectrum(); 103 | 104 | void downSampleFrame(std::vector inputAudioFrame); 105 | 106 | void makeHammingWindow(); 107 | 108 | double round(double val) 109 | { 110 | return floor(val + 0.5); 111 | } 112 | 113 | std::vector window; 114 | std::vector buffer; 115 | std::vector magnitudeSpectrum; 116 | std::vector downsampledInputAudioFrame; 117 | std::vector chromagram; 118 | 119 | double referenceFrequency; 120 | double noteFrequencies[12]; 121 | 122 | int bufferSize; 123 | int samplingFrequency; 124 | int inputAudioFrameSize; 125 | int downSampledAudioFrameSize; 126 | 127 | int numHarmonics; 128 | int numOctaves; 129 | int numBinsToSearch; 130 | 131 | int numSamplesSinceLastCalculation; 132 | int chromaCalculationInterval; 133 | bool chromaReady; 134 | 135 | #ifdef USE_FFTW 136 | fftw_plan p; 137 | fftw_complex *complexOut; 138 | fftw_complex *complexIn; 139 | #endif 140 | 141 | #ifdef USE_KISS_FFT 142 | kiss_fft_cfg cfg; 143 | kiss_fft_cpx *fftIn; 144 | kiss_fft_cpx *fftOut; 145 | #endif 146 | 147 | }; 148 | 149 | #endif /* defined(__CHROMAGRAM_H) */ 150 | -------------------------------------------------------------------------------- /libs/Gist/src/onset-detection-functions/OnsetDetectionFunction.h: -------------------------------------------------------------------------------- 1 | //======================================================================= 2 | /** @file OnsetDetectionFunction.h 3 | * @brief Implementations of onset detection functions 4 | * @author Adam Stark 5 | * @copyright Copyright (C) 2013 Adam Stark 6 | * 7 | * This file is part of the 'Gist' audio analysis library 8 | * 9 | * This program is free software: you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as published by 11 | * the Free Software Foundation, either version 3 of the License, or 12 | * (at your option) any later version. 13 | * 14 | * This program is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | * GNU General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public License 20 | * along with this program. If not, see . 21 | */ 22 | //======================================================================= 23 | 24 | 25 | #ifndef __GIST__ONSETDETECTIONFUNCTION__ 26 | #define __GIST__ONSETDETECTIONFUNCTION__ 27 | 28 | #define _USE_MATH_DEFINES 29 | #include 30 | #include 31 | 32 | /** template class for calculating onset detection functions 33 | * Instantiations of the class should be of either 'float' or 34 | * 'double' types and no others */ 35 | template 36 | class OnsetDetectionFunction 37 | { 38 | 39 | public: 40 | //=========================================================== 41 | /** constructor */ 42 | OnsetDetectionFunction(int frameSize); 43 | 44 | //=========================================================== 45 | /** Sets the frame size of internal buffers. Assumes all magnitude 46 | * spectra are passed as the first half (i.e. not mirrored) 47 | * @param frameSize the frame size 48 | */ 49 | void setFrameSize(int frameSize); 50 | 51 | //=========================================================== 52 | /** calculates the energy difference onset detection function 53 | * @param buffer the time domain audio frame containing audio samples 54 | * @returns the energy difference onset detection function sample for the frame 55 | */ 56 | T energyDifference(std::vector buffer); 57 | 58 | //=========================================================== 59 | /** calculates the spectral difference between the current magnitude 60 | * spectrum and the previous magnitude spectrum 61 | * @param magnitudeSpectrum a vector containing the magnitude spectrum 62 | * @returns the spectral difference onset detection function sample 63 | */ 64 | T spectralDifference(std::vector magnitudeSpectrum); 65 | 66 | //=========================================================== 67 | /** calculates the half wave rectified spectral difference between the 68 | * current magnitude spectrum and the previous magnitude spectrum 69 | * @param magnitudeSpectrum a vector containing the magnitude spectrum 70 | * @returns the HWR spectral difference onset detection function sample 71 | */ 72 | T spectralDifferenceHWR(std::vector magnitudeSpectrum); 73 | 74 | //=========================================================== 75 | /** calculates the complex spectral difference from the real and imaginary parts 76 | * of the FFT 77 | * @param fftReal a vector containing the real part of the FFT 78 | * @param fftImag a vector containing the imaginary part of the FFT 79 | * @returns the complex spectral difference onset detection function sample 80 | */ 81 | T complexSpectralDifference(std::vector fftReal,std::vector fftImag); 82 | 83 | //=========================================================== 84 | /** calculates the high frequency content onset detection function from 85 | * the magnitude spectrum 86 | * @param magnitudeSpectrum a vector containing the magnitude spectrum 87 | * @returns the high frequency content onset detection function sample 88 | */ 89 | T highFrequencyContent(std::vector magnitudeSpectrum); 90 | 91 | private: 92 | 93 | 94 | /** maps phasein into the [-pi:pi] range */ 95 | T princarg(T phaseVal); 96 | 97 | //=========================================================== 98 | /** holds the previous energy sum for the energy difference onset detection function */ 99 | T prevEnergySum; 100 | 101 | /** a vector containing the previous magnitude spectrum passed to the 102 | last spectral difference call */ 103 | std::vector prevMagnitudeSpectrum_spectralDifference; 104 | 105 | /** a vector containing the previous magnitude spectrum passed to the 106 | last spectral difference (half wave rectified) call */ 107 | std::vector prevMagnitudeSpectrum_spectralDifferenceHWR; 108 | 109 | /** a vector containing the previous phase spectrum passed to the 110 | last complex spectral difference call */ 111 | std::vector prevPhaseSpectrum_complexSpectralDifference; 112 | 113 | /** a vector containing the second previous phase spectrum passed to the 114 | last complex spectral difference call */ 115 | std::vector prevPhaseSpectrum2_complexSpectralDifference; 116 | 117 | /** a vector containing the previous magnitude spectrum passed to the 118 | last complex spectral difference call */ 119 | std::vector prevMagnitudeSpectrum_complexSpectralDifference; 120 | }; 121 | 122 | #endif -------------------------------------------------------------------------------- /libs/kiss_fft130/README: -------------------------------------------------------------------------------- 1 | KISS FFT - A mixed-radix Fast Fourier Transform based up on the principle, 2 | "Keep It Simple, Stupid." 3 | 4 | There are many great fft libraries already around. Kiss FFT is not trying 5 | to be better than any of them. It only attempts to be a reasonably efficient, 6 | moderately useful FFT that can use fixed or floating data types and can be 7 | incorporated into someone's C program in a few minutes with trivial licensing. 8 | 9 | USAGE: 10 | 11 | The basic usage for 1-d complex FFT is: 12 | 13 | #include "kiss_fft.h" 14 | 15 | kiss_fft_cfg cfg = kiss_fft_alloc( nfft ,is_inverse_fft ,0,0 ); 16 | 17 | while ... 18 | 19 | ... // put kth sample in cx_in[k].r and cx_in[k].i 20 | 21 | kiss_fft( cfg , cx_in , cx_out ); 22 | 23 | ... // transformed. DC is in cx_out[0].r and cx_out[0].i 24 | 25 | free(cfg); 26 | 27 | Note: frequency-domain data is stored from dc up to 2pi. 28 | so cx_out[0] is the dc bin of the FFT 29 | and cx_out[nfft/2] is the Nyquist bin (if exists) 30 | 31 | Declarations are in "kiss_fft.h", along with a brief description of the 32 | functions you'll need to use. 33 | 34 | Code definitions for 1d complex FFTs are in kiss_fft.c. 35 | 36 | You can do other cool stuff with the extras you'll find in tools/ 37 | 38 | * multi-dimensional FFTs 39 | * real-optimized FFTs (returns the positive half-spectrum: (nfft/2+1) complex frequency bins) 40 | * fast convolution FIR filtering (not available for fixed point) 41 | * spectrum image creation 42 | 43 | The core fft and most tools/ code can be compiled to use float, double, 44 | Q15 short or Q31 samples. The default is float. 45 | 46 | 47 | BACKGROUND: 48 | 49 | I started coding this because I couldn't find a fixed point FFT that didn't 50 | use assembly code. I started with floating point numbers so I could get the 51 | theory straight before working on fixed point issues. In the end, I had a 52 | little bit of code that could be recompiled easily to do ffts with short, float 53 | or double (other types should be easy too). 54 | 55 | Once I got my FFT working, I was curious about the speed compared to 56 | a well respected and highly optimized fft library. I don't want to criticize 57 | this great library, so let's call it FFT_BRANDX. 58 | During this process, I learned: 59 | 60 | 1. FFT_BRANDX has more than 100K lines of code. The core of kiss_fft is about 500 lines (cpx 1-d). 61 | 2. It took me an embarrassingly long time to get FFT_BRANDX working. 62 | 3. A simple program using FFT_BRANDX is 522KB. A similar program using kiss_fft is 18KB (without optimizing for size). 63 | 4. FFT_BRANDX is roughly twice as fast as KISS FFT in default mode. 64 | 65 | It is wonderful that free, highly optimized libraries like FFT_BRANDX exist. 66 | But such libraries carry a huge burden of complexity necessary to extract every 67 | last bit of performance. 68 | 69 | Sometimes simpler is better, even if it's not better. 70 | 71 | FREQUENTLY ASKED QUESTIONS: 72 | Q: Can I use kissfft in a project with a ___ license? 73 | A: Yes. See LICENSE below. 74 | 75 | Q: Why don't I get the output I expect? 76 | A: The two most common causes of this are 77 | 1) scaling : is there a constant multiplier between what you got and what you want? 78 | 2) mixed build environment -- all code must be compiled with same preprocessor 79 | definitions for FIXED_POINT and kiss_fft_scalar 80 | 81 | Q: Will you write/debug my code for me? 82 | A: Probably not unless you pay me. I am happy to answer pointed and topical questions, but 83 | I may refer you to a book, a forum, or some other resource. 84 | 85 | 86 | PERFORMANCE: 87 | (on Athlon XP 2100+, with gcc 2.96, float data type) 88 | 89 | Kiss performed 10000 1024-pt cpx ffts in .63 s of cpu time. 90 | For comparison, it took md5sum twice as long to process the same amount of data. 91 | 92 | Transforming 5 minutes of CD quality audio takes less than a second (nfft=1024). 93 | 94 | DO NOT: 95 | ... use Kiss if you need the Fastest Fourier Transform in the World 96 | ... ask me to add features that will bloat the code 97 | 98 | UNDER THE HOOD: 99 | 100 | Kiss FFT uses a time decimation, mixed-radix, out-of-place FFT. If you give it an input buffer 101 | and output buffer that are the same, a temporary buffer will be created to hold the data. 102 | 103 | No static data is used. The core routines of kiss_fft are thread-safe (but not all of the tools directory). 104 | 105 | No scaling is done for the floating point version (for speed). 106 | Scaling is done both ways for the fixed-point version (for overflow prevention). 107 | 108 | Optimized butterflies are used for factors 2,3,4, and 5. 109 | 110 | The real (i.e. not complex) optimization code only works for even length ffts. It does two half-length 111 | FFTs in parallel (packed into real&imag), and then combines them via twiddling. The result is 112 | nfft/2+1 complex frequency bins from DC to Nyquist. If you don't know what this means, search the web. 113 | 114 | The fast convolution filtering uses the overlap-scrap method, slightly 115 | modified to put the scrap at the tail. 116 | 117 | LICENSE: 118 | Revised BSD License, see COPYING for verbiage. 119 | Basically, "free to use&change, give credit where due, no guarantees" 120 | Note this license is compatible with GPL at one end of the spectrum and closed, commercial software at 121 | the other end. See http://www.fsf.org/licensing/licenses 122 | 123 | A commercial license is available which removes the requirement for attribution. Contact me for details. 124 | 125 | 126 | TODO: 127 | *) Add real optimization for odd length FFTs 128 | *) Document/revisit the input/output fft scaling 129 | *) Make doc describing the overlap (tail) scrap fast convolution filtering in kiss_fastfir.c 130 | *) Test all the ./tools/ code with fixed point (kiss_fastfir.c doesn't work, maybe others) 131 | 132 | AUTHOR: 133 | Mark Borgerding 134 | Mark@Borgerding.net 135 | -------------------------------------------------------------------------------- /libs/kiss_fft130/_kiss_fft_guts.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2003-2010, Mark Borgerding 3 | 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 7 | 8 | * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 10 | * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 | 12 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 13 | */ 14 | 15 | /* kiss_fft.h 16 | defines kiss_fft_scalar as either short or a float type 17 | and defines 18 | typedef struct { kiss_fft_scalar r; kiss_fft_scalar i; }kiss_fft_cpx; */ 19 | #include "kiss_fft.h" 20 | #include 21 | 22 | #define MAXFACTORS 32 23 | /* e.g. an fft of length 128 has 4 factors 24 | as far as kissfft is concerned 25 | 4*4*4*2 26 | */ 27 | 28 | struct kiss_fft_state{ 29 | int nfft; 30 | int inverse; 31 | int factors[2*MAXFACTORS]; 32 | kiss_fft_cpx twiddles[1]; 33 | }; 34 | 35 | /* 36 | Explanation of macros dealing with complex math: 37 | 38 | C_MUL(m,a,b) : m = a*b 39 | C_FIXDIV( c , div ) : if a fixed point impl., c /= div. noop otherwise 40 | C_SUB( res, a,b) : res = a - b 41 | C_SUBFROM( res , a) : res -= a 42 | C_ADDTO( res , a) : res += a 43 | * */ 44 | #ifdef FIXED_POINT 45 | #if (FIXED_POINT==32) 46 | # define FRACBITS 31 47 | # define SAMPPROD int64_t 48 | #define SAMP_MAX 2147483647 49 | #else 50 | # define FRACBITS 15 51 | # define SAMPPROD int32_t 52 | #define SAMP_MAX 32767 53 | #endif 54 | 55 | #define SAMP_MIN -SAMP_MAX 56 | 57 | #if defined(CHECK_OVERFLOW) 58 | # define CHECK_OVERFLOW_OP(a,op,b) \ 59 | if ( (SAMPPROD)(a) op (SAMPPROD)(b) > SAMP_MAX || (SAMPPROD)(a) op (SAMPPROD)(b) < SAMP_MIN ) { \ 60 | fprintf(stderr,"WARNING:overflow @ " __FILE__ "(%d): (%d " #op" %d) = %ld\n",__LINE__,(a),(b),(SAMPPROD)(a) op (SAMPPROD)(b) ); } 61 | #endif 62 | 63 | 64 | # define smul(a,b) ( (SAMPPROD)(a)*(b) ) 65 | # define sround( x ) (kiss_fft_scalar)( ( (x) + (1<<(FRACBITS-1)) ) >> FRACBITS ) 66 | 67 | # define S_MUL(a,b) sround( smul(a,b) ) 68 | 69 | # define C_MUL(m,a,b) \ 70 | do{ (m).r = sround( smul((a).r,(b).r) - smul((a).i,(b).i) ); \ 71 | (m).i = sround( smul((a).r,(b).i) + smul((a).i,(b).r) ); }while(0) 72 | 73 | # define DIVSCALAR(x,k) \ 74 | (x) = sround( smul( x, SAMP_MAX/k ) ) 75 | 76 | # define C_FIXDIV(c,div) \ 77 | do { DIVSCALAR( (c).r , div); \ 78 | DIVSCALAR( (c).i , div); }while (0) 79 | 80 | # define C_MULBYSCALAR( c, s ) \ 81 | do{ (c).r = sround( smul( (c).r , s ) ) ;\ 82 | (c).i = sround( smul( (c).i , s ) ) ; }while(0) 83 | 84 | #else /* not FIXED_POINT*/ 85 | 86 | # define S_MUL(a,b) ( (a)*(b) ) 87 | #define C_MUL(m,a,b) \ 88 | do{ (m).r = (a).r*(b).r - (a).i*(b).i;\ 89 | (m).i = (a).r*(b).i + (a).i*(b).r; }while(0) 90 | # define C_FIXDIV(c,div) /* NOOP */ 91 | # define C_MULBYSCALAR( c, s ) \ 92 | do{ (c).r *= (s);\ 93 | (c).i *= (s); }while(0) 94 | #endif 95 | 96 | #ifndef CHECK_OVERFLOW_OP 97 | # define CHECK_OVERFLOW_OP(a,op,b) /* noop */ 98 | #endif 99 | 100 | #define C_ADD( res, a,b)\ 101 | do { \ 102 | CHECK_OVERFLOW_OP((a).r,+,(b).r)\ 103 | CHECK_OVERFLOW_OP((a).i,+,(b).i)\ 104 | (res).r=(a).r+(b).r; (res).i=(a).i+(b).i; \ 105 | }while(0) 106 | #define C_SUB( res, a,b)\ 107 | do { \ 108 | CHECK_OVERFLOW_OP((a).r,-,(b).r)\ 109 | CHECK_OVERFLOW_OP((a).i,-,(b).i)\ 110 | (res).r=(a).r-(b).r; (res).i=(a).i-(b).i; \ 111 | }while(0) 112 | #define C_ADDTO( res , a)\ 113 | do { \ 114 | CHECK_OVERFLOW_OP((res).r,+,(a).r)\ 115 | CHECK_OVERFLOW_OP((res).i,+,(a).i)\ 116 | (res).r += (a).r; (res).i += (a).i;\ 117 | }while(0) 118 | 119 | #define C_SUBFROM( res , a)\ 120 | do {\ 121 | CHECK_OVERFLOW_OP((res).r,-,(a).r)\ 122 | CHECK_OVERFLOW_OP((res).i,-,(a).i)\ 123 | (res).r -= (a).r; (res).i -= (a).i; \ 124 | }while(0) 125 | 126 | 127 | #ifdef FIXED_POINT 128 | # define KISS_FFT_COS(phase) floor(.5+SAMP_MAX * cos (phase)) 129 | # define KISS_FFT_SIN(phase) floor(.5+SAMP_MAX * sin (phase)) 130 | # define HALF_OF(x) ((x)>>1) 131 | #elif defined(USE_SIMD) 132 | # define KISS_FFT_COS(phase) _mm_set1_ps( cos(phase) ) 133 | # define KISS_FFT_SIN(phase) _mm_set1_ps( sin(phase) ) 134 | # define HALF_OF(x) ((x)*_mm_set1_ps(.5)) 135 | #else 136 | # define KISS_FFT_COS(phase) (kiss_fft_scalar) cos(phase) 137 | # define KISS_FFT_SIN(phase) (kiss_fft_scalar) sin(phase) 138 | # define HALF_OF(x) ((x)*.5) 139 | #endif 140 | 141 | #define kf_cexp(x,phase) \ 142 | do{ \ 143 | (x)->r = KISS_FFT_COS(phase);\ 144 | (x)->i = KISS_FFT_SIN(phase);\ 145 | }while(0) 146 | 147 | 148 | /* a debugging function */ 149 | #define pcpx(c)\ 150 | fprintf(stderr,"%g + %gi\n",(double)((c)->r),(double)((c)->i) ) 151 | 152 | 153 | #ifdef KISS_FFT_USE_ALLOCA 154 | // define this to allow use of alloca instead of malloc for temporary buffers 155 | // Temporary buffers are used in two case: 156 | // 1. FFT sizes that have "bad" factors. i.e. not 2,3 and 5 157 | // 2. "in-place" FFTs. Notice the quotes, since kissfft does not really do an in-place transform. 158 | #include 159 | #define KISS_FFT_TMP_ALLOC(nbytes) alloca(nbytes) 160 | #define KISS_FFT_TMP_FREE(ptr) 161 | #else 162 | #define KISS_FFT_TMP_ALLOC(nbytes) KISS_FFT_MALLOC(nbytes) 163 | #define KISS_FFT_TMP_FREE(ptr) KISS_FFT_FREE(ptr) 164 | #endif 165 | -------------------------------------------------------------------------------- /libs/Gist/src/mfcc/MFCC.cpp: -------------------------------------------------------------------------------- 1 | //======================================================================= 2 | /** @file MFCC.cpp 3 | * @brief Calculates Mel Frequency Cepstral Coefficients 4 | * @author Adam Stark 5 | * @copyright Copyright (C) 2014 Adam Stark 6 | * 7 | * This file is part of the 'Gist' audio analysis library 8 | * 9 | * This program is free software: you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as published by 11 | * the Free Software Foundation, either version 3 of the License, or 12 | * (at your option) any later version. 13 | * 14 | * This program is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | * GNU General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public License 20 | * along with this program. If not, see . 21 | */ 22 | //======================================================================= 23 | 24 | #include "MFCC.h" 25 | 26 | //================================================================== 27 | template 28 | MFCC::MFCC(int frameSize_,int samplingFrequency_) 29 | { 30 | numCoefficents = 13; 31 | frameSize = frameSize_; 32 | samplingFrequency = samplingFrequency_; 33 | 34 | initialise(); 35 | } 36 | 37 | //================================================================== 38 | template 39 | void MFCC::setNumCoefficients(int numCoefficients_) 40 | { 41 | numCoefficents = numCoefficients_; 42 | 43 | initialise(); 44 | } 45 | 46 | //================================================================== 47 | template 48 | void MFCC::setFrameSize(int frameSize_) 49 | { 50 | frameSize = frameSize_; 51 | 52 | initialise(); 53 | } 54 | 55 | //================================================================== 56 | template 57 | void MFCC::setSamplingFrequency(int samplingFrequency_) 58 | { 59 | samplingFrequency = samplingFrequency_; 60 | 61 | initialise(); 62 | } 63 | 64 | //================================================================== 65 | template 66 | std::vector MFCC::melFrequencyCepstralCoefficients(std::vector magnitudeSpectrum) 67 | { 68 | std::vector melSpec; 69 | 70 | melSpec = melFrequencySpectrum(magnitudeSpectrum); 71 | 72 | for (int i = 0;i < melSpec.size();i++) 73 | { 74 | melSpec[i] = log(melSpec[i]); 75 | } 76 | 77 | return discreteCosineTransform(melSpec); 78 | } 79 | 80 | //================================================================== 81 | template 82 | std::vector MFCC::melFrequencySpectrum(std::vector magnitudeSpectrum) 83 | { 84 | std::vector filteredSpectrum; 85 | 86 | for (int i = 0;i < numCoefficents;i++) 87 | { 88 | double coeff = 0; 89 | 90 | for (int j = 0;j < magnitudeSpectrum.size();j++) 91 | { 92 | coeff += (T) ((magnitudeSpectrum[j]*magnitudeSpectrum[j])*filterBank[i][j]); 93 | } 94 | 95 | filteredSpectrum.push_back(coeff); 96 | } 97 | 98 | return filteredSpectrum; 99 | } 100 | 101 | //================================================================== 102 | template 103 | void MFCC::initialise() 104 | { 105 | magnitudeSpectrumSize = frameSize/2; 106 | minFrequency = 0; 107 | maxFrequency = samplingFrequency/2; 108 | 109 | calculateMelFilterBank(); 110 | } 111 | 112 | 113 | 114 | //================================================================== 115 | template 116 | std::vector MFCC::discreteCosineTransform(std::vector inputSignal) 117 | { 118 | std::vector outputSignal(inputSignal.size()); 119 | 120 | T N = (T) inputSignal.size(); 121 | T piOverN = M_PI / N; 122 | 123 | for (int k = 0;k < outputSignal.size();k++) 124 | { 125 | T sum = 0; 126 | T kVal = (T) k; 127 | 128 | for (int n = 0;n < inputSignal.size();n++) 129 | { 130 | T tmp = piOverN * (((T)n)+0.5) * kVal; 131 | 132 | sum += inputSignal[n]*cos(tmp); 133 | } 134 | 135 | outputSignal[k] = (T) (2*sum); 136 | } 137 | 138 | return outputSignal; 139 | } 140 | 141 | 142 | 143 | //================================================================== 144 | template 145 | void MFCC::calculateMelFilterBank() 146 | { 147 | int maxMel = floor(frequencyToMel(maxFrequency)); 148 | int minMel = floor(frequencyToMel(minFrequency)); 149 | 150 | filterBank.resize(numCoefficents); 151 | 152 | for (int i = 0;i < numCoefficents;i++) 153 | { 154 | filterBank[i].resize(magnitudeSpectrumSize); 155 | 156 | for (int j = 0;j < magnitudeSpectrumSize;j++) 157 | { 158 | filterBank[i][j] = 0.0; 159 | } 160 | } 161 | 162 | std::vector centreIndices; 163 | 164 | for (int i = 0;i < numCoefficents + 2;i++) 165 | { 166 | double f = i * (maxMel - minMel) / (numCoefficents + 1) + minMel; 167 | 168 | double tmp = log(1 + 1000.0 / 700.0) / 1000.0; 169 | tmp = (exp(f * tmp) - 1) / 22050; 170 | 171 | tmp = 0.5 + 700 * ((double)magnitudeSpectrumSize) * tmp; 172 | 173 | tmp = floor(tmp); 174 | 175 | int centreIndex = (int) tmp; 176 | 177 | centreIndices.push_back(centreIndex); 178 | } 179 | 180 | for (int i = 0;i < numCoefficents;i++) 181 | { 182 | int filterBeginIndex = centreIndices[i]; 183 | int filterCenterIndex = centreIndices[i+1]; 184 | int filterEndIndex = centreIndices[i+2]; 185 | 186 | T triangleRangeUp = (T)(filterCenterIndex - filterBeginIndex); 187 | T triangleRangeDown = (T)(filterEndIndex - filterCenterIndex); 188 | 189 | // upward slope 190 | for (int k = filterBeginIndex;k < filterCenterIndex;k++) 191 | { 192 | filterBank[i][k] = ((T)(k-filterBeginIndex)) / triangleRangeUp; 193 | } 194 | 195 | // downwards slope 196 | for (int k = filterCenterIndex;k < filterEndIndex;k++) 197 | { 198 | filterBank[i][k] = ((T)(filterEndIndex - k)) / triangleRangeDown; 199 | } 200 | } 201 | 202 | } 203 | 204 | //================================================================== 205 | template 206 | T MFCC::frequencyToMel(T frequency) 207 | { 208 | return int(1127) * log(1 + (frequency / 700.0)); 209 | } 210 | 211 | 212 | //=========================================================== 213 | template class MFCC; 214 | template class MFCC; -------------------------------------------------------------------------------- /libs/Gist/src/pitch/Yin.cpp: -------------------------------------------------------------------------------- 1 | //======================================================================= 2 | /** @file Yin.cpp 3 | * @brief Implementation of the YIN pitch detection algorithm (de Cheveigné and Kawahara) 4 | * @author Adam Stark 5 | * @copyright Copyright (C) 2013 Adam Stark 6 | * 7 | * This file is part of the 'Gist' audio analysis library 8 | * 9 | * This program is free software: you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as published by 11 | * the Free Software Foundation, either version 3 of the License, or 12 | * (at your option) any later version. 13 | * 14 | * This program is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | * GNU General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public License 20 | * along with this program. If not, see . 21 | */ 22 | //======================================================================= 23 | 24 | #include "Yin.h" 25 | 26 | //=========================================================== 27 | template 28 | Yin::Yin(int samplingFrequency) 29 | { 30 | setSamplingFrequency(samplingFrequency); 31 | 32 | setMaxFrequency(1500); 33 | 34 | prevPeriodEstimate = 1.0; 35 | } 36 | 37 | //=========================================================== 38 | template 39 | void Yin::setSamplingFrequency(int samplingFrequency) 40 | { 41 | int oldFs = fs; 42 | 43 | fs = samplingFrequency; 44 | 45 | minPeriod = ((float) fs) / ((float) oldFs) * minPeriod; 46 | } 47 | 48 | //=========================================================== 49 | template 50 | void Yin::setMaxFrequency(T maxFreq) 51 | { 52 | T minPeriodFloating; 53 | 54 | // if maxFrequency is zero or less than 200Hz, assume a bug 55 | // and set it to an arbitrary value fo 2000Hz 56 | if (maxFreq <= 200) 57 | { 58 | maxFreq = 2000.; 59 | } 60 | 61 | minPeriodFloating = ((T) fs) / maxFreq; 62 | 63 | minPeriod = (int) ceil(minPeriodFloating); 64 | } 65 | 66 | //=========================================================== 67 | template 68 | T Yin::pitchYin(std::vector frame) 69 | { 70 | unsigned long period; 71 | T fPeriod; 72 | 73 | // steps 1, 2 and 3 of the Yin algorithm 74 | // get the difference function ("delta") 75 | //std::vector delta = cumulativeMeanNormalisedDifferenceFunction(&frame[0],frame.size()); 76 | cumulativeMeanNormalisedDifferenceFunction(&frame[0],frame.size()); 77 | 78 | // first, see if the previous period estimate has a minima 79 | long continuityPeriod = searchForOtherRecentMinima(delta); 80 | 81 | // if there is no minima at the previous period estimate 82 | if (continuityPeriod == -1) 83 | { 84 | // then estimate the period from the function 85 | period = getPeriodCandidate(delta); 86 | } 87 | else // if there was a minima at the previous period estimate 88 | { 89 | // go with that 90 | period = (unsigned long)continuityPeriod; 91 | } 92 | 93 | // check that we can interpolate (i.e. that period isn't first or last element) 94 | if ((period > 0) && (period < (delta.size()-1))) 95 | { 96 | // parabolic interpolation 97 | fPeriod = parabolicInterpolation(period,delta[period-1],delta[period],delta[period+1]); 98 | } 99 | else // if no interpolation is possible 100 | { 101 | // just use the period "as is" 102 | fPeriod = (T) period; 103 | } 104 | 105 | // store the previous period estimate for later 106 | prevPeriodEstimate = fPeriod; 107 | 108 | return periodToPitch(fPeriod); 109 | } 110 | 111 | //=========================================================== 112 | template 113 | void Yin::cumulativeMeanNormalisedDifferenceFunction(T *frame,unsigned long numSamples) 114 | { 115 | T cumulativeSum = 0.0; 116 | 117 | //std::vector delta; 118 | unsigned long L = numSamples/2; 119 | 120 | delta.resize(L); 121 | 122 | T *deltaPointer = &delta[0]; 123 | 124 | // for each time lag tau 125 | for (int tau = 0;tau < L;tau++) 126 | { 127 | *deltaPointer = 0.0; 128 | 129 | // sum all squared differences for all samples up to half way through 130 | // the frame between the sample and the sample 'tau' samples away 131 | for (int j = 0;j < L;j++) 132 | { 133 | T diff = frame[j] - frame[j+tau]; 134 | *deltaPointer += (diff*diff); 135 | } 136 | 137 | // calculate the cumulative sum of tau values to date 138 | cumulativeSum = cumulativeSum + delta[tau]; 139 | 140 | if (cumulativeSum > 0) 141 | { 142 | *deltaPointer = *deltaPointer *tau / cumulativeSum; 143 | } 144 | 145 | deltaPointer++; 146 | } 147 | 148 | // set the first element to zero 149 | delta[0] = 1.; 150 | } 151 | 152 | //=========================================================== 153 | template 154 | unsigned long Yin::getPeriodCandidate(std::vector delta) 155 | { 156 | unsigned long minPeriod = 30; 157 | unsigned long period; 158 | 159 | T thresh = 0.1; 160 | 161 | std::vector candidates; 162 | 163 | T minVal = 100000; 164 | unsigned long minInd = 0; 165 | 166 | for (unsigned long i = minPeriod;i < (delta.size()-1);i++) 167 | { 168 | if (delta[i] < minVal) 169 | { 170 | minVal = delta[i]; 171 | minInd = i; 172 | } 173 | 174 | if (delta[i] < thresh) 175 | { 176 | if ((delta[i] < delta[i-1]) && (delta[i] < delta[i+1])) 177 | { 178 | candidates.push_back(i); 179 | } 180 | } 181 | } 182 | 183 | if (candidates.size() == 0) 184 | { 185 | period = minInd; 186 | } 187 | else 188 | { 189 | period = candidates[0]; 190 | } 191 | 192 | return period; 193 | } 194 | 195 | //=========================================================== 196 | template 197 | T Yin::parabolicInterpolation(unsigned long period,T y1,T y2,T y3) 198 | { 199 | // if all elements are the same, our interpolation algorithm 200 | // will end up with a divide-by-zero, so just return the original 201 | // period without interpolation 202 | if ((y3 == y2) && (y2 == y1)) 203 | { 204 | return (T) period; 205 | } 206 | else 207 | { 208 | T newPeriod = ((T)period) + (y3-y1) / (2. * (2* y2-y3-y1)); 209 | 210 | return newPeriod; 211 | } 212 | } 213 | 214 | //=========================================================== 215 | template 216 | long Yin::searchForOtherRecentMinima(std::vector delta) 217 | { 218 | long newMinima = -1; 219 | 220 | long prevEst; 221 | 222 | prevEst = (long) round(prevPeriodEstimate); 223 | 224 | for (long i = prevEst-1;i <= prevEst+1;i++) 225 | { 226 | if ((i > 0) && (i < delta.size()-1)) 227 | { 228 | if ((delta[i] < delta[i-1]) && (delta[i] < delta[i+1])) 229 | { 230 | newMinima = i; 231 | } 232 | } 233 | } 234 | 235 | return newMinima; 236 | 237 | } 238 | 239 | //=========================================================== 240 | template 241 | T Yin::periodToPitch(T period) 242 | { 243 | return ((T) fs) / period; 244 | } 245 | 246 | //=========================================================== 247 | template class Yin; 248 | template class Yin; -------------------------------------------------------------------------------- /libs/Gist/src/onset-detection-functions/OnsetDetectionFunction.cpp: -------------------------------------------------------------------------------- 1 | //======================================================================= 2 | /** @file OnsetDetectionFunction.cpp 3 | * @brief Implementations of onset detection functions 4 | * @author Adam Stark 5 | * @copyright Copyright (C) 2013 Adam Stark 6 | * 7 | * This file is part of the 'Gist' audio analysis library 8 | * 9 | * This program is free software: you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as published by 11 | * the Free Software Foundation, either version 3 of the License, or 12 | * (at your option) any later version. 13 | * 14 | * This program is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | * GNU General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public License 20 | * along with this program. If not, see . 21 | */ 22 | //======================================================================= 23 | 24 | #include "OnsetDetectionFunction.h" 25 | 26 | //=========================================================== 27 | template 28 | OnsetDetectionFunction::OnsetDetectionFunction(int frameSize) 29 | { 30 | // initialise buffers with the frame size 31 | setFrameSize(frameSize); 32 | } 33 | 34 | //=========================================================== 35 | template 36 | void OnsetDetectionFunction::setFrameSize(int frameSize) 37 | { 38 | // resize the prev magnitude spectrum vector 39 | prevMagnitudeSpectrum_spectralDifference.resize(frameSize); 40 | prevMagnitudeSpectrum_spectralDifferenceHWR.resize(frameSize); 41 | prevPhaseSpectrum_complexSpectralDifference.resize(frameSize); 42 | prevPhaseSpectrum2_complexSpectralDifference.resize(frameSize); 43 | prevMagnitudeSpectrum_complexSpectralDifference.resize(frameSize); 44 | 45 | // fill it with zeros 46 | for (int i = 0;i < prevMagnitudeSpectrum_spectralDifference.size();i++) 47 | { 48 | prevMagnitudeSpectrum_spectralDifference[i] = 0.0; 49 | prevMagnitudeSpectrum_spectralDifferenceHWR[i] = 0.0; 50 | prevPhaseSpectrum_complexSpectralDifference[i] = 0.0; 51 | prevPhaseSpectrum2_complexSpectralDifference[i] = 0.0; 52 | prevMagnitudeSpectrum_complexSpectralDifference[i] = 0.0; 53 | } 54 | 55 | prevEnergySum = 0; 56 | } 57 | 58 | //----------------------------------------------------------- 59 | //----------------------------------------------------------- 60 | 61 | //=========================================================== 62 | template 63 | T OnsetDetectionFunction::energyDifference(std::vector buffer) 64 | { 65 | T sum; 66 | T difference; 67 | 68 | sum = 0; // initialise sum 69 | 70 | // sum the squares of the samples 71 | for (int i = 0;i < buffer.size();i++) 72 | { 73 | sum = sum + (buffer[i]*buffer[i]); 74 | } 75 | 76 | difference = sum - prevEnergySum; // sample is first order difference in energy 77 | 78 | prevEnergySum = sum; // store energy value for next calculation 79 | 80 | if (difference > 0) 81 | { 82 | return difference; 83 | } 84 | else 85 | { 86 | return 0.0; 87 | } 88 | } 89 | 90 | //=========================================================== 91 | template 92 | T OnsetDetectionFunction::spectralDifference(std::vector magnitudeSpectrum) 93 | { 94 | T sum = 0; // initialise sum to zero 95 | 96 | for (int i = 0;i < magnitudeSpectrum.size();i++) 97 | { 98 | // calculate difference 99 | T diff = magnitudeSpectrum[i] - prevMagnitudeSpectrum_spectralDifference[i]; 100 | 101 | // ensure all difference values are positive 102 | if (diff < 0) 103 | { 104 | diff = diff*-1; 105 | } 106 | 107 | // add difference to sum 108 | sum = sum+diff; 109 | 110 | // store the sample for next time 111 | prevMagnitudeSpectrum_spectralDifference[i] = magnitudeSpectrum[i]; 112 | } 113 | 114 | return sum; 115 | } 116 | 117 | //=========================================================== 118 | template 119 | T OnsetDetectionFunction::spectralDifferenceHWR(std::vector magnitudeSpectrum) 120 | { 121 | T sum = 0; // initialise sum to zero 122 | 123 | for (int i = 0;i < magnitudeSpectrum.size();i++) 124 | { 125 | // calculate difference 126 | T diff = magnitudeSpectrum[i] - prevMagnitudeSpectrum_spectralDifferenceHWR[i]; 127 | 128 | // only for positive changes 129 | if (diff > 0) 130 | { 131 | // add difference to sum 132 | sum = sum+diff; 133 | } 134 | 135 | // store the sample for next time 136 | prevMagnitudeSpectrum_spectralDifferenceHWR[i] = magnitudeSpectrum[i]; 137 | } 138 | 139 | return sum; 140 | } 141 | 142 | //=========================================================== 143 | template 144 | T OnsetDetectionFunction::complexSpectralDifference(std::vector fftReal,std::vector fftImag) 145 | { 146 | T dev,pdev; 147 | T sum; 148 | T magDiff,phaseDiff; 149 | T value; 150 | T phaseVal; 151 | T magVal; 152 | 153 | sum = 0; // initialise sum to zero 154 | 155 | // compute phase values from fft output and sum deviations 156 | for (int i = 0;i < fftReal.size();i++) 157 | { 158 | // calculate phase value 159 | phaseVal = atan2(fftImag[i],fftReal[i]); 160 | 161 | // calculate magnitude value 162 | magVal = sqrt((fftReal[i]*fftReal[i]) + (fftImag[i]*fftImag[i])); 163 | 164 | // phase deviation 165 | dev = phaseVal - (2*prevPhaseSpectrum_complexSpectralDifference[i]) + prevPhaseSpectrum2_complexSpectralDifference[i]; 166 | 167 | // wrap into [-pi,pi] range 168 | pdev = princarg(dev); 169 | 170 | 171 | // calculate magnitude difference (real part of Euclidean distance between complex frames) 172 | magDiff = magVal - prevMagnitudeSpectrum_complexSpectralDifference[i]; 173 | 174 | // calculate phase difference (imaginary part of Euclidean distance between complex frames) 175 | phaseDiff = -magVal*sin(pdev); 176 | 177 | // square real and imaginary parts, sum and take square root 178 | value = sqrt((magDiff*magDiff) + (phaseDiff*phaseDiff)); 179 | 180 | // add to sum 181 | sum = sum + value; 182 | 183 | // store values for next calculation 184 | prevPhaseSpectrum2_complexSpectralDifference[i] = prevPhaseSpectrum_complexSpectralDifference[i]; 185 | prevPhaseSpectrum_complexSpectralDifference[i] = phaseVal; 186 | prevMagnitudeSpectrum_complexSpectralDifference[i] = magVal; 187 | } 188 | 189 | return sum; 190 | } 191 | 192 | //=========================================================== 193 | template 194 | T OnsetDetectionFunction::highFrequencyContent(std::vector magnitudeSpectrum) 195 | { 196 | T sum; 197 | 198 | sum = 0; // initialise sum to zero 199 | 200 | for (int i = 0;i < magnitudeSpectrum.size();i++) 201 | { 202 | sum += (magnitudeSpectrum[i]*((T) (i+1))); 203 | } 204 | 205 | return sum; 206 | } 207 | 208 | //=========================================================== 209 | template 210 | T OnsetDetectionFunction::princarg(T phaseVal) 211 | { 212 | // if phase value is less than or equal to -pi then add 2*pi 213 | while (phaseVal <= (-M_PI)) 214 | { 215 | phaseVal = phaseVal + (2*M_PI); 216 | } 217 | 218 | // if phase value is larger than pi, then subtract 2*pi 219 | while (phaseVal > M_PI) 220 | { 221 | phaseVal = phaseVal - (2*M_PI); 222 | } 223 | 224 | return phaseVal; 225 | } 226 | 227 | //=========================================================== 228 | template class OnsetDetectionFunction; 229 | template class OnsetDetectionFunction; -------------------------------------------------------------------------------- /src/ofxGist.h: -------------------------------------------------------------------------------- 1 | /* 2 | * ofxGist.h 3 | * Gist 4 | * 5 | * Created by Andreas Borg on 30/03/2015 6 | * Copyright 2015 Local Projects. All rights reserved. 7 | * 8 | * Wrapper of Adam Stark's Gist 9 | * Gist is a C++ based audio analysis library, written for use in real-time applications. 10 | * 11 | * http://www.adamstark.co.uk/sound-analyser/ 12 | * 13 | * https://github.com/adamstark/Gist 14 | */ 15 | 16 | #ifndef _ofxGist 17 | #define _ofxGist 18 | 19 | #include "ofMain.h" 20 | 21 | /* Use KISS Fast Fourier Transform */ 22 | //needs to be included before Gist..also make sure there is only one kiss instance in your project 23 | #define USE_KISS_FFT 24 | 25 | #include "Gist.h" 26 | 27 | 28 | 29 | 30 | 31 | /* 32 | 33 | Spectral Difference, derivate, shows the amount of change…effectively onset 34 | 35 | Spectral Crest - How tonal the signal is, useful for distinguishing instuments 36 | 37 | Spectral Centroid - Correlates to the brightness of the sound 38 | 39 | Mel-frequency spectrum - Human perception FFT 40 | 41 | Zero Crossing Rate - Sound brightness 42 | 43 | Root mean square - Signal energy 44 | 45 | */ 46 | 47 | 48 | //TODO : MFCC and spectral non float values 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | typedef enum GIST_FEATURE{ 58 | GIST_PITCH, 59 | GIST_NOTE, 60 | GIST_ROOT_MEAN_SQUARE, 61 | GIST_PEAK_ENERGY, 62 | GIST_SPECTRAL_CREST, 63 | GIST_ZERO_CROSSING_RATE, 64 | GIST_SPECTRAL_CENTROID, 65 | GIST_SPECTRAL_FLATNESS, 66 | GIST_SPECTRAL_DIFFERENCE, 67 | GIST_SPECTRAL_DIFFERENCE_COMPLEX, 68 | GIST_SPECTRAL_DIFFERENCE_HALFWAY, 69 | GIST_HIGH_FREQUENCY_CONTENT 70 | 71 | }GIST_FEATURE; 72 | 73 | class GistEvent : public ofEventArgs { 74 | 75 | public: 76 | 77 | GistEvent(){}; 78 | float energy; 79 | float frequency; 80 | float note; 81 | float onsetAmount; 82 | GIST_FEATURE feature;//onset_detection feature that triggered event 83 | 84 | 85 | //these are global to keep all in sync 86 | static ofEvent ON; 87 | static ofEvent OFF; 88 | 89 | 90 | }; 91 | 92 | 93 | 94 | 95 | #define GIST_DEFAULT_SAMPLING_FREQUENCY 44100 96 | #define GIST_DEFAULT_BUFFERSIZE 512 97 | 98 | class ofxGist { 99 | 100 | public: 101 | 102 | 103 | //If you add _GIST_FEATURE above make sure to add here 104 | static vectorgetFeatureNames(){ 105 | 106 | if(ofxGist::_featureNames.size()){ 107 | return ofxGist::_featureNames; 108 | } 109 | stringstream str; 110 | 111 | str<<"GIST_PITCH,"; 112 | str<<"GIST_NOTE,"; 113 | str<<"GIST_ROOT_MEAN_SQUARE,"; 114 | str<<"GIST_PEAK_ENERGY,"; 115 | str<<"GIST_SPECTRAL_CREST,"; 116 | str<<"GIST_ZERO_CROSSING_RATE,"; 117 | str<<"GIST_SPECTRAL_CENTROID,"; 118 | str<<"GIST_SPECTRAL_FLATNESS,"; 119 | str<<"GIST_SPECTRAL_DIFFERENCE,"; 120 | str<<"GIST_SPECTRAL_DIFFERENCE_COMPLEX,"; 121 | str<<"GIST_SPECTRAL_DIFFERENCE_HALFWAY,"; 122 | str<<"GIST_HIGH_FREQUENCY_CONTENT"; 123 | 124 | 125 | ofxGist::_featureNames = ofSplitString(str.str(),","); 126 | return ofxGist::_featureNames; 127 | }; 128 | 129 | 130 | static GIST_FEATURE getFeatureFromName(string n){ 131 | 132 | init(); 133 | 134 | 135 | for ( int it = 0; it != ofxGist::getFeatureNames().size(); it++ ){ 136 | if(ofxGist::getFeatureNames()[it] == n){ 137 | GIST_FEATURE feature = static_cast(it); 138 | return feature; 139 | } 140 | 141 | 142 | } 143 | 144 | ofLogWarning()<<"ofGist feature "<(0); 146 | 147 | } 148 | 149 | 150 | ofxGist():gist(GIST_DEFAULT_BUFFERSIZE,GIST_DEFAULT_SAMPLING_FREQUENCY){ 151 | setup(); 152 | }; 153 | 154 | void setup(){ 155 | ofxGist::init(); 156 | 157 | _defaultSampleRate = GIST_DEFAULT_SAMPLING_FREQUENCY; 158 | _defaultBufferSize = GIST_DEFAULT_BUFFERSIZE; 159 | 160 | _isNoteOn = 0; 161 | 162 | gist.setAudioFrameSize(_defaultBufferSize); 163 | 164 | //not detecting anything by default 165 | for(GIST_FEATURE feature:_features){ 166 | _doDetect[feature] = 0; 167 | _useForOnsetDetection[feature] = 0; 168 | _thresholds[feature]=0; 169 | } 170 | 171 | 172 | 173 | //some near guess defaults 174 | _thresholds[GIST_SPECTRAL_DIFFERENCE_COMPLEX] = .5; 175 | 176 | 177 | clearHistory(); 178 | 179 | _calculateMFCC = false; 180 | } 181 | 182 | void processAudio(const vector& input, int bufferSize = 512, int nChannels = 2,int sampleRate = 44100); 183 | 184 | 185 | void setDetect(GIST_FEATURE,bool b = true); 186 | bool getDetect(GIST_FEATURE f); 187 | 188 | 189 | void setUseForOnsetDetection(GIST_FEATURE,bool b = true); 190 | bool getUseForOnsetDetection(GIST_FEATURE f); 191 | 192 | 193 | float getValue(GIST_FEATURE f); 194 | float getValue(int f);//will be cast to enum 195 | 196 | 197 | float getMin(GIST_FEATURE f); 198 | float getMin(int f);//will be cast to enum 199 | 200 | float getMax(GIST_FEATURE f); 201 | float getMax(int f);//will be cast to enum 202 | 203 | 204 | float getAvg(GIST_FEATURE f); 205 | float getAvg(int f);//will be cast to enum 206 | 207 | 208 | //used for onset detection events 209 | 210 | void setThreshold(GIST_FEATURE f, float t); 211 | float getThreshold(GIST_FEATURE f); 212 | float getThreshold(int f);//will be cast to enum 213 | 214 | 215 | void clearHistory();//min/max etc 216 | 217 | 218 | 219 | 220 | float getNoteFrequency();//midi value 221 | float frequencyToMidi(float freq); 222 | string getNoteName(); 223 | 224 | /* 225 | 226 | In sound processing, the mel-frequency cepstrum (MFC) is a representation of the short-term power spectrum of a sound, based on a linear cosine transform of a log power spectrum on a nonlinear mel scale of frequency. 227 | 228 | Mel-frequency cepstral coefficients (MFCCs) are coefficients that collectively make up an MFC. They are derived from a type of cepstral representation of the audio clip (a nonlinear "spectrum-of-a-spectrum"). The difference between the cepstrum and the mel-frequency cepstrum is that in the MFC, the frequency bands are equally spaced on the mel scale, which approximates the human auditory system's response more closely than the linearly-spaced frequency bands used in the normal cepstrum. This frequency warping can allow for better representation of sound, for example, in audio compression. 229 | 230 | MFCCs are commonly derived as follows:[1][2] 231 | 232 | Take the Fourier transform of (a windowed excerpt of) a signal. 233 | Map the powers of the spectrum obtained above onto the mel scale, using triangular overlapping windows. 234 | Take the logs of the powers at each of the mel frequencies. 235 | Take the discrete cosine transform of the list of mel log powers, as if it were a signal. 236 | The MFCCs are the amplitudes of the resulting spectrum. 237 | 238 | */ 239 | 240 | vector getMelFrequencySpectrum(); 241 | vector getMelFrequencyCepstralCoefficients(); 242 | 243 | 244 | float getMFCCMin(int coeffNum);//of 13 245 | float getMFCCMax(int coeffNum); 246 | float getMFCCAvg(int coeffNum); 247 | 248 | 249 | 250 | protected: 251 | 252 | static void init(){ 253 | 254 | if(ofxGist::_features.size()==0){ 255 | for ( int it = 0; it != ofxGist::getFeatureNames().size(); it++ ){ 256 | GIST_FEATURE feature = static_cast(it); 257 | _features.push_back(feature); 258 | } 259 | } 260 | 261 | } 262 | 263 | 264 | 265 | 266 | void processOnsetDetection(GIST_FEATURE); 267 | 268 | 269 | int _defaultSampleRate; 270 | int _defaultBufferSize; 271 | 272 | Gist gist; 273 | 274 | 275 | bool _isNoteOn; 276 | 277 | bool _calculateMFCC; 278 | 279 | static vector_featureNames; 280 | 281 | static vector_features; 282 | map_doDetect; 283 | map_values; 284 | map_useForOnsetDetection; 285 | 286 | 287 | map_minValues; 288 | map_maxValues; 289 | map_avgValues; 290 | map_avgValueNum; 291 | 292 | 293 | vector _mfccMinValues; 294 | vector _mfccMaxValues; 295 | vector _mfccAvgValues; 296 | vector _mfccAvgValueNum; 297 | 298 | //onset delta thresholds, ie. relative change 299 | map_thresholds; 300 | map > _history;//used to track limited relative changes 301 | 302 | }; 303 | 304 | #endif 305 | -------------------------------------------------------------------------------- /libs/Stark-Plumbley/ChordDetector.cpp: -------------------------------------------------------------------------------- 1 | //======================================================================= 2 | /** @file ChordDetector.cpp 3 | * @brief ChordDetector - a class for estimating chord labels from chromagram input 4 | * @author Adam Stark 5 | * @copyright Copyright (C) 2008-2014 Queen Mary University of London 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | //======================================================================= 21 | 22 | #include "ChordDetector.h" 23 | #include 24 | 25 | //======================================================================= 26 | ChordDetector::ChordDetector() 27 | { 28 | bias = 1.06; 29 | 30 | makeChordProfiles(); 31 | 32 | } 33 | 34 | //======================================================================= 35 | void ChordDetector::detectChord(std::vector chroma) 36 | { 37 | detectChord(&chroma[0]); 38 | } 39 | 40 | //======================================================================= 41 | void ChordDetector::detectChord(double *chroma) 42 | { 43 | for (int i = 0;i < 12;i++) 44 | { 45 | chromagram[i] = chroma[i]; 46 | } 47 | 48 | classifyChromagram(); 49 | } 50 | 51 | 52 | //======================================================================= 53 | void ChordDetector::classifyChromagram() 54 | { 55 | int i; 56 | int j; 57 | int fifth; 58 | int chordindex; 59 | 60 | // remove some of the 5th note energy from chromagram 61 | for (i = 0;i < 12;i++) 62 | { 63 | fifth = (i+7) % 12; 64 | chromagram[fifth] = chromagram[fifth] - (0.1*chromagram[i]); 65 | 66 | if (chromagram[fifth] < 0) 67 | { 68 | chromagram[fifth] = 0; 69 | } 70 | 71 | } 72 | 73 | 74 | // major chords 75 | for (j=0;j < 12;j++) 76 | { 77 | chord[j] = calculateChordScore(chromagram,chordProfiles[j],bias,3); 78 | } 79 | 80 | // minor chords 81 | for (j=12;j < 24;j++) 82 | { 83 | chord[j] = calculateChordScore(chromagram,chordProfiles[j],bias,3); 84 | } 85 | 86 | // diminished 5th chords 87 | for (j=24;j < 36;j++) 88 | { 89 | chord[j] = calculateChordScore(chromagram,chordProfiles[j],bias,3); 90 | } 91 | 92 | // augmented 5th chords 93 | for (j=36;j < 48;j++) 94 | { 95 | chord[j] = calculateChordScore(chromagram,chordProfiles[j],bias,3); 96 | } 97 | 98 | // sus2 chords 99 | for (j=48;j < 60;j++) 100 | { 101 | chord[j] = calculateChordScore(chromagram,chordProfiles[j],1,3); 102 | } 103 | 104 | // sus4 chords 105 | for (j=60;j < 72;j++) 106 | { 107 | chord[j] = calculateChordScore(chromagram,chordProfiles[j],1,3); 108 | } 109 | 110 | // major 7th chords 111 | for (j=72;j < 84;j++) 112 | { 113 | chord[j] = calculateChordScore(chromagram,chordProfiles[j],1,4); 114 | } 115 | 116 | // minor 7th chords 117 | for (j=84;j < 96;j++) 118 | { 119 | chord[j] = calculateChordScore(chromagram,chordProfiles[j],bias,4); 120 | } 121 | 122 | // dominant 7th chords 123 | for (j=96;j < 108;j++) 124 | { 125 | chord[j] = calculateChordScore(chromagram,chordProfiles[j],bias,4); 126 | } 127 | 128 | chordindex = minimumIndex(chord,108); 129 | 130 | // major 131 | if (chordindex < 12) 132 | { 133 | rootNote = chordindex; 134 | quality = Major; 135 | intervals = 0; 136 | } 137 | 138 | // minor 139 | if ((chordindex >= 12) && (chordindex < 24)) 140 | { 141 | rootNote = chordindex-12; 142 | quality = Minor; 143 | intervals = 0; 144 | } 145 | 146 | // diminished 5th 147 | if ((chordindex >= 24) && (chordindex < 36)) 148 | { 149 | rootNote = chordindex-24; 150 | quality = Dimished5th; 151 | intervals = 0; 152 | } 153 | 154 | // augmented 5th 155 | if ((chordindex >= 36) && (chordindex < 48)) 156 | { 157 | rootNote = chordindex-36; 158 | quality = Augmented5th; 159 | intervals = 0; 160 | } 161 | 162 | // sus2 163 | if ((chordindex >= 48) && (chordindex < 60)) 164 | { 165 | rootNote = chordindex-48; 166 | quality = Suspended; 167 | intervals = 2; 168 | } 169 | 170 | // sus4 171 | if ((chordindex >= 60) && (chordindex < 72)) 172 | { 173 | rootNote = chordindex-60; 174 | quality = Suspended; 175 | intervals = 4; 176 | } 177 | 178 | // major 7th 179 | if ((chordindex >= 72) && (chordindex < 84)) 180 | { 181 | rootNote = chordindex-72; 182 | quality = Major; 183 | intervals = 7; 184 | } 185 | 186 | // minor 7th 187 | if ((chordindex >= 84) && (chordindex < 96)) 188 | { 189 | rootNote = chordindex-84; 190 | quality = Minor; 191 | intervals = 7; 192 | } 193 | 194 | // dominant 7th 195 | if ((chordindex >= 96) && (chordindex < 108)) 196 | { 197 | rootNote = chordindex-96; 198 | quality = Dominant; 199 | intervals = 7; 200 | } 201 | } 202 | 203 | //======================================================================= 204 | double ChordDetector::calculateChordScore(double *chroma,double *chordProfile,double biasToUse, double N) 205 | { 206 | double sum = 0; 207 | double delta; 208 | 209 | for (int i=0;i < 12;i++) 210 | { 211 | sum = sum + ((1-chordProfile[i])*(chroma[i]*chroma[i])); 212 | } 213 | 214 | delta = sqrt(sum) / ((12 - N)*biasToUse); 215 | 216 | return delta; 217 | } 218 | 219 | //======================================================================= 220 | int ChordDetector::minimumIndex(double *array,int arrayLength) 221 | { 222 | double minValue = 100000; 223 | int minIndex = 0; 224 | int i; 225 | 226 | for (i = 0;i < arrayLength;i++) 227 | { 228 | if (array[i] < minValue) 229 | { 230 | minValue = array[i]; 231 | minIndex = i; 232 | } 233 | } 234 | 235 | return minIndex; 236 | } 237 | 238 | //======================================================================= 239 | void ChordDetector::makeChordProfiles() 240 | { 241 | int i; 242 | int t; 243 | int j = 0; 244 | int root; 245 | int third; 246 | int fifth; 247 | int seventh; 248 | 249 | double v1 = 1; 250 | double v2 = 1; 251 | double v3 = 1; 252 | 253 | // set profiles matrix to all zeros 254 | for (j = 0;j < 108;j++) 255 | { 256 | for (t = 0;t < 12;t++) 257 | { 258 | chordProfiles[j][t] = 0; 259 | } 260 | } 261 | 262 | // reset j to zero to begin creating profiles 263 | j = 0; 264 | 265 | // major chords 266 | for (i = 0;i < 12;i++) 267 | { 268 | root = i % 12; 269 | third = (i+4) % 12; 270 | fifth = (i+7) % 12; 271 | 272 | chordProfiles[j][root] = v1; 273 | chordProfiles[j][third] = v2; 274 | chordProfiles[j][fifth] = v3; 275 | 276 | j++; 277 | } 278 | 279 | // minor chords 280 | for (i = 0;i < 12;i++) 281 | { 282 | root = i % 12; 283 | third = (i+3) % 12; 284 | fifth = (i+7) % 12; 285 | 286 | chordProfiles[j][root] = v1; 287 | chordProfiles[j][third] = v2; 288 | chordProfiles[j][fifth] = v3; 289 | 290 | j++; 291 | } 292 | 293 | // diminished chords 294 | for (i = 0;i < 12;i++) 295 | { 296 | root = i % 12; 297 | third = (i+3) % 12; 298 | fifth = (i+6) % 12; 299 | 300 | chordProfiles[j][root] = v1; 301 | chordProfiles[j][third] = v2; 302 | chordProfiles[j][fifth] = v3; 303 | 304 | j++; 305 | } 306 | 307 | // augmented chords 308 | for (i = 0;i < 12;i++) 309 | { 310 | root = i % 12; 311 | third = (i+4) % 12; 312 | fifth = (i+8) % 12; 313 | 314 | chordProfiles[j][root] = v1; 315 | chordProfiles[j][third] = v2; 316 | chordProfiles[j][fifth] = v3; 317 | 318 | j++; 319 | } 320 | 321 | // sus2 chords 322 | for (i = 0;i < 12;i++) 323 | { 324 | root = i % 12; 325 | third = (i+2) % 12; 326 | fifth = (i+7) % 12; 327 | 328 | chordProfiles[j][root] = v1; 329 | chordProfiles[j][third] = v2; 330 | chordProfiles[j][fifth] = v3; 331 | 332 | j++; 333 | } 334 | 335 | // sus4 chords 336 | for (i = 0;i < 12;i++) 337 | { 338 | root = i % 12; 339 | third = (i+5) % 12; 340 | fifth = (i+7) % 12; 341 | 342 | chordProfiles[j][root] = v1; 343 | chordProfiles[j][third] = v2; 344 | chordProfiles[j][fifth] = v3; 345 | 346 | j++; 347 | } 348 | 349 | // major 7th chords 350 | for (i = 0;i < 12;i++) 351 | { 352 | root = i % 12; 353 | third = (i+4) % 12; 354 | fifth = (i+7) % 12; 355 | seventh = (i+11) % 12; 356 | 357 | chordProfiles[j][root] = v1; 358 | chordProfiles[j][third] = v2; 359 | chordProfiles[j][fifth] = v3; 360 | chordProfiles[j][seventh] = v3; 361 | 362 | j++; 363 | } 364 | 365 | // minor 7th chords 366 | for (i = 0;i < 12;i++) 367 | { 368 | root = i % 12; 369 | third = (i+3) % 12; 370 | fifth = (i+7) % 12; 371 | seventh = (i+10) % 12; 372 | 373 | chordProfiles[j][root] = v1; 374 | chordProfiles[j][third] = v2; 375 | chordProfiles[j][fifth] = v3; 376 | chordProfiles[j][seventh] = v3; 377 | 378 | j++; 379 | } 380 | 381 | // dominant 7th chords 382 | for (i = 0;i < 12;i++) 383 | { 384 | root = i % 12; 385 | third = (i+4) % 12; 386 | fifth = (i+7) % 12; 387 | seventh = (i+10) % 12; 388 | 389 | chordProfiles[j][root] = v1; 390 | chordProfiles[j][third] = v2; 391 | chordProfiles[j][fifth] = v3; 392 | chordProfiles[j][seventh] = v3; 393 | 394 | j++; 395 | } 396 | } -------------------------------------------------------------------------------- /example/src/ofApp.cpp: -------------------------------------------------------------------------------- 1 | #include "ofApp.h" 2 | 3 | //-------------------------------------------------------------- 4 | void ofApp::setup(){ 5 | ofSetCircleResolution(80); 6 | ofSetFrameRate(60); 7 | ofBackground(255); 8 | ofEnableSmoothing(); 9 | ofEnableAlphaBlending(); 10 | ofSetVerticalSync(true); 11 | 12 | 13 | bufferSize = 512; 14 | sampleRate = 44100; 15 | 16 | 17 | 18 | 19 | useMic = 1; 20 | isPaused = 0; 21 | 22 | player.setLoop(true); 23 | 24 | mfccMax = 0; 25 | showMFCC = 0; 26 | 27 | vector features = ofxGist::getFeatureNames(); 28 | 29 | int num = features.size(); 30 | 31 | for(int v = 0;vsetShowSmoothedCurve(1); 55 | */ 56 | 57 | //gist.setUseForOnsetDetection(GIST_PEAK_ENERGY); 58 | 59 | //gist.setUseForOnsetDetection(GIST_SPECTRAL_DIFFERENCE); 60 | //gist.setThreshold(GIST_SPECTRAL_DIFFERENCE, .2); 61 | 62 | gist.setUseForOnsetDetection(GIST_PEAK_ENERGY); 63 | gist.setThreshold(GIST_PEAK_ENERGY, .05);// 64 | 65 | ofAddListener(GistEvent::ON,this,&ofApp::onNoteOn); 66 | ofAddListener(GistEvent::OFF,this,&ofApp::onNoteOff); 67 | 68 | 69 | 70 | noteOnRadius = 0; 71 | 72 | soundStream.setup(this,0, 1, sampleRate, bufferSize, 1); 73 | 74 | 75 | loadSong("assets/sounds/Coltrane_acc_VUIMM.wav"); 76 | } 77 | 78 | 79 | void ofApp::onNoteOn(GistEvent &e){ 80 | 81 | noteOnRadius = 100; 82 | }; 83 | 84 | 85 | void ofApp::onNoteOff(GistEvent &e){ 86 | 87 | //noteOnRadius = 0; 88 | }; 89 | 90 | 91 | //-------------------------------------------------------------- 92 | void ofApp::update(){ 93 | 94 | 95 | if(isPaused){ 96 | return; 97 | } 98 | if(!useMic){ 99 | if(player.isLoaded()){ 100 | vector output = player.getCurrentBuffer(bufferSize); 101 | processAudio(&output[0], bufferSize, 2); 102 | fftSmoothed = player.getFFT(); 103 | } 104 | } 105 | 106 | 107 | 108 | int num = ofxGist::getFeatureNames().size(); 109 | 110 | for(int v = 0;vsetRange(gist.getMin(v),gist.getMax(v)); 112 | plots[v]->update(gist.getValue(v)); 113 | } 114 | 115 | vectormfcc = gist.getMelFrequencyCepstralCoefficients(); 116 | 117 | //vectormfcc = gist.getMelFrequencySpectrum(); 118 | 119 | if(mfccSmoothed.size().999f){ 127 | mfccSmoothed[f] = mfcc[i]; 128 | } 129 | // let the smoothed value sink to zero: 130 | mfccSmoothed[i] *= damping; 131 | f++; 132 | 133 | if(mfccMaxsetRange(gist.getMFCCMin(i),gist.getMFCCMax(i)); 139 | 140 | mfccPlots[i]->update(mfcc[i]); 141 | } 142 | 143 | 144 | 145 | 146 | /* 147 | //crest avg 148 | plots.back()->setRange(gist.getMin(GIST_SPECTRAL_CREST),gist.getMax(GIST_SPECTRAL_CREST)); 149 | plots.back()->update(gist.getAvg(GIST_SPECTRAL_CREST)); 150 | */ 151 | 152 | 153 | if(noteOnRadius>0){ 154 | noteOnRadius--; 155 | } 156 | } 157 | 158 | //-------------------------------------------------------------- 159 | void ofApp::draw(){ 160 | ofBackground(0); 161 | 162 | 163 | 164 | 165 | 166 | // draw the left: 167 | //ofSetHexColor(0x333333); 168 | int waveHeight = ofGetHeight(); 169 | 170 | //ofRect(0,0,256,waveHeight); 171 | float barW = ofGetWidth()/(float)fftSmoothed.size(); 172 | float currX = 0; 173 | 174 | ofSetColor(255,255,255,100); 175 | for (int i = 0; i < fftSmoothed.size(); i++){ 176 | //ofLine(i,100,i,100+left[i]*waveHeight); 177 | 178 | ofRect(currX,waveHeight,barW,-fftSmoothed[i]*waveHeight); 179 | currX+=barW; 180 | } 181 | 182 | currX = 0; 183 | waveHeight = ofGetHeight(); 184 | barW = ofGetWidth()/(float)mfccSmoothed.size(); 185 | ofSetColor(255,100,100,200); 186 | for (int i = 0; i < mfccSmoothed.size() && showMFCC; i++){ 187 | //ofLine(i,100,i,100+left[i]*waveHeight); 188 | 189 | ofRect(currX,ofGetHeight(),barW,- ofMap(mfccSmoothed[i], 0.0,mfccMax, 0.0,1.0,true )*waveHeight); 190 | currX+=barW; 191 | } 192 | 193 | 194 | int num; 195 | int margin = 5; 196 | if(showMFCC){ 197 | num = mfccPlots.size(); 198 | int plotHeight = (ofGetHeight()-margin*num)/(float)num; 199 | 200 | for(int v = 0;vdraw(margin,margin+plotHeight*v, ofGetWidth()-20, 100); 202 | } 203 | }else{ 204 | 205 | 206 | num = plots.size(); 207 | 208 | int plotHeight = (ofGetHeight()-margin*num)/(float)num; 209 | 210 | for(int v = 0;vdraw(margin,margin+plotHeight*v, ofGetWidth()-20, 100); 212 | } 213 | 214 | } 215 | 216 | 217 | 218 | ofSetColor(255,0,0,200); 219 | ofCircle(ofGetWidth()/2,ofGetHeight()/2,noteOnRadius); 220 | 221 | 222 | if(!showMFCC){ 223 | 224 | 225 | ofSetColor(0,0,0,250); 226 | ofRect(5,5,600,180); 227 | stringstream str; 228 | if(plots.size() ){ 229 | for(int v = 0;vgetVariableName()<<" | min: "<setLowerRange(0); //set only the lowest part of the range upper is adaptative to curve 255 | graph->setAutoRangeShrinksBack(true); //graph2 scale can shrink back after growing if graph2 curves requires it 256 | graph->setRange(0,max); 257 | graph->setColor(color); 258 | graph->setShowNumericalInfo(true); 259 | graph->setRespectBorders(true); 260 | graph->setLineWidth(2); 261 | 262 | 263 | graph->setDrawBackground(false); 264 | 265 | graph->setDrawGrid(true); 266 | graph->setGridColor(ofColor(30)); //grid lines color 267 | graph->setGridUnit(14); 268 | graph->setShowSmoothedCurve(0); //graph2 a smoothed version of the values, but alos the original in lesser alpha 269 | graph->setSmoothFilter(0.1); //smooth filter strength 270 | 271 | graph->setMaxHistory(2000); 272 | 273 | 274 | 275 | return graph; 276 | 277 | }; 278 | 279 | 280 | void ofApp::clear(){ 281 | 282 | 283 | } 284 | 285 | 286 | void ofApp::loadSong(string str){ 287 | 288 | cout<<"loadSong "<buffer; 302 | buffer.assign(&input[0],&input[bufferSize]); 303 | 304 | gist.processAudio(buffer, bufferSize, nChannels,sampleRate); 305 | } 306 | 307 | 308 | void ofApp::audioIn(float * input, int bufferSize, int nChannels){ 309 | if(!useMic){ 310 | return; 311 | } 312 | 313 | processAudio(input, bufferSize, nChannels); 314 | 315 | } 316 | 317 | 318 | 319 | 320 | //-------------------------------------------------------------- 321 | void ofApp::keyPressed(int key){ 322 | if(key =='f'){ 323 | ofToggleFullscreen(); 324 | } 325 | 326 | if(key =='m'){ 327 | useMic = !useMic; 328 | 329 | if(!useMic){ 330 | player.play(); 331 | }else{ 332 | player.stop(); 333 | } 334 | 335 | 336 | gist.clearHistory(); 337 | } 338 | 339 | if(key ==' '){ 340 | isPaused = !isPaused; 341 | player.setPaused(isPaused); 342 | } 343 | 344 | if(key =='r'){ 345 | gist.clearHistory(); 346 | } 347 | 348 | 349 | if(key =='c'){ 350 | showMFCC = !showMFCC; 351 | } 352 | } 353 | 354 | //-------------------------------------------------------------- 355 | void ofApp::keyReleased(int key){ 356 | 357 | } 358 | 359 | //-------------------------------------------------------------- 360 | void ofApp::mouseMoved(int x, int y ){ 361 | 362 | } 363 | 364 | //-------------------------------------------------------------- 365 | void ofApp::mouseDragged(int x, int y, int button){ 366 | if(!useMic){ 367 | player.setPosition(x/(float)ofGetWidth()); 368 | } 369 | 370 | float t = x/(float)ofGetWidth(); 371 | gist.setThreshold(GIST_SPECTRAL_DIFFERENCE,t); 372 | } 373 | 374 | //-------------------------------------------------------------- 375 | void ofApp::mousePressed(int x, int y, int button){ 376 | 377 | } 378 | 379 | //-------------------------------------------------------------- 380 | void ofApp::mouseReleased(int x, int y, int button){ 381 | 382 | } 383 | 384 | //-------------------------------------------------------------- 385 | void ofApp::windowResized(int w, int h){ 386 | 387 | } 388 | 389 | //-------------------------------------------------------------- 390 | void ofApp::gotMessage(ofMessage msg){ 391 | 392 | } 393 | 394 | //-------------------------------------------------------------- 395 | void ofApp::dragEvent(ofDragInfo dragInfo){ 396 | clear(); 397 | vector paths = ofSplitString(dragInfo.files[0], "data/"); 398 | loadSong(paths[1]); 399 | 400 | } 401 | -------------------------------------------------------------------------------- /libs/Stark-Plumbley/Chromagram.cpp: -------------------------------------------------------------------------------- 1 | //======================================================================= 2 | /** @file Chromagram.cpp 3 | * @brief Chromagram - a class for calculating the chromagram in real-time 4 | * @author Adam Stark 5 | * @copyright Copyright (C) 2008-2014 Queen Mary University of London 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | //======================================================================= 21 | 22 | #include "Chromagram.h" 23 | 24 | //================================================================================== 25 | Chromagram::Chromagram(int frameSize,int fs) : referenceFrequency(130.81278265), bufferSize(8192), numHarmonics(2), numOctaves(2), numBinsToSearch(2) 26 | { 27 | // calculate note frequencies 28 | for (int i = 0;i < 12;i++) 29 | { 30 | noteFrequencies[i] = referenceFrequency*pow(2,(((float) i)/12)); 31 | } 32 | 33 | 34 | // set up FFT 35 | setupFFT(); 36 | 37 | // set buffer size 38 | buffer.resize(bufferSize); 39 | 40 | // setup chromagram vector 41 | chromagram.resize(12); 42 | 43 | // initialise chromagram 44 | for (int i = 0;i < 12;i++) 45 | { 46 | chromagram[i] = 0.0; 47 | } 48 | 49 | // setup magnitude spectrum vector 50 | magnitudeSpectrum.resize((bufferSize/2)+1); 51 | 52 | // make window function 53 | makeHammingWindow(); 54 | 55 | // set sampling frequency 56 | setSamplingFrequency(fs); 57 | 58 | // set input audio frame size 59 | setInputAudioFrameSize(frameSize); 60 | 61 | // initialise num samples counter 62 | numSamplesSinceLastCalculation = 0; 63 | 64 | // set chroma calculation interval (in samples at the input audio sampling frequency) 65 | chromaCalculationInterval = 4096; 66 | 67 | // initialise chroma ready variable 68 | chromaReady = false; 69 | 70 | } 71 | 72 | //================================================================================== 73 | Chromagram::~Chromagram() 74 | { 75 | // ------------------------------------ 76 | #ifdef USE_FFTW 77 | // destroy fft plan 78 | fftw_destroy_plan(p); 79 | 80 | fftw_free(complexIn); 81 | fftw_free(complexOut); 82 | #endif 83 | 84 | // ------------------------------------ 85 | #ifdef USE_KISS_FFT 86 | // free the Kiss FFT configuration 87 | free(cfg); 88 | 89 | delete [] fftIn; 90 | delete [] fftOut; 91 | #endif 92 | } 93 | 94 | //================================================================================== 95 | void Chromagram::processAudioFrame(double *inputAudioFrame) 96 | { 97 | // create a vector 98 | std::vector v; 99 | 100 | // use the array to initialise it 101 | v.assign(inputAudioFrame, inputAudioFrame + inputAudioFrameSize); 102 | 103 | // process the vector 104 | processAudioFrame(v); 105 | } 106 | 107 | //================================================================================== 108 | void Chromagram::processAudioFrame(std::vector inputAudioFrame) 109 | { 110 | // our default state is that the chroma is not ready 111 | chromaReady = false; 112 | 113 | // downsample the input audio frame by 4 114 | downSampleFrame(inputAudioFrame); 115 | 116 | // move samples back 117 | for (int i=0;i < bufferSize-downSampledAudioFrameSize;i++) 118 | { 119 | buffer[i] = buffer[i+downSampledAudioFrameSize]; 120 | } 121 | 122 | int n = 0; 123 | // add new samples to buffer 124 | for (int i = (bufferSize-downSampledAudioFrameSize);i < bufferSize;i++) 125 | { 126 | buffer[i] = downsampledInputAudioFrame[n]; 127 | n++; 128 | } 129 | 130 | // add number of samples from calculation 131 | numSamplesSinceLastCalculation += inputAudioFrameSize; 132 | 133 | // if we have had enough samples 134 | if (numSamplesSinceLastCalculation >= chromaCalculationInterval) 135 | { 136 | // calculate the chromagram 137 | calculateChromagram(); 138 | 139 | // reset num samples counter 140 | numSamplesSinceLastCalculation = 0; 141 | } 142 | 143 | } 144 | 145 | //================================================================================== 146 | void Chromagram::setInputAudioFrameSize(int frameSize) 147 | { 148 | inputAudioFrameSize = frameSize; 149 | 150 | downsampledInputAudioFrame.resize(inputAudioFrameSize / 4); 151 | 152 | downSampledAudioFrameSize = (int) downsampledInputAudioFrame.size(); 153 | } 154 | 155 | //================================================================================== 156 | void Chromagram::setSamplingFrequency(int fs) 157 | { 158 | samplingFrequency = fs; 159 | } 160 | 161 | //================================================================================== 162 | void Chromagram::setChromaCalculationInterval(int numSamples) 163 | { 164 | chromaCalculationInterval = numSamples; 165 | } 166 | 167 | //================================================================================== 168 | std::vector Chromagram::getChromagram() 169 | { 170 | return chromagram; 171 | } 172 | 173 | //================================================================================== 174 | bool Chromagram::isReady() 175 | { 176 | return chromaReady; 177 | } 178 | 179 | //================================================================================== 180 | void Chromagram::setupFFT() 181 | { 182 | // ------------------------------------------------------ 183 | #ifdef USE_FFTW 184 | complexIn = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * bufferSize); // complex array to hold fft data 185 | complexOut = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * bufferSize); // complex array to hold fft data 186 | p = fftw_plan_dft_1d(bufferSize, complexIn, complexOut, FFTW_FORWARD, FFTW_ESTIMATE); // FFT plan initialisation 187 | #endif 188 | 189 | // ------------------------------------------------------ 190 | #ifdef USE_KISS_FFT 191 | // initialise the fft time and frequency domain audio frame arrays 192 | fftIn = new kiss_fft_cpx[bufferSize]; 193 | fftOut = new kiss_fft_cpx[bufferSize]; 194 | cfg = kiss_fft_alloc(bufferSize,0,0,0); 195 | #endif 196 | } 197 | 198 | 199 | //================================================================================== 200 | void Chromagram::calculateChromagram() 201 | { 202 | calculateMagnitudeSpectrum(); 203 | 204 | double divisorRatio = (((double) samplingFrequency) / 4.0)/((double)bufferSize); 205 | 206 | for (int n = 0;n < 12;n++) 207 | { 208 | double chromaSum = 0.0; 209 | 210 | for (int octave = 1; octave <= numOctaves;octave++) 211 | { 212 | double noteSum = 0.0; 213 | 214 | for (int harmonic = 1;harmonic <= numHarmonics;harmonic++) 215 | { 216 | int centerBin = round((noteFrequencies[n]*octave*harmonic)/divisorRatio); 217 | int minBin = centerBin - (numBinsToSearch*harmonic); 218 | int maxBin = centerBin + (numBinsToSearch*harmonic); 219 | 220 | double maxVal = 0.0; 221 | 222 | for (int k = minBin;k < maxBin;k++) 223 | { 224 | if (magnitudeSpectrum[k] > maxVal) 225 | { 226 | maxVal = magnitudeSpectrum[k]; 227 | } 228 | } 229 | 230 | noteSum += (maxVal / (double) harmonic); 231 | } 232 | 233 | chromaSum += noteSum; 234 | } 235 | 236 | chromagram[n] = chromaSum; 237 | } 238 | 239 | chromaReady = true; 240 | } 241 | 242 | //================================================================================== 243 | void Chromagram::calculateMagnitudeSpectrum() 244 | { 245 | 246 | #ifdef USE_FFTW 247 | // ----------------------------------------------- 248 | // FFTW VERSION 249 | // ----------------------------------------------- 250 | int i = 0; 251 | 252 | for (int i = 0;i < bufferSize;i++) 253 | { 254 | complexIn[i][0] = buffer[i] * window[i]; 255 | complexIn[i][1] = 0.0; 256 | } 257 | 258 | // execute fft plan, i.e. compute fft of buffer 259 | fftw_execute(p); 260 | 261 | // compute first (N/2)+1 mag values 262 | for (i = 0;i < (bufferSize/2)+1;i++) 263 | { 264 | magnitudeSpectrum[i] = sqrt(pow(complexOut[i][0],2) + pow(complexOut[i][1],2)); 265 | magnitudeSpectrum[i] = sqrt(magnitudeSpectrum[i]); 266 | } 267 | #endif 268 | 269 | 270 | #ifdef USE_KISS_FFT 271 | // ----------------------------------------------- 272 | // KISS FFT VERSION 273 | // ----------------------------------------------- 274 | int i = 0; 275 | 276 | for (int i = 0;i < bufferSize;i++) 277 | { 278 | fftIn[i].r = buffer[i] * window[i]; 279 | fftIn[i].i = 0.0; 280 | } 281 | 282 | // execute kiss fft 283 | kiss_fft(cfg, fftIn, fftOut); 284 | 285 | // compute first (N/2)+1 mag values 286 | for (i = 0;i < (bufferSize/2)+1;i++) 287 | { 288 | magnitudeSpectrum[i] = sqrt(pow(fftOut[i].r,2) + pow(fftOut[i].i,2)); 289 | magnitudeSpectrum[i] = sqrt(magnitudeSpectrum[i]); 290 | } 291 | #endif 292 | } 293 | 294 | //================================================================================== 295 | void Chromagram::downSampleFrame(std::vector inputAudioFrame) 296 | { 297 | std::vector filteredFrame(inputAudioFrameSize); 298 | 299 | float b0,b1,b2,a1,a2; 300 | float x_1,x_2,y_1,y_2; 301 | 302 | b0 = 0.2929; 303 | b1 = 0.5858; 304 | b2 = 0.2929; 305 | a1 = -0.0000; 306 | a2 = 0.1716; 307 | 308 | x_1 = 0; 309 | x_2 = 0; 310 | y_1 = 0; 311 | y_2 = 0; 312 | 313 | for (int i=0;i < inputAudioFrameSize;i++) 314 | { 315 | filteredFrame[i] = inputAudioFrame[i]*b0 + x_1*b1 + x_2*b2 - y_1*a1 - y_2*a2; 316 | 317 | x_2 = x_1; 318 | x_1 = inputAudioFrame[i]; 319 | y_2 = y_1; 320 | y_1 = filteredFrame[i]; 321 | } 322 | 323 | for (int i=0;i < inputAudioFrameSize/4;i++) 324 | { 325 | downsampledInputAudioFrame[i] = filteredFrame[i*4]; 326 | } 327 | } 328 | //================================================================================== 329 | void Chromagram::makeHammingWindow() 330 | { 331 | // set the window to the correct size 332 | window.resize(bufferSize); 333 | 334 | // apply hanning window to buffer 335 | for (int n = 0; n < bufferSize;n++) 336 | { 337 | window[n] = 0.54 - 0.46*cos(2*M_PI*(((double) n)/((double) bufferSize))); 338 | } 339 | } -------------------------------------------------------------------------------- /libs/kiss_fft130/kissfft.hh: -------------------------------------------------------------------------------- 1 | #ifndef KISSFFT_CLASS_HH 2 | #include 3 | #include 4 | 5 | namespace kissfft_utils { 6 | 7 | template 8 | struct traits 9 | { 10 | typedef T_scalar scalar_type; 11 | typedef std::complex cpx_type; 12 | void fill_twiddles( std::complex * dst ,int nfft,bool inverse) 13 | { 14 | T_scalar phinc = (inverse?2:-2)* acos( (T_scalar) -1) / nfft; 15 | for (int i=0;i(0,i*phinc) ); 17 | } 18 | 19 | void prepare( 20 | std::vector< std::complex > & dst, 21 | int nfft,bool inverse, 22 | std::vector & stageRadix, 23 | std::vector & stageRemainder ) 24 | { 25 | _twiddles.resize(nfft); 26 | fill_twiddles( &_twiddles[0],nfft,inverse); 27 | dst = _twiddles; 28 | 29 | //factorize 30 | //start factoring out 4's, then 2's, then 3,5,7,9,... 31 | int n= nfft; 32 | int p=4; 33 | do { 34 | while (n % p) { 35 | switch (p) { 36 | case 4: p = 2; break; 37 | case 2: p = 3; break; 38 | default: p += 2; break; 39 | } 40 | if (p*p>n) 41 | p=n;// no more factors 42 | } 43 | n /= p; 44 | stageRadix.push_back(p); 45 | stageRemainder.push_back(n); 46 | }while(n>1); 47 | } 48 | std::vector _twiddles; 49 | 50 | 51 | const cpx_type twiddle(int i) { return _twiddles[i]; } 52 | }; 53 | 54 | } 55 | 56 | template 58 | > 59 | class kissfft 60 | { 61 | public: 62 | typedef T_traits traits_type; 63 | typedef typename traits_type::scalar_type scalar_type; 64 | typedef typename traits_type::cpx_type cpx_type; 65 | 66 | kissfft(int nfft,bool inverse,const traits_type & traits=traits_type() ) 67 | :_nfft(nfft),_inverse(inverse),_traits(traits) 68 | { 69 | _traits.prepare(_twiddles, _nfft,_inverse ,_stageRadix, _stageRemainder); 70 | } 71 | 72 | void transform(const cpx_type * src , cpx_type * dst) 73 | { 74 | kf_work(0, dst, src, 1,1); 75 | } 76 | 77 | private: 78 | void kf_work( int stage,cpx_type * Fout, const cpx_type * f, size_t fstride,size_t in_stride) 79 | { 80 | int p = _stageRadix[stage]; 81 | int m = _stageRemainder[stage]; 82 | cpx_type * Fout_beg = Fout; 83 | cpx_type * Fout_end = Fout + p*m; 84 | 85 | if (m==1) { 86 | do{ 87 | *Fout = *f; 88 | f += fstride*in_stride; 89 | }while(++Fout != Fout_end ); 90 | }else{ 91 | do{ 92 | // recursive call: 93 | // DFT of size m*p performed by doing 94 | // p instances of smaller DFTs of size m, 95 | // each one takes a decimated version of the input 96 | kf_work(stage+1, Fout , f, fstride*p,in_stride); 97 | f += fstride*in_stride; 98 | }while( (Fout += m) != Fout_end ); 99 | } 100 | 101 | Fout=Fout_beg; 102 | 103 | // recombine the p smaller DFTs 104 | switch (p) { 105 | case 2: kf_bfly2(Fout,fstride,m); break; 106 | case 3: kf_bfly3(Fout,fstride,m); break; 107 | case 4: kf_bfly4(Fout,fstride,m); break; 108 | case 5: kf_bfly5(Fout,fstride,m); break; 109 | default: kf_bfly_generic(Fout,fstride,m,p); break; 110 | } 111 | } 112 | 113 | // these were #define macros in the original kiss_fft 114 | void C_ADD( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a+b;} 115 | void C_MUL( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a*b;} 116 | void C_SUB( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a-b;} 117 | void C_ADDTO( cpx_type & c,const cpx_type & a) { c+=a;} 118 | void C_FIXDIV( cpx_type & ,int ) {} // NO-OP for float types 119 | scalar_type S_MUL( const scalar_type & a,const scalar_type & b) { return a*b;} 120 | scalar_type HALF_OF( const scalar_type & a) { return a*.5;} 121 | void C_MULBYSCALAR(cpx_type & c,const scalar_type & a) {c*=a;} 122 | 123 | void kf_bfly2( cpx_type * Fout, const size_t fstride, int m) 124 | { 125 | for (int k=0;kreal() - HALF_OF(scratch[3].real() ) , Fout->imag() - HALF_OF(scratch[3].imag() ) ); 177 | 178 | C_MULBYSCALAR( scratch[0] , epi3.imag() ); 179 | 180 | C_ADDTO(*Fout,scratch[3]); 181 | 182 | Fout[m2] = cpx_type( Fout[m].real() + scratch[0].imag() , Fout[m].imag() - scratch[0].real() ); 183 | 184 | C_ADDTO( Fout[m] , cpx_type( -scratch[0].imag(),scratch[0].real() ) ); 185 | ++Fout; 186 | }while(--k); 187 | } 188 | 189 | void kf_bfly5( cpx_type * Fout, const size_t fstride, const size_t m) 190 | { 191 | cpx_type *Fout0,*Fout1,*Fout2,*Fout3,*Fout4; 192 | size_t u; 193 | cpx_type scratch[13]; 194 | cpx_type * twiddles = &_twiddles[0]; 195 | cpx_type *tw; 196 | cpx_type ya,yb; 197 | ya = twiddles[fstride*m]; 198 | yb = twiddles[fstride*2*m]; 199 | 200 | Fout0=Fout; 201 | Fout1=Fout0+m; 202 | Fout2=Fout0+2*m; 203 | Fout3=Fout0+3*m; 204 | Fout4=Fout0+4*m; 205 | 206 | tw=twiddles; 207 | for ( u=0; u=Norig) twidx-=Norig; 284 | C_MUL(t,scratchbuf[q] , twiddles[twidx] ); 285 | C_ADDTO( Fout[ k ] ,t); 286 | } 287 | k += m; 288 | } 289 | } 290 | } 291 | 292 | int _nfft; 293 | bool _inverse; 294 | std::vector _twiddles; 295 | std::vector _stageRadix; 296 | std::vector _stageRemainder; 297 | traits_type _traits; 298 | }; 299 | #endif 300 | -------------------------------------------------------------------------------- /libs/Gist/src/Gist.h: -------------------------------------------------------------------------------- 1 | //======================================================================= 2 | /** @file Gist.h 3 | * @brief Includes all relevant parts of the 'Gist' audio analysis library 4 | * @author Adam Stark 5 | * @copyright Copyright (C) 2013 Adam Stark 6 | * 7 | * This file is part of the 'Gist' audio analysis library 8 | * 9 | * This program is free software: you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as published by 11 | * the Free Software Foundation, either version 3 of the License, or 12 | * (at your option) any later version. 13 | * 14 | * This program is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | * GNU General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public License 20 | * along with this program. If not, see . 21 | */ 22 | //======================================================================= 23 | 24 | 25 | #ifndef __GISTHEADER__ 26 | #define __GISTHEADER__ 27 | 28 | 29 | 30 | //======================================================================= 31 | // core 32 | #include "core/CoreTimeDomainFeatures.h" 33 | #include "core/CoreFrequencyDomainFeatures.h" 34 | 35 | // onset detection functions 36 | #include "onset-detection-functions/OnsetDetectionFunction.h" 37 | 38 | // pitch detection 39 | #include "pitch/Yin.h" 40 | 41 | // MFCC 42 | #include "mfcc/MFCC.h" 43 | 44 | //======================================================================= 45 | // fft 46 | #ifdef USE_FFTW 47 | #include "fftw3.h" 48 | #endif 49 | 50 | #ifdef USE_KISS_FFT 51 | #include "../../kiss_fft130/kiss_fft.h" 52 | #endif 53 | 54 | //======================================================================= 55 | /** Class for all performing all Gist audio analyses */ 56 | template 57 | class Gist 58 | { 59 | public: 60 | 61 | /** Constructor 62 | * @param frameSize_ the input audio frame size 63 | * @param sampleRate the input audio sample rate 64 | */ 65 | Gist(int frameSize_,int sampleRate_) :fftConfigured(false), onsetDetectionFunction(frameSize_), yin(sampleRate_), mfcc(frameSize_,sampleRate_) 66 | { 67 | setAudioFrameSize(frameSize_); 68 | } 69 | 70 | /** Destructor */ 71 | ~Gist() 72 | { 73 | if (fftConfigured) 74 | { 75 | freeFFT(); 76 | } 77 | } 78 | 79 | /** Set the audio frame size. 80 | * @param frameSize_ the frame size to use 81 | */ 82 | void setAudioFrameSize(int frameSize_) 83 | { 84 | frameSize = frameSize_; 85 | 86 | audioFrame.resize(frameSize); 87 | fftReal.resize(frameSize); 88 | fftImag.resize(frameSize); 89 | magnitudeSpectrum.resize(frameSize/2); 90 | 91 | configureFFT(); 92 | 93 | onsetDetectionFunction.setFrameSize(frameSize); 94 | mfcc.setFrameSize(frameSize); 95 | } 96 | 97 | /** Process an audio frame 98 | * @param audioFrame a vector containing audio samples 99 | */ 100 | void processAudioFrame(std::vector audioFrame_) 101 | { 102 | audioFrame = audioFrame_; 103 | 104 | performFFT(); 105 | } 106 | 107 | /** Process an audio frame 108 | * @param buffer a pointer to an array containing the audio samples 109 | * @param numSamples the number of samples in the audio frame 110 | */ 111 | void processAudioFrame(T *buffer,unsigned long numSamples) 112 | { 113 | audioFrame.assign(buffer,buffer + numSamples); 114 | 115 | performFFT(); 116 | } 117 | 118 | /** Gist automatically calculates the magnitude spectrum when processAudioFrame() is called, this function returns it. 119 | @returns the current magnitude spectrum */ 120 | std::vector getMagnitudeSpectrum() 121 | { 122 | return magnitudeSpectrum; 123 | } 124 | 125 | //================= CORE TIME DOMAIN FEATURES ================= 126 | 127 | /** Calculates the root mean square (RMS) of the currently stored audio frame 128 | * @returns the root mean square (RMS) value 129 | */ 130 | T rootMeanSquare() 131 | { 132 | return coreTimeDomainFeatures.rootMeanSquare(audioFrame); 133 | } 134 | 135 | /** Calculates the peak energy of the currently stored audio frame 136 | * @returns the peak energy value 137 | */ 138 | T peakEnergy() 139 | { 140 | return coreTimeDomainFeatures.peakEnergy(audioFrame); 141 | } 142 | 143 | /** Calculates the zero crossing rate of the currently stored audio frame 144 | * @returns the zero crossing rate 145 | */ 146 | T zeroCrossingRate() 147 | { 148 | return coreTimeDomainFeatures.zeroCrossingRate(audioFrame); 149 | } 150 | 151 | //=============== CORE FREQUENCY DOMAIN FEATURES ============== 152 | 153 | /** Calculates the spectral centroid from the magnitude spectrum 154 | * @returns the spectral centroid 155 | */ 156 | T spectralCentroid() 157 | { 158 | return coreFrequencyDomainFeatures.spectralCentroid(magnitudeSpectrum); 159 | } 160 | 161 | /** Calculates the spectral crest 162 | * @returns the spectral crest 163 | */ 164 | T spectralCrest() 165 | { 166 | return coreFrequencyDomainFeatures.spectralCrest(magnitudeSpectrum); 167 | } 168 | 169 | /** Calculates the spectral flatness from the magnitude spectrum 170 | * @returns the spectral flatness 171 | */ 172 | T spectralFlatness() 173 | { 174 | return coreFrequencyDomainFeatures.spectralFlatness(magnitudeSpectrum); 175 | } 176 | 177 | //================= ONSET DETECTION FUNCTIONS ================= 178 | 179 | /** Calculates the energy difference onset detection function sample for the magnitude spectrum frame 180 | * @returns the energy difference onset detection function sample 181 | */ 182 | T energyDifference() 183 | { 184 | return onsetDetectionFunction.energyDifference(audioFrame); 185 | } 186 | 187 | /** Calculates the spectral difference onset detection function sample for the magnitude spectrum frame 188 | * @returns the spectral difference onset detection function sample 189 | */ 190 | T spectralDifference() 191 | { 192 | return onsetDetectionFunction.spectralDifference(magnitudeSpectrum); 193 | } 194 | 195 | /** Calculates the complex spectral difference onset detection function sample for the magnitude spectrum frame 196 | * @returns the complex spectral difference onset detection function sample 197 | */ 198 | T spectralDifferenceHWR() 199 | { 200 | return onsetDetectionFunction.spectralDifferenceHWR(magnitudeSpectrum); 201 | } 202 | 203 | /** Calculates the complex spectral difference onset detection function sample for the magnitude spectrum frame 204 | * @returns the complex spectral difference onset detection function sample 205 | */ 206 | T complexSpectralDifference() 207 | { 208 | return onsetDetectionFunction.complexSpectralDifference(fftReal,fftImag); 209 | } 210 | 211 | /** Calculates the high frequency content onset detection function sample for the magnitude spectrum frame 212 | * @returns the high frequency content onset detection function sample 213 | */ 214 | T highFrequencyContent() 215 | { 216 | return onsetDetectionFunction.highFrequencyContent(magnitudeSpectrum); 217 | } 218 | 219 | //=========================== PITCH ============================ 220 | 221 | /** Calculates monophonic pitch according to the Yin algorithm 222 | * @returns the pitch estimate for the audio frame 223 | */ 224 | T pitchYin() 225 | { 226 | return yin.pitchYin(audioFrame); 227 | } 228 | 229 | //=========================== MFCCs ============================= 230 | 231 | /** Calculates the Mel Frequency Spectrum 232 | * @returns the Mel spectrum as a vector 233 | */ 234 | std::vector melFrequencySpectrum() 235 | { 236 | return mfcc.melFrequencySpectrum(magnitudeSpectrum); 237 | } 238 | 239 | /** Calculates Mel Frequency Cepstral Coefficients 240 | * @returns the MFCCs as a vector 241 | */ 242 | std::vector melFrequencyCepstralCoefficients() 243 | { 244 | return mfcc.melFrequencyCepstralCoefficients(magnitudeSpectrum); 245 | } 246 | 247 | 248 | private: 249 | 250 | //======================================================================= 251 | 252 | /** configure the FFT implementation given the audio frame size) */ 253 | void configureFFT() 254 | { 255 | if (fftConfigured) 256 | { 257 | freeFFT(); 258 | } 259 | 260 | 261 | #ifdef USE_FFTW 262 | // ------------------------------------------------------ 263 | // initialise the fft time and frequency domain audio frame arrays 264 | fftIn = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * frameSize); // complex array to hold fft data 265 | fftOut = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * frameSize); // complex array to hold fft data 266 | 267 | // FFT plan initialisation 268 | p = fftw_plan_dft_1d(frameSize, fftIn, fftOut, FFTW_FORWARD, FFTW_ESTIMATE); 269 | #endif /* END USE_FFTW */ 270 | 271 | 272 | #ifdef USE_KISS_FFT 273 | // ------------------------------------------------------ 274 | // initialise the fft time and frequency domain audio frame arrays 275 | fftIn = new kiss_fft_cpx[frameSize]; 276 | fftOut = new kiss_fft_cpx[frameSize]; 277 | cfg = kiss_fft_alloc(frameSize,0,0,0); 278 | #endif /* END USE_KISS_FFT */ 279 | 280 | fftConfigured = true; 281 | } 282 | 283 | /** Free all FFT-related data */ 284 | void freeFFT() 285 | { 286 | 287 | #ifdef USE_FFTW 288 | // destroy fft plan 289 | fftw_destroy_plan(p); 290 | 291 | fftw_free(fftIn); 292 | fftw_free(fftOut); 293 | #endif 294 | 295 | #ifdef USE_KISS_FFT 296 | // free the Kiss FFT configuration 297 | free(cfg); 298 | 299 | delete [] fftIn; 300 | delete [] fftOut; 301 | #endif 302 | 303 | } 304 | 305 | 306 | /** perform the FFT on the current audio frame */ 307 | void performFFT() 308 | { 309 | #ifdef USE_FFTW 310 | // copy samples from audio frame 311 | for (int i = 0;i < frameSize;i++) 312 | { 313 | fftIn[i][0] = (double) audioFrame[i]; 314 | fftIn[i][1] = (double) 0.0; 315 | } 316 | 317 | // perform the FFT 318 | fftw_execute(p); 319 | 320 | // store real and imaginary parts of FFT 321 | for (int i = 0;i < frameSize;i++) 322 | { 323 | fftReal[i] = (T) fftOut[i][0]; 324 | fftImag[i] = (T) fftOut[i][1]; 325 | } 326 | #endif 327 | 328 | #ifdef USE_KISS_FFT 329 | for (int i = 0;i < frameSize;i++) 330 | { 331 | fftIn[i].r = (double) audioFrame[i]; 332 | fftIn[i].i = 0.0; 333 | } 334 | 335 | // execute kiss fft 336 | kiss_fft(cfg, fftIn, fftOut); 337 | 338 | // store real and imaginary parts of FFT 339 | for (int i = 0;i < frameSize;i++) 340 | { 341 | fftReal[i] = (T) fftOut[i].r; 342 | fftImag[i] = (T) fftOut[i].i; 343 | } 344 | #endif 345 | 346 | 347 | 348 | // calculate the magnitude spectrum 349 | for (int i = 0;i < frameSize/2;i++) 350 | { 351 | magnitudeSpectrum[i] = sqrt((fftReal[i]*fftReal[i]) + (fftImag[i]*fftImag[i])); 352 | } 353 | 354 | } 355 | 356 | //======================================================================= 357 | 358 | #ifdef USE_FFTW 359 | fftw_plan p; /**< fftw plan */ 360 | fftw_complex *fftIn; /**< to hold complex fft values for input */ 361 | fftw_complex *fftOut; /**< to hold complex fft values for output */ 362 | #endif 363 | 364 | #ifdef USE_KISS_FFT 365 | kiss_fft_cfg cfg; /**< Kiss FFT configuration */ 366 | kiss_fft_cpx *fftIn; /**< FFT input samples, in complex form */ 367 | kiss_fft_cpx *fftOut; /**< FFT output samples, in complex form */ 368 | #endif 369 | 370 | int frameSize; /**< The audio frame size */ 371 | 372 | std::vector audioFrame; /**< The current audio frame */ 373 | std::vector fftReal; /**< The real part of the FFT for the current audio frame */ 374 | std::vector fftImag; /**< The imaginary part of the FFT for the current audio frame */ 375 | std::vector magnitudeSpectrum; /**< The magnitude spectrum of the current audio frame */ 376 | 377 | bool fftConfigured; 378 | 379 | /** object to compute core time domain features */ 380 | CoreTimeDomainFeatures coreTimeDomainFeatures; 381 | 382 | /** object to compute core frequency domain features */ 383 | CoreFrequencyDomainFeatures coreFrequencyDomainFeatures; 384 | 385 | /** object to compute onset detection functions */ 386 | OnsetDetectionFunction onsetDetectionFunction; 387 | 388 | /** object to compute pitch estimates via the Yin algorithm */ 389 | Yin yin; 390 | 391 | /** object to compute MFCCs and mel-frequency specta */ 392 | MFCC mfcc; 393 | }; 394 | 395 | 396 | #endif 397 | -------------------------------------------------------------------------------- /libs/kiss_fft130/kiss_fft.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2003-2010, Mark Borgerding 3 | 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 7 | 8 | * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 10 | * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 | 12 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 13 | */ 14 | 15 | 16 | #include "_kiss_fft_guts.h" 17 | /* The guts header contains all the multiplication and addition macros that are defined for 18 | fixed or floating point complex numbers. It also delares the kf_ internal functions. 19 | */ 20 | 21 | static void kf_bfly2( 22 | kiss_fft_cpx * Fout, 23 | const size_t fstride, 24 | const kiss_fft_cfg st, 25 | int m 26 | ) 27 | { 28 | kiss_fft_cpx * Fout2; 29 | kiss_fft_cpx * tw1 = st->twiddles; 30 | kiss_fft_cpx t; 31 | Fout2 = Fout + m; 32 | do{ 33 | C_FIXDIV(*Fout,2); C_FIXDIV(*Fout2,2); 34 | 35 | C_MUL (t, *Fout2 , *tw1); 36 | tw1 += fstride; 37 | C_SUB( *Fout2 , *Fout , t ); 38 | C_ADDTO( *Fout , t ); 39 | ++Fout2; 40 | ++Fout; 41 | }while (--m); 42 | } 43 | 44 | static void kf_bfly4( 45 | kiss_fft_cpx * Fout, 46 | const size_t fstride, 47 | const kiss_fft_cfg st, 48 | const size_t m 49 | ) 50 | { 51 | kiss_fft_cpx *tw1,*tw2,*tw3; 52 | kiss_fft_cpx scratch[6]; 53 | size_t k=m; 54 | const size_t m2=2*m; 55 | const size_t m3=3*m; 56 | 57 | 58 | tw3 = tw2 = tw1 = st->twiddles; 59 | 60 | do { 61 | C_FIXDIV(*Fout,4); C_FIXDIV(Fout[m],4); C_FIXDIV(Fout[m2],4); C_FIXDIV(Fout[m3],4); 62 | 63 | C_MUL(scratch[0],Fout[m] , *tw1 ); 64 | C_MUL(scratch[1],Fout[m2] , *tw2 ); 65 | C_MUL(scratch[2],Fout[m3] , *tw3 ); 66 | 67 | C_SUB( scratch[5] , *Fout, scratch[1] ); 68 | C_ADDTO(*Fout, scratch[1]); 69 | C_ADD( scratch[3] , scratch[0] , scratch[2] ); 70 | C_SUB( scratch[4] , scratch[0] , scratch[2] ); 71 | C_SUB( Fout[m2], *Fout, scratch[3] ); 72 | tw1 += fstride; 73 | tw2 += fstride*2; 74 | tw3 += fstride*3; 75 | C_ADDTO( *Fout , scratch[3] ); 76 | 77 | if(st->inverse) { 78 | Fout[m].r = scratch[5].r - scratch[4].i; 79 | Fout[m].i = scratch[5].i + scratch[4].r; 80 | Fout[m3].r = scratch[5].r + scratch[4].i; 81 | Fout[m3].i = scratch[5].i - scratch[4].r; 82 | }else{ 83 | Fout[m].r = scratch[5].r + scratch[4].i; 84 | Fout[m].i = scratch[5].i - scratch[4].r; 85 | Fout[m3].r = scratch[5].r - scratch[4].i; 86 | Fout[m3].i = scratch[5].i + scratch[4].r; 87 | } 88 | ++Fout; 89 | }while(--k); 90 | } 91 | 92 | static void kf_bfly3( 93 | kiss_fft_cpx * Fout, 94 | const size_t fstride, 95 | const kiss_fft_cfg st, 96 | size_t m 97 | ) 98 | { 99 | size_t k=m; 100 | const size_t m2 = 2*m; 101 | kiss_fft_cpx *tw1,*tw2; 102 | kiss_fft_cpx scratch[5]; 103 | kiss_fft_cpx epi3; 104 | epi3 = st->twiddles[fstride*m]; 105 | 106 | tw1=tw2=st->twiddles; 107 | 108 | do{ 109 | C_FIXDIV(*Fout,3); C_FIXDIV(Fout[m],3); C_FIXDIV(Fout[m2],3); 110 | 111 | C_MUL(scratch[1],Fout[m] , *tw1); 112 | C_MUL(scratch[2],Fout[m2] , *tw2); 113 | 114 | C_ADD(scratch[3],scratch[1],scratch[2]); 115 | C_SUB(scratch[0],scratch[1],scratch[2]); 116 | tw1 += fstride; 117 | tw2 += fstride*2; 118 | 119 | Fout[m].r = Fout->r - HALF_OF(scratch[3].r); 120 | Fout[m].i = Fout->i - HALF_OF(scratch[3].i); 121 | 122 | C_MULBYSCALAR( scratch[0] , epi3.i ); 123 | 124 | C_ADDTO(*Fout,scratch[3]); 125 | 126 | Fout[m2].r = Fout[m].r + scratch[0].i; 127 | Fout[m2].i = Fout[m].i - scratch[0].r; 128 | 129 | Fout[m].r -= scratch[0].i; 130 | Fout[m].i += scratch[0].r; 131 | 132 | ++Fout; 133 | }while(--k); 134 | } 135 | 136 | static void kf_bfly5( 137 | kiss_fft_cpx * Fout, 138 | const size_t fstride, 139 | const kiss_fft_cfg st, 140 | int m 141 | ) 142 | { 143 | kiss_fft_cpx *Fout0,*Fout1,*Fout2,*Fout3,*Fout4; 144 | int u; 145 | kiss_fft_cpx scratch[13]; 146 | kiss_fft_cpx * twiddles = st->twiddles; 147 | kiss_fft_cpx *tw; 148 | kiss_fft_cpx ya,yb; 149 | ya = twiddles[fstride*m]; 150 | yb = twiddles[fstride*2*m]; 151 | 152 | Fout0=Fout; 153 | Fout1=Fout0+m; 154 | Fout2=Fout0+2*m; 155 | Fout3=Fout0+3*m; 156 | Fout4=Fout0+4*m; 157 | 158 | tw=st->twiddles; 159 | for ( u=0; ur += scratch[7].r + scratch[8].r; 174 | Fout0->i += scratch[7].i + scratch[8].i; 175 | 176 | scratch[5].r = scratch[0].r + S_MUL(scratch[7].r,ya.r) + S_MUL(scratch[8].r,yb.r); 177 | scratch[5].i = scratch[0].i + S_MUL(scratch[7].i,ya.r) + S_MUL(scratch[8].i,yb.r); 178 | 179 | scratch[6].r = S_MUL(scratch[10].i,ya.i) + S_MUL(scratch[9].i,yb.i); 180 | scratch[6].i = -S_MUL(scratch[10].r,ya.i) - S_MUL(scratch[9].r,yb.i); 181 | 182 | C_SUB(*Fout1,scratch[5],scratch[6]); 183 | C_ADD(*Fout4,scratch[5],scratch[6]); 184 | 185 | scratch[11].r = scratch[0].r + S_MUL(scratch[7].r,yb.r) + S_MUL(scratch[8].r,ya.r); 186 | scratch[11].i = scratch[0].i + S_MUL(scratch[7].i,yb.r) + S_MUL(scratch[8].i,ya.r); 187 | scratch[12].r = - S_MUL(scratch[10].i,yb.i) + S_MUL(scratch[9].i,ya.i); 188 | scratch[12].i = S_MUL(scratch[10].r,yb.i) - S_MUL(scratch[9].r,ya.i); 189 | 190 | C_ADD(*Fout2,scratch[11],scratch[12]); 191 | C_SUB(*Fout3,scratch[11],scratch[12]); 192 | 193 | ++Fout0;++Fout1;++Fout2;++Fout3;++Fout4; 194 | } 195 | } 196 | 197 | /* perform the butterfly for one stage of a mixed radix FFT */ 198 | static void kf_bfly_generic( 199 | kiss_fft_cpx * Fout, 200 | const size_t fstride, 201 | const kiss_fft_cfg st, 202 | int m, 203 | int p 204 | ) 205 | { 206 | int u,k,q1,q; 207 | kiss_fft_cpx * twiddles = st->twiddles; 208 | kiss_fft_cpx t; 209 | int Norig = st->nfft; 210 | 211 | kiss_fft_cpx * scratch = (kiss_fft_cpx*)KISS_FFT_TMP_ALLOC(sizeof(kiss_fft_cpx)*p); 212 | 213 | for ( u=0; u=Norig) twidx-=Norig; 228 | C_MUL(t,scratch[q] , twiddles[twidx] ); 229 | C_ADDTO( Fout[ k ] ,t); 230 | } 231 | k += m; 232 | } 233 | } 234 | KISS_FFT_TMP_FREE(scratch); 235 | } 236 | 237 | static 238 | void kf_work( 239 | kiss_fft_cpx * Fout, 240 | const kiss_fft_cpx * f, 241 | const size_t fstride, 242 | int in_stride, 243 | int * factors, 244 | const kiss_fft_cfg st 245 | ) 246 | { 247 | kiss_fft_cpx * Fout_beg=Fout; 248 | const int p=*factors++; /* the radix */ 249 | const int m=*factors++; /* stage's fft length/p */ 250 | const kiss_fft_cpx * Fout_end = Fout + p*m; 251 | 252 | #ifdef _OPENMP 253 | // use openmp extensions at the 254 | // top-level (not recursive) 255 | if (fstride==1 && p<=5) 256 | { 257 | int k; 258 | 259 | // execute the p different work units in different threads 260 | # pragma omp parallel for 261 | for (k=0;k floor_sqrt) 324 | p = n; /* no more factors, skip to end */ 325 | } 326 | n /= p; 327 | *facbuf++ = p; 328 | *facbuf++ = n; 329 | } while (n > 1); 330 | } 331 | 332 | /* 333 | * 334 | * User-callable function to allocate all necessary storage space for the fft. 335 | * 336 | * The return value is a contiguous block of memory, allocated with malloc. As such, 337 | * It can be freed with free(), rather than a kiss_fft-specific function. 338 | * */ 339 | kiss_fft_cfg kiss_fft_alloc(int nfft,int inverse_fft,void * mem,size_t * lenmem ) 340 | { 341 | kiss_fft_cfg st=NULL; 342 | size_t memneeded = sizeof(struct kiss_fft_state) 343 | + sizeof(kiss_fft_cpx)*(nfft-1); /* twiddle factors*/ 344 | 345 | if ( lenmem==NULL ) { 346 | st = ( kiss_fft_cfg)KISS_FFT_MALLOC( memneeded ); 347 | }else{ 348 | if (mem != NULL && *lenmem >= memneeded) 349 | st = (kiss_fft_cfg)mem; 350 | *lenmem = memneeded; 351 | } 352 | if (st) { 353 | int i; 354 | st->nfft=nfft; 355 | st->inverse = inverse_fft; 356 | 357 | for (i=0;iinverse) 361 | phase *= -1; 362 | kf_cexp(st->twiddles+i, phase ); 363 | } 364 | 365 | kf_factor(nfft,st->factors); 366 | } 367 | return st; 368 | } 369 | 370 | 371 | void kiss_fft_stride(kiss_fft_cfg st,const kiss_fft_cpx *fin,kiss_fft_cpx *fout,int in_stride) 372 | { 373 | if (fin == fout) { 374 | //NOTE: this is not really an in-place FFT algorithm. 375 | //It just performs an out-of-place FFT into a temp buffer 376 | kiss_fft_cpx * tmpbuf = (kiss_fft_cpx*)KISS_FFT_TMP_ALLOC( sizeof(kiss_fft_cpx)*st->nfft); 377 | kf_work(tmpbuf,fin,1,in_stride, st->factors,st); 378 | memcpy(fout,tmpbuf,sizeof(kiss_fft_cpx)*st->nfft); 379 | KISS_FFT_TMP_FREE(tmpbuf); 380 | }else{ 381 | kf_work( fout, fin, 1,in_stride, st->factors,st ); 382 | } 383 | } 384 | 385 | void kiss_fft(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout) 386 | { 387 | kiss_fft_stride(cfg,fin,fout,1); 388 | } 389 | 390 | 391 | void kiss_fft_cleanup(void) 392 | { 393 | // nothing needed any more 394 | } 395 | 396 | int kiss_fft_next_fast_size(int n) 397 | { 398 | while(1) { 399 | int m=n; 400 | while ( (m%2) == 0 ) m/=2; 401 | while ( (m%3) == 0 ) m/=3; 402 | while ( (m%5) == 0 ) m/=5; 403 | if (m<=1) 404 | break; /* n is completely factorable by twos, threes, and fives */ 405 | n++; 406 | } 407 | return n; 408 | } 409 | -------------------------------------------------------------------------------- /src/ofxGist.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * ofxGist.cpp 3 | * Gist 4 | * 5 | * Created by Andreas Borg on 30/03/2015 6 | * Copyright 2015 __MyCompanyName__. All rights reserved. 7 | * 8 | */ 9 | 10 | #include "ofxGist.h" 11 | 12 | 13 | 14 | ofEvent GistEvent::ON; 15 | ofEvent GistEvent::OFF; 16 | 17 | 18 | 19 | 20 | 21 | vectorofxGist::_featureNames; 22 | vectorofxGist::_features; 23 | //------------------------------------------------------------------ 24 | void ofxGist::processAudio(const vector& input, int bufferSize, int nChannels, int sampleRate){ 25 | 26 | if(_defaultBufferSize != bufferSize){ 27 | gist.setAudioFrameSize(bufferSize); 28 | _defaultBufferSize = bufferSize; 29 | } 30 | 31 | if(_defaultSampleRate != sampleRate){ 32 | //gist.setAudioFrameSize(bufferSize); 33 | _defaultSampleRate = sampleRate; 34 | } 35 | 36 | 37 | gist.processAudioFrame(input); 38 | 39 | 40 | int v = _features.size(); 41 | while(v--){ 42 | 43 | //store max/min/avg 44 | if( _values[_features[v]] > _maxValues[_features[v]]){ 45 | _maxValues[_features[v]] = _values[_features[v]]; 46 | } 47 | 48 | if( _values[_features[v]] < _minValues[_features[v]]){ 49 | _minValues[_features[v]] = _values[_features[v]]; 50 | } 51 | 52 | if(_avgValueNum[_features[v]]){ 53 | _avgValues[_features[v]] = _values[_features[v]]; 54 | }else{ 55 | _avgValues[_features[v]] = (_avgValues[_features[v]]*_avgValueNum[_features[v]] + _values[_features[v]])/(float)(_avgValueNum[_features[v]]+1); 56 | } 57 | _avgValueNum[_features[v]]++; 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | switch (_features[v] ){ 66 | case GIST_PITCH: 67 | if(_doDetect[_features[v]] ){ 68 | // yin.setSamplingFrequency(sampleRate); 69 | //_values[GIST_PITCH] = MAX(0,yin.pitchYin(input)); 70 | 71 | _values[GIST_PITCH] = MAX(0,gist.pitchYin()); 72 | 73 | if(_useForOnsetDetection[_features[v]]){ 74 | processOnsetDetection(_features[v]); 75 | } 76 | } 77 | break; 78 | case GIST_NOTE: 79 | if(_doDetect[_features[v]] ){ 80 | //this might take last frame unfortunately 81 | _values[GIST_NOTE] = getNoteFrequency(); 82 | 83 | if(_useForOnsetDetection[_features[v]]){ 84 | processOnsetDetection(_features[v]); 85 | } 86 | } 87 | break; 88 | 89 | 90 | 91 | case GIST_PEAK_ENERGY: 92 | if(_doDetect[_features[v]] ){ 93 | //CoreTimeDomainFeatures tdf; 94 | //_values[GIST_PEAK_ENERGY] = tdf.peakEnergy(input); 95 | _values[GIST_PEAK_ENERGY] = gist.peakEnergy(); 96 | 97 | if(_useForOnsetDetection[_features[v]]){ 98 | processOnsetDetection(_features[v]); 99 | } 100 | } 101 | break; 102 | 103 | case GIST_ROOT_MEAN_SQUARE: 104 | if(_doDetect[_features[v]] ){ 105 | //CoreTimeDomainFeatures tdf; 106 | //_values[GIST_ROOT_MEAN_SQUARE] = tdf.rootMeanSquare(input); 107 | _values[GIST_ROOT_MEAN_SQUARE] = gist.rootMeanSquare(); 108 | 109 | if(_useForOnsetDetection[_features[v]]){ 110 | processOnsetDetection(_features[v]); 111 | } 112 | 113 | } 114 | break; 115 | case GIST_ZERO_CROSSING_RATE: 116 | if(_doDetect[_features[v]] ){ 117 | //CoreTimeDomainFeatures tdf; 118 | //_values[GIST_ZERO_CROSSING_RATE] = tdf.zeroCrossingRate(input); 119 | _values[GIST_ZERO_CROSSING_RATE] = gist.zeroCrossingRate(); 120 | 121 | if(_useForOnsetDetection[_features[v]]){ 122 | processOnsetDetection(_features[v]); 123 | } 124 | } 125 | break; 126 | case GIST_SPECTRAL_CENTROID: 127 | if(_doDetect[_features[v]] ){ 128 | //CoreFrequencyDomainFeatures fdf; 129 | //_values[GIST_SPECTRAL_CENTROID] = fdf.spectralCentroid(gist.getMagnitudeSpectrum()); 130 | _values[GIST_SPECTRAL_CENTROID] = gist.spectralCentroid(); 131 | 132 | if(_useForOnsetDetection[_features[v]]){ 133 | processOnsetDetection(_features[v]); 134 | } 135 | } 136 | break; 137 | case GIST_SPECTRAL_FLATNESS: 138 | if(_doDetect[_features[v]] ){ 139 | //CoreFrequencyDomainFeatures fdf; 140 | //_values[GIST_SPECTRAL_FLATNESS] = fdf.spectralFlatness(input); 141 | _values[GIST_SPECTRAL_FLATNESS] = gist.spectralFlatness(); 142 | 143 | if(_useForOnsetDetection[_features[v]]){ 144 | processOnsetDetection(_features[v]); 145 | } 146 | } 147 | break; 148 | case GIST_SPECTRAL_DIFFERENCE: 149 | if(_doDetect[_features[v]] ){ 150 | _values[GIST_SPECTRAL_DIFFERENCE] = gist.spectralDifference(); 151 | 152 | if(_useForOnsetDetection[_features[v]]){ 153 | processOnsetDetection(_features[v]); 154 | } 155 | } 156 | break; 157 | 158 | case GIST_SPECTRAL_DIFFERENCE_COMPLEX: 159 | if(_doDetect[_features[v]] ){ 160 | //OnsetDetectionFunction odf(bufferSize); 161 | //_values[GIST_DIFFERENCE] = odf.spectralDifference(input); 162 | 163 | _values[GIST_SPECTRAL_DIFFERENCE_COMPLEX] = gist.complexSpectralDifference(); 164 | 165 | 166 | 167 | if(_useForOnsetDetection[_features[v]]){ 168 | processOnsetDetection(_features[v]); 169 | } 170 | 171 | 172 | 173 | } 174 | break; 175 | 176 | case GIST_HIGH_FREQUENCY_CONTENT: 177 | if(_doDetect[_features[v]] ){ 178 | 179 | _values[GIST_HIGH_FREQUENCY_CONTENT] = gist.highFrequencyContent(); 180 | 181 | 182 | if(_useForOnsetDetection[_features[v]]){ 183 | processOnsetDetection(_features[v]); 184 | } 185 | 186 | 187 | } 188 | break; 189 | 190 | 191 | 192 | 193 | 194 | 195 | case GIST_SPECTRAL_DIFFERENCE_HALFWAY: 196 | if(_doDetect[_features[v]] ){ 197 | 198 | _values[GIST_SPECTRAL_DIFFERENCE_HALFWAY] = gist.spectralDifferenceHWR(); 199 | 200 | if(_useForOnsetDetection[_features[v]]){ 201 | processOnsetDetection(_features[v]); 202 | } 203 | } 204 | break; 205 | 206 | 207 | 208 | case GIST_SPECTRAL_CREST: 209 | if(_doDetect[_features[v]] ){ 210 | //CoreFrequencyDomainFeatures fdf; 211 | //_values[GIST_SPECTRAL_CREST] = fdf.spectralCrest(input); 212 | 213 | _values[GIST_SPECTRAL_CREST] = gist.spectralCrest(); 214 | 215 | if(_useForOnsetDetection[_features[v]]){ 216 | processOnsetDetection(_features[v]); 217 | } 218 | } 219 | break; 220 | 221 | default: 222 | 223 | break; 224 | } 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | } 234 | 235 | 236 | 237 | 238 | 239 | if(_calculateMFCC){ 240 | 241 | vectormfcc = getMelFrequencyCepstralCoefficients(); 242 | int mfccs = mfcc.size(); 243 | 244 | 245 | while(mfccs--){ 246 | float val = mfcc[mfccs]; 247 | 248 | //store max/min/avg 249 | if( val > _mfccMaxValues[mfccs]){ 250 | _mfccMaxValues[mfccs] = val; 251 | } 252 | 253 | 254 | if(val < _mfccMinValues[mfccs]){ 255 | _mfccMinValues[mfccs] = val; 256 | } 257 | 258 | if(_mfccAvgValues[mfccs]){ 259 | _mfccAvgValues[mfccs] = val; 260 | }else{ 261 | _mfccAvgValues[mfccs] = (_mfccAvgValues[mfccs]*_mfccAvgValueNum[mfccs] + val)/(float)(_mfccAvgValueNum[mfccs]+1); 262 | } 263 | _mfccAvgValueNum[mfccs]++; 264 | 265 | 266 | } 267 | 268 | } 269 | 270 | 271 | }; 272 | 273 | 274 | /* 275 | Any feature can be used for some type of onset detection really 276 | */ 277 | void ofxGist::processOnsetDetection(GIST_FEATURE feature){ 278 | 279 | 280 | _history[feature].push_back(_values[feature]); 281 | 282 | 283 | 284 | int bigChange = 0; 285 | 286 | 287 | //check changes between last few events 288 | int frames = _history[feature].size(); 289 | if(frames>1){ 290 | float delta = _history[feature][frames-1] -_history[feature][frames-2]; 291 | 292 | 293 | float diffThreshold = _maxValues[feature]*_thresholds[feature]; 294 | //float diffThreshold = _avgValues[feature]/2.0f; 295 | 296 | float angle = atan(delta); 297 | if(delta > diffThreshold){ 298 | bigChange = 1; 299 | }else if(angle < 0){ 300 | //whenever starts to decline 301 | bigChange = -1; 302 | } 303 | } 304 | 305 | 306 | if(bigChange == 1 && !_isNoteOn){ 307 | GistEvent e; 308 | e.energy = gist.peakEnergy(); 309 | e.frequency = gist.pitchYin(); 310 | e.feature = feature; 311 | e.note = getNoteFrequency(); 312 | e.onsetAmount = _values[feature]; 313 | ofNotifyEvent(GistEvent::ON,e); 314 | _isNoteOn = 1; 315 | }else if(bigChange == -1 && _isNoteOn){ 316 | GistEvent e; 317 | e.energy = gist.peakEnergy(); 318 | e.frequency = gist.pitchYin(); 319 | e.feature = feature; 320 | e.note = getNoteFrequency(); 321 | e.onsetAmount = _values[feature]; 322 | ofNotifyEvent(GistEvent::OFF,e); 323 | _isNoteOn = 0; 324 | } 325 | 326 | 327 | 328 | int historySize = 100; 329 | 330 | if(_history[feature].size()>historySize){ 331 | _history[feature].erase(_history[feature].begin(),_history[feature].begin()+ _history[feature].size()-historySize); 332 | } 333 | 334 | }; 335 | 336 | 337 | void ofxGist::setDetect(GIST_FEATURE f,bool b){ 338 | ofLog()<<"ofxGist will detect "<(f); 373 | return getValue(feature); 374 | }; 375 | 376 | 377 | float ofxGist::getMin(GIST_FEATURE f){ 378 | return _minValues[f]; 379 | 380 | }; 381 | 382 | 383 | float ofxGist::getMin(int f){ 384 | GIST_FEATURE feature = static_cast(f); 385 | return getMin(feature); 386 | }; 387 | 388 | 389 | float ofxGist::getMax(GIST_FEATURE f){ 390 | return _maxValues[f]; 391 | 392 | }; 393 | 394 | 395 | float ofxGist::getMax(int f){ 396 | GIST_FEATURE feature = static_cast(f); 397 | return getMax(feature); 398 | }; 399 | 400 | 401 | float ofxGist::getAvg(GIST_FEATURE f){ 402 | return _avgValues[f]; 403 | 404 | }; 405 | 406 | 407 | float ofxGist::getAvg(int f){ 408 | GIST_FEATURE feature = static_cast(f); 409 | return getAvg(feature); 410 | }; 411 | 412 | 413 | 414 | void ofxGist::setThreshold(GIST_FEATURE f, float t){ 415 | _thresholds[f] = t; 416 | }; 417 | 418 | float ofxGist::getThreshold(GIST_FEATURE f){ 419 | return _thresholds[f]; 420 | }; 421 | 422 | float ofxGist::getThreshold(int f){ 423 | GIST_FEATURE feature = static_cast(f); 424 | return getThreshold(feature); 425 | } 426 | 427 | 428 | 429 | 430 | float ofxGist::frequencyToMidi(float freq){ 431 | float midi; 432 | if (freq < 2. || freq > 100000.) return 0.; // avoid nans and infs 433 | /* log(freq/A-2)/log(2) */ 434 | midi = freq / 6.875; 435 | midi = logf (midi) / 0.69314718055995; 436 | midi *= 12; 437 | midi -= 3; 438 | return MAX(0,midi); 439 | }; 440 | 441 | float ofxGist::getNoteFrequency(){ 442 | if(_doDetect[GIST_PITCH] ){ 443 | return frequencyToMidi(_values[GIST_PITCH]); 444 | } 445 | return 0.0; 446 | }; 447 | 448 | 449 | string ofxGist::getNoteName(){ 450 | int val = getNoteFrequency(); 451 | int relVal = val % 12; 452 | int oct = floor(val/12); 453 | 454 | string n[] = {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"}; 455 | 456 | return n[relVal]+"-"+ofToString(oct); 457 | 458 | }; 459 | 460 | 461 | 462 | void ofxGist::clearHistory(){ 463 | for(GIST_FEATURE feature:_features){ 464 | _values[feature] = 0; 465 | _minValues[feature] = 100000000; 466 | _maxValues[feature] = 0; 467 | _avgValues[feature] = 0; 468 | _avgValueNum[feature] = 0; 469 | } 470 | 471 | 472 | int v = getMelFrequencyCepstralCoefficients().size(); 473 | 474 | _mfccMinValues.clear(); 475 | _mfccMaxValues.clear(); 476 | _mfccAvgValues.clear(); 477 | _mfccAvgValueNum.clear(); 478 | 479 | 480 | while(v--){ 481 | _mfccMinValues.push_back(100000000); 482 | _mfccMaxValues.push_back(0); 483 | _mfccAvgValues.push_back(0); 484 | _mfccAvgValueNum.push_back(0); 485 | 486 | } 487 | 488 | }; 489 | 490 | 491 | 492 | vector ofxGist::getMelFrequencySpectrum(){ 493 | _calculateMFCC = true; 494 | return gist.melFrequencySpectrum(); 495 | }; 496 | 497 | vector ofxGist::getMelFrequencyCepstralCoefficients(){ 498 | _calculateMFCC = true; 499 | return gist.melFrequencyCepstralCoefficients(); 500 | }; 501 | 502 | 503 | 504 | float ofxGist::getMFCCMin(int coeffNum){ 505 | _calculateMFCC = true; 506 | return _mfccMinValues[coeffNum]; 507 | }; 508 | 509 | float ofxGist::getMFCCMax(int coeffNum){ 510 | _calculateMFCC = true; 511 | return _mfccMaxValues[coeffNum]; 512 | }; 513 | 514 | float ofxGist::getMFCCAvg(int coeffNum){ 515 | _calculateMFCC = true; 516 | return _mfccAvgValues[coeffNum]; 517 | }; 518 | 519 | 520 | -------------------------------------------------------------------------------- /libs/Stark-Plumbley/LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | 3 | Version 3, 29 June 2007 4 | 5 | Copyright © 2007 Free Software Foundation, Inc. 6 | 7 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for software and other kinds of works. 11 | 12 | The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. 13 | 14 | When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. 15 | 16 | To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. 17 | 18 | For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. 19 | 20 | Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. 21 | 22 | For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. 23 | 24 | Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. 25 | 26 | Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. 27 | 28 | The precise terms and conditions for copying, distribution and modification follow. 29 | TERMS AND CONDITIONS 30 | 0. Definitions. 31 | 32 | “This License” refers to version 3 of the GNU General Public License. 33 | 34 | “Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. 35 | 36 | “The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. 37 | 38 | To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. 39 | 40 | A “covered work” means either the unmodified Program or a work based on the Program. 41 | 42 | To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. 43 | 44 | To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. 45 | 46 | An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 47 | 1. Source Code. 48 | 49 | The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. 50 | 51 | A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. 52 | 53 | The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. 54 | 55 | The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. 56 | 57 | The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. 58 | 59 | The Corresponding Source for a work in source code form is that same work. 60 | 2. Basic Permissions. 61 | 62 | All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. 63 | 64 | You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. 65 | 66 | Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 67 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 68 | 69 | No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. 70 | 71 | When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 72 | 4. Conveying Verbatim Copies. 73 | 74 | You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. 75 | 76 | You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 77 | 5. Conveying Modified Source Versions. 78 | 79 | You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: 80 | 81 | a) The work must carry prominent notices stating that you modified it, and giving a relevant date. 82 | b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. 83 | c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. 84 | d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. 85 | 86 | A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 87 | 6. Conveying Non-Source Forms. 88 | 89 | You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: 90 | 91 | a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. 92 | b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. 93 | c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. 94 | d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. 95 | e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. 96 | 97 | A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. 98 | 99 | A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. 100 | 101 | “Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. 102 | 103 | If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). 104 | 105 | The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. 106 | 107 | Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 108 | 7. Additional Terms. 109 | 110 | “Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. 111 | 112 | When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. 113 | 114 | Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: 115 | 116 | a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or 117 | b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or 118 | c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or 119 | d) Limiting the use for publicity purposes of names of licensors or authors of the material; or 120 | e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or 121 | f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. 122 | 123 | All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. 124 | 125 | If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. 126 | 127 | Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 128 | 8. Termination. 129 | 130 | You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). 131 | 132 | However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. 133 | 134 | Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. 135 | 136 | Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 137 | 9. Acceptance Not Required for Having Copies. 138 | 139 | You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 140 | 10. Automatic Licensing of Downstream Recipients. 141 | 142 | Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. 143 | 144 | An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. 145 | 146 | You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 147 | 11. Patents. 148 | 149 | A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. 150 | 151 | A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. 152 | 153 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. 154 | 155 | In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. 156 | 157 | If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. 158 | 159 | If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. 160 | 161 | A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. 162 | 163 | Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 164 | 12. No Surrender of Others' Freedom. 165 | 166 | If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 167 | 13. Use with the GNU Affero General Public License. 168 | 169 | Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 170 | 14. Revised Versions of this License. 171 | 172 | The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 173 | 174 | Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. 175 | 176 | If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. 177 | 178 | Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 179 | 15. Disclaimer of Warranty. 180 | 181 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 182 | 16. Limitation of Liability. 183 | 184 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 185 | 17. Interpretation of Sections 15 and 16. 186 | 187 | If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. 188 | 189 | END OF TERMS AND CONDITIONS --------------------------------------------------------------------------------