renderwav.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. #include <cctype>
  5. #include <cstdio>
  6. #include <cstdlib>
  7. #include <fstream>
  8. #include <iterator>
  9. #include <vector>
  10. #include <algorithm>
  11. #include <filesystem>
  12. #include <map>
  13. #include <string>
  14. #include <chrono>
  15. #include "WavReader.h"
  16. #include "core/FlpImport.h"
  17. #include "core/RackRenderer.h"
  18. #include "core/WorkerPool.h"
  19. namespace
  20. {
  21. void writeWav (const char* path, const std::vector<float>& left, const std::vector<float>& right, int sampleRate)
  22. {
  23. std::ofstream out (path, std::ios::binary);
  24. auto u32 = [&] (std::uint32_t v) { out.write ((const char*) &v, 4); };
  25. auto u16 = [&] (std::uint16_t v) { out.write ((const char*) &v, 2); };
  26. const auto frames = (std::uint32_t) left.size();
  27. const auto dataBytes = frames * 4;
  28. out.write ("RIFF", 4);
  29. u32 (36 + dataBytes);
  30. out.write ("WAVEfmt ", 8);
  31. u32 (16);
  32. u16 (1); // PCM
  33. u16 (2); // stereo
  34. u32 ((std::uint32_t) sampleRate);
  35. u32 ((std::uint32_t) sampleRate * 4);
  36. u16 (4);
  37. u16 (16);
  38. out.write ("data", 4);
  39. u32 (dataBytes);
  40. for (std::uint32_t i = 0; i < frames; ++i)
  41. for (float s : { left[i], right[i] })
  42. {
  43. const auto clipped = s > 1.0f ? 1.0f : (s < -1.0f ? -1.0f : s);
  44. u16 ((std::uint16_t) (std::int16_t) (clipped * 32767.0f));
  45. }
  46. }
  47. } // namespace
  48. int main (int argc, char** argv)
  49. {
  50. if (argc < 3)
  51. {
  52. std::fprintf (stderr, "usage: renderwav project.flp output.wav [pattern] [loops]\n");
  53. return 2;
  54. }
  55. std::ifstream in (argv[1], std::ios::binary);
  56. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  57. lynx::Song song;
  58. // On Linux/WSL FL lives under /mnt/c; the .flp paths use backslashes.
  59. const std::string flRoot = std::getenv ("FL_ROOT") ? std::getenv ("FL_ROOT")
  60. : "/mnt/c/Program Files/Image-Line/FL Studio 2026";
  61. auto toLocal = [] (std::string p) {
  62. std::replace (p.begin(), p.end(), '\\', '/');
  63. // absolute Windows paths ("C:/...") → the WSL mount ("/mnt/c/...")
  64. if (p.size() > 2 && p[1] == ':' && p[2] == '/' && std::isalpha ((unsigned char) p[0]))
  65. p = "/mnt/" + std::string (1, (char) std::tolower ((unsigned char) p[0])) + p.substr (2);
  66. return p;
  67. };
  68. lynx::FlpImportOptions options;
  69. options.roots = { flRoot, flRoot + "/Data", "" };
  70. options.fileExists = [&] (const std::string& p) { return std::filesystem::exists (toLocal (p)); };
  71. options.readFile = [&] (const std::string& p) { // (the rack compressors' presets of Harmless/Harmor)
  72. std::ifstream f (toLocal (p), std::ios::binary);
  73. return std::vector<std::uint8_t> ((std::istreambuf_iterator<char> (f)), std::istreambuf_iterator<char>());
  74. };
  75. try
  76. {
  77. song = lynx::importFlp (flp::parseProject (bytes), options);
  78. }
  79. catch (const flp::Error& e)
  80. {
  81. std::fprintf (stderr, "error: %s\n", e.what());
  82. return 1;
  83. }
  84. // "song" instead of the index: the whole song (playlist), like the app's export
  85. const bool wholeSong = argc > 3 && std::string (argv[3]) == "song";
  86. std::int64_t songTicks = 0;
  87. if (wholeSong)
  88. song = lynx::makeExportSong (song, true, 0, songTicks);
  89. int chosen = argc > 3 && ! wholeSong ? std::atoi (argv[3]) : -1;
  90. if (chosen < 0 || chosen >= (int) song.patterns.size())
  91. {
  92. chosen = 0;
  93. for (int i = 0; i < (int) song.patterns.size(); ++i)
  94. if (song.patterns[(std::size_t) i].notes.size() > song.patterns[(std::size_t) chosen].notes.size())
  95. chosen = i;
  96. }
  97. song.currentPattern = chosen;
  98. const int loops = argc > 4 ? std::max (1, std::atoi (argv[4])) : 2;
  99. const auto& pattern = song.patterns[(std::size_t) chosen];
  100. const auto lengthTicks = wholeSong ? songTicks : pattern.effectiveLength (song.beatsPerBar) * loops;
  101. constexpr int sampleRate = 44100;
  102. constexpr int blockSize = 256;
  103. const auto tps = lynx::ticksPerSample (song.bpm, sampleRate);
  104. auto totalSamples = (std::size_t) (lengthTicks / tps) + sampleRate; // +1 s of tail
  105. if (const char* s = std::getenv ("LYNX_SECONDS"); s != nullptr && std::atof (s) > 0) // benchmark: render only the start
  106. totalSamples = std::min (totalSamples, (std::size_t) (std::atof (s) * sampleRate));
  107. std::printf ("%.1f BPM, %zu channels, pattern \"%s\" (%zu notes), %d loops, %.1f s\n", song.bpm,
  108. song.channels.size(), pattern.name.c_str(), pattern.notes.size(), loops,
  109. (double) totalSamples / sampleRate);
  110. for (std::size_t i = 0; i < song.channels.size(); ++i)
  111. {
  112. 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" };
  113. const auto k = (std::size_t) song.channels[i].instrument;
  114. std::printf (" %2zu %-28s -> %s\n", i, song.channels[i].name.c_str(), k < std::size (kinds) ? kinds[k] : "?");
  115. }
  116. // like the app's export: instruments with FL render-quality settings use them (LYNX_LIVE=1: the live ones)
  117. lynx::setOfflineRendering (std::getenv ("LYNX_LIVE") == nullptr);
  118. std::map<std::string, std::shared_ptr<const lynx::SampleData>> cache;
  119. auto state = lynx::RackState::build (song, nullptr, sampleRate, [&] (const std::string& p) {
  120. auto& entry = cache[p];
  121. if (entry == nullptr)
  122. entry = lynx::tools::readWav (toLocal (p));
  123. if (entry == nullptr)
  124. std::printf (" (could not read %s)\n", p.c_str());
  125. return entry;
  126. });
  127. {
  128. std::size_t edges = 0, delayed = 0, tracksWithFx = 0;
  129. for (const auto& ins : state->mixerInputs)
  130. for (const auto& in : ins)
  131. {
  132. ++edges;
  133. const auto& d = state->sendDelays[(std::size_t) in.source];
  134. delayed += (std::size_t) in.delay < d.size() && d[(std::size_t) in.delay] != nullptr;
  135. }
  136. for (const auto& t : song.mixer)
  137. tracksWithFx += ! t.effects.empty();
  138. std::printf ("mixer: %zu edges (%zu with PDC delay), %zu tracks with effects\n", edges, delayed, tracksWithFx);
  139. }
  140. lynx::RackRenderer renderer;
  141. // LYNX_THREADS=n: n worker threads for the channels and mixer layers, as the app's audio engine uses
  142. std::unique_ptr<lynx::WorkerPool> pool;
  143. if (const char* t = std::getenv ("LYNX_THREADS"); t != nullptr && std::atoi (t) > 0)
  144. {
  145. pool = std::make_unique<lynx::WorkerPool> (std::atoi (t));
  146. renderer.setWorkerPool (pool.get());
  147. }
  148. renderer.prepare (sampleRate);
  149. std::vector<float> left (totalSamples), right (totalSamples);
  150. const auto started = std::chrono::steady_clock::now();
  151. double tick = 0.0;
  152. for (std::size_t pos = 0; pos < totalSamples; pos += blockSize)
  153. {
  154. const auto n = (int) std::min<std::size_t> (blockSize, totalSamples - pos);
  155. const bool playing = tick < (double) lengthTicks;
  156. renderer.process (state.get(), playing, tick, n, left.data() + pos, right.data() + pos);
  157. tick += n * tps;
  158. }
  159. std::printf ("render: %.0f ms\n", std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - started).count());
  160. // LYNX_RAW=path: also write the un-normalized float samples (L block then R block), for bit-exact comparisons
  161. if (const char* raw = std::getenv ("LYNX_RAW"); raw != nullptr)
  162. {
  163. std::ofstream r (raw, std::ios::binary);
  164. r.write ((const char*) left.data(), (std::streamsize) (left.size() * sizeof (float)));
  165. r.write ((const char*) right.data(), (std::streamsize) (right.size() * sizeof (float)));
  166. }
  167. // normalize the peak to -1 dBFS
  168. float peak = 0.0f;
  169. for (std::size_t i = 0; i < totalSamples; ++i)
  170. peak = std::max ({ peak, std::abs (left[i]), std::abs (right[i]) });
  171. std::printf ("peak before normalizing: %.4f\n", peak);
  172. if (peak > 0.0f)
  173. {
  174. const auto gain = 0.891f / peak;
  175. for (std::size_t i = 0; i < totalSamples; ++i)
  176. {
  177. left[i] *= gain;
  178. right[i] *= gain;
  179. }
  180. }
  181. writeWav (argv[2], left, right, sampleRate);
  182. std::printf ("written to %s\n", argv[2]);
  183. return 0;
  184. }