Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@paulfd
Copy link
Member

@paulfd paulfd commented Mar 10, 2020

For now it's more C++11 compatibility. For reference from #110 here is @falkTX patch with some of the [[fallthrough]] and [[maybe_unused]] things to remove too!

diff --git a/src/sfizz/Buffer.h b/src/sfizz/Buffer.h
index 757fe9c..e37b634 100644
--- a/src/sfizz/Buffer.h
+++ b/src/sfizz/Buffer.h
@@ -274,9 +274,9 @@ public:
         return counter;
     }
 private:
-    static constexpr auto AlignmentMask { Alignment - 1 };
-    static constexpr auto TypeAlignment { Alignment / sizeof(value_type) };
-    static constexpr auto TypeAlignmentMask { TypeAlignment - 1 };
+    static constexpr auto AlignmentMask = Alignment - 1U;
+    static constexpr auto TypeAlignment = Alignment / sizeof(value_type);
+    static constexpr auto TypeAlignmentMask = TypeAlignment - 1U;
     static_assert(std::is_arithmetic<value_type>::value, "Type should be arithmetic");
     static_assert(Alignment == 0 || Alignment == 4 || Alignment == 8 || Alignment == 16, "Bad alignment value");
     static_assert(TypeAlignment * sizeof(value_type) == Alignment, "The alignment does not appear to be divided by the size of the Type");
diff --git a/src/sfizz/EGDescription.h b/src/sfizz/EGDescription.h
index cc65551..ceba155 100644
--- a/src/sfizz/EGDescription.h
+++ b/src/sfizz/EGDescription.h
@@ -134,9 +134,12 @@ struct EGDescription
      * @param velocity
      * @return float
      */
-    float getStart(const SfzCCArray &ccValues, uint8_t velocity [[maybe_unused]]) const noexcept
+    float getStart(const SfzCCArray &ccValues, uint8_t velocity) const noexcept
     {
         return Default::egPercentRange.clamp(ccSwitchedValue(ccValues, ccStart, start));
+
+        // unused
+        (void)velocity;
     }
     /**
      * @brief Get the sustain level with possibly a CC modifier and a velocity modifier
diff --git a/src/sfizz/MathHelpers.h b/src/sfizz/MathHelpers.h
index aa99bec..60aec45 100644
--- a/src/sfizz/MathHelpers.h
+++ b/src/sfizz/MathHelpers.h
@@ -127,9 +127,7 @@ inline float midiNoteFrequency(const int noteNumber)
 template<class T>
 constexpr T clamp( T v, T lo, T hi )
 {
-    v = std::min(v, hi);
-    v = std::max(v, lo);
-    return v;
+    return std::max(std::min(v, hi), lo);
 }
 
 template<int Increment = 1, class T>
@@ -152,17 +150,17 @@ constexpr ValueType linearInterpolation(ValueType left, ValueType right, ValueTy
 }
 
 template <class Type>
-constexpr Type pi { static_cast<Type>(3.141592653589793238462643383279502884) };
+constexpr Type pi() { return static_cast<Type>(3.141592653589793238462643383279502884); };
 template <class Type>
-constexpr Type twoPi { static_cast<Type>(2) * pi<Type> };
+constexpr Type twoPi() { return static_cast<Type>(2) * pi<Type>(); };
 template <class Type>
-constexpr Type piTwo { pi<Type> / static_cast<Type>(2) };
+constexpr Type piTwo() { return pi<Type>() / static_cast<Type>(2); };
 template <class Type>
-constexpr Type piFour { pi<Type> / static_cast<Type>(4) };
+constexpr Type piFour() { return pi<Type>() / static_cast<Type>(4); };
 template <class Type>
-constexpr Type sqrtTwo { static_cast<Type>(1.414213562373095048801688724209698078569671875376948073176) };
+constexpr Type sqrtTwo() { return static_cast<Type>(1.414213562373095048801688724209698078569671875376948073176); };
 template <class Type>
-constexpr Type sqrtTwoInv { static_cast<Type>(0.707106781186547524400844362104849039284835937688474036588) };
+constexpr Type sqrtTwoInv() { return static_cast<Type>(0.707106781186547524400844362104849039284835937688474036588); };
 
 /**
    @brief A fraction which is parameterized by integer type
diff --git a/src/sfizz/MidiState.h b/src/sfizz/MidiState.h
index afba37c..e48e776 100644
--- a/src/sfizz/MidiState.h
+++ b/src/sfizz/MidiState.h
@@ -134,13 +134,13 @@ private:
      * @brief Stores the note on times.
      *
      */
-	MidiNoteArray<NoteOnTime> noteOnTimes { };
+	MidiNoteArray<NoteOnTime> noteOnTimes;
     /**
      * @brief Stores the velocity of the note ons for currently
      * depressed notes.
      *
      */
-	MidiNoteArray<uint8_t> lastNoteVelocities { };
+	MidiNoteArray<uint8_t> lastNoteVelocities;
     /**
      * @brief Current known values for the CCs.
      *
diff --git a/src/sfizz/Range.h b/src/sfizz/Range.h
index acb88c6..27fec5d 100644
--- a/src/sfizz/Range.h
+++ b/src/sfizz/Range.h
@@ -39,7 +39,7 @@ public:
     // }
     constexpr Range(Type start, Type end) noexcept
         : _start(start)
-        , _end(std::max(start, end))
+        , _end(start > end ? start : end)
     {
     }
     ~Range() = default;
diff --git a/src/sfizz/SIMDHelpers.h b/src/sfizz/SIMDHelpers.h
index f4c5a2d..678a985 100644
--- a/src/sfizz/SIMDHelpers.h
+++ b/src/sfizz/SIMDHelpers.h
@@ -734,7 +734,7 @@ namespace _internals {
         int i = 0;
 
         for (; i < panSize; ++i)
-            pan[i] = std::cos(i * (piTwo<double> / (panSize - 1)));
+            pan[i] = std::cos(i * (piTwo<double>() / (panSize - 1)));
 
         for (; i < static_cast<int>(pan.size()); ++i)
             pan[i] = pan[panSize - 1];
diff --git a/src/sfizz/SfzHelpers.h b/src/sfizz/SfzHelpers.h
index 1e590d1..fb8ce05 100644
--- a/src/sfizz/SfzHelpers.h
+++ b/src/sfizz/SfzHelpers.h
@@ -81,7 +81,7 @@ constexpr float normalizePercents(T percentValue)
  * @param bendValue
  * @return constexpr float
  */
-constexpr float normalizeBend(float bendValue)
+inline float normalizeBend(float bendValue)
 {
     return std::min(std::max(bendValue, -8191.0f), 8191.0f) / 8191.0f;
 }
@@ -199,7 +199,7 @@ constexpr void addToBase(T& base, T modifier)
  * @param base
  * @param modifier
  */
-constexpr void multiplyByCents(float& base, int modifier)
+inline void multiplyByCents(float& base, int modifier)
 {
     base *= centsFactor(modifier);
 }
diff --git a/src/sfizz/StringViewHelpers.h b/src/sfizz/StringViewHelpers.h
index 0cc49d3..7e198e8 100644
--- a/src/sfizz/StringViewHelpers.h
+++ b/src/sfizz/StringViewHelpers.h
@@ -61,8 +61,5 @@ constexpr uint64_t Fnv1aPrime = 0x01000193;
  */
 constexpr uint64_t hash(absl::string_view s, uint64_t h = Fnv1aBasis)
 {
-    if (s.length() > 0)
-        return hash( { s.data() + 1, s.length() - 1 }, (h ^ s.front()) * Fnv1aPrime );
-
-    return h;
+    return s.empty() ? h : hash( { s.data() + 1, s.length() - 1 }, (h ^ s.front()) * Fnv1aPrime );
 }
diff --git a/src/sfizz/Synth.cpp b/src/sfizz/Synth.cpp
index 0c3b3f8..cf024a5 100644
--- a/src/sfizz/Synth.cpp
+++ b/src/sfizz/Synth.cpp
@@ -156,7 +156,7 @@ void sfz::Synth::handleControlOpcodes(const std::vector<Opcode>& members)
         const auto backParameter = member.backParameter();
         switch (member.lettersOnlyHash) {
         case hash("Set_cc"):
-            [[fallthrough]];
+            // fall-through
         case hash("set_cc"):
             if (backParameter && Default::ccNumberRange.containsWithEnd(*backParameter)) {
                 const auto ccValue = readOpcode(member.value, Default::ccValueRange).value_or(0);
@@ -164,13 +164,13 @@ void sfz::Synth::handleControlOpcodes(const std::vector<Opcode>& members)
             }
             break;
         case hash("Label_cc"):
-            [[fallthrough]];
+            // fall-through
         case hash("label_cc"):
             if (backParameter && Default::ccNumberRange.containsWithEnd(*backParameter))
                 ccNames.emplace_back(*backParameter, std::string(member.value));
             break;
         case hash("Default_path"):
-            [[fallthrough]];
+            // fall-through
         case hash("default_path"):
             defaultPath = absl::StrReplaceAll(trim(member.value), { { "\\", "/" } });
             DBG("Changing default sample path to " << defaultPath);
@@ -273,7 +273,7 @@ bool sfz::Synth::loadSfzFile(const fs::path& file)
                 region->isStereo = true;
 
             // TODO: adjust with LFO targets
-            const auto maxOffset { region->offset + region->offsetRandom };
+            const uint maxOffset { region->offset + region->offsetRandom };
             if (!resources.filePool.preloadFile(region->sample, maxOffset))
                 removeCurrentRegion();
         }
@@ -363,7 +363,7 @@ sfz::Voice* sfz::Synth::findFreeVoice() noexcept
 
 int sfz::Synth::getNumActiveVoices() const noexcept
 {
-    auto activeVoices { 0 };
+    int activeVoices { 0 };
     for (const auto& voice : voices) {
         if (!voice->isFree())
             activeVoices++;
@@ -465,7 +465,7 @@ void sfz::Synth::noteOn(int delay, int noteNumber, uint8_t velocity) noexcept
     noteOnDispatch(delay, noteNumber, velocity);
 }
 
-void sfz::Synth::noteOff(int delay, int noteNumber, uint8_t velocity [[maybe_unused]]) noexcept
+void sfz::Synth::noteOff(int delay, int noteNumber, uint8_t velocity) noexcept
 {
     ASSERT(noteNumber < 128);
     ASSERT(noteNumber >= 0);
@@ -485,7 +485,10 @@ void sfz::Synth::noteOff(int delay, int noteNumber, uint8_t velocity [[maybe_unu
     for (auto& voice : voices)
         voice->registerNoteOff(delay, noteNumber, replacedVelocity);
 
-    noteOffDispatch(delay, noteNumber, replacedVelocity);
+    return noteOffDispatch(delay, noteNumber, replacedVelocity);
+
+    // unused
+    (void)velocity;
 }
 
 void sfz::Synth::noteOffDispatch(int delay, int noteNumber, uint8_t velocity) noexcept

class AudioBuffer {
public:
using value_type = std::remove_cv_t<Type>;
using value_type = typename std::remove_cv<Type>::type;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These _t type traits are in abseil.


for (; i < panSize; ++i)
pan[i] = std::cos(i * (piTwo<double> / (panSize - 1)));
pan[i] = std::cos(i * (twoPi<double>() / (panSize - 1)));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You introduce an error here.

* @param modifier
*/
constexpr void multiplyByCents(float& base, int modifier)
void multiplyByCents(float& base, int modifier)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should be inline, otherwise this function will be defined&used more than once

@falkTX
Copy link
Contributor

falkTX commented Mar 10, 2020

very nice! almost there. I am fixing a few things.
the chrono "1ms" style of numbers is not supported though

@falkTX
Copy link
Contributor

falkTX commented Mar 10, 2020

Fixing those now, will post a patch here soon

@paulfd
Copy link
Member Author

paulfd commented Mar 10, 2020

awww I fixed them too xD there were autos in lambdas too, and since I'm only setting CXX STANDARD to eleven I don't have the possible errors with [[fallthrough]] and the likes yet.

@paulfd
Copy link
Member Author

paulfd commented Mar 10, 2020

I'll wait for your patch and see if it matches 🙂

@falkTX
Copy link
Contributor

falkTX commented Mar 10, 2020

some of the stuff I dont know how to handle. still working on it, but this is what I have right now:

diff --git a/src/sfizz/ADSREnvelope.cpp b/src/sfizz/ADSREnvelope.cpp
index e795d53..4a20b27 100644
--- a/src/sfizz/ADSREnvelope.cpp
+++ b/src/sfizz/ADSREnvelope.cpp
@@ -11,19 +11,19 @@
 
 namespace sfz {
 
+constexpr int secondsToSamples(const float sampleRate, const float timeInSeconds) {
+    return static_cast<int>(timeInSeconds * sampleRate);
+};
+
 template <class Type>
 void ADSREnvelope<Type>::reset(const Region& region, const MidiState& state, int delay, uint8_t velocity, float sampleRate) noexcept
 {
-    auto secondsToSamples = [sampleRate](auto timeInSeconds) {
-        return static_cast<int>(timeInSeconds * sampleRate);
-    };
-
     const auto ccArray = state.getCCArray();
-    this->delay = delay + secondsToSamples(region.amplitudeEG.getDelay(ccArray, velocity));
-    this->attack = secondsToSamples(region.amplitudeEG.getAttack(ccArray, velocity));
-    this->decay = secondsToSamples(region.amplitudeEG.getDecay(ccArray, velocity));
-    this->release = secondsToSamples(region.amplitudeEG.getRelease(ccArray, velocity));
-    this->hold = secondsToSamples(region.amplitudeEG.getHold(ccArray, velocity));
+    this->delay = delay + secondsToSamples(sampleRate, region.amplitudeEG.getDelay(ccArray, velocity));
+    this->attack = secondsToSamples(sampleRate, region.amplitudeEG.getAttack(ccArray, velocity));
+    this->decay = secondsToSamples(sampleRate, region.amplitudeEG.getDecay(ccArray, velocity));
+    this->release = secondsToSamples(sampleRate, region.amplitudeEG.getRelease(ccArray, velocity));
+    this->hold = secondsToSamples(sampleRate, region.amplitudeEG.getHold(ccArray, velocity));
     this->peak = 1.0;
     this->sustain =  normalizePercents(region.amplitudeEG.getSustain(ccArray, velocity));
     this->start = this->peak * normalizePercents(region.amplitudeEG.getStart(ccArray, velocity));
diff --git a/src/sfizz/EQPool.cpp b/src/sfizz/EQPool.cpp
index f38e874..77fbf99 100644
--- a/src/sfizz/EQPool.cpp
+++ b/src/sfizz/EQPool.cpp
@@ -3,7 +3,6 @@
 #include <thread>
 #include "absl/algorithm/container.h"
 #include "SIMDHelpers.h"
-using namespace std::chrono_literals;
 
 sfz::EQHolder::EQHolder(const MidiState& state)
 :midiState(state)
@@ -113,7 +112,7 @@ size_t sfz::EQPool::setnumEQs(size_t numEQs)
     AtomicDisabler disabler { canGiveOutEQs };
 
     while(givingOutEQs)
-        std::this_thread::sleep_for(1ms);
+        std::this_thread::sleep_for(std::chrono::milliseconds(1));
 
     auto eqIterator = eqs.begin();
     auto eqSentinel = eqs.rbegin();
diff --git a/src/sfizz/EventEnvelopes.cpp b/src/sfizz/EventEnvelopes.cpp
index e42abcd..78bd708 100644
--- a/src/sfizz/EventEnvelopes.cpp
+++ b/src/sfizz/EventEnvelopes.cpp
@@ -47,15 +47,18 @@ void EventEnvelope<Type>::registerEvent(int timestamp, Type inputValue)
         events.emplace_back(timestamp, function(inputValue));
 }
 
+template <class Type>
+constexpr bool c_stable_sorter(const std::pair<int, Type>& lhs, const std::pair<int, Type>& rhs) {
+    return lhs.first < rhs.first;
+}
+
 template <class Type>
 void EventEnvelope<Type>::prepareEvents(int blockLength)
 {
     if (resetEvents)
         clear();
 
-    absl::c_stable_sort(events, [](const auto& lhs, const auto& rhs) {
-        return lhs.first < rhs.first;
-    });
+    absl::c_stable_sort(events, c_stable_sorter<Type>);
 
     auto eventIt = events.begin();
     while (eventIt < events.end()) {
diff --git a/src/sfizz/FilePool.cpp b/src/sfizz/FilePool.cpp
index a716d32..7ddf4ba 100644
--- a/src/sfizz/FilePool.cpp
+++ b/src/sfizz/FilePool.cpp
@@ -35,7 +35,6 @@
 #include <memory>
 #include <sndfile.hh>
 #include <thread>
-using namespace std::chrono_literals;
 
 template <class T>
 void readBaseFile(SndfileHandle& sndFile, sfz::AudioBuffer<T>& output, uint32_t numFrames)
@@ -57,13 +56,13 @@ void readBaseFile(SndfileHandle& sndFile, sfz::AudioBuffer<T>& output, uint32_t
 template <class T>
 std::unique_ptr<sfz::AudioBuffer<T>> readFromFile(SndfileHandle& sndFile, uint32_t numFrames, sfz::Oversampling factor)
 {
-    auto baseBuffer = std::make_unique<sfz::AudioBuffer<T>>();
+    auto baseBuffer = absl::make_unique<sfz::AudioBuffer<T>>();
     readBaseFile(sndFile, *baseBuffer, numFrames);
 
     if (factor == sfz::Oversampling::x1)
         return baseBuffer;
 
-    auto outputBuffer = std::make_unique<sfz::AudioBuffer<T>>(sndFile.channels(), numFrames * static_cast<int>(factor));
+    auto outputBuffer = absl::make_unique<sfz::AudioBuffer<T>>(sndFile.channels(), numFrames * static_cast<int>(factor));
     sfz::Oversampler oversampler { factor };
     oversampler.stream(*baseBuffer, *outputBuffer);
     return outputBuffer;
@@ -272,7 +271,7 @@ void sfz::FilePool::tryToClearPromises()
     AtomicDisabler disabler { canAddPromisesToClear };
 
     while (addingPromisesToClear)
-        std::this_thread::sleep_for(1ms);
+        std::this_thread::sleep_for(std::chrono::milliseconds(1));
 
     for (auto& promise: promisesToClear) {
         if (promise->dataReady)
@@ -284,7 +283,7 @@ void sfz::FilePool::clearingThread()
 {
     while (!quitThread) {
         tryToClearPromises();
-        std::this_thread::sleep_for(50ms);
+        std::this_thread::sleep_for(std::chrono::milliseconds(50));
     }
 }
 
@@ -302,7 +301,7 @@ void sfz::FilePool::loadingThread() noexcept
         }
 
         if (!promiseQueue.try_pop(promise)) {
-            std::this_thread::sleep_for(1ms);
+            std::this_thread::sleep_for(std::chrono::milliseconds(1));
             continue;
         }
 
@@ -326,7 +325,7 @@ void sfz::FilePool::loadingThread() noexcept
 
         while (!filledPromiseQueue.try_push(promise)) {
             DBG("[sfizz] Error enqueuing the promise for " << promise->filename << " in the filledPromiseQueue");
-            std::this_thread::sleep_for(1ms);
+            std::this_thread::sleep_for(std::chrono::milliseconds(1));
         }
 
         promise.reset();
@@ -412,7 +411,7 @@ void sfz::FilePool::emptyFileLoadingQueues() noexcept
 {
     emptyQueue = true;
     while (emptyQueue)
-        std::this_thread::sleep_for(1ms);
+        std::this_thread::sleep_for(std::chrono::microseconds(100));
 }
 
 void sfz::FilePool::waitForBackgroundLoading() noexcept
@@ -421,11 +420,11 @@ void sfz::FilePool::waitForBackgroundLoading() noexcept
     // of the files we need to load still.
     // Spinlocking on the size of the background queue
     while (!promiseQueue.was_empty()){
-        std::this_thread::sleep_for(0.1ms);
+        std::this_thread::sleep_for(std::chrono::microseconds(100));
     }
 
     // Spinlocking on the threads possibly logging in the background
     while (threadsLoading > 0) {
-        std::this_thread::sleep_for(0.1ms);
+        std::this_thread::sleep_for(std::chrono::microseconds(100));
     }
 }
diff --git a/src/sfizz/FilterPool.cpp b/src/sfizz/FilterPool.cpp
index 354486d..0b600ec 100644
--- a/src/sfizz/FilterPool.cpp
+++ b/src/sfizz/FilterPool.cpp
@@ -4,7 +4,6 @@
 #include "AtomicGuard.h"
 #include <thread>
 #include <chrono>
-using namespace std::chrono_literals;
 
 sfz::FilterHolder::FilterHolder(const MidiState& midiState)
 : midiState(midiState)
@@ -113,7 +112,7 @@ size_t sfz::FilterPool::setNumFilters(size_t numFilters)
     AtomicDisabler disabler { canGiveOutFilters };
 
     while(givingOutFilters)
-        std::this_thread::sleep_for(1ms);
+        std::this_thread::sleep_for(std::chrono::milliseconds(1));
 
     auto filterIterator = filters.begin();
     auto filterSentinel = filters.rbegin();
diff --git a/src/sfizz/MidiState.h b/src/sfizz/MidiState.h
index b629c88..badb0e1 100644
--- a/src/sfizz/MidiState.h
+++ b/src/sfizz/MidiState.h
@@ -134,13 +134,13 @@ private:
      * @brief Stores the note on times.
      *
      */
-	MidiNoteArray<NoteOnTime> noteOnTimes { };
+	MidiNoteArray<NoteOnTime> noteOnTimes;
     /**
      * @brief Stores the velocity of the note ons for currently
      * depressed notes.
      *
      */
-	MidiNoteArray<uint8_t> lastNoteVelocities { };
+	MidiNoteArray<uint8_t> lastNoteVelocities;
     /**
      * @brief Current known values for the CCs.
      *
diff --git a/src/sfizz/Oversampler.cpp b/src/sfizz/Oversampler.cpp
index b2b986a..2a98fc0 100644
--- a/src/sfizz/Oversampler.cpp
+++ b/src/sfizz/Oversampler.cpp
@@ -105,7 +105,7 @@ void sfz::Oversampler::stream(const sfz::AudioBuffer<float>& input, sfz::AudioBu
     {
         // std::cout << "Input frames: " << inputFrameCounter << "/" << numFrames << '\n';
         const auto thisChunkSize = std::min(chunkSize, numFrames - inputFrameCounter);
-        const auto outputChunkSize { thisChunkSize * static_cast<int>(factor) };
+        const auto outputChunkSize = thisChunkSize * static_cast<int>(factor);
         for (size_t chanIdx = 0; chanIdx < numChannels; chanIdx++) {
             const auto inputChunk = input.getSpan(chanIdx).subspan(inputFrameCounter, thisChunkSize);
             const auto outputChunk = output.getSpan(chanIdx).subspan(outputFrameCounter, outputChunkSize);
diff --git a/src/sfizz/Synth.cpp b/src/sfizz/Synth.cpp
index 06b075a..e2c7ea0 100644
--- a/src/sfizz/Synth.cpp
+++ b/src/sfizz/Synth.cpp
@@ -342,7 +342,7 @@ bool sfz::Synth::loadSfzFile(const fs::path& file)
                 region->isStereo = true;
 
             // TODO: adjust with LFO targets
-            const auto maxOffset { region->offset + region->offsetRandom };
+            const auto maxOffset = region->offset + region->offsetRandom;
             if (!resources.filePool.preloadFile(region->sample, maxOffset))
                 removeCurrentRegion();
         }
@@ -432,7 +432,7 @@ sfz::Voice* sfz::Synth::findFreeVoice() noexcept
 
 int sfz::Synth::getNumActiveVoices() const noexcept
 {
-    auto activeVoices { 0 };
+    auto activeVoices = 0;
     for (const auto& voice : voices) {
         if (!voice->isFree())
             activeVoices++;
diff --git a/src/sfizz/Voice.cpp b/src/sfizz/Voice.cpp
index f92ec40..149003c 100644
--- a/src/sfizz/Voice.cpp
+++ b/src/sfizz/Voice.cpp
@@ -45,7 +45,7 @@ void sfz::Voice::startVoice(Region* region, int delay, int number, uint8_t value
     pitchRatio = region->getBasePitchVariation(number, value);
 
     baseVolumedB = region->getBaseVolumedB(number);
-    auto volumedB { baseVolumedB };
+    auto volumedB = baseVolumedB;
     if (region->volumeCC)
         volumedB += normalizeCC(resources.midiState.getCCValue(region->volumeCC->cc)) * region->volumeCC->value;
     volumeEnvelope.reset(db2mag(Default::volumeRange.clamp(volumedB)));
@@ -63,19 +63,19 @@ void sfz::Voice::startVoice(Region* region, int delay, int number, uint8_t value
     crossfadeEnvelope.reset(Default::normalizedRange.clamp(crossfadeGain));
 
     basePan = normalizePercents(region->pan);
-    auto pan { basePan };
+    auto pan = basePan;
     if (region->panCC)
         pan += normalizeCC(resources.midiState.getCCValue(region->panCC->cc)) * normalizePercents(region->panCC->value);
     panEnvelope.reset(Default::symmetricNormalizedRange.clamp(pan));
 
     basePosition = normalizePercents(region->position);
-    auto position { basePosition };
+    auto position = basePosition;
     if (region->positionCC)
         position += normalizeCC(resources.midiState.getCCValue(region->positionCC->cc)) * normalizePercents(region->positionCC->value);
     positionEnvelope.reset(Default::symmetricNormalizedRange.clamp(position));
 
     baseWidth = normalizePercents(region->width);
-    auto width { baseWidth };
+    auto width = baseWidth;
     if (region->widthCC)
         width += normalizeCC(resources.midiState.getCCValue(region->widthCC->cc)) * normalizePercents(region->widthCC->value);
     widthEnvelope.reset(Default::symmetricNormalizedRange.clamp(width));

@paulfd
Copy link
Member Author

paulfd commented Mar 10, 2020

What's the issues with the auto volumedB { baseVolumedB }; ?

@paulfd
Copy link
Member Author

paulfd commented Mar 10, 2020

Here's the patches I made if you need inspiration. If you're on it it's better that you do it since you'll have the gcc-4.9 specific errors on top of what I have.

https://pastebin.com/S2Fz2Lr6

@paulfd
Copy link
Member Author

paulfd commented Mar 10, 2020

In the meanwhile I will try to propose the atomic_queue changes upstream.

@falkTX
Copy link
Contributor

falkTX commented Mar 10, 2020

What's the issues with the auto volumedB { baseVolumedB }; ?

GCC thinks you want a initializer-list as the auto, which leads to errors.
It misinterprets the bracket as an initializer.
By using =, we force it to be a single value instead of a list.

Thanks for the patch. I got libsfizz.so built, though with random stuff commented out that I did not know how to fix yet.

@falkTX
Copy link
Contributor

falkTX commented Mar 10, 2020

this one I dont know how to fix, we need to force C99 mode for the C code.

lv2/sfizz.c:35:
lv2/./lv2/atom/util.h: In function 'lv2_atom_object_query':
lv2/./lv2/atom/util.h:336:2: error: 'for' loop initial declarations are only allowed in C99 or C11 mode
  for (LV2_Atom_Object_Query* q = query; q->key; ++q) {

@paulfd
Copy link
Member Author

paulfd commented Mar 10, 2020

Well since the error is in the LV2 headers, you should have them somewhere. @redtide do you remember why we have the lv2 headers in-tree? Did we use something specific in a latest release?

@jpcima
Copy link
Collaborator

jpcima commented Mar 10, 2020

Some older LV2 distributions don't provide lv2_util.

@falkTX
Copy link
Contributor

falkTX commented Mar 10, 2020

We just need a way to specify the language spec.
On newer GCC, it is set to C99 by default, but it is not the case for older versions.
But anyway, should be simple enough. I think we this I will get the plugin built

@falkTX
Copy link
Contributor

falkTX commented Mar 10, 2020

Ok, here follows a patch, let me know if I should upload it somewhere else.
(I imported all your changes, except for the ones meant for tests)
Only atomic_queue.h changes are needed after this point. Do you have a diff for that?

diff --git a/lv2/CMakeLists.txt b/lv2/CMakeLists.txt
index aa732cb..240298f 100644
--- a/lv2/CMakeLists.txt
+++ b/lv2/CMakeLists.txt
@@ -3,6 +3,9 @@ set (LV2PLUGIN_PRJ_NAME "${PROJECT_NAME}_lv2")
 # Set the build directory as <build_dir>/lv2/<plugin_name>.lv2/
 set (PROJECT_BINARY_DIR "${PROJECT_BINARY_DIR}/${PROJECT_NAME}.lv2")
 
+# C99 or higher is needed
+set(CMAKE_C_STANDARD 99)
+
 # LV2 plugin specific settings
 include (LV2Config)
 
diff --git a/src/sfizz/ADSREnvelope.cpp b/src/sfizz/ADSREnvelope.cpp
index e795d53..edc708a 100644
--- a/src/sfizz/ADSREnvelope.cpp
+++ b/src/sfizz/ADSREnvelope.cpp
@@ -14,7 +14,7 @@ namespace sfz {
 template <class Type>
 void ADSREnvelope<Type>::reset(const Region& region, const MidiState& state, int delay, uint8_t velocity, float sampleRate) noexcept
 {
-    auto secondsToSamples = [sampleRate](auto timeInSeconds) {
+    auto secondsToSamples = [sampleRate](Type timeInSeconds) {
         return static_cast<int>(timeInSeconds * sampleRate);
     };
 
diff --git a/src/sfizz/EQPool.cpp b/src/sfizz/EQPool.cpp
index f38e874..77fbf99 100644
--- a/src/sfizz/EQPool.cpp
+++ b/src/sfizz/EQPool.cpp
@@ -3,7 +3,6 @@
 #include <thread>
 #include "absl/algorithm/container.h"
 #include "SIMDHelpers.h"
-using namespace std::chrono_literals;
 
 sfz::EQHolder::EQHolder(const MidiState& state)
 :midiState(state)
@@ -113,7 +112,7 @@ size_t sfz::EQPool::setnumEQs(size_t numEQs)
     AtomicDisabler disabler { canGiveOutEQs };
 
     while(givingOutEQs)
-        std::this_thread::sleep_for(1ms);
+        std::this_thread::sleep_for(std::chrono::milliseconds(1));
 
     auto eqIterator = eqs.begin();
     auto eqSentinel = eqs.rbegin();
diff --git a/src/sfizz/Effects.cpp b/src/sfizz/Effects.cpp
index 512f2b5..efbb5b6 100644
--- a/src/sfizz/Effects.cpp
+++ b/src/sfizz/Effects.cpp
@@ -40,21 +40,21 @@ std::unique_ptr<Effect> EffectFactory::makeEffect(absl::Span<const Opcode> membe
 
     if (!opcode) {
         DBG("The effect does not specify a type");
-        return std::make_unique<sfz::fx::Nothing>();
+        return absl::make_unique<sfz::fx::Nothing>();
     }
 
     const absl::string_view type = opcode->value;
 
-    const auto it = absl::c_find_if(_entries, [&](auto&& entry) { return entry.name == type; });
+    const auto it = absl::c_find_if(_entries, [&](const FactoryEntry& entry) { return entry.name == type; });
     if (it == _entries.end()) {
         DBG("Unsupported effect type: " << type);
-        return std::make_unique<sfz::fx::Nothing>();
+        return absl::make_unique<sfz::fx::Nothing>();
     }
 
     auto fx = it->make(members);
     if (!fx) {
         DBG("Could not instantiate effect of type: " << type);
-        return std::make_unique<sfz::fx::Nothing>();
+        return absl::make_unique<sfz::fx::Nothing>();
     }
 
     return fx;
diff --git a/src/sfizz/EventEnvelopes.cpp b/src/sfizz/EventEnvelopes.cpp
index e42abcd..c64a541 100644
--- a/src/sfizz/EventEnvelopes.cpp
+++ b/src/sfizz/EventEnvelopes.cpp
@@ -53,7 +53,7 @@ void EventEnvelope<Type>::prepareEvents(int blockLength)
     if (resetEvents)
         clear();
 
-    absl::c_stable_sort(events, [](const auto& lhs, const auto& rhs) {
+    absl::c_stable_sort(events, [](const std::pair<int, Type>& lhs, const std::pair<int, Type>& rhs) {
         return lhs.first < rhs.first;
     });
 
diff --git a/src/sfizz/FilePool.cpp b/src/sfizz/FilePool.cpp
index a716d32..f240d3d 100644
--- a/src/sfizz/FilePool.cpp
+++ b/src/sfizz/FilePool.cpp
@@ -32,10 +32,10 @@
 #include "AtomicGuard.h"
 #include "absl/types/span.h"
 #include "absl/strings/match.h"
+#include "absl/memory/memory.h"
 #include <memory>
 #include <sndfile.hh>
 #include <thread>
-using namespace std::chrono_literals;
 
 template <class T>
 void readBaseFile(SndfileHandle& sndFile, sfz::AudioBuffer<T>& output, uint32_t numFrames)
@@ -57,13 +57,13 @@ void readBaseFile(SndfileHandle& sndFile, sfz::AudioBuffer<T>& output, uint32_t
 template <class T>
 std::unique_ptr<sfz::AudioBuffer<T>> readFromFile(SndfileHandle& sndFile, uint32_t numFrames, sfz::Oversampling factor)
 {
-    auto baseBuffer = std::make_unique<sfz::AudioBuffer<T>>();
+    auto baseBuffer = absl::make_unique<sfz::AudioBuffer<T>>();
     readBaseFile(sndFile, *baseBuffer, numFrames);
 
     if (factor == sfz::Oversampling::x1)
         return baseBuffer;
 
-    auto outputBuffer = std::make_unique<sfz::AudioBuffer<T>>(sndFile.channels(), numFrames * static_cast<int>(factor));
+    auto outputBuffer = absl::make_unique<sfz::AudioBuffer<T>>(sndFile.channels(), numFrames * static_cast<int>(factor));
     sfz::Oversampler oversampler { factor };
     oversampler.stream(*baseBuffer, *outputBuffer);
     return outputBuffer;
@@ -216,10 +216,9 @@ bool sfz::FilePool::preloadFile(const std::string& filename, uint32_t maxOffset)
             preloadedFiles[filename].preloadedData = readFromFile<float>(sndFile, framesToLoad, oversamplingFactor);
         }
     } else {
-        preloadedFiles.insert_or_assign(filename, {
-            readFromFile<float>(sndFile, framesToLoad, oversamplingFactor),
-            static_cast<float>(oversamplingFactor) * static_cast<float>(sndFile.samplerate())
-        });
+        const float sourceSampleRate { static_cast<float>(oversamplingFactor) * static_cast<float>(sndFile.samplerate()) };
+        PreloadedFileHandle handle { readFromFile<float>(sndFile, framesToLoad, oversamplingFactor), sourceSampleRate };
+        preloadedFiles.insert_or_assign(filename, handle);
     }
 
     return true;
@@ -272,7 +271,7 @@ void sfz::FilePool::tryToClearPromises()
     AtomicDisabler disabler { canAddPromisesToClear };
 
     while (addingPromisesToClear)
-        std::this_thread::sleep_for(1ms);
+        std::this_thread::sleep_for(std::chrono::milliseconds(1));
 
     for (auto& promise: promisesToClear) {
         if (promise->dataReady)
@@ -284,7 +283,7 @@ void sfz::FilePool::clearingThread()
 {
     while (!quitThread) {
         tryToClearPromises();
-        std::this_thread::sleep_for(50ms);
+        std::this_thread::sleep_for(std::chrono::milliseconds(50));
     }
 }
 
@@ -302,7 +301,7 @@ void sfz::FilePool::loadingThread() noexcept
         }
 
         if (!promiseQueue.try_pop(promise)) {
-            std::this_thread::sleep_for(1ms);
+            std::this_thread::sleep_for(std::chrono::milliseconds(1));
             continue;
         }
 
@@ -326,7 +325,7 @@ void sfz::FilePool::loadingThread() noexcept
 
         while (!filledPromiseQueue.try_push(promise)) {
             DBG("[sfizz] Error enqueuing the promise for " << promise->filename << " in the filledPromiseQueue");
-            std::this_thread::sleep_for(1ms);
+            std::this_thread::sleep_for(std::chrono::milliseconds(1));
         }
 
         promise.reset();
@@ -412,7 +411,7 @@ void sfz::FilePool::emptyFileLoadingQueues() noexcept
 {
     emptyQueue = true;
     while (emptyQueue)
-        std::this_thread::sleep_for(1ms);
+        std::this_thread::sleep_for(std::chrono::microseconds(100));
 }
 
 void sfz::FilePool::waitForBackgroundLoading() noexcept
@@ -421,11 +420,11 @@ void sfz::FilePool::waitForBackgroundLoading() noexcept
     // of the files we need to load still.
     // Spinlocking on the size of the background queue
     while (!promiseQueue.was_empty()){
-        std::this_thread::sleep_for(0.1ms);
+        std::this_thread::sleep_for(std::chrono::microseconds(100));
     }
 
     // Spinlocking on the threads possibly logging in the background
     while (threadsLoading > 0) {
-        std::this_thread::sleep_for(0.1ms);
+        std::this_thread::sleep_for(std::chrono::microseconds(100));
     }
 }
diff --git a/src/sfizz/FilePool.h b/src/sfizz/FilePool.h
index 84b6868..c75e6c7 100644
--- a/src/sfizz/FilePool.h
+++ b/src/sfizz/FilePool.h
@@ -44,10 +44,11 @@ namespace sfz {
 using AudioBufferPtr = std::shared_ptr<AudioBuffer<float>>;
 
 
+// Strict C++11 disallows member initialization if aggregate initialization is to be used...
 struct PreloadedFileHandle
 {
-    std::shared_ptr<AudioBuffer<float>> preloadedData {};
-    float sampleRate { config::defaultSampleRate };
+    std::shared_ptr<AudioBuffer<float>> preloadedData;
+    float sampleRate;
 };
 
 struct FilePromise
@@ -78,7 +79,7 @@ struct FilePromise
     AudioBuffer<float> fileData {};
     float sampleRate { config::defaultSampleRate };
     Oversampling oversamplingFactor { config::defaultOversamplingFactor };
-    std::atomic_size_t availableFrames { 0 };
+    std::atomic<size_t> availableFrames { 0 };
     std::atomic<bool> dataReady { false };
     std::chrono::time_point<std::chrono::high_resolution_clock> creationTime;
 
diff --git a/src/sfizz/FilterPool.cpp b/src/sfizz/FilterPool.cpp
index 354486d..0b600ec 100644
--- a/src/sfizz/FilterPool.cpp
+++ b/src/sfizz/FilterPool.cpp
@@ -4,7 +4,6 @@
 #include "AtomicGuard.h"
 #include <thread>
 #include <chrono>
-using namespace std::chrono_literals;
 
 sfz::FilterHolder::FilterHolder(const MidiState& midiState)
 : midiState(midiState)
@@ -113,7 +112,7 @@ size_t sfz::FilterPool::setNumFilters(size_t numFilters)
     AtomicDisabler disabler { canGiveOutFilters };
 
     while(givingOutFilters)
-        std::this_thread::sleep_for(1ms);
+        std::this_thread::sleep_for(std::chrono::milliseconds(1));
 
     auto filterIterator = filters.begin();
     auto filterSentinel = filters.rbegin();
diff --git a/src/sfizz/Logger.cpp b/src/sfizz/Logger.cpp
index 15b7fa8..fa1defd 100644
--- a/src/sfizz/Logger.cpp
+++ b/src/sfizz/Logger.cpp
@@ -13,8 +13,6 @@
 #include <sstream>
 #include <cmath>
 
-using namespace std::chrono_literals;
-
 template<class T>
 void printStatistics(std::vector<T>& data)
 {
@@ -141,7 +139,7 @@ void sfz::Logger::moveEvents() noexcept
             callbackTimes.clear();
         }
 
-        std::this_thread::sleep_for(10ms);
+        std::this_thread::sleep_for(std::chrono::milliseconds(10));
     }
 }
 
diff --git a/src/sfizz/MidiState.h b/src/sfizz/MidiState.h
index b629c88..badb0e1 100644
--- a/src/sfizz/MidiState.h
+++ b/src/sfizz/MidiState.h
@@ -134,13 +134,13 @@ private:
      * @brief Stores the note on times.
      *
      */
-	MidiNoteArray<NoteOnTime> noteOnTimes { };
+	MidiNoteArray<NoteOnTime> noteOnTimes;
     /**
      * @brief Stores the velocity of the note ons for currently
      * depressed notes.
      *
      */
-	MidiNoteArray<uint8_t> lastNoteVelocities { };
+	MidiNoteArray<uint8_t> lastNoteVelocities;
     /**
      * @brief Current known values for the CCs.
      *
diff --git a/src/sfizz/OnePoleFilter.h b/src/sfizz/OnePoleFilter.h
index 46791ef..99ddc75 100644
--- a/src/sfizz/OnePoleFilter.h
+++ b/src/sfizz/OnePoleFilter.h
@@ -26,7 +26,7 @@ public:
     template <class C>
     static Type normalizedGain(Type cutoff, C sampleRate)
     {
-        return std::tan(cutoff / static_cast<Type>(sampleRate) * fPi);
+        return std::tan(cutoff / static_cast<Type>(sampleRate) * pi<float>());
     }
 
     OnePoleFilter(Type gain)
diff --git a/src/sfizz/Opcode.h b/src/sfizz/Opcode.h
index 7edbe9a..c510f5a 100644
--- a/src/sfizz/Opcode.h
+++ b/src/sfizz/Opcode.h
@@ -11,6 +11,7 @@
 #include "SfzHelpers.h"
 #include "StringViewHelpers.h"
 #include <absl/types/optional.h>
+#include "absl/meta/type_traits.h"
 #include <string_view>
 #include <vector>
 #include <type_traits>
@@ -45,7 +46,7 @@ struct Opcode {
  * @param validRange the range of admitted values
  * @return absl::optional<ValueType> the cast value, or null
  */
-template <typename ValueType, typename std::enable_if<std::is_integral<ValueType>::value, int>::type = 0>
+template <typename ValueType, absl::enable_if_t<std::is_integral<ValueType>::value, int> = 0>
 inline absl::optional<ValueType> readOpcode(absl::string_view value, const Range<ValueType>& validRange)
 {
         int64_t returnedValue;
@@ -74,7 +75,7 @@ inline absl::optional<ValueType> readOpcode(absl::string_view value, const Range
  * @param validRange the range of admitted values
  * @return absl::optional<ValueType> the cast value, or null
  */
-template <typename ValueType, typename std::enable_if<std::is_floating_point<ValueType>::value, int>::type = 0>
+template <typename ValueType, absl::enable_if_t<std::is_floating_point<ValueType>::value, int> = 0>
 inline absl::optional<ValueType> readOpcode(absl::string_view value, const Range<ValueType>& validRange)
 {
     float returnedValue;
diff --git a/src/sfizz/Oversampler.cpp b/src/sfizz/Oversampler.cpp
index b2b986a..2a98fc0 100644
--- a/src/sfizz/Oversampler.cpp
+++ b/src/sfizz/Oversampler.cpp
@@ -105,7 +105,7 @@ void sfz::Oversampler::stream(const sfz::AudioBuffer<float>& input, sfz::AudioBu
     {
         // std::cout << "Input frames: " << inputFrameCounter << "/" << numFrames << '\n';
         const auto thisChunkSize = std::min(chunkSize, numFrames - inputFrameCounter);
-        const auto outputChunkSize { thisChunkSize * static_cast<int>(factor) };
+        const auto outputChunkSize = thisChunkSize * static_cast<int>(factor);
         for (size_t chanIdx = 0; chanIdx < numChannels; chanIdx++) {
             const auto inputChunk = input.getSpan(chanIdx).subspan(inputFrameCounter, thisChunkSize);
             const auto outputChunk = output.getSpan(chanIdx).subspan(outputFrameCounter, outputChunkSize);
diff --git a/src/sfizz/Region.cpp b/src/sfizz/Region.cpp
index ddf2a76..d8fe8ce 100644
--- a/src/sfizz/Region.cpp
+++ b/src/sfizz/Region.cpp
@@ -1011,7 +1011,7 @@ float sfz::Region::velocityCurve(uint8_t velocity) const noexcept
     float gain { 1.0f };
 
     if (velocityPoints.size() > 0) { // Custom velocity curve
-        auto after = std::find_if(velocityPoints.begin(), velocityPoints.end(), [velocity](auto& val) { return val.first >= velocity; });
+        auto after = std::find_if(velocityPoints.begin(), velocityPoints.end(), [velocity](const std::pair<int, float>& val) { return val.first >= velocity; });
         auto before = after == velocityPoints.begin() ? velocityPoints.begin() : after - 1;
         // Linear interpolation
         float relativePositionInSegment {
diff --git a/src/sfizz/SIMDSSE.cpp b/src/sfizz/SIMDSSE.cpp
index 74adfb6..bec05f0 100644
--- a/src/sfizz/SIMDSSE.cpp
+++ b/src/sfizz/SIMDSSE.cpp
@@ -623,7 +623,7 @@ void sfz::pan<float, true>(absl::Span<const float> panEnvelope, absl::Span<float
     }
 
     const auto mmOne = _mm_set_ps1(1.0f);
-    const auto mmPiFour = _mm_set_ps1(piFour<float>);
+    const auto mmPiFour = _mm_set_ps1(piFour<float>());
     __m128 mmCos;
     __m128 mmSin;
     while (pan < lastAligned) {
@@ -660,7 +660,7 @@ void sfz::width<float, true>(absl::Span<const float> widthEnvelope, absl::Span<f
         incrementAll(width, left, right);
     }
 
-    const auto mmPiFour = _mm_set_ps1(piFour<float>);
+    const auto mmPiFour = _mm_set_ps1(piFour<float>());
     __m128 mmCos;
     __m128 mmSin;
     while (width < lastAligned) {
diff --git a/src/sfizz/Synth.cpp b/src/sfizz/Synth.cpp
index 06b075a..e2c7ea0 100644
--- a/src/sfizz/Synth.cpp
+++ b/src/sfizz/Synth.cpp
@@ -342,7 +342,7 @@ bool sfz::Synth::loadSfzFile(const fs::path& file)
                 region->isStereo = true;
 
             // TODO: adjust with LFO targets
-            const auto maxOffset { region->offset + region->offsetRandom };
+            const auto maxOffset = region->offset + region->offsetRandom;
             if (!resources.filePool.preloadFile(region->sample, maxOffset))
                 removeCurrentRegion();
         }
@@ -432,7 +432,7 @@ sfz::Voice* sfz::Synth::findFreeVoice() noexcept
 
 int sfz::Synth::getNumActiveVoices() const noexcept
 {
-    auto activeVoices { 0 };
+    auto activeVoices = 0;
     for (const auto& voice : voices) {
         if (!voice->isFree())
             activeVoices++;
diff --git a/src/sfizz/Voice.cpp b/src/sfizz/Voice.cpp
index f92ec40..149003c 100644
--- a/src/sfizz/Voice.cpp
+++ b/src/sfizz/Voice.cpp
@@ -45,7 +45,7 @@ void sfz::Voice::startVoice(Region* region, int delay, int number, uint8_t value
     pitchRatio = region->getBasePitchVariation(number, value);
 
     baseVolumedB = region->getBaseVolumedB(number);
-    auto volumedB { baseVolumedB };
+    auto volumedB = baseVolumedB;
     if (region->volumeCC)
         volumedB += normalizeCC(resources.midiState.getCCValue(region->volumeCC->cc)) * region->volumeCC->value;
     volumeEnvelope.reset(db2mag(Default::volumeRange.clamp(volumedB)));
@@ -63,19 +63,19 @@ void sfz::Voice::startVoice(Region* region, int delay, int number, uint8_t value
     crossfadeEnvelope.reset(Default::normalizedRange.clamp(crossfadeGain));
 
     basePan = normalizePercents(region->pan);
-    auto pan { basePan };
+    auto pan = basePan;
     if (region->panCC)
         pan += normalizeCC(resources.midiState.getCCValue(region->panCC->cc)) * normalizePercents(region->panCC->value);
     panEnvelope.reset(Default::symmetricNormalizedRange.clamp(pan));
 
     basePosition = normalizePercents(region->position);
-    auto position { basePosition };
+    auto position = basePosition;
     if (region->positionCC)
         position += normalizeCC(resources.midiState.getCCValue(region->positionCC->cc)) * normalizePercents(region->positionCC->value);
     positionEnvelope.reset(Default::symmetricNormalizedRange.clamp(position));
 
     baseWidth = normalizePercents(region->width);
-    auto width { baseWidth };
+    auto width = baseWidth;
     if (region->widthCC)
         width += normalizeCC(resources.midiState.getCCValue(region->widthCC->cc)) * normalizePercents(region->widthCC->value);
     widthEnvelope.reset(Default::symmetricNormalizedRange.clamp(width));
diff --git a/src/sfizz/effects/Lofi.cpp b/src/sfizz/effects/Lofi.cpp
index 60b6694..f29d995 100644
--- a/src/sfizz/effects/Lofi.cpp
+++ b/src/sfizz/effects/Lofi.cpp
@@ -37,7 +37,7 @@
 
 #include "Lofi.h"
 #include "Opcode.h"
-#include <memory>
+#include "absl/memory/memory.h"
 #include <algorithm>
 #include <cstring>
 #include <cmath>
@@ -79,7 +79,7 @@ namespace fx {
 
     std::unique_ptr<Effect> Lofi::makeInstance(absl::Span<const Opcode> members)
     {
-        auto fx = std::make_unique<Lofi>();
+        auto fx = absl::make_unique<Lofi>();
 
         for (const Opcode& opcode : members) {
             switch (opcode.lettersOnlyHash) {
@@ -92,7 +92,7 @@ namespace fx {
             }
         }
 
-        return fx;
+        return std::move(fx);
     }
 
     ///
diff --git a/src/sfizz/sfizz.cpp b/src/sfizz/sfizz.cpp
index 9115f31..61e5a0c 100644
--- a/src/sfizz/sfizz.cpp
+++ b/src/sfizz/sfizz.cpp
@@ -6,10 +6,11 @@
 
 #include "Synth.h"
 #include "sfizz.hpp"
+#include "absl/memory/memory.h"
 
 sfz::Sfizz::Sfizz()
 {
-    synth = std::make_unique<sfz::Synth>();
+    synth = absl::make_unique<sfz::Synth>();
 }
 
 sfz::Sfizz::~Sfizz()

@paulfd
Copy link
Member Author

paulfd commented Mar 10, 2020

In d13f10d but is it not OK?

@falkTX
Copy link
Contributor

falkTX commented Mar 10, 2020

No, the following code fails:

        CallbackTime callbackTime;
        while (callbackTimeQueue.try_pop(callbackTime))

with:

src/external/atomic_queue/atomic_queue.h:206:43: error: could not convert 'std::move<sfz::CallbackTime&>((* & q_element))' from 'std::remove_reference<sfz::CallbackTime&>::type {aka sfz::CallbackTime}' to 'sfz::CallbackBreakdown'
             T element{std::move(q_element)};
                                           ^

This is the last piece!

@falkTX
Copy link
Contributor

falkTX commented Mar 10, 2020

This works, but I am not sure if it is right.

diff --git a/src/external/atomic_queue/atomic_queue.h b/src/external/atomic_queue/atomic_queue.h
index bcbd29a..92e0b45 100644
--- a/src/external/atomic_queue/atomic_queue.h
+++ b/src/external/atomic_queue/atomic_queue.h
@@ -203,7 +203,7 @@ protected:
             while(ATOMIC_QUEUE_UNLIKELY(state.load(A) != STORED))
                 if(Derived::maximize_throughput_)
                     spin_loop_pause();
-            T element{std::move(q_element)};
+            T&& element{std::move(q_element)};
             state.store(EMPTY, R);
             return element;
         }
@@ -211,7 +211,7 @@ protected:
             for(;;) {
                 unsigned char expected = STORED;
                 if(ATOMIC_QUEUE_LIKELY(state.compare_exchange_strong(expected, LOADING, X, X))) {
-                    T element{std::move(q_element)};
+                    T&& element{std::move(q_element)};
                     state.store(EMPTY, R);
                     return element;
                 }

@paulfd
Copy link
Member Author

paulfd commented Mar 10, 2020

Hm can you try

diff --git a/src/sfizz/Logger.h b/src/sfizz/Logger.h
index d23cb61..35a851e 100644
--- a/src/sfizz/Logger.h
+++ b/src/sfizz/Logger.h
@@ -55,13 +55,13 @@ struct FileTime
 
 struct CallbackBreakdown
 {
-    Duration dispatch { 0 };
-    Duration renderMethod { 0 };
-    Duration data { 0 };
-    Duration amplitude { 0 };
-    Duration filters { 0 };
-    Duration panning { 0 };
-    Duration effects { 0 };
+    Duration dispatch;
+    Duration renderMethod;
+    Duration data;
+    Duration amplitude;
+    Duration filters;
+    Duration panning;
+    Duration effects;
 };
 
 struct CallbackTime

@paulfd
Copy link
Member Author

paulfd commented Mar 10, 2020

Your patch applies on top of ed8ba2f ?

@falkTX
Copy link
Contributor

falkTX commented Mar 10, 2020

Yes. If not, I can do a PR next if we merge this one

@falkTX
Copy link
Contributor

falkTX commented Mar 10, 2020

FYI the changes made to CallbackBreakdown do not work

@falkTX
Copy link
Contributor

falkTX commented Mar 10, 2020

Woohoo, it is working :D 🚀

I recorded a video as demo https://nextcloud.falktx.com/s/5qcjXNKBCC8tCCg/download

There is a very nasty memory leak though. in around a minute all RAM is used, and then OOM kills the webserver if I keep playing

@paulfd
Copy link
Member Author

paulfd commented Mar 10, 2020

Wah, nice!

Well, not the leak though...

if (CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND (CMAKE_CXX_STANDARD LESS 14 OR NOT CMAKE_CXX_STANDARD))
# There is a strange segfault in clang in c++11 when instantiating the
# envelopes in FloatEnvelopes.cpp.
message("Forcing C++14 to bypass a clang segfault")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

upgrade the xcode version instead?
(and keep back the deployment target version)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can try but I'm not sure. It also crashes the default clang on my machine (ubuntu 19.10). It's a really weird bug.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And with LTO disabled?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It fails at compile time so I guess LTO is not the issue here. I will start by trying to actually downgrade XCode to use the default Travis one and we'll see what happens :)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nope, either downgrading or upgrading... I guess I should file a compiler bug report :/

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes you should, but also, try replacing.

    std::function<Type(Type)> function { [](Type input) { return input; } };

with

    std::function<Type(Type)> function { [](Type input) -> Type { return input; } };

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Holy shit, nice catch lol

@falkTX
Copy link
Contributor

falkTX commented Mar 11, 2020

This is very cool, the plugin builds without any issues now!
Build log: https://kx.studio/Paste/raw/PXH22
Only a few unused args warning remain now.
I will test the build on the device

@paulfd
Copy link
Member Author

paulfd commented Mar 11, 2020

Some unused args are actually WIP for unrelated things so I did not spend too much effort on these, I have to admit 🙂

@paulfd paulfd merged commit 4695656 into sfztools:develop Mar 14, 2020
@paulfd paulfd mentioned this pull request Mar 16, 2020
@paulfd paulfd deleted the gcc-4.9 branch January 21, 2022 10:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants