4
0

nativebench.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. // nativebench (round 190pz): what every LYNX native engine costs, measured as the mixer and the Channel Rack run it.
  2. //
  3. // For each built-in effect (FL-native equivalents, LYNX's own devices, the Live-device stand-ins, the plugin pack's
  4. // engines) and each built-in instrument, a one-channel song is rendered through RackRenderer as perfbench does (one
  5. // thread, live quality, flush-to-zero as on LYNX's audio threads), with and without the engine; the difference of the
  6. // instructions retired (Linux perf_event: exact, whatever the machine's load) is the engine's own cost:
  7. //
  8. // effects signal a programme (kick, hats, a saw-chord pad; about -18 dBFS RMS) through the slot
  9. // silence no input, the slot's smart disable off: does the effect sleep by itself?
  10. // smart no input, smart disable on (the default), after its hold: does the renderer take it out?
  11. // automation the signal with the slot's first two parameters automated (a point every 1/16 beat)
  12. // instruments signal a 4-note chord held 3.5 of every 4 beats, an 8th-note line an octave up
  13. // silence 2 s after the song stopped (its notes ended): idle() (the renderer skips the channel) or still rendering?
  14. //
  15. // plus the memory one instance takes (heap bytes held after the rack build: the first instance and each further one),
  16. // the allocations made while rendering (operator new on the audio thread: must be 0), the block-to-block spread of the
  17. // engine's instructions (spikes) and the thread CPU time (noisy: an indication only; decisions rest on instructions).
  18. //
  19. // usage: nativebench [--fl <FL Studio's Data folder>] [--rates 44100,48000] [--blocks 128,512] [--seconds S]
  20. // [--only name[,name...]] [--kinds fx|inst|all] [--tsv file] [--hashes file]
  21. // --hashes: one line per engine, mode and configuration with the hash of the output (a change that must be exact
  22. // gives the same file before and after)
  23. #include <algorithm>
  24. #include <atomic>
  25. #include <chrono>
  26. #include <cmath>
  27. #include <cstdio>
  28. #include <cstdlib>
  29. #include <cstring>
  30. #include <filesystem>
  31. #include <fstream>
  32. #include <iterator>
  33. #include <map>
  34. #include <memory>
  35. #include <new>
  36. #include <set>
  37. #include <string>
  38. #include <vector>
  39. #include <execinfo.h>
  40. #include <malloc.h>
  41. #include <time.h>
  42. #if defined(__linux__)
  43. #include <linux/perf_event.h>
  44. #include <sys/ioctl.h>
  45. #include <sys/syscall.h>
  46. #include <unistd.h>
  47. #endif
  48. #if defined(__x86_64__)
  49. #include <xmmintrin.h>
  50. #endif
  51. #include "WavReader.h"
  52. #include "core/Effects.h"
  53. #include "core/FlpImport.h"
  54. #include "core/Instruments.h"
  55. #include "core/LiveEventQueue.h"
  56. #include "core/NativeEngines.h"
  57. #include "core/RackRenderer.h"
  58. #include "core/Scheduler.h"
  59. #include "core/SynthPresets.h"
  60. // allocations on the measuring thread while it renders (the audio thread must not allocate)
  61. namespace
  62. {
  63. std::atomic<bool> countingAllocs { false };
  64. std::atomic<long> allocCount { 0 };
  65. // LYNX_NB_ALLOCTRACE=n: the call stacks of the first n allocations made while rendering (where an engine allocates)
  66. int allocTraces = -1;
  67. void noteAlloc (std::size_t size)
  68. {
  69. allocCount.fetch_add (1, std::memory_order_relaxed);
  70. if (allocTraces < 0)
  71. allocTraces = std::getenv ("LYNX_NB_ALLOCTRACE") != nullptr ? std::atoi (std::getenv ("LYNX_NB_ALLOCTRACE")) : 0;
  72. if (allocTraces > 0)
  73. {
  74. --allocTraces;
  75. countingAllocs.store (false);
  76. void* frames[24];
  77. const auto n = backtrace (frames, 24);
  78. std::fprintf (stderr, "--- allocation of %zu bytes while rendering:\n", size);
  79. backtrace_symbols_fd (frames, n, 2);
  80. countingAllocs.store (true);
  81. }
  82. }
  83. } // namespace
  84. void* operator new (std::size_t size)
  85. {
  86. if (countingAllocs.load (std::memory_order_relaxed))
  87. noteAlloc (size);
  88. if (auto* p = std::malloc (size == 0 ? 1 : size))
  89. return p;
  90. throw std::bad_alloc();
  91. }
  92. void* operator new[] (std::size_t size) { return operator new (size); }
  93. void* operator new (std::size_t size, const std::nothrow_t&) noexcept
  94. {
  95. if (countingAllocs.load (std::memory_order_relaxed))
  96. noteAlloc (size);
  97. return std::malloc (size == 0 ? 1 : size);
  98. }
  99. void* operator new[] (std::size_t size, const std::nothrow_t& t) noexcept { return operator new (size, t); }
  100. void* operator new (std::size_t size, std::align_val_t al)
  101. {
  102. if (countingAllocs.load (std::memory_order_relaxed))
  103. noteAlloc (size);
  104. const auto a = std::max<std::size_t> ((std::size_t) al, sizeof (void*));
  105. if (auto* p = std::aligned_alloc (a, (size + a - 1) / a * a))
  106. return p;
  107. throw std::bad_alloc();
  108. }
  109. void* operator new[] (std::size_t size, std::align_val_t al) { return operator new (size, al); }
  110. void operator delete (void* p) noexcept { std::free (p); }
  111. void operator delete[] (void* p) noexcept { std::free (p); }
  112. void operator delete (void* p, std::size_t) noexcept { std::free (p); }
  113. void operator delete[] (void* p, std::size_t) noexcept { std::free (p); }
  114. void operator delete (void* p, std::align_val_t) noexcept { std::free (p); }
  115. void operator delete[] (void* p, std::align_val_t) noexcept { std::free (p); }
  116. void operator delete (void* p, std::size_t, std::align_val_t) noexcept { std::free (p); }
  117. void operator delete[] (void* p, std::size_t, std::align_val_t) noexcept { std::free (p); }
  118. namespace
  119. {
  120. using namespace lynx;
  121. namespace fs = std::filesystem;
  122. double threadCpuMs()
  123. {
  124. timespec ts {};
  125. clock_gettime (CLOCK_THREAD_CPUTIME_ID, &ts);
  126. return ts.tv_sec * 1000.0 + ts.tv_nsec * 1e-6;
  127. }
  128. struct InstructionCounter
  129. {
  130. #if defined(__linux__)
  131. int fd = -1;
  132. InstructionCounter()
  133. {
  134. perf_event_attr a {};
  135. a.type = PERF_TYPE_HARDWARE;
  136. a.size = sizeof (a);
  137. a.config = PERF_COUNT_HW_INSTRUCTIONS;
  138. a.disabled = 1;
  139. a.exclude_kernel = 1;
  140. a.exclude_hv = 1;
  141. fd = (int) syscall (SYS_perf_event_open, &a, 0, -1, -1, 0);
  142. }
  143. ~InstructionCounter()
  144. {
  145. if (fd >= 0)
  146. close (fd);
  147. }
  148. void start() { if (fd >= 0) { ioctl (fd, PERF_EVENT_IOC_RESET, 0); ioctl (fd, PERF_EVENT_IOC_ENABLE, 0); } }
  149. void stop() { if (fd >= 0) ioctl (fd, PERF_EVENT_IOC_DISABLE, 0); }
  150. long long read()
  151. {
  152. long long v = -1;
  153. if (fd >= 0 && ::read (fd, &v, sizeof (v)) != (ssize_t) sizeof (v))
  154. v = -1;
  155. return v;
  156. }
  157. #else
  158. void start() {}
  159. void stop() {}
  160. long long read() { return -1; }
  161. #endif
  162. };
  163. std::size_t heapBytes()
  164. {
  165. const auto m = mallinfo2();
  166. return m.uordblks + m.hblkhd;
  167. }
  168. std::string local (std::string p)
  169. {
  170. std::replace (p.begin(), p.end(), '\\', '/');
  171. return existingPathIgnoringCase (p);
  172. }
  173. natives::FlAccess flAccess (const std::string& data)
  174. {
  175. natives::FlAccess fl;
  176. if (data.empty())
  177. return fl;
  178. fl.roots.data = fs::path (data).string();
  179. fl.roots.factoryData = fs::path (data).parent_path().string();
  180. fl.fileExists = [] (const std::string& p) { return fs::is_regular_file (local (p)); };
  181. fl.readFile = [] (const std::string& p) {
  182. std::ifstream f (local (p), std::ios::binary);
  183. return std::vector<std::uint8_t> { std::istreambuf_iterator<char> (f), {} };
  184. };
  185. fl.listPresets = [] (const std::string& folder) {
  186. std::vector<std::string> out;
  187. std::error_code ec;
  188. for (const auto& e : fs::recursive_directory_iterator (local (folder), ec))
  189. if (e.is_regular_file())
  190. out.push_back (e.path().string());
  191. std::sort (out.begin(), out.end());
  192. return out;
  193. };
  194. fl.saveEmbedded = [] (const std::vector<std::uint8_t>& wav, const std::string& name) {
  195. const auto path = (fs::temp_directory_path() / ("lynx-nativebench-" + std::to_string (::getpid()) + "-" + std::to_string (wav.size()) + "-"
  196. + std::to_string (name.size()) + ".wav")).string();
  197. std::ofstream (path, std::ios::binary).write ((const char*) wav.data(), (std::streamsize) wav.size());
  198. return path;
  199. };
  200. return fl;
  201. }
  202. // the effects' programme at `rate`: a kick every beat, 16th hats, a saw-chord pad (120 BPM), deterministic
  203. std::shared_ptr<SampleData> programme (double rate, double seconds)
  204. {
  205. auto d = std::make_shared<SampleData>();
  206. d->sampleRate = rate;
  207. const auto frames = (std::size_t) (rate * seconds);
  208. d->left.resize (frames);
  209. d->right.resize (frames);
  210. std::uint32_t seed = 987654321u;
  211. const double chord[4] = { 130.81, 164.81, 196.0, 246.94 };
  212. double phase[8] {};
  213. double lp = 0.0, lpR = 0.0;
  214. for (std::size_t i = 0; i < frames; ++i)
  215. {
  216. const auto t = (double) i / rate;
  217. const auto beat = std::fmod (t * 2.0, 1.0) / 2.0; // seconds since the beat
  218. const auto six = std::fmod (t * 8.0, 1.0) / 8.0; // since the 16th
  219. const auto kick = std::exp (-beat * 18.0) * std::sin (6.283185307179586 * (50.0 * beat + 2.2 * (1.0 - std::exp (-beat * 40.0))));
  220. seed = seed * 1664525u + 1013904223u;
  221. const auto noise = (double) ((int) (seed >> 9) - (1 << 22)) / (double) (1 << 22);
  222. const auto hat = std::exp (-six * 160.0) * noise;
  223. double padL = 0.0, padR = 0.0;
  224. for (int k = 0; k < 4; ++k)
  225. {
  226. for (int s = 0; s < 2; ++s)
  227. {
  228. auto& ph = phase[k * 2 + s];
  229. ph += chord[k] * (s == 0 ? 0.997 : 1.003) / rate;
  230. ph -= std::floor (ph);
  231. (s == 0 ? padL : padR) += 2.0 * ph - 1.0;
  232. }
  233. }
  234. lp += 0.08 * (padL - lp);
  235. lpR += 0.08 * (padR - lpR);
  236. d->left[i] = (float) (0.45 * kick + 0.08 * hat + 0.05 * lp);
  237. d->right[i] = (float) (0.45 * kick + 0.07 * hat + 0.05 * lpR);
  238. }
  239. return d;
  240. }
  241. struct Config
  242. {
  243. double rate;
  244. int block;
  245. };
  246. struct Run
  247. {
  248. long long instr = 0;
  249. double cpuMs = 0.0;
  250. std::vector<long long> blocks;
  251. std::uint64_t hash = 0;
  252. long allocs = 0;
  253. std::size_t samples = 0;
  254. std::size_t heapAfterBuild = 0, heapBefore = 0;
  255. double peakOut = 0.0;
  256. };
  257. std::uint64_t hashOf (const std::vector<float>& l, const std::vector<float>& r)
  258. {
  259. std::uint64_t h = 1469598103934665603ull;
  260. for (const auto* v : { &l, &r })
  261. for (const auto x : *v)
  262. {
  263. std::uint32_t bits;
  264. std::memcpy (&bits, &x, 4);
  265. h = (h ^ bits) * 1099511628211ull;
  266. }
  267. return h;
  268. }
  269. constexpr double bpm = 120.0;
  270. // renders `song` for warmup + seconds (playing), measures the last `seconds`
  271. // `playSeconds` >= 0: the transport stops after that many seconds (the instruments' silence: their notes end, the song stops)
  272. Run render (const Song& song, const RackState::SampleProvider& provider, const Config& c, double warmup, double seconds, double playSeconds = -1.0)
  273. {
  274. Run run;
  275. run.heapBefore = heapBytes();
  276. auto state = RackState::build (song, nullptr, c.rate, provider);
  277. run.heapAfterBuild = heapBytes();
  278. auto renderer = std::make_unique<RackRenderer>();
  279. renderer->prepare (c.rate, std::max (2048, c.block));
  280. auto live = std::make_unique<LiveEventQueue>();
  281. const auto tps = ticksPerSample (bpm, c.rate);
  282. std::vector<float> l ((std::size_t) c.block), r ((std::size_t) c.block);
  283. double tick = 0.0;
  284. const auto warmBlocks = (int) std::ceil (warmup * c.rate / c.block);
  285. const auto playBlocks = playSeconds < 0.0 ? 1 << 30 : (int) std::ceil (playSeconds * c.rate / c.block);
  286. int played = 0;
  287. auto playing = [&] { return played++ < playBlocks; };
  288. for (int b = 0; b < warmBlocks; ++b)
  289. {
  290. const auto on = playing();
  291. renderer->process (state.get(), on, tick, c.block, l.data(), r.data(), live.get(), nullptr);
  292. tick += on ? c.block * tps : 0.0;
  293. }
  294. const auto blocks = (int) std::ceil (seconds * c.rate / c.block);
  295. std::vector<float> outL, outR;
  296. outL.reserve ((std::size_t) blocks * (std::size_t) c.block);
  297. outR.reserve ((std::size_t) blocks * (std::size_t) c.block);
  298. run.blocks.reserve ((std::size_t) blocks);
  299. InstructionCounter counter;
  300. allocCount.store (0);
  301. const auto cpu0 = threadCpuMs();
  302. for (int b = 0; b < blocks; ++b)
  303. {
  304. const auto on = playing();
  305. countingAllocs.store (true, std::memory_order_relaxed);
  306. counter.start();
  307. renderer->process (state.get(), on, tick, c.block, l.data(), r.data(), live.get(), nullptr);
  308. counter.stop();
  309. countingAllocs.store (false, std::memory_order_relaxed);
  310. const auto n = counter.read();
  311. run.blocks.push_back (n);
  312. run.instr += n;
  313. tick += on ? c.block * tps : 0.0;
  314. outL.insert (outL.end(), l.begin(), l.end());
  315. outR.insert (outR.end(), r.begin(), r.end());
  316. }
  317. run.cpuMs = threadCpuMs() - cpu0;
  318. run.allocs = allocCount.load();
  319. run.samples = (std::size_t) blocks * (std::size_t) c.block;
  320. run.hash = hashOf (outL, outR);
  321. for (std::size_t i = 0; i < outL.size(); ++i)
  322. run.peakOut = std::max (run.peakOut, (double) std::max (std::fabs (outL[i]), std::fabs (outR[i])));
  323. return run;
  324. }
  325. Note note (int channel, double beat, double beats, int key, float velocity)
  326. {
  327. Note n;
  328. n.channel = channel;
  329. n.start = (std::int64_t) (beat * ppq);
  330. n.length = (std::int64_t) (beats * ppq);
  331. n.key = key;
  332. n.velocity = velocity;
  333. return n;
  334. }
  335. // the effects' song: the programme as an audio clip on insert 1 (with `slots` on it, `copies` times on inserts 1..copies)
  336. Song effectSong (const std::vector<EffectSlot>& slots, int copies, bool withInput, double seconds)
  337. {
  338. Song song;
  339. song.bpm = bpm;
  340. song.mixer = Song::defaultMixer (std::max (2, copies));
  341. for (int k = 0; k < copies; ++k)
  342. for (const auto& s : slots)
  343. song.mixer[(std::size_t) (1 + k)].effects.push_back (s);
  344. ChannelDef ch;
  345. ch.name = "Programme";
  346. ch.instrument = InstrumentKind::audioClip;
  347. ch.samplePath = "/nativebench/programme.wav";
  348. ch.mixerTrack = 1;
  349. ch.volume = 0.8f;
  350. song.channels.push_back (ch);
  351. if (withInput)
  352. {
  353. Clip clip;
  354. clip.kind = ClipKind::audio;
  355. clip.channel = 0;
  356. clip.track = 0;
  357. clip.start = 0;
  358. clip.length = (std::int64_t) (seconds * bpm / 60.0 * ppq);
  359. song.playlist.push_back (clip);
  360. }
  361. song.mode = PlayMode::song;
  362. return song;
  363. }
  364. // the instruments' song: `channel` on insert 1 playing chords + a line for `beats` (none: no notes)
  365. Song instrumentSong (const ChannelDef* channel, double beats)
  366. {
  367. Song song;
  368. song.bpm = bpm;
  369. song.mixer = Song::defaultMixer (2);
  370. if (channel != nullptr)
  371. {
  372. auto ch = *channel;
  373. ch.mixerTrack = 1;
  374. song.channels.push_back (ch);
  375. auto& p = song.patterns.emplace_back();
  376. p.name = "Bench";
  377. const int roots[4] = { 48, 45, 41, 43 };
  378. for (int bar = 0; bar * 4 < (int) beats; ++bar)
  379. {
  380. const auto root = roots[bar % 4];
  381. for (int k : { 0, 4, 7, 11 })
  382. p.notes.push_back (note (0, bar * 4, 3.5, root + k, 0.75f));
  383. for (int e = 0; e < 8; ++e)
  384. p.notes.push_back (note (0, bar * 4 + e * 0.5, 0.4, root + 12 + (e * 5) % 12, 0.8f));
  385. }
  386. Clip clip;
  387. clip.pattern = 0;
  388. clip.start = 0;
  389. clip.length = (std::int64_t) (beats * ppq);
  390. song.playlist.push_back (clip);
  391. }
  392. song.mode = PlayMode::song;
  393. return song;
  394. }
  395. std::vector<std::string> split (const std::string& s, char sep = ',')
  396. {
  397. std::vector<std::string> out;
  398. std::string cur;
  399. for (const auto ch : s)
  400. if (ch == sep)
  401. {
  402. if (! cur.empty())
  403. out.push_back (cur);
  404. cur.clear();
  405. }
  406. else
  407. cur += ch;
  408. if (! cur.empty())
  409. out.push_back (cur);
  410. return out;
  411. }
  412. std::string lower (std::string s)
  413. {
  414. for (auto& ch : s)
  415. ch = (char) std::tolower ((unsigned char) ch);
  416. return s;
  417. }
  418. struct Stats
  419. {
  420. double perSample = 0.0; // engine instructions per sample
  421. double cpuPct = 0.0; // engine thread CPU, % of a core at real time (noisy)
  422. double spike = 0.0; // the engine's p99 block / its median block
  423. double worst = 0.0; // the engine's longest block / its median block
  424. };
  425. Stats diff (const Run& with, const Run& base, double rate)
  426. {
  427. Stats s;
  428. s.perSample = (double) (with.instr - base.instr) / (double) with.samples;
  429. const auto audioMs = 1000.0 * (double) with.samples / rate;
  430. s.cpuPct = 100.0 * (with.cpuMs - base.cpuMs) / audioMs;
  431. std::vector<long long> d;
  432. const auto n = std::min (with.blocks.size(), base.blocks.size());
  433. for (std::size_t i = 0; i < n; ++i)
  434. d.push_back (with.blocks[i] - base.blocks[i]);
  435. std::sort (d.begin(), d.end());
  436. if (! d.empty() && d[d.size() / 2] > 0)
  437. {
  438. s.spike = (double) d[std::min (d.size() - 1, (std::size_t) (0.99 * (double) d.size()))] / (double) d[d.size() / 2];
  439. s.worst = (double) d.back() / (double) d[d.size() / 2];
  440. }
  441. return s;
  442. }
  443. } // namespace
  444. int main (int argc, char** argv)
  445. {
  446. #if defined(__x86_64__)
  447. _mm_setcsr (_mm_getcsr() | 0x8040u); // FTZ + DAZ, as LYNX's audio threads
  448. #endif
  449. std::string flData, tsvPath, hashPath, kinds = "all";
  450. std::vector<Config> configs;
  451. std::vector<double> rates { 44100.0, 48000.0 };
  452. std::vector<int> blocks { 128, 512 };
  453. std::set<std::string> only;
  454. double seconds = 3.0;
  455. for (int i = 1; i < argc; ++i)
  456. {
  457. const std::string a = argv[i];
  458. auto next = [&] { return i + 1 < argc ? std::string (argv[++i]) : std::string(); };
  459. if (a == "--fl")
  460. flData = next();
  461. else if (a == "--tsv")
  462. tsvPath = next();
  463. else if (a == "--hashes")
  464. hashPath = next();
  465. else if (a == "--kinds")
  466. kinds = next();
  467. else if (a == "--seconds")
  468. seconds = std::max (0.5, std::atof (next().c_str()));
  469. else if (a == "--rates")
  470. {
  471. rates.clear();
  472. for (const auto& r : split (next()))
  473. rates.push_back (std::atof (r.c_str()));
  474. }
  475. else if (a == "--blocks")
  476. {
  477. blocks.clear();
  478. for (const auto& b : split (next()))
  479. blocks.push_back (std::atoi (b.c_str()));
  480. }
  481. else if (a == "--only")
  482. for (const auto& n : split (next()))
  483. only.insert (lower (n));
  484. }
  485. for (const auto r : rates)
  486. for (const auto b : blocks)
  487. configs.push_back ({ r, b });
  488. const auto fl = flAccess (flData);
  489. std::FILE* tsv = tsvPath.empty() ? nullptr : std::fopen (tsvPath.c_str(), "w");
  490. std::FILE* hashes = hashPath.empty() ? nullptr : std::fopen (hashPath.c_str(), "w");
  491. if (tsv != nullptr)
  492. std::fprintf (tsv, "group\tname\tkind\trate\tblock\tmode\tinstr_per_sample\tcpu_pct\tp99_over_median\tworst_over_median\tallocs\tpeak\t"
  493. "heap_first_kb\theap_next_kb\tnote\n");
  494. const double warmup = 1.0, smartWarmup = 6.0;
  495. std::map<double, std::shared_ptr<SampleData>> progs;
  496. for (const auto r : rates)
  497. progs[r] = programme (r, warmup + smartWarmup + seconds + 1.0);
  498. double currentRate = 44100.0;
  499. const RackState::SampleProvider provider = [&] (const std::string& p) -> std::shared_ptr<const SampleData> {
  500. if (p == "/nativebench/programme.wav")
  501. return progs[currentRate];
  502. return tools::readWav (local (p));
  503. };
  504. auto emit = [&] (const char* group, const std::string& name, int kind, const Config& c, const char* mode, const Stats& s, const Run& with,
  505. double heapFirstKb, double heapNextKb, const std::string& note) {
  506. std::printf ("%-5s %-28s %6.0f/%-4d %-10s %9.1f instr/sample %6.2f %% spike %5.2f / %6.2f allocs %ld peak %.3f heap %.0f + %.0f KB %s\n", group,
  507. name.c_str(), c.rate, c.block, mode, s.perSample, s.cpuPct, s.spike, s.worst, with.allocs, with.peakOut, heapFirstKb, heapNextKb,
  508. note.c_str());
  509. std::fflush (stdout);
  510. if (tsv != nullptr)
  511. {
  512. std::fprintf (tsv, "%s\t%s\t%d\t%.0f\t%d\t%s\t%.2f\t%.3f\t%.3f\t%.3f\t%ld\t%.5f\t%.1f\t%.1f\t%s\n", group, name.c_str(), kind, c.rate, c.block, mode,
  513. s.perSample, s.cpuPct, s.spike, s.worst, with.allocs, with.peakOut, heapFirstKb, heapNextKb, note.c_str());
  514. std::fflush (tsv);
  515. }
  516. if (hashes != nullptr)
  517. {
  518. std::fprintf (hashes, "%s %s %.0f/%d %s %016llx\n", group, name.c_str(), c.rate, c.block, mode, (unsigned long long) with.hash);
  519. std::fflush (hashes);
  520. }
  521. };
  522. // ---- effects
  523. if (kinds == "all" || kinds == "fx")
  524. {
  525. // baselines per configuration and mode
  526. struct Base { Run signal, silence, smart; };
  527. std::map<int, Base> base;
  528. for (std::size_t k = 0; k < configs.size(); ++k)
  529. {
  530. currentRate = configs[k].rate;
  531. base[(int) k].signal = render (effectSong ({}, 1, true, 30.0), provider, configs[k], warmup, seconds);
  532. base[(int) k].silence = render (effectSong ({}, 1, false, 30.0), provider, configs[k], warmup, seconds);
  533. base[(int) k].smart = render (effectSong ({}, 1, false, 30.0), provider, configs[k], smartWarmup, seconds);
  534. }
  535. static const std::set<EffectKind> skipped { EffectKind::plugin, EffectKind::parallel, EffectKind::hardwareInsert };
  536. for (int kindIndex = 0; kindIndex < 256; ++kindIndex)
  537. {
  538. const auto kind = (EffectKind) kindIndex;
  539. if (kindIndex > (int) EffectKind::timeprism) // (the last kind)
  540. break;
  541. if (skipped.count (kind) != 0)
  542. continue;
  543. const auto name = std::string (effectInfo (kind).name != nullptr ? effectInfo (kind).name : "?");
  544. if (! only.empty() && only.count (lower (name)) == 0)
  545. continue;
  546. auto made = natives::newEffect (kind, fl, bpm);
  547. if (! made)
  548. {
  549. std::printf ("fx %-28s not made here (needs FL Studio)\n", name.c_str());
  550. continue;
  551. }
  552. auto slot = *made;
  553. const auto& info = effectInfo (kind);
  554. for (std::size_t k = 0; k < configs.size(); ++k)
  555. {
  556. const auto& c = configs[k];
  557. currentRate = c.rate;
  558. // signal (+ the memory: one instance, two instances)
  559. const auto with = render (effectSong ({ slot }, 1, true, 30.0), provider, c, warmup, seconds);
  560. double firstKb = 0.0, nextKb = 0.0;
  561. if (k == 0)
  562. {
  563. const auto two = render (effectSong ({ slot }, 2, true, 30.0), provider, c, 0.0, 0.05);
  564. const auto baseHeap = (double) base[0].signal.heapAfterBuild - (double) base[0].signal.heapBefore;
  565. firstKb = ((double) with.heapAfterBuild - (double) with.heapBefore - baseHeap) / 1024.0;
  566. nextKb = ((double) two.heapAfterBuild - (double) two.heapBefore - ((double) with.heapAfterBuild - (double) with.heapBefore)) / 1024.0;
  567. }
  568. const auto sig = diff (with, base[(int) k].signal, c.rate);
  569. emit ("fx", name, kindIndex, c, "signal", sig, with, firstKb, nextKb, "");
  570. // silence, smart disable off: the effect's own behaviour
  571. auto awake = slot;
  572. awake.smartDisable = false;
  573. const auto quiet = render (effectSong ({ awake }, 1, false, 30.0), provider, c, warmup, seconds);
  574. const auto qs = diff (quiet, base[(int) k].silence, c.rate);
  575. char ratio[64];
  576. std::snprintf (ratio, sizeof (ratio), "x%.2f of signal", sig.perSample > 0.0 ? qs.perSample / sig.perSample : 0.0);
  577. emit ("fx", name, kindIndex, c, "silence", qs, quiet, 0.0, 0.0, ratio);
  578. // silence, smart disable as made (on): after the hold
  579. const auto smart = render (effectSong ({ slot }, 1, false, 30.0), provider, c, smartWarmup, seconds);
  580. const auto ss = diff (smart, base[(int) k].smart, c.rate);
  581. emit ("fx", name, kindIndex, c, "smart", ss, smart, 0.0, 0.0, slot.smartDisable ? "smart disable on" : "smart disable off as made");
  582. // automation: the first two parameters moving
  583. if (! info.params.empty())
  584. {
  585. auto song = effectSong ({ slot }, 1, true, 30.0);
  586. std::string names;
  587. for (int p = 0; p < std::min<int> (2, (int) info.params.size()); ++p)
  588. {
  589. Automation a;
  590. a.name = "p" + std::to_string (p);
  591. a.target.kind = AutomationTargetKind::effectParam;
  592. a.target.index = 1;
  593. a.target.slot = 0;
  594. a.target.param = p;
  595. const auto d = info.params[(std::size_t) p].defaultValue;
  596. const auto lo = std::clamp (d - 0.2f, 0.0f, 1.0f), hi = std::clamp (d + 0.2f, 0.0f, 1.0f);
  597. for (double b = 0.0; b <= 64.0; b += 0.25)
  598. {
  599. AutomationPoint pt;
  600. pt.tick = (std::int64_t) std::llround (b * ppq);
  601. pt.value = lo + (hi - lo) * (float) (0.5 + 0.5 * std::sin (b * 0.9 + p));
  602. a.points.push_back (pt);
  603. }
  604. song.automations.push_back (a);
  605. Clip clip;
  606. clip.kind = ClipKind::automation;
  607. clip.automation = (int) song.automations.size() - 1;
  608. clip.pattern = 0;
  609. clip.track = 2 + p;
  610. clip.start = 0;
  611. clip.length = 64 * ppq;
  612. song.playlist.push_back (clip);
  613. names += (names.empty() ? "" : "+") + std::string (info.params[(std::size_t) p].name);
  614. }
  615. const auto moving = render (song, provider, c, warmup, seconds);
  616. const auto ms = diff (moving, base[(int) k].signal, c.rate);
  617. char text[160];
  618. std::snprintf (text, sizeof (text), "x%.2f of signal (%s)", sig.perSample > 0.0 ? ms.perSample / sig.perSample : 0.0, names.c_str());
  619. emit ("fx", name, kindIndex, c, "automation", ms, moving, 0.0, 0.0, text);
  620. }
  621. }
  622. }
  623. }
  624. // ---- instruments
  625. if (kinds == "all" || kinds == "inst")
  626. {
  627. struct Item
  628. {
  629. std::string name;
  630. ChannelDef channel;
  631. };
  632. std::vector<Item> items;
  633. auto own = [&] (const char* n, InstrumentKind kind) {
  634. ChannelDef ch;
  635. ch.name = n;
  636. ch.instrument = kind;
  637. items.push_back ({ n, ch });
  638. };
  639. own ("LYNX Synth (default)", InstrumentKind::synth);
  640. {
  641. const auto presets = synthPresets();
  642. for (std::size_t k : { (std::size_t) 3, (std::size_t) 7 })
  643. if (k < presets.size())
  644. {
  645. ChannelDef ch;
  646. ch.instrument = InstrumentKind::synth;
  647. ch.synth = presets[k].second;
  648. ch.name = "LYNX Synth (" + presets[k].first + ")";
  649. items.push_back ({ ch.name, ch });
  650. }
  651. }
  652. own ("Kick", InstrumentKind::kick);
  653. own ("Snare", InstrumentKind::snare);
  654. own ("Hat", InstrumentKind::hat);
  655. own ("Clap", InstrumentKind::clap);
  656. own ("Fruity DrumSynth Live", InstrumentKind::drumsynth);
  657. for (const auto& e : natives::instrumentEngines())
  658. {
  659. auto c = natives::makeChannel (e.kind, fl);
  660. if (! c)
  661. {
  662. std::printf ("inst %-28s not made here (needs FL Studio)\n", e.name);
  663. continue;
  664. }
  665. if (e.kind == InstrumentKind::granulizer && c->samplePath.empty() && ! flData.empty())
  666. c->samplePath = (fs::path (flData) / "Patches" / "Packs" / "Loops" / "DL Pendulus.wav").string();
  667. items.push_back ({ e.name, *c });
  668. }
  669. std::map<int, Run> base, baseStopped;
  670. for (std::size_t k = 0; k < configs.size(); ++k)
  671. {
  672. currentRate = configs[k].rate;
  673. base[(int) k] = render (instrumentSong (nullptr, 64.0), provider, configs[k], warmup, seconds);
  674. baseStopped[(int) k] = render (instrumentSong (nullptr, 64.0), provider, configs[k], 2.0 + 2.0, seconds, 2.0);
  675. }
  676. for (const auto& item : items)
  677. {
  678. if (! only.empty() && only.count (lower (item.name)) == 0)
  679. continue;
  680. for (std::size_t k = 0; k < configs.size(); ++k)
  681. {
  682. const auto& c = configs[k];
  683. currentRate = c.rate;
  684. const auto song = instrumentSong (&item.channel, 64.0);
  685. const auto with = render (song, provider, c, warmup, seconds);
  686. double firstKb = 0.0;
  687. if (k == 0)
  688. firstKb = ((double) with.heapAfterBuild - (double) with.heapBefore - ((double) base[0].heapAfterBuild - (double) base[0].heapBefore)) / 1024.0;
  689. const auto sig = diff (with, base[(int) k], c.rate);
  690. emit ("inst", item.name, (int) item.channel.instrument, c, "signal", sig, with, firstKb, 0.0, with.peakOut < 1e-6 ? "SILENT" : "");
  691. // after the notes: 2 s of the song, then stopped (its notes end); measured from 2 s after the stop
  692. const auto quiet = render (song, provider, c, 2.0 + 2.0, seconds, 2.0);
  693. const auto qs = diff (quiet, baseStopped[(int) k], c.rate);
  694. char ratio[64];
  695. std::snprintf (ratio, sizeof (ratio), "x%.3f of signal", sig.perSample > 0.0 ? qs.perSample / sig.perSample : 0.0);
  696. emit ("inst", item.name, (int) item.channel.instrument, c, "silence", qs, quiet, 0.0, 0.0, ratio);
  697. }
  698. }
  699. }
  700. if (tsv != nullptr)
  701. std::fclose (tsv);
  702. if (hashes != nullptr)
  703. std::fclose (hashes);
  704. std::printf ("DONE\n");
  705. return 0;
  706. }