FlpImport.cpp 141 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723
  1. #include "core/FlpImport.h"
  2. #include "core/EditorPolish.h"
  3. #include "core/FruityPhaser.h"
  4. #include "core/FlPluginDb.h"
  5. #include "core/FlVoiceProcessor.h"
  6. #include "core/HardcoreFx.h"
  7. #include "core/GrossBeat.h"
  8. #include "core/LovePhilter.h"
  9. #include "core/DrumSynthLive.h"
  10. #include "core/Gms.h"
  11. #include "core/Harmless.h"
  12. #include "core/Morphine.h"
  13. #include "core/BassDrum.h"
  14. #include "core/FruitKick.h"
  15. #include "core/Harmor.h"
  16. #include "core/MiniSynth.h"
  17. #include "core/SimSynth.h"
  18. #include "core/Drumaxx.h"
  19. #include "core/Plucked.h"
  20. #include "core/FlKeys.h"
  21. #include "core/DirectWave.h"
  22. #include "core/BeepMap.h"
  23. #include "core/Sawer.h"
  24. #include "core/Granulizer.h"
  25. #include "core/Ogun.h"
  26. #include "core/Dx10.h"
  27. #include "core/Kepler.h"
  28. #include "core/TransistorBass.h"
  29. #include "core/Slayer.h"
  30. #include "core/PoiZone.h"
  31. #include "core/Toxic.h"
  32. #include "core/ThreeOsc.h"
  33. #include "core/HarmlessFx.h"
  34. #include "core/SytrusEngine.h"
  35. #include "core/PhysicalModels.h"
  36. #include "core/Effects.h"
  37. #include "core/FlEffects.h"
  38. #include "core/Reeverb2.h"
  39. #include "core/LuxeVerb.h"
  40. #include "core/ConvolverFx.h"
  41. #include "core/ChorusFx.h"
  42. #include "core/FlPatcher.h"
  43. #include "core/FlSamplers.h"
  44. #include "core/FlSynths.h"
  45. #include "core/FlWrapper.h"
  46. #include "core/FruityDynamics.h"
  47. #include "core/SynthPresets.h"
  48. #include "core/NewtoneFx.h"
  49. #include <algorithm>
  50. #include <cstring>
  51. #include <cctype>
  52. #include <cmath>
  53. #include <map>
  54. namespace lynx
  55. {
  56. namespace
  57. {
  58. bool contains (const std::string& haystack, const char* needle)
  59. {
  60. return haystack.find (needle) != std::string::npos;
  61. }
  62. std::string lowercase (std::string s)
  63. {
  64. std::transform (s.begin(), s.end(), s.begin(), [] (unsigned char c) { return (char) std::tolower (c); });
  65. return s;
  66. }
  67. } // namespace
  68. InstrumentKind guessInstrument (const std::string& channelName, flp::ChannelType type)
  69. {
  70. const auto name = lowercase (channelName);
  71. if (type == flp::ChannelType::sampler || type == flp::ChannelType::unknown)
  72. {
  73. if (contains (name, "kick") || contains (name, "bd") || contains (name, "808"))
  74. return InstrumentKind::kick;
  75. if (contains (name, "snare") || contains (name, "snr") || contains (name, "rim"))
  76. return InstrumentKind::snare;
  77. if (contains (name, "clap") || contains (name, "snap"))
  78. return InstrumentKind::clap;
  79. if (contains (name, "hat") || contains (name, "hh") || contains (name, "ride") || contains (name, "cym")
  80. || contains (name, "crash") || contains (name, "shaker") || contains (name, "perc") || contains (name, "tamb"))
  81. return InstrumentKind::hat;
  82. }
  83. return InstrumentKind::synth;
  84. }
  85. std::string resolveFlPath (const std::string& flPath, const FlPathRoots& roots)
  86. {
  87. const std::pair<const char*, const std::string*> variables[] = {
  88. { "%FLStudioFactoryData%", &roots.factoryData },
  89. { "%FLStudioUserData%", &roots.userData },
  90. { "%FLStudioData%", &roots.data },
  91. };
  92. for (const auto& [name, root] : variables)
  93. {
  94. const std::string variable (name);
  95. if (flPath.compare (0, variable.size(), variable) == 0)
  96. return root->empty() ? std::string() : *root + flPath.substr (variable.size());
  97. }
  98. return flPath;
  99. }
  100. std::optional<EffectKind> effectForFlPlugin (const std::string& name)
  101. {
  102. static const std::pair<const char*, EffectKind> table[] = {
  103. { "Fruity Parametric EQ 2", EffectKind::parametricEq }, { "Fruity Parametric EQ", EffectKind::parametricEq },
  104. { "Fruity 7 Band EQ", EffectKind::parametricEq },
  105. { "Fruity Limiter", EffectKind::limiter }, { "Maximus", EffectKind::limiter }, { "Fruity Soft Clipper", EffectKind::distortion },
  106. { "Fruity Reeverb 2", EffectKind::reverb }, { "Fruity Reeverb", EffectKind::reverb }, { "LuxeVerb", EffectKind::reverb },
  107. { "Fruity Delay 3", EffectKind::delay }, { "Fruity Delay 2", EffectKind::delay }, { "Fruity Delay Bank", EffectKind::delay },
  108. { "Fruity Delay", EffectKind::delay }, { "Fruity Compressor", EffectKind::compressor },
  109. { "Fruity Multiband Compressor", EffectKind::compressor }, { "Soundgoodizer", EffectKind::compressor },
  110. { "Fruity WaveShaper", EffectKind::distortion }, { "Fruity Fast Dist", EffectKind::distortion },
  111. { "Fruity Blood Overdrive", EffectKind::distortion }, { "Distructor", EffectKind::distortion },
  112. { "Fruity Flangus", EffectKind::chorus }, { "Fruity Chorus", EffectKind::chorus }, { "Hyper Chorus", EffectKind::chorus },
  113. { "Vintage Chorus", EffectKind::chorus }, { "Fruity Flanger", EffectKind::chorus },
  114. { "Fruity Balance", EffectKind::utility }, { "Fruity PanOMatic", EffectKind::utility }, { "Fruity Stereo Shaper", EffectKind::utility },
  115. { "Fruity Center", EffectKind::utility }, { "Fruity Phase Inverter", EffectKind::utility },
  116. { "Fruity Stereo Enhancer", EffectKind::utility }, { "Fruity Convolver", EffectKind::reverb }, { "EQUO", EffectKind::parametricEq },
  117. { "Spreader", EffectKind::utility }, { "Transient Processor", EffectKind::utility },
  118. { "Fruity Phaser", EffectKind::chorus }, { "Fruity Bass Boost", EffectKind::eq }, { "Fruity Free Filter", EffectKind::filter },
  119. { "Fruity Love Philter", EffectKind::filter }, { "Fruity Filter", EffectKind::filter }, { "Fruity Fast LP", EffectKind::filter },
  120. { "Gross Beat", EffectKind::volumeGate }, { "Frequency Splitter", EffectKind::parametricEq },
  121. { "Fruity Peak Controller", EffectKind::peakController },
  122. { "Pitch Shifter", EffectKind::pitchShift }, { "Frequency Shifter", EffectKind::freqShift },
  123. { "Emphasis", EffectKind::limiter }, { "Low Lifter", EffectKind::parametricEq },
  124. { "Fruity Send", EffectKind::utility }, { "Transporter", EffectKind::utility },
  125. { "Vintage Phaser", EffectKind::vintagePhaser }, { "Fruity Squeeze", EffectKind::squeeze },
  126. { "Hardcore", EffectKind::hardcore },
  127. { "Multiband Delay", EffectKind::delay },
  128. };
  129. // old presets (FL 3) store the name with different casing ("Fruity delay 2")
  130. const auto wanted = lowercase (name);
  131. for (const auto& [plugin, kind] : table)
  132. if (wanted == lowercase (plugin))
  133. return kind;
  134. return std::nullopt;
  135. }
  136. // Range of an FL parameter's raw value (what FL's parameter setter stores and what pattern events 0xDF / 0xD8 hold),
  137. // so that (raw − lo) / (hi − lo) is FL's normalised value, the one automation clips carry (REA_rodada85 §2).
  138. // `plugin` = the FL plugin of the target slot or channel. Unknown ranges: no value.
  139. std::optional<std::pair<int, int>> flRawRange (flp::ControlId id, const std::string& plugin)
  140. {
  141. const auto p = id.param();
  142. if (id.isChannel())
  143. {
  144. if (p == 0 || p == 1) // volume 0..12800 (10000 = default), pan 0..12800 (6400 = centre)
  145. return std::pair { 0, 12800 };
  146. }
  147. else if (id.isMixer())
  148. {
  149. if (p == flp::ControlId::mixerVolume)
  150. return std::pair { 0, 16000 };
  151. if (p == flp::ControlId::mixerPan)
  152. return std::pair { -6400, 6400 };
  153. if (p == 0x1F01) // slot dry/wet
  154. return std::pair { 0, 12800 };
  155. }
  156. if (p < flp::ControlId::pluginParamBase)
  157. return std::nullopt;
  158. // plugin parameters: the plugin's own control integer (FL hands it to ProcessParam unscaled)
  159. const auto k = p - flp::ControlId::pluginParamBase;
  160. if (plugin == "Fruity Reeverb 2" && k < reeverb2ParamCount)
  161. return std::pair { reeverb2::ranges[(std::size_t) k].lo, reeverb2::ranges[(std::size_t) k].hi };
  162. if (plugin == "Fruity Reeverb" && k < reeverb1ParamCount)
  163. return std::pair { 0, reeverb1::maxima[(std::size_t) k] };
  164. if (plugin == "Fruity Convolver" && k < convolverParamCount)
  165. return std::pair { convolver::ranges[(std::size_t) k].lo, convolver::ranges[(std::size_t) k].hi };
  166. if (plugin == "LuxeVerb" && k < luxeVerbControlCount)
  167. return std::pair { luxeverb::ranges[(std::size_t) k].lo, luxeverb::ranges[(std::size_t) k].hi };
  168. return std::nullopt;
  169. }
  170. AutomationTarget automationTargetFor (flp::ControlId id, const std::map<int, int>& channelMap, int mixerTracks)
  171. {
  172. AutomationTarget t;
  173. if (id.isTempo())
  174. {
  175. t.kind = AutomationTargetKind::tempo;
  176. return t;
  177. }
  178. if (id.isChannel())
  179. {
  180. const auto channel = channelMap.find (id.channel());
  181. if (channel == channelMap.end())
  182. return t;
  183. t.index = channel->second;
  184. const auto p = id.param();
  185. if (p == 0)
  186. t.kind = AutomationTargetKind::channelVolume;
  187. else if (p == 1)
  188. t.kind = AutomationTargetKind::channelPan;
  189. else if (p >= flp::ControlId::pluginParamBase)
  190. {
  191. t.kind = AutomationTargetKind::channelParam;
  192. t.param = p - flp::ControlId::pluginParamBase;
  193. }
  194. return t;
  195. }
  196. if (id.isMixer() && id.track() >= 0 && id.track() < mixerTracks)
  197. {
  198. t.index = id.track();
  199. const auto p = id.param();
  200. if (p == 0x1F01) // slot dry/wet
  201. {
  202. t.kind = AutomationTargetKind::effectMix;
  203. t.slot = id.slot();
  204. }
  205. else if (p == flp::ControlId::mixerVolume)
  206. t.kind = AutomationTargetKind::mixerVolume;
  207. else if (p == flp::ControlId::mixerPan)
  208. t.kind = AutomationTargetKind::mixerPan;
  209. else if (p >= flp::ControlId::pluginParamBase)
  210. {
  211. t.kind = AutomationTargetKind::effectParam;
  212. t.slot = id.slot();
  213. t.param = p - flp::ControlId::pluginParamBase;
  214. }
  215. }
  216. return t;
  217. }
  218. bool synthFrom3xOsc (const std::vector<std::uint8_t>& state, SynthSettings& synth)
  219. {
  220. // version 10/11: 20 parameters + 4 bools (80 B); 12+: 21 parameters + 4 bools (+ HQ)
  221. if (state.size() < 84)
  222. return false;
  223. auto i32 = [&] (std::size_t offset) {
  224. return (std::int32_t) ((std::uint32_t) state[offset] | ((std::uint32_t) state[offset + 1] << 8)
  225. | ((std::uint32_t) state[offset + 2] << 16) | ((std::uint32_t) state[offset + 3] << 24));
  226. };
  227. const auto version = i32 (0);
  228. if (version < 10 || version > 64)
  229. return false;
  230. // parameter i is at 0x04 + 4i; (i + 1) = 7·osc + field, fields [mix, pan, shape, coarse, fine, spo, detune]
  231. auto param = [&] (int osc, int field) { return i32 ((std::size_t) (4 + 4 * (7 * osc + field - 1))); };
  232. const auto boolsAt = version >= 12 ? (std::size_t) 0x58 : (std::size_t) 0x54;
  233. const bool am = version >= 11 && state.size() > boolsAt + 3 && state[boolsAt + 3] != 0;
  234. // levels (§2.2): osc 3 takes mix3/128, osc 2 a share of the rest, osc 1 what remains
  235. const auto g3 = std::clamp (param (2, 0), 0, 128) / 128.0f;
  236. const auto rest = am ? 1.0f : 1.0f - g3;
  237. const auto g2 = rest * std::clamp (param (1, 0), 0, 128) / 128.0f;
  238. // with AM, osc 3 is not summed: its level becomes the modulation depth (REA_rodada6 §3)
  239. const std::array<float, 3> levels { std::max (0.0f, rest - g2), g2, g3 };
  240. synth.am = am;
  241. for (int o = 0; o < 3; ++o)
  242. {
  243. auto& osc = synth.osc[(std::size_t) o];
  244. switch (param (o, 2))
  245. {
  246. case 0: osc.wave = Waveform::sine; break;
  247. case 1: osc.wave = Waveform::triangle; break;
  248. case 2: osc.wave = Waveform::square; break;
  249. case 5: osc.wave = Waveform::noise; break;
  250. default: osc.wave = Waveform::saw; break; // 3 saw, 4 rounded saw, 6 custom without sample
  251. }
  252. const auto coarse = std::clamp (param (o, 3), -24, 24);
  253. osc.octave = coarse / 12; // truncates toward zero; the remainder becomes semitones
  254. osc.semitones = coarse - osc.octave * 12;
  255. // stereo detune only sounds on the right channel: half of it counts as average detune
  256. osc.detune = std::clamp ((float) std::clamp (param (o, 4), -100, 100) + std::clamp (param (o, 6), -50, 50) * 0.5f, -100.0f, 100.0f);
  257. osc.pan = std::clamp (param (o, 1), -64, 64) / 64.0f;
  258. osc.level = levels[(std::size_t) o];
  259. }
  260. return true;
  261. }
  262. namespace
  263. {
  264. // FL channel filter cutoff (Hz) for normalized Mod X `x` (REA_rodada4 §3); 20 kHz = open.
  265. double channelFilterHz (int type, double x)
  266. {
  267. constexpr double twoPi = 6.283185307179586;
  268. x = std::clamp (x, 0.0, 1.0);
  269. switch (type)
  270. {
  271. case 0:
  272. 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));
  273. case 1:
  274. case 2:
  275. case 3:
  276. case 4:
  277. case 5: return ((std::pow (51.0, x) - 1.0) * 0.0596 + 0.02) * 44100.0 / twoPi;
  278. case 6:
  279. case 7: return 44100.0 / (twoPi / 2.0) * std::asin (std::min (1.0, (std::pow (26.0, x) - 1.0) * 0.04) / 2.0);
  280. default: return 20000.0;
  281. }
  282. }
  283. } // namespace
  284. float filterEnvelopeOctaves (int modX, int type, int amount)
  285. {
  286. const auto x = std::clamp (modX / 256.0, 0.0, 1.0);
  287. const auto from = std::clamp (channelFilterHz (type, x), 20.0, 20000.0);
  288. const auto to = std::clamp (channelFilterHz (type, x + amount / 128.0), 20.0, 20000.0);
  289. return (float) std::log2 (to / from);
  290. }
  291. void synthFilterFromChannel (int modX, int modY, int type, float& cutoffHz, float& resonance, int& mode)
  292. {
  293. mode = type == 2 ? 1 : type == 3 ? 2 : type == 4 ? 3 : 0; // BP, HP, BS; the rest is low-pass
  294. const auto x = std::clamp (modX / 256.0, 0.0, 1.0);
  295. const auto r = std::clamp (modY / 256.0, 0.0, 1.0);
  296. auto fromQ = [] (double q) { return (float) std::clamp ((2.0 - 1.0 / q) / 1.9, 0.0, 1.0); }; // the synth SVF: k = 1/Q
  297. resonance = 0.0f;
  298. if (type == 0) // Fast LP: 1 pole + feedback; feedback grows with Mod Y (approximation)
  299. resonance = (float) (r * 0.9);
  300. else if (type >= 1 && type <= 5) // LP/BP/HP/BS biquads (LPx2 = the LP twice)
  301. resonance = fromQ (r <= 0.0 ? 0.1 : (std::pow (51.0, 0.625 * r) - 1.0) * 0.4 + 0.1);
  302. else if (type == 6 || type == 7) // Chamberlin SVF
  303. resonance = fromQ (1.0 / (r <= 0.0 ? 1.0 : (r < 1.0 ? 1.0 - 0.8 * r : 0.2)));
  304. cutoffHz = (float) std::clamp (channelFilterHz (type, x), 20.0, 20000.0);
  305. }
  306. // The 364-byte channel-settings snapshot Fruity DX10 keeps (REA_rodada42 §3): the five 0xDA records (pan, volume,
  307. // cutoff, resonance, pitch; 68 bytes each) followed by Mod X at 0x15c, Mod Y at 0x160 and the filter type at 0x168. A
  308. // version-2 state carries its own (after the 22 parameters); for a version-1 state FL's host hands the plugin the
  309. // channel's records (the plugin asks for them when it has no snapshot — inference from the request, not observed).
  310. // Missing records take the plugin's defaults (neutral; the volume record with flag 4 and release tension −101).
  311. std::vector<std::uint8_t> dx10Snapshot (const flp::Channel& c)
  312. {
  313. std::vector<std::uint8_t> s (364, 0);
  314. auto put = [&] (std::size_t at, std::int32_t v) { std::memcpy (s.data() + at, &v, 4); };
  315. for (int k = 0; k < 5; ++k)
  316. {
  317. const auto& e = c.envelopes[(std::size_t) k];
  318. const auto base = (std::size_t) (0x44 * k);
  319. const std::int32_t defaults[17] = { k == 1 ? 4 : 0, 0, 100, 20000, 20000, 30000, 50, 20000, 0, 100, 20000, 0, 32950, 0, 0, 0, k == 1 ? -101 : 0 };
  320. for (int i = 0; i < 17; ++i)
  321. put (base + 4 * (std::size_t) i, defaults[i]);
  322. if (e.present)
  323. std::memcpy (s.data() + base, e.raw.data(), (std::size_t) std::min (e.rawSize, 0x44));
  324. }
  325. put (0x15c, c.hasLevels ? c.modX : 256);
  326. put (0x160, c.hasLevels ? c.modY : 0);
  327. put (0x168, c.hasLevels ? c.filterType : 0);
  328. return s;
  329. }
  330. void splitDrumChannel (Song& song, int channel, const std::vector<DrumPad>& pads)
  331. {
  332. if (channel < 0 || channel >= (int) song.channels.size() || pads.empty())
  333. return;
  334. const auto original = song.channels[(std::size_t) channel];
  335. const auto inserted = (int) pads.size() - 1; // the first pad takes the original channel's place
  336. std::vector<ChannelDef> padChannels;
  337. for (const auto& pad : pads)
  338. {
  339. ChannelDef def = original;
  340. def.name = original.name + " - " + pad.name;
  341. def.instrument = InstrumentKind::sampler;
  342. def.plugin = {};
  343. const auto single = pad.layers.size() == 1;
  344. def.samplePath = single ? pad.layers.front().path : std::string();
  345. def.zones = single ? std::vector<SampleZone> {} : pad.layers;
  346. for (auto& z : def.zones)
  347. z.rootKey = 60, z.lowKey = 0, z.highKey = 127; // the pad plays at the sample's pitch
  348. // volume: channel gain × pad gain (× the single layer's), mapped back to the channel curve
  349. const auto gain = channelGain (original.volume) * pad.gain * (single ? pad.layers.front().gain : 1.0f);
  350. def.volume = std::clamp ((float) (std::log (10.0 * gain + 1.0) / std::log (11.0)), 0.0f, 1.0f);
  351. def.pan = std::clamp (original.pan + pad.pan, -1.0f, 1.0f);
  352. def.sampler = {};
  353. def.sampler.pitch = std::clamp (original.sampler.pitch + pad.tune + (single ? pad.layers.front().tune : 0.0f), -24.0f, 24.0f);
  354. // kit-specific cut groups (don't mix with other channels' groups)
  355. def.cutGroup = pad.cutGroup > 0 ? 1000 * (channel + 1) + pad.cutGroup : 0;
  356. def.cutBy = pad.cutBy > 0 ? 1000 * (channel + 1) + pad.cutBy : 0;
  357. def.mixerTrack = std::clamp (original.mixerTrack + pad.mixerOffset, 0, maxMixerTracks - 1);
  358. padChannels.push_back (std::move (def));
  359. }
  360. song.channels[(std::size_t) channel] = padChannels.front();
  361. song.channels.insert (song.channels.begin() + channel + 1, padChannels.begin() + 1, padChannels.end());
  362. // channels after the original shift by `inserted` positions
  363. auto shift = [&] (int c) { return c > channel ? c + inserted : c; };
  364. for (auto& p : song.patterns)
  365. {
  366. std::vector<Note> kept;
  367. for (auto n : p.notes)
  368. {
  369. if (n.channel != channel)
  370. {
  371. n.channel = shift (n.channel);
  372. kept.push_back (n);
  373. continue;
  374. }
  375. for (int i = 0; i < (int) pads.size(); ++i)
  376. if (pads[(std::size_t) i].key == n.key)
  377. {
  378. n.channel = channel + i;
  379. n.key = 60;
  380. kept.push_back (n);
  381. break;
  382. }
  383. }
  384. p.notes = std::move (kept);
  385. p.sortNotes();
  386. }
  387. song.forEachClipList ([&] (std::vector<Clip>& clips) {
  388. for (auto& c : clips)
  389. c.channel = c.channel >= 0 ? shift (c.channel) : c.channel;
  390. });
  391. song.forEachTarget ([&] (AutomationTarget& t) {
  392. if ((t.kind == AutomationTargetKind::channelVolume || t.kind == AutomationTargetKind::channelPan
  393. || t.kind == AutomationTargetKind::channelParam) && t.index >= 0)
  394. t.index = shift (t.index);
  395. });
  396. }
  397. bool isFlSynthPresetPlugin (const std::string& pluginName)
  398. {
  399. static const char* const supported[] = { "3x osc", "sytrus", "harmor", "gms", "harmless", "minisynth", "fruity dx10", "dx10",
  400. "fruit kick", "ogun", "autogun", "sakura", "kepler", "boobass", "poizone", "bassdrum",
  401. "toxic biohazard" };
  402. const auto name = lowercase (pluginName);
  403. return std::any_of (std::begin (supported), std::end (supported), [&] (const char* n) { return name == n; });
  404. }
  405. std::optional<SynthSettings> synthFromFlPreset (const std::vector<std::uint8_t>& bytes)
  406. {
  407. // native GMS preset (.gmsynth): it is the plugin state without the "SSLF"
  408. if (bytes.size() >= 4 && (std::memcmp (bytes.data(), "4nyS", 4) == 0 || std::memcmp (bytes.data(), "3nyS", 4) == 0))
  409. {
  410. std::vector<std::uint8_t> state { 'S', 'S', 'L', 'F' };
  411. const auto n = (std::uint32_t) bytes.size();
  412. for (int i = 0; i < 4; ++i)
  413. state.push_back ((std::uint8_t) (n >> (8 * i)));
  414. state.insert (state.end(), bytes.begin(), bytes.end());
  415. SynthSettings synth;
  416. float gain = 1.0f;
  417. if (synthFromGms (state, 120.0, synth, gain))
  418. return synth;
  419. return std::nullopt;
  420. }
  421. try
  422. {
  423. auto project = flp::parseProject (bytes, true);
  424. if (project.channels.empty() || ! isFlSynthPresetPlugin (project.channels.front().pluginName))
  425. return std::nullopt;
  426. project.channels.front().type = flp::ChannelType::native; // native generator (the .fst doesn't say)
  427. FlpImportOptions options;
  428. options.threeOscAsSynth = true; // a 3x Osc preset fills the built-in synth
  429. const auto song = importFlp (project, options);
  430. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::sakura)
  431. {
  432. // the synth's preset button keeps the synth approximation of a Sakura patch
  433. SynthSettings synth;
  434. if (synthFromSakura (project.channels.front().pluginState, synth))
  435. return synth;
  436. }
  437. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::sytrus)
  438. {
  439. // likewise for Sytrus: the preset button fills the built-in synth with the 3-oscillator conversion
  440. SynthSettings synth;
  441. float gain = 1.0f;
  442. if (synthFromSytrus (project.channels.front().pluginState, song.bpm, synth, gain))
  443. return synth;
  444. }
  445. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::harmless)
  446. {
  447. // ... and of a Harmless patch
  448. SynthSettings synth;
  449. float gain = 1.0f;
  450. if (synthFromHarmless (project.channels.front().pluginState, song.bpm, synth, gain))
  451. return synth;
  452. }
  453. if (! song.channels.empty() && (song.channels.front().instrument == InstrumentKind::gms || song.channels.front().instrument == InstrumentKind::morphine))
  454. {
  455. // ... and of GMS / Morphine patches (their 3-oscillator / averaged-spectrum conversions)
  456. SynthSettings synth;
  457. float gain = 1.0f;
  458. const auto& st = project.channels.front().pluginState;
  459. if (song.channels.front().instrument == InstrumentKind::gms ? synthFromGms (st, song.bpm, synth, gain) : synthFromMorphine (st, synth, gain))
  460. return synth;
  461. }
  462. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::toxic)
  463. {
  464. // ... and of a Toxic Biohazard patch (the 2-operator conversion)
  465. SynthSettings synth;
  466. float gain = 1.0f;
  467. if (synthFromToxic (project.channels.front().pluginState, synth, gain))
  468. return synth;
  469. }
  470. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::harmor)
  471. {
  472. // ... and of a Harmor patch (the spectral-oscillator conversion)
  473. SynthSettings synth;
  474. float gain = 1.0f;
  475. if (synthFromHarmor (project.channels.front().pluginState, synth, gain))
  476. return synth;
  477. }
  478. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::dx10)
  479. {
  480. // ... and of a Fruity DX10 patch (the 3-oscillator FM conversion)
  481. SynthSettings synth;
  482. if (synthFromDX10 (project.channels.front().pluginState, synth))
  483. return synth;
  484. }
  485. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::kepler)
  486. {
  487. // ... and of a Kepler patch (the synth conversion)
  488. SynthSettings synth;
  489. float gain = 1.0f;
  490. if (synthFromKepler (project.channels.front().pluginState, synth, gain))
  491. return synth;
  492. }
  493. if (! song.channels.empty()
  494. && (song.channels.front().instrument == InstrumentKind::ogun || song.channels.front().instrument == InstrumentKind::autogun))
  495. {
  496. // ... and of an Ogun / Autogun patch (the spectral-oscillator conversion)
  497. SynthSettings synth;
  498. float gain = 1.0f;
  499. if (synthFromOgun (project.channels.front().pluginState, synth, gain))
  500. return synth;
  501. }
  502. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::poizone)
  503. {
  504. // ... and of a PoiZone patch (the 2-oscillator conversion)
  505. SynthSettings synth;
  506. float gain = 1.0f;
  507. if (synthFromPoiZone (project.channels.front().pluginState, synth, gain))
  508. return synth;
  509. }
  510. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::minisynth)
  511. {
  512. // ... and of a MiniSynth patch (the internal-synth conversion)
  513. SynthSettings synth;
  514. if (synthFromMiniSynth (project.channels.front().pluginState, song.bpm, synth))
  515. return synth;
  516. }
  517. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::fruitkick)
  518. {
  519. // ... and of Fruit Kick / BassDrum patches (their sine + pitch-sweep conversions)
  520. SynthSettings synth;
  521. if (synthFromFruitKick (project.channels.front().pluginState, synth))
  522. return synth;
  523. }
  524. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::bassdrum)
  525. {
  526. SynthSettings synth;
  527. float gain = 1.0f;
  528. if (synthFromBassDrum (project.channels.front().pluginState, synth, gain))
  529. return synth;
  530. }
  531. if (song.channels.empty() || song.channels.front().instrument != InstrumentKind::synth)
  532. return std::nullopt;
  533. return song.channels.front().synth;
  534. }
  535. catch (const flp::Error&)
  536. {
  537. return std::nullopt;
  538. }
  539. }
  540. namespace
  541. {
  542. // Old FL saved its own Fruity effects as VST2 plugins inside Fruity Wrapper: the wrapper keeps their parameters as
  543. // 0…1 floats (REA_rodada89 §2). Fruity Compressor's 6 controls map linearly onto its native ranges — an untouched
  544. // instance's floats land exactly on the native defaults [DATA, RawFL demo] — so its native state (layout v1:
  545. // 6 × i32) is rebuilt; the lookahead flag has no VST2 parameter (off, not confirmed). Fruity Phaser likewise (round
  546. // 105). Other effects: defaults.
  547. std::vector<std::uint8_t> wrappedFruityState (const ForeignPlugin& plugin)
  548. {
  549. std::vector<std::uint8_t> native;
  550. FlVst2State state;
  551. // Fruity Phaser (REA_rodada105_phaser): the nine floats over the native ranges, except the stage count, which the
  552. // old plugin kept over 0…23 stages (FL's render test: an untouched instance saves 8/23 for the native 8 stages =
  553. // raw 7) [DATA; only the defaults were seen, the other values' mapping is not confirmed]
  554. if (plugin.name == "Fruity Phaser" && parseFlVst2State (plugin.state, state) && state.params.size() >= (std::size_t) phaserfx::params)
  555. {
  556. phaserfx::State s {};
  557. for (int k = 0; k < phaserfx::params; ++k)
  558. {
  559. const auto v = (double) std::clamp (state.params[(std::size_t) k], 0.0f, 1.0f);
  560. s[(std::size_t) k] = k == 5 ? std::clamp ((int) std::lround (v * 23.0) - 1, 0, phaserfx::rawMax[5])
  561. : (int) std::lround (v * phaserfx::rawMax[(std::size_t) k]);
  562. }
  563. return phaserfx::serialize (s);
  564. }
  565. if (plugin.name != "Fruity Compressor" || ! parseFlVst2State (plugin.state, state) || state.params.size() < fldyn::compressorControls)
  566. return native;
  567. auto put = [&native] (std::int32_t v) {
  568. for (int b = 0; b < 4; ++b)
  569. native.push_back ((std::uint8_t) ((std::uint32_t) v >> (8 * b)));
  570. };
  571. put (1);
  572. for (std::size_t k = 0; k < (std::size_t) fldyn::compressorControls; ++k)
  573. {
  574. const auto lo = fldyn::compressorMin[k], hi = fldyn::compressorMax[k];
  575. put (lo + (std::int32_t) std::lround (std::clamp (state.params[k], 0.0f, 1.0f) * (float) (hi - lo)));
  576. }
  577. return native;
  578. }
  579. } // namespace
  580. Song importFlp (const flp::Project& input, const FlpImportOptions& options)
  581. {
  582. // Patcher used as an instrument: the channel becomes the main generator inside it (REA_rodada14 §1)
  583. std::optional<flp::Project> unpacked;
  584. for (std::size_t i = 0; i < input.channels.size(); ++i)
  585. if (lowercase (input.channels[i].pluginName) == "patcher")
  586. if (const auto graph = parsePatcher (input.channels[i].pluginState); graph && graph->mainGenerator >= 0)
  587. {
  588. if (! unpacked)
  589. unpacked = input;
  590. const auto& node = graph->nodes[(std::size_t) graph->mainGenerator];
  591. unpacked->channels[i].pluginName = node.plugin;
  592. unpacked->channels[i].pluginState = node.state;
  593. }
  594. const auto& project = unpacked ? *unpacked : input;
  595. Song song;
  596. song.bpm = project.tempo > 0.0 ? project.tempo : 140.0;
  597. song.beatsPerBar = std::clamp (project.beatsPerBar, 1, 32);
  598. song.swing = std::clamp (project.swing / 128.0f, 0.0f, 1.0f);
  599. song.channelGroups = project.filterGroups;
  600. song.info.title = project.title;
  601. song.info.author = project.artist;
  602. song.info.genre = project.genre;
  603. song.info.url = project.url;
  604. song.info.comments = project.comments;
  605. std::replace (song.info.comments.begin(), song.info.comments.end(), '\r', '\n'); // (FL saves CR line breaks)
  606. // FL channels may have sparse indices; we map them to dense indices.
  607. std::map<int, int> channelMap;
  608. std::vector<std::pair<int, std::vector<DrumPad>>> drumKits; // FPC channels to split at the end
  609. std::optional<std::string> drumSynthDll; // the user's DrumSynth Live engine DLL, once checked ("" = not usable)
  610. // a sample on this PC: where the project says, else re-rooted from another PC's folders or next to the project
  611. // (`sampleUser` names what uses the sample, for the missing-files list; `record` false for paths only probed)
  612. std::string sampleUser;
  613. auto locateSample = [&] (const std::string& flPath, bool record = true) {
  614. auto found = locateFlSample (flPath, options.roots, options.projectFolder, options.fileExists);
  615. const auto saved = resolveFlPath (flPath, options.roots);
  616. if (found.empty())
  617. {
  618. if (const auto chosen = relocatedPath (options.relocations, saved); ! chosen.empty() && options.fileExists && options.fileExists (chosen))
  619. return chosen;
  620. if (record && options.report != nullptr)
  621. addMissingFile (options.report->missingFiles, saved, sampleUser);
  622. }
  623. else if (found != saved && options.report != nullptr)
  624. {
  625. ++options.report->relocatedSamples;
  626. if (record && std::none_of (options.report->relocatedFiles.begin(), options.report->relocatedFiles.end(),
  627. [&] (const auto& r) { return r.first == saved; }))
  628. options.report->relocatedFiles.push_back ({ saved, found });
  629. }
  630. return found;
  631. };
  632. for (const auto& c : project.channels)
  633. {
  634. // automation clips become Song::automations (further below), not channels
  635. if (c.type == flp::ChannelType::automationClip)
  636. continue;
  637. channelMap[c.index] = (int) song.channels.size();
  638. ChannelDef def;
  639. def.name = c.name.empty() ? "Channel " + std::to_string (c.index + 1) : c.name;
  640. sampleUser = (c.type == flp::ChannelType::audioClip ? "Audio clip: " : "") + def.name;
  641. def.instrument = guessInstrument (def.name, c.type);
  642. // FL synthesizer that becomes the internal synth: a preset matching the name (in FLEX, the name
  643. // of the preset chosen in the plugin says more than the channel's)
  644. if (def.instrument == InstrumentKind::synth)
  645. {
  646. def.synth = presetForChannelName (def.name);
  647. if (lowercase (c.pluginName) == "flex")
  648. if (const auto names = flexPresetName (c.pluginState))
  649. if (auto byPreset = presetForChannelName (names->second + " " + names->first); byPreset != SynthSettings {})
  650. def.synth = byPreset;
  651. }
  652. const auto isAudioClip = c.type == flp::ChannelType::audioClip;
  653. if ((c.type == flp::ChannelType::sampler || isAudioClip) && ! c.samplePath.empty() && options.fileExists)
  654. {
  655. const auto path = locateSample (c.samplePath);
  656. if (! path.empty())
  657. {
  658. def.instrument = isAudioClip ? InstrumentKind::audioClip : InstrumentKind::sampler;
  659. def.samplePath = path;
  660. }
  661. }
  662. if (isAudioClip && def.instrument != InstrumentKind::audioClip)
  663. def.instrument = InstrumentKind::audioClip; // no file: stays silent, but the clip remains in the playlist
  664. def.mixerTrack = std::clamp (c.mixerTrack, 0, maxMixerTracks - 1);
  665. def.muted = ! c.enabled; // switched off in FL's Channel Rack: its notes don't play (REA_rodada80 §3.1)
  666. if (c.colour != 0)
  667. def.colour = 0xFF000000u | c.colour;
  668. if (c.filterGroup >= 0 && c.filterGroup < (int) project.filterGroups.size())
  669. def.group = c.filterGroup;
  670. if (c.hasLevels)
  671. {
  672. def.volume = std::clamp (c.volume / 12800.0f, 0.0f, 1.0f); // same curve (channelGain)
  673. def.pan = std::clamp ((c.pan - 6400) / 6400.0f, -1.0f, 1.0f);
  674. def.sampler.pitch = std::clamp (c.pitchCents / 100.0f, -24.0f, 24.0f);
  675. }
  676. // level adjustments (0xE5): FL multiplies the channel volume by the adjustment through the same curve
  677. // (gain = f(volume)·f(volAdj), REA_rodada3 §2 [DECOMP]; an FL render of one channel with volAdj 7286 vs 12800
  678. // differs by −10.4 dB, f() gives −10.7 dB, a linear factor −4.9 dB) and adds the pan adjustment to the pan.
  679. if (c.hasLevelAdjust)
  680. {
  681. if (c.volAdj != 12800)
  682. {
  683. const auto g = channelGain (def.volume) * channelGain (std::clamp (c.volAdj / 12800.0f, 0.0f, 1.0f));
  684. def.volume = std::clamp ((float) (std::log (10.0 * g + 1.0) / std::log (11.0)), 0.0f, 1.0f);
  685. }
  686. if (c.panAdj != 0)
  687. def.pan = std::clamp (def.pan + c.panAdj / 6400.0f, -1.0f, 1.0f);
  688. }
  689. // sample root note: our sampler plays at the original pitch at C5 (60)
  690. if (c.rootNote >= 0 && c.rootNote <= 127)
  691. def.sampler.pitch = std::clamp (def.sampler.pitch + (float) (60 - c.rootNote), -24.0f, 24.0f);
  692. def.swingMix = std::clamp (c.swingMix / 128.0f, 0.0f, 1.0f);
  693. def.cutGroup = c.cutGroup;
  694. def.cutBy = c.cutBy;
  695. // "cut itself" (group == cut by) and mono channel become the sampler's "cut"
  696. if ((c.cutGroup != 0 && c.cutGroup == c.cutBy) || c.maxVoices == 1)
  697. def.sampler.cut = true;
  698. def.synth.mono = c.monoFlag || c.maxVoices == 1;
  699. // channel porta and slide time: n = round((27^(v/1024) - 1) * 48/26) ticks of 1/192 beat
  700. // (REA_rodada6 §4); the time also applies to notes with their own porta
  701. {
  702. const auto ticks = std::round ((std::pow (27.0, std::clamp (c.slideTime, 0, 1660) / 1024.0) - 1.0) * 48.0 / 26.0);
  703. def.synth.portaBeats = def.sampler.portaBeats = (float) std::max (1.0, ticks) / 192.0f;
  704. def.synth.porta = def.sampler.porta = c.portaFlag;
  705. }
  706. // volume envelope (record 1 of 0xDA) -> sampler ADSR
  707. const auto& volumeEnvelope = c.envelopes[1];
  708. const auto hasVolumeEnvelope = volumeEnvelope.present && volumeEnvelope.enabled;
  709. if (hasVolumeEnvelope)
  710. {
  711. const auto& env = volumeEnvelope;
  712. const auto beats = (env.flags & 1) != 0; // tempo-synced: units in beats
  713. auto seconds = [&] (int v) {
  714. const auto t = flp::Channel::envelopeTime (v);
  715. return (float) (beats ? t * 2.0 * 60.0 / song.bpm : t); // 0.128 beat instead of 0.064 s
  716. };
  717. def.sampler.attack = std::clamp (seconds (env.attack), 0.0f, 2.0f);
  718. def.sampler.decay = std::clamp (seconds (env.decay), 0.0f, 10.0f);
  719. def.sampler.sustain = std::clamp (env.sustain / 128.0f, 0.0f, 1.0f);
  720. def.sampler.release = std::clamp (std::max (seconds (env.release), 0.002f), 0.0f, 4.0f); // envelope on: the note ends
  721. // FL's own articulator (delay, hold, tensions, tick steps; REA_rodada69 §3) from the record as stored
  722. if (env.rawSize >= 68 && c.type == flp::ChannelType::sampler)
  723. {
  724. def.sampler.flVolumeEnvelope.resize (18);
  725. std::memcpy (def.sampler.flVolumeEnvelope.data(), env.raw.data(), 68);
  726. def.sampler.flVolumeEnvelope[17] = project.header.ppq > 0 ? project.header.ppq : 96;
  727. }
  728. }
  729. // FL's whole native sampler voice (REA_rodada76): the five articulator records as stored (a missing one keeps
  730. // the plugins' default record), Mod X/Y, filter type, PPQ
  731. if (c.type == flp::ChannelType::sampler && def.instrument == InstrumentKind::sampler)
  732. {
  733. const auto defaults = flvp::defaultSnapshot();
  734. def.sampler.flChannel.assign (90, 0);
  735. for (int k = 0; k < 5; ++k)
  736. {
  737. const auto& env = c.envelopes[(std::size_t) k];
  738. const auto* src = env.rawSize >= 68 ? env.raw.data() : defaults.data() + 0x44 * k;
  739. std::memcpy (def.sampler.flChannel.data() + 17 * k, src, 68);
  740. }
  741. def.sampler.flChannel[85] = c.modX;
  742. def.sampler.flChannel[86] = c.modY;
  743. def.sampler.flChannel[87] = c.filterType;
  744. def.sampler.flChannel[88] = project.header.ppq > 0 ? project.header.ppq : 96;
  745. def.sampler.flChannel[89] = project.panLaw;
  746. }
  747. // channel filter (Mod X/Y + type from 0xDB) applies to the sampler too
  748. synthFilterFromChannel (c.modX, c.modY, c.filterType, def.sampler.cutoff, def.sampler.resonance, def.sampler.filterType);
  749. // channel cutoff (record 2) and pitch (record 4) envelopes
  750. auto modEnvelope = [&] (const flp::Channel::Envelope& env, float amount) {
  751. ModEnvelope m;
  752. if (! env.present || ! env.enabled || amount == 0.0f)
  753. return m;
  754. const auto beats = (env.flags & 1) != 0;
  755. auto seconds = [&] (int v) {
  756. const auto t = flp::Channel::envelopeTime (v);
  757. return (float) std::clamp (beats ? t * 2.0 * 60.0 / song.bpm : t, 0.0, 20.0);
  758. };
  759. m.amount = amount;
  760. m.attack = seconds (env.attack);
  761. m.hold = seconds (env.hold);
  762. m.decay = seconds (env.decay);
  763. m.sustain = std::clamp (env.sustain / 128.0f, 0.0f, 1.0f);
  764. m.release = seconds (env.release);
  765. return m;
  766. };
  767. const auto filterEnv = modEnvelope (c.envelopes[2], filterEnvelopeOctaves (c.modX, c.filterType, c.envelopes[2].amount));
  768. const auto pitchEnv = modEnvelope (c.envelopes[4], std::clamp (c.envelopes[4].amount, -2400, 2400) / 100.0f);
  769. def.sampler.filterEnv = filterEnv;
  770. def.sampler.pitchEnv = pitchEnv;
  771. // channel LFOs (records 0 pan, 1 volume, 2 cutoff, 4 pitch; REA_rodada6 §2)
  772. {
  773. auto lfoFrom = [&] (const flp::Channel::Envelope& env, float amount) {
  774. ChannelLfo l;
  775. if (! env.present || env.lfoAmount == 0 || amount == 0.0f)
  776. return l;
  777. l.sync = (env.flags & 0x02) != 0;
  778. auto time = [&] (int v) { // seconds, or beats when synced (double the scale)
  779. const auto t = flp::Channel::envelopeTime (v);
  780. return (float) std::clamp (l.sync ? t * 2.0 : t, 0.0, 64.0);
  781. };
  782. l.amount = amount;
  783. l.period = std::max (0.01f, time (env.lfoSpeed));
  784. l.shape = std::clamp (env.lfoShape, 0, 2);
  785. l.delay = time (env.lfoDelay);
  786. l.attack = time (env.lfoAttack);
  787. l.global = (env.flags & 0x20) != 0;
  788. return l;
  789. };
  790. std::array<ChannelLfo, lfoTargets> lfo {};
  791. lfo[lfoPan] = lfoFrom (c.envelopes[0], std::clamp (c.envelopes[0].lfoAmount, -64, 64) / 64.0f);
  792. lfo[lfoVolume] = lfoFrom (c.envelopes[1], std::clamp (c.envelopes[1].lfoAmount, -128, 128) / 128.0f);
  793. lfo[lfoCutoff] = lfoFrom (c.envelopes[2], filterEnvelopeOctaves (c.modX, c.filterType, c.envelopes[2].lfoAmount));
  794. lfo[lfoPitch] = lfoFrom (c.envelopes[4], std::clamp (c.envelopes[4].lfoAmount, -2400, 2400) / 100.0f);
  795. def.sampler.lfo = lfo;
  796. def.synth.lfo = lfo;
  797. }
  798. // third-party plugin (VST/CLAP) in Fruity Wrapper: the app looks for the same installed plugin;
  799. // until then (or if not found) the channel stays on the internal synth
  800. // FL generators with samples (REA_rodada9): DirectWave becomes a multi-sample sampler; FPC is
  801. // split into one channel per pad at the end of the import (notes go to the pad by key)
  802. auto existing = [&] (std::string path) { return locateSample (path); };
  803. auto installed = [&] (std::string path) { return locateSample (path, false); }; // FL's own data (FL Keys wavetables)
  804. // DirectWave: the exact engine (REA_rodada72); the multi-sample sampler stays as the fallback
  805. bool directWaveExact = false;
  806. if (c.pluginName == "DirectWave")
  807. directWaveExact = dw::importChannel (def, c.pluginState, existing, options.readFile, options.saveEmbedded);
  808. if (c.pluginName == "DirectWave" && ! directWaveExact)
  809. if (auto program = directWaveProgram (c.pluginState))
  810. {
  811. std::vector<SampleZone> zones;
  812. for (std::size_t i = 0; i < program->zones.size(); ++i)
  813. {
  814. auto z = program->zones[i];
  815. auto path = existing (z.path);
  816. // file missing on this machine: use the audio the project stored with it
  817. if (path.empty() && i < program->embeddedWav.size() && ! program->embeddedWav[i].empty() && options.saveEmbedded)
  818. path = options.saveEmbedded (program->embeddedWav[i], def.name + " " + std::to_string (i + 1));
  819. if (! path.empty())
  820. {
  821. z.path = path;
  822. zones.push_back (std::move (z));
  823. }
  824. }
  825. if (! zones.empty())
  826. {
  827. def.instrument = InstrumentKind::sampler;
  828. def.zones = std::move (zones);
  829. def.sampler.attack = std::clamp (program->attack, 0.0f, 2.0f);
  830. def.sampler.decay = std::clamp (program->decay, 0.0f, 10.0f);
  831. def.sampler.sustain = program->sustain;
  832. def.sampler.release = std::clamp (std::max (program->release, 0.01f), 0.0f, 4.0f);
  833. }
  834. }
  835. // Fruity Slicer / Slicex: sampler with the slices (slice i plays on key 60 + i, at the sample's pitch)
  836. {
  837. const auto name = lowercase (c.pluginName);
  838. std::optional<SlicedSample> sliced;
  839. if (name == "fruity slicer")
  840. sliced = fruitySlicer (c.pluginState);
  841. else if (name == "slicex")
  842. sliced = slicex (c.pluginState);
  843. if (sliced)
  844. {
  845. std::string path;
  846. if (! sliced->embeddedWav.empty() && options.saveEmbedded) // audio that only exists inside the project
  847. path = options.saveEmbedded (sliced->embeddedWav, def.name);
  848. if (path.empty())
  849. path = existing (sliced->path);
  850. if (! path.empty())
  851. {
  852. auto positions = sliced->positions;
  853. std::int64_t frames = 0;
  854. if (positions.empty()) // Slicex: the slices are the WAV "cue" points
  855. {
  856. const auto bytes = ! sliced->embeddedWav.empty() ? sliced->embeddedWav
  857. : options.readFile ? options.readFile (path) : std::vector<std::uint8_t> {};
  858. positions = wavCuePoints (bytes, frames);
  859. }
  860. if (frames <= 0 && options.sampleFrames)
  861. frames = options.sampleFrames (path);
  862. def.instrument = InstrumentKind::sampler;
  863. def.samplePath = path;
  864. def.sampler.pitch = std::clamp (def.sampler.pitch + sliced->pitchCents / 100.0f, -24.0f, 24.0f);
  865. // Slicex's master volume (REA_rodada69 §5): a single full-range zone carries the gain
  866. if (sliced->gain != 1.0f && ! path.empty())
  867. {
  868. SampleZone zone;
  869. zone.path = path;
  870. zone.gain = sliced->gain;
  871. def.zones = { zone };
  872. }
  873. if (frames > 0)
  874. for (auto p : positions)
  875. if (p >= 0 && p < frames)
  876. def.sampler.slices.push_back ((float) ((double) p / (double) frames));
  877. }
  878. }
  879. }
  880. // FL Keys: FL's engine on the wavetable (.wti) that ships with FL (REA_rodada69 §8); the zoned sampler is the
  881. // fallback when the wavetable cannot be read
  882. bool flKeysExact = false;
  883. if (c.pluginName == "FL Keys" && options.readFile && ! options.roots.factoryData.empty())
  884. flKeysExact = flkeys::importChannel (def, c.pluginState, options.roots.factoryData + "\\Plugins\\Fruity\\Generators\\FL Keys\\Wavtables",
  885. options.readFile, installed, options.saveEmbedded);
  886. if (c.pluginName == "FL Keys" && ! flKeysExact && options.readFile && ! options.roots.factoryData.empty())
  887. if (const auto set = flKeysSet (c.pluginState))
  888. {
  889. const auto folder = options.roots.factoryData + "\\Plugins\\Fruity\\Generators\\FL Keys\\Wavtables";
  890. const auto wtiBytes = options.readFile (folder + "\\" + *set + ".wti");
  891. const std::string wti (wtiBytes.begin(), wtiBytes.end());
  892. std::vector<std::uint8_t> rawData;
  893. if (wti.find ("filetype=raw") != std::string::npos)
  894. if (const auto file = wti.find ("samplefile="); file != std::string::npos)
  895. {
  896. auto name = wti.substr (file + 11, wti.find_first_of ("\r\n", file) - file - 11);
  897. rawData = options.readFile (folder + "\\" + name);
  898. }
  899. std::vector<SampleZone> zones;
  900. for (auto z : flKeysZones (wti, folder, rawData, options.saveEmbedded))
  901. if (z.path = installed (z.path); ! z.path.empty())
  902. zones.push_back (std::move (z));
  903. if (! zones.empty())
  904. {
  905. def.instrument = InstrumentKind::sampler;
  906. def.zones = std::move (zones);
  907. def.sampler.release = 0.4f; // the piano releases the note with a short release
  908. }
  909. }
  910. // Wave Traveller: plays its sample (the scratch curve is left out)
  911. if (c.pluginName == "Wave Traveller")
  912. if (const auto wave = waveTravellerSample (c.pluginState))
  913. if (auto path = existing (wave->first); ! path.empty())
  914. {
  915. def.instrument = InstrumentKind::sampler;
  916. def.samplePath = std::move (path);
  917. def.sampler.pitch = std::clamp (def.sampler.pitch + (float) (60 - wave->second), -24.0f, 24.0f);
  918. }
  919. // Fruity Envelope Controller: "controller" channel (silent) that triggers the envelopes from notes
  920. if ((c.pluginName == "Fruity Envelope Controller" && parseEnvelopeController (c.pluginState))
  921. || (c.pluginName == "Fruity Keyboard Controller" && parseKeyboardController (c.pluginState)))
  922. {
  923. def.instrument = InstrumentKind::controller;
  924. def.controllerState = c.pluginState;
  925. }
  926. // Fruity DrumSynth Live: its engine with all 120 patches (REA_rodada30 §1); the recorded waveforms some patches
  927. // use are read at run time from the user's own engine DLL (without it they are silent, the synthesis is not).
  928. // Fallback when the state can't be parsed: the FL drum sample with the same name as the editor's sound
  929. if (c.pluginName == "Fruity DrumSynth Live")
  930. {
  931. if (auto params = drumSynthLiveParams (c.pluginState))
  932. {
  933. def.instrument = InstrumentKind::drumsynth;
  934. def.modelParams = std::move (*params);
  935. if (! drumSynthDll)
  936. {
  937. drumSynthDll = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Fruity DrumSynth Live\\drumsynth_eng_x64.dll",
  938. options.roots);
  939. if (drumSynthDll->empty() || ! options.fileExists || ! options.fileExists (*drumSynthDll) || ! drumSynthDllUsable (*drumSynthDll))
  940. drumSynthDll = std::string();
  941. }
  942. def.samplePath = *drumSynthDll;
  943. }
  944. else if (const auto sound = drumSynthLiveSound (c.pluginState))
  945. for (const auto& candidate : drumSampleCandidates (*sound))
  946. if (auto path = locateSample (candidate, false); ! path.empty())
  947. {
  948. def.instrument = InstrumentKind::sampler;
  949. def.samplePath = std::move (path);
  950. break;
  951. }
  952. }
  953. if (c.pluginName == "FPC")
  954. if (auto pads = fpcPads (c.pluginState))
  955. {
  956. std::vector<DrumPad> found;
  957. for (auto pad : *pads)
  958. {
  959. std::vector<SampleZone> layers;
  960. for (auto layer : pad.layers)
  961. if (layer.path = existing (layer.path); ! layer.path.empty())
  962. layers.push_back (std::move (layer));
  963. pad.layers = std::move (layers);
  964. if (! pad.layers.empty())
  965. found.push_back (std::move (pad));
  966. }
  967. if (! found.empty())
  968. drumKits.push_back ({ (int) song.channels.size(), std::move (found) });
  969. }
  970. if (c.pluginName == "Fruity Wrapper" && parseFlWrapper (c.pluginState, def.plugin.foreign))
  971. def.plugin.name = def.plugin.foreign.name;
  972. // Fruit Kick, MiniSynth, ... (REA_rodada10): approximated by the internal synth; the channel LFOs are kept
  973. bool adoptedFromPlugin = false;
  974. if (def.instrument == InstrumentKind::synth)
  975. {
  976. const auto name = lowercase (c.pluginName);
  977. SynthSettings fromPlugin;
  978. float pluginGain = 1.0f;
  979. auto adopt = [&] {
  980. for (int i = 0; i < lfoTargets; ++i)
  981. if (def.synth.lfo[(std::size_t) i].amount != 0.0f)
  982. fromPlugin.lfo[(std::size_t) i] = def.synth.lfo[(std::size_t) i];
  983. def.synth = fromPlugin;
  984. adoptedFromPlugin = true;
  985. const auto g = channelGain (def.volume) * pluginGain;
  986. def.volume = std::clamp ((float) (std::log (10.0 * g + 1.0) / std::log (11.0)), 0.0f, 1.0f);
  987. };
  988. if (name == "3x osc" && ! options.threeOscAsSynth && threeOscStateUsable (c.pluginState))
  989. {
  990. // FL's 3x Osc engine (REA_rodada47) with the channel settings its voice processor keeps (the channel's
  991. // 0xDA/0xDB records, which FL restores after the plugin state) and the project's PPQ for the envelope
  992. // ticks; the channel's sample (if any) is the custom wave of shape 6. The internal-synth conversion
  993. // stays as the fallback (state unreadable)
  994. def.instrument = InstrumentKind::threeosc;
  995. const auto fromChannel = c.hasLevels || std::any_of (c.envelopes.begin(), c.envelopes.end(), [] (const auto& e) { return e.present; });
  996. def.pluginState = threeOscNormalisedState (c.pluginState, fromChannel ? dx10Snapshot (c) : std::vector<std::uint8_t> {});
  997. def.modelParams = { (float) (project.header.ppq > 0 ? project.header.ppq : 96) };
  998. if (! c.samplePath.empty() && options.fileExists)
  999. {
  1000. auto path = resolveFlPath (c.samplePath, options.roots);
  1001. if (! path.empty() && (path[0] == '\\' || path[0] == '/') && ! options.roots.factoryData.empty())
  1002. path = options.roots.factoryData + "\\Data" + path; // (old presets: relative to FL's Data folder)
  1003. if (! path.empty() && ! options.fileExists (path) && options.fileExists (path + ".wav"))
  1004. path += ".wav";
  1005. if (! path.empty() && options.fileExists (path))
  1006. def.samplePath = path;
  1007. }
  1008. adoptedFromPlugin = true;
  1009. }
  1010. else if (name == "fruity granulizer" && granulizerStateUsable (c.pluginState))
  1011. {
  1012. // FL's Fruity Granulizer engine (REA_rodada67) on the channel's sample (FL hands it to the plugin), with the
  1013. // channel settings its voice processor keeps and the project's PPQ, as 3x Osc. Without the sample the
  1014. // channel stays silent, as in FL (the plugin refuses notes)
  1015. def.instrument = InstrumentKind::granulizer;
  1016. const auto fromChannel = c.hasLevels || std::any_of (c.envelopes.begin(), c.envelopes.end(), [] (const auto& e) { return e.present; });
  1017. def.pluginState = granulizerNormalisedState (c.pluginState, fromChannel ? dx10Snapshot (c) : std::vector<std::uint8_t> {});
  1018. def.modelParams = { (float) (project.header.ppq > 0 ? project.header.ppq : 96) };
  1019. if (! c.samplePath.empty() && options.fileExists)
  1020. {
  1021. auto path = resolveFlPath (c.samplePath, options.roots);
  1022. if (! path.empty() && (path[0] == '\\' || path[0] == '/') && ! options.roots.factoryData.empty())
  1023. path = options.roots.factoryData + "\\Data" + path;
  1024. if (! path.empty() && ! options.fileExists (path) && options.fileExists (path + ".wav"))
  1025. path += ".wav";
  1026. if (! path.empty() && options.fileExists (path))
  1027. def.samplePath = path;
  1028. }
  1029. adoptedFromPlugin = true;
  1030. }
  1031. else if (name == "harmless")
  1032. {
  1033. // FL's additive engine (REA_rodada32); the internal synth approximation stays as the fallback
  1034. if (auto params = harmlessParams (c.pluginState))
  1035. {
  1036. def.instrument = InstrumentKind::harmless;
  1037. def.modelParams = std::move (*params);
  1038. adoptedFromPlugin = true;
  1039. // rack compressor: Harmless's own preset <n>.fst from the user's installation (REA_rodada36 §2)
  1040. const auto compType = (int) def.modelParams[(std::size_t) harmlessComboIndex + 3];
  1041. if (compType > 0)
  1042. {
  1043. const auto path = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Harmless\\Data\\Compression\\"
  1044. + std::to_string (compType) + ".fst",
  1045. options.roots);
  1046. std::optional<std::vector<std::uint8_t>> state;
  1047. if (! path.empty() && options.readFile && (! options.fileExists || options.fileExists (path)))
  1048. state = hlfx::maximusStateFromFst (options.readFile (path));
  1049. if (state && hlfx::makeMaximusPreset (*state) != nullptr)
  1050. {
  1051. def.modelParams.push_back ((float) state->size());
  1052. for (const auto byte : *state)
  1053. def.modelParams.push_back ((float) byte);
  1054. }
  1055. else if (options.report != nullptr)
  1056. ++options.report->droppedEffects["Harmless compressor (preset not found)"];
  1057. }
  1058. }
  1059. else if (synthFromHarmless (c.pluginState, song.bpm, fromPlugin, pluginGain))
  1060. adopt();
  1061. }
  1062. else if (name == "fruit kick")
  1063. {
  1064. // FL's Fruit Kick engine with its voice framework (REA_rodada43 §1). A version-0 state has no envelope
  1065. // snapshot of its own: FL hands the plugin the channel's envelope/filter records, so they are appended
  1066. // to it. The sine + pitch-envelope conversion stays as the fallback for unreadable states.
  1067. if (fruitKickStateUsable (c.pluginState))
  1068. {
  1069. // the same 364-byte channel snapshot as DX10's (REA_rodada42 §3): five 68-byte records + Mod X/Y + type
  1070. const auto snap = dx10Snapshot (c);
  1071. std::vector<std::vector<std::uint8_t>> records;
  1072. for (int k = 0; k < 5; ++k)
  1073. records.emplace_back (snap.begin() + 68 * k, snap.begin() + 68 * (k + 1));
  1074. std::int32_t cut = 256, res = 0, type = 0;
  1075. std::memcpy (&cut, snap.data() + 0x15c, 4);
  1076. std::memcpy (&res, snap.data() + 0x160, 4);
  1077. std::memcpy (&type, snap.data() + 0x168, 4);
  1078. def.instrument = InstrumentKind::fruitkick;
  1079. def.pluginState = fruitKickWithChannelEnvelope (c.pluginState, records, cut, res, type);
  1080. adoptedFromPlugin = true;
  1081. if (options.report != nullptr)
  1082. for (const auto& f : fruitKickFallbacks (def.pluginState))
  1083. ++options.report->droppedEffects["Fruit Kick: " + f];
  1084. }
  1085. else if (synthFromFruitKick (c.pluginState, fromPlugin))
  1086. adopt();
  1087. }
  1088. else if (name == "minisynth")
  1089. {
  1090. // FL's MiniSynth engine from the raw state (REA_rodada41) with its wave tables built at run time from the
  1091. // installation's oscdata.dat; the internal-synth conversion stays as the fallback (state unreadable or
  1092. // file not found)
  1093. const auto oscdata = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Minisynth\\oscdata.dat", options.roots);
  1094. if (miniSynthStateUsable (c.pluginState) && ! oscdata.empty() && options.fileExists && options.fileExists (oscdata))
  1095. {
  1096. def.instrument = InstrumentKind::minisynth;
  1097. def.pluginState = c.pluginState;
  1098. def.samplePath = oscdata;
  1099. adoptedFromPlugin = true;
  1100. }
  1101. else if (synthFromMiniSynth (c.pluginState, song.bpm, fromPlugin))
  1102. adopt();
  1103. }
  1104. else if (name == "fruity dx10" || name == "dx10")
  1105. {
  1106. // FL's FM engine from the raw state (REA_rodada42), with the channel settings its voice processor
  1107. // keeps (a version-2 state's own snapshot, else the channel's 0xDA/0xDB records) and the project's PPQ
  1108. // for the envelope ticks; the 3-oscillator FM approximation stays as a fallback
  1109. if (auto st = dx10StateWithSnapshot (c.pluginState, dx10Snapshot (c)); ! st.empty())
  1110. {
  1111. def.instrument = InstrumentKind::dx10;
  1112. def.pluginState = std::move (st);
  1113. def.modelParams = { (float) (project.header.ppq > 0 ? project.header.ppq : 96) };
  1114. adoptedFromPlugin = true;
  1115. }
  1116. else if (synthFromDX10 (c.pluginState, fromPlugin))
  1117. adopt();
  1118. }
  1119. else if (name == "sytrus")
  1120. {
  1121. // FL's Sytrus engine from the raw state (REA_rodada31); the 3-oscillator conversion stays as a fallback
  1122. if (sytrus::stateUsable (c.pluginState))
  1123. {
  1124. def.instrument = InstrumentKind::sytrus;
  1125. def.pluginState = c.pluginState;
  1126. adoptedFromPlugin = true;
  1127. }
  1128. else if (synthFromSytrus (c.pluginState, song.bpm, fromPlugin, pluginGain))
  1129. adopt();
  1130. }
  1131. else if (name == "harmor")
  1132. {
  1133. // FL's additive engine from the raw state (REA_rodada34); the spectral-oscillator conversion stays as
  1134. // the fallback for states the engine can't read
  1135. if (harmorStateUsable (c.pluginState))
  1136. {
  1137. def.instrument = InstrumentKind::harmor;
  1138. def.pluginState = c.pluginState;
  1139. adoptedFromPlugin = true;
  1140. // rack compressor: Harmor's own preset System\Compression\<n>.fst from the user's installation
  1141. // (REA_rodada38); its Maximus state goes into modelParams (size, bytes…)
  1142. const auto compType = harmorCompressorType (c.pluginState);
  1143. if (compType > 0)
  1144. {
  1145. const auto path = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Harmor\\System\\Compression\\"
  1146. + std::to_string (compType) + ".fst",
  1147. options.roots);
  1148. std::optional<std::vector<std::uint8_t>> state;
  1149. if (! path.empty() && options.readFile && (! options.fileExists || options.fileExists (path)))
  1150. state = hlfx::maximusStateFromFst (options.readFile (path));
  1151. if (state && hlfx::makeMaximusPreset (*state) != nullptr)
  1152. {
  1153. def.modelParams.clear();
  1154. def.modelParams.push_back ((float) state->size());
  1155. for (const auto byte : *state)
  1156. def.modelParams.push_back ((float) byte);
  1157. }
  1158. else if (options.report != nullptr)
  1159. ++options.report->droppedEffects["Harmor compressor (preset not found)"];
  1160. }
  1161. }
  1162. else if (synthFromHarmor (c.pluginState, fromPlugin, pluginGain))
  1163. adopt();
  1164. }
  1165. else if (name == "gms")
  1166. {
  1167. // FL's GMS engine from the raw state (REA_rodada39 §1) with its oscillator waves read at run time from
  1168. // the user's installation; the 3-oscillator conversion stays as the fallback (state unreadable or waves
  1169. // not found)
  1170. const auto folder = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\GMS\\Synth Waves", options.roots);
  1171. const auto waves = gmsWaveNames (c.pluginState);
  1172. const auto wavesFound = ! waves.empty() && ! folder.empty() && options.fileExists
  1173. && std::all_of (waves.begin(), waves.end(), [&] (const std::string& w) {
  1174. return w.empty() || options.fileExists (folder + "\\" + w + ".wav");
  1175. });
  1176. if (gmsStateUsable (c.pluginState) && wavesFound)
  1177. {
  1178. def.instrument = InstrumentKind::gms;
  1179. def.pluginState = c.pluginState;
  1180. def.samplePath = folder;
  1181. adoptedFromPlugin = true;
  1182. }
  1183. else if (synthFromGms (c.pluginState, song.bpm, fromPlugin, pluginGain))
  1184. adopt();
  1185. }
  1186. else if (name == "ogun" || name == "autogun")
  1187. {
  1188. // FL's inverse-FFT engine from the raw state (REA_rodada37). Autogun (REA_rodada57) runs the same engine on
  1189. // its state variant, then its Magic Dust stage with the preset Autogun\Data\SG.dat of the user's FL
  1190. // installation (read at run time; without it the stage is skipped). States the engine can't read keep the
  1191. // spectral-oscillator conversion.
  1192. if (name == "ogun" && ogunStateUsable (c.pluginState))
  1193. {
  1194. def.instrument = InstrumentKind::ogun;
  1195. def.pluginState = c.pluginState;
  1196. adoptedFromPlugin = true;
  1197. }
  1198. else if (name == "autogun" && autogunStateUsable (c.pluginState))
  1199. {
  1200. def.instrument = InstrumentKind::autogun;
  1201. def.pluginState = c.pluginState;
  1202. const auto sg = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Autogun\\Data\\SG.dat", options.roots);
  1203. if (! sg.empty() && (! options.fileExists || options.fileExists (sg)))
  1204. def.samplePath = sg;
  1205. else if (options.report != nullptr && ogunParam (c.pluginState, 63).value_or (0) > 0)
  1206. ++options.report->droppedEffects["Autogun: Magic Dust (SG.dat not found)"];
  1207. adoptedFromPlugin = true;
  1208. }
  1209. else if (synthFromOgun (c.pluginState, fromPlugin, pluginGain))
  1210. adopt();
  1211. }
  1212. else if (name == "sakura")
  1213. {
  1214. // the physical string model (REA_rodada28 §1); the old saw + triangle stays as a fallback
  1215. if (auto params = sakuraParams (c.pluginState))
  1216. {
  1217. def.instrument = InstrumentKind::sakura;
  1218. def.modelParams = std::move (*params);
  1219. adoptedFromPlugin = true;
  1220. }
  1221. else if (synthFromSakura (c.pluginState, fromPlugin))
  1222. adopt();
  1223. }
  1224. else if (name == "simsynth")
  1225. {
  1226. // FL's SimSynth engine from the raw state (REA_rodada64 §1–4); it needs no installation data. A state the
  1227. // engine can't read keeps the channel unsupported (there is no conversion to fall back to)
  1228. if (simSynthStateUsable (c.pluginState))
  1229. {
  1230. def.instrument = InstrumentKind::simsynth;
  1231. def.pluginState = c.pluginState;
  1232. adoptedFromPlugin = true;
  1233. }
  1234. }
  1235. else if (name == "drumaxx")
  1236. {
  1237. // FL's Drumaxx engine from the raw state (REA_rodada67 §6–§9); it needs no installation data. A state the
  1238. // engine can't read keeps the channel unsupported (there is no conversion to fall back to)
  1239. if (drumaxxStateUsable (c.pluginState))
  1240. {
  1241. def.instrument = InstrumentKind::drumaxx;
  1242. def.pluginState = c.pluginState;
  1243. adoptedFromPlugin = true;
  1244. }
  1245. }
  1246. else if (name == "wasp" || name == "wasp xt")
  1247. {
  1248. // FL 2026 has no 64-bit Wasp: its DLL is a placeholder that keeps the state and plays nothing (REA_rodada64 §5)
  1249. def.instrument = InstrumentKind::wasp;
  1250. def.pluginState = c.pluginState;
  1251. adoptedFromPlugin = true;
  1252. }
  1253. else if (name == "fl slayer")
  1254. {
  1255. // FL's engine from the raw state (REA_rodada68) with the recorded pick excitations, chord and glide tables
  1256. // read at run time from the user's own Slayer_Engine.dll; there is no conversion to fall back to (state or
  1257. // DLL not usable: the channel stays unsupported)
  1258. const auto dll = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\FL Slayer\\Slayer_Engine.dll", options.roots);
  1259. if (slayerStateUsable (c.pluginState) && ! dll.empty() && options.fileExists && options.fileExists (dll) && slayerDllUsable (dll))
  1260. {
  1261. def.instrument = InstrumentKind::slayer;
  1262. def.pluginState = c.pluginState;
  1263. def.samplePath = dll;
  1264. // the root-note shift stays in the key; the rest of the channel pitch reaches FL Slayer as a pitch
  1265. // bend (ProcessEvent 4, REA_rodada79 §2.2)
  1266. def.modelParams = { c.rootNote >= 0 && c.rootNote <= 127 ? (float) (60 - c.rootNote) : 0.0f };
  1267. adoptedFromPlugin = true;
  1268. }
  1269. }
  1270. else if (name == "fruity dance")
  1271. {
  1272. // a visual plugin: notes change the dance, its Gen_Render writes nothing (REA_rodada68 §8)
  1273. def.instrument = InstrumentKind::fruitydance;
  1274. def.pluginState = c.pluginState;
  1275. adoptedFromPlugin = true;
  1276. }
  1277. else if (name == "transistor bass")
  1278. {
  1279. // FL's engine from the raw state (REA_rodada57 §2) with the "303 Pulse" oscillator cycles read at run time
  1280. // from the user's own engine DLL; there is no conversion to fall back to (state or DLL not usable: the
  1281. // channel stays unsupported)
  1282. const auto dll = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Transistor Bass\\engine_x64.dll", options.roots);
  1283. if (transistorBassStateUsable (c.pluginState) && ! dll.empty() && options.fileExists && options.fileExists (dll)
  1284. && transistorBassDllUsable (dll))
  1285. {
  1286. def.instrument = InstrumentKind::transistorbass;
  1287. def.pluginState = c.pluginState;
  1288. def.samplePath = dll;
  1289. adoptedFromPlugin = true;
  1290. }
  1291. }
  1292. else if (name == "plucked!")
  1293. {
  1294. // FL's Karplus-Strong engine from the raw state (REA_rodada65 §1); there was no conversion before
  1295. if (pluckedStateUsable (c.pluginState))
  1296. {
  1297. def.instrument = InstrumentKind::plucked;
  1298. def.pluginState = c.pluginState;
  1299. adoptedFromPlugin = true;
  1300. }
  1301. }
  1302. else if (name == "beepmap")
  1303. {
  1304. // FL's image-synthesis engine from the raw state, bitmap included (REA_rodada65 §2)
  1305. if (beepMapStateUsable (c.pluginState))
  1306. {
  1307. def.instrument = InstrumentKind::beepmap;
  1308. def.pluginState = c.pluginState;
  1309. def.modelParams = { (float) (project.header.ppq > 0 ? project.header.ppq : 96) };
  1310. adoptedFromPlugin = true;
  1311. }
  1312. }
  1313. else if (name == "sawer")
  1314. {
  1315. // FL's engine from the raw state (REA_rodada65 §3) with its oscillator cycle read at run time from the
  1316. // user's Sawer\data.saw; there was no conversion before (state or file not usable: unsupported)
  1317. const auto saw = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Sawer\\data.saw", options.roots);
  1318. if (sawerStateUsable (c.pluginState) && ! saw.empty() && options.fileExists && options.fileExists (saw))
  1319. {
  1320. def.instrument = InstrumentKind::sawer;
  1321. def.pluginState = c.pluginState;
  1322. def.samplePath = saw;
  1323. adoptedFromPlugin = true;
  1324. }
  1325. }
  1326. else if (name == "kepler")
  1327. {
  1328. // FL's engine from the raw state (REA_rodada46) with its LFO-shape and noise tables read at run time from the
  1329. // user's own engine DLL; the synth conversion stays as the fallback (state or DLL not usable)
  1330. const auto dll = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Kepler\\engine_x64.dll", options.roots);
  1331. if (keplerStateUsable (c.pluginState) && ! dll.empty() && options.fileExists && options.fileExists (dll) && keplerDllUsable (dll))
  1332. {
  1333. def.instrument = InstrumentKind::kepler;
  1334. def.pluginState = c.pluginState;
  1335. def.samplePath = dll;
  1336. adoptedFromPlugin = true;
  1337. }
  1338. else if (synthFromKepler (c.pluginState, fromPlugin, pluginGain))
  1339. adopt();
  1340. }
  1341. else if (name == "boobass")
  1342. {
  1343. // FL's engine with its multisample read at run time from the user's own BooBass DLL (REA_rodada29 §4)
  1344. const auto dll = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\BooBass\\BooBass_Eng_x64.dll", options.roots);
  1345. auto word = [&] (std::size_t at) { std::uint32_t v = 0; std::memcpy (&v, c.pluginState.data() + at, 4); return v; };
  1346. if (c.pluginState.size() >= 16 && word (0) == 1 && ! dll.empty() && options.fileExists && options.fileExists (dll)
  1347. && booBassDllUsable (dll))
  1348. {
  1349. def.instrument = InstrumentKind::boobass;
  1350. def.samplePath = dll;
  1351. for (std::size_t k = 0; k < 3; ++k)
  1352. def.modelParams.push_back ((float) std::clamp ((int) word (4 + 4 * k), 0, 65535));
  1353. adoptedFromPlugin = true;
  1354. }
  1355. else if (synthFromBooBass (c.pluginState, fromPlugin))
  1356. adopt();
  1357. }
  1358. else if (name == "poizone")
  1359. {
  1360. // FL's PoiZone engine from the raw state (REA_rodada44); the 2-oscillator conversion stays as the
  1361. // fallback for states the engine can't read
  1362. if (poizoneStateUsable (c.pluginState))
  1363. {
  1364. def.instrument = InstrumentKind::poizone;
  1365. def.pluginState = c.pluginState;
  1366. adoptedFromPlugin = true;
  1367. }
  1368. else if (synthFromPoiZone (c.pluginState, fromPlugin, pluginGain))
  1369. adopt();
  1370. }
  1371. else if (name == "bassdrum")
  1372. {
  1373. // FL's BassDrum engine (REA_rodada43 §2) reading its oscillator table and noise sample at run time from
  1374. // the user's BassDrum folder; the sine + sweep conversion stays as the fallback (state unreadable or
  1375. // folder not found)
  1376. const auto folder = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\BassDrum", options.roots);
  1377. const auto tableFound = ! folder.empty() && options.fileExists && options.fileExists (folder + "\\sounddata");
  1378. if (bassDrumStateUsable (c.pluginState) && tableFound)
  1379. {
  1380. def.instrument = InstrumentKind::bassdrum;
  1381. def.pluginState = c.pluginState;
  1382. def.samplePath = folder;
  1383. adoptedFromPlugin = true;
  1384. if (const auto noise = bassDrumNoiseName (c.pluginState); ! noise.empty() && options.report != nullptr
  1385. && ! options.fileExists (folder + "\\Noise Samples\\" + noise))
  1386. ++options.report->droppedEffects["BassDrum noise sample (not found)"];
  1387. }
  1388. else if (synthFromBassDrum (c.pluginState, fromPlugin, pluginGain))
  1389. adopt();
  1390. }
  1391. else if (name == "toxic biohazard")
  1392. {
  1393. // FL's engine from the raw state (REA_rodada45); its built-in waves 2…32 are spectra read at run time from the
  1394. // user's own Toxic Biohazard_x64.dll (SHA-256 checked). Without it (or for states the engine can't read) the
  1395. // 2-operator conversion stays
  1396. const auto dll = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Toxic Biohazard\\Toxic Biohazard_x64.dll",
  1397. options.roots);
  1398. const auto dllFound = ! dll.empty() && options.fileExists && options.fileExists (dll) && toxicDllUsable (dll);
  1399. if (toxicStateUsable (c.pluginState) && (dllFound || ! toxicNeedsDll (c.pluginState)))
  1400. {
  1401. def.instrument = InstrumentKind::toxic;
  1402. def.pluginState = c.pluginState;
  1403. if (dllFound)
  1404. def.samplePath = dll;
  1405. adoptedFromPlugin = true;
  1406. }
  1407. else if (synthFromToxic (c.pluginState, fromPlugin, pluginGain))
  1408. adopt();
  1409. }
  1410. else if (name == "morphine")
  1411. {
  1412. // FL's Morphine engine from the raw state (REA_rodada39 §2); its noise sample is read at run time from
  1413. // the user's installation (not found: the noise stays silent). The averaged-spectrum conversion stays as
  1414. // the fallback for states the engine can't read
  1415. if (morphineStateUsable (c.pluginState))
  1416. {
  1417. def.instrument = InstrumentKind::morphine;
  1418. def.pluginState = c.pluginState;
  1419. adoptedFromPlugin = true;
  1420. if (const auto noise = morphineNoiseName (c.pluginState); ! noise.empty())
  1421. {
  1422. const auto path = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Morphine\\Noise Samples\\" + noise,
  1423. options.roots);
  1424. if (! path.empty() && options.fileExists && options.fileExists (path))
  1425. def.samplePath = path;
  1426. else if (options.report != nullptr)
  1427. ++options.report->droppedEffects["Morphine noise sample (not found)"];
  1428. }
  1429. }
  1430. else if (synthFromMorphine (c.pluginState, fromPlugin, pluginGain))
  1431. adopt();
  1432. }
  1433. else if (name == "drumpad" && drumpadParams (c.pluginState))
  1434. {
  1435. // the physical drum model (REA_rodada28 §2)
  1436. const auto dp = drumpadParams (c.pluginState);
  1437. def.instrument = InstrumentKind::drumpad;
  1438. def.modelParams.assign (dp->begin(), dp->end());
  1439. adoptedFromPlugin = true;
  1440. }
  1441. else if (name == "drumpad")
  1442. if (const auto patch = drumpadPatchName (c.pluginState))
  1443. {
  1444. // kick/snare/clap/hi-hat: the drum instruments; the rest, a drum on the synth
  1445. if (const auto drum = guessInstrument (*patch, flp::ChannelType::sampler); drum != InstrumentKind::synth)
  1446. {
  1447. def.instrument = drum;
  1448. adoptedFromPlugin = true;
  1449. }
  1450. else
  1451. {
  1452. fromPlugin = drumToneForName (*patch);
  1453. // confirmed: Pitch ×2^(2x − 1) and Mallet Amplitude 10^(−4(1 − x)) (the physical model isn't)
  1454. if (const auto dp = drumpadParams (c.pluginState))
  1455. {
  1456. const auto semis = 12.0f * (2.0f * std::clamp ((*dp)[29], 0.0f, 1.0f) - 1.0f);
  1457. for (auto& o : fromPlugin.osc)
  1458. {
  1459. o.semitones += (int) std::lround (semis);
  1460. o.detune += 100.0f * (semis - (float) std::lround (semis));
  1461. }
  1462. pluginGain = (float) std::pow (10.0, -4.0 * (1.0 - std::clamp ((double) (*dp)[2], 0.0, 1.0)));
  1463. }
  1464. adopt();
  1465. }
  1466. }
  1467. }
  1468. // 3x Osc: oscillators from the plugin state; envelope and filter come from the channel (REA_rodada4)
  1469. if (def.instrument == InstrumentKind::synth && c.pluginName == "3x Osc" && synthFrom3xOsc (c.pluginState, def.synth))
  1470. {
  1471. if (hasVolumeEnvelope)
  1472. {
  1473. def.synth.attack = def.sampler.attack;
  1474. def.synth.decay = def.sampler.decay;
  1475. def.synth.sustain = def.sampler.sustain;
  1476. def.synth.release = def.sampler.release;
  1477. }
  1478. else
  1479. {
  1480. // without an envelope FL plays the note as a gate, with only a short declick
  1481. def.synth.attack = 0.002f;
  1482. def.synth.decay = 0.0f;
  1483. def.synth.sustain = 1.0f;
  1484. def.synth.release = 0.02f;
  1485. }
  1486. synthFilterFromChannel (c.modX, c.modY, c.filterType, def.synth.cutoff, def.synth.resonance, def.synth.filterType);
  1487. def.synth.filterEnv = filterEnv;
  1488. def.synth.pitchEnv = pitchEnv;
  1489. }
  1490. // sample region and start offset
  1491. if (std::isfinite (c.sampleStart) && std::isfinite (c.sampleEnd) && std::isfinite (c.startOffset))
  1492. {
  1493. const auto start = std::clamp (c.sampleStart, 0.0, 1.0), end = std::clamp (c.sampleEnd, 0.0, 1.0);
  1494. if (end > start)
  1495. {
  1496. def.sampler.regionStart = (float) std::clamp (start + std::clamp (c.startOffset, 0.0, 1.0) * (end - start), 0.0, 1.0);
  1497. def.sampler.regionEnd = (float) end;
  1498. }
  1499. }
  1500. // time-stretch: the sample lasts TIME/192 beats × MUL
  1501. if (c.stretchTime > 0.0f)
  1502. {
  1503. def.sampler.stretchBeats = (float) (c.stretchTime / 192.0 * std::pow (2.0, c.stretchMul / 10000.0));
  1504. def.sampler.keepPitch = c.stretchMode != 0; // only FL's "Resample" changes the pitch
  1505. }
  1506. // report: what happened to this channel's generator/sample
  1507. if (options.report != nullptr)
  1508. {
  1509. auto& r = *options.report;
  1510. const auto plugin = lowercase (c.pluginName);
  1511. if (plugin.empty())
  1512. r.missingSamples += ! c.samplePath.empty() && def.samplePath.empty() ? 1 : 0;
  1513. else if (plugin == "3x osc" || ((plugin == "directwave" || plugin == "fl keys") && ! def.zones.empty())
  1514. || ((plugin == "fruity slicer" || plugin == "slicex") && ! def.samplePath.empty())
  1515. || (plugin == "fpc" && ! drumKits.empty() && drumKits.back().first == (int) song.channels.size()))
  1516. ++r.converted[c.pluginName];
  1517. else if (def.instrument == InstrumentKind::sakura || def.instrument == InstrumentKind::drumpad
  1518. || def.instrument == InstrumentKind::boobass || def.instrument == InstrumentKind::drumsynth
  1519. || def.instrument == InstrumentKind::harmless || def.instrument == InstrumentKind::sytrus
  1520. || def.instrument == InstrumentKind::harmor || def.instrument == InstrumentKind::gms
  1521. || def.instrument == InstrumentKind::morphine
  1522. || def.instrument == InstrumentKind::ogun || def.instrument == InstrumentKind::minisynth
  1523. || def.instrument == InstrumentKind::dx10
  1524. || def.instrument == InstrumentKind::kepler || def.instrument == InstrumentKind::poizone
  1525. || def.instrument == InstrumentKind::fruitkick || def.instrument == InstrumentKind::bassdrum || def.instrument == InstrumentKind::toxic
  1526. || def.instrument == InstrumentKind::autogun || def.instrument == InstrumentKind::transistorbass
  1527. || def.instrument == InstrumentKind::simsynth || def.instrument == InstrumentKind::wasp
  1528. || def.instrument == InstrumentKind::plucked || def.instrument == InstrumentKind::beepmap
  1529. || def.instrument == InstrumentKind::sawer || def.instrument == InstrumentKind::flkeys
  1530. || def.instrument == InstrumentKind::granulizer || def.instrument == InstrumentKind::drumaxx
  1531. || def.instrument == InstrumentKind::slayer || def.instrument == InstrumentKind::fruitydance
  1532. || def.instrument == InstrumentKind::directwave)
  1533. ++r.converted[c.pluginName]; // FL's own engine rebuilt from the plugin state
  1534. else if ((plugin == "harmless" && def.instrument != InstrumentKind::harmless) || (plugin == "harmor" && def.instrument != InstrumentKind::harmor && adoptedFromPlugin) || (plugin == "minisynth" && def.instrument != InstrumentKind::minisynth) || plugin == "fruity dx10" || plugin == "dx10" || (plugin == "fruit kick" && def.instrument != InstrumentKind::fruitkick)
  1535. || ((plugin == "sytrus" || plugin == "gms" || plugin == "ogun" || plugin == "autogun" || plugin == "sakura" || plugin == "kepler" || plugin == "boobass" || plugin == "drumpad" || plugin == "poizone" || plugin == "bassdrum"
  1536. || plugin == "toxic biohazard" || plugin == "morphine") && adoptedFromPlugin)
  1537. || (plugin == "wave traveller" && def.instrument == InstrumentKind::sampler)
  1538. || (plugin == "fruity drumsynth live" && def.instrument == InstrumentKind::sampler))
  1539. ++r.approximated[c.pluginName];
  1540. else if (((plugin == "fruity envelope controller" || plugin == "fruity keyboard controller") && def.instrument == InstrumentKind::controller)
  1541. || (plugin == "fruity drumsynth live" && def.instrument == InstrumentKind::drumsynth)
  1542. || (plugin == "harmless" && def.instrument == InstrumentKind::harmless)
  1543. || (plugin == "harmor" && def.instrument == InstrumentKind::harmor))
  1544. ++r.converted[c.pluginName];
  1545. else if (plugin == "fruity wrapper" && def.plugin.foreign.format == ForeignPlugin::Format::none)
  1546. ++r.unsupported["Fruity Wrapper (plugin state not readable)"]; // e.g. a wrapper version newer than 12
  1547. else if (plugin != "fruity wrapper" && plugin != "fruity keyboard controller" && plugin != "midi out"
  1548. && def.instrument == InstrumentKind::synth)
  1549. ++r.unsupported[c.pluginName]; // (Keyboard Controller only sends notes to other channels)
  1550. }
  1551. song.channels.push_back (std::move (def));
  1552. }
  1553. // Mixer: names, mute/solo, routing and levels from the .flp; enough inserts for all
  1554. // routes (minimum 16, like a new project). FL's extra tracks (500/501) are left out.
  1555. int highestTrack = 16;
  1556. for (const auto& c : song.channels)
  1557. highestTrack = std::max (highestTrack, c.mixerTrack);
  1558. for (const auto& insert : project.mixer)
  1559. if (insert.index < maxMixerTracks)
  1560. for (auto target : insert.routes)
  1561. if (target < maxMixerTracks && (insert.index > 0 || target > 0))
  1562. highestTrack = std::max ({ highestTrack, target, insert.index });
  1563. song.mixer = Song::defaultMixer (std::min (highestTrack, maxMixerTracks - 1));
  1564. const auto tracks = (int) song.mixer.size();
  1565. for (const auto& insert : project.mixer)
  1566. {
  1567. if (insert.index < 0 || insert.index >= tracks)
  1568. continue;
  1569. auto& track = song.mixer[(std::size_t) insert.index];
  1570. if (insert.index > 0 && ! insert.name.empty())
  1571. track.name = insert.name;
  1572. if (insert.colour != 0 && insert.colour != 0x485156) // FL's default gray
  1573. track.colour = 0xFF000000u | insert.colour;
  1574. track.muted = (insert.flags & 0x08) == 0;
  1575. track.invertPhase = (insert.flags & 0x01) != 0;
  1576. track.swapChannels = (insert.flags & 0x02) != 0;
  1577. track.solo = insert.index > 0 && (insert.flags & 0x1000) != 0;
  1578. if (insert.index > 0 && insert.hasRoutes)
  1579. {
  1580. track.toMaster = std::find (insert.routes.begin(), insert.routes.end(), 0) != insert.routes.end();
  1581. // The level comes from 0xE1 (below). Without a record a route is 100%, except in FL 11 and older,
  1582. // whose templates route every insert to the send tracks at the end of the mixer (100+) at level 0.
  1583. // FL 12+ plays an unrecorded route to insert 100+ at full level (REA_rodada89 §4.1 [EXEC]: FL's
  1584. // "Advanced" templates feed bus tracks 117…125 that way); the exact version boundary is not confirmed.
  1585. const auto oldSendTracks = project.versionNumber < 12'000'000u;
  1586. for (auto target : insert.routes)
  1587. if (target > 0 && target < tracks && target != insert.index)
  1588. track.sends.push_back ({ target, target >= 100 && oldSendTracks ? 0.0f : 1.0f });
  1589. }
  1590. }
  1591. // native FL effects become the similar internal effects (default parameters: the internal
  1592. // state of FL plugins is not known); the others are left out
  1593. std::map<std::pair<int, int>, std::pair<int, std::string>> effectSlotMap; // (track, FL slot) -> (our effect, FL plugin)
  1594. // inputs of each track (REA_rodada22 §1): [itself, the ones routing to it in ascending order (at
  1595. // any level; level 0 = sidechain only)]; the index k stored in the plugins points into this list
  1596. std::map<int, std::vector<int>> trackInputs;
  1597. for (const auto& insert : project.mixer)
  1598. if (insert.hasRoutes)
  1599. for (const auto target : insert.routes)
  1600. if (target > 0 && target != insert.index)
  1601. trackInputs[target].push_back (insert.index);
  1602. auto sidechainSource = [&] (int track, int k) {
  1603. if (k <= 0)
  1604. return -1;
  1605. auto inputs = trackInputs[track];
  1606. std::sort (inputs.begin(), inputs.end());
  1607. inputs.erase (std::unique (inputs.begin(), inputs.end()), inputs.end());
  1608. inputs.insert (inputs.begin(), track);
  1609. return k < (int) inputs.size() && inputs[(std::size_t) k] < tracks ? inputs[(std::size_t) k] : -1;
  1610. };
  1611. std::map<std::pair<int, int>, decltype (LovePhilterConversion::paramMap)> lovePhilterMaps; // Love Philter automation
  1612. // data files of the user's FL installation that some effects load at run time (Soundgoodizer's presets,
  1613. // REA_rodada40); nothing of them is stored in LYNX itself, only in the imported project
  1614. const FlDataReader flData = [&options] (const std::string& relative) -> std::vector<std::uint8_t> {
  1615. const auto path = resolveFlPath ("%FLStudioFactoryData%\\" + relative, options.roots);
  1616. if (path.empty() || ! options.readFile || (options.fileExists && ! options.fileExists (path)))
  1617. return {};
  1618. return options.readFile (path);
  1619. };
  1620. // exact engines that fell back to their approximation (for the report)
  1621. auto noteFallback = [&options, &project] (const std::string& plugin, EffectSlot& fx) {
  1622. if (fx.kind == EffectKind::grossBeat) // its song-position sync counts in the project's ticks (REA_rodada53)
  1623. grossbeat::setPpq (fx.state, project.header.ppq > 0 ? project.header.ppq : 96);
  1624. if (options.report == nullptr || fx.kind == EffectKind::maximus || fx.kind == EffectKind::grossBeat)
  1625. return;
  1626. if (plugin == "Gross Beat")
  1627. ++options.report->droppedEffects["Gross Beat (state not read: volume gate only)"];
  1628. if (plugin == "Maximus")
  1629. ++options.report->droppedEffects["Maximus (option not decoded: approximated)"];
  1630. else if (plugin == "Soundgoodizer")
  1631. ++options.report->droppedEffects["Soundgoodizer (preset file not found: approximated)"];
  1632. else if ((plugin == "Fruity Limiter" && fx.kind != EffectKind::fruityLimiter)
  1633. || (plugin == "Fruity Compressor" && fx.kind != EffectKind::fruityCompressor)
  1634. || (plugin == "Fruity Delay 2" && fx.kind != EffectKind::fruityDelay2)
  1635. || (plugin == "Fruity Delay 3" && fx.kind != EffectKind::fruityDelay3)
  1636. || (plugin == "Fruity Stereo Shaper" && fx.kind != EffectKind::stereoShaper)
  1637. || (plugin == "Fruity Stereo Enhancer" && fx.kind != EffectKind::stereoEnhancer)
  1638. || (plugin == "Transient Processor" && fx.kind != EffectKind::transientProcessor)
  1639. || (plugin == "Spreader" && fx.kind != EffectKind::spreader)
  1640. || (plugin == "EQUO" && fx.kind != EffectKind::equo)
  1641. || (plugin == "Pitch Shifter" && fx.kind != EffectKind::flPitchShifter)
  1642. || (plugin == "Frequency Splitter" && fx.kind != EffectKind::frequencySplitter)
  1643. || (plugin == "Distructor" && fx.kind != EffectKind::distructor)
  1644. || (plugin == "Multiband Delay" && fx.kind != EffectKind::multibandDelay))
  1645. ++options.report->droppedEffects[plugin + " (state not readable: approximated)"];
  1646. else if ((plugin == "Fruity WaveShaper" && fx.kind != EffectKind::fruityWaveShaper)
  1647. || (plugin == "Fruity Soft Clipper" && fx.kind != EffectKind::fruitySoftClipper)
  1648. || (plugin == "Fruity Delay Bank" && fx.kind != EffectKind::fruityDelayBank)
  1649. || (plugin == "Fruity Multiband Compressor" && fx.kind != EffectKind::fruityMultiband))
  1650. ++options.report->droppedEffects[plugin + " (state not readable: approximated)"];
  1651. else if ((plugin == "Fruity PanOMatic" && fx.kind != EffectKind::fruityPanOMatic)
  1652. || (plugin == "Fruity Balance" && fx.kind != EffectKind::fruityBalance)
  1653. || (plugin == "Fruity Blood Overdrive" && fx.kind != EffectKind::fruityBloodOverdrive))
  1654. ++options.report->droppedEffects[plugin + " (state not readable: approximated)"];
  1655. else if ((plugin == "Fruity Fast LP" && fx.kind != EffectKind::fruityFastLP)
  1656. || (plugin == "Fruity Free Filter" && fx.kind != EffectKind::fruityFreeFilter)
  1657. || (plugin == "Fruity Filter" && fx.kind != EffectKind::fruityFilter))
  1658. ++options.report->droppedEffects[plugin + " (state not readable: approximated)"];
  1659. else if (chorusControls (plugin) > 0 && fx.kind == EffectKind::chorus)
  1660. ++options.report->droppedEffects[plugin + " (state not readable: approximated)"];
  1661. else if ((plugin == "Fruity Fast Dist" && fx.kind != EffectKind::fruityFastDist)
  1662. || (plugin == "Fruity Flangus" && fx.kind != EffectKind::fruityFlangus)
  1663. || (plugin == "Fruity Flanger" && fx.kind != EffectKind::fruityFlanger)
  1664. || (plugin == "Fruity Phaser" && fx.kind != EffectKind::fruityPhaser))
  1665. ++options.report->droppedEffects[plugin + " (state not readable: approximated)"];
  1666. else if (plugin == "Hardcore" && fx.kind == EffectKind::hardcore
  1667. && ! hardcore::hasCabinet (fx, (int) hardcore::fromSlot (hardcore::pCabinet, fx.params[(std::size_t) hardcore::pCabinet])))
  1668. {
  1669. if (hardcore::fromSlot (hardcore::pCabinet, fx.params[(std::size_t) hardcore::pCabinet]) > 0.0f)
  1670. ++options.report->droppedEffects["Hardcore (cabinet impulse not found: cabinet off)"];
  1671. }
  1672. };
  1673. for (const auto& insert : project.mixer)
  1674. {
  1675. if (insert.index < 0 || insert.index >= tracks)
  1676. continue;
  1677. auto& track = song.mixer[(std::size_t) insert.index];
  1678. for (const auto& original : insert.slots)
  1679. {
  1680. // Patcher with a simple serial chain: the plugins inside become consecutive slots
  1681. std::vector<flp::MixerInsert::Slot> expanded { original };
  1682. // Fruity Love Philter: the units become parametric EQ + gain/pan (or a parallel container)
  1683. // (only for states the exact engine cannot read: the others go through effectFromFl, REA_rodada66)
  1684. if (original.plugin == "Fruity Love Philter" && (int) track.effects.size() < maxEffectSlots
  1685. && philter::parse (original.state) == nullptr)
  1686. if (auto conversion = lovePhilterEffects (original.state))
  1687. {
  1688. const auto first = (int) track.effects.size();
  1689. for (auto& fx : conversion->slots)
  1690. if ((int) track.effects.size() < maxEffectSlots)
  1691. track.effects.push_back (std::move (fx));
  1692. effectSlotMap.insert ({ { insert.index, original.index }, { first, original.plugin } });
  1693. if (conversion->paramMap)
  1694. lovePhilterMaps[{ insert.index, original.index }] = conversion->paramMap;
  1695. for (const auto& link : conversion->links) // cutoff envelope/LFO: live automation
  1696. if (first + std::max (link.source, link.target) < (int) track.effects.size())
  1697. {
  1698. Automation a;
  1699. a.name = "Love Philter (" + track.name + ")";
  1700. a.target = { AutomationTargetKind::effectParam, insert.index, first + link.target, link.param };
  1701. a.source = { insert.index, first + link.source, 0 };
  1702. a.curve = link.curve;
  1703. song.automations.push_back (std::move (a));
  1704. }
  1705. if (options.report != nullptr)
  1706. {
  1707. ++options.report->converted["Fruity Love Philter"];
  1708. for (const auto& note : conversion->notes)
  1709. ++options.report->droppedEffects[note];
  1710. }
  1711. continue;
  1712. }
  1713. // Patcher with branches (REA_rodada20 §3.3): the audio graph reduced to series/parallel becomes slots and
  1714. // nested parallel containers; splitter nodes enter via the band/bus used
  1715. if (lowercase (original.plugin) == "patcher" && (int) track.effects.size() < maxEffectSlots)
  1716. if (const auto graph = parsePatcher (original.state); graph && graph->serialChain.empty() && graph->audio)
  1717. {
  1718. std::function<std::vector<EffectSlot> (const PatcherExpr&, float&)> build = [&] (const PatcherExpr& e, float& gain) {
  1719. std::vector<EffectSlot> chain;
  1720. gain *= e.gain;
  1721. switch (e.kind)
  1722. {
  1723. case PatcherExpr::Kind::identity: break;
  1724. case PatcherExpr::Kind::node:
  1725. {
  1726. const auto& node = graph->nodes[(std::size_t) e.node];
  1727. if (e.bus >= 0)
  1728. {
  1729. const auto head = patcherBranchHead (node.plugin, node.state, e.bus);
  1730. if (! head.valid)
  1731. {
  1732. if (options.report != nullptr)
  1733. ++options.report->droppedEffects["Patcher: bus " + std::to_string (e.bus) + " of " + node.plugin];
  1734. break;
  1735. }
  1736. gain *= head.gain;
  1737. if (head.slot)
  1738. chain.push_back (*head.slot);
  1739. if (! head.note.empty() && options.report != nullptr)
  1740. ++options.report->droppedEffects[head.note];
  1741. }
  1742. else if (auto fx = effectFromFl (node.plugin, node.state, song.bpm, flData); fx && fx->kind != EffectKind::plugin)
  1743. {
  1744. noteFallback (node.plugin, *fx);
  1745. chain.push_back (std::move (*fx));
  1746. }
  1747. else if (options.report != nullptr)
  1748. ++options.report->droppedEffects[node.plugin + " (in Patcher)"];
  1749. break;
  1750. }
  1751. case PatcherExpr::Kind::series:
  1752. for (const auto& c : e.children)
  1753. for (auto& slot : build (c, gain))
  1754. chain.push_back (std::move (slot));
  1755. break;
  1756. case PatcherExpr::Kind::parallel:
  1757. {
  1758. auto container = makeEffectSlot (EffectKind::parallel);
  1759. for (const auto& c : e.children)
  1760. {
  1761. EffectBranch branch;
  1762. auto branchGain = 1.0f;
  1763. branch.chain = build (c, branchGain);
  1764. branch.gain = std::clamp (branchGain, 0.0f, 4.0f);
  1765. container.branches.push_back (std::move (branch));
  1766. }
  1767. chain.push_back (std::move (container));
  1768. break;
  1769. }
  1770. }
  1771. return chain;
  1772. };
  1773. auto gain = 1.0f;
  1774. auto chain = build (*graph->audio, gain);
  1775. if (std::abs (gain - 1.0f) > 1e-4f)
  1776. {
  1777. auto utility = makeEffectSlot (EffectKind::utility);
  1778. utility.params[0] = gain <= 0.0f ? 0.0f : std::clamp ((float) (20.0 * std::log10 (gain) / 48.0 + 0.5), 0.0f, 1.0f);
  1779. chain.push_back (std::move (utility));
  1780. }
  1781. if ((int) (track.effects.size() + chain.size()) > maxEffectSlots) // doesn't fit: a single-branch container
  1782. {
  1783. auto container = makeEffectSlot (EffectKind::parallel);
  1784. container.branches.push_back ({ std::move (chain), 1.0f });
  1785. chain = { std::move (container) };
  1786. }
  1787. effectSlotMap.insert ({ { insert.index, original.index }, { (int) track.effects.size(), original.plugin } });
  1788. for (auto& slot : chain)
  1789. track.effects.push_back (std::move (slot));
  1790. if (options.report != nullptr)
  1791. ++options.report->converted["Patcher (series/parallel)"];
  1792. continue;
  1793. }
  1794. if (lowercase (original.plugin) == "patcher")
  1795. if (const auto graph = parsePatcher (original.state); graph && ! graph->serialChain.empty())
  1796. {
  1797. expanded.clear();
  1798. for (const auto n : graph->serialChain)
  1799. expanded.push_back ({ original.index, graph->nodes[(std::size_t) n].plugin, graph->nodes[(std::size_t) n].state });
  1800. if (options.report != nullptr)
  1801. ++options.report->converted["Patcher (in series)"];
  1802. }
  1803. for (const auto& slot : expanded)
  1804. {
  1805. if ((int) track.effects.size() >= maxEffectSlots)
  1806. continue;
  1807. ForeignPlugin foreign;
  1808. std::optional<EffectSlot> made;
  1809. const auto wrapped = slot.plugin == "Fruity Wrapper" && parseFlWrapper (slot.state, foreign);
  1810. // old FL saved its own Fruity effects as VST2 inside the wrapper: becomes the internal effect
  1811. if (wrapped && foreign.format == ForeignPlugin::Format::vst2 && effectForFlPlugin (foreign.name))
  1812. made = effectFromFl (foreign.name, wrappedFruityState (foreign), song.bpm);
  1813. else if (wrapped)
  1814. {
  1815. // the app swaps in the installed plugin; without it, the slot is removed
  1816. made = makeEffectSlot (EffectKind::plugin);
  1817. made->plugin.name = foreign.name;
  1818. made->plugin.foreign = std::move (foreign);
  1819. }
  1820. else
  1821. {
  1822. made = effectFromFl (slot.plugin, slot.state, song.bpm, flData); // native effect with the saved settings (REA_rodada7)
  1823. if (made)
  1824. noteFallback (slot.plugin, *made);
  1825. }
  1826. if (! made)
  1827. {
  1828. // the ones that don't touch audio (controllers, visualizers, notes) aren't missed
  1829. static const char* silent[] = { "Fruity Peak Controller", "Fruity X-Y Controller", "Control Surface", "Wave Candy",
  1830. "ZGameEditor Visualizer", "Fruity NoteBook 2", "Fruity NoteBook", "Edison",
  1831. "Fruity Formula Controller", "Fruity LSD", "Fruity dB Meter", "Fruity Spectroman" };
  1832. const auto harmless = std::any_of (std::begin (silent), std::end (silent), [&] (const char* n) { return slot.plugin == n; });
  1833. if (options.report != nullptr && ! harmless)
  1834. ++options.report->droppedEffects[slot.plugin == "Fruity Wrapper" ? std::string ("Fruity Wrapper (plugin state not readable)")
  1835. : slot.plugin];
  1836. continue;
  1837. }
  1838. auto fx = std::move (*made);
  1839. // sidechain (REA_rodada22 §1): Fruity Limiter (i32 at 0xA4, v ≥ 6; only the compressor detector and only
  1840. // with Comp threshold < 0 dB) and Fruity Compressor (i32 at 0x20, v3)
  1841. if (slot.plugin == "Fruity Limiter" && slot.state.size() >= 0xA8)
  1842. {
  1843. std::int32_t version = 0, k = 0, compThreshold = 1000;
  1844. std::memcpy (&version, slot.state.data(), 4);
  1845. std::memcpy (&k, slot.state.data() + 0xA4, 4);
  1846. std::memcpy (&compThreshold, slot.state.data() + 4 + 8 * 4, 4);
  1847. const auto source = version >= 6 ? sidechainSource (insert.index, k) : -1;
  1848. if (fx.kind == EffectKind::fruityLimiter)
  1849. {
  1850. // the exact engine: the side input feeds its compression detector (REA_rodada48)
  1851. fx.sidechain = source;
  1852. if (source >= 0 && compThreshold < 1000 && options.report != nullptr)
  1853. ++options.report->converted["Fruity Limiter (sidechain)"];
  1854. }
  1855. else if (source >= 0 && compThreshold < 1000)
  1856. if (auto comp = fruityLimiterCompressor (slot.state))
  1857. {
  1858. const auto enabled = fx.enabled;
  1859. fx = std::move (*comp);
  1860. fx.enabled = enabled;
  1861. fx.sidechain = source;
  1862. if (options.report != nullptr)
  1863. ++options.report->converted["Fruity Limiter (sidechain)"];
  1864. }
  1865. }
  1866. else if (slot.plugin == "LuxeVerb" && fx.kind == EffectKind::luxeVerb && slot.state.size() >= 8)
  1867. {
  1868. // the state's second i32 is the sidechain input the envelope can follow (REA_rodada60 §3.1)
  1869. std::int32_t k = 0;
  1870. std::memcpy (&k, slot.state.data() + 4, 4);
  1871. if (k > 0)
  1872. fx.sidechain = sidechainSource (insert.index, k);
  1873. }
  1874. else if (slot.plugin == "Vocodex")
  1875. {
  1876. // ModIn/CarIn index the same inputs list as the sidechains (REA_rodada22 §1)
  1877. if (const auto v = vocodexEffect (slot.state, flData))
  1878. {
  1879. fx.sidechain = sidechainSource (insert.index, v->modIn);
  1880. fx.sidechain2 = sidechainSource (insert.index, v->carIn);
  1881. if (options.report != nullptr)
  1882. for (const auto& note : v->notes)
  1883. ++options.report->droppedEffects[note];
  1884. }
  1885. }
  1886. else if (fx.kind == EffectKind::newtone || fx.kind == EffectKind::newtime)
  1887. {
  1888. // the source sample: the path the host stored (record 3), else the engine's working copy (REA_rodada73 §2.3)
  1889. if (const auto parsed = newtonefx::parse (slot.state))
  1890. {
  1891. std::vector<std::string> candidates;
  1892. if (! parsed->sourcePath.empty())
  1893. candidates.push_back (resolveFlPath (parsed->sourcePath, options.roots));
  1894. for (const auto& t : parsed->tracks)
  1895. candidates.push_back (t.filePath);
  1896. for (const auto& path : candidates)
  1897. if (! path.empty() && options.fileExists && options.fileExists (path))
  1898. {
  1899. fx.samplePath = path;
  1900. break;
  1901. }
  1902. for (const auto& path : candidates) // located by the user (the "Missing files" window)
  1903. if (const auto chosen = relocatedPath (options.relocations, path);
  1904. fx.samplePath.empty() && ! chosen.empty() && options.fileExists && options.fileExists (chosen))
  1905. fx.samplePath = chosen;
  1906. if (options.report != nullptr && ! parsed->tracks.empty())
  1907. {
  1908. if (fx.samplePath.empty())
  1909. {
  1910. ++options.report->missingSamples;
  1911. if (! candidates.empty() && ! candidates.front().empty())
  1912. addMissingFile (options.report->missingFiles, candidates.front(),
  1913. (insert.name.empty() ? "Insert " + std::to_string (insert.index) : insert.name) + ": " + slot.plugin);
  1914. }
  1915. // Newtone's note edits are rendered by LYNX's engine (REA_rodada95, close, not exact); Newtime's
  1916. // warping is not reproduced. Only slave mode plays them (otherwise FL passes the input through).
  1917. if (parsed->edited() && parsed->slave() && fx.kind == EffectKind::newtime)
  1918. ++options.report->droppedEffects[slot.plugin + " (edits not reproduced: plays the original sample)"];
  1919. else if (fx.kind == EffectKind::newtime)
  1920. ++options.report->droppedEffects["Newtime (time warping engine not reproduced: plays the original sample)"];
  1921. else
  1922. ++options.report->converted[slot.plugin];
  1923. }
  1924. }
  1925. }
  1926. else if (slot.plugin == "Fruity Compressor" && slot.state.size() >= 0x24
  1927. && (fx.kind == EffectKind::compressor || fx.kind == EffectKind::fruityCompressor))
  1928. {
  1929. std::int32_t version = 0, k = 0;
  1930. std::memcpy (&version, slot.state.data(), 4);
  1931. std::memcpy (&k, slot.state.data() + 0x20, 4);
  1932. if (version == 3)
  1933. fx.sidechain = sidechainSource (insert.index, k);
  1934. }
  1935. // slot bypass and dry/wet (0xE1, p = 0x1F00 / 0x1F01)
  1936. for (const auto& control : project.controls)
  1937. if (control.id.isMixer() && control.id.track() == insert.index && control.id.slot() == slot.index)
  1938. {
  1939. if (control.id.param() == 0x1F00)
  1940. fx.enabled = control.value != 0;
  1941. else if (control.id.param() == 0x1F01)
  1942. fx.mix = std::clamp (control.value / 12800.0f, 0.0f, 1.0f);
  1943. }
  1944. effectSlotMap.insert ({ { insert.index, slot.index }, { (int) track.effects.size(), slot.plugin } });
  1945. track.effects.push_back (fx);
  1946. }
  1947. }
  1948. }
  1949. // cycles shouldn't exist in the file; if they do, the send that closes the cycle is dropped
  1950. for (int t = 1; t < tracks; ++t)
  1951. {
  1952. auto sends = std::move (song.mixer[(std::size_t) t].sends);
  1953. song.mixer[(std::size_t) t].sends.clear();
  1954. for (const auto& s : sends)
  1955. song.setRoute (t, s.target, true, s.level);
  1956. }
  1957. for (const auto& control : project.controls)
  1958. {
  1959. if (! control.id.isMixer())
  1960. continue;
  1961. const auto t = control.id.track();
  1962. const auto p = control.id.param();
  1963. if (t < 0 || t >= tracks)
  1964. continue;
  1965. auto& track = song.mixer[(std::size_t) t];
  1966. // FL ranges: volume 0..16000 (12800 = 0 dB), pan ±6400, route levels 0..16000 on the fader curve too
  1967. // (12800 = 0 dB, 16000 = +5.6 dB; destination 0 = the route to Master). REA_rodada107 §3: FL renders with
  1968. // a route level of 16000 / 12800 / 6400 differ by +5.6 / 0 / −12.7 dB, the fader curve's values.
  1969. if (p == flp::ControlId::mixerVolume)
  1970. track.volume = std::clamp (control.value / 16000.0f, 0.0f, 1.0f);
  1971. else if (p == flp::ControlId::mixerPan)
  1972. track.pan = std::clamp (control.value / 6400.0f, -1.0f, 1.0f);
  1973. else if (p == flp::ControlId::mixerStereo)
  1974. track.stereo = std::clamp (control.value / 64.0f, -1.0f, 1.0f);
  1975. else if (p >= flp::ControlId::mixerEqBase && p < flp::ControlId::mixerEqBase + 24 && (p - flp::ControlId::mixerEqBase) % 8 < 3)
  1976. {
  1977. // track EQ: p = 0x1FD0 + group·8 + band (group 0 gain, 1 frequency, 2 width; REA_rodada6 §1)
  1978. const auto group = (p - flp::ControlId::mixerEqBase) / 8;
  1979. const auto band = (std::size_t) ((p - flp::ControlId::mixerEqBase) % 8);
  1980. const auto v = (double) control.value;
  1981. if (group == 0)
  1982. track.eq.gainDb[band] = (float) std::clamp (v * 0.01, -18.0, 18.0);
  1983. else if (group == 1)
  1984. track.eq.hz[band] = (float) std::clamp (10.0 + 159.9 * (std::pow (101.0, v / 65536.0) - 1.0), 10.0, 16000.0);
  1985. else
  1986. track.eq.width[band] = (float) std::clamp (v / 65536.0, 0.0, 1.0);
  1987. }
  1988. else if (p == flp::ControlId::mixerSendBase)
  1989. track.masterLevel = faderGain (control.value / 16000.0f);
  1990. else if (p > flp::ControlId::mixerSendBase && p < flp::ControlId::mixerSendBase + tracks)
  1991. for (auto& send : track.sends)
  1992. if (send.target == p - flp::ControlId::mixerSendBase)
  1993. send.level = faderGain (control.value / 16000.0f);
  1994. }
  1995. // the FL template routes every insert to the send tracks at level 0; that makes no sound, only wastes CPU
  1996. for (auto& t : song.mixer)
  1997. t.sends.erase (std::remove_if (t.sends.begin(), t.sends.end(), [] (const MixerSend& s) { return s.level <= 0.0f; }),
  1998. t.sends.end());
  1999. const auto filePpq = project.header.ppq > 0 ? (std::int64_t) project.header.ppq : 96;
  2000. auto rescale = [filePpq] (std::int64_t ticks) { return ticks * ppq / filePpq; };
  2001. std::map<int, int> patternMap; // FL index -> our dense index
  2002. for (const auto& src : project.patterns)
  2003. {
  2004. Pattern p;
  2005. p.name = src.name.empty() ? "Pattern " + std::to_string (src.index) : src.name;
  2006. if (src.colour && *src.colour != 0x485156) // FL's default gray becomes an automatic colour
  2007. p.colour = 0xFF000000u | *src.colour;
  2008. for (const auto& n : src.notes)
  2009. {
  2010. const auto it = channelMap.find (n.channel);
  2011. if (it == channelMap.end())
  2012. continue;
  2013. Note note;
  2014. note.start = rescale (n.position);
  2015. // Step notes (length 0) play for one step.
  2016. note.length = n.length > 0 ? rescale (n.length) : ticksPerStep;
  2017. note.channel = it->second;
  2018. note.key = n.key; // FL and MIDI use the same numbering; only the octave name differs
  2019. note.velocity = std::clamp (n.velocity / 128.0f, 0.0f, 1.0f);
  2020. note.pan = std::clamp ((n.pan - 64) / 64.0f, -1.0f, 1.0f);
  2021. note.finePitch = (float) std::clamp ((int) n.finePitch - 120, -120, 120);
  2022. note.muted = n.muted();
  2023. note.slide = n.slide();
  2024. note.porta = n.porta();
  2025. p.notes.push_back (note);
  2026. }
  2027. p.sortNotes();
  2028. if (! p.notes.empty() || ! src.controlEvents.empty()) // a pattern of events only still plays them
  2029. {
  2030. patternMap[src.index] = (int) song.patterns.size();
  2031. song.patterns.push_back (std::move (p));
  2032. }
  2033. }
  2034. // Our target for an FL controlID: the FL slot (0..9, with gaps) becomes our effect's
  2035. // index (effect not imported = no target); internal effect parameter only with the FL-to-ours
  2036. // map (`valueMap` receives the value conversion).
  2037. auto resolveTarget = [&] (flp::ControlId id, std::function<float (float)>& valueMap) {
  2038. auto target = automationTargetFor (id, channelMap, (int) song.mixer.size());
  2039. if (target.kind == AutomationTargetKind::effectParam || target.kind == AutomationTargetKind::effectMix)
  2040. {
  2041. const auto found = effectSlotMap.find ({ target.index, target.slot });
  2042. if (found == effectSlotMap.end())
  2043. target.kind = AutomationTargetKind::none;
  2044. else
  2045. {
  2046. target.slot = found->second.first;
  2047. const auto& fx = song.mixer[(std::size_t) target.index].effects[(std::size_t) target.slot];
  2048. if (target.kind == AutomationTargetKind::effectParam && found->second.second == "Fruity Love Philter"
  2049. && fx.kind != EffectKind::lovePhilter)
  2050. {
  2051. const auto map = lovePhilterMaps.find ({ id.track(), id.slot() });
  2052. const auto mapped = map != lovePhilterMaps.end() && map->second ? map->second (target.param) : std::nullopt;
  2053. if (mapped)
  2054. {
  2055. target.slot = found->second.first + std::get<0> (*mapped);
  2056. target.param = std::get<1> (*mapped);
  2057. valueMap = std::get<2> (*mapped);
  2058. }
  2059. else
  2060. target.kind = AutomationTargetKind::none;
  2061. }
  2062. else if (target.kind == AutomationTargetKind::effectParam && fx.kind == EffectKind::lovePhilter)
  2063. {
  2064. // the exact Love Philter exposes 48 of FL's controls as (raw − min) / range (core/LovePhilter.h)
  2065. target.param = philter::paramOfFlIndex (target.param);
  2066. if (target.param < 0)
  2067. target.kind = AutomationTargetKind::none;
  2068. }
  2069. else if (target.kind == AutomationTargetKind::effectParam && fx.kind == EffectKind::luxeVerb)
  2070. {
  2071. // the exact LuxeVerb keeps FL's 49 controls as (raw − min) / range: FL's normalised value as is
  2072. if (target.param < 0 || target.param >= luxeVerbControlCount)
  2073. target.kind = AutomationTargetKind::none;
  2074. }
  2075. else if (target.kind == AutomationTargetKind::effectParam && fx.kind == EffectKind::convolver)
  2076. {
  2077. // the exact Convolver keeps FL's 4 automatable controls as (raw − min) / range
  2078. if (target.param < 0 || target.param >= convolverParamCount)
  2079. target.kind = AutomationTargetKind::none;
  2080. }
  2081. else if (target.kind == AutomationTargetKind::effectParam && (fx.kind == EffectKind::reeverb2 || fx.kind == EffectKind::reeverb1))
  2082. {
  2083. // the exact Reeverbs keep FL's controls as (raw − min) / range: FL's normalised value as is
  2084. if (target.param < 0 || target.param >= (fx.kind == EffectKind::reeverb2 ? 15 : reeverb1ParamCount))
  2085. target.kind = AutomationTargetKind::none;
  2086. }
  2087. else if (target.kind == AutomationTargetKind::effectParam && fx.kind != EffectKind::plugin)
  2088. {
  2089. if (const auto mapped = effectParamFromFl (found->second.second, target.param))
  2090. {
  2091. target.param = mapped->param;
  2092. valueMap = mapped->convert;
  2093. }
  2094. else
  2095. target.kind = AutomationTargetKind::none;
  2096. }
  2097. }
  2098. }
  2099. return target;
  2100. };
  2101. // Pattern events (.flp 0xDF, REA_rodada85): per pattern and target, FL's raw values held from their tick on.
  2102. // They become the pattern's event lanes (round 83) in FL's normalised scale, then our target's (valueMap).
  2103. {
  2104. auto pluginOf = [&] (flp::ControlId id) -> std::string {
  2105. if (id.isChannel())
  2106. {
  2107. for (const auto& c : project.channels)
  2108. if (c.index == id.channel())
  2109. return c.pluginName;
  2110. }
  2111. else if (id.isMixer())
  2112. {
  2113. const auto found = effectSlotMap.find ({ id.track(), id.slot() });
  2114. if (found != effectSlotMap.end())
  2115. return found->second.second;
  2116. }
  2117. return {};
  2118. };
  2119. auto note = [&] (const std::string& what) {
  2120. if (options.report != nullptr)
  2121. ++options.report->unsupported["Pattern events: " + what];
  2122. };
  2123. // FL value → our 0..1 for a target (nothing when the target or its scale is not reproduced)
  2124. auto convertor = [&] (flp::ControlId id, AutomationTarget& target) -> std::function<float (std::int32_t)> {
  2125. std::function<float (float)> valueMap;
  2126. target = resolveTarget (id, valueMap);
  2127. const auto plugin = pluginOf (id);
  2128. if (target.kind == AutomationTargetKind::none || target.kind == AutomationTargetKind::tempo)
  2129. {
  2130. note ("target not reproduced" + (plugin.empty() ? std::string() : " (" + plugin + ")"));
  2131. return {};
  2132. }
  2133. const auto range = flRawRange (id, plugin);
  2134. if (! range || range->second <= range->first)
  2135. {
  2136. note ("value scale not known (" + (plugin.empty() ? std::string ("FL parameter") : plugin) + ")");
  2137. return {};
  2138. }
  2139. const auto lo = (double) range->first, span = (double) (range->second - range->first);
  2140. return [lo, span, valueMap] (std::int32_t raw) {
  2141. auto v = (float) std::clamp (((double) raw - lo) / span, 0.0, 1.0);
  2142. return valueMap ? std::clamp (valueMap (v), 0.0f, 1.0f) : v;
  2143. };
  2144. };
  2145. for (const auto& src : project.patterns)
  2146. {
  2147. const auto pm = patternMap.find (src.index);
  2148. if (src.controlEvents.empty() || pm == patternMap.end())
  2149. continue;
  2150. auto& pattern = song.patterns[(std::size_t) pm->second];
  2151. std::vector<std::uint32_t> ids; // targets in order of first appearance
  2152. for (const auto& e : src.controlEvents)
  2153. if (std::find (ids.begin(), ids.end(), e.id.raw) == ids.end())
  2154. ids.push_back (e.id.raw);
  2155. for (const auto raw : ids)
  2156. {
  2157. PatternEvents lane;
  2158. const auto convert = convertor (flp::ControlId { raw }, lane.target);
  2159. if (! convert)
  2160. continue;
  2161. for (const auto& e : src.controlEvents)
  2162. if (e.id.raw == raw)
  2163. lane.events.push_back ({ rescale ((std::int64_t) e.tick), convert (e.value) });
  2164. // one event per tick: the last one of a tick wins (FL applies them in order)
  2165. std::stable_sort (lane.events.begin(), lane.events.end(),
  2166. [] (const PatternEvent& a, const PatternEvent& b) { return a.tick < b.tick; });
  2167. std::vector<PatternEvent> kept;
  2168. for (const auto& e : lane.events)
  2169. if (! kept.empty() && kept.back().tick == e.tick)
  2170. kept.back() = e;
  2171. else
  2172. kept.push_back (e);
  2173. lane.events = std::move (kept);
  2174. // a target already driven by a lane of this pattern: the later lane wins, like FL's single target
  2175. pattern.events.erase (std::remove_if (pattern.events.begin(), pattern.events.end(),
  2176. [&] (const PatternEvents& l) { return l.target == lane.target; }),
  2177. pattern.events.end());
  2178. pattern.events.push_back (std::move (lane));
  2179. if (options.report != nullptr)
  2180. ++options.report->converted["Pattern events"];
  2181. }
  2182. }
  2183. // 0xD8: values FL resets when the song starts — the targets' own values before any pattern event
  2184. for (const auto& c : project.initControls)
  2185. {
  2186. AutomationTarget target;
  2187. if (const auto convert = convertor (c.id, target))
  2188. song.setTargetValue (target, convert (c.value));
  2189. }
  2190. }
  2191. // Automation clips: one Automation per FL automation channel, with the target from the 0xE3 link.
  2192. std::map<int, int> automationMap; // FL channel -> index into song.automations
  2193. for (const auto& c : project.channels)
  2194. {
  2195. if (c.type != flp::ChannelType::automationClip || c.automation.empty())
  2196. continue;
  2197. Automation a;
  2198. a.name = c.name.empty() ? "Automation " + std::to_string (c.index + 1) : c.name;
  2199. std::function<float (float)> valueMap; // FL normalized value -> ours (effect parameters)
  2200. for (const auto& link : project.automationLinks)
  2201. if (link.channel == c.index)
  2202. {
  2203. a.target = resolveTarget (link.target, valueMap);
  2204. break;
  2205. }
  2206. for (std::size_t i = 0; i < c.automation.size(); ++i)
  2207. {
  2208. const auto& p = c.automation[i];
  2209. const auto tick = (std::int64_t) std::llround (p.position * ppq);
  2210. auto value = (float) std::clamp (p.value, 0.0, 1.0);
  2211. // FL automates tempo from 60 to 180 BPM; our target covers the full tempo range
  2212. if (a.target.kind == AutomationTargetKind::tempo)
  2213. value = valueFromTempo (60.0 + 120.0 * value);
  2214. else if (valueMap)
  2215. value = std::clamp (valueMap (value), 0.0f, 1.0f);
  2216. // FL's curve belongs to the segment ending at the point; ours sits on the left point
  2217. if (i > 0)
  2218. {
  2219. auto& previous = a.points.back();
  2220. if (p.curve == 0 || p.curve == 1) // single/double curve: exponential by tension
  2221. previous.tension = std::clamp (-p.tension, -1.0f, 1.0f);
  2222. else if (p.curve == 2 && tick - previous.tick > 1) // hold: step right before the point
  2223. a.points.push_back ({ tick - 1, previous.value, 0.0f });
  2224. }
  2225. a.points.push_back ({ tick, value, 0.0f });
  2226. }
  2227. automationMap[c.index] = (int) song.automations.size();
  2228. song.automations.push_back (std::move (a));
  2229. }
  2230. // Controller links (REA_rodada14 §7): Peak Controller in a mixer slot -> live automation of the
  2231. // target (the effect output is read every block). Other controllers are still left out.
  2232. for (const auto& link : project.controllerLinks)
  2233. {
  2234. // Envelope Controller on a channel: output k follows articulator k
  2235. if (link.source.isChannel())
  2236. {
  2237. const auto channel = channelMap.find (link.source.channel());
  2238. if (channel == channelMap.end() || song.channels[(std::size_t) channel->second].instrument != InstrumentKind::controller)
  2239. continue;
  2240. Automation a;
  2241. std::function<float (float)> valueMap;
  2242. a.target = resolveTarget (link.target, valueMap);
  2243. if (a.target.kind == AutomationTargetKind::none || a.target.kind == AutomationTargetKind::tempo)
  2244. continue;
  2245. a.name = "Controller (" + song.channels[(std::size_t) channel->second].name + ")";
  2246. a.source.channel = channel->second;
  2247. a.source.output = link.source.param() - flp::ControlId::pluginParamBase;
  2248. if (valueMap)
  2249. for (int i = 0; i <= 32; ++i)
  2250. a.curve.push_back (std::clamp (valueMap ((float) i / 32.0f), 0.0f, 1.0f));
  2251. song.automations.push_back (std::move (a));
  2252. if (options.report != nullptr)
  2253. ++options.report->converted["Channel controller (link)"];
  2254. continue;
  2255. }
  2256. if (! link.source.isMixer() || link.source.track() < 0 || link.source.track() >= (int) song.mixer.size())
  2257. continue;
  2258. // static X-Y Controller / Control Surface: the current value is applied to the target once
  2259. {
  2260. const flp::MixerInsert::Slot* source = nullptr;
  2261. for (const auto& insert : project.mixer)
  2262. if (insert.index == link.source.track())
  2263. for (const auto& slot : insert.slots)
  2264. if (slot.index == link.source.slot())
  2265. source = &slot;
  2266. if (source != nullptr)
  2267. if (const auto value = controllerConstantOutput (source->plugin, source->state, link.source.param() - flp::ControlId::pluginParamBase))
  2268. {
  2269. std::function<float (float)> valueMap;
  2270. const auto target = resolveTarget (link.target, valueMap);
  2271. if (target.kind != AutomationTargetKind::none && target.kind != AutomationTargetKind::tempo
  2272. && song.setTargetValue (target, valueMap ? valueMap (*value) : *value) && options.report != nullptr)
  2273. ++options.report->converted[source->plugin + " (link)"];
  2274. continue;
  2275. }
  2276. }
  2277. const auto found = effectSlotMap.find ({ link.source.track(), link.source.slot() });
  2278. if (found == effectSlotMap.end()
  2279. || song.mixer[(std::size_t) link.source.track()].effects[(std::size_t) found->second.first].kind != EffectKind::peakController)
  2280. continue;
  2281. Automation a;
  2282. std::function<float (float)> valueMap;
  2283. a.target = resolveTarget (link.target, valueMap);
  2284. if (a.target.kind == AutomationTargetKind::none || a.target.kind == AutomationTargetKind::tempo)
  2285. continue;
  2286. a.name = "Peak Controller (" + song.mixer[(std::size_t) link.source.track()].name + ")";
  2287. a.source = { link.source.track(), found->second.first, link.source.param() - flp::ControlId::pluginParamBase };
  2288. if (valueMap)
  2289. for (int i = 0; i <= 32; ++i)
  2290. a.curve.push_back (std::clamp (valueMap ((float) i / 32.0f), 0.0f, 1.0f));
  2291. song.automations.push_back (std::move (a));
  2292. if (options.report != nullptr)
  2293. ++options.report->converted["Peak Controller (link)"];
  2294. }
  2295. // Playlist: all arrangements (the first stays open); pattern, audio and automation clips.
  2296. std::vector<const std::vector<flp::PlaylistTrackInfo>*> importedTracks;
  2297. if (! project.arrangements.empty())
  2298. song.arrangements.clear();
  2299. for (const auto& arrangement : project.arrangements)
  2300. {
  2301. std::vector<Clip> clips;
  2302. for (const auto& item : arrangement.items)
  2303. {
  2304. if (item.length == 0)
  2305. continue;
  2306. if (item.kind == flp::PlaylistItem::Kind::channelClip && automationMap.count (item.index))
  2307. {
  2308. Clip clip;
  2309. clip.kind = ClipKind::automation;
  2310. clip.automation = automationMap[item.index];
  2311. clip.track = item.track;
  2312. clip.start = rescale (item.position);
  2313. clip.length = rescale (item.length);
  2314. // trim in beats (-1 = no trim)
  2315. if (std::isfinite (item.startOffset) && item.startOffset > 0.0f)
  2316. clip.offset = (std::int64_t) std::llround (item.startOffset * ppq);
  2317. clips.push_back (clip);
  2318. continue;
  2319. }
  2320. if (item.kind == flp::PlaylistItem::Kind::channelClip)
  2321. {
  2322. const auto channel = channelMap.find (item.index);
  2323. if (channel == channelMap.end() || song.channels[(std::size_t) channel->second].instrument != InstrumentKind::audioClip)
  2324. continue;
  2325. Clip clip;
  2326. clip.kind = ClipKind::audio;
  2327. clip.channel = channel->second;
  2328. clip.track = item.track;
  2329. clip.start = rescale (item.position);
  2330. clip.length = rescale (item.length);
  2331. // The region start comes in beats or in milliseconds, depending on the clip;
  2332. // we find out by the unit in which (end - start) matches the length.
  2333. const auto beats = (double) item.length / (double) filePpq;
  2334. const auto span = (double) item.endOffset - (double) item.startOffset;
  2335. if (std::isfinite (item.startOffset) && item.startOffset > 0.0f)
  2336. {
  2337. if (std::abs (span - beats) < 0.02 * std::max (1.0, beats))
  2338. clip.offset = (std::int64_t) std::llround (item.startOffset * ppq);
  2339. else if (std::abs (span - beats * 60000.0 / song.bpm) < 0.02 * std::max (1.0, span))
  2340. clip.offset = (std::int64_t) std::llround (item.startOffset / 1000.0 * song.bpm / 60.0 * ppq);
  2341. else if (const auto& ch = song.channels[(std::size_t) channel->second]; ch.sampler.stretchBeats > 0.0f && span > 0.0 && beats > 0.0)
  2342. {
  2343. // time-stretched clip: start/end are in the SAMPLE's milliseconds, so the span is the clip
  2344. // length times the stretch factor (e.g. 31 219 ms over 64 beats = 29 538 ms at 130 BPM)
  2345. const auto factor = span / (beats * 60000.0 / song.bpm);
  2346. if (factor > 0.25 && factor < 4.0)
  2347. clip.offset = (std::int64_t) std::llround (item.startOffset / factor / 1000.0 * song.bpm / 60.0 * ppq);
  2348. }
  2349. }
  2350. // clip gain and fades (FL 20.99+ records); fades are in ms, at most the clip length
  2351. clip.gain = item.gain;
  2352. const auto msToTicks = [&] (float ms)
  2353. { return std::clamp ((std::int64_t) std::llround (ms / 1000.0 * song.bpm / 60.0 * ppq), (std::int64_t) 0, clip.length); };
  2354. clip.fadeIn = msToTicks (item.fadeInMs);
  2355. clip.fadeOut = msToTicks (item.fadeOutMs);
  2356. clips.push_back (clip);
  2357. continue;
  2358. }
  2359. const auto it = patternMap.find (item.index);
  2360. if (it == patternMap.end())
  2361. continue;
  2362. Clip clip;
  2363. clip.pattern = it->second;
  2364. clip.track = item.track;
  2365. clip.start = rescale (item.position);
  2366. clip.length = rescale (item.length);
  2367. clip.offset = item.patternStartTick > 0 ? rescale (item.patternStartTick) : 0;
  2368. clips.push_back (clip);
  2369. }
  2370. std::sort (clips.begin(), clips.end(), [] (const Clip& a, const Clip& b) { return a.start < b.start; });
  2371. Arrangement a;
  2372. a.name = arrangement.name.empty() ? "Arrangement " + std::to_string (song.arrangements.size() + 1) : arrangement.name;
  2373. // markers; type 8 changes the time signature (loop/pause actions become plain markers)
  2374. for (const auto& m : arrangement.markers)
  2375. {
  2376. Marker marker;
  2377. marker.tick = rescale (m.position);
  2378. marker.name = m.name;
  2379. marker.name.erase (0, marker.name.find_first_not_of (' '));
  2380. marker.name.erase (marker.name.find_last_not_of (' ') + 1);
  2381. if (m.type == 8 && m.numerator >= 1 && m.numerator <= 32 && m.denominator >= 1 && m.denominator <= 32)
  2382. {
  2383. marker.numerator = m.numerator;
  2384. marker.denominator = m.denominator;
  2385. }
  2386. // unnamed: the FL marker type (REA_rodada6 §5)
  2387. static const char* typeNames[] = { "", "Loop (marker)", "Skip", "Pause", "Loop", "Start", "Pattern length", "",
  2388. "", "Start recording", "Stop recording", "Loop length", "Key/scale" };
  2389. if (marker.name.empty() && m.type > 0 && m.type < 13 && m.type != 8)
  2390. marker.name = typeNames[m.type];
  2391. a.markers.push_back (std::move (marker));
  2392. }
  2393. std::stable_sort (a.markers.begin(), a.markers.end(), [] (const Marker& x, const Marker& y) { return x.tick < y.tick; });
  2394. importedTracks.push_back (&arrangement.tracks);
  2395. if (song.arrangements.empty())
  2396. song.playlist = std::move (clips); // the first is the current one
  2397. else
  2398. a.clips = std::move (clips);
  2399. song.arrangements.push_back (std::move (a));
  2400. }
  2401. // the .flp doesn't say which arrangement was open; the fullest is usually the song
  2402. {
  2403. int fullest = 0;
  2404. std::size_t most = song.playlist.size();
  2405. for (int i = 1; i < (int) song.arrangements.size(); ++i)
  2406. if (song.arrangements[(std::size_t) i].clips.size() > most)
  2407. {
  2408. most = song.arrangements[(std::size_t) i].clips.size();
  2409. fullest = i;
  2410. }
  2411. song.selectArrangement (fullest);
  2412. // Playlist track names, mute and colour (from the open arrangement); FL's default grey = no colour
  2413. if (fullest < (int) importedTracks.size())
  2414. for (const auto& t : *importedTracks[(std::size_t) fullest])
  2415. {
  2416. const auto coloured = (t.colour & 0xFFFFFF) != 0x485156;
  2417. const auto sized = std::abs (t.heightScale - 1.0f) > 0.01f;
  2418. if (t.index >= 0 && t.index < 500 && (! t.name.empty() || ! t.enabled || coloured || t.grouped || ! t.expanded || sized))
  2419. {
  2420. if ((int) song.playlistTracks.size() <= t.index)
  2421. song.playlistTracks.resize ((std::size_t) t.index + 1);
  2422. auto& track = song.playlistTracks[(std::size_t) t.index];
  2423. track = { t.name, ! t.enabled, 0, coloured ? 0xFF000000u | t.colour : 0u };
  2424. // FL's size is relative to its default row; LYNX keeps the same proportion of its own default
  2425. if (sized)
  2426. track.height = polish::clampTrackHeight ((int) std::lround (polish::defaultTrackHeight * t.heightScale));
  2427. track.grouped = t.index > 0 && t.grouped;
  2428. track.collapsed = ! t.expanded;
  2429. }
  2430. }
  2431. }
  2432. if (! song.playlist.empty())
  2433. song.mode = PlayMode::song;
  2434. if (song.patterns.empty())
  2435. song.patterns.emplace_back().name = "Pattern 1";
  2436. // The .flp doesn't say which pattern was open; the fullest is the best starting point.
  2437. for (int i = 0; i < (int) song.patterns.size(); ++i)
  2438. if (song.patterns[(std::size_t) i].notes.size() > song.patterns[(std::size_t) song.currentPattern].notes.size())
  2439. song.currentPattern = i;
  2440. // MIDI Out (REA_rodada16 §1): the channel makes no sound; its notes go to the plugins (Fruity
  2441. // Wrapper) listening on the same MIDI port
  2442. for (const auto& c : project.channels)
  2443. {
  2444. if (lowercase (c.pluginName) != "midi out" || c.pluginState.size() < 28)
  2445. continue;
  2446. const auto from = channelMap.find (c.index);
  2447. if (from == channelMap.end())
  2448. continue;
  2449. std::int32_t port = -1;
  2450. std::memcpy (&port, c.pluginState.data() + 24, 4);
  2451. auto& source = song.channels[(std::size_t) from->second];
  2452. source.muted = true;
  2453. for (int target = 0; target < (int) song.channels.size(); ++target)
  2454. {
  2455. const auto& t = song.channels[(std::size_t) target];
  2456. if (target == from->second || port < 0 || t.plugin.foreign.midiInPort != port)
  2457. continue;
  2458. for (auto& pattern : song.patterns)
  2459. {
  2460. const auto count = pattern.notes.size();
  2461. for (std::size_t n = 0; n < count; ++n)
  2462. if (pattern.notes[n].channel == from->second)
  2463. {
  2464. auto copy = pattern.notes[n];
  2465. copy.channel = target;
  2466. pattern.notes.push_back (copy);
  2467. }
  2468. }
  2469. }
  2470. }
  2471. // FPC kits: one channel per pad (last to first, so indices don't shift)
  2472. for (auto it = drumKits.rbegin(); it != drumKits.rend(); ++it)
  2473. splitDrumChannel (song, it->first, it->second);
  2474. numberChorusInstances (song); // the random LFO phases FL gives each Hyper Chorus instance (REA_rodada59 §2.6)
  2475. return song;
  2476. }
  2477. } // namespace lynx