FlpImport.cpp 139 KB

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