renderwav.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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_STRETCH=0 keep-pitch samples unstretched (default since rollup 0.1.31 step 8: stretched to the tempo, as the app)
  12. // LYNX_PROFILE=1 per-channel / per-insert-effect CPU time, heaviest first
  13. // LYNX_ALLOCS=1 counts the heap allocations made while a block is processed (the audio thread and the
  14. // workers; round 167e) and prints where the first distinct ones came from (Linux: addresses for
  15. // addr2line -e renderwav)
  16. // The block timing report (budget = block duration) is always printed.
  17. #include <cctype>
  18. #include <cmath>
  19. #include <cstdio>
  20. #include <cstdlib>
  21. #include <cstring>
  22. #include <fstream>
  23. #include <iterator>
  24. #include <vector>
  25. #include <algorithm>
  26. #include <filesystem>
  27. #include <map>
  28. #include <sstream>
  29. #include <string>
  30. #include <chrono>
  31. #include <thread>
  32. #include <time.h>
  33. #include <atomic>
  34. #include <new>
  35. #if defined(__linux__)
  36. #include <execinfo.h>
  37. #endif
  38. #if defined(_WIN32)
  39. #define WIN32_LEAN_AND_MEAN
  40. #define NOMINMAX
  41. #include <windows.h>
  42. #include <mmsystem.h>
  43. #endif
  44. #include "WavReader.h"
  45. #include "core/FlpImport.h"
  46. #include "core/PluginSubstitutes.h"
  47. #include "core/RackRenderer.h"
  48. #include "core/WorkerPool.h"
  49. #include "core/TimeStretch.h"
  50. #include "core/TempoMap.h"
  51. #include "core/ExportOptions.h"
  52. // LYNX_ALLOCS: every operator new while `counting` is set (inside RackRenderer::process) is counted
  53. namespace allocs
  54. {
  55. std::atomic<bool> counting { false };
  56. std::atomic<long> count { 0 };
  57. constexpr int maxSites = 96, depth = 12;
  58. struct Site
  59. {
  60. void* frames[depth] {};
  61. int n = 0;
  62. long hits = 0;
  63. };
  64. Site sites[maxSites];
  65. std::atomic<int> siteCount { 0 };
  66. std::atomic_flag recording = ATOMIC_FLAG_INIT;
  67. void note() noexcept
  68. {
  69. count.fetch_add (1, std::memory_order_relaxed);
  70. #if defined(__linux__)
  71. if (recording.test_and_set()) // (one at a time; backtrace() itself may allocate once: not counted, flag held)
  72. return;
  73. counting.store (false);
  74. void* f[depth + 2];
  75. const auto n = backtrace (f, depth + 2);
  76. const auto used = std::max (0, n - 2);
  77. bool found = false;
  78. for (int i = 0; i < siteCount.load() && ! found; ++i)
  79. if (sites[i].n == used && std::equal (f + 2, f + 2 + used, sites[i].frames))
  80. found = ++sites[i].hits > 0;
  81. if (! found && siteCount.load() < maxSites)
  82. {
  83. auto& s = sites[siteCount.load()];
  84. s.n = used;
  85. std::copy (f + 2, f + 2 + used, s.frames);
  86. s.hits = 1;
  87. siteCount.fetch_add (1);
  88. }
  89. counting.store (true);
  90. recording.clear();
  91. #endif
  92. }
  93. } // namespace allocs
  94. void* operator new (std::size_t n)
  95. {
  96. if (allocs::counting.load (std::memory_order_relaxed))
  97. allocs::note();
  98. if (auto* p = std::malloc (n > 0 ? n : 1))
  99. return p;
  100. throw std::bad_alloc();
  101. }
  102. void* operator new[] (std::size_t n) { return operator new (n); }
  103. void* operator new (std::size_t n, const std::nothrow_t&) noexcept
  104. {
  105. if (allocs::counting.load (std::memory_order_relaxed))
  106. allocs::note();
  107. return std::malloc (n > 0 ? n : 1);
  108. }
  109. void* operator new[] (std::size_t n, const std::nothrow_t& t) noexcept { return operator new (n, t); }
  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. namespace
  115. {
  116. // like the app's audio threads: MMCSS "Pro Audio" on Windows (with a 1 ms timer for the real-time pacing)
  117. void realtimePriority()
  118. {
  119. #if defined(_WIN32)
  120. using AvSet = void* (__stdcall*) (const wchar_t*, unsigned long*);
  121. static const auto avSet = [] () -> AvSet {
  122. if (auto* avrt = LoadLibraryW (L"avrt.dll"))
  123. return reinterpret_cast<AvSet> (reinterpret_cast<void*> (GetProcAddress (avrt, "AvSetMmThreadCharacteristicsW")));
  124. return nullptr;
  125. }();
  126. unsigned long task = 0;
  127. if (avSet == nullptr || avSet (L"Pro Audio", &task) == nullptr)
  128. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  129. #endif
  130. }
  131. void writeWav (const char* path, const std::vector<float>& left, const std::vector<float>& right, int sampleRate)
  132. {
  133. std::ofstream out (path, std::ios::binary);
  134. auto u32 = [&] (std::uint32_t v) { out.write ((const char*) &v, 4); };
  135. auto u16 = [&] (std::uint16_t v) { out.write ((const char*) &v, 2); };
  136. const auto frames = (std::uint32_t) left.size();
  137. const auto dataBytes = frames * 4;
  138. out.write ("RIFF", 4);
  139. u32 (36 + dataBytes);
  140. out.write ("WAVEfmt ", 8);
  141. u32 (16);
  142. u16 (1); // PCM
  143. u16 (2); // stereo
  144. u32 ((std::uint32_t) sampleRate);
  145. u32 ((std::uint32_t) sampleRate * 4);
  146. u16 (4);
  147. u16 (16);
  148. out.write ("data", 4);
  149. u32 (dataBytes);
  150. for (std::uint32_t i = 0; i < frames; ++i)
  151. for (float s : { left[i], right[i] })
  152. {
  153. const auto clipped = s > 1.0f ? 1.0f : (s < -1.0f ? -1.0f : s);
  154. u16 ((std::uint16_t) (std::int16_t) (clipped * 32767.0f));
  155. }
  156. }
  157. } // namespace
  158. int main (int argc, char** argv)
  159. {
  160. if (argc < 3)
  161. {
  162. std::fprintf (stderr, "usage: renderwav project.flp output.wav [pattern] [loops]\n");
  163. return 2;
  164. }
  165. std::ifstream in (argv[1], std::ios::binary);
  166. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  167. lynx::Song song;
  168. // On Linux/WSL FL lives under /mnt/c; the .flp paths use backslashes.
  169. const std::string flRoot = std::getenv ("FL_ROOT") ? std::getenv ("FL_ROOT")
  170. #if defined(_WIN32)
  171. : "C:/Program Files/Image-Line/FL Studio 2026";
  172. #else
  173. : "/mnt/c/Program Files/Image-Line/FL Studio 2026";
  174. #endif
  175. auto toLocal = [] (std::string p) {
  176. std::replace (p.begin(), p.end(), '\\', '/');
  177. // absolute Windows paths ("C:/...") → the WSL mount ("/mnt/c/...")
  178. #if ! defined(_WIN32) // (the Windows build of this tool reads them as they are)
  179. if (p.size() > 2 && p[1] == ':' && p[2] == '/' && std::isalpha ((unsigned char) p[0]))
  180. p = "/mnt/" + std::string (1, (char) std::tolower ((unsigned char) p[0])) + p.substr (2);
  181. #endif
  182. return p;
  183. };
  184. lynx::FlpImportOptions options;
  185. options.roots = { flRoot, flRoot + "/Data", "" };
  186. options.fileExists = [&] (const std::string& p) { return std::filesystem::exists (toLocal (p)); };
  187. options.readFile = [&] (const std::string& p) { // (the rack compressors' presets of Harmless/Harmor)
  188. std::ifstream f (toLocal (p), std::ios::binary);
  189. return std::vector<std::uint8_t> ((std::istreambuf_iterator<char> (f)), std::istreambuf_iterator<char>());
  190. };
  191. // LYNX_REPORT=1: the import report (what is converted, approximated, unsupported, not reproduced, dropped) after the
  192. // import (round 190pr: the demo song sweep's "what remains")
  193. lynx::FlpImportReport report;
  194. const bool printReport = std::getenv ("LYNX_REPORT") != nullptr;
  195. if (printReport)
  196. options.report = &report;
  197. const auto importStart = std::chrono::steady_clock::now();
  198. try
  199. {
  200. const auto parsed = flp::parseProject (bytes);
  201. song = lynx::importFlp (parsed, options);
  202. if (printReport)
  203. {
  204. // the automation targets: clips (0xE3), song-start values (0xD8), pattern events (0xDF: per target, value range)
  205. const auto who = [&] (flp::ControlId id) {
  206. std::string s;
  207. if (id.isChannel())
  208. {
  209. for (const auto& c : parsed.channels)
  210. if (c.index == id.channel())
  211. s = "ch " + std::to_string (c.index) + " " + c.name + " [" + c.pluginName + "]";
  212. }
  213. else if (id.isMixer())
  214. {
  215. s = "insert " + std::to_string (id.track()) + " slot " + std::to_string (id.slot());
  216. for (const auto& ins : parsed.mixer)
  217. if (ins.index == id.track())
  218. for (const auto& sl : ins.slots)
  219. if (sl.index == id.slot())
  220. s += " [" + sl.plugin + "]";
  221. }
  222. char b[64];
  223. std::snprintf (b, sizeof b, " param 0x%04x (%d)", id.param(), id.param() >= 0x8000 ? id.param() - 0x8000 : -1);
  224. return s + b;
  225. };
  226. for (const auto& l : parsed.automationLinks)
  227. std::printf ("auto clip ch %d -> %s\n", l.channel, who (l.target).c_str());
  228. for (const auto& c : parsed.initControls)
  229. std::printf ("init value %s = %d\n", who (c.id).c_str(), c.value);
  230. std::map<std::uint32_t, std::pair<std::int32_t, std::int32_t>> ranges;
  231. std::map<std::uint32_t, int> counts;
  232. for (const auto& p : parsed.patterns)
  233. for (const auto& e : p.controlEvents)
  234. {
  235. auto [it, fresh] = ranges.try_emplace (e.id.raw, e.value, e.value);
  236. it->second.first = std::min (it->second.first, e.value);
  237. it->second.second = std::max (it->second.second, e.value);
  238. ++counts[e.id.raw];
  239. }
  240. for (const auto& [id, r] : ranges)
  241. std::printf ("pattern events %s: %d events, %d..%d\n", who (flp::ControlId { id }).c_str(), counts[id], r.first, r.second);
  242. const auto list = [] (const char* what, const std::map<std::string, int>& m) {
  243. for (const auto& [k, n] : m)
  244. std::printf ("report %s: %s x%d\n", what, k.c_str(), n);
  245. };
  246. list ("converted", report.converted);
  247. list ("approximated", report.approximated);
  248. list ("unsupported", report.unsupported);
  249. list ("not reproduced", report.notReproduced);
  250. list ("dropped effect", report.droppedEffects);
  251. list ("partial effect", report.partialEffects);
  252. if (report.missingSamples > 0)
  253. std::printf ("report missing samples: %d\n", report.missingSamples);
  254. // the tempo map: the song's tempo every 4 bars and its playing time there
  255. {
  256. double seconds = 0.0;
  257. const auto bar = (double) song.barTicks();
  258. std::int64_t end = 0;
  259. for (const auto& c : song.playlist)
  260. end = std::max (end, c.end());
  261. for (double t = 0.0; t < (double) end; t += 1.0)
  262. {
  263. const auto bpm = song.tempoAt (t);
  264. if (std::fmod (t, 4.0 * bar) == 0.0)
  265. std::printf ("tempo at bar %d: %.3f BPM, %.3f s\n", (int) (t / bar) + 1, bpm, seconds);
  266. seconds += 60.0 / (bpm * (double) lynx::ppq);
  267. }
  268. std::printf ("tempo map end %.3f s\n", seconds);
  269. }
  270. }
  271. std::printf ("import: %.0f ms\n", std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - importStart).count());
  272. std::size_t held = 0; // FL's held step notes (round 190oz)
  273. for (const auto& pat : song.patterns)
  274. for (const auto& n : pat.notes)
  275. held += n.heldStep() ? 1 : 0;
  276. if (held > 0)
  277. std::printf ("held step notes: %zu\n", held);
  278. }
  279. catch (const flp::Error& e)
  280. {
  281. std::fprintf (stderr, "error: %s\n", e.what());
  282. return 1;
  283. }
  284. // LYNX_SOLO="i j …": only those LYNX channels play (every other channel muted), e.g. one channel's silence check
  285. if (const char* e = std::getenv ("LYNX_SOLO"))
  286. {
  287. std::vector<bool> keep (song.channels.size(), false);
  288. std::istringstream list (e);
  289. for (int i = 0; list >> i;)
  290. if (i >= 0 && i < (int) keep.size())
  291. keep[(std::size_t) i] = true;
  292. for (std::size_t i = 0; i < song.channels.size(); ++i)
  293. if (! keep[i])
  294. song.channels[i].muted = true;
  295. }
  296. // LYNX_SUBSTITUTES=1: third-party effects become their LYNX substitutes, as in the app when none is installed
  297. // (otherwise they stay unresolved, i.e. silent pass-through); LYNX_DISABLE="t.k t.k": those insert slots off
  298. if (const char* e = std::getenv ("LYNX_SUBSTITUTES"); e != nullptr && std::atoi (e) != 0)
  299. {
  300. const auto context = lynx::substituteContextOf (song);
  301. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  302. for (std::size_t k = 0; k < song.mixer[t].effects.size(); ++k)
  303. if (auto& fx = song.mixer[t].effects[k]; fx.kind == lynx::EffectKind::plugin && fx.plugin.foreign.format != lynx::ForeignPlugin::Format::none
  304. && lynx::substituteEffectSlot (fx, lynx::pluginIdentity (fx.plugin.foreign), context))
  305. 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);
  306. }
  307. // LYNX_SUBSTITUTES_BYPASS=1: the project's "substitutes bypassed" switch on (A/B)
  308. if (const char* e = std::getenv ("LYNX_SUBSTITUTES_BYPASS"); e != nullptr && std::atoi (e) != 0)
  309. song.substitutesBypassed = true;
  310. // LYNX_PARAM="t.k.p=v …": insert t, slot k, parameter p set to the normalised value v (experiments)
  311. if (const char* e = std::getenv ("LYNX_PARAM"))
  312. {
  313. std::istringstream list (e);
  314. std::string item;
  315. while (list >> item)
  316. {
  317. int t = -1, k = -1, prm = -1;
  318. float v = 0.0f;
  319. if (std::sscanf (item.c_str(), "%d.%d.%d=%f", &t, &k, &prm, &v) == 4 && t >= 0 && t < (int) song.mixer.size() && k >= 0
  320. && k < (int) song.mixer[(std::size_t) t].effects.size() && prm >= 0 && prm < lynx::maxEffectParams)
  321. song.mixer[(std::size_t) t].effects[(std::size_t) k].params[(std::size_t) prm] = v;
  322. }
  323. }
  324. // LYNX_MUTE="name|name…": channels with these names muted (round 190ov: what one channel adds to a render)
  325. if (const char* e = std::getenv ("LYNX_MUTE"))
  326. {
  327. std::string list = std::string ("|") + e + "|";
  328. for (auto& c : song.channels)
  329. if (list.find ("|" + c.name + "|") != std::string::npos)
  330. c.muted = true;
  331. }
  332. if (const char* e = std::getenv ("LYNX_DISABLE"))
  333. {
  334. std::istringstream list (e);
  335. std::string item;
  336. while (list >> item)
  337. if (const auto dot = item.find ('.'); dot != std::string::npos)
  338. {
  339. 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());
  340. if (t < song.mixer.size() && k < song.mixer[t].effects.size())
  341. song.mixer[t].effects[k].enabled = false;
  342. }
  343. }
  344. // "song" instead of the index: the whole song (playlist), like the app's export
  345. const bool wholeSong = argc > 3 && std::string (argv[3]) == "song";
  346. std::int64_t songTicks = 0;
  347. if (wholeSong) // with the app's empty tail (1 s), so the song does not wrap to its start inside the rendered tail
  348. {
  349. const auto tail = (std::int64_t) std::ceil (lynx::ticksPerSample (song.bpm, 44100) * 44100.0);
  350. // round 190pr: following the Start / skip / pause markers, as the app's export (and FL's) when Song::exportMarkers is on
  351. if (const auto spans = lynx::exportopts::exportSpans (song); spans.size() > 1 || (spans.size() == 1 && spans.front().first > 0))
  352. {
  353. lynx::exportopts::Options o;
  354. o.range = lynx::exportopts::Range::song;
  355. o.disableMaxPolyphony = false; // (as this tool renders every other song)
  356. std::int64_t loopTicks = 0;
  357. song = lynx::exportopts::makeRenderSong (song, o, tail, songTicks, loopTicks);
  358. std::printf ("export follows the markers: %zu span(s), from tick %lld\n", spans.size(), (long long) spans.front().first);
  359. }
  360. else
  361. song = lynx::makeExportSong (song, true, tail, songTicks);
  362. }
  363. int chosen = argc > 3 && ! wholeSong ? std::atoi (argv[3]) : -1;
  364. if (chosen < 0 || chosen >= (int) song.patterns.size())
  365. {
  366. chosen = 0;
  367. for (int i = 0; i < (int) song.patterns.size(); ++i)
  368. if (song.patterns[(std::size_t) i].notes.size() > song.patterns[(std::size_t) chosen].notes.size())
  369. chosen = i;
  370. }
  371. song.currentPattern = chosen;
  372. const int loops = argc > 4 ? std::max (1, std::atoi (argv[4])) : 2;
  373. const auto& pattern = song.patterns[(std::size_t) chosen];
  374. const auto lengthTicks = wholeSong ? songTicks : pattern.effectiveLength (song.meter()) * loops;
  375. constexpr int sampleRate = 44100;
  376. const int blockSize = std::getenv ("LYNX_BLOCK") ? std::clamp (std::atoi (std::getenv ("LYNX_BLOCK")), 16, 8192) : 256;
  377. const auto tps = lynx::ticksPerSample (song.bpm, sampleRate);
  378. // round 190pr: with tempo automation / tempo events the transport moves at the block's tempo, as the app's does
  379. // (RackRenderer::currentBpm; before, this tool played every song at its start tempo: Secret Agent Rendezvous' first
  380. // 24 bars at 110 instead of FL's 120 BPM); LYNX_FIXEDTEMPO=1: the old clock
  381. const bool followTempo = lynx::tempomap::active (song) && std::getenv ("LYNX_FIXEDTEMPO") == nullptr;
  382. auto totalSamples = followTempo ? (std::size_t) std::ceil (song.secondsForTicks (lengthTicks) * sampleRate) + sampleRate
  383. : (std::size_t) (lengthTicks / tps) + sampleRate; // +1 s of tail
  384. if (const char* s = std::getenv ("LYNX_SECONDS"); s != nullptr && std::atof (s) > 0) // benchmark: render only the start
  385. totalSamples = std::min (totalSamples, (std::size_t) (std::atof (s) * sampleRate));
  386. std::printf ("%.1f BPM, %zu channels, pattern \"%s\" (%zu notes), %d loops, %.1f s\n", song.bpm,
  387. song.channels.size(), pattern.name.c_str(), pattern.notes.size(), loops,
  388. (double) totalSamples / sampleRate);
  389. for (std::size_t i = 0; i < song.channels.size(); ++i)
  390. {
  391. 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" };
  392. const auto k = (std::size_t) song.channels[i].instrument;
  393. std::printf (" %2zu %-28s -> %s\n", i, song.channels[i].name.c_str(), k < std::size (kinds) ? kinds[k] : "?");
  394. }
  395. // like the app's export: instruments with FL render-quality settings use them (LYNX_LIVE=1: the live ones)
  396. lynx::setOfflineRendering (std::getenv ("LYNX_LIVE") == nullptr);
  397. std::map<std::string, std::shared_ptr<const lynx::SampleData>> cache;
  398. const auto buildStart = std::chrono::steady_clock::now();
  399. lynx::RackState::Factories factories;
  400. factories.samples = [&] (const std::string& p) {
  401. auto& entry = cache[p];
  402. if (entry == nullptr)
  403. entry = lynx::tools::readWav (toLocal (p));
  404. if (entry == nullptr)
  405. std::printf (" (could not read %s)\n", p.c_str());
  406. return entry;
  407. };
  408. // Keep-pitch samples are time-stretched to the tempo as in the app (its sample library does the same stretch, cached;
  409. // round 190gn's LYNX_STRETCH=1, the default since rollup 0.1.31 step 8 so measurements match the app: round 190pt found
  410. // the Vocodex demo's "silence" was renderwav's unstretched clips). LYNX_STRETCH=0 plays them unstretched (the old default).
  411. std::size_t stretchedCount = 0;
  412. if (const char* e = std::getenv ("LYNX_STRETCH"); e == nullptr || e[0] != '0')
  413. factories.stretchedSamples = [&] (const std::string& p, double ratio, lynx::StretchMethod method, double semitones,
  414. const lynx::StretchMap& map, const lynx::StretchOptions& options) -> std::shared_ptr<const lynx::SampleData> {
  415. const auto original = factories.samples (p);
  416. if (original == nullptr)
  417. return nullptr;
  418. ++stretchedCount;
  419. return map.empty() ? lynx::timeStretch (*original, ratio, method, semitones, options)
  420. : lynx::timeStretchMapped (*original, map, method, semitones, options);
  421. };
  422. auto state = lynx::RackState::build (song, nullptr, sampleRate, factories);
  423. if (factories.stretchedSamples)
  424. std::printf ("keep-pitch samples stretched to the tempo: %zu (LYNX_STRETCH=0: unstretched)\n", stretchedCount);
  425. else
  426. std::printf ("keep-pitch samples NOT stretched (LYNX_STRETCH=0)\n");
  427. std::printf ("rack build: %.0f ms\n", std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - buildStart).count());
  428. {
  429. std::size_t edges = 0, delayed = 0, tracksWithFx = 0;
  430. for (const auto& ins : state->mixerInputs)
  431. for (const auto& in : ins)
  432. {
  433. ++edges;
  434. const auto& d = state->sendDelays[(std::size_t) in.source];
  435. delayed += (std::size_t) in.delay < d.size() && d[(std::size_t) in.delay] != nullptr;
  436. }
  437. for (const auto& t : song.mixer)
  438. tracksWithFx += ! t.effects.empty();
  439. std::printf ("mixer: %zu edges (%zu with PDC delay), %zu tracks with effects\n", edges, delayed, tracksWithFx);
  440. }
  441. // LYNX_LISTFX=1: every mixer track with effects or sends: fader, effects (kind, on, mix, unresolved plugins), sends
  442. // (round 190pr: where a demo song's level goes)
  443. if (std::getenv ("LYNX_LISTFX") != nullptr)
  444. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  445. {
  446. const auto& tr = song.mixer[t];
  447. if (tr.effects.empty() && tr.sends.empty() && t != 0)
  448. continue;
  449. std::printf ("track %3zu %-24s vol %.3f pan %+.2f%s%s:", t, tr.name.c_str(), tr.volume, tr.pan, tr.muted ? " MUTED" : "",
  450. tr.toMaster ? "" : " (not to master)");
  451. for (const auto& fx : tr.effects)
  452. std::printf (" [@%d %s%s%s mix %.2f]", fx.row, lynx::effectInfo (fx.kind).name, fx.enabled ? "" : " off",
  453. fx.kind == lynx::EffectKind::plugin ? (" " + fx.plugin.name + (fx.plugin.foreign.format != lynx::ForeignPlugin::Format::none ? " UNRESOLVED" : "")).c_str() : "",
  454. fx.mix);
  455. for (const auto& s : tr.sends)
  456. std::printf (" ->%d(%.2f)", s.target, s.level);
  457. std::printf ("\n");
  458. }
  459. lynx::RackRenderer renderer;
  460. // LYNX_THREADS=n: n worker threads for the channels and mixer layers, as the app's audio engine uses
  461. std::unique_ptr<lynx::WorkerPool> pool;
  462. if (const char* t = std::getenv ("LYNX_THREADS"); t != nullptr && std::atoi (t) > 0)
  463. {
  464. pool = std::make_unique<lynx::WorkerPool> (std::atoi (t), [] { realtimePriority(); });
  465. renderer.setWorkerPool (pool.get());
  466. }
  467. renderer.prepare (sampleRate, std::max (2048, blockSize));
  468. const bool profile = std::getenv ("LYNX_PROFILE") != nullptr;
  469. const bool countAllocs = std::getenv ("LYNX_ALLOCS") != nullptr;
  470. long blocksWithAllocs = 0;
  471. const bool realtime = std::getenv ("LYNX_REALTIME") != nullptr;
  472. #if defined(_WIN32)
  473. timeBeginPeriod (1);
  474. realtimePriority();
  475. #endif
  476. renderer.setProfiling (profile);
  477. std::vector<float> left (totalSamples), right (totalSamples);
  478. // the units whose latency is only known after their first block (the app then re-plans PDC once)
  479. const auto latenciesBefore = state->currentLatencies();
  480. const auto started = std::chrono::steady_clock::now();
  481. double tick = 0.0;
  482. const double budgetMs = 1000.0 * blockSize / sampleRate;
  483. std::vector<double> wallMs, cpuMs;
  484. auto threadCpuMs = [] {
  485. #if defined(_WIN32)
  486. FILETIME created, exited, kernel, user;
  487. GetThreadTimes (GetCurrentThread(), &created, &exited, &kernel, &user);
  488. return (((std::uint64_t) user.dwHighDateTime << 32 | user.dwLowDateTime) + ((std::uint64_t) kernel.dwHighDateTime << 32 | kernel.dwLowDateTime)) * 1e-4;
  489. #else
  490. timespec ts {};
  491. clock_gettime (CLOCK_THREAD_CPUTIME_ID, &ts);
  492. return ts.tv_sec * 1000.0 + ts.tv_nsec * 1e-6;
  493. #endif
  494. };
  495. if (const char* w = std::getenv ("LYNX_WARMUP"); w != nullptr && std::atoi (w) > 0)
  496. {
  497. std::vector<float> wl ((std::size_t) blockSize), wr ((std::size_t) blockSize);
  498. for (int done = 0, total = std::atoi (w); done < total; done += blockSize)
  499. {
  500. const int n = std::min (blockSize, total - done);
  501. std::fill (wl.begin(), wl.end(), 0.0f);
  502. std::fill (wr.begin(), wr.end(), 0.0f);
  503. renderer.process (state.get(), false, 0.0, n, wl.data(), wr.data());
  504. }
  505. }
  506. for (std::size_t pos = 0; pos < totalSamples; pos += blockSize)
  507. {
  508. const auto n = (int) std::min<std::size_t> (blockSize, totalSamples - pos);
  509. const bool playing = tick < (double) lengthTicks;
  510. const auto t0 = std::chrono::steady_clock::now();
  511. const auto c0 = threadCpuMs();
  512. const auto allocsBefore = allocs::count.load();
  513. allocs::counting.store (countAllocs);
  514. renderer.process (state.get(), playing, tick, n, left.data() + pos, right.data() + pos);
  515. allocs::counting.store (false);
  516. blocksWithAllocs += allocs::count.load() != allocsBefore;
  517. wallMs.push_back (std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - t0).count());
  518. cpuMs.push_back (threadCpuMs() - c0);
  519. tick += n * (followTempo ? lynx::ticksPerSample (renderer.currentBpm(), sampleRate) : tps);
  520. if (realtime) // the next block starts one block later, like a sound card's callback
  521. std::this_thread::sleep_until (started + std::chrono::microseconds ((long long) ((pos + (std::size_t) n) * 1.0e6 / sampleRate)));
  522. }
  523. {
  524. const auto after = state->currentLatencies();
  525. std::size_t index = song.channels.size();
  526. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  527. for (std::size_t k = 0; k < state->effects[t].size(); ++k, ++index)
  528. if (index < after.size() && after[index] != latenciesBefore[index])
  529. std::printf ("latency changed after the first block: insert %zu slot %zu %s: %d -> %d\n", t, k + 1,
  530. lynx::effectInfo (song.mixer[t].effects[k].kind).name, latenciesBefore[index], after[index]);
  531. }
  532. std::printf ("render: %.0f ms\n", std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - started).count());
  533. {
  534. auto report = [&] (const char* what, std::vector<double> v) {
  535. if (v.empty())
  536. return;
  537. double sum = 0.0;
  538. std::size_t over = 0, nearly = 0;
  539. for (auto x : v)
  540. sum += x, over += x >= budgetMs, nearly += x >= 0.8 * budgetMs && x < budgetMs;
  541. std::sort (v.begin(), v.end());
  542. auto pct = [&] (double p) { return v[std::min (v.size() - 1, (std::size_t) (p * (double) v.size()))]; };
  543. std::printf ("blocks %s: %zu x %d samples (budget %.2f ms): mean %.0f%%, p50 %.0f%%, p99 %.0f%%, max %.0f%%; "
  544. "over budget %zu (%.2f%%), 80-100%% %zu\n",
  545. what, v.size(), blockSize, budgetMs, 100.0 * sum / (double) v.size() / budgetMs, 100.0 * pct (0.5) / budgetMs,
  546. 100.0 * pct (0.99) / budgetMs, 100.0 * v.back() / budgetMs, over, 100.0 * (double) over / (double) v.size(), nearly);
  547. };
  548. report ("wall", wallMs);
  549. {
  550. // where the slowest blocks were (seconds into the render)
  551. std::vector<std::size_t> order (cpuMs.size());
  552. for (std::size_t i = 0; i < order.size(); ++i)
  553. order[i] = i;
  554. const auto& by = pool == nullptr ? cpuMs : wallMs;
  555. std::sort (order.begin(), order.end(), [&] (std::size_t a, std::size_t b) { return by[a] > by[b]; });
  556. std::printf ("slowest blocks:");
  557. for (std::size_t i = 0; i < order.size() && i < 8; ++i)
  558. std::printf (" %.2fs=%.0f%%", (double) (order[i] * (std::size_t) blockSize) / sampleRate, 100.0 * by[order[i]] / budgetMs);
  559. std::printf ("\n");
  560. }
  561. if (pool == nullptr)
  562. report ("thread-cpu", cpuMs);
  563. #if ! defined(LYNX_OLDPOOL)
  564. if (pool != nullptr)
  565. std::printf ("workers: %d threads ran %llu indices, %llu wake-ups\n", pool->workers(),
  566. (unsigned long long) pool->indicesRunByWorkers(), (unsigned long long) pool->wakeUps());
  567. #endif
  568. }
  569. if (countAllocs)
  570. {
  571. std::printf ("allocations while processing: %ld in %ld of %zu blocks\n", allocs::count.load(), blocksWithAllocs, wallMs.size());
  572. for (int i = 0; i < allocs::siteCount.load(); ++i)
  573. {
  574. std::printf (" site %d (%ld):", i, allocs::sites[i].hits);
  575. #if defined(__linux__)
  576. if (char** names = backtrace_symbols (allocs::sites[i].frames, allocs::sites[i].n))
  577. {
  578. for (int k = 0; k < allocs::sites[i].n; ++k)
  579. std::printf (" %s", std::strrchr (names[k], '(') != nullptr ? std::strrchr (names[k], '(') : names[k]);
  580. std::free (names);
  581. }
  582. #endif
  583. std::printf ("\n");
  584. }
  585. }
  586. if (profile)
  587. {
  588. const auto& u = renderer.unitTimes();
  589. const auto total = (double) u.processNs.load();
  590. struct Row
  591. {
  592. double ns;
  593. std::string name;
  594. double maxNs = 0.0;
  595. };
  596. std::vector<Row> rows;
  597. for (std::size_t c = 0; c < song.channels.size() && c < (std::size_t) lynx::RackRenderer::maxChannels; ++c)
  598. if (const auto ns = (double) u.channelNs[c].load(); ns > 0.0)
  599. rows.push_back ({ ns, "channel " + std::to_string (c) + " \"" + song.channels[c].name + "\"", (double) u.channelMaxNs[c].load() });
  600. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  601. for (std::size_t k = 0; k < song.mixer[t].effects.size() && k < (std::size_t) lynx::maxEffectSlots; ++k)
  602. if (const auto ns = (double) u.effectNs[t * lynx::maxEffectSlots + k].load(); ns > 0.0)
  603. rows.push_back ({ ns, "insert " + std::to_string (t) + " slot " + std::to_string (k + 1) + " "
  604. + lynx::effectInfo (song.mixer[t].effects[k].kind).name
  605. + (song.mixer[t].effects[k].plugin.name.empty() ? "" : " (" + song.mixer[t].effects[k].plugin.name + ")"),
  606. (double) u.effectMaxNs[t * lynx::maxEffectSlots + k].load() });
  607. std::sort (rows.begin(), rows.end(), [] (const Row& a, const Row& b) { return a.ns > b.ns; });
  608. const auto audioMs = 1000.0 * (double) u.processedSamples.load() / sampleRate;
  609. std::printf ("profile: process %.0f ms for %.0f ms of audio (units below are CPU time, summed over threads)\n", total * 1e-6, audioMs);
  610. for (std::size_t i = 0; i < rows.size() && i < 25; ++i)
  611. 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),
  612. rows[i].maxNs * 1e-6, rows[i].name.c_str());
  613. // the spikes: units whose single call took longest
  614. std::sort (rows.begin(), rows.end(), [] (const Row& a, const Row& b) { return a.maxNs > b.maxNs; });
  615. std::printf ("longest single calls:\n");
  616. for (std::size_t i = 0; i < rows.size() && i < 10; ++i)
  617. std::printf (" %7.2f ms %s\n", rows[i].maxNs * 1e-6, rows[i].name.c_str());
  618. }
  619. // round 190gn (A1): the keep-pitch samplers' pitch shifters after the render (made at build + taken from the stock)
  620. {
  621. int held = 0, channels = 0;
  622. for (const auto& i : state->instruments)
  623. if (i != nullptr && i->pitchShiftersHeld() > 0)
  624. held += i->pitchShiftersHeld(), ++channels;
  625. const auto* stock = state->shifterStock.get();
  626. std::printf ("pitch shifters: %d held by %d channels (%d from the stock, %d left in it, %d voices missed one)\n", held, channels,
  627. stock != nullptr ? stock->handedOut() : 0, stock != nullptr ? stock->ready (0) + stock->ready (1) : 0,
  628. stock != nullptr ? stock->missed() : 0);
  629. if (std::getenv ("LYNX_SHIFTER_LIST") != nullptr)
  630. for (std::size_t c = 0; c < state->instruments.size(); ++c)
  631. if (const auto& i = state->instruments[c]; i != nullptr && i->pitchShiftersHeld() > 0)
  632. std::printf (" shifters %2zu %-28s %d\n", c, song.channels[c].name.c_str(), i->pitchShiftersHeld());
  633. }
  634. // LYNX_RAW=path: also write the un-normalized float samples (L block then R block), for bit-exact comparisons
  635. if (const char* raw = std::getenv ("LYNX_RAW"); raw != nullptr)
  636. {
  637. std::ofstream r (raw, std::ios::binary);
  638. r.write ((const char*) left.data(), (std::streamsize) (left.size() * sizeof (float)));
  639. r.write ((const char*) right.data(), (std::streamsize) (right.size() * sizeof (float)));
  640. }
  641. // normalize the peak to -1 dBFS
  642. float peak = 0.0f;
  643. for (std::size_t i = 0; i < totalSamples; ++i)
  644. peak = std::max ({ peak, std::abs (left[i]), std::abs (right[i]) });
  645. std::printf ("peak before normalizing: %.4f\n", peak);
  646. if (peak > 0.0f)
  647. {
  648. const auto gain = 0.891f / peak;
  649. for (std::size_t i = 0; i < totalSamples; ++i)
  650. {
  651. left[i] *= gain;
  652. right[i] *= gain;
  653. }
  654. }
  655. writeWav (argv[2], left, right, sampleRate);
  656. std::printf ("written to %s\n", argv[2]);
  657. return 0;
  658. }