Permalink
Browse files

Encapsulate

  • Loading branch information...
mlang committed Jul 25, 2017
1 parent 3d6f4b6 commit ad943ba9aefd741806f21cadb0b52c80c5877d5e
Showing with 32 additions and 13 deletions.
  1. +32 −13 edge.cpp
View
@@ -3,35 +3,53 @@
#include <jack.hpp>
template<typename T> T exponentialAverage(T Value, T Average, T Weight) {
return Weight * Value + (T(1) - Weight) * Average;
}
// https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
template<typename T>
class ExponentiallyWeightedMovingAverage {
T Average;
T const Weight;
public:
explicit ExponentiallyWeightedMovingAverage(T Weight, T Initial = T(0))
: Average(Initial), Weight(Weight) {}
ExponentiallyWeightedMovingAverage &operator()(T Value) {
Average = Weight * Value + (T(1) - Weight) * Average;
return *this;
}
operator T() const noexcept { return Average; }
};
class EdgeDetect : public JACK::Client {
JACK::AudioIn In;
float SlowAverage, FastAverage, PreviousDifference;
std::size_t PulseWidth;
decltype(In)::value_type PreviousDifference = 0;
ExponentiallyWeightedMovingAverage<decltype(In)::value_type>
FastAverage, SlowAverage;
std::size_t PulseWidth = 0;
float const Threshold;
public:
EdgeDetect(float Threshold = 0.2)
: JACK::Client("EdgeDetect")
, In(createAudioIn("In"))
, SlowAverage(0), FastAverage(0), PreviousDifference(0), PulseWidth(0)
EdgeDetect(float Threshold = 0.2) : JACK::Client("EdgeDetect")
, In(createAudioIn("In")), FastAverage(0.25), SlowAverage(0.0625)
, Threshold(Threshold) {}
int process(std::uint32_t FrameCount) override {
std::size_t Frame = 0;
for (auto Sample : In.buffer(FrameCount)) {
FastAverage = exponentialAverage(Sample, FastAverage, 0.25f);
SlowAverage = exponentialAverage(Sample, SlowAverage, 0.0625f);
auto Difference = FastAverage - SlowAverage;
auto Difference = FastAverage(Sample) - SlowAverage(Sample);
if (PreviousDifference < Threshold && Difference > Threshold) {
std::cout << "Positive Edge (" << Frame << ", " << PulseWidth << ")" << "\n";
PulseWidth = 0;
}
PreviousDifference = Difference;
Frame += 1; PulseWidth += 1;
}
return 0;
}
};
@@ -43,8 +61,9 @@ int main() {
App.activate();
while (true) {
std::this_thread::sleep_for(1s);
std::this_thread::sleep_for(10ms);
}
return EXIT_SUCCESS;
}

0 comments on commit ad943ba

Please sign in to comment.