4
0

newtonelab.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. // LYNX vocal lab (round 190li): runs LYNX's Newtone engine (core/NewtoneFx.h: analyseNotes + an edit + renderEdits)
  2. // offline on a WAV, for the scoring in tools/vocallab/vocallab.py. Also dumps the analysed notes (detection scoring).
  3. //
  4. // usage: newtonelab <in.wav> <out.wav|-> [options / edits, applied in order]
  5. // engine=N the render engine revision (Track::engine; 0 = FL's as built until 0.1.30, 1 = round 190li)
  6. // fine=0|1 "Separate close notes" analysis (AnalyseOptions::fineSplit)
  7. // notes=<path.json> write the analysed notes (before the edits) as JSON
  8. // shift=<sel>:<st> pitch offset (semitones) added to the chosen notes
  9. // centre=<0..1> variation=<0..2> transition=<0..2> the editor's global knobs (every note)
  10. // modulation=<0..2> pitchdrift=<0..2> LYNX's split of Variation (round 190li; every note)
  11. // formant=<sel>:<st> volume=<sel>:<dB> stretch=<sel>:<factor, > 1 = longer> lengthen=<sel>:<seconds> (later notes move)
  12. // quantize=<grid seconds>
  13. // bench=<N> render N more times and print the render's cost (ms, and CPU instructions per source second where
  14. // the kernel exposes the counter): the engine's cost for an edit (the editor's preview plays the result)
  15. // <sel> = "all", or "@<seconds>": the voiced note whose source span holds that time.
  16. // Standalone build (no core library): g++ -std=c++20 -O2 -Isrc -DNEWTONELAB_STANDALONE tools/newtonelab.cpp
  17. // src/core/NewtoneFx.cpp src/core/VocalPitch.cpp
  18. #include <chrono>
  19. #include <cmath>
  20. #include <cstdio>
  21. #include <cstdlib>
  22. #include <cstring>
  23. #include <fstream>
  24. #include <iterator>
  25. #include <string>
  26. #include <vector>
  27. #include "core/Instruments.h"
  28. #include "core/NewtoneFx.h"
  29. #ifdef NEWTONELAB_STANDALONE
  30. // (the parts of the core the Newtone engine does not use: Edison's score dump and Newtime's stretch)
  31. #include "core/Song.h"
  32. #include "core/TimeStretch.h"
  33. namespace lynx
  34. {
  35. void Pattern::sortNotes() {}
  36. Pattern& Song::activePattern() { std::abort(); }
  37. std::shared_ptr<SampleData> timeStretch (const SampleData&, double, StretchMethod, double, const StretchOptions&) { std::abort(); }
  38. }
  39. #endif
  40. #ifdef __linux__
  41. #include <linux/perf_event.h>
  42. #include <sys/ioctl.h>
  43. #include <sys/syscall.h>
  44. #include <unistd.h>
  45. #endif
  46. namespace
  47. {
  48. long long instructionsOf (void (*f) (void*), void* ctx)
  49. {
  50. #ifdef __linux__
  51. perf_event_attr a {};
  52. a.type = PERF_TYPE_HARDWARE;
  53. a.size = sizeof a;
  54. a.config = PERF_COUNT_HW_INSTRUCTIONS;
  55. a.disabled = 1;
  56. a.exclude_kernel = 1;
  57. a.exclude_hv = 1;
  58. const auto fd = (int) syscall (SYS_perf_event_open, &a, 0, -1, -1, 0);
  59. if (fd >= 0)
  60. {
  61. ioctl (fd, PERF_EVENT_IOC_RESET, 0);
  62. ioctl (fd, PERF_EVENT_IOC_ENABLE, 0);
  63. f (ctx);
  64. ioctl (fd, PERF_EVENT_IOC_DISABLE, 0);
  65. long long n = 0;
  66. if (read (fd, &n, sizeof n) != (ssize_t) sizeof n)
  67. n = -1;
  68. close (fd);
  69. return n;
  70. }
  71. #endif
  72. f (ctx);
  73. return -1;
  74. }
  75. std::shared_ptr<lynx::SampleData> readWav (const char* path)
  76. {
  77. std::ifstream in (path, std::ios::binary);
  78. std::vector<unsigned char> d ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  79. if (d.size() < 12 || std::memcmp (d.data(), "RIFF", 4) != 0)
  80. return nullptr;
  81. int fmt = 0, ch = 0, bits = 0;
  82. double sr = 0;
  83. std::size_t i = 12;
  84. auto u16 = [&] (std::size_t at) { return (unsigned) d[at] | ((unsigned) d[at + 1] << 8); };
  85. auto u32 = [&] (std::size_t at) { return u16 (at) | (u16 (at + 2) << 16); };
  86. while (i + 8 <= d.size())
  87. {
  88. const auto n = (std::size_t) u32 (i + 4);
  89. if (std::memcmp (&d[i], "fmt ", 4) == 0)
  90. {
  91. fmt = (int) u16 (i + 8);
  92. ch = (int) u16 (i + 10);
  93. sr = u32 (i + 12);
  94. bits = (int) u16 (i + 22);
  95. if (fmt == 0xFFFE && n >= 26)
  96. fmt = (int) u16 (i + 32);
  97. }
  98. else if (std::memcmp (&d[i], "data", 4) == 0 && ch > 0)
  99. {
  100. auto s = std::make_shared<lynx::SampleData>();
  101. s->sampleRate = sr;
  102. const auto bytes = bits / 8;
  103. const auto frames = std::min (n, d.size() - i - 8) / (std::size_t) (bytes * ch);
  104. s->left.resize (frames);
  105. if (ch > 1)
  106. s->right.resize (frames);
  107. for (std::size_t f = 0; f < frames; ++f)
  108. for (int c = 0; c < std::min (ch, 2); ++c)
  109. {
  110. const auto* p = &d[i + 8 + (f * (std::size_t) ch + (std::size_t) c) * (std::size_t) bytes];
  111. float v = 0;
  112. if (fmt == 3 && bits == 32)
  113. std::memcpy (&v, p, 4);
  114. else if (bits == 16)
  115. v = (float) (std::int16_t) (p[0] | (p[1] << 8)) / 32768.0f;
  116. else if (bits == 24)
  117. 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;
  118. else if (bits == 32)
  119. v = (float) ((double) (std::int32_t) ((std::uint32_t) p[0] | (std::uint32_t) p[1] << 8 | (std::uint32_t) p[2] << 16 | (std::uint32_t) p[3] << 24) / 2147483648.0);
  120. (c == 0 ? s->left : s->right)[f] = v;
  121. }
  122. return s;
  123. }
  124. i += 8 + n + (n & 1);
  125. }
  126. return nullptr;
  127. }
  128. void writeWav (const char* path, const lynx::SampleData& s)
  129. {
  130. const auto frames = s.frames();
  131. const int ch = s.isStereo() ? 2 : 1;
  132. std::FILE* f = std::fopen (path, "wb");
  133. if (f == nullptr)
  134. return;
  135. auto w32 = [&] (std::uint32_t v) { std::fwrite (&v, 4, 1, f); };
  136. auto w16 = [&] (std::uint16_t v) { std::fwrite (&v, 2, 1, f); };
  137. const auto data = (std::uint32_t) (frames * (std::size_t) ch * 4);
  138. std::fwrite ("RIFF", 1, 4, f);
  139. w32 (36 + data);
  140. std::fwrite ("WAVEfmt ", 1, 8, f);
  141. w32 (16);
  142. w16 (3);
  143. w16 ((std::uint16_t) ch);
  144. w32 ((std::uint32_t) s.sampleRate);
  145. w32 ((std::uint32_t) s.sampleRate * (std::uint32_t) ch * 4);
  146. w16 ((std::uint16_t) (ch * 4));
  147. w16 (32);
  148. std::fwrite ("data", 1, 4, f);
  149. w32 (data);
  150. for (std::size_t i = 0; i < frames; ++i)
  151. {
  152. std::fwrite (&s.leftData()[i], 4, 1, f);
  153. if (ch == 2)
  154. std::fwrite (&s.rightData()[i], 4, 1, f);
  155. }
  156. std::fclose (f);
  157. }
  158. std::vector<int> select (const lynx::newtonefx::Track& t, const std::string& sel, double fs)
  159. {
  160. if (sel == "all")
  161. return {};
  162. if (! sel.empty() && sel[0] == '@')
  163. {
  164. const auto at = (std::int64_t) std::llround (std::atof (sel.c_str() + 1) * fs);
  165. for (int k = 0; k < (int) t.pitches.size(); ++k)
  166. {
  167. const auto& p = t.pitches[(std::size_t) k];
  168. if (p.voiced() && at >= p.origStart && at < p.voicedEnd())
  169. return { k };
  170. }
  171. for (int k = 0; k < (int) t.pitches.size(); ++k)
  172. if (at >= t.pitches[(std::size_t) k].origStart && at < t.pitches[(std::size_t) k].origEnd)
  173. return { k };
  174. }
  175. std::fprintf (stderr, "no note at %s\n", sel.c_str());
  176. std::exit (3);
  177. }
  178. template <typename F>
  179. void each (lynx::newtonefx::Track& t, const std::vector<int>& which, F&& f)
  180. {
  181. if (which.empty())
  182. {
  183. for (auto& p : t.pitches)
  184. f (p);
  185. }
  186. else
  187. for (const auto k : which)
  188. f (t.pitches[(std::size_t) k]);
  189. }
  190. void dumpNotes (const char* path, const lynx::newtonefx::Track& t, double fs)
  191. {
  192. std::FILE* f = std::fopen (path, "w");
  193. if (f == nullptr)
  194. return;
  195. std::fprintf (f, "{\"sr\": %g, \"notes\": [", fs);
  196. bool first = true;
  197. for (const auto& p : t.pitches)
  198. {
  199. std::fprintf (f, "%s{\"start\": %.6f, \"end\": %.6f, \"voicedEnd\": %.6f, \"pitch\": %.4f, \"voiced\": %s}", first ? "" : ", ",
  200. (double) p.origStart / fs, (double) p.origEnd / fs, (double) p.voicedEnd() / fs, p.origPitch, p.voiced() ? "true" : "false");
  201. first = false;
  202. }
  203. std::fprintf (f, "]}\n");
  204. std::fclose (f);
  205. }
  206. } // namespace
  207. int main (int argc, char** argv)
  208. {
  209. using namespace lynx::newtonefx;
  210. if (argc < 3)
  211. {
  212. std::fprintf (stderr, "usage: newtonelab in.wav out.wav|- [engine=N fine=0|1 notes=x.json shift=all:3 ...]\n");
  213. return 1;
  214. }
  215. auto src = readWav (argv[1]);
  216. if (src == nullptr)
  217. {
  218. std::fprintf (stderr, "cannot read %s\n", argv[1]);
  219. return 2;
  220. }
  221. const auto fs = src->sampleRate;
  222. AnalyseOptions options;
  223. int engine = -1;
  224. std::vector<std::string> args (argv + 3, argv + argc);
  225. for (const auto& a : args)
  226. if (a.rfind ("fine=", 0) == 0)
  227. options.fineSplit = std::atoi (a.c_str() + 5) != 0;
  228. else if (a.rfind ("engine=", 0) == 0)
  229. engine = std::atoi (a.c_str() + 7);
  230. auto track = analyseNotes (*src, options);
  231. if (engine >= 0)
  232. track.engine = engine;
  233. for (const auto& a : args)
  234. {
  235. const auto eq = a.find ('=');
  236. if (eq == std::string::npos)
  237. continue;
  238. const auto key = a.substr (0, eq), value = a.substr (eq + 1);
  239. const auto colon = value.find (':');
  240. const auto sel = colon == std::string::npos ? std::string ("all") : value.substr (0, colon);
  241. const auto amount = std::atof (colon == std::string::npos ? value.c_str() : value.c_str() + colon + 1);
  242. if (key == "notes")
  243. dumpNotes (value.c_str(), track, fs);
  244. else if (key == "shift")
  245. each (track, select (track, sel, fs), [&] (Note& p) { p.shift += amount; });
  246. else if (key == "centre")
  247. applyCentre (track, amount);
  248. else if (key == "variation")
  249. applyVariation (track, amount);
  250. else if (key == "transition")
  251. applyTransition (track, amount);
  252. else if (key == "modulation")
  253. applyModulation (track, amount);
  254. else if (key == "pitchdrift")
  255. applyPitchDrift (track, amount);
  256. else if (key == "formant")
  257. each (track, select (track, sel, fs), [&] (Note& p) { p.formant = std::exp2 (amount / 12.0); });
  258. else if (key == "volume")
  259. each (track, select (track, sel, fs), [&] (Note& p) { p.volume = std::pow (10.0, amount / 20.0); });
  260. else if (key == "stretch" || key == "lengthen")
  261. {
  262. const auto which = select (track, sel, fs);
  263. for (const auto k : which)
  264. {
  265. auto& p = track.pitches[(std::size_t) k];
  266. const auto len = (double) (p.voicedEnd() - p.origStart); // (the voiced part gets longer; the tail keeps its length)
  267. // (lengthen: by `amount` seconds; stretch: by the factor)
  268. const auto delta = (std::int64_t) std::llround (key == "lengthen" ? amount * fs : len * (amount - 1.0));
  269. const auto factor = (len + (double) delta) / std::max (1.0, len);
  270. const auto tail = p.origEnd - p.voicedEnd();
  271. // the voiced part stretched, the tail after it (silence, the next consonant) as it was: a split at the voice's end
  272. if (tail > 0 && splitNote (track, (std::size_t) k, p.voicedEnd()))
  273. {
  274. auto& q = track.pitches[(std::size_t) k];
  275. q.curEnd = q.curStart + (std::int64_t) std::llround (len) + delta;
  276. q.stretch = 1.0 / factor;
  277. for (auto j = (std::size_t) k + 1; j < track.pitches.size(); ++j)
  278. track.pitches[j].curStart += delta, track.pitches[j].curEnd += delta;
  279. }
  280. else
  281. {
  282. p.curEnd = p.origEnd + delta;
  283. p.stretch = (double) (p.origEnd - p.origStart) / (double) (p.curEnd - p.curStart);
  284. for (auto j = (std::size_t) k + 1; j < track.pitches.size(); ++j)
  285. track.pitches[j].curStart += delta, track.pitches[j].curEnd += delta;
  286. }
  287. }
  288. }
  289. else if (key == "quantize")
  290. quantizeTime (track, {}, amount * fs);
  291. else if (key != "fine" && key != "engine" && key != "bench")
  292. {
  293. std::fprintf (stderr, "unknown option %s\n", a.c_str());
  294. return 1;
  295. }
  296. }
  297. track.edited = true;
  298. if (std::string (argv[2]) == "-")
  299. return 0;
  300. int bench = 0;
  301. for (const auto& a : args)
  302. if (a.rfind ("bench=", 0) == 0)
  303. bench = std::atoi (a.c_str() + 6);
  304. if (bench > 0)
  305. {
  306. struct Ctx
  307. {
  308. const lynx::SampleData* s;
  309. const Track* t;
  310. int n;
  311. } ctx { src.get(), &track, bench };
  312. const auto t0 = std::chrono::steady_clock::now();
  313. const auto ins = instructionsOf ([] (void* c) {
  314. auto* x = static_cast<Ctx*> (c);
  315. for (int k = 0; k < x->n; ++k)
  316. (void) renderEdits (*x->s, *x->t);
  317. }, &ctx);
  318. const auto ms = std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - t0).count() / bench;
  319. const auto seconds = (double) src->frames() / fs;
  320. std::printf ("bench: %.1f ms per render of %.2f s (%.1f ms per second of audio)", ms, seconds, ms / seconds);
  321. if (ins > 0)
  322. std::printf (", %.1f M instructions per second of audio", (double) ins / bench / seconds / 1e6);
  323. std::printf ("\n");
  324. }
  325. auto out = renderEdits (*src, track);
  326. writeWav (argv[2], out != nullptr ? *out : *src);
  327. std::printf ("notes %d engine %d rendered %s\n", (int) track.pitches.size(), track.engine, out != nullptr ? "yes" : "no (unedited)");
  328. return 0;
  329. }