| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732 |
- #include "core/FlpImport.h"
- #include "core/DrumSynthLive.h"
- #include "core/Harmless.h"
- #include "core/HarmlessFx.h"
- #include "core/PhysicalModels.h"
- #include "core/Effects.h"
- #include "core/FlEffects.h"
- #include "core/FlPatcher.h"
- #include "core/FlSamplers.h"
- #include "core/FlSynths.h"
- #include "core/FlWrapper.h"
- #include "core/SynthPresets.h"
- #include <algorithm>
- #include <cstring>
- #include <cctype>
- #include <cmath>
- #include <map>
- namespace lynx
- {
- namespace
- {
- bool contains (const std::string& haystack, const char* needle)
- {
- return haystack.find (needle) != std::string::npos;
- }
- std::string lowercase (std::string s)
- {
- std::transform (s.begin(), s.end(), s.begin(), [] (unsigned char c) { return (char) std::tolower (c); });
- return s;
- }
- } // namespace
- InstrumentKind guessInstrument (const std::string& channelName, flp::ChannelType type)
- {
- const auto name = lowercase (channelName);
- if (type == flp::ChannelType::sampler || type == flp::ChannelType::unknown)
- {
- if (contains (name, "kick") || contains (name, "bd") || contains (name, "808"))
- return InstrumentKind::kick;
- if (contains (name, "snare") || contains (name, "snr") || contains (name, "rim"))
- return InstrumentKind::snare;
- if (contains (name, "clap") || contains (name, "snap"))
- return InstrumentKind::clap;
- if (contains (name, "hat") || contains (name, "hh") || contains (name, "ride") || contains (name, "cym")
- || contains (name, "crash") || contains (name, "shaker") || contains (name, "perc") || contains (name, "tamb"))
- return InstrumentKind::hat;
- }
- return InstrumentKind::synth;
- }
- std::string resolveFlPath (const std::string& flPath, const FlPathRoots& roots)
- {
- const std::pair<const char*, const std::string*> variables[] = {
- { "%FLStudioFactoryData%", &roots.factoryData },
- { "%FLStudioUserData%", &roots.userData },
- { "%FLStudioData%", &roots.data },
- };
- for (const auto& [name, root] : variables)
- {
- const std::string variable (name);
- if (flPath.compare (0, variable.size(), variable) == 0)
- return root->empty() ? std::string() : *root + flPath.substr (variable.size());
- }
- return flPath;
- }
- std::optional<EffectKind> effectForFlPlugin (const std::string& name)
- {
- static const std::pair<const char*, EffectKind> table[] = {
- { "Fruity Parametric EQ 2", EffectKind::parametricEq }, { "Fruity Parametric EQ", EffectKind::parametricEq },
- { "Fruity 7 Band EQ", EffectKind::parametricEq },
- { "Fruity Limiter", EffectKind::limiter }, { "Maximus", EffectKind::limiter }, { "Fruity Soft Clipper", EffectKind::distortion },
- { "Fruity Reeverb 2", EffectKind::reverb }, { "Fruity Reeverb", EffectKind::reverb }, { "LuxeVerb", EffectKind::reverb },
- { "Fruity Delay 3", EffectKind::delay }, { "Fruity Delay 2", EffectKind::delay }, { "Fruity Delay Bank", EffectKind::delay },
- { "Fruity Delay", EffectKind::delay }, { "Fruity Compressor", EffectKind::compressor },
- { "Fruity Multiband Compressor", EffectKind::compressor }, { "Soundgoodizer", EffectKind::compressor },
- { "Fruity WaveShaper", EffectKind::distortion }, { "Fruity Fast Dist", EffectKind::distortion },
- { "Fruity Blood Overdrive", EffectKind::distortion }, { "Distructor", EffectKind::distortion },
- { "Fruity Flangus", EffectKind::chorus }, { "Fruity Chorus", EffectKind::chorus }, { "Hyper Chorus", EffectKind::chorus },
- { "Vintage Chorus", EffectKind::chorus }, { "Fruity Flanger", EffectKind::chorus },
- { "Fruity Balance", EffectKind::utility }, { "Fruity PanOMatic", EffectKind::utility }, { "Fruity Stereo Shaper", EffectKind::utility },
- { "Fruity Center", EffectKind::utility }, { "Fruity Phase Inverter", EffectKind::utility },
- { "Fruity Stereo Enhancer", EffectKind::utility }, { "Fruity Convolver", EffectKind::reverb }, { "EQUO", EffectKind::parametricEq },
- { "Spreader", EffectKind::utility }, { "Transient Processor", EffectKind::utility },
- { "Fruity Phaser", EffectKind::chorus }, { "Fruity Bass Boost", EffectKind::eq }, { "Fruity Free Filter", EffectKind::filter },
- { "Fruity Love Philter", EffectKind::filter }, { "Fruity Filter", EffectKind::filter }, { "Fruity Fast LP", EffectKind::filter },
- { "Gross Beat", EffectKind::volumeGate }, { "Frequency Splitter", EffectKind::parametricEq },
- { "Fruity Peak Controller", EffectKind::peakController },
- { "Pitch Shifter", EffectKind::pitchShift }, { "Frequency Shifter", EffectKind::freqShift },
- { "Emphasis", EffectKind::limiter }, { "Low Lifter", EffectKind::parametricEq },
- { "Fruity Send", EffectKind::utility }, { "Transporter", EffectKind::utility },
- { "Vintage Phaser", EffectKind::vintagePhaser }, { "Fruity Squeeze", EffectKind::squeeze },
- };
- // old presets (FL 3) store the name with different casing ("Fruity delay 2")
- const auto wanted = lowercase (name);
- for (const auto& [plugin, kind] : table)
- if (wanted == lowercase (plugin))
- return kind;
- return std::nullopt;
- }
- AutomationTarget automationTargetFor (flp::ControlId id, const std::map<int, int>& channelMap, int mixerTracks)
- {
- AutomationTarget t;
- if (id.isTempo())
- {
- t.kind = AutomationTargetKind::tempo;
- return t;
- }
- if (id.isChannel())
- {
- const auto channel = channelMap.find (id.channel());
- if (channel == channelMap.end())
- return t;
- t.index = channel->second;
- const auto p = id.param();
- if (p == 0)
- t.kind = AutomationTargetKind::channelVolume;
- else if (p == 1)
- t.kind = AutomationTargetKind::channelPan;
- else if (p >= flp::ControlId::pluginParamBase)
- {
- t.kind = AutomationTargetKind::channelParam;
- t.param = p - flp::ControlId::pluginParamBase;
- }
- return t;
- }
- if (id.isMixer() && id.track() >= 0 && id.track() < mixerTracks)
- {
- t.index = id.track();
- const auto p = id.param();
- if (p == 0x1F01) // slot dry/wet
- {
- t.kind = AutomationTargetKind::effectMix;
- t.slot = id.slot();
- }
- else if (p == flp::ControlId::mixerVolume)
- t.kind = AutomationTargetKind::mixerVolume;
- else if (p == flp::ControlId::mixerPan)
- t.kind = AutomationTargetKind::mixerPan;
- else if (p >= flp::ControlId::pluginParamBase)
- {
- t.kind = AutomationTargetKind::effectParam;
- t.slot = id.slot();
- t.param = p - flp::ControlId::pluginParamBase;
- }
- }
- return t;
- }
- bool synthFrom3xOsc (const std::vector<std::uint8_t>& state, SynthSettings& synth)
- {
- // version 10/11: 20 parameters + 4 bools (80 B); 12+: 21 parameters + 4 bools (+ HQ)
- if (state.size() < 84)
- return false;
- auto i32 = [&] (std::size_t offset) {
- return (std::int32_t) ((std::uint32_t) state[offset] | ((std::uint32_t) state[offset + 1] << 8)
- | ((std::uint32_t) state[offset + 2] << 16) | ((std::uint32_t) state[offset + 3] << 24));
- };
- const auto version = i32 (0);
- if (version < 10 || version > 64)
- return false;
- // parameter i is at 0x04 + 4i; (i + 1) = 7·osc + field, fields [mix, pan, shape, coarse, fine, spo, detune]
- auto param = [&] (int osc, int field) { return i32 ((std::size_t) (4 + 4 * (7 * osc + field - 1))); };
- const auto boolsAt = version >= 12 ? (std::size_t) 0x58 : (std::size_t) 0x54;
- const bool am = version >= 11 && state.size() > boolsAt + 3 && state[boolsAt + 3] != 0;
- // levels (§2.2): osc 3 takes mix3/128, osc 2 a share of the rest, osc 1 what remains
- const auto g3 = std::clamp (param (2, 0), 0, 128) / 128.0f;
- const auto rest = am ? 1.0f : 1.0f - g3;
- const auto g2 = rest * std::clamp (param (1, 0), 0, 128) / 128.0f;
- // with AM, osc 3 is not summed: its level becomes the modulation depth (REA_rodada6 §3)
- const std::array<float, 3> levels { std::max (0.0f, rest - g2), g2, g3 };
- synth.am = am;
- for (int o = 0; o < 3; ++o)
- {
- auto& osc = synth.osc[(std::size_t) o];
- switch (param (o, 2))
- {
- case 0: osc.wave = Waveform::sine; break;
- case 1: osc.wave = Waveform::triangle; break;
- case 2: osc.wave = Waveform::square; break;
- case 5: osc.wave = Waveform::noise; break;
- default: osc.wave = Waveform::saw; break; // 3 saw, 4 rounded saw, 6 custom without sample
- }
- const auto coarse = std::clamp (param (o, 3), -24, 24);
- osc.octave = coarse / 12; // truncates toward zero; the remainder becomes semitones
- osc.semitones = coarse - osc.octave * 12;
- // stereo detune only sounds on the right channel: half of it counts as average detune
- 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);
- osc.pan = std::clamp (param (o, 1), -64, 64) / 64.0f;
- osc.level = levels[(std::size_t) o];
- }
- return true;
- }
- namespace
- {
- // FL channel filter cutoff (Hz) for normalized Mod X `x` (REA_rodada4 §3); 20 kHz = open.
- double channelFilterHz (int type, double x)
- {
- constexpr double twoPi = 6.283185307179586;
- x = std::clamp (x, 0.0, 1.0);
- switch (type)
- {
- case 0:
- 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));
- case 1:
- case 2:
- case 3:
- case 4:
- case 5: return ((std::pow (51.0, x) - 1.0) * 0.0596 + 0.02) * 44100.0 / twoPi;
- case 6:
- 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);
- default: return 20000.0;
- }
- }
- } // namespace
- float filterEnvelopeOctaves (int modX, int type, int amount)
- {
- const auto x = std::clamp (modX / 256.0, 0.0, 1.0);
- const auto from = std::clamp (channelFilterHz (type, x), 20.0, 20000.0);
- const auto to = std::clamp (channelFilterHz (type, x + amount / 128.0), 20.0, 20000.0);
- return (float) std::log2 (to / from);
- }
- void synthFilterFromChannel (int modX, int modY, int type, float& cutoffHz, float& resonance, int& mode)
- {
- mode = type == 2 ? 1 : type == 3 ? 2 : type == 4 ? 3 : 0; // BP, HP, BS; the rest is low-pass
- const auto x = std::clamp (modX / 256.0, 0.0, 1.0);
- const auto r = std::clamp (modY / 256.0, 0.0, 1.0);
- 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
- resonance = 0.0f;
- if (type == 0) // Fast LP: 1 pole + feedback; feedback grows with Mod Y (approximation)
- resonance = (float) (r * 0.9);
- else if (type >= 1 && type <= 5) // LP/BP/HP/BS biquads (LPx2 = the LP twice)
- resonance = fromQ (r <= 0.0 ? 0.1 : (std::pow (51.0, 0.625 * r) - 1.0) * 0.4 + 0.1);
- else if (type == 6 || type == 7) // Chamberlin SVF
- resonance = fromQ (1.0 / (r <= 0.0 ? 1.0 : (r < 1.0 ? 1.0 - 0.8 * r : 0.2)));
- cutoffHz = (float) std::clamp (channelFilterHz (type, x), 20.0, 20000.0);
- }
- void splitDrumChannel (Song& song, int channel, const std::vector<DrumPad>& pads)
- {
- if (channel < 0 || channel >= (int) song.channels.size() || pads.empty())
- return;
- const auto original = song.channels[(std::size_t) channel];
- const auto inserted = (int) pads.size() - 1; // the first pad takes the original channel's place
- std::vector<ChannelDef> padChannels;
- for (const auto& pad : pads)
- {
- ChannelDef def = original;
- def.name = original.name + " - " + pad.name;
- def.instrument = InstrumentKind::sampler;
- def.plugin = {};
- const auto single = pad.layers.size() == 1;
- def.samplePath = single ? pad.layers.front().path : std::string();
- def.zones = single ? std::vector<SampleZone> {} : pad.layers;
- for (auto& z : def.zones)
- z.rootKey = 60, z.lowKey = 0, z.highKey = 127; // the pad plays at the sample's pitch
- // volume: channel gain × pad gain (× the single layer's), mapped back to the channel curve
- const auto gain = channelGain (original.volume) * pad.gain * (single ? pad.layers.front().gain : 1.0f);
- def.volume = std::clamp ((float) (std::log (10.0 * gain + 1.0) / std::log (11.0)), 0.0f, 1.0f);
- def.pan = std::clamp (original.pan + pad.pan, -1.0f, 1.0f);
- def.sampler = {};
- def.sampler.pitch = std::clamp (original.sampler.pitch + pad.tune + (single ? pad.layers.front().tune : 0.0f), -24.0f, 24.0f);
- // kit-specific cut groups (don't mix with other channels' groups)
- def.cutGroup = pad.cutGroup > 0 ? 1000 * (channel + 1) + pad.cutGroup : 0;
- def.cutBy = pad.cutBy > 0 ? 1000 * (channel + 1) + pad.cutBy : 0;
- def.mixerTrack = std::clamp (original.mixerTrack + pad.mixerOffset, 0, maxMixerTracks - 1);
- padChannels.push_back (std::move (def));
- }
- song.channels[(std::size_t) channel] = padChannels.front();
- song.channels.insert (song.channels.begin() + channel + 1, padChannels.begin() + 1, padChannels.end());
- // channels after the original shift by `inserted` positions
- auto shift = [&] (int c) { return c > channel ? c + inserted : c; };
- for (auto& p : song.patterns)
- {
- std::vector<Note> kept;
- for (auto n : p.notes)
- {
- if (n.channel != channel)
- {
- n.channel = shift (n.channel);
- kept.push_back (n);
- continue;
- }
- for (int i = 0; i < (int) pads.size(); ++i)
- if (pads[(std::size_t) i].key == n.key)
- {
- n.channel = channel + i;
- n.key = 60;
- kept.push_back (n);
- break;
- }
- }
- p.notes = std::move (kept);
- p.sortNotes();
- }
- song.forEachClipList ([&] (std::vector<Clip>& clips) {
- for (auto& c : clips)
- c.channel = c.channel >= 0 ? shift (c.channel) : c.channel;
- });
- song.forEachTarget ([&] (AutomationTarget& t) {
- if ((t.kind == AutomationTargetKind::channelVolume || t.kind == AutomationTargetKind::channelPan
- || t.kind == AutomationTargetKind::channelParam) && t.index >= 0)
- t.index = shift (t.index);
- });
- }
- bool isFlSynthPresetPlugin (const std::string& pluginName)
- {
- static const char* const supported[] = { "3x osc", "sytrus", "harmor", "gms", "harmless", "minisynth", "fruity dx10", "dx10",
- "fruit kick", "ogun", "autogun", "sakura", "kepler", "boobass", "poizone", "bassdrum",
- "toxic biohazard" };
- const auto name = lowercase (pluginName);
- return std::any_of (std::begin (supported), std::end (supported), [&] (const char* n) { return name == n; });
- }
- std::optional<SynthSettings> synthFromFlPreset (const std::vector<std::uint8_t>& bytes)
- {
- // native GMS preset (.gmsynth): it is the plugin state without the "SSLF"
- if (bytes.size() >= 4 && (std::memcmp (bytes.data(), "4nyS", 4) == 0 || std::memcmp (bytes.data(), "3nyS", 4) == 0))
- {
- std::vector<std::uint8_t> state { 'S', 'S', 'L', 'F' };
- const auto n = (std::uint32_t) bytes.size();
- for (int i = 0; i < 4; ++i)
- state.push_back ((std::uint8_t) (n >> (8 * i)));
- state.insert (state.end(), bytes.begin(), bytes.end());
- SynthSettings synth;
- float gain = 1.0f;
- if (synthFromGms (state, 120.0, synth, gain))
- return synth;
- return std::nullopt;
- }
- try
- {
- auto project = flp::parseProject (bytes, true);
- if (project.channels.empty() || ! isFlSynthPresetPlugin (project.channels.front().pluginName))
- return std::nullopt;
- project.channels.front().type = flp::ChannelType::native; // native generator (the .fst doesn't say)
- const auto song = importFlp (project);
- if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::sakura)
- {
- // the synth's preset button keeps the synth approximation of a Sakura patch
- SynthSettings synth;
- if (synthFromSakura (project.channels.front().pluginState, synth))
- return synth;
- }
- if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::harmless)
- {
- // ... and of a Harmless patch
- SynthSettings synth;
- float gain = 1.0f;
- if (synthFromHarmless (project.channels.front().pluginState, song.bpm, synth, gain))
- return synth;
- }
- if (song.channels.empty() || song.channels.front().instrument != InstrumentKind::synth)
- return std::nullopt;
- return song.channels.front().synth;
- }
- catch (const flp::Error&)
- {
- return std::nullopt;
- }
- }
- Song importFlp (const flp::Project& input, const FlpImportOptions& options)
- {
- // Patcher used as an instrument: the channel becomes the main generator inside it (REA_rodada14 §1)
- std::optional<flp::Project> unpacked;
- for (std::size_t i = 0; i < input.channels.size(); ++i)
- if (lowercase (input.channels[i].pluginName) == "patcher")
- if (const auto graph = parsePatcher (input.channels[i].pluginState); graph && graph->mainGenerator >= 0)
- {
- if (! unpacked)
- unpacked = input;
- const auto& node = graph->nodes[(std::size_t) graph->mainGenerator];
- unpacked->channels[i].pluginName = node.plugin;
- unpacked->channels[i].pluginState = node.state;
- }
- const auto& project = unpacked ? *unpacked : input;
- Song song;
- song.bpm = project.tempo > 0.0 ? project.tempo : 140.0;
- song.beatsPerBar = std::clamp (project.beatsPerBar, 1, 32);
- song.swing = std::clamp (project.swing / 128.0f, 0.0f, 1.0f);
- // FL channels may have sparse indices; we map them to dense indices.
- std::map<int, int> channelMap;
- std::vector<std::pair<int, std::vector<DrumPad>>> drumKits; // FPC channels to split at the end
- std::optional<std::string> drumSynthDll; // the user's DrumSynth Live engine DLL, once checked ("" = not usable)
- for (const auto& c : project.channels)
- {
- // automation clips become Song::automations (further below), not channels
- if (c.type == flp::ChannelType::automationClip)
- continue;
- channelMap[c.index] = (int) song.channels.size();
- ChannelDef def;
- def.name = c.name.empty() ? "Channel " + std::to_string (c.index + 1) : c.name;
- def.instrument = guessInstrument (def.name, c.type);
- // FL synthesizer that becomes the internal synth: a preset matching the name (in FLEX, the name
- // of the preset chosen in the plugin says more than the channel's)
- if (def.instrument == InstrumentKind::synth)
- {
- def.synth = presetForChannelName (def.name);
- if (lowercase (c.pluginName) == "flex")
- if (const auto names = flexPresetName (c.pluginState))
- if (auto byPreset = presetForChannelName (names->second + " " + names->first); byPreset != SynthSettings {})
- def.synth = byPreset;
- }
- const auto isAudioClip = c.type == flp::ChannelType::audioClip;
- if ((c.type == flp::ChannelType::sampler || isAudioClip) && ! c.samplePath.empty() && options.fileExists)
- {
- const auto path = resolveFlPath (c.samplePath, options.roots);
- if (! path.empty() && options.fileExists (path))
- {
- def.instrument = isAudioClip ? InstrumentKind::audioClip : InstrumentKind::sampler;
- def.samplePath = path;
- }
- }
- if (isAudioClip && def.instrument != InstrumentKind::audioClip)
- def.instrument = InstrumentKind::audioClip; // no file: stays silent, but the clip remains in the playlist
- def.mixerTrack = std::clamp (c.mixerTrack, 0, maxMixerTracks - 1);
- if (c.colour != 0)
- def.colour = 0xFF000000u | c.colour;
- if (c.hasLevels)
- {
- def.volume = std::clamp (c.volume / 12800.0f, 0.0f, 1.0f); // same curve (channelGain)
- def.pan = std::clamp ((c.pan - 6400) / 6400.0f, -1.0f, 1.0f);
- def.sampler.pitch = std::clamp (c.pitchCents / 100.0f, -24.0f, 24.0f);
- }
- // sample root note: our sampler plays at the original pitch at C5 (60)
- if (c.rootNote >= 0 && c.rootNote <= 127)
- def.sampler.pitch = std::clamp (def.sampler.pitch + (float) (60 - c.rootNote), -24.0f, 24.0f);
- def.swingMix = std::clamp (c.swingMix / 128.0f, 0.0f, 1.0f);
- def.cutGroup = c.cutGroup;
- def.cutBy = c.cutBy;
- // "cut itself" (group == cut by) and mono channel become the sampler's "cut"
- if ((c.cutGroup != 0 && c.cutGroup == c.cutBy) || c.maxVoices == 1)
- def.sampler.cut = true;
- def.synth.mono = c.monoFlag || c.maxVoices == 1;
- // channel porta and slide time: n = round((27^(v/1024) - 1) * 48/26) ticks of 1/192 beat
- // (REA_rodada6 §4); the time also applies to notes with their own porta
- {
- const auto ticks = std::round ((std::pow (27.0, std::clamp (c.slideTime, 0, 1660) / 1024.0) - 1.0) * 48.0 / 26.0);
- def.synth.portaBeats = def.sampler.portaBeats = (float) std::max (1.0, ticks) / 192.0f;
- def.synth.porta = def.sampler.porta = c.portaFlag;
- }
- // volume envelope (record 1 of 0xDA) -> sampler ADSR
- const auto& volumeEnvelope = c.envelopes[1];
- const auto hasVolumeEnvelope = volumeEnvelope.present && volumeEnvelope.enabled;
- if (hasVolumeEnvelope)
- {
- const auto& env = volumeEnvelope;
- const auto beats = (env.flags & 1) != 0; // tempo-synced: units in beats
- auto seconds = [&] (int v) {
- const auto t = flp::Channel::envelopeTime (v);
- return (float) (beats ? t * 2.0 * 60.0 / song.bpm : t); // 0.128 beat instead of 0.064 s
- };
- def.sampler.attack = std::clamp (seconds (env.attack), 0.0f, 2.0f);
- def.sampler.decay = std::clamp (seconds (env.decay), 0.0f, 10.0f);
- def.sampler.sustain = std::clamp (env.sustain / 128.0f, 0.0f, 1.0f);
- def.sampler.release = std::clamp (std::max (seconds (env.release), 0.002f), 0.0f, 4.0f); // envelope on: the note ends
- }
- // channel filter (Mod X/Y + type from 0xDB) applies to the sampler too
- synthFilterFromChannel (c.modX, c.modY, c.filterType, def.sampler.cutoff, def.sampler.resonance, def.sampler.filterType);
- // channel cutoff (record 2) and pitch (record 4) envelopes
- auto modEnvelope = [&] (const flp::Channel::Envelope& env, float amount) {
- ModEnvelope m;
- if (! env.present || ! env.enabled || amount == 0.0f)
- return m;
- const auto beats = (env.flags & 1) != 0;
- auto seconds = [&] (int v) {
- const auto t = flp::Channel::envelopeTime (v);
- return (float) std::clamp (beats ? t * 2.0 * 60.0 / song.bpm : t, 0.0, 20.0);
- };
- m.amount = amount;
- m.attack = seconds (env.attack);
- m.hold = seconds (env.hold);
- m.decay = seconds (env.decay);
- m.sustain = std::clamp (env.sustain / 128.0f, 0.0f, 1.0f);
- m.release = seconds (env.release);
- return m;
- };
- const auto filterEnv = modEnvelope (c.envelopes[2], filterEnvelopeOctaves (c.modX, c.filterType, c.envelopes[2].amount));
- const auto pitchEnv = modEnvelope (c.envelopes[4], std::clamp (c.envelopes[4].amount, -2400, 2400) / 100.0f);
- def.sampler.filterEnv = filterEnv;
- def.sampler.pitchEnv = pitchEnv;
- // channel LFOs (records 0 pan, 1 volume, 2 cutoff, 4 pitch; REA_rodada6 §2)
- {
- auto lfoFrom = [&] (const flp::Channel::Envelope& env, float amount) {
- ChannelLfo l;
- if (! env.present || env.lfoAmount == 0 || amount == 0.0f)
- return l;
- l.sync = (env.flags & 0x02) != 0;
- auto time = [&] (int v) { // seconds, or beats when synced (double the scale)
- const auto t = flp::Channel::envelopeTime (v);
- return (float) std::clamp (l.sync ? t * 2.0 : t, 0.0, 64.0);
- };
- l.amount = amount;
- l.period = std::max (0.01f, time (env.lfoSpeed));
- l.shape = std::clamp (env.lfoShape, 0, 2);
- l.delay = time (env.lfoDelay);
- l.attack = time (env.lfoAttack);
- l.global = (env.flags & 0x20) != 0;
- return l;
- };
- std::array<ChannelLfo, lfoTargets> lfo {};
- lfo[lfoPan] = lfoFrom (c.envelopes[0], std::clamp (c.envelopes[0].lfoAmount, -64, 64) / 64.0f);
- lfo[lfoVolume] = lfoFrom (c.envelopes[1], std::clamp (c.envelopes[1].lfoAmount, -128, 128) / 128.0f);
- lfo[lfoCutoff] = lfoFrom (c.envelopes[2], filterEnvelopeOctaves (c.modX, c.filterType, c.envelopes[2].lfoAmount));
- lfo[lfoPitch] = lfoFrom (c.envelopes[4], std::clamp (c.envelopes[4].lfoAmount, -2400, 2400) / 100.0f);
- def.sampler.lfo = lfo;
- def.synth.lfo = lfo;
- }
- // third-party plugin (VST/CLAP) in Fruity Wrapper: the app looks for the same installed plugin;
- // until then (or if not found) the channel stays on the internal synth
- // FL generators with samples (REA_rodada9): DirectWave becomes a multi-sample sampler; FPC is
- // split into one channel per pad at the end of the import (notes go to the pad by key)
- auto existing = [&] (std::string path) {
- const auto resolved = resolveFlPath (path, options.roots);
- return ! resolved.empty() && options.fileExists && options.fileExists (resolved) ? resolved : std::string();
- };
- if (c.pluginName == "DirectWave")
- if (auto program = directWaveProgram (c.pluginState))
- {
- std::vector<SampleZone> zones;
- for (std::size_t i = 0; i < program->zones.size(); ++i)
- {
- auto z = program->zones[i];
- auto path = existing (z.path);
- // file missing on this machine: use the audio the project stored with it
- if (path.empty() && i < program->embeddedWav.size() && ! program->embeddedWav[i].empty() && options.saveEmbedded)
- path = options.saveEmbedded (program->embeddedWav[i], def.name + " " + std::to_string (i + 1));
- if (! path.empty())
- {
- z.path = path;
- zones.push_back (std::move (z));
- }
- }
- if (! zones.empty())
- {
- def.instrument = InstrumentKind::sampler;
- def.zones = std::move (zones);
- def.sampler.attack = std::clamp (program->attack, 0.0f, 2.0f);
- def.sampler.decay = std::clamp (program->decay, 0.0f, 10.0f);
- def.sampler.sustain = program->sustain;
- def.sampler.release = std::clamp (std::max (program->release, 0.01f), 0.0f, 4.0f);
- }
- }
- // Fruity Slicer / Slicex: sampler with the slices (slice i plays on key 60 + i, at the sample's pitch)
- {
- const auto name = lowercase (c.pluginName);
- std::optional<SlicedSample> sliced;
- if (name == "fruity slicer")
- sliced = fruitySlicer (c.pluginState);
- else if (name == "slicex")
- sliced = slicex (c.pluginState);
- if (sliced)
- {
- std::string path;
- if (! sliced->embeddedWav.empty() && options.saveEmbedded) // audio that only exists inside the project
- path = options.saveEmbedded (sliced->embeddedWav, def.name);
- if (path.empty())
- path = existing (sliced->path);
- if (! path.empty())
- {
- auto positions = sliced->positions;
- std::int64_t frames = 0;
- if (positions.empty()) // Slicex: the slices are the WAV "cue" points
- {
- const auto bytes = ! sliced->embeddedWav.empty() ? sliced->embeddedWav
- : options.readFile ? options.readFile (path) : std::vector<std::uint8_t> {};
- positions = wavCuePoints (bytes, frames);
- }
- if (frames <= 0 && options.sampleFrames)
- frames = options.sampleFrames (path);
- def.instrument = InstrumentKind::sampler;
- def.samplePath = path;
- def.sampler.pitch = std::clamp (def.sampler.pitch + sliced->pitchCents / 100.0f, -24.0f, 24.0f);
- if (frames > 0)
- for (auto p : positions)
- if (p >= 0 && p < frames)
- def.sampler.slices.push_back ((float) ((double) p / (double) frames));
- }
- }
- }
- // FL Keys: the samples of the set (.wti) that ships with FL
- if (c.pluginName == "FL Keys" && options.readFile && ! options.roots.factoryData.empty())
- if (const auto set = flKeysSet (c.pluginState))
- {
- const auto folder = options.roots.factoryData + "\\Plugins\\Fruity\\Generators\\FL Keys\\Wavtables";
- const auto wtiBytes = options.readFile (folder + "\\" + *set + ".wti");
- const std::string wti (wtiBytes.begin(), wtiBytes.end());
- std::vector<std::uint8_t> rawData;
- if (wti.find ("filetype=raw") != std::string::npos)
- if (const auto file = wti.find ("samplefile="); file != std::string::npos)
- {
- auto name = wti.substr (file + 11, wti.find_first_of ("\r\n", file) - file - 11);
- rawData = options.readFile (folder + "\\" + name);
- }
- std::vector<SampleZone> zones;
- for (auto z : flKeysZones (wti, folder, rawData, options.saveEmbedded))
- if (z.path = existing (z.path); ! z.path.empty())
- zones.push_back (std::move (z));
- if (! zones.empty())
- {
- def.instrument = InstrumentKind::sampler;
- def.zones = std::move (zones);
- def.sampler.release = 0.4f; // the piano releases the note with a short release
- }
- }
- // Wave Traveller: plays its sample (the scratch curve is left out)
- if (c.pluginName == "Wave Traveller")
- if (const auto wave = waveTravellerSample (c.pluginState))
- if (auto path = existing (wave->first); ! path.empty())
- {
- def.instrument = InstrumentKind::sampler;
- def.samplePath = std::move (path);
- def.sampler.pitch = std::clamp (def.sampler.pitch + (float) (60 - wave->second), -24.0f, 24.0f);
- }
- // Fruity Envelope Controller: "controller" channel (silent) that triggers the envelopes from notes
- if ((c.pluginName == "Fruity Envelope Controller" && parseEnvelopeController (c.pluginState))
- || (c.pluginName == "Fruity Keyboard Controller" && parseKeyboardController (c.pluginState)))
- {
- def.instrument = InstrumentKind::controller;
- def.controllerState = c.pluginState;
- }
- // Fruity DrumSynth Live: its engine with all 120 patches (REA_rodada30 §1); the recorded waveforms some patches
- // use are read at run time from the user's own engine DLL (without it they are silent, the synthesis is not).
- // Fallback when the state can't be parsed: the FL drum sample with the same name as the editor's sound
- if (c.pluginName == "Fruity DrumSynth Live")
- {
- if (auto params = drumSynthLiveParams (c.pluginState))
- {
- def.instrument = InstrumentKind::drumsynth;
- def.modelParams = std::move (*params);
- if (! drumSynthDll)
- {
- drumSynthDll = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Fruity DrumSynth Live\\drumsynth_eng_x64.dll",
- options.roots);
- if (drumSynthDll->empty() || ! options.fileExists || ! options.fileExists (*drumSynthDll) || ! drumSynthDllUsable (*drumSynthDll))
- drumSynthDll = std::string();
- }
- def.samplePath = *drumSynthDll;
- }
- else if (const auto sound = drumSynthLiveSound (c.pluginState))
- for (const auto& candidate : drumSampleCandidates (*sound))
- if (auto path = existing (candidate); ! path.empty())
- {
- def.instrument = InstrumentKind::sampler;
- def.samplePath = std::move (path);
- break;
- }
- }
- if (c.pluginName == "FPC")
- if (auto pads = fpcPads (c.pluginState))
- {
- std::vector<DrumPad> found;
- for (auto pad : *pads)
- {
- std::vector<SampleZone> layers;
- for (auto layer : pad.layers)
- if (layer.path = existing (layer.path); ! layer.path.empty())
- layers.push_back (std::move (layer));
- pad.layers = std::move (layers);
- if (! pad.layers.empty())
- found.push_back (std::move (pad));
- }
- if (! found.empty())
- drumKits.push_back ({ (int) song.channels.size(), std::move (found) });
- }
- if (c.pluginName == "Fruity Wrapper" && parseFlWrapper (c.pluginState, def.plugin.foreign))
- def.plugin.name = def.plugin.foreign.name;
- // Fruit Kick, MiniSynth, ... (REA_rodada10): approximated by the internal synth; the channel LFOs are kept
- bool adoptedFromPlugin = false;
- if (def.instrument == InstrumentKind::synth)
- {
- const auto name = lowercase (c.pluginName);
- SynthSettings fromPlugin;
- float pluginGain = 1.0f;
- auto adopt = [&] {
- for (int i = 0; i < lfoTargets; ++i)
- if (def.synth.lfo[(std::size_t) i].amount != 0.0f)
- fromPlugin.lfo[(std::size_t) i] = def.synth.lfo[(std::size_t) i];
- def.synth = fromPlugin;
- adoptedFromPlugin = true;
- const auto g = channelGain (def.volume) * pluginGain;
- def.volume = std::clamp ((float) (std::log (10.0 * g + 1.0) / std::log (11.0)), 0.0f, 1.0f);
- };
- if (name == "harmless")
- {
- // FL's additive engine (REA_rodada32); the internal synth approximation stays as the fallback
- if (auto params = harmlessParams (c.pluginState))
- {
- def.instrument = InstrumentKind::harmless;
- def.modelParams = std::move (*params);
- adoptedFromPlugin = true;
- // rack compressor: Harmless's own preset <n>.fst from the user's installation (REA_rodada36 §2)
- const auto compType = (int) def.modelParams[(std::size_t) harmlessComboIndex + 3];
- if (compType > 0)
- {
- const auto path = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Harmless\\Data\\Compression\\"
- + std::to_string (compType) + ".fst",
- options.roots);
- std::optional<std::vector<std::uint8_t>> state;
- if (! path.empty() && options.readFile && (! options.fileExists || options.fileExists (path)))
- state = hlfx::maximusStateFromFst (options.readFile (path));
- if (state && hlfx::makeMaximusPreset (*state) != nullptr)
- {
- def.modelParams.push_back ((float) state->size());
- for (const auto byte : *state)
- def.modelParams.push_back ((float) byte);
- }
- else if (options.report != nullptr)
- ++options.report->droppedEffects["Harmless compressor (preset not found)"];
- }
- }
- else if (synthFromHarmless (c.pluginState, song.bpm, fromPlugin, pluginGain))
- adopt();
- }
- else if (name == "fruit kick" && synthFromFruitKick (c.pluginState, fromPlugin))
- adopt();
- else if (name == "minisynth" && synthFromMiniSynth (c.pluginState, song.bpm, fromPlugin))
- adopt();
- else if ((name == "fruity dx10" || name == "dx10") && synthFromDX10 (c.pluginState, fromPlugin))
- adopt();
- else if (name == "sytrus" && synthFromSytrus (c.pluginState, song.bpm, fromPlugin, pluginGain))
- adopt();
- else if (name == "harmor" && synthFromHarmor (c.pluginState, fromPlugin, pluginGain))
- adopt();
- else if (name == "gms" && synthFromGms (c.pluginState, song.bpm, fromPlugin, pluginGain))
- adopt();
- else if ((name == "ogun" || name == "autogun") && synthFromOgun (c.pluginState, fromPlugin, pluginGain))
- adopt();
- else if (name == "sakura")
- {
- // the physical string model (REA_rodada28 §1); the old saw + triangle stays as a fallback
- if (auto params = sakuraParams (c.pluginState))
- {
- def.instrument = InstrumentKind::sakura;
- def.modelParams = std::move (*params);
- adoptedFromPlugin = true;
- }
- else if (synthFromSakura (c.pluginState, fromPlugin))
- adopt();
- }
- else if (name == "kepler" && synthFromKepler (c.pluginState, fromPlugin, pluginGain))
- adopt();
- else if (name == "boobass")
- {
- // FL's engine with its multisample read at run time from the user's own BooBass DLL (REA_rodada29 §4)
- const auto dll = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\BooBass\\BooBass_Eng_x64.dll", options.roots);
- auto word = [&] (std::size_t at) { std::uint32_t v = 0; std::memcpy (&v, c.pluginState.data() + at, 4); return v; };
- if (c.pluginState.size() >= 16 && word (0) == 1 && ! dll.empty() && options.fileExists && options.fileExists (dll)
- && booBassDllUsable (dll))
- {
- def.instrument = InstrumentKind::boobass;
- def.samplePath = dll;
- for (std::size_t k = 0; k < 3; ++k)
- def.modelParams.push_back ((float) std::clamp ((int) word (4 + 4 * k), 0, 65535));
- adoptedFromPlugin = true;
- }
- else if (synthFromBooBass (c.pluginState, fromPlugin))
- adopt();
- }
- else if (name == "poizone" && synthFromPoiZone (c.pluginState, fromPlugin, pluginGain))
- adopt();
- else if (name == "bassdrum" && synthFromBassDrum (c.pluginState, fromPlugin, pluginGain))
- adopt();
- else if (name == "toxic biohazard" && synthFromToxic (c.pluginState, fromPlugin, pluginGain))
- adopt();
- else if (name == "morphine" && synthFromMorphine (c.pluginState, fromPlugin, pluginGain))
- adopt();
- else if (name == "drumpad" && drumpadParams (c.pluginState))
- {
- // the physical drum model (REA_rodada28 §2)
- const auto dp = drumpadParams (c.pluginState);
- def.instrument = InstrumentKind::drumpad;
- def.modelParams.assign (dp->begin(), dp->end());
- adoptedFromPlugin = true;
- }
- else if (name == "drumpad")
- if (const auto patch = drumpadPatchName (c.pluginState))
- {
- // kick/snare/clap/hi-hat: the drum instruments; the rest, a drum on the synth
- if (const auto drum = guessInstrument (*patch, flp::ChannelType::sampler); drum != InstrumentKind::synth)
- {
- def.instrument = drum;
- adoptedFromPlugin = true;
- }
- else
- {
- fromPlugin = drumToneForName (*patch);
- // confirmed: Pitch ×2^(2x − 1) and Mallet Amplitude 10^(−4(1 − x)) (the physical model isn't)
- if (const auto dp = drumpadParams (c.pluginState))
- {
- const auto semis = 12.0f * (2.0f * std::clamp ((*dp)[29], 0.0f, 1.0f) - 1.0f);
- for (auto& o : fromPlugin.osc)
- {
- o.semitones += (int) std::lround (semis);
- o.detune += 100.0f * (semis - (float) std::lround (semis));
- }
- pluginGain = (float) std::pow (10.0, -4.0 * (1.0 - std::clamp ((double) (*dp)[2], 0.0, 1.0)));
- }
- adopt();
- }
- }
- }
- // 3x Osc: oscillators from the plugin state; envelope and filter come from the channel (REA_rodada4)
- if (def.instrument == InstrumentKind::synth && c.pluginName == "3x Osc" && synthFrom3xOsc (c.pluginState, def.synth))
- {
- if (hasVolumeEnvelope)
- {
- def.synth.attack = def.sampler.attack;
- def.synth.decay = def.sampler.decay;
- def.synth.sustain = def.sampler.sustain;
- def.synth.release = def.sampler.release;
- }
- else
- {
- // without an envelope FL plays the note as a gate, with only a short declick
- def.synth.attack = 0.002f;
- def.synth.decay = 0.0f;
- def.synth.sustain = 1.0f;
- def.synth.release = 0.02f;
- }
- synthFilterFromChannel (c.modX, c.modY, c.filterType, def.synth.cutoff, def.synth.resonance, def.synth.filterType);
- def.synth.filterEnv = filterEnv;
- def.synth.pitchEnv = pitchEnv;
- }
- // sample region and start offset
- if (std::isfinite (c.sampleStart) && std::isfinite (c.sampleEnd) && std::isfinite (c.startOffset))
- {
- const auto start = std::clamp (c.sampleStart, 0.0, 1.0), end = std::clamp (c.sampleEnd, 0.0, 1.0);
- if (end > start)
- {
- def.sampler.regionStart = (float) std::clamp (start + std::clamp (c.startOffset, 0.0, 1.0) * (end - start), 0.0, 1.0);
- def.sampler.regionEnd = (float) end;
- }
- }
- // time-stretch: the sample lasts TIME/192 beats × MUL
- if (c.stretchTime > 0.0f)
- {
- def.sampler.stretchBeats = (float) (c.stretchTime / 192.0 * std::pow (2.0, c.stretchMul / 10000.0));
- def.sampler.keepPitch = c.stretchMode != 0; // only FL's "Resample" changes the pitch
- }
- // report: what happened to this channel's generator/sample
- if (options.report != nullptr)
- {
- auto& r = *options.report;
- const auto plugin = lowercase (c.pluginName);
- if (plugin.empty())
- r.missingSamples += ! c.samplePath.empty() && def.samplePath.empty() ? 1 : 0;
- else if (plugin == "3x osc" || ((plugin == "directwave" || plugin == "fl keys") && ! def.zones.empty())
- || ((plugin == "fruity slicer" || plugin == "slicex") && ! def.samplePath.empty())
- || (plugin == "fpc" && ! drumKits.empty() && drumKits.back().first == (int) song.channels.size()))
- ++r.converted[c.pluginName];
- else if ((plugin == "harmless" && def.instrument != InstrumentKind::harmless) || plugin == "minisynth" || plugin == "fruity dx10" || plugin == "dx10" || plugin == "fruit kick"
- || ((plugin == "sytrus" || plugin == "harmor" || plugin == "gms" || plugin == "ogun" || plugin == "autogun" || plugin == "sakura" || plugin == "kepler" || plugin == "boobass" || plugin == "drumpad" || plugin == "poizone" || plugin == "bassdrum"
- || plugin == "toxic biohazard" || plugin == "morphine") && adoptedFromPlugin)
- || (plugin == "wave traveller" && def.instrument == InstrumentKind::sampler)
- || (plugin == "fruity drumsynth live" && def.instrument == InstrumentKind::sampler))
- ++r.approximated[c.pluginName];
- else if (((plugin == "fruity envelope controller" || plugin == "fruity keyboard controller") && def.instrument == InstrumentKind::controller)
- || (plugin == "fruity drumsynth live" && def.instrument == InstrumentKind::drumsynth)
- || (plugin == "harmless" && def.instrument == InstrumentKind::harmless))
- ++r.converted[c.pluginName];
- else if (plugin != "fruity wrapper" && plugin != "fruity keyboard controller" && plugin != "midi out"
- && def.instrument == InstrumentKind::synth)
- ++r.unsupported[c.pluginName]; // (Keyboard Controller only sends notes to other channels)
- }
- song.channels.push_back (std::move (def));
- }
- // Mixer: names, mute/solo, routing and levels from the .flp; enough inserts for all
- // routes (minimum 16, like a new project). FL's extra tracks (500/501) are left out.
- int highestTrack = 16;
- for (const auto& c : song.channels)
- highestTrack = std::max (highestTrack, c.mixerTrack);
- for (const auto& insert : project.mixer)
- if (insert.index < maxMixerTracks)
- for (auto target : insert.routes)
- if (target < maxMixerTracks && (insert.index > 0 || target > 0))
- highestTrack = std::max ({ highestTrack, target, insert.index });
- song.mixer = Song::defaultMixer (std::min (highestTrack, maxMixerTracks - 1));
- const auto tracks = (int) song.mixer.size();
- for (const auto& insert : project.mixer)
- {
- if (insert.index < 0 || insert.index >= tracks)
- continue;
- auto& track = song.mixer[(std::size_t) insert.index];
- if (insert.index > 0 && ! insert.name.empty())
- track.name = insert.name;
- if (insert.colour != 0 && insert.colour != 0x485156) // FL's default gray
- track.colour = 0xFF000000u | insert.colour;
- track.muted = (insert.flags & 0x08) == 0;
- track.invertPhase = (insert.flags & 0x01) != 0;
- track.swapChannels = (insert.flags & 0x02) != 0;
- track.solo = insert.index > 0 && (insert.flags & 0x1000) != 0;
- if (insert.index > 0 && insert.hasRoutes)
- {
- track.toMaster = std::find (insert.routes.begin(), insert.routes.end(), 0) != insert.routes.end();
- // The level comes from 0xE1 (below). Without a record, FL templates route every insert to the
- // send tracks at the end of the mixer (100+) at level 0; routes to regular inserts are 100%.
- for (auto target : insert.routes)
- if (target > 0 && target < tracks && target != insert.index)
- track.sends.push_back ({ target, target >= 100 ? 0.0f : 1.0f });
- }
- }
- // native FL effects become the similar internal effects (default parameters: the internal
- // state of FL plugins is not known); the others are left out
- std::map<std::pair<int, int>, std::pair<int, std::string>> effectSlotMap; // (track, FL slot) -> (our effect, FL plugin)
- // inputs of each track (REA_rodada22 §1): [itself, the ones routing to it in ascending order (at
- // any level; level 0 = sidechain only)]; the index k stored in the plugins points into this list
- std::map<int, std::vector<int>> trackInputs;
- for (const auto& insert : project.mixer)
- if (insert.hasRoutes)
- for (const auto target : insert.routes)
- if (target > 0 && target != insert.index)
- trackInputs[target].push_back (insert.index);
- auto sidechainSource = [&] (int track, int k) {
- if (k <= 0)
- return -1;
- auto inputs = trackInputs[track];
- std::sort (inputs.begin(), inputs.end());
- inputs.erase (std::unique (inputs.begin(), inputs.end()), inputs.end());
- inputs.insert (inputs.begin(), track);
- return k < (int) inputs.size() && inputs[(std::size_t) k] < tracks ? inputs[(std::size_t) k] : -1;
- };
- std::map<std::pair<int, int>, decltype (LovePhilterConversion::paramMap)> lovePhilterMaps; // Love Philter automation
- for (const auto& insert : project.mixer)
- {
- if (insert.index < 0 || insert.index >= tracks)
- continue;
- auto& track = song.mixer[(std::size_t) insert.index];
- for (const auto& original : insert.slots)
- {
- // Patcher with a simple serial chain: the plugins inside become consecutive slots
- std::vector<flp::MixerInsert::Slot> expanded { original };
- // Fruity Love Philter: the units become parametric EQ + gain/pan (or a parallel container)
- if (original.plugin == "Fruity Love Philter" && (int) track.effects.size() < maxEffectSlots)
- if (auto conversion = lovePhilterEffects (original.state))
- {
- const auto first = (int) track.effects.size();
- for (auto& fx : conversion->slots)
- if ((int) track.effects.size() < maxEffectSlots)
- track.effects.push_back (std::move (fx));
- effectSlotMap.insert ({ { insert.index, original.index }, { first, original.plugin } });
- if (conversion->paramMap)
- lovePhilterMaps[{ insert.index, original.index }] = conversion->paramMap;
- for (const auto& link : conversion->links) // cutoff envelope/LFO: live automation
- if (first + std::max (link.source, link.target) < (int) track.effects.size())
- {
- Automation a;
- a.name = "Love Philter (" + track.name + ")";
- a.target = { AutomationTargetKind::effectParam, insert.index, first + link.target, link.param };
- a.source = { insert.index, first + link.source, 0 };
- a.curve = link.curve;
- song.automations.push_back (std::move (a));
- }
- if (options.report != nullptr)
- {
- ++options.report->converted["Fruity Love Philter"];
- for (const auto& note : conversion->notes)
- ++options.report->droppedEffects[note];
- }
- continue;
- }
- // Patcher with branches (REA_rodada20 §3.3): the audio graph reduced to series/parallel becomes slots and
- // nested parallel containers; splitter nodes enter via the band/bus used
- if (lowercase (original.plugin) == "patcher" && (int) track.effects.size() < maxEffectSlots)
- if (const auto graph = parsePatcher (original.state); graph && graph->serialChain.empty() && graph->audio)
- {
- std::function<std::vector<EffectSlot> (const PatcherExpr&, float&)> build = [&] (const PatcherExpr& e, float& gain) {
- std::vector<EffectSlot> chain;
- gain *= e.gain;
- switch (e.kind)
- {
- case PatcherExpr::Kind::identity: break;
- case PatcherExpr::Kind::node:
- {
- const auto& node = graph->nodes[(std::size_t) e.node];
- if (e.bus >= 0)
- {
- const auto head = patcherBranchHead (node.plugin, node.state, e.bus);
- if (! head.valid)
- {
- if (options.report != nullptr)
- ++options.report->droppedEffects["Patcher: bus " + std::to_string (e.bus) + " of " + node.plugin];
- break;
- }
- gain *= head.gain;
- if (head.slot)
- chain.push_back (*head.slot);
- if (! head.note.empty() && options.report != nullptr)
- ++options.report->droppedEffects[head.note];
- }
- else if (auto fx = effectFromFl (node.plugin, node.state, song.bpm); fx && fx->kind != EffectKind::plugin)
- chain.push_back (std::move (*fx));
- else if (options.report != nullptr)
- ++options.report->droppedEffects[node.plugin + " (in Patcher)"];
- break;
- }
- case PatcherExpr::Kind::series:
- for (const auto& c : e.children)
- for (auto& slot : build (c, gain))
- chain.push_back (std::move (slot));
- break;
- case PatcherExpr::Kind::parallel:
- {
- auto container = makeEffectSlot (EffectKind::parallel);
- for (const auto& c : e.children)
- {
- EffectBranch branch;
- auto branchGain = 1.0f;
- branch.chain = build (c, branchGain);
- branch.gain = std::clamp (branchGain, 0.0f, 4.0f);
- container.branches.push_back (std::move (branch));
- }
- chain.push_back (std::move (container));
- break;
- }
- }
- return chain;
- };
- auto gain = 1.0f;
- auto chain = build (*graph->audio, gain);
- if (std::abs (gain - 1.0f) > 1e-4f)
- {
- auto utility = makeEffectSlot (EffectKind::utility);
- utility.params[0] = gain <= 0.0f ? 0.0f : std::clamp ((float) (20.0 * std::log10 (gain) / 48.0 + 0.5), 0.0f, 1.0f);
- chain.push_back (std::move (utility));
- }
- if ((int) (track.effects.size() + chain.size()) > maxEffectSlots) // doesn't fit: a single-branch container
- {
- auto container = makeEffectSlot (EffectKind::parallel);
- container.branches.push_back ({ std::move (chain), 1.0f });
- chain = { std::move (container) };
- }
- effectSlotMap.insert ({ { insert.index, original.index }, { (int) track.effects.size(), original.plugin } });
- for (auto& slot : chain)
- track.effects.push_back (std::move (slot));
- if (options.report != nullptr)
- ++options.report->converted["Patcher (series/parallel)"];
- continue;
- }
- if (lowercase (original.plugin) == "patcher")
- if (const auto graph = parsePatcher (original.state); graph && ! graph->serialChain.empty())
- {
- expanded.clear();
- for (const auto n : graph->serialChain)
- expanded.push_back ({ original.index, graph->nodes[(std::size_t) n].plugin, graph->nodes[(std::size_t) n].state });
- if (options.report != nullptr)
- ++options.report->converted["Patcher (in series)"];
- }
- for (const auto& slot : expanded)
- {
- if ((int) track.effects.size() >= maxEffectSlots)
- continue;
- ForeignPlugin foreign;
- std::optional<EffectSlot> made;
- const auto wrapped = slot.plugin == "Fruity Wrapper" && parseFlWrapper (slot.state, foreign);
- // old FL saved its own Fruity effects as VST2 inside the wrapper: becomes the internal effect
- if (wrapped && foreign.format == ForeignPlugin::Format::vst2 && effectForFlPlugin (foreign.name))
- made = effectFromFl (foreign.name, {}, song.bpm);
- else if (wrapped)
- {
- // the app swaps in the installed plugin; without it, the slot is removed
- made = makeEffectSlot (EffectKind::plugin);
- made->plugin.name = foreign.name;
- made->plugin.foreign = std::move (foreign);
- }
- else
- made = effectFromFl (slot.plugin, slot.state, song.bpm); // native effect with the saved settings (REA_rodada7)
- if (! made)
- {
- // the ones that don't touch audio (controllers, visualizers, notes) aren't missed
- static const char* silent[] = { "Fruity Peak Controller", "Fruity X-Y Controller", "Control Surface", "Wave Candy",
- "ZGameEditor Visualizer", "Fruity NoteBook 2", "Fruity NoteBook", "Edison",
- "Fruity Formula Controller", "Fruity LSD", "Fruity dB Meter", "Fruity Spectroman" };
- const auto harmless = std::any_of (std::begin (silent), std::end (silent), [&] (const char* n) { return slot.plugin == n; });
- if (options.report != nullptr && slot.plugin != "Fruity Wrapper" && ! harmless)
- ++options.report->droppedEffects[slot.plugin];
- continue;
- }
- auto fx = std::move (*made);
- // sidechain (REA_rodada22 §1): Fruity Limiter (i32 at 0xA4, v ≥ 6; only the compressor detector and only
- // with Comp threshold < 0 dB) and Fruity Compressor (i32 at 0x20, v3)
- if (slot.plugin == "Fruity Limiter" && slot.state.size() >= 0xA8)
- {
- std::int32_t version = 0, k = 0, compThreshold = 1000;
- std::memcpy (&version, slot.state.data(), 4);
- std::memcpy (&k, slot.state.data() + 0xA4, 4);
- std::memcpy (&compThreshold, slot.state.data() + 4 + 8 * 4, 4);
- if (const auto source = sidechainSource (insert.index, k); version >= 6 && source >= 0 && compThreshold < 1000)
- if (auto comp = fruityLimiterCompressor (slot.state))
- {
- const auto enabled = fx.enabled;
- fx = std::move (*comp);
- fx.enabled = enabled;
- fx.sidechain = source;
- if (options.report != nullptr)
- ++options.report->converted["Fruity Limiter (sidechain)"];
- }
- }
- else if (slot.plugin == "Vocodex")
- {
- // ModIn/CarIn index the same inputs list as the sidechains (REA_rodada22 §1)
- if (const auto v = vocodexEffect (slot.state))
- {
- fx.sidechain = sidechainSource (insert.index, v->modIn);
- fx.sidechain2 = sidechainSource (insert.index, v->carIn);
- if (options.report != nullptr)
- for (const auto& note : v->notes)
- ++options.report->droppedEffects[note];
- }
- }
- else if (slot.plugin == "Fruity Compressor" && slot.state.size() >= 0x24 && fx.kind == EffectKind::compressor)
- {
- std::int32_t version = 0, k = 0;
- std::memcpy (&version, slot.state.data(), 4);
- std::memcpy (&k, slot.state.data() + 0x20, 4);
- if (version == 3)
- fx.sidechain = sidechainSource (insert.index, k);
- }
- // slot bypass and dry/wet (0xE1, p = 0x1F00 / 0x1F01)
- for (const auto& control : project.controls)
- if (control.id.isMixer() && control.id.track() == insert.index && control.id.slot() == slot.index)
- {
- if (control.id.param() == 0x1F00)
- fx.enabled = control.value != 0;
- else if (control.id.param() == 0x1F01)
- fx.mix = std::clamp (control.value / 12800.0f, 0.0f, 1.0f);
- }
- effectSlotMap.insert ({ { insert.index, slot.index }, { (int) track.effects.size(), slot.plugin } });
- track.effects.push_back (fx);
- }
- }
- }
- // cycles shouldn't exist in the file; if they do, the send that closes the cycle is dropped
- for (int t = 1; t < tracks; ++t)
- {
- auto sends = std::move (song.mixer[(std::size_t) t].sends);
- song.mixer[(std::size_t) t].sends.clear();
- for (const auto& s : sends)
- song.setRoute (t, s.target, true, s.level);
- }
- for (const auto& control : project.controls)
- {
- if (! control.id.isMixer())
- continue;
- const auto t = control.id.track();
- const auto p = control.id.param();
- if (t < 0 || t >= tracks)
- continue;
- auto& track = song.mixer[(std::size_t) t];
- // FL ranges: volume 0..16000 (12800 = 0 dB), pan ±6400, send 0..16000 (12800 = 100%)
- if (p == flp::ControlId::mixerVolume)
- track.volume = std::clamp (control.value / 16000.0f, 0.0f, 1.0f);
- else if (p == flp::ControlId::mixerPan)
- track.pan = std::clamp (control.value / 6400.0f, -1.0f, 1.0f);
- else if (p == flp::ControlId::mixerStereo)
- track.stereo = std::clamp (control.value / 64.0f, -1.0f, 1.0f);
- else if (p >= flp::ControlId::mixerEqBase && p < flp::ControlId::mixerEqBase + 24 && (p - flp::ControlId::mixerEqBase) % 8 < 3)
- {
- // track EQ: p = 0x1FD0 + group·8 + band (group 0 gain, 1 frequency, 2 width; REA_rodada6 §1)
- const auto group = (p - flp::ControlId::mixerEqBase) / 8;
- const auto band = (std::size_t) ((p - flp::ControlId::mixerEqBase) % 8);
- const auto v = (double) control.value;
- if (group == 0)
- track.eq.gainDb[band] = (float) std::clamp (v * 0.01, -18.0, 18.0);
- else if (group == 1)
- track.eq.hz[band] = (float) std::clamp (10.0 + 159.9 * (std::pow (101.0, v / 65536.0) - 1.0), 10.0, 16000.0);
- else
- track.eq.width[band] = (float) std::clamp (v / 65536.0, 0.0, 1.0);
- }
- else if (p >= flp::ControlId::mixerSendBase && p < flp::ControlId::mixerSendBase + tracks)
- for (auto& send : track.sends)
- if (send.target == p - flp::ControlId::mixerSendBase)
- send.level = std::clamp (control.value / 12800.0f, 0.0f, 1.0f);
- }
- // the FL template routes every insert to the send tracks at level 0; that makes no sound, only wastes CPU
- for (auto& t : song.mixer)
- t.sends.erase (std::remove_if (t.sends.begin(), t.sends.end(), [] (const MixerSend& s) { return s.level <= 0.0f; }),
- t.sends.end());
- const auto filePpq = project.header.ppq > 0 ? (std::int64_t) project.header.ppq : 96;
- auto rescale = [filePpq] (std::int64_t ticks) { return ticks * ppq / filePpq; };
- std::map<int, int> patternMap; // FL index -> our dense index
- for (const auto& src : project.patterns)
- {
- Pattern p;
- p.name = src.name.empty() ? "Pattern " + std::to_string (src.index) : src.name;
- if (src.colour && *src.colour != 0x485156) // FL's default gray becomes an automatic colour
- p.colour = 0xFF000000u | *src.colour;
- for (const auto& n : src.notes)
- {
- const auto it = channelMap.find (n.channel);
- if (it == channelMap.end())
- continue;
- Note note;
- note.start = rescale (n.position);
- // Step notes (length 0) play for one step.
- note.length = n.length > 0 ? rescale (n.length) : ticksPerStep;
- note.channel = it->second;
- note.key = n.key; // FL and MIDI use the same numbering; only the octave name differs
- note.velocity = std::clamp (n.velocity / 128.0f, 0.0f, 1.0f);
- note.pan = std::clamp ((n.pan - 64) / 64.0f, -1.0f, 1.0f);
- note.finePitch = (float) std::clamp ((int) n.finePitch - 120, -120, 120);
- note.muted = n.muted();
- note.slide = n.slide();
- note.porta = n.porta();
- p.notes.push_back (note);
- }
- p.sortNotes();
- if (! p.notes.empty())
- {
- patternMap[src.index] = (int) song.patterns.size();
- song.patterns.push_back (std::move (p));
- }
- }
- // Our target for an FL controlID: the FL slot (0..9, with gaps) becomes our effect's
- // index (effect not imported = no target); internal effect parameter only with the FL-to-ours
- // map (`valueMap` receives the value conversion).
- auto resolveTarget = [&] (flp::ControlId id, std::function<float (float)>& valueMap) {
- auto target = automationTargetFor (id, channelMap, (int) song.mixer.size());
- if (target.kind == AutomationTargetKind::effectParam || target.kind == AutomationTargetKind::effectMix)
- {
- const auto found = effectSlotMap.find ({ target.index, target.slot });
- if (found == effectSlotMap.end())
- target.kind = AutomationTargetKind::none;
- else
- {
- target.slot = found->second.first;
- const auto& fx = song.mixer[(std::size_t) target.index].effects[(std::size_t) target.slot];
- if (target.kind == AutomationTargetKind::effectParam && found->second.second == "Fruity Love Philter")
- {
- const auto map = lovePhilterMaps.find ({ id.track(), id.slot() });
- const auto mapped = map != lovePhilterMaps.end() && map->second ? map->second (target.param) : std::nullopt;
- if (mapped)
- {
- target.slot = found->second.first + std::get<0> (*mapped);
- target.param = std::get<1> (*mapped);
- valueMap = std::get<2> (*mapped);
- }
- else
- target.kind = AutomationTargetKind::none;
- }
- else if (target.kind == AutomationTargetKind::effectParam && fx.kind != EffectKind::plugin)
- {
- if (const auto mapped = effectParamFromFl (found->second.second, target.param))
- {
- target.param = mapped->param;
- valueMap = mapped->convert;
- }
- else
- target.kind = AutomationTargetKind::none;
- }
- }
- }
- return target;
- };
- // Automation clips: one Automation per FL automation channel, with the target from the 0xE3 link.
- std::map<int, int> automationMap; // FL channel -> index into song.automations
- for (const auto& c : project.channels)
- {
- if (c.type != flp::ChannelType::automationClip || c.automation.empty())
- continue;
- Automation a;
- a.name = c.name.empty() ? "Automation " + std::to_string (c.index + 1) : c.name;
- std::function<float (float)> valueMap; // FL normalized value -> ours (effect parameters)
- for (const auto& link : project.automationLinks)
- if (link.channel == c.index)
- {
- a.target = resolveTarget (link.target, valueMap);
- break;
- }
- for (std::size_t i = 0; i < c.automation.size(); ++i)
- {
- const auto& p = c.automation[i];
- const auto tick = (std::int64_t) std::llround (p.position * ppq);
- auto value = (float) std::clamp (p.value, 0.0, 1.0);
- // FL automates tempo from 60 to 180 BPM; our target covers the full tempo range
- if (a.target.kind == AutomationTargetKind::tempo)
- value = valueFromTempo (60.0 + 120.0 * value);
- else if (valueMap)
- value = std::clamp (valueMap (value), 0.0f, 1.0f);
- // FL's curve belongs to the segment ending at the point; ours sits on the left point
- if (i > 0)
- {
- auto& previous = a.points.back();
- if (p.curve == 0 || p.curve == 1) // single/double curve: exponential by tension
- previous.tension = std::clamp (-p.tension, -1.0f, 1.0f);
- else if (p.curve == 2 && tick - previous.tick > 1) // hold: step right before the point
- a.points.push_back ({ tick - 1, previous.value, 0.0f });
- }
- a.points.push_back ({ tick, value, 0.0f });
- }
- automationMap[c.index] = (int) song.automations.size();
- song.automations.push_back (std::move (a));
- }
- // Controller links (REA_rodada14 §7): Peak Controller in a mixer slot -> live automation of the
- // target (the effect output is read every block). Other controllers are still left out.
- for (const auto& link : project.controllerLinks)
- {
- // Envelope Controller on a channel: output k follows articulator k
- if (link.source.isChannel())
- {
- const auto channel = channelMap.find (link.source.channel());
- if (channel == channelMap.end() || song.channels[(std::size_t) channel->second].instrument != InstrumentKind::controller)
- continue;
- Automation a;
- std::function<float (float)> valueMap;
- a.target = resolveTarget (link.target, valueMap);
- if (a.target.kind == AutomationTargetKind::none || a.target.kind == AutomationTargetKind::tempo)
- continue;
- a.name = "Controller (" + song.channels[(std::size_t) channel->second].name + ")";
- a.source.channel = channel->second;
- a.source.output = link.source.param() - flp::ControlId::pluginParamBase;
- if (valueMap)
- for (int i = 0; i <= 32; ++i)
- a.curve.push_back (std::clamp (valueMap ((float) i / 32.0f), 0.0f, 1.0f));
- song.automations.push_back (std::move (a));
- if (options.report != nullptr)
- ++options.report->converted["Channel controller (link)"];
- continue;
- }
- if (! link.source.isMixer() || link.source.track() < 0 || link.source.track() >= (int) song.mixer.size())
- continue;
- // static X-Y Controller / Control Surface: the current value is applied to the target once
- {
- const flp::MixerInsert::Slot* source = nullptr;
- for (const auto& insert : project.mixer)
- if (insert.index == link.source.track())
- for (const auto& slot : insert.slots)
- if (slot.index == link.source.slot())
- source = &slot;
- if (source != nullptr)
- if (const auto value = controllerConstantOutput (source->plugin, source->state, link.source.param() - flp::ControlId::pluginParamBase))
- {
- std::function<float (float)> valueMap;
- const auto target = resolveTarget (link.target, valueMap);
- if (target.kind != AutomationTargetKind::none && target.kind != AutomationTargetKind::tempo
- && song.setTargetValue (target, valueMap ? valueMap (*value) : *value) && options.report != nullptr)
- ++options.report->converted[source->plugin + " (link)"];
- continue;
- }
- }
- const auto found = effectSlotMap.find ({ link.source.track(), link.source.slot() });
- if (found == effectSlotMap.end()
- || song.mixer[(std::size_t) link.source.track()].effects[(std::size_t) found->second.first].kind != EffectKind::peakController)
- continue;
- Automation a;
- std::function<float (float)> valueMap;
- a.target = resolveTarget (link.target, valueMap);
- if (a.target.kind == AutomationTargetKind::none || a.target.kind == AutomationTargetKind::tempo)
- continue;
- a.name = "Peak Controller (" + song.mixer[(std::size_t) link.source.track()].name + ")";
- a.source = { link.source.track(), found->second.first, link.source.param() - flp::ControlId::pluginParamBase };
- if (valueMap)
- for (int i = 0; i <= 32; ++i)
- a.curve.push_back (std::clamp (valueMap ((float) i / 32.0f), 0.0f, 1.0f));
- song.automations.push_back (std::move (a));
- if (options.report != nullptr)
- ++options.report->converted["Peak Controller (link)"];
- }
- // Playlist: all arrangements (the first stays open); pattern, audio and automation clips.
- std::vector<const std::vector<flp::PlaylistTrackInfo>*> importedTracks;
- if (! project.arrangements.empty())
- song.arrangements.clear();
- for (const auto& arrangement : project.arrangements)
- {
- std::vector<Clip> clips;
- for (const auto& item : arrangement.items)
- {
- if (item.length == 0)
- continue;
- if (item.kind == flp::PlaylistItem::Kind::channelClip && automationMap.count (item.index))
- {
- Clip clip;
- clip.kind = ClipKind::automation;
- clip.automation = automationMap[item.index];
- clip.track = item.track;
- clip.start = rescale (item.position);
- clip.length = rescale (item.length);
- // trim in beats (-1 = no trim)
- if (std::isfinite (item.startOffset) && item.startOffset > 0.0f)
- clip.offset = (std::int64_t) std::llround (item.startOffset * ppq);
- clips.push_back (clip);
- continue;
- }
- if (item.kind == flp::PlaylistItem::Kind::channelClip)
- {
- const auto channel = channelMap.find (item.index);
- if (channel == channelMap.end() || song.channels[(std::size_t) channel->second].instrument != InstrumentKind::audioClip)
- continue;
- Clip clip;
- clip.kind = ClipKind::audio;
- clip.channel = channel->second;
- clip.track = item.track;
- clip.start = rescale (item.position);
- clip.length = rescale (item.length);
- // The region start comes in beats or in milliseconds, depending on the clip;
- // we find out by the unit in which (end - start) matches the length.
- const auto beats = (double) item.length / (double) filePpq;
- const auto span = (double) item.endOffset - (double) item.startOffset;
- if (std::isfinite (item.startOffset) && item.startOffset > 0.0f)
- {
- if (std::abs (span - beats) < 0.02 * std::max (1.0, beats))
- clip.offset = (std::int64_t) std::llround (item.startOffset * ppq);
- else if (std::abs (span - beats * 60000.0 / song.bpm) < 0.02 * std::max (1.0, span))
- clip.offset = (std::int64_t) std::llround (item.startOffset / 1000.0 * song.bpm / 60.0 * ppq);
- }
- clips.push_back (clip);
- continue;
- }
- const auto it = patternMap.find (item.index);
- if (it == patternMap.end())
- continue;
- Clip clip;
- clip.pattern = it->second;
- clip.track = item.track;
- clip.start = rescale (item.position);
- clip.length = rescale (item.length);
- clip.offset = item.patternStartTick > 0 ? rescale (item.patternStartTick) : 0;
- clips.push_back (clip);
- }
- std::sort (clips.begin(), clips.end(), [] (const Clip& a, const Clip& b) { return a.start < b.start; });
- Arrangement a;
- a.name = arrangement.name.empty() ? "Arrangement " + std::to_string (song.arrangements.size() + 1) : arrangement.name;
- // markers; type 8 changes the time signature (loop/pause actions become plain markers)
- for (const auto& m : arrangement.markers)
- {
- Marker marker;
- marker.tick = rescale (m.position);
- marker.name = m.name;
- marker.name.erase (0, marker.name.find_first_not_of (' '));
- marker.name.erase (marker.name.find_last_not_of (' ') + 1);
- if (m.type == 8 && m.numerator >= 1 && m.numerator <= 32 && m.denominator >= 1 && m.denominator <= 32)
- {
- marker.numerator = m.numerator;
- marker.denominator = m.denominator;
- }
- // unnamed: the FL marker type (REA_rodada6 §5)
- static const char* typeNames[] = { "", "Loop (marker)", "Skip", "Pause", "Loop", "Start", "Pattern length", "",
- "", "Start recording", "Stop recording", "Loop length", "Key/scale" };
- if (marker.name.empty() && m.type > 0 && m.type < 13 && m.type != 8)
- marker.name = typeNames[m.type];
- a.markers.push_back (std::move (marker));
- }
- std::stable_sort (a.markers.begin(), a.markers.end(), [] (const Marker& x, const Marker& y) { return x.tick < y.tick; });
- importedTracks.push_back (&arrangement.tracks);
- if (song.arrangements.empty())
- song.playlist = std::move (clips); // the first is the current one
- else
- a.clips = std::move (clips);
- song.arrangements.push_back (std::move (a));
- }
- // the .flp doesn't say which arrangement was open; the fullest is usually the song
- {
- int fullest = 0;
- std::size_t most = song.playlist.size();
- for (int i = 1; i < (int) song.arrangements.size(); ++i)
- if (song.arrangements[(std::size_t) i].clips.size() > most)
- {
- most = song.arrangements[(std::size_t) i].clips.size();
- fullest = i;
- }
- song.selectArrangement (fullest);
- // Playlist track names and mute (from the open arrangement)
- if (fullest < (int) importedTracks.size())
- for (const auto& t : *importedTracks[(std::size_t) fullest])
- if (t.index >= 0 && t.index < 500 && (! t.name.empty() || ! t.enabled))
- {
- if ((int) song.playlistTracks.size() <= t.index)
- song.playlistTracks.resize ((std::size_t) t.index + 1);
- song.playlistTracks[(std::size_t) t.index] = { t.name, ! t.enabled };
- }
- }
- if (! song.playlist.empty())
- song.mode = PlayMode::song;
- if (song.patterns.empty())
- song.patterns.emplace_back().name = "Pattern 1";
- // The .flp doesn't say which pattern was open; the fullest is the best starting point.
- for (int i = 0; i < (int) song.patterns.size(); ++i)
- if (song.patterns[(std::size_t) i].notes.size() > song.patterns[(std::size_t) song.currentPattern].notes.size())
- song.currentPattern = i;
- // MIDI Out (REA_rodada16 §1): the channel makes no sound; its notes go to the plugins (Fruity
- // Wrapper) listening on the same MIDI port
- for (const auto& c : project.channels)
- {
- if (lowercase (c.pluginName) != "midi out" || c.pluginState.size() < 28)
- continue;
- const auto from = channelMap.find (c.index);
- if (from == channelMap.end())
- continue;
- std::int32_t port = -1;
- std::memcpy (&port, c.pluginState.data() + 24, 4);
- auto& source = song.channels[(std::size_t) from->second];
- source.muted = true;
- for (int target = 0; target < (int) song.channels.size(); ++target)
- {
- const auto& t = song.channels[(std::size_t) target];
- if (target == from->second || port < 0 || t.plugin.foreign.midiInPort != port)
- continue;
- for (auto& pattern : song.patterns)
- {
- const auto count = pattern.notes.size();
- for (std::size_t n = 0; n < count; ++n)
- if (pattern.notes[n].channel == from->second)
- {
- auto copy = pattern.notes[n];
- copy.channel = target;
- pattern.notes.push_back (copy);
- }
- }
- }
- }
- // FPC kits: one channel per pad (last to first, so indices don't shift)
- for (auto it = drumKits.rbegin(); it != drumKits.rend(); ++it)
- splitDrumChannel (song, it->first, it->second);
- return song;
- }
- } // namespace lynx
|