TempoDetect.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. #include "core/TempoDetect.h"
  2. #include <algorithm>
  3. #include <cmath>
  4. #include <numeric>
  5. namespace lynx::tempodetect
  6. {
  7. std::vector<float> onsetCurve (const float* left, const float* right, std::size_t frames, double sampleRate, double hopSeconds)
  8. {
  9. std::vector<float> curve;
  10. if (left == nullptr || frames == 0 || sampleRate <= 0.0)
  11. return curve;
  12. const auto hop = std::max<std::size_t> (16, (std::size_t) std::llround (hopSeconds * sampleRate));
  13. const auto hops = frames / hop;
  14. if (hops < 2)
  15. return curve;
  16. // three bands from two one-pole low-passes (~150 Hz and ~2 kHz): kick, body, hats
  17. const auto coefficient = [sampleRate] (double hz) { return (float) (1.0 - std::exp (-2.0 * 3.14159265358979 * hz / sampleRate)); };
  18. const auto aLow = coefficient (150.0), aMid = coefficient (2000.0);
  19. float low = 0.0f, mid = 0.0f;
  20. std::vector<float> previous (3, 0.0f);
  21. curve.reserve (hops);
  22. for (std::size_t h = 0; h < hops; ++h)
  23. {
  24. double e[3] = { 0.0, 0.0, 0.0 };
  25. for (std::size_t i = h * hop, end = i + hop; i < end; ++i)
  26. {
  27. const auto x = right != nullptr ? 0.5f * (left[i] + right[i]) : left[i];
  28. low += aLow * (x - low);
  29. mid += aMid * (x - mid);
  30. const float bands[3] = { low, mid - low, x - mid };
  31. for (int b = 0; b < 3; ++b)
  32. e[b] += (double) bands[b] * bands[b];
  33. }
  34. auto flux = 0.0f;
  35. for (int b = 0; b < 3; ++b)
  36. {
  37. const auto level = (float) std::log (1.0e-10 + e[b] / (double) hop);
  38. if (h > 0)
  39. flux += std::max (0.0f, level - previous[(std::size_t) b]);
  40. previous[(std::size_t) b] = level;
  41. }
  42. curve.push_back (flux);
  43. }
  44. // remove the local mean (~0.4 s) so sustained parts do not count as pulses
  45. const auto half = std::max<std::size_t> (1, (std::size_t) std::llround (0.2 / hopSeconds));
  46. std::vector<double> prefix (curve.size() + 1, 0.0);
  47. for (std::size_t i = 0; i < curve.size(); ++i)
  48. prefix[i + 1] = prefix[i] + curve[i];
  49. std::vector<float> out (curve.size());
  50. for (std::size_t i = 0; i < curve.size(); ++i)
  51. {
  52. const auto a = i > half ? i - half : 0, b = std::min (curve.size(), i + half + 1);
  53. const auto mean = (prefix[b] - prefix[a]) / (double) (b - a);
  54. out[i] = std::max (0.0f, curve[i] - (float) mean);
  55. }
  56. // a short triangular blur (~±15 ms): pulses a fraction of a hop apart still correlate, so the period can be
  57. // read between whole hops
  58. const auto radius = std::max<int> (1, (int) std::lround (0.015 / hopSeconds));
  59. std::vector<float> smooth (out.size(), 0.0f);
  60. for (std::size_t i = 0; i < out.size(); ++i)
  61. {
  62. double sum = 0.0, weights = 0.0;
  63. for (int k = -radius; k <= radius; ++k)
  64. {
  65. const auto j = (long long) i + k;
  66. if (j < 0 || j >= (long long) out.size())
  67. continue;
  68. const auto w = (double) (radius + 1 - std::abs (k));
  69. sum += w * out[(std::size_t) j];
  70. weights += w;
  71. }
  72. smooth[i] = (float) (sum / weights);
  73. }
  74. return smooth;
  75. }
  76. Result detect (const float* left, const float* right, std::size_t frames, double sampleRate, const Options& options)
  77. {
  78. Result result;
  79. if (sampleRate <= 0.0 || frames < (std::size_t) (2.0 * sampleRate))
  80. return result;
  81. // the hop in whole frames (as onsetCurve rounds it): its exact length in seconds keeps the tempo unbiased
  82. const auto hopFrames = std::max<long long> (16, std::llround (0.005 * sampleRate));
  83. const auto hopSeconds = (double) hopFrames / sampleRate;
  84. // at most two minutes are read (enough for a steady tempo; a long file stays quick)
  85. const auto analysed = std::min (frames, (std::size_t) (120.0 * sampleRate));
  86. const auto curve = onsetCurve (left, right, analysed, sampleRate, hopSeconds);
  87. const auto n = curve.size();
  88. const auto minBpm = std::clamp (options.minBpm, 20.0, 400.0);
  89. const auto maxBpm = std::clamp (options.maxBpm, minBpm + 1.0, 800.0);
  90. constexpr int harmonics = 4;
  91. const auto maxLag = (std::size_t) std::ceil (harmonics * 60.0 / (minBpm * hopSeconds)) + 2;
  92. if (n < maxLag + 8)
  93. return result;
  94. const auto energy = std::inner_product (curve.begin(), curve.end(), curve.begin(), 0.0);
  95. if (energy <= 1.0e-9)
  96. return result;
  97. // autocorrelation per lag, normalised by the overlap
  98. std::vector<double> r (maxLag + 1, 0.0);
  99. for (std::size_t lag = 1; lag <= maxLag; ++lag)
  100. {
  101. double sum = 0.0;
  102. for (std::size_t i = lag; i < n; ++i)
  103. sum += (double) curve[i] * curve[i - lag];
  104. r[lag] = sum / (double) (n - lag);
  105. }
  106. const auto at = [&r] (double lag) {
  107. const auto i = (std::size_t) lag;
  108. if (i + 1 >= r.size())
  109. return 0.0;
  110. const auto f = lag - (double) i;
  111. return r[i] * (1.0 - f) + r[i + 1] * f;
  112. };
  113. // a comb over the period and its multiples, with a mild preference for the middle of the range (geometric)
  114. const auto middle = std::sqrt (minBpm * maxBpm);
  115. auto score = [&] (double bpm) {
  116. const auto period = 60.0 / (bpm * hopSeconds);
  117. double s = 0.0;
  118. for (int k = 1; k <= harmonics; ++k)
  119. s += at (period * k) / (double) k;
  120. const auto octaves = std::log2 (bpm / middle);
  121. return s * std::exp (-0.5 * octaves * octaves / (1.2 * 1.2));
  122. };
  123. auto best = minBpm, bestScore = -1.0, total = 0.0;
  124. int count = 0;
  125. for (auto bpm = minBpm; bpm <= maxBpm + 1.0e-9; bpm += 0.05)
  126. {
  127. const auto s = score (bpm);
  128. total += s;
  129. ++count;
  130. if (s > bestScore)
  131. {
  132. bestScore = s;
  133. best = bpm;
  134. }
  135. }
  136. // refine the period on many beats (fractional-lag correlation of the curve itself, up to 16 periods):
  137. // a long lag reads the tempo far more precisely than one period
  138. const auto direct = [&curve, n] (double lag) {
  139. const auto whole = (std::size_t) lag;
  140. const auto f = (float) (lag - (double) whole);
  141. if (whole + 2 >= n)
  142. return 0.0;
  143. double sum = 0.0;
  144. for (std::size_t i = whole + 1; i < n; ++i)
  145. sum += (double) curve[i] * (curve[i - whole] * (1.0f - f) + curve[i - whole - 1] * f);
  146. return sum / (double) (n - whole);
  147. };
  148. {
  149. const auto period = 60.0 / (best * hopSeconds);
  150. const auto periods = std::clamp ((int) ((double) n * 0.5 / period), 1, 16);
  151. auto fine = [&] (double bpm) {
  152. const auto p = 60.0 / (bpm * hopSeconds);
  153. double s = 0.0;
  154. for (int k = 1; k <= periods; ++k)
  155. s += direct (p * k);
  156. return s;
  157. };
  158. auto bestFine = fine (best);
  159. const auto centre = best;
  160. for (int step = -40; step <= 40; ++step)
  161. {
  162. const auto bpm = centre * (1.0 + 0.0002 * step);
  163. if (const auto s = fine (bpm); s > bestFine)
  164. {
  165. bestFine = s;
  166. best = bpm;
  167. }
  168. }
  169. }
  170. const auto mean = total / std::max (1, count);
  171. if (bestScore <= 0.0)
  172. return result;
  173. result.confidence = std::clamp ((bestScore - mean) / bestScore, 0.0, 1.0);
  174. result.bpm = best;
  175. const auto seconds = (double) frames / sampleRate;
  176. if (options.snapToLength)
  177. {
  178. // a loop of whole beats: the length gives the exact tempo
  179. const auto beats = seconds * best / 60.0;
  180. const auto whole = std::round (beats);
  181. if (whole >= 4.0)
  182. {
  183. const auto exact = whole * 60.0 / seconds;
  184. if (std::abs (exact - best) / best < 0.002 && exact >= minBpm - 0.5 && exact <= maxBpm + 0.5)
  185. result.bpm = exact;
  186. }
  187. }
  188. if (options.wholeBpm)
  189. result.bpm = std::round (result.bpm);
  190. result.beats = seconds * result.bpm / 60.0;
  191. return result;
  192. }
  193. } // namespace lynx::tempodetect