ExportOptions.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  1. #include "core/ExportOptions.h"
  2. #include <algorithm>
  3. #include <cmath>
  4. #include <cstdio>
  5. #include <cstring>
  6. #include <fstream>
  7. #include <optional>
  8. #include <set>
  9. #include <sstream>
  10. #include "core/PatternBlocks.h"
  11. #include "core/Preferences.h"
  12. namespace lynx::exportopts
  13. {
  14. const std::vector<int>& mp3Bitrates()
  15. {
  16. static const std::vector<int> list { 96, 128, 160, 192, 224, 256, 320 };
  17. return list;
  18. }
  19. const std::vector<int>& oggBitrates()
  20. {
  21. static const std::vector<int> list { 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 500 };
  22. return list;
  23. }
  24. const std::vector<double>& sampleRates()
  25. {
  26. static const std::vector<double> list { 44100.0, 48000.0, 88200.0, 96000.0, 192000.0 };
  27. return list;
  28. }
  29. const char* extension (Format format)
  30. {
  31. switch (format)
  32. {
  33. case Format::mp3: return ".mp3";
  34. case Format::ogg: return ".ogg";
  35. case Format::flac: return ".flac";
  36. case Format::wav: break;
  37. }
  38. return ".wav";
  39. }
  40. int fileBits (const Options& o) noexcept
  41. {
  42. switch (o.format)
  43. {
  44. case Format::wav: return o.wavBits;
  45. case Format::flac: return o.flacBits;
  46. case Format::mp3:
  47. case Format::ogg: break;
  48. }
  49. return 16;
  50. }
  51. bool usesDither (const Options& o) noexcept
  52. {
  53. if (o.dither == DitherMode::none)
  54. return false;
  55. if (o.format == Format::wav)
  56. return o.wavBits == 16 || o.wavBits == 24;
  57. return o.format == Format::flac;
  58. }
  59. double mp3SampleRate (double rate) noexcept
  60. {
  61. if (rate == 32000.0 || rate == 44100.0 || rate == 48000.0)
  62. return rate;
  63. return std::fmod (rate, 11025.0) == 0.0 ? 44100.0 : 48000.0;
  64. }
  65. namespace
  66. {
  67. template <typename T>
  68. T nearest (const std::vector<T>& list, T value)
  69. {
  70. auto best = list.front();
  71. for (auto v : list)
  72. if (std::abs ((double) v - (double) value) < std::abs ((double) best - (double) value))
  73. best = v;
  74. return best;
  75. }
  76. int toInt (const std::map<std::string, std::string>& kv, const char* key, int fallback)
  77. {
  78. const auto it = kv.find (key);
  79. if (it == kv.end() || it->second.empty())
  80. return fallback;
  81. try
  82. {
  83. return std::stoi (it->second);
  84. }
  85. catch (...)
  86. {
  87. return fallback;
  88. }
  89. }
  90. double toDouble (const std::map<std::string, std::string>& kv, const char* key, double fallback)
  91. {
  92. const auto it = kv.find (key);
  93. if (it == kv.end() || it->second.empty())
  94. return fallback;
  95. try
  96. {
  97. return std::stod (it->second);
  98. }
  99. catch (...)
  100. {
  101. return fallback;
  102. }
  103. }
  104. } // namespace
  105. Options clamped (Options o)
  106. {
  107. const Options d;
  108. if ((int) o.format < 0 || (int) o.format > 3) o.format = d.format;
  109. if (o.wavBits != 16 && o.wavBits != 24 && o.wavBits != 32) o.wavBits = d.wavBits;
  110. if (o.flacBits != 16 && o.flacBits != 24) o.flacBits = d.flacBits;
  111. o.flacLevel = std::clamp (o.flacLevel, 0, 8);
  112. o.mp3Kbps = nearest (mp3Bitrates(), o.mp3Kbps);
  113. o.oggKbps = nearest (oggBitrates(), o.oggKbps);
  114. o.sampleRate = nearest (sampleRates(), o.sampleRate);
  115. if ((int) o.dither < 0 || (int) o.dither > 2) o.dither = d.dither;
  116. if ((int) o.tail < 0 || (int) o.tail > 2) o.tail = d.tail;
  117. if (! (o.maxTailSeconds >= 0.0)) o.maxTailSeconds = d.maxTailSeconds;
  118. o.maxTailSeconds = std::min (o.maxTailSeconds, 60.0);
  119. if ((int) o.range < 0 || (int) o.range > 2) o.range = d.range;
  120. o.loops = std::clamp (o.loops, 1, 16);
  121. if ((int) o.stems < 0 || (int) o.stems > 2) o.stems = d.stems;
  122. if ((int) o.channels < 0 || (int) o.channels > 3) o.channels = d.channels;
  123. o.moreFormats &= 0xFu & ~(1u << (int) o.format);
  124. if (! (o.masterLufs >= -30.0 && o.masterLufs <= -5.0)) o.masterLufs = d.masterLufs;
  125. return o;
  126. }
  127. double lengthInBars (double seconds, double bpm, int beatsPerBar) noexcept
  128. {
  129. return seconds <= 0.0 || bpm <= 0.0 ? 0.0 : seconds * bpm / 60.0 / (double) std::max (1, beatsPerBar);
  130. }
  131. std::int64_t estimatedBytes (const Options& o, double seconds) noexcept
  132. {
  133. if (seconds <= 0.0)
  134. return 0;
  135. const auto channels = o.channels == Channels::stereo ? 2.0 : 1.0;
  136. std::int64_t total = 0; // every format the export writes (FL's disk space counts all ticked boxes)
  137. for (const auto f : { Format::wav, Format::mp3, Format::ogg, Format::flac })
  138. if (f == o.format || (o.moreFormats & (1u << (int) f)) != 0)
  139. switch (f)
  140. {
  141. case Format::wav: total += (std::int64_t) (seconds * o.sampleRate * channels * (o.wavBits / 8.0)) + 44; break;
  142. case Format::flac: total += (std::int64_t) (seconds * o.sampleRate * channels * (o.flacBits / 8.0) * 0.6); break; // ~60 % of PCM
  143. case Format::mp3: total += (std::int64_t) (seconds * o.mp3Kbps * 1000.0 / 8.0); break;
  144. case Format::ogg: total += (std::int64_t) (seconds * o.oggKbps * 1000.0 / 8.0); break;
  145. }
  146. return total;
  147. }
  148. std::vector<Format> formatsOf (const Options& o)
  149. {
  150. std::vector<Format> out { o.format };
  151. for (const auto f : { Format::wav, Format::mp3, Format::ogg, Format::flac })
  152. if (f != o.format && (o.moreFormats & (1u << (int) f)) != 0)
  153. out.push_back (f);
  154. return out;
  155. }
  156. std::uint32_t flLastExportedMask (const Options& o) noexcept
  157. {
  158. std::uint32_t mask = flFormatBit (o.format);
  159. for (const auto f : { Format::wav, Format::mp3, Format::ogg, Format::flac })
  160. if ((o.moreFormats & (1u << (int) f)) != 0)
  161. mask |= flFormatBit (f);
  162. return mask;
  163. }
  164. Options withFlLastExported (Options o, std::uint32_t mask)
  165. {
  166. if (mask < 8 || mask > 0x3FF) // FL: anything else falls back to WAV
  167. mask = 8;
  168. std::vector<Format> chosen;
  169. for (const auto f : { Format::wav, Format::mp3, Format::ogg, Format::flac })
  170. if ((mask & flFormatBit (f)) != 0)
  171. chosen.push_back (f);
  172. if (chosen.empty()) // only formats LYNX writes elsewhere (MIDI, M4A): WAV
  173. chosen.push_back (Format::wav);
  174. o.format = chosen.front();
  175. o.moreFormats = 0;
  176. for (std::size_t i = 1; i < chosen.size(); ++i)
  177. o.moreFormats |= 1u << (int) chosen[i];
  178. return o;
  179. }
  180. Options withSingleFormat (Options o, Format f)
  181. {
  182. o.format = f;
  183. o.moreFormats = 0;
  184. return o;
  185. }
  186. std::vector<Note> midiExportNotes (const Song& original)
  187. {
  188. std::optional<Song> expanded; // Pattern Blocks (round 170f) export as their clips
  189. if (patternblocks::active (original))
  190. patternblocks::expandSong (expanded.emplace (original));
  191. const Song& song = expanded ? *expanded : original;
  192. std::vector<Note> out;
  193. const auto trackMuted = [&song] (int track) {
  194. return track >= 0 && track < (int) song.playlistTracks.size() && song.playlistTracks[(std::size_t) track].muted;
  195. };
  196. if (song.mode == PlayMode::song)
  197. for (const auto& c : song.playlist)
  198. {
  199. if (c.kind != ClipKind::pattern || c.muted || c.length <= 0 || trackMuted (c.track) || c.pattern < 0
  200. || c.pattern >= (int) song.patterns.size())
  201. continue;
  202. {
  203. // the pattern repeats along a clip longer than it (LYNX extra stretchedClipsLoop, issue #25)
  204. const auto& pattern = song.patterns[(std::size_t) c.pattern];
  205. const auto period = std::max<std::int64_t> (1, pattern.effectiveLength (song.beatsPerBar));
  206. const auto repeats = stretchedClipsLoop() && c.offset + c.length > period;
  207. for (auto pass = repeats ? c.offset / period : 0; pass <= (repeats ? (c.offset + c.length - 1) / period : 0); ++pass)
  208. for (auto n : pattern.notes)
  209. {
  210. if (repeats && n.start >= period)
  211. continue;
  212. const auto at = n.start + (repeats ? pass * period : 0);
  213. if (n.muted || at < c.offset || at >= c.offset + c.length)
  214. continue;
  215. n.start = c.start + (at - c.offset);
  216. n.length = std::max<std::int64_t> (1, std::min (n.length, c.end() - n.start));
  217. out.push_back (n);
  218. }
  219. }
  220. }
  221. if (out.empty() && (song.mode != PlayMode::song || std::none_of (song.playlist.begin(), song.playlist.end(),
  222. [] (const Clip& c) { return c.kind == ClipKind::pattern; })))
  223. if (song.currentPattern >= 0 && song.currentPattern < (int) song.patterns.size())
  224. for (const auto& n : song.patterns[(std::size_t) song.currentPattern].notes)
  225. if (! n.muted)
  226. out.push_back (n);
  227. std::stable_sort (out.begin(), out.end(), [] (const Note& a, const Note& b) { return a.start < b.start; });
  228. return out;
  229. }
  230. std::string toText (const Options& o)
  231. {
  232. std::ostringstream s;
  233. s << "format=" << (int) o.format << "\n"
  234. << "wavBits=" << o.wavBits << "\n"
  235. << "flacBits=" << o.flacBits << "\n"
  236. << "flacLevel=" << o.flacLevel << "\n"
  237. << "mp3Kbps=" << o.mp3Kbps << "\n"
  238. << "oggKbps=" << o.oggKbps << "\n"
  239. << "sampleRate=" << (int) o.sampleRate << "\n"
  240. << "dither=" << (int) o.dither << "\n"
  241. << "tail=" << (int) o.tail << "\n"
  242. << "maxTail=" << o.maxTailSeconds << "\n"
  243. << "range=" << (int) o.range << "\n"
  244. << "loops=" << o.loops << "\n"
  245. << "stems=" << (int) o.stems << "\n"
  246. << "stemsMaster=" << (o.stemsIncludeMaster ? 1 : 0) << "\n"
  247. << "normalize=" << (o.normalize ? 1 : 0) << "\n"
  248. << "masterEffects=" << (o.masterEffects ? 1 : 0) << "\n"
  249. << "insertEffects=" << (o.insertEffects ? 1 : 0) << "\n"
  250. << "trimPdc=" << (o.trimPdc ? 1 : 0) << "\n"
  251. << "hqAllPlugins=" << (o.hqAllPlugins ? 1 : 0) << "\n"
  252. << "pluginWarmUp=" << (o.pluginWarmUp ? 1 : 0) << "\n"
  253. << "showWhenDone=" << (o.showWhenDone ? 1 : 0) << "\n"
  254. << "disableMaxPolyphony=" << (o.disableMaxPolyphony ? 1 : 0) << "\n"
  255. << "moreFormats=" << o.moreFormats << "\n"
  256. << "channels=" << (int) o.channels << "\n"
  257. << "saveTempo=" << (o.saveTempo ? 1 : 0) << "\n"
  258. << "loopMarkers=" << (o.loopMarkers ? 1 : 0) << "\n"
  259. << "playlistMarkers=" << (o.playlistMarkers ? 1 : 0) << "\n"
  260. << "masterLufs=" << o.masterLufs << "\n";
  261. return s.str();
  262. }
  263. Options fromText (const std::string& text)
  264. {
  265. const auto kv = prefs::parseKeyValues (text);
  266. const Options d;
  267. Options o;
  268. o.format = (Format) toInt (kv, "format", (int) d.format);
  269. o.wavBits = toInt (kv, "wavBits", d.wavBits);
  270. o.flacBits = toInt (kv, "flacBits", d.flacBits);
  271. o.flacLevel = toInt (kv, "flacLevel", d.flacLevel);
  272. o.mp3Kbps = toInt (kv, "mp3Kbps", d.mp3Kbps);
  273. o.oggKbps = toInt (kv, "oggKbps", d.oggKbps);
  274. o.sampleRate = toDouble (kv, "sampleRate", d.sampleRate);
  275. o.dither = (DitherMode) toInt (kv, "dither", (int) d.dither);
  276. o.tail = (TailMode) toInt (kv, "tail", (int) d.tail);
  277. o.maxTailSeconds = toDouble (kv, "maxTail", d.maxTailSeconds);
  278. o.range = (Range) toInt (kv, "range", (int) d.range);
  279. o.loops = toInt (kv, "loops", d.loops);
  280. o.stems = (Stems) toInt (kv, "stems", (int) d.stems);
  281. o.stemsIncludeMaster = toInt (kv, "stemsMaster", d.stemsIncludeMaster ? 1 : 0) != 0;
  282. o.normalize = toInt (kv, "normalize", d.normalize ? 1 : 0) != 0;
  283. o.masterEffects = toInt (kv, "masterEffects", d.masterEffects ? 1 : 0) != 0;
  284. o.insertEffects = toInt (kv, "insertEffects", d.insertEffects ? 1 : 0) != 0;
  285. o.trimPdc = toInt (kv, "trimPdc", d.trimPdc ? 1 : 0) != 0;
  286. o.hqAllPlugins = toInt (kv, "hqAllPlugins", d.hqAllPlugins ? 1 : 0) != 0;
  287. o.pluginWarmUp = toInt (kv, "pluginWarmUp", d.pluginWarmUp ? 1 : 0) != 0;
  288. o.showWhenDone = toInt (kv, "showWhenDone", d.showWhenDone ? 1 : 0) != 0;
  289. o.disableMaxPolyphony = toInt (kv, "disableMaxPolyphony", d.disableMaxPolyphony ? 1 : 0) != 0;
  290. o.moreFormats = (std::uint32_t) std::clamp (toInt (kv, "moreFormats", 0), 0, 15);
  291. o.channels = (Channels) toInt (kv, "channels", (int) d.channels);
  292. o.saveTempo = toInt (kv, "saveTempo", d.saveTempo ? 1 : 0) != 0;
  293. o.loopMarkers = toInt (kv, "loopMarkers", d.loopMarkers ? 1 : 0) != 0;
  294. o.playlistMarkers = toInt (kv, "playlistMarkers", d.playlistMarkers ? 1 : 0) != 0;
  295. o.masterLufs = toDouble (kv, "masterLufs", d.masterLufs);
  296. return clamped (o);
  297. }
  298. bool hasSelection (const Song& song) noexcept
  299. {
  300. return song.loopEnd > song.loopStart && song.loopStart >= 0;
  301. }
  302. Song makeRenderSong (const Song& original, const Options& o, std::int64_t tailTicks, std::int64_t& musicTicks, std::int64_t& loopTicks)
  303. {
  304. // FL's legacy Pattern Blocks (round 170f) are rendered as the clips they play as
  305. std::optional<Song> expanded;
  306. if (patternblocks::active (original))
  307. patternblocks::expandSong (expanded.emplace (original));
  308. const Song& song = expanded ? *expanded : original;
  309. Song base = song;
  310. std::int64_t length = 0;
  311. if (o.range == Range::selection && hasSelection (song))
  312. {
  313. const auto from = song.loopStart, to = song.loopEnd;
  314. std::vector<Clip> cropped;
  315. for (auto clip : song.playlist)
  316. {
  317. if (clip.end() <= from || clip.start >= to || clip.length <= 0)
  318. continue;
  319. if (clip.start < from)
  320. clip = splitClip (clip, from);
  321. if (clip.end() > to)
  322. splitClip (clip, to); // keeps the head
  323. clip.start -= from;
  324. cropped.push_back (clip);
  325. }
  326. base.playlist = std::move (cropped);
  327. base.mode = PlayMode::song;
  328. std::int64_t ignored = 0;
  329. base = makeExportSong (base, true, 0, ignored);
  330. length = to - from;
  331. if (base.playlist.empty()) // nothing in the selection: a silent pass of the right length
  332. {
  333. base.patterns.emplace_back().name = "(silence)";
  334. Clip silent;
  335. silent.pattern = (int) base.patterns.size() - 1;
  336. silent.length = length;
  337. base.playlist.push_back (silent);
  338. }
  339. }
  340. else
  341. base = makeExportSong (song, o.range == Range::song || (o.range == Range::selection), 0, length);
  342. length = std::max<std::int64_t> (1, length);
  343. loopTicks = length;
  344. // the range repeated: copies of the clips shifted by one pass each
  345. const auto loops = std::clamp (o.loops, 1, 16);
  346. if (loops > 1)
  347. {
  348. const auto once = base.playlist;
  349. for (int k = 1; k < loops; ++k)
  350. for (auto clip : once)
  351. {
  352. clip.start += length * k;
  353. base.playlist.push_back (clip);
  354. }
  355. }
  356. musicTicks = length * loops;
  357. // the tail: an empty pattern after the music (plus a bar of slack, like makeExportSong)
  358. if (tailTicks > 0)
  359. {
  360. base.patterns.emplace_back().name = "(tail)";
  361. Clip tail;
  362. tail.pattern = (int) base.patterns.size() - 1;
  363. tail.start = musicTicks;
  364. tail.length = tailTicks + (std::int64_t) ppq * std::max (1, base.beatsPerBar);
  365. base.playlist.push_back (tail);
  366. }
  367. if (! o.masterEffects && ! base.mixer.empty())
  368. base.mixer[0].effects.clear();
  369. if (! o.insertEffects)
  370. for (std::size_t t = 1; t < base.mixer.size(); ++t)
  371. base.mixer[t].effects.clear();
  372. if (o.disableMaxPolyphony) // FL: every channel's Max polyphony becomes 0 (no limit) for the render
  373. for (auto& c : base.channels)
  374. c.maxPolyphony = 0;
  375. // FL's export plays the song straight through: marker loops / skips / pauses and the Start / Loop markers act only
  376. // while playing live (REA_rodada165f-markers §1.3: FL's renders of every marker action match the plain song)
  377. for (auto& a : base.arrangements)
  378. for (auto& m : a.markers)
  379. if (m.action == Marker::markerLoop || m.action == Marker::markerSkip || m.action == Marker::markerPause
  380. || m.action == Marker::songLoop || m.action == Marker::start)
  381. m.action = Marker::none;
  382. base.mode = PlayMode::song;
  383. base.loopStart = base.loopEnd = 0;
  384. return base;
  385. }
  386. std::vector<int> stemTracks (const Song& song)
  387. {
  388. std::vector<int> out;
  389. for (int t = 1; t < (int) song.mixer.size(); ++t)
  390. {
  391. auto used = std::any_of (song.channels.begin(), song.channels.end(), [t] (const ChannelDef& c) { return c.mixerTrack == t; });
  392. for (int src = 1; src < (int) song.mixer.size() && ! used; ++src)
  393. used = src != t && song.routes (src, t);
  394. if (used)
  395. out.push_back (t);
  396. }
  397. return out;
  398. }
  399. std::vector<int> stemTracks (const Song& song, const std::vector<int>& only)
  400. {
  401. if (only.empty())
  402. return stemTracks (song);
  403. std::vector<int> out;
  404. for (auto t : only)
  405. if (t > 0 && t < (int) song.mixer.size())
  406. out.push_back (t);
  407. std::sort (out.begin(), out.end());
  408. out.erase (std::unique (out.begin(), out.end()), out.end());
  409. return out;
  410. }
  411. std::vector<int> stemChannels (const Song& original, Range range)
  412. {
  413. std::optional<Song> expanded; // Pattern Blocks (round 170f) count as their clips
  414. if (patternblocks::active (original))
  415. patternblocks::expandSong (expanded.emplace (original));
  416. const Song& song = expanded ? *expanded : original;
  417. std::set<int> used;
  418. auto addPattern = [&] (int p) {
  419. if (p < 0 || p >= (int) song.patterns.size())
  420. return;
  421. for (const auto& n : song.patterns[(std::size_t) p].notes)
  422. used.insert (n.channel);
  423. };
  424. if (range == Range::pattern || song.playlist.empty())
  425. addPattern (song.currentPattern);
  426. else
  427. for (const auto& c : song.playlist)
  428. {
  429. if (c.muted || song.isTrackMuted (c.track))
  430. continue;
  431. if (c.kind == ClipKind::pattern)
  432. addPattern (c.pattern);
  433. else if (c.kind == ClipKind::audio)
  434. used.insert (c.channel);
  435. }
  436. std::vector<int> out;
  437. for (auto c : used)
  438. if (c >= 0 && c < (int) song.channels.size() && ! song.channels[(std::size_t) c].muted)
  439. out.push_back (c);
  440. return out;
  441. }
  442. Song makeChannelStemSong (const Song& song, int channel)
  443. {
  444. Song out = song;
  445. for (int c = 0; c < (int) out.channels.size(); ++c)
  446. if (c != channel)
  447. out.channels[(std::size_t) c].muted = true;
  448. return out;
  449. }
  450. std::string stemFileName (const std::string& base, int number, const std::string& name, const char* ext)
  451. {
  452. std::string clean;
  453. for (auto ch : name)
  454. clean += std::string ("<>:\"/\\|?*").find (ch) != std::string::npos || (unsigned char) ch < 32 ? '_' : ch;
  455. while (! clean.empty() && (clean.back() == ' ' || clean.back() == '.'))
  456. clean.pop_back();
  457. return base + " - " + std::to_string (number) + (clean.empty() ? "" : " " + clean) + ext;
  458. }
  459. void applyTail (std::vector<float>& left, std::vector<float>& right, std::int64_t loopFrames, TailMode mode)
  460. {
  461. const auto frames = (std::int64_t) left.size();
  462. if (mode == TailMode::leave || loopFrames <= 0 || frames <= loopFrames)
  463. {
  464. if (mode != TailMode::leave && loopFrames > 0 && frames < loopFrames) // render ended early: pad to the length
  465. {
  466. left.resize ((std::size_t) loopFrames, 0.0f);
  467. right.resize ((std::size_t) loopFrames, 0.0f);
  468. }
  469. return;
  470. }
  471. if (mode == TailMode::wrap)
  472. for (auto i = loopFrames; i < frames; ++i)
  473. {
  474. const auto j = (std::size_t) (i % loopFrames);
  475. left[j] += left[(std::size_t) i];
  476. if ((std::size_t) i < right.size())
  477. right[j] += right[(std::size_t) i];
  478. }
  479. left.resize ((std::size_t) loopFrames);
  480. right.resize ((std::size_t) loopFrames);
  481. }
  482. float normalizeGain (float peak) noexcept
  483. {
  484. return peak > 1.0e-9f ? 1.0f / peak : 1.0f;
  485. }
  486. void toChannels (float* left, const float* right, int n, Channels mode) noexcept
  487. {
  488. switch (mode)
  489. {
  490. case Channels::monoMerged:
  491. for (int i = 0; i < n; ++i)
  492. left[i] = 0.5f * (left[i] + right[i]);
  493. break;
  494. case Channels::monoRight:
  495. for (int i = 0; i < n; ++i)
  496. left[i] = right[i];
  497. break;
  498. case Channels::stereo:
  499. case Channels::monoLeft: break;
  500. }
  501. }
  502. std::string formatDuration (double seconds)
  503. {
  504. const auto total = (long long) std::llround (std::max (0.0, seconds));
  505. const auto h = total / 3600, m = (total / 60) % 60, s = total % 60;
  506. char text[32];
  507. if (h > 0)
  508. std::snprintf (text, sizeof (text), "%lld:%02lld:%02lld", h, m, s);
  509. else
  510. std::snprintf (text, sizeof (text), "%lld:%02lld", m, s);
  511. return text;
  512. }
  513. namespace
  514. {
  515. void put32 (std::vector<std::uint8_t>& b, std::uint32_t v)
  516. {
  517. for (int i = 0; i < 4; ++i)
  518. b.push_back ((std::uint8_t) (v >> (8 * i)));
  519. }
  520. void put16 (std::vector<std::uint8_t>& b, std::uint16_t v)
  521. {
  522. b.push_back ((std::uint8_t) v);
  523. b.push_back ((std::uint8_t) (v >> 8));
  524. }
  525. void putTag (std::vector<std::uint8_t>& b, const char* tag)
  526. {
  527. b.insert (b.end(), tag, tag + 4);
  528. }
  529. void putFloat (std::vector<std::uint8_t>& b, float f)
  530. {
  531. std::uint32_t v = 0;
  532. std::memcpy (&v, &f, 4);
  533. put32 (b, v);
  534. }
  535. // a chunk: tag, size, body, pad byte
  536. void chunk (std::vector<std::uint8_t>& out, const char* tag, const std::vector<std::uint8_t>& body)
  537. {
  538. putTag (out, tag);
  539. put32 (out, (std::uint32_t) body.size());
  540. out.insert (out.end(), body.begin(), body.end());
  541. if ((body.size() & 1) != 0)
  542. out.push_back (0);
  543. }
  544. } // namespace
  545. WavExtras wavExtras (const Song& song, const Options& o, double sampleRate)
  546. {
  547. WavExtras x;
  548. std::int64_t musicTicks = 0, loopTicks = 0;
  549. const auto copy = makeRenderSong (song, o, 0, musicTicks, loopTicks);
  550. x.musicFrames = (std::int64_t) std::llround (copy.secondsForTicks (musicTicks) * sampleRate);
  551. x.loop = o.loopMarkers;
  552. x.acid = o.saveTempo;
  553. x.tempo = (float) song.bpm;
  554. x.numerator = std::max (1, song.beatsPerBar);
  555. x.denominator = std::max (1, 16 / stepsPerBeat); // FL: 16 / steps per beat
  556. if (o.playlistMarkers)
  557. {
  558. // the range: the selection starts at the loop region (as makeRenderSong cuts it), one pass
  559. const auto selection = o.range == Range::selection && hasSelection (song);
  560. const auto start = selection ? song.loopStart : (std::int64_t) 0;
  561. const auto end = selection ? song.loopEnd : start + loopTicks;
  562. const auto startSeconds = song.secondsForTicks (start);
  563. for (const auto& m : song.markers())
  564. if (m.action == Marker::none && ! m.isSignature() && m.tick >= start && m.tick < end)
  565. x.markers.push_back ({ (std::int64_t) std::llround ((song.secondsForTicks (m.tick) - startSeconds) * sampleRate), m.name });
  566. std::stable_sort (x.markers.begin(), x.markers.end(), [] (const auto& a, const auto& b) { return a.frame < b.frame; });
  567. }
  568. return x;
  569. }
  570. std::vector<std::uint8_t> wavExtraChunks (const WavExtras& x, double sampleRate, std::int64_t dataFrames)
  571. {
  572. std::vector<std::uint8_t> out;
  573. if (x.loop)
  574. {
  575. // smpl: manufacturer 0, product 0, sample period (ns), MIDI unity note 60, pitch fraction 0, SMPTE 0 / 0,
  576. // one loop, no sampler data; the loop: id 0x20000, type 0x400, start 0, end = last frame of the music
  577. std::vector<std::uint8_t> b;
  578. put32 (b, 0);
  579. put32 (b, 0);
  580. put32 (b, (std::uint32_t) std::llround (1.0e9 / std::max (1.0, sampleRate)));
  581. put32 (b, 60);
  582. put32 (b, 0);
  583. put32 (b, 0);
  584. put32 (b, 0);
  585. put32 (b, 1);
  586. put32 (b, 0);
  587. put32 (b, 0x20000);
  588. put32 (b, 0x400);
  589. put32 (b, 0);
  590. put32 (b, (std::uint32_t) std::max<std::int64_t> (0, x.musicFrames - 1));
  591. put32 (b, 0);
  592. put32 (b, 0);
  593. chunk (out, "smpl", b);
  594. }
  595. if (x.acid)
  596. {
  597. // acid: flags 4, root note 60, 0x80, 0.0, beats, meter (FL writes the numerator first), tempo
  598. std::vector<std::uint8_t> b;
  599. put32 (b, 4);
  600. put16 (b, 60);
  601. put16 (b, 0x80);
  602. putFloat (b, 0.0f);
  603. put32 (b, (std::uint32_t) std::llround ((double) dataFrames * x.tempo / (std::max (1.0, sampleRate) * 60.0)));
  604. put16 (b, (std::uint16_t) x.numerator);
  605. put16 (b, (std::uint16_t) x.denominator);
  606. putFloat (b, x.tempo);
  607. chunk (out, "acid", b);
  608. }
  609. if (! x.markers.empty())
  610. {
  611. // cue: ids 0x10000 + index, each at its frame in the "data" chunk
  612. std::vector<std::uint8_t> cue, adtl, tlst;
  613. put32 (cue, (std::uint32_t) x.markers.size());
  614. putTag (adtl, "adtl");
  615. for (std::size_t i = 0; i < x.markers.size(); ++i)
  616. {
  617. const auto id = (std::uint32_t) (0x10000 + i);
  618. const auto frame = (std::uint32_t) std::max<std::int64_t> (0, x.markers[i].frame);
  619. put32 (cue, id);
  620. put32 (cue, frame);
  621. putTag (cue, "data");
  622. put32 (cue, 0);
  623. put32 (cue, 0);
  624. put32 (cue, frame);
  625. // labl: the name, or "Marker <index>"
  626. auto name = x.markers[i].name.empty() ? "Marker " + std::to_string (i) : x.markers[i].name;
  627. std::vector<std::uint8_t> l;
  628. put32 (l, id);
  629. l.insert (l.end(), name.begin(), name.end());
  630. l.push_back (0);
  631. chunk (adtl, "labl", l);
  632. }
  633. chunk (out, "cue ", cue);
  634. chunk (out, "LIST", adtl);
  635. // tlst (FL's trigger list, up to 125 markers): 'cue ', the id − 1 (sic), 1, 0xff, note 60 + index (≤ 131),
  636. // 0x90, then zeros
  637. if (x.markers.size() < 0x7e)
  638. {
  639. put32 (tlst, (std::uint32_t) x.markers.size());
  640. for (std::size_t i = 0; i < x.markers.size(); ++i)
  641. {
  642. putTag (tlst, "cue ");
  643. put32 (tlst, (std::uint32_t) (0x10000 + i - 1));
  644. put32 (tlst, 1);
  645. tlst.push_back (0xff);
  646. tlst.push_back ((std::uint8_t) std::min<std::size_t> (0x3c + i, 0x83));
  647. tlst.push_back (0x90);
  648. tlst.push_back (0);
  649. put32 (tlst, 0);
  650. put32 (tlst, 0);
  651. }
  652. chunk (out, "tlst", tlst);
  653. }
  654. }
  655. return out;
  656. }
  657. bool appendWavChunks (const std::string& path, const std::vector<std::uint8_t>& chunks)
  658. {
  659. if (chunks.empty())
  660. return true;
  661. std::fstream f (path, std::ios::in | std::ios::out | std::ios::binary);
  662. if (! f)
  663. return false;
  664. char head[12] {};
  665. f.read (head, 12);
  666. if (! f || std::memcmp (head, "RIFF", 4) != 0 || std::memcmp (head + 8, "WAVE", 4) != 0)
  667. return false;
  668. f.seekg (0, std::ios::end);
  669. auto size = (std::uint64_t) f.tellg();
  670. std::vector<std::uint8_t> tail;
  671. if ((size & 1) != 0) // (the last chunk's pad byte)
  672. tail.push_back (0);
  673. tail.insert (tail.end(), chunks.begin(), chunks.end());
  674. if (size + tail.size() - 8 > 0xffffffffull)
  675. return false;
  676. f.seekp ((std::streamoff) size);
  677. f.write ((const char*) tail.data(), (std::streamsize) tail.size());
  678. size += tail.size();
  679. std::uint8_t riff[4];
  680. for (int i = 0; i < 4; ++i)
  681. riff[i] = (std::uint8_t) ((size - 8) >> (8 * i));
  682. f.seekp (4);
  683. f.write ((const char*) riff, 4);
  684. return (bool) f;
  685. }
  686. std::int64_t wavDataFrames (const std::string& path)
  687. {
  688. std::ifstream f (path, std::ios::binary);
  689. char head[12] {};
  690. f.read (head, 12);
  691. if (! f || std::memcmp (head, "RIFF", 4) != 0 || std::memcmp (head + 8, "WAVE", 4) != 0)
  692. return -1;
  693. std::uint32_t align = 0;
  694. for (;;)
  695. {
  696. std::uint8_t h[8] {};
  697. f.read ((char*) h, 8);
  698. if (! f)
  699. return -1;
  700. const auto size = (std::uint32_t) h[4] | (std::uint32_t) h[5] << 8 | (std::uint32_t) h[6] << 16 | (std::uint32_t) h[7] << 24;
  701. if (std::memcmp (h, "fmt ", 4) == 0 && size >= 16)
  702. {
  703. std::uint8_t fmt[16] {};
  704. f.read ((char*) fmt, 16);
  705. align = (std::uint32_t) fmt[12] | (std::uint32_t) fmt[13] << 8;
  706. f.seekg ((std::streamoff) (size - 16 + (size & 1)), std::ios::cur);
  707. continue;
  708. }
  709. if (std::memcmp (h, "data", 4) == 0)
  710. return align > 0 ? (std::int64_t) (size / align) : -1;
  711. f.seekg ((std::streamoff) (size + (size & 1)), std::ios::cur);
  712. }
  713. }
  714. bool appendWavExtras (const std::string& path, const WavExtras& x, double sampleRate)
  715. {
  716. if (! x.loop && ! x.acid && x.markers.empty())
  717. return true;
  718. const auto frames = wavDataFrames (path);
  719. if (frames < 0)
  720. return false;
  721. return appendWavChunks (path, wavExtraChunks (x, sampleRate, frames));
  722. }
  723. } // namespace lynx::exportopts