4
0

physmodrender.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. // physmodrender: LYNX Model's renders and cost per voice, headless (round 190ni).
  2. //
  3. // physmodrender note <out.wav> <model 0-5 | table.lpm> <key> <velocity 0-1> <seconds> [--rate R] [--set index=value ...]
  4. // [--release S] one note (mono 32-bit float WAV), the model's own preset values unless --set
  5. // physmodrender notes <list.txt> [--rate R]
  6. // one note per line: <out.wav> <model | table.lpm> <key> <velocity> <seconds> [index=value ...] [cents=C]
  7. // (batch, one process; cents = the note's own detune, e.g. a recording's tuning for the timbre score)
  8. // physmodrender bench [--model M] [--voices N] [--seconds S] [--rate R] [--block B] [--reps K] [--cpu sse2|avx]
  9. // N voices held (different keys, damping 0 so they keep ringing), rendered in blocks of B: instructions and
  10. // thread CPU time per voice-sample, % of one core per voice and for N voices at real time, modes per voice,
  11. // the engine's memory, the tables' size; then an output hash (the SSE and AVX paths must print the same)
  12. // physmodrender info the compiled-in tables: anchors, modes, bytes, provenance hash
  13. #include <algorithm>
  14. #include <cctype>
  15. #include <cmath>
  16. #include <cstdint>
  17. #include <cstdio>
  18. #include <cstdlib>
  19. #include <cstring>
  20. #include <ctime>
  21. #include <fstream>
  22. #include <iterator>
  23. #include <optional>
  24. #include <memory>
  25. #include <sstream>
  26. #include <string>
  27. #include <vector>
  28. #if defined(__linux__)
  29. #include <linux/perf_event.h>
  30. #include <sys/ioctl.h>
  31. #include <sys/syscall.h>
  32. #include <unistd.h>
  33. #endif
  34. #include "core/CpuFeatures.h"
  35. #include "core/physmod/LynxModel.h"
  36. using namespace lynx;
  37. namespace
  38. {
  39. struct InstructionCounter
  40. {
  41. #if defined(__linux__)
  42. int fd = -1;
  43. InstructionCounter()
  44. {
  45. perf_event_attr a {};
  46. a.type = PERF_TYPE_HARDWARE;
  47. a.size = sizeof (a);
  48. a.config = PERF_COUNT_HW_INSTRUCTIONS;
  49. a.disabled = 1;
  50. a.exclude_kernel = 1;
  51. a.exclude_hv = 1;
  52. fd = (int) syscall (SYS_perf_event_open, &a, 0, -1, -1, 0);
  53. }
  54. ~InstructionCounter()
  55. {
  56. if (fd >= 0)
  57. close (fd);
  58. }
  59. void start() { if (fd >= 0) { ioctl (fd, PERF_EVENT_IOC_RESET, 0); ioctl (fd, PERF_EVENT_IOC_ENABLE, 0); } }
  60. long long stop()
  61. {
  62. if (fd < 0)
  63. return -1;
  64. ioctl (fd, PERF_EVENT_IOC_DISABLE, 0);
  65. long long v = -1;
  66. if (::read (fd, &v, sizeof (v)) != (ssize_t) sizeof (v))
  67. v = -1;
  68. return v;
  69. }
  70. #else
  71. void start() {}
  72. long long stop() { return -1; }
  73. #endif
  74. };
  75. double threadMs()
  76. {
  77. #if defined(CLOCK_THREAD_CPUTIME_ID)
  78. timespec ts {};
  79. clock_gettime (CLOCK_THREAD_CPUTIME_ID, &ts);
  80. return ts.tv_sec * 1000.0 + ts.tv_nsec * 1e-6;
  81. #else
  82. return 1000.0 * (double) std::clock() / CLOCKS_PER_SEC;
  83. #endif
  84. }
  85. bool writeWav (const std::string& path, const std::vector<float>& mono, int rate)
  86. {
  87. std::ofstream f (path, std::ios::binary);
  88. if (! f)
  89. return false;
  90. const auto put32 = [&f] (std::uint32_t v) { f.write (reinterpret_cast<const char*> (&v), 4); };
  91. const auto put16 = [&f] (std::uint16_t v) { f.write (reinterpret_cast<const char*> (&v), 2); };
  92. const auto bytes = (std::uint32_t) (mono.size() * 4);
  93. f.write ("RIFF", 4);
  94. put32 (36 + bytes);
  95. f.write ("WAVEfmt ", 8);
  96. put32 (16);
  97. put16 (3); // IEEE float
  98. put16 (1);
  99. put32 ((std::uint32_t) rate);
  100. put32 ((std::uint32_t) rate * 4);
  101. put16 (4);
  102. put16 (32);
  103. f.write ("data", 4);
  104. put32 (bytes);
  105. f.write (reinterpret_cast<const char*> (mono.data()), (std::streamsize) bytes);
  106. return (bool) f;
  107. }
  108. std::vector<std::uint8_t> readFile (const std::string& path)
  109. {
  110. std::ifstream f (path, std::ios::binary);
  111. return std::vector<std::uint8_t> ((std::istreambuf_iterator<char> (f)), std::istreambuf_iterator<char>());
  112. }
  113. // "<model | table.lpm>": the model number, or a table file (its model's preset values)
  114. struct Source
  115. {
  116. int model = 0;
  117. std::optional<lm::Table> table;
  118. };
  119. std::optional<Source> sourceOf (const std::string& s)
  120. {
  121. Source src;
  122. if (s.size() > 4 && s.substr (s.size() - 4) == ".lpm")
  123. {
  124. const auto bytes = readFile (s);
  125. std::string err;
  126. src.table = lm::parseTable (bytes.data(), bytes.size(), &err);
  127. if (! src.table)
  128. {
  129. std::fprintf (stderr, "%s: %s\n", s.c_str(), err.c_str());
  130. return std::nullopt;
  131. }
  132. src.model = src.table->model;
  133. return src;
  134. }
  135. src.model = std::clamp (std::atoi (s.c_str()), 0, lm::modelCount - 1);
  136. return src;
  137. }
  138. bool renderNote (const std::string& out, const std::string& source, int key, float velocity, double seconds, int rate,
  139. const std::vector<std::pair<int, double>>& sets, double releaseAt, float cents = 0.0f)
  140. {
  141. const auto src = sourceOf (source);
  142. if (! src)
  143. return false;
  144. auto v = lm::presetValues (src->model);
  145. std::vector<double> state (v.begin(), v.end());
  146. for (const auto& [i, x] : sets)
  147. if (i >= 0 && i < lm::stateSize)
  148. state[(std::size_t) i] = x;
  149. const int length = (int) std::lround (seconds * rate);
  150. lm::RefNote n;
  151. n.start = 0;
  152. n.key = key;
  153. n.velocity = velocity;
  154. n.release = releaseAt > 0.0 ? (int) std::lround (releaseAt * rate) : -1;
  155. n.cents = cents;
  156. const auto stereo = lm::renderReference (state, { n }, rate, length, 256, src->table ? &*src->table : nullptr);
  157. std::vector<float> mono ((std::size_t) length);
  158. for (int i = 0; i < length; ++i)
  159. mono[(std::size_t) i] = stereo[(std::size_t) i * 2];
  160. if (! writeWav (out, mono, rate))
  161. {
  162. std::fprintf (stderr, "cannot write %s\n", out.c_str());
  163. return false;
  164. }
  165. return true;
  166. }
  167. std::vector<std::pair<int, double>> parseSets (const std::vector<std::string>& words)
  168. {
  169. std::vector<std::pair<int, double>> sets;
  170. for (const auto& w : words)
  171. if (const auto eq = w.find ('='); eq != std::string::npos && eq > 0 && std::isdigit ((unsigned char) w[0]))
  172. sets.push_back ({ std::atoi (w.substr (0, eq).c_str()), std::atof (w.substr (eq + 1).c_str()) });
  173. return sets;
  174. }
  175. int bench (int model, int voices, double seconds, int rate, int block, int reps)
  176. {
  177. auto v = lm::presetValues (model);
  178. v[(std::size_t) lm::p::damping] = 0.0; // (every T60 x4: the voices keep ringing through the measurement)
  179. v[(std::size_t) lm::p::release] = 1.0;
  180. InstructionCounter counter;
  181. std::printf ("model %s, %d voices, %d Hz, block %d, %s path\n", lm::modelName (model), voices, rate, block,
  182. lm::modesUseAvx() ? "AVX" : "SSE");
  183. double bestNs = 1e30;
  184. long long bestIns = -1;
  185. std::uint64_t hash = 1469598103934665603ull;
  186. double modesMean = 0.0;
  187. int activeAtEnd = 0;
  188. for (int r = 0; r < reps; ++r)
  189. {
  190. lm::Engine e;
  191. e.prepare (rate);
  192. e.setValues (v.data());
  193. const auto& t = lm::builtInTable (model);
  194. const int lo = (int) std::ceil (t.anchors.front().key), hi = (int) std::floor (t.anchors.back().key);
  195. for (int k = 0; k < voices; ++k)
  196. e.note (lo + (k * std::max (1, hi - lo)) / std::max (1, voices - 1) % 128, 0.9f);
  197. std::vector<float> L ((std::size_t) block), R ((std::size_t) block);
  198. // the strikes' first 50 ms are not measured (the contact pulses), then `seconds` of ringing
  199. const int warm = rate / 20 / block + 1;
  200. for (int b = 0; b < warm; ++b)
  201. {
  202. std::fill (L.begin(), L.end(), 0.0f);
  203. std::fill (R.begin(), R.end(), 0.0f);
  204. e.render (L.data(), R.data(), block);
  205. }
  206. int modes = 0;
  207. for (int k = 0; k < lm::maxVoices; ++k)
  208. modes += e.modesOfVoice (k);
  209. modesMean = (double) modes / std::max (1, e.activeVoices());
  210. const int blocks = (int) (seconds * rate / block);
  211. long long voiceSamples = 0;
  212. const auto t0 = threadMs();
  213. counter.start();
  214. for (int b = 0; b < blocks; ++b)
  215. {
  216. std::fill (L.begin(), L.end(), 0.0f);
  217. std::fill (R.begin(), R.end(), 0.0f);
  218. voiceSamples += (long long) e.activeVoices() * block;
  219. e.render (L.data(), R.data(), block);
  220. if (r == 0)
  221. for (int i = 0; i < block; ++i)
  222. {
  223. std::uint32_t bits;
  224. std::memcpy (&bits, &L[(std::size_t) i], 4);
  225. hash = (hash ^ bits) * 1099511628211ull;
  226. }
  227. }
  228. const auto ins = counter.stop();
  229. const auto ms = threadMs() - t0;
  230. activeAtEnd = e.activeVoices();
  231. const auto ns = ms * 1e6 / (double) std::max (voiceSamples, 1ll);
  232. if (ns < bestNs)
  233. bestNs = ns;
  234. if (ins >= 0)
  235. {
  236. const auto per = (long long) std::llround ((double) ins / (double) std::max (voiceSamples, 1ll) * 1000.0);
  237. bestIns = bestIns < 0 ? per : std::min (bestIns, per);
  238. }
  239. }
  240. const auto corePerVoice = bestNs * rate / 1e9 * 100.0;
  241. std::printf ("modes per voice (mean) %.1f, voices still active at the end %d\n", modesMean, activeAtEnd);
  242. std::printf ("instructions per voice-sample %s\n", bestIns >= 0 ? (std::to_string (bestIns / 1000) + "." + std::to_string (bestIns % 1000 / 100)).c_str() : "n/a");
  243. std::printf ("CPU per voice-sample %.2f ns (best of %d), %.3f %% of one core per voice, %.2f %% for %d voices\n", bestNs, reps,
  244. corePerVoice, corePerVoice * voices, voices);
  245. std::printf ("engine memory %zu bytes; tables %zu bytes on disk (all six), %zu bytes parsed\n", lm::Engine::footprintBytes(),
  246. [] { std::size_t s = 0; for (int m = 0; m < lm::modelCount; ++m) s += lm::builtInTableBytes (m); return s; }(),
  247. [] { std::size_t s = 0; for (int m = 0; m < lm::modelCount; ++m) s += lm::tableMemoryBytes (lm::builtInTable (m)); return s; }());
  248. std::printf ("output hash %016llx\n", (unsigned long long) hash);
  249. return 0;
  250. }
  251. } // namespace
  252. int main (int argc, char** argv)
  253. {
  254. std::vector<std::string> a (argv + 1, argv + argc);
  255. const auto opt = [&a] (const char* name, double fallback) {
  256. for (std::size_t i = 0; i + 1 < a.size(); ++i)
  257. if (a[i] == name)
  258. return std::atof (a[i + 1].c_str());
  259. return fallback;
  260. };
  261. if (! a.empty() && a[0] == "--cpu" && a.size() > 1)
  262. a.erase (a.begin(), a.begin() + 2);
  263. for (std::size_t i = 0; i + 1 < a.size(); ++i)
  264. if (a[i] == "--cpu")
  265. cpu::setLevelForTest (a[i + 1] == "sse2" ? cpu::sse2 : a[i + 1] == "avx" ? cpu::avx : cpu::avx2);
  266. const int rate = (int) opt ("--rate", 48000);
  267. if (a.size() >= 6 && a[0] == "note")
  268. {
  269. std::vector<std::string> rest;
  270. for (std::size_t i = 6; i < a.size(); ++i)
  271. if (a[i] == "--set" && i + 1 < a.size())
  272. rest.push_back (a[++i]);
  273. return renderNote (a[1], a[2], std::atoi (a[3].c_str()), (float) std::atof (a[4].c_str()), std::atof (a[5].c_str()), rate,
  274. parseSets (rest), opt ("--release", -1.0))
  275. ? 0
  276. : 1;
  277. }
  278. if (a.size() >= 2 && a[0] == "notes")
  279. {
  280. std::ifstream f (a[1]);
  281. std::string line;
  282. int bad = 0, n = 0;
  283. while (std::getline (f, line))
  284. {
  285. std::istringstream in (line);
  286. std::vector<std::string> w;
  287. for (std::string x; in >> x;)
  288. w.push_back (x);
  289. if (w.size() < 5 || w[0][0] == '#')
  290. continue;
  291. ++n;
  292. float cents = 0.0f;
  293. for (std::size_t k = 5; k < w.size(); ++k)
  294. if (w[k].rfind ("cents=", 0) == 0)
  295. cents = (float) std::atof (w[k].c_str() + 6);
  296. if (! renderNote (w[0], w[1], std::atoi (w[2].c_str()), (float) std::atof (w[3].c_str()), std::atof (w[4].c_str()), rate,
  297. parseSets (std::vector<std::string> (w.begin() + 5, w.end())), -1.0, cents))
  298. ++bad;
  299. }
  300. std::printf ("rendered %d notes, %d failed\n", n - bad, bad);
  301. return bad == 0 ? 0 : 1;
  302. }
  303. if (! a.empty() && a[0] == "bench")
  304. return bench ((int) opt ("--model", 0), (int) opt ("--voices", 32), opt ("--seconds", 2.0), rate, (int) opt ("--block", 256),
  305. (int) opt ("--reps", 5));
  306. if (! a.empty() && a[0] == "info")
  307. {
  308. for (int m = 0; m < lm::modelCount; ++m)
  309. {
  310. const auto& t = lm::builtInTable (m);
  311. std::printf ("%-14s %3zu anchors %4zu modes %6zu bytes keys %.0f-%.0f provenance ", lm::modelName (m), t.anchors.size(), t.modes.size(),
  312. lm::builtInTableBytes (m), t.anchors.empty() ? 0.0 : t.anchors.front().key, t.anchors.empty() ? 0.0 : t.anchors.back().key);
  313. for (auto b : t.provenance)
  314. std::printf ("%02x", b);
  315. std::printf ("\n");
  316. }
  317. return 0;
  318. }
  319. std::fprintf (stderr, "usage: physmodrender note|notes|bench|info ... (see tools/physmodrender.cpp)\n");
  320. return 2;
  321. }