4
0

FlpImport.cpp 115 KB

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