FlpImport.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. #include "core/FlpImport.h"
  2. #include "core/Effects.h"
  3. #include "core/SynthPresets.h"
  4. #include <algorithm>
  5. #include <cctype>
  6. #include <cmath>
  7. #include <map>
  8. namespace lynx
  9. {
  10. namespace
  11. {
  12. bool contains (const std::string& haystack, const char* needle)
  13. {
  14. return haystack.find (needle) != std::string::npos;
  15. }
  16. std::string lowercase (std::string s)
  17. {
  18. std::transform (s.begin(), s.end(), s.begin(), [] (unsigned char c) { return (char) std::tolower (c); });
  19. return s;
  20. }
  21. } // namespace
  22. InstrumentKind guessInstrument (const std::string& channelName, flp::ChannelType type)
  23. {
  24. const auto name = lowercase (channelName);
  25. if (type == flp::ChannelType::sampler || type == flp::ChannelType::unknown)
  26. {
  27. if (contains (name, "kick") || contains (name, "bd") || contains (name, "808"))
  28. return InstrumentKind::kick;
  29. if (contains (name, "snare") || contains (name, "snr") || contains (name, "rim"))
  30. return InstrumentKind::snare;
  31. if (contains (name, "clap") || contains (name, "snap"))
  32. return InstrumentKind::clap;
  33. if (contains (name, "hat") || contains (name, "hh") || contains (name, "ride") || contains (name, "cym")
  34. || contains (name, "crash") || contains (name, "shaker") || contains (name, "perc") || contains (name, "tamb"))
  35. return InstrumentKind::hat;
  36. }
  37. return InstrumentKind::synth;
  38. }
  39. std::string resolveFlPath (const std::string& flPath, const FlPathRoots& roots)
  40. {
  41. const std::pair<const char*, const std::string*> variables[] = {
  42. { "%FLStudioFactoryData%", &roots.factoryData },
  43. { "%FLStudioUserData%", &roots.userData },
  44. { "%FLStudioData%", &roots.data },
  45. };
  46. for (const auto& [name, root] : variables)
  47. {
  48. const std::string variable (name);
  49. if (flPath.compare (0, variable.size(), variable) == 0)
  50. return root->empty() ? std::string() : *root + flPath.substr (variable.size());
  51. }
  52. return flPath;
  53. }
  54. std::optional<EffectKind> effectForFlPlugin (const std::string& name)
  55. {
  56. static const std::pair<const char*, EffectKind> table[] = {
  57. { "Fruity Parametric EQ 2", EffectKind::eq }, { "Fruity Parametric EQ", EffectKind::eq }, { "Fruity 7 Band EQ", EffectKind::eq },
  58. { "Fruity Limiter", EffectKind::limiter }, { "Maximus", EffectKind::limiter }, { "Fruity Soft Clipper", EffectKind::distortion },
  59. { "Fruity Reeverb 2", EffectKind::reverb }, { "Fruity Reeverb", EffectKind::reverb }, { "LuxeVerb", EffectKind::reverb },
  60. { "Fruity Delay 3", EffectKind::delay }, { "Fruity Delay 2", EffectKind::delay }, { "Fruity Delay Bank", EffectKind::delay },
  61. { "Fruity Delay", EffectKind::delay }, { "Fruity Compressor", EffectKind::compressor },
  62. { "Fruity Multiband Compressor", EffectKind::compressor }, { "Soundgoodizer", EffectKind::compressor },
  63. { "Fruity WaveShaper", EffectKind::distortion }, { "Fruity Fast Dist", EffectKind::distortion },
  64. { "Fruity Blood Overdrive", EffectKind::distortion }, { "Distructor", EffectKind::distortion },
  65. { "Fruity Flangus", EffectKind::chorus }, { "Fruity Chorus", EffectKind::chorus }, { "Hyper Chorus", EffectKind::chorus },
  66. { "Vintage Chorus", EffectKind::chorus }, { "Fruity Flanger", EffectKind::chorus },
  67. { "Fruity Love Philter", EffectKind::filter }, { "Fruity Filter", EffectKind::filter }, { "Fruity Fast LP", EffectKind::filter },
  68. };
  69. for (const auto& [plugin, kind] : table)
  70. if (name == plugin)
  71. return kind;
  72. return std::nullopt;
  73. }
  74. AutomationTarget automationTargetFor (flp::ControlId id, const std::map<int, int>& channelMap, int mixerTracks)
  75. {
  76. AutomationTarget t;
  77. if (id.isTempo())
  78. {
  79. t.kind = AutomationTargetKind::tempo;
  80. return t;
  81. }
  82. if (id.isChannel())
  83. {
  84. const auto channel = channelMap.find (id.channel());
  85. if (channel == channelMap.end())
  86. return t;
  87. t.index = channel->second;
  88. const auto p = id.param();
  89. if (p == 0)
  90. t.kind = AutomationTargetKind::channelVolume;
  91. else if (p == 1)
  92. t.kind = AutomationTargetKind::channelPan;
  93. else if (p >= flp::ControlId::pluginParamBase)
  94. {
  95. t.kind = AutomationTargetKind::channelParam;
  96. t.param = p - flp::ControlId::pluginParamBase;
  97. }
  98. return t;
  99. }
  100. if (id.isMixer() && id.track() >= 0 && id.track() < mixerTracks)
  101. {
  102. t.index = id.track();
  103. const auto p = id.param();
  104. if (p == flp::ControlId::mixerVolume)
  105. t.kind = AutomationTargetKind::mixerVolume;
  106. else if (p == flp::ControlId::mixerPan)
  107. t.kind = AutomationTargetKind::mixerPan;
  108. else if (p >= flp::ControlId::pluginParamBase)
  109. {
  110. t.kind = AutomationTargetKind::effectParam;
  111. t.slot = id.slot();
  112. t.param = p - flp::ControlId::pluginParamBase;
  113. }
  114. }
  115. return t;
  116. }
  117. bool synthFrom3xOsc (const std::vector<std::uint8_t>& state, SynthSettings& synth)
  118. {
  119. // versão 10/11: 20 parâmetros + 4 bools (80 B); 12+: 21 parâmetros + 4 bools (+ HQ)
  120. if (state.size() < 84)
  121. return false;
  122. auto i32 = [&] (std::size_t offset) {
  123. return (std::int32_t) ((std::uint32_t) state[offset] | ((std::uint32_t) state[offset + 1] << 8)
  124. | ((std::uint32_t) state[offset + 2] << 16) | ((std::uint32_t) state[offset + 3] << 24));
  125. };
  126. const auto version = i32 (0);
  127. if (version < 10 || version > 64)
  128. return false;
  129. // parâmetro i fica em 0x04 + 4i; (i + 1) = 7·osc + campo, campos [mix, pan, shape, coarse, fine, spo, detune]
  130. auto param = [&] (int osc, int field) { return i32 ((std::size_t) (4 + 4 * (7 * osc + field - 1))); };
  131. const auto boolsAt = version >= 12 ? (std::size_t) 0x58 : (std::size_t) 0x54;
  132. const bool am = version >= 11 && state.size() > boolsAt + 3 && state[boolsAt + 3] != 0;
  133. // níveis (§2.2): o osc 3 leva mix3/128, o osc 2 uma parte do resto, o osc 1 o que sobra
  134. const auto g3 = std::clamp (param (2, 0), 0, 128) / 128.0f;
  135. const auto rest = am ? 1.0f : 1.0f - g3;
  136. const auto g2 = rest * std::clamp (param (1, 0), 0, 128) / 128.0f;
  137. const std::array<float, 3> levels { std::max (0.0f, rest - g2), g2, am ? 0.0f : g3 }; // AM ainda não: osc 3 mudo
  138. for (int o = 0; o < 3; ++o)
  139. {
  140. auto& osc = synth.osc[(std::size_t) o];
  141. switch (param (o, 2))
  142. {
  143. case 0: osc.wave = Waveform::sine; break;
  144. case 1: osc.wave = Waveform::triangle; break;
  145. case 2: osc.wave = Waveform::square; break;
  146. case 5: osc.wave = Waveform::noise; break;
  147. default: osc.wave = Waveform::saw; break; // 3 serra, 4 serra arredondada, 6 custom sem sample
  148. }
  149. const auto coarse = std::clamp (param (o, 3), -24, 24);
  150. osc.octave = coarse / 12; // trunca em direção a zero; o resto vira semitons
  151. osc.semitones = coarse - osc.octave * 12;
  152. // o stereo detune só soa no canal direito: metade dele vale como desafinação média
  153. 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);
  154. osc.pan = std::clamp (param (o, 1), -64, 64) / 64.0f;
  155. osc.level = levels[(std::size_t) o];
  156. }
  157. return true;
  158. }
  159. void synthFilterFromChannel (int modX, int modY, int type, float& cutoffHz, float& resonance)
  160. {
  161. constexpr double twoPi = 6.283185307179586;
  162. const auto x = std::clamp (modX / 256.0, 0.0, 1.0);
  163. const auto r = std::clamp (modY / 256.0, 0.0, 1.0);
  164. auto fromQ = [] (double q) { return (float) std::clamp ((2.0 - 1.0 / q) / 1.9, 0.0, 1.0); }; // o SVF do synth: k = 1/Q
  165. double hz = 20000.0;
  166. resonance = 0.0f;
  167. switch (type)
  168. {
  169. case 0: // Fast LP: 1 polo + realimentação; aberto com Mod X no máximo e sem ressonância
  170. {
  171. if (x >= 1.0 && r <= 0.0)
  172. break;
  173. const auto c = std::min ((std::pow (601.0, x) - 1.0) / 600.0, 0.999);
  174. hz = x >= 1.0 ? 20000.0 : -44100.0 / twoPi * std::log (1.0 - c);
  175. resonance = (float) (r * 0.9); // aproximação: a realimentação cresce com Mod Y
  176. break;
  177. }
  178. case 1:
  179. case 5: // biquad LP (LPx2 = o mesmo duas vezes)
  180. hz = ((std::pow (51.0, x) - 1.0) * 0.0596 + 0.02) * 44100.0 / twoPi;
  181. resonance = fromQ (r <= 0.0 ? 0.1 : (std::pow (51.0, 0.625 * r) - 1.0) * 0.4 + 0.1);
  182. break;
  183. case 6:
  184. case 7: // SVF de Chamberlin
  185. {
  186. const auto f = std::min (1.0, (std::pow (26.0, x) - 1.0) * 0.04);
  187. hz = 44100.0 / (twoPi / 2.0) * std::asin (f / 2.0);
  188. const auto d = r <= 0.0 ? 1.0 : (r < 1.0 ? 1.0 - 0.8 * r : 0.2);
  189. resonance = fromQ (1.0 / d);
  190. break;
  191. }
  192. default: break; // BP/HP/BS: o synth só tem passa-baixas, melhor deixar aberto
  193. }
  194. cutoffHz = (float) std::clamp (hz, 20.0, 20000.0);
  195. }
  196. Song importFlp (const flp::Project& project, const FlpImportOptions& options)
  197. {
  198. Song song;
  199. song.bpm = project.tempo > 0.0 ? project.tempo : 140.0;
  200. song.beatsPerBar = std::clamp (project.beatsPerBar, 1, 32);
  201. song.swing = std::clamp (project.swing / 128.0f, 0.0f, 1.0f);
  202. // Canais do FL podem ter índices esparsos; mapeamos para índices densos.
  203. std::map<int, int> channelMap;
  204. for (const auto& c : project.channels)
  205. {
  206. // clips de automação viram Song::automations (mais abaixo), não canais
  207. if (c.type == flp::ChannelType::automationClip)
  208. continue;
  209. channelMap[c.index] = (int) song.channels.size();
  210. ChannelDef def;
  211. def.name = c.name.empty() ? "Canal " + std::to_string (c.index + 1) : c.name;
  212. def.instrument = guessInstrument (def.name, c.type);
  213. // sintetizador do FL que vira o synth interno: um preset que combine com o nome
  214. if (def.instrument == InstrumentKind::synth)
  215. def.synth = presetForChannelName (def.name);
  216. const auto isAudioClip = c.type == flp::ChannelType::audioClip;
  217. if ((c.type == flp::ChannelType::sampler || isAudioClip) && ! c.samplePath.empty() && options.fileExists)
  218. {
  219. const auto path = resolveFlPath (c.samplePath, options.roots);
  220. if (! path.empty() && options.fileExists (path))
  221. {
  222. def.instrument = isAudioClip ? InstrumentKind::audioClip : InstrumentKind::sampler;
  223. def.samplePath = path;
  224. }
  225. }
  226. if (isAudioClip && def.instrument != InstrumentKind::audioClip)
  227. def.instrument = InstrumentKind::audioClip; // sem arquivo: fica mudo, mas o clip continua na playlist
  228. def.mixerTrack = std::clamp (c.mixerTrack, 0, maxMixerTracks - 1);
  229. if (c.colour != 0)
  230. def.colour = 0xFF000000u | c.colour;
  231. if (c.hasLevels)
  232. {
  233. def.volume = std::clamp (c.volume / 12800.0f, 0.0f, 1.0f); // mesma curva (channelGain)
  234. def.pan = std::clamp ((c.pan - 6400) / 6400.0f, -1.0f, 1.0f);
  235. def.sampler.pitch = std::clamp (c.pitchCents / 100.0f, -24.0f, 24.0f);
  236. }
  237. // nota-raiz do sample: o nosso sampler toca na altura original em C5 (60)
  238. if (c.rootNote >= 0 && c.rootNote <= 127)
  239. def.sampler.pitch = std::clamp (def.sampler.pitch + (float) (60 - c.rootNote), -24.0f, 24.0f);
  240. def.swingMix = std::clamp (c.swingMix / 128.0f, 0.0f, 1.0f);
  241. def.cutGroup = c.cutGroup;
  242. def.cutBy = c.cutBy;
  243. // "cut itself" (grupo == cut by) e canal mono viram o "cut" do sampler
  244. if ((c.cutGroup != 0 && c.cutGroup == c.cutBy) || c.maxVoices == 1)
  245. def.sampler.cut = true;
  246. // envelope de volume (registro 1 do 0xDA) -> ADSR do sampler
  247. const auto& volumeEnvelope = c.envelopes[1];
  248. const auto hasVolumeEnvelope = volumeEnvelope.present && volumeEnvelope.enabled;
  249. if (hasVolumeEnvelope)
  250. {
  251. const auto& env = volumeEnvelope;
  252. const auto beats = (env.flags & 1) != 0; // sincronizado com o tempo: unidades em tempos
  253. auto seconds = [&] (int v) {
  254. const auto t = flp::Channel::envelopeTime (v);
  255. return (float) (beats ? t * 2.0 * 60.0 / song.bpm : t); // 0,128 tempo em vez de 0,064 s
  256. };
  257. def.sampler.attack = std::clamp (seconds (env.attack), 0.0f, 2.0f);
  258. def.sampler.decay = std::clamp (seconds (env.decay), 0.0f, 10.0f);
  259. def.sampler.sustain = std::clamp (env.sustain / 128.0f, 0.0f, 1.0f);
  260. def.sampler.release = std::clamp (std::max (seconds (env.release), 0.002f), 0.0f, 4.0f); // envelope ligado: a nota acaba
  261. }
  262. // filtro do canal (Mod X/Y + tipo do 0xDB) vale para o sampler também
  263. synthFilterFromChannel (c.modX, c.modY, c.filterType, def.sampler.cutoff, def.sampler.resonance);
  264. // 3x Osc: osciladores do estado do plugin; envelope e filtro vêm do canal (REA_rodada4)
  265. if (def.instrument == InstrumentKind::synth && c.pluginName == "3x Osc" && synthFrom3xOsc (c.pluginState, def.synth))
  266. {
  267. if (hasVolumeEnvelope)
  268. {
  269. def.synth.attack = def.sampler.attack;
  270. def.synth.decay = def.sampler.decay;
  271. def.synth.sustain = def.sampler.sustain;
  272. def.synth.release = def.sampler.release;
  273. }
  274. else
  275. {
  276. // sem envelope o FL toca a nota como um portão, só com um declique curto
  277. def.synth.attack = 0.002f;
  278. def.synth.decay = 0.0f;
  279. def.synth.sustain = 1.0f;
  280. def.synth.release = 0.02f;
  281. }
  282. synthFilterFromChannel (c.modX, c.modY, c.filterType, def.synth.cutoff, def.synth.resonance);
  283. }
  284. // trecho do sample e start offset
  285. if (std::isfinite (c.sampleStart) && std::isfinite (c.sampleEnd) && std::isfinite (c.startOffset))
  286. {
  287. const auto start = std::clamp (c.sampleStart, 0.0, 1.0), end = std::clamp (c.sampleEnd, 0.0, 1.0);
  288. if (end > start)
  289. {
  290. def.sampler.regionStart = (float) std::clamp (start + std::clamp (c.startOffset, 0.0, 1.0) * (end - start), 0.0, 1.0);
  291. def.sampler.regionEnd = (float) end;
  292. }
  293. }
  294. // time-stretch: o sample dura TIME/192 tempos × MUL
  295. if (c.stretchTime > 0.0f)
  296. {
  297. def.sampler.stretchBeats = (float) (c.stretchTime / 192.0 * std::pow (2.0, c.stretchMul / 10000.0));
  298. def.sampler.keepPitch = c.stretchMode != 0; // só o "Resample" do FL muda a altura
  299. }
  300. song.channels.push_back (std::move (def));
  301. }
  302. // Mixer: nomes, mute/solo, roteamento e níveis do .flp; inserts suficientes para todas as
  303. // rotas (mínimo 16, como um projeto novo). As trilhas extras do FL (500/501) ficam de fora.
  304. int highestTrack = 16;
  305. for (const auto& c : song.channels)
  306. highestTrack = std::max (highestTrack, c.mixerTrack);
  307. for (const auto& insert : project.mixer)
  308. if (insert.index < maxMixerTracks)
  309. for (auto target : insert.routes)
  310. if (target < maxMixerTracks && (insert.index > 0 || target > 0))
  311. highestTrack = std::max ({ highestTrack, target, insert.index });
  312. song.mixer = Song::defaultMixer (std::min (highestTrack, maxMixerTracks - 1));
  313. const auto tracks = (int) song.mixer.size();
  314. for (const auto& insert : project.mixer)
  315. {
  316. if (insert.index < 0 || insert.index >= tracks)
  317. continue;
  318. auto& track = song.mixer[(std::size_t) insert.index];
  319. if (insert.index > 0 && ! insert.name.empty())
  320. track.name = insert.name;
  321. if (insert.colour != 0 && insert.colour != 0x485156) // o cinza padrão do FL
  322. track.colour = 0xFF000000u | insert.colour;
  323. track.muted = (insert.flags & 0x08) == 0;
  324. track.invertPhase = (insert.flags & 0x01) != 0;
  325. track.swapChannels = (insert.flags & 0x02) != 0;
  326. track.solo = insert.index > 0 && (insert.flags & 0x1000) != 0;
  327. if (insert.index > 0 && insert.hasRoutes)
  328. {
  329. track.toMaster = std::find (insert.routes.begin(), insert.routes.end(), 0) != insert.routes.end();
  330. // O nível vem do 0xE1 (abaixo). Sem registro, os templates do FL ligam todo insert às
  331. // trilhas de send do fim do mixer (100+) com nível 0; rotas para inserts comuns valem 100%.
  332. for (auto target : insert.routes)
  333. if (target > 0 && target < tracks && target != insert.index)
  334. track.sends.push_back ({ target, target >= 100 ? 0.0f : 1.0f });
  335. }
  336. }
  337. // efeitos nativos do FL viram os efeitos internos parecidos (parâmetros no padrão: o estado
  338. // interno dos plugins do FL não é conhecido); os outros ficam de fora
  339. for (const auto& insert : project.mixer)
  340. {
  341. if (insert.index < 0 || insert.index >= tracks)
  342. continue;
  343. auto& track = song.mixer[(std::size_t) insert.index];
  344. for (const auto& slot : insert.slots)
  345. {
  346. const auto kind = effectForFlPlugin (slot.plugin);
  347. if (! kind || (int) track.effects.size() >= maxEffectSlots)
  348. continue;
  349. auto fx = makeEffectSlot (*kind);
  350. if (*kind == EffectKind::filter)
  351. fx.params[1] = 1.0f; // aberto: sem os ajustes do FL, melhor não abafar
  352. if (slot.plugin == "Fruity Soft Clipper")
  353. fx.params[0] = 0.15f; // drive baixo
  354. // bypass e dry/wet do slot (0xE1, p = 0x1F00 / 0x1F01)
  355. for (const auto& control : project.controls)
  356. if (control.id.isMixer() && control.id.track() == insert.index && control.id.slot() == slot.index)
  357. {
  358. if (control.id.param() == 0x1F00)
  359. fx.enabled = control.value != 0;
  360. else if (control.id.param() == 0x1F01)
  361. fx.mix = std::clamp (control.value / 12800.0f, 0.0f, 1.0f);
  362. }
  363. track.effects.push_back (fx);
  364. }
  365. }
  366. // ciclos não deveriam existir no arquivo; se existirem, o envio que fecha o ciclo cai
  367. for (int t = 1; t < tracks; ++t)
  368. {
  369. auto sends = std::move (song.mixer[(std::size_t) t].sends);
  370. song.mixer[(std::size_t) t].sends.clear();
  371. for (const auto& s : sends)
  372. song.setRoute (t, s.target, true, s.level);
  373. }
  374. for (const auto& control : project.controls)
  375. {
  376. if (! control.id.isMixer())
  377. continue;
  378. const auto t = control.id.track();
  379. const auto p = control.id.param();
  380. if (t < 0 || t >= tracks)
  381. continue;
  382. auto& track = song.mixer[(std::size_t) t];
  383. // faixas do FL: volume 0..16000 (12800 = 0 dB), pan ±6400, envio 0..16000 (12800 = 100%)
  384. if (p == flp::ControlId::mixerVolume)
  385. track.volume = std::clamp (control.value / 16000.0f, 0.0f, 1.0f);
  386. else if (p == flp::ControlId::mixerPan)
  387. track.pan = std::clamp (control.value / 6400.0f, -1.0f, 1.0f);
  388. else if (p == flp::ControlId::mixerStereo)
  389. track.stereo = std::clamp (control.value / 64.0f, -1.0f, 1.0f);
  390. else if (p >= flp::ControlId::mixerSendBase && p < flp::ControlId::mixerSendBase + tracks)
  391. for (auto& send : track.sends)
  392. if (send.target == p - flp::ControlId::mixerSendBase)
  393. send.level = std::clamp (control.value / 12800.0f, 0.0f, 1.0f);
  394. }
  395. // o template do FL liga todo insert às trilhas de send com nível 0; isso não soa, só gasta CPU
  396. for (auto& t : song.mixer)
  397. t.sends.erase (std::remove_if (t.sends.begin(), t.sends.end(), [] (const MixerSend& s) { return s.level <= 0.0f; }),
  398. t.sends.end());
  399. const auto filePpq = project.header.ppq > 0 ? (std::int64_t) project.header.ppq : 96;
  400. auto rescale = [filePpq] (std::int64_t ticks) { return ticks * ppq / filePpq; };
  401. std::map<int, int> patternMap; // índice no FL -> índice denso nosso
  402. for (const auto& src : project.patterns)
  403. {
  404. Pattern p;
  405. p.name = src.name.empty() ? "Pattern " + std::to_string (src.index) : src.name;
  406. if (src.colour && *src.colour != 0x485156) // o cinza padrão do FL vira cor automática
  407. p.colour = 0xFF000000u | *src.colour;
  408. for (const auto& n : src.notes)
  409. {
  410. const auto it = channelMap.find (n.channel);
  411. if (it == channelMap.end())
  412. continue;
  413. Note note;
  414. note.start = rescale (n.position);
  415. // Notas de step (duração 0) tocam por um step.
  416. note.length = n.length > 0 ? rescale (n.length) : ticksPerStep;
  417. note.channel = it->second;
  418. note.key = n.key; // FL e MIDI usam a mesma numeração; só o nome da oitava difere
  419. note.velocity = std::clamp (n.velocity / 128.0f, 0.0f, 1.0f);
  420. note.pan = std::clamp ((n.pan - 64) / 64.0f, -1.0f, 1.0f);
  421. note.finePitch = (float) std::clamp ((int) n.finePitch - 120, -120, 120);
  422. note.muted = n.muted();
  423. note.slide = n.slide();
  424. p.notes.push_back (note);
  425. }
  426. p.sortNotes();
  427. if (! p.notes.empty())
  428. {
  429. patternMap[src.index] = (int) song.patterns.size();
  430. song.patterns.push_back (std::move (p));
  431. }
  432. }
  433. // Clips de automação: um Automation por canal de automação do FL, com o alvo do link 0xE3.
  434. std::map<int, int> automationMap; // canal do FL -> índice em song.automations
  435. for (const auto& c : project.channels)
  436. {
  437. if (c.type != flp::ChannelType::automationClip || c.automation.empty())
  438. continue;
  439. Automation a;
  440. a.name = c.name.empty() ? "Automação " + std::to_string (c.index + 1) : c.name;
  441. for (const auto& link : project.automationLinks)
  442. if (link.channel == c.index)
  443. {
  444. a.target = automationTargetFor (link.target, channelMap, (int) song.mixer.size());
  445. break;
  446. }
  447. for (std::size_t i = 0; i < c.automation.size(); ++i)
  448. {
  449. const auto& p = c.automation[i];
  450. const auto tick = (std::int64_t) std::llround (p.position * ppq);
  451. auto value = (float) std::clamp (p.value, 0.0, 1.0);
  452. // o FL automatiza o tempo de 60 a 180 BPM; o nosso alvo cobre a faixa inteira do andamento
  453. if (a.target.kind == AutomationTargetKind::tempo)
  454. value = valueFromTempo (60.0 + 120.0 * value);
  455. // a curva do FL é do trecho que termina no ponto; a nossa fica no ponto da esquerda
  456. if (i > 0)
  457. {
  458. auto& previous = a.points.back();
  459. if (p.curve == 0 || p.curve == 1) // single/double curve: exponencial pela tensão
  460. previous.tension = std::clamp (-p.tension, -1.0f, 1.0f);
  461. else if (p.curve == 2 && tick - previous.tick > 1) // hold: degrau logo antes do ponto
  462. a.points.push_back ({ tick - 1, previous.value, 0.0f });
  463. }
  464. a.points.push_back ({ tick, value, 0.0f });
  465. }
  466. automationMap[c.index] = (int) song.automations.size();
  467. song.automations.push_back (std::move (a));
  468. }
  469. // Playlist: todos os arrangements (o primeiro fica aberto); clips de pattern, de áudio e de automação.
  470. std::vector<const std::vector<flp::PlaylistTrackInfo>*> importedTracks;
  471. if (! project.arrangements.empty())
  472. song.arrangements.clear();
  473. for (const auto& arrangement : project.arrangements)
  474. {
  475. std::vector<Clip> clips;
  476. for (const auto& item : arrangement.items)
  477. {
  478. if (item.length == 0)
  479. continue;
  480. if (item.kind == flp::PlaylistItem::Kind::channelClip && automationMap.count (item.index))
  481. {
  482. Clip clip;
  483. clip.kind = ClipKind::automation;
  484. clip.automation = automationMap[item.index];
  485. clip.track = item.track;
  486. clip.start = rescale (item.position);
  487. clip.length = rescale (item.length);
  488. // recorte em tempos (-1 = sem recorte)
  489. if (std::isfinite (item.startOffset) && item.startOffset > 0.0f)
  490. clip.offset = (std::int64_t) std::llround (item.startOffset * ppq);
  491. clips.push_back (clip);
  492. continue;
  493. }
  494. if (item.kind == flp::PlaylistItem::Kind::channelClip)
  495. {
  496. const auto channel = channelMap.find (item.index);
  497. if (channel == channelMap.end() || song.channels[(std::size_t) channel->second].instrument != InstrumentKind::audioClip)
  498. continue;
  499. Clip clip;
  500. clip.kind = ClipKind::audio;
  501. clip.channel = channel->second;
  502. clip.track = item.track;
  503. clip.start = rescale (item.position);
  504. clip.length = rescale (item.length);
  505. // O início do trecho vem em tempos ou em milissegundos, conforme o clip;
  506. // descobrimos pela unidade em que (fim - início) bate com a duração.
  507. const auto beats = (double) item.length / (double) filePpq;
  508. const auto span = (double) item.endOffset - (double) item.startOffset;
  509. if (std::isfinite (item.startOffset) && item.startOffset > 0.0f)
  510. {
  511. if (std::abs (span - beats) < 0.02 * std::max (1.0, beats))
  512. clip.offset = (std::int64_t) std::llround (item.startOffset * ppq);
  513. else if (std::abs (span - beats * 60000.0 / song.bpm) < 0.02 * std::max (1.0, span))
  514. clip.offset = (std::int64_t) std::llround (item.startOffset / 1000.0 * song.bpm / 60.0 * ppq);
  515. }
  516. clips.push_back (clip);
  517. continue;
  518. }
  519. const auto it = patternMap.find (item.index);
  520. if (it == patternMap.end())
  521. continue;
  522. Clip clip;
  523. clip.pattern = it->second;
  524. clip.track = item.track;
  525. clip.start = rescale (item.position);
  526. clip.length = rescale (item.length);
  527. clip.offset = item.patternStartTick > 0 ? rescale (item.patternStartTick) : 0;
  528. clips.push_back (clip);
  529. }
  530. std::sort (clips.begin(), clips.end(), [] (const Clip& a, const Clip& b) { return a.start < b.start; });
  531. Arrangement a;
  532. a.name = arrangement.name.empty() ? "Arrangement " + std::to_string (song.arrangements.size() + 1) : arrangement.name;
  533. importedTracks.push_back (&arrangement.tracks);
  534. if (song.arrangements.empty())
  535. song.playlist = std::move (clips); // o primeiro é o atual
  536. else
  537. a.clips = std::move (clips);
  538. song.arrangements.push_back (std::move (a));
  539. }
  540. // o .flp não diz qual arrangement estava aberto; o mais cheio costuma ser a música
  541. {
  542. int fullest = 0;
  543. std::size_t most = song.playlist.size();
  544. for (int i = 1; i < (int) song.arrangements.size(); ++i)
  545. if (song.arrangements[(std::size_t) i].clips.size() > most)
  546. {
  547. most = song.arrangements[(std::size_t) i].clips.size();
  548. fullest = i;
  549. }
  550. song.selectArrangement (fullest);
  551. // nomes e mute das trilhas da Playlist (do arrangement aberto)
  552. if (fullest < (int) importedTracks.size())
  553. for (const auto& t : *importedTracks[(std::size_t) fullest])
  554. if (t.index >= 0 && t.index < 500 && (! t.name.empty() || ! t.enabled))
  555. {
  556. if ((int) song.playlistTracks.size() <= t.index)
  557. song.playlistTracks.resize ((std::size_t) t.index + 1);
  558. song.playlistTracks[(std::size_t) t.index] = { t.name, ! t.enabled };
  559. }
  560. }
  561. if (! song.playlist.empty())
  562. song.mode = PlayMode::song;
  563. if (song.patterns.empty())
  564. song.patterns.emplace_back().name = "Pattern 1";
  565. // O .flp não diz qual pattern estava aberta; a mais cheia é o melhor ponto de partida.
  566. for (int i = 0; i < (int) song.patterns.size(); ++i)
  567. if (song.patterns[(std::size_t) i].notes.size() > song.patterns[(std::size_t) song.currentPattern].notes.size())
  568. song.currentPattern = i;
  569. return song;
  570. }
  571. } // namespace lynx