AlsImport.cpp 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584
  1. #include "core/AlsImport.h"
  2. #include "core/AlsDevices.h"
  3. #include "core/Effects.h"
  4. #include "core/Rack.h"
  5. #include <array>
  6. #include <algorithm>
  7. #include <cmath>
  8. #include <cstdlib>
  9. #include <cstring>
  10. #include <map>
  11. #include <set>
  12. #include <unordered_map>
  13. #include <utility>
  14. #include "core/ClipLauncher.h"
  15. #include "core/DynamicsSuite.h"
  16. #include "core/FlWrapper.h"
  17. #include "core/Gzip.h"
  18. #include "core/LiveScales.h"
  19. #include "core/MissingFiles.h"
  20. #include "core/TimeStretch.h"
  21. #include "core/XmlLite.h"
  22. // Evidence tags as in docs/analise/ALS_FORMAT.md: [DATA] the sets Live 12 ships, [BIN] Live 12.4's member-name table.
  23. namespace lynx
  24. {
  25. namespace
  26. {
  27. using xml::Element;
  28. constexpr double minusInfGain = 0.000316228; // Live's −70 dB fader floor = off [DATA: MidiControllerRange Min]
  29. constexpr double beforeSongTime = -63072000.0; // the automation's "before the song" point [DATA]
  30. std::int64_t ticksOf (double beats) noexcept { return (std::int64_t) std::llround (beats * ppq); }
  31. int intOf (const std::string& s, int fallback = 0)
  32. {
  33. char* end = nullptr;
  34. const auto v = std::strtol (s.c_str(), &end, 10);
  35. return end != s.c_str() ? (int) v : fallback;
  36. }
  37. double numberAttr (const Element& e, std::string_view a, double fallback = 0.0)
  38. {
  39. if (! e.hasAttr (a))
  40. return fallback;
  41. const auto s = e.attr (a);
  42. char* end = nullptr;
  43. const auto v = std::strtod (s.c_str(), &end);
  44. return end != s.c_str() ? v : fallback;
  45. }
  46. std::string trackName (const Element& track)
  47. {
  48. auto n = track.value ("Name/UserName");
  49. if (n.empty())
  50. n = track.value ("Name/EffectiveName");
  51. // Live's auto-numbering marker ("# Drums" → "1 Drums") is shown resolved in EffectiveName
  52. if (n.find ('#') != std::string::npos)
  53. if (const auto eff = track.value ("Name/EffectiveName"); ! eff.empty())
  54. n = eff;
  55. return n;
  56. }
  57. std::string fileStem (const std::string& path)
  58. {
  59. auto name = pathFileName (path);
  60. if (const auto dot = name.find_last_of ('.'); dot != std::string::npos && dot > 0)
  61. name.resize (dot);
  62. return name;
  63. }
  64. std::string joinPath (const std::string& folder, const std::string& rel)
  65. {
  66. if (folder.empty())
  67. return rel;
  68. const auto sep = folder.find ('\\') != std::string::npos && folder.find ('/') == std::string::npos ? '\\' : '/';
  69. auto out = folder;
  70. if (out.back() != '/' && out.back() != '\\')
  71. out += sep;
  72. for (const auto c : rel)
  73. out += (c == '/' || c == '\\') ? sep : c;
  74. return out;
  75. }
  76. // A parameter's automation target id ("AutomationTarget Id" under a parameter element) [DATA]
  77. std::string targetId (const Element& parameter) { return parameter.path ("AutomationTarget").attr ("Id"); }
  78. // How an automated value maps to LYNX's 0..1 for its target
  79. enum class ValueMap { fader, pan, tempo, plain };
  80. struct Target
  81. {
  82. AutomationTarget target;
  83. ValueMap map = ValueMap::plain;
  84. std::string name;
  85. // (round 190cf) a parameter of a Live device that became a LYNX effect: Live's own unit → LYNX's 0..1
  86. std::function<float (double)> law;
  87. };
  88. // (round 190ed) an automated parameter inside a rack, or one of a rack's own macros, kept until the rack has its place
  89. // (an insert's slot or a channel): then a macro of that rack carries the envelope (core/Rack.h macros are the slot's
  90. // automatable parameters 0 … 15)
  91. struct RackAuto
  92. {
  93. std::string id; // the parameter's AutomationTarget Id
  94. std::vector<int> path; // rack nodes from the rack being read down to the document that holds the target
  95. int node = -1; // −1: macro `param` of that document; else the node whose parameter `param` the envelope moves
  96. int param = 0;
  97. std::function<float (double)> law; // Live's value → the target's 0..1
  98. float current = 0.0f; // the target's 0..1 as imported (a new macro starts there: no change in sound)
  99. std::string name;
  100. };
  101. struct Ctx
  102. {
  103. const AlsImportOptions& options;
  104. FlpImportReport* report;
  105. Song song;
  106. std::unordered_map<std::string, Target> targets; // AutomationTarget Id → LYNX target
  107. std::map<std::string, int> audioChannels; // resolved sample path (+ stretch mode) → audioClip channel
  108. int nextRow = 0;
  109. std::set<std::string> missingSeen;
  110. // round 190bq (Live's own devices → LYNX's): a track's Id → its insert (a compressor's side-chain input), the key
  111. // shift of the instrument just read (a Simpler in Slice mode) and of each channel, and whether the instrument
  112. // being read sits on a drum pad (a pad keeps the sample, tuning, level and pan only)
  113. std::map<int, int> insertOfTrack;
  114. int pendingKeyShift = 0;
  115. std::map<int, int> keyShift;
  116. bool inDrumPad = false;
  117. // round 190cf: Live's MIDI effects written into a channel's notes (in the chain's order), and how many leading
  118. // MIDI effects of the next rack read were already taken by the track's channel (a one-chain Instrument Rack)
  119. std::map<int, std::vector<alsdev::NoteEffect>> noteEffects;
  120. int skipLeadingMidi = 0;
  121. std::string signatureTarget; // the main track's TimeSignature AutomationTarget Id (round 190cg)
  122. // round 190ed: every AutomationTarget Id an arrangement envelope points at; where the rack being read collects its
  123. // automated parameters; targets on the channel being read (their index is set when the channel is placed)
  124. std::set<std::string> automated;
  125. std::vector<RackAuto>* rackAutos = nullptr;
  126. std::vector<std::pair<std::string, Target>> channelTargets;
  127. std::set<std::string> explained; // envelopes already listed with their own reason
  128. // round 190ed: a Peak Controller linked to a translated effect's parameter (Auto Filter's LFO / envelope follower),
  129. // placed once its slots are known: the controller's insert and slot (−1 = appended to that insert after every
  130. // track is read: a side-chain source), the effect's insert and slot
  131. struct PendingLink
  132. {
  133. int sourceInsert = -1, sourceSlot = -1;
  134. EffectSlot controller;
  135. int targetTrack = -1, targetSlot = -1, param = 0;
  136. std::vector<float> curve;
  137. std::vector<std::string> notes;
  138. std::string from, what;
  139. };
  140. std::vector<PendingLink> pendingLinks;
  141. // the scale of the first MIDI clip that has Live's clip scale switched on (round 190o)
  142. std::optional<projectkey::Key> clipKey;
  143. bool clipKeySeen = false;
  144. explicit Ctx (const AlsImportOptions& o) : options (o), report (o.common.report) {}
  145. void note (std::map<std::string, int> FlpImportReport::* list, const std::string& what)
  146. {
  147. if (report != nullptr)
  148. ++(report->*list)[what];
  149. }
  150. // A sample reference → a path that exists on this PC ("" = missing; the saved path is reported)
  151. std::string resolveSample (const Element& sampleRef, const std::string& user)
  152. {
  153. const auto fileRef = sampleRef.child ("FileRef");
  154. if (! fileRef)
  155. return {};
  156. const auto type = (int) fileRef.number ("RelativePathType", 0);
  157. auto rel = fileRef.value ("RelativePath");
  158. if (rel.empty()) // Live ≤ 10 style: a list of folder names [model]
  159. for (const auto& el : fileRef.path ("RelativePath").children ("RelativePathElement"))
  160. rel += (rel.empty() ? "" : "/") + el.attr ("Dir");
  161. const auto saved = fileRef.value ("Path");
  162. const auto& exists = options.common.fileExists;
  163. std::vector<std::string> candidates;
  164. if (const auto it = options.common.relocations.find (saved); it != options.common.relocations.end())
  165. candidates.push_back (it->second);
  166. if (! rel.empty())
  167. {
  168. if (type == 1 || type == 0)
  169. candidates.push_back (joinPath (options.common.projectFolder, rel));
  170. for (const auto& root : options.libraryRoots)
  171. candidates.push_back (joinPath (root, rel));
  172. }
  173. if (! saved.empty())
  174. candidates.push_back (saved);
  175. // a set moved without its folder structure: the file next to it, or in its Samples folders
  176. if (const auto name = pathFileName (saved.empty() ? rel : saved); ! name.empty())
  177. for (const auto* sub : { "", "Samples/Imported", "Samples/Recorded", "Samples/Processed/Consolidate", "Samples/Processed/Crop",
  178. "Samples/Processed/Freeze", "Samples/Processed/Reverse" })
  179. candidates.push_back (joinPath (options.common.projectFolder, std::string (sub).empty() ? name : std::string (sub) + "/" + name));
  180. if (exists)
  181. for (const auto& c : candidates)
  182. if (! c.empty() && exists (c))
  183. {
  184. if (report != nullptr && c != saved && ! saved.empty() && c != candidates.front())
  185. {
  186. ++report->relocatedSamples;
  187. report->relocatedFiles.push_back ({ saved, c });
  188. }
  189. return c;
  190. }
  191. const auto shown = saved.empty() ? rel : saved;
  192. if (report != nullptr && ! shown.empty())
  193. {
  194. if (missingSeen.insert (shown).second)
  195. ++report->missingSamples;
  196. addMissingFile (report->missingFiles, shown, user);
  197. }
  198. return {};
  199. }
  200. };
  201. // ---------------------------------------------------------------------------------------------------------------
  202. // Plugins [BIN: AVstPluginInfo / AVst3PluginInfo / AVst3Preset / AVstPreset members]
  203. std::optional<ForeignPlugin> pluginOf (const Element& device)
  204. {
  205. const auto desc = device.child ("PluginDesc");
  206. if (! desc)
  207. return std::nullopt;
  208. ForeignPlugin p;
  209. if (const auto v3 = desc.child ("Vst3PluginInfo"))
  210. {
  211. p.format = ForeignPlugin::Format::vst3;
  212. p.name = v3.value ("Name");
  213. std::array<std::int32_t, 4> f {};
  214. for (int k = 0; k < 4; ++k)
  215. f[(std::size_t) k] = (std::int32_t) std::strtoll (v3.value ("Uid/Fields." + std::to_string (k), "0").c_str(), nullptr, 10);
  216. p.classId = alsVst3ClassId (f);
  217. p.hasClassId = f != std::array<std::int32_t, 4> {};
  218. const auto preset = v3.path ("Preset/Vst3Preset");
  219. const auto component = alsHexDecode (preset.child ("ProcessorState").text());
  220. const auto controller = alsHexDecode (preset.child ("ControllerState").text());
  221. // FL's VST3 record layout (FlWrapper.h splitFlVst3State), which the plugin resolver turns into JUCE's state
  222. if (! component.empty() || ! controller.empty())
  223. {
  224. auto put32 = [&p] (std::uint32_t v) { for (int k = 0; k < 4; ++k) p.state.push_back ((std::uint8_t) (v >> (8 * k))); };
  225. auto put64 = [&p] (std::uint64_t v) { for (int k = 0; k < 8; ++k) p.state.push_back ((std::uint8_t) (v >> (8 * k))); };
  226. auto record = [&] (std::uint32_t id, const std::vector<std::uint8_t>& bytes) {
  227. put32 (id);
  228. put64 (bytes.size());
  229. p.state.insert (p.state.end(), bytes.begin(), bytes.end());
  230. };
  231. put32 (1);
  232. std::vector<std::uint8_t> head (64, 0);
  233. head[0] = 1;
  234. record (1, head);
  235. record (3, component);
  236. record (2, controller);
  237. }
  238. return p;
  239. }
  240. if (const auto v2 = desc.child ("VstPluginInfo"))
  241. {
  242. p.format = ForeignPlugin::Format::vst2;
  243. p.name = v2.value ("PlugName");
  244. p.path = v2.value ("Path");
  245. p.vst2Id = (std::uint32_t) std::strtoll (v2.value ("UniqueId", "0").c_str(), nullptr, 10);
  246. const auto preset = v2.path ("Preset/VstPreset");
  247. const auto buffer = alsHexDecode (preset.child ("Buffer").text());
  248. if (! buffer.empty())
  249. {
  250. FlVst2State s;
  251. s.currentProgram = (std::int32_t) preset.number ("ProgramNumber", 0);
  252. const auto params = (std::size_t) std::max (0.0, preset.number ("ParameterCount", 0));
  253. // VstPreset/Type is the fxp/fxb four-character code [LIVE: kHs Gain VST2 saved by Live 12.4 = 'FBCh', Buffer
  254. // = the raw effGetChunk bytes]: 'FBCh' / 'FPCh' → a chunk; 'FxBk' / 'FxCk' → the parameter values
  255. const auto type = (std::uint32_t) (std::int64_t) preset.number ("Type", 0);
  256. const auto usesChunks = type == 0x46426368u || type == 0x46506368u;
  257. if (! usesChunks && params > 0 && buffer.size() == params * 4)
  258. {
  259. // a plugin without chunks: its parameter values, 32-bit floats [model; TODO-LIVE: the byte order]
  260. const auto big = preset.number ("ByteOrder", 0) != 0;
  261. for (std::size_t k = 0; k < params; ++k)
  262. {
  263. std::uint32_t u = 0;
  264. for (int b = 0; b < 4; ++b)
  265. u |= (std::uint32_t) buffer[k * 4 + (std::size_t) (big ? 3 - b : b)] << (8 * b);
  266. float f;
  267. std::memcpy (&f, &u, 4);
  268. s.params.push_back (f);
  269. }
  270. }
  271. else
  272. {
  273. s.flags = 8; // the plugin uses chunks
  274. s.chunk = buffer;
  275. }
  276. p.state = writeFlVst2State (s);
  277. }
  278. return p;
  279. }
  280. if (const auto au = desc.child ("AuPluginInfo"))
  281. {
  282. p.format = ForeignPlugin::Format::other; // macOS Audio Units: kept by name only
  283. p.name = au.value ("Name");
  284. return p;
  285. }
  286. return std::nullopt;
  287. }
  288. // Live's instrument devices [DATA: the device tags in the shipped sets]
  289. bool isInstrumentDevice (std::string_view tag)
  290. {
  291. static const std::set<std::string_view> names { "OriginalSimpler", "MultiSampler", "InstrumentGroupDevice", "DrumGroupDevice",
  292. "Operator", "InstrumentVector", "Drift", "InstrumentMeld", "UltraAnalog", "LoungeLizard",
  293. "StringStudio", "Collision", "Tension", "InstrumentImpulse", "MxDeviceInstrument",
  294. "DrumSampler" };
  295. return names.count (tag) > 0;
  296. }
  297. bool isMidiEffect (std::string_view tag) { return tag.starts_with ("Midi") || tag == "MxDeviceMidiEffect"; }
  298. // A readable name for a native device, for the report ("Eq8" → "EQ Eight" is Live's own naming; the report keeps
  299. // the stored device name so nothing trademarked is invented)
  300. std::string deviceName (const Element& device)
  301. {
  302. auto n = device.value ("UserName");
  303. return n.empty() ? std::string (device.name()) : n + " (" + std::string (device.name()) + ")";
  304. }
  305. // The first sample part of a Simpler / Sampler as a zone
  306. std::vector<SampleZone> zonesOf (Ctx& ctx, const Element& device, const std::string& user)
  307. {
  308. std::vector<SampleZone> zones;
  309. for (const auto& part : device.path ("Player/MultiSampleMap/SampleParts").children ("MultiSamplePart"))
  310. {
  311. SampleZone z;
  312. z.path = ctx.resolveSample (part.child ("SampleRef"), user);
  313. if (z.path.empty())
  314. continue;
  315. z.rootKey = (int) part.number ("RootKey", 60);
  316. z.lowKey = (int) part.number ("KeyRange/Min", 0);
  317. z.highKey = (int) part.number ("KeyRange/Max", 127);
  318. z.lowVelocity = (int) part.number ("VelocityRange/Min", 1);
  319. z.highVelocity = (int) part.number ("VelocityRange/Max", 127);
  320. z.tune = (float) (part.number ("Detune", 0) / 100.0);
  321. z.gain = (float) part.number ("Volume", 1);
  322. if (part.number ("SustainLoop/Mode", 0) != 0)
  323. {
  324. z.loopStart = (std::int64_t) part.number ("SustainLoop/Start", 0);
  325. z.loopEnd = (std::int64_t) part.number ("SustainLoop/End", 0);
  326. z.loopMode = 1;
  327. }
  328. zones.push_back (std::move (z));
  329. }
  330. return zones;
  331. }
  332. // Simpler's envelope (seconds from Live's ms) [DATA: Envelope/AttackTime … in the device, ms]
  333. void applySimplerEnvelope (const Element& device, SamplerSettings& s)
  334. {
  335. const auto env = device.child ("VolumeAndPan").child ("Envelope") ? device.path ("VolumeAndPan/Envelope") : device.child ("Envelope");
  336. if (! env)
  337. return;
  338. const auto ms = [&env] (const char* name, double fallback) { return env.number (std::string (name) + "/Manual", fallback) / 1000.0; };
  339. s.attack = (float) std::clamp (ms ("AttackTime", 0.1), 0.0, 2.0);
  340. s.decay = (float) std::max (0.0, ms ("DecayTime", 600));
  341. s.sustain = (float) std::clamp (env.number ("SustainLevel/Manual", 1), 0.0, 1.0);
  342. s.release = (float) std::clamp (ms ("ReleaseTime", 50), 0.0, 4.0);
  343. }
  344. bool instrumentFrom (Ctx& ctx, const Element& device, ChannelDef& channel, std::vector<DrumPad>* pads, int depth = 0);
  345. // ---------------------------------------------------------------------------------------------------------------
  346. // Racks (round 183c, docs/analise/REA_rodada183c.md §1–5 [DATA]): Live's Audio Effect / Instrument Racks become LYNX
  347. // racks (a Patcher in rack mode, core/Rack.h) with their chains, zones, chain mixers, macros, variations and the macro
  348. // mappings onto the devices LYNX keeps (plugins, nested racks, the chains' volume / pan, the chain selector). Live's own
  349. // devices inside a chain are dropped and listed, as on a track.
  350. // A macro mapping stored on a parameter: KeyMidi on channel 16, NoteOrController = the macro, MidiControllerRange =
  351. // the range in the parameter's own units [DATA]. nullopt = not mapped.
  352. struct LiveMapping
  353. {
  354. int macro = 0;
  355. double min = 0.0, max = 1.0;
  356. };
  357. std::optional<LiveMapping> mappingOf (const Element& parameter)
  358. {
  359. const auto key = parameter.child ("KeyMidi");
  360. if (! key || (int) key.number ("Channel", -1) != 16)
  361. return std::nullopt;
  362. LiveMapping m;
  363. m.macro = (int) key.number ("NoteOrController", -1);
  364. if (m.macro < 0 || m.macro >= rackMacroCount)
  365. return std::nullopt;
  366. m.min = parameter.number ("MidiControllerRange/Min", 0.0);
  367. m.max = parameter.number ("MidiControllerRange/Max", 1.0);
  368. return m;
  369. }
  370. void mapInto (PatcherDoc& doc, const LiveMapping& m, RackMapping target, float min, float max)
  371. {
  372. target.min = std::clamp (min, 0.0f, 1.0f);
  373. target.max = std::clamp (max, 0.0f, 1.0f);
  374. rack::map (doc, m.macro, target);
  375. }
  376. // The plugin parameters of a PluginDevice that a macro drives (VST2: ParameterId is the parameter's index [model];
  377. // VST3 ids are not indices: listed, not mapped)
  378. void pluginMappings (Ctx& ctx, const Element& device, PatcherDoc& doc, int node)
  379. {
  380. const auto vst3 = (bool) device.path ("PluginDesc/Vst3PluginInfo");
  381. for (const auto& p : device.path ("ParameterList").children ("PluginFloatParameter"))
  382. if (const auto m = mappingOf (p.child ("ParameterValue")))
  383. {
  384. if (vst3)
  385. {
  386. ctx.note (&FlpImportReport::approximated, "Macro mapping on a VST3 parameter (not kept)");
  387. continue;
  388. }
  389. RackMapping target;
  390. target.node = node;
  391. target.param = (int) p.number ("ParameterId", -1);
  392. if (target.param >= 0)
  393. mapInto (doc, *m, target, (float) m->min, (float) m->max);
  394. }
  395. }
  396. // (round 190ed) The envelopes on a plugin's parameters. Live keeps a VST2 parameter as 0..1 [DATA, model] and its
  397. // ParameterId is its index [model], which LYNX's plugin parameters use too. (round 190ek) A VST3's ParameterId is the
  398. // plugin's own ParamID and its envelope holds the parameter's plain value, between the MidiControllerRange Live saves
  399. // for it [MEASURED in a Live 12.4 save, round 190ei: kHs Gain's "Gain" ParamID 1, range 0.0316 … 31.62, envelope points
  400. // 0.2486 … 28.52; "mode" ParamID 414, 0 … 1; 126 unused entries ParameterId −1]. Such a parameter is carried as slot k
  401. // = its place among the device's parameters with an id (FL's VST3 automation slots, core/FlWrapper.h, which the plugin
  402. // host turns into the plugin's own order when it opens it: `vst3Slots` gets the ParamIDs), its value mapped linearly over
  403. // that range (exact for 0 … 1, the usual range; another range is listed as approximate — the plugin's own curve
  404. // between the ends is known only to the plugin). `inRack`: the host does not remap a plugin inside a rack: listed there.
  405. void pluginAutos (Ctx& ctx, const Element& device, const std::string& plugin,
  406. const std::function<void (const std::string& id, int param, float current, const std::string& name, std::function<float (double)> law)>& sink,
  407. std::vector<std::int32_t>* vst3Slots = nullptr, bool inRack = false)
  408. {
  409. const auto vst3 = (bool) device.path ("PluginDesc/Vst3PluginInfo");
  410. int slot = 0;
  411. for (const auto& p : device.path ("ParameterList").children ("PluginFloatParameter"))
  412. {
  413. const auto paramId = (std::int64_t) p.number ("ParameterId", -1);
  414. const auto mySlot = paramId >= 0 ? slot++ : -1;
  415. const auto id = targetId (p.child ("ParameterValue"));
  416. if (id.empty() || ctx.automated.count (id) == 0)
  417. continue;
  418. auto name = p.value ("ParameterName");
  419. if (! vst3)
  420. {
  421. if (paramId < 0)
  422. continue;
  423. sink (id, (int) paramId, (float) std::clamp (p.number ("ParameterValue/Manual", 0.0), 0.0, 1.0),
  424. plugin + " " + (name.empty () ? "#" + std::to_string (paramId) : name), [] (double v) { return (float) std::clamp (v, 0.0, 1.0); });
  425. continue;
  426. }
  427. if (inRack || vst3Slots == nullptr || mySlot < 0)
  428. {
  429. ctx.note (&FlpImportReport::unsupported, "Automation of a VST3 plugin's parameter inside a rack (" + plugin + ": LYNX maps a VST3's own parameter ids on inserts and channels)");
  430. ctx.explained.insert (id);
  431. continue;
  432. }
  433. const auto lo = p.number ("ParameterValue/MidiControllerRange/Min", 0.0), hi = p.number ("ParameterValue/MidiControllerRange/Max", 1.0);
  434. const auto span = std::abs (hi - lo) > 1.0e-12 ? hi - lo : 1.0;
  435. if (std::abs (lo) > 1.0e-6 || std::abs (hi - 1.0) > 1.0e-6)
  436. ctx.note (&FlpImportReport::approximated, "Automation of a VST3 parameter with its own range (" + plugin + " " + name
  437. + ": Live's plain values mapped linearly between the range's ends)");
  438. if ((std::size_t) mySlot >= vst3Slots->size())
  439. vst3Slots->resize ((std::size_t) mySlot + 1, -1);
  440. (*vst3Slots)[(std::size_t) mySlot] = (std::int32_t) paramId;
  441. const auto law = [lo, span] (double v) { return (float) std::clamp ((v - lo) / span, 0.0, 1.0); };
  442. sink (id, mySlot, law (p.number ("ParameterValue/Manual", lo)), plugin + " " + (name.empty () ? "#" + std::to_string (paramId) : name), law);
  443. }
  444. // every parameter with an id keeps its slot (the host gives the slots it does not list the next free ones)
  445. if (vst3 && vst3Slots != nullptr && ! vst3Slots->empty())
  446. {
  447. slot = 0;
  448. for (const auto& p : device.path ("ParameterList").children ("PluginFloatParameter"))
  449. if (const auto paramId = (std::int64_t) p.number ("ParameterId", -1); paramId >= 0)
  450. {
  451. if ((std::size_t) slot >= vst3Slots->size())
  452. vst3Slots->resize ((std::size_t) slot + 1, -1);
  453. (*vst3Slots)[(std::size_t) slot++] = (std::int32_t) paramId;
  454. }
  455. }
  456. }
  457. // (round 190ek) The automation slots of a VST3 as FL's record 4 (u32 N + N × i32 ParamID) in its state (FL's record
  458. // layout, which pluginOf writes), read by the plugin host to put each automation on the plugin's own parameter
  459. void appendVst3Slots (ForeignPlugin& plugin, const std::vector<std::int32_t>& slots)
  460. {
  461. if (slots.empty() || plugin.format != ForeignPlugin::Format::vst3 || plugin.state.size() < 4)
  462. return;
  463. auto put32 = [&plugin] (std::uint32_t v) { for (int k = 0; k < 4; ++k) plugin.state.push_back ((std::uint8_t) (v >> (8 * k))); };
  464. put32 (4);
  465. const auto size = (std::uint64_t) (4 + 4 * slots.size());
  466. for (int k = 0; k < 8; ++k)
  467. plugin.state.push_back ((std::uint8_t) (size >> (8 * k)));
  468. put32 ((std::uint32_t) slots.size());
  469. for (const auto id : slots)
  470. put32 ((std::uint32_t) id);
  471. }
  472. // (round 190ed) The macro of rack `doc` that drives a target `path` leads to from `depth`: the target itself when it is
  473. // a macro of `doc`, else a free macro of `doc` (no mapping, no name of its own, not under an envelope itself) mapped
  474. // over the target's whole range and set to the target's value (nothing moves; Rand and variations leave it alone).
  475. // A target in a nested rack goes through a free macro of each rack on the way. −1 when no macro is free.
  476. int bindMacro (PatcherDoc& doc, const std::vector<RackAuto>& all, const RackAuto& a, std::size_t depth)
  477. {
  478. auto* r = rack::rackOf (doc);
  479. if (r == nullptr)
  480. return -1;
  481. if (depth == a.path.size() && a.node < 0)
  482. return a.param >= 0 && a.param < rackMacroCount ? a.param : -1;
  483. RackMapping target;
  484. auto value = a.current;
  485. if (depth == a.path.size())
  486. {
  487. target.node = a.node;
  488. target.param = a.param;
  489. }
  490. else
  491. {
  492. const auto n = a.path[depth];
  493. if (n < 0 || n >= (int) doc.nodes.size())
  494. return -1;
  495. auto& node = doc.nodes[(std::size_t) n];
  496. auto& inner = node.generator ? node.channel.patcher : node.effect.patcher;
  497. const auto k = bindMacro (inner, all, a, depth + 1);
  498. if (k < 0 || rack::rackOf (inner) == nullptr)
  499. return -1;
  500. target.node = n;
  501. target.param = k;
  502. value = rack::rackOf (inner)->macros[(std::size_t) k].value / 127.0f;
  503. r = rack::rackOf (doc);
  504. }
  505. // a second envelope reaching the same target uses the macro already bound to it
  506. for (int k = 0; k < rackMacroCount; ++k)
  507. for (const auto& m : r->macros[(std::size_t) k].mappings)
  508. if (m.target == RackMapping::Target::param && m.node == target.node && m.param == target.param && m.min == 0.0f && m.max == 1.0f)
  509. return k;
  510. std::set<int> reserved;
  511. for (const auto& other : all)
  512. if (other.node < 0 && other.path.size() == depth && std::equal (other.path.begin(), other.path.end(), a.path.begin()))
  513. reserved.insert (other.param);
  514. for (int k = 0; k < rackMacroCount; ++k)
  515. {
  516. auto& m = r->macros[(std::size_t) k];
  517. if (! m.mappings.empty() || ! m.name.empty() || reserved.count (k) != 0)
  518. continue;
  519. target.min = 0.0f;
  520. target.max = 1.0f;
  521. if (! rack::map (doc, k, target))
  522. return -1;
  523. r = rack::rackOf (doc);
  524. auto& bound = r->macros[(std::size_t) k];
  525. bound.name = a.name;
  526. bound.excludeFromRandom = bound.excludeFromVariations = true;
  527. while (r->shownMacros <= k && r->shownMacros < rackMacroCount)
  528. r->shownMacros = rack::moreMacros (r->shownMacros);
  529. rack::setMacro (doc, k, std::clamp (value, 0.0f, 1.0f) * 127.0f);
  530. rack::compile (doc);
  531. return k;
  532. }
  533. return -1;
  534. }
  535. // (round 190ed) A rack has its place: each envelope it collected targets the rack's macro that carries it
  536. void placeRackAutos (Ctx& ctx, PatcherDoc& doc, const std::vector<RackAuto>& autos, const std::function<AutomationTarget (int macro)>& at,
  537. bool onChannel = false)
  538. {
  539. for (const auto& a : autos)
  540. {
  541. const auto k = bindMacro (doc, autos, a, 0);
  542. if (k < 0)
  543. {
  544. ctx.note (&FlpImportReport::unsupported, "Automation inside a rack whose macros are all in use (" + a.name + ")");
  545. ctx.explained.insert (a.id);
  546. continue;
  547. }
  548. if (onChannel)
  549. ctx.channelTargets.push_back ({ a.id, Target { at (k), ValueMap::plain, a.name, a.law } });
  550. else
  551. ctx.targets[a.id] = { at (k), ValueMap::plain, a.name, a.law };
  552. }
  553. }
  554. bool rackFrom (Ctx& ctx, const Element& device, PatcherDoc& doc, int depth);
  555. // One of Live's own audio effects as the LYNX effect in its role, settings translated (round 190bq, core/AlsDevices.h).
  556. // The report lists the pair — under "converted" when the maths is the same, under "kept but approximated" when the
  557. // pair is fitted — and every setting that is clamped, fitted or has no counterpart. False: not a device LYNX maps (or
  558. // its element lacks the parameters): the caller drops and lists it as before.
  559. bool nativeEffectFrom (Ctx& ctx, const Element& d, EffectSlot& slot, std::vector<alsdev::ParamLink>* links = nullptr, std::string* name = nullptr,
  560. std::optional<alsdev::Translated::Modulator>* modulator = nullptr)
  561. {
  562. alsdev::Context context;
  563. context.bpm = ctx.song.bpm;
  564. auto t = alsdev::effectFromLiveDevice (d, context);
  565. if (! t)
  566. return false;
  567. // (round 190ed) a modulation from outside the effect (Auto Filter's LFO / envelope follower): the caller places
  568. // its Peak Controller and link; inside a rack chain no link can be made, so it is listed
  569. if (t->modulator)
  570. {
  571. if (modulator != nullptr)
  572. *modulator = std::move (t->modulator);
  573. else
  574. t->notes.dropped.push_back (t->modulator->what + " on the cutoff inside a rack");
  575. }
  576. if (links != nullptr)
  577. *links = t->links;
  578. if (name != nullptr)
  579. *name = t->from;
  580. if (t->side.on)
  581. {
  582. const auto it = t->side.trackId >= 0 ? ctx.insertOfTrack.find (t->side.trackId) : ctx.insertOfTrack.end();
  583. if (it != ctx.insertOfTrack.end())
  584. {
  585. t->slot.sidechain = it->second;
  586. if (t->side.otherTap)
  587. t->notes.approximated.push_back ("side-chain input taken after the source track's fader");
  588. }
  589. else
  590. {
  591. if (t->sideParam >= 0)
  592. t->slot.params[(std::size_t) t->sideParam] = 0.0f;
  593. t->notes.dropped.push_back ("side-chain input (its source is not a track of the set; the device hears its own input)");
  594. }
  595. }
  596. const auto pair = t->from + " -> " + t->to;
  597. if (t->approximate)
  598. ctx.note (&FlpImportReport::partialEffects, pair + " (settings fitted to LYNX's engine)");
  599. else
  600. ctx.note (&FlpImportReport::converted, pair);
  601. for (const auto& n : t->notes.approximated)
  602. ctx.note (&FlpImportReport::partialEffects, t->from + ": " + n);
  603. for (const auto& n : t->notes.dropped)
  604. ctx.note (&FlpImportReport::partialEffects, t->from + ": " + n + " (not applied)");
  605. slot = std::move (t->slot);
  606. return true;
  607. }
  608. // A Live member name as words: "FormantShift" → "Formant Shift"
  609. std::string spacedName (std::string_view tag)
  610. {
  611. std::string out;
  612. for (std::size_t i = 0; i < tag.size(); ++i)
  613. {
  614. const auto c = tag[i];
  615. const auto upper = c >= 'A' && c <= 'Z';
  616. const auto prevLower = i > 0 && ((tag[i - 1] >= 'a' && tag[i - 1] <= 'z') || (tag[i - 1] >= '0' && tag[i - 1] <= '9'));
  617. if (upper && prevLower)
  618. out += ' ';
  619. out += c;
  620. }
  621. return out;
  622. }
  623. // One device of a rack chain → a Patcher node (−1 = dropped and listed)
  624. int rackDeviceFrom (Ctx& ctx, const Element& d, PatcherDoc& doc, int chain, bool instrumentRack, int depth, bool* native = nullptr,
  625. std::set<std::string>* mappedLinks = nullptr)
  626. {
  627. const auto tag = std::string (d.name());
  628. PatchNode node;
  629. if (tag == "PluginDevice")
  630. {
  631. const auto p = pluginOf (d);
  632. if (! p)
  633. return -1;
  634. // in an Instrument Rack chain, the chain's instrument: a VST3 Live marks as one (DeviceType 1 [DATA]) or a VST2
  635. // with no audio input (NumAudioInputs 0 [DATA]), when the chain has none yet
  636. const auto chainNodes = rack::devices (*rack::rackOf (doc), chain);
  637. const auto hasInstrument = std::any_of (chainNodes.begin(), chainNodes.end(), [&doc] (int n) { return doc.nodes[(std::size_t) n].generator; });
  638. const auto asInstrument = instrumentRack && ! hasInstrument
  639. && ((int) d.number ("PluginDesc/Vst3PluginInfo/DeviceType", 0) == 1
  640. || ((bool) d.path ("PluginDesc/VstPluginInfo") && (int) d.number ("PluginDesc/VstPluginInfo/NumAudioInputs", 2) == 0));
  641. if (asInstrument)
  642. {
  643. node.generator = true;
  644. node.channel.instrument = InstrumentKind::plugin;
  645. node.channel.plugin.name = p->name;
  646. node.channel.plugin.foreign = *p;
  647. node.channel.name = p->name;
  648. }
  649. else
  650. {
  651. node.effect.kind = EffectKind::plugin;
  652. node.effect.enabled = d.boolean ("On/Manual", true);
  653. node.effect.plugin.name = p->name;
  654. node.effect.plugin.foreign = *p;
  655. }
  656. ctx.note (&FlpImportReport::converted, "Plugin: " + p->name);
  657. const auto n = rack::addDevice (doc, chain, std::move (node));
  658. if (n >= 0)
  659. {
  660. pluginMappings (ctx, d, doc, n);
  661. pluginAutos (
  662. ctx, d, p->name,
  663. [&ctx, n] (const std::string& id, int param, float current, const std::string& name, std::function<float (double)> law) {
  664. if (ctx.rackAutos != nullptr)
  665. ctx.rackAutos->push_back ({ id, {}, n, param, std::move (law), current, name });
  666. },
  667. nullptr, true);
  668. }
  669. return n;
  670. }
  671. if ((tag == "AudioEffectGroupDevice" || tag == "InstrumentGroupDevice") && depth < 8)
  672. {
  673. auto inner = rack::makeRack (tag == "InstrumentGroupDevice" ? RackDoc::Kind::instrument : RackDoc::Kind::audioEffect);
  674. // (round 190ed) the inner rack's automated targets: reached from here through this node
  675. std::vector<RackAuto> innerAutos;
  676. auto* const outerAutos = std::exchange (ctx.rackAutos, &innerAutos);
  677. const auto read = rackFrom (ctx, d, inner, depth + 1);
  678. ctx.rackAutos = outerAutos;
  679. if (! read)
  680. return -1;
  681. if (tag == "InstrumentGroupDevice")
  682. {
  683. node.generator = true;
  684. node.channel.instrument = InstrumentKind::patcher;
  685. node.channel.name = d.value ("UserName");
  686. node.channel.patcher = std::move (inner);
  687. }
  688. else
  689. {
  690. node.effect = makeEffectSlot (EffectKind::patcher);
  691. node.effect.enabled = d.boolean ("On/Manual", true);
  692. node.effect.patcher = std::move (inner);
  693. }
  694. node.label = d.value ("UserName");
  695. const auto n = rack::addDevice (doc, chain, std::move (node));
  696. if (n < 0)
  697. return -1;
  698. if (ctx.rackAutos != nullptr)
  699. for (auto& a : innerAutos)
  700. {
  701. a.path.insert (a.path.begin(), n);
  702. ctx.rackAutos->push_back (std::move (a));
  703. }
  704. // the inner rack's macros mapped onto the outer rack's (0…127 → 0..1) [DATA]
  705. for (int k = 0; k < rackMacroCount; ++k)
  706. if (const auto m = mappingOf (d.child ("MacroControls." + std::to_string (k))))
  707. {
  708. RackMapping target;
  709. target.node = n;
  710. target.param = k;
  711. mapInto (doc, *m, target, (float) (m->min / 127.0), (float) (m->max / 127.0));
  712. }
  713. return n;
  714. }
  715. if (instrumentRack && isInstrumentDevice (tag))
  716. {
  717. ChannelDef channel;
  718. channel.name = d.value ("UserName");
  719. if (instrumentFrom (ctx, d, channel, nullptr, depth + 1))
  720. {
  721. node.generator = true;
  722. node.channel = std::move (channel);
  723. return rack::addDevice (doc, chain, std::move (node));
  724. }
  725. return -1;
  726. }
  727. if (isMidiEffect (tag))
  728. {
  729. ctx.note (&FlpImportReport::unsupported, deviceName (d));
  730. return -1;
  731. }
  732. // (round 190bq) Live's own effects LYNX has an engine for: the LYNX effect in the chain
  733. std::vector<alsdev::ParamLink> links;
  734. std::string from;
  735. if (! isInstrumentDevice (tag) && nativeEffectFrom (ctx, d, node.effect, &links, &from))
  736. {
  737. node.label = d.value ("UserName");
  738. const auto n = rack::addDevice (doc, chain, std::move (node));
  739. if (n >= 0 && native != nullptr)
  740. *native = true;
  741. // (round 190ed) envelopes on its parameters: carried by a macro of the rack once the rack has its place
  742. if (n >= 0 && ctx.rackAutos != nullptr)
  743. for (const auto& l : links)
  744. if (const auto id = targetId (d.path (l.live)); ! id.empty() && ctx.automated.count (id) != 0)
  745. ctx.rackAutos->push_back ({ id, {}, n, l.param, l.value, doc.nodes[(std::size_t) n].effect.params[(std::size_t) l.param],
  746. from + " " + spacedName (pathFileName (l.live)) });
  747. // (round 190cf) the rack's macros drive the LYNX effect's parameters over the range the mapping holds, each
  748. // end through the parameter's law (between the ends the macro moves LYNX's control in a straight line)
  749. if (n >= 0)
  750. for (const auto& l : links)
  751. if (const auto m = mappingOf (d.path (l.live)))
  752. {
  753. RackMapping target;
  754. target.node = n;
  755. target.param = l.param;
  756. mapInto (doc, *m, target, l.value (m->min), l.value (m->max));
  757. if (mappedLinks != nullptr)
  758. mappedLinks->insert (l.live);
  759. }
  760. if (n >= 0)
  761. return n;
  762. }
  763. ctx.note (&FlpImportReport::droppedEffects, deviceName (d));
  764. return -1;
  765. }
  766. RackZone zoneOf (const Element& range, RackZone fallback)
  767. {
  768. if (! range)
  769. return fallback;
  770. RackZone z;
  771. z.lo = std::clamp ((int) range.number ("Min", fallback.lo), 0, 127);
  772. z.hi = std::clamp ((int) range.number ("Max", fallback.hi), z.lo, 127);
  773. z.fadeLo = std::clamp ((int) range.number ("CrossfadeMin", z.lo), z.lo, z.hi);
  774. z.fadeHi = std::clamp ((int) range.number ("CrossfadeMax", z.hi), z.fadeLo, z.hi);
  775. return z;
  776. }
  777. // A Drum Rack pad (round 190ec, docs/analise/ALS_FORMAT.md §7): DrumBranch/BranchInfo {ReceivingNote = 128 − the key, 0 = all
  778. // notes; SendingNote = the key played; ChokeGroup 0 none, 1…16} [DATA: the shipped kits, pad names against clip notes],
  779. // the chain's sends (MixerDevice/SendInfos/AudioBranchSendInfo {Index, Send (linear gain, −70 dB floor = off), EnabledByUser})
  780. // and its Audio To (RoutingHelper/Routable/Target "…/DeviceIn.<d>.R<k>,ChainIn" = return chain k; "AudioOut/None" = the
  781. // rack's output) [DATA: Drums Lesson routes all 16 pads into "a Mix Bus" that way]
  782. void drumPadFrom (const Element& branch, RackChain& chain, std::vector<std::vector<std::pair<int, RackSend>>>& sends, std::vector<int>& audioTo)
  783. {
  784. const auto receiving = (int) branch.number ("BranchInfo/ReceivingNote", 128 - rack::drumFirstPad);
  785. chain.receive = receiving >= 1 && receiving <= 128 ? 128 - receiving : -1;
  786. chain.play = std::clamp ((int) branch.number ("BranchInfo/SendingNote", rack::drumPlayNote), 0, 127);
  787. chain.choke = std::clamp ((int) branch.number ("BranchInfo/ChokeGroup", 0), 0, rack::drumChokeGroups);
  788. std::vector<std::pair<int, RackSend>> mine;
  789. for (const auto& info : branch.path ("MixerDevice/SendInfos").children ("AudioBranchSendInfo"))
  790. {
  791. RackSend x;
  792. const auto level = info.number ("Send/Manual", 0.0);
  793. x.level = level > 0.000317 ? (float) std::clamp (level, 0.0, 1.0) : 0.0f; // (Live's floor, −70 dB, is −inf)
  794. x.on = info.boolean ("EnabledByUser", true);
  795. mine.emplace_back ((int) info.number ("Index", (double) mine.size()), x);
  796. }
  797. sends.push_back (std::move (mine));
  798. const auto target = branch.value ("MixerDevice/RoutingHelper/Routable/Target");
  799. int to = -1;
  800. if (const auto at = target.rfind (".R"); at != std::string::npos && target.find (",ChainIn", at) != std::string::npos)
  801. to = std::atoi (target.c_str() + at + 2);
  802. audioTo.push_back (to);
  803. }
  804. void drumReturnsFrom (Ctx& ctx, const Element& device, PatcherDoc& doc, int depth)
  805. {
  806. for (const auto& branch : device.path ("ReturnBranches").children())
  807. {
  808. auto name = branch.value ("Name/UserName");
  809. if (name.empty()) // (Live's EffectiveName carries the letter it shows, "a Mix Bus": LYNX adds it itself)
  810. {
  811. name = branch.value ("Name/EffectiveName");
  812. const auto* before = rack::rackOf (doc);
  813. const auto letter = rack::returnLetter (before != nullptr ? (int) before->returns.size() : 0);
  814. if (name == letter)
  815. name.clear();
  816. else if (name.size() > 2 && name.compare (0, 2, letter + " ") == 0)
  817. name = name.substr (2);
  818. }
  819. const auto k = rack::addReturn (doc, name);
  820. auto* r = rack::rackOf (doc);
  821. if (k < 0)
  822. return;
  823. auto& ret = r->returns[(std::size_t) k];
  824. ret.active = branch.boolean ("MixerDevice/Speaker/Manual", true);
  825. ret.solo = branch.boolean ("IsSoloed", false);
  826. ret.volume = (float) std::clamp (branch.number ("MixerDevice/Volume/Manual", 1.0), 0.0, 2.0);
  827. ret.pan = (float) std::clamp (branch.number ("MixerDevice/Panorama/Manual", 0.0), -1.0, 1.0);
  828. const auto slot = (int) r->chains.size() + k;
  829. for (const auto& d : branch.path ("DeviceChain/AudioToAudioDeviceChain/Devices").children())
  830. rackDeviceFrom (ctx, d, doc, slot, false, depth, nullptr, nullptr);
  831. if (mappingOf (branch.path ("MixerDevice/Volume")) || mappingOf (branch.path ("MixerDevice/Panorama")))
  832. ctx.note (&FlpImportReport::approximated, "Drum rack: a macro on a return chain's volume or pan (not applied)");
  833. }
  834. }
  835. // Fills a new rack document from a Live rack device (the document comes from rack::makeRack: its first chain is replaced;
  836. // from rack::makeDrumRack for a Drum Rack)
  837. bool rackFrom (Ctx& ctx, const Element& device, PatcherDoc& doc, int depth)
  838. {
  839. auto* r = rack::rackOf (doc);
  840. if (r == nullptr)
  841. return false;
  842. const auto instrumentRack = r->kind == RackDoc::Kind::instrument;
  843. std::array<std::vector<std::string>, rackMacroCount> droppedTargets;
  844. auto skipMidi = std::exchange (ctx.skipLeadingMidi, 0); // (round 190cf) only for the rack this call reads
  845. // a Drum Rack (round 190ec): its pads' Simplers play their Play note, so a Slice-mode Simpler on a pad must not move
  846. // the track's notes (the key shift is the track channel's own)
  847. const auto drum = r->drum;
  848. const auto keyShiftBefore = ctx.pendingKeyShift;
  849. std::vector<std::vector<std::pair<int, RackSend>>> drumSends; // [chain] (return index, send)
  850. std::vector<int> drumAudioTo;
  851. while (! r->chains.empty())
  852. {
  853. rack::removeChain (doc, 0);
  854. r = rack::rackOf (doc);
  855. }
  856. for (const auto& branch : device.path ("Branches").children())
  857. {
  858. auto name = branch.value ("Name/UserName");
  859. if (name.empty())
  860. name = branch.value ("Name/EffectiveName");
  861. const auto c = rack::addChain (doc, name.empty() ? "Chain" : name);
  862. r = rack::rackOf (doc);
  863. auto& chain = r->chains[(std::size_t) c];
  864. chain.active = branch.boolean ("MixerDevice/Speaker/Manual", true);
  865. chain.solo = branch.boolean ("IsSoloed", false);
  866. chain.volume = (float) std::clamp (branch.number ("MixerDevice/Volume/Manual", 1.0), 0.0, 2.0);
  867. chain.pan = (float) std::clamp (branch.number ("MixerDevice/Panorama/Manual", 0.0), -1.0, 1.0);
  868. chain.select = zoneOf (branch.child ("BranchSelectorRange"), RackZone { 0, 0, 0, 0 });
  869. chain.key = zoneOf (branch.path ("ZoneSettings/KeyRange"), RackZone {});
  870. chain.velocity = zoneOf (branch.path ("ZoneSettings/VelocityRange"), RackZone { 1, 127, 1, 127 });
  871. if (drum)
  872. drumPadFrom (branch, chain, drumSends, drumAudioTo);
  873. // the chain's devices (Live's chain kinds: AudioToAudio, MidiToAudio, MidiToMidi) [DATA]
  874. for (const auto* list : { "DeviceChain/AudioToAudioDeviceChain/Devices", "DeviceChain/MidiToAudioDeviceChain/Devices" })
  875. for (const auto& d : branch.path (list).children())
  876. {
  877. // (round 190cf) the leading MIDI effects the track's channel already took (a one-chain Instrument Rack)
  878. if (skipMidi > 0 && isMidiEffect (d.name()))
  879. {
  880. --skipMidi;
  881. continue;
  882. }
  883. skipMidi = 0;
  884. bool native = false;
  885. std::set<std::string> mappedLinks;
  886. if (rackDeviceFrom (ctx, d, doc, c, instrumentRack, depth, &native, &mappedLinks) >= 0 && ! native)
  887. continue;
  888. // a dropped device's mapped parameters (for the macro names); on a Live device that became a LYNX effect
  889. // the macros drive the parameters that have a counterpart (round 190cf), the others are listed
  890. bool unmapped = false;
  891. for (const auto& parameter : d.children())
  892. if (const auto m = mappingOf (parameter); m && mappedLinks.count (std::string (parameter.name())) == 0)
  893. {
  894. droppedTargets[(std::size_t) m->macro].push_back (spacedName (parameter.name()));
  895. unmapped = true;
  896. }
  897. if (native && unmapped)
  898. ctx.note (&FlpImportReport::partialEffects, "Macro mapping onto a setting of a converted Live device that has no LYNX control (not applied)");
  899. }
  900. // macros on the chain's volume / pan (Live's linear gain and −1..1 → LYNX's 0..1 controls)
  901. if (const auto m = mappingOf (branch.path ("MixerDevice/Volume")))
  902. {
  903. RackMapping target;
  904. target.target = RackMapping::Target::chainVolume;
  905. target.chain = c;
  906. mapInto (doc, *m, target, rack::volumeValue ((float) m->min), rack::volumeValue ((float) m->max));
  907. }
  908. if (const auto m = mappingOf (branch.path ("MixerDevice/Panorama")))
  909. {
  910. RackMapping target;
  911. target.target = RackMapping::Target::chainPan;
  912. target.chain = c;
  913. mapInto (doc, *m, target, (float) ((m->min + 1.0) * 0.5), (float) ((m->max + 1.0) * 0.5));
  914. }
  915. r = rack::rackOf (doc);
  916. }
  917. if (drum) // the return chains, then the chains' sends and Audio To (round 190ec)
  918. {
  919. drumReturnsFrom (ctx, device, doc, depth);
  920. r = rack::rackOf (doc);
  921. for (int c = 0; c < (int) r->chains.size() && c < (int) drumSends.size(); ++c)
  922. {
  923. auto& chain = r->chains[(std::size_t) c];
  924. chain.sends.assign (r->returns.size(), RackSend {});
  925. for (const auto& [k, send] : drumSends[(std::size_t) c])
  926. if (k >= 0 && k < (int) r->returns.size())
  927. chain.sends[(std::size_t) k] = send;
  928. const auto to = drumAudioTo[(std::size_t) c];
  929. chain.audioTo = to >= 0 && to < (int) r->returns.size() ? to : -1;
  930. }
  931. ctx.pendingKeyShift = keyShiftBefore;
  932. r->showPads = device.boolean ("ArePadsVisible", true);
  933. r->showIO = device.boolean ("IsMidiSectionVisible", false);
  934. r->showSends = device.boolean ("AreSendsVisible", false);
  935. r->showReturns = device.boolean ("IsReturnBranchesListVisible", false);
  936. r->padScroll = std::clamp ((int) device.number ("PadScrollPosition", rack::drumDefaultScroll), 0, rack::drumPadRows - 4);
  937. }
  938. else if (r->chains.empty())
  939. rack::addChain (doc);
  940. r = rack::rackOf (doc);
  941. for (int k = 0; k < rackMacroCount; ++k)
  942. {
  943. const auto n = std::to_string (k);
  944. auto& m = r->macros[(std::size_t) k];
  945. m.value = (float) std::clamp (device.number ("MacroControls." + n + "/Manual", 0.0), 0.0, 127.0);
  946. const auto shown = device.value ("MacroDisplayNames." + n);
  947. if (shown != "Macro " + std::to_string (k + 1))
  948. m.name = shown;
  949. const auto def = device.number ("MacroDefaults." + n, -1.0);
  950. m.defaultValue = def < 0.0 ? -1.0f : (float) std::min (def, 127.0);
  951. m.excludeFromRandom = device.boolean ("ExcludeMacroFromRandomization." + n, false);
  952. m.excludeFromVariations = device.boolean ("ExcludeMacroFromSnapshots." + n, false);
  953. }
  954. // Live names a macro that wasn't renamed after its one mapped parameter ("Macro 3" stored, "Formant Shift" shown
  955. // [SHOT]); when LYNX drops that device, the macro keeps the name Live showed
  956. for (int k = 0; k < rackMacroCount; ++k)
  957. if (auto& m = r->macros[(std::size_t) k]; m.name.empty() && m.mappings.empty() && droppedTargets[(std::size_t) k].size() == 1)
  958. m.name = droppedTargets[(std::size_t) k].front();
  959. r->shownMacros = std::clamp ((int) device.number ("NumVisibleMacroControls", 8), 1, rackMacroCount);
  960. // (round 190ed) the macros an envelope moves (0…127 → the slot's parameter k, 0..1)
  961. if (ctx.rackAutos != nullptr)
  962. for (int k = 0; k < rackMacroCount; ++k)
  963. if (const auto id = targetId (device.child ("MacroControls." + std::to_string (k))); ! id.empty() && ctx.automated.count (id) != 0)
  964. ctx.rackAutos->push_back ({ id, {}, -1, k, [] (double v) { return (float) std::clamp (v / 127.0, 0.0, 1.0); },
  965. r->macros[(std::size_t) k].value / 127.0f, rack::macroName (*r, k) });
  966. r->selector = (float) std::clamp (device.number ("ChainSelector/Manual", 0.0), 0.0, 127.0);
  967. r->selectorFiltersCtrl = device.boolean ("ChainSelectorFilterMidiCtrl", false);
  968. r->autoSelect = device.boolean ("IsAutoSelectEnabled", false);
  969. r->showMacros = device.boolean ("AreMacroControlsVisible", true);
  970. r->showChains = device.boolean ("IsBranchesListVisible", false);
  971. r->showDevices = device.boolean ("AreDevicesVisible", false);
  972. // the zone editor: Live keeps only whether it shows [DATA]; an Audio Effect Rack has only the Chain editor, the
  973. // others open on Key
  974. if (device.boolean ("IsRangesEditorVisible", false))
  975. r->zoneEditor = r->kind == RackDoc::Kind::audioEffect ? 2 : 0;
  976. r->showVariations = device.boolean ("AreMacroVariationsControlsVisible", false);
  977. for (const auto& snapshot : device.path ("MacroVariations/MacroSnapshots").children ("MacroSnapshot"))
  978. {
  979. RackVariation v;
  980. v.name = snapshot.value ("SnapshotName");
  981. for (int k = 0; k < rackMacroCount; ++k)
  982. {
  983. const auto n = std::to_string (k);
  984. v.has[(std::size_t) k] = snapshot.boolean ("MacroHasValue." + n, false);
  985. v.values[(std::size_t) k] = v.has[(std::size_t) k] ? (float) std::clamp (snapshot.number ("MacroValues." + n, 0.0), 0.0, 127.0) : -1.0f;
  986. }
  987. r->variations.push_back (std::move (v));
  988. }
  989. // the chain selector on a macro (0…127 → 0..1)
  990. if (const auto m = mappingOf (device.child ("ChainSelector")))
  991. {
  992. RackMapping target;
  993. target.target = RackMapping::Target::selector;
  994. mapInto (doc, *m, target, (float) (m->min / 127.0), (float) (m->max / 127.0));
  995. }
  996. // a mapped parameter follows its macro (Live drives it from the macro; its own stored value may be an old one [DATA:
  997. // a chain volume stored at 0 dB under a macro that puts it at −9.6 dB])
  998. for (int k = 0; k < rackMacroCount; ++k)
  999. if (! rack::rackOf (doc)->macros[(std::size_t) k].mappings.empty())
  1000. rack::setMacro (doc, k, rack::rackOf (doc)->macros[(std::size_t) k].value);
  1001. rack::rackOf (doc)->name = device.value ("UserName");
  1002. rack::compile (doc);
  1003. ctx.note (&FlpImportReport::converted, drum ? "Drum rack" : instrumentRack ? "Instrument rack" : "Audio effect rack");
  1004. return true;
  1005. }
  1006. // Fills `channel` from a MIDI track's instrument device. Returns false for none.
  1007. bool instrumentFrom (Ctx& ctx, const Element& device, ChannelDef& channel, std::vector<DrumPad>* pads, int depth)
  1008. {
  1009. const auto tag = std::string (device.name());
  1010. if (tag == "PluginDevice")
  1011. {
  1012. if (const auto p = pluginOf (device))
  1013. {
  1014. channel.instrument = InstrumentKind::plugin;
  1015. channel.plugin.name = p->name;
  1016. channel.plugin.foreign = *p;
  1017. ctx.note (&FlpImportReport::converted, "Plugin: " + p->name);
  1018. // (round 190ed) envelopes on the plugin's parameters (the track's own instrument only)
  1019. if (depth == 0 && ! ctx.inDrumPad)
  1020. {
  1021. std::vector<std::int32_t> slots;
  1022. pluginAutos (
  1023. ctx, device, p->name,
  1024. [&ctx] (const std::string& id, int param, float, const std::string& name, std::function<float (double)> law) {
  1025. ctx.channelTargets.push_back ({ id, Target { AutomationTarget { AutomationTargetKind::channelParam, -1, 0, param }, ValueMap::plain, name, std::move (law) } });
  1026. },
  1027. &slots);
  1028. appendVst3Slots (channel.plugin.foreign, slots); // (round 190ek)
  1029. }
  1030. return true;
  1031. }
  1032. return false;
  1033. }
  1034. if (tag == "OriginalSimpler" || tag == "MultiSampler")
  1035. {
  1036. auto zones = zonesOf (ctx, device, channel.name);
  1037. if (zones.empty())
  1038. {
  1039. ctx.note (&FlpImportReport::unsupported, deviceName (device) + " (sample missing)");
  1040. return false;
  1041. }
  1042. channel.instrument = InstrumentKind::sampler;
  1043. // (round 190bq) a Simpler loops by its own Loop switch in Classic mode (SustainLoop is the Sampler's); a looped
  1044. // sample stays a zone, which holds the loop points
  1045. const auto simpler = tag == "OriginalSimpler" && (bool) device.path ("Globals/PlaybackMode");
  1046. const auto simplerLoop = simpler && (int) device.number ("Globals/PlaybackMode", 0) == 0
  1047. && device.boolean ("Player/LoopModulators/LoopOn/Manual", false);
  1048. if (simpler)
  1049. for (auto& zone : zones)
  1050. zone.loopMode = 0;
  1051. const auto firstPath = zones.front().path;
  1052. const auto& z = zones.front();
  1053. if (! simplerLoop && zones.size() == 1 && z.lowKey == 0 && z.highKey == 127 && z.lowVelocity <= 1 && z.highVelocity == 127 && std::abs (60 - z.rootKey) <= 24)
  1054. {
  1055. channel.samplePath = z.path;
  1056. channel.sampler.pitch = (float) (60 - z.rootKey) + z.tune;
  1057. channel.sampler.gainDb = z.gain > 0.0f ? 20.0f * std::log10 (z.gain) : -24.0f;
  1058. }
  1059. else
  1060. {
  1061. channel.samplePath = z.path;
  1062. channel.zones = std::move (zones);
  1063. }
  1064. applySimplerEnvelope (device, channel.sampler);
  1065. // one-shot (Player/PlaybackMode 1 [DATA name]): the whole sample plays (release 0 = one-shot in LYNX)
  1066. if ((int) device.number ("Globals/PlaybackMode", 0) == 1)
  1067. channel.sampler.release = 0.0f;
  1068. // (round 190bq) the rest of a Simpler: transpose, volume, pan, filter, envelopes, LFO, voices, glide, one-shot
  1069. // fades, slices, region, loop, warp (core/AlsDevices.h); what LYNX's Sampler lacks goes to the report
  1070. if (simpler)
  1071. {
  1072. alsdev::Notes notes;
  1073. const auto seconds = ctx.options.common.sampleSeconds ? ctx.options.common.sampleSeconds (firstPath) : 0.0;
  1074. const auto r = alsdev::applySimpler (device, channel, ctx.song.bpm, seconds, notes);
  1075. if (r.loop && ! channel.zones.empty())
  1076. for (auto& zone : channel.zones)
  1077. {
  1078. zone.loopStart = r.loopStart;
  1079. zone.loopEnd = r.loopEnd;
  1080. zone.loopMode = 1;
  1081. }
  1082. if (ctx.inDrumPad)
  1083. ctx.note (&FlpImportReport::approximated, "Drum rack pad: Simpler settings other than sample, tuning, level and pan (not applied)");
  1084. else
  1085. {
  1086. ctx.pendingKeyShift = r.keyShift;
  1087. // (round 190ed) envelopes on the filter's frequency (Hz, the same law) and resonance (as the import
  1088. // reads it) move the Sampler's Cutoff / Resonance knobs
  1089. const auto filter = device.path ("Filter/Slot/Value/SimplerFilter");
  1090. if (depth == 0 && device.boolean ("Filter/IsOn/Manual", false) && filter)
  1091. {
  1092. if (const auto id = targetId (filter.child ("Freq")); ! id.empty() && ctx.automated.count (id) != 0)
  1093. ctx.channelTargets.push_back ({ id, Target { AutomationTarget { AutomationTargetKind::channelParam, -1, 0, samplerparam::cutoff }, ValueMap::plain,
  1094. "Simpler Filter Freq", [] (double hz) { return samplerparam::toValue (samplerparam::cutoff, (float) std::clamp (hz, 20.0, 20000.0)); } } });
  1095. if (const auto id = targetId (filter.child ("Res")); ! id.empty() && ctx.automated.count (id) != 0)
  1096. ctx.channelTargets.push_back ({ id, Target { AutomationTarget { AutomationTargetKind::channelParam, -1, 0, samplerparam::resonance }, ValueMap::plain,
  1097. "Simpler Filter Res", [] (double r) { return samplerparam::toValue (samplerparam::resonance, (float) std::clamp (r, 0.0, 1.0)); } } });
  1098. }
  1099. for (const auto& n : notes.approximated)
  1100. ctx.note (&FlpImportReport::approximated, "Simpler: " + n);
  1101. for (const auto& n : notes.dropped)
  1102. ctx.note (&FlpImportReport::approximated, "Simpler: " + n + " (not applied)");
  1103. }
  1104. }
  1105. ctx.note (&FlpImportReport::converted, tag == "OriginalSimpler" ? "Simpler" : "Sampler");
  1106. return true;
  1107. }
  1108. if (tag == "DrumGroupDevice" && depth < 8 && ! ctx.options.drumPadsAsChannels) // (round 190ec: a LYNX Drum Rack)
  1109. {
  1110. auto doc = rack::makeDrumRack();
  1111. if (rackFrom (ctx, device, doc, depth))
  1112. {
  1113. channel.instrument = InstrumentKind::patcher;
  1114. channel.patcher = std::move (doc);
  1115. return true;
  1116. }
  1117. return false;
  1118. }
  1119. if (tag == "DrumGroupDevice" && pads != nullptr)
  1120. {
  1121. for (const auto& branch : device.path ("Branches").children ("DrumBranch"))
  1122. {
  1123. DrumPad pad;
  1124. pad.name = branch.value ("Name/UserName");
  1125. if (pad.name.empty())
  1126. pad.name = branch.value ("Name/EffectiveName");
  1127. // BranchInfo/ReceivingNote = 128 − the pad's MIDI key [DATA: 92 ↔ C1 (36) in the drum lesson set]
  1128. pad.key = 128 - (int) branch.number ("BranchInfo/ReceivingNote", 92);
  1129. pad.cutGroup = (int) branch.number ("BranchInfo/ChokeGroup", 0);
  1130. pad.cutBy = pad.cutGroup;
  1131. for (const auto& inner : branch.path ("DeviceChain/MidiToAudioDeviceChain/Devices").children())
  1132. {
  1133. ChannelDef sub;
  1134. sub.name = pad.name;
  1135. const auto wasPad = ctx.inDrumPad;
  1136. ctx.inDrumPad = true;
  1137. const auto made = instrumentFrom (ctx, inner, sub, nullptr, depth + 1);
  1138. ctx.inDrumPad = wasPad;
  1139. if (made && sub.instrument == InstrumentKind::sampler)
  1140. {
  1141. // (round 190bq) the pad's Simpler volume and pan ride on the pad's layers and pan
  1142. const auto level = std::pow (10.0f, sub.sampler.gainDb / 20.0f);
  1143. if (sub.zones.empty())
  1144. {
  1145. SampleZone z;
  1146. z.path = sub.samplePath;
  1147. z.tune = sub.sampler.pitch; // (played at its own pitch on the pad's key)
  1148. z.gain = level;
  1149. pad.layers.push_back (z);
  1150. }
  1151. else
  1152. {
  1153. pad.layers = sub.zones;
  1154. for (auto& layer : pad.layers)
  1155. {
  1156. layer.gain *= level;
  1157. layer.tune += sub.sampler.pitch;
  1158. }
  1159. }
  1160. pad.pan = sub.pan;
  1161. break;
  1162. }
  1163. }
  1164. pad.gain = (float) branch.number ("MixerDevice/Volume/Manual", 1);
  1165. pad.pan = (float) std::clamp ((double) pad.pan + branch.number ("MixerDevice/Panorama/Manual", 0), -1.0, 1.0);
  1166. if (! pad.layers.empty())
  1167. pads->push_back (std::move (pad));
  1168. }
  1169. if (pads->empty())
  1170. return false;
  1171. channel.instrument = InstrumentKind::sampler;
  1172. channel.samplePath = pads->front().layers.front().path;
  1173. ctx.note (&FlpImportReport::converted, "Drum rack");
  1174. return true;
  1175. }
  1176. if (tag == "InstrumentGroupDevice" && depth < 8) // (round 183c: a LYNX Instrument Rack)
  1177. {
  1178. auto doc = rack::makeRack (RackDoc::Kind::instrument);
  1179. // (round 190ed) the envelopes inside the rack and on its macros (the track's own instrument only): the channel's
  1180. // macro parameters
  1181. std::vector<RackAuto> autos;
  1182. auto* const saved = std::exchange (ctx.rackAutos, depth == 0 && ! ctx.inDrumPad ? &autos : nullptr);
  1183. const auto read = rackFrom (ctx, device, doc, depth);
  1184. ctx.rackAutos = saved;
  1185. if (read)
  1186. {
  1187. channel.instrument = InstrumentKind::patcher;
  1188. channel.patcher = std::move (doc);
  1189. placeRackAutos (ctx, channel.patcher, autos, [] (int k) { return AutomationTarget { AutomationTargetKind::channelParam, -1, 0, k }; }, true);
  1190. return true;
  1191. }
  1192. return false;
  1193. }
  1194. if (tag == "DrumGroupDevice" && depth < 8)
  1195. {
  1196. // a Drum Rack without pads (nested): its first chain's instrument
  1197. for (const auto& branch : device.path ("Branches").children())
  1198. for (const auto& inner : branch.path ("DeviceChain/MidiToAudioDeviceChain/Devices").children())
  1199. if (isInstrumentDevice (inner.name()) || inner.name() == "PluginDevice")
  1200. if (instrumentFrom (ctx, inner, channel, nullptr, depth + 1))
  1201. {
  1202. ctx.note (&FlpImportReport::approximated, "Instrument rack (first chain)");
  1203. return true;
  1204. }
  1205. return false;
  1206. }
  1207. // (round 190ed) Operator without FM in use and Drift: the built-in synth with their oscillators, filter and amp
  1208. // envelope (core/AlsDevices.h); the report lists the pair as fitted and what has no place
  1209. if (tag == "Operator" || tag == "Drift")
  1210. {
  1211. alsdev::Notes notes;
  1212. ChannelDef synth = channel;
  1213. if (tag == "Operator" ? alsdev::operatorToSynth (device, synth, ctx.song.bpm, notes) : alsdev::driftToSynth (device, synth, ctx.song.bpm, notes))
  1214. {
  1215. channel = std::move (synth);
  1216. ctx.note (&FlpImportReport::partialEffects, tag + " -> built-in synth (settings fitted to LYNX's engine)");
  1217. for (const auto& n : notes.approximated)
  1218. ctx.note (&FlpImportReport::partialEffects, tag + ": " + n);
  1219. for (const auto& n : notes.dropped)
  1220. ctx.note (&FlpImportReport::partialEffects, tag + ": " + n + " (not applied)");
  1221. return true;
  1222. }
  1223. if (tag == "Operator")
  1224. {
  1225. // FM (or a waveform whose order is not settled): no LYNX engine holds it yet
  1226. ctx.note (&FlpImportReport::unsupported, deviceName (device) + " (FM synthesis: no LYNX engine for it yet)");
  1227. return false;
  1228. }
  1229. }
  1230. // Live's synths: no LYNX equivalent; the channel keeps a built-in synth, as for an unknown FL generator
  1231. ctx.note (&FlpImportReport::unsupported, deviceName (device));
  1232. return false;
  1233. }
  1234. // One of Live's MIDI effects in front of a track's instrument (round 190cf, core/AlsDevices.h): the Arpeggiator becomes
  1235. // the channel's arpeggiator; Pitch, Velocity, Chord and Note Length are written into the notes of the track's clips
  1236. // (LYNX has no live note processor inside a channel for them), in the chain's order. False = no counterpart, or a
  1237. // setting that cannot be kept: the caller lists the device as unsupported, as before.
  1238. bool midiEffectFrom (Ctx& ctx, const Element& d, ChannelDef& channel, std::vector<alsdev::NoteEffect>& effects)
  1239. {
  1240. const auto tag = d.name();
  1241. if (tag != "MidiArpeggiator" && tag != "MidiPitcher" && tag != "MidiVelocity" && tag != "MidiChord" && tag != "MidiNoteLength")
  1242. return false;
  1243. alsdev::Context context;
  1244. context.bpm = ctx.song.bpm;
  1245. alsdev::Notes notes;
  1246. std::string name;
  1247. if (tag == "MidiArpeggiator")
  1248. {
  1249. ArpSettings arp;
  1250. if (channel.arp.enabled() || ! alsdev::arpeggiatorToArp (d, context, arp, notes))
  1251. return false;
  1252. name = "Arpeggiator";
  1253. if (! d.boolean ("On/Manual", true))
  1254. {
  1255. ctx.note (&FlpImportReport::approximated, name + " (switched off in the set: left out)");
  1256. return true;
  1257. }
  1258. channel.arp = arp;
  1259. ctx.note (&FlpImportReport::converted, "Arpeggiator -> channel arpeggiator");
  1260. }
  1261. else
  1262. {
  1263. const auto e = alsdev::noteEffectFromLiveDevice (d, context, notes);
  1264. // behind an arpeggiator only what gives the same notes either way round can be written into the clips
  1265. if (! e || (channel.arp.enabled() && (e->kind == alsdev::NoteEffect::Kind::chord || e->kind == alsdev::NoteEffect::Kind::length)))
  1266. return false;
  1267. name = e->name;
  1268. if (! d.boolean ("On/Manual", true))
  1269. {
  1270. ctx.note (&FlpImportReport::approximated, name + " (switched off in the set: left out)");
  1271. return true;
  1272. }
  1273. effects.push_back (*e);
  1274. ctx.note (&FlpImportReport::approximated, name + " (MIDI effect): written into the notes of the track's clips; notes played live are not changed");
  1275. }
  1276. for (const auto& n : notes.approximated)
  1277. ctx.note (&FlpImportReport::approximated, name + ": " + n);
  1278. for (const auto& n : notes.dropped)
  1279. ctx.note (&FlpImportReport::approximated, name + ": " + n + " (not applied)");
  1280. return true;
  1281. }
  1282. // (round 190ed) The Peak Controller of a translated effect's modulation (core/AlsDevices.h Translated::Modulator): in
  1283. // front of the effect on its insert, or (a side-chain envelope follower) at the end of the source track's insert once
  1284. // every track is read; the link is made then (finishLinks)
  1285. void placeModulator (Ctx& ctx, const Element& d, MixerTrack& insert, int track, alsdev::Translated::Modulator& mod, std::vector<alsdev::ParamLink>& links,
  1286. const std::string& from)
  1287. {
  1288. // the parameter the link moves keeps no envelope of its own (the link would fight it)
  1289. for (auto it = links.begin(); it != links.end(); ++it)
  1290. if (it->param == mod.param)
  1291. {
  1292. if (const auto id = targetId (d.path (it->live)); ! id.empty() && ctx.automated.count (id) != 0)
  1293. {
  1294. ctx.note (&FlpImportReport::partialEffects, from + ": automation of the cutoff under its " + mod.what + " (the link moves the cutoff; not carried)");
  1295. ctx.explained.insert (id);
  1296. }
  1297. links.erase (it);
  1298. break;
  1299. }
  1300. Ctx::PendingLink link;
  1301. link.controller = std::move (mod.controller);
  1302. link.targetTrack = track;
  1303. link.param = mod.param;
  1304. link.curve = std::move (mod.curve);
  1305. link.notes = std::move (mod.notes);
  1306. link.from = from;
  1307. link.what = mod.what;
  1308. if (mod.sideTrackId >= 0)
  1309. if (const auto it = ctx.insertOfTrack.find (mod.sideTrackId); it != ctx.insertOfTrack.end())
  1310. {
  1311. link.sourceInsert = it->second;
  1312. link.notes.push_back ("envelope follower on the side-chain source: its Peak Controller sits at the end of that track's insert");
  1313. ctx.pendingLinks.push_back (std::move (link));
  1314. return;
  1315. }
  1316. if (mod.sideTrackId >= 0 || mod.sideOther)
  1317. link.notes.push_back ("side-chain input of the envelope follower (its source is not a track of the set; the follower hears the effect's input)");
  1318. if (insert.effects.size() + 2 > (std::size_t) maxEffectSlots)
  1319. {
  1320. ctx.note (&FlpImportReport::partialEffects, from + ": " + mod.what + " on the cutoff (no free effect slot for its Peak Controller) (not applied)");
  1321. return;
  1322. }
  1323. insert.effects.push_back (std::move (link.controller));
  1324. link.sourceInsert = track;
  1325. link.sourceSlot = (int) insert.effects.size() - 1;
  1326. ctx.pendingLinks.push_back (std::move (link));
  1327. }
  1328. // (round 190ed) Every track is read: the side-chain controllers go to the end of their source inserts and each link is made
  1329. void finishLinks (Ctx& ctx)
  1330. {
  1331. auto& song = ctx.song;
  1332. for (auto& link : ctx.pendingLinks)
  1333. {
  1334. if (link.targetSlot < 0 || link.sourceInsert < 0 || link.sourceInsert >= (int) song.mixer.size())
  1335. continue;
  1336. if (link.sourceSlot < 0)
  1337. {
  1338. auto& source = song.mixer[(std::size_t) link.sourceInsert];
  1339. if (source.effects.size() >= (std::size_t) maxEffectSlots)
  1340. {
  1341. ctx.note (&FlpImportReport::partialEffects, link.from + ": " + link.what + " on the cutoff (no free effect slot on the side-chain source) (not applied)");
  1342. continue;
  1343. }
  1344. source.effects.push_back (std::move (link.controller));
  1345. link.sourceSlot = (int) source.effects.size() - 1;
  1346. }
  1347. Automation a;
  1348. a.name = song.mixer[(std::size_t) link.targetTrack].name + " " + link.from + " cutoff (" + link.what + ")";
  1349. a.target = { AutomationTargetKind::effectParam, link.targetTrack, link.targetSlot, link.param };
  1350. a.source.track = link.sourceInsert;
  1351. a.source.slot = link.sourceSlot;
  1352. a.source.output = 0; // peak + LFO
  1353. a.curve = link.curve;
  1354. song.automations.push_back (std::move (a));
  1355. ctx.note (&FlpImportReport::partialEffects, link.from + " " + link.what + " -> Peak Controller linked to the Filter's cutoff");
  1356. for (const auto& n : link.notes)
  1357. ctx.note (&FlpImportReport::partialEffects, link.from + ": " + n);
  1358. }
  1359. ctx.pendingLinks.clear();
  1360. }
  1361. // Audio effects of a track (after its instrument): plugins carried over, the rest listed
  1362. void effectsFrom (Ctx& ctx, const std::vector<Element>& devices, MixerTrack& insert)
  1363. {
  1364. for (const auto& d : devices)
  1365. {
  1366. const auto tag = d.name();
  1367. if (tag == "PluginDevice")
  1368. {
  1369. if (const auto p = pluginOf (d); p && insert.effects.size() < (std::size_t) maxEffectSlots)
  1370. {
  1371. EffectSlot slot;
  1372. slot.kind = EffectKind::plugin;
  1373. slot.enabled = d.boolean ("On/Manual", true);
  1374. slot.plugin.name = p->name;
  1375. slot.plugin.foreign = *p;
  1376. insert.effects.push_back (std::move (slot));
  1377. ctx.note (&FlpImportReport::converted, "Plugin: " + p->name);
  1378. // (round 190ed) envelopes on the plugin's parameters
  1379. const auto track = (int) (&insert - ctx.song.mixer.data()), at = (int) insert.effects.size() - 1;
  1380. std::vector<std::int32_t> slots;
  1381. pluginAutos (
  1382. ctx, d, p->name,
  1383. [&ctx, track, at] (const std::string& id, int param, float, const std::string& name, std::function<float (double)> law) {
  1384. ctx.targets[id] = { AutomationTarget { AutomationTargetKind::effectParam, track, at, param }, ValueMap::plain, name, std::move (law) };
  1385. },
  1386. &slots);
  1387. appendVst3Slots (insert.effects.back().plugin.foreign, slots); // (round 190ek)
  1388. }
  1389. continue;
  1390. }
  1391. if (tag == "AudioEffectGroupDevice" && insert.effects.size() < (std::size_t) maxEffectSlots) // (round 183c)
  1392. {
  1393. auto slot = rack::makeRackSlot (RackDoc::Kind::audioEffect);
  1394. slot.enabled = d.boolean ("On/Manual", true);
  1395. // (round 190ed) the envelopes inside the rack and on its macros: the slot's macro parameters
  1396. std::vector<RackAuto> autos;
  1397. auto* const saved = std::exchange (ctx.rackAutos, &autos);
  1398. const auto read = rackFrom (ctx, d, slot.patcher, 0);
  1399. ctx.rackAutos = saved;
  1400. if (read)
  1401. {
  1402. insert.effects.push_back (std::move (slot));
  1403. const auto track = (int) (&insert - ctx.song.mixer.data()), at = (int) insert.effects.size() - 1;
  1404. placeRackAutos (ctx, insert.effects.back().patcher, autos, [track, at] (int k) {
  1405. return AutomationTarget { AutomationTargetKind::effectParam, track, at, k };
  1406. });
  1407. }
  1408. continue;
  1409. }
  1410. if (isMidiEffect (tag))
  1411. {
  1412. ctx.note (&FlpImportReport::unsupported, deviceName (d));
  1413. continue;
  1414. }
  1415. // (round 190bq) Live's own effects LYNX has an engine for: the LYNX effect, settings translated
  1416. std::vector<alsdev::ParamLink> links;
  1417. std::string from;
  1418. std::optional<alsdev::Translated::Modulator> modulator;
  1419. if (EffectSlot slot; insert.effects.size() < (std::size_t) maxEffectSlots && nativeEffectFrom (ctx, d, slot, &links, &from, &modulator))
  1420. {
  1421. const auto track = (int) (&insert - ctx.song.mixer.data());
  1422. // (round 190ed) the modulation's Peak Controller: in front of the effect, or at the end of the side-chain
  1423. // source's insert once every track is read; the link drives the parameter the modulation moves, so that
  1424. // parameter's own envelope is not carried as well
  1425. if (modulator)
  1426. placeModulator (ctx, d, insert, track, *modulator, links, from);
  1427. insert.effects.push_back (std::move (slot));
  1428. if (modulator && ! ctx.pendingLinks.empty() && ctx.pendingLinks.back().targetSlot == -1)
  1429. ctx.pendingLinks.back().targetSlot = (int) insert.effects.size() - 1;
  1430. // (round 190cf) automation of the device's parameters follows onto the LYNX effect's, by the same laws
  1431. for (auto& l : links)
  1432. if (const auto id = targetId (d.path (l.live)); ! id.empty())
  1433. ctx.targets[id] = { AutomationTarget { AutomationTargetKind::effectParam, track, (int) insert.effects.size() - 1, l.param },
  1434. ValueMap::plain, from + " " + spacedName (pathFileName (l.live)), std::move (l.value) };
  1435. continue;
  1436. }
  1437. // (round 190cf) a device LYNX could hold, on an insert whose slots are all taken, is named with that reason
  1438. if (insert.effects.size() >= (std::size_t) maxEffectSlots && alsdev::effectFromLiveDevice (d).has_value())
  1439. ctx.note (&FlpImportReport::droppedEffects, deviceName (d) + " (no free effect slot: an insert holds " + std::to_string (maxEffectSlots) + ")");
  1440. else
  1441. ctx.note (&FlpImportReport::droppedEffects, deviceName (d));
  1442. }
  1443. }
  1444. // ---------------------------------------------------------------------------------------------------------------
  1445. // Clips
  1446. struct ClipLoop
  1447. {
  1448. double start = 0, end = 0; // clip-content span played first [start, end)
  1449. double loopStart = 0, loopEnd = 0; // with `on`
  1450. bool on = false;
  1451. };
  1452. ClipLoop loopOf (const Element& clip)
  1453. {
  1454. const auto l = clip.child ("Loop");
  1455. ClipLoop c;
  1456. c.loopStart = l.number ("LoopStart", 0);
  1457. c.loopEnd = l.number ("LoopEnd", 0);
  1458. c.on = l.boolean ("LoopOn", false) && c.loopEnd > c.loopStart;
  1459. c.start = c.loopStart + l.number ("StartRelative", 0);
  1460. c.end = c.on ? c.loopEnd : l.number ("OutMarker", c.loopEnd);
  1461. if (c.end <= c.start)
  1462. c.end = c.start + std::max (0.0, c.loopEnd - c.loopStart);
  1463. return c;
  1464. }
  1465. // The content ranges a clip of `length` beats plays, as (clip time, content start, content end) passes [DATA: Loop]
  1466. struct Pass
  1467. {
  1468. double at, from, to;
  1469. };
  1470. std::vector<Pass> passesOf (const ClipLoop& loop, double length)
  1471. {
  1472. std::vector<Pass> passes;
  1473. if (length <= 0)
  1474. return passes;
  1475. double at = 0;
  1476. auto from = loop.start, to = loop.end;
  1477. for (int guard = 0; at < length - 1e-9 && guard < 4096; ++guard)
  1478. {
  1479. const auto take = std::min (to - from, length - at);
  1480. if (take <= 1e-9)
  1481. break;
  1482. passes.push_back ({ at, from, from + take });
  1483. at += take;
  1484. if (! loop.on)
  1485. break;
  1486. from = loop.loopStart;
  1487. to = loop.loopEnd;
  1488. }
  1489. return passes;
  1490. }
  1491. // A set's or a clip's ScaleInformation as a project key (round 190o) [LIVE 12.4 save: Root 0…11, Name = the index into
  1492. // Live's scale chooser; Live 11: RootNote and the name as text]; nullopt when FL's list (which holds the project key)
  1493. // has no scale with the same degrees.
  1494. std::optional<projectkey::Key> liveScaleOf (const Element& owner)
  1495. {
  1496. const auto info = owner.child ("ScaleInformation");
  1497. if (! info)
  1498. return std::nullopt;
  1499. const auto name = info.value ("Name");
  1500. const auto numeric = ! name.empty() && std::all_of (name.begin(), name.end(), [] (char ch) { return ch >= '0' && ch <= '9'; });
  1501. const auto index = numeric ? std::atoi (name.c_str()) : livescales::indexOfName (name);
  1502. return livescales::keyFor ((int) info.number ("Root", info.number ("RootNote", 0)), index);
  1503. }
  1504. int patternFromMidiClip (Ctx& ctx, const Element& clip, int channel, double length, const ClipLoop* loopOverride = nullptr)
  1505. {
  1506. if (! ctx.clipKeySeen && clip.boolean ("IsInKey", false))
  1507. {
  1508. ctx.clipKeySeen = true;
  1509. ctx.clipKey = liveScaleOf (clip);
  1510. }
  1511. Pattern p;
  1512. p.name = clip.value ("Name");
  1513. p.colour = alsColour ((int) clip.number ("Color", -1));
  1514. const auto passes = passesOf (loopOverride != nullptr ? *loopOverride : loopOf (clip), length);
  1515. // Live 12's probability groups (round 187c) [LIVE 12.4 save: NoteProbabilityGroup { GroupType 0 = Play All, 1 = Play
  1516. // One; Notes/NoteId; Probability (the group's: its notes keep their own for an ungroup) }]: NoteId → group
  1517. struct ChanceGroup
  1518. {
  1519. int index = 0;
  1520. bool playOne = false;
  1521. double chance = 1.0;
  1522. };
  1523. std::map<int, ChanceGroup> groupOfNote;
  1524. int groupCount = 0;
  1525. for (const auto& g : clip.path ("Notes/NoteProbabilityGroups").children ("NoteProbabilityGroup"))
  1526. {
  1527. const ChanceGroup group { ++groupCount, g.number ("GroupType", 0) == 1, std::clamp (g.number ("Probability", 1), 0.0, 1.0) };
  1528. for (const auto& id : g.path ("Notes").children ("NoteId"))
  1529. groupOfNote[(int) numberAttr (id, "NoteId", -1)] = group;
  1530. }
  1531. for (const auto& keyTrack : clip.path ("Notes/KeyTracks").children ("KeyTrack"))
  1532. {
  1533. const auto key = (int) keyTrack.number ("MidiKey", 60);
  1534. for (const auto& n : keyTrack.path ("Notes").children ("MidiNoteEvent"))
  1535. {
  1536. const auto t = numberAttr (n, "Time"), d = numberAttr (n, "Duration", 0.25);
  1537. const auto grouped = groupOfNote.find ((int) numberAttr (n, "NoteId", -1));
  1538. for (std::size_t passIndex = 0; passIndex < passes.size(); ++passIndex)
  1539. {
  1540. const auto& pass = passes[passIndex];
  1541. if (t < pass.from - 1e-9 || t >= pass.to - 1e-9)
  1542. continue;
  1543. Note note;
  1544. note.channel = channel;
  1545. note.key = std::clamp (key, 0, 127);
  1546. note.start = ticksOf (pass.at + t - pass.from);
  1547. note.length = std::max<std::int64_t> (1, std::min (ticksOf (d), ticksOf (length) - note.start));
  1548. note.velocity = (float) std::clamp (numberAttr (n, "Velocity", 100) / 127.0, 0.0, 1.0);
  1549. note.release = (float) std::clamp (numberAttr (n, "OffVelocity", 64) / 127.0, 0.0, 1.0);
  1550. note.muted = n.hasAttr ("IsEnabled") && n.attr ("IsEnabled") == "false";
  1551. // Live's note Chance and Velocity Range (round 187c; Live 12 leaves out the defaults 1 and 0 [DATA])
  1552. note.chance = (float) std::clamp (numberAttr (n, "Probability", 1), 0.0, 1.0);
  1553. note.velocityRange = (float) std::clamp (numberAttr (n, "VelocityDeviation", 0) / 127.0, -1.0, 1.0);
  1554. if (grouped != groupOfNote.end()) // each pass of a looped clip draws its own groups
  1555. {
  1556. note.chanceGroup = (int) passIndex * groupCount + grouped->second.index;
  1557. note.chanceOne = grouped->second.playOne;
  1558. note.chance = (float) grouped->second.chance;
  1559. }
  1560. p.notes.push_back (note);
  1561. }
  1562. }
  1563. }
  1564. p.lengthTicks = ticksOf (length);
  1565. p.sortNotes();
  1566. ctx.song.patterns.push_back (std::move (p));
  1567. return (int) ctx.song.patterns.size() - 1;
  1568. }
  1569. // Live's warp mode → LYNX's warp modes (round 175a, N4): Re-Pitch (3) resamples; Beats (0), Tones (1), Texture (2)
  1570. // map to LYNX's modes of the same names, Complex (4) and Complex Pro (6) to Complex [DATA: WarpMode values]
  1571. void applyWarpMode (int mode, SamplerSettings& s)
  1572. {
  1573. s.keepPitch = mode != 3;
  1574. s.stretchMethod = mode == 0 ? StretchMethod::beats : mode == 1 ? StretchMethod::tones : mode == 2 ? StretchMethod::texture : StretchMethod::complex;
  1575. }
  1576. // `stretchBeats` > 0: the channel plays the file stretched offline to that many beats at the song tempo (the warp
  1577. // modes' own engines, core/TimeStretch); 0: the clips stretch it in real time (their `stretch`)
  1578. int audioChannelFor (Ctx& ctx, const std::string& path, int mixerTrack, int warpMode, bool warped, double stretchBeats = 0.0,
  1579. double beatsPitch = 0.0, const std::vector<WarpPoint>& warp = {})
  1580. {
  1581. auto key = path + "|" + std::to_string (mixerTrack) + "|" + std::to_string (warped ? warpMode : -1) + "|"
  1582. + std::to_string (std::llround (stretchBeats * 1.0e6)) + "|" + std::to_string (std::llround (beatsPitch * 100.0));
  1583. for (const auto& w : warp) // (clips of one file with different markers need channels of their own)
  1584. key += "|" + std::to_string (std::llround (w.seconds * 1.0e6)) + ":" + std::to_string (std::llround (w.beats * 1.0e6));
  1585. if (const auto it = ctx.audioChannels.find (key); it != ctx.audioChannels.end())
  1586. return it->second;
  1587. ChannelDef c;
  1588. c.name = fileStem (path);
  1589. c.instrument = InstrumentKind::audioClip;
  1590. c.samplePath = path;
  1591. // 0 dB: a Playlist audio clip plays at unity at FL's default channel volume (10000 / 12800; Instruments.cpp
  1592. // audioClipUnity) [measured, round 175a: 1.0 played Live's warped vocal 5.2 dB too loud]
  1593. c.volume = 10000.0f / 12800.0f;
  1594. c.mixerTrack = mixerTrack;
  1595. if (warped)
  1596. applyWarpMode (warpMode, c.sampler);
  1597. c.sampler.stretchBeats = (float) stretchBeats;
  1598. c.sampler.stretchPitch = (float) beatsPitch;
  1599. c.sampler.warp = warp;
  1600. ctx.song.channels.push_back (std::move (c));
  1601. const auto index = (int) ctx.song.channels.size() - 1;
  1602. ctx.audioChannels[key] = index;
  1603. return index;
  1604. }
  1605. // `out`: the clips go there instead of the Playlist; `loopOverride`: the content played instead of the clip's own Loop
  1606. void addAudioClip (Ctx& ctx, const Element& clip, int row, int mixerTrack, double at, double length, const std::string& user,
  1607. std::vector<Clip>* out = nullptr, const ClipLoop* loopOverride = nullptr)
  1608. {
  1609. const auto path = ctx.resolveSample (clip.child ("SampleRef"), "Audio clip: " + user);
  1610. if (path.empty() || length <= 0)
  1611. return;
  1612. const auto warped = clip.boolean ("IsWarped", true);
  1613. const auto mode = (int) clip.number ("WarpMode", 0);
  1614. const auto bpm = ctx.song.bpm;
  1615. // warp: beats of the clip's content ↔ seconds of the sample, piecewise linear [DATA: WarpMarker SecTime/BeatTime].
  1616. // `rate` is the one between the first and the last marker; a clip stretched offline keeps every segment (round 175a,
  1617. // M1: the channel's warp markers); one stretched in real time plays at `rate`.
  1618. double rate = bpm / 60.0, beatAtZero = 0.0; // beats per sample second; the content beat at sample time 0
  1619. std::vector<std::pair<double, double>> marks;
  1620. if (warped)
  1621. {
  1622. for (const auto& m : clip.path ("WarpMarkers").children ("WarpMarker"))
  1623. marks.push_back ({ numberAttr (m, "SecTime"), numberAttr (m, "BeatTime") });
  1624. std::sort (marks.begin(), marks.end());
  1625. if (marks.size() >= 2 && marks.back().first > marks.front().first + 1e-6 && marks.back().second > marks.front().second)
  1626. rate = (marks.back().second - marks.front().second) / (marks.back().first - marks.front().first);
  1627. if (! marks.empty())
  1628. beatAtZero = marks.front().second - rate * marks.front().first;
  1629. }
  1630. // more than one tempo inside the clip (Live writes one marker past the last real one, so 2 segments can still be one)
  1631. const auto bends = [&] {
  1632. double maxDev = 0;
  1633. for (const auto& [sec, beat] : marks)
  1634. maxDev = std::max (maxDev, std::abs (beatAtZero + rate * sec - beat));
  1635. return marks.size() > 2 && maxDev > 1.0 / 64.0;
  1636. }();
  1637. auto stretch = warped ? std::clamp (rate * 60.0 / bpm, 0.01, 100.0) : 1.0;
  1638. // a warped clip that keeps its pitch, whose file length the set records [DATA: SampleRef DefaultDuration /
  1639. // DefaultSampleRate]: the channel stretches the whole file offline with the clip's warp mode (round 175a, N4:
  1640. // LYNX's Beats engine only runs offline), to the file's length in content beats; the clip then plays it as is
  1641. auto fileFrames = clip.number ("SampleRef/DefaultDuration", 0), fileRate = clip.number ("SampleRef/DefaultSampleRate", 0);
  1642. // (a set without the file's length, as LYNX writes them: markers that bend the tempo still need it; the file's own)
  1643. if (bends && ! (fileFrames > 0 && fileRate > 0) && ctx.options.common.sampleSeconds)
  1644. if (const auto seconds = ctx.options.common.sampleSeconds (path); seconds > 0.0)
  1645. {
  1646. fileFrames = seconds;
  1647. fileRate = 1.0;
  1648. }
  1649. // Beats with a transpose: Live resamples each piece (higher and shorter, still on its beat), so the transposition is
  1650. // rendered offline with the stretch, keyed by the pitch, and the clip itself plays untransposed [LIVE: Beats-up5]
  1651. const auto transpose = std::clamp (clip.number ("PitchCoarse", 0) + clip.number ("PitchFine", 0) / 100.0, -48.0, 48.0);
  1652. const auto bakePitch = warped && mode == 0 && transpose != 0.0;
  1653. double fileBeats = 0.0, beatsPitch = 0.0;
  1654. std::vector<WarpPoint> warp;
  1655. if (warped && mode != 3 && fileFrames > 0 && fileRate > 0 && (std::abs (stretch - 1.0) > 1.0e-9 || bakePitch || bends))
  1656. {
  1657. stretch = 1.0;
  1658. beatsPitch = bakePitch ? transpose : 0.0;
  1659. if (bends)
  1660. {
  1661. // every segment: the file from its start to its end, in content beats, with the markers kept for the render
  1662. StretchMap beatsOf;
  1663. for (const auto& [sec, beat] : marks)
  1664. if (beatsOf.empty() || (sec > beatsOf.back().first + 1e-9 && beat > beatsOf.back().second + 1e-9))
  1665. beatsOf.push_back ({ sec, beat });
  1666. beatAtZero = stretchMapOutput (beatsOf, 0.0);
  1667. fileBeats = stretchMapOutput (beatsOf, fileFrames / fileRate) - beatAtZero;
  1668. for (const auto& [sec, beat] : beatsOf)
  1669. warp.push_back ({ sec, beat });
  1670. }
  1671. else
  1672. fileBeats = rate * fileFrames / fileRate;
  1673. }
  1674. else if (bends && ctx.report != nullptr)
  1675. ++ctx.report->partialEffects["Warp markers (one tempo per clip)"]; // stretched in real time: one rate
  1676. // content position (beats, or seconds when not warped) → LYNX playback ticks from the sample's start
  1677. const auto contentTicks = [&] (double v) { return warped ? (v - beatAtZero) * ppq : v * bpm / 60.0 * ppq; };
  1678. const auto channel = audioChannelFor (ctx, path, mixerTrack, mode, warped, fileBeats, beatsPitch, warp);
  1679. const auto loop = loopOverride != nullptr ? *loopOverride : loopOf (clip);
  1680. // not warped: the loop values are seconds [DATA: IsWarped=false clips]; the clip length is in beats either way
  1681. auto unwarpedLoop = loop;
  1682. if (! warped)
  1683. for (auto* v : { &unwarpedLoop.start, &unwarpedLoop.end, &unwarpedLoop.loopStart, &unwarpedLoop.loopEnd })
  1684. *v *= bpm / 60.0;
  1685. const auto passes = passesOf (warped ? loop : unwarpedLoop, length);
  1686. for (const auto& pass : passes)
  1687. {
  1688. Clip c;
  1689. c.kind = ClipKind::audio;
  1690. c.channel = channel;
  1691. c.track = row;
  1692. c.start = ticksOf (at + pass.at);
  1693. c.length = std::max<std::int64_t> (1, ticksOf (pass.to - pass.from));
  1694. const auto off = warped ? contentTicks (pass.from) : pass.from * ppq;
  1695. c.offset = (std::int64_t) std::llround (std::max (0.0, off));
  1696. c.offsetFraction = (float) (std::max (0.0, off) - (double) c.offset);
  1697. c.stretch = stretch;
  1698. c.gain = (float) clip.number ("SampleVolume", 1);
  1699. // Re-Pitch ignores the clip's transpose: the tempo alone sets the pitch [LIVE: +5 st on a Re-Pitch clip renders
  1700. // at the original pitch, 2026-11-06]
  1701. c.pitch = (warped && mode == 3) || beatsPitch != 0.0 ? 0.0f : (float) std::clamp (transpose, -12.0, 12.0);
  1702. c.muted = clip.boolean ("Disabled", false);
  1703. if (&pass == &passes.front())
  1704. c.fadeIn = std::clamp (ticksOf (clip.number ("Fades/FadeInLength", 0)), (std::int64_t) 0, c.length);
  1705. if (&pass == &passes.back())
  1706. c.fadeOut = std::clamp (ticksOf (clip.number ("Fades/FadeOutLength", 0)), (std::int64_t) 0, c.length);
  1707. (out != nullptr ? *out : ctx.song.playlist).push_back (c);
  1708. }
  1709. }
  1710. void addMidiClip (Ctx& ctx, const Element& clip, int row, int channel, double at, double length, std::vector<Clip>* out = nullptr,
  1711. const ClipLoop* loopOverride = nullptr)
  1712. {
  1713. if (length <= 0)
  1714. return;
  1715. Clip c;
  1716. c.kind = ClipKind::pattern;
  1717. c.pattern = patternFromMidiClip (ctx, clip, channel, length, loopOverride);
  1718. c.track = row;
  1719. c.start = ticksOf (at);
  1720. c.length = ticksOf (length);
  1721. c.muted = clip.boolean ("Disabled", false);
  1722. (out != nullptr ? *out : ctx.song.playlist).push_back (c);
  1723. }
  1724. // A clip's or scene's FollowAction block [DATA: section 5; numbers LIVE: REA_rodada181a.md, read in Live 12's Clip View]
  1725. ClipFollow followOf (const Element& f)
  1726. {
  1727. ClipFollow c;
  1728. c.enabled = f.boolean ("FollowActionEnabled", false);
  1729. c.a = (FollowKind) std::clamp ((int) f.number ("FollowActionA", 4), 0, 9);
  1730. c.b = (FollowKind) std::clamp ((int) f.number ("FollowActionB", 0), 0, 9); // [INFERRED] B uses A's numbers
  1731. c.chanceA = std::clamp ((int) std::lround (f.number ("FollowChanceA", 100)), 0, 100);
  1732. c.chanceB = std::clamp ((int) std::lround (f.number ("FollowChanceB", 0)), 0, 100);
  1733. // the jump target: Live shows the stored number itself, 1-based (5 shows "5", 0 an empty field) [LIVE, 181c];
  1734. // LYNX's jump row counts from 0. [INFERRED] the number counts scenes from the top, not clips of the group
  1735. c.jumpA = std::clamp ((int) f.number ("JumpIndexA", 1) - 1, 0, launcher::maxScenes - 1);
  1736. c.jumpB = std::clamp ((int) f.number ("JumpIndexB", 1) - 1, 0, launcher::maxScenes - 1);
  1737. c.linked = f.boolean ("IsLinked", true);
  1738. c.iterations = std::clamp ((int) std::lround (f.number ("LoopIterations", 1)), 1, 999);
  1739. c.ticks = std::max<std::int64_t> (1, ticksOf (f.number ("FollowTime", 4)));
  1740. return c;
  1741. }
  1742. // ---------------------------------------------------------------------------------------------------------------
  1743. // Automation
  1744. float mapValue (ValueMap m, double v)
  1745. {
  1746. switch (m)
  1747. {
  1748. case ValueMap::fader: return faderPosition ((float) std::clamp (v <= minusInfGain * 1.0001 ? 0.0 : v, 0.0, (double) maxFaderGain));
  1749. case ValueMap::pan: return (float) std::clamp ((v + 1.0) * 0.5, 0.0, 1.0);
  1750. case ValueMap::tempo: return std::clamp (valueFromTempo (v), 0.0f, 1.0f);
  1751. case ValueMap::plain: break;
  1752. }
  1753. return (float) std::clamp (v, 0.0, 1.0);
  1754. }
  1755. void addAutomation (Ctx& ctx, const Element& envelopes, const std::string& owner, int& automationRow)
  1756. {
  1757. for (const auto& env : envelopes.path ("Envelopes").children ("AutomationEnvelope"))
  1758. {
  1759. const auto id = env.path ("EnvelopeTarget/PointeeId").attr ("Value");
  1760. // the time signature and its changes along the Arrangement (round 190cg): EnumEvents holding the signature
  1761. // code, the first one "before the song" [DATA: every stored set has that one event, Value = Manual]; each later
  1762. // one becomes a time signature marker [INFERRED: Time in beats as in every other envelope]
  1763. if (! id.empty() && id == ctx.signatureTarget)
  1764. {
  1765. for (const auto& e : env.path ("Automation/Events").children())
  1766. {
  1767. int num = 4, den = 4;
  1768. const auto time = numberAttr (e, "Time");
  1769. if (e.name() != "EnumEvent" || time <= 0.0 || ! alsTimeSignature ((int) numberAttr (e, "Value"), num, den))
  1770. continue;
  1771. Marker m;
  1772. m.tick = ticksOf (time);
  1773. m.numerator = num;
  1774. m.denominator = den;
  1775. m.action = Marker::timeSignature;
  1776. ctx.song.addMarker (m);
  1777. }
  1778. continue;
  1779. }
  1780. const auto it = ctx.targets.find (id);
  1781. if (it == ctx.targets.end())
  1782. {
  1783. if (ctx.explained.count (id) == 0)
  1784. ctx.note (&FlpImportReport::unsupported, "Automation of a device parameter (" + owner + ")");
  1785. continue;
  1786. }
  1787. std::vector<std::pair<double, double>> events;
  1788. for (const auto& e : env.path ("Automation/Events").children())
  1789. if (e.name() == "FloatEvent")
  1790. events.push_back ({ numberAttr (e, "Time"), numberAttr (e, "Value") });
  1791. if (events.empty())
  1792. continue;
  1793. std::stable_sort (events.begin(), events.end(), [] (auto& a, auto& b) { return a.first < b.first; });
  1794. // the "before the song" point: the value at the start
  1795. for (auto& e : events)
  1796. if (e.first <= beforeSongTime + 1.0)
  1797. e.first = 0.0;
  1798. if (events.size() == 1)
  1799. continue; // a single value: the parameter's own setting already holds it
  1800. Automation a;
  1801. a.name = owner + " " + it->second.name;
  1802. a.target = it->second.target;
  1803. const auto first = std::max (0.0, events.front().first);
  1804. for (const auto& [t, v] : events)
  1805. a.points.push_back ({ ticksOf (std::max (0.0, t) - first), it->second.law ? std::clamp (it->second.law (v), 0.0f, 1.0f) : mapValue (it->second.map, v), 0.0f });
  1806. ctx.song.automations.push_back (std::move (a));
  1807. Clip c;
  1808. c.kind = ClipKind::automation;
  1809. c.automation = (int) ctx.song.automations.size() - 1;
  1810. c.track = automationRow++;
  1811. c.start = ticksOf (first);
  1812. c.length = std::max<std::int64_t> (ppq, ctx.song.automations.back().points.back().tick);
  1813. ctx.song.playlist.push_back (c);
  1814. }
  1815. }
  1816. void registerMixerTargets (Ctx& ctx, const Element& mixer, int insert, const std::string& name)
  1817. {
  1818. if (const auto id = targetId (mixer.child ("Volume")); ! id.empty())
  1819. ctx.targets[id] = { AutomationTarget { AutomationTargetKind::mixerVolume, insert, 0, 0 }, ValueMap::fader, "volume", {} };
  1820. if (const auto id = targetId (mixer.child ("Pan")); ! id.empty())
  1821. ctx.targets[id] = { AutomationTarget { AutomationTargetKind::mixerPan, insert, 0, 0 }, ValueMap::pan, "pan", {} };
  1822. (void) name;
  1823. }
  1824. // ---------------------------------------------------------------------------------------------------------------
  1825. // Session view → the clip grid (round 181c). Each track's ClipSlotList holds one ClipSlot per scene [DATA: section 5];
  1826. // launch settings use the numbers read in Live 12's Clip View [LIVE: REA_rodada181a.md]. A grid clip plays one pass of
  1827. // what Live loops: a looping clip becomes its loop region with the slot's Loop on, a one-shot its start…end span.
  1828. void sessionToGrid (Ctx& ctx, const Element& set, const std::vector<Element>& tracks, const std::vector<int>& rowOf,
  1829. const std::vector<int>& channelOf, const std::vector<int>& insertOf, const std::vector<Element>& scenes)
  1830. {
  1831. auto& song = ctx.song;
  1832. bool any = false;
  1833. for (std::size_t i = 0; i < tracks.size(); ++i)
  1834. {
  1835. const auto kind = tracks[i].name();
  1836. if (rowOf[i] < 0 || (kind != "MidiTrack" && kind != "AudioTrack"))
  1837. continue;
  1838. const auto list = tracks[i].path ("DeviceChain/MainSequencer/ClipSlotList").children ("ClipSlot");
  1839. for (std::size_t s = 0; s < list.size(); ++s)
  1840. {
  1841. if ((int) s >= launcher::maxScenes)
  1842. {
  1843. ctx.note (&FlpImportReport::unsupported, "Session scenes past LYNX's grid limit");
  1844. break;
  1845. }
  1846. bool placed = false;
  1847. for (const auto& clip : list[s].path ("ClipSlot/Value").children())
  1848. {
  1849. if (clip.name() != "MidiClip" && clip.name() != "AudioClip")
  1850. continue;
  1851. const auto own = loopOf (clip);
  1852. auto body = own;
  1853. if (own.on)
  1854. {
  1855. body.start = own.loopStart;
  1856. body.end = own.loopEnd;
  1857. if (std::abs (own.start - own.loopStart) > 1e-6)
  1858. ctx.note (&FlpImportReport::approximated, "Session clip whose start marker is inside its loop (it starts at the loop start)");
  1859. }
  1860. body.on = false; // one pass: the grid's Loop repeats the clip
  1861. auto length = body.end - body.start;
  1862. if (clip.name() == "AudioClip" && ! clip.boolean ("IsWarped", true))
  1863. length *= song.bpm / 60.0; // an unwarped clip's loop values are seconds [DATA]
  1864. if (length <= 1e-9)
  1865. continue;
  1866. std::vector<Clip> made;
  1867. if (clip.name() == "MidiClip" && channelOf[i] >= 0)
  1868. addMidiClip (ctx, clip, rowOf[i], channelOf[i], 0.0, length, &made, &body);
  1869. else if (clip.name() == "AudioClip")
  1870. addAudioClip (ctx, clip, rowOf[i], insertOf[i], 0.0, length, song.mixer[(std::size_t) insertOf[i]].name, &made, &body);
  1871. if (made.empty())
  1872. continue;
  1873. const auto id = launcher::setClip (song, rowOf[i], (int) s, made.front());
  1874. if (id < 0)
  1875. {
  1876. ctx.note (&FlpImportReport::unsupported, "Session clips past LYNX's grid limits");
  1877. continue;
  1878. }
  1879. auto& slot = song.clipGrid->slots[(std::size_t) id];
  1880. slot.name = clip.value ("Name");
  1881. slot.colour = alsColour ((int) clip.number ("Color", -1));
  1882. slot.mode = (LaunchMode) std::clamp ((int) clip.number ("LaunchMode", 0), 0, 3);
  1883. slot.quant = (LaunchQuant) std::clamp ((int) clip.number ("LaunchQuantisation", 0), 0, 14);
  1884. slot.legato = clip.boolean ("Legato", false);
  1885. slot.loop = own.on;
  1886. slot.follow = followOf (clip.child ("FollowAction"));
  1887. any = placed = true;
  1888. break; // one clip per slot
  1889. }
  1890. if (! placed && ! list[s].boolean ("HasStop", true))
  1891. {
  1892. launcher::ensureGrid (song);
  1893. launcher::setStopButton (song, rowOf[i], (int) s, false);
  1894. }
  1895. }
  1896. }
  1897. if (! any)
  1898. {
  1899. song.clipGrid.reset(); // only stop buttons, no clip: a set without Session clips adds no grid
  1900. return;
  1901. }
  1902. auto& grid = launcher::ensureGrid (song);
  1903. if (grid.scenes.size() < scenes.size())
  1904. grid.scenes.resize (std::min<std::size_t> (scenes.size(), (std::size_t) launcher::maxScenes));
  1905. for (std::size_t s = 0; s < scenes.size() && s < grid.scenes.size(); ++s)
  1906. {
  1907. auto& sc = grid.scenes[s];
  1908. sc.name = scenes[s].value ("Name");
  1909. sc.colour = alsColour ((int) scenes[s].number ("Color", -1));
  1910. if (scenes[s].boolean ("IsTempoEnabled", false))
  1911. sc.tempo = std::clamp (scenes[s].number ("Tempo", 120), 10.0, 999.0);
  1912. int n = 4, d = 4;
  1913. if (scenes[s].boolean ("IsTimeSignatureEnabled", false) && alsTimeSignature ((int) scenes[s].number ("TimeSignatureId", 201), n, d))
  1914. {
  1915. sc.beatsPerBar = n;
  1916. if (d != 4)
  1917. ctx.note (&FlpImportReport::approximated, "Scene time signatures other than n/4 (the numerator is kept)");
  1918. }
  1919. if (scenes[s].boolean ("FollowAction/FollowActionEnabled", false))
  1920. ctx.note (&FlpImportReport::unsupported, "Scene follow actions");
  1921. }
  1922. // the set-wide value has no Global entry: a clip's number is that + 1 [LIVE: 9 = 1/8 = clip 10]
  1923. grid.globalQuant = (LaunchQuant) std::clamp ((int) set.number ("GlobalQuantisation", 4) + 1, 1, 14);
  1924. }
  1925. } // namespace
  1926. // ---------------------------------------------------------------------------------------------------------------
  1927. bool alsTimeSignature (int code, int& numerator, int& denominator) noexcept
  1928. {
  1929. if (code < 0 || code > 494)
  1930. return false;
  1931. numerator = code % 99 + 1;
  1932. denominator = 1 << (code / 99);
  1933. return true;
  1934. }
  1935. int alsTimeSignatureCode (int numerator, int denominator) noexcept
  1936. {
  1937. int log = 0;
  1938. while ((1 << log) < denominator && log < 4)
  1939. ++log;
  1940. return std::clamp (numerator, 1, 99) - 1 + 99 * log;
  1941. }
  1942. std::array<std::uint8_t, 16> alsVst3ClassId (const std::array<std::int32_t, 4>& f) noexcept
  1943. {
  1944. // COM-compatible FUID memory layout (Windows): l1 little-endian, l2's halves swapped and little-endian, l3 and l4
  1945. // big-endian — the inverse of PluginHost's vst3NormalisedHash grouping
  1946. std::array<std::uint8_t, 16> d {};
  1947. const auto l1 = (std::uint32_t) f[0], l2 = (std::uint32_t) f[1], l3 = (std::uint32_t) f[2], l4 = (std::uint32_t) f[3];
  1948. d[0] = (std::uint8_t) l1; d[1] = (std::uint8_t) (l1 >> 8); d[2] = (std::uint8_t) (l1 >> 16); d[3] = (std::uint8_t) (l1 >> 24);
  1949. d[4] = (std::uint8_t) (l2 >> 16); d[5] = (std::uint8_t) (l2 >> 24); d[6] = (std::uint8_t) l2; d[7] = (std::uint8_t) (l2 >> 8);
  1950. for (int k = 0; k < 4; ++k)
  1951. {
  1952. d[(std::size_t) (8 + k)] = (std::uint8_t) (l3 >> (24 - 8 * k));
  1953. d[(std::size_t) (12 + k)] = (std::uint8_t) (l4 >> (24 - 8 * k));
  1954. }
  1955. return d;
  1956. }
  1957. std::array<std::int32_t, 4> alsVst3Fields (const std::array<std::uint8_t, 16>& d) noexcept
  1958. {
  1959. const auto make = [] (std::uint32_t a, std::uint32_t b, std::uint32_t c, std::uint32_t e) { return (a << 24) | (b << 16) | (c << 8) | e; };
  1960. return { (std::int32_t) make (d[3], d[2], d[1], d[0]), (std::int32_t) make (d[5], d[4], d[7], d[6]),
  1961. (std::int32_t) make (d[8], d[9], d[10], d[11]), (std::int32_t) make (d[12], d[13], d[14], d[15]) };
  1962. }
  1963. std::vector<std::uint8_t> alsHexDecode (const std::string& text)
  1964. {
  1965. std::vector<std::uint8_t> out;
  1966. out.reserve (text.size() / 2);
  1967. int hi = -1;
  1968. for (const auto c : text)
  1969. {
  1970. int v;
  1971. if (c >= '0' && c <= '9') v = c - '0';
  1972. else if (c >= 'a' && c <= 'f') v = c - 'a' + 10;
  1973. else if (c >= 'A' && c <= 'F') v = c - 'A' + 10;
  1974. else if (c == ' ' || c == '\t' || c == '\n' || c == '\r') continue;
  1975. else return {};
  1976. if (hi < 0)
  1977. hi = v;
  1978. else
  1979. {
  1980. out.push_back ((std::uint8_t) (hi * 16 + v));
  1981. hi = -1;
  1982. }
  1983. }
  1984. return hi < 0 ? out : std::vector<std::uint8_t> {};
  1985. }
  1986. std::string alsHexEncode (const std::vector<std::uint8_t>& bytes, std::size_t lineBytes)
  1987. {
  1988. static const char* digits = "0123456789ABCDEF";
  1989. std::string out;
  1990. out.reserve (bytes.size() * 2 + bytes.size() / std::max<std::size_t> (1, lineBytes) * 2);
  1991. for (std::size_t i = 0; i < bytes.size(); ++i)
  1992. {
  1993. if (lineBytes > 0 && i > 0 && i % lineBytes == 0)
  1994. out += '\n';
  1995. out += digits[bytes[i] >> 4];
  1996. out += digits[bytes[i] & 15];
  1997. }
  1998. return out;
  1999. }
  2000. // LYNX's own 70-colour approximation of a 14 × 5 hue grid (columns: hues, the last one greys; rows: from light to
  2001. // dark). Not Live's colour values: only the hue order, so imported tracks keep their colour families.
  2002. std::uint32_t alsColour (int index) noexcept
  2003. {
  2004. if (index < 0 || index >= 70)
  2005. return 0;
  2006. const auto col = index % 14, row = index / 14;
  2007. static const float light[5] = { 0.72f, 0.60f, 0.48f, 0.38f, 0.28f };
  2008. static const float sat[5] = { 0.75f, 0.85f, 0.70f, 0.55f, 0.45f };
  2009. const auto l = light[row];
  2010. const auto s = col == 13 ? 0.0f : sat[row];
  2011. const auto h = (float) col / 13.0f * 330.0f; // red → magenta
  2012. const auto c = (1.0f - std::abs (2.0f * l - 1.0f)) * s;
  2013. const auto x = c * (1.0f - std::abs (std::fmod (h / 60.0f, 2.0f) - 1.0f));
  2014. const auto m = l - c / 2.0f;
  2015. float r = 0, g = 0, b = 0;
  2016. if (h < 60) { r = c; g = x; }
  2017. else if (h < 120) { r = x; g = c; }
  2018. else if (h < 180) { g = c; b = x; }
  2019. else if (h < 240) { g = x; b = c; }
  2020. else if (h < 300) { r = x; b = c; }
  2021. else { r = c; b = x; }
  2022. const auto to8 = [m] (float v) { return (std::uint32_t) std::clamp ((int) std::lround ((v + m) * 255.0f), 0, 255); };
  2023. return 0xFF000000u | (to8 (r) << 16) | (to8 (g) << 8) | to8 (b);
  2024. }
  2025. int alsColourIndex (std::uint32_t argb) noexcept
  2026. {
  2027. if (argb == 0)
  2028. return -1;
  2029. auto best = 0;
  2030. auto bestD = 1 << 30;
  2031. for (int i = 0; i < 70; ++i)
  2032. {
  2033. const auto c = alsColour (i);
  2034. const auto dr = (int) ((c >> 16) & 255) - (int) ((argb >> 16) & 255), dg = (int) ((c >> 8) & 255) - (int) ((argb >> 8) & 255),
  2035. db = (int) (c & 255) - (int) (argb & 255);
  2036. if (const auto d = dr * dr + dg * dg + db * db; d < bestD)
  2037. {
  2038. bestD = d;
  2039. best = i;
  2040. }
  2041. }
  2042. return best;
  2043. }
  2044. bool isAlsData (const std::uint8_t* data, std::size_t size)
  2045. {
  2046. std::string head;
  2047. if (gzip::isGzip (data, size))
  2048. {
  2049. // only the start is needed: inflate a bounded prefix
  2050. const auto all = gzip::decompress (data, size);
  2051. if (! all)
  2052. return false;
  2053. head.assign (all->begin(), all->begin() + (std::ptrdiff_t) std::min<std::size_t> (all->size(), 512));
  2054. }
  2055. else
  2056. head.assign (data, data + std::min<std::size_t> (size, 512));
  2057. return head.find ("<Ableton") != std::string::npos;
  2058. }
  2059. namespace
  2060. {
  2061. bool parseSet (const std::vector<std::uint8_t>& bytes, xml::Document& doc, std::string* error)
  2062. {
  2063. std::string text;
  2064. if (gzip::isGzip (bytes.data(), bytes.size()))
  2065. {
  2066. auto raw = gzip::decompress (bytes.data(), bytes.size());
  2067. if (! raw)
  2068. {
  2069. if (error != nullptr)
  2070. *error = "the set is damaged (it could not be decompressed)";
  2071. return false;
  2072. }
  2073. text.assign (raw->begin(), raw->end());
  2074. }
  2075. else
  2076. text.assign (bytes.begin(), bytes.end());
  2077. std::string why;
  2078. if (! doc.parse (std::move (text), &why))
  2079. {
  2080. if (error != nullptr)
  2081. *error = "the set is damaged (" + why + ")";
  2082. return false;
  2083. }
  2084. return true;
  2085. }
  2086. void collectPlugins (const Element& e, std::vector<FlpPluginUse>& out)
  2087. {
  2088. for (const auto& c : e.children())
  2089. {
  2090. if (c.name() == "PluginDevice")
  2091. {
  2092. if (auto p = pluginOf (c))
  2093. {
  2094. const auto desc = c.child ("PluginDesc");
  2095. // VST3 DeviceType 1 = instrument; VST2 Category 2 = kPlugCategSynth [LIVE: 2 / 1 for an effect]
  2096. const auto instrument = (int) desc.number ("Vst3PluginInfo/DeviceType", 0) == 1 || (int) desc.number ("VstPluginInfo/Category", 0) == 2;
  2097. out.push_back ({ std::move (*p), instrument });
  2098. }
  2099. continue;
  2100. }
  2101. collectPlugins (c, out);
  2102. }
  2103. }
  2104. } // namespace
  2105. std::optional<Song> importAls (const std::vector<std::uint8_t>& bytes, const AlsImportOptions& options, std::string* error)
  2106. {
  2107. xml::Document doc;
  2108. if (! parseSet (bytes, doc, error))
  2109. return std::nullopt;
  2110. return importAlsXml (doc, options, error);
  2111. }
  2112. std::vector<FlpPluginUse> alsForeignPlugins (const std::vector<std::uint8_t>& bytes)
  2113. {
  2114. std::vector<FlpPluginUse> out;
  2115. xml::Document doc;
  2116. if (parseSet (bytes, doc, nullptr))
  2117. collectPlugins (doc.root(), out);
  2118. return out;
  2119. }
  2120. std::optional<Song> importAlsXml (const xml::Document& doc, const AlsImportOptions& options, std::string* error)
  2121. {
  2122. const auto root = doc.root();
  2123. const auto fail = [error] (const char* why) -> std::optional<Song> {
  2124. if (error != nullptr)
  2125. *error = why;
  2126. return std::nullopt;
  2127. };
  2128. if (root.name() != "Ableton" || ! root.child ("LiveSet"))
  2129. return fail ("not a Live set");
  2130. // Live 8 and later write MajorVersion 4 / 5; older sets are not XML at all
  2131. if (const auto major = intOf (root.attr ("MajorVersion"), 0); major < 4)
  2132. return fail ("this Live set version is not supported");
  2133. Ctx ctx (options);
  2134. auto& song = ctx.song;
  2135. song.channels.clear();
  2136. song.patterns.clear();
  2137. song.playlist.clear();
  2138. song.mixer = Song::defaultMixer (0);
  2139. song.mode = PlayMode::song;
  2140. song.arrangements = { Arrangement { "Arrangement", {}, 0, 0, {} } };
  2141. const auto set = root.child ("LiveSet");
  2142. auto main = set.child ("MainTrack"); // Live 12
  2143. if (! main)
  2144. main = set.child ("MasterTrack"); // Live 11 and older [BIN: MasterTrack legacy paths]
  2145. const auto mainMixer = main.path ("DeviceChain/Mixer");
  2146. song.bpm = std::clamp (mainMixer.number ("Tempo/Manual", 120), minTempo, maxTempo);
  2147. if (const auto id = targetId (mainMixer.child ("Tempo")); ! id.empty())
  2148. ctx.targets[id] = { AutomationTarget { AutomationTargetKind::tempo, 0, 0, 0 }, ValueMap::tempo, "tempo", {} };
  2149. ctx.signatureTarget = targetId (mainMixer.child ("TimeSignature"));
  2150. // the tempo envelope's shown range [DATA: Mixer/TempoAutomationViewBottom / Top, 60 and 200 in every stored set]
  2151. if (const auto low = mainMixer.number ("TempoAutomationViewBottom", 0), high = mainMixer.number ("TempoAutomationViewTop", 0); high > low && low > 0)
  2152. {
  2153. song.tempoViewLow = std::clamp (low, minTempo, maxTempo);
  2154. song.tempoViewHigh = std::clamp (high, song.tempoViewLow + 1.0, maxTempo);
  2155. }
  2156. int num = 4, den = 4;
  2157. alsTimeSignature ((int) mainMixer.number ("TimeSignature/Manual", 201), num, den);
  2158. if (den == 4)
  2159. song.beatsPerBar = num;
  2160. else
  2161. {
  2162. Marker m;
  2163. m.tick = 0;
  2164. m.numerator = num;
  2165. m.denominator = den;
  2166. m.action = Marker::timeSignature;
  2167. song.addMarker (m);
  2168. }
  2169. song.mixer[0].volume = mapValue (ValueMap::fader, mainMixer.number ("Volume/Manual", 1));
  2170. song.mixer[0].pan = (float) mainMixer.number ("Pan/Manual", 0);
  2171. registerMixerTargets (ctx, mainMixer, 0, "Main");
  2172. // tracks: one insert each (returns too), in order
  2173. const auto tracks = set.child ("Tracks").children();
  2174. // (round 190ed) the parameters an arrangement envelope moves
  2175. for (const auto& owner : { main.child ("AutomationEnvelopes") })
  2176. for (const auto& env : owner.path ("Envelopes").children ("AutomationEnvelope"))
  2177. ctx.automated.insert (env.path ("EnvelopeTarget/PointeeId").attr ("Value"));
  2178. for (const auto& t : tracks)
  2179. for (const auto& env : t.path ("AutomationEnvelopes/Envelopes").children ("AutomationEnvelope"))
  2180. ctx.automated.insert (env.path ("EnvelopeTarget/PointeeId").attr ("Value"));
  2181. std::vector<int> insertOf (tracks.size(), 0), rowOf (tracks.size(), -1);
  2182. std::map<std::string, int> groupInsert, groupRow;
  2183. std::vector<int> returns;
  2184. for (std::size_t i = 0; i < tracks.size(); ++i)
  2185. {
  2186. if ((int) song.mixer.size() >= maxMixerTracks)
  2187. break;
  2188. MixerTrack m;
  2189. m.name = trackName (tracks[i]);
  2190. m.colour = alsColour ((int) tracks[i].number ("Color", -1));
  2191. song.mixer.push_back (std::move (m));
  2192. insertOf[i] = (int) song.mixer.size() - 1;
  2193. const auto kind = tracks[i].name();
  2194. if (kind == "ReturnTrack")
  2195. returns.push_back (insertOf[i]);
  2196. else
  2197. {
  2198. PlaylistTrack row;
  2199. row.name = song.mixer.back().name;
  2200. row.colour = song.mixer.back().colour;
  2201. row.grouped = tracks[i].value ("TrackGroupId", "-1") != "-1";
  2202. row.mixerTrack = insertOf[i];
  2203. row.mode = kind == "AudioTrack" ? PlaylistTrackMode::audio : PlaylistTrackMode::unassigned;
  2204. song.playlistTracks.push_back (row);
  2205. rowOf[i] = (int) song.playlistTracks.size() - 1;
  2206. if (kind == "GroupTrack")
  2207. {
  2208. groupInsert[tracks[i].attr ("Id")] = insertOf[i];
  2209. song.playlistTracks.back().collapsed = ! tracks[i].boolean ("TrackUnfolded", true);
  2210. }
  2211. }
  2212. }
  2213. // mixer settings and routing
  2214. for (std::size_t i = 0; i < tracks.size(); ++i)
  2215. {
  2216. if (insertOf[i] == 0)
  2217. continue;
  2218. const auto& t = tracks[i];
  2219. auto& m = song.mixer[(std::size_t) insertOf[i]];
  2220. const auto mixer = t.path ("DeviceChain/Mixer");
  2221. m.volume = mapValue (ValueMap::fader, mixer.number ("Volume/Manual", 1));
  2222. m.pan = (float) std::clamp (mixer.number ("Pan/Manual", 0), -1.0, 1.0);
  2223. m.muted = ! mixer.boolean ("Speaker/Manual", true);
  2224. m.solo = mixer.boolean ("SoloSink", false);
  2225. registerMixerTargets (ctx, mixer, insertOf[i], m.name);
  2226. const auto out = t.value ("DeviceChain/AudioOutputRouting/Target", "AudioOut/Main");
  2227. const auto group = t.value ("TrackGroupId", "-1");
  2228. if (out == "AudioOut/GroupTrack" && groupInsert.count (group))
  2229. {
  2230. m.toMaster = false;
  2231. m.sends.push_back ({ groupInsert[group], 1.0f });
  2232. }
  2233. else if (out == "AudioOut/None")
  2234. m.toMaster = false;
  2235. else if (out.rfind ("AudioOut/External", 0) == 0)
  2236. ; // a hardware output: LYNX plays it through the Master (the device's outputs are chosen in LYNX)
  2237. const auto sends = mixer.path ("Sends").children ("TrackSendHolder");
  2238. for (std::size_t k = 0; k < sends.size() && k < returns.size(); ++k)
  2239. {
  2240. if (returns[k] == insertOf[i])
  2241. continue;
  2242. const auto level = sends[k].number ("Send/Manual", 0);
  2243. if (const auto id = targetId (sends[k].child ("Send")); ! id.empty())
  2244. ctx.targets[id] = { AutomationTarget { AutomationTargetKind::mixerSend, insertOf[i], returns[k], 0 }, ValueMap::fader, "send", {} };
  2245. if (level > minusInfGain * 1.0001 && sends[k].boolean ("EnabledByUser", true))
  2246. m.sends.push_back ({ returns[k], (float) std::min (level, (double) maxFaderGain) });
  2247. }
  2248. }
  2249. // Live's Pre / Post toggle of each return (LiveSet/SendsPre, one SendPreBool per return, in order): "Pre" taps every
  2250. // track's send to that return before the track's mixer, which is LYNX's pre-fader send (round 190aq)
  2251. {
  2252. const auto toggles = set.child ("SendsPre").children ("SendPreBool");
  2253. for (std::size_t k = 0; k < toggles.size() && k < returns.size(); ++k)
  2254. if (toggles[k].attr ("Value") == "true")
  2255. for (auto& m : song.mixer)
  2256. for (auto& send : m.sends)
  2257. if (send.target == returns[k])
  2258. send.pre = true;
  2259. }
  2260. // channels, devices and arrangement clips
  2261. std::vector<int> channelOf (tracks.size(), -1);
  2262. std::vector<std::vector<DrumPad>> drumPads (tracks.size());
  2263. for (std::size_t i = 0; i < tracks.size(); ++i)
  2264. if (tracks[i].hasAttr ("Id"))
  2265. ctx.insertOfTrack[intOf (tracks[i].attr ("Id"), -1)] = insertOf[i];
  2266. for (std::size_t i = 0; i < tracks.size(); ++i)
  2267. {
  2268. const auto& t = tracks[i];
  2269. const auto kind = t.name();
  2270. const auto devices = t.path ("DeviceChain/DeviceChain/Devices").children();
  2271. auto& insert = song.mixer[(std::size_t) insertOf[i]];
  2272. if (kind == "MidiTrack")
  2273. {
  2274. ChannelDef c;
  2275. c.name = insert.name;
  2276. c.colour = insert.colour;
  2277. c.volume = 1.0f;
  2278. c.mixerTrack = insertOf[i];
  2279. std::size_t firstEffect = 0;
  2280. std::vector<alsdev::NoteEffect> noteEffects; // (round 190cf)
  2281. for (std::size_t d = 0; d < devices.size(); ++d)
  2282. {
  2283. const auto tag = devices[d].name();
  2284. if (isMidiEffect (tag))
  2285. {
  2286. if (! midiEffectFrom (ctx, devices[d], c, noteEffects))
  2287. ctx.note (&FlpImportReport::unsupported, deviceName (devices[d]));
  2288. firstEffect = d + 1;
  2289. continue;
  2290. }
  2291. if (isInstrumentDevice (tag) || tag == "PluginDevice")
  2292. {
  2293. // (round 190cf) an Instrument Rack with one chain: the MIDI effects at the head of that chain sit in
  2294. // front of the instrument just as the track's own do
  2295. ctx.skipLeadingMidi = 0;
  2296. if (const auto branches = devices[d].path ("Branches").children(); tag == "InstrumentGroupDevice" && branches.size() == 1)
  2297. for (const auto& inner : branches.front().path ("DeviceChain/MidiToAudioDeviceChain/Devices").children())
  2298. {
  2299. if (! isMidiEffect (inner.name()) || ! midiEffectFrom (ctx, inner, c, noteEffects))
  2300. break;
  2301. ++ctx.skipLeadingMidi;
  2302. }
  2303. ctx.pendingKeyShift = 0;
  2304. instrumentFrom (ctx, devices[d], c, &drumPads[i]);
  2305. ctx.skipLeadingMidi = 0;
  2306. firstEffect = d + 1;
  2307. }
  2308. break;
  2309. }
  2310. song.channels.push_back (std::move (c));
  2311. channelOf[i] = (int) song.channels.size() - 1;
  2312. // (round 190ed) the envelopes on the channel's instrument (a plugin's parameters, an Instrument Rack's macros,
  2313. // a Simpler's filter)
  2314. for (auto& [id, target] : ctx.channelTargets)
  2315. {
  2316. target.target.index = channelOf[i];
  2317. ctx.targets[id] = std::move (target);
  2318. }
  2319. ctx.channelTargets.clear();
  2320. if (! noteEffects.empty())
  2321. ctx.noteEffects[channelOf[i]] = std::move (noteEffects);
  2322. if (ctx.pendingKeyShift != 0)
  2323. ctx.keyShift[channelOf[i]] = ctx.pendingKeyShift;
  2324. ctx.pendingKeyShift = 0;
  2325. effectsFrom (ctx, { devices.begin() + (std::ptrdiff_t) firstEffect, devices.end() }, insert);
  2326. song.playlistTracks[(std::size_t) rowOf[i]].mode = PlaylistTrackMode::instrument;
  2327. song.playlistTracks[(std::size_t) rowOf[i]].channel = channelOf[i];
  2328. for (const auto& clip : t.path ("DeviceChain/MainSequencer/ClipTimeable/ArrangerAutomation/Events").children ("MidiClip"))
  2329. {
  2330. const auto start = clip.number ("CurrentStart", numberAttr (clip, "Time"));
  2331. addMidiClip (ctx, clip, rowOf[i], channelOf[i], start, clip.number ("CurrentEnd", start) - start);
  2332. }
  2333. }
  2334. else
  2335. {
  2336. effectsFrom (ctx, devices, insert);
  2337. if (kind == "AudioTrack")
  2338. for (const auto& clip : t.path ("DeviceChain/MainSequencer/Sample/ArrangerAutomation/Events").children ("AudioClip"))
  2339. {
  2340. const auto start = clip.number ("CurrentStart", numberAttr (clip, "Time"));
  2341. addAudioClip (ctx, clip, rowOf[i], insertOf[i], start, clip.number ("CurrentEnd", start) - start, insert.name);
  2342. }
  2343. }
  2344. if (! t.path ("TakeLanes/TakeLanes").children ("TakeLane").empty())
  2345. ctx.note (&FlpImportReport::unsupported, "Take lanes (only the main lane is kept)");
  2346. }
  2347. finishLinks (ctx); // (round 190ed)
  2348. // Session clips: in the clip grid (round 181c, the default: the user's choice of 2026-11-08), or on the Playlist
  2349. // after the arrangement, one section per scene (an option; the default before)
  2350. const auto scenes = set.child ("Scenes").children ("Scene");
  2351. if (options.sessionOnPlaylist)
  2352. {
  2353. std::int64_t end = 0;
  2354. for (const auto& c : song.playlist)
  2355. end = std::max (end, c.end());
  2356. const auto bar = den == 4 ? (std::int64_t) song.beatsPerBar * ppq : (std::int64_t) num * ppq * 4 / den;
  2357. const auto roundUp = [bar] (std::int64_t t) { return bar > 0 ? (t + bar - 1) / bar * bar : t; };
  2358. auto cursor = roundUp (end);
  2359. for (std::size_t s = 0; s < std::max<std::size_t> (scenes.size(), 1); ++s)
  2360. {
  2361. double longest = 0;
  2362. struct Slot
  2363. {
  2364. std::size_t track;
  2365. Element clip;
  2366. };
  2367. std::vector<Slot> slots;
  2368. for (std::size_t i = 0; i < tracks.size(); ++i)
  2369. {
  2370. const auto list = tracks[i].path ("DeviceChain/MainSequencer/ClipSlotList").children ("ClipSlot");
  2371. if (s >= list.size())
  2372. continue;
  2373. const auto value = list[s].path ("ClipSlot/Value");
  2374. for (const auto& clip : value.children())
  2375. if (clip.name() == "MidiClip" || clip.name() == "AudioClip")
  2376. {
  2377. slots.push_back ({ i, clip });
  2378. longest = std::max (longest, clip.number ("CurrentEnd", 0) - clip.number ("CurrentStart", 0));
  2379. }
  2380. }
  2381. if (slots.empty())
  2382. continue;
  2383. const auto at = (double) cursor / ppq;
  2384. for (const auto& [i, clip] : slots)
  2385. {
  2386. const auto length = clip.number ("CurrentEnd", 0) - clip.number ("CurrentStart", 0);
  2387. if (clip.name() == "MidiClip" && channelOf[i] >= 0)
  2388. addMidiClip (ctx, clip, rowOf[i], channelOf[i], at, length);
  2389. else if (clip.name() == "AudioClip" && rowOf[i] >= 0)
  2390. addAudioClip (ctx, clip, rowOf[i], insertOf[i], at, length, song.mixer[(std::size_t) insertOf[i]].name);
  2391. }
  2392. Marker m;
  2393. m.tick = cursor;
  2394. m.name = s < scenes.size() ? scenes[s].value ("Name") : std::string();
  2395. if (m.name.empty())
  2396. m.name = "Scene " + std::to_string (s + 1);
  2397. song.addMarker (m);
  2398. cursor = roundUp (cursor + std::max<std::int64_t> (bar, ticksOf (longest)));
  2399. ctx.note (&FlpImportReport::approximated, "Session clips (placed after the arrangement, one section per scene)");
  2400. }
  2401. }
  2402. else
  2403. sessionToGrid (ctx, set, tracks, rowOf, channelOf, insertOf, scenes);
  2404. // (round 190bq) a Simpler in Slice mode: Live's first slice plays on C1, LYNX's on key 60 — its notes move up
  2405. for (const auto& [channel, shift] : ctx.keyShift)
  2406. for (auto& pattern : song.patterns)
  2407. for (auto& n : pattern.notes)
  2408. if (n.channel == channel)
  2409. n.key = std::clamp (n.key + shift, 0, 127);
  2410. // (round 190cf) Live's MIDI effects that LYNX keeps as notes: each note of the channel through the chain, in order
  2411. for (const auto& [channel, effects] : ctx.noteEffects)
  2412. for (auto& pattern : song.patterns)
  2413. {
  2414. std::vector<Note> made;
  2415. for (const auto& n : pattern.notes)
  2416. {
  2417. if (n.channel != channel)
  2418. {
  2419. made.push_back (n);
  2420. continue;
  2421. }
  2422. const auto lengthBeats = (double) n.length / (double) ppq;
  2423. std::vector<alsdev::NoteEdit> edits { { n.key, n.velocity, lengthBeats } };
  2424. for (const auto& effect : effects)
  2425. {
  2426. std::vector<alsdev::NoteEdit> next;
  2427. for (const auto& e : edits)
  2428. for (const auto& o : alsdev::applyNoteEffect (effect, e))
  2429. next.push_back (o);
  2430. edits = std::move (next);
  2431. }
  2432. for (const auto& e : edits)
  2433. {
  2434. auto note = n;
  2435. note.key = std::clamp (e.key, 0, 127);
  2436. note.velocity = e.velocity;
  2437. if (e.lengthBeats != lengthBeats)
  2438. note.length = std::max<std::int64_t> (1, ticksOf (e.lengthBeats));
  2439. made.push_back (note);
  2440. }
  2441. }
  2442. pattern.notes = std::move (made);
  2443. pattern.sortNotes();
  2444. }
  2445. // drum racks: one sampler channel per pad (as an FL drum sampler); later channels shift, so from the last one
  2446. for (std::size_t i = tracks.size(); i-- > 0;)
  2447. if (channelOf[i] >= 0 && ! drumPads[i].empty())
  2448. splitDrumChannel (song, channelOf[i], drumPads[i]);
  2449. // locators
  2450. for (const auto& loc : set.path ("Locators/Locators").children ("Locator"))
  2451. {
  2452. Marker m;
  2453. m.tick = ticksOf (std::max (0.0, loc.number ("Time", 0)));
  2454. m.name = loc.value ("Name");
  2455. song.addMarker (m);
  2456. }
  2457. // the arrangement loop
  2458. // (round 190cg: with the Loop switch off the brace keeps its place [DATA: LoopOn false with LoopStart / LoopLength
  2459. // in every stored set]; LYNX keeps the range too, switched off)
  2460. if (const auto tr = set.child ("Transport"); tr.number ("LoopLength", 0) > 0)
  2461. {
  2462. song.loopStart = ticksOf (std::max (0.0, tr.number ("LoopStart", 0)));
  2463. song.loopEnd = song.loopStart + ticksOf (tr.number ("LoopLength", 0));
  2464. song.loopOff = ! tr.boolean ("LoopOn", false);
  2465. }
  2466. // automation (rows under the tracks)
  2467. int automationRow = (int) song.playlistTracks.size();
  2468. addAutomation (ctx, main.child ("AutomationEnvelopes"), "Main", automationRow);
  2469. for (std::size_t i = 0; i < tracks.size(); ++i)
  2470. addAutomation (ctx, tracks[i].child ("AutomationEnvelopes"), song.mixer[(std::size_t) insertOf[i]].name, automationRow);
  2471. std::stable_sort (song.playlist.begin(), song.playlist.end(), [] (const Clip& a, const Clip& b) { return a.start < b.start; });
  2472. if (song.patterns.empty())
  2473. {
  2474. Pattern first;
  2475. first.name = "Pattern 1";
  2476. song.patterns.push_back (std::move (first));
  2477. }
  2478. song.currentPattern = 0;
  2479. // Live's Scale Mode → the project key (round 190o): the set's own scale when it is on (Live 12), else the scale of
  2480. // the first clip that has one on (Live 11 has clip scales only). LYNX has one key per project.
  2481. if (set.boolean ("InKey", false))
  2482. projectkey::set (song, liveScaleOf (set));
  2483. else if (ctx.clipKeySeen)
  2484. projectkey::set (song, ctx.clipKey);
  2485. return std::move (ctx.song);
  2486. }
  2487. } // namespace lynx