renderwav.cpp 26 KB

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