FlpImport.cpp 195 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706
  1. #include "core/FlpImport.h"
  2. #include "core/Dvs.h"
  3. #include "core/FlExtraFx.h"
  4. #include "core/Scratcher.h"
  5. #include "core/Transmitter.h"
  6. #include "core/TransporterFl.h"
  7. #include "core/ControlSurface.h"
  8. #include "core/VoltageController.h"
  9. #include "core/XyController.h"
  10. #include "core/Vfx.h"
  11. #include "core/VideoPlayer.h"
  12. #include "core/Patcher.h"
  13. #include <filesystem>
  14. #include "core/EditorPolish.h"
  15. #include "core/FruityPhaser.h"
  16. #include "core/FlPluginDb.h"
  17. #include "core/FlVoiceProcessor.h"
  18. #include "core/HardcoreFx.h"
  19. #include "core/GrossBeat.h"
  20. #include "core/LovePhilter.h"
  21. #include "core/DrumSynthLive.h"
  22. #include "core/Gms.h"
  23. #include "core/Harmless.h"
  24. #include "core/Morphine.h"
  25. #include "core/BassDrum.h"
  26. #include "core/FruitKick.h"
  27. #include "core/Harmor.h"
  28. #include "core/ClipOps.h"
  29. #include "core/MiniSynth.h"
  30. #include "core/SimSynth.h"
  31. #include "core/Drumaxx.h"
  32. #include "core/Plucked.h"
  33. #include "core/FlKeys.h"
  34. #include "core/DirectWave.h"
  35. #include "core/BeepMap.h"
  36. #include "core/Sawer.h"
  37. #include "core/Granulizer.h"
  38. #include "core/WaveTraveller.h"
  39. #include "core/Ogun.h"
  40. #include "core/Dx10.h"
  41. #include "core/Kepler.h"
  42. #include "core/TransistorBass.h"
  43. #include "core/Slayer.h"
  44. #include "core/PoiZone.h"
  45. #include "core/Toxic.h"
  46. #include "core/ThreeOsc.h"
  47. #include "core/TimeStretch.h"
  48. #include "core/HarmlessFx.h"
  49. #include "core/SytrusEngine.h"
  50. #include "core/PhysicalModels.h"
  51. #include "core/ChannelMiscFx.h"
  52. #include "core/Effects.h"
  53. #include "core/FlEffects.h"
  54. #include "core/Reeverb2.h"
  55. #include "core/LuxeVerb.h"
  56. #include "core/ConvolverFx.h"
  57. #include "core/ChorusFx.h"
  58. #include "core/FlPatcher.h"
  59. #include "core/FlSamplers.h"
  60. #include "core/FlSynths.h"
  61. #include "core/FlWrapper.h"
  62. #include "core/FruityDynamics.h"
  63. #include "core/SoundFont.h"
  64. #include "core/SynthPresets.h"
  65. #include "core/NewtoneFx.h"
  66. #include <algorithm>
  67. #include <cstring>
  68. #include <cctype>
  69. #include <cmath>
  70. #include <map>
  71. #include <ctime>
  72. namespace lynx
  73. {
  74. double flDateTimeToUnix (double days)
  75. {
  76. if (! (days > 25569.0 && days < 2958466.0)) // 1970-01-01 … 9999-12-31
  77. return 0.0;
  78. // the local wall-clock reading as a civil date (H. Hinnant's days → y/m/d), then mktime gives UTC
  79. const auto local = (days - 25569.0) * 86400.0;
  80. const auto secs = (long long) std::floor (local);
  81. long long z = secs / 86400 + 719468;
  82. const auto sod = secs % 86400;
  83. const long long era = z / 146097, doe = z - era * 146097;
  84. const long long yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
  85. const long long doy = doe - (365 * yoe + yoe / 4 - yoe / 100), mp = (5 * doy + 2) / 153;
  86. std::tm tm {};
  87. tm.tm_mday = (int) (doy - (153 * mp + 2) / 5 + 1);
  88. tm.tm_mon = (int) (mp < 10 ? mp + 2 : mp - 10);
  89. tm.tm_year = (int) (yoe + era * 400 + (tm.tm_mon <= 1 ? 1 : 0)) - 1900;
  90. tm.tm_hour = (int) (sod / 3600);
  91. tm.tm_min = (int) (sod / 60 % 60);
  92. tm.tm_sec = (int) (sod % 60);
  93. tm.tm_isdst = -1;
  94. const auto t = std::mktime (&tm);
  95. return t == (std::time_t) -1 ? local : (double) t + (local - (double) secs);
  96. }
  97. namespace
  98. {
  99. bool contains (const std::string& haystack, const char* needle)
  100. {
  101. return haystack.find (needle) != std::string::npos;
  102. }
  103. std::string lowercase (std::string s)
  104. {
  105. std::transform (s.begin(), s.end(), s.begin(), [] (unsigned char c) { return (char) std::tolower (c); });
  106. return s;
  107. }
  108. } // namespace
  109. void applyFlLayerFlags (int flags, LayerSettings& layer)
  110. {
  111. // REA_rodada164a §1 [DECOMP 0xF46490, 0xD29240]: bit 0 Random, bit 1 Crossfade, bit 2 Sequential (Random wins)
  112. layer.random = (flags & 1) != 0;
  113. layer.crossfade = (flags & 2) != 0;
  114. layer.sequential = (flags & 4) != 0 && ! layer.random;
  115. }
  116. InstrumentKind guessInstrument (const std::string& channelName, flp::ChannelType type)
  117. {
  118. const auto name = lowercase (channelName);
  119. if (type == flp::ChannelType::sampler || type == flp::ChannelType::unknown)
  120. {
  121. if (contains (name, "kick") || contains (name, "bd") || contains (name, "808"))
  122. return InstrumentKind::kick;
  123. if (contains (name, "snare") || contains (name, "snr") || contains (name, "rim"))
  124. return InstrumentKind::snare;
  125. if (contains (name, "clap") || contains (name, "snap"))
  126. return InstrumentKind::clap;
  127. if (contains (name, "hat") || contains (name, "hh") || contains (name, "ride") || contains (name, "cym")
  128. || contains (name, "crash") || contains (name, "shaker") || contains (name, "perc") || contains (name, "tamb"))
  129. return InstrumentKind::hat;
  130. }
  131. return InstrumentKind::synth;
  132. }
  133. // `path` as it exists on disk when only the letter case differs (POSIX file systems are case-sensitive; FL's paths
  134. // come from Windows). Returns `path` unchanged when it exists or no case-insensitive match is found.
  135. std::string existingPathIgnoringCase (const std::string& path)
  136. {
  137. namespace fs = std::filesystem;
  138. std::error_code ec;
  139. if (path.empty() || path.front() != '/' || fs::exists (path, ec))
  140. return path;
  141. auto lower = [] (std::string t) {
  142. std::transform (t.begin(), t.end(), t.begin(), [] (unsigned char c) { return (char) std::tolower (c); });
  143. return t;
  144. };
  145. fs::path current ("/");
  146. for (const auto& part : fs::path (path).relative_path())
  147. {
  148. if (fs::exists (current / part, ec))
  149. {
  150. current /= part;
  151. continue;
  152. }
  153. const auto wanted = lower (part.string());
  154. bool found = false;
  155. for (fs::directory_iterator it (current, ec), end; ! ec && it != end; it.increment (ec))
  156. if (lower (it->path().filename().string()) == wanted)
  157. {
  158. current = it->path();
  159. found = true;
  160. break;
  161. }
  162. if (! found)
  163. return path;
  164. }
  165. return current.string();
  166. }
  167. std::string resolveFlPath (const std::string& flPath, const FlPathRoots& roots)
  168. {
  169. const std::pair<const char*, const std::string*> variables[] = {
  170. { "%FLStudioFactoryData%", &roots.factoryData },
  171. { "%FLStudioUserData%", &roots.userData },
  172. { "%FLStudioData%", &roots.data },
  173. };
  174. for (const auto& [name, root] : variables)
  175. {
  176. const std::string variable (name);
  177. if (flPath.compare (0, variable.size(), variable) == 0)
  178. {
  179. if (root->empty())
  180. return {};
  181. auto path = *root + flPath.substr (variable.size());
  182. // a POSIX root (macOS, Linux, a Wine prefix): FL's backslashes become '/', and FL's file names, written for
  183. // a case-insensitive file system, are matched ignoring case when the exact spelling does not exist
  184. if (root->front() == '/')
  185. {
  186. std::replace (path.begin(), path.end(), '\\', '/');
  187. path = existingPathIgnoringCase (path);
  188. }
  189. return path;
  190. }
  191. }
  192. return flPath;
  193. }
  194. namespace
  195. {
  196. const std::pair<const char*, EffectKind> flEffectTable[] = {
  197. { "Fruity Parametric EQ 2", EffectKind::parametricEq }, { "Fruity Parametric EQ", EffectKind::parametricEq },
  198. { "Fruity 7 Band EQ", EffectKind::parametricEq },
  199. { "Fruity Limiter", EffectKind::limiter }, { "Maximus", EffectKind::limiter }, { "Fruity Soft Clipper", EffectKind::distortion },
  200. { "Fruity Reeverb 2", EffectKind::reverb }, { "Fruity Reeverb", EffectKind::reverb }, { "LuxeVerb", EffectKind::reverb },
  201. { "Fruity Delay 3", EffectKind::delay }, { "Fruity Delay 2", EffectKind::delay }, { "Fruity Delay Bank", EffectKind::delay },
  202. { "Fruity Delay", EffectKind::delay }, { "Fruity Compressor", EffectKind::compressor },
  203. { "Fruity Multiband Compressor", EffectKind::compressor }, { "Soundgoodizer", EffectKind::compressor },
  204. { "Fruity WaveShaper", EffectKind::distortion }, { "Fruity Fast Dist", EffectKind::distortion },
  205. { "Fruity Blood Overdrive", EffectKind::distortion }, { "Distructor", EffectKind::distortion },
  206. { "Fruity Flangus", EffectKind::chorus }, { "Fruity Chorus", EffectKind::chorus }, { "Hyper Chorus", EffectKind::chorus },
  207. { "Vintage Chorus", EffectKind::chorus }, { "Fruity Flanger", EffectKind::chorus },
  208. { "Fruity Balance", EffectKind::utility }, { "Fruity PanOMatic", EffectKind::utility }, { "Fruity Stereo Shaper", EffectKind::utility },
  209. { "Fruity Center", EffectKind::utility }, { "Fruity Phase Inverter", EffectKind::utility },
  210. { "Fruity Stereo Enhancer", EffectKind::utility }, { "Fruity Convolver", EffectKind::reverb }, { "EQUO", EffectKind::parametricEq },
  211. { "Spreader", EffectKind::utility }, { "Transient Processor", EffectKind::utility },
  212. { "Fruity Phaser", EffectKind::chorus }, { "Fruity Bass Boost", EffectKind::eq }, { "Fruity Free Filter", EffectKind::filter },
  213. { "Fruity Love Philter", EffectKind::filter }, { "Fruity Filter", EffectKind::filter }, { "Fruity Fast LP", EffectKind::filter },
  214. { "Gross Beat", EffectKind::volumeGate }, { "Frequency Splitter", EffectKind::parametricEq },
  215. { "Fruity Peak Controller", EffectKind::peakController }, { "Fruity Formula Controller", EffectKind::formulaController },
  216. { "Pitch Shifter", EffectKind::pitchShift }, { "Frequency Shifter", EffectKind::freqShift },
  217. { "Emphasis", EffectKind::limiter }, { "Low Lifter", EffectKind::parametricEq },
  218. { "Fruity Send", EffectKind::utility }, { "Transporter", EffectKind::utility },
  219. { "Vintage Phaser", EffectKind::vintagePhaser }, { "Fruity Squeeze", EffectKind::squeeze },
  220. { "Hardcore", EffectKind::hardcore },
  221. { "Multiband Delay", EffectKind::delay },
  222. { "Emphasizer", EffectKind::emphasizer },
  223. { "Wave Candy", EffectKind::waveCandy }, { "ZGameEditor Visualizer", EffectKind::visualizer },
  224. { "Fruity Mute 2", EffectKind::fruityMute2 }, { "Fruity Big Clock", EffectKind::bigClock }, // round 165g
  225. { "Tuner", EffectKind::tuner }, { "Fruity HTML NoteBook", EffectKind::htmlNotebook },
  226. { "Fruity Scratcher", EffectKind::scratcher }, // round 165g (flscratch165)
  227. { "Transmitter", EffectKind::transmitter }, // round 165g (fltrans165)
  228. };
  229. } // namespace
  230. std::optional<EffectKind> effectForFlPlugin (const std::string& name)
  231. {
  232. // old presets (FL 3) store the name with different casing ("Fruity delay 2")
  233. const auto wanted = lowercase (name);
  234. for (const auto& [plugin, kind] : flEffectTable)
  235. if (wanted == lowercase (plugin))
  236. return kind;
  237. return std::nullopt;
  238. }
  239. // FL's own spelling of a native effect's name (Patcher nodes keep old casings: "Fruity delay 2", REA_rodada14 §1.3)
  240. static std::string canonicalFlEffectName (const std::string& name)
  241. {
  242. const auto wanted = lowercase (name);
  243. for (const auto& entry : flEffectTable)
  244. if (wanted == lowercase (entry.first))
  245. return entry.first;
  246. return name;
  247. }
  248. // Range of an FL parameter's raw value (what FL's parameter setter stores and what pattern events 0xDF / 0xD8 hold),
  249. // so that (raw − lo) / (hi − lo) is FL's normalised value, the one automation clips carry (REA_rodada85 §2).
  250. // `plugin` = the FL plugin of the target slot or channel. Unknown ranges: no value.
  251. std::optional<std::pair<int, int>> flRawRange (flp::ControlId id, const std::string& plugin)
  252. {
  253. const auto p = id.param();
  254. if (id.isChannel())
  255. {
  256. if (p == 0 || p == 1) // volume 0..12800 (10000 = default), pan 0..12800 (6400 = centre)
  257. return std::pair { 0, 12800 };
  258. }
  259. else if (id.isMixer())
  260. {
  261. if (p == flp::ControlId::mixerVolume)
  262. return std::pair { 0, 16000 };
  263. if (p == flp::ControlId::mixerPan)
  264. return std::pair { -6400, 6400 };
  265. if (p == 0x1F01) // slot dry/wet
  266. return std::pair { 0, 12800 };
  267. }
  268. if (p < flp::ControlId::pluginParamBase)
  269. return std::nullopt;
  270. // plugin parameters: the plugin's own control integer (FL hands it to ProcessParam unscaled)
  271. const auto k = p - flp::ControlId::pluginParamBase;
  272. if ((plugin == "Fruity Soundfont Player" || plugin == "SoundFont Player") && k < 13)
  273. return sf::flParamRange (k);
  274. if (plugin == "Fruity Reeverb 2" && k < reeverb2ParamCount)
  275. return std::pair { reeverb2::ranges[(std::size_t) k].lo, reeverb2::ranges[(std::size_t) k].hi };
  276. if (plugin == "Fruity Reeverb" && k < reeverb1ParamCount)
  277. return std::pair { 0, reeverb1::maxima[(std::size_t) k] };
  278. if (plugin == "Fruity Convolver" && k < convolverParamCount)
  279. return std::pair { convolver::ranges[(std::size_t) k].lo, convolver::ranges[(std::size_t) k].hi };
  280. if (plugin == "Fruity Scratcher" && k < scratcher::count) // the platter wheel 0…30000, Mute 0/1 (1 = muted), …
  281. return std::pair { scratcher::controlRange (k).lo, scratcher::controlRange (k).hi };
  282. if (plugin == "Transporter" && k < transporter::numControls) // FL's 22 controls, each over its own range
  283. return std::pair { transporter::rawMin[(std::size_t) k], transporter::rawMax[(std::size_t) k] };
  284. if (plugin == "Transmitter" && k < transmitter::count) // 0…10000 for the knobs, the switches / selectors raw
  285. return std::pair { transmitter::controlRange (k).lo, transmitter::controlRange (k).hi };
  286. if (plugin == "LuxeVerb" && k < luxeVerbControlCount)
  287. return std::pair { luxeverb::ranges[(std::size_t) k].lo, luxeverb::ranges[(std::size_t) k].hi };
  288. return std::nullopt;
  289. }
  290. AutomationTarget automationTargetFor (flp::ControlId id, const std::map<int, int>& channelMap, int mixerTracks)
  291. {
  292. AutomationTarget t;
  293. if (id.isTempo())
  294. {
  295. t.kind = AutomationTargetKind::tempo;
  296. return t;
  297. }
  298. if (id.isChannel())
  299. {
  300. const auto channel = channelMap.find (id.channel());
  301. if (channel == channelMap.end())
  302. return t;
  303. t.index = channel->second;
  304. const auto p = id.param();
  305. if (p == 0)
  306. t.kind = AutomationTargetKind::channelVolume;
  307. else if (p == 1)
  308. t.kind = AutomationTargetKind::channelPan;
  309. else if (p >= flp::ControlId::pluginParamBase)
  310. {
  311. t.kind = AutomationTargetKind::channelParam;
  312. t.param = p - flp::ControlId::pluginParamBase;
  313. }
  314. return t;
  315. }
  316. if (id.isMixer() && id.track() >= 0 && id.track() < mixerTracks)
  317. {
  318. t.index = id.track();
  319. const auto p = id.param();
  320. if (p == 0x1F01) // slot dry/wet
  321. {
  322. t.kind = AutomationTargetKind::effectMix;
  323. t.slot = id.slot();
  324. }
  325. else if (p == flp::ControlId::mixerVolume)
  326. t.kind = AutomationTargetKind::mixerVolume;
  327. else if (p == flp::ControlId::mixerPan)
  328. t.kind = AutomationTargetKind::mixerPan;
  329. else if (p >= flp::ControlId::pluginParamBase)
  330. {
  331. t.kind = AutomationTargetKind::effectParam;
  332. t.slot = id.slot();
  333. t.param = p - flp::ControlId::pluginParamBase;
  334. }
  335. }
  336. return t;
  337. }
  338. bool synthFrom3xOsc (const std::vector<std::uint8_t>& state, SynthSettings& synth)
  339. {
  340. // version 10/11: 20 parameters + 4 bools (80 B); 12+: 21 parameters + 4 bools (+ HQ)
  341. if (state.size() < 84)
  342. return false;
  343. auto i32 = [&] (std::size_t offset) {
  344. return (std::int32_t) ((std::uint32_t) state[offset] | ((std::uint32_t) state[offset + 1] << 8)
  345. | ((std::uint32_t) state[offset + 2] << 16) | ((std::uint32_t) state[offset + 3] << 24));
  346. };
  347. const auto version = i32 (0);
  348. if (version < 10 || version > 64)
  349. return false;
  350. // parameter i is at 0x04 + 4i; (i + 1) = 7·osc + field, fields [mix, pan, shape, coarse, fine, spo, detune]
  351. auto param = [&] (int osc, int field) { return i32 ((std::size_t) (4 + 4 * (7 * osc + field - 1))); };
  352. const auto boolsAt = version >= 12 ? (std::size_t) 0x58 : (std::size_t) 0x54;
  353. const bool am = version >= 11 && state.size() > boolsAt + 3 && state[boolsAt + 3] != 0;
  354. // levels (§2.2): osc 3 takes mix3/128, osc 2 a share of the rest, osc 1 what remains
  355. const auto g3 = std::clamp (param (2, 0), 0, 128) / 128.0f;
  356. const auto rest = am ? 1.0f : 1.0f - g3;
  357. const auto g2 = rest * std::clamp (param (1, 0), 0, 128) / 128.0f;
  358. // with AM, osc 3 is not summed: its level becomes the modulation depth (REA_rodada6 §3)
  359. const std::array<float, 3> levels { std::max (0.0f, rest - g2), g2, g3 };
  360. synth.am = am;
  361. for (int o = 0; o < 3; ++o)
  362. {
  363. auto& osc = synth.osc[(std::size_t) o];
  364. switch (param (o, 2))
  365. {
  366. case 0: osc.wave = Waveform::sine; break;
  367. case 1: osc.wave = Waveform::triangle; break;
  368. case 2: osc.wave = Waveform::square; break;
  369. case 5: osc.wave = Waveform::noise; break;
  370. default: osc.wave = Waveform::saw; break; // 3 saw, 4 rounded saw, 6 custom without sample
  371. }
  372. const auto coarse = std::clamp (param (o, 3), -24, 24);
  373. osc.octave = coarse / 12; // truncates toward zero; the remainder becomes semitones
  374. osc.semitones = coarse - osc.octave * 12;
  375. // stereo detune only sounds on the right channel: half of it counts as average detune
  376. 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);
  377. osc.pan = std::clamp (param (o, 1), -64, 64) / 64.0f;
  378. osc.level = levels[(std::size_t) o];
  379. }
  380. return true;
  381. }
  382. namespace
  383. {
  384. // FL channel filter cutoff (Hz) for normalized Mod X `x` (REA_rodada4 §3); 20 kHz = open.
  385. double channelFilterHz (int type, double x)
  386. {
  387. constexpr double twoPi = 6.283185307179586;
  388. x = std::clamp (x, 0.0, 1.0);
  389. switch (type)
  390. {
  391. case 0:
  392. 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));
  393. case 1:
  394. case 2:
  395. case 3:
  396. case 4:
  397. case 5: return ((std::pow (51.0, x) - 1.0) * 0.0596 + 0.02) * 44100.0 / twoPi;
  398. case 6:
  399. 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);
  400. default: return 20000.0;
  401. }
  402. }
  403. } // namespace
  404. float filterEnvelopeOctaves (int modX, int type, int amount)
  405. {
  406. const auto x = std::clamp (modX / 256.0, 0.0, 1.0);
  407. const auto from = std::clamp (channelFilterHz (type, x), 20.0, 20000.0);
  408. const auto to = std::clamp (channelFilterHz (type, x + amount / 128.0), 20.0, 20000.0);
  409. return (float) std::log2 (to / from);
  410. }
  411. void synthFilterFromChannel (int modX, int modY, int type, float& cutoffHz, float& resonance, int& mode)
  412. {
  413. mode = type == 2 ? 1 : type == 3 ? 2 : type == 4 ? 3 : 0; // BP, HP, BS; the rest is low-pass
  414. const auto x = std::clamp (modX / 256.0, 0.0, 1.0);
  415. const auto r = std::clamp (modY / 256.0, 0.0, 1.0);
  416. 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
  417. resonance = 0.0f;
  418. if (type == 0) // Fast LP: 1 pole + feedback; feedback grows with Mod Y (approximation)
  419. resonance = (float) (r * 0.9);
  420. else if (type >= 1 && type <= 5) // LP/BP/HP/BS biquads (LPx2 = the LP twice)
  421. resonance = fromQ (r <= 0.0 ? 0.1 : (std::pow (51.0, 0.625 * r) - 1.0) * 0.4 + 0.1);
  422. else if (type == 6 || type == 7) // Chamberlin SVF
  423. resonance = fromQ (1.0 / (r <= 0.0 ? 1.0 : (r < 1.0 ? 1.0 - 0.8 * r : 0.2)));
  424. cutoffHz = (float) std::clamp (channelFilterHz (type, x), 20.0, 20000.0);
  425. }
  426. // The 364-byte channel-settings snapshot Fruity DX10 keeps (REA_rodada42 §3): the five 0xDA records (pan, volume,
  427. // cutoff, resonance, pitch; 68 bytes each) followed by Mod X at 0x15c, Mod Y at 0x160 and the filter type at 0x168. A
  428. // version-2 state carries its own (after the 22 parameters); for a version-1 state FL's host hands the plugin the
  429. // channel's records (the plugin asks for them when it has no snapshot — inference from the request, not observed).
  430. // Missing records take the plugin's defaults (neutral; the volume record with flag 4 and release tension −101).
  431. std::vector<std::uint8_t> dx10Snapshot (const flp::Channel& c)
  432. {
  433. std::vector<std::uint8_t> s (364, 0);
  434. auto put = [&] (std::size_t at, std::int32_t v) { std::memcpy (s.data() + at, &v, 4); };
  435. for (int k = 0; k < 5; ++k)
  436. {
  437. const auto& e = c.envelopes[(std::size_t) k];
  438. const auto base = (std::size_t) (0x44 * k);
  439. const std::int32_t defaults[17] = { k == 1 ? 4 : 0, 0, 100, 20000, 20000, 30000, 50, 20000, 0, 100, 20000, 0, 32950, 0, 0, 0, k == 1 ? -101 : 0 };
  440. for (int i = 0; i < 17; ++i)
  441. put (base + 4 * (std::size_t) i, defaults[i]);
  442. if (e.present)
  443. std::memcpy (s.data() + base, e.raw.data(), (std::size_t) std::min (e.rawSize, 0x44));
  444. }
  445. put (0x15c, c.hasLevels ? c.modX : 256);
  446. put (0x160, c.hasLevels ? c.modY : 0);
  447. put (0x168, c.hasLevels ? c.filterType : 0);
  448. return s;
  449. }
  450. void applyFlStretchPanel (SamplerSettings& s, int mode, int pitchCents, int mul, float timeTicks, double sampleSeconds, double bpm)
  451. {
  452. if (mode != 0)
  453. {
  454. s.keepPitch = true;
  455. s.stretchMethod = stretchMethodForFlMode (mode);
  456. s.pitch = std::clamp (s.pitch + std::clamp (pitchCents, -4800, 4800) / 100.0f, -24.0f, 24.0f);
  457. }
  458. if (timeTicks <= 0.0f && mul != 0 && sampleSeconds > 0.0 && bpm > 0.0)
  459. s.stretchBeats = std::clamp ((float) (sampleSeconds * std::pow (2.0, mul / 10000.0) * bpm / 60.0), 0.0f, 4096.0f);
  460. }
  461. void splitDrumChannel (Song& song, int channel, const std::vector<DrumPad>& pads)
  462. {
  463. if (channel < 0 || channel >= (int) song.channels.size() || pads.empty())
  464. return;
  465. const auto original = song.channels[(std::size_t) channel];
  466. const auto inserted = (int) pads.size() - 1; // the first pad takes the original channel's place
  467. std::vector<ChannelDef> padChannels;
  468. for (const auto& pad : pads)
  469. {
  470. ChannelDef def = original;
  471. def.name = original.name + " - " + pad.name;
  472. def.instrument = InstrumentKind::sampler;
  473. def.plugin = {};
  474. const auto single = pad.layers.size() == 1;
  475. def.samplePath = single ? pad.layers.front().path : std::string();
  476. def.zones = single ? std::vector<SampleZone> {} : pad.layers;
  477. for (auto& z : def.zones)
  478. z.rootKey = 60, z.lowKey = 0, z.highKey = 127; // the pad plays at the sample's pitch
  479. // volume: channel gain × pad gain (× the single layer's), mapped back to the channel curve
  480. const auto gain = channelGain (original.volume) * pad.gain * (single ? pad.layers.front().gain : 1.0f);
  481. def.volume = std::clamp ((float) (std::log (10.0 * gain + 1.0) / std::log (11.0)), 0.0f, 1.0f);
  482. def.pan = std::clamp (original.pan + pad.pan, -1.0f, 1.0f);
  483. def.sampler = {};
  484. def.sampler.pitch = std::clamp (original.sampler.pitch + pad.tune + (single ? pad.layers.front().tune : 0.0f), -24.0f, 24.0f);
  485. // kit-specific cut groups (don't mix with other channels' groups)
  486. def.cutGroup = pad.cutGroup > 0 ? 1000 * (channel + 1) + pad.cutGroup : 0;
  487. def.cutBy = pad.cutBy > 0 ? 1000 * (channel + 1) + pad.cutBy : 0;
  488. def.mixerTrack = std::clamp (original.mixerTrack + pad.mixerOffset, 0, maxMixerTracks - 1);
  489. padChannels.push_back (std::move (def));
  490. }
  491. song.channels[(std::size_t) channel] = padChannels.front();
  492. song.channels.insert (song.channels.begin() + channel + 1, padChannels.begin() + 1, padChannels.end());
  493. // channels after the original shift by `inserted` positions
  494. auto shift = [&] (int c) { return c > channel ? c + inserted : c; };
  495. for (auto& p : song.patterns)
  496. {
  497. std::vector<Note> kept;
  498. for (auto n : p.notes)
  499. {
  500. if (n.channel != channel)
  501. {
  502. n.channel = shift (n.channel);
  503. kept.push_back (n);
  504. continue;
  505. }
  506. for (int i = 0; i < (int) pads.size(); ++i)
  507. if (pads[(std::size_t) i].key == n.key)
  508. {
  509. n.channel = channel + i;
  510. n.key = 60;
  511. kept.push_back (n);
  512. break;
  513. }
  514. }
  515. p.notes = std::move (kept);
  516. p.sortNotes();
  517. // the Channel Rack's loop points: the pads loop like the kit did
  518. std::vector<ChannelLoop> loops;
  519. for (auto l : p.channelLoops)
  520. {
  521. if (l.channel != channel)
  522. {
  523. l.channel = shift (l.channel);
  524. loops.push_back (l);
  525. continue;
  526. }
  527. for (int i = 0; i < (int) pads.size(); ++i)
  528. loops.push_back ({ channel + i, l.setting });
  529. }
  530. p.channelLoops = std::move (loops);
  531. }
  532. song.forEachClipList ([&] (std::vector<Clip>& clips) {
  533. for (auto& c : clips)
  534. c.channel = c.channel >= 0 ? shift (c.channel) : c.channel;
  535. });
  536. // Layer children (round 164): shifted; a Layer of the kit plays every pad
  537. for (auto& l : song.channels)
  538. {
  539. std::vector<int> kids;
  540. for (const auto k : l.layer.children)
  541. {
  542. kids.push_back (shift (k));
  543. if (k == channel)
  544. for (int i = 1; i <= inserted; ++i)
  545. kids.push_back (channel + i);
  546. }
  547. l.layer.children = std::move (kids);
  548. }
  549. song.forEachTarget ([&] (AutomationTarget& t) {
  550. if ((t.kind == AutomationTargetKind::channelVolume || t.kind == AutomationTargetKind::channelPan
  551. || t.kind == AutomationTargetKind::channelParam) && t.index >= 0)
  552. t.index = shift (t.index);
  553. });
  554. }
  555. bool isFlSynthPresetPlugin (const std::string& pluginName)
  556. {
  557. static const char* const supported[] = { "3x osc", "sytrus", "harmor", "gms", "harmless", "minisynth", "fruity dx10", "dx10",
  558. "fruit kick", "ogun", "autogun", "sakura", "kepler", "boobass", "poizone", "bassdrum",
  559. "toxic biohazard" };
  560. const auto name = lowercase (pluginName);
  561. return std::any_of (std::begin (supported), std::end (supported), [&] (const char* n) { return name == n; });
  562. }
  563. std::optional<SynthSettings> synthFromFlPreset (const std::vector<std::uint8_t>& bytes)
  564. {
  565. // native GMS preset (.gmsynth): it is the plugin state without the "SSLF"
  566. if (bytes.size() >= 4 && (std::memcmp (bytes.data(), "4nyS", 4) == 0 || std::memcmp (bytes.data(), "3nyS", 4) == 0))
  567. {
  568. std::vector<std::uint8_t> state { 'S', 'S', 'L', 'F' };
  569. const auto n = (std::uint32_t) bytes.size();
  570. for (int i = 0; i < 4; ++i)
  571. state.push_back ((std::uint8_t) (n >> (8 * i)));
  572. state.insert (state.end(), bytes.begin(), bytes.end());
  573. SynthSettings synth;
  574. float gain = 1.0f;
  575. if (synthFromGms (state, 120.0, synth, gain))
  576. return synth;
  577. return std::nullopt;
  578. }
  579. try
  580. {
  581. auto project = flp::parseProject (bytes, true);
  582. if (project.channels.empty() || ! isFlSynthPresetPlugin (project.channels.front().pluginName))
  583. return std::nullopt;
  584. project.channels.front().type = flp::ChannelType::native; // native generator (the .fst doesn't say)
  585. FlpImportOptions options;
  586. options.threeOscAsSynth = true; // a 3x Osc preset fills the built-in synth
  587. const auto song = importFlp (project, options);
  588. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::sakura)
  589. {
  590. // the synth's preset button keeps the synth approximation of a Sakura patch
  591. SynthSettings synth;
  592. if (synthFromSakura (project.channels.front().pluginState, synth))
  593. return synth;
  594. }
  595. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::sytrus)
  596. {
  597. // likewise for Sytrus: the preset button fills the built-in synth with the 3-oscillator conversion
  598. SynthSettings synth;
  599. float gain = 1.0f;
  600. if (synthFromSytrus (project.channels.front().pluginState, song.bpm, synth, gain))
  601. return synth;
  602. }
  603. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::harmless)
  604. {
  605. // ... and of a Harmless patch
  606. SynthSettings synth;
  607. float gain = 1.0f;
  608. if (synthFromHarmless (project.channels.front().pluginState, song.bpm, synth, gain))
  609. return synth;
  610. }
  611. if (! song.channels.empty() && (song.channels.front().instrument == InstrumentKind::gms || song.channels.front().instrument == InstrumentKind::morphine))
  612. {
  613. // ... and of GMS / Morphine patches (their 3-oscillator / averaged-spectrum conversions)
  614. SynthSettings synth;
  615. float gain = 1.0f;
  616. const auto& st = project.channels.front().pluginState;
  617. if (song.channels.front().instrument == InstrumentKind::gms ? synthFromGms (st, song.bpm, synth, gain) : synthFromMorphine (st, synth, gain))
  618. return synth;
  619. }
  620. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::toxic)
  621. {
  622. // ... and of a Toxic Biohazard patch (the 2-operator conversion)
  623. SynthSettings synth;
  624. float gain = 1.0f;
  625. if (synthFromToxic (project.channels.front().pluginState, synth, gain))
  626. return synth;
  627. }
  628. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::harmor)
  629. {
  630. // ... and of a Harmor patch (the spectral-oscillator conversion)
  631. SynthSettings synth;
  632. float gain = 1.0f;
  633. if (synthFromHarmor (project.channels.front().pluginState, synth, gain))
  634. return synth;
  635. }
  636. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::dx10)
  637. {
  638. // ... and of a Fruity DX10 patch (the 3-oscillator FM conversion)
  639. SynthSettings synth;
  640. if (synthFromDX10 (project.channels.front().pluginState, synth))
  641. return synth;
  642. }
  643. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::kepler)
  644. {
  645. // ... and of a Kepler patch (the synth conversion)
  646. SynthSettings synth;
  647. float gain = 1.0f;
  648. if (synthFromKepler (project.channels.front().pluginState, synth, gain))
  649. return synth;
  650. }
  651. if (! song.channels.empty()
  652. && (song.channels.front().instrument == InstrumentKind::ogun || song.channels.front().instrument == InstrumentKind::autogun))
  653. {
  654. // ... and of an Ogun / Autogun patch (the spectral-oscillator conversion)
  655. SynthSettings synth;
  656. float gain = 1.0f;
  657. if (synthFromOgun (project.channels.front().pluginState, synth, gain))
  658. return synth;
  659. }
  660. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::poizone)
  661. {
  662. // ... and of a PoiZone patch (the 2-oscillator conversion)
  663. SynthSettings synth;
  664. float gain = 1.0f;
  665. if (synthFromPoiZone (project.channels.front().pluginState, synth, gain))
  666. return synth;
  667. }
  668. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::minisynth)
  669. {
  670. // ... and of a MiniSynth patch (the internal-synth conversion)
  671. SynthSettings synth;
  672. if (synthFromMiniSynth (project.channels.front().pluginState, song.bpm, synth))
  673. return synth;
  674. }
  675. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::fruitkick)
  676. {
  677. // ... and of Fruit Kick / BassDrum patches (their sine + pitch-sweep conversions)
  678. SynthSettings synth;
  679. if (synthFromFruitKick (project.channels.front().pluginState, synth))
  680. return synth;
  681. }
  682. if (! song.channels.empty() && song.channels.front().instrument == InstrumentKind::bassdrum)
  683. {
  684. SynthSettings synth;
  685. float gain = 1.0f;
  686. if (synthFromBassDrum (project.channels.front().pluginState, synth, gain))
  687. return synth;
  688. }
  689. if (song.channels.empty() || song.channels.front().instrument != InstrumentKind::synth)
  690. return std::nullopt;
  691. return song.channels.front().synth;
  692. }
  693. catch (const flp::Error&)
  694. {
  695. return std::nullopt;
  696. }
  697. }
  698. namespace
  699. {
  700. // Old FL saved its own Fruity effects as VST2 plugins inside Fruity Wrapper: the wrapper keeps their parameters as
  701. // 0…1 floats (REA_rodada89 §2). Fruity Compressor's 6 controls map linearly onto its native ranges — an untouched
  702. // instance's floats land exactly on the native defaults [DATA, RawFL demo] — so its native state (layout v1:
  703. // 6 × i32) is rebuilt; the lookahead flag has no VST2 parameter (off, not confirmed). Fruity Phaser likewise (round
  704. // 105). Other effects: defaults.
  705. std::vector<std::uint8_t> wrappedFruityState (const ForeignPlugin& plugin)
  706. {
  707. std::vector<std::uint8_t> native;
  708. FlVst2State state;
  709. // Fruity Phaser (REA_rodada105_phaser): the nine floats over the native ranges, except the stage count, which the
  710. // old plugin kept over 0…23 stages (FL's render test: an untouched instance saves 8/23 for the native 8 stages =
  711. // raw 7) [DATA; only the defaults were seen, the other values' mapping is not confirmed]
  712. if (plugin.name == "Fruity Phaser" && parseFlVst2State (plugin.state, state) && state.params.size() >= (std::size_t) phaserfx::params)
  713. {
  714. phaserfx::State s {};
  715. for (int k = 0; k < phaserfx::params; ++k)
  716. {
  717. const auto v = (double) std::clamp (state.params[(std::size_t) k], 0.0f, 1.0f);
  718. s[(std::size_t) k] = k == 5 ? std::clamp ((int) std::lround (v * 23.0) - 1, 0, phaserfx::rawMax[5])
  719. : (int) std::lround (v * phaserfx::rawMax[(std::size_t) k]);
  720. }
  721. return phaserfx::serialize (s);
  722. }
  723. if (plugin.name != "Fruity Compressor" || ! parseFlVst2State (plugin.state, state) || state.params.size() < fldyn::compressorControls)
  724. return native;
  725. auto put = [&native] (std::int32_t v) {
  726. for (int b = 0; b < 4; ++b)
  727. native.push_back ((std::uint8_t) ((std::uint32_t) v >> (8 * b)));
  728. };
  729. put (1);
  730. for (std::size_t k = 0; k < (std::size_t) fldyn::compressorControls; ++k)
  731. {
  732. const auto lo = fldyn::compressorMin[k], hi = fldyn::compressorMax[k];
  733. put (lo + (std::int32_t) std::lround (std::clamp (state.params[k], 0.0f, 1.0f) * (float) (hi - lo)));
  734. }
  735. return native;
  736. }
  737. } // namespace
  738. Song importFlp (const flp::Project& input, const FlpImportOptions& options)
  739. {
  740. // Patcher used as an instrument: the channel becomes the main generator inside it (REA_rodada14 §1)
  741. std::optional<flp::Project> unpacked;
  742. for (std::size_t i = 0; i < input.channels.size(); ++i)
  743. if (lowercase (input.channels[i].pluginName) == "patcher")
  744. if (const auto graph = parsePatcher (input.channels[i].pluginState); graph && graph->mainGenerator >= 0)
  745. {
  746. if (! unpacked)
  747. unpacked = input;
  748. const auto& node = graph->nodes[(std::size_t) graph->mainGenerator];
  749. unpacked->channels[i].pluginName = node.plugin;
  750. unpacked->channels[i].pluginState = node.state;
  751. }
  752. const auto& project = unpacked ? *unpacked : input;
  753. Song song;
  754. song.bpm = project.tempo > 0.0 ? project.tempo : 140.0;
  755. song.performanceMode = project.performanceMode; // (round 165m)
  756. song.autoCrossfades = project.autoCrossfades; // FL's Playlist "Automatic crossfades" (round 167a)
  757. song.beatsPerBar = std::clamp (project.beatsPerBar, 1, 32);
  758. song.swing = std::clamp (project.swing / 128.0f, 0.0f, 1.0f);
  759. song.playTruncatedNotes = project.playTruncatedNotes; // 0x1E (REA round 167g)
  760. song.fastDeclick = project.fastDeclick; // 0x28 (REA round 167h)
  761. song.panTriangular = (project.panLaw >> 1) == 1; // 0x17: FL saves 2 × its pan-law mode (REA round 167j §1)
  762. song.masterPitch = (float) std::clamp (project.mainPitch, -1200, 1200); // FL's render follows it (REA round 167g §1)
  763. song.channelGroups = project.filterGroups;
  764. song.info.title = project.title;
  765. song.info.author = project.artist;
  766. song.info.genre = project.genre;
  767. song.info.url = project.url;
  768. song.info.comments = project.comments;
  769. std::replace (song.info.comments.begin(), song.info.comments.end(), '\r', '\n'); // (FL saves CR line breaks)
  770. song.info.showOnOpen = project.showInfo; // 0x0A, Project info › Show on opening (REA round 167g)
  771. // 0xED: TDateTime days since 1899-12-30 (25569 days before 1970-01-01), FL's local time kept as it reads
  772. song.info.created = flDateTimeToUnix (project.createdDays);
  773. song.info.workSeconds = std::min (project.workDays, 36500.0) * 86400.0;
  774. // FL channels may have sparse indices; we map them to dense indices.
  775. std::map<int, int> channelMap;
  776. std::vector<std::pair<int, std::vector<DrumPad>>> drumKits; // FPC channels to split at the end
  777. std::optional<std::string> drumSynthDll; // the user's DrumSynth Live engine DLL, once checked ("" = not usable)
  778. // a sample on this PC: where the project says, else re-rooted from another PC's folders or next to the project
  779. // (`sampleUser` names what uses the sample, for the missing-files list; `record` false for paths only probed)
  780. std::string sampleUser;
  781. auto locateSample = [&] (const std::string& flPath, bool record = true) {
  782. auto found = locateFlSample (flPath, options.roots, options.projectFolder, options.fileExists);
  783. const auto saved = resolveFlPath (flPath, options.roots);
  784. if (found.empty())
  785. {
  786. if (const auto chosen = relocatedPath (options.relocations, saved); ! chosen.empty() && options.fileExists && options.fileExists (chosen))
  787. return chosen;
  788. if (record && options.report != nullptr)
  789. addMissingFile (options.report->missingFiles, saved, sampleUser);
  790. }
  791. else if (found != saved && options.report != nullptr)
  792. {
  793. ++options.report->relocatedSamples;
  794. if (record && std::none_of (options.report->relocatedFiles.begin(), options.report->relocatedFiles.end(),
  795. [&] (const auto& r) { return r.first == saved; }))
  796. options.report->relocatedFiles.push_back ({ saved, found });
  797. }
  798. return found;
  799. };
  800. for (const auto& c : project.channels)
  801. {
  802. // automation clips become Song::automations (further below), not channels
  803. if (c.type == flp::ChannelType::automationClip)
  804. continue;
  805. channelMap[c.index] = (int) song.channels.size();
  806. ChannelDef def;
  807. def.name = c.name.empty() ? "Channel " + std::to_string (c.index + 1) : c.name;
  808. sampleUser = (c.type == flp::ChannelType::audioClip ? "Audio clip: " : "") + def.name;
  809. def.instrument = guessInstrument (def.name, c.type);
  810. // FL's Layer channel (REA_rodada164a §1): its children (FL's channel indices, mapped below) and options
  811. if (c.type == flp::ChannelType::layer)
  812. {
  813. def.instrument = InstrumentKind::layer;
  814. def.layer.children = c.layerChildren;
  815. applyFlLayerFlags (c.layerFlags, def.layer);
  816. def.layer.fade = std::clamp ((float) c.layerFade / 256.0f, 0.0f, 1.0f);
  817. }
  818. // every channel's key region (REA_rodada164a §2): FL's 0…256 range is every key
  819. if (c.keyRegionLow > 0 || c.keyRegionHigh < 256)
  820. {
  821. def.keyLow = std::clamp (c.keyRegionLow, 0, 127);
  822. def.keyHigh = std::clamp (c.keyRegionHigh, def.keyLow, 127);
  823. }
  824. // FL synthesizer that becomes the internal synth: a preset matching the name (in FLEX, the name
  825. // of the preset chosen in the plugin says more than the channel's)
  826. if (def.instrument == InstrumentKind::synth)
  827. {
  828. def.synth = presetForChannelName (def.name);
  829. if (lowercase (c.pluginName) == "flex")
  830. if (const auto names = flexPresetName (c.pluginState))
  831. if (auto byPreset = presetForChannelName (names->second + " " + names->first); byPreset != SynthSettings {})
  832. def.synth = byPreset;
  833. }
  834. const auto isAudioClip = c.type == flp::ChannelType::audioClip;
  835. if ((c.type == flp::ChannelType::sampler || isAudioClip) && ! c.samplePath.empty() && options.fileExists)
  836. {
  837. const auto path = locateSample (c.samplePath);
  838. if (! path.empty())
  839. {
  840. def.instrument = isAudioClip ? InstrumentKind::audioClip : InstrumentKind::sampler;
  841. def.samplePath = path;
  842. }
  843. }
  844. if (isAudioClip && def.instrument != InstrumentKind::audioClip)
  845. def.instrument = InstrumentKind::audioClip; // no file: stays silent, but the clip remains in the playlist
  846. def.mixerTrack = std::clamp (c.mixerTrack, 0, maxMixerTracks - 1);
  847. def.muted = ! c.enabled; // switched off in FL's Channel Rack: its notes don't play (REA_rodada80 §3.1)
  848. def.soloLock = c.soloLock; // 0x20 "Lock active/mute state" (REA_rodada167l §5)
  849. def.ghostHidden = ! c.ghostShown; // 0x32: the channel's ghost notes in the Piano Roll (REA_rodada167l §5)
  850. if (c.colour != 0)
  851. def.colour = 0xFF000000u | c.colour;
  852. if (c.filterGroup >= 0 && c.filterGroup < (int) project.filterGroups.size())
  853. def.group = c.filterGroup;
  854. if (c.hasLevels)
  855. {
  856. def.volume = std::clamp (c.volume / 12800.0f, 0.0f, 1.0f); // same curve (channelGain)
  857. def.pan = std::clamp ((c.pan - 6400) / 6400.0f, -1.0f, 1.0f);
  858. def.sampler.pitch = std::clamp (c.pitchCents / 100.0f, -24.0f, 24.0f);
  859. }
  860. // level adjustments (0xE5): FL multiplies the channel volume by the adjustment through the same curve
  861. // (gain = f(volume)·f(volAdj), REA_rodada3 §2 [DECOMP]; an FL render of one channel with volAdj 7286 vs 12800
  862. // differs by −10.4 dB, f() gives −10.7 dB, a linear factor −4.9 dB) and adds the pan adjustment to the pan.
  863. if (c.hasLevelAdjust)
  864. {
  865. if (c.volAdj != 12800)
  866. {
  867. const auto g = channelGain (def.volume) * channelGain (std::clamp (c.volAdj / 12800.0f, 0.0f, 1.0f));
  868. def.volume = std::clamp ((float) (std::log (10.0 * g + 1.0) / std::log (11.0)), 0.0f, 1.0f);
  869. }
  870. if (c.panAdj != 0)
  871. def.pan = std::clamp (def.pan + c.panAdj / 6400.0f, -1.0f, 1.0f);
  872. }
  873. // sample root note: our sampler plays at the original pitch at C5 (60)
  874. if (c.rootNote >= 0 && c.rootNote <= 127)
  875. def.sampler.pitch = std::clamp (def.sampler.pitch + (float) (60 - c.rootNote), -24.0f, 24.0f);
  876. // an FL audio clip plays like a C5 note of its channel: the header pitch, the root note and the fine tune
  877. // transpose it too [FL: measured, REA_rodada164e-clippitch §2 — round 163 had dropped them on an assumption]
  878. def.swingMix = std::clamp (c.swingMix / 128.0f, 0.0f, 1.0f);
  879. def.cutGroup = c.cutGroup;
  880. def.cutBy = c.cutBy;
  881. // "cut itself" (group == cut by) and mono channel become the sampler's "cut"
  882. if ((c.cutGroup != 0 && c.cutGroup == c.cutBy) || c.maxVoices == 1)
  883. def.sampler.cut = true;
  884. def.synth.mono = c.monoFlag || c.maxVoices == 1;
  885. def.maxPolyphony = std::clamp (c.maxVoices, 0, 128); // FL's Polyphony › Max (0 = unlimited)
  886. // channel porta and slide time: n = round((27^(v/1024) - 1) * 48/26) ticks of 1/192 beat
  887. // (REA_rodada6 §4); the time also applies to notes with their own porta
  888. {
  889. const auto ticks = std::round ((std::pow (27.0, std::clamp (c.slideTime, 0, 1660) / 1024.0) - 1.0) * 48.0 / 26.0);
  890. def.synth.portaBeats = def.sampler.portaBeats = (float) std::max (1.0, ticks) / 192.0f;
  891. def.synth.porta = def.sampler.porta = c.portaFlag;
  892. }
  893. // the Misc tab (REA round 146b [EXEC: FL renders and saves]): time shift / gate, echo delay, tracking, main
  894. // pitch, pitch range, the arpeggiator
  895. {
  896. auto& m = def.misc;
  897. // FL rounds the shift to the project's ticks
  898. const auto filePpq = project.header.ppq > 0 ? project.header.ppq : 96;
  899. m.shiftBeats = c.timeShift > 0 ? (float) (std::nearbyint (channelmisc::flTimeKnobBeats (c.timeShift) * filePpq) / filePpq) : 0.0f;
  900. m.gateBeats = c.timeGate < 1446 ? (float) std::max (1.0 / filePpq, std::nearbyint (channelmisc::flTimeKnobBeats (c.timeGate) * filePpq) / filePpq) : 0.0f;
  901. m.fullPorta = c.fullPorta;
  902. m.echo.feedback = std::clamp (c.echoFeedback / 12800.0f, 0.0f, 2.0f);
  903. m.echo.pan = std::clamp ((c.echoPan - 6400) / 6400.0f, -1.0f, 1.0f);
  904. m.echo.pitch = (float) std::clamp (c.echoPitch, -4800, 4800);
  905. m.echo.echoes = std::clamp (c.echoes, 0, 16);
  906. m.echo.timeBeats = std::clamp (c.echoTime / 192.0f, 1.0f / 192.0f, 16.0f);
  907. m.echo.modX = std::clamp ((c.echoModX - 128) / 128.0f, -1.0f, 1.0f);
  908. m.echo.modY = std::clamp ((c.echoModY - 128) / 128.0f, -1.0f, 1.0f);
  909. m.echo.pingPong = (c.delayFlags & 2) != 0;
  910. m.echo.fat = (c.delayFlags & 4) != 0;
  911. for (int k = 0; k < 2; ++k)
  912. if (const auto& t = c.tracking[(std::size_t) k]; t.present)
  913. {
  914. auto& to = k == 0 ? m.velocity : m.key;
  915. to.mid = t.mid;
  916. to.pan = std::clamp (t.pan / 64.0f, -1.0f, 1.0f);
  917. to.modX = std::clamp (t.modX / 256.0f, -1.0f, 1.0f);
  918. to.modY = std::clamp (t.modY / 256.0f, -1.0f, 1.0f);
  919. }
  920. m.pitchRange = std::clamp (c.pitchRange, 0, 48);
  921. m.mainPitch = c.mainPitch;
  922. // the root note keyboard and Add to key (round 149); a sampler's root is folded into its pitch above
  923. if (c.rootNote >= 0 && c.rootNote <= 127)
  924. m.rootNote = c.rootNote;
  925. m.addToKey = c.addToKey;
  926. m.fineTune = (float) std::clamp (c.fineTune, -100, 100);
  927. // arpeggiator: FL's directions 1 up, 2 down, 3 up-down bounce, 4 up-down sticky, 5 random
  928. static constexpr int directions[] = { 0, 1, 2, 3, 5, 4 };
  929. if (c.arpDirection >= 1 && c.arpDirection <= 5)
  930. {
  931. auto& a = def.arp;
  932. a.direction = directions[c.arpDirection];
  933. a.range = std::clamp (c.arpRange, 1, 4);
  934. a.stepBeats = (float) std::clamp (channelmisc::flTimeKnobBeats (c.arpTime), 1.0 / 192.0, 4.0);
  935. a.gate = std::clamp (c.arpGate / 48.0f, 0.05f, 128.0f / 48.0f);
  936. a.slide = c.arpSlide;
  937. a.octaveRepeat = std::clamp (c.arpRepeat, 0, 16); // 0: FL's chord at once (round 149)
  938. a.chordSustain = c.arpChord != -2;
  939. if (c.arpChord == 0)
  940. a.chord = { 0 }; // "None": the root, stepping by octaves
  941. else if (c.arpChord > 0 && options.readFile && ! options.roots.factoryData.empty())
  942. {
  943. const auto map = options.readFile (options.roots.factoryData + "\\System\\Config\\Chords.map");
  944. a.chord = channelmisc::chordFromFlMap (std::string (map.begin(), map.end()), c.arpChord);
  945. }
  946. }
  947. }
  948. // volume envelope (record 1 of 0xDA) -> sampler ADSR
  949. const auto& volumeEnvelope = c.envelopes[1];
  950. const auto hasVolumeEnvelope = volumeEnvelope.present && volumeEnvelope.enabled;
  951. if (hasVolumeEnvelope)
  952. {
  953. const auto& env = volumeEnvelope;
  954. const auto beats = (env.flags & 1) != 0; // tempo-synced: units in beats
  955. auto seconds = [&] (int v) {
  956. const auto t = flp::Channel::envelopeTime (v);
  957. return (float) (beats ? t * 2.0 * 60.0 / song.bpm : t); // 0.128 beat instead of 0.064 s
  958. };
  959. def.sampler.attack = std::clamp (seconds (env.attack), 0.0f, 2.0f);
  960. def.sampler.decay = std::clamp (seconds (env.decay), 0.0f, 10.0f);
  961. def.sampler.sustain = std::clamp (env.sustain / 128.0f, 0.0f, 1.0f);
  962. def.sampler.release = std::clamp (std::max (seconds (env.release), 0.002f), 0.0f, 4.0f); // envelope on: the note ends
  963. // FL's own articulator (delay, hold, tensions, tick steps; REA_rodada69 §3) from the record as stored
  964. if (env.rawSize >= 68 && c.type == flp::ChannelType::sampler)
  965. {
  966. def.sampler.flVolumeEnvelope.resize (18);
  967. std::memcpy (def.sampler.flVolumeEnvelope.data(), env.raw.data(), 68);
  968. def.sampler.flVolumeEnvelope[17] = project.header.ppq > 0 ? project.header.ppq : 96;
  969. }
  970. }
  971. // FL's whole native sampler voice (REA_rodada76): the five articulator records as stored (a missing one keeps
  972. // the plugins' default record), Mod X/Y, filter type, PPQ
  973. if (c.type == flp::ChannelType::sampler && def.instrument == InstrumentKind::sampler)
  974. {
  975. const auto defaults = flvp::defaultSnapshot();
  976. def.sampler.flChannel.assign (90, 0);
  977. for (int k = 0; k < 5; ++k)
  978. {
  979. const auto& env = c.envelopes[(std::size_t) k];
  980. const auto* src = env.rawSize >= 68 ? env.raw.data() : defaults.data() + 0x44 * k;
  981. std::memcpy (def.sampler.flChannel.data() + 17 * k, src, 68);
  982. }
  983. def.sampler.flChannel[85] = c.modX;
  984. def.sampler.flChannel[86] = c.modY;
  985. def.sampler.flChannel[87] = c.filterType;
  986. def.sampler.flChannel[88] = project.header.ppq > 0 ? project.header.ppq : 96;
  987. def.sampler.flChannel[89] = project.panLaw;
  988. }
  989. // channel filter (Mod X/Y + type from 0xDB) applies to the sampler too
  990. synthFilterFromChannel (c.modX, c.modY, c.filterType, def.sampler.cutoff, def.sampler.resonance, def.sampler.filterType);
  991. // channel cutoff (record 2) and pitch (record 4) envelopes
  992. auto modEnvelope = [&] (const flp::Channel::Envelope& env, float amount) {
  993. ModEnvelope m;
  994. if (! env.present || ! env.enabled || amount == 0.0f)
  995. return m;
  996. const auto beats = (env.flags & 1) != 0;
  997. auto seconds = [&] (int v) {
  998. const auto t = flp::Channel::envelopeTime (v);
  999. return (float) std::clamp (beats ? t * 2.0 * 60.0 / song.bpm : t, 0.0, 20.0);
  1000. };
  1001. m.amount = amount;
  1002. m.attack = seconds (env.attack);
  1003. m.hold = seconds (env.hold);
  1004. m.decay = seconds (env.decay);
  1005. m.sustain = std::clamp (env.sustain / 128.0f, 0.0f, 1.0f);
  1006. m.release = seconds (env.release);
  1007. return m;
  1008. };
  1009. const auto filterEnv = modEnvelope (c.envelopes[2], filterEnvelopeOctaves (c.modX, c.filterType, c.envelopes[2].amount));
  1010. const auto pitchEnv = modEnvelope (c.envelopes[4], std::clamp (c.envelopes[4].amount, -2400, 2400) / 100.0f);
  1011. def.sampler.filterEnv = filterEnv;
  1012. def.sampler.pitchEnv = pitchEnv;
  1013. // channel LFOs (records 0 pan, 1 volume, 2 cutoff, 4 pitch; REA_rodada6 §2)
  1014. {
  1015. auto lfoFrom = [&] (const flp::Channel::Envelope& env, float amount) {
  1016. ChannelLfo l;
  1017. if (! env.present || env.lfoAmount == 0 || amount == 0.0f)
  1018. return l;
  1019. l.sync = (env.flags & 0x02) != 0;
  1020. auto time = [&] (int v) { // seconds, or beats when synced (double the scale)
  1021. const auto t = flp::Channel::envelopeTime (v);
  1022. return (float) std::clamp (l.sync ? t * 2.0 : t, 0.0, 64.0);
  1023. };
  1024. l.amount = amount;
  1025. l.period = std::max (0.01f, time (env.lfoSpeed));
  1026. l.shape = std::clamp (env.lfoShape, 0, 2);
  1027. l.delay = time (env.lfoDelay);
  1028. l.attack = time (env.lfoAttack);
  1029. l.global = (env.flags & 0x20) != 0;
  1030. return l;
  1031. };
  1032. std::array<ChannelLfo, lfoTargets> lfo {};
  1033. lfo[lfoPan] = lfoFrom (c.envelopes[0], std::clamp (c.envelopes[0].lfoAmount, -64, 64) / 64.0f);
  1034. lfo[lfoVolume] = lfoFrom (c.envelopes[1], std::clamp (c.envelopes[1].lfoAmount, -128, 128) / 128.0f);
  1035. lfo[lfoCutoff] = lfoFrom (c.envelopes[2], filterEnvelopeOctaves (c.modX, c.filterType, c.envelopes[2].lfoAmount));
  1036. lfo[lfoPitch] = lfoFrom (c.envelopes[4], std::clamp (c.envelopes[4].lfoAmount, -2400, 2400) / 100.0f);
  1037. def.sampler.lfo = lfo;
  1038. def.synth.lfo = lfo;
  1039. }
  1040. // third-party plugin (VST/CLAP) in Fruity Wrapper: the app looks for the same installed plugin;
  1041. // until then (or if not found) the channel stays on the internal synth
  1042. // FL generators with samples (REA_rodada9): DirectWave becomes a multi-sample sampler; FPC is
  1043. // split into one channel per pad at the end of the import (notes go to the pad by key)
  1044. auto existing = [&] (std::string path) { return locateSample (path); };
  1045. auto installed = [&] (std::string path) { return locateSample (path, false); }; // FL's own data (FL Keys wavetables)
  1046. // DirectWave: the exact engine (REA_rodada72); the multi-sample sampler stays as the fallback
  1047. bool directWaveExact = false;
  1048. if (c.pluginName == "DirectWave")
  1049. directWaveExact = dw::importChannel (def, c.pluginState, existing, options.readFile, options.saveEmbedded);
  1050. if (c.pluginName == "DirectWave" && ! directWaveExact)
  1051. if (auto program = directWaveProgram (c.pluginState))
  1052. {
  1053. std::vector<SampleZone> zones;
  1054. for (std::size_t i = 0; i < program->zones.size(); ++i)
  1055. {
  1056. auto z = program->zones[i];
  1057. auto path = existing (z.path);
  1058. // file missing on this machine: use the audio the project stored with it
  1059. if (path.empty() && i < program->embeddedWav.size() && ! program->embeddedWav[i].empty() && options.saveEmbedded)
  1060. path = options.saveEmbedded (program->embeddedWav[i], def.name + " " + std::to_string (i + 1));
  1061. if (! path.empty())
  1062. {
  1063. z.path = path;
  1064. zones.push_back (std::move (z));
  1065. }
  1066. }
  1067. if (! zones.empty())
  1068. {
  1069. def.instrument = InstrumentKind::sampler;
  1070. def.zones = std::move (zones);
  1071. def.sampler.attack = std::clamp (program->attack, 0.0f, 2.0f);
  1072. def.sampler.decay = std::clamp (program->decay, 0.0f, 10.0f);
  1073. def.sampler.sustain = program->sustain;
  1074. def.sampler.release = std::clamp (std::max (program->release, 0.01f), 0.0f, 4.0f);
  1075. }
  1076. }
  1077. // Fruity Slicer / Slicex: sampler with the slices (slice i plays on key 60 + i, at the sample's pitch)
  1078. {
  1079. const auto name = lowercase (c.pluginName);
  1080. std::optional<SlicedSample> sliced;
  1081. if (name == "fruity slicer")
  1082. sliced = fruitySlicer (c.pluginState);
  1083. else if (name == "slicex")
  1084. sliced = slicex (c.pluginState);
  1085. if (sliced)
  1086. {
  1087. std::string path;
  1088. if (! sliced->embeddedWav.empty() && options.saveEmbedded) // audio that only exists inside the project
  1089. path = options.saveEmbedded (sliced->embeddedWav, def.name);
  1090. if (path.empty())
  1091. path = existing (sliced->path);
  1092. if (! path.empty())
  1093. {
  1094. auto positions = sliced->positions;
  1095. std::int64_t frames = 0;
  1096. if (positions.empty()) // Slicex: the slices are the WAV "cue" points
  1097. {
  1098. const auto bytes = ! sliced->embeddedWav.empty() ? sliced->embeddedWav
  1099. : options.readFile ? options.readFile (path) : std::vector<std::uint8_t> {};
  1100. positions = wavCuePoints (bytes, frames);
  1101. }
  1102. if (frames <= 0 && options.sampleFrames)
  1103. frames = options.sampleFrames (path);
  1104. def.instrument = InstrumentKind::sampler;
  1105. def.samplePath = path;
  1106. def.sampler.pitch = std::clamp (def.sampler.pitch + sliced->pitchCents / 100.0f, -24.0f, 24.0f);
  1107. // Slicex's master volume (REA_rodada69 §5): a single full-range zone carries the gain
  1108. if (sliced->gain != 1.0f && ! path.empty())
  1109. {
  1110. SampleZone zone;
  1111. zone.path = path;
  1112. zone.gain = sliced->gain;
  1113. def.zones = { zone };
  1114. }
  1115. if (frames > 0)
  1116. for (auto p : positions)
  1117. if (p >= 0 && p < frames)
  1118. def.sampler.slices.push_back ((float) ((double) p / (double) frames));
  1119. }
  1120. }
  1121. }
  1122. // FL Keys: FL's engine on the wavetable (.wti) that ships with FL (REA_rodada69 §8); the zoned sampler is the
  1123. // fallback when the wavetable cannot be read
  1124. bool flKeysExact = false;
  1125. if (c.pluginName == "FL Keys" && options.readFile && ! options.roots.factoryData.empty())
  1126. flKeysExact = flkeys::importChannel (def, c.pluginState, options.roots.factoryData + "\\Plugins\\Fruity\\Generators\\FL Keys\\Wavtables",
  1127. options.readFile, installed, options.saveEmbedded);
  1128. if (c.pluginName == "FL Keys" && ! flKeysExact && options.readFile && ! options.roots.factoryData.empty())
  1129. if (const auto set = flKeysSet (c.pluginState))
  1130. {
  1131. const auto folder = options.roots.factoryData + "\\Plugins\\Fruity\\Generators\\FL Keys\\Wavtables";
  1132. const auto wtiBytes = options.readFile (folder + "\\" + *set + ".wti");
  1133. const std::string wti (wtiBytes.begin(), wtiBytes.end());
  1134. std::vector<std::uint8_t> rawData;
  1135. if (wti.find ("filetype=raw") != std::string::npos)
  1136. if (const auto file = wti.find ("samplefile="); file != std::string::npos)
  1137. {
  1138. auto name = wti.substr (file + 11, wti.find_first_of ("\r\n", file) - file - 11);
  1139. rawData = options.readFile (folder + "\\" + name);
  1140. }
  1141. std::vector<SampleZone> zones;
  1142. for (auto z : flKeysZones (wti, folder, rawData, options.saveEmbedded))
  1143. if (z.path = installed (z.path); ! z.path.empty())
  1144. zones.push_back (std::move (z));
  1145. if (! zones.empty())
  1146. {
  1147. def.instrument = InstrumentKind::sampler;
  1148. def.zones = std::move (zones);
  1149. def.sampler.release = 0.4f; // the piano releases the note with a short release
  1150. }
  1151. }
  1152. // Wave Traveller: FL's engine (REA_rodada167f) on FL's state, with the sample its state names (FL loads that
  1153. // one, not the channel's). Without the sample the channel stays silent, as in FL (the plugin refuses notes)
  1154. if (c.pluginName == "Wave Traveller")
  1155. {
  1156. wavetrav::State wt;
  1157. if (wavetrav::parseState (c.pluginState, wt))
  1158. {
  1159. def.instrument = InstrumentKind::wavetraveller;
  1160. def.pluginState = c.pluginState;
  1161. def.samplePath = wt.samplePath.empty() ? std::string() : existing (wt.samplePath);
  1162. }
  1163. }
  1164. // Fruity Envelope Controller: "controller" channel (silent) that triggers the envelopes from notes
  1165. if ((c.pluginName == "Fruity Envelope Controller" && parseEnvelopeController (c.pluginState))
  1166. || (c.pluginName == "Fruity Keyboard Controller" && parseKeyboardController (c.pluginState)))
  1167. {
  1168. def.instrument = InstrumentKind::controller;
  1169. def.controllerState = c.pluginState;
  1170. }
  1171. // Fruity DrumSynth Live: its engine with all 120 patches (REA_rodada30 §1); the recorded waveforms some patches
  1172. // use are read at run time from the user's own engine DLL (without it they are silent, the synthesis is not).
  1173. // Fallback when the state can't be parsed: the FL drum sample with the same name as the editor's sound
  1174. if (c.pluginName == "Fruity DrumSynth Live")
  1175. {
  1176. if (auto params = drumSynthLiveParams (c.pluginState))
  1177. {
  1178. def.instrument = InstrumentKind::drumsynth;
  1179. def.modelParams = std::move (*params);
  1180. if (! drumSynthDll)
  1181. {
  1182. drumSynthDll = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Fruity DrumSynth Live\\drumsynth_eng_x64.dll",
  1183. options.roots);
  1184. if (drumSynthDll->empty() || ! options.fileExists || ! options.fileExists (*drumSynthDll) || ! drumSynthDllUsable (*drumSynthDll))
  1185. drumSynthDll = std::string();
  1186. }
  1187. def.samplePath = *drumSynthDll;
  1188. }
  1189. else if (const auto sound = drumSynthLiveSound (c.pluginState))
  1190. for (const auto& candidate : drumSampleCandidates (*sound))
  1191. if (auto path = locateSample (candidate, false); ! path.empty())
  1192. {
  1193. def.instrument = InstrumentKind::sampler;
  1194. def.samplePath = std::move (path);
  1195. break;
  1196. }
  1197. }
  1198. if (c.pluginName == "FPC")
  1199. if (auto pads = fpcPads (c.pluginState))
  1200. {
  1201. std::vector<DrumPad> found;
  1202. for (auto pad : *pads)
  1203. {
  1204. std::vector<SampleZone> layers;
  1205. for (auto layer : pad.layers)
  1206. if (layer.path = existing (layer.path); ! layer.path.empty())
  1207. layers.push_back (std::move (layer));
  1208. pad.layers = std::move (layers);
  1209. if (! pad.layers.empty())
  1210. found.push_back (std::move (pad));
  1211. }
  1212. if (! found.empty())
  1213. drumKits.push_back ({ (int) song.channels.size(), std::move (found) });
  1214. }
  1215. if (c.pluginName == "Fruity Wrapper" && parseFlWrapper (c.pluginState, def.plugin.foreign))
  1216. {
  1217. def.plugin.name = def.plugin.foreign.name;
  1218. applyFlWrapperOptions (def.plugin.foreign, def.plugin);
  1219. def.plugin.midiInPort = def.plugin.foreign.midiInPort; // the MIDI Out channels on that port play it
  1220. def.plugin.midiOutPort = def.plugin.foreign.midiOutPort; // its notes play the plugins on that port
  1221. }
  1222. // MIDI Out (REA_rodada16 §1): a silent channel whose notes the renderer sends to the plugins on its port
  1223. if (lowercase (c.pluginName) == "midi out" && c.pluginState.size() >= 28)
  1224. {
  1225. def.instrument = InstrumentKind::midiOut;
  1226. def.pluginState = c.pluginState;
  1227. }
  1228. // Voltage Controller (REA_rodada164a §6): its notes as control voltages; FL's state kept as its settings
  1229. if (c.pluginName == "Fruity Voltage Controller" && voltage::parse (c.pluginState))
  1230. {
  1231. def.instrument = InstrumentKind::voltage;
  1232. def.pluginState = c.pluginState;
  1233. }
  1234. // Dashboard (REA_rodada164f-flimport): its value controls as LYNX's Dashboard panel (FL's state kept, for its
  1235. // controller links below)
  1236. if (c.pluginName == "Dashboard")
  1237. if (auto dash = surface::parseFlDashboard (c.pluginState))
  1238. {
  1239. def.instrument = InstrumentKind::dashboard;
  1240. def.patcher.surface = std::move (dash->controls);
  1241. def.pluginState = c.pluginState;
  1242. }
  1243. // FL's VFX plugins (round 164b): note processors, with FL's state as it is
  1244. if (const auto kind = vfx::kindOfFlName (c.pluginName))
  1245. {
  1246. def.instrument = InstrumentKind::vfx;
  1247. vfx::State vs;
  1248. vs.kind = *kind;
  1249. vs.fl = c.pluginState.empty() ? vfx::defaultState (*kind) : c.pluginState;
  1250. def.pluginState = vfx::writeState (vs);
  1251. }
  1252. // Fruit Kick, MiniSynth, ... (REA_rodada10): approximated by the internal synth; the channel LFOs are kept
  1253. bool adoptedFromPlugin = false;
  1254. if (def.instrument == InstrumentKind::synth)
  1255. {
  1256. const auto name = lowercase (c.pluginName);
  1257. SynthSettings fromPlugin;
  1258. float pluginGain = 1.0f;
  1259. auto adopt = [&] {
  1260. for (int i = 0; i < lfoTargets; ++i)
  1261. if (def.synth.lfo[(std::size_t) i].amount != 0.0f)
  1262. fromPlugin.lfo[(std::size_t) i] = def.synth.lfo[(std::size_t) i];
  1263. def.synth = fromPlugin;
  1264. adoptedFromPlugin = true;
  1265. const auto g = channelGain (def.volume) * pluginGain;
  1266. def.volume = std::clamp ((float) (std::log (10.0 * g + 1.0) / std::log (11.0)), 0.0f, 1.0f);
  1267. };
  1268. if (name == "3x osc" && ! options.threeOscAsSynth && threeOscStateUsable (c.pluginState))
  1269. {
  1270. // FL's 3x Osc engine (REA_rodada47) with the channel settings its voice processor keeps (the channel's
  1271. // 0xDA/0xDB records, which FL restores after the plugin state) and the project's PPQ for the envelope
  1272. // ticks; the channel's sample (if any) is the custom wave of shape 6. The internal-synth conversion
  1273. // stays as the fallback (state unreadable)
  1274. def.instrument = InstrumentKind::threeosc;
  1275. const auto fromChannel = c.hasLevels || std::any_of (c.envelopes.begin(), c.envelopes.end(), [] (const auto& e) { return e.present; });
  1276. def.pluginState = threeOscNormalisedState (c.pluginState, fromChannel ? dx10Snapshot (c) : std::vector<std::uint8_t> {});
  1277. def.modelParams = { (float) (project.header.ppq > 0 ? project.header.ppq : 96) };
  1278. if (! c.samplePath.empty() && options.fileExists)
  1279. {
  1280. auto path = resolveFlPath (c.samplePath, options.roots);
  1281. if (! path.empty() && (path[0] == '\\' || path[0] == '/') && ! options.roots.factoryData.empty())
  1282. path = options.roots.factoryData + "\\Data" + path; // (old presets: relative to FL's Data folder)
  1283. if (! path.empty() && ! options.fileExists (path) && options.fileExists (path + ".wav"))
  1284. path += ".wav";
  1285. if (! path.empty() && options.fileExists (path))
  1286. def.samplePath = path;
  1287. }
  1288. adoptedFromPlugin = true;
  1289. }
  1290. else if (name == "fruity granulizer" && granulizerStateUsable (c.pluginState))
  1291. {
  1292. // FL's Fruity Granulizer engine (REA_rodada67) on the channel's sample (FL hands it to the plugin), with the
  1293. // channel settings its voice processor keeps and the project's PPQ, as 3x Osc. Without the sample the
  1294. // channel stays silent, as in FL (the plugin refuses notes)
  1295. def.instrument = InstrumentKind::granulizer;
  1296. const auto fromChannel = c.hasLevels || std::any_of (c.envelopes.begin(), c.envelopes.end(), [] (const auto& e) { return e.present; });
  1297. def.pluginState = granulizerNormalisedState (c.pluginState, fromChannel ? dx10Snapshot (c) : std::vector<std::uint8_t> {});
  1298. def.modelParams = { (float) (project.header.ppq > 0 ? project.header.ppq : 96) };
  1299. if (! c.samplePath.empty() && options.fileExists)
  1300. {
  1301. auto path = resolveFlPath (c.samplePath, options.roots);
  1302. if (! path.empty() && (path[0] == '\\' || path[0] == '/') && ! options.roots.factoryData.empty())
  1303. path = options.roots.factoryData + "\\Data" + path;
  1304. if (! path.empty() && ! options.fileExists (path) && options.fileExists (path + ".wav"))
  1305. path += ".wav";
  1306. if (! path.empty() && options.fileExists (path))
  1307. def.samplePath = path;
  1308. }
  1309. adoptedFromPlugin = true;
  1310. }
  1311. else if (name == "harmless")
  1312. {
  1313. // FL's additive engine (REA_rodada32); the internal synth approximation stays as the fallback
  1314. if (auto params = harmlessParams (c.pluginState))
  1315. {
  1316. def.instrument = InstrumentKind::harmless;
  1317. def.modelParams = std::move (*params);
  1318. adoptedFromPlugin = true;
  1319. // rack compressor: Harmless's own preset <n>.fst from the user's installation (REA_rodada36 §2)
  1320. const auto compType = (int) def.modelParams[(std::size_t) harmlessComboIndex + 3];
  1321. if (compType > 0)
  1322. {
  1323. const auto path = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Harmless\\Data\\Compression\\"
  1324. + std::to_string (compType) + ".fst",
  1325. options.roots);
  1326. std::optional<std::vector<std::uint8_t>> state;
  1327. if (! path.empty() && options.readFile && (! options.fileExists || options.fileExists (path)))
  1328. state = hlfx::maximusStateFromFst (options.readFile (path));
  1329. if (state && hlfx::makeMaximusPreset (*state) != nullptr)
  1330. {
  1331. def.modelParams.push_back ((float) state->size());
  1332. for (const auto byte : *state)
  1333. def.modelParams.push_back ((float) byte);
  1334. }
  1335. else if (options.report != nullptr)
  1336. ++options.report->partialEffects["Harmless compressor (preset not found)"];
  1337. }
  1338. }
  1339. else if (synthFromHarmless (c.pluginState, song.bpm, fromPlugin, pluginGain))
  1340. adopt();
  1341. }
  1342. else if (name == "fruit kick")
  1343. {
  1344. // FL's Fruit Kick engine with its voice framework (REA_rodada43 §1). A version-0 state has no envelope
  1345. // snapshot of its own: FL hands the plugin the channel's envelope/filter records, so they are appended
  1346. // to it. The sine + pitch-envelope conversion stays as the fallback for unreadable states.
  1347. if (fruitKickStateUsable (c.pluginState))
  1348. {
  1349. // the same 364-byte channel snapshot as DX10's (REA_rodada42 §3): five 68-byte records + Mod X/Y + type
  1350. const auto snap = dx10Snapshot (c);
  1351. std::vector<std::vector<std::uint8_t>> records;
  1352. for (int k = 0; k < 5; ++k)
  1353. records.emplace_back (snap.begin() + 68 * k, snap.begin() + 68 * (k + 1));
  1354. std::int32_t cut = 256, res = 0, type = 0;
  1355. std::memcpy (&cut, snap.data() + 0x15c, 4);
  1356. std::memcpy (&res, snap.data() + 0x160, 4);
  1357. std::memcpy (&type, snap.data() + 0x168, 4);
  1358. def.instrument = InstrumentKind::fruitkick;
  1359. def.pluginState = fruitKickWithChannelEnvelope (c.pluginState, records, cut, res, type);
  1360. adoptedFromPlugin = true;
  1361. if (options.report != nullptr)
  1362. for (const auto& f : fruitKickFallbacks (def.pluginState))
  1363. ++options.report->partialEffects["Fruit Kick: " + f];
  1364. }
  1365. else if (synthFromFruitKick (c.pluginState, fromPlugin))
  1366. adopt();
  1367. }
  1368. else if (name == "minisynth")
  1369. {
  1370. // FL's MiniSynth engine from the raw state (REA_rodada41) with its wave tables built at run time from the
  1371. // installation's oscdata.dat; the internal-synth conversion stays as the fallback (state unreadable or
  1372. // file not found)
  1373. const auto oscdata = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Minisynth\\oscdata.dat", options.roots);
  1374. if (miniSynthStateUsable (c.pluginState) && ! oscdata.empty() && options.fileExists && options.fileExists (oscdata))
  1375. {
  1376. def.instrument = InstrumentKind::minisynth;
  1377. def.pluginState = c.pluginState;
  1378. def.samplePath = oscdata;
  1379. adoptedFromPlugin = true;
  1380. }
  1381. else if (synthFromMiniSynth (c.pluginState, song.bpm, fromPlugin))
  1382. adopt();
  1383. }
  1384. else if (name == "fruity dx10" || name == "dx10")
  1385. {
  1386. // FL's FM engine from the raw state (REA_rodada42), with the channel settings its voice processor
  1387. // keeps (a version-2 state's own snapshot, else the channel's 0xDA/0xDB records) and the project's PPQ
  1388. // for the envelope ticks; the 3-oscillator FM approximation stays as a fallback
  1389. if (auto st = dx10StateWithSnapshot (c.pluginState, dx10Snapshot (c)); ! st.empty())
  1390. {
  1391. def.instrument = InstrumentKind::dx10;
  1392. def.pluginState = std::move (st);
  1393. def.modelParams = { (float) (project.header.ppq > 0 ? project.header.ppq : 96) };
  1394. adoptedFromPlugin = true;
  1395. }
  1396. else if (synthFromDX10 (c.pluginState, fromPlugin))
  1397. adopt();
  1398. }
  1399. else if (name == "sytrus")
  1400. {
  1401. // FL's Sytrus engine from the raw state (REA_rodada31); the 3-oscillator conversion stays as a fallback
  1402. if (sytrus::stateUsable (c.pluginState))
  1403. {
  1404. def.instrument = InstrumentKind::sytrus;
  1405. def.pluginState = c.pluginState;
  1406. adoptedFromPlugin = true;
  1407. }
  1408. else if (synthFromSytrus (c.pluginState, song.bpm, fromPlugin, pluginGain))
  1409. adopt();
  1410. }
  1411. else if (name == "harmor")
  1412. {
  1413. // FL's additive engine from the raw state (REA_rodada34); the spectral-oscillator conversion stays as
  1414. // the fallback for states the engine can't read
  1415. if (harmorStateUsable (c.pluginState))
  1416. {
  1417. def.instrument = InstrumentKind::harmor;
  1418. // an old (version 11…15) state is stored in the current layout, as FL re-saves it (REA_rodada165g-flbeta165s §1)
  1419. def.pluginState = harmorUpgradeState (c.pluginState).value_or (c.pluginState);
  1420. adoptedFromPlugin = true;
  1421. // rack compressor: Harmor's own preset System\Compression\<n>.fst from the user's installation
  1422. // (REA_rodada38); its Maximus state goes into modelParams (size, bytes…)
  1423. const auto compType = harmorCompressorType (c.pluginState);
  1424. if (compType > 0)
  1425. {
  1426. const auto path = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Harmor\\System\\Compression\\"
  1427. + std::to_string (compType) + ".fst",
  1428. options.roots);
  1429. std::optional<std::vector<std::uint8_t>> state;
  1430. if (! path.empty() && options.readFile && (! options.fileExists || options.fileExists (path)))
  1431. state = hlfx::maximusStateFromFst (options.readFile (path));
  1432. if (state && hlfx::makeMaximusPreset (*state) != nullptr)
  1433. {
  1434. def.modelParams.clear();
  1435. def.modelParams.push_back ((float) state->size());
  1436. for (const auto byte : *state)
  1437. def.modelParams.push_back ((float) byte);
  1438. }
  1439. else if (options.report != nullptr)
  1440. ++options.report->partialEffects["Harmor compressor (preset not found)"];
  1441. }
  1442. }
  1443. else if (synthFromHarmor (c.pluginState, fromPlugin, pluginGain))
  1444. adopt();
  1445. }
  1446. else if (name == "gms")
  1447. {
  1448. // FL's GMS engine from the raw state (REA_rodada39 §1) with its oscillator waves read at run time from
  1449. // the user's installation; the 3-oscillator conversion stays as the fallback (state unreadable or waves
  1450. // not found)
  1451. const auto folder = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\GMS\\Synth Waves", options.roots);
  1452. const auto waves = gmsWaveNames (c.pluginState);
  1453. const auto wavesFound = ! waves.empty() && ! folder.empty() && options.fileExists
  1454. && std::all_of (waves.begin(), waves.end(), [&] (const std::string& w) {
  1455. return w.empty() || options.fileExists (folder + "\\" + w + ".wav");
  1456. });
  1457. if (gmsStateUsable (c.pluginState) && wavesFound)
  1458. {
  1459. def.instrument = InstrumentKind::gms;
  1460. def.pluginState = c.pluginState;
  1461. def.samplePath = folder;
  1462. adoptedFromPlugin = true;
  1463. }
  1464. else if (synthFromGms (c.pluginState, song.bpm, fromPlugin, pluginGain))
  1465. adopt();
  1466. }
  1467. else if (name == "ogun" || name == "autogun")
  1468. {
  1469. // FL's inverse-FFT engine from the raw state (REA_rodada37). Autogun (REA_rodada57) runs the same engine on
  1470. // its state variant, then its Magic Dust stage with the preset Autogun\Data\SG.dat of the user's FL
  1471. // installation (read at run time; without it the stage is skipped). States the engine can't read keep the
  1472. // spectral-oscillator conversion.
  1473. if (name == "ogun" && ogunStateUsable (c.pluginState))
  1474. {
  1475. def.instrument = InstrumentKind::ogun;
  1476. def.pluginState = c.pluginState;
  1477. adoptedFromPlugin = true;
  1478. }
  1479. else if (name == "autogun" && autogunStateUsable (c.pluginState))
  1480. {
  1481. def.instrument = InstrumentKind::autogun;
  1482. def.pluginState = c.pluginState;
  1483. const auto sg = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Autogun\\Data\\SG.dat", options.roots);
  1484. if (! sg.empty() && (! options.fileExists || options.fileExists (sg)))
  1485. def.samplePath = sg;
  1486. else if (options.report != nullptr && ogunParam (c.pluginState, 63).value_or (0) > 0)
  1487. ++options.report->partialEffects["Autogun: Magic Dust (SG.dat not found)"];
  1488. adoptedFromPlugin = true;
  1489. }
  1490. else if (synthFromOgun (c.pluginState, fromPlugin, pluginGain))
  1491. adopt();
  1492. }
  1493. else if (name == "sakura")
  1494. {
  1495. // the physical string model (REA_rodada28 §1); the old saw + triangle stays as a fallback
  1496. if (auto params = sakuraParams (c.pluginState))
  1497. {
  1498. def.instrument = InstrumentKind::sakura;
  1499. def.modelParams = std::move (*params);
  1500. adoptedFromPlugin = true;
  1501. }
  1502. else if (synthFromSakura (c.pluginState, fromPlugin))
  1503. adopt();
  1504. }
  1505. else if (name == "simsynth")
  1506. {
  1507. // FL's SimSynth engine from the raw state (REA_rodada64 §1–4); it needs no installation data. A state the
  1508. // engine can't read keeps the channel unsupported (there is no conversion to fall back to)
  1509. if (simSynthStateUsable (c.pluginState))
  1510. {
  1511. def.instrument = InstrumentKind::simsynth;
  1512. def.pluginState = c.pluginState;
  1513. adoptedFromPlugin = true;
  1514. }
  1515. }
  1516. else if (name == "drumaxx")
  1517. {
  1518. // FL's Drumaxx engine from the raw state (REA_rodada67 §6–§9); it needs no installation data. A state the
  1519. // engine can't read keeps the channel unsupported (there is no conversion to fall back to)
  1520. if (drumaxxStateUsable (c.pluginState))
  1521. {
  1522. def.instrument = InstrumentKind::drumaxx;
  1523. def.pluginState = c.pluginState;
  1524. adoptedFromPlugin = true;
  1525. }
  1526. }
  1527. else if (name == "wasp" || name == "wasp xt")
  1528. {
  1529. // FL 2026 has no 64-bit Wasp: its DLL is a placeholder that keeps the state and plays nothing (REA_rodada64 §5)
  1530. def.instrument = InstrumentKind::wasp;
  1531. def.pluginState = c.pluginState;
  1532. adoptedFromPlugin = true;
  1533. }
  1534. else if (name == "fl slayer")
  1535. {
  1536. // FL's engine from the raw state (REA_rodada68) with the recorded pick excitations, chord and glide tables
  1537. // read at run time from the user's own Slayer_Engine.dll; there is no conversion to fall back to (state or
  1538. // DLL not usable: the channel stays unsupported)
  1539. const auto dll = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\FL Slayer\\Slayer_Engine.dll", options.roots);
  1540. if (slayerStateUsable (c.pluginState) && ! dll.empty() && options.fileExists && options.fileExists (dll) && slayerDllUsable (dll))
  1541. {
  1542. def.instrument = InstrumentKind::slayer;
  1543. def.pluginState = c.pluginState;
  1544. def.samplePath = dll;
  1545. // the root-note shift stays in the key; the rest of the channel pitch reaches FL Slayer as a pitch
  1546. // bend (ProcessEvent 4, REA_rodada79 §2.2)
  1547. def.modelParams = { c.rootNote >= 0 && c.rootNote <= 127 ? (float) (60 - c.rootNote) : 0.0f };
  1548. adoptedFromPlugin = true;
  1549. }
  1550. }
  1551. else if (name == "fruity video player")
  1552. {
  1553. // FL's state as it is (round 165g, core/VideoPlayer.h); the video's path through FL's folder names
  1554. if (auto vs = video::read (c.pluginState))
  1555. {
  1556. if (vs->path.find ('%') != std::string::npos)
  1557. if (const auto resolved = resolveFlPath (vs->path, options.roots); ! resolved.empty())
  1558. vs->path = resolved;
  1559. def.instrument = InstrumentKind::videoplayer;
  1560. def.pluginState = video::write (*vs);
  1561. adoptedFromPlugin = true;
  1562. }
  1563. }
  1564. else if (name == "fruity dance")
  1565. {
  1566. // a visual plugin: notes change the dance, its Gen_Render writes nothing (REA_rodada68 §8)
  1567. def.instrument = InstrumentKind::fruitydance;
  1568. def.pluginState = c.pluginState;
  1569. adoptedFromPlugin = true;
  1570. }
  1571. else if (name == "transistor bass")
  1572. {
  1573. // FL's engine from the raw state (REA_rodada57 §2) with the "303 Pulse" oscillator cycles read at run time
  1574. // from the user's own engine DLL; there is no conversion to fall back to (state or DLL not usable: the
  1575. // channel stays unsupported)
  1576. const auto dll = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Transistor Bass\\engine_x64.dll", options.roots);
  1577. if (transistorBassStateUsable (c.pluginState) && ! dll.empty() && options.fileExists && options.fileExists (dll)
  1578. && transistorBassDllUsable (dll))
  1579. {
  1580. def.instrument = InstrumentKind::transistorbass;
  1581. def.pluginState = c.pluginState;
  1582. def.samplePath = dll;
  1583. adoptedFromPlugin = true;
  1584. }
  1585. }
  1586. else if (name == "fruity soundfont player" || name == "soundfont player")
  1587. {
  1588. // FL's SoundFont player → LYNX Soundfont: the font (FL path macros expanded; MissingFiles relocates it
  1589. // when it moved), its preset and the overrides (REA_rodada158 §1)
  1590. sf::FlPlayerState fl;
  1591. if (sf::parseFlPlayerState (c.pluginState, fl))
  1592. {
  1593. const auto resolved = resolveFlPath (fl.path, options.roots);
  1594. const auto info = resolved.empty() ? sf::FontInfo {} : sf::scanFontFile (resolved);
  1595. const auto name0 = def.name;
  1596. def.instrument = InstrumentKind::soundfont;
  1597. def.samplePath = resolved.empty() ? fl.path : resolved;
  1598. def.modelParams = sf::paramsFromFl (fl, info.presets);
  1599. def.pluginState.clear();
  1600. def.name = name0;
  1601. adoptedFromPlugin = true;
  1602. }
  1603. }
  1604. else if (name == "plucked!")
  1605. {
  1606. // FL's Karplus-Strong engine from the raw state (REA_rodada65 §1); there was no conversion before
  1607. if (pluckedStateUsable (c.pluginState))
  1608. {
  1609. def.instrument = InstrumentKind::plucked;
  1610. def.pluginState = c.pluginState;
  1611. adoptedFromPlugin = true;
  1612. }
  1613. }
  1614. else if (name == "beepmap")
  1615. {
  1616. // FL's image-synthesis engine from the raw state, bitmap included (REA_rodada65 §2)
  1617. if (beepMapStateUsable (c.pluginState))
  1618. {
  1619. def.instrument = InstrumentKind::beepmap;
  1620. def.pluginState = c.pluginState;
  1621. def.modelParams = { (float) (project.header.ppq > 0 ? project.header.ppq : 96) };
  1622. adoptedFromPlugin = true;
  1623. }
  1624. }
  1625. else if (name == "sawer")
  1626. {
  1627. // FL's engine from the raw state (REA_rodada65 §3) with its oscillator cycle read at run time from the
  1628. // user's Sawer\data.saw; there was no conversion before (state or file not usable: unsupported)
  1629. const auto saw = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Sawer\\data.saw", options.roots);
  1630. if (sawerStateUsable (c.pluginState) && ! saw.empty() && options.fileExists && options.fileExists (saw))
  1631. {
  1632. def.instrument = InstrumentKind::sawer;
  1633. def.pluginState = c.pluginState;
  1634. def.samplePath = saw;
  1635. adoptedFromPlugin = true;
  1636. }
  1637. }
  1638. else if (name == "kepler")
  1639. {
  1640. // FL's engine from the raw state (REA_rodada46) with its LFO-shape and noise tables read at run time from the
  1641. // user's own engine DLL; the synth conversion stays as the fallback (state or DLL not usable)
  1642. const auto dll = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Kepler\\engine_x64.dll", options.roots);
  1643. if (keplerStateUsable (c.pluginState) && ! keplerExoState (c.pluginState) && ! dll.empty() && options.fileExists
  1644. && options.fileExists (dll) && keplerDllUsable (dll) && ! keplerExoDllUsable (dll))
  1645. {
  1646. def.instrument = InstrumentKind::kepler;
  1647. def.pluginState = c.pluginState;
  1648. def.samplePath = dll;
  1649. adoptedFromPlugin = true;
  1650. }
  1651. else if (synthFromKepler (c.pluginState, fromPlugin, pluginGain))
  1652. adopt();
  1653. }
  1654. else if (name == "kepler exo")
  1655. {
  1656. // FL 2026's Kepler Exo: Kepler's engine on the "Kepler-2" state (REA_rodada167d) with the tables of the user's own
  1657. // Kepler Exo engine DLL; no synth conversion exists for it (state or DLL not usable: the channel stays empty)
  1658. const auto dll = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Kepler Exo\\engine_x64.dll", options.roots);
  1659. if (keplerExoState (c.pluginState) && ! dll.empty() && options.fileExists && options.fileExists (dll) && keplerExoDllUsable (dll))
  1660. {
  1661. def.instrument = InstrumentKind::keplerExo;
  1662. def.pluginState = c.pluginState;
  1663. def.samplePath = dll;
  1664. adoptedFromPlugin = true;
  1665. }
  1666. }
  1667. else if (name == "boobass")
  1668. {
  1669. // FL's engine with its multisample read at run time from the user's own BooBass DLL (REA_rodada29 §4)
  1670. const auto dll = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\BooBass\\BooBass_Eng_x64.dll", options.roots);
  1671. auto word = [&] (std::size_t at) { std::uint32_t v = 0; std::memcpy (&v, c.pluginState.data() + at, 4); return v; };
  1672. if (c.pluginState.size() >= 16 && word (0) == 1 && ! dll.empty() && options.fileExists && options.fileExists (dll)
  1673. && booBassDllUsable (dll))
  1674. {
  1675. def.instrument = InstrumentKind::boobass;
  1676. def.samplePath = dll;
  1677. for (std::size_t k = 0; k < 3; ++k)
  1678. def.modelParams.push_back ((float) std::clamp ((int) word (4 + 4 * k), 0, 65535));
  1679. adoptedFromPlugin = true;
  1680. }
  1681. else if (synthFromBooBass (c.pluginState, fromPlugin))
  1682. adopt();
  1683. }
  1684. else if (name == "poizone")
  1685. {
  1686. // FL's PoiZone engine from the raw state (REA_rodada44); the 2-oscillator conversion stays as the
  1687. // fallback for states the engine can't read
  1688. if (poizoneStateUsable (c.pluginState))
  1689. {
  1690. def.instrument = InstrumentKind::poizone;
  1691. def.pluginState = c.pluginState;
  1692. adoptedFromPlugin = true;
  1693. }
  1694. else if (synthFromPoiZone (c.pluginState, fromPlugin, pluginGain))
  1695. adopt();
  1696. }
  1697. else if (name == "bassdrum")
  1698. {
  1699. // FL's BassDrum engine (REA_rodada43 §2) reading its oscillator table and noise sample at run time from
  1700. // the user's BassDrum folder; the sine + sweep conversion stays as the fallback (state unreadable or
  1701. // folder not found)
  1702. const auto folder = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\BassDrum", options.roots);
  1703. const auto tableFound = ! folder.empty() && options.fileExists && options.fileExists (folder + "\\sounddata");
  1704. if (bassDrumStateUsable (c.pluginState) && tableFound)
  1705. {
  1706. def.instrument = InstrumentKind::bassdrum;
  1707. def.pluginState = c.pluginState;
  1708. def.samplePath = folder;
  1709. adoptedFromPlugin = true;
  1710. if (const auto noise = bassDrumNoiseName (c.pluginState); ! noise.empty() && options.report != nullptr
  1711. && ! options.fileExists (folder + "\\Noise Samples\\" + noise))
  1712. ++options.report->partialEffects["BassDrum noise sample (not found)"];
  1713. }
  1714. else if (synthFromBassDrum (c.pluginState, fromPlugin, pluginGain))
  1715. adopt();
  1716. }
  1717. else if (name == "toxic biohazard")
  1718. {
  1719. // FL's engine from the raw state (REA_rodada45); its built-in waves 2…32 are spectra read at run time from the
  1720. // user's own Toxic Biohazard_x64.dll (SHA-256 checked). Without it (or for states the engine can't read) the
  1721. // 2-operator conversion stays
  1722. const auto dll = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Toxic Biohazard\\Toxic Biohazard_x64.dll",
  1723. options.roots);
  1724. const auto dllFound = ! dll.empty() && options.fileExists && options.fileExists (dll) && toxicDllUsable (dll);
  1725. if (toxicStateUsable (c.pluginState) && (dllFound || ! toxicNeedsDll (c.pluginState)))
  1726. {
  1727. def.instrument = InstrumentKind::toxic;
  1728. def.pluginState = c.pluginState;
  1729. if (dllFound)
  1730. def.samplePath = dll;
  1731. adoptedFromPlugin = true;
  1732. }
  1733. else if (synthFromToxic (c.pluginState, fromPlugin, pluginGain))
  1734. adopt();
  1735. }
  1736. else if (name == "morphine")
  1737. {
  1738. // FL's Morphine engine from the raw state (REA_rodada39 §2); its noise sample is read at run time from
  1739. // the user's installation (not found: the noise stays silent). The averaged-spectrum conversion stays as
  1740. // the fallback for states the engine can't read
  1741. if (morphineStateUsable (c.pluginState))
  1742. {
  1743. def.instrument = InstrumentKind::morphine;
  1744. def.pluginState = c.pluginState;
  1745. adoptedFromPlugin = true;
  1746. if (const auto noise = morphineNoiseName (c.pluginState); ! noise.empty())
  1747. {
  1748. const auto path = resolveFlPath ("%FLStudioFactoryData%\\Plugins\\Fruity\\Generators\\Morphine\\Noise Samples\\" + noise,
  1749. options.roots);
  1750. if (! path.empty() && options.fileExists && options.fileExists (path))
  1751. def.samplePath = path;
  1752. else if (options.report != nullptr)
  1753. ++options.report->partialEffects["Morphine noise sample (not found)"];
  1754. }
  1755. }
  1756. else if (synthFromMorphine (c.pluginState, fromPlugin, pluginGain))
  1757. adopt();
  1758. }
  1759. else if (name == "drumpad" && drumpadParams (c.pluginState))
  1760. {
  1761. // the physical drum model (REA_rodada28 §2)
  1762. const auto dp = drumpadParams (c.pluginState);
  1763. def.instrument = InstrumentKind::drumpad;
  1764. def.modelParams.assign (dp->begin(), dp->end());
  1765. adoptedFromPlugin = true;
  1766. }
  1767. else if (name == "drumpad")
  1768. if (const auto patch = drumpadPatchName (c.pluginState))
  1769. {
  1770. // kick/snare/clap/hi-hat: the drum instruments; the rest, a drum on the synth
  1771. if (const auto drum = guessInstrument (*patch, flp::ChannelType::sampler); drum != InstrumentKind::synth)
  1772. {
  1773. def.instrument = drum;
  1774. adoptedFromPlugin = true;
  1775. }
  1776. else
  1777. {
  1778. fromPlugin = drumToneForName (*patch);
  1779. // confirmed: Pitch ×2^(2x − 1) and Mallet Amplitude 10^(−4(1 − x)) (the physical model isn't)
  1780. if (const auto dp = drumpadParams (c.pluginState))
  1781. {
  1782. const auto semis = 12.0f * (2.0f * std::clamp ((*dp)[29], 0.0f, 1.0f) - 1.0f);
  1783. for (auto& o : fromPlugin.osc)
  1784. {
  1785. o.semitones += (int) std::lround (semis);
  1786. o.detune += 100.0f * (semis - (float) std::lround (semis));
  1787. }
  1788. pluginGain = (float) std::pow (10.0, -4.0 * (1.0 - std::clamp ((double) (*dp)[2], 0.0, 1.0)));
  1789. }
  1790. adopt();
  1791. }
  1792. }
  1793. }
  1794. // 3x Osc: oscillators from the plugin state; envelope and filter come from the channel (REA_rodada4)
  1795. if (def.instrument == InstrumentKind::synth && c.pluginName == "3x Osc" && synthFrom3xOsc (c.pluginState, def.synth))
  1796. {
  1797. if (hasVolumeEnvelope)
  1798. {
  1799. def.synth.attack = def.sampler.attack;
  1800. def.synth.decay = def.sampler.decay;
  1801. def.synth.sustain = def.sampler.sustain;
  1802. def.synth.release = def.sampler.release;
  1803. }
  1804. else
  1805. {
  1806. // without an envelope FL plays the note as a gate, with only a short declick
  1807. def.synth.attack = 0.002f;
  1808. def.synth.decay = 0.0f;
  1809. def.synth.sustain = 1.0f;
  1810. def.synth.release = 0.02f;
  1811. }
  1812. synthFilterFromChannel (c.modX, c.modY, c.filterType, def.synth.cutoff, def.synth.resonance, def.synth.filterType);
  1813. def.synth.filterEnv = filterEnv;
  1814. def.synth.pitchEnv = pitchEnv;
  1815. }
  1816. // sample region and start offset
  1817. if (std::isfinite (c.sampleStart) && std::isfinite (c.sampleEnd) && std::isfinite (c.startOffset))
  1818. {
  1819. // FL's end is a fraction of what follows the start: the region is [start, start + end·(1 − start)]
  1820. // (FLEngine FUN_00ff0db0, REA_rodada167h §2; FL's demos hold ends below their starts, e.g. 0.62 / 0.14)
  1821. const auto start = std::clamp (c.sampleStart, 0.0, 1.0);
  1822. const auto end = std::clamp (start + std::clamp (c.sampleEnd, 0.0, 1.0) * (1.0 - start), 0.0, 1.0);
  1823. if (end > start)
  1824. {
  1825. def.sampler.regionStart = (float) start;
  1826. def.sampler.regionEnd = (float) end;
  1827. // the start offset: FL starts notes there, a fraction of the (cropped) region [FL render, §4]
  1828. def.sampler.startOffset = (float) std::clamp (c.startOffset, 0.0, 1.0);
  1829. }
  1830. }
  1831. // the Sampler's precomputed effects, loop flags and declicking mode (REA_rodada167h §1)
  1832. // (audio clip channels: the precomputed effects and Reverse too — FL plays them, round 167k §8)
  1833. if (c.type == flp::ChannelType::sampler || def.instrument == InstrumentKind::audioClip)
  1834. {
  1835. auto& p = def.sampler.precompute;
  1836. p.fadeStereo = (c.fxFlags & 1) != 0;
  1837. def.sampler.reverse = def.sampler.reverse || (c.fxFlags & 2) != 0;
  1838. p.swapStereo = (c.fxFlags & 0x100) != 0;
  1839. p.fadeIn = std::clamp (c.fadeIn, 0, 1024);
  1840. p.fadeOut = std::clamp (c.fadeOut, 0, 1024);
  1841. p.removeDc = c.removeDc;
  1842. p.normalize = c.normalize;
  1843. p.reversePolarity = c.reversePolarity;
  1844. p.crossfade = std::clamp (c.crossfade, 0, 2048);
  1845. p.trim = std::clamp (c.trim, 0, 32768);
  1846. p.pingPong = c.pingPong;
  1847. // the legacy precomputed effects (REA_rodada167l §1), within the ranges of FL's knobs
  1848. p.boost = std::clamp (c.boost, 0, 256);
  1849. p.eq = std::clamp (c.eq, 0, 256);
  1850. p.ringMix = std::clamp (c.ringMix, 0, 256);
  1851. p.ringFreq = std::clamp (c.ringFreq, 0, 256);
  1852. p.stereoDelay = std::clamp (c.stereoDelay, 0, 4096);
  1853. p.cutoff = std::clamp (c.cutoff, 16, 1024);
  1854. p.resonance = std::clamp (c.resonance, 0, 640);
  1855. p.reverb = std::clamp (c.reverb, 0, 256);
  1856. p.reverbType = c.reverbType == 0 ? 0 : 1;
  1857. p.pogo = std::clamp (c.pogo, 0, 512);
  1858. p.clip = (c.fxFlags & 4) != 0;
  1859. def.sampler.useLoopPoints = c.useLoopPoints();
  1860. def.sampler.declickMode = std::clamp (c.declickMode, 0, 5);
  1861. }
  1862. // time-stretch: the sample lasts TIME/192 beats × MUL
  1863. if (c.stretchTime > 0.0f)
  1864. {
  1865. def.sampler.stretchBeats = (float) (c.stretchTime / 192.0 * std::pow (2.0, c.stretchMul / 10000.0));
  1866. def.sampler.keepPitch = c.stretchMode != 0; // only FL's "Resample" changes the pitch
  1867. def.sampler.stretchMethod = stretchMethodForFlMode (c.stretchMode);
  1868. // Fruity Granulizer: FL hands the plugin TIME as its beat count, without MUL (REA_rodada165g-flgran165 §3)
  1869. if (def.instrument == InstrumentKind::granulizer)
  1870. def.sampler.stretchBeats = (float) (c.stretchTime / 192.0);
  1871. }
  1872. // FL's time-stretching panel on a sample channel or an audio clip [FL: measured, REA_rodada164e-clippitch §2]:
  1873. // every mode but Resample keeps the length (also without a TIME: the keys, the pitch knob and the root note
  1874. // transpose keeping the length) and adds its PITCH knob; Resample ignores that knob. MUL without a TIME
  1875. // stretches the sample by 2^(MUL/10000) (Resample: slower and lower), at the project's tempo here.
  1876. if ((c.type == flp::ChannelType::sampler || isAudioClip)
  1877. && (def.instrument == InstrumentKind::sampler || def.instrument == InstrumentKind::audioClip))
  1878. {
  1879. const auto needsLength = c.stretchTime <= 0.0f && c.stretchMul != 0 && ! def.samplePath.empty() && options.sampleSeconds;
  1880. applyFlStretchPanel (def.sampler, c.stretchMode, c.stretchPitch, c.stretchMul, c.stretchTime,
  1881. needsLength ? options.sampleSeconds (def.samplePath) : 0.0, song.bpm);
  1882. }
  1883. // report: what happened to this channel's generator/sample
  1884. if (options.report != nullptr)
  1885. {
  1886. auto& r = *options.report;
  1887. const auto plugin = lowercase (c.pluginName);
  1888. if (plugin.empty())
  1889. r.missingSamples += ! c.samplePath.empty() && def.samplePath.empty() ? 1 : 0;
  1890. else if (plugin == "3x osc" || ((plugin == "directwave" || plugin == "fl keys") && ! def.zones.empty())
  1891. || ((plugin == "fruity slicer" || plugin == "slicex") && ! def.samplePath.empty())
  1892. || (plugin == "fpc" && ! drumKits.empty() && drumKits.back().first == (int) song.channels.size()))
  1893. ++r.converted[c.pluginName];
  1894. else if (def.instrument == InstrumentKind::sakura || def.instrument == InstrumentKind::drumpad
  1895. || def.instrument == InstrumentKind::boobass || def.instrument == InstrumentKind::drumsynth
  1896. || def.instrument == InstrumentKind::harmless || def.instrument == InstrumentKind::sytrus
  1897. || def.instrument == InstrumentKind::harmor || def.instrument == InstrumentKind::gms
  1898. || def.instrument == InstrumentKind::morphine
  1899. || def.instrument == InstrumentKind::ogun || def.instrument == InstrumentKind::minisynth
  1900. || def.instrument == InstrumentKind::dx10
  1901. || def.instrument == InstrumentKind::kepler || def.instrument == InstrumentKind::keplerExo || def.instrument == InstrumentKind::poizone
  1902. || def.instrument == InstrumentKind::fruitkick || def.instrument == InstrumentKind::bassdrum || def.instrument == InstrumentKind::toxic
  1903. || def.instrument == InstrumentKind::autogun || def.instrument == InstrumentKind::transistorbass
  1904. || def.instrument == InstrumentKind::simsynth || def.instrument == InstrumentKind::wasp
  1905. || def.instrument == InstrumentKind::plucked || def.instrument == InstrumentKind::beepmap
  1906. || def.instrument == InstrumentKind::sawer || def.instrument == InstrumentKind::flkeys
  1907. || def.instrument == InstrumentKind::granulizer || def.instrument == InstrumentKind::drumaxx
  1908. || def.instrument == InstrumentKind::slayer || def.instrument == InstrumentKind::fruitydance
  1909. || def.instrument == InstrumentKind::videoplayer || def.instrument == InstrumentKind::wavetraveller
  1910. || def.instrument == InstrumentKind::directwave || def.instrument == InstrumentKind::soundfont)
  1911. ++r.converted[c.pluginName]; // FL's own engine rebuilt from the plugin state
  1912. else if ((plugin == "harmless" && def.instrument != InstrumentKind::harmless) || (plugin == "harmor" && def.instrument != InstrumentKind::harmor && adoptedFromPlugin) || (plugin == "minisynth" && def.instrument != InstrumentKind::minisynth) || plugin == "fruity dx10" || plugin == "dx10" || (plugin == "fruit kick" && def.instrument != InstrumentKind::fruitkick)
  1913. || ((plugin == "sytrus" || plugin == "gms" || plugin == "ogun" || plugin == "autogun" || plugin == "sakura" || plugin == "kepler" || plugin == "boobass" || plugin == "drumpad" || plugin == "poizone" || plugin == "bassdrum"
  1914. || plugin == "toxic biohazard" || plugin == "morphine") && adoptedFromPlugin)
  1915. || (plugin == "fruity drumsynth live" && def.instrument == InstrumentKind::sampler))
  1916. ++r.approximated[c.pluginName];
  1917. else if (((plugin == "fruity envelope controller" || plugin == "fruity keyboard controller") && def.instrument == InstrumentKind::controller)
  1918. || (plugin == "fruity drumsynth live" && def.instrument == InstrumentKind::drumsynth)
  1919. || (plugin == "harmless" && def.instrument == InstrumentKind::harmless)
  1920. || (plugin == "harmor" && def.instrument == InstrumentKind::harmor))
  1921. ++r.converted[c.pluginName];
  1922. else if (plugin == "fruity wrapper" && def.plugin.foreign.format == ForeignPlugin::Format::none)
  1923. ++r.unsupported["Fruity Wrapper (plugin state not readable)"]; // e.g. a wrapper version newer than 12
  1924. else if ((plugin == "midi out" && def.instrument == InstrumentKind::midiOut)
  1925. || (plugin == "fruity voltage controller" && def.instrument == InstrumentKind::voltage)
  1926. || (plugin == "dashboard" && def.instrument == InstrumentKind::dashboard))
  1927. ++r.converted[c.pluginName];
  1928. else if (def.instrument == InstrumentKind::vfx)
  1929. ++r.converted[c.pluginName];
  1930. else if (plugin != "fruity wrapper" && plugin != "fruity keyboard controller" && plugin != "midi out"
  1931. && def.instrument == InstrumentKind::synth)
  1932. {
  1933. const auto note = flextra::inertPluginNote (c.pluginName); // round 165g: ReWired, Video Player, FL Studio Mobile
  1934. if (c.pluginName == "ReWired")
  1935. def.muted = true; // no sound of their own in LYNX: the stand-in synth must not play their notes
  1936. ++r.unsupported[note.empty() ? c.pluginName : note]; // (Keyboard Controller only sends notes to other channels)
  1937. }
  1938. }
  1939. song.channels.push_back (std::move (def));
  1940. }
  1941. // Layer children: FL's channel indices → LYNX's (children that did not become channels are dropped)
  1942. for (auto& def : song.channels)
  1943. if (def.instrument == InstrumentKind::layer)
  1944. {
  1945. std::vector<int> mapped;
  1946. for (const auto k : def.layer.children)
  1947. if (const auto found = channelMap.find (k); found != channelMap.end())
  1948. mapped.push_back (found->second);
  1949. def.layer.children = std::move (mapped);
  1950. if (options.report != nullptr)
  1951. ++options.report->converted["Layer"];
  1952. }
  1953. // Mixer: names, mute/solo, routing and levels from the .flp; enough inserts for all
  1954. // routes (minimum 16, like a new project). FL's extra tracks (500/501) are left out.
  1955. int highestTrack = 16;
  1956. for (const auto& c : song.channels)
  1957. highestTrack = std::max (highestTrack, c.mixerTrack);
  1958. for (const auto& insert : project.mixer)
  1959. if (insert.index < maxMixerTracks)
  1960. for (auto target : insert.routes)
  1961. if (target < maxMixerTracks && (insert.index > 0 || target > 0))
  1962. highestTrack = std::max ({ highestTrack, target, insert.index });
  1963. song.mixer = Song::defaultMixer (std::min (highestTrack, maxMixerTracks - 1));
  1964. const auto tracks = (int) song.mixer.size();
  1965. for (const auto& insert : project.mixer)
  1966. {
  1967. if (insert.index < 0 || insert.index >= tracks)
  1968. continue;
  1969. auto& track = song.mixer[(std::size_t) insert.index];
  1970. if (insert.index > 0 && ! insert.name.empty())
  1971. track.name = insert.name;
  1972. if (insert.colour != 0 && insert.colour != 0x485156) // FL's default gray
  1973. track.colour = 0xFF000000u | insert.colour;
  1974. track.muted = (insert.flags & 0x08) == 0;
  1975. track.invertPhase = (insert.flags & 0x01) != 0;
  1976. track.swapChannels = (insert.flags & 0x02) != 0;
  1977. track.solo = insert.index > 0 && (insert.flags & 0x1000) != 0;
  1978. // REA round 146a (FL's insert writer FUN_00f3d620): bits 6-7 = dock (0 left, 1 middle, 2 right), 0x400 separator
  1979. track.separator = insert.index > 0 && (insert.flags & 0x400) != 0;
  1980. // (FL's last insert, the "Current" track, is saved with dock 0 too; LYNX keeps it in the middle)
  1981. const auto dockBits = insert.flags >> 6 & 3;
  1982. const auto isCurrentTrack = insert.index > 0 && insert.index + 1 == (int) project.mixer.size();
  1983. track.dock = dockBits == 2 ? MixerDock::right : (dockBits == 0 && ! isCurrentTrack) ? MixerDock::left : MixerDock::middle;
  1984. // FL's track latency (REA round 165f-mixer, FUN_00f3d620): the manual latency (0xEC f32), "Bypass track latency
  1985. // compensation" (0x31) and "Compensate for master latency" (0xEC flag 0x4000 = off)
  1986. track.latencyMs = std::clamp (insert.latencyMs, -maxTrackLatencyMs, maxTrackLatencyMs);
  1987. if (insert.index > 0)
  1988. track.latencyBypass = (LatencyBypass) std::clamp (insert.latencyBypass, 0, 2);
  1989. track.compensateMasterLatency = (insert.flags & 0x4000) == 0;
  1990. // 0x93 "Audio output target" (REA round 156): −1 none, 0 the first pair (the only values seen in 1162 .flp files:
  1991. // every Master 0, one insert 0); other values depend on FL's device list and are not imported, nor a Master
  1992. // set to none (the project would play silent)
  1993. if (insert.output == 0 && insert.index > 0)
  1994. track.outputChannel = 0;
  1995. // 0x9A "Audio input source" (REA round 157c): resolved against the open device when the project opens
  1996. // (AudioEngine::setSong). FL plays an insert's input through it whether the insert is armed or not, stopped or
  1997. // playing ([FL] FL Studio 2026, meters of unarmed inserts with an input): monitoring On
  1998. if (insert.input >= 0)
  1999. {
  2000. track.flInput = insert.input;
  2001. track.monitor = InputMonitor::on;
  2002. }
  2003. if (insert.index > 0 && insert.hasRoutes)
  2004. {
  2005. track.toMaster = std::find (insert.routes.begin(), insert.routes.end(), 0) != insert.routes.end();
  2006. // The level comes from 0xE1 (below). Without a record a route is 100%, except in FL 11 and older,
  2007. // whose templates route every insert to the send tracks at the end of the mixer (100+) at level 0.
  2008. // FL 12+ plays an unrecorded route to insert 100+ at full level (REA_rodada89 §4.1 [EXEC]: FL's
  2009. // "Advanced" templates feed bus tracks 117…125 that way); the exact version boundary is not confirmed.
  2010. const auto oldSendTracks = project.versionNumber < 12'000'000u;
  2011. for (auto target : insert.routes)
  2012. if (target > 0 && target < tracks && target != insert.index)
  2013. track.sends.push_back ({ target, target >= 100 && oldSendTracks ? 0.0f : 1.0f });
  2014. }
  2015. }
  2016. // native FL effects become the similar internal effects (default parameters: the internal
  2017. // state of FL plugins is not known); the others are left out
  2018. std::map<std::pair<int, int>, std::pair<int, std::string>> effectSlotMap; // (track, FL slot) -> (our effect, FL plugin)
  2019. // inputs of each track (REA_rodada22 §1): [itself, the ones routing to it in ascending order (at
  2020. // any level; level 0 = sidechain only)]; the index k stored in the plugins points into this list
  2021. std::map<int, std::vector<int>> trackInputs;
  2022. for (const auto& insert : project.mixer)
  2023. if (insert.hasRoutes)
  2024. for (const auto target : insert.routes)
  2025. if (target > 0 && target != insert.index)
  2026. trackInputs[target].push_back (insert.index);
  2027. auto sidechainSource = [&] (int track, int k) {
  2028. if (k <= 0)
  2029. return -1;
  2030. auto inputs = trackInputs[track];
  2031. std::sort (inputs.begin(), inputs.end());
  2032. inputs.erase (std::unique (inputs.begin(), inputs.end()), inputs.end());
  2033. inputs.insert (inputs.begin(), track);
  2034. return k < (int) inputs.size() && inputs[(std::size_t) k] < tracks ? inputs[(std::size_t) k] : -1;
  2035. };
  2036. std::map<std::pair<int, int>, decltype (LovePhilterConversion::paramMap)> lovePhilterMaps; // Love Philter automation
  2037. // data files of the user's FL installation that some effects load at run time (Soundgoodizer's presets,
  2038. // REA_rodada40); nothing of them is stored in LYNX itself, only in the imported project
  2039. const FlDataReader flData = [&options] (const std::string& relative) -> std::vector<std::uint8_t> {
  2040. const auto path = resolveFlPath ("%FLStudioFactoryData%\\" + relative, options.roots);
  2041. if (path.empty() || ! options.readFile || (options.fileExists && ! options.fileExists (path)))
  2042. return {};
  2043. return options.readFile (path);
  2044. };
  2045. // exact engines that fell back to their approximation (for the report)
  2046. auto noteFallback = [&options, &project] (const std::string& plugin, EffectSlot& fx) {
  2047. if (fx.kind == EffectKind::grossBeat) // its song-position sync counts in the project's ticks (REA_rodada53)
  2048. grossbeat::setPpq (fx.state, project.header.ppq > 0 ? project.header.ppq : 96);
  2049. if (options.report == nullptr || fx.kind == EffectKind::maximus || fx.kind == EffectKind::grossBeat)
  2050. return;
  2051. if (plugin == "Gross Beat")
  2052. ++options.report->partialEffects["Gross Beat (state not read: volume gate only)"];
  2053. if (plugin == "ZGameEditor Visualizer") // round 164c: its effects are approximated by LYNX Visualizer layers
  2054. ++options.report->partialEffects["ZGameEditor Visualizer (scene approximated with LYNX Visualizer layers)"];
  2055. if (plugin == "Maximus")
  2056. ++options.report->partialEffects["Maximus (option not decoded: approximated)"];
  2057. else if (plugin == "Soundgoodizer")
  2058. ++options.report->partialEffects["Soundgoodizer (preset file not found: approximated)"];
  2059. else if ((plugin == "Fruity Limiter" && fx.kind != EffectKind::fruityLimiter)
  2060. || (plugin == "Fruity Compressor" && fx.kind != EffectKind::fruityCompressor)
  2061. || (plugin == "Fruity Delay 2" && fx.kind != EffectKind::fruityDelay2)
  2062. || (plugin == "Fruity Delay 3" && fx.kind != EffectKind::fruityDelay3)
  2063. || (plugin == "Fruity Stereo Shaper" && fx.kind != EffectKind::stereoShaper)
  2064. || (plugin == "Fruity Stereo Enhancer" && fx.kind != EffectKind::stereoEnhancer)
  2065. || (plugin == "Transient Processor" && fx.kind != EffectKind::transientProcessor)
  2066. || (plugin == "Spreader" && fx.kind != EffectKind::spreader)
  2067. || (plugin == "EQUO" && fx.kind != EffectKind::equo)
  2068. || (plugin == "Pitch Shifter" && fx.kind != EffectKind::flPitchShifter)
  2069. || (plugin == "Frequency Splitter" && fx.kind != EffectKind::frequencySplitter)
  2070. || (plugin == "Distructor" && fx.kind != EffectKind::distructor)
  2071. || (plugin == "Multiband Delay" && fx.kind != EffectKind::multibandDelay))
  2072. ++options.report->partialEffects[plugin + " (state not readable: approximated)"];
  2073. else if ((plugin == "Fruity WaveShaper" && fx.kind != EffectKind::fruityWaveShaper)
  2074. || (plugin == "Fruity Soft Clipper" && fx.kind != EffectKind::fruitySoftClipper)
  2075. || (plugin == "Fruity Delay Bank" && fx.kind != EffectKind::fruityDelayBank)
  2076. || (plugin == "Fruity Multiband Compressor" && fx.kind != EffectKind::fruityMultiband))
  2077. ++options.report->partialEffects[plugin + " (state not readable: approximated)"];
  2078. else if ((plugin == "Fruity PanOMatic" && fx.kind != EffectKind::fruityPanOMatic)
  2079. || (plugin == "Fruity Balance" && fx.kind != EffectKind::fruityBalance)
  2080. || (plugin == "Fruity Send" && fx.kind != EffectKind::fruitySend)
  2081. || (plugin == "Transporter" && fx.kind != EffectKind::flTransporter)
  2082. || (plugin == "Fruity Blood Overdrive" && fx.kind != EffectKind::fruityBloodOverdrive))
  2083. ++options.report->partialEffects[plugin + " (state not readable: approximated)"];
  2084. else if ((plugin == "Fruity Phase Inverter" && fx.kind != EffectKind::flPhaseInverter)
  2085. || (plugin == "Fruity Center" && fx.kind != EffectKind::flCenter)
  2086. || (plugin == "Fruity Bass Boost" && fx.kind != EffectKind::flBassBoost)
  2087. || (plugin == "Fruity 7 Band EQ" && fx.kind != EffectKind::fl7BandEq)
  2088. || (plugin == "Fruity Delay" && fx.kind != EffectKind::flDelay1))
  2089. ++options.report->partialEffects[plugin + " (state not readable: approximated)"];
  2090. else if ((plugin == "Fruity Fast LP" && fx.kind != EffectKind::fruityFastLP)
  2091. || (plugin == "Fruity Free Filter" && fx.kind != EffectKind::fruityFreeFilter)
  2092. || (plugin == "Fruity Filter" && fx.kind != EffectKind::fruityFilter))
  2093. ++options.report->partialEffects[plugin + " (state not readable: approximated)"];
  2094. else if (chorusControls (plugin) > 0 && fx.kind == EffectKind::chorus)
  2095. ++options.report->partialEffects[plugin + " (state not readable: approximated)"];
  2096. else if ((plugin == "Fruity Fast Dist" && fx.kind != EffectKind::fruityFastDist)
  2097. || (plugin == "Fruity Flangus" && fx.kind != EffectKind::fruityFlangus)
  2098. || (plugin == "Fruity Flanger" && fx.kind != EffectKind::fruityFlanger)
  2099. || (plugin == "Fruity Phaser" && fx.kind != EffectKind::fruityPhaser))
  2100. ++options.report->partialEffects[plugin + " (state not readable: approximated)"];
  2101. else if (plugin == "Hardcore" && fx.kind == EffectKind::hardcore
  2102. && ! hardcore::hasCabinet (fx, (int) hardcore::fromSlot (hardcore::pCabinet, fx.params[(std::size_t) hardcore::pCabinet])))
  2103. {
  2104. if (hardcore::fromSlot (hardcore::pCabinet, fx.params[(std::size_t) hardcore::pCabinet]) > 0.0f)
  2105. ++options.report->partialEffects["Hardcore (cabinet impulse not found: cabinet off)"];
  2106. }
  2107. };
  2108. // FL's Patcher as LYNX's real graph (REA_rodada141): every node (effects through the same converters as the mixer
  2109. // slots, instruments through a one-channel import), every cable (audio with its gain, notes, control values mapped
  2110. // to LYNX's parameters), the editor positions and the extra outputs
  2111. std::function<std::optional<PatcherDoc> (const std::vector<std::uint8_t>&, const flp::Channel*)> patcherFromFl;
  2112. int patcherSidechain = -1; // the last converted Patcher's side-chain pin: "7 Sidechain" = insert 7
  2113. patcherFromFl = [&] (const std::vector<std::uint8_t>& state, const flp::Channel* asChannel) -> std::optional<PatcherDoc> {
  2114. const auto graph = parsePatcher (state);
  2115. if (! graph)
  2116. return std::nullopt;
  2117. PatcherDoc doc;
  2118. std::vector<int> nodeOf (graph->nodes.size(), -1);
  2119. for (std::size_t n = 0; n < graph->nodes.size(); ++n)
  2120. {
  2121. const auto& fl = graph->nodes[n];
  2122. PatchNode node;
  2123. node.label = fl.label;
  2124. // FL's boxes are small: its positions spread to LYNX's node size (FL's dense graphs sit ~60 px apart)
  2125. constexpr float spreadX = 2.0f, spreadY = 1.6f;
  2126. node.x = fl.x * spreadX;
  2127. node.y = fl.y * spreadY;
  2128. if (const auto kind = vfx::kindOfFlName (fl.plugin)) // a VFX node (an effect in FL's graph): voices in, voices out
  2129. {
  2130. node.generator = true;
  2131. vfx::makeChannel (node.channel, *kind);
  2132. vfx::State vs;
  2133. vs.kind = *kind;
  2134. vs.fl = fl.state.empty() ? vfx::defaultState (*kind) : fl.state;
  2135. node.channel.pluginState = vfx::writeState (vs);
  2136. if (! fl.label.empty())
  2137. node.channel.name = fl.label;
  2138. node.channel.mixerTrack = 0;
  2139. node.channel.volume = 1.0f;
  2140. node.channel.pan = 0.0f;
  2141. if ((options.report != nullptr))
  2142. ++options.report->converted["Patcher: " + fl.plugin];
  2143. }
  2144. else if (fl.generator)
  2145. {
  2146. node.generator = true;
  2147. flp::Project mini;
  2148. mini.header = project.header;
  2149. mini.tempo = project.tempo;
  2150. flp::Channel ch;
  2151. if (asChannel != nullptr)
  2152. ch = *asChannel;
  2153. ch.index = 0;
  2154. ch.pluginName = fl.plugin;
  2155. ch.pluginState = fl.state;
  2156. if (! fl.label.empty())
  2157. ch.name = fl.label;
  2158. mini.channels = { ch };
  2159. auto miniOptions = options;
  2160. miniOptions.report = nullptr;
  2161. auto sub = importFlp (mini, miniOptions);
  2162. if (sub.channels.empty())
  2163. continue;
  2164. node.channel = std::move (sub.channels.front());
  2165. node.channel.mixerTrack = 0;
  2166. node.channel.volume = 1.0f; // (FL's node has no channel volume: unity)
  2167. node.channel.pan = 0.0f;
  2168. }
  2169. else
  2170. {
  2171. std::optional<EffectSlot> made;
  2172. ForeignPlugin foreign;
  2173. if (lowercase (fl.plugin) == "patcher")
  2174. {
  2175. if (auto inner = patcherFromFl (fl.state, nullptr))
  2176. {
  2177. made = makeEffectSlot (EffectKind::patcher);
  2178. made->patcher = std::move (*inner);
  2179. }
  2180. }
  2181. else if (fl.plugin == "Fruity Wrapper" && parseFlWrapper (fl.state, foreign))
  2182. {
  2183. if (foreign.format == ForeignPlugin::Format::vst2 && effectForFlPlugin (foreign.name))
  2184. made = effectFromFl (foreign.name, wrappedFruityState (foreign), song.bpm);
  2185. else
  2186. {
  2187. made = makeEffectSlot (EffectKind::plugin);
  2188. made->plugin.name = foreign.name;
  2189. applyFlWrapperOptions (foreign, made->plugin);
  2190. made->plugin.foreign = std::move (foreign);
  2191. }
  2192. }
  2193. else if ((made = effectFromFl (canonicalFlEffectName (fl.plugin), fl.state, song.bpm, flData)))
  2194. noteFallback (canonicalFlEffectName (fl.plugin), *made);
  2195. if (! made)
  2196. {
  2197. // a pass-through in its place (controllers and visualizers have nothing to pass anyway)
  2198. made = makeEffectSlot (EffectKind::utility);
  2199. if (node.label.empty())
  2200. node.label = fl.plugin;
  2201. if (options.report != nullptr)
  2202. ++options.report->partialEffects["Patcher: " + fl.plugin + " (no equivalent: passes the signal)"];
  2203. }
  2204. if ((fl.flags & 4) != 0)
  2205. made->enabled = false;
  2206. node.effect = std::move (*made);
  2207. // the extra outputs FL's splitters have (bands / difference) as LYNX bus heads
  2208. for (const auto& cable : graph->cables)
  2209. for (const auto& [id, port] : graph->ports)
  2210. if (id == cable.source && port.node == (int) n && ! port.input && port.kind == 0 && port.index > 0
  2211. && std::none_of (node.busHeads.begin(), node.busHeads.end(), [&] (const PatchNode::BusHead& h) { return h.bus == port.index; }))
  2212. {
  2213. const auto head = patcherBranchHead (canonicalFlEffectName (fl.plugin), fl.state, port.index);
  2214. if (! head.valid)
  2215. continue;
  2216. PatchNode::BusHead h;
  2217. h.bus = port.index;
  2218. h.head = head.slot;
  2219. h.gain = head.gain;
  2220. node.busHeads.push_back (std::move (h));
  2221. }
  2222. }
  2223. nodeOf[n] = (int) doc.nodes.size();
  2224. doc.nodes.push_back (std::move (node));
  2225. }
  2226. if (graph->ioPlaced)
  2227. {
  2228. doc.inputX = graph->inputX * 2.0f;
  2229. doc.inputY = graph->inputY * 1.6f;
  2230. doc.outputX = graph->outputX * 2.0f;
  2231. doc.outputY = graph->outputY * 1.6f;
  2232. }
  2233. else if (! doc.nodes.empty()) // around the nodes
  2234. {
  2235. float lo = doc.nodes.front().x, hi = lo, mid = 0.0f;
  2236. for (const auto& n : doc.nodes)
  2237. {
  2238. lo = std::min (lo, n.x);
  2239. hi = std::max (hi, n.x);
  2240. mid += n.y / (float) doc.nodes.size();
  2241. }
  2242. doc.inputX = lo - 160.0f;
  2243. doc.outputX = hi + 160.0f;
  2244. doc.inputY = doc.outputY = mid;
  2245. }
  2246. auto portOf = [&] (std::uint64_t id) -> const PatcherPort* {
  2247. for (const auto& [pid, port] : graph->ports)
  2248. if (pid == id)
  2249. return &port;
  2250. return nullptr;
  2251. };
  2252. // the I/O nodes' MIDI pins as FL saved them (activated even without a cable; FL's node menu › Events, round 162)
  2253. for (const auto& [pid, port] : graph->ports)
  2254. if (port.node < 0 && port.kind == 1)
  2255. if (const auto number = flPatcherMidiPinPort (port); number >= 0)
  2256. {
  2257. auto& list = port.input ? doc.toMidiPorts : doc.fromMidiPorts;
  2258. if (std::find (list.begin(), list.end(), number) == list.end())
  2259. list.insert (std::upper_bound (list.begin(), list.end(), number), number);
  2260. }
  2261. for (const auto& c : graph->cables)
  2262. {
  2263. const auto* src = portOf (c.source);
  2264. const auto* dst = portOf (c.destination);
  2265. if (src == nullptr || dst == nullptr)
  2266. continue;
  2267. PatchWire w;
  2268. w.enabled = ! c.disabled;
  2269. w.gain = std::isfinite (c.gain) ? c.gain : 1.0f;
  2270. if (src->node >= 0)
  2271. {
  2272. if ((std::size_t) src->node >= nodeOf.size() || nodeOf[(std::size_t) src->node] < 0)
  2273. continue;
  2274. w.from = nodeOf[(std::size_t) src->node];
  2275. }
  2276. if (dst->node >= 0)
  2277. {
  2278. if ((std::size_t) dst->node >= nodeOf.size() || nodeOf[(std::size_t) dst->node] < 0)
  2279. continue;
  2280. w.to = nodeOf[(std::size_t) dst->node];
  2281. }
  2282. if (c.kind == 0)
  2283. {
  2284. w.kind = PatchWire::Kind::audio;
  2285. w.fromPort = src->node < 0 ? (src->index > 0 ? 1 : 0) : std::max (0, src->index);
  2286. if (src->node < 0 && src->index > 0)
  2287. if (const auto track = std::atoi (src->name.c_str()); track > 0 && track < maxMixerTracks)
  2288. patcherSidechain = track;
  2289. w.toPort = dst->node < 0 ? std::max (0, dst->index) : std::min (1, std::max (0, dst->index));
  2290. if (w.to == patchToHost && w.toPort > 0) // an extra output: "Insert N" names its insert
  2291. {
  2292. while ((int) doc.outputTracks.size() < w.toPort)
  2293. doc.outputTracks.push_back (-1);
  2294. int insertNumber = -1;
  2295. if (dst->name.rfind ("Insert ", 0) == 0)
  2296. insertNumber = std::atoi (dst->name.c_str() + 7);
  2297. if (insertNumber > 0 && insertNumber < maxMixerTracks)
  2298. doc.outputTracks[(std::size_t) w.toPort - 1] = insertNumber;
  2299. }
  2300. }
  2301. else if (c.kind == 1)
  2302. {
  2303. w.kind = PatchWire::Kind::midi;
  2304. if (w.from == patchFromHost) // "Notes", or "MIDI port N": what reaches the Patcher on that port (round 162)
  2305. {
  2306. const auto port = flPatcherMidiPinPort (*src);
  2307. if (port < -1)
  2308. continue;
  2309. w.fromPort = port < 0 ? 0 : patchMidiPortPin (port);
  2310. }
  2311. else
  2312. {
  2313. // a node's MIDI output: a MIDI Out's (round 162), a VFX node's voice output N (FL's pin N, 1…;
  2314. // round 164b); other plugins' MIDI outputs are not passed yet
  2315. const auto& source = doc.nodes[(std::size_t) w.from];
  2316. if (! source.generator)
  2317. continue;
  2318. if (source.channel.instrument == InstrumentKind::vfx)
  2319. w.fromPort = std::max (0, src->index - 1);
  2320. else if (source.channel.instrument == InstrumentKind::midiOut)
  2321. w.fromPort = 0;
  2322. else
  2323. continue;
  2324. }
  2325. if (w.to == patchToHost) // "MIDI port N": the notes go to the plugins on that MIDI port
  2326. {
  2327. const auto number = flPatcherMidiPinPort (*dst);
  2328. if (number < 0)
  2329. continue;
  2330. w.toPort = number;
  2331. }
  2332. else
  2333. w.toPort = 0;
  2334. }
  2335. else
  2336. {
  2337. w.kind = PatchWire::Kind::control;
  2338. if (w.from < 0 || w.to < 0)
  2339. continue; // (the Patcher's own published parameters)
  2340. w.fromPort = src->index >= 0x10000000 ? src->index - 0x10000000 : std::max (0, src->index);
  2341. const auto& source = doc.nodes[(std::size_t) w.from];
  2342. if (! source.generator && source.effect.kind == EffectKind::peakController) // FL: peak, LFO, peak + LFO
  2343. w.fromPort = w.fromPort == 0 ? 1 : w.fromPort == 1 ? 2 : 0;
  2344. if (w.fromPort >= patcher::nodePorts (source).controlOuts)
  2345. {
  2346. // the source has no such output in LYNX (an X-Y controller, a Control Surface…): its target keeps the
  2347. // value FL saved instead of being pinned to 0
  2348. if (options.report != nullptr)
  2349. ++options.report->partialEffects["Patcher: control from " + graph->nodes[(std::size_t) src->node].plugin + " (not reproduced)"];
  2350. continue;
  2351. }
  2352. const auto& target = doc.nodes[(std::size_t) w.to];
  2353. const auto& flTarget = graph->nodes[(std::size_t) dst->node];
  2354. if (target.generator)
  2355. {
  2356. if (target.channel.instrument != InstrumentKind::plugin)
  2357. continue;
  2358. w.toPort = dst->index;
  2359. }
  2360. else if (target.effect.kind == EffectKind::plugin)
  2361. w.toPort = dst->index;
  2362. else if (const auto map = effectParamFromFl (canonicalFlEffectName (flTarget.plugin), dst->index))
  2363. {
  2364. w.toPort = map->param;
  2365. if (map->convert)
  2366. {
  2367. constexpr int points = 33;
  2368. for (int k = 0; k < points; ++k)
  2369. w.curve.push_back (std::clamp (map->convert ((float) k / (float) (points - 1)), 0.0f, 1.0f));
  2370. }
  2371. }
  2372. else
  2373. {
  2374. if (options.report != nullptr)
  2375. ++options.report->partialEffects["Patcher: control of " + flTarget.plugin + " parameter " + std::to_string (dst->index)
  2376. + " (not mapped)"];
  2377. continue;
  2378. }
  2379. }
  2380. doc.wires.push_back (std::move (w));
  2381. }
  2382. // the Patcher's published parameters (record 1100): Patcher parameter k → the node's parameter behind that port
  2383. for (const auto& [portId, k] : graph->exposed)
  2384. {
  2385. const auto* port = portOf (portId);
  2386. if (port == nullptr || k < 0 || k > 4096 || port->node < 0 || (std::size_t) port->node >= nodeOf.size() || nodeOf[(std::size_t) port->node] < 0
  2387. || port->kind != 2 || ! port->input)
  2388. continue;
  2389. PatchParam p;
  2390. p.node = nodeOf[(std::size_t) port->node];
  2391. const auto& target = doc.nodes[(std::size_t) p.node];
  2392. const auto& flTarget = graph->nodes[(std::size_t) port->node];
  2393. if (target.generator ? target.channel.instrument == InstrumentKind::plugin : target.effect.kind == EffectKind::plugin)
  2394. p.param = port->index;
  2395. else if (const auto map = target.generator ? std::nullopt : effectParamFromFl (canonicalFlEffectName (flTarget.plugin), port->index))
  2396. {
  2397. p.param = map->param;
  2398. if (map->convert)
  2399. for (int i = 0; i < 33; ++i)
  2400. p.curve.push_back (std::clamp (map->convert ((float) i / 32.0f), 0.0f, 1.0f));
  2401. }
  2402. else
  2403. continue;
  2404. p.name = patcher::nodeName (target) + " " + std::to_string (port->index + 1);
  2405. if ((int) doc.published.size() <= k)
  2406. doc.published.resize ((std::size_t) k + 1);
  2407. doc.published[(std::size_t) k] = std::move (p);
  2408. }
  2409. return doc;
  2410. };
  2411. // generator Patchers: the channel becomes the graph (the main generator stays in it as the import made it)
  2412. for (const auto& c : input.channels)
  2413. if (lowercase (c.pluginName) == "patcher")
  2414. if (const auto mapped = channelMap.find (c.index); mapped != channelMap.end() && mapped->second < (int) song.channels.size())
  2415. if (auto doc = patcherFromFl (c.pluginState, &c); doc && std::any_of (doc->nodes.begin(), doc->nodes.end(), [] (const PatchNode& n) {
  2416. return n.generator;
  2417. }))
  2418. {
  2419. auto& def = song.channels[(std::size_t) mapped->second];
  2420. def.instrument = InstrumentKind::patcher;
  2421. def.patcher = std::move (*doc);
  2422. def.plugin = {};
  2423. def.pluginState.clear();
  2424. if (options.report != nullptr)
  2425. ++options.report->converted["Patcher (graph)"];
  2426. }
  2427. for (const auto& insert : project.mixer)
  2428. {
  2429. if (insert.index < 0 || insert.index >= tracks)
  2430. continue;
  2431. auto& track = song.mixer[(std::size_t) insert.index];
  2432. for (const auto& original : insert.slots)
  2433. {
  2434. // Patcher with a simple serial chain: the plugins inside become consecutive slots
  2435. std::vector<flp::MixerInsert::Slot> expanded { original };
  2436. // Fruity Love Philter: the units become parametric EQ + gain/pan (or a parallel container)
  2437. // (only for states the exact engine cannot read: the others go through effectFromFl, REA_rodada66)
  2438. if (original.plugin == "Fruity Love Philter" && (int) track.effects.size() < maxEffectSlots
  2439. && philter::parse (original.state) == nullptr)
  2440. if (auto conversion = lovePhilterEffects (original.state))
  2441. {
  2442. const auto first = (int) track.effects.size();
  2443. for (auto& fx : conversion->slots)
  2444. if ((int) track.effects.size() < maxEffectSlots)
  2445. track.effects.push_back (std::move (fx));
  2446. effectSlotMap.insert ({ { insert.index, original.index }, { first, original.plugin } });
  2447. if (conversion->paramMap)
  2448. lovePhilterMaps[{ insert.index, original.index }] = conversion->paramMap;
  2449. for (const auto& link : conversion->links) // cutoff envelope/LFO: live automation
  2450. if (first + std::max (link.source, link.target) < (int) track.effects.size())
  2451. {
  2452. Automation a;
  2453. a.name = "Love Philter (" + track.name + ")";
  2454. a.target = { AutomationTargetKind::effectParam, insert.index, first + link.target, link.param };
  2455. a.source = { insert.index, first + link.source, 0 };
  2456. a.curve = link.curve;
  2457. song.automations.push_back (std::move (a));
  2458. }
  2459. if (options.report != nullptr)
  2460. {
  2461. ++options.report->converted["Fruity Love Philter"];
  2462. for (const auto& note : conversion->notes)
  2463. ++options.report->partialEffects[note];
  2464. }
  2465. continue;
  2466. }
  2467. // Patcher (REA_rodada141): the slot holds FL's whole graph, run as it is
  2468. if (lowercase (original.plugin) == "patcher" && (int) track.effects.size() < maxEffectSlots)
  2469. if (patcherSidechain = -1; auto doc = patcherFromFl (original.state, nullptr))
  2470. {
  2471. auto slot = makeEffectSlot (EffectKind::patcher);
  2472. slot.patcher = std::move (*doc);
  2473. if (patcherSidechain > 0 && patcherSidechain < tracks && patcherSidechain != insert.index)
  2474. slot.sidechain = patcherSidechain;
  2475. effectSlotMap.insert ({ { insert.index, original.index }, { (int) track.effects.size(), original.plugin } });
  2476. track.effects.push_back (std::move (slot));
  2477. if (options.report != nullptr)
  2478. ++options.report->converted["Patcher (graph)"];
  2479. continue;
  2480. }
  2481. // Patcher with branches (REA_rodada20 §3.3): the audio graph reduced to series/parallel becomes slots and
  2482. // nested parallel containers; splitter nodes enter via the band/bus used
  2483. if (lowercase (original.plugin) == "patcher" && (int) track.effects.size() < maxEffectSlots)
  2484. if (const auto graph = parsePatcher (original.state); graph && graph->serialChain.empty() && graph->audio)
  2485. {
  2486. std::function<std::vector<EffectSlot> (const PatcherExpr&, float&)> build = [&] (const PatcherExpr& e, float& gain) {
  2487. std::vector<EffectSlot> chain;
  2488. gain *= e.gain;
  2489. switch (e.kind)
  2490. {
  2491. case PatcherExpr::Kind::identity: break;
  2492. case PatcherExpr::Kind::node:
  2493. {
  2494. const auto& node = graph->nodes[(std::size_t) e.node];
  2495. if (e.bus >= 0)
  2496. {
  2497. const auto head = patcherBranchHead (node.plugin, node.state, e.bus);
  2498. if (! head.valid)
  2499. {
  2500. if (options.report != nullptr)
  2501. ++options.report->droppedEffects["Patcher: bus " + std::to_string (e.bus) + " of " + node.plugin];
  2502. break;
  2503. }
  2504. gain *= head.gain;
  2505. if (head.slot)
  2506. chain.push_back (*head.slot);
  2507. if (! head.note.empty() && options.report != nullptr)
  2508. ++options.report->partialEffects[head.note];
  2509. }
  2510. else if (auto fx = effectFromFl (node.plugin, node.state, song.bpm, flData); fx && fx->kind != EffectKind::plugin)
  2511. {
  2512. noteFallback (node.plugin, *fx);
  2513. chain.push_back (std::move (*fx));
  2514. }
  2515. else if (options.report != nullptr)
  2516. ++options.report->droppedEffects[node.plugin + " (in Patcher)"];
  2517. break;
  2518. }
  2519. case PatcherExpr::Kind::series:
  2520. for (const auto& c : e.children)
  2521. for (auto& slot : build (c, gain))
  2522. chain.push_back (std::move (slot));
  2523. break;
  2524. case PatcherExpr::Kind::parallel:
  2525. {
  2526. auto container = makeEffectSlot (EffectKind::parallel);
  2527. for (const auto& c : e.children)
  2528. {
  2529. EffectBranch branch;
  2530. auto branchGain = 1.0f;
  2531. branch.chain = build (c, branchGain);
  2532. branch.gain = std::clamp (branchGain, 0.0f, 4.0f);
  2533. container.branches.push_back (std::move (branch));
  2534. }
  2535. chain.push_back (std::move (container));
  2536. break;
  2537. }
  2538. }
  2539. return chain;
  2540. };
  2541. auto gain = 1.0f;
  2542. auto chain = build (*graph->audio, gain);
  2543. if (std::abs (gain - 1.0f) > 1e-4f)
  2544. {
  2545. auto utility = makeEffectSlot (EffectKind::utility);
  2546. utility.params[0] = gain <= 0.0f ? 0.0f : std::clamp ((float) (20.0 * std::log10 (gain) / 48.0 + 0.5), 0.0f, 1.0f);
  2547. chain.push_back (std::move (utility));
  2548. }
  2549. if ((int) (track.effects.size() + chain.size()) > maxEffectSlots) // doesn't fit: a single-branch container
  2550. {
  2551. auto container = makeEffectSlot (EffectKind::parallel);
  2552. container.branches.push_back ({ std::move (chain), 1.0f });
  2553. chain = { std::move (container) };
  2554. }
  2555. effectSlotMap.insert ({ { insert.index, original.index }, { (int) track.effects.size(), original.plugin } });
  2556. for (auto& slot : chain)
  2557. track.effects.push_back (std::move (slot));
  2558. if (options.report != nullptr)
  2559. ++options.report->converted["Patcher (series/parallel)"];
  2560. continue;
  2561. }
  2562. if (lowercase (original.plugin) == "patcher")
  2563. if (const auto graph = parsePatcher (original.state); graph && ! graph->serialChain.empty())
  2564. {
  2565. expanded.clear();
  2566. for (const auto n : graph->serialChain)
  2567. expanded.push_back ({ original.index, graph->nodes[(std::size_t) n].plugin, graph->nodes[(std::size_t) n].state });
  2568. if (options.report != nullptr)
  2569. ++options.report->converted["Patcher (in series)"];
  2570. }
  2571. for (const auto& slot : expanded)
  2572. {
  2573. if ((int) track.effects.size() >= maxEffectSlots)
  2574. continue;
  2575. ForeignPlugin foreign;
  2576. std::optional<EffectSlot> made;
  2577. const auto wrapped = slot.plugin == "Fruity Wrapper" && parseFlWrapper (slot.state, foreign);
  2578. // old FL saved its own Fruity effects as VST2 inside the wrapper: becomes the internal effect
  2579. if (wrapped && foreign.format == ForeignPlugin::Format::vst2 && effectForFlPlugin (foreign.name))
  2580. made = effectFromFl (foreign.name, wrappedFruityState (foreign), song.bpm);
  2581. else if (wrapped)
  2582. {
  2583. // the app swaps in the installed plugin; without it, the slot is removed
  2584. made = makeEffectSlot (EffectKind::plugin);
  2585. made->plugin.name = foreign.name;
  2586. applyFlWrapperOptions (foreign, made->plugin);
  2587. made->plugin.foreign = std::move (foreign);
  2588. }
  2589. else
  2590. {
  2591. made = effectFromFl (slot.plugin, slot.state, song.bpm, flData); // native effect with the saved settings (REA_rodada7)
  2592. if (made)
  2593. noteFallback (slot.plugin, *made);
  2594. }
  2595. if (! made)
  2596. {
  2597. // the ones that don't touch audio (controllers, visualizers, notes) aren't missed
  2598. static const char* silent[] = { "Fruity Peak Controller", "Fruity X-Y Controller", "Control Surface",
  2599. "Fruity NoteBook 2", "Fruity NoteBook", "Edison",
  2600. "Fruity Formula Controller", "Fruity LSD" };
  2601. const auto harmless = std::any_of (std::begin (silent), std::end (silent), [&] (const char* n) { return slot.plugin == n; });
  2602. // FL plugins with nothing to reproduce here (vendor lighting, discontinued bridges): the note says why (round 165g)
  2603. if (const auto note = flextra::inertPluginNote (slot.plugin); ! note.empty())
  2604. {
  2605. if (options.report != nullptr)
  2606. ++options.report->droppedEffects[note];
  2607. continue;
  2608. }
  2609. if (options.report != nullptr && ! harmless)
  2610. ++options.report->droppedEffects[slot.plugin == "Fruity Wrapper" ? std::string ("Fruity Wrapper (plugin state not readable)")
  2611. : slot.plugin];
  2612. continue;
  2613. }
  2614. auto fx = std::move (*made);
  2615. // FL's per-plugin "Smart disable" (0xD4 flag 0x20, REA round 139): off = processed even in silence
  2616. if (slot.wrapperFlags >= 0)
  2617. fx.smartDisable = (slot.wrapperFlags & 0x20) != 0;
  2618. // sidechain (REA_rodada22 §1): Fruity Limiter (i32 at 0xA4, v ≥ 6; only the compressor detector and only
  2619. // with Comp threshold < 0 dB) and Fruity Compressor (i32 at 0x20, v3)
  2620. if (slot.plugin == "Fruity Limiter" && slot.state.size() >= 0xA8)
  2621. {
  2622. std::int32_t version = 0, k = 0, compThreshold = 1000;
  2623. std::memcpy (&version, slot.state.data(), 4);
  2624. std::memcpy (&k, slot.state.data() + 0xA4, 4);
  2625. std::memcpy (&compThreshold, slot.state.data() + 4 + 8 * 4, 4);
  2626. const auto source = version >= 6 ? sidechainSource (insert.index, k) : -1;
  2627. if (fx.kind == EffectKind::fruityLimiter)
  2628. {
  2629. // the exact engine: the side input feeds its compression detector (REA_rodada48)
  2630. fx.sidechain = source;
  2631. if (source >= 0 && compThreshold < 1000 && options.report != nullptr)
  2632. ++options.report->converted["Fruity Limiter (sidechain)"];
  2633. }
  2634. else if (source >= 0 && compThreshold < 1000)
  2635. if (auto comp = fruityLimiterCompressor (slot.state))
  2636. {
  2637. const auto enabled = fx.enabled;
  2638. fx = std::move (*comp);
  2639. fx.enabled = enabled;
  2640. fx.sidechain = source;
  2641. if (options.report != nullptr)
  2642. ++options.report->converted["Fruity Limiter (sidechain)"];
  2643. }
  2644. }
  2645. else if (slot.plugin == "LuxeVerb" && fx.kind == EffectKind::luxeVerb && slot.state.size() >= 8)
  2646. {
  2647. // the state's second i32 is the sidechain input the envelope can follow (REA_rodada60 §3.1)
  2648. std::int32_t k = 0;
  2649. std::memcpy (&k, slot.state.data() + 4, 4);
  2650. if (k > 0)
  2651. fx.sidechain = sidechainSource (insert.index, k);
  2652. }
  2653. else if (slot.plugin == "Vocodex")
  2654. {
  2655. // ModIn/CarIn index the same inputs list as the sidechains (REA_rodada22 §1)
  2656. if (const auto v = vocodexEffect (slot.state, flData))
  2657. {
  2658. fx.sidechain = sidechainSource (insert.index, v->modIn);
  2659. fx.sidechain2 = sidechainSource (insert.index, v->carIn);
  2660. if (options.report != nullptr)
  2661. for (const auto& note : v->notes)
  2662. ++options.report->partialEffects[note];
  2663. }
  2664. }
  2665. else if (fx.kind == EffectKind::scratcher)
  2666. {
  2667. // the turntable's sample: FL's path with its macros (%FLStudioFactoryData%…), else the user's relocation
  2668. if (const auto st = scratcher::parse (slot.state))
  2669. {
  2670. const auto wanted = st->samplePath.empty() ? std::string() : resolveFlPath (st->samplePath, options.roots);
  2671. if (! wanted.empty() && options.fileExists && options.fileExists (wanted))
  2672. fx.samplePath = wanted;
  2673. else if (const auto chosen = relocatedPath (options.relocations, wanted);
  2674. ! wanted.empty() && ! chosen.empty() && options.fileExists && options.fileExists (chosen))
  2675. fx.samplePath = chosen;
  2676. if (options.report != nullptr)
  2677. {
  2678. if (! wanted.empty() && fx.samplePath.empty())
  2679. {
  2680. ++options.report->missingSamples;
  2681. addMissingFile (options.report->missingFiles, wanted,
  2682. (insert.name.empty() ? "Insert " + std::to_string (insert.index) : insert.name) + ": " + slot.plugin);
  2683. }
  2684. if (st->timecode != -1 && ! dvs::supported (st->timecode))
  2685. ++options.report->partialEffects["Fruity Scratcher (Traktor Mk2 / Timecode CD timecode not decoded: the platter stays silent)"];
  2686. else
  2687. ++options.report->converted[slot.plugin];
  2688. }
  2689. }
  2690. }
  2691. else if (fx.kind == EffectKind::flTransporter)
  2692. {
  2693. // the detector follows FL's input track when one is chosen (the inputs list, like the Limiter's); the
  2694. // loops' send goes to the mixer insert of that number: the plug-in asks the host for the send buffer
  2695. // with the same call and index as Fruity Send (REA_rodada167n §1, REA_rodada105_send §2)
  2696. if (const auto st = transporter::parse (slot.state))
  2697. {
  2698. fx.sidechain = sidechainSource (insert.index, st->inputTrack);
  2699. const auto send = st->sendTrack;
  2700. fx.params[(std::size_t) transporter::sendParam] =
  2701. send > 0 && send < tracks && send != insert.index ? (float) send / (float) transporter::rawMax[transporter::sendParam] : 0.0f;
  2702. }
  2703. }
  2704. else if (fx.kind == EffectKind::transmitter)
  2705. {
  2706. // the detection follows FL's sidechain input when one is chosen (the inputs list, like the Limiter's);
  2707. // the transient / sustain parts go to the inserts FL's send menus name (the insert number, like the
  2708. // Fruity Send's destination: REA_rodada167b §1)
  2709. if (const auto st = transmitter::parse (slot.state))
  2710. {
  2711. fx.sidechain = sidechainSource (insert.index, st->sidechain);
  2712. const int sends[2] = { st->transientSend, st->sustainSend };
  2713. for (int o = 0; o < 2; ++o)
  2714. fx.sendTracks[(std::size_t) o] = sends[o] > 0 && sends[o] < tracks && sends[o] != insert.index ? sends[o] : 0;
  2715. }
  2716. }
  2717. else if (fx.kind == EffectKind::newtone || fx.kind == EffectKind::newtime)
  2718. {
  2719. // the source sample: the path the host stored (record 3), else the engine's working copy (REA_rodada73 §2.3)
  2720. if (const auto parsed = newtonefx::parse (slot.state))
  2721. {
  2722. std::vector<std::string> candidates;
  2723. if (! parsed->sourcePath.empty())
  2724. candidates.push_back (resolveFlPath (parsed->sourcePath, options.roots));
  2725. for (const auto& t : parsed->tracks)
  2726. candidates.push_back (t.filePath);
  2727. for (const auto& path : candidates)
  2728. if (! path.empty() && options.fileExists && options.fileExists (path))
  2729. {
  2730. fx.samplePath = path;
  2731. break;
  2732. }
  2733. for (const auto& path : candidates) // located by the user (the "Missing files" window)
  2734. if (const auto chosen = relocatedPath (options.relocations, path);
  2735. fx.samplePath.empty() && ! chosen.empty() && options.fileExists && options.fileExists (chosen))
  2736. fx.samplePath = chosen;
  2737. if (options.report != nullptr && ! parsed->tracks.empty())
  2738. {
  2739. if (fx.samplePath.empty())
  2740. {
  2741. ++options.report->missingSamples;
  2742. if (! candidates.empty() && ! candidates.front().empty())
  2743. addMissingFile (options.report->missingFiles, candidates.front(),
  2744. (insert.name.empty() ? "Insert " + std::to_string (insert.index) : insert.name) + ": " + slot.plugin);
  2745. }
  2746. // Newtone's note edits and Newtime's warp markers are rendered by LYNX's engines (REA_rodada95,
  2747. // REA_rodada167b: close, not sample-exact). Only slave mode plays them (otherwise FL passes the
  2748. // input through).
  2749. ++options.report->converted[slot.plugin];
  2750. }
  2751. }
  2752. }
  2753. else if (slot.plugin == "Fruity Compressor" && slot.state.size() >= 0x24
  2754. && (fx.kind == EffectKind::compressor || fx.kind == EffectKind::fruityCompressor))
  2755. {
  2756. std::int32_t version = 0, k = 0;
  2757. std::memcpy (&version, slot.state.data(), 4);
  2758. std::memcpy (&k, slot.state.data() + 0x20, 4);
  2759. if (version == 3)
  2760. fx.sidechain = sidechainSource (insert.index, k);
  2761. }
  2762. // slot bypass and dry/wet (0xE1, p = 0x1F00 / 0x1F01)
  2763. for (const auto& control : project.controls)
  2764. if (control.id.isMixer() && control.id.track() == insert.index && control.id.slot() == slot.index)
  2765. {
  2766. if (control.id.param() == 0x1F00)
  2767. fx.enabled = control.value != 0;
  2768. else if (control.id.param() == 0x1F01)
  2769. fx.mix = std::clamp (control.value / 12800.0f, 0.0f, 1.0f);
  2770. }
  2771. effectSlotMap.insert ({ { insert.index, slot.index }, { (int) track.effects.size(), slot.plugin } });
  2772. track.effects.push_back (fx);
  2773. }
  2774. }
  2775. }
  2776. // cycles shouldn't exist in the file; if they do, the send that closes the cycle is dropped
  2777. for (int t = 1; t < tracks; ++t)
  2778. {
  2779. auto sends = std::move (song.mixer[(std::size_t) t].sends);
  2780. song.mixer[(std::size_t) t].sends.clear();
  2781. for (const auto& s : sends)
  2782. song.setRoute (t, s.target, true, s.level);
  2783. }
  2784. for (const auto& control : project.controls)
  2785. {
  2786. if (! control.id.isMixer())
  2787. continue;
  2788. const auto t = control.id.track();
  2789. const auto p = control.id.param();
  2790. if (t < 0 || t >= tracks)
  2791. continue;
  2792. auto& track = song.mixer[(std::size_t) t];
  2793. // FL ranges: volume 0..16000 (12800 = 0 dB), pan ±6400, route levels 0..16000 on the fader curve too
  2794. // (12800 = 0 dB, 16000 = +5.6 dB; destination 0 = the route to Master). REA_rodada107 §3: FL renders with
  2795. // a route level of 16000 / 12800 / 6400 differ by +5.6 / 0 / −12.7 dB, the fader curve's values.
  2796. if (p == flp::ControlId::mixerVolume)
  2797. track.volume = std::clamp (control.value / 16000.0f, 0.0f, 1.0f);
  2798. else if (p == flp::ControlId::mixerPan)
  2799. track.pan = std::clamp (control.value / 6400.0f, -1.0f, 1.0f);
  2800. else if (p == flp::ControlId::mixerStereo)
  2801. track.stereo = std::clamp (control.value / 64.0f, -1.0f, 1.0f);
  2802. else if (p >= flp::ControlId::mixerEqBase && p < flp::ControlId::mixerEqBase + 24 && (p - flp::ControlId::mixerEqBase) % 8 < 3)
  2803. {
  2804. // track EQ: p = 0x1FD0 + group·8 + band (group 0 gain, 1 frequency, 2 width; REA_rodada6 §1)
  2805. const auto group = (p - flp::ControlId::mixerEqBase) / 8;
  2806. const auto band = (std::size_t) ((p - flp::ControlId::mixerEqBase) % 8);
  2807. const auto v = (double) control.value;
  2808. if (group == 0)
  2809. track.eq.gainDb[band] = (float) std::clamp (v * 0.01, -18.0, 18.0);
  2810. else if (group == 1)
  2811. track.eq.hz[band] = (float) std::clamp (10.0 + 159.9 * (std::pow (101.0, v / 65536.0) - 1.0), 10.0, 16000.0);
  2812. else
  2813. track.eq.width[band] = (float) std::clamp (v / 65536.0, 0.0, 1.0);
  2814. }
  2815. else if (p == flp::ControlId::mixerSendBase)
  2816. track.masterLevel = faderGain (control.value / 16000.0f);
  2817. else if (p > flp::ControlId::mixerSendBase && p < flp::ControlId::mixerSendBase + tracks)
  2818. for (auto& send : track.sends)
  2819. if (send.target == p - flp::ControlId::mixerSendBase)
  2820. send.level = faderGain (control.value / 16000.0f);
  2821. }
  2822. // the FL template routes every insert to the send tracks at level 0; that makes no sound, only wastes CPU
  2823. for (auto& t : song.mixer)
  2824. t.sends.erase (std::remove_if (t.sends.begin(), t.sends.end(), [] (const MixerSend& s) { return s.level <= 0.0f; }),
  2825. t.sends.end());
  2826. const auto filePpq = project.header.ppq > 0 ? (std::int64_t) project.header.ppq : 96;
  2827. auto rescale = [filePpq] (std::int64_t ticks) { return ticks * ppq / filePpq; };
  2828. std::map<int, int> patternMap; // FL index -> our dense index
  2829. for (const auto& src : project.patterns)
  2830. {
  2831. Pattern p;
  2832. p.name = src.name.empty() ? "Pattern " + std::to_string (src.index) : src.name;
  2833. if (src.colour && *src.colour != 0x485156) // FL's default gray becomes an automatic colour
  2834. p.colour = 0xFF000000u | *src.colour;
  2835. // the Channel Rack's looping (round 165f-rack): FL keeps the loop points of every channel, by FL index
  2836. p.loopOn = src.loopOn;
  2837. p.loopMode = (RackLoopMode) std::clamp (src.loopMode, 1, 3);
  2838. for (const auto& [flChannel, setting] : src.channelLoops)
  2839. if (const auto it = channelMap.find (flChannel); it != channelMap.end())
  2840. if (std::none_of (p.channelLoops.begin(), p.channelLoops.end(), [&] (const ChannelLoop& l) { return l.channel == it->second; }))
  2841. p.channelLoops.push_back ({ it->second, std::max (setting, -3) });
  2842. for (const auto& n : src.notes)
  2843. {
  2844. const auto it = channelMap.find (n.channel);
  2845. if (it == channelMap.end())
  2846. continue;
  2847. Note note;
  2848. note.start = rescale (n.position);
  2849. // Step notes (length 0) play for one step.
  2850. note.length = n.length > 0 ? rescale (n.length) : ticksPerStep;
  2851. note.channel = it->second;
  2852. note.key = n.key; // FL and MIDI use the same numbering; only the octave name differs
  2853. note.velocity = std::clamp (n.velocity / 128.0f, 0.0f, 1.0f);
  2854. note.pan = std::clamp ((n.pan - 64) / 64.0f, -1.0f, 1.0f);
  2855. note.finePitch = (float) std::clamp ((int) n.finePitch - 120, -120, 120);
  2856. note.muted = n.muted();
  2857. note.slide = n.slide();
  2858. note.porta = n.porta();
  2859. note.colour = n.extra & 0x0F;
  2860. note.group = n.group;
  2861. p.notes.push_back (note);
  2862. }
  2863. p.sortNotes();
  2864. if (! p.notes.empty() || ! src.controlEvents.empty()) // a pattern of events only still plays them
  2865. {
  2866. patternMap[src.index] = (int) song.patterns.size();
  2867. song.patterns.push_back (std::move (p));
  2868. }
  2869. }
  2870. // Our target for an FL controlID: the FL slot (0..9, with gaps) becomes our effect's
  2871. // index (effect not imported = no target); internal effect parameter only with the FL-to-ours
  2872. // map (`valueMap` receives the value conversion).
  2873. auto resolveTarget = [&] (flp::ControlId id, std::function<float (float)>& valueMap) {
  2874. auto target = automationTargetFor (id, channelMap, (int) song.mixer.size());
  2875. // FL Soundfont Player → LYNX Soundfont: FL's P index and scale → LYNX's parameter (REA_rodada158 §1)
  2876. if (target.kind == AutomationTargetKind::channelParam && target.index >= 0 && target.index < (int) song.channels.size()
  2877. && song.channels[(std::size_t) target.index].instrument == InstrumentKind::soundfont)
  2878. {
  2879. const auto flIndex = target.param;
  2880. if (const auto mapped = sf::automationFromFl (flIndex, 0.0f))
  2881. {
  2882. target.param = mapped->first;
  2883. valueMap = [flIndex] (float v) { const auto m = sf::automationFromFl (flIndex, v); return m ? m->second : 0.0f; };
  2884. }
  2885. else
  2886. target.kind = AutomationTargetKind::none;
  2887. }
  2888. // round 165: FL's Dashboard parameter p ≥ 1 = record p − 1 = LYNX's control p − 1 (its output); 0 is the patch
  2889. // selector (not a LYNX target). The Voltage Controller's 0…15 (offsets, scales) are LYNX's own numbers.
  2890. if (target.kind == AutomationTargetKind::channelParam && target.index >= 0 && target.index < (int) song.channels.size())
  2891. {
  2892. const auto& channel = song.channels[(std::size_t) target.index];
  2893. if (channel.instrument == InstrumentKind::dashboard)
  2894. {
  2895. const auto k = target.param - 1;
  2896. if (k >= 0 && k < (int) channel.patcher.surface.size())
  2897. target.param = surface::firstOutput (channel.patcher.surface, k);
  2898. else
  2899. target.kind = AutomationTargetKind::none;
  2900. }
  2901. else if (channel.instrument == InstrumentKind::voltage && (target.param < 0 || target.param >= voltage::paramCount))
  2902. target.kind = AutomationTargetKind::none;
  2903. }
  2904. if (target.kind == AutomationTargetKind::effectParam || target.kind == AutomationTargetKind::effectMix)
  2905. {
  2906. const auto found = effectSlotMap.find ({ target.index, target.slot });
  2907. if (found == effectSlotMap.end())
  2908. target.kind = AutomationTargetKind::none;
  2909. else
  2910. {
  2911. target.slot = found->second.first;
  2912. const auto& fx = song.mixer[(std::size_t) target.index].effects[(std::size_t) target.slot];
  2913. if (target.kind == AutomationTargetKind::effectParam && found->second.second == "Fruity Love Philter"
  2914. && fx.kind != EffectKind::lovePhilter)
  2915. {
  2916. const auto map = lovePhilterMaps.find ({ id.track(), id.slot() });
  2917. const auto mapped = map != lovePhilterMaps.end() && map->second ? map->second (target.param) : std::nullopt;
  2918. if (mapped)
  2919. {
  2920. target.slot = found->second.first + std::get<0> (*mapped);
  2921. target.param = std::get<1> (*mapped);
  2922. valueMap = std::get<2> (*mapped);
  2923. }
  2924. else
  2925. target.kind = AutomationTargetKind::none;
  2926. }
  2927. else if (target.kind == AutomationTargetKind::effectParam && fx.kind == EffectKind::lovePhilter)
  2928. {
  2929. // the exact Love Philter exposes 48 of FL's controls as (raw − min) / range (core/LovePhilter.h)
  2930. target.param = philter::paramOfFlIndex (target.param);
  2931. if (target.param < 0)
  2932. target.kind = AutomationTargetKind::none;
  2933. }
  2934. else if (target.kind == AutomationTargetKind::effectParam && fx.kind == EffectKind::luxeVerb)
  2935. {
  2936. // the exact LuxeVerb keeps FL's 49 controls as (raw − min) / range: FL's normalised value as is
  2937. if (target.param < 0 || target.param >= luxeVerbControlCount)
  2938. target.kind = AutomationTargetKind::none;
  2939. }
  2940. else if (target.kind == AutomationTargetKind::effectParam && fx.kind == EffectKind::convolver)
  2941. {
  2942. // the exact Convolver keeps FL's 4 automatable controls as (raw − min) / range
  2943. if (target.param < 0 || target.param >= convolverParamCount)
  2944. target.kind = AutomationTargetKind::none;
  2945. }
  2946. else if (target.kind == AutomationTargetKind::effectParam && (fx.kind == EffectKind::reeverb2 || fx.kind == EffectKind::reeverb1))
  2947. {
  2948. // the exact Reeverbs keep FL's controls as (raw − min) / range: FL's normalised value as is
  2949. if (target.param < 0 || target.param >= (fx.kind == EffectKind::reeverb2 ? 15 : reeverb1ParamCount))
  2950. target.kind = AutomationTargetKind::none;
  2951. }
  2952. else if (target.kind == AutomationTargetKind::effectParam && fx.kind == EffectKind::patcher)
  2953. {
  2954. // the Patcher's own parameter k: one it publishes (REA_rodada141), FL's normalised value as is
  2955. if (target.param < 0 || target.param >= (int) fx.patcher.published.size() || fx.patcher.published[(std::size_t) target.param].node < 0)
  2956. target.kind = AutomationTargetKind::none;
  2957. }
  2958. else if (target.kind == AutomationTargetKind::effectParam && fx.kind != EffectKind::plugin)
  2959. {
  2960. if (const auto mapped = effectParamFromFl (found->second.second, target.param))
  2961. {
  2962. target.param = mapped->param;
  2963. valueMap = mapped->convert;
  2964. }
  2965. else
  2966. target.kind = AutomationTargetKind::none;
  2967. }
  2968. }
  2969. }
  2970. return target;
  2971. };
  2972. // Pattern events (.flp 0xDF, REA_rodada85): per pattern and target, FL's raw values held from their tick on.
  2973. // They become the pattern's event lanes (round 83) in FL's normalised scale, then our target's (valueMap).
  2974. {
  2975. auto pluginOf = [&] (flp::ControlId id) -> std::string {
  2976. if (id.isChannel())
  2977. {
  2978. for (const auto& c : project.channels)
  2979. if (c.index == id.channel())
  2980. return c.pluginName;
  2981. }
  2982. else if (id.isMixer())
  2983. {
  2984. const auto found = effectSlotMap.find ({ id.track(), id.slot() });
  2985. if (found != effectSlotMap.end())
  2986. return found->second.second;
  2987. }
  2988. return {};
  2989. };
  2990. auto note = [&] (const std::string& what) {
  2991. if (options.report != nullptr)
  2992. ++options.report->unsupported["Pattern events: " + what];
  2993. };
  2994. // FL value → our 0..1 for a target (nothing when the target or its scale is not reproduced)
  2995. auto convertor = [&] (flp::ControlId id, AutomationTarget& target) -> std::function<float (std::int32_t)> {
  2996. std::function<float (float)> valueMap;
  2997. target = resolveTarget (id, valueMap);
  2998. const auto plugin = pluginOf (id);
  2999. if (target.kind == AutomationTargetKind::none || target.kind == AutomationTargetKind::tempo)
  3000. {
  3001. note ("target not reproduced" + (plugin.empty() ? std::string() : " (" + plugin + ")"));
  3002. return {};
  3003. }
  3004. const auto range = flRawRange (id, plugin);
  3005. if (! range || range->second <= range->first)
  3006. {
  3007. note ("value scale not known (" + (plugin.empty() ? std::string ("FL parameter") : plugin) + ")");
  3008. return {};
  3009. }
  3010. const auto lo = (double) range->first, span = (double) (range->second - range->first);
  3011. return [lo, span, valueMap] (std::int32_t raw) {
  3012. auto v = (float) std::clamp (((double) raw - lo) / span, 0.0, 1.0);
  3013. return valueMap ? std::clamp (valueMap (v), 0.0f, 1.0f) : v;
  3014. };
  3015. };
  3016. for (const auto& src : project.patterns)
  3017. {
  3018. const auto pm = patternMap.find (src.index);
  3019. if (src.controlEvents.empty() || pm == patternMap.end())
  3020. continue;
  3021. auto& pattern = song.patterns[(std::size_t) pm->second];
  3022. std::vector<std::uint32_t> ids; // targets in order of first appearance
  3023. for (const auto& e : src.controlEvents)
  3024. if (std::find (ids.begin(), ids.end(), e.id.raw) == ids.end())
  3025. ids.push_back (e.id.raw);
  3026. for (const auto raw : ids)
  3027. {
  3028. PatternEvents lane;
  3029. const auto convert = convertor (flp::ControlId { raw }, lane.target);
  3030. if (! convert)
  3031. continue;
  3032. for (const auto& e : src.controlEvents)
  3033. if (e.id.raw == raw)
  3034. lane.events.push_back ({ rescale ((std::int64_t) e.tick), convert (e.value) });
  3035. // one event per tick: the last one of a tick wins (FL applies them in order)
  3036. std::stable_sort (lane.events.begin(), lane.events.end(),
  3037. [] (const PatternEvent& a, const PatternEvent& b) { return a.tick < b.tick; });
  3038. std::vector<PatternEvent> kept;
  3039. for (const auto& e : lane.events)
  3040. if (! kept.empty() && kept.back().tick == e.tick)
  3041. kept.back() = e;
  3042. else
  3043. kept.push_back (e);
  3044. lane.events = std::move (kept);
  3045. // a target already driven by a lane of this pattern: the later lane wins, like FL's single target
  3046. pattern.events.erase (std::remove_if (pattern.events.begin(), pattern.events.end(),
  3047. [&] (const PatternEvents& l) { return l.target == lane.target; }),
  3048. pattern.events.end());
  3049. pattern.events.push_back (std::move (lane));
  3050. if (options.report != nullptr)
  3051. ++options.report->converted["Pattern events"];
  3052. }
  3053. }
  3054. // 0xD8: values FL resets when the song starts — the targets' own values before any pattern event
  3055. for (const auto& c : project.initControls)
  3056. {
  3057. AutomationTarget target;
  3058. if (const auto convert = convertor (c.id, target))
  3059. {
  3060. const auto value = convert (c.value);
  3061. song.setTargetValue (target, value);
  3062. song.setInitialValue (target, value); // kept: reset whenever the song starts (REA round 146)
  3063. }
  3064. }
  3065. }
  3066. // Automation clips: one Automation per FL automation channel, with the target from the 0xE3 link.
  3067. std::map<int, int> automationMap; // FL channel -> index into song.automations
  3068. for (const auto& c : project.channels)
  3069. {
  3070. if (c.type != flp::ChannelType::automationClip || c.automation.empty())
  3071. continue;
  3072. Automation a;
  3073. a.name = c.name.empty() ? "Automation " + std::to_string (c.index + 1) : c.name;
  3074. std::function<float (float)> valueMap; // FL normalized value -> ours (effect parameters)
  3075. for (const auto& link : project.automationLinks)
  3076. if (link.channel == c.index)
  3077. {
  3078. a.target = resolveTarget (link.target, valueMap);
  3079. break;
  3080. }
  3081. for (std::size_t i = 0; i < c.automation.size(); ++i)
  3082. {
  3083. const auto& p = c.automation[i];
  3084. const auto tick = (std::int64_t) std::llround (p.position * ppq);
  3085. auto value = (float) std::clamp (p.value, 0.0, 1.0);
  3086. // FL automates tempo from 60 to 180 BPM; our target covers the full tempo range
  3087. if (a.target.kind == AutomationTargetKind::tempo)
  3088. value = valueFromTempo (60.0 + 120.0 * value);
  3089. else if (valueMap)
  3090. value = std::clamp (valueMap (value), 0.0f, 1.0f);
  3091. // FL's curve belongs to the segment ending at the point; ours sits on the left point
  3092. if (i > 0)
  3093. {
  3094. auto& previous = a.points.back();
  3095. if (p.curve == 0 || p.curve == 1) // single/double curve: exponential by tension
  3096. previous.tension = std::clamp (-p.tension, -1.0f, 1.0f);
  3097. else if (p.curve == 2 && tick - previous.tick > 1) // hold: step right before the point
  3098. a.points.push_back ({ tick - 1, previous.value, 0.0f });
  3099. }
  3100. a.points.push_back ({ tick, value, 0.0f });
  3101. }
  3102. automationMap[c.index] = (int) song.automations.size();
  3103. song.automations.push_back (std::move (a));
  3104. }
  3105. // Controller links (REA_rodada14 §7): Peak Controller in a mixer slot -> live automation of the
  3106. // target (the effect output is read every block). Other controllers are still left out.
  3107. for (const auto& link : project.controllerLinks)
  3108. {
  3109. // Envelope Controller on a channel: output k follows articulator k
  3110. if (link.source.isChannel())
  3111. {
  3112. const auto channel = channelMap.find (link.source.channel());
  3113. if (channel == channelMap.end()
  3114. || (song.channels[(std::size_t) channel->second].instrument != InstrumentKind::controller
  3115. && song.channels[(std::size_t) channel->second].instrument != InstrumentKind::dashboard))
  3116. continue;
  3117. const auto& sourceChannel = song.channels[(std::size_t) channel->second];
  3118. auto output = link.source.param() - flp::ControlId::pluginParamBase;
  3119. if (sourceChannel.instrument == InstrumentKind::dashboard) // FL's output number → the panel's order
  3120. {
  3121. const auto k = surface::flDashboardOutputToLynx (sourceChannel.pluginState, output);
  3122. if (! k)
  3123. continue;
  3124. output = *k;
  3125. }
  3126. Automation a;
  3127. std::function<float (float)> valueMap;
  3128. a.target = resolveTarget (link.target, valueMap);
  3129. if (a.target.kind == AutomationTargetKind::none || a.target.kind == AutomationTargetKind::tempo)
  3130. continue;
  3131. a.name = "Controller (" + song.channels[(std::size_t) channel->second].name + ")";
  3132. a.source.channel = channel->second;
  3133. a.source.output = output;
  3134. if (valueMap)
  3135. for (int i = 0; i <= 32; ++i)
  3136. a.curve.push_back (std::clamp (valueMap ((float) i / 32.0f), 0.0f, 1.0f));
  3137. song.automations.push_back (std::move (a));
  3138. if (options.report != nullptr)
  3139. ++options.report->converted["Channel controller (link)"];
  3140. continue;
  3141. }
  3142. if (! link.source.isMixer() || link.source.track() < 0 || link.source.track() >= (int) song.mixer.size())
  3143. continue;
  3144. // an X-Y (-Z) Controller / Control Surface imported as LYNX's own (round 164): a live link (below)
  3145. const auto liveSlot = effectSlotMap.find ({ link.source.track(), link.source.slot() });
  3146. const auto liveKind = liveSlot != effectSlotMap.end() ? song.mixer[(std::size_t) link.source.track()].effects[(std::size_t) liveSlot->second.first].kind
  3147. : EffectKind::eq;
  3148. const auto newController = xy::isXyController (liveKind) || liveKind == EffectKind::controlSurface;
  3149. // static X-Y Controller / Control Surface (not imported): the current value is applied to the target once
  3150. if (! newController)
  3151. {
  3152. const flp::MixerInsert::Slot* source = nullptr;
  3153. for (const auto& insert : project.mixer)
  3154. if (insert.index == link.source.track())
  3155. for (const auto& slot : insert.slots)
  3156. if (slot.index == link.source.slot())
  3157. source = &slot;
  3158. if (source != nullptr)
  3159. if (const auto value = controllerConstantOutput (source->plugin, source->state, link.source.param() - flp::ControlId::pluginParamBase))
  3160. {
  3161. std::function<float (float)> valueMap;
  3162. const auto target = resolveTarget (link.target, valueMap);
  3163. if (target.kind != AutomationTargetKind::none && target.kind != AutomationTargetKind::tempo
  3164. && song.setTargetValue (target, valueMap ? valueMap (*value) : *value) && options.report != nullptr)
  3165. ++options.report->converted[source->plugin + " (link)"];
  3166. continue;
  3167. }
  3168. }
  3169. const auto found = effectSlotMap.find ({ link.source.track(), link.source.slot() });
  3170. if (found == effectSlotMap.end()
  3171. || (song.mixer[(std::size_t) link.source.track()].effects[(std::size_t) found->second.first].kind != EffectKind::peakController
  3172. && song.mixer[(std::size_t) link.source.track()].effects[(std::size_t) found->second.first].kind != EffectKind::formulaController
  3173. && ! newController))
  3174. continue;
  3175. const auto& sourceSlot = song.mixer[(std::size_t) link.source.track()].effects[(std::size_t) found->second.first];
  3176. const auto formulaSource = sourceSlot.kind == EffectKind::formulaController;
  3177. Automation a;
  3178. std::function<float (float)> valueMap;
  3179. a.target = resolveTarget (link.target, valueMap);
  3180. if (a.target.kind == AutomationTargetKind::none || a.target.kind == AutomationTargetKind::tempo)
  3181. continue;
  3182. a.name = std::string (newController ? effectInfo (sourceSlot.kind).name : formulaSource ? "Formula Controller" : "Peak Controller") + " ("
  3183. + song.mixer[(std::size_t) link.source.track()].name + ")";
  3184. a.source = { link.source.track(), found->second.first, link.source.param() - flp::ControlId::pluginParamBase };
  3185. if (sourceSlot.kind == EffectKind::controlSurface) // FL's output numbers → the panel's order
  3186. {
  3187. const auto k = surface::flOutputToLynx (sourceSlot.state, a.source.output);
  3188. if (! k)
  3189. continue;
  3190. a.source.output = *k;
  3191. }
  3192. else if (xy::isXyController (sourceSlot.kind) && (a.source.output < 0 || a.source.output >= xy::axesOf (sourceSlot.kind)))
  3193. continue;
  3194. if (valueMap)
  3195. for (int i = 0; i <= 32; ++i)
  3196. a.curve.push_back (std::clamp (valueMap ((float) i / 32.0f), 0.0f, 1.0f));
  3197. song.automations.push_back (std::move (a));
  3198. if (options.report != nullptr)
  3199. ++options.report->converted[newController ? std::string (effectInfo (sourceSlot.kind).name) + " (link)"
  3200. : formulaSource ? "Formula Controller (link)" : "Peak Controller (link)"];
  3201. }
  3202. // Playlist: all arrangements (the first stays open); pattern, audio and automation clips.
  3203. std::vector<const std::vector<flp::PlaylistTrackInfo>*> importedTracks;
  3204. if (! project.arrangements.empty())
  3205. song.arrangements.clear();
  3206. for (const auto& arrangement : project.arrangements)
  3207. {
  3208. std::vector<Clip> clips;
  3209. for (const auto& item : arrangement.items)
  3210. {
  3211. if (item.length == 0)
  3212. continue;
  3213. if (item.kind == flp::PlaylistItem::Kind::channelClip && automationMap.count (item.index))
  3214. {
  3215. Clip clip;
  3216. clip.kind = ClipKind::automation;
  3217. clip.automation = automationMap[item.index];
  3218. clip.track = item.track;
  3219. clip.start = rescale (item.position);
  3220. clip.length = rescale (item.length);
  3221. // trim in beats (-1 = no trim)
  3222. if (std::isfinite (item.startOffset) && item.startOffset > 0.0f)
  3223. clip.offset = (std::int64_t) std::llround (item.startOffset * ppq);
  3224. clips.push_back (clip);
  3225. continue;
  3226. }
  3227. if (item.kind == flp::PlaylistItem::Kind::channelClip)
  3228. {
  3229. const auto channel = channelMap.find (item.index);
  3230. if (channel == channelMap.end() || song.channels[(std::size_t) channel->second].instrument != InstrumentKind::audioClip)
  3231. continue;
  3232. Clip clip;
  3233. clip.kind = ClipKind::audio;
  3234. clip.channel = channel->second;
  3235. clip.track = item.track;
  3236. clip.start = rescale (item.position);
  3237. clip.length = rescale (item.length);
  3238. // The region start comes in beats or in milliseconds, depending on the clip;
  3239. // we find out by the unit in which (end - start) matches the length.
  3240. const auto beats = (double) item.length / (double) filePpq;
  3241. const auto span = (double) item.endOffset - (double) item.startOffset;
  3242. if (std::isfinite (item.startOffset) && item.startOffset > 0.0f)
  3243. {
  3244. // offsets in ms are kept to the sample: the sub-tick rest goes to offsetFraction (REA_rodada110 §1:
  3245. // a 77 019.27 ms offset rounded to whole ticks played 2 samples late against FL)
  3246. const auto setOffset = [&clip] (double ticks)
  3247. {
  3248. clip.offset = (std::int64_t) std::llround (ticks);
  3249. clip.offsetFraction = (float) (ticks - (double) clip.offset);
  3250. };
  3251. if (std::abs (span - beats) < 0.02 * std::max (1.0, beats))
  3252. clip.offset = (std::int64_t) std::llround (item.startOffset * ppq);
  3253. else if (std::abs (span - beats * 60000.0 / song.bpm) < 0.02 * std::max (1.0, span))
  3254. setOffset (item.startOffset / 1000.0 * song.bpm / 60.0 * ppq);
  3255. else if (const auto& ch = song.channels[(std::size_t) channel->second]; ch.sampler.stretchBeats > 0.0f && span > 0.0 && beats > 0.0)
  3256. {
  3257. // time-stretched clip: start/end are in the SAMPLE's milliseconds, so the span is the clip
  3258. // length times the stretch factor (e.g. 31 219 ms over 64 beats = 29 538 ms at 130 BPM)
  3259. const auto factor = span / (beats * 60000.0 / song.bpm);
  3260. if (factor > 0.25 && factor < 4.0)
  3261. setOffset (item.startOffset / factor / 1000.0 * song.bpm / 60.0 * ppq);
  3262. }
  3263. }
  3264. // clip gain and fades (FL 20.99+ records); fades are in ms, at most the clip length
  3265. clip.gain = item.gain;
  3266. clip.pitch = item.pitch;
  3267. clip.reversed = item.reversed;
  3268. // FL's clip stretch (round 167l, FL render: a 6-beat item with stretch 1.5 ends 9 beats later, the song
  3269. // with it): the item's length and start offset are the unstretched ones
  3270. clip.stretch = item.stretch;
  3271. if (clip.stretch != 1.0)
  3272. {
  3273. clip.length = (std::int64_t) std::llround ((double) clip.length * clip.stretch);
  3274. const auto offset = ((double) clip.offset + (double) clip.offsetFraction) * clip.stretch;
  3275. clip.offset = (std::int64_t) std::llround (offset);
  3276. clip.offsetFraction = (float) (offset - (double) clip.offset);
  3277. }
  3278. const auto msToTicks = [&] (float ms)
  3279. { return std::clamp ((std::int64_t) std::llround (ms / 1000.0 * song.bpm / 60.0 * ppq), (std::int64_t) 0, clip.length); };
  3280. clip.fadeIn = msToTicks (item.fadeInMs);
  3281. clip.fadeOut = msToTicks (item.fadeOutMs);
  3282. clips.push_back (clip);
  3283. continue;
  3284. }
  3285. const auto it = patternMap.find (item.index);
  3286. if (it == patternMap.end())
  3287. continue;
  3288. Clip clip;
  3289. clip.pattern = it->second;
  3290. clip.track = item.track;
  3291. clip.start = rescale (item.position);
  3292. clip.length = rescale (item.length);
  3293. clip.offset = item.patternStartTick > 0 ? rescale (item.patternStartTick) : 0;
  3294. clips.push_back (clip);
  3295. }
  3296. std::sort (clips.begin(), clips.end(), [] (const Clip& a, const Clip& b) { return a.start < b.start; });
  3297. Arrangement a;
  3298. a.name = arrangement.name.empty() ? "Arrangement " + std::to_string (song.arrangements.size() + 1) : arrangement.name;
  3299. // markers; type 8 changes the time signature; the other types are FL's marker actions (core/MarkerPlan.h)
  3300. for (const auto& m : arrangement.markers)
  3301. {
  3302. Marker marker;
  3303. marker.tick = rescale (m.position);
  3304. marker.name = m.name;
  3305. marker.name.erase (0, marker.name.find_first_not_of (' '));
  3306. marker.name.erase (marker.name.find_last_not_of (' ') + 1);
  3307. if (m.type != 8 && m.type > 0 && m.type < 256)
  3308. marker.action = m.type; // FL's marker action (9 Start recording, 10 Stop recording, ...)
  3309. if (m.type == 8 && m.numerator >= 1 && m.numerator <= 32 && m.denominator >= 1 && m.denominator <= 32)
  3310. {
  3311. marker.numerator = m.numerator;
  3312. marker.denominator = m.denominator;
  3313. }
  3314. // (unnamed action markers show their action's name on the ruler, as in FL)
  3315. a.markers.push_back (std::move (marker));
  3316. }
  3317. std::stable_sort (a.markers.begin(), a.markers.end(), [] (const Marker& x, const Marker& y) { return x.tick < y.tick; });
  3318. importedTracks.push_back (&arrangement.tracks);
  3319. if (song.arrangements.empty())
  3320. song.playlist = std::move (clips); // the first is the current one
  3321. else
  3322. a.clips = std::move (clips);
  3323. song.arrangements.push_back (std::move (a));
  3324. }
  3325. // the arrangement open when FL saved (event 0x64, REA round 167g); files without it: the fullest is usually the song
  3326. {
  3327. int fullest = -1;
  3328. for (int i = 0; i < (int) project.arrangements.size() && i < (int) song.arrangements.size(); ++i)
  3329. if (project.currentArrangement >= 0 && project.arrangements[(std::size_t) i].index == project.currentArrangement)
  3330. fullest = i;
  3331. if (fullest < 0 && project.currentArrangement != -1)
  3332. fullest = 0; // FL's loader: an index past the last arrangement opens the first
  3333. if (fullest < 0)
  3334. {
  3335. fullest = 0;
  3336. std::size_t most = song.playlist.size();
  3337. for (int i = 1; i < (int) song.arrangements.size(); ++i)
  3338. if (song.arrangements[(std::size_t) i].clips.size() > most)
  3339. {
  3340. most = song.arrangements[(std::size_t) i].clips.size();
  3341. fullest = i;
  3342. }
  3343. }
  3344. song.selectArrangement (fullest);
  3345. // Playlist track names, mute and colour (from the open arrangement); FL's default grey = no colour
  3346. if (fullest < (int) importedTracks.size())
  3347. for (const auto& t : *importedTracks[(std::size_t) fullest])
  3348. {
  3349. const auto coloured = (t.colour & 0xFFFFFF) != 0x485156;
  3350. const auto sized = std::abs (t.heightScale - 1.0f) > 0.01f;
  3351. TrackPerformance performance;
  3352. performance.motion = (TrackPerformance::Motion) std::clamp (t.motion, 0, 6);
  3353. performance.press = (TrackPerformance::Press) std::clamp (t.press, 0, 3);
  3354. performance.triggerSync = (TrackPerformance::Sync) std::clamp (t.triggerSync, 0, 6);
  3355. performance.queue = t.queue;
  3356. performance.tolerant = t.tolerant;
  3357. performance.positionSync = (TrackPerformance::Sync) std::clamp (t.positionSync, 0, 6);
  3358. if (t.index >= 0 && t.index < 500 && (! t.name.empty() || ! t.enabled || coloured || t.grouped || ! t.expanded || sized || t.mode != 0
  3359. || ! performance.isDefault()))
  3360. {
  3361. if ((int) song.playlistTracks.size() <= t.index)
  3362. song.playlistTracks.resize ((std::size_t) t.index + 1);
  3363. auto& track = song.playlistTracks[(std::size_t) t.index];
  3364. track = { t.name, ! t.enabled, 0, coloured ? 0xFF000000u | t.colour : 0u };
  3365. // FL's size is relative to its default row; LYNX keeps the same proportion of its own default
  3366. if (sized)
  3367. track.height = polish::clampTrackHeight ((int) std::lround (polish::defaultTrackHeight * t.heightScale));
  3368. track.grouped = t.index > 0 && t.grouped;
  3369. track.performance = performance; // Performance mode's track settings (round 165m)
  3370. track.collapsed = ! t.expanded;
  3371. // track modes (REA round 146a): an audio track's mixer track, an instrument track's channel
  3372. const auto mixerOk = t.mixerTrack > 0 && t.mixerTrack < (int) song.mixer.size();
  3373. if (t.mode == 1 && mixerOk)
  3374. {
  3375. track.mode = PlaylistTrackMode::audio;
  3376. track.mixerTrack = t.mixerTrack;
  3377. }
  3378. else if (t.mode == 3)
  3379. if (const auto it = channelMap.find (t.channel); it != channelMap.end() && it->second < (int) song.channels.size())
  3380. {
  3381. track.mode = PlaylistTrackMode::instrument;
  3382. track.channel = it->second;
  3383. track.mixerTrack = mixerOk ? t.mixerTrack : song.channels[(std::size_t) it->second].mixerTrack;
  3384. }
  3385. }
  3386. }
  3387. }
  3388. // PAT / SONG as saved (event 0x09, REA round 167g); files without it: SONG when the Playlist has clips
  3389. if (project.songMode >= 0)
  3390. song.mode = project.songMode == 1 ? PlayMode::song : PlayMode::pattern;
  3391. else if (! song.playlist.empty())
  3392. song.mode = PlayMode::song;
  3393. if (song.patterns.empty())
  3394. song.patterns.emplace_back().name = "Pattern 1";
  3395. // The pattern selected when FL saved (event 0x43, REA round 167g); when it is missing or was empty (empty patterns
  3396. // are not imported), the fullest is the best starting point.
  3397. if (const auto it = patternMap.find (project.currentPattern); project.currentPattern > 0 && it != patternMap.end())
  3398. song.currentPattern = it->second;
  3399. else
  3400. for (int i = 0; i < (int) song.patterns.size(); ++i)
  3401. if (song.patterns[(std::size_t) i].notes.size() > song.patterns[(std::size_t) song.currentPattern].notes.size())
  3402. song.currentPattern = i;
  3403. // FPC kits: one channel per pad (last to first, so indices don't shift)
  3404. for (auto it = drumKits.rbegin(); it != drumKits.rend(); ++it)
  3405. splitDrumChannel (song, it->first, it->second);
  3406. numberChorusInstances (song); // the random LFO phases FL gives each Hyper Chorus instance (REA_rodada59 §2.6)
  3407. clipops::updateCrossfades (song); // the project's "Automatic crossfades" on its overlapping audio clips (round 167a)
  3408. return song;
  3409. }
  3410. std::optional<MixerTrack> mixerTrackFromFlPreset (std::span<const std::uint8_t> fileBytes, const FlpImportOptions& options)
  3411. {
  3412. if (! flp::looksLikeMixerPreset (fileBytes))
  3413. return std::nullopt;
  3414. try
  3415. {
  3416. const auto project = flp::parseMixerPreset (fileBytes);
  3417. auto song = importFlp (project, options);
  3418. if (song.mixer.size() < 2)
  3419. return std::nullopt;
  3420. auto track = song.mixer[1];
  3421. track.name = project.mixer[1].name; // (the import's "Insert 1" when the preset has no name)
  3422. track.colour = project.mixer[1].colour != 0 && project.mixer[1].colour != 0x485156 ? 0xFF000000u | project.mixer[1].colour : 0u;
  3423. return track;
  3424. }
  3425. catch (const std::exception&)
  3426. {
  3427. return std::nullopt;
  3428. }
  3429. }
  3430. } // namespace lynx