renderwav.cpp 18 KB

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