renderwav.cpp 7.6 KB

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