FlpExport.cpp 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316
  1. #include "core/FlVoiceBlock.h"
  2. #include "core/GrossBeat.h"
  3. #include "core/StepSlide.h"
  4. #include "core/Sections.h"
  5. #include "core/ChordLaneOps.h"
  6. #include "core/ClipEnvelope.h"
  7. #include "core/FlCurve.h"
  8. #include "core/NoteConditions.h"
  9. #include "core/NoteRepeat.h"
  10. #include "core/PlaylistOps.h"
  11. #include "core/FlpExport.h"
  12. #include "core/FlpImport.h" // (round 190rm: flRawRange, the song-start values' ranges)
  13. #include "core/TrackVersions.h"
  14. #include "core/RackAutomation.h" // round 190ow (PAT-7: FL's channel order)
  15. #include "core/ModulatorExport.h"
  16. #include "core/TrackClips.h"
  17. #include "core/TrackStates.h"
  18. #include "core/ProjectContents.h"
  19. #include "core/Fpc.h"
  20. #include "core/SamplerPage.h"
  21. #include <algorithm>
  22. #include <cctype>
  23. #include <cmath>
  24. #include <cstring>
  25. #include <map>
  26. #include <numeric>
  27. #include <set>
  28. #include "core/EditorPolish.h"
  29. #include "core/Effects.h"
  30. #include "core/FlEffects.h"
  31. #include "core/FlStateWrite.h"
  32. #include "core/FlWrapper.h"
  33. #include "core/FruityDance.h"
  34. #include "core/GoalKnobs.h"
  35. #include "core/PatternBlocks.h"
  36. #include "core/ThreeOsc.h"
  37. #include "core/TimeStretch.h"
  38. #include "core/MixerOps.h"
  39. #include "core/Transmitter.h"
  40. #include "core/Vocodex.h"
  41. #include "core/KeyRegions.h"
  42. namespace lynx::flpexport
  43. {
  44. namespace
  45. {
  46. // FL's curve mode byte of a LYNX segment (an older project's bend, LYNX's own law, goes out as a Single curve with the
  47. // same tension: the nearest FL shape)
  48. std::uint8_t flCurveOf (const AutomationPoint& p) noexcept
  49. {
  50. return p.mode < flcurve::modeCount ? p.mode : (std::uint8_t) flcurve::singleCurve;
  51. }
  52. // ---- small helpers ----
  53. int iround (double v) noexcept { return (int) std::lround (v); }
  54. // FL's time-stretching mode. Each one is a different algorithm in FL (Thief with −2 instead of its −1 renders at xcorr
  55. // 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
  56. // method it plays; otherwise FL's Stretch for General. Every mode but Resample (0) keeps the length, also without a TIME.
  57. int flStretchMode (const SamplerSettings& s) noexcept
  58. {
  59. if (! s.keepPitch)
  60. return 0;
  61. if (s.flStretchMode != 0 && stretchMethodForFlMode (s.flStretchMode) == s.stretchMethod)
  62. return s.flStretchMode;
  63. const auto m = s.stretchMethod;
  64. return m == StretchMethod::mono || m == StretchMethod::tones ? 2 : m == StretchMethod::transients || m == StretchMethod::beats ? 7 : -1;
  65. }
  66. std::uint32_t rgb (std::uint32_t argb) noexcept { return argb & 0xFFFFFFu; }
  67. struct Hash
  68. {
  69. std::uint64_t h = 1469598103934665603ull; // FNV-1a 64
  70. void bytes (const void* p, std::size_t n) noexcept
  71. {
  72. const auto* b = (const std::uint8_t*) p;
  73. for (std::size_t i = 0; i < n; ++i)
  74. h = (h ^ b[i]) * 1099511628211ull;
  75. }
  76. void i64 (std::int64_t v) noexcept { bytes (&v, sizeof v); }
  77. void text (const std::string& s) noexcept { i64 ((std::int64_t) s.size()); bytes (s.data(), s.size()); }
  78. void blob (const std::vector<std::uint8_t>& v) noexcept { i64 ((std::int64_t) v.size()); bytes (v.data(), v.size()); }
  79. // the project file keeps parameters to 1e-4 (ProjectFile's effectToVar), so does the fingerprint
  80. void value (float v) noexcept { i64 (std::isfinite (v) ? (std::int64_t) std::llround ((double) v * 10000.0) : 0); }
  81. };
  82. // The FL generator for each InstrumentKind whose state LYNX keeps in FL's own format (pluginState = FL's 0xD5), and the
  83. // sample / data path FL keeps in the channel (3x Osc's custom wave, the Granulizer's and Wave Traveller's sample).
  84. struct FlGenerator
  85. {
  86. InstrumentKind kind;
  87. const char* name;
  88. bool channelSample; // the channel's samplePath is FL's channel sample
  89. };
  90. constexpr FlGenerator flGenerators[] = {
  91. { InstrumentKind::sytrus, "Sytrus", false }, { InstrumentKind::harmor, "Harmor", false },
  92. { InstrumentKind::gms, "GMS", false }, { InstrumentKind::morphine, "Morphine", false },
  93. { InstrumentKind::ogun, "Ogun", false }, { InstrumentKind::minisynth, "MiniSynth", false },
  94. { InstrumentKind::dx10, "Fruity DX10", false }, { InstrumentKind::kepler, "Kepler", false },
  95. { InstrumentKind::poizone, "PoiZone", false }, { InstrumentKind::fruitkick, "Fruit Kick", false },
  96. { InstrumentKind::bassdrum, "BassDrum", false }, { InstrumentKind::toxic, "Toxic Biohazard", false },
  97. { InstrumentKind::threeosc, "3x Osc", true }, { InstrumentKind::autogun, "Autogun", false },
  98. { InstrumentKind::transistorbass, "Transistor Bass", false }, { InstrumentKind::simsynth, "SimSynth", false },
  99. { InstrumentKind::wasp, "Wasp", false }, { InstrumentKind::plucked, "Plucked!", false },
  100. { InstrumentKind::beepmap, "BeepMap", false }, { InstrumentKind::sawer, "Sawer", false },
  101. { InstrumentKind::flkeys, "FL Keys", false }, { InstrumentKind::granulizer, "Fruity Granulizer", true },
  102. { InstrumentKind::drumaxx, "Drumaxx", false }, { InstrumentKind::slayer, "FL Slayer", false },
  103. { InstrumentKind::fruitydance, "Fruity Dance", false }, { InstrumentKind::directwave, "DirectWave", false },
  104. { InstrumentKind::midiOut, "MIDI Out", false }, { InstrumentKind::voltage, "Fruity Voltage Controller", false },
  105. { InstrumentKind::dashboard, "Dashboard", false }, { InstrumentKind::videoplayer, "Fruity Video Player", false },
  106. { InstrumentKind::keplerExo, "Kepler Exo", false }, { InstrumentKind::wavetraveller, "Wave Traveller", true },
  107. { InstrumentKind::fruityslicer, "Fruity Slicer", false },
  108. { InstrumentKind::slicex, "Slicex", false },
  109. { InstrumentKind::fpc, "FPC", false },
  110. };
  111. const FlGenerator* generatorFor (InstrumentKind kind) noexcept
  112. {
  113. for (const auto& g : flGenerators)
  114. if (g.kind == kind)
  115. return &g;
  116. return nullptr;
  117. }
  118. bool originMatches (const ChannelDef& c) { return ! c.flOrigin.empty() && c.flOrigin.fingerprint == fingerprint (c); }
  119. bool sameName (const std::string& a, const std::string& b) noexcept
  120. {
  121. return a.size() == b.size() && std::equal (a.begin(), a.end(), b.begin(), [] (char x, char y) {
  122. return std::tolower ((unsigned char) x) == std::tolower ((unsigned char) y);
  123. });
  124. }
  125. // FL's trial mark (plugin record flag 0x80, issue #282, REA_rodada190qs): FL sets it on a plugin it saved while that
  126. // plugin was a trial, and an FL where it still is one does not load its settings (it locks the plugin until it is
  127. // bought). The mark stays with the plugin it was saved with, whatever LYNX did to its settings, as FL's own resave keeps
  128. // it; a channel that now holds another generator (or none: FL writes the mark on plugin records only) loses it.
  129. bool keepsTrialMark (const ChannelDef& def, const std::string& generator)
  130. {
  131. if (generator.empty())
  132. return false;
  133. if (! def.flOrigin.empty())
  134. return sameName (def.flOrigin.plugin, generator);
  135. // (no origin: the FPC kit and hosted plugins, which travel as themselves)
  136. return generator == "FPC" ? def.instrument == InstrumentKind::fpc : generator == "Fruity Wrapper";
  137. }
  138. // the export report's line for a project from an FL trial save (Song::flTrialSaved, round 190qt)
  139. const char* const trialProjectNote = "This project came from an FL Studio trial save, so FL Studio's trial will treat it as one.";
  140. std::string trialNote (const std::string& label, const std::string& plugin)
  141. {
  142. return label + ": " + plugin + " was saved by a trial of FL Studio. Where " + plugin
  143. + " is still a trial, FL Studio keeps it locked and does not load its settings (as with FL's own trial saves);"
  144. " an FL Studio that owns it loads them";
  145. }
  146. bool originMatches (const EffectSlot& s) { return ! s.flOrigin.empty() && s.flOrigin.fingerprint == fingerprint (s); }
  147. bool samplerLike (InstrumentKind k) noexcept { return k == InstrumentKind::sampler || k == InstrumentKind::audioClip; }
  148. // what FL's Sampler can't do of a LYNX sampler (it then needs a render)
  149. bool samplerExportable (const ChannelDef& c) noexcept
  150. {
  151. return samplerLike (c.instrument) && c.zones.empty() && c.sampler.slices.empty();
  152. }
  153. std::string channelLabel (const ChannelDef& c, int index)
  154. {
  155. return "Channel " + std::to_string (index + 1) + " '" + c.name + "'";
  156. }
  157. std::string insertLabel (const Song& song, int t)
  158. {
  159. if (t == 0)
  160. return "Master";
  161. const auto& name = song.mixer[(std::size_t) t].name;
  162. return "Insert " + std::to_string (t) + (name.empty() ? std::string() : " '" + name + "'");
  163. }
  164. // ---- Fruity Wrapper (0xD5 version 12, REA_rodada5 §2; FL 2026's record order [DATA: its saved projects]) ----
  165. struct Records
  166. {
  167. std::vector<std::uint8_t> b;
  168. void put32 (std::uint32_t v)
  169. {
  170. for (int k = 0; k < 4; ++k)
  171. b.push_back ((std::uint8_t) (v >> (8 * k)));
  172. }
  173. void record (std::uint32_t id, const std::vector<std::uint8_t>& data)
  174. {
  175. put32 (id);
  176. const auto n = (std::uint64_t) data.size();
  177. for (int k = 0; k < 8; ++k)
  178. b.push_back ((std::uint8_t) (n >> (8 * k)));
  179. b.insert (b.end(), data.begin(), data.end());
  180. }
  181. void record (std::uint32_t id, const std::string& text) { record (id, std::vector<std::uint8_t> (text.begin(), text.end())); }
  182. };
  183. std::vector<std::uint8_t> le32s (std::initializer_list<std::uint32_t> values)
  184. {
  185. std::vector<std::uint8_t> out;
  186. for (const auto v : values)
  187. for (int k = 0; k < 4; ++k)
  188. out.push_back ((std::uint8_t) (v >> (8 * k)));
  189. return out;
  190. }
  191. std::vector<std::uint8_t> le32s (const std::vector<std::uint32_t>& values)
  192. {
  193. std::vector<std::uint8_t> out;
  194. for (const auto v : values)
  195. for (int k = 0; k < 4; ++k)
  196. out.push_back ((std::uint8_t) (v >> (8 * k)));
  197. return out;
  198. }
  199. // FL 2026's Fruity Limiter as it comes (version 7, 169 bytes) [DATA: FL 2026's own templates, e.g. "Cheese's recording
  200. // setup"]: the substitute for LYNX's Limiter (option B, and the Master, which can't be bounced)
  201. const std::uint8_t fruityLimiterDefault[169] = {
  202. 0x07, 0x00, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0x5b, 0x04, 0x00, 0x00,
  203. 0x03, 0x00, 0x00, 0x00, 0x88, 0x13, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x42, 0x0b, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00,
  204. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x1a, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
  205. 0x8a, 0x02, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5b, 0x10, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00,
  206. 0xe8, 0x03, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0x5b, 0x04, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x88, 0x13, 0x00, 0x00,
  207. 0x03, 0x00, 0x00, 0x00, 0x42, 0x0b, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  208. 0x00, 0x00, 0x00, 0x00, 0x0a, 0x1a, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x8a, 0x02, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00,
  209. 0x00, 0x00, 0x00, 0x00, 0x5b, 0x10, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01,
  210. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  211. };
  212. // FL 2026's Fruity Parametric EQ 2 as a new instance saves it (version 8, 354 bytes) [DATA: captured in round 189k, FL
  213. // 2026 saving a project whose Master slot had the plugin with no state; the same bytes as its Default.fst preset except
  214. // 0x131]: the base the Master looks' EQ is written over (core/FlStateWrite.h). A new instance has HQ with the
  215. // alternative design on (0x124 = 3).
  216. const std::uint8_t parametricEq2Default[354] = {
  217. 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  218. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xab, 0x2a, 0x00, 0x00, 0x1c, 0x47, 0x00, 0x00,
  219. 0x8e, 0x63, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x72, 0x9c, 0x00, 0x00, 0xe4, 0xb8, 0x00, 0x00, 0x55, 0xd5, 0x00, 0x00,
  220. 0xbc, 0x9c, 0x00, 0x00, 0x44, 0x63, 0x00, 0x00, 0x44, 0x63, 0x00, 0x00, 0x44, 0x63, 0x00, 0x00, 0x44, 0x63, 0x00, 0x00,
  221. 0x44, 0x63, 0x00, 0x00, 0xbc, 0x9c, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
  222. 0x06, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  223. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  224. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  225. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xab, 0x2a, 0x00, 0x00,
  226. 0x1c, 0x47, 0x00, 0x00, 0x8e, 0x63, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x72, 0x9c, 0x00, 0x00, 0xe4, 0xb8, 0x00, 0x00,
  227. 0x55, 0xd5, 0x00, 0x00, 0xbc, 0x9c, 0x00, 0x00, 0x44, 0x63, 0x00, 0x00, 0x44, 0x63, 0x00, 0x00, 0x44, 0x63, 0x00, 0x00,
  228. 0x44, 0x63, 0x00, 0x00, 0x44, 0x63, 0x00, 0x00, 0xbc, 0x9c, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
  229. 0x06, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
  230. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  231. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  232. 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7f, 0x00,
  233. 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00,
  234. 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  235. };
  236. // option B's clean mappings: the LYNX effect → an FL plugin with its state
  237. std::optional<std::pair<std::string, std::vector<std::uint8_t>>> substituteFor (const EffectSlot& slot)
  238. {
  239. if (slot.kind == EffectKind::limiter)
  240. return std::pair { std::string ("Fruity Limiter"), std::vector<std::uint8_t> (std::begin (fruityLimiterDefault), std::end (fruityLimiterDefault)) };
  241. return std::nullopt;
  242. }
  243. // LYNX's 0..1 automation value → FL's raw parameter value for a pattern event / initial value
  244. std::int32_t rawValue (const AutomationTarget& t, float v, const Song* song = nullptr)
  245. {
  246. v = std::clamp (v, 0.0f, 1.0f);
  247. // the PITCH knob (round 190py): cents within the channel's ±range
  248. if (t.kind == AutomationTargetKind::channelParam && t.param == channelPitchParam)
  249. return song != nullptr && t.index >= 0 && t.index < (int) song->channels.size()
  250. ? iround (channelPitchSemitones (song->channels[(std::size_t) t.index], v) * 100.0)
  251. : 0;
  252. // Gross Beat's own raw ranges (round 190re; v is FL's normalised value: the scratch dial's turned round)
  253. if (t.kind == AutomationTargetKind::effectParam && song != nullptr && t.param >= 0 && t.param < grossbeat::paramCount
  254. && t.index >= 0 && t.index < (int) song->mixer.size() && t.slot >= 0 && t.slot < (int) song->mixer[(std::size_t) t.index].effects.size()
  255. && song->mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind == EffectKind::grossBeat)
  256. return grossbeat::rawFromParam (t.param, t.param == grossbeat::scratchParam ? 1.0f - v : v);
  257. switch (t.kind)
  258. {
  259. case AutomationTargetKind::channelVolume:
  260. case AutomationTargetKind::channelPan: return iround (v * 12800.0);
  261. case AutomationTargetKind::channelAdjust: // (round 190dz) FL's knob ranges: volume 0…25600, pan ±6400, Mod X / Y ±256
  262. return t.param == leveladjust::volume ? iround (v * 25600.0)
  263. : t.param == leveladjust::pan ? iround ((v * 2.0 - 1.0) * 6400.0)
  264. : iround ((v * 2.0 - 1.0) * 256.0);
  265. case AutomationTargetKind::mixerVolume:
  266. case AutomationTargetKind::mixerSend: return iround (v * 16000.0);
  267. case AutomationTargetKind::mixerPan: return iround ((v * 2.0 - 1.0) * 6400.0);
  268. case AutomationTargetKind::effectMix: return iround (v * 12800.0);
  269. case AutomationTargetKind::tempo: return iround (10000.0 + 512000.0 * v); // BPM × 1000 (issue #86, REA_rodada178a §2)
  270. default: return iround (v * 65536.0);
  271. }
  272. }
  273. std::uint32_t mixerId (int track, int slot, int param) noexcept
  274. {
  275. return 0x70000000u + ((std::uint32_t) track << 22) + ((std::uint32_t) slot << 16) + (std::uint32_t) param;
  276. }
  277. // FL's channel filter cutoff for normalised Mod X (REA_rodada4 §3), as the importer's channelFilterHz
  278. double filterHz (int type, double x)
  279. {
  280. constexpr double twoPi = 6.283185307179586;
  281. x = std::clamp (x, 0.0, 1.0);
  282. switch (type)
  283. {
  284. 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));
  285. case 1:
  286. case 2:
  287. case 3:
  288. case 4:
  289. case 5: return ((std::pow (51.0, x) - 1.0) * 0.0596 + 0.02) * 44100.0 / twoPi;
  290. default: return 20000.0;
  291. }
  292. }
  293. // a monotonic f over [0, 1]: the x whose f(x) is nearest `target`
  294. template <typename F>
  295. double invert (F&& f, double target, bool increasing = true)
  296. {
  297. double lo = 0.0, hi = 1.0;
  298. for (int i = 0; i < 40; ++i)
  299. {
  300. const auto mid = 0.5 * (lo + hi);
  301. if ((f (mid) < target) == increasing)
  302. lo = mid;
  303. else
  304. hi = mid;
  305. }
  306. return 0.5 * (lo + hi);
  307. }
  308. } // namespace
  309. // ================================================================================================================
  310. int envelopeTimeValue (double seconds) noexcept
  311. {
  312. if (! (seconds > 0.0))
  313. return 100; // FL: values up to 100 are no time at all
  314. const auto v = 65536.0 * std::log (seconds / 0.064 + 1.0) / std::log (1000.0);
  315. return std::clamp (iround (v), 101, 65536);
  316. }
  317. int slideTimeValue (float beats) noexcept
  318. {
  319. // n = round((27^(v/1024) − 1)·48/26) ticks of 1/192 beat (REA_rodada6 §4)
  320. const auto n = std::max (1.0, (double) beats * 192.0);
  321. return std::clamp (iround (1024.0 * std::log (n * 26.0 / 48.0 + 1.0) / std::log (27.0)), 0, 1660);
  322. }
  323. std::vector<std::uint8_t> defaultThreeOscState()
  324. {
  325. // a version-13 state of zeros is LYNX's Params {}; normalised: version 14 + the default voice snapshot
  326. std::vector<std::uint8_t> zero (4 + 21 * 4 + 8, 0);
  327. zero[0] = 13;
  328. return threeOscNormalisedState (zero, {});
  329. }
  330. std::vector<std::uint8_t> fruityLimiterDefaultState()
  331. {
  332. return std::vector<std::uint8_t> (std::begin (fruityLimiterDefault), std::end (fruityLimiterDefault));
  333. }
  334. std::vector<std::uint8_t> parametricEq2DefaultState()
  335. {
  336. return std::vector<std::uint8_t> (std::begin (parametricEq2Default), std::end (parametricEq2Default));
  337. }
  338. std::optional<std::pair<std::string, std::vector<std::uint8_t>>> nativeLookState (const EffectSlot& s)
  339. {
  340. if (s.look == 0)
  341. return std::nullopt;
  342. switch (s.kind)
  343. {
  344. case EffectKind::parametricEq:
  345. if (peqfl::lawOf (s.params) != peqfl::Law::peq2)
  346. return std::nullopt;
  347. return std::pair { std::string ("Fruity Parametric EQ 2"), flstate::parametricEq2 (s.params, parametricEq2DefaultState()) };
  348. case EffectKind::fruityMultiband: return std::pair { std::string ("Fruity Multiband Compressor"), flstate::multiband (s.params) };
  349. case EffectKind::stereoEnhancer: return std::pair { std::string ("Fruity Stereo Enhancer"), flstate::stereoEnhancer (s.params) };
  350. case EffectKind::fruitySoftClipper: return std::pair { std::string ("Fruity Soft Clipper"), flstate::softClipper (s.params) };
  351. case EffectKind::fruityLimiter: return std::pair { std::string ("Fruity Limiter"), flstate::limiter (s.params, fruityLimiterDefaultState()) };
  352. default: return std::nullopt;
  353. }
  354. }
  355. std::uint64_t fingerprint (const ChannelDef& c)
  356. {
  357. Hash h;
  358. h.i64 ((std::int64_t) c.instrument);
  359. h.blob (c.pluginState);
  360. h.blob (c.controllerState);
  361. h.i64 ((std::int64_t) c.modelParams.size());
  362. for (const auto v : c.modelParams)
  363. h.value (v);
  364. h.i64 ((std::int64_t) c.zones.size());
  365. h.i64 ((std::int64_t) c.sampler.slices.size());
  366. h.text (c.plugin.id);
  367. return h.h;
  368. }
  369. std::uint64_t fingerprint (const EffectSlot& s)
  370. {
  371. Hash h;
  372. h.i64 ((std::int64_t) s.kind);
  373. const auto used = s.kind == EffectKind::plugin ? (std::size_t) 0 : std::min (effectInfo (s.kind).params.size(), s.params.size());
  374. for (std::size_t i = 0; i < used; ++i)
  375. h.value (s.params[i]);
  376. h.blob (s.state);
  377. h.i64 ((std::int64_t) s.branches.size());
  378. h.i64 ((std::int64_t) s.patcher.nodes.size());
  379. return h.h;
  380. }
  381. void stampOrigins (Song& song)
  382. {
  383. for (auto& c : song.channels)
  384. if (! c.flOrigin.empty())
  385. c.flOrigin.fingerprint = fingerprint (c);
  386. for (auto& t : song.mixer)
  387. for (auto& s : t.effects)
  388. if (! s.flOrigin.empty())
  389. s.flOrigin.fingerprint = fingerprint (s);
  390. }
  391. std::string flGeneratorName (const ChannelDef& c)
  392. {
  393. if (originMatches (c))
  394. return c.flOrigin.plugin;
  395. if (c.instrument == InstrumentKind::layer)
  396. return "Layer";
  397. // (an empty state: the engines LYNX plays from their defaults, which are FL's — a new FL instance)
  398. // (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
  399. // state keeps uninitialised voice settings, its notes never end; round 171e, FL render])
  400. const auto own = c.instrument == InstrumentKind::threeosc;
  401. if (const auto* g = generatorFor (c.instrument); g != nullptr && (! c.pluginState.empty() || own))
  402. return g->name;
  403. return {};
  404. }
  405. namespace
  406. {
  407. std::string instrumentName (InstrumentKind k)
  408. {
  409. switch (k)
  410. {
  411. case InstrumentKind::kick: return "LYNX Kick";
  412. case InstrumentKind::snare: return "LYNX Snare";
  413. case InstrumentKind::hat: return "LYNX Hat";
  414. case InstrumentKind::clap: return "LYNX Clap";
  415. case InstrumentKind::synth: return "LYNX Synth";
  416. case InstrumentKind::sampler: return "Sampler (multi-sample / slices)";
  417. case InstrumentKind::controller: return "Envelope Controller";
  418. case InstrumentKind::patcher: return "Patcher";
  419. case InstrumentKind::soundfont: return "LYNX Soundfont";
  420. case InstrumentKind::vfx: return "VFX note processor";
  421. default: return "instrument";
  422. }
  423. }
  424. } // namespace
  425. bool needsFreeze (const ChannelDef& c)
  426. {
  427. if (c.instrument == InstrumentKind::plugin || c.plugin.foreign.format != ForeignPlugin::Format::none)
  428. return false; // the wrapper (or, unknown, planRenders decides)
  429. if (! flGeneratorName (c).empty())
  430. return false;
  431. return ! samplerExportable (c);
  432. }
  433. bool effectExportable (const EffectSlot& s, const Options& options)
  434. {
  435. if (s.isSubstitute() && s.substituteFor.foreign.format != ForeignPlugin::Format::none)
  436. return true;
  437. if (s.kind == EffectKind::plugin)
  438. return s.plugin.foreign.format != ForeignPlugin::Format::none || (options.pluginRecord && options.pluginRecord (s.plugin, false));
  439. if (originMatches (s) || nativeLookState (s))
  440. return true;
  441. return options.lynxOnly == LynxOnly::substitute && substituteFor (s).has_value();
  442. }
  443. // ================================================================================================================
  444. RenderPlan planRenders (const Song& song, const Options& options)
  445. {
  446. RenderPlan plan;
  447. if (options.lynxOnly != LynxOnly::renderAudio)
  448. return plan;
  449. for (int i = 0; i < (int) song.channels.size(); ++i)
  450. {
  451. const auto& c = song.channels[(std::size_t) i];
  452. const auto pluginUnknown = c.instrument == InstrumentKind::plugin && c.plugin.foreign.format == ForeignPlugin::Format::none
  453. && ! (options.pluginRecord && options.pluginRecord (c.plugin, true));
  454. // (silent kinds — controllers, VFX, video, MIDI out — make no audio to freeze; they are left out instead)
  455. const auto silent = c.instrument == InstrumentKind::controller || c.instrument == InstrumentKind::vfx;
  456. if ((needsFreeze (c) && ! silent) || pluginUnknown)
  457. plan.channels.push_back (i);
  458. }
  459. // inserts with a slot FL can't have (Master excluded: bouncing it would bounce the whole song), downstream first
  460. std::vector<int> order;
  461. for (const auto t : song.mixerOrder())
  462. if (t > 0 && t < (int) song.mixer.size())
  463. order.push_back (t);
  464. std::set<int> silenced;
  465. for (auto it = order.rbegin(); it != order.rend(); ++it)
  466. {
  467. const auto t = *it;
  468. const auto& track = song.mixer[(std::size_t) t];
  469. const auto lynxOnly = std::any_of (track.effects.begin(), track.effects.end(),
  470. [&] (const EffectSlot& s) { return song.slotActive (s) && ! effectExportable (s, options); });
  471. if (! lynxOnly)
  472. continue;
  473. // an insert heard only through inserts already bounced is in their audio
  474. auto audible = track.toMaster;
  475. for (const auto& send : track.sends)
  476. audible = audible || silenced.count (send.target) == 0;
  477. if (! audible && ! track.sends.empty())
  478. continue;
  479. plan.inserts.push_back (t);
  480. silenced.insert (t);
  481. }
  482. return plan;
  483. }
  484. Song makeInsertRenderSong (const Song& song, int track)
  485. {
  486. auto out = makeBounceSong (song, track);
  487. if (track <= 0 || track >= (int) out.mixer.size())
  488. return out;
  489. for (int t = 1; t < (int) out.mixer.size(); ++t)
  490. if (t != track)
  491. out.mixer[(std::size_t) t].toMaster = false;
  492. return out;
  493. }
  494. Song makeFreezeSong (const Song& song, int channel)
  495. {
  496. Song out = song;
  497. out.mode = PlayMode::song;
  498. for (int i = 0; i < (int) out.channels.size(); ++i)
  499. if (i != channel)
  500. out.channels[(std::size_t) i].muted = true;
  501. if (channel >= 0 && channel < (int) out.channels.size())
  502. {
  503. auto& c = out.channels[(std::size_t) channel];
  504. c.muted = false;
  505. c.mixerTrack = 0;
  506. }
  507. for (auto& t : out.mixer)
  508. t.solo = false;
  509. if (! out.mixer.empty())
  510. {
  511. auto& master = out.mixer[0];
  512. master.effects.clear();
  513. master.volume = unityFader;
  514. master.pan = 0.0f;
  515. master.stereo = 0.0f;
  516. master.eq = TrackEq {};
  517. master.muted = false;
  518. master.invertPhase = master.swapChannels = false;
  519. }
  520. // the Master's own automation would colour the render
  521. for (auto& a : out.automations)
  522. if ((a.target.kind == AutomationTargetKind::mixerVolume || a.target.kind == AutomationTargetKind::mixerPan
  523. || a.target.kind == AutomationTargetKind::effectParam || a.target.kind == AutomationTargetKind::effectMix)
  524. && a.target.index == 0)
  525. a.target.kind = AutomationTargetKind::none;
  526. return out;
  527. }
  528. void applyFreeze (Song& song, int channel, const std::string& wav, std::int64_t length)
  529. {
  530. if (channel < 0 || channel >= (int) song.channels.size())
  531. return;
  532. auto& c = song.channels[(std::size_t) channel];
  533. const auto mixerTrack = c.mixerTrack;
  534. const auto name = c.name;
  535. const auto colour = c.colour;
  536. ChannelDef frozen;
  537. frozen.name = name + " (audio)";
  538. frozen.instrument = InstrumentKind::audioClip;
  539. frozen.samplePath = wav;
  540. frozen.mixerTrack = mixerTrack;
  541. // unity: the render holds the channel's level and pan. A Playlist audio clip plays at unity at FL's default channel
  542. // volume (10000 of 12800, Instruments.cpp audioClipUnity), in FL as in LYNX; 100 % played the render 5.2 dB louder
  543. // (round 182b: Patience exported from a Live set rendered +4.3 dB in FL and in LYNX)
  544. frozen.volume = audioClipUnityVolume;
  545. frozen.colour = colour;
  546. frozen.uid = c.uid;
  547. c = std::move (frozen);
  548. for (auto& p : song.patterns)
  549. {
  550. p.notes.erase (std::remove_if (p.notes.begin(), p.notes.end(), [channel] (const Note& n) { return n.channel == channel; }), p.notes.end());
  551. p.channelLoops.erase (std::remove_if (p.channelLoops.begin(), p.channelLoops.end(), [channel] (const ChannelLoop& l) { return l.channel == channel; }),
  552. p.channelLoops.end());
  553. for (auto& lane : p.events)
  554. if ((lane.target.kind == AutomationTargetKind::channelVolume || lane.target.kind == AutomationTargetKind::channelPan
  555. || lane.target.kind == AutomationTargetKind::channelParam || lane.target.kind == AutomationTargetKind::channelAdjust)
  556. && lane.target.index == channel)
  557. lane.target.kind = AutomationTargetKind::none;
  558. }
  559. for (auto& a : song.automations)
  560. if ((a.target.kind == AutomationTargetKind::channelVolume || a.target.kind == AutomationTargetKind::channelPan
  561. || a.target.kind == AutomationTargetKind::channelParam || a.target.kind == AutomationTargetKind::channelAdjust)
  562. && a.target.index == channel)
  563. a.target.kind = AutomationTargetKind::none;
  564. int lane = 0;
  565. song.forEachClipList ([&lane] (const std::vector<Clip>& clips) {
  566. for (const auto& clip : clips)
  567. lane = std::max (lane, clip.track + 1);
  568. });
  569. Clip clip;
  570. clip.kind = ClipKind::audio;
  571. clip.channel = channel;
  572. clip.track = lane;
  573. clip.length = length;
  574. song.playlist.push_back (clip);
  575. if ((int) song.playlistTracks.size() <= lane)
  576. song.playlistTracks.resize ((std::size_t) lane + 1);
  577. song.playlistTracks[(std::size_t) lane].name = name + " (audio)";
  578. }
  579. void applyChannelRender (Song& song, int channel, const std::string& wav, std::int64_t length, Report& report)
  580. {
  581. if (channel < 0 || channel >= (int) song.channels.size())
  582. return;
  583. const auto& c = song.channels[(std::size_t) channel];
  584. report.rendered.push_back ("Channel " + std::to_string (channel + 1) + " '" + c.name + "': "
  585. + (c.instrument == InstrumentKind::plugin ? "plugin '" + c.plugin.name + "'" : instrumentName (c.instrument))
  586. + " → audio clip");
  587. applyFreeze (song, channel, wav, length);
  588. }
  589. int applyInsertRender (Song& song, int track, const std::string& wav, std::int64_t length, const Options& options, Report& report)
  590. {
  591. if (track <= 0 || track >= (int) song.mixer.size())
  592. return -1;
  593. std::vector<std::string> names;
  594. auto& effects = song.mixer[(std::size_t) track].effects;
  595. for (int s = 0; s < (int) effects.size(); ++s)
  596. {
  597. auto& fx = effects[(std::size_t) s];
  598. if (! song.slotActive (fx) || effectExportable (fx, options))
  599. continue;
  600. names.push_back (effectInfo (fx.kind).name);
  601. fx.enabled = false;
  602. for (auto& a : song.automations)
  603. if ((a.target.kind == AutomationTargetKind::effectParam || a.target.kind == AutomationTargetKind::effectMix)
  604. && a.target.index == track && a.target.slot == s)
  605. a.target.kind = AutomationTargetKind::none;
  606. for (auto& p : song.patterns)
  607. for (auto& lane : p.events)
  608. if ((lane.target.kind == AutomationTargetKind::effectParam || lane.target.kind == AutomationTargetKind::effectMix)
  609. && lane.target.index == track && lane.target.slot == s)
  610. lane.target.kind = AutomationTargetKind::none;
  611. }
  612. const auto name = song.mixer[(std::size_t) track].name;
  613. const auto added = applyBounce (song, track, wav, length);
  614. if (added < 0)
  615. return -1;
  616. std::string list;
  617. for (const auto& n : names)
  618. list += (list.empty() ? "" : ", ") + n;
  619. report.rendered.push_back ("Insert " + std::to_string (track) + " '" + name + "' (" + list + ") → audio clip on insert "
  620. + std::to_string (added));
  621. return added;
  622. }
  623. // ================================================================================================================
  624. std::vector<std::uint8_t> flVst3State (const std::vector<std::uint8_t>& component, const std::vector<std::uint8_t>& controller)
  625. {
  626. // u32 1 + records {u32 id, u64 size}: 1 (64 B, first u32 = 1), 3 component, 2 controller [DATA: FL 2026's VST3
  627. // states]; record 4 (FL's parameter slots) is left out: FL then gives slot k to the plugin's k-th parameter, which is
  628. // LYNX's parameter index (REA_rodada22 §2.3)
  629. if (component.empty() && controller.empty())
  630. return {}; // (no state: the wrapper then has none and FL starts the plugin from its defaults)
  631. Records r;
  632. r.put32 (1);
  633. std::vector<std::uint8_t> head (64, 0);
  634. head[0] = 1;
  635. r.record (1, head);
  636. r.record (3, component);
  637. r.record (2, controller);
  638. return r.b;
  639. }
  640. std::vector<std::uint8_t> writeWrapper (const ForeignPlugin& p, bool instrument, const PluginRef* ref)
  641. {
  642. Records r;
  643. r.put32 (12);
  644. // 0x01: MIDI in / out ports, the pitch bend range, 8 zero bytes
  645. {
  646. const auto in = ref != nullptr ? ref->midiInPort : p.midiInPort;
  647. const auto out = ref != nullptr ? ref->midiOutPort : p.midiOutPort;
  648. const auto bend = ref != nullptr ? ref->bendRange : (p.bendRange >= 1 ? p.bendRange : 12);
  649. r.record (0x01, le32s ({ (std::uint32_t) in, (std::uint32_t) out, (std::uint32_t) bend, 0, 0 }));
  650. }
  651. // 0x02: the options [DATA: FL 2026's defaults 00 | a0 00 00 00 | 19 00 00 00 | flags 0xB4007D8C | fixed 0 | 1 | flags2 0]
  652. {
  653. std::uint32_t flags = 0xB4007D8Cu, fixed = 0, flags2 = 0;
  654. if (ref != nullptr)
  655. {
  656. auto set = [&flags] (std::uint32_t bit, bool on) { flags = on ? flags | bit : flags & ~bit; };
  657. set (0x2u, ref->fixedBuffers);
  658. set (0x4u, ref->notifyRender);
  659. set (0x1000u, ref->threaded);
  660. set (0x40000u, ref->separateProcess);
  661. set (0x20000000u, ref->allowSmartDisable);
  662. set (0x1u, ref->sendBendRange);
  663. set (0x20u, ! ref->releaseVelocity);
  664. set (0x800u, ref->sendLoopPosition);
  665. set (0x20000u, ref->modXAftertouch);
  666. set (0x02000000u, ! ref->resetOnFlush);
  667. set (0x01000000u, ref->hostKeysFirst);
  668. set (0x04000000u, ref->dpiAware); // Settings › GUI (round 190oh)
  669. set (0x40000000u, ref->scaleEditorDimensions);
  670. fixed = (ref->maxSizeBuffers ? 1u : 0u) | (ref->hostMaxBuffer ? 2u : 0u);
  671. flags2 = (ref->allNotesOffOnStop ? 0u : 0x1000u) | (ref->allowHostKeys ? 0x800u : 0u);
  672. set (0x8u, ref->processInactive); // "Process inactive inputs and outputs" (round 188d)
  673. }
  674. else if (p.hasWrapperOptions)
  675. {
  676. flags = p.wrapperFlags;
  677. fixed = p.fixedOptions;
  678. flags2 = p.hasWrapperFlags2 ? p.wrapperFlags2 : 0;
  679. }
  680. std::vector<std::uint8_t> o { 0x00, 0xa0, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00 };
  681. const auto tail = le32s ({ flags, fixed, 1, flags2 });
  682. o.insert (o.end(), tail.begin(), tail.end());
  683. r.record (0x02, o);
  684. }
  685. // 0x1E / 0x1F / 0x20: Processing › Connections, 12 bytes per input / output {i32 offset, u32 active, u32 0}
  686. // [DATA round 188d]; without a mapping one input and one output (FL lays them out again from the plugin)
  687. {
  688. const auto* ins = ref != nullptr ? &ref->inputs : (p.hasRoutes ? &p.inputRoutes : nullptr);
  689. const auto* outs = ref != nullptr ? &ref->outputs : (p.hasRoutes ? &p.outputRoutes : nullptr);
  690. if ((ins != nullptr && ! ins->empty()) || (outs != nullptr && ! outs->empty()))
  691. {
  692. auto list = [] (const std::vector<PluginOutputRoute>& routes) {
  693. std::vector<std::uint32_t> words;
  694. for (const auto& route : routes)
  695. words.insert (words.end(), { (std::uint32_t) route.offset, route.isActive (true) ? 1u : 0u, 0u });
  696. return le32s (words);
  697. };
  698. // (an effect whose inputs alone are mapped: its output as below, one default entry)
  699. const auto outputs = outs->empty() && ! instrument ? std::vector<PluginOutputRoute> { { 0, 1 } } : *outs;
  700. r.record (0x1E, le32s ({ (std::uint32_t) ins->size(), (std::uint32_t) outputs.size(), 0, 0 }));
  701. if (! ins->empty())
  702. r.record (0x1F, list (*ins));
  703. if (! outputs.empty())
  704. r.record (0x20, list (outputs));
  705. }
  706. else
  707. {
  708. r.record (0x1E, le32s ({ 1, 1, 0, 0 }));
  709. r.record (0x1F, le32s ({ 0, instrument ? 0u : 1u, 0 }));
  710. r.record (0x20, le32s ({ 0, 1, 0 }));
  711. }
  712. }
  713. std::uint32_t type = 0;
  714. switch (p.format)
  715. {
  716. case ForeignPlugin::Format::vst2: type = instrument ? 4 : 0; break;
  717. case ForeignPlugin::Format::vst3: type = instrument ? 8 : 7; break;
  718. case ForeignPlugin::Format::clap: type = instrument ? 12 : 11; break;
  719. default: break;
  720. }
  721. r.record (0x32, le32s ({ type, 0, 0, 0 }));
  722. if (p.format == ForeignPlugin::Format::vst2)
  723. r.record (0x33, le32s ({ p.vst2Id }));
  724. if (p.format == ForeignPlugin::Format::vst3 || (p.format == ForeignPlugin::Format::vst2 && p.hasClassId))
  725. r.record (0x34, std::vector<std::uint8_t> (p.classId.begin(), p.classId.end()));
  726. if (p.format == ForeignPlugin::Format::clap)
  727. r.record (0x3A, p.clapId);
  728. r.record (0x36, p.name);
  729. r.record (0x37, p.path);
  730. if (! p.state.empty())
  731. r.record (0x35, p.state);
  732. return r.b;
  733. }
  734. // ================================================================================================================
  735. namespace
  736. {
  737. struct Converter
  738. {
  739. Converter (const Song& s, const Options& o, Report& r) : song (s), options (o), report (r) {}
  740. const Song& song;
  741. const Options& options;
  742. Report& report;
  743. flp::Project out;
  744. int filePpq = 96;
  745. std::map<int, int> automationChannel; // song.automations index → FL channel
  746. // the FL slot (0..9) of each exported effect: (track, LYNX slot) → FL slot
  747. std::map<std::pair<int, int>, int> slotMap;
  748. std::map<std::pair<int, int>, std::string> slotPlugin; // → FL plugin name ("Fruity Wrapper" for hosted plugins)
  749. // round 190ot: slots written as FL's own plugin from LYNX's parameters (a Master look, the Simple layout's Duck):
  750. // their side input index is set by fixSideInputs as an imported state's is
  751. std::set<std::pair<int, int>> ownState;
  752. 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)
  753. std::string path (const std::string& p) const { return options.samplePath && ! p.empty() ? options.samplePath (p) : p; }
  754. void choosePpq()
  755. {
  756. // FL's own 96 when every note and clip fits it, else LYNX's 960; other times (pattern lengths, event ticks, markers,
  757. // offsets) are rounded to the file's PPQ [FL 2026 played a 960-PPQ export of an FL demo wrongly, round 171e]
  758. if (options.ppq > 0)
  759. {
  760. filePpq = options.ppq;
  761. out.header.ppq = (std::uint16_t) filePpq;
  762. return;
  763. }
  764. bool fine = true;
  765. auto use = [&fine] (std::int64_t t) { fine = fine && t % (ppq / 96) == 0; };
  766. for (const auto& p : song.patterns)
  767. for (const auto& n : p.notes)
  768. {
  769. use (n.start);
  770. use (n.length);
  771. }
  772. song.forEachClipList ([&] (const std::vector<Clip>& clips) {
  773. for (const auto& c : clips)
  774. {
  775. use (c.start);
  776. // (an audio clip's length goes unstretched, as playlistItem writes it)
  777. use (c.kind == ClipKind::audio && c.stretch > 0.0 && c.stretch != 1.0 ? (std::int64_t) std::llround ((double) c.length / c.stretch)
  778. : c.length);
  779. }
  780. });
  781. filePpq = fine ? 96 : ppq;
  782. out.header.ppq = (std::uint16_t) filePpq;
  783. }
  784. void globals()
  785. {
  786. out.version = options.write.version;
  787. out.versionNumber = flp::parseVersionNumber (out.version);
  788. out.flagsA9 = 15;
  789. out.tempo = song.bpm;
  790. out.beatsPerBar = song.beatsPerBar;
  791. out.beatUnit = meterUnit (song.beatUnit);
  792. out.swing = std::clamp (iround (song.swing * 128.0), 0, 128);
  793. out.mainPitch = iround (song.masterPitch);
  794. if (song.mainVolume != unityFader) // (round 190oa, DF-21: FlpWrite writes FL's 12800 unless the project has its own)
  795. out.controls.push_back ({ { flp::ControlId::mainVolume }, iround (song.mainVolume * 16000.0f) });
  796. out.currentPattern = std::clamp (song.currentPattern, 0, std::max (0, (int) song.patterns.size() - 1)) + 1;
  797. out.songMode = song.mode == PlayMode::song ? 1 : 0;
  798. out.showInfo = song.info.showOnOpen;
  799. out.currentArrangement = std::max (0, song.currentArrangement);
  800. out.playTruncatedNotes = song.playTruncatedNotes;
  801. // round 190qt (owner's option A): a project from an FL trial save goes back as one (0x1C = 0, FL's values
  802. // scrambled after it), so FL's trial treats it as FL's own trial save; every other project stays registered
  803. out.trialSaved = song.flTrialSaved;
  804. if (song.flTrialSaved)
  805. report.notes.push_back (trialProjectNote);
  806. out.autoPdc = song.autoPdc;
  807. out.compensateAutomations = song.compensateAutomations;
  808. out.timeSignatureMode = song.timeSignatureMode;
  809. out.fastDeclick = song.fastDeclick;
  810. out.performanceMode = song.performanceMode;
  811. out.panLaw = song.panTriangular ? 2 : 0;
  812. out.autoCrossfades = song.autoCrossfades;
  813. // (round 190rc: a data folder missing on this computer is left out, as FL's own projects without one are saved)
  814. out.dataFolder = song.dataFolder.empty() || ! options.folderExists || options.folderExists (song.dataFolder) ? song.dataFolder : std::string();
  815. out.hasScaleHighlight = true;
  816. out.scaleHighlight = notetools::flMenuScaleIndex (song.scaleHighlight.scale); // (LYNX's index -> FL's)
  817. out.scaleRoot = song.scaleHighlight.root;
  818. out.title = song.info.title;
  819. out.artist = song.info.author;
  820. out.genre = song.info.genre;
  821. out.url = song.info.url;
  822. out.comments = song.info.comments;
  823. // (FL's TDateTime: days since 1899-12-30; the Unix epoch is day 25569)
  824. if (song.info.created > 0.0)
  825. out.createdDays = song.info.created / 86400.0 + 25569.0;
  826. out.workDays = song.info.workSeconds / 86400.0;
  827. out.filterGroups = song.channelGroups;
  828. if (out.filterGroups.empty())
  829. out.filterGroups.push_back ("Unsorted");
  830. if (song.masterPitch != 0.0f)
  831. report.exact.push_back ("Main pitch");
  832. report.exact.push_back ("Tempo, time signature, swing, project info");
  833. }
  834. // ---- channels ----
  835. void envelopesFromAdsr (flp::Channel& c, const ChannelDef& def)
  836. {
  837. const auto& s = def.sampler;
  838. for (int k = 0; k < 5; ++k)
  839. {
  840. auto& e = c.envelopes[(std::size_t) k];
  841. e = {};
  842. e.present = true;
  843. e.flags = k == 1 ? 4 : 0;
  844. e.sustain = 50;
  845. }
  846. // the volume envelope: on when LYNX shapes the note (an untouched sampler plays the whole sample)
  847. const auto shaped = s.attack > 0.0f || s.decay > 0.0f || s.sustain < 1.0f || s.release > 0.0f;
  848. auto& v = c.envelopes[1];
  849. v.enabled = shaped;
  850. v.delay = 100;
  851. v.attack = envelopeTimeValue (s.attack);
  852. v.hold = 100;
  853. v.decay = envelopeTimeValue (s.decay);
  854. v.sustain = std::clamp (iround (s.sustain * 128.0), 0, 128);
  855. v.release = envelopeTimeValue (s.release);
  856. auto mod = [&] (flp::Channel::Envelope& e, const ModEnvelope& m, int amount) {
  857. if (m.amount == 0.0f)
  858. return;
  859. e.enabled = true;
  860. e.attack = envelopeTimeValue (m.attack);
  861. e.hold = envelopeTimeValue (m.hold);
  862. e.decay = envelopeTimeValue (m.decay);
  863. e.sustain = std::clamp (iround (m.sustain * 128.0), 0, 128);
  864. e.release = envelopeTimeValue (m.release);
  865. e.amount = amount;
  866. };
  867. mod (c.envelopes[4], s.pitchEnv, std::clamp (iround (s.pitchEnv.amount * 100.0), -2400, 2400));
  868. if (s.filterEnv.amount != 0.0f)
  869. {
  870. // the amount moves Mod X by amount/128: the octaves at the channel's cutoff
  871. const auto x = c.modX / 256.0;
  872. const auto from = filterHz (c.filterType, x);
  873. const auto target = std::clamp (from * std::pow (2.0, (double) s.filterEnv.amount), 20.0, 20000.0);
  874. const auto toX = invert ([&] (double y) { return filterHz (c.filterType, y); }, target);
  875. mod (c.envelopes[2], s.filterEnv, std::clamp (iround ((toX - x) * 128.0), -128, 128));
  876. }
  877. auto lfo = [&] (flp::Channel::Envelope& e, const ChannelLfo& l, int amount) {
  878. if (l.amount == 0.0f)
  879. return;
  880. e.lfoAmount = amount;
  881. const auto scale = l.sync ? 2.0 : 1.0;
  882. e.lfoSpeed = envelopeTimeValue (l.period / scale);
  883. e.lfoDelay = envelopeTimeValue (l.delay / scale);
  884. e.lfoAttack = envelopeTimeValue (l.attack / scale);
  885. e.lfoShape = std::clamp (l.shape, 0, 2);
  886. e.flags |= (l.sync ? 2 : 0) | (l.global ? 0x20 : 0);
  887. };
  888. lfo (c.envelopes[0], s.lfo[lfoPan], std::clamp (iround (s.lfo[lfoPan].amount * 64.0), -64, 64));
  889. lfo (c.envelopes[1], s.lfo[lfoVolume], std::clamp (iround (s.lfo[lfoVolume].amount * 128.0), -128, 128));
  890. lfo (c.envelopes[4], s.lfo[lfoPitch], std::clamp (iround (s.lfo[lfoPitch].amount * 100.0), -2400, 2400));
  891. c.envelopeCount = 5;
  892. }
  893. void filterFrom (flp::Channel& c, const SamplerSettings& s)
  894. {
  895. // LYNX's mode (0 LP, 1 BP, 2 HP, 3 BS) → FL's type (1 LP, 2 BP, 3 HP, 4 BS: the biquads)
  896. static constexpr int types[] = { 1, 2, 3, 4 };
  897. const auto open = s.cutoff >= 19999.0f && s.resonance <= 0.0f && s.filterType == 0;
  898. c.filterType = open ? 0 : types[std::clamp (s.filterType, 0, 3)];
  899. c.modX = open ? 256 : std::clamp (iround (256.0 * invert ([&] (double y) { return filterHz (c.filterType, y); }, s.cutoff)), 0, 256);
  900. // the biquads' Q = (51^(0.625·r) − 1)·0.4 + 0.1 and LYNX's resonance = (2 − 1/Q)/1.9
  901. const auto q = 1.0 / std::max (0.05, 2.0 - 1.9 * (double) s.resonance);
  902. const auto r = q <= 0.1 ? 0.0 : std::log ((q - 0.1) / 0.4 + 1.0) / std::log (51.0) / 0.625;
  903. c.modY = open ? 0 : std::clamp (iround (r * 256.0), 0, 256);
  904. }
  905. flp::Channel channel (const ChannelDef& def, int index)
  906. {
  907. flp::Channel c;
  908. c.index = index;
  909. c.name = def.name;
  910. c.colour = def.colour != 0 ? rgb (def.colour) : 0;
  911. c.icon = def.icon;
  912. // FL keeps a Smart disabled generator from running through silence, so it changes the phase of what it plays
  913. // (Thief without FL's own flags: xcorr 0.891, same spectrum; round 180d)
  914. c.wrapperFlags = def.flWrapperFlags;
  915. // a hosted plugin's window: FL's "Detached" is flag 0x4 of the same record (issue #116, REA_rodada190i.md)
  916. if (def.instrument == InstrumentKind::plugin || def.plugin.foreign.format != ForeignPlugin::Format::none)
  917. c.wrapperFlags = withFlDetached (def.flWrapperFlags >= 0 ? def.flWrapperFlags : def.smartDisable ? 0x170 : 0x150, def.plugin.detached); // (round 190ok: 0x20 = smart disable)
  918. c.enabled = ! def.muted;
  919. c.soloLock = def.soloLock;
  920. c.ghostShown = ! def.ghostHidden;
  921. c.filterGroup = def.group >= 0 && def.group < (int) out.filterGroups.size() ? def.group : 0;
  922. c.mixerTrack = std::clamp (def.mixerTrack, 0, std::max (0, (int) song.mixer.size() - 1));
  923. // levels: the same curves (channelGain both sides); the Sampler's Gain has no FL knob, it goes into the volume
  924. auto volume = def.volume;
  925. if (samplerLike (def.instrument) && def.sampler.gainDb != 0.0f)
  926. {
  927. const auto g = channelGain (volume) * std::pow (10.0f, def.sampler.gainDb / 20.0f);
  928. volume = (float) std::clamp (std::log (10.0 * g + 1.0) / std::log (11.0), 0.0, 1.0);
  929. if (g > 1.0f)
  930. report.notes.push_back (channelLabel (def, index) + ": the Sampler's Gain is above FL's channel volume range (capped at 100%)");
  931. }
  932. // a hosted plugin (round 190ad, REA_rodada190ad.md): FL's wrapper plays it √2 over LYNX's own channel law. A
  933. // project with FL's levels writes the knob as it is; one with LYNX's own gets the volume that sounds the same
  934. if (def.instrument == InstrumentKind::plugin && ! song.flPluginLevels)
  935. {
  936. const auto g = channelGain (volume) * 0.70710678f;
  937. volume = (float) std::clamp (std::log (10.0 * g + 1.0) / std::log (11.0), 0.0, 1.0);
  938. }
  939. // warp markers that bend the tempo inside the file (round 175a, M1): FL's channel stretch has one tempo
  940. if (def.sampler.keepPitch && def.sampler.stretchBeats > 0.0f
  941. && ! warpStretchMap (def.sampler.warp, 1.0e9, 1000.0, 1.0e9).empty()) // (any file length: do the markers bend)
  942. report.notes.push_back (channelLabel (def, index) + ": its warp markers are written as one tempo (FL's sample channels have none)");
  943. c.hasLevels = true;
  944. c.volume = std::clamp (iround (volume * 12800.0), 0, 12800);
  945. c.pan = std::clamp (iround (6400.0 + def.pan * 6400.0), 0, 12800);
  946. // FL's Levels adjustment (0xE5, round 190dz): the Misc tab's offsets as FL's raw values
  947. {
  948. const auto& l = def.misc.levels;
  949. c.hasLevelAdjust = true;
  950. c.panAdj = std::clamp (iround (l.pan * 6400.0), -6400, 6400);
  951. c.volAdj = std::clamp (iround (l.volume * 12800.0), 0, 25600);
  952. c.modXAdj = std::clamp (iround (l.modX * 256.0), -256, 256);
  953. c.modYAdj = std::clamp (iround (l.modY * 256.0), -256, 256);
  954. }
  955. const auto root = std::clamp (def.misc.rootNote, 0, 127);
  956. // FL's stretch PITCH knob and the header pitch add up, but do not sound the same in FL's stretcher (Thief with all
  957. // 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
  958. c.stretchPitch = def.sampler.keepPitch ? def.sampler.flStretchPitch : 0;
  959. const auto cents = iround (((double) def.sampler.pitch - (60.0 - root)) * 100.0) - c.stretchPitch;
  960. c.pitchCents = cents;
  961. c.rootNote = root;
  962. c.fineTune = iround (def.misc.fineTune);
  963. c.pitchRange = std::clamp (std::max (def.misc.pitchRange, (std::abs (cents) + 99) / 100), 0, 48);
  964. c.swingMix = std::clamp (iround (def.swingMix * 128.0), 0, 128);
  965. c.cutGroup = def.cutGroup;
  966. c.cutBy = def.cutBy;
  967. c.maxVoices = std::clamp (def.maxPolyphony, 0, 128);
  968. c.monoFlag = def.misc.mono;
  969. c.portaFlag = def.misc.porta;
  970. c.slideTime = slideTimeValue (def.misc.portaBeats);
  971. // Misc: time, echo, tracking, the root note keyboard, the arpeggiator (REA round 146b)
  972. const auto& m = def.misc;
  973. c.timeShift = m.shiftBeats > 0.0f ? channelmiscTime (m.shiftBeats) : 0;
  974. c.timeGate = m.gateBeats > 0.0f ? std::min (1445, channelmiscTime (m.gateBeats)) : 1447;
  975. c.fullPorta = m.fullPorta;
  976. c.echoFeedback = std::clamp (iround (m.echo.feedback * 12800.0), 0, 25600);
  977. c.echoPan = std::clamp (iround (6400.0 + m.echo.pan * 6400.0), 0, 12800);
  978. c.echoPitch = iround (m.echo.pitch);
  979. c.echoes = m.echo.echoes;
  980. c.echoTime = std::max (1, iround (m.echo.timeBeats * 192.0));
  981. c.echoModX = std::clamp (iround (128.0 + m.echo.modX * 128.0), 0, 256);
  982. c.echoModY = std::clamp (iround (128.0 + m.echo.modY * 128.0), 0, 256);
  983. c.delayFlags = (m.echo.pingPong ? 2 : 0) | (m.echo.fat ? 4 : 0);
  984. for (int k = 0; k < 2; ++k)
  985. {
  986. const auto& from = k == 0 ? m.velocity : m.key;
  987. auto& t = c.tracking[(std::size_t) k];
  988. t.present = true;
  989. t.mid = from.mid;
  990. t.pan = iround (from.pan * 64.0);
  991. t.modX = iround (from.modX * 256.0);
  992. t.modY = iround (from.modY * 256.0);
  993. }
  994. c.trackingCount = 2;
  995. c.mainPitch = m.mainPitch;
  996. c.addToKey = m.addToKey;
  997. // FL's directions 1 up, 2 down, 3 bounce, 4 sticky, 5 random; LYNX: 4 random, 5 sticky
  998. static constexpr int toFl[] = { 0, 1, 2, 3, 5, 4 };
  999. const auto& a = def.arp;
  1000. c.arpDirection = toFl[std::clamp (a.direction, 0, 5)];
  1001. c.arpRange = std::clamp (a.range, 1, 4);
  1002. c.arpTime = channelmiscTime (a.stepBeats);
  1003. c.arpGate = std::clamp (iround (a.gate * 48.0), 1, 128);
  1004. c.arpSlide = a.slide;
  1005. c.arpRepeat = a.octaveRepeat;
  1006. c.arpChord = ! a.chordSustain ? -2 : a.chord == std::vector<int> { 0 } ? 0 : -1;
  1007. if (a.enabled() && ! a.chord.empty() && a.chord != std::vector<int> { 0 })
  1008. report.notes.push_back (channelLabel (def, index) + ": the arpeggiator's chord is written as Auto");
  1009. if (def.hasKeyRegion())
  1010. {
  1011. c.keyRegionLow = def.keyLow;
  1012. c.keyRegionHigh = def.keyHigh;
  1013. }
  1014. // the channel filter and articulators
  1015. if (flvoiceblock::has (def))
  1016. {
  1017. // round 190rt (issue #311): a generator that carries the plugin voice processor's block (3x Osc, DX10,
  1018. // Granulizer, BeepMap) — FL loads the channel's records into it, so they are the block's own (its Envelope /
  1019. // instrument tab), not the Sampler's ADSR
  1020. const auto block = flvoiceblock::bytes (def);
  1021. for (int k = 0; k < 5; ++k)
  1022. {
  1023. auto& e = c.envelopes[(std::size_t) k];
  1024. e.present = true;
  1025. e.rawSize = 68;
  1026. std::memcpy (e.raw.data(), block.data() + 0x44 * k, 68);
  1027. }
  1028. c.envelopeCount = 5;
  1029. std::memcpy (&c.modX, block.data() + 0x15c, 4);
  1030. std::memcpy (&c.modY, block.data() + 0x160, 4);
  1031. std::memcpy (&c.filterType, block.data() + 0x168, 4);
  1032. }
  1033. else if (def.sampler.flChannel.size() >= 88)
  1034. {
  1035. // FL's own records as the import stored them (REA_rodada76)
  1036. for (int k = 0; k < 5; ++k)
  1037. {
  1038. auto& e = c.envelopes[(std::size_t) k];
  1039. e.present = true;
  1040. e.rawSize = 68;
  1041. std::memcpy (e.raw.data(), def.sampler.flChannel.data() + 17 * k, 68);
  1042. }
  1043. c.envelopeCount = 5;
  1044. c.modX = def.sampler.flChannel[85];
  1045. c.modY = def.sampler.flChannel[86];
  1046. c.filterType = def.sampler.flChannel[87];
  1047. }
  1048. else
  1049. {
  1050. filterFrom (c, def.sampler);
  1051. envelopesFromAdsr (c, def);
  1052. if (def.sampler.flVolumeEnvelope.size() >= 17)
  1053. {
  1054. auto& e = c.envelopes[1];
  1055. e.rawSize = 68;
  1056. std::memcpy (e.raw.data(), def.sampler.flVolumeEnvelope.data(), 68);
  1057. }
  1058. }
  1059. // the generator
  1060. if (def.instrument == InstrumentKind::layer)
  1061. {
  1062. c.type = flp::ChannelType::layer;
  1063. c.layerChildren = def.layer.children;
  1064. c.layerFlags = (def.layer.random ? 1 : 0) | (def.layer.crossfade ? 2 : 0) | (def.layer.sequential ? 4 : 0);
  1065. c.layerFade = std::clamp (iround (def.layer.fade * 256.0), 0, 256);
  1066. report.exact.push_back (channelLabel (def, index) + ": Layer");
  1067. }
  1068. else if (samplerLike (def.instrument) && ! originMatches (def))
  1069. {
  1070. c.type = def.instrument == InstrumentKind::audioClip ? flp::ChannelType::audioClip : flp::ChannelType::sampler;
  1071. sampler (c, def);
  1072. report.exact.push_back (channelLabel (def, index) + (def.instrument == InstrumentKind::audioClip ? ": audio clip" : ": Sampler"));
  1073. }
  1074. else if (def.instrument == InstrumentKind::plugin || def.plugin.foreign.format != ForeignPlugin::Format::none)
  1075. {
  1076. // (also a stand-in whose FL plugin is not on this PC: its wrapper goes back as FL wrote it)
  1077. c.type = flp::ChannelType::instrument;
  1078. if (const auto record = hosted (def.plugin, true))
  1079. {
  1080. c.pluginName = "Fruity Wrapper";
  1081. c.pluginState = writeWrapper (*record, true, def.plugin.foreign.format == ForeignPlugin::Format::none ? &def.plugin : nullptr);
  1082. report.exact.push_back (channelLabel (def, index) + ": " + record->name + " (Fruity Wrapper)");
  1083. }
  1084. else
  1085. report.dropped.push_back (channelLabel (def, index) + ": plugin '" + def.plugin.name + "' (not found)");
  1086. }
  1087. else if (const auto name = flGeneratorName (def); ! name.empty())
  1088. {
  1089. c.type = flp::ChannelType::instrument;
  1090. c.pluginName = name;
  1091. c.pluginState = originMatches (def) && ! def.flOrigin.state.empty() ? def.flOrigin.state : def.pluginState;
  1092. // a dancer edited in LYNX keeps LYNX's text state: FL gets its own bytes (the sprite sheet's file included)
  1093. if (def.instrument == InstrumentKind::fruitydance)
  1094. if (const auto dancer = dance::fromState (c.pluginState))
  1095. c.pluginState = dance::toFl (*dancer, options.flFactoryData);
  1096. if (c.pluginState.empty() && def.instrument == InstrumentKind::threeosc)
  1097. c.pluginState = defaultThreeOscState();
  1098. if (def.instrument == InstrumentKind::fpc) // the kit as FPC's state (core/Fpc.h: FL's own bytes when nothing was edited)
  1099. if (const auto kit = fpc::read (c.pluginState))
  1100. c.pluginState = fpc::write (*kit);
  1101. const auto* g = generatorFor (def.instrument);
  1102. if ((g != nullptr && g->channelSample) || samplerLike (def.instrument))
  1103. c.samplePath = path (def.samplePath);
  1104. if (samplerLike (def.instrument))
  1105. sampler (c, def);
  1106. report.exact.push_back (channelLabel (def, index) + ": " + name);
  1107. }
  1108. else
  1109. {
  1110. // left for the report (option A renders these before the conversion)
  1111. c.type = flp::ChannelType::sampler;
  1112. report.dropped.push_back (channelLabel (def, index) + ": " + instrumentName (def.instrument) + " (no FL equivalent)");
  1113. }
  1114. if (flTrialSaved (c.wrapperFlags))
  1115. {
  1116. if (keepsTrialMark (def, c.pluginName))
  1117. report.notes.push_back (trialNote (channelLabel (def, index), c.pluginName == "Fruity Wrapper" ? def.plugin.name : c.pluginName));
  1118. else
  1119. c.wrapperFlags &= ~flTrialSavedFlag;
  1120. }
  1121. return c;
  1122. }
  1123. static int channelmiscTime (double beats)
  1124. {
  1125. // channelmisc::flTimeKnobValue (ChannelMiscFx.h)
  1126. if (beats <= 0.0)
  1127. return 0;
  1128. return (int) std::lround (1024.0 * std::log (beats * 192.0 * 26.0 / 48.0 + 1.0) / std::log (27.0));
  1129. }
  1130. void sampler (flp::Channel& c, const ChannelDef& def)
  1131. {
  1132. const auto& s = def.sampler;
  1133. c.samplePath = path (def.samplePath);
  1134. const auto& p = s.precompute;
  1135. c.fxFlags = (p.fadeStereo ? 1 : 0) | (s.reverse ? 2 : 0) | (p.clip ? 4 : 0) | (p.swapStereo ? 0x100 : 0);
  1136. c.fadeIn = p.fadeIn;
  1137. c.fadeOut = p.fadeOut;
  1138. c.removeDc = p.removeDc;
  1139. c.normalize = p.normalize;
  1140. c.reversePolarity = p.reversePolarity;
  1141. c.crossfade = p.crossfade;
  1142. c.trim = p.trim;
  1143. c.pingPong = p.pingPong;
  1144. c.boost = p.boost;
  1145. c.eq = p.eq;
  1146. c.ringMix = p.ringMix;
  1147. c.ringFreq = p.ringFreq;
  1148. c.stereoDelay = p.stereoDelay;
  1149. c.cutoff = p.cutoff;
  1150. c.resonance = p.resonance;
  1151. c.reverb = p.reverb;
  1152. c.reverbType = p.reverbType;
  1153. c.pogo = p.pogo;
  1154. c.declickMode = s.declickMode;
  1155. c.sampleFlags = samplerpage::contentFlags (s); // (round 190dh: FL's Content options and Use loop points)
  1156. if (s.hasLoopOverride())
  1157. c.loopStart = s.loopStart, c.loopEnd = s.loopEnd;
  1158. // the region: FL's end is a fraction of what follows the start (REA_rodada167h §2)
  1159. const auto start = std::clamp ((double) s.regionStart, 0.0, 1.0);
  1160. const auto end = std::clamp ((double) s.regionEnd, start, 1.0);
  1161. c.sampleStart = start;
  1162. c.sampleEnd = start < 1.0 ? (end - start) / (1.0 - start) : 1.0;
  1163. c.startOffset = std::clamp ((double) s.startOffset, 0.0, 1.0);
  1164. // the time-stretch: the whole sample lasts TIME/192 beats × MUL's factor (round 190dh: MUL kept, TIME without it)
  1165. if (s.stretchBeats > 0.0f)
  1166. {
  1167. c.stretchTime = samplerpage::stretchTime (s) * 192.0f;
  1168. c.stretchMul = std::clamp (s.stretchMul, -20000, 20000);
  1169. }
  1170. c.stretchMode = flStretchMode (s);
  1171. if (s.cut && c.cutGroup == 0 && c.cutBy == 0)
  1172. c.cutGroup = c.cutBy = freeCutGroup++; // "cut itself"
  1173. }
  1174. int freeCutGroup = 1;
  1175. std::optional<ForeignPlugin> hosted (const PluginRef& ref, bool instrument) const
  1176. {
  1177. if (ref.foreign.format != ForeignPlugin::Format::none)
  1178. return ref.foreign; // still the FL original, byte for byte
  1179. if (options.pluginRecord)
  1180. return options.pluginRecord (ref, instrument);
  1181. return std::nullopt;
  1182. }
  1183. void channels()
  1184. {
  1185. for (const auto& c : song.channels)
  1186. freeCutGroup = std::max ({ freeCutGroup, c.cutGroup + 1, c.cutBy + 1 });
  1187. for (int i = 0; i < (int) song.channels.size(); ++i)
  1188. out.channels.push_back (channel (song.channels[(std::size_t) i], i));
  1189. }
  1190. // ---- automation targets ----
  1191. std::optional<flp::ControlId> controlFor (const AutomationTarget& t, std::function<float (float)>* valueMap = nullptr) const
  1192. {
  1193. flp::ControlId id;
  1194. switch (t.kind)
  1195. {
  1196. case AutomationTargetKind::tempo:
  1197. id.raw = flp::ControlId::tempo;
  1198. // (LYNX's tempo target is FL's whole range, 10…522 BPM: the clip's range below is the whole range too)
  1199. return id;
  1200. case AutomationTargetKind::channelVolume:
  1201. case AutomationTargetKind::channelPan:
  1202. if (t.index < 0 || t.index >= (int) song.channels.size())
  1203. return std::nullopt;
  1204. id.raw = ((std::uint32_t) t.index << 16) | (t.kind == AutomationTargetKind::channelPan ? 1u : 0u);
  1205. return id;
  1206. case AutomationTargetKind::channelAdjust: // FL's channel parameters 0x10…0x14 (round 190dz)
  1207. if (t.index < 0 || t.index >= (int) song.channels.size() || ! leveladjust::valid (t.param))
  1208. return std::nullopt;
  1209. id.raw = ((std::uint32_t) t.index << 16) | (std::uint32_t) (0x10 + t.param);
  1210. return id;
  1211. case AutomationTargetKind::channelParam:
  1212. if (t.param == channelPitchParam && t.index >= 0 && t.index < (int) song.channels.size()) // (round 190py: PITCH)
  1213. {
  1214. id.raw = ((std::uint32_t) t.index << 16) | 4u;
  1215. return id;
  1216. }
  1217. if (t.index < 0 || t.index >= (int) song.channels.size() || song.channels[(std::size_t) t.index].instrument != InstrumentKind::plugin
  1218. || out.channels[(std::size_t) t.index].pluginName != "Fruity Wrapper")
  1219. return std::nullopt;
  1220. id.raw = ((std::uint32_t) t.index << 16) | (std::uint32_t) (flp::ControlId::pluginParamBase + t.param);
  1221. return id;
  1222. case AutomationTargetKind::mixerVolume:
  1223. id.raw = mixerId (t.index, 0, flp::ControlId::mixerVolume);
  1224. return id;
  1225. case AutomationTargetKind::mixerPan:
  1226. id.raw = mixerId (t.index, 0, flp::ControlId::mixerPan);
  1227. return id;
  1228. case AutomationTargetKind::mixerSend:
  1229. id.raw = mixerId (t.index, 0, flp::ControlId::mixerSendBase + t.slot);
  1230. return id;
  1231. case AutomationTargetKind::effectMix:
  1232. case AutomationTargetKind::effectParam:
  1233. {
  1234. const auto found = slotMap.find ({ t.index, t.slot });
  1235. if (found == slotMap.end())
  1236. return std::nullopt;
  1237. if (t.kind == AutomationTargetKind::effectMix)
  1238. {
  1239. id.raw = mixerId (t.index, found->second, 0x1F01);
  1240. return id;
  1241. }
  1242. const auto& plugin = slotPlugin.at ({ t.index, t.slot });
  1243. auto param = t.param;
  1244. // round 190re (0.1.32 regression sweep): Gross Beat's 9 parameters, which the import has given their own
  1245. // target since round 190py (FL's normalised value, the scratch dial turned round), go back as FL's own;
  1246. // they were left out ("its target has no FL equivalent": Asher Postman's two clips)
  1247. if (plugin == "Gross Beat" && song.mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind == EffectKind::grossBeat && t.param >= 0 && t.param < grossbeat::paramCount)
  1248. {
  1249. if (valueMap != nullptr && t.param == grossbeat::scratchParam)
  1250. *valueMap = [] (float v) { return 1.0f - v; };
  1251. id.raw = mixerId (t.index, found->second, flp::ControlId::pluginParamBase + t.param);
  1252. return id;
  1253. }
  1254. if (plugin != "Fruity Wrapper")
  1255. {
  1256. // FL's parameter whose map lands on this LYNX parameter (FlEffects' effectParamFromFl), and the
  1257. // inverse of its value conversion
  1258. param = -1;
  1259. for (int k = 0; k < 512 && param < 0; ++k)
  1260. if (const auto map = effectParamFromFl (plugin, k); map && map->param == t.param)
  1261. {
  1262. param = k;
  1263. if (valueMap != nullptr && map->convert)
  1264. {
  1265. const auto convert = map->convert;
  1266. const auto increasing = convert (1.0f) >= convert (0.0f);
  1267. *valueMap = [convert, increasing] (float v) {
  1268. return (float) invert ([&] (double y) { return (double) convert ((float) y); }, v, increasing);
  1269. };
  1270. }
  1271. }
  1272. if (param < 0)
  1273. return std::nullopt;
  1274. }
  1275. id.raw = mixerId (t.index, found->second, flp::ControlId::pluginParamBase + param);
  1276. return id;
  1277. }
  1278. default: return std::nullopt;
  1279. }
  1280. }
  1281. // A hosted effect's side input (slot.sidechain, picked with LYNX's "SC" picker or set by input 2's index) as FL's
  1282. // input 2 index (round 189j): its place in insert t's inputs list as written here — [t, then every insert routed
  1283. // to t, the level-0 sidechain routes included, ascending] (REA_rodada22 §1, core/MixerOps.h insertInputs). An
  1284. // index already there that names another insert is replaced: the slot's source is what LYNX plays. True when
  1285. // `inputs` changed.
  1286. bool withSideIndex (std::vector<PluginOutputRoute>& inputs, int t, int source) const
  1287. {
  1288. if (t <= 0 || source <= 0 || source == t || source >= (int) song.mixer.size())
  1289. return false;
  1290. auto k = 1;
  1291. for (int u = 1; u < source; ++u)
  1292. if (u != t && (song.routes (u, t) || feedsSideInput (u, t)))
  1293. ++k;
  1294. if (inputs.size() > 1 && inputs[1].offset == k && inputs[1].isActive (true))
  1295. return false;
  1296. if (inputs.size() < 2)
  1297. inputs.resize (2);
  1298. inputs[1] = { k, inputs[1].active == 0 ? (std::int8_t) -1 : inputs[1].active };
  1299. return true;
  1300. }
  1301. bool feedsSideInput (int source, int t) const
  1302. {
  1303. const auto& fx = song.mixer[(std::size_t) t].effects;
  1304. return std::any_of (fx.begin(), fx.end(), [source] (const EffectSlot& e) { return e.sidechain == source || e.sidechain2 == source; });
  1305. }
  1306. // the inserts whose effects take insert `source` as a side-chain input (LYNX keeps the source, FL a level-0 route)
  1307. std::vector<int> sidechainTargets (int source) const
  1308. {
  1309. std::vector<int> out;
  1310. for (int u = 1; u < (int) song.mixer.size(); ++u)
  1311. if (u != source)
  1312. for (const auto& fx : song.mixer[(std::size_t) u].effects)
  1313. if ((fx.sidechain == source || fx.sidechain2 == source) && std::find (out.begin(), out.end(), u) == out.end())
  1314. out.push_back (u);
  1315. return out;
  1316. }
  1317. // ---- patterns ----
  1318. bool playsSample (int channel) const
  1319. {
  1320. for (const auto& c : out.channels)
  1321. if (c.index == channel)
  1322. return c.type == flp::ChannelType::sampler || c.type == flp::ChannelType::audioClip;
  1323. return false;
  1324. }
  1325. // round 190rt (issue #309): the channel's FL volume envelope is on — FL then sends no note-off for a step note
  1326. // (length 0): it sounds on past its step and past the channel's next notes (FL 2026 renders rel50 / rel50-2steps in
  1327. // issues309_190rt/art), so a one-step LYNX note, which LYNX releases after its step, goes out with its length
  1328. bool volumeEnvelopeOn (int channel) const
  1329. {
  1330. for (const auto& c : out.channels)
  1331. if (c.index == channel)
  1332. {
  1333. const auto& e = c.envelopes[1];
  1334. if (! e.present)
  1335. return false;
  1336. if (e.rawSize >= 8)
  1337. {
  1338. std::int32_t on = 0;
  1339. std::memcpy (&on, e.raw.data() + 4, 4);
  1340. return on != 0;
  1341. }
  1342. return e.enabled;
  1343. }
  1344. return false;
  1345. }
  1346. void patterns()
  1347. {
  1348. for (int i = 0; i < (int) song.patterns.size(); ++i)
  1349. {
  1350. const auto& src = song.patterns[(std::size_t) i];
  1351. flp::Pattern p;
  1352. p.index = i + 1;
  1353. p.name = src.name;
  1354. if (src.colour != 0)
  1355. p.colour = rgb (src.colour);
  1356. p.fixedLength = src.lengthTicks > 0 ? ticks (src.lengthTicks) : 0;
  1357. p.loopOn = src.loopOn;
  1358. p.loopMode = (int) src.loopMode;
  1359. for (const auto& l : src.channelLoops)
  1360. p.channelLoops.push_back ({ l.channel, l.setting });
  1361. for (const auto& m : src.markers)
  1362. p.markers.push_back (marker (m));
  1363. // round 190pm (P19): ratchets FL's repeat rates hold exactly go as that rate (FL's own note repeat); the others as
  1364. // their strikes, notes of their own. A Condition has no FL equivalent: the note plays on every pass
  1365. std::vector<Note> written;
  1366. written.reserve (src.notes.size());
  1367. for (const auto& n : src.notes)
  1368. {
  1369. ratchetsAsRate += n.hasRatchets() && noteconditions::flRateFor (n) > 0 ? 1 : 0;
  1370. conditions += n.hasCondition() ? 1 : 0;
  1371. if (n.hasRatchets() && noterepeat::ratchetCount (n) > 1 && noteconditions::flRateFor (n) == 0 && n.length >= noterepeat::ratchetCount (n))
  1372. {
  1373. ++ratchetsAsNotes;
  1374. for (const auto& s : noteconditions::ratchetNotes (n))
  1375. written.push_back (s);
  1376. }
  1377. else
  1378. written.push_back (n);
  1379. }
  1380. for (const auto& n : written)
  1381. {
  1382. if (n.channel < 0 || n.channel >= (int) song.channels.size())
  1383. continue;
  1384. flp::Note f;
  1385. f.position = ticks (n.start);
  1386. // a step (one step long, on the step grid): FL's step note, which the Channel Rack shows as a step.
  1387. // Only on a channel that plays a sample: FL holds a step note on a generator (3x Osc, a plugin)
  1388. // until something cuts it, so the voices pile up (FL render, round 171e)
  1389. // A slide note keeps its length (length 0 would move the notes at once) unless it has none (issue #272)
  1390. // (round 190rt: not on a LYNX Sampler whose ADSR turns FL's volume envelope on — FL would hold the step;
  1391. // an FL project's own Sampler keeps its steps as steps, so its round trip stays FL's: QUEUE-0.1.33 #24)
  1392. const auto lynxEnvelope = volumeEnvelopeOn (n.channel) && song.channels[(std::size_t) n.channel].sampler.flChannel.empty();
  1393. const auto step = (! n.slide && n.length == ticksPerStep && n.start % ticksPerStep == 0 && playsSample (n.channel) && ! lynxEnvelope)
  1394. || n.heldStep() || stepslide::is (n);
  1395. f.length = step ? 0 : std::max<std::uint32_t> (1, ticks (n.length));
  1396. f.channel = (std::uint16_t) n.channel;
  1397. f.key = (std::uint16_t) std::clamp (n.key, 0, 131);
  1398. f.velocity = (std::uint8_t) std::clamp (iround (n.velocity * 128.0), 0, 128);
  1399. f.pan = (std::uint8_t) std::clamp (iround (64.0 + n.pan * 64.0), 0, 128);
  1400. f.finePitch = (std::uint8_t) std::clamp (iround (120.0 + n.finePitch), 0, 240);
  1401. f.release = (std::uint8_t) std::clamp (iround (n.release * 128.0), 0, 128);
  1402. f.modX = (std::uint8_t) std::clamp (iround (n.modX * 256.0), 0, 255);
  1403. f.modY = (std::uint8_t) std::clamp (iround (n.modY * 256.0), 0, 255);
  1404. f.flags = (std::uint16_t) (0x4000 | (n.slide ? 8 : 0));
  1405. f.extra = (std::uint8_t) ((n.colour & 0x0F) | (n.porta ? 0x10 : 0) | (n.muted ? 0x20 : 0));
  1406. f.group = (std::uint16_t) std::max (0, n.group);
  1407. f.repeats = (std::uint8_t) std::clamp (n.repeat, 0, noterepeat::rateCount); // (issue #208)
  1408. if (n.repeat == 0 && n.hasRatchets())
  1409. f.repeats = (std::uint8_t) noteconditions::flRateFor (n); // (round 190pm: the ratchets at FL's rate)
  1410. p.notes.push_back (f);
  1411. }
  1412. std::stable_sort (p.notes.begin(), p.notes.end(), [] (const flp::Note& a, const flp::Note& b) { return a.position < b.position; });
  1413. for (const auto& lane : src.events)
  1414. {
  1415. std::function<float (float)> map;
  1416. const auto id = controlFor (lane.target, &map);
  1417. if (! id)
  1418. {
  1419. if (lane.target.kind != AutomationTargetKind::none)
  1420. report.dropped.push_back ("Pattern '" + src.name + "': an event lane (its target has no FL equivalent)");
  1421. continue;
  1422. }
  1423. for (const auto& e : lane.events)
  1424. p.controlEvents.push_back ({ ticks (e.tick), *id, rawValue (lane.target, map ? map (e.value) : e.value, &song) });
  1425. }
  1426. out.patterns.push_back (std::move (p));
  1427. }
  1428. report.exact.push_back (std::to_string (song.patterns.size()) + " patterns (notes with every property, names, colours)");
  1429. if (ratchetsAsRate > 0)
  1430. report.exact.push_back (std::to_string (ratchetsAsRate) + " note(s) with ratchets: as FL's note repeat at the same rate");
  1431. if (ratchetsAsNotes > 0)
  1432. report.notes.push_back (std::to_string (ratchetsAsNotes)
  1433. + " note(s) with ratchets: written as their strikes, notes of their own (FL's repeat rates can't hold them)");
  1434. if (conditions > 0)
  1435. report.notes.push_back (std::to_string (conditions) + " note(s) with a Condition (first pass, fill, cycle): FL has none, they play on every pass");
  1436. }
  1437. int ratchetsAsRate = 0, ratchetsAsNotes = 0, conditions = 0; // (round 190pm)
  1438. flp::TimeMarker marker (const Marker& m) const
  1439. {
  1440. flp::TimeMarker t;
  1441. t.position = ticks (m.tick);
  1442. t.name = m.name;
  1443. if (m.isSignature())
  1444. {
  1445. t.type = 8;
  1446. t.numerator = m.numerator;
  1447. t.denominator = m.denominator;
  1448. }
  1449. else
  1450. t.type = m.action;
  1451. if (m.action == Marker::keyScale) // round 190nu: the key, as FL 2026 writes it
  1452. {
  1453. t.keyRoot = m.keyRoot;
  1454. t.keyScale = notetools::flMenuScaleIndex (m.keyFlScale); // (LYNX's index -> FL's; −1 / −2 unchanged)
  1455. if (const auto key = keyregions::keyOf (m))
  1456. t.keyMask = keyregions::flOutOfScaleMask (*key);
  1457. }
  1458. return t;
  1459. }
  1460. // ---- automation clips: FL channels after the song's ----
  1461. void automations()
  1462. {
  1463. for (int a = 0; a < (int) song.automations.size(); ++a)
  1464. {
  1465. const auto& src = song.automations[(std::size_t) a];
  1466. if (src.isLive())
  1467. {
  1468. report.dropped.push_back ("Automation '" + src.name + "': a live controller link");
  1469. continue;
  1470. }
  1471. std::function<float (float)> map;
  1472. auto id = controlFor (src.target, &map);
  1473. // round 190ov: a clip with target links (FL's clip linked to several controls, or LYNX's "Crossfade with"):
  1474. // one 0xE3 record per link FL has, its formula in an 0xE6 after it; the points are the clip's own value, which
  1475. // FL sends each link
  1476. std::vector<flp::AutomationLink> linkIds; // (channel set below; each with its formula, FL's 0xE6)
  1477. if (! src.links.empty())
  1478. {
  1479. map = {};
  1480. for (const auto& link : src.links)
  1481. {
  1482. if (const auto linkId = controlFor (link.target))
  1483. {
  1484. if (std::find_if (linkIds.begin(), linkIds.end(), [&] (const flp::AutomationLink& x) { return x.target.raw == linkId->raw; }) == linkIds.end())
  1485. linkIds.push_back ({ 0, *linkId, link.formula });
  1486. }
  1487. else if (link.target.kind != AutomationTargetKind::none)
  1488. report.dropped.push_back ("Automation '" + src.name + "': a target link with no FL equivalent");
  1489. }
  1490. id = linkIds.empty() ? std::nullopt : std::optional<flp::ControlId> (linkIds.front().target);
  1491. }
  1492. if (! id && src.target.kind != AutomationTargetKind::none)
  1493. {
  1494. report.dropped.push_back ("Automation '" + src.name + "': its target has no FL equivalent");
  1495. continue;
  1496. }
  1497. // (no target at all: FL's own unlinked automation clip, kept as one)
  1498. flp::Channel c;
  1499. c.index = (int) out.channels.size();
  1500. c.type = flp::ChannelType::automationClip;
  1501. c.name = src.name;
  1502. c.colour = src.colour != 0 ? rgb (src.colour) : 0; // (round 190ig: the clip's colour; none = FL's default)
  1503. // an automation clip's channel levels are its range: pan = minimum, volume = maximum (of 12800, in the
  1504. // target's whole range) [DATA: FL's tempo clips keep 1250…4250 = 60…180 BPM; FL 2026 played a clip written
  1505. // with a channel's default levels over 6400…10000: round 171e, FL render]. Always the whole range here.
  1506. // Round 190ow (PAT-7): the clip's own MIN / MAX (the rack row's knobs), the points written in FL's 0..1 of the
  1507. // range they were made in (pointsMin / pointsMax: an FL clip's own levels; a LYNX clip's whole range, which
  1508. // writes what the earlier export did). FL re-ranges them into MIN..MAX as LYNX does.
  1509. c.hasLevels = true;
  1510. c.pan = iround (std::clamp (src.rangeMin, 0.0f, 1.0f) * 12800.0);
  1511. c.volume = iround (std::clamp (src.rangeMax, 0.0f, 1.0f) * 12800.0);
  1512. c.enabled = ! src.muted; // (round 190ow: the mute light)
  1513. const auto pointsSpan = (double) src.pointsMax - (double) src.pointsMin;
  1514. const auto unranged = src.pointsMin == 0.0f && src.pointsMax == 1.0f;
  1515. const auto flValue = [&] (float v) {
  1516. const auto raw = (double) (map ? map (v) : v);
  1517. if (unranged)
  1518. return std::clamp (raw, 0.0, 1.0);
  1519. return std::abs (pointsSpan) > 1.0e-9 ? std::clamp ((raw - src.pointsMin) / pointsSpan, 0.0, 1.0) : 0.0;
  1520. };
  1521. for (std::size_t i = 0; i < src.points.size(); ++i)
  1522. {
  1523. const auto& pt = src.points[i];
  1524. flp::AutomationPoint fp;
  1525. fp.position = (double) pt.tick / ppq;
  1526. fp.value = flValue (pt.value);
  1527. // FL's curve sits on the segment ending at the point (FlpImport: previous.tension = −p.tension)
  1528. fp.tension = i > 0 ? 0.0f - src.points[i - 1].tension : 0.0f; // (0 − t: a straight segment writes +0)
  1529. fp.curve = i > 0 ? flCurveOf (src.points[i - 1]) : (std::uint8_t) 0;
  1530. c.automation.push_back (fp);
  1531. }
  1532. if (c.automation.empty())
  1533. c.automation.push_back ({ 0.0, flValue (song.targetValue (src.target)), 0.0f });
  1534. // FL's clip LFO (round 177b): the fields back as they were read; the level carries the clip's range (FL scales
  1535. // the LFO by its channel range, written whole here)
  1536. if (const auto& lfo = src.lfo; ! lfo.isDefault())
  1537. {
  1538. auto& f = c.automationLfo;
  1539. f.present = true;
  1540. f.enabled = lfo.on ? -1 : 0;
  1541. // (round 190ow: FL scales the level by the channel range written above, MIN..MAX; LYNX's LFO by its
  1542. // `range` in the points' range, re-ranged with them)
  1543. const auto lfoScale = unranged || std::abs (pointsSpan) < 1.0e-9 ? (double) lfo.range : (double) lfo.range / pointsSpan;
  1544. f.level = std::abs (lfoScale - 1.0) < 1.0e-6 ? lfo.level : (int) std::lround (lfo.level * lfoScale);
  1545. f.mode = lfo.add ? 1 : 0;
  1546. f.flags = lfo.flags;
  1547. f.speed = lfo.speed;
  1548. f.tension = lfo.tension;
  1549. f.skew = lfo.skew;
  1550. f.pulseWidth = lfo.pulseWidth;
  1551. f.phase = lfo.phase;
  1552. if (lfo.fl.present)
  1553. {
  1554. f.mainFlags = lfo.fl.mainFlags;
  1555. f.mainEnabled = lfo.fl.mainEnabled;
  1556. f.mainLoop = lfo.fl.mainLoop;
  1557. f.adsr = lfo.fl.adsr;
  1558. f.lfoLoop = lfo.fl.lfoLoop;
  1559. }
  1560. f.points.clear();
  1561. for (std::size_t i = 0; i < lfo.amp.size(); ++i)
  1562. f.points.push_back ({ (double) lfo.amp[i].tick / ppq, (double) std::clamp (lfo.amp[i].value, 0.0f, 1.0f),
  1563. i > 0 ? 0.0f - lfo.amp[i - 1].tension : 0.0f, i > 0 ? flCurveOf (lfo.amp[i - 1]) : (std::uint8_t) 0 });
  1564. if (lfo.amp == lfo.fl.rawAmp && lfo.fl.rawPoints.size() == lfo.amp.size() * 24)
  1565. f.rawPoints = lfo.fl.rawPoints; // unchanged since the import: its records byte for byte
  1566. }
  1567. automationChannel[a] = c.index;
  1568. if (! linkIds.empty())
  1569. for (auto linkId : linkIds)
  1570. {
  1571. linkId.channel = c.index;
  1572. out.automationLinks.push_back (std::move (linkId));
  1573. }
  1574. else if (id)
  1575. out.automationLinks.push_back ({ c.index, *id });
  1576. out.channels.push_back (std::move (c));
  1577. }
  1578. if (! automationChannel.empty())
  1579. report.exact.push_back (std::to_string (automationChannel.size()) + " automation clips (points, curves, links)");
  1580. for (const auto& v : song.initialValues)
  1581. {
  1582. std::function<float (float)> map;
  1583. if (const auto id = controlFor (v.target, &map))
  1584. {
  1585. auto raw = rawValue (v.target, v.value, &song);
  1586. // (round 190rm) a plugin parameter's song-start value is the plugin's own integer (the import's
  1587. // flRawRange), not 0..65536: Thief's Fruity Balance volume went back as 52429 instead of 256 (205 times
  1588. // the level: FL rendered the exported song as full-scale noise / DC from its first sample)
  1589. if ((v.target.kind == AutomationTargetKind::effectParam || v.target.kind == AutomationTargetKind::channelParam)
  1590. && id->param() >= flp::ControlId::pluginParamBase)
  1591. {
  1592. std::string plugin;
  1593. if (v.target.kind == AutomationTargetKind::effectParam)
  1594. {
  1595. if (const auto it = slotPlugin.find ({ v.target.index, v.target.slot }); it != slotPlugin.end())
  1596. plugin = it->second;
  1597. }
  1598. else if (v.target.index >= 0 && v.target.index < (int) out.channels.size())
  1599. plugin = out.channels[(std::size_t) v.target.index].pluginName;
  1600. const auto grossBeat = plugin == "Gross Beat"; // (its own raw law, in rawValue)
  1601. if (const auto range = flRawRange (*id, plugin); range && ! grossBeat && range->second > range->first)
  1602. {
  1603. const auto fl = std::clamp ((double) (map ? map (v.value) : v.value), 0.0, 1.0);
  1604. raw = (std::int32_t) std::lround ((double) range->first + fl * (double) (range->second - range->first));
  1605. }
  1606. }
  1607. out.initControls.push_back ({ 0, *id, raw });
  1608. }
  1609. }
  1610. if (! song.midiLinks.empty())
  1611. report.notes.push_back ("MIDI controller links stay in LYNX (FL keeps them per machine)");
  1612. // round 190om: a note's own pitch / timbre / pressure curves (MPE, an imported module's slides, vibrato and
  1613. // arpeggios) have no FL equivalent (FL's notes hold one value each): the notes play their key
  1614. {
  1615. int curved = 0;
  1616. for (const auto& p : song.patterns)
  1617. for (const auto& n : p.notes)
  1618. curved += n.curves.has() ? 1 : 0;
  1619. if (curved > 0)
  1620. report.dropped.push_back (std::to_string (curved) + " notes' own pitch / timbre / pressure curves (FL's notes have none)");
  1621. }
  1622. }
  1623. // ---- round 190ow (DE-123): the automation clip channels' steps / notes ----
  1624. void automationNotes()
  1625. {
  1626. int written = 0;
  1627. for (int i = 0; i < (int) song.patterns.size() && i < (int) out.patterns.size(); ++i)
  1628. {
  1629. const auto& src = song.patterns[(std::size_t) i];
  1630. if (src.autoNotes.empty())
  1631. continue;
  1632. auto& p = out.patterns[(std::size_t) i];
  1633. for (const auto& n : src.autoNotes)
  1634. {
  1635. const auto it = automationChannel.find (n.channel);
  1636. if (it == automationChannel.end())
  1637. continue;
  1638. flp::Note f;
  1639. f.position = ticks (n.start);
  1640. f.length = n.length > 0 ? std::max<std::uint32_t> (1, ticks (n.length)) : 0; // (0: FL's step)
  1641. f.channel = (std::uint16_t) it->second;
  1642. f.key = (std::uint16_t) std::clamp (n.key, 0, 131);
  1643. f.velocity = (std::uint8_t) std::clamp (iround (n.velocity * 128.0), 0, 128);
  1644. f.flags = 0x4000;
  1645. f.extra = (std::uint8_t) (n.muted ? 0x20 : 0);
  1646. p.notes.push_back (f);
  1647. ++written;
  1648. }
  1649. std::stable_sort (p.notes.begin(), p.notes.end(), [] (const flp::Note& a, const flp::Note& b) { return a.position < b.position; });
  1650. }
  1651. if (written > 0)
  1652. report.exact.push_back (std::to_string (written) + " steps / notes that start automation clips");
  1653. }
  1654. // ---- round 190ow (PAT-7): FL's channel order = the Channel rack's, the automation clip channels between the others
  1655. // where their rows are (core/RackAutomation.h). Until here the channels are numbered as LYNX's (automation clips after
  1656. // them); this renumbers every channel reference of the project. A song whose rows all sit after its channels keeps
  1657. // the numbers (the file as before).
  1658. void rackOrder()
  1659. {
  1660. const auto count = (int) out.channels.size();
  1661. std::vector<int> order; // new FL index → old
  1662. std::vector<char> placed ((std::size_t) count, 0);
  1663. const auto take = [&] (int old) {
  1664. if (old >= 0 && old < count && placed[(std::size_t) old] == 0)
  1665. {
  1666. placed[(std::size_t) old] = 1;
  1667. order.push_back (old);
  1668. }
  1669. };
  1670. for (const auto& e : rackauto::order (song))
  1671. {
  1672. if (! e.automation)
  1673. take (e.index);
  1674. else if (const auto it = automationChannel.find (e.index); it != automationChannel.end())
  1675. take (it->second);
  1676. }
  1677. for (int old = 0; old < count; ++old)
  1678. take (old);
  1679. std::vector<int> to ((std::size_t) count, 0); // old → new
  1680. bool same = true;
  1681. for (int i = 0; i < count; ++i)
  1682. {
  1683. to[(std::size_t) order[(std::size_t) i]] = i;
  1684. same = same && order[(std::size_t) i] == i;
  1685. }
  1686. if (same)
  1687. return;
  1688. const auto map = [&] (int old) { return old >= 0 && old < count ? to[(std::size_t) old] : old; };
  1689. const auto mapId = [&] (flp::ControlId& id) {
  1690. if (id.isChannel() && id.channel() < count)
  1691. id.raw = ((std::uint32_t) map (id.channel()) << 16) | (id.raw & 0xFFFFu);
  1692. };
  1693. for (auto& c : out.channels)
  1694. {
  1695. c.index = map (c.index);
  1696. for (auto& child : c.layerChildren)
  1697. child = map (child);
  1698. }
  1699. std::stable_sort (out.channels.begin(), out.channels.end(), [] (const flp::Channel& a, const flp::Channel& b) { return a.index < b.index; });
  1700. for (auto& p : out.patterns)
  1701. {
  1702. for (auto& n : p.notes)
  1703. n.channel = (std::uint16_t) map (n.channel);
  1704. for (auto& l : p.channelLoops)
  1705. l.first = map (l.first);
  1706. for (auto& e : p.controlEvents)
  1707. mapId (e.id);
  1708. }
  1709. for (auto& a : out.arrangements)
  1710. {
  1711. for (auto& item : a.items)
  1712. if (item.kind == flp::PlaylistItem::Kind::channelClip)
  1713. item.index = map (item.index);
  1714. for (auto& t : a.tracks)
  1715. if (t.channel >= 0)
  1716. t.channel = map (t.channel);
  1717. }
  1718. for (auto& v : out.controls)
  1719. mapId (v.id);
  1720. for (auto& v : out.initControls)
  1721. mapId (v.id);
  1722. for (auto& l : out.automationLinks)
  1723. {
  1724. l.channel = map (l.channel);
  1725. mapId (l.target);
  1726. }
  1727. for (auto& l : out.controllerLinks)
  1728. {
  1729. mapId (l.source);
  1730. mapId (l.target);
  1731. }
  1732. for (auto& [a, c] : automationChannel)
  1733. c = map (c);
  1734. }
  1735. // ---- the Playlist ----
  1736. int sectionMarkers = 0; // (round 190ol)
  1737. int chordMarkers = 0; // (round 190pf)
  1738. void arrangements()
  1739. {
  1740. for (int i = 0; i < (int) song.arrangements.size(); ++i)
  1741. {
  1742. const auto current = i == song.currentArrangement;
  1743. const auto& arrangement = song.arrangements[(std::size_t) i];
  1744. const auto& clips = current ? song.playlist : arrangement.clips;
  1745. flp::Arrangement a;
  1746. a.index = i;
  1747. a.name = arrangement.name;
  1748. a.rowZoom = polish::flZoomForRowHeight (song.playlistRowHeight); // FL's vertical zoom, event 0xF2 (round 190oo, PAT-6)
  1749. // round 190ol: FL has no Sections lane: each section becomes a plain time marker at its start, named after it
  1750. int fromSections = 0, fromChords = 0;
  1751. // round 190pf: nor a Chord lane: each chord becomes a plain time marker at its start, named after it ("Am7")
  1752. const auto withSections = sections::markersWithSections (current ? song.markers() : arrangement.markers, arrangement.sections, &fromSections);
  1753. for (const auto& m : arrangement.chords.empty() ? withSections : chordlane::markersWithChords (withSections, arrangement.chords, &fromChords))
  1754. a.markers.push_back (marker (m));
  1755. sectionMarkers += fromSections;
  1756. chordMarkers += fromChords;
  1757. for (const auto& clip : clips)
  1758. if (auto item = playlistItem (clip))
  1759. a.items.push_back (*item);
  1760. std::stable_sort (a.items.begin(), a.items.end(), [] (const flp::PlaylistItem& x, const flp::PlaylistItem& y) { return x.position < y.position; });
  1761. for (int t = 0; t < (int) song.playlistTracks.size() && t < 500; ++t)
  1762. a.tracks.push_back (trackInfo (song.playlistTracks[(std::size_t) t], t, song.playlistRowHeight));
  1763. out.arrangements.push_back (std::move (a));
  1764. }
  1765. report.exact.push_back ("Playlist: " + std::to_string (song.arrangements.size()) + " arrangement(s), tracks, markers");
  1766. if (std::any_of (song.arrangements.begin(), song.arrangements.end(), [] (const Arrangement& x) { return ! x.sections.empty(); }))
  1767. report.notes.push_back ("Song sections: FL has no Sections lane; " + std::to_string (sectionMarkers)
  1768. + " time marker(s) at the sections' starts, named after them (moving a section in FL moves only its marker)");
  1769. if (std::any_of (song.arrangements.begin(), song.arrangements.end(), [] (const Arrangement& x) { return ! x.chords.empty(); }))
  1770. report.notes.push_back ("Chord lane: FL has no chord track; " + std::to_string (chordMarkers)
  1771. + " time marker(s) at the chords' starts, named after them");
  1772. if (std::any_of (song.channels.begin(), song.channels.end(), [] (const ChannelDef& c) { return c.followChords != 0; }))
  1773. report.notes.push_back ("Chord lane: the channels that follow it play their patterns' own notes in FL");
  1774. }
  1775. std::optional<flp::PlaylistItem> playlistItem (const Clip& clip) const
  1776. {
  1777. flp::PlaylistItem item;
  1778. item.track = std::clamp (clip.track, 0, 499);
  1779. item.position = ticks (clip.start);
  1780. item.length = std::max<std::uint32_t> (1, ticks (clip.length));
  1781. // FL's clip mute: bit 0x2000 of the item flags (issue #110, REA round 182e)
  1782. item.flags = (std::uint16_t) (flp::PlaylistItem::defaultFlags | (clip.muted ? flp::PlaylistItem::mutedFlag : 0));
  1783. switch (clip.kind)
  1784. {
  1785. case ClipKind::pattern:
  1786. if (clip.pattern < 0 || clip.pattern >= (int) song.patterns.size())
  1787. return std::nullopt;
  1788. item.kind = flp::PlaylistItem::Kind::pattern;
  1789. item.index = clip.pattern + 1;
  1790. item.gain = 0.0f;
  1791. if (clip.offset > 0)
  1792. {
  1793. item.patternStartTick = (std::int32_t) ticks (clip.offset);
  1794. item.patternEndTick = (std::int32_t) ticks (clip.offset + clip.length);
  1795. }
  1796. return item;
  1797. case ClipKind::audio:
  1798. {
  1799. if (clip.channel < 0 || clip.channel >= (int) song.channels.size())
  1800. return std::nullopt;
  1801. item.kind = flp::PlaylistItem::Kind::channelClip;
  1802. item.index = clip.channel;
  1803. const auto stretch = clip.stretch > 0.0 ? clip.stretch : 1.0;
  1804. item.stretch = stretch;
  1805. item.length = std::max<std::uint32_t> (1, ticks ((std::int64_t) std::llround ((double) clip.length / stretch)));
  1806. // start / end in milliseconds (of the sample: a stretched channel's factor, REA_rodada110 §1)
  1807. const auto msPerTick = 60000.0 / song.bpm / ppq;
  1808. auto factor = 1.0;
  1809. const auto& ch = song.channels[(std::size_t) clip.channel];
  1810. if (ch.sampler.stretchBeats > 0.0f && options.sampleSeconds)
  1811. if (const auto seconds = options.sampleSeconds (ch.samplePath); seconds > 0.0)
  1812. factor = seconds * 1000.0 / (ch.sampler.stretchBeats * 60000.0 / song.bpm);
  1813. const auto offset = ((double) clip.offset + clip.offsetFraction) / stretch;
  1814. item.startOffset = (float) (offset * msPerTick * factor);
  1815. item.endOffset = (float) ((offset + (double) clip.length / stretch) * msPerTick * factor);
  1816. item.fadeInMs = (float) ((double) clip.fadeIn * msPerTick);
  1817. item.fadeOutMs = (float) ((double) clip.fadeOut * msPerTick);
  1818. item.fadeInTension = clip.fadeIn > 0 ? clip.fadeInTension : 0.0f;
  1819. item.fadeOutTension = clip.fadeOut > 0 ? clip.fadeOutTension : 0.0f;
  1820. {
  1821. // the shapes follow the clip, the rest of FL's bits stay as they came
  1822. const auto shape = [&clip] (int side, std::uint32_t raw) -> std::uint32_t
  1823. { return (clip.linearFades & (1 << side)) != 0 ? 1u : raw == 1u ? 0u : raw; };
  1824. item.fadeFlags = (clip.flFadeFlags & ~((3u << 8) | (3u << 12)))
  1825. | (shape (0, (clip.flFadeFlags >> 8) & 3) << 8) | (shape (1, (clip.flFadeFlags >> 12) & 3) << 12);
  1826. }
  1827. item.gain = clip.gain;
  1828. item.pitch = std::clamp (clip.pitch, -12.0f, 12.0f); // (FL's clip pitch range; a Live transpose may reach ±48)
  1829. item.reversed = clip.reversed;
  1830. return item;
  1831. }
  1832. case ClipKind::automation:
  1833. {
  1834. const auto found = automationChannel.find (clip.automation);
  1835. if (found == automationChannel.end())
  1836. return std::nullopt;
  1837. item.kind = flp::PlaylistItem::Kind::channelClip;
  1838. item.index = found->second;
  1839. item.gain = 1.0f;
  1840. // the trim in beats. −1 = none, and FL then takes the clip's whole content for its end, whatever the
  1841. // item's length says: a 20-beat clip of a 546-beat automation at beat 284 made Thief 208 bars long
  1842. // instead of 144 (round 180d). So only a clip that shows all its content goes without a trim, as in
  1843. // FL's own files.
  1844. if (clip.offset > 0 || (clip.automation >= 0 && clip.automation < (int) song.automations.size()
  1845. && clip.length != song.automations[(std::size_t) clip.automation].length()))
  1846. {
  1847. item.startOffset = (float) ((double) clip.offset / ppq);
  1848. item.endOffset = (float) ((double) (clip.offset + clip.length) / ppq);
  1849. }
  1850. else
  1851. item.startOffset = item.endOffset = -1.0f;
  1852. return item;
  1853. }
  1854. }
  1855. return std::nullopt;
  1856. }
  1857. static flp::PlaylistTrackInfo trackInfo (const PlaylistTrack& t, int index, int rowHeight)
  1858. {
  1859. flp::PlaylistTrackInfo info;
  1860. info.index = index;
  1861. info.name = t.name;
  1862. info.enabled = ! t.muted;
  1863. info.colour = t.colour != 0 ? rgb (t.colour) : 0x485156;
  1864. info.grouped = t.grouped;
  1865. info.expanded = ! t.collapsed;
  1866. info.lockedToContent = t.lockedToContent;
  1867. info.lockedHeight = t.lockedHeight;
  1868. info.heightScale = t.height > 0 ? polish::flSizeForHeight (t.height, rowHeight) : 1.0f; // (round 190ft: FL's size factor; 190gw: on the song's default row)
  1869. info.mode = t.mode == PlaylistTrackMode::audio ? 1 : t.mode == PlaylistTrackMode::instrument ? 3 : 0;
  1870. info.mixerTrack = t.mixerTrack;
  1871. info.channel = t.channel;
  1872. info.icon = t.icon;
  1873. info.motion = (int) t.performance.motion;
  1874. info.press = (int) t.performance.press;
  1875. info.triggerSync = (int) t.performance.triggerSync;
  1876. info.positionSync = (int) t.performance.positionSync;
  1877. info.queue = t.performance.queue;
  1878. info.tolerant = t.performance.tolerant;
  1879. return info;
  1880. }
  1881. // ---- the mixer ----
  1882. void mixer()
  1883. {
  1884. for (int t = 0; t < (int) song.mixer.size(); ++t)
  1885. {
  1886. const auto& track = song.mixer[(std::size_t) t];
  1887. flp::MixerInsert m;
  1888. m.index = t;
  1889. m.name = t == 0 ? std::string() : track.name;
  1890. m.colour = track.colour != 0 ? rgb (track.colour) : 0;
  1891. m.colourSet = track.colour != 0 ? 1 : 0;
  1892. m.icon = track.icon;
  1893. m.flags = 0x04u | (track.muted ? 0u : 0x08u) | (track.invertPhase ? 0x01u : 0u) | (track.swapChannels ? 0x02u : 0u)
  1894. | (t > 0 && track.solo ? 0x1000u : 0u) | (t > 0 && track.separator ? 0x400u : 0u)
  1895. | (track.compensateMasterLatency ? 0u : 0x4000u)
  1896. | ((std::uint32_t) (t == 0 ? 0 : track.dock == MixerDock::left ? 0 : track.dock == MixerDock::right ? 2 : 1) << 6);
  1897. m.latencyMs = track.latencyMs;
  1898. m.latencyBypass = (int) track.latencyBypass;
  1899. m.recordSource = (int) track.recordSource;
  1900. m.monitor = (int) track.monitor;
  1901. m.input = track.flInput;
  1902. m.output = t == 0 ? 0 : track.outputChannel == 0 ? 0 : -1;
  1903. if (t > 0)
  1904. {
  1905. m.hasRoutes = true;
  1906. if (track.toMaster)
  1907. m.routes.push_back (0);
  1908. for (const auto& s : track.sends)
  1909. if (s.target > 0 && s.target < (int) song.mixer.size() && s.target != t)
  1910. m.routes.push_back (s.target);
  1911. // a side-chain input is FL's route at level 0 (sidechain only): without it FL's compressors and
  1912. // limiters have nothing to follow (thief's kick ducking was lost: +3.7 dB in FL, round 171e2)
  1913. for (const auto target : sidechainTargets (t))
  1914. if (std::find (m.routes.begin(), m.routes.end(), target) == m.routes.end())
  1915. m.routes.push_back (target);
  1916. }
  1917. // the levels (FL ranges: volume 0..16000 with 12800 = 0 dB, pan ±6400, separation ±64, route levels on the fader curve)
  1918. auto control = [&] (int slot, int param, std::int32_t value) { out.controls.push_back ({ { mixerId (t, slot, param) }, value }); };
  1919. // FL has no VCA (round 177a): the VCAs' gain is baked into the member's fader
  1920. const auto vca = t > 0 ? mixerops::vcaGain (song, t) : 1.0f;
  1921. const auto volume = vca == 1.0f ? track.volume : std::clamp (faderPosition (faderGain (track.volume) * vca), 0.0f, 1.0f);
  1922. control (0, flp::ControlId::mixerVolume, std::clamp (iround (volume * 16000.0), 0, 16000));
  1923. control (0, flp::ControlId::mixerPan, std::clamp (iround (track.pan * 6400.0), -6400, 6400));
  1924. control (0, flp::ControlId::mixerStereo, std::clamp (iround (track.stereo * 64.0), -64, 64));
  1925. for (int b = 0; b < 3; ++b)
  1926. {
  1927. const auto& eq = track.eq;
  1928. // (a bypassed EQ, LYNX's own: FL has no bypass, so it goes flat — what is heard stays the same)
  1929. control (0, flp::ControlId::mixerEqBase + b, eq.bypassed ? 0 : std::clamp (iround (eq.gainDb[(std::size_t) b] * 100.0), -1800, 1800));
  1930. const auto hz = std::clamp ((double) eq.hz[(std::size_t) b], 10.0, 16000.0);
  1931. 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));
  1932. control (0, flp::ControlId::mixerEqBase + 16 + b, std::clamp (iround (eq.width[(std::size_t) b] * 65536.0), 0, 65536));
  1933. }
  1934. if (t > 0)
  1935. {
  1936. control (0, flp::ControlId::mixerSendBase, std::clamp (iround (faderPosition (track.masterLevel) * 16000.0), 0, 16000));
  1937. for (const auto& s : track.sends)
  1938. if (s.target > 0 && s.target < (int) song.mixer.size())
  1939. control (0, flp::ControlId::mixerSendBase + s.target, std::clamp (iround (faderPosition (s.level) * 16000.0), 0, 16000));
  1940. for (const auto target : sidechainTargets (t))
  1941. if (std::none_of (track.sends.begin(), track.sends.end(), [&] (const MixerSend& s) { return s.target == target; }))
  1942. control (0, flp::ControlId::mixerSendBase + target, 0);
  1943. }
  1944. // the effect slots. Round 190bu: FL has no dry/wet for a whole chain, so the insert's Blend goes into each
  1945. // exported slot's own Mix (the same for one effect, close for several) and the report says so
  1946. const auto chainBlend = std::isfinite (track.chainBlend) ? std::clamp (track.chainBlend, 0.0f, 1.0f) : 1.0f;
  1947. bool blendNoted = false;
  1948. int next = 0;
  1949. for (int s = 0; s < (int) track.effects.size(); ++s)
  1950. {
  1951. const auto& fx = track.effects[(std::size_t) s];
  1952. const auto row = std::max (next, fx.row >= 0 ? fx.row : next);
  1953. if (row >= flEffectSlots) // (FL has 10 slots per insert: the effects in the rows added past them are left out)
  1954. {
  1955. for (int k = s; k < (int) track.effects.size(); ++k)
  1956. report.dropped.push_back (insertLabel (song, t) + ": " + projectcontents::effectSlotName (track.effects[(std::size_t) k])
  1957. + " (in a slot past FL's 10)");
  1958. break;
  1959. }
  1960. flp::MixerInsert::Slot slot;
  1961. slot.index = row;
  1962. slot.wrapperFlags = fx.smartDisable ? 0x160 : 0x140;
  1963. const auto label = insertLabel (song, t) + " slot " + std::to_string (row + 1) + ": ";
  1964. std::string what;
  1965. if (fx.isSubstitute() && fx.substituteFor.foreign.format != ForeignPlugin::Format::none)
  1966. {
  1967. slot.plugin = "Fruity Wrapper";
  1968. slot.state = writeWrapper (fx.substituteFor.foreign, false);
  1969. what = fx.substituteFor.foreign.name + " (the original plugin, LYNX's substitute left out)";
  1970. }
  1971. else if (fx.kind == EffectKind::plugin)
  1972. {
  1973. if (auto record = hosted (fx.plugin, false))
  1974. {
  1975. slot.plugin = "Fruity Wrapper";
  1976. // the side input picked with LYNX's "SC" picker is FL's input 2 index (round 189j)
  1977. auto ref = fx.plugin;
  1978. if (ref.foreign.format == ForeignPlugin::Format::none)
  1979. withSideIndex (ref.inputs, t, fx.sidechain);
  1980. else if (withSideIndex (record->inputRoutes, t, fx.sidechain) && ! record->hasRoutes)
  1981. {
  1982. record->hasRoutes = true;
  1983. record->outputRoutes = { { 0, 1 } };
  1984. }
  1985. slot.state = writeWrapper (*record, false, ref.foreign.format == ForeignPlugin::Format::none ? &ref : nullptr);
  1986. slot.wrapperFlags = withFlDetached (slot.wrapperFlags, fx.plugin.detached); // (issue #116)
  1987. what = record->name + " (Fruity Wrapper)";
  1988. }
  1989. }
  1990. else if (const auto native = nativeLookState (fx))
  1991. {
  1992. // a Master look's slot (round 189k): FL's own plugin with the slot's settings
  1993. slot.plugin = native->first;
  1994. slot.state = native->second;
  1995. what = native->first;
  1996. ownState.insert ({ t, s });
  1997. }
  1998. else if (fx.kind == EffectKind::fruityLimiter && fx.goal == goals::duck && ! originMatches (fx))
  1999. {
  2000. // the Simple layout's "Duck under..." (round 190ot): FL's Fruity Limiter with the slot's settings, its
  2001. // side input the trigger's place in the insert's inputs (fixSideInputs)
  2002. slot.plugin = "Fruity Limiter";
  2003. slot.state = flstate::limiter (fx.params, fruityLimiterDefaultState());
  2004. what = "Fruity Limiter (Duck, sidechain)";
  2005. ownState.insert ({ t, s });
  2006. }
  2007. else if (originMatches (fx))
  2008. {
  2009. slot.plugin = fx.flOrigin.plugin;
  2010. slot.state = fx.flOrigin.state;
  2011. what = fx.flOrigin.plugin;
  2012. }
  2013. else if (const auto sub = substituteFor (fx); sub && (options.lynxOnly == LynxOnly::substitute || t == 0))
  2014. {
  2015. slot.plugin = sub->first;
  2016. slot.state = sub->second;
  2017. report.substituted.push_back (label + effectInfo (fx.kind).name + " → " + sub->first + " (FL's defaults)");
  2018. }
  2019. if (slot.plugin.empty())
  2020. {
  2021. // round 190re: a slot left out takes no FL row, so it is named by its own place in LYNX (before, by the next
  2022. // free FL row: five slots left out in a row all read "slot 2"), and a hosted plugin missing on this computer
  2023. // by its name, as a channel's is (before: "Plugin (LYNX only)")
  2024. const auto where = insertLabel (song, t) + " slot " + std::to_string (s + 1) + ": ";
  2025. if (song.slotActive (fx))
  2026. report.dropped.push_back (fx.kind == EffectKind::plugin ? where + "plugin '" + fx.plugin.name + "' (not found)"
  2027. : where + effectInfo (fx.kind).name + " (LYNX only)");
  2028. continue;
  2029. }
  2030. if (! what.empty())
  2031. {
  2032. report.exact.push_back (label + what);
  2033. }
  2034. // FL's trial mark stays with the effect it was saved with (issue #282; keepsTrialMark)
  2035. if (fx.flOrigin.trialSaved && sameName (fx.flOrigin.plugin, slot.plugin))
  2036. {
  2037. slot.wrapperFlags |= flTrialSavedFlag;
  2038. report.notes.push_back (trialNote (label.substr (0, label.size() - 2), slot.plugin));
  2039. }
  2040. slotMap[{ t, s }] = row;
  2041. slotPlugin[{ t, s }] = slot.plugin;
  2042. control (row, 0x1F00, fx.enabled ? 1 : 0);
  2043. control (row, 0x1F01, std::clamp (iround (fx.mix * chainBlend * 12800.0), 0, 12800));
  2044. if (chainBlend < 1.0f && ! blendNoted)
  2045. {
  2046. blendNoted = true;
  2047. report.notes.push_back (insertLabel (song, t) + ": the chain's Blend (" + std::to_string (iround (chainBlend * 100.0))
  2048. + "%) is written into each effect's Mix level (FL has no dry/wet for a whole chain)");
  2049. }
  2050. m.slots.push_back (std::move (slot));
  2051. next = row + 1;
  2052. }
  2053. out.mixer.push_back (std::move (m));
  2054. }
  2055. fixSideInputs();
  2056. if (! song.vcas.empty())
  2057. 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)");
  2058. // LYNX's pre-fader sends (round 190aq): FL has post-fader routes only, so they are written as those
  2059. if (const auto pre = std::accumulate (song.mixer.begin(), song.mixer.end(), 0, [] (int n, const MixerTrack& m) {
  2060. return n + (int) std::count_if (m.sends.begin(), m.sends.end(), [] (const MixerSend& s) { return s.pre; });
  2061. }); pre > 0)
  2062. report.notes.push_back ("Pre-fader sends: FL Studio's sends are post-fader; " + std::to_string (pre)
  2063. + (pre == 1 ? " pre-fader send is" : " pre-fader sends are") + " written as post-fader (they follow the track's fader in FL)");
  2064. report.exact.push_back ("Mixer: " + std::to_string (song.mixer.size()) + " tracks (names, colours, routes, sends, levels, EQ)");
  2065. }
  2066. // FL's plugins name a side input by its place k in the insert's inputs list (itself, then the inserts routing into
  2067. // it by number; REA_rodada22 §1). An effect exported as its imported FL state still holds the k it was imported
  2068. // with; when LYNX's side-chain source now sits at another place (an insert moved, round 177a, or a new source), k is
  2069. // rewritten. A k that still names LYNX's source, or an effect without a LYNX source, keeps its bytes.
  2070. void fixSideInputs()
  2071. {
  2072. std::map<int, std::vector<int>> inputs;
  2073. for (const auto& m : out.mixer)
  2074. for (const auto target : m.routes)
  2075. if (target > 0 && target != m.index)
  2076. inputs[target].push_back (m.index);
  2077. auto sourceAt = [&inputs] (int track, int k) {
  2078. auto list = inputs[track];
  2079. std::sort (list.begin(), list.end());
  2080. list.erase (std::unique (list.begin(), list.end()), list.end());
  2081. list.insert (list.begin(), track);
  2082. return std::pair { list, k > 0 && k < (int) list.size() ? list[(std::size_t) k] : -1 };
  2083. };
  2084. auto rd = [] (const std::vector<std::uint8_t>& d, std::size_t at) {
  2085. std::int32_t v = 0;
  2086. if (at + 4 <= d.size())
  2087. std::memcpy (&v, d.data() + at, 4);
  2088. return (int) v;
  2089. };
  2090. auto fix = [&] (std::vector<std::uint8_t>& d, std::size_t at, int track, int source) {
  2091. if (source <= 0 || at + 4 > d.size())
  2092. return;
  2093. const auto [list, now] = sourceAt (track, rd (d, at));
  2094. if (now == source)
  2095. return;
  2096. const auto it = std::find (list.begin(), list.end(), source);
  2097. if (it == list.end())
  2098. return;
  2099. const auto k = (std::int32_t) (it - list.begin());
  2100. std::memcpy (d.data() + at, &k, 4);
  2101. };
  2102. for (auto& m : out.mixer)
  2103. {
  2104. const auto t = m.index;
  2105. if (t <= 0 || t >= (int) song.mixer.size())
  2106. continue;
  2107. const auto& effects = song.mixer[(std::size_t) t].effects;
  2108. for (int s = 0; s < (int) effects.size(); ++s)
  2109. {
  2110. const auto found = slotMap.find ({ t, s });
  2111. if (found == slotMap.end())
  2112. continue;
  2113. const auto& fx = effects[(std::size_t) s];
  2114. const auto own = ownState.count ({ t, s }) > 0;
  2115. if (! own && ! originMatches (fx))
  2116. continue;
  2117. auto slot = std::find_if (m.slots.begin(), m.slots.end(), [row = found->second] (const flp::MixerInsert::Slot& x) { return x.index == row; });
  2118. if (slot == m.slots.end() || (! own && slot->plugin != fx.flOrigin.plugin))
  2119. continue;
  2120. auto& d = slot->state;
  2121. if (slot->plugin == "Fruity Limiter" && rd (d, 0) >= 6)
  2122. fix (d, 0xA4, t, fx.sidechain);
  2123. else if (slot->plugin == "Fruity Compressor" && rd (d, 0) == 3)
  2124. fix (d, 0x20, t, fx.sidechain);
  2125. else if (slot->plugin == "LuxeVerb")
  2126. fix (d, 4, t, fx.sidechain);
  2127. else if (slot->plugin == "Transmitter")
  2128. fix (d, 12 + 4 * (std::size_t) transmitter::count, t, fx.sidechain);
  2129. else if (slot->plugin == "Transporter" && d.size() >= 4)
  2130. fix (d, 4 + 4 * (std::size_t) (rd (d, 0) >= 8 ? 22 : 20) + 2 + 12, t, fx.sidechain);
  2131. else if (slot->plugin == "Vocodex")
  2132. if (const auto v = vocodex::parseState (d))
  2133. {
  2134. if (! v->lrEncoding)
  2135. fix (d, v->paramsAt + 80 + 20, t, fx.sidechain);
  2136. if (v->carIn >= 0)
  2137. fix (d, v->paramsAt + 80 + 24, t, fx.sidechain2);
  2138. }
  2139. }
  2140. }
  2141. }
  2142. void run()
  2143. {
  2144. choosePpq();
  2145. globals();
  2146. channels();
  2147. mixer(); // (before the automations: their effect targets need the slots)
  2148. patterns();
  2149. automations();
  2150. automationNotes();
  2151. arrangements();
  2152. rackOrder();
  2153. out.mixerTrackCount = 0;
  2154. out.header.channelCount = (std::uint16_t) out.channels.size();
  2155. }
  2156. };
  2157. } // namespace
  2158. flp::Project toProject (const Song& input, const Options& options, Report& report)
  2159. {
  2160. // FL 2026 has no Pattern Blocks: they become pattern clips (each pattern on a track of its own, locked to content)
  2161. Song song = input;
  2162. // track versions (round 190pe, a LYNX extra): FL has none; each track goes over as the version it plays
  2163. if (const auto n = trackversions::keepActiveOnly (song); n > 0)
  2164. report.notes.push_back ("Track versions: " + std::to_string (n) + " version(s) that are not active left out (each track is written as the version it plays)");
  2165. if (patternblocks::active (song))
  2166. {
  2167. const auto n = patternblocks::toClipsInEveryArrangement (song);
  2168. if (n > 0)
  2169. report.notes.push_back ("Pattern Blocks: " + std::to_string (n) + " block(s) written as pattern clips (FL 2026 has no blocks)");
  2170. }
  2171. // audio clip envelopes (round 190gi): FL has none on a clip; FL's own way is the clip menu's Automate › Volume /
  2172. // Panning, an automation clip of the clip channel's Levels adjustment over the clip — written that way, same curve
  2173. if (const auto n = clipenv::bakeToAutomation (song); n > 0)
  2174. report.notes.push_back ("Clip envelopes: " + std::to_string (n) + " envelope(s) written as automation clips of the clip's channel Levels adjustment (FL's Automate > Volume / Panning)");
  2175. // automation lanes (round 177b): FL has none; each becomes an automation clip on a free track
  2176. if (const auto n = autolanes::lanesToClips (song); n > 0)
  2177. report.notes.push_back ("Automation lanes: " + std::to_string (n) + " lane(s) written as automation clips (FL has no lanes)");
  2178. // modulators (round 177b): FL has none. Round 190ox: what follows the song position alone becomes automation clips
  2179. // (FL's clip LFO for an LFO, points for steps and random, a flat clip for a macro); the rest is listed
  2180. {
  2181. auto baked = modexport::bakeForFl (song);
  2182. if (baked.clips > 0)
  2183. report.notes.push_back ("Modulators: " + std::to_string (baked.clips) + " route(s) written as automation clips (FL has no modulators)");
  2184. for (auto& n : baked.notes)
  2185. report.notes.push_back (std::move (n));
  2186. for (auto& l : baked.lost)
  2187. report.dropped.push_back (std::move (l));
  2188. }
  2189. // track clips (round 190ne, core/TrackClips.h): FL has no such flag, so each is an ordinary pattern on FL's
  2190. // instrument track; identical ones are merged first (the owner's choice: silently), and more patterns than FL's
  2191. // 999 are reported
  2192. // round 190op (P4, LYNX extras): FL can neither hide a Playlist track nor deactivate a channel or insert. Hidden tracks
  2193. // are written visible; deactivated units are written active, with the settings and plugin states the project holds
  2194. if (const auto n = trackstates::hiddenCount (song); n > 0)
  2195. report.notes.push_back ("Hidden tracks: " + std::to_string (n) + " track(s) written visible (FL cannot hide Playlist tracks)");
  2196. {
  2197. std::string units;
  2198. int count = 0;
  2199. for (std::size_t i = 0; i < song.channels.size(); ++i)
  2200. if (song.channels[i].deactivated)
  2201. units += (count++ > 0 ? ", " : "") + song.channels[i].name;
  2202. for (std::size_t t = 1; t < song.mixer.size(); ++t)
  2203. if (song.mixer[t].deactivated)
  2204. units += (count++ > 0 ? ", " : "") + (song.mixer[t].name.empty() ? "Insert " + std::to_string (t) : song.mixer[t].name);
  2205. if (count > 0)
  2206. report.notes.push_back ("Deactivated: " + units + " written active with their settings and plugin states (FL has no deactivated tracks)");
  2207. }
  2208. trackclips::mergeIdentical (song);
  2209. if ((int) song.patterns.size() > trackclips::flPatternLimit)
  2210. report.notes.push_back ("Warning: " + std::to_string (song.patterns.size()) + " patterns are more than the "
  2211. + std::to_string (trackclips::flPatternLimit) + " FL Studio can hold: the patterns past "
  2212. + std::to_string (trackclips::flPatternLimit) + " may be missing in FL");
  2213. Converter c (song, options, report);
  2214. c.run();
  2215. return std::move (c.out);
  2216. }
  2217. std::vector<std::uint8_t> exportFlp (const Song& song, const Options& options, Report& report)
  2218. {
  2219. return flp::writeProject (toProject (song, options, report), options.write);
  2220. }
  2221. } // namespace lynx::flpexport