diff --git a/src/sfizz/ADSREnvelope.h b/src/sfizz/ADSREnvelope.h index f9cf9ec2..20733032 100644 --- a/src/sfizz/ADSREnvelope.h +++ b/src/sfizz/ADSREnvelope.h @@ -25,15 +25,55 @@ #include "LeakDetector.h" #include namespace sfz { - +/** + * @brief Describe an attack/delay/sustain/release envelope that can + * produce its coefficient in a blockwise manner for SIMD-type operations. + * + * @tparam Type the underlying type + */ template class ADSREnvelope { public: ADSREnvelope() = default; + /** + * @brief Resets the ADSR envelope. There's alot of parameter but what can you do. + * They all match the SFZ specification. + * + * @param attack + * @param release + * @param sustain + * @param delay + * @param decay + * @param hold + * @param start + * @param depth + */ void reset(int attack, int release, Type sustain = 1.0, int delay = 0, int decay = 0, int hold = 0, Type start = 0.0, Type depth = 1) noexcept; + /** + * @brief Get the next value for the envelope + * + * @return Type + */ Type getNextValue() noexcept; + /** + * @brief Get a block of values for the envelope. This method tries hard to be efficient + * and hopefully it is. + * + * @param output + */ void getBlock(absl::Span output) noexcept; + /** + * @brief Start the envelope release after a delay. + * + * @param releaseDelay the delay before releasing in samples + */ void startRelease(int releaseDelay) noexcept; + /** + * @brief Is the envelope smoothing? + * + * @return true + * @return false + */ bool isSmoothing() noexcept; private: @@ -62,4 +102,4 @@ private: LEAK_DETECTOR(ADSREnvelope); }; -} \ No newline at end of file +} diff --git a/src/sfizz/AtomicGuard.h b/src/sfizz/AtomicGuard.h index c36f1bd4..874e1f61 100644 --- a/src/sfizz/AtomicGuard.h +++ b/src/sfizz/AtomicGuard.h @@ -21,10 +21,63 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +/** + * @brief This file contains a pair of RAII helpers that handle some form + * of lock-free mutex-type protection adapter to audio applications where you have 1 priority thread + * that should never block and would rather return silence than wait, and another low-priority + * thread that handles long computations. + * + * @code{.cpp} + * + * // Somewhere in a class... + * std::atomic canEnterCallback; + * std::atomic inCallback; + * + * void functionThatSuspendsCallback() + * { + * AtomicDisabler callbackDisabler { canEnterCallback }; + * + * while (inCallback) { + * std::this_thread::sleep_for(1ms); + * } + * + * // Do your thing. + * } + * + * void callback(int samplesPerBlock) noexcept + * { + * AtomicGuard callbackGuard { inCallback }; + * if (!canEnterCallback) + * return; + * + * // Do your thing. + * } + * @endcode + * There are probably many ways to improve these and probably even debug them. + * The spinlocking itself could be integrated in the constructor, although the + * check for return in the callback could not. + */ #include namespace sfz { +/** + * @brief Simple class to set an atomic to true and automatically set it back to false on + * destruction. + * + * You call it like this assuming you need indicate that you are in e.g. a callback + * @code{.cpp} + * void functionToProtect() + * { + * AtomicGuard { guard }; + * + * // Do stuff, the atomic will be set back to false as soon as you're back + * } + * @endcode + * Note that this is not thread-safe at all, in the sense that it is only meant to be + * used with 2 threads along with the AtomicDisabler. One thread uses AtomicGuards, the other + * AtomicDisablers, and no other contending thread can share this pair of atomics. + */ class AtomicGuard { public: @@ -42,6 +95,23 @@ private: std::atomic& guard; }; +/** + * @brief Simple class to set an atomic to false and automatically set it back to true on + * destruction. + * + * You call it like this assuming you need to disable e.g. a callback + * @code{.cpp} + * void functionThatDisableAnotherFunction() + * { + * AtomicDisabler { disabler }; + * + * // Do stuff, the atomic will be set back to true as soon as you're back + * } + * @endcode + * Note that this is not thread-safe at all, in the sense that it is only meant to be + * used with 2 threads along with the AtomicGuard. One thread uses AtomicGuards, the other + * AtomicDisabler, and no other contending thread can share this pair of atomics. + */ class AtomicDisabler { public: diff --git a/src/sfizz/AudioBuffer.h b/src/sfizz/AudioBuffer.h index 2ef1b35a..98105a5b 100644 --- a/src/sfizz/AudioBuffer.h +++ b/src/sfizz/AudioBuffer.h @@ -32,7 +32,16 @@ namespace sfz { - +/** + * @brief A class to handle a collection of buffers, where each buffer has the same size. + * + * Unlike AudioSpan, this class *owns* its underlying buffers and they are freed when the buffer + * is destroyed. + * + * @tparam Type the underlying type of the buffers + * @tparam MaxChannels the maximum number of channels in the buffer + * @tparam Alignment the alignment for the buffers + */ template class AudioBuffer { public: @@ -43,9 +52,21 @@ public: using const_iterator = const_pointer; using size_type = size_t; + /** + * @brief Construct a new Audio Buffer object + * + */ AudioBuffer() { } + + /** + * @brief Construct a new Audio Buffer object with a specified number of + * channels and frames. + * + * @param numChannels + * @param numFrames + */ AudioBuffer(int numChannels, int numFrames) : numChannels(numChannels) , numFrames(numFrames) @@ -54,6 +75,13 @@ public: buffers[i] = std::make_unique(numFrames); } + /** + * @brief Resizes all the underlying buffers to a new size. + * + * @param newSize + * @return true if the resize worked + * @return false otherwise + */ bool resize(size_type newSize) { bool returnedOK = true; @@ -62,6 +90,12 @@ public: return returnedOK; } + /** + * @brief Return an iterator to a specific channel with a non-const type. + * + * @param channelIndex + * @return iterator + */ iterator channelWriter(int channelIndex) { ASSERT(channelIndex < numChannels) @@ -71,6 +105,12 @@ public: return {}; } + /** + * @brief Returns a sentinel for the channelWriter(channelIndex) iterator + * + * @param channelIndex + * @return iterator + */ iterator channelWriterEnd(int channelIndex) { ASSERT(channelIndex < numChannels) @@ -80,6 +120,12 @@ public: return {}; } + /** + * @brief Returns a const iterator for a specific channel + * + * @param channelIndex + * @return const_iterator + */ const_iterator channelReader(int channelIndex) const { ASSERT(channelIndex < numChannels) @@ -89,6 +135,12 @@ public: return {}; } + /** + * @brief Returns a sentinel for the channelReader(channelIndex) iterator + * + * @param channelIndex + * @return const_iterator + */ const_iterator channelReaderEnd(int channelIndex) const { ASSERT(channelIndex < numChannels) @@ -98,6 +150,12 @@ public: return {}; } + /** + * @brief Get a Span for a specific channel + * + * @param channelIndex + * @return absl::Span + */ absl::Span getSpan(int channelIndex) const { ASSERT(channelIndex < numChannels) @@ -107,32 +165,67 @@ public: return {}; } + /** + * @brief Get a const Span object for a specific channel + * + * @param channelIndex + * @return absl::Span + */ absl::Span getConstSpan(int channelIndex) const { return getSpan(channelIndex); } + /** + * @brief Add a channel to the buffer with the current number of frames. + * + */ void addChannel() { if (numChannels < MaxChannels) buffers[numChannels++] = std::make_unique(numFrames); } + /** + * @brief Get the number of elements in each buffer + * + * @return size_type + */ size_type getNumFrames() const { return numFrames; } + /** + * @brief Get the number of channels + * + * @return int + */ int getNumChannels() const { return numChannels; } + /** + * @brief Check if the buffers contains no elements + * + * @return true + * @return false + */ bool empty() const { return numFrames == 0; } + /** + * @brief Get a reference to a given element in a given buffer. + * + * In release builds this is not checked and may touch bad memory. + * + * @param channelIndex + * @param frameIndex + * @return Type& + */ Type& getSample(int channelIndex, size_type frameIndex) { // Uhoh @@ -142,6 +235,13 @@ public: return *(buffers[channelIndex]->data() + frameIndex); } + /** + * @brief Alias for getSample(...) + * + * @param channelIndex + * @param frameIndex + * @return Type& + */ Type& operator()(int channelIndex, size_type frameIndex) { return getSample(channelIndex, frameIndex); diff --git a/src/sfizz/Buffer.h b/src/sfizz/Buffer.h index 7f982bd4..0cab3d9b 100644 --- a/src/sfizz/Buffer.h +++ b/src/sfizz/Buffer.h @@ -32,6 +32,18 @@ namespace sfz { +/** + * @brief A heap buffer structure that tries to align its beginning and adds a small offset + * at the end for alignment too. + * + * Apparently on Linux this effort is mostly useless, and in the end most of the SIMD operations + * are coded with alignment checks and sentinels so this class could probably be much simpler. + * It does however wrap realloc which in some cases should be a bit more efficient than + * allocating a whole new block. + * + * @tparam Type The buffer type + * @tparam Alignment the required alignment in bytes (defaults to SIMDConfig::defaultAlignment) + */ template class Buffer { public: @@ -46,16 +58,33 @@ public: using const_reverse_iterator = std::reverse_iterator; using size_type = size_t; + /** + * @brief Construct a new Buffer object that is empty + * + */ Buffer() { - + } - + + /** + * @brief Construct a new Buffer object with size + * + * @param size + */ Buffer(size_t size) { resize(size); } + /** + * @brief Resizes the buffer. Given that std::realloc may return either the same pointer + * or a new one, you need to account for both cases in the code if you are using deep pointers. + * + * @param newSize the new buffer size in bytes + * @return true if allocation succeeded + * @return false otherwise + */ bool resize(size_t newSize) { if (newSize == 0) { @@ -83,6 +112,10 @@ public: return true; } + /** + * @brief Clear the buffers and frees the underlying memory + * + */ void clear() { largerSize = 0; @@ -97,6 +130,11 @@ public: std::free(paddedData); } + /** + * @brief Construct a new Buffer object from an existing one + * + * @param other + */ Buffer(const Buffer& other) { if (resize(other.size())) { @@ -104,6 +142,11 @@ public: } } + /** + * @brief Construct a new Buffer object by moving an existing one + * + * @param other + */ Buffer(Buffer&& other) { largerSize = std::exchange(other.largerSize, 0); @@ -161,4 +204,4 @@ private: LEAK_DETECTOR(Buffer); }; -} \ No newline at end of file +} diff --git a/src/sfizz/CCMap.h b/src/sfizz/CCMap.h index 6da0940f..5d8b6e7f 100644 --- a/src/sfizz/CCMap.h +++ b/src/sfizz/CCMap.h @@ -26,10 +26,23 @@ #include namespace sfz { +/** + * @brief A simple map that holds ValueType elements at different indices, and can return a default one + * if not present. Used mostly for CC modifiers in region descriptions as to store only the CC modifiers + * that are specified in the SFZ file rather than a gazillion of dummy "disabled" modifiers. The default + * value is set on construction. + * + * @tparam ValueType The type held in the map + */ template class CCMap { public: CCMap() = delete; + /** + * @brief Construct a new CCMap object with the specified default value. + * + * @param defaultValue + */ CCMap(const ValueType& defaultValue) : defaultValue(defaultValue) { @@ -38,6 +51,12 @@ public: CCMap(const CCMap&) = default; ~CCMap() = default; + /** + * @brief Returns the held object at the index, or a default value if not present + * + * @param index + * @return const ValueType& + */ const ValueType& getWithDefault(int index) const noexcept { auto it = container.find(index); @@ -48,6 +67,12 @@ public: } } + /** + * @brief Get the value at index key or emplace a new one if not present + * + * @param key the index of the element + * @return ValueType& + */ ValueType& operator[](const int& key) noexcept { if (!contains(key)) @@ -55,8 +80,27 @@ public: return container.operator[](key); } + /** + * @brief Is the container empty + * + * @return true + * @return false + */ inline bool empty() const { return container.empty(); } + /** + * @brief Returns the value at index with bounds checking (and possibly exceptions) + * + * @param index + * @return const ValueType& + */ const ValueType& at(int index) const { return container.at(index); } + /** + * @brief Returns true if the container containers an element at index + * + * @param index + * @return true + * @return false + */ bool contains(int index) const noexcept { return container.find(index) != container.end(); } typename std::map::iterator begin() { return container.begin(); } typename std::map::iterator end() { return container.end(); } @@ -65,4 +109,4 @@ private: std::map container; LEAK_DETECTOR(CCMap); }; -} \ No newline at end of file +} diff --git a/src/sfizz/Config.h b/src/sfizz/Config.h index f2a96a15..28aee001 100644 --- a/src/sfizz/Config.h +++ b/src/sfizz/Config.h @@ -43,7 +43,7 @@ namespace config { constexpr float voiceStealingThreshold { 0.00001 }; } // namespace config - +// Enable or disable SIMD accelerators by default namespace SIMDConfig { constexpr unsigned int defaultAlignment { 16 }; constexpr bool writeInterleaved { true }; @@ -66,4 +66,4 @@ namespace SIMDConfig { constexpr bool mean { false }; constexpr bool meanSquared { false }; } -} // namespace sfz \ No newline at end of file +} // namespace sfz diff --git a/src/sfizz/EGDescription.h b/src/sfizz/EGDescription.h index ee40fba5..bdec2e76 100644 --- a/src/sfizz/EGDescription.h +++ b/src/sfizz/EGDescription.h @@ -31,7 +31,14 @@ namespace sfz { - +/** + * @brief A description for an SFZ envelope generator, with its envelope parameters + * and possible CC modulation. This is a structure to be integrated directly in a + * region and accessed, so not too many getters and setters in there. + * + * TODO: should be updated for SFZ v2 + * + */ struct EGDescription { EGDescription() = default; @@ -63,30 +70,79 @@ struct EGDescription absl::optional ccStart; absl::optional ccSustain; + /** + * @brief Get the attack with possibly a CC modifier and a velocity modifier + * + * @param ccValues + * @param velocity + * @return float + */ float getAttack(const CCValueArray &ccValues, uint8_t velocity) const noexcept { return ccSwitchedValue(ccValues, ccAttack, attack) + normalizeCC(velocity)*vel2attack; } + /** + * @brief Get the decay with possibly a CC modifier and a velocity modifier + * + * @param ccValues + * @param velocity + * @return float + */ float getDecay(const CCValueArray &ccValues, uint8_t velocity) const noexcept { return ccSwitchedValue(ccValues, ccDecay, decay) + normalizeCC(velocity)*vel2decay; } + /** + * @brief Get the delay with possibly a CC modifier and a velocity modifier + * + * @param ccValues + * @param velocity + * @return float + */ float getDelay(const CCValueArray &ccValues, uint8_t velocity) const noexcept { return ccSwitchedValue(ccValues, ccDelay, delay) + normalizeCC(velocity)*vel2delay; } + /** + * @brief Get the holding duration with possibly a CC modifier and a velocity modifier + * + * @param ccValues + * @param velocity + * @return float + */ float getHold(const CCValueArray &ccValues, uint8_t velocity) const noexcept { return ccSwitchedValue(ccValues, ccHold, hold) + normalizeCC(velocity)*vel2hold; } + /** + * @brief Get the release duration with possibly a CC modifier and a velocity modifier + * + * @param ccValues + * @param velocity + * @return float + */ float getRelease(const CCValueArray &ccValues, uint8_t velocity) const noexcept { return ccSwitchedValue(ccValues, ccRelease, release) + normalizeCC(velocity)*vel2release; } + /** + * @brief Get the starting level with possibly a CC modifier and a velocity modifier + * + * @param ccValues + * @param velocity + * @return float + */ float getStart(const CCValueArray &ccValues, uint8_t velocity [[maybe_unused]]) const noexcept { return ccSwitchedValue(ccValues, ccStart, start); } + /** + * @brief Get the sustain level with possibly a CC modifier and a velocity modifier + * + * @param ccValues + * @param velocity + * @return float + */ float getSustain(const CCValueArray &ccValues, uint8_t velocity) const noexcept { return ccSwitchedValue(ccValues, ccSustain, sustain) + normalizeCC(velocity)*vel2sustain; diff --git a/src/sfizz/FilePool.h b/src/sfizz/FilePool.h index c8d43c7b..3c088dce 100644 --- a/src/sfizz/FilePool.h +++ b/src/sfizz/FilePool.h @@ -36,6 +36,23 @@ #include namespace sfz { +/** + * @brief This is a singleton-designed class that holds all the preloaded + * data as well as functions to request new file data and collect the file + * handles to close after they are read. + * + * This object caches the file data that was already preloaded in case it is asked + * again by a region using the same sample. In this situation, both regions have a + * handle on the same preloaded data. + * + * The file request is immediately served using the preloaded data. A ticket is then + * provided to the voice that requested the file, and the file loading happens in the + * background. When the file is fully loaded, the background makes the full data available + * to the voice and consumes the ticket, while conserving a handle on this file. When the + * voice dies it releases its handle on the files, which should decrease the reference count + * to 1. A garbage collection thread then runs regularly to clear the memory of all file + * handles with a reference count of 1. + */ class FilePool { public: FilePool() { } @@ -46,7 +63,17 @@ public: fileLoadingThread.join(); garbageCollectionThread.join(); } + /** + * @brief Set the root directory from which to search for files to load + * + * @param directory + */ void setRootDirectory(const fs::path& directory) noexcept { rootDirectory = directory; } + /** + * @brief Get the number of preloaded sample files + * + * @return size_t + */ size_t getNumPreloadedSamples() const noexcept { return preloadedData.size(); } struct FileInformation { @@ -56,8 +83,35 @@ public: double sampleRate { config::defaultSampleRate }; std::shared_ptr> preloadedData; }; + /** + * @brief Get metadata information about a file as well as the first chunk of data + * + * If the same file was already preloaded and with a compatible offset, the handle + * is shared between the regions. Otherwise, a new handle is created (the others keep + * the old preloaded file). + * + * @param filename + * @param offset the maximum offset to consider for preloading. The total preloaded + * size will be preloadedSize + offset + * @return absl::optional + */ absl::optional getFileInformation(const std::string& filename, uint32_t offset) noexcept; + /** + * @brief Queue a full loading operation for a given voice. + * + * The goal of the ticket is to avoid file loading operations that for some reason + * finish too late a "replace" a proper sample with an obsolete one for a voice. + * + * @param voice the voice to give the full file data to + * @param sample the sample file + * @param numFrames the number of frames to load from the file + * @param ticket an ideally unique ticket number for this file. + */ void enqueueLoading(Voice* voice, const std::string* sample, int numFrames, unsigned ticket) noexcept; + /** + * @brief Clear all preloaded files. + * + */ void clear(); private: fs::path rootDirectory; diff --git a/src/sfizz/FloatEnvelopes.cpp b/src/sfizz/FloatEnvelopes.cpp index b3c0cb80..c08a0823 100644 --- a/src/sfizz/FloatEnvelopes.cpp +++ b/src/sfizz/FloatEnvelopes.cpp @@ -21,6 +21,17 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +/** + * @file FloatEnvelopes.cpp + * @author Paul Ferrand (paul@ferrand.cc) + * @brief Force the instantiations of the ADSR and linear envelopes for floats + * @version 0.1 + * @date 2019-11-30 + * + * @copyright Copyright (c) 2019 Paul Ferrand + * + */ + #include "LinearEnvelope.h" #include "ADSREnvelope.h" @@ -33,4 +44,4 @@ namespace sfz { template class LinearEnvelope; template class ADSREnvelope; -} \ No newline at end of file +} diff --git a/src/sfizz/HistoricalBuffer.h b/src/sfizz/HistoricalBuffer.h index 5e616b02..1c9ae985 100644 --- a/src/sfizz/HistoricalBuffer.h +++ b/src/sfizz/HistoricalBuffer.h @@ -4,6 +4,12 @@ namespace sfz { +/** + * @brief A naive circular buffer which is supposed to hold power values + * and return the average of its content. + * + * @tparam ValueType + */ template class HistoricalBuffer { public: @@ -14,13 +20,24 @@ public: resize(size); } + /** + * @brief Resize the underlying buffer. Newly added "slots" are + * initialized to 0.0 + * + * @param size + */ void resize(int size) { buffer.resize(size); fill(absl::MakeSpan(buffer), 0.0); index = 0; } - + + /** + * @brief Add a value to the buffer + * + * @param value + */ void push(ValueType value) { if (size > 0) { @@ -30,6 +47,11 @@ public: } } + /** + * @brief Return the average of all the values in the buffer + * + * @return ValueType + */ ValueType getAverage() const { return mean(buffer); @@ -39,4 +61,4 @@ private: size_t size { 0 }; size_t index { 0 }; }; -} \ No newline at end of file +} diff --git a/src/sfizz/LeakDetector.h b/src/sfizz/LeakDetector.h index 659d9033..669f8d5a 100644 --- a/src/sfizz/LeakDetector.h +++ b/src/sfizz/LeakDetector.h @@ -26,6 +26,23 @@ #include "Debug.h" #if __cplusplus >= 201703L +/** + * @brief Tries to catch memory leaks by counting constructions + * and deletions of objects. This will trap at the end of the program + * execution if some elements were not properly deleted for one reason + * or another. Use by adding the LEAK_DETECTOR macro at the end of a class + * definition with the proper class name, e.g. + * + * @code{.cpp} + * class Buffer + * { + * // Some code for buffer + * LEAK_DETECTOR(Buffer); + * } + * @endcode + * + * @tparam Owner + */ template class LeakDetector { public: diff --git a/src/sfizz/LinearEnvelope.h b/src/sfizz/LinearEnvelope.h index ae9b5927..d69562c3 100644 --- a/src/sfizz/LinearEnvelope.h +++ b/src/sfizz/LinearEnvelope.h @@ -30,17 +30,74 @@ #include namespace sfz { - +/** + * @brief Describes a simple linear envelope that can be polled in a blockwise + * manner. It works by storing "events" in the immediate future and linearly + * interpolating between these events. This envelope can also transform its + * incoming target points through a lambda, although the interpolation will + * always be linear (i.e. the lambda function is applied before the interpolation). + * + * The way to use this class is by repeatedly calling `registerEvent` and then + * `getBlock` to get a block of interpolated values in between the specified events. + * You should only register events whose timestamps are below the size of the block + * you will require when calling `getBlock`. + * + * @tparam Type + */ template class LinearEnvelope { public: + /** + * @brief Construct a new linear envelope with a default memory size for + * incoming events. + * + */ LinearEnvelope(); + /** + * @brief Construct a new linear envelope with a specific memory size for + * incoming events as well as a transformation function for incoming events. + * + * @param maxCapacity + * @param function + */ LinearEnvelope(int maxCapacity, std::function function); + /** + * @brief Set the maximum memory size for incoming events + * + * @param maxCapacity + */ void setMaxCapacity(int maxCapacity); + /** + * @brief Set the transformation function for the value of incoming events. + * + * @param function + */ void setFunction(std::function function); + /** + * @brief Register a new event. Note that the timestamp of the new value should + * be less than the future call to `getBlock` otherwise the event will be ignored. + * + * @param timestamp + * @param inputValue + */ void registerEvent(int timestamp, Type inputValue); + /** + * @brief Clear all events in memory + * + */ void clear(); + /** + * @brief Reset the envelope and clears the memory. + * + * @param value + */ void reset(Type value = 0.0); + /** + * @brief Get a block of interpolated values between events previously registered + * using `registerEvent`. + * + * @param output + */ void getBlock(absl::Span output); private: std::function function { [](Type input) { return input; } }; diff --git a/src/sfizz/MathHelpers.h b/src/sfizz/MathHelpers.h index 86ac7c09..601152e7 100644 --- a/src/sfizz/MathHelpers.h +++ b/src/sfizz/MathHelpers.h @@ -21,6 +21,13 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +/** + * @file MathHelpers.h + * @author Paul Ferrand (paul@ferrand.cc) + * @brief Contains math helper functions and math constants + * @version 0.1 + * @date 2019-11-23 + */ #pragma once #include #include @@ -34,43 +41,91 @@ inline constexpr T min(T op1, T op2, T op3) { return std::min(op1, std::min(op2, template inline constexpr T min(T op1, T op2, T op3, T op4) { return std::min(op1, std::min(op2, std::min(op3, op4))); } - +/** + * @brief Converts db values into power (applies 10**(in/10)) + * + * @tparam Type + * @param in + * @return Type + */ template inline constexpr Type db2pow(Type in) { return std::pow(static_cast(10.0), in * static_cast(0.1)); } +/** + * @brief Converts power values into dB (applies 10log10(in)) + * + * @tparam Type + * @param in + * @return Type + */ template inline constexpr Type pow2db(Type in) { return static_cast(10.0) * std::log10(in); } +/** + * @brief Converts dB values to magnitude (applies 10**(in/20)) + * + * @tparam Type + * @param in + * @return constexpr Type + */ template inline constexpr Type db2mag(Type in) { return std::pow(static_cast(10.0), in * static_cast(0.05)); } +/** + * @brief Converts magnitude values into dB (applies 20log10(in)) + * + * @tparam Type + * @param in + * @return Type + */ template inline constexpr Type mag2db(Type in) { return static_cast(20.0) * std::log10(in); } +/** + * @brief Global random singletons + * + * TODO: could be moved into a singleton class holder + * + */ namespace Random { static std::random_device randomDevice; static std::mt19937 randomGenerator { randomDevice() }; } // namespace Random +/** + * @brief Converts a midi note to a frequency value + * + * @param noteNumber + * @return float + */ inline float midiNoteFrequency(const int noteNumber) { return 440.0f * std::pow(2.0f, (noteNumber - 69) / 12.0f); } +/** + * @brief Clamps a value between bounds, including the bounds! + * + * @tparam T + * @param v + * @param lo + * @param hi + * @return T + */ template -constexpr const T& clamp( const T& v, const T& lo, const T& hi ) +constexpr T clamp( const T& v, const T& lo, const T& hi ) { assert( !(hi < lo) ); return (v < lo) ? lo : (hi < v) ? hi : v; diff --git a/src/sfizz/MidiState.h b/src/sfizz/MidiState.h index 11c97f7b..6035940d 100644 --- a/src/sfizz/MidiState.h +++ b/src/sfizz/MidiState.h @@ -5,8 +5,20 @@ namespace sfz { +/** + * @brief Holds the current "MIDI state", meaning the known state of all CCs + * currently, as well as the note velocities that triggered the currently + * pressed notes. + * + */ struct MidiState { + /** + * @brief Update the state after a note on event + * + * @param noteNumber + * @param velocity + */ inline void noteOn(int noteNumber, uint8_t velocity) { if (noteNumber >= 0 && noteNumber < 128) { @@ -15,6 +27,12 @@ struct MidiState } } + /** + * @brief Register a note off and get the note duration + * + * @param noteNumber + * @return float + */ inline float getNoteDuration(int noteNumber) const { if (noteNumber >= 0 && noteNumber < 128) { @@ -26,6 +44,12 @@ struct MidiState return 0.0f; } + /** + * @brief Get the note on velocity for a given note + * + * @param noteNumber + * @return uint8_t + */ inline uint8_t getNoteVelocity(int noteNumber) const { if (noteNumber >= 0 && noteNumber < 128) @@ -33,8 +57,22 @@ struct MidiState return 0; } + + /** + * @brief Stores the note on times. + * + */ std::array noteOnTimes { }; + /** + * @brief Stores the velocity of the note ons for currently + * depressed notes. + * + */ std::array lastNoteVelocities { }; + /** + * @brief Current known values for the CCs. + * + */ CCValueArray cc; }; } diff --git a/src/sfizz/OnePoleFilter.h b/src/sfizz/OnePoleFilter.h index 72c71c3e..9c3afd0f 100644 --- a/src/sfizz/OnePoleFilter.h +++ b/src/sfizz/OnePoleFilter.h @@ -29,6 +29,12 @@ namespace sfz { +/** + * @brief An implementation of a one pole filter. This is a scalar + * implementation. + * + * @tparam Type the underlying type of the filter. + */ template class OnePoleFilter { public: @@ -137,4 +143,4 @@ private: state += 2 * intermediate; } }; -} \ No newline at end of file +} diff --git a/src/sfizz/Opcode.h b/src/sfizz/Opcode.h index 79694ca5..45011a82 100644 --- a/src/sfizz/Opcode.h +++ b/src/sfizz/Opcode.h @@ -35,6 +35,12 @@ #include "absl/strings/numbers.h" namespace sfz { +/** + * @brief Opcode description class; should be very lightweight to use + * and move around. The class parses the parameters of the opcode + * on construction. + * + */ struct Opcode { Opcode() = delete; Opcode(absl::string_view inputOpcode, absl::string_view inputValue); @@ -45,6 +51,16 @@ struct Opcode { LEAK_DETECTOR(Opcode); }; +/** + * @brief Read a value from the sfz file and cast it to the destination parameter along + * with a proper clamping into range if needed. This particular template version acts on + * integral target types, but can accept floats as an input. + * + * @tparam ValueType the target casting type + * @param value the string value to be read and stored + * @param validRange the range of admitted values + * @return absl::optional the cast value, or null + */ template ::value, int> = 0> inline absl::optional readOpcode(absl::string_view value, const Range& validRange) { @@ -64,6 +80,16 @@ inline absl::optional readOpcode(absl::string_view value, const Range return validRange.clamp(static_cast(returnedValue)); } +/** + * @brief Read a value from the sfz file and cast it to the destination parameter along + * with a proper clamping into range if needed. This particular template version acts on + * floating types. + * + * @tparam ValueType the target casting type + * @param value the string value to be read and stored + * @param validRange the range of admitted values + * @return absl::optional the cast value, or null + */ template ::value, int> = 0> inline absl::optional readOpcode(absl::string_view value, const Range& validRange) { @@ -74,6 +100,9 @@ inline absl::optional readOpcode(absl::string_view value, const Range return validRange.clamp(returnedValue); } +/** + * @brief Read a boolean value from the sfz file and cast it to the destination parameter. + */ inline absl::optional readBooleanFromOpcode(const Opcode& opcode) { switch (hash(opcode.value)) { @@ -86,6 +115,15 @@ inline absl::optional readBooleanFromOpcode(const Opcode& opcode) } } +/** + * @brief Set a target parameter from an opcode value, with possibly a textual note rather + * than a number + * + * @tparam ValueType + * @param opcode the source opcode + * @param target the value to update + * @param validRange the range of admitted values used to clamp the opcode + */ template inline void setValueFromOpcode(const Opcode& opcode, ValueType& target, const Range& validRange) { @@ -96,6 +134,15 @@ inline void setValueFromOpcode(const Opcode& opcode, ValueType& target, const Ra target = *value; } +/** + * @brief Set a target parameter from an opcode value, with possibly a textual note rather + * than a number + * + * @tparam ValueType + * @param opcode the source opcode + * @param target the value to update + * @param validRange the range of admitted values used to clamp the opcode + */ template inline void setValueFromOpcode(const Opcode& opcode, absl::optional& target, const Range& validRange) { @@ -106,6 +153,15 @@ inline void setValueFromOpcode(const Opcode& opcode, absl::optional& target = *value; } +/** + * @brief Set a target end of a range from an opcode value, with possibly a textual note rather + * than a number + * + * @tparam ValueType + * @param opcode the source opcode + * @param target the value to update + * @param validRange the range of admitted values used to clamp the opcode + */ template inline void setRangeEndFromOpcode(const Opcode& opcode, Range& target, const Range& validRange) { @@ -116,6 +172,15 @@ inline void setRangeEndFromOpcode(const Opcode& opcode, Range& target target.setEnd(*value); } +/** + * @brief Set a target beginning of a range from an opcode value, with possibly a textual note rather + * than a number + * + * @tparam ValueType + * @param opcode the source opcode + * @param target the value to update + * @param validRange the range of admitted values used to clamp the opcode + */ template inline void setRangeStartFromOpcode(const Opcode& opcode, Range& target, const Range& validRange) { @@ -126,6 +191,14 @@ inline void setRangeStartFromOpcode(const Opcode& opcode, Range& targ target.setStart(*value); } +/** + * @brief Set a CC modulation parameter from an opcode value. + * + * @tparam ValueType + * @param opcode the source opcode + * @param target the new CC modulation parameter + * @param validRange the range of admitted values used to clamp the opcode + */ template inline void setCCPairFromOpcode(const Opcode& opcode, absl::optional& target, const Range& validRange) { diff --git a/src/sfizz/Range.h b/src/sfizz/Range.h index 5ea5b10e..2af64b4f 100644 --- a/src/sfizz/Range.h +++ b/src/sfizz/Range.h @@ -26,10 +26,13 @@ #include #include - namespace sfz { - +/** + * @brief This class holds a range with functions to clamp and test if a value is in the range + * + * @tparam Type + */ template class Range { static_assert(std::is_arithmetic::value, "The Type should be arithmetic"); @@ -59,6 +62,11 @@ public: ~Range() = default; Type getStart() const noexcept { return _start; } Type getEnd() const noexcept { return _end; } + /** + * @brief Get the range as an std::pair of the endpoints + * + * @return std::pair + */ std::pair getPair() const noexcept { return std::make_pair(_start, _end); } Range(const Range& range) = default; Range(Range&& range) = default; @@ -76,9 +84,35 @@ public: if (end < _start) _start = end; } + /** + * @brief Clamp a value within the range including the endpoints + * + * @param value + * @return Type + */ Type clamp(Type value) const noexcept { return ::clamp(value, _start, _end); } + /** + * @brief Checks if a value is in the range, including the endpoints + * + * @param value + * @return true + * @return false + */ bool containsWithEnd(Type value) const noexcept { return (value >= _start && value <= _end); } + /** + * @brief Checks if a value is in the range, excluding the end of the range + * + * @param value + * @return true + * @return false + */ bool contains(Type value) const noexcept { return (value >= _start && value < _end); } + /** + * @brief Shrink the region if it is smaller than the provided start and end points + * + * @param start + * @param end + */ void shrinkIfSmaller(Type start, Type end) { if (start > end) diff --git a/src/sfizz/Region.cpp b/src/sfizz/Region.cpp index 3ea2e94e..26a8ba41 100644 --- a/src/sfizz/Region.cpp +++ b/src/sfizz/Region.cpp @@ -189,10 +189,10 @@ bool sfz::Region::parseOpcode(const Opcode& opcode) case hash("sustain_sw"): checkSustain = readBooleanFromOpcode(opcode).value_or(Default::checkSustain); - break; + break; case hash("sostenuto_sw"): checkSostenuto = readBooleanFromOpcode(opcode).value_or(Default::checkSostenuto); - break; + break; // Region logic: internal conditions case hash("lochanaft"): setRangeStartFromOpcode(opcode, aftertouchRange, Default::aftertouchRange); @@ -649,7 +649,7 @@ uint32_t sfz::Region::getOffset() noexcept return offset + offsetDistribution(Random::randomGenerator); } -uint32_t sfz::Region::getDelay() noexcept +float sfz::Region::getDelay() noexcept { return delay + delayDistribution(Random::randomGenerator); } diff --git a/src/sfizz/Region.h b/src/sfizz/Region.h index f4173460..b33eaffa 100644 --- a/src/sfizz/Region.h +++ b/src/sfizz/Region.h @@ -36,6 +36,18 @@ #include namespace sfz { +/** + * @brief Regions are the basic building blocks for the SFZ parsing and handling code. + * All SFZ files are made of regions that are activated when a key is pressed or a CC + * is triggered. Most opcodes constrain the situations in which a region can be activated. + * Once activated, the Synth object will find a voice to play the region. + * + * This class is mostly open as there are a ton of parameters needed for the voice to be + * able to play the region, and using getters would incur a ton of boilerplate code. Note + * also that some parameters may be parsed and stored in regions but no playing logi is + * available in the voices to take advantage of them. + * + */ struct Region { Region(const MidiState& midiState) : midiState(midiState) @@ -45,27 +57,185 @@ struct Region { Region(const Region&) = default; ~Region() = default; + /** + * @brief Triggers on release? + * + * @return true + * @return false + */ bool isRelease() const noexcept { return trigger == SfzTrigger::release || trigger == SfzTrigger::release_key; } + /** + * @brief Is a generator (*sine or *silence mostly)? + * + * @return true + * @return false + */ bool isGenerator() const noexcept { return sample.size() > 0 ? sample[0] == '*' : false; } + /** + * @brief Is a looping region (at least potentially)? + * + * @return true + * @return false + */ bool shouldLoop() const noexcept { return (loopMode == SfzLoopMode::loop_continuous || loopMode == SfzLoopMode::loop_sustain); } + /** + * @brief Given the current midi state, is the region switched on? + * + * @return true + * @return false + */ bool isSwitchedOn() const noexcept; + /** + * @brief Register a new note on event. The region may be switched on or off using keys so + * this function updates the keyswitches state. + * + * @param channel + * @param noteNumber + * @param velocity + * @param randValue a random value between 0 and 1 used to randomize a bit the region activations + * and vary the samples + * @return true if the region should trigger on this event. + * @return false + */ bool registerNoteOn(int channel, int noteNumber, uint8_t velocity, float randValue) noexcept; + /** + * @brief Register a new note off event. The region may be switched on or off using keys so + * this function updates the keyswitches state. + * + * @param channel + * @param noteNumber + * @param velocity + * @param randValue a random value between 0 and 1 used to randomize a bit the region activations + * and vary the samples + * @return true if the region should trigger on this event. + * @return false + */ bool registerNoteOff(int channel, int noteNumber, uint8_t velocity, float randValue) noexcept; + /** + * @brief Register a new CC event. The region may be switched on or off using CCs so + * this function checks if it indeeds need to activate or not. + * + * @param channel + * @param ccNumber + * @param ccValue + * @return true if the region should trigger on this event + * @return false + */ bool registerCC(int channel, int ccNumber, uint8_t ccValue) noexcept; + /** + * @brief Register a new pitch wheel event. + * + * @param channel + * @param pitch + * @return true if the region should trigger on this event + * @return false + */ void registerPitchWheel(int channel, int pitch) noexcept; + /** + * @brief Register a new aftertouch event. + * + * @param channel + * @param aftertouch + * @return true if the region should trigger on this event + * @return false + */ void registerAftertouch(int channel, uint8_t aftertouch) noexcept; + /** + * @brief Register tempo + * + * @param channel + * @param aftertouch + * @return true if the region should trigger on this event + * @return false + */ void registerTempo(float secondsPerQuarter) noexcept; + /** + * @brief Is the underlying region sample a stereo one? + * + * @return true + * @return false + */ bool isStereo() const noexcept; + /** + * @brief Get the base pitch of the region depending on which note has been + * pressed and at which velocity. + * + * @param noteNumber + * @param velocity + * @return float + */ float getBasePitchVariation(int noteNumber, uint8_t velocity) noexcept; + /** + * @brief Get the note-related gain of the region depending on which note has been + * pressed and at which velocity. + * + * @param noteNumber + * @param velocity + * @return float + */ float getNoteGain(int noteNumber, uint8_t velocity) noexcept; + /** + * @brief Get the additional crossfade gain of the region depending on the + * CC values + * + * @param ccState + * @return float + */ float getCrossfadeGain(const CCValueArray& ccState) noexcept; + /** + * @brief Get the base volume of the region depending on which note has been + * pressed to trigger the region. + * + * @param noteNumber + * @return float + */ float getBaseVolumedB(int noteNumber) noexcept; + /** + * @brief Get the base gain of the region. + * + * @return float + */ float getBaseGain() noexcept; + /** + * @brief Computes the gain value related to the velocity of the note + * + * @return float + */ float velocityCurve(uint8_t velocity) const noexcept; + /** + * @brief Get the region offset in samples + * + * @return uint32_t + */ uint32_t getOffset() noexcept; - uint32_t getDelay() noexcept; + /** + * @brief Get the region delay in samples + * + * @return uint32_t + */ + float getDelay() noexcept; + /** + * @brief Get the index of the sample end, either natural end or forced + * loop. + * + * @return uint32_t + */ uint32_t trueSampleEnd() const noexcept; + /** + * @brief Can the region use the preloaded data only to play its full range? + * + * @return true + * @return false + */ bool canUsePreloadedData() const noexcept; + /** + * @brief Parse a new opcode into the region to fill in the proper parameters. + * This must be called multiple times for each opcode applying to this region. + * + * @param opcode + * @return true if the opcode was properly read and stored. + * @return false + */ bool parseOpcode(const Opcode& opcode); // Sound source: sample playback @@ -138,7 +308,7 @@ struct Region { CCMap> crossfadeCCInRange { Default::crossfadeCCInRange }; // xfin_loccN xfin_hiccN CCMap> crossfadeCCOutRange { Default::crossfadeCCOutRange }; // xfout_loccN xfout_hiccN float rtDecay { Default::rtDecay }; // rt_decay - + // Performance parameters: pitch uint8_t pitchKeycenter { Default::pitchKeycenter }; // pitch_keycenter @@ -175,4 +345,4 @@ private: LEAK_DETECTOR(Region); }; -} // namespace sfz \ No newline at end of file +} // namespace sfz diff --git a/src/sfizz/SIMDHelpers.h b/src/sfizz/SIMDHelpers.h index 84c7ceff..33b8c8ab 100644 --- a/src/sfizz/SIMDHelpers.h +++ b/src/sfizz/SIMDHelpers.h @@ -21,6 +21,39 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +/** + * @file SIMDHelpers.h + * @author Paul Ferrand (paul@ferrand.cc) + * @brief This file contains useful functions to treat buffers of numerical values + * (e.g. a buffer of floats usually). + * + * These functions are templated to apply on + * various underlying buffer types, and this file contains the generic version of the + * function. Some templates specializations exists for different architecture that try + * to make use of SIMD intrinsics; you can find such a file in SIMDSSE.cpp and possibly + * someday SIMDNEON.cpp for ARM platforms. + * + * If you want to write specializations for float buffers the idea is to start from the SIMDDummy + * file that just calls back the generic implementation, and implement the specializations you + * wish from this list. You can then either activate or deactivate a SIMD version by default + * using the variables in Config.h, or call e.g. writeInterleaved(...) to use the + * SIMD version of writeInterleaved. To implement e.g. double template specializations you + * will need to amend this file to pre-declare the specializations, and create a file similar to + * SIMDxxx.cpp. + * + * All the SIMD functions are benchmarked. If you run the benchmark for a given function you can check + * if it is interesting to run the SIMD version by default. The interest is that you can activate + * and deactivate each SIMD specialization with a fine granularity, since SIMD performance + * will be very dependent on the processor architecture. Modern processors can also organize their + * instructions so that scalar non-SIMD code runs sometimes much more efficiently than SIMD code + * especially when the latter does not operate on misaligned buffers. + * + * @version 0.1 + * @date 2019-11-23 + * + * @copyright Copyright (c) 2019 + * + */ #pragma once #include "Config.h" #include "Debug.h" @@ -39,6 +72,17 @@ namespace _internals { } } +/** + * @brief Read interleaved stereo data from a buffer and separate it in a left/right pair of buffers. + * + * The output size will be the minimum of the input span and output spans size. + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param input + * @param outputLeft + * @param outputRight + */ template void readInterleaved(absl::Span input, absl::Span outputLeft, absl::Span outputRight) noexcept { @@ -62,6 +106,17 @@ namespace _internals { } } +/** + * @brief Write a pair of left and right stereo input into a single buffer interleaved. + * + * The output size will be the minimum of the input spans and output span size. + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param inputLeft + * @param inputRight + * @param output + */ template void writeInterleaved(absl::Span inputLeft, absl::Span inputRight, absl::Span output) noexcept { @@ -81,6 +136,14 @@ void writeInterleaved(absl::Span inputLeft, absl::Span template <> void readInterleaved(absl::Span input, absl::Span outputLeft, absl::Span outputRight) noexcept; +/** + * @brief Fill a buffer with a value; comparable to std::fill in essence. + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param output + * @param value + */ template void fill(absl::Span output, T value) noexcept { @@ -90,6 +153,14 @@ void fill(absl::Span output, T value) noexcept template <> void fill(absl::Span output, float value) noexcept; +/** + * @brief Exp math function + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param input + * @param output + */ template void exp(absl::Span input, absl::Span output) noexcept { @@ -102,6 +173,16 @@ void exp(absl::Span input, absl::Span output) noexcept template <> void exp(absl::Span input, absl::Span output) noexcept; +/** + * @brief Log math function + * + * The output size will be the minimum of the input span and output span size. + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param input + * @param output + */ template void log(absl::Span input, absl::Span output) noexcept { @@ -114,6 +195,16 @@ void log(absl::Span input, absl::Span output) noexcept template <> void log(absl::Span input, absl::Span output) noexcept; +/** + * @brief sin math function + * + * The output size will be the minimum of the input span and output span size. + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param input + * @param output + */ template void sin(absl::Span input, absl::Span output) noexcept { @@ -126,6 +217,16 @@ void sin(absl::Span input, absl::Span output) noexcept template <> void sin(absl::Span input, absl::Span output) noexcept; +/** + * @brief cos math function + * + * The output size will be the minimum of the input span and output span size. + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param input + * @param output + */ template void cos(absl::Span input, absl::Span output) noexcept { @@ -160,6 +261,26 @@ namespace _internals { } } +/** + * @brief Computes an integer index and 2 float coefficients corresponding to the + * linear interpolation procedure. This version will saturate the index to the upper + * bound if the upper bound is reached. + * + * The indices are computed starting from the given floatIndex, and each increment + * is given by the elements of jumps. + * The output size will be the minimum of the inputs span and outputs span size. + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param jumps the floating point increments to the index + * @param leftCoeffs the linear interpolation coefficients for the left value + * @param rightCoeffs the linear interpolation coefficients for the right value + * @param indices the integer sample indices for the left values; the right values + * for interpolation at index i are (indices[i] + 1) and not indices[i+1] + * @param floatIndex the starting floating point index + * @param loopEnd the end of the "loop" which is not really a loop because it saturate. + * @return float + */ template float saturatingSFZIndex(absl::Span jumps, absl::Span leftCoeffs, absl::Span rightCoeffs, absl::Span indices, T floatIndex, T loopEnd) noexcept { @@ -199,6 +320,23 @@ namespace _internals { } } +/** + * @brief Computes an integer index and 2 float coefficients corresponding to the + * linear interpolation procedure. This version will loop the index at the upper + * bound loopend and restart it at the start of the loop. + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param jumps the floating point increments to the index + * @param leftCoeffs the linear interpolation coefficients for the left value + * @param rightCoeffs the linear interpolation coefficients for the right value + * @param indices the integer sample indices for the left values; the right values + * for interpolation at index i are (indices[i] + 1) and not indices[i+1] + * @param floatIndex the starting floating point index + * @param loopEnd the end index of the loop + * @param loopStart the start index of the loop + * @return float + */ template float loopingSFZIndex(absl::Span jumps, absl::Span leftCoeffs, absl::Span rightCoeffs, absl::Span indices, T floatIndex, T loopEnd, T loopStart) noexcept { @@ -229,6 +367,17 @@ namespace _internals { } } +/** + * @brief Applies a scalar gain to the input + * + * The output size will be the minimum of the input span and output span size. + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param gain the gain to apply + * @param input + * @param output + */ template void applyGain(T gain, absl::Span input, absl::Span output) noexcept { @@ -248,6 +397,17 @@ namespace _internals { } } +/** + * @brief Applies a vector gain to an input stap + * + * The output size will be the minimum of the gain, input span and output span size. + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param gain + * @param input + * @param output + */ template void applyGain(absl::Span gain, absl::Span input, absl::Span output) noexcept { @@ -261,12 +421,30 @@ void applyGain(absl::Span gain, absl::Span input, absl::Span(g, in, out); } +/** + * @brief Applies a scalar gain in-place on a span + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param gain + * @param output + */ template void applyGain(T gain, absl::Span output) noexcept { applyGain(gain, output, output); } +/** + * @brief Applies a vector gain in-place on a span + * + * The output size will be the minimum of the gain span and output span size. + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param gain + * @param output + */ template void applyGain(absl::Span gain, absl::Span output) noexcept { @@ -287,6 +465,17 @@ namespace _internals { } } +/** + * @brief Applies a gain to the input and add it on the output + * + * The output size will be the minimum of the gain span, input span and output span sizes. + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param gain + * @param input + * @param output + */ template void multiplyAdd(absl::Span gain, absl::Span input, absl::Span output) noexcept { @@ -312,6 +501,16 @@ namespace _internals { } } +/** + * @brief Compute a linear ramp blockwise between 2 values + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param output The destination span + * @param start + * @param step + * @return T + */ template T linearRamp(absl::Span output, T start, T step) noexcept { @@ -330,6 +529,16 @@ namespace _internals { } } +/** + * @brief Compute a multiplicative ramp blockwise between 2 values + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param output The destination span + * @param start + * @param step + * @return T + */ template T multiplicativeRamp(absl::Span output, T start, T step) noexcept { @@ -358,6 +567,16 @@ namespace _internals { } } +/** + * @brief Add an input span to the output span + * + * The output size will be the minimum of the gain span, input span and output span sizes. + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param input + * @param output + */ template void add(absl::Span input, absl::Span output) noexcept { @@ -398,6 +617,14 @@ namespace _internals { } } +/** + * @brief Subtract a value from a span + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param value + * @param output + */ template void subtract(const T value, absl::Span output) noexcept { @@ -407,6 +634,16 @@ void subtract(const T value, absl::Span output) noexcept _internals::snippetSubtract(value, out); } +/** + * @brief Subtract a span from another span + * + * The output size will be the minimum of the input span and output span sizes. + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param input + * @param output + */ template void subtract(absl::Span input, absl::Span output) noexcept { @@ -432,6 +669,16 @@ namespace _internals { } } +/** + * @brief Copy a span in another + * + * The output size will be the minimum of the input span and output span sizes. + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param input + * @param output + */ template void copy(absl::Span input, absl::Span output) noexcept { @@ -456,6 +703,17 @@ namespace _internals { } } +/** + * @brief Pans a mono signal left or right + * + * The output size will be the minimum of the pan envelope span and left and right buffer span sizes. + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param panEnvelope + * @param leftBuffer + * @param rightBuffer + */ template void pan(absl::Span panEnvelope, absl::Span leftBuffer, absl::Span rightBuffer) noexcept { @@ -472,6 +730,14 @@ void pan(absl::Span panEnvelope, absl::Span leftBuffer, absl::Span void pan(absl::Span panEnvelope, absl::Span leftBuffer, absl::Span rightBuffer) noexcept; +/** + * @brief Computes the mean of a span + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param vector + * @return T + */ template T mean(absl::Span vector) noexcept { @@ -489,6 +755,14 @@ T mean(absl::Span vector) noexcept template <> float mean(absl::Span vector) noexcept; +/** + * @brief Computes the mean squared of a span + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param vector + * @return T + */ template T meanSquared(absl::Span vector) noexcept { @@ -517,6 +791,17 @@ namespace _internals { } } +/** + * @brief Computes the cumulative sum of a span. + * The first output is the same as the first input. + * + * The output size will be the minimum of the input span and output span sizes. + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param vector + * @return T + */ template void cumsum(absl::Span input, absl::Span output) noexcept { @@ -550,6 +835,17 @@ namespace _internals { } } +/** + * @brief Computes the linear interpolation coefficients for a floating point index + * and extracts the integer index of the elements to interpolate + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param floatJumps the floating point indices + * @param jumps the integer indices outputs + * @param leftCoeffs the left interpolation coefficients + * @param rightCoeffs the right interpolation coefficients + */ template void sfzInterpolationCast(absl::Span floatJumps, absl::Span jumps, absl::Span leftCoeffs, absl::Span rightCoeffs) noexcept { @@ -580,6 +876,17 @@ namespace _internals { } } +/** + * @brief Computes the differential of a span (successive differences). + * The first output is the same as the first input. + * + * The output size will be the minimum of the input span and output span sizes. + * + * @tparam T the underlying type + * @tparam SIMD use the SIMD version or the scalar version + * @param vector + * @return T + */ template void diff(absl::Span input, absl::Span output) noexcept { @@ -599,4 +906,4 @@ void diff(absl::Span input, absl::Span output) noexcept template <> void diff(absl::Span input, absl::Span output) noexcept; -} // namespace sfz \ No newline at end of file +} // namespace sfz diff --git a/src/sfizz/ScopedFTZ.h b/src/sfizz/ScopedFTZ.h index 4590c540..1db03bbc 100644 --- a/src/sfizz/ScopedFTZ.h +++ b/src/sfizz/ScopedFTZ.h @@ -21,6 +21,10 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +/** + * @brief Flush floating points to zero and disable denormals as an RAII helper. + * + */ class ScopedFTZ { public: diff --git a/src/sfizz/SfzHelpers.h b/src/sfizz/SfzHelpers.h index 87df290f..74a528f6 100644 --- a/src/sfizz/SfzHelpers.h +++ b/src/sfizz/SfzHelpers.h @@ -35,12 +35,27 @@ using CCValueArray = std::array; using CCValuePair = std::pair ; using CCNamePair = std::pair; +/** + * @brief Converts cents to a pitch ratio + * + * @tparam T + * @param cents + * @param centsPerOctave + * @return constexpr float + */ template inline constexpr float centsFactor(T cents, T centsPerOctave = 1200) { return std::pow(2.0f, static_cast(cents) / centsPerOctave); } +/** + * @brief Normalize a CC value between (T)0.0 and (T)1.0 + * + * @tparam T + * @param ccValue + * @return constexpr float + */ template inline constexpr float normalizeCC(T ccValue) { @@ -48,18 +63,40 @@ inline constexpr float normalizeCC(T ccValue) return static_cast(std::min(std::max(ccValue, static_cast(0)), static_cast(127))) / 127.0f; } +/** + * @brief Normalize a percentage between 0 and 1 + * + * @tparam T + * @param percentValue + * @return constexpr float + */ template inline constexpr float normalizePercents(T percentValue) { return std::min(std::max(static_cast(percentValue), 0.0f), 100.0f) / 100.0f; } +/** + * @brief Normalize a possibly negative percentage between -1 and 1 + * + * @tparam T + * @param percentValue + * @return constexpr float + */ template inline constexpr float normalizeNegativePercents(T percentValue) { return std::min(std::max(static_cast(percentValue), -100.0f), 100.0f) / 100.0f; } +/** + * @brief If a cc switch exists for the value, returns the value with the CC modifier, otherwise returns the value alone. + * + * @param ccValues + * @param ccSwitch + * @param value + * @return float + */ inline float ccSwitchedValue(const CCValueArray& ccValues, const absl::optional& ccSwitch, float value) noexcept { if (ccSwitch) @@ -68,6 +105,12 @@ inline float ccSwitchedValue(const CCValueArray& ccValues, const absl::optional< return value; } +/** + * @brief Convert a note in string to its equivalent midi note number + * + * @param value + * @return absl::optional + */ absl::optional readNoteValue(const absl::string_view& value); } // namespace sfz diff --git a/src/sfizz/StringViewHelpers.h b/src/sfizz/StringViewHelpers.h index 4b3ad8d0..4248908e 100644 --- a/src/sfizz/StringViewHelpers.h +++ b/src/sfizz/StringViewHelpers.h @@ -21,9 +21,25 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +/** + * @file StringViewHelpers.h + * @author Paul Ferrand (paul@ferrand.cc) + * @brief Contains some helper functions for string views + * @version 0.1 + * @date 2019-11-23 + * + * @copyright Copyright (c) 2019 + * + */ + #pragma once #include "absl/strings/string_view.h" +/** + * @brief Removes the whitespace on a string_view in place + * + * @param s + */ inline void trimInPlace(absl::string_view& s) { const auto leftPosition = s.find_first_not_of(" \r\t\n\f\v"); @@ -36,22 +52,30 @@ inline void trimInPlace(absl::string_view& s) } } +/** + * @brief Removes the whitespace on a string_view and return a new string_view + * + * @param s + * @return absl::string_view + */ inline absl::string_view trim(absl::string_view s) { - const auto leftPosition = s.find_first_not_of(" \r\t\n\f\v"); - if (leftPosition != s.npos) { - s.remove_prefix(leftPosition); - const auto rightPosition = s.find_last_not_of(" \r\t\n\f\v"); - s.remove_suffix(s.size() - rightPosition - 1); - } else { - s.remove_suffix(s.size()); - } + trimInPlace(s); return s; } constexpr uint64_t Fnv1aBasis = 0x811C9DC5; constexpr uint64_t Fnv1aPrime = 0x01000193; +/** + * @brief Compile-time hashing function to be used mostly with switch/case statements. + * + * See e.g. the Region.cpp file + * + * @param s the input string to be hashed + * @param h the hashing seed to use + * @return uint64_t + */ inline constexpr uint64_t hash(absl::string_view s, uint64_t h = Fnv1aBasis) { if (s.length() > 0) diff --git a/src/sfizz/Synth.cpp b/src/sfizz/Synth.cpp index e07a6f36..221a499d 100644 --- a/src/sfizz/Synth.cpp +++ b/src/sfizz/Synth.cpp @@ -320,6 +320,7 @@ void sfz::Synth::garbageCollect() noexcept void sfz::Synth::setSamplesPerBlock(int samplesPerBlock) noexcept { AtomicDisabler callbackDisabler { canEnterCallback }; + while (inCallback) { std::this_thread::sleep_for(1ms); } @@ -347,11 +348,10 @@ void sfz::Synth::renderBlock(AudioSpan buffer) noexcept ScopedFTZ ftz; buffer.fill(0.0f); + AtomicGuard callbackGuard { inCallback }; if (!canEnterCallback) return; - AtomicGuard callbackGuard { inCallback }; - auto tempSpan = AudioSpan(tempBuffer).first(buffer.getNumFrames()); for (auto& voice : voices) { voice->renderBlock(tempSpan); @@ -369,11 +369,10 @@ void sfz::Synth::noteOn(int delay, int channel, int noteNumber, uint8_t velocity midiState.noteOn(noteNumber, velocity); + AtomicGuard callbackGuard { inCallback }; if (!canEnterCallback) return; - AtomicGuard callbackGuard { inCallback }; - auto randValue = randNoteDistribution(Random::randomGenerator); for (auto& region : noteActivationLists[noteNumber]) { @@ -402,11 +401,10 @@ void sfz::Synth::noteOff(int delay, int channel, int noteNumber, uint8_t velocit ASSERT(noteNumber >= 0); // DBG("Received note " << noteNumber << "/" << +velocity << " OFF at time " << delay); + AtomicGuard callbackGuard { inCallback }; if (!canEnterCallback) return; - AtomicGuard callbackGuard { inCallback }; - // 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 ? sfz::getNoteVelocity(noteNumber) : velocity); @@ -435,11 +433,10 @@ void sfz::Synth::cc(int delay, int channel, int ccNumber, uint8_t ccValue) noexc ASSERT(ccNumber < 128); ASSERT(ccNumber >= 0); + AtomicGuard callbackGuard { inCallback }; if (!canEnterCallback) return; - AtomicGuard callbackGuard { inCallback }; - for (auto& voice : voices) voice->registerCC(delay, channel, ccNumber, ccValue); diff --git a/src/sfizz/Synth.h b/src/sfizz/Synth.h index 7cffeac2..546df2d0 100644 --- a/src/sfizz/Synth.h +++ b/src/sfizz/Synth.h @@ -36,38 +36,250 @@ #include namespace sfz { - +/** + * @brief This class is the core of the sfizz library. In C++ it is the main point + * of entry and in C the interface basically maps the functions of the class into + * C bindings. + * + * The JACK client provides an example of how you can use this class as an entry + * point for your own projects. Just include this header and compile against the + * static library. If you wish to use the shared library you should rather use the + * C bindings. + * + * This class derives from the Parser and provides a specific set of callbacks; see + * the Parser documentation for more precisions. + * + * The Synth object contains: + * - A set of SFZ Regions that get filled up upon parsing + * - A set of Voices that play the sounds of the regions when triggered. + * - Some singleton resources, particularly the midiState which contains the current + * midi status (note is on or off, last note velocity, current CC values, ...) + * as well as a FilePool that preloads and give access to files. + * + * The synth is callback based, in the sense that it renders audio block by block + * using the renderBlock() function. Between each call to renderBlock() you have to + * send the relevent events for the block in the form of MIDI events: noteOn(), + * noteOff(), cc(). You can also send pitchBend(), aftertouch() and bpm() + * events -- but as of 2019 they are not handled. + * + * All events have a delay information, which must be less than the size of the + * next call to renderBlock() in units of frames or samples. For example, if you + * will call to render a block of 256 samples, all the events you send to the + * synth should have a delay parameter strictly lower than 256. Events beyond 256 + * may be completely ignored by the synth as the incoming event buffer is cleared + * during the renderBlock() call. + * + * The jack_client.cpp file contains examples of the most classical usage of the + * synth and can be used as a reference. + */ class Synth : public Parser { public: + /** + * @brief Construct a new Synth object with no voices. If you want sound + * you will need to call setNumVoices() before playing. + * + */ Synth(); + /** + * @brief Construct a new Synth object with a specified number of voices. + * + * @param numVoices + */ Synth(int numVoices); + /** + * @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. + * + * @param file + * @return true + * @return false if the file was not found or no regions were loaded. + */ bool loadSfzFile(const fs::path& file) final; + /** + * @brief Get the current number of regions loaded + * + * @return int + */ int getNumRegions() const noexcept; + /** + * @brief Get the current number of groups loaded + * + * @return int + */ int getNumGroups() const noexcept; + /** + * @brief Get the current number of masters loaded + * + * @return int + */ int getNumMasters() const noexcept; + /** + * @brief Get the current number of curves loaded + * + * @return int + */ int getNumCurves() const noexcept; + /** + * @brief Get a raw view into a specific region. This is mostly used + * for testing. + * + * @param idx + * @return const Region* + */ const Region* getRegionView(int idx) const noexcept; + /** + * @brief Get a list of unknown opcodes. The lifetime of the + * string views in the code are linked to the currently loaded + * sfz file. + * + * TODO: change this to strings we don't really care about performance + * here and this hurts the C interface. + * + * @return std::set + */ std::set getUnknownOpcodes() const noexcept; + /** + * @brief Get the number of preloaded samples in the synth + * + * @return size_t + */ size_t getNumPreloadedSamples() const noexcept; + /** + * @brief Set the maximum size of the blocks for the callback. The actual + * size can be lower in each callback but should not be larger + * than this value. + * + * @param samplesPerBlock + */ void setSamplesPerBlock(int samplesPerBlock) noexcept; + /** + * @brief Set the sample rate. If you do not call it it is initialized + * to sfz::config::defaultSampleRate. + * + * @param sampleRate + */ void setSampleRate(float sampleRate) noexcept; + /** + * @brief Get the current value for the volume, in dB. + * + * @return float + */ float getVolume() const noexcept; + /** + * @brief Set the value for the volume. This value will be + * clamped within sfz::default::volumeRange. + * + * @param volume + */ void setVolume(float volume) noexcept; - void renderBlock(AudioSpan buffer) noexcept; + /** + * @brief Send a note on event to 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(). + * @param channel the midi channel for the event + * @param noteNumber the midi note number + * @param velocity the midi note velocity + */ void noteOn(int delay, int channel, int noteNumber, uint8_t velocity) noexcept; + /** + * @brief Send a note off event to 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(). + * @param channel the midi channel for the event + * @param noteNumber the midi note number + * @param velocity the midi note velocity + */ void noteOff(int delay, int channel, int noteNumber, uint8_t velocity) noexcept; + /** + * @brief Send a CC event to 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(). + * @param channel the midi channel for the event + * @param ccNumber the cc number + * @param ccValue the cc value + */ void cc(int delay, int channel, int ccNumber, uint8_t ccValue) noexcept; + /** + * @brief Send a pitch bend event to 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(). + * @param channel the midi channel for the event + * @param pitch the pitch value + */ void pitchWheel(int delay, int channel, int pitch) noexcept; + /** + * @brief Send a aftertouch event to 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(). + * @param channel the midi channel for the event + * @param aftertouch the aftertouch value + */ void aftertouch(int delay, int channel, uint8_t aftertouch) noexcept; + /** + * @brief Send a tempo event to 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(). + * @param channel the midi channel for the event + * @param secondsPerQuarter the new period of the quarter note + */ void tempo(int delay, float secondsPerQuarter) noexcept; + /** + * @brief Render an block of audio data in the buffer. This call will reset the synth + * in its waiting state for the next batch of events. The size of the block is integrated + * in the AudioSpan object. You can build an AudioSpan implicitely from a large number + * of source objects; check the AudioSpan reference for more precision. + * + * @param buffer the buffer to write the next block into; this should be a stereo buffer. + */ + void renderBlock(AudioSpan buffer) noexcept; + /** + * @brief Get the number of active voices + * + * @return int + */ int getNumActiveVoices() const noexcept; + /** + * @brief Get the total number of voices in the synth (the polyphony) + * + * @return int + */ int getNumVoices() const noexcept; + /** + * @brief Change the number of voices (the polyphony) + * + * @param numVoices + */ void setNumVoices(int numVoices) noexcept; + /** + * @brief Trigger a garbage collection, which removes the samples that are + * loaded by the FilePool after being requested by the voices. This does + * not concern the preloaded samples, only the samples loaded to be played + * fully. This function is run regularly in a background thread so normally + * you should not need to call it explicitely. + * + */ void garbageCollect() noexcept; protected: + /** + * @brief The parser callback; this is called by the parent object each time + * a new region, group, master, global, curve or control set of opcodes + * appears in the parser + * + * @param header the header for the set of opcodes + * @param members the opcode members + */ void callback(absl::string_view header, const std::vector& members) final; private: @@ -76,43 +288,89 @@ private: int numGroups { 0 }; int numMasters { 0 }; int numCurves { 0 }; + + /** + * @brief Remove all regions, resets all voices and clears everything + * to bring back the synth in its original state. + * + */ void clear(); + /** + * @brief Resets and possibly changes the number of voices (polyphony) in + * the synth. + * + * @param numVoices + */ void resetVoices(int numVoices); + /** + * @brief Helper function to dispatch opcodes + * + * @param members the opcodes of the block + */ void handleGlobalOpcodes(const std::vector& members); + /** + * @brief Helper function to dispatch opcodes + * + * @param members the opcodes of the block + */ void handleControlOpcodes(const std::vector& members); + /** + * @brief Helper function to merge all the currently active opcodes + * as set by the successive callbacks and create a new region to store + * in the synth. + * + * @param regionOpcodes the opcodes that are specific to the region + */ void buildRegion(const std::vector& regionOpcodes); + // Opcode memory; these are used to build regions, as a new region + // will integrate opcodes from the group, master and global block std::vector globalOpcodes; std::vector masterOpcodes; std::vector groupOpcodes; + // Singletons passed as references to the voices + // TODO: these should probably go in a global singleton holder along with a buffer distribution and LFO/EG stuff... FilePool filePool; MidiState midiState; + + /** + * @brief Find a voice that is not currently playing + * + * @return Voice* + */ Voice* findFreeVoice() noexcept; + // Names for the cc as set by the cc_label or cc_name opcodes std::vector ccNames; + // Default active switch if multiple keyswitchable regions are present absl::optional defaultSwitch; std::set unknownOpcodes; using RegionPtrVector = std::vector; using VoicePtrVector = std::vector; std::vector> regions; std::vector> voices; + // Views to speed up iteration over the regions and voices when events + // occur in the audio callback VoicePtrVector voiceViewArray; std::array noteActivationLists; std::array ccActivationLists; + // Internal temporary buffer AudioBuffer tempBuffer { 2, config::defaultSamplesPerBlock }; + int samplesPerBlock { config::defaultSamplesPerBlock }; float sampleRate { config::defaultSampleRate }; float volume { Default::volume }; + int numVoices { config::numVoices }; + // Distribution used to generate random value for the *rand opcodes std::uniform_real_distribution randNoteDistribution { 0, 1 }; unsigned fileTicket { 1 }; + // Atomic guards; must be used with AtomicGuard and AtomicDisabler std::atomic canEnterCallback { true }; std::atomic inCallback { false }; - int numVoices { config::numVoices }; - LEAK_DETECTOR(Synth); }; diff --git a/src/sfizz/Voice.h b/src/sfizz/Voice.h index ae58b756..59fd94ab 100644 --- a/src/sfizz/Voice.h +++ b/src/sfizz/Voice.h @@ -36,49 +36,237 @@ #include namespace sfz { +/** + * @brief The SFZ voice are the polyphony holders. They get activated by the synth + * and tasked to play a given region until the end, stopping on note-offs, off-groups + * or natural sample decay. + * + */ class Voice { public: Voice() = delete; + /** + * @brief Construct a new voice with the midistate singleton + * + * @param midiState + */ Voice(const MidiState& midiState); enum class TriggerType { NoteOn, NoteOff, CC }; + /** + * @brief Change the sample rate of the voice. This is used to compute all + * pitch related transformations so it needs to be propagated from the synth + * at all times. + * + * @param sampleRate + */ void setSampleRate(float sampleRate) noexcept; + /** + * @brief Set the expected block size. If the block size is not fixed, set an + * upper bound. The voice will adapt at each callback to the actual number of + * samples requested but this function will allocate temporary buffers that are + * needed for proper functioning. + * + * @param samplesPerBlock + */ void setSamplesPerBlock(int samplesPerBlock) noexcept; - + + /** + * @brief Start playing a region after a short delay for different triggers (note on, off, cc) + * + * @param region + * @param delay + * @param channel + * @param number + * @param value + * @param triggerType + */ void startVoice(Region* region, int delay, int channel, int number, uint8_t value, TriggerType triggerType) noexcept; + /** + * @brief Tells the voice that it should expect to receive a file at some point using the + * setFileData() function. The ticket is a unique identifier that will prevent the file data + * to be set "too late"; if the voice receives the file for an older ticket, it will discard + * it. + * + * @param ticket + */ void expectFileData(unsigned ticket); + /** + * @brief Sets the file data for a given ticket. The voice can freely release and destroy the + * shared pointer, as it will be garbage collected by the file pool afterwards. + * + * @param file + * @param ticket + */ void setFileData(std::shared_ptr> file, unsigned ticket) noexcept; + /** + * @brief Register a note-off event; this may trigger a release. + * + * @param delay + * @param channel + * @param noteNumber + * @param velocity + */ void registerNoteOff(int delay, int channel, int noteNumber, uint8_t velocity) noexcept; + /** + * @brief Register a CC event; this may trigger a release. If the voice is playing and its + * region has CC modifiers, it will use this value to compute the CC envelope to apply to the + * parameter. + * + * @param delay + * @param channel + * @param ccNumber + * @param ccValue + */ void registerCC(int delay, int channel, int ccNumber, uint8_t ccValue) noexcept; + /** + * @brief Register a pitch wheel event; for now this does nothing + * + * @param delay + * @param channel + * @param pitch + */ void registerPitchWheel(int delay, int channel, int pitch) noexcept; + /** + * @brief Register an aftertouch event; for now this does nothing + * + * @param delay + * @param channel + * @param aftertouch + */ void registerAftertouch(int delay, int channel, uint8_t aftertouch) noexcept; + /** + * @brief Register a tempo event; for now this does nothing + * + * @param delay + * @param channel + * @param pitch + */ void registerTempo(int delay, float secondsPerQuarter) noexcept; + /** + * @brief Checks if the voice should be offed by another starting in the group specified. + * This will trigger the release if true. + * + * @param delay + * @param group + * @return true + * @return false + */ bool checkOffGroup(int delay, uint32_t group) noexcept; + /** + * @brief Render a block of data for this voice into the span + * + * @param buffer + */ void renderBlock(AudioSpan buffer) noexcept; + /** + * @brief Is the voice free? + * + * @return true + * @return false + */ bool isFree() const noexcept; + /** + * @brief Can the voice be "stolen" and reused (i.e. is it releasing) + * + * @return true + * @return false + */ bool canBeStolen() const noexcept; + /** + * @brief Get the number that triggered the voice (note number or cc number) + * + * @return int + */ int getTriggerNumber() const noexcept; + /** + * @brief Get the channel that triggered the voice + * + * @return int + */ int getTriggerChannel() const noexcept; + /** + * @brief Get the value that triggered the voice (note velocity or cc value) + * + * @return uint8_t + */ uint8_t getTriggerValue() const noexcept; + /** + * @brief Get the type of trigger + * + * @return TriggerType + */ TriggerType getTriggerType() const noexcept; + /** + * @brief Reset the voice to its initial values + * + */ void reset() noexcept; + /** + * @brief Clear the loaded file data if it's not useful anymore + * + */ void garbageCollect() noexcept; + /** + * @brief Get the mean squared power of the last rendered block. This is used + * to determine which voice to steal if there are too many notes flying around. + * + * @return float + */ float getMeanSquaredAverage() const noexcept; + /** + * @brief Get the position of the voice in the source, in samples + * + * @return uint32_t + */ uint32_t getSourcePosition() const noexcept; private: + /** + * @brief Fill a span with data from a file source. This is the first step + * in rendering each block of data. + * + * @param buffer + */ void fillWithData(AudioSpan buffer) noexcept; + /** + * @brief Fill a span with data from a generator source. This is the first step + * in rendering each block of data. + * + * @param buffer + */ void fillWithGenerator(AudioSpan buffer) noexcept; + /** + * @brief Computes the values for the envelope depending on the note or CC number and the velocity/cc value + * + * @param delay + * @param velocity + */ void prepareEGEnvelope(int delay, uint8_t velocity) noexcept; + /** + * @brief The function processing a mono sample source + * + * @param buffer + */ void processMono(AudioSpan buffer) noexcept; + /** + * @brief The function processing a stereo sample source + * + * @param buffer + */ void processStereo(AudioSpan buffer) noexcept; + /** + * @brief Release the voice after a given delay + * + * @param delay + */ void release(int delay) noexcept; Region* region { nullptr }; @@ -137,4 +325,4 @@ private: LEAK_DETECTOR(Voice); }; -} // namespace sfz \ No newline at end of file +} // namespace sfz