summaryrefslogtreecommitdiffhomepage
path: root/BPMDetect.cpp
blob: 756747dc2c5f972012ac96baa6bc55f507bf3268 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include "BPMDetect.h"

#include "log.h"

BPMDetect::BPMDetect(int divider):
  m_divider{divider},
  m_count{}
{
}

// Strategy: evaluate last 3 valid beats
// always skip m_divider-1 beats
void BPMDetect::receive_event()
{
  // guard by divider
  ++m_count;
  if (m_count < m_divider) {
    return;
  } else {
    m_count = 0;
  }

  // calculate bpm
  time_point now = clock_type::now();

  m_timestamps.push_back(now);

  while (m_timestamps.size() > 3) {
    m_timestamps.pop_front();
  }

  if (m_timestamps.size() == 3) {
    int bpm = 60 * 2 / std::chrono::duration<double>(m_timestamps.back() - m_timestamps.front()).count();

    signal_bpm(bpm);
  }
}