renderwav.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. // The block timing report (budget = block duration) is always printed.
  11. #include <cctype>
  12. #include <cstdio>
  13. #include <cstdlib>
  14. #include <fstream>
  15. #include <iterator>
  16. #include <vector>
  17. #include <algorithm>
  18. #include <filesystem>
  19. #include <map>
  20. #include <string>
  21. #include <chrono>
  22. #include <thread>
  23. #include <time.h>
  24. #if defined(_WIN32)
  25. #define WIN32_LEAN_AND_MEAN
  26. #define NOMINMAX
  27. #include <windows.h>
  28. #include <mmsystem.h>
  29. #endif
  30. #include "WavReader.h"
  31. #include "core/FlpImport.h"
  32. #include "core/RackRenderer.h"
  33. #include "core/WorkerPool.h"
  34. namespace
  35. {
  36. // like the app's audio threads: MMCSS "Pro Audio" on Windows (with a 1 ms timer for the real-time pacing)
  37. void realtimePriority()
  38. {
  39. #if defined(_WIN32)
  40. using AvSet = void* (__stdcall*) (const wchar_t*, unsigned long*);
  41. static const auto avSet = [] () -> AvSet {
  42. if (auto* avrt = LoadLibraryW (L"avrt.dll"))
  43. return reinterpret_cast<AvSet> (reinterpret_cast<void*> (GetProcAddress (avrt, "AvSetMmThreadCharacteristicsW")));
  44. return nullptr;
  45. }();
  46. unsigned long task = 0;
  47. if (avSet == nullptr || avSet (L"Pro Audio", &task) == nullptr)
  48. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  49. #endif
  50. }
  51. void writeWav (const char* path, const std::vector<float>& left, const std::vector<float>& right, int sampleRate)
  52. {
  53. std::ofstream out (path, std::ios::binary);
  54. auto u32 = [&] (std::uint32_t v) { out.write ((const char*) &v, 4); };
  55. auto u16 = [&] (std::uint16_t v) { out.write ((const char*) &v, 2); };
  56. const auto frames = (std::uint32_t) left.size();
  57. const auto dataBytes = frames * 4;
  58. out.write ("RIFF", 4);
  59. u32 (36 + dataBytes);
  60. out.write ("WAVEfmt ", 8);
  61. u32 (16);
  62. u16 (1); // PCM
  63. u16 (2); // stereo
  64. u32 ((std::uint32_t) sampleRate);
  65. u32 ((std::uint32_t) sampleRate * 4);
  66. u16 (4);
  67. u16 (16);
  68. out.write ("data", 4);
  69. u32 (dataBytes);
  70. for (std::uint32_t i = 0; i < frames; ++i)
  71. for (float s : { left[i], right[i] })
  72. {
  73. const auto clipped = s > 1.0f ? 1.0f : (s < -1.0f ? -1.0f : s);
  74. u16 ((std::uint16_t) (std::int16_t) (clipped * 32767.0f));
  75. }
  76. }
  77. } // namespace
  78. int main (int argc, char** argv)
  79. {
  80. if (argc < 3)
  81. {
  82. std::fprintf (stderr, "usage: renderwav project.flp output.wav [pattern] [loops]\n");
  83. return 2;
  84. }
  85. std::ifstream in (argv[1], std::ios::binary);
  86. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  87. lynx::Song song;
  88. // On Linux/WSL FL lives under /mnt/c; the .flp paths use backslashes.
  89. const std::string flRoot = std::getenv ("FL_ROOT") ? std::getenv ("FL_ROOT")
  90. #if defined(_WIN32)
  91. : "C:/Program Files/Image-Line/FL Studio 2026";
  92. #else
  93. : "/mnt/c/Program Files/Image-Line/FL Studio 2026";
  94. #endif
  95. auto toLocal = [] (std::string p) {
  96. std::replace (p.begin(), p.end(), '\\', '/');
  97. // absolute Windows paths ("C:/...") → the WSL mount ("/mnt/c/...")
  98. #if ! defined(_WIN32) // (the Windows build of this tool reads them as they are)
  99. if (p.size() > 2 && p[1] == ':' && p[2] == '/' && std::isalpha ((unsigned char) p[0]))
  100. p = "/mnt/" + std::string (1, (char) std::tolower ((unsigned char) p[0])) + p.substr (2);
  101. #endif
  102. return p;
  103. };
  104. lynx::FlpImportOptions options;
  105. options.roots = { flRoot, flRoot + "/Data", "" };
  106. options.fileExists = [&] (const std::string& p) { return std::filesystem::exists (toLocal (p)); };
  107. options.readFile = [&] (const std::string& p) { // (the rack compressors' presets of Harmless/Harmor)
  108. std::ifstream f (toLocal (p), std::ios::binary);
  109. return std::vector<std::uint8_t> ((std::istreambuf_iterator<char> (f)), std::istreambuf_iterator<char>());
  110. };
  111. try
  112. {
  113. song = lynx::importFlp (flp::parseProject (bytes), options);
  114. }
  115. catch (const flp::Error& e)
  116. {
  117. std::fprintf (stderr, "error: %s\n", e.what());
  118. return 1;
  119. }
  120. // "song" instead of the index: the whole song (playlist), like the app's export
  121. const bool wholeSong = argc > 3 && std::string (argv[3]) == "song";
  122. std::int64_t songTicks = 0;
  123. if (wholeSong)
  124. song = lynx::makeExportSong (song, true, 0, songTicks);
  125. int chosen = argc > 3 && ! wholeSong ? std::atoi (argv[3]) : -1;
  126. if (chosen < 0 || chosen >= (int) song.patterns.size())
  127. {
  128. chosen = 0;
  129. for (int i = 0; i < (int) song.patterns.size(); ++i)
  130. if (song.patterns[(std::size_t) i].notes.size() > song.patterns[(std::size_t) chosen].notes.size())
  131. chosen = i;
  132. }
  133. song.currentPattern = chosen;
  134. const int loops = argc > 4 ? std::max (1, std::atoi (argv[4])) : 2;
  135. const auto& pattern = song.patterns[(std::size_t) chosen];
  136. const auto lengthTicks = wholeSong ? songTicks : pattern.effectiveLength (song.beatsPerBar) * loops;
  137. constexpr int sampleRate = 44100;
  138. const int blockSize = std::getenv ("LYNX_BLOCK") ? std::clamp (std::atoi (std::getenv ("LYNX_BLOCK")), 16, 8192) : 256;
  139. const auto tps = lynx::ticksPerSample (song.bpm, sampleRate);
  140. auto totalSamples = (std::size_t) (lengthTicks / tps) + sampleRate; // +1 s of tail
  141. if (const char* s = std::getenv ("LYNX_SECONDS"); s != nullptr && std::atof (s) > 0) // benchmark: render only the start
  142. totalSamples = std::min (totalSamples, (std::size_t) (std::atof (s) * sampleRate));
  143. std::printf ("%.1f BPM, %zu channels, pattern \"%s\" (%zu notes), %d loops, %.1f s\n", song.bpm,
  144. song.channels.size(), pattern.name.c_str(), pattern.notes.size(), loops,
  145. (double) totalSamples / sampleRate);
  146. for (std::size_t i = 0; i < song.channels.size(); ++i)
  147. {
  148. 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" };
  149. const auto k = (std::size_t) song.channels[i].instrument;
  150. std::printf (" %2zu %-28s -> %s\n", i, song.channels[i].name.c_str(), k < std::size (kinds) ? kinds[k] : "?");
  151. }
  152. // like the app's export: instruments with FL render-quality settings use them (LYNX_LIVE=1: the live ones)
  153. lynx::setOfflineRendering (std::getenv ("LYNX_LIVE") == nullptr);
  154. std::map<std::string, std::shared_ptr<const lynx::SampleData>> cache;
  155. auto state = lynx::RackState::build (song, nullptr, sampleRate, [&] (const std::string& p) {
  156. auto& entry = cache[p];
  157. if (entry == nullptr)
  158. entry = lynx::tools::readWav (toLocal (p));
  159. if (entry == nullptr)
  160. std::printf (" (could not read %s)\n", p.c_str());
  161. return entry;
  162. });
  163. {
  164. std::size_t edges = 0, delayed = 0, tracksWithFx = 0;
  165. for (const auto& ins : state->mixerInputs)
  166. for (const auto& in : ins)
  167. {
  168. ++edges;
  169. const auto& d = state->sendDelays[(std::size_t) in.source];
  170. delayed += (std::size_t) in.delay < d.size() && d[(std::size_t) in.delay] != nullptr;
  171. }
  172. for (const auto& t : song.mixer)
  173. tracksWithFx += ! t.effects.empty();
  174. std::printf ("mixer: %zu edges (%zu with PDC delay), %zu tracks with effects\n", edges, delayed, tracksWithFx);
  175. }
  176. lynx::RackRenderer renderer;
  177. // LYNX_THREADS=n: n worker threads for the channels and mixer layers, as the app's audio engine uses
  178. std::unique_ptr<lynx::WorkerPool> pool;
  179. if (const char* t = std::getenv ("LYNX_THREADS"); t != nullptr && std::atoi (t) > 0)
  180. {
  181. pool = std::make_unique<lynx::WorkerPool> (std::atoi (t), [] { realtimePriority(); });
  182. renderer.setWorkerPool (pool.get());
  183. }
  184. renderer.prepare (sampleRate, std::max (2048, blockSize));
  185. const bool profile = std::getenv ("LYNX_PROFILE") != nullptr;
  186. const bool realtime = std::getenv ("LYNX_REALTIME") != nullptr;
  187. #if defined(_WIN32)
  188. timeBeginPeriod (1);
  189. realtimePriority();
  190. #endif
  191. renderer.setProfiling (profile);
  192. std::vector<float> left (totalSamples), right (totalSamples);
  193. // the units whose latency is only known after their first block (the app then re-plans PDC once)
  194. const auto latenciesBefore = state->currentLatencies();
  195. const auto started = std::chrono::steady_clock::now();
  196. double tick = 0.0;
  197. const double budgetMs = 1000.0 * blockSize / sampleRate;
  198. std::vector<double> wallMs, cpuMs;
  199. auto threadCpuMs = [] {
  200. #if defined(_WIN32)
  201. FILETIME created, exited, kernel, user;
  202. GetThreadTimes (GetCurrentThread(), &created, &exited, &kernel, &user);
  203. return (((std::uint64_t) user.dwHighDateTime << 32 | user.dwLowDateTime) + ((std::uint64_t) kernel.dwHighDateTime << 32 | kernel.dwLowDateTime)) * 1e-4;
  204. #else
  205. timespec ts {};
  206. clock_gettime (CLOCK_THREAD_CPUTIME_ID, &ts);
  207. return ts.tv_sec * 1000.0 + ts.tv_nsec * 1e-6;
  208. #endif
  209. };
  210. for (std::size_t pos = 0; pos < totalSamples; pos += blockSize)
  211. {
  212. const auto n = (int) std::min<std::size_t> (blockSize, totalSamples - pos);
  213. const bool playing = tick < (double) lengthTicks;
  214. const auto t0 = std::chrono::steady_clock::now();
  215. const auto c0 = threadCpuMs();
  216. renderer.process (state.get(), playing, tick, n, left.data() + pos, right.data() + pos);
  217. wallMs.push_back (std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - t0).count());
  218. cpuMs.push_back (threadCpuMs() - c0);
  219. tick += n * tps;
  220. if (realtime) // the next block starts one block later, like a sound card's callback
  221. std::this_thread::sleep_until (started + std::chrono::microseconds ((long long) ((pos + (std::size_t) n) * 1.0e6 / sampleRate)));
  222. }
  223. {
  224. const auto after = state->currentLatencies();
  225. std::size_t index = song.channels.size();
  226. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  227. for (std::size_t k = 0; k < state->effects[t].size(); ++k, ++index)
  228. if (index < after.size() && after[index] != latenciesBefore[index])
  229. std::printf ("latency changed after the first block: insert %zu slot %zu %s: %d -> %d\n", t, k + 1,
  230. lynx::effectInfo (song.mixer[t].effects[k].kind).name, latenciesBefore[index], after[index]);
  231. }
  232. std::printf ("render: %.0f ms\n", std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - started).count());
  233. {
  234. auto report = [&] (const char* what, std::vector<double> v) {
  235. if (v.empty())
  236. return;
  237. double sum = 0.0;
  238. std::size_t over = 0, nearly = 0;
  239. for (auto x : v)
  240. sum += x, over += x >= budgetMs, nearly += x >= 0.8 * budgetMs && x < budgetMs;
  241. std::sort (v.begin(), v.end());
  242. auto pct = [&] (double p) { return v[std::min (v.size() - 1, (std::size_t) (p * (double) v.size()))]; };
  243. std::printf ("blocks %s: %zu x %d samples (budget %.2f ms): mean %.0f%%, p50 %.0f%%, p99 %.0f%%, max %.0f%%; "
  244. "over budget %zu (%.2f%%), 80-100%% %zu\n",
  245. what, v.size(), blockSize, budgetMs, 100.0 * sum / (double) v.size() / budgetMs, 100.0 * pct (0.5) / budgetMs,
  246. 100.0 * pct (0.99) / budgetMs, 100.0 * v.back() / budgetMs, over, 100.0 * (double) over / (double) v.size(), nearly);
  247. };
  248. report ("wall", wallMs);
  249. {
  250. // where the slowest blocks were (seconds into the render)
  251. std::vector<std::size_t> order (cpuMs.size());
  252. for (std::size_t i = 0; i < order.size(); ++i)
  253. order[i] = i;
  254. const auto& by = pool == nullptr ? cpuMs : wallMs;
  255. std::sort (order.begin(), order.end(), [&] (std::size_t a, std::size_t b) { return by[a] > by[b]; });
  256. std::printf ("slowest blocks:");
  257. for (std::size_t i = 0; i < order.size() && i < 8; ++i)
  258. std::printf (" %.2fs=%.0f%%", (double) (order[i] * (std::size_t) blockSize) / sampleRate, 100.0 * by[order[i]] / budgetMs);
  259. std::printf ("\n");
  260. }
  261. if (pool == nullptr)
  262. report ("thread-cpu", cpuMs);
  263. #if ! defined(LYNX_OLDPOOL)
  264. if (pool != nullptr)
  265. std::printf ("workers: %d threads ran %llu indices, %llu wake-ups\n", pool->workers(),
  266. (unsigned long long) pool->indicesRunByWorkers(), (unsigned long long) pool->wakeUps());
  267. #endif
  268. }
  269. if (profile)
  270. {
  271. const auto& u = renderer.unitTimes();
  272. const auto total = (double) u.processNs.load();
  273. struct Row
  274. {
  275. double ns;
  276. std::string name;
  277. double maxNs = 0.0;
  278. };
  279. std::vector<Row> rows;
  280. for (std::size_t c = 0; c < song.channels.size() && c < (std::size_t) lynx::RackRenderer::maxChannels; ++c)
  281. if (const auto ns = (double) u.channelNs[c].load(); ns > 0.0)
  282. rows.push_back ({ ns, "channel " + std::to_string (c) + " \"" + song.channels[c].name + "\"", (double) u.channelMaxNs[c].load() });
  283. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  284. for (std::size_t k = 0; k < song.mixer[t].effects.size() && k < (std::size_t) lynx::maxEffectSlots; ++k)
  285. if (const auto ns = (double) u.effectNs[t * lynx::maxEffectSlots + k].load(); ns > 0.0)
  286. rows.push_back ({ ns, "insert " + std::to_string (t) + " slot " + std::to_string (k + 1) + " "
  287. + lynx::effectInfo (song.mixer[t].effects[k].kind).name
  288. + (song.mixer[t].effects[k].plugin.name.empty() ? "" : " (" + song.mixer[t].effects[k].plugin.name + ")"),
  289. (double) u.effectMaxNs[t * lynx::maxEffectSlots + k].load() });
  290. std::sort (rows.begin(), rows.end(), [] (const Row& a, const Row& b) { return a.ns > b.ns; });
  291. const auto audioMs = 1000.0 * (double) u.processedSamples.load() / sampleRate;
  292. std::printf ("profile: process %.0f ms for %.0f ms of audio (units below are CPU time, summed over threads)\n", total * 1e-6, audioMs);
  293. for (std::size_t i = 0; i < rows.size() && i < 25; ++i)
  294. 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),
  295. rows[i].maxNs * 1e-6, rows[i].name.c_str());
  296. // the spikes: units whose single call took longest
  297. std::sort (rows.begin(), rows.end(), [] (const Row& a, const Row& b) { return a.maxNs > b.maxNs; });
  298. std::printf ("longest single calls:\n");
  299. for (std::size_t i = 0; i < rows.size() && i < 10; ++i)
  300. std::printf (" %7.2f ms %s\n", rows[i].maxNs * 1e-6, rows[i].name.c_str());
  301. }
  302. // LYNX_RAW=path: also write the un-normalized float samples (L block then R block), for bit-exact comparisons
  303. if (const char* raw = std::getenv ("LYNX_RAW"); raw != nullptr)
  304. {
  305. std::ofstream r (raw, std::ios::binary);
  306. r.write ((const char*) left.data(), (std::streamsize) (left.size() * sizeof (float)));
  307. r.write ((const char*) right.data(), (std::streamsize) (right.size() * sizeof (float)));
  308. }
  309. // normalize the peak to -1 dBFS
  310. float peak = 0.0f;
  311. for (std::size_t i = 0; i < totalSamples; ++i)
  312. peak = std::max ({ peak, std::abs (left[i]), std::abs (right[i]) });
  313. std::printf ("peak before normalizing: %.4f\n", peak);
  314. if (peak > 0.0f)
  315. {
  316. const auto gain = 0.891f / peak;
  317. for (std::size_t i = 0; i < totalSamples; ++i)
  318. {
  319. left[i] *= gain;
  320. right[i] *= gain;
  321. }
  322. }
  323. writeWav (argv[2], left, right, sampleRate);
  324. std::printf ("written to %s\n", argv[2]);
  325. return 0;
  326. }