FlpExport.cpp 79 KB

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