ExportOptions.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. #include "core/ExportOptions.h"
  2. #include <algorithm>
  3. #include <cmath>
  4. #include <cstdio>
  5. #include <set>
  6. #include <sstream>
  7. #include "core/Preferences.h"
  8. namespace lynx::exportopts
  9. {
  10. const std::vector<int>& mp3Bitrates()
  11. {
  12. static const std::vector<int> list { 96, 128, 160, 192, 224, 256, 320 };
  13. return list;
  14. }
  15. const std::vector<int>& oggBitrates()
  16. {
  17. static const std::vector<int> list { 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 500 };
  18. return list;
  19. }
  20. const std::vector<double>& sampleRates()
  21. {
  22. static const std::vector<double> list { 44100.0, 48000.0, 88200.0, 96000.0, 192000.0 };
  23. return list;
  24. }
  25. const char* extension (Format format)
  26. {
  27. switch (format)
  28. {
  29. case Format::mp3: return ".mp3";
  30. case Format::ogg: return ".ogg";
  31. case Format::flac: return ".flac";
  32. case Format::wav: break;
  33. }
  34. return ".wav";
  35. }
  36. int fileBits (const Options& o) noexcept
  37. {
  38. switch (o.format)
  39. {
  40. case Format::wav: return o.wavBits;
  41. case Format::flac: return o.flacBits;
  42. case Format::mp3:
  43. case Format::ogg: break;
  44. }
  45. return 16;
  46. }
  47. bool usesDither (const Options& o) noexcept
  48. {
  49. if (o.dither == DitherMode::none)
  50. return false;
  51. if (o.format == Format::wav)
  52. return o.wavBits == 16 || o.wavBits == 24;
  53. return o.format == Format::flac;
  54. }
  55. double mp3SampleRate (double rate) noexcept
  56. {
  57. if (rate == 32000.0 || rate == 44100.0 || rate == 48000.0)
  58. return rate;
  59. return std::fmod (rate, 11025.0) == 0.0 ? 44100.0 : 48000.0;
  60. }
  61. namespace
  62. {
  63. template <typename T>
  64. T nearest (const std::vector<T>& list, T value)
  65. {
  66. auto best = list.front();
  67. for (auto v : list)
  68. if (std::abs ((double) v - (double) value) < std::abs ((double) best - (double) value))
  69. best = v;
  70. return best;
  71. }
  72. int toInt (const std::map<std::string, std::string>& kv, const char* key, int fallback)
  73. {
  74. const auto it = kv.find (key);
  75. if (it == kv.end() || it->second.empty())
  76. return fallback;
  77. try
  78. {
  79. return std::stoi (it->second);
  80. }
  81. catch (...)
  82. {
  83. return fallback;
  84. }
  85. }
  86. double toDouble (const std::map<std::string, std::string>& kv, const char* key, double fallback)
  87. {
  88. const auto it = kv.find (key);
  89. if (it == kv.end() || it->second.empty())
  90. return fallback;
  91. try
  92. {
  93. return std::stod (it->second);
  94. }
  95. catch (...)
  96. {
  97. return fallback;
  98. }
  99. }
  100. } // namespace
  101. Options clamped (Options o)
  102. {
  103. const Options d;
  104. if ((int) o.format < 0 || (int) o.format > 3) o.format = d.format;
  105. if (o.wavBits != 16 && o.wavBits != 24 && o.wavBits != 32) o.wavBits = d.wavBits;
  106. if (o.flacBits != 16 && o.flacBits != 24) o.flacBits = d.flacBits;
  107. o.flacLevel = std::clamp (o.flacLevel, 0, 8);
  108. o.mp3Kbps = nearest (mp3Bitrates(), o.mp3Kbps);
  109. o.oggKbps = nearest (oggBitrates(), o.oggKbps);
  110. o.sampleRate = nearest (sampleRates(), o.sampleRate);
  111. if ((int) o.dither < 0 || (int) o.dither > 2) o.dither = d.dither;
  112. if ((int) o.tail < 0 || (int) o.tail > 2) o.tail = d.tail;
  113. if (! (o.maxTailSeconds >= 0.0)) o.maxTailSeconds = d.maxTailSeconds;
  114. o.maxTailSeconds = std::min (o.maxTailSeconds, 60.0);
  115. if ((int) o.range < 0 || (int) o.range > 2) o.range = d.range;
  116. o.loops = std::clamp (o.loops, 1, 16);
  117. if ((int) o.stems < 0 || (int) o.stems > 2) o.stems = d.stems;
  118. if ((int) o.channels < 0 || (int) o.channels > 3) o.channels = d.channels;
  119. o.moreFormats &= 0xFu & ~(1u << (int) o.format);
  120. return o;
  121. }
  122. double lengthInBars (double seconds, double bpm, int beatsPerBar) noexcept
  123. {
  124. return seconds <= 0.0 || bpm <= 0.0 ? 0.0 : seconds * bpm / 60.0 / (double) std::max (1, beatsPerBar);
  125. }
  126. std::int64_t estimatedBytes (const Options& o, double seconds) noexcept
  127. {
  128. if (seconds <= 0.0)
  129. return 0;
  130. const auto channels = o.channels == Channels::stereo ? 2.0 : 1.0;
  131. std::int64_t total = 0; // every format the export writes (FL's disk space counts all ticked boxes)
  132. for (const auto f : { Format::wav, Format::mp3, Format::ogg, Format::flac })
  133. if (f == o.format || (o.moreFormats & (1u << (int) f)) != 0)
  134. switch (f)
  135. {
  136. case Format::wav: total += (std::int64_t) (seconds * o.sampleRate * channels * (o.wavBits / 8.0)) + 44; break;
  137. case Format::flac: total += (std::int64_t) (seconds * o.sampleRate * channels * (o.flacBits / 8.0) * 0.6); break; // ~60 % of PCM
  138. case Format::mp3: total += (std::int64_t) (seconds * o.mp3Kbps * 1000.0 / 8.0); break;
  139. case Format::ogg: total += (std::int64_t) (seconds * o.oggKbps * 1000.0 / 8.0); break;
  140. }
  141. return total;
  142. }
  143. std::vector<Format> formatsOf (const Options& o)
  144. {
  145. std::vector<Format> out { o.format };
  146. for (const auto f : { Format::wav, Format::mp3, Format::ogg, Format::flac })
  147. if (f != o.format && (o.moreFormats & (1u << (int) f)) != 0)
  148. out.push_back (f);
  149. return out;
  150. }
  151. std::uint32_t flLastExportedMask (const Options& o) noexcept
  152. {
  153. std::uint32_t mask = flFormatBit (o.format);
  154. for (const auto f : { Format::wav, Format::mp3, Format::ogg, Format::flac })
  155. if ((o.moreFormats & (1u << (int) f)) != 0)
  156. mask |= flFormatBit (f);
  157. return mask;
  158. }
  159. Options withFlLastExported (Options o, std::uint32_t mask)
  160. {
  161. if (mask < 8 || mask > 0x3FF) // FL: anything else falls back to WAV
  162. mask = 8;
  163. std::vector<Format> chosen;
  164. for (const auto f : { Format::wav, Format::mp3, Format::ogg, Format::flac })
  165. if ((mask & flFormatBit (f)) != 0)
  166. chosen.push_back (f);
  167. if (chosen.empty()) // only formats LYNX writes elsewhere (MIDI, M4A): WAV
  168. chosen.push_back (Format::wav);
  169. o.format = chosen.front();
  170. o.moreFormats = 0;
  171. for (std::size_t i = 1; i < chosen.size(); ++i)
  172. o.moreFormats |= 1u << (int) chosen[i];
  173. return o;
  174. }
  175. Options withSingleFormat (Options o, Format f)
  176. {
  177. o.format = f;
  178. o.moreFormats = 0;
  179. return o;
  180. }
  181. std::vector<Note> midiExportNotes (const Song& song)
  182. {
  183. std::vector<Note> out;
  184. const auto trackMuted = [&song] (int track) {
  185. return track >= 0 && track < (int) song.playlistTracks.size() && song.playlistTracks[(std::size_t) track].muted;
  186. };
  187. if (song.mode == PlayMode::song)
  188. for (const auto& c : song.playlist)
  189. {
  190. if (c.kind != ClipKind::pattern || c.muted || c.length <= 0 || trackMuted (c.track) || c.pattern < 0
  191. || c.pattern >= (int) song.patterns.size())
  192. continue;
  193. for (auto n : song.patterns[(std::size_t) c.pattern].notes)
  194. {
  195. if (n.muted || n.start < c.offset || n.start >= c.offset + c.length)
  196. continue;
  197. n.start = c.start + (n.start - c.offset);
  198. n.length = std::max<std::int64_t> (1, std::min (n.length, c.end() - n.start));
  199. out.push_back (n);
  200. }
  201. }
  202. if (out.empty() && (song.mode != PlayMode::song || std::none_of (song.playlist.begin(), song.playlist.end(),
  203. [] (const Clip& c) { return c.kind == ClipKind::pattern; })))
  204. if (song.currentPattern >= 0 && song.currentPattern < (int) song.patterns.size())
  205. for (const auto& n : song.patterns[(std::size_t) song.currentPattern].notes)
  206. if (! n.muted)
  207. out.push_back (n);
  208. std::stable_sort (out.begin(), out.end(), [] (const Note& a, const Note& b) { return a.start < b.start; });
  209. return out;
  210. }
  211. std::string toText (const Options& o)
  212. {
  213. std::ostringstream s;
  214. s << "format=" << (int) o.format << "\n"
  215. << "wavBits=" << o.wavBits << "\n"
  216. << "flacBits=" << o.flacBits << "\n"
  217. << "flacLevel=" << o.flacLevel << "\n"
  218. << "mp3Kbps=" << o.mp3Kbps << "\n"
  219. << "oggKbps=" << o.oggKbps << "\n"
  220. << "sampleRate=" << (int) o.sampleRate << "\n"
  221. << "dither=" << (int) o.dither << "\n"
  222. << "tail=" << (int) o.tail << "\n"
  223. << "maxTail=" << o.maxTailSeconds << "\n"
  224. << "range=" << (int) o.range << "\n"
  225. << "loops=" << o.loops << "\n"
  226. << "stems=" << (int) o.stems << "\n"
  227. << "stemsMaster=" << (o.stemsIncludeMaster ? 1 : 0) << "\n"
  228. << "normalize=" << (o.normalize ? 1 : 0) << "\n"
  229. << "masterEffects=" << (o.masterEffects ? 1 : 0) << "\n"
  230. << "trimPdc=" << (o.trimPdc ? 1 : 0) << "\n"
  231. << "hqAllPlugins=" << (o.hqAllPlugins ? 1 : 0) << "\n"
  232. << "pluginWarmUp=" << (o.pluginWarmUp ? 1 : 0) << "\n"
  233. << "showWhenDone=" << (o.showWhenDone ? 1 : 0) << "\n"
  234. << "disableMaxPolyphony=" << (o.disableMaxPolyphony ? 1 : 0) << "\n"
  235. << "moreFormats=" << o.moreFormats << "\n"
  236. << "channels=" << (int) o.channels << "\n";
  237. return s.str();
  238. }
  239. Options fromText (const std::string& text)
  240. {
  241. const auto kv = prefs::parseKeyValues (text);
  242. const Options d;
  243. Options o;
  244. o.format = (Format) toInt (kv, "format", (int) d.format);
  245. o.wavBits = toInt (kv, "wavBits", d.wavBits);
  246. o.flacBits = toInt (kv, "flacBits", d.flacBits);
  247. o.flacLevel = toInt (kv, "flacLevel", d.flacLevel);
  248. o.mp3Kbps = toInt (kv, "mp3Kbps", d.mp3Kbps);
  249. o.oggKbps = toInt (kv, "oggKbps", d.oggKbps);
  250. o.sampleRate = toDouble (kv, "sampleRate", d.sampleRate);
  251. o.dither = (DitherMode) toInt (kv, "dither", (int) d.dither);
  252. o.tail = (TailMode) toInt (kv, "tail", (int) d.tail);
  253. o.maxTailSeconds = toDouble (kv, "maxTail", d.maxTailSeconds);
  254. o.range = (Range) toInt (kv, "range", (int) d.range);
  255. o.loops = toInt (kv, "loops", d.loops);
  256. o.stems = (Stems) toInt (kv, "stems", (int) d.stems);
  257. o.stemsIncludeMaster = toInt (kv, "stemsMaster", d.stemsIncludeMaster ? 1 : 0) != 0;
  258. o.normalize = toInt (kv, "normalize", d.normalize ? 1 : 0) != 0;
  259. o.masterEffects = toInt (kv, "masterEffects", d.masterEffects ? 1 : 0) != 0;
  260. o.trimPdc = toInt (kv, "trimPdc", d.trimPdc ? 1 : 0) != 0;
  261. o.hqAllPlugins = toInt (kv, "hqAllPlugins", d.hqAllPlugins ? 1 : 0) != 0;
  262. o.pluginWarmUp = toInt (kv, "pluginWarmUp", d.pluginWarmUp ? 1 : 0) != 0;
  263. o.showWhenDone = toInt (kv, "showWhenDone", d.showWhenDone ? 1 : 0) != 0;
  264. o.disableMaxPolyphony = toInt (kv, "disableMaxPolyphony", d.disableMaxPolyphony ? 1 : 0) != 0;
  265. o.moreFormats = (std::uint32_t) std::clamp (toInt (kv, "moreFormats", 0), 0, 15);
  266. o.channels = (Channels) toInt (kv, "channels", (int) d.channels);
  267. return clamped (o);
  268. }
  269. bool hasSelection (const Song& song) noexcept
  270. {
  271. return song.loopEnd > song.loopStart && song.loopStart >= 0;
  272. }
  273. Song makeRenderSong (const Song& song, const Options& o, std::int64_t tailTicks, std::int64_t& musicTicks, std::int64_t& loopTicks)
  274. {
  275. Song base = song;
  276. std::int64_t length = 0;
  277. if (o.range == Range::selection && hasSelection (song))
  278. {
  279. const auto from = song.loopStart, to = song.loopEnd;
  280. std::vector<Clip> cropped;
  281. for (auto clip : song.playlist)
  282. {
  283. if (clip.end() <= from || clip.start >= to || clip.length <= 0)
  284. continue;
  285. if (clip.start < from)
  286. clip = splitClip (clip, from);
  287. if (clip.end() > to)
  288. splitClip (clip, to); // keeps the head
  289. clip.start -= from;
  290. cropped.push_back (clip);
  291. }
  292. base.playlist = std::move (cropped);
  293. base.mode = PlayMode::song;
  294. std::int64_t ignored = 0;
  295. base = makeExportSong (base, true, 0, ignored);
  296. length = to - from;
  297. if (base.playlist.empty()) // nothing in the selection: a silent pass of the right length
  298. {
  299. base.patterns.emplace_back().name = "(silence)";
  300. Clip silent;
  301. silent.pattern = (int) base.patterns.size() - 1;
  302. silent.length = length;
  303. base.playlist.push_back (silent);
  304. }
  305. }
  306. else
  307. base = makeExportSong (song, o.range == Range::song || (o.range == Range::selection), 0, length);
  308. length = std::max<std::int64_t> (1, length);
  309. loopTicks = length;
  310. // the range repeated: copies of the clips shifted by one pass each
  311. const auto loops = std::clamp (o.loops, 1, 16);
  312. if (loops > 1)
  313. {
  314. const auto once = base.playlist;
  315. for (int k = 1; k < loops; ++k)
  316. for (auto clip : once)
  317. {
  318. clip.start += length * k;
  319. base.playlist.push_back (clip);
  320. }
  321. }
  322. musicTicks = length * loops;
  323. // the tail: an empty pattern after the music (plus a bar of slack, like makeExportSong)
  324. if (tailTicks > 0)
  325. {
  326. base.patterns.emplace_back().name = "(tail)";
  327. Clip tail;
  328. tail.pattern = (int) base.patterns.size() - 1;
  329. tail.start = musicTicks;
  330. tail.length = tailTicks + (std::int64_t) ppq * std::max (1, base.beatsPerBar);
  331. base.playlist.push_back (tail);
  332. }
  333. if (! o.masterEffects && ! base.mixer.empty())
  334. base.mixer[0].effects.clear();
  335. if (o.disableMaxPolyphony) // FL: every channel's Max polyphony becomes 0 (no limit) for the render
  336. for (auto& c : base.channels)
  337. c.maxPolyphony = 0;
  338. base.mode = PlayMode::song;
  339. base.loopStart = base.loopEnd = 0;
  340. return base;
  341. }
  342. std::vector<int> stemTracks (const Song& song)
  343. {
  344. std::vector<int> out;
  345. for (int t = 1; t < (int) song.mixer.size(); ++t)
  346. {
  347. auto used = std::any_of (song.channels.begin(), song.channels.end(), [t] (const ChannelDef& c) { return c.mixerTrack == t; });
  348. for (int src = 1; src < (int) song.mixer.size() && ! used; ++src)
  349. used = src != t && song.routes (src, t);
  350. if (used)
  351. out.push_back (t);
  352. }
  353. return out;
  354. }
  355. std::vector<int> stemChannels (const Song& song, Range range)
  356. {
  357. std::set<int> used;
  358. auto addPattern = [&] (int p) {
  359. if (p < 0 || p >= (int) song.patterns.size())
  360. return;
  361. for (const auto& n : song.patterns[(std::size_t) p].notes)
  362. used.insert (n.channel);
  363. };
  364. if (range == Range::pattern || song.playlist.empty())
  365. addPattern (song.currentPattern);
  366. else
  367. for (const auto& c : song.playlist)
  368. {
  369. if (c.muted || song.isTrackMuted (c.track))
  370. continue;
  371. if (c.kind == ClipKind::pattern)
  372. addPattern (c.pattern);
  373. else if (c.kind == ClipKind::audio)
  374. used.insert (c.channel);
  375. }
  376. std::vector<int> out;
  377. for (auto c : used)
  378. if (c >= 0 && c < (int) song.channels.size() && ! song.channels[(std::size_t) c].muted)
  379. out.push_back (c);
  380. return out;
  381. }
  382. Song makeChannelStemSong (const Song& song, int channel)
  383. {
  384. Song out = song;
  385. for (int c = 0; c < (int) out.channels.size(); ++c)
  386. if (c != channel)
  387. out.channels[(std::size_t) c].muted = true;
  388. return out;
  389. }
  390. std::string stemFileName (const std::string& base, int number, const std::string& name, const char* ext)
  391. {
  392. std::string clean;
  393. for (auto ch : name)
  394. clean += std::string ("<>:\"/\\|?*").find (ch) != std::string::npos || (unsigned char) ch < 32 ? '_' : ch;
  395. while (! clean.empty() && (clean.back() == ' ' || clean.back() == '.'))
  396. clean.pop_back();
  397. return base + " - " + std::to_string (number) + (clean.empty() ? "" : " " + clean) + ext;
  398. }
  399. void applyTail (std::vector<float>& left, std::vector<float>& right, std::int64_t loopFrames, TailMode mode)
  400. {
  401. const auto frames = (std::int64_t) left.size();
  402. if (mode == TailMode::leave || loopFrames <= 0 || frames <= loopFrames)
  403. {
  404. if (mode != TailMode::leave && loopFrames > 0 && frames < loopFrames) // render ended early: pad to the length
  405. {
  406. left.resize ((std::size_t) loopFrames, 0.0f);
  407. right.resize ((std::size_t) loopFrames, 0.0f);
  408. }
  409. return;
  410. }
  411. if (mode == TailMode::wrap)
  412. for (auto i = loopFrames; i < frames; ++i)
  413. {
  414. const auto j = (std::size_t) (i % loopFrames);
  415. left[j] += left[(std::size_t) i];
  416. if ((std::size_t) i < right.size())
  417. right[j] += right[(std::size_t) i];
  418. }
  419. left.resize ((std::size_t) loopFrames);
  420. right.resize ((std::size_t) loopFrames);
  421. }
  422. float normalizeGain (float peak) noexcept
  423. {
  424. return peak > 1.0e-9f ? 1.0f / peak : 1.0f;
  425. }
  426. void toChannels (float* left, const float* right, int n, Channels mode) noexcept
  427. {
  428. switch (mode)
  429. {
  430. case Channels::monoMerged:
  431. for (int i = 0; i < n; ++i)
  432. left[i] = 0.5f * (left[i] + right[i]);
  433. break;
  434. case Channels::monoRight:
  435. for (int i = 0; i < n; ++i)
  436. left[i] = right[i];
  437. break;
  438. case Channels::stereo:
  439. case Channels::monoLeft: break;
  440. }
  441. }
  442. std::string formatDuration (double seconds)
  443. {
  444. const auto total = (long long) std::llround (std::max (0.0, seconds));
  445. const auto h = total / 3600, m = (total / 60) % 60, s = total % 60;
  446. char text[32];
  447. if (h > 0)
  448. std::snprintf (text, sizeof (text), "%lld:%02lld:%02lld", h, m, s);
  449. else
  450. std::snprintf (text, sizeof (text), "%lld:%02lld", m, s);
  451. return text;
  452. }
  453. } // namespace lynx::exportopts