renderwav.cpp 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. // renderwav: importa um .flp e renderiza uma pattern com os instrumentos internos.
  2. // Uso: renderwav projeto.flp saida.wav [indice-da-pattern] [loops]
  3. // Sem índice, escolhe a pattern com mais notas.
  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 "WavReader.h"
  13. #include "core/FlpImport.h"
  14. #include "core/RackRenderer.h"
  15. namespace
  16. {
  17. void writeWav (const char* path, const std::vector<float>& left, const std::vector<float>& right, int sampleRate)
  18. {
  19. std::ofstream out (path, std::ios::binary);
  20. auto u32 = [&] (std::uint32_t v) { out.write ((const char*) &v, 4); };
  21. auto u16 = [&] (std::uint16_t v) { out.write ((const char*) &v, 2); };
  22. const auto frames = (std::uint32_t) left.size();
  23. const auto dataBytes = frames * 4;
  24. out.write ("RIFF", 4);
  25. u32 (36 + dataBytes);
  26. out.write ("WAVEfmt ", 8);
  27. u32 (16);
  28. u16 (1); // PCM
  29. u16 (2); // estéreo
  30. u32 ((std::uint32_t) sampleRate);
  31. u32 ((std::uint32_t) sampleRate * 4);
  32. u16 (4);
  33. u16 (16);
  34. out.write ("data", 4);
  35. u32 (dataBytes);
  36. for (std::uint32_t i = 0; i < frames; ++i)
  37. for (float s : { left[i], right[i] })
  38. {
  39. const auto clipped = s > 1.0f ? 1.0f : (s < -1.0f ? -1.0f : s);
  40. u16 ((std::uint16_t) (std::int16_t) (clipped * 32767.0f));
  41. }
  42. }
  43. } // namespace
  44. int main (int argc, char** argv)
  45. {
  46. if (argc < 3)
  47. {
  48. std::fprintf (stderr, "uso: renderwav projeto.flp saida.wav [pattern] [loops]\n");
  49. return 2;
  50. }
  51. std::ifstream in (argv[1], std::ios::binary);
  52. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  53. daw::Song song;
  54. // No Linux/WSL o FL fica em /mnt/c; os caminhos do .flp usam barras invertidas.
  55. const std::string flRoot = std::getenv ("FL_ROOT") ? std::getenv ("FL_ROOT")
  56. : "/mnt/c/Program Files/Image-Line/FL Studio 2026";
  57. auto toLocal = [] (std::string p) {
  58. std::replace (p.begin(), p.end(), '\\', '/');
  59. return p;
  60. };
  61. daw::FlpImportOptions options;
  62. options.roots = { flRoot, flRoot + "/Data", "" };
  63. options.fileExists = [&] (const std::string& p) { return std::filesystem::exists (toLocal (p)); };
  64. try
  65. {
  66. song = daw::importFlp (flp::parseProject (bytes), options);
  67. }
  68. catch (const flp::Error& e)
  69. {
  70. std::fprintf (stderr, "erro: %s\n", e.what());
  71. return 1;
  72. }
  73. int chosen = argc > 3 ? std::atoi (argv[3]) : -1;
  74. if (chosen < 0 || chosen >= (int) song.patterns.size())
  75. {
  76. chosen = 0;
  77. for (int i = 0; i < (int) song.patterns.size(); ++i)
  78. if (song.patterns[(std::size_t) i].notes.size() > song.patterns[(std::size_t) chosen].notes.size())
  79. chosen = i;
  80. }
  81. song.currentPattern = chosen;
  82. const int loops = argc > 4 ? std::max (1, std::atoi (argv[4])) : 2;
  83. const auto& pattern = song.patterns[(std::size_t) chosen];
  84. const auto lengthTicks = pattern.effectiveLength (song.beatsPerBar) * loops;
  85. constexpr int sampleRate = 44100;
  86. constexpr int blockSize = 256;
  87. const auto tps = daw::ticksPerSample (song.bpm, sampleRate);
  88. const auto totalSamples = (std::size_t) (lengthTicks / tps) + sampleRate; // +1 s de cauda
  89. std::printf ("%.1f BPM, %zu canais, pattern \"%s\" (%zu notas), %d loops, %.1f s\n", song.bpm,
  90. song.channels.size(), pattern.name.c_str(), pattern.notes.size(), loops,
  91. (double) totalSamples / sampleRate);
  92. for (std::size_t i = 0; i < song.channels.size(); ++i)
  93. {
  94. static const char* kinds[] = { "kick", "snare", "hat", "clap", "synth", "sampler" };
  95. std::printf (" %2zu %-28s -> %s\n", i, song.channels[i].name.c_str(), kinds[(int) song.channels[i].instrument]);
  96. }
  97. std::map<std::string, std::shared_ptr<const daw::SampleData>> cache;
  98. auto state = daw::RackState::build (song, nullptr, sampleRate, [&] (const std::string& p) {
  99. auto& entry = cache[p];
  100. if (entry == nullptr)
  101. entry = daw::tools::readWav (toLocal (p));
  102. if (entry == nullptr)
  103. std::printf (" (não consegui ler %s)\n", p.c_str());
  104. return entry;
  105. });
  106. daw::RackRenderer renderer;
  107. renderer.prepare (sampleRate);
  108. std::vector<float> left (totalSamples), right (totalSamples);
  109. double tick = 0.0;
  110. for (std::size_t pos = 0; pos < totalSamples; pos += blockSize)
  111. {
  112. const auto n = (int) std::min<std::size_t> (blockSize, totalSamples - pos);
  113. const bool playing = tick < (double) lengthTicks;
  114. renderer.process (state.get(), playing, tick, n, left.data() + pos, right.data() + pos);
  115. tick += n * tps;
  116. }
  117. // normaliza o pico para -1 dBFS
  118. float peak = 0.0f;
  119. for (std::size_t i = 0; i < totalSamples; ++i)
  120. peak = std::max ({ peak, std::abs (left[i]), std::abs (right[i]) });
  121. if (peak > 0.0f)
  122. {
  123. const auto gain = 0.891f / peak;
  124. for (std::size_t i = 0; i < totalSamples; ++i)
  125. {
  126. left[i] *= gain;
  127. right[i] *= gain;
  128. }
  129. }
  130. writeWav (argv[2], left, right, sampleRate);
  131. std::printf ("gravado em %s\n", argv[2]);
  132. return 0;
  133. }