FlpImport.cpp 143 KB

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