lynxtunelab.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. // LYNX vocal lab (round 190li): runs LYNX Tune (core/LynxTune.h, the real-time pitch corrector) offline on a WAV, in
  2. // blocks, for the scoring in tools/vocallab/tunelab.py. The output is latency-compensated (the same length as the input,
  3. // sample-aligned with it) so it can be compared with the source and the ideals directly.
  4. //
  5. // usage: lynxtunelab <in.wav> <out.wav|-> [name=value ...]
  6. // retune=<ms> humanize=<%> flex=<%> scale=<0..13 (0 chromatic)> key=<0..11> formant=<0|1> fshift=<st>
  7. // natvib=<dB> range=<0..3> low=<0|1> tracking=<0..1> mix=<0..1> block=<samples, 256> rev=<the hidden revision>
  8. // ignorevib=<0|1> p<index>=<raw 0..1 value> (any parameter by index)
  9. // trace=<path.csv> per-block meters: time, sung note, target note, applied correction (semitones)
  10. // bench=<N> process the file N more times for the timing (ns per sample, and CPU instructions if the
  11. // kernel exposes the counter)
  12. // Standalone build: g++ -std=c++20 -O2 -ffp-contract=off -Isrc tools/lynxtunelab.cpp src/core/LynxTune.cpp
  13. // src/core/VocalPitch.cpp -o lynxtunelab
  14. #include <chrono>
  15. #include <cmath>
  16. #include <cstdint>
  17. #include <cstdio>
  18. #include <cstdlib>
  19. #include <cstring>
  20. #include <fstream>
  21. #include <iterator>
  22. #include <string>
  23. #include <vector>
  24. #include <linux/perf_event.h>
  25. #include <sys/ioctl.h>
  26. #include <sys/syscall.h>
  27. #include <unistd.h>
  28. #include "core/Effects.h"
  29. #include "core/LynxTune.h"
  30. #include "core/VocalPitch.h"
  31. namespace
  32. {
  33. struct Wav
  34. {
  35. double sr = 48000.0;
  36. std::vector<float> x; // mono (a stereo file is mixed down)
  37. };
  38. bool readWav (const char* path, Wav& w)
  39. {
  40. std::ifstream in (path, std::ios::binary);
  41. std::vector<unsigned char> d ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  42. if (d.size() < 12 || std::memcmp (d.data(), "RIFF", 4) != 0)
  43. return false;
  44. int fmt = 0, ch = 0, bits = 0;
  45. std::size_t i = 12;
  46. auto u16 = [&] (std::size_t at) { return (unsigned) d[at] | ((unsigned) d[at + 1] << 8); };
  47. auto u32 = [&] (std::size_t at) { return u16 (at) | (u16 (at + 2) << 16); };
  48. while (i + 8 <= d.size())
  49. {
  50. const auto n = (std::size_t) u32 (i + 4);
  51. if (std::memcmp (&d[i], "fmt ", 4) == 0)
  52. {
  53. fmt = (int) u16 (i + 8);
  54. ch = (int) u16 (i + 10);
  55. w.sr = u32 (i + 12);
  56. bits = (int) u16 (i + 22);
  57. if (fmt == 0xFFFE && n >= 26)
  58. fmt = (int) u16 (i + 32);
  59. }
  60. else if (std::memcmp (&d[i], "data", 4) == 0 && ch > 0)
  61. {
  62. const auto bytes = bits / 8;
  63. const auto frames = std::min (n, d.size() - i - 8) / (std::size_t) (bytes * ch);
  64. w.x.assign (frames, 0.0f);
  65. for (std::size_t f = 0; f < frames; ++f)
  66. for (int c = 0; c < ch; ++c)
  67. {
  68. const auto* p = &d[i + 8 + (f * (std::size_t) ch + (std::size_t) c) * (std::size_t) bytes];
  69. float v = 0;
  70. if (fmt == 3 && bits == 32)
  71. std::memcpy (&v, p, 4);
  72. else if (bits == 16)
  73. v = (float) (std::int16_t) (p[0] | (p[1] << 8)) / 32768.0f;
  74. else if (bits == 24)
  75. v = (float) ((std::int32_t) ((std::uint32_t) p[0] << 8 | (std::uint32_t) p[1] << 16 | (std::uint32_t) p[2] << 24) >> 8) / 8388608.0f;
  76. w.x[f] += v / (float) ch;
  77. }
  78. return true;
  79. }
  80. i += 8 + n + (n & 1);
  81. }
  82. return false;
  83. }
  84. void writeWav (const char* path, const std::vector<float>& x, double sr)
  85. {
  86. std::FILE* f = std::fopen (path, "wb");
  87. if (f == nullptr)
  88. return;
  89. auto w32 = [&] (std::uint32_t v) { std::fwrite (&v, 4, 1, f); };
  90. auto w16 = [&] (std::uint16_t v) { std::fwrite (&v, 2, 1, f); };
  91. const auto data = (std::uint32_t) (x.size() * 4);
  92. std::fwrite ("RIFF", 1, 4, f);
  93. w32 (36 + data);
  94. std::fwrite ("WAVEfmt ", 1, 8, f);
  95. w32 (16);
  96. w16 (3);
  97. w16 (1);
  98. w32 ((std::uint32_t) sr);
  99. w32 ((std::uint32_t) sr * 4);
  100. w16 (4);
  101. w16 (32);
  102. std::fwrite ("data", 1, 4, f);
  103. w32 (data);
  104. std::fwrite (x.data(), 4, x.size(), f);
  105. std::fclose (f);
  106. }
  107. int openInstructionCounter()
  108. {
  109. perf_event_attr a {};
  110. a.type = PERF_TYPE_HARDWARE;
  111. a.size = sizeof a;
  112. a.config = PERF_COUNT_HW_INSTRUCTIONS;
  113. a.disabled = 1;
  114. a.exclude_kernel = 1;
  115. a.exclude_hv = 1;
  116. return (int) syscall (SYS_perf_event_open, &a, 0, -1, -1, 0);
  117. }
  118. } // namespace
  119. int main (int argc, char** argv)
  120. {
  121. using namespace lynx;
  122. namespace lt = lynx::lynxtune;
  123. if (argc < 3)
  124. {
  125. std::fprintf (stderr, "usage: lynxtunelab in.wav out.wav|- [retune=ms humanize=%% flex=%% scale=N key=N ...]\n");
  126. return 1;
  127. }
  128. Wav src;
  129. if (! readWav (argv[1], src))
  130. {
  131. std::fprintf (stderr, "cannot read %s\n", argv[1]);
  132. return 2;
  133. }
  134. EffectParams p {};
  135. const auto& inf = lt::info();
  136. for (std::size_t k = 0; k < inf.params.size(); ++k)
  137. p[k] = inf.params[k].defaultValue;
  138. p[lt::scale] = 0.0f; // chromatic unless asked
  139. int block = 256, bench = 0;
  140. std::string trace;
  141. for (int a = 3; a < argc; ++a)
  142. {
  143. const std::string s (argv[a]);
  144. const auto eq = s.find ('=');
  145. if (eq == std::string::npos)
  146. continue;
  147. const auto key = s.substr (0, eq);
  148. const auto v = std::atof (s.c_str() + eq + 1);
  149. if (key == "retune") p[lt::retune] = (float) std::sqrt (std::clamp (v, 0.0, 400.0) / 400.0);
  150. else if (key == "humanize") p[lt::humanize] = (float) (v / 100.0);
  151. else if (key == "flex") p[lt::flexTune] = (float) (v / 100.0);
  152. else if (key == "scale") p[lt::scale] = (float) (v / (vocal::scaleCount - 1));
  153. else if (key == "key") p[lt::key] = (float) (v / 11.0);
  154. else if (key == "formant") p[lt::formantPreserve] = (float) v;
  155. else if (key == "fshift") p[lt::formantShift] = (float) (v / 14.0 + 0.5);
  156. else if (key == "natvib") p[lt::naturalVibrato] = (float) (v / 24.0 + 0.5);
  157. else if (key == "range") p[lt::range] = (float) (v / (lt::rangeCount - 1));
  158. else if (key == "low") p[lt::lowLatency] = (float) v;
  159. else if (key == "tracking") p[lt::tracking] = (float) v;
  160. else if (key == "mix") p[lt::mix] = (float) v;
  161. else if (key == "ignorevib") p[lt::ignoreVibrato] = (float) v;
  162. else if (key == "rev") p[lt::count] = (float) v; // the hidden revision (round 190li), right after the named ones
  163. else if (key == "block") block = std::max (1, (int) v);
  164. else if (key == "bench") bench = (int) v;
  165. else if (key == "trace") trace = s.substr (eq + 1);
  166. else if (key.size() > 1 && key[0] == 'p') p[(std::size_t) std::clamp (std::atoi (key.c_str() + 1), 0, maxEffectParams - 1)] = (float) v;
  167. else
  168. {
  169. std::fprintf (stderr, "unknown option %s\n", s.c_str());
  170. return 1;
  171. }
  172. }
  173. auto fx = lt::make (&p);
  174. fx->prepare (src.sr);
  175. const auto lat = fx->latencySamples();
  176. const auto n = (int) src.x.size();
  177. std::vector<float> buf ((std::size_t) (n + lat + block), 0.0f);
  178. std::copy (src.x.begin(), src.x.end(), buf.begin());
  179. std::FILE* tr = trace.empty() ? nullptr : std::fopen (trace.c_str(), "w");
  180. if (tr != nullptr)
  181. std::fprintf (tr, "t,sung,target,shift\n");
  182. auto runOnce = [&] (std::vector<float>& b, bool traced) {
  183. fx->reset();
  184. for (int i = 0; i + block <= (int) b.size(); i += block)
  185. {
  186. fx->process (b.data() + i, nullptr, block, p, 120.0);
  187. if (traced && tr != nullptr)
  188. std::fprintf (tr, "%.5f,%.4f,%.4f,%.5f\n", (double) (i + block - lat) / src.sr, 127.0 * fx->controlOutput (0),
  189. 127.0 * fx->controlOutput (1), 4.0 * (fx->controlOutput (2) - 0.5));
  190. }
  191. };
  192. runOnce (buf, true);
  193. if (tr != nullptr)
  194. std::fclose (tr);
  195. std::vector<float> out (buf.begin() + lat, buf.begin() + lat + n);
  196. if (std::string (argv[2]) != "-")
  197. writeWav (argv[2], out, src.sr);
  198. double nsPerSample = 0.0, insPerSample = -1.0;
  199. if (bench > 0)
  200. {
  201. const auto counter = openInstructionCounter();
  202. std::vector<float> b2;
  203. long long ins = 0;
  204. const auto t0 = std::chrono::steady_clock::now();
  205. for (int r = 0; r < bench; ++r)
  206. {
  207. b2.assign ((std::size_t) (n + lat + block), 0.0f);
  208. std::copy (src.x.begin(), src.x.end(), b2.begin());
  209. if (counter >= 0)
  210. {
  211. ioctl (counter, PERF_EVENT_IOC_RESET, 0);
  212. ioctl (counter, PERF_EVENT_IOC_ENABLE, 0);
  213. }
  214. runOnce (b2, false);
  215. if (counter >= 0)
  216. {
  217. ioctl (counter, PERF_EVENT_IOC_DISABLE, 0);
  218. long long c = 0;
  219. if (read (counter, &c, sizeof c) == (ssize_t) sizeof c)
  220. ins += c;
  221. }
  222. }
  223. const auto t1 = std::chrono::steady_clock::now();
  224. nsPerSample = (double) std::chrono::duration_cast<std::chrono::nanoseconds> (t1 - t0).count() / ((double) bench * (double) b2.size());
  225. if (counter >= 0)
  226. {
  227. insPerSample = (double) ins / ((double) bench * (double) b2.size());
  228. close (counter);
  229. }
  230. }
  231. std::printf ("{\"latency\": %d, \"samples\": %d, \"ns_per_sample\": %.3f, \"instructions_per_sample\": %.2f}\n", lat, n, nsPerSample, insPerSample);
  232. return 0;
  233. }