Update the convolution code:

(1) to be multithreaded,
    (2) to work on multichannel audio and
    (3) to work on 48k and 44.1k audio.

    Allow multiple impulse response (IR) files with a new setting: "convolution_ir_files"
    When convolution starts, Shairport Sync will look for an IR file with a sample rate
    matching the input (44.1k or 48k) and channel count.
    If one can't be found, it will look for a single-channel IR file with the same rate.
    It will always choose the first match in the file list supplied "convolution_ir_files".

    Allow multithreading -- use the "convolution_thread_pool_size" to set the number of threads to use.

    Deprecate "convolution" -- use "convolution_enabled" instead.
    Deprecate "convolution_max_length" -- use "convolution_max_length_in_seconds" instead.
    Deprecate "convolution_ir_file" -- use "convolution_ir_files" instead.
    Update corresponding D-Bus methods and properties.

Update the loudness code to work on 48k and well as 44.1k audio and with multichannel audio.

    Deprecate "loudness" -- use "loudness_enabled" instead.
    Update corresponding D-Bus methods and properties.

Fix a deprecated FFmpeg warning.

Update HiFi-LoFi FFT convolver to latest available.
This commit is contained in:
Mike Brady
2025-10-13 13:26:20 +01:00
parent 08d369385c
commit d043f98330
25 changed files with 2480 additions and 1504 deletions
+1041 -1018
View File
File diff suppressed because it is too large Load Diff
+168 -176
View File
@@ -1,176 +1,168 @@
// ==================================================================================
// Copyright (c) 2016 HiFi-LoFi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ==================================================================================
#ifndef _AUDIOFFT_H
#define _AUDIOFFT_H
/**
* AudioFFT provides real-to-complex/complex-to-real FFT routines.
*
* Features:
*
* - Real-complex FFT and complex-real inverse FFT for power-of-2-sized real data.
*
* - Uniform interface to different FFT implementations (currently Ooura, FFTW3 and Apple Accelerate).
*
* - Complex data is handled in "split-complex" format, i.e. there are separate
* arrays for the real and imaginary parts which can be useful for SIMD optimizations
* (split-complex arrays have to be of length (size/2+1) representing bins from DC
* to Nyquist frequency).
*
* - Output is "ready to use" (all scaling etc. is already handled internally).
*
* - No allocations/deallocations after the initialization which makes it usable
* for real-time audio applications (that's what I wrote it for and using it).
*
*
* How to use it in your project:
*
* - Add the .h and .cpp file to your project - that's all.
*
* - To get extra speed, you can link FFTW3 to your project and define
* AUDIOFFT_FFTW3 (however, please check whether your project suits the
* according license).
*
* - To get the best speed on Apple platforms, you can link the Apple
* Accelerate framework to your project and define
* AUDIOFFT_APPLE_ACCELERATE (however, please check whether your
* project suits the according license).
*
*
* Remarks:
*
* - AudioFFT is not intended to be the fastest FFT, but to be a fast-enough
* FFT suitable for most audio applications.
*
* - AudioFFT uses the quite liberal MIT license.
*
*
* Example usage:
* @code
* #include "AudioFFT.h"
*
* void Example()
* {
* const size_t fftSize = 1024; // Needs to be power of 2!
*
* std::vector<float> input(fftSize, 0.0f);
* std::vector<float> re(audiofft::AudioFFT::ComplexSize(fftSize));
* std::vector<float> im(audiofft::AudioFFT::ComplexSize(fftSize));
* std::vector<float> output(fftSize);
*
* audiofft::AudioFFT fft;
* fft.init(1024);
* fft.fft(input.data(), re.data(), im.data());
* fft.ifft(output.data(), re.data(), im.data());
* }
* @endcode
*/
#include <cstddef>
#include <memory>
namespace audiofft
{
namespace details
{
class AudioFFTImpl
{
public:
AudioFFTImpl() = default;
virtual ~AudioFFTImpl() = default;
virtual void init(size_t size) = 0;
virtual void fft(const float* data, float* re, float* im) = 0;
virtual void ifft(float* data, const float* re, const float* im) = 0;
private:
AudioFFTImpl(const AudioFFTImpl&) = delete;
AudioFFTImpl& operator=(const AudioFFTImpl&) = delete;
};
}
// ======================================================
/**
* @class AudioFFT
* @brief Performs 1D FFTs
*/
class AudioFFT
{
public:
/**
* @brief Constructor
*/
AudioFFT();
/**
* @brief Initializes the FFT object
* @param size Size of the real input (must be power 2)
*/
void init(size_t size);
/**
* @brief Performs the forward FFT
* @param data The real input data (has to be of the length as specified in init())
* @param re The real part of the complex output (has to be of length as returned by ComplexSize())
* @param im The imaginary part of the complex output (has to be of length as returned by ComplexSize())
*/
void fft(const float* data, float* re, float* im);
/**
* @brief Performs the inverse FFT
* @param data The real output data (has to be of the length as specified in init())
* @param re The real part of the complex input (has to be of length as returned by ComplexSize())
* @param im The imaginary part of the complex input (has to be of length as returned by ComplexSize())
*/
void ifft(float* data, const float* re, const float* im);
/**
* @brief Calculates the necessary size of the real/imaginary complex arrays
* @param size The size of the real data
* @return The size of the real/imaginary complex arrays
*/
static size_t ComplexSize(size_t size);
private:
std::unique_ptr<details::AudioFFTImpl> _impl;
AudioFFT(const AudioFFT&) = delete;
AudioFFT& operator=(const AudioFFT&) = delete;
};
/**
* @deprecated
* @brief Let's keep an AudioFFTBase type around for now because it has been here already in the 1st version in order to avoid breaking existing code.
*/
typedef AudioFFT AudioFFTBase;
} // End of namespace
#endif // Header guard
// ==================================================================================
// Copyright (c) 2017 HiFi-LoFi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ==================================================================================
#ifndef _AUDIOFFT_H
#define _AUDIOFFT_H
/**
* AudioFFT provides real-to-complex/complex-to-real FFT routines.
*
* Features:
*
* - Real-complex FFT and complex-real inverse FFT for power-of-2-sized real data.
*
* - Uniform interface to different FFT implementations (currently Ooura, FFTW3 and Apple Accelerate).
*
* - Complex data is handled in "split-complex" format, i.e. there are separate
* arrays for the real and imaginary parts which can be useful for SIMD optimizations
* (split-complex arrays have to be of length (size/2+1) representing bins from DC
* to Nyquist frequency).
*
* - Output is "ready to use" (all scaling etc. is already handled internally).
*
* - No allocations/deallocations after the initialization which makes it usable
* for real-time audio applications (that's what I wrote it for and using it).
*
*
* How to use it in your project:
*
* - Add the .h and .cpp file to your project - that's all.
*
* - To get extra speed, you can link FFTW3 to your project and define
* AUDIOFFT_FFTW3 (however, please check whether your project suits the
* according license).
*
* - To get the best speed on Apple platforms, you can link the Apple
* Accelerate framework to your project and define
* AUDIOFFT_APPLE_ACCELERATE (however, please check whether your
* project suits the according license).
*
*
* Remarks:
*
* - AudioFFT is not intended to be the fastest FFT, but to be a fast-enough
* FFT suitable for most audio applications.
*
* - AudioFFT uses the quite liberal MIT license.
*
*
* Example usage:
* @code
* #include "AudioFFT.h"
*
* void Example()
* {
* const size_t fftSize = 1024; // Needs to be power of 2!
*
* std::vector<float> input(fftSize, 0.0f);
* std::vector<float> re(audiofft::AudioFFT::ComplexSize(fftSize));
* std::vector<float> im(audiofft::AudioFFT::ComplexSize(fftSize));
* std::vector<float> output(fftSize);
*
* audiofft::AudioFFT fft;
* fft.init(1024);
* fft.fft(input.data(), re.data(), im.data());
* fft.ifft(output.data(), re.data(), im.data());
* }
* @endcode
*/
#include <cstddef>
#include <memory>
namespace audiofft
{
namespace detail
{
class AudioFFTImpl;
}
// =============================================================
/**
* @class AudioFFT
* @brief Performs 1D FFTs
*/
class AudioFFT
{
public:
/**
* @brief Constructor
*/
AudioFFT();
AudioFFT(const AudioFFT&) = delete;
AudioFFT& operator=(const AudioFFT&) = delete;
/**
* @brief Destructor
*/
~AudioFFT();
/**
* @brief Initializes the FFT object
* @param size Size of the real input (must be power 2)
*/
void init(size_t size);
/**
* @brief Performs the forward FFT
* @param data The real input data (has to be of the length as specified in init())
* @param re The real part of the complex output (has to be of length as returned by ComplexSize())
* @param im The imaginary part of the complex output (has to be of length as returned by ComplexSize())
*/
void fft(const float* data, float* re, float* im);
/**
* @brief Performs the inverse FFT
* @param data The real output data (has to be of the length as specified in init())
* @param re The real part of the complex input (has to be of length as returned by ComplexSize())
* @param im The imaginary part of the complex input (has to be of length as returned by ComplexSize())
*/
void ifft(float* data, const float* re, const float* im);
/**
* @brief Calculates the necessary size of the real/imaginary complex arrays
* @param size The size of the real data
* @return The size of the real/imaginary complex arrays
*/
static size_t ComplexSize(size_t size);
private:
std::unique_ptr<detail::AudioFFTImpl> _impl;
};
/**
* @deprecated
* @brief Let's keep an AudioFFTBase type around for now because it has been here already in the 1st version in order to avoid breaking existing code.
*/
typedef AudioFFT AudioFFTBase;
} // End of namespace
#endif // Header guard
+186
View File
@@ -0,0 +1,186 @@
#include "ConvolverThreadPool.h"
#include "FFTConvolver.h"
#include "config.h"
ConvolverThreadPool::ConvolverThreadPool()
: _convolvers(), _threads(), _taskQueue(), _queueMutex(), _condition(), _completionCV(),
_stop(false), _activeTasks(0) {}
ConvolverThreadPool::~ConvolverThreadPool() {
shutdown();
// Delete all convolver instances
for (size_t i = 0; i < _convolvers.size(); ++i) {
delete _convolvers[i];
}
_convolvers.clear();
}
bool ConvolverThreadPool::init(size_t numThreads, size_t numConvolvers) {
// Clean up any existing threads first
shutdown();
// Validate parameters
if (numThreads == 0 || numConvolvers == 0) {
return false;
}
// Delete any existing convolvers
for (size_t i = 0; i < _convolvers.size(); ++i) {
delete _convolvers[i];
}
_convolvers.clear();
// Reset state
_stop = false;
_activeTasks = 0;
// Create convolver instances (but don't initialize them yet)
_convolvers.resize(numConvolvers);
for (size_t i = 0; i < numConvolvers; ++i) {
_convolvers[i] = new FFTConvolver();
}
// Create worker threads
_threads.reserve(numThreads);
for (size_t i = 0; i < numThreads; i++) {
#ifndef COMPILE_FOR_OSX
pthread_setname_np(pthread_self(), "convolver");
#endif
_threads.emplace_back([this]() { workerThread(); });
}
return true;
}
// Mutex to protect FFTW plan creation (required)
std::mutex fftwMutex;
bool ConvolverThreadPool::initConvolver(size_t convolverId, size_t blockSize, const Sample *ir,
size_t irLen) {
if (convolverId >= _convolvers.size()) {
return false;
}
// Make sure no tasks are using this convolver
waitForAll();
std::lock_guard<std::mutex> lock(fftwMutex);
return _convolvers[convolverId]->init(blockSize, ir, irLen);
}
bool ConvolverThreadPool::initAllConvolvers(size_t blockSize, const Sample *ir, size_t irLen) {
// Make sure no tasks are running
waitForAll();
for (size_t i = 0; i < _convolvers.size(); ++i) {
if (!_convolvers[i]->init(blockSize, ir, irLen)) {
return false;
}
}
return true;
}
void ConvolverThreadPool::processAsync(size_t convolverId, const Sample *input, Sample *output,
size_t len) {
assert(convolverId < _convolvers.size());
{
std::lock_guard<std::mutex> lock(_queueMutex);
// Create the task
_taskQueue.push([this, convolverId, input, output, len]() {
_convolvers[convolverId]->process(input, output, len);
});
++_activeTasks;
}
// Wake up one worker thread
_condition.notify_one();
}
void ConvolverThreadPool::waitForAll() {
std::unique_lock<std::mutex> lock(_queueMutex);
_completionCV.wait(lock, [this]() { return _taskQueue.empty() && _activeTasks == 0; });
}
void ConvolverThreadPool::clearState(size_t convolverId) {
assert(convolverId < _convolvers.size());
// Make sure no tasks are running before clearing state
waitForAll();
// _convolvers[convolverId]->clearState();
}
void ConvolverThreadPool::clearAllStates() {
// Make sure no tasks are running before clearing state
waitForAll();
for (size_t i = 0; i < _convolvers.size(); ++i) {
_convolvers[i]->clearState();
}
}
void ConvolverThreadPool::workerThread() {
while (true) {
std::function<void()> task;
// Wait for a task or stop signal
{
std::unique_lock<std::mutex> lock(_queueMutex);
_condition.wait(lock, [this]() { return _stop || !_taskQueue.empty(); });
// Exit if stopping and no more tasks
if (_stop && _taskQueue.empty()) {
return;
}
// Get the next task
task = std::move(_taskQueue.front());
_taskQueue.pop();
}
// Execute the task (outside the lock for better parallelism)
task();
// Mark task as complete
{
std::lock_guard<std::mutex> lock(_queueMutex);
--_activeTasks;
_completionCV.notify_all();
}
}
}
void ConvolverThreadPool::shutdown() {
// Signal threads to stop
{
std::lock_guard<std::mutex> lock(_queueMutex);
_stop = true;
}
_condition.notify_all();
// Wait for all threads to finish
for (auto &thread : _threads) {
if (thread.joinable()) {
thread.join();
}
}
// Clear thread vector
_threads.clear();
// Clear remaining tasks - properly this time
{
std::lock_guard<std::mutex> lock(_queueMutex);
while (!_taskQueue.empty()) {
_taskQueue.pop();
}
}
// Reset state
_activeTasks = 0;
_stop = false;
}
+72
View File
@@ -0,0 +1,72 @@
#ifndef CONVOLVER_THREAD_POOL_H
#define CONVOLVER_THREAD_POOL_H
#include "FFTConvolver.h"
#include <cassert>
#include <condition_variable>
#include <functional>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
// Use the fftconvolver namespace
using fftconvolver::FFTConvolver;
using fftconvolver::Sample;
class ConvolverThreadPool {
private:
std::vector<FFTConvolver *> _convolvers;
std::vector<std::thread> _threads;
std::queue<std::function<void()>> _taskQueue;
std::mutex _queueMutex;
std::condition_variable _condition;
std::condition_variable _completionCV;
bool _stop;
size_t _activeTasks;
public:
ConvolverThreadPool();
~ConvolverThreadPool();
// Initialize the thread pool (creates convolvers but doesn't initialize them)
// numThreads: number of worker threads (level of parallelism)
// numConvolvers: total number of convolver instances
bool init(size_t numThreads, size_t numConvolvers);
// Initialize a specific convolver with its IR
// convolverId: which convolver to initialize
// blockSize: block size for convolution
// ir: impulse response data
// irLen: length of impulse response
bool initConvolver(size_t convolverId, size_t blockSize, const Sample *ir, size_t irLen);
// Initialize all convolvers with the same IR
bool initAllConvolvers(size_t blockSize, const Sample *ir, size_t irLen);
// Queue a convolution task (non-blocking)
void processAsync(size_t convolverId, const Sample *input, Sample *output, size_t len);
// Wait for all queued tasks to complete (blocking)
void waitForAll();
// Clear the state of a specific convolver
void clearState(size_t convolverId);
// Clear the state of all convolvers
void clearAllStates();
// Get the number of convolvers
size_t getNumConvolvers() const { return _convolvers.size(); }
// Get the number of threads
size_t getNumThreads() const { return _threads.size(); }
void shutdown();
private:
void workerThread();
// void shutdown();
};
#endif // CONVOLVER_THREAD_POOL_H
+20
View File
@@ -77,6 +77,26 @@ void FFTConvolver::reset()
_inputBufferFill = 0;
}
void FFTConvolver::clearState()
{
if (_segCount == 0)
{
return; // Not initialized
}
_inputBuffer.setZero();
_inputBufferFill = 0;
_overlap.setZero();
for (size_t i = 0; i < _segCount; ++i)
{
_segments[i]->setZero();
}
_preMultiplied.setZero();
_conv.setZero();
_current = 0;
}
bool FFTConvolver::init(size_t blockSize, const Sample* ir, size_t irLen)
{
+21 -11
View File
@@ -1,18 +1,22 @@
// ==================================================================================
// Copyright (c) 2012 HiFi-LoFi
// Copyright (c) 2017 HiFi-LoFi
//
// This is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ==================================================================================
#ifndef _FFTCONVOLVER_FFTCONVOLVER_H
@@ -74,6 +78,12 @@ public:
*/
void reset();
/**
* @brief Clears audio history
*/
void clearState();
private:
size_t _blockSize;
size_t _segSize;
+15 -11
View File
@@ -1,18 +1,22 @@
// ==================================================================================
// Copyright (c) 2012 HiFi-LoFi
// Copyright (c) 2017 HiFi-LoFi
//
// This is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ==================================================================================
#include "Utilities.h"
+16 -13
View File
@@ -1,18 +1,22 @@
// ==================================================================================
// Copyright (c) 2012 HiFi-LoFi
// Copyright (c) 2017 HiFi-LoFi
//
// This is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ==================================================================================
#ifndef _FFTCONVOLVER_UTILITIES_H
@@ -94,8 +98,7 @@ public:
_size = size;
}
}
if (_data)
setZero();
setZero();
}
size_t size() const
+164 -45
View File
@@ -1,10 +1,12 @@
#include "convolver.h"
#include "ConvolverThreadPool.h"
#include "FFTConvolver.h"
#include "Utilities.h"
#include <pthread.h>
#include <sndfile.h>
#include <unistd.h>
extern "C" void _warn(const char *filename, const int linenumber, const char *format, ...);
extern "C" void _debug(const char *filename, const int linenumber, int level, const char *format,
@@ -13,64 +15,150 @@ extern "C" void _debug(const char *filename, const int linenumber, int level, co
#define warn(...) _warn(__FILE__, __LINE__, __VA_ARGS__)
#define debug(...) _debug(__FILE__, __LINE__, __VA_ARGS__)
fftconvolver::FFTConvolver convolver_l;
fftconvolver::FFTConvolver convolver_r;
// Create and initialize the thread pool
ConvolverThreadPool pool;
void convolver_pool_init(size_t numThreads, size_t numConvolvers) {
if (!pool.init(numThreads, numConvolvers)) {
debug(1, "failed to initialize thread pool!");
} else {
debug(1, "thread pool initialized with %u threads and %u convolvers.", numThreads,
numConvolvers);
}
}
void convolver_pool_closedown() {
pool.shutdown(); // Just shutdown, don't delete
debug(3, "thread pool shut down");
}
int convolver_init(const char *filename, unsigned char channel_count,
double max_length_in_seconds, size_t block_size) {
debug(3, "convolver_init");
int success = 0;
SF_INFO info = {}; // Zero everything, including format
if (filename) {
SNDFILE *file = sf_open(filename, SFM_READ, &info);
if (file) {
size_t max_length = (size_t)(max_length_in_seconds * info.samplerate);
const size_t size =
(unsigned int)info.frames > max_length ? max_length : (unsigned int)info.frames;
float *buffer = (float*)malloc(sizeof(float) * size * info.channels);
if (buffer != NULL) {
// float buffer[size * info.channels];
float *abuffer = (float*)malloc(sizeof(float) * size);
if (abuffer != NULL) {
size_t l = sf_readf_float(file, buffer, size);
if (l != 0) {
unsigned int cc;
if (info.channels == 1) {
for (cc = 0; cc < channel_count; cc++) {
if (!pool.initConvolver(cc, block_size, buffer, size)) {
debug(1, "new convolver failed to initialize convolver %u ", cc);
}
}
} else if (info.channels == channel_count) {
// we have to deinterleave the ir file channels for each convolver
// float abuffer[size];
for (cc = 0; cc < channel_count; cc++) {
unsigned int i;
for (i = 0; i < size; ++i) {
abuffer[i] = buffer[channel_count * i + cc];
}
if (!pool.initConvolver(cc, block_size, abuffer, size)) {
debug(1, "new convolver failed to initialize convolver %u ", cc);
}
}
}
success = 1;
}
debug(2,
"convolution impulse response filter initialized from \"%s\" with %d channel%s and "
"%d samples",
filename, info.channels, info.channels == 1 ? "" : "s", size);
sf_close(file);
free((void*)abuffer);
} else {
debug(1, "failed to init convolvers because insufficient memory was available");
}
free((void*)buffer);
} else {
warn("failed to init convolvers because insufficient memory was available");
}
} else {
warn("Convolution impulse response filter file \"%s\" can not be opened. Please check that "
"it exists, is a valid sound file and has appropriate access permissions.",
filename);
}
}
return success;
}
void convolver_process(unsigned int channel, float *data, int length) {
pool.processAsync(channel, data, data, length);
}
void convolver_wait_for_all() { pool.waitForAll(); }
void convolver_clear_state() {
pool.clearAllStates();
}
const unsigned int max_channels = 8;
fftconvolver::FFTConvolver convolvers[max_channels];
// fftconvolver::FFTConvolver convolver_l;
// fftconvolver::FFTConvolver convolver_r;
// always lock use this when accessing the playing conn value
/*
pthread_mutex_t convolver_lock = PTHREAD_MUTEX_INITIALIZER;
int convolver_init(const char *filename, int max_length) {
int convolver_init(const char *filename, unsigned char channel_count, double max_length_in_seconds,
size_t block_size) {
debug(1, "convolver_init");
int success = 0;
SF_INFO info;
if (filename) {
SNDFILE *file = sf_open(filename, SFM_READ, &info);
if (file) {
size_t max_length = (size_t)(max_length_in_seconds * info.samplerate);
const size_t size =
(unsigned int)info.frames > max_length ? max_length : (unsigned int)info.frames;
float buffer[size * info.channels];
if (info.samplerate == 44100) {
if ((info.channels == 1) || (info.channels == 2)) {
const size_t size = info.frames > max_length ? max_length : info.frames;
float buffer[size * info.channels];
size_t l = sf_readf_float(file, buffer, size);
if (l != 0) {
pthread_mutex_lock(&convolver_lock);
size_t l = sf_readf_float(file, buffer, size);
if (l != 0) {
pthread_mutex_lock(&convolver_lock);
convolver_l.reset(); // it is possible that init could be called more than once
convolver_r.reset(); // so it could be necessary to remove all previous settings
if (info.channels == 1) {
convolver_l.init(352, buffer, size);
convolver_r.init(352, buffer, size);
} else {
// deinterleave
float buffer_l[size];
float buffer_r[size];
unsigned int i;
for (i = 0; i < size; ++i) {
buffer_l[i] = buffer[2 * i + 0];
buffer_r[i] = buffer[2 * i + 1];
}
convolver_l.init(352, buffer_l, size);
convolver_r.init(352, buffer_r, size);
}
pthread_mutex_unlock(&convolver_lock);
success = 1;
}
debug(1,
"convolution impulse response filter initialized from \"%s\" with %d channel%s and "
"%d samples",
filename, info.channels, info.channels == 1 ? "" : "s", size);
} else {
warn("Convolution impulse response filter file \"%s\" contains %d channels. Only 1 or 2 "
"is supported.",
filename, info.channels);
unsigned int cc;
for (cc = 0; cc < channel_count; cc++) {
convolvers[cc].reset();
}
} else {
warn("Convolution impulse response filter file \"%s\" sample rate is %d Hz. Only 44100 Hz "
"is supported.",
filename, info.samplerate);
if (info.channels == 1) {
for (cc = 0; cc < channel_count; cc++) {
convolvers[cc].init(block_size, buffer, size);
}
} else if (info.channels == channel_count) {
// we have to deinterleave the ir file channels for each convolver
for (cc = 0; cc < channel_count; cc++) {
float abuffer[size];
unsigned int i;
for (i = 0; i < size; ++i) {
abuffer[i] = buffer[channel_count * i + cc];
}
convolvers[cc].init(block_size, abuffer, size);
}
}
pthread_mutex_unlock(&convolver_lock);
success = 1;
}
debug(2,
"convolution impulse response filter initialized from \"%s\" with %d channel%s and "
"%d samples",
filename, info.channels, info.channels == 1 ? "" : "s", size);
sf_close(file);
} else {
warn("Convolution impulse response filter file \"%s\" can not be opened. Please check that "
@@ -80,6 +168,36 @@ int convolver_init(const char *filename, int max_length) {
}
return success;
}
void convolver_reset() {
debug(1, "convolver_reset");
pthread_mutex_lock(&convolver_lock);
unsigned int cc;
for (cc = 0; cc < max_channels; cc++) {
convolvers[cc].reset();
}
// convolver_l.reset(); // it is possible that init could be called more than once
// convolver_r.reset(); // so it could be necessary to remove all previous settings
pthread_mutex_unlock(&convolver_lock);
}
void convolver_clear_state() {
debug(1, "convolver_clear_state");
pthread_mutex_lock(&convolver_lock);
unsigned int cc;
for (cc = 0; cc < max_channels; cc++) {
convolvers[cc].clearState();
}
// convolver_l.reset(); // it is possible that init could be called more than once
// convolver_r.reset(); // so it could be necessary to remove all previous settings
pthread_mutex_unlock(&convolver_lock);
}
void convolver_process(unsigned int channel, float *data, int length) {
pthread_mutex_lock(&convolver_lock);
convolvers[channel].process(data, data, length);
pthread_mutex_unlock(&convolver_lock);
usleep(100);
}
void convolver_process_l(float *data, int length) {
pthread_mutex_lock(&convolver_lock);
@@ -92,3 +210,4 @@ void convolver_process_r(float *data, int length) {
convolver_r.process(data, data, length);
pthread_mutex_unlock(&convolver_lock);
}
*/
+15 -3
View File
@@ -4,10 +4,22 @@
#ifdef __cplusplus
extern "C" {
#endif
#include <stddef.h>
int convolver_init(const char* file, int max_length);
void convolver_process_l(float* data, int length);
void convolver_process_r(float* data, int length);
// int convolver_init(const char* file, unsigned char channel_count, double max_length_in_seconds, size_t block_size);
void convolver_reset();
//void convolver_clear_state();
// void convolver_process(unsigned int channel, float *data, int length);
// void convolver_process_l(float* data, int length);
// void convolver_process_r(float* data, int length);
void convolver_pool_init(size_t numThreads, size_t numConvolvers);
void convolver_pool_closedown();
int convolver_init(const char* file, unsigned char channel_count, double max_length_in_seconds, size_t block_size);
void convolver_process(unsigned int channel, float *data, int length);
void convolver_clear_state();
void convolver_wait_for_all();
#ifdef __cplusplus
}