From 8b8caf49376e92bd4ce873a4f6c460f8203121c7 Mon Sep 17 00:00:00 2001 From: Jean Pierre Cimalando Date: Mon, 1 Feb 2021 21:08:57 +0100 Subject: [PATCH 1/8] Remove callback guard where useless --- src/sfizz/Synth.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/sfizz/Synth.cpp b/src/sfizz/Synth.cpp index 0316b397..71bdd49d 100644 --- a/src/sfizz/Synth.cpp +++ b/src/sfizz/Synth.cpp @@ -54,7 +54,6 @@ Synth::Impl::Impl() initializeSIMDDispatchers(); initializeInterpolators(); - const std::lock_guard disableCallback { callbackGuard_ }; parser_.setListener(this); effectFactory_.registerStandardEffectTypes(); effectBuses_.reserve(5); // sufficient room for main and fx1-4 @@ -69,8 +68,6 @@ Synth::Impl::Impl() Synth::Impl::~Impl() { - const std::lock_guard disableCallback { callbackGuard_ }; - voiceManager_.reset(); resources_.filePool.emptyFileLoadingQueues(); } From e178ae25e6e7456370ddd87e91afd2af1e210964 Mon Sep 17 00:00:00 2001 From: Jean Pierre Cimalando Date: Mon, 1 Feb 2021 21:29:12 +0100 Subject: [PATCH 2/8] Remove all callback guards --- src/sfizz/Synth.cpp | 32 -------------------------------- src/sfizz/SynthPrivate.h | 2 -- 2 files changed, 34 deletions(-) diff --git a/src/sfizz/Synth.cpp b/src/sfizz/Synth.cpp index 71bdd49d..2a12f683 100644 --- a/src/sfizz/Synth.cpp +++ b/src/sfizz/Synth.cpp @@ -18,7 +18,6 @@ #include "Resources.h" #include "ScopedFTZ.h" #include "StringViewHelpers.h" -#include "utility/SpinMutex.h" #include "utility/XmlHelpers.h" #include "Voice.h" #include "Interpolators.h" @@ -486,7 +485,6 @@ void Synth::Impl::handleEffectOpcodes(const std::vector& rawMembers) bool Synth::loadSfzFile(const fs::path& file) { Impl& impl = *impl_; - const std::lock_guard disableCallback { impl.callbackGuard_ }; impl.clear(); @@ -515,7 +513,6 @@ bool Synth::loadSfzFile(const fs::path& file) bool Synth::loadSfzString(const fs::path& path, absl::string_view text) { Impl& impl = *impl_; - const std::lock_guard disableCallback { impl.callbackGuard_ }; impl.clear(); @@ -805,8 +802,6 @@ void Synth::setSamplesPerBlock(int samplesPerBlock) noexcept Impl& impl = *impl_; ASSERT(samplesPerBlock <= config::maxBlockSize); - const std::lock_guard disableCallback { impl.callbackGuard_ }; - impl.samplesPerBlock_ = samplesPerBlock; for (auto& voice : impl.voiceManager_) voice.setSamplesPerBlock(samplesPerBlock); @@ -828,7 +823,6 @@ int Synth::getSamplesPerBlock() const noexcept void Synth::setSampleRate(float sampleRate) noexcept { Impl& impl = *impl_; - const std::lock_guard disableCallback { impl.callbackGuard_ }; impl.sampleRate_ = sampleRate; for (auto& voice : impl.voiceManager_) @@ -865,10 +859,6 @@ void Synth::renderBlock(AudioSpan buffer) noexcept impl.resources_.filePool.triggerGarbageCollection(); } - const std::unique_lock lock { impl.callbackGuard_, std::try_to_lock }; - if (!lock.owns_lock()) - return; - size_t numFrames = buffer.getNumFrames(); auto tempSpan = impl.resources_.bufferPool.getStereoBuffer(numFrames); auto tempMixSpan = impl.resources_.bufferPool.getStereoBuffer(numFrames); @@ -986,11 +976,6 @@ void Synth::noteOn(int delay, int noteNumber, uint8_t velocity) noexcept const auto normalizedVelocity = normalizeVelocity(velocity); ScopedTiming logger { impl.dispatchDuration_, ScopedTiming::Operation::addToDuration }; impl.resources_.midiState.noteOnEvent(delay, noteNumber, normalizedVelocity); - - const std::unique_lock lock { impl.callbackGuard_, std::try_to_lock }; - if (!lock.owns_lock()) - return; - impl.noteOnDispatch(delay, noteNumber, normalizedVelocity); } @@ -1004,10 +989,6 @@ void Synth::noteOff(int delay, int noteNumber, uint8_t velocity) noexcept ScopedTiming logger { impl.dispatchDuration_, ScopedTiming::Operation::addToDuration }; impl.resources_.midiState.noteOffEvent(delay, noteNumber, normalizedVelocity); - const std::unique_lock lock { impl.callbackGuard_, std::try_to_lock }; - if (!lock.owns_lock()) - return; - // FIXME: Some keyboards (e.g. Casio PX5S) can send a real note-off velocity. In this case, do we have a // way in sfz to specify that a release trigger should NOT use the note-on velocity? // auto replacedVelocity = (velocity == 0 ? getNoteVelocity(noteNumber) : velocity); @@ -1148,10 +1129,6 @@ void Synth::Impl::performHdcc(int delay, int ccNumber, float normValue, bool asM ScopedTiming logger { dispatchDuration_, ScopedTiming::Operation::addToDuration }; resources_.midiState.ccEvent(delay, ccNumber, normValue); - const std::unique_lock lock { callbackGuard_, std::try_to_lock }; - if (!lock.owns_lock()) - return; - if (asMidi) { if (ccNumber == config::resetCC) { resetAllControllers(delay); @@ -1492,7 +1469,6 @@ void Synth::setNumVoices(int numVoices) noexcept { ASSERT(numVoices > 0); Impl& impl = *impl_; - const std::lock_guard disableCallback { impl.callbackGuard_ }; // fast path if (numVoices == impl.numVoices_) @@ -1601,7 +1577,6 @@ void Synth::Impl::setupModMatrix() void Synth::setOversamplingFactor(Oversampling factor) noexcept { Impl& impl = *impl_; - const std::lock_guard disableCallback { impl.callbackGuard_ }; // fast path if (factor == impl.oversamplingFactor_) @@ -1624,7 +1599,6 @@ Oversampling Synth::getOversamplingFactor() const noexcept void Synth::setPreloadSize(uint32_t preloadSize) noexcept { Impl& impl = *impl_; - const std::lock_guard disableCallback { impl.callbackGuard_ }; // fast path if (preloadSize == impl.resources_.filePool.getPreloadSize()) @@ -1660,10 +1634,6 @@ void Synth::Impl::resetAllControllers(int delay) noexcept { resources_.midiState.resetAllControllers(delay); - const std::unique_lock lock { callbackGuard_, std::try_to_lock }; - if (!lock.owns_lock()) - return; - for (auto& voice : voiceManager_) { voice.registerPitchWheel(delay, 0); for (int cc = 0; cc < config::numCCs; ++cc) @@ -1732,8 +1702,6 @@ void Synth::disableLogging() noexcept void Synth::allSoundOff() noexcept { Impl& impl = *impl_; - const std::lock_guard disableCallback { impl.callbackGuard_ }; - for (auto& voice : impl.voiceManager_) voice.reset(); for (auto& effectBus : impl.effectBuses_) diff --git a/src/sfizz/SynthPrivate.h b/src/sfizz/SynthPrivate.h index 488979be..42063ed0 100644 --- a/src/sfizz/SynthPrivate.h +++ b/src/sfizz/SynthPrivate.h @@ -246,8 +246,6 @@ struct Synth::Impl final: public Parser::Listener { // Distribution used to generate random value for the *rand opcodes std::uniform_real_distribution randNoteDistribution_ { 0, 1 }; - SpinMutex callbackGuard_; - // Singletons passed as references to the voices Resources resources_; From c110acc966258ceffe5937ca669ed0b87173f306 Mon Sep 17 00:00:00 2001 From: Jean Pierre Cimalando Date: Mon, 1 Feb 2021 22:04:02 +0100 Subject: [PATCH 3/8] Provide the spin mutex as internal library --- common.mk | 6 ++- src/CMakeLists.txt | 14 +++++-- src/sfizz/FilePool.h | 3 +- .../utility/{ => spin_mutex}/SpinMutex.cpp | 0 .../utility/{ => spin_mutex}/SpinMutex.h | 0 src/sfizz/utility/spin_mutex/spin_mutex.cpp | 37 +++++++++++++++++++ src/sfizz/utility/spin_mutex/spin_mutex.h | 24 ++++++++++++ tests/CMakeLists.txt | 2 +- tests/ConcurrencyT.cpp | 2 +- 9 files changed, 79 insertions(+), 9 deletions(-) rename src/sfizz/utility/{ => spin_mutex}/SpinMutex.cpp (100%) rename src/sfizz/utility/{ => spin_mutex}/SpinMutex.h (100%) create mode 100644 src/sfizz/utility/spin_mutex/spin_mutex.cpp create mode 100644 src/sfizz/utility/spin_mutex/spin_mutex.h diff --git a/common.mk b/common.mk index 4efdbc57..5c7cf10f 100644 --- a/common.mk +++ b/common.mk @@ -117,7 +117,7 @@ SFIZZ_SOURCES = \ src/sfizz/Synth.cpp \ src/sfizz/SynthMessaging.cpp \ src/sfizz/Tuning.cpp \ - src/sfizz/utility/SpinMutex.cpp \ + src/sfizz/utility/spin_mutex/SpinMutex.cpp \ src/sfizz/Voice.cpp \ src/sfizz/VoiceManager.cpp \ src/sfizz/VoiceStealing.cpp \ @@ -126,7 +126,9 @@ SFIZZ_SOURCES = \ ### Other internal -SFIZZ_C_FLAGS += -I$(SFIZZ_DIR)/src/sfizz +SFIZZ_C_FLAGS += \ + -I$(SFIZZ_DIR)/src/sfizz \ + -I$(SFIZZ_DIR)/src/sfizz/utility/spin_mutex # Pkg-config dependency diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 6786663e..2a574522 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -26,7 +26,6 @@ set(SFIZZ_HEADERS sfizz/Curve.h sfizz/Debug.h sfizz/utility/NumericId.h - sfizz/utility/SpinMutex.h sfizz/utility/XmlHelpers.h sfizz/modulations/ModId.h sfizz/modulations/ModKey.h @@ -163,7 +162,6 @@ set(SFIZZ_SOURCES sfizz/modulations/sources/FlexEnvelope.cpp sfizz/modulations/sources/ADSREnvelope.cpp sfizz/modulations/sources/LFO.cpp - sfizz/utility/SpinMutex.cpp sfizz/effects/Nothing.cpp sfizz/effects/Filter.cpp sfizz/effects/Eq.cpp @@ -239,13 +237,23 @@ target_sources(sfizz_messaging PRIVATE target_include_directories(sfizz_messaging PUBLIC ".") target_link_libraries(sfizz_messaging PUBLIC absl::strings) +# Sfizz spinlock mutex +add_library(sfizz_spin_mutex STATIC + sfizz/utility/spin_mutex/spin_mutex.h + sfizz/utility/spin_mutex/spin_mutex.cpp + sfizz/utility/spin_mutex/SpinMutex.h + sfizz/utility/spin_mutex/SpinMutex.cpp) +target_include_directories(sfizz_spin_mutex PUBLIC sfizz/utility/spin_mutex) +target_link_libraries(sfizz_spin_mutex PRIVATE sfizz::atomic_queue) +add_library(sfizz::spin_mutex ALIAS sfizz_spin_mutex) + # Sfizz internals (use this for testing) add_library(sfizz_internal STATIC) add_library(sfizz::internal ALIAS sfizz_internal) target_sources(sfizz_internal PRIVATE ${SFIZZ_HEADERS} ${SFIZZ_SOURCES} ${FAUST_FILES}) target_include_directories(sfizz_internal PUBLIC "." "sfizz") target_link_libraries(sfizz_internal - PUBLIC absl::strings absl::span sfizz::filesystem sfizz::atomic_queue + PUBLIC absl::strings absl::span sfizz::filesystem sfizz::atomic_queue sfizz::spin_mutex PRIVATE sfizz::parser sfizz::messaging absl::flat_hash_map Threads::Threads st_audiofile sfizz::pugixml sfizz::spline sfizz::tunings sfizz::hiir sfizz::kissfft sfizz::cephes sfizz::cpuid sfizz::threadpool sfizz::jsl sfizz::atomic) if(SFIZZ_USE_SNDFILE) target_compile_definitions(sfizz_internal PUBLIC "SFIZZ_USE_SNDFILE=1") diff --git a/src/sfizz/FilePool.h b/src/sfizz/FilePool.h index 7f8be842..fa67db72 100644 --- a/src/sfizz/FilePool.h +++ b/src/sfizz/FilePool.h @@ -33,7 +33,7 @@ #include "FileId.h" #include "FileMetadata.h" #include "SIMDHelpers.h" -#include "utility/SpinMutex.h" +#include #include "ghc/fs_std.hpp" #include #include @@ -43,7 +43,6 @@ #include #include #include -#include "utility/SpinMutex.h" class ThreadPool; namespace sfz { diff --git a/src/sfizz/utility/SpinMutex.cpp b/src/sfizz/utility/spin_mutex/SpinMutex.cpp similarity index 100% rename from src/sfizz/utility/SpinMutex.cpp rename to src/sfizz/utility/spin_mutex/SpinMutex.cpp diff --git a/src/sfizz/utility/SpinMutex.h b/src/sfizz/utility/spin_mutex/SpinMutex.h similarity index 100% rename from src/sfizz/utility/SpinMutex.h rename to src/sfizz/utility/spin_mutex/SpinMutex.h diff --git a/src/sfizz/utility/spin_mutex/spin_mutex.cpp b/src/sfizz/utility/spin_mutex/spin_mutex.cpp new file mode 100644 index 00000000..af786711 --- /dev/null +++ b/src/sfizz/utility/spin_mutex/spin_mutex.cpp @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: BSD-2-Clause + +// This code is part of the sfizz library and is licensed under a BSD 2-clause +// license. You should have receive a LICENSE.md file along with the code. +// If not, contact the sfizz maintainers at https://github.com/sfztools/sfizz + +#include "spin_mutex.h" +#include "SpinMutex.h" + +struct spin_mutex_ { + SpinMutex mtx; +}; + +spin_mutex_t* spin_mutex_create() +{ + return new spin_mutex_t; +} + +void spin_mutex_destroy(spin_mutex_t* mtx) +{ + delete mtx; +} + +void spin_mutex_lock(spin_mutex_t* mtx) +{ + mtx->mtx.lock(); +} + +void spin_mutex_unlock(spin_mutex_t* mtx) +{ + mtx->mtx.unlock(); +} + +bool spin_mutex_trylock(spin_mutex_t* mtx) +{ + return mtx->mtx.try_lock(); +} diff --git a/src/sfizz/utility/spin_mutex/spin_mutex.h b/src/sfizz/utility/spin_mutex/spin_mutex.h new file mode 100644 index 00000000..63c9053f --- /dev/null +++ b/src/sfizz/utility/spin_mutex/spin_mutex.h @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: BSD-2-Clause + +// This code is part of the sfizz library and is licensed under a BSD 2-clause +// license. You should have receive a LICENSE.md file along with the code. +// If not, contact the sfizz maintainers at https://github.com/sfztools/sfizz + +#pragma once +#include + +#if defined(__cplusplus) +extern "C" { +#endif + +typedef struct spin_mutex_ spin_mutex_t; + +spin_mutex_t* spin_mutex_create(); +void spin_mutex_destroy(spin_mutex_t* mtx); +void spin_mutex_lock(spin_mutex_t* mtx); +void spin_mutex_unlock(spin_mutex_t* mtx); +bool spin_mutex_trylock(spin_mutex_t* mtx); + +#if defined(__cplusplus) +} // extern "C" +#endif diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 15c1d0d6..6e28170f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -46,7 +46,7 @@ set(SFIZZ_TEST_SOURCES ) add_executable(sfizz_tests ${SFIZZ_TEST_SOURCES}) -target_link_libraries(sfizz_tests PRIVATE sfizz::internal sfizz::jsl) +target_link_libraries(sfizz_tests PRIVATE sfizz::internal sfizz::spin_mutex sfizz::jsl) sfizz_enable_lto_if_needed(sfizz_tests) sfizz_enable_fast_math(sfizz_tests) diff --git a/tests/ConcurrencyT.cpp b/tests/ConcurrencyT.cpp index 9ec72cd5..f82e20bd 100644 --- a/tests/ConcurrencyT.cpp +++ b/tests/ConcurrencyT.cpp @@ -4,8 +4,8 @@ // license. You should have receive a LICENSE.md file along with the code. // If not, contact the sfizz maintainers at https://github.com/sfztools/sfizz -#include "sfizz/utility/SpinMutex.h" #include "catch2/catch.hpp" +#include #include #include #include From 1d6b06aa2e66f4c4bd6afa9abc0c2ddc67d5d061 Mon Sep 17 00:00:00 2001 From: Jean Pierre Cimalando Date: Mon, 1 Feb 2021 22:46:02 +0100 Subject: [PATCH 4/8] Thread-safety at LV2 level --- lv2/CMakeLists.txt | 8 +++--- lv2/sfizz.c | 64 ++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 63 insertions(+), 9 deletions(-) diff --git a/lv2/CMakeLists.txt b/lv2/CMakeLists.txt index c5a4e861..d247dd14 100644 --- a/lv2/CMakeLists.txt +++ b/lv2/CMakeLists.txt @@ -22,25 +22,25 @@ add_library(${LV2PLUGIN_PRJ_NAME} MODULE ${PROJECT_NAME}.c atomic_compat.h ${LV2PLUGIN_TTL_SRC_FILES}) -target_link_libraries(${LV2PLUGIN_PRJ_NAME} ${PROJECT_NAME}::${PROJECT_NAME}) +target_link_libraries(${LV2PLUGIN_PRJ_NAME} PRIVATE sfizz::sfizz sfizz::spin_mutex) if(SFIZZ_LV2_UI) add_library(${LV2PLUGIN_PRJ_NAME}_ui MODULE ${PROJECT_NAME}_ui.cpp vstgui_helpers.h vstgui_helpers.cpp) - target_link_libraries(${LV2PLUGIN_PRJ_NAME}_ui sfizz::editor sfizz::vstgui) + target_link_libraries(${LV2PLUGIN_PRJ_NAME}_ui PRIVATE sfizz::editor sfizz::vstgui) endif() # Explicitely strip all symbols on Linux but lv2_descriptor() # MacOS linker does not support this apparently https://bugs.webkit.org/show_bug.cgi?id=144555 if(${CMAKE_SYSTEM_NAME} MATCHES "Linux") file(COPY lv2.version DESTINATION ${CMAKE_BINARY_DIR}/lv2) - target_link_libraries(${LV2PLUGIN_PRJ_NAME} "-Wl,--version-script=lv2.version") + target_link_libraries(${LV2PLUGIN_PRJ_NAME} PRIVATE "-Wl,--version-script=lv2.version") # target_link_libraries(${LV2PLUGIN_PRJ_NAME} "-Wl,-u,lv2_descriptor") if(SFIZZ_LV2_UI) file(COPY lv2ui.version DESTINATION ${CMAKE_BINARY_DIR}/lv2) - target_link_libraries(${LV2PLUGIN_PRJ_NAME}_ui "-Wl,--version-script=lv2ui.version") + target_link_libraries(${LV2PLUGIN_PRJ_NAME}_ui PRIVATE "-Wl,--version-script=lv2ui.version") # target_link_libraries(${LV2PLUGIN_PRJ_NAME}_ui "-Wl,-u,lv2ui_descriptor") endif() endif() diff --git a/lv2/sfizz.c b/lv2/sfizz.c index 57d80846..115fea48 100644 --- a/lv2/sfizz.c +++ b/lv2/sfizz.c @@ -53,6 +53,8 @@ #include +#include + #include #include #include @@ -160,6 +162,7 @@ typedef struct // Sfizz related data sfizz_synth_t *synth; sfizz_client_t *client; + spin_mutex_t *synth_mutex; bool expect_nominal_block_length; char sfz_file_path[MAX_PATH_SIZE]; char scala_file_path[MAX_PATH_SIZE]; @@ -599,6 +602,7 @@ instantiate(const LV2_Descriptor *descriptor, self->synth = sfizz_create_synth(); self->client = sfizz_create_client(self); + self->synth_mutex = spin_mutex_create(); sfizz_set_broadcast_callback(self->synth, &sfizz_lv2_receive_message, self); sfizz_set_receive_callback(self->client, &sfizz_lv2_receive_message); @@ -617,6 +621,7 @@ static void cleanup(LV2_Handle instance) { sfizz_plugin_t *self = (sfizz_plugin_t *)instance; + spin_mutex_destroy(self->synth_mutex); sfizz_delete_client(self->client); sfizz_free(self->synth); free(self); @@ -876,8 +881,14 @@ static void run(LV2_Handle instance, uint32_t sample_count) { sfizz_plugin_t *self = (sfizz_plugin_t *)instance; - if (!self->control_port || !self->notify_port) + assert(self->control_port && self->notify_port); + + if (!spin_mutex_trylock(self->synth_mutex)) + { + for (int channel = 0; channel < 2; ++channel) + memset(self->output_buffers[channel], 0, sample_count * sizeof(float)); return; + } // Set up forge to write directly to notify output port. const size_t notify_capacity = self->notify_port->atom.size; @@ -1048,6 +1059,8 @@ run(LV2_Handle instance, uint32_t sample_count) // Render the block sfizz_render_block(self->synth, self->output_buffers, 2, (int)sample_count); + spin_mutex_unlock(self->synth_mutex); + if (self->midnam && atomic_exchange(&self->must_update_midnam, 0)) { self->midnam->update(self->midnam->handle); @@ -1099,7 +1112,9 @@ lv2_set_options(LV2_Handle instance, const LV2_Options_Option *options) if (opt->key == self->sample_rate_uri) { sfizz_lv2_parse_sample_rate(self, opt); + spin_mutex_lock(self->synth_mutex); sfizz_set_sample_rate(self->synth, self->sample_rate); + spin_mutex_unlock(self->synth_mutex); } else if (!self->expect_nominal_block_length && opt->key == self->max_block_length_uri) { @@ -1109,7 +1124,9 @@ lv2_set_options(LV2_Handle instance, const LV2_Options_Option *options) continue; } self->max_block_size = *(int *)opt->value; + spin_mutex_lock(self->synth_mutex); sfizz_set_samples_per_block(self->synth, self->max_block_size); + spin_mutex_unlock(self->synth_mutex); } else if (opt->key == self->nominal_block_length_uri) { @@ -1119,7 +1136,9 @@ lv2_set_options(LV2_Handle instance, const LV2_Options_Option *options) continue; } self->max_block_size = *(int *)opt->value; + spin_mutex_lock(self->synth_mutex); sfizz_set_samples_per_block(self->synth, self->max_block_size); + spin_mutex_unlock(self->synth_mutex); } } return LV2_OPTIONS_SUCCESS; @@ -1263,6 +1282,7 @@ restore(LV2_Handle instance, } // Sync the parameters to the synth + spin_mutex_lock(self->synth_mutex); // Load an empty file to remove the default sine, and then the new file. sfizz_load_string(self->synth, "empty.sfz", ""); @@ -1299,6 +1319,8 @@ restore(LV2_Handle instance, lv2_log_note(&self->logger, "[sfizz] Restoring the oversampling to %d\n", self->oversampling); sfizz_set_oversampling_factor(self->synth, self->oversampling); + spin_mutex_unlock(self->synth_mutex); + return status; } @@ -1419,7 +1441,12 @@ work(LV2_Handle instance, if (atom->type == self->sfizz_sfz_file_uri) { const char *sfz_file_path = LV2_ATOM_BODY_CONST(atom); - if (!sfizz_lv2_load_file(self, sfz_file_path)) { + + spin_mutex_lock(self->synth_mutex); + bool success = sfizz_lv2_load_file(self, sfz_file_path); + spin_mutex_unlock(self->synth_mutex); + + if (!success) { lv2_log_error(&self->logger, "[sfizz] Error with %s; no file should be loaded\n", sfz_file_path); } @@ -1430,7 +1457,12 @@ work(LV2_Handle instance, else if (atom->type == self->sfizz_scala_file_uri) { const char *scala_file_path = LV2_ATOM_BODY_CONST(atom); - if (sfizz_lv2_load_scala_file(self, scala_file_path)) { + + spin_mutex_lock(self->synth_mutex); + bool success = sfizz_lv2_load_scala_file(self, scala_file_path); + spin_mutex_unlock(self->synth_mutex); + + if (success) { lv2_log_note(&self->logger, "[sfizz] Scala file loaded: %s\n", scala_file_path); } else { lv2_log_error(&self->logger, @@ -1443,7 +1475,11 @@ work(LV2_Handle instance, else if (atom->type == self->sfizz_num_voices_uri) { const int num_voices = *(const int *)LV2_ATOM_BODY_CONST(atom); + + spin_mutex_lock(self->synth_mutex); sfizz_set_num_voices(self->synth, num_voices); + spin_mutex_unlock(self->synth_mutex); + if (sfizz_get_num_voices(self->synth) == num_voices) { lv2_log_note(&self->logger, "[sfizz] Number of voices changed to: %d\n", num_voices); } else { @@ -1453,7 +1489,11 @@ work(LV2_Handle instance, else if (atom->type == self->sfizz_preload_size_uri) { const unsigned int preload_size = *(const unsigned int *)LV2_ATOM_BODY_CONST(atom); + + spin_mutex_lock(self->synth_mutex); sfizz_set_preload_size(self->synth, preload_size); + spin_mutex_unlock(self->synth_mutex); + if (sfizz_get_preload_size(self->synth) == preload_size) { lv2_log_note(&self->logger, "[sfizz] Preload size changed to: %d\n", preload_size); } else { @@ -1464,7 +1504,11 @@ work(LV2_Handle instance, { const sfizz_oversampling_factor_t oversampling = *(const sfizz_oversampling_factor_t *)LV2_ATOM_BODY_CONST(atom); + + spin_mutex_lock(self->synth_mutex); sfizz_set_oversampling_factor(self->synth, oversampling); + spin_mutex_unlock(self->synth_mutex); + if (sfizz_get_oversampling_factor(self->synth) == oversampling) { lv2_log_note(&self->logger, "[sfizz] Oversampling changed to: %d\n", oversampling); } else { @@ -1482,7 +1526,12 @@ work(LV2_Handle instance, lv2_log_note(&self->logger, "[sfizz] File %s seems to have been updated, reloading\n", self->sfz_file_path); - if (!sfizz_lv2_load_file(self, self->sfz_file_path)) { + + spin_mutex_lock(self->synth_mutex); + bool success = sfizz_lv2_load_file(self, self->sfz_file_path); + spin_mutex_unlock(self->synth_mutex); + + if (!success) { lv2_log_error(&self->logger, "[sfizz] Error with %s; no file should be loaded\n", self->sfz_file_path); } @@ -1493,7 +1542,12 @@ work(LV2_Handle instance, lv2_log_note(&self->logger, "[sfizz] Scala file %s seems to have been updated, reloading\n", self->scala_file_path); - if (sfizz_lv2_load_scala_file(self, self->scala_file_path)) { + + spin_mutex_lock(self->synth_mutex); + bool success = sfizz_lv2_load_scala_file(self, self->scala_file_path); + spin_mutex_unlock(self->synth_mutex); + + if (success) { lv2_log_note(&self->logger, "[sfizz] Scala file loaded: %s\n", self->scala_file_path); } else { lv2_log_error(&self->logger, From e0a7fb1dbc7d4d07dce947a43686901dcfa1798a Mon Sep 17 00:00:00 2001 From: Jean Pierre Cimalando Date: Mon, 1 Feb 2021 22:51:24 +0100 Subject: [PATCH 5/8] Thread-safety at VST level --- vst/CMakeLists.txt | 3 ++- vst/SfizzVstProcessor.cpp | 15 ++++++++++----- vst/SfizzVstProcessor.h | 4 ++-- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/vst/CMakeLists.txt b/vst/CMakeLists.txt index 02afabef..a2c07724 100644 --- a/vst/CMakeLists.txt +++ b/vst/CMakeLists.txt @@ -58,8 +58,9 @@ if(WIN32) target_sources(${VSTPLUGIN_PRJ_NAME} PRIVATE vst3.def) endif() target_link_libraries(${VSTPLUGIN_PRJ_NAME} - PRIVATE ${PROJECT_NAME}::${PROJECT_NAME} + PRIVATE sfizz::sfizz PRIVATE sfizz::editor + PRIVATE sfizz::spin_mutex PRIVATE sfizz::pugixml sfizz::filesystem) target_include_directories(${VSTPLUGIN_PRJ_NAME} PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") diff --git a/vst/SfizzVstProcessor.cpp b/vst/SfizzVstProcessor.cpp index c77365da..6a22e52f 100644 --- a/vst/SfizzVstProcessor.cpp +++ b/vst/SfizzVstProcessor.cpp @@ -138,7 +138,7 @@ tresult PLUGIN_API SfizzVstProcessor::setState(IBStream* stream) } // - std::lock_guard lock(_processMutex); + std::lock_guard lock(_processMutex); _state = s; syncStateToSynth(); @@ -148,7 +148,7 @@ tresult PLUGIN_API SfizzVstProcessor::setState(IBStream* stream) tresult PLUGIN_API SfizzVstProcessor::getState(IBStream* stream) { - std::lock_guard lock(_processMutex); + std::lock_guard lock(_processMutex); return _state.store(stream); } @@ -224,7 +224,7 @@ tresult PLUGIN_API SfizzVstProcessor::process(Vst::ProcessData& data) for (unsigned c = 0; c < numChannels; ++c) outputs[c] = data.outputs[0].channelBuffers32[c]; - std::unique_lock lock(_processMutex, std::try_to_lock); + std::unique_lock lock(_processMutex, std::try_to_lock); if (!lock.owns_lock()) { for (unsigned c = 0; c < numChannels; ++c) @@ -515,7 +515,7 @@ tresult PLUGIN_API SfizzVstProcessor::notify(Vst::IMessage* message) if (result != kResultTrue) return result; - std::unique_lock lock(_processMutex); + std::unique_lock lock(_processMutex); _state.sfzFile.assign(static_cast(data), size); loadSfzFileOrDefault(*_synth, _state.sfzFile); lock.unlock(); @@ -533,7 +533,7 @@ tresult PLUGIN_API SfizzVstProcessor::notify(Vst::IMessage* message) if (result != kResultTrue) return result; - std::unique_lock lock(_processMutex); + std::unique_lock lock(_processMutex); _state.scalaFile.assign(static_cast(data), size); _synth->loadScalaFile(_state.scalaFile); lock.unlock(); @@ -601,23 +601,28 @@ void SfizzVstProcessor::doBackgroundWork() if (!std::strcmp(id, "SetNumVoices")) { int32 value = *msg->payload(); + std::lock_guard lock(_processMutex); _synth->setNumVoices(value); } else if (!std::strcmp(id, "SetOversampling")) { int32 value = *msg->payload(); + std::lock_guard lock(_processMutex); _synth->setOversamplingFactor(1 << value); } else if (!std::strcmp(id, "SetPreloadSize")) { int32 value = *msg->payload(); + std::lock_guard lock(_processMutex); _synth->setPreloadSize(value); } else if (!std::strcmp(id, "CheckShouldReload")) { if (_synth->shouldReloadFile()) { fprintf(stderr, "[Sfizz] sfz file has changed, reloading\n"); + std::lock_guard lock(_processMutex); loadSfzFileOrDefault(*_synth, _state.sfzFile); } else if (_synth->shouldReloadScala()) { fprintf(stderr, "[Sfizz] scala file has changed, reloading\n"); + std::lock_guard lock(_processMutex); _synth->loadScalaFile(_state.scalaFile); } } diff --git a/vst/SfizzVstProcessor.h b/vst/SfizzVstProcessor.h index bbbf7490..e8408169 100644 --- a/vst/SfizzVstProcessor.h +++ b/vst/SfizzVstProcessor.h @@ -10,8 +10,8 @@ #include "ring_buffer/ring_buffer.h" #include "public.sdk/source/vst/vstaudioeffect.h" #include +#include #include -#include #include #include @@ -65,7 +65,7 @@ private: Ring_Buffer _fifoToWorker; RTSemaphore _semaToWorker; Ring_Buffer _fifoMessageFromUi; - std::mutex _processMutex; + SpinMutex _processMutex; // file modification periodic checker uint32 _fileChangeCounter = 0; From 62ec01a3620877fcb5e2225e6c6d256aa5656ede Mon Sep 17 00:00:00 2001 From: Jean Pierre Cimalando Date: Mon, 1 Feb 2021 23:12:29 +0100 Subject: [PATCH 6/8] Thread-safety for the JACK client --- clients/CMakeLists.txt | 2 +- clients/jack_client.cpp | 19 ++++++++++++++++--- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/clients/CMakeLists.txt b/clients/CMakeLists.txt index a48af11a..367acc04 100644 --- a/clients/CMakeLists.txt +++ b/clients/CMakeLists.txt @@ -1,6 +1,6 @@ if(SFIZZ_JACK) add_executable(sfizz_jack MidiHelpers.h jack_client.cpp) - target_link_libraries(sfizz_jack PRIVATE sfizz::sfizz sfizz::jack absl::flags_parse) + target_link_libraries(sfizz_jack PRIVATE sfizz::sfizz sfizz::jack sfizz::spin_mutex absl::flags_parse) sfizz_enable_lto_if_needed(sfizz_jack) install(TARGETS sfizz_jack DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT "jack" OPTIONAL) diff --git a/clients/jack_client.cpp b/clients/jack_client.cpp index b9e5f5dd..46fff6b2 100644 --- a/clients/jack_client.cpp +++ b/clients/jack_client.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -38,11 +39,14 @@ #include #include #include +#include +#include static jack_port_t* midiInputPort; static jack_port_t* outputPort1; static jack_port_t* outputPort2; static jack_client_t* client; +static SpinMutex processMutex; int process(jack_nframes_t numFrames, void* arg) { @@ -51,6 +55,16 @@ int process(jack_nframes_t numFrames, void* arg) auto* buffer = jack_port_get_buffer(midiInputPort, numFrames); assert(buffer); + auto* leftOutput = reinterpret_cast(jack_port_get_buffer(outputPort1, numFrames)); + auto* rightOutput = reinterpret_cast(jack_port_get_buffer(outputPort2, numFrames)); + + std::unique_lock lock { processMutex, std::try_to_lock }; + if (!lock.owns_lock()) { + std::fill_n(leftOutput, numFrames, 0.0f); + std::fill_n(rightOutput, numFrames, 0.0f); + return 0; + } + auto numMidiEvents = jack_midi_get_event_count(buffer); jack_midi_event_t event; @@ -96,9 +110,6 @@ int process(jack_nframes_t numFrames, void* arg) } } - auto* leftOutput = reinterpret_cast(jack_port_get_buffer(outputPort1, numFrames)); - auto* rightOutput = reinterpret_cast(jack_port_get_buffer(outputPort2, numFrames)); - float* stereoOutput[] = { leftOutput, rightOutput }; synth->renderBlock(stereoOutput, numFrames); @@ -112,6 +123,7 @@ int sampleBlockChanged(jack_nframes_t nframes, void* arg) auto* synth = reinterpret_cast(arg); // DBG("Sample per block changed to " << nframes); + std::lock_guard lock { processMutex }; synth->setSamplesPerBlock(nframes); return 0; } @@ -123,6 +135,7 @@ int sampleRateChanged(jack_nframes_t nframes, void* arg) auto* synth = reinterpret_cast(arg); // DBG("Sample rate changed to " << nframes); + std::lock_guard lock { processMutex }; synth->setSampleRate(nframes); return 0; } From 3fea4ba0e5a6cd2a30455e0dce2b59711dca5afe Mon Sep 17 00:00:00 2001 From: Jean Pierre Cimalando Date: Tue, 2 Feb 2021 00:28:08 +0100 Subject: [PATCH 7/8] Fix AudioUnit with spin mutex --- vst/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/vst/CMakeLists.txt b/vst/CMakeLists.txt index a2c07724..cc73ce59 100644 --- a/vst/CMakeLists.txt +++ b/vst/CMakeLists.txt @@ -199,6 +199,7 @@ elseif(SFIZZ_AU) target_link_libraries(${AUPLUGIN_PRJ_NAME} PRIVATE ${PROJECT_NAME}::${PROJECT_NAME} PRIVATE sfizz::editor + PRIVATE sfizz::spin_mutex PRIVATE sfizz::pugixml sfizz::filesystem) target_include_directories(${AUPLUGIN_PRJ_NAME} PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") From cb91698144af1bcdd5847ad2522987f86939e653 Mon Sep 17 00:00:00 2001 From: Jean Pierre Cimalando Date: Tue, 2 Feb 2021 15:46:11 +0100 Subject: [PATCH 8/8] Update doc with thread-safety constraints --- src/sfizz.h | 160 +++++++++++++++++++++++++++++++++++++---- src/sfizz.hpp | 195 +++++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 325 insertions(+), 30 deletions(-) diff --git a/src/sfizz.h b/src/sfizz.h index 5deaea5f..343d73a0 100644 --- a/src/sfizz.h +++ b/src/sfizz.h @@ -5,9 +5,28 @@ // If not, contact the sfizz maintainers at https://github.com/sfztools/sfizz /** - @file - @brief sfizz public C API. -*/ + * @file + * @brief sfizz public C API. + * + * sfizz is a synthesizer for SFZ instruments. + * + * The synthesizer must be operated under indicated constraints in order to + * guarantee thread-safety. + * + * At any given time, no more than 2 tasks must interact in parallel with this + * library: + * - a processing tasks @b RT for audio and MIDI, which can be real-time + * - a Control tasks @b CT + * + * The tasks RT and CT can be assumed by different threads over the lifetime, as + * long as the switch is adequately synchronized. If real-time processing is not + * required, it's acceptable for the 2 tasks can be assumed by a single thread. + * + * Where one or more following items are indicated on a function, the constraints apply. + * - @b RT: the function must be invoked from the Real-time thread + * - @b CT: the function must be invoked from the Control thread + * - @b OFF: the function cannot be invoked while a thread is calling @b RT functions + */ #pragma once #include "sfizz_message.h" @@ -84,6 +103,10 @@ SFIZZ_EXPORTED_API void sfizz_free(sfizz_synth_t* synth); * * @return @true when file loading went OK, * @false if some error occured while loading. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread + * - @b OFF: the function cannot be invoked while a thread is calling @b RT functions */ SFIZZ_EXPORTED_API bool sfizz_load_file(sfizz_synth_t* synth, const char* path); @@ -101,6 +124,10 @@ SFIZZ_EXPORTED_API bool sfizz_load_file(sfizz_synth_t* synth, const char* path); * * @return @true when file loading went OK, * @false if some error occured while loading. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread + * - @b OFF: the function cannot be invoked while a thread is calling @b RT functions */ SFIZZ_EXPORTED_API bool sfizz_load_string(sfizz_synth_t* synth, const char* path, const char* text); @@ -113,6 +140,10 @@ SFIZZ_EXPORTED_API bool sfizz_load_string(sfizz_synth_t* synth, const char* path * * @return @true when tuning scale loaded OK, * @false if some error occurred. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread + * - @b OFF: the function cannot be invoked while a thread is calling @b RT functions */ SFIZZ_EXPORTED_API bool sfizz_load_scala_file(sfizz_synth_t* synth, const char* path); @@ -125,6 +156,10 @@ SFIZZ_EXPORTED_API bool sfizz_load_scala_file(sfizz_synth_t* synth, const char* * * @return @true when tuning scale loaded OK, * @false if some error occurred. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread + * - @b OFF: the function cannot be invoked while a thread is calling @b RT functions */ SFIZZ_EXPORTED_API bool sfizz_load_scala_string(sfizz_synth_t* synth, const char* text); @@ -134,6 +169,9 @@ SFIZZ_EXPORTED_API bool sfizz_load_scala_string(sfizz_synth_t* synth, const char * * @param synth The synth. * @param root_key The MIDI number of the Scala root key (default 60 for C4). + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_set_scala_root_key(sfizz_synth_t* synth, int root_key); @@ -153,6 +191,9 @@ SFIZZ_EXPORTED_API int sfizz_get_scala_root_key(sfizz_synth_t* synth); * * @param synth The synth. * @param frequency The frequency which indicates where standard tuning A4 is (default 440 Hz). + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_set_tuning_frequency(sfizz_synth_t* synth, float frequency); @@ -174,6 +215,9 @@ SFIZZ_EXPORTED_API float sfizz_get_tuning_frequency(sfizz_synth_t* synth); * * @param synth The synth. * @param ratio The parameter in domain 0-1. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_load_stretch_tuning_by_ratio(sfizz_synth_t* synth, float ratio); @@ -249,6 +293,10 @@ SFIZZ_EXPORTED_API int sfizz_get_num_active_voices(sfizz_synth_t* synth); * * @param synth The synth. * @param samples_per_block The number of samples per block. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread + * - @b OFF: the function cannot be invoked while a thread is calling @b RT functions */ SFIZZ_EXPORTED_API void sfizz_set_samples_per_block(sfizz_synth_t* synth, int samples_per_block); @@ -260,6 +308,10 @@ SFIZZ_EXPORTED_API void sfizz_set_samples_per_block(sfizz_synth_t* synth, int sa * * @param synth The synth * @param sample_rate The sample rate. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread + * - @b OFF: the function cannot be invoked while a thread is calling @b RT functions */ SFIZZ_EXPORTED_API void sfizz_set_sample_rate(sfizz_synth_t* synth, float sample_rate); @@ -274,6 +326,9 @@ SFIZZ_EXPORTED_API void sfizz_set_sample_rate(sfizz_synth_t* synth, float sample * @param delay The delay of the event in the block, in samples. * @param note_number The MIDI note number. * @param velocity The MIDI velocity. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_send_note_on(sfizz_synth_t* synth, int delay, int note_number, char velocity); @@ -290,6 +345,9 @@ SFIZZ_EXPORTED_API void sfizz_send_note_on(sfizz_synth_t* synth, int delay, int * @param delay The delay of the event in the block, in samples. * @param note_number The MIDI note number. * @param velocity The MIDI velocity. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_send_note_off(sfizz_synth_t* synth, int delay, int note_number, char velocity); @@ -304,6 +362,9 @@ SFIZZ_EXPORTED_API void sfizz_send_note_off(sfizz_synth_t* synth, int delay, int * @param delay The delay of the event in the block, in samples. * @param cc_number The MIDI CC number. * @param cc_value The MIDI CC value. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_send_cc(sfizz_synth_t* synth, int delay, int cc_number, char cc_value); @@ -318,6 +379,9 @@ SFIZZ_EXPORTED_API void sfizz_send_cc(sfizz_synth_t* synth, int delay, int cc_nu * @param delay The delay of the event in the block, in samples. * @param cc_number The MIDI CC number. * @param norm_value The normalized CC value, in domain 0 to 1. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_send_hdcc(sfizz_synth_t* synth, int delay, int cc_number, float norm_value); @@ -335,6 +399,9 @@ SFIZZ_EXPORTED_API void sfizz_send_hdcc(sfizz_synth_t* synth, int delay, int cc_ * @param delay The delay of the event in the block, in samples. * @param cc_number The MIDI CC number. * @param norm_value The normalized CC value, in domain 0 to 1. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_automate_hdcc(sfizz_synth_t* synth, int delay, int cc_number, float norm_value); @@ -348,6 +415,9 @@ SFIZZ_EXPORTED_API void sfizz_automate_hdcc(sfizz_synth_t* synth, int delay, int * @param synth The synth. * @param delay The delay. * @param pitch The pitch. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_send_pitch_wheel(sfizz_synth_t* synth, int delay, int pitch); @@ -357,8 +427,11 @@ SFIZZ_EXPORTED_API void sfizz_send_pitch_wheel(sfizz_synth_t* synth, int delay, * * @param synth The synth. * @param delay The delay at which the event occurs; this should be lower - * than the size of the block in the next call to renderBlock(). + * than the size of the block in the next call to renderBlock(). * @param aftertouch The aftertouch value. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_send_aftertouch(sfizz_synth_t* synth, int delay, char aftertouch); @@ -369,6 +442,9 @@ SFIZZ_EXPORTED_API void sfizz_send_aftertouch(sfizz_synth_t* synth, int delay, c * @param synth The synth. * @param delay The delay. * @param seconds_per_beat The seconds per beat. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_send_tempo(sfizz_synth_t* synth, int delay, float seconds_per_beat); @@ -380,6 +456,9 @@ SFIZZ_EXPORTED_API void sfizz_send_tempo(sfizz_synth_t* synth, int delay, float * @param delay The delay. * @param beats_per_bar The number of beats per bar, or time signature numerator. * @param beat_unit The note corresponding to one beat, or time signature denominator. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_send_time_signature(sfizz_synth_t* synth, int delay, int beats_per_bar, int beat_unit); @@ -391,6 +470,9 @@ SFIZZ_EXPORTED_API void sfizz_send_time_signature(sfizz_synth_t* synth, int dela * @param delay The delay. * @param bar The current bar. * @param bar_beat The fractional position of the current beat within the bar. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_send_time_position(sfizz_synth_t* synth, int delay, int bar, double bar_beat); @@ -401,6 +483,9 @@ SFIZZ_EXPORTED_API void sfizz_send_time_position(sfizz_synth_t* synth, int delay * @param synth The synth. * @param delay The delay. * @param playback_state The playback state, 1 if playing, 0 if stopped. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_send_playback_state(sfizz_synth_t* synth, int delay, int playback_state); @@ -419,6 +504,9 @@ SFIZZ_EXPORTED_API void sfizz_send_playback_state(sfizz_synth_t* synth, int dela * @param num_channels Should be equal to 2 for the time being. * @param num_frames Number of frames to fill. This should be less than * or equal to the expected samples_per_block. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_render_block(sfizz_synth_t* synth, float** channels, int num_channels, int num_frames); @@ -443,6 +531,10 @@ SFIZZ_EXPORTED_API unsigned int sfizz_get_preload_size(sfizz_synth_t* synth); * * @param synth The synth. * @param[in] preload_size The preload size. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread + * - @b OFF: the function cannot be invoked while a thread is calling @b RT functions */ SFIZZ_EXPORTED_API void sfizz_set_preload_size(sfizz_synth_t* synth, unsigned int preload_size); @@ -471,16 +563,16 @@ SFIZZ_EXPORTED_API sfizz_oversampling_factor_t sfizz_get_oversampling_factor(sfi * the loading speed. You can tweak the size of the preloaded data to compensate * for the memory increase, but the full loading will need to take place anyway. * - * This function takes a lock and disables the callback; prefer calling it out - * of the RT thread. It can also take a long time to return. - * If the new oversampling factor is the same as the current one, it will - * release the lock immediately and exit. * @since 0.2.0 * * @param synth The synth. * @param[in] oversampling The oversampling factor. * * @return @true if the oversampling factor was correct, @false otherwise. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread + * - @b OFF: the function cannot be invoked while a thread is calling @b RT functions */ SFIZZ_EXPORTED_API bool sfizz_set_oversampling_factor(sfizz_synth_t* synth, sfizz_oversampling_factor_t oversampling); @@ -512,6 +604,9 @@ SFIZZ_EXPORTED_API int sfizz_get_sample_quality(sfizz_synth_t* synth, sfizz_proc * @param synth The synth. * @param[in] mode The processing mode. * @param[in] quality The desired sample quality, in the range 1 to 10. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_set_sample_quality(sfizz_synth_t* synth, sfizz_process_mode_t mode, int quality); @@ -521,6 +616,9 @@ SFIZZ_EXPORTED_API void sfizz_set_sample_quality(sfizz_synth_t* synth, sfizz_pro * * @param synth The synth. * @param volume The new volume. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_set_volume(sfizz_synth_t* synth, float volume); @@ -535,14 +633,14 @@ SFIZZ_EXPORTED_API float sfizz_get_volume(sfizz_synth_t* synth); /** * @brief Set the number of voices used by the synth. * - * This function takes a lock and disables the callback; prefer calling - * it out of the RT thread. It can also take a long time to return. - * If the new number of voices is the same as the current one, it will - * release the lock immediately and exit. * @since 0.2.0 * * @param synth The synth. * @param num_voices The number of voices. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread + * - @b OFF: the function cannot be invoked while a thread is calling @b RT functions */ SFIZZ_EXPORTED_API void sfizz_set_num_voices(sfizz_synth_t* synth, int num_voices); @@ -578,6 +676,9 @@ SFIZZ_EXPORTED_API int sfizz_get_num_bytes(sfizz_synth_t* synth); * @since 0.2.0 * * @param synth The synth. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_enable_freewheeling(sfizz_synth_t* synth); @@ -586,6 +687,9 @@ SFIZZ_EXPORTED_API void sfizz_enable_freewheeling(sfizz_synth_t* synth); * @since 0.2.0 * * @param synth The synth. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_disable_freewheeling(sfizz_synth_t* synth); @@ -609,7 +713,10 @@ SFIZZ_EXPORTED_API char* sfizz_get_unknown_opcodes(sfizz_synth_t* synth); * @param synth The synth. * * @return @true if any included files (including the root file) - have been modified since the sfz file was loaded, @false otherwise. + * have been modified since the sfz file was loaded, @false otherwise. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread */ SFIZZ_EXPORTED_API bool sfizz_should_reload_file(sfizz_synth_t* synth); @@ -622,6 +729,9 @@ SFIZZ_EXPORTED_API bool sfizz_should_reload_file(sfizz_synth_t* synth); * @param synth The synth. * * @return @true if the scala file has been modified since loading. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread */ SFIZZ_EXPORTED_API bool sfizz_should_reload_scala(sfizz_synth_t* synth); @@ -632,6 +742,9 @@ SFIZZ_EXPORTED_API bool sfizz_should_reload_scala(sfizz_synth_t* synth); * @note This can produce many outputs so use with caution. * * @param synth The synth. + * + * @par Thread-safety constraints + * - TBD ? */ SFIZZ_EXPORTED_API void sfizz_enable_logging(sfizz_synth_t* synth); @@ -640,6 +753,9 @@ SFIZZ_EXPORTED_API void sfizz_enable_logging(sfizz_synth_t* synth); * @since 0.3.0 * * @param synth The synth. + * + * @par Thread-safety constraints + * - TBD ? */ SFIZZ_EXPORTED_API void sfizz_disable_logging(sfizz_synth_t* synth); @@ -651,6 +767,9 @@ SFIZZ_EXPORTED_API void sfizz_disable_logging(sfizz_synth_t* synth); * * @param synth The synth. * @param prefix The prefix. + * + * @par Thread-safety constraints + * - TBD ? */ SFIZZ_EXPORTED_API void sfizz_set_logging_prefix(sfizz_synth_t* synth, const char* prefix); @@ -659,6 +778,9 @@ SFIZZ_EXPORTED_API void sfizz_set_logging_prefix(sfizz_synth_t* synth, const cha * @since 0.3.2 * * @param synth The synth. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_all_sound_off(sfizz_synth_t* synth); @@ -672,6 +794,9 @@ SFIZZ_EXPORTED_API void sfizz_all_sound_off(sfizz_synth_t* synth); * @param synth The synth. * @param id The definition variable name. * @param value The definition value. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread */ SFIZZ_EXPORTED_API void sfizz_add_external_definitions(sfizz_synth_t* synth, const char* id, const char* value); @@ -680,6 +805,9 @@ SFIZZ_EXPORTED_API void sfizz_add_external_definitions(sfizz_synth_t* synth, con * @since 0.4.0 * * @param synth The synth. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread */ SFIZZ_EXPORTED_API void sfizz_clear_external_definitions(sfizz_synth_t* synth); @@ -805,6 +933,9 @@ SFIZZ_EXPORTED_API void sfizz_set_receive_callback(sfizz_client_t* client, sfizz * @param path The OSC address pattern. * @param sig The OSC type tag string. * @param args The OSC arguments, whose number and format is determined the type tag string. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_send_message(sfizz_synth_t* synth, sfizz_client_t* client, int delay, const char* path, const char* sig, const sfizz_arg_t* args); @@ -815,6 +946,9 @@ SFIZZ_EXPORTED_API void sfizz_send_message(sfizz_synth_t* synth, sfizz_client_t* * @param synth The synth. * @param broadcast The pointer to the receiving function. * @param data The opaque data pointer which is passed to the receiver. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ SFIZZ_EXPORTED_API void sfizz_set_broadcast_callback(sfizz_synth_t* synth, sfizz_receive_t* broadcast, void* data); diff --git a/src/sfizz.hpp b/src/sfizz.hpp index e6b34daf..dfef34f1 100644 --- a/src/sfizz.hpp +++ b/src/sfizz.hpp @@ -31,8 +31,25 @@ namespace sfz class Synth; class Client; /** - * @brief Main class. - */ + * @brief Synthesizer for SFZ instruments +* +* The synthesizer must be operated under indicated constraints in order to +* guarantee thread-safety. +* +* At any given time, no more than 2 tasks must interact in parallel with this +* library: +* - a processing tasks @b RT for audio and MIDI, which can be real-time +* - a Control tasks @b CT +* +* The tasks RT and CT can be assumed by different threads over the lifetime, as +* long as the switch is adequately synchronized. If real-time processing is not +* required, it's acceptable for the 2 tasks can be assumed by a single thread. +* +* Where one or more following items are indicated on a function, the constraints apply. +* - @b RT: the function must be invoked from the Real-time thread +* - @b CT: the function must be invoked from the Control thread +* - @b OFF: the function cannot be invoked while a thread is calling @b RT functions +*/ class SFIZZ_EXPORTED_API Sfizz { public: @@ -57,15 +74,16 @@ public: /** * @brief Empties the current regions and load a new SFZ file into the synth. * - * This function will disable all callbacks so it is safe to call from a - * UI thread for example, although it may generate a click. However it is - * not reentrant, so you should not call it from concurrent threads. * @since 0.2.0 * * @param path The path to the file to load, as string. * * @return @false if the file was not found or no regions were loaded, * @true otherwise. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread + * - @b OFF: the function cannot be invoked while a thread is calling @b RT functions */ bool loadSfzFile(const std::string& path); @@ -76,6 +94,7 @@ public: * This accepts a virtual path name for the imaginary sfz file, which is not * required to exist on disk. The purpose of the virtual path is to locate * samples with relative paths. + * * @since 0.4.0 * * @param path The virtual path of the SFZ file, as string. @@ -83,36 +102,54 @@ public: * * @return @false if no regions were loaded, * @true otherwise. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread + * - @b OFF: the function cannot be invoked while a thread is calling @b RT functions */ bool loadSfzString(const std::string& path, const std::string& text); /** * @brief Sets the tuning from a Scala file loaded from the file system. + * * @since 0.4.0 * * @param path The path to the file in Scala format. * * @return @true when tuning scale loaded OK, * @false if some error occurred. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread + * - @b OFF: the function cannot be invoked while a thread is calling @b RT functions */ bool loadScalaFile(const std::string& path); /** * @brief Sets the tuning from a Scala file loaded from memory. + * * @since 0.4.0 * * @param text The contents of the file in Scala format. * * @return @true when tuning scale loaded OK, * @false if some error occurred. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread + * - @b OFF: the function cannot be invoked while a thread is calling @b RT functions */ bool loadScalaString(const std::string& text); /** * @brief Sets the scala root key. + * * @since 0.4.0 * * @param rootKey The MIDI number of the Scala root key (default 60 for C4). + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void setScalaRootKey(int rootKey); @@ -126,9 +163,13 @@ public: /** * @brief Sets the reference tuning frequency. + * * @since 0.4.0 * * @param frequency The frequency which indicates where standard tuning A4 is (default 440 Hz). + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void setTuningFrequency(float frequency); @@ -144,9 +185,13 @@ public: * @brief Configure stretch tuning using a predefined parametric Railsback curve. * * A ratio 1/2 is supposed to match the average piano; 0 disables (the default). + * * @since 0.4.0 * * @param ratio The parameter in domain 0-1. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void loadStretchTuningByRatio(float ratio); @@ -191,9 +236,14 @@ public: * * The actual size can be lower in each callback but should not be larger * than this value. + * * @since 0.2.0 * * @param samplesPerBlock The number of samples per block. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread + * - @b OFF: the function cannot be invoked while a thread is calling @b RT functions */ void setSamplesPerBlock(int samplesPerBlock) noexcept; @@ -201,9 +251,14 @@ public: * @brief Set the sample rate. * * If you do not call it it is initialized to `sfz::config::defaultSampleRate`. + * * @since 0.2.0 * * @param sampleRate The sample rate. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread + * - @b OFF: the function cannot be invoked while a thread is calling @b RT functions */ void setSampleRate(float sampleRate) noexcept; @@ -229,10 +284,14 @@ public: * does not use the opcode `sample_quality`. The engine uses distinct * default quality settings for live mode and freewheeling mode, * which both can be accessed by the means of this function. + * * @since 0.4.0 * * @param[in] mode The processing mode. * @param[in] quality The desired sample quality, in the range 1 to 10. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void setSampleQuality(ProcessMode mode, int quality); @@ -246,53 +305,73 @@ public: * @brief Set the value for the volume. * * This value will be clamped within `sfz::default::volumeRange`. + * * @since 0.2.0 * * @param volume The new volume. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void setVolume(float volume) noexcept; /** * @brief Send a note on event to the synth. + * * @since 0.2.0 * * @param delay the delay at which the event occurs; this should be lower * than the size of the block in the next call to renderBlock(). * @param noteNumber the midi note number. * @param velocity the midi note velocity. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void noteOn(int delay, int noteNumber, uint8_t velocity) noexcept; /** * @brief Send a note off event to the synth. + * * @since 0.2.0 * * @param delay the delay at which the event occurs; this should be lower * than the size of the block in the next call to renderBlock(). * @param noteNumber the midi note number. * @param velocity the midi note velocity. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void noteOff(int delay, int noteNumber, uint8_t velocity) noexcept; /** * @brief Send a CC event to the synth + * * @since 0.2.0 * * @param delay the delay at which the event occurs; this should be lower * than the size of the block in the next call to renderBlock(). * @param ccNumber the cc number. * @param ccValue the cc value. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void cc(int delay, int ccNumber, uint8_t ccValue) noexcept; /** * @brief Send a high precision CC event to the synth + * * @since 0.4.0 * * @param delay the delay at which the event occurs; this should be lower * than the size of the block in the next call to renderBlock(). * @param ccNumber the cc number. * @param normValue the normalized cc value, in domain 0 to 1. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void hdcc(int delay, int ccNumber, float normValue) noexcept; @@ -308,65 +387,92 @@ public: * than the size of the block in the next call to renderBlock(). * @param ccNumber the cc number. * @param normValue the normalized cc value, in domain 0 to 1. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void automateHdcc(int delay, int ccNumber, float normValue) noexcept; /** * @brief Send a pitch bend event to the synth + * * @since 0.2.0 * * @param delay the delay at which the event occurs; this should be lower * than the size of the block in the next call to renderBlock(). * @param pitch the pitch value centered between -8192 and 8192. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void pitchWheel(int delay, int pitch) noexcept; /** * @brief Send a aftertouch event to the synth. (CURRENTLY UNIMPLEMENTED) + * * @since 0.2.0 * * @param delay the delay at which the event occurs; this should be lower * than the size of the block in the next call to renderBlock(). * @param aftertouch the aftertouch value. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void aftertouch(int delay, uint8_t aftertouch) noexcept; /** * @brief Send a tempo event to the synth. + * * @since 0.2.0 * * @param delay the delay at which the event occurs; this should be lower * than the size of the block in the next call to renderBlock(). * @param secondsPerBeat the new period of the beat. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void tempo(int delay, float secondsPerBeat) noexcept; /** * @brief Send the time signature. + * * @since 0.5.0 * * @param delay The delay. * @param beatsPerBar The number of beats per bar, or time signature numerator. * @param beatUnit The note corresponding to one beat, or time signature denominator. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void timeSignature(int delay, int beatsPerBar, int beatUnit); /** * @brief Send the time position. + * * @since 0.5.0 * * @param delay The delay. * @param bar The current bar. * @param barBeat The fractional position of the current beat within the bar. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void timePosition(int delay, int bar, double barBeat); /** * @brief Send the playback state. + * * @since 0.5.0 * * @param delay The delay. * @param playbackState The playback state, 1 if playing, 0 if stopped. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void playbackState(int delay, int playbackState); @@ -375,11 +481,15 @@ public: * * This call will reset the synth in its waiting state for the next batch * of events. The buffers must be float[numSamples][numOutputs * 2]. + * * @since 0.2.0 * * @param buffers the buffers to write the next block into. * @param numFrames the number of stereo frames in the block. * @param numOutputs the number of stereo outputs. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void renderBlock(float** buffers, size_t numFrames, int numOutputs = 1) noexcept; @@ -398,13 +508,13 @@ public: /** * @brief Change the number of voices (the polyphony). * - * This function takes a lock and disables the callback; prefer calling - * it out of the RT thread. It can also take a long time to return. - * If the new number of voices is the same as the current one, it will - * release the lock immediately and exit. * @since 0.2.0 * * @param numVoices The number of voices. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread + * - @b OFF: the function cannot be invoked while a thread is calling @b RT functions */ void setNumVoices(int numVoices) noexcept; @@ -424,15 +534,15 @@ public: * to compensate for the memory increase, but the full loading will * need to take place anyway. * - * This function takes a lock and disables the callback; prefer calling - * it out of the RT thread. It can also take a long time to return. - * If the new oversampling factor is the same as the current one, it will - * release the lock immediately and exit. * @since 0.2.0 * * @param factor The oversampling factor. * * @return @true if the factor did indeed change, @false otherwise. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread + * - @b OFF: the function cannot be invoked while a thread is calling @b RT functions */ bool setOversamplingFactor(int factor) noexcept; @@ -445,13 +555,13 @@ public: /** * @brief Set the preloaded file size. * - * This function takes a lock and disables the callback; prefer calling - * it out of the RT thread. It can also take a long time to return. - * If the new preload size is the same as the current one, it will - * release the lock immediately and exit. * @since 0.2.0 * * @param preloadSize The preload size. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread + * - @b OFF: the function cannot be invoked while a thread is calling @b RT functions */ void setPreloadSize(uint32_t preloadSize) noexcept; @@ -478,7 +588,11 @@ public: * * This will wait for background loaded files to finish loading * before each render callback to ensure that there will be no dropouts. + * * @since 0.2.0 + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void enableFreeWheeling() noexcept; @@ -487,7 +601,11 @@ public: * * You should disable freewheeling before live use of the plugin * otherwise the audio thread will lock. + * * @since 0.2.0 + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void disableFreeWheeling() noexcept; @@ -495,10 +613,14 @@ public: * @brief Check if the SFZ should be reloaded. * * Depending on the platform this can create file descriptors. + * * @since 0.2.0 * * @return @true if any included files (including the root file) have * been modified since the sfz file was loaded, @false otherwise. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread */ bool shouldReloadFile(); @@ -506,9 +628,13 @@ public: * @brief Check if the tuning (scala) file should be reloaded. * * Depending on the platform this can create file descriptors. + * * @since 0.4.0 * * @return @true if a scala file has been loaded and has changed, @false otherwise. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread */ bool shouldReloadScala(); @@ -519,41 +645,61 @@ public: * @note This can produce many outputs so use with caution. * * @param prefix the file prefix to use for logging. + * + * @par Thread-safety constraints + * - TBD ? */ void enableLogging() noexcept; /** * @brief Enable logging of timings to sidecar CSV files. + * * @since 0.3.2 * * @note This can produce many outputs so use with caution. * * @param prefix the file prefix to use for logging. + * + * @par Thread-safety constraints + * - TBD ? */ void enableLogging(const std::string& prefix) noexcept; /** * @brief Set the logging prefix. + * * @since 0.3.2 * * @param prefix + * + * @par Thread-safety constraints + * - TBD ? */ void setLoggingPrefix(const std::string& prefix) noexcept; /** * @brief Disable logging of timings to sidecar CSV files. + * * @since 0.3.0 + * + * @par Thread-safety constraints + * - TBD ? */ void disableLogging() noexcept; /** * @brief Shuts down the current processing, clear buffers and reset the voices. + * * @since 0.3.2 + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void allSoundOff() noexcept; /** * @brief Add external definitions prior to loading. + * * @since 0.4.0 * * @note These do not get reset by loading or resetting the synth. @@ -561,12 +707,19 @@ public: * * @param id The definition variable name. * @param value The definition value. + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread */ void addExternalDefinition(const std::string& id, const std::string& value); /** * @brief Clears external definitions for the next file loading. + * * @since 0.4.0 + * + * @par Thread-safety constraints + * - @b CT: the function must be invoked from the Control thread */ void clearExternalDefinitions(); @@ -624,6 +777,7 @@ public: /** * @brief Send a message to the synth engine + * * @since 0.6.0 * * @param client The client sending the message. @@ -631,15 +785,22 @@ public: * @param path The OSC address pattern. * @param sig The OSC type tag string. * @param args The OSC arguments, whose number and format is determined the type tag string. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void sendMessage(Client& client, int delay, const char* path, const char* sig, const sfizz_arg_t* args); /** * @brief Set the function which receives broadcast messages from the synth engine. + * * @since 0.6.0 * * @param broadcast The pointer to the receiving function. * @param data The opaque data pointer which is passed to the receiver. + * + * @par Thread-safety constraints + * - @b RT: the function must be invoked from the Real-time thread */ void setBroadcastCallback(sfizz_receive_t* broadcast, void* data);