loop_accuracy.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. // Round 190kx: the loop analysis accuracy table — key and tempo detection over LYNX's own synthetic corpus
  2. // (tests/LoopCorpus190kx.h). Build (from the repo root; the linker flag skips the parts of AudioEditTools it never calls):
  3. // g++ -std=c++20 -O2 -Isrc -Itests tools/loop_accuracy.cpp src/core/KeyFollow.cpp src/core/TempoDetect.cpp \
  4. // src/core/LoopAnalysis.cpp src/core/AudioEditTools.cpp src/core/NoteTools.cpp src/core/AutoWarp.cpp \
  5. // -Wl,--unresolved-symbols=ignore-in-object-files -o loop_accuracy
  6. // Run: loop_accuracy [--legacy] [--list] [--filter=drums-rock] [--sweep | --tempo-sweep]
  7. // --legacy: keyfollow::detectKey and tempodetect::detect, the detectors before round 190kx
  8. // --sweep / --tempo-sweep: key / tempo settings tried (a "!" marks a class where a setting is worse than the legacy)
  9. #include <chrono>
  10. #include <cstdio>
  11. #include <cstring>
  12. #include <algorithm>
  13. #include <map>
  14. #include "LoopCorpus190kx.h"
  15. #include "core/KeyFollow.h"
  16. #include "core/LoopAnalysis.h"
  17. #include "core/TempoDetect.h"
  18. namespace
  19. {
  20. const char* tempoClass (double got, double want)
  21. {
  22. if (! (got > 0.0))
  23. return "none";
  24. const auto r = got / want;
  25. const auto near = [r] (double x) { return std::abs (r / x - 1.0) < 0.01; };
  26. if (near (1.0))
  27. return "exact";
  28. if (near (2.0) || near (0.5))
  29. return "octave";
  30. if (near (1.5) || near (2.0 / 3.0) || near (3.0) || near (1.0 / 3.0) || near (0.75) || near (4.0 / 3.0))
  31. return "third";
  32. return "other";
  33. }
  34. const char* keyClass (int gotRoot, bool gotMinor, bool got, int root, bool minor)
  35. {
  36. if (root < 0)
  37. return got ? "false" : "none-ok";
  38. if (! got)
  39. return "none";
  40. if (gotRoot == root && gotMinor == minor)
  41. return "exact";
  42. const auto rel = [] (int r, bool m) { return (r + (m ? 3 : 0)) % 12; };
  43. if (rel (gotRoot, gotMinor) == rel (root, minor))
  44. return "relative";
  45. if (gotMinor == minor && ((gotRoot - root + 12) % 12 == 7 || (gotRoot - root + 12) % 12 == 5))
  46. return "fifth";
  47. if (gotRoot == root)
  48. return "parallel";
  49. return "other";
  50. }
  51. } // namespace
  52. int main (int argc, char** argv)
  53. {
  54. bool legacy = false, list = false, sweep = false, tempoSweep = false;
  55. std::string filter;
  56. for (int i = 1; i < argc; ++i)
  57. {
  58. legacy |= std::strcmp (argv[i], "--legacy") == 0, list |= std::strcmp (argv[i], "--list") == 0, sweep |= std::strcmp (argv[i], "--sweep") == 0,
  59. tempoSweep |= std::strcmp (argv[i], "--tempo-sweep") == 0;
  60. if (std::strncmp (argv[i], "--filter=", 9) == 0)
  61. filter = argv[i] + 9;
  62. }
  63. auto items = loopcorpus::corpus (false, filter);
  64. if (! filter.empty())
  65. items.erase (std::remove_if (items.begin(), items.end(), [&] (const loopcorpus::Item& it) { return it.name.find (filter) == std::string::npos; }), items.end());
  66. if (tempoSweep)
  67. {
  68. // per class: the legacy detector's exact count, then each setting's (a "!" marks a class worse than legacy)
  69. std::map<std::string, int> legacyExact;
  70. for (const auto& it : items)
  71. if (it.bpm > 0.0)
  72. {
  73. const auto r = lynx::tempodetect::detect (it.audio->leftData(), it.audio->isStereo() ? it.audio->rightData() : nullptr, it.audio->frames(), it.audio->sampleRate);
  74. legacyExact[(it.name.substr (0, it.name.find ('-', it.name.find ('-') + 1)))] += std::string (tempoClass (r.bpm, it.bpm)) == "exact";
  75. }
  76. int legacyTotal = 0;
  77. for (auto& [k, v] : legacyExact)
  78. legacyTotal += v;
  79. std::printf ("legacy total %d\n", legacyTotal);
  80. for (double share : { 0.6, 0.75 })
  81. for (double sigma : { 0.8 })
  82. for (double ratio : { 1.5 })
  83. for (double level : { 2.0 })
  84. {
  85. auto& o = lynx::loopanalysis::tempoOptions();
  86. o.loopShare = share, o.priorSigma = sigma, o.backbeatRatio = ratio, o.kickRatio = level;
  87. std::map<std::string, int> exact;
  88. int total = 0;
  89. for (const auto& it : items)
  90. if (it.bpm > 0.0)
  91. {
  92. const auto t = lynx::loopanalysis::detectTempo (*it.audio);
  93. const auto ok = t.confidence >= o.minConfidence && std::string (tempoClass (t.bpm, it.bpm)) == "exact";
  94. exact[(it.name.substr (0, it.name.find ('-', it.name.find ('-') + 1)))] += ok;
  95. total += ok;
  96. }
  97. std::string worse;
  98. for (auto& [k, v] : legacyExact)
  99. if (exact[k] < v)
  100. worse += " !" + k + " " + std::to_string (exact[k]) + "<" + std::to_string (v);
  101. std::printf ("share %.2f sigma %.1f ratio %.2f kick %.1f | exact %d%s\n", share, sigma, ratio, level, total, worse.c_str());
  102. std::fflush (stdout);
  103. }
  104. return 0;
  105. }
  106. if (sweep)
  107. {
  108. // key settings tried on the tonal and mixed loops (and the drums for false keys): one line each
  109. struct Try
  110. {
  111. const char* label;
  112. lynx::loopanalysis::KeyOptions o;
  113. };
  114. std::vector<Try> tries;
  115. for (int frames : { 1, 2 })
  116. for (double startWeight : { 2.0 })
  117. for (double startSeconds : { 0.5 })
  118. for (double margin : { 0.05 })
  119. {
  120. lynx::loopanalysis::KeyOptions o;
  121. o.hpssFrames = frames;
  122. o.tonicStart = startWeight, o.startSeconds = startSeconds, o.minMargin = margin;
  123. tries.push_back ({ "", o });
  124. }
  125. // the legacy detector's exact keys per class (a "!" marks a setting worse than it in a class)
  126. std::map<std::string, int> legacyExact;
  127. for (const auto& it : items)
  128. if (it.keyRoot >= 0)
  129. {
  130. const auto d = lynx::keyfollow::detectKey (*it.audio);
  131. legacyExact[it.name.substr (0, it.name.find ('-', it.name.find ('-') + 1))] += d.key && d.key->root == it.keyRoot && d.key->minor == it.minor;
  132. }
  133. for (const auto& t : tries)
  134. {
  135. lynx::loopanalysis::keyOptions() = t.o;
  136. int exact = 0, relative = 0, fifth = 0, other = 0, none = 0, falseKey = 0, keyed = 0, unkeyed = 0;
  137. std::map<std::string, int> classExact;
  138. for (const auto& it : items)
  139. {
  140. const auto d = lynx::loopanalysis::detectKey (*it.audio);
  141. const auto c = std::string (keyClass (d.key ? d.key->root : -1, d.key && d.key->minor, d.key.has_value(), it.keyRoot, it.minor));
  142. if (it.keyRoot >= 0)
  143. classExact[it.name.substr (0, it.name.find ('-', it.name.find ('-') + 1))] += c == "exact";
  144. if (it.keyRoot >= 0)
  145. ++keyed, exact += c == "exact", relative += c == "relative", fifth += c == "fifth", other += c == "other" || c == "parallel", none += c == "none";
  146. else
  147. ++unkeyed, falseKey += c == "false";
  148. }
  149. std::string worse;
  150. for (auto& [k, v] : legacyExact)
  151. if (classExact[k] < v)
  152. worse += " !" + k + " " + std::to_string (classExact[k]) + "<" + std::to_string (v);
  153. std::printf ("hpss %d start %.1f x %.2f s margin %.2f | exact %3d/%d rel %3d fifth %2d other %3d none %3d | false %3d/%d%s\n", t.o.hpssFrames, t.o.tonicStart,
  154. t.o.startSeconds, t.o.minMargin, exact, keyed, relative, fifth, other, none, falseKey, unkeyed, worse.c_str());
  155. std::fflush (stdout);
  156. }
  157. return 0;
  158. }
  159. // per class of loop (drums style / tonal part / mixed style / one-shot): counts per result class
  160. std::map<std::string, std::map<std::string, int>> keyTable, tempoTable, wholeTable;
  161. double seconds = 0.0, audio = 0.0;
  162. for (const auto& it : items)
  163. {
  164. const auto t0 = std::chrono::steady_clock::now();
  165. int kr = -1;
  166. bool km = false, kg = false;
  167. double bpm = 0.0;
  168. bool whole = false;
  169. if (legacy)
  170. {
  171. const auto d = lynx::keyfollow::detectKey (*it.audio);
  172. if (d.key)
  173. kr = d.key->root, km = d.key->minor, kg = true;
  174. const auto r = lynx::tempodetect::detect (it.audio->leftData(), it.audio->isStereo() ? it.audio->rightData() : nullptr, it.audio->frames(),
  175. it.audio->sampleRate);
  176. bpm = r.bpm;
  177. whole = r.beats >= 3.9 && std::abs (r.beats - std::round (r.beats)) <= 0.04 && r.confidence >= 0.35;
  178. }
  179. else
  180. {
  181. const auto a = lynx::loopanalysis::analyse (*it.audio, it.name + ".wav", false);
  182. if (a.key)
  183. kr = a.key->root, km = a.key->minor, kg = true;
  184. bpm = a.bpm;
  185. whole = a.wholeBeats;
  186. }
  187. seconds += std::chrono::duration<double> (std::chrono::steady_clock::now() - t0).count();
  188. audio += (double) it.audio->frames() / it.audio->sampleRate;
  189. const auto group = (it.kind == loopcorpus::Kind::drums ? "drums " : it.kind == loopcorpus::Kind::tonal ? "tonal " : it.kind == loopcorpus::Kind::mixed ? "mixed " : "1shot ") + it.style;
  190. const auto kc = keyClass (kr, km, kg, it.keyRoot, it.minor);
  191. keyTable[group][kc]++, keyTable["ALL"][kc]++;
  192. if (it.bpm > 0.0)
  193. {
  194. const auto tc = tempoClass (bpm, it.bpm);
  195. tempoTable[group][tc]++, tempoTable["ALL"][tc]++;
  196. const auto ok = whole && std::abs (bpm * it.beats / it.bpm - std::round (bpm * it.beats / it.bpm)) < 0.05;
  197. wholeTable[group][ok ? "whole-ok" : "whole-miss"]++, wholeTable["ALL"][ok ? "whole-ok" : "whole-miss"]++;
  198. }
  199. else
  200. {
  201. wholeTable[group][whole ? "whole-false" : "whole-none-ok"]++;
  202. }
  203. if (list)
  204. std::printf ("%-36s bpm %7.2f (want %6.1f) %-6s | key %-3s%s (want %s%s) %s\n", it.name.c_str(), bpm, it.bpm, tempoClass (bpm, it.bpm > 0 ? it.bpm : 1),
  205. kg ? loopcorpus::noteName (kr) : "-", kg && km ? "m" : "", it.keyRoot >= 0 ? loopcorpus::noteName (it.keyRoot) : "-",
  206. it.minor ? "m" : "", kc);
  207. }
  208. const auto print = [] (const char* title, std::map<std::string, std::map<std::string, int>>& t, std::vector<std::string> cols) {
  209. std::printf ("\n%s\n%-18s", title, "class");
  210. for (auto& c : cols)
  211. std::printf (" %9s", c.c_str());
  212. std::printf ("\n");
  213. for (auto& [g, row] : t)
  214. {
  215. int n = 0;
  216. for (auto& [c, v] : row)
  217. n += v;
  218. std::printf ("%-18s", g.c_str());
  219. for (auto& c : cols)
  220. std::printf (" %9s", row.count (c) ? (std::to_string (row[c]) + "/" + std::to_string (n)).c_str() : "-");
  221. std::printf ("\n");
  222. }
  223. };
  224. print ("KEY", keyTable, { "exact", "relative", "fifth", "parallel", "other", "none", "none-ok", "false" });
  225. print ("TEMPO", tempoTable, { "exact", "octave", "third", "other", "none" });
  226. print ("WHOLE BEATS", wholeTable, { "whole-ok", "whole-miss", "whole-none-ok", "whole-false" });
  227. std::printf ("\n%zu items, %.1f s of audio analysed in %.2f s (%.1f ms per second of audio)\n", items.size(), audio, seconds, 1000.0 * seconds / audio);
  228. }