renderwav.cpp 6.5 KB

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