renderwav.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. // renderwav: imports an .flp and renders a pattern with the built-in instruments.
  2. // Usage: renderwav project.flp output.wav [pattern-index] [loops]
  3. // Without an index, picks the pattern with the most notes.
  4. //
  5. // Real-time diagnostics (REA round 87), environment variables:
  6. // LYNX_BLOCK=n block size (default 256)
  7. // LYNX_THREADS=n n worker threads, as the app's audio engine uses
  8. // LYNX_REALTIME=1 paces the blocks at real time (the workers sleep between blocks, as with a sound card)
  9. // LYNX_PROFILE=1 per-channel / per-insert-effect CPU time, heaviest first
  10. // LYNX_ALLOCS=1 counts the heap allocations made while a block is processed (the audio thread and the
  11. // workers; round 167e) and prints where the first distinct ones came from (Linux: addresses for
  12. // addr2line -e renderwav)
  13. // The block timing report (budget = block duration) is always printed.
  14. #include <cctype>
  15. #include <cmath>
  16. #include <cstdio>
  17. #include <cstdlib>
  18. #include <cstring>
  19. #include <fstream>
  20. #include <iterator>
  21. #include <vector>
  22. #include <algorithm>
  23. #include <filesystem>
  24. #include <map>
  25. #include <sstream>
  26. #include <string>
  27. #include <chrono>
  28. #include <thread>
  29. #include <time.h>
  30. #include <atomic>
  31. #include <new>
  32. #if defined(__linux__)
  33. #include <execinfo.h>
  34. #endif
  35. #if defined(_WIN32)
  36. #define WIN32_LEAN_AND_MEAN
  37. #define NOMINMAX
  38. #include <windows.h>
  39. #include <mmsystem.h>
  40. #endif
  41. #include "WavReader.h"
  42. #include "core/FlpImport.h"
  43. #include "core/PluginSubstitutes.h"
  44. #include "core/RackRenderer.h"
  45. #include "core/WorkerPool.h"
  46. // LYNX_ALLOCS: every operator new while `counting` is set (inside RackRenderer::process) is counted
  47. namespace allocs
  48. {
  49. std::atomic<bool> counting { false };
  50. std::atomic<long> count { 0 };
  51. constexpr int maxSites = 96, depth = 12;
  52. struct Site
  53. {
  54. void* frames[depth] {};
  55. int n = 0;
  56. long hits = 0;
  57. };
  58. Site sites[maxSites];
  59. std::atomic<int> siteCount { 0 };
  60. std::atomic_flag recording = ATOMIC_FLAG_INIT;
  61. void note() noexcept
  62. {
  63. count.fetch_add (1, std::memory_order_relaxed);
  64. #if defined(__linux__)
  65. if (recording.test_and_set()) // (one at a time; backtrace() itself may allocate once: not counted, flag held)
  66. return;
  67. counting.store (false);
  68. void* f[depth + 2];
  69. const auto n = backtrace (f, depth + 2);
  70. const auto used = std::max (0, n - 2);
  71. bool found = false;
  72. for (int i = 0; i < siteCount.load() && ! found; ++i)
  73. if (sites[i].n == used && std::equal (f + 2, f + 2 + used, sites[i].frames))
  74. found = ++sites[i].hits > 0;
  75. if (! found && siteCount.load() < maxSites)
  76. {
  77. auto& s = sites[siteCount.load()];
  78. s.n = used;
  79. std::copy (f + 2, f + 2 + used, s.frames);
  80. s.hits = 1;
  81. siteCount.fetch_add (1);
  82. }
  83. counting.store (true);
  84. recording.clear();
  85. #endif
  86. }
  87. } // namespace allocs
  88. void* operator new (std::size_t n)
  89. {
  90. if (allocs::counting.load (std::memory_order_relaxed))
  91. allocs::note();
  92. if (auto* p = std::malloc (n > 0 ? n : 1))
  93. return p;
  94. throw std::bad_alloc();
  95. }
  96. void* operator new[] (std::size_t n) { return operator new (n); }
  97. void* operator new (std::size_t n, const std::nothrow_t&) noexcept
  98. {
  99. if (allocs::counting.load (std::memory_order_relaxed))
  100. allocs::note();
  101. return std::malloc (n > 0 ? n : 1);
  102. }
  103. void* operator new[] (std::size_t n, const std::nothrow_t& t) noexcept { return operator new (n, t); }
  104. void operator delete (void* p) noexcept { std::free (p); }
  105. void operator delete[] (void* p) noexcept { std::free (p); }
  106. void operator delete (void* p, std::size_t) noexcept { std::free (p); }
  107. void operator delete[] (void* p, std::size_t) noexcept { std::free (p); }
  108. namespace
  109. {
  110. // like the app's audio threads: MMCSS "Pro Audio" on Windows (with a 1 ms timer for the real-time pacing)
  111. void realtimePriority()
  112. {
  113. #if defined(_WIN32)
  114. using AvSet = void* (__stdcall*) (const wchar_t*, unsigned long*);
  115. static const auto avSet = [] () -> AvSet {
  116. if (auto* avrt = LoadLibraryW (L"avrt.dll"))
  117. return reinterpret_cast<AvSet> (reinterpret_cast<void*> (GetProcAddress (avrt, "AvSetMmThreadCharacteristicsW")));
  118. return nullptr;
  119. }();
  120. unsigned long task = 0;
  121. if (avSet == nullptr || avSet (L"Pro Audio", &task) == nullptr)
  122. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  123. #endif
  124. }
  125. void writeWav (const char* path, const std::vector<float>& left, const std::vector<float>& right, int sampleRate)
  126. {
  127. std::ofstream out (path, std::ios::binary);
  128. auto u32 = [&] (std::uint32_t v) { out.write ((const char*) &v, 4); };
  129. auto u16 = [&] (std::uint16_t v) { out.write ((const char*) &v, 2); };
  130. const auto frames = (std::uint32_t) left.size();
  131. const auto dataBytes = frames * 4;
  132. out.write ("RIFF", 4);
  133. u32 (36 + dataBytes);
  134. out.write ("WAVEfmt ", 8);
  135. u32 (16);
  136. u16 (1); // PCM
  137. u16 (2); // stereo
  138. u32 ((std::uint32_t) sampleRate);
  139. u32 ((std::uint32_t) sampleRate * 4);
  140. u16 (4);
  141. u16 (16);
  142. out.write ("data", 4);
  143. u32 (dataBytes);
  144. for (std::uint32_t i = 0; i < frames; ++i)
  145. for (float s : { left[i], right[i] })
  146. {
  147. const auto clipped = s > 1.0f ? 1.0f : (s < -1.0f ? -1.0f : s);
  148. u16 ((std::uint16_t) (std::int16_t) (clipped * 32767.0f));
  149. }
  150. }
  151. } // namespace
  152. int main (int argc, char** argv)
  153. {
  154. if (argc < 3)
  155. {
  156. std::fprintf (stderr, "usage: renderwav project.flp output.wav [pattern] [loops]\n");
  157. return 2;
  158. }
  159. std::ifstream in (argv[1], std::ios::binary);
  160. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  161. lynx::Song song;
  162. // On Linux/WSL FL lives under /mnt/c; the .flp paths use backslashes.
  163. const std::string flRoot = std::getenv ("FL_ROOT") ? std::getenv ("FL_ROOT")
  164. #if defined(_WIN32)
  165. : "C:/Program Files/Image-Line/FL Studio 2026";
  166. #else
  167. : "/mnt/c/Program Files/Image-Line/FL Studio 2026";
  168. #endif
  169. auto toLocal = [] (std::string p) {
  170. std::replace (p.begin(), p.end(), '\\', '/');
  171. // absolute Windows paths ("C:/...") → the WSL mount ("/mnt/c/...")
  172. #if ! defined(_WIN32) // (the Windows build of this tool reads them as they are)
  173. if (p.size() > 2 && p[1] == ':' && p[2] == '/' && std::isalpha ((unsigned char) p[0]))
  174. p = "/mnt/" + std::string (1, (char) std::tolower ((unsigned char) p[0])) + p.substr (2);
  175. #endif
  176. return p;
  177. };
  178. lynx::FlpImportOptions options;
  179. options.roots = { flRoot, flRoot + "/Data", "" };
  180. options.fileExists = [&] (const std::string& p) { return std::filesystem::exists (toLocal (p)); };
  181. options.readFile = [&] (const std::string& p) { // (the rack compressors' presets of Harmless/Harmor)
  182. std::ifstream f (toLocal (p), std::ios::binary);
  183. return std::vector<std::uint8_t> ((std::istreambuf_iterator<char> (f)), std::istreambuf_iterator<char>());
  184. };
  185. const auto importStart = std::chrono::steady_clock::now();
  186. try
  187. {
  188. song = lynx::importFlp (flp::parseProject (bytes), options);
  189. std::printf ("import: %.0f ms\n", std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - importStart).count());
  190. }
  191. catch (const flp::Error& e)
  192. {
  193. std::fprintf (stderr, "error: %s\n", e.what());
  194. return 1;
  195. }
  196. // LYNX_SUBSTITUTES=1: third-party effects become their LYNX substitutes, as in the app when none is installed
  197. // (otherwise they stay unresolved, i.e. silent pass-through); LYNX_DISABLE="t.k t.k": those insert slots off
  198. if (const char* e = std::getenv ("LYNX_SUBSTITUTES"); e != nullptr && std::atoi (e) != 0)
  199. {
  200. const auto context = lynx::substituteContextOf (song);
  201. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  202. for (std::size_t k = 0; k < song.mixer[t].effects.size(); ++k)
  203. if (auto& fx = song.mixer[t].effects[k]; fx.kind == lynx::EffectKind::plugin && fx.plugin.foreign.format != lynx::ForeignPlugin::Format::none
  204. && lynx::substituteEffectSlot (fx, lynx::pluginIdentity (fx.plugin.foreign), context))
  205. std::printf ("insert %d: %s -> %s (slot %d.%d)\n", (int) t, lynx::substituteOriginalName (fx).c_str(), lynx::effectInfo (fx.kind).name, (int) t, (int) k);
  206. }
  207. // LYNX_SUBSTITUTES_BYPASS=1: the project's "substitutes bypassed" switch on (A/B)
  208. if (const char* e = std::getenv ("LYNX_SUBSTITUTES_BYPASS"); e != nullptr && std::atoi (e) != 0)
  209. song.substitutesBypassed = true;
  210. // LYNX_PARAM="t.k.p=v …": insert t, slot k, parameter p set to the normalised value v (experiments)
  211. if (const char* e = std::getenv ("LYNX_PARAM"))
  212. {
  213. std::istringstream list (e);
  214. std::string item;
  215. while (list >> item)
  216. {
  217. int t = -1, k = -1, prm = -1;
  218. float v = 0.0f;
  219. if (std::sscanf (item.c_str(), "%d.%d.%d=%f", &t, &k, &prm, &v) == 4 && t >= 0 && t < (int) song.mixer.size() && k >= 0
  220. && k < (int) song.mixer[(std::size_t) t].effects.size() && prm >= 0 && prm < lynx::maxEffectParams)
  221. song.mixer[(std::size_t) t].effects[(std::size_t) k].params[(std::size_t) prm] = v;
  222. }
  223. }
  224. if (const char* e = std::getenv ("LYNX_DISABLE"))
  225. {
  226. std::istringstream list (e);
  227. std::string item;
  228. while (list >> item)
  229. if (const auto dot = item.find ('.'); dot != std::string::npos)
  230. {
  231. const auto t = (std::size_t) std::atoi (item.substr (0, dot).c_str()), k = (std::size_t) std::atoi (item.substr (dot + 1).c_str());
  232. if (t < song.mixer.size() && k < song.mixer[t].effects.size())
  233. song.mixer[t].effects[k].enabled = false;
  234. }
  235. }
  236. // "song" instead of the index: the whole song (playlist), like the app's export
  237. const bool wholeSong = argc > 3 && std::string (argv[3]) == "song";
  238. std::int64_t songTicks = 0;
  239. if (wholeSong) // with the app's empty tail (1 s), so the song does not wrap to its start inside the rendered tail
  240. song = lynx::makeExportSong (song, true, (std::int64_t) std::ceil (lynx::ticksPerSample (song.bpm, 44100) * 44100.0), songTicks);
  241. int chosen = argc > 3 && ! wholeSong ? std::atoi (argv[3]) : -1;
  242. if (chosen < 0 || chosen >= (int) song.patterns.size())
  243. {
  244. chosen = 0;
  245. for (int i = 0; i < (int) song.patterns.size(); ++i)
  246. if (song.patterns[(std::size_t) i].notes.size() > song.patterns[(std::size_t) chosen].notes.size())
  247. chosen = i;
  248. }
  249. song.currentPattern = chosen;
  250. const int loops = argc > 4 ? std::max (1, std::atoi (argv[4])) : 2;
  251. const auto& pattern = song.patterns[(std::size_t) chosen];
  252. const auto lengthTicks = wholeSong ? songTicks : pattern.effectiveLength (song.beatsPerBar) * loops;
  253. constexpr int sampleRate = 44100;
  254. const int blockSize = std::getenv ("LYNX_BLOCK") ? std::clamp (std::atoi (std::getenv ("LYNX_BLOCK")), 16, 8192) : 256;
  255. const auto tps = lynx::ticksPerSample (song.bpm, sampleRate);
  256. auto totalSamples = (std::size_t) (lengthTicks / tps) + sampleRate; // +1 s of tail
  257. if (const char* s = std::getenv ("LYNX_SECONDS"); s != nullptr && std::atof (s) > 0) // benchmark: render only the start
  258. totalSamples = std::min (totalSamples, (std::size_t) (std::atof (s) * sampleRate));
  259. std::printf ("%.1f BPM, %zu channels, pattern \"%s\" (%zu notes), %d loops, %.1f s\n", song.bpm,
  260. song.channels.size(), pattern.name.c_str(), pattern.notes.size(), loops,
  261. (double) totalSamples / sampleRate);
  262. for (std::size_t i = 0; i < song.channels.size(); ++i)
  263. {
  264. static const char* kinds[] = { "kick", "snare", "hat", "clap", "synth", "sampler", "audio clip", "plugin", "controller", "sakura", "drumpad", "boobass", "drumsynth", "harmless", "sytrus", "harmor", "gms", "morphine", "ogun", "minisynth", "dx10", "kepler", "poizone", "fruit kick", "bassdrum", "toxic", "threeosc", "autogun", "transistor bass", "simsynth", "wasp", "plucked", "beepmap", "sawer", "granulizer" };
  265. const auto k = (std::size_t) song.channels[i].instrument;
  266. std::printf (" %2zu %-28s -> %s\n", i, song.channels[i].name.c_str(), k < std::size (kinds) ? kinds[k] : "?");
  267. }
  268. // like the app's export: instruments with FL render-quality settings use them (LYNX_LIVE=1: the live ones)
  269. lynx::setOfflineRendering (std::getenv ("LYNX_LIVE") == nullptr);
  270. std::map<std::string, std::shared_ptr<const lynx::SampleData>> cache;
  271. const auto buildStart = std::chrono::steady_clock::now();
  272. auto state = lynx::RackState::build (song, nullptr, sampleRate, [&] (const std::string& p) {
  273. auto& entry = cache[p];
  274. if (entry == nullptr)
  275. entry = lynx::tools::readWav (toLocal (p));
  276. if (entry == nullptr)
  277. std::printf (" (could not read %s)\n", p.c_str());
  278. return entry;
  279. });
  280. std::printf ("rack build: %.0f ms\n", std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - buildStart).count());
  281. {
  282. std::size_t edges = 0, delayed = 0, tracksWithFx = 0;
  283. for (const auto& ins : state->mixerInputs)
  284. for (const auto& in : ins)
  285. {
  286. ++edges;
  287. const auto& d = state->sendDelays[(std::size_t) in.source];
  288. delayed += (std::size_t) in.delay < d.size() && d[(std::size_t) in.delay] != nullptr;
  289. }
  290. for (const auto& t : song.mixer)
  291. tracksWithFx += ! t.effects.empty();
  292. std::printf ("mixer: %zu edges (%zu with PDC delay), %zu tracks with effects\n", edges, delayed, tracksWithFx);
  293. }
  294. lynx::RackRenderer renderer;
  295. // LYNX_THREADS=n: n worker threads for the channels and mixer layers, as the app's audio engine uses
  296. std::unique_ptr<lynx::WorkerPool> pool;
  297. if (const char* t = std::getenv ("LYNX_THREADS"); t != nullptr && std::atoi (t) > 0)
  298. {
  299. pool = std::make_unique<lynx::WorkerPool> (std::atoi (t), [] { realtimePriority(); });
  300. renderer.setWorkerPool (pool.get());
  301. }
  302. renderer.prepare (sampleRate, std::max (2048, blockSize));
  303. const bool profile = std::getenv ("LYNX_PROFILE") != nullptr;
  304. const bool countAllocs = std::getenv ("LYNX_ALLOCS") != nullptr;
  305. long blocksWithAllocs = 0;
  306. const bool realtime = std::getenv ("LYNX_REALTIME") != nullptr;
  307. #if defined(_WIN32)
  308. timeBeginPeriod (1);
  309. realtimePriority();
  310. #endif
  311. renderer.setProfiling (profile);
  312. std::vector<float> left (totalSamples), right (totalSamples);
  313. // the units whose latency is only known after their first block (the app then re-plans PDC once)
  314. const auto latenciesBefore = state->currentLatencies();
  315. const auto started = std::chrono::steady_clock::now();
  316. double tick = 0.0;
  317. const double budgetMs = 1000.0 * blockSize / sampleRate;
  318. std::vector<double> wallMs, cpuMs;
  319. auto threadCpuMs = [] {
  320. #if defined(_WIN32)
  321. FILETIME created, exited, kernel, user;
  322. GetThreadTimes (GetCurrentThread(), &created, &exited, &kernel, &user);
  323. return (((std::uint64_t) user.dwHighDateTime << 32 | user.dwLowDateTime) + ((std::uint64_t) kernel.dwHighDateTime << 32 | kernel.dwLowDateTime)) * 1e-4;
  324. #else
  325. timespec ts {};
  326. clock_gettime (CLOCK_THREAD_CPUTIME_ID, &ts);
  327. return ts.tv_sec * 1000.0 + ts.tv_nsec * 1e-6;
  328. #endif
  329. };
  330. for (std::size_t pos = 0; pos < totalSamples; pos += blockSize)
  331. {
  332. const auto n = (int) std::min<std::size_t> (blockSize, totalSamples - pos);
  333. const bool playing = tick < (double) lengthTicks;
  334. const auto t0 = std::chrono::steady_clock::now();
  335. const auto c0 = threadCpuMs();
  336. const auto allocsBefore = allocs::count.load();
  337. allocs::counting.store (countAllocs);
  338. renderer.process (state.get(), playing, tick, n, left.data() + pos, right.data() + pos);
  339. allocs::counting.store (false);
  340. blocksWithAllocs += allocs::count.load() != allocsBefore;
  341. wallMs.push_back (std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - t0).count());
  342. cpuMs.push_back (threadCpuMs() - c0);
  343. tick += n * tps;
  344. if (realtime) // the next block starts one block later, like a sound card's callback
  345. std::this_thread::sleep_until (started + std::chrono::microseconds ((long long) ((pos + (std::size_t) n) * 1.0e6 / sampleRate)));
  346. }
  347. {
  348. const auto after = state->currentLatencies();
  349. std::size_t index = song.channels.size();
  350. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  351. for (std::size_t k = 0; k < state->effects[t].size(); ++k, ++index)
  352. if (index < after.size() && after[index] != latenciesBefore[index])
  353. std::printf ("latency changed after the first block: insert %zu slot %zu %s: %d -> %d\n", t, k + 1,
  354. lynx::effectInfo (song.mixer[t].effects[k].kind).name, latenciesBefore[index], after[index]);
  355. }
  356. std::printf ("render: %.0f ms\n", std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - started).count());
  357. {
  358. auto report = [&] (const char* what, std::vector<double> v) {
  359. if (v.empty())
  360. return;
  361. double sum = 0.0;
  362. std::size_t over = 0, nearly = 0;
  363. for (auto x : v)
  364. sum += x, over += x >= budgetMs, nearly += x >= 0.8 * budgetMs && x < budgetMs;
  365. std::sort (v.begin(), v.end());
  366. auto pct = [&] (double p) { return v[std::min (v.size() - 1, (std::size_t) (p * (double) v.size()))]; };
  367. std::printf ("blocks %s: %zu x %d samples (budget %.2f ms): mean %.0f%%, p50 %.0f%%, p99 %.0f%%, max %.0f%%; "
  368. "over budget %zu (%.2f%%), 80-100%% %zu\n",
  369. what, v.size(), blockSize, budgetMs, 100.0 * sum / (double) v.size() / budgetMs, 100.0 * pct (0.5) / budgetMs,
  370. 100.0 * pct (0.99) / budgetMs, 100.0 * v.back() / budgetMs, over, 100.0 * (double) over / (double) v.size(), nearly);
  371. };
  372. report ("wall", wallMs);
  373. {
  374. // where the slowest blocks were (seconds into the render)
  375. std::vector<std::size_t> order (cpuMs.size());
  376. for (std::size_t i = 0; i < order.size(); ++i)
  377. order[i] = i;
  378. const auto& by = pool == nullptr ? cpuMs : wallMs;
  379. std::sort (order.begin(), order.end(), [&] (std::size_t a, std::size_t b) { return by[a] > by[b]; });
  380. std::printf ("slowest blocks:");
  381. for (std::size_t i = 0; i < order.size() && i < 8; ++i)
  382. std::printf (" %.2fs=%.0f%%", (double) (order[i] * (std::size_t) blockSize) / sampleRate, 100.0 * by[order[i]] / budgetMs);
  383. std::printf ("\n");
  384. }
  385. if (pool == nullptr)
  386. report ("thread-cpu", cpuMs);
  387. #if ! defined(LYNX_OLDPOOL)
  388. if (pool != nullptr)
  389. std::printf ("workers: %d threads ran %llu indices, %llu wake-ups\n", pool->workers(),
  390. (unsigned long long) pool->indicesRunByWorkers(), (unsigned long long) pool->wakeUps());
  391. #endif
  392. }
  393. if (countAllocs)
  394. {
  395. std::printf ("allocations while processing: %ld in %ld of %zu blocks\n", allocs::count.load(), blocksWithAllocs, wallMs.size());
  396. for (int i = 0; i < allocs::siteCount.load(); ++i)
  397. {
  398. std::printf (" site %d (%ld):", i, allocs::sites[i].hits);
  399. #if defined(__linux__)
  400. if (char** names = backtrace_symbols (allocs::sites[i].frames, allocs::sites[i].n))
  401. {
  402. for (int k = 0; k < allocs::sites[i].n; ++k)
  403. std::printf (" %s", std::strrchr (names[k], '(') != nullptr ? std::strrchr (names[k], '(') : names[k]);
  404. std::free (names);
  405. }
  406. #endif
  407. std::printf ("\n");
  408. }
  409. }
  410. if (profile)
  411. {
  412. const auto& u = renderer.unitTimes();
  413. const auto total = (double) u.processNs.load();
  414. struct Row
  415. {
  416. double ns;
  417. std::string name;
  418. double maxNs = 0.0;
  419. };
  420. std::vector<Row> rows;
  421. for (std::size_t c = 0; c < song.channels.size() && c < (std::size_t) lynx::RackRenderer::maxChannels; ++c)
  422. if (const auto ns = (double) u.channelNs[c].load(); ns > 0.0)
  423. rows.push_back ({ ns, "channel " + std::to_string (c) + " \"" + song.channels[c].name + "\"", (double) u.channelMaxNs[c].load() });
  424. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  425. for (std::size_t k = 0; k < song.mixer[t].effects.size() && k < (std::size_t) lynx::maxEffectSlots; ++k)
  426. if (const auto ns = (double) u.effectNs[t * lynx::maxEffectSlots + k].load(); ns > 0.0)
  427. rows.push_back ({ ns, "insert " + std::to_string (t) + " slot " + std::to_string (k + 1) + " "
  428. + lynx::effectInfo (song.mixer[t].effects[k].kind).name
  429. + (song.mixer[t].effects[k].plugin.name.empty() ? "" : " (" + song.mixer[t].effects[k].plugin.name + ")"),
  430. (double) u.effectMaxNs[t * lynx::maxEffectSlots + k].load() });
  431. std::sort (rows.begin(), rows.end(), [] (const Row& a, const Row& b) { return a.ns > b.ns; });
  432. const auto audioMs = 1000.0 * (double) u.processedSamples.load() / sampleRate;
  433. std::printf ("profile: process %.0f ms for %.0f ms of audio (units below are CPU time, summed over threads)\n", total * 1e-6, audioMs);
  434. for (std::size_t i = 0; i < rows.size() && i < 25; ++i)
  435. std::printf (" %6.1f%% of real time, longest call %7.2f ms %s\n", 100.0 * rows[i].ns * 1e-6 / std::max (1.0, audioMs),
  436. rows[i].maxNs * 1e-6, rows[i].name.c_str());
  437. // the spikes: units whose single call took longest
  438. std::sort (rows.begin(), rows.end(), [] (const Row& a, const Row& b) { return a.maxNs > b.maxNs; });
  439. std::printf ("longest single calls:\n");
  440. for (std::size_t i = 0; i < rows.size() && i < 10; ++i)
  441. std::printf (" %7.2f ms %s\n", rows[i].maxNs * 1e-6, rows[i].name.c_str());
  442. }
  443. // LYNX_RAW=path: also write the un-normalized float samples (L block then R block), for bit-exact comparisons
  444. if (const char* raw = std::getenv ("LYNX_RAW"); raw != nullptr)
  445. {
  446. std::ofstream r (raw, std::ios::binary);
  447. r.write ((const char*) left.data(), (std::streamsize) (left.size() * sizeof (float)));
  448. r.write ((const char*) right.data(), (std::streamsize) (right.size() * sizeof (float)));
  449. }
  450. // normalize the peak to -1 dBFS
  451. float peak = 0.0f;
  452. for (std::size_t i = 0; i < totalSamples; ++i)
  453. peak = std::max ({ peak, std::abs (left[i]), std::abs (right[i]) });
  454. std::printf ("peak before normalizing: %.4f\n", peak);
  455. if (peak > 0.0f)
  456. {
  457. const auto gain = 0.891f / peak;
  458. for (std::size_t i = 0; i < totalSamples; ++i)
  459. {
  460. left[i] *= gain;
  461. right[i] *= gain;
  462. }
  463. }
  464. writeWav (argv[2], left, right, sampleRate);
  465. std::printf ("written to %s\n", argv[2]);
  466. return 0;
  467. }