FlpExport.cpp 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548
  1. #include "core/PlaylistOps.h"
  2. #include "core/FlpExport.h"
  3. #include <algorithm>
  4. #include <cmath>
  5. #include <cstring>
  6. #include <map>
  7. #include <numeric>
  8. #include <set>
  9. #include "core/Effects.h"
  10. #include "core/FlEffects.h"
  11. #include "core/PatternBlocks.h"
  12. #include "core/ThreeOsc.h"
  13. namespace lynx::flpexport
  14. {
  15. namespace
  16. {
  17. // ---- small helpers ----
  18. int iround (double v) noexcept { return (int) std::lround (v); }
  19. std::uint32_t rgb (std::uint32_t argb) noexcept { return argb & 0xFFFFFFu; }
  20. struct Hash
  21. {
  22. std::uint64_t h = 1469598103934665603ull; // FNV-1a 64
  23. void bytes (const void* p, std::size_t n) noexcept
  24. {
  25. const auto* b = (const std::uint8_t*) p;
  26. for (std::size_t i = 0; i < n; ++i)
  27. h = (h ^ b[i]) * 1099511628211ull;
  28. }
  29. void i64 (std::int64_t v) noexcept { bytes (&v, sizeof v); }
  30. void text (const std::string& s) noexcept { i64 ((std::int64_t) s.size()); bytes (s.data(), s.size()); }
  31. void blob (const std::vector<std::uint8_t>& v) noexcept { i64 ((std::int64_t) v.size()); bytes (v.data(), v.size()); }
  32. // the project file keeps parameters to 1e-4 (ProjectFile's effectToVar), so does the fingerprint
  33. void value (float v) noexcept { i64 (std::isfinite (v) ? (std::int64_t) std::llround ((double) v * 10000.0) : 0); }
  34. };
  35. // The FL generator for each InstrumentKind whose state LYNX keeps in FL's own format (pluginState = FL's 0xD5), and the
  36. // sample / data path FL keeps in the channel (3x Osc's custom wave, the Granulizer's and Wave Traveller's sample).
  37. struct FlGenerator
  38. {
  39. InstrumentKind kind;
  40. const char* name;
  41. bool channelSample; // the channel's samplePath is FL's channel sample
  42. };
  43. constexpr FlGenerator flGenerators[] = {
  44. { InstrumentKind::sytrus, "Sytrus", false }, { InstrumentKind::harmor, "Harmor", false },
  45. { InstrumentKind::gms, "GMS", false }, { InstrumentKind::morphine, "Morphine", false },
  46. { InstrumentKind::ogun, "Ogun", false }, { InstrumentKind::minisynth, "MiniSynth", false },
  47. { InstrumentKind::dx10, "Fruity DX10", false }, { InstrumentKind::kepler, "Kepler", false },
  48. { InstrumentKind::poizone, "PoiZone", false }, { InstrumentKind::fruitkick, "Fruit Kick", false },
  49. { InstrumentKind::bassdrum, "BassDrum", false }, { InstrumentKind::toxic, "Toxic Biohazard", false },
  50. { InstrumentKind::threeosc, "3x Osc", true }, { InstrumentKind::autogun, "Autogun", false },
  51. { InstrumentKind::transistorbass, "Transistor Bass", false }, { InstrumentKind::simsynth, "SimSynth", false },
  52. { InstrumentKind::wasp, "Wasp", false }, { InstrumentKind::plucked, "Plucked!", false },
  53. { InstrumentKind::beepmap, "BeepMap", false }, { InstrumentKind::sawer, "Sawer", false },
  54. { InstrumentKind::flkeys, "FL Keys", false }, { InstrumentKind::granulizer, "Fruity Granulizer", true },
  55. { InstrumentKind::drumaxx, "Drumaxx", false }, { InstrumentKind::slayer, "FL Slayer", false },
  56. { InstrumentKind::fruitydance, "Fruity Dance", false }, { InstrumentKind::directwave, "DirectWave", false },
  57. { InstrumentKind::midiOut, "MIDI Out", false }, { InstrumentKind::voltage, "Fruity Voltage Controller", false },
  58. { InstrumentKind::dashboard, "Dashboard", false }, { InstrumentKind::videoplayer, "Fruity Video Player", false },
  59. { InstrumentKind::keplerExo, "Kepler Exo", false }, { InstrumentKind::wavetraveller, "Wave Traveller", true },
  60. };
  61. const FlGenerator* generatorFor (InstrumentKind kind) noexcept
  62. {
  63. for (const auto& g : flGenerators)
  64. if (g.kind == kind)
  65. return &g;
  66. return nullptr;
  67. }
  68. bool originMatches (const ChannelDef& c) { return ! c.flOrigin.empty() && c.flOrigin.fingerprint == fingerprint (c); }
  69. bool originMatches (const EffectSlot& s) { return ! s.flOrigin.empty() && s.flOrigin.fingerprint == fingerprint (s); }
  70. bool samplerLike (InstrumentKind k) noexcept { return k == InstrumentKind::sampler || k == InstrumentKind::audioClip; }
  71. // what FL's Sampler can't do of a LYNX sampler (it then needs a render)
  72. bool samplerExportable (const ChannelDef& c) noexcept
  73. {
  74. return samplerLike (c.instrument) && c.zones.empty() && c.sampler.slices.empty();
  75. }
  76. std::string channelLabel (const ChannelDef& c, int index)
  77. {
  78. return "Channel " + std::to_string (index + 1) + " '" + c.name + "'";
  79. }
  80. std::string insertLabel (const Song& song, int t)
  81. {
  82. if (t == 0)
  83. return "Master";
  84. const auto& name = song.mixer[(std::size_t) t].name;
  85. return "Insert " + std::to_string (t) + (name.empty() ? std::string() : " '" + name + "'");
  86. }
  87. // ---- Fruity Wrapper (0xD5 version 12, REA_rodada5 §2; FL 2026's record order [DATA: its saved projects]) ----
  88. struct Records
  89. {
  90. std::vector<std::uint8_t> b;
  91. void put32 (std::uint32_t v)
  92. {
  93. for (int k = 0; k < 4; ++k)
  94. b.push_back ((std::uint8_t) (v >> (8 * k)));
  95. }
  96. void record (std::uint32_t id, const std::vector<std::uint8_t>& data)
  97. {
  98. put32 (id);
  99. const auto n = (std::uint64_t) data.size();
  100. for (int k = 0; k < 8; ++k)
  101. b.push_back ((std::uint8_t) (n >> (8 * k)));
  102. b.insert (b.end(), data.begin(), data.end());
  103. }
  104. void record (std::uint32_t id, const std::string& text) { record (id, std::vector<std::uint8_t> (text.begin(), text.end())); }
  105. };
  106. std::vector<std::uint8_t> le32s (std::initializer_list<std::uint32_t> values)
  107. {
  108. std::vector<std::uint8_t> out;
  109. for (const auto v : values)
  110. for (int k = 0; k < 4; ++k)
  111. out.push_back ((std::uint8_t) (v >> (8 * k)));
  112. return out;
  113. }
  114. // FL 2026's Fruity Limiter as it comes (version 7, 169 bytes) [DATA: FL 2026's own templates, e.g. "Cheese's recording
  115. // setup"]: the substitute for LYNX's Limiter (option B, and the Master, which can't be bounced)
  116. const std::uint8_t fruityLimiterDefault[169] = {
  117. 0x07, 0x00, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0x5b, 0x04, 0x00, 0x00,
  118. 0x03, 0x00, 0x00, 0x00, 0x88, 0x13, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x42, 0x0b, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00,
  119. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x1a, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
  120. 0x8a, 0x02, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5b, 0x10, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00,
  121. 0xe8, 0x03, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0x5b, 0x04, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x88, 0x13, 0x00, 0x00,
  122. 0x03, 0x00, 0x00, 0x00, 0x42, 0x0b, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  123. 0x00, 0x00, 0x00, 0x00, 0x0a, 0x1a, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x8a, 0x02, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00,
  124. 0x00, 0x00, 0x00, 0x00, 0x5b, 0x10, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01,
  125. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  126. };
  127. // option B's clean mappings: the LYNX effect → an FL plugin with its state
  128. std::optional<std::pair<std::string, std::vector<std::uint8_t>>> substituteFor (const EffectSlot& slot)
  129. {
  130. if (slot.kind == EffectKind::limiter)
  131. return std::pair { std::string ("Fruity Limiter"), std::vector<std::uint8_t> (std::begin (fruityLimiterDefault), std::end (fruityLimiterDefault)) };
  132. return std::nullopt;
  133. }
  134. // LYNX's 0..1 automation value → FL's raw parameter value for a pattern event / initial value
  135. std::int32_t rawValue (const AutomationTarget& t, float v)
  136. {
  137. v = std::clamp (v, 0.0f, 1.0f);
  138. switch (t.kind)
  139. {
  140. case AutomationTargetKind::channelVolume:
  141. case AutomationTargetKind::channelPan: return iround (v * 12800.0);
  142. case AutomationTargetKind::mixerVolume:
  143. case AutomationTargetKind::mixerSend: return iround (v * 16000.0);
  144. case AutomationTargetKind::mixerPan: return iround ((v * 2.0 - 1.0) * 6400.0);
  145. case AutomationTargetKind::effectMix: return iround (v * 12800.0);
  146. default: return iround (v * 65536.0);
  147. }
  148. }
  149. std::uint32_t mixerId (int track, int slot, int param) noexcept
  150. {
  151. return 0x70000000u + ((std::uint32_t) track << 22) + ((std::uint32_t) slot << 16) + (std::uint32_t) param;
  152. }
  153. // FL's channel filter cutoff for normalised Mod X (REA_rodada4 §3), as the importer's channelFilterHz
  154. double filterHz (int type, double x)
  155. {
  156. constexpr double twoPi = 6.283185307179586;
  157. x = std::clamp (x, 0.0, 1.0);
  158. switch (type)
  159. {
  160. case 0: return x >= 1.0 ? 20000.0 : -44100.0 / twoPi * std::log (1.0 - std::min ((std::pow (601.0, x) - 1.0) / 600.0, 0.999));
  161. case 1:
  162. case 2:
  163. case 3:
  164. case 4:
  165. case 5: return ((std::pow (51.0, x) - 1.0) * 0.0596 + 0.02) * 44100.0 / twoPi;
  166. default: return 20000.0;
  167. }
  168. }
  169. // a monotonic f over [0, 1]: the x whose f(x) is nearest `target`
  170. template <typename F>
  171. double invert (F&& f, double target, bool increasing = true)
  172. {
  173. double lo = 0.0, hi = 1.0;
  174. for (int i = 0; i < 40; ++i)
  175. {
  176. const auto mid = 0.5 * (lo + hi);
  177. if ((f (mid) < target) == increasing)
  178. lo = mid;
  179. else
  180. hi = mid;
  181. }
  182. return 0.5 * (lo + hi);
  183. }
  184. } // namespace
  185. // ================================================================================================================
  186. int envelopeTimeValue (double seconds) noexcept
  187. {
  188. if (! (seconds > 0.0))
  189. return 100; // FL: values up to 100 are no time at all
  190. const auto v = 65536.0 * std::log (seconds / 0.064 + 1.0) / std::log (1000.0);
  191. return std::clamp (iround (v), 101, 65536);
  192. }
  193. int slideTimeValue (float beats) noexcept
  194. {
  195. // n = round((27^(v/1024) − 1)·48/26) ticks of 1/192 beat (REA_rodada6 §4)
  196. const auto n = std::max (1.0, (double) beats * 192.0);
  197. return std::clamp (iround (1024.0 * std::log (n * 26.0 / 48.0 + 1.0) / std::log (27.0)), 0, 1660);
  198. }
  199. std::vector<std::uint8_t> defaultThreeOscState()
  200. {
  201. // a version-13 state of zeros is LYNX's Params {}; normalised: version 14 + the default voice snapshot
  202. std::vector<std::uint8_t> zero (4 + 21 * 4 + 8, 0);
  203. zero[0] = 13;
  204. return threeOscNormalisedState (zero, {});
  205. }
  206. std::vector<std::uint8_t> fruityLimiterDefaultState()
  207. {
  208. return std::vector<std::uint8_t> (std::begin (fruityLimiterDefault), std::end (fruityLimiterDefault));
  209. }
  210. std::uint64_t fingerprint (const ChannelDef& c)
  211. {
  212. Hash h;
  213. h.i64 ((std::int64_t) c.instrument);
  214. h.blob (c.pluginState);
  215. h.blob (c.controllerState);
  216. h.i64 ((std::int64_t) c.modelParams.size());
  217. for (const auto v : c.modelParams)
  218. h.value (v);
  219. h.i64 ((std::int64_t) c.zones.size());
  220. h.i64 ((std::int64_t) c.sampler.slices.size());
  221. h.text (c.plugin.id);
  222. return h.h;
  223. }
  224. std::uint64_t fingerprint (const EffectSlot& s)
  225. {
  226. Hash h;
  227. h.i64 ((std::int64_t) s.kind);
  228. const auto used = s.kind == EffectKind::plugin ? (std::size_t) 0 : std::min (effectInfo (s.kind).params.size(), s.params.size());
  229. for (std::size_t i = 0; i < used; ++i)
  230. h.value (s.params[i]);
  231. h.blob (s.state);
  232. h.i64 ((std::int64_t) s.branches.size());
  233. h.i64 ((std::int64_t) s.patcher.nodes.size());
  234. return h.h;
  235. }
  236. void stampOrigins (Song& song)
  237. {
  238. for (auto& c : song.channels)
  239. if (! c.flOrigin.empty())
  240. c.flOrigin.fingerprint = fingerprint (c);
  241. for (auto& t : song.mixer)
  242. for (auto& s : t.effects)
  243. if (! s.flOrigin.empty())
  244. s.flOrigin.fingerprint = fingerprint (s);
  245. }
  246. std::string flGeneratorName (const ChannelDef& c)
  247. {
  248. if (originMatches (c))
  249. return c.flOrigin.plugin;
  250. if (c.instrument == InstrumentKind::layer)
  251. return "Layer";
  252. // (an empty state: the engines LYNX plays from their defaults, which are FL's — a new FL instance)
  253. // (3x Osc with no state: LYNX's default is written as FL's own version-14 state [FL 2026: a 3x Osc with an empty
  254. // state keeps uninitialised voice settings, its notes never end; round 171e, FL render])
  255. const auto own = c.instrument == InstrumentKind::threeosc;
  256. if (const auto* g = generatorFor (c.instrument); g != nullptr && (! c.pluginState.empty() || own))
  257. return g->name;
  258. return {};
  259. }
  260. namespace
  261. {
  262. std::string instrumentName (InstrumentKind k)
  263. {
  264. switch (k)
  265. {
  266. case InstrumentKind::kick: return "LYNX Kick";
  267. case InstrumentKind::snare: return "LYNX Snare";
  268. case InstrumentKind::hat: return "LYNX Hat";
  269. case InstrumentKind::clap: return "LYNX Clap";
  270. case InstrumentKind::synth: return "LYNX Synth";
  271. case InstrumentKind::sampler: return "Sampler (multi-sample / slices)";
  272. case InstrumentKind::controller: return "Envelope Controller";
  273. case InstrumentKind::patcher: return "Patcher";
  274. case InstrumentKind::soundfont: return "LYNX Soundfont";
  275. case InstrumentKind::vfx: return "VFX note processor";
  276. default: return "instrument";
  277. }
  278. }
  279. } // namespace
  280. bool needsFreeze (const ChannelDef& c)
  281. {
  282. if (c.instrument == InstrumentKind::plugin || c.plugin.foreign.format != ForeignPlugin::Format::none)
  283. return false; // the wrapper (or, unknown, planRenders decides)
  284. if (! flGeneratorName (c).empty())
  285. return false;
  286. return ! samplerExportable (c);
  287. }
  288. bool effectExportable (const EffectSlot& s, const Options& options)
  289. {
  290. if (s.isSubstitute() && s.substituteFor.foreign.format != ForeignPlugin::Format::none)
  291. return true;
  292. if (s.kind == EffectKind::plugin)
  293. return s.plugin.foreign.format != ForeignPlugin::Format::none || (options.pluginRecord && options.pluginRecord (s.plugin, false));
  294. if (originMatches (s))
  295. return true;
  296. return options.lynxOnly == LynxOnly::substitute && substituteFor (s).has_value();
  297. }
  298. // ================================================================================================================
  299. RenderPlan planRenders (const Song& song, const Options& options)
  300. {
  301. RenderPlan plan;
  302. if (options.lynxOnly != LynxOnly::renderAudio)
  303. return plan;
  304. for (int i = 0; i < (int) song.channels.size(); ++i)
  305. {
  306. const auto& c = song.channels[(std::size_t) i];
  307. const auto pluginUnknown = c.instrument == InstrumentKind::plugin && c.plugin.foreign.format == ForeignPlugin::Format::none
  308. && ! (options.pluginRecord && options.pluginRecord (c.plugin, true));
  309. // (silent kinds — controllers, VFX, video, MIDI out — make no audio to freeze; they are left out instead)
  310. const auto silent = c.instrument == InstrumentKind::controller || c.instrument == InstrumentKind::vfx;
  311. if ((needsFreeze (c) && ! silent) || pluginUnknown)
  312. plan.channels.push_back (i);
  313. }
  314. // inserts with a slot FL can't have (Master excluded: bouncing it would bounce the whole song), downstream first
  315. std::vector<int> order;
  316. for (const auto t : song.mixerOrder())
  317. if (t > 0 && t < (int) song.mixer.size())
  318. order.push_back (t);
  319. std::set<int> silenced;
  320. for (auto it = order.rbegin(); it != order.rend(); ++it)
  321. {
  322. const auto t = *it;
  323. const auto& track = song.mixer[(std::size_t) t];
  324. const auto lynxOnly = std::any_of (track.effects.begin(), track.effects.end(),
  325. [&] (const EffectSlot& s) { return song.slotActive (s) && ! effectExportable (s, options); });
  326. if (! lynxOnly)
  327. continue;
  328. // an insert heard only through inserts already bounced is in their audio
  329. auto audible = track.toMaster;
  330. for (const auto& send : track.sends)
  331. audible = audible || silenced.count (send.target) == 0;
  332. if (! audible && ! track.sends.empty())
  333. continue;
  334. plan.inserts.push_back (t);
  335. silenced.insert (t);
  336. }
  337. return plan;
  338. }
  339. Song makeInsertRenderSong (const Song& song, int track)
  340. {
  341. auto out = makeBounceSong (song, track);
  342. if (track <= 0 || track >= (int) out.mixer.size())
  343. return out;
  344. for (int t = 1; t < (int) out.mixer.size(); ++t)
  345. if (t != track)
  346. out.mixer[(std::size_t) t].toMaster = false;
  347. return out;
  348. }
  349. Song makeFreezeSong (const Song& song, int channel)
  350. {
  351. Song out = song;
  352. out.mode = PlayMode::song;
  353. for (int i = 0; i < (int) out.channels.size(); ++i)
  354. if (i != channel)
  355. out.channels[(std::size_t) i].muted = true;
  356. if (channel >= 0 && channel < (int) out.channels.size())
  357. {
  358. auto& c = out.channels[(std::size_t) channel];
  359. c.muted = false;
  360. c.mixerTrack = 0;
  361. }
  362. for (auto& t : out.mixer)
  363. t.solo = false;
  364. if (! out.mixer.empty())
  365. {
  366. auto& master = out.mixer[0];
  367. master.effects.clear();
  368. master.volume = unityFader;
  369. master.pan = 0.0f;
  370. master.stereo = 0.0f;
  371. master.eq = TrackEq {};
  372. master.muted = false;
  373. master.invertPhase = master.swapChannels = false;
  374. }
  375. // the Master's own automation would colour the render
  376. for (auto& a : out.automations)
  377. if ((a.target.kind == AutomationTargetKind::mixerVolume || a.target.kind == AutomationTargetKind::mixerPan
  378. || a.target.kind == AutomationTargetKind::effectParam || a.target.kind == AutomationTargetKind::effectMix)
  379. && a.target.index == 0)
  380. a.target.kind = AutomationTargetKind::none;
  381. return out;
  382. }
  383. void applyFreeze (Song& song, int channel, const std::string& wav, std::int64_t length)
  384. {
  385. if (channel < 0 || channel >= (int) song.channels.size())
  386. return;
  387. auto& c = song.channels[(std::size_t) channel];
  388. const auto mixerTrack = c.mixerTrack;
  389. const auto name = c.name;
  390. const auto colour = c.colour;
  391. ChannelDef frozen;
  392. frozen.name = name + " (audio)";
  393. frozen.instrument = InstrumentKind::audioClip;
  394. frozen.samplePath = wav;
  395. frozen.mixerTrack = mixerTrack;
  396. frozen.volume = 1.0f; // unity: the render holds the channel's level and pan
  397. frozen.colour = colour;
  398. frozen.uid = c.uid;
  399. c = std::move (frozen);
  400. for (auto& p : song.patterns)
  401. {
  402. p.notes.erase (std::remove_if (p.notes.begin(), p.notes.end(), [channel] (const Note& n) { return n.channel == channel; }), p.notes.end());
  403. p.channelLoops.erase (std::remove_if (p.channelLoops.begin(), p.channelLoops.end(), [channel] (const ChannelLoop& l) { return l.channel == channel; }),
  404. p.channelLoops.end());
  405. for (auto& lane : p.events)
  406. if ((lane.target.kind == AutomationTargetKind::channelVolume || lane.target.kind == AutomationTargetKind::channelPan
  407. || lane.target.kind == AutomationTargetKind::channelParam) && lane.target.index == channel)
  408. lane.target.kind = AutomationTargetKind::none;
  409. }
  410. for (auto& a : song.automations)
  411. if ((a.target.kind == AutomationTargetKind::channelVolume || a.target.kind == AutomationTargetKind::channelPan
  412. || a.target.kind == AutomationTargetKind::channelParam) && a.target.index == channel)
  413. a.target.kind = AutomationTargetKind::none;
  414. int lane = 0;
  415. song.forEachClipList ([&lane] (const std::vector<Clip>& clips) {
  416. for (const auto& clip : clips)
  417. lane = std::max (lane, clip.track + 1);
  418. });
  419. Clip clip;
  420. clip.kind = ClipKind::audio;
  421. clip.channel = channel;
  422. clip.track = lane;
  423. clip.length = length;
  424. song.playlist.push_back (clip);
  425. if ((int) song.playlistTracks.size() <= lane)
  426. song.playlistTracks.resize ((std::size_t) lane + 1);
  427. song.playlistTracks[(std::size_t) lane].name = name + " (audio)";
  428. }
  429. void applyChannelRender (Song& song, int channel, const std::string& wav, std::int64_t length, Report& report)
  430. {
  431. if (channel < 0 || channel >= (int) song.channels.size())
  432. return;
  433. const auto& c = song.channels[(std::size_t) channel];
  434. report.rendered.push_back ("Channel " + std::to_string (channel + 1) + " '" + c.name + "': "
  435. + (c.instrument == InstrumentKind::plugin ? "plugin '" + c.plugin.name + "'" : instrumentName (c.instrument))
  436. + " → audio clip");
  437. applyFreeze (song, channel, wav, length);
  438. }
  439. int applyInsertRender (Song& song, int track, const std::string& wav, std::int64_t length, const Options& options, Report& report)
  440. {
  441. if (track <= 0 || track >= (int) song.mixer.size())
  442. return -1;
  443. std::vector<std::string> names;
  444. auto& effects = song.mixer[(std::size_t) track].effects;
  445. for (int s = 0; s < (int) effects.size(); ++s)
  446. {
  447. auto& fx = effects[(std::size_t) s];
  448. if (! song.slotActive (fx) || effectExportable (fx, options))
  449. continue;
  450. names.push_back (effectInfo (fx.kind).name);
  451. fx.enabled = false;
  452. for (auto& a : song.automations)
  453. if ((a.target.kind == AutomationTargetKind::effectParam || a.target.kind == AutomationTargetKind::effectMix)
  454. && a.target.index == track && a.target.slot == s)
  455. a.target.kind = AutomationTargetKind::none;
  456. for (auto& p : song.patterns)
  457. for (auto& lane : p.events)
  458. if ((lane.target.kind == AutomationTargetKind::effectParam || lane.target.kind == AutomationTargetKind::effectMix)
  459. && lane.target.index == track && lane.target.slot == s)
  460. lane.target.kind = AutomationTargetKind::none;
  461. }
  462. const auto name = song.mixer[(std::size_t) track].name;
  463. const auto added = applyBounce (song, track, wav, length);
  464. if (added < 0)
  465. return -1;
  466. std::string list;
  467. for (const auto& n : names)
  468. list += (list.empty() ? "" : ", ") + n;
  469. report.rendered.push_back ("Insert " + std::to_string (track) + " '" + name + "' (" + list + ") → audio clip on insert "
  470. + std::to_string (added));
  471. return added;
  472. }
  473. // ================================================================================================================
  474. std::vector<std::uint8_t> flVst3State (const std::vector<std::uint8_t>& component, const std::vector<std::uint8_t>& controller)
  475. {
  476. // u32 1 + records {u32 id, u64 size}: 1 (64 B, first u32 = 1), 3 component, 2 controller [DATA: FL 2026's VST3
  477. // states]; record 4 (FL's parameter slots) is left out: FL then gives slot k to the plugin's k-th parameter, which is
  478. // LYNX's parameter index (REA_rodada22 §2.3)
  479. if (component.empty() && controller.empty())
  480. return {}; // (no state: the wrapper then has none and FL starts the plugin from its defaults)
  481. Records r;
  482. r.put32 (1);
  483. std::vector<std::uint8_t> head (64, 0);
  484. head[0] = 1;
  485. r.record (1, head);
  486. r.record (3, component);
  487. r.record (2, controller);
  488. return r.b;
  489. }
  490. std::vector<std::uint8_t> writeWrapper (const ForeignPlugin& p, bool instrument, const PluginRef* ref)
  491. {
  492. Records r;
  493. r.put32 (12);
  494. // 0x01: MIDI in / out ports, the pitch bend range, 8 zero bytes
  495. {
  496. const auto in = ref != nullptr ? ref->midiInPort : p.midiInPort;
  497. const auto out = ref != nullptr ? ref->midiOutPort : p.midiOutPort;
  498. const auto bend = ref != nullptr ? ref->bendRange : (p.bendRange >= 1 ? p.bendRange : 12);
  499. r.record (0x01, le32s ({ (std::uint32_t) in, (std::uint32_t) out, (std::uint32_t) bend, 0, 0 }));
  500. }
  501. // 0x02: the options [DATA: FL 2026's defaults 00 | a0 00 00 00 | 19 00 00 00 | flags 0xB4007D8C | fixed 0 | 1 | flags2 0]
  502. {
  503. std::uint32_t flags = 0xB4007D8Cu, fixed = 0, flags2 = 0;
  504. if (ref != nullptr)
  505. {
  506. auto set = [&flags] (std::uint32_t bit, bool on) { flags = on ? flags | bit : flags & ~bit; };
  507. set (0x2u, ref->fixedBuffers);
  508. set (0x4u, ref->notifyRender);
  509. set (0x1000u, ref->threaded);
  510. set (0x40000u, ref->separateProcess);
  511. set (0x20000000u, ref->allowSmartDisable);
  512. set (0x1u, ref->sendBendRange);
  513. set (0x20u, ! ref->releaseVelocity);
  514. set (0x800u, ref->sendLoopPosition);
  515. set (0x20000u, ref->modXAftertouch);
  516. set (0x02000000u, ! ref->resetOnFlush);
  517. fixed = (ref->maxSizeBuffers ? 1u : 0u) | (ref->hostMaxBuffer ? 2u : 0u);
  518. flags2 = ref->allNotesOffOnStop ? 0u : 0x1000u;
  519. }
  520. else if (p.hasWrapperOptions)
  521. {
  522. flags = p.wrapperFlags;
  523. fixed = p.fixedOptions;
  524. flags2 = p.hasWrapperFlags2 ? p.wrapperFlags2 : 0;
  525. }
  526. std::vector<std::uint8_t> o { 0x00, 0xa0, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00 };
  527. const auto tail = le32s ({ flags, fixed, 1, flags2 });
  528. o.insert (o.end(), tail.begin(), tail.end());
  529. r.record (0x02, o);
  530. }
  531. // 0x1E / 0x1F / 0x20: one input and one output bus (FL lays them out again from the plugin)
  532. r.record (0x1E, le32s ({ 1, 1, 0, 0 }));
  533. r.record (0x1F, le32s ({ 0, instrument ? 0u : 1u, 0 }));
  534. r.record (0x20, le32s ({ 0, 1, 0 }));
  535. std::uint32_t type = 0;
  536. switch (p.format)
  537. {
  538. case ForeignPlugin::Format::vst2: type = instrument ? 4 : 0; break;
  539. case ForeignPlugin::Format::vst3: type = instrument ? 8 : 7; break;
  540. case ForeignPlugin::Format::clap: type = instrument ? 12 : 11; break;
  541. default: break;
  542. }
  543. r.record (0x32, le32s ({ type, 0, 0, 0 }));
  544. if (p.format == ForeignPlugin::Format::vst2)
  545. r.record (0x33, le32s ({ p.vst2Id }));
  546. if (p.format == ForeignPlugin::Format::vst3 || (p.format == ForeignPlugin::Format::vst2 && p.hasClassId))
  547. r.record (0x34, std::vector<std::uint8_t> (p.classId.begin(), p.classId.end()));
  548. if (p.format == ForeignPlugin::Format::clap)
  549. r.record (0x3A, p.clapId);
  550. r.record (0x36, p.name);
  551. r.record (0x37, p.path);
  552. if (! p.state.empty())
  553. r.record (0x35, p.state);
  554. return r.b;
  555. }
  556. // ================================================================================================================
  557. namespace
  558. {
  559. struct Converter
  560. {
  561. Converter (const Song& s, const Options& o, Report& r) : song (s), options (o), report (r) {}
  562. const Song& song;
  563. const Options& options;
  564. Report& report;
  565. flp::Project out;
  566. int filePpq = 96;
  567. std::map<int, int> automationChannel; // song.automations index → FL channel
  568. // the FL slot (0..9) of each exported effect: (track, LYNX slot) → FL slot
  569. std::map<std::pair<int, int>, int> slotMap;
  570. std::map<std::pair<int, int>, std::string> slotPlugin; // → FL plugin name ("Fruity Wrapper" for hosted plugins)
  571. std::uint32_t ticks (std::int64_t t) const { return (std::uint32_t) std::max<std::int64_t> (0, (t * filePpq + ppq / 2) / ppq); } // (rounded)
  572. std::string path (const std::string& p) const { return options.samplePath && ! p.empty() ? options.samplePath (p) : p; }
  573. void choosePpq()
  574. {
  575. // FL's own 96 when every note and clip fits it, else LYNX's 960; other times (pattern lengths, event ticks, markers,
  576. // offsets) are rounded to the file's PPQ [FL 2026 played a 960-PPQ export of an FL demo wrongly, round 171e]
  577. if (options.ppq > 0)
  578. {
  579. filePpq = options.ppq;
  580. out.header.ppq = (std::uint16_t) filePpq;
  581. return;
  582. }
  583. bool fine = true;
  584. auto use = [&fine] (std::int64_t t) { fine = fine && t % (ppq / 96) == 0; };
  585. for (const auto& p : song.patterns)
  586. for (const auto& n : p.notes)
  587. {
  588. use (n.start);
  589. use (n.length);
  590. }
  591. song.forEachClipList ([&] (const std::vector<Clip>& clips) {
  592. for (const auto& c : clips)
  593. {
  594. if (c.muted)
  595. continue; // (left out)
  596. use (c.start);
  597. // (an audio clip's length goes unstretched, as playlistItem writes it)
  598. use (c.kind == ClipKind::audio && c.stretch > 0.0 && c.stretch != 1.0 ? (std::int64_t) std::llround ((double) c.length / c.stretch)
  599. : c.length);
  600. }
  601. });
  602. filePpq = fine ? 96 : ppq;
  603. out.header.ppq = (std::uint16_t) filePpq;
  604. }
  605. void globals()
  606. {
  607. out.version = options.write.version;
  608. out.versionNumber = flp::parseVersionNumber (out.version);
  609. out.flagsA9 = 15;
  610. out.tempo = song.bpm;
  611. out.beatsPerBar = song.beatsPerBar;
  612. out.swing = std::clamp (iround (song.swing * 128.0), 0, 128);
  613. out.mainPitch = iround (song.masterPitch);
  614. out.currentPattern = std::clamp (song.currentPattern, 0, std::max (0, (int) song.patterns.size() - 1)) + 1;
  615. out.songMode = song.mode == PlayMode::song ? 1 : 0;
  616. out.showInfo = song.info.showOnOpen;
  617. out.currentArrangement = std::max (0, song.currentArrangement);
  618. out.playTruncatedNotes = song.playTruncatedNotes;
  619. out.autoPdc = song.autoPdc;
  620. out.compensateAutomations = song.compensateAutomations;
  621. out.timeSignatureMode = song.timeSignatureMode;
  622. out.fastDeclick = song.fastDeclick;
  623. out.performanceMode = song.performanceMode;
  624. out.panLaw = song.panTriangular ? 2 : 0;
  625. out.autoCrossfades = song.autoCrossfades;
  626. out.dataFolder = song.dataFolder;
  627. out.hasScaleHighlight = true;
  628. out.scaleHighlight = song.scaleHighlight.scale;
  629. out.scaleRoot = song.scaleHighlight.root;
  630. out.title = song.info.title;
  631. out.artist = song.info.author;
  632. out.genre = song.info.genre;
  633. out.url = song.info.url;
  634. out.comments = song.info.comments;
  635. // (FL's TDateTime: days since 1899-12-30; the Unix epoch is day 25569)
  636. if (song.info.created > 0.0)
  637. out.createdDays = song.info.created / 86400.0 + 25569.0;
  638. out.workDays = song.info.workSeconds / 86400.0;
  639. out.filterGroups = song.channelGroups;
  640. if (out.filterGroups.empty())
  641. out.filterGroups.push_back ("Unsorted");
  642. if (song.masterPitch != 0.0f)
  643. report.exact.push_back ("Main pitch");
  644. report.exact.push_back ("Tempo, time signature, swing, project info");
  645. }
  646. // ---- channels ----
  647. void envelopesFromAdsr (flp::Channel& c, const ChannelDef& def)
  648. {
  649. const auto& s = def.sampler;
  650. for (int k = 0; k < 5; ++k)
  651. {
  652. auto& e = c.envelopes[(std::size_t) k];
  653. e = {};
  654. e.present = true;
  655. e.flags = k == 1 ? 4 : 0;
  656. e.sustain = 50;
  657. }
  658. // the volume envelope: on when LYNX shapes the note (an untouched sampler plays the whole sample)
  659. const auto shaped = s.attack > 0.0f || s.decay > 0.0f || s.sustain < 1.0f || s.release > 0.0f;
  660. auto& v = c.envelopes[1];
  661. v.enabled = shaped;
  662. v.delay = 100;
  663. v.attack = envelopeTimeValue (s.attack);
  664. v.hold = 100;
  665. v.decay = envelopeTimeValue (s.decay);
  666. v.sustain = std::clamp (iround (s.sustain * 128.0), 0, 128);
  667. v.release = envelopeTimeValue (s.release);
  668. auto mod = [&] (flp::Channel::Envelope& e, const ModEnvelope& m, int amount) {
  669. if (m.amount == 0.0f)
  670. return;
  671. e.enabled = true;
  672. e.attack = envelopeTimeValue (m.attack);
  673. e.hold = envelopeTimeValue (m.hold);
  674. e.decay = envelopeTimeValue (m.decay);
  675. e.sustain = std::clamp (iround (m.sustain * 128.0), 0, 128);
  676. e.release = envelopeTimeValue (m.release);
  677. e.amount = amount;
  678. };
  679. mod (c.envelopes[4], s.pitchEnv, std::clamp (iround (s.pitchEnv.amount * 100.0), -2400, 2400));
  680. if (s.filterEnv.amount != 0.0f)
  681. {
  682. // the amount moves Mod X by amount/128: the octaves at the channel's cutoff
  683. const auto x = c.modX / 256.0;
  684. const auto from = filterHz (c.filterType, x);
  685. const auto target = std::clamp (from * std::pow (2.0, (double) s.filterEnv.amount), 20.0, 20000.0);
  686. const auto toX = invert ([&] (double y) { return filterHz (c.filterType, y); }, target);
  687. mod (c.envelopes[2], s.filterEnv, std::clamp (iround ((toX - x) * 128.0), -128, 128));
  688. }
  689. auto lfo = [&] (flp::Channel::Envelope& e, const ChannelLfo& l, int amount) {
  690. if (l.amount == 0.0f)
  691. return;
  692. e.lfoAmount = amount;
  693. const auto scale = l.sync ? 2.0 : 1.0;
  694. e.lfoSpeed = envelopeTimeValue (l.period / scale);
  695. e.lfoDelay = envelopeTimeValue (l.delay / scale);
  696. e.lfoAttack = envelopeTimeValue (l.attack / scale);
  697. e.lfoShape = std::clamp (l.shape, 0, 2);
  698. e.flags |= (l.sync ? 2 : 0) | (l.global ? 0x20 : 0);
  699. };
  700. lfo (c.envelopes[0], s.lfo[lfoPan], std::clamp (iround (s.lfo[lfoPan].amount * 64.0), -64, 64));
  701. lfo (c.envelopes[1], s.lfo[lfoVolume], std::clamp (iround (s.lfo[lfoVolume].amount * 128.0), -128, 128));
  702. lfo (c.envelopes[4], s.lfo[lfoPitch], std::clamp (iround (s.lfo[lfoPitch].amount * 100.0), -2400, 2400));
  703. c.envelopeCount = 5;
  704. }
  705. void filterFrom (flp::Channel& c, const SamplerSettings& s)
  706. {
  707. // LYNX's mode (0 LP, 1 BP, 2 HP, 3 BS) → FL's type (1 LP, 2 BP, 3 HP, 4 BS: the biquads)
  708. static constexpr int types[] = { 1, 2, 3, 4 };
  709. const auto open = s.cutoff >= 19999.0f && s.resonance <= 0.0f && s.filterType == 0;
  710. c.filterType = open ? 0 : types[std::clamp (s.filterType, 0, 3)];
  711. c.modX = open ? 256 : std::clamp (iround (256.0 * invert ([&] (double y) { return filterHz (c.filterType, y); }, s.cutoff)), 0, 256);
  712. // the biquads' Q = (51^(0.625·r) − 1)·0.4 + 0.1 and LYNX's resonance = (2 − 1/Q)/1.9
  713. const auto q = 1.0 / std::max (0.05, 2.0 - 1.9 * (double) s.resonance);
  714. const auto r = q <= 0.1 ? 0.0 : std::log ((q - 0.1) / 0.4 + 1.0) / std::log (51.0) / 0.625;
  715. c.modY = open ? 0 : std::clamp (iround (r * 256.0), 0, 256);
  716. }
  717. flp::Channel channel (const ChannelDef& def, int index)
  718. {
  719. flp::Channel c;
  720. c.index = index;
  721. c.name = def.name;
  722. c.colour = def.colour != 0 ? rgb (def.colour) : 0;
  723. c.icon = def.icon;
  724. c.enabled = ! def.muted;
  725. c.soloLock = def.soloLock;
  726. c.ghostShown = ! def.ghostHidden;
  727. c.filterGroup = def.group >= 0 && def.group < (int) out.filterGroups.size() ? def.group : 0;
  728. c.mixerTrack = std::clamp (def.mixerTrack, 0, std::max (0, (int) song.mixer.size() - 1));
  729. // levels: the same curves (channelGain both sides); the Sampler's Gain has no FL knob, it goes into the volume
  730. auto volume = def.volume;
  731. if (samplerLike (def.instrument) && def.sampler.gainDb != 0.0f)
  732. {
  733. const auto g = channelGain (volume) * std::pow (10.0f, def.sampler.gainDb / 20.0f);
  734. volume = (float) std::clamp (std::log (10.0 * g + 1.0) / std::log (11.0), 0.0, 1.0);
  735. if (g > 1.0f)
  736. report.notes.push_back (channelLabel (def, index) + ": the Sampler's Gain is above FL's channel volume range (capped at 100%)");
  737. }
  738. c.hasLevels = true;
  739. c.volume = std::clamp (iround (volume * 12800.0), 0, 12800);
  740. c.pan = std::clamp (iround (6400.0 + def.pan * 6400.0), 0, 12800);
  741. const auto root = std::clamp (def.misc.rootNote, 0, 127);
  742. const auto cents = iround (((double) def.sampler.pitch - (60.0 - root)) * 100.0);
  743. c.pitchCents = cents;
  744. c.rootNote = root;
  745. c.fineTune = iround (def.misc.fineTune);
  746. c.pitchRange = std::clamp (std::max (def.misc.pitchRange, (std::abs (cents) + 99) / 100), 0, 48);
  747. c.swingMix = std::clamp (iround (def.swingMix * 128.0), 0, 128);
  748. c.cutGroup = def.cutGroup;
  749. c.cutBy = def.cutBy;
  750. c.maxVoices = std::clamp (def.maxPolyphony, 0, 128);
  751. c.monoFlag = def.misc.mono;
  752. c.portaFlag = def.misc.porta;
  753. c.slideTime = slideTimeValue (def.misc.portaBeats);
  754. // Misc: time, echo, tracking, the root note keyboard, the arpeggiator (REA round 146b)
  755. const auto& m = def.misc;
  756. c.timeShift = m.shiftBeats > 0.0f ? channelmiscTime (m.shiftBeats) : 0;
  757. c.timeGate = m.gateBeats > 0.0f ? std::min (1445, channelmiscTime (m.gateBeats)) : 1447;
  758. c.fullPorta = m.fullPorta;
  759. c.echoFeedback = std::clamp (iround (m.echo.feedback * 12800.0), 0, 25600);
  760. c.echoPan = std::clamp (iround (6400.0 + m.echo.pan * 6400.0), 0, 12800);
  761. c.echoPitch = iround (m.echo.pitch);
  762. c.echoes = m.echo.echoes;
  763. c.echoTime = std::max (1, iround (m.echo.timeBeats * 192.0));
  764. c.echoModX = std::clamp (iround (128.0 + m.echo.modX * 128.0), 0, 256);
  765. c.echoModY = std::clamp (iround (128.0 + m.echo.modY * 128.0), 0, 256);
  766. c.delayFlags = (m.echo.pingPong ? 2 : 0) | (m.echo.fat ? 4 : 0);
  767. for (int k = 0; k < 2; ++k)
  768. {
  769. const auto& from = k == 0 ? m.velocity : m.key;
  770. auto& t = c.tracking[(std::size_t) k];
  771. t.present = true;
  772. t.mid = from.mid;
  773. t.pan = iround (from.pan * 64.0);
  774. t.modX = iround (from.modX * 256.0);
  775. t.modY = iround (from.modY * 256.0);
  776. }
  777. c.trackingCount = 2;
  778. c.mainPitch = m.mainPitch;
  779. c.addToKey = m.addToKey;
  780. // FL's directions 1 up, 2 down, 3 bounce, 4 sticky, 5 random; LYNX: 4 random, 5 sticky
  781. static constexpr int toFl[] = { 0, 1, 2, 3, 5, 4 };
  782. const auto& a = def.arp;
  783. c.arpDirection = toFl[std::clamp (a.direction, 0, 5)];
  784. c.arpRange = std::clamp (a.range, 1, 4);
  785. c.arpTime = channelmiscTime (a.stepBeats);
  786. c.arpGate = std::clamp (iround (a.gate * 48.0), 1, 128);
  787. c.arpSlide = a.slide;
  788. c.arpRepeat = a.octaveRepeat;
  789. c.arpChord = ! a.chordSustain ? -2 : a.chord == std::vector<int> { 0 } ? 0 : -1;
  790. if (a.enabled() && ! a.chord.empty() && a.chord != std::vector<int> { 0 })
  791. report.notes.push_back (channelLabel (def, index) + ": the arpeggiator's chord is written as Auto");
  792. if (def.hasKeyRegion())
  793. {
  794. c.keyRegionLow = def.keyLow;
  795. c.keyRegionHigh = def.keyHigh;
  796. }
  797. // the channel filter and articulators
  798. if (def.sampler.flChannel.size() >= 88)
  799. {
  800. // FL's own records as the import stored them (REA_rodada76)
  801. for (int k = 0; k < 5; ++k)
  802. {
  803. auto& e = c.envelopes[(std::size_t) k];
  804. e.present = true;
  805. e.rawSize = 68;
  806. std::memcpy (e.raw.data(), def.sampler.flChannel.data() + 17 * k, 68);
  807. }
  808. c.envelopeCount = 5;
  809. c.modX = def.sampler.flChannel[85];
  810. c.modY = def.sampler.flChannel[86];
  811. c.filterType = def.sampler.flChannel[87];
  812. }
  813. else
  814. {
  815. filterFrom (c, def.sampler);
  816. envelopesFromAdsr (c, def);
  817. if (def.sampler.flVolumeEnvelope.size() >= 17)
  818. {
  819. auto& e = c.envelopes[1];
  820. e.rawSize = 68;
  821. std::memcpy (e.raw.data(), def.sampler.flVolumeEnvelope.data(), 68);
  822. }
  823. }
  824. // the generator
  825. if (def.instrument == InstrumentKind::layer)
  826. {
  827. c.type = flp::ChannelType::layer;
  828. c.layerChildren = def.layer.children;
  829. c.layerFlags = (def.layer.random ? 1 : 0) | (def.layer.crossfade ? 2 : 0) | (def.layer.sequential ? 4 : 0);
  830. c.layerFade = std::clamp (iround (def.layer.fade * 256.0), 0, 256);
  831. report.exact.push_back (channelLabel (def, index) + ": Layer");
  832. }
  833. else if (samplerLike (def.instrument) && ! originMatches (def))
  834. {
  835. c.type = def.instrument == InstrumentKind::audioClip ? flp::ChannelType::audioClip : flp::ChannelType::sampler;
  836. sampler (c, def);
  837. report.exact.push_back (channelLabel (def, index) + (def.instrument == InstrumentKind::audioClip ? ": audio clip" : ": Sampler"));
  838. }
  839. else if (def.instrument == InstrumentKind::plugin || def.plugin.foreign.format != ForeignPlugin::Format::none)
  840. {
  841. // (also a stand-in whose FL plugin is not on this PC: its wrapper goes back as FL wrote it)
  842. c.type = flp::ChannelType::instrument;
  843. if (const auto record = hosted (def.plugin, true))
  844. {
  845. c.pluginName = "Fruity Wrapper";
  846. c.pluginState = writeWrapper (*record, true, def.plugin.foreign.format == ForeignPlugin::Format::none ? &def.plugin : nullptr);
  847. report.exact.push_back (channelLabel (def, index) + ": " + record->name + " (Fruity Wrapper)");
  848. }
  849. else
  850. report.dropped.push_back (channelLabel (def, index) + ": plugin '" + def.plugin.name + "' (not found)");
  851. }
  852. else if (const auto name = flGeneratorName (def); ! name.empty())
  853. {
  854. c.type = flp::ChannelType::instrument;
  855. c.pluginName = name;
  856. c.pluginState = originMatches (def) && ! def.flOrigin.state.empty() ? def.flOrigin.state : def.pluginState;
  857. if (c.pluginState.empty() && def.instrument == InstrumentKind::threeosc)
  858. c.pluginState = defaultThreeOscState();
  859. const auto* g = generatorFor (def.instrument);
  860. if ((g != nullptr && g->channelSample) || samplerLike (def.instrument))
  861. c.samplePath = path (def.samplePath);
  862. if (samplerLike (def.instrument))
  863. sampler (c, def);
  864. report.exact.push_back (channelLabel (def, index) + ": " + name);
  865. }
  866. else
  867. {
  868. // left for the report (option A renders these before the conversion)
  869. c.type = flp::ChannelType::sampler;
  870. report.dropped.push_back (channelLabel (def, index) + ": " + instrumentName (def.instrument) + " (no FL equivalent)");
  871. }
  872. return c;
  873. }
  874. static int channelmiscTime (double beats)
  875. {
  876. // channelmisc::flTimeKnobValue (ChannelMiscFx.h)
  877. if (beats <= 0.0)
  878. return 0;
  879. return (int) std::lround (1024.0 * std::log (beats * 192.0 * 26.0 / 48.0 + 1.0) / std::log (27.0));
  880. }
  881. void sampler (flp::Channel& c, const ChannelDef& def)
  882. {
  883. const auto& s = def.sampler;
  884. c.samplePath = path (def.samplePath);
  885. const auto& p = s.precompute;
  886. c.fxFlags = (p.fadeStereo ? 1 : 0) | (s.reverse ? 2 : 0) | (p.clip ? 4 : 0) | (p.swapStereo ? 0x100 : 0);
  887. c.fadeIn = p.fadeIn;
  888. c.fadeOut = p.fadeOut;
  889. c.removeDc = p.removeDc;
  890. c.normalize = p.normalize;
  891. c.reversePolarity = p.reversePolarity;
  892. c.crossfade = p.crossfade;
  893. c.trim = p.trim;
  894. c.pingPong = p.pingPong;
  895. c.boost = p.boost;
  896. c.eq = p.eq;
  897. c.ringMix = p.ringMix;
  898. c.ringFreq = p.ringFreq;
  899. c.stereoDelay = p.stereoDelay;
  900. c.cutoff = p.cutoff;
  901. c.resonance = p.resonance;
  902. c.reverb = p.reverb;
  903. c.reverbType = p.reverbType;
  904. c.pogo = p.pogo;
  905. c.declickMode = s.declickMode;
  906. c.sampleFlags = 2 | (s.useLoopPoints ? 8 : 0);
  907. // the region: FL's end is a fraction of what follows the start (REA_rodada167h §2)
  908. const auto start = std::clamp ((double) s.regionStart, 0.0, 1.0);
  909. const auto end = std::clamp ((double) s.regionEnd, start, 1.0);
  910. c.sampleStart = start;
  911. c.sampleEnd = start < 1.0 ? (end - start) / (1.0 - start) : 1.0;
  912. c.startOffset = std::clamp ((double) s.startOffset, 0.0, 1.0);
  913. // the time-stretch: the whole sample lasts TIME/192 beats (MUL 0)
  914. if (s.stretchBeats > 0.0f)
  915. {
  916. c.stretchTime = s.stretchBeats * 192.0f;
  917. c.stretchMul = 0;
  918. c.stretchMode = ! s.keepPitch ? 0 : s.stretchMethod == StretchMethod::mono ? 2 : s.stretchMethod == StretchMethod::transients ? 7 : -2;
  919. }
  920. if (s.cut && c.cutGroup == 0 && c.cutBy == 0)
  921. c.cutGroup = c.cutBy = freeCutGroup++; // "cut itself"
  922. }
  923. int freeCutGroup = 1;
  924. std::optional<ForeignPlugin> hosted (const PluginRef& ref, bool instrument) const
  925. {
  926. if (ref.foreign.format != ForeignPlugin::Format::none)
  927. return ref.foreign; // still the FL original, byte for byte
  928. if (options.pluginRecord)
  929. return options.pluginRecord (ref, instrument);
  930. return std::nullopt;
  931. }
  932. void channels()
  933. {
  934. for (const auto& c : song.channels)
  935. freeCutGroup = std::max ({ freeCutGroup, c.cutGroup + 1, c.cutBy + 1 });
  936. for (int i = 0; i < (int) song.channels.size(); ++i)
  937. out.channels.push_back (channel (song.channels[(std::size_t) i], i));
  938. }
  939. // ---- automation targets ----
  940. std::optional<flp::ControlId> controlFor (const AutomationTarget& t, std::function<float (float)>* valueMap = nullptr) const
  941. {
  942. flp::ControlId id;
  943. switch (t.kind)
  944. {
  945. case AutomationTargetKind::tempo:
  946. id.raw = flp::ControlId::tempo;
  947. // (LYNX's tempo target is FL's whole range, 10…522 BPM: the clip's range below is the whole range too)
  948. return id;
  949. case AutomationTargetKind::channelVolume:
  950. case AutomationTargetKind::channelPan:
  951. if (t.index < 0 || t.index >= (int) song.channels.size())
  952. return std::nullopt;
  953. id.raw = ((std::uint32_t) t.index << 16) | (t.kind == AutomationTargetKind::channelPan ? 1u : 0u);
  954. return id;
  955. case AutomationTargetKind::channelParam:
  956. if (t.index < 0 || t.index >= (int) song.channels.size() || song.channels[(std::size_t) t.index].instrument != InstrumentKind::plugin
  957. || out.channels[(std::size_t) t.index].pluginName != "Fruity Wrapper")
  958. return std::nullopt;
  959. id.raw = ((std::uint32_t) t.index << 16) | (std::uint32_t) (flp::ControlId::pluginParamBase + t.param);
  960. return id;
  961. case AutomationTargetKind::mixerVolume:
  962. id.raw = mixerId (t.index, 0, flp::ControlId::mixerVolume);
  963. return id;
  964. case AutomationTargetKind::mixerPan:
  965. id.raw = mixerId (t.index, 0, flp::ControlId::mixerPan);
  966. return id;
  967. case AutomationTargetKind::mixerSend:
  968. id.raw = mixerId (t.index, 0, flp::ControlId::mixerSendBase + t.slot);
  969. return id;
  970. case AutomationTargetKind::effectMix:
  971. case AutomationTargetKind::effectParam:
  972. {
  973. const auto found = slotMap.find ({ t.index, t.slot });
  974. if (found == slotMap.end())
  975. return std::nullopt;
  976. if (t.kind == AutomationTargetKind::effectMix)
  977. {
  978. id.raw = mixerId (t.index, found->second, 0x1F01);
  979. return id;
  980. }
  981. const auto& plugin = slotPlugin.at ({ t.index, t.slot });
  982. auto param = t.param;
  983. if (plugin != "Fruity Wrapper")
  984. {
  985. // FL's parameter whose map lands on this LYNX parameter (FlEffects' effectParamFromFl), and the
  986. // inverse of its value conversion
  987. param = -1;
  988. for (int k = 0; k < 512 && param < 0; ++k)
  989. if (const auto map = effectParamFromFl (plugin, k); map && map->param == t.param)
  990. {
  991. param = k;
  992. if (valueMap != nullptr && map->convert)
  993. {
  994. const auto convert = map->convert;
  995. const auto increasing = convert (1.0f) >= convert (0.0f);
  996. *valueMap = [convert, increasing] (float v) {
  997. return (float) invert ([&] (double y) { return (double) convert ((float) y); }, v, increasing);
  998. };
  999. }
  1000. }
  1001. if (param < 0)
  1002. return std::nullopt;
  1003. }
  1004. id.raw = mixerId (t.index, found->second, flp::ControlId::pluginParamBase + param);
  1005. return id;
  1006. }
  1007. default: return std::nullopt;
  1008. }
  1009. }
  1010. // the inserts whose effects take insert `source` as a side-chain input (LYNX keeps the source, FL a level-0 route)
  1011. std::vector<int> sidechainTargets (int source) const
  1012. {
  1013. std::vector<int> out;
  1014. for (int u = 1; u < (int) song.mixer.size(); ++u)
  1015. if (u != source)
  1016. for (const auto& fx : song.mixer[(std::size_t) u].effects)
  1017. if ((fx.sidechain == source || fx.sidechain2 == source) && std::find (out.begin(), out.end(), u) == out.end())
  1018. out.push_back (u);
  1019. return out;
  1020. }
  1021. // ---- patterns ----
  1022. bool playsSample (int channel) const
  1023. {
  1024. for (const auto& c : out.channels)
  1025. if (c.index == channel)
  1026. return c.type == flp::ChannelType::sampler || c.type == flp::ChannelType::audioClip;
  1027. return false;
  1028. }
  1029. void patterns()
  1030. {
  1031. for (int i = 0; i < (int) song.patterns.size(); ++i)
  1032. {
  1033. const auto& src = song.patterns[(std::size_t) i];
  1034. flp::Pattern p;
  1035. p.index = i + 1;
  1036. p.name = src.name;
  1037. if (src.colour != 0)
  1038. p.colour = rgb (src.colour);
  1039. p.fixedLength = src.lengthTicks > 0 ? ticks (src.lengthTicks) : 0;
  1040. p.loopOn = src.loopOn;
  1041. p.loopMode = (int) src.loopMode;
  1042. for (const auto& l : src.channelLoops)
  1043. p.channelLoops.push_back ({ l.channel, l.setting });
  1044. for (const auto& m : src.markers)
  1045. p.markers.push_back (marker (m));
  1046. for (const auto& n : src.notes)
  1047. {
  1048. if (n.channel < 0 || n.channel >= (int) song.channels.size())
  1049. continue;
  1050. flp::Note f;
  1051. f.position = ticks (n.start);
  1052. // a step (one step long, on the step grid): FL's step note, which the Channel Rack shows as a step.
  1053. // Only on a channel that plays a sample: FL holds a step note on a generator (3x Osc, a plugin)
  1054. // until something cuts it, so the voices pile up (FL render, round 171e)
  1055. const auto step = n.length == ticksPerStep && n.start % ticksPerStep == 0 && playsSample (n.channel);
  1056. f.length = step ? 0 : std::max<std::uint32_t> (1, ticks (n.length));
  1057. f.channel = (std::uint16_t) n.channel;
  1058. f.key = (std::uint16_t) std::clamp (n.key, 0, 131);
  1059. f.velocity = (std::uint8_t) std::clamp (iround (n.velocity * 128.0), 0, 128);
  1060. f.pan = (std::uint8_t) std::clamp (iround (64.0 + n.pan * 64.0), 0, 128);
  1061. f.finePitch = (std::uint8_t) std::clamp (iround (120.0 + n.finePitch), 0, 240);
  1062. f.release = (std::uint8_t) std::clamp (iround (n.release * 128.0), 0, 128);
  1063. f.modX = (std::uint8_t) std::clamp (iround (n.modX * 256.0), 0, 255);
  1064. f.modY = (std::uint8_t) std::clamp (iround (n.modY * 256.0), 0, 255);
  1065. f.flags = (std::uint16_t) (0x4000 | (n.slide ? 8 : 0));
  1066. f.extra = (std::uint8_t) ((n.colour & 0x0F) | (n.porta ? 0x10 : 0) | (n.muted ? 0x20 : 0));
  1067. f.group = (std::uint16_t) std::max (0, n.group);
  1068. p.notes.push_back (f);
  1069. }
  1070. std::stable_sort (p.notes.begin(), p.notes.end(), [] (const flp::Note& a, const flp::Note& b) { return a.position < b.position; });
  1071. for (const auto& lane : src.events)
  1072. {
  1073. std::function<float (float)> map;
  1074. const auto id = controlFor (lane.target, &map);
  1075. if (! id)
  1076. {
  1077. if (lane.target.kind != AutomationTargetKind::none)
  1078. report.dropped.push_back ("Pattern '" + src.name + "': an event lane (its target has no FL equivalent)");
  1079. continue;
  1080. }
  1081. for (const auto& e : lane.events)
  1082. p.controlEvents.push_back ({ ticks (e.tick), *id, rawValue (lane.target, map ? map (e.value) : e.value) });
  1083. }
  1084. out.patterns.push_back (std::move (p));
  1085. }
  1086. report.exact.push_back (std::to_string (song.patterns.size()) + " patterns (notes with every property, names, colours)");
  1087. }
  1088. flp::TimeMarker marker (const Marker& m) const
  1089. {
  1090. flp::TimeMarker t;
  1091. t.position = ticks (m.tick);
  1092. t.name = m.name;
  1093. if (m.isSignature())
  1094. {
  1095. t.type = 8;
  1096. t.numerator = m.numerator;
  1097. t.denominator = m.denominator;
  1098. }
  1099. else
  1100. t.type = m.action;
  1101. return t;
  1102. }
  1103. // ---- automation clips: FL channels after the song's ----
  1104. void automations()
  1105. {
  1106. for (int a = 0; a < (int) song.automations.size(); ++a)
  1107. {
  1108. const auto& src = song.automations[(std::size_t) a];
  1109. if (src.isLive())
  1110. {
  1111. report.dropped.push_back ("Automation '" + src.name + "': a live controller link");
  1112. continue;
  1113. }
  1114. std::function<float (float)> map;
  1115. const auto id = controlFor (src.target, &map);
  1116. if (! id && src.target.kind != AutomationTargetKind::none)
  1117. {
  1118. report.dropped.push_back ("Automation '" + src.name + "': its target has no FL equivalent");
  1119. continue;
  1120. }
  1121. // (no target at all: FL's own unlinked automation clip, kept as one)
  1122. flp::Channel c;
  1123. c.index = (int) out.channels.size();
  1124. c.type = flp::ChannelType::automationClip;
  1125. c.name = src.name;
  1126. // an automation clip's channel levels are its range: pan = minimum, volume = maximum (of 12800, in the
  1127. // target's whole range) [DATA: FL's tempo clips keep 1250…4250 = 60…180 BPM; FL 2026 played a clip written
  1128. // with a channel's default levels over 6400…10000: round 171e, FL render]. Always the whole range here.
  1129. c.hasLevels = true;
  1130. c.pan = 0;
  1131. c.volume = 12800;
  1132. for (std::size_t i = 0; i < src.points.size(); ++i)
  1133. {
  1134. const auto& pt = src.points[i];
  1135. flp::AutomationPoint fp;
  1136. fp.position = (double) pt.tick / ppq;
  1137. fp.value = std::clamp ((double) (map ? map (pt.value) : pt.value), 0.0, 1.0);
  1138. // FL's curve sits on the segment ending at the point (FlpImport: previous.tension = −p.tension)
  1139. fp.tension = i > 0 ? -src.points[i - 1].tension : 0.0f;
  1140. c.automation.push_back (fp);
  1141. }
  1142. if (c.automation.empty())
  1143. c.automation.push_back ({ 0.0, (double) (map ? map (song.targetValue (src.target)) : song.targetValue (src.target)), 0.0f });
  1144. // FL's clip LFO (round 177b): the fields back as they were read; the level carries the clip's range (FL scales
  1145. // the LFO by its channel range, written whole here)
  1146. if (const auto& lfo = src.lfo; ! lfo.isDefault())
  1147. {
  1148. auto& f = c.automationLfo;
  1149. f.present = true;
  1150. f.enabled = lfo.on ? -1 : 0;
  1151. f.level = std::abs (lfo.range - 1.0f) < 1.0e-6f ? lfo.level : (int) std::lround (lfo.level * lfo.range);
  1152. f.mode = lfo.add ? 1 : 0;
  1153. f.flags = lfo.flags;
  1154. f.speed = lfo.speed;
  1155. f.tension = lfo.tension;
  1156. f.skew = lfo.skew;
  1157. f.pulseWidth = lfo.pulseWidth;
  1158. f.phase = lfo.phase;
  1159. if (lfo.fl.present)
  1160. {
  1161. f.mainFlags = lfo.fl.mainFlags;
  1162. f.mainEnabled = lfo.fl.mainEnabled;
  1163. f.mainLoop = lfo.fl.mainLoop;
  1164. f.adsr = lfo.fl.adsr;
  1165. f.lfoLoop = lfo.fl.lfoLoop;
  1166. }
  1167. f.points.clear();
  1168. for (std::size_t i = 0; i < lfo.amp.size(); ++i)
  1169. f.points.push_back ({ (double) lfo.amp[i].tick / ppq, (double) std::clamp (lfo.amp[i].value, 0.0f, 1.0f),
  1170. i > 0 ? -lfo.amp[i - 1].tension : 0.0f, 0 });
  1171. if (lfo.amp == lfo.fl.rawAmp && lfo.fl.rawPoints.size() == lfo.amp.size() * 24)
  1172. f.rawPoints = lfo.fl.rawPoints; // unchanged since the import: its records byte for byte
  1173. }
  1174. automationChannel[a] = c.index;
  1175. if (id)
  1176. out.automationLinks.push_back ({ c.index, *id });
  1177. out.channels.push_back (std::move (c));
  1178. }
  1179. if (! automationChannel.empty())
  1180. report.exact.push_back (std::to_string (automationChannel.size()) + " automation clips (points, curves, links)");
  1181. for (const auto& v : song.initialValues)
  1182. if (const auto id = controlFor (v.target))
  1183. out.initControls.push_back ({ 0, *id, rawValue (v.target, v.value) });
  1184. if (! song.midiLinks.empty())
  1185. report.notes.push_back ("MIDI controller links stay in LYNX (FL keeps them per machine)");
  1186. }
  1187. // ---- the Playlist ----
  1188. void arrangements()
  1189. {
  1190. for (int i = 0; i < (int) song.arrangements.size(); ++i)
  1191. {
  1192. const auto current = i == song.currentArrangement;
  1193. const auto& arrangement = song.arrangements[(std::size_t) i];
  1194. const auto& clips = current ? song.playlist : arrangement.clips;
  1195. flp::Arrangement a;
  1196. a.index = i;
  1197. a.name = arrangement.name;
  1198. for (const auto& m : current ? song.markers() : arrangement.markers)
  1199. a.markers.push_back (marker (m));
  1200. int muted = 0;
  1201. for (const auto& clip : clips)
  1202. {
  1203. if (clip.muted)
  1204. {
  1205. ++muted; // (FL's clip mute is not in the model: a muted clip is left out, as it is heard)
  1206. continue;
  1207. }
  1208. if (auto item = playlistItem (clip))
  1209. a.items.push_back (*item);
  1210. }
  1211. if (muted > 0)
  1212. report.notes.push_back ("Arrangement '" + a.name + "': " + std::to_string (muted) + " muted clip(s) left out");
  1213. std::stable_sort (a.items.begin(), a.items.end(), [] (const flp::PlaylistItem& x, const flp::PlaylistItem& y) { return x.position < y.position; });
  1214. for (int t = 0; t < (int) song.playlistTracks.size() && t < 500; ++t)
  1215. a.tracks.push_back (trackInfo (song.playlistTracks[(std::size_t) t], t));
  1216. out.arrangements.push_back (std::move (a));
  1217. }
  1218. report.exact.push_back ("Playlist: " + std::to_string (song.arrangements.size()) + " arrangement(s), tracks, markers");
  1219. }
  1220. std::optional<flp::PlaylistItem> playlistItem (const Clip& clip) const
  1221. {
  1222. flp::PlaylistItem item;
  1223. item.track = std::clamp (clip.track, 0, 499);
  1224. item.position = ticks (clip.start);
  1225. item.length = std::max<std::uint32_t> (1, ticks (clip.length));
  1226. switch (clip.kind)
  1227. {
  1228. case ClipKind::pattern:
  1229. if (clip.pattern < 0 || clip.pattern >= (int) song.patterns.size())
  1230. return std::nullopt;
  1231. item.kind = flp::PlaylistItem::Kind::pattern;
  1232. item.index = clip.pattern + 1;
  1233. item.gain = 0.0f;
  1234. if (clip.offset > 0)
  1235. {
  1236. item.patternStartTick = (std::int32_t) ticks (clip.offset);
  1237. item.patternEndTick = (std::int32_t) ticks (clip.offset + clip.length);
  1238. }
  1239. return item;
  1240. case ClipKind::audio:
  1241. {
  1242. if (clip.channel < 0 || clip.channel >= (int) song.channels.size())
  1243. return std::nullopt;
  1244. item.kind = flp::PlaylistItem::Kind::channelClip;
  1245. item.index = clip.channel;
  1246. const auto stretch = clip.stretch > 0.0 ? clip.stretch : 1.0;
  1247. item.stretch = stretch;
  1248. item.length = std::max<std::uint32_t> (1, ticks ((std::int64_t) std::llround ((double) clip.length / stretch)));
  1249. // start / end in milliseconds (of the sample: a stretched channel's factor, REA_rodada110 §1)
  1250. const auto msPerTick = 60000.0 / song.bpm / ppq;
  1251. auto factor = 1.0;
  1252. const auto& ch = song.channels[(std::size_t) clip.channel];
  1253. if (ch.sampler.stretchBeats > 0.0f && options.sampleSeconds)
  1254. if (const auto seconds = options.sampleSeconds (ch.samplePath); seconds > 0.0)
  1255. factor = seconds * 1000.0 / (ch.sampler.stretchBeats * 60000.0 / song.bpm);
  1256. const auto offset = ((double) clip.offset + clip.offsetFraction) / stretch;
  1257. item.startOffset = (float) (offset * msPerTick * factor);
  1258. item.endOffset = (float) ((offset + (double) clip.length / stretch) * msPerTick * factor);
  1259. item.fadeInMs = (float) ((double) clip.fadeIn * msPerTick);
  1260. item.fadeOutMs = (float) ((double) clip.fadeOut * msPerTick);
  1261. item.gain = clip.gain;
  1262. item.pitch = clip.pitch;
  1263. item.reversed = clip.reversed;
  1264. return item;
  1265. }
  1266. case ClipKind::automation:
  1267. {
  1268. const auto found = automationChannel.find (clip.automation);
  1269. if (found == automationChannel.end())
  1270. return std::nullopt;
  1271. item.kind = flp::PlaylistItem::Kind::channelClip;
  1272. item.index = found->second;
  1273. item.gain = 1.0f;
  1274. // the trim in beats (−1 = none)
  1275. if (clip.offset > 0)
  1276. {
  1277. item.startOffset = (float) ((double) clip.offset / ppq);
  1278. item.endOffset = (float) ((double) (clip.offset + clip.length) / ppq);
  1279. }
  1280. else
  1281. item.startOffset = item.endOffset = -1.0f;
  1282. return item;
  1283. }
  1284. }
  1285. return std::nullopt;
  1286. }
  1287. static flp::PlaylistTrackInfo trackInfo (const PlaylistTrack& t, int index)
  1288. {
  1289. flp::PlaylistTrackInfo info;
  1290. info.index = index;
  1291. info.name = t.name;
  1292. info.enabled = ! t.muted;
  1293. info.colour = t.colour != 0 ? rgb (t.colour) : 0x485156;
  1294. info.grouped = t.grouped;
  1295. info.expanded = ! t.collapsed;
  1296. info.lockedToContent = t.lockedToContent;
  1297. info.lockedHeight = t.lockedHeight;
  1298. info.mode = t.mode == PlaylistTrackMode::audio ? 1 : t.mode == PlaylistTrackMode::instrument ? 3 : 0;
  1299. info.mixerTrack = t.mixerTrack;
  1300. info.channel = t.channel;
  1301. info.icon = t.icon;
  1302. info.motion = (int) t.performance.motion;
  1303. info.press = (int) t.performance.press;
  1304. info.triggerSync = (int) t.performance.triggerSync;
  1305. info.positionSync = (int) t.performance.positionSync;
  1306. info.queue = t.performance.queue;
  1307. info.tolerant = t.performance.tolerant;
  1308. return info;
  1309. }
  1310. // ---- the mixer ----
  1311. void mixer()
  1312. {
  1313. for (int t = 0; t < (int) song.mixer.size(); ++t)
  1314. {
  1315. const auto& track = song.mixer[(std::size_t) t];
  1316. flp::MixerInsert m;
  1317. m.index = t;
  1318. m.name = t == 0 ? std::string() : track.name;
  1319. m.colour = track.colour != 0 ? rgb (track.colour) : 0;
  1320. m.colourSet = track.colour != 0 ? 1 : 0;
  1321. m.icon = track.icon;
  1322. m.flags = 0x04u | (track.muted ? 0u : 0x08u) | (track.invertPhase ? 0x01u : 0u) | (track.swapChannels ? 0x02u : 0u)
  1323. | (t > 0 && track.solo ? 0x1000u : 0u) | (t > 0 && track.separator ? 0x400u : 0u)
  1324. | (track.compensateMasterLatency ? 0u : 0x4000u)
  1325. | ((std::uint32_t) (t == 0 ? 0 : track.dock == MixerDock::left ? 0 : track.dock == MixerDock::right ? 2 : 1) << 6);
  1326. m.latencyMs = track.latencyMs;
  1327. m.latencyBypass = (int) track.latencyBypass;
  1328. m.recordSource = (int) track.recordSource;
  1329. m.monitor = (int) track.monitor;
  1330. m.input = track.flInput;
  1331. m.output = t == 0 ? 0 : track.outputChannel == 0 ? 0 : -1;
  1332. if (t > 0)
  1333. {
  1334. m.hasRoutes = true;
  1335. if (track.toMaster)
  1336. m.routes.push_back (0);
  1337. for (const auto& s : track.sends)
  1338. if (s.target > 0 && s.target < (int) song.mixer.size() && s.target != t)
  1339. m.routes.push_back (s.target);
  1340. // a side-chain input is FL's route at level 0 (sidechain only): without it FL's compressors and
  1341. // limiters have nothing to follow (thief's kick ducking was lost: +3.7 dB in FL, round 171e2)
  1342. for (const auto target : sidechainTargets (t))
  1343. if (std::find (m.routes.begin(), m.routes.end(), target) == m.routes.end())
  1344. m.routes.push_back (target);
  1345. }
  1346. // the levels (FL ranges: volume 0..16000 with 12800 = 0 dB, pan ±6400, separation ±64, route levels on the fader curve)
  1347. auto control = [&] (int slot, int param, std::int32_t value) { out.controls.push_back ({ { mixerId (t, slot, param) }, value }); };
  1348. control (0, flp::ControlId::mixerVolume, std::clamp (iround (track.volume * 16000.0), 0, 16000));
  1349. control (0, flp::ControlId::mixerPan, std::clamp (iround (track.pan * 6400.0), -6400, 6400));
  1350. control (0, flp::ControlId::mixerStereo, std::clamp (iround (track.stereo * 64.0), -64, 64));
  1351. for (int b = 0; b < 3; ++b)
  1352. {
  1353. const auto& eq = track.eq;
  1354. control (0, flp::ControlId::mixerEqBase + b, std::clamp (iround (eq.gainDb[(std::size_t) b] * 100.0), -1800, 1800));
  1355. const auto hz = std::clamp ((double) eq.hz[(std::size_t) b], 10.0, 16000.0);
  1356. control (0, flp::ControlId::mixerEqBase + 8 + b, std::clamp (iround (65536.0 * std::log ((hz - 10.0) / 159.9 + 1.0) / std::log (101.0)), 0, 65536));
  1357. control (0, flp::ControlId::mixerEqBase + 16 + b, std::clamp (iround (eq.width[(std::size_t) b] * 65536.0), 0, 65536));
  1358. }
  1359. if (t > 0)
  1360. {
  1361. control (0, flp::ControlId::mixerSendBase, std::clamp (iround (faderPosition (track.masterLevel) * 16000.0), 0, 16000));
  1362. for (const auto& s : track.sends)
  1363. if (s.target > 0 && s.target < (int) song.mixer.size())
  1364. control (0, flp::ControlId::mixerSendBase + s.target, std::clamp (iround (faderPosition (s.level) * 16000.0), 0, 16000));
  1365. for (const auto target : sidechainTargets (t))
  1366. if (std::none_of (track.sends.begin(), track.sends.end(), [&] (const MixerSend& s) { return s.target == target; }))
  1367. control (0, flp::ControlId::mixerSendBase + target, 0);
  1368. }
  1369. // the effect slots
  1370. int next = 0;
  1371. for (int s = 0; s < (int) track.effects.size(); ++s)
  1372. {
  1373. const auto& fx = track.effects[(std::size_t) s];
  1374. const auto row = std::max (next, fx.row >= 0 ? fx.row : next);
  1375. if (row >= maxEffectSlots)
  1376. break;
  1377. flp::MixerInsert::Slot slot;
  1378. slot.index = row;
  1379. slot.wrapperFlags = fx.smartDisable ? 0x160 : 0x140;
  1380. const auto label = insertLabel (song, t) + " slot " + std::to_string (row + 1) + ": ";
  1381. std::string what;
  1382. if (fx.isSubstitute() && fx.substituteFor.foreign.format != ForeignPlugin::Format::none)
  1383. {
  1384. slot.plugin = "Fruity Wrapper";
  1385. slot.state = writeWrapper (fx.substituteFor.foreign, false);
  1386. what = fx.substituteFor.foreign.name + " (the original plugin, LYNX's substitute left out)";
  1387. }
  1388. else if (fx.kind == EffectKind::plugin)
  1389. {
  1390. if (const auto record = hosted (fx.plugin, false))
  1391. {
  1392. slot.plugin = "Fruity Wrapper";
  1393. slot.state = writeWrapper (*record, false, fx.plugin.foreign.format == ForeignPlugin::Format::none ? &fx.plugin : nullptr);
  1394. what = record->name + " (Fruity Wrapper)";
  1395. }
  1396. }
  1397. else if (originMatches (fx))
  1398. {
  1399. slot.plugin = fx.flOrigin.plugin;
  1400. slot.state = fx.flOrigin.state;
  1401. what = fx.flOrigin.plugin;
  1402. }
  1403. else if (const auto sub = substituteFor (fx); sub && (options.lynxOnly == LynxOnly::substitute || t == 0))
  1404. {
  1405. slot.plugin = sub->first;
  1406. slot.state = sub->second;
  1407. report.substituted.push_back (label + effectInfo (fx.kind).name + " → " + sub->first + " (FL's defaults)");
  1408. }
  1409. if (slot.plugin.empty())
  1410. {
  1411. if (song.slotActive (fx))
  1412. report.dropped.push_back (label + effectInfo (fx.kind).name + " (LYNX only)");
  1413. continue;
  1414. }
  1415. if (! what.empty())
  1416. {
  1417. report.exact.push_back (label + what);
  1418. }
  1419. slotMap[{ t, s }] = row;
  1420. slotPlugin[{ t, s }] = slot.plugin;
  1421. control (row, 0x1F00, fx.enabled ? 1 : 0);
  1422. control (row, 0x1F01, std::clamp (iround (fx.mix * 12800.0), 0, 12800));
  1423. m.slots.push_back (std::move (slot));
  1424. next = row + 1;
  1425. }
  1426. out.mixer.push_back (std::move (m));
  1427. }
  1428. report.exact.push_back ("Mixer: " + std::to_string (song.mixer.size()) + " tracks (names, colours, routes, sends, levels, EQ)");
  1429. }
  1430. void run()
  1431. {
  1432. choosePpq();
  1433. globals();
  1434. channels();
  1435. mixer(); // (before the automations: their effect targets need the slots)
  1436. patterns();
  1437. automations();
  1438. arrangements();
  1439. out.mixerTrackCount = 0;
  1440. out.header.channelCount = (std::uint16_t) out.channels.size();
  1441. }
  1442. };
  1443. } // namespace
  1444. flp::Project toProject (const Song& input, const Options& options, Report& report)
  1445. {
  1446. // FL 2026 has no Pattern Blocks: they become pattern clips (each pattern on a track of its own, locked to content)
  1447. Song song = input;
  1448. if (patternblocks::active (song))
  1449. {
  1450. const auto n = patternblocks::toClipsInEveryArrangement (song);
  1451. if (n > 0)
  1452. report.notes.push_back ("Pattern Blocks: " + std::to_string (n) + " block(s) written as pattern clips (FL 2026 has no blocks)");
  1453. }
  1454. // automation lanes (round 177b): FL has none; each becomes an automation clip on a free track
  1455. if (const auto n = autolanes::lanesToClips (song); n > 0)
  1456. report.notes.push_back ("Automation lanes: " + std::to_string (n) + " lane(s) written as automation clips (FL has no lanes)");
  1457. // modulators (round 177b): FL has none; the modulated controls keep their own values
  1458. for (const auto& m : song.modulators)
  1459. if (! m.routes.empty())
  1460. report.dropped.push_back ("Modulator '" + m.name + "' (" + std::to_string (m.routes.size())
  1461. + " target(s)): FL has no modulators; the targets keep their own values");
  1462. Converter c (song, options, report);
  1463. c.run();
  1464. return std::move (c.out);
  1465. }
  1466. std::vector<std::uint8_t> exportFlp (const Song& song, const Options& options, Report& report)
  1467. {
  1468. return flp::writeProject (toProject (song, options, report), options.write);
  1469. }
  1470. } // namespace lynx::flpexport