├── .gitignore
├── docs
├── logo.png
└── Introduction.txt
├── packaging
├── KeyFinderConfig.cmake.in
└── libkeyfinder.pc.in
├── examples
├── CMakeLists.txt
└── basic.cpp
├── .github
└── workflows
│ ├── docs.yml
│ └── build-and-test.yml
├── tests
├── spectrumanalysertest.cpp
├── _testhelpers.cpp
├── CMakeLists.txt
├── chromatransformfactorytest.cpp
├── lowpassfilterfactorytest.cpp
├── constantstest.cpp
├── workspacetest.cpp
├── binodetest.cpp
├── temporalwindowfactorytest.cpp
├── _testhelpers.h
├── tests.pro
├── fftadaptertest.cpp
├── toneprofilestest.cpp
├── downsamplershortcuttest.cpp
├── windowfunctiontest.cpp
├── chromagramtest.cpp
├── chromatransformtest.cpp
├── keyclassifiertest.cpp
├── keyfindertest.cpp
├── lowpassfiltertest.cpp
└── audiodatatest.cpp
├── src
├── binode.h
├── exception.h
├── workspace.cpp
├── windowfunctions.h
├── toneprofiles.h
├── workspace.h
├── keyclassifier.h
├── chromagram.h
├── chromatransform.h
├── lowpassfilter.h
├── spectrumanalyser.h
├── temporalwindowfactory.h
├── chromatransformfactory.h
├── fftadapter.h
├── keyfinder.h
├── lowpassfilterfactory.h
├── keyclassifier.cpp
├── windowfunctions.cpp
├── chromatransformfactory.cpp
├── spectrumanalyser.cpp
├── temporalwindowfactory.cpp
├── audiodata.h
├── constants.h
├── chromagram.cpp
├── toneprofiles.cpp
├── lowpassfilterfactory.cpp
├── chromatransform.cpp
├── keyfinder.cpp
├── constants.cpp
├── fftadapter.cpp
├── lowpassfilter.cpp
└── audiodata.cpp
├── CHANGELOG.md
├── cmake
└── FindFFTW3.cmake
├── README.md
├── CMakeLists.txt
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 | build
2 | docs/html
3 | docs/latex
4 |
--------------------------------------------------------------------------------
/docs/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mixxxdj/libkeyfinder/HEAD/docs/logo.png
--------------------------------------------------------------------------------
/packaging/KeyFinderConfig.cmake.in:
--------------------------------------------------------------------------------
1 | @PACKAGE_INIT@
2 |
3 | list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/modules")
4 | include(CMakeFindDependencyMacro)
5 | find_dependency(FFTW3)
6 |
7 | include("${CMAKE_CURRENT_LIST_DIR}/KeyFinderTargets.cmake")
8 |
9 | check_required_components(KeyFinder)
10 |
--------------------------------------------------------------------------------
/examples/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.1.0)
2 | project(KeyFinderBasicExample)
3 |
4 | list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../cmake")
5 |
6 | find_package(KeyFinder CONFIG REQUIRED)
7 | add_executable(basic basic.cpp)
8 | target_link_libraries(basic PRIVATE KeyFinder::keyfinder)
9 |
--------------------------------------------------------------------------------
/packaging/libkeyfinder.pc.in:
--------------------------------------------------------------------------------
1 | prefix=@CMAKE_INSTALL_PREFIX@
2 | includedir=@PKGCONFIG_INCLUDEDIR@
3 | libdir=@PKGCONFIG_LIBDIR@
4 |
5 | Name: libkeyfinder
6 | Description: libkeyfinder can be used to estimate the musical key of digital audio
7 | Version: @CMAKE_PROJECT_VERSION@
8 | URL: https://github.com/mixxxdj/libkeyfinder
9 | Libs: -L${libdir} -lkeyfinder
10 | Requires.private: fftw3
11 | Cflags: -I${includedir}
12 |
--------------------------------------------------------------------------------
/.github/workflows/docs.yml:
--------------------------------------------------------------------------------
1 | name: Generate Docs
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 |
8 | jobs:
9 | doxygen:
10 | name: Doxygen
11 | runs-on: ubuntu-latest
12 | steps:
13 | - name: "Check out repository"
14 | uses: actions/checkout@v2
15 |
16 | - name: Install Doxygen
17 | run: sudo apt-get update && sudo apt-get install -y --no-install-recommends doxygen
18 |
19 | - name: Generate Documentation
20 | run: doxygen
21 | working-directory: docs
22 |
23 | - name: Deploy to GitHub Pages
24 | uses: peaceiris/actions-gh-pages@v3
25 | with:
26 | github_token: ${{ secrets.GITHUB_TOKEN }}
27 | publish_dir: docs/html
28 |
--------------------------------------------------------------------------------
/tests/spectrumanalysertest.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "_testhelpers.h"
23 |
24 | // TODO: this.
25 |
--------------------------------------------------------------------------------
/tests/_testhelpers.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "_testhelpers.h"
23 |
24 | float sine_wave (
25 | unsigned int index,
26 | float frequency,
27 | unsigned int sampleRate,
28 | unsigned int magnitude
29 | ) {
30 | return magnitude * sin(index * frequency / sampleRate * 2.0 * PI);
31 | }
32 |
--------------------------------------------------------------------------------
/src/binode.h:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #ifndef BINODE_H
23 | #define BINODE_H
24 |
25 | namespace KeyFinder {
26 |
27 | template
28 | class Binode {
29 | public:
30 | Binode(T x = 0): l(0), r(0), data(x) {}
31 | Binode* l, *r;
32 | T data;
33 | };
34 |
35 | }
36 |
37 | #endif
38 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Change log
2 |
3 | ## 2.2.8
4 | * Update tests to Catch3
5 | * Bump minimum CMake version to 3.5 to avoid deprecation warning
6 |
7 | ## 2.2.7
8 | * Fix pkgconfig file when CMAKE_INSTALL_{INCLUDE,LIB}DIR are absolute paths
9 |
10 | ## 2.2.6
11 | * Install CMake package config to CMAKE_INSTALL_LIBDIR
12 | * Install FindFFTW3.cmake module
13 | * Fix fftw3 missing from Requires.private in pkgconfig file
14 |
15 | ## 2.2.5
16 | * Set version for .so library and setup version symlinks
17 |
18 | ## 2.2.4
19 |
20 | * Rename repository from libKeyFinder to libkeyfinder
21 | * Support building Windows DLL
22 | * Add Windows to GitHub Actions CI
23 | * Add CMake target export files
24 | * Use catch2 for tests
25 | * Add CTest support with standard BUILD_TESTING CMake option
26 | * Add example program and build it on CI
27 | * Add Doxygen documentation and deploy to https://mixxxdj.github.io/libkeyfinder/
28 |
29 | ## 2.2.3
30 |
31 | * Maintenance transferred to [Mixxx DJ Software](https://mixxx.org/) team
32 | * Fix CMake build
33 | * Use GitHub Actions for CI on Ubuntu and macOS
34 |
35 | ## 2.2.2
36 |
37 | * Add CMake build system support
38 |
39 | ## 2.2.1
40 |
41 | * update tests and downsampling shortcut
42 |
--------------------------------------------------------------------------------
/src/exception.h:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #ifndef EXCEPTION_H
23 | #define EXCEPTION_H
24 |
25 | #include
26 | #include
27 |
28 | namespace KeyFinder {
29 |
30 | class Exception : public std::runtime_error {
31 | public:
32 | Exception(const char* msg) : std::runtime_error(msg) { }
33 | };
34 |
35 | }
36 |
37 | #endif
38 |
--------------------------------------------------------------------------------
/tests/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | add_executable(keyfinder-tests
2 | _testhelpers.cpp
3 | audiodatatest.cpp
4 | binodetest.cpp
5 | chromagramtest.cpp
6 | chromatransformtest.cpp
7 | chromatransformfactorytest.cpp
8 | constantstest.cpp
9 | downsamplershortcuttest.cpp
10 | fftadaptertest.cpp
11 | keyclassifiertest.cpp
12 | keyfindertest.cpp
13 | lowpassfiltertest.cpp
14 | lowpassfilterfactorytest.cpp
15 | spectrumanalysertest.cpp
16 | temporalwindowfactorytest.cpp
17 | toneprofilestest.cpp
18 | windowfunctiontest.cpp
19 | workspacetest.cpp)
20 | target_include_directories(keyfinder-tests PRIVATE ../src)
21 | target_link_libraries(keyfinder-tests PRIVATE keyfinder)
22 | find_package(Catch2 CONFIG)
23 | if(NOT TARGET Catch2::Catch2)
24 | message(STATUS "Fetching Catch2 from GitHub")
25 | include(FetchContent)
26 | FetchContent_Declare(
27 | Catch2
28 | GIT_REPOSITORY https://github.com/catchorg/Catch2.git
29 | GIT_TAG v3.3.2)
30 | FetchContent_MakeAvailable(Catch2)
31 | list(APPEND CMAKE_MODULE_PATH ${catch2_SOURCE_DIR}/contrib)
32 | endif()
33 | target_link_libraries(keyfinder-tests PRIVATE Catch2::Catch2WithMain)
34 | include(Catch)
35 | catch_discover_tests(keyfinder-tests)
36 |
--------------------------------------------------------------------------------
/src/workspace.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "workspace.h"
23 |
24 | namespace KeyFinder {
25 |
26 | Workspace::Workspace() : remainderBuffer(), preprocessedBuffer(), chromagram(NULL), fftAdapter(NULL), lpfBuffer(NULL) { }
27 |
28 | Workspace::~Workspace() {
29 | if (fftAdapter != NULL)
30 | delete fftAdapter;
31 | if (chromagram != NULL)
32 | delete chromagram;
33 | if (lpfBuffer != NULL)
34 | delete lpfBuffer;
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/tests/chromatransformfactorytest.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "_testhelpers.h"
23 |
24 | TEST (ChromaTransformFactoryTest, RepeatedTransformRequests) {
25 | KeyFinder::ChromaTransformFactory ctf;
26 |
27 | const KeyFinder::ChromaTransform* ct1 = ctf.getChromaTransform(4410);
28 | const KeyFinder::ChromaTransform* ct2 = ctf.getChromaTransform(4410);
29 | const KeyFinder::ChromaTransform* ct3 = ctf.getChromaTransform(4800);
30 |
31 | ASSERT_EQ(ct1, ct2);
32 | ASSERT_NE(ct2, ct3);
33 | }
34 |
--------------------------------------------------------------------------------
/src/windowfunctions.h:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #ifndef WINDOWFUNCTIONS_H
23 | #define WINDOWFUNCTIONS_H
24 |
25 | #include "constants.h"
26 |
27 | namespace KeyFinder {
28 |
29 | class WindowFunction {
30 | public:
31 | double window(temporal_window_t windowType, int sample, int width) const;
32 | double gaussianWindow(int sample, int width, double sigma) const;
33 | std::vector convolve(const std::vector& input, const std::vector& window) const;
34 | };
35 |
36 | }
37 |
38 | #endif
39 |
--------------------------------------------------------------------------------
/tests/lowpassfilterfactorytest.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "_testhelpers.h"
23 |
24 | TEST (LowPassFilterFactoryTest, RepeatedFilterRequests) {
25 | KeyFinder::LowPassFilterFactory lpff;
26 |
27 | const KeyFinder::LowPassFilter* lpf1 = lpff.getLowPassFilter(2, 1, 20.0, 8);
28 | const KeyFinder::LowPassFilter* lpf2 = lpff.getLowPassFilter(2, 1, 20.0, 8);
29 | const KeyFinder::LowPassFilter* lpf3 = lpff.getLowPassFilter(2, 1, 20.0, 16);
30 |
31 | ASSERT_EQ(lpf1, lpf2);
32 | ASSERT_NE(lpf2, lpf3);
33 | }
34 |
--------------------------------------------------------------------------------
/src/toneprofiles.h:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #ifndef TONEPROFILES_H
23 | #define TONEPROFILES_H
24 |
25 | #include "constants.h"
26 | #include "binode.h"
27 |
28 | namespace KeyFinder {
29 |
30 | class ToneProfile {
31 | public:
32 | ToneProfile(const std::vector& customProfile);
33 | ~ToneProfile();
34 | double cosineSimilarity(const std::vector& chromaVector, int offset) const;
35 | private:
36 | void free();
37 | std::vector*> tonics;
38 | };
39 |
40 | }
41 |
42 | #endif
43 |
--------------------------------------------------------------------------------
/src/workspace.h:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #ifndef WORKSPACE_H
23 | #define WORKSPACE_H
24 |
25 | #include "audiodata.h"
26 | #include "binode.h"
27 | #include "chromagram.h"
28 | #include "fftadapter.h"
29 |
30 | namespace KeyFinder {
31 |
32 | class Workspace {
33 | public:
34 | Workspace();
35 | ~Workspace();
36 | AudioData remainderBuffer;
37 | AudioData preprocessedBuffer;
38 | Chromagram* chromagram;
39 | FftAdapter* fftAdapter;
40 | std::vector* lpfBuffer;
41 | };
42 |
43 | }
44 |
45 | #endif
46 |
--------------------------------------------------------------------------------
/src/keyclassifier.h:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #ifndef KEYCLASSIFIER_H
23 | #define KEYCLASSIFIER_H
24 |
25 | #include "constants.h"
26 | #include "toneprofiles.h"
27 |
28 | namespace KeyFinder {
29 |
30 | class KeyClassifier {
31 | public:
32 | KeyClassifier(const std::vector& majorProfile, const std::vector& minorProfile);
33 | ~KeyClassifier();
34 | key_t classify(const std::vector& chromaVector);
35 | private:
36 | ToneProfile* major;
37 | ToneProfile* minor;
38 | ToneProfile* silence;
39 | };
40 |
41 | }
42 |
43 | #endif
44 |
--------------------------------------------------------------------------------
/tests/constantstest.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "_testhelpers.h"
23 |
24 | TEST (ConstantsTest, aFewDefaultBandFreqs) {
25 | ASSERT_NEAR(32.7, KeyFinder::getFrequencyOfBand(0), 0.01);
26 | ASSERT_NEAR(55.0, KeyFinder::getFrequencyOfBand(9), 0.01);
27 | ASSERT_NEAR(1975.53, KeyFinder::getLastFrequency(), 0.01);
28 | }
29 |
30 | TEST (ConstantsTest, FreqBounds) {
31 | ASSERT_THROW(KeyFinder::getFrequencyOfBand(-1), KeyFinder::Exception);
32 | ASSERT_NO_THROW(KeyFinder::getFrequencyOfBand(71));
33 | ASSERT_THROW(KeyFinder::getFrequencyOfBand(72), KeyFinder::Exception);
34 | }
35 |
--------------------------------------------------------------------------------
/tests/workspacetest.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "_testhelpers.h"
23 |
24 | TEST (WorkspaceTest, ConstructorDefaultsWork) {
25 | KeyFinder::Workspace w;
26 |
27 | ASSERT_EQ(0, w.preprocessedBuffer.getChannels());
28 | ASSERT_EQ(0, w.preprocessedBuffer.getFrameRate());
29 | ASSERT_EQ(0, w.preprocessedBuffer.getSampleCount());
30 |
31 | ASSERT_EQ(0, w.remainderBuffer.getChannels());
32 | ASSERT_EQ(0, w.remainderBuffer.getFrameRate());
33 | ASSERT_EQ(0, w.remainderBuffer.getSampleCount());
34 |
35 | ASSERT_EQ(NULL, w.chromagram);
36 | ASSERT_EQ(NULL, w.fftAdapter);
37 | ASSERT_EQ(NULL, w.lpfBuffer);
38 | }
39 |
--------------------------------------------------------------------------------
/src/chromagram.h:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #ifndef CHROMAGRAM_H
23 | #define CHROMAGRAM_H
24 |
25 | #include "constants.h"
26 |
27 | namespace KeyFinder {
28 |
29 | class Chromagram {
30 | public:
31 | Chromagram(unsigned int hops = 0);
32 | void append(const Chromagram& that);
33 | void setMagnitude(unsigned int hop, unsigned int band, double value);
34 | double getMagnitude(unsigned int hop, unsigned int band) const;
35 | unsigned int getHops() const;
36 | std::vector collapseToOneHop() const;
37 | private:
38 | std::vector< std::vector > chromaData;
39 | };
40 |
41 | }
42 |
43 | #endif
44 |
--------------------------------------------------------------------------------
/src/chromatransform.h:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #ifndef CHROMATRANSFORM_H
23 | #define CHROMATRANSFORM_H
24 |
25 | #include "constants.h"
26 | #include "fftadapter.h"
27 |
28 | namespace KeyFinder {
29 |
30 | class ChromaTransform {
31 | public:
32 | ChromaTransform(unsigned int frameRate);
33 | std::vector chromaVector(const FftAdapter* const fft) const;
34 | protected:
35 | unsigned int frameRate;
36 | std::vector< std::vector > directSpectralKernel;
37 | std::vector chromaBandFftBinOffsets;
38 | double kernelWindow(double n, double N) const;
39 | };
40 |
41 | }
42 |
43 | #endif
44 |
--------------------------------------------------------------------------------
/tests/binodetest.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "_testhelpers.h"
23 |
24 | TEST_CASE ("BinodeTest/ConstructorDefaultsWork") {
25 | KeyFinder::Binode bf;
26 | ASSERT_FLOAT_EQ(0.0, bf.data);
27 | ASSERT_EQ(NULL, bf.l);
28 | ASSERT_EQ(NULL, bf.r);
29 |
30 | KeyFinder::Binode bi;
31 | ASSERT_EQ(0, bi.data);
32 | ASSERT_EQ(NULL, bi.l);
33 | ASSERT_EQ(NULL, bi.r);
34 | }
35 |
36 | TEST_CASE ("BinodeTest/ConstructorArgumentsWork") {
37 | KeyFinder::Binode bf(365.25);
38 | ASSERT_FLOAT_EQ(365.25, bf.data);
39 | ASSERT_EQ(NULL, bf.l);
40 | ASSERT_EQ(NULL, bf.r);
41 |
42 | KeyFinder::Binode bi(14);
43 | ASSERT_EQ(14, bi.data);
44 | }
45 |
--------------------------------------------------------------------------------
/src/lowpassfilter.h:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #ifndef LOWPASSFILTER_H
23 | #define LOWPASSFILTER_H
24 |
25 | #include "constants.h"
26 | #include "audiodata.h"
27 | #include "workspace.h"
28 |
29 | namespace KeyFinder {
30 |
31 | class LowPassFilterPrivate;
32 |
33 | class LowPassFilter {
34 | public:
35 | LowPassFilter(unsigned int order, unsigned int frameRate, double cornerFrequency, unsigned int fftFrameSize);
36 | ~LowPassFilter();
37 | void filter(AudioData& audio, Workspace& workspace, unsigned int shortcutFactor = 1) const;
38 | void const * getCoefficients() const; // for unit testing only
39 | protected:
40 | LowPassFilterPrivate* priv;
41 | };
42 |
43 | }
44 |
45 | #endif
46 |
--------------------------------------------------------------------------------
/src/spectrumanalyser.h:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #ifndef SPECTRUMANALYSER_H
23 | #define SPECTRUMANALYSER_H
24 |
25 | #include "chromagram.h"
26 | #include "audiodata.h"
27 | #include "fftadapter.h"
28 | #include "chromatransformfactory.h"
29 | #include "constants.h"
30 | #include "temporalwindowfactory.h"
31 | #include "windowfunctions.h"
32 |
33 | namespace KeyFinder {
34 |
35 | class SpectrumAnalyser {
36 | public:
37 | SpectrumAnalyser(unsigned int frameRate, ChromaTransformFactory* ctFactory, TemporalWindowFactory* twFactory);
38 | Chromagram* chromagramOfWholeFrames(AudioData& audio, FftAdapter* const fft) const;
39 | protected:
40 | const ChromaTransform* chromaTransform;
41 | const std::vector* tw;
42 | };
43 |
44 | }
45 |
46 | #endif
47 |
--------------------------------------------------------------------------------
/cmake/FindFFTW3.cmake:
--------------------------------------------------------------------------------
1 | #[=======================================================================[.rst:
2 | FindFFTW3
3 | --------
4 |
5 | Finds the FFTW3 library.
6 |
7 | Imported Targets
8 | ^^^^^^^^^^^^^^^^
9 |
10 | This module provides the following imported targets, if found:
11 |
12 | ``FFTW3::fftw3``
13 | The FFTW3 library
14 |
15 | Result Variables
16 | ^^^^^^^^^^^^^^^^
17 |
18 | This will define the following variables:
19 |
20 | ``FFTW3_FOUND``
21 | True if the system has the FFTW3 library.
22 | ``FFTW3_INCLUDE_DIRS``
23 | Include directories needed to use FFTW3.
24 | ``FFTW3_LIBRARIES``
25 | Libraries needed to link to FFTW3.
26 |
27 | Cache Variables
28 | ^^^^^^^^^^^^^^^
29 |
30 | The following cache variables may also be set:
31 |
32 | ``FFTW3_INCLUDE_DIR``
33 | The directory containing ``fftw3.h``.
34 | ``FFTW3_LIBRARY``
35 | The path to the FFTW3 library.
36 |
37 | #]=======================================================================]
38 |
39 | find_path(FFTW3_INCLUDE_DIR
40 | NAMES fftw3.h
41 | DOC "FFTW3 include directory")
42 | mark_as_advanced(FFTW3_INCLUDE_DIR)
43 |
44 | find_library(FFTW3_LIBRARY
45 | NAMES fftw fftw3 fftw-3.3
46 | DOC "FFTW3 library"
47 | )
48 | mark_as_advanced(FFTW3_LIBRARY)
49 |
50 | include(FindPackageHandleStandardArgs)
51 | find_package_handle_standard_args(
52 | FFTW3
53 | DEFAULT_MSG
54 | FFTW3_LIBRARY
55 | FFTW3_INCLUDE_DIR
56 | )
57 |
58 | if(FFTW3_FOUND)
59 | set(FFTW3_LIBRARIES "${FFTW3_LIBRARY}")
60 | set(FFTW3_INCLUDE_DIRS "${FFTW3_INCLUDE_DIR}")
61 |
62 | if(NOT TARGET FFTW3::fftw3)
63 | add_library(FFTW3::fftw3 UNKNOWN IMPORTED)
64 | set_target_properties(FFTW3::fftw3
65 | PROPERTIES
66 | IMPORTED_LOCATION "${FFTW3_LIBRARY}"
67 | INTERFACE_INCLUDE_DIRECTORIES "${FFTW3_INCLUDE_DIR}"
68 | )
69 | endif()
70 | endif()
71 |
--------------------------------------------------------------------------------
/src/temporalwindowfactory.h:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #ifndef TEMPORALWINDOWFACTORY_H
23 | #define TEMPORALWINDOWFACTORY_H
24 |
25 | #include "constants.h"
26 | #include "windowfunctions.h"
27 |
28 | namespace KeyFinder {
29 |
30 | class TemporalWindowFactory {
31 | public:
32 | TemporalWindowFactory();
33 | ~TemporalWindowFactory();
34 | const std::vector* getTemporalWindow(unsigned int frameSize);
35 | private:
36 | class TemporalWindowWrapper;
37 | std::vector temporalWindows;
38 | std::mutex temporalWindowFactoryMutex;
39 | };
40 |
41 | class TemporalWindowFactory::TemporalWindowWrapper {
42 | public:
43 | TemporalWindowWrapper(unsigned int frameSize);
44 | unsigned int getFrameSize() const;
45 | const std::vector* getTemporalWindow() const;
46 | private:
47 | std::vector temporalWindow;
48 | };
49 |
50 |
51 |
52 |
53 | }
54 |
55 | #endif
56 |
--------------------------------------------------------------------------------
/src/chromatransformfactory.h:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #ifndef CHROMATRANSFORMFACTORY_H
23 | #define CHROMATRANSFORMFACTORY_H
24 |
25 | #include "constants.h"
26 | #include "chromatransform.h"
27 |
28 | namespace KeyFinder {
29 |
30 | class ChromaTransformFactory {
31 | public:
32 | ChromaTransformFactory();
33 | ~ChromaTransformFactory();
34 | const ChromaTransform* getChromaTransform(unsigned int frameRate);
35 | private:
36 | class ChromaTransformWrapper;
37 | std::vector chromaTransforms;
38 | std::mutex chromaTransformFactoryMutex;
39 | };
40 |
41 | class ChromaTransformFactory::ChromaTransformWrapper {
42 | public:
43 | ChromaTransformWrapper(unsigned int frameRate, const ChromaTransform* const transform);
44 | ~ChromaTransformWrapper();
45 | const ChromaTransform* getChromaTransform() const;
46 | unsigned int getFrameRate() const;
47 | private:
48 | unsigned int frameRate;
49 | const ChromaTransform* const chromaTransform;
50 | };
51 |
52 | }
53 |
54 | #endif
55 |
--------------------------------------------------------------------------------
/tests/temporalwindowfactorytest.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "_testhelpers.h"
23 |
24 | TEST (TemporalWindowFactoryTest, FrameSize) {
25 | KeyFinder::TemporalWindowFactory twf;
26 |
27 | const std::vector* tw1 = twf.getTemporalWindow(10);
28 | ASSERT_EQ(10, tw1->size());
29 | }
30 |
31 | TEST (TemporalWindowFactoryTest, Function) {
32 | KeyFinder::TemporalWindowFactory twf;
33 |
34 | const std::vector* tw1 = twf.getTemporalWindow(1000);
35 |
36 | KeyFinder::WindowFunction win;
37 | for (unsigned int i = 0; i < 1000; i++) {
38 | float a = win.window(KeyFinder::WINDOW_BLACKMAN, i, 1000);
39 | float b = tw1->at(i);
40 | ASSERT_FLOAT_EQ(a, b);
41 | }
42 | }
43 |
44 | TEST (TemporalWindowFactoryTest, RepeatedWindowRequests) {
45 | KeyFinder::TemporalWindowFactory twf;
46 |
47 | const std::vector* tw1 = twf.getTemporalWindow(10);
48 | const std::vector* tw2 = twf.getTemporalWindow(10);
49 | const std::vector* tw3 = twf.getTemporalWindow(12);
50 |
51 | ASSERT_EQ(tw1, tw2);
52 | ASSERT_NE(tw2, tw3);
53 | }
54 |
--------------------------------------------------------------------------------
/src/fftadapter.h:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #ifndef FFTADAPTER_H
23 | #define FFTADAPTER_H
24 |
25 | #include "constants.h"
26 |
27 | namespace KeyFinder {
28 |
29 | class FftAdapterPrivate;
30 | class InverseFftAdapterPrivate;
31 |
32 | class FftAdapter {
33 | public:
34 | FftAdapter(unsigned int frameSize);
35 | ~FftAdapter();
36 | unsigned int getFrameSize() const;
37 | void setInput(unsigned int sample, double real);
38 | void execute();
39 | double getOutputReal(unsigned int bin) const;
40 | double getOutputImaginary(unsigned int bin) const;
41 | double getOutputMagnitude(unsigned int bin) const;
42 | protected:
43 | unsigned int frameSize;
44 | FftAdapterPrivate* priv;
45 | };
46 |
47 | class InverseFftAdapter {
48 | public:
49 | InverseFftAdapter(unsigned int frameSize);
50 | ~InverseFftAdapter();
51 | unsigned int getFrameSize() const;
52 | void setInput(unsigned int sample, double real, double imaginary);
53 | void execute();
54 | double getOutput(unsigned int bin) const;
55 | protected:
56 | unsigned int frameSize;
57 | InverseFftAdapterPrivate* priv;
58 | };
59 |
60 | }
61 |
62 | #endif
63 |
--------------------------------------------------------------------------------
/src/keyfinder.h:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #ifndef KEYFINDER_H
23 | #define KEYFINDER_H
24 |
25 | #include "audiodata.h"
26 | #include "lowpassfilterfactory.h"
27 | #include "chromatransformfactory.h"
28 | #include "spectrumanalyser.h"
29 | #include "keyclassifier.h"
30 |
31 | namespace KeyFinder {
32 |
33 | class KeyFinder {
34 | public:
35 |
36 | // for progressive analysis
37 | void progressiveChromagram(AudioData audio, Workspace& workspace);
38 | void finalChromagram(Workspace& workspace);
39 | key_t keyOfChromagram(const Workspace& workspace) const;
40 |
41 | // for analysis of a whole audio file
42 | key_t keyOfAudio(const AudioData& audio);
43 |
44 | // for experimentation with alternative tone profiles
45 | key_t keyOfChromaVector(const std::vector& chromaVector, const std::vector& overrideMajorProfile, const std::vector& overrideMinorProfile) const;
46 |
47 | private:
48 | void preprocess(AudioData& workingAudio, Workspace& workspace, bool flushRemainderBuffer = false);
49 | void chromagramOfBufferedAudio(Workspace& workspace);
50 | key_t keyOfChromaVector(const std::vector& chromaVector) const;
51 | LowPassFilterFactory lpfFactory;
52 | ChromaTransformFactory ctFactory;
53 | TemporalWindowFactory twFactory;
54 | };
55 |
56 | }
57 |
58 | #endif
59 |
--------------------------------------------------------------------------------
/src/lowpassfilterfactory.h:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #ifndef LOWPASSFILTERFACTORY_H
23 | #define LOWPASSFILTERFACTORY_H
24 |
25 | #include "constants.h"
26 | #include "lowpassfilter.h"
27 |
28 | namespace KeyFinder {
29 |
30 | class LowPassFilterFactory {
31 | public:
32 | LowPassFilterFactory();
33 | ~LowPassFilterFactory();
34 | const LowPassFilter* getLowPassFilter(unsigned int order, unsigned int frameRate, double cornerFrequency, unsigned int fftFrameSize);
35 | private:
36 | class LowPassFilterWrapper;
37 | std::vector lowPassFilters;
38 | std::mutex lowPassFilterFactoryMutex;
39 | };
40 |
41 | class LowPassFilterFactory::LowPassFilterWrapper {
42 | public:
43 | LowPassFilterWrapper(unsigned int order, unsigned int frameRate, double cornerFrequency, unsigned int fftFrameSize, const LowPassFilter* const filter);
44 | ~LowPassFilterWrapper();
45 | const LowPassFilter* getLowPassFilter() const;
46 | unsigned int getOrder() const;
47 | unsigned int getFrameRate() const;
48 | double getCornerFrequency() const;
49 | unsigned int getFftFrameSize() const;
50 | private:
51 | unsigned int order;
52 | unsigned int frameRate;
53 | double cornerFrequency;
54 | unsigned int fftFrameSize;
55 | const LowPassFilter* lowPassFilter;
56 | };
57 |
58 | }
59 |
60 | #endif
61 |
--------------------------------------------------------------------------------
/tests/_testhelpers.h:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #ifndef TESTHELPERS_H
23 | #define TESTHELPERS_H
24 |
25 | #include
26 | #include
27 | #include "keyfinder.h"
28 |
29 | // all of this is a bit weak.
30 | #define ASSERT(expr) REQUIRE(expr)
31 | #define ASSERT_TRUE(expr) REQUIRE(expr)
32 | #define ASSERT_FALSE(expr) REQUIRE_FALSE(expr)
33 | #define ASSERT_EQ(a,b) REQUIRE((a) == (b))
34 | #define ASSERT_NE(a,b) REQUIRE((a) != (b))
35 | #define ASSERT_GT(a,b) REQUIRE((a) > (b))
36 | #define ASSERT_GE(a,b) REQUIRE((a) >= (b))
37 | #define ASSERT_LT(a,b) REQUIRE((a) < (b))
38 | #define ASSERT_LE(a,b) REQUIRE((a) <= (b))
39 |
40 | // this is shit. find GTest's macro maybe.
41 | #define TINY 0.0000001
42 | #define ASSERT_FLOAT_EQ(a,b) REQUIRE((a) >= (b) - TINY); REQUIRE((a) <= (b) + TINY)
43 | #define ASSERT_NEAR(a,b,d) REQUIRE((a) >= (b) - (d)); REQUIRE((a) <= (b) + (d))
44 |
45 | // just fix.
46 | #define ASSERT_THROW(expr, exc_type) REQUIRE_THROWS_AS(expr, exc_type)
47 | #define ASSERT_NO_THROW(expr) REQUIRE_NOTHROW(expr)
48 |
49 | // just to keep using GTest's TEST() macro; use a text editor instead and fix.
50 | #define STRINGIFY_ULTRA(s) #s
51 | #define STRINGIFY(s) STRINGIFY_ULTRA(s)
52 | #define TEST(a,b) TEST_CASE(STRINGIFY(a) "/" STRINGIFY(b))
53 |
54 | float sine_wave (
55 | unsigned int index,
56 | float frequency,
57 | unsigned int sampleRate,
58 | unsigned int magnitude = 1
59 | );
60 |
61 | #endif // TESTHELPERS_H
62 |
--------------------------------------------------------------------------------
/tests/tests.pro:
--------------------------------------------------------------------------------
1 | #*************************************************************************
2 | #
3 | # Copyright 2011-2013 Ibrahim Sha'ath
4 | #
5 | # This file is part of LibKeyFinder.
6 | #
7 | # LibKeyFinder 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 | # LibKeyFinder 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 LibKeyFinder. If not, see .
19 | #
20 | #*************************************************************************
21 |
22 | cache()
23 |
24 | TEMPLATE = app
25 | CONFIG += console
26 | CONFIG -= app_bundle
27 | CONFIG -= qt
28 |
29 | CONFIG += c++11
30 | LIBS += -stdlib=libc++
31 | QMAKE_CXXFLAGS += -std=c++11 -stdlib=libc++
32 |
33 | LIBS += -lkeyfinder
34 |
35 | HEADERS += _testhelpers.h
36 |
37 | SOURCES += \
38 | main.cpp \
39 | _testhelpers.cpp \
40 | audiodatatest.cpp \
41 | binodetest.cpp \
42 | chromagramtest.cpp \
43 | chromatransformtest.cpp \
44 | chromatransformfactorytest.cpp \
45 | constantstest.cpp \
46 | downsamplershortcuttest.cpp \
47 | fftadaptertest.cpp \
48 | keyclassifiertest.cpp \
49 | keyfindertest.cpp \
50 | lowpassfiltertest.cpp \
51 | lowpassfilterfactorytest.cpp \
52 | spectrumanalysertest.cpp \
53 | temporalwindowfactorytest.cpp \
54 | toneprofilestest.cpp \
55 | windowfunctiontest.cpp \
56 | workspacetest.cpp
57 |
58 | macx{
59 | QMAKE_MACOSX_DEPLOYMENT_TARGET = 10.7
60 | QMAKE_MAC_SDK = macosx10.12
61 | DEPENDPATH += /usr/local/lib
62 | INCLUDEPATH += /usr/local/include
63 | CONFIG -= ppc ppc64
64 | CONFIG += x86 x86_64
65 | }
66 |
67 | unix|macx{
68 | DEPENDPATH += /usr/local/lib
69 | INCLUDEPATH += /usr/local/include catch
70 | LIBS += -L/usr/local/lib -L/usr/lib
71 | }
72 |
73 | win32{
74 | INCLUDEPATH += C:/minGW32/local/include
75 | DEPENDPATH += C:/minGW32/local/bin
76 | LIBS += -LC:/minGW32/local/bin -LC:/minGW32/local/lib
77 | }
78 |
--------------------------------------------------------------------------------
/src/keyclassifier.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "keyclassifier.h"
23 |
24 | namespace KeyFinder {
25 |
26 | KeyClassifier::KeyClassifier(const std::vector& majorProfile, const std::vector& minorProfile) {
27 |
28 | if (majorProfile.size() != BANDS) {
29 | throw Exception("Tone profile must have 72 elements");
30 | }
31 |
32 | if (minorProfile.size() != BANDS) {
33 | throw Exception("Tone profile must have 72 elements");
34 | }
35 |
36 | major = new ToneProfile(majorProfile);
37 | minor = new ToneProfile(minorProfile);
38 | silence = new ToneProfile(std::vector(BANDS, 0.0));
39 | }
40 |
41 | KeyClassifier::~KeyClassifier() {
42 | delete major;
43 | delete minor;
44 | delete silence;
45 | }
46 |
47 | key_t KeyClassifier::classify(const std::vector& chromaVector) {
48 | std::vector scores(24);
49 | double bestScore = 0.0;
50 | for (unsigned int i = 0; i < SEMITONES; i++) {
51 | double score;
52 | score = major->cosineSimilarity(chromaVector, i); // major
53 | scores[i*2] = score;
54 | score = minor->cosineSimilarity(chromaVector, i); // minor
55 | scores[(i*2)+1] = score;
56 | }
57 | bestScore = silence->cosineSimilarity(chromaVector, 0);
58 | // find best match, defaulting to silence
59 | key_t bestMatch = SILENCE;
60 | for (unsigned int i = 0; i < 24; i++) {
61 | if (scores[i] > bestScore) {
62 | bestScore = scores[i];
63 | bestMatch = (key_t)i;
64 | }
65 | }
66 | return bestMatch;
67 | }
68 |
69 | }
70 |
--------------------------------------------------------------------------------
/src/windowfunctions.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "windowfunctions.h"
23 |
24 | namespace KeyFinder {
25 |
26 | double WindowFunction::window(temporal_window_t windowType, int n, int N) const {
27 | switch (windowType) {
28 | case WINDOW_BLACKMAN:
29 | return 0.42 - (0.5 * cos((2 * PI * n)/(N-1))) + (0.08 * cos((4 * PI * n)/(N-1)));
30 | default:
31 | // This should be unreachable code, but just in case fall back to hamming window.
32 | // fall through
33 | case WINDOW_HAMMING:
34 | return 0.54 - (0.46 * cos((2 * PI * n)/(N-1)));
35 | }
36 |
37 | }
38 |
39 | double WindowFunction::gaussianWindow(int n, int N, double sigma) const {
40 | return exp(-1 * (pow(n - (N / 2), 2) / (2 * sigma * sigma)));
41 | }
42 |
43 | std::vector WindowFunction::convolve(const std::vector& input, const std::vector& window) const {
44 |
45 | unsigned int inputSize = input.size();
46 | unsigned int padding = window.size() / 2;
47 | std::vector convolved(inputSize, 0.0);
48 |
49 | // TODO: this implements zero padding for boundary effects, write something mean-based later.
50 | for (unsigned int sample = 0; sample < inputSize; sample++) {
51 | double convolution = 0.0;
52 | for (unsigned int k = 0; k < window.size(); k++) {
53 | int frm = (signed)sample - (signed)padding + (signed)k;
54 | if (frm >= 0 && frm < (signed)inputSize) {
55 | // don't run off either end
56 | convolution += input[frm] * window[k] / window.size();
57 | }
58 | }
59 | convolved[sample] = convolution;
60 | }
61 | return convolved;
62 | }
63 |
64 | }
65 |
--------------------------------------------------------------------------------
/src/chromatransformfactory.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "chromatransformfactory.h"
23 |
24 | namespace KeyFinder {
25 |
26 | ChromaTransformFactory::ChromaTransformWrapper::ChromaTransformWrapper(unsigned int inFrameRate, const ChromaTransform* const inChromaTransform) : frameRate(inFrameRate), chromaTransform(inChromaTransform) { }
27 |
28 | ChromaTransformFactory::ChromaTransformWrapper::~ChromaTransformWrapper() {
29 | delete chromaTransform;
30 | }
31 |
32 | const ChromaTransform* ChromaTransformFactory::ChromaTransformWrapper::getChromaTransform() const {
33 | return chromaTransform;
34 | }
35 |
36 | unsigned int ChromaTransformFactory::ChromaTransformWrapper::getFrameRate() const {
37 | return frameRate;
38 | }
39 |
40 | ChromaTransformFactory::ChromaTransformFactory() : chromaTransforms(0) { }
41 |
42 | ChromaTransformFactory::~ChromaTransformFactory() {
43 | for (unsigned int i = 0; i < chromaTransforms.size(); i++) {
44 | delete chromaTransforms[i];
45 | }
46 | }
47 |
48 | const ChromaTransform* ChromaTransformFactory::getChromaTransform(unsigned int frameRate) {
49 | for (unsigned int i = 0; i < chromaTransforms.size(); i++) {
50 | ChromaTransformWrapper* wrapper = chromaTransforms[i];
51 | if (wrapper->getFrameRate() == frameRate) {
52 | return wrapper->getChromaTransform();
53 | }
54 | }
55 | chromaTransformFactoryMutex.lock();
56 | chromaTransforms.push_back(new ChromaTransformWrapper(frameRate, new ChromaTransform(frameRate)));
57 | unsigned int newChromaTransformIndex = chromaTransforms.size()-1;
58 | chromaTransformFactoryMutex.unlock();
59 | return chromaTransforms[newChromaTransformIndex]->getChromaTransform();
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/src/spectrumanalyser.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "spectrumanalyser.h"
23 |
24 | namespace KeyFinder {
25 |
26 | SpectrumAnalyser::SpectrumAnalyser(unsigned int frameRate, ChromaTransformFactory* spFactory, TemporalWindowFactory* twFactory) {
27 | chromaTransform = spFactory->getChromaTransform(frameRate);
28 | tw = twFactory->getTemporalWindow(FFTFRAMESIZE);
29 | }
30 |
31 | Chromagram* SpectrumAnalyser::chromagramOfWholeFrames(AudioData& audio, FftAdapter* const fftAdapter) const {
32 |
33 | if (audio.getChannels() != 1) {
34 | throw Exception("Audio must be monophonic to be analysed");
35 | }
36 |
37 | unsigned int frmSize = fftAdapter->getFrameSize();
38 | if (audio.getSampleCount() < frmSize) {
39 | return new Chromagram(0);
40 | }
41 |
42 | unsigned int hops = 1 + ((audio.getSampleCount() - frmSize) / HOPSIZE);
43 | Chromagram* ch = new Chromagram(hops);
44 |
45 | for (unsigned int hop = 0; hop < hops; hop++) {
46 |
47 | audio.resetIterators();
48 | audio.advanceReadIterator(hop * HOPSIZE);
49 |
50 | std::vector::const_iterator twIt = tw->begin();
51 | for (unsigned int sample = 0; sample < frmSize; sample++) {
52 | fftAdapter->setInput(sample, audio.getSampleAtReadIterator() * *twIt);
53 | audio.advanceReadIterator();
54 | std::advance(twIt, 1);
55 | }
56 |
57 | fftAdapter->execute();
58 |
59 | std::vector cv = chromaTransform->chromaVector(fftAdapter);
60 | std::vector::const_iterator cvIt = cv.begin();
61 | for (unsigned int band = 0; band < BANDS; band++) {
62 | ch->setMagnitude(hop, band, *cvIt);
63 | std::advance(cvIt, 1);
64 | }
65 | }
66 | return ch;
67 | }
68 |
69 | }
70 |
--------------------------------------------------------------------------------
/src/temporalwindowfactory.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "temporalwindowfactory.h"
23 |
24 | namespace KeyFinder {
25 |
26 | TemporalWindowFactory::TemporalWindowWrapper::TemporalWindowWrapper(unsigned int frameSize) {
27 | WindowFunction win;
28 | temporalWindow.resize(frameSize);
29 | std::vector::iterator twIt = temporalWindow.begin();
30 | for (unsigned int i = 0; i < frameSize; i++) {
31 | *twIt = win.window(WINDOW_BLACKMAN, i, frameSize);
32 | std::advance(twIt, 1);
33 | }
34 | }
35 |
36 | unsigned int TemporalWindowFactory::TemporalWindowWrapper::getFrameSize() const {
37 | return temporalWindow.size();
38 | }
39 |
40 | const std::vector* TemporalWindowFactory::TemporalWindowWrapper::getTemporalWindow() const {
41 | return &temporalWindow;
42 | }
43 |
44 | TemporalWindowFactory::TemporalWindowFactory() : temporalWindows(0) { }
45 |
46 | TemporalWindowFactory::~TemporalWindowFactory() {
47 | for (unsigned int i = 0; i < temporalWindows.size(); i++) {
48 | delete temporalWindows[i];
49 | }
50 | }
51 |
52 | const std::vector* TemporalWindowFactory::getTemporalWindow(unsigned int frameSize) {
53 | for (unsigned int i = 0; i < temporalWindows.size(); i++) {
54 | TemporalWindowWrapper* wrapper = temporalWindows[i];
55 | if (wrapper->getFrameSize() == frameSize) {
56 | return wrapper->getTemporalWindow();
57 | }
58 | }
59 | temporalWindowFactoryMutex.lock();
60 | temporalWindows.push_back(new TemporalWindowWrapper(frameSize));
61 | unsigned int newTemporalWindowIndex = temporalWindows.size()-1;
62 | temporalWindowFactoryMutex.unlock();
63 | return temporalWindows[newTemporalWindowIndex]->getTemporalWindow();
64 | }
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/tests/fftadaptertest.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "_testhelpers.h"
23 |
24 | TEST (FftAdapterTest, ForwardAndBackward) {
25 |
26 | unsigned int frameSize = 4096;
27 | std::vector original(frameSize);
28 | KeyFinder::FftAdapter forwards(frameSize);
29 |
30 | for (unsigned int i = 0; i < frameSize; i++) {
31 | float sample = 0.0;
32 | sample += sine_wave(i, 2, frameSize, 10000);
33 | sample += sine_wave(i, 4, frameSize, 8000);
34 | sample += sine_wave(i, 5, frameSize, 6000);
35 | sample += sine_wave(i, 7, frameSize, 4000);
36 | sample += sine_wave(i, 13, frameSize, 2000);
37 | sample += sine_wave(i, 20, frameSize, 500);
38 | forwards.setInput(i, sample);
39 | original[i] = sample;
40 | }
41 |
42 | forwards.execute();
43 |
44 | for (unsigned int i = 0; i < frameSize; i++) {
45 | float out = forwards.getOutputMagnitude(i);
46 | if (i == 2) {
47 | ASSERT_FLOAT_EQ(10000 / 2 * frameSize, out);
48 | } else if (i == 4) {
49 | ASSERT_FLOAT_EQ(8000 / 2 * frameSize, out);
50 | } else if (i == 5) {
51 | ASSERT_FLOAT_EQ(6000 / 2 * frameSize, out);
52 | } else if (i == 7) {
53 | ASSERT_FLOAT_EQ(4000 / 2 * frameSize, out);
54 | } else if (i == 13) {
55 | ASSERT_FLOAT_EQ(2000 / 2 * frameSize, out);
56 | } else if (i == 20) {
57 | ASSERT_NEAR(500 / 2 * frameSize, out, 0.1);
58 | } else {
59 | ASSERT_GT(5, out);
60 | }
61 | }
62 |
63 | KeyFinder::InverseFftAdapter backwards(frameSize);
64 |
65 | for (unsigned int i = 0; i < frameSize; i++) {
66 | backwards.setInput(i, forwards.getOutputReal(i), forwards.getOutputImaginary(i));
67 | }
68 |
69 | backwards.execute();
70 |
71 | for (unsigned int i = 0; i < frameSize; i++) {
72 | ASSERT_NEAR(original[i], backwards.getOutput(i), 0.001);
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/src/audiodata.h:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #ifndef AUDIOSTREAM_H
23 | #define AUDIOSTREAM_H
24 |
25 | #include "constants.h"
26 |
27 | namespace KeyFinder {
28 |
29 | class AudioData {
30 | public:
31 | AudioData();
32 |
33 | unsigned int getChannels() const;
34 | unsigned int getFrameRate() const;
35 | double getSample(unsigned int index) const;
36 | double getSampleByFrame(unsigned int frame, unsigned int channel) const;
37 | double getSampleAtReadIterator() const;
38 | unsigned int getSampleCount() const;
39 | unsigned int getFrameCount() const;
40 |
41 | void setChannels(unsigned int newChannels);
42 | void setFrameRate(unsigned int newFrameRate);
43 | void setSample(unsigned int index, double value);
44 | void setSampleByFrame(unsigned int frame, unsigned int channels, double value);
45 | void setSampleAtWriteIterator(double value);
46 | void addToSampleCount(unsigned int newSamples);
47 | void addToFrameCount(unsigned int newFrames);
48 |
49 | void advanceReadIterator(unsigned int by = 1);
50 | void advanceWriteIterator(unsigned int by = 1);
51 | bool readIteratorWithinUpperBound() const;
52 | bool writeIteratorWithinUpperBound() const;
53 | void resetIterators();
54 |
55 | void append(const AudioData& that);
56 | void prepend(const AudioData& that);
57 | void discardFramesFromFront(unsigned int discardFrameCount);
58 | void reduceToMono();
59 | void downsample(unsigned int factor, bool shortcut = true);
60 | AudioData* sliceSamplesFromBack(unsigned int sliceSampleCount);
61 |
62 | private:
63 | std::deque samples;
64 | unsigned int channels;
65 | unsigned int frameRate;
66 | std::deque::const_iterator readIterator;
67 | std::deque::iterator writeIterator;
68 | };
69 |
70 | }
71 |
72 | #endif
73 |
--------------------------------------------------------------------------------
/src/constants.h:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #ifndef CONSTANTS_H
23 | #define CONSTANTS_H
24 |
25 | #include
26 | #include
27 | #include
28 | #include
29 | #include "exception.h"
30 |
31 | #undef PI
32 | #define PI 3.1415926535897932384626433832795
33 |
34 | #undef SEMITONES
35 | #define SEMITONES 12 // per octave, obviously
36 |
37 | #undef OCTAVES
38 | #define OCTAVES 6
39 |
40 | #undef BANDS
41 | #define BANDS (SEMITONES * OCTAVES)
42 |
43 | #undef KEYS
44 | #define KEYS (SEMITONES * 2)
45 |
46 | #undef TONEPROFILESIZE
47 | #define TONEPROFILESIZE (BANDS * 2)
48 |
49 | #undef FFTFRAMESIZE
50 | #define FFTFRAMESIZE 16384
51 |
52 | #undef HOPSIZE
53 | #define HOPSIZE (FFTFRAMESIZE / 4)
54 |
55 | #undef DIRECTSKSTRETCH
56 | #define DIRECTSKSTRETCH 0.8
57 |
58 | namespace KeyFinder {
59 |
60 | enum key_t {
61 | A_MAJOR = 0,
62 | A_MINOR,
63 | B_FLAT_MAJOR,
64 | B_FLAT_MINOR,
65 | B_MAJOR,
66 | B_MINOR = 5,
67 | C_MAJOR,
68 | C_MINOR,
69 | D_FLAT_MAJOR,
70 | D_FLAT_MINOR,
71 | D_MAJOR = 10,
72 | D_MINOR,
73 | E_FLAT_MAJOR,
74 | E_FLAT_MINOR,
75 | E_MAJOR,
76 | E_MINOR = 15,
77 | F_MAJOR,
78 | F_MINOR,
79 | G_FLAT_MAJOR,
80 | G_FLAT_MINOR,
81 | G_MAJOR = 20,
82 | G_MINOR,
83 | A_FLAT_MAJOR,
84 | A_FLAT_MINOR,
85 | SILENCE = 24
86 | };
87 |
88 | enum temporal_window_t {
89 | WINDOW_BLACKMAN,
90 | WINDOW_HAMMING
91 | };
92 |
93 | enum scale_t {
94 | SCALE_MAJOR,
95 | SCALE_MINOR
96 | };
97 |
98 | double getFrequencyOfBand(unsigned int band);
99 | double getLastFrequency();
100 |
101 | const std::vector& toneProfileMajor();
102 | const std::vector& toneProfileMinor();
103 | }
104 |
105 | #endif
106 |
--------------------------------------------------------------------------------
/src/chromagram.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "chromagram.h"
23 |
24 | namespace KeyFinder {
25 |
26 | Chromagram::Chromagram(unsigned int hops) : chromaData(hops, std::vector(BANDS, 0.0)) { }
27 |
28 | double Chromagram::getMagnitude(unsigned int hop, unsigned int band) const {
29 | if (hop >= getHops()) {
30 | std::ostringstream ss;
31 | ss << "Cannot get magnitude of out-of-bounds hop (" << hop << "/" << getHops() << ")";
32 | throw Exception(ss.str().c_str());
33 | }
34 | if (band >= BANDS) {
35 | std::ostringstream ss;
36 | ss << "Cannot get magnitude of out-of-bounds band (" << band << "/" << BANDS << ")";
37 | throw Exception(ss.str().c_str());
38 | }
39 | return chromaData[hop][band];
40 | }
41 |
42 | void Chromagram::setMagnitude(unsigned int hop, unsigned int band, double value) {
43 | if (hop >= getHops()) {
44 | std::ostringstream ss;
45 | ss << "Cannot set magnitude of out-of-bounds hop (" << hop << "/" << getHops() << ")";
46 | throw Exception(ss.str().c_str());
47 | }
48 | if (band >= BANDS) {
49 | std::ostringstream ss;
50 | ss << "Cannot set magnitude of out-of-bounds band (" << band << "/" << BANDS << ")";
51 | throw Exception(ss.str().c_str());
52 | }
53 | if (!std::isfinite(value)) {
54 | throw Exception("Cannot set magnitude to NaN");
55 | }
56 | chromaData[hop][band] = value;
57 | }
58 |
59 | std::vector Chromagram::collapseToOneHop() const {
60 | std::vector oneHop = std::vector(BANDS, 0.0);
61 | for (unsigned int h = 0; h < getHops(); h++) {
62 | for (unsigned int b = 0; b < BANDS; b++) {
63 | oneHop[b] += getMagnitude(h, b) / getHops();
64 | }
65 | }
66 | return oneHop;
67 | }
68 |
69 | void Chromagram::append(const Chromagram& that) {
70 | chromaData.insert(chromaData.end(), that.chromaData.begin(), that.chromaData.end());
71 | }
72 |
73 | unsigned int Chromagram::getHops() const {
74 | return chromaData.size();
75 | }
76 |
77 | }
78 |
--------------------------------------------------------------------------------
/.github/workflows/build-and-test.yml:
--------------------------------------------------------------------------------
1 | name: build
2 |
3 | on:
4 | push:
5 | pull_request:
6 |
7 | jobs:
8 | build:
9 | strategy:
10 | matrix:
11 | include:
12 | - name: Ubuntu 22.04
13 | os: ubuntu-22.04
14 | install_dir: ~/libKeyFinder
15 | cmake_extras: -DCMAKE_BUILD_TYPE=RelWithDebInfo
16 | - name: macOS 12
17 | os: macos-12
18 | install_dir: ~/libKeyFinder
19 | cmake_extras: -DCMAKE_BUILD_TYPE=RelWithDebInfo
20 | - name: Windows 2019
21 | os: windows-2019
22 | install_dir: C:\libKeyFinder
23 | cmake_extras: >-
24 | -DBUILD_TESTING=OFF
25 | -DVCPKG_TARGET_TRIPLET=x64-windows-static
26 | -DCMAKE_TOOLCHAIN_FILE=C:\vcpkg\scripts\buildsystems\vcpkg.cmake
27 | cmake_config: --config RelWithDebInfo
28 | ctest_config: --build-config RelWithDebInfo
29 |
30 | name: ${{ matrix.name }}
31 | runs-on: ${{ matrix.os }}
32 | steps:
33 | - name: Check out Git repository
34 | uses: actions/checkout@v4
35 | - name: "[Ubuntu] Install dependencies"
36 | if: startsWith(matrix.os, 'ubuntu')
37 | run: |
38 | sudo apt-get update
39 | sudo apt-get install -y --no-install-recommends fftw3-dev
40 | - name: "[macOS] Install dependencies"
41 | if: startsWith(matrix.os, 'macos')
42 | run: brew install fftw catch2
43 | - name: "[Windows] Set up vcpkg cache"
44 | uses: actions/cache@v4
45 | if: runner.os == 'Windows'
46 | with:
47 | path: C:\Users\runneradmin\AppData\Local\vcpkg\archives
48 | key: vcpkg-${{ github.head_ref }}-${{ github.run_number }}
49 | restore-keys: |
50 | vcpkg-${{ github.head_ref }}
51 | vcpkg
52 | - name: "[Windows] Install dependencies"
53 | if: startsWith(matrix.os, 'windows')
54 | run: vcpkg install fftw3 catch2
55 | env:
56 | VCPKG_DEFAULT_TRIPLET: x64-windows-static
57 | - name: Set up build directory
58 | run: mkdir build
59 | - name: Configure
60 | run: cmake -DCMAKE_INSTALL_PREFIX=${{ matrix.install_dir }} ${{ matrix.cmake_extras }} ..
61 | working-directory: build
62 | - name: Build
63 | run: cmake --build . ${{ matrix.cmake_config }}
64 | working-directory: build
65 | env:
66 | CMAKE_BUILD_PARALLEL_LEVEL: 2
67 | - name: Install
68 | run: cmake --install . ${{ matrix.cmake_config }}
69 | working-directory: build
70 | - name: Run Tests
71 | if: runner.os != 'Windows'
72 | run: ctest ${{ matrix.ctest_config }} --output-on-failure
73 | working-directory: build
74 | env:
75 | CTEST_PARALLEL_LEVEL: 2
76 | - name: Build example application
77 | run: |
78 | mkdir build
79 | cd build
80 | cmake ${{ matrix.cmake_extras }} ..
81 | cmake --build .
82 | working-directory: examples
83 | env:
84 | CMAKE_PREFIX_PATH: ${{ matrix.install_dir }}
85 | - name: Upload Build Artifact
86 | uses: actions/upload-artifact@v4
87 | with:
88 | name: ${{ matrix.name }} libKeyFinder build
89 | path: ${{ matrix.install_dir }}
90 |
--------------------------------------------------------------------------------
/tests/toneprofilestest.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "_testhelpers.h"
23 |
24 | static void constructToneProfile(std::vector &vec) {
25 | KeyFinder::ToneProfile tp(vec);
26 | }
27 |
28 | TEST (ToneProfilesTest, ExceptionOnWrongCustomSize) {
29 | std::vector vec(71, 0.0);
30 | ASSERT_THROW(constructToneProfile(vec), KeyFinder::Exception);
31 | std::vector vec2(72, 0.0);
32 | ASSERT_NO_THROW(constructToneProfile(vec2));
33 | }
34 | /*
35 | TEST (ToneProfilesTest, ExceptionOnWrongInputSize) {
36 | std::vector vec(144, 0.0);
37 | KeyFinder::ToneProfile tp(KeyFinder::SCALE_MAJOR, vec);
38 | std::vector vec2(73, 0.0);
39 | ASSERT_THROW(tp.similarity(vec2, 0), KeyFinder::Exception);
40 | vec2.resize(72);
41 | ASSERT_NO_THROW(tp.similarity(vec2, 0));
42 | }
43 |
44 | TEST (ToneProfilesTest, PerfectSimilarity) {
45 | std::vector vec(144, 0.0);
46 | vec[0] = 1.0;
47 | vec[3] = 1.0;
48 | vec[7] = 1.0;
49 | KeyFinder::ToneProfile tp(KeyFinder::SCALE_MAJOR, vec);
50 | vec.resize(72);
51 | float result = tp.similarity(vec, 0);
52 | ASSERT_FLOAT_EQ(1.0, result);
53 | }
54 |
55 | TEST (ToneProfilesTest, SimilarityNormalisesMagnitude) {
56 | std::vector vec(144, 0.0);
57 | vec[0] = 1.0;
58 | vec[3] = 1.0;
59 | vec[7] = 1.0;
60 | KeyFinder::ToneProfile tp(KeyFinder::SCALE_MAJOR, vec);
61 | vec.resize(72);
62 | vec[0] = 1000.0;
63 | vec[3] = 1000.0;
64 | vec[7] = 1000.0;
65 | float result = tp.similarity(vec, 0);
66 | ASSERT_FLOAT_EQ(1.0, result);
67 | }
68 |
69 | TEST (ToneProfilesTest, PerfectDissimilarity) {
70 | std::vector vec1(144, 0.0);
71 | vec1[0] = 1.0;
72 | vec1[3] = 1.0;
73 | vec1[7] = 1.0;
74 | std::vector vec2(72, 1.0);
75 | vec2[0] = 0.0;
76 | vec2[3] = 0.0;
77 | vec2[7] = 0.0;
78 | KeyFinder::ToneProfile tp(KeyFinder::SCALE_MAJOR, vec1);
79 | float result = tp.similarity(vec2, 0);
80 | ASSERT_FLOAT_EQ(0.0, result);
81 | }
82 |
83 | TEST (ToneProfilesTest, PartialSimilarity) {
84 | std::vector vec1(144, 0.0);
85 | vec1[0] = 1.0;
86 | vec1[1] = 3.0;
87 | std::vector vec2(72, 0.0);
88 | vec2[0] = 3.0;
89 | vec2[1] = 1.0;
90 | KeyFinder::ToneProfile tp(KeyFinder::SCALE_MAJOR, vec1);
91 | float result = tp.similarity(vec2, 0);
92 | ASSERT_FLOAT_EQ(0.6, result);
93 | }
94 |
95 | */
96 |
--------------------------------------------------------------------------------
/src/toneprofiles.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "toneprofiles.h"
23 |
24 | namespace KeyFinder {
25 |
26 | ToneProfile::ToneProfile(const std::vector& customProfile) {
27 |
28 | if (customProfile.size() != BANDS) {
29 | throw Exception("Tone profile must have 72 elements");
30 | }
31 |
32 | for (unsigned int o = 0; o < OCTAVES; o++) {
33 | Binode *tonic = new Binode((double)customProfile[o * SEMITONES]);
34 | Binode *q = tonic;
35 | for (unsigned int i = 1; ir = new Binode((double)customProfile[o * SEMITONES + i]);
37 | q->r->l = q;
38 | q = q->r;
39 | }
40 | q->r = tonic;
41 | tonic->l = q;
42 |
43 | // offset from A to C (3 semitones)
44 | for (unsigned int i=0; i<3; i++) {
45 | tonic = tonic->r;
46 | }
47 |
48 | tonics.push_back(tonic);
49 | }
50 | }
51 |
52 | ToneProfile::~ToneProfile() {
53 | free();
54 | }
55 |
56 | void ToneProfile::free() {
57 | for (unsigned int o = 0; o < OCTAVES; o++) {
58 | Binode* p = tonics[o];
59 | do {
60 | Binode* zap = p;
61 | p = p->r;
62 | delete zap;
63 | } while (p != tonics[o]);
64 | }
65 | }
66 |
67 | double ToneProfile::cosineSimilarity(const std::vector& input, int offset) const {
68 |
69 | if (input.size() != BANDS) throw Exception("Chroma data must have 72 elements");
70 |
71 | double intersection = 0.0;
72 | double profileNorm = 0.0;
73 | double inputNorm = 0.0;
74 |
75 | for (unsigned int o = 0; o < OCTAVES; o++) {
76 | // Rotate starting pointer left for offset. Each step shifts the position
77 | // of the tonic one step further right of the starting pointer (or one semitone up).
78 | Binode* p = tonics[o];
79 | for (int i=0; il;
81 | }
82 | for (unsigned int i = o * SEMITONES; i < (o + 1) * SEMITONES; i++) {
83 | intersection += input[i] * p->data;
84 | profileNorm += pow((p->data),2);
85 | inputNorm += pow((input[i]),2);
86 | p = p->r;
87 | }
88 | }
89 |
90 | if (profileNorm > 0 && inputNorm > 0) {
91 | // div by zero check
92 | return intersection / (sqrt(profileNorm) * sqrt(inputNorm));
93 | } else {
94 | return 0;
95 | }
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # libkeyfinder
2 |
3 | [](https://github.com/mixxxdj/libkeyfinder/actions/workflows/build-and-test.yml)
4 |
5 | libkeyfinder is a small C++11 library for estimating the musical key of digital audio. It is published under the [GNU General Public License version 3 or later](LICENSE).
6 |
7 | The library was written by [Ibrahim Shaath](http://ibrahimshaath.co.uk/keyfinder/) in 2011 as part of a master's project in computer science, ["Estimations of key in digital music recordings"](https://www.ibrahimshaath.co.uk/keyfinder/KeyFinder.pdf), and originally hosted [in this repo](https://github.com/ibsh/libKeyFinder).
8 |
9 | A [GUI application](https://github.com/ibsh/is_KeyFinder) to use it is available for [macOS](http://www.ibrahimshaath.co.uk/keyfinder/bins/KeyFinder-OSX-2-4.zip) and [Windows](http://www.ibrahimshaath.co.uk/keyfinder/bins/KeyFinder-WIN-1-25.zip). This app is no longer maintained, however, and does not build on contemporary Linux distributions.
10 |
11 | In 2020, Ibrahim handed over maintenance of libkeyfinder to the [Mixxx DJ software](https://mixxx.org) team who incorporated it into Mixxx as of Mixxx 2.3. If you want to discuss anything related to libkeyfinder with us, please get in touch on the [Mixxx Zulip chat](https://mixxx.zulipchat.com/#narrow/stream/109171-development/topic/KeyFinder). Contributions are welcome by opening pull requests and issues on [GitHub](https://github.com/mixxxdj/libkeyfinder).
12 |
13 | ## Installation
14 |
15 | First, you will need to install [FFTW3](http://www.fftw.org/download.html):
16 |
17 | * Fedora: `$ sudo dnf install cmake fftw-devel catch2-devel`
18 | * Debian & Ubuntu: `$ sudo apt install cmake libfftw3-dev`
19 | * Arch Linux: `$ sudo pacman -S cmake fftw catch2`
20 | * MacOS (via [Homebrew](https://brew.sh/)): `$ brew install cmake fftw catch2`
21 | * Windows: `> vcpkg install fftw3 catch2`
22 |
23 | [Catch2](https://github.com/catchorg/Catch2) is required for building the tests. It is not available in Debian 10 or Ubuntu 20.04 LTS,
24 | although it is available in Ubuntu 20.10 and Debian 11 testing. If catch2 is not found, it will be automatically downloaded by CMake.
25 | Alternatively, it's possible disable building the unit tests by passing `-DBUILD_TESTING=OFF` to CMake.
26 |
27 | Once dependencies are installed, from the top level folder of this libkeyfinder repository:
28 |
29 | ```sh
30 | $ cmake -DCMAKE_INSTALL_PREFIX=/where/you/want/to/install/to -S . -B build
31 | $ cmake --build build --parallel number-of-cpu-cores
32 | $ cmake --install build
33 | ```
34 |
35 | If you want to build libkeyfinder statically, add `-DBUILD_SHARED_LIBS=OFF` to the first call to `cmake` above.
36 |
37 | On MacOS, a typical location to install to is `/usr/local` and you can check the number of CPU cores by running `$ sysctl -n hw.logicalcpu`.
38 |
39 | ## Testing
40 |
41 | The tests are built together with the library. Simply run ctest from the build directory:
42 |
43 | ```sh
44 | $ cd build
45 | $ ctest --parallel number-of-cpu-cores
46 | ```
47 |
48 | Note that there is a known intermittent failure in the `FftAdapterTest/ForwardAndBackward` test. Try running the tests a handful of times to determine whether you are hitting the intermittent failure or have introduced a new bug.
49 |
50 | ## Usage
51 |
52 | Refer to the [documentation](https://mixxxdj.github.io/libkeyfinder/).
53 |
--------------------------------------------------------------------------------
/docs/Introduction.txt:
--------------------------------------------------------------------------------
1 | // Documentation (Doxygen) hook
2 | /*! \mainpage KeyFinder library
3 | *
4 | * \section intro_sec Introduction
5 | *
6 | * `libkeyfinder` is a small C++11 library for estimating the musical key of digital audio. It is published under the GNU General Public License (GPL) version 3 or later.
7 | *
8 | * It was written by [Ibrahim Shaath](http://ibrahimshaath.co.uk/keyfinder/) who wrote it in 2011 as part of a master's thesis in computer science.
9 | * A [GUI application](https://github.com/ibsh/is_KeyFinder) to use it is available for [macOS](http://www.ibrahimshaath.co.uk/keyfinder/bins/KeyFinder-OSX-2-4.zip) and [Windows](http://www.ibrahimshaath.co.uk/keyfinder/bins/KeyFinder-WIN-1-25.zip), however that is no longer maintained and does not build on contemporary Linux distributions.
10 | *
11 | * In 2020, Ibrahim handed over maintenance of libkeyfinder to the [Mixxx DJ software](https://mixxx.org) team who incorporated it into Mixxx as of Mixxx 2.3.
12 | * If you want to discuss anything related to libkeyfinder with us, please get in touch on the [Mixxx Zulip chat](https://mixxx.zulipchat.com/#narrow/stream/109171-development/topic/KeyFinder).
13 | * Contributions are welcome by opening pull requests and issues on [GitHub](https://github.com/mixxxdj/libkeyfinder).
14 | *
15 | * \section example_basic Basic Example
16 | *
17 | * For the most basic use case, do something like this:
18 | *
19 | * ```
20 | * // Static because it retains useful resources for repeat use
21 | * static KeyFinder::KeyFinder k;
22 | *
23 | * // Build an empty audio object
24 | * KeyFinder::AudioData a;
25 | *
26 | * // Prepare the object for your audio stream
27 | * a.setFrameRate(yourAudioStream.framerate);
28 | * a.setChannels(yourAudioStream.channels);
29 | * a.addToSampleCount(yourAudioStream.length);
30 | *
31 | * // Copy your audio into the object
32 | * for (int i = 0; i < yourAudioStream.length; i++) {
33 | * a.setSample(i, yourAudioStream[i]);
34 | * }
35 | *
36 | * // Run the analysis
37 | * KeyFinder::key_t key = k.keyOfAudio(a);
38 | *
39 | * // And do something with the result
40 | * doSomethingWith(key);
41 | * ```
42 | *
43 | * \section example_progressive Progressive Estimation Example
44 | *
45 | * Alternatively, you can transform a stream of audio into a chromatic representation, and make progressive estimates of the key:
46 | *
47 | * ```
48 | * KeyFinder::AudioData a;
49 | * a.setFrameRate(yourAudioStream.framerate);
50 | * a.setChannels(yourAudioStream.channels);
51 | * a.addToSampleCount(yourAudioStream.packetLength);
52 | *
53 | * static KeyFinder::KeyFinder k;
54 | *
55 | * // the workspace holds the memory allocations for analysis of a single track
56 | * KeyFinder::Workspace w;
57 | *
58 | * while (someType yourPacket = newAudioPacket()) {
59 | *
60 | * for (int i = 0; i < yourPacket.length; i++) {
61 | * a.setSample(i, yourPacket[i]);
62 | * }
63 | * k.progressiveChromagram(a, w);
64 | *
65 | * // if you want to grab progressive key estimates...
66 | * KeyFinder::key_t key = k.keyOfChromagram(w);
67 | * doSomethingWithMostRecentKeyEstimate(key);
68 | * }
69 | *
70 | * // if you only want a single key estimate, or to squeeze
71 | * // every last bit of audio from the working buffer after
72 | * // progressive estimates...
73 | * k.finalChromagram(w);
74 | *
75 | * // and finally...
76 | * KeyFinder::key key = k.keyOfChromagram(w);
77 | *
78 | * doSomethingWithFinalKeyEstimate(key);
79 | * ```
80 | */
81 |
--------------------------------------------------------------------------------
/src/lowpassfilterfactory.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "lowpassfilterfactory.h"
23 |
24 | namespace KeyFinder {
25 |
26 | LowPassFilterFactory::LowPassFilterWrapper::LowPassFilterWrapper(unsigned int inOrder, unsigned int inFrameRate, double inCornerFrequency, unsigned int inFftFrameSize, const LowPassFilter* const inLowPassFilter) {
27 | order = inOrder;
28 | frameRate = inFrameRate;
29 | cornerFrequency = inCornerFrequency;
30 | fftFrameSize = inFftFrameSize;
31 | lowPassFilter = inLowPassFilter;
32 | }
33 |
34 | LowPassFilterFactory::LowPassFilterWrapper::~LowPassFilterWrapper() {
35 | delete lowPassFilter;
36 | }
37 |
38 | const LowPassFilter* LowPassFilterFactory::LowPassFilterWrapper::getLowPassFilter() const {
39 | return lowPassFilter;
40 | }
41 |
42 | unsigned int LowPassFilterFactory::LowPassFilterWrapper::getOrder() const {
43 | return order;
44 | }
45 |
46 | unsigned int LowPassFilterFactory::LowPassFilterWrapper::getFrameRate() const {
47 | return frameRate;
48 | }
49 |
50 | double LowPassFilterFactory::LowPassFilterWrapper::getCornerFrequency() const {
51 | return cornerFrequency;
52 | }
53 |
54 | unsigned int LowPassFilterFactory::LowPassFilterWrapper::getFftFrameSize() const {
55 | return fftFrameSize;
56 | }
57 |
58 | LowPassFilterFactory::LowPassFilterFactory() : lowPassFilters(0) { }
59 |
60 | LowPassFilterFactory::~LowPassFilterFactory() {
61 | for (unsigned int i = 0; i < lowPassFilters.size(); i++) {
62 | delete lowPassFilters[i];
63 | }
64 | }
65 |
66 | const LowPassFilter* LowPassFilterFactory::getLowPassFilter(unsigned int inOrder, unsigned int inFrameRate, double inCornerFrequency, unsigned int inFftFrameSize) {
67 | for (unsigned int i = 0; i < lowPassFilters.size(); i++) {
68 | LowPassFilterWrapper* wrapper = lowPassFilters[i];
69 | if (wrapper->getOrder() == inOrder &&
70 | wrapper->getFrameRate() == inFrameRate &&
71 | wrapper->getCornerFrequency() == inCornerFrequency &&
72 | wrapper->getFftFrameSize() == inFftFrameSize) {
73 | return wrapper->getLowPassFilter();
74 | }
75 | }
76 | lowPassFilterFactoryMutex.lock();
77 | LowPassFilter *lpf = new LowPassFilter(inOrder, inFrameRate, inCornerFrequency, inFftFrameSize);
78 | lowPassFilters.push_back(new LowPassFilterWrapper(inOrder, inFrameRate, inCornerFrequency, inFftFrameSize, lpf));
79 | unsigned int newLowPassFilterIndex = lowPassFilters.size()-1;
80 | lowPassFilterFactoryMutex.unlock();
81 | return lowPassFilters[newLowPassFilterIndex]->getLowPassFilter();
82 | }
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/tests/downsamplershortcuttest.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "_testhelpers.h"
23 |
24 | TEST (DownsamplerShortcutTest, EverythingWorksWithShortcutFactor) {
25 |
26 | unsigned int channels = 1;
27 | unsigned int frameRate = 44100;
28 | unsigned int frames = frameRate * 5;
29 | float magnitude = 1000.0;
30 | float tolerance = 0.05 * magnitude;
31 | float highFrequency = 21000.0;
32 | float lowFrequency = 800.0;
33 | float cornerFrequency = 6500.0;
34 | unsigned int factor = 3;
35 | unsigned int filterOrder = 160;
36 | unsigned int filterFFT = 2048;
37 |
38 | // make two sine waves, several seconds long
39 | KeyFinder::AudioData a;
40 | a.setChannels(channels);
41 | a.setFrameRate(frameRate);
42 | a.addToFrameCount(frames);
43 | for (unsigned int i = 0; i < frames; i++) {
44 | float sample = 0.0;
45 | sample += sine_wave(i, highFrequency, frameRate, magnitude); // high freq
46 | sample += sine_wave(i, lowFrequency, frameRate, magnitude); // low freq
47 | for (unsigned int j = 0; j < channels; j++) {
48 | a.setSampleByFrame(i, j, sample);
49 | }
50 | }
51 |
52 | KeyFinder::LowPassFilter* lpf = new KeyFinder::LowPassFilter(filterOrder, frameRate, cornerFrequency, filterFFT);
53 | KeyFinder::Workspace w;
54 | lpf->filter(a, w, factor);
55 | delete lpf;
56 |
57 | // test for lower wave only in the useful samples,
58 | // and expect the non-useful samples to stay unfiltered
59 | for (unsigned int i = 0; i < frames; i++) {
60 | if (i % factor == 0) {
61 | float expected = sine_wave(i, lowFrequency, frameRate, magnitude);
62 | for (unsigned int j = 0; j < channels; j++) {
63 | ASSERT_NEAR(expected, a.getSampleByFrame(i, j), tolerance);
64 | }
65 | } else {
66 | float expected = 0.0;
67 | expected += sine_wave(i, highFrequency, frameRate, magnitude); // high freq
68 | expected += sine_wave(i, lowFrequency, frameRate, magnitude); // low freq
69 | for (unsigned int j = 0; j < channels; j++) {
70 | ASSERT_FLOAT_EQ(expected, a.getSampleByFrame(i, j));
71 | }
72 | }
73 | }
74 |
75 | a.downsample(factor);
76 |
77 | ASSERT_EQ(channels, a.getChannels());
78 | ASSERT_EQ(frameRate / factor, a.getFrameRate());
79 | ASSERT_EQ(frames / factor, a.getFrameCount());
80 |
81 | // and test for integrity of wave after downsample
82 | for (unsigned int i = 0; i < frames / factor; i++) {
83 | float expected = sine_wave(i, lowFrequency, frameRate / factor, magnitude);
84 | for (unsigned int j = 0; j < channels; j++) {
85 | ASSERT_NEAR(expected, a.getSampleByFrame(i, j), tolerance);
86 | }
87 | }
88 |
89 | }
90 |
--------------------------------------------------------------------------------
/src/chromatransform.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "chromatransform.h"
23 |
24 | namespace KeyFinder {
25 |
26 | ChromaTransform::ChromaTransform(unsigned int inFrameRate) {
27 |
28 | frameRate = inFrameRate;
29 | if (frameRate < 1) {
30 | throw Exception("Frame rate must be > 0");
31 | }
32 |
33 | if (getLastFrequency() > frameRate / 2.0) {
34 | throw Exception("Analysis frequencies over Nyquist");
35 | }
36 |
37 | if (frameRate / (double)FFTFRAMESIZE > (getFrequencyOfBand(1) - getFrequencyOfBand(0))) {
38 | throw Exception("Insufficient low-end resolution");
39 | }
40 |
41 | chromaBandFftBinOffsets.resize(BANDS, 0);
42 | directSpectralKernel.resize(BANDS, std::vector(0, 0.0));
43 |
44 | double myQFactor = DIRECTSKSTRETCH * (pow(2,(1.0 / SEMITONES))-1);
45 |
46 | for (unsigned int i = 0; i < BANDS; i++) {
47 |
48 | double centreOfWindow = getFrequencyOfBand(i) * FFTFRAMESIZE / inFrameRate;
49 | double widthOfWindow = centreOfWindow * myQFactor;
50 | double beginningOfWindow = centreOfWindow - (widthOfWindow / 2);
51 | double endOfWindow = beginningOfWindow + widthOfWindow;
52 |
53 | double sumOfCoefficients = 0.0;
54 |
55 | chromaBandFftBinOffsets[i] = ceil(beginningOfWindow); // first useful fft bin
56 | for (unsigned int fftBin = chromaBandFftBinOffsets[i]; fftBin <= floor(endOfWindow); fftBin++) {
57 | double coefficient = kernelWindow(fftBin - beginningOfWindow, widthOfWindow);
58 | sumOfCoefficients += coefficient;
59 | directSpectralKernel[i].push_back(coefficient);
60 | }
61 |
62 | // normalisation by sum of coefficients and frequency of bin; models CQT very closely
63 | for (unsigned int j = 0; j < directSpectralKernel[i].size(); j++) {
64 | directSpectralKernel[i][j] = directSpectralKernel[i][j] / sumOfCoefficients * getFrequencyOfBand(i);
65 | }
66 | }
67 | }
68 |
69 | double ChromaTransform::kernelWindow(double n, double N) const {
70 | // discretely sampled continuous function, but different to other window functions
71 | return 1.0 - cos((2 * PI * n) / N);
72 | }
73 |
74 | std::vector ChromaTransform::chromaVector(const FftAdapter* const fftAdapter) const {
75 | std::vector chromaVector(BANDS);
76 | for (unsigned int i = 0; i < BANDS; i++) {
77 | double sum = 0.0;
78 | for (unsigned int j = 0; j < directSpectralKernel[i].size(); j++) {
79 | double magnitude = fftAdapter->getOutputMagnitude(chromaBandFftBinOffsets[i]+j);
80 | sum += (magnitude * directSpectralKernel[i][j]);
81 | }
82 | chromaVector[i] = sum;
83 | }
84 | return chromaVector;
85 | }
86 |
87 | }
88 |
--------------------------------------------------------------------------------
/tests/windowfunctiontest.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "_testhelpers.h"
23 |
24 | TEST (WindowFunctionTest, AllTemporalWindowsAreSymmetricalAndRangeFrom0To1) {
25 |
26 | KeyFinder::WindowFunction win;
27 | unsigned int evenWidth = 24;
28 | unsigned int oddWidth = 25;
29 |
30 | for (unsigned int w = 0; w < 4; w++) {
31 |
32 | KeyFinder::temporal_window_t type;
33 | if (w % 2 == 0) type = KeyFinder::WINDOW_BLACKMAN;
34 | else type = KeyFinder::WINDOW_HAMMING;
35 |
36 | unsigned int width;
37 | if (w / 2 == 0) width = evenWidth;
38 | else width = oddWidth;
39 |
40 | ASSERT_NEAR(0.0, win.window(type, 0, width), 0.1);
41 | ASSERT_NEAR(1.0, win.window(type, width / 2, width), 0.1);
42 | ASSERT_NEAR(0.0, win.window(type, width - 1, width), 0.1);
43 | for (unsigned int n = 0; n < width / 2; n++) {
44 | ASSERT_FLOAT_EQ(win.window(type, n, width), win.window(type, width - 1 - n, width));
45 | }
46 | }
47 | }
48 |
49 | TEST (WindowFunctionTest, GaussianFn) {
50 | KeyFinder::WindowFunction win;
51 | unsigned int width = 23;
52 | std::vector g(width, 0.0);
53 | for (unsigned int i = 0; i < width; i++)
54 | g[i] = win.gaussianWindow(i, width, sqrt(12.0));
55 | ASSERT_NEAR(0.0, g[0], 0.01);
56 | for (unsigned int i = 1; i < width / 2; i++)
57 | ASSERT_GT(g[i], g[i-1]);
58 | ASSERT_FLOAT_EQ(1.0, g[width / 2]);
59 | for (unsigned int i = width / 2 + 1; i < width; i++)
60 | ASSERT_LT(g[i], g[i-1]);
61 | ASSERT_NEAR(0.0, g[width - 1], 0.01);
62 | }
63 |
64 | TEST (WindowFunctionTest, ConvolutionOfPulseAndRectangle) {
65 | KeyFinder::WindowFunction win;
66 | unsigned int width = 101;
67 | std::vector a(width, 0.0);
68 | a[width/2] = 1.0;
69 | std::vector b(width, 1.0);
70 | std::vector c = win.convolve(a, b);
71 | for (unsigned int i = 0; i < width; i++) {
72 | float a = c[i];
73 | ASSERT_FLOAT_EQ(1.0 / width, a);
74 | }
75 | }
76 |
77 | TEST (WindowFunctionTest, ConvolutionOfTwoRectangles) {
78 | KeyFinder::WindowFunction win;
79 | unsigned int width = 101;
80 | std::vector a(width, 1.0);
81 | std::vector b(width, 1.0);
82 | std::vector c = win.convolve(a, b);
83 | ASSERT_NEAR(0.5, c[0], 0.01);
84 | ASSERT_NEAR(1.0, c[width / 2], 0.01);
85 | ASSERT_NEAR(0.5, c[width - 1], 0.01);
86 | }
87 |
88 | TEST (WindowFunctionTest, ConvolutionOfPulseAndCurve) {
89 | KeyFinder::WindowFunction win;
90 | unsigned int width = 101;
91 | std::vector a(width, 0.0);
92 | a[width/2] = 1.0;
93 | std::vector b(width, 0.0);
94 | for(unsigned int i = 0; i < width; i++)
95 | b[i] = win.window(KeyFinder::WINDOW_BLACKMAN, i, width);
96 | std::vector c = win.convolve(a, b);
97 | for(unsigned int i = 0; i < width; i++) {
98 | float a = c[i];
99 | ASSERT_FLOAT_EQ(win.window(KeyFinder::WINDOW_BLACKMAN, i, width) / width, a);
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/tests/chromagramtest.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "_testhelpers.h"
23 |
24 | TEST (ChromagramTest, ConstructorDefaultsWork) {
25 | KeyFinder::Chromagram c;
26 | ASSERT_EQ(0, c.getHops());
27 | }
28 |
29 | TEST (ChromagramTest, ConstructorArgumentsWork) {
30 | KeyFinder::Chromagram c(20);
31 | ASSERT_EQ(20, c.getHops());
32 | for (int h = 0; h < 20; h++) {
33 | for (int b = 0; b < BANDS; b++) {
34 | ASSERT_FLOAT_EQ(0.0, c.getMagnitude(h, b));
35 | }
36 | }
37 | }
38 |
39 | TEST (ChromagramTest, Mutator) {
40 | KeyFinder::Chromagram c(1);
41 | c.setMagnitude(0, 0, 1.0);
42 | ASSERT_FLOAT_EQ(1.0, c.getMagnitude(0, 0));
43 | }
44 |
45 | TEST (ChromagramTest, CopyConstructor) {
46 | KeyFinder::Chromagram c(1);
47 | c.setMagnitude(0, 0, 1.0);
48 | ASSERT_EQ(1, c.getHops());
49 | ASSERT_FLOAT_EQ(1.0, c.getMagnitude(0, 0));
50 | ASSERT_FLOAT_EQ(0.0, c.getMagnitude(0, 1));
51 |
52 | KeyFinder::Chromagram c2(c);
53 | ASSERT_EQ(1, c2.getHops());
54 | ASSERT_FLOAT_EQ(1.0, c2.getMagnitude(0, 0));
55 | ASSERT_FLOAT_EQ(0.0, c2.getMagnitude(0, 1));
56 | }
57 |
58 | TEST (ChromagramTest, Assignment) {
59 | KeyFinder::Chromagram c(1);
60 | c.setMagnitude(0, 0, 1.0);
61 | ASSERT_EQ(1, c.getHops());
62 | ASSERT_FLOAT_EQ(1.0, c.getMagnitude(0, 0));
63 | ASSERT_FLOAT_EQ(0.0, c.getMagnitude(0, 1));
64 |
65 | KeyFinder::Chromagram c2 = c;
66 | ASSERT_EQ(1, c2.getHops());
67 | ASSERT_FLOAT_EQ(1.0, c2.getMagnitude(0, 0));
68 | ASSERT_FLOAT_EQ(0.0, c2.getMagnitude(0, 1));
69 | }
70 |
71 | TEST (ChromagramTest, Bounds) {
72 | KeyFinder::Chromagram c(5);
73 | // hops min max
74 | ASSERT_THROW(c.getMagnitude(-1, 0), KeyFinder::Exception);
75 | ASSERT_THROW(c.getMagnitude( 5, 0), KeyFinder::Exception);
76 | ASSERT_THROW(c.setMagnitude(-1, 0, 1.0), KeyFinder::Exception);
77 | ASSERT_THROW(c.setMagnitude( 5, 0, 1.0), KeyFinder::Exception);
78 | // bands min max
79 | ASSERT_THROW(c.getMagnitude( 0, -1), KeyFinder::Exception);
80 | ASSERT_THROW(c.getMagnitude( 0, BANDS), KeyFinder::Exception);
81 | ASSERT_THROW(c.setMagnitude( 0, -1, 1.0), KeyFinder::Exception);
82 | ASSERT_THROW(c.setMagnitude( 0, BANDS, 1.0), KeyFinder::Exception);
83 | // value bounds
84 | ASSERT_THROW(c.setMagnitude( 0, 0, INFINITY), KeyFinder::Exception);
85 | ASSERT_THROW(c.setMagnitude( 0, 0, NAN), KeyFinder::Exception);
86 | }
87 |
88 | TEST (ChromagramTest, Append) {
89 | KeyFinder::Chromagram a(1);
90 | KeyFinder::Chromagram b(1);
91 | a.setMagnitude(0, 0, 10.0);
92 | b.setMagnitude(0, 0, 20.0);
93 | ASSERT_NO_THROW(a.append(b));
94 | ASSERT_EQ(2, a.getHops());
95 | ASSERT_FLOAT_EQ(10.0, a.getMagnitude(0, 0));
96 | ASSERT_FLOAT_EQ(20.0, a.getMagnitude(1, 0));
97 | }
98 |
99 | TEST (ChromagramTest, CollapseToOneHop) {
100 |
101 | KeyFinder::Chromagram c(3);
102 | c.setMagnitude(0, 0, 10.0);
103 | c.setMagnitude(1, 0, 15.0);
104 | c.setMagnitude(2, 0, 20.0);
105 |
106 | std::vector d = c.collapseToOneHop();
107 |
108 | ASSERT_EQ(72, d.size());
109 | ASSERT_FLOAT_EQ(15.0, d[0]);
110 | }
111 |
--------------------------------------------------------------------------------
/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.5)
2 | project(KeyFinder VERSION 2.2.8)
3 | set(CMAKE_CXX_STANDARD 11)
4 | set(CMAKE_CXX_STANDARD_REQUIRED True)
5 |
6 | option(BUILD_SHARED_LIBS "Build dynamic library" ON)
7 |
8 | add_library(keyfinder
9 | src/audiodata.cpp
10 | src/chromagram.cpp
11 | src/chromatransform.cpp
12 | src/chromatransformfactory.cpp
13 | src/fftadapter.cpp
14 | src/keyclassifier.cpp
15 | src/keyfinder.cpp
16 | src/lowpassfilter.cpp
17 | src/lowpassfilterfactory.cpp
18 | src/spectrumanalyser.cpp
19 | src/temporalwindowfactory.cpp
20 | src/toneprofiles.cpp
21 | src/windowfunctions.cpp
22 | src/workspace.cpp
23 | src/constants.cpp
24 | )
25 |
26 | set_target_properties(keyfinder PROPERTIES
27 | SOVERSION ${PROJECT_VERSION_MAJOR}
28 | VERSION ${PROJECT_VERSION})
29 |
30 | list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
31 | find_package(FFTW3 REQUIRED)
32 | target_link_libraries(keyfinder PUBLIC FFTW3::fftw3)
33 |
34 | target_include_directories(keyfinder PUBLIC
35 | $
36 | $
37 | )
38 |
39 | set_target_properties(keyfinder PROPERTIES
40 | WINDOWS_EXPORT_ALL_SYMBOLS TRUE
41 | )
42 |
43 | #
44 | # Installation
45 | #
46 | include(GNUInstallDirs)
47 | include(CMakePackageConfigHelpers)
48 |
49 | # Library
50 | install(TARGETS keyfinder
51 | EXPORT KeyFinderTargets
52 | ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
53 | LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}"
54 | RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
55 | INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
56 | )
57 |
58 | # Headers
59 | install(FILES
60 | src/audiodata.h
61 | src/chromagram.h
62 | src/chromatransform.h
63 | src/chromatransformfactory.h
64 | src/fftadapter.h
65 | src/keyclassifier.h
66 | src/keyfinder.h
67 | src/lowpassfilter.h
68 | src/lowpassfilterfactory.h
69 | src/spectrumanalyser.h
70 | src/temporalwindowfactory.h
71 | src/toneprofiles.h
72 | src/windowfunctions.h
73 | src/workspace.h
74 | src/constants.h
75 | src/exception.h
76 | src/binode.h
77 | DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/keyfinder")
78 |
79 | # pkgconfig
80 | if(IS_ABSOLUTE "${CMAKE_INSTALL_LIBDIR}")
81 | set(PKGCONFIG_LIBDIR "${CMAKE_INSTALL_LIBDIR}")
82 | else()
83 | set(PKGCONFIG_LIBDIR "\${prefix}/${CMAKE_INSTALL_LIBDIR}")
84 | endif()
85 | if(IS_ABSOLUTE "${CMAKE_INSTALL_INCLUDEDIR}")
86 | set(PKGCONFIG_INCLUDEDIR "${CMAKE_INSTALL_INCLUDEDIR}")
87 | else()
88 | set(PKGCONFIG_INCLUDEDIR "\${prefix}/${CMAKE_INSTALL_INCLUDEDIR}")
89 | endif()
90 | configure_file(${CMAKE_CURRENT_SOURCE_DIR}/packaging/libkeyfinder.pc.in
91 | ${CMAKE_CURRENT_BINARY_DIR}/packaging/libkeyfinder.pc @ONLY)
92 | install(FILES ${CMAKE_CURRENT_BINARY_DIR}/packaging/libkeyfinder.pc DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
93 |
94 | # CMake config
95 | set(KEYFINDER_INSTALL_CMAKEDIR "${CMAKE_INSTALL_LIBDIR}/cmake/KeyFinder")
96 | install(
97 | EXPORT KeyFinderTargets
98 | FILE KeyFinderTargets.cmake
99 | NAMESPACE KeyFinder::
100 | DESTINATION "${KEYFINDER_INSTALL_CMAKEDIR}"
101 | )
102 | configure_package_config_file(packaging/KeyFinderConfig.cmake.in
103 | "${CMAKE_CURRENT_BINARY_DIR}/packaging/KeyFinderConfig.cmake"
104 | INSTALL_DESTINATION "${KEYFINDER_INSTALL_CMAKEDIR}"
105 | )
106 | write_basic_package_version_file(
107 | "${CMAKE_CURRENT_BINARY_DIR}/packaging/KeyFinderConfigVersion.cmake"
108 | VERSION "${CMAKE_PROJECT_VERSION}"
109 | COMPATIBILITY SameMajorVersion
110 | )
111 | install(
112 | FILES
113 | "${CMAKE_CURRENT_BINARY_DIR}/packaging/KeyFinderConfig.cmake"
114 | "${CMAKE_CURRENT_BINARY_DIR}/packaging/KeyFinderConfigVersion.cmake"
115 | DESTINATION "${KEYFINDER_INSTALL_CMAKEDIR}"
116 | )
117 | install(FILES cmake/FindFFTW3.cmake DESTINATION "${KEYFINDER_INSTALL_CMAKEDIR}/modules")
118 |
119 | #
120 | # Tests
121 | #
122 | include(CTest)
123 | if(BUILD_TESTING)
124 | add_subdirectory(tests)
125 | endif()
126 |
--------------------------------------------------------------------------------
/tests/chromatransformtest.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "_testhelpers.h"
23 |
24 | TEST (ChromaTransformTest, InsistsOnPositiveFrameRate) {
25 | KeyFinder::ChromaTransform* ct = NULL;
26 | ASSERT_THROW(ct = new KeyFinder::ChromaTransform(0), KeyFinder::Exception);
27 | ASSERT_EQ(NULL, ct);
28 | ASSERT_NO_THROW(ct = new KeyFinder::ChromaTransform(4410));
29 | ASSERT_NO_THROW(delete ct);
30 | }
31 |
32 | TEST (ChromaTransformTest, InsistsOnNyquistHigherThanAnalysisFreqs) {
33 | float high = KeyFinder::getLastFrequency();
34 | KeyFinder::ChromaTransform* ct = NULL;
35 | ASSERT_THROW(ct = new KeyFinder::ChromaTransform(high * 2 - 1), KeyFinder::Exception);
36 | ASSERT_EQ(NULL, ct);
37 | ASSERT_NO_THROW(ct = new KeyFinder::ChromaTransform(high * 2 + 1));
38 | delete ct;
39 | }
40 |
41 | TEST (ChromaTransformTest, InsistsOnSufficientBassResolution) {
42 | KeyFinder::ChromaTransform* ct = NULL;
43 | ASSERT_THROW(ct = new KeyFinder::ChromaTransform(31861), KeyFinder::Exception);
44 | ASSERT_EQ(NULL, ct);
45 | ASSERT_NO_THROW(ct = new KeyFinder::ChromaTransform(31860));
46 | delete ct;
47 | }
48 |
49 | // Inheritance so we can get the (private) kernel out.
50 | class MyChromaTransform : public KeyFinder::ChromaTransform {
51 | public:
52 | MyChromaTransform(unsigned int f) : KeyFinder::ChromaTransform(f) { }
53 | std::vector getChromaBandFftBinOffsets() { return chromaBandFftBinOffsets; }
54 | std::vector< std::vector > getDirectSpectralKernel() { return directSpectralKernel; }
55 | };
56 |
57 | /*TEST (ChromaTransformTest, TestSpectralKernel) {
58 | MyChromaTransform* myCt = NULL;
59 | myCt = new MyChromaTransform(4410);
60 | std::vector cbfbo = myCt->getChromaBandFftBinOffsets();
61 | std::vector< std::vector > dsk = myCt->getDirectSpectralKernel();
62 | delete myCt;
63 |
64 | // ensure correct element sizes
65 | ASSERT_EQ(BANDS, cbfbo.size());
66 | ASSERT_EQ(BANDS, dsk.size());
67 |
68 | // ensure offsets and sizes increase as frequency increases
69 | for (unsigned int i = 1; i < BANDS; i++) {
70 | ASSERT_GT(cbfbo[i], cbfbo[i-1]);
71 | ASSERT_GE(dsk[i].size(), dsk[i-1].size());
72 | }
73 |
74 | // ensure that the relationship between frequency and bandwidth is constantish
75 | float q = KeyFinder::getLastFrequency() / dsk[dsk.size() - 1].size();
76 | for (unsigned int i = 0; i < BANDS; i++) {
77 | ASSERT_NEAR(q, KeyFinder::getFrequencyOfBand(i) / dsk[i].size(), q / 6);
78 | }
79 |
80 | // ensure that each kernel element is an up-and-down curve,
81 | // and that the peak is the vector's centre +/- 1,
82 | // and that the peak is at the expected frequency.
83 | for (unsigned int i = 0; i < BANDS; i++) {
84 | int peak = -1;
85 | for (unsigned int j = 1; j < dsk[i].size(); j++) {
86 | if (peak < 0) {
87 | if(dsk[i][j] <= dsk[i][j-1]) peak = j-1;
88 | } else {
89 | ASSERT_LT(dsk[i][j], dsk[i][j-1]);
90 | }
91 | }
92 | ASSERT_NEAR((dsk[i].size() / 2), peak, 1);
93 | float peakFrequency = (cbfbo[i] + peak) * 4410.0 / FFTFRAMESIZE;
94 | ASSERT_NEAR(KeyFinder::getFrequencyOfBand(i), peakFrequency, 0.2);
95 | }
96 | }*/
97 |
--------------------------------------------------------------------------------
/tests/keyclassifiertest.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "_testhelpers.h"
23 |
24 | /*
25 | TEST (KeyClassifierTest, DetectsSilence) {
26 | KeyFinder::KeyClassifier kc(simCos, tpS, false);
27 | std::vector chroma(12);
28 | ASSERT_EQ(KeyFinder::SILENCE, kc.classify(chroma));
29 | }
30 |
31 | TEST (KeyClassifierTest, DetectsAMinorTriad) {
32 | std::vector chromaNoOffset(12);
33 | chromaNoOffset[0] = 1.0; // A
34 | chromaNoOffset[3] = 1.0; // C
35 | chromaNoOffset[7] = 1.0; // E
36 |
37 | std::vector chromaOffset(12);
38 | chromaOffset[9] = 1.0; // A, offset
39 | chromaOffset[0] = 1.0; // C, offset
40 | chromaOffset[4] = 1.0; // E, offset
41 |
42 | // No offset, cosine similarity
43 | KeyFinder::KeyClassifier kc1(simCos, tpK, false);
44 | ASSERT_EQ(KeyFinder::A_MINOR, kc1.classify(chromaNoOffset));
45 | KeyFinder::KeyClassifier kc2(simCos, tpT, false);
46 | ASSERT_EQ(KeyFinder::A_MINOR, kc2.classify(chromaNoOffset));
47 | KeyFinder::KeyClassifier kc3(simCos, tpG, false);
48 | ASSERT_EQ(KeyFinder::A_MINOR, kc3.classify(chromaNoOffset));
49 | KeyFinder::KeyClassifier kc4(simCos, tpS, false);
50 | ASSERT_EQ(KeyFinder::A_MINOR, kc4.classify(chromaNoOffset));
51 |
52 | // No offset, correlation
53 | KeyFinder::KeyClassifier kc5(simCor, tpK, false);
54 | ASSERT_EQ(KeyFinder::A_MINOR, kc5.classify(chromaNoOffset));
55 | KeyFinder::KeyClassifier kc6(simCor, tpT, false);
56 | ASSERT_EQ(KeyFinder::A_MINOR, kc6.classify(chromaNoOffset));
57 | KeyFinder::KeyClassifier kc7(simCor, tpG, false);
58 | ASSERT_EQ(KeyFinder::A_MINOR, kc7.classify(chromaNoOffset));
59 | KeyFinder::KeyClassifier kc8(simCor, tpS, false);
60 | ASSERT_EQ(KeyFinder::A_MINOR, kc8.classify(chromaNoOffset));
61 |
62 | // With offset, cosine similarity
63 | KeyFinder::KeyClassifier kc9(simCos, tpK, true);
64 | ASSERT_EQ(KeyFinder::A_MINOR, kc9.classify(chromaOffset));
65 | KeyFinder::KeyClassifier kc10(simCos, tpT, true);
66 | ASSERT_EQ(KeyFinder::A_MINOR, kc10.classify(chromaOffset));
67 | KeyFinder::KeyClassifier kc11(simCos, tpG, true);
68 | ASSERT_EQ(KeyFinder::A_MINOR, kc11.classify(chromaOffset));
69 | KeyFinder::KeyClassifier kc12(simCos, tpS, true);
70 | ASSERT_EQ(KeyFinder::A_MINOR, kc12.classify(chromaOffset));
71 |
72 | // With offset, correlation
73 | KeyFinder::KeyClassifier kc13(simCor, tpK, true);
74 | ASSERT_EQ(KeyFinder::A_MINOR, kc13.classify(chromaOffset));
75 | KeyFinder::KeyClassifier kc14(simCor, tpT, true);
76 | ASSERT_EQ(KeyFinder::A_MINOR, kc14.classify(chromaOffset));
77 | KeyFinder::KeyClassifier kc15(simCor, tpG, true);
78 | ASSERT_EQ(KeyFinder::A_MINOR, kc15.classify(chromaOffset));
79 | KeyFinder::KeyClassifier kc16(simCor, tpS, true);
80 | ASSERT_EQ(KeyFinder::A_MINOR, kc16.classify(chromaOffset));
81 | }
82 |
83 | TEST (KeyClassifierTest, DetectsOtherTriads) {
84 | // all with offset
85 | std::vector cMajor(12);
86 | cMajor[0] = 1.0;
87 | cMajor[4] = 1.0;
88 | cMajor[7] = 1.0;
89 |
90 | std::vector cMinor(12);
91 | cMinor[0] = 1.0;
92 | cMinor[3] = 1.0;
93 | cMinor[7] = 1.0;
94 |
95 | std::vector gMajor(12);
96 | gMajor[7] = 1.0;
97 | gMajor[11] = 1.0;
98 | gMajor[2] = 1.0;
99 |
100 | KeyFinder::KeyClassifier kc(simCos, tpS, true);
101 | ASSERT_EQ(KeyFinder::C_MAJOR, kc.classify(cMajor));
102 | ASSERT_EQ(KeyFinder::C_MINOR, kc.classify(cMinor));
103 | ASSERT_EQ(KeyFinder::G_MAJOR, kc.classify(gMajor));
104 | }
105 | */
106 |
--------------------------------------------------------------------------------
/src/keyfinder.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "keyfinder.h"
23 |
24 | namespace KeyFinder {
25 |
26 | key_t KeyFinder::keyOfAudio(const AudioData& originalAudio) {
27 |
28 | Workspace workspace;
29 | progressiveChromagram(originalAudio, workspace);
30 | finalChromagram(workspace);
31 |
32 | return keyOfChromaVector(workspace.chromagram->collapseToOneHop());
33 | }
34 |
35 | void KeyFinder::progressiveChromagram(AudioData audio, Workspace& workspace) {
36 | preprocess(audio, workspace);
37 | workspace.preprocessedBuffer.append(audio);
38 | chromagramOfBufferedAudio(workspace);
39 | }
40 |
41 | void KeyFinder::finalChromagram(Workspace& workspace) {
42 | // flush remainder buffer
43 | if (workspace.remainderBuffer.getSampleCount() > 0) {
44 | AudioData flush;
45 | preprocess(flush, workspace, true);
46 | }
47 | // zero padding
48 | unsigned int paddedHopCount = ceil(workspace.preprocessedBuffer.getSampleCount() / (double)HOPSIZE);
49 | unsigned int finalSampleLength = FFTFRAMESIZE + ((paddedHopCount - 1) * HOPSIZE);
50 | workspace.preprocessedBuffer.addToSampleCount(finalSampleLength - workspace.preprocessedBuffer.getSampleCount());
51 | chromagramOfBufferedAudio(workspace);
52 | }
53 |
54 | void KeyFinder::preprocess(AudioData& workingAudio, Workspace& workspace, bool flushRemainderBuffer) {
55 |
56 | workingAudio.reduceToMono();
57 |
58 | if (workspace.remainderBuffer.getChannels() > 0) {
59 | workingAudio.prepend(workspace.remainderBuffer);
60 | workspace.remainderBuffer.discardFramesFromFront(workspace.remainderBuffer.getFrameCount());
61 | }
62 |
63 | // TODO: there is presumably some good maths to determine filter frequencies. For now, this approximates original experiment values.
64 | double lpfCutoff = getLastFrequency() * 1.012;
65 | double dsCutoff = getLastFrequency() * 1.10;
66 | unsigned int downsampleFactor = (int) floor(workingAudio.getFrameRate() / 2 / dsCutoff);
67 |
68 | unsigned int bufferExcess = workingAudio.getSampleCount() % downsampleFactor;
69 | if (!flushRemainderBuffer && bufferExcess != 0) {
70 | AudioData* remainder = workingAudio.sliceSamplesFromBack(bufferExcess);
71 | workspace.remainderBuffer.append(*remainder);
72 | delete remainder;
73 | }
74 |
75 | const LowPassFilter* lpf = lpfFactory.getLowPassFilter(160, workingAudio.getFrameRate(), lpfCutoff, 2048);
76 | lpf->filter(workingAudio, workspace, downsampleFactor);
77 | // note we don't delete the LPF; it's stored in the factory for reuse
78 |
79 | workingAudio.downsample(downsampleFactor);
80 | }
81 |
82 | void KeyFinder::chromagramOfBufferedAudio(Workspace& workspace) {
83 | if (workspace.fftAdapter == NULL) {
84 | workspace.fftAdapter = new FftAdapter(FFTFRAMESIZE);
85 | }
86 | SpectrumAnalyser sa(workspace.preprocessedBuffer.getFrameRate(), &ctFactory, &twFactory);
87 | Chromagram* c = sa.chromagramOfWholeFrames(workspace.preprocessedBuffer, workspace.fftAdapter);
88 | workspace.preprocessedBuffer.discardFramesFromFront(HOPSIZE * c->getHops());
89 | if (workspace.chromagram == NULL) {
90 | workspace.chromagram = c;
91 | } else {
92 | workspace.chromagram->append(*c);
93 | delete c;
94 | }
95 | }
96 |
97 | key_t KeyFinder::keyOfChromaVector(const std::vector& chromaVector) const {
98 | KeyClassifier classifier(toneProfileMajor(), toneProfileMinor());
99 | return classifier.classify(chromaVector);
100 | }
101 |
102 | key_t KeyFinder::keyOfChromaVector(const std::vector &chromaVector, const std::vector &overrideMajorProfile, const std::vector &overrideMinorProfile) const {
103 | KeyClassifier classifier(overrideMajorProfile, overrideMinorProfile);
104 | return classifier.classify(chromaVector);
105 | }
106 |
107 | key_t KeyFinder::keyOfChromagram(const Workspace& workspace) const {
108 | KeyClassifier classifier(toneProfileMajor(), toneProfileMinor());
109 | return classifier.classify(workspace.chromagram->collapseToOneHop());
110 | }
111 |
112 | }
113 |
--------------------------------------------------------------------------------
/src/constants.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "constants.h"
23 |
24 | namespace KeyFinder {
25 |
26 | static double FREQUENCIES[] = {
27 | 32.7031956625748,
28 | 34.647828872109,
29 | 36.708095989676,
30 | 38.8908729652601,
31 | 41.2034446141088,
32 | 43.6535289291255,
33 | 46.2493028389543,
34 | 48.9994294977187,
35 | 51.9130871974932,
36 | 55,
37 | 58.2704701897613,
38 | 61.7354126570155,
39 | 65.4063913251497,
40 | 69.2956577442181,
41 | 73.4161919793519,
42 | 77.7817459305203,
43 | 82.4068892282175,
44 | 87.307057858251,
45 | 92.4986056779087,
46 | 97.9988589954374,
47 | 103.826174394986,
48 | 110,
49 | 116.540940379523,
50 | 123.470825314031,
51 | 130.812782650299,
52 | 138.591315488436,
53 | 146.832383958704,
54 | 155.563491861041,
55 | 164.813778456435,
56 | 174.614115716502,
57 | 184.997211355817,
58 | 195.997717990875,
59 | 207.652348789973,
60 | 220,
61 | 233.081880759045,
62 | 246.941650628062,
63 | 261.625565300599,
64 | 277.182630976872,
65 | 293.664767917408,
66 | 311.126983722081,
67 | 329.62755691287,
68 | 349.228231433004,
69 | 369.994422711635,
70 | 391.99543598175,
71 | 415.304697579946,
72 | 440.000000000001,
73 | 466.163761518091,
74 | 493.883301256125,
75 | 523.251130601198,
76 | 554.365261953745,
77 | 587.329535834816,
78 | 622.253967444163,
79 | 659.255113825741,
80 | 698.456462866009,
81 | 739.98884542327,
82 | 783.9908719635,
83 | 830.609395159892,
84 | 880.000000000002,
85 | 932.327523036182,
86 | 987.76660251225,
87 | 1046.5022612024,
88 | 1108.73052390749,
89 | 1174.65907166963,
90 | 1244.50793488833,
91 | 1318.51022765148,
92 | 1396.91292573202,
93 | 1479.97769084654,
94 | 1567.981743927,
95 | 1661.21879031978,
96 | 1760,
97 | 1864.65504607236,
98 | 1975.5332050245
99 | };
100 |
101 | double getFrequencyOfBand(unsigned int band) {
102 | if (band >= BANDS) {
103 | std::ostringstream ss;
104 | ss << "Cannot get frequency of out-of-bounds band index (" << band << "/" << BANDS << ")";
105 | throw Exception(ss.str().c_str());
106 | }
107 | return FREQUENCIES[band];
108 | }
109 |
110 | double getLastFrequency() {
111 | return FREQUENCIES[BANDS - 1];
112 | }
113 |
114 | static double MAJOR_PROFILE[SEMITONES] = {
115 | 7.23900502618145225142,
116 | 3.50351166725158691406,
117 | 3.58445177536649417505,
118 | 2.84511816478676315967,
119 | 5.81898892118549859731,
120 | 4.55865057415321039969,
121 | 2.44778850545506543313,
122 | 6.99473192146829525484,
123 | 3.39106613673504853068,
124 | 4.55614256655143456953,
125 | 4.07392666663523606019,
126 | 4.45932757378886890365,
127 | };
128 |
129 | static double MINOR_PROFILE[SEMITONES] = {
130 | 7.00255045060284420089,
131 | 3.14360279015996679775,
132 | 4.35904319714962529275,
133 | 5.40418120718934069657,
134 | 3.67234420879306133756,
135 | 4.08971184917797891956,
136 | 3.90791435991553992579,
137 | 6.19960288562316463867,
138 | 3.63424625625277419871,
139 | 2.87241191079875557435,
140 | 5.35467999794542670600,
141 | 3.83242038595048351013,
142 | };
143 |
144 | static double OCTAVE_WEIGHTS[OCTAVES] = {
145 | 0.39997267549999998559,
146 | 0.55634425248300645173,
147 | 0.52496636345143543600,
148 | 0.60847548384277727607,
149 | 0.59898115679999996974,
150 | 0.49072435317960994006,
151 | };
152 |
153 | static std::vector tpMajor;
154 | static std::vector tpMinor;
155 |
156 | const std::vector& toneProfileMajor() {
157 | if (tpMajor.size() == 0) {
158 | for (unsigned int o = 0; o < OCTAVES; o++) {
159 | for (unsigned int s = 0; s < SEMITONES; s++) {
160 | tpMajor.push_back(OCTAVE_WEIGHTS[o] * MAJOR_PROFILE[s]);
161 | }
162 | }
163 | }
164 | return tpMajor;
165 | }
166 |
167 | const std::vector& toneProfileMinor() {
168 | if (tpMinor.size() == 0) {
169 | for (unsigned int o = 0; o < OCTAVES; o++) {
170 | for (unsigned int s = 0; s < SEMITONES; s++) {
171 | tpMinor.push_back(OCTAVE_WEIGHTS[o] * MINOR_PROFILE[s]);
172 | }
173 | }
174 | }
175 | return tpMinor;
176 | }
177 |
178 | }
179 |
--------------------------------------------------------------------------------
/examples/basic.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #include
6 | #include
7 |
8 | // WAVE header as described here:
9 | // http://soundfile.sapp.org/doc/WaveFormat/
10 | typedef struct WAVE_HEADER {
11 | /* RIFF Chunk Descriptor */
12 | uint8_t ChunkID[4];
13 | uint32_t ChunkSize;
14 | uint8_t Format[4];
15 | /* "fmt" sub-chunk */
16 | uint8_t SubChunk1ID[4];
17 | uint32_t SubChunk1Size;
18 | uint16_t AudioFormat;
19 | uint16_t NumChannels;
20 | uint32_t SampleRate;
21 | uint32_t ByteRate;
22 | uint16_t BlockAlign;
23 | uint16_t BitsPerSample;
24 | /* "data" sub-chunk */
25 | uint8_t Subchunk2ID[4];
26 | uint32_t Subchunk2Size;
27 | } wave_header_t;
28 |
29 | int main(int argc, char* argv[]) {
30 | if (argc != 2) {
31 | fprintf(stderr, "usage: %s WAVE_FILE\n", argv[0]);
32 | return 1;
33 | }
34 |
35 | const char* filePath = argv[1];
36 | FILE* file = fopen(filePath, "r");
37 | if (file == nullptr) {
38 | fprintf(stderr, "Failed to open WAVE file: %s\n", filePath);
39 | return 2;
40 | }
41 |
42 | wave_header_t waveHeader;
43 | size_t bytesRead = fread(&waveHeader, 1, sizeof(waveHeader), file);
44 | if (bytesRead < sizeof(waveHeader)) {
45 | fprintf(stderr, "Failed to read WAVE header.\n");
46 | return 3;
47 | }
48 |
49 | const size_t sampleSize = waveHeader.BitsPerSample / 8;
50 | const auto numSamples = static_cast(waveHeader.Subchunk2Size / (waveHeader.NumChannels * sampleSize));
51 |
52 | // Prepare the object for your audio stream
53 | KeyFinder::AudioData a;
54 | printf("Sample Rate: %d\n", waveHeader.SampleRate);
55 | a.setFrameRate(waveHeader.SampleRate);
56 | printf("Num Channels: %d\n", waveHeader.NumChannels);
57 | a.setChannels(waveHeader.NumChannels);
58 | printf("Num Samples: %u\n", numSamples);
59 | a.addToSampleCount(numSamples);
60 |
61 | // Copy audio into the object
62 | int8_t* buffer = new int8_t[sampleSize];
63 | int i = 0;
64 | while (fread(buffer, sizeof(buffer[0]), sampleSize / (sizeof buffer[0]), file) == sampleSize) {
65 | uint32_t sample = 0;
66 | for(int i = 0; i < sampleSize; i++) {
67 | sample |= buffer[i] << (i * 8);
68 | }
69 | a.setSample(i, sample);
70 | i++;
71 | }
72 | delete[] buffer;
73 | fclose(file);
74 |
75 | // Run the analysis
76 | KeyFinder::KeyFinder k;
77 | KeyFinder::key_t key = k.keyOfAudio(a);
78 | // And do something with the result
79 | switch(key) {
80 | case KeyFinder::A_MAJOR:
81 | puts("A major\n");
82 | break;
83 | case KeyFinder::A_MINOR:
84 | puts("A minor\n");
85 | break;
86 | case KeyFinder::B_FLAT_MAJOR:
87 | puts("B flat major\n");
88 | break;
89 | case KeyFinder::B_FLAT_MINOR:
90 | puts("B flat minor\n");
91 | break;
92 | case KeyFinder::B_MAJOR:
93 | puts("B major\n");
94 | break;
95 | case KeyFinder::B_MINOR:
96 | puts("B minor\n");
97 | break;
98 | case KeyFinder::C_MAJOR:
99 | puts("C major\n");
100 | break;
101 | case KeyFinder::C_MINOR:
102 | puts("C minor\n");
103 | break;
104 | case KeyFinder::D_FLAT_MAJOR:
105 | puts("D flat major\n");
106 | break;
107 | case KeyFinder::D_FLAT_MINOR:
108 | puts("D flat major\n");
109 | break;
110 | case KeyFinder::D_MAJOR:
111 | puts("D major\n");
112 | break;
113 | case KeyFinder::D_MINOR:
114 | puts("D minor\n");
115 | break;
116 | case KeyFinder::E_FLAT_MAJOR:
117 | puts("E flat major\n");
118 | break;
119 | case KeyFinder::E_FLAT_MINOR:
120 | puts("E flat minor\n");
121 | break;
122 | case KeyFinder::E_MAJOR:
123 | puts("E major\n");
124 | break;
125 | case KeyFinder::E_MINOR:
126 | puts("E minor\n");
127 | break;
128 | case KeyFinder::F_MAJOR:
129 | puts("G major\n");
130 | break;
131 | case KeyFinder::F_MINOR:
132 | puts("G minor\n");
133 | break;
134 | case KeyFinder::G_FLAT_MAJOR:
135 | puts("G flat major\n");
136 | break;
137 | case KeyFinder::G_FLAT_MINOR:
138 | puts("G flat minor\n");
139 | break;
140 | case KeyFinder::G_MAJOR:
141 | puts("G major\n");
142 | break;
143 | case KeyFinder::G_MINOR:
144 | puts("G minor\n");
145 | break;
146 | case KeyFinder::A_FLAT_MAJOR:
147 | puts("A flat major\n");
148 | break;
149 | case KeyFinder::A_FLAT_MINOR:
150 | puts("A flat minor\n");
151 | break;
152 | case KeyFinder::SILENCE:
153 | puts("Silence\n");
154 | break;
155 | }
156 |
157 | return 0;
158 | }
159 |
--------------------------------------------------------------------------------
/src/fftadapter.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "fftadapter.h"
23 |
24 | // Included here to allow substitution of a separate implementation .cpp
25 | #include
26 | #include
27 | #include
28 |
29 | namespace KeyFinder {
30 |
31 | std::mutex fftwPlanMutex;
32 |
33 | class FftAdapterPrivate {
34 | public:
35 | double* inputReal;
36 | fftw_complex* outputComplex;
37 | fftw_plan plan;
38 | };
39 |
40 | FftAdapter::FftAdapter(unsigned int inFrameSize) : priv(new FftAdapterPrivate) {
41 | frameSize = inFrameSize;
42 | priv->inputReal = (double*)fftw_malloc(sizeof(double) * frameSize);
43 | priv->outputComplex = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * frameSize);
44 | memset(priv->outputComplex, 0, sizeof(fftw_complex) * frameSize);
45 | fftwPlanMutex.lock();
46 | priv->plan = fftw_plan_dft_r2c_1d(frameSize, priv->inputReal, priv->outputComplex, FFTW_ESTIMATE);
47 | fftwPlanMutex.unlock();
48 | }
49 |
50 | FftAdapter::~FftAdapter() {
51 | fftw_destroy_plan(priv->plan);
52 | fftw_free(priv->inputReal);
53 | fftw_free(priv->outputComplex);
54 | delete priv;
55 | }
56 |
57 | unsigned int FftAdapter::getFrameSize() const {
58 | return frameSize;
59 | }
60 |
61 | void FftAdapter::setInput(unsigned int i, double real) {
62 | if (i >= frameSize) {
63 | std::ostringstream ss;
64 | ss << "Cannot set out-of-bounds sample (" << i << "/" << frameSize << ")";
65 | throw Exception(ss.str().c_str());
66 | }
67 | if (!std::isfinite(real)) {
68 | throw Exception("Cannot set sample to NaN");
69 | }
70 | priv->inputReal[i] = real;
71 | }
72 |
73 | double FftAdapter::getOutputReal(unsigned int i) const {
74 | if (i >= frameSize) {
75 | std::ostringstream ss;
76 | ss << "Cannot get out-of-bounds sample (" << i << "/" << frameSize << ")";
77 | throw Exception(ss.str().c_str());
78 | }
79 | return priv->outputComplex[i][0];
80 | }
81 |
82 | double FftAdapter::getOutputImaginary(unsigned int i) const {
83 | if (i >= frameSize) {
84 | std::ostringstream ss;
85 | ss << "Cannot get out-of-bounds sample (" << i << "/" << frameSize << ")";
86 | throw Exception(ss.str().c_str());
87 | }
88 | return priv->outputComplex[i][1];
89 | }
90 |
91 | double FftAdapter::getOutputMagnitude(unsigned int i) const {
92 | if (i >= frameSize) {
93 | std::ostringstream ss;
94 | ss << "Cannot get out-of-bounds sample (" << i << "/" << frameSize << ")";
95 | throw Exception(ss.str().c_str());
96 | }
97 | return sqrt( pow(getOutputReal(i), 2) + pow(getOutputImaginary(i), 2) );
98 | }
99 |
100 | void FftAdapter::execute() {
101 | fftw_execute(priv->plan);
102 | }
103 |
104 | // ================================= INVERSE =================================
105 |
106 | class InverseFftAdapterPrivate {
107 | public:
108 | fftw_complex* inputComplex;
109 | double* outputReal;
110 | fftw_plan plan;
111 | };
112 |
113 | InverseFftAdapter::InverseFftAdapter(unsigned int inFrameSize) : priv(new InverseFftAdapterPrivate) {
114 | frameSize = inFrameSize;
115 | priv->inputComplex = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * frameSize);
116 | priv->outputReal = (double*)fftw_malloc(sizeof(double) * frameSize);
117 | fftwPlanMutex.lock();
118 | priv->plan = fftw_plan_dft_c2r_1d(frameSize, priv->inputComplex, priv->outputReal, FFTW_ESTIMATE);
119 | fftwPlanMutex.unlock();
120 | }
121 |
122 | InverseFftAdapter::~InverseFftAdapter() {
123 | fftw_destroy_plan(priv->plan);
124 | fftw_free(priv->inputComplex);
125 | fftw_free(priv->outputReal);
126 | delete priv;
127 | }
128 |
129 | unsigned int InverseFftAdapter::getFrameSize() const {
130 | return frameSize;
131 | }
132 |
133 | void InverseFftAdapter::setInput(unsigned int i, double real, double imag) {
134 | if (i >= frameSize) {
135 | std::ostringstream ss;
136 | ss << "Cannot set out-of-bounds sample (" << i << "/" << frameSize << ")";
137 | throw Exception(ss.str().c_str());
138 | }
139 | if (!std::isfinite(real) || !std::isfinite(imag)) {
140 | throw Exception("Cannot set sample to NaN");
141 | }
142 | priv->inputComplex[i][0] = real;
143 | priv->inputComplex[i][1] = imag;
144 | }
145 |
146 | double InverseFftAdapter::getOutput(unsigned int i) const {
147 | if (i >= frameSize) {
148 | std::ostringstream ss;
149 | ss << "Cannot get out-of-bounds sample (" << i << "/" << frameSize << ")";
150 | throw Exception(ss.str().c_str());
151 | }
152 | // divide by frameSize to normalise
153 | return priv->outputReal[i] / frameSize;
154 | }
155 |
156 | void InverseFftAdapter::execute() {
157 | fftw_execute(priv->plan);
158 | }
159 |
160 | }
161 |
--------------------------------------------------------------------------------
/tests/keyfindertest.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "_testhelpers.h"
23 |
24 | TEST (KeyFinderTest, BasicUseCase) {
25 | unsigned int sampleRate = 44100;
26 | KeyFinder::AudioData inputAudio;
27 | inputAudio.setChannels(1);
28 | inputAudio.setFrameRate(sampleRate);
29 | inputAudio.addToSampleCount(sampleRate);
30 | for (unsigned int i = 0; i < sampleRate; i++) {
31 | float sample = 0.0;
32 | sample += sine_wave(i, 440.0000, sampleRate, 1);
33 | sample += sine_wave(i, 523.2511, sampleRate, 1);
34 | sample += sine_wave(i, 659.2551, sampleRate, 1);
35 | inputAudio.setSample(i, sample);
36 | }
37 | KeyFinder::KeyFinder kf;
38 | ASSERT_EQ(KeyFinder::A_MINOR, kf.keyOfAudio(inputAudio));
39 | }
40 |
41 | TEST (KeyFinderTest, ProgressiveUseCase) {
42 |
43 | /*
44 | * Build a second of audio, to be added ten times. The default settings will
45 | * lead to a downsample factor of 10, so there'll be 44100 samples of audio
46 | * after pre-processing. That'll be 7 hops, with 15428 samples left in the
47 | * buffer. Then finish that off with finalChromagramOfAudio, which should add
48 | * 4 more hops and leave 12288 zeroed samples in the buffer.
49 | */
50 |
51 | unsigned int sampleRate = 44100;
52 | KeyFinder::AudioData inputAudio;
53 | inputAudio.setFrameRate(sampleRate);
54 | inputAudio.setChannels(1);
55 | inputAudio.addToSampleCount(sampleRate);
56 | for (unsigned int i = 0; i < sampleRate; i++) {
57 | float sample = 0.0;
58 | sample += sine_wave(i, 440.0000, sampleRate, 1);
59 | sample += sine_wave(i, 523.2511, sampleRate, 1);
60 | sample += sine_wave(i, 659.2551, sampleRate, 1);
61 | inputAudio.setSample(i, sample);
62 | }
63 |
64 | /*
65 | * Add an annoying bit of silence at the beginning to mess with our perfect
66 | * integral relationship with the downsample factor, though it shouldn't alter
67 | * the numbers above.
68 | */
69 |
70 | KeyFinder::AudioData offset;
71 | offset.setFrameRate(sampleRate);
72 | offset.setChannels(1);
73 | offset.addToSampleCount(4);
74 |
75 | KeyFinder::KeyFinder k;
76 | KeyFinder::Workspace w;
77 | KeyFinder::FftAdapter* testFftPointer = NULL;
78 |
79 | k.progressiveChromagram(offset, w);
80 | ASSERT_EQ(4, w.remainderBuffer.getSampleCount());
81 | for (unsigned int i = 0; i < 10; i++) {
82 | k.progressiveChromagram(inputAudio, w);
83 | // ensure we're using the same FFT adapter throughout
84 | if (testFftPointer == NULL) testFftPointer = w.fftAdapter;
85 | ASSERT_EQ(testFftPointer, w.fftAdapter);
86 | ASSERT_EQ(4410, w.preprocessedBuffer.getFrameRate());
87 | ASSERT_EQ(1, w.preprocessedBuffer.getChannels());
88 | // check that the offset left some unprocessed audio in the remainder
89 | ASSERT_EQ(4, w.remainderBuffer.getSampleCount());
90 | // and that the remainder is equal to the last 4 samples which were excluded
91 | for (unsigned int j = 0; j < 4; j++) {
92 | ASSERT_FLOAT_EQ(
93 | inputAudio.getSample(inputAudio.getSampleCount() - 4 + j),
94 | w.remainderBuffer.getSample(j)
95 | );
96 | }
97 | }
98 |
99 | // progressive result without emptying preprocessedBuffer
100 | ASSERT_EQ(7, w.chromagram->getHops());
101 | ASSERT_EQ(15428, w.preprocessedBuffer.getSampleCount());
102 |
103 | // after emptying preprocessedBuffer
104 | k.finalChromagram(w);
105 | ASSERT_EQ(0, w.remainderBuffer.getSampleCount());
106 | ASSERT_EQ(11, w.chromagram->getHops());
107 | ASSERT_EQ(12288, w.preprocessedBuffer.getSampleCount());
108 |
109 | for (unsigned int i = 0; i < w.preprocessedBuffer.getSampleCount(); i++) {
110 | ASSERT_FLOAT_EQ(0.0, w.preprocessedBuffer.getSample(i));
111 | }
112 |
113 | ASSERT_EQ(KeyFinder::A_MINOR, k.keyOfChromagram(w));
114 | }
115 |
116 | TEST (KeyFinderTest, KeyOfChromagramReturnsSilence) {
117 | KeyFinder::Workspace w;
118 | w.chromagram = new KeyFinder::Chromagram(1);
119 | KeyFinder::KeyFinder kf;
120 | ASSERT_EQ(KeyFinder::SILENCE, kf.keyOfChromagram(w));
121 | }
122 |
123 | TEST (KeyFinderTest, KeyOfChromagramPassesThroughChromaData) {
124 | KeyFinder::Workspace w;
125 | w.chromagram = new KeyFinder::Chromagram(1);
126 | w.chromagram->setMagnitude(0, 24 + 0, 10000.0);
127 | w.chromagram->setMagnitude(0, 24 + 3, 10000.0);
128 | w.chromagram->setMagnitude(0, 24 + 7, 10000.0);
129 | KeyFinder::KeyFinder kf;
130 |
131 | ASSERT_EQ(KeyFinder::C_MINOR, kf.keyOfChromagram(w));
132 | }
133 |
134 | TEST (KeyFinderTest, KeyOfChromagramCollapsesTimeDimension) {
135 | KeyFinder::Workspace w;
136 | w.chromagram = new KeyFinder::Chromagram(5);
137 | w.chromagram->setMagnitude(1, 24 + 0, 1.0);
138 | w.chromagram->setMagnitude(2, 24 + 3, 1.0);
139 | w.chromagram->setMagnitude(3, 24 + 7, 1.0);
140 | KeyFinder::KeyFinder kf;
141 | ASSERT_EQ(KeyFinder::C_MINOR, kf.keyOfChromagram(w));
142 | }
143 |
--------------------------------------------------------------------------------
/src/lowpassfilter.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | /*************************************************************************
23 |
24 | The low pass filter implementation is based on the work of Tony Fisher,
25 | as shown at http://www-users.cs.york.ac.uk/~fisher/mkfilter/
26 |
27 | *************************************************************************/
28 |
29 | #include "lowpassfilter.h"
30 |
31 | // implementation specific
32 | #include "fftadapter.h"
33 | #include "windowfunctions.h"
34 |
35 | namespace KeyFinder {
36 |
37 | class LowPassFilterPrivate {
38 | public:
39 | LowPassFilterPrivate(unsigned int order, unsigned int frameRate, double cornerFrequency, unsigned int fftFrameSize);
40 | void filter(AudioData& audio, Workspace& workspace, unsigned int shortcutFactor = 1) const;
41 | unsigned int order;
42 | unsigned int delay; // always order / 2
43 | unsigned int impulseLength; // always order + 1
44 | double gain;
45 | std::vector coefficients;
46 | };
47 |
48 | LowPassFilter::LowPassFilter(unsigned int order, unsigned int frameRate, double cornerFrequency, unsigned int fftFrameSize) {
49 | priv = new LowPassFilterPrivate(order, frameRate, cornerFrequency, fftFrameSize);
50 | }
51 |
52 | LowPassFilter::~LowPassFilter() {
53 | if (priv != nullptr) {
54 | delete priv;
55 | }
56 | }
57 |
58 | void LowPassFilter::filter(AudioData& audio, Workspace& workspace, unsigned int shortcutFactor) const {
59 | priv->filter(audio, workspace, shortcutFactor);
60 | }
61 |
62 | void const * LowPassFilter::getCoefficients() const {
63 | return &priv->coefficients;
64 | }
65 |
66 | LowPassFilterPrivate::LowPassFilterPrivate(unsigned int inOrder, unsigned int frameRate, double cornerFrequency, unsigned int fftFrameSize) {
67 | if (inOrder % 2 != 0) {
68 | throw Exception("LPF order must be an even number");
69 | }
70 | if (inOrder > fftFrameSize / 4) {
71 | throw Exception("LPF order must be <= FFT frame size / 4");
72 | }
73 | order = inOrder;
74 | delay = order / 2;
75 | impulseLength = order + 1;
76 | double cutoffPoint = cornerFrequency / frameRate;
77 | InverseFftAdapter* ifft = new InverseFftAdapter(fftFrameSize);
78 |
79 | // Build frequency domain response
80 | double tau = 0.5 / cutoffPoint;
81 | for (unsigned int i = 0; i < fftFrameSize/2; i++) {
82 | double input = 0.0;
83 | if (i / (double) fftFrameSize <= cutoffPoint) {
84 | input = tau;
85 | }
86 | ifft->setInput(i, input, 0.0);
87 | ifft->setInput(fftFrameSize - i - 1, input, 0.0);
88 | }
89 |
90 | // inverse FFT to determine time-domain response
91 | ifft->execute();
92 |
93 | // TODO determine whether to handle bad_alloc
94 | coefficients.resize(impulseLength, 0.0);
95 | unsigned int centre = order / 2;
96 | gain = 0.0;
97 | WindowFunction win;
98 |
99 | for (unsigned int i = 0; i < impulseLength; i++) {
100 | // Grabbing the very end and the very beginning of the real FFT output?
101 | unsigned int index = (fftFrameSize - centre + i) % fftFrameSize;
102 | double coeff = ifft->getOutput(index);
103 | coeff *= win.window(WINDOW_HAMMING, i, impulseLength);
104 | coefficients[i] = coeff;
105 | gain += coeff;
106 | }
107 |
108 | delete ifft;
109 | }
110 |
111 | void LowPassFilterPrivate::filter(AudioData& audio, Workspace& workspace, unsigned int shortcutFactor) const {
112 |
113 | if (audio.getChannels() > 1) {
114 | throw Exception("Monophonic audio only");
115 | }
116 |
117 | std::vector* buffer = workspace.lpfBuffer;
118 |
119 | if (buffer == NULL) {
120 | workspace.lpfBuffer = new std::vector(impulseLength, 0.0);
121 | buffer = workspace.lpfBuffer;
122 | } else {
123 | // clear delay buffer
124 | std::vector::iterator bufferIterator = buffer->begin();
125 | while (bufferIterator < buffer->end()) {
126 | *bufferIterator = 0.0;
127 | std::advance(bufferIterator, 1);
128 | }
129 | }
130 |
131 | std::vector::iterator bufferFront = buffer->begin();
132 | std::vector::iterator bufferBack;
133 | std::vector::iterator bufferTemp;
134 |
135 | unsigned int sampleCount = audio.getSampleCount();
136 | audio.resetIterators();
137 |
138 | double sum;
139 | // for each frame (running off the end of the sample stream by delay)
140 | for (unsigned int inSample = 0; inSample < sampleCount + delay; inSample++) {
141 | // shuffle old samples along delay buffer
142 | bufferBack = bufferFront;
143 | std::advance(bufferFront, 1);
144 | if (bufferFront == buffer->end()) {
145 | bufferFront = buffer->begin();
146 | }
147 |
148 | // load new sample into back of delay buffer
149 | if (audio.readIteratorWithinUpperBound()) {
150 | *bufferBack = audio.getSampleAtReadIterator() / gain;
151 | audio.advanceReadIterator();
152 | } else {
153 | *bufferBack = 0.0; // zero pad once we're past the end of the file
154 | }
155 | // start doing the maths once the delay has passed
156 | int outSample = (signed)inSample - (signed)delay;
157 | if (outSample < 0) {
158 | continue;
159 | }
160 | // and, if shortcut != 1, only do the maths for the useful samples (this is mathematically dodgy, but it's faster and it usually works)
161 | if (outSample % shortcutFactor > 0) {
162 | continue;
163 | }
164 | sum = 0.0;
165 | bufferTemp = bufferFront;
166 | std::vector::const_iterator coefficientIterator = coefficients.begin();
167 | while (coefficientIterator < coefficients.end()) {
168 | sum += *coefficientIterator * *bufferTemp;
169 | std::advance(coefficientIterator, 1);
170 | std::advance(bufferTemp, 1);
171 | if (bufferTemp == buffer->end()) {
172 | bufferTemp = buffer->begin();
173 | }
174 | }
175 | audio.setSampleAtWriteIterator(sum);
176 | audio.advanceWriteIterator(shortcutFactor);
177 | }
178 | }
179 |
180 | }
181 |
--------------------------------------------------------------------------------
/tests/lowpassfiltertest.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "_testhelpers.h"
23 |
24 | unsigned int frameRate = 44100;
25 | float magnitude = 32768.0;
26 | // TODO: 5% tolerance is not ideal, and only works when
27 | // target frequencies are far from corner.
28 | // Do some manual tests and compare to libSRC.
29 | float tolerance = 0.05 * magnitude;
30 |
31 | float highFrequency = 21000.0;
32 | float lowFrequency = 800.0;
33 | float cornerFrequency = 6500.0;
34 |
35 | unsigned int filterOrder = 160;
36 | unsigned int filterFFT = 2048;
37 |
38 | TEST (LowPassFilterTest, InsistsOnEvenOrder) {
39 | KeyFinder::LowPassFilter* lpf = NULL;
40 | ASSERT_THROW(lpf = new KeyFinder::LowPassFilter(filterOrder + 1, frameRate, cornerFrequency, filterFFT), KeyFinder::Exception);
41 | ASSERT_EQ(NULL, lpf);
42 | }
43 |
44 | TEST (LowPassFilterTest, InsistsOnOrderNotGreaterThanOneQuarterFftFrameSize) {
45 | KeyFinder::LowPassFilter* lpf = NULL;
46 | ASSERT_THROW(lpf = new KeyFinder::LowPassFilter(514, frameRate, cornerFrequency, 2048), KeyFinder::Exception);
47 | ASSERT_EQ(NULL, lpf);
48 | ASSERT_NO_THROW(lpf = new KeyFinder::LowPassFilter(512, frameRate, cornerFrequency, 2048));
49 | ASSERT_NO_THROW(delete lpf);
50 | }
51 |
52 | TEST (LowPassFilterTest, InsistsOnMonophonicAudio) {
53 | KeyFinder::AudioData a;
54 | a.setChannels(2);
55 | a.setFrameRate(frameRate);
56 | a.addToSampleCount(frameRate);
57 |
58 | KeyFinder::LowPassFilter* lpf = new KeyFinder::LowPassFilter(filterOrder, frameRate, cornerFrequency, filterFFT);
59 | KeyFinder::Workspace w;
60 | ASSERT_THROW(lpf->filter(a, w), KeyFinder::Exception);
61 | a.reduceToMono();
62 | ASSERT_NO_THROW(lpf->filter(a, w));
63 | delete lpf;
64 | }
65 |
66 | TEST (LowPassFilterTest, InitialisesNullBuffer) {
67 | KeyFinder::AudioData a;
68 | a.setChannels(1);
69 | a.setFrameRate(frameRate);
70 | a.addToSampleCount(frameRate);
71 |
72 | KeyFinder::LowPassFilter* lpf = new KeyFinder::LowPassFilter(filterOrder, frameRate, cornerFrequency, filterFFT);
73 | KeyFinder::Workspace w;
74 | std::vector* nullPtr = NULL;
75 | ASSERT_EQ(nullPtr, w.lpfBuffer);
76 | lpf->filter(a, w);
77 | ASSERT_NE(nullPtr, w.lpfBuffer);
78 | }
79 |
80 | TEST (LowPassFilterTest, DoesntAlterAudioMetadata) {
81 | KeyFinder::AudioData a;
82 | a.setChannels(1);
83 | a.setFrameRate(frameRate);
84 | a.addToSampleCount(frameRate);
85 |
86 | KeyFinder::LowPassFilter* lpf = new KeyFinder::LowPassFilter(filterOrder, frameRate, cornerFrequency, filterFFT);
87 | KeyFinder::Workspace w;
88 | lpf->filter(a, w);
89 | delete lpf;
90 |
91 | ASSERT_EQ(1, a.getChannels());
92 | ASSERT_EQ(frameRate, a.getFrameRate());
93 | ASSERT_EQ(frameRate, a.getSampleCount());
94 | }
95 |
96 | TEST (LowPassFilterTest, KillsHigherFreqs) {
97 | // make a high frequency sine wave, one second long
98 | KeyFinder::AudioData a;
99 | a.setChannels(1);
100 | a.setFrameRate(frameRate);
101 | a.addToSampleCount(frameRate);
102 | for (unsigned int i = 0; i < frameRate; i++) {
103 | a.setSample(i, sine_wave(i, highFrequency, frameRate, magnitude));
104 | }
105 |
106 | KeyFinder::LowPassFilter* lpf = new KeyFinder::LowPassFilter(filterOrder, frameRate, cornerFrequency, filterFFT);
107 | KeyFinder::Workspace w;
108 | lpf->filter(a, w);
109 | delete lpf;
110 |
111 | // test for near silence
112 | for (unsigned int i = 0; i < frameRate; i++) {
113 | ASSERT_NEAR(0.0, a.getSample(i), tolerance);
114 | }
115 | }
116 |
117 | TEST (LowPassFilterTest, MaintainsLowerFreqs) {
118 | // make a low frequency sine wave, one second long
119 | KeyFinder::AudioData a;
120 | a.setChannels(1);
121 | a.setFrameRate(frameRate);
122 | a.addToSampleCount(frameRate);
123 | for (unsigned int i = 0; i < frameRate; i++) {
124 | a.setSample(i, sine_wave(i, lowFrequency, frameRate, magnitude));
125 | }
126 |
127 | KeyFinder::LowPassFilter* lpf = new KeyFinder::LowPassFilter(filterOrder, frameRate, cornerFrequency, filterFFT);
128 | KeyFinder::Workspace w;
129 | lpf->filter(a, w);
130 | delete lpf;
131 |
132 | // test for near perfect reproduction
133 | for (unsigned int i = 0; i < frameRate; i++) {
134 | float expected = sine_wave(i, lowFrequency, frameRate, magnitude);
135 | ASSERT_NEAR(expected, a.getSample(i), tolerance);
136 | }
137 | }
138 |
139 | TEST (LowPassFilterTest, DoesBothAtOnce) {
140 | // make two sine waves, one second long
141 | KeyFinder::AudioData a;
142 | a.setChannels(1);
143 | a.setFrameRate(frameRate);
144 | a.addToSampleCount(frameRate);
145 | for (unsigned int i = 0; i < frameRate; i++) {
146 | float sample = 0.0;
147 | sample += sine_wave(i, highFrequency, frameRate, magnitude); // high freq
148 | sample += sine_wave(i, lowFrequency, frameRate, magnitude); // low freq
149 | a.setSample(i, sample);
150 | }
151 |
152 | KeyFinder::LowPassFilter* lpf = new KeyFinder::LowPassFilter(filterOrder, frameRate, cornerFrequency, filterFFT);
153 | KeyFinder::Workspace w;
154 | lpf->filter(a, w);
155 | delete lpf;
156 |
157 | // test for lower wave only
158 | for (unsigned int i = 0; i < frameRate; i++) {
159 | float expected = sine_wave(i, lowFrequency, frameRate, magnitude);
160 | ASSERT_NEAR(expected, a.getSample(i), tolerance);
161 | }
162 | }
163 |
164 | TEST (LowPassFilterTest, WorksOnRepetitiveWaves) {
165 | // make two sine waves, but this time, several seconds long
166 | unsigned int samples = frameRate * 5;
167 | KeyFinder::AudioData a;
168 | a.setChannels(1);
169 | a.setFrameRate(frameRate);
170 | a.addToSampleCount(samples);
171 | for (unsigned int i = 0; i < samples; i++) {
172 | float sample = 0.0;
173 | sample += sine_wave(i, highFrequency, frameRate, magnitude); // high freq
174 | sample += sine_wave(i, lowFrequency, frameRate, magnitude); // low freq
175 | a.setSample(i, sample);
176 | // ensure repetition of sine waves is perfect...
177 | if (i >= frameRate) {
178 | ASSERT_NEAR(a.getSample(i), a.getSample(i - frameRate), tolerance);
179 | }
180 | }
181 |
182 | KeyFinder::LowPassFilter* lpf = new KeyFinder::LowPassFilter(filterOrder, frameRate, cornerFrequency, filterFFT);
183 | KeyFinder::Workspace w;
184 | lpf->filter(a, w);
185 | delete lpf;
186 |
187 | // test for lower wave only
188 | for (unsigned int i = 0; i < samples; i++) {
189 | float expected = sine_wave(i, lowFrequency, frameRate, magnitude);
190 | ASSERT_NEAR(expected, a.getSample(i), tolerance);
191 | }
192 | }
193 |
194 | TEST (LowPassFilterTest, DefaultFilterMatchesFisherCoefficients) {
195 | KeyFinder::LowPassFilter* lpf = new KeyFinder::LowPassFilter(160, 44100, 2000.0, 2048);
196 | std::vector* myCoeffs = (std::vector*)lpf->getCoefficients();
197 |
198 | float fisherCoeffsFirstHalf[] = {
199 | -0.0022979864, -0.0014851155, -0.0005276345, +0.0005287637,
200 | +0.0016288105, +0.0027066298, +0.0036859262, +0.0044820600,
201 | +0.0050064517, +0.0051734225, +0.0049091760, +0.0041622026,
202 | +0.0029140060, +0.0011887658, -0.0009395862, -0.0033443515,
203 | -0.0058483343, -0.0082321768, -0.0102489292, -0.0116443067,
204 | -0.0121813339, -0.0116673677, -0.0099809222, -0.0070953669,
205 | -0.0030964983, +0.0018087642, +0.0072947272, +0.0129315999,
206 | +0.0182126619, +0.0225928091, +0.0255360681, +0.0265684688,
207 | +0.0253317039, +0.0216323992, +0.0154816648, +0.0071199603,
208 | -0.0029768131, -0.0141127078, -0.0254095608, -0.0358661777,
209 | -0.0444356705, -0.0501157252, -0.0520448654, -0.0495965416,
210 | -0.0424622921, -0.0307153754, -0.0148472270, +0.0042291942,
211 | +0.0252127139, +0.0464845605, +0.0662137647, +0.0824916099,
212 | +0.0934864451, +0.0976077458, +0.0936666466, +0.0810194757,
213 | +0.0596811993, +0.0303971839, -0.0053357703, -0.0453047237,
214 | -0.0866737087, -0.1261316811, -0.1600878564, -0.1849028543,
215 | -0.1971406561, -0.1938239736, -0.1726744703, -0.1323195052,
216 | -0.0724487288, +0.0060931437, +0.1012868940, +0.2099971950,
217 | +0.3281078087, +0.4507269541, +0.5724509503, +0.6876697384,
218 | +0.7908945043, +0.8770856432, +0.9419588972, +0.9822487143,
219 | +0.9959106445
220 | };
221 |
222 | for (unsigned int i = 0; i < 81; i++) {
223 | ASSERT_FLOAT_EQ(fisherCoeffsFirstHalf[i], myCoeffs->at(i));
224 | ASSERT_FLOAT_EQ(myCoeffs->at(i), myCoeffs->at(160 - i));
225 | }
226 | delete lpf;
227 | }
228 |
--------------------------------------------------------------------------------
/src/audiodata.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "audiodata.h"
23 |
24 | namespace KeyFinder {
25 |
26 | AudioData::AudioData(): samples(0), channels(0), frameRate(0) { }
27 |
28 | unsigned int AudioData::getChannels() const {
29 | return channels;
30 | }
31 |
32 | void AudioData::setChannels(unsigned int inChannels) {
33 | if (inChannels < 1) {
34 | throw Exception("New channel count must be > 0");
35 | }
36 | channels = inChannels;
37 | }
38 |
39 | unsigned int AudioData::getFrameRate() const {
40 | return frameRate;
41 | }
42 |
43 | void AudioData::setFrameRate(unsigned int inFrameRate) {
44 | if (inFrameRate < 1) {
45 | throw Exception("New frame rate must be > 0");
46 | }
47 | frameRate = inFrameRate;
48 | }
49 |
50 | void AudioData::append(const AudioData& that) {
51 | if (channels == 0 && frameRate == 0) {
52 | channels = that.channels;
53 | frameRate = that.frameRate;
54 | }
55 | if (that.channels != channels) {
56 | throw Exception("Cannot append audio data with a different number of channels");
57 | }
58 | if (that.frameRate != frameRate) {
59 | throw Exception("Cannot append audio data with a different frame rate");
60 | }
61 | samples.insert(samples.end(), that.samples.begin(), that.samples.end());
62 | }
63 |
64 | void AudioData::prepend(const AudioData& that) {
65 | if (channels == 0 && frameRate == 0) {
66 | channels = that.channels;
67 | frameRate = that.frameRate;
68 | }
69 | if (that.channels != channels) {
70 | throw Exception("Cannot prepend audio data with a different number of channels");
71 | }
72 | if (that.frameRate != frameRate) {
73 | throw Exception("Cannot prepend audio data with a different frame rate");
74 | }
75 | samples.insert(samples.begin(), that.samples.begin(), that.samples.end());
76 | }
77 |
78 | // get sample by absolute index
79 | double AudioData::getSample(unsigned int index) const {
80 | if (index >= getSampleCount()) {
81 | std::ostringstream ss;
82 | ss << "Cannot get out-of-bounds sample (" << index << "/" << getSampleCount() << ")";
83 | throw Exception(ss.str().c_str());
84 | }
85 | return samples[index];
86 | }
87 |
88 | // get sample by frame and channel
89 | double AudioData::getSampleByFrame(unsigned int frame, unsigned int channel) const {
90 | if (frame >= getFrameCount()) {
91 | std::ostringstream ss;
92 | ss << "Cannot get out-of-bounds frame (" << frame << "/" << getFrameCount() << ")";
93 | throw Exception(ss.str().c_str());
94 | }
95 | if (channel >= channels) {
96 | std::ostringstream ss;
97 | ss << "Cannot get out-of-bounds channel (" << channel << "/" << channels << ")";
98 | throw Exception(ss.str().c_str());
99 | }
100 | return getSample(frame * channels + channel);
101 | }
102 |
103 | // set sample by absolute index
104 | void AudioData::setSample(unsigned int index, double value) {
105 | if (index >= getSampleCount()) {
106 | std::ostringstream ss;
107 | ss << "Cannot set out-of-bounds sample (" << index << "/" << getSampleCount() << ")";
108 | throw Exception(ss.str().c_str());
109 | }
110 | if (!std::isfinite(value)) {
111 | throw Exception("Cannot set sample to NaN");
112 | }
113 | samples[index] = value;
114 | }
115 |
116 | // set sample by frame and channel
117 | void AudioData::setSampleByFrame(unsigned int frame, unsigned int channel, double value) {
118 | if (frame >= getFrameCount()) {
119 | std::ostringstream ss;
120 | ss << "Cannot set out-of-bounds frame (" << frame << "/" << getFrameCount() << ")";
121 | throw Exception(ss.str().c_str());
122 | }
123 | if (channel >= channels) {
124 | std::ostringstream ss;
125 | ss << "Cannot set out-of-bounds channel (" << channel << "/" << channels << ")";
126 | throw Exception(ss.str().c_str());
127 | }
128 | setSample(frame * channels + channel, value);
129 | }
130 |
131 | void AudioData::addToSampleCount(unsigned int inSamples) {
132 | samples.resize(getSampleCount() + inSamples, 0.0);
133 | }
134 |
135 | void AudioData::addToFrameCount(unsigned int inFrames) {
136 | if (channels < 1) {
137 | throw Exception("Channels must be > 0");
138 | }
139 | addToSampleCount(inFrames * channels);
140 | }
141 |
142 | unsigned int AudioData::getSampleCount() const {
143 | return samples.size();
144 | }
145 |
146 | unsigned int AudioData::getFrameCount() const {
147 | if (channels < 1) {
148 | throw Exception("Channels must be > 0");
149 | }
150 | return getSampleCount() / channels;
151 | }
152 |
153 | void AudioData::reduceToMono() {
154 | if (channels < 2) {
155 | return;
156 | }
157 | std::deque::const_iterator readAt = samples.begin();
158 | std::deque::iterator writeAt = samples.begin();
159 | while (readAt < samples.end()) {
160 | double sum = 0.0;
161 | for (unsigned int c = 0; c < channels; c++) {
162 | sum += *readAt;
163 | std::advance(readAt, 1);
164 | }
165 | *writeAt = sum / channels;
166 | std::advance(writeAt, 1);
167 | }
168 | samples.resize(getSampleCount() / channels);
169 | channels = 1;
170 | }
171 |
172 | // Strictly to be applied AFTER low pass filtering
173 | void AudioData::downsample(unsigned int factor, bool shortcut) {
174 | if (factor == 1) {
175 | return;
176 | }
177 | if (channels > 1) {
178 | throw Exception("Apply to monophonic only");
179 | }
180 | std::deque::const_iterator readAt = samples.begin();
181 | std::deque::iterator writeAt = samples.begin();
182 |
183 | // Prevent std::advance out of iterator range problems
184 | size_t numSamplesRemaining = samples.size();
185 |
186 | while (readAt < samples.end()) {
187 | double mean = 0.0;
188 | if (shortcut) {
189 | mean = *readAt;
190 | if (numSamplesRemaining >= factor) {
191 | std::advance(readAt, factor);
192 | } else {
193 | readAt = samples.end();
194 | }
195 | numSamplesRemaining -= factor;
196 | } else {
197 | for (unsigned int s = 0; s < factor; s++) {
198 | if (readAt < samples.end()) {
199 | mean += *readAt;
200 | std::advance(readAt, 1);
201 | --numSamplesRemaining;
202 | }
203 | mean /= (double)factor;
204 | }
205 | }
206 | *writeAt = mean;
207 | std::advance(writeAt, 1);
208 | }
209 | samples.resize(ceil((double)getSampleCount() / (double)factor));
210 | setFrameRate(getFrameRate() / factor);
211 | }
212 |
213 | void AudioData::discardFramesFromFront(unsigned int discardFrameCount) {
214 | if (discardFrameCount > getFrameCount()) {
215 | std::ostringstream ss;
216 | ss << "Cannot discard " << discardFrameCount << " frames of " << getFrameCount();
217 | throw Exception(ss.str().c_str());
218 | }
219 | unsigned int discardSampleCount = discardFrameCount * channels;
220 | std::deque::iterator discardToHere = samples.begin();
221 | std::advance(discardToHere, discardSampleCount);
222 | samples.erase(samples.begin(), discardToHere);
223 | }
224 |
225 | AudioData* AudioData::sliceSamplesFromBack(unsigned int sliceSampleCount) {
226 |
227 | if (sliceSampleCount > getSampleCount()) {
228 | std::ostringstream ss;
229 | ss << "Cannot slice " << sliceSampleCount << " samples of " << getSampleCount();
230 | throw Exception(ss.str().c_str());
231 | }
232 |
233 | unsigned int samplesToLeaveIntact = getSampleCount() - sliceSampleCount;
234 |
235 | AudioData* that = new AudioData();
236 | that->channels = channels;
237 | that->setFrameRate(getFrameRate());
238 | that->addToSampleCount(sliceSampleCount);
239 |
240 | std::deque::const_iterator readAt = samples.begin();
241 | std::advance(readAt, samplesToLeaveIntact);
242 | std::deque::iterator writeAt = that->samples.begin();
243 | while (readAt < samples.end()) {
244 | *writeAt = *readAt;
245 | std::advance(readAt, 1);
246 | std::advance(writeAt, 1);
247 | }
248 |
249 | samples.resize(samplesToLeaveIntact);
250 |
251 | return that;
252 | }
253 |
254 | void AudioData::resetIterators() {
255 | readIterator = samples.begin();
256 | writeIterator = samples.begin();
257 | }
258 |
259 | bool AudioData::readIteratorWithinUpperBound() const {
260 | return (readIterator < samples.end());
261 | }
262 |
263 | bool AudioData::writeIteratorWithinUpperBound() const {
264 | return (writeIterator < samples.end());
265 | }
266 |
267 | void AudioData::advanceReadIterator(unsigned int by) {
268 | std::advance(readIterator, by);
269 | }
270 |
271 | void AudioData::advanceWriteIterator(unsigned int by) {
272 | std::advance(writeIterator, by);
273 | }
274 |
275 | double AudioData::getSampleAtReadIterator() const {
276 | return *readIterator;
277 | }
278 |
279 | void AudioData::setSampleAtWriteIterator(double value) {
280 | *writeIterator = value;
281 | }
282 |
283 | }
284 |
--------------------------------------------------------------------------------
/tests/audiodatatest.cpp:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 |
3 | Copyright 2011-2015 Ibrahim Sha'ath
4 |
5 | This file is part of LibKeyFinder.
6 |
7 | LibKeyFinder 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 | LibKeyFinder 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 LibKeyFinder. If not, see .
19 |
20 | *************************************************************************/
21 |
22 | #include "_testhelpers.h"
23 |
24 | TEST_CASE ("AudioDataTest/ConstructorWorks") {
25 | KeyFinder::AudioData a;
26 | ASSERT_EQ(0, a.getChannels());
27 | ASSERT_EQ(0, a.getFrameRate());
28 | ASSERT_EQ(0, a.getSampleCount());
29 | }
30 |
31 | TEST_CASE ("AudioDataTest/Channels") {
32 | KeyFinder::AudioData a;
33 | a.setChannels(2);
34 | ASSERT_EQ(2, a.getChannels());
35 | ASSERT_THROW(a.setChannels(0), KeyFinder::Exception);
36 | }
37 |
38 | TEST_CASE ("AudioDataTest/FrameRate") {
39 | KeyFinder::AudioData a;
40 | a.setFrameRate(44100);
41 | ASSERT_EQ(44100, a.getFrameRate());
42 | ASSERT_THROW(a.setFrameRate(0), KeyFinder::Exception);
43 | }
44 |
45 | TEST_CASE ("AudioDataTest/SampleInitialisation") {
46 | KeyFinder::AudioData a;
47 | a.addToSampleCount(100);
48 | ASSERT_EQ(100, a.getSampleCount());
49 | // init values
50 | for (int i = 0; i < 100; i++) {
51 | ASSERT(0.0 == a.getSample(i));
52 | }
53 | }
54 |
55 | TEST_CASE ("AudioDataTest/SampleMutator") {
56 | KeyFinder::AudioData a;
57 | a.addToSampleCount(1);
58 | a.setSample(0, 10.0);
59 | ASSERT_FLOAT_EQ(10.0, a.getSample(0));
60 | }
61 |
62 | TEST_CASE ("AudioDataTest/SampleMutatorBounds") {
63 | KeyFinder::AudioData a;
64 | a.addToSampleCount(5);
65 | ASSERT_THROW(a.getSample(-1), KeyFinder::Exception);
66 | ASSERT_THROW(a.getSample(5), KeyFinder::Exception);
67 |
68 | ASSERT_THROW(a.setSample(-1, 1.0), KeyFinder::Exception);
69 | ASSERT_THROW(a.setSample(5, 1.0), KeyFinder::Exception);
70 |
71 | ASSERT_THROW(a.setSample(0, INFINITY), KeyFinder::Exception);
72 | ASSERT_THROW(a.setSample(0, NAN), KeyFinder::Exception);
73 | }
74 |
75 | TEST_CASE ("AudioDataTest/FrameAccessBeforeChannelsInitialised") {
76 | KeyFinder::AudioData a;
77 | a.addToSampleCount(4);
78 | ASSERT_THROW(a.getSampleByFrame(0, 0), KeyFinder::Exception);
79 | }
80 |
81 | TEST_CASE ("AudioDataTest/FrameMutator") {
82 | KeyFinder::AudioData a;
83 | a.setChannels(4);
84 | a.addToFrameCount(5);
85 | ASSERT_EQ(5, a.getFrameCount());
86 | ASSERT_EQ(20, a.getSampleCount());
87 |
88 | a.setSample(6, 10.0);
89 | ASSERT_FLOAT_EQ(10.0, a.getSample(6));
90 | ASSERT_FLOAT_EQ(10.0, a.getSampleByFrame(1, 2));
91 | a.setSampleByFrame(1, 2, 20.0);
92 | ASSERT_FLOAT_EQ(20.0, a.getSample(6));
93 | ASSERT_FLOAT_EQ(20.0, a.getSampleByFrame(1, 2));
94 | }
95 |
96 | TEST_CASE ("AudioDataTest/FrameMutatorBounds") {
97 | KeyFinder::AudioData a;
98 | a.setChannels(2);
99 | a.addToFrameCount(10);
100 | ASSERT_THROW(a.getSampleByFrame(-1, 0), KeyFinder::Exception);
101 | ASSERT_THROW(a.getSampleByFrame(10, 0), KeyFinder::Exception);
102 | ASSERT_THROW(a.getSampleByFrame( 0,-1), KeyFinder::Exception);
103 | ASSERT_THROW(a.getSampleByFrame( 0, 2), KeyFinder::Exception);
104 | }
105 |
106 | TEST_CASE ("AudioDataTest/AppendToNew") {
107 | KeyFinder::AudioData a;
108 | KeyFinder::AudioData b;
109 |
110 | ASSERT_NO_THROW(a.append(b));
111 | ASSERT_EQ(0, a.getChannels());
112 | ASSERT_EQ(0, a.getFrameRate());
113 |
114 | b.setChannels(1);
115 | b.setFrameRate(1);
116 | b.addToFrameCount(1);
117 |
118 | ASSERT_NO_THROW(a.append(b));
119 | ASSERT_EQ(1, a.getChannels());
120 | ASSERT_EQ(1, a.getFrameRate());
121 | ASSERT_EQ(1, a.getFrameCount());
122 | }
123 |
124 | TEST_CASE ("AudioDataTest/PrependToNew") {
125 | KeyFinder::AudioData a;
126 | KeyFinder::AudioData b;
127 |
128 | ASSERT_NO_THROW(a.prepend(b));
129 | ASSERT_EQ(0, a.getChannels());
130 | ASSERT_EQ(0, a.getFrameRate());
131 |
132 | b.setChannels(1);
133 | b.setFrameRate(1);
134 | b.addToFrameCount(1);
135 |
136 | ASSERT_NO_THROW(a.prepend(b));
137 | ASSERT_EQ(1, a.getChannels());
138 | ASSERT_EQ(1, a.getFrameRate());
139 | ASSERT_EQ(1, a.getFrameCount());
140 | }
141 |
142 | TEST_CASE ("AudioDataTest/AppendToInitialised") {
143 | KeyFinder::AudioData a;
144 | KeyFinder::AudioData b;
145 |
146 | a.setChannels(1);
147 | a.setFrameRate(1);
148 | ASSERT_THROW(a.append(b), KeyFinder::Exception);
149 |
150 | b.setChannels(2);
151 | b.setFrameRate(1);
152 | ASSERT_THROW(a.append(b), KeyFinder::Exception);
153 |
154 | b.setChannels(1);
155 | b.setFrameRate(2);
156 | ASSERT_THROW(a.append(b), KeyFinder::Exception);
157 |
158 | b.setChannels(1);
159 | b.setFrameRate(1);
160 | ASSERT_NO_THROW(a.append(b));
161 |
162 | a.addToFrameCount(1);
163 | b.addToFrameCount(1);
164 | a.setSampleByFrame(0, 0, 10.0);
165 | b.setSampleByFrame(0, 0, 20.0);
166 |
167 | a.append(b);
168 | ASSERT_EQ(2, a.getFrameCount());
169 | ASSERT_FLOAT_EQ(10.0, a.getSampleByFrame(0, 0));
170 | ASSERT_FLOAT_EQ(20.0, a.getSampleByFrame(1, 0));
171 | }
172 |
173 | TEST_CASE ("AudioDataTest/PrependToInitialised") {
174 | KeyFinder::AudioData a;
175 | KeyFinder::AudioData b;
176 |
177 | a.setChannels(1);
178 | a.setFrameRate(1);
179 | ASSERT_THROW(a.prepend(b), KeyFinder::Exception);
180 |
181 | b.setChannels(2);
182 | b.setFrameRate(1);
183 | ASSERT_THROW(a.prepend(b), KeyFinder::Exception);
184 |
185 | b.setChannels(1);
186 | b.setFrameRate(2);
187 | ASSERT_THROW(a.prepend(b), KeyFinder::Exception);
188 |
189 | b.setChannels(1);
190 | b.setFrameRate(1);
191 | ASSERT_NO_THROW(a.prepend(b));
192 |
193 | a.addToFrameCount(1);
194 | b.addToFrameCount(1);
195 | a.setSampleByFrame(0, 0, 10.0);
196 | b.setSampleByFrame(0, 0, 20.0);
197 |
198 | a.prepend(b);
199 | ASSERT_EQ(2, a.getFrameCount());
200 | ASSERT_FLOAT_EQ(20.0, a.getSampleByFrame(0, 0));
201 | ASSERT_FLOAT_EQ(10.0, a.getSampleByFrame(1, 0));
202 | }
203 |
204 | TEST_CASE ("AudioDataTest/DiscardFromFront") {
205 | KeyFinder::AudioData a;
206 |
207 | a.setChannels(1);
208 | a.setFrameRate(1);
209 |
210 | ASSERT_THROW(a.discardFramesFromFront(1), KeyFinder::Exception);
211 | a.addToFrameCount(10);
212 | ASSERT_THROW(a.discardFramesFromFront(11), KeyFinder::Exception);
213 | ASSERT_NO_THROW(a.discardFramesFromFront(0));
214 | a.setSampleByFrame(5, 0, 10.0);
215 | ASSERT_NO_THROW(a.discardFramesFromFront(5));
216 | ASSERT_EQ(5, a.getFrameCount());
217 | ASSERT_FLOAT_EQ(10.0, a.getSampleByFrame(0, 0));
218 | }
219 |
220 | TEST_CASE ("AudioDataTest/SliceFromBack") {
221 | KeyFinder::AudioData a;
222 | a.setChannels(1);
223 | a.setFrameRate(1);
224 |
225 | KeyFinder::AudioData* b = NULL;
226 | KeyFinder::AudioData* nullPtr = NULL;
227 |
228 | ASSERT_THROW(b = a.sliceSamplesFromBack(1), KeyFinder::Exception);
229 | ASSERT_EQ(nullPtr, b);
230 |
231 | a.addToFrameCount(10);
232 | ASSERT_THROW(b = a.sliceSamplesFromBack(11), KeyFinder::Exception);
233 | ASSERT_EQ(nullPtr, b);
234 |
235 | a.resetIterators();
236 | float v = 0;
237 | while (a.writeIteratorWithinUpperBound()) {
238 | a.setSampleAtWriteIterator(v);
239 | a.advanceWriteIterator();
240 | v += 1.0;
241 | }
242 |
243 | ASSERT_NO_THROW(b = a.sliceSamplesFromBack(5));
244 | ASSERT_NE(nullPtr, b);
245 | ASSERT_EQ(5, a.getSampleCount());
246 | ASSERT_EQ(5, b->getSampleCount());
247 | ASSERT_FLOAT_EQ(5.0, b->getSample(0));
248 | ASSERT_FLOAT_EQ(9.0, b->getSample(4));
249 | delete b;
250 | }
251 |
252 | TEST_CASE ("AudioDataTest/MakeMono") {
253 | KeyFinder::AudioData a;
254 | a.setChannels(2);
255 | a.addToSampleCount(20);
256 | for (int i = 0; i < 10; i++) {
257 | a.setSample(i * 2, 100.0);
258 | }
259 | a.reduceToMono();
260 | ASSERT_EQ(10, a.getSampleCount());
261 | for (int i = 0; i < 10; i++) {
262 | ASSERT_FLOAT_EQ(50.0, a.getSample(i));
263 | }
264 | }
265 |
266 | TEST_CASE ("AudioDataTest/DownsamplerInsistsOnMonophonicAudio") {
267 | KeyFinder::AudioData a;
268 | a.setChannels(2);
269 | a.setFrameRate(100);
270 | a.addToSampleCount(10);
271 |
272 | ASSERT_THROW(a.downsample(5), KeyFinder::Exception);
273 | a.reduceToMono();
274 | ASSERT_NO_THROW(a.downsample(5));
275 | }
276 |
277 | TEST_CASE ("AudioDataTest/DownsamplerResamplesIntegralRelationship") {
278 | KeyFinder::AudioData a;
279 | a.setChannels(1);
280 | a.setFrameRate(100);
281 | a.addToSampleCount(10);
282 | for (unsigned int i = 0; i < 5; i++)
283 | a.setSample(i, 100.0);
284 | for (unsigned int i = 5; i < 10; i++)
285 | a.setSample(i, 500.0);
286 |
287 | a.downsample(5);
288 |
289 | ASSERT_EQ(20, a.getFrameRate());
290 | ASSERT_EQ(2, a.getSampleCount());
291 | ASSERT_FLOAT_EQ(100.0, a.getSample(0));
292 | ASSERT_FLOAT_EQ(500.0, a.getSample(1));
293 | }
294 |
295 | TEST_CASE ("AudioDataTest/DownsamplerResamplesNonintegralRelationship") {
296 | KeyFinder::AudioData a;
297 | a.setChannels(1);
298 | a.setFrameRate(100);
299 | a.addToSampleCount(12);
300 | for (unsigned int i = 0; i < 5; i++)
301 | a.setSample(i, 100.0);
302 | for (unsigned int i = 5; i < 10; i++)
303 | a.setSample(i, 500.0);
304 | for (unsigned int i = 10; i < 12; i++)
305 | a.setSample(i, 1000.0);
306 |
307 | a.downsample(5);
308 |
309 | ASSERT_EQ(3, a.getSampleCount());
310 | ASSERT_FLOAT_EQ(100.0, a.getSample(0));
311 | ASSERT_FLOAT_EQ(500.0, a.getSample(1));
312 | // this doesn't make total mathematical sense but I'm taking a shortcut for performance
313 | ASSERT_FLOAT_EQ(1000.0, a.getSample(2));
314 | }
315 |
316 | TEST_CASE ("AudioDataTest/DownsamplerResamplesSineWave") {
317 | unsigned int frameRate = 10000;
318 | unsigned int frames = frameRate * 4;
319 | float freq = 20;
320 | float magnitude = 32768.0;
321 | unsigned int factor = 5;
322 |
323 | KeyFinder::AudioData a;
324 | a.setChannels(1);
325 | a.setFrameRate(frameRate);
326 | a.addToSampleCount(frames);
327 | for (unsigned int i = 0; i < frames; i++)
328 | a.setSample(i, sine_wave(i, freq, frameRate, magnitude));
329 |
330 | a.downsample(factor);
331 |
332 | unsigned int newFrameRate = frameRate / factor;
333 | unsigned int newFrames = frames / factor;
334 |
335 | ASSERT_EQ(newFrameRate, a.getFrameRate());
336 | ASSERT_EQ(newFrames, a.getSampleCount());
337 | for (unsigned int i = 0; i < newFrames; i++) {
338 | ASSERT_NEAR(sine_wave(i, freq, newFrameRate, magnitude), a.getSample(i), magnitude * 0.05);
339 | }
340 | }
341 |
342 | TEST_CASE ("AudioDataTest/Iterators") {
343 | KeyFinder::AudioData a;
344 | a.setChannels(1);
345 | a.setFrameRate(1);
346 | a.addToSampleCount(10);
347 |
348 | a.setSample(0, 10.0);
349 | a.setSample(1, 20.0);
350 | a.setSample(3, 50.0);
351 |
352 | a.resetIterators(); // this is required before each use
353 |
354 | ASSERT_FLOAT_EQ(10.0, a.getSampleAtReadIterator());
355 | a.setSampleAtWriteIterator(15.0);
356 | ASSERT_FLOAT_EQ(15.0, a.getSampleAtReadIterator());
357 |
358 | a.advanceReadIterator();
359 | a.advanceWriteIterator();
360 | ASSERT_FLOAT_EQ(20.0, a.getSampleAtReadIterator());
361 | a.setSampleAtWriteIterator(25.0);
362 | ASSERT_FLOAT_EQ(25.0, a.getSampleAtReadIterator());
363 |
364 | a.advanceReadIterator(2);
365 | a.advanceWriteIterator(2);
366 | ASSERT_FLOAT_EQ(50.0, a.getSampleAtReadIterator());
367 | a.setSampleAtWriteIterator(55.0);
368 | ASSERT_FLOAT_EQ(55.0, a.getSampleAtReadIterator());
369 |
370 | a.resetIterators();
371 | ASSERT_FLOAT_EQ(15.0, a.getSampleAtReadIterator());
372 | a.setSampleAtWriteIterator(150.0);
373 | ASSERT_FLOAT_EQ(150.0, a.getSampleAtReadIterator());
374 |
375 | ASSERT_TRUE(a.readIteratorWithinUpperBound());
376 | ASSERT_TRUE(a.writeIteratorWithinUpperBound());
377 | a.advanceReadIterator(10);
378 | a.advanceWriteIterator(10);
379 | ASSERT_FALSE(a.readIteratorWithinUpperBound());
380 | ASSERT_FALSE(a.writeIteratorWithinUpperBound());
381 | }
382 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------