FlpImport.cpp 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732
  1. #include "core/FlpImport.h"
  2. #include "core/DrumSynthLive.h"
  3. #include "core/Harmless.h"
  4. #include "core/HarmlessFx.h"
  5. #include "core/PhysicalModels.h"
  6. #include "core/Effects.h"
  7. #include "core/FlEffects.h"
  8. #include "core/FlPatcher.h"
  9. #include "core/FlSamplers.h"
  10. #include "core/FlSynths.h"
  11. #include "core/FlWrapper.h"
  12. #include "core/SynthPresets.h"
  13. #include <algorithm>
  14. #include <cstring>
  15. #include <cctype>
  16. #include <cmath>
  17. #include <map>
  18. namespace lynx
  19. {
  20. namespace
  21. {
  22. bool contains (const std::string& haystack, const char* needle)
  23. {
  24. return haystack.find (needle) != std::string::npos;
  25. }
  26. std::string lowercase (std::string s)
  27. {
  28. std::transform (s.begin(), s.end(), s.begin(), [] (unsigned char c) { return (char) std::tolower (c); });
  29. return s;
  30. }
  31. } // namespace
  32. InstrumentKind guessInstrument (const std::string& channelName, flp::ChannelType type)
  33. {
  34. const auto name = lowercase (channelName);
  35. if (type == flp::ChannelType::sampler || type == flp::ChannelType::unknown)
  36. {
  37. if (contains (name, "kick") || contains (name, "bd") || contains (name, "808"))
  38. return InstrumentKind::kick;
  39. if (contains (name, "snare") || contains (name, "snr") || contains (name, "rim"))
  40. return InstrumentKind::snare;
  41. if (contains (name, "clap") || contains (name, "snap"))
  42. return InstrumentKind::clap;
  43. if (contains (name, "hat") || contains (name, "hh") || contains (name, "ride") || contains (name, "cym")
  44. || contains (name, "crash") || contains (name, "shaker") || contains (name, "perc") || contains (name, "tamb"))
  45. return InstrumentKind::hat;
  46. }
  47. return InstrumentKind::synth;
  48. }
  49. std::string resolveFlPath (const std::string& flPath, const FlPathRoots& roots)
  50. {
  51. const std::pair<const char*, const std::string*> variables[] = {
  52. { "%FLStudioFactoryData%", &roots.factoryData },
  53. { "%FLStudioUserData%", &roots.userData },
  54. { "%FLStudioData%", &roots.data },
  55. };
  56. for (const auto& [name, root] : variables)
  57. {
  58. const std::string variable (name);
  59. if (flPath.compare (0, variable.size(), variable) == 0)
  60. return root->empty() ? std::string() : *root + flPath.substr (variable.size());
  61. }
  62. return flPath;
  63. }
  64. std::optional<EffectKind> effectForFlPlugin (const std::string& name)
  65. {
  66. static const std::pair<const char*, EffectKind> table[] = {
  67. { "Fruity Parametric EQ 2", EffectKind::parametricEq }, { "Fruity Parametric EQ", EffectKind::parametricEq },
  68. { "Fruity 7 Band EQ", EffectKind::parametricEq },
  69. { "Fruity Limiter", EffectKind::limiter }, { "Maximus", EffectKind::limiter }, { "Fruity Soft Clipper", EffectKind::distortion },
  70. { "Fruity Reeverb 2", EffectKind::reverb }, { "Fruity Reeverb", EffectKind::reverb }, { "LuxeVerb", EffectKind::reverb },
  71. { "Fruity Delay 3", EffectKind::delay }, { "Fruity Delay 2", EffectKind::delay }, { "Fruity Delay Bank", EffectKind::delay },
  72. { "Fruity Delay", EffectKind::delay }, { "Fruity Compressor", EffectKind::compressor },
  73. { "Fruity Multiband Compressor", EffectKind::compressor }, { "Soundgoodizer", EffectKind::compressor },
  74. { "Fruity WaveShaper", EffectKind::distortion }, { "Fruity Fast Dist", EffectKind::distortion },
  75. { "Fruity Blood Overdrive", EffectKind::distortion }, { "Distructor", EffectKind::distortion },
  76. { "Fruity Flangus", EffectKind::chorus }, { "Fruity Chorus", EffectKind::chorus }, { "Hyper Chorus", EffectKind::chorus },
  77. { "Vintage Chorus", EffectKind::chorus }, { "Fruity Flanger", EffectKind::chorus },
  78. { "Fruity Balance", EffectKind::utility }, { "Fruity PanOMatic", EffectKind::utility }, { "Fruity Stereo Shaper", EffectKind::utility },
  79. { "Fruity Center", EffectKind::utility }, { "Fruity Phase Inverter", EffectKind::utility },
  80. { "Fruity Stereo Enhancer", EffectKind::utility }, { "Fruity Convolver", EffectKind::reverb }, { "EQUO", EffectKind::parametricEq },
  81. { "Spreader", EffectKind::utility }, { "Transient Processor", EffectKind::utility },
  82. { "Fruity Phaser", EffectKind::chorus }, { "Fruity Bass Boost", EffectKind::eq }, { "Fruity Free Filter", EffectKind::filter },
  83. { "Fruity Love Philter", EffectKind::filter }, { "Fruity Filter", EffectKind::filter }, { "Fruity Fast LP", EffectKind::filter },
  84. { "Gross Beat", EffectKind::volumeGate }, { "Frequency Splitter", EffectKind::parametricEq },
  85. { "Fruity Peak Controller", EffectKind::peakController },
  86. { "Pitch Shifter", EffectKind::pitchShift }, { "Frequency Shifter", EffectKind::freqShift },
  87. { "Emphasis", EffectKind::limiter }, { "Low Lifter", EffectKind::parametricEq },
  88. { "Fruity Send", EffectKind::utility }, { "Transporter", EffectKind::utility },
  89. { "Vintage Phaser", EffectKind::vintagePhaser }, { "Fruity Squeeze", EffectKind::squeeze },
  90. };
  91. // old presets (FL 3) store the name with different casing ("Fruity delay 2")
  92. const auto wanted = lowercase (name);
  93. for (const auto& [plugin, kind] : table)
  94. if (wanted == lowercase (plugin))
  95. return kind;
  96. return std::nullopt;
  97. }
  98. AutomationTarget automationTargetFor (flp::ControlId id, const std::map<int, int>& channelMap, int mixerTracks)
  99. {
  100. AutomationTarget t;
  101. if (id.isTempo())
  102. {
  103. t.kind = AutomationTargetKind::tempo;
  104. return t;
  105. }
  106. if (id.isChannel())
  107. {
  108. const auto channel = channelMap.find (id.channel());
  109. if (channel == channelMap.end())
  110. return t;
  111. t.index = channel->second;
  112. const auto p = id.param();
  113. if (p == 0)
  114. t.kind = AutomationTargetKind::channelVolume;
  115. else if (p == 1)
  116. t.kind = AutomationTargetKind::channelPan;
  117. else if (p >= flp::ControlId::pluginParamBase)
  118. {
  119. t.kind = AutomationTargetKind::channelParam;
  120. t.param = p - flp::ControlId::pluginParamBase;
  121. }
  122. return t;
  123. }
  124. if (id.isMixer() && id.track() >= 0 && id.track() < mixerTracks)
  125. {
  126. t.index = id.track();
  127. const auto p = id.param();
  128. if (p == 0x1F01) // slot dry/wet
  129. {
  130. t.kind = AutomationTargetKind::effectMix;
  131. t.slot = id.slot();
  132. }
  133. else if (p == flp::ControlId::mixerVolume)
  134. t.kind = AutomationTargetKind::mixerVolume;
  135. else if (p == flp::ControlId::mixerPan)
  136. t.kind = AutomationTargetKind::mixerPan;
  137. else if (p >= flp::ControlId::pluginParamBase)
  138. {
  139. t.kind = AutomationTargetKind::effectParam;
  140. t.slot = id.slot();
  141. t.param = p - flp::ControlId::pluginParamBase;
  142. }
  143. }
  144. return t;
  145. }
  146. bool synthFrom3xOsc (const std::vector<std::uint8_t>& state, SynthSettings& synth)
  147. {
  148. // version 10/11: 20 parameters + 4 bools (80 B); 12+: 21 parameters + 4 bools (+ HQ)
  149. if (state.size() < 84)
  150. return false;
  151. auto i32 = [&] (std::size_t offset) {
  152. return (std::int32_t) ((std::uint32_t) state[offset] | ((std::uint32_t) state[offset + 1] << 8)
  153. | ((std::uint32_t) state[offset + 2] << 16) | ((std::uint32_t) state[offset + 3] << 24));
  154. };
  155. const auto version = i32 (0);
  156. if (version < 10 || version > 64)
  157. return false;
  158. // parameter i is at 0x04 + 4i; (i + 1) = 7·osc + field, fields [mix, pan, shape, coarse, fine, spo, detune]
  159. auto param = [&] (int osc, int field) { return i32 ((std::size_t) (4 + 4 * (7 * osc + field - 1))); };
  160. const auto boolsAt = version >= 12 ? (std::size_t) 0x58 : (std::size_t) 0x54;
  161. const bool am = version >= 11 && state.size() > boolsAt + 3 && state[boolsAt + 3] != 0;
  162. // levels (§2.2): osc 3 takes mix3/128, osc 2 a share of the rest, osc 1 what remains
  163. const auto g3 = std::clamp (param (2, 0), 0, 128) / 128.0f;
  164. const auto rest = am ? 1.0f : 1.0f - g3;
  165. const auto g2 = rest * std::clamp (param (1, 0), 0, 128) / 128.0f;
  166. // with AM, osc 3 is not summed: its level becomes the modulation depth (REA_rodada6 §3)
  167. const std::array<float, 3> levels { std::max (0.0f, rest - g2), g2, g3 };
  168. synth.am = am;
  169. for (int o = 0; o < 3; ++o)
  170. {
  171. auto& osc = synth.osc[(std::size_t) o];
  172. switch (param (o, 2))
  173. {
  174. case 0: osc.wave = Waveform::sine; break;
  175. case 1: osc.wave = Waveform::triangle; break;
  176. case 2: osc.wave = Waveform::square; break;
  177. case 5: osc.wave = Waveform::noise; break;
  178. default: osc.wave = Waveform::saw; break; // 3 saw, 4 rounded saw, 6 custom without sample
  179. }
  180. const auto coarse = std::clamp (param (o, 3), -24, 24);
  181. osc.octave = coarse / 12; // truncates toward zero; the remainder becomes semitones
  182. osc.semitones = coarse - osc.octave * 12;
  183. // stereo detune only sounds on the right channel: half of it counts as average detune
  184. 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);
  185. osc.pan = std::clamp (param (o, 1), -64, 64) / 64.0f;
  186. osc.level = levels[(std::size_t) o];
  187. }
  188. return true;
  189. }
  190. namespace
  191. {
  192. // FL channel filter cutoff (Hz) for normalized Mod X `x` (REA_rodada4 §3); 20 kHz = open.
  193. double channelFilterHz (int type, double x)
  194. {
  195. constexpr double twoPi = 6.283185307179586;
  196. x = std::clamp (x, 0.0, 1.0);
  197. switch (type)
  198. {
  199. case 0:
  200. 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));
  201. case 1:
  202. case 2:
  203. case 3:
  204. case 4:
  205. case 5: return ((std::pow (51.0, x) - 1.0) * 0.0596 + 0.02) * 44100.0 / twoPi;
  206. case 6:
  207. 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);
  208. default: return 20000.0;
  209. }
  210. }
  211. } // namespace
  212. float filterEnvelopeOctaves (int modX, int type, int amount)
  213. {
  214. const auto x = std::clamp (modX / 256.0, 0.0, 1.0);
  215. const auto from = std::clamp (channelFilterHz (type, x), 20.0, 20000.0);
  216. const auto to = std::clamp (channelFilterHz (type, x + amount / 128.0), 20.0, 20000.0);
  217. return (float) std::log2 (to / from);
  218. }
  219. void synthFilterFromChannel (int modX, int modY, int type, float& cutoffHz, float& resonance, int& mode)
  220. {
  221. mode = type == 2 ? 1 : type == 3 ? 2 : type == 4 ? 3 : 0; // BP, HP, BS; the rest is low-pass
  222. const auto x = std::clamp (modX / 256.0, 0.0, 1.0);
  223. const auto r = std::clamp (modY / 256.0, 0.0, 1.0);
  224. 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
  225. resonance = 0.0f;
  226. if (type == 0) // Fast LP: 1 pole + feedback; feedback grows with Mod Y (approximation)
  227. resonance = (float) (r * 0.9);
  228. else if (type >= 1 && type <= 5) // LP/BP/HP/BS biquads (LPx2 = the LP twice)
  229. resonance = fromQ (r <= 0.0 ? 0.1 : (std::pow (51.0, 0.625 * r) - 1.0) * 0.4 + 0.1);
  230. else if (type == 6 || type == 7) // Chamberlin SVF
  231. resonance = fromQ (1.0 / (r <= 0.0 ? 1.0 : (r < 1.0 ? 1.0 - 0.8 * r : 0.2)));
  232. cutoffHz = (float) std::clamp (channelFilterHz (type, x), 20.0, 20000.0);
  233. }
  234. void splitDrumChannel (Song& song, int channel, const std::vector<DrumPad>& pads)
  235. {
  236. if (channel < 0 || channel >= (int) song.channels.size() || pads.empty())
  237. return;
  238. const auto original = song.channels[(std::size_t) channel];
  239. const auto inserted = (int) pads.size() - 1; // the first pad takes the original channel's place
  240. std::vector<ChannelDef> padChannels;
  241. for (const auto& pad : pads)
  242. {
  243. ChannelDef def = original;
  244. def.name = original.name + " - " + pad.name;
  245. def.instrument = InstrumentKind::sampler;
  246. def.plugin = {};
  247. const auto single = pad.layers.size() == 1;
  248. def.samplePath = single ? pad.layers.front().path : std::string();
  249. def.zones = single ? std::vector<SampleZone> {} : pad.layers;
  250. for (auto& z : def.zones)
  251. z.rootKey = 60, z.lowKey = 0, z.highKey = 127; // the pad plays at the sample's pitch
  252. // volume: channel gain × pad gain (× the single layer's), mapped back to the channel curve
  253. const auto gain = channelGain (original.volume) * pad.gain * (single ? pad.layers.front().gain : 1.0f);
  254. def.volume = std::clamp ((float) (std::log (10.0 * gain + 1.0) / std::log (11.0)), 0.0f, 1.0f);
  255. def.pan = std::clamp (original.pan + pad.pan, -1.0f, 1.0f);
  256. def.sampler = {};
  257. def.sampler.pitch = std::clamp (original.sampler.pitch + pad.tune + (single ? pad.layers.front().tune : 0.0f), -24.0f, 24.0f);
  258. // kit-specific cut groups (don't mix with other channels' groups)
  259. def.cutGroup = pad.cutGroup > 0 ? 1000 * (channel + 1) + pad.cutGroup : 0;
  260. def.cutBy = pad.cutBy > 0 ? 1000 * (channel + 1) + pad.cutBy : 0;
  261. def.mixerTrack = std::clamp (original.mixerTrack + pad.mixerOffset, 0, maxMixerTracks - 1);
  262. padChannels.push_back (std::move (def));
  263. }
  264. song.channels[(std::size_t) channel] = padChannels.front();
  265. song.channels.insert (song.channels.begin() + channel + 1, padChannels.begin() + 1, padChannels.end());
  266. // channels after the original shift by `inserted` positions
  267. auto shift = [&] (int c) { return c > channel ? c + inserted : c; };
  268. for (auto& p : song.patterns)
  269. {
  270. std::vector<Note> kept;
  271. for (auto n : p.notes)
  272. {
  273. if (n.channel != channel)
  274. {
  275. n.channel = shift (n.channel);
  276. kept.push_back (n);
  277. continue;
  278. }
  279. for (int i = 0; i < (int) pads.size(); ++i)
  280. if (pads[(std::size_t) i].key == n.key)
  281. {
  282. n.channel = channel + i;
  283. n.key = 60;
  284. kept.push_back (n);
  285. break;
  286. }
  287. }
  288. p.notes = std::move (kept);
  289. p.sortNotes();
  290. }
  291. song.forEachClipList ([&] (std::vector<Clip>& clips) {
  292. for (auto& c : clips)
  293. c.channel = c.channel >= 0 ? shift (c.channel) : c.channel;
  294. });
  295. song.forEachTarget ([&] (AutomationTarget& t) {
  296. if ((t.kind == AutomationTargetKind::channelVolume || t.kind == AutomationTargetKind::channelPan
  297. || t.kind == AutomationTargetKind::channelParam) && t.index >= 0)
  298. t.index = shift (t.index);
  299. });
  300. }
  301. bool isFlSynthPresetPlugin (const std::string& pluginName)
  302. {
  303. static const char* const supported[] = { "3x osc", "sytrus", "harmor", "gms", "harmless", "minisynth", "fruity dx10", "dx10",
  304. "fruit kick", "ogun", "autogun", "sakura", "kepler", "boobass", "poizone", "bassdrum",
  305. "toxic biohazard" };
  306. const auto name = lowercase (pluginName);
  307. return std::any_of (std::begin (supported), std::end (supported), [&] (const char* n) { return name == n; });
  308. }
  309. std::optional<SynthSettings> synthFromFlPreset (const std::vector<std::uint8_t>& bytes)
  310. {
  311. // native GMS preset (.gmsynth): it is the plugin state without the "SSLF"
  312. if (bytes.size() >= 4 && (std::memcmp (bytes.data(), "4nyS", 4) == 0 || std::memcmp (bytes.data(), "3nyS", 4) == 0))
  313. {
  314. std::vector<std::uint8_t> state { 'S', 'S', 'L', 'F' };
  315. const auto n = (std::uint32_t) bytes.size();
  316. for (int i = 0; i < 4; ++i)
  317. state.push_back ((std::uint8_t) (n >> (8 * i)));
  318. state.insert (state.end(), bytes.begin(), bytes.end());
  319. SynthSettings synth;
  320. float gain = 1.0f;
  321. if (synthFromGms (state, 120.0, synth, gain))
  322. return synth;
  323. return std::nullopt;
  324. }
  325. try
  326. {
  327. auto project = flp::parseProject (bytes, true);
  328. if (project.channels.empty() || ! isFlSynthPresetPlugin (project.channels.front().pluginName))
  329. return std::nullopt;
  330. project.channels.front().type = flp::ChannelType::native; // native generator (the .fst doesn't say)
  331. const auto song = importFlp (project);
  332. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::sakura)
  333. {
  334. // the synth's preset button keeps the synth approximation of a Sakura patch
  335. SynthSettings synth;
  336. if (synthFromSakura (project.channels.front().pluginState, synth))
  337. return synth;
  338. }
  339. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::harmless)
  340. {
  341. // ... and of a Harmless patch
  342. SynthSettings synth;
  343. float gain = 1.0f;
  344. if (synthFromHarmless (project.channels.front().pluginState, song.bpm, synth, gain))
  345. return synth;
  346. }
  347. if (song.channels.empty() || song.channels.front().instrument != InstrumentKind::synth)
  348. return std::nullopt;
  349. return song.channels.front().synth;
  350. }
  351. catch (const flp::Error&)
  352. {
  353. return std::nullopt;
  354. }
  355. }
  356. Song importFlp (const flp::Project& input, const FlpImportOptions& options)
  357. {
  358. // Patcher used as an instrument: the channel becomes the main generator inside it (REA_rodada14 §1)
  359. std::optional<flp::Project> unpacked;
  360. for (std::size_t i = 0; i < input.channels.size(); ++i)
  361. if (lowercase (input.channels[i].pluginName) == "patcher")
  362. if (const auto graph = parsePatcher (input.channels[i].pluginState); graph && graph->mainGenerator >= 0)
  363. {
  364. if (! unpacked)
  365. unpacked = input;
  366. const auto& node = graph->nodes[(std::size_t) graph->mainGenerator];
  367. unpacked->channels[i].pluginName = node.plugin;
  368. unpacked->channels[i].pluginState = node.state;
  369. }
  370. const auto& project = unpacked ? *unpacked : input;
  371. Song song;
  372. song.bpm = project.tempo > 0.0 ? project.tempo : 140.0;
  373. song.beatsPerBar = std::clamp (project.beatsPerBar, 1, 32);
  374. song.swing = std::clamp (project.swing / 128.0f, 0.0f, 1.0f);
  375. // FL channels may have sparse indices; we map them to dense indices.
  376. std::map<int, int> channelMap;
  377. std::vector<std::pair<int, std::vector<DrumPad>>> drumKits; // FPC channels to split at the end
  378. std::optional<std::string> drumSynthDll; // the user's DrumSynth Live engine DLL, once checked ("" = not usable)
  379. for (const auto& c : project.channels)
  380. {
  381. // automation clips become Song::automations (further below), not channels
  382. if (c.type == flp::ChannelType::automationClip)
  383. continue;
  384. channelMap[c.index] = (int) song.channels.size();
  385. ChannelDef def;
  386. def.name = c.name.empty() ? "Channel " + std::to_string (c.index + 1) : c.name;
  387. def.instrument = guessInstrument (def.name, c.type);
  388. // FL synthesizer that becomes the internal synth: a preset matching the name (in FLEX, the name
  389. // of the preset chosen in the plugin says more than the channel's)
  390. if (def.instrument == InstrumentKind::synth)
  391. {
  392. def.synth = presetForChannelName (def.name);
  393. if (lowercase (c.pluginName) == "flex")
  394. if (const auto names = flexPresetName (c.pluginState))
  395. if (auto byPreset = presetForChannelName (names->second + " " + names->first); byPreset != SynthSettings {})
  396. def.synth = byPreset;
  397. }
  398. const auto isAudioClip = c.type == flp::ChannelType::audioClip;
  399. if ((c.type == flp::ChannelType::sampler || isAudioClip) && ! c.samplePath.empty() && options.fileExists)
  400. {
  401. const auto path = resolveFlPath (c.samplePath, options.roots);
  402. if (! path.empty() && options.fileExists (path))
  403. {
  404. def.instrument = isAudioClip ? InstrumentKind::audioClip : InstrumentKind::sampler;
  405. def.samplePath = path;
  406. }
  407. }
  408. if (isAudioClip && def.instrument != InstrumentKind::audioClip)
  409. def.instrument = InstrumentKind::audioClip; // no file: stays silent, but the clip remains in the playlist
  410. def.mixerTrack = std::clamp (c.mixerTrack, 0, maxMixerTracks - 1);
  411. if (c.colour != 0)
  412. def.colour = 0xFF000000u | c.colour;
  413. if (c.hasLevels)
  414. {
  415. def.volume = std::clamp (c.volume / 12800.0f, 0.0f, 1.0f); // same curve (channelGain)
  416. def.pan = std::clamp ((c.pan - 6400) / 6400.0f, -1.0f, 1.0f);
  417. def.sampler.pitch = std::clamp (c.pitchCents / 100.0f, -24.0f, 24.0f);
  418. }
  419. // sample root note: our sampler plays at the original pitch at C5 (60)
  420. if (c.rootNote >= 0 && c.rootNote <= 127)
  421. def.sampler.pitch = std::clamp (def.sampler.pitch + (float) (60 - c.rootNote), -24.0f, 24.0f);
  422. def.swingMix = std::clamp (c.swingMix / 128.0f, 0.0f, 1.0f);
  423. def.cutGroup = c.cutGroup;
  424. def.cutBy = c.cutBy;
  425. // "cut itself" (group == cut by) and mono channel become the sampler's "cut"
  426. if ((c.cutGroup != 0 && c.cutGroup == c.cutBy) || c.maxVoices == 1)
  427. def.sampler.cut = true;
  428. def.synth.mono = c.monoFlag || c.maxVoices == 1;
  429. // channel porta and slide time: n = round((27^(v/1024) - 1) * 48/26) ticks of 1/192 beat
  430. // (REA_rodada6 §4); the time also applies to notes with their own porta
  431. {
  432. const auto ticks = std::round ((std::pow (27.0, std::clamp (c.slideTime, 0, 1660) / 1024.0) - 1.0) * 48.0 / 26.0);
  433. def.synth.portaBeats = def.sampler.portaBeats = (float) std::max (1.0, ticks) / 192.0f;
  434. def.synth.porta = def.sampler.porta = c.portaFlag;
  435. }
  436. // volume envelope (record 1 of 0xDA) -> sampler ADSR
  437. const auto& volumeEnvelope = c.envelopes[1];
  438. const auto hasVolumeEnvelope = volumeEnvelope.present && volumeEnvelope.enabled;
  439. if (hasVolumeEnvelope)
  440. {
  441. const auto& env = volumeEnvelope;
  442. const auto beats = (env.flags & 1) != 0; // tempo-synced: units in beats
  443. auto seconds = [&] (int v) {
  444. const auto t = flp::Channel::envelopeTime (v);
  445. return (float) (beats ? t * 2.0 * 60.0 / song.bpm : t); // 0.128 beat instead of 0.064 s
  446. };
  447. def.sampler.attack = std::clamp (seconds (env.attack), 0.0f, 2.0f);
  448. def.sampler.decay = std::clamp (seconds (env.decay), 0.0f, 10.0f);
  449. def.sampler.sustain = std::clamp (env.sustain / 128.0f, 0.0f, 1.0f);
  450. def.sampler.release = std::clamp (std::max (seconds (env.release), 0.002f), 0.0f, 4.0f); // envelope on: the note ends
  451. }
  452. // channel filter (Mod X/Y + type from 0xDB) applies to the sampler too
  453. synthFilterFromChannel (c.modX, c.modY, c.filterType, def.sampler.cutoff, def.sampler.resonance, def.sampler.filterType);
  454. // channel cutoff (record 2) and pitch (record 4) envelopes
  455. auto modEnvelope = [&] (const flp::Channel::Envelope& env, float amount) {
  456. ModEnvelope m;
  457. if (! env.present || ! env.enabled || amount == 0.0f)
  458. return m;
  459. const auto beats = (env.flags & 1) != 0;
  460. auto seconds = [&] (int v) {
  461. const auto t = flp::Channel::envelopeTime (v);
  462. return (float) std::clamp (beats ? t * 2.0 * 60.0 / song.bpm : t, 0.0, 20.0);
  463. };
  464. m.amount = amount;
  465. m.attack = seconds (env.attack);
  466. m.hold = seconds (env.hold);
  467. m.decay = seconds (env.decay);
  468. m.sustain = std::clamp (env.sustain / 128.0f, 0.0f, 1.0f);
  469. m.release = seconds (env.release);
  470. return m;
  471. };
  472. const auto filterEnv = modEnvelope (c.envelopes[2], filterEnvelopeOctaves (c.modX, c.filterType, c.envelopes[2].amount));
  473. const auto pitchEnv = modEnvelope (c.envelopes[4], std::clamp (c.envelopes[4].amount, -2400, 2400) / 100.0f);
  474. def.sampler.filterEnv = filterEnv;
  475. def.sampler.pitchEnv = pitchEnv;
  476. // channel LFOs (records 0 pan, 1 volume, 2 cutoff, 4 pitch; REA_rodada6 §2)
  477. {
  478. auto lfoFrom = [&] (const flp::Channel::Envelope& env, float amount) {
  479. ChannelLfo l;
  480. if (! env.present || env.lfoAmount == 0 || amount == 0.0f)
  481. return l;
  482. l.sync = (env.flags & 0x02) != 0;
  483. auto time = [&] (int v) { // seconds, or beats when synced (double the scale)
  484. const auto t = flp::Channel::envelopeTime (v);
  485. return (float) std::clamp (l.sync ? t * 2.0 : t, 0.0, 64.0);
  486. };
  487. l.amount = amount;
  488. l.period = std::max (0.01f, time (env.lfoSpeed));
  489. l.shape = std::clamp (env.lfoShape, 0, 2);
  490. l.delay = time (env.lfoDelay);
  491. l.attack = time (env.lfoAttack);
  492. l.global = (env.flags & 0x20) != 0;
  493. return l;
  494. };
  495. std::array<ChannelLfo, lfoTargets> lfo {};
  496. lfo[lfoPan] = lfoFrom (c.envelopes[0], std::clamp (c.envelopes[0].lfoAmount, -64, 64) / 64.0f);
  497. lfo[lfoVolume] = lfoFrom (c.envelopes[1], std::clamp (c.envelopes[1].lfoAmount, -128, 128) / 128.0f);
  498. lfo[lfoCutoff] = lfoFrom (c.envelopes[2], filterEnvelopeOctaves (c.modX, c.filterType, c.envelopes[2].lfoAmount));
  499. lfo[lfoPitch] = lfoFrom (c.envelopes[4], std::clamp (c.envelopes[4].lfoAmount, -2400, 2400) / 100.0f);
  500. def.sampler.lfo = lfo;
  501. def.synth.lfo = lfo;
  502. }
  503. // third-party plugin (VST/CLAP) in Fruity Wrapper: the app looks for the same installed plugin;
  504. // until then (or if not found) the channel stays on the internal synth
  505. // FL generators with samples (REA_rodada9): DirectWave becomes a multi-sample sampler; FPC is
  506. // split into one channel per pad at the end of the import (notes go to the pad by key)
  507. auto existing = [&] (std::string path) {
  508. const auto resolved = resolveFlPath (path, options.roots);
  509. return ! resolved.empty() && options.fileExists && options.fileExists (resolved) ? resolved : std::string();
  510. };
  511. if (c.pluginName == "DirectWave")
  512. if (auto program = directWaveProgram (c.pluginState))
  513. {
  514. std::vector<SampleZone> zones;
  515. for (std::size_t i = 0; i < program->zones.size(); ++i)
  516. {
  517. auto z = program->zones[i];
  518. auto path = existing (z.path);
  519. // file missing on this machine: use the audio the project stored with it
  520. if (path.empty() && i < program->embeddedWav.size() && ! program->embeddedWav[i].empty() && options.saveEmbedded)
  521. path = options.saveEmbedded (program->embeddedWav[i], def.name + " " + std::to_string (i + 1));
  522. if (! path.empty())
  523. {
  524. z.path = path;
  525. zones.push_back (std::move (z));
  526. }
  527. }
  528. if (! zones.empty())
  529. {
  530. def.instrument = InstrumentKind::sampler;
  531. def.zones = std::move (zones);
  532. def.sampler.attack = std::clamp (program->attack, 0.0f, 2.0f);
  533. def.sampler.decay = std::clamp (program->decay, 0.0f, 10.0f);
  534. def.sampler.sustain = program->sustain;
  535. def.sampler.release = std::clamp (std::max (program->release, 0.01f), 0.0f, 4.0f);
  536. }
  537. }
  538. // Fruity Slicer / Slicex: sampler with the slices (slice i plays on key 60 + i, at the sample's pitch)
  539. {
  540. const auto name = lowercase (c.pluginName);
  541. std::optional<SlicedSample> sliced;
  542. if (name == "fruity slicer")
  543. sliced = fruitySlicer (c.pluginState);
  544. else if (name == "slicex")
  545. sliced = slicex (c.pluginState);
  546. if (sliced)
  547. {
  548. std::string path;
  549. if (! sliced->embeddedWav.empty() && options.saveEmbedded) // audio that only exists inside the project
  550. path = options.saveEmbedded (sliced->embeddedWav, def.name);
  551. if (path.empty())
  552. path = existing (sliced->path);
  553. if (! path.empty())
  554. {
  555. auto positions = sliced->positions;
  556. std::int64_t frames = 0;
  557. if (positions.empty()) // Slicex: the slices are the WAV "cue" points
  558. {
  559. const auto bytes = ! sliced->embeddedWav.empty() ? sliced->embeddedWav
  560. : options.readFile ? options.readFile (path) : std::vector<std::uint8_t> {};
  561. positions = wavCuePoints (bytes, frames);
  562. }
  563. if (frames <= 0 && options.sampleFrames)
  564. frames = options.sampleFrames (path);
  565. def.instrument = InstrumentKind::sampler;
  566. def.samplePath = path;
  567. def.sampler.pitch = std::clamp (def.sampler.pitch + sliced->pitchCents / 100.0f, -24.0f, 24.0f);
  568. if (frames > 0)
  569. for (auto p : positions)
  570. if (p >= 0 && p < frames)
  571. def.sampler.slices.push_back ((float) ((double) p / (double) frames));
  572. }
  573. }
  574. }
  575. // FL Keys: the samples of the set (.wti) that ships with FL
  576. if (c.pluginName == "FL Keys" && options.readFile && ! options.roots.factoryData.empty())
  577. if (const auto set = flKeysSet (c.pluginState))
  578. {
  579. const auto folder = options.roots.factoryData + "\\Plugins\\Fruity\\Generators\\FL Keys\\Wavtables";
  580. const auto wtiBytes = options.readFile (folder + "\\" + *set + ".wti");
  581. const std::string wti (wtiBytes.begin(), wtiBytes.end());
  582. std::vector<std::uint8_t> rawData;
  583. if (wti.find ("filetype=raw") != std::string::npos)
  584. if (const auto file = wti.find ("samplefile="); file != std::string::npos)
  585. {
  586. auto name = wti.substr (file + 11, wti.find_first_of ("\r\n", file) - file - 11);
  587. rawData = options.readFile (folder + "\\" + name);
  588. }
  589. std::vector<SampleZone> zones;
  590. for (auto z : flKeysZones (wti, folder, rawData, options.saveEmbedded))
  591. if (z.path = existing (z.path); ! z.path.empty())
  592. zones.push_back (std::move (z));
  593. if (! zones.empty())
  594. {
  595. def.instrument = InstrumentKind::sampler;
  596. def.zones = std::move (zones);
  597. def.sampler.release = 0.4f; // the piano releases the note with a short release
  598. }
  599. }
  600. // Wave Traveller: plays its sample (the scratch curve is left out)
  601. if (c.pluginName == "Wave Traveller")
  602. if (const auto wave = waveTravellerSample (c.pluginState))
  603. if (auto path = existing (wave->first); ! path.empty())
  604. {
  605. def.instrument = InstrumentKind::sampler;
  606. def.samplePath = std::move (path);
  607. def.sampler.pitch = std::clamp (def.sampler.pitch + (float) (60 - wave->second), -24.0f, 24.0f);
  608. }
  609. // Fruity Envelope Controller: "controller" channel (silent) that triggers the envelopes from notes
  610. if ((c.pluginName == "Fruity Envelope Controller" && parseEnvelopeController (c.pluginState))
  611. || (c.pluginName == "Fruity Keyboard Controller" && parseKeyboardController (c.pluginState)))
  612. {
  613. def.instrument = InstrumentKind::controller;
  614. def.controllerState = c.pluginState;
  615. }
  616. // Fruity DrumSynth Live: its engine with all 120 patches (REA_rodada30 §1); the recorded waveforms some patches
  617. // use are read at run time from the user's own engine DLL (without it they are silent, the synthesis is not).
  618. // Fallback when the state can't be parsed: the FL drum sample with the same name as the editor's sound
  619. if (c.pluginName == "Fruity DrumSynth Live")
  620. {
  621. if (auto params = drumSynthLiveParams (c.pluginState))
  622. {
  623. def.instrument = InstrumentKind::drumsynth;
  624. def.modelParams = std::move (*params);
  625. if (! drumSynthDll)
  626. {
  627. drumSynthDll = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Fruity DrumSynth Live\\drumsynth_eng_x64.dll",
  628. options.roots);
  629. if (drumSynthDll->empty() || ! options.fileExists || ! options.fileExists (*drumSynthDll) || ! drumSynthDllUsable (*drumSynthDll))
  630. drumSynthDll = std::string();
  631. }
  632. def.samplePath = *drumSynthDll;
  633. }
  634. else if (const auto sound = drumSynthLiveSound (c.pluginState))
  635. for (const auto& candidate : drumSampleCandidates (*sound))
  636. if (auto path = existing (candidate); ! path.empty())
  637. {
  638. def.instrument = InstrumentKind::sampler;
  639. def.samplePath = std::move (path);
  640. break;
  641. }
  642. }
  643. if (c.pluginName == "FPC")
  644. if (auto pads = fpcPads (c.pluginState))
  645. {
  646. std::vector<DrumPad> found;
  647. for (auto pad : *pads)
  648. {
  649. std::vector<SampleZone> layers;
  650. for (auto layer : pad.layers)
  651. if (layer.path = existing (layer.path); ! layer.path.empty())
  652. layers.push_back (std::move (layer));
  653. pad.layers = std::move (layers);
  654. if (! pad.layers.empty())
  655. found.push_back (std::move (pad));
  656. }
  657. if (! found.empty())
  658. drumKits.push_back ({ (int) song.channels.size(), std::move (found) });
  659. }
  660. if (c.pluginName == "Fruity Wrapper" && parseFlWrapper (c.pluginState, def.plugin.foreign))
  661. def.plugin.name = def.plugin.foreign.name;
  662. // Fruit Kick, MiniSynth, ... (REA_rodada10): approximated by the internal synth; the channel LFOs are kept
  663. bool adoptedFromPlugin = false;
  664. if (def.instrument == InstrumentKind::synth)
  665. {
  666. const auto name = lowercase (c.pluginName);
  667. SynthSettings fromPlugin;
  668. float pluginGain = 1.0f;
  669. auto adopt = [&] {
  670. for (int i = 0; i < lfoTargets; ++i)
  671. if (def.synth.lfo[(std::size_t) i].amount != 0.0f)
  672. fromPlugin.lfo[(std::size_t) i] = def.synth.lfo[(std::size_t) i];
  673. def.synth = fromPlugin;
  674. adoptedFromPlugin = true;
  675. const auto g = channelGain (def.volume) * pluginGain;
  676. def.volume = std::clamp ((float) (std::log (10.0 * g + 1.0) / std::log (11.0)), 0.0f, 1.0f);
  677. };
  678. if (name == "harmless")
  679. {
  680. // FL's additive engine (REA_rodada32); the internal synth approximation stays as the fallback
  681. if (auto params = harmlessParams (c.pluginState))
  682. {
  683. def.instrument = InstrumentKind::harmless;
  684. def.modelParams = std::move (*params);
  685. adoptedFromPlugin = true;
  686. // rack compressor: Harmless's own preset <n>.fst from the user's installation (REA_rodada36 §2)
  687. const auto compType = (int) def.modelParams[(std::size_t) harmlessComboIndex + 3];
  688. if (compType > 0)
  689. {
  690. const auto path = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Harmless\\Data\\Compression\\"
  691. + std::to_string (compType) + ".fst",
  692. options.roots);
  693. std::optional<std::vector<std::uint8_t>> state;
  694. if (! path.empty() && options.readFile && (! options.fileExists || options.fileExists (path)))
  695. state = hlfx::maximusStateFromFst (options.readFile (path));
  696. if (state && hlfx::makeMaximusPreset (*state) != nullptr)
  697. {
  698. def.modelParams.push_back ((float) state->size());
  699. for (const auto byte : *state)
  700. def.modelParams.push_back ((float) byte);
  701. }
  702. else if (options.report != nullptr)
  703. ++options.report->droppedEffects["Harmless compressor (preset not found)"];
  704. }
  705. }
  706. else if (synthFromHarmless (c.pluginState, song.bpm, fromPlugin, pluginGain))
  707. adopt();
  708. }
  709. else if (name == "fruit kick" && synthFromFruitKick (c.pluginState, fromPlugin))
  710. adopt();
  711. else if (name == "minisynth" && synthFromMiniSynth (c.pluginState, song.bpm, fromPlugin))
  712. adopt();
  713. else if ((name == "fruity dx10" || name == "dx10") && synthFromDX10 (c.pluginState, fromPlugin))
  714. adopt();
  715. else if (name == "sytrus" && synthFromSytrus (c.pluginState, song.bpm, fromPlugin, pluginGain))
  716. adopt();
  717. else if (name == "harmor" && synthFromHarmor (c.pluginState, fromPlugin, pluginGain))
  718. adopt();
  719. else if (name == "gms" && synthFromGms (c.pluginState, song.bpm, fromPlugin, pluginGain))
  720. adopt();
  721. else if ((name == "ogun" || name == "autogun") && synthFromOgun (c.pluginState, fromPlugin, pluginGain))
  722. adopt();
  723. else if (name == "sakura")
  724. {
  725. // the physical string model (REA_rodada28 §1); the old saw + triangle stays as a fallback
  726. if (auto params = sakuraParams (c.pluginState))
  727. {
  728. def.instrument = InstrumentKind::sakura;
  729. def.modelParams = std::move (*params);
  730. adoptedFromPlugin = true;
  731. }
  732. else if (synthFromSakura (c.pluginState, fromPlugin))
  733. adopt();
  734. }
  735. else if (name == "kepler" && synthFromKepler (c.pluginState, fromPlugin, pluginGain))
  736. adopt();
  737. else if (name == "boobass")
  738. {
  739. // FL's engine with its multisample read at run time from the user's own BooBass DLL (REA_rodada29 §4)
  740. const auto dll = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\BooBass\\BooBass_Eng_x64.dll", options.roots);
  741. auto word = [&] (std::size_t at) { std::uint32_t v = 0; std::memcpy (&v, c.pluginState.data() + at, 4); return v; };
  742. if (c.pluginState.size() >= 16 && word (0) == 1 && ! dll.empty() && options.fileExists && options.fileExists (dll)
  743. && booBassDllUsable (dll))
  744. {
  745. def.instrument = InstrumentKind::boobass;
  746. def.samplePath = dll;
  747. for (std::size_t k = 0; k < 3; ++k)
  748. def.modelParams.push_back ((float) std::clamp ((int) word (4 + 4 * k), 0, 65535));
  749. adoptedFromPlugin = true;
  750. }
  751. else if (synthFromBooBass (c.pluginState, fromPlugin))
  752. adopt();
  753. }
  754. else if (name == "poizone" && synthFromPoiZone (c.pluginState, fromPlugin, pluginGain))
  755. adopt();
  756. else if (name == "bassdrum" && synthFromBassDrum (c.pluginState, fromPlugin, pluginGain))
  757. adopt();
  758. else if (name == "toxic biohazard" && synthFromToxic (c.pluginState, fromPlugin, pluginGain))
  759. adopt();
  760. else if (name == "morphine" && synthFromMorphine (c.pluginState, fromPlugin, pluginGain))
  761. adopt();
  762. else if (name == "drumpad" && drumpadParams (c.pluginState))
  763. {
  764. // the physical drum model (REA_rodada28 §2)
  765. const auto dp = drumpadParams (c.pluginState);
  766. def.instrument = InstrumentKind::drumpad;
  767. def.modelParams.assign (dp->begin(), dp->end());
  768. adoptedFromPlugin = true;
  769. }
  770. else if (name == "drumpad")
  771. if (const auto patch = drumpadPatchName (c.pluginState))
  772. {
  773. // kick/snare/clap/hi-hat: the drum instruments; the rest, a drum on the synth
  774. if (const auto drum = guessInstrument (*patch, flp::ChannelType::sampler); drum != InstrumentKind::synth)
  775. {
  776. def.instrument = drum;
  777. adoptedFromPlugin = true;
  778. }
  779. else
  780. {
  781. fromPlugin = drumToneForName (*patch);
  782. // confirmed: Pitch ×2^(2x − 1) and Mallet Amplitude 10^(−4(1 − x)) (the physical model isn't)
  783. if (const auto dp = drumpadParams (c.pluginState))
  784. {
  785. const auto semis = 12.0f * (2.0f * std::clamp ((*dp)[29], 0.0f, 1.0f) - 1.0f);
  786. for (auto& o : fromPlugin.osc)
  787. {
  788. o.semitones += (int) std::lround (semis);
  789. o.detune += 100.0f * (semis - (float) std::lround (semis));
  790. }
  791. pluginGain = (float) std::pow (10.0, -4.0 * (1.0 - std::clamp ((double) (*dp)[2], 0.0, 1.0)));
  792. }
  793. adopt();
  794. }
  795. }
  796. }
  797. // 3x Osc: oscillators from the plugin state; envelope and filter come from the channel (REA_rodada4)
  798. if (def.instrument == InstrumentKind::synth && c.pluginName == "3x Osc" && synthFrom3xOsc (c.pluginState, def.synth))
  799. {
  800. if (hasVolumeEnvelope)
  801. {
  802. def.synth.attack = def.sampler.attack;
  803. def.synth.decay = def.sampler.decay;
  804. def.synth.sustain = def.sampler.sustain;
  805. def.synth.release = def.sampler.release;
  806. }
  807. else
  808. {
  809. // without an envelope FL plays the note as a gate, with only a short declick
  810. def.synth.attack = 0.002f;
  811. def.synth.decay = 0.0f;
  812. def.synth.sustain = 1.0f;
  813. def.synth.release = 0.02f;
  814. }
  815. synthFilterFromChannel (c.modX, c.modY, c.filterType, def.synth.cutoff, def.synth.resonance, def.synth.filterType);
  816. def.synth.filterEnv = filterEnv;
  817. def.synth.pitchEnv = pitchEnv;
  818. }
  819. // sample region and start offset
  820. if (std::isfinite (c.sampleStart) && std::isfinite (c.sampleEnd) && std::isfinite (c.startOffset))
  821. {
  822. const auto start = std::clamp (c.sampleStart, 0.0, 1.0), end = std::clamp (c.sampleEnd, 0.0, 1.0);
  823. if (end > start)
  824. {
  825. def.sampler.regionStart = (float) std::clamp (start + std::clamp (c.startOffset, 0.0, 1.0) * (end - start), 0.0, 1.0);
  826. def.sampler.regionEnd = (float) end;
  827. }
  828. }
  829. // time-stretch: the sample lasts TIME/192 beats × MUL
  830. if (c.stretchTime > 0.0f)
  831. {
  832. def.sampler.stretchBeats = (float) (c.stretchTime / 192.0 * std::pow (2.0, c.stretchMul / 10000.0));
  833. def.sampler.keepPitch = c.stretchMode != 0; // only FL's "Resample" changes the pitch
  834. }
  835. // report: what happened to this channel's generator/sample
  836. if (options.report != nullptr)
  837. {
  838. auto& r = *options.report;
  839. const auto plugin = lowercase (c.pluginName);
  840. if (plugin.empty())
  841. r.missingSamples += ! c.samplePath.empty() && def.samplePath.empty() ? 1 : 0;
  842. else if (plugin == "3x osc" || ((plugin == "directwave" || plugin == "fl keys") && ! def.zones.empty())
  843. || ((plugin == "fruity slicer" || plugin == "slicex") && ! def.samplePath.empty())
  844. || (plugin == "fpc" && ! drumKits.empty() && drumKits.back().first == (int) song.channels.size()))
  845. ++r.converted[c.pluginName];
  846. else if ((plugin == "harmless" && def.instrument != InstrumentKind::harmless) || plugin == "minisynth" || plugin == "fruity dx10" || plugin == "dx10" || plugin == "fruit kick"
  847. || ((plugin == "sytrus" || plugin == "harmor" || plugin == "gms" || plugin == "ogun" || plugin == "autogun" || plugin == "sakura" || plugin == "kepler" || plugin == "boobass" || plugin == "drumpad" || plugin == "poizone" || plugin == "bassdrum"
  848. || plugin == "toxic biohazard" || plugin == "morphine") && adoptedFromPlugin)
  849. || (plugin == "wave traveller" && def.instrument == InstrumentKind::sampler)
  850. || (plugin == "fruity drumsynth live" && def.instrument == InstrumentKind::sampler))
  851. ++r.approximated[c.pluginName];
  852. else if (((plugin == "fruity envelope controller" || plugin == "fruity keyboard controller") && def.instrument == InstrumentKind::controller)
  853. || (plugin == "fruity drumsynth live" && def.instrument == InstrumentKind::drumsynth)
  854. || (plugin == "harmless" && def.instrument == InstrumentKind::harmless))
  855. ++r.converted[c.pluginName];
  856. else if (plugin != "fruity wrapper" && plugin != "fruity keyboard controller" && plugin != "midi out"
  857. && def.instrument == InstrumentKind::synth)
  858. ++r.unsupported[c.pluginName]; // (Keyboard Controller only sends notes to other channels)
  859. }
  860. song.channels.push_back (std::move (def));
  861. }
  862. // Mixer: names, mute/solo, routing and levels from the .flp; enough inserts for all
  863. // routes (minimum 16, like a new project). FL's extra tracks (500/501) are left out.
  864. int highestTrack = 16;
  865. for (const auto& c : song.channels)
  866. highestTrack = std::max (highestTrack, c.mixerTrack);
  867. for (const auto& insert : project.mixer)
  868. if (insert.index < maxMixerTracks)
  869. for (auto target : insert.routes)
  870. if (target < maxMixerTracks && (insert.index > 0 || target > 0))
  871. highestTrack = std::max ({ highestTrack, target, insert.index });
  872. song.mixer = Song::defaultMixer (std::min (highestTrack, maxMixerTracks - 1));
  873. const auto tracks = (int) song.mixer.size();
  874. for (const auto& insert : project.mixer)
  875. {
  876. if (insert.index < 0 || insert.index >= tracks)
  877. continue;
  878. auto& track = song.mixer[(std::size_t) insert.index];
  879. if (insert.index > 0 && ! insert.name.empty())
  880. track.name = insert.name;
  881. if (insert.colour != 0 && insert.colour != 0x485156) // FL's default gray
  882. track.colour = 0xFF000000u | insert.colour;
  883. track.muted = (insert.flags & 0x08) == 0;
  884. track.invertPhase = (insert.flags & 0x01) != 0;
  885. track.swapChannels = (insert.flags & 0x02) != 0;
  886. track.solo = insert.index > 0 && (insert.flags & 0x1000) != 0;
  887. if (insert.index > 0 && insert.hasRoutes)
  888. {
  889. track.toMaster = std::find (insert.routes.begin(), insert.routes.end(), 0) != insert.routes.end();
  890. // The level comes from 0xE1 (below). Without a record, FL templates route every insert to the
  891. // send tracks at the end of the mixer (100+) at level 0; routes to regular inserts are 100%.
  892. for (auto target : insert.routes)
  893. if (target > 0 && target < tracks && target != insert.index)
  894. track.sends.push_back ({ target, target >= 100 ? 0.0f : 1.0f });
  895. }
  896. }
  897. // native FL effects become the similar internal effects (default parameters: the internal
  898. // state of FL plugins is not known); the others are left out
  899. std::map<std::pair<int, int>, std::pair<int, std::string>> effectSlotMap; // (track, FL slot) -> (our effect, FL plugin)
  900. // inputs of each track (REA_rodada22 §1): [itself, the ones routing to it in ascending order (at
  901. // any level; level 0 = sidechain only)]; the index k stored in the plugins points into this list
  902. std::map<int, std::vector<int>> trackInputs;
  903. for (const auto& insert : project.mixer)
  904. if (insert.hasRoutes)
  905. for (const auto target : insert.routes)
  906. if (target > 0 && target != insert.index)
  907. trackInputs[target].push_back (insert.index);
  908. auto sidechainSource = [&] (int track, int k) {
  909. if (k <= 0)
  910. return -1;
  911. auto inputs = trackInputs[track];
  912. std::sort (inputs.begin(), inputs.end());
  913. inputs.erase (std::unique (inputs.begin(), inputs.end()), inputs.end());
  914. inputs.insert (inputs.begin(), track);
  915. return k < (int) inputs.size() && inputs[(std::size_t) k] < tracks ? inputs[(std::size_t) k] : -1;
  916. };
  917. std::map<std::pair<int, int>, decltype (LovePhilterConversion::paramMap)> lovePhilterMaps; // Love Philter automation
  918. for (const auto& insert : project.mixer)
  919. {
  920. if (insert.index < 0 || insert.index >= tracks)
  921. continue;
  922. auto& track = song.mixer[(std::size_t) insert.index];
  923. for (const auto& original : insert.slots)
  924. {
  925. // Patcher with a simple serial chain: the plugins inside become consecutive slots
  926. std::vector<flp::MixerInsert::Slot> expanded { original };
  927. // Fruity Love Philter: the units become parametric EQ + gain/pan (or a parallel container)
  928. if (original.plugin == "Fruity Love Philter" && (int) track.effects.size() < maxEffectSlots)
  929. if (auto conversion = lovePhilterEffects (original.state))
  930. {
  931. const auto first = (int) track.effects.size();
  932. for (auto& fx : conversion->slots)
  933. if ((int) track.effects.size() < maxEffectSlots)
  934. track.effects.push_back (std::move (fx));
  935. effectSlotMap.insert ({ { insert.index, original.index }, { first, original.plugin } });
  936. if (conversion->paramMap)
  937. lovePhilterMaps[{ insert.index, original.index }] = conversion->paramMap;
  938. for (const auto& link : conversion->links) // cutoff envelope/LFO: live automation
  939. if (first + std::max (link.source, link.target) < (int) track.effects.size())
  940. {
  941. Automation a;
  942. a.name = "Love Philter (" + track.name + ")";
  943. a.target = { AutomationTargetKind::effectParam, insert.index, first + link.target, link.param };
  944. a.source = { insert.index, first + link.source, 0 };
  945. a.curve = link.curve;
  946. song.automations.push_back (std::move (a));
  947. }
  948. if (options.report != nullptr)
  949. {
  950. ++options.report->converted["Fruity Love Philter"];
  951. for (const auto& note : conversion->notes)
  952. ++options.report->droppedEffects[note];
  953. }
  954. continue;
  955. }
  956. // Patcher with branches (REA_rodada20 §3.3): the audio graph reduced to series/parallel becomes slots and
  957. // nested parallel containers; splitter nodes enter via the band/bus used
  958. if (lowercase (original.plugin) == "patcher" && (int) track.effects.size() < maxEffectSlots)
  959. if (const auto graph = parsePatcher (original.state); graph && graph->serialChain.empty() && graph->audio)
  960. {
  961. std::function<std::vector<EffectSlot> (const PatcherExpr&, float&)> build = [&] (const PatcherExpr& e, float& gain) {
  962. std::vector<EffectSlot> chain;
  963. gain *= e.gain;
  964. switch (e.kind)
  965. {
  966. case PatcherExpr::Kind::identity: break;
  967. case PatcherExpr::Kind::node:
  968. {
  969. const auto& node = graph->nodes[(std::size_t) e.node];
  970. if (e.bus >= 0)
  971. {
  972. const auto head = patcherBranchHead (node.plugin, node.state, e.bus);
  973. if (! head.valid)
  974. {
  975. if (options.report != nullptr)
  976. ++options.report->droppedEffects["Patcher: bus " + std::to_string (e.bus) + " of " + node.plugin];
  977. break;
  978. }
  979. gain *= head.gain;
  980. if (head.slot)
  981. chain.push_back (*head.slot);
  982. if (! head.note.empty() && options.report != nullptr)
  983. ++options.report->droppedEffects[head.note];
  984. }
  985. else if (auto fx = effectFromFl (node.plugin, node.state, song.bpm); fx && fx->kind != EffectKind::plugin)
  986. chain.push_back (std::move (*fx));
  987. else if (options.report != nullptr)
  988. ++options.report->droppedEffects[node.plugin + " (in Patcher)"];
  989. break;
  990. }
  991. case PatcherExpr::Kind::series:
  992. for (const auto& c : e.children)
  993. for (auto& slot : build (c, gain))
  994. chain.push_back (std::move (slot));
  995. break;
  996. case PatcherExpr::Kind::parallel:
  997. {
  998. auto container = makeEffectSlot (EffectKind::parallel);
  999. for (const auto& c : e.children)
  1000. {
  1001. EffectBranch branch;
  1002. auto branchGain = 1.0f;
  1003. branch.chain = build (c, branchGain);
  1004. branch.gain = std::clamp (branchGain, 0.0f, 4.0f);
  1005. container.branches.push_back (std::move (branch));
  1006. }
  1007. chain.push_back (std::move (container));
  1008. break;
  1009. }
  1010. }
  1011. return chain;
  1012. };
  1013. auto gain = 1.0f;
  1014. auto chain = build (*graph->audio, gain);
  1015. if (std::abs (gain - 1.0f) > 1e-4f)
  1016. {
  1017. auto utility = makeEffectSlot (EffectKind::utility);
  1018. utility.params[0] = gain <= 0.0f ? 0.0f : std::clamp ((float) (20.0 * std::log10 (gain) / 48.0 + 0.5), 0.0f, 1.0f);
  1019. chain.push_back (std::move (utility));
  1020. }
  1021. if ((int) (track.effects.size() + chain.size()) > maxEffectSlots) // doesn't fit: a single-branch container
  1022. {
  1023. auto container = makeEffectSlot (EffectKind::parallel);
  1024. container.branches.push_back ({ std::move (chain), 1.0f });
  1025. chain = { std::move (container) };
  1026. }
  1027. effectSlotMap.insert ({ { insert.index, original.index }, { (int) track.effects.size(), original.plugin } });
  1028. for (auto& slot : chain)
  1029. track.effects.push_back (std::move (slot));
  1030. if (options.report != nullptr)
  1031. ++options.report->converted["Patcher (series/parallel)"];
  1032. continue;
  1033. }
  1034. if (lowercase (original.plugin) == "patcher")
  1035. if (const auto graph = parsePatcher (original.state); graph && ! graph->serialChain.empty())
  1036. {
  1037. expanded.clear();
  1038. for (const auto n : graph->serialChain)
  1039. expanded.push_back ({ original.index, graph->nodes[(std::size_t) n].plugin, graph->nodes[(std::size_t) n].state });
  1040. if (options.report != nullptr)
  1041. ++options.report->converted["Patcher (in series)"];
  1042. }
  1043. for (const auto& slot : expanded)
  1044. {
  1045. if ((int) track.effects.size() >= maxEffectSlots)
  1046. continue;
  1047. ForeignPlugin foreign;
  1048. std::optional<EffectSlot> made;
  1049. const auto wrapped = slot.plugin == "Fruity Wrapper" && parseFlWrapper (slot.state, foreign);
  1050. // old FL saved its own Fruity effects as VST2 inside the wrapper: becomes the internal effect
  1051. if (wrapped && foreign.format == ForeignPlugin::Format::vst2 && effectForFlPlugin (foreign.name))
  1052. made = effectFromFl (foreign.name, {}, song.bpm);
  1053. else if (wrapped)
  1054. {
  1055. // the app swaps in the installed plugin; without it, the slot is removed
  1056. made = makeEffectSlot (EffectKind::plugin);
  1057. made->plugin.name = foreign.name;
  1058. made->plugin.foreign = std::move (foreign);
  1059. }
  1060. else
  1061. made = effectFromFl (slot.plugin, slot.state, song.bpm); // native effect with the saved settings (REA_rodada7)
  1062. if (! made)
  1063. {
  1064. // the ones that don't touch audio (controllers, visualizers, notes) aren't missed
  1065. static const char* silent[] = { "Fruity Peak Controller", "Fruity X-Y Controller", "Control Surface", "Wave Candy",
  1066. "ZGameEditor Visualizer", "Fruity NoteBook 2", "Fruity NoteBook", "Edison",
  1067. "Fruity Formula Controller", "Fruity LSD", "Fruity dB Meter", "Fruity Spectroman" };
  1068. const auto harmless = std::any_of (std::begin (silent), std::end (silent), [&] (const char* n) { return slot.plugin == n; });
  1069. if (options.report != nullptr && slot.plugin != "Fruity Wrapper" && ! harmless)
  1070. ++options.report->droppedEffects[slot.plugin];
  1071. continue;
  1072. }
  1073. auto fx = std::move (*made);
  1074. // sidechain (REA_rodada22 §1): Fruity Limiter (i32 at 0xA4, v ≥ 6; only the compressor detector and only
  1075. // with Comp threshold < 0 dB) and Fruity Compressor (i32 at 0x20, v3)
  1076. if (slot.plugin == "Fruity Limiter" && slot.state.size() >= 0xA8)
  1077. {
  1078. std::int32_t version = 0, k = 0, compThreshold = 1000;
  1079. std::memcpy (&version, slot.state.data(), 4);
  1080. std::memcpy (&k, slot.state.data() + 0xA4, 4);
  1081. std::memcpy (&compThreshold, slot.state.data() + 4 + 8 * 4, 4);
  1082. if (const auto source = sidechainSource (insert.index, k); version >= 6 && source >= 0 && compThreshold < 1000)
  1083. if (auto comp = fruityLimiterCompressor (slot.state))
  1084. {
  1085. const auto enabled = fx.enabled;
  1086. fx = std::move (*comp);
  1087. fx.enabled = enabled;
  1088. fx.sidechain = source;
  1089. if (options.report != nullptr)
  1090. ++options.report->converted["Fruity Limiter (sidechain)"];
  1091. }
  1092. }
  1093. else if (slot.plugin == "Vocodex")
  1094. {
  1095. // ModIn/CarIn index the same inputs list as the sidechains (REA_rodada22 §1)
  1096. if (const auto v = vocodexEffect (slot.state))
  1097. {
  1098. fx.sidechain = sidechainSource (insert.index, v->modIn);
  1099. fx.sidechain2 = sidechainSource (insert.index, v->carIn);
  1100. if (options.report != nullptr)
  1101. for (const auto& note : v->notes)
  1102. ++options.report->droppedEffects[note];
  1103. }
  1104. }
  1105. else if (slot.plugin == "Fruity Compressor" && slot.state.size() >= 0x24 && fx.kind == EffectKind::compressor)
  1106. {
  1107. std::int32_t version = 0, k = 0;
  1108. std::memcpy (&version, slot.state.data(), 4);
  1109. std::memcpy (&k, slot.state.data() + 0x20, 4);
  1110. if (version == 3)
  1111. fx.sidechain = sidechainSource (insert.index, k);
  1112. }
  1113. // slot bypass and dry/wet (0xE1, p = 0x1F00 / 0x1F01)
  1114. for (const auto& control : project.controls)
  1115. if (control.id.isMixer() && control.id.track() == insert.index && control.id.slot() == slot.index)
  1116. {
  1117. if (control.id.param() == 0x1F00)
  1118. fx.enabled = control.value != 0;
  1119. else if (control.id.param() == 0x1F01)
  1120. fx.mix = std::clamp (control.value / 12800.0f, 0.0f, 1.0f);
  1121. }
  1122. effectSlotMap.insert ({ { insert.index, slot.index }, { (int) track.effects.size(), slot.plugin } });
  1123. track.effects.push_back (fx);
  1124. }
  1125. }
  1126. }
  1127. // cycles shouldn't exist in the file; if they do, the send that closes the cycle is dropped
  1128. for (int t = 1; t < tracks; ++t)
  1129. {
  1130. auto sends = std::move (song.mixer[(std::size_t) t].sends);
  1131. song.mixer[(std::size_t) t].sends.clear();
  1132. for (const auto& s : sends)
  1133. song.setRoute (t, s.target, true, s.level);
  1134. }
  1135. for (const auto& control : project.controls)
  1136. {
  1137. if (! control.id.isMixer())
  1138. continue;
  1139. const auto t = control.id.track();
  1140. const auto p = control.id.param();
  1141. if (t < 0 || t >= tracks)
  1142. continue;
  1143. auto& track = song.mixer[(std::size_t) t];
  1144. // FL ranges: volume 0..16000 (12800 = 0 dB), pan ±6400, send 0..16000 (12800 = 100%)
  1145. if (p == flp::ControlId::mixerVolume)
  1146. track.volume = std::clamp (control.value / 16000.0f, 0.0f, 1.0f);
  1147. else if (p == flp::ControlId::mixerPan)
  1148. track.pan = std::clamp (control.value / 6400.0f, -1.0f, 1.0f);
  1149. else if (p == flp::ControlId::mixerStereo)
  1150. track.stereo = std::clamp (control.value / 64.0f, -1.0f, 1.0f);
  1151. else if (p >= flp::ControlId::mixerEqBase && p < flp::ControlId::mixerEqBase + 24 && (p - flp::ControlId::mixerEqBase) % 8 < 3)
  1152. {
  1153. // track EQ: p = 0x1FD0 + group·8 + band (group 0 gain, 1 frequency, 2 width; REA_rodada6 §1)
  1154. const auto group = (p - flp::ControlId::mixerEqBase) / 8;
  1155. const auto band = (std::size_t) ((p - flp::ControlId::mixerEqBase) % 8);
  1156. const auto v = (double) control.value;
  1157. if (group == 0)
  1158. track.eq.gainDb[band] = (float) std::clamp (v * 0.01, -18.0, 18.0);
  1159. else if (group == 1)
  1160. track.eq.hz[band] = (float) std::clamp (10.0 + 159.9 * (std::pow (101.0, v / 65536.0) - 1.0), 10.0, 16000.0);
  1161. else
  1162. track.eq.width[band] = (float) std::clamp (v / 65536.0, 0.0, 1.0);
  1163. }
  1164. else if (p >= flp::ControlId::mixerSendBase && p < flp::ControlId::mixerSendBase + tracks)
  1165. for (auto& send : track.sends)
  1166. if (send.target == p - flp::ControlId::mixerSendBase)
  1167. send.level = std::clamp (control.value / 12800.0f, 0.0f, 1.0f);
  1168. }
  1169. // the FL template routes every insert to the send tracks at level 0; that makes no sound, only wastes CPU
  1170. for (auto& t : song.mixer)
  1171. t.sends.erase (std::remove_if (t.sends.begin(), t.sends.end(), [] (const MixerSend& s) { return s.level <= 0.0f; }),
  1172. t.sends.end());
  1173. const auto filePpq = project.header.ppq > 0 ? (std::int64_t) project.header.ppq : 96;
  1174. auto rescale = [filePpq] (std::int64_t ticks) { return ticks * ppq / filePpq; };
  1175. std::map<int, int> patternMap; // FL index -> our dense index
  1176. for (const auto& src : project.patterns)
  1177. {
  1178. Pattern p;
  1179. p.name = src.name.empty() ? "Pattern " + std::to_string (src.index) : src.name;
  1180. if (src.colour && *src.colour != 0x485156) // FL's default gray becomes an automatic colour
  1181. p.colour = 0xFF000000u | *src.colour;
  1182. for (const auto& n : src.notes)
  1183. {
  1184. const auto it = channelMap.find (n.channel);
  1185. if (it == channelMap.end())
  1186. continue;
  1187. Note note;
  1188. note.start = rescale (n.position);
  1189. // Step notes (length 0) play for one step.
  1190. note.length = n.length > 0 ? rescale (n.length) : ticksPerStep;
  1191. note.channel = it->second;
  1192. note.key = n.key; // FL and MIDI use the same numbering; only the octave name differs
  1193. note.velocity = std::clamp (n.velocity / 128.0f, 0.0f, 1.0f);
  1194. note.pan = std::clamp ((n.pan - 64) / 64.0f, -1.0f, 1.0f);
  1195. note.finePitch = (float) std::clamp ((int) n.finePitch - 120, -120, 120);
  1196. note.muted = n.muted();
  1197. note.slide = n.slide();
  1198. note.porta = n.porta();
  1199. p.notes.push_back (note);
  1200. }
  1201. p.sortNotes();
  1202. if (! p.notes.empty())
  1203. {
  1204. patternMap[src.index] = (int) song.patterns.size();
  1205. song.patterns.push_back (std::move (p));
  1206. }
  1207. }
  1208. // Our target for an FL controlID: the FL slot (0..9, with gaps) becomes our effect's
  1209. // index (effect not imported = no target); internal effect parameter only with the FL-to-ours
  1210. // map (`valueMap` receives the value conversion).
  1211. auto resolveTarget = [&] (flp::ControlId id, std::function<float (float)>& valueMap) {
  1212. auto target = automationTargetFor (id, channelMap, (int) song.mixer.size());
  1213. if (target.kind == AutomationTargetKind::effectParam || target.kind == AutomationTargetKind::effectMix)
  1214. {
  1215. const auto found = effectSlotMap.find ({ target.index, target.slot });
  1216. if (found == effectSlotMap.end())
  1217. target.kind = AutomationTargetKind::none;
  1218. else
  1219. {
  1220. target.slot = found->second.first;
  1221. const auto& fx = song.mixer[(std::size_t) target.index].effects[(std::size_t) target.slot];
  1222. if (target.kind == AutomationTargetKind::effectParam && found->second.second == "Fruity Love Philter")
  1223. {
  1224. const auto map = lovePhilterMaps.find ({ id.track(), id.slot() });
  1225. const auto mapped = map != lovePhilterMaps.end() && map->second ? map->second (target.param) : std::nullopt;
  1226. if (mapped)
  1227. {
  1228. target.slot = found->second.first + std::get<0> (*mapped);
  1229. target.param = std::get<1> (*mapped);
  1230. valueMap = std::get<2> (*mapped);
  1231. }
  1232. else
  1233. target.kind = AutomationTargetKind::none;
  1234. }
  1235. else if (target.kind == AutomationTargetKind::effectParam && fx.kind != EffectKind::plugin)
  1236. {
  1237. if (const auto mapped = effectParamFromFl (found->second.second, target.param))
  1238. {
  1239. target.param = mapped->param;
  1240. valueMap = mapped->convert;
  1241. }
  1242. else
  1243. target.kind = AutomationTargetKind::none;
  1244. }
  1245. }
  1246. }
  1247. return target;
  1248. };
  1249. // Automation clips: one Automation per FL automation channel, with the target from the 0xE3 link.
  1250. std::map<int, int> automationMap; // FL channel -> index into song.automations
  1251. for (const auto& c : project.channels)
  1252. {
  1253. if (c.type != flp::ChannelType::automationClip || c.automation.empty())
  1254. continue;
  1255. Automation a;
  1256. a.name = c.name.empty() ? "Automation " + std::to_string (c.index + 1) : c.name;
  1257. std::function<float (float)> valueMap; // FL normalized value -> ours (effect parameters)
  1258. for (const auto& link : project.automationLinks)
  1259. if (link.channel == c.index)
  1260. {
  1261. a.target = resolveTarget (link.target, valueMap);
  1262. break;
  1263. }
  1264. for (std::size_t i = 0; i < c.automation.size(); ++i)
  1265. {
  1266. const auto& p = c.automation[i];
  1267. const auto tick = (std::int64_t) std::llround (p.position * ppq);
  1268. auto value = (float) std::clamp (p.value, 0.0, 1.0);
  1269. // FL automates tempo from 60 to 180 BPM; our target covers the full tempo range
  1270. if (a.target.kind == AutomationTargetKind::tempo)
  1271. value = valueFromTempo (60.0 + 120.0 * value);
  1272. else if (valueMap)
  1273. value = std::clamp (valueMap (value), 0.0f, 1.0f);
  1274. // FL's curve belongs to the segment ending at the point; ours sits on the left point
  1275. if (i > 0)
  1276. {
  1277. auto& previous = a.points.back();
  1278. if (p.curve == 0 || p.curve == 1) // single/double curve: exponential by tension
  1279. previous.tension = std::clamp (-p.tension, -1.0f, 1.0f);
  1280. else if (p.curve == 2 && tick - previous.tick > 1) // hold: step right before the point
  1281. a.points.push_back ({ tick - 1, previous.value, 0.0f });
  1282. }
  1283. a.points.push_back ({ tick, value, 0.0f });
  1284. }
  1285. automationMap[c.index] = (int) song.automations.size();
  1286. song.automations.push_back (std::move (a));
  1287. }
  1288. // Controller links (REA_rodada14 §7): Peak Controller in a mixer slot -> live automation of the
  1289. // target (the effect output is read every block). Other controllers are still left out.
  1290. for (const auto& link : project.controllerLinks)
  1291. {
  1292. // Envelope Controller on a channel: output k follows articulator k
  1293. if (link.source.isChannel())
  1294. {
  1295. const auto channel = channelMap.find (link.source.channel());
  1296. if (channel == channelMap.end() || song.channels[(std::size_t) channel->second].instrument != InstrumentKind::controller)
  1297. continue;
  1298. Automation a;
  1299. std::function<float (float)> valueMap;
  1300. a.target = resolveTarget (link.target, valueMap);
  1301. if (a.target.kind == AutomationTargetKind::none || a.target.kind == AutomationTargetKind::tempo)
  1302. continue;
  1303. a.name = "Controller (" + song.channels[(std::size_t) channel->second].name + ")";
  1304. a.source.channel = channel->second;
  1305. a.source.output = link.source.param() - flp::ControlId::pluginParamBase;
  1306. if (valueMap)
  1307. for (int i = 0; i <= 32; ++i)
  1308. a.curve.push_back (std::clamp (valueMap ((float) i / 32.0f), 0.0f, 1.0f));
  1309. song.automations.push_back (std::move (a));
  1310. if (options.report != nullptr)
  1311. ++options.report->converted["Channel controller (link)"];
  1312. continue;
  1313. }
  1314. if (! link.source.isMixer() || link.source.track() < 0 || link.source.track() >= (int) song.mixer.size())
  1315. continue;
  1316. // static X-Y Controller / Control Surface: the current value is applied to the target once
  1317. {
  1318. const flp::MixerInsert::Slot* source = nullptr;
  1319. for (const auto& insert : project.mixer)
  1320. if (insert.index == link.source.track())
  1321. for (const auto& slot : insert.slots)
  1322. if (slot.index == link.source.slot())
  1323. source = &slot;
  1324. if (source != nullptr)
  1325. if (const auto value = controllerConstantOutput (source->plugin, source->state, link.source.param() - flp::ControlId::pluginParamBase))
  1326. {
  1327. std::function<float (float)> valueMap;
  1328. const auto target = resolveTarget (link.target, valueMap);
  1329. if (target.kind != AutomationTargetKind::none && target.kind != AutomationTargetKind::tempo
  1330. && song.setTargetValue (target, valueMap ? valueMap (*value) : *value) && options.report != nullptr)
  1331. ++options.report->converted[source->plugin + " (link)"];
  1332. continue;
  1333. }
  1334. }
  1335. const auto found = effectSlotMap.find ({ link.source.track(), link.source.slot() });
  1336. if (found == effectSlotMap.end()
  1337. || song.mixer[(std::size_t) link.source.track()].effects[(std::size_t) found->second.first].kind != EffectKind::peakController)
  1338. continue;
  1339. Automation a;
  1340. std::function<float (float)> valueMap;
  1341. a.target = resolveTarget (link.target, valueMap);
  1342. if (a.target.kind == AutomationTargetKind::none || a.target.kind == AutomationTargetKind::tempo)
  1343. continue;
  1344. a.name = "Peak Controller (" + song.mixer[(std::size_t) link.source.track()].name + ")";
  1345. a.source = { link.source.track(), found->second.first, link.source.param() - flp::ControlId::pluginParamBase };
  1346. if (valueMap)
  1347. for (int i = 0; i <= 32; ++i)
  1348. a.curve.push_back (std::clamp (valueMap ((float) i / 32.0f), 0.0f, 1.0f));
  1349. song.automations.push_back (std::move (a));
  1350. if (options.report != nullptr)
  1351. ++options.report->converted["Peak Controller (link)"];
  1352. }
  1353. // Playlist: all arrangements (the first stays open); pattern, audio and automation clips.
  1354. std::vector<const std::vector<flp::PlaylistTrackInfo>*> importedTracks;
  1355. if (! project.arrangements.empty())
  1356. song.arrangements.clear();
  1357. for (const auto& arrangement : project.arrangements)
  1358. {
  1359. std::vector<Clip> clips;
  1360. for (const auto& item : arrangement.items)
  1361. {
  1362. if (item.length == 0)
  1363. continue;
  1364. if (item.kind == flp::PlaylistItem::Kind::channelClip && automationMap.count (item.index))
  1365. {
  1366. Clip clip;
  1367. clip.kind = ClipKind::automation;
  1368. clip.automation = automationMap[item.index];
  1369. clip.track = item.track;
  1370. clip.start = rescale (item.position);
  1371. clip.length = rescale (item.length);
  1372. // trim in beats (-1 = no trim)
  1373. if (std::isfinite (item.startOffset) && item.startOffset > 0.0f)
  1374. clip.offset = (std::int64_t) std::llround (item.startOffset * ppq);
  1375. clips.push_back (clip);
  1376. continue;
  1377. }
  1378. if (item.kind == flp::PlaylistItem::Kind::channelClip)
  1379. {
  1380. const auto channel = channelMap.find (item.index);
  1381. if (channel == channelMap.end() || song.channels[(std::size_t) channel->second].instrument != InstrumentKind::audioClip)
  1382. continue;
  1383. Clip clip;
  1384. clip.kind = ClipKind::audio;
  1385. clip.channel = channel->second;
  1386. clip.track = item.track;
  1387. clip.start = rescale (item.position);
  1388. clip.length = rescale (item.length);
  1389. // The region start comes in beats or in milliseconds, depending on the clip;
  1390. // we find out by the unit in which (end - start) matches the length.
  1391. const auto beats = (double) item.length / (double) filePpq;
  1392. const auto span = (double) item.endOffset - (double) item.startOffset;
  1393. if (std::isfinite (item.startOffset) && item.startOffset > 0.0f)
  1394. {
  1395. if (std::abs (span - beats) < 0.02 * std::max (1.0, beats))
  1396. clip.offset = (std::int64_t) std::llround (item.startOffset * ppq);
  1397. else if (std::abs (span - beats * 60000.0 / song.bpm) < 0.02 * std::max (1.0, span))
  1398. clip.offset = (std::int64_t) std::llround (item.startOffset / 1000.0 * song.bpm / 60.0 * ppq);
  1399. }
  1400. clips.push_back (clip);
  1401. continue;
  1402. }
  1403. const auto it = patternMap.find (item.index);
  1404. if (it == patternMap.end())
  1405. continue;
  1406. Clip clip;
  1407. clip.pattern = it->second;
  1408. clip.track = item.track;
  1409. clip.start = rescale (item.position);
  1410. clip.length = rescale (item.length);
  1411. clip.offset = item.patternStartTick > 0 ? rescale (item.patternStartTick) : 0;
  1412. clips.push_back (clip);
  1413. }
  1414. std::sort (clips.begin(), clips.end(), [] (const Clip& a, const Clip& b) { return a.start < b.start; });
  1415. Arrangement a;
  1416. a.name = arrangement.name.empty() ? "Arrangement " + std::to_string (song.arrangements.size() + 1) : arrangement.name;
  1417. // markers; type 8 changes the time signature (loop/pause actions become plain markers)
  1418. for (const auto& m : arrangement.markers)
  1419. {
  1420. Marker marker;
  1421. marker.tick = rescale (m.position);
  1422. marker.name = m.name;
  1423. marker.name.erase (0, marker.name.find_first_not_of (' '));
  1424. marker.name.erase (marker.name.find_last_not_of (' ') + 1);
  1425. if (m.type == 8 && m.numerator >= 1 && m.numerator <= 32 && m.denominator >= 1 && m.denominator <= 32)
  1426. {
  1427. marker.numerator = m.numerator;
  1428. marker.denominator = m.denominator;
  1429. }
  1430. // unnamed: the FL marker type (REA_rodada6 §5)
  1431. static const char* typeNames[] = { "", "Loop (marker)", "Skip", "Pause", "Loop", "Start", "Pattern length", "",
  1432. "", "Start recording", "Stop recording", "Loop length", "Key/scale" };
  1433. if (marker.name.empty() && m.type > 0 && m.type < 13 && m.type != 8)
  1434. marker.name = typeNames[m.type];
  1435. a.markers.push_back (std::move (marker));
  1436. }
  1437. std::stable_sort (a.markers.begin(), a.markers.end(), [] (const Marker& x, const Marker& y) { return x.tick < y.tick; });
  1438. importedTracks.push_back (&arrangement.tracks);
  1439. if (song.arrangements.empty())
  1440. song.playlist = std::move (clips); // the first is the current one
  1441. else
  1442. a.clips = std::move (clips);
  1443. song.arrangements.push_back (std::move (a));
  1444. }
  1445. // the .flp doesn't say which arrangement was open; the fullest is usually the song
  1446. {
  1447. int fullest = 0;
  1448. std::size_t most = song.playlist.size();
  1449. for (int i = 1; i < (int) song.arrangements.size(); ++i)
  1450. if (song.arrangements[(std::size_t) i].clips.size() > most)
  1451. {
  1452. most = song.arrangements[(std::size_t) i].clips.size();
  1453. fullest = i;
  1454. }
  1455. song.selectArrangement (fullest);
  1456. // Playlist track names and mute (from the open arrangement)
  1457. if (fullest < (int) importedTracks.size())
  1458. for (const auto& t : *importedTracks[(std::size_t) fullest])
  1459. if (t.index >= 0 && t.index < 500 && (! t.name.empty() || ! t.enabled))
  1460. {
  1461. if ((int) song.playlistTracks.size() <= t.index)
  1462. song.playlistTracks.resize ((std::size_t) t.index + 1);
  1463. song.playlistTracks[(std::size_t) t.index] = { t.name, ! t.enabled };
  1464. }
  1465. }
  1466. if (! song.playlist.empty())
  1467. song.mode = PlayMode::song;
  1468. if (song.patterns.empty())
  1469. song.patterns.emplace_back().name = "Pattern 1";
  1470. // The .flp doesn't say which pattern was open; the fullest is the best starting point.
  1471. for (int i = 0; i < (int) song.patterns.size(); ++i)
  1472. if (song.patterns[(std::size_t) i].notes.size() > song.patterns[(std::size_t) song.currentPattern].notes.size())
  1473. song.currentPattern = i;
  1474. // MIDI Out (REA_rodada16 §1): the channel makes no sound; its notes go to the plugins (Fruity
  1475. // Wrapper) listening on the same MIDI port
  1476. for (const auto& c : project.channels)
  1477. {
  1478. if (lowercase (c.pluginName) != "midi out" || c.pluginState.size() < 28)
  1479. continue;
  1480. const auto from = channelMap.find (c.index);
  1481. if (from == channelMap.end())
  1482. continue;
  1483. std::int32_t port = -1;
  1484. std::memcpy (&port, c.pluginState.data() + 24, 4);
  1485. auto& source = song.channels[(std::size_t) from->second];
  1486. source.muted = true;
  1487. for (int target = 0; target < (int) song.channels.size(); ++target)
  1488. {
  1489. const auto& t = song.channels[(std::size_t) target];
  1490. if (target == from->second || port < 0 || t.plugin.foreign.midiInPort != port)
  1491. continue;
  1492. for (auto& pattern : song.patterns)
  1493. {
  1494. const auto count = pattern.notes.size();
  1495. for (std::size_t n = 0; n < count; ++n)
  1496. if (pattern.notes[n].channel == from->second)
  1497. {
  1498. auto copy = pattern.notes[n];
  1499. copy.channel = target;
  1500. pattern.notes.push_back (copy);
  1501. }
  1502. }
  1503. }
  1504. }
  1505. // FPC kits: one channel per pad (last to first, so indices don't shift)
  1506. for (auto it = drumKits.rbegin(); it != drumKits.rend(); ++it)
  1507. splitDrumChannel (song, it->first, it->second);
  1508. return song;
  1509. }
  1510. } // namespace lynx