4
0

AlsImport.cpp 96 KB

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